0% found this document useful (0 votes)
20 views

LPC&RTOS - Converted3

The document discusses the LPC2378 microcontroller block diagram and programming of its general purpose input/output ports and analog-to-digital converter. It describes the GPIO ports, their configuration registers, and how to interface an LCD display.

Uploaded by

Charan Eswar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

LPC&RTOS - Converted3

The document discusses the LPC2378 microcontroller block diagram and programming of its general purpose input/output ports and analog-to-digital converter. It describes the GPIO ports, their configuration registers, and how to interface an LCD display.

Uploaded by

Charan Eswar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

BITS Pilani

Pilani Campus

Embedded System Design


ESZG512 / MELZG526 / SEZG516
BITS Pilani
Pilani Campus
Prof. Manoj S Kakade
Dept of EEE
Embedded System Design
Contact Session 7

Contents LPC2378 Block Diagram

 LPC2378 Block Diagram


 LPC23XX General Purpose Input/Output ports and programming
 LPC2378 Block Diagram
 LPC23XX Analog-to-Digital Converter (ADC) and
programming
 LCD interfacing

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

LPC2378 Block Diagram


LPC23XX General Purpose Input / Output ports
Features:
 Digital I/O ports
 GPIO PORT 0 and PORT 1 are ports accessible via either the
group of registers providing enhanced features and accelerated
port access or the legacy group of registers.
 PORT 2 / 3 / 4 are accessed as fast ports only.
 Accelerated GPIO functions:
 GPIO registers are relocated to the ARM local bus so that the fastest
possible I/O timing can be achieved.
 Mask registers allow treating sets of port bits as a group, leaving other bits
unchanged.
 All GPIO registers are byte and half-word addressable.
 The entire port value can be written in one instruction.
Source: LPC23XX User manual
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

LPC23XX General Purpose Input / Output ports LPC23XX General Purpose Input / Output ports
 Bit-level set and clear registers allow a single instruction set or clear of any  Each enabled interrupt contributes to a Wakeup signal that can be used to bring
number of bits in one port. the part out of Power-down mode.
 Direction control of individual bits.  Registers provide software a view of pending rising edge interrupts, pending
 All I/O default to inputs after reset. falling edge interrupts, and overall pending GPIO interrupts.
 Backward compatibility with other earlier devices is maintained with legacy  GPIO0 and GPIO2 interrupts share the same VIC slot with the External
registers appearing at the original addresses on the APB bus. Interrupt 3 event.
 Interrupt generating digital ports  Applications
 PORT0 and PORT2 provide an interrupt for each port pin.  General purpose I/O.
 Each interrupt can be programmed to generate an interrupt on a rising edge, a  Driving LEDs, or other indicators.
falling edge, or both.  Controlling off-chip devices.
 Edge detection is asynchronous, so it may operate when clocks are not  Sensing digital inputs, detecting edges.
present, such as during Power-down mode.  Bringing the part out of Power Down mode.
 With this feature, level-triggered interrupts are not needed.

Source: LPC23XX User manual Source: LPC23XX User manual


BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
Total pins -112 Port 0 & 1 How do they function ?
Use as GPIO/ Fast I/O - SCS Reg Bit 0 – GPIOM
 Port 2
Pin Select Registers
 Pin 14-31 NA
Every pin has alternate functions
 Port 3
00 – GPIO
 Pin 8-22 NA
P0.0
 Pin 27-31 NA
RD
 Port 4
TXD3 PIN0.0
 Pin 16-23 NA
 Pin 26-27 NA SDA

Pin Mode Registers – Select Pull-up / Pull down

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

How to use GPIO? How to use FGPIO?


Regs – Legacy – Only for Port 0/1: IOxPIN, IOxSET, IOxCLR, IOxDIR FIOxPIN
FIOxPIN0-3
FIOxPINL / FIOxPINU
FIOxSET
FIOxSET0-3
FIOxSETL / FIOxSETU
FIOxCLR
FIOxCLR0-3
FIOxCLR / FIOxCLRU
FIOxDIR
FIOxDIR0-3
FIOxDIRL / FIOxDIRU
FIOxMASK
FIOxMASK0-3
FIOxMASKL / FIOxMASKU

Source: LPC23XX User manual


BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

How to use FGPIO?


Example 1:
sequential accesses to IOSET and IOCLR affecting the
same GPIO pin/bit
In the example code:
IO0DIR = 0x0000 0080 ;pin P0.7 configured as output
IO0CLR = 0x0000 0080 ;P0.7 goes LOW
IO0SET = 0x0000 0080 ;P0.7 goes HIGH
IO0CLR = 0x0000 0080 ;P0.7 goes LOW
pin P0.7 is configured as an output (write to IO0DIR register).
After this, P0.7 output is set to low (first write to IO0CLR register).
Short high pulse follows on P0.7 (write access to IO0SET), and
the final write to IO0CLR register sets pin P0.7 back to low level.

Source: LPC23XX User manual Source: LPC23XX User manual


BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

LPC2378 Block Diagram LPC2378 Block Diagram

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus


LPC23XX Analog-to-Digital Converter (ADC) LPC23XX Analog-to-Digital Converter (ADC)
Features:
 10 bit successive approximation analog to digital converter.
 Input multiplexing among 6 pins or 8 pins.
 Power down mode.
 Measurement range 0 to 3 V.
 10 bit conversion time ≥ 2.44 μs.
 Burst conversion mode for single or multiple inputs.
 Optional conversion on transition on input pin or Timer Match
signal.
 Individual result registers for each A/D channel to reduce interrupt
Basic clocking for the A/D converters is provided by the APB peripheral clock PCLK_ADC. A
overhead. programmable divider is included in each converter to scale this clock to the 4.5 MHz (max)
clock needed by the successive approximation process. A fully accurate conversion requires 11
Source: LPC23XX User manual
of Source:
these LPC23XX
clocks.User manual
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Basic configuration Programming for ADC: Step.1.


The ADC is configured using the following registers: Enable ADC by setting bit 12 in PCONP register
1. Power: In the PCONP register, set bits PCADC.
Remark: On reset, the ADC is disabled. To enable the ADC, first
set the PCADC bit, and then enable the ADC in the AD0CR
register (bit PDN) Table 27–520. To disable the ADC, first clear the
PDN bit, and then clear the PCADC bit.
2. Clock: In the PCLK_SEL0 register, select PCLK_ADC. To scale
the clock for the ADC, see Table 27–520 bits CLKDIV.
3. Pins: Select ADC pins and pin modes in registers PINSELn and
PINMODEn.
4. Interrupts: To enable interrupts in the ADC, see Table 27–523.
Interrupts are enabled in the VIC using the VICIntEnable register.

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Programming for ADC: Step.2. Programming for ADC: Step.3.


Configure the PINSEL registers to choose the ADC inputs Configure the clock in PCLKSEL0 register

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Programming for ADC: Step.4. Programming for ADC: Step.5.


Configure the Interrupt Enable Register Configure A/D control register
Select AD0.1 channel, clock for A/D is 4 MHz, burst mode, 10 bits,
A/D converter is operational

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus


Programming for ADC: Step.6.
In the ISR, when an interrupt is received, check the ADC status
register.

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Interfacing of LPC 2XXX with


Programming for ADC: Step.7. 16x2 LCD
 After finding which channel(s) completed conversion, read the 16x2 LCD
ADC data register. Each channel has a separate data register. D0 D7 RS EN R/W

P0.12

P0.19

P1.20

P1.21

LPC 2XXX

Fig.- Interfacing of LPC-2XXX with 16x2 LCD


Source: LPC23XX User manual
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Interfacing of LPC 2XXX with Interfacing of LPC 2XXX with


16x2 LCD 16x2 LCD
How to set a Register How to set a Register 0=Input
0=Input
1=Output 1=Output
3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1
3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 9 8 7 6 5 4 3 2 1 0
9 8 7 6 5 4 3 2 1 0 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

0 0 0 F F 0 0 0 0 0 3 0 0 0 0 0
Data Pins P0.12 to Port
Port P0.19 as a P1.20
Output Pin to LCD and
D0-D7 P1.21 as
RS and
EN and
as a O/P
pin
IODIR0= 0x000FF000
Source: LPC23XX User manual IODIR1= 0x00300000
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Interfacing of LPC 2XXX with Interfacing of LPC 2XXX with


16x2 LCD 16x2 LCD
Pin Number Symbol Pin Function  Data Bus: As shown in the above figure and table, an alpha numeric lcd has a 8-
1 VSS Ground bit data bus referenced as D0-D7. As it is a 8-bit data bus, we can send the
2 VCC +5v data/cmd to LCD in bytes. It also provides the provision to send the the data/cmd
3 VEE Contrast adjustment (VO) in chunks of 4-bit, which is used when there are limited number of GPIO lines on
4 RS Register Select. 0:Command, 1: Data the microcontroller.
5 R/W Read/Write, R/W=0: Write & R/W=1: Read
6 EN Enable. Falling edge triggered  Register Select(RS): The LCD has two register namely a Data register and
7 D0 Data Bit 0 (Not used in 4-bit operation) Command register. Any data that needs to be displayed on the LCD has to be
8 D1 Data Bit 1 (Not used in 4-bit operation) written to the data register of LCD. Command can be issued to LCD by writing it
9 D2 Data Bit 2 (Not used in 4-bit operation) to Command register of LCD. This signal is used to differentiate the data/cmd
10 D3 Data Bit 3 (Not used in 4-bit operation)
received by the LCD.
11 D4 Data Bit 4
 If the RS signal is LOW then the LCD interprets the 8-bit info as Command and
12 D5 Data Bit 5
13 D6 Data Bit 6
writes it Command register and performs the action as per the command.
14 D7 Data Bit 7/Busy Flag If the RS signal is HIGH then the LCD interprets the 8-bit info as data and
15 A/LED+ Back-light Anode(+) copies it to data register. After that the LCD decodes the data for generating the
16 K/LED- Back-Light Cathode(-) 5x7 pattern and finally displays on the LCD.

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus


Interfacing of LPC 2XXX with Interfacing of LPC 2XXX with
16x2 LCD 16x2 LCD
 Read/Write(RW): This signal is used to write the data/cmd to LCD Interfacing:
LCD and reads the busy flag of LCD. For write operation the RW
should be LOW and for read operation the R/W should be HIGH.
The RS pin is used to select one of these registers.
 Enable(EN): This pin is used to send the enable trigger to LCD.  RS (Register Select): If ‘1’, data register is selected.
After sending the data/cmd, Selecting the data/cmd register, If ‘0’, command register is selected.
Selecting the Write operation. A HIGH-to-LOW pulse has to be
send on this enable pin which will latch the info into the LCD
register and triggers the LCD to act accordingly. The R/w input allows the user to read or write information to LCD.
 R/W (Read/write): while reading ,R/W=’1’.
while writing, R/W=’0’.

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Interfacing of LPC 2XXX with Interfacing of LPC 2XXX with


16x2 LCD 16x2 LCD
Hex Value Functions
LCD Interfacing: 1 Clear the display LCD Commands
2 Return home
4 Decrement cursor(shift cursor to left)
 The (E) Enable pin is used by the LCD to latch the information presented to its 6 Increment cursor(shift cursor to right)
5 Shift display right
data pins. 7 Shift display left
8 Display off, Cursor off
0A Display off, Cursor on
 A high to low pulse should be applied to this pin in order for the LCD to latch 0C Display on, Cursor off
0E Display on, Cursor blinking
in the data presented at data pins.
10 Shift cursor position to left
14 Shift cursor position to right
18 Shift entire display to left
 The 8-bit data pins, D0-D7, are used to send information to LCD or read the 1C Shift entire display to right
contents of the LCD’s internal registers. 80 Force cursor to beginning of 1st line
C0 Force cursor to beginning of 2nd line
38 2 lines and 5X7 matrix
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Interfacing of LPC 2XXX with Interfacing of LPC 2XXX with


16x2 LCD 16x2 LCD LCD Interfacing Details

Description Signal

LCD LPC2xxx
LCD D0 P0.12
LCD D1 P0.13
LCD D2 P0.14
LCD D3 P0.15
LCD D4 P0.16
LCD D5 P0.17
LCD D6 P0.18
LCD D7 P0.19
LCD RS P1.20
LCD EN P1.21

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Interfacing of LPC 2XXX with Interfacing of LPC 2XXX with


16x2 LCD 16x2 LCD
IODIR0=0x000FF000; //Port 0.0 from pin 12-19 Command Mode:
IOCLR0=0X000FF000;
IODIR1=0x00300000; // port 1 pin 20=rs,21=en
RS=0; IOCLR1=0X00100000;
Command Data Mode cmddata=cmddata<<12;

IOSET0=cmddata;
• RS=0 • RS=1
Send Command
• Command • Data
EN=High (1) IOSET1=0x00200000;
• En=1 • En=1
• DELAY • DELAY DELAY

• En=0 • En=0 EN=Low(0)

IOCLR1=0x00200000;
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
Interfacing of LPC 2XXX with
16x2 LCD
Data Mode:
IOCLR0=0X000FF000;

RS=1; IOSET1=0X00100000;

outdata=outdata<<12;
Thank you
IOSET0=outdata;

Send Data

EN=High (1) IOSET1=0x00200000;

DELAY

EN=Low(0) IOCLR1=0x00200000;

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

BITS Pilani
Pilani Campus

Embedded System Design


ESZG512/MELZG526/SEZG516
BITS Pilani
Pilani Campus
Prof. Manoj S Kakade
Dept of EEE
Embedded System Design
Contact Session 10

Contents Introduction to LPC 23xx: Timer


 LPC23xx Timer and its programming  Features
 Four Timer/Counters
 LPC23xx Interrupt
 4 channels/Timer
 LPC23xx Timer with interrupt programming
 A minimum of 2 capture i/ps & 2 Match o/ps are pinned out for all
4 timers
 Choice of several pins for each Timer
 32 bit Timer/Counter with programmable 32 bit Prescaler
 Counter / Timer operation

Source: LPC23XX User manual


BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Introduction to LPC 23xx: Timer Introduction to LPC 23xx: Timer


 TIMER/COUNTER 0-3 registers  PC Prescale Counter: The 32 bit PC is a counter which is
 IR Interrupt Register: The IR can be written to clear interrupts. The incremented to the value stored in PR. When the value in PR is
IR can be read to identify which of eight possible interrupt sources reached, the TC is incremented and the PC is cleared. The PC is
are pending observable and controllable through the bus interface
 TCR Timer Control Register: The TCR is used to control the Timer  MCR Match Control Register: The MCR is used to control if an
Counter functions. The Timer Counter can be disabled or reset interrupt is generated and if the TC is reset when a Match occurs
through the TCR  MR0/1/2/3 Match Register 0/1/2/3: MR0/1/2/3 can be enabled
 TC Timer Counter: The 32 bit TC is incremented every PR+1 cycles through the MCR to reset the TC, stop both the TC and PC, and/or
of PCLK. The TC is controlled through the TCR generate an interrupt every time MR0/1/2/3 matches the TC
 PR Prescale Register: The Prescale Counter is equal to this value,
the next clock increments the TC and clears the PC

Source: LPC23XX User manual Source: LPC23XX User manual


BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
Introduction to LPC 23xx: Timer Introduction to LPC 23xx: Timer
 CCR Capture Control Register: The CCR controls which edges of • EMR External Match Register: The EMR controls the external
the capture inputs are used to load the Capture Registers and match pins MATn.0-3 (n corresponds to timers 0 to 3)
whether or not an interrupt is generated when a capture takes place. • CTCR Count Control Register: The CTCR selects between Timer
 CR0 Capture Register 0: CR0 is loaded with the value of TC when and Counter mode, and in Counter mode selects the signal and
there is an event on the CAPn.0 (CAP0.0, CAP1.0, CAP2.0, or edge(s) for counting
CAP3.0) input
 CR1 Capture Register 1: CR1 is loaded with the value of TC when
there is an event on the CAPn.0 (CAP1.0, CAP1.1, CAP2.1, or
CAP3.1) input

Source: LPC23XX User manual Source: LPC23XX User manual


BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Introduction to LPC 23xx: Timer Introduction to LPC 23xx: Timer


 Figure shows a timer configured to stop and generate an interrupt on
match.
 The prescaler is again set to 2 and the match register set to 6.
 In the next clock after the timer reaches the match value, the timer
enable bit in TCR is cleared, and the interrupt indicating that a match
occurred is generated.

Functional Block Diagram Source: LPC23XX User manual


BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Programming of Timer Programming of Timer


 CALCULATION OF TIME DELAY:
STEPS TO PROGRAM TIMERS:
 Peripheral Frequency = CPU Clock / APB divider
 Since we are using Default 1/4 divider here our peripheral frequency will be
 Reset timer0 initially to deactivate counting.
 Peripheral Frequency = 48 MHz / 4 = 12 MHz  Load calculated values in the Prescaler register T0PR and Match
 Then we have to calculate T0MR0 (count) value to generate required delay by register T0MR0.
matching  Initialize T0PC and T0TC registers.
 Count = (Peripheral Frequency / Desired Frequency) – 1  Select operations using match registers when match is encountered.
= (12,000,000 / 10) – 1  Start the Timer by enabling it through T0TCR register.
= (12,000,000 – 1)
 Wait till the interrupt and then clear the flag by writing T0IR
= 11,99,999
register.
 Now count 1199999 gives the T0MR0 value to generate 100ms delay. So to
make it as 1 sec we have to multiply it with 10. And that we can use it in the
Prescale register T0PR, thus we can generate a delay of 1 sec using this.

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Programming of Timer Programming of Timer


#include<lpc23xx.h>
#define LED_D0 1<<15
void delay(void)
#define LED_D1 1<<16 {
#define LED_D2 1<<17
#define LED_D3 1<<18 T0TCR=(1<<1); //Reset Timer0
#define LED_D4 1<<19
#define LED_D5 1<<20
T0MR0=1199999; //Loading match register value
#define LED_D6 1<<21 T0PR=9; //Loading Prescalar register value
#define LED_D7 1<<22
void delay(void); T0PC=T0TC=0;
int main (void)
{
T0MCR=(1<<0)|(1<<2); //Generates interrupt and stop on match
IODIR0 = LED_D0|LED_D1|LED_D2|LED_D3|LED_D4|LED_D5|LED_D6|LED_D7; /* Define Output pins */ T0TCR=(1<<0); //Starting Timer
while (1) /* Loop forever */ while(!(T0IR&(1<<0))); //Waiting for interrupt
{
/* bit pattern for LEDs connected at GPIO Port 0*/
T0IR=(1<<0); //Clearing interrupt: Writing a logic one to the
IOSET0=LED_D0|LED_D1|LED_D2|LED_D3|LED_D4|LED_D5|LED_D6|LED_D7; /* turn LEDs ON */ //corresponding IR bit will reset the interrupt.
delay(); /* Delay */ }
IOCLR0=LED_D0|LED_D1|LED_D2|LED_D3|LED_D4|LED_D5|LED_D6|LED_D7; /* turn LEDs OFF */
delay(); /* Delay */
}
}
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
Interrupts Interrupts
 Interrupt : “An interrupt is a signal sent to the CPU which indicates Interrupts are handled by Vectored Interrupt Controller(VIC)
that a system event has a occurred which needs immediate
attention”.
 Interrupt ReQuest (IRQ) can be thought of as a special request to
the CPU to execute a function(small piece of code) when an
interrupt occurs.
 ISR : This function or ‘small piece of code’ is technically called an
‘Interrupt Service Routine‘ or ‘ISR’.
 So when an IRQ arrives to the CPU, it stops executing the current
code and start executing the ISR. After the ISR execution has
finished the CPU gets back to where it had stopped.

Source: LPC23XX User manual


BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Interrupts Interrupts
LPC23XX Vectored Interrupt Controller (VIC): Interrupt structure of LPC23xx
Features  The VIC is a component from the ARM prime cell.
 ARM PrimeCell Vectored Interrupt Controller  VIC module is a highly optimized interrupt controller.
 Mapped to AHB address space for fast access  The VIC is used to handle all the on-chip interrupt sources from
 Supports 32 vectored IRQ interrupts peripherals.
 16 programmable interrupt priority levels  Each of the on-chip interrupt sources is connected to the VIC on
 Fixed hardware priority within each programmable priority level a fixed channel: your application software can connect each of
these channels to the CPU interrupt lines (FIQ, IRQ) in one of
 Hardware priority level masking
three ways.
 Any input can be assigned as an FIQ interrupt
 Software interrupt generation

Source: LPC23XX User manual


BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Interrupts Interrupts
 The VIC allows each interrupt to be handled as an FIQ interrupt,  The ARM processor core has two interrupt inputs called Interrupt
a vectored IRQ interrupt Request (IRQ) and Fast Interrupt reQuest (FIQ).
 FIQ is the fastest followed by vectored IRQ with non-vectored  VIC takes 32 interrupt request inputs and programmably assigns
IRQ being the slowest. them as FIQ or vectored IRQ types.
 Fast Interrupt reQuest (FIQ) requests have the highest priority.
 If more than one request is assigned to FIQ, the VIC ORs the
requests to produce the FIQ signal to the ARM processor.
 Vectored IRQ’s, which include all interrupt requests that are not
classified as FIQs, have a programmable interrupt priority.
 The VIC ORs the requests from all of the vectored IRQs to
produce the IRQ signal to the ARM processor.

Source: LPC23XX User manual


BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Interrupts Interrupts
Block diagram of the Vectored Interrupt Controller VIC register map
 VICIRQStatus - IRQ Status Register: This register reads out the
state of those interrupt requests that are enabled and classified as
IRQ.
 VICFIQStatus - FIQ Status Requests: This register reads out the
state of those interrupt requests that are enabled and classified as
FIQ.
 VICRawIntr - Raw Interrupt Status Register: This register reads
out the state of the 32 interrupt requests / software interrupts,
regardless of enabling or classification.
 VICIntSelect - Interrupt Select Register: This register classifies
each of the 32 interrupt requests as contributing to FIQ or IRQ.

Source: LPC23XX User manual Source: LPC23XX User manual


BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
Interrupts Interrupts
 VICIntEnable - Interrupt Enable Register: This register controls  VICProtection - Protection enable register: This register allows limiting
which of the 32 interrupt requests and software interrupts are access to the VIC registers by software running in privileged mode.
enabled to contribute to FIQ or IRQ.  VICSWPriorityMask - Software Priority Mask Register: Allows masking
 VICIntEnClr - Interrupt Enable Clear Register: This register individual interrupt priority levels in any combination.
allows software to clear one or more bits in the Interrupt Enable  VICVectAddr0-31 - Vector address 0-31 register: Vector Address
register Registers 0-31 hold the addresses of the Interrupt Service routines (ISRs)
 VICSoftInt - Software Interrupt Register: The contents of this for the 32 vectored IRQ slots.
register are ORed with the 32 interrupt requests from various  VICVectPriority0-31 - Vector priority 0-31 register: Vector Priority
peripheral functions. Registers 0-31. Each of these registers designates the priority of the
 VICSoftIntClear - Software Interrupt Clear Register: This corresponding vectored IRQ slot
register allows software to clear one or more bits in the Software  VICAddress - Vector address register: When an IRQ interrupt occurs, the
Interrupt register Vector Address Register holds the address of the currently active interrupt

Source: LPC23XX User manual Source: LPC23XX User manual


BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Interrupts Interrupts
FIQ Interrupt  Once you have selected an FIQ source the interrupt can be
 Any interrupt source may be assigned as the FIQ interrupt. enabled in the VIC Interrupt Enable Register.
 The VIC Interrupt Select Register has a unique bit for each  Configuring the VIC, the peripheral generating the interrupt must
interrupt. be configured and its own interrupt registers enabled.
 Setting this bit connects the selected channel to the FIQ interrupt.  Once an FIQ interrupt is generated, the processor will change to
 In an ideal system we would only have one FIQ interrupt. FIQ Mode and vector to FIQ vector.
 However setting multiple bits in the Interrupt Select Register will  Place a jump to your ISR routine at this location in order to serve
enable multiple FIQ interrupt sources. the interrupt.
 On entry the interrupt source can be determined by examining
the VIC FIQ Status Register and the appropriate code executed.
 Several FIQ sources slows entry into the ISR code.

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Interrupts Interrupts
Leaving an FIQ Interrupt Vectored IRQ
 Before you exit the ISR code you must make sure that any  The VIC provides a programmable hardware lookup table which
delivers the address of the C function to run for a given interrupt
interrupt status flags in the peripheral have been cleared. source.
 If this is not done you will get continuous interrupts until the flag  The VIC contains 32 slots for vectored addressing.
is cleared.  Each slot contains a Vector Address Register and a Vector Priority
 To clear the flag: write a logic 1 not a logic 0. Register.
 The Vector Priority Register allows you to assign a priority to each
interrupt slot.
 It supports 16 priority levels, 15 being the lowest priority and 0 the
highest.
 After reset the priority of all the VIC slots is set to 15, and the
individual priority can be elevated by the user.

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Interrupts Interrupts
 Vector Address Register must be initialised with the address of Leaving An IRQ Interrupt
the appropriate C function to run when the interrupt associated  Interrupt status flags are cleared in the peripheral which
with the slot occurs. generated the request.
 So whenever an interrupt configured as a vectored interrupt is  At the end of the interrupt you must do a dummy write to the
generated, the address of its ISR will be loaded into a fixed Vector Address Register.
memory location called the Vector Address Register.  This signals the end of the interrupt to the VIC, and any pending
 The ARM7 CPU is going through its normal entry into the IRQ IRQ interrupt will be asserted.
Mode and will jump to IRQ interrupt vector.

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus


Timer 0 interrupt programming

Steps:
1. Convert Timer0 interrupt to an IRQ interrupt
2. Set Vectored IRQ slot 4 to highest priority
3. Pass address of the IRQ into the VIC Slot
4. Enable Timer0 as IRQ interrupt Thank you
5. In IRQ interrupt handler:
1. Clear interrupt flag
2. VICAddress register must be written (with any value) at
the end of an ISR

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

BITS Pilani
Pilani Campus

Embedded System Design


ESZG512/MELZG526/SEZG516
BITS Pilani
Pilani Campus
Prof. Manoj S Kakade
Dept of EEE
Embedded System Design
Contact Session 14

CS14 : (I2C_SPI_interfacing) I2C


 Communication protocols required for communication between
 I2C Protocol different hardware components of an Embedded system
 EEPROM Interfacing through I2C  The Inter-Integrated Circuit (aka I²C - pronounced I-squared-C or
 SPI Protocol very rarely I-two-C) is a hardware specification and protocol
developed by the semiconductor division of Philips (now NXP
Semiconductors) back in 1982.
 It is a master-slave, half-duplex, single-ended 8-bit oriented serial
bus specification, which uses only two wires to interconnect a given
number of slave devices to a master.

3 BITS pilani, Deemed to be University under Section 3, UGC Act 4 BITS pilani, Deemed to be University under Section 3, UGC Act

I2C I2C
 The two wires forming an I²C bus are bidirectional open-drain  I2C bus signals are SDA (Serial Data) and SCL (Serial Clock) .
lines, named Serial Data Line (SDA) and Serial Clock Line (SCL) Both the signals are bidirectional in nature.
respectively.  The bus is also a ‘WIRED AND’ bus, which implies that if any of
 The I²C protocol specifies that these two lines need to be pulled up the device transmits a ‘0’ , ‘0’ will appear on the bus.
with resistors.
 Being a protocol based on just two wires, there should be a way to
address an individual slave device on the same bus.
 For this reason, I²C defines that each slave device provides a
unique slave address for the given bus.
 The address may be 7- or 10-bit wide
 The protocol is also byte oriented protocol as a transmitting
device expects to receive an acknowledgement from receiving
device after every byte of data transfer.
5 BITS pilani, Deemed to be University under Section 3, UGC Act 6 BITS pilani, Deemed to be University under Section 3, UGC Act
I2C I2C
The I²C Protocol
 In the I²C protocol all transactions are always initiated and
completed by the master.
 This is one of the few rules of this communication protocol to keep
in mind while programming I²C devices.
 All messages exchanged over the I²C bus are broken up into two
types of frame: an address frame, where the master indicates to
which slave the message is being sent, and one or more data
frames, which are 8-bit data messages passed from master to slave
or vice versa.
 Data is placed on the SDA line after SCL goes low, and it is
sampled after the SCL line goes high.

7 BITS pilani, Deemed to be University under Section 3, UGC Act 8 BITS pilani, Deemed to be University under Section 3, UGC Act

I2C I2C
 The time between clock edges and data read/write is defined by
devices on the bus and it vary from chip to chip.
 Both SDA and SCL are bidirectional lines, connected to a positive
supply voltage via a current-source or pull-up resistors.
 When the bus is free, both lines are HIGH.
 The output stages of devices connected to the bus must have an START and STOP Condition
open-drain or open-collector to perform the wired-AND function.
 All transactions begin with a START and are terminated by a
 The bus capacitance limits the number of interfaces connected to the STOP.
bus.
 A HIGH to LOW transition on the SDA line while SCL is HIGH
 For a single master application, the master’s SCL output can be a defines a START condition.
push-pull driver design if there are no devices on the bus that would
stretch the clock.  A LOW to HIGH transition on the SDA line while SCL is HIGH
defines a STOP condition.
9 BITS pilani, Deemed to be University under Section 3, UGC Act 10 BITS pilani, Deemed to be University under Section 3, UGC Act

I2C I2C
 START and STOP conditions are always generated by the master. Byte Format
 The bus is considered to be busy after the START condition.  Every word transmitted on the SDA line must be eight bits long, and
 The bus is considered to be free again a certain time after the STOP this also includes the address frame.
condition.  The number of bytes that can be transmitted per transfer is
 The bus stays busy if a repeated START (also called RESTART unrestricted.
condition) is generated instead of a STOP condition.  Each byte must be followed by an Acknowledge (ACK) bit.
 In this case, the START and RESTART conditions are functionally  Data is transferred with the Most Significant Bit (MSB) first.
identical.  If a slave cannot receive or transmit another complete byte of data
until it has performed some other function, for example servicing an
internal interrupt, it can hold the clock line SCL LOW to force the
master into a wait state.
 Data transfer continues when the slave is ready for another byte of
data and releases clock line SCL.
11 BITS pilani, Deemed to be University under Section 3, UGC Act 12 BITS pilani, Deemed to be University under Section 3, UGC Act

I2C I2C
Address Frame The ACK signal is defined as follows:
 The address frame is always first in any new communication  The transmitter releases the SDA line during the acknowledge
sequence. clock pulse so that the receiver can pull the SDA line LOW and it
 For a 7-bit address, the address is clocked out most significant bit remains stable LOW during the HIGH period of this clock pulse.
(MSB) first, followed by a R/W bit indicating whether this is a read  When SDA remains HIGH during this ninth clock pulse, this is
(1) or write (0) operation. defined as the Not Acknowledge (NACK) signal.
 The addressed slave should respond with an ACK bit.  The master can then generate either a STOP condition to abort the
Acknowledge (ACK) and Not Acknowledge (NACK) transfer, or a RESTART condition to start a new transfer.
 The ACK takes place after every byte. The ACK bit allows the There are five conditions leading to the generation of a NACK:
receiver to signal the transmitter that the byte was successfully 1. No receiver is present on the bus with the transmitted address so
received and another byte may be sent. there is no device to respond with an acknowledge.
 The master generates all clock pulses over the SCL line, including
the ACK ninth clock pulse.
13 BITS pilani, Deemed to be University under Section 3, UGC Act 14 BITS pilani, Deemed to be University under Section 3, UGC Act
I2C I2C
2. The receiver is unable to receive or transmit because it is Data Frames
performing some real-time function and is not ready to start  After the address frame has been sent, data can begin being
communication with the master. transmitted.
3. During the transfer, the receiver gets data or commands that it  The master will simply continue generating clock pulses on SCL at
does not understand. a regular interval, and the data will be placed on SDA by either the
4. During the transfer, the receiver cannot receive any more data master or the slave, depending on whether the R/W bit indicated a
bytes. read or write operation.
5. A master-receiver must signal the end of the transfer to the slave  Usually, the first or the first two bytes contains the address of the
transmitter. slave register to write to/read from.
 For example, for I²C EEPROMs the first two bytes following the
address frame represent the address of the memory location
involved in the transaction.

15 BITS pilani, Deemed to be University under Section 3, UGC Act 16 BITS pilani, Deemed to be University under Section 3, UGC Act

I2C I2C Arbitration


 Depending on the R/W bit, the successive bytes are filled by the  If multiple masters find the bus idle at the same time, they might
master (if the R/W bit is set to 1) or the slave (if R/W bit is 0). attempt to start the transfer by sending start sequence
 The number of data frames is arbitrary, and most slave devices will simultaneously.
auto-increment the internal register, meaning that subsequent reads  Ultimately, only one of the device can succeed in transmitting data .
or writes will come from the next register in line.  This is achieved via an arbitration process. Since the bus is WIRED
 This mode is also called sequential or burst mode and it is a way to AND,the device which transmits a ‘0’ on bus first, will win the bus
speed up transfer speed. mastership.
 The address & R/W are included in the arbitration process.
 Each master device can read back what it has transmitted on bus.
 If the data available on the bus is matching with what it has
transmitted, then the master continues transfer, else the master backs
off.
17 BITS pilani, Deemed to be University under Section 3, UGC Act 18 BITS pilani, Deemed to be University under Section 3, UGC Act

I2C Arbitration : Scenario 1 I2C Arbitration : Scenario 2


 Master 1 attempts to transmit data to Slave A with address 0x32  Master 1 attempts to read data from Slave B (address 0x27)
 Master 2 attempts to transmit data to Slave B with address 0x27  Master 2 attempts to write data to Slave B( address 0x27)
 Both masters transmits start sequence followed by address bits as  Both masters transmits start sequence followed by address bits and
follows. R/W bit as follows.
 Slave A address 0x32- 0110010  Slave A address 0x27-0100111, R/W=1
 Slave B address 0x27- 0100111  Slave B address 0x27-0100111, R/W=0 (Win arbitration)
 Master 2 wins arbitration after transmission of 3rd bit (Transmission  Master 1 backs off after transmission of R/W, Master 2 continues
is MSB first), Master 1 backs off, with data transfer.
 Master 2 continues with address R/W and the data transfer

19 BITS pilani, Deemed to be University under Section 3, UGC Act 20 BITS pilani, Deemed to be University under Section 3, UGC Act

I2C Speed Modes


 I2C devices support various speed Modes.  Many times single-master multiple-slave configurations may be
sufficient.
 Compliant hardware guarantees that it can handle transmission
 A master device is the one which initiates/terminates the transfer
speed up to the maximum clock rate specified by the mode.
and generates the clock signals.
 Standard mode: 100 kbit/s,  Slave is a device addressed by the master.
 Full Speed :400 kbit/s,  Both master as well as slave can receive and transmit data.
 Fast Mode: 1 Mbit/s,
 High Speed : 3.2 Mbit/s  There are many devices with built-in I2C bus: for example,
EEPROM, RAM, LCD display drivers, ADC, DAC, etc.
 Ultra Fast-mode : 5 Mbits/s

21 BITS pilani, Deemed to be University under Section 3, UGC Act BITS pilani, Deemed to be University under Section 3, UGC Act
Device Addressing Write Protocol
 The 24C256 EEPROM requires an 8-bit device address word  To write a single or multiple bytes of data into the EEPROM, we
following a start condition to enable the chip for a read or write need to follow the protocol
operation. Refer circuit schematic for A0A1A2

BITS pilani, Deemed to be University under Section 3, UGC Act BITS pilani, Deemed to be University under Section 3, UGC Act

Read Protocol LPC21XX I2C Registers


I2C Control Set Register. When a one is written to a bit of this register, the
 To read a data byte from a particular address, we first need a I2CONSET corresponding bit in the I2C control register is set. Writing a zero has no effect on
dummy write sequence at that particular address, before we issue the corresponding bit in the I2C control register.
the read command. I2C Control Clear Register. When a one is written to a bit of this register, the
I2CONCLR corresponding bit in the I2C control register is cleared. Writing a zero has no
effect on the corresponding bit in the I2C control register.
I2C Status Register. During I2C operation, this register provides detailed status
I2CSTAT codes that allow software to determine the next action needed.
I2C Data Register. During master or slave transmit mode, data to be transmitted
I2CDAT is written to this register. During master or slave receive mode, data that has been
received may be read from this register.
SCH Duty Cycle Register High Half Word. Determines the high time of the
I2C Clock Frequency: I2SCLH I2C clock.

SCL Duty Cycle Register Low Half Word. Determines the low time of the I2C
I2SCLL clock. I2nSCLL and I2nSCLHtogether determine the clock frequency generated
by anI2C master.

BITS pilani, Deemed to be University under Section 3, UGC Act BITS pilani, Deemed to be University under Section 3, UGC Act

Circuit Schematic SPI


Introduction to the SPI Specification
 The Serial Peripheral Interface (SPI) is a specification about serial,
synchronous and full-duplex communications between a master
controller (which is usually implemented with an MCU or
something with programmable functionalities) and several slave
devices.
 The nature of the SPI interface allows full duplex as well as half
duplex communications over the same bus.
 SPI specification is a de facto standard, and it was defined by
Motorola¹ in late ‘70, and it is still largely adopted as
communication protocol for many digital ICs.

BITS pilani, Deemed to be University under Section 3, UGC Act 28 BITS pilani, Deemed to be University under Section 3, UGC Act

SPI SPI
 The structure of a typical SPI bus A typical SPI bus is formed by four signals, even if it is possible to
drive some SPI devices with just three I/Os (in this case we talk about
3-wire SPI):
• SCK: this signal I/O is used to generate the clock to synchronize
data transfer over the SPI bus.
 It is generated by the master device, and this means that in an SPI
bus every transfer is always started by the master.
 Different from the I²C specification, the SPI is intrinsically faster
and the SPI clock speed is usually several MHz.
 Nowadays is quite common to find SPI devices able to exchange
data at a rate up to 100MHz.
 SPI protocol allows to devices with different communication
speeds to coexist over the same bus.
29 BITS pilani, Deemed to be University under Section 3, UGC Act 30 BITS pilani, Deemed to be University under Section 3, UGC Act
SPI SPI
• MOSI: the name of this signal I/O stands for Master Output Slave  Different from the I²C protocol, the SPI does not use slave
Input, and it is used to send data from the master device to a slave . addresses to select devices, but it demands this operation to a
 Different from the I²C bus, where just one wire is used to exchange physical line that is asserted LOW to perform a selection.
data both the ways, the SPI protocol defines two distinct lines to  In a typical SPI bus only one slave device can be active at same
exchange data between master and slaves. time by asserting low its SS line.
• MISO: it stands for Master Input Slave Output and it corresponds  This is the reason why devices with different communication speed
to the I/O line used to send data from a slave device to the master. can coexist on the same bus.
• SSn: it stands for Slave Select and in a typical SPI bus there exist
‘n’ separated lines used to address the specific SPI devices
involved in a transaction.

31 BITS pilani, Deemed to be University under Section 3, UGC Act 32 BITS pilani, Deemed to be University under Section 3, UGC Act

SPI SPI
Clock Polarity and Phase  SPI bus modes according CPOL and CPHA configuration
 In addition to setting the bus clock frequency, the master and slaves
must also agree on the clock polarity and phase with respect to the
data exchanged over MOSI and MISO lines. Mode CPOL CPHA
 SPI Specification by Motorola names these two settings as CPOL 0 0 0
(Clock polarity ) and CPHA (clock phase) respectively, and most
silicon vendors have adopted that convention. 1 0 1
 The combinations of polarity and phase are often referred to as SPI 2 1 0
bus modes which are commonly numbered according Table. 3 1 1
 The most common mode are mode 0 and mode 3, but the majority
of slave devices support at least a couple of bus modes

33 BITS pilani, Deemed to be University under Section 3, UGC Act 34 BITS pilani, Deemed to be University under Section 3, UGC Act

SPI SPI
 The timing diagram is shown in Figure, and it is further described  At CPOL=0 the base value of the clock is zero, i.e. the active state
below: is 1 and idle state is 0.
• For CPHA=0, data is captured on the SCK rising edge (LOW →
HIGH transition) and data is output on a falling edge (HIGH →
LOW clock transition).
• For CPHA=1, data is captured on the SCK falling edge and data is
output on a rising edge.
 At CPOL=1 the base value of the clock is one (inversion of
CPOL=0), i.e. the active state is 0 and idle state is 1.
• For CPHA=0, data is captured on SCK falling edge and data is
output on a rising edge.
• For CPHA=1, data is captured on SCK rising edge and data is
output on a falling edge.
35 BITS pilani, Deemed to be University under Section 3, UGC Act 36 BITS pilani, Deemed to be University under Section 3, UGC Act

SPI SPI bus features


 That is, CPHA=0 means sampling on the first clock edge, while 1. SPI bus provides bidirectional, synchronous serial
CPHA=1 means sampling on the second clock edge, regardless of communication between uC and peripherals.
whether that clock edge is rising or falling. 2. It is based upon a master-slave protocol where master is the
 Note that with CPHA=0, the data must be stable for a half cycle device that drives the clock signal.
before the first clock cycle. 3. SPI is capable of up to 3 Mbps (megabits-per-second) data
transfer rate.
4. SPI has a hold facility that allows the transmitter to suspend data
transfer.
6. Data in SPI can be transferred as multiple bytes known as
blocks or pages.
7. The SPI clock is symmetrical (an equal low and high time).

37 BITS pilani, Deemed to be University under Section 3, UGC Act BITS pilani, Deemed to be University under Section 3, UGC Act
SPI bus features
8. Developed by Motorola and supported by various uC products. Bus Configuration and SPI Protocol of Multiple slaves
Multiple slave devices can be connected in parallel or daisy chained
9. In SPI mode, the serial 8-bit synchronous data transmission and utilizing the same SPI bus.
reception is possible simultaneously.
Parallel Configuration
10. Multiple masters and multiple slaves are allowed on the bus. For the parallel connection, each device on the bus should have a
separate CS line, while SCK, SDI and SDO lines are connected in
11. Master initiates the data frame. Master generates the clock (SCK) parallel.
and selects the slave device and then data transfer in both
directions takes place.

BITS pilani, Deemed to be University under Section 3, UGC Act BITS pilani, Deemed to be University under Section 3, UGC Act

Daisy Chain Configuration


 In this configuration CS and SCK lines connected in parallel, and
each SDO pin of previous chip is connected to SDI pin.
 Daisy Chaining simplifies the connection by reducing the length and
connections of the data lines, but restricts access to a single device in
chain.

BITS pilani, Deemed to be University under Section 3, UGC Act BITS pilani, Deemed to be University under Section 3, UGC Act

Daisy Chain Configuration


When wiring up a SPI device,
 In other words, all the devices in chain will be involved in a write or
there is one trick that you can
read operation.
do to simplify the
 We can consider that every device in the chain is a portion of one big
microcontroller connection is to
shift register, where serial data is shifted out on each clock going
combine the Dl and DO lines
through all the DCPs, from DCP0 to DCP1 and all the way down to
into one pin Fig.
the last DCP(N-1) in this chain.
In this method of connecting
the two devices, when the Data
pin on the microcontroller has
completed sending the serial
data, the output driver can be
turned off and the
microcontroller can read the
data coming from the device.
BITS pilani, Deemed to be University under Section 3, UGC Act BITS pilani, Deemed to be University under Section 3, UGC Act

 The current limiting resistor between the Data pin and DI/DO
limits any current flows when both the microcontroller and device
are driving the line.

 This trick can be used in a variety of different situations, but it must


be done so carefully. THANK YOU!!!!!
 The resistor will prevent any possible I/O pin damage due to bus
contention (two devices driving the same line to different levels at
the same time).

 However, if the resistor is not properly wired into the circuit or if


the MCU attempts to read while it is driving, then invalid data will
be stored or read.
BITS pilani, Deemed to be University under Section 3, UGC Act 46 BITS pilani, Deemed to be University under Section 3, UGC Act
BITS Pilani
Pilani|Dubai|Goa|Hyderabad

Embedded System Design


ESZG512/MELZG526/SEZG516
BITS Pilani
Pilani|Dubai|Goa|Hyderabad
Prof. Manoj S Kakade
Dept of EEE
Embedded System Design
Contact Session 15
1 2

CS15 : (Embedded Software Design) Computer Systems


 Hardware
 Assembly
 Firmware
 Compiling  Software
 Linking  Application software
 Foreground and background systems  System software
 What is an Operating System?  Programming systems
 Utilities
 Process or Task
 Operating systems
 Task States
 Threads
 Firmware's are generally a type of software used to control hardware devices.
 Software (application software) runs on top of the operating system and has no direct interface
with hardware. Firmware is low-level software that stands between the hardware and the
operating system.

3 BITS pilani, Deemed to be University under Section 3, UGC Act BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Computer Software Foundations of Computer Systems


 Application software is designed to solve a specific problem.
 System software is intended to support the operation and use of
the computer itself.
 Provide a general programming environment.
 Provide functions used by application software and users.
 Provide mechanisms to share the hardware in an orderly fashion.
 Utility software is software designed to help analyze, configure, optimize or
maintain a computer. It is used to support the computer infrastructure - in
contrast to application software, which is aimed at directly performing tasks that
benefit ordinary users. Eg : Antivirus Software, File Management Tool,
Compression Tool, Disk Management Tool, Disk Cleanup Tool etc..

5 6

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Foundations of Computer Systems Evolution of Programming


Machine Language
– Binary format
Users 11100101100111110001000000010000
11100101100111110000000000001000
Application Software 11100000100000010101000000000000
11100101100011110101000000001000
Programming System – Hexadecimal format
E59F1010
Operating System E59F0008
E0815000
Hardware E58F5008

7 8

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Evolution of Programming From Source to Executable
Source Code Object Code
Assembly Language
– Mnemonic codes
E59F1010 LDR R1, num1 Preprocessor Linker
E59F0008 LDR R0, num2 Libraries
E0815000 ADD R5, R1, R0 Preprocessed Code Executable Code
E58F5008 STR R5, sum

High-Level Language Compiler Loader


– C language
sum = num1 + num2; Assembly Code
Debugger
Assembler

9 10

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

EMBEDDED SOFTWARE DEVELOPMENT TOOLS Development Phases of an Embedded System


 Introduction
Phase 1:Analysis
 Application programs are typically developed, compiled, and run on host system
 Embedded programs are targeted to a target processor (different from the (Requirements & specifications)
development/host processor and operating environment) that drives a device or
controls Phase 2: Design
 What tools are needed to develop, test, and locate embedded software into the target ( Selection of development tools)
processor and its operatingenvironment?
Phase 3: Implementation
 Distinction Phase 4: Testing and Debugging
 Host: Where the embedded software is developed, compiled, tested, debugged,
optimized, and prior to its translation into target device. (Because the host has
keyboards, editors, monitors, printers, more memory, etc. for development, while the
target may have not of these capabilities for developing the software.)
 Target: After development, the code is cross-compiled, translated – cross- assembled,
linked (into target processor instruction set) and located into the target 11 12

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Software Development Cycle Integrated DevelopmentEnvironment (IDE)

Project creation – Target device  An IDE gives a single focal point for the application
select & configure the toolsettings
development for
1. Creating source file through a project manager.
Source file creation usingassembler, C, 2. Rich featured source code.
RTOSenvironment & application build
up using projectmanager 3. Organization of source file into a project.
Object code 4. Provision of database for many devices.
5. a)Compiles, points errors and interactively correct the errors.
Error Correction b)Assembles and links to application.
c)Links a device data sheets, user guides & development tool
Object files
manuals.
Testing after linking

Absolute File
O.K. 13 14
ToPROM
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Integrated DevelopmentEnvironment (IDE) Integrated DevelopmentEnvironment (IDE)


 Assembler  Linker
 It optimally exploits the chosen microcontroller chips special features. Its instructions  Linker creates an absolute object module file from other library
gives direct control of stack, I/O and registers etc. modules.
 Compiler
 Object to Hex file converter gives hex file for the use of device
 Creates a object code file programmer.
 e.g. C51 compiler from Keil
 Debugger
 Dissembler
 Provides many functionalities like start-stop debugging, single-
 It translates the object codes into the mnemonics form of assembly language
step tracing etc.
 Library and Library Manager
 Simulator
 An ordered & specially formatted program collection of object codes so that a linker
can use it.  It simulates hardware performance for software to be embedded
 Cross assembler and Cross Compiler
in that without actually employing a specific device. It simulates
all functions of a microcontroller circuit, including interfaced
 Cross compiler and Cross assembler convert the object code file for a CPU, is
converted to the object code file for another processor & vice versa.
additional memory and peripherals.
15 16

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Integrated DevelopmentEnvironment (IDE) Tool Chain for Building Embedded Software
 Cross-Compilers
 Native tools are good for the host, but to port/locate embedded code
to target, the host must have a tool-chain that includes a cross-
compiler, one which runs on the host but produces code for the
target processor

 Cross-Assemblers and Tool Chain


 Host uses cross-assembler to assemble code in target’s instruction
syntax for the target
 Tool chain is a collection of compatible, translation tools, which are
‘pipelined’ to produce a complete binary/machine code that can be
linked and located into the target processor
17 18

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Foreground and Background


EMBEDDED SOFTWARE DEVELOPMENT TOOLS Systems
 Linker/Locators for Embedded Software
 The foreground/background model for managing task execution
 Native linkers are different from cross-linkers (or locators) that perform additional tasks to locate
embedded binary code into target processors.
decomposes the set of tasks comprising the application into two
 Address Resolution –
subsets called background tasks and foreground tasks.
 Native Linker: produces host machine code on the hard-drive (in a named file), which the loader  The traditional view of such systems allocates tasks that interact
loads into RAM, and then schedules (under the OS control) the program to go to the CPU. with the user or other I/O devices to the foreground set and the
 In RAM, the application program/code’s logical addresses for, e.g., variable/operands and remainder to the background set.
function calls, are ordered or organized by the linker. The locator then maps the logical addresses
 The interpretation is slightly modified in the embedded world.
into physical addresses – a process called address resolution. The locator then loads the code
accordingly into RAM . In the process the locator also resolves the addresses for calls to the
native OS routines
 Locator: produces target machine code (which the locator glues into the RTOS) and the
combined code (called map) gets copied into the target ROM. The locator doesn’t stay in the
target environment, hence all addresses are resolved, guided by locating-tools and directives,
prior to running the code 19

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Foreground and Background Foreground and Background


Systems Systems
 The foreground tasks are those initiated by interrupt or by a real-  The background tasks should include all those that do not have
time constraint that must be met. tight time constraints.
 They will be assigned the higher priority levels in the system.  Tasks that are designed to continuously monitor system integrity
 In contrast, background tasks are noninterrupt driven and are or involve heavy processing are good candidates.
assigned the lower priorities.
 Once started, the background task will typically run to completion;
however, it can be interrupted or preempted by any foreground task
at any time.
 Often separate ready queues will be maintained for the two types of
tasks.

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

What is an Operating System? What is an Operating System?


 A software layer between the application software and the  Typical embedded system (ES) solves a problem by
hardware decomposing it into smaller pieces called tasks that work
together in an organized way
 System is called multitasking system and design aspects include:
 Exchanging/sharing data between tasks
 Synchronizing tasks
 Scheduling tasks

 The piece of software that provides the required coordination is


called an operating system (OS)
 When the control must ensure that task execution satisfies a set
of specified time constraints, the OS is called a real-time
operating system (RTOS)
Source: James. K. Peckol, “Embedded System Design – A Contemporary Design Tool” Source: James. K. Peckol, “Embedded System Design – A Contemporary Design Tool”

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
What is an Operating System? What is an Operating System?
 Primary software modules within an operating system that implement  Full Featured Operating System provides additional libraries of
such control functions, device drivers, rich communication packages, human
 Scheduler
 Dispatcher
computer interface.
 Intertask communication

 Scheduler determines Real Time Operating System - RTOS


 Which task will run
 When the task will run  Real time operating system is a special purpose operating system
 The dispatcher performs the necessary operations to start the task implies rigid time requirements must be met. If requirements are
 Intertask communication mechanism for exchanging data and not met results system functionality is inaccurate and
information between tasks or processes same machine different compromised.
machines  Such systems usually interact with the physical environment:
 Kernel- Smallest portion of operating system provides above services sensors, measurement devices.
Source: James. K. Peckol, “Embedded System Design – A Contemporary Design Tool” Source: James. K. Peckol, “Embedded System Design – A Contemporary Design Tool”

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

What is an Operating System? Process or Task


 Embedded program (a static entity) = a collection of firmware
Come in two flavors
modules
Hard Real Time  When a firmware module is executing, it is called a process or task
 System delays are known or at least bounded said to be  A task is usually implemented in C by writing a function
operating correctly if can return results within any time  A task or process simply identifies a job that is to be done within an
constraints embedded application
 When a process is created, it is allocated a number of resources by
Soft Real Time the OS, which may include:
 Process stack
 Critical tasks get priority over other tasks retain priority until  Memory address space
complete  Registers (through the CPU)
 A program counter (PC)
 I/O ports, network connections, file descriptors, etc.
 These resources are generally not shared with other processes
Source: James. K. Peckol, “Embedded System Design – A Contemporary Design Tool”
Source: James. K. Peckol, “Embedded System Design – A Contemporary Design Tool”
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Types of Tasks Single Process


 Periodic tasks  Traditional view of computing: focuses on program. One says that
 Found in hard real-time applications the program (or task within the program) runs on the computer
 Examples: control, every 10 ms; multimedia, every 22.727us;
 In embedded applications, we change the point of view to that of
 Intermittent tasks microprocessor: CPU is used to execute the firmware. CPU is just
 Found in all types of applications
 Examples: send email every night at 4am; calibrate a sensor on startup; save all data when power another resource
goes down;  The time it takes a task to complete is called execution time
 Background tasks
 A soft real-time or non real-time task
 Will be accomplished only if CPU time is available

 Complex tasks
 Found in all types of applications
 Examples: Microsoft Word; Apache web server;

Source: James. K. Peckol, “Embedded System Design – A Contemporary Design Tool”


Source: James. K. Peckol, “Embedded System Design – A Contemporary Design Tool”
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Multiple Processes Multiple Processes


 If another task is added to the system, potential resource contention
problems arise
 This is resolved by carefully managing how the resources are
allocated to each task and by controlling how long each can retain
the resources
 The main resource, CPU, is given to tasks in a time multiplexed
fashion (i.e., time sharing); when done fast enough, it will appear as
if both tasks are using it at the same time
 The execution time of the program will be extended, but operation
will give the appearance of simultaneous execution. Such a scheme
is called multitasking

Source: James. K. Peckol, “Embedded System Design – A Contemporary Design Tool” Source: James. K. Peckol, “Embedded System Design – A Contemporary Design Tool”

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Multiple Processes Task Scheduling
Sequence Diagram  A schedule is set up to specify when, under what conditions, and
 At any instant in time, only one process is actively executing; it for how long each task will be given the use of the CPU (and other
resources)
said to be in run state
 The criteria for deciding which task is to run next are collectively
 The other processes are in ready or in waiting state called a scheduling strategy, which generally falls into three
categories:
 Multiprogramming
 each task continues until it performs an operation that requires waiting for an external
event
 Real-Time
 tasks with specified temporal deadlines are guaranteed to complete before those
deadlines expire
 Time sharing
 running task is required to give up the CPU so that another task may get a turn
Source: James. K. Peckol, “Embedded System Design – A Contemporary Design Tool”
Source: James. K. Peckol, “Embedded System Design – A Contemporary Design Tool”
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Task States Task States


 Primarily 4 states
1. Running or Executing
2. Ready to Run (but not running)
3. Waiting (for something other than the CPU)
4. Inactive
 Only one task can be Running at a time, unless we use a
multicore CPU
 Task waiting for CPU is Ready to Run
 When a task has requested I/O or put itself to sleep, it is Waiting
 An Inactive task is waiting to be allowed into the schedule
Source: James. K. Peckol, “Embedded System Design – A Contemporary Design Tool” Source: James. K. Peckol, “Embedded System Design – A Contemporary Design Tool”

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Process Context switch


 Process is a program in execution, comprises active processes  Task’s context comprises important information about the state of
 as process executes it’s often changing state the task, Values of any variables held in the CPU’s registers, Value
of the program counter, State of the stack etc.
 Transition between states is referred to as context switch
 Each time running task is stopped – preempted or blocked CPU is
 State must be saved / restored to switch between tasks
given to another task that is ready switch to a new context is
 Program Counter (PC)
executed
 Register values
 Process or status flags (Status Register)  Context switch first requires state of the currently active task be
 Stack Pointer (SP) saved
 Memory state
 Peripheral configurations
 etc

Source: James. K. Peckol, “Embedded System Design – A Contemporary Design Tool” Source: James. K. Peckol, “Embedded System Design – A Contemporary Design Tool”

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Task / Process Control Block Task / Process Control Block


Task / Process Control Block TCB contains all of the important information about the task
 In tasked based approach each  A typical TCB contains following information
process represented in the  Pointer (for linking the TCB to various queues)
operating system by a data  Process ID and state
structure called Task Control  Program counter
Block – TCB also known as a  CPU registers
process control block  Scheduling information ( priorities and pointers to scheduling queues)
 Memory management information (tag tables and cache information)
 Scheduling information (time limits or time and resources used)
 I/O status information (resources allocated or open files)

Source: James. K. Peckol, “Embedded System Design – A Contemporary Design Tool” Source: James. K. Peckol, “Embedded System Design – A Contemporary Design Tool”

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Address Space of a Process Address Space of a Process
Address Space of a Process
 When a process is created by the OS, it is given a portion of the
physical memory in which to work
 The set of addresses delimiting that code and the data memory,
proprietary to each process, is called its address space
 Processes are segregated Supervisor
 Supervisor mode Mode access
 User mode – limited to a subset of instructions
User
 A process may create or spawn child processes (each with its own mode
data address space, data, status, and stack) access
 A process may create multiple threads (each with its own stack and
status information)

Source: James. K. Peckol, “Embedded System Design – A Contemporary Design Tool” Source: James. K. Peckol, “Embedded System Design – A Contemporary Design Tool”

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Threads Single-process single-thread


 A process or task is characterized by a collection of resources  The sequential execution of a set of instructions through a task or
that are utilized to execute a program process in an embedded application is called a thread of execution
 The smallest subset of these resources (a copy of the CPU or thread of control
registers including the PC and a stack) that is necessary for the  This model is referred as single-process single-thread
execution of the program is called a thread
 A thread is a unit of computation with code and context, but no
private data
 A thread can be in only one process; a process without a thread
can do nothing!

Source: James. K. Peckol, “Embedded System Design – A Contemporary Design Tool” Source: James. K. Peckol, “Embedded System Design – A Contemporary Design Tool”

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Single-Process Multiple-Threads
Multiple Threads
 During partitioning and functional decomposition of the function Single-Process Multiple-Threads
intended to be performed  by an ES identify which actions
would benefit from parallel execution
 For example, allocate a sub job for each type of I/O
 Each of the sub jobs has its own thread of execution
 Such a system is called a single-process multithread design
 Threads are not independent of each other (unlike processes or
tasks)
 Threads can access any address within the process, including other threads’ stacks All four categories of multitasking operating system:
 An OS that supports tasks with multiple threads is called a – Single process single thread
– Multiprocess single thread
multithreaded operating system – Single process multiple threads
– Multiprocess multiple threads
Source: James. K. Peckol, “Embedded System Design – A Contemporary Design Tool” Source: James. K. Peckol, “Embedded System Design – A Contemporary Design Tool”

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Processes (tasks) vs. Threads

Processes (tasks) vs. Threads Complete software system with two processes
• At the minimum, a process or task needs the following:
1. The code or firmware, the instructions
–These are in the memory and have addresses
Shared among
2. The data that the code is manipulating member
–The data starts in the memory and may be moved to registers. Threads
the data has addresses
3. CPU and associated physical registers
4. A stack Proprietary to
each Thread
5. Status information

Source: James. K. Peckol, “Embedded System Design – A Contemporary Design Tool” Source: James. K. Peckol, “Embedded System Design – A Contemporary Design Tool”

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Reentrant Code

 Context switch between threads can be substantially simpler and Reentrant Code
faster than between processes  Child processes (and their threads) share the same firmware
 When switching between threads much less information must be memory area  two different threads can execute the same
saved and restored function
 An operating system that supports tasks with multiple threads  Functions using only local variables are inherently reentrant
referred to as a multithreaded operating system  Functions using global variables, variables local to the process,
 Can easily extend design to support multiple processes can further variables passed by reference, or shared resources are not
decompose each process into multiple subtasks such a system reentrant
called multiprocess – multithread design  Any shared functions must be designed to be reentrant

Source: James. K. Peckol, “Embedded System Design – A Contemporary Design Tool” Source: James. K. Peckol, “Embedded System Design – A Contemporary Design Tool”

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

 In world of embedded systems can control operation of systems  Absolute time


in number of different ways  Real world time
 Can loosely classify such systems into two broad categories  Duration
 Time based  Relative time measure
 Reactive  Non-equal intervals
 Interval
 Time Based Systems  Distinct from duration
 Interval marked by specific start and end times
 Systems whose behaviour controlled by time Can be
 Equal intervals have same start and stop can have same duration
Absolute
Relative
Following an interval
Source: James. K. Peckol, “Embedded System Design – A Contemporary Design Tool” Source: James. K. Peckol, “Embedded System Design – A Contemporary Design Tool”

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Tasks and Intertask Communication Interprocess / Interthread Communication

• Multitasking / Multithreading system supports multiple tasks  When threads operating independently our systems have few if
• Important job in multitasking system any Conflicts, Chances for corruption, Contentions
 Exchanging data between tasks  Real systems must deal with all such problems resources and
 Synchronizing tasks inter thread communication must take place in robust manner
 Sharing resources  Interaction may be direct or indirect Must be synchronized and
co-ordinated want to prevent race conditions outcome of task or
computation depends upon order in which tasks execute

Source: James. K. Peckol, “Embedded System Design – A Contemporary Design Tool” Source: James. K. Peckol, “Embedded System Design – A Contemporary Design Tool”

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Thank you
Embedded System Design
BITS Pilani Prof. Manoj S Kakade
Dept of EEE
Pilani Campus

55
1
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
BITS Pilani Contents
Pilani Campus

Cortex Microcontroller Software Interface Standard-Real-Time


Operating System (CMSIS-RTOS)-RTX

Reference Book:
 Trevor Martin,“The Designer’s Guide to the Cortex-M Processor
EEEZG512/ESZG512/MELZG526/SEZG516 Family”, Second Edition, Elsevier Ltd.
Embedded System Design
Contact Session 16
2
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Introduction RTOS kernel


 “Cortex Microcontroller Software Interface Standard (CMSIS)”
defines a standard API for Cortex-M RTOS.
 RTOS structure allows you to take a more object-orientated design
approach
 RTOS also provides you with multithreaded support on a small
microcontroller.
 RTOS-based project is composed of well-defined threads it helps to
improve project management, code reuse, and software testing.
 RTOS has additional memory requirements and increased interrupt
latency.
 Keil RTX RTOS: 500 bytes of RAM and 5k bytes of code. RTOS kernel
Source: Trevor Martin, “The Designer’s Guide to the Cortex-M Processor Family” Source: Trevor Martin, “The Designer’s Guide to the Cortex-M Processor Family”

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

CMSIS-RTOS API Threads


Accessing the CMSIS-RTOS API:  In CMSIS-RTOS the basic unit of execution is a “thread.”
 To access any of the CMSIS-RTOS features in our application  A thread is very similar to a “C” procedure but has some very
fundamental differences.
code it is necessary to include the following header file:
#include<cmsis_os.h>
 This header file is maintained by ARM as part of the CMSIS-
RTOS standard.
 Keil RTX RTOS this is the default API.

 While we always return from our “C” function, once started an RTOS
thread must contain a loop so that it never terminates and thus runs
forever.
Source: Trevor Martin, “The Designer’s Guide to the Cortex-M Processor Family” Source: Trevor Martin, “The Designer’s Guide to the Cortex-M Processor Family”

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Threads Threads
 When a thread is created, it is also allocated its own thread ID. Context switch:
 This is a variable which acts as a handle for each thread and is
used when we want to manage the activity of the thread.
osThreadId id1,id2,id3;

Each thread has its own stack for saving its data during a context switch.
Source: Trevor Martin, “The Designer’s Guide to the Cortex-M Processor Family” Source: Trevor Martin, “The Designer’s Guide to the Cortex-M Processor Family”

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Threads Starting the RTOS
Threads may be in one of three states: void thread1 (void);
 Running -The currently running thread void thread2 (void);
 Ready -Threads ready to run osThreadId thrdID1, thrdID2;
 Wait -Blocked threads waiting for an OS event void main (void)
{
osKernelInitialize ();
IODIR1 5 0x00FF0000; // Do any C code you want
Init_Thread(); //Create a Thread
osKernelStart(); //Start the RTOS
}
Source: Trevor Martin, “The Designer’s Guide to the Cortex-M Processor Family” Source: Trevor Martin, “The Designer’s Guide to the Cortex-M Processor Family”

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Threads
 Threads of equal priority will be scheduled in a round-robin  A First CMSIS-RTOS Project – Demo in Keil
fashion.
 High priority tasks will preempt low priority tasks and enter the
running state “on demand.”

Source: Trevor Martin, “The Designer’s Guide to the Cortex-M Processor Family” Source: Trevor Martin, “The Designer’s Guide to the Cortex-M Processor Family”

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Creating Threads Creating Threads


 By default, the main() function is automatically created as the first  First a thread structure is defined; this allows us to define the thread
thread running. operating parameters.
osThreadId thread1_id; //thread handle
 We want to control main as a thread we must get its thread ID.
void thread1 (void const *argument);
 The first RTOS function we must therefore call is osThreadGetId() //function prototype for thread1
which returns the thread ID number of the currently running thread. osThreadDef(thread1, osPriorityNormal, 1, 0);
 This is then stored in its ID handle. //thread definition structure

 Once the thread structure has been defined the thread can be created using
the osThreadCreate() API call.
 Then the thread is created from within the application code; this is often
done within the main thread but can be at any point in the code.
thread1_id 5 osThreadCreate(osThread(thread1), NULL);
Source: Trevor Martin, “The Designer’s Guide to the Cortex-M Processor Family” Source: Trevor Martin, “The Designer’s Guide to the Cortex-M Processor Family”

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Creating Threads Thread Management and Priority


 When each thread is created, it is also assigned its own stack for CMSIS-RTOS priority levels:
storing data during the context switch. osPriorityIdle
 This should not be confused with the native Cortex processor osPriorityLow
stack; it is really a block of memory that is allocated to the thread. osPriorityBelowNormal
osPriorityNormal
Example Demo in Keil osPriorityAboveNormal
 Creating and Managing Threads: We will create and manage osPriorityHigh
some additional threads. Each of the threads created will toggle a
GPIO pin on GPIO port B to simulate flashing an LED. osPriorityRealTime
osPriorityError

Source: Trevor Martin, “The Designer’s Guide to the Cortex-M Processor Family” Source: Trevor Martin, “The Designer’s Guide to the Cortex-M Processor Family”

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Thread Management and Priority
 Once the threads are running, there are a small number of OS Multiple Instances
system calls which are used to manage the running threads.  One of the interesting possibilities of an RTOS is that you can create
 It is also then possible to elevate or lower a thread’s priority either multiple running instances of the same base thread code.
from another function or from within its own code.  First we create the thread structure and set the number of thread instances
to two:
osStatus osThreadSetPriority(threadID, priority);
osThreadDef(thread1, osPriorityNormal, 2, 0);
osPriority osThreadGetPriority(threadID);
 Then we can create two instances of the thread assigned to different
thread handles. A parameter is also passed to allow each instance to
Example: identify which UART it is responsible for.
We will look at assigning different priorities to threads ThreadID_1_0 = osThreadCreate(osThread(thread1), UART1);
ThreadID_1_1 = osThreadCreate(osThread(thread1), UART2);

Source: Trevor Martin, “The Designer’s Guide to the Cortex-M Processor Family” Source: Trevor Martin, “The Designer’s Guide to the Cortex-M Processor Family”

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Time Management
 RTOS also provides some timing services which can be accessed
Example: through RTOS system calls.
We will look at creating one thread and then create multiple run-time Time Delay
instances of the same thread.  The most basic of these timing services is a simple timer delay function.
void osDelay ( uint32_t millisec )
 This call will place the calling thread into the WAIT_DELAY state for
the specified number of milliseconds.
 The scheduler will pass execution to the next thread in the READY
state
 When the timer expires, the thread will leave the wait_delay state and
move to the READY state.
 The thread will resume running when the scheduler moves it to the
RUNNING state.

Source: Trevor Martin, “The Designer’s Guide to the Cortex-M Processor Family” Source: Trevor Martin, “The Designer’s Guide to the Cortex-M Processor Family”

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Waiting for an Event


 In addition to a pure time delay it is possible to make a thread halt
and enter the waiting state until the thread is triggered by another
RTOS event.
 RTOS events can be a signal, message, or mail event.
 The osWait() API call also has a timeout period defined in
milliseconds that allows the thread to wake up and continue
execution if no event occurs.
osStatus osWait ( uint32_t millisec )
 When the interval expires, the thread moves from the wait to the
READY state and will be placed into the running state by the
During their lifetime threads move through many states. scheduler.
Source: Trevor Martin, “The Designer’s Guide to the Cortex-M Processor Family” Source: Trevor Martin, “The Designer’s Guide to the Cortex-M Processor Family”

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Example: Virtual Timers


We will look at using the basic time delay function.  The CMSIS-RTOS API can be used to define any number of
virtual timers which act as count down timers.
 When they expire, they will run a user call-back function to
perform a specific action.
 Each timer can be configured as a one shot or repeat timer.
 A virtual timer is created by first defining a timer structure.
osTimerDef(timer0,led_function);

Source: Trevor Martin, “The Designer’s Guide to the Cortex-M Processor Family” Source: Trevor Martin, “The Designer’s Guide to the Cortex-M Processor Family”

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
 This defines a name for the timer and the name of the call back Example:
function. The timer must then be instantiated in an RTOS thread. We will configure a number of virtual timers to trigger a callback
osTimerId timer0_handle 5 osTimerCreate (timer(timer0), function at various frequencies.
osTimerPeriodic, (void *)0);
 This creates the timer and defines it as a periodic timer or a single
Idle Demon
shot timer (osTimerOnce). The final parameter passes an
argument to the call back function when the timer expires.  If during our RTOS program we have no thread running and no
thread ready to run (eg, they are all waiting on delay functions)
osTimerStart ( timer0_handle,0x100);
then the RTOS will use the spare run-time to call an “Idle
 The timer can then be started at any point in a thread the timer Demon” that is again located in the RTX_Conf_CM.c file.
start function invokes the timer by its handle and defines a count
 This idle code is in effect a low priority thread within the RTOS
period in milliseconds.
which only runs when nothing else is ready.
Source: Trevor Martin, “The Designer’s Guide to the Cortex-M Processor Family” Source: Trevor Martin, “The Designer’s Guide to the Cortex-M Processor Family”

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Inter-Thread Communication
 The CMSIS-RTOS API supports inter-thread communication with
signals, semaphores, mutexes, mailboxes, and message queues.
Signals
 CMSIS-RTOS Keil RTX supports up to 16 signal flags for each
thread.
 These signals are stored in the thread control block.
 It is possible to halt the execution of a thread until a particular
signal flag or group of signal flags are set by another thread in the
system A thread may be placed into a waiting state until a pattern of flags is set
by another thread. When this happens, it will return to the ready state
and wait to be scheduled by the kernel
Source: Trevor Martin, “The Designer’s Guide to the Cortex-M Processor Family” Source: Trevor Martin, “The Designer’s Guide to the Cortex-M Processor Family”

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

 The signal wait system calls will suspend execution of the thread Example:
and place it into the wait_event state. We will look at using signals to trigger activity between two threads.
 Execution of the thread will not start until all the flags set in the While this is a simple program it introduces the concept of
signal wait API call have been set. synchronizing the activity of threads together.
 It is also possible to define a periodic timeout after which the
waiting thread will move back to the ready state, so that it can
resume execution when selected by the scheduler.
 A value of 0xFFFF defines an infinite timeout period.
osEvent osSignalWait ( int32_t signals,uint32_t millisec);
 If the signals variable is set to zero when osSignalWait is called
then setting any flag will cause the thread to resume execution.
Source: Trevor Martin, “The Designer’s Guide to the Cortex-M Processor Family” Source: Trevor Martin, “The Designer’s Guide to the Cortex-M Processor Family”

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Semaphores
 Semaphores are a method of synchronizing activity between two or Semaphores help to control access to program resources.
more threads.
 A semaphore is a container that holds a number of tokens.
 As a thread executes, it will reach an RTOS call to acquire a
semaphore token.
 If the semaphore contains one or more tokens, the thread will
continue executing and the number of tokens in the semaphore will
be decremented by one.
 If there are currently no tokens in the semaphore, the thread will be
placed in a waiting state until a token becomes available.
 At any point in its execution, a thread may add a token to the
semaphore causing its token count to increment by one
Source: Trevor Martin, “The Designer’s Guide to the Cortex-M Processor Family” Source: Trevor Martin, “The Designer’s Guide to the Cortex-M Processor Family”

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Mutex
To use a semaphore in the CMSIS-RTOS you must first declare a  Mutex stands for “Mutual Exclusion.”
semaphore container:  A mutex is a specialized version of semaphore.
osSemaphoreId sem1;  Like a semaphore, a mutex is a container for tokens.
osSemaphoreDef(sem1);  A mutex can only contain one token which cannot be created or
Then within a thread the semaphore container can be initialized with destroyed.
a number of tokens.  The principle use of a mutex is to control access to a chip resource such
sem1 = osSemaphoreCreate(osSemaphore(sem1), as a peripheral. For this reason a mutex token is binary and bounded.
SIX_TOKENS);  Apart from this it really works in the same way as a semaphore.
 First of all we must declare the mutex container and initialize the mutex:
Example: osMutexId uart_mutex;
We will look at the configuration of a semaphore and use it to signal osMutexDef (uart_mutex);
between two tasks.
Source: Trevor Martin, “The Designer’s Guide to the Cortex-M Processor Family” Source: Trevor Martin, “The Designer’s Guide to the Cortex-M Processor Family”

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

 Once declared the mutex must be created in a thread. Example:


uart_mutex = osMutexCreate(osMutex(uart_mutex)); Program writes streams of characters to the microcontroller UART
 Then any thread needing to access the peripheral must first from different threads.
acquire the mutex token:
osMutexWait(osMutexId mutex_id,uint32_t millisec;
 Finally, when we are finished with the peripheral the mutex must
be released:
osMutexRelease(osMutexId mutex_id);
 Mutex use is much more rigid than semaphore use, but is a much
safer mechanism when controlling absolute access to underlying
chip registers.
Source: Trevor Martin, “The Designer’s Guide to the Cortex-M Processor Family” Source: Trevor Martin, “The Designer’s Guide to the Cortex-M Processor Family”

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Data Exchange
 CMSIS-RTOS provides two methods of data transfer between  The second form of data transfer is a mail queue.
threads.  This is very similar to a message queue except that it transfers
 The first method is a message queue which creates a buffered data blocks of data rather than a single integer
“pipe” between two threads.
 The message queue is designed to transfer integer values

Source: Trevor Martin, “The Designer’s Guide to the Cortex-M Processor Family” Source: Trevor Martin, “The Designer’s Guide to the Cortex-M Processor Family”

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

 Message and mail queues both provide a method for transferring Examples:
data between threads. Message Queue
 This allows you to view your design as a collection of objects We will look at defining a message queue between two threads and
(threads) interconnected by data flows. then use it to send process data.
 The data flow is implemented by message and mail queues.
 This provides both a buffered transfer of data and a well-defined Mailbox
communication interface between threads. Demonstrates configuration of a mailbox and using it to post
messages between tasks.

Source: Trevor Martin, “The Designer’s Guide to the Cortex-M Processor Family” Source: Trevor Martin, “The Designer’s Guide to the Cortex-M Processor Family”

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Scheduling Options Preemptive Scheduling
 CMSIS-RTOS allows you to build an application with three  If the round-robin option is disabled in the RTX_Config_CM.c
different kernel scheduling options. file, each thread must be declared with a different priority.
 These are round-robin scheduling, preemptive scheduling, and  When the RTOS is started and the threads are created, the thread
cooperative multitasking. with the highest priority will run

Source: Trevor Martin, “The Designer’s Guide to the Cortex-M Processor Family” Source: Trevor Martin, “The Designer’s Guide to the Cortex-M Processor Family”

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

 This thread will run until it blocks, that is, it is forced to wait for Round-Robin Scheduling
an event flag, semaphore, or other object.  A round-robin-based scheduling scheme can be created by
 When it blocks, the next ready thread with the highest priority enabling the round-robin option in the RTX_Conf_CM.c file and
will be scheduled and will run until it blocks, or a higher priority declaring each thread with the same priority
thread becomes ready to run.
 So with preemptive scheduling we build a hierarchy of thread
execution, with each thread consuming variable amounts of run-
time.

Source: Trevor Martin, “The Designer’s Guide to the Cortex-M Processor Family” Source: Trevor Martin, “The Designer’s Guide to the Cortex-M Processor Family”

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

 In this scheme, each thread will be allotted a fixed amount of run- Round-Robin Preemptive Scheduling
time before execution is passed to the next ready thread.  The default scheduling option for the Keil RTX is round-robin
 If a thread blocks before its timeslice has expired, execution will preemptive.
be passed to the next ready thread.  For most applications this is the most useful option and you
should use this scheduling scheme unless there is a strong reason
to do otherwise.

Source: Trevor Martin, “The Designer’s Guide to the Cortex-M Processor Family” Source: Trevor Martin, “The Designer’s Guide to the Cortex-M Processor Family”

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Cooperative Multitasking
 A final scheduling option is cooperative multitasking.
 In this scheme, round-robin scheduling is disabled and each
thread has the same priority.
 This means that the first thread to run will run forever unless it
blocks.
 Then execution will pass to the next ready thread
 Threads can block on any of the standard OS objects, but there is
also an additional OS call, osThreadYeild(), that schedules a In a cooperative RTOS each thread will run until it reaches a
thread to the ready state and passes execution to the next ready blocking OS call or uses the osThreadYield() call.
thread.
Source: Trevor Martin, “The Designer’s Guide to the Cortex-M Processor Family” Source: Trevor Martin, “The Designer’s Guide to the Cortex-M Processor Family”

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy