Nik Hendricks
Nik Hendricks

Reputation: 573

python3 pySerial TypeError: unicode strings are not supported, please encode to bytes:

In Python 3 I imported the pySerial library so I could communicate with my Arduino Uno by serial commands.
It worked very well in Python 2.7 but in Python 3 I keep running into a error it says this

TypeError: unicode strings are not supported, please encode to bytes: 'allon'

In Python 2.7 the only thing I did differently is use raw_input but I don't know what is happening in Python 3. Here is my code

import serial, time
import tkinter
import os

def serialcmdw():
    os.system('clear')
    serialcmd = input("serial command: ")
    ser.write (serialcmd)

serialcmdw()

ser = serial.Serial()
os.system('clear')
ser.port = "/dev/cu.usbmodem4321"
ser.baudrate = 9600
ser.open()
time.sleep(1)
serialcmdw()

Upvotes: 54

Views: 167949

Answers (3)

nsr
nsr

Reputation: 895

Encode your data which you are writing to serial,in your case "serialcmd" to bytes.try the following :

ser.write(serialcmd.encode())

Upvotes: 76

Osama Dar
Osama Dar

Reputation: 454

If we have the string itself and not in a variable, we can do like this:

    ser.write(b'\x0101')

This will convert the string to bytes type

Upvotes: 7

Vichagorn Lupponglung
Vichagorn Lupponglung

Reputation: 371

i found same you problem for learn "Arduino Python Serial"
You can do another way this:

ser.write(str.encode('allon'))

Upvotes: 27

Related Questions