Theory Lecture Week 3M MES SM23-24 Prof Muhibul
Theory Lecture Week 3M MES SM23-24 Prof Muhibul
Arduino Interrupts
4
Introduction
6
The Main Reasons You Might Use Interrupts
• To detect pin changes (e.g., rotary encoders, button presses)
• Watchdog timer (e.g., if nothing happens after 8 seconds, interrupt me)
• Timer interrupts - used for comparing/overflowing timers
• SPI data transfers
• I2C data transfers
• USART data transfers
• ADC conversions (analog to digital)
• EEPROM ready for use
• Flash memory ready
7
Interrupt Vector
• The interrupt vectors and vector table are crucial to the understanding of
hardware and software interrupts. Interrupt vectors are addresses that
inform the interrupt handler as to where to find the ISR (Interrupt Service
Routine, also called Interrupt Service Procedure).
• Misspelling the vector name (even wrong capitalization) will result in the
ISR not being called and it will not also result in a compiler error.
Course Teacher: Prof. Dr. Engr. Muhibul Haque Bhuyan 23 June 2024 8
Interrupt Service Routines
• Interrupt Service Routines are functions with no arguments. Some
Arduino libraries are designed to call your own functions, so you
just supply an ordinary function, e.g.,
// Interrupt Service Routine (ISR)
void pinChange ()
{
flag = true;
} // end of pinChange
• As per the datasheet, the minimal amount of time to service an interrupt is
82 clock cycles in total. Assuming a 16 MHz clock, there would be 62.5 ns
time needed per clock cycle. So, the total time required is 5.125 s.
Course Teacher: Prof. Dr. Engr. Muhibul Haque Bhuyan 23 June 2024 9
Interrupt Service Routines
• When an ISR is entered, interrupts are disabled. Naturally, they must have
been enabled in the first place, otherwise, the ISR would not be entered.
However, to avoid having an ISR itself be interrupted, the processor turns
interrupts off.
• When an ISR exits, then interrupts are enabled again. The compiler also
generates code inside an ISR to save registers and status flags, so that
whatever you were doing when the interrupt occurred will not be affected.
• However, you can turn interrupts on inside an ISR if you absolutely must.
// Interrupt Service Routine (ISR)
void pinChange (){
// handle pin change here
interrupts (); // allow more interrupts
} // end of pinChange
Course Teacher: Prof. Dr. Engr. Muhibul Haque Bhuyan 23 June 2024 10
Interrupt Function of Arduino
• Re-enables interrupts (after they’ve been disabled by noInterrupts()). Interrupts allow
certain important tasks to happen in the background and are enabled by default.
Some functions will not work while interrupts are disabled, and incoming
communication may be ignored. Interrupts can slightly disrupt the timing of code,
however, and may be disabled for particularly critical sections of code.
▪ Syntax: interrupts() and noInterrupts(), all are opposite of interrupts()
▪ Parameters: None
▪ Returns: Nothing
• Example Code: The code enables Interrupts.
void setup() {}
void loop() {
noInterrupts();
// critical, time-sensitive code here
interrupts();
// other code here
}
Course Teacher: Prof. Dr. Engr. Muhibul Haque Bhuyan 23 June 2024 11
Global Enable
• The main interrupt flag
• This is used to turn all the interrupts on or off
• Example: sei(); //globally enable interrupt
• Available in the Status Register (SREG): Bit 7
Course Teacher: Prof. Dr. Engr. Muhibul Haque Bhuyan 23 June 2024 12
Atmega328p Interrupt Vector Table
• The ATmega328P provides support for 25 different interrupt sources.
These interrupts and the separate Reset Vector each have a separate
program vector located at the lowest addresses in the Flash program
memory space.
• The list also determines the priority levels of the different interrupts. The
lower the address the higher the priority level. RESET has the highest
priority, and next is INT0 – the External Interrupt Request 0.
13
Atmega328p Interrupt
Vector Table
14
List of interrupts, in priority order, for the ATmega328p:
15
Trigger
• An asynchronous event that causes the interrupt
• For example, the push button press during experiment 4 in our MES
Lab can be a trigger.
• It can cause an interrupt that is registered by the module and is
reacted to.
• What if all the conditions are not met but a trigger flag is set?
• In this case, rather than the request being dismissed, it is held
pending and postponed until a later time.
• What happens after a trigger? Once the interrupt is triggered
and processed, the interrupt flag is cleared.
• Clearing the interrupt flag is called acknowledgment.
Course Teacher: Prof. Dr. Engr. Muhibul Haque Bhuyan 23 June 2024 16
Interrupt Service Routine (ISR)
• The module that is executed when hardware requests an interrupt.
• There may be 1 large ISR handling all the interrupt requests, or
many small ISRs handling the many interrupts (interrupt vectors).
Example:
ISR(TIMER0_OVF_vect) // enabling overflow vector inside Timer0 using an ISR
Course Teacher: Prof. Dr. Engr. Muhibul Haque Bhuyan 23 June 2024 17
General Rules for ISR
• The ISR should execute as fast as possible.
▪ The interrupt should occur when it’s time to perform the required action
▪ The ISR should perform the action
▪ The ISR should end and return to the main function right away.
• Placing backward branches (busy, wait, iterations) inside the ISR
should be avoided.
• The percentage of time spent executing ISR should be small when
compared to the time between interrupt triggers.
Course Teacher: Prof. Dr. Engr. Muhibul Haque Bhuyan 23 June 2024 18
General Rules while writing an Interrupt
Service Routine (ISR):
• Keep it short
• Don't use delay ()
• Don't do serial prints
• Make variables shared with the main code volatile
• Variables shared with the main code may need to be protected by
"critical sections" (see below)
• Don't try to turn interrupts off or on
Course Teacher: Prof. Dr. Engr. Muhibul Haque Bhuyan 23 June 2024 19
What are "volatile" variables?
• Variables shared between ISR functions and normal functions
should be declared "volatile". This tells the compiler that such
variables might change at any time, and thus the compiler
must reload the variable whenever you reference it, rather than
relying upon a copy it might have in a processor register.
volatile boolean flag;
void loop ()
{
if (flag)
{
// interrupt has occurred
}
} // end of loop
Course Teacher: Prof. Dr. Engr. Muhibul Haque Bhuyan 23 June 2024 21
Atmega328p Interrupt Processing
• When an interrupt occurs, the microcontroller completes the current
instruction and stores the address of the next instruction on the stack.
• It also turns off the interrupt system to prevent further interrupts while one
is in progress. This is done by clearing the SREG Global Interrupt
Enable I-bit.
• The Interrupt flag bit is cleared for Type 1 Interrupts only (see the next
Slide for Type definitions).
22
Atmega328p Interrupt Processing
• The execution of the ISR is performed by loading the beginning
address of the ISR specific for that interrupt into the program counter.
The processor starts running the ISR.
• Execution of the ISR continues until the Return from Interrupt
instruction (RETI) is encountered. The SREG I-bit is automatically set
when the RETI instruction is executed (i.e., Interrupts enabled).
• When the processor exits from an interrupt, it will always return to the
interrupted program and execute one more instruction before any
pending interrupt is served.
• The Status Register is not automatically stored when entering an
interrupt routine, nor restored when returning from an interrupt routine.
This must be handled by software.
23
Atmega328p Interrupt Processing – Type 1
• The user software can write logic one to the I-bit to enable nested
interrupts. All enabled interrupts can then interrupt the current interrupt
routine.
oThe SREG I-bit is automatically set to logic one when a Return from
Interrupt instruction (RETI) is executed.
• There are basically two types of interrupts:
oThe first type (Type 1) is triggered by an event that sets the Interrupt Flag. For
these interrupts, the Program Counter is vectored to the actual Interrupt Vector to
execute the interrupt handling routine, and hardware clears the corresponding
Interrupt Flag.
24
Atmega328p Interrupt Processing – Type 1
▪ If the same interrupt condition occurs while the corresponding interrupt
enables bit is cleared, the Interrupt Flag will be set and remembered until
the interrupt is enabled, or the flag is cleared by software (interrupt
canceled).
▪ Interrupt Flag can be cleared by writing a logic one to the flag bit
position(s) to be cleared.
oIf one or more interrupt conditions occur while the Global Interrupt Enable
(SREG I) bit is cleared, the corresponding Interrupt Flag(s) will be set and
remembered until the Global Interrupt Enable bit is set on return (RETI) and
will then be executed by order of priority.
25
Atmega328p Interrupt Processing – Type 2
• The second type (Type 2) of interrupts will trigger as long as the
interrupt condition is present. These interrupts do not necessarily
have Interrupt Flags. If the interrupt condition disappears before
the interrupt is enabled, the interrupt will not be triggered.
26
TIMSK0 – Timer/Counter0 Interrupt Mask Register
39
500 ms Blink Example Code using Timer1 Interrupts and Pre-scalar values of 256
• We use the pre-scalar value of 256 to reduce the timer clock frequency to
16 MHz/256 = 62.5 kHz, with a new timer clock period = 1/62.5 kHz = 16
μs. Thus, the required timer count = (500,000 s/16 μs) – 1 = 31,250 – 1 =
31,249. So, this is the value that we should store in the OCR register.
void setup() {
pinMode(13, OUTPUT);
cli(); // stop interrupts till we make the settings
TCCR1A = 0; // Reset the entire A and B registers of Timer1 to make sure that
TCCR1B = 0; // we start with everything disabled.
40
500 ms Blink Example Code using Timer1 Interrupts and Pre-scalar values of 256
TCCR1B = 0b00000100; // Set CS12 bit of TCCR1B to 1 to get a prescalar value of 256.
TIMSK1 = 0b00000010; // Set OCIE1A bit to 1 to enable compare match mode of A reg.
OCR1A = 31250; // We set the required timer count value in the compare register, A
sei(); // Enable back the interrupts
}
void loop() {
// put your main code here, to run repeatedly.
}
// With the settings above, this ISR will trigger each 500 ms.
ISR(TIMER1_COMPA_vect){
TCNT1 = 0; // First, set the timer back to 0 so that it resets for the next interrupt
LED_State = !LED_State; // Invert the LED State
digitalWrite(13, LED_State); // Write this new state to the LED connected to pin D5
} 41
External Interrupts
• External interrupts triggered by:
▫ INT0 or INT1 pins
▫ Any of the PCINT23:0 pins
• INT0 and INT1 are mapped with the pins PD2 and PD3 on
ATMega328P
• PD2 and PD3 are mapped with digital pins 2 and 3 (GPIO) on the
Arduino Uno board
• PCINT23:0 are mapped with ports B, C, and D on the Arduino Uno
board
• Implies any of the I/O pins on the board can be configured to handle
interrupts
• These interrupts can be used to wake up the processor from sleep
modes
Course Teacher: Prof. Dr. Engr. Muhibul Haque Bhuyan 23 June 2024 42
External Interrupts
• INT0 and INT1 are referred to as ‘External Interrupts’
▫ Can be triggered by a rising edge, falling edge, logical change, or
low level
• PCINT23:0 are referred to as ‘Pin Change Interrupts’
• External interrupts have a higher priority
• External interrupts have their own interrupt vectors
• Pin change interrupts share interrupt vectors
▫ The interrupt handler has to decide which pin the interrupt
originated from
Course Teacher: Prof. Dr. Engr. Muhibul Haque Bhuyan 23 June 2024 43
EICRA – External Interrupt Control Register A
• Contains control bits for interrupt sense control
Course Teacher: Prof. Dr. Engr. Muhibul Haque Bhuyan 23 June 2024 45
EICRA – External Interrupt Control Register A
• Value of the pin is sampled before detecting the edges
• If edge or toggle interrupt is selected:
▫ Pulses longer than 1 clock period will generate an interrupt
▫ Shorter pulses are not guaranteed to generate an interrupt
• If low-level interrupt is selected, to generate interrupt:
▫ Low level must be held until the completion of currently
executing instruction
Course Teacher: Prof. Dr. Engr. Muhibul Haque Bhuyan 23 June 2024 46
EIMSK – External Interrupt Mask Register
Course Teacher: Prof. Dr. Engr. Muhibul Haque Bhuyan 23 June 2024 47
EIMSK – External Interrupt Mask Register
• When INT1/INT0 bit is enabled, and I bit (bit 7) of SREG is enabled:
▫ External pin interrupt is activated
▫ ISCx1, and ISCx0 pins in EICRA define whether the external interrupt
will be activated on:
Rising edge
Falling edge
Logic change
Low level
• Activity on the pin will cause an interrupt even if the pin is configured as
an output
• Executed from INT1/INT0 interrupt vector
Course Teacher: Prof. Dr. Engr. Muhibul Haque Bhuyan 23 June 2024 48
EIFR – External Interrupt Flag Register
Course Teacher: Prof. Dr. Engr. Muhibul Haque Bhuyan 23 June 2024 49
EIFR – External Interrupt Flag Register
• When the INTx pin triggers an interrupt request, INTFx is set
• If I bit in SREG and INTx bit in EIMSK are set, MCU will jump to
a relevant interrupt vector
• INTFx cleared when:
▫ Interrupt routine is executed
▫ A logical 1 is written (cancel any falling interrupts)
▫ Always cleared when INTx is configured as a level interrupt
Course Teacher: Prof. Dr. Engr. Muhibul Haque Bhuyan 23 June 2024 50
External Interrupt related Program
volatile boolean Output_Signal = true;
void isr() {
Output_Signal = !Output_Signal;
digitalWrite(8, Output_Signal);
}
void setup () {
cli();
pinMode(8, OUTPUT); // an LED is connected to this pin, 8
attachInterrupt (digitalPinToInterrupt (2), isr, RISING); // a push switch is connected to this pin, 2
EICRA = 0b00000011;
sei();
EIMSK = 0b00000001; }
void loop () {
digitalWrite(8, Output_Signal);
}
Course Teacher: Prof. Dr. Engr. Muhibul Haque Bhuyan 23 June 2024 51
Circuit Diagram of External Interrupt related Program
• When the INT0 pin triggers an interrupt
request, INTF0 is set
• If I bit in SREG and INT0 bit in EIMSK are set,
MCU will jump to the interrupt vector
• INTF0 cleared when:
▫ Interrupt routine is executed
▫ A logical 1 is written (cancel any falling
interrupts)
▫ Always cleared when INT0 is configured as a
level interrupt
Course Teacher: Prof. Dr. Engr. Muhibul Haque Bhuyan 23 June 2024 52
PCICR – Pin Change Interrupt Control Register
Course Teacher: Prof. Dr. Engr. Muhibul Haque Bhuyan 23 June 2024 53
PCICR – Pin Change Interrupt Control Register
• If PCIEx is enabled and I bit in SREG is enabled, pin change
interrupt x is enabled
• PCINT 23:16 corresponds to pin change interrupt 2
• PCINT 14:8 corresponds to pin change interrupt 1
• PCINT 7:0 corresponds to pin change interrupt 0
• The pins are enabled individually from PCMSKx register
• Executed from PCIx interrupt vector
• Any change in these pins will cause an interrupt
Course Teacher: Prof. Dr. Engr. Muhibul Haque Bhuyan 23 June 2024 54
PCICR – Pin Change Interrupt Control Register
• PCINT 23:16 –
▫ PD7:PD0 on ATMega328P
▫ Pins D7:D0 (GPIO) on Arduino Uno board
• PCINT 14:8 –
▫ PC6:PC0 on ATMega328P
▫ PC5:0 – Pins A5:A0 on Arduino Uno board
▫ PC6 – Reset pin on Arduino Uno Board
• PCINT 7:0 –
▫ PB7:PB0 on ATMega328P
▫ PB5:0 – Pins D13:D8 on Arduino Uno board
▫ PB6 and PB7 are not available externally on the Arduino Uno board
Course Teacher: Prof. Dr. Engr. Muhibul Haque Bhuyan 23 June 2024 55
PCIFR – Pin Change Interrupt Flag Register
Course Teacher: Prof. Dr. Engr. Muhibul Haque Bhuyan 23 June 2024 56
PCIFR – Pin Change Interrupt Flag Register
• Any logic change on PCINT23:0 triggers an interrupt request:
PCIFx set
• If I bit in SREG and PCIEx on PCICR are set, MCU will go to the
corresponding interrupt vector
• Flag is cleared when:
▫ Interrupt routine is executed
▫ A logical 1 is written
Course Teacher: Prof. Dr. Engr. Muhibul Haque Bhuyan 23 June 2024 57
PCMSK2 – Pin Change Mask Register 2
Course Teacher: Prof. Dr. Engr. Muhibul Haque Bhuyan 23 June 2024 61
Thanks for attending….
?
Course Teacher: Prof. Dr. Engr. Muhibul Haque Bhuyan 23 June 2024 62