how to set time on digitalRead to count pulses

Hey everyone I need your help on how to set a time on when the arduino will read pulses. I want to make the arduino read how many high pulses it gets in 1 second then display it after that given time rather than displaying the high pulses incrementing. I'm using Arduino Mega 2560.

This is the code I used:

int pulsePin = 52;
int ledPin = 13;
unsigned long highCounter = 0;
int pulse = 0;
int lastPulse = LOW;
 
void setup() {
   pinMode(pulsePin, INPUT);
   pinMode(ledPin, OUTPUT);
   digitalWrite(pulsePin, HIGH);   
   Serial.begin(4800);
}
 
void loop() {
  pulse = digitalRead(pulsePin);
  if (pulse != lastPulse) {
    digitalWrite(ledPin, pulse);
    Serial.println(pulse);
    lastPulse = pulse;
    if (pulse == HIGH) highCounter++;
    Serial.println(highCounter);
  } 
}

Hello and welcome :slight_smile:

Something like that maybe:

unsigned long oldMillis = 0;

void loop() {
  pulse = digitalRead(pulsePin);
  if (pulse != lastPulse) {
    digitalWrite(ledPin, pulse);
    Serial.println(pulse);
    lastPulse = pulse;
    if (pulse == HIGH) highCounter++;
  } 

  // print and reset highCounter every seconds
  if ( millis() - oldMillis >= 1000 )
  {
    oldMillis = millis();
    Serial.println(highCounter);
    highCounter = 0;
  }
}

Sorry this was the code that i used ignore the first one..
i got this code from http://note19.com/2008/12/29/pulse-counter/#comment-5221

int pulsePin = 3;
int ledPin = 13;
unsigned long highCounter = 0;
unsigned long duration = 0;
int pulse = 0;
int lastPulse = LOW;
unsigned long timeNow = 0;
unsigned long lastTime = 0;
 
void setup() {
   pinMode(pulsePin, INPUT);
  // enable the 20K pull-up resistor to 
  // steer the input pin to a HIGH reading.
   digitalWrite(pulsePin, HIGH);   
   Serial.begin(9600);
   Serial.println("Pulse Reader - Version 2");
}
 
void loop() {
  pulse = digitalRead(pulsePin);
  if (pulse != lastPulse) { // pulse has changed
    timeNow = millis();
    duration = timeNow - lastTime;
    // blink the LED
    digitalWrite(ledPin, pulse);
    Serial.print(pulse);
    Serial.print(" ,");
    Serial.println(duration);
    lastPulse = pulse;
    lastTime = timeNow;
    if (pulse == HIGH) highCounter++;
  } 
}

So what does that code do that you don't want it to, or not do that you want it to?

Where are you testing that less time has elapsed than the length of time you want to count pulses in?

Where are you resetting the counter? Where are you resetting the time that pulse counting started?

Thanks guix I tried the code you sent me and it diplayed after the time delay that was set

if ( millis() - oldMillis >= 1000 )

but when the pulses were sent mid the time frame it somehow displays the number of high pulses in 2 instances. So now what i want to do is to use 3 buttons and when button 1 is pressed it would wait for 1 pulse when button 2 is pressed it would wait for 5 pulses and if button 3 is pressed it would wait for 10 pulses. HELP! :