I'm controlling a floating gas ball valve, and in the setup() function I run a position calibration function to ensure that it reaches a known, slightly open position that will be set to the minimum, avoiding a flame-out condition.
The control uses a Timer1 Overflow ISR for accurate timing, which increments an OVF_count variable. This works correctly during the setup() function.
The problem arises when I open the valve for a set period of time, measured in overflows, to reach the minimum position. The while loop used to wait for a certain period of time:
while (OVF_count < min_pos);
only works when I have a print function inside it, for example:
while (OVF_count < min_pos)
{
Serial.println(OVF_count);
}
When I do this, I can see the OVF_count variable incrementing to the value I set min_pos to correctly, and executes the rest of the code correctly. However, if I leave this line out, the code stops at the line before this, seemingly looping forever like it forgot what min_pos was set to.
The craziest part of this is I have several, nearly identical while loops before this that pause the program waiting for user input, and these all work perfectly.
Here is a sample of the code that I'm running:
// Start calibration, prevent interrupt control
calibration_flag = 1;
Serial.print("Valve resetting\nPress when fully closed to calibrate..\n\n");
// Close valve until user input
digitalWrite(open_pin, 0);
digitalWrite(close_pin, 1);
while (digitalRead(button_pin)); <<<< Correctly working loops
Serial.println("Calibration starting\n");
OVF_count = 0;
// Open until set minimum flow point
digitalWrite(open_pin, 1);
digitalWrite(close_pin, 0);
while (OVF_count < min_pos); <<<< The problem line
// Stop valve
digitalWrite(open_pin, 0);
digitalWrite(close_pin, 0);
// set position tracker to calibrated minimum
cur_pos = min_pos;
Serial.println("Ignite burner");
Serial.println("Press to start..");
// Wait until user ignition
while (digitalRead(button_pin));
// End calibration, allow interrupt control
calibration_flag = 0;