到PC的串行通信Raspberry Pi

问题描述

我正在尝试通过串行连接将树莓派连接到PC。目的是通过串行连接从传感器发送数据,以便我可以检查其工作情况。

Link to the serial connector.

Link to the USB adapter

目前,我可以SSH并使用腻子使用串行连接。我一直在使用以下指南来帮助我编写一些基本的测试代码,以确保一切正常。

Link to guide

我正在尝试运行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