Sei sulla pagina 1di 112

PIC book

CHAPTER I INTRODUCTION TO
MICROCONTROLLERS

CHAPTER V MPLAB
Introduction

Introduction
History
Microcontrollers versus microprocessors
1.1
1.2
1.3
1.4
1.5
1.6
1.7
1.8
1.9

Memory unit
Central processing unit
Buses
Input-output unit
Serial communication
Timer unit
Watchdog
Analog to digital converter
Program

CHAPTER II MICROCONTROLLER
PIC16F84

5.1
5.2
5.3
5.4
5.5
5.6
5.7
5.8

Installing the MPLAB program package


Introduction to MPLAB
Choosing the development mode
Designing a project
Designing new assembler file
Writing a program
MPSIM simulator
Toolbar

CHAPTER VI THE SAMPLES


Introduction
6.1 The microcontroller power supply
6.2 Macros used in programs

Introduction
CISC, RISC
Applications
Clock/instruction cycle
Pipelining
Pin description

6.3 Samples

2.1
2.2
2.3
2.4
2.5
2.6
2.7
2.8

Clock generator - oscillator


Reset
Central processing unit
Ports
Memory organization
Interrupts
Free timer TMR0
EEPROM Data memory

CHAPTER III INSTRUCTION SET


Introduction
Instruction set in PIC16Cxx microcontroller
family
Data Transfer
Arithmetic and logic
Bit operations
Directing the program flow
Instruction execution period
Word list

CHAPTER IV ASSEMBLY LANGUAGE


PROGRAMMING

Macros WAIT, WAITX


Macro PRINT

Light Emitting Diodes


Keyboard
Optocoupler
Optocouplering the input lines
Optocouplering the output lines
Relays
Generating a sound
Shift registers
Input shift register
Output shift register
7-segment Displays (multiplexing)
LCD display
12-bit AD converter
Serial communication

APPENDIX A INSTRUCTION SET

APPENDIX B NUMERIC SYSTEMS


Introduction
B.1 Decimal numeric system
B.2 Binary numeric system
B.3 Hexadecimal numeric system
APPENDIX C GLOSSARY

Introduction

http://www.mikroelektronika.co.yu/english/product/books/PICbook/picbook.htm (2 of 4) [5/11/2003 8:46:40 AM]

Contents
Preface
1 Introduction
1.1
1.2
1.3
1.4
1.5

The Idea of System Control


Computer in the Loop
Centralized and Distributed Control Systems
Scada Systems
Hardware Requirements for Computer Control
1.5.1 General Purpose Computers
1.5.2 Microcontrollers
1.6 Software Requirements for Computer Control
1.6.1 Polling
1.6.2 Using External Interrupts for Timing
1.6.3 Using Timer Interrupts
1.6.4 Ballast Coding
1.6.5 Using an External Real-Time Clock
1.7 Sensors Used in Computer Control
1.7.1 Temperature Sensors
1.7.2 Position Sensors
1.7.3 Velocity and Acceleration Sensors
1.7.4 Force Sensors
1.7.5 Pressure Sensors
1.7.6 Liquid Sensors
1.7.7 Air Flow Sensors
1.8 Exercises
Further Reading
2 System Modelling
2.1 Mechanical Systems
2.1.1 Translational Mechanical Systems
2.1.2 Rotational Mechanical Systems

xi
1
1
2
5
6
7
7
8
9
11
11
12
12
13
14
15
17
20
21
21
22
23
24
25
27
27
28
32

vi

CONTENTS

2.2 Electrical Systems


2.3 Electromechanical Systems
2.4 Fluid Systems
2.4.1 Hydraulic Systems
2.5 Thermal Systems
2.6 Exercises
Further Reading
3 The PIC Microcontroller
3.1 The PIC Microcontroller Family
3.1.1 The 10FXXX Family
3.1.2 The 12CXXX/PIC12FXXX Family
3.1.3 The 16C5X Family
3.1.4 The 16CXXX Family
3.1.5 The 17CXXX Family
3.1.6 The PIC18CXXX Family
3.2 Minimum PIC Conguration
3.2.1 External Oscillator
3.2.2 Crystal Operation
3.2.3 Resonator Operation
3.2.4 RC Operation
3.2.5 Internal Clock
3.3 Some Popular PIC Microcontrollers
3.3.1 PIC16F84 Microcontroller
3.3.2 PIC16F877 Microcontroller
3.4 Exercises
Further Reading
4 Programming PIC Microcontrollers in C
4.1 PICC Lite Variable Types
4.1.1 Bit
4.1.2 Unsigned Char
4.1.3 Signed Char
4.1.4 Unsigned Int
4.1.5 Signed Int
4.1.6 Long
4.1.7 Unsigned Long
4.1.8 Float
4.1.9 Double
4.2 Variables
4.3 Comments in Programs
4.4 Storing Variables in the Program Memory
4.5 Static Variables
4.6 Volatile Variables
4.7 Persistent Variables

37
42
44
44
49
52
52
57
57
58
59
59
59
60
60
61
63
63
63
65
65
66
67
71
75
76
77
78
78
78
79
79
79
79
79
80
80
80
81
82
82
83
83

CONTENTS

4.8
4.9
4.10
4.11
4.12
4.13
4.14
4.15

4.16

4.17
4.18

4.19
4.20
4.21
4.22
4.23

4.24

Absolute Address Variables


Bank1 Qualier
Arrays
ASCII Constants
Arithmetic and Logic Operators
Number Bases
Structures
Program Flow Control
4.15.1 IfElse Statement
4.15.2 SwitchCase Statement
4.15.3 For Statement
4.15.4 While Statement
4.15.5 Do Statement
4.15.6 Break Statement
4.15.7 Continue Statement
Functions in C
4.16.1 User Functions
4.16.2 Built-in Functions
Pointers in C
Pre-processor Commands
4.18.1 #dene
4.18.2 #include
4.18.3 #asm and #endasm
Accessing the EEPROM Memory
Interupts in C Programs
Delays in C Programs
Structure of a C Program
PIC Microcontroller InputOutput Interface
4.23.1 Connecting an LED
4.23.2 Connecting a Push-Button Switch
4.23.3 Connecting an LCD
Exercises
Further Reading

5 Microcontroller Project Development


5.1 Hardware and Software Requirements
5.2 Program Development Tools
5.2.1 Flow Charts
5.2.2 Structure Charts
5.2.3 Pseudocode
5.3 Exercise
Further Reading
6 Sampled Data Systems and the z-Transform
6.1 The Sampling Process
6.2 The z-Transform

vii

83
83
84
86
86
89
89
91
91
92
94
95
95
96
96
96
97
98
99
101
101
103
103
104
104
105
105
107
107
109
111
116
117
119
119
120
121
121
123
129
129
131
131
136

viii

CONTENTS

6.2.1 Unit Step Function


6.2.2 Unit Ramp Function
6.2.3 Exponential Function
6.2.4 General Exponential Function
6.2.5 Sine Function
6.2.6 Cosine Function
6.2.7 Discrete Impulse Function
6.2.8 Delayed Discrete Impulse Function
6.2.9 Tables of z-Transforms
6.2.10 The z-Transform of a Function Expressed as a Laplace Transform
6.2.11 Properties of z-Transforms
6.2.12 Inverse z-Transforms
6.3 Pulse Transfer Function and Manipulation of Block Diagrams
6.3.1 Open-Loop Systems
6.3.2 Open-Loop Time Response
6.3.3 Closed-Loop Systems
6.3.4 Closed-Loop Time Response
6.4 Exercises
Further Reading
7 System Time Response Characteristics
7.1
7.2
7.3
7.4

Time Response Comparison


Time Domain Specications
Mapping the s-Plane into the z-Plane
Damping Ratio and Undamped Natural Frequency in the z-Plane
7.4.1 Damping Ratio
7.4.2 Undamped Natural Frequency
7.5 Damping Ratio and Undamped Natural Frequency Using Formulae
7.6 Exercises
Further Reading
8 System Stability
8.1
8.2
8.3
8.4
8.5
8.6
8.7

Factorizing the Characteristic Equation


Jurys Stability Test
RouthHurwitz Criterion
Root Locus
Nyquist Criterion
Bode Diagrams
Exercises
Further Reading

9 Discrete Controller Design


9.1 Digital Controllers
9.1.1 Dead-Beat Controller
9.1.2 Dahlin Controller

137
137
138
138
139
139
140
140
140
140
143
145
154
154
156
162
166
166
169
171
171
174
177
178
178
179
181
183
184
187
187
189
192
194
201
205
208
211
213
214
215
217

CONTENTS

9.1.3 Pole-Placement Control Analytical


9.1.4 Pole-Placement Control Graphical
9.2 PID Controller
9.2.1 Saturation and Integral Wind-Up
9.2.2 Derivative Kick
9.2.3 PID Tuning
9.3 Exercises
Further Reading
10 Controller Realization

ix

219
222
230
233
233
134
137
240
243

10.1 Direct Structure


10.1.1 Direct Canonical Structure
10.1.2 Direct Noncanonical Structure
10.2 Cascade Realization
10.3 Parallel Realization
10.4 PID Controller Implementations
10.5 Microcontroller Implementations
10.5.1 Implementing Second-Order Modules
10.5.2 Implementing First-Order Modules
10.5.3 Implementing Higher-Order Modules
10.6 Choice of Sampling Interval
10.7 Exercises
Further Reading

243
243
245
246
249
250
253
254
260
263
263
267
268

11 Liquid Level Digital Control System: a Case Study

269

11.1
11.2
11.3
11.4
11.5

The System Schematic


System Model
Identication of the System
Designing a Controller
Conclusions

269
270
273
274
278

Appendix A

Table of z-Transforms

283

Appendix B

MATLAB Tutorial

285

Index

307

Contents
Preface .................................................................................................................. ix
Whats on the CD-ROM?....................................................................................... x
Chapter 1: Why Are We Doing This? ................................................................... 1
Selecting a Suitable Microcontroller ............................................................................................. 2
Selecting a Suitable 802.11b Communications Device ................................................................. 3
802.11b Hardware Overview ....................................................................................................... 3
AirDrop Basics ............................................................................................................................. 4

Chapter 2: The AirDrop-P ..................................................................................... 9


The AirDrop-P Hardware.............................................................................................................. 9
Learn to Play Guitar and Become Famous .................................................................................. 15

Chapter 3: The AirDrop-A................................................................................... 17


The AirDrop-A Hardware ........................................................................................................... 17
Bowing Out............................................................................................................................... 23

Chapter 4: 802.11b CompactFlash Network Interface Cards ........................... 25


They Were Not Designed To Do This .......................................................................................... 25
The TEW-222CF ........................................................................................................................ 25
Never Ignore an Inquisitive Author with Hand Tools ................................................................... 26
Unwrapping the TEW-222CF..................................................................................................... 30
An Undercover Look at the Zonet ZCF1100 ............................................................................... 32
Whats Behind Door Number 4 .................................................................................................. 34
RF, Witchcraft, Pointy Hats, Ghouls, Goblins...Same Thing ......................................................... 35

Chapter 5: Talking With 802.11bCompactFlash NICs........................................ 37


Physically Connecting a Microcontroller to a CompactFlash Card ............................................... 38
Musical Overtones..................................................................................................................... 43

Chapter 6: Touring the Card Information Structure ......................................... 45


Talking in Tuples ........................................................................................................................ 46
First Steps with the AirDrop-P .................................................................................................... 48
Walking the Tuple Chain............................................................................................................ 50
CIS Reconnaissance ................................................................................................................... 59

Contents
Dumping Linksys WCF12 Tuples ................................................................................................ 65
Dumping Netgear MA701 Tuples............................................................................................... 68
Dumping Zonet ZCF100 Tuples.................................................................................................. 70
Enabling the 802.11b CompactFlash NIC................................................................................... 74
The Value of Parsing the CIS...................................................................................................... 77
Full Throttle ............................................................................................................................... 77

Chapter 7: Learning to Talk to 802.11b CompactFlash NICs ............................ 79


What the 802.11b NIC Does for Us ........................................................................................... 79
The 802.11b CompactFlash NIC I/O Drivers................................................................................ 83

Chapter 8: Setting Up An AirDrop Wireless Network ...................................... 93


Setting Up the AP...................................................................................................................... 94
Somethings in the Air ............................................................................................................... 95
Guitars and Hollywood............................................................................................................ 104

Chapter 9: AirDrop Driver Basics ..................................................................... 105


BAP......................................................................................................................................... 105
FID .......................................................................................................................................... 106
RID.......................................................................................................................................... 107
Reading a RID.......................................................................................................................... 118
Stringing Up the SSID .............................................................................................................. 125
Good RIDdance ....................................................................................................................... 128
Retrieving the MAC Address.................................................................................................... 130
Status Check ........................................................................................................................... 134

Chapter 10: Putting an AirDrop on a Wireless LAN........................................ 137


Bogie Number 1 Allocating Transmit Buffers ......................................................................... 137
Bogie Number 2 Enabling the MAC ...................................................................................... 147
Authenticating the AirDrop Wireless LAN Station..................................................................... 158
Associating with the AIRDROP_NETWORK AP.......................................................................... 160

Chapter 11: Processing 802.11b Frames with the AirDrop ............................ 167
AirDrop Frame Structure.......................................................................................................... 168
AirDrop-P Frame Reception...................................................................................................... 184

Chapter 12: PINGING the AirDrop.................................................................... 209


Examining the IP Header.......................................................................................................... 231

Chapter 13: Flying Cargo with UDP and the AirDrop..................................... 243
Running a UDP Application on the AirDrop-P........................................................................... 243
The EDTP Internet Test Panel and the Code Behind It ............................................................... 245
Exercising the AirDrop-P with the EDTP Internet Test Panel....................................................... 249
Notes ...................................................................................................................................... 274

Chapter 14: Flying Cargo with TCP/IP and the AirDrop.................................. 275
TCP and the AirDrop-P ............................................................................................................ 275
The TCP/IP Stacks Physical Layer .............................................................................................. 284
The TCP/IP Stacks Data Link Layer ........................................................................................... 284
vi

Contents
The TCP/IP Stacks Network Layer............................................................................................. 284
The TCP/IP Stacks Transport Layer ........................................................................................... 284
The TCP/IP Stacks Application Layer ........................................................................................ 285
TCP/IP The Big Ugly .............................................................................................................. 285
Youve Done It! ....................................................................................................................... 334

Chapter 15: WEP and the AirDrop ................................................................... 335


Incorporating WEP into the AirDrop 802.11b Driver................................................................. 335
The New Experimental AirDrop Hardware ................................................................................ 345
An Experimental AVR AirDrop Variant...................................................................................... 345
The Experimental AirDrop Firmware......................................................................................... 348
Coding a Simple 802.11b Web Server ..................................................................................... 355
The AirDrop SRAM .................................................................................................................. 358

Chapter 16: A New Kid in Town Who Calls Himself ZigBee........................... 361
Zig What???............................................................................................................................ 361
Making ZigBee Talk ................................................................................................................. 363
The Microchip ZigBee Stack ..................................................................................................... 366

Chapter 17: Parting Frames .............................................................................. 371


Numeric Notation.................................................................................................................... 373
Source Code Presentation........................................................................................................ 373

Conventions ...................................................................................................... 373


Sub Snippets ........................................................................................................................... 374
Netasyst Sniffer Capture Text Presentation ............................................................................... 375
Mini Sniffs ............................................................................................................................... 375

Index .................................................................................................................. 377

vii

Contents

Part 1 Microcontroller
1 PIC Hardware

1
3

Processor System

PIC 16F877 Architecture

PIC Instruction Set

18

Special Function Registers

25

2 PIC Software

35

Assembly Language

37

Software Design

44

C Programming

47

3 Circuit Simulation

55

Basic Circuit

56

Software Debugging

63

Hardware Testing

65

Hardware Implementation

70

Program Downloading

73

xi

Contents

Part 2

Interfacing

77

Input & Output

79

Switch Input

79

Switch Debouncing

81

Timer and Interrupts

84

Keypad Input

87

7-Segment LED Display

88

Liquid Crystal Display

90

xii

Data Processing

101

Number Systems

101

Conversion

106

Variable Types

110

Arithmetic

112

Calculate, Compare & Capture

121

Calculator

121

Pulse Output

128

Period Measurement

130

Analogue Interfacing

141

8-bit Conversion

141

10-bit Conversion

145

Amplifier Interfaces

149

Contents

Part 3

Transient & Frequency Response

160

Instrumentation Amplifier

161

Current Loop

163

Comparators

165

Op-amp Selection

168

Analogue Output

168

Systems

177

8 Power Outputs

179

Current Drivers

179

Relays & Motors

183

Power Output Interfacing

185

Motor Interfacing

189

9 Serial Communication

201

USART

201

SPI

205

IC

10 Sensor Interfacing

210

223

Sensors

223

Sensor Types

228

Amplifier Design

236

Weather Station

238
xiii

Contents

xiv

11 System Design

249

Base System

249

Memory System

259

Other PIC Chips

266

System Design

270

Other MCU Families

274

Answers to Assessment Questions

279

Index & Abbreviations

291

CONTENIDO

Prologo
1. Microcontroladores programables: La solucin esta en un chip
2: Microcontroladores de 8 bits:
3: Los sellos mgicos de parallax
4: Pbasic: El lenguaje mas fcil del mundo
5: El primer contacto con el PIC16F84
6: En el interior del procesador
7: Los recursos fundamentales: temporizadores, puertas de e/s y eeprom de
datos
8: Interrupciones, reset y recursos auxiliares
9: Manejando el repertorio de instrucciones 10: Herramientas y diseo de
proyectos
11: Ejercicios de programacin en ensamblador
12: Los primeros diseos prcticos.
A: Gua Rpida del PIC16X84
B: Gua del usuario del SIM2000
C: Breve descripcin del Micro PIC Trainer
D: La familia PIC al completo
E: Contenido del CD
F: Proyectos con el PIC16F84 Bibliografa y direcciones de inters relacionadas
con los PIC ndice

Table of Contents

Preface

xv

Chapter 1 - Basic Electronics


1.0
1.1
1.2
1.3

The Atom
Isotopes and Ions
Static Electricity
Electrical Charge

