python - Raspberry Pi 和 Arduino 之间的简单 2 路串行通信
问题描述
我想在我的 Raspberry Pi 和我的 Arduino 之间进行简单的 2 路串行通信。这是一个项目,我将用另一个我还没有的串行设备替换 Arduino。
我已经完成了从 Arduino 到 Raspberry Pi的单向通信(https://maker.pro/raspberry-pi/tutorial/how-to-connect-and-interface-raspberry-pi-with-arduino ),但是2路有点麻烦。我使用的 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',我没有的设备会响应。
我很感激任何帮助。谢谢你。
解决方案
我迟到了回复你,但我希望这对其他人有帮助。我试图进行双向通信,我可以从双方发送和接收字符串数据,这就是我所做的:-
Arduino 方面:-
void setup() {
Serial.begin(9600); // begin transmission
}
void loop() {
String val;
while (Serial.available() > 0) {
val = val + (char)Serial.read(); // read data byte by byte and store it
}
Serial.print(val); // send the received data back to raspberry pi
}
在覆盆子方面我有(python): -
import serial
port = "/dev/ttyACM0"#put your port here
baudrate = 9600
ser = serial.Serial(port, baudrate)
def tell(msg):
msg = msg + '\n'
x = msg.encode('ascii') # encode n send
ser.write(x)
def hear():
msg = ser.read_until() # read until a new line
mystring = msg.decode('ascii') # decode n return
return mystring
while True:
val = input() # take user input
tell(val) # send it to arduino
var = hear() # listen to arduino
print(var) #print what arduino sent
我希望很清楚 Arduino 收到来自树莓派的消息并将同样的东西发送回 Arduino。同样,你可以用它做一些其他的事情。
推荐阅读
- python - pysftp 无法创建日志文件 - 权限被拒绝
- vue.js - 为什么我的 paypal 添加到购物车按钮可以与沙盒一起使用,而我的订阅按钮却不能?
- python - pandas - 多张大纸上的 read_excel 效率
- python - 如果其他特定列与变量匹配,则更新数据库列
- regex - 值不是有效的 XML 正则表达式
- java - 字符串频率搜索未找到所有单词
- powershell - 排除任何基于关键字的发现
- .net - User.Identity.IsAuthenticated 被检查两次?
- c++ - 您好,函数上的程序(通过引用/按值传递),我不完全确定我的程序有什么问题
- authorization - 公理 - 条件编辑器