C Programming For Embedded Systems
C Programming For Embedded Systems
TEAMFLY
Team-Fly®
Page i
Kirk Zurell
Page ii
Disclaimer:
R&D Books
Lawrence, KS 66046
USA
Berkeley, CA 94710
ISBN 1-929629-04-4
Page iii
Waterloo, Ontario
E-mail: [email protected]
http://www.bytecraft.com
Page v
Acknowledgments
Page vii
Table of Contents
Acknowledgments
v
Chapter 1
1
Introduction
Role of This Book
Typographical Conventions
4
Chapter 2
5
Problem Specification
Product Requirements
Hardware Engineering
Software Planning
Software Architecture
Pseudocode
10
Flowchart
11
State Diagram
12
Resource Management
13
Testing Regime
14
Page viii
Chapter 3
17
Microcontrollers In-depth
19
Instruction Sets
20
The Stack
20
21
22
22
23
Timers
24
Watchdog Timer
25
Examples 26
26
Interrupt Circuitry
26
27
29
30
Multiple Interrupts
31
RESET
31
I/O Ports
32
Analog-to-Digital Conversion
33
Serial Peripheral Buses
34
36
Chapter 4
37
Design Process
Product Functionality
37
Hardware Design
38
Software Design
39
Software Architecture
39
Flowchart
40
Resource Management
42
Scratch Pad
42
Interrupt Planning
42
Testing Choices
44
44
Code Inspection
44
45
45
45
Page ix
Chapter 5
47
47
Device Knowledge
49
#pragma has
49
#pragma port
51
Endianness
52
Mechanical Knowledge
52
Libraries
54
54
Chapter 6
57
Identifier Declaration
59
59
60
60
61
61
61
Real Numbers
63
Complex Data Types
63
Pointers
63
Arrays
64
Enumerated Types
65
Structures
66
Unions
68
typedef
69
70
70
72
72
73
External Linkage
73
Internal Linkage
73
No Linkage
74
74
75
76
Page x
Chapter 7
79
79
Functions
80
Function Parameters
81
Control Structures
81
81
Initialization Functions
82
Control Statements
82
Decision Structures
82
Looping Structures
84
Control Expression
84
84
86
TEAMFLY
87
89
Chapter 8
91
Libraries
Creating Libraries
92
95
97
Chapter 9
99
Team-Fly®
Optimization
100
101
Hand Optimization
102
103
Debugging Embedded C
104
Register Type Modifier
104
Local Memory
104
Pointers
105
105
Calling Conventions
105
105
Exercising Hardware
106
Debugging by Inspection
106
Page xi
Dummy Loads
108
108
Simulators
108
Emulators
109
110
Chapter 10
111
Sample Project
111
"Hello World!"
112
Keypad Test
113
LCD Test
114
Talking to Ports
115
116
Appendix A
119
Table of Contents
Appendix A
123
Embedded C Libraries
Appendix B
163
ASCII Chart
Appendix C
165
Glossary
Index
171
180
Page 1
Chapter 1—
Introduction
1.1—
Page 2
1.2—
Page 3
C is a high
1.3—
1.4—
Typographical Conventions
Page 4
Bold
Italic
provides emphasis.
Letter
Letter
Gothic
Italic
0x
0b
1.5—
http://www.bytecraft.com/embedded_C/
Page 5
Chapter 2—
Problem Specification
Product Requirements
Page 6
Results
•
Program will accept and store time settings for three daily
usage periods.
•
2.2—
Hardware Engineering
This book does not deal directly with hardware, except for
the example project. Nevertheless, the target platform
influences everything about the product. It determines the
ease with which code is generated by the compiler, and it
determines some overall software design decisions.
Engineering Factors
Estimate
Operating Environment
domestic environment
Page 8
Engineering Factors
Estimate
Interfaces
pins necessary
Memory Size
Special Features
Development Tools
C compiler
simulator or emulator
development board
2.3—
Software Planning
•
C provides device-independence not offered by machine
language. If you hand-code a program in assembly, you run
the risk of wasting it all with a change in microcontroller.
Changing processors in a design programmed in C can incur
as little extra effort as changing a header file in your
software modules.
Team-Fly®
Page 9
HVAC interface,
keypad,
LCD, and
•
temperature sensor;
2.3.1—
Software Architecture
Page 10
2.3.2—
Pseudocode
1. Initialization
3. Main loop
Page 11
2.3.3—
Flowchart
Page 12
Figure
2.1
Data
flow
for
the
algorithm
2.3.4—
State Diagram
Page 13
Figure
2.2
State
diagram
for
the
algorithm
2.3.5—
Resource Management
we are
Page 14
Variable/Module
Resources
User settings
Stack
Local variables
Constants
Initialization
Main line
LCD
Keypad decode
2.4—
Testing Regime
•
Design for debugging.
Code inspection.
mation is useful both to the tester and the end user, but it
may prove a liability if the market will not tolerate
equipment that appears to fail.
Results
Our design will have an LCD panel. With this capability, the
system can write debug messages to the display. These can
include a ''splash screen" on power-up, echoed keystrokes,
or displayed status messages.
Page 17
Chapter 3—
Microcontrollers In-depth
Page 18
Timer
Most chips supply some I/O lines that can switch external
equipment; occasionally these pins can sink heavy current
to reduce external components. Some varieties provide A/D
and D/A converters or specialized logic for driving certain
devices (like infrared LEDs).
Peripheral Buses
3.1—
The accumulator
TEAMFLY
register
Team-Fly®
Page 20
3.1.1—
Instruction Sets
Listing 3.1
3.1.2—
The Stack
Page 21
Figure
3.1
MC68HC705C8
stack
3.2—
Page 22
3.2.1—
Listing 3.2
/* ... */
3.2.2—
Page 23
Fused ROM is the traditional PROM, with ROM cells that are
programmed by selectively blowing fuses in a memory
matrix, according to bit patterns. Programmable only by
external equipment.
3.2.3—
Page 24
3.3—
Timers
Page 25
Listing 3.3
#pragma vector TIMER_IRQ @ 0xFFE0;
void TIMER_IRQ(void) {
3.3.1—
Watchdog Timer
void main(void) {
while(1) {
/* ... */
RESET_WATCHDOG();
Page 26
3.3.2—
Examples
mode. The timer T1 is used for real time controls tasks with
three user-selectable modes.
watchdog useless.
3.4—
Interrupt Circuitry
3.4.1—
Page 28
Architecture
Arbitration
Notes
Motorola 6805/08
Vectored
National COP8
Mixed
Nonvectored
Zilog Z8
Vectored
Scenix SX
Nonvectored
No priority levels.
Intel 8051
Nonvectored
Cypress M8
Nonvectored
Table 3.2 shows the COP8 vector table, as required for the
COP8SAA7 device. The rank is as enforced by the VIS
instruction.
Rank
Source
Description
Vector Address *
Software
INTR Instruction
0bFE - 0bFF
Reserved
Future
0bFC - 0bFD
3
External
G0
0bFA - 0bFB
Page 29
Rank
Source
Description
Vector Address *
4
Timer T0
Underflow
0bF8 - 0bF9
Timer T1
T1A/Underflow
0bF6 - 0bF7
Timer T1
T1B
0bF4 - 0bF5
MICROWIRE/PLUS
BUSY Low
0bF2 - 0bF3
8
Reserved
Future
0bF0 - 0bF1
Reserved
Future
0bEE - 0bEF
10
Reserved
Future
0bEC - 0bED
11
Reserved
Future
0bEA - 0bEB
12
Reserved
Future
0bE8 - 0bE9
13
Reserved
Future
0bE6 - 0bE7
14
Reserved
Future
0bE4 - 0bE5
15
Port L/Wakeup
Port L Edge
0bE2 - 0bE3
16
Default
VIS Instruction
0bE0 - 0bE1
interrupts
3.4.2—
Team-Fly®
Page 30
Motorola 6808
Motorola 6805
Microchip PIC
Zilog Z8
Scenix SX
Cypress M8
3.4.3—
Listing 3.5
#ifdef CYC
#endif
Page 31
#ifdef COP8C
#endif
#ifdef C6805
#endif
3.4.4—
Multiple Interrupts
3.4.5—
RESET
initial power-on;
Page 32
•
a watchdog time-out;
This can be used to check if the RESET was cold (power was
cycled —
I/O Ports
Page 33
3.5.1—
Analog-to-Digital Conversion
Page 34
You can declare the control ports with #pragma port in the
device header file.
3.6—
Page 35
within the memory map as the compiler understands it.
You then write device driver routines to read and write each
SPECIAL memory area.
Standard
Manufacturer
Notes
I2C
Philips
operates across two wires. The two lines consist of the serial
data line and the serial clock line, which are both
bidirectional. No programming interface is specified.
SCI
various
Enhanced UART for board-level serial
SPI
various
possibly compatible).
Page 36
3.7—
Manual Programming
Simulators
Emulators
Page 37
Chapter 4—
Design Process
4.1—
Product Functionality
Results
•
Program will measure current temperature. We will have to
service and read an A/D converter connected to a
thermistor. To minimize part count, the A/D converter will be
quite rudimentary.
Page 38
•
Program will accept and store user-selected heating and
cooling temperature settings, and time settings for three
daily usage periods. We will build in reasonable defaults,
and then keep the current settings in RAM. If the power goes
out, the device won't put anyone in danger.
4.2—
Hardware Design
As mentioned previously, hardware is outside the scope of
this book. We include this hardware information to justify
the choices we make in the design of the thermostat.
The j1a is the only chip needed; the rest are discrete parts.
Page 39
4.3—
Software Design
4.3.1—
Software Architecture
As before, we will be using C.
Results
TEAMFLY
stdio includes routines to get and put strings from displays
and keyboards. This library relies on others to do the actual
input and output.
Team-Fly®
Page 40
4.3.2—
Flowchart
Page 41
Results
Figure
4.1
Data
flow
for
the
algorithm
(revised)
Page 42
4.4—
Resource Management
4.4.1—
Scratch Pad
4.4.2—
Interrupt Planning
Page 43
and
Results
A Millisecond Counter
Page 44
A Second Counter
Since we will need the external IRQ pin as an extra input, we
cannot use the keypad interrupt function associated with
port A pins 0–3.
4.5—
Testing Choices
4.5.1—
4.5.2—
Code Inspection
Page 45
Listing 4.1
Library skeleton
#pragma library;
/* . . . */
#pragma endlibrary;
4.5.4—
4.5.5—
Target System in a Test Harness
Page 46
Results
For initial code inspection, we will use the C6805 listing file.
The listing file includes numerous reports that are useful
both during code-and-compile cycles, and when doing code
review on others'
work.
Page 47
Chapter 5—
mechanical knowledge.
5.1—
Page 48
Listing 5.1
/* C function */
0306 81 RTS }
00EA {
#asm
LOOP:
#endasm
030D 81 RTS }
Page 49
5.2—
Device Knowledge
5.2.1—
#pragma has
#pragma has instruction are dependent upon the processor
family and the compiler.
Listing 5.2
void main(void)
Team-Fly®
Page 50
031F 81 RTS }
0327 48 LSLA
0328 59 ROLX
032F 5C INCX
0334 81 RTS
0316 B6 EA LDA $EA result = one * two; 0318 BE E9 LDX
$E9
Page 51
031A 42 MUL
031D 81 RTS }
5.2.2—
#pragma port
Listing 5.4
Listing 5.5
Page 52
5.2.3—
Endianness
5.3—
Mechanical Knowledge
Page 53
Listing 5.6
#include <port.h>
*/
DDR_WAIT();
DDR_WAIT();
Page 54
5.4—
Libraries
5.5—
Page 55
Listing 5.7
#include <hc705c8.h>
#include <port.h>
#define ON 1
#define OFF 0
#define PUSHED 1
void main(void){
while (1){
if (PORTA.1 == PUSHED){
if (PORTA.1 == PUSHED){
} /* end main */
Page 57
Chapter 6—
object files —
Page 59
Modifier
Notes
auto
const
extern
far
near
static
unsigned
volatile
Identifier Declaration
characters.
6.1.1—
Page 60
Listing 6.1
#define eeprom_r(LOC) I2C_read(LOC)
int eeprom i;
6.2—
TEAMFLY
6.3—
Team-Fly®
Page 61
6.4—
and 16 bits.
long and short are useful because they are less likely to
change between a target with a natural 8-bit data type and
one that delves into 16-bit values. In cases of a switchable
int, you can maintain code portability by using short for
those values that require 8 bits, and long for values which
require 16 bits.
Like the int, the short and long data types uses a sign bit by
default and can therefore contain negative numbers.
6.4.1—
6.5—
Page 62
Listing 6.2
bits switch_fixup(void)
00EB 0000 bit heat_flag; 00EB 0001 bit cool_flag; 00EA bits
switches; 0300 00 01 04 BRSET 0,$01,$0307 heat_flag =
PORTB.0; 0303 11 EB BCLR 0,$EB
return(switches);
031E 81 RTS
Page 63
6.6—
Real Numbers
myFloatVariable = 2.0;
6.7—
6.7.1—
Pointers
Page 64
6.7.2—
Arrays
int myIntArray[8];
/* uninitialized */
{1,2,4,8,16,32,64,128};
/* initialized below */
{1,8,2,7,3,6,4,5};
07FE 03 32
0332 AE C0 LDX #$C0
0334 7F CLR ,X
0335 5C INCX
Page 65
033A 5F CLRX
0340 5C INCX
0348 01 02 04 08 10 20 40 80
6.7.3—
Enumerated Types
Page 66
Listing 6.5
Specifying a starting value for enumerated elements
enum ORDINALS {first = 1, second, third, fourth, fifth};
When the compiler encounters an element in an
enumerated list without an assigned value, it counts from
the last value that was specified. For example, the following
enumerated list specifies the appropriate values for its
elements.
Listing 6.6
6.7.4—
Structures
Listing 6.7
struct display {
Page 67
char AorP;
};
Listing 6.8
struct reg_tag {
} TCR;
The Byte Craft compiler can span a bit field across two
bytes. Not all compilers support this optimization, however.
In the worst case, the following structure would place the
second field entirely in a separate word of memory from the
first.
Listing 6.9
struct {
Page 68
Unions
Listing 6.10
struct lohi_tag{
short lowByte;
short hiByte;
};
union tagName {
int asInt;
char asChar;
short asShort:
long asLong;
} scratchPad;
Page 69
Listing 6.11
union TIMER1_tag {
} TMR1;
/* ... */
seed = TMR1.halves.TMR1L;
6.8—
typedef
The typedef keyword defines a new variable type in terms of
existing types. The compiler cares most about the size of
the new type, to determine the amount of RAM or ROM to
reserve.
Page 70
Listing 6.12
typedef struct {
char * name;
int start;
int min_temp;
int max_temp;
} time_record;
time_record targets[] {
6.9—
6.9.1—
TEAMFLY
Team-Fly®
Page 71
PI = 3.0;
6.9.2—
The signed keyword forces the compiler to use the high bit
of an integer variable as a sign bit. If the sign bit is set with
the value 1, then the rest of the variable is interpreted as a
negative value. By default, short, int, and long data types
are signed. The char data type is unsigned by default.
Page 72
Size Modifiers:
short myShortInt;
6.9.4—
The far keyword creates a pointer that can point to any data
in memory: const char * myString = "Constant String"; char
far * myIndex = &myString;
Page 73
6.10—
6.10.1—
External Linkage
6.10.2—
Internal Linkage
Note
6.10.3—
No Linkage
6.10.4—
int Calculate_Sum()
Page 75
6.10.5—
Listing 6.13
Page 76
Listing 6.14
Using static variables to track function depth void
myRecurseFunc(void) {
depthCount += 1;
myRecurseFunc();
6.10.6—
Listing 6.15
while (myCounter<10) {
/* ... */
myCounter += 1;
} /* end while */
Page 77
Because of the scarcity of registers on 8-bit machines and
the desire for size optimization rather than speed, the
register keyword is not very useful for embedded system
programmers.
6.10.7—
Listing 6.16
/* ... */
Page 79
Chapter 7—
Page 80
while ( condition){
statements
7.2—
Functions
When the compiler reaches the function definition, it
generates machine instructions to implement the
functionality, and reserves enough program memory to hold
the statements in the function. The address of the function
is available through the symbol table.
Page 81
7.2.1—
Function Parameters
int myFunc()
int myFunc(void)
In embedded programs, main() does not accept any
parameters.
7.3—
Control Structures
7.3.1—
TEAMFLY
From there, the main() function can execute code from other
functions and receive return values.
Team-Fly®
Page 82
7.3.2—
Initialization Functions
routine or equivalent.
7.3.3—
Control Statements
7.4—
Decision Structures
Listing 7.1
switch(choice) {
case 1: return 5;
030A 81 RTS
Page 83
0311 81 RTS
0318 81 RTS
default: return 9;
031B 81 RTS
The Byte Craft compiler can extend the case label to deal
with common programming problems.
Listing 7.2
Listing 7.3
case '0'..'9':
7.5—
Looping Structures
Listing 7.4
void main(void)
while(1)
7.5.4—
Control Expression
7.5.5—
Page 85
Listing 7.5
while(1)
{
switch(ch)
case '0'..'9':
Page 86
case 'D':
7.6—
7.6.1—
Page 87
Note
For example, if both operands have bit 0 set, then the result
of the bitwise AND expression has bit 0
set.
Listing 7.6
y=0b00000111,
z;
Page 88
Listing 7.8
int x=0b00000101,
y=0b00000111,
z;
Listing 7.9
int x=0b00000101,
y=0b00000111,
z;
Listing 7.10
z;
Page 89
Listing 7.11
0305 81 RTS
0306 14 01 BSET 2,$01
0308 81 RTS }
7.6.3—
The right shift operator shifts the data right by the specified
number of positions. Bits shifted out the right side
disappear. With unsigned integer values, 0s are shifted in at
the high end, as necessary.
x >> number;
The left shift operator shifts the data right by the specified
number of positions. Bits shifted out the left side disappear
and new bits coming in are 0s. The binary number is shifted
left by number bits.
x << number;
Left shifting a binary number is equivalent to multiplying it
by 2n.
Listing 7.12
porta = 0b10000000;
porta >> 1;
Page 90
porta << 1;
030F 48 LSLA
0310 5A DECX
Page 91
Chapter 8—
Libraries
TEAMFLY
Team-Fly®
Page 92
Standard I/O
•
SPI (Serial Peripheral Interface)
MICROWIRE bus
I/O ports
While manipulating I/O ports is usually a matter of a few
assignment statements, there is some benefit in abstracting
the port from the particular implementation.
LCD displays
Timers
8.1—
Creating Libraries
Page 93
Two arrays of integers, one for hours and one for minutes,
seemed best. Array element 0 is a good choice for the
current time, and 1–3 for the daily cycle start times.
Listing 8.1
#ifndef __TIMESTMP_C
#define __TIMESTMP_C
#pragma library;
#include <timestmp.h>
/* Declared above:
bit use_metric = 0:
char buffer[7];
*/
Page 94
}
#pragma endlibrary;
#endif /* __TIMESTMP_C */
Listing 8.2
#ifndef __TIMESTMP_H
#define __TIMESTMP_H
bit use_metric;
char buffer[7];
#endif /* __TIMESTMP_H */
Page 95
8.2—
Listing 8.3
char i;
/* Set up string */
if(!use_metric) {
buffer[5] = 'a';
buffer[5] = 'p';
if(hours == 0)
hours = 12;
}
/* Fill in hours */
buffer[0] = '0';
buffer[0] = i;
Page 96
/* Fill in minutes */
buffer[3] = '0';
Alternatively, you could unroll the bottom for loops to avoid
the loop management code.
Listing 8.4
Page 97
8.3—
With the Byte Craft compilers, there are two scenarios for
library use: traditional linking with BClink and Absolute Code
Mode.
Listing 8.5
#include <timestmp.h>
void main(void) {
/* ... */
#include <timestmp.c>
Listing 8.6
#define __TIMESTMP_H
ifdef MAKEOBJECT
#else /* MAKEOBJECT */
Page 98
bit use_metric;
char buffer[7];
#endif /* MAKEOBJECT */
#endif /* __TIMESTMP_H */
Page 99
Chapter 9—
a lifeline of communication, or
Page 100
9.1—
Optimization
Page 101
Constant Folding
Lofting
Edge Effects
Code that causes values to roll over within their variables
can be a candidate for special treatment.
Long Operations
Array Calculations
9.1.1—
Instruction Set-Dependent Optimizations
•
Bit operations can be conducted using bit set and bit clear
instructions instead of using a multibyte sequence that does
a load, bitwise AND or OR, and store.
Team-Fly®
Page 102
9.2—
Hand Optimization
Listing 9.1
void walk_through_A(void)
delay_100us(10);
}
Page 103
can determine from the design whether the port in this case
will act in a volatile manner.
9.2.1—
Listing 9.2
void up_and_down(void)
{
int up, down; /* probably separate locations */
porta = up;
/* ... */
porta = down;
Listing 9.3
void up_and_down(void)
{
int up;
Page 104
porta = up;
/*...*/
porta = down;
Debugging Embedded C
9.3.1—
9.3.2—
Local Memory
Page 105
9.3.3—
Pointers
9.4.1—
Calling Conventions
9.4.2—
Page 106
9.5—
Exercising Hardware
9.6—
Debugging by Inspection
Listing 9.4
SYMBOL TABLE
Page 107
Listing 9.5
0000 CC register cc
0000 PORTA portrw
Page 108
The compiler can also present the values that it knows are
held in the processor registers. If you are working without
the benefit of an emulator, this provides some of the
information an emulator would track.
9.7—
Dummy Loads
9.8—
9.8.1—
Simulators
Using a simulator, you can step through your code while the
program is running. The simulator will report on register and
status values, peripheral register contents, and RAM usage.
Page 109
9.8.2—
Emulators
following.
Page 110
9.9—
Page 111
Chapter 10—
Sample Project
10.1—
TEAMFLY
Team-Fly®
Page 112
10.1.1—
''Hello World!"
Listing 10.1
#include <705j1a.h>
#include <port.h>
unsigned long counter;
void pause(void)
NOP();
void main(void)
PORTB.0 = 0;
DDR_MASKED(PORTB,_______C,00000000);
DDR_WAIT();
while(1)
pause();
PORTB.0 = 1;
Page 113
pause();
PORTB.0 = 0;
10.1.2—
Keypad Test
Listing 10.2
#include <705j1a.h>
#include <delay.h>
#include <port.h>
#include <keypad.h>
void main(void)
int8 store;
PORTB = 0;
DDR(PORTB,00000000);
DDR_WAIT();
keypad_init();
while(1)
Page 114
switch(keypad_getch()) {
#include <keypad.c>
#include <port.c>
#include <delay.c>
10.1.3—
LCD Test
Listing 10.3
#include <705j1a.h>
#include <delay.h>
#include <port.h>
#define LCD_DL 0
#define LCD_UPPER4 1
#include <lcd.h>
Page 115
void main(void)
lcd_init();
while(1)
puts("Hello World");
delay_100us(10);
lcd_send_control(LCDCLR);
delay_100us(10);
#include <lcd.c>
#include <delay.c>
10.2—
Talking to Ports
organized.
Page 116
10.3—
10.1
A/D
converter
circuit
Page 117
#include <705j1a.h>
#include <port.h>
#define Pf PORTB.5
#define Pi ISCR.IRQF
DDRB = 00000000;
Pf = 0;
while(1)
Page 118
converter.
The value of Vmin occurs when Pi is consistently just at the
sense threshold, and the processor is always feeding back a
1 to the Pf pin. At an input of Vmax, a 0 is always being fed
back from Pf.
The A/D value is linear and scaled between Vmin and Vmax.
It is determined from the ratio of 1s read on Pi (N1) to the
total tests in a sample. The accuracy of the system is a
linear function of test sample size (N). Vi can be calculated
using the following relationship.
Page 119
Appendix A —
Table of Contents
Introduction
123
125
126
Math Library
126
Library Definitions
127
DEF.H
127
STDIO
129
129
129
STDLIB
130
STDLIB
130
130
131
Page 120
132
133
qsort
134
pow
135
STRING
136
136
size_t
136
136
137
strlen
138
138
CTYPE
139
CTYPE.H
139
139
DELAY
141
141
delay_ms
141
KEYPAD
142
142
142
LCD
143
143
LCD_DATA
144
145
146
I2C_EE
147
147
MWIRE_EE
149
149
mwire_bus_delay
150
151
TEAMFLY
Team-Fly®
Page 121
MATH
152
MATH.H and MATH.C
152
152
153
153
fabs
154
fmod
154
155
modf
155
156
FLOAT
156
FLOAT.H
156
UART
158
UART
158
159
PORT
160
160
161
Page 123
Appendix A —
Embedded C Libraries
Introduction
Pressure to cut development costs leads naturally to the
urge to standardize hardware and software products.
Standardized computers led to standardized development
languages and (quasi-) standardized operating systems. As
well, developers created standard libraries of useful
functions with widespread appeal.
Reusable Code
Product Reliability
Page 125
The latter point is one of the reasons why it's important to
ship the library source code with the compiler. Product
reliability, discussed previously, is another. Fortunately,
contemporary software industry practice, from a business
point of view, permits, and even encourages, the
distribution of source code. Byte Craft realized early on the
importance of shipping library source with each compiler.
You can easily use the libraries in your programs with the
following steps.
command-line option.
Use #include <> to add their header files at the top of your
source code. For example:
#include <stdio.h>
Math Library
Operator
Functions
* __MUL8x8(void)
__MUL16x16(void)
/ __DIV8BY8(void)
__LDIV(void)
% __RMOD(void)
Page 127
Library Definitions
DEF.H
Note
Description
Page 128
Example
#pragma library
#include <abc_def.h>
void my_func1(void)
{
PORTO.1 = 0; /* uses general definition in abc_def.h */
#pragma endlibrary
Compile the file to an object file, rename the object file with
a . lib extension, and place it in a directory in the LIBRARY
path.
void my_func1(void);
Create your program source file and include both the device
header and the library header file.
#include <specific_device.h>
#include <my_library.h>
void main(void)
/* . . . */
my_func1();
/* . . . */
Page 129
STDIO
Name
Description
Name
Synopsis
#define BACKSPACE . . .
#include <stdio.h>
Description
Page 130
gets() retrieves a line from a device understood to be the
standard input, and places it in the buffer str, which has size
size . It retrieves characters up to a newline or carriage
return, or to size - 1. It zeros the last position of the buffer.
STDLIB
STDLIB
Name
stdlib is a library of standard functions.
Description
Name
Page 131
Synopsis
#include <stdlib.h>
#define SEED 0x3045 /* Seed must not be 0. */
int16 rand(void);
Description
To initialize the pseudorandom number sequence, call
randmize() in your initialization procedures. Then, call rand()
for each new random number.
Requirements
Name
abs() and labs() determine the absolute value.
TEAMFLY
Synopsis
#include <stdlib.h>
int8 abs(int8 i)
int16 labs(int16 l)
Description
value.
Team-Fly®
Page 132
Name
Synopsis
#include <stdlib.h>
Radix
Representation
2
Binary
16 characters
Octal
6 characters
10
Decimal
5 characters
16
Hexadecimal
4 characters
Representation
Binary
8 characters
Octal
3 characters
Page 133
Representation
Decimal
3 characters
Hexadecimal
2 characters
Radix
Representation
Binary
16 characters
Octal
7 characters
10
Decimal
6 characters
16
Hexadecimal
5 characters
Representation
Binary
8 characters
Octal
4 characters
Decimal
4 characters
Hexadecimal
3 characters
Name
Page 134
Synopsis
#include <stdlib.h>
Description
-0b1000000000000000 to
0b1111111111111111
Binary
-0o100000 to
0o17777
Octal
-0100000 to 0177777
Octal
-32768 to 65535
Decimal
-0x8000 to 0xffff
Hexadecimal
-0b10000000 to 0b11111111
Binary
-0o200 to 0o377
Octal
-0200 to 0377
Octal
-128 to 255
Decimal
-0x80 to 0xFF
Hexadecimal
qsort
Name
place.
Page 135
Synopsis
#include <stdlib.h>
pow
Name
Synopsis
#include <stdlib.h>
Page 136
STRING
Name
Description
size_t
Name
Synopsis
#include <string.h>
typedef unsigned int8 size_t;
Description
Name
Page 137
Synopsis
#include <string.h>
Description
memcpy() copies n bytes of memory from location src to
location memchr() searches an array for a character. It
begins at address s, and searches for the first element of
the array of size n that equals (unsigned char)c. It returns
the address of the matching element, or a null pointer if no
match was found.
Name
Synopsis
#include <string.h>
Page 138
Description
strlen
Name
Description
Name
Page 139
Synopsis
#include <string.h>
Description
CTYPE
CTYPE.H
Name
Description
Name
Page 140
Synopsis
#include <ctype.h>
Description
TEAMFLY
Team-Fly®
Page 141
DELAY
Name
wait.
Description
delay_ms
Name
Synopsis
#include <delay.h>
Description
Page 142
KEYPAD
Name
Requirements
Name
Synopsis
#define KEYPAD_PORT
#include <keypad.h>
Description
Page 143
"456B"
"789C"
"*0#D";
LCD
Name
Requirements
Description
Page 144
Configuration
LCD_DATA
Name
LCD_DATA_IN_CONTROL_OUT() and
LCD_DATA_OUT_CONTROL_IN() are macros to control the
LCD data and control ports.
Page 145
Synopsis
#define LCD_DATA_IN_CONTROL_OUT() ...
#include <lcd.h>
Description
Name
Synopsis
#include <lcd.h>
void lcd_init(void);
void lcd_busy_check(void);
Description
Page 146
Name
Synopsis
#include <lcd.h>
char lcd_getch(void);
Description
X0123456789...
Y +--------------------------------
0|
1|
...
Thus, to move the insert point to the final cell of the bottom
row of a 2-line, 40-space panel, use lcd_gotoXY(1,39);
Page 147
I2C_EE
Name
Description
Requirements
Page 148
Configuration
#define I2C_CONTROL PORT1
#define I2C_SCL 0
#define I2C_SDA 5
Name
Synopsis
#include <i2c_ee.h>
Description
Page 149
MWIRE_EE
Name
Description
•
A read/write serial input/output register
Requirements
Page 150
Configuration
You must define the following symbols before using the
mwire_ee library. If not defined, default values are used.
MWIRE_CONTROL
MWIRE_CLK
MWIRE_CS
MWIRE_DATA
MWIRE_DO
MWIRE_DI
MWIRE_PORT_DDR_READ()
MWIRE_PORT_DDR_WRITE()
MWIRE_PORT_DDR()
MICROWIRE port
mwire_bus_delay
Name
TEAMFLY
Synopsis
#include <mwire_ee.h>
void mwire_bus_delay() {
Description
Team-Fly®
Page 151
mwire_write_all
Name
Synopsis
#include <mwire_ee. h>
#define mwire_enable()
#define mwire_disable()
#define mwire_erase(ADDRESS)
Description
Page 152
MATH
Name
Description
Requirements
Requires float.h
Name
Synopsis
#include <math.h>
Description
acos() returns the angle in radians (from 0 to pi) whose
cosine is x.
Page 153
Name
Synopsis
#include <math.h>
Description
Name
Synopsis
#include <math.h>
Description
Page 154
fabs
Name
Synopsis
#include <math.h>
Description
fmod
Name
Synopsis
#include <math.h>
Description
Page 155
Name
exp(), log(), and log10() calculate exponents and logarithms.
Synopsis
#include <math.h>
Description
modf
Name
Synopsis
#include <math.h>
Description
Page 156
Name
Synopsis
#include <math.h>
Description
FLOAT.H
Name
Synopsis
#include <float.h>
#define FLT_DIG
#define FLT_EPSILON
#define FLT_MANT_DIG
#define FLT_MAX
#define FLT_MAX_10_EXP
#define FLT_MAX_EXP
#define FLT_MIN
Page 157
#define FLT_MIN_10_EXP
#define FLT_MIN_EXP
#define FLT_RADIX
#define FLT_ROUNDS
Description
Definitions
The
compiler
will
round
toward
the
nearest
representable
value.
Page 158
UART
UART
Name
Requirements
Definitions
UART_TD_PORT
UART_RD_PORT
UART_RD_PIN
Variables
uart_mode
Page 159
Configuration
Baud
Rate
Stop
Bits
Parity
Data
Bits
BAUD_2400 PARITY_ODD
BAUD_4800
BAUD_9600
BAUD_19200
BAUD_38400
BAUD_57600
BAUD_115200
Example:
Name
I/O.
Synopsis
char uart_getch(void);
void uart_putch(char);
char uart_kbhit(void);
Description
UART.
Page 160
PORT
Name
Requirements
Description
#define 00000000 0b11111111
TEAMFLY
Team-Fly®
Page 161
Name
Synopsis
#include <port.h>
DDR(port, direction)
DDR_WAIT()
Description
Example
DDR_WAIT();
DDR_WAIT();
Page 162
DDR_WAIT();
Page 163
Appendix B—
ASCII Chart
HEX
ASCII
HEX
ASCII
HEX
ASCII
HEX
ASCII
00
NUL
20
SP
40
60
01
SOH
21
41
61
02
STX
22
''
42
B
62
03
ETX
23
43
63
04
EOT
24
44
64
05
ENQ
25
45
65
06
ACK
26
&
46
66
07
BEL
27
'
47
G
67
08
BS
28
48
68
09
HT
29
49
69
(table continue on next page)
Page 164
HEX
ASCII
HEX
ASCII
HEX
ASCII
HEX
ASCII
0A
LF
2A
4A
J
6A
0B
VT
2B
4B
6B
0C
FF
2C
4C
6C
0D
CR
2D
4D
6D
0E
SO
2E
4E
6E
0F
SI
2F
4F
O
6F
10
DLE
30
50
70
11
DC1
31
51
71
12
DC2
32
52
72
13
DC3
33
53
73
14
DC4
34
54
T
74
15
NAK
35
55
75
16
SYN
36
56
76
17
ETB
37
57
77
18
CAN
38
58
78
19
EM
39
59
Y
79
1A
SUB
3A
5A
7A
1B
ESC
3B
5B
7B
1C
FS
3C
5C
7C
1D
GS
3D
5D
7D
1E
RS
3E
>
5E
7E
1F
US
3F
5F
7F
DEL
Page 165
Appendix C —
Glossary
A
accumulator
Also "A", "AC", or other names. The register that holds the
results of ALU operations.
A/D
Analog to digital.
addressing mode
ALU
AND
ANSI C
assembly language
Page 166
bank
bit field
block
breakpoint
CAN
cast
checksum
A value that is the result of adding specific binary values. A
checksum is often used to verify the integrity of a sequence
of binary numbers.
cross assembler
cross compiler
debugger
Page 167
declaration
dereference
EEPROM
embedded
endianness
global variable
hysteresis
index register
interrupt
J1850
local variable
logical operator
Operators that perform logical operations on their operands.
For example, !, &&, and ||.
Page 168
machine language
mask
maskable interrupt
memory-mapped
NOP
No operation. An instruction used to create a delay.
NOT
object code
operator
OR
paging
port
program counter
Also PC. A register that holds the address of the next
instruction to be executed. The program counter is
incremented after each byte of each instruction is fetched.
programmer's model
PROM
TEAMFLY
Team-Fly®
Page 169
real time
register
reset
ROMable
RS-232
SCI
SPI
scope
shift
simulator
stack
stack pointer
Page 170
static
timer
A peripheral that counts independent of program execution.
UART
volatile
watchdog (timer)
Page 171
Index
A
abs() 131
acknowledgement
asynchronous 26
synchronous 26
acos() 152
ahtoi16() 134
ahtoi8() 134
arbitration 27
architecture
Harvard 24
von Neumann 23
asin() 152
asynchronous acknowledgement 26
atan() 152
atan2() 152
atoi16() 134
atoi8() 134
block 79
bus 18
ceil() 153
constant 71
cos() 153
cosh() 153
data type
character 60
double 63
float 63
Page 172
integer 61
long 61
long double 63
parameter 60
short 61
emulator 108
exp() 155
fabs() 154
floor() 153
flowchart 9
FLT_DIG 157
FLT_EPSILON 157
FLT_MANT_DIG 157
FLT_MAX 157
FLT_MAX_10_EXP 157
FLT_MAX_EXP 157
FLT_MIN 157
FLT_MIN_10_EXP 157
FLT_MIN_EXP 157
FLT_RADIX 157
fmod() 154
frexp() 154
Harvard architecture 24
header file 63
i16toa() 133
I2C 147
i8toa() 133
identifier
constant 71
assigning to a float 63
interrupts 18, 26
keypad_debounce_delay() 143
L
labs() 131
LCD_DATA 144
LCD_E 144
LCD_RS 144
LCD_RW 144
ldexp() 155
LED 54
log() 155
log10() 155
maskable interrupts 26
microcontroller 19
MICROWIRE 149
modf() 155
mwire_disable() 151
mwire_enable() 151
mwire_erase() 151
mwire_read() 151
mwire_read_all() 151
mwire_write() 151
Page 173
nonmaskable interrupts 26
nonvectored arbitration 27
parameters 60
processor state 29
pseudocode 9
Q
qsort() 135
QSORT_COMPARE 135
RAM 58
rand() 131
randmize() 131
real numbers 63
scopes 21
simulator 108
sin() 153
sinh() 154
size_t 136
sqrt() 156
srand() 131
stack 20
state diagram 9
strcat() 138
strchr() 138
symbol table 59
synchronous acknowledgement 26
tan() 154
tanh() 154
timer 24
typographical conventions 4
bold 4
ui16toa() 132
ui8toa() 132
variables 9
vectored arbitration 27
watchdog timer 25
while 79
Page 180
also includes:
•
A schematic for the thermostat project
•
Pictures of a finished thermostat system
Supplementary documentation
System Rquirements
TEAMFLY
Team-Fly®
Document Outline
sample.pdf
sterling.com
Welcome to Sterling Software