Есть некая заготовка кода: нажимаем одну клавишу - увеличивается яркость свечения светодиода, нажимаем другую - уменьшается.

Одна беда - не получается вырваться из цикла: при достижении максимальных/минимальных значений параметр переходит через крайнюю точку (а нужно, чтобы он в них останавливался). Перепробовал кучу разных вариантов - не осилил...

PHP код:
// set pin numbers:
const int redPin   = 9;   // Red LED,   connected to digital pin 9
const int buttonPin3 = 2;  //Уменьшение
const int buttonPin4 = 3;  //Увеличение


// Program variables set as integer (number) type
int redLEDValue   = 255; // Variables to store the values to send to the pins

int i = 0;     // Loop counter
int buttonState = 0;   

//setup the pins/ inputs & outputs
void setup()
{
pinMode(redPin, OUTPUT);   // sets the pins as output
pinMode(buttonPin3, INPUT);  
pinMode(buttonPin4, INPUT);
}

// Main program count to 763, a third of the way switch the incrementing of the LED
void loop() {
     
     
i += 1;      // Increment counter
     
 
buttonState = digitalRead(buttonPin3);

if (
buttonState == HIGH){ // Уменьшение

redLEDValue -= 1; // Red down
}
else if (
i < 509) // Second phase of fades
{
redLEDValue = 1; // Red low
  
}
    

  
buttonState = digitalRead(buttonPin4);

if (
buttonState == HIGH) {  // Увеличение

redLEDValue += 1; // Red up
}
else if (
i < 763) // Third phase of fades
{
redLEDValue += 1; // Red up
  
}

// analogWrite() expects 2 parameters, the object/pin and a value between 0 (off) and 255 (full on)
analogWrite(redPin,   redLEDValue);   // Write current values to LED pins


delay(50); // Pause for xx milliseconds before resuming the loop
} 
Понимаю, что решение где-то на поверхности, но...