I would like to update Button to turn the LED ON and turn it OFF whenever the button is pressed.
The problem is that the button only sometimes turns the LED ON and OFF but most of the time it works quite unreliable. Sometimes the LED is dimmed when the button is pressed and the LED is in HIGH state. Other time the LED does not stay in HIGH state only for the moment the button is pressed.
Here is the updated script.
const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin = 12; // the number of the LED pin
int LEDState = HIGH;
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT);
}
void loop() {
// read the state of the pushbutton value:
int buttonState = 0; // variable for reading the pushbutton status
buttonState = digitalRead(buttonPin);
LEDState = turnLEDOn(buttonState, LEDState);
}
int turnLEDOn(int buttonState, int LEDState) {
if (buttonState == HIGH) {
digitalWrite(ledPin, LEDState);
return LEDState == HIGH ? LOW : HIGH;
}
}
How do you have your button wired up? Your code the button pin as INPUT which means you need a pull-up or pull-down resistor attached - do you have that?
A more common wiring arrangement is to have one side of the button connected to ground and the other to a pin. Then, declare the pin as INPUT_PULLUP. This will change the logic such that HIGH = no button press and LOW = button press.
You will also need to debounce your button. They are noisy, mechanical devices that will make/break several times while you press them. Look at the File->examples->02.Digital->Debounce example. You can also try the Bounce2 library which will do all that for you.
Thank you for your help.
The debounce example does the same I wanted to achieve.
The wiring is almost identical to the Button example.
The change is:
Separate LED used on the circuit instead of the one on the board. This is why I use the pin 12.
And yes there is a pull-up resistor added just as as in the example.