Morten Nissov
Morten Nissov

Reputation: 452

Reading from a sensor and writing to a CSV file

I have a sensor which prints to my COM4 port. I can read from this using serial like:

import serial
ser = serial.Serial('COM4')
while True:
    if ser.in_waiting > 0:
        temp = ser.readline()
        print(temp)

Is there an efficient way to write this to a CSV file instead of printing to the console?

The problem I'm experiencing is if I stop the script midstream then the changes to the file seem to get thrown away, even if I include a step of writing the header in before the while True loop.

Upvotes: -1

Views: 1499

Answers (3)

Daniel
Daniel

Reputation: 42778

readline is blocking, so in_waiting is not necessary.

Instead of print, just use write to a file:

import serial

port = serial.Serial('COM4')
with open("output.csv", "w") as output:
    for line in port:
        output.write(line)

Upvotes: 0

Morten Nissov
Morten Nissov

Reputation: 452

I ended up, following Pranav Hosangadi's advice, handling the sigterm call manually as

import serial
import signal

def signal_handler(signal, frame):
    global interrupted
    interrupted = True


signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
interrupted = False

if __name__ == '__main__':
    ser = serial.Serial('COM4')
    with open(filename, 'w') as f:
        while True:
            if ser.in_waiting > 0:
                temp = ser.readline()
                f.write(temp)

            if interrupted:
                break

Upvotes: 0

Thunder Coder
Thunder Coder

Reputation: 102

import csv
import serial
ser = serial.Serial('COM4')
while true:
  with open("csv-file-name.csv", 'w') as csvfile:
      writer = csv.writer(csvfile, delimiter=",")
      if ser.in_waiting > 0:
        temp = ser.readline()
        writer.writerow(temp)

Check out this page for more info.

Upvotes: 1

Related Questions