OK, I am glad you got your original working with our help.
If you are going forward with this, I urge you to look again at the IPO solution.
while statements hang up your loop, meaning you won't be able to think about anything else, or do anything else.
while (CAPvolt -30 > (VCC / 2))
{
VCC = analogRead(VCCPin); // read input voltage
CAPvolt = analogRead(CAPpin); // read cap voltage
}
It may not matter. Take a look at
Link to : IPO model Charge / Discharge
in the wokwi simluator. Move the slider towards the LED that is illiminated. This simulates the charging and discharging.
The loop runs full speed, leaving 99 percent of the processor power left over and fully available.
// https://forum.arduino.cc/t/sketch-to-compare-voltages-for-series-parallel-capacitor-switching-circuit/1046639
const int CHARGE1pin = 2; // capacitor 1 in parallel
const int CHARGE2pin = 3; // capacitor 2 in parallel
const int DISpin = 4; // capacitors in series
const int VCCPin = A0; // Voltage sensor 'S'
const int CAPpin = A1; // Voltage sensor 'S'
int VCC = 0;
int CAPvolt = 0;
bool charging = false;
const int chargeLamp = A2; // move the slider right to simulate charging
const int dischargeLamp = A3; // move the slider left to simulate discharging
void setup () {
pinMode(CHARGE1pin, OUTPUT); // mosfet
pinMode(CHARGE2pin, OUTPUT); // mosfet
pinMode(DISpin, OUTPUT); // mosfet
pinMode(chargeLamp, OUTPUT); // lamp
pinMode(dischargeLamp, OUTPUT); // lamp
}
void loop () {
// INPUT
VCC = analogRead(VCCPin); // read input voltage
CAPvolt = analogRead(CAPpin); // read cap voltage
int difference = VCC - CAPvolt;
// PROCESS
if (charging) {
if (CAPvolt > VCC - 30)
charging = false; // stop charging!
}
else { // (not charging)
if (CAPvolt < VCC / 2)
charging = true; // start charging!
}
// OUTPUT
if (charging) {
digitalWrite(DISpin, LOW); // discharge mosfet Off
digitalWrite(CHARGE1pin, HIGH); // charge mosfet ON
digitalWrite(CHARGE2pin, HIGH); // charge mosfet ON
digitalWrite(chargeLamp, 1);
digitalWrite(dischargeLamp, 0);
}
else {
digitalWrite(CHARGE1pin, LOW); // charge mosfet Off
digitalWrite(CHARGE2pin, LOW); // charge mosfet Off
digitalWrite(DISpin, HIGH); // discharge mosfet ON
digitalWrite(chargeLamp, 0);
digitalWrite(dischargeLamp, 1);
}
}
Anything you want to add, just use the IPO model and add to the I, P and O sections of the loop.
I may not have your functionality correct, but the idea is sound.
Tip o' the hat to @paulpaulson, indefatigable proponent of IPO.
a7