Serial ports are serial communication interfaces through which information is transferred sequentially one bit at a time. Parallel ports, on the other hand, transmit multiple bits simultaneously. The PySerial and functions like python serial read make communication with Serial Ports easier.
About the PySerial Package
Python on a computer with the PySerial package installed can communicate with external hardware. It is a useful package for problem solvers because it facilitates data exchange between computers and external hardware like voltmeters, flow meters, lights, and other devices that send information via ports.
Installing the Module
The PySerial package is NOT part of the Python Standard Library. Therefore, install manually. Anaconda Distributions of Python comes with the package pre-installed.
PIP Installation Command
$ pip install pyserial
Anaconda Prompt Command
> conda install pyserial
Importing the Module + Verifying Installation
After installing, the version can be verified with the following command.
import serial print(serial.version)
About the Function
Arguments – Pass an integer value to specify the number of bytes to be returned.
Returns – Provides us a number of specified bytes
Using the Python serial read function to Fetch Information From Serial Ports
Python serial read is an important function of the module. It allows us to rake in the information that is provided from the ports. Here’s a Python implementation that helps us to do so.
with serial.Serial('/my/sample1', 3443, timeout=1) as serial: readOneByte = serial.read() readTenByte = serial.read(10)
.read()reads one byte at a time. By providing an integer value, you can set how many bytes of information are to be read by the function.
Python Serial Read vs Readline
|If an integer is specified within the function, it will that return that many bytes.|
Will return 20 bytes.
|Instead of using |
Using Serial Read + Write on Raspberry Pi
Ensure that your Raspberry Pi is up to date by running the following commands
sudo apt update sudo apt upgrade
ser = serial.Serial( # Serial Port to read the data from port='/dev/ttyUSB0', #Rate at which the information is shared to the communication channel baudrate = 9600, #Applying Parity Checking (none in this case) parity=serial.PARITY_NONE, # Pattern of Bits to be read stopbits=serial.STOPBITS_ONE, # Total number of bits to be read bytesize=serial.EIGHTBITS, # Number of serial commands to accept before timing out timeout=1 ) # Pause the program for 1 second to avoid overworking the serial port while 1: x=ser.readline() print x
import time import serial ser = serial.Serial( # Serial Port to read the data from port='/dev/ttyUSB0', #Rate at which the information is shared to the communication channel baudrate = 9600, #Applying Parity Checking (none in this case) parity=serial.PARITY_NONE, # Pattern of Bits to be read stopbits=serial.STOPBITS_ONE, # Total number of bits to be read bytesize=serial.EIGHTBITS, # Number of serial commands to accept before timing out timeout=1 ) counter=0 # Mentions the Current Counter number for each line written # Pauses for one second each iteration to avoid overworking the port while 1: ser.write("Write counter: %d \n"%(counter)) time.sleep(1) counter += 1
Python Serial Read in Hex Format
.hex() function we are storing the byte data in hex format in the variable
import serial ser = serial.Serial( port='/samplePort/ttyUSB1', baudrate=115200, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout = None ) while 1: print ser.read() hexData= ser.read().hex() print hexData
Python pySerial in_waiting Function
This function can be used to retrieve the number of bytes in the input buffer.
Return(s) – Integer
Arguments – None
The function out_waiting() performs similarly. It provides the number of bytes in the output buffer.
Here’s an example program implementing the said function.
import serial ser = serial.Serial( port = '/samplePort/myUSB', baudrate = 5000, parity = serial.PARITY_NONE, stopbits = serial.STOPBITS_ONE, bytesize = serial.EIGHTBITS, timeout=0.5, inter_byte_timeout=0.1 ) # Reads one byte of information myBytes = ser.read(1) # Checks for more bytes in the input buffer bufferBytes = ser.inWaiting() # If exists, it is added to the myBytes variable with previously read information if bufferBytes: myBytes = myBytes + ser.read(bufferBytes) print(myBytes)
Python pySerial flush() function
flush() eliminates the contents of the internal buffer of a file object. It doesn’t take any arguments nor return anything. There are 2 types of flush functions:
flushInput()– Clears Input Buffer
flushOutput()– Clears Output Buffer
import serial ser = serial.Serial('/samplePort/myUSB10') # Clearing Input Buffer ser.flushInput() # Clearing Output Buffer ser.flushOutput() ser.write("get") # Pause for 100 milliseconds sleep(.1) print ser.read()
Reading Data From Arduino Boards using Python Serial Read
Arduino is an open-source electronics platform that provides easy-to-use hardware and software. Arduino boards can read inputs from sensors, a finger on a button, or a Twitter message, which they then output in the form of motors, LEDs, or even text.
import serial import time ser = serial.Serial('COM4', 9800, timeout=1) time.sleep(2) for i in range(50): # Reading all bytes available bytes till EOL line = ser.readline() if line: # Converting Byte Strings into unicode strings string = line.decode() # Converting Unicode String into integer num = int(string) print(num) ser.close()
'module' object has no attribute 'Serial'
For this problem, try renaming your project file to ‘serial.py’. Delete
serial.pyc if it exists. After that run
Furthermore, this problem occurs due to the fact that the package you’re importing has the same name as your project file.
FAQs on Python Serial Read
.read() function only receives one byte at a time. However, we can iterate the function to receive one byte at a time over multiple loops. This is quite redundant. The
.readline() will read a complete set of bytes until EOL is achieved.
We learned that with the help of the PySerial Module and Python Serial Read we are able to handle information from devices via Serial Ports.