Synchronizing to an time-varying external pulse

Hi everyone,

I'm trying to find a good way to structure a program to monitor an input for a pulse. The time between pulses vary from 250ms down to 20ms. The difference between two consecutive pulse widths might be on the order of 10%.

I've considered a couple of ways to do it. I could run the entire section of sync-critical code in an interrupt, or use while() to hang the main loop until the sensor fires. Anyone have any pointers for something like this?

I've written quite a few pulse receiving applications, and I have always evolved to detecting the pulse by interrupt. Just create a simple little Interrupt routine that sets a boolean flag when a pulse arrives, and let your main loop read the flag and initiate whatever action you require. Always best to minimize the time spent in the ISR.

I have found that trying to read a pulse in a loop works fine, until you start adding to the code. Then strange things begin to happen. Interrupts are very easy to use with Arduino, and after all, detecting pulses is what they're for.

Good luck

John Doner

If you organize your code correctly it can check the status of the input in every iteration of loop() without needing to stop doing anything else and without needing to use interrupts. If you need to measure the width of a pulse there is a pulseIn() function.

Interrupts are a very effective and simple way to detect pulses if you know how to program and debug interrupts. If you don't they can be a nightmare. You can't use Serial.print() within interrupt service routines (ISR) for debugging.

Keep the code in your ISR very short - 2 or 3 lines of code.

...R

Thanks guys. Good advice.