8051&C I
8051&C I
8051&C I
Pont, 2002-2003
Embedded This document may be freely distributed and copied, provided that copyright notice at
the foot of each OHP page is clearly visible in all copies.
Systems I
A 10-week course, using C
Michael J. Pont
University of Leicester
17
16
15
14
13
12
11
10
20
19
18
2
1
7
6
5
3
9
8
VSS
XTL1
XTL2
P3.7
P3.6
P3.5
P3.4
P3.3
P3.2
P3.1
P3.0
RST
P1.7
P1.6
P1.5
P1.4
P1.3
P1.2
P1.1
P1.0
‘8051’
/ PSEN
P0.0
VCC
P2.0
P2.1
P2.2
P2.3
P2.4
P2.5
P2.6
P2.7
P0.7
P0.6
P0.5
P0.4
P0.3
P0.2
P0.1
ALE
/ EA
34
37
38
39
24
25
28
30
35
36
40
26
27
29
32
33
31
21
22
23
[v1.2]
I II
Seminar 1: “Hello, Embedded World” 1 Seminar 2: Basic hardware foundations (resets, oscillators and port I/O) 21
Overview of this seminar 2 Review: The 8051 microcontroller 22
Overview of this course 3 Review: Central-heating controller 23
By the end of the course … 4 Overview of this seminar 24
Main course textbook 5 Oscillator Hardware 25
Why use C? 6 How to connect a crystal to a microcontroller 27
Pre-requisites! 7 Oscillator frequency and machine cycle period 28
The 8051 microcontroller 8 Keep the clock frequency as low as possible 29
The “super loop” software architecture 9 Stability issues 30
Strengths and weaknesseses of “super loops” 10 Improving the stability of a crystal oscillator 31
Example: Central-heating controller 11 Overall strengths and weaknesses 32
Reading from (and writing to) port pins 12 Reset Hardware 34
SFRs and ports 13 More robust reset circuits 35
SFRs and ports 14 Driving DC Loads 36
Creating and using sbit variables 15 Use of pull-up resistors 38
Example: Reading and writing bytes 16 Driving a low-power load without using a buffer 39
Creating “software delays” 17 Using an IC Buffer 40
Using the performance analyzer to test software delays 18 Example: Buffering three LEDs with a 74HC04 41
Strengths and weaknesses of software-only delays 19 What is a multi-segment LED? 42
Preparation for the next seminar 20 Driving a single digit 43
Preparation for the next seminar 44
III IV
Seminar 3: Reading Switches 45 Seminar 4: Adding Structure to Your Code 77
Introduction 46 Introduction 78
Review: Basic techniques for reading from port pins 47 Object-Oriented Programming with C 79
Example: Reading and writing bytes (review) 48 Example of “O-O C” 82
Example: Reading and writing bits (simple version) 49 The Project Header (Main.H) 85
Example: Reading and writing bits (generic version) 51 The Port Header (Port.H) 92
The need for pull-up resistors 56 Re-structuring a “Hello World” example 96
The need for pull-up resistors 57 Example: Re-structuring the Goat-Counting Example 104
The need for pull-up resistors 58 Preparation for the next seminar 114
Dealing with switch bounce 59
Example: Reading switch inputs (basic code) 61
Example: Counting goats 68
Conclusions 74
Preparation for the next seminar 75
V VI
Seminar 5: Meeting Real-Time Constraints 115 Seminar 6: Creating an Embedded Operating System 139
Introduction 116 Introduction 140
Creating “hardware delays” 118 Timer-based interrupts (the core of an embedded OS) 144
The TCON SFR 119 The interrupt service routine (ISR) 145
The TMOD SFR 120 Automatic timer reloads 146
Two further registers 121 Introducing sEOS 147
Example: Generating a precise 50 ms delay 122 Introducing sEOS 148
Example: Creating a portable hardware delay 126 Tasks, functions and scheduling 153
The need for ‘timeout’ mechanisms - example 129 Setting the tick interval 154
Creating loop timeouts 130 Saving power 157
Example: Testing loop timeouts 132 Using sEOS in your own projects 158
Example: A more reliable switch interface 134 Is this approach portable? 159
Creating hardware timeouts 135 Example: Milk pasteurization 160
Conclusions 137 Conclusions 174
Preparation for the next seminar 138 Preparation for the next seminar 175
VII VIII
Seminar 7: Multi-State Systems and Function Sequences 177 Seminar 8: Using the Serial Interface 211
Introduction 178 Overview of this seminar 212
Implementing a Multi-State (Timed) system 180 What is ‘RS-232’? 213
Example: Traffic light sequencing 181 Basic RS-232 Protocol 214
Example: Animatronic dinosaur 189 Asynchronous data transmission and baud rates 215
Implementing a Multi-State (Input/Timed) system 195 RS-232 voltage levels 216
Example: Controller for a washing machine 197 The software architecture 217
Conclusions 208 Overview 218
Preparation for the next seminar 209 Using the on-chip U(S)ART for RS-232 communications 219
Serial port registers 220
Baud rate generation 221
Why use 11.0592 MHz crystals? 222
PC Software 223
What about printf()? 224
RS-232 and 8051: Overall strengths and weaknesses 225
Example: Displaying elapsed time on a PC 226
Example: Data acquisition 235
Conclusions 239
Preparation for the next seminar 240
IX X
Seminar 9: Case Study: Intruder Alarm System 241 Seminar 10: Case Study: Controlling a Mobile Robot 263
Introduction 242 Overview 264
System Operation 243 What can the robot do? 265
Key software components used in this example 244 The robot brain 266
Running the program 245 How does the robot move? 267
The software 246 Pulse-width modulation 268
Extending and modifying the system 260 Software PWM 269
Conclusions 261 The resulting code 270
More about the robot 271
Conclusions 272
XI XII
Overview of this seminar
This introductory seminar will:
• Provide an overview of this course
Seminar 1: • Introduce the 8051 microcontroller
“Hello, Embedded • Present the “Super Loop” software architecture
World” • Describe how to use port pins
• Consider how you can generate delays (and why you might
need to).
4V - 6V (battery)
10 µF
1 RST VCC 20
10 KΩ 2 P3.0 P1.7 19
3 P3.1 P1.6 18 5.5V, 0.3A lamp
4 17
Atmel 2051
XTL2 P1.5
E
4 MHz
5 XTL1 P1.4 16
B
6 P3.2 P1.3 15 ZTX751
7 P3.3 P1.2 14
C
8 P3.4 P1.1 13
9 P3.5 P1.0 12
10 GND P3.7 11
17
16
15
14
13
12
11
20
18
10
19
5
4
3
2
1
6
8
9
VSS
XTL1
XTL2
P3.7
P3.6
P3.5
P3.4
P3.3
P3.2
P3.1
P3.0
RST
P1.7
P1.6
P1.5
P1.4
P1.3
P1.2
P1.1
P1.0
‘8051’
/ PSEN
P0.0
VCC
P2.0
P2.1
P2.2
P2.3
P2.4
P2.5
P2.6
P2.7
P0.7
P0.6
P0.5
P0.4
P0.3
P0.2
P0.1
ALE
/ EA
34
35
36
37
38
39
40
24
25
26
27
28
29
30
32
33
31
21
23
22
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 1 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 2
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Overview of this course By the end of the course …
This course is concerned with the implementation of software (and By the end of the course, you will be able to:
a small amount of hardware) for embedded systems constructed
1. Design software for single-processor embedded applications
using a single microcontroller.
based on small, industry standard, microcontrollers;
The processors examined in detail are from the 8051 family 2. Implement the above designs using a modern, high-level
(including both ‘Standard’ and ‘Small’ devices). programming language (‘C’), and
All programming is in the ‘C’ language. 3. Begin to understand issues of reliability and safety and how
software design and programming decisions may have a
positive or negative impact in this area.
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 3 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 4
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Main course textbook Why use C?
• It is a ‘mid-level’, with ‘high-level’ features (such as support
Throughout this course, we will be making heavy use of this book: for functions and modules), and ‘low-level’ features (such as
good access to hardware via pointers);
Embedded C
• It is very efficient;
by Michael J. Pont (2002)
• It is popular and well understood;
Addison-Wesley
[ISBN: 0-201-79523X] • Even desktop developers who have used only Java or C++
can soon understand C syntax;
• Good, well-proven compilers are available for every
embedded processor (8-bit to 32-bit or more);
For further information about this book, please see: • Experienced staff are available;
http://www.engg.le.ac.uk/books/Pont/ec51.htm • Books, training courses, code samples and WWW sites
discussing the use of the language are all widely available.
Overall, C may not be an perfect language for developing embedded
systems, but it is a good choice (and is unlikely that a ‘perfect’ language
will ever be created).
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 5 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 6
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Pre-requisites! The 8051 microcontroller
• Throughout this course, it will be assumed that you have had
previous programming experience: this might be in - for
16
13
17
15
14
12
11
20
18
10
19
2
1
7
6
5
3
9
8
VSS
XTL1
XTL2
P3.7
P3.6
P3.5
P3.4
P3.3
P3.2
P3.1
P3.0
RST
P1.7
P1.6
P1.5
P1.4
P1.3
P1.2
P1.1
P1.0
example - Java or C++.
‘8051’
• For most people with such a background, “getting to grips”
/ PSEN
P0.0
VCC
P2.0
P2.1
P2.2
P2.3
P2.4
P2.5
P2.6
P2.7
P0.7
P0.6
P0.5
P0.4
P0.3
P0.2
P0.1
ALE
/ EA
with C is straightforward.
34
37
38
39
35
36
40
24
25
26
27
28
29
30
32
33
31
21
23
22
Typical features of a modern 8051:
• Thirty-two input / output lines.
• Internal data (RAM) memory - 256 bytes.
• Up to 64 kbytes of ROM memory (usually flash)
• Three 16-bit timers / counters
• Nine interrupts (two external) with two priority levels.
• Low-power Idle and Power-down modes.
The different members of this family are suitable for everything from
automotive and aerospace systems to TV “remotes”.
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 7 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 8
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
The “super loop” software architecture Strengths and weaknesseses of “super loops”
☺ The main strength of Super Loop systems is their simplicity. This
Problem makes them (comparatively) easy to build, debug, test and maintain.
What is the minimum software environment you need to create an ☺ Super Loops are highly efficient: they have minimal hardware
resource implications.
embedded C program?
☺ Super Loops are highly portable.
Solution
BUT:
void main(void)
{ If your application requires accurate timing (for example, you need to
/* Prepare for task X */
X_Init(); acquire data precisely every 2 ms), then this framework will not
provide the accuracy or flexibility you require.
while(1) /* 'for ever' (Super Loop) */
The basic Super Loop operates at ‘full power’ (normal operating
{
X(); /* Perform the task */ mode) at all times. This may not be necessary in all applications, and
} can have a dramatic impact on system power consumption.
}
[As we will see in Seminar 6, a scheduler can address these
problems.]
Crucially, the ‘super loop’, or ‘endless loop’, is required because we
have no operating system to return to: our application will keep looping
until the system power is removed.
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 9 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 10
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Example: Central-heating controller Reading from (and writing to) port pins
Problem
Temperature
sensor
Central
heating Boiler
How do you write software to read from and /or write to the ports
Temperature
controller
on an (8051) microcontroller?
dial
void main(void) Background
{
/* Init the system */ The Standard 8051s have four 8-bit ports.
C_HEAT_Init();
while(1) /* 'for ever' (Super Loop) */
{
All of the ports are bidirectional: that is, they may be used for both
/* Find out what temperature the user requires input and output.
(via the user interface) */
C_HEAT_Get_Required_Temperature();
/* Find out what the current room temperature is
(via temperature sensor) */
C_HEAT_Get_Actual_Temperature();
/* Adjust the gas burner, as required */
C_HEAT_Control_Boiler();
}
}
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 11 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 12
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
SFRs and ports SFRs and ports
Control of the 8051 ports through software is carried out using what A typical SFR header file for an 8051 family device will contain the
are known as ‘special function registers’ (SFRs). lines:
sfr P0 = 0x80;
Physically, the SFR is a area of memory in internal RAM: sfr P1 = 0x90;
sfr P2 = 0xA0;
• P0 is at address 0x80 sfr P3 = 0xB0;
• P1 at address 0x90
Having declared the SFR variables, we can write to the ports in a
• P2 at address 0xA0 straightforward manner. For example, we can send some data to
Port 1 as follows:
• P3 at address 0xB0
unsigned char Port_data;
Port_data = 0x0F;
P1 = Port_data; /* Write 00001111 to Port 1 */
NOTE: 0x means that the number format is HEXADECIMAL
- see Embedded C, Chapter 2. Similarly, we can read from (for example) Port 1 as follows:
unsigned char Port_data;
P1 = 0xFF; /* Set the port to ‘read mode’ */
Port_data = P1; /* Read from the port */
Note that, in order to read from a pin, we need to ensure that the last
thing written to the pin was a ‘1’.
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 13 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 14
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Creating and using sbit variables Example: Reading and writing bytes
To write to a single pin, we can make use of an sbit variable in the
Keil (C51) compiler to provide a finer level of control.
Here’s a clean way of doing this:
The input port
The output port
#define LED_PORT P3
#define LED_ON 0 /* Easy to change the logic here */
#define LED_OFF 1 void main (void)
{
... unsigned char Port1_value;
sbit Warning_led = LED_PORT^0; /* LED is connected to pin 3.0 */ /* Must set up P1 for reading */
P1 = 0xFF;
...
while(1)
Warning_led = LED_ON; {
... /* delay */ /* Read the value of P1 */
Warning_led = LED_OFF; Port1_value = P1;
... /* delay */
Warning_led = LED_ON; /* Copy the value to P2 */
... /* etc */ P2 = Port1_value;
}
}
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 15 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 16
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Creating “software delays” Using the performance analyzer to test software delays
Problem
How do you create a simple delay without using any hardware
(timer) resources?
Solution
Loop_Delay()
{
unsigned int x,y;
for (x=0; x <= 65535; x++)
{
y++;
}
}
Longer_Loop_Delay()
{
unsigned int x, y, z;
for (x=0; x<=65535; x++)
{
for (y=0; y<=65535; y++);
{
z++;
}
}
}
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 17 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 18
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Strengths and weaknesses of software-only delays Preparation for the next seminar
☺ SOFTWARE DELAY can be used to produce very short delays. In the lab session associated with this seminar, you will use a
☺ SOFTWARE DELAY requires no hardware timers. hardware simulator to try out the techniques discussed here. This
☺ SOFTWARE DELAY will work on any microcontroller. will give you a chance to focus on the software aspects of
embedded systems, without dealing with hardware problems.
BUT:
In the next seminar, we will prepare to create your first test systems
It is very difficult to produce precisely timed delays. on “real hardware”.
The loops must be re-tuned if you decide to use a different processor,
change the clock frequency, or even change the compiler optimisation
settings. Please read Chapters 1, 2 and 3
before the next seminar
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 19 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 20
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Review: The 8051 microcontroller
16
13
17
15
14
12
11
20
18
10
19
2
1
7
6
5
3
9
8
Seminar 2:
VSS
XTL1
XTL2
P3.7
P3.6
P3.5
P3.4
P3.3
P3.2
P3.1
P3.0
RST
P1.7
P1.6
P1.5
P1.4
P1.3
P1.2
P1.1
P1.0
‘8051’
Basic hardware
/ PSEN
P0.0
VCC
P2.0
P2.1
P2.2
P2.3
P2.4
P2.5
P2.6
P2.7
P0.7
P0.6
P0.5
P0.4
P0.3
P0.2
P0.1
ALE
/ EA
34
37
38
39
35
36
40
24
25
26
27
28
29
30
32
33
31
21
23
22
foundations (resets, Typical features of a modern 8051:
oscillators and port • Thirty-two input / output lines.
I/O) • Internal data (RAM) memory - 256 bytes.
• Up to 64 kbytes of ROM memory (usually flash)
• Three 16-bit timers / counters
• Nine interrupts (two external) with two priority levels.
Vcc
• Low-power Idle and Power-down modes.
Vcc EA
Atmel
The different members of this family are suitable for everything from
89C52 automotive and aerospace systems to TV “remotes”.
12 MHz
DS1812 RESET XTAL 1
30 pF ±10
GND XTAL 2
30 pF ±10
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 21 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 22
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Review: Central-heating controller Overview of this seminar
This seminar will:
Temperature
sensor
Central
• Consider the techniques you need to construct your first
heating
controller
Boiler
“real” embedded system (on a breadboard).
Temperature
dial
void main(void)
Specifically, we’ll look at:
{
/* Init the system */ • Oscillator circuits
C_HEAT_Init();
• Reset circuits
while(1) /* 'for ever' (Super Loop) */
{
/* Find out what temperature the user requires • Controlling LEDs
(via the user interface) */
C_HEAT_Get_Required_Temperature();
/* Find out what the current room temperature is
(via temperature sensor) */
C_HEAT_Get_Actual_Temperature();
/* Adjust the gas burner, as required */
C_HEAT_Control_Boiler();
}
}
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 23 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 24
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Oscillator Hardware
CRYSTAL OSCILLATOR
• All digital computer systems are driven by some form of
oscillator circuit. Crystals may be used to generate a popular form of oscillator circuit
• This circuit is the ‘heartbeat’ of the system and is crucial to known as a Pierce oscillator.
correct operation. Vcc
For example: C
L
Oscillator output
(to microcontroller)
• If the oscillator fails, the system will not function at all.
Crystal
JFET
• If the oscillator runs irregularly, any timing calculations
performed by the system will be inaccurate. R
• A variant of the Pierce oscillator is common in the 8051
family. To create such an oscillator, most of the components
are included on the microcontroller itself.
• The user of this device must generally only supply the
crystal and two small capacitors to complete the oscillator
implementation.
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 25 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 26
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
How to connect a crystal to a microcontroller Oscillator frequency and machine cycle period
• In the original members of the 8051 family, the machine
cycle takes twelve oscillator periods.
8051-family
microcontroller • In later family members, such as the Infineon C515C, a
XTAL
machine cycle takes six oscillator periods; in more recent
C devices such as the Dallas 89C420, only one oscillator
GND XTAL period is required per machine cycle.
C • As a result, the later members of the family operating at the
same clock frequency execute instructions much more
rapidly.
In the absence of specific information, a capacitor value of
30 pF will perform well in most circumstances.
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 27 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 28
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Keep the clock frequency as low as possible Stability issues
Many developers select an oscillator / resonator frequency that is at • A key factor in selecting an oscillator for your system is the
or near the maximum value supported by a particular device. issue of oscillator stability. In most cases, oscillator stability
is expressed in figures such as ‘±20 ppm’: ‘20 parts per
million’.
This can be a mistake:
• Many application do not require the levels of performance
• To see what this means in practice, consider that there are
that a modern 8051 device can provide.
approximately 32 million seconds in a year. In every million
• The electromagnetic interference (EMI) generated by a seconds, your crystal may gain (or lose) 20 seconds. Over
circuit increases with clock frequency. the year, a clock based on a 20 ppm crystal may therefore
gain (or lose) about 32 x 20 seconds, or around 10 minutes.
• In most modern (CMOS-based) 8051s, there is an almost
linear relationship between the oscillator frequency and the
power-supply current. As a result, by using the lowest Standard quartz crystals are typically rated from ±10 to ±100 ppm, and
frequency necessary it is possible to reduce the power so may gain (or lose) from around 5 to 50 minutes per year.
requirement: this can be useful in many applications.
• When accessing low-speed peripherals (such as slow
memory, or LCD displays), programming and hardware
design can be greatly simplified - and the cost of peripheral
components, such as memory latches, can be reduced - if the
chip is operating more slowly.
In general, you should operate at the lowest possible oscillator
frequency compatible with the performance needs of your application.
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 29 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 30
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Improving the stability of a crystal oscillator
• If you want a general crystal-controlled embedded system to
keep accurate time, you can choose to keep the device in an
oven (or fridge) at a fixed temperature, and fine-tune the
software to keep accurate time. This is, however, rarely
practical.
• ‘Temperature Compensated Crystal Oscillators’ (TCXOs)
are available that provide - in an easy-to-use package - a
crystal oscillator, and circuitry that compensates for changes
in temperature. Such devices provide stability levels of up to
±0.1 ppm (or more): in a clock circuit, this should gain or
lose no more than around 1 minute every 20 years.
TCXOs can cost in excess of $100.00 per unit...
• One practical alternative is to determine the temperature-
frequency characteristics for your chosen crystal, and include
this information in your application.
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 31
Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Reset Hardware
CERAMIC RESONATOR
• The process of starting any microcontroller is a non-trivial
one.
Overall strengths and weaknesses
• The underlying hardware is complex and a small,
☺ Cheaper than crystal oscillators.
manufacturer-defined, ‘reset routine’ must be run to place
☺ Physically robust: less easily damage by physical vibration (or
dropped equipment, etc) than crystal oscillator.
this hardware into an appropriate state before it can begin
executing the user program. Running this reset routine takes
☺ Many resonators contain in-built capacitors, and can be used without
any external components. time, and requires that the microcontroller’s oscillator is
☺ Small size. About half the size of crystal oscillator. operating.
• An RC reset circuit is usually the simplest way of controlling
BUT: the reset behaviour.
Comparatively low stability: not general appropriate for use where
accurate timing (over an extended period) is required. Typically ±5000 Example:
ppm = ±2500 min per year (up to ~50 minutes / week).
Vcc
10 uF Vcc
AT89C2051
RESET XTAL 1
30 pF ±10
10 K
GND XTAL 2
30 pF ±10
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 33 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 34
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
More robust reset circuits Driving DC Loads
• The port pins on a typical 8051 microcontroller can be set at
Example: values of either 0V or 5V (or, in a 3V system, 0V and 3V)
under software control.
Vcc
• Each pin can typically sink (or source) a current of around
Vcc EA 10 mA.
Atmel
89C52
12 MHz
• The total current we can source or sink per microcontroller
DS1812 RESET XTAL 1
30 pF ±10
(all 32 pins, where available) is typically 70 mA or less.
GND XTAL 2
30 pF ±10
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 35 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 36
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Use of pull-up resistors
NAKED LED
To adapt circuits for use on pins without internal pull-up resistors is
straightforward: you simply need to add an external pull-up resistor:
Vcc
Vcc
Rled Vcc − Vdiode
Rled =
I diode Rled
Rpull-up
PX.Y
8051 Device Logic 0 (0v)
to light LED
PX.Y
8051 Device Logic 0
to light LED
Connecting a single LED directly to a microcomputer port is
usually possible.
• Supply voltage, Vcc = 5V,
The value of the pull-up resistor should be between 1K and 10K.
This requirement applies to all of the examples on this course.
• LED forward voltage, Vdiode = 2V,
• Required diode current, Idiode = 15 mA (note that the data NOTE:
sheet for your chosen LED will provide this information). This is usually only necessary on Port 0
(see Seminar 3 for further details).
This gives a required R value of 200Ω.
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 37 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 38
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Driving a low-power load without using a buffer Using an IC Buffer
5V
Vcc
“Low” output = 0V LED is (fully) ON
R
“High” output = 5V LED is OFF
R
Pin X.Y
(CMOS)
Load
Buffer
8051 Device
PX.Y
Logic 0 (0v) V − Vload
8051 Device
to drive load
R= cc
I load Using a CMOS buffer.
5V
“Low” output = ~1V LED is ON
Vcc R
“High” output = 5V LED is OFF
Rpull-up
Piezo-electric
Pin X.Y
Buffer
buzzer
(TTL)
8051 Device
PX.Y
Logic 0 (0v) to sound buzzer
8051 Device Using a TTL buffer.
It makes sense to use CMOS logic in your buffer designs wherever
See “PATTERNS FOR TIME-TRIGGERED EMBEDDED SYSTEMS”, p.115 possible. You should also make it clear in the design
(NAKED LOAD) documentation that CMOS logic is to be used.
See “PATTERNS FOR TIME-TRIGGERED EMBEDDED SYSTEMS”, p.118 (IC
BUFFER)
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 39 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 40
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Example: Buffering three LEDs with a 74HC04 What is a multi-segment LED?
This example shows a 74HC04 buffering three LEDs. As discussed Multiple LEDs are often arranged as multi-segment displays:
in Solution, we do not require pull-up resistors with the HC combinations of eight segments and similar seven-segment displays
(CMOS) buffers. (without a decimal point) are particularly common.
8
In this case, we assume that the LEDs are to be driven at 15 mA a
each, which is within the capabilities (50 mA total) of the buffer. f b
g
V −V 5V − 2V e
Rled = cc diode
= = 200Ω c
I diode 0.015 A
d
5V
Such displays are arranged either as ‘common cathode’ or ‘common
200R 200R 200R
anode’ packages:
(PX.a, Anode (+)
PX.b, (Red) (Amber) (Green)
74HC04
PX.c)
Port X
Logic 1 (PX.a) (PX.b) (PX.c)
8051 Device to light
LED
Cathode (-)
See “PATTERNS FOR TIME-TRIGGERED EMBEDDED SYSTEMS”, p.123
The required current per segment varies from about 2 mA (very
small displays) to about 60 mA (very large displays, 100mm or
more).
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 41 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 42
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Driving a single digit Preparation for the next seminar
• In most cases, we require some form of buffer or driver IC
between the port and the MS LED.
Please read Chapter 4
before the next seminar
• For example, we can use UDN2585A.
Each of the (8) channels in this buffer can simultaneously
source up to 120 mA of current (at up to 25V): this is
enough, for example, for even very large LED displays.
Vcc
8
PX.0 9 a
b
c
UDN
2585A
g
dp
10
10 R
PX.7
• Note that this is an inverting (current source) buffer. Logic 0
on the input line will light the corresponding LED segment.
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 43 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 44
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Introduction
• Embedded systems usually use switches as part of their user
interface.
Seminar 3: • This general rule applies from the most basic remote-control
system for opening a garage door, right up to the most
Reading Switches sophisticated aircraft autopilot system.
• Whatever the system you create, you need to be able to
create a reliable switch interface.
To pin on: On Off 1 2 3 Start Engage AP
Port 1, 4 5 6 Temporary Manual
Port 2,
1 2 3 4 5
or 7 8 9 Disengage AP
STOP
Port 3.
0 Enter < > Up and Around
In this seminar, we consider how you can read inputs from
mechanical switches in your embedded application.
Before considering switches themselves, we will consider the
process of reading the state of port pins.
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 45 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 46
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Review: Basic techniques for reading from port pins Example: Reading and writing bytes (review)
We can send some data to Port 1 as follows:
sfr P1 = 0x90; /* Usually in header file */
P1 = 0x0F; /* Write 00001111 to Port 1 */
In exactly the same way, we can read from Port 1 as follows:
The input port
unsigned char Port_data;
The output port
P1 = 0xFF; /* Set the port to ‘read mode’ */
Port_data = P1; /* Read from the port */ void main (void)
{
unsigned char Port1_value;
/* Must set up P1 for reading */
P1 = 0xFF;
while(1)
{
/* Read the value of P1 */
Port1_value = P1;
/* Copy the value to P2 */
P2 = Port1_value;
}
}
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 47 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 48
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Example: Reading and writing bits (simple version) Experienced ‘C’ programmers please note these lines:
/*-------------------------------------------------------------*- sbit Switch_pin = P1^0;
sbit LED_pin = P1^1;
Bits1.C (v1.00)
-*-------------------------------------------------------------*/ Here we gain access to two port pins through the use of an sbit
variable declaration. The symbol ‘^’ is used, but the XOR bitwise
#include <Reg52.H>
operator is NOT involved.
sbit Switch_pin = P1^0;
sbit LED_pin = P1^1;
/* ............................................................... */
void main (void)
{
bit x;
/* Set switch pin for reading */
Switch_pin = 1;
while(1)
{
x = Switch_pin; /* Read Pin 1.0 */
LED_pin = x; /* Write to Pin 1.1 */
}
}
/*-------------------------------------------------------------*-
---- END OF FILE ---------------------------------------
-*-------------------------------------------------------------*/
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 49 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 50
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Example: Reading and writing bits (generic version) /* Desktop program - illustrating the use of bitwise operators */
#include <stdio.h>
The six bitwise operators:
void Display_Byte(const unsigned char);
Operator Description /* ............................................................... */
& Bitwise AND int main()
| {
Bitwise OR (inclusive OR) unsigned char x = 0xFE;
^ Bitwise XOR (exclusive OR) unsigned int y = 0x0A0B;
<< Left shift printf("%-35s","x");
>> Right shift Display_Byte(x);
~ One’s complement printf("%-35s","1s complement [~x]");
Display_Byte(~x);
printf("%-35s","Bitwise AND [x & 0x0f]");
Display_Byte(x & 0x0f);
A B A AND B A OR B A XOR B
0 0 0 0 0 printf("%-35s","Bitwise OR [x | 0x0f]");
Display_Byte(x | 0x0f);
0 1 0 1 1
1 0 0 1 1 printf("%-35s","Bitwise XOR [x ^ 0x0f]");
Display_Byte(x ^ 0x0f);
1 1 1 1 0
printf("%-35s","Left shift, 1 place [x <<= 1] ");
Display_Byte(x <<= 1);
x = 0xfe; /* Return x to original value */
printf("%-35s","Right shift, 4 places [x >>= 4]");
Display_Byte(x >>= 4);
printf("\n\n");
printf("%-35s","Display MS byte of unsigned int y");
Display_Byte((unsigned char) (y >> 8));
printf("%-35s","Display LS byte of unsigned int y");
Display_Byte((unsigned char) (y & 0xFF));
return 0;
}
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 51 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 52
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
/* --------------------------------------------------------------- */ /*-------------------------------------------------------------*-
void Display_Byte(const unsigned char CH) Reading and writing individual port pins.
{
unsigned char i, c = CH; NOTE: Both pins on the same port
unsigned char Mask = 1 << 7;
-*-------------------------------------------------------------*/
for (i = 1; i <= 8; i++)
{ #include <reg52.H>
putchar(c & Mask ? '1' : '0');
c <<= 1; void Write_Bit_P1(const unsigned char, const bit);
} bit Read_Bit_P1(const unsigned char);
putchar('\n'); /* ............................................................... */
}
void main (void)
{
bit x;
while(1)
x 11111110 {
1s complement [~x] 00000001 x = Read_Bit_P1(0); /* Read Port 1, Pin 0 */
Bitwise AND [x & 0x0f] 00001110 Write_Bit_P1(1,x); /* Write to Port 1, Pin 1 */
Bitwise OR [x | 0x0f] 11111111 }
Bitwise XOR [x ^ 0x0f] 11110001 }
Left shift, 1 place [x <<= 1] 11111100
Right shift, 4 places [x >>= 4] 00001111 /* --------------------------------------------------------------- */
void Write_Bit_P1(const unsigned char PIN, const bit VALUE)
Display MS byte of unsigned int y 00001010 {
Display LS byte of unsigned int y 00001011 unsigned char p = 0x01; /* 00000001 */
/* Left shift appropriate number of places */
p <<= PIN;
/* If we want 1 output at this pin */
if (VALUE == 1)
{
P1 |= p; /* Bitwise OR */
return;
}
/* If we want 0 output at this pin */
p = ~p; /* Complement */
P1 &= p; /* Bitwise AND */
}
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 53 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 54
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
/* --------------------------------------------------------------- */
bit Read_Bit_P1(const unsigned char PIN)
The need for pull-up resistors
{
unsigned char p = 0x01; /* 00000001 */
/* Left shift appropriate number of places */ To pin on:
p <<= PIN;
Port 1,
/* Write a 1 to the pin (to set up for reading) */ Port 2,
Write_Bit_P1(PIN, 1); or
/* Read the pin (bitwise AND) and return */
Port 3.
return (P1 & p);
}
/*-------------------------------------------------------------*-
---- END OF FILE ---------------------------------------
-*-------------------------------------------------------------*/
This hardware operates as follows:
• When the switch is open, it has no impact on the port pin.
An internal resistor on the port ‘pulls up’ the pin to the
supply voltage of the microcontroller (typically 5V). If we
read the pin, we will see the value ‘1’.
• When the switch is closed (pressed), the pin voltage will be
0V. If we read the the pin, we will see the value ‘0’.
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 55 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 56
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
The need for pull-up resistors The need for pull-up resistors
We briefly looked at pull-up resistors in Seminar 2. Vcc
With pull-ups: 10KΩ
Vcc Vcc To pin on:
Switch released: Switch pressed:
Reads ‘1’ Reads ‘0’
Port 0.
Without pull-ups:
Vcc Vcc
Switch released: Switch pressed:
Reads ‘0’ Reads ‘0’
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 57 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 58
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Dealing with switch bounce
Creating some simple software to check for a valid switch input is
In practice, all mechanical switch contacts bounce (that is, turn on straightforward:
and off, repeatedly, for a short period of time) after the switch is
closed or opened. 1. We read the relevant port pin.
2. If we think we have detected a switch depression, we wait for
+5v
20 ms and then read the pin again.
3. If the second reading confirms the first reading, we assume
Voltage
the switch really has been depressed.
+5v
Note that the figure of ‘20 ms’ will, of course, depend on the switch
t1 t2 Time used.
As far as the microcontroller is concerned, each ‘bounce’ is
equivalent to one press and release of an ‘ideal’ switch. Without
appropriate software design, this can give rise to a number of
problems, not least:
• Rather than reading ‘A’ from a keypad, we may read
‘AAAAA’
• Counting the number of times that a switch is pressed
becomes extremely difficult.
• If a switch is depressed once, and then released some time
later, the ‘bounce’ may make it appear as if the switch has
been pressed again (at the time of release).
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 59 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 60
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Example: Reading switch inputs (basic code) /*-------------------------------------------------------------*-
Switch_read.C (v1.00)
--------------------------------------------------------
This switch-reading code is adequate if we want to perform
operations such as: A simple 'switch input' program for the 8051.
- Reads (and debounces) switch input on Pin 1^0
- If switch is pressed, changes Port 3 output
• Drive a motor while a switch is pressed.
-*-------------------------------------------------------------*/
• Switch on a light while a switch is pressed.
#include <Reg52.h>
• Activate a pump while a switch is pressed. /* Connect switch to this pin */
sbit Switch_pin = P1^0;
/* Display switch status on this port */
These operations could be implemented using an electrical switch, #define Output_port P3
without using a microcontroller; however, use of a microcontroller
/* Return values from Switch_Get_Input() */
may well be appropriate if we require more complex behaviour. #define SWITCH_NOT_PRESSED (bit) 0
For example: #define SWITCH_PRESSED (bit) 1
/* Function prototypes */
• Drive a motor while a switch is pressed void SWITCH_Init(void);
Condition: If the safety guard is not in place, don’t turn the bit SWITCH_Get_Input(const unsigned char DEBOUNCE_PERIOD);
void DISPLAY_SWITCH_STATUS_Init(void);
motor. Instead sound a buzzer for 2 seconds. void DISPLAY_SWITCH_STATUS_Update(const bit);
void DELAY_LOOP_Wait(const unsigned int DELAY_MS);
• Switch on a light while a switch is pressed
Condition: To save power, ignore requests to turn on the
light during daylight hours.
• Activate a pump while a switch is pressed
Condition: If the main water reservoir is below 300 litres,
do not start the main pump: instead, start the reserve pump
and draw the water from the emergency tank.
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 61 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 62
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
/* ---------------------------------------------------------------- */ /*-------------------------------------------------------------*-
void main(void)
{ SWITCH_Get_Input()
bit Sw_state;
Reads and debounces a mechanical switch as follows:
/* Init functions */
SWITCH_Init(); 1. If switch is not pressed, return SWITCH_NOT_PRESSED.
DISPLAY_SWITCH_STATUS_Init();
2. If switch is pressed, wait for the DEBOUNCE_PERIOD (in ms).
while(1) Then:
{ a. If switch is no longer pressed, return SWITCH_NOT_PRESSED.
Sw_state = SWITCH_Get_Input(30); b. If switch is still pressed, return SWITCH_PRESSED
DISPLAY_SWITCH_STATUS_Update(Sw_state); See Switch_Wait.H for details of return values.
}
} -*-------------------------------------------------------------*/
bit SWITCH_Get_Input(const unsigned char DEBOUNCE_PERIOD)
/*-------------------------------------------------------------*- {
bit Return_value = SWITCH_NOT_PRESSED;
SWITCH_Init()
if (Switch_pin == 0)
Initialisation function for the switch library. {
/* Switch is pressed */
-*-------------------------------------------------------------*/
void SWITCH_Init(void) /* Debounce - just wait... */
{ DELAY_LOOP_Wait(DEBOUNCE_PERIOD);
Switch_pin = 1; /* Use this pin for input */
} /* Check switch again */
if (Switch_pin == 0)
{
Return_value = SWITCH_PRESSED;
}
}
/* Now return switch value */
return Return_value;
}
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 63 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 64
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
/*-------------------------------------------------------------*- /*-------------------------------------------------------------*-
DISPLAY_SWITCH_STATUS_Init() DELAY_LOOP_Wait()
Initialization function for the DISPLAY_SWITCH_STATUS library. Delay duration varies with parameter.
-*-------------------------------------------------------------*/ Parameter is, *ROUGHLY*, the delay, in milliseconds,
void DISPLAY_SWITCH_STATUS_Init(void) on 12MHz 8051 (12 osc cycles).
{
Output_port = 0xF0; You need to adjust the timing for your application!
}
-*-------------------------------------------------------------*/
/*-------------------------------------------------------------*- void DELAY_LOOP_Wait(const unsigned int DELAY_MS)
{
DISPLAY_SWITCH_STATUS_Update() unsigned int x, y;
Simple function to display data (SWITCH_STATUS) for (x = 0; x <= DELAY_MS; x++)
on LEDs connected to port (Output_Port) {
for (y = 0; y <= 120; y++);
-*-------------------------------------------------------------*/ }
void DISPLAY_SWITCH_STATUS_Update(const bit SWITCH_STATUS) }
{
if (SWITCH_STATUS == SWITCH_PRESSED)
{
Output_port = 0x0F;
}
else
{
Output_port = 0xF0;
}
}
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 65 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 66
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Example: Counting goats
• With the simple code in the previous example, problems can
arise whenever a switch is pressed for a period longer than
The output port The input port
the debounce interval.
• This is a concern, because in many cases, users will press
switches for at least 500 ms (or until they receive feedback
that the system has detected the switch press). As a result, a
user typing “Hello” on a keypad may see:
“HHHHHHHHHeeeeeeeeellllllllllllllllooooooooooo”
appear on the screen.
One consequence is that this code is not suitable for applications
where we need to count the number of times that a switch is pressed
and then released.
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 67 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 68
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 69
Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
/*-------------------------------------------------------------*/ /*-------------------------------------------------------------*-
void SWITCH_Init(void) DISPLAY_COUNT_Init()
{
Switch_pin = 1; /* Use this pin for input */ Initialisation function for the DISPLAY COUNT library.
}
-*-------------------------------------------------------------*/
/*-------------------------------------------------------------*- void DISPLAY_COUNT_Init(void)
{
SWITCH_Get_Input() Count_port = 0x00;
}
Reads and debounces a mechanical switch as follows:
/*-------------------------------------------------------------*-
1. If switch is not pressed, return SWITCH_NOT_PRESSED.
DISPLAY_COUNT_Update()
2. If switch is pressed, wait for the DEBOUNCE_PERIOD (in ms).
Then: Simple function to display tByte data (COUNT)
a. If switch is no longer pressed, return SWITCH_NOT_PRESSED. on LEDs connected to port (Count_Port)
b. If switch is still pressed, wait (indefinitely) for
switch to be released, *then* return SWITCH_PRESSED -*-------------------------------------------------------------*/
void DISPLAY_COUNT_Update(const unsigned char COUNT)
See Switch_Wait.H for details of return values. {
Count_port = COUNT;
-*-------------------------------------------------------------*/ }
bit SWITCH_Get_Input(const unsigned char DEBOUNCE_PERIOD)
{ /*-------------------------------------------------------------*-
bit Return_value = SWITCH_NOT_PRESSED;
DELAY_LOOP_Wait()
if (Switch_pin == 0)
{ Delay duration varies with parameter.
/* Switch is pressed */
Parameter is, *ROUGHLY*, the delay, in milliseconds,
/* Debounce - just wait... */ on 12MHz 8051 (12 osc cycles).
DELAY_LOOP_Wait(DEBOUNCE_PERIOD);
You need to adjust the timing for your application!
/* Check switch again */
if (Switch_pin == 0) -*-------------------------------------------------------------*/
{ void DELAY_LOOP_Wait(const unsigned int DELAY_MS)
/* Wait until the switch is released. */ {
while (Switch_pin == 0); unsigned int x, y;
Return_value = SWITCH_PRESSED;
} for (x = 0; x <= DELAY_MS; x++)
} {
for (y = 0; y <= 120; y++);
/* Now (finally) return switch value */ }
return Return_value; }
}
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 71 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 72
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Conclusions
The switch interface code presented and discussed in this seminar
has allowed us to do two things:
The number of goats (in binary)
• To perform an activity while a switch is depressed;
• To respond to the fact that a user has pressed – and then
The switch input (Pin 1.0) released – a switch.
In both cases, we have illustrated how the switch may be
‘debounced’ in software.
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 73 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 74
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Preparation for the next seminar
In the next seminar, we turn our attention to techniques that can
help you re-use the code you develop in subsequent projects.
Please read Chapter 5
before the next seminar
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 75 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 76
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Introduction
We will do three things in this seminar:
1. We will describe how to use an object-oriented style of
Seminar 4: programming with C programs, allowing the creation of
libraries of code that can be easily adapted for use in
Adding Structure to different embedded projects;
Your Code 2. We will describe how to create and use a ‘Project Header’
file. This file encapsulates key aspects of the hardware
environment, such as the type of processor to be used, the
oscillator frequency and the number of oscillator cycles
required to execute each instruction. This helps to document
the system, and makes it easier to port the code to a different
Port Header (Port.H) processor.
// Pins 3.0 and 3.1 used // Switches
// for RS-232 interface sbit Sw_up = P1^2;
sbit Sw_down = P1^3;
3. We will describe how to create and use a ‘Port Header’ file.
This brings together all details of the port access from the
Up Down
whole system. Like the Project Header, this helps during
porting and also serves as a means of documenting important
system features.
We will use all three of these techniques in the code examples
presented in subsequent seminars.
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 77 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 78
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Object-Oriented Programming with C
1
Graham notes :
“[The phrase] ‘object-oriented’ has become almost
Language generation Example languages
synonymous with modernity, goodness and worth in
- Machine Code information technology circles.”
First-Generation Language Assembly 2
(1GL) Language. Jalote notes :
Second-Generation Languages COBOL, “One main claimed advantage of using object orientation
(2GLs) FORTRAN is that an OO model closely represents the problem
domain, which makes it easier to produce and understand
Third-Generation Languages C, Pascal, Ada 83
(3GLs)
designs.”
Fourth-Generation Languages C++, Java, Ada 95
(4GLs)
O-O languages are not readily available for small embedded systems,
primarily because of the overheads that can result from the use of some
of the features of these languages.
1
Graham, I. (1994) “Object-Oriented Methods,” (2nd Ed.) Addison-Wesley. Page
1.
2
Jalote, P. (1997) “An Integrated Approach to Software Engineering”, (2nd Ed.)
Springer-Verlag. Page 273.
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 79 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 80
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
It is possible to create ‘file-based-classes’ in C without imposing a Example of “O-O C”
significant memory or CPU load. /*-------------------------------------------------------------*-
PC_IO.H (v1.00)
Header file --------------------------------------------------------
Serial.C
Serial.C - see PC_IO.C for details.
All
All
program
program -*-------------------------------------------------------------*/
code Header file
code
in
in aa #ifndef _PC_IO_H
single Switch.C
Switch.C
single #define _PC_IO_H
source
source
file
file Header file /* ------ Public constants ------------------------------------ */
sEOS.C
sEOS.C /* Value returned by PC_LINK_Get_Char_From_Buffer if no char is
available in buffer */
#define PC_LINK_IO_NO_CHAR 127
/* ------ Public function prototypes -------------------------- */
void PC_LINK_IO_Write_String_To_Buffer(const char* const);
void PC_LINK_IO_Write_Char_To_Buffer(const char);
char PC_LINK_IO_Get_Char_From_Buffer(void);
/* Must regularly call this function... */
void PC_LINK_IO_Update(void);
#endif
/*-------------------------------------------------------------*-
---- END OF FILE ---------------------------------------
-*-------------------------------------------------------------*/
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 81 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 82
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
/*-------------------------------------------------------------*- /*-------------------------------------------------------------*/
void PC_LINK_IO_Write_Char_To_Buffer(...)
PC_IO.C (v1.00) {
...
-------------------------------------------------------- }
[INCOMPLETE - STRUCTURE ONLY - see EC Chap 9 for complete library] /*-------------------------------------------------------------*/
void PC_LINK_IO_Write_String_To_Buffer(...)
-*-------------------------------------------------------------*/ {
...
#include "Main.H" }
#include "PC_IO.H"
/*-------------------------------------------------------------*/
/* ------ Public variable definitions ------------------------- */ char PC_LINK_IO_Get_Char_From_Buffer(...)
{
tByte In_read_index_G; /* Data in buffer that has been read */ ...
tByte In_waiting_index_G; /* Data in buffer not yet read */ }
tByte Out_written_index_G; /* Data in buffer that has been written */ /*-------------------------------------------------------------*/
tByte Out_waiting_index_G; /* Data in buffer not yet written */ void PC_LINK_IO_Send_Char(...)
{
/* ------ Private function prototypes ------------------------- */ ...
}
static void PC_LINK_IO_Send_Char(const char);
/* ------ Private constants ----------------------------------- */
/* The receive buffer length */
#define RECV_BUFFER_LENGTH 8
/* The transmit buffer length */
#define TRAN_BUFFER_LENGTH 50
#define XON 0x11
#define XOFF 0x13
/* ------ Private variables ----------------------------------- */
static tByte Recv_buffer[RECV_BUFFER_LENGTH];
static tByte Tran_buffer[TRAN_BUFFER_LENGTH];
/*-------------------------------------------------------------*/
void PC_LINK_IO_Update(...)
{
...
}
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 83 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 84
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
The Project Header (Main.H)
Project Header (Main.H)
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 85
Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
The device header Oscillator frequency and oscillations per instruction
/*---------------------------------------------------------- /* Oscillator / resonator frequency (in Hz) e.g. (11059200UL) */
REG515C.H #define OSC_FREQ (12000000UL)
Header file for the Infineon C515C /* Number of oscillations per instruction (12, etc)
12 - Original 8051 / 8052 and numerous modern versions
Copyright (c) 1995-1999 Keil Elektronik GmbH All rights reserved. 6 - Various Infineon and Philips devices, etc.
----------------------------------------------------------------*/ 4 - Dallas 320, 520 etc.
1 - Dallas 420, etc. */
... #define OSC_PER_INST (12)
/* A/D Converter */
sfr ADCON0 = 0xD8;
...
We demonstrate how to use this information:
/* Interrupt System */
sfr IEN0 = 0xA8; • For creating delays (Embedded C, Chapter 6),
...
• For controlling timing in an operating system (Chapter 7),
/* Ports */
sfr P0 = 0x80; and,
sfr P1 = 0x90;
sfr P2 = 0xA0; • For controlling the baud rate in a serial interface (Chapter 9).
sfr P3 = 0xB0;
sfr P4 = 0xE8;
sfr P5 = 0xF8;
sfr P6 = 0xDB;
sfr P7 = 0xFA;
...
/* Serial Channel */
sfr SCON = 0x98;
...
/* Timer0 / Timer1 */
sfr TCON = 0x88;
...
/* CAP/COM Unit / Timer2 */
sfr CCEN = 0xC1;
...
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 87 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 88
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Common data types Interrupts
As we noted in “Embedded C” Chapter 2, interrupts are a key
typedef unsigned char tByte; component of most embedded systems.
typedef unsigned int tWord;
typedef unsigned long tLong;
The following lines in the Project Header are intended to make it
In C, the typedef keyword allows us to provide aliases for data easier for you to use (timer-based) interrupts in your projects:
types: we can then use these aliases in place of the original types. #define INTERRUPT_Timer_0_Overflow 1
Thus, in the projects you will see code like this: #define INTERRUPT_Timer_1_Overflow 3
#define INTERRUPT_Timer_2_Overflow 5
tWord Temperature;
We discuss how to make use of this facility in Embedded C, Ch. 7.
Rather than:
unsigned int Temperature;
The main reason for using these typedef statements is to simplify -
and promote - the use of unsigned data types.
• The 8051 does not support signed arithmetic and extra code
is required to manipulate signed data: this reduces your
program speed and increases the program size.
• Use of bitwise operators generally makes sense only with
unsigned data types: use of ‘typedef’ variables reduces the
likelihood that programmers will inadvertently apply these
operators to signed data.
Finally, as in desktop programming, use of the typedef keyword in
this way can make it easier to adapt your code for use on a different
processor.
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 89 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 90
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Summary: Why use the Project Header? The Port Header (Port.H)
Use of PROJECT HEADER can help to make your code more
readable, not least because anyone using your projects knows where Port Header (Port.H)
to find key information, such as the model of microcontroller and
// Pins 3.0 and 3.1 used // Switches
the oscillator frequency required to execute the software. // for RS-232 interface sbit Sw_up = P1^2;
sbit Sw_down = P1^3;
The use of a project header can help to make your code more easily
portable, by placing some of the key microcontroller-dependent Up Down
data in one place: if you change the processor or the oscillator used
then - in many cases - you will need to make changes only to the
Project Header.
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 91 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 92
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
The Port Header file is simple to understand and easy to apply. There are many advantages obtained by integrating all port access
in a single Port.H header file:
Consider, for example, that we have three C files in a project (A, B,
/* ----- Port.H ----- */
C), each of which require access to one or more port pins, or to a
complete port. /* Port access for File B */
#define Port_B = P0;
File A may include the following: /* Port access for File A */
sbit Pin_A = P3^2;
/* File A */
/* Port access for File C */
sbit Pin_A = P3^2; sbit Pin_C = P2^7;
... ...
File B may include the following:
/* File B */
#define Port_B = P0;
...
File C may include the following:
/* File C */
sbit Pin_C = P2^7;
...
In this version of the code, all of the port access requirements are
spread over multiple files.
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 93 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 94
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
/*-------------------------------------------------------------*-
Port.H (v1.01)
Re-structuring a “Hello World” example
-------------------------------------------------------- /*-------------------------------------------------------------*-
'Port Header' (see Chap 5) for project DATA_ACQ (see Chap 9) Main.H (v1.00)
-*-------------------------------------------------------------*/ -*-------------------------------------------------------------*/
#ifndef _PORT_H #ifndef _MAIN_H
#define _PORT_H #define _MAIN_H
#include "Main.H" /*--------------------------------------------------------
WILL NEED TO EDIT THIS SECTION FOR EVERY PROJECT
/* ------ Menu_A.C ----------------------------------------- */ -------------------------------------------------------- */
/* Uses whole of Port 1 and Port 2 for data acquisition */
#define Data_Port1 P1 /* Must include the appropriate microcontroller header file here */
#define Data_Port2 P2 #include <reg52.h>
/* Oscillator / resonator frequency (in Hz) e.g. (11059200UL) */
/* ------ PC_IO.C ------------------------------------------ */ #define OSC_FREQ (12000000UL)
/* Pins 3.0 and 3.1 used for RS-232 interface */ /* Number of oscillations per instruction (12, etc)
12 - Original 8051 / 8052 and numerous modern versions
#endif 6 - Various Infineon and Philips devices, etc.
4 - Dallas 320, 520 etc.
/*-------------------------------------------------------------*- 1 - Dallas 420, etc. */
---- END OF FILE --------------------------------------- #define OSC_PER_INST (12)
-*-------------------------------------------------------------*/
/* --------------------------------------------------------
SHOULD NOT NEED TO EDIT THE SECTIONS BELOW
-------------------------------------------------------- */
/* Typedefs (see Chap 5) */
typedef unsigned char tByte;
typedef unsigned int tWord;
typedef unsigned long tLong;
/* Interrupts (see Chap 7) */
#define INTERRUPT_Timer_0_Overflow 1
#define INTERRUPT_Timer_1_Overflow 3
#define INTERRUPT_Timer_2_Overflow 5
#endif
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 95 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 96
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
/*-------------------------------------------------------------*- /*-------------------------------------------------------------*-
Port.H (v1.00) Main.C (v1.00)
-------------------------------------------------------- --------------------------------------------------------
'Port Header' for project HELLO2 (see Chap 5) A "Hello Embedded World" test program for 8051.
-*-------------------------------------------------------------*/ (Re-structured version - multiple source files)
#ifndef _PORT_H -*-------------------------------------------------------------*/
#define _PORT_H
#include "Main.H"
/* ------ LED_Flash.C ----------------------------------------- */ #include "Port.H"
/* Connect LED to this pin, via appropriate resistor */ #include "Delay_Loop.h"
sbit LED_pin = P1^5; #include "LED_Flash.h"
#endif void main(void)
{
/*-------------------------------------------------------------*- LED_FLASH_Init();
---- END OF FILE ---------------------------------------
-*-------------------------------------------------------------*/ while(1)
{
/* Change the LED state (OFF to ON, or vice versa) */
LED_FLASH_Change_State();
/* Delay for *approx* 1000 ms */
DELAY_LOOP_Wait(1000);
}
}
/*-------------------------------------------------------------*-
---- END OF FILE ---------------------------------------
-*-------------------------------------------------------------*/
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 97 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 98
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
/*-------------------------------------------------------------*- /*-------------------------------------------------------------*-
LED_flash.H (v1.00) LED_flash.C (v1.00)
-------------------------------------------------------- --------------------------------------------------------
- See LED_flash.C for details. Simple 'Flash LED' test function.
-*-------------------------------------------------------------*/ -*-------------------------------------------------------------*/
#ifndef _LED_FLASH_H #include "Main.H"
#define _LED_FLASH_H #include "Port.H"
/* ------ Public function prototypes -------------------------- */ #include "LED_flash.H"
void LED_FLASH_Init(void); /* ------ Private variable definitions ------------------------ */
void LED_FLASH_Change_State(void);
static bit LED_state_G;
#endif
/*-------------------------------------------------------------*-
/*-------------------------------------------------------------*-
---- END OF FILE --------------------------------------- LED_FLASH_Init()
-*-------------------------------------------------------------*/
Prepare for LED_Change_State() function - see below.
-*-------------------------------------------------------------*/
void LED_FLASH_Init(void)
{
LED_state_G = 0;
}
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 99 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 100
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
/*-------------------------------------------------------------*- /*-------------------------------------------------------------*-
LED_FLASH_Change_State() Delay_Loop.H (v1.00)
Changes the state of an LED (or pulses a buzzer, etc) on a --------------------------------------------------------
specified port pin.
- See Delay_Loop.C for details.
Must call at twice the required flash rate: thus, for 1 Hz
flash (on for 0.5 seconds, off for 0.5 seconds) must call -*-------------------------------------------------------------*/
every 0.5 seconds.
#ifndef _DELAY_LOOP_H
-*-------------------------------------------------------------*/ #define _DELAY_LOOP_H
void LED_FLASH_Change_State(void)
{ /* ------ Public function prototype --------------------------- */
/* Change the LED from OFF to ON (or vice versa) */ void DELAY_LOOP_Wait(const tWord DELAY_MS);
if (LED_state_G == 1)
{ #endif
LED_state_G = 0;
LED_pin = 0; /*-------------------------------------------------------------*-
} ---- END OF FILE ---------------------------------------
else -*-------------------------------------------------------------*/
{
LED_state_G = 1;
LED_pin = 1;
}
}
/*-------------------------------------------------------------*-
---- END OF FILE ---------------------------------------
-*-------------------------------------------------------------*/
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 101 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 102
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
/*-------------------------------------------------------------*-
Delay_Loop.C (v1.00)
Example: Re-structuring the Goat-Counting Example
-------------------------------------------------------- /*-------------------------------------------------------------*-
Create a simple software delay using a loop. Main.H (v1.00)
-*-------------------------------------------------------------*/ -*-------------------------------------------------------------*/
#include "Main.H" #ifndef _MAIN_H
#include "Port.H" #define _MAIN_H
#include "Delay_loop.h" /*--------------------------------------------------------
WILL NEED TO EDIT THIS SECTION FOR EVERY PROJECT
/*-------------------------------------------------------------*- -------------------------------------------------------- */
DELAY_LOOP_Wait() /* Must include the appropriate microcontroller header file here */
#include <reg52.h>
Delay duration varies with parameter.
/* Oscillator / resonator frequency (in Hz) e.g. (11059200UL) */
Parameter is, *ROUGHLY*, the delay, in milliseconds, #define OSC_FREQ (12000000UL)
on 12MHz 8051 (12 osc cycles).
/* Number of oscillations per instruction (12, etc)
You need to adjust the timing for your application! 12 - Original 8051 / 8052 and numerous modern versions
6 - Various Infineon and Philips devices, etc.
-*-------------------------------------------------------------*/ 4 - Dallas 320, 520 etc.
void DELAY_LOOP_Wait(const tWord DELAY_MS) 1 - Dallas 420, etc. */
{ #define OSC_PER_INST (12)
tWord x, y;
/* --------------------------------------------------------
for (x = 0; x <= DELAY_MS; x++) SHOULD NOT NEED TO EDIT THE SECTIONS BELOW
{ -------------------------------------------------------- */
for (y = 0; y <= 120; y++);
} /* Typedefs (see Chap 5) */
} typedef unsigned char tByte;
typedef unsigned int tWord;
/*-------------------------------------------------------------*- typedef unsigned long tLong;
---- END OF FILE ---------------------------------------
-*-------------------------------------------------------------*/ /* Interrupts (see Chap 7) */
#define INTERRUPT_Timer_0_Overflow 1
#define INTERRUPT_Timer_1_Overflow 3
#define INTERRUPT_Timer_2_Overflow 5
#endif
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 103 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 104
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
/*-------------------------------------------------------------*- /*-------------------------------------------------------------*-
Port.H (v1.00) Main.C (v1.00)
-------------------------------------------------------- --------------------------------------------------------
'Port Header' for project GOATS2 (see Chap 5) A 'switch count' program for the 8051.
-*-------------------------------------------------------------*/ -*-------------------------------------------------------------*/
#ifndef _PORT_H #include "Main.H"
#define _PORT_H #include "Port.H"
/* ------ Switch_Wait.C ------------------------------------------ */ #include "Switch_wait.H"
/* Connect switch to this pin */ #include "Display_count.H"
sbit Switch_pin = P1^0;
/* ---------------------------------------------------------------- */
/* ------ Display_count.C ---------------------------------------- */ void main(void)
/* Display count (binary) on this port */ {
#define Count_port P3 tByte Switch_presses = 0;
#endif /* Init functions */
SWITCH_Init();
/*-------------------------------------------------------------*- DISPLAY_COUNT_Init();
---- END OF FILE ---------------------------------------
-*-------------------------------------------------------------*/ while(1)
{
if (SWITCH_Get_Input(30) == SWITCH_PRESSED)
{
Switch_presses++;
}
DISPLAY_COUNT_Update(Switch_presses);
}
}
/*-------------------------------------------------------------*-
---- END OF FILE ---------------------------------------
-*-------------------------------------------------------------*/
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 105 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 106
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
/*-------------------------------------------------------------*- /*-------------------------------------------------------------*-
Switch_wait.H (v1.00) Switch_Wait.C (v1.00)
-------------------------------------------------------- --------------------------------------------------------
- See Switch_wait.C for details. Simple library for debouncing a switch input.
-*-------------------------------------------------------------*/ NOTE: Duration of function is highly variable!
#ifndef _SWITCH_WAIT_H -*-------------------------------------------------------------*/
#define _SWITCH_WAIT_H
#include "Main.H"
/* ------ Public constants ------------------------------------ */ #include "Port.H"
/* Return values from Switch_Get_Input() */
#define SWITCH_NOT_PRESSED (bit) 0 #include "Switch_wait.h"
#define SWITCH_PRESSED (bit) 1 #include "Delay_loop.h"
/* ------ Public function prototype --------------------------- */ /*-------------------------------------------------------------*-
void SWITCH_Init(void);
bit SWITCH_Get_Input(const tByte DEBOUNCE_PERIOD); SWITCH_Init()
#endif Initialisation function for the switch library.
/*-------------------------------------------------------------*- -*-------------------------------------------------------------*/
---- END OF FILE --------------------------------------- void SWITCH_Init(void)
-*-------------------------------------------------------------*/ {
Switch_pin = 1; /* Use this pin for input */
}
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 107 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 108
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
/*-------------------------------------------------------------*- /*-------------------------------------------------------------*-
SWITCH_Get_Input() Display_count.H (v1.00)
Reads and debounces a mechanical switch as follows: --------------------------------------------------------
1. If switch is not pressed, return SWITCH_NOT_PRESSED. - See Display_count.C for details.
2. If switch is pressed, wait for DEBOUNCE_PERIOD (in ms). -*-------------------------------------------------------------*/
a. If switch is not pressed, return SWITCH_NOT_PRESSED.
b. If switch is pressed, wait (indefinitely) for #ifndef _DISPLAY_COUNT_H
switch to be released, then return SWITCH_PRESSED #define _DISPLAY_COUNT_H
See Switch_Wait.H for details of return values. /* ------ Public function prototypes -------------------------- */
void DISPLAY_COUNT_Init(void);
-*-------------------------------------------------------------*/ void DISPLAY_COUNT_Update(const tByte);
bit SWITCH_Get_Input(const tByte DEBOUNCE_PERIOD)
{ #endif
bit Return_value = SWITCH_NOT_PRESSED;
/*-------------------------------------------------------------*-
if (Switch_pin == 0) ---- END OF FILE ---------------------------------------
{ -*-------------------------------------------------------------*/
/* Switch is pressed */
/* Debounce - just wait... */
DELAY_LOOP_Wait(DEBOUNCE_PERIOD);
/* Check switch again */
if (Switch_pin == 0)
{
/* Wait until the switch is released. */
while (Switch_pin == 0);
Return_value = SWITCH_PRESSED;
}
}
/* Now (finally) return switch value */
return Return_value;
}
/*-------------------------------------------------------------*-
---- END OF FILE ---------------------------------------
-*-------------------------------------------------------------*/
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 109 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 110
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
/*-------------------------------------------------------------*- /*-------------------------------------------------------------*-
Display_count.C (v1.00) Delay_Loop.H (v1.00)
-------------------------------------------------------- --------------------------------------------------------
Display an unsigned char on a port. - See Delay_Loop.C for details.
-*-------------------------------------------------------------*/ -*-------------------------------------------------------------*/
#include "Main.H" #ifndef _DELAY_LOOP_H
#include "Port.H" #define _DELAY_LOOP_H
#include "Display_Count.H" /* ------ Public function prototype --------------------------- */
void DELAY_LOOP_Wait(const tWord DELAY_MS);
/*-------------------------------------------------------------*-
#endif
DISPLAY_COUNT_Init()
/*-------------------------------------------------------------*-
Initialisation function for the DISPLAY COUNT library. ---- END OF FILE ---------------------------------------
-*-------------------------------------------------------------*/
-*-------------------------------------------------------------*/
void DISPLAY_COUNT_Init(void)
{
Count_port = 0x00;
}
/*-------------------------------------------------------------*-
DISPLAY_COUNT_Update()
Simple function to display tByte data (COUNT)
on LEDs connected to port (Count_Port)
-*-------------------------------------------------------------*/
void DISPLAY_COUNT_Update(const tByte COUNT)
{
Count_port = COUNT;
}
/*-------------------------------------------------------------*-
---- END OF FILE ---------------------------------------
-*-------------------------------------------------------------*/
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 111 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 112
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
/*-------------------------------------------------------------*-
Delay_Loop.C (v1.00)
Preparation for the next seminar
--------------------------------------------------------
Create a simple software delay using a loop.
Please read Chapter 6
-*-------------------------------------------------------------*/
before the next seminar
#include "Main.H"
#include "Port.H"
#include "Delay_loop.h"
/*-------------------------------------------------------------*-
DELAY_LOOP_Wait()
Delay duration varies with parameter.
Parameter is, *ROUGHLY*, the delay, in milliseconds,
on 12MHz 8051 (12 osc cycles).
You need to adjust the timing for your application!
-*-------------------------------------------------------------*/
void DELAY_LOOP_Wait(const tWord DELAY_MS)
{
tWord x, y;
for (x = 0; x <= DELAY_MS; x++)
{
for (y = 0; y <= 120; y++);
}
}
/*-------------------------------------------------------------*-
---- END OF FILE ---------------------------------------
-*-------------------------------------------------------------*/
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 113 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 114
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Introduction
In this seminar, we begin to consider the issues involved in the
accurate measurement of time.
Seminar 5: These issues are important because many embedded systems must
Meeting Real-Time satisfy real-time constraints.
Constraints q
x, y, z = position coordinates
υ, β, ϖ = velocity cordinates
p = roll rate
q = pitch rate
y,β Rudder
r = yaw rate
δr
Elevator
δe
Aileron
x,υ δa
p
z,ϖ
r
Yaw (rate)
sensor
Pitch
(rate) Rudder
sensor
Roll
(rate) Elevator
sensor Aircraft
Autopilot
System
Main
pilot Aileron
controls
Position Main engine
sensors (fuel)
(GPS) controllers
Velocity
sensors
(3 axes)
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 115 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 116
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
bit SWITCH_Get_Input(const tByte DEBOUNCE_PERIOD)
{
Creating “hardware delays”
tByte Return_value = SWITCH_NOT_PRESSED;
All members of the 8051 family have at least two 16-bit timer /
if (Switch_pin == 0)
{ counters, known as Timer 0 and Timer 1.
/* Switch is pressed */
/* Debounce - just wait... */
DELAY_LOOP_Wait(DEBOUNCE_PERIOD); /* POTENTIAL PROBLEM */
These timers can be used to generate accurate delays.
/* Check switch again */
if (Switch_pin == 0)
{ /* Configure Timer 0 as a 16-bit timer */
/* Wait until the switch is released. */ TMOD &= 0xF0; /* Clear all T0 bits (T1 left unchanged) */
while (Switch_pin == 0); /* POTENTIAL CATASTROPHE */ TMOD |= 0x01; /* Set required T0 bits (T1 left unchanged) */
Return_value = SWITCH_PRESSED;
} ET0 = 0; /* No interrupts */
}
/* Values for 50 ms delay */
/* Now (finally) return switch value */ TH0 = 0x3C; /* Timer 0 initial value (High Byte) */
return Return_value; TL0 = 0xB0; /* Timer 0 initial value (Low Byte) */
}
TF0 = 0; /* Clear overflow flag */
TR0 = 1; /* Start Timer 0 */
while (TF0 == 0); /* Loop until Timer 0 overflows (TF0 == 1) */
The first problem is that we wait for a ‘debounce’ period in order to
confirm that the switch has been pressed. Because this delay is TR0 = 0; /* Stop Timer 0 */
implemented using a software loop it may not be very precisely
timed.
Now let’s see how this works…
The second problem is even more serious in a system with real-time
characteristics: we cause the system to wait - indefinitely - for the
user to release the switch.
We’ll see how to deal with both of these problems in this seminar
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 117 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 118
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
The TCON SFR The TMOD SFR
Bit 7 6 5 4 3 2 1 0
Bit 7 6 5 4 3 2 1 0 NAME Gate C/T M1 M0 Gate C/T M1 M0
(msb) (lsb)
TF1 TR1 TF0 TR0 IE1 IT1 IE0 IT0 Timer 1 Timer 0
NAME
Mode 1 (M1 = 0; M0 = 1)
TF1 Timer 1 overflow flag
16-bit timer/counter (with manual reload)
Set by hardware on Timer 1 overflow.
(Cleared by hardware if processor vectors to interrupt routine.) Mode 2 (M1 = 1; M0 = 0)
TR1 Timer 1 run control bit 8-bit timer/counter (with 8-bit auto-reload)
Set / cleared by software to turn Timer 1 either ‘ON’ or ‘OFF’.
TF0 Timer 0 overflow flag GATE Gating control
Set by hardware on Timer 0 overflow. When set, timer/counter “x” is enabled only while “INT x” pin is high and “TRx”
(Cleared by hardware if processor vectors to interrupt routine.) control bit is set. When cleared timer “x” is enabled whenever “TRx” control bit
is set.
TR0 Timer 0 run control bit
C/T Counter or timer select bit
Set / cleared by software to turn Timer 0 either ‘ON’ or ‘OFF’.
Set for counter operation (input from “Tx” input pin).
Cleared for timer operation (input from internal system clock).
Note that the overflow of the timers can be used to generate an
interrupt. We will not make use of this facility in the Hardware Delay
code.
To disable the generation of interrupts, we can use the C statements:
ET0 = 0; /* No interrupts (Timer 0) */
ET1 = 0; /* No interrupts (Timer 1) */
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 119 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 120
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Two further registers Example: Generating a precise 50 ms delay
/*-------------------------------------------------------------*-
Before we can see how this hardware can be used to create delays,
you need to be aware that there are an additional two registers Hardware_Delay_50ms.C (v1.00)
associated with each timer: these are known as TL0 and TH0, and --------------------------------------------------------
TL1 and TH1.
A test program for hardware-based delays.
-*-------------------------------------------------------------*/
#include <reg52.h>
sbit LED_pin = P1^5;
bit LED_state_G;
void LED_FLASH_Init(void);
void LED_FLASH_Change_State(void);
void DELAY_HARDWARE_One_Second(void);
void DELAY_HARDWARE_50ms(void);
/*..................................................................*/
void main(void)
{
LED_FLASH_Init();
while(1)
{
/* Change the LED state (OFF to ON, or vice versa) */
LED_FLASH_Change_State();
/* Delay for approx 1000 ms */
DELAY_HARDWARE_One_Second();
}
}
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 121 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 122
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
/*-------------------------------------------------------------*- /*-------------------------------------------------------------*-
LED_FLASH_Init() DELAY_HARDWARE_One_Second()
Prepare for LED_Change_State() function - see below. Hardware delay of 1000 ms.
-*-------------------------------------------------------------*/ *** Assumes 12MHz 8051 (12 osc cycles) ***
void LED_FLASH_Init(void)
{ -*-------------------------------------------------------------*/
LED_state_G = 0; void DELAY_HARDWARE_One_Second(void)
} {
unsigned char d;
/*-------------------------------------------------------------*-
/* Call DELAY_HARDWARE_50ms() twenty times */
LED_FLASH_Change_State() for (d = 0; d < 20; d++)
{
Changes the state of an LED (or pulses a buzzer, etc) on a DELAY_HARDWARE_50ms();
specified port pin. }
}
Must call at twice the required flash rate: thus, for 1 Hz
flash (on for 0.5 seconds, off for 0.5 seconds) must call /*-------------------------------------------------------------*-
every 0.5 seconds.
DELAY_HARDWARE_50ms()
-*-------------------------------------------------------------*/
void LED_FLASH_Change_State(void) *** Assumes 12MHz 8051 (12 osc cycles) ***
{
/* Change the LED from OFF to ON (or vice versa) */ -*-------------------------------------------------------------*/
if (LED_state_G == 1) void DELAY_HARDWARE_50ms(void)
{ {
LED_state_G = 0; /* Configure Timer 0 as a 16-bit timer */
LED_pin = 0; TMOD &= 0xF0; /* Clear all T0 bits (T1 left unchanged) */
} TMOD |= 0x01; /* Set required T0 bits (T1 left unchanged) */
else
{ ET0 = 0; /* No interrupts */
LED_state_G = 1;
LED_pin = 1; /* Values for 50 ms delay */
} TH0 = 0x3C; /* Timer 0 initial value (High Byte) */
} TL0 = 0xB0; /* Timer 0 initial value (Low Byte) */
TF0 = 0; /* Clear overflow flag */
TR0 = 1; /* Start timer 0 */
while (TF0 == 0); /* Loop until Timer 0 overflows (TF0 == 1) */
TR0 = 0; /* Stop Timer 0 */
}
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 123 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 124
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Example: Creating a portable hardware delay
/*-------------------------------------------------------------*-
Main.C (v1.00)
--------------------------------------------------------
Flashing LED with hardware-based delay (T0).
-*-------------------------------------------------------------*/
#include "Main.H"
#include "Port.H"
In this case, we assume - again - the standard 12 MHz / 12 #include "Delay_T0.h"
#include "LED_Flash.h"
oscillations-per-instruction microcontroller environment.
void main(void)
{
We require a 50 ms delay, so the timer requires the following LED_FLASH_Init();
number of increments before it overflows: while(1)
{
50ms /* Change the LED state (OFF to ON, or vice versa) */
× 1000000 = 50000 increments. LED_FLASH_Change_State();
1000 ms
/* Delay for *approx* 1000 ms */
DELAY_T0_Wait(1000);
The timer overflows when it is incremented from its maximum }
}
count of 65535.
/*-------------------------------------------------------------*-
---- END OF FILE ---------------------------------------
Thus, the initial value we need to load to produce a 50 ms delay is: -*-------------------------------------------------------------*/
65536 - 50000 = 15536 (decimal) = 0x3CB0
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 125 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 126
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
/* Timer preload values for use in simple (hardware) delays
- Timers are 16-bit, manual reload ('one shot').
NOTE: These values are portable but timings are *approximate*
and *must* be checked by hand if accurate timing is required.
Define Timer 0 / Timer 1 reload values for ~1 msec delay
NOTE: Adjustment made to allow for function call overheard etc. */
#define PRELOAD01 (65536 - (tWord)(OSC_FREQ / (OSC_PER_INST * 1020)))
#define PRELOAD01H (PRELOAD01 / 256)
#define PRELOAD01L (PRELOAD01 % 256)
/*-------------------------------------------------------------*/
void DELAY_T0_Wait(const tWord N)
{
tWord ms;
/* Configure Timer 0 as a 16-bit timer */
TMOD &= 0xF0; /* Clear all T0 bits (T1 left unchanged) */
TMOD |= 0x01; /* Set required T0 bits (T1 left unchanged) */
ET0 = 0; /* No interrupts */
/* Delay value is *approximately* 1 ms per loop */
for (ms = 0; ms < N; ms++)
{
TH0 = PRELOAD01H;
TL0 = PRELOAD01L;
TF0 = 0; /* Clear overflow flag */
TR0 = 1; /* Start timer 0 */
while (TF0 == 0); /* Loop until Timer 0 overflows (TF0 == 1) */
TR0 = 0; /* Stop Timer 0 */
}
}
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 127 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 128
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
The need for ‘timeout’ mechanisms - example Creating loop timeouts
The Philips 8Xc552 is an Extended 8051 device with a number of Basis of loop timeout:
on-chip peripherals, including an 8-channel, 10-bit ADC. Philips tWord Timeout_loop = 0;
provide an application note (AN93017) that describes how to use
...
this feature of the microcontroller.
while (++Timeout_loop);
This application note includes the following code:
/* Wait until AD conversion finishes (checking ADCI) */ Original ADC code:
while ((ADCON & ADCI) == 0);
/* Wait until AD conversion finishes (checking ADCI) */
Such code is potentially unreliable, because there are circumstances while ((ADCON & ADCI) == 0);
under which our application may ‘hang’. This might occur for one
or more of the following reasons: Modified version, with a loop timeout:
• If the ADC has been incorrectly initialised, we cannot be tWord Timeout_loop = 0;
sure that a data conversion will be carried out. /* Take sample from ADC
Wait until conversion finishes (checking ADCI)
• If the ADC has been subjected to an excessive input voltage, - simple loop timeout */
while (((ADCON & ADCI) == 0) && (++Timeout_loop != 0));
then it may not operate at all.
• If the variable ADCON or ADCI were not correctly Note that this alternative implementation is also useful:
initialised, they may not operate as required.
while (((ADCON & ADCI) == 0) && (Timeout_loop != 0))
{
Timeout_loop++; /* Disable for use in hardware simulator */
The Philips example is not intended to illustrate ‘production’ code. }
Unfortunately, however, code in this form is common in embedded
applications.
Two possible solutions: Loop timeouts and hardware timeouts.
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 129 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 130
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
/*-------------------------------------------------------------*-
TimeoutL.H (v1.00)
Example: Testing loop timeouts
-------------------------------------------------------- /*-------------------------------------------------------------*-
Simple software (loop) timeout delays for the 8051 family. Main.C (v1.00)
* THESE VALUES ARE NOT PRECISE - YOU MUST ADAPT TO YOUR SYSTEM * -*-------------------------------------------------------------*/
-*-------------------------------------------------------------*/ #include <reg52.H>
#ifndef _TIMEOUTL_H #include "TimeoutL.H"
#define _TIMEOUTL_H
/* Typedefs (see Chap 5) */
/* ------ Public constants ------------------------------------ */ typedef unsigned char tByte;
typedef unsigned int tWord;
/* Vary this value to change the loop duration typedef unsigned long tLong;
THESE ARE APPROX VALUES FOR VARIOUS TIMEOUT DELAYS
ON 8051, 12 MHz, 12 Osc / cycle /* Function prototypes */
void Test_Timeout(void);
*** MUST BE FINE TUNED FOR YOUR APPLICATION ***
/*-------------------------------------------------------------*/
*** Timings vary with compiler optimisation settings *** */ void main(void)
{
/* tWord */ while(1)
#define LOOP_TIMEOUT_INIT_001ms 65435 {
#define LOOP_TIMEOUT_INIT_010ms 64535 Test_Timeout();
#define LOOP_TIMEOUT_INIT_500ms 14535 }
/* tLong */ }
#define LOOP_TIMEOUT_INIT_10000ms 4294795000UL
/*-------------------------------------------------------------*/
#endif void Test_Timeout(void)
{
/*-------------------------------------------------------------*- tLong Timeout_loop = LOOP_TIMEOUT_INIT_10000ms;
---- END OF FILE ---------------------------------------
-*-------------------------------------------------------------*/ /* Simple loop timeout... */
while (++Timeout_loop != 0);
}
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 131 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 132
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Example: A more reliable switch interface
bit SWITCH_Get_Input(const tByte DEBOUNCE_PERIOD)
{
tByte Return_value = SWITCH_NOT_PRESSED;
tLong Timeout_loop = LOOP_TIMEOUT_INIT_10000ms;
if (Switch_pin == 0)
{
/* Switch is pressed */
/* Debounce - just wait... */
DELAY_T0_Wait(DEBOUNCE_PERIOD);
/* Check switch again */
if (Switch_pin == 0)
{
/* Wait until the switch is released.
(WITH TIMEOUT LOOP - 10 seconds) */
while ((Switch_pin == 0) && (++Timeout_loop != 0));
/* Check for timeout */
if (Timeout_loop == 0)
{
Return_value = SWITCH_NOT_PRESSED;
}
else
{
Return_value = SWITCH_PRESSED;
}
}
}
/* Now (finally) return switch value */
return Return_value;
}
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 133 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 134
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
/*-------------------------------------------------------------*-
Creating hardware timeouts TimeoutH.H (v1.00)
/* Configure Timer 0 as a 16-bit timer */ -*-------------------------------------------------------------*/
TMOD &= 0xF0; /* Clear all T0 bits (T1 left unchanged) */
TMOD |= 0x01; /* Set required T0 bits (T1 left unchanged) */ #ifndef _TIMEOUTH_H
#define _TIMEOUTH_H
ET0 = 0; /* No interrupts */
/* ------ Public constants ------------------------------------ */
/* Simple timeout feature - approx 10 ms */
TH0 = PRELOAD_10ms_H; /* See Timeout.H for PRELOAD details */ /* Timer T_ values for use in simple (hardware) timeouts */
TL0 = PRELOAD_10ms_L; - Timers are 16-bit, manual reload ('one shot'). */
TF0 = 0; /* Clear flag */
TR0 = 1; /* Start timer */ NOTE: These macros are portable but timings are *approximate*
and *must* be checked by hand for accurate timing. */
while (((ADCON & ADCI) == 0) && !TF0);
/* Define initial Timer 0 / Timer 1 values for ~50 µs delay */
#define T_50micros (65536 - (tWord)((OSC_FREQ /
26000)/(OSC_PER_INST)))
#define T_50micros_H (T_50micros / 256)
#define T_50micros_L (T_50micros % 256)
...
/* Define initial Timer 0 / Timer 1 values for ~10 msec delay */
#define T_10ms (65536 - (tWord)(OSC_FREQ / (OSC_PER_INST * 100)))
#define T_10ms_H (T_10ms / 256)
#define T_10ms_L (T_10ms % 256)
/* Define initial Timer 0 / Timer 1 values for ~15 msec delay */
#define T_15ms (65536 - (tWord)(OSC_FREQ / (OSC_PER_INST * 67)))
#define T_15ms_H (T_15ms / 256)
#define T_15ms_L (T_15ms % 256)
/* Define initial Timer 0 / Timer 1 values for ~20 msec delay */
#define T_20ms (65536 - (tWord)(OSC_FREQ / (OSC_PER_INST * 50)))
#define T_20ms_H (T_20ms / 256)
#define T_20ms_L (T_20ms % 256)
/* Define initial Timer 0 / Timer 1 values for ~50 msec delay */
#define T_50ms (65536 - (tWord)(OSC_FREQ / (OSC_PER_INST * 20)))
#define T_50ms_H (T_50ms / 256)
#define T_50ms_L (T_50ms % 256)
#endif
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 135 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 136
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Conclusions Preparation for the next seminar
The delay and timeout considered in this seminar are widely used in
embedded applications.
Please read Chapter 7
In the next seminar we go on to consider another key software before the next seminar
component in many embedded applications: the operating system.
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 137 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 138
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Introduction
void main(void)
{
/* Prepare run function X */
Seminar 6: X_Init();
while(1) /* 'for ever' (Super Loop) */
Creating an Embedded {
X(); /* Run function X */
}
Operating System }
A particular limitation with this architecture is that it is very
difficult to execute function X() at precise intervals of time: as we
will see, this is a very significant drawback.
Determine flow rate from pulse stream
For example …
Milk
Milkpasteurisation
pasteurisationsystem
system
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 139 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 140
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 141
Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Timer-based interrupts (the core of an embedded OS)
void main(void)
{ #define INTERRUPT_Timer_2_Overflow 5
...
Init_System();
void main(void)
while(1) /* 'for ever' (Super Loop) */ {
{ Timer_2_Init(); /* Set up Timer 2 */
X(); /* Call the function (10 ms duration) */
Delay_50ms(); /* Delay for 50 ms */ EA = 1; /* Globally enable interrupts */
}
} while(1); /* An empty Super Loop */
}
void Timer_2_Init(void)
This will be fine, if: {
/* Timer 2 is configured as a 16-bit timer,
1. We know the precise duration of function X(), and, which is automatically reloaded when it overflows
This code (generic 8051/52) assumes a 12 MHz system osc.
2. This duration never varies. The Timer 2 resolution is then 1.000 µs
Reload value is FC18 (hex) = 64536 (decimal)
Timer (16-bit) overflows when it reaches 65536 (decimal)
Thus, with these setting, timer will overflow every 1 ms */
T2CON = 0x04; /* Load T2 control register */
TH2 = 0xFC; /* Load T2 high byte */
RCAP2H = 0xFC; /* Load T2 reload capt. reg. high byte */
TL2 = 0x18; /* Load T2 low byte */
RCAP2L = 0x18; /* Load T2 reload capt. reg. low byte */
/* Timer 2 interrupt is enabled, and ISR will be called
whenever the timer overflows - see below. */
ET2 = 1;
/* Start Timer 2 running */
TR2 = 1;
}
void X(void) interrupt INTERRUPT_Timer_2_Overflow
{
/* This ISR is called every 1 ms */
/* Place required code here... */
}
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 143 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 144
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
The interrupt service routine (ISR) Automatic timer reloads
/* Preload values for 50 ms delay */
TH0 = 0x3C; /* Timer 0 initial value (High Byte) */
The interrupt generated by the overflow of Timer 2, invokes the TL0 = 0xB0; /* Timer 0 initial value (Low Byte) */
ISR: TF0 = 0; /* Clear overflow flag */
TR0 = 1; /* Start timer 0 */
/* --------------------------------------------------------------- */
void X(void) interrupt INTERRUPT_Timer_2_Overflow while (TF0 == 0); /* Loop until Timer 0 overflows (TF0 == 1) */
{
/* This ISR is called every 1 ms */ TR0 = 0; /* Stop Timer 0 */
/* Place required code here... */
}
For our operating system, we have slightly different requirements:
The link between this function and the timer overflow is made using • We require a long series of interrupts, at precisely-
the Keil keyword interrupt: determined intervals.
void X(void) interrupt INTERRUPT_Timer_2_Overflow • We would like to generate these interrupts without imposing
a significant load on the CPU.
…plus the following #define directive:
#define INTERRUPT_Timer_2_Overflow 5 Timer 2 matches these requirements precisely.
In this case, the timer is reloaded using the contents of the ‘capture’
Interrupt source Address IE Index registers (note that the names of these registers vary slightly
Power On Reset 0x00 - between chip manufacturers):
External Interrupt 0 0x03 0 RCAP2H = 0xFC; /* Load T2 reload capt. reg. high byte */
RCAP2L = 0x18; /* Load T2 reload capt. reg. low byte */
Timer 0 Overflow 0x0B 1
External Interrupt 1 0x13 2
Timer 1 Overflow 0x1B 3
This automatic reload facility ensures that the timer keeps
generating the required ticks, at precise 1 ms intervals, with very
UART Receive/Transmit 0x23 4
little software load, and without any intervention from the user’s
Timer 2 Overflow 0x2B 5
program.
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 145 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 146
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Introducing sEOS Introducing sEOS
See “Embedded C”, Chapter 7
void main(void)
{
Init_System(); /*--------------------------------------------------------*-
while(1) /* 'for ever' (Super Loop) */ Main.c (v1.00)
{
X(); /* Call the function (10 ms duration) */ ---------------------------------------------------
Delay_50ms(); /* Delay for 50 ms */
} Demonstration of sEOS running a dummy task.
}
-*--------------------------------------------------------*/
#include "Main.H"
#include "Port.H"
In this case: #include "Simple_EOS.H"
• We use a Super Loop and delay code #include "X.H"
/* ----------------------------------------------------- */
• We call X() every 60 ms - approximately.
void main(void)
{
/* Prepare for dummy task */
X_Init();
Now let’s look at a better way of doing this …
/* Set up simple EOS (60 ms tick interval) */
sEOS_Init_Timer2(60);
while(1) /* Super Loop */
{
/* Enter idle mode to save power */
sEOS_Go_To_Sleep();
}
}
/*--------------------------------------------------------*-
---- END OF FILE ----------------------------------
-*--------------------------------------------------------*/
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 147 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 148
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
/*--------------------------------------------------------*- /*--------------------------------------------------------*-
Simple_EOS.C (v1.00) sEOS_Init_Timer2()
--------------------------------------------------- -*--------------------------------------------------------*/
void sEOS_Init_Timer2(const tByte TICK_MS)
Main file for Simple Embedded Operating System (sEOS). {
tLong Inc;
Demonstration version with dummy task X(). tWord Reload_16;
tByte Reload_08H, Reload_08L;
-*--------------------------------------------------------*/
/* Timer 2 is configured as a 16-bit timer,
#include "Main.H" which is automatically reloaded when it overflows */
#include "Simple_EOS.H" T2CON = 0x04; /* Load T2 control register */
/* Header for dummy task */ /* Number of timer increments required (max 65536) */
#include "X.H" Inc = ((tLong)TICK_MS * (OSC_FREQ/1000)) /
(tLong)OSC_PER_INST;
/*--------------------------------------------------------*-
/* 16-bit reload value */
sEOS_ISR() Reload_16 = (tWord) (65536UL - Inc);
Invoked periodically by Timer 2 overflow: /* 8-bit reload values (High & Low) */
see sEOS_Init_Timer2() for timing details. Reload_08H = (tByte)(Reload_16 / 256);
Reload_08L = (tByte)(Reload_16 % 256);
-*--------------------------------------------------------*/
sEOS_ISR() interrupt INTERRUPT_Timer_2_Overflow /* Used for manually checking timing (in simulator) */
{ /*P2 = Reload_08H; */
/* Must manually reset the T2 flag */ /*P3 = Reload_08L; */
TF2 = 0;
TH2 = Reload_08H; /* Load T2 high byte */
/*===== USER CODE - Begin ============================= */ RCAP2H = Reload_08H; /* Load T2 reload capt. reg h byte */
TL2 = Reload_08L; /* Load T2 low byte */
/* Call dummy task here */ RCAP2L = Reload_08L; /* Load T2 reload capt. reg l byte */
X();
/* Timer 2 interrupt is enabled, and ISR will be called
/*===== USER CODE - End =============================== */ whenever the timer overflows. */
} ET2 = 1;
/* Start Timer 2 running */
TR2 = 1;
EA = 1; /* Globally enable interrupts */
}
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 149 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 150
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
/*--------------------------------------------------------*-
/*--------------------------------------------------------*-
sEOS_Go_To_Sleep()
X.C (v1.00)
This operating system enters 'idle mode' between clock ticks
to save power. The next clock tick will return processor ---------------------------------------------------
to the normal operating state.
Dummy task to introduce sEOS.
-*--------------------------------------------------------*/
void sEOS_Go_To_Sleep(void) -*--------------------------------------------------------*/
{
PCON |= 0x01; /* Enter idle mode (generic 8051 version) */ #include "X.H"
}
/*--------------------------------------------------------*-
/*--------------------------------------------------------*-
---- END OF FILE ---------------------------------- X_Init()
-*--------------------------------------------------------*/
Dummy task init function.
-*--------------------------------------------------------*/
void X_Init(void)
{
/* Dummy task init... */
}
/*--------------------------------------------------------*-
X()
Dummy task called from sEOS ISR.
-*--------------------------------------------------------*/
void X(void)
{
/* Dummy task... */
}
/*--------------------------------------------------------*-
---- END OF FILE ----------------------------------
-*--------------------------------------------------------*/
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 151 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 152
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Tasks, functions and scheduling Setting the tick interval
• In discussions about embedded systems, you will frequently In the function main(), we can see that the control of the tick
hear and read about ‘task design’, ‘task execution times’ and interval has been largely automated:
‘multi-tasking’ systems. /* Set up simple EOS (60 ms tick interval) */
sEOS_Init_Timer2(60);
• In this context, the term ‘task’ is usually used to refer to a In this example, a tick interval of 60 ms is used: this means that the
function that is executed on a periodic basis. ISR (the ‘update’ function) at the heart of sEOS will be invoked
every 60 ms:
• In the case of sEOS, the tasks will be implemented using /*--------------------------------------------------------*-
functions which are called from the timer-driven sEOS_ISR()
interrupt service routine.
Invoked periodically by Timer 2 overflow:
see sEOS_Init_Timer2() for timing details.
-*--------------------------------------------------------*/
sEOS_ISR() interrupt INTERRUPT_Timer_2_Overflow
{
…
}
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 153 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 154
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
The ‘automatic’ tick interval control is achieved using the C pre- • If using a 12 MHz oscillator, then accurate timing can
processor, and the information included in the project header file usually be obtained over a range of tick intervals from 1 ms
(Main.H): to 60 ms (approximately).
/* Oscillator / resonator frequency (in Hz) e.g. (11059200UL) */ • If using other clock frequencies (e.g. 11.0592 MHz), precise
#define OSC_FREQ (12000000UL)
timing can only be obtained at a much more limited range of
/* Number of oscillations per instruction (12, etc) */
...
tick intervals.
#define OSC_PER_INST (12)
• If you are developing an application where precise timing is
This information is then used to calculate the required timer reload required, you must check the timing calculations by hand.
values in Simple_EOS.C as follows:
/* Used for manually checking timing (in simulator) */
/* Number of timer increments required (max 65536) */ P2 = Reload_08H;
Inc = ((tLong)TICK_MS * (OSC_FREQ/1000)) / (tLong)OSC_PER_INST; P3 = Reload_08L;
/* 16-bit reload value */
Reload_16 = (tWord) (65536UL - Inc);
/* 8-bit reload values (High & Low) */
Reload_08H = (tByte)(Reload_16 / 256);
Reload_08L = (tByte)(Reload_16 % 256);
…
TH2 = Reload_08H; /* Load T2 high byte */
RCAP2H = Reload_08H; /* Load T2 reload capt. reg h byte */
TL2 = Reload_08L; /* Load T2 low byte */
RCAP2L = Reload_08L; /* Load T2 reload capt. reg l byte */
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 155 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 156
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Saving power Using sEOS in your own projects
Using sEOS, we can reduce the power consumption of the When using sEOS in your own applications, you will need to
application by having the processor enter idle mode when it finishes include a copy of the files Simple_EOS.C and Simple_EOS.H in your
executing the ISR. project: the .C file will then need to be edited - in the area indicated
below - in order to match your requirements:
This is achieved through the function sEOS_Go_To_Sleep(): sEOS_ISR() interrupt INTERRUPT_Timer_2_Overflow
{
/*--------------------------------------------------------*-
/* Must manually reset the T2 flag */
TF2 = 0;
sEOS_Go_To_Sleep()
/*===== USER CODE - Begin ============================= */
This operating system enters 'idle mode' between clock ticks
to save power. The next clock tick will return processor /* ADD YOUR FUNCTION (TASK) CALLS HERE... */
to the normal operating state.
/*===== USER CODE - End =============================== */
-*--------------------------------------------------------*/ }
void sEOS_Go_To_Sleep(void)
{
PCON |= 0x01; /* Enter idle mode (generic 8051 version) */
}
Note that the processor will automatically return to ‘Normal’ mode
when the timer next overflows (generating an interrupt).
Device Normal Idle Power Down
Atmel 89S53 11 mA 2 mA 60 µA
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 157 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 158
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Is this approach portable? Example: Milk pasteurization
• The presence of an on-chip timer which can be used to
generate interrupts in this way is by no means restricted to
the 8051 family: almost all processors intended for use in Determine flow rate from pulse stream
embedded applications have timers which can be used in a
manner very similar to that described here.
• For example, similar timers are included on other 8-bit
microcontrollers (e.g. Microchip PIC family, the Motorola
HC08 family), and also on 16-bit devices (e.g. the Infineon Milk
Milkpasteurisation
pasteurisationsystem
system
C167 family) as well as on 32-bit processors (e.g. the ARM
family, the Motorola MPC500 family).
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 159 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 160
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
/*-------------------------------------------------------------*- /*-------------------------------------------------------------*-
Port.H (v1.00) Main.c (v1.00)
-------------------------------------------------------- --------------------------------------------------------
Port Header file for the milk pasteurization example Milk pasteurization example.
(“Embedded C” Chapter 7)
-*-------------------------------------------------------------*/
-*-------------------------------------------------------------*/
#include "Main.H"
/* ------ Pulse_Count.C ---------------------------------- */ #include "Port.H"
#include "Simple_EOS.H"
/* Connect pulse input to this pin - debounced in software */ #include "Bargraph.H"
sbit Sw_pin = P3^0;
#include "Pulse_Count.H"
/* Connect alarm to this pin (set if pulse is below threshold) */
sbit Alarm_pin = P3^7; /* --------------------------------------------------------------- */
/* ------ Bargraph.C -------------------------------------- */ void main(void)
{
/* Bargraph display on these pins (the 8 port pins may be PULSE_COUNT_Init();
distributed over several ports, if required). */ BARGRAPH_Init();
sbit Pin0 = P1^0;
sbit Pin1 = P1^1; /* Set up simple EOS (30ms tick interval) */
sbit Pin2 = P1^2; sEOS_Init_Timer2(30);
sbit Pin3 = P1^3;
sbit Pin4 = P1^4; while(1) /* Super Loop */
sbit Pin5 = P1^5; {
sbit Pin6 = P1^6; /* Enter idle mode to save power */
sbit Pin7 = P1^7; sEOS_Go_To_Sleep();
}
}
/*-------------------------------------------------------------*-
---- END OF FILE --------------------------------------- /*-------------------------------------------------------------*-
-*-------------------------------------------------------------*/ ---- END OF FILE ---------------------------------------
-*-------------------------------------------------------------*/
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 161 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 162
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
/*-------------------------------------------------------------*- /*-------------------------------------------------------------*-
Simple_EOS.C (v1.00) sEOS_Init_Timer2()
-------------------------------------------------------- ...
Main file for Simple Embedded Operating System (sEOS) for 8051. -*-------------------------------------------------------------*/
void sEOS_Init_Timer2(const tByte TICK_MS)
-- This version for milk-flow-rate monitoring. {
tLong Inc;
-*-------------------------------------------------------------*/ tWord Reload_16;
tByte Reload_08H, Reload_08L;
#include "Main.H"
#include "Simple_EOS.H" /* Timer 2 is configured as a 16-bit timer,
which is automatically reloaded when it overflows */
#include "Pulse_count.H" T2CON = 0x04; /* Load T2 control register */
/* Number of timer increments required (max 65536) */
/*-------------------------------------------------------------*- Inc = ((tLong)TICK_MS * (OSC_FREQ/1000)) / (tLong)OSC_PER_INST;
sEOS_ISR() /* 16-bit reload value */
Reload_16 = (tWord) (65536UL - Inc);
Invoked periodically by Timer 2 overflow:
see sEOS_Init_Timer2() for timing details. /* 8-bit reload values (High & Low) */
Reload_08H = (tByte)(Reload_16 / 256);
-*-------------------------------------------------------------*/ Reload_08L = (tByte)(Reload_16 % 256);
sEOS_ISR() interrupt INTERRUPT_Timer_2_Overflow
{ /* Used for manually checking timing (in simulator) */
/* Must manually reset the T2 flag */ /*P2 = Reload_08H; */
TF2 = 0; /*P3 = Reload_08L; */
/*===== USER CODE - Begin ================================== */ TH2 = Reload_08H; /* Load T2 high byte */
RCAP2H = Reload_08H; /* Load T2 reload capt. reg. high byte */
/* Call 'Update' function here */ TL2 = Reload_08L; /* Load T2 low byte */
PULSE_COUNT_Update(); RCAP2L = Reload_08L; /* Load T2 reload capt. reg. low byte */
/*===== USER CODE - End ==================================== */ /* Timer 2 interrupt is enabled, and ISR will be called
} whenever the timer overflows. */
ET2 = 1;
/* Start Timer 2 running */
TR2 = 1;
EA = 1; /* Globally enable interrupts */
}
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 163 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 164
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
/*-------------------------------------------------------------*- /*-------------------------------------------------------------*-
sEOS_Go_To_Sleep() Pulse_Count.C (v1.00)
This operating system enters 'idle mode' between clock ticks --------------------------------------------------------
to save power. The next clock tick will return the processor
to the normal operating state. Count pulses from a mechanical switch or similar device.
___
-*-------------------------------------------------------------*/ Responds to falling edge of pulse: |___
void sEOS_Go_To_Sleep(void)
{ -*-------------------------------------------------------------*/
PCON |= 0x01; /* Enter idle mode (generic 8051 version) */
} #include "Main.H"
#include "Port.H"
/*-------------------------------------------------------------*-
---- END OF FILE --------------------------------------- #include "Bargraph.H"
-*-------------------------------------------------------------*/ #include "Pulse_Count.H"
/* ------ Private function prototypes ------------------------- */
void PULSE_COUNT_Check_Below_Threshold(const tByte);
/* ------ Public variable declarations ------------------------ */
/* The data to be displayed */
extern tBargraph Data_G;
/* ------ Public variable definitions -------------------------- */
/* Set only after falling edge is detected */
bit Falling_edge_G;
/* ------ Private variable definitions ------------------------- */
/* The results of successive tests of the pulse signal */
/* (NOTE: Can't have arrays of bits...) */
static bit Test4, Test3, Test2, Test1, Test0;
static tByte Total_G = 0;
static tWord Calls_G = 0;
/* ------ Private constants ----------------------------------- */
/* Allows changed of logic without hardware changes */
#define HI_LEVEL (0)
#define LO_LEVEL (1)
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 165 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 166
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
/*-------------------------------------------------------------*-
/*-------------------------------------------------------------*-
PULSE_COUNT_Update()
PULSE_COUNT_Init()
This is the main switch function.
Initialisation function for the switch library.
It should be called every 30 ms
-*-------------------------------------------------------------*/ (to allow for typical 20ms debounce time).
void PULSE_COUNT_Init(void)
{ -*-------------------------------------------------------------*/
Sw_pin = 1; /* Use this pin for input */ void PULSE_COUNT_Update(void)
{
/* The tests (see text) */ /* Clear timer flag */
Test4 = LO_LEVEL; TF2 = 0;
Test3 = LO_LEVEL;
Test2 = LO_LEVEL; /* Shuffle the test results */
Test1 = LO_LEVEL; Test4 = Test3;
Test0 = LO_LEVEL; Test3 = Test2;
} Test2 = Test1;
Test1 = Test0;
/*-------------------------------------------------------------*-
/* Get latest test result */
PULSE_COUNT_Check_Below_Threshold() Test0 = Sw_pin;
Checks to see if pulse count is below a specified /* Required result:
threshold value. If it is, the alarm is sounded. Test4 == HI_LEVEL
Test3 == HI_LEVEL
-*-------------------------------------------------------------*/ Test1 == LO_LEVEL
void PULSE_COUNT_Check_Below_Threshold(const tByte THRESHOLD) Test0 == LO_LEVEL */
{
if (Data_G < THRESHOLD) if ((Test4 == HI_LEVEL) &&
{ (Test3 == HI_LEVEL) &&
Alarm_pin = 0; (Test1 == LO_LEVEL) &&
} (Test0 == LO_LEVEL))
else {
{ /* Falling edge detected */
Alarm_pin = 1; Falling_edge_G = 1;
} }
} else
{
/* Default */
Falling_edge_G = 0;
}
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 167 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 168
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
/* Calculate average every 45 calls to this task /*-------------------------------------------------------------*-
- maximum count over this period is 9 pulses
if (++Calls_G < 45) */ Bargraph.h (v1.00)
/* 450 used here for test purposes (in simulator) --------------------------------------------------------
[Because there is a limit to how fast you can simulate pulses
by hand...] */ - See Bargraph.c for details.
if (++Calls_G < 450)
{ -*-------------------------------------------------------------*/
Total_G += (int) Falling_edge_G;
} #include "Main.h"
else
{ /* ------ Public data type declarations ----------------------- */
/* Update the display */
Data_G = Total_G; /* Max is 9 */ typedef tByte tBargraph;
Total_G = 0;
Calls_G = 0; /* ------ Public function prototypes -------------------------- */
PULSE_COUNT_Check_Below_Threshold(3);
BARGRAPH_Update(); void BARGRAPH_Init(void);
} void BARGRAPH_Update(void);
}
/* ------ Public constants ------------------------------------ */
/*-------------------------------------------------------------*-
---- END OF FILE --------------------------------------- #define BARGRAPH_MAX (9)
-*-------------------------------------------------------------*/ #define BARGRAPH_MIN (0)
/*-------------------------------------------------------------*-
---- END OF FILE ---------------------------------------
-*-------------------------------------------------------------*/
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 169 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 170
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
/*-------------------------------------------------------------*- /*-------------------------------------------------------------*-
Bargraph.c (v1.00) BARGRAPH_Init()
-------------------------------------------------------- Prepare for the bargraph display.
Simple bargraph library. -*-------------------------------------------------------------*/
void BARGRAPH_Init(void)
-*-------------------------------------------------------------*/ {
Pin0 = BARGRAPH_OFF;
#include "Main.h" Pin1 = BARGRAPH_OFF;
#include "Port.h" Pin2 = BARGRAPH_OFF;
Pin3 = BARGRAPH_OFF;
#include "Bargraph.h" Pin4 = BARGRAPH_OFF;
Pin5 = BARGRAPH_OFF;
/* ------ Public variable declarations ------------------------ */ Pin6 = BARGRAPH_OFF;
Pin7 = BARGRAPH_OFF;
/* The data to be displayed */
tBargraph Data_G; /* Use a linear scale to display data
Remember: *9* possible output states
/* ------ Private constants ----------------------------------- */ - do all calculations ONCE */
M9_1_G = (BARGRAPH_MAX - BARGRAPH_MIN) / 9;
#define BARGRAPH_ON (1) M9_2_G = M9_1_G * 2;
#define BARGRAPH_OFF (0) M9_3_G = M9_1_G * 3;
M9_4_G = M9_1_G * 4;
/* ------ Private variables ----------------------------------- */ M9_5_G = M9_1_G * 5;
M9_6_G = M9_1_G * 6;
/* These variables store the thresholds M9_7_G = M9_1_G * 7;
used to update the display */ M9_8_G = M9_1_G * 8;
static tBargraph M9_1_G; }
static tBargraph M9_2_G;
static tBargraph M9_3_G;
static tBargraph M9_4_G;
static tBargraph M9_5_G;
static tBargraph M9_6_G;
static tBargraph M9_7_G;
static tBargraph M9_8_G;
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 171 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 172
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
/*-------------------------------------------------------------*- Conclusions
BARGRAPH_Update()
• The simple operating system (‘sEOS’) introduced in this
Update the bargraph display.
seminar imposes a very low processor load but is nonetheless
-*-------------------------------------------------------------*/ flexible and useful.
void BARGRAPH_Update(void)
{
tBargraph Data = Data_G - BARGRAPH_MIN;
• The simple nature of sEOS also provides other benefits. For
Pin0 = ((Data >= M9_1_G) == BARGRAPH_ON);
Pin1 = ((Data >= M9_2_G) == BARGRAPH_ON); example, it means that developers themselves can, very
Pin2 = ((Data >= M9_3_G) == BARGRAPH_ON); rapidly, port the OS onto a new microcontroller
Pin3 = ((Data >= M9_4_G) == BARGRAPH_ON);
Pin4 = ((Data >= M9_5_G) == BARGRAPH_ON); environment. It also means that the architecture may be
Pin5
Pin6
=
=
((Data
((Data
>=
>=
M9_6_G)
M9_7_G)
==
==
BARGRAPH_ON);
BARGRAPH_ON);
readily adapted to meet the needs of a particular application.
Pin7 = ((Data >= M9_8_G) == BARGRAPH_ON);
}
/*-------------------------------------------------------------*- Perhaps the most important side-effect of this form of simple OS is that
---- END OF FILE ---------------------------------------
-*-------------------------------------------------------------*/
- unlike a traditional ‘real-time operating system’ - it becomes part of the
application itself, rather than forming a separate code layer.
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 173 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 174
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Preparation for the next seminar
Please read Chapter 8
before the next seminar
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 175 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 176
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Seminar 7:
Multi-State Systems
and Function
Sequences
Sleeping
Sleeping
Waking
Waking Attacking
Attacking
Growling
Growling
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 177
Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
For completeness, we will mention on further possibility:
Implementing a Multi-State (Timed) system
• Multi-State (Input)
This is a comparatively rare form of system, in which the We can describe the time-driven, multi-state architecture as follows:
transition between states (and behaviour in each state)
• The system will operate in two or more states.
depends only on the system inputs.
• Each state may be associated with one or more function
For example, the system might only move between State A calls.
and State B if a particular input is received. It will remain
• Transitions between states will be controlled by the passage
indefinitely in State A if this input is not received.
of time.
Such systems have no concept of time, and - therefore - no • Transitions between states may also involve function calls.
way of implementing timeout or similar behaviours. We will
not consider such systems in this course.
Please note that, in order to ease subsequent maintenance tasks, the
system states should not be arbitrarily named, but should - where
In this seminar, we will consider how the Multi-State (Time) and possible - reflect a physical state observable by the user and / or
Multi-State (Input / Time) architectures can be implemented in C. developer.
Please also note that the system states will usually be represented
by means of a switch statement in the operating system ISR.
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 179 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 180
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Example: Traffic light sequencing
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 181
Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
/*-------------------------------------------------------------*-
In this simple case, we do not require function calls from (or Main.c (v1.00)
between) system states: the required behaviour will be implemented --------------------------------------------------------
directly through control of the (three) port pins which – in the final
Traffic light example.
system – would be connected to appropriate bulbs.
-*-------------------------------------------------------------*/
For example: #include "Main.H"
#include "Port.H"
case RED: #include "Simple_EOS.H"
{
Red_light = ON; #include "T_Lights.H"
Amber_light = OFF;
Green_light = OFF; /* --------------------------------------------------------------- */
... void main(void)
{
/* Prepare to run traffic sequence */
TRAFFIC_LIGHTS_Init(RED);
/* Set up simple EOS (50 ms ticks) */
sEOS_Init_Timer2(50);
while(1) /* Super Loop */
{
/* Enter idle mode to save power */
sEOS_Go_To_Sleep();
}
}
/*-------------------------------------------------------------*-
---- END OF FILE ---------------------------------------
-*-------------------------------------------------------------*/
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 183 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 184
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
/*-------------------------------------------------------------*- /*-------------------------------------------------------------*-
T_Lights.H (v1.00) T_lights.C (v1.00)
-------------------------------------------------------- -*-------------------------------------------------------------*/
- See T_Lights.C for details. #include "Main.H"
#include "Port.H"
-*-------------------------------------------------------------*/
#include "T_lights.H"
#ifndef _T_LIGHTS_H
#define _T_LIGHTS_H /* ------ Private constants ----------------------------------- */
/* ------ Public data type declarations ----------------------- */ /* Easy to change logic here */
#define ON 0
/* Possible system states */ #define OFF 1
typedef enum {RED, RED_AND_AMBER, GREEN, AMBER} eLight_State;
/* Times in each of the (four) possible light states
/* ------ Public function prototypes -------------------------- */ (Times are in seconds) */
#define RED_DURATION 20
void TRAFFIC_LIGHTS_Init(const eLight_State); #define RED_AND_AMBER_DURATION 5
void TRAFFIC_LIGHTS_Update(void); #define GREEN_DURATION 30
#define AMBER_DURATION 5
#endif
/*-------------------------------------------------------------*- /* ------ Private variables ----------------------------------- */
---- END OF FILE ---------------------------------------
-*-------------------------------------------------------------*/ /* The state of the system */
static eLight_State Light_state_G;
/* The time in that state */
static tLong Time_in_state;
/* Used by sEOS */
static tByte Call_count_G = 0;
/*-------------------------------------------------------------*-
TRAFFIC_LIGHTS_Init()
Prepare for traffic light activity.
-*-------------------------------------------------------------*/
void TRAFFIC_LIGHTS_Init(const eLight_State START_STATE)
{
Light_state_G = START_STATE; /* Decide on initial state */
}
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 185 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 186
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
/*-------------------------------------------------------------*-
case GREEN:
TRAFFIC_LIGHTS_Update() {
Red_light = OFF;
Must be called once per second. Amber_light = OFF;
Green_light = ON;
-*-------------------------------------------------------------*/
void TRAFFIC_LIGHTS_Update(void) if (++Time_in_state == GREEN_DURATION)
{ {
switch (Light_state_G) Light_state_G = AMBER;
{ Time_in_state = 0;
case RED: }
{
Red_light = ON; break;
Amber_light = OFF; }
Green_light = OFF;
case AMBER:
if (++Time_in_state == RED_DURATION) {
{ Red_light = OFF;
Light_state_G = RED_AND_AMBER; Amber_light = ON;
Time_in_state = 0; Green_light = OFF;
}
if (++Time_in_state == AMBER_DURATION)
break; {
} Light_state_G = RED;
Time_in_state = 0;
case RED_AND_AMBER: }
{
Red_light = ON; break;
Amber_light = ON; }
Green_light = OFF; }
}
if (++Time_in_state == RED_AND_AMBER_DURATION)
{ /*-------------------------------------------------------------*-
Light_state_G = GREEN; ---- END OF FILE ---------------------------------------
Time_in_state = 0; -*-------------------------------------------------------------*/
}
break;
}
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 187 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 188
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Example: Animatronic dinosaur
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 189
Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
/*-------------------------------------------------------------*- /*-------------------------------------------------------------*-
DINOSAUR_Init()
Dinosaur.C (v1.00) -*-------------------------------------------------------------*/
void DINOSAUR_Init(void)
-------------------------------------------------------- {
/* Initial dinosaur state */
Demonstration of multi-state (timed) architecture: Dinosaur_state_G = SLEEPING;
Dinosaur control system. }
-*-------------------------------------------------------------*/ /*-------------------------------------------------------------*-
#include "Main.h" DINOSAUR_Update()
#include "Port.h"
Must be scheduled once per second (from the sEOS ISR).
#include "Dinosaur.h"
-*-------------------------------------------------------------*/
/* ------ Private data type declarations ---------------------- */ void DINOSAUR_Update(void)
/* Possible system states */ {
typedef switch (Dinosaur_state_G)
enum {SLEEPING, WAKING, GROWLING, ATTACKING} eDinosaur_State; {
case SLEEPING:
/* ------ Private function prototypes ------------------------- */ {
void DINOSAUR_Perform_Sleep_Movements(void); /* Call relevant function */
void DINOSAUR_Perform_Waking_Movements(void); DINOSAUR_Perform_Sleep_Movements();
void DINOSAUR_Growl(void);
void DINOSAUR_Perform_Attack_Movements(void); if (++Time_in_state_G == SLEEPING_DURATION)
{
/* ------ Private constants ----------------------------------- */ Dinosaur_state_G = WAKING;
/* Times in each of the (four) possible states Time_in_state_G = 0;
(Times are in seconds) */ }
#define SLEEPING_DURATION 255
#define WAKING_DURATION 60 break;
#define GROWLING_DURATION 40 }
#define ATTACKING_DURATION 120
case WAKING:
/* ------ Private variables ----------------------------------- */ {
/* The current state of the system */ DINOSAUR_Perform_Waking_Movements();
static eDinosaur_State Dinosaur_state_G;
if (++Time_in_state_G == WAKING_DURATION)
/* The time in the state */ {
static tByte Time_in_state_G; Dinosaur_state_G = GROWLING;
Time_in_state_G = 0;
/* Used by sEOS */ }
static tByte Call_count_G = 0;
break;
}
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 191 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 192
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
case GROWLING:
{ /*-------------------------------------------------------------*/
/* Call relevant function */ void DINOSAUR_Perform_Sleep_Movements(void)
DINOSAUR_Growl(); {
/* Demo only... */
if (++Time_in_state_G == GROWLING_DURATION) P1 = (tByte) Dinosaur_state_G;
{ P2 = Time_in_state_G;
Dinosaur_state_G = ATTACKING; }
Time_in_state_G = 0;
} /*-------------------------------------------------------------*/
void DINOSAUR_Perform_Waking_Movements(void)
break; {
} /* Demo only... */
P1 = (tByte) Dinosaur_state_G;
case ATTACKING: P2 = Time_in_state_G;
{ }
/* Call relevant function */
DINOSAUR_Perform_Attack_Movements(); /*-------------------------------------------------------------*/
void DINOSAUR_Growl(void)
if (++Time_in_state_G == ATTACKING_DURATION) {
{ /* Demo only... */
Dinosaur_state_G = SLEEPING; P1 = (tByte) Dinosaur_state_G;
Time_in_state_G = 0; P2 = Time_in_state_G;
} }
break; /*-------------------------------------------------------------*/
} void DINOSAUR_Perform_Attack_Movements(void)
} {
} /* Demo only... */
P1 = (tByte) Dinosaur_state_G;
P2 = Time_in_state_G;
}
/*-------------------------------------------------------------*-
---- END OF FILE ---------------------------------------
-*-------------------------------------------------------------*/
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 193 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 194
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Implementing a Multi-State (Input/Timed) system Implementing state timeouts
• The system will operate in two or more states. Consider the following - informal - system requirements:
• Each state may be associated with one or more function • The pump should be run for 10 seconds. If, during this time,
calls. no liquid is detected in the outflow tank, then the pump
• Transitions between states may be controlled by the passage should be switched off and ‘low water’ warning should be
of time, by system inputs or a combination of time and sounded. If liquid is detected, the pump should be run for a
inputs. further 45 seconds, or until the ‘high water’ sensor is
activated (whichever is first).
• Transitions between states may also involve function calls.
• After the front door is opened, the correct password must be
entered on the control panel within 30 seconds or the alarm
will sound.
• The ‘down flap’ signal will be issued. If, after 50 ms, no
flap movement is detected, it should be concluded that the
flap hydraulics are damaged. The system should then alert
the user and enter manual mode.
To meet this type of requirement, we can do two things:
• Keep track of the time in each system state;
• If the time exceeds a pre-determined error value, then we
should move to a different state.
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 195 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 196
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Example: Controller for a washing machine
Here is a brief description of the way in which we expect the system
Water
Valve to operate:
Water
Heater 1. The user selects a wash program (e.g. ‘Wool’, ‘Cotton’) on
the selector dial.
Start
Switch
Water
Pump
2. The user presses the ‘Start’ switch.
Selector
Dial
Washing
Drum
Machine
Motor
Controller
Water
Level
Sensor
LED
3. The door lock is engaged.
indicators
4. The water valve is opened to allow water into the wash drum.
Temperature
Sensor
Door
lock
Detergent
5. If the wash program involves detergent, the detergent hatch is
Hatch
opened. When the detergent has been released, the detergent
hatch is closed.
6. When the ‘full water level’ is sensed, the water valve is
closed.
7. If the wash program involves warm water, the water heater is
switched on. When the water reaches the correct
temperature, the water heater is switched off.
8. The washer motor is turned on to rotate the drum. The motor
then goes through a series of movements, both forward and
reverse (at various speeds) to wash the clothes. (The precise
set of movements carried out depends on the wash program
that the user has selected.) At the end of the wash cycle, the
motor is stopped.
9. The pump is switched on to drain the drum. When the drum
is empty, the pump is switched off.
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 197 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 198
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
/*-------------------------------------------------------------*-
Washer.C (v1.01)
The Input / Timed architecture discussed here is by no means unique to
‘white goods’ (such as washing machines). --------------------------------------------------------
Multi-state framework for washing-machine controller.
• For example, the sequence of events used to raise the landing -*-------------------------------------------------------------*/
gear in a passenger aircraft will be controlled in a similar
#include "Main.H"
manner. In this case, basic tests (such as ‘WoW’ - ‘Weight #include "Port.H"
on Wheels’) will be used to determine whether the aircraft is
#include "Washer.H"
on the ground or in the air: these tests will be completed
before the operation begins. /* ------ Private data type declarations ---------------------- */
/* Possible system states */
typedef enum {INIT, START, FILL_DRUM, HEAT_WATER,
• Feedback from various door and landing-gear sensors will WASH_01, WASH_02, ERROR} eSystem_state;
then be used to ensure that each phase of the manoeuvre /* ------ Private function prototypes ------------------------- */
completes correctly. tByte WASHER_Read_Selector_Dial(void);
bit WASHER_Read_Start_Switch(void);
bit WASHER_Read_Water_Level(void);
bit WASHER_Read_Water_Temperature(void);
void WASHER_Control_Detergent_Hatch(bit);
void WASHER_Control_Door_Lock(bit);
void WASHER_Control_Motor(bit);
void WASHER_Control_Pump(bit);
void WASHER_Control_Water_Heater(bit);
void WASHER_Control_Water_Valve(bit);
/* ------ Private constants ----------------------------------- */
#define OFF 0
#define ON 1
#define MAX_FILL_DURATION (tLong) 1000
#define MAX_WATER_HEAT_DURATION (tLong) 1000
#define WASH_01_DURATION 30000
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 199 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 200
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
/* --------------------------------------------------------------- */
/* ------ Private variables ----------------------------------- */ void WASHER_Update(void)
{
static eSystem_state System_state_G; /* Call once per second */
switch (System_state_G)
static tWord Time_in_state_G; {
case INIT:
static tByte Program_G; {
/* For demo purposes only */
/* Ten different programs are supported Debug_port = (tByte) System_state_G;
Each one may or may not use detergent */
static tByte Detergent_G[10] = {1,1,1,0,0,1,0,1,1,0}; /* Set up initial state */
/* Motor is off */
/* Each one may or may not use hot water */ WASHER_Control_Motor(OFF);
static tByte Hot_Water_G[10] = {1,1,1,0,0,1,0,1,1,0};
/* Pump is off */
/* --------------------------------------------------------------- */ WASHER_Control_Pump(OFF);
void WASHER_Init(void)
{ /* Heater is off */
System_state_G = INIT; WASHER_Control_Water_Heater(OFF);
}
/* Valve is closed */
WASHER_Control_Water_Valve(OFF);
/* Wait (indefinitely) until START is pressed */
if (WASHER_Read_Start_Switch() != 1)
{
return;
}
/* Start switch pressed
-> read the selector dial */
Program_G = WASHER_Read_Selector_Dial();
/* Change state */
System_state_G = START;
break;
}
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 201 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 202
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
case START: case FILL_DRUM:
{ {
/* For demo purposes only */ /* For demo purposes only */
Debug_port = (tByte) System_state_G; Debug_port = (tByte) System_state_G;
/* Lock the door */ /* Remain in this state until drum is full
WASHER_Control_Door_Lock(ON); NOTE: Timeout facility included here */
if (++Time_in_state_G >= MAX_FILL_DURATION)
/* Start filling the drum */ {
WASHER_Control_Water_Valve(ON); /* Should have filled the drum by now... */
System_state_G = ERROR;
/* Release the detergent (if any) */ }
if (Detergent_G[Program_G] == 1)
{ /* Check the water level */
WASHER_Control_Detergent_Hatch(ON); if (WASHER_Read_Water_Level() == 1)
} {
/* Drum is full */
/* Ready to go to next state */
System_state_G = FILL_DRUM; /* Does the program require hot water? */
Time_in_state_G = 0; if (Hot_Water_G[Program_G] == 1)
{
break; WASHER_Control_Water_Heater(ON);
}
/* Ready to go to next state */
System_state_G = HEAT_WATER;
Time_in_state_G = 0;
}
else
{
/* Using cold water only */
/* Ready to go to next state */
System_state_G = WASH_01;
Time_in_state_G = 0;
}
}
break;
}
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 203 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 204
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
case HEAT_WATER: case WASH_01:
{ {
/* For demo purposes only */ /* For demo purposes only */
Debug_port = (tByte) System_state_G; Debug_port = (tByte) System_state_G;
/* Remain in this state until water is hot /* All wash program involve WASH_01
NOTE: Timeout facility included here */ Drum is slowly rotated to ensure clothes are fully wet */
if (++Time_in_state_G >= MAX_WATER_HEAT_DURATION) WASHER_Control_Motor(ON);
{
/* Should have warmed the water by now... */ if (++Time_in_state_G >= WASH_01_DURATION)
System_state_G = ERROR; {
} System_state_G = WASH_02;
Time_in_state_G = 0;
/* Check the water temperature */ }
if (WASHER_Read_Water_Temperature() == 1)
{ break;
/* Water is at required temperature */ }
/* Ready to go to next state */
System_state_G = WASH_01; /* REMAINING WASH PHASES OMITTED HERE ... */
Time_in_state_G = 0;
} case WASH_02:
{
break; /* For demo purposes only */
} Debug_port = (tByte) System_state_G;
break;
}
case ERROR:
{
/* For demo purposes only */
Debug_port = (tByte) System_state_G;
break;
}
}
}
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 205 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 206
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
/* --------------------------------------------------------------- */
tByte WASHER_Read_Selector_Dial(void)
{
Conclusions
/* User code here... */
This seminar has discussed the implementation of multi-state
return 0;
} (timed) and multi-state (input / timed) systems. Used in
conjunction with an operating system like that presented in
/* --------------------------------------------------------------- */
bit WASHER_Read_Start_Switch(void) “Embedded C” Chapter 7, this flexible system architecture is in
{
/* Simplified for demo ... */
widespread use in embedded applications.
if (Start_pin == 0)
{
/* Start switch pressed */
return 1;
}
else
{
return 0;
}
}
/* --------------------------------------------------------------- */
bit WASHER_Read_Water_Level(void)
{
/* User code here... */
return 1;
}
/* --------------------------------------------------------------- */
bit WASHER_Read_Water_Temperature(void)
{
/* User code here... */
return 1;
}
/* --------------------------------------------------------------- */
void WASHER_Control_Detergent_Hatch(bit State)
{
bit Tmp = State;
/* User code here... */
}
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 207 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 208
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Preparation for the next seminar
Please read Chapter 9
before the next seminar
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 209 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 210
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Overview of this seminar
This seminar will:
• Discuss the RS-232 data communication standard
Seminar 8: • Consider how we can use RS-232 to transfer data to and
Using the Serial from deskbound PCs (and similar devices).
Interface This can be useful, for example:
• In data acquisition applications.
• In control applications (sending controller parameters).
• For general debugging.
Vcc
1.0 µF
7
5
9
MAX 233
Rx 19
20
Tx 18
6
1
1
Connect together: 6, 9
Pins 12 & 17
Pins 11 & 15
Pins 16 & 10
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 211 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 212
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
What is ‘RS-232’? Basic RS-232 Protocol
In 1997 the Telecommunications Industry Association released RS-232 is a character-oriented protocol. That is, it is intended to be
what is formally known as TIA-232 Version F, a serial used to send single 8-bit blocks of data. To transmit a byte of data
communication protocol which has been universally referred to as over an RS-232 link, we generally encode the information as
‘RS-232’ since its first ‘Recommended Standard’ appeared in the follows:
1960s. Similar standards (V.28) are published by the International
• We send a ‘Start’ bit.
Telecommunications Union (ITU) and by CCITT (The Consultative
Committee International Telegraph and Telephone). • We send the data (8 bits).
The ‘RS-232’ standard includes details of: • We send a ‘Stop’ bit (or bits).
• The protocol to be used for data transmission. •
• The voltages to be used on the signal lines. NOTE: The UART takes care of these details!
• The connectors to be used to link equipment together.
Overall, the standard is comprehensive and widely used, at data
transfer rates of up to around 115 or 330 kbits / second (115 / 330 k
baud). Data transfer can be over distances of 15 metres or more.
Note that RS-232 is a peer-to-peer communication standard.
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 213 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 214
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Asynchronous data transmission and baud rates RS-232 voltage levels
• RS-232 uses an asynchronous protocol. • The threshold levels used by the receiver are +3 V and -3 V
and the lines are inverted.
• Both ends of the communication link have an internal clock,
running at the same rate. The data (in the case of RS-232, • The maximum voltage allowed is +/- 15V.
the ‘Start’ bit) is then used to synchronise the clocks, if
necessary, to ensure successful data transfer.
• Note that these voltages cannot be obtained directly from the
naked microcontroller port pins: some form of interface
• RS-232 generally operates at one of a (restricted) range of hardware is required.
baud rates.
• For example, the Maxim Max232 and Max233 are popular
• Typically these are: 75, 110, 300, 1200, 2400, 4800, 9600, and widely-used line driver chips.
14400, 19200, 28800, 33600, 56000, 115000 and (rarely)
330000 baud. Vcc
1.0 µF
• 9600 baud is a very ‘safe’ choice, as it is very widely 7
supported.
5
Max
9
19
Rx To Tx pin ( P3.1)
18
233 1
Tx
6
20
1
To Rx pin ( P3.0)
6,9
Connect together:
Pins 12 & 17
Pins 11 & 15
Pins 16 & 10
Using a Max 233 as an RS-232 tranceiver.
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 215 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 216
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
The software architecture Overview
• Suppose we wish to transfer data to a PC at a standard 9600 Current core temperature All characters
baud rate; that is, 9600 bits per second. Transmitting each is 36.678 degrees written immediately
byte of data, plus stop and start bits, involves the to buffer
transmission of 10 bits of information (assuming a single (very fast operation)
stop bit is used). As a result, each byte takes approximately
1 ms to transmit.
Buffer
• Suppose, for example, we wish to send this information to
the PC:
Current core temperature is 36.678 degrees
…then the task sending these 42 characters will take more
than 40 milliseconds to complete. This will - frequently be
an unacceptably long duration.
• The most obvious way of solving this problem is to increase
the baud rate; however, this is not always possible (and it
does not really solve the underlying problem).
A better solution is to write all data to a buffer in the microcontroller.
The contents of this buffer will then be sent - usually one byte at a time -
to the PC, using a regular, scheduled, task.
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 217 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 218
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Using the on-chip U(S)ART for RS-232 communications Serial port registers
• The UART is full duplex, meaning it can transmit and The serial port control and status register is the special function
receive simultaneously. register SCON. This register contains the mode selection bits (and
the serial port interrupt bits, TI and RI: not used here).
• It is also receive-buffered, meaning it can commence
reception of a second byte before a previously received byte
SBUF is the receive and transmit buffer of serial interface.
has been read from the receive register.
Writing to SBUF loads the transmit register and initiates
• The serial port can operate in 4 modes (one synchronous transmission.
mode, three asynchronous modes). SBUF = 0x0D; /* Output CR */
• We are primarily interested in Mode 1.
Reading out SBUF accesses a physically separate receive register.
/* Read the data from UART */
• In this mode, 10 bits are transmitted (through TxD) or Data = SBUF;
received (through RxD): a start bit (0), 8 data bits (lsb first),
and a stop bit (1).
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 219 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 220
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Baud rate generation Why use 11.0592 MHz crystals?
• We are primarily concerned here with the use of the serial
It is very important to appreciate that it is not generally possible to
port in Mode 1. produce standard baud rates (e.g. 9600) using Timer 1 (or Timer 2),
• In this mode the baud rate is determined by the overflow rate unless you use an 11.0592 MHz crystal oscillator.
of Timer 1 or Timer 2.
• We focus on the use of Timer 1 for baud rate generation. Remember: this is an asynchronous protocol, and relies for correct
operation on the fact that both ends of the connection are working
at the same baud rate. In practice, you can generally work with a
The baud rate is determined by the Timer 1 overflow rate and the difference in baud rates at both ends of the connection by up to 5%,
value of SMOD follows: but no more.
SMOD
2 × Frequency
Baud rate (Mode 1) = oscillator
32 × Instructionscycle × (256 − TH 1)
Despite the possible 5% margin, it is always good policy to get the baud
Where:
rate as close as possible to the standard value because, in the field,
SMOD …is the ‘double baud rate’ bit in the PCON register; there may be significant temperature variations between the oscillator in
Frequencyoscillator …is the oscillator / resonator frequency; the PC and that in the embedded system.
Instructions cycle …is the number of machine instructions per oscillator
cycle (e.g. 12 or 6) Note also that it is generally essential to use some form of crystal
TH1 …is the reload value for Timer 1 oscillator (rather than a ceramic resonator) when working with
asynchronous serial links (such as RS-232, RS-485, or CAN): the
Note that Timer is used in 8-bit auto-reload mode and that interrupt ceramic resonator is not sufficiently stable for this purpose.
generation should be disabled.
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 221 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 222
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
PC Software What about printf()?
If your desktop computer is running Windows (95, 98, NT, 2000), We do not generally recommend the use of standard library
then a simple but effective option is the ‘Hyperterminal’ application function “printf()”, because:
which is included with all of these operating systems.
• this function sends data immediately to the UART. As a
result, the duration of the transmission is often too long to be
safely handled in a co-operatively scheduled application,
and,
• most implementations of printf() do not incorporate
timeouts, making it possible that use of this functions can
‘hang’ the whole application if errors occur.
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 223 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 224
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
RS-232 and 8051: Overall strengths and weaknesses Example: Displaying elapsed time on a PC
☺ RS-232 support is part of the 8051 core: applications based on RS-232
are very portable.
Vcc
☺ At the PC end too, RS-232 is ubiquitous: every PC has one or more 1.0 µF
RS-232 ports.
☺ Links can - with modern tranceiver chips - be up to 30 m (100 ft) in 7
length.
5
9
☺ Because of the hardware support, RS-232 generally imposes a low
MAX 233
software load. Rx 19
20
Tx 18
BUT:
6
1
1
Connect together: 6, 9
RS-232 is a peer-to-peer protocol (unlike, for example, RS-485): you
Pins 12 & 17
can only connect one microcontroller directly (simultaneously) to each
Pins 11 & 15
PC.
Pins 16 & 10
RS-232 has little or no error checking at the hardware level (unlike, for
example, CAN): if you want to be sure that the data you received at the
PC is valid, you need to carry out checks in software.
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 225 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 226
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
/*-------------------------------------------------------------*-
Main.c (v1.00)
--------------------------------------------------------
RS-232 (Elapsed Time) example - sEOS.
-*-------------------------------------------------------------*/
#include "Main.H"
#include "Port.H"
#include "Simple_EOS.H"
#include "PC_O_T1.h"
#include "Elap_232.h"
/* --------------------------------------------------------------- */
void main(void)
{
/* Set baud rate to 9600 */
PC_LINK_O_Init_T1(9600);
/* Prepare for elapsed time measurement */
Elapsed_Time_RS232_Init();
/* Set up simple EOS (5ms tick) */
sEOS_Init_Timer2(5);
while(1) /* Super Loop */
{
sEOS_Go_To_Sleep(); /* Enter idle mode to save power */
}
}
/*-------------------------------------------------------------*-
---- END OF FILE ---------------------------------------
-*-------------------------------------------------------------*/
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 227 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 228
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
/*-------------------------------------------------------------*- /*-------------------------------------------------------------*/
Elap_232.C (v1.00) void Elapsed_Time_RS232_Update(void)
{
-------------------------------------------------------- char Time_Str[30] = "\rElapsed time: ";
Simple library function for keeping track of elapsed time if (++Sec_G == 60)
Demo version to display time on PC screen via RS232 link. {
Sec_G = 0;
-*-------------------------------------------------------------*/
if (++Min_G == 60)
#include "Main.h" {
#include "Elap_232.h" Min_G = 0;
#include "PC_O.h"
if (++Hou_G == 24)
/* ------ Public variable definitions ------------------------- */ {
Hou_G = 0;
tByte Hou_G; }
tByte Min_G; }
tByte Sec_G; }
/* ------ Public variable declarations ------------------------ */ Time_Str[15] = CHAR_MAP_G[Hou_G / 10];
Time_Str[16] = CHAR_MAP_G[Hou_G % 10];
/* See Char_Map.c */
extern const char code CHAR_MAP_G[10]; Time_Str[18] = CHAR_MAP_G[Min_G / 10];
Time_Str[19] = CHAR_MAP_G[Min_G % 10];
/*-------------------------------------------------------------*-
Time_Str[21] = CHAR_MAP_G[Sec_G / 10];
Elapsed_Time_RS232_Init() Time_Str[22] = CHAR_MAP_G[Sec_G % 10];
Init function for simple library displaying elapsed time on PC /* We use the "seconds" data to turn on and off the colon
via RS-232 link. (between hours and minutes) */
if ((Sec_G % 2) == 0)
-*-------------------------------------------------------------*/ {
void Elapsed_Time_RS232_Init(void) Time_Str[17] = ':';
{ Time_Str[20] = ':';
Hou_G = 0; }
Min_G = 0; else
Sec_G = 0; {
} Time_Str[17] = ' ';
Time_Str[20] = ' ';
}
PC_LINK_O_Write_String_To_Buffer(Time_Str);
}
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 229 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 230
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
/*-------------------------------------------------------------*-
/*-------------------------------------------------------------*/
PC_LINK_O_Init_T1()
void PC_LINK_O_Update(void)
This version uses T1 for baud rate generation. {
/* Deal with transmit bytes here.
Uses 8051 (internal) UART hardware Are there any data ready to send? */
if (Out_written_index_G < Out_waiting_index_G)
-*-------------------------------------------------------------*/ {
void PC_LINK_O_Init_T1(const tWord BAUD_RATE) PC_LINK_O_Send_Char(Tran_buffer[Out_written_index_G]);
{
PCON &= 0x7F; /* Set SMOD bit to 0 (don't double baud rates) */ Out_written_index_G++;
}
/* Receiver disabled else
8-bit data, 1 start bit, 1 stop bit, variable baud */ {
SCON = 0x42; /* No data to send - just reset the buffer index */
Out_waiting_index_G = 0;
TMOD |= 0x20; /* T1 in mode 2, 8-bit auto reload */ Out_written_index_G = 0;
}
TH1 = (256 - (tByte)((((tLong)OSC_FREQ / 100) * 3125) }
/ ((tLong) BAUD_RATE * OSC_PER_INST * 1000)));
/*-------------------------------------------------------------*/
TL1 = TH1;
TR1 = 1; /* Run the timer */ void PC_LINK_O_Write_String_To_Buffer(const char* const STR_PTR)
TI = 1; /* Send first character (dummy) */ {
tByte i = 0;
/* Set up the buffers for reading and writing */
Out_written_index_G = 0; while (STR_PTR[i] != '\0')
Out_waiting_index_G = 0; {
PC_LINK_O_Write_Char_To_Buffer(STR_PTR[i]);
/* Interrupt *NOT* enabled */ i++;
ES = 0; }
} }
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 231 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 232
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
/*-------------------------------------------------------------*/
void PC_LINK_O_Write_Char_To_Buffer(const char CHARACTER) sEOS_ISR() interrupt INTERRUPT_Timer_2_Overflow
{ {
/* Write to the buffer *only* if there is space TF2 = 0; /* Must manually reset the T2 flag */
(No error reporting in this simple library...) */
if (Out_waiting_index_G < TRAN_BUFFER_LENGTH) /*===== USER CODE - Begin ================================== */
{ /* Call RS-232 update function every 5ms */
Tran_buffer[Out_waiting_index_G] = CHARACTER; PC_LINK_O_Update();
Out_waiting_index_G++;
} /* This ISR is called every 5 ms
} - only want to update time every second */
if (++Call_count_G == 200)
/*-------------------------------------------------------------*/ {
void PC_LINK_O_Send_Char(const char CHARACTER) /* Time to update time */
{ Call_count_G = 0;
tLong Timeout1 = 0;
/* Call time update function */
if (CHARACTER == '\n') Elapsed_Time_RS232_Update();
{ }
Timeout1 = 0; /*===== USER CODE - End ==================================== */
while ((++Timeout1) && (TI == 0)); }
if (Timeout1 == 0)
{
/* UART did not respond - error
No error reporting in this simple library... */
return;
}
TI = 0;
SBUF = 0x0d; /* Output CR */
}
Timeout1 = 0;
while ((++Timeout1) && (TI == 0));
if (Timeout1 == 0)
{
/* UART did not respond - error
No error reporting in this simple library... */
return;
}
TI = 0;
SBUF = CHARACTER;
}
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 233 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 234
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Example: Data acquisition void MENU_Command_Processor(void)
{
char Ch;
In this section, we give an example of a simple data acquisition
if (First_time_only_G == 0)
system with a serial-menu architecture. {
First_time_only_G = 1;
MENU_Show_Menu();
In this case, using the menu, the user can determine the state of the }
input pins on Port 1 or Port 2: /* Check for user inputs */
PC_LINK_IO_Update();
Ch = PC_LINK_IO_Get_Char_From_Buffer();
if (Ch != PC_LINK_IO_NO_CHAR)
{
MENU_Perform_Task(Ch);
MENU_Show_Menu();
}
}
void MENU_Show_Menu(void)
{
PC_LINK_IO_Write_String_To_Buffer("Menu:\n");
PC_LINK_IO_Write_String_To_Buffer("a - Read P1\n");
PC_LINK_IO_Write_String_To_Buffer("b - Read P2\n\n");
PC_LINK_IO_Write_String_To_Buffer("? : ");
}
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 235 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 236
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
void MENU_Perform_Task(char c)
{ sEOS_ISR() interrupt INTERRUPT_Timer_2_Overflow
PC_LINK_IO_Write_Char_To_Buffer(c); /* Echo the menu option */ {
PC_LINK_IO_Write_Char_To_Buffer('\n'); TF2 = 0; /* Must manually reset the T2 flag */
/* Perform the task */ /*===== USER CODE - Begin ================================== */
switch (c) /* Call MENU_Command_Processor every 5ms */
{ MENU_Command_Processor();
case 'a':
case 'A': /*===== USER CODE - End ==================================== */
{ }
Get_Data_From_Port1();
break;
}
case 'b':
case 'B':
{
Get_Data_From_Port2();
break;
}
}
}
void Get_Data_From_Port1(void)
{
tByte Port1 = Data_Port1;
char String[11] = "\nP1 = XXX\n\n";
String[6] = CHAR_MAP_G[Port1 / 100];
String[7] = CHAR_MAP_G[(Port1 / 10) % 10];
String[8] = CHAR_MAP_G[Port1 % 10];
PC_LINK_IO_Write_String_To_Buffer(String);
}
void Get_Data_From_Port2(void)
{
tByte Port2 = Data_Port2;
char String[11] = "\nP2 = XXX\n\n";
String[6] = CHAR_MAP_G[Port2 / 100];
String[7] = CHAR_MAP_G[(Port2 / 10) % 10];
String[8] = CHAR_MAP_G[Port2 % 10];
PC_LINK_IO_Write_String_To_Buffer(String);
}
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 237 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 238
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Conclusions Preparation for the next seminar
In this seminar, we have illustrated how the serial interface on the
8051 microcontroller may be used.
Please read Chapter 10
In the next seminar, we will use a case study to illustrate how the before the next seminar
various techniques discussed in this can be used in practical
applications.
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 239 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 240
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Introduction
Bell box
Door Window
Seminar 9: D
Control
panel
W
W
Case Study: Statue
Intruder Alarm System W
W W
Bell box
Door Window
1 2 3
D W
Control 4 5 6
panel W
7 8 9
* 0 #
Statue
W
W W
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 241 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 242
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
System Operation Key software components used in this example
• When initially activated, the system is in ‘Disarmed’ state. This case study uses the following software components:
• In Disarmed state, the sensors are ignored. The alarm does • Software to control external port pins (to activate the
not sound. The system remains in this state until the user external bell), as introduced in “Embedded C” Chapter 3.
enters a valid password via the keypad (in our demonstration
• Switch reading, as discussed in “Embedded C” Chapter 4, to
system, the password is “1234”). When a valid password is
process the inputs from the door and window sensors. Note
entered, the systems enters ‘Arming’ state.
that - in this simple example (intended for use in the
• In Arming state, the system waits for 60 seconds, to allow simulator) - no switch debouncing is carried out. This
the user to leave the area before the monitoring process feature can be added, if required, without difficulty.
begins. After 60 seconds, the system enters ‘Armed’ state.
• The embedded operating system, sEOS, introduced in
• In Armed state, the status of the various system sensors is “Embedded C” Chapter 7.
monitored. If a window sensor is tripped, the system enters
• A simple ‘keypad’ library, based on a bank of switches.
‘Intruder’ state. If the door sensor is tripped, the system
Note that - to simplify the use of the keypad library in the
enters ‘Disarming’ state. The keypad activity is also
simulator - we have assumed the presence of only eight keys
monitored: if a correct password is typed in, the system
in the example program (0 - 7). This final system would
enters ‘Disarmed’ state.
probably use at least 10 keys: support for additional keys can
• In Disarming state, we assume that the door has been be easily added if required.
opened by someone who may be an authorised system user.
• The RS-232 library (from “Embedded C” Chapter 9) is used
The system remains in this state for up to 60 seconds, after
to illustrate the operation of the program. This library would
which - by default - it enters Intruder state. If, during the 60-
not be necessary in the final system (but it might be useful to
second period, the user enters the correct password, the
retain it, to support system maintenance).
system enters ‘Disarmed’ state.
• In Intruder state, an alarm will sound. The alarm will keep
sounding (indefinitely), until the correct password is entered.
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 243 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 244
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Running the program The software
/*-------------------------------------------------------------*-
Port.H (v1.00)
--------------------------------------------------------
'Port Header' (see Chap 5) for project INTRUDER (see Chap 10)
-*-------------------------------------------------------------*/
/* ------ Keypad.C ------------------------------------------- */
#define KEYPAD_PORT P2
sbit K0 = KEYPAD_PORT^0;
sbit K1 = KEYPAD_PORT^1;
sbit K2 = KEYPAD_PORT^2;
sbit K3 = KEYPAD_PORT^3;
sbit K4 = KEYPAD_PORT^4;
sbit K5 = KEYPAD_PORT^5;
sbit K6 = KEYPAD_PORT^6;
sbit K7 = KEYPAD_PORT^7;
/* ------ Intruder.C --------------------------------------- */
sbit Sensor_pin = P1^0;
sbit Sounder_pin = P1^7;
/* ------ Lnk_O.C ------------------------------------------ */
/* Pins 3.0 and 3.1 used for RS-232 interface */
/*-------------------------------------------------------------*-
---- END OF FILE ---------------------------------------
-*-------------------------------------------------------------*/
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 245 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 246
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
/*-------------------------------------------------------------*- /*-------------------------------------------------------------*-
Main.c (v1.00) Intruder.C (v1.00)
-------------------------------------------------------- -*-------------------------------------------------------------*/
Simple intruder alarm system. ...
-*-------------------------------------------------------------*/ /* ------ Private data type declarations ---------------------- */
#include "Main.H" /* Possible system states */
#include "Port.H" typedef enum {DISARMED, ARMING, ARMED, DISARMING, INTRUDER}
#include "Simple_EOS.H" eSystem_state;
#include "PC_O_T1.h" /* ------ Private function prototypes ------------------------- */
#include "Keypad.h"
#include "Intruder.h" bit INTRUDER_Get_Password_G(void);
bit INTRUDER_Check_Window_Sensors(void);
/* ............................................................... */ bit INTRUDER_Check_Door_Sensor(void);
void INTRUDER_Sound_Alarm(void);
void main(void)
{ ...
/* Set baud rate to 9600 */
PC_LINK_O_Init_T1(9600); /* --------------------------------------------------------------- */
void INTRUDER_Init(void)
/* Prepare the keypad */ {
KEYPAD_Init(); /* Set the initial system state (DISARMED) */
System_state_G = DISARMED;
/* Prepare the intruder alarm */
INTRUDER_Init(); /* Set the 'time in state' variable to 0 */
State_call_count_G = 0;
/* Set up simple EOS (5ms tick) */
sEOS_Init_Timer2(5); /* Clear the keypad buffer */
KEYPAD_Clear_Buffer();
while(1) /* Super Loop */
{ /* Set the 'New state' flag */
sEOS_Go_To_Sleep(); /* Enter idle mode to save power */ New_state_G = 1;
}
} /* Set the (two) sensor pins to 'read' mode */
Window_sensor_pin = 1;
/*-------------------------------------------------------------*- Sounder_pin = 1;
---- END OF FILE --------------------------------------- }
-*-------------------------------------------------------------*/
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 247 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 248
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
void INTRUDER_Update(void) case ARMING:
{ {
/* Incremented every time */ if (New_state_G)
if (State_call_count_G < 65534) {
{ PC_LINK_O_Write_String_To_Buffer("\nArming...");
State_call_count_G++; New_state_G = 0;
} }
/* Call every 50 ms */ /* Remain here for 60 seconds (50 ms tick assumed) */
switch (System_state_G) if (++State_call_count_G > 1200)
{ {
case DISARMED: System_state_G = ARMED;
{ New_state_G = 1;
if (New_state_G) State_call_count_G = 0;
{ break;
PC_LINK_O_Write_String_To_Buffer("\nDisarmed"); }
New_state_G = 0;
} break;
}
/* Make sure alarm is switched off */
Sounder_pin = 1;
/* Wait for correct password ... */
if (INTRUDER_Get_Password_G() == 1)
{
System_state_G = ARMING;
New_state_G = 1;
State_call_count_G = 0;
break;
}
break;
}
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 249 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 250
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
case ARMED: case DISARMING:
{ {
if (New_state_G) if (New_state_G)
{ {
PC_LINK_O_Write_String_To_Buffer("\nArmed"); PC_LINK_O_Write_String_To_Buffer("\nDisarming...");
New_state_G = 0; New_state_G = 0;
} }
/* First, check the window sensors */ /* Remain here for 60 seconds (50 ms tick assumed)
if (INTRUDER_Check_Window_Sensors() == 1) to allow user to enter the password
{ - after time up, sound alarm. */
/* An intruder detected */ if (++State_call_count_G > 1200)
System_state_G = INTRUDER; {
New_state_G = 1; System_state_G = INTRUDER;
State_call_count_G = 0; New_state_G = 1;
break; State_call_count_G = 0;
} break;
}
/* Next, check the door sensors */
if (INTRUDER_Check_Door_Sensor() == 1) /* Still need to check the window sensors */
{ if (INTRUDER_Check_Window_Sensors() == 1)
/* May be authorised user - go to 'Disarming' state */ {
System_state_G = DISARMING; /* An intruder detected */
New_state_G = 1; System_state_G = INTRUDER;
State_call_count_G = 0; New_state_G = 1;
break; State_call_count_G = 0;
} break;
}
/* Finally, check for correct password */
if (INTRUDER_Get_Password_G() == 1) /* Finally, check for correct password */
{ if (INTRUDER_Get_Password_G() == 1)
System_state_G = DISARMED; {
New_state_G = 1; System_state_G = DISARMED;
State_call_count_G = 0; New_state_G = 1;
break; State_call_count_G = 0;
} break;
}
break;
} break;
}
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 251 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 252
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
case INTRUDER:
{ bit INTRUDER_Get_Password_G(void)
if (New_state_G) {
{ signed char Key;
PC_LINK_O_Write_String_To_Buffer("\n** INTRUDER! **"); tByte Password_G_count = 0;
New_state_G = 0; tByte i;
}
/* Update the keypad buffer */
/* Sound the alarm! */ KEYPAD_Update();
INTRUDER_Sound_Alarm();
/* Are there any new data in the keypad buffer? */
/* Keep sounding alarm until we get correct password */ if (KEYPAD_Get_Data_From_Buffer(&Key) == 0)
if (INTRUDER_Get_Password_G() == 1) {
{ /* No new data - password can't be correct */
System_state_G = DISARMED; return 0;
New_state_G = 1; }
State_call_count_G = 0;
} /* If we are here, a key has been pressed */
break; /* How long since last key was pressed?
} Must be pressed within 50 seconds (assume 50 ms 'tick') */
} if (State_call_count_G > 1000)
} {
/* More than 5 seconds since last key
- restart the input process */
State_call_count_G = 0;
Position_G = 0;
}
if (Position_G == 0)
{
PC_LINK_O_Write_Char_To_Buffer('\n');
}
PC_LINK_O_Write_Char_To_Buffer(Key);
Input_G[Position_G] = Key;
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 253 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 254
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
/* Have we got four numbers? */
if ((++Position_G) == 4) bit INTRUDER_Check_Window_Sensors(void)
{ {
Position_G = 0; /* Just a single window 'sensor' here
Password_G_count = 0; - easily extended. */
if (Window_sensor_pin == 0)
/* Check the password */ {
for (i = 0; i < 4; i++) /* Intruder detected... */
{ PC_LINK_O_Write_String_To_Buffer("\nWindow damaged");
if (Input_G[i] == Password_G[i]) return 1;
{ }
Password_G_count++;
} /* Default */
} return 0;
} }
if (Password_G_count == 4) /* --------------------------------------------------------------- */
{ bit INTRUDER_Check_Door_Sensor(void)
/* Password correct */ {
return 1; /* Single door sensor (access route) */
} if (Door_sensor_pin == 0)
else {
{ /* Someone has opened the door... */
/* Password NOT correct */ PC_LINK_O_Write_String_To_Buffer("\nDoor open");
return 0; return 1;
} }
}
/* Default */
return 0;
}
/* --------------------------------------------------------------- */
void INTRUDER_Sound_Alarm(void)
{
if (Alarm_bit)
{
/* Alarm connected to this pin */
Sounder_pin = 0;
Alarm_bit = 0;
}
else
{
Sounder_pin = 1;
Alarm_bit = 1;
}
}
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 255 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 256
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
void KEYPAD_Update(void)
{ bit KEYPAD_Scan(char* const pKey)
char Key; {
char Key = KEYPAD_NO_NEW_DATA;
/* Scan keypad here... */
if (KEYPAD_Scan(&Key) == 0) if (K0 == 0) { Key = '0'; }
{ if (K1 == 0) { Key = '1'; }
/* No new key data - just return */ if (K2 == 0) { Key = '2'; }
return; if (K3 == 0) { Key = '3'; }
} if (K4 == 0) { Key = '4'; }
if (K5 == 0) { Key = '5'; }
/* Want to read into index 0, if old data has been read if (K6 == 0) { Key = '6'; }
(simple ~circular buffer). */ if (K7 == 0) { Key = '7'; }
if (KEYPAD_in_waiting_index == KEYPAD_in_read_index)
{ if (Key == KEYPAD_NO_NEW_DATA)
KEYPAD_in_waiting_index = 0; {
KEYPAD_in_read_index = 0; /* No key pressed */
} Old_key_G = KEYPAD_NO_NEW_DATA;
Last_valid_key_G = KEYPAD_NO_NEW_DATA;
/* Load keypad data into buffer */
KEYPAD_recv_buffer[KEYPAD_in_waiting_index] = Key; return 0; /* No new data */
}
if (KEYPAD_in_waiting_index < KEYPAD_RECV_BUFFER_LENGTH)
{ /* A key has been pressed: debounce by checking twice */
/* Increment without overflowing buffer */ if (Key == Old_key_G)
KEYPAD_in_waiting_index++; {
} /* A valid (debounced) key press has been detected */
}
/* Must be a new key to be valid - no 'auto repeat' */
if (Key != Last_valid_key_G)
bit KEYPAD_Get_Data_From_Buffer(char* const pKey) {
{ /* New key! */
/* If there is new data in the buffer */ *pKey = Key;
if (KEYPAD_in_read_index < KEYPAD_in_waiting_index) Last_valid_key_G = Key;
{
*pKey = KEYPAD_recv_buffer[KEYPAD_in_read_index]; return 1;
}
KEYPAD_in_read_index++; }
return 1; /* No new data */
} Old_key_G = Key;
return 0;
return 0; }
}
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 257 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 258
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
sEOS_ISR() interrupt INTERRUPT_Timer_2_Overflow
{
Extending and modifying the system
TF2 = 0; /* Must manually reset the T2 flag */
/*===== USER CODE - Begin ================================== */
/* Call RS-232 update function every 5ms */ • How would you add a “real” keypad?
PC_LINK_O_Update();
(See “Patterns for Time-Triggered Embedded Systems, Chap. 20)
/* This ISR is called every 5 ms
- only want to update intruder every 50 ms. */
if (++Call_count_G == 10) • How would you add an LCD display?
{
/* Time to update intruder alarm */ (See “Patterns for Time-Triggered Embedded Systems, Chap. 22)
Call_count_G = 0;
/* Call intruder update function */ • How would you add additional nodes?
INTRUDER_Update();
} (See “Patterns for Time-Triggered Embedded Systems, Part F)
/*===== USER CODE - End ==================================== */
}
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 259 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 260
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Conclusions
This case study has illustrated most of the key features of embedded
C, as discussed throughout the earlier sessions in this course.
We’ll consider a final case study in the next seminar.
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 261 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 262
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Overview
Seminar 10: In this session, we will discuss the design of software to control a
Case Study: small mobile robot.
Controlling a
Mobile Robot
The robot is “Mr Line”
He is produced by “Microrobot NA”
http://www.microrobotna.com
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 263 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 264
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
What can the robot do? The robot brain
The robot has IR sensors and transmitters that allow him to detect a Mr Line is controlled by an 8051 microcontroller (an AT89C2051).
black line on a white surface - and follow it.
We’ll use a pin-compatible AT89C4051 in this study.
http://www.microrobotna.com
http://www.microrobotna.com
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 265 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 266
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
How does the robot move? Pulse-width modulation
Mr Line has two DC motors: by controlling the relative speed of
these motors, we can control the speed and direction in which he
will move. V x y
Time
x
Duty cycle (%) = x+y
× 100
Period = x + y, where x and y are in seconds.
1
Frequency = x+y
, where x and y are in seconds.
The key point to note is that the average voltage seen by the load is
http://www.microrobotna.com given by the duty cycle multiplied by the load voltage.
See: “Patterns for Time-Triggered Embedded Systems”, Chapter 33
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 267 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 268
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
Software PWM The resulting code
< We’ll discuss the resulting code in the lecture … >
PWM_PERIOD_G
PWM_G
PWM_position_G
if (PWM_position_G < PWM_G)
{
PWM_pin = PWM_ON;
}
else
{
PWM_pin = PWM_OFF;
}
See: “Patterns for Time-Triggered Embedded Systems”, Chapter 33
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 269 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 270
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.
More about the robot Conclusions
Please see: That brings us to the end of this course!
http://www.le.ac.uk/engineering/mjp9/robot.htm
COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 271 COPYRIGHT © MICHAEL J. PONT, 2001-2003. Contains material from: PES I - 272
Pont, M.J. (2002) “Embedded C”, Addison-Wesley. Pont, M.J. (2002) “Embedded C”, Addison-Wesley.