How to measure time intervals while simultaneously driving LEDs? While running Fire2012 and some other code, I’m going to want to calculate the speed of a bicycle by timing the intervals between a magnet on the wheel tripping either a reed switch or hall effect sensor. I’ve been starting to read up on timers and interrupts, and my initial idea is to have a timer for about a hundredth of a second (thousandth if I want to try for more accuracy) which upon expiration engages an interrupt that checks the sensor and detects/times edges on the sensor signal. The idea would be that the APA102 computation and drawing would happen while that timer is ticking, and be interrupted every hundredth of a second to sample the speed sensor. Before I start trying to code this I thought I’d ask if this sounds like a good approach since I’m very new to arduino programming. Thanks!
BTW I have looked at lots of arduino bicycle speedometers on the web and most don’t seem to be doing any heavy lifting processing, just essentially idling between samples, which is much easier.
I’ve done it with a hall effect sensor:
Should be easy. You want your sensor to trip the interrupt by putting it on an interrupt pin set to trigger when going high (or low)
You want your interrupt routine to be as clean as possible so just make it set a volatile variable to true - then in the main loop test if that variable is true. Remember to set it back to false after checking, but inside the code that is triggered if true.
If you don’t want to use an interrupt pin then check out any of the debounce libraries.
If you haven’t bought your hardware yet then I’d go with a Teensy-LC - loads of horsepower and you’ll never worry about how long something is taking to run.
Thanks folks. Nathaniel’s code and James both point toward the same strategy: using edges to trigger the interrupts. That does simplify things compared to my original half baked strategy (posted at the top) of interrupting based on timers. I can just check and store the arduino timer value in the interrupt routine. Each time I catch a leading edge, I just subtract the last edge time from the current edge time and I’ve got my interval. Perhaps with some debounce logic that ignores edges that occur shortly after the leading edge.