nochmal kurz eine Frage:
Kann ich an diesem Code irgendetwas optimieren? Mich persönlich stört es, dass ich Uhrzeit und Datum trennen musste, aber wenn ich das mit ";" im String getrennt hätte, hätte das quotechar in der csv wieder ein ' ' davor gemacht und das will ich nicht. Gibt es dafür eine bessere Lösung?
Code: Alles auswählen
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import serial, time, struct, csv
from datetime import datetime as DateTime
ser = serial.Serial()
ser.port = "/dev/feinstaub"
ser.baudrate = 9600
ser.open()
ser.flushInput()
byte, lastbyte = "\x00", "\x00"
#STRINGS
OUTPUT_FILENAME = "/home/pi/Documents/Feinstaubdaten/Feinstaubdaten{:%Y%m%d_%H%M%S}.csv"
Name = ["Feinstaubsensor"]
Beschriftung = ["Datum","Uhrzeit","PM2.5","PM10"]
Datum = "{:%Y:%m:%d}"
Uhrzeit = "{:%H:%M:%S}"
while True:
lastbyte = byte
byte = ser.read(size=1)
if lastbyte == "\xAA" and byte == "\xC0":
sentence = ser.read(size=9)
readings = struct.unpack('<HHxxBBB',sentence)
pm_25 = readings[0]/10.0
pm_10 = readings[1]/10.0
with open(OUTPUT_FILENAME.format(DateTime.now()), 'a') as csvfile:
output = csv.writer(csvfile, delimiter=';', escapechar=' ', quoting=csv.QUOTE_NONE)
output.writerow(Name)
output.writerow(Beschriftung)
output.writerow([Datum.format(DateTime.now()), Uhrzeit.format(DateTime.now()), pm_25, pm_10])
time.sleep(5)