• Status: Solved
  • Priority: High
  • Security: Public
  • Views: 1936
  • Last Modified:

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
 
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'
>>>
0
Rama Tito
Asked:
Rama Tito
  • 2
1 Solution
 
gelonidaCommented:
you can try:

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

Open in new window

0
 
Rama TitoProgrammerAuthor Commented:
Thanks
0
 
gelonidaCommented:
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
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now