You are on page 1of 112

PIC book

CHAPTER I INTRODUCTION TO CHAPTER V MPLAB


MICROCONTROLLERS
Introduction
Introduction
History 5.1 Installing the MPLAB program package
Microcontrollers versus microprocessors 5.2 Introduction to MPLAB
5.3 Choosing the development mode
1.1 Memory unit 5.4 Designing a project
1.2 Central processing unit 5.5 Designing new assembler file
1.3 Buses 5.6 Writing a program
1.4 Input-output unit 5.7 MPSIM simulator
1.5 Serial communication 5.8 Toolbar
1.6 Timer unit
1.7 Watchdog CHAPTER VI THE SAMPLES
1.8 Analog to digital converter
1.9 Program Introduction

6.1 The microcontroller power supply


CHAPTER II MICROCONTROLLER 6.2 Macros used in programs
PIC16F84
● Macros WAIT, WAITX
Introduction ● Macro PRINT

CISC, RISC
Applications 6.3 Samples
Clock/instruction cycle
Pipelining ● Light Emitting Diodes
Pin description ● Keyboard
● Optocoupler
2.1 Clock generator - oscillator ❍ Optocouplering the input lines

2.2 Reset ❍ Optocouplering the output lines

2.3 Central processing unit ● Relays


2.4 Ports ● Generating a sound
2.5 Memory organization ● Shift registers
2.6 Interrupts ❍ Input shift register
2.7 Free timer TMR0 ❍ Output shift register

2.8 EEPROM Data memory ● 7-segment Displays (multiplexing)


● LCD display
● 12-bit AD converter
CHAPTER III INSTRUCTION SET ● Serial communication

Introduction APPENDIX A INSTRUCTION SET

Instruction set in PIC16Cxx microcontroller


family APPENDIX B NUMERIC SYSTEMS
Data Transfer
Arithmetic and logic
Introduction
Bit operations
Directing the program flow
Instruction execution period B.1 Decimal numeric system
Word list B.2 Binary numeric system
B.3 Hexadecimal numeric system

CHAPTER IV ASSEMBLY LANGUAGE APPENDIX C GLOSSARY


PROGRAMMING

Introduction

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


Contents

Preface xi

1 Introduction 1
1.1 The Idea of System Control 1
1.2 Computer in the Loop 2
1.3 Centralized and Distributed Control Systems 5
1.4 Scada Systems 6
1.5 Hardware Requirements for Computer Control 7
1.5.1 General Purpose Computers 7
1.5.2 Microcontrollers 8
1.6 Software Requirements for Computer Control 9
1.6.1 Polling 11
1.6.2 Using External Interrupts for Timing 11
1.6.3 Using Timer Interrupts 12
1.6.4 Ballast Coding 12
1.6.5 Using an External Real-Time Clock 13
1.7 Sensors Used in Computer Control 14
1.7.1 Temperature Sensors 15
1.7.2 Position Sensors 17
1.7.3 Velocity and Acceleration Sensors 20
1.7.4 Force Sensors 21
1.7.5 Pressure Sensors 21
1.7.6 Liquid Sensors 22
1.7.7 Air Flow Sensors 23
1.8 Exercises 24
Further Reading 25

2 System Modelling 27
2.1 Mechanical Systems 27
2.1.1 Translational Mechanical Systems 28
2.1.2 Rotational Mechanical Systems 32
vi CONTENTS

2.2 Electrical Systems 37


2.3 Electromechanical Systems 42
2.4 Fluid Systems 44
2.4.1 Hydraulic Systems 44
2.5 Thermal Systems 49
2.6 Exercises 52
Further Reading 52

3 The PIC Microcontroller 57


3.1 The PIC Microcontroller Family 57
3.1.1 The 10FXXX Family 58
3.1.2 The 12CXXX/PIC12FXXX Family 59
3.1.3 The 16C5X Family 59
3.1.4 The 16CXXX Family 59
3.1.5 The 17CXXX Family 60
3.1.6 The PIC18CXXX Family 60
3.2 Minimum PIC Configuration 61
3.2.1 External Oscillator 63
3.2.2 Crystal Operation 63
3.2.3 Resonator Operation 63
3.2.4 RC Operation 65
3.2.5 Internal Clock 65
3.3 Some Popular PIC Microcontrollers 66
3.3.1 PIC16F84 Microcontroller 67
3.3.2 PIC16F877 Microcontroller 71
3.4 Exercises 75
Further Reading 76

4 Programming PIC Microcontrollers in C 77


4.1 PICC Lite Variable Types 78
4.1.1 Bit 78
4.1.2 Unsigned Char 78
4.1.3 Signed Char 79
4.1.4 Unsigned Int 79
4.1.5 Signed Int 79
4.1.6 Long 79
4.1.7 Unsigned Long 79
4.1.8 Float 80
4.1.9 Double 80
4.2 Variables 80
4.3 Comments in Programs 81
4.4 Storing Variables in the Program Memory 82
4.5 Static Variables 82
4.6 Volatile Variables 83
4.7 Persistent Variables 83
CONTENTS vii

4.8 Absolute Address Variables 83


4.9 Bank1 Qualifier 83
4.10 Arrays 84
4.11 ASCII Constants 86
4.12 Arithmetic and Logic Operators 86
4.13 Number Bases 89
4.14 Structures 89
4.15 Program Flow Control 91
4.15.1 If–Else Statement 91
4.15.2 Switch–Case Statement 92
4.15.3 For Statement 94
4.15.4 While Statement 95
4.15.5 Do Statement 95
4.15.6 Break Statement 96
4.15.7 Continue Statement 96
4.16 Functions in C 96
4.16.1 User Functions 97
4.16.2 Built-in Functions 98
4.17 Pointers in C 99
4.18 Pre-processor Commands 101
4.18.1 #define 101
4.18.2 #include 103
4.18.3 #asm and #endasm 103
4.19 Accessing the EEPROM Memory 104
4.20 Interupts in C Programs 104
4.21 Delays in C Programs 105
4.22 Structure of a C Program 105
4.23 PIC Microcontroller Input–Output Interface 107
4.23.1 Connecting an LED 107
4.23.2 Connecting a Push-Button Switch 109
4.23.3 Connecting an LCD 111
4.24 Exercises 116
Further Reading 117

5 Microcontroller Project Development 119


5.1 Hardware and Software Requirements 119
5.2 Program Development Tools 120
5.2.1 Flow Charts 121
5.2.2 Structure Charts 121
5.2.3 Pseudocode 123
5.3 Exercise 129
Further Reading 129

6 Sampled Data Systems and the z-Transform 131


6.1 The Sampling Process 131
6.2 The z-Transform 136
viii CONTENTS

6.2.1 Unit Step Function 137


6.2.2 Unit Ramp Function 137
6.2.3 Exponential Function 138
6.2.4 General Exponential Function 138
6.2.5 Sine Function 139
6.2.6 Cosine Function 139
6.2.7 Discrete Impulse Function 140
6.2.8 Delayed Discrete Impulse Function 140
6.2.9 Tables of z-Transforms 140
6.2.10 The z-Transform of a Function Expressed as a Laplace Transform 140
6.2.11 Properties of z-Transforms 143
6.2.12 Inverse z-Transforms 145
6.3 Pulse Transfer Function and Manipulation of Block Diagrams 154
6.3.1 Open-Loop Systems 154
6.3.2 Open-Loop Time Response 156
6.3.3 Closed-Loop Systems 162
6.3.4 Closed-Loop Time Response 166
6.4 Exercises 166
Further Reading 169

7 System Time Response Characteristics 171


7.1 Time Response Comparison 171
7.2 Time Domain Specifications 174
7.3 Mapping the s-Plane into the z-Plane 177
7.4 Damping Ratio and Undamped Natural Frequency in the z-Plane 178
7.4.1 Damping Ratio 178
7.4.2 Undamped Natural Frequency 179
7.5 Damping Ratio and Undamped Natural Frequency Using Formulae 181
7.6 Exercises 183
Further Reading 184

8 System Stability 187


8.1 Factorizing the Characteristic Equation 187
8.2 Jury’s Stability Test 189
8.3 Routh–Hurwitz Criterion 192
8.4 Root Locus 194
8.5 Nyquist Criterion 201
8.6 Bode Diagrams 205
8.7 Exercises 208
Further Reading 211

9 Discrete Controller Design 213


9.1 Digital Controllers 214
9.1.1 Dead-Beat Controller 215
9.1.2 Dahlin Controller 217
CONTENTS ix

9.1.3 Pole-Placement Control – Analytical 219


9.1.4 Pole-Placement Control – Graphical 222
9.2 PID Controller 230
9.2.1 Saturation and Integral Wind-Up 233
9.2.2 Derivative Kick 233
9.2.3 PID Tuning 134
9.3 Exercises 137
Further Reading 240

10 Controller Realization 243


10.1 Direct Structure 243
10.1.1 Direct Canonical Structure 243
10.1.2 Direct Noncanonical Structure 245
10.2 Cascade Realization 246
10.3 Parallel Realization 249
10.4 PID Controller Implementations 250
10.5 Microcontroller Implementations 253
10.5.1 Implementing Second-Order Modules 254
10.5.2 Implementing First-Order Modules 260
10.5.3 Implementing Higher-Order Modules 263
10.6 Choice of Sampling Interval 263
10.7 Exercises 267
Further Reading 268

11 Liquid Level Digital Control System: a Case Study 269


11.1 The System Schematic 269
11.2 System Model 270
11.3 Identification of the System 273
11.4 Designing a Controller 274
11.5 Conclusions 278

Appendix A Table of z-Transforms 283

Appendix B MATLAB Tutorial 285

Index 307
Contents

Preface .................................................................................................................. ix
What’s 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
What’s 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

v
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
Something’s 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 Stack’s Physical Layer .............................................................................................. 284
The TCP/IP Stack’s Data Link Layer ........................................................................................... 284

vi
Contents

The TCP/IP Stack’s Network Layer............................................................................................. 284


The TCP/IP Stack’s Transport Layer ........................................................................................... 284
The TCP/IP Stack’s Application Layer ........................................................................................ 285
TCP/IP – The Big Ugly .............................................................................................................. 285
You’ve 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

1 PIC Hardware 3
Processor System 4
PIC 16F877 Architecture 8
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

4 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

5 Data Processing 101


Number Systems 101
Conversion 106
Variable Types 110
Arithmetic 112

6 Calculate, Compare & Capture 121


Calculator 121
Pulse Output 128
Period Measurement 130

7 Analogue Interfacing 141


8-bit Conversion 141
10-bit Conversion 145
Amplifier Interfaces 149

xii
Contents

Transient & Frequency Response 160


Instrumentation Amplifier 161
Current Loop 163
Comparators 165
Op-amp Selection 168
Analogue Output 168

Part 3 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
2
IC 210

10 Sensor Interfacing 223


Sensors 223
Sensor Types 228
Amplifier Design 236
Weather Station 238

xiii
Contents

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

xiv
CONTENIDO

Prologo
1. Microcontroladores programables: La solución esta en un chip
2: Microcontroladores de 8 bits:
3: Los sellos mágicos de parallax
4: Pbasic: El lenguaje mas fácil 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 diseño de
proyectos
11: Ejercicios de programación en ensamblador
12: Los primeros diseños prácticos.
A: Guía Rápida del PIC16X84
B: Guía del usuario del SIM2000
C: Breve descripción del Micro PIC Trainer
D: La familia PIC al completo
E: Contenido del CD
F: Proyectos con el PIC16F84 Bibliografía y direcciones de interés relacionadas
con los PIC Índice
Table of Contents

Preface xv

Chapter 1 - Basic Electronics 1


1.0 The Atom 1
1.1 Isotopes and Ions 2
1.2 Static Electricity 3
1.3 Electrical Charge 4
1.3.1 Voltage 4
1.3.2 Current 4
1.3.3 Power 5
1.3.4 Ohm's Law 5
1.4 Electrical Circuits 6
1.4.1 Types of Circuits 6
1.5 Circuit Elements 8
1.5.1 Resistors 9
1.5.2 Revisiting Ohm's Law 9
1.5.3 Resistors in Series and Parallel 10
1.5.4 Capacitors 12
1.5.5 Capacitors in Series and in Parallel 13
1.5.6 Inductors 14
1.5.7 Transformers 15
1.6 Semiconductors 15
1.6.1 Integrated Circuits 16
1.6.2 Semiconductor Electronics 16
1.6.3 P-Type and N-Type Silicon 17
1.6.4 The Diode 17

Chapter 2 - Number Systems 19


2.0 Counting 19
2.0.1 The Tally System 19
2.0.2 Roman Numerals 20
2.1 The Origins of the Decimal System 20
2.1.1 Number Systems for Digital-Electronics 22
2.1.2 Positional Characteristics 22
2.1.3 Radix or Base of a Number System 23

v
vi Microcontroller Programming

2.2 Types of Numbers 23


2.2.1 Whole Numbers 24
2.2.2 Signed Numbers 24
2.2.3 Rational, Irrational, and Imaginary Numbers 24
2.3 Radix Representations 25
2.3.1 Decimal versus Binary Numbers 25
2.3.2 Hexadecimal and Octal 26
2.4 Number System Conversions 27
2.4.1 Binary-to-ASCII-Decimal 28
2.4.2 Binary-to-Hexadecimal Conversion 29
2.4.3 Decimal-to-Binary Conversion 29

Chapter 3 - Data Types and Data Storage 33


3.0 Electronic-Digital Machines 33
3.1 Character Representations 33
3.1.1 ASCII 34
3.1.2 EBCDIC and IBM 36
3.1.3 Unicode 36
3.2 Storage and Encoding of Integers 37
3.2.1 Signed and Unsigned Representations 37
3.2.2 Word Size 38
3.2.3 Byte Ordering 39
3.2.4 Sign-Magnitude Representation 40
3.2.5 Radix Complement Representation 41
3.3 Encoding of Fractional Numbers 44
3.3.1 Fixed-Point Representations 45
3.3.2 Floating-Point Representations 46
3.3.3 Standardized Floating-Point Representations 47
3.3.4 IEEE 754 Single Format 48
3.3.5 Encoding and Decoding Floating-Point Numbers 50
3.4 Binary-Coded Decimals (BCD) 51
3.4.1 Floating-Point BCD 52

Chapter 4 - Digital Logic, Arithmetic, and Conversions 55


4.0 Microcontroller Logic and Arithmetic 55
4.0.1 CPU Flags 55
4.0.2 Word Size 56
4.1 Logical Instructions 56
4.1.1 Logical AND 57
4.1.2 Logical OR 57
4.1.3 Logical XOR 57
4.1.4 Logical NOT 58
4.2 Microcontroller Arithmetic 58
4.2.1 Unsigned and Two’s Complement Arithmetic 58
4.2.2 Operations on Decimal Numbers 60
4.3 Bit Manipulations and Auxiliary Operations 62
4.3.1 Bit Shift and Rotate 62
4.3.2 Comparison Operations 63
4.3.3 Other Support Operations 63
Contents vii

4.4 Unsigned Binary Arithmetic 64


4.4.1 Multi-byte Unsigned Addition 64
4.4.2 Unsigned Multiplication 65
4.4.3 Unsigned Division 67
4.5 Signed Binary Arithmetic 67
4.5.1 Overflow Detection in Signed Arithmetic 69
4.5.2 Sign Extension Operations 70
4.5.3 Multi-byte Signed Operations 71
4.6 Data Format Conversions 72
4.6.1 BCD Digits to ASCII Decimal 72
4.6.2 Unsigned Binary to ASCII Decimal Digits 73
4.6.3 ASCII Decimal String to Unsigned Binary 73
4.6.4 Unsigned Binary to ASCII Hexadecimal Digits 75
4.6.6 Signed Numerical Conversions 76

Chapter 5 - Circuits and Logic Gates 77


5.0 Digital Circuits 77
5.1 The Diode Revisited 78
5.1.1 The Light-Emitting Diode (LED) 79
5.2 The Transistor 81
5.2.1 Bipolar Transistor 81
5.2.2 MOS Transistor 83
5.3 Logic Gates 84
5.4 Transistor-Transistor Logic 85
5.4.1 Inverter Gates 86
5.4.2 The AND Gate 87
5.4.3 The NAND Gate 87
5.4.4 The OR Gate 88
5.4.5 The NOR Gate 88
5.4.6 Positive and Negative Logic 89
5.4.7 The XOR Gate 90
5.4.8 Schmitt Trigger Inverter 91
5.5 Other TTL Logic Families 93
5.6 CMOS Logic Gates 93

Chapter 6 - Circuit Components 95


6.0 Power Supplies 95
6.1 Clocked Logic and Flip-flops 96
6.1.1 The RS Flip-flop 96
6.1.2 Clocked RS Flip-flop 98
6.1.3 The D Flip-flop 99
6.1.4 The Edge-triggered D Flip-flop 100
6.1.5 Preset and Clear Signals 101
6.1.6 D Flip-flop Waveform Action 102
6.1.7 Flip-flop Applications 103
6.2 Clocks 103
6.2.1 Clock Waveforms 104
6.2.2 The TTL Clock 105
6.2.3 The 555 Timer 106
viii Microcontroller Programming

6.2.4 Microcontroller Clocks 106


6.3 Frequency Dividers and Counters 107
6.3.1 Frequency Dividers 107
6.3.2 The JK Flip-flop Counter 107
6.3.3 Ripple Counters 108
6.3.4 Decoding Gates 110
6.3.5 Synchronous Counters 110
6.3.6 Counter ICs 112
6.3.7 Shift Registers 113
6.4 Multiplexers and Demultiplexers 115
6.4.1 Multiplexers 115
6.4.2 Demultiplexers 118
6.4.3 Multiplexer and Demultiplexer ICs 118
6.5 Input Devices 118
6.5.1 Switches 118
6.5.2 Switch Contact Bounce 120
6.5.3 Keypads 121
6.6 Output Devices 122
6.6.1 Seven-segment LED 122
6.6.2 Liquid Crystal Displays 124
6.6.3 LCD Technologies 125

