How to make a variable with the inputs of 3 ultrasonic sensors with a raspberry pi and an Arduino?

99 Views Asked by At

I am using Arduino Uno that has 3 ultrasonic sensors and I have successfully gotten my raspberry pi to print out those values, but I don't know how to make those into into variables.

Here is the Arduino Code

    void setup() {
 Serial.begin(9600);


     void loop() {


 digitalWrite(trigPin1, LOW);
 delayMicroseconds(2);
 digitalWrite(trigPin1, HIGH);
 delayMicroseconds(2);
 digitalWrite(trigPin1, LOW);
 duration1 = pulseIn(echoPin1, HIGH);
 distance1 = (duration1/2) / 29.1;

 digitalWrite(trigPin2, LOW);
 delayMicroseconds(2);
 digitalWrite(trigPin2, HIGH);
 delayMicroseconds(2);
 digitalWrite(trigPin2, LOW);
 duration2 = pulseIn(echoPin2, HIGH);
 distance2 = (duration2/2) / 29.1;

 digitalWrite(trigPin3, LOW);
 delayMicroseconds(2);
 digitalWrite(trigPin3, HIGH);
 delayMicroseconds(2);
 digitalWrite(trigPin3, LOW);
 duration3 = pulseIn(echoPin3, HIGH);
 distance3 = (duration3/2) / 29.1;

 Serial.print(distance1);
 Serial.print(" distance1 - ");
 Serial.print(distance2);
 Serial.print("distance2 - ");
 Serial.print(distance3);
 Serial.println("distance3 - ");

Here is the Python Code on the Raspberry Pi

import serial

if __name__ == '__main__':
    ser = serial.Serial('/dev/ttyACM0', 9600, timeout=1)
    ser.reset_input_buffer()

    while True:
        if ser.in_waiting > 0:
            line = ser.readline().decode('utf-8').rstrip()
            print(line)

Also the raspberry pi and the Arduino are connected through a USB.

Thank you for your help and ask any questions if something mentioned doesn't make sense

2

There are 2 best solutions below

4
On

Are you sure the USB port you are connecting is /dev/ttyACM0 right port? If you type ls /dev/tty* in Raspberry terminal it will show you connected ports.

0
On

Following my comment, I would suggest you simplify the serial protocol to just the values and a separator.

So on the arduino you could have something like this:

String distance_output ;
distance_output = distance1 ;
distance_output += ":" ;
distance_output += distance2 ;
distance_output += ":" ;
distance_output += distance3 ;
Serial.println(distance_output.c_str());

This would produce an output string of something like "21:18:10"

Then on the pi you could just have the code:

while True:
   if ser.in_waiting > 0:

      line = ser.readline().decode('utf-8').rstrip()

      values = line.split(":")

      if len(values) == 3:   
         dist1 = int(values[0])
         dist2 = int(values[1])
         dist3 = int(values[2])

Going forward, you may want to extend this protocol to identify different sensors etc.

but hopefully this will help you progress.