- Published on
How to Read Data from Arduino via Serial Port
- Authors
- Name
- Tinker Assist
Pyserial
We are going to be using the pyserial library. As the name would suggest, this library allows us to identify open serial COM ports, connect, to them, and send/receive data. Start by installing this through the command line.
>> pip install pyserial
Now that we have it installed, we can go ahead and write our script.
Writing the Script
First, lets import the serial.tools.list_ports class that will allow us to see which COM ports are available for receiving data on our device.
import serial.tools.list_ports
Now, we can use the library to identify which COM ports are active on our device, and create a new instance of our Serial object that will represent our Arduino
ports = serial.tools.list_ports.comports()
serialInst = serial.Serial()
Next, we can generate a list of ports in a format that is digestible for us
portsList = []
for onePort in ports:
portsList.append(str(onePort))
print(str(onePort))
Now, we want to prompt our users to select from our list of ports in the command line.
val = input("Select Port: COM")
Next, we want to take our user input and create a string value that we can assign to our Serial object instance (portVar).
for x in range(0,len(portsList)):
if portsList[x].startswith("COM" + str(val)):
portVar = "COM" + str(val)
print(portVar)
Now that we have our variable, lets go ahead and assign it to the port variable on our Serial instance, set the baud rate to the same as that on our Arduino, and open the port to receive data.
serialInst.baudrate = 9600
serialInst.port = portVar
serialInst.open()
Next, we must create an infinite loop to print our incoming data
while True:
if serialInst.in_waiting:
packet = serialInst.readline()
print(packet.decode('utf').rstrip('\n'))
And thats it! We should be seeing data pour in from our Arduino or other Serial device.
Full Script
import serial.tools.list_ports
ports = serial.tools.list_ports.comports()
serialInst = serial.Serial()
portsList = []
for onePort in ports:
portsList.append(str(onePort))
print(str(onePort))
val = input("Select Port: COM")
for x in range(0,len(portsList)):
if portsList[x].startswith("COM" + str(val)):
portVar = "COM" + str(val)
print(portVar)
serialInst.baudrate = 9600
serialInst.port = portVar
serialInst.open()
while True:
if serialInst.in_waiting:
packet = serialInst.readline()
print(packet.decode('utf').rstrip('\n'))
serial.tools.list_ports
A common question that I have asked myself and others have asked is: why isnt serial.tools.list_ports working? Its important that you import this library just as we have shown here "import serial.tools.list_ports" and not with simply "import serial" as this will not produce equivalent access