Using Maxuino to read from an ultrasonic sensor


    Jan 11 2018 | 4:54 am
    Hey all,
    I'm working with max, an arduino uno (loaded with standard firmata) with the maxuino object pretty happily to get two motors working for a robotics project, but I need to connect up an ulatrasonic sensor too. The practical connecting seems pretty easy: UCC to 5v
    Trig to PWM pin (digital)
    Echo to Normal (digital)
    Gnd to Ground But I can't seem to find anything about how to write the code to actually view the data. From what I understand I'll need to trig the sensor, and read the echo, but I'm struggling to find any code to help. Anyone have a basic patch they could share?

    • Jan 11 2018 | 7:58 am
      http://howtomechatronics.com/tutorials/arduino/ultrasonic-sensor-hc-sr04/
    • Jan 11 2018 | 10:13 am
      I found this, and the theory was useful. However their process works by loading up a different script into the arduino, and currently mine is loaded with standard firmata in order to use the Maxuino object. I also no nothing about arduino programming at this point... :) I assume that the Maxuino object can read the pins that the sensor is connected to, I just don't know how, or what I need to do in order to get it to send that 10 us trigger.
    • Jan 11 2018 | 10:28 am
      Honestly, using maxuino is a mistake in first place. If You post exactly what all You need from Arduino in Your project, I will help You with it. But - forget maxuino.
    • Jan 11 2018 | 8:36 pm
      Can you elaborate more on why using Maxuino is a mistake in the first place? Any help with Arduino would be greatly appreciated.
      It's been a journey to get this far into actually getting to the motors to work, so Maxuino seemed to make things easier from a basic level. But Arduino is the part that I have no idea about, so I was contemplating learning that over the next 12 months, but I need to finish this project first. I have a tank base with two motors that I need to control, a devastator tank ( https://www.dfrobot.com/product-1219.html ). I also need an ultrasonic sensor so that I can stop it from crashing into things, as it will run autonomously. So all I need the arduino to interface with are the two motors, and the ultrasonic sensor. As long as I can send information to the motors, and read the information from the sensor, and get those into Max, the rest should be a lot easier for me!
    • Jan 12 2018 | 8:14 am
      The reason I dislike maxuino approach is that it does keep You from learning Arduino basics. And that becomes a problem as soon as one needs something that is not covered with maxuino. Sending pulse of that short period over serial is not reliably possible, because it is serial communication. You could send a message to arduino to do it for You, but than again - You need to program it in the arduino. There is a good example on dfrobot that can be used on arduino: https://www.dfrobot.com/wiki/index.php/Devastator_Tank_Mobile_Platform_SKU:ROB0112
      Look at sample code, it has all it needs to control it from Max. Which Arduino board do You use ? One should check if PWM is supported on pins which are selected in sample code. Basicly each motor needs direction switch, which is simple Low - High, and 0 -255 PWM for speed. But please post here exact and detailed infos of the project. And I don't understand why You need to control it from Max if it is going to run autonomously ? So again detailed info on the project, who should control the motors, do You need scalable speed, or just fixed speed etc etc I will be glad to help You.
    • Jan 12 2018 | 12:35 pm
      and You probably need 2 ultrasonic sensors, one at front and another one at back. So to simplify things - one has to control 2 motors with direction and speed, and read distance in front and back to either stop the roboter or send it to oposite direction if it gets closer than xx cm to whatever objects. All that needs just 7 pins, 4 for motor control, and 3 for 2 Sensors, You can trigger both sensors from same pin and read 2 echos back. I can write arduino code which triggers the sensors, reports the distance in cm for front & back via serial, and listens for motor control coming from Max. But to do so, I need to know how do You want to drive that Tank. Simple forward, backward, left, right, stop with predefined speed, or all controlable in real time with something like joystick...
    • Jan 13 2018 | 10:16 am
      @Source Audio: Thanks for clarifying, I felt that would be the issue with Maxuino, in that it works at a basic level but that's it. Given some other projects I'm working on, I've just ordered a copy of Arduino for Dummies (based on my research it has max / msp examples in it), and will commit to learning that over the next month or so. In the meantime, some help with Arduino Code would be amazing. I've done some programming, so the code that you mention does make sense, I just lack the vocabulary to instigate anything more complicated. To answer your questions, the tank really only has to move forwards, so only one sensor is needed. The plan is for it to move in a single direction, until it reaches an object, then stop. It would then rotate a random amount of degrees (one motor running forward, one backward), and then repeat. In terms of why in regards to max/msp, the tank has a mounted speaker, and I'm using max/msp to run the audio side of things. Movement and sound will be synchronous with other parts of the project, so I really need it to run max/msp so that I can develop it further. So all the arduino needs to do is control those two motors, and one sensor. As for the speed of the tank itself I'm not sure, but I assume I can vary this from max? If you could help me in coding the arduino (I'm using an arduino uno), and a basic max patch that shows how to send the information there, that would be amazing. It would also help me learn a lot too!
    • Jan 13 2018 | 1:32 pm
      Ok, that's some more infos, but not as detailed as I wished. The thing is - depending on what all Arduino has to do, or in what extent it would have to comunicate with max, I would do it one or another way. But let's get going. I will make first sketch that would allow You to control 2 motors from Max, having per motor one direction toggle and speed 0 -255. That will be sent to Arduino as String of 4 Values with prepended "M" to make sure that only that values get routed to motor control. And 1 button to stop the Tank. That would send "S" to Arduino. Arduino Pins for Motors: MOTOR 1 : D2 Direction, D3 PWM Speed MOTOR 2 : D4 Direction , D5 PWM Speed --------------------------------- The Ultrasonic Sensor has to be adjusted to work properly. The main thing is to define range of operation, like maximum 50 cm. That helps to avoid waiting for ecoes if no object is in range. Depending on speed of Tank, and if You don't want it to really bump into any object,it could be 5 - 10 cm. You will have to adjust that. Sensor will send "CLOSE" to max when Tank gets closer than set distance to any object. Than You can trigger Stop and Turn ->Continue Values to motors. Doing randomising for turning will be easier for You if You do it in Max, right ? --------------------------------
      I would suggest You test Motor Control and Sensor separately, and than both together.
    • Jan 18 2018 | 4:12 am
      @Source audio,
      Wow, thanks for all this. I've open the max patch and it seems to make sense, about to load up the motor test and see how it all goes.
      In terms of the sensor, what distance is it set to at the moment? And which pin do I need to connect that to? Apologies my responses are not as detailed as you require, it's just that I was assuming I'd be able to see all the information coming into Max itself, and then I could make my patch more accurate and test things as I go. For example, I assumed the sensor would send distance information into max itself, and then I could test distance in accordance with the acceleration of the tank itself, and adjust accordingly.
      Also, 'Arduino for dummies' book arrived today :)
    • Jan 18 2018 | 4:30 am
      So, have uploaded the MOTOR_TEST.ino first (I had a read through the program, and it made sense in terms of logic, still recognising the language though). Have plugged it all into the corresponding pins. I opened the max patch, turned on the metro, and then turn on the the motor control section but clicking the checkbox, and changing the number, but nothing happened. Tried the sliders but nothing happened either. Is there something else I need to set in max for it to recognise the arduino uno interface?
    • Jan 18 2018 | 9:07 am
      I would troubleshoot the motor test in 2 phases. 1 without max - just open Arduino IDE and open serial monitor, set it to correct baud rate 57600 and write some motor values like M 1 100 1 100 or S to stop it If that works, than quit arduino - that is important thing only 1 software can communicate with the board at the time. Than load max patch and send print message to serial object to see if Your board is on port a, If not change it to match. --------------- Ultrasonic Sensor pins are easy to recognise in the code, but here again : trigPin = D6 echoPin = D7 So You would use pins 2 3 4 5 for motor and 6 7 for the sensor. In the sensor test code max distance is set to 50 cm, calculation is done by doubling time audio travels through air, expressed in microseconds. Test patch just sends measured distance in cm via serial. In motor & Sensor patch it sends "CLOSE" if Sensor is closer than 20 cm to any object. if (distanceFront < 20 and distanceFront > 0){Serial.println("CLOSE");}
    • Jan 18 2018 | 10:12 am
      I finally got sime time to solder few things together and test myself I found few mistakes, and I am sorry if You spent too much time looking for solution, and mistake was on my side. As first one needs to add pinMode statements in setup for motor direction pins, and second mistake is missing end of line in max patch. That is needed so that arduino recognises the motor sequence of 1 letter and 4 numbers. So here are corrected patches:
    • Jan 18 2018 | 10:39 pm
      @Source Audio: Thanks for checking the code, you're very right in the fact that that would have altered trouble shooting. So good news, the motors worked. It didn't work the first time, but I went back through your instructions and found my arduino is on port c, once that was changed it worked fine on the motor test. I then uploaded the sensor test, and connected up all the pins, but that doesn't seem to be working in Max. Although, when looking at the Arduino board, the 'TX' light definitely flashes when my hand reaches 50cm from the sensor, which seems to imply that the issue might be in the max patch? Or the message the arduino is sending to Max? Any ideas?
    • Jan 19 2018 | 9:27 am
      Sensor test patch sends value in cm via serial. Can You read the values in arduino serial monitor? In the Motor and sensor sketch it just sends "CLOSE" when sensor detects object closer than 20 cm. Max patch is just set to bang when CLOSE message received, if You want to read all, just connect message object to fromsymbol here is modified patch:
      There are ways to detect if arduino is present and auto connect serial to right port, or not if arduino is not present. print message to serial object outputs ports available to right outlet.That can be run through few objects to do the trick. If You want I could upload some examples...
    • Jan 21 2018 | 8:37 am
      @Source Audio: Thanks for that patch. Now i can see the numbers moving, however the button doesn't bang when it goes past 20. I can change the object to a 'sel 20', and that bangs happily, but I'm sure there is a reason you went with 'sel CLOSE'? Is there a chance it could miss the number '20' when scanning through numbers, as opposed the 'CLOSE' message that is generated by the Arduino? And any idea as to why its behaving this way?
    • Jan 21 2018 | 8:38 am
      I have no idea how to read the values in arduino serial by the way. Do I need to send a message to it like when doing the motor test?
    • Jan 21 2018 | 9:17 am
      I made this sketches so that You can test the hardware and then modify them to Your needs. The Sensor Test sketch sends all measured values via serial, The Motor and Sensor sketch sends only word CLOSE when sensor detects something closer than 20 cm, and nothing else. The reason : You want to test and calibrate sensor so that motor can be stoped on time. When that is done, You don't want that sensor values every 50 ms sent to serial, You just want to stop and turn the Tank. That's why sel CLOSE. And if You find that 20 cm is too much, just change that to some other value. If You just read the 2 sketches You will see and understand the difference. By the way - You can also read this sketches using TextEdit- it is plain text format, nothing exotic. -------------- Again - only 1 software can talk to Arduino via Serial at a time. If You use Max, You have to at least close Arduino Serial Monitor. If You wan't to upload Arduino Code, You must either quit Max, or disconnect Arduino from Max using "close" message to serial object. If Max is running and Arduino gets disconnected, that would freeze Max and You have to force Quit it. ----------------- Arduino Serial Monitor is under Tools menu. You have to set it to same baud rate as the currently running Arduino Board. That is 57600 in sketches I sent You. Than it can send and receive messages to Arduino Board.
    • Jan 21 2018 | 9:45 am
      @ Source Audio: Ok, thanks for clarifying. I didn't understand the difference between the two Arduino sketches, that the sensor test sketch would not send a 'CLOSE' message, and rather just the values. Now it makes a lot of sense in terms of testing and prototyping, so thankyou very much for offering both. It also helps me understand the language a little more. Yes, I understand that only one program can run at a time. Great, now I understand that part of the Serial Monitor too. Thankyou so much for your time and help with this. Now I can prototype this project, and will starting learning arduino in preparation for my next project (simple project, just need to control solenoids in that one!). Thanks again!!! :D
    • Jan 21 2018 | 10:10 am
      You are welcome, I am glad You found way out of maxuino and into open world of Arduino, it's worth it. If You need any further assistance, just ask, no problem. Here is one good wiki : http://arduino-info.wikispaces.com/home You can find many infos and examples there.
    • Jan 22 2018 | 8:38 am
      Thanks for the link! Shall do some reading. And yes, you may get a future message from here :) Thanks again!!
    • Mar 08 2018 | 10:06 pm
      @ Source Audio: Just wondering if I can ask you some more questions? I've been moving my patch from my laptop to a 'Latte Panda', essentially a windows 10 development board with inbuilt Arduino. To start with though I'm just using the same Arduino Uno that I was using with my laptop, and took the patch over to the Latte Panda. All seems to run fine for the about a bit, I turn each motor on and off, and use the sensor, and its all a-ok. However at a point, the patch stops responding, the motors often get stuck on, and the Max Console reads: 'Serial . error writing to serial port'. From that point onwards nothing works. When I quit out of the patch, the only other message that appears is 'serial . serial: error resetting port attributes'. Any idea what is going on? While the computer is substantially less power than my laptop, I would have thought that basic messaging would have been fine.
      I did also try using the onboard Arduino, but I couldn't get that to work at all. When uploading the code to the internal board, it appears to load, but the Arduino software also comes up with 'Avrdude: stk500_getsync(): not in sync: rsp=0x00', which might have something to do with that issue? I'm also not sure if running the internal arduino will make it easier or harder, and to be honest I don't really care which one I use, as at this stage I'd just like it to work!! The only other thought that I have, is that the amperage powering the Latte Panda is actually not great enough to power the computer and the external Arduino, which might cause the 'drop outs' in communication. This may be a good reason to get the internal Arduino working (and save money on parts), so if you have any ideas on the error message for the Arduino that would be greatly appreciated!!
    • Mar 08 2018 | 10:53 pm
      Update: Tested the same system, but I also added a separate 12v power source to the Arduino Uno to see if it was an issue with powering the whole system from one battery. However I have exactly the same errors/issues happening too. I really hope its not the spec of the latte panda that's letting down the system, but would be surprised if that were the case. Will attempt to run the latte panda headless (via VNC) to see if that helps at all next.
    • Mar 08 2018 | 11:48 pm
      Next update: I think it may be the latte panda thats crashing, not max. Looking at 'Resource monitor' shows me that 80% of the memory is in use before max 7 is even started! I know nothing about windows so just trying to find someone to help me turn off whatever half of these processes are and free up some memory. Failing that, I'll have to try and invest in the more powerful version of the computer, or search for other options for running this project.
    • Mar 08 2018 | 11:49 pm
      Maybe the UDOO....
    • Mar 09 2018 | 8:08 am
      Can You upload Your final Arduino sketch, and maxpatch ? And what Arduino model is built in the 'Latte Panda' ? Maybe one has to change something to be able to talk to it. So all info You can provide would be helpfull, also Arduino IDE Version.
    • Mar 11 2018 | 7:55 am
      To be honest I was just using the same test patches you supplied, as I can't really develop the project until its all together and I know the limitations of the system. It uses the Atmega32u4, and apparently is the same are the Arduino Leonardo in a lot of ways. And I'm using IDE 1.8.5. But all this being said, when I watched that resource monitor on the latte panda, it looks like the system really can't handle much, and so I think that Max/msp is pushing it over the edge in terms of CPU/RAM, so I honestly don't think its work trouble shooting until I get the next board. I'm saving for the highest spec UDOO, so hopefully i can get that in a week or two. Will be in touch when it arrives and let you know how it handles max and the patch!
    • Mar 11 2018 | 8:54 am
      It should work though, it is just a trivial task to send few bytes over serial port... If Max is too heavy, try compiling a standalone with everything unneeded removed, in first place extensions, on real pc and run it on Panda. And of course windows 10... It can be trimmed down to bare minimum, which I think is necessary. But back to arduino - can You not try few simple things on built in board, like blinking a led, controlled by serial data ? I would start with arduino Serial monitor first. Just simple stuff like if serial input is 1 the light the led, if 0 - turn it off. If You want I can provide a sketch like that...
    • Mar 12 2018 | 7:26 am
      I feel like it should work too, but my knowledge is limited here. I also read that windows 10 can be made to run better, the issue here is that the unit doesn't ship with a complete license for windows 10. And to be honest I'm reluctant to buy one until I feel more confidence in the specs of the device. And I also have no idea about compiling stand alone versions of anything, sorry! :) As for Arduino, I'm still working through the my beginners book, so I can't really trouble shoot arduino yet. A basic patch would be great, and I'm happy to test that, but don't want to waste your time if the system might not be able to handle Max/msp!
    • Mar 12 2018 | 8:18 am
      I see, You have many questionmarks and a lot to learn. One thing could be the cause of interrupted serial data : power saving settings for USB. One should disable it, and configure the system for max performance, disable all window animations, screensavers etc Than one could make real tests. Try this simple arduino sketch on internal Arduino : void setup() { pinMode(13, OUTPUT); digitalWrite(13, LOW); Serial.begin(9600);}
      void loop() { if (Serial.available() > 0) { int LED = Serial.parseInt(); if (LED == 1) {digitalWrite(13, HIGH); Serial.println("LED is ON");} if (LED == 0) {digitalWrite(13, LOW);Serial.println("LED is OFF");} delay(50);}} After uploading to internal Leonardo on correct COMM port, You can send 1 or 0 from Arduino Serial Montor to light the internal LED on or off. ----------------- Now I guess You are not going to license Max7 on that Panda, jut use it to run patches. if that is so, You can delete many things in Max folder to make it run smoother. Maybe even downgrading to older version, like max 5 or 6 ? One can still download free runtime versions and run max 7 patches on them. I can send You max5 RT trimmed down, no java, no jitter etc, just plain max. It starts and runs like an arrow...
    • Mar 15 2018 | 10:53 pm
      Yes, much to learn! It's tricky as I know Max, I just don't know anything about Arduino. Mostly I find I earn more when I attempt a project, its just that this project has evolved a lot, originally from using Pure Data on a Raspberry Pi. That I had done before, but not with arduino, but I knew the computer would handle pure data. When I changed to max/msp and this latte panda, it meant more variables, so more learning. Again, I thankyou for helping me with the learning process! It would seem that I can't make many changes to my version of windows without buying a full version of windows, which as I stated I'm hesitant to do, but I will look to see if I can find it cheaply in the mean time. As for your sketch, that has opened up a few new issues, and it might be the computer that is at fault. I opened your sketch, and it didn't work on the latte panda (by the way, it is actually an Arduino Uno, there is confusing documentation...). So I uploaded it to another Arduino Uno that I had, and ran serial monitor from my computer, and the sketch works fine. I then went back to the latte panda and ran the blink patch, and sure enough, that doesn't work either. I get the same error message appearing everytime I load a patch:
      avrdue: stk500_getsync(): not in sync: resp=0x00
      I've posted on the latte panda forums in order to get an answer about that error message, as I think that's the problem. For now though I'd better hold back on the full version of windows too, as if it is a faulty board that's not going to help me! If you have any idea on that error message please let me know. If not I'll post when I know more from the other forum. Thanks again for your help and patience!
    • Mar 15 2018 | 11:05 pm
      Oh, and yes I trimmed down version of Max 5 would be wonderful! I'm still running max 6 on my laptop at the moment. All I need is the basic features of Max/msp, just for audio and robotics control.
    • Mar 16 2018 | 7:39 am
      Sorry that it took time to reply, I had problems with loging in and posting. It seems that folks at cycling are still soldering their wires arround new authorisations - logins etc stuff avrdue: stk500_getsync(): not in sync: resp=0x00 That error almost allways means that serial connection to the board is broken, either the ftdi chip is faulty, or one did not select correct model of arduino, processor or COMM port. All lattepanda docs mention leonardo as built in board, so where did You get that UNO modell ? UNO has ATMEGA 328p cpu, and it has to be selected under processor menu. And one has to restart Arduino IDE to make that setting active. -------- As for Max 5 runtime, with removed parts, I can't upload it here - it is 5.7 MB and that is too much for the forum upload.
      here is download link : https://files.fm/u/6nu4b5nc
    • Mar 16 2018 | 8:07 am
      I just had a look at lattepanda hardware. It should run max 7 without problem for what You need. I had several projects using Windows Tablets with less powerfull CPU/GPU, and max 7 runs just fine to playback Audio, Video and do "normal" tasks. But Windows was 8.1 pro trimmed down to the bare bones, simply nothing, just drivers, max and notepad ...
    • Apr 06 2018 | 6:05 am
      @Source Audio: Excuse the delay, was trouble shooting a few things at the same time. The good news I've got the latte panda onboard Arduino to work now. It seems the latte panda will run ok, but I will invest in a pro version of windows and trim it down like you said in the near future. The motors now work fine, and everything in regards to them works perfectly. However the sensor is not working now :( I've tried a second sensor I have here, and it also doesn't work, so we can rule out the sensor. Is there anything that needs to change in the Arduino Sketch now that I'm using an Arduino Leonardo, and not an Arduino Uno? I've checked my wiring twice, and but can't seen any issues there. I've opened up Serial Monitor, and when I move my hand around the sensor nothing seems to happen. Apart form setting the Baud rate to 57600, is there anything else i need to do? Any ideas?
    • Apr 06 2018 | 6:06 am
      (By the way, the issue with the arduino leonardo is in the uploading process. I have to hold down the re-set button when I upload a new sketch, and then everything works fine).
    • Apr 06 2018 | 6:59 am
      Hi there, I honestly lost a trace about what exactly was in the sketch - maxpatch, I'll have a look into it and report back. But in the meantime - I remember that serial USB communication has to be initialised differently for ATmega32U4 based boards, one had to insert while (!Serial);  // for Leonardo/Micro/Zero boards in the setup, so that part should look like : void setup() { while (!Serial);  // for Leonardo/Micro/Zero  Serial.begin(57600); } ---------- The thing is - one has to wait till USB serial communication gets initialised.
    • Apr 08 2018 | 10:08 am
      Totally understandable! Excuse the time delay, as I said I was working between forums to try and get the problem solved, such a learning curve! I've been doing some more tests, but I can't seem to the sensor to work even when I add the while (!Serial); command. This is how it looks: int Direction1 = 2; int Speed1 = 3; int Direction2 = 4; int Speed2 = 5; //Motor Speed Control const int trigPin = 6; const int echoPin = 7; long timeFront; int distanceFront; // Ultra Sensor
      void setup() {while (!Serial); pinMode(2, OUTPUT); pinMode(4, OUTPUT); pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); Serial.begin(57600); }
      void loop() { digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); timeFront = pulseIn(echoPin, HIGH, 2940); distanceFront = timeFront*0.034/2; // NEED QUED TRIG > READ ????? if (distanceFront < 20 and distanceFront > 0){Serial.println("CLOSE");} //stop ROBOT Serial.print(distanceFront); delay(50);
      if (Serial.available() > 0) {char val = Serial.read(); if (val == 'S'){digitalWrite(Direction1,LOW); digitalWrite(Speed1, 0); digitalWrite(Direction2,LOW); digitalWrite(Speed2, 0);} if (val == 'M'){ int D1 = Serial.parseInt(); int S1 = Serial.parseInt(); int D2 = Serial.parseInt(); int S2 = Serial.parseInt(); if (Serial.read() == '\n') { digitalWrite(Direction1, D1); analogWrite(Speed1, S1); digitalWrite(Direction2, D2); analogWrite(Speed2, S2); }}}}
      ------- One thing that I have noticed is that when I make changes in the max patch, the light on the arduino leonardo / latte panda blinks. For example, it blinks when I start a motor, or stop a motor. However nothing happens when I move my hand in front of the sensor. The motors work fine, its just the sensor part that doesn't. Quite frustrating when it worked on the arduino uno totally fine. I assume its a difference between boards? Although there is now a windows operating system controlling it, but I assume that shouldn't matter?
    • Apr 08 2018 | 1:51 pm
      maybe setup should be : void setup() {while (!Serial); Serial.begin(57600); pinMode(2, OUTPUT); pinMode(4, OUTPUT); pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT);}
      I would do simple tests to find the problem. Check if leonardo is sending anything to max using some simple method like: void setup() {while (!Serial); Serial.begin(57600);} void loop() { Serial.println("CLOSE"); delay(500); Serial.println("Away");delay(500);}
      if You receive the 2 messages in Max, then serial communication is ok, and You go on to troubleshoot some other part. It could be that pin numbering is different between UNO and that built in leonardo, and that tsensors are connected to wrong pins
    • Apr 10 2018 | 8:58 am
      Another possible problem which I overlooked : leonardo has different Timer configuration than UNO or other 328p based arduinos. Using pin 3 on leonardo for PWM output , could affect timing of delay. That's because Timer 0 is used for delays, microseconds etc and leonardo uses Timer 0 on pin 3... this could be a better pin configuration : int Direction1 = 4; int Speed1 = 5; int Direction2 = 8; int Speed2 = 9; //Motor Speed Control const int trigPin = 3; const int echoPin = 2; long timeFront; int distanceFront; // Ultra Sensor In this way Timers should not conflict on leonardo.
    • Apr 15 2018 | 5:54 am
      @Source Audio: excuse the delay, have wanted to be thorough with my testing. First of all I changed the ordering this: void setup() {while (!Serial); Serial.begin(57600); pinMode(2, OUTPUT); pinMode(4, OUTPUT); pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT);} And didn't get any results. While you also state a simple test after this, I'm afraid I'm not entirely sure how that test works. I uploaded the code to the arduino, then opened up a max patch and checked the max patch for the window, and couldn't see anything. I also did the same in Arduino Serial, but also couldn't see any results.
      Did I have to input anything into the Serial Window in order to see anything or should it just automatically print messages if it detects something from the ultrasonic sensor? I then changed the pin configuration, re-uploaded it to the arduino and checked the max patch, but still nothing. In all cases the motors still operate as expected, but the ultrasonic sensor never works. Would you be able to give me further instructions on how to test the ultrasonic sensor with that simple arduino sketch?
    • Apr 15 2018 | 2:50 pm
      That seems to be a real troublemaker... Let's get it step by step. First one needs to check if Serial communication is working. When You say motor works, do You mean motors move when You send messages from Max to arduino ? If so, that would mean that serial communication is working. If You are not sure, then upload this simple sketch to leonardo: void setup() {while (!Serial); Serial.begin(57600);} void loop() { Serial.println("CLOSE"); delay(500); Serial.println("Away");delay(500);}
      Close Arduino IDE, open Max and see if it is receiving Close and Away messages. Are You using exactly the same hardware that worked on UNO ? I mean not same type, but same pieces of hardware ? Please, get that serial working and let me know. I would not mind if You would upload Your current arduino sketch. Don't paste it as text here , but upload it as file.
    • Apr 17 2018 | 10:11 am
      Great, thanks! Yes, the both the motors work when you send messages from Max to the arduino, so that should mean that Serial communication is working. In terms of hardware, everything is exactly the same, however I changed the wires that were connecting the ultrasonic sensor to the Arduino. In order to make sure that it wasn't the leads, I 've just uploaded the sketch to the original Arduino Uno, plugged in the Ultrasonic Sensor, and tested it using the original Pin configuration (using pins 6 and 7), and it is still working fine to communicate with Max. So with this in mind it appears the hardware is all functioning Ok. I posted on the Latte Panda Forum, and they sent through a link to the specifics of there version of the Leonardo, which may may be helpful (it talks specifically about certain pins). http://docs.lattepanda.com/content/hardware/inputsAndOutputs/ I'll upload the current Arduino Code that I'm using with the new Pin Configuration shortly.
    • Apr 17 2018 | 10:21 am
      Here is the last edit I made to your original code to update the Pins to the newer configuration.
    • Apr 17 2018 | 11:30 am
      I just looked at the picture of LatePanda Layout, could be that You are mistaking the Pin Nubering of LatePanda connector, with Pin numbering of Leonardo ? It is a bit confusing if one looks at it. Hopefully You do follow Arduino D0, D1, D2 etc as orientation and not pin numbering of the LatePanda connector. I would suggest to try Ultrasonic sensor alone till it starts working on some pin pair. You could use the sketch which I sent You to only test U. Sensor, remember? That would make sure that there is no conflict in sending PWM using same Timer which is controlling delayMicroseconds. You could also try to make trig Pulse a bit longer, 5 microseconds ----------- here is modified sensor test
      Difference is trigPin is on D7, echo Pin on D6 D7 should use Timer 4 on Leonardo. And You could try to change delayMicroseconds(2); to delayMicroseconds(5); to see if it helps. leave delayMicroseconds(10); as is
    • Apr 20 2018 | 12:12 am
      @Source Audio: Thanks again for your help. This is starting to get really frustrating for me, but I really appreciate your ongoing support with this project :) I tried the new sketch, check the pins, uploaded the sketch and tested the max patch (with Arduino software closed), but nothing happened. I then changed the delayMicroseconds(5), and re-tested, and nothing happened.
      I then thought that I would test it using Trig on Pin 9 and Echo on Pin 8, as 9 does PWM and obviously works if it was successfully driving the motors successfully. But that didn't work either. I then wondered if there was a voltage issue, perhaps a fault with the board, so I tested the voltage across the VCC and GRD terminals on the Ultrasonic Sensor, but it read pretty close to 5v, so it would seem that power is going through. Do you think there could be anything else in the sketch that could be changed?
    • Apr 20 2018 | 6:32 am
      I can't imagine why is that not working. Not having that hardware makes it impossible to find out what is going on. Maybe You could look into some of the ping libraries for the Sensor, maybe they have some kind of fix for leonardo board. Driving motors is easy thing to plant on whatever code that would finally get that sensor to work
    • Apr 20 2018 | 9:15 am
      Well, thanks for your help, sadly I guess its the issue when prototyping using newer technology that is so specific. The only thing that latte panda have recommended is that the tested the board using this ultrasonic sensor : https://www.dfrobot.com/product-53.html Since I'm running out of options I might have to give it a try.
    • Apr 20 2018 | 9:21 am
      Just found a stocking here in Australia. Will let you know how I go when it arrives. Will also try and find out how latte panda tested it.
    • Apr 26 2018 | 11:01 pm
      @Source Audio: So I've had a small breakthrough, but I could use your help to combine some codes (I've tried, but it doesn't work). I got the new sensor, the URM37 V3.2 https://www.dfrobot.com/wiki/index.php/URM37_V3.2_Ultrasonic_Sensor_(SKU:SEN0001) On their wiki,I found some code that I managed to understand, and it would print the distance read by the sensor into serial monitor (have been progressing through my arduino lessons!). From this I can see that the sensor is actually reading the distance, and printing it fine. So this sensor works! However the pins are labelled slightly different, and while i tried changing the pin numbers in our sketch, clearly it needs a little more adjusting that just that. The code that I got form the DFRobot site is made to deal with a Servo as well as the sensor, for a very specific purpose. But I'm not entirely sure how to copy only the sensor part of this sketch, into the last sketch, and have it work. Is there any chance you could do this for me? I know its a big ask, but considering this seems to be working, I hope we are near the end. I'll try to merge the codes again myself, but due to my beginners arduino language I'm not entirely sure how I'll go... if it does work I'll post again! Here is the code from the DFRobot site: // # Editor : Jiang from DFRobot // # Data : 24.07.2012 // # Product name:ultrasonic scanner Kit // # Product SKU:SEN0001 // # Version : 0.2 // # Description: // # The Sketch for scanning 180 degree area 4-500cm detecting range // # Connection: // # Pin 1 VCC (URM V3.2) -> VCC (Arduino) // # Pin 2 GND (URM V3.2) -> GND (Arduino) // # Pin 4 PWM (URM V3.2) -> Pin 3 (Arduino) // # Pin 6 COMP/TRIG (URM V3.2) -> Pin 5 (Arduino) // # Pin mode: PWM // # Working Mode: PWM passive control mode. // # If it is your first time to use it,please make sure the two jumpers to the right hand // # side of the device are set to TTL mode. You'll also find a secondary jumper on // # the left hand side, you must break this connection or you may damage your device. #include <Servo.h> // Include Servo library Servo myservo; // create servo object to control a servo int pos=0; // variable to store the servo position int URPWM=3; // PWM Output 0-25000us,every 50us represent 1cm int URTRIG=5; // PWM trigger pin boolean up=true; // create a boolean variable unsigned long time; // create a time variable unsigned long urmTimer = 0; // timer for managing the sensor reading flash rate unsigned int Distance=0; uint8_t EnPwmCmd[4]={0x44,0x22,0xbb,0x01}; // distance measure command void setup(){ // Serial initialization Serial.begin(9600); // Sets the baud rate to 9600 myservo.attach(9); // Pin 9 to control servo PWM_Mode_Setup(); } void loop(){ if(millis()-time>=20){ // interval 0.02 seconds time=millis(); // get the current time of programme if(up){ // judge the condition if(pos>=0 && pos<=179){ pos=pos+1; // in steps of 1 degree myservo.write(pos); // tell servo to go to position in variable 'pos' } if(pos>179) up= false; // assign the variable again } else { if(pos>=1 && pos<=180){ pos=pos-1; myservo.write(pos); } if(pos<1) up=true; } } if(millis()-urmTimer>50){ urmTimer=millis(); PWM_Mode(); } } void PWM_Mode_Setup(){ pinMode(URTRIG,OUTPUT); // A low pull on pin COMP/TRIG digitalWrite(URTRIG,HIGH); // Set to HIGH pinMode(URPWM, INPUT); // Sending Enable PWM mode command for(int i=0;i<4;i++){ Serial.write(EnPwmCmd[i]); } } void PWM_Mode(){ // a low pull on pin COMP/TRIG triggering a sensor reading digitalWrite(URTRIG, LOW); digitalWrite(URTRIG, HIGH); // reading Pin PWM will output pulses unsigned long DistanceMeasured=pulseIn(URPWM,LOW); if(DistanceMeasured==50000){ // the reading is invalid. Serial.print("Invalid"); } else{ Distance=DistanceMeasured/50; // every 50us low level stands for 1cm } Serial.print("Distance="); Serial.print(Distance); Serial.println("cm"); }
    • Apr 27 2018 | 6:10 am
      On that page there is a code for only sensor, so why not use that ? It is set for pins 3 & 5, meaning that motors should change pins to 4 & 6 for motor 1, and 8 &9 for motor 2. But first task would be to tweak the code to Your needs, I mean to print the results the way You want. this part : Serial.print("Distance="); Serial.print(Distance); Serial.println("cm"); can be changed to : Serial.print(Distance); then You can receive only distance in cm in Max --------- Don't get confused with the fact that functions trig and pwm output are indicated from sensors point of view. Trig out form arduino is actually pin 5 and echo pin 3
    • Apr 27 2018 | 6:23 am
      And if that pin combination is a way to go, here is code for the old sensor that worked on UNO, modified for pins 3 & 5 for sensor, 4 & 6 for motor 1, and 8 & 9 for motor 2. I am wondering if that would work.
    • Apr 27 2018 | 10:56 am
      @Source Audio: The code that you included in the URM_37.zip folder works fine (I must have missed that!). However the motorandsenesorpanda.zip files don't work again. When I look at the code in the URM_37, it appears to be doing this differently as there is a lot of things I don't really understand in there. From what I can see, in order to edit our motorandsensorpanda files, the new int's to the start from the new script. I then assume this is the part that needs replacing: void loop() { digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); timeFront = pulseIn(echoPin, HIGH, 2940); distanceFront = timeFront*0.034/2; // NEED QUED TRIG > READ ????? if (distanceFront < 20 and distanceFront > 0){Serial.println("CLOSE");} //stop ROBOT Serial.print(distanceFront); delay(50); And it needs to be replaced with the text from the URM_37 file. Is that correct? And then this section which is the motor should stay the same? if (Serial.available() > 0) {char val = Serial.read(); if (val == 'S'){digitalWrite(Direction1,LOW); digitalWrite(Speed1, 0); digitalWrite(Direction2,LOW); digitalWrite(Speed2, 0);} if (val == 'M'){ int D1 = Serial.parseInt(); int S1 = Serial.parseInt(); int D2 = Serial.parseInt(); int S2 = Serial.parseInt(); if (Serial.read() == '\n') { digitalWrite(Direction1, D1); analogWrite(Speed1, S1); digitalWrite(Direction2, D2); analogWrite(Speed2, S2); }}}}
    • Apr 27 2018 | 11:29 am
      I am on the move, so can't post any sketches, but the idea is to add only motor control parts to the working sensor patch. Start with pins, setup, loop etc parts. If You get messed, I'll have a look at it when I get back home later
    • Apr 29 2018 | 11:58 pm
      Source Audio: So, there will be lots of questions here, as I'm starting to understand the situation more, and can be more active in trouble shooting. I notice from your Arduino sketch, that the only thing that gets printed into the serial window is the word 'CLOSE', is that correct? If this is the case, then I have got the arduino sketch on the URM37 to do exactly that, it only prints the word 'CLOSE' when an object gets to 20cm distance from the sensor. One other thing i need to understand, is that when I use my laptop, and the Max/msp patch, I used a 'print' object connection to the 'serial' object to see what it was generating in the Max window, and it was only producing numbers, it never produces the word 'CLOSE'. Is this because that part of the Arduino sketch is only to test the logic, so that it can be seen the arduino monitor easily?
      And in the Arduino, do the numbers ever need to be sent using the Serial.PrintIn command, or again, is that only used to 'see' it in the Serial Monitor? I assume the numbers are always 'sent' to the Serial Port, and therefore always available for anything else reading the serial Port, is that correct?
      Using my last process to further understand the data pathway, I did the same test using the Latte Panda. While the serial monitor in Arduino clearly produces the 'CLOSE' message, when I open the Max/msp patch and connect a 'print' object to the 'serial' object, it never prints any numbers into the max window. It would therefore seem to me that there is an issue in communication between Max and the Arduino, the signal seems to flow OK from Max to Aruino, but not from Arduino to Max. Do you have any idea as to what would block the flow of information between Arduino to Max? The only thing that I can thing of is port, and BAUD rate. I know the port must be working as the motors have worked in the past, so I assume the port must be correct? As for the BAUD, I tried it on 4800 just in case it was for some reason to fast, but that didn't seem to solve the issue either. NOTE: I haven't used the motors in any of this trouble shooting sketch, I'm just keeping it to the sensors to keep things simple.
    • Apr 30 2018 | 12:03 am
      Actually I think I just figured out part of the number appearing in the Max Window. They're actually code for the word 'CLOSE' aren't they, and the rest of your Max Patch connected to the serial object translated them back into the word 'CLOSE', and then uses 'Select' to bang when that word is generated. Is this correct?
    • Apr 30 2018 | 12:43 am
      Have been researching other issue with latte panda, and while this doesn't make sense to me with my minimal knowledge of Arduino, it may make sense to you! This person was having the opposite trouble that I am having, they could read information but couldn't send information using the latte panda, and this is what they discovered: 'The key is Leonardo doesn't execute SerialEvent() (for some reason!). It is supposed to execute between loop() passes as all other Arduinos do (almost all, there are two others like Leonardo... Micro and ETH, I think). In looking back at links to SerialEvent, I can now see that this is "documented" e.g. https://www.arduino.cc/en/Tutorial/SerialEvent but NOT in the links that describe differences between Leonardo and the rest of the Arduinos. like this: https://www.arduino.cc/en/Guide/Arduino ... icro#toc11
      To get this working, I just added a call to SerialEvent() as the first line in loop() and it now works with the Serial Monitor and my C# code on the LattePanda. Also, Arduino v1.69 doesn't upload to Leonardo correctly, so you need to upgrade to v1.8x.' (Taken from: http://www.lattepanda.com/topic-f6t1429.html?start=20 )
    • Apr 30 2018 | 6:47 am
      Here are the answers: CLOSE is the code word for Sensor getting closer than 20 cm. We decided together to do so, because that was all You needed, and we wanted to keep serial data traffic as low as possible. Arduino sends data in ASCII format, which then get output as numbers from serial object in max. That's why one uses itoa to translate that into symbols. One exception is if one uses serial.Write in arduino to send numbers only. That gets output as plain integers in max. But one can do that only if ONLY nubers have to be sent/received. Serial.print sends single items as ASCII bytes, Serial.println sends newline code at end, that is the difference. -------------------- There was no call to serialEvent() in any of the arduino sketches I sent You, so that can't be the problem. Arduino is listening only to single messages, and You confirmed that motor control worked with Leonardo on Lattepanda. ------- I asked You to do simple test on lattepanda, sending something over serial port and seeing if anything gets in, You never replied with results. Please use that sketch from my post - Apr 15 2018 and report if You receive the words CLOSE and Away in max.
    • May 01 2018 | 10:57 am
      Source Audio: Thanks for your replies, and glad to see that I'm finally starting to get some of my trouble shooting and understanding correct. I apologise, I didn't do the sketch posted on Apr 15 2018 as I thought that because the motors were working I didn't have to, and that that meant that serial communication was working too. My apologies for again for not doing this test sooner due to my misunderstanding of Serial Communication. I just uploaded that sketch onto the latte panda, and in Serial Monitor I can see the words 'close' and 'away', but when I quit out of the Aruidono IDE, and run the max patch, no messages come through. It doesn't change the message box with the 'set', and when I connect a print object I see no numerical data in the Max Window. I went back to my Uno and Mac OS, and tried the same patch just to make sure I understand the process, and I can see it work very clearly there, both in terms of changing the message box, and generating numerical data in the Max Window. This seems to imply an issue with Serial Communication then?
    • May 01 2018 | 11:07 am
      No need for apologise for anything, it's Your project, so You dictate the progress. Finally - it is clear that max patch isn't receiving serial data, but it seems it does send ... Very strange. Could You upload max patch that You use on lattepanda ? Just to make sure that some simple mistake does not make troubles. And what max version do You use ?
    • May 01 2018 | 11:21 am
      Maybe You could try comport object from jasch, it allows more control over serial port, maybe one needs to enable dtr, rts etc to activate Leonardos serial port.
    • May 03 2018 | 9:32 pm
      Thanks for understanding, but it is due to my ignorance. I assumed that serial communication was like a pipe, it data flowed one way it could flow the other. But its clearly more like a two lane street. I'll post the patch that I'm using below. As for Max, my Mac that I edit the patches on is Running Max 6.0.8. I'm just using the latest version of Max on that, but in the 'runtime' mode (as in, you install it but don't pay for a licence). So that one is running 7.4.3 (Windows 32-bit). I'm in the studio today, so will look into Comport and see how I go. Here is the patch:
    • May 03 2018 | 10:34 pm
      A bit more research, might be a max 7 issue: https://cycling74.com/forums/arduino-101-and-serial-object-compatibility-in-max7 Still working on comport, unfortunately there is a dead link on the jasch page....
    • May 03 2018 | 10:57 pm
      Just to let you know of my progress, I've installed Max 6.0.8 on the latte panda just to rule out compatibility issues, and tried running everything again. That didn't work, so I'll get back to trying comport.
    • May 04 2018 | 12:26 am
      Great news, comport worked with the sensor! So now on the latte panda, I can use the original sensor quite fine, and it sends the data into the comport object, and will read the 'CLOSE' message and bang the trig object nicely. That system is working. One odd thing I have noticed though is that my COM ports have changed. While it used to be com 1 and 6, now it is com 1 and 3, and so I'm using com 3 now. Odd, but I have no idea why this has changed all of a sudden. However, now the motors won't work, and I assume there is something different between how comport sends information vs serial. Ive tried looking into it but can't seem to find an answer. I've tried turning RTS/DTR on/off in all the combinations to see if that helps, but it doesn't seem to change anything either. Also tried the RTS/CTS handshake but I'm really not sure what I'm doing with any of these things to be honest... In terms of the patch, all I have done is changed the serial object for the comport object, and am using 'comport 3 57600'. Can you advise me how to make the motors work with comport?
    • May 04 2018 | 8:01 am
      Here is modified patch. Comport object works a bit different than serial.
    • May 04 2018 | 9:58 am
      Source Audio: It works, it all works!! What a journey that has been!!!! I can't thank you enough for your patience and help with this, and I've learnt so much more about Arduino in the process too (still working my way through my textbook, making more and more sense each week). Out of curiosity, do you have any idea as to why comport works but serial doesn't? I read a few posts about preference for comport, but didn't see a strict answer as to why. In the process of upgrading my mac to Max 7 now, just so I can keep everything on the same playing level (and re-learn all the new Max 7 things too). Many many thanks, this has been a huge help!!
    • May 04 2018 | 10:16 am
      I am glad You finally got it working. About difference comport - cy74 serial object ... I guess it has to do with establishing serial communication with that particular usb based board. All FTDI or CH340 based boards which use dedicated usb/serial chips start communicating as soon as one openes serial pipe, with ATmega32u4 it seems to be different. But it is just a guess.
    • May 05 2018 | 8:25 am
      Interesting, but good to know. At least now I have sketches for both, so hopefully I can begin to understand the difference. Once this is completed I'll be moving on to using some basic actuators in a similar way, but think I'll just start with comport and hope it's easier!!! Thanks again, pretty sure we'll cross paths on the forum again in the future :)