使用Python在树莓派上将雨传感器数据和时间记录到CSV文件中

0 投票
1 回答
37 浏览
提问于 2025-04-13 20:33

我做了一个小型气象站,最近添加的传感器是一个“雨水传感器”,你可以在这里看到。我按照一个简单的指南来设置,能够正确读取传感器是否检测到下雨。使用以下代码...

import RPi.GPIO as GPIO
import time

POWER_PIN = 12  # GPIO pin that provides power to the rain sensor
DO_PIN = 7     # GPIO pin connected to the DO pin of the rain sensor

def setup():
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(POWER_PIN, GPIO.OUT)  # configure the power pin as an OUTPUT
    GPIO.setup(DO_PIN, GPIO.IN)

def loop():
    GPIO.output(POWER_PIN, GPIO.HIGH)  # turn the rain sensor's power ON
    time.sleep(0.01)                   # wait 10 milliseconds

    rain_state = GPIO.input(DO_PIN)

    GPIO.output(POWER_PIN, GPIO.LOW)  # turn the rain sensor's power OFF

    if rain_state == GPIO.HIGH:
        print("The rain is NOT detected")
    else:
        print("The rain is detected")

    time.sleep(1)  # pause for 1 second to avoid reading sensors frequently and prolong the sensor lifetime

def cleanup():
    GPIO.cleanup()

if __name__ == "__main__":
    try:
        setup()
        while True:
            loop()
    except KeyboardInterrupt:
        cleanup()`

我在尝试将这些数据写入一个csv文件,每分钟记录一次,但遇到了困难。任何帮助都非常感谢...

我试过使用chatGPT,但没有成功。使用下面的代码,理论上应该可以工作,但我得到了:

return False
^
SyntaxError: 'return' outside function

import csv
import time
import RPi.GPIO as GPIO



# Function to check if rain is detected (replace this with your actual rain detection logic)
def is_rain_detected():
    POWER_PIN = 12  # GPIO pin that provides power to the rain sensor
DO_PIN = 7     # GPIO pin connected to the DO pin of the rain sensor

def setup():
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(POWER_PIN, GPIO.OUT)  # configure the power pin as an OUTPUT
    GPIO.setup(DO_PIN, GPIO.IN)

def loop():
    GPIO.output(POWER_PIN, GPIO.HIGH)  # turn the rain sensor's power ON
    time.sleep(0.01)                   # wait 10 milliseconds

    rain_state = GPIO.input(DO_PIN)

    GPIO.output(POWER_PIN, GPIO.LOW)  # turn the rain sensor's power OFF

    if rain_state == GPIO.HIGH:
        print("The rain is NOT detected")
    else:
        print("The rain is detected")

    time.sleep(1)  # pause for 1 second to avoid reading sensors frequently and prolong the sensor lifetime

def cleanup():
    GPIO.cleanup()

if __name__ == "__main__":
    try:
        setup()
        while True:
            loop()
    except KeyboardInterrupt:
        cleanup()

        return False

# Function to log rain detection event with timestamp to CSV
def log_rain_event():
    # Get current timestamp
    timestamp = time.strftime('%Y-%m-%d %H:%M:%S')

    # Get rain detection status
    rain_detected = is_rain_detected()

    # Append rain event to CSV if rain is detected
    if rain_detected:
        with open('rain_log.csv', 'a', newline='') as csvfile:
            fieldnames = ['Timestamp', 'Rain Detected']
            writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

            # Check if file is empty, if yes, write header
            if csvfile.tell() == 0:
                writer.writeheader()

            # Write the rain detection event
            writer.writerow({'Timestamp': timestamp, 'Rain Detected': 'Yes'})

# Example of how to continuously monitor the rain sensor and log events
while True:
    log_rain_event()
    time.sleep(1)  # Adjust the sleep time as needed to control the frequency of checks

import csv

import time

import RPi.GPIO as GPIO







# Function to check if rain is detected (replace this with your actual rain detection logic)

def is_rain_detected():

    POWER_PIN = 12  # GPIO pin that provides power to the rain sensor

    DO_PIN = 7     # GPIO pin connected to the DO pin of the rain sensor



def setup():

    GPIO.setmode(GPIO.BCM)

    GPIO.setup(POWER_PIN, GPIO.OUT)  # configure the power pin as an OUTPUT

    GPIO.setup(DO_PIN, GPIO.IN)



def loop():

    GPIO.output(POWER_PIN, GPIO.HIGH)  # turn the rain sensor's power ON

    time.sleep(0.01)                   # wait 10 milliseconds



    rain_state = GPIO.input(DO_PIN)



    GPIO.output(POWER_PIN, GPIO.LOW)  # turn the rain sensor's power OFF



    if rain_state == GPIO.HIGH:

        print("The rain is NOT detected")

    else:

        print("The rain is detected")



    time.sleep(1)  # pause for 1 second to avoid reading sensors frequently and prolong the sensor lifetime



def cleanup():

    GPIO.cleanup()





# Function to log rain detection event with timestamp to CSV

def log_rain_event():

    # Get current timestamp

    timestamp = time.strftime('%Y-%m-%d %H:%M:%S')



    # Get rain detection status

    rain_detected = is_rain_detected()



    # Append rain event to CSV if rain is detected

    if rain_detected:

        with open('rain_log.csv', 'a', newline='') as csvfile:

            fieldnames = ['Timestamp', 'Rain Detected']

            writer = csv.DictWriter(csvfile, fieldnames=fieldnames)



            # Check if file is empty, if yes, write header

            if csvfile.tell() == 0:

                writer.writeheader()



            # Write the rain detection event

            writer.writerow({'Timestamp': timestamp, 'Rain Detected': 'Yes'})



# Example of how to continuously monitor the rain sensor and log events

while True:

    log_rain_event()

    time.sleep(1)  # Adjust the sleep time as needed to control the frequency of checks

1 个回答

0

这句话是关于语法错误的,就像你提到的那样。

if __name__ == "__main__":
    try:
        setup()
        while True:
            loop()
    except KeyboardInterrupt:
        cleanup()

        return False

不能def 之外使用 return,因为你并没有返回任何东西。你可以把那条语句删掉,因为它对代码没有任何帮助。你也可以 raise 一个 KeyboardInterrupt,因为这就是触发 except 的原因。

撰写回答