[英]How to make a variable with the inputs of 3 ultrasonic sensors with a raspberry pi and an Arduino?
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.我正在使用具有 3 个超声波传感器的 Arduino Uno,并且我已经成功地让我的树莓派打印出这些值,但我不知道如何将它们变成变量。
Here is the Arduino Code这是Arduino代码
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这是 Raspberry Pi 上的 Python 代码
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.树莓派和 Arduino 也通过 USB 连接。
Thank you for your help and ask any questions if something mentioned doesn't make sense感谢您的帮助,如果提到的内容没有意义,请提出任何问题
Are you sure the USB port you are connecting is /dev/ttyACM0
right port?您确定您连接的 USB 端口是
/dev/ttyACM0
正确的端口吗? If you type ls /dev/tty*
in Raspberry terminal it will show you connected ports.如果您在 Raspberry 终端中键入
ls /dev/tty*
,它将显示已连接的端口。
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:所以在arduino上你可以有这样的东西:
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"
这将产生类似
"21:18:10"
的输出字符串
Then on the pi you could just have the code:然后在 pi 上,您可以只使用以下代码:
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.但希望这会帮助你进步。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.