Embedded Systems Notes
Embedded Systems Notes
Embedded Systems Notes
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.
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 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.
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
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.
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
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 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.
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
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.
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
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
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.
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
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.
QUESTIONS - LECTURE 1
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.
An embedded design is a design that has fixed functionality and a single purpose -
e.g. a microwave digital timer.
Moores Law states that, the number of transistors capable of being fabricated within
a single device, will double every 2 years.
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.
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
Refer to Page 5 Embedded System Design for a suitable definition of the main design
metrics associated with an embedded design i.e.
Unit Cost
Flexibility ability to change functionality without large NRE cost software is flexible
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?
TIME TO MARKET
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
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))
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
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
Number of Units
Crossover point
As a general relationship:
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
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:
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
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
}
}
}
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
(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
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?
INITIALISE PROCESS
PUMP DRAIN CHECK NEXT PUMP DRAIN CHECK NEXT PUMP DRAIN CHECK NEXT
OFF OFF STATE ON OFF STATE OFF ON STATE
NEXT STATE NEXT STATE NEXT STATE NEXT STATE NEXT STATE NEXT STATE
= FILL = IDLE = EMPTY = FILL = FILL = EMPTY
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.
EXAMPLE
pnt = &Count;
Count = 12
then
*pnt=12
26
CODE EXAMPLE
X=*pnt;
ARRAY POINTERS
EXAMPLE:
The name Total is a pointer to the array and holds the address of the first element of the
array
EXAMPLE:
*(Total+2)=4;
&Total[j] which points to the jth element of array Total can also be written as:
Total + j
27
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 = 0; Z[3] = 0
or
*P = 0; Z[2] = 0
*(P + 1) = 0; Z[3] = 0
unsigned int Cnt, Tot; declare two variables Cnt and Tot
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.
A REVIEW OF VARIABLES
GLOBAL VARIABLES
Disadvantage is that they take up permanent memory space and are accessible from
all functions
unsigned char x;
unsigned int i;
float x;
Can be initialized when declared e.g.
unsigned char y = 3;
LOCAL VARIABLES
Unless declared as static will not hold data when exiting the function
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
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.
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 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
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
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.
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
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
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.
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:
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.
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.
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>
To generate a header file suitable for the source code LCD.c we would need the following:
LCD.h
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);
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
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.
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:
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:
# 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
INTERRUPTS
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.
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
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
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
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
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.
Even with suitable context saving, there will be times when interrupts cannot be tolerated
and may need to be masked i.e. disabled:
CONCLUSIONS
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 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
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.
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.
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
Typical peripheral devices which may have an in-built I2C capability include real time clock
chips, EEPROM, displays, ADC, DAC etc
52
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.
A change in the state of the data line, from HIGH to LOW, while the clock is HIGH, defines a
START condition.
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.
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
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)
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)
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:
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 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
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.
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.
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
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.
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
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
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
A safe system philosophy is needed for such equipment as transportation, medical systems
and atomic energy
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.
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 safety philosophy associated with the functionality of, for example, medical equipment
has evolved over the last twenty years and includes one central theme -
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.
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.
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
The above diagram shows what is needed functionally for the device to perform the required
activity why is this unsafe?
72
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
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.
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 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)
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
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.
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.
RANGE CALCULATION
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
n = 3.5
-95.8 = 35 log(1/d)
log(1/d) = -2.737
log(d) = 2.737
d=546m
78
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.
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
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
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
RESOLUTION
When sampling an alternating signal, the sampling rate must be at least twice
the highest frequency component of the input signal Shannons Theorem
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
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.
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.
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.
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
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.
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
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
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).
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:
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
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.
void main(void)
{
while(1)
{
if(task3_flag = = 1)
{
task3();
task3_flag=0;
}
}
}