与 PC 的串行通信 Raspberry Pi

Serial Communication Raspberry Pi to PC

我正在尝试通过串行连接将 raspberry pi 连接到电脑。目标是通过串行连接从传感器发送数据,以便我可以检查它的工作情况。

Link to the serial connector.

Link to the USB adapter

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

Link to guide

我正在尝试 运行 Serial_Write 脚本。我已确保安装了 Py Serial 库 - 并且启用了串行,因为我可以通过 putty 进行连接。

#!/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