You are on page 1of 88

1

LECTURE 1. EMBEDDED SYSTEMS

EVOLUTION IN DIGITAL DESIGN

MEDIUM SCALE INTEGRATION

The first medium scale integrated circuits containing perhaps 4 gates or a counter
date from the 1960s for so-called TTL and early 70s for the lower power but slower
CMOS technology. Complex digital designs incorporating state machine control were
possible and the realization of a digital system design by interconnecting numbers of
such chips in a fixed manner on a printed circuit has remained a technique even to
today.

NOTE: Transistortransistor logic (TTL) is a class of digital circuits built from


bipolar junction transistors (BJT) and resistors. It is called transistortransistor logic
because both the logic gating function (e.g., AND) and the amplifying function are
performed by transistors. CMOS Complementary metaloxidesemiconductor
uses "complementary-symmetry" -refers to the fact that the typical digital design
style with CMOS uses complementary and symmetrical pairs of p-type and n-type
metal oxide semiconductor field effect transistors (MOSFETs) for logic functions.

The fixed nature of the functionality means that, should a change be needed, the
printed circuit board used to interconnect the MSI devices must be scrapped and
replaced. This design technique is known as glue logic simply because functionality
is obtained by assembling numbers of MSI chips and soldering them together on a
pcb (glue together).
2

The 7400 shown below is an example of MSI it comprises 4 packages of 2 input


NAND gates.

By interconnecting gates, more complicated logic functions can be derived

By using multiple MSI packages and suitable inter-wiring (glue-logic) extremely


complex digital solutions can be designed BUT should the need for the design to
be changed arises, the complete hardware board must be scrapped.

The above shows a typical MSI digital design using 7400 series devices as glue-
logic
3

THE MICROPROCESSOR

In the mid 1970s the microprocessor appeared. This provided a way of inputting a
sequence of digital codes held in ROM (the program) to a device called a
microprocessor. Each code would be detected and indicate a set sequence of events
called the instruction which would then be carried out by the microprocessor. The
instruction might be an increment register, decrement register, load register or other.
Each decoded instruction would initiate a mini state machine constructed in
hardware which would cause the instruction to be completed. Where the
microprocessor had power was in that, by changing the order of the program i.e.
changing the instructions, the microprocessor could be given a completely new
functionality. This completely removed the inflexibility of the glue logic technique.

Disadvantages of the microprocessor revolution were that completely new design


techniques had to be learnt. In addition, peripheral devices e.g. memory (both RAM
and program ROM), I/O interfacing, timing had to be used to make a complete
system so the need for a dedicated pcb remained. However, unlike glue logic,
changes in functionality could be made by reprogramming.

The microprocessor became the default tool for medium level system design which
took the name of embedded design. A embedded design is one that has a single
function e.g. a TV remote control or a microwave timer unit as such, embedded
designs can be fabricated in any of the technologies listed here.

NOTE: The first microprocessors emerged in the early 1970s and were used for
electronic calculators, using binary-coded decimal (BCD) arithmetic on 4-bit words.
Other embedded uses of 4-bit and 8-bit microprocessors, such as terminals, printers,
various kinds of automation etc., followed soon after. Affordable 8-bit
microprocessors with 16-bit addressing also led to the first general-purpose
microcomputers from the mid-1970s on.

Since the early 1970s, the increase in capacity of microprocessors has followed
Moore's law; this originally suggested that the number of components that can be
fitted onto a chip doubles every year. With present technology, it is actually every
two years, and as such Moore later changed the period to two years.
4

THE MICROCONTROLLER

One problem associated with the microprocessor was that it required


interconnection to such external resources of program, data memory and
input/output interfacing. In order to address memory or access peripheral devices,
unique address codes needed to be placed on an address bus (collection of
individual address lines) and corresponding data placed on a dedicated data bus. As
such the microprocessor system required printed circuit board space not only for the
microprocessor but for all the memory and I/O components and the bus structures.

In the early 1990s Microchip and others introduced the concept of the
microcontroller. This device was a simple microprocessor system on a single chip
i.e. program memory, data memory and I/O was integrated on the single device. The
microcontroller has become the standard for most but not all embedded designs.

NOTE: The first single-chip microprocessor was the Intel 4004.

The 4004 was the world's first universal microprocessor. In the late 1960s, many
scientists had discussed the possibility of a computer on a chip, but nearly everyone
felt that integrated circuit technology was not yet ready to support such a chip. Intel's
Ted Hoff felt differently; he was the first person to recognize that the new silicon-
gated MOS technology might make a single-chip CPU (central processing unit)
possible. Hoff and the Intel team developed such an architecture with just over 2,300
transistors in an area of only 3 by 4 millimetres. With its 4-bit CPU, command
register, decoder, decoding control, control monitoring of machine commands and
interim register, the 4004 was a remarkable invention. Today's 64-bit
microprocessors are still based on similar designs, and the microprocessor is still the
most complex mass-produced product ever with more than 5.5 million transistors
performing hundreds of millions of calculations each second - numbers that are sure

to be outdated fast.
INTEL 4004 Microprocessor system on a chip ca. 1971
5

A BRIEF REMINDER OF HOW A MICROCONTROLLER SYSTEM WORKS

In order to appreciate the differences between an embedded system using a


microcontroller (the same description would refer to a microprocessor system but
dont forget that, unlike the microcontroller, it is not a single integrated circuit) and
one that uses re-configurable hardware a brief summary of typical operation follows:

The hardware architecture of a typical (in this case Microchip PIC) microcontroller
is as shown:

The microcontroller can perform a set of simple instructions that can, for example,
move data, add and subtract data, set or clear input/output pins from the
microcontroller. For the PIC microcontroller, these instructions are limited in number
i.e. 35 instructions within the instruction set. In order to complete complicated tasks,
6

the order in which the instructions are executed will determine the way in which the
system operates. The program is the sequence of instructions that must be
executed in order. You will have created the programming code file using an IDE text
editor and compiling the code to create the programming file (.hex). This program
code is downloaded to the microcontroller and placed in sequence within the flash
program memory section.

The Program Counter is a register (location of binary data) that holds a physical
pointer to the next instruction that must be decoded and executed. On power-up the
Program Counter is set to the first location in Program Memory. The procedure that
automatically occurs for this first instruction will be repeated in sequential order for
the following instructions in Program Memory.

The first instruction is extracted from Program Memory, placed in an instruction


register and input to the Instruction Decoder. The Instruction Decoder decodes (i.e.
determines which instruction it is) the instruction then causes the hardware to
execute or carry-out the instruction. The Program Counter is then loaded with the
address (location) of the next instruction to fetch from Program Memory.

The nature of each instruction will determine the data flow within the microcontroller
by controlling so-called control lines to activate sections of the ALU (Arithmetic &
Logic Unit associated with performing many of the instructions associated with
arithmetic and logic e.g. ADD, SUBTRACT, logical AND etc..).

The rate at which the Program Memory instructions are fetched and executed will be
ultimately determined by on-chip or external timing oscillator.

Separate hardware exists for PORT structures, timer registers, ADC and serial
communications. This hardware can operate independently of the running program
loop offering some degree of parallel activity. This is shown in the diagram lower
right.

RAM memory is available as temporary variable storage space and most


microcontrollers will have EEPROM data memory that is non-volatile (meaning it is
not lost on power down).

Stack Memory is a RAM resource used to store the return address when branching
to a sub-routine or interrupt service routine.

The important point to note with microcontroller systems is that they are
SEQUENTIAL in nature. It is a major limitation since the microcontroller can only do
one thing at a time. Some parallelism is provided by the hardware of independent
timers, ADC, USART etc.. Multiple tasks may be completed only using time sharing
techniques.
7

RE-CONFIGURABLE HARDWARE

This technology is significantly different to microcontroller technology. It allows for


true parallelism and multitasking without time-sharing tricks. The following
description is generic and intentionally simplistic to allow a feel for the technology.

In a re-configurable device (larger devices are called FPGAs or Field Programmable


Gate Arrays and smaller devices are called CPLDs or Complex Programmable Logic
Devices) multiple instances of electronic components in the form of gates, flip-flops
and multiplexers are arranged into a cell matrix. Each cell sometimes called a
Configurable Logic Block will have identical components e.g. a flip-flop, some gates
and a multiplexer. These components are largely isolated within the cell. The cell is
electrically isolated from other cells. Finally, along the physical perimeter of the re-
configurable IC are input/output pins similar to the PORT pins of a microcontroller
that allow connection from external devices to and from the re-configurable device.

Running between cells are electrical connection lines called unsurprisingly


interconnect. The FPGA or CPLD can be configured or programmed by serially
inputting a configuration stream or file. The binary pattern of the configuration stream
is such that a specific section of the configuration stream is associated with a
specific logic cell. The 0 and 1 pattern within this section will determine the
interconnection of resource within the cell and also the interconnection of this cell to
adjacent cells and/or to the I/O pins.

So, by altering the configuration data stream, we can alter the connected logic
structure within the device. Since a digital electronic system is created from gates,
flip-flops and multiplexers, if there are sufficiently many Configurable Logic Cells
within the device, we can create quite complex digital electronic systems. This is like
the glue-logic process used by interconnecting MSI devices like the 7400 BUT has
the advantage that should a redesign be needed, the new version can be configured
on the existing FPGA device and no discarding of hardware is necessary.

Re-configurable design is fundamentally different to a system designed using a


microcontroller. Programming the microcontroller does not alter the hardware
structure within the microcontroller but merely dictates the order in which the
hardware is used in order to accomplish a task. In re-configurable, each new design
has a new hardware structure that uniquely accomplishes the system task(s).
8

The following diagram shows a simplified FPGA cellular structure:

The interconnect is seen running between the cells (Logic Blocks).

CONFIGURATION OR PROGRAMMING

Just like the microcontroller program is developed within a manufacturers IDE, code
compiled and the program file downloaded, the FPGA/CPLD follows a similar
procedure. There are two methods of developing the system prior to compiling a
program file:Schematic Capture where the system to be designed is created within
a GUI as visual components and interconnections identical to creating a schematic
diagram for an electronic circuit. Once complete, IDE tools allow for basic errors to
be located and corrected, circuit simulation to check for correct function and finally
the creation of a compiled program or configuration file. The IDE is then connected
by programming cable to a target board holding the device to be configured and the
file is downloaded.HLL A High Level Language programming method using either
VHDL or Verilog languages can be used to create the program file however, it is vital
to stress that the program creation does not follow the sequential programming
methods used for conventional HLLs and microcontroller programming. VHDL or
Verilog can be used to create multiple concurrent (meaning able to operate at the
same time) hardware systems. Again, once checked for syntax errors and simulated
for functionality, the code can be compiled to create the program or configuration bit
stream needed to configure the FPGA/CPLD cell structures.
9

