Search code examples
pythonstringarduinoserial-portexport-to-csv

How to read Serial data with Python from more then one Arduino ADC?


I am begginer in Python. I am trying to write serial port data from Arduino to CSV file in Python. I want to save data in format: time, sensor1, sensor2 as numbers allowing to open them in Excel in separate columns. My code allows to obtain CSV as follows:

12:25:57,"294,293" I cannot remove the quotations.

My Arduino code for serial output:

Serial.print(sensorValue_1);
Serial.print(",");
Serial.println(sensorValue_2);
delay(1000);

My Python code:

import csv
import serial
import time

ser=serial.Serial("COM15", 9600)
ser.flushInput()

while True:
    ser_bytes = ser.readline().decode().strip()


    t = time.localtime()
    decoded_time = time.strftime('%H:%M:%S', t)
    print(decoded_time, ser_bytes)
    with open("test_file.csv", "a", newline='') as f:
        writer = csv.writer(f, delimiter = ",")
        writer.writerow([decoded_time, ser_bytes])
        f.close()

I will appreciate the help.


Solution

  • I edited your code and add some comments. try this if this is what you need.

    import csv
    import serial
    import time
    
    ser=serial.Serial("COM15", 9600)
    ser.flushInput()
    
    while True:
        #use split(',') to seperate ser_byte string to list
        ser_bytes = ser.readline().decode().strip().split(',')
    
        # using list comprehension to perform conversion to int
        new_ser_bytes = [int(i) for i in ser_bytes]
    
        #new_ser_bytes[0] is sensorValue_1
        #new_ser_bytes[1] is sensorValue_2
        
        t = time.localtime()
        decoded_time = time.strftime('%H:%M:%S', t)
        #print(decoded_time, ser_bytes)
        with open("test_file.csv", "a", newline='') as f:
            writer = csv.writer(f, delimiter = ",")
            #writerow with seperate sensorValue
            writer.writerow([decoded_time, new_ser_bytes[0], new_ser_bytes[1]])
            f.close()