我正在尝试做一个项目,基本上是一个Raspberry PI尝试将数据发布到Arduino,然后Raspberry PI将捕获数据。问题是,接收到的数据是字节。我想将数据打印到Raspberry PI。这是我的Raspberry代码:
import serial
import time
import encodings
s = serial.Serial('/dev/ttyACM1', 9600) # change name, if needed
s.close()
s.open()
time.sleep(5) # the Arduino is reset after enabling the serial connection, therefore we have to wait
a = "test"
s.write(a.encode())
try:
while True:
response = s.readline()
response.decode(encoding="utf-8")
print(response)
except KeyboardInterrupt:
s.close()
这是arduino代码:
void setup() {
Serial.begin(9600);
}
void loop() {
if (Serial.available()) {
byte nr = Serial.read();
Serial.print("The following char was received: ");
Serial.println(nr,DEC);
}
}
这是不带x.decode('utf-8)的输出:
b'The following char was received: 116\r\n'
这是x.decode('utf-8')的输出:
b'The following char was received: 116\r\n'
似乎没有用。我的代码有问题吗?
Arduino从您的“测试”接收到第一个字节“ t”。
[Serial.println('t', DEC);
将发送116\r\n
。
您明确地告诉Arduino将字节值116的't'转换为字节序列49,49,54(='1','1','6')
尝试用Serial.println(nr);
代替Serial.println(nr, DEC);
将代码更改为:
if (Serial.available()) {
char nr = (char) Serial.read();
Serial.print("The following char was received: ");
Serial.println(nr);
}
[Serial.read()返回一个整数,如果您希望将其作为一个char,则需要将其强制转换为char。