Presentation is loading. Please wait.

Presentation is loading. Please wait.

Embedded Systems Programming Interrupts and Handlers

Similar presentations


Presentation on theme: "Embedded Systems Programming Interrupts and Handlers"— Presentation transcript:

1 Embedded Systems Programming Interrupts and Handlers
Real Time, and Timers Interrupts and Handlers 1

2 Real Time Systems - Definitions
Real Time Systems – are hardware or software systems that are subject to a "real-time constraint" – i.e., operational deadlines from event to system response. Deadline – the latest time by which the system must respond to an event. For periodic systems (where events happen repeatedly) this may be expressed as maximal allowed time interval between an event occurrence and the system response. Hard RT systems – in such system the completion of an operation after its deadline is considered useless - ultimately, this may lead to a critical failure of the complete system. Examples: Car engine (delayed signals may result in engine failure or damage) Medical equipment such as heart peacemakers. Aircraft controls Syncronisation of Robots in an automated production line 2 Embedded Systems Programming II Richard Anthony, Computer Science, The University of Greenwich

3 Real Time Systems – Definitions
Soft RT systems - tolerate such lateness, and may respond with delay resulting for example with decreased service quality. Examples: Video conference systems (delay may result in, for example, dropping frames while displaying a video). A bus-stop display sign which is updated a few milli-seconds late (or even a few seconds late). An Indicator light on a car that is supposed to flash at a rate of (for example) 1Hz, but perhaps sometimes the rate drifts by up to 10%. A burglar alarm is supposed to turn on the siren within 0.1 second of an intrusion – but a delay of a few milliseconds here is tolerable. As these examples illustrate, there are some application-specific meanings of soft-real-time, and of the amount of tolerance acceptable. In most cases soft real-time events are not safety-critical. 3 Embedded Systems Programming II Richard Anthony, Computer Science, The University of Greenwich

4 Timing - Synchronous and Asynchronous behaviour
Synchronous systems – all operations are coordinated under the centralized control of a fixed-rate clock signal or several clocks. The coordinator uses a clock to initiate actions. This leads to events occurring at predictable times. Example: A sensor that is sampled every second (a new reading is taken) Asynchronous systems – operate more autonomously (than synchronous systems) and under distributed control (have no global clock). They are usually triggered by signals indicating completion of instructions and operations (which may last longer or shorter depending on circumstances). Example : An urgent condition arises in a chemical plant where a valve A should be closed before valve B is opened – but valve A is still open when valve B is opened (such a condition must be signalled, and recognized as soon as possible). Embedded Systems Programming II Richard Anthony, Computer Science, The University of Greenwich

5 Timing – Scheduling, and Urgent events
Scheduling – is the process of deciding how to commit resources between a variety of possible tasks. Time can be specified (for example scheduling a flight to depart at 8:00), or floating as part of a sequence of events (one task starts after a previous one is completed). Time can be specified in order to run a task only one time (one shot). Time can be specified in order to run a task periodically (hourly, daily, etc.). Urgent events – some events (internal or external), that may appear unpredictably at any time while a system operating (usually out of schedule). These events may require an immediate response and handling. However they may need to be prioritized in order to distinguish their importance in case more than one occurs at the same time. Embedded Systems Programming II Richard Anthony, Computer Science, The University of Greenwich

6 Timing example – Using a busy wait to flash a LED at 1HZ
Requirements – LED on, wait ½ second, LED off, wait ½ second, repeat. Main: rcall LED_ON rcall Delay_HalfSecond rcall LED_OFF rjmp Main Problems: - the code runs continually (effectively as a single thread) - the CPU is utilised 100% - nothing else can run at the same time. On LED Off 0.5 second Time Start 0.5S 1.5S 1.0S 2.0S Timing diagram

7 Timing example – Using a Timer to flash a LED at 1HZ
Initialisation: clr r20 //LED status flag rcall ConfigureTimer rcall LED_ON Main: rjmp Main Timer_Interrupt_Handler: // Turn LED on or OFF // depending on its current status // Remember LED status in // register r20 0=off 1=on The code runs effectively as two independent and asynchronous threads The timer interrupt handler only uses the CPU for a small fraction of total time. Other code can run at the same time – e.g. place some other logic in the Main loop. On LED Off 0.5 second Time Start 0.5S 1.5S 1.0S 2.0S Active Interrupt Handler Not active Timing diagram