HISTORY: RE-CONFIGURABLE GATE ARRAYS

In the 1980s some early examples of re-configurable gate array technology were
appearing. The application for such relatively low density products (less than a few
hundred gates ) was typically microprocessor address decoding to select devices.
The devices could be programmed by Boolean equation or by schematic capture in
which an IDE (integrated development environment) provided by the manufacture to
be run on conventional desk-top platforms allowed for circuit symbols to be
interconnected and connected to I/O pins in the same manner as constructing a
circuit diagram. Software tools converted the schematic into netlist format to allow
programming of the device.

A netlist is an electronic data file containing all the interconnect information for a
circuit i.e. allows a schematic to be stored as node interconnect data.

ASIC DESIGN

Each of the MSI devices used in the 1960s and 70s glue logic designs was an
early example of an ASIC or Application Specific Integrated Circuit. Each design
was fixed functionality was obtained by fixed N and P semiconductor layout on a
silicon substrate. The once only or NRE costs for an ASIC design are large. They
represent the cost involved in designing the locations of P and N extrinsic
semiconductor then producing photographic masks etc.. Special tooling is needed to
dope the required areas, lay down interconnect and wire to external physical pin
locations. However, size reduction is achieved by the integration. The design is not
flexible a mistake would lead to most of the once only costs having to be repeated
(once only costs for a small current digital ASIC design might be in the order of
$US400,000 say a serious investment ). The benefit of ASIC design is in the unit
cost. A device can be produced for cents in 1000 off quantities if we ignore the need
to pay back the once only costs.
10

RE-CONFIGURABLE LOGIC DEVICES

Since mid 1980s the size of re-configurable arrays has increased enormously. Costs
have decreased to levels that encourage the use of devices in a wide range of
applications. In 2004, devices such as the ALTERA MAX7000 series offer over 2500
gates for a unit cost of about $NZ40 and the FLEX10K series with in excess of
40,000 gates is offered for about $NZ80. Not only is the number of gates much
larger but the way in which they are arranged allows for implementation of complex
sequential systems. A microprocessor is a form of hardware sequencer controlled by
a set of sequential input codes (instructions) input from program memory. Since
Moores Law states, that the number of transistors capable of being fabricated within
a single device, will double every 2 years you can estimate current device densities.

The state of technology is such that the complete hardware structure of a


microprocessor can be implemented on a re-configurable device a so-called soft
processor core. In fact, microprocessor designers often now use re-configurable
logic as a way of testing functionality of their design before implementing the
processor as an ASIC. In this way, costly functional errors can be found and
corrected before going to expensive ASIC tooling. Re-configurable devices are fast
the ALTERA devices mentioned above can accommodate speeds in excess of
50MHz say whilst it is now standard to expect speeds of between 50MHz and
400MHz and the upper limits are pressing 1GHz (data 2004 so check for today!).

By returning to the state machine design techniques of complex systems


implemented in the days of the glue logic era we can design almost any intelligent
system using re-configurable logic FPGAs or CPLDs.

NOTE: The FPGA is higher density than the CPLD but requires an additional
memory device in order to retain its data after power-down. The CPLD is the
Complex Programmable Logic Device which generally has less capacity than the
FPGA but is non-volatile.

Vendors now make design tools either low cost or free which encourages use of the
technology.
11

HYBRID EMBEDDED DESIGNS

Until recently one definition of an embedded design was a design which used a
microprocessor. In fact, this definition is no longer accurate. An embedded design
could be completely enclosed within a re-configurable device without the use of a
microprocessor core state machine techniques coupled with hardware descriptive
language can now accommodate any embedded requirement.

Often designs may be hybrid containing both microcontroller and FPGA. The FPGA
offers fast execution and parallel processing that is impossible with conventional
microcontrollers.

The FPGA is particularly suited to DSP applications where data is being processed
at high speeds often in real time.

It is possible to change the functionality of the FPGA by simply loading new


configuration settings. This can be done in 200 to 300ms for the FLEX10K FPGA
(data from 2004) which offers the ability to adapt the design during run time.
12

QUESTIONS - LECTURE 1

What is meant by the term glue-logic?

Glue-Logic is the interconnection of digital components such as gates or counters


to make complex digital functions.

What is the disadvantage of Glue Logic using MSI digital devices?

If MSI devices are used, the printed circuit board holding the MSI devices must be
scrapped if a new functionality is required since the interconnection is fixed by the
fixed routes taken by PCB tracks between devices.

What is an embedded design give an example?

An embedded design is a design that has fixed functionality and a single purpose -
e.g. a microwave digital timer.

What was the first single-chip microprocessor?

Intel 4004 ca. 1971.

What is Moores Law?

Moores Law states that, the number of transistors capable of being fabricated within
a single device, will double every 2 years.

What is the difference between a microprocessor and a microcontroller?

A microcontroller is a single chip microprocessor system with RAM,I/O and program


memory integrated on the chip.
13

LECTURE 2 DESIGN METRICS

When considering areas of computational applications most people would first think of the
PC with associated applications software to perform a variety of tasks. The PC is linked with
a computational engine formed by an advanced microprocessor.

Numerous electronic devices designed for specific applications, with specific functionality,
exist which employ a microprocessor albeit a device of lesser computational power than that
of the PC. Examples might be washing machines, ATMs, microwave ovens, alarm systems,
automotive engine control and ABS braking etc.. In these systems, the microprocessor (or
microcontroller) is embedded within the apparatus, has fixed programme and is largely
invisible or transparent to the user.

If you refer to Chapter 1 of Embedded System Design (Vahid/Givargis) you will see the
impressive statistics for the rise in use of embedded processors e.g. 35 to 50 per average
US household in 1999 predicted to rise to nearly 300 by 2004. The question might be asked
where are all these embedded processors? Try and identify at least 10 applications.

CHARACTERISTICS OF AN EMBEDDED SYSTEM

Vihad/Givargis suggest three fundamental characteristics of an embedded system:

1. Single Function
The embedded system generally has only one designed function e.g. a control system
for a microwave oven say.

2. Tight Constraint
Most embedded systems are heavily constrained in design metrics. The term design
metric meaning all aspects of the design specification e.g. unit cost, size (e.g. need to fit
the design to a single chip), performance (usually speed) and power consumption.

3. Reactive

The term reactive means that a system must respond in an acceptable timely manner to
changes in input stimuli and must compute certain results in real time without
unacceptable delay.
14

COMMON DESIGN METRICS

Refer to Page 5 Embedded System Design for a suitable definition of the main design
metrics associated with an embedded design i.e.

NRE (Non-recurring Engineering) Cost also known as once-only costs

Unit Cost

Size physical dimensions

Performance speed of operation

Power exceptionally important if the device is portable and battery powered

Flexibility ability to change functionality without large NRE cost software is flexible

Time-To-Prototype - the time taken to produce a physical example of the desired


functionality

Time-To-Market the time taken before the product can be released to the customer
this will include design, test, manufacture times

Maintainability - how can the product be modified at a later time by persons who may
not be original designers?

Correctness does the system have hidden problems will it function correctly?

Safety can the system cause harm?

CHANGING ONE DESIGN METRIC CAN CAUSE ANOTHER TO CHANGE!

An example of this might be a trade-off between unit cost and NRE.


15

TIME TO MARKET

If the design is delayed it can have dramatic consequences for profitability.

MARKET WINDOW DIAGRAM

Revenue($)

Time (Months)

The above shows a typical market window for a product. You should be able to justify the
shape of the curve, as well as the window defined between the two verticals. If in doubt,
consider the cell phone as an example. Initially, infrastructure may not be available,
advertising and marketing has not been done so the take up will be slow. At the upper end,
the curve will fall away as newer generation models are introduced and demand for older
technology decreases i.e. 2G to 3G.
16

MARKET REVENUE - effect of delay in entering the market

Revenue ($) On Time Entry

Delayed
Entry

Time (Weeks)
D W 2W

Assuming the product is ready to take advantage of the market window, on-time entry will
show as above with W being the time of market peak. Assuming a symmetrical market rise
and fall then 2W will indicate the time at which revenue will have fallen back to the initial
value at the start of on-time entry.

To calculate the total revenue received from the product you would have to calculate the
area beneath the triangle i.e. base x height which, in this case, would be * 2W * W i.e.
W2 assuming the angle of market rise is 45 degrees.

For the delayed entry curve, the total revenue will be * (W D + W)* (W D))

If we define percentage revenue loss as

((On-Time Delayed) / On-Time)) * 100

Then, from the previous equations:

Percentage revenue loss = (D (3W D) / 2W 2) * 100

Using the example - given by Embedded System Design- for a product with a 52 week
lifetime so that W = 26 weeks and substituting D = 4 for a 4 week delay shows that 22% of
potential revenue will be lost by this small delay!
17

NRE VERSUS UNIT COST

You will certainly become familiar with a relationship that suggests that a system with low
unit cost frequently incurs large NRE expenditure. An example might be the use of an
Application Specific IC (ASIC) in a system. An ASIC chip will allow manufacture at unit costs
of cents but the once-only costs may be hundreds of thousands of dollars. The same system
can be run using a non-specific FPGA say with a unit cost of $30 but no associated NRE
cost. A graph shows the relationship between NRE and unit cost. The type of technology
chosen will depend on the expected number of unit sales!

Total Cost
No NRE but high Unit Cost

High NRE but low Unit Cost

Number of Units

Crossover point

The significance of the curve should be self-evident.

As a general relationship:

Total Cost = NRE Cost + Unit Cost * Number of Units

Per Product Cost = Total Cost / Number of Units = NRE Cost/ Number of Units + Unit Cost
18

EXAMPLE

Using Technology A, a manufacturer will incur NRE costs of $2000 and this will allow for a
unit cost of $100

Using Technology B, a manufacturer will incur NRE costs of $30000 for a unit cost of $30

Using Technology C, a manufacturer will incur NRE costs of $100000 for a unit cost of $2

Plot Total Cost versus Volume on one graph for each of the above and suggest the
projected sales needed to justify Technology C over Technology A or B.
19

LECTURE 3 STATE MACHINE DESIGN MODEL

A state machine is a method of non-linear rather than sequential programming. This


means that the flow of the program may not follow a set sequence but may be redirected at
any time according to input stimuli. Using this design method the various states that the
system can take are described. A state is a mode of operation which is entered from another
state when receiving an appropriate signal or stimulus. The state is remains constant until
appropriate signal condition occurs allowing progression to the next state.

A state diagram shows how the various states of a system are interconnected and the
transition signals needed by the system to progress from one state to another.

You may use software tools such as Microsoft Visio to draw state machine diagrams.

EXAMPLE:

STATE MACHINE STRUCTURE

