Counting pulses

I'am trying to count pulses from a sensor for measuring lengths of a gravel conveyer. It is a pnp sensor there sits on a wheel. 1 rotation = 26 pulses. The wheel speed is about 1 revolution per secund.

Is this code fine? or is it better to use attachInterrupt?

tandt_ler2.ino (378 Bytes)

There is no reason to post so little code as an attachment.

int pulse = 2;
int counter = 0;
int currentState = 0;
int previousState = 0;

void setup() {
pinMode(pulse, INPUT);
Serial.begin(9600);
}

void loop(){

if (digitalRead(pulse) == HIGH){ 
currentState = 1;
}
else {
currentState = 0;
}

if(currentState != previousState){
if(currentState == 1){
counter = counter + 1;
Serial.println(counter);
}
}
previousState = currentState;
}

Your indenting sucks.

if (digitalRead(pulse) == HIGH){ 
currentState = 1;
}
else {
currentState = 0;
}

Is there some reason not to use:

currentState = digitalRead(pulse);

Using 6 lines of code when one will do gives the bugs 6 times as many places to hide.

pulse is a lousy name for a variable that holds a pin number. pulsePin makes more sense to me.

Depends how fast the pulses come in. 100Hz, no need for interrupts, 20kHz and definitely need an
ISR, in between it depends on the rest of sketch really.

You can simplify the loop() code massively:

void loop()
{
  currentState = digitalRead(pulse) ;
  if (currentState && !previousState)
    Serial.println(++counter);
  previousState = currentState;
}

One issue you might encounter is noise / contact bounce in the sensor - do you know if
it gives clean single pulses? If not you might want to treat it like a button and do software
debouncing.

Push the Serial baud rate up to 115200, you don't want to miss pulses because you are waiting
for sluggish 9600 baud serial to push out to the host. With serial over USB there's no
reason to use glacial baud rates.

[ Oh, one more thing, is it 5V? PNP output could be 24V in industrial equipment... That would
mean doing level shifting. ]

Thanks for the answers - good feedback :slight_smile:

The rest of the sketch..... : I will use the pulses (conveyer length) to control a air ram. The air ram will dropoff a value of gravel.

yes it is 24V industrial equipment - i use a voltage divider to get 5V.