8 Real Time Systems – Real-Time Clocks (1)
Real Time Clock - is a computer/device clock (most often in the form of an integrated circuit) that keeps track of the current time. Why is it needed in general computing? To synchronise control and monitoring actions with (timing of) real-world events, File timestamps, Transaction timing, deadlock detection, security (timestamping of network messages to prevent replay), etc. Why is it important in embedded systems specifically? Periodic measurement or monitoring, Event timestamps (i.e. recording the time or sequence at which events occur) Controlling peripherals, e.g. controlling a motor at a particular speed using Pulse-Width Modulation ( a timer generates the pulses), Waveform generation for advanced applications. 8 Embedded Systems Programming II Richard Anthony, Computer Science, The University of Greenwich

9 Real Time Systems – Real-Time Clocks (2) - Implementation
Hardware: The most accurate method. Uses a electronic circuit and a quartz crystal. Needs a small battery to keep it going at all times (even when main power is lost). A PC has one; thus it ‘knows’ the time even after it has been turned off. Runs at a fixed speed. Software (delay loop): Universally possible in any computer system. Wastes processing power. Unreliable because the timing will be altered if the delay routine is interrupted (e.g. if an interrupt handler is called because of some external event the delay countdown is temporarily stopped). Hybrid hardware / software solutions: A hardware logic unit provides the counting and timing functions, and is configured by software, thus it can be PROGRAMMED to perform whatever counting / timing function is needed. The most flexible (not always available, but ATmega1281 has SIX). Accuracy varies, but can be as accurate as a purely hardware clock. 9 Embedded Systems Programming II Richard Anthony, Computer Science, The University of Greenwich

10 Real Time Systems – Programmable Timers and Counters (1)
Counter - This is a functional unit that counts events Such as Hardware clock pulses, External events from an interface pin. The event count is stored in a register that can be accessed from software (Set to an initial value, reset to 0, read value) Most counter devices support the generation of an interrupt when a certain Count value is reached. Count register ‘Maximum count’ register Compare logic External events Programmed value Programmed configuration (set value, clear value, read value) Generate interrupt 10 Embedded Systems Programming II Richard Anthony, Computer Science, The University of Greenwich

11 Real Time Systems – Programmable Timers and Counters (2)
Timer - This is a functional unit that measures a time interval Such as: Determining the elapsed time since system startup, Keeping track of real-world time, Measuring time between events (S/W events or external). Time is measured by counting clock pulses. The time value is stored in a register that can be accessed from software (Set to an initial value, reset to 0, read value). Most timer devices support the generation of an interrupt when a certain Time interval has passed. ‘Time value’ register ‘Time interval’ register Compare logic Clock pulses Programmed value Programmed configuration (set value, clear value, read value) Generate interrupt 11 Embedded Systems Programming II Richard Anthony, Computer Science, The University of Greenwich

12 Real Time Systems – Programmable Timers and Counters (3)
The last two slides show that counters and timers have closely-related functionality and share much of the same logic. For this reason they are usually combined into a single functional component called a ‘Timer / Counter’ which can be programmed to perform whichever function is required. Typical combined functionality uses include: Counting the number of external events that occur in a given time frame. Counting the number of millisecond time intervals (from the timer part), to display wall-clock time in seconds, minutes, hours etc. The ATmega1281 has six timer / counters, these are referred to in the documentation as TC0 … TC5. 12 Embedded Systems Programming II Richard Anthony, Computer Science, The University of Greenwich

13 Real Time Systems – Programmable Timers and Counters (4)
Precision and ranges Counters and timers have a fixed maximum precision which is designed in. For example: an 8-bit counter can only count up to 255 events, or a 16-bit timer measures intervals up to clock pulses. With a 1MHz input clock, a 16-bit timer can measure intervals of milliseconds; but what if you want to measure a 10-second interval? A ‘Clock pre-scaler’ is usually built in to enable counting over higher ranges, and timing at application-level speeds. (This is also known as a ‘clock divider’ because a prescaler of 1024 will count 1024 input clock pulses, and only pass one pulse to the timer). Prescaler example: If a pre-scaler of is used, the 16-bit timer can now measure intervals of up to 67 seconds. In this case, if the time interval register is loaded with the decimal value 9781 then an almost exactly 10-second period can be timed. An interrupt can be generated when the end of the period is reached. 13 Embedded Systems Programming II Richard Anthony, Computer Science, The University of Greenwich

14 ICP1 (+ can be triggered direct from Analogue comparator)
Real Time Systems – Programmable Timers and Counters (5) Timer / Counters perform a variety of functions and thus must be precisely configured in any particular use situation. Place configuration data values into special ‘Configuration Registers’. The ATMega1281 Timer / Counters have the following characteristics (64-pin package) T/C Preci -sion (bits) Clock prescaler options External clock input Can generate interrupts PWM outputs Output Compare Modulator Count external events Capture occurrence time of external event 8 1,8,64,256,1024 N Y OC0A * OC0B OC0A T0 1 16 OC1A OC1B * OC1C T1 ICP1 (+ can be triggered direct from Analogue comparator) 2 1, 8, 32, 64, 128, 256,1024 TOSC1 TOSC2 OC2A 3 OC3A OC3B OC3C T3 ICP3 4 5 * This output can be used to auto-trigger the Analogue to Digital Converter 14 Embedded Systems Programming II Richard Anthony, Computer Science, The University of Greenwich

15 Clock divider (to allow the device to operate at slower speed, e.g.
time longer intervals) ‘Overflow’ interrupt request Control register (specifies required behaviour mode) Current value ‘Compare match’ interrupt request Waveform output (such as Pulse-Width Modulation) Target value

16 Real Time Systems – Programmable Timers and Counters (6)
Configuration registers (TC0 is used as an example) Timer/Counter Control Register 0A – sets the main operation mode of TC0 I/O register TCCR0A Compare Match Output A Mode (behaviour of OC0A pin) Compare Match Output B Mode (behaviour of OC0B pin) Configure whether to operate as a counter, timer or waveform generator 16 Embedded Systems Programming II Richard Anthony, Computer Science, The University of Greenwich

17 Real Time Systems – Programmable Timers and Counters (7)
Configuration registers (TC0 is used as an example) Timer/Counter Control Register 0B – sets the main operation mode of TC0 I/O register TCCR0B Force Output Compare A, (directly control OC0A pin) Force Output Compare B, (directly control OC0B pin) Set internal clock and prescaler values or external clock Configure whether to operate as a counter, timer or waveform generator 17 Embedded Systems Programming II Richard Anthony, Computer Science, The University of Greenwich

18 Waveform Generation Mode selection (3 configuration bits)
TCCR0B bit 3 is WGM2, TCCR0A bit 1 is WGM1, TCCR0A bit 0 is WGM0 Embedded Systems Programming II Richard Anthony, Computer Science, The University of Greenwich

19 Clock / prescaler selection ( 3 configuration bits)
TCCR0B bit 2 is CS02, TCCR0B bit 1 is CS01, TCCR0B bit 0 is CS00 Embedded Systems Programming II Richard Anthony, Computer Science, The University of Greenwich

20 Real Time Systems – Programmable Timers and Counters (10)
Timer/Counter Register 0 – provides read / write access to the internal 8-bit counter in TC0 I/O register TCNT0 The value of the internal counter. I.e. the number of time-intervals that have passed (clock pulses) Or the number of ‘events’ that have been counted 20 Embedded Systems Programming II Richard Anthony, Computer Science, The University of Greenwich

21 Real Time Systems – Programmable Timers and Counters (11)
Output Compare Register 0 A – This is the ‘Maximum count’ register, i.e. it signifies how high to count up to, or how long the time interval should be. Used in PWM and Output Compare modes (associated with OC0A pin) I/O register OCR0A The OCR0A value is continuously compared with the internal counter value. The device can be configured to generate an interrupt when the two values match. Embedded Systems Programming II Richard Anthony, Computer Science, The University of Greenwich 21

22 Real Time Systems – Programmable Timers and Counters (12)
Output Compare Register 0 B – This is the ‘Maximum count’ register, i.e. it signifies how high to count up to, or how long the time interval should be. Used in PWM and Output Compare modes (associated with OC0B pin) I/O register OCR0B The OCR0B value is continuously compared with the internal counter value. The device can be configured to generate an interrupt when the two values match. Embedded Systems Programming II Richard Anthony, Computer Science, The University of Greenwich 22

23 Real Time Systems – Programmable Timers and Counters (13)
Timer / Counter Interrupt Mask 0 –Three bits in this register are used to mask / enable the interrupts generated by TC0. I/O register TIMSK0 Generate Interrupt when OCR0B matches TCNT0 (if this bit set to ‘1’) Generate Interrupt when OCR0A matches TCNT0 Generate Interrupt when TCNT0 value reaches its maximum 8-bit value and overflows back to 0 (if this bit set to ‘1’) 23 Embedded Systems Programming II Richard Anthony, Computer Science, The University of Greenwich

24 Real Time Systems – Programmable Timers and Counters (14)
Timer / Counter Interrupt Flag Register 0 – Three bits in this register are used to signify if an interrupt has been generated by TC0. I/O register TIFR0 Set when OCR0B matches TCNT0 Set when OCR0A matches TCNT0 Set when TCNT0 value reaches its maximum 8-bit value and overflows back to 0 24 Embedded Systems Programming II Richard Anthony, Computer Science, The University of Greenwich

25 Register programming example –Timer 0 (Assumes 1MHz Clock)
void InitialiseTimer0() // Generate an interrupt after a 1/4 Second interval { TCCR0A = 0b ; // Normal port operation, Normal waveform TCCR0B = 0b ; // Normal waveform, Use 1024 prescaler // Overflow occurs after counting to 256 (but already divided by 1024) // So overflow occurs after 1024 * 256 / = seconds TCNT0 = 0b ; // Timer/Counter count/value register TIMSK0 = 0b ; // Use 'Overflow' Interrupt, } ISR(TIMER0_OVF_vect) // Overflow Handler for TC 0 (Shift LED BAR left) LED_value *= 2; // Shift left by multiplying by 2 if(0 == LED_value) // Check if bar has gone past the leftmost value LED_value = 1; // Reset LED BAR position to right hand end PORTB = ~LED_value;

26 Interrupts - Event-driven program design
Event-driven programming is the best way to implement real-time systems. Many real-world ‘events’ are asynchronous (i.e. they happen independently of the monitoring / control system) Examples include – key press, alarm condition, temperature change … Thus the system needs to have a way to detect these events rapidly. ►Interrupts are ideal for this. For each type of ‘event’ to be detected there must be an interrupt system in place, comprising: Interrupt handler – program code that is activated when the event is detected. Interrupt vector – points to the interrupt handler address in program memory. Interrupt mask – determines if the interrupt is enabled, or disabled. 26 Embedded Systems Programming II Richard Anthony, Computer Science, The University of Greenwich

27 Interrupts – compared with Polling (Example: scanning for switch inputs)
Time Start (T0) Active Interrupt Handler Not active Polling Sample logic Event of interest TE Event is not detected until next polling action. (A very short-lived event can be missed by polling). Event is detected by hardware within 1 clock cycle. The interrupt H/W operates automatically and asynchronously. Even very short-lived events are detected. The Interrupt handler is invoked automatically. Timing diagram Example – detecting switch inputs on bits 2 and 3 of Port D. Port D bit 2 has alternate function INT2, Bit 3 has alternate function INT3. Therefore without any H/W changes it is possible to implement either polling or an interrupt-driven approach to use these two switches to control an application’s behaviour. Interrupt-driven approach leads to simpler code design, allows multitasking and ensures fast reaction to events.

28 Interrupt Vectors - ATmega1281 has 57 Interrupt Vectors (inc reset)
(this slide shows approximately half of the interrupt vectors) Direct external event interrupts Timer 2 event interrupts Timer 1 event interrupts Timer 0 event interrupts 28 Richard Anthony, Computer Science, The University of Greenwich

29 Interrupts – Interrupt Handlers (Assembly example)
An ‘Interrupt Handler’ is a (usually) short piece of program code that is activated when the interrupt has been detected. The operation of an Interrupt Handler is like a subroutine except that instead of being invoked by Call or Rcall, it is triggered by the appropriate external event. The mechanism for writing an interrupt handler is very similar to writing a subroutine except for two differences: The Interrupt Handler ends with ‘Return from Interrupt’ Reti, instead of Ret. 2. The Interrupt Vector must point to the Interrupt Handler. .org 0 Rjmp INIT ; Reset handler vector at address 0 (two bytes long) Rjmp EXT_INT0 ; INT0 interrupt vector at address 2 (two bytes long) Rjmp EXT_INT1 ; INT1 interrupt vector at address 4 (two bytes long) INIT: … ; ‘Normal’ code that runs from startup and also from Reset EXT_INT0: … ; Interrupt handler code for INT0 Reti ; return from interrupt EXT_INT1: … ; Interrupt handler code for INT1 29 Embedded Systems Programming II Richard Anthony, Computer Science, The University of Greenwich

30 Interrupts – Interrupt Prioritisation
Interrupts must be prioritised – so that the system knows what to do first if two different events happen at the same time (highest priority first). On many systems the priority of each interrupt can be programmed. On the ATmega1281 the priority is fixed in the interrupt vectors number order. Highest Priority (Reset) Highest priority ‘usable’ interrupt (INT0) Lower Priority Embedded Systems Programming II Richard Anthony, Computer Science, The University of Greenwich 30


Download ppt "Embedded Systems Programming Interrupts and Handlers"

Similar presentations


Ads by Google