简体   繁体   中英

Serial Communication Raspberry Pi to PC

I am trying to connect a raspberry pi to a pc over the serial connection. The goal is to send data from sensors over the serial connection so that I can check its working.

Link to the serial connector.

Link to the USB adapter

Currently I can SSH and Use the Serial Connection with putty. I have been using the following guide to help me get some basic test code written to make sure everything works.

Link to guide

I am trying to run the Serial_Write script. I have made sure I have the Py Serial library installed - and serial is enabled since I can connect over 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

Once I try to run the code I get the following error.

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'

Wasn't encoding correctly. I was thinking of Java Bytes, but in python Bytes are just 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM