I'm sure this is really a simple question, but I want to code 3 different LEDs to respond to buttons. Specifically, I want to turn it on and leave it on when the button is pushed, and then be able to turn it off and leave it off at the push of the same button. If anyone can tell me how to code this that would be great!
Use something like this
int ledState;
void loop()
{
if (digitalRead(button) == 0)
{
ledState = ! ledState;
// the NOT operator (!) toggles ledState between true and false
digitalWrite(ledPin, ledState);
}
}
connect the button between the input pin and ground
set the input pin as
INPUT_PULLUP in setup()
You should debounce the button. You can google that to see different ways
some toggle code.
//zoomkat LED button toggle test 11-08-2012
int button = 5; //button pin, connect to ground as button
int press = 0;
boolean toggle = true;
void setup()
{
pinMode(13, OUTPUT); //LED on pin 13
pinMode(button, INPUT); //arduino monitor pin state
digitalWrite(5, HIGH); //enable pullups to make pin 5 high
}
void loop()
{
press = digitalRead(button);
if (press == LOW)
{
if(toggle)
{
digitalWrite(13, HIGH); // set the LED on
toggle = !toggle;
}
else
{
digitalWrite(13, LOW); // set the LED off
toggle = !toggle;
}
}
delay(500); //delay for debounce
}
const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin = 13; // the number of the LED pin
byte oldPinState = HIGH;
void setup ()
{
pinMode (buttonPin, INPUT_PULLUP);
pinMode (ledPin, OUTPUT);
} // end of setup
void loop ()
{
byte pinState = digitalRead (buttonPin);
if (pinState != oldPinState)
{
delay (10); // debounce
if (pinState == LOW)
digitalWrite (ledPin, !digitalRead (ledPin)); // toggle pin
oldPinState = pinState; // remember new state
} // end of if pin state change
} // end of loop