Arduino | raspberry pi - communication

Hello everyone.I have an arduino Mega and a raspberry pi 3.I searched in the internet how to send data from arduino to raspberry and I did it.For example, I send a message and raspberry print it to my terminal.But if I have (for example) 4 ultrasonic sensors connected to arduino and want to send 4 distances to raspberry pi to do a job (for example simple if statements) ,how can I control these 4 variables?
For example , if(distance_1 <= 200) do this or if(distance_2 > 50) do that ,etc…


You want to have the RPi make decisions based on input received from the Mega and then have the Pi send actions to the Mega?


In your example, I would expect that the Mega could make the decisions itself and if the Pi needs to know the values too, they can be sent over serial as it sounds as though you have already done.

For the more general case you will have to devise a message format to share information. For your example you could send a string to the Pi like this: <5.1,2.3,5.6,8.9> Then the Pi can parse out the four values. It can send a similarly delimited string back that the Mega can use to figure out what the Pi wants it to do.

this thread discusses receiving a msg from another device and breaking the msg into sub-fields

What if I have 4 ultrasonic sensors(as I said) AND 2 motors to control and want to send info about sensors every 1 second and info about speed of motors every 0.1 seconds from mega to rpi?
Is there any links/examples to help me?

a common approach is to send “named data” in a string terminated with a \n


at 9600 bps, each character takes ~1ms. a ~30 char string is ~30ms

and anything else you can imagine

It’s a good idea to use a prefix and suffix character so you can keep the two ends in sync, although GCJS eol character gives you the same kind of thing.

For the small amount of data you want to transfer here, it should be easy to do it quickly enough and of course you can run the serial port a lot faster too.

JSON is another popular format. Overkill here though I would say.

Have you tried using the words “arduino send serial to raspberry pi” in your favorite internet search engine to find code you can use to adapt to your wants?. Now do understand not everyone wants to send the output of 4 ultrasonic sensors every second and info about speed every .01 seconds and so on and so forth. So what you ARE going to do is ADAPT what you want to the examples.

Oh, and ‘we’ don’t write RPi code on this site, typically. Meaning how the RPi does the thing will be another discussion on another forum.

Is there any example for this?

serial communication is processor agnostic