python 中的传感器数据日志 csv

Sensor data log csv in python

我是编程新手,想为红外传感器编写代码,以便在检测到运动时在 .csv 文件中记录时间戳。到目前为止,我已经找到了检测代码,但现在需要添加代码来指定它在 csv 文件中写入一个条目。运动检测代码的学分:https://www.modmypi.com/blog/raspberry-pi-gpio-sensing-motion-detection

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
PIR_PIN = 7
GPIO.setup(PIR_PIN, GPIO.IN)

def MOTION(PIR_PIN):
print ("Motion Detected")

print ("PIR Module Test (CTRL+C to exit)")

time.sleep(2)
print ("Ready")

try:
    GPIO.add_event_detect(PIR_PIN, GPIO.RISING, callback=MOTION)
    while 1:
        time.sleep(100)

except KeyboardInterrupt:
    print("Quit")
    GPIO.cleanup()

接下来,我尝试添加以下几行内容,然后将写入两列 TIMESTAMP 和 "motion detected":

import csv
import strftime 

row = [strfttime("%a, %d %b %Y %H:%M:%S"), motion_detected]    
with open('datalog.csv', 'a') as f:
    w = csv.writer(f)
    w.writerow(row)

我只找到了从静态文件写入 CSV 的方法,因此它们似乎没有为我的问题提供直接的答案。因此,加入这些代码或更正第二个代码的任何帮助都会很棒!

import RPi.GPIO as GPIO
import time
import csv
import strftime

GPIO.setmode(GPIO.BCM)
PIR_PIN = 7
GPIO.setup(PIR_PIN, GPIO.IN)

def MOTION(PIR_PIN):
    print ("Motion Detected")

    print ("PIR Module Test (CTRL+C to exit)")

    row = [strfttime("%a, %d %b %Y %H:%M:%S"), 'motion_detected']    
    with open('datalog.csv', 'a') as f:
        w = csv.writer(f)
        w.writerow(row)

    time.sleep(2)
    print ("Ready")

try:
    GPIO.add_event_detect(PIR_PIN, GPIO.RISING, callback=MOTION)
    while 1:
        time.sleep(100)

except KeyboardInterrupt:
    print("Quit")
    GPIO.cleanup()

注意:字符串motion detected需要加引号(Python支持单引号和双引号)