Hardware Reference
In-Depth Information
CODE AND DIGITAL CONTENT FOR THIS CHAPTER
Code downloads, video, and other digital content for this chapter can be found at www
.exploringarduino.com/content/ch12 .
In addition, all code can be found at www.wiley.com/remtitle
.cgi?isbn=1118549368 on the Download Code tab. The code is in the chapter 12
download and individually named according to the names throughout the chapter.
Up to this point, every Arduino program you've written has been synchro-
nous. This presents a few problems, namely that using delay() can preclude
your Arduino from doing other things. In the preceding chapter, you created
a software timer using millis() to avoid the synchronous blocking nature of
delay() . In this chapter, you take this idea a step further by adding both timer
and hardware interrupts. Interrupts make it possible to execute code asynchro-
nously by triggering certain events (time elapsed, input state change, and so on).
Interrupts, as their name implies, allow you to stop whatever your Arduino is
currently doing, complete a different task, and then return to what the Arduino
was previously executing. In this chapter, you learn how to execute interrupts
when timed events occur or when input pins change state. You will use this
knowledge to build a “nonblocking” hardware interrupt system, as well as a
sound machine using timer interrupts.
NOTE Followavideotutorialaboutinterruptsandhardwaredebouncing:
www.jeremyblum.com/2011/03/07/arduino-tutorial-10-interrupts-
and-hardware-debouncing .YoucanalsofindthisvideoontheWileywebsite
shownatthebeginningofthischapter.
UsingHardwareInterrupts
Hardware interrupts are trigged depending on the state (or change in state), of
an input I/O pin. Hardware interrupts can be particularly useful if you want to
change some state variable within your code without having to constantly poll
the state of a button. In some previous chapters, you used a software debounce
routine along with a check for the button state each time through the loop. This
works great if the other content in your loop does not take a long time to execute.
Suppose, however, that you want to run a procedure in your loop that takes
awhile. For example, perhaps you want to slowly ramp up the brightness of an
LED or the speed of a motor using a for() loop with some delay() statements.
If you want button presses to adjust the color or speed of such an LED fade, you
will miss any presses of the button that occur while the delay() is happening.
Ordinarily, human reaction time is slow enough that you can execute many
functions within the loop() of an Arduino program, and can poll a button once
every time you go through the loop without missing the button press. However,
when there are “slow” components to your code within the loop() , you risk
missing external inputs.
 
Search WWH ::




Custom Search