A struggle with While Statement

Hey guys. I’m having, some trouble with a ‘‘While’’ statement. This is my code.

int PotValue = 0;
int micValue = 0;
int ledPwr;
const int redLed = 5;
const int greenLed = 2;
const int blueLed = 6;


void setup()

{

  Serial.begin(9600);
  pinMode(redLed,OUTPUT);
  pinMode(greenLed,OUTPUT);
  pinMode(blueLed,OUTPUT);
  

}



void loop(){
    PotValue = analogRead(A3);
    float voltage = PotValue * (5.0 / 1023.0);
    Serial.print("Voltage =");
    Serial.print(voltage);
    Serial.println(5);




  while (voltage < 2.5){
    micValue = analogRead(A5);
    ledPwr = map(micValue, 120,1024,255,0);
    analogWrite(redLed,ledPwr);
    delay(5);
      break;
     }

    while (voltage > 2.5){
    micValue = analogRead(A5);
    ledPwr = map(micValue, 120,1024,255,0);
    analogWrite(greenLed,ledPwr);
    delay(5);
      break;
     }

}

The problem is that the it doesn’t switch between the the two loops. it powers permanently the red led.

 while (voltage < 2.5){
    micValue = analogRead(A5);
    ledPwr = map(micValue, 120,1024,255,0);
    analogWrite(redLed,ledPwr);
    delay(5);
      break;
     }

Once in the while loop the value of the voltage variable will not change so the while loop will never end. You need to update the value of voltage inside the while loop

Hi,
Read the voltage value first then use if ... statement instead.

https://www.arduino.cc/reference/en/language/structure/control-structure/if/

So much easier to use.

Tom.. :slight_smile: