|
| 1 | +import csv |
| 2 | +import time |
| 3 | +import subprocess |
| 4 | +import re |
| 5 | + |
| 6 | +def get_rpi_temperature(): |
| 7 | + try: |
| 8 | + # Run vcgencmd to get temperature |
| 9 | + temp_output = subprocess.check_output(['vcgencmd', 'measure_temp']).decode() |
| 10 | + # Extract temperature value using regex |
| 11 | + temp = float(re.search(r'temp=([\d\.]+)', temp_output).group(1)) |
| 12 | + return temp |
| 13 | + except Exception as e: |
| 14 | + print(f"Error reading temperature: {e}") |
| 15 | + return None |
| 16 | + |
| 17 | +def log_temperature(): |
| 18 | + # Open CSV file in append mode |
| 19 | + with open('rpi_temperature_log.csv', 'a', newline='') as csvfile: |
| 20 | + writer = csv.writer(csvfile) |
| 21 | + # Write header if file is empty |
| 22 | + if csvfile.tell() == 0: |
| 23 | + writer.writerow(['Time Elapsed (Minutes)', 'Temperature (Celsius)']) |
| 24 | + |
| 25 | + start_time = time.time() |
| 26 | + |
| 27 | + while True: |
| 28 | + # Calculate elapsed time in minutes |
| 29 | + elapsed_minutes = (time.time() - start_time) / 60.0 |
| 30 | + # Get current temperature |
| 31 | + temperature = get_rpi_temperature() |
| 32 | + |
| 33 | + if temperature is not None: |
| 34 | + # Write to CSV |
| 35 | + writer.writerow([f"{elapsed_minutes:.2f}", f"{temperature:.2f}"]) |
| 36 | + csvfile.flush() # Ensure data is written immediately |
| 37 | + print(f"Logged: {elapsed_minutes:.2f} minutes, {temperature:.2f}°C") |
| 38 | + |
| 39 | + # Wait for 5 minutes (300 seconds) |
| 40 | + time.sleep(300) |
| 41 | + |
| 42 | +if __name__ == "__main__": |
| 43 | + try: |
| 44 | + log_temperature() |
| 45 | + except KeyboardInterrupt: |
| 46 | + print("\nLogging stopped by user") |
0 commit comments