Link to home
Start Free TrialLog in
Avatar of Rama Tito
Rama TitoFlag for Malaysia

asked on

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'
>>>
ASKER CERTIFIED SOLUTION
Avatar of gelonida
gelonida
Flag of France image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Rama Tito

ASKER

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