Newbie s Guide to AVR Interrupts

Similar documents
INTERRUPTS in microprocessor systems

Interrupts & Interrupt Service Routines (ISRs)

ATmega Interrupts. Reading. The AVR Microcontroller and Embedded Systems using Assembly and C) by Muhammad Ali Mazidi, Sarmad Naimi, and Sepehr Naimi

Microprocessors & Interfacing

Embedded Systems and Software

Interrupts (I) Lecturer: Sri Notes by Annie Guo. Week8 1

12.1. Unit 12. Exceptions & Interrupts

Interrupts and timers

Fundamental concept in computation Interrupt execution of a program to handle an event

Grundlagen Microcontroller Interrupts. Günther Gridling Bettina Weiss

Interrupts L33-1. Interrupts

e-pg Pathshala Subject : Computer Science Paper: Embedded System Module: Interrupt Handling Module No: CS/ES/13 Quadrant 1 e-text

AVR Timers TIMER0. Based on:

CHAPTER 11 INTERRUPTS PROGRAMMING

MCS-51 Serial Port A T 8 9 C 5 2 1

Newbie s Guide to AVR Timers

EE 308: Microcontrollers

Microcontroller basics

real-time kernel documentation

PC Interrupt Structure and 8259 DMA Controllers

Software debouncing of buttons

GCC and the PROGMEM Attribute

ECE332, Week 8. Topics. October 15, Exceptions. Hardware Interrupts Software exceptions

THE CPU SPENDS ALMOST ALL of its time fetching instructions from memory

CPEG300 Embedded System Design. Lecture 6 Interrupt System

Processor and compiler dependent

AGH University of Science and Technology Cracow Department of Electronics

Today: Computer System Overview (Stallings, chapter ) Next: Operating System Overview (Stallings, chapter ,

EEL 4744C: Microprocessor Applications. Lecture 7. Part 2. M68HC12 Interrupt. Dr. Tao Li 1

Process Coordination and Shared Data

AVR ISA & AVR Programming (I) Lecturer: Sri Parameswaran Notes by: Annie Guo

Hardware OS & OS- Application interface

An Interrupt is either a Hardware generated CALL (externally derived from a hardware signal)

AVR ISA & AVR Programming (I)

In examining performance Interested in several things Exact times if computable Bounded times if exact not computable Can be measured

Interrupts and Serial Communication on the PIC18F8520

Definition: An operating system is the software that manages resources

FIFTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLOGY-MARCH 2014 EMBEDDED SYSTEMS (Common for CT,CM) [Time: 3 hours] (Maximum marks : 100)

Embedded Systems and Software. Serial Communication

ECEN 449 Microprocessor System Design. Hardware-Software Communication. Texas A&M University

COSC 243. Input / Output. Lecture 13 Input/Output. COSC 243 (Computer Architecture)

AVR ISA & AVR Programming (I) Lecturer: Sri Parameswaran Notes by: Annie Guo

13-2 EE 4770 Lecture Transparency. Formatted 8:18, 13 March 1998 from lsli

Embedded Systems and Software

Using the EEPROM memory in AVR-GCC

COMP2121: Microprocessors and Interfacing

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 09, SPRING 2013

YOU WILL NOT BE ALLOWED INTO YOUR LAB SECTION WITHOUT THE REQUIRED PRE-LAB.

FINAL EXAM. last name first name

Interrupts and Low Power Features

Changing the Embedded World TM. Module 3: Getting Started Debugging

COMP 7860 Embedded Real- Time Systems: Threads

Interrupts and Time. Real-Time Systems, Lecture 5. Martina Maggio 28 January Lund University, Department of Automatic Control

Computer System Overview

AGH University of Science and Technology Cracow Department of Electronics

Real Time Embedded Systems. Lecture 10 January 31, 2012 Interrupts

Computer System Overview OPERATING SYSTEM TOP-LEVEL COMPONENTS. Simplified view: Operating Systems. Slide 1. Slide /S2. Slide 2.

Interrupts Peter Rounce

Interrupts and Time. Interrupts. Content. Real-Time Systems, Lecture 5. External Communication. Interrupts. Interrupts

Q.1 Explain Computer s Basic Elements

AVR Subroutine Basics

GUJARAT TECHNOLOGICAL UNIVERSITY MASTER OF COMPUTER APPLICATION SEMESTER: III

Emulating an asynchronous serial interface (USART) via software routines

Topic 11: Interrupts ISMAIL ARIFFIN FKE UTM SKUDAI JOHOR


Introduction to Embedded Systems

Real-Time Programming

Engineer To Engineer Note

Using programmed I/O on the M16C; and Writing an Interrupt Service Routine (ISR)

Input / Output. School of Computer Science G51CSA

Lecture #13 Interrupts Embedded System Engineering Philip Koopman Monday, 29-Feb-2016

For more notes of DAE

Module 3. Embedded Systems I/O. Version 2 EE IIT, Kharagpur 1

[TUT] Newbie's Guide to AVR Interrupts

AVR Microcontrollers Architecture

1 Introduction to Computers and Computer Terminology Programs Memory Processor Data Sheet Example Application...

Interrupt handling. Purpose. Interrupts. Computer Organization

Lecture test next week

Last 2 Classes: Introduction to Operating Systems & C++ tutorial. Today: OS and Computer Architecture

MICROPROCESSOR BASED SYSTEM DESIGN

Emulating an asynchronous serial interface (ASC0) via software routines

Interrupts and Using Them in C

Last Time. Think carefully about whether you use a heap Look carefully for stack overflow Especially when you have multiple threads

leos little embedded Operating System User's guide Written by Leonardo Miliani

These three counters can be programmed for either binary or BCD count.

Microprocessors B (17.384) Spring Lecture Outline

An overview of Interrupts ECE3534

Fall 2017 Project Assignment Speed Trap

ECE 353 Lab 4. General MIDI Explorer. Professor Daniel Holcomb Fall 2015

Using Input Capture on the 9S12

8051 Serial Port. EE4380 Fall02 Class 10. Pari vallal Kannan. Center for Integrated Circuits and Systems University of Texas at Dallas

Interrupt/Timer/DMA 1

Interrupts Peter Rounce - room 6.18

Common Computer-System and OS Structures

Memory Management. Kevin Webb Swarthmore College February 27, 2018

Signals. POSIX defines a variety of signal types, each for a particular

Link Service Routines

Microcontrollers. Program organization Interrupt driven I/O. EECE 218 Microcontrollers 1

Interrupts, timers and counters

Maxim > Design Support > Technical Documents > Application Notes > Microcontrollers > APP 4465

Transcription:

Newbie s Guide to AVR Interrupts Dean Camera March 15, 2015 ********** Text Dean Camera, 2013. All rights reserved. This document may be freely distributed without payment to the author, provided that it is not sold, and the original author information is retained. For more tutorials, project information, donation information and author contact information, please visit www.fourwalledcubicle.com. 1

Contents 1 What are Interrupts? 3 2 What can cause interrupts? 4 3 So how do we define an ISR? 5 4 Enabling a Specific Interrupt 7 5 Things you Need to Know 8 5.1 When an interrupt is executing, your main program isn t.............. 8 5.2 Data shared between the ISR and your main program must be both volatile and global in scope in the C language............................ 8 5.3 Pay attention to variables needing atomic access................... 9 5.4 Each interrupt source has exactly one flag to indicate that the event occurred... 9 5.5 The interrupt source flag is usually cleared when the ISR fires............ 9 6 Putting it all together 10 2

Chapter 1 What are Interrupts? One of the most fundamental and useful principles of modern embedded processors are interrupts. There seems to be a lot of confusion about interrupts; what are they, and how do we use them? In short, an interrupt is a way for an external (or, sometimes, internal) event to pause the current processor s activity, so that it can complete a brief task before resuming execution where it left off. Consider the following. Let s say we are at home, writing an excellent tutorial on how a principle of modern embedded processors works. We are very interested in this topic, so we are devoting all our concentration to our keyboard. However, half way though, the phone rings. Despite not being by the phone waiting for a call, we are able to stop what we are doing, take the call, and go back where we left off once we have hung up. This is how a processor interrupt works. We can set up the processor so that it is looking for a specific external event (like a pin going low, or a timer overflowing) to become true, while it goes on and performs other tasks. When these events occur, we stop the current task, handle the event, and resume back where we left off. This gives us a great deal of flexibility; rather than having to actively poll our events to see if they have happened, we can instead just ignore them completely and trust our interrupt routines to process them instead. What we are doing is called asynchronous processing - that is, we are processing the interrupt events outside the regular execution thread of the main program. It s important to note that we are not doing two things at once (although it may appear that way) - the regular program is stopped while an interrupt routine runs. When correctly set up, we can link a specific interrupt source to a specific handler routine, called an Interrupt Service Routine, or ISR for short. 3

Chapter 2 What can cause interrupts? There are two main sources of interrupts: ˆ Hardware Interrupts, which occur in response to a changing external event such as a pin going low, or a timer reaching a preset value ˆ Software Interrupts, which occur in response to a command or sequence of commands issued in software The 8-bit AVRs lack software interrupts, which are usually used for special operating system tasks like switching between user and kernel space, or for handling exceptions. Because of this, we ll only be looking at hardware interrupts. Each AVR model contains a different set of interrupt sources. We can find out which interrupts our chosen model has by looking in the Interrupts chapter of the AVR s datasheet. This chapter contains a table, similar to the following fragment from the AT90USB1287 datasheet: Vector No. Address Source Interrupt Definition 2 $ 0002 INT0 External Interrupt Request 0 3 $ 0004 INT1 External Interrupt Request 1 4 $ 0006 INT2 External Interrupt Request 2 This contains a complete list of all the possible interrupts in our AVR, giving each interrupt s Vector table address, Source Interrupt Name, and Source Interrupt Description. Take a look at your AVR s list - see the variety of interrupt sources, from all sorts of on-chip peripherals of the AVR. Hardware interrupts can be useful to process sparingly occurring events, such as buttons presses or alarm inputs. They can also be useful for situations where a low, fixed latency is required, for example when processing inputs from a rotary encoder. 4

Chapter 3 So how do we define an ISR? How we do interrupts varies between programming languages, but at the lowest level, we are simply making a general AVR function somewhere in the AVR s FLASH memory space, and linking it to a specific interrupt source by placing a JMP or RJMP instruction to this function at the address specified in the table we just looked at. At the start of the AVR s FLASH memory space lies the Interrupt Vector Table, which is simply a set of hardwired addresses which the AVR s processor will jump to when each of the interrupts fire. By placing a jump instruction at each interrupt s address in the table, we can make the AVR processor jump to our ISR which lies elsewhere. For an ISR to be called, we need three conditions to be true: ˆ Firstly, the AVR s global Interrupts Enable bit (I) must be set in the MCU control register SREG. This allows the AVR s core to process interrupts via ISRs when set, and prevents them from running when cleared. It defaults to being cleared on power up, so we need to set it. ˆ Secondly, the individual interrupt source s enable bit must be set. Each interrupt source has a separate interrupt enable bit in the related peripheral s control registers, which turns on the ISR for that interrupt. This must also be set, so that when the interrupt event occurs the processor runs the associated ISR. ˆ Thirdly, The condition for the interrupt must be met - for example, for the USART Receive Complete (USART RX) interrupt, a character must have been received. When all three conditions are met, the AVR will fire our ISR each time the interrupt event occurs. Again, the method used to define an ISR differs between languages and compilers, so I ll just put the AVR-GCC and AVR ASM versions here. # include <avr / interrupt.h> ISR ( Vector Source _vect ) // ISR code to execute here. org 0x Vector Address jmp MyISRHandler MyISRHandler : ; ISR code to execute here reti Note that in the case of the assembly version, we need to add a reti instruction at the end of our interrupt instead of the usual ret instruction to return to the main program s execution; this special instruction has the dual function of exiting the ISR, and automatically re-enabling the 5

CHAPTER 3. SO HOW DO WE DEFINE AN ISR? 6 Global Interrupt Enable bit. This happens inside the C version too when the function returns, we just don t see it normally. This raises the next point; by default, on the AVR devices, interrupts are themselves not interruptible. When an interrupt fires, the AVR CPU will automatically disable the Global Interrupt Enable bit, to prevent the ISR from being itself interrupted. This is to prevent stack overflows from too many interrupts occurring at once and to prevent the ISRs from running too long, as most uses of interrupts are to have minimal latency when processing an event. It s perfectly possible to set the Global Interrupt Enable bit again as part of the ISR so that nested interrupts can occur, but this is highly not recommended as it is dangerous.

Chapter 4 Enabling a Specific Interrupt If you simply add in an ISR to your existing program, you will find that it appears to do nothing when you try to fire it. This is because while we have defined an ISR, we haven t enabled the interrupt source! As mentioned in part 3, we need to meet all three criteria for the ISR to fire. Firstly, we need to set the I bit in the SREG register. This is the Global Interrupt Enable bit, without which the AVR will simply ignore any and all interrupts. In assembly, we have two special single-cycle instructions for dealing with the I bit: ˆ sei, which SEts the global Interrupt flag ˆ cli, which CLears the global Interrupt flag While in C, we have to use special macros from our libc library s header. In the case of AVR- GCC and its avr-libc library, we just use the sei() and cli() macro equivalents defined in <avr/interrupt.h>. Next, we also need to enable a specific interrupt source, to satisfy the second condition for firing an ISR. The way to do this varies greatly between interrupt sources, but always involves setting a specific flag in one of the peripheral registers. Let s set an interrupt on the USART Receive Complete (USART RX) interrupt. According to the datasheet, we want to set the RXCIE bit in the UCSRB register. In AVR8 assembly, we need to do the following: in r16, UCSRB ori r16, (1 << RXCIE ) out UCSRB, r16 Or in C: UCSRB = (1 << RXCIE ); That should be enough to make the AVR s execution jump to the appropriate ISR when the interrupt occurs. 7

Chapter 5 Things you Need to Know There are a few things to keep in mind when using interrupts in your program: 5.1 When an interrupt is executing, your main program isn t That means that if your application isn t robust and you receive many interrupts in a very short space of time, your main program s execution will slow to a halt. Keep this in mind when you decide to attach a 4MHz clock input to an external interrupt pin. 5.2 Data shared between the ISR and your main program must be both volatile and global in scope in the C language Without the volatile keyword, the compiler may optimize out accesses to a variable you update in an ISR, as the C language itself has no concept of different execution threads. Take the following example: # include <avr / interrupt.h> int MyValue ; ISR ( SomeVector_vect ) MyValue ++; int main ( void ) SetupInterrupts (); while ( MyValue == 0); // Wait for interrupt TurnOnLED (); There is a good chance the program will freeze forever in the while loop, as (according to the optimizer) the MyValue global s value never changes in the loop. By making the global variable volatile, you are declaring to the compiler that the value may change due to circumstances it is not aware of, forcing it to generate code to reload the value each time. 8

CHAPTER 5. THINGS YOU NEED TO KNOW 9 5.3 Pay attention to variables needing atomic access There s another subtle bug in the above code sample; it s possible at the machine code level for an interrupt to occur half way between the fetching of the two bytes of the integer variable MyValue, causing corruption if the variable s value is altered inside the ISR. This can be avoided by making the fetching of the variable s value in the main program code atomic, by disabling the global interrupt enable bit while the fetching is taking place. In avr-libc this can be done in the following manner: # include <avr / interrupt.h> # include <util / atomic.h> volatile int MyValue ; ISR ( SomeVector_vect ) MyValue ++; int main ( void ) SetupInterrupts (); int MyValue_Local ; do ATOMIC_BLOCK ( ATOMIC_RESTORESTATE ) MyValue_Local = MyValue ; while ( MyValue_Local == 0) // Wait for interrupt TurnOnLED (); Your compiler may vary. 5.4 Each interrupt source has exactly one flag to indicate that the event occurred If two or more of the same interrupt event occurs while you are in the middle of processing an ISR, you will only receive one ISR call for the event when the current ISR terminates, and the remaining interrupt events will be lost. 5.5 The interrupt source flag is usually cleared when the ISR fires This isn t always the case (some interrupt flags are cleared when a particular register is read, such as the USART receive complete flag), however, this is more of an exception to the rule. The upshot of this is that if you receive another interrupt to the source you are currently processing while in its ISR, you ll get another call to the ISR once the current one terminates. Again, you are still limited to a single event occurred flag for each interrupt, so you can miss interrupts if many happen at once before you have a chance to process them.

Chapter 6 Putting it all together Rather than waste my efforts by repeating what I ve already done before here, I will instead direct readers to my previous tutorial on Interrupt Driven USART Communications for a short, practical example of how to use interrupts in an application. 10