python - python 中的传感器数据日志 csv

标签 python csv raspberry-pi sensors

我是编程新手,想为红外传感器编写代码,以便在检测到运动时在 .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,需要在其两边加上引号(Python支持单引号和双引号)。

关于python - python 中的传感器数据日志 csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37133977/

相关文章:

python - 将全角 Unicode 字符转换为 ASCII 字符

具有相同值的 Python 二维数组

python - Pandas read_csv 摆脱双引号

python - 使用 Python 脚本更改 Linux 用户名或密码

python - python 3中pickle和_pickle有什么区别?

node.js - 如何在 nodejs 中加载非常大的 csv 文件?

sql - 通过 Management Studio 从 SQL Server 2012 导出到 .CSV

raspberry-pi - 无法在 Raspberry Pi 4 上安装 docker

c - 如何在Raspberry pi中使用arm中断实现真正的ISR?

linux - 使用 qprocess 在 linux 中运行外部应用程序