Hardware Reference
In-Depth Information
UsingTimerInterrupts
Hardware interrupts are not the only kind of interrupt you can trigger on
an Arduino; there are also timer-based interrupts. The ATMega328 (the chip
used in the Uno) has three hardware timers, which you can use for all kinds
of different things. In fact, the default Arduino library already uses these tim-
ers to increment millis() , operate delay() , and enable PWM output with
analogWrite() . Although not officially supported by the Arduino programming
language (yet), you can also take manual control of one of these timers to initi-
ate timed functions, generate arbitrary PWM signals on any pin, and more. In
this section, you learn how to use a third-party library (the TimerOne library)
to take manual control of the 16-bit Timer1 on the ATMega328-based Arduinos.
Similar libraries are available for doing these tricks on the Leonardo, and other
Arduino boards, but this section focuses on the Uno.
NOTE Timer1isusedtoenablePWMoutputonpins9and10;sowhenyou
usethislibrary,youwillbeunabletorun analogWrite() onthosepins.
UnderstandingTimerInterrupts
Just like a timer on your watch, timers on the Arduino count up from zero,
incrementing with every clock cycle of the oscillating crystal that drives the
Arduino. Timer1 is a 16-bit timer, meaning that it can count up from zero to 2 16 -1,
or 65,535. Once that number is reached, it resets back to zero and starts counting
again. How quickly it reaches that number depends on the clock divider. With
no divider, the clock would go through 16 million cycles per second (16MHz),
and would overflow and reset this counter many times per second. However,
you can “divide” the clock, an approach taken by many underlying Arduino
functions and libraries. The TimerOne library abstracts away much of the com-
plexity of dealing with the timer, allowing you to simply set a trigger period.
Using the timer, a function can be triggered every set number of microseconds.
GettingtheLibrary
To get started, download the TimerOne library, either from the Exploring Arduino
web page for this chapter or directly from https://code.google.com/p/arduino-
timerone/downloads . Unzip it (but keep it within a folder called TimerOne ), and
copy it to your Arduino libraries folder. The default location of the folder will
differ based on your operating system:
Windows: Documents/Arduino/libraries
Mac: Documents/Arduino/libraries
Linux: /home/YOUR_USER_NAME/sketchbook/libraries
 
Search WWH ::




Custom Search