Professional Documents
Culture Documents
3C Polling Vs Interrupts V1 2
3C Polling Vs Interrupts V1 2
Notes:
Inside the attached ISR function, delay() will not work and the value returned by millis() will not
increment (since both delay() and millis() relies on interrupts to work). delayMicroseconds()
does not use any counter, so it will work as normal.
Serial data received while in the ISR function may be lost.
You should declare as “volatile” any variables that you modify within the attached ISR function.
2
External Interrupts: interrupts that are triggered based on the value of an Arduino pin that is set
by an external source, such as a button press. To use external interrupts, you need to associate an
internal interrupt (interrupt#0 or interrupt#1) with an Arduino pin via the attachInterrupt()
function:
Syntax
attachInterrupt(digitalPinToInterrupt(pin), ISR, mode) (recommended)
Parameters
Returns
Nothing
Example Code
const byte ledPin = 13; // set LED pin to D13
const byte interruptPin = 2; // interrupt pins can be
// D2 or D3 on Arduino UNO
volatile bool state = LOW; // volatile used since boolean
// variable “state” changes
// in ISR
void setup() {
pinMode(ledPin, OUTPUT); // since we are setting
// the value of the LED pin
// it is configured as an
// OUTPUT
pinMode(interruptPin, INPUT_PULLUP); // since the
// value of the interrupt
// pin is being monitored
// to trigger an interrupt
// it is set as an INPUT
attachInterrupt(digitalPinToInterrupt(interruptPin), blink,
CHANGE); // initiate the interrupt on the
// correct pin to call function “blink”
// when the state of interruptPin
// CHANGES from HIGH to LOW or LOW to
// HIGH
}
void loop() {
digitalWrite(ledPin, state); // turn LED on/off
// depending on the
// state variable
}
void blink() {
state = !state; // toggle the state variable
// from LOW to HIGH or HIGH to LOW
}
4
Debouncing
-when a button is pressed, there are two metal contacts which can generate multiple signals high-
low-high-low as the contacts make and break contact several times instead of producing the
desired clean transition step signal from low to high (or high to low)
-eg. for the case where the button signal is high unless pressed, pushing the button down once
might change the value of the pin monitoring the button press as follows:
-if the pushbutton signal is connected to Pin 2 (corresponding to interrupt#0) on the Arduino
UNO and the attachInterrupt function is set to “FALLING” then to prevent the software from
interpreting the above as 3 separate button presses, can “debounce” an input by checking over a
long enough period (each time the ISR is called) to ensure the button was actually pressed only
once, eg. within the ISR:
// store the number of milliseconds that have elapsed since
// the Arduino was turned on
current_time = millis();