Chapter 7 - The Microchip PIC 129


7.0 The PICMicro Microcontroller 129
7.0.1 Programming the PIC 130
PIC Programmers 131
Development Boards 131
7.0.2 Prototyping the PIC Circuit 132
7.1 PIC Architecture 134
7.1.1 Baseline PIC Family 134
PIC10 Devices 135
PIC12 Devices 135
PIC14 Devices 138
7.1.2 Mid-range PIC Family 138
PIC16 Devices 139
7.1.3 High-Performance PIC Family 139
PIC18 Devices 139

Chapter 8 - Mid-range PIC Architecture 141


8.0 Processor Architecture and Design 142
8.0.1 Harvard Architecture 142
8.0.2 RISC CPU Design 143
8.0.3 Single-word Instructions 143
8.0.4 Instruction Format 144
8.0.5 Mid-Range Device Versions 145
8.1 The Mid-range Core Features 145
8.1.1 Oscillator 145
8.1.2 System Reset 147
8.1.3 Interrupts 148
8.2 Mid-Range CPU and Instruction Set 149
Contents ix

8.2.1 Mid-Range Instruction Set 149


8.2.2 STATUS and OPTION Registers 151
8.3 EEPROM Data Storage 153
8.3.1 EEPROM in Mid-Range PICs 153
8.4 Data Memory Organization 154
8.4.1 The w Register 154
8.4.2 The Data Registers 154
Memory Banks 154
The SFRs 155
The GPRs 157
8.4.3 Indirect Addressing 158
8.5 Mid-range I/O and Peripheral Modules 158
8.5.1 I/O Ports 159
8.5.2 Timer Modules 160
8.5.3 Capture-and-Compare Module 160
8.5.4 Master Synchronous Serial Port (MSSP) Module 161
8.5.5 USART Module 161
8.5.6 A/D Module 161

Chapter 9 - PIC Programming: Tools and Techniques 163


9.0 Microchip’s MPLAB 163
9.0.1 Embedded Systems 164
9.1 Integrated Development Environment 165
9.1.1 Installing MPLAB 165
9.1.2 Creating the Project 167
9.1.3 Project Build Options 169
9.1.4 Building the Project 169
9.2 Simulators and Debuggers 170
9.2.1 MPLAB SIM 171
9.2.2 MPLAB Hardware Debuggers 172
9.2.3 A “Quick-and-Dirty” Debugger 174
9.3 Programmers 174
9.4 Engineering PIC Software 175
9.4.1 Using Program Comments 176
Program Header 176
Commented Banners 177
Commented Bitmaps 178
9.4.2 Defining Data Elements 179
The cblock Directive 179
9.4.3 Banking Techniques 180
The banksel Directive 180
Bank Selection Macros 180
Deprecated Banking Instructions 181
9.4.4 Processor and Configuration Controls 182
Configuration Bits 182
9.4.5 Naming Conventions 184
9.4.6 Errorlevel Directive 186
9.5 Pseudo Instructions 186
x Microcontroller Programming

Chapter 10 - Programming Essentials: Input and Output 189


10.0 16F84A Programming Template 189
10.1 Introducing the 16F84A 191
10.1.1 Template Circuit for 16F84A 191
10.1.2 Power Supplies 191
Voltage Regulator 192
10.1.3 Comparisons in PIC Programming 193
The Infamous PIC Carry Flag 194
10.2 Simple Circuits and Programs 194
10.2.1 A Single LED Circuit 194
LED Flasher Program 196
10.2.2 LED/Pushbutton Circuit 199
10.2.3 Multiple LED Circuit 202
10.3 Programming the Seven-segment LED 204
10.4 A Demonstration Board 206
10.4.1 PCB Images for Demo Board 206
10.4.2 TestDemo1 Program 208

Chapter 11 - Interrupts 211


11.0 Interrupts on the 16F84 211
11.0.1 The Interrupt Control Register 211
11.0.2 The OPTION Register 212
11.1 Interrupt Sources 213
11.1.1 Port-B External Interrupt 214
11.1.2 Timer0 Interrupt 214
11.1.3 Port-B Line Change Interrupt 215
Multiple External Interrupts 217
11.1.4 EEPROM Data Write Interrupt 217
11.2 Interrupt Handlers 217
11.2.1 Context Saving Operations 218
Saving w and STATUS Registers 218
11.3 Interrupt Programming 218
11.3.1 Programming the External Interrupt 219
RB0 Interrupt Initialization 220
RB0 Interrupt Service Routine 221
11.3.2 Wakeup from SLEEP Using the RB0 Interrupt 222
The SleepDemo Program 223
11.3.3 Port-B Bits 4-7 Status Change Interrupt 224
RB4-7 Interrupt Initialization 225
RB4-7 Change Interrupt Service Routine 227
11.4 Sample Programs 229
11.4.1 The RB0Int Program 229
11.4.2 The SleepDemo Program 232
11.4.3 The RB4to7Int Program 235

Chapter 12 - Timers and Counters 241


12.0 The 16F84 Timer0 Module 241
12.0.1 Timer0 Operation 241
Contents xi

Timer0 Interrupt 242


Timer0 Prescaler 242
12.1 Delays Using Timer0 243
12.1.1 Long Delay Loops 244
How Accurate the Delay? 245
The Black-Ammerman Method 245
12.2 Timer0 as a Counter 246
12.3 Timer0 Programming 247
12.3.1 Programming a Counter 247
A Timer/Counter Test Circuit 248
The Tmr0Counter Program 248
12.3.2 Timer0 as a Simple Delay Timer 250
12.3.3 Measured Time Lapse 252
Interrupt-driven Timer 255
12.4 The Watchdog Timer 259
12.4.1 Watchdog Timer Programming 260
12.5 Sample Programs 260
12.5.1 The Tmr0Counter program 260
12.5.2 The Timer0 Program 263
12.5.3 The LapseTimer Program 265
12.5.4 The LapseTmrInt Program 269

Chapter 13 - LCD Interfacing and Programming 275


13.0 LCD Features and Architecture 275
13.0.1 LCD Functions and Components 276
Internal Registers 276
Busy Flag 276
Address Counter 276
Display Data RAM (DDRAM) 276
Character Generator ROM (CGROM) 276
Character Generator RAM (CGRAM) 277
Timing Generation Circuit 277
Liquid Crystal Display Driver Circuit 278
Cursor/Blink Control Circuit 278
13.0.2 Connectivity and Pin-Out 278
13.1 Interfacing with the HD44780 279
13.1.1 Busy Flag or Timed Delay Options 280
13.1.2 Contrast Control 281
13.1.3 Display Backlight 281
13.1.4 Display Memory Mapping 281
13.2 HD44780 Instruction Set 283
13.2.1 Instruction Set Overview 283
Clearing the Display 283
Return home 284
Entry mode set 284
Display and Cursor ON/OFF 284
Cursor/display shift 284
Function set 285
Set CGRAM address 285
Set DDRAM address 285
Read busy flag and Address register 285
xii Microcontroller Programming

Write data 285


Read data 286
13.2.2 A 16F84 8-bit Data Mode Circuit 286
13.3 LCD Programming 287
13.3.1 Defining Constants and Variables 287
Using MPLAB Data Directives 289
13.3.2 LCD Initialization 290
Function Set Command 290
Display Off 291
Display and Cursor On 291
Set Entry Mode 292
Cursor and Display Shift 292
Clear Display 293
13.3.3 Auxiliary Operations 293
Time Delay Routine 293
Pulsing the E Line 295
Reading the Busy Flag 295
Bit Merging Operations 296
13.3.4 Text Data Storage and Display 298
Generating and Storing a Text String 299
Displaying the Text String 301
13.3.5 Data Compression Techniques 302
4-bit Data Transfer Mode 302
Master/Slave Systems 304
13.4 Sample Programs 306
13.4.1 LCDTest1 306
13.4.2 LCDTest2 Program 316
13.4.3 LCDTest3 Program 327

Chapter 14 - Communications 339


14.0 PIC Communications Overview 339
14.1 Serial Data Transmission 340
14.1.1 Asynchronous Serial Transmission 340
14.1.2 Synchronous Serial Transmission 342
14.1.3 PIC Serial Communications 342
14.1.4 The RS-232-C Standard 343
Essential Concepts 344
The Serial Bit Stream 344
Parity Testing 345
Connectors and Wiring 345
The Null Modem 346
The Null Modem Cable 347
14.1.5 The EIA-485 Standard 349
EIA-485 in PIC-based Systems 350
14.2 Parallel Data Transmission 350
14.2.1 PIC Parallel Slave Port (PSP) 351
14.3 PIC “Free-style” Serial Programming 351
14.3.1 PIC-to-PIC Serial Communications 352
PIC-to-PIC Serial Communications Circuits 352
PIC-to-PIC Serial Communications Programs 354
14.3.2 Program Using Shift Register ICs 360
Contents xiii

The 74HC165 Parallel-to-Serial Shift Register 361


74HC164 Serial-to-Parallel Shift Register 364
14.4 PIC Protocol-based Serial Programming 366
14.4.1 RS-232-C Communications on the 16F84 366
The RS-232-C Transceiver IC 367
PIC to PC Communications 368
An RS-232-C TTY Board 368
A 16F84A UART Emulation 369
An LCD Scrolling Routine 371
14.4.2 RS-232-C Communications on the 16F87x 375
The 16F87x USART Module 376
The USART Baud Rate Generator 376
16F87x USART Asynchronous Transmitter 379
16F87x USART Asynchronous Receiver 380
PIC-to-PC RS-232-C Communications Circuit 381
16F877 PIC Initialization Code 381
USART Receive and Transmit Routines 384
The USART Receive Interrupt 386
14.5 Sample Programs 389
14.5.1 SerialSnd Program 389
14.5.2 SerialRcv Program 394
14.5.3 Serial6465 Program 400
14.5.4 TTYUsart Program 404
14.5.5 SerComLCD Program 420
14.5.6 SerIntLCD Program 438

Chapter 15 - Data EEPROM Programming 459


15.0 PIC Internal EEPROM Memory 460
15.0.1 EEPROM Programming on the 16F84 460
Reading EEPROM Data Memory on the 16F84 460
16F84 EEPROM Data Memory Write 461
16F84 EEPROM Demonstration Program 462
15.0.2 EEPROM Programming on the 16F87x 465
Reading EEPROM Data Memory on the 16F87x 467
Writing to EEPROM Data Memory in the 16F87x 467
GFR Access Issue in the 16F87x 469
15.0.3 16F87x EEPROM Circuit and Program 469
15.1 EEPROM Devices and Interfaces 475
15.1.1 The I2C Serial Interface 476
15.1.2 I2C Communications 476
15.1.3 EEPROM Communications Conditions 477
15.1.4 EEPROM Write Operation 478
15.1.5 EEPROM Read Operation 478
15.1.6 I2C EEPROM Devices 479
15.1.7 PIC Master Synchronous Serial Port (MSSP) 480
MSSP in Master Mode 482
15.1.8 I2C Serial EEPROM Programming on the 16F877 486
IC2 Initialization Procedure 486
I2C Write Byte Procedure 488
I2C Read Byte Procedure 490
15.2 Sample Programs 492
xiv Microcontroller Programming

15.2.1 EECounter Program 492


15.2.2 Ser2EEP Program 504
15.2.3 I2CEEP Program 521

Chapter 16 - Analog to Digital and Realtime Clocks 543


16.0 A/D Converters 544
16.0.1 Converter Resolution 544
16.0.2 ADC Implementation 545
16.1 A/D Integrated Circuits 546
16.1.1 ADC0331 Sample Circuit and Program 547
16.2 PIC On-Board A/D Hardware 549
16.2.1 A/D Module on the 16F87x 549
The ADCON0 Register 550
The ADCON1 Register 552
SLEEP Mode Operation 554
16.2.2 A/D Module Sample Circuit and Program 554
16.3 Realtime Clocks 558
16.3.1 The NJU6355 Realtime Clock 558
16.3.2 RTC Demonstration Circuit and Program 560
BCD Conversion Procedures 565
16.4 Sample Programs 568
16.4.1 ADF84 Program 568
16.4.2 A2DinLCD Program 580
16.4.3 RTC2LCD Program 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
v

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 Two’s 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 Bus Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
3.3.1 Address Bus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
3.3.2 Data Bus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
3.3.3 Control Bus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
3.4 Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
3.5 Time Base . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
3.5.1 Timing Subsystem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
3.6 Port Systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
3.7 Analog-to-Digital Converters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
3.8 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
3.9 Interrupt System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
3.10 Speed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
3.11 Choosing a Microcontroller for a Specific Design . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
3.11.1 System Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
3.12 Microcontroller Vendors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
3.13 Cutting Edge Technology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
3.14 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48

4. 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 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
7.4 Application: DC Motor Speed and Direction Control . . . . . . . . . . . . . . . . . . . . . 106
7.4.1 Motor Operating Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
7.5 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
Contents

Preface ................................................................................................................. ix
A Quick Look at the Microcontrollers .................................................................................. x
Atmel’s AVR ................................................................................................................. x
Microchip’s PIC ........................................................................................................... xii
What’s on the CD-ROM? .................................................................................. xvi

Chapter 1: The Essence of Microcontroller Networking—RS-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
Microchip’s 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

v
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: I2C…The Other Serial Protocol ............................................................. 81


Why use I²C? ................................................................................................................... 83
The I²C bus ...................................................................................................................... 83
I²C ACKS and NAKS .................................................................................................. 86
More on Arbitration and Clock Synchronization ......................................................... 87
I²C Addressing ........................................................................................................... 91
Some I²C Firmware .................................................................................................... 91
The AVR Master I²C Code .......................................................................................... 92
The AVR I²C Master-Receiver Mode Code .................................................................. 97
The PIC I²C Slave-Transmitter Mode Code .................................................................. 99
The AVR-to-PIC I²C 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 CS8900A’s 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 PIC16F877’s 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: Let’s 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

1 Introduction to the PIC microcontroller 1


The aim of the book 1
Program memory 2
Microcontroller clock 3
The microcontroller system 3
Types of microcontroller 4
Microcontroller specification 5
Using the microcontroller 6
1 Microcontroller hardware 6
2 Programming the microcontroller 9

2 Programming the 16F84 microcontroller 11


Microcontroller inputs and output (I/O) 12
Timing with the microcontroller 12
Programming the microcontroller 12
Entering data 13
The header for the 16F84 14
Program example 16
Saving and assembling the code 19
PICSTART PLUS programmer 23
Programming flowchart 26
Problem: flashing two LEDs 26
Solution to problem, flashing two LEDs 27

3 Introductory projects 29
LED_Flasher2 29
SOS 30
Code for SOS circuit 30
Flashing 8 LEDs 33
Chasing 8 LEDs 35
Traffic lights 39
More than 8 outputs 45

4 Headers, porting code – which micro? 47


Factors affecting the choice of the microcontroller 47
Choosing the microcontroller 48
Headers 49
vi Contents

5 Using inputs 64
Switch flowchart 66
Program development 67
Scanning (using multiple inputs) 73
Switch scanning 73
Control application – a hot air blower 77

6 Understanding the headers 82


The 16F84 82
16F84 memory map 87
The 16F818 88

7 Keypad scanning 93
Programming example for the keypad 94

8 Program examples 110


Counting events 110
Look up table 115
7-Segment display 115
Numbers larger than 255 126
Long time intervals 133
One hour delay 136

9 The 16C54 microcontroller 139


Header for the 16C54 139
16C54 memory map 142

10 Alpha numeric displays 143


Display pin identification 144
Configuring the display 145
Writing to the display 146
Program example 146
Program operation 160
Display configuration 161
Writing to the display 162
Displaying a number 163

11 Analogue to digital conversion 166


Making an A/D reading 167
Configuring the A/D device 168
Analogue header for the 16F818 171
A/D conversion – example, a temperature sensitive
switch 174
Program code 176
Another example – a voltage indicator 178
Contents vii

12 Radio transmitters and receivers 186


Measuring the received pulse width 189

13 EEPROM data memory 199


Example using the EEPROM 200

14 Interrupts 207
Interrupt sources 208
Interrupt control register 208
Program using an interrupt 209

15 The 12 series 8 pin microcontroller 216


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

16 The 16F87X Microcontroller 229


16F87X family specification 229
The 16F872 microcontroller 230
16F87X memory map 232
The 16F872 header 233
16F872 application – a greenhouse control 236
Programming the 16F872 microcontroller
using PICSTART PLUS 242
Reconfiguring the 16F872 header 243

17 The 16F62X Microcontroller 245


16F62X oscillator modes 245
16F62X and 16F84 Pinouts 247
16F62X port configuration 247
16F62X memory map 248
The 16F62X headers 248
HEAD62RC.ASM 250
A 16F627 application – flashing an LED on and off 252
The 16F627 LED flasher code 253
Configuration settings for the 16F627 255
Other features of the 16F62X 255
viii Contents

18 Projects 257
Project 1 Electronic dice 257
Project 2 Reaction timer 266
Project 3 Burglar alarm 272
Fault finding 282
Development kits 285

19 Instruction set, files and registers 287


The PIC microcontroller instruction set 287
Registers 289
Instruction set summary 292

Appendix A Microcontroller data 299


Appendix B Electrical characteristics 301
Appendix C Decimal, binary and hexadecimal numbers 303
Appendix D Useful contacts 306

Index 307
Contents

Chapter 1. Conventions Used in This Book 1

Chapter 2. PICmicro® MCU Part Number


Feature Comparison 3

Feature to Part Number Table 3

Chapter 3. Device Pinouts 7

Low-End 8
Mid-Range 10
PIC17Cxx 14
PIC18Cxx 17

Chapter 4. PICmicro® MCU Instruction Sets 21

Parameters 21
Low-End Instruction Set 22
Mid-Range Instruction Set 31
PIC17Cxx Instruction Set 40
PIC18Cxx Instruction Set 63
Microchip Special Instruction Mnemonics 104
Parallax PICmicro® MCU Instruction Set 111

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

Chapter 5. PICmicro® MCU Processor


Architectures 123

The PICmicro® MCU’s Arithmetic Logic Unit 123


Low-End PICmicro® MCUs 125
Register access 126
STATUS register 128
Program counter 128
Mid-Range PICmicro® MCUs 130
Register access 130
STATUS register 132
Program counter 133
Interrupt operation 134
Interrupt handler skeleton 135
PIC17Cxx 136
Register access 137
STATUS register 138
Program counter 139
Interrupt operation 140
Interrupt handler skeleton 142
PIC18Cxx 142
Register access 144
STATUS register 146
Program counter 147
Interrupt operation 150
Interrupt handler skeleton 150

Chapter 6. PICmicro® MCU Register Mappings 151


Low-End PICmicro® MCUs 151
Mid-Range PICmicro® MCUs 154
PIC17Cxx 169
PIC18Cxx 186
Contents vii

Chapter 7. Built-In Hardware Features 207

Configuration Registers 207


Oscillators 208
Sleep 213
Option Register 216
Input/Output Ports and TRIS Registers 217
Watchdog Timer 221
TMR0 222
Prescaler 223
TMR1 224
TMR2 227
Compare/Capture/PWM(CCP) Module 228
USART Module 232
SSP Module 239
SPI operation 239
I2C operation 244
Built-In ADC 252
Built-In Comparators 257
Parallel Slave Port 261
Built-In EEPROM Data Memory Access 263
EPROM Program Memory Access 269
Flash Program Memory Access 271
External Parallel Memory 273

Chapter 8. PICmicro® MCU


Hardware Interfacing 277

Power 277
Reset 281
Digital Logic Interfacing 282
viii Contents

Parallel Bus Device Interfacing 282


Button Interfacing 284
Switch Matrix Keypad/Keyboard Interfacing 287
Combining Input and Output 291
Simulated “Open Collector’’/“Open Drain’’ I/O 292
LEDs 293
Multisegment LED displays 293
LCD Interfaces 296
I2C Bit Banging “Master’’ Interface 334
RS-232 Interfaces 338
RS-485/RS-422 345
Asynchronous Serial I/O Software Routines 347
Dallas Semiconductor One-Wire Interface 357
Reading Potentiometer Using Parallel I/O Pins 363
Motor Drivers 365
R/C Servo Control 370
Audio Output 371
AC Power Control 373
Hall-Effect Sensors 374
Sony Infrared TV Remote Control 374

Chapter 9. PICmicro® MCU Programming 379

“Hex’’ File Format 379


Low-End PICmicro® MCU Programming 381
Mid-Range Serial Programming 385
PIC17Cxx Programming 394
PIC17Cxx ICSP Programming 398
PIC18Cxx Programming 402
Microchip ICSP Programming Connector 405
Third Party/Downloadable Programmers 406
Contents ix

Chapter 10. PC Interfaces 407

Memory Map 407


I/O Space Map 407
Interrupt Function by Number 422
ISA Bus 425
ISA pinouts 425
Interrupts 429
Keyboard and Mouse Ports 430
Connector specification 430
Keyboard operation with timing diagrams 431
Keyboard scan codes 432
Keyboard controller commands 436
BIOS interfaces 436
Keyboard commands 441
Serial Port 441
Connector pinouts 442
8250 block diagram 443
Serial port base addresses 443
8250 registers 444
Interrupts 449
Interrupt 14h–RS-232 communications APIs 451
Parallel Port 455
Block diagram/connector 455
Base registers 457
Registers 457
Data output waveform 458
BIOS interfaces 459

Chapter 11. Useful Code “Snippets’’ 461

Jumping Outside the Current Page 461


Tables 462
Conditional Branching 465
x Contents

Time Delays 466


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

Chapter 12. 16-Bit Numbers 483

Defining 16 Bit Numbers 483


Increments and Decrements 484
Addition/Subtraction 485
Bitwise Operations on Constants and Variables 488
Contents xi

Comparisons with 16-Bit Variables 489


Multiplication 492
Division 495

Chapter 13. PICmicro® MCU


Operations Tables 499

I/O Pin Current Capabilities 500


RC Oscillator Component Values 500
LP Oscillator Operating Characteristics 501
XT Oscillator Operating Characteristics 502
HS Oscillator Operating Characteristics 504

Chapter 14. PICmicro® MCU Application


Debugging Checklist 507

Chapter 15. PICmicro® MCU Application


Software Development Tools 517

Microsoft Compatible Editor “Ctrl’’ Key


Combinations 517
MPSIM.INI 518
MPLAB 519
Stimulus (.STI) files 525
MPLAB assembler directives 526
Standard Declaration and Include (“.inc’’) Files 536
Linking–Linked Applications 536
Application Code Template 539
The BASIC Language 540
Microsoft BASIC Enhancements 542
PicBasic 549
xii Contents

Visual Basic 578


MSComm control 581
The “C’’ Language 588
Declarations 588
Statements 590
Operators 593
Directives 595
“Backslash’’ characters 598
Common C functions 598
PICmicro® MCU enhancement functions 603

Chapter 16. Constants and Data Tables 605

Mathematical and Physical Constants 605


ASCII 606
ASCII control characters 607
ANSI display control sequences 609
IBM PC extended ASCII characters 612
Windows ASCII characters 612
EBCDIC 612
Audio Notes 615
“Touch-Tone’’ Telephone Frequencies 616
Modem “AT’’ Commands 616
Modem registers 622
Morse Code 625
Phonetic Alphabets 626
“Ten’’ Radio Codes 626

Chapter 17. Miscellaneous Electronics 629

Resistor Color Coding 629


Electromagnetic Spectrum 630
Radar bands 632
Contents xiii

Digital Logic 632


Gates 632
Flip flops 633

Chapter 18. Formulas 635


DC Electronics Formulas 635
AC Electronics Formulas 636
Mathematical Formulas 638
Boolean Arithmetic 638
Conversions 640

Chapter 19. Resources 641


Microchip 641
PICmicro® MCU Books 642
Useful Books 643
PICList Internet List Server 648
Recommended PICmicro® MCU Web Sites 656
Periodicals 658
Useful Web Sites 659
Hardware FAQs 660
Part Suppliers 661
Digi-Key 661
AP Circuits 661
Wirz Electronics 662
Tower Hobbies 663
Jameco 663
JDR 663
Newark 664
Marshall Industries 664
Mouser Electronics 665
Mondo-tronics Robotics Store 665

Index 667
Contents

Introduction xxi
Acknowledgements xxv

Section 1 Getting Started with Embedded Systems 1

1 Tiny computers, hidden control 3


1.1 The main idea – embedded systems in today’s world 3
1.1.1 What is an embedded system? 3
1.2 Some example embedded systems 4
1.2.1 The domestic refrigerator 4
1.2.2 A car door mechanism 5
1.2.3 The electronic ‘ping-pong’ 6
1.2.4 The Derbot Autonomous Guided Vehicle 7
1.3 Some computer essentials 8
1.3.1 Elements of a computer 9
1.3.2 Instruction sets – CISC and RISC 9
1.3.3 Memory types 10
1.3.4 Organising memory 10
1.4 Microprocessors and microcontrollers 11
1.4.1 Microprocessors 11
1.4.2 Microcontrollers 12
1.4.3 Microcontroller families 13
1.4.4 Microcontroller packaging and appearance 14
1.5 Microchip and the PIC microcontroller 15
1.5.1 Background 15
1.5.2 PIC microcontrollers today 15
1.6 An introduction to PIC microcontrollers using the 12 Series 17
1.6.1 The 12F508 architecture 18
1.7 What others do – a Freescale microcontroller 20
Summary 22
References 22

Section 2 Minimum Systems and the PIC® 16F84A 23

2 Introducing the PIC® 16 Series and the 16F84A 25


2.1 The main idea – the PIC 16 Series family 25
2.1.1 A family overview 25
vi Contents

2.1.2 The 16F84A 27


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

3 Parallel ports, power supply and the clock oscillator 45


3.1 The main idea – parallel input/output 46
3.2 The technical challenge of parallel input/output 46
3.2.1 Building a parallel interface 46
3.2.2 Port electrical characteristics 49
3.2.3 Some special cases 49
3.3 Connecting to the parallel port 52
3.3.1 Switches 52
3.3.2 Light-emitting diodes 53
3.4 The PIC 16F84A parallel ports 55
3.4.1 The 16F84A Port B 55
3.4.2 The 16F84A Port A 55
3.4.3 Port output characteristics 56
3.5 The clock oscillator 59
3.5.1 Clock oscillator types 59
3.5.2 Practical oscillator considerations 60
3.5.3 The 16F84A clock oscillator 60
3.6 Power supply 61
3.6.1 The need for power, and its sources 61
3.6.2 16F84A operating conditions 62
3.7 The hardware design of the electronic ping-pong 63
Contents vii

Summary 64
References 64

4 Starting to program – an introduction to Assembler 65


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

5 Building Assembler programs 89


5.1 The main idea – building structured programs 89
5.1.1 Flow diagrams 89
5.1.2 State diagrams 91
5.2 Flow control – branching and subroutines 92
5.2.1 Conditional branching and working with bits 92
5.2.2 Subroutines and the Stack 94
viii Contents

5.3 Generating time delays and intervals 95


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

6 Working with time: interrupts, counters and timers 120


6.1 The main idea – interrupts 121
6.1.1 Interrupt structures 121
6.1.2 The 16F84A interrupt structure 122
6.1.3 The CPU response to an interrupt 124
6.2 Working with interrupts 125
6.2.1 Programming with a single interrupt 125
6.2.2 Moving to multiple interrupts – identifying the source 126
Contents ix

6.2.3 Stopping interrupts from wrecking your


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

Section 3 Larger Systems and the PIC® 16F873A 143

7 Larger systems and the PIC® 16F873A 145


7.1 The main idea – the PIC 16F87XA 146
7.2 The 16F873A block diagram and CPU 146
7.2.1 Overview of CPU and core 146
7.2.2 Overview of memory 147
7.2.3 Overview of peripherals 150
7.3 16F873A memory and memory maps 150
7.3.1 The 16F873A program memory 150
7.3.2 The 16F873A data memory and Special Function Registers 152
7.3.3 The Configuration Word 154
7.4 ‘Special’ memory operations 155
7.4.1 Accessing EEPROM and program memory 155
7.4.2 In-Circuit Serial Programming (ICSPTM ) 156
7.5 The 16F873A interrupts 158
7.5.1 The interrupt structure 158
7.5.2 The interrupt registers 159
7.5.3 Interrupt identification and context saving 161
7.6 The 16F873A oscillator, reset and power supply 161
7.6.1 The clock oscillator 161
7.6.2 Reset and power supply 161
7.7 The 16F873A parallel ports 161
7.7.1 The 16F873A Port A 163
7.7.2 The 16F873A Port B 164
7.7.3 The 16F873A Port C 164
x Contents

7.8 Test, commission and diagnostic tools 165


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

8 The human and physical interfaces 184


8.1 The main idea – the human interface 184
8.2 From switches to keypads 187
8.2.1 The keypad 187
8.2.2 Design example: use of keypad in Derbot hand controller 188
8.3 LED displays 193
8.3.1 LED arrays: seven-segment displays 193
8.3.2 Design example: the Derbot hand controller
seven-segment display 194
8.4 Liquid crystal displays 199
8.4.1 The HD44780 LCD driver and its derivatives 199
8.4.2 Design example: use of LCD display in Derbot hand controller 200
8.5 The main idea – interfacing to the physical world 203
8.6 Some simple sensors 203
8.6.1 The microswitch 204
8.6.2 Light-dependent resistors 204
8.6.3 Optical object sensing 205
8.6.4 The opto-sensor applied as a shaft encoder 205
8.6.5 Ultrasonic object sensor 207
8.7 More on digital input 207
8.7.1 16F873A input characteristics 207
8.7.2 Ensuring legal logic levels, and input protection 208
8.7.3 Switch debouncing 212
Contents xi

8.8 Actuators: motors and servos 212


8.8.1 DC and stepper motors 212
8.8.2 Angular positioning: the ‘servo’ 214
8.9 Interfacing to actuators 215
8.9.1 Simple DC switching 215
8.9.2 Simple switching on the Derbot 217
8.9.3 Reversible switching: the H-bridge 218
8.9.4 Motor switching on the Derbot 220
8.10 Building up the Derbot 220
8.11 Applying sensors and actuators – a ‘blind’ navigation Derbot program 222
Summary 223
References 223

9 Taking timing further 225


9.1 The main ideas – taking counting and timing further 225
9.2 The 16F87XA Timer 0 and Timer 1 226
9.2.1 Timer 0 226
9.2.2 Timer 1 226
9.2.3 Application of Timer 0 and Timer 1 as counters for Derbot odometry 228
9.2.4 Using Timer 0 and Timer 1 to generate repetitive interrupts 231
9.3 The 16F87XA Timer 2, comparator and PR2 register 232
9.3.1 Timer 2 232
9.3.2 The PR2 register, comparator and postscaler 234
9.4 The capture/compare/PWM (CCP) modules 235
9.4.1 A capture/compare/PWM overview 235
9.4.2 Capture mode 235
9.4.3 Compare mode 237
9.5 Pulse width modulation 237
9.5.1 The principle of PWM 237
9.5.2 Generating PWM signals in hardware – the 16F87XA PWM 239
9.5.3 PWM applied in the Derbot for motor control 241
9.6 Generating PWM in software 244
9.6.1 An example of software-generated PWM 245
9.6.2 Further Assembler directives for memory definition and branching 248
9.7 PWM used for digital-to-analog conversion 249
9.7.1 An example of PWM used for digital-to-analog conversion 249
9.8 Frequency measurement 252
9.8.1 The principle of frequency measurement 252
9.8.2 Frequency (speed) measurement in the Derbot 252
9.9 Speed control applied to the Derbot 255
9.10 Where there is no timer 258
9.11 Sleep mode 260
9.12 Where do we go from here? 261
9.13 Building up the Derbot 262
xii Contents

Summary 262
References 262

10 Starting with serial 263


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

10.11 Implementing serial without a serial port – ‘bit banging’ 303


10.12 Building up the Derbot 303
Summary 303
References 303

11 Data acquisition and manipulation 304


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

Section 4 Smarter Systems and the PIC® 18FXX2 333

12 Smarter systems and the PIC® 18FXX2 335


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

13 The PIC® 18FXX2 peripherals 368


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

14 Introducing C 386
14.1 The main idea – why C? 387
14.2 An introduction to C 387
14.2.1 A little history 387
14.2.2 A first program 388
14.2.3 Laying out the program – declarations, statements, comments and space 388
14.2.4 C keywords 390
14.2.5 The C function 391
14.2.6 Data type and storage 392
14.2.7 C operators 392
14.2.8 Control of program flow, and the while keyword 393
xvi Contents

14.2.9 The C preprocessor and its directives 394


14.2.10 Use of libraries, and the Standard Library 394
14.3 Compiling the C program 394
14.4 The MPLAB C18 compiler 395
14.4.1 Specification of radix 396
14.4.2 Arithmetic operations 396
14.5 A C18 tutorial 396
14.5.1 The Linker and Linker Scripts 396
14.5.2 Linking header and library files 397
14.5.3 Building the project 397
14.5.4 Project files 398
14.6 Simulating a C program 400
14.7 A second C example – the Fibonacci program 401
14.7.1 Program preliminaries – more on declaring variables 402
14.7.2 The do–while construct 403
14.7.3 Labels and the goto keyword 403
14.7.4 Simulating the Fibonacci program 403
14.8 The MPLAB C18 libraries 403
14.8.1 Hardware peripheral functions 404
14.8.2 The software peripheral library 404
14.8.3 The general software library 405
14.8.4 The maths library 406
14.9 Further reading 406
Summary 407
References 407

15 C and the embedded environment 409


15.1 The main idea – adapting C to the embedded environment 409
15.2 Controlling and branching on bit values 409
15.2.1 Controlling individual bits 411
15.2.2 The if and if–else conditional branch structures 411
15.2.3 Setting the configuration bits 412
15.2.4 Simulating and running the example program 412
15.3 More on functions 413
15.3.1 The function prototype 413
15.3.2 The function definition 414
15.3.3 Function calls and data passing 414
15.3.4 Library delay functions, and Delay10KTCYx( ) 415
15.4 More branching and looping 415
15.4.1 Using the break keyword 415
15.4.2 Using the for keyword 416
15.5 Using the timer and PWM peripherals 417
15.5.1 Using the timer peripherals 420
Contents xvii

15.5.2 Using PWM 421


15.5.3 The main program loop 421
Summary 422

16 Acquiring and using data with C 423


16.1 The main idea – using C for data manipulation 423
16.2 Using the 18FXX2 ADC 423
16.2.1 The light-seeking program structure 427
16.2.2 Use of the ADC 428
16.2.3 Further use of if–else 429
16.2.4 Simulating the light-seeking program 429
16.3 Pointers, arrays and strings 431
16.3.1 Pointers 431
16.3.2 Arrays 432
16.3.3 Using pointers with arrays 432
16.3.4 Strings 433
16.3.5 An example program: using pointers, arrays and strings 433
16.3.6 A word on evaluating the while condition 434
16.3.7 Simulating the program example 435
16.4 Using the I2 C peripheral 437
16.4.1 An example I2 C program 437
16.4.2 Use of ++ and −− operators 439
16.5 Formatting data for display 440
16.5.1 Overview of example program 440
16.5.2 Using library functions for data formatting 442
16.5.3 Program evaluation 442
Summary 443

17 More C and the wider C environment 444