1
2
3
4

1.3.1
1.3.2
1.3.3
1.3.4

4
4
5
5

Voltage
Current
Power
Ohm's Law

1.4 Electrical Circuits


1.4.1 Types of Circuits

1.5 Circuit Elements


1.5.1
1.5.2
1.5.3
1.5.4
1.5.5
1.5.6
1.5.7

Resistors
Revisiting Ohm's Law
Resistors in Series and Parallel
Capacitors
Capacitors in Series and in Parallel
Inductors
Transformers

1.6 Semiconductors
1.6.1
1.6.2
1.6.3
1.6.4

Integrated Circuits
Semiconductor Electronics
P-Type and N-Type Silicon
The Diode

Chapter 2 - Number Systems


2.0 Counting
2.0.1 The Tally System
2.0.2 Roman Numerals

2.1 The Origins of the Decimal System


2.1.1 Number Systems for Digital-Electronics
2.1.2 Positional Characteristics
2.1.3 Radix or Base of a Number System

6
6

8
9
9
10
12
13
14
15

15
16
16
17
17

19
19
19
20

20
22
22
23

vi

Microcontroller Programming

2.2 Types of Numbers


2.2.1 Whole Numbers
2.2.2 Signed Numbers
2.2.3 Rational, Irrational, and Imaginary Numbers

2.3 Radix Representations


2.3.1 Decimal versus Binary Numbers
2.3.2 Hexadecimal and Octal

2.4 Number System Conversions

23
24
24
24

25
25
26

27

2.4.1 Binary-to-ASCII-Decimal
2.4.2 Binary-to-Hexadecimal Conversion
2.4.3 Decimal-to-Binary Conversion

28
29
29

Chapter 3 - Data Types and Data Storage

33

3.0 Electronic-Digital Machines


3.1 Character Representations

33
33

3.1.1 ASCII
3.1.2 EBCDIC and IBM
3.1.3 Unicode

34
36
36

3.2 Storage and Encoding of Integers


3.2.1
3.2.2
3.2.3
3.2.4
3.2.5

Signed and Unsigned Representations


Word Size
Byte Ordering
Sign-Magnitude Representation
Radix Complement Representation

3.3 Encoding of Fractional Numbers


3.3.1
3.3.2
3.3.3
3.3.4
3.3.5

Fixed-Point Representations
Floating-Point Representations
Standardized Floating-Point Representations
IEEE 754 Single Format
Encoding and Decoding Floating-Point Numbers

3.4 Binary-Coded Decimals (BCD)


3.4.1 Floating-Point BCD

Chapter 4 - Digital Logic, Arithmetic, and Conversions


4.0 Microcontroller Logic and Arithmetic

37
37
38
39
40
41

44
45
46
47
48
50

51
52

55
55

4.0.1 CPU Flags


4.0.2 Word Size

55
56

4.1 Logical Instructions

56

4.1.1
4.1.2
4.1.3
4.1.4

Logical
Logical
Logical
Logical

AND
OR
XOR
NOT

4.2 Microcontroller Arithmetic


4.2.1 Unsigned and Twos Complement Arithmetic
4.2.2 Operations on Decimal Numbers

4.3 Bit Manipulations and Auxiliary Operations


4.3.1 Bit Shift and Rotate
4.3.2 Comparison Operations
4.3.3 Other Support Operations

57
57
57
58

58
58
60

62
62
63
63

Contents

vii

4.4 Unsigned Binary Arithmetic


4.4.1 Multi-byte Unsigned Addition
4.4.2 Unsigned Multiplication
4.4.3 Unsigned Division

4.5 Signed Binary Arithmetic


4.5.1 Overflow Detection in Signed Arithmetic
4.5.2 Sign Extension Operations
4.5.3 Multi-byte Signed Operations

4.6 Data Format Conversions


4.6.1
4.6.2
4.6.3
4.6.4
4.6.6

BCD Digits to ASCII Decimal


Unsigned Binary to ASCII Decimal Digits
ASCII Decimal String to Unsigned Binary
Unsigned Binary to ASCII Hexadecimal Digits
Signed Numerical Conversions

Chapter 5 - Circuits and Logic Gates


5.0 Digital Circuits
5.1 The Diode Revisited
5.1.1 The Light-Emitting Diode (LED)

5.2 The Transistor

64
64
65
67

67
69
70
71

72
72
73
73
75
76

77
77
78
79

81

5.2.1 Bipolar Transistor


5.2.2 MOS Transistor

81
83

5.3 Logic Gates


5.4 Transistor-Transistor Logic

84
85

5.4.1
5.4.2
5.4.3
5.4.4
5.4.5
5.4.6
5.4.7
5.4.8

Inverter Gates
The AND Gate
The NAND Gate
The OR Gate
The NOR Gate
Positive and Negative Logic
The XOR Gate
Schmitt Trigger Inverter

5.5 Other TTL Logic Families


5.6 CMOS Logic Gates

Chapter 6 - Circuit Components


6.0 Power Supplies
6.1 Clocked Logic and Flip-flops
6.1.1
6.1.2
6.1.3
6.1.4
6.1.5
6.1.6
6.1.7

The RS Flip-flop
Clocked RS Flip-flop
The D Flip-flop
The Edge-triggered D Flip-flop
Preset and Clear Signals
D Flip-flop Waveform Action
Flip-flop Applications

6.2 Clocks
6.2.1 Clock Waveforms
6.2.2 The TTL Clock
6.2.3 The 555 Timer

86
87
87
88
88
89
90
91

93
93

95
95
96
96
98
99
100
101
102
103

103
104
105
106

viii

Microcontroller Programming

6.2.4 Microcontroller Clocks

6.3 Frequency Dividers and Counters


6.3.1
6.3.2
6.3.3
6.3.4
6.3.5
6.3.6
6.3.7

Frequency Dividers
The JK Flip-flop Counter
Ripple Counters
Decoding Gates
Synchronous Counters
Counter ICs
Shift Registers

6.4 Multiplexers and Demultiplexers


6.4.1 Multiplexers
6.4.2 Demultiplexers
6.4.3 Multiplexer and Demultiplexer ICs

6.5 Input Devices


6.5.1 Switches
6.5.2 Switch Contact Bounce
6.5.3 Keypads
6.6 Output Devices
6.6.1 Seven-segment LED
6.6.2 Liquid Crystal Displays
6.6.3 LCD Technologies

Chapter 7 - The Microchip PIC


7.0 The PICMicro Microcontroller
7.0.1 Programming the PIC
PIC Programmers
Development Boards
7.0.2 Prototyping the PIC Circuit

7.1 PIC Architecture


7.1.1 Baseline PIC Family
PIC10 Devices
PIC12 Devices
PIC14 Devices
7.1.2 Mid-range PIC Family
PIC16 Devices
7.1.3 High-Performance PIC Family
PIC18 Devices

Chapter 8 - Mid-range PIC Architecture


8.0 Processor Architecture and Design
8.0.1
8.0.2
8.0.3
8.0.4
8.0.5

Harvard Architecture
RISC CPU Design
Single-word Instructions
Instruction Format
Mid-Range Device Versions

8.1 The Mid-range Core Features


8.1.1 Oscillator
8.1.2 System Reset
8.1.3 Interrupts

8.2 Mid-Range CPU and Instruction Set

106

107
107
107
108
110
110
112
113

115
115
118
118

118
118
120
121
122
122
124
125

129
129
130
131
131
132

134
134
135
135
138
138
139
139
139

141
142
142
143
143
144
145

145
145
147
148

149

Contents

ix

8.2.1 Mid-Range Instruction Set


8.2.2 STATUS and OPTION Registers

8.3 EEPROM Data Storage


8.3.1 EEPROM in Mid-Range PICs

8.4 Data Memory Organization


8.4.1 The w Register
8.4.2 The Data Registers
Memory Banks
The SFRs
The GPRs
8.4.3 Indirect Addressing

8.5 Mid-range I/O and Peripheral Modules


8.5.1
8.5.2
8.5.3
8.5.4
8.5.5
8.5.6

I/O Ports
Timer Modules
Capture-and-Compare Module
Master Synchronous Serial Port (MSSP) Module
USART Module
A/D Module

Chapter 9 - PIC Programming: Tools and Techniques


9.0 Microchips MPLAB
9.0.1 Embedded Systems

9.1 Integrated Development Environment


9.1.1
9.1.2
9.1.3
9.1.4

Installing MPLAB
Creating the Project
Project Build Options
Building the Project

9.2 Simulators and Debuggers


9.2.1 MPLAB SIM
9.2.2 MPLAB Hardware Debuggers
9.2.3 A Quick-and-Dirty Debugger

9.3 Programmers
9.4 Engineering PIC Software
9.4.1 Using Program Comments
Program Header
Commented Banners
Commented Bitmaps
9.4.2 Defining Data Elements
The cblock Directive
9.4.3 Banking Techniques
The banksel Directive
Bank Selection Macros
Deprecated Banking Instructions
9.4.4 Processor and Configuration Controls
Configuration Bits
9.4.5 Naming Conventions
9.4.6 Errorlevel Directive

9.5 Pseudo Instructions

149
151

153
153

154
154
154
154
155
157
158

158
159
160
160
161
161
161

163
163
164

165
165
167
169
169

170
171
172
174

174
175
176
176
177
178
179
179
180
180
180
181
182
182
184
186

186

Microcontroller Programming

Chapter 10 - Programming Essentials: Input and Output


10.0 16F84A Programming Template
10.1 Introducing the 16F84A
10.1.1 Template Circuit for 16F84A
10.1.2 Power Supplies
Voltage Regulator
10.1.3 Comparisons in PIC Programming
The Infamous PIC Carry Flag

10.2 Simple Circuits and Programs


10.2.1 A Single LED Circuit
LED Flasher Program
10.2.2 LED/Pushbutton Circuit
10.2.3 Multiple LED Circuit

189
189
191
191
191
192
193
194

194
194
196
199
202

10.3 Programming the Seven-segment LED


10.4 A Demonstration Board

204
206

10.4.1 PCB Images for Demo Board


10.4.2 TestDemo1 Program

206
208

Chapter 11 - Interrupts
11.0 Interrupts on the 16F84
11.0.1 The Interrupt Control Register
11.0.2 The OPTION Register

11.1 Interrupt Sources


11.1.1 Port-B External Interrupt
11.1.2 Timer0 Interrupt
11.1.3 Port-B Line Change Interrupt
Multiple External Interrupts
11.1.4 EEPROM Data Write Interrupt

11.2 Interrupt Handlers


11.2.1 Context Saving Operations
Saving w and STATUS Registers

11.3 Interrupt Programming


11.3.1 Programming the External Interrupt
RB0 Interrupt Initialization
RB0 Interrupt Service Routine
11.3.2 Wakeup from SLEEP Using the RB0 Interrupt
The SleepDemo Program
11.3.3 Port-B Bits 4-7 Status Change Interrupt
RB4-7 Interrupt Initialization
RB4-7 Change Interrupt Service Routine

11.4 Sample Programs


11.4.1 The RB0Int Program
11.4.2 The SleepDemo Program
11.4.3 The RB4to7Int Program

Chapter 12 - Timers and Counters

211
211
211
212

213
214
214
215
217
217

217
218
218

218
219
220
221
222
223
224
225
227

229
229
232
235

241

12.0 The 16F84 Timer0 Module

241

12.0.1 Timer0 Operation

241

Contents

xi

Timer0 Interrupt
Timer0 Prescaler

242
242

12.1 Delays Using Timer0

243

12.1.1 Long Delay Loops


How Accurate the Delay?
The Black-Ammerman Method

12.2 Timer0 as a Counter


12.3 Timer0 Programming
12.3.1 Programming a Counter
A Timer/Counter Test Circuit
The Tmr0Counter Program
12.3.2 Timer0 as a Simple Delay Timer
12.3.3 Measured Time Lapse
Interrupt-driven Timer

12.4 The Watchdog Timer


12.4.1 Watchdog Timer Programming

12.5 Sample Programs


12.5.1
12.5.2
12.5.3
12.5.4

The Tmr0Counter program


The Timer0 Program
The LapseTimer Program
The LapseTmrInt Program

Chapter 13 - LCD Interfacing and Programming


13.0 LCD Features and Architecture
13.0.1 LCD Functions and Components
Internal Registers
Busy Flag
Address Counter
Display Data RAM (DDRAM)
Character Generator ROM (CGROM)
Character Generator RAM (CGRAM)
Timing Generation Circuit
Liquid Crystal Display Driver Circuit
Cursor/Blink Control Circuit
13.0.2 Connectivity and Pin-Out

13.1 Interfacing with the HD44780


13.1.1
13.1.2
13.1.3
13.1.4

Busy Flag or Timed Delay Options


Contrast Control
Display Backlight
Display Memory Mapping

13.2 HD44780 Instruction Set


13.2.1 Instruction Set Overview
Clearing the Display
Return home
Entry mode set
Display and Cursor ON/OFF
Cursor/display shift
Function set
Set CGRAM address
Set DDRAM address
Read busy flag and Address register

244
245
245

246
247
247
248
248
250
252
255

259
260

260
260
263
265
269

275
275
276
276
276
276
276
276
277
277
278
278
278

279
280
281
281
281

283
283
283
284
284
284
284
285
285
285
285

xii

Microcontroller Programming

Write data
Read data
13.2.2 A 16F84 8-bit Data Mode Circuit

13.3 LCD Programming


13.3.1 Defining Constants and Variables
Using MPLAB Data Directives
13.3.2 LCD Initialization
Function Set Command
Display Off
Display and Cursor On
Set Entry Mode
Cursor and Display Shift
Clear Display
13.3.3 Auxiliary Operations
Time Delay Routine
Pulsing the E Line
Reading the Busy Flag
Bit Merging Operations
13.3.4 Text Data Storage and Display
Generating and Storing a Text String
Displaying the Text String
13.3.5 Data Compression Techniques
4-bit Data Transfer Mode
Master/Slave Systems

13.4 Sample Programs


13.4.1 LCDTest1
13.4.2 LCDTest2 Program
13.4.3 LCDTest3 Program

Chapter 14 - Communications
14.0 PIC Communications Overview
14.1 Serial Data Transmission
14.1.1
14.1.2
14.1.3
14.1.4

Asynchronous Serial Transmission


Synchronous Serial Transmission
PIC Serial Communications
The RS-232-C Standard
Essential Concepts
The Serial Bit Stream
Parity Testing
Connectors and Wiring
The Null Modem
The Null Modem Cable
14.1.5 The EIA-485 Standard
EIA-485 in PIC-based Systems

14.2 Parallel Data Transmission


14.2.1 PIC Parallel Slave Port (PSP)

14.3 PIC Free-style Serial Programming


14.3.1 PIC-to-PIC Serial Communications
PIC-to-PIC Serial Communications Circuits
PIC-to-PIC Serial Communications Programs
14.3.2 Program Using Shift Register ICs

285
286
286

287
287
289
290
290
291
291
292
292
293
293
293
295
295
296
298
299
301
302
302
304

306
306
316
327

339
339
340
340
342
342
343
344
344
345
345
346
347
349
350

350
351

351
352
352
354
360

Contents

xiii

The 74HC165 Parallel-to-Serial Shift Register


74HC164 Serial-to-Parallel Shift Register

14.4 PIC Protocol-based Serial Programming


14.4.1 RS-232-C Communications on the 16F84
The RS-232-C Transceiver IC
PIC to PC Communications
An RS-232-C TTY Board
A 16F84A UART Emulation
An LCD Scrolling Routine
14.4.2 RS-232-C Communications on the 16F87x
The 16F87x USART Module
The USART Baud Rate Generator
16F87x USART Asynchronous Transmitter
16F87x USART Asynchronous Receiver
PIC-to-PC RS-232-C Communications Circuit
16F877 PIC Initialization Code
USART Receive and Transmit Routines
The USART Receive Interrupt

14.5 Sample Programs


14.5.1
14.5.2
14.5.3
14.5.4
14.5.5
14.5.6

361
364

366
366
367
368
368
369
371
375
376
376
379
380
381
381
384
386

389

SerialSnd Program
SerialRcv Program
Serial6465 Program
TTYUsart Program
SerComLCD Program
SerIntLCD Program

389
394
400
404
420
438

Chapter 15 - Data EEPROM Programming

459

15.0 PIC Internal EEPROM Memory


15.0.1 EEPROM Programming on the 16F84
Reading EEPROM Data Memory on the 16F84
16F84 EEPROM Data Memory Write
16F84 EEPROM Demonstration Program
15.0.2 EEPROM Programming on the 16F87x
Reading EEPROM Data Memory on the 16F87x
Writing to EEPROM Data Memory in the 16F87x
GFR Access Issue in the 16F87x
15.0.3 16F87x EEPROM Circuit and Program

15.1 EEPROM Devices and Interfaces


15.1.1
15.1.2
15.1.3
15.1.4
15.1.5
15.1.6
15.1.7

The I2C Serial Interface


I2C Communications
EEPROM Communications Conditions
EEPROM Write Operation
EEPROM Read Operation
I2C EEPROM Devices
PIC Master Synchronous Serial Port (MSSP)
MSSP in Master Mode
15.1.8 I2C Serial EEPROM Programming on the 16F877
IC2 Initialization Procedure
I2C Write Byte Procedure
I2C Read Byte Procedure

15.2 Sample Programs

460
460
460
461
462
465
467
467
469
469

475
476
476
477
478
478
479
480
482
486
486
488
490

492

xiv

Microcontroller Programming

15.2.1 EECounter Program


15.2.2 Ser2EEP Program
15.2.3 I2CEEP Program

Chapter 16 - Analog to Digital and Realtime Clocks


16.0 A/D Converters
16.0.1 Converter Resolution
16.0.2 ADC Implementation

16.1 A/D Integrated Circuits


16.1.1 ADC0331 Sample Circuit and Program

16.2 PIC On-Board A/D Hardware


16.2.1 A/D Module on the 16F87x
The ADCON0 Register
The ADCON1 Register
SLEEP Mode Operation
16.2.2 A/D Module Sample Circuit and Program

16.3 Realtime Clocks


16.3.1 The NJU6355 Realtime Clock
16.3.2 RTC Demonstration Circuit and Program
BCD Conversion Procedures