A state machine is a system where there are clearly identifiable states or conditions exist. A
typical example might be the following:

A process control system where there are several distinct states e.g. IDLE, RUN, STOP,
ALARM

such that the system can only find itself in one state at a time and the transition between
states can only occur dependent on being in the correct state and the occurrence of a
specific stimulus:

The state machine is often shown as a STATE DIAGRAM an example might be:

The system stays in the current state unless exposed to the correct stimulus (transition
signal) to move to another state.
20

A state machine structure can be implemented in a variety of coding styles, however, the
most frequent method is to get the code to generate a state variable in the following way
using a switch construction:

STATE OUTPUT

IDLE BUZZER = 0 (off) MOTOR=0(off)

RUN MOTOR = 1 (on) BUZZER=0(off)

ALARM MOTOR = 0(off) BUZZER = 1 (on)

STOP MOTOR = 0 (off) BUZZER=1(on)

// state.c a programme to show the use of a state machine in


structured design
#include <xc.h>
//CONFIGURATION FUSES =============================================
#pragma config WDTEN=OFF, FOSC=INTIO67,MCLRE=EXTMCLR,LVP=OFF
//==================================================================
#define START_KEY PORTBbits.RB0
#define STOP_KEY PORTBbits.RB2
#define RESET_KEY PORTBbits.RB3
#define ALARM_KEY PORTBbits.RB1
#define BUZZER LATC1
#define MOTOR LATC0
#define IDLE 1
#define RUN 2
#define ALARM 3
#define STOP 4
#define OFF 0
#define ON 1
unsigned char state;
void init(void); //function prototype

void init(void)
{
OSCCON=0b01010010; //sets for internal //oscillator at 4MHz
ANSELC=0x00;
TRISC=0x00;
PORTC=0x00;
ANSELB=0x00;//needed to make PORTB digital I/O
TRISB=0xFF;
state=IDLE;
}
21

void main (void)


{
init();
while(1)
{
switch(state)
{
case IDLE:
if(!START_KEY)
state=RUN;
else
state=IDLE;
BUZZER=OFF;
MOTOR=OFF;
break;
case RUN:
if(!ALARM_KEY)
state=ALARM;
else
if(!STOP_KEY)
state=STOP;
else
state=RUN;
BUZZER=OFF;
MOTOR=ON;
break;
case ALARM:
state=STOP;
BUZZER=ON;
MOTOR=OFF;
break;
case STOP:
if(!RESET_KEY)
state=IDLE;
else
state=STOP;
BUZZER=ON;
MOTOR=OFF;
break;
default:
state=IDLE;

}
}

}
The above system responds best to tasks which are not time critical i.e. each task needs to
be completely finished before the code is re-directed to the next state.
The change of state stimulus is set in each state and must be cleared immediately you enter
the next state.
By definition states exist one at a time there is no concurrent activity.
The change of state stimulus could be an interrupt interrupts can exist within each state.
The functionality of each state can be examined largely in isolation from the other sections of
the design.
22

EXAMPLE:

A process control system operates a pump to fill a tank. Pressing a START switch
commences the process. When the tank is filling a drain valve is closed. When the tank is
full, the pump switches off and the drain valve opens allowing the tank to empty. When the
tank is emptied, the process repeats.
23

This system can be described by a state diagram as shown below:

(You may use the Data Flow template from Microsoft Visio)

RESET

NOT EMPTY

IDLE EMPTY
PUMP OFF DRAIN ON
DRAIN OFF PUMP OFF

FULL

START

EMPTY

FILL
PUMP ON
DRAIN OFF

NOT FULL

TANK FILLING
SYSTEM
24

WHY USE A STATE DIAGRAM?

It allows you to visualise the operation of the system and check functionality prior to coding.
Can we convert this information to a suitable JSD and hence into suitable code?

TANK FILL SYSTEM

INITIALISE PROCESS

INITIALISE PORTS &


NEXT STATE = IDLE
INTERRUPT(S)

STATE = IDLE STATE = FILL STATE = EMPTY

PUMP DRAIN CHECK NEXT PUMP DRAIN CHECK NEXT PUMP DRAIN CHECK NEXT
OFF OFF STATE ON OFF STATE OFF ON STATE

START = 1 START = 0 FULL = 1 FULL = 0 EMPTY = 1 START = 1

NEXT STATE NEXT STATE NEXT STATE NEXT STATE NEXT STATE NEXT STATE
= FILL = IDLE = EMPTY = FILL = FILL = EMPTY

TANK FILL PROCESS

The above diagram allows direct coding to be made. The case/switch statement is often
used when coding state machine designs as in the previous example.
25

POINTER TERMINOLOGY

Pointers are used in embedded C programming mostly to access array data. This is
made easy since, as you will see later, the procedure to access the first element of an array
is to point to the name of the array.

Pointers are an important part of the C language - they hold the addresses of variables i.e.
the location of data NOT variable data itself.

You must declare a pointer variable to be used with the pointer this pointer variable holds
the data that is at the address of the pointer.

Pointer variables are declared in the same way as other variables, but with the character
(*) in front of the variable name.

The pointer points to (or holds the addresses of) a variable.

EXAMPLE

unsigned char *pnt;


This declaration allows a pointer pnt to point at a variable of type unsigned char. You have to
declare it before you can use it!

POINTERS MUST BE INITIALISED

pnt = &Count;

pnt is set to the address of a variable called Count


If

Count = 12
then

*pnt=12
26

CODE EXAMPLE

pnt = &Count; points to address of variable Count

*pnt=10; this will assign a value of 10 to Count

X=*pnt;

this will assign the contents of Count to a variable X i.e. 10

ARRAY POINTERS

In C language the name of an array is also a pointer to the array.

EXAMPLE:

unsigned int Total[10];

The name Total is a pointer to the array and holds the address of the first element of the
array

EXAMPLE:

unsigned int Total[10]; declares an array with 10 elements

Total[2]=4; this is a way of assigning a value to the third array element

The same can be done using pointer terminology:

*(Total+2)=4;

&Total[j] which points to the jth element of array Total can also be written as:

Total + j
27

EXAMPLE OF ARRAY POINTERS

P = &Z[2]; P points to array Z element 2

We can now clear elements 2 and 3 of array Z, as in the two examples that follow. The two
examples are identical except that in the first example pointer P holds the address of Z[3] at
the end of the statements, and it holds the address of Z[2] at the end of the second set of
statements:

*P = 0; Z[2] = 0

P = P + 1; P now points to element 3 of Z

*P = 0; Z[3] = 0

or

*P = 0; Z[2] = 0

*(P + 1) = 0; Z[3] = 0

A POINTER CAN BE ASSIGNED TO ANOTHER POINTER

unsigned int *i, *j; declare 2 pointers i and j

unsigned int Cnt, Tot; declare two variables Cnt and Tot

i = &Cnt; i points to Cnt

*i = 10; this makes Cnt = 10

j = i; copy pointer i to pointer j

Tot = *j; this makes Tot = 10


28

MORE EXAMPLE CODE

const unsigned char Message[]="Hello World!";


This type declaration of an array is useful as it places a string in permanent (usually flash)
memory not user RAM that is always limited in microcontrollers. We might want this
message to be sent to a connected terminal or LCD display module.

We can use a function like this to allow transmission:

void send_msg(const unsigned char *text)

while(*text)

write_data(*text++);

}
We would use a line of code to complete the transmission as follows:

send_msg(Message);
The name of the array is a pointer to the first array element.

A string array will always end with a zero character meaning in the above that the
write_data( ) function will repeatedly fetch the next array member until this zero
end of string marker is found. After each write_data( ) the array position is
incremented.

The ++ in the code (*text++) means that the pointer is incremented.


29

A REVIEW OF VARIABLES

GLOBAL VARIABLES

Placed above functions

Must be declared before being used

Accessible by any function

Disadvantage is that they take up permanent memory space and are accessible from
all functions

EXAMPLE OF GLOBAL VARIABLE DECLARATION

unsigned char x;

unsigned int i;

float x;
Can be initialized when declared e.g.

unsigned char y = 3;

LOCAL VARIABLES

Are usable only in the function in which they are declared

Must be first line of the function

Unless declared as static will not hold data when exiting the function

STATIC LOCAL VARIABLES

Uses the keyword static e.g.

static unsigned int x;


Static local variable retains data from one function call to the next
30

THE VOLATILE QUALIFIER FOR VARIABLES

Variables that may change state outside the background loop need the volatile
qualifier e.g. volatile unsigned char count;

This means any variable that can be altered during an interrupt service routine and
all PORT pins
31

LECTURE 4 STRUCTURED DESIGN AND MULTIPLE FILE PROJECTS

STRUCTURED DESIGN METHODS

WHY IS STRUCTURE IMPORTANT?

An embedded design, whether implemented using a microcontroller or re-configurable


hardware, implies a sequence of activities governed by the structure of a program listing (for
the microcontroller) or the design of a suitable state machine sequencer (for the re-
configurable device). We will consider the microcontroller embedded design.

If the functionality required is relatively trivial, then the number of sequential instructions (the
program) will be limited.

The father of the C++ language Bjarne Stroustrup suggested that a little program (say less
than 1000 lines) can be written in anything, anyhow! If you dont quit easy, youll make it
work, at the end.

THE PROBLEM LIES WITH LARGER PROGRAMS

If you are designing larger programs and you dont use techniques of good programming,
then new errors will emerge at the same rate as you fix old errors.

The reason is that every part of the program may depend on other parts, but these
dependencies are so complicated and non-intuitive that even the programmer who wrote
the program may not be able to follow them. When you change one part of the program you
cannot easily see all the implications for the rest of the program. This is a particularly
dangerous scenario in safety-critical designs.
32

MODULARITY

A number of attempts have been made to introduce OOP (Object Oriented Programming)
languages for embedded microcontroller applications (Dallas TINI & Parallax Javalin
devices can be programmed in Java) but, generally, embedded microcontrollers are not
suitably structured for such an approach. The default programming language is C and we
will focus our interest in structured design using the C language.

The idea of modularity is known in microprocessor assembly language programming. Each


module can be written as a separate sub-routine and called within the main body of the
program as many times as required.

The top down bottom up design procedure models a common sense approach to design.
Every project starts with an initial project brief which describes the project at a top system
level.

From this description, it is possible that sub-division into component parts or modules can
take place. A simple system might require only one such analysis into a lower level of
abstraction. A more complex system might require the modules to be further sub-divided.
33

THE IDEAL MODULE

Should have clearly identifiable purpose

Should be testable as stand-alone entities

Should have single entry and exit points and defined data input and output

Should be independent of other modules in fact they will have dependence and this
dependence must be understood

Once designed, the programmer should be able to treat them as black box entities
i.e. detailed knowledge of contents are not vital e.g. module to write to EEPROM
memory say

THE USE OF THE FLOW CHART

Describing a program using a flow chart is not ideal there is no restriction on how the flow
diagram symbols are connected together with branches allowing program re-direction from
one place to virtually anywhere. So, except for the simplest program we would not use a
single flow chart for documentation of the project.

We can, however, describe the program modules using a module flow chart.
34

The module flow chart must start and end with single START and EXIT terminator symbols
e.g.

TOP DOWN DECOMPOSITION

From the flow chart representation of module functionality, we can generate module code.
This does provide a way of describing the top level system but further decomposition will be
off-sheet. You have to be able to document what you have done in a manner which is easily
understood by another (modification at a later stage) or by yourself when, after a week, you
have completely forgotten why the program takes the form that it does.

EXAMPLE

A digital voltmeter could have the following functionality:

After power-up, the display is initialised e.g. set to zero. The machine then enters a
continuous measurement and display sequence. The input voltage is converted, given a
polarity, scaled then displayed. The description of code modules by flow diagram would be
straight forward i.e. a flow chart might describe a module for conversion of binary to BCD
say. The problem comes in trying to diagrammatically present the overall system.
35

An alternative structured design method called Jacksons Structured Design would give the
following diagram : ( The Design of Small-Scale Embedded Systems - Wilmhurst)

Once the design is decomposed, in the manner above, the code for each lower level can be
described by flow chart and/or written directly. The above shows how an initial, once only,
section of functionality is followed by a repeat forever section. JSD diagrams are read from
left to right and top to bottom.
36

The JSD method also allows for describing processes of selection e.g.

The above deals with the relatively trivial module of code associated with controlling a street
light. The O symbol identifies a selection procedure which results in either Switch On or
Switch Off.
37

FUNCTION PROTOTYPES AND MULTIPLE SOURCE CODE FILE PROJECTS

You may have noticed that, after pre-processor directives such as #include <xc.h>, you
listed the function prototypes of all functions which were to be called within the program.

Why did we do this?

The function prototype contains the function name along with data type of the function
argument(s) and data type of the returned parameter (if any) e.g.

void write_4bit_data(char);

In a single source code project you may have noticed that your program would compile
whether you inserted the prototypes or not, so what do they do? They give the compiler
advanced information about the structure of the function so that it will know how to deal with
it when it finds instances of it during compilation. In a single source code file, if a function A
calls another function B then, when listing the function code you will need to make sure
function B appears above function A or the compiler will generate an error.

If you list all the function prototypes you will not generate an error no matter what order you
list your function code modules.

As an example, the functions that might be used to operate on an LCD include delay_ms()
and write_4bit_data(). If we do not declare the function prototypes ahead of the function
code the following would NOT compile:

void write_4bit_data(char byte)


{
PORTD=(PORTD & 0xF0)|((byte>>4) & 0x0F) ;
EN=1;
delay_ms(1);
EN=0;
delay_ms(6);
PORTD=(PORTD & 0xF0)|(byte & 0x0F);
EN=1;
delay_ms(1);
EN=0;
delay_ms(6);
}
void delay_ms(unsigned int ms)
{
int i;
while(ms>0)
{
for(i=0; i<54; i++);
ms--;
}
}
38

However, if we had listed the delay_ms() function code above write_4bit_data() the code
would compile. By listing the function prototypes at the head of the source code before the
function code, the order of the functions is no longer important.

The function prototype gives the compiler information about the nature of the function i.e.
name and data types used which is needed to compile without error.

THE USE OF MULTIPLE SOURCE CODE FILES IN A PROJECT


You will often see examples of project coding which seem to have more than one source
code file and also have associated header files. Why do we need to split up our code into
multiple source code files?

When we have designed a project we have, until now, always used one source code file i.e.
all the program detail was contained in one file e.g. a program source code file might contain
all the functionality to initialise ports, RS232 serial transmission, analogue to digital
conversion and an LCD display.

RE-USE
As an example, we have previously used LCD functions to allow bytes of data to be entered
into the display as data-to-display or as commands. An LCD display is a frequent component
of many projects and it makes sense that, when the code associated with driving it has been
developed and debugged, it could be re-used on different designs. Therefore, if we
constructed a source code file for the LCD code we could include it in projects and use the
software linker to integrate it with other modules of code.

This introduces the concept of custom libraries of functions.

INTEGRATION OF CODE FROM MULTIPLE AUTHORS

In a large project, it might make sense to employ more than one design engineer to generate
code. The use of a multiple source code file system allows each engineer to design and test
code which can subsequently be integrated into a larger system.
39

EXAMPLE refers to code suitable for 18F25K22 and PICAXE Target Board using Version
1 Plug In Board

The source code in a project could be split into two source code files (or more) e.g. main.c [
containing the main() function it is convention to name the source code file containing the
main function as main.c ] and LCD.c [ containing the LCD functions ]. In this example we will
use the __delay_ms() function provided by the xc8 compiler. NOTE: This function has an
upper limit just below 200ms when used for 18 series devices.

Each source code file other than main.c will have an associated header file e.g. LCD.h for
LCD.c source code file.

HEADER FILES

We have already seen the use of standard header files included in projects e.g.

#include <xc.h>

A header file usually contains all or some of the following:

1. Function prototypes of functions called in the associated .c source file


2. Definitions
3. Variable declarations or definitions
40

To generate a header file suitable for the source code LCD.c we would need the following:

LCD.h

#define _XTAL_FREQ 4000000


#define RS LATB0
#define EN LATB1
#define LCD_TRIS TRISB
#define LCD_PORT PORTB

void write_4bit_data(char);
void write_8bit_data(char);
void init_display(void);
void send_msg(const unsigned char*);
void clear_display(void);
void set_address_line1(unsigned char);
void set_address_line2(unsigned char);
void write_command(unsigned char);

void write_data(unsigned char);

In the above, we have definitions followed by function prototypes.

NOTE:

1. The output from PORTB Bit 0 is called LATB0 with LAT being used (short for
LATCH) for all port pins when configured as outputs.
2. We defined the crystal frequency here since the delay function __delay_ms() is used
within the LCD.c source file.
41

The source code file LCD.c (comments omitted) would be as follows:

We include LCD.h since it contains function prototypes and definitions referred to in LCD.c
and xc.h since it defines non-C terms specific to the microcontroller such as TRISB.
42

IMPORTANT RULE

The source code file e.g. LCD.c above MUST include all the header files containing function
prototypes of functions and definitions etc. which are used in the code i.e. LCD.h and xc.h in
this case.

HOW TO ADJUST THE MPLAB ENVIRONMENT FOR MULTIPLE FILES


Make sure you Add to Program Files all the source code modules and all the header files.
They will appear on the project tree on the left hand side of the IDE.

USING GLOBAL VARIABLES IN MULTIPLE FILES

If a variable is declared as a global i.e. declaration is in (usually) the main.c file outside any
function, it can be accessed in another source file simply by defining it in that source file
using the keyword extern.
43

EXAMPLE:

A variable is declared as a global e.g.

int count;

(in main.c)

We wish to use and modify this variable in a second source code file and would need to
define it in the second source file as follows:

extern int count;

THE USE OF INSTEAD OF < >

# include files we have created and placed in the project folder are bracketed whilst those
in the compiler directory i.e. xc8 for the xc8 compiler are s
44

LECTURE 5 INTERRUPTS AND I2C

INTERRUPTS

The microcontroller operates in a sequential manner, interrogating each instruction then


executing it. The only change in the line-by-line sequence is when a branch/jump instruction
is encountered at which point the program will move to a new section of sequential code
according to the branch decision. This system is fine if events are to be managed in a
sequential manner.

Polling is a term used to describe the regular interrogation of signals from a defined input
pin. Most programs will endlessly loop, and, provided the pin is checked at least once in the
performance of the loop, a change of state can cause a required redirection of the program
to service the input stimulus. In this way, external signals can influence the functionality of
the program. The disadvantage of polling is that of time should the stimulus be transient
then it may have disappeared before the program has stepped to the polling instruction.
There are also events which might demand instant response and for which the delay in
response due to a looping polling strategy are unacceptable.

An interrupt is an event, external or internal to the microcontroller, which when it occurs


causes the program to service a specific related interrupt service routine immediately
although some care needs to be taken in the definition of immediately.

REAL TIME

Systems which have a strong dependence on time are frequently said to operate in real
time. In fact, all microprocessor systems will have some element of dependency on timely
completion of tasks even processing a data base where output data is required weekly
suggests a time implication. One definition of a real time system has been given as:

A system operating in real time must be able to provide the correct results at the required
time deadlines

There is no implicit requirement for high speed operation although this will be advantageous
in satisfying the demands of such a system.
45

Programming for real time applications is characterised as follows:

Ability to respond at appropriate speed to external events occurring at unpredictable


times
Ability to measure time accurately hence initiate time-based activity
In complex systems the ability to distinguish between needs which are time critical
and those which are not and to make a response accordingly

Ref: Design of Small Scale Embedded Systems - Wilmhurst

INTERRUPT STRUCTURES

All microcontrollers will offer an interrupt structure. In the 16F887, this will allow for external
interrupts from the following sources:

RB0 - when configured, a change on this PORT B pin state will cause an interrupt INT

The 18F25K22 has three external interrupt pins.

Change on RB7-RB4 when configured, any change in state of these 4 pins will cause an
interrupt RBINT useful for hex key pad entry say

Other internal interrupt sources are TMR0, TMR1, TMR2, A/D etc..

The PIC 18F series has a simple high and low priority structure. In this system, an interrupt
that is within the high priority group will interrupt an interrupt service routine for an interrupt in
the lower priority group. This priority scheme can be disabled and the interrupt structure then
reverts to that of the 16F where priority is according to listing for test in the interrupt service
routine.
46

LATENCY & PRIORITY

The time taken from the point at which the interrupt stimulus occurs to the point at which the
interrupt service routine code execution starts is called the latency of the interrupt. Program
flow must be re-directed and registers saved (the minimum being the program counter) this
all takes time. Latency is usually calculated as the worst case scenario.

The interrupt system of the 16F886 is not directly prioritised this means that when two
interrupts occur simultaneously they are equally weighted in significance. However, the
system will be forced to an interrupt vector address at which the type of interrupt is checked
by inspecting the state of the individual interrupt flags to see which has been set. By
checking flags in sequence by IF statement, the interrupt sources can be effectively
prioritised i.e. if the first IF statement examines the external interrupt flag INTF it has first
priority if a subsequent IF statement inspects a second interrupt flag.

Some microcontrollers are more sophisticated, in that they allow interrupt prioritisation at
design time. The 18F series microcontrollers allow the user to select high or low priority for
individual interrupts and a high priority interrupt event can switch activity from an executing
low priority interrupt service routine.

The 16F/18F series does not support the concept of nested interrupts i.e. interrupts being
actioned whilst execution is within the interrupt service routine of other interrupts.
47

LATENCIES WITH MULTIPLE ACTIVE INTERRUPTS

It might, at first look like a system with multiple and prioritised interrupt facilities is a good
thing however, in complex systems it is essential that the designer is aware of the worst
case latency for the interrupt under consideration for example, a badly conceived system
may not reliably service a lower priority interrupt in a timely manner with demand from higher
priority interrupts being large.

In order to function well, an interrupt should clearly occur when necessary and cause no
disruption to the system other than implementing the desired functionality of the interrupt
service routine.

Context Saving is a term used to describe the saving of all data and register contents which
define the current state of the processor. On completion of the interrupt service routine, the
saved data is restored and normal system function continues.

Some processors such as the 16F886 and 80C552 save the program counter only in many
cases this may not be enough. For example, if the interrupt occurs during a multi- instruction
calculation and the interrupt service routine alters working register (accumulator) or status
register then a meaningless calculation will result.

Context saving adds to the latency overhead but cannot be ignored.

Even with suitable context saving, there will be times when interrupts cannot be tolerated
and may need to be masked i.e. disabled:

The system is not fully initialised


A critical time-sensitive task is being performed e.g. a delay loop or an output pulse
timed in software
When certain PORT outputs are being changed near simultaneously in a sequence
of instructions
When a variable, which is accessed by the interrupt service routine, is being
calculated by the main programme as a sequence of instructions
48

CONCLUSIONS

Ref: Design of Small Scale Embedded Systems - Wilmhurst

Complications increase when multiple interrupts are used use interrupts only where
essential and minimise the number of sources
When executing an ISR the processor is committed only to that activity other
interrupts and activities are blocked. ISRs should be of minimum length.
Understand the interdependence between interrupt routines and the main
programme hence identify all critical areas, mask interrupts as appropriate and
ensure context saving takes place.
Estimate latencies for each interrupt source and ensure that timing requirements
remain satisfied.

THE INTERRUPT SYSTEM OF THE 18F25K22

The 18F25K22 is the device used for this course. A Data Sheet is in the main RESOURCE
folder for the course and you should, at all times, refer to this document when designing
programs.

Whilst the 18F series supports priority (high and low) interrupts we will use it in the default
state which follows a similar concept to that used for the 16F series. Differences do occur
and you should refer to the Data Sheet e.g. TMR0 Section 11.0 and also the xc8 Compiler
Manual.

The following is an extract from the Data Sheet showing the hardware for TMR0:
49

The register that controls the use of TMR0 is called T0CON and has settings for the various
signals given in the above diagram. If you wish to use this timer as an interrupt source you
will need to enable the interrupt and the global interrupt and make the suitable settings of
T0CON. The names used for these signals by the xc8 compiler can be found in the include
file for the p18f25K22 this file is provided in the main RESOURCE folder.

To demonstrate the similarity between older mid-range devices and the 18F25K22 a small
project called TIMER has been provided in the LAB 5 RESOURCE folder. It has been
designed for use with the STUDENT HARDWARE PLUGIN BOARD EMBEDDED 2013
Design File and the course hardware and will result in the YELLOW LED on the target board
being flashed at a rate of 1Hz.

An interrupt is generated at approximately 1ms and used as the time-base for generating the
change of state of the LED (RC3 output) every 500ms. See Data Sheet Section 11.0.
50

SETTING UP THE INTERRUPT

Before the TMR0 timer interrupt can be used it must be set up and then enabled. The
following code is found in the example TIMER project:

void init_int(void)
{
T0PS0=1;
T0PS1=0;
T0PS2=0; // set PS to divide by 4
PSA=0; //enable PS
T0CS=0;//use as timer
T08BIT=1; //make TMR0 an 8 bit timer
TMR0ON=1;//turn on TMR0
T0IE=1;//enable the interrupt
T0IF=0;//clear the flag
GIE=1;//enable global interrupts
}

Make sure you fully understand all the settings again refer to Data Sheet 18F25K22
Section 11.0 TIMER0.

The syntax used for the interrupt service routine is identical to that used with the HITECH C
compiler for the 16F886 microcontroller i.e.

void interrupt tmr0(void)


{
T0IF=0;//reset the flag
count++;
if(count==488)
{
LATC3=~LATC3;
count=0;
}
}
51

I2C

HISTORY

The I2C system was developed by Philips Semiconductor as a simple two wire interface to
enable connection of multiple devices to a single bus structure. The main advantage of such
a system is that I/O resource for the microcontroller is conserved i.e. data bytes can be
transferred using only two I/O pins. In addition, the speed of data transmission is significantly
faster than the RS232 protocol.

Devices are connected together as master or slave The master is the device which
initiates the data transfer. Usually, in embedded systems, the master is the microcontroller
and the peripheral or peripherals act as slaves.

Each device is identified by a unique address.

The address will be usually 7 bits in length and transfer of data may be in one of two modes
i.e. standard at a rate of 100kbs or fast at 400kbps. A further High Speed Mode was
released in 1998 allowing 3.4Mbs transmissions.

DEFINITIONS

The following terms may be defined:

Transmitter the device which sends data to the bus.


Receiver the device which receives data from the bus.
Master the device which initiates data transfer, generates the clock signals and
terminates the transfer.
Slave the device addressed by the master.

Typical peripheral devices which may have an in-built I2C capability include real time clock
chips, EEPROM, displays, ADC, DAC etc
52

A typical connection arrangement might be as follows:

Note: The lines are pulled up to 5V through 4k7 resistors so that each line must be driven to
0

In this case, the microcontroller shares the 2 wire bus with a RTC DS1307 and other
peripherals.

Data transfer may be initiated only when the bus is not busy.

During data transfer, the data line must remain stable whenever the clock line is
HIGH. Changes in the data line while the clock line is high will be interpreted as
control signals.

Accordingly, the following bus conditions have been defined:

BUS NOT BUSY:

Both data and clock lines remain HIGH.


53

START DATA TRANSFER:

A change in the state of the data line, from HIGH to LOW, while the clock is HIGH, defines a
START condition.

STOP DATA TRANSFER:

A change in the state of the data line, from LOW to HIGH, while the clock line is HIGH,
defines the STOP condition.

DATA VALID:

The state of the data line represents valid data when, after a START condition, the data line

is stable for the duration of the HIGH period of the clock signal.

The data on the line must be changed during the LOW period of the clock signal.

There is one clock pulse per bit of data.

Each data transfer is initiated with a START condition and terminated with a STOP condition.

The number of data bytes transferred between START and STOP conditions is not limited,
and is determined by the master device. The information is transferred byte-wise and each
receiver acknowledges with a ninth bit.

Within the 2-wire bus specifications a regular mode (100kHz clock rate) and a fast mode
(400kHz clock rate) are defined. The DS1307 operates in the regular mode (100kHz) only.
54

ACKNOWLEDGE:

Each receiving device, when addressed, is obliged to generate an acknowledge after the
reception of each byte. The master device must generate an extra clock pulse which is
associated with this acknowledge bit.

A device that acknowledges must pull down the SDA line during the acknowledge clock
pulse in such away that the SDA line is stable LOW during the HIGH period of the
acknowledge-related clock pulse.

NOT ACKNOWLEDGE:

A master must signal an end of data to the slave by not generating an acknowledge bit on
the last byte that has been clocked out of the slave.
55

EXAMPLES:

I2C was introduced by Philips Semiconductor and has been accepted as an industry
standard for synchronous serial connection. It is generally well documented and most
microcontrollers will have hardware which simplifies the coding needed.
56

CODE

void i2c_Init(void)
{
OSCCON=0b01010010; //sets for internal oscillator at 4MHz
ANSELC=0x00;
TRISC3=1; //set SCL and SDA as inputs to start
TRISC4=1;
SSP1CON1=0x28; //enable serial in MASTER mode I2C
SSP1CON2=0x00; //clear all bits to start
SSP1ADD=10;//value to create a 100kHz baud rate with 4MHz FOSC
SMP1=1; //disable slew rate control for 100KHz
SSP1IF=0; //clear interrupt flag
BCL1IF=0; //clear bus collision flag
}

void i2c_WaitForIdle(void)
{
while((SSP1CON2 & 0x1F)|RW1) {}; //wait for no bus activity
}

void i2c_Start(void)
{
i2c_WaitForIdle();
SEN1=1;
}
void i2c_RepStart(void)
{
i2c_WaitForIdle();
RSEN1=1;
}
void i2c_Stop(void)
{
i2c_WaitForIdle();
PEN1=1;
}
57

int i2c_Read(unsigned char ack)


{
unsigned char i2c_ReadData; //declare a variable
i2c_WaitForIdle();
RCEN1=1; //set for i2c reception
i2c_WaitForIdle();
i2c_ReadData = SSP1BUF;
i2c_WaitForIdle();
if(ack)
ACKDT1=0; //either send acknowlege
else
ACKDT1=1; //or send not acknowledge
ACKEN1=1; //now allow this bit to be sent

return (i2c_ReadData); //return what is in the buffer


}
unsigned char i2c_Write (unsigned char i2c_WriteData)
{
i2c_WaitForIdle();
SSP1BUF=i2c_WriteData;
return(! ACKSTAT1);
}

The above represent suitable library functions for the 18F25K22 microcontroller using I2C.

void i2c_Init(void)

This function is used to set the clock frequency SCL, clear flags and set data direction for the
2-wire bus.

void i2c_WaitForIdle(void)

This function is used to allow no transaction to be started whilst the bus is busy this is
necessary to avoid a bus conflict.
58

void i2c_Start(void)

This function generates the START signal.

void i2c_RepStart(void)

This function is the REPEAT START used during a read sequence in place of a STOP so
that the device address can be written and then, after this function call, the same device can
be read from finally ending the sequence with a STOP see the code example for this.

void i2c_Stop(void)

This is the STOP sequence used to terminate a transaction.

int i2c_Read(unsigned char ack)

This function is used to read data from a connected SLAVE.


59

CODING EXAMPLE USING THESE LIBRARY FUNCTIONS

address=30; //choose an address location


data=0x55; //choose data to write and read from EEPROM
i2c_Init();
i2c_Start();
i2c_Write(0xA0);
i2c_Write(address);
i2c_Write(data);
i2c_Stop();
__delay_ms(11); //wait for write to complete

//now read back the data


i2c_Start();
i2c_Write(0xA0);
i2c_Write(address);
i2c_RepStart();
i2c_Write(0xA1);
data=i2c_Read(0);
i2c_Stop();

The above code is used to write a byte of data (0x55) to an I2C EEPROM device address
30d. After initialisation, a START is sent followed by the hardware address of the EEPROM
device (0xA0). The next transmitted byte is the address within the EEPROM and the
following transmitted byte is the data intended to be written to that address. A STOP
concludes the transaction.

Reading the data follows a similar pattern. The hardware address of the EEPROM is sent
followed by the byte address in the EEPROM that data is to be retrieved from. A REPEAT
START signal is sent followed by the EEPROM address but this time the trailing bit is a 1
to indicate a read transaction i.e. (0xA1 instead of 0xA0). Data is now transmitted from the
EEPROM SLAVE device and stored in variable data. The complete transaction is
terminated by a STOP signal.
60

LECTURE 6 SPI

SPI

Various alternative serial peripheral communication protocols exist. The most frequently
seen will be SPI or serial peripheral interface. This uses master to slave communication
and again, the master will generate clock pulses. The difference between I2C and SPI is that
an SPI device does not need to be addressed by a serial address byte but simply by forcing
its chip select line low. The diagram below shows a simple SPI slave device. SPI is
generally a much faster interface with clocking speed of up to 30Mbps.

DEFINITIONS

MASTER Device that controls data transfer by generating clock pulses and selecting
SLAVES by CS (chip select) signal.

SLAVE any device connected to the bus and being enabled by a CS (chip select) signal
from the MASTER.

The SPI device has two data lines SDO for data output and SDI for data input. Bytes of data
are exchanged under the control of the synchronous clock SCL. The procedure would be
enabled by the MASTER (microcontroller) forcing CS low.
61

The MASTER device (the microcontroller) will initiate data transfer in the following manner:

THE SPI BUS

An SPI interface is shown above. The Master must first be configured as a MASTER and the
clock speed set. The MASTER is responsible for generating synchronous clock pulses.

The MASTER and SLAVE must be working in the same MODE.

The MODE is one of 4 possible states defining the clock idle condition i.e. 0 or 1 and the
clock edge on which data is clocked i.e. active to idle edge or idle to active edge. Data is
read or valid on the alternate clock edge. For example, if data is output to the bus on the
rising clock edge with the idle state 0, then data is read on the falling edge.

A typical maximum data rate for a microcontroller SPI interface might be in the order of
10Mbs much faster than RS232 exchanges.
62

SPI MASTER WRITE DATA TO SLAVE

A data byte must be loaded into the buffer register SSPBUF. As soon as this is done, SPI
hardware will clock the data out of the SDO pin MSB first.

At the same time as data bits are being clocked out of SDO, whatever was in the SSPSR of
the SLAVE will be clocked into the MASTER SSPSR so that, when the full 8 bits have exited
the MASTER, 8 bits from the SLAVE have been received into the SSPSR. At this point the
contents of the MASTER SSPSR is transferred to the SSPBUF the SSPIF flag for the
MASTER is set and the buffer full flag BF is set.

Any attempt to write data to the SSPBUF whilst data is being transmitted/received in the
SSPSR will be ignored.

SPI SLAVE RECEIVES DATA

The SLAVE must wait on clocks from the MASTER. After 8 clocks, the SSPSR of the SLAVE
is full with the incoming byte and this byte is automatically transferred to the SLAVE
SSPBUF setting both the SSPIF and BF flags. The BF flag is cleared by reading the
SSPBUF. A procedure might be to read the SSPBUF so clearing any data and, in the
process clearing the buffer full BF flag, then waiting for the BF flag to be set indicating data
has arrived into the SSPBUF via the SSPSR. This can then be read directly from the
SSPBUF.

SPI SLAVE TRANSMITS DATA

After reading data incoming to the SLAVE i.e. after BF=1 reading the SSPBUF, a byte of
data can be loaded into the SSPBUF, automatically transferred to the SSPSR of the SLAVE
so that, on receiving a further 8 clock pulses from the MASTER, this byte of data will have
been sent MSB first to the MASTER.
63

SPI MULTIPLE SPI DEVICES SHARING THE SPI BUS

The SPI bus consists of SDI, SDO, SCK as well as a SLAVE SELECT SS. If more than one
SPI SLAVE device is to be used, the SS pin of the SLAVE to be used at any one time will be
activated. With SS deactivated, the corresponding SLAVE device is isolated from the bus.

A TYPICAL SPI CONNECTION

This shows an SPI EEPROM device connected as a SLAVE to the 18F25K22 MASTER.
Unlike the I2C bus, pull-up resistors are not required for the bus lines.
64

LECTURE 7 SOFTWARE SAFETY

There are two main reasons for software failure:

1. The software does not meet the desired functionality i.e. what it should or
should not do has not been thoroughly investigated in the design phase.
2. Errors in implementation

Omissions in functionality are often due to the designer missing key features in the
development phase even when the development process is well structured. There may be a
failure to anticipate all the user scenarios. Such omissions can be due to pressure by
management to get a product to the market place on time and within a budget.

VALIDATION TESTING

The term validation testing is used to represent the last formal methods used to
exercise/test software prior to product release. It may not be possible to exercise the
software with sufficient depth to observe defects which might occur in all user scenarios.

Well organised companies will have an extensive testing plan the IEEE describes a
suitable standard

i.e. IEEE Std 1012-1986. In particular, so-called regression testing should be included in
any plan if major modifications to the software have been made to ensure that all previous
functionality - theoretically unaltered by the modifications - is still maintained.

The major element of all quality systems is traceability if a defect has been inadvertently
propagated, how certain is the company that it can isolate and recall the appropriate product.

Software modifications should include a Version Number and the full details of what the
modification is and how it was tested would need to be documented.

Whilst there is a fast moving trend in consumer goods for rapid obsolescence, embedded
designs may last a long time e.g. a chemical processing plant or metal foundry might have
systems working with embedded software which is 15 or more years old. The original
designers will have certainly moved on from the company, and, unless documentation is
complete, a system will be more easily scrapped and redesigned than repaired.
65

CYCLE TESTING

A last line of defence in product testing is so-called cycle testing. This takes the product and
continuously runs the software whilst submitting the product to the greatest possible
combinations and repetitions of user activities.

The process can be automated with the automatic test procedure generating without
intervention test input stimuli and monitoring output conditions for undesirable errors.

CODING ERRORS

The second reason for software failure is so-called implementation errors or code bugs.

Design and code reviews may only detect the most obvious errors. The problem with
reviews is the inherent complexity of software and the depth of familiarity the reviewer must
attain to have the chance of meaningful analysis.

The worst problems arise from poor handling of data and other resources by competing
processes.

A process may be in the middle of modifying data when it is interrupted by a higher priority
process that then uses the partially modified and hence unreliable data.

Such errors may not cause the system to crash (failing completely which may be a fail-safe
condition) but to continue working but in an unpredictable or non-deterministic manner.

REENTRANCY

REENTRANCY is the ability of a software module to be safely interrupted and called by an


interrupting process.

The problem of non re-entrancy manifests itself in the use of libraries e.g. floating point math
etc. which are not in themselves re-entrant.
66

CRITICAL CODE

The system may have sections of code which just must not be interrupted these are called
critical code sections. An example of critical code is best represented by an example:

A chemical plant system consists of a tank, pump and valve to control flow and storage of
fluid as shown below:

PUMP

TANK
VALVE

During a normal tank drain process, the pump is turned off, the valve is opened and a status
variable is set to indicate DRAINING.

A problem occurs if, after opening the valve, an interrupting process needs to disable the
system. The status variable is set to indicate DISABLED and the valve is closed.

The original DRAIN process is now allowed to continue finishing execution. The status
variable is set to DRAIN but the valve is closed so the process can never complete and the
system will hang.

In this case, the drain process is a critical code section. The problem comes from ignoring
the ability of an important system parameter (in this case a drain valve) to be compromised
by an interrupting process.
67

THE SAFE SYSTEM

A safe system philosophy is needed for such equipment as transportation, medical systems
and atomic energy

As it is recognised that software cannot be 100% fault free assured - in safety-critical


systems a philosophy of safe system rather than safe component must be employed.

The software can be considered as a system component. This will be the basis of all design
philosophy, and, as will be detailed subsequently, the concept of redundancy will be
universally employed in safety-critical equipment such as medical devices and other safety-
critical areas of design.

Other industries have exhaustively examined the philosophy of the safe system including
such areas as transportation including automotive systems and atomic energy.

A question which might be asked

If the system is safe from the effects of component failure, why should we be
preoccupied with the design of such components - why not just let the system cope
with the component failure by nature of its redundant design?

An answer would be that, whilst the component will be expected to potentially fail, it must do
so in a predictable manner the recognition of the failure being a fundamental part of the
system safety concept. Component failure can be ignored only if it is exhaustively
demonstrated that such failure cannot influence the performance of any other component in
the system an unpredictable manner of failure may not have been anticipated.
68

THE SINGLE-FAULT HAZARD

The safety philosophy associated with the functionality of, for example, medical equipment
has evolved over the last twenty years and includes one central theme -

No single fault shall cause a human hazard

Obviously, faults will occur but, provided they are recognised and cause the equipment to
enter the safe state, they are permissible. In addition, any fault which is not directly
hazardous in itself, but which might stop the entry into the safe state after a subsequent
potentially hazardous fault has occurred must not be hidden but recognised before each and
every use of the device or within a small enough time period that makes the likelihood of
subsequent hazardous fault occurrence negligible.
69

FIGURE 1 shows a single fault hazard philosophy, developed by the German TUV
organisation, which has formed the basis of design for medical device developers. In the
diagram, T0 - the fault tolerance time is a concept which allows for transitory fault
condition. If the fault causes a hazard after T0 the system is unsafe. If this fault is detected
before a second fault is expected to occur then the system is a safe system. If, however, a
second fault occurs before detection of the first, and if this causes a hazard, then the system
is deemed unsafe.

FIGURE 1: FAIL-SAFE EQUIPMENT


70

RISK ANALYSIS

Design of all safety-critical equipment would require a detailed RISK ANALYSIS. If the
likelihood of a fault occurring is extremely remote e.g. 1 in 1 million operational uses of the
equipment it may be discounted.

If a fault is unlikely i.e. very low probability but the occurrence would cause a hazard it must
be addressed by some form of fault mitigation i.e. the fault must be capable of detection
and some system must be capable of rendering the equipment safe.

As part of the design process, all aspects of the equipment design and expected use are to
be considered and a table made of all recognized hazard scenarios. A second process is
then conducted to present mitigation for all recognized faults.

SAFETY SYSTEMS REDUNDANCY

THE MONITOR ACTUATOR PRINCIPLE

THE MEDICAL SYRINGE PUMP EXAMPLE

A Syringe Pump is an apparatus used to send controlled flows of high potency drug to a
patient in a hospital environment. It consists of a user keypad to set the desired rate, a motor
gearbox to drive a linear actuator and some form of alarm system that can indicate fault
conditions.
71

FIGURE 2: A FUNCTIONAL APPARATUS THAT IS NOT SAFE

The above diagram shows what is needed functionally for the device to perform the required
activity why is this unsafe?
72

A Safe System based on Monitor-Actuator Philosophy

FIGURE 3: SYSTEM MITIGATION BY REDUNDANCY EXECUTION DIVERSITY

Redundancy is used to ensure safe operation

What assumptions are made in the above design?


73

FIGURE 4: MONITOR ACTUATOR BLOCK SCHEMATIC

In the above system the GUARD channel duplicates the SYSTEM channel such that if
GUARD and SYSTEM are not in synchronism, the COMPARE block will operate to inhibit
the SYSTEM and place it into a safe state. The MONITOR is GUARD whilst the
ACTUATOR is SYSTEM in the diagram.
74

LECTURE 8 WIRELESS EMBEDDED SYSTEMS

There are various possibilities using wireless technology to make an embedded system
mobile.

Simple digital transmitter and receiver without complex protocol using typical licence-free
430MHz UHF and 900MHz.

ISM FREQUENCY BANDS

These frequency bands i.e. 430MHz and 900MHz are part of the ISM (Industrial, Scientific
and Medical) frequency band allocation. The industrial, scientific and medical (ISM) radio
bands are radio bands (portions of the radio spectrum) reserved internationally for the use
of radio frequency (RF) energy for industrial, scientific and medical purposes other than
communications. They are mainly license-free. Examples of applications in these bands
include radio-frequency process heating, microwave ovens, and medical diathermy
(electrically introduced heating) machines. The powerful emissions of these devices can
create electromagnetic interference and disrupt radio communication using the same
frequency, so these devices were limited to certain bands of frequencies. In general,
communications equipment operating in these bands must tolerate any interference
generated by ISM equipment, and users have no regulatory protection from ISM device
operation.

The advantage of using these frequencies is the ability to produce products that do not
require radio frequency licensing. A disadvantage is that these frequencies are available to
many and mutual interference cannot be assumed.

ISM frequencies are available at higher frequencies such as the popular 2.4GHz band.

RANGE

In any remote control system, a primary consideration is operating range. The 430MHz,
900MHz and 2.4GHz bands popular in embedded wireless connectivity are largely line-of-
sight meaning that the receiving system (node) must be visible to the transmitting device
(node). However, other factors influence range such as radio reflection where a receiving
node receives a signal both directly but also from a reflection of the transmitting signal fro
intervening object such as the ground. In this case the signals may arrive at the receiver
after slightly differing transmission times and cause mutual interference limiting the range.

Objects and material such as walls, vehicles and buildings may obscure direct transmission
and greatly reduce range.

The choice of transmission frequency will also limit range such that the higher the frequency
the lower the range.
75

THE RANGE EQUATION

The Friis transmission equation is used in telecommunications engineering, and gives the
power received by one antenna under idealized conditions given another antenna some
distance away transmitting a known amount of power. The formula was derived in 1945 by
Danish-American radio engineer Harald T. Friis at Bell Labs.

In its simplest form, the Friis transmission equation is as follows. Given two antennas, the
ratio of power available at the input of the receiving antenna, , to output power to the
transmitting antenna, , is given by

(1)

where and are the antenna gains (with respect to an isotropic radiator) of the
transmitting and receiving antennas respectively, is the wavelength, and is the distance
between the antennas. The inverse of the factor in parentheses is the so-called free-space
path loss. To use the equation as written, the antenna gain may not be in units of decibels,
and the wavelength and distance units must be the same. If the gain has units of dB, the
equation is slightly modified to:

(2)

(Gain has units of dB, and power has units of dBm)

DEFINITIONS

ANTENNA GAIN

ANTENNA GAIN is usually defined as the ratio of the power produced by the antenna from a
far-field source on the antenna's beam axis to the power produced by a hypothetical lossless
isotropic antenna, which is equally sensitive to signals from all directions. Usually this ratio is
expressed in decibels, and these units are referred to as "decibels-isotropic" (dBi).

ISOTROPIC RADIATOR

An ISOTROPIC RADIATOR is a theoretical point source of electromagnetic or sound waves


which radiates the same intensity of radiation in all directions. It has no preferred direction of
radiation. It radiates uniformly in all directions over a sphere centred on the source.
76

dBm

dBm (sometimes dBmW) is an abbreviation for the power ratio in decibels (dB) of the
measured power referenced to one milliwatt (mW). It is used in radio, microwave and fiber
optic networks as a convenient measure of absolute power because of its capability to
express both very large and very small values in a short form.

A TYPICAL RANGE CALCULATION

The Friis Equation is slightly modified to account for environmental conditions as follows:

(3)

Friis had originally suggested that the received signal was proportional to (1/d) 2 from
Equation 2 and that this accurately characterises wave behaviour in an environment absent
of anything which alters the waves travel. With n=2 it means that, in this free space
environment that the strength of the received radio wave is inversely proportional to the
square of the distance d between transmitter and receiver. As such, doubling the distance
separating transmitter and receiver will reduce the received signal strength to 25% or or
6dB.

In a real-world environment, RF waves are altered (bent, diffracted, reflected, attenuated,


absorbed etc.) and a better approximation is to alter the exponent n to reflect the
environment. Empirical testing has given Table 1:
77

RANGE CALCULATION

Re-arranging Equation (3) gives:

PR (dB) = 20 log (/4) + 10n log (1/d) + PT + GT + GR (4)

A TYPICAL CALCULATION

Note: PR is referred to as the receiver sensitivity which is that signal power required at the
input to the receiver to allow for reliable operation of the digital link.

Given:

PT = 13dBm

PR = -120 dBm

GT = -15 dB

GR = 3 dB

Frequency = 315MHz so = c/f = (3x108)/(315x106) = 0.69m

(c= speed of transmission of electromagnetic waves in ms -1)

n = 3.5

Substituting these values in Equation (4) gives:

-120 = 20 log(0.0549) + 10x3.5 log(1/d) + 13 -15 +3

-95.8 = 35 log(1/d)

log(1/d) = -2.737

log(d) = 2.737

d=546m
78

USE OF 430MHz and 900MHz SIMPLE DIGITAL TRANSCEIVERS

430MHz and 900Mhz are frequently used for low cost digital wireless transceivers. They are
often without any signal conditioning and provide no error detection or correction.

One of the problems in using these devices is that the effective range can be greatly
reduced as the digital transmission rate increases e.g. range at 1200 baud may be very
much greater than at 9600 baud say. As the signalling rate increases, the signal to noise
ration decreases and errors will occur in reception.

A second problem is with an unbalanced digital data stream. In order to reliably detect the
difference between a transmitted 1 and 0 a detection threshold must be set by the
receiver. This threshold is determined by the average DC signalling value. If the system is
transmitting as many 1s as 0s the average will be half way between that DC value
corresponding to a 1 and that corresponding to a 0. If the data stream becomes
unbalanced with more 0s than 1s for example, the threshold will fall such that the threshold
for detecting a 1 will be much closer to the threshold for detecting a 0 and errors will occur.

This problem can be overcome by conditioning the digital data into a transmission protocol
called Manchester Encoding.

A TYPICAL 430MHz Digital Transceiver


79

MANCHESTER ENCODING

Differential Manchester encoding, also called bi-phase mark code (BMC) or FM1, is a line
code in which data and clock signals are combined to form a single 2-level self-
synchronizing data stream. It is a differential encoding, using the presence or absence of
transitions to indicate logical value. It is not necessary to know the polarity of the sent signal
since the information is not kept in the actual values of the voltage but in their change: in
other words it does not matter whether a logical 1 or 0 is received, but only whether the
polarity is the same or different from the previous value; this makes synchronization easier.

The technology defined by the ZigBee specification is intended to be simpler and less
expensive than other WPANs, such as Bluetooth. ZigBee is targeted at radio-frequency (RF)
applications that require a low data rate, long battery life, and secure networking.

ZigBee is a low-cost, low-power, wireless mesh networking proprietary standard. The low
cost allows the technology to be widely deployed in wireless control and monitoring
applications, the low power-usage allows longer life with smaller batteries, and the mesh
networking provides high reliability and larger range.
80

LECTURE 9 ANALOGUE TO DIGITAL CONVERSION

REVISION NOTE

ADC CONVERTER
87
2.343 Volts

Microcontrollers are very efficient at processing digital numbers, but they cannot handle
analogue signals directly. An analogue-to-digital converter, converts an analogue voltage
level to a digital number. The microcontroller can then efficiently process the digital
representation of the original analogue voltage. By definition, digital numbers are non-
fractional whole numbers.
In this example, an input voltage of 2.343 volts is converted to 87. The users software can
use the value 87 as the representation of the original input voltage. At this point, the number
87 is only used for discussion purposes as a typical output.

INPUT RANGE

The analogue-to-digital converter is only capable of performing an accurate conversion if the


analogue input voltage is within the valid input range of the converter. If the input voltage
falls outside this range, the conversion value will be inaccurate. The input range is set by
high and low voltage references. These define the upper and lower limits of the valid input
range. In many cases, the high and low voltage references are selected as the
microcontroller supply voltage and ground, at other times an external reference or
references are used. In addition, some devices have internal voltage references that can be
used. The source or sources for these voltage references are a configuration option when
setting up the analogue-to-digital converter in the PICmicro microcontroller (MCU). Note that
there are restrictions on the voltage reference levels, for example: the reference voltages
generally shouldnt be less than Vss or greater than VDD. There is also a minimum
difference that is required between the high and low reference voltages.

QUANTISATION
The output of an analogue-to-digital converter is a quantized representation of the original
analogue signal. The term quantization refers to subdividing a range into small but
measurable increments. The total allowable input range is divided into a finite number of
regions with a fixed increment. The analogue-to-digital converter determines the appropriate
region to assign the given input voltage.
In this example, the step or increment is one-tenth of a volt and the input voltage is 2.343
volts. The appropriate result would be assigned as a digital value of 87, because 2.343 volts
fits between the quantization limits of 2.3 volts and 2.4 volts. Any input voltage between the
2.3 and 2.4 volt quantization limits will be assigned a digital value of 87.
81

The process of quantization has the potential to introduce an inaccuracy known as


quantization error, which can be viewed as being similar to a rounding error. In the above
example, the 2.343 volt input is in effect rounded to the nearest tenth of a volt. The
maximum quantization error in this case would be five hundredths of a volt or one-half of the
increment size. It should be noted that the minimum quantization error for the analogue-to-
digital converter peripheral in the PIC micro devices is 500 micro volts. Therefore, the
smallest step size for each state cannot be less than one mV.

