我想在我的Raspberry Pi和我的Arduino之间进行简单的双向串行通信 . 这是一个项目,我将用另一个我还没有的串行设备替换Arduino .
我已经完成了从Arduino到Raspberry Pi的单向通信(https://maker.pro/raspberry-pi/tutorial/how-to-connect-and-interface-raspberry-pi-with-arduino),但我在使用双向时遇到了一些麻烦 . 我使用的Arduino代码来自这个例子:https://www.arduino.cc/en/Serial/Read:
int incomingByte = 0; // for incoming serial data
void setup() {
Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
}
void loop() {
// send data only when you receive data:
if (Serial.available() > 0) {
// read the incoming byte:
incomingByte = Serial.read();
// say what you got:
Serial.print("I received: ");
Serial.println(incomingByte, DEC);
}
}
我使用的Python代码是这样的:
import serial
import time
ser = serial.Serial('/dev/ttyACM1',9600)
var1 = "3"
while True:
ser.write(var1.encode())
time.sleep(0.2)
read_serial=ser.readline()
print read_serial
在浏览网络之后,我将要从ser.write('3')发送的值更改为字符串'var1',然后将'.encode()'添加到字节后进行编码 . 没有错误,但没有发生/正在写出来 .
这样做的目的是让Raspberry Pi向Arduino发送'3',并向Arduino发送'我收到的响应:3',它应该在Raspberry Pi / Python的终端窗口中打印出来 . 从那里我想我可以使我的目标更复杂,发送这样的命令:'0 30 50 100'我没有的设备会响应 .
我感谢任何帮助 . 谢谢 .
1 回答
在我的项目中,我的目标是通过串行接口 Build Arduino和Raspberry Pi之间的双向数据交换 . Raspberry Pi发送Arduino命令执行,Arduino发送Raspberry Pi传感器读数(当前是随机数) .
目前,该项目包括两个用于Raspberry Pi的脚本,用Python编写,以及一个Arduino程序 . 使用URWID库的Raspberry Pi的第一个脚本组织图形界面和命令输入,第二个脚本用于与串行端口通信 . 来源如下 . 操作的结果非常令人满意,但也许某个地方我做错了什么?这个问题的解决方案是否正确?
Arduino software:
Python GUI script
Python communication script