0

Here some simple code I have written. Data is not accumulated in the CSV file; can someone share code to read data from serial port and log this to a CSV file?

import serial
import csv
import string
import os
import time
import sys

def main():
    pass

if __name__ == '__main__':
    main()
    count=0
    f=open("test.txt","w+");
    result = csv.writer(f,delimiter=',', dialect='excel-tab')

    result_statememt=("date","zenith","elevation","azimuth","conv_elevation");
    result.writerow(result_statememt)
    f.close()
    while(count<10):
        #time.sleep(60)
        ser=serial.Serial()
        ser.port=3
        ser.baudrate=9600
        ser.open()
        str=ser.read(50)
        val=str.split(":")
        lines=str.split("\r\n")
        count=count+1
        print count
        f=open("test.txt","a+")
        result=csv.writer(f,delimiter=',')
        result.writerow()
        f.close()

    f.close()
    ser.close()
1
  • 1
    result.writerow() is an error, you're not passing anything to it. Commented Dec 7, 2013 at 10:41

1 Answer 1

2

As noted, since you're not passing anything to result.writerow() nothing is being written to the CSV file. But I'm also concerned that you're reading 50 bytes at a time from the serial port, then splitting it on the : character and then splitting it on a \r\n delimiter. I don't think this is going to do what you want.

My guess is that you are expecting the serial port to deliver lines terminated by \r\n, each line consisting of a set of fields separated by :, and you want to write these fields to a CSV file. I'd recommend trying something like this instead:

with open("test.txt", "wb") as output_file:
    csv_out = csv.writer(output_file, delimiter=',', dialect='excel-tab')
    csv_out.writerow("date","zenith","elevation","azimuth","conv_elevation")

    ser=serial.Serial(port=3, baudrate=9600, timeout=60)
    ser.open()
    for count in range(10):
        str = ser.readline().rstrip()
        csv_out.writerow(str.split(':'))
    ser.close()

I haven't used the Python serial module and don't currently have hardware to test this, but based on my reading of the module documentation this should be closer to what you want to do. I think the read timeout is measured in seconds, so this will time out if the serial port doesn't produce any data for one minute.

Sign up to request clarification or add additional context in comments.

2 Comments

What's rtrim()? Perhaps you mean rstrip()?
Ack, yes, I did. Apparently some repressed PHP memory rose up when I wasn't looking. Fixing, thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.