17.1 The main idea – more C and the wider C environment 444
17.2 Assembler inserts 445
17.3 Controlling memory allocation 446
17.3.1 Memory allocation pragmas 447
17.3.2 Setting the Configuration Words 447
17.4 Interrupts 448
17.4.1 The Interrupt Service Routine 448
17.4.2 Locating and identifying the ISR 449
17.5 Example with interrupt on overflow – flashing LEDs
on the Derbot 449
17.5.1 Using Timer 0 450
17.5.2 Using interrupts, and the ISR action 451
17.5.3 Simulating the flashing LEDs program 452
17.6 Storage classes and their application 453
17.6.1 Storage classes 453
xviii Contents

17.6.2 Scope 454


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

18 Multi-tasking and the Real Time Operating System 466


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

18.6 Data and resource protection – the semaphore 478


18.7 Where do we go from here? 479
Summary 479
References 479

19 The SalvoTM Real Time Operating System 480


19.1 The main idea – Salvo, an example RTOS 480
19.1.1 Basic Salvo features 480
19.1.2 Salvo versions and references 481
19.2 Configuring the Salvo application 482
19.2.1 Building Salvo applications – the library build 482
19.2.2 Salvo libraries 482
19.2.3 Using Salvo with C18 483
19.3 Writing Salvo programs 483
19.3.1 Initialisation and scheduling 484
19.3.2 Writing Salvo tasks 485
19.4 A first Salvo example 485
19.4.1 Program overview and the main function 487
19.4.2 Tasks and scheduling 488
19.4.3 Creating a Salvo/C18 project 488
19.4.4 Setting the configuration file 489
19.4.5 Building the Salvo example 489
19.4.6 Simulating the Salvo program 490
19.5 Using interrupts, delays and semaphores with Salvo 491
19.5.1 An example program using an interrupt-based clock tick 492
19.5.2 Selecting the library and configuration 494
19.5.3 Using interrupts and establishing the clock tick 494
19.5.4 Using delays 496
19.5.5 Using a binary semaphore 496
19.5.6 Simulating the program 497
19.5.7 Running the program 499
19.6 Using Salvo messages and increasing RTOS complexity 499
19.7 A program example with messages 500
19.7.1 Selecting the library and configuration 505
19.7.2 The task: USnd_ Task 505
19.7.3 The task: Motor_ Task 505
19.7.4 The use of messages 506
19.7.5 The use of interrupts, and the ISRs 507
19.7.6 Simulating or running the program 509
19.8 The RTOS overhead 509
Summary 510
References 510
xx Contents

Section 5 Techniques of Connectivity and Networking 511


20 Connectivity and networks 513
20.1 The main idea – networking and connectivity 513
20.1.1 A word on protocols 514
20.2 Infrared connectivity 515
20.2.1 The IrDA and the PIC microcontroller 515
20.3 Radio connectivity 516
20.3.1 Bluetooth 516
20.3.2 Zigbee 517
20.3.3 Zigbee and the PIC microcontroller 517
20.4 Controller Area Network (CAN) and Local Interconnect Network (LIN) 518
20.4.1 Controller Area Network (CAN) 518
20.4.2 CAN and the PIC microcontroller 520
20.4.3 Local Interconnect Network (LIN) 520
20.4.4 LIN and the PIC microcontroller 521
20.5 Embedded systems and the Internet 522
20.5.1 Connecting to the Internet with the PIC microcontroller 523
20.6 Conclusion 523
Summary 524
References 524

Appendix 1 The PIC® 16 Series instruction set 527


Appendix 2 The electronic ping-pong 528
Appendix 3 The Derbot AGV – hardware design details 533
Appendix 4 Some basics of Autonomous Guided Vehicles 537
Appendix 5 PIC® 18 Series instruction set (non-extended) 541
Appendix 6 Essentials of C 544

Index 549
Contents

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

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

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

Part I The Fundamentals

1. Digital Representation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

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
El Registro INTCON .......................................27
Indice PCL y PCLATH ...............................................28
STACK (PILA) .................................................28
Cap tulo 1 Registros INDF y FSR ....................................29
Arquitectura de un PIC PORTS I/O......................................................30
Registros PORTA y TRISA .............................30
Introducci n ......................................................5 Registros PORTB y TRISB.............................32
Caracter sticas del PIC .....................................5 M dulo Temporizador TIMER0 .......................34
Caracter sticas Perif ricas................................5 Prescaler (Divisor de Frecuencia) ..................35
Caracter sticas Especiales del Interrupci n de Timer0....................................36
Microcontrolador ...............................................6 Memoria de Datos EEPROM..........................36
Patas del PIC....................................................6 Lectura de la Memoria de
Resumen del Dispositivo ..................................9 Datos de EEPROM.........................................38
Ficha Did ctica ...............................................10 Escritura de la Memoria de
Lo que Debe Saber Datos EEPROM..............................................39
Sobre los PICs................................................13 Verificaci n de Escritura .................................40
a) El Procesador es segmentado La CPU del PIC ..............................................42
tipo "pipe line" .................................................13 Bits de Configuraci n......................................43
b) El Procesador es de tipo RISC ..................14 Configuraciones del Oscilador........................43
c) Poseen una arquitectura Oscilador de Cristal o
tipo Harvard ....................................................14 Resonador de Cer mica.................................44
d) Son de arquitectura ortogonal basada Oscilador RC...................................................44
en banco de registros .....................................15 Reset...............................................................44
Palabras de Configuraci n Reset de Encendido .......................................47
e Identificaci n................................................18 Temporizador de Arranque del
Organizaci n de la Memoria...........................19 Oscilador (OST)..............................................48
Organizaci n de la Memoria Temporizador de Encendido
de Programas .................................................19 (PWRT) ...........................................................48
Organizaci n de la Memoria El Perro Guardi n (WDT) ...............................48
de Datos..........................................................19 Interrupciones del Micro .................................49
Los Registros del PIC.....................................20 Interrupci n Externa (INT) ..............................51
Archivo de Registro de Interrupci n por Desborde
Uso General....................................................20 del TMR0 ........................................................51
Registros de Funciones Interrupci n por Cambio de
Especiales (SFR)............................................21 Estado en las patas RB7 y RB4 .....................51
Registro de Status ..........................................23 Interrupci n por Finalizaci n de la Escritura
Registro OPTION_REG..................................25 en la EEPROM de datos ................................51

2 Microcontroladores PIC
Indice

Cap tulo 2 MOVF.....................................................81


Manejo de las Instrucciones MOVWF .................................................82
de un PIC NOP .......................................................83
RETFIE ..................................................83
Introducci n ....................................................53 RETLW ...................................................84
Instrucci n: SUMA ..........................................54 RETURN ................................................85
C digo de la instrucci n ADDWf ....................55 RLF ........................................................85
El Set de Instrucciones RRF........................................................86
del 16X84........................................................56 SLEEP....................................................87
ADDLW...................................................59 SUBLW...................................................88
ADDWF ..................................................60 SUBWF ..................................................90
ANDLW...................................................61 SWAPF...................................................92
ANDWF ..................................................62 XORLW ..................................................93
BCF ........................................................63 XORWF ..................................................94
BSF ........................................................64 Palabras de Configuraci n
BTFSC ...................................................65 e Identificaci n...............................................96
BTFSS....................................................67
CALL ......................................................68
CLRF......................................................69 Cap tulo 3
CLRW.....................................................70 Aprendiendo a Programar
CLRWDT ................................................71
COMF.....................................................72 Circuito de un Entrenador...............................97
DECF .....................................................73 Encendido Intermitente
DECFSZ.................................................74 de un Led......................................................100
GOTO.....................................................75 Secuenciador de 4 Canales .........................108
INCF.......................................................76 Generador de Se ales de Audio...................112
INCFSZ ..................................................77 Los Formatos de los Archivos.......................115
IORLW....................................................78 Secuenciador de 8 Canales..........................115
IORWF ...................................................79 Compilaci n de un Programa .......................118
MOVLW ..................................................80 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 3
Contents

Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .xi
Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xv
About the Author . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii
What’s on the CD-ROM? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .xix
Chapter 1: What Are Intelligent Sensors, and
Why Should I Care about Them? . . . . . . . . . . . . . . . . . . . . . . 1
1.1 Conventional Sensors Aren’t Perfect . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 First Things First—Digitizing the Sensor Signal. . . . . . . . . . . . . . . . . . 7
1.3 Next Step—Add Some Intelligence . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.4 Finish Up with Quick and Reliable Communications . . . . . . . . . . . . 8
1.5 Put It All Together, and You’ve Got an Intelligent Sensor . . . . . . . . . . 9
1.6 Why Don’t 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 DSC’s 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 Application—Temperature 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 Application—Pressure 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 Application—Flow 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 PICmicro®MCU 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 PICmicro®MCU 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

6
Table of Contents

1. Introduction 1
1.1 Typographical Conventions....................................................................... 1
1.2 Explaining the Microcontroller ................................................................. 2
1.3 Book Contents ........................................................................................... 3

2. Microcontroller Overview 5
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

i
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

x
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
Preflight checklist ................................................................................................. 4
The flight............................................................................................................... 4
Compiling and linking ................................................................................................................ 6
Building the first project ............................................................................................................. 7
PORT initialization ..................................................................................................................... 9
Retesting PORTA...................................................................................................................... 10
Testing PORTB ......................................................................................................................... 10
Post-flight briefing ............................................................................................. 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
Preflight checklist ............................................................................................... 17
The flight............................................................................................................. 18
An animated simulation ............................................................................................................ 21
Using the Logic Analyzer ........................................................................................................ 24
Post-flight briefing ............................................................................................. 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
Preflight checklist ............................................................................................... 30
The flight............................................................................................................. 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-flight briefing ............................................................................................. 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
Preflight checklist ............................................................................................... 42
The flight............................................................................................................. 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-flight briefing ............................................................................................. 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
Preflight checklist ............................................................................................... 53
The flight............................................................................................................. 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-flight briefing ............................................................................................. 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
Preflight checklist ............................................................................................... 69
The flight .................................................................................................................................. 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-flight briefing ............................................................................................. 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
Preflight checklist ............................................................................................... 89
The flight............................................................................................................. 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-flight briefing ........................................................................................... 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
Preflight checklist ............................................................................................. 109
The flight........................................................................................................... 110
UART configuration .......................................................................................... 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-flight briefing ........................................................................................... 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-flight checklist............................................................................................ 128
The flight........................................................................................................... 128
HD44780 controller compatibility ........................................................................................ 129
The Parallel Master Port ......................................................................................................... 131
Configuring the PMP for LCD module control ...................................................................... 132
A small library of functions to access an LCD display .......................................................... 133
Advanced LCD control ........................................................................................................... 136
Post-flight briefing ........................................................................................... 138
Notes for C experts .......................................................................................... 138
Tips and tricks ................................................................................................... 139
Exercises ............................................................................................................ 140
Books ............................................................................................................... 140
Links ............................................................................................................... 140

CHAPTER 10: IT’S AN ANALOG WORLD ................................................................ 141


Flight plan ......................................................................................................... 141
Preflight checklist ............................................................................................. 142
The flight........................................................................................................... 142
The first conversion ................................................................................................................ 144
Automatic sampling timing .................................................................................................... 145
Developing a demo ................................................................................................................. 146
Developing a game ................................................................................................................. 147
Measuring temperature ........................................................................................................... 149
The breath-alizer game ........................................................................................................... 153
Post-flight briefing ........................................................................................... 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 flight........................................................................................................... 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 Profile ............................................................................................................. 175
Another method – Change Notification .................................................................................. 176
Evaluating cost ....................................................................................................................... 181
A third method – I/O polling .................................................................................................. 181
Testing the I/O polling method ............................................................................................... 186
Cost and efficiency of the solution ......................................................................................... 188
Completing the interface: adding a FIFO buffer .................................................................... 190
Completing the interface: performing key codes decoding .................................................... 194
Post-flight briefing ........................................................................................... 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 flight........................................................................................................... 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-flight briefing ........................................................................................... 260
Tips and tricks ................................................................................................... 260
Exercises ............................................................................................................ 261
Books ............................................................................................................... 261
Links ............................................................................................................... 261

xii
Contents

CHAPTER 13: MASS STORAGE ............................................................................... 263


Flight plan ......................................................................................................... 263
The flight........................................................................................................... 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-flight briefing ........................................................................................... 280
Tips and tricks ................................................................................................... 280
Exercises ............................................................................................................ 281
Books ............................................................................................................... 281
Links ............................................................................................................... 281

CHAPTER 14: FILE I/O.............................................................................................. 283


Flight plan ......................................................................................................... 283
The flight........................................................................................................... 284
Sectors and Clusters ............................................................................................................... 284
The File Allocation Table (FAT) ............................................................................................. 285
The Root Directory ................................................................................................................. 286
The treasure hunt .................................................................................................................... 288
Opening a file ......................................................................................................................... 296
Reading data from a file ......................................................................................................... 305
Closing a file ........................................................................................................................... 308
Creating the fileio module ...................................................................................................... 308
Testing fopenM() and freadM() .............................................................................................. 311
Writing data to a file ............................................................................................................... 313
Closing a file, second take ...................................................................................................... 317
Accessory functions................................................................................................................ 319
Testing the complete fileio module......................................................................................... 323
Code Size ................................................................................................................................ 326
Post-flight briefing ........................................................................................... 326
Tips and tricks ................................................................................................... 327
Exercises ............................................................................................................ 327
Books ............................................................................................................... 328
Links ............................................................................................................... 328

CHAPTER 15: VOLARE ............................................................................................ 329


Flight plan ......................................................................................................... 330
The flight........................................................................................................... 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 file format ............................................................................................................ 339
The play() function ............................................................................................................ 341
The low level audio routines .................................................................................................. 347
Testing the WAVE file player.................................................................................................. 350
Optimizing the file I/O............................................................................................................ 353
LED Profiling ......................................................................................................................... 353
Looking under the hood for more ........................................................................................... 356
Post-flight briefing ........................................................................................... 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 
&AST3WITCHINGˆ3OUNDFROMA0)# 
2EFERENCES 
#(!04%24HE"ASICSn$IGITAL)NPUT 
)NTRODUCTION 
3WITCH"OUNCEAND3EALING#URRENT 
)SOLATED3WITCHING 

V
#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 #1—Flashing an LED . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .133

Project #2—Scrolling LEDs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .139

Project #3—Driving a 7-Segment LED Display . . . . . . . . . . . . . . . . . . . . .146

Chapter Six: Moving on with the 16F876 . . . . . . . . . . . . . . . . . . . . . .153

Project #4—Accessing Port A I/O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .153


Project #5—Analog-to-Digital Conversion . . . . . . . . . . . . . . . . . . . . . . . .162

Project #6—Driving a Servomotor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .173

Chapter Seven: Communication . . . . . . . . . . . . . . . . . . . . . . . . . . . .183

Project #7—Driving a LCD Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . .183

Project #8—Serial Communication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .195

Project #9—Driving a LCD with a Single Serial Connection . . . . . . . . . . .204

Chapter Eight: Memory and Sound . . . . . . . . . . . . . . . . . . . . . . . . . .221

Project #10—Using External Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . .222

Project #11—Accessing Internal Memory . . . . . . . . . . . . . . . . . . . . . . . . .232

Project #12—Making Music . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .241

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

Project #13—Robot Base . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .251

Project #14—Line Tracker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .262

Project #15—Obstacle Detection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .284

APPENDIX A . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .305

APPENDIX B . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .309

INDEX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .315

x
Contents

Preface ix

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

2 The PIC microcontroller family 13


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

2.4.3 Register file map and special function registers 22


2.4.4 Oscillator circuits 34
2.4.5 Reset circuit 40
2.4.6 Interrupts 41
2.4.7 The configuration word 42
2.4.8 I/O interface 42
2.5 Exercises 47

3 PIC microcontroller project development 49


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

4 PicBasic and PicBasic Pro programming 80


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

4.2.9 Arithmetic operators 105


4.2.10 PicBasic Pro commands 107
4.3 Liquid crystal display (LCD) interface and commands 113
4.3.1 Parallel LCDs 114
4.3.2 Serial LCDs 120
4.4 Interrupts 124
4.5 Recommended PicBasic Pro program structure 125
4.6 Using stepping motors 126
4.7 Using servomotors 128
4.8 Exercises 129

5 PicBasic and PicBasic Pro projects 131


Project 1 – Simple flashing LED 132
Project 2 – Complex flashing LED 138
Project 3 – Flashing LED warning lights 142
Project 4 – Turning on odd numbered LEDs 144
Project 5 – Binary counting LEDs 148
Project 6 – Left scrolling LEDs 152
Project 7 – Right scrolling LEDs 156
Project 8 – Right-left scrolling LEDs 160
Project 9 – LED dice 165
Project 10 – 7-segment LED display counter 172
Project 11 – 7-segment LED dice 182
Project 12 – Dual 7-segment LED display 189
Project 13 – Dual 7-segment LED display counter 198
Project 14 – Dual 7-segment LED event counter 204
Project 15 – 4-digit display with serial driver – counter project 210
Project 16 – 4-digit LED with serial driver – counter project with leading zeroes blanked 227
Project 17 – 4-digit external interrupt-driven event counter 236
Project 18 – 4-digit timer interrupt-driven chronograph 241
Project 19 – Car park control system 248
Project 20 – Seconds counter with LCD display 260
Project 21 – LCD-based clock with hours–minutes–seconds display 271
Project 22 – LCD-based chronometer 280
Project 23 – LCD-based voltmeter using A/D converter 288
Project 24 – LCD-based thermometer using A/D converter 300
Project 25 – Serial LCD-based thermometer with external EEPROM memory 306
Project 26 – Programmable thermometer with RS232 serial output 315
Project 27 – Electronic organ 331
Project 28 – Unipolar stepping motor control 337
Project 29 – Unipolar stepping motor control using UCN5804B 344
Project 30 – Servomotor-based mobile robot control 348

About the CDROM 359


Index 361

You might also like