16.4 Sample Programs


16.4.1 ADF84 Program
16.4.2 A2DinLCD Program
16.4.3 RTC2LCD Program

492
504
521

543
544
544
545

546
547

549
549
550
552
554
554

558
558
560
565

568
568
580
595

Appendix A - Resistor Color Codes

613

Appendix B - Building Your Own Circuit Boards

615

Appendix C - Mid-range Instruction Set

621

Appendix D - Supplementary Programs

659

Index

795

Contents
1.

Digital Design Fundamentals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1


1.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Binary Math . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.2.1 Representation of Integers and Floating Point Variables. . . . . . . . . . . . . . .2
1.2.2 Twos Complement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.2.3 Floating Point Notation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2.4 Basic Math Operations: Addition and Subtraction . . . . . . . . . . . . . . . . . . . 4
1.3 Codes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3.1 Unicode and ASCII . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3.2 Gray Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.4 Combinational and Sequential Circuits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.4.1 Digital Design Building Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.5 Digital Design Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.5.1 Programmable Gate Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.5.2 Microprocessors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.5.3 Digital Signal Processors (DSPs) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.5.4 Microcontrollers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.5.5 Mixed Mode Processing Microcontroller with FPGA . . . . . . . . . . . . . . . 13
1.6 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

2.

The Design and Development Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15


2.1 The Design Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.2 Implementation and Testing Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
2.2.1 Software Development Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.3 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

3.

Microcontroller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
3.1 So What Exactly is a Microcontroller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
3.1.1 Microcontroller Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
3.1.2 Basic Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
3.1.3 RISC versus CISC Instruction Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
3.2 Register Set. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .33

vi

CONTENTS

3.3

3.4
3.5
3.6
3.7
3.8

3.9
3.10
3.11
3.12
3.13
3.14
4.

Bus Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
3.3.1 Address Bus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
3.3.2 Data Bus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
3.3.3 Control Bus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
Time Base . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
3.5.1 Timing Subsystem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
Port Systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
Analog-to-Digital Converters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Communication Systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
3.8.1 Serial Communications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
3.8.2 Terminology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
3.8.3 Serial Communication Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
3.8.4 Handshake Mechanisms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
3.8.5 RS-232 Protocol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Interrupt System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Speed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
Choosing a Microcontroller for a Specic Design . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
3.11.1 System Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
Microcontroller Vendors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
Cutting Edge Technology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48

Timing Subsystem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
4.1 Background Theory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
4.1.1 Frequency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
4.1.2 Period . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
4.1.3 Duty Cycle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
4.2 Timer System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
4.2.1 Hardware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
4.2.2 Operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
4.3 Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
4.3.1 Measuring External Timing Event . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
4.3.2 Counting Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
4.3.3 Generating Timing Signals to Interface External Devices . . . . . . . . . . . . 59
4.3.4 Industrial Implementation Case Study (PWM) . . . . . . . . . . . . . . . . . . . . . 60
4.4 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62

CONTENTS

vii

5.

Analog-to-Digital Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
5.1 Background Theory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
5.1.1 Analog Signals Versus Digital Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
5.1.2 Sampling, Quantization, and Encoding . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
5.1.3 Resolution and Data Rate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
5.2 Analog-to-Digital Conversion Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
5.3 ADC Conversion Technologies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
5.3.1 Successive-Approximation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
5.3.2 Integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
5.3.3 Counter-Based Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
5.3.4 Parallel Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
5.4 Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
5.4.1 Signal Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
5.4.2 Signal Conditioning for ATD Converters . . . . . . . . . . . . . . . . . . . . . . . . . . 79
5.4.3 Digital-to-Analog Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
5.4.4 Industrial Implementation: Digital Cameras . . . . . . . . . . . . . . . . . . . . . . . . 81
5.5 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82

6.

Networked Microcontrollers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
6.1 Background Theory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
6.1.1 Designing Computer Networks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
6.1.2 Types of Networks and Protocols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
6.2 Microcontroller Networks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
6.2.1 Controller Area Network . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
6.2.2 BDLC Networks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
6.2.3 Customized Networks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
6.3 Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
6.3.1 Automobiles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
6.3.2 Mobile Robots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
6.4 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92

7.

Operating Parameters and Interfacing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95


7.1 Operating Parameters. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .95
7.2 Input Devices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
7.2.1 Switches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
7.2.2 Switch Debouncing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
7.2.3 Keypads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
7.2.4 Sensors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102

viii

CONTENTS

7.3

7.4
7.5

Output Devices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102


7.3.1 Light-Emitting Diodes (LEDs) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
7.3.2 Liquid Crystal Display (LCD) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
7.3.3 DC Devices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
7.3.4 AC Devices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
Application: DC Motor Speed and Direction Control . . . . . . . . . . . . . . . . . . . . . 106
7.4.1 Motor Operating Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107

Contents

Preface ................................................................................................................. ix
A Quick Look at the Microcontrollers .................................................................................. x
Atmels AVR ................................................................................................................. x
Microchips PIC ........................................................................................................... xii

Whats on the CD-ROM? .................................................................................. xvi


Chapter 1: The Essence of Microcontroller NetworkingRS-232 ......................... 1
Some History ...................................................................................................................... 3
RS-232 Standard Operating Procedure ................................................................................ 5
RS-232 Voltage Conversion Considerations ......................................................................... 8

Chapter 2: Implementing RS-232 with a Microcontroller .................................... 11


Basic RS-232 Hardware .................................................................................................... 11
Building a Simple Microcontroller RS-232 Transceiver ........................................................ 14
RS-232 Interface Hardware ........................................................................................ 15
A Microcontroller DCE Device .................................................................................... 16
Microchips PICkit 1 FLASH Starter Kit ........................................................................ 16
Writing Some Simple RS-232 Firmware ...................................................................... 20
A Bit of RS-232 Transmit Code ................................................................................... 27
Some RS-232 Receive Code ....................................................................................... 32

Chapter 3: Writing RS-232 Microcontroller Routines in BASIC ............................ 37


BASIC RS-232 .................................................................................................................. 37

Chapter 4: Building Some RS-232 Communications Hardware ........................... 43


A Few More BASIC RS-232 Instructions ............................................................................ 43

Contents
Chapter 5: Using Microcontroller USARTs ............................................................. 47
Some Interrupt-Driven USART Code ................................................................................. 50
Applying What We Know about RS-232 to the Atmel AVR ............................................... 70
Coding the AVR RS-232 Routines ............................................................................... 73

Chapter 6: I2CThe Other Serial Protocol ............................................................. 81


Why use IC? ................................................................................................................... 83
The IC bus ...................................................................................................................... 83
IC ACKS and NAKS .................................................................................................. 86
More on Arbitration and Clock Synchronization ......................................................... 87
IC Addressing ........................................................................................................... 91
Some IC Firmware .................................................................................................... 91
The AVR Master IC Code .......................................................................................... 92
The AVR IC Master-Receiver Mode Code .................................................................. 97
The PIC IC Slave-Transmitter Mode Code .................................................................. 99
The AVR-to-PIC IC Communications Ball ................................................................. 105

Chapter 7: Ethernet ............................................................................................... 121


What is Ethernet? .......................................................................................................... 121
The CS8900A-CQ .......................................................................................................... 122
CS8900A-CQ Reset Overview .................................................................................. 123
CS8900A-CQ Media Interface Overview .................................................................. 123
CS8900A-CQ Transmit Process Overview ................................................................. 123
CS8900A-CQ Receive Process Overview ................................................................... 124
CS8900A-CQ External Storage Overview ................................................................. 125
CS8900A-CQ Status Indicators ................................................................................. 126
The CS8900A-CQ MAC Engine ................................................................................ 126
Easy Ethernet CS8900A Hardware .................................................................................. 130
The PIC16F877 Microcontroller ................................................................................ 130
The Microchip PIC18F452 ........................................................................................ 131
The CS8900A-CQ Ethernet Engine ................................................................................. 131
Powering the CS8900A-CQ ............................................................................................ 132
The CS8900A-CQ Ethernet Magnetics ............................................................................ 132
Designing in the Easy Ethernet CS8900As PIC16F877 Microcontroller ............................. 135
The ICSP (In-Circuit Serial Programming) Interface .......................................................... 136
Developing the Easy Ethernet CS8900A Firmware .......................................................... 139
Setting up the PIC16F877 Microcontroller ....................................................................... 141
Carving up the PIC16F877s Memory Resources .............................................................. 143
Function Prototypes ................................................................................................. 143
Defining the Variables .............................................................................................. 144
The Easy Ethernet CS8900A Macros ............................................................................... 151
Defining the CS8900A-CQ PacketPage Register Set ........................................................ 156
CS8900A-CQ Bus Interface Registers ....................................................................... 158
Product Identification Code ...................................................................................... 158

vi

Contents
CS8900A-CQ Status and Control Registers ............................................................... 159
Did It Register? ........................................................................................................ 172

Chapter 8: Writing the CS8900A-CQ Firmware .................................................. 173


The First Step ................................................................................................................. 174
Reset the CS8900A-CQ .................................................................................................. 175
Load the CS8900A-CQ Basic Parameters ........................................................................ 176
Load the CS8900A-CQ Individual Address Register Set ................................................... 178
Enable the CS8900A-CQ Transmitter and Receiver .......................................................... 179
The Main Service Loop ................................................................................................... 180
A Frame Under the Microscope ...................................................................................... 182
The Art of ARP ............................................................................................................... 189

Chapter 9: PINGing the Easy Ethernet CS8900A ................................................. 203


Chapter 10: UDP and the Easy Ethernet CS8900A .............................................. 221
A UDP Internet Test Panel ............................................................................................... 223

Chapter 11: TCP and the Easy Ethernet CS8900A............................................... 239


The Physical Layer .......................................................................................................... 241
The Data Link Layer ........................................................................................................ 241
The Network Layer ......................................................................................................... 242
The Transport Layer ........................................................................................................ 242
The Application Layer ..................................................................................................... 242
Coding TCP/IP for the Easy Ethernet CS8900A ............................................................... 244

Chapter 12: Lets Do It Again ................................................................................ 293


Easy Ethernet Whacked??? What the? ....................................................................... 293
The Realtek RTL8019AS ................................................................................................. 294
The Easy Ethernet W Hardware ...................................................................................... 302
The Easy Ethernet W Firmware ....................................................................................... 304
Initializing the Realtek RTL8019AS .................................................................................. 307
Online with the Easy Ethernet W .................................................................................... 324
Sending a Frame using the Easy Ethernet W ................................................................... 327
Tools for Work and Play .................................................................................................. 331

Chapter 13: Putting the Easy Ethernet AVR Online ........................................... 337
Chapter 14: Finale ................................................................................................. 347
Obtaining Easy Ethernet Devices ..................................................................................... 348

About the Author .................................................................................................. 349


Index ....................................................................................................................... 351
vii

Contents
Introduction

ix

Introduction to the PIC microcontroller

The aim of the book


Program memory
Microcontroller clock
The microcontroller system
Types of microcontroller
Microcontroller specification
Using the microcontroller
1 Microcontroller hardware
2 Programming the microcontroller

1
2
3
3
4
5
6
6
9

Programming the 16F84 microcontroller

11

Microcontroller inputs and output (I/O)


Timing with the microcontroller
Programming the microcontroller
Entering data
The header for the 16F84
Program example
Saving and assembling the code
PICSTART PLUS programmer
Programming flowchart
Problem: flashing two LEDs
Solution to problem, flashing two LEDs

12
12
12
13
14
16
19
23
26
26
27

Introductory projects

29

LED_Flasher2
SOS
Code for SOS circuit
Flashing 8 LEDs
Chasing 8 LEDs
Traffic lights
More than 8 outputs

29
30
30
33
35
39
45

Headers, porting code which micro?

47

Factors affecting the choice of the microcontroller


Choosing the microcontroller
Headers

47
48
49

vi Contents
5

10

11

Using inputs

64

Switch flowchart
Program development
Scanning (using multiple inputs)
Switch scanning
Control application a hot air blower

66
67
73
73
77

Understanding the headers

82

The 16F84
16F84 memory map
The 16F818

82
87
88

Keypad scanning

93

Programming example for the keypad

94

Program examples

110

Counting events
Look up table
7-Segment display
Numbers larger than 255
Long time intervals
One hour delay

110
115
115
126
133
136

The 16C54 microcontroller

139

Header for the 16C54


16C54 memory map

139
142

Alpha numeric displays

143

Display pin identification


Configuring the display
Writing to the display
Program example
Program operation
Display configuration
Writing to the display
Displaying a number

144
145
146
146
160
161
162
163

Analogue to digital conversion

166

Making an A/D reading


Configuring the A/D device
Analogue header for the 16F818
A/D conversion example, a temperature sensitive
switch
Program code
Another example a voltage indicator

167
168
171
174
176
178

Contents
12

13

14

15

16

17

vii

Radio transmitters and receivers

186

Measuring the received pulse width

189

EEPROM data memory

199

Example using the EEPROM

200

Interrupts

207

Interrupt sources
Interrupt control register
Program using an interrupt

208
208
209

The 12 series 8 pin microcontroller

216

Pin diagram of the 12C508/509


Pin diagram of the 12F629 and 12F675
Features of these 12 series
The memory map of the 12C508
Oscillator calibration
I/O PORT, GPIO
Delays with the 12 series
Header for 12C508/9
Program application for 12C508
Program application using the 12F629/675

216
216
217
217
218
219
220
220
222
225

The 16F87X Microcontroller

229

16F87X family specification


The 16F872 microcontroller
16F87X memory map
The 16F872 header
16F872 application a greenhouse control
Programming the 16F872 microcontroller
using PICSTART PLUS
Reconfiguring the 16F872 header

229
230
232
233
236

The 16F62X Microcontroller

245

16F62X oscillator modes


16F62X and 16F84 Pinouts
16F62X port configuration
16F62X memory map
The 16F62X headers
HEAD62RC.ASM
A 16F627 application flashing an LED on and off
The 16F627 LED flasher code
Configuration settings for the 16F627
Other features of the 16F62X

245
247
247
248
248
250
252
253
255
255

242
243

viii
18

19

Contents
Projects

257

Project 1 Electronic dice


Project 2 Reaction timer
Project 3 Burglar alarm
Fault finding
Development kits

257
266
272
282
285

Instruction set, files and registers

287

The PIC microcontroller instruction set


Registers
Instruction set summary

287
289
292

Appendix
Appendix
Appendix
Appendix
Index

A Microcontroller data
B Electrical characteristics
C Decimal, binary and hexadecimal numbers
D Useful contacts

299
301
303
306
307

Contents

Chapter 1. Conventions Used in This Book

Chapter 2. PICmicro MCU Part Number


Feature Comparison

Feature to Part Number Table

Chapter 3. Device Pinouts


Low-End
Mid-Range
PIC17Cxx
PIC18Cxx

7
8
10
14
17

Chapter 4. PICmicro MCU Instruction Sets

21

Parameters
Low-End Instruction Set
Mid-Range Instruction Set
PIC17Cxx Instruction Set
PIC18Cxx Instruction Set
Microchip Special Instruction Mnemonics
Parallax PICmicro MCU Instruction Set

21
22
31
40
63
104
111

Copyright 2001 The McGraw-Hill Companies. Click Here for Terms of Use.

vi

Contents

Chapter 5. PICmicro MCU Processor


Architectures
The PICmicro MCUs Arithmetic Logic Unit
Low-End PICmicro MCUs
Register access
STATUS register
Program counter
Mid-Range PICmicro MCUs
Register access
STATUS register
Program counter
Interrupt operation
Interrupt handler skeleton
PIC17Cxx
Register access
STATUS register
Program counter
Interrupt operation
Interrupt handler skeleton
PIC18Cxx
Register access
STATUS register
Program counter
Interrupt operation
Interrupt handler skeleton

123
123
125
126
128
128
130
130
132
133
134
135
136
137
138
139
140
142
142
144
146
147
150
150

Chapter 6. PICmicro MCU Register Mappings 151


Low-End PICmicro MCUs
Mid-Range PICmicro MCUs
PIC17Cxx
PIC18Cxx

151
154
169
186

Contents
Chapter 7. Built-In Hardware Features
Configuration Registers
Oscillators
Sleep
Option Register
Input/Output Ports and TRIS Registers
Watchdog Timer
TMR0
Prescaler
TMR1
TMR2
Compare/Capture/PWM(CCP) Module
USART Module
SSP Module
SPI operation
I2C operation
Built-In ADC
Built-In Comparators
Parallel Slave Port
Built-In EEPROM Data Memory Access
EPROM Program Memory Access
Flash Program Memory Access
External Parallel Memory

Chapter 8. PICmicro MCU


Hardware Interfacing
Power
Reset
Digital Logic Interfacing

vii
207
207
208
213
216
217
221
222
223
224
227
228
232
239
239
244
252
257
261
263
269
271
273

277
277
281
282

viii

Contents

Parallel Bus Device Interfacing


Button Interfacing
Switch Matrix Keypad/Keyboard Interfacing
Combining Input and Output
Simulated Open Collector/Open Drain I/O
LEDs
Multisegment LED displays
LCD Interfaces
I2C Bit Banging Master Interface
RS-232 Interfaces
RS-485/RS-422
Asynchronous Serial I/O Software Routines
Dallas Semiconductor One-Wire Interface
Reading Potentiometer Using Parallel I/O Pins
Motor Drivers
R/C Servo Control
Audio Output
AC Power Control
Hall-Effect Sensors
Sony Infrared TV Remote Control

282
284
287
291
292
293
293
296
334
338
345
347
357
363
365
370
371
373
374
374

Chapter 9. PICmicro MCU Programming

379

Hex File Format


Low-End PICmicro MCU Programming
Mid-Range Serial Programming
PIC17Cxx Programming
PIC17Cxx ICSP Programming
PIC18Cxx Programming
Microchip ICSP Programming Connector
Third Party/Downloadable Programmers

379
381
385
394
398
402
405
406

