如何解决到PC的串行通信Raspberry Pi
我正在尝试通过串行连接将树莓派连接到PC。目的是通过串行连接从传感器发送数据,以便我可以检查其工作情况。
目前,我可以SSH并使用腻子使用串行连接。我一直在使用以下指南来帮助我编写一些基本的测试代码,以确保一切正常。
我正在尝试运行Serial_Write脚本。我已经确保安装了Py串行库-并启用了串行,因为我可以通过腻子进行连接。
#!/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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。