Callback by Interrupt

Download Report

Transcript Callback by Interrupt

Callback
TYWu
Reference and Library
• Reference
– http://www.arduino.cc/playground/Code/Timer
1
• Download Library
– http://code.google.com/p/arduinotimerone/downloads/detail?name=TimerOnev9.zip&can=2&q=
– Unzip the downloaded file in …arduino1.0.4\libraries\TimerOne
TimerOne.h
• initialize(period)
– You must call this method first to use any of
the other methods. You can optionally specify
the timer's period here (in microseconds), by
default it is set at 1 second. Note that this
breaks analogWrite() for digital pins 9 and 10
on Arduino.
Template
#include "TimerOne.h"
void setup()
{
Timer1.initialize(500000);
// initialize timer1, and set a 1/2 second period
Timer1.attachInterrupt(callback);
// attaches callback() as a timer overflow interrupt
}
Template (Cont’d)
void callback()
{
//callback statements
}
void loop()
{
// your program here...
}
Example
#include "TimerOne.h"
unsigned long time;
void setup()
{
Timer1.initialize(500000);
Timer1.attachInterrupt(callback);
Serial.begin(9600);
time = millis();
}
Example (Cont’d)
void callback()
{
Serial.println(millis() - time);
time = millis();
}
void loop()
{}
attachInterrupt()
• attachInterrupt()
– Specifies a function to call when an external
interrupt occurs.
– Replaces any previous function that was
attached to the interrupt.
– Most Arduino boards have two external
interrupts: numbers 0 (on digital pin 2) and 1
(on digital pin 3)
attachInterrupt()
• The table below shows the available
interrupt pins on various boards.
attachInterrupt()
• Syntax
attachInterrupt(interrupt, function, mode)
attachInterrupt(pin, function, mode) (Arduino Due only)
– interrupt: the number of the interrupt (int)
– function: the function to call when the interrupt occurs; this
function must take no parameters and return nothing. This
function is sometimes referred to as an interrupt service routine.
– mode: defines when the interrupt should be triggered. Four
contstants are predefined as valid values:
•
•
•
•
LOW to trigger the interrupt whenever the pin is low,
CHANGE to trigger the interrupt whenever the pin changes value
RISING to trigger when the pin goes from low to high,
FALLING for when the pin goes from high to low.
attachInterrupt()
• Example
int pin = 13;
volatile int state = LOW;
void setup() {
pinMode(pin, OUTPUT);
attachInterrupt(0, blink, CHANGE);
}
void loop() {
digitalWrite(pin, state);
}
void blink() {
delay(1000);
state = !state;
}
attachInterrupt()
If pin 2 changes its value….
What's happened?
Lab
• Lab
Interrupt