This is my code for my project. The code works as when the voltage is greater than 10.68volts the first relay is active, but when its low than 10.68v it switches to relay 2. the relays are connected to two different batteries but the same load. The code does not work as needed, both relay are on continuously when input in arduino. but it should be like one relay must be on at a time
// Voltage sensor data starts
#define ANALOG_IN_PIN A0
const int analogInPin1 = A0;
// Floats for ADC voltage & Input voltage
float adc_voltage = 0.0;
float in_voltage = 0.0;
// Float for Reference Voltage
float ref_voltage = 3.27;
// Integer for ADC value
int adc_value = 0;
//voltage sensor data ends
// Floats for resistor values in divider (in ohms)
float R1 = 30000.0;
float R2 = 7500.0;
//set point
int setPoint = in_voltage > 10.68; // Initial value of setPoint (analog value)
int setPoint1 = in_voltage < 10.68;
// motor pins starts
int motor1pin1 = 2;
int motor1pin2 = 3;
int motor2pin1 = 4;
int motor2pin2 = 5;
//relay data starts
int relay1 = 6;
int relay2 = 7;
//relay data ends
void setup() {
// Motor data starts
pinMode(motor1pin1, OUTPUT);
pinMode(motor1pin2, OUTPUT);
pinMode(motor2pin1, OUTPUT);
pinMode(motor2pin2, OUTPUT);
//(Optional)
pinMode(9, OUTPUT);
pinMode(10, OUTPUT);
//relay data starts
pinMode(relay1, OUTPUT);
pinMode(relay2, OUTPUT);
//ends
//start serial Monitor
// Setup Serial Monitor
Serial.begin(9600);
Serial.println("DC Voltage Test");
}
void loop() {
// Read the Analog Input
adc_value = analogRead(ANALOG_IN_PIN);
// Determine voltage at ADC input
adc_voltage = (adc_value * ref_voltage) / 1024.0;
// Calculate voltage at divider input
in_voltage = adc_voltage / (R2/(R1+R2)) ;
// Print results to Serial Monitor to 2 decimal places
Serial.print("Input Voltage = ");
Serial.println(in_voltage, 2);
// put your main code here, to run repeatedly:
//Controlling speed (0 = off and 255 = max speed):
//(Optional)
analogWrite(9, 100); //ENA pin
analogWrite(10, 200); //ENB pin
//(motor drive start)
digitalWrite(motor1pin1, HIGH);
digitalWrite(motor1pin2, LOW);
digitalWrite(motor2pin1, HIGH);
digitalWrite(motor2pin2, LOW);
if (analogRead(analogInPin1) > setPoint) {
relay1 = 1;
digitalWrite(relay1,LOW);
delay(4000);
}
else {
relay1 = 0;
digitalWrite(relay1,HIGH);
delay(1000);
}
if (analogRead(analogInPin1) > setPoint1) {
relay2 = 1;
digitalWrite(relay2,LOW);
delay(4000);
}
else {
relay2 = 0;
digitalWrite(relay2,HIGH);
delay(1000);
}
// wait 10 millisecond before the next loop
delay(1000);
}