#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_ILI9341.h>
#include <PZEM004Tv30.h>
#define TFT_CS 5
#define TFT_DC 22
#define TFT_RST 21
#define RELAY_PIN 18
#define LAMP1_PIN 32
#define LAMP2_PIN 33
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC, TFT_RST);
PZEM004Tv30 pzem(Serial2, 16, 17); // Specify the serial port and the pins used for RX and TX
void setup() {
// Initialize Serial
Serial.begin(115200);
Serial2.begin(9600); // Initialize Serial2 for PZEM-004T
// Initialize TFT display
tft.begin();
tft.setRotation(1);
tft.fillScreen(ILI9341_BLACK);
tft.setTextColor(ILI9341_WHITE);
tft.setTextSize(2);
// Initialize Relay
pinMode(RELAY_PIN, OUTPUT);
digitalWrite(RELAY_PIN, LOW); // Start with relay off
// Initialize Lamp Pins
pinMode(LAMP1_PIN, OUTPUT);
pinMode(LAMP2_PIN, OUTPUT);
digitalWrite(LAMP1_PIN, LOW);
digitalWrite(LAMP2_PIN, LOW);
// Initialize PZEM-004T
pzem.setAddress(0x01);
}
void loop() {
// Read data from PZEM-004T
float voltage = pzem.voltage();
float current = pzem.current();
float power = pzem.power();
float energy = pzem.energy();
float frequency = pzem.frequency();
float pf = pzem.pf();
// Update TFT Display
tft.fillScreen(ILI9341_BLACK);
tft.setCursor(0, 0);
tft.print("Voltage: ");
tft.print(voltage);
tft.println(" V");
tft.print("Current: ");
tft.print(current);
tft.println(" A");
tft.print("Power: ");
tft.print(power);
tft.println(" W");
tft.print("Energy: ");
tft.print(energy);
tft.println(" Wh");
tft.print("Frequency: ");
tft.print(frequency);
tft.println(" Hz");
tft.print("PF: ");
tft.print(pf);
// Example relay control logic
if (voltage > 230) {
digitalWrite(RELAY_PIN, HIGH); // Turn on relay
digitalWrite(LAMP1_PIN, HIGH); // Turn on Lamp1
digitalWrite(LAMP2_PIN, HIGH); // Turn on Lamp2
} else {
digitalWrite(RELAY_PIN, LOW); // Turn off relay
digitalWrite(LAMP1_PIN, LOW); // Turn off Lamp1
digitalWrite(LAMP2_PIN, LOW); // Turn off Lamp2
}
delay(1000); // Update every second
}