#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// Define pins
#define BATTERY_PIN A0 // Analog pin for battery voltage monitoring
#define RELAY1_PIN 7 // Digital pin to control relay 1
#define RELAY2_PIN 4 // Digital pin to control relay 2
// Define voltage thresholds for each relay (adjust these according to your setup)
#define RELAY1_MAX_VOLTAGE 20.8 // Relay 1: Maximum battery voltage before diverting (28.8V)
#define RELAY1_MIN_VOLTAGE 20.0 // Relay 1: Minimum battery voltage to stop diverting
#define RELAY2_MAX_VOLTAGE 29.5 // Relay 2: Maximum battery voltage before diverting (29.5V)
#define RELAY2_MIN_VOLTAGE 25.0 // Relay 2: Minimum battery voltage to stop diverting
// Voltage divider resistors values (in ohms)
#define R1 10000.0 // 10kΩ resistor
#define R2 2000.0 // 2kΩ resistor
// Initialize the LCD with I2C address 0x27 and size 16x2
LiquidCrystal_I2C lcd(0x27, 16, 2);
// Function to read the battery voltage
float readBatteryVoltage() {
int sensorValue = analogRead(BATTERY_PIN); // Read the analog pin value (0-1023)
float voltage = sensorValue * (5.0 / 1023.0); // Convert to voltage (0-5V)
voltage = voltage * ((R1 + R2) / R2); // Convert to the actual battery voltage
return voltage;
}
void setup() {
// Initialize serial communication for debugging
Serial.begin(9600);
// Initialize the relay pins as output
pinMode(RELAY1_PIN, OUTPUT);
pinMode(RELAY2_PIN, OUTPUT);
digitalWrite(RELAY1_PIN, LOW); // Ensure relay 1 is off initially
digitalWrite(RELAY2_PIN, LOW); // Ensure relay 2 is off initially
// Initialize the LCD
lcd.begin(16, 2); // Specify the number of columns and rows
lcd.backlight(); // Turn on the LCD backlight
}
void loop() {
float batteryVoltage = readBatteryVoltage(); // Read the current battery voltage
Serial.print("Battery Voltage: ");
Serial.println(batteryVoltage); // Print the battery voltage to the serial monitor
// Display battery voltage on the LCD
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Batt Voltage:");
lcd.setCursor(0, 1);
lcd.print(batteryVoltage);
lcd.print(" V");
// Control Relay 1
if (batteryVoltage >= RELAY1_MAX_VOLTAGE) {
Serial.println("Relay 1: Over-voltage detected! Diverting load to heating element.");
digitalWrite(RELAY1_PIN, HIGH); // Activate relay 1 to divert the load
} else if (batteryVoltage <= RELAY1_MIN_VOLTAGE) {
Serial.println("Relay 1: Battery voltage normal. Stopping load diversion.");
digitalWrite(RELAY1_PIN, LOW); // Deactivate relay 1 to stop diverting the load
}
// Control Relay 2
if (batteryVoltage >= RELAY2_MAX_VOLTAGE) {
Serial.println("Relay 2: Over-voltage detected! Diverting load to heating element.");
digitalWrite(RELAY2_PIN, HIGH); // Activate relay 2 to divert the load
} else if (batteryVoltage <= RELAY2_MIN_VOLTAGE) {
Serial.println("Relay 2: Battery voltage normal. Stopping load diversion.");
digitalWrite(RELAY2_PIN, LOW); // Deactivate relay 2 to stop diverting the load
}
delay(1000); // Wait for 1 second before the next loop
}