传感器数据在python中记录csv

时间:2016-05-10 09:10:17

标签: python csv raspberry-pi sensor

我是编程新手,想要为红外传感器编写代码,以便在检测到运动时记录.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和“检测到运动”两列中写入:

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的方法,所以它们似乎没有提供我问题的简单答案。因此,加入这些代码或纠正第二个代码的任何帮助都会很棒!

1 个答案:

答案 0 :(得分:1)

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中,支持单个和双重标记)。