RESOLUTION

Resolution defines the number of possible analogue-to-digital converter output states. As


previously discussed, the result is a digital or whole number, so for an 8-bit converter the
possible states will be: zero, one, two, three and so on, with 255 as the maximum state. A
10-bit converter will have 1023 as the maximum state, and a 12- bit converter will have 4095
as the maximum state. If the input range remains constant, a higher resolution converter will
have less quantization error because the range is divided into smaller steps. This is similar in
concept to the process of rounding a number to the nearest hundredths, having potentially
less error than rounding to the nearest tenths.

A NOTE ON ANALOGUE TO DIGITAL SAMPLING SHANNONS THEOREM

When sampling an alternating signal, the sampling rate must be at least twice
the highest frequency component of the input signal Shannons Theorem

ALIASING AND ANALOGUE TO DIGITAL CONVERSION

A signal that has a frequency of more than half the sampling rate i.e. does not follow
Shannons Theorem -may introduce low frequency unwanted error components when
subsequently converted back into an analogue signal. This is called aliasing error.

In order to prevent aliasing the storage of digital samples representing lower frequencies
than the input signal an input low pass filter can be used. A low pass filter is a device that
accepts frequencies below a cut-off frequency Fc and suppresses or rejects frequencies
above Fc.

This is called an anti-aliasing filter. By accepting only frequencies up to half the sampling
frequency and suppressing higher frequencies, the problem of aliasing can be prevented.
The filter is connected to the input of the ADC as shown below:

LOW PASS
FILTER
Analogue signal ADC
Fc=1/2
Fsample
82

SAMPLE AND HOLD CAPACITOR

This component is a vital part of the successive approximation ADC. It will be connected by
analogue switch to the incoming signal and will charge/discharge to follow the voltage
change on this input. After sufficient time to charge/discharge satisfactorily up to the input
voltage, the SH capacitor is isolated from the signal this is performed when the start of
conversion is executed. The SH capacitor now holds a stable and unchanging voltage
suitable for ADC by the successive approximation hardware of the converter.

ACQUISITION TIME

This is the time taken from the closure of the analogue switch connecting the sample and
hold capacitor of the ADC until the input voltage has stabilised with accurate value on the
sample and hold capacitor. Acquisition time will be longer if the input resistance to the S/H
capacitor is increased for any reason.

CONVERSION TIME

Each ADC will have a conversion time i.e. the time taken to convert a stable input voltage
signal into its corresponding digital value.

ADC SPEED

The speed of any ADC is determined by acquisition time and conversion time such that a
new conversion cannot be performed until the previous signal has been acquired and
converted. The minimum time interval between conversions will therefore be:

T= Tacq + Tcon

Where Tacq is the acquisition time and Tcon is the ADC conversion time.

ADC Rate = 1/T


83

LECTURE 10 THE REAL TIME OPERATING SYSTEM

Acknowledgement Designing Embedded Systems with PIC Microcontrollers Wilmhurst

A program written for a real time operating system will be written as tasks. These tasks are
usually prioritised with the operating system controlling task execution.

The RTOS has three main functions:

1. It decides which task is to be run and for how long


2. It allows communication between tasks
3. It controls the use common resources used for tasks e.g. memory and hardware
peripherals

SCHEDULING & TASKS

Scheduling

A central part of the RTOS is the scheduler. There are various scheduling methods but the
scheduler must be aware of the tasks that are ready to run and their priority.

Cyclic Scheduling

This is the most fundamental system where tasks are allowed to execute to completion
before the next task is enabled. This is the conventional sequential programming model and
has the disadvantage that the repetition rate for each task will be variable and dependent on
the time taken for other tasks within the loop.

Round Robin Scheduling with Context Switching

This will require the concept of a clock tick that we saw with the simple time-slice
scheduler described previously.

In this system each task is allowed a fixed period to run. In the event that the task cannot
complete, context saving will occur, and the task will resume on its next slot. All tasks are
treated as equal in priority. This is an example of a pre-emptive system i.e. they are pre-
empted meaning that they are interrupted before completion.

This system has overheads time needs to be allowed for the necessary context saving
meaning that the tasks will run slower. Context saving must be complete. Critical code
sections that cannot be interrupted may be difficult to fit within this rigid structure.
84

TASK STATES

In an RTOS system tasks are identified by various qualifiers as to their state.

Ready- This means that the task is ready to run and will do so immediately it is granted
CPU access. On leaving the ready state it will enter the active or running state.

Running - The task is executing. It will stay running until either it finishes the task or it is
stopped or pre-empted by the scheduler to allow another task to run. It may be blocked or
waiting as described below.

Blocked/Waiting/Delayed A task may be ready to run but is not allowed to do so causes


may be various such as waiting for task data to arrive, waiting for a task resource currently
being used by another task, or waiting for a delay period to elapse. This state is left when
the cause of the block has been removed and the running state can resume.

Stopped/Suspended/Dormant - the task, at present, does not need CPU time. A task leaves
this state and enters the ready state when it is re-activated.

Destroyed In this state the task no longer exists, as far as the RTOS is concerned. The
task may not need to have continuous existence for the duration of the program execution.
Tasks have to be created or initialised by the program before they can run. Removing
unneeded tasks from the task list can simplify the scheduler and reduce demands on
memory.

Un-initialised/
destroyed
RTOS TASK STATES

ACTIVATE RELEASE

Blocked/
Stopped/
Ready/eligible waiting/
suspended
delayed

PRE-EMPT START

COMPLETE Running

WAIT
85

Prioritised Pre-emptive Scheduling

We have seen that a conventional interrupt-based program allows for prioritising of interrupt
sources meaning that a higher priority interrupt will run before a lower priority source. This
concept is also used within RTOS design.

In a prioritised pre-emptive scheduler, tasks are given priorities. Higher priority tasks are
allowed to complete before any time whatsoever is given to tasks of lower priority. The
scheduler is still run and synchronised by a clock tick. On every tick, the scheduler checks
to see which ready task has the highest priority and allows that task access to the CPU.
The highest priority task will keep CPU access. A low priority task which is executing is
replaced by one of higher priority at the clock tick.

Cooperative scheduling

A disadvantage of prioritised pre-emptive scheduling is that the scheduler must rigorously


context save for all tasks that have been pre-empted and this is memory intensive. Context
switching is time consuming and tasks must be written in such a way that they may be
switched at any time during their operation.

Cooperative scheduling is an alternative strategy. In this type of system each task must give
up access to the CPU of its own accord. The tasks need to be written correctly to prevent
blocking the system i.e. a task monopolising the CPU. This system has the advantage of
requiring less context saving but may not be as responsive as the pre-emptive scheduler i.e.
it has to get to a switch point of its own choosing before it relinquishes control. It will use less
memory and has a place for smaller microcontrollers where memory resource is limited. An
example of a cooperative scheduler targeted at small microcontrollers such as Microchip PIC
is Salvo(R).

Writing tasks and setting priority

These activities are the responsibility of the programmer. Priority may be static (not changing
for the duration of the program) or dynamic (may be changed as the program runs). The
programmer would assign priorities as follows:

Highest priority tasks are those essential for system survival.


Middle priority tasks are those essential for correct system operation.
Low priority tasks are those that, for example, may be tolerated if delayed.

Data and resource protection the semaphore

Several tasks may need to use the same item of shared resource. This item might be
hardware such as memory or peripheral device or it might be a common software module. A
mechanism to deal with access conflict is the semaphore. A semaphore is allocated to
each shared resource and is used to indicate if it is in use.

In a binary semaphore the first task needing to use the resource will find the semaphore in
a GO state and will immediately change it to WAIT before starting to use the resource. Any
other task needing to use the resource will have to enter the blocked state. When the first
task has completed accessing the resource it changes the semaphore back to the GO. A
concept of mutual exclusion is so described meaning that when one task is accessing the
resource all others are excluded.
86

Multi-tasking in microcontrollers

If the tasks to be performed by a microcontroller programme are not time critical e.g. each
task can be executed before the next is due, the most recommended programming template
is the state machine.

As seen previously, the state machine requires that the system can be broken into separate
areas of functionality or states with transition from one state to any of the others determined
by unique conditions. This is an example of non-linear programming since the programme
flow can change direction according to the next state to be entered it does not follow a pre-
determined sequence. The state machine is reliable and robust.

Time-slicing

If tasks are time-critical e.g. if they must be executed at a pre-determined frequency e.g.
every 10ms say or if there are multiple tasks to service regularly then a system of time-
slicing is recommended.

In a time-slicing system, there will be a system tick rate used to synchronise the execution
of tasks. As an example, suppose that the system requires three tasks to be executed such
that task 1 takes 1ms to complete and is repeated every 10ms, task 2 takes 2ms to complete
and is to be repeated every 50ms and task 3 takes 5ms to complete and is to be repeated
every 100ms then a suitable tick rate interval would be 10ms.

This 10ms interval would probably be generated by timer interrupt set to occur every 10ms.
The timer interrupt service routine would then handle the task code since, even with all three
tasks requiring servicing, there is sufficient time between successive interrupts to handle all
three tasks one after another.
87

Tick Interval

10ms 10ms 10ms 10ms 10ms 10ms 10ms 10ms 10ms 10ms

Task1 Task1 Task1 Task1 Task1 Task1 Task1 Task1 Task1 Task1

Task2 Task2

Task3

1ms 1ms 1ms 1ms 3ms 1ms 1ms 1ms 1ms 8ms

Total task time

A typical programme structure might be as follows:

void interrupt tmr0(void)


{
T0IF=0; // reset interrupt flag
task1();
task2_count++;
task3_count++;
if(task2_count = = 5)
{
task2();
task2_count=0;
}
if(task3_count = = 10)
{
task3();
task3_count=0;
}

void main(void)
{
while(1)
{
}
}
88

How do we deal with tasks that are low priority but take longer than the tick interval to
complete?
Suppose that, in the above example task 3 is changed such that it now takes 20ms to
complete even but still needs to be repeated every 100ms. We clearly cannot complete task
3 in the interrupt service routine without losing our time synchronisation i.e. the three tasks
would take 1 + 2 + 20 = 23 ms which is greater than the tick period!

In this case, the recommended procedure is to use a flag set in the interrupt service routine
to indicate to the background loop that task 3 requires execution, then to execute the task in
the background loop.

The above code would be changed as follows:

void interrupt tmr0(void)


{
T0IF=0; // reset interrupt flag
task1();
task2_count++;
task3_count++;
if(task2_count = = 5)
{
task2();
task2_count=0;
}
if(task3_count = = 10)
{
task3_flag = 1;
task3_count=0;
}
}

void main(void)
{
while(1)
{
if(task3_flag = = 1)
{
task3();
task3_flag=0;
}
}
}

You might also like