5/8 sensors HCsr04 from arduino to max for installation
Hello everyone, I have to do an installation with 5/8 HCsr04 to detect presence and distance. Each sensor starts a sound sequence in max which interacts with an approaching instrumentalist. Maxuino is dated and let go, as I could do in your opinion. I'm at the beginning with arduino, I've already run a HCsr04. Thank you all
From self-taught experience:
1. Getting data passing from Arduino to MAX through serial object is quite straightforward, once you have more or less understood the famous (and mysterious - at least for beginners) sequence of objects allowing to "decipher" the data received through the serial port and making it identical, in MAX, to the Arduino source message :
2. As far as sending each blablabla piece of data is concerned, the Arduino code should read as follows: Serial.print("blablabla");Serial.println(" ");
3. USB Arduino/Computer connections are reliable (but patches are long to load). Bluetooth is more chaotic. I am currently in the process of testing WIFI/OSC. Send regular "I-am-still-connected-type" messages from Arduino to MAX in order to detect connection losses easily.
4. As you will have several sensors, pay sufficient attention to the routing of data, otherwise you may end up with unmanageable situations in MAX !
5. You have plenty of tutorials explaining HCsr04 Arduino coding, which is pretty simple if you consider only basic usage. Just make sure you correctly set min/max and calibration of distances to avoid troubles.
6. Lastly, it may sound obvious, but it is more of a self-reminder, as I literaly hate doing that : for public performances/installations, the whole thing has to be very robust. Meticulous soldering of the different parts is a must. The use of simple jumper wires is definitely not enough (believe me ..).
Hello Sebastian thanks, yes indeed I had thought about the leaps of HCsr04, I will make a selection of incoming numbers. The problem I have now is that the USB serial doesn't work. I'm experimenting with the max test. Perhaps the USB serial is not good? I think I read that somewhere
Maybe.
Have you sent a print message to the serial object in order to have the connected items listed in the Max Console, and selected the letter corresponding to your Arduino ?
Are the Arduino and serial object baud rates identical ?
Yes Sebastien, here is the sketch and the patch
#define trigPin 6
#define echoPin 7
#define pinAlimenta 8
long durata, cm;
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(pinAlimenta, OUTPUT);
digitalWrite(pinAlimenta, HIGH);
}
void loop()
{
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
durata = pulseIn(echoPin, HIGH);
cm = durata / 58; // per i pollici la formula è durata / 148;
Serial.write(cm);
}
Ok now work but if I quit from arduino IDE
using 2 apps at same time on same serial port does not work.
also to upload code, you need to send message close to serial in max.
Serial.write from arduino sends raw bytes 0 - 255,
using zl.group and itoa in max is not working for that.
-----
you could add a bit of delay in main loop in arduino,
and poll input faster in max.
that code could work for a single sensor, but for multiple
sensors you need either an ID prepended for each sensor,
or create array in arduino and send it as a list.
in any case using Serial.print and Serial.println.
depending on what infos you need from sensors,
one would prefer one or the other option.
if you need only to report if sensor has detected something
closer than nn cm, then it makes no sense to send a list of 8 sensors
all the time, but only state of each sensor if it changed.
As far as sending each blablabla piece of data is concerned, the Arduino code should read as follows: Serial.print("blablabla");Serial.println(" "); (1)
The sel 13 10 object "filters out" ASCII 13 and 10 values received through serial port and outputs the other values through its rightmost outlet. Indeed, Serial.println(" ") from Arduino is received as a pair of 13 (println = Carriage Return) and 10 (" " = Line Feed) out of the serial object. "blablabla" is coded by numbers always different from 13 or 10.
So each number corresponding to blablabla is consecutively placed in a list by the zl.group object (max size 1000), until a 13 is output by serial : at this moment, the list is forwarded to the itoa and fromsymbol objects to be "translated" into numbers or MAX message, and zl.group starts compiling a new list until the sel 13 10 object receives a 13, and so on.
(1). Alternatively, for numbers: Serial.print(number-to-be-sent);Serial.println(" ");
Hi Seba, I removed the Serial.write and inserted the other serial.print, but I only receive the data from the distance sensor, is that right?
#define trigPin 6
#define echoPin 7
long durata, cm;
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop()
{
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
durata = pulseIn(echoPin, HIGH);
cm = durata / 58; // per i pollici la formula è durata / 148;
Serial.print("Cm = ");
Serial.println(cm);
Serial.println();
}
Hi,
You are trying to send 2 different pieces of information: the first one is the text "cm=" and the second one is the cm value itself. Each one should be sent using an individual Serial.print message, and they have to be followed each by Serial.println() to be identified separately by MAX.
So, the code should read:
Serial.print("Cm = ");
Serial.println();
Serial.print(cm);
Serial.println();
NB: as suggested by SOURCE AUDIO, you may consider adding a delay(100); instruction at the end of the Arduino loop, in order to reduce the flow of data (100 is just an idea, the value depends on how fast you want the sensor to react to movements), and maybe increase the metro frequency to, say, 50.
ok thanks for now the distance is enough for me, I need it to detect if an instrumentalist is close up to one meter or between one and two meters. If I may ask, how can I add a second independent sensor?
You can either plug a second sensor on the same Arduino board (using trigPin 8 and echoPin 9, for instance) and update the code accordingly, or you can also use a second Arduino board, USB-plug it separately, and duplicate MAX serial input routine for the new Arduino.
In both cases, this is where appropriate data labelling/routing might become crucial, depending on what you intend to achieve.
I would add few words here.
There were reports from users that max serial communication is not reliable for long term installations, if I remember correctly, mostly on windows.
Arduino simply stops communication after some period.
If that is still so, I have no idea, but it would be safer to use
32u4 based arduino and set it as HID or midi usb device.
-----------
To the next point - adding more sensors.
they can all share same trigger pin but use one echo pin per sensor.
there is even easy to use library:
https://www.arduino.cc/reference/en/libraries/hcsr04-ultrasonic-sensor/
original multi example shows 6 units, but it is no problem to use 8 of them.
if you want to send raw readings to max,
arduino code would be quite simple:
#include <HCSR04.h>
HCSR04 hc(2, new int[6]{5, 6, 7, 8, 9, 10}, 6);
int x;
void setup(){Serial.begin(9600);}
void loop(){for (int x = 0; x < 6; x++) {Serial.print(x); Serial.print(" ");
Serial.println(hc.dist(x));}
delay(60);
}
-------------
in max you get pairs - sensor number and value in cm
Thanks Seba
source audio, I need this thanks, I'll update you when I can work on it. For the serial I'm using a macair M1 de 2020 and I keep the arduino on for a long time as a test and it doesn't crash. I will keep it on 24h :). for the code with more HCsr04 i have to buy other bredboards
you use breadboards ?
no soldering ?
For now I'm doing coding tests, then the installation will be another step. The sensors will be far away, at least 2/3 meters away from the arduino. I'll have to do all the work it's a second job :)
"The sensors will be far away, at least 2/3 meters away from the Arduino"
Then you should include that in your tests as well. As far as I know (but I know only a few !), sensors should be as close as possible to the board. Long wires may increase resistance: this can alter measurements.
I had no particular issue using serial and Arduino (Nano) through USB (I also have a MAC but used the installation for a maximum of a few hours only). I faced a lot of challenges using bluetooth serial connection, though : multiple connection breaks, mysterious and unmanageable "tty attributes" error messages in MAX ....
To my opinion, soldering is a must for public performance/installations.
Sebastian, so I'll put the arduino next to the sensors, about a meter apart. The USB cable connected to the Mac can also be 10 meters long, right?
Hey Dailon. I really recommend that you perform full scale testing of your installation upfront, in order to check that these distances won't cause any issue. There are usually significant differences between tinkering at your desk with breadboards, 10 cm long jumper wires, self-cooked code etc .... and the real big thing ! Calibration is also important for HC-SR04 (for instance : air temperature influences the measurements by modifying the sound's speed). If you don't test well in advance, then it may be too late when you realize that everything works differently in real conditions.
Sure Sebastian, if you've had experiences I take your advice for good, I have to do it and I will do it, I can't fail :)
If I use two arduinos I use the same code but on two different serials that they receive from MAX. But how do I upload the same sketch in two arduini?????
ok ok i fixed it :)))
don't use overlong USB cabe.
10m can be used reliably only with active extender cable.
if distance from sensors to your computer needs to be
10m or more why not use ESP-32 sending UDP/OSC ?
Sensor cables will have some loss/voltage drop, depending on
cable gauge/resistance.
pulse measurment does not really suffer much from cable length, but could from interference that causes jitter.
placing a cap betwen power rails could smooth that.
I would first see what 4 wire cable you can get,
check resistance and so power loss.
If you can't calculate that yourself, post link to available cables
or any other infos, I'll be glad to calculate that for you.
but 2 meters should be safe to use.
In first pace you need to define the goal,
where sensors have to be placed to make sense for your installation,
then look for best solutions.
then - your measurement is not a critical one,
if you get somewhat offseted results, it is easy to compensate
them in max.
Ok thanks a lot, I'll let you know. I used a 5m USB cable and everything was ok, from 10m instead there was no card activity. I don't know the installation distances well, but I think 5m between USB Mac-Arduino and 2-3m between Arduino-sensors could be fine.
The sensors would go on one or two branches of a sound tree that I built like these in the picture
This could be a typical situation
Source audio, now I would like to try with arduino, 5m usb cable works. For sensor cables 0.75 is good in your opinion? Is EPS-32 to be used on arduino? Receiving OSC communication?
you don't need that thick wires, 0.2 would be really sufficient
for 2 meters cable, even 0.14 which is standard for control
kind of multicore cables would do.
Only for longer distances, one should start to calculate,
but see - wire gauge is not the only factor, also kind
and at the end resistance per meter plays a role.
now about wireless vs wired USB.
if you are confortable with 5m USB cable,
it is better to use wired sensors and arduino.
otherwise you can purchase USB extender or active cable,
which can give you 10m, but it could need extrnal power suppy to
power all sensors as well.
for wireless solution you have 2 options:
1- to connect sensors to ESP-32 and send sensor data over Wifi
UDP / OSC directly to your computer.
(ESP-32 is arduino IDE programmable)
it would need more programming than wired solution,
and you should use closed network, like one access point
to connect ESP-32 board and your computer using static IP, login etc.
On winows you can also create ad-hoc network, on mac it is
not working because apple disabled pass protected ad-hoc.
2- it is also possible to communicate over wireless serial UART
little transducers, which can easilly work 20 - 30 meters distance.
procedure is - one has 2 arduinos, and each has such one
transducer.
remote arduino collects sensor data, and sends them over to arduino on computer using wireless serial.
all that is cheap stuff, you can buy 2 nano and few LC12S transducers under 10 EURO.
https://www.satistronics.com/shop/product/180300-lc12s-uart-wireless-serial-transparent-transmition-128-channel-module-9312
I have used both options many times, and can supply you with schematics, code and any other help needed.
only unknown variable is to deal with 8 distance sensors,
because I never used that many at a time.
for wireless option, I would suggest to make distance scaling
before sending data, to keep traffic as low as possible.
I mean to detect if sensor detects something closer than 1 meter,
2 meters or not.
that are only 3 values per sensor, and can be sent only when state changes.
------
I hope this infos are understandable, let me know what you think and prefer as option.
I would probably go wireless for this, assuming it’s not a system which is mission critical.
However, easiest solution would be a good quality 10m usb extender. Search for ones compatible with the oculus headsets on Amazon. I’ve found these will still transmit 3-400mA or so across them without external power at the other end. Daisy chaining these I’ve used arduinos up to 30m away.
With an ESP32 you could power everything from a lipo battery, and save on cabling. This is getting more complex but is nice cabling-wise (Though depends on how permanent your installation is etc).
Another option that I’ve not seen here is to use a MAX485 IC at each end (you can buy these pre-made and they are cheap but excellent) which then transmits everything over rj45 Ethernet cables. You’d still need to transmit power though.
I had a test with one HC-SR04 sensor and 8m long telephone 0.15 cable
which I had laying arround, just to test worst case...
it still worked well enough with only minimal jitter.
---------
I think the difficulty in such projects is more about soldering sensors well,
and adding means of mounting them, connecting to arduino etc.
This devices are having rather wide beam and placing them
close, or pointing into more or less same direction is problematic,
increasing with distance of interest.
In a somewhat similar project with 6 Sensors on the stage,
and a need for more precise detection,
I ended sticking short cardboard tubes on sender/transmitter on each HC
and a laser pointer, to narrow the beam and easier position them.
Source audio, Yes, cardboard tubes are a good idea, better if they are made of fabric-like material, I read somewhere. Yes, the welds must be done well :-))). I don't understand how you use the laser beam
i glued small magnet on both senor board and laser to quickly and precisely mount it on the sensor, then send the light to see exactly where sensor points.
great . . .
Hi everyone, in this test I used the 5m usb cable and it works. If I use 2m cables to connect the sensor it doesn't work :)))
----------
With 10m of USB cable and with better soldering it now works
maybe you have too many unsoldered connections.
I measured my test cable - exactly 8.82m
Ok Audio source, I make connections like you and buy the 0.15 telephone wire
If you can get thicker wire, ok, I just wanted to see how far one can go
with 0.15.
I woud definitlly make connectors better then on my photo,
4 pin sockets on sensor side are ok, but must be glued together with wires onto something stiff and secure.
here is the code that I used for testing
#include <HCSR04.h>
HCSR04 hc(2, new int[8]{3, 4, 5, 6, 7, 8, 9, 10}, 8);
int x;
unsigned long Sens[8] = {0,0,0,0,0,0,0,0};
unsigned long SW[8] = {0,0,0,0,0,0,0,0};
unsigned long exSW[8] = {0,0,0,0,0,0,0,0};
void setup(){Serial.begin(9600);}
void loop(){for (int x = 0; x < 8; x++) {Sens[x] = hc.dist(x);
if (Sens[x] > 0 and Sens[x] < 100) {SW[x] = 1;}
if (Sens[x] > 100 and Sens[x] < 200) {SW[x] = 2;}
if (Sens[x] == 0 || Sens[x] > 200) {SW[x] = 0;}
if (SW[x] != exSW[x]) Serial.print(x); Serial.print(" ");
Serial.println(SW[x]); exSW[x] = SW[x];
}
delay(100);
}
using arduino library
https://www.arduino.cc/reference/en/libraries/hcsr04-ultrasonic-sensor/
ping pin 2, echo pins 3 - 10.
It is important to pull unused sensor pins to ground.
code detects 3 states,
1 = closer then 100 cm
2 = between 100 and 200 cm
0 = not detected or mr than 200 cm away,
an sends sensor state only if it changes.
and max receiver
Hello DAILON,
I was just curious to know if you could make it finally ;-).
Hi Sebastien and everyone, sorry but school has started again and I have less time. However, I did a test by soldering the wires directly to the pins and with a 5m Mac-Arduino USB and 5m 0.15 Arduino-sensor cable it works well. It detects up to just under 2 m away from the sensor. But I had to isolate the solder joints otherwise it wouldn't work. Thanks everyone, I will improve, but in the meantime a good achievement :))))
Thanks for the feedback and good luck with the next steps.
Cheers.
Cheers :)))
Hey everyone, hope is OK for me to revisit/revive this thread since I think it's relevant to the problem I am having atm.
I have a HRLV-MaxSonar-EZ0 distance sensor I am now trying to read data from within my MAX patch. The sensor is installed right above the small custom made speaker - there are 16 speakers in the sound installation. Each speaker also has an LED ring and its own Arduino board which is installed into the pre-amp box.
I have successfully used serial object to activate/deactivate LEDs but now struggling to get the data from the distance sensor. Even when I try to just print any values and physically move things in front of the speakers, there seems to be no data coming through to MAX.
I've tried the patches you listed above but without much success.
Any ideas what else I should check to firstly see if the sensor is indeed working?
Thanks!
EDIT: I just checked if the sensors are working via Arduino IDE and indeed they are.
I guess this means that I am not fetching the data properly via MAX? If it's being transmitted in bytes...do I need to do something specifically to pull it in?
HRLV-MaxSonar-EZ0 can not work with HCSR04 code.
do you use analog out pin or pwm ?
post the code you use, and how do you connect 16 arduinos to serial port .
Hi guys, is everything okay? Once school is over I'll do some more tests. I used these terminals to connect the sensor and I must say they work well. I have a cable about 4m long between the sensor and the Arduino and the detection is good up to 200cm with clothes, with reflective plastic even further. Only you have to skip a pin in the connection because the pins of the terminal are wider than the holes on the card