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

Posted on Updated on

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)
ser.flushInput()

print(ser.name)

oldline = []

while True:
    try:
        #ser_bytes = ser.readline()
        #decoded_bytes = float(ser_bytes[0:len(ser_bytes)-2].decode("utf-8"))
        #print(decoded_bytes)
        
        
        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
        
    except:
        print("exiting")
        #print("Keyboard Interrupt")
        break

I have now added it here: https://github.com/vrdriver/Serial-PI-thon

Advertisements

Leave a Reply

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

WordPress.com Logo

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

Google+ photo

You are commenting using your Google+ 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