For a university project, I need to write a python script that uses the data of some Arduino ultrasonic sensors. I managed to glue together a way to read one using tutorials found on google, but I don't really know if it's applicable to more of them.
Here's the Arduino code:
int trigPin = 11; // Trigger
int echoPin = 12; // Echo
long duration, cm, inches;
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(5);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
cm = (duration/2) / 29.1; // Divide by 29.1 or multiply by 0.0343
Serial.print(cm);
Serial.println();
delay(250);
}
Just a basic ultrasonic sensor code, easy to add more sensors if needed.
And here is the python code, where the problem lies.
import serial
import time
ser = serial.Serial('COM7', 9800)
time.sleep(2)
while True:
line = ser.readline() # read a byte
if line:
string = line.decode() # convert the byte string to a unicode string
num = int(string) # convert the unicode string to an int
print(num)
ser.close()
I'm going tp admit that I really get 100% how the python script is reading the serial output from the Arduino, but I tested it and it worked.
My question is, can this method be used with more than one sensor, and if it can, how can I implement it?
Yes you can - I've run 5 ultrasonic sensors on an Arduino transmitting the results over serial to a python program.
You can either read all the distances at the same time and send them in a single string with a separator. Eg. "12:23:45”. In python use string.split(':')
to separate into individual values.
Or send them one at a time with an identifier (useful if sensors are read at different rates). Eg "dist1:12" and "dist2:23" and use the same split()
function to separate the identifier and the value.