Search code examples
csvarduinoexport-to-csvarduino-unopsychopy

How can I write a stream of integers with timestamps using writerow to a .csv file?


I have a continuous stream of integers I am receiving from an Arduino uno I have set up. The input is going into PsychoPy (v1.85.2) and I would like to have this stream of numbers continuously saved into a .csv file with timestamps for datalogging purposes.

I have confirmed that I'm receiving input from the Arduino using print port.readline() I'm not sure why, but the actual integer stream simply isn't writing to the .csv file. Only the timestamps are written to the .csv file.

This is my code in PsychoPy:

import serial
import time
import csv

port = serial.Serial("COM3", 9600)
# by default, the Arduino resets on connection,
# give it some time to wake-up.
time.sleep(1)


csvfile = "C:\Users\xxxx\Desktop\csvfile.csv"
while True:
    res = port.readline()
    with open (csvfile,'a') as output:
        writer = csv.writer(output)
        now = time.strftime('%d-%m-%Y %H:%M:%S')
        writer.writerow([now, res])

I'm not sure if this is an issue with the serial reading from the Arduino, the fact that I'm running it through PsychoPy, or (most likely) some error in my code. Assistance is appreciated!


Solution

  • The issue was was that port.readline() was returning a string with a \n(a new line) at the end of the string. To fix this, I used a .strip() to remove all the whitespace before and after the string and finally converted the string to a float value.

    while True:
    res = port.readline()
    resa = float(res.strip())
    with open (csvfile,'a') as output:
        writer = csv.writer(output)
        now = time.strftime('%d-%m-%Y %H:%M:%S')
        writer.writerow([resa, now])