Contents
Chapter 10. PC Interfaces
Memory Map
I/O Space Map
Interrupt Function by Number
ISA Bus
ISA pinouts
Interrupts
Keyboard and Mouse Ports
Connector specification
Keyboard operation with timing diagrams
Keyboard scan codes
Keyboard controller commands
BIOS interfaces
Keyboard commands
Serial Port
Connector pinouts
8250 block diagram
Serial port base addresses
8250 registers
Interrupts
Interrupt 14hRS-232 communications APIs
Parallel Port
Block diagram/connector
Base registers
Registers
Data output waveform
BIOS interfaces

ix
407
407
407
422
425
425
429
430
430
431
432
436
436
441
441
442
443
443
444
449
451
455
455
457
457
458
459

Chapter 11. Useful Code Snippets

461

Jumping Outside the Current Page


Tables
Conditional Branching

461
462
465

Contents
Time Delays
Negating the Contents of a Register
Incrementing/Decrementing w
Rotating a Byte in Place
Copy Bits from One Register to Another
Converting a Nybble to ASCII
Converting an ASCII Byte to a Hex Nybble
Using T0CKI as an Interrupt Source Pin
Dividing by Three
Sixteen-Bit Pulse Measurement with
5-Cycle Delay
Detect a Change in a Register
Test a Byte within a Range
Convert ASCII to Upper Case
Swap the Contents of w with a Register
Swap the Contents of Two Registers
Compare and Swap if Y  X
Counting the Number of 1s in a Byte
Generating Parity for a Byte
Keeping a Variable within a Range
Swapping Bit Pairs
Bitwise Operations
Constant Multiplication
Constant Division

Chapter 12. 16-Bit Numbers


Defining 16 Bit Numbers
Increments and Decrements
Addition/Subtraction
Bitwise Operations on Constants and Variables

466
467
468
469
470
470
471
471
472
473
474
474
475
475
475
476
476
477
477
478
478
479
480

483
483
484
485
488

Contents
Comparisons with 16-Bit Variables
Multiplication
Division

Chapter 13. PICmicro MCU


Operations Tables
I/O Pin Current Capabilities
RC Oscillator Component Values
LP Oscillator Operating Characteristics
XT Oscillator Operating Characteristics
HS Oscillator Operating Characteristics

xi
489
492
495

499
500
500
501
502
504

Chapter 14. PICmicro MCU Application


Debugging Checklist

507

Chapter 15. PICmicro MCU Application


Software Development Tools

517

Microsoft Compatible Editor Ctrl Key


Combinations
MPSIM.INI
MPLAB
Stimulus (.STI) files
MPLAB assembler directives
Standard Declaration and Include (.inc) Files
LinkingLinked Applications
Application Code Template
The BASIC Language
Microsoft BASIC Enhancements
PicBasic

517
518
519
525
526
536
536
539
540
542
549

xii

Contents
Visual Basic
MSComm control
The C Language
Declarations
Statements
Operators
Directives
Backslash characters
Common C functions
PICmicro MCU enhancement functions

578
581
588
588
590
593
595
598
598
603

Chapter 16. Constants and Data Tables

605

Mathematical and Physical Constants


ASCII
ASCII control characters
ANSI display control sequences
IBM PC extended ASCII characters
Windows ASCII characters
EBCDIC
Audio Notes
Touch-Tone Telephone Frequencies
Modem AT Commands
Modem registers
Morse Code
Phonetic Alphabets
Ten Radio Codes

605

Chapter 17. Miscellaneous Electronics

629

Resistor Color Coding


Electromagnetic Spectrum
Radar bands

606
607
609
612
612
612
615
616
616
622
625
626
626

629
630
632

Contents
Digital Logic
Gates
Flip flops

Chapter 18. Formulas


DC Electronics Formulas
AC Electronics Formulas
Mathematical Formulas
Boolean Arithmetic
Conversions

Chapter 19. Resources


Microchip
PICmicro MCU Books
Useful Books
PICList Internet List Server
Recommended PICmicro MCU Web Sites
Periodicals
Useful Web Sites
Hardware FAQs
Part Suppliers
Digi-Key
AP Circuits
Wirz Electronics
Tower Hobbies
Jameco
JDR
Newark
Marshall Industries
Mouser Electronics
Mondo-tronics Robotics Store

Index

xiii
632
632
633

635
635
636
638
638
640

641
641
642
643
648
656
658
659
660
661
661
661
662
663
663
663
664
664
665
665

667

Contents
Introduction
Acknowledgements

Section 1
1

Getting Started with Embedded Systems

Tiny computers, hidden control


1.1

The main idea embedded systems in todays world


1.1.1 What is an embedded system?
1.2 Some example embedded systems
1.2.1 The domestic refrigerator
1.2.2 A car door mechanism
1.2.3 The electronic ping-pong
1.2.4 The Derbot Autonomous Guided Vehicle
1.3 Some computer essentials
1.3.1 Elements of a computer
1.3.2 Instruction sets CISC and RISC
1.3.3 Memory types
1.3.4 Organising memory
1.4 Microprocessors and microcontrollers
1.4.1 Microprocessors
1.4.2 Microcontrollers
1.4.3 Microcontroller families
1.4.4 Microcontroller packaging and appearance
1.5 Microchip and the PIC microcontroller
1.5.1 Background
1.5.2 PIC microcontrollers today
1.6 An introduction to PIC microcontrollers using the 12 Series
1.6.1 The 12F508 architecture
1.7 What others do a Freescale microcontroller
Summary
References

Section 2
2

Minimum Systems and the PIC 16F84A

xxi
xxv

1
3
3
3
4
4
5
6
7
8
9
9
10
10
11
11
12
13
14
15
15
15
17
18
20
22
22

23

Introducing the PIC 16 Series and the 16F84A

25

2.1

25
25

The main idea the PIC 16 Series family


2.1.1 A family overview

vi

Contents
2.1.2 The 16F84A
2.1.3 A caution on upgrades
2.2 An architecture overview of the 16F84A
2.2.1 The Status register
2.3 A review of memory technologies
2.3.1 Static RAM (SRAM)
2.3.2 EPROM (Erasable Programmable Read-Only Memory)
2.3.3 EEPROM (Electrically Erasable Programmable Read-Only Memory)
2.3.4 Flash
2.4 The 16F84A memory
2.4.1 The 16F84A program memory
2.4.2 The 16F84A data and Special Function Register memory (RAM)
2.4.3 The Configuration Word
2.4.4 EEPROM
2.5 Some issues of timing
2.5.1 Clock oscillator and instruction cycle
2.5.2 Pipelining
2.6 Power-up and Reset
2.7 What others do the Atmel AT89C2051
2.8 Taking things further the 16F84A on-chip reset circuit
Summary
References

27
27
27
29
29
30
31
31
31
32
32
33
35
35
37
37
38
38
40
41
44
44

Parallel ports, power supply and the clock oscillator

45

3.1
3.2

46
46
46
49
49
52
52
53
55
55
55
56
59
59
60
60
61
61
62
63

3.3

3.4

3.5

3.6

3.7

The main idea parallel input/output


The technical challenge of parallel input/output
3.2.1 Building a parallel interface
3.2.2 Port electrical characteristics
3.2.3 Some special cases
Connecting to the parallel port
3.3.1 Switches
3.3.2 Light-emitting diodes
The PIC 16F84A parallel ports
3.4.1 The 16F84A Port B
3.4.2 The 16F84A Port A
3.4.3 Port output characteristics
The clock oscillator
3.5.1 Clock oscillator types
3.5.2 Practical oscillator considerations
3.5.3 The 16F84A clock oscillator
Power supply
3.6.1 The need for power, and its sources
3.6.2 16F84A operating conditions
The hardware design of the electronic ping-pong

Contents

vii

Summary
References

64
64

Starting to program an introduction to Assembler

65

4.1

The main idea what programs do and how we develop them


4.1.1 The problem of programming and the Assembler compromise
4.1.2 The process of writing in Assembler
4.1.3 The program development process
4.2 The PIC 16 Series instruction set, with a little more on the ALU
4.2.1 More on the PIC 16 Series ALU
4.2.2 The PIC 16 Series instruction set an introduction
4.3 Assemblers and Assembler format
4.3.1 Introducing Assemblers and the Microchip MPASMTM Assembler
4.3.2 Assembler format
4.3.3 Assembler directives
4.3.4 Number representation
4.4 Creating simple programs
4.4.1 A simple data transfer program
4.5 Adopting a development environment
4.5.1 Introducing MPLAB
4.5.2 The elements of MPLAB
4.5.3 The MPLAB file structure
4.6 An introductory MPLAB tutorial
4.6.1 Creating a project
4.6.2 Entering source code
4.6.3 Assembling the project
4.7 An introduction to simulation
4.7.1 Getting started
4.7.2 Generating port inputs
4.7.3 Viewing microcontroller features
4.7.4 Resetting and running the program
4.8 Downloading the program to a microcontroller
4.9 What others do a brief comparison of CISC and RISC instruction sets
4.10 Taking things further the 16 Series instruction set format
Summary
References

66
66
67
68
69
69
70
71
71
71
72
72
73
73
76
76
76
77
77
77
79
80
81
81
81
82
82
83
86
87
88
88

Building Assembler programs

89

5.1

89
89
91
92
92
94

5.2

The main idea building structured programs


5.1.1 Flow diagrams
5.1.2 State diagrams
Flow control branching and subroutines
5.2.1 Conditional branching and working with bits
5.2.2 Subroutines and the Stack

viii

Contents
5.3
5.4

Generating time delays and intervals


Dealing with data
5.4.1 Indirect addressing and the File Select Register
5.4.2 Look-up tables
5.4.3 Example program with delays and look-up table
5.5 Introducing logical instructions
5.6 Introducing arithmetic instructions and the Carry flag
5.6.1 Using add instructions
5.6.2 Using subtract instructions
5.6.3 An arithmetic program example
5.6.4 Using indirect addressing to save the Fibonacci series
5.7 Taming Assembler complexity
5.7.1 Include Files
5.7.2 Macros
5.7.3 MPLAB special instructions
5.8 More use of the MPLAB simulator
5.8.1 Breakpoints
5.8.2 Stopwatch
5.8.3 Trace
5.9 The ping-pong program
5.9.1 A structure for the ping-pong program
5.9.2 Exploring the ping-pong program code
5.10 Simulating the ping-pong program tutorial
5.10.1 Setting up input stimulus
5.10.2 Setting up the Watch window
5.10.3 Single stepping
5.10.4 Animate
5.10.5 Run
5.10.6 Breakpoints
5.10.7 Stopwatch
5.10.8 Trace
5.10.9 Debugging the full program
5.11 What others do graphical simulators
Summary
References

95
97
97
98
99
101
102
102
102
102
104
106
106
107
108
109
109
110
110
112
112
115
116
116
116
116
117
117
117
117
117
118
118
119
119

Working with time: interrupts, counters and timers

120

6.1

121
121
122
124
125
125
126

6.2

The main idea interrupts


6.1.1 Interrupt structures
6.1.2 The 16F84A interrupt structure
6.1.3 The CPU response to an interrupt
Working with interrupts
6.2.1 Programming with a single interrupt
6.2.2 Moving to multiple interrupts identifying the source

Contents
Stopping interrupts from wrecking your
program 1 context saving
6.2.4 Stopping interrupts from wrecking your program 2 critical
regions and masking
6.3 The main idea counters and timers
6.3.1 The digital counter reviewed
6.3.2 The counter as timer
6.3.3 The 16F84A Timer 0 module
6.4 Applying the 16F84A Timer 0, with examples using the electronic ping-pong
6.4.1 Object or event counting
6.4.2 Hardware-generated delays
6.5 The Watchdog Timer
6.6 Sleep mode
6.7 What others do
6.8 Taking things further interrupt latency
Summary

ix

6.2.3

Section 3
7

Larger Systems and the PIC 16F873A

127
130
131
131
132
134
136
136
137
138
139
140
141
142

143

Larger systems and the PIC 16F873A

145

7.1
7.2

146
146
146
147
150
150
150
152
154
155
155
156
158
158
159
161
161
161
161
161
163
164
164

7.3

7.4

7.5

7.6

7.7

The main idea the PIC 16F87XA


The 16F873A block diagram and CPU
7.2.1 Overview of CPU and core
7.2.2 Overview of memory
7.2.3 Overview of peripherals
16F873A memory and memory maps
7.3.1 The 16F873A program memory
7.3.2 The 16F873A data memory and Special Function Registers
7.3.3 The Configuration Word
Special memory operations
7.4.1 Accessing EEPROM and program memory
7.4.2 In-Circuit Serial Programming (ICSPTM )
The 16F873A interrupts
7.5.1 The interrupt structure
7.5.2 The interrupt registers
7.5.3 Interrupt identification and context saving
The 16F873A oscillator, reset and power supply
7.6.1 The clock oscillator
7.6.2 Reset and power supply
The 16F873A parallel ports
7.7.1 The 16F873A Port A
7.7.2 The 16F873A Port B
7.7.3 The 16F873A Port C

Contents
7.8

Test, commission and diagnostic tools


7.8.1 The challenge of testing an embedded system
7.8.2 Oscilloscopes and logic analysers
7.8.3 In-circuit emulators
7.8.4 On-chip debuggers
7.9 The Microchip in-circuit debugger (ICD 2)
7.10 Applying the 16F873A: the Derbot AGV
7.10.1 Power supply, oscillator and reset
7.10.2 Use of the parallel ports
7.10.3 Assembling the hardware
7.11 Downloading, testing and running a simple
program with ICD 2
7.11.1 A first Derbot program
7.11.2 Applying the ICD 2
7.11.3 Setting the configuration bits within the program
7.12 Taking things further the 16F874A/16F877A
Ports D and E
Summary
References

165
165
167
170
170
171
172
172
173
174

The human and physical interfaces

184

8.1
8.2

184
187
187
188
193
193

8.3

8.4

8.5
8.6

8.7

The main idea the human interface


From switches to keypads
8.2.1 The keypad
8.2.2 Design example: use of keypad in Derbot hand controller
LED displays
8.3.1 LED arrays: seven-segment displays
8.3.2 Design example: the Derbot hand controller
seven-segment display
Liquid crystal displays
8.4.1 The HD44780 LCD driver and its derivatives
8.4.2 Design example: use of LCD display in Derbot hand controller
The main idea interfacing to the physical world
Some simple sensors
8.6.1 The microswitch
8.6.2 Light-dependent resistors
8.6.3 Optical object sensing
8.6.4 The opto-sensor applied as a shaft encoder
8.6.5 Ultrasonic object sensor
More on digital input
8.7.1 16F873A input characteristics
8.7.2 Ensuring legal logic levels, and input protection
8.7.3 Switch debouncing

176
176
178
179
180
182
183

194
199
199
200
203
203
204
204
205
205
207
207
207
208
212

Contents

xi

8.8

Actuators: motors and servos


8.8.1 DC and stepper motors
8.8.2 Angular positioning: the servo
8.9 Interfacing to actuators
8.9.1 Simple DC switching
8.9.2 Simple switching on the Derbot
8.9.3 Reversible switching: the H-bridge
8.9.4 Motor switching on the Derbot
8.10 Building up the Derbot
8.11 Applying sensors and actuators a blind navigation Derbot program
Summary
References

212
212
214
215
215
217
218
220
220
222
223
223

Taking timing further

225

9.1
9.2

225
226
226
226
228
231
232
232
234
235
235
235
237
237
237
239
241
244
245
248
249
249
252
252
252
255
258
260
261
262

9.3

9.4

9.5

9.6

9.7
9.8

9.9
9.10
9.11
9.12
9.13

The main ideas taking counting and timing further


The 16F87XA Timer 0 and Timer 1
9.2.1 Timer 0
9.2.2 Timer 1
9.2.3 Application of Timer 0 and Timer 1 as counters for Derbot odometry
9.2.4 Using Timer 0 and Timer 1 to generate repetitive interrupts
The 16F87XA Timer 2, comparator and PR2 register
9.3.1 Timer 2
9.3.2 The PR2 register, comparator and postscaler
The capture/compare/PWM (CCP) modules
9.4.1 A capture/compare/PWM overview
9.4.2 Capture mode
9.4.3 Compare mode
Pulse width modulation
9.5.1 The principle of PWM
9.5.2 Generating PWM signals in hardware the 16F87XA PWM
9.5.3 PWM applied in the Derbot for motor control
Generating PWM in software
9.6.1 An example of software-generated PWM
9.6.2 Further Assembler directives for memory definition and branching
PWM used for digital-to-analog conversion
9.7.1 An example of PWM used for digital-to-analog conversion
Frequency measurement
9.8.1 The principle of frequency measurement
9.8.2 Frequency (speed) measurement in the Derbot
Speed control applied to the Derbot
Where there is no timer
Sleep mode
Where do we go from here?
Building up the Derbot

xii

10

Contents
Summary
References

262
262

Starting with serial

263

10.1 The main idea introducing serial


10.2 Simple serial links synchronous data communication
10.2.1 Synchronous basics
10.2.2 Implementing synchronous serial I/O in the microcontroller
10.2.3 Microwire and SPI (Serial Peripheral Interface)
10.2.4 Introducing multiple nodes
10.3 The 16F87XA Master Synchronous Serial Port (MSSP) module in SPI mode
10.3.1 Port overview
10.3.2 Port configuration
10.3.3 Setting the clock
10.3.4 Managing data transfer
10.4 A simple SPI example
10.5 The limitations of Microwire and SPI, and of simple
synchronous serial transfer
10.6 Enhancing synchronous serial, and the Inter-Integrated Circuit bus
10.6.1 Main I2 C features and physical interconnection
10.6.2 The pull-up resistor
10.6.3 I2 C signal characteristics
10.7 The MSSP configured for I2 C
10.7.1 The MSSP I2 C registers and their preliminary use
10.7.2 The MSSP in I2 C Slave mode
10.7.3 The MSSP in I2 C Master mode
10.8 I2 C applied in the Derbot AGV
10.8.1 The Derbot hand controller as a serial node
10.8.2 The AGV as an I2 C master
10.8.3 The hand controller as an I2 C slave
10.8.4 Evaluation of the Derbot I2 C programs
10.9 Evaluation of synchronous serial data communication
and an introduction to asynchronous
10.9.1 Asynchronous principles
10.9.2 Synchronising serial data without an incoming clock
10.10 The 16F87XA Addressable Universal Synchronous
Asynchronous Receiver Transmitter (USART)
10.10.1 Port overview
10.10.2 The USART asynchronous transmitter
10.10.3 The USART baud rate generator
10.10.4 The USART asynchronous receiver
10.10.5 An asynchronous example
10.10.6 Using address detection with the USART receive mode
10.10.7 The USART in synchronous mode

