I am trying to program my push button switch to switch on the LED if i press once and to switch off if i press again.
Below is the program i have written.. Its not performing the task i want.
Can someone please check and tell me where I have gone wrong.
int switchpin=2, ledpin=10, reading, current_state, brightness;
int initial_state=LOW;
int button_pushed(void)
{
// See if button is pushed
if (digitalRead(2))
{
// Wait for bouncing
delay(20);
// if button still pushed
if (digitalRead(2))
{
return 1;
}
}
return 0;
}
And in the main loop...
/* Wait for button to be pushed */
while (!button_pushed());
/* Turn on LED */
digitalWrite(ledpin, HIGH);
/* Wait for button to be let go */
while (button_pushed());
/* Wait for button to be pushed */
while (!button_pushed());
/* Turn off LED */
digitalWrite(ledpin, LOW);
/* Wait for button to be let go */
while (button_pushed());
while (current_state==HIGH)
{
if (brightness<=255)
{
brightness=brightness+15;
analogWrite(ledpin, brightness);
delay(200);
}
}
If this while statement is encountered when current_state contains HIGH, the body is executed. Since nothing in the body ever changes the value of current_state, the while loop will never end.
You need to change the while statement to an if statement. The loop() function takes care of the looping. Get rid of the debounce function. The delay()s in the increment/display steps will take care of any bouncing issues.
My two cens for ON OFF button. I'm an old programmer of ancient languages but new to Arduino fun. This reverses the output pin every time the button is pressed. Some of the delays are left over from other tries. I just needed a quick way to turn ON /OFF and hold that state.
while (buttonState == HIGH) {
delay(20); // debounce