Reading text Data from a USB Serial Device in Python on a raspberry pi.

Programming in python is very new to me, and I’m only doing this out of necessity, as it appears it’s the most easy and common method on the raspberry pi. So, here goes…

This code reads data from a USB device which issues text on a serial port, where I can then disseminate the data.

And yes, this is initial version which hasn’t been tested 100% yet.


import serial
import time
import csv

port = '/dev/serial/by-id/usb-Prolific_Technology_Inc._USB-Serial_Controller_D-if00-port0'
#port = '/dev/ttyUSB0'
baud = 9600

ser = serial.Serial(port, baud, timeout=1)


oldline = []

while True:
        #ser_bytes = ser.readline()
        #decoded_bytes = float(ser_bytes[0:len(ser_bytes)-2].decode("utf-8"))
        line = ser.readline()                 # read bytes until line-ending
        line = line.decode(encoding='UTF-8')  # convert to string
        #line = line.rstrip('\r\n')            # remove line-ending characters
        split_line = line.splitlines()
        if oldline != split_line:      
            with open("test_data.csv","a") as f:
                for item in split_line:
                    writer = csv.writer(f,delimiter=",")
                    writer.writerow([time.time(), item])
        oldline = split_line
        #print("Keyboard Interrupt")
        #break # updated so it doesn't quit now

I have now added it here:

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at

Up ↑

%d bloggers like this: