Trouble with code.

Hello,

I'm trying to read the voltage that a potentiometer is letting though and then use that value to turn on led's, but the led don't turn on (Photos of the breadboard are bellow. Sorry for the bad quality). Code:

int potentiometerPin = A0;
int led1pin = 2;
int led2pin = 3;
int led3pin = 4;
int led4pin = 5;
int led5pin = 6;
int sensorValue = 0;

void setup() {
  Serial.begin(9600);
  pinMode(led1pin, OUTPUT);
  pinMode(led2pin, OUTPUT);
  pinMode(led3pin, OUTPUT);
  pinMode(led4pin, OUTPUT);
  pinMode(led5pin, OUTPUT);
}

void loop() {
  sensorValue = analogRead(potentiometerPin);
  float voltage = sensorValue*(5.0/1023.0);
  
  if (voltage == 1.00) {
    digitalWrite(led1pin, HIGH);
  } else {
    digitalWrite(led1pin, LOW);
  }

  if (voltage == 2.00) {
    digitalWrite(led2pin, HIGH);
  } else {
    digitalWrite(led2pin, LOW);
  }

  if (voltage == 3.00) {
    digitalWrite(led3pin, HIGH);
  } else {
    digitalWrite(led3pin, LOW);
  }

  if (voltage == 4.00) {
    digitalWrite(led4pin, HIGH);
  } else {
    digitalWrite(led4pin, LOW);
  }

  if (voltage == 5.00) {
    digitalWrite(led5pin, HIGH);
  } else {
    digitalWrite(led5pin, LOW);
  }
  
  Serial.println(voltage);
  delay(1);
}

Don’t compare floats for equality. Instead, your first check could be:

  if (voltage < 1.00)
  {
    digitalWrite(led1pin, HIGH);
  }
  else
  {
    digitalWrite(led1pin, LOW);
  }

Thank you for the help. The code works perfectly. :slight_smile:

  float voltage = sensorValue*(5.0/1023.0);
 
  if (voltage == 1.00) {

you should never compare a float with exactly equal ( == ) since due to the nature of the variable type it probably never is (though theoretically it could be)
the best practice in this case would probably be to change the type to (unsigned) int and do the multiplication first to maintain acuracy

uint16_t voltage = (sensorValue * 5) / 1023;

you can consider to reduce the divider to a value that you consider to be close enough to 5v (say '1020') to make sure that the last led lights up.