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?
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.
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. ]