Reputation: 41
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.
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.
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'
Upvotes: 1
Views: 869
Reputation: 41
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
Upvotes: 2