Codes for Switching a Priority Power Source with relay (voltage as input)

So, we're currently coding for a Voltage- based switching device using arduino Uno.
We will be using arduino to control which priority source (Main grid and battery- charged through piezoelectric transducers) will be used by the load depending on the value of the battery that is to be read by the arduino. We used voltage divider to input the value of the battery and that same value will be stored in voltagefinal as seen on the photo attached.

The code works fine, it switches from one relay to another as the voltages being sent to the arduino satisfy the conditions set. But what we need is for the arduino to switch on the first relay (which we set as the grid) for supplying the load whenever the detected value of the battery is below the reference voltage and then turn it off as the other relay (that is for the battery) turns on only when the voltage detected reached about 90-95% of the battery's max capacity.

Using the code below, it will immediately turn back to using the other relay as it detects a value greater than the reference while charging where in shouldn't be, not until it reaches the 90-95%. anyone who can help me modify our code?

Thank you in advance. i will be clarifying things that seems unclear.

2.jpg

1.jpg

Use the </> symbol to post your code.

Thanks.

So this is our code as of now.

// number of analog samples to take per reading
#define NUM_SAMPLES 10
#define RELAY1 7
#define RELAY2 6

int sum = 0; // sum of samples taken
unsigned char sample_count = 0; // current sample number
float voltage = 0.0; // calculated voltage
float voltagefinal = 0.0;

void setup()
{
pinMode(RELAY1, OUTPUT);
pinMode (RELAY2, OUTPUT);
Serial.begin(9600);
}

void loop()
{
// take a number of analog samples and add them up
while (sample_count < NUM_SAMPLES) {
sum += analogRead(A2);
sample_count++;
delay(50);
}
// calculate the voltage
// use 5.0 for a 5.0V ADC reference voltage
// 5.015V is the calibrated reference voltage
voltage = ((float)sum / (float)NUM_SAMPLES * 5.015) / 1024.0;
// send voltage for display on Serial Monitor
// voltage multiplied by 11 when using voltage divider that
// divides by 11. 11.132 is the calibrated voltage divide
// value
voltagefinal = (voltage * 11.132);
Serial.print(voltagefinal);
Serial.println (" V");
sample_count = 0;
sum = 0;

if (voltagefinal >= 10) {
digitalWrite(RELAY1, 0);
delay(50);
digitalWrite(RELAY2, 1);
Serial.println("Piezo Source");
} else if (voltagefinal <=2.4) {
digitalWrite(RELAY1, 1);
delay(50);
digitalWrite(RELAY2, 0);
Serial.println("Grid On");
}
}

Your code does something when the voltage is greater than or equal to 10 or when the voltage is less than or equal to 2.4

In the range, 2.4 < voltage < 10, you don't do anything. Is that what you want?