Title: RealTime Programming in Embedded Systems
1Lecture 2
- Real-Time Programming in Embedded Systems
2Categories of RT Systems
A real-time system is defined as one in which the
timing of the result is as important as the
logical correctness. Savitzky http//www.stsc.hi
ll.af.mil/crosstalk/2003/11/0311ludwig.html
Hard Real-Time System
Soft Real-Time System
- Critical pieces have absolute deadlines
- Missing deadline means system failure
- Response times must be deterministic
- Average performance or response time is
emphasized - Missing a deadline is not necessarily catastrophic
3Some Hard RT Systems
Airplane controls in a fly-by-wire system
Arc Fault Detector / Circuit Interrupter for
nuclear sub. Arc-faults, caused by water
dripping on to a live wire, pose a serious fire
hazard in an aircraft.
Real-time classification can be more obvious when
the consequences of long response time are
severe. However the real classifier is really
the extent to which deterministic execution time
is required.
4Some Soft R/T Systems
- Objective minimize total tardiness
- Non-deterministic timing tolerated
Bike Computer
Home Thermostat
Vending Machine
5http//www.embedded.com/showArticle.jhtml?articleI
D9900353
A typical system is a hybrid, with a few tasks
having constraints like those of a hard
real-time system, and many more less important
tasks (or tasks more amenable to latency) which
have soft requirements.
- Respond to button presses
- Update screen periodically
- Control DVD door motor
- Process audio samples to add audio effects such
as surround sound, equilization, etc. - Read optically encoded volume knob
- Respond to remote control signals
A microprocessor in this Home Theater System
might have to
6Breaking down of requirements
What are things that are likely to require the
developer to deal with them in a hard or
deterministic manner?
- Respond to button presses
- Update screen periodically
- Control DVD door motor
- Process Audio samples to add DSP effects surround
sound..etc. - Read optically encoded volume knob
- Respond to remote control signals
- Process Audio samples to add DSP effects surround
sound..etc. - Read optically encoded volume knob (depends on
implementation) - Respond to remote signals?
7Optically Encoded Knob
Knob Interface The optically encoded knobs put
out two out of phase pulse trains which differ in
relative phase depending on the direction in
which the switch is turned.
Depending on the implementation, it might be
considered a device failure if these pulses were
missed or misinterpreted
8IR Remote Control Signals
36 or 38kHz carrier
If we want a processor to be able to read and
respond to these signals, there are clearly some
timing requirements that must be met. However,
due to the expected flaky nature of remote
controls, and the fact that the signal is
repeated over and over again, we may tolerate
occasional missed bits due to the processor being
busy doing something else.
9A possible event driven program
while (1) if (adc_sample_ready) process_samp
le() if (button_pressed) interpret_button()
check_display() if (display_change) update_
display() read_volume_knob() if
(knob_moving) process_vol_change()
10Program Structure to Respond to Events
- Polling Loop
- Examine each input in turn to see if an event
requires service
- Interrupt
- Provide event driven structure
- Allow non-sequential running of code. Section of
code to handle the event is run when the event
signal is generated - When interrupt handler is complete, processor
continues running code where it left off
11Some Examples of Interrupt Sources
- External Signals
- Some GPIO pins
- Reset
- NMI (Non Maskable Interrupt)
- Internal Peripherals
- Timers
- Serial Ports
- Comms Interfaces
- A/D and D/A Converters, etc.
- Events
- Illegal Instruction Trap
- Bus Errors / Page Fault
- Power-Fail Detection
- Privilege Violation
12Actions When Processor Jumps to ISR
- Processor finishes what it is currently doing
(granularity depends on processor) - State of processor saved
- Program counter (return address)
- Registers
- ISR is executed
- Return from ISR instruction at end of ISR
- Processor state is restored
- Returns to the next instruction to execute
some of this is usually the responsibility of
the ISR writer
13Interrupt Latency
- Time it takes processor to switch from what its
doing to the ISR after the Interrupt Signal is
active - Can be variable, especially in machines with
variable duration instructions (is variable in
Rabbit) - Actual hardware interrupt latency doesnt tell
the whole story - How long, (and is it deterministic?), will it
take to actually respond this takes into
account all the instructions that the processor
must execute just to get to your real code.
This is what really matters at the system level!
Also note that the C ISR can frequently be
optimized by writing in assembly, but mixing
assembly and C requires some understanding of how
the compiler workswe will work on this knowledge
for the RABBIT next week.
14 1e4a F5 push af
1e4b E5 push hl 1e4c
CD0F30 call entint_ 1e4f 21F92F
ld hl,2FF9 1e52 E5 push
hl 1e53 D9 exx
1e54 210000 ld hl,0000
1e57 CD0A2F call sspixffn_
1e5a D33A3800 ioi ld a,(0038)
1e5e E602 and 02 1e60
28F8 jr z,1E5A 1e62
D33A4800 ioi ld a,(0048) 1e66 3222C0
ld (C022),a 1e69 3A5CC5 ld
a,(C55C)
prepare for interrupt save IP, etc., defined in
util.lib
C ISR in Dynamic C Environment
root debug interrupt void convert_isr() asm
loop1 ioi ld A,(PFDR) and 2 jr z,loop1
ioi ld A,(PGDR) ld (tempword1),A ld
A,(PFDRShadow) or 1 ioi ld (PFDR),A ioi
ld A,(PGDR) ld (tempword),A ld A,
(PFDRShadow) and 0fbh ioi ld
(PFDR),A endasm tempintptr (int
)tempword if (currentrbuf 0)
rdataptr (int )rdatabuf0 wordct else
rdataptr (int )rdatabuf1 wordct //
STREAMING MODE ROUTINE // etc..
save registers, defined in util.lib
2006 210100 ld hl,0001
2009 226C81 ld (816C),hl 200c
EF rst 28h 200d D9
exx 200e 210000 ld
hl,0000 2011 CD142F call
rspixffn_ 2014 C9 ret
restored saved registers, defined in util.lib
15Interrupt Priority
- In system with multiple interrupts, we want some
way to prioritize those interrupts. - Avoid moderately important tasks interrupting the
most time-critical tasks (and allow the reverse) - Simple summary IRQ is assigned a priority, and
processor enforces a system whereby lower
priority interrupts wont happen until higher
ones are finished
16- The priority of the interrupt is usually
established by bits in an I/O control register
associated with the hardware that creates the
interrupt. - The 8-bit interrupt register (IP) holds the
processor priority in the least significant 2
bits. When an interrupt takes place, the IP
register is shifted left 2 positions and the
lower 2 bits are set to equal the priority of the
interrupt that just took place. - This means that an interrupt service request
(ISR) can only be interrupted by an interrupt of
higher priority (unless the priority is
explicitly set lower by the programmer). The IP
register serves as a 4-word stack of 2-bit words
to save and restore interrupt priorities. - It can be shifted right, restoring the previous
priority by a special instruction (IPRES). Since
only the current processor priority and 3
previous priorities can be saved in the interrupt
register, instructions are also provided to PUSH
and POP IP using the regular stack. - A new priority can be "pushed" into the IP
register with special instructions (IPSET 0,
IPSET 1, IPSET 2, IPSET 3).
Proc Priority Effect
The effect of the processor priority on
interrupts is shown above.
17Interrupt Vectors
sometimes
- Each processor has predefined interrupt signals
(from its peripherals, pins..etc) - When that signal happens
- Processor checks to see if that source is enabled
- If so processor jumps to a predetermined
location, where a jump address is programmed in
memory. (This address is the location of the
user-defined interrupt service routine) - Often set in mapper instructions, or can be
written by the SW itself
Set in memory where it is predetermined (by
hardware) to jump when various interrupts occur
is called the Vector Table
18Rabbit 3000 has registers EIR, IIR These
registers point to the interrupt table with a
predefined structure. Thus the programmer
(and/or compiler/runtime model) can place the
interrupt table wherever it wishes. (Even move
it around)
19Using Interrupts (General)
- Identify interrupt signal that you wish to use
(i.e. what peripheral or pin) - Write an ISR (perhaps at first, just a shell of
one) - Hookup the ISR
- Make sure that the location of your ISR is in the
vector table in the appropriate place. - Enable that interrupt signal
- Usually a register which says whether to, and
under what circumstances to interrupt processor
20Example in Dynamic C (Input-Capture Peripheral)
SetVectIntern(0x15, convert_isr) // set up
ISR // see definition of SetVectIntern for
vector numbers WrPortI(ICCR,ICCRShadow,0x03)
// turns on input capture interrupt at priority
3 WrPortI(ICCSR,ICCSRShadow,0xf0) // under
what conditions will peripheral
interrupt? while (1) // do something
interesting, knowing that // every time that
peripheral wants us, well // run convert_isr
without worrying about it
21SetVectIntern(note that this and many similar
functions is considered part of Dynamic C)
- SetVectIntern ltSYS.LIBgt
- SYNTAX unsigned SetVectIntern(int vectNum, void
isr) - DESCRIPTION
- Function to set an internal interrupt jump table
entry. All Rabbit interrupts use jump vectors.
This function writes a jp instruction (0xC3)
followed by the 16 bit ISR address to the
appropriate location in the vector table. - The location in RAM of the vector table is
determined and set by the BIOS automatically at
startup. The start of the table is always on a
0x100 boundary. - It is perfectly permissible to have ISRs in xmem
and do long jumps to them from the vector table.
It is even possible to place the entire bodyof
the ISR in the vector table if it is 16 byte long
or less, but this function only sets up jumps to
16 bit addresses. - The following table shows the vectNum argument
that should be used for each peripheral or RST.
The offset into the vector table is also shown. - NEXT SLIDE
- PARAMETER1 Interrupt number. 0 - 15 are the only
valid values. - PARAMETER2 ISR handler address. Must be a root
address. - RETURN VALUE Address of vector table entry, or
zero if the vectnum is not valid.
22(No Transcript)
23Rabbit/Dynamic C Interrupt Steps
- Steps Followed by an ISR
- The CPU loads the Interrupt Priority register
(IP) with the priority of the interrupt before
the ISR is called. This effectively turns off
interrupts that are of the same or lower
priority. Generally, the ISR performs the
following actions - Save all registers that will be used, i.e. push
them on the stack. Interrupt routines written in
C save all registers automatically. Stand-alone
assembly routines must push the registers
explicitly. - Determine the cause of the interrupt. Some
devices map multiple causes to the same interrupt
vector. An interrupt handler must determine what
actually caused the interrupt. - Remove the cause of the interrupt.
- If an interrupt has more than one possible cause,
check for all the causes and remove all the
causes at the same time. - When finished, restore registers saved on the
stack. Naturally, this code must match the code
that saved the registers. Interrupt routines
written in C perform this automatically.
Stand-alone assembly routines must pop the
registers explicitly. - Restore the interrupt priority level so that
other interrupts can get the attention of the
CPU. ISRs written in C restore the interrupt
priority level automatically when the function
returns. However, stand-alone assembly ISRs must
restore the interrupt priority level explicitly
by calling ipres. - The interrupt priority level must be restored
immediately before the return instructions ret or
reti. If the interrupts are enabled earlier, the
system can stack up the interrupts. This may or
may not be acceptable because there is the
potential to overflow the stack. - Return. There are three types of interrupt
returns ret, reti, and retn.
24External Interrupts (R3000)
- Processor has 2 External IRQ lines
- Edge sensitive (Rising or Falling configurable)
- INT0 (PE0,PE4), and INT1(PE1,PE5)
- In ISR, state of pins can be read to determine
who interrupted you (if it is ambiguous) - External interrupts must be given a priority
level
Need to write an ISR Hook Up the ISR Enable the
IRQ
25Proposed Software Architecture for our receiver
- External Interrupt for Optically Encoded Volume
Knob (low priority) - Serial Port (for CODEC) or Timer Interrupt for
traditional A/D (high priority) - Main program for handling button presses and
screen updates and other slow control features - We just want to make sure that the main program
makes it around its main loop frequently enough
that missing a button press (slow) is unlikely.
26Simple ISR for knob
Hook sigA to PE0 and sigB to some other port
(Ill say PE2). Plan on enabling INT0A interrupt
for rising edge. root debug interrupt
knob_edge_isr() if (BitRdPortI(PEDR,2)
1) if (knobval lt maxval) knobval else i
f (knobval gt 0) knobval-- . . Sum
directions .
27Things We Want to Know About Interrupts
- Interrupts
- how do they really work?
- What capabilities do we need?
- Stop the running program on any instruction
- Vector to some other piece of code
- Resume right where we left off
- We would also like to
- Nest interrupts (have an interrupt be interrupted
and so on) - Turn off interrupts for periods of time
- Block interrupts of lower priority
28DMA
- Lots of interrupts can overburden processor
(interrupt overhead) - Many programs spend a huge portion of their time
moving data around, re-ordering it..etc. - In processors which are designed to work with
data-intensive tasks, this can be greatly
optimized by having an external device do the
memory moving for you. - DMA process allows external or internal devices
to place their data directly into processor
memory without interrupting the processor. - This can turn out to be VERY important when
pushing your processor.
29Uses for DMA
Processor can start a block memory transfer, and
then do something else while its waiting for a
whole buffer to appear
DMA_start_buffer_transfer (A_BUFFER) Process(B_Bu
ffer) While (!DMA_done) DMA_start_buffer_transfe
r (B_BUFFER) Process(A_Buffer) //etc.
DMA Controller can be transferring memory, and
Interrupt the CPU when complete.
Interrupt dma0_isr() // dma controller just
told us that buffer is complete start_new_DMA_tra
nsfer() process_full_databuffer()
30DMA on DSPs (continued)
- Serial Ports and DMA on processor work closely
together - Serial port can be configured to transfer whole
blocks of memory instead of just 1 word. - Buffer size is defined and serial port goes to
work with DMA controller to place many received
words in processor memory - Processor is signaled with DMA interrupt when
buffer is full
31DMA chaining
- As an added benefit, the DMA channels on most
DSPs can be setup for DMA chaining - This means that upon completion of a buffer
transfer, the DMA controller autoinitializes
another DMA transfer. - This is very useful for serial port situations in
which there is a regular flow of data. You set
the DMA controller up once, and it just
periodically tells you when youve got a new
buffer full of data to process.
32Data reordering with DMA
- Interleaving
- De-Interleaving
- Bit Reversal
- Complex pattern decoding
In short, if your processor has DMA, investigate
using it for any type of data moving even if you
think it might be too complex. Frequently the
DMA controller can handle it. What you get is
memory moving essentially for free.