Python – pyserial – how to read and parse continuously

pyserial – how to read and parse continuously… here is a solution to the problem.

pyserial – how to read and parse continuously

I’m trying to capture data from a hardware device connected via USB to a Linux computer running ubuntu. This is a very simple script I currently have :

import serial
ser = serial. Serial('/dev/ttyUB0', 9600)
s = ser.read(10000)
print(s)
  1. How do I make this print continuously?
  2. The data is hexadecimal, I would like to explain. Should I save continuous data to a text file before doing another script analysis? Essentially, I’m trying to build a sniffer to take data and interpret it.

Thanks for your help! I’m a newbie :).

Solution

1)
Just put the read and print in the while True: section.

Example:

import serial
ser = serial. Serial('/dev/ttyUB0', 9600)
while True:
    s = ser.read(10000)
    print(s)

If you need to sniff send and receive, check out another answer for more information. https://stackoverflow.com/a/19232484/3533874

2)
To speed things up, I’ll save the data to a file without processing and have other scripts decode/process the hexadecimal data. Make sure to write to the file in binary mode.

Example:

import serial
ser = serial. Serial('/dev/ttyUB0', 9600)

# This will just keep going over and over again
with open('hexdatafile.dat', 'wb') as datafile:
    datafile.write(ser.read(10000))

Related Problems and Solutions