This code is an Arduino sketch that controls and logs...

September 2, 2025 at 09:29 PM

#include <SPI.h> #include <SD.h> #include <Wire.h> #include <RTClib.h> #define TV_RELAY 8 #define GEYSER_RELAY 9 #define SD_CS 3 #define PIR_PIN 7 #define TV_SENSOR A1 #define GEYSER_SENSOR A0 RTC_DS1307 rtc; File logFile; // Motion tracking unsigned long lastMotionTime = 0; const unsigned long MAX_INACTIVE_TIME = 2UL * 60UL * 60UL * 1000UL; // 2 hours in ms void setup() { Serial.begin(9600); // Relays pinMode(TV_RELAY, OUTPUT); pinMode(GEYSER_RELAY, OUTPUT); digitalWrite(TV_RELAY, HIGH); // Assume relay is active LOW digitalWrite(GEYSER_RELAY, HIGH); // PIR pinMode(PIR_PIN, INPUT); // RTC if (!rtc.begin()) { Serial.println("RTC not found!"); while (1); } // SD if (!SD.begin(SD_CS)) { Serial.println("SD init failed!"); while (1); } logFile = SD.open("energy.csv", FILE_WRITE); if (logFile) { logFile.println("Time,TV_Current,Geyser_Current,TV_Status,Geyser_Status"); logFile.close(); } } void loop() { // ==== Motion Detection ==== if (digitalRead(PIR_PIN) == HIGH) { lastMotionTime = millis(); // Update motion timestamp } // Check inactivity for TV if (millis() - lastMotionTime > MAX_INACTIVE_TIME) { digitalWrite(TV_RELAY, HIGH); // TV off } // ==== Read Sensors ==== float tvCurrent = analogRead(TV_SENSOR); // raw for now float geyserCurrent = analogRead(GEYSER_SENSOR); // ==== Get Time ==== DateTime now = rtc.now(); // ==== Log Data ==== logFile = SD.open("energy.csv", FILE_WRITE); if (logFile) { logFile.print(now.timestamp()); logFile.print(","); logFile.print(tvCurrent); logFile.print(","); logFile.print(geyserCurrent); logFile.print(","); logFile.print(digitalRead(TV_RELAY) == LOW ? "ON" : "OFF"); logFile.print(","); logFile.println(digitalRead(GEYSER_RELAY) == LOW ? "ON" : "OFF"); logFile.close(); } delay(5000); // log every 5s }

This code is an Arduino sketch that controls and logs the energy usage of two devices (a TV and a geyser) while monitoring motion and inactivity using a PIR sensor. Here's a detailed breakdown of what it does:

Summary:

The code monitors motion using a PIR sensor, turns a TV off after 2 hours of inactivity, logs the current (sensor readings) and relay states (ON/OFF status) of the TV and geyser to an SD card, and timestamps the logs using an RTC (Real-Time Clock).


Key Components and Features:

  1. Hardware Setup:
    • Relay control for two devices:

      • TV_RELAY (Pin 8) controls the TV.
      • GEYSER_RELAY (Pin 9) controls the geyser.
      • The relays are assumed to be active LOW (they are ON when the pin is LOW and OFF when the pin is HIGH).
    • Current sensors:

      • TV_SENSOR (Analog pin A1) measures the current (or some value) for the TV.
      • GEYSER_SENSOR (Analog pin A0) measures the current (or some value) for the geyser.
    • PIR motion detection:

      • PIR_PIN (Digital pin 7) detects motion. When motion is detected, the PIR sensor's output is HIGH.
    • SD card for logging:

      • Connected via SPI (SD_CS pin 3) to log data into a CSV file named energy.csv.
    • RTC (Real-Time Clock):

      • The RTC (DS1307) provides the current date and time for timestamping the log entries.

  1. Code Execution Flow:

    setup():

    • Sets up serial communication, pin modes for relays, and initializes the RTC, SD card, and log file:
      • Writes the CSV header (Time,TV_Current,Geyser_Current,TV_Status,Geyser_Status) to energy.csv on the SD card.
    • Ensures proper functioning of the RTC and SD card or halts the program.

    loop():

    • Motion Detection & Inactivity Handling:

      • Monitors the PIR sensor for motion (PIR_PIN). If motion is detected, it updates lastMotionTime with the current time.
      • If no motion is detected for more than 2 hours (MAX_INACTIVE_TIME), the TV is turned off by setting TV_RELAY to HIGH.
    • Sensor Readings:

      • Reads raw analog sensor values for TV_SENSOR and GEYSER_SENSOR to estimate current usage for the TV and geyser.
    • Logging Data:

      • Retrieves the current timestamp from the RTC (rtc.now()).
      • Logs the following information into energy.csv:
        • Current timestamp (time).
        • Current readings (TV_SENSOR and GEYSER_SENSOR).
        • TV relay state (ON or OFF).
        • Geyser relay state (ON or OFF).
    • Logs data every 5 seconds (delay(5000)).


  1. Key Functionalities:
    • Power Management:
      • Automatically turns off the TV after 2 hours of inactivity, conserving energy.
    • Data Logging:
      • Records the energy usage (via current sensor readings) and the ON/OFF status of devices into a file on an SD card, providing a history for monitoring.
    • Timestamping:
      • Uses a real-time clock (RTC) to timestamp the logged data for accurate records.
    • Motion Tracking:
      • Tracks motion using a PIR sensor to determine when the TV should remain ON or turn OFF due to inactivity.

Example Log Entry:

A log entry might look like this (assuming placeholders for sensor data):

2023-10-12T10:45:30,345,123,ON,OFF

This means:

  • Timestamp: 2023-10-12T10:45:30.
  • TV current: 345 (raw sensor reading).
  • Geyser current: 123 (raw sensor reading).
  • TV status: ON (relay is LOW).
  • Geyser status: OFF (relay is HIGH).

Purpose:

This code automates controlling and monitoring energy usage and logs the relevant data for analysis. It is useful for building energy-efficient systems where monitoring and optimization of device usage is important.

Generate your own explanations
Download our vscode extension
Read other generated explanations

Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node