Loops, holds and returns

im trying to get my led to hold after i fad up.
and as long as the button/ sensor is held the led stay on with out looping back to the fad up.
i also want the led to stay off when the botton/sensor is off

int LEDpin = 11;     // LED on pin 11
int switchPin = 9; // momentary switch on 9, other side connected to ground
int brightness =0;
bool running = false;

void setup() {
  pinMode(LEDpin, OUTPUT);
  pinMode(switchPin, INPUT);
  digitalWrite(switchPin, HIGH);  // turn on pullup resistor
  analogWrite(11, 0);
}

void loop() 
{

  if (digitalRead(switchPin) == LOW) {
    // switch is pressed - pullup keeps pin high normally
    delay(100);                     // delay to debounce switch
               
  for (brightness = 0; brightness <= 255; brightness += 5) {
    analogWrite(11, brightness);
    delay(50);
   
     // Wait for 30 millisecond(s)
  }

  }
  else (digitalRead(switchPin) ==HIGH); {
    analogWrite(11, 0);
    }
}

this is what i have so far

IM NEW HERE Preformatted text

Inside the if() statement (between the if() braces), but immediately after the for(){} statement (after the close brace of the for(){} statement), add another if (digitalRead(switchPin) == LOW) and make a loop that does nothing. This should hold the program until the button is released and the pin goes high.

    if (digitalRead(switchPin) == LOW) { // read the pushbutton, waiting for a LOW
      while (1); // NOP/do nothing loop
    } // at this point, the pushbutton has been released, continue to the else(){} statement 
    digitalWrite(switchPin, HIGH); // I neglected to include this when I first posted.

That 'while (1) ;' loop will freeze the sketch forever. I think you meant:

    while (digitalRead(switchPin) == LOW) { 
      // do nothing until the button is released
    } 
// at this point, the pushbutton has been released
1 Like

eek. I see. Thank you, Mr. Wasser and sorry Mr. Log.

thank you very much
adding that "while" did the job

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.