alicjawieloch / kama-team

repo for kama-team interns
0 stars 0 forks source link

Write a script to collect temperature data from sensors at regular intervals #5

Open ArielBleriot opened 4 months ago

ArielBleriot commented 4 months ago

Python script using Raspberry Pi to collect temperature data from a sensor ## asumption of using Adafruit_DHT library.

import Adafruit_DHT import time import csv import os

Define sensor type and GPIO pin

SENSOR = Adafruit_DHT.DHT22 PIN = 4 # GPIO pin number where the sensor is connected

Define interval (in seconds) for data collection

INTERVAL = 60

Ensure the data directory exists

data_dir = 'data' if not os.path.exists(data_dir): os.makedirs(data_dir)

Function to read temperature from sensor

def read_temperature(): humidity, temperature = Adafruit_DHT.read_retry(SENSOR, PIN) return temperature, humidity

Function to log temperature data to a CSV file

def log_temperature_data(): with open(os.path.join(data_dir, 'temperature_data.csv'), mode='a') as file: writer = csv.writer(file) writer.writerow(['Timestamp', 'Temperature (C)', 'Humidity (%)']) # Add headers while True: temperature, humidity = read_temperature() if temperature is not None and humidity is not None: timestamp = time.strftime('%Y-%m-%d %H:%M:%S') writer.writerow([timestamp, f'{temperature:.2f}', f'{humidity:.2f}']) print(f'{timestamp}: Temperature: {temperature:.2f}°C, Humidity: {humidity:.2f}%') else: print('Failed to get reading. Trying again...') time.sleep(INTERVAL)

Start logging temperature data

if name == "main": log_temperature_data()