Page 1 of 1

Really simple problem

Posted: Wed Apr 15, 2020 4:29 pm
by Newby Tyro
This is on Raspberry Pi model 2b, using python 3.7.3 and Raspbian - latest version as of a week ago

I need to push some data through the pi serial port. I find that I have to call python as root user in order to be permitted to open the serial port. I import serial, open the port ttyAMA0 at 9600 baud as ser, and use ser.write(b'Hello'). This works fine. BUT I want to send a message that is not a fixed string: I use msg = input('message = ? ') to get the data - that works fine. But I haven't yet found the necessary conversion to get ser.write() to accept - I know I need bytes, but nothing I have found in the python library or in PySerial has worked - yet. I have tried many many things, but python (or the Pi) finds something wrong with all of them.

If you are thinking of being kind enough to help, please be very specific - I seem to misunderstand rather easily!!

import serial
import time
ser = serial.Serial('/dev/ttyAMA0', 9600, timeout = 4)
while True:
msg = input('message = ? ')
# here all the different attempts to manipulate msg
ser.write(.......)
rmsg = ser.read(100) #this works fine, too
....

Re: Really simple problem

Posted: Wed Apr 15, 2020 4:50 pm
by danjperron

Code: Select all

ser.write(msg.encode("utf-8"))

Re: Really simple problem

Posted: Wed Apr 15, 2020 5:13 pm
by BluPants
Try str.encode()

Re: Really simple problem

Posted: Wed Apr 15, 2020 6:49 pm
by Newby Tyro
Thanks very much!! I searched for headings such as bytes, conversion, serial, you name it, but for some reason I did not think of encode - ?

Both replies are, I believe, equivalent - so thanks to you both for this simple solution to my simple problem!!

Re: Really simple problem

Posted: Wed Jul 08, 2020 4:44 pm
by hippy
I have been battling a similar problem; trying to convert code which works fine in Python 2 and uses strings which contain 8-bit character values greater than 127 to something a Python 3 serial .write() will send accurately.

I gave up on .encode() and variants, other 'clever tricks', which did not actually work in practice, and ended up doing it by brute force creating a byte array to send. This works for me with Python 3.7.3 and using serial .write() as well as print -

Code: Select all

s = chr(0xFA) + chr(0xAF)

e = s.encode()

b = bytearray()
for c in s:
  b.append(ord(c))

print("Raw       :", len(s), s)
print("Encoded   :", len(e), e)
print("ByteArray :", len(b), b)

Code: Select all

Raw       : 2 ú¯
Encoded   : 4 b'\xc3\xba\xc2\xaf'
ByteArray : 2 bytearray(b'\xfa\xaf')

Re: Really simple problem

Posted: Wed Jul 08, 2020 5:23 pm
by PiGraham
danjperron wrote:
Wed Apr 15, 2020 4:50 pm

Code: Select all

ser.write(msg.encode("utf-8"))
Maybe that should be

Code: Select all

ser.write(msg.encode("ascii", "replace"))
To get 8 bit ascii codes. It could depend what's on the receiving side. Does it understand utf-8?