Hardware Reference
In-Depth Information
If the Arduino integrated development environment (IDE) was open when
you copied the TimerOne folder, make sure you restart it so that the library is
loaded. You are now ready to take control of Timer1 with your Arduino.
ExecutingTwoTasksSimultaneously(ish)
It's important to keep in mind that there is no such thing as “true” simultaneous
execution on an Arduino. Interrupts merely make it seem like multiple things
are happening at the same time, by allowing you to switch between multiple
tasks extremely quickly. Using the TimerOne library you just installed, you
make an LED blink using the timer while you execute other functions within
loop() . At the end of the chapter, you will execute serial print statements in
the main loop with delays, while using timer interrupts to control lights and
sounds simultaneously. To confirm that the library is installed properly, you can
load the program shown in Listing 12-2 on to an Arduino Uno (with no other
components connected). It should blink the onboard LED connected to pin 13.
This LED will blink on and off every second and is controlled by the timer.
If you put any other code in loop() , it will appear to execute simultaneously.
Listing 12-2: Simple Timer Interrupt Blink Test—timer1.ino
//Using Timer Interrupts with the Arduino
#include <TimerOne.h>
const int LED=13;
void setup()
{
pinMode(LED, OUTPUT);
Timer1.initialize(1000000); //Set a timer of length 1000000
//microseconds (1 second)
Timer1.attachInterrupt(blinky); //Runs "blinky" on each
//timmer interrupt
}
void loop()
{
//Put any other code here.
}
//Timer interrupt function
void blinky()
{
digitalWrite(LED, !digitalRead(LED)); //Toggle LED State
}
Search WWH ::




Custom Search