263
265
265
266
266
267
267
268
268
270
271
273
275
275
275
275
276
277
277
281
283
286
286
286
290
292
293
293
293
295
295
295
298
299
300
302
302

Contents

11

xiii

10.11 Implementing serial without a serial port bit banging


10.12 Building up the Derbot
Summary
References

303
303
303
303

Data acquisition and manipulation

304

11.1

The main idea analog and digital quantities, their


acquisition and use
11.2 The data acquisition system
11.2.1 The analog-to-digital converter
11.2.2 Signal conditioning amplification and filtering
11.2.3 The analog multiplexer
11.2.4 Sample and hold, and acquisition time
11.2.5 Timing and microprocessor control
11.2.6 Data acquisition in the microcontroller environment
11.3 The PIC 16F87XA ADC module
11.3.1 Overview and block diagram
11.3.2 Controlling the ADC
11.3.3 The analog input model
11.3.4 Calculating acquisition time
11.3.5 Repeated conversions
11.3.6 Trading off conversion speed and resolution
11.4 Applying the ADC in the Derbot light meter program
11.4.1 Configuration of the ADC
11.4.2 Acquisition time
11.4.3 Data conversion
11.5 Some simple data manipulation techniques
11.5.1 Fixed- and floating-point arithmetic
11.5.2 Binary to Binary Coded Decimal conversion
11.5.3 Multiplication
11.5.4 Scaling and the Derbot light meter example
11.5.5 Using the voltage reference for scaling
11.6 The Derbot light-seeking program
11.7 The comparator module
11.7.1 Review of comparator action
11.7.2 The 16F87XA comparators and voltage reference
11.8 Applying the Derbot circuit for measurement purposes
11.8.1 The electronic tape measure
11.8.2 The light meter
11.8.3 The voltmeter
11.8.4 Other measurement systems
11.9 Configuring the Derbot AGV as a light-seeking robot
Summary
References

304
305
306
308
308
309
310
311
312
312
313
317
318
319
319
319
319
320
321
321
322
323
324
324
326
326
327
327
329
329
329
331
331
331
332
332
332

xiv

Contents

Section 4
12

Smarter Systems and the PIC 18FXX2

333

Smarter systems and the PIC 18FXX2

335

12.1 The main idea the PIC 18 Series and the 18FXX2
12.2 The 18F2X2 block diagram and Status register
12.3 The 18 Series instruction set
12.3.1 Instructions which are unchanged
12.3.2 Instructions which have been upgraded
12.3.3 New, variant, instructions
12.3.4 New instructions
12.4 Data memory and Special Function Registers
12.4.1 The data memory map
12.4.2 Access RAM
12.4.3 Indirect addressing and accessing tables in data memory
12.5 Program memory
12.5.1 The program memory map
12.5.2 The Program Counter
12.5.3 Upgrading from the 16 Series and computed goto instructions
12.5.4 The Configuration registers
12.6 The Stacks
12.6.1 Automatic Stack operations
12.6.2 Programmer access to the Stack
12.6.3 The Fast Register Stack
12.7 The interrupts
12.7.1 An interrupt structure overview
12.7.2 The interrupt sources, their enabling and prioritisation
12.7.3 Overall interrupt prioritisation enabling
12.7.4 Global enabling
12.7.5 Other aspects of the interrupt logic
12.7.6 The Interrupt registers
12.7.7 Context saving with interrupts
12.8 Power supply and reset
12.8.1 Power supply
12.8.2 Power-up and Reset
12.9 The oscillator sources
12.9.1 LP, XT, HS and RC oscillator modes
12.9.2 EC, ECIO and RCIO oscillator modes
12.9.3 HS + PLL oscillator mode
12.9.4 Clock source switching
12.10 Introductory programming with the 18F242
12.10.1 Using the MPLAB IDE for the 18 Series
12.10.2 The Fibonacci program
Summary
References

336
337
340
344
344
345
345
345
345
347
347
347
349
349
349
350
352
352
352
352
353
353
353
354
354
355
355
356
358
358
358
360
362
363
363
363
364
364
365
367
367

Contents
13

14

xv

The PIC 18FXX2 peripherals

368

13.1 The main idea the 18FXX2 peripherals


13.2 The parallel ports
13.2.1 The 18FXX2 Port A
13.2.2 The 18FXX2 Port B
13.2.3 The 18FXX2 Port C
13.2.4 The parallel slave port
13.3 The timers
13.3.1 Timer 0
13.3.2 Timer 1
13.3.3 Timer 2
13.3.4 Timer 3
13.3.5 The Watchdog Timer
13.4 The capture/compare/PWM (CCP) modules
13.4.1 The control registers
13.4.2 Capture mode
13.4.3 Compare mode
13.4.4 Pulse width modulation
13.5 The serial ports
13.5.1 The MSSP in SPI mode
13.5.2 The MSSP in I2 C mode
13.5.3 The USART
13.6 The analog-to-digital converter (ADC)
13.7 Low-voltage detect
13.8 Applying the 18 Series in the Derbot-18
13.9 The 18F2420 and the extended instruction set
13.9.1 Nanowatt technology
13.9.2 The extended instruction set
13.9.3 Enhanced peripherals
Summary
Reference

368
369
369
369
371
371
371
371
373
373
373
376
376
376
376
377
378
378
379
379
380
380
380
382
383
383
384
384
385
385

Introducing C

386

14.1 The main idea why C?


14.2 An introduction to C
14.2.1 A little history
14.2.2 A first program
14.2.3 Laying out the program declarations, statements, comments and space
14.2.4 C keywords
14.2.5 The C function
14.2.6 Data type and storage
14.2.7 C operators
14.2.8 Control of program flow, and the while keyword

387
387
387
388
388
390
391
392
392
393

xvi

15

Contents
14.2.9 The C preprocessor and its directives
14.2.10 Use of libraries, and the Standard Library
14.3 Compiling the C program
14.4 The MPLAB C18 compiler
14.4.1 Specification of radix
14.4.2 Arithmetic operations
14.5 A C18 tutorial
14.5.1 The Linker and Linker Scripts
14.5.2 Linking header and library files
14.5.3 Building the project
14.5.4 Project files
14.6 Simulating a C program
14.7 A second C example the Fibonacci program
14.7.1 Program preliminaries more on declaring variables
14.7.2 The dowhile construct
14.7.3 Labels and the goto keyword
14.7.4 Simulating the Fibonacci program
14.8 The MPLAB C18 libraries
14.8.1 Hardware peripheral functions
14.8.2 The software peripheral library
14.8.3 The general software library
14.8.4 The maths library
14.9 Further reading
Summary
References

394
394
394
395
396
396
396
396
397
397
398
400
401
402
403
403
403
403
404
404
405
406
406
407
407

C and the embedded environment

409

15.1 The main idea adapting C to the embedded environment


15.2 Controlling and branching on bit values
15.2.1 Controlling individual bits
15.2.2 The if and ifelse conditional branch structures
15.2.3 Setting the configuration bits
15.2.4 Simulating and running the example program
15.3 More on functions
15.3.1 The function prototype
15.3.2 The function definition
15.3.3 Function calls and data passing
15.3.4 Library delay functions, and Delay10KTCYx( )
15.4 More branching and looping
15.4.1 Using the break keyword
15.4.2 Using the for keyword
15.5 Using the timer and PWM peripherals
15.5.1 Using the timer peripherals

409
409
411
411
412
412
413
413
414
414
415
415
415
416
417
420

Contents

16

17

xvii

15.5.2 Using PWM


15.5.3 The main program loop
Summary

421
421
422

Acquiring and using data with C

423

16.1 The main idea using C for data manipulation


16.2 Using the 18FXX2 ADC
16.2.1 The light-seeking program structure
16.2.2 Use of the ADC
16.2.3 Further use of ifelse
16.2.4 Simulating the light-seeking program
16.3 Pointers, arrays and strings
16.3.1 Pointers
16.3.2 Arrays
16.3.3 Using pointers with arrays
16.3.4 Strings
16.3.5 An example program: using pointers, arrays and strings
16.3.6 A word on evaluating the while condition
16.3.7 Simulating the program example
16.4 Using the I2 C peripheral
16.4.1 An example I2 C program
16.4.2 Use of ++ and operators
16.5 Formatting data for display
16.5.1 Overview of example program
16.5.2 Using library functions for data formatting
16.5.3 Program evaluation
Summary

423
423
427
428
429
429
431
431
432
432
433
433
434
435
437
437
439
440
440
442
442
443

More C and the wider C environment

444

17.1 The main idea more C and the wider C environment


17.2 Assembler inserts
17.3 Controlling memory allocation
17.3.1 Memory allocation pragmas
17.3.2 Setting the Configuration Words
17.4 Interrupts
17.4.1 The Interrupt Service Routine
17.4.2 Locating and identifying the ISR
17.5 Example with interrupt on overflow flashing LEDs
on the Derbot
17.5.1 Using Timer 0
17.5.2 Using interrupts, and the ISR action
17.5.3 Simulating the flashing LEDs program
17.6 Storage classes and their application
17.6.1 Storage classes

444
445
446
447
447
448
448
449
449
450
451
452
453
453

xviii

18

Contents
17.6.2 Scope
17.6.3 Duration
17.6.4 Linkage
17.6.5 Working with 18 Series memory
17.6.6 Storage class examples
17.7 Start-up code: c018i.c
17.7.1 The C18 start-up files
17.7.2 The c018i.c structure
17.7.3 Simulating c018i.c
17.8 Structures, unions and bit-fields
17.9 Processor-specific header files
17.9.1 SFR definitions
17.9.2 Assembler utilities in the header file
17.10 Taking things further the MPLAB Linker and the .map file
17.10.1 What the Linker does
17.10.2 The Linker Script
17.10.3 The .map file
Summary
References

454
454
455
455
455
456
456
457
457
459
460
460
461
462
462
462
464
465
465

Multi-tasking and the Real Time Operating System

466

18.1 The main ideas the challenge of multi-tasking


and real time
18.1.1 Multi-tasking tasks, priorities and deadlines
18.1.2 So what is real time?
18.2 Achieving multi-tasking with sequential programming
18.2.1 Evaluating the super loop
18.2.2 Time-triggered and event-triggered tasks
18.2.3 Using interrupts for prioritisation the foreground/background structure
18.2.4 Introducing a clock tick to synchronise program activity
18.2.5 A general-purpose operating system
18.2.6 The limits of sequential programming when multi-tasking
18.3 The Real Time Operating System (RTOS)
18.4 Scheduling and the scheduler
18.4.1 Cyclic scheduling
18.4.2 Round robin scheduling and context switching
18.4.3 Task states
18.4.4 Prioritised pre-emptive scheduling
18.4.5 Cooperative scheduling
18.4.6 The role of interrupts in scheduling
18.5 Developing tasks
18.5.1 Defining tasks
18.5.2 Writing tasks and setting priority

466
467
468
469
469
469
469
470
471
471
472
473
473
473
474
475
476
477
477
477
478

Contents

19

xix

18.6 Data and resource protection the semaphore


18.7 Where do we go from here?
Summary
References

478
479
479
479

The SalvoTM Real Time Operating System

480

19.1 The main idea Salvo, an example RTOS


19.1.1 Basic Salvo features
19.1.2 Salvo versions and references
19.2 Configuring the Salvo application
19.2.1 Building Salvo applications the library build
19.2.2 Salvo libraries
19.2.3 Using Salvo with C18
19.3 Writing Salvo programs
19.3.1 Initialisation and scheduling
19.3.2 Writing Salvo tasks
19.4 A first Salvo example
19.4.1 Program overview and the main function
19.4.2 Tasks and scheduling
19.4.3 Creating a Salvo/C18 project
19.4.4 Setting the configuration file
19.4.5 Building the Salvo example
19.4.6 Simulating the Salvo program
19.5 Using interrupts, delays and semaphores with Salvo
19.5.1 An example program using an interrupt-based clock tick
19.5.2 Selecting the library and configuration
19.5.3 Using interrupts and establishing the clock tick
19.5.4 Using delays
19.5.5 Using a binary semaphore
19.5.6 Simulating the program
19.5.7 Running the program
19.6 Using Salvo messages and increasing RTOS complexity
19.7 A program example with messages
19.7.1 Selecting the library and configuration
19.7.2 The task: USnd_ Task
19.7.3 The task: Motor_ Task
19.7.4 The use of messages
19.7.5 The use of interrupts, and the ISRs
19.7.6 Simulating or running the program
19.8 The RTOS overhead
Summary
References

480
480
481
482
482
482
483
483
484
485
485
487
488
488
489
489
490
491
492
494
494
496
496
497
499
499
500
505
505
505
506
507
509
509
510
510

xx

Contents

Section 5 Techniques of Connectivity and Networking

511

20

Connectivity and networks

513

20.1 The main idea networking and connectivity


20.1.1 A word on protocols
20.2 Infrared connectivity
20.2.1 The IrDA and the PIC microcontroller
20.3 Radio connectivity
20.3.1 Bluetooth
20.3.2 Zigbee
20.3.3 Zigbee and the PIC microcontroller
20.4 Controller Area Network (CAN) and Local Interconnect Network (LIN)
20.4.1 Controller Area Network (CAN)
20.4.2 CAN and the PIC microcontroller
20.4.3 Local Interconnect Network (LIN)
20.4.4 LIN and the PIC microcontroller
20.5 Embedded systems and the Internet
20.5.1 Connecting to the Internet with the PIC microcontroller
20.6 Conclusion
Summary
References

513
514
515
515
516
516
517
517
518
518
520
520
521
522
523
523
524
524

Appendix 1
Appendix 2
Appendix 3
Appendix 4
Appendix 5
Appendix 6
Index

The PIC 16 Series instruction set


The electronic ping-pong
The Derbot AGV hardware design details
Some basics of Autonomous Guided Vehicles
PIC 18 Series instruction set (non-extended)
Essentials of C

527
528
533
537
541
544
549

Contents

List of Figures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

VI

List of Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

XI

List of Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . XIV


Part I

The Fundamentals

1.

Digital Representation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2.

Logic Circuitry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

17

3.

Stored Program Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

41

Part II

The Software

4.

The PIC16F84 Microcontroller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77

5.

The Instruction Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105

6.

Subroutines and Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137

7.

Interrupt Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171

8.

Assembly language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197

9.

High-Level Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231

Part III

The Outside World

10. The Real World . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253


11. One Byte at a Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271

VI

Contents

12. One Bit at a Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305


13. Time is of the Essence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361
14. Take the Rough with the Smooth . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391
15. To Have and to Hold . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431
16. A Case Study . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455
Appendices
A.

14-bit Core Instruction Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 475

B.

Special Purpose Register Structure for the PIC16C74B . . . . . . . . . 477

C.

C Instruction Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 479

D.

Acronyms and Abbreviations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481

Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 485

Indice
Cap tulo 1
Arquitectura de un PIC
Introducci n ......................................................5
Caracter sticas del PIC .....................................5
Caracter sticas Perif ricas................................5
Caracter sticas Especiales del
Microcontrolador ...............................................6
Patas del PIC....................................................6
Resumen del Dispositivo ..................................9
Ficha Did ctica ...............................................10
Lo que Debe Saber
Sobre los PICs................................................13
a) El Procesador es segmentado
tipo "pipe line" .................................................13
b) El Procesador es de tipo RISC ..................14
c) Poseen una arquitectura
tipo Harvard ....................................................14
d) Son de arquitectura ortogonal basada
en banco de registros .....................................15
Palabras de Configuraci n
e Identificaci n................................................18
Organizaci n de la Memoria...........................19
Organizaci n de la Memoria
de Programas .................................................19
Organizaci n de la Memoria
de Datos..........................................................19
Los Registros del PIC.....................................20
Archivo de Registro de
Uso General....................................................20
Registros de Funciones
Especiales (SFR)............................................21
Registro de Status ..........................................23
Registro OPTION_REG..................................25

El Registro INTCON .......................................27


PCL y PCLATH ...............................................28
STACK (PILA) .................................................28
Registros INDF y FSR ....................................29
PORTS I/O......................................................30
Registros PORTA y TRISA .............................30
Registros PORTB y TRISB.............................32
M dulo Temporizador TIMER0 .......................34
Prescaler (Divisor de Frecuencia) ..................35
Interrupci n de Timer0....................................36
Memoria de Datos EEPROM..........................36
Lectura de la Memoria de
Datos de EEPROM.........................................38
Escritura de la Memoria de
Datos EEPROM..............................................39
Verificaci n de Escritura .................................40
La CPU del PIC ..............................................42
Bits de Configuraci n......................................43
Configuraciones del Oscilador........................43
Oscilador de Cristal o
Resonador de Cer mica.................................44
Oscilador RC...................................................44
Reset...............................................................44
Reset de Encendido .......................................47
Temporizador de Arranque del
Oscilador (OST)..............................................48
Temporizador de Encendido
(PWRT) ...........................................................48
El Perro Guardi n (WDT) ...............................48
Interrupciones del Micro .................................49
Interrupci n Externa (INT) ..............................51
Interrupci n por Desborde
del TMR0 ........................................................51
Interrupci n por Cambio de
Estado en las patas RB7 y RB4 .....................51
Interrupci n por Finalizaci n de la Escritura
en la EEPROM de datos ................................51

Microcontroladores PIC

Indice

Cap tulo 2
Manejo de las Instrucciones
de un PIC
Introducci n ....................................................53
Instrucci n: SUMA ..........................................54
C digo de la instrucci n ADDWf ....................55
El Set de Instrucciones
del 16X84........................................................56
ADDLW...................................................59
ADDWF ..................................................60
ANDLW...................................................61
ANDWF ..................................................62
BCF ........................................................63
BSF ........................................................64
BTFSC ...................................................65
BTFSS....................................................67
CALL ......................................................68
CLRF......................................................69
CLRW.....................................................70
CLRWDT ................................................71
COMF.....................................................72
DECF .....................................................73
DECFSZ.................................................74
GOTO.....................................................75
INCF.......................................................76
INCFSZ ..................................................77
IORLW....................................................78
IORWF ...................................................79
MOVLW ..................................................80

MOVF.....................................................81
MOVWF .................................................82
NOP .......................................................83
RETFIE ..................................................83
RETLW ...................................................84
RETURN ................................................85
RLF ........................................................85
RRF........................................................86
SLEEP....................................................87
SUBLW...................................................88
SUBWF ..................................................90
SWAPF...................................................92
XORLW ..................................................93
XORWF ..................................................94
Palabras de Configuraci n
e Identificaci n...............................................96

Cap tulo 3
Aprendiendo a Programar
Circuito de un Entrenador...............................97
Encendido Intermitente
de un Led......................................................100
Secuenciador de 4 Canales .........................108
Generador de Se ales de Audio...................112
Los Formatos de los Archivos.......................115
Secuenciador de 8 Canales..........................115
Compilaci n de un Programa .......................118
Carga del Programa en un PIC ....................121

Dedico este libro a todos los que trabajan por una Argentina mejor, a los que creen que
es posible cambiar las cosas desde el trabajo y el esfuerzo colectivo, a los que creen
que las respuestas est n en casa... en esta hermosa y bendita Am rica Latina.
Dedico este libro a quienes saben construir en paz...
Dedico este libro a quienes integran Editorial Quark, Imprenta Rosgal y Centro Japon s
de Informaci n Electr nica.
Horacio Daniel Vallejo

Microcontroladores PIC

Contents

Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .xi
Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xv
About the Author . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii
Whats on the CD-ROM? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .xix
Chapter 1: What Are Intelligent Sensors, and
Why Should I Care about Them? . . . . . . . . . . . . . . . . . . . . . . 1
1.1 Conventional Sensors Arent Perfect . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 First Things FirstDigitizing the Sensor Signal. . . . . . . . . . . . . . . . . . 7
1.3 Next StepAdd Some Intelligence . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.4 Finish Up with Quick and Reliable Communications . . . . . . . . . . . . 8
1.5 Put It All Together, and Youve Got an Intelligent Sensor . . . . . . . . . . 9
1.6 Why Dont We Make Everything Intelligent? . . . . . . . . . . . . . . . . . . 11
1.7 Real-world Examples of Intelligent Sensors . . . . . . . . . . . . . . . . . . . 13
1.8 Outline of the Remainder of the Book . . . . . . . . . . . . . . . . . . . . . . 16
Chapter 2: Intuitive Digital Signal Processing . . . . . . . . . . . . . 21
2.1 Foundational Concepts for Signal Processing . . . . . . . . . . . . . . . . . . 21
2.2 Issues Related to Signal Sampling . . . . . . . . . . . . . . . . . . . . . . . . . . 44
2.3 How to Analyze a Sensor Signal Application . . . . . . . . . . . . . . . . . . 47
2.4 A General Sensor Signal-processing Framework . . . . . . . . . . . . . . . . 48
2.5 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
Chapter 3: Underneath the Hood of the dsPIC DSC. . . . . . . . . 53
3.1 The dsPIC DSCs Data Processing Architecture . . . . . . . . . . . . . . . . 55
3.2 Interrupt Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
vii

viii Contents

3.3 The On-chip Peripherals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71


3.4 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
Chapter 4: Learning to be a Good Communicator . . . . . . . . . . 99
4.1 Types of Communications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
4.2 Communication Options Available on the dsPIC30F . . . . . . . . . . 106
4.3 High-level Protocols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
4.4 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
Chapter 5: A Basic Toolkit for the dsPIC DSC . . . . . . . . . . . . . 137
5.1 The Application Test Bed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
5.2 Overview of the Firmware Framework . . . . . . . . . . . . . . . . . . . . . 138
5.3 Implementation of the Framework Modules . . . . . . . . . . . . . . . . . 149
5.4 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
Chapter 6: Sensor ApplicationTemperature Sensor . . . . . . 161
6.1 Types of Temperature Sensors . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
6.2 Key Aspects of Temperature Measurement . . . . . . . . . . . . . . . . . . . 167
6.3 Application Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
6.4 Hardware Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
6.5 Firmware Implementation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
6.6 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
Chapter 7: Sensor ApplicationPressure and Load Sensors . . 209
7.1 Types of Load and Pressure Sensors . . . . . . . . . . . . . . . . . . . . . . . . . . 209
7.2 Key Aspects of Load Measurement . . . . . . . . . . . . . . . . . . . . . . . . 212
7.3 Application Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216
7.4 Firmware Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
7.5 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
Chapter 8: Sensor ApplicationFlow Sensors . . . . . . . . . . . . 229
8.1 Types of Flow Sensors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
8.2 Key Aspects of Flow Measurement . . . . . . . . . . . . . . . . . . . . . . . . 232
8.3 Application Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
8.4 Hardware Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
8.5 Firmware Implementation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245
8.6 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250

Contents

ix

Chapter 9: Where Are We Headed? . . . . . . . . . . . . . . . . . . . . 253


9.1 Technology Trends . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
9.2 Economic Trends . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260
9.3 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
Appendix A: Software on the Included CD-ROM . . . . . . . . . . 265
A.1 On-disk Website of Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265
A.2 Source Code for the Three Applications . . . . . . . . . . . . . . . . . . . . . . . 266
Appendix B: Initialization of the dsPIC DSC
and the System Start-up Code . . . . . . . . . . . . . . . . . . . . . 267
Appendix C: Buffered, Interrupt-driven Serial I/O . . . . . . . . . 271
C.1 Pseudo-code for the Framework . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273
C.2 System Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273
C.3 Reading Data From the Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . 273
C.4 Writing Data to the Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275

Contents
Introduction
History
Why use C?
PC based versus PICmicroMCU Based Program Development
Product Development
Terminology
Trying and Testing Code
C Coding Standards
Basics

1 C Fundamentals
Structure of C Programs
Components of a C Program
#pragma
main()
#include
printf Function
Variables
Constants
Comments
Functions
C Keywords

2 Variables
Data Types
Variable Declaration
Variable Assignment
Enumeration
typedef
Type Conversions

3 Functions
Functions
Function Prototypes
Using Function Arguments
Using Function to Return Values
Classic and Modern Function Declarations

4 Operators
Arithmetic
Relational
Logical
Bitwise
4

Increment and Decrement


Precedence of

5 Program Control Statements


If
If-else
?
for Loop
while Loop
do-while Loop
Nesting Program Control Statements
Break
Continue
Null
Return

6 Arrays / Strings
One Dimensional Arrays
Strings
Multidimensional Arrays
Initializing Arrays
Arrays of Strings

7 Pointers
Pointer Basics
Pointers and Arrays
Passing Pointer to Functions

8 Structures / Unions
Structure Basics
Pointers to Structures
Nested Structures
Union Basics
Pointers to Unions

9 PICmicroMCU Specific C
Inputs and Outputs
Mixing C and Assembler
Advanced BIT Manipulation
Timers
A/D Conversion
Data Communications
I2C Communications
SPI Communications
PWM
LCD Driving
5

Interrupts
Include Libraries
Additional Information

Table of Contents
1. Introduction

1.1 Typographical Conventions....................................................................... 1


1.2 Explaining the Microcontroller ................................................................. 2
1.3 Book Contents ........................................................................................... 3

2. Microcontroller Overview

2.1 What is a Microcontroller?......................................................................... 5


2.2 The Microcontroller in a System............................................................... 7
2.3 Architecture ............................................................................................... 7
2.3.1 Von Neumann ......................................................................................................................8
2.3.2 Von Neumann Memory Map.............................................................................................8
2.3.3 Harvard ..................................................................................................................................9
2.3.4 Harvard Memory Map.......................................................................................................10
2.3.5 The Central Processing Unit ............................................................................................11
2.3.6 Central Processing Unit.....................................................................................................13
2.3.7 ROM.....................................................................................................................................14
2.3.8 RAM .....................................................................................................................................15
2.3.9 I/O Ports.............................................................................................................................16
2.3.10 Timer..................................................................................................................................17
2.3.11 Interrupt Circuitry............................................................................................................18
2.3.12 Buses ..................................................................................................................................19

2.4 Sample Microcontroller Configurations.................................................. 19


2.4.1 Motorola MC68HC705C8 ................................................................................................19
2.4.2 National Semiconductor COP8SAA7 ............................................................................20
2.4.3 Microchip PIC16C54.........................................................................................................20
2.4.4 Microchip PIC16C74.........................................................................................................21

Table of Contents

3. The Embedded Environment

23

3.1 The Embedded Difference ......................................................................23


3.2 Fabrication Techniques ..........................................................................24
3.3 Memory Addressing and Types ..............................................................24
3.3.1 RAM..................................................................................................................................... 24
3.3.2 ROM .................................................................................................................................... 25
3.3.3 PROM ................................................................................................................................. 25
3.3.4 EPROM .............................................................................................................................. 25
3.3.5 EEPROM ........................................................................................................................... 26
3.3.6 Flash Memory..................................................................................................................... 27
3.3.7 Registers .............................................................................................................................. 27
3.3.8 Scratch Pad ......................................................................................................................... 28

3.4 Interrupts .................................................................................................29


3.4.1 Interrupt Handling ............................................................................................................ 30
3.4.2 Synchronous and Asynchronous Interrupt Acknowledgement................................. 30
3.4.3 Servicing Interrupts ........................................................................................................... 31
3.4.4 Interrupt Detection ........................................................................................................... 32
3.4.5 Executing Interrupt Handlers.......................................................................................... 33
3.4.6 Multiple Interrupts ............................................................................................................ 34

3.5 Specific Interrupts ...................................................................................34


3.5.1 RESET ................................................................................................................................ 35
3.5.2 Software Interrupt/Trap .................................................................................................. 35
3.5.3 IRQ ...................................................................................................................................... 36
3.5.4 TIMER ................................................................................................................................ 36

3.6 Power .......................................................................................................37


3.6.1 Brownout ............................................................................................................................ 37
3.6.2 Halt/Idle ............................................................................................................................. 37

3.7 Input and Output.....................................................................................37


3.7.1 Ports..................................................................................................................................... 37
3.7.2 Serial Input and Output.................................................................................................... 38

3.8 Analog to Digital Conversion ..................................................................40


3.9 Miscellaneous .......................................................................................... 41
3.9.1 Digital Signal Processor .................................................................................................... 41
3.9.2 Clock Monitor .................................................................................................................... 41
ii

Table of Contents

3.10 Devices................................................................................................... 41
3.10.1 Mask ROM........................................................................................................................41
3.10.2 Windowed Parts ...............................................................................................................41
3.10.3 OTP....................................................................................................................................41

4. Programming Fundamentals

43

4.1 What is a Program?.................................................................................. 43


4.2 Number Systems ..................................................................................... 43
4.3 Binary Information.................................................................................. 44
4.4 Memory Addressing ................................................................................ 46
4.5 Machine Language.................................................................................. 46
4.6 Assembly Language ................................................................................ 46
4.6.1 Assembler ............................................................................................................................47

4.7 Instruction Sets........................................................................................ 47


4.8 The Development of Programming Languages ..................................... 48
4.9 Compilers ................................................................................................ 50
4.9.1 The Preprocessor ...............................................................................................................50
4.9.2 The Compiler ......................................................................................................................50
4.9.3 The Linker ...........................................................................................................................50

4.10 Cross Development................................................................................ 51


4.10.1 Cross compiler..................................................................................................................51
4.10.2 Cross development tools ................................................................................................51
4.10.3 Embedded Development Cycle.....................................................................................52

5. First Look at a C Program

55

5.1 Program Comments................................................................................. 56


5.2 Preprocessor directives............................................................................ 56
5.3 C Functions ............................................................................................. 58
5.3.1 The main( ) function..........................................................................................................58
5.3.2 Calling a Function ..............................................................................................................59

iii

Table of Contents

5.4 The Function Body..................................................................................60


5.4.1 The Assignment Statement .............................................................................................. 60
5.4.2 Control statements ............................................................................................................ 60
5.4.3 Calling Functions ............................................................................................................... 62

5.5 The Embedded Difference......................................................................62


5.5.1 Device Knowledge ............................................................................................................ 63
5.5.2 Special Data Types and Data Access.............................................................................. 63
5.5.3 Program Flow..................................................................................................................... 63
5.5.4 Combining C and Assembly Language .......................................................................... 63
5.5.5 Mechanical Knowledge..................................................................................................... 64

6. C Program Structure

65

6.1 C Preprocessor Directives........................................................................65


6.2 Identifier Declaration ..............................................................................65
6.2.1 Identifiers in Memory ....................................................................................................... 66
6.2.2 Identifier names ................................................................................................................. 66
6.2.3 Variable Data Identifiers................................................................................................... 67
6.2.4 Constant Data Identifiers ................................................................................................. 67
6.2.5 Function Identifiers........................................................................................................... 68

6.3 Statements ...............................................................................................68


6.3.1 The Semicolon Statement Terminator ........................................................................... 69
6.3.2 Combining Statements in a Block................................................................................... 69

7. Basic Data Types

71

7.1 The ASCII Character Set ......................................................................... 71


7.2 Data types ................................................................................................ 71
7.3 Variable Data Types ................................................................................72
7.3.1 Variable Data Type Memory Allocation ........................................................................ 72
7.3.2 Variable Scope.................................................................................................................... 73
7.3.3 Global Scope ...................................................................................................................... 74
7.3.4 Local Scope......................................................................................................................... 74
7.3.5 Declaring Two Variables with the Same Name............................................................ 74
7.3.6 Why Scope is Important................................................................................................... 75

7.4 Function Data Types...............................................................................75


7.4.1 Function Parameter data types ........................................................................................ 76
iv

Table of Contents

7.5 The Character Data Type........................................................................ 76


7.5.1 Assigning a character value...............................................................................................76
7.5.2 ASCII Character Arrangement ........................................................................................77
7.5.3 Numeric Characters ...........................................................................................................77
7.5.4 Escape Sequences...............................................................................................................77

7.6 Integer Data Types.................................................................................. 78


7.6.1 Integer Sign Bit...................................................................................................................78
7.6.2 The short Data Type .........................................................................................................78
7.6.3 The long Data type ............................................................................................................79
7.6.4 Different Notations ...........................................................................................................79

7.7 Data Type Modifiers ............................................................................... 79


7.7.1 Signed and Unsigned .........................................................................................................80
7.7.2 Other Data Type Modifiers..............................................................................................80

7.8 Real Numbers ......................................................................................... 80


7.8.1 The float Data Type...........................................................................................................81
7.8.2 The double and long double Types.................................................................................81
7.8.3 Assigning an Integer to a float .........................................................................................81

8. Operators and Expressions

83

8.1 Operators ................................................................................................. 83


8.2 C Expressions.......................................................................................... 84
8.2.1 Binding.................................................................................................................................85
8.2.2 Unary Operators.................................................................................................................85
8.2.3 Binary Operators ................................................................................................................85
8.2.4 Trinary Operator ................................................................................................................86
8.2.5 Operator Precedence .........................................................................................................86
8.2.6 The = Operator ..................................................................................................................87

8.3 Arithmetic Operators............................................................................... 88


8.3.1 Increment and Decrement Operators ............................................................................89

8.4 Assignment Operators............................................................................. 90


8.5 Comparison Operators ............................................................................ 91
8.5.1 Expressing True and False................................................................................................91
8.5.2 The Equality Operators.....................................................................................................92
8.5.3 Relational Operators..........................................................................................................92
8.5.4 Logical Operators...............................................................................................................93
v

Table of Contents

8.6 Bit Level Operators..................................................................................95


8.6.1 Bit Logical Operators........................................................................................................ 95
8.6.2 Bit shift operators .............................................................................................................. 97

9. Control Structures

99

9.1 Conditional Expressions..........................................................................99


9.2 Decision Structures................................................................................ 100
9.2.1 if and else Statements...................................................................................................... 100
9.2.2 Nested if statements........................................................................................................ 101
9.2.3 Matching else and if......................................................................................................... 102
9.2.4 switch and case................................................................................................................. 103
9.2.5 Execution within a switch .............................................................................................. 103
9.2.6 Fall-through execution.................................................................................................... 104
9.2.7 The default case ............................................................................................................... 105
9.2.8 The goto Statement ......................................................................................................... 105
9.2.9 Comparing goto and switch..case.................................................................................. 106

9.3 Looping Structures ................................................................................ 106


9.3.1 Control expression .......................................................................................................... 106
9.3.2 The while loop.................................................................................................................. 107
9.3.3 The do loop ...................................................................................................................... 107
9.3.4 The for loop...................................................................................................................... 108
9.3.5 How the for loop works ................................................................................................. 108

9.4 Exiting a Loop....................................................................................... 109


9.4.1 The break Statement ....................................................................................................... 109
9.4.2 The continue Statement.................................................................................................. 109

10. Functions

111

10.1 main() ....................................................................................................111


10.2 Executing a Function ...........................................................................111
10.2.1 Calling a Function.......................................................................................................... 112

10.3 Function Prototype Declarations..........................................................113


10.3.1 Defining the Function Interface ................................................................................. 113
10.3.2 Calling Functions in Other Files ................................................................................. 113
10.3.3 Function Type, Name and Parameter List ................................................................ 114
10.3.4 Functions and void........................................................................................................ 115
vi

Table of Contents

10.4 Function Definitions.............................................................................116


10.4.1 Statement Block..............................................................................................................116
10.4.2 Variable Declarations in Function Definitions .........................................................116

10.5 Function Parameters.............................................................................117


10.5.1 Passing Data by Value ...................................................................................................117
10.5.2 Passing Data by Reference ...........................................................................................117
10.5.3 Functions Without Parameters ....................................................................................118

11. Complex Data Types

121

11.1 Pointers..................................................................................................121
11.1.1 Declaring a Pointer ........................................................................................................121
11.1.2 Pointer Operators ..........................................................................................................122
11.1.3 Pointer Pitfalls ................................................................................................................123

11.2 Arrays ....................................................................................................124


11.2.1 Accessing Array Elements ............................................................................................124
11.2.2 Multidimensional Arrays...............................................................................................125
11.2.3 Array Operations and Pointer Arithmetic .................................................................125
11.2.4 Arrays of Pointers ..........................................................................................................126

11.3 User Defined Data Types .....................................................................127


11.3.1 Using typedef to Define New Data Types.................................................................127
11.3.2 Using types defined with typedef ................................................................................128

11.4 Enumerated Types................................................................................128


11.4.1 Enumerated Type Elements.........................................................................................129
11.4.2 Enumerated Type Value Checks .................................................................................129
11.4.3 Specifying Values for Enumerated Elements............................................................130

11.5 Structures ..............................................................................................131


11.5.1 The structure tag ............................................................................................................131
11.5.2 Using typedef to Define a Structure ...........................................................................132
11.5.3 Accessing Structure Members......................................................................................132
11.5.4 Indicating a Field with the Dot Operator ..................................................................132
11.5.5 Indicating a Field with the Structure Pointer ............................................................133
11.5.6 Bit Fields in Structures ..................................................................................................133
11.5.7 Storing bit fields in memory.........................................................................................134
11.5.8 The behaviour of bit fields ...........................................................................................134

11.6 Unions ...................................................................................................135


11.6.1 Retrieving a Union Element.........................................................................................136
vii

Table of Contents

11.6.2 Using Unions with Incompatible Variables .............................................................. 137

12. Storage and Data Type Modifiers

139

12.1 Storage Class Modifiers........................................................................ 139


12.1.1 External linkage.............................................................................................................. 139
12.1.2 Internal linkage............................................................................................................... 139
12.1.3 No linkage....................................................................................................................... 140
12.1.4 The extern Modifier ...................................................................................................... 140
12.1.5 Global Variables and extern......................................................................................... 141
12.1.6 The static Modifier ........................................................................................................ 142
12.1.7 The visibility of static variables ................................................................................... 142
12.1.8 The register Modifier .................................................................................................... 143
12.1.9 The auto Modifier.......................................................................................................... 144

12.2 Data Type Modifiers ............................................................................ 145


12.2.1 Value Constancy Modifiers: const and volatile......................................................... 145
12.2.2 Allowable Values Modifiers: signed and unsigned................................................... 146
12.2.3 Size Modifiers: short and long..................................................................................... 146
12.2.4 Pointer Size Modifiers: near and far ........................................................................... 147
12.2.5 Using near and far pointers.......................................................................................... 148
12.2.6 Default pointer type ...................................................................................................... 148

13. The C Preprocessor

151

13.1 Preprocessor Directive Syntax ..............................................................151


13.2 White Space in the Preprocessor ......................................................... 152
13.3 File Inclusion ....................................................................................... 152
13.3.1 File Inclusion Searches .................................................................................................153

13.4 Defining Symbolic Constants .............................................................. 153


13.4.1 The #undef directive ....................................................................................................154
13.4.2 Defining empty symbols .......................................................................................... 155

13.5 Defining Macros .................................................................................. 155


13.5.1 Macro Expansion........................................................................................................... 156
13.5.2 # and ## Operators ..................................................................................................... 157

13.6 Conditional Source Code ..................................................................... 157


13.6.1 #if and #endif................................................................................................................ 157
13.6.2 The defined( ) Function................................................................................................ 158
viii

Table of Contents

13.6.3 The #else and #elif Directives ....................................................................................158


13.6.4 #ifdef and #ifndef .........................................................................................................159

13.7 Producing Error messages ...................................................................159


13.8 Defining Target Hardware ...................................................................160
13.9 In-line Assembly Language..................................................................160
13.9.1 The #asm and #endasm Directives............................................................................160

14. Libraries

161

14.1 Portable Device Driver Libraries ..........................................................161


14.2 An Example Development Scenario.....................................................162
14.2.1 How SPI Works .............................................................................................................163
14.2.2 SPI_set_master(ARGUMENT);.................................................................................164
14.2.3 SPI_send_rec(0,4); .........................................................................................................166

14.3 Device Driver Library Summary...........................................................168

15. Sample Project

169

15.1 Project Specifics ....................................................................................169


15.2 Project Foundations..............................................................................169
15.2.1 Asynchronous.................................................................................................................169
15.2.2 SCI ....................................................................................................................................170
15.2.3 RS-232..............................................................................................................................170

15.3 Electrical Specifications .......................................................................171


15.4 PIC Implementation.............................................................................171
15.4.1 Anatomy of a PC serial port.........................................................................................171
15.4.2 A Note On Chip Sets ....................................................................................................172
15.4.3 IRQ...................................................................................................................................172

15.5 Programming Interrupts.......................................................................177


15.6 The Sample Project Code .....................................................................179
15.6.1 PIC16C74 Code..............................................................................................................179
15.6.2 PC Code...........................................................................................................................180

ix

Table of Contents

16. C Precedence Rules

185

17. ASCII Chart

187

18. Glossary

189

19. Bibliography

197

20. Index

198

Contents
Preface................................................................................................................. xv
Introduction ...................................................................................................... xvii
Who should read this book? ...................................................................................................xvii
Structure of the book .............................................................................................................xviii
What this book is not ............................................................................................................... xix
Checklists ................................................................................................................................ xix

PART I
CHAPTER 1: THE FIRST FLIGHT................................................................................... 3
Flight plan ............................................................................................................. 3
Preight checklist ................................................................................................. 4
The ight............................................................................................................... 4
Compiling and linking ................................................................................................................ 6
Building the rst project ............................................................................................................. 7
PORT initialization ..................................................................................................................... 9
Retesting PORTA...................................................................................................................... 10
Testing PORTB ......................................................................................................................... 10

Post-ight brieng ............................................................................................. 12


Notes for assembly experts ............................................................................... 13
Notes for PIC MCU experts ................................................................................ 14
Notes for C experts ............................................................................................ 14
Tips and tricks ..................................................................................................... 14
Exercises .............................................................................................................. 15
Books ................................................................................................................. 15
Links ................................................................................................................. 15
CHAPTER 2: A LOOP IN THE PATTERN ..................................................................... 17
Flight plan ........................................................................................................... 17
Preight checklist ............................................................................................... 17
The ight............................................................................................................. 18
An animated simulation ............................................................................................................ 21
Using the Logic Analyzer ........................................................................................................ 24

Post-ight brieng ............................................................................................. 26


Notes for assembly experts ............................................................................... 27
vii

Contents
Notes for PIC microcontroller experts............................................................... 27
Notes for C experts ............................................................................................ 27
Tips and tricks ..................................................................................................... 27
Exercises .............................................................................................................. 28
Books ................................................................................................................. 28
Links ................................................................................................................. 28
CHAPTER 3: MORE PATTERN WORK, MORE LOOPS ............................................... 29
Flight plan ........................................................................................................... 29
Preight checklist ............................................................................................... 30
The ight............................................................................................................. 30
Do Loops .................................................................................................................................. 30
Variable declarations ................................................................................................................ 31
for loops ................................................................................................................................. 31
More loop examples ................................................................................................................. 32
Arrays ....................................................................................................................................... 33
A new demo .............................................................................................................................. 34
Testing with the Logic Analyzer............................................................................................... 36
Using the Explorer16 demonstration board .............................................................................. 37

Post-ight brieng ............................................................................................. 37


Notes for assembly experts ............................................................................... 37
Notes for PIC microcontroller experts............................................................... 38
Notes for C experts ............................................................................................ 38
Tips and tricks ..................................................................................................... 38
Exercises .............................................................................................................. 40
Books ................................................................................................................. 40
Links ................................................................................................................. 40
CHAPTER 4: NUMB3RS ............................................................................................. 41
Flight plan ........................................................................................................... 41
Preight checklist ............................................................................................... 42
The ight............................................................................................................. 42
On optimization (or lack thereof) ............................................................................................. 43
Testing ...................................................................................................................................... 44
Going long ................................................................................................................................ 44
Note on the multiplication of long integers .............................................................................. 45
Long long multiplication .......................................................................................................... 45
Floating point............................................................................................................................ 46

Notes for C experts ............................................................................................ 46


Measuring performance ........................................................................................................... 47

Post-ight brieng ............................................................................................. 49


Notes for assembly experts ....................................................................................................... 50

Notes for PIC microcontroller experts............................................................... 51


Tips and tricks ..................................................................................................... 51
viii

Contents
Math libraries............................................................................................................................ 51
Complex data types .................................................................................................................. 51

Exercises .............................................................................................................. 52
Books ................................................................................................................. 52
Links ................................................................................................................. 52
CHAPTER 5: INTERRUPTS ......................................................................................... 53
Flight plan ........................................................................................................... 53
Preight checklist ............................................................................................... 53
The ight............................................................................................................. 54
Nesting of interrupts ................................................................................................................. 57
Traps ......................................................................................................................................... 57
A template and an example for Timer1 interrupt ..................................................................... 58
A real example with Timer1 ..................................................................................................... 59
Testing the Timer1 interrupt ..................................................................................................... 61
The secondary oscillator ........................................................................................................... 63
The real-time clock calendar (RTCC) ...................................................................................... 64
Managing multiple interrupts ................................................................................................... 64

Post-ight brieng ............................................................................................. 65


Notes for C experts ............................................................................................ 65
Notes for assembly experts ............................................................................... 65
Notes for PIC microcontroller experts............................................................... 66
Tips and tricks ..................................................................................................... 66
Exercises .............................................................................................................. 68
Books ................................................................................................................. 68
Links ................................................................................................................. 68
CHAPTER 6: TAKING A LOOK UNDER THE HOOD .................................................. 69
Flight plan ........................................................................................................... 69
Preight checklist ............................................................................................... 69
The ight .................................................................................................................................. 70
Memory space allocation .......................................................................................................... 71
Program space visibility ........................................................................................................... 72
Investigating memory allocation .............................................................................................. 73
Looking at the MAP ................................................................................................................. 77
Pointers ..................................................................................................................................... 79
The heap ................................................................................................................................... 80
MPLAB C30 Memory Models ................................................................................................. 81

Post-ight brieng ............................................................................................. 81


Notes for C experts ............................................................................................ 81
Notes for assembly experts ............................................................................... 82
Notes for PIC microcontroller experts............................................................... 82
Tips and tricks ..................................................................................................... 82
Exercises .............................................................................................................. 83
ix

Contents
Books ................................................................................................................. 83
Links ................................................................................................................. 83

PART II FLYING SOLO


CHAPTER 7: COMMUNICATION ............................................................................... 89
Flight plan ........................................................................................................... 89
Preight checklist ............................................................................................... 89
The ight............................................................................................................. 90
Synchronous serial interfaces ................................................................................................... 90
Asynchronous serial interfaces ................................................................................................. 91

Parallel interfaces ............................................................................................... 92


Synchronous communication using the SPI modules .............................................................. 93
Testing the Read Status Register command ............................................................................. 95
Writing to the EEPROM........................................................................................................... 98
Reading the memory contents .................................................................................................. 99
A nonvolatile storage library .................................................................................................... 99
Testing the new NVM library ................................................................................................. 102

Post-ight brieng ........................................................................................... 104


Notes for C experts .......................................................................................... 104
Notes for the experts ....................................................................................... 104
Notes for PIC microcontroller experts............................................................. 105
Tips and tricks ................................................................................................... 105
Exercises ............................................................................................................ 107
Books ............................................................................................................... 107
Links ............................................................................................................... 107
CHAPTER 8: ASYNCHRONOUS COMMUNICATION ............................................... 109
Flight plan ......................................................................................................... 109
Preight checklist ............................................................................................. 109
The ight........................................................................................................... 110
UART conguration .......................................................................................... 111
Sending and receiving data ..................................................................................................... 113
Testing the serial communication routines ............................................................................. 114
Building a simple console library ........................................................................................... 116
Testing a VT100 terminal ....................................................................................................... 118
Using the serial port as a debugging tool ............................................................................... 120
The matrix .............................................................................................................................. 120

Post-ight brieng ........................................................................................... 122


Notes for C experts .......................................................................................... 123
Notes for PIC microcontroller experts............................................................. 124
Tips and tricks ................................................................................................... 124
About the ICD2 and UARTs on ICE .................................................................. 124
Exercises ............................................................................................................ 125
x

Contents
Books ............................................................................................................... 125
Links ............................................................................................................... 125
CHAPTER 9: GLASS BLISS ....................................................................................... 127
Flight plan ......................................................................................................... 128
Pre-ight checklist............................................................................................ 128
The ight........................................................................................................... 128
HD44780 controller compatibility ........................................................................................ 129
The Parallel Master Port ......................................................................................................... 131
Conguring the PMP for LCD module control ...................................................................... 132
A small library of functions to access an LCD display .......................................................... 133
Advanced LCD control ........................................................................................................... 136

Post-ight brieng ........................................................................................... 138


Notes for C experts .......................................................................................... 138
Tips and tricks ................................................................................................... 139
Exercises ............................................................................................................ 140
Books ............................................................................................................... 140
Links ............................................................................................................... 140
CHAPTER 10: ITS AN ANALOG WORLD ................................................................ 141
Flight plan ......................................................................................................... 141
Preight checklist ............................................................................................. 142
The ight........................................................................................................... 142
The rst conversion ................................................................................................................ 144
Automatic sampling timing .................................................................................................... 145
Developing a demo ................................................................................................................. 146
Developing a game ................................................................................................................. 147
Measuring temperature ........................................................................................................... 149
The breath-alizer game ........................................................................................................... 153

Post-ight brieng ........................................................................................... 154


Notes for C experts .......................................................................................... 154
Tips and tricks ................................................................................................... 155
Exercises ............................................................................................................ 155
Books ............................................................................................................... 155
Links ............................................................................................................... 155

PART III CROSS-COUNTRY FLYING


CHAPTER 11: CAPTURING INPUTS ......................................................................... 161
Flight plan ......................................................................................................... 161
The ight........................................................................................................... 162
The PS/2 communication protocol ......................................................................................... 163
Interfacing a PIC24 to the PS/2 .............................................................................................. 163
Input Capture .......................................................................................................................... 163
Testing the Input Capture method using Stimulus Scripts ..................................................... 168
xi

Contents
Testing the PS/2 receive routines ........................................................................................... 172
The simulation ........................................................................................................................ 174
The Simulator Prole ............................................................................................................. 175
Another method Change Notication .................................................................................. 176
Evaluating cost ....................................................................................................................... 181
A third method I/O polling .................................................................................................. 181
Testing the I/O polling method ............................................................................................... 186
Cost and efciency of the solution ......................................................................................... 188
Completing the interface: adding a FIFO buffer .................................................................... 190
Completing the interface: performing key codes decoding .................................................... 194

Post-ight brieng ........................................................................................... 197


Tips and tricks ................................................................................................... 198
Stalling transmissions from the keyboard Open-Drain Output Control .............................. 198

Exercises ............................................................................................................ 199


Books ............................................................................................................... 199
Links ............................................................................................................... 199
CHAPTER 12: THE DARK SCREEN........................................................................... 201
Flight plan ......................................................................................................... 201
The ight........................................................................................................... 202
Generating the composite video signal................................................................................... 204
Using the Output Compare modules ...................................................................................... 208
Memory allocation ................................................................................................................. 211
Image serialization.................................................................................................................. 211
Building the video module ..................................................................................................... 214
Testing the video generator .................................................................................................... 218
Measuring performance .......................................................................................................... 220
The dark screen....................................................................................................................... 221
A test pattern........................................................................................................................... 222
Plotting .................................................................................................................................. 223
A starry night .......................................................................................................................... 224
Line drawing ........................................................................................................................... 226
Bresenham algorithm.............................................................................................................. 228
Plotting math functions........................................................................................................... 230
Two-dimensional function visualization................................................................................. 232
Fractals ................................................................................................................................... 236
Text ......................................................................................................................................... 242
Testing the TextOnGPage module .......................................................................................... 246
Developing a text page video ................................................................................................. 247
Testing the text page performance .......................................................................................... 256

Post-ight brieng ........................................................................................... 260


Tips and tricks ................................................................................................... 260
Exercises ............................................................................................................ 261
Books ............................................................................................................... 261
Links ............................................................................................................... 261
xii

Contents
CHAPTER 13: MASS STORAGE ............................................................................... 263
Flight plan ......................................................................................................... 263
The ight........................................................................................................... 264
The SD/MMC card physical interface .................................................................................... 264
Interfacing to the Explorer16 board........................................................................................ 265
Starting a new project ............................................................................................................. 266
Selecting the SPI mode of operation ...................................................................................... 267
Sending commands in SPI mode ........................................................................................... 267
Completing the SD/MMC card initialization ......................................................................... 270
Reading data from an SD/MMC card ..................................................................................... 271
Writing data to an SD/MMC card .......................................................................................... 274
Using the SD/MMC interface module .................................................................................... 276

Post-ight brieng ........................................................................................... 280


Tips and tricks ................................................................................................... 280
Exercises ............................................................................................................ 281
Books ............................................................................................................... 281
Links ............................................................................................................... 281
CHAPTER 14: FILE I/O.............................................................................................. 283
Flight plan ......................................................................................................... 283
The ight........................................................................................................... 284
Sectors and Clusters ............................................................................................................... 284
The File Allocation Table (FAT) ............................................................................................. 285
The Root Directory ................................................................................................................. 286
The treasure hunt .................................................................................................................... 288
Opening a le ......................................................................................................................... 296
Reading data from a le ......................................................................................................... 305
Closing a le ........................................................................................................................... 308
Creating the leio module ...................................................................................................... 308
Testing fopenM() and freadM() .............................................................................................. 311
Writing data to a le ............................................................................................................... 313
Closing a le, second take ...................................................................................................... 317
Accessory functions................................................................................................................ 319
Testing the complete leio module......................................................................................... 323
Code Size ................................................................................................................................ 326

Post-ight brieng ........................................................................................... 326


Tips and tricks ................................................................................................... 327
Exercises ............................................................................................................ 327
Books ............................................................................................................... 328
Links ............................................................................................................... 328
CHAPTER 15: VOLARE ............................................................................................ 329
Flight plan ......................................................................................................... 330
The ight........................................................................................................... 330

xiii

Contents
Using the PIC24 OC modules in PWM mode ........................................................................ 332
Testing the PWM as a D/A converter ..................................................................................... 334
Producing analog waveforms ................................................................................................. 335
Reproducing voice messages ................................................................................................. 338
A media player ....................................................................................................................... 339
The WAVE le format ............................................................................................................ 339
The play() function ............................................................................................................ 341
The low level audio routines .................................................................................................. 347
Testing the WAVE le player.................................................................................................. 350
Optimizing the le I/O............................................................................................................ 353
LED Proling ......................................................................................................................... 353
Looking under the hood for more ........................................................................................... 356

Post-ight brieng ........................................................................................... 360


Tips and tricks ................................................................................................... 360
Exercises ............................................................................................................ 360
Books ............................................................................................................... 361
Links ............................................................................................................... 361
About the Author ............................................................................................. 363
Index ............................................................................................................... 365

xiv

Contents

CHAPTER I THE FUNDAMENTS OF PIC BASIC


CHAPTER II BASIC ELEMENTS OF PIC BASIC LANGUAGE
CHAPTER III OPERATORS
CHAPTER IV INSTRUCTIONS
CHAPTER V SAMPLE PROGRAMS FOR SUBSYSTEMS WITHIN THE
MICROS
CHAPTER VI SAMPLES WITH PIC16F84 MICROCONTROLLER
CHAPTER VII SAMPLES WITH PIC16F877 MICROCONTROLLER
APPENDIX A MPLAB
APPENDIX B MicroCode studio
In this book you can find:
Practical connection samples for:
Temperature sensors, AD and DA converters LCD and LED displays, relays. Every
example is commented in details with detailed connection scheme
Program writing
Learn how to write your own program, correct mistakes and use it to start a
microcontroller.
Instruction Set
Every instruction is explained in detail with the example how to use it.
MicroCode studio
How to install it, how to use it
MPLAB program package
How to install it, how to start the first program, how to connect BASIC and MPLAB
etc.

CONTENTS

Section 1
Display controller experiments

Section 2
Interfacing with keypads
Section 3
Experimenting with serial eeproms

Section 4
Experimenting with analog to digital converters

Section 5
Experimenting with digital to analog converters

Section 6
Experimenting with remote control

Section 7
Temperature measurement experiments

Section 8
Experimenting with robotics

Section 9
Experimenting with audio control devices

Section 10
Programming techniques

Section 11
Powering up the PIC

#ONTENTS
0REFACE X
!CKNOWLEDGMENTS XII
7HATSONTHE#$ 2/- XIII
#(!04%27HATISA0)# 
0)#Shv 
(OW$O)4ELL4HEM!PART 
7HICH/NE3HOULD)5SE 
(OW$O)0ICK/NE 
3O 7HICH/NE$O)2EALLY7ANTTO5SE 
"ASIC-ICROS-"ASIC#OMPILER 
2EFERENCES 

#(!04%2-"ASIC#OMPILERAND$EVELOPMENT"OARDS 
4HE#OMPILER0ACKAGE 
"!3)#AND)TS%SSENTIALS 
$EVELOPMENT"OARDS 
0ROGRAMMING3TYLE 
"UILDINGTHE#IRCUITSAND3TANDARD!SSUMPTIONS 
0INS 0ORTSAND)NPUT/UTPUT 
0SEUDO #ODEAND0LANNINGTHE0ROGRAM 
)NSIDETHE#OMPILER 
2EFERENCES 

#(!04%24HE"ASICSn/UTPUT 
0IN!RCHITECTURES 
,%$)NDICATORS 
3WITCHING)NDUCTIVE,OADS 
,OW3IDE3WITCHING 
)SOLATED3WITCHING 
3PECIAL0URPOSE3WITCHING 
&AST3WITCHING3OUNDFROMA0)# 
2EFERENCES 

#(!04%24HE"ASICSn$IGITAL)NPUT 
)NTRODUCTION 
3WITCH"OUNCEAND3EALING#URRENT 
)SOLATED3WITCHING 

#ONTENTS
2EADINGA+EYPAD 
2EFERENCES 

#(!04%2,#$-ODULES 
3ELECTINGA$ISPLAY 
6&$$ISPLAYS 
#ONNECTIONTO0)# 
(ELLO7ORLD 
,#$-ODULE-EMORY 3HIFTSAND,INES 
&ONT3ELECTION 
#USTOM#HARACTERS 
2EFERENCES 

#(!04%22EADING#OMPLEX)NPUT3WITCHES 
0IN3AVING4ECHNIQUES 
2OTARY%NCODERS 
2EADINGA2ELATIVE%NCODER 
$UAL%NCODERSAND,#$ 
2EFERENCES 

#(!04%23EVEN 3EGMENT,%$$ISPLAYS 


,%$$ISPLAY3ELECTION 
#IRCUIT$ESIGN 
2EFERENCES 

#(!04%2)NTRODUCTORY3TEPPER-OTORS 
3TEPPER-OTOR"ASICS 
0ROGRAMS 
2EFERENCES 

#(!04%223 3ERIAL)NTERFACE 


(OWTO#ONNECTTO9OUR0# 
6OLTAGE,EVELSIN23 AND,EVEL#ONVERSION 
3TANDARD0IN#ONNECTIONS 
!SYNCHRONOUS4RANSMISSION 3TART"ITS 3TOP"ITSAND"IT/RDER 
-"ASICS0ROCEDURESFOR3ERIAL#OMMUNICATIONS 
0ROGRAMS 
2EFERENCES 

#(!04%2)NTERRUPTSAND4IMERSIN-"ASIC 
)NTERRUPTSAND4IMERS/VERVIEW 
)NTERRUPTS 
4IMERS 
#APTUREAND#OMPARE 
2EFERENCES 

#(!04%2!NALOG TO $IGITAL#ONVERSION 


)NTRODUCTIONTO!NALOG TO $IGITAL#ONVERSION 
2ESOLUTIONAND!CCURACY 
3ELF #ONTAINED$6- 
2EFERENCES 
VI

#ONTENTS
#(!04%2$IGITAL4EMPERATURE3ENSORSAND2EAL 4IME#LOCKS 
$3"4EMPERATURE3ENSOR 
$32EAL 4IME#LOCK 
#OMBINATION$ATE 4IMEAND4EMPERATURE 
2EFERENCES 

#(!04%2!SSEMBLER 
4HE"ASICS 
/P#ODES 
2EFERENCES 

#(!04%2)N ,INE!SSEMBLER 


!DDING!SSEMBLERTO-"ASIC0ROGRAMS 
"OLT )N!SSEMBLER&UNCTIONS 
2EFERENCES 

#(!04%2)NTERRUPT(ANDLERSAND4IMERSIN!SSEMBLER 
)32!3-n-"ASICS'ATEWAYTO!SSEMBLER)NTERRUPT3ERVICE2OUTINES 
0ROGRAM%XAMPLES 
2EFERENCES 

#(!04%2$IGITAL TO !NALOG#ONVERSION 


)NTRODUCTIONTO$IGITAL TO !NALOG#ONVERSION 
2ESOLUTIONn!CCURACYAND3IGNAL TO .OISE2ATIO 
(ENRY.YQUISTANDHIS3AMPLING4HEOREM 
$!##IRCUIT$ESIGN 
!LTERNATIVE!NALOG/UTPUT3OLUTIONS 
2EFERENCES 

#(!04%2$4-&4ONE$ECODINGAND4ELEPHONE)NTERFACE 
7HATIS4OUCH 4ONE3IGNALING 
'ENERATING4OUCH 4ONE3IGNALS 
$ECODINGA4OUCH 4ONE3IGNAL 
2EFERENCES 

#(!04%2%XTERNAL-EMORY 
)# "US$EVICES 
0RACTICAL5SEOF%XTERNAL%%02/- 
0ARALLEL!CCESS-EMORY 
2EFERENCES 

#(!04%2!DVANCED3TEPPER-OTORS 
-ICROSTEPPING 
0ROGRAMS 
2EFERENCES 

#(!04%28 (OME!UTOMATION 


(OW8 7ORKS 
0ROGRAMS 
2EFERENCES 

VII

#ONTENTS
#(!04%2$IGITAL0OTENTIOMETERSAND#ONTROLLABLE&ILTER 
'ETTING3TARTEDWITHAN-#0 
23 #ONTROLOFAN-#0 
$AISY#HAINING-ULTIPLE-#0$EVICES 
23 #OMMANDOF-ULTIPLE$AISY#HAINED-#0$EVICES 
,OGARITHMIC2ESPONSEFOR!UDIO6OLUME#ONTROL 
%LECTRONICALLY4UNABLE,OW 0ASS&ILTER5SING-#0 
2EFERENCES 

#(!04%2)NFRARED2EMOTE#ONTROLS 
#OMMON%NCODING3TANDARDS 
)22ECEIVER 
#HARACTERIZING7IDE.ARROW0ULSE)NTERVALS 
$ECODINGA2%# #ONTROLLER 
2EFERENCES 

#(!04%2!#0OWER#ONTROL 
)NTRODUCTIONTO4RIACS 
3NUBBERLESSVERSUS3TANDARDD6DTANDD)DT)SSUES 
4RIGGERINGA4RIAC 
0HASEAND#YCLE#ONTROL 
0OWER#ONTROL"OARD 
0ROGRAMS 
2EFERENCES 

#(!04%2$#-OTOR#ONTROL 
)NTRODUCTIONTO#ONTROL4HEORY 
-EASURE-OTOR3PEED4ACHOMETER/UTPUT0ULSE7IDTH  
%RROR4ARGET7IDTHn-EASURED7IDTH 
4HE#ONTROL!LGORITHM 
-OTOR#ONTROL0ROGRAMS 
2EFERENCES 

#(!04%2"AR#ODE2EADER 
"AR#ODEShv 
"AR#ODE7AND 
0ROGRAMS 
2EFERENCES 

#(!04%23ENDING-ORSE#ODE 
-ORSE#ODE 
0ROGRAMS 
2EFERENCES 

#(!04%2-ORSE#ODE2EADER 
3ENDINGAND2ECEIVING-ORSE 
4ONE$ETECTOR#IRCUIT 
0ROGRAMS 
2EFERENCES 

VIII

#ONTENTS
#(!04%27EATHER3TATIONAND$ATA,OGGER 
3ENSOR3ELECTION 
#ONNECTINGTHE3ENSORSAND-EMORY 
)NITIAL4ESTS 
2EFERENCES 

#(!04%2-IGRATINGFROMVXTOANDTHE5NDOCUMENTED-"ASIC 
-IGRATINGFROMVXTO 
5NDOCUMENTED-"ASIC 

!00%.$)8!0ARTS,ISTAND3UPPLIERS 
3UPPLIERS 
'ENERIC#OMPONENTS2EQUIRED 
3PECIlC#OMPONENTS 

!00%.$)8"&UNCTION)NDEX 
!BOUTTHE!UTHOR 
)NDEX 

IX

Contents

Introduction

xi

Chapter One: Getting Familiar with PICs and PicBasic . . . . . . . . . . . .1


PIC Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2
Software for PICs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9
Assembly Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .10
PicBasic Compiler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .11
Chapter Two: PicBasic Compiler (PBC) . . . . . . . . . . . . . . . . . . . . . . . .13
How PBC Works . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .14
Variables, Memory, and I/O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .17
Program Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .18
PBC Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .21
Using PBC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .47

vii

Chapter Three: The PicBasic Pro Compiler . . . . . . . . . . . . . . . . . . . .51


Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .55
Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .57
Symbols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .58
Numeric and ASCII . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .58
Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .59
I/O Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .59
I/O Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .60
Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .62
Math Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .62
Arithmetic Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .63
Binary Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .65
PBPro Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .66
Chapter Four: Inside the PIC Microcontroller . . . . . . . . . . . . . . . . .117
Fundamentals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .117
Program Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .118
Reset Vector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .119
Data Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .120
STATUS Register . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .120
I/O Registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .122
A/D Registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .123
Peripheral Interrupt Vector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .126
OPTION Register . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .127

viii

INTCON Register . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .129


Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .132
Chapter Five: Simple PIC Projects . . . . . . . . . . . . . . . . . . . . . . . . . .133
Project #1Flashing an LED . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .133
Project #2Scrolling LEDs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .139
Project #3Driving a 7-Segment LED Display . . . . . . . . . . . . . . . . . . . . .146
Chapter Six: Moving on with the 16F876 . . . . . . . . . . . . . . . . . . . . . .153
Project #4Accessing Port A I/O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .153
Project #5Analog-to-Digital Conversion . . . . . . . . . . . . . . . . . . . . . . . .162
Project #6Driving a Servomotor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .173
Chapter Seven: Communication . . . . . . . . . . . . . . . . . . . . . . . . . . . .183
Project #7Driving a LCD Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . .183
Project #8Serial Communication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .195
Project #9Driving a LCD with a Single Serial Connection . . . . . . . . . . .204
Chapter Eight: Memory and Sound . . . . . . . . . . . . . . . . . . . . . . . . . .221
Project #10Using External Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . .222
Project #11Accessing Internal Memory . . . . . . . . . . . . . . . . . . . . . . . . .232
Project #12Making Music . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .241

ix

Chapter Nine: Robotics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .249


Project #13Robot Base . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .251
Project #14Line Tracker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .262
Project #15Obstacle Detection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .284
APPENDIX A . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .305
APPENDIX B . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .309
INDEX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .315

Contents
Preface

ix

Microcontroller systems
1.1 Introduction
1.2 Microcontroller systems
1.2.1 RAM
1.2.2 ROM
1.2.3 EPROM
1.2.4 EEPROM
1.2.5 Flash EEPROM
1.3 Microcontroller features
1.3.1 Supply voltage
1.3.2 The clock
1.3.3 Timers
1.3.4 Watchdog
1.3.5 Reset input
1.3.6 Interrupts
1.3.7 Brown-out detector
1.3.8 Analogue-to-digital converter
1.3.9 Serial I/O
1.3.10 EEPROM data memory
1.3.11 LCD drivers
1.3.12 Analogue comparator
1.3.13 Real-time clock
1.3.14 Sleep mode
1.3.15 Power-on reset
1.3.16 Low power operation
1.3.17 Current sink/source capability
1.4 Microcontroller architectures
1.4.1 RISC and CISC
1.5 Exercises

1
1
2
5
6
6
6
6
6
7
7
7
7
8
8
8
8
9
9
9
10
10
10
10
10
10
11
11
11

The PIC microcontroller family


2.1 12-bit instruction word
2.2 14-bit instruction word
2.3 16-bit instruction word
2.4 Inside a PIC microcontroller
2.4.1 Program memory (Flash)
2.4.2 Data memory (RAM)

13
15
17
21
21
21
22

vi

Contents
2.4.3 Register file map and special function registers
2.4.4 Oscillator circuits
2.4.5 Reset circuit
2.4.6 Interrupts
2.4.7 The configuration word
2.4.8 I/O interface
2.5 Exercises

22
34
40
41
42
42
47

PIC microcontroller project development


3.1 Required hardware tools
3.1.1 PC
3.1.2 PIC microcontroller programmer device
3.1.3 Solderless breadboard
3.1.4 PIC microcontroller and minimum support components
3.1.5 Power supply
3.2 Required software tools
3.2.1 Text editor
3.2.2 PicBasic and PicBasic Pro compilers
3.2.3 Programmer device software
3.3 Bundled development systems
3.4 Experimenter boards
3.5 Example project development
3.6 Other useful development tools
3.6.1 Simulators
3.6.2 In Circuit Emulators (ICE)
3.7 Exercises
3.8 Links to useful web sites

49
49
49
50
52
53
58
60
60
65
67
69
71
73
77
77
77
78
78

PicBasic and PicBasic Pro programming


4.1 PicBasic language
4.1.1 PicBasic variables
4.1.2 PicBasic mathematical and logical operations
4.1.3 PicBasic program flow control commands
4.1.4 Other PicBasic commands
4.1.5 Recommended PicBasic program structure
4.2 PicBasic Pro language
4.2.1 PicBasic Pro variables
4.2.2 Constants
4.2.3 Comments
4.2.4 Multi-statement lines
4.2.5 INCLUDE
4.2.6 DEFINE
4.2.7 Line extension
4.2.8 Accessing ports and other registers in PicBasic Pro

80
80
80
85
86
90
101
101
102
103
103
103
104
104
104
104

Contents

4.3

4.4
4.5
4.6
4.7
4.8
5

4.2.9 Arithmetic operators


4.2.10 PicBasic Pro commands
Liquid crystal display (LCD) interface and commands
4.3.1 Parallel LCDs
4.3.2 Serial LCDs
Interrupts
Recommended PicBasic Pro program structure
Using stepping motors
Using servomotors
Exercises

PicBasic and PicBasic Pro projects


Project 1 Simple flashing LED
Project 2 Complex flashing LED
Project 3 Flashing LED warning lights
Project 4 Turning on odd numbered LEDs
Project 5 Binary counting LEDs
Project 6 Left scrolling LEDs
Project 7 Right scrolling LEDs
Project 8 Right-left scrolling LEDs
Project 9 LED dice
Project 10 7-segment LED display counter
Project 11 7-segment LED dice
Project 12 Dual 7-segment LED display
Project 13 Dual 7-segment LED display counter
Project 14 Dual 7-segment LED event counter
Project 15 4-digit display with serial driver counter project
Project 16 4-digit LED with serial driver counter project with leading zeroes blanked
Project 17 4-digit external interrupt-driven event counter
Project 18 4-digit timer interrupt-driven chronograph
Project 19 Car park control system
Project 20 Seconds counter with LCD display
Project 21 LCD-based clock with hoursminutesseconds display
Project 22 LCD-based chronometer
Project 23 LCD-based voltmeter using A/D converter
Project 24 LCD-based thermometer using A/D converter
Project 25 Serial LCD-based thermometer with external EEPROM memory
Project 26 Programmable thermometer with RS232 serial output
Project 27 Electronic organ
Project 28 Unipolar stepping motor control
Project 29 Unipolar stepping motor control using UCN5804B
Project 30 Servomotor-based mobile robot control

About the CDROM


Index

vii
105
107
113
114
120
124
125
126
128
129
131
132
138
142
144
148
152
156
160
165
172
182
189
198
204
210
227
236
241
248
260
271
280
288
300
306
315
331
337
344
348
359
361

Potrebbero piacerti anche