sak1195
sak1195

Reputation: 11

Do while loop runs more than once with flag set?

I am having trouble getting this loop to only run once. I have a flag set and my understanding is it will run through once, change flag = 1, then not run through again but when I execute it, the loop runs over and over again. Any help is appreciated.

EDIT: The issue I'm finding is even when my voltage satisfies the if statement, the loop continues to run.

voltage = analogRead(A0); //reads in voltage from pin A0
Serial.println(voltage);

//Calibration routine
do {
  if ((voltage >= 1) && (voltage <= 10)) {
    //while the voltage is between 4.88 and 48.8 mV the calibration light will flash once
    //this ensures the voltage is above 0 and lower than the threshold for the max voltage routine
    digitalWrite(calibrationLED, HIGH);
    delay(2000);
    digitalWrite(calibrationLED, LOW);
    delay(1000);
    digitalWrite(calibrationLED, HIGH);
    delay(2000);
    Serial.println("Calibrated");
    delay(5000);
    voltageInitial = analogRead(A0);
    //stores the initial voltage to a separate variable, does not change over the course of the crimp
    Serial.println("Initial Voltage: ");
    Serial.println(voltageInitial);
    flag = 1;
  }
} while (flag == 0);

Upvotes: 0

Views: 137

Answers (4)

gre_gor
gre_gor

Reputation: 6776

You are waiting for the voltage variable to change, without actually changing it (reading from analog pin).

You need to add voltage = analogRead(A0); into your loop.

do
{
    voltage = analogRead(A0);
    if ((voltage >= 1) && (voltage <= 10))   //while the voltage is between 4.88 and 48.8 mV the calibration light will flash once
    {                                        //this ensures the voltage is above 0 and lower than the threshold for the max voltage routine 
        ...

        flag = 1;
    }
} while (flag == 0);

Upvotes: 0

DTdev
DTdev

Reputation: 562

This is an infinite loop actually until the value of the voltage comes between 1 to 10. so flag=1 should be out of the if condition. Otherwise you can add a break after if condition is finished. It will execute exactly once after the condition.

Upvotes: 2

dbush
dbush

Reputation: 224417

The flag variable will only get set to 1 if the if condition is true. This happens when voltage has a value from 1 to 10.

If the value of voltage is not in the range 1 - 10, flag will not be set. And since voltage is never modified inside of the loop, you have an infinite loop.

Upvotes: 5

vivi
vivi

Reputation: 334

"the loop runs over and over again. " It smells the loop never enter inside if ((voltage >= 1) && (voltage <= 10)) , thus never set flag = 1;

So naturally it keep running.

Upvotes: 4

Related Questions