
In a basic Arduino sketch, if you want to take action based on the status of a digital input pin, you’d check the state of the pin repeatedly until a particular condition is met. However, as your sketches become increasingly complex, you’ll find that it’s not always the best way to do this. EngBlaze posted a pair of guides to using interrupts so that you can execute code asynchronously in Arduino sketch. Here’s the analogy they use to illustrate the difference:
Imagine youโre sitting on your couch, enjoying a frosty brew and watching a movie after a long day. Life is good. Thereโs only one problem: youโre waiting for an incredibly important package to arrive, and you need it as soon as possible. If you were a normal AVR program or Arduino sketch, youโd have to repeatedly stop your movie, get up, and go check the mailbox every 5 minutes to make sure you knew when the package was there.
Instead, imagine if the package was sent Fedex or UPS with delivery confirmation. Now, the delivery man will go to your front door and ring the doorbell as soon as he arrives. Thatโs your interrupt trigger. Once you get the trigger, you can pause your movie and go deal with the package. Thatโs your interrupt service routine. As soon as youโre done, you can pick up the film where you left off, with no extra time wasted. Thatโs the power of interrupts.
The first guide covers using hardware interrupts, such as switches and the second discusses timer interrupts, so that you don’t have to repeatedly check if a certain amount of time has passed when executing code on a particular interval. The guides are complete with code examples to give you a jumpstart on your own interrupt-driven Arduino project. [via Reddit]
ADVERTISEMENT