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

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
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>
  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'
Rama TitoProgrammerAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

you can try:

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

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Rama TitoProgrammerAuthor Commented:
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


Open in new window

Normally it's not a good idea to change a library's code
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.