HELP- Turn on a LED while a push button is pressed 4 times or more per second

Hi. I’m trying to make a project that turn on a LED while a button is pressed with a frequency of 4 times or more per second.

For exemple: I’m pressing the button with a frequency of 4 times per second. The LED turn on but if I dicrease the frequency to 2 times per second, I want the LED being turned off.

Basicly, I want the LED on while the button is being pressed with a frequency of 4 times or more per second.

I have made this code. It turns on the led when the push button frequency is 4 times or more per second but it doesn’t turn off the led when the frequency decreases.

const int buttonPin = 2; //input button 
const unsigned long T = 1000; //one second
int ledPin = 13; // LED output pin

unsigned long t0 = 0;
int n_pulses = 0;

void setup()
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);

void loop()
  t0 = millis();
  n_pulses = 0;
  while((millis() - t0) <= T)
    if(digitalRead(buttonPin) == HIGH)
      while(digitalRead(buttonPin) == HIGH);
      if(n_pulses > 3){
      digitalWrite(ledPin, HIGH); 

Does anyone can help me solving this?

Take a look at part 3 of Using millis() for timing. A beginners guide

It has an example of counting button presses in a period

Nowhere in that code do you ever switch the LED off. So once it has been switched on it will stay on for ever.

Currently you say "if n_pulses is > 3 switch the LED on. Perhaps you also need an 'else digitalWrite (ledPin, LOW);' to switch it off.