Skip to content

Instantly share code, notes, and snippets.

@ThePenguin1140
Last active October 6, 2015 03:58
Show Gist options
  • Save ThePenguin1140/ccd6fc4a31a8d8e270b9 to your computer and use it in GitHub Desktop.
Save ThePenguin1140/ccd6fc4a31a8d8e270b9 to your computer and use it in GitHub Desktop.
// set pin numbers:
const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin = 10; // the number of the LED pin
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
int btncount = 0;
void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
}
void loop() {
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH:
if (buttonState && !btnCount) {
// turn LED on:
digitalWrite(ledPin, HIGH);
btncount = 1;
}
else if(buttonState && btnCount) {
// turn LED off:
digitalWrite(ledPin, LOW);
btnCount = 0;
}
}
@ThePenguin1140
Copy link
Author

TL;DR (Too Long; Didn't Read):

All you are missing is the if structures, remember that you are actually checking two variables the state of the button and the state of the light;

  if(button && light){
    turn off
  }else if(button && !light){
    turn on
  }

FYI:

! is the symbol for NOT, which flips booleans.

Note:

We don't care about Pin 13 anymore, the internal LED, so we can just ignore it. Which means any lines referencing it can be deleted.

Now if I understand correctly you want to toggle the light with the button.
So lets break that down:
If we push the button then we want to turn the light on.
If we push the button again then we turn the light off.

So already we see that there are two variables; the button, and the state of the light.
If we push the button AND the light is off then turn it on.
If we push the button AND the light is on then turn it off.

Which can be turned into the following logic structure:

  boolean lightOff = false;
  //If we push the button **AND** the light is off then turn it on.
  if(buttonPressed && lightOff){ 
    //turn the light on
    digitalWrite(ledPin, HIGH);
    lightOff = false;
  //If we push the button **AND** the light is on then turn it off. 
  }else if(buttonPressed && !lightOff){ 
    //turn the light off
    digitalWrite(ledPin, LOW);
    lightOff = true;
  }

of course lightOff can be replaced with an int which would mean we have to replace all false assignments to 0 and true to 1.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment