How to turn off aLED after pushing a button multiple times

Hey i am very new to Arduino and just getting started. I made the following program in which one button is turning the LED on and another is turning the LED off.

int ledPin = 5;
int buttonApin = 9;
int buttonBpin = 8;

byte leds = 0;

void setup() 
{
  pinMode(ledPin, OUTPUT);
  pinMode(buttonApin, INPUT_PULLUP);  
  pinMode(buttonBpin, INPUT_PULLUP);  
}

void loop() 
{
  if (digitalRead(buttonApin) == LOW)
  {
    digitalWrite(ledPin, HIGH);
  }
  if (digitalRead(buttonBpin) == LOW)
  {
    digitalWrite(ledPin, LOW);
  }
}

Now onto my question is it possible to let "buttonBpin" (in my example) to shut the LED off after i press the button a defined amount of times(like 4 for example)? I can turn the LED on and off after pressing the buttons once but i am stuck going further than that.
Thank you in advance.

Sure. Start investigating the library "button.h".

Suggest you a avoid doing things in code based on a switches state, rather, look at when your switches change their state.

It’s a simple matter of incrementing a counter variable and based on a the value do what’s needed.

Just watch out for contact bounce in the switches. You need some way to respond to a press once and only once.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.