t4 2 Arduino Revisited
t4 2 Arduino Revisited
if(digitalRead(buttonPin) == LOW) {
void setup() digitalWrite(ledPin, HIGH); //LED ON
{
}
pinMode(ledPin, OUTPUT);
else {
digitalWrite(ledPin, LOW); //set ledPin off as default
digitalWrite(ledPin, LOW); //LED OFF
pinMode(buttonPin, INPUT_PULLUP); //set buttonPin as
input }
{
void loop() {
ledState = !ledState;
//do nothing, but wait for interrupt
digitalWrite(ledPin, ledState);
}
}
What are interrupts?
Interrupts are a way for a microcontroller to temporarily stop what it is doing to
handle another task.
The currently executing program is paused, an ISR (interrupt service routine)
is executed, and then your program continues, none the wiser.
Interrupts can detect brief pulses on input pins. Polling may miss the pulse
while you are doing other calculations.
Types of interrupt:
Hardware interrupt
Software interrupt
Interrupts in Arduino
There are 26 different interrupts on an Arduino Uno
1 Reset
2 External Interrupt Request 0 (pin D2)
3 External Interrupt Request 1 (pin D3)
4 Pin Change Interrupt Request 0 (pins D8 to D13)
5 Pin Change Interrupt Request 1 (pins A0 to A5)
6 Pin Change Interrupt Request 2 (pins D0 to D7)
7 Watchdog Time-out Interrupt
8 Timer/Counter2 Compare Match A
…
18 SPI Serial Transfer Complete
19 USART Rx Complete
…
25 2-wire Serial Interface (I2C)
…
ISR
Interrupt Service Routines should be kept short. Interrupts are
disabled when the ISR is called, so other interrupts are postponed.
Do not call millis() or delay() or Serial or …
The hardware can call a routine for us based on activity on pin 2
(INT0) or pin 3 (INT1)
Our loop() code does not need to know what is happening
But, we often want to know what is going on. How do we share
that information?
Regarding the external interrupt...
attachInterrupt(digitalPinToInterrupt(pin),ISR,mode);//recommended for
arduino board
attachInterrupt(pin, ISR, mode) ; //recommended Arduino Due, Zero only
//argument ISR: the ISR to call when the interrupt occurs; this function must
take no parameters and return nothing
https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/
Example for Data Access
const byte LED = 13, SW = 2;
If you share a multi-byte value (e.g. short int) between an ISR and
your code, you have to take additional precautions.
1fa: f8 94 cli
1fc: 80 91 10 01 lds r24, 0x0110
200: 90 91 11 01 lds r25, 0x0111
204: 78 94 sei
206: 80 50 subi r24, 0x00
208: 91 40 sbci r25, 0x01
20a: 69 f5 brne .+90
Pin Change Interrupt
Pin 2 is INT0
Pin 3 is INT1
But, what about pins 0,1,4,5,6,…
Pin Change Interrupts can monitor all pins, but it requires certain library
(PinChangeInt.h)
Different pins can have different ISRs
Useful resources:
http://gammon.com.au/interrupts
https://playground.arduino.cc/Main/PinChangeInterrupt/
https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/
http://brd4.braude.ac.il/~ksamuel/ElIn.31361/Exercises/E021%20Interrupts%202016-05-16.pdf