I have a problem with constrain() (and min() and max() for that matter) where I can still get out of bound values for one loop.
I'm trying to build a LED that fades in and out at different speeds depending on where the potentiometer is, but I have found that if the value of the potentiometer doesn't add up to exactly 0 or 255 it will ignore my constrain for one loop causing the LED to flash unevenly.
My code looks like this:
int led = 3;
int pot = A0;
int potval;
int dir = 1;
int brightness;
void setup() {
Serial.begin(9600);
pinMode(pot, INPUT);
pinMode(led, OUTPUT);
}
void loop() {
Serial.print("potval: ");
Serial.print(potval);
Serial.print("\t brightness: ");
Serial.println(brightness);
potval = map(analogRead(pot), 0, 1023, 0, 22);
analogWrite(led, brightness);
if (potval == 0) {
analogWrite(led, 0);
}
else if (potval >= 21) {
analogWrite(led, 255);
}
if (brightness <= 0 || brightness >= 255)
{
brightness = constrain(brightness, 0, 255);
dir = -dir; // switch fading direction
}
brightness += potval * dir;
delay(100);
}
How can I make sure the values are always in bounds?