# Counting high frequency pulses.

I'm trying to read the pulse output of a sensor, then output a short signal every 100 pulses. The maximum frequency of pulses is 1kHz. I'm trying to use the pulseIn function with a digitalWrite to turn on and off an LED, but that doesn't seem to be giving any output. Here's my current code:

``````int Geiger = 2;
int LED = 13;
int stuff;

unsigned long Count;

void setup()

{

pinMode(Geiger, INPUT);
pinMode(LED, OUTPUT);

}

void loop()

{

Count=0;

stuff = pulseIn(Geiger, HIGH, 1);
if (stuff>1){
Count = Count+1;
if (Count = 100){
digitalWrite(LED, HIGH);
delay(10);
digitalWrite(LED, LOW);
Count = 0;
}
stuff = 0;
}

}
``````

I'm a beginner in Arduino, but I do have some older experience with other languages like Java and Python.

Thanks for any help.

You have a timeout value of 1 microsecond. That means it only waits for 1 us. every time through loop, and it will miss any pulses that happen when the rest of the code in loop() is running. Also do you really want to only do something if stuff >= 2?

I think you will have to bite the bullet and use an input pin interrupt to count the pulses.

That's what I figured might happen, but I didn't know what the alternative would be. I have the arduino references page for input pin interrupt open. If you have any other suggestions for resources on this, or have the time to explain it yourself I would be very grateful, otherwise I'll just try to figure out if I can do it as is.

it's unfortunate that this won't work for what I want, because I had (kind of) improved the code with less if statements, and an infinite for loops so it wouldn't end immediately.

For me, Nick Gammon's site had the clearest and most comprehensive breakdown on interrupts. If you just follow the basic rules, you should be okay. If all you need to do is flash an LED, you don't need any communication between the main program and ISR, you can just do everything in the ISR. That will simplify it a lot.

Okay, thanks. I'll look into that. for now this is what I've gotten:

``````int geiger = 2;
int LED = 13;
unsigned long count;

void setup() {
pinMode(LED, OUTPUT);
pinMode(geiger, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(geiger), pulse, RISING);
}

void loop() {
for( ; ; ) {
if(count > 99){
count = 0;
digitalWrite(LED, HIGH);
delay(10);
digitalWrite(LED, LOW);
}
}
}
void pulse() {
count++;
}
``````

I haven't tested it yet, but it compiles without issue.