Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /********* Pleasedontcode.com **********
- Pleasedontcode thanks you for automatic code generation! Enjoy your code!
- - Terms and Conditions:
- You have a non-exclusive, revocable, worldwide, royalty-free license
- for personal and commercial use. Attribution is optional; modifications
- are allowed, but you're responsible for code maintenance. We're not
- liable for any loss or damage. For full terms,
- please visit pleasedontcode.com/termsandconditions.
- - Project: # AC Monitoring
- - Source Code NOT compiled for: ESP32 DevKit V1
- - Source Code created on: 2026-01-14 18:20:41
- ********* Pleasedontcode.com **********/
- /****** SYSTEM REQUIREMENTS *****/
- /****** SYSTEM REQUIREMENT 1 *****/
- /* Monitor AC voltage, current, and power consumption */
- /* in real-time using PZEM-004T-v30 energy meter */
- /* module with ESP32 DevKit V1 for IoT energy */
- /* tracking applications. */
- /****** END SYSTEM REQUIREMENTS *****/
- /****** DEFINITION OF LIBRARIES *****/
- #include <PZEM004Tv30.h> // https://github.com/mandulaj/PZEM-004T-v30
- /****** HARDWARE CONFIGURATION *****/
- // PZEM-004T-v30 Serial Communication Pins (ESP32 Serial2)
- #define PZEM_RX_PIN 16 // GPIO16 - Receive pin for PZEM module
- #define PZEM_TX_PIN 17 // GPIO17 - Transmit pin for PZEM module
- #define PZEM_ADDR 0xF8 // Default PZEM module address (0xF8)
- #define PZEM_BAUD 9600 // Baud rate for PZEM communication
- // Serial Communication for Debug Output
- #define DEBUG_BAUD 115200 // Baud rate for Serial Monitor output
- // Timing Configuration
- #define READING_INTERVAL 2000 // Interval to read PZEM data (milliseconds)
- #define SERIAL_PRINT_INTERVAL 2000 // Interval to print data to Serial (milliseconds)
- /****** SENSOR THRESHOLDS AND LIMITS *****/
- // Over/Under Voltage Detection
- #define VOLTAGE_THRESHOLD_HIGH 260 // Over-voltage threshold (V)
- #define VOLTAGE_THRESHOLD_LOW 180 // Under-voltage threshold (V)
- #define VOLTAGE_MIN_ACTIVE 5.0 // Minimum voltage to consider mains present (V)
- // Over-Current Detection
- #define CURRENT_THRESHOLD_HIGH 25 // Over-current threshold (A)
- // Power Measurement
- #define POWER_INVALID_THRESHOLD 350 // Invalid voltage threshold for safety (V)
- /****** FUNCTION PROTOTYPES *****/
- void setup(void);
- void loop(void);
- void initializeSerialCommunication(void);
- void initializePZEMModule(void);
- void readPZEMData(void);
- void displayEnergyMetrics(void);
- void checkAlarmConditions(void);
- void handleOverVoltageAlarm(void);
- void handleUnderVoltageAlarm(void);
- void handleOverCurrentAlarm(void);
- void checkMainsPresence(void);
- /****** DEFINITION OF PZEM CLASS INSTANCES *****/
- // Create PZEM004Tv30 instance for ESP32 with hardware Serial2
- PZEM004Tv30 pzem(Serial2, PZEM_RX_PIN, PZEM_TX_PIN, PZEM_ADDR);
- /****** GLOBAL VARIABLES FOR SENSOR DATA *****/
- // Voltage measurement (V)
- float voltage = 0.0;
- // Current measurement (A)
- float current = 0.0;
- // Power measurement (W)
- float power = 0.0;
- // Energy measurement (kWh)
- float energy = 0.0;
- // Frequency measurement (Hz)
- float frequency = 0.0;
- // Power Factor (0.00 to 1.00)
- float powerFactor = 0.0;
- /****** GLOBAL VARIABLES FOR STATE MANAGEMENT *****/
- // Tracks if over-voltage alarm has been reported
- bool alarmOverVoltageActive = false;
- // Tracks if under-voltage alarm has been reported
- bool alarmUnderVoltageActive = false;
- // Tracks if over-current alarm has been reported
- bool alarmOverCurrentActive = false;
- // Tracks whether mains is detected (voltage present)
- bool mainsPresent = false;
- // Previous mains state for edge detection
- bool previousMainsState = false;
- /****** GLOBAL VARIABLES FOR TIMING *****/
- // Timestamp of last PZEM data reading
- unsigned long lastReadTime = 0;
- // Timestamp of last serial print
- unsigned long lastPrintTime = 0;
- /****** SETUP FUNCTION *****/
- void setup(void)
- {
- // Initialize serial communication for debug output
- initializeSerialCommunication();
- // Initialize PZEM-004T-v30 module
- initializePZEMModule();
- // Print startup message
- Serial.println("\n=====================================");
- Serial.println(" PZEM-004T-v30 Energy Monitor");
- Serial.println(" ESP32 DevKit V1");
- Serial.println(" Real-time AC Energy Tracking");
- Serial.println("=====================================\n");
- // Initialize timing variables
- lastReadTime = millis();
- lastPrintTime = millis();
- }
- /****** MAIN LOOP FUNCTION *****/
- void loop(void)
- {
- unsigned long currentTime = millis();
- // Read PZEM sensor data at specified interval
- if (currentTime - lastReadTime >= READING_INTERVAL)
- {
- readPZEMData();
- checkMainsPresence();
- checkAlarmConditions();
- lastReadTime = currentTime;
- }
- // Display energy metrics at specified interval
- if (currentTime - lastPrintTime >= SERIAL_PRINT_INTERVAL)
- {
- displayEnergyMetrics();
- lastPrintTime = currentTime;
- }
- }
- /****** FUNCTION IMPLEMENTATIONS *****/
- // Initialize Serial communication for debug output to Serial Monitor
- void initializeSerialCommunication(void)
- {
- // Configure Serial0 for debug output at 115200 baud
- Serial.begin(DEBUG_BAUD);
- // Brief delay to stabilize serial connection
- delay(1000);
- }
- // Initialize PZEM-004T-v30 module with hardware Serial2
- void initializePZEMModule(void)
- {
- Serial.println("Initializing PZEM-004T-v30 Energy Meter Module...");
- Serial.print("RX Pin: GPIO");
- Serial.print(PZEM_RX_PIN);
- Serial.print(" | TX Pin: GPIO");
- Serial.println(PZEM_TX_PIN);
- Serial.print("Module Address: 0x");
- Serial.print(PZEM_ADDR, HEX);
- Serial.print(" | Baud Rate: ");
- Serial.print(PZEM_BAUD);
- Serial.println(" bps");
- Serial.println("Waiting for first data reading...\n");
- // Delay to allow module initialization
- delay(2000);
- }
- // Read all measurements from PZEM-004T-v30 module
- void readPZEMData(void)
- {
- // Read voltage from PZEM module (V)
- voltage = pzem.voltage();
- // Read current from PZEM module (A)
- current = pzem.current();
- // Read active power from PZEM module (W)
- power = pzem.power();
- // Read accumulated energy from PZEM module (kWh)
- energy = pzem.energy();
- // Read mains frequency from PZEM module (Hz)
- frequency = pzem.frequency();
- // Read power factor from PZEM module (0.00 to 1.00)
- powerFactor = pzem.pf();
- }
- // Display all energy metrics to Serial Monitor
- void displayEnergyMetrics(void)
- {
- Serial.println("========== ENERGY MONITORING DATA ==========");
- // Display voltage reading with validation
- Serial.print("Voltage: ");
- if (isnan(voltage))
- {
- Serial.println("ERROR (NaN)");
- }
- else
- {
- Serial.print(voltage, 2);
- Serial.println(" V");
- }
- // Display current reading with validation
- Serial.print("Current: ");
- if (isnan(current))
- {
- Serial.println("ERROR (NaN)");
- }
- else
- {
- Serial.print(current, 2);
- Serial.println(" A");
- }
- // Display power reading with validation
- Serial.print("Power: ");
- if (isnan(power))
- {
- Serial.println("ERROR (NaN)");
- }
- else
- {
- Serial.print(power, 2);
- Serial.println(" W");
- }
- // Display energy reading with validation
- Serial.print("Energy: ");
- if (isnan(energy))
- {
- Serial.println("ERROR (NaN)");
- }
- else
- {
- Serial.print(energy, 3);
- Serial.println(" kWh");
- }
- // Display frequency reading with validation
- Serial.print("Frequency: ");
- if (isnan(frequency))
- {
- Serial.println("ERROR (NaN)");
- }
- else
- {
- Serial.print(frequency, 1);
- Serial.println(" Hz");
- }
- // Display power factor reading with validation
- Serial.print("Power Factor: ");
- if (isnan(powerFactor))
- {
- Serial.println("ERROR (NaN)");
- }
- else
- {
- Serial.print(powerFactor, 2);
- Serial.println("");
- }
- // Display mains presence status
- Serial.print("Mains Status: ");
- if (mainsPresent)
- {
- Serial.println("PRESENT");
- }
- else
- {
- Serial.println("ABSENT");
- }
- // Display alarm status indicators
- Serial.print("Alarms: ");
- if (alarmOverVoltageActive || alarmUnderVoltageActive || alarmOverCurrentActive)
- {
- if (alarmOverVoltageActive)
- {
- Serial.print("[OVER-VOLTAGE] ");
- }
- if (alarmUnderVoltageActive)
- {
- Serial.print("[UNDER-VOLTAGE] ");
- }
- if (alarmOverCurrentActive)
- {
- Serial.print("[OVER-CURRENT] ");
- }
- Serial.println("");
- }
- else
- {
- Serial.println("NONE");
- }
- Serial.println("==========================================\n");
- }
- // Check all alarm conditions and update alarm states
- void checkAlarmConditions(void)
- {
- // Only check alarms if mains is present and voltage is valid
- if (!mainsPresent || isnan(voltage) || voltage > POWER_INVALID_THRESHOLD)
- {
- return;
- }
- // Check over-voltage condition
- if (voltage > VOLTAGE_THRESHOLD_HIGH && !alarmOverVoltageActive)
- {
- handleOverVoltageAlarm();
- }
- else if (voltage <= VOLTAGE_THRESHOLD_HIGH)
- {
- alarmOverVoltageActive = false;
- }
- // Check under-voltage condition
- if (voltage < VOLTAGE_THRESHOLD_LOW && !alarmUnderVoltageActive)
- {
- handleUnderVoltageAlarm();
- }
- else if (voltage >= VOLTAGE_THRESHOLD_LOW)
- {
- alarmUnderVoltageActive = false;
- }
- // Check over-current condition
- if (!isnan(current) && current > CURRENT_THRESHOLD_HIGH && !alarmOverCurrentActive)
- {
- handleOverCurrentAlarm();
- }
- else if (isnan(current) || current <= CURRENT_THRESHOLD_HIGH)
- {
- alarmOverCurrentActive = false;
- }
- }
- // Handle over-voltage alarm (voltage exceeds 260V)
- void handleOverVoltageAlarm(void)
- {
- alarmOverVoltageActive = true;
- Serial.println("\n!!! ALARM: OVER-VOLTAGE !!!");
- Serial.print("Voltage Reading: ");
- Serial.print(voltage, 2);
- Serial.println(" V (Threshold: 260V)");
- Serial.println("Risk: Potential equipment damage");
- Serial.println("Action: Check mains supply quality\n");
- }
- // Handle under-voltage alarm (voltage drops below 180V)
- void handleUnderVoltageAlarm(void)
- {
- alarmUnderVoltageActive = true;
- Serial.println("\n!!! ALARM: UNDER-VOLTAGE !!!");
- Serial.print("Voltage Reading: ");
- Serial.print(voltage, 2);
- Serial.println(" V (Threshold: 180V)");
- Serial.println("Risk: Equipment may malfunction");
- Serial.println("Action: Check mains supply stability\n");
- }
- // Handle over-current alarm (current exceeds 25A)
- void handleOverCurrentAlarm(void)
- {
- alarmOverCurrentActive = true;
- Serial.println("\n!!! ALARM: OVER-CURRENT !!!");
- Serial.print("Current Reading: ");
- Serial.print(current, 2);
- Serial.println(" A (Threshold: 25A)");
- Serial.println("Risk: Potential short circuit or overload");
- Serial.println("Action: Check connected load and wiring\n");
- }
- // Check and update mains presence status based on voltage
- void checkMainsPresence(void)
- {
- // Determine if mains is present based on minimum voltage threshold
- if (!isnan(voltage) && voltage >= VOLTAGE_MIN_ACTIVE)
- {
- mainsPresent = true;
- }
- else
- {
- mainsPresent = false;
- }
- // Detect mains state transition
- if (mainsPresent != previousMainsState)
- {
- if (mainsPresent)
- {
- Serial.println("\n+++ MAINS DETECTED +++\n");
- }
- else
- {
- Serial.println("\n--- MAINS LOST ---\n");
- // Clear all alarms when mains is lost
- alarmOverVoltageActive = false;
- alarmUnderVoltageActive = false;
- alarmOverCurrentActive = false;
- }
- previousMainsState = mainsPresent;
- }
- }
- /* END CODE */
Advertisement
Add Comment
Please, Sign In to add comment