Hi, I'm doing my project relay switch between 2 power source but im not sure about the connection
And this is my code
// Pin definitions
const int relayPin = 7; // Relay control pin for switching between municipality and solar
const int primaryVoltagePin = A0; // Primary voltage sensor pin (Municipality/Eskom)
const int solarVoltagePin = A1; // Solar panel voltage sensor pin
// Voltage thresholds
const float primaryThreshold = 4.9; // Threshold to confirm if the primary power is "ON" (slightly below 5V)
const float offThreshold = 0.1; // Threshold to detect when power is "OFF" (considered near zero)
const float solarLowThreshold = 2.0; // Solar panel low voltage threshold (too low to be used)
const float solarHighThreshold = 3.0;// Solar panel high voltage threshold (sufficient to be used)
void setup() {
pinMode(relayPin, OUTPUT); // Configure relay pin as output
// Start with primary source assumed available at startup
digitalWrite(relayPin, LOW); // Activate primary power
// Initialize serial communication for monitoring
Serial.begin(9600);
}
void loop() {
// Read and convert voltage readings
float primaryVoltage = analogRead(primaryVoltagePin) * (5.0 / 1023.0) ; // Voltage divider for primary
float solarVoltage = analogRead(solarVoltagePin) * (5.0 / 1023.0); // No divider for solar
// Display voltage readings on the Serial Monitor
Serial.print("Primary Voltage: ");
Serial.print(primaryVoltage);
Serial.print(" V, Solar Voltage: ");
Serial.print(solarVoltage);
Serial.println(" V");
// Decision-making based on voltage levels
if (primaryVoltage > primaryThreshold) {
// Primary power is available, switch to primary
switchToPrimary();
} else if (primaryVoltage <= offThreshold && solarVoltage > solarHighThreshold) {
// Primary power is off, but solar is sufficient, switch to solar
switchToSolar();
} else if (primaryVoltage <= offThreshold && solarVoltage <= solarLowThreshold) {
// Both sources are off, power off the system
powerOff();
}
delay(1000); // Wait 1 second before the next reading
}
// Function to switch to primary power
void switchToPrimary() {
digitalWrite(relayPin, HIGH); // Switch to municipality power
Serial.println("Switched to Primary Power (Municipality)");
}
// Function to switch to solar power
void switchToSolar() {
digitalWrite(relayPin, HIGH); // Switch to solar power
Serial.println("Switched to Backup Power (Solar)");
}
// Function to power off the system
void powerOff() {
digitalWrite(relayPin, LOW); // Turn off the relay
Serial.println("All Power Sources are OFF");
}
