-1

I am trying to program a sketch such that an LED will light up for as long as a push button is pressed down. I have tested the components and electronics configuration before with a simpler program, and it all works, but there seems to be a problem in the code. I wanted to know how my sketch may be altered so the code will work:

const int ledPin = 12;
const int switchPin = 2;
const int Time = 100;
int buttonState = 0;
int count = 0;
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(switchPin, INPUT); 
}

void loop() {
buttonState = digitalRead(switchPin);
while (buttonState == HIGH) {
    count++;
    delay(100);
  }
  count=count*10;

  if (count>1) {
    digitalWrite(ledPin, HIGH);
    delay((count*10));
    digitalWrite(ledPin, LOW);
  }

}
4
  • And how exactly this doesn't work?
    – gre_gor
    Commented Aug 8, 2018 at 22:30
  • @gre_gor there is no response from the LED at all, regardless of how long, or much I press the button. When I use a simpler button-light up sketch, it works perfectly, but not with this code Commented Aug 8, 2018 at 22:46
  • 1
    Why do you increase the count value? Should the led be longer on each time the button is pressed. If so, please add that to your question. Hint: nothing stops the while.
    – Jot
    Commented Aug 8, 2018 at 22:57
  • Are you also trying to see how long the button was pressed down for?
    – VE7JRO
    Commented Aug 8, 2018 at 23:38

2 Answers 2

3
while (buttonState == HIGH) {
    count++;
    delay(100);
}

this will never exit when the button is ever high. You should also reset count after the if.

Instead you want to either do buttonState = digitalRead(switchPin); inside the loop or rejig the function to be a state machine using timestamps like blink without delay.

-1

Try installing a 1-10k resistor to ground connected to the input pin switchPin, assuming that the pushbutton is connecting 5V to switchPin. This will force a true logic 0 when the button is not pressed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.