DT131B
Embedded Systems Programming
Lecture 20-21: Micro Controllers-4 – Interrupts
– Timers
Adapted from Barnett, Cox and O’Cull(2007), Embedded C Programming and the Atmel AVR.
Dawit Mengistu (dawit.mengistu@hkr.se)
Input Output Techniques
As explained in previous lectures, transferring data between peripheral and processor can take place in one of the following ways:
• Programmed
• Interrupt Driven
• Direct Memory Access (DMA)
2
Input Output Techniques
3
Review of Programmed I/O
• Alsocalledpollingmethod
• CPU has direct control over I/O – Initialize I/O
– Sensing status (usually with a while loop) – Read/write data
• CPUwaitsforI/Omoduletocompleteoperation
• WastesCPUtime,oftennotusefulinreal-time
applications.
Examples: the digital input and serial communications in Lab4.
4
Review of Interrupt Driven I/O
• OvercomesCPUwaiting
• NorepeatedCPUcheckingofdevice • I/Omoduleinterruptswhenready
Basic Operations
• CPU issues read command
• I/O module gets data from peripheral whilst CPU does other work
• I/O module interrupts CPU
• CPU requests data
• I/O module transfers data
5
Interrupts
• Intheserialcommunicationsseenearlier,theCPU has to continuously poll for the transmit/receive status of devices .
• Pollingwastesusefulexecutiontimeandisnot generally recommended in real time applications.
• Interruptshandleunscheduled,highpriority events that might occur inside or outside the μC.
6
Simple Interrupt Processing
7
Interrupt I/O: CPU Viewpoint
• Issue read command
• Do other work
• Check for interrupt at end of each instruction cycle
• If interrupted:-
– Save context (registers)
– Process interrupt
• Fetch data & store
8
Changes in Memory and Registers for an Interrupt
• How to identify the module issuing the interrupt?
• How to deal with multiple interrupts?
– i.e. an interrupt handler being interrupted
9
Interrupt Service Routine (ISR)
• Whenaninterruptoccurs,theμCcompletesthe current instruction and transfers control to the interrupt event.
• Aninterrupteventusuallyhasaninterruptservice routine (ISR), a program code executed to address the event.
• When the ISR execution is completed, control is returned to where the μC left when the interrupting event occured.
• TheISRforoneinterruptpossiblymaynotbe completed before another interrupt occurs.
10
MASTER intr request
data/address
intr ack
When I/O device needs MASTER attention, an interrupt signal is sent
MASTER is “forced” to suspend its current task
MASTER acknowledges interrupt and jumps to interrupt service routine
When finished control is returned to the interrupted task
I/O Interrupt Processing
SLAVE
Status Regs
Control Regs Data Regs
Processor
Key observations:
– MASTER is free to do something else until attention is needed
– Improves utilization of MASTER, leading to a much better response
– I/Os can proceed asynchronously
11
mechanism
Multiple Interrupts
• Eachinterruptlinehasapriority
• Higherprioritylinescaninterruptlowerpriority
lines
• High-qualitysystemssupportinterruptnestingand bus mastering.
Example: The PC Bus
• 80×86 has one interrupt line
• 8086 based systems use one 8259A interrupt controller
• 8259A has 8 programmable interrupt lines
12
Properties of Interrupts
• Interruptlatency
– The elapsed time between the occurrence of an interrupt and the execution of the first instruction of the interrupt service routine (ISR).
– Indirectly related to system responsiveness. The smaller the latency, the faster the response.
• Interruptscanhappenatanytimeandinany order (but can be “masked” in some processors).
• Interruptscanbeignored(masked)whencritical task is executed.
13
ATMega168/328 Interrupts
• Our μC has two external interrupt lines (pins). The μC can be programmed in such a way that when state change occurs on these pins, a corresponding ISR can be executed. The ISR has a known starting address.
• It has also internal interrupts such as: -reset
-timer
-USART (receive/transmit)
-ADC, … 14
ATMega 168 μC Pin Diagram
15
Arduino Board Pin Diagram
AREF
GND
13
12
11
10
9
8
7
6
5
4
3
2
1
0
Arduino
PB5
PB4
PB3
PB2
PB1
PB0
PD7
PD6
PD5
PD4
PD3
PD2
PD1
PD0
Atmga168
SW1
RGB-G
RGB-B
RGB-R
LED6
LED5
LED4
LED3
LED2
LED1
SW2
Prototyp
21
22
19
18
17
16
15
14
13
12
11
6
5
4
3
2
Atmga168
0
1
2
3
4
5
Arduino
PC0
PC1
PC2
PC3
PC4
PC5
Atmga168
L
P
Prototyp
23
25
25
26
27
28
Atmga168
P= Potentio meter, L = LDR sensors
16
LED3 LED2 LED1
LED6 P LED7 LED5
SW1
SW2
LED4 L
R
Pin Map
17
ISR Address Table on ATMega168 /328
18
Steps:
Programming Interrupts
1. Write the program that should be executed (ISR) when the event triggering the interrupt occurs.
2. Ensure the ISR for a specific interrupt points to the correct interrupt vector (starting) address.
3. Enable global interrupt in the status register of the processor by calling sei() (enable interrupt).
This Enables the Global Interrupt Enable (I-bit) in the Status Register (SREG).
4. To disable interrupts, call cli() (clear interrupt). Note: It may be necessary to disable interrupts in some cases
19
Programming Interrupts (cont’)
• Enable the specific interrupt system (INTx or Vector number of the particular interrupt).
– Enabling the specific interrupt (internal or external) register and/or, – Setting the Interrupt Enable bit of the I/O concerned.
• When an interrupt occurs, the Global Interrupt Enable (I-bit) in the Status Register (SREG) is cleared in order to disable other interrupt calls.
• Your software can write logic 1 to the I-bit to enable nested interrupts (interrupt to interrupt the interrupt), if needed.
• The I-bit is automatically set when the program exits the interrupt routine.
20
Interrupt Execution Flow
Execute ISR
21
Example
• Implement external interrupt INT0 to detect the pressing of a button connected to the ground (similar to in Lab4).
• INT0 shares pin with PIND2
• The code lights three LEDs connected to PD5-7 in a circular manner, with pressing of the button.
ISR(INT0_vect){
unsigned char i;
for (i=0; i<10; i++)
_delay_ms(100); // Software debouncing control if (counter == 3) counter = 0;
PORTD = (1 << (counter+5));
PORTD |= 1<
volatile int counter = 0; //use the volatile qualifier on optimizing compilers
-next
Timers
Are used for several purposes such as:
• Recordthetimewhenaneventoccurs
• Calculatethetimedifferencebetweenevents
• Perform tasks at specific or periodic time instants
• Createaccuratetimedelays
• Generate waveforms of certain shape, period or duty cycle.
23
Timer Functions
1. Input Capture (typically used to measure time interval between events):
• An input signal is connected to a pin, designated as input capture pin, of the timer.
• When a preset event (rising edge, falling edge, change) occurs on the input capture pin, the current value of the timer is stored in a register. The time interval between successive events can be measured.
2. Output Compare (used to control timing of events):
• Some timers have a pin designated as output compare pin.
• When the timer reaches a preset value, the output compare pin
is automatically changed to logic 0 or logic 1.
24
Timer Operation
• Our μC has three timers: Timer0 (8-bit), Timer1(16-bit) and Timer2 (8-bit).
• Each timer is associated with a counter and a clock signal.
• The counter is incremented by 1 in every clock cycle.
• The clock signal of a timer can come from the internal system clock or an external clock source.
• A prescaler is used to make the timer count at a slower rate than its clock signal.
desired clock = system clock / prescaler
All timers have 10-bit prescalars.
They are used for event counting, PWM, waveform generation. Timer1 is additionally used for time interval measurement.
25
Timer Modes
• Timers are usually used in the following modes:
– Normal Mode
– CTC (Clear Timer on Compare) – Fast PWM
– Phase Correct PWM
26
Normal Mode
• Thetimerwillcountuptoitsmaximumvalue.
• When it reaches its maximum value, it sets the Overflow interrupt (Timerx_OVR) and resets timer to its original value.
255/65535
• ftimer = fclock /2n (n = 8/16).
27
Timer Registers
• TCNTx: Timer/Counter a 16-bit register stores the current value of timer x.
• TCCRx: Timer/Counter Control Registers configures the operations of Timer x. (Timer1 has 2 registers, TCCR1A and TCCR1B)
• ICR1: Input Capture Register stores timer value when an event occurs on input capture pin (Timer 1 only).
• OCRxA, OCRxB: Output Compare Registers store the preset values for output compare.
• TIMSKx enables timer interrupts
• TIFRx monitors status of timer interrupts.
28
Example: Timer0 Registers
29
TCR0 bits
000 None
001 clkI/0
010 clkI/0/8
011 clkI/0/64
100 clkI/0/8clkI/0/256
101 clkI/0/8clkI/0/1024
110 External clock on T0 (falling edge trigger) 111 External clock on T1 (rising edge trigger)
Waveform generation mode (WGM)
00 Normal
10 PWM, Phase Correct 01 CTC
11 Fast PWM
CS2:0 (clock select prescaler)
30
Timer Registers
• The TIMSK register is used by all three timers. Timer 0 uses the Timer/Counter 0 Output CompareMatch Interrupt Enable (OCIE0) bit and the Timer/Counter 0 Overflow Interrupt Enable (TOIE0) bit.
When the OCIE0 bit and the I-bit in the Status Register are both set to 1, the Timer/Counter 0 Compare Match interrupt is enabled. When the TOIE0 bit and
the I-bit in the Status Register are both set to 1, the Timer/Counter 0 Overflow interrupt is enabled.
• The TIFR register is used by all three timers. Timer 0 uses the OCF0, which sets for an output compare match. Timer 0 also uses the TOV0, which sets when Timer/Counter 0 Overflows.
31
Timer1 Registers
OutputCompare Register 1ChannelA (OCR1AH/ OCR1AL). The OCR1A register holds a user-defined 16-bit value that is continuously compared with the TCNT1 register when Channel A is used.
Output Compare Register 1 Channel B (OCR1BH/ OCR1BL). The OCR1B register holds a user-defined 16-bit value that is continuously compared with the TCNT1 register when Channel B is used.
Input Capture Register 1 (ICR1H/ICR1L).
ICR1 is a 16-bit register used to capture the value of the TCNT1 register when a desired edge on ICP1 pin has occurred.
32
Example
Write a C program to toggle pin 2 of PORTB every 2 seconds. Use timer 0 overflow interrupt to create delays of 2s each. (Remember: our clock speed is 20MHZ)
#include
#include
volatile int overflow_count;
ISR(TIMER0_OVF_vect){ // handler for Timer1 overflow interrupt
overflow_count++; // increment overflow count
if (overflow_count >= 156){ // when about 2s has passed
overflow_count = 0; // start new count if (PORTB & 0x01)
PORTB &= 0xfe; else
} }
33
PORTB |= 0x01; // toggle pin 0 of port B
Example (cont’d)
int main(void) {
DDRB = 0xFF; // set port B for output
PORTB = 0x00; // initial value of PORTB
overflow_count = 0; // initialise overflow count
TCCR0A = 0b00000000; // normal mode
TCCR0B = 0b00000101; // prescaler 1024
TIMSK = 0b00000001; // enable Timer 0 overflow interrupt sei(); // enable interrupt subsystem globally
while (1){
; //do anything you want to do here… } // infinite loop
return 0; }
The above delay is not accurate. How can we improve it?
34
Example: Time lapse
Write a program to measure the time taken to execute a code to implement a certain functionality.
#include
#include
#include
volatile uint32_t n;
ISR(TIMER1_OVF_vect){ // handler for Timer1 overflow interrupt
n++; // increment overflow count }
void dosomeFunctionality(){
//here we have the code for implementing the algorithm //….
}
35
Example (cont’d)
int main(void) {
uint32_t elapse_time;
TCCR1A = 0b00000000; // normal mode
TCCR1B = 0b00000001; // no prescaler, internal clock TIMSK = 0b00000100; // enable Timer 1 overflow interrupt n = 0; // reset n
TCNT1 = 0; // reset Timer 1
sei(); // enable interrupt subsystem globally
// —– start code ————–
Call your function Here…. dosomeFunctionality();
// —– end code —————–
}
36
elapse_time = n * 65536 + (uint32_t) TCNT1; cli(); // disable interrupt subsystem globally return 0;
CTC Mode
• We use the output compare register (OCR) to store a value of our choice
• When the timer value matches with the content of the OCR,
– An output compare pin will be set to high/ low/ toggled
– Generates PWM signals and can be used as DAC
– Can also trigger an interrupt handler routine
– When the time reaches OCR value it resets to 0.
37
Fast PWM Mode
• Timer goes from 0 to TOP, where TOP is equal to the value in OCRnx register. (or)
0xFF (for 8-bit mode, WGM = 0101) or 0x1FF (for 9-bit mode, WGM = 0110) or 0x3FF (for 10-bit mode, WGM = 0111) or
• Whenever the timer value reaches the value of OCRnx, an output pin is pulled low and when counting begins from 0, it is pulled high again to Vcc.
38
fclock = ?
39
Phase Correct PWM Mode
• This is similar to fast PWM except that the timer starts counting down instead of resetting to 0 when it reaches the maximum.
• The value of the Ocn pin toggles only when the value of OCRn matches with the TIMERn content.
40
fclock = ?
41
Produce a Custom Waveform
• Select the operation mode of Timer 1: CTC, fast PWM, or phase correct PWM, … (i)
• Selecthowoutputcomparepinwillbeupdatedon compare match event. (i)
• Configure timer 1: clock source, prescaler, …(i)
• Putcorrectvaluesintheoutputcompareregisters.(ii)
(i) set TCCR1A and TCCR1B
(ii) set OCR1A
42
Example: PWM
Write a code to generate a PWM signal of duty cycle 25%
i) With Timer 0
ii) With Timer 1
How would you increase the duty cycle to 50%?
43