-1

I'm trying to use my button as a switch (the led goes on after I push the button and the led goes off when I push the button again). I know I have the right circuit, because I also used a code from the internet, which looks really like mine. But my code doesn't work. The led doesn't go on. Does anyone know what is wrong with my code?

I have found the mistake now. The last 2 lines of the code were in the if statement block. But why doesn't it work then?

Here is the code i have written:

int ledPin = 8;
int buttonPin = 4;

int ledState = HIGH;      // the current state of the LED
int previousState = LOW;  // the previous state of the button
int readingState ;        // the current state of the button

void setup() {
   // put your setup code here, to run once:
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
readingState = digitalRead(buttonPin);

if(readingState == HIGH && previousState == LOW){
  if (ledState == HIGH){
    ledState = LOW;
  }

  else{
    ledState = HIGH;
    }

digitalWrite(ledPin, ledState);
previousState = readingState;

}
}
  • and doing blink (using a time based trigger) works? – ratchet freak Jul 14 '18 at 13:55
  • Yes I can get the LED blinking – jan Jul 14 '18 at 13:57
  • 1
    Why don't you use the internal pull-up resistor? Did you use one externally? If not, your input is floating and the state is undefined. – tttapa Jul 14 '18 at 15:43
  • I did use a pull up resistor – jan Jul 14 '18 at 17:25
  • 1
    If you don't update previousState on each iteration, your outermost if statement cannot be true if previousState is high, if that's your question. – tttapa Jul 14 '18 at 19:05
0

This is really easy to do if you use the Bounce2 Library. The library has an example called change.ino that does exactly what you want to do (assuming that you use a N.O. switch between GND and the Arduino pin with no external pull-up or pull-down resistor).

You could change this debouncer.interval(500); to this debouncer.interval(20); in the sketch.

0

I have found the mistake now. The last 2 lines of the code were in the if statement block. But why doesn't it work then?

previousState is set to high, and is never set again, so your if statement will never execute again because previousState is always set to high.

Moving the last line out of the if block sets previousState at every loop, and can then have a value other than HIGH, and then your if condition can be satisfied.

The penultimate line could stay in the if, or be lifted out, logically it shouldn't matter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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