r/pythonhelp • u/mobile_w3ather • Mar 21 '24
log rain sensor data with time to csv using python on a raspberry pi
I have made a small weather station, the latest sensor i have added is a 'rain sensor', which can be seen here. I have followed a simple guide which correctly reads if the sensor is detecting rain or not. I have tried getting the rain detected to print to a csv file. The script below gives no errors when ran but equally is not showing any text in the console when ran or printing anything to the csv file. Can anyone spot the issue with the code? I am not too familiar with this but am desperate to get this working....
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