简体   繁体   中英

Serial data reading from Raspberry Pi

I am trying to capture my temperature sensor reading from Arduino Uno, turn on AC if temperature is high or off and then send temperature to Raspberry Pi and write to a log file.

My Python code in Raspberry Pi to capture event and log to a file.

import time
import datetime
import serial

now = datetime.datetime.now()
month=time.strftime("%Y_%m")

#f= open(month+".txt","w+")
f=open("temperature.log","w+")

ser = serial.Serial('/dev/ttyACM0', 9600) # enable the serial port
print 'before while'
while 1: # execute the loop forever
    val=ser.readline()
    # read the serial data sent by the UNO
    f.write(now.strftime("%Y-%m-%d %H:%M"))
# print the serial data sent by UNO
    f.write(' -> ')
    f.write(val)
f.close()

I can get the temperature value (sometimes it's a mess 16707 ), but most importantly it does not write to the log file.

Where am I missing? Do I have to include another library in the Python code?

You are closing the log file at the end of each loop. It should run once, but after the file is closed, it won't write again until you open it. Just put f.close() after the while loop. Or as a better practice:

ser = serial.Serial('/dev/ttyACM0', 9600)
with open("temperature.log", "w+") as f:
    print 'before while'
    while 1:
        val = ser.readline()
        f.write(now.strftime("%Y-%m-%d %H:%M"))
        f.write(' -> ')
        f.write(val)

This will close the file automatically once the code inside the with statement is finished.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM