Keywords: python-3.x | arduino | pyserial
Abstract: This article addresses a common error when using pySerial in Python 3, where unicode strings cause a TypeError. It explains the difference between Python 2 and 3 string handling, provides a solution using the .encode() method, and includes code examples for proper serial communication with Arduino.
Introduction
Serial communication is essential for interfacing with devices like Arduino in Python. The pySerial library facilitates this, but migrating from Python 2 to 3 can introduce issues, particularly with string encoding.
Problem Analysis
In Python 3, strings are Unicode by default, whereas serial communication requires byte strings. The error TypeError: unicode strings are not supported, please encode to bytes: 'allon' occurs when trying to send a Unicode string via ser.write(). In Python 2, strings were bytes by default, which is why the same code worked without modification.
Solution
To resolve this, encode the string to bytes using the .encode() method. For example, replace ser.write(serialcmd) with ser.write(serialcmd.encode()). This converts the Unicode string to a byte sequence that pySerial can handle.
Code Example
Here is a revised version of the provided code, incorporating the fix:
import serial
import time
import os
def serialcmdw(ser):
os.system('clear')
serialcmd = input("serial command: ")
ser.write(serialcmd.encode()) # Encode to bytes
ser = serial.Serial()
ser.port = "/dev/cu.usbmodem4321"
ser.baudrate = 9600
ser.open()
time.sleep(1)
serialcmdw(ser)
This code initializes the serial connection and prompts for a command, encoding it before sending.
Additional Notes
Other solutions, such as using str.encode('allon') as mentioned in Answer 2, are also valid but less general. The .encode() method is preferred as it handles any string input dynamically.
Conclusion
Understanding the string encoding differences between Python 2 and 3 is crucial for successful serial communication. Always encode Unicode strings to bytes when using pySerial in Python 3 to avoid TypeErrors.