My name is Rodger and I just started with the Arduino on Monday. I have made a code that will turn on an LED when the button is pushed, and turn it off when the button is released. Now the object is to push the button it turns on the LED but the Led won't turn off until the button is pushed again. Can some one point me in the right direction to find out what I need to do to make this work?
It isn't after a certain number of pushes, it is when it is pressed and released the led comes on, then when it is pressed and released again the led goes off. This has to happen over and over again.
Ok I see what you are saying, but the issue is how does the arduino board know if it is supposed to turn on or turn off the led? Not trying to be difficult, I just don't understand.
Then you can simply use the Debounce example the way it is. Here is the description from the example.
Debounce
Each time the input pin goes from LOW to HIGH (e.g. because of a push-button
press), the output pin is toggled from LOW to HIGH or HIGH to LOW. There's
a minimum delay between toggles to debounce the circuit (i.e. to ignore
noise).
The full code is in your arduino menu. [File] - [Examples] - [Digital] - [Debounce]
The debounce description is kind of miss leading. It will not work the way you want.
Here is a code i just wrote that will do what you want.. Its not fancy, I wrote it in a hurry.
// set pin numbers:
const int buttonPin = 3; // the number of the pushbutton pin
const int ledPin = 13; // the number of the LED pin
// Variables will change:
int ledState = LOW; // the current state of the output pin
int buttonState; // the current reading from the input pin
void setup() {
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
}
void loop() {
if (buttonState == HIGH){ // Check if button was being pressed. (in software)
if (digitalRead(buttonPin) == LOW){ // Check if button still is being pressed. (in hardware)
buttonState = LOW; // If not, set state to low. (in software)
}
}else if (digitalRead(buttonPin) == HIGH){ // Check if button is high due to noise or being pressed
delay(50); //Debounce time
if (digitalRead(buttonPin) == HIGH){ // Button Pressed not noise
buttonState = HIGH; // Set the software check for button still being pressed
if (ledState == HIGH){ // Check state of ledPin
digitalWrite(ledPin, LOW); // Change output state (hardware)
ledState = LOW; // Change state (in software)
} else if (ledState == LOW){
digitalWrite(ledPin, HIGH);
ledState = HIGH;
}
}
}
}
The code i just posted will allow you to press the button for as little or as long as you like and only count one press. Then change the led to the opposite state. There are better ways to-do this but this seems like it will be the easiest to understand, what is actually happening, for beginners.