[英]Serial Communication Raspberry Pi to PC
我正在尝试通过串行连接将树莓派连接到电脑。 目标是通过串行连接从传感器发送数据,以便我可以检查其工作情况。
目前我可以使用 SSH 和使用腻子的串行连接。 我一直在使用以下指南来帮助我编写一些基本的测试代码,以确保一切正常。
我正在尝试运行 Serial_Write 脚本。 我已经确保安装了 Py Serial 库 - 并且启用了串行,因为我可以通过腻子连接。
#!/usr/bin/env python
import time
import serial
ser = serial.Serial(
port='/dev/ttyS0', #Replace ttyS0 with ttyAM0 for Pi1,Pi2,Pi0
baudrate = 9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=1
)
counter=0
while 1:
ser.write('Write counter: %d \n'%(counter))
time.sleep(1)
counter += 1
一旦我尝试运行代码,我就会收到以下错误。
Traceback (most recent call last):
File "Serial_Write.py", line 14, in <module>
ser.write('Write counter: %d \n'%(counter))
File "/home/pi/.local/lib/python3.7/site-packages/serial/serialposix.py", line 532, in write
d = to_bytes(data)
File "/home/pi/.local/lib/python3.7/site-packages/serial/serialutil.py", line 63, in to_bytes
raise TypeError('unicode strings are not supported, please encode to bytes: {!r}'.format(seq))
TypeError: unicode strings are not supported, please encode to bytes: 'Write counter: 0 \n'
没有正确编码。 我在想 Java 字节,但在 python 中字节只是 B
import time
import serial
ser = serial.Serial(
port='/dev/ttyS0', #Replace ttyS0 with ttyAM0 for Pi1,Pi2,Pi0
baudrate = 9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=1
)
counter=0
while True:
ser.write(b'Write counter: %d \n'%(counter)) #encode to bytes
print("Testing")
time.sleep(1)
counter += 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.