簡體   English   中英

傳感器數據在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和“檢測到運動”兩列中寫入:

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的字符串motion detected ,您需要在其周圍添加配額標記(在Python中,支持單個和雙重標記)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM