TypeError: unicode strings are not supported, please encode to bytes: 'AT\r\n'

Rama Tito
Rama Tito used Ask the Experts™
on
import serial

import os, time
 
# Enable Serial Communication
port = serial.Serial("/dev/ttyS0", baudrate=38400, timeout=1)

# Transmitting AT Commands to the Modem
# '\r\n' indicates the Enter key
 
port.write('AT'+'\r\n')
rcv = port.read(10)
print (rcv)

Open in new window

Hi, I am trying to establish communication raspberry pi 3 with SIM 900. I am facing encode issues. I did try many solution from online but didn't get through. the code are as follows with compile results; Please do advice, thanks.
-------------------------------------------------------------------------------------------------------------------
>>> 
======================= RESTART: /home/pi/my_serial.py =======================
Traceback (most recent call last):
  File "/home/pi/my_serial.py", line 11, in <module>
    port.write('AT'+'\r\n')
  File "/usr/lib/python3/dist-packages/serial/serialposix.py", line 518, in write
    d = to_bytes(data)
  File "/usr/lib/python3/dist-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: 'AT\r\n'
>>>
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
you can try:

d = to_bytes(data.encode('utf-8')

Open in new window

Rama TitoProgrammer

Author

Commented:
Thanks
python3 distinguishes between byte strings and text strings and is much less tolerant (but more predicatable) than python2.

It seems port.write()  wants to have byte strings.

so you have to convert your text to byte strings which requires that you specify an encoding.

I noticed just now, that I suggested to change the code in a python library (which is not your own code)

I assume, that what you really did was in the end something like

port.write(('AT'+'\r\n').encode('utf-8')

Open in new window


Normally it's not a good idea to change a library's code

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial