Skip to main content

Full text of "Embedded Programming"

See other formats


-«flfc 



INULUUtb 12 

INCREDIBLE PROJECTS 

YOU CAN BUILD! 



MICROCONTROLLER 



PROJE 



BOOK 



A TR U E BEGINNER'S GUIDE TO TH E 
POPULAR PIC MICROCONTROLLER 



JOHNIOVINE 



o 



** 



H ilJL I ± 



PROGRAM 

PIC CHIPS DIRECTLY 

USING BASIC 



f**t 



PIC Microcontroller 
Project Book 



This page intentionally left blank. 



PIC Microcontroller 

Project Book 



John lovine 



McGraw-Hill 

New York San Francisco Washington, D.C. Auckland Bogota 

Caracas Lisbon London Madrid Mexico City Milan 

Montreal New Delhi San Juan Singapore 

Sydney Tokyo Toronto 



McGrmv-Hill 

A fhuiaofl of flwA'IcGrnir HtU (. sriiptnws 

Copyright © 2000 by 71k McGraw-l It'll Companies. All lights reserved. Muaufaetum] iit the United States iirAuwrkiL Except m- per- 
rolUrtl under the Untied States Copynghr. Act of 1076, no part of Ihas publx/ulti irt may he ttpnkUleed ** distributed in any ttnttt Of by 

I ■ I :.! »■-. ■ ! - •« <.-.' II ' i ■: ! . ■= ill.' lk". I -■■ -Li I ■'■ !'!.-. ". I ,1. | I ■ I V.Ilil..:! |'i.l |k%i:i|| \ L, j 'i hi I ,! 

O-UM30544-X 

The muci Ltd ui this e.B*>ek also appeal's in the prim *ersio« of this title. 0-07-13547^-4.. 



All tfafemria ■» tratemwfc* af tftdr respective on j*t* Ralia dan pm i fttteimik syrnbui nfter every (wtwrmje of a trade- 
matted name, we uat names in an editorial fashion only, and to the btjiotli uf the tradtmirk owner, with no iruetntioti of lnftifl*c- 
nwnl of Itie UudeRBirlt Where suth devignaiiiifis upfteir in Ihrs. bunk. tliev ha.*e heer* pnnled uriili initial cup*- 

MuGf aw-tliD cBookfe arc Bttiiljb-k- ai special tjiiamny dhrtHinli to use as premium*, and sales pronsulkrita. ttf for use Lis Mrrporaic 
[nuniilg pnigfuin*. Pot more ifttufinaJiun, please confcacl CJt'Ofje Hnaiv, Special Sale*. 3t ^dlgi?_hctitttf Afe^awJtill.t-uB! Or p J 1 J ■ 
904-40*9. 

TERMS OF USE 

Thifr iM tOpVn^hre J wtwk and Hit Mctinrtv-liilt t'urrtfKinieSL, IrH'- ("Metinm -Hill""! ;uul vt% |iee.niOiS; reverse :iJl fight* in and hi flie 
work. Use of this wuifc i* uibjeci tu these terms. Ewl-j'1 us permitted under the. Copyright Act of 1976 and the right to Mure and 
retrieve ■one iwipy id ihe work, yuu may pnf ileennipile, disiitseiiifrle, ie verse engmeer, reproduce, nuidify, eivaie derivative wnrks 
baaed UfXMK irananik, diauibiite. disseimnajie, sell publish «r suMkcDM: d*- *-urk m am pun uf it witlsuuL McGraw-Hill"* piiur eon- 
*£f1l. You niav use the *siri f»r yi*ir Own lUtiPUlVH£t£ii} and pemipid liw^ my i>lher use nf the work u ilnv|l r S [Ti.ihihilcMJ. Yoiit 
ul-Iil k> use the u.i,sfk jiuv Ik unnia^ieJ if you c'^iJ tu ei.iti3pL> ^ith cIksc fesfQb. 

THE WORK IS P|t(JVII>HJ M AS IS'. MeaHAW-HEU. AND 1 1 S I H ti^SOKS MAKh N( KifAKAMh.h.S Ok WAKKANTIUS 

.« TO THE ACCURACY. ADEQUACY OR COMPLETENESS OF OR RESULTS TO BE OBTAINED FROM USING TOE 
WORK, CNCLflHNJC; AMY INf-ORXlATKJN "I MAI ('AN BH A(X1iSSED tiakOtlCill TKH WORK VIA IIYFKKLtNK CH4 
OTHERWISE. AND EXPRESSLY DISCLAIM ANY WARRANTY, EXPRESS OR INtFLIED. INCLUDING BUT NOT LIMITED 
TU 1MPI 1P.D WARKAMIKS OF MhHCHAMAIilllTV OK flTNIvSS V\)U A PARTICUI^R PVWmV, MrfiraW-Hill uihl iK 
lkcflsuiTt do nut wuai jjii uf i*uitriinjlec LhdC ibe fuiKtioiu eontaiued La the wurk will meet ytws rtquircHKrats- «■ tfuit irs operation will 
he uninierrufiitfU: "r emv free. Neiilir-T M»tlr;i-rt-l|ill nnr >iv iuvn^iirs ^hull In? Uithle o> vu« m- iutjtaij? else ftir wnj- inw»rimc>, crnu 
c« -aiubijiiaii. n^udHeuof aai&Q, ui the woik of for any djjn jets jeatdiiny UicrcfiMiL NKGraw-IlilL haa in> ii:s(.xmsibLljE% i«n the con- 
i,eni 4"-r any inPunnirtiun aetess«J thmogli the wnck tTnifcr qr>arv'inii%i:tmv^ sh;i!J Mvfinm-rfi'll inuVor iK EicenHm. Ix 1 liiihJe Uw anj. 
.i.li:,lI. hklJjli^J. >]feead, piutisive. eutisequentijl or limiLdj darnkipes dia.; i>:.-di frots the use of or iDabJIrty la use the work, even 

if any i if them has been advised ul die jv^^ihilHy ol'sudi damages. Thi-. NmiUlH^l of Eiahtl ity sJiull apply ui an> clui > niSC vhiit- 

f«ver whether wch cMm or caaid nrbsea in eoruruei. lurt or ocfadiwij«e. 

DOl: JfJ.Lt].WHMif7L.l«J4K 



Contents 



Preface xl 

Chapter 1 Microcontroller 1 

What Is a Microcontroller 1 

Why Use a Microcontroller 1 

The Future of Elecronics Is Here — it's Microcontrollers 1 

Designer Computers 2 

The PIC Chip 2 

Better than Any Stamp 2 

PIC Programming Overview 4 

Ready. Steady, Go 8 

Parts List 8 

Chapter 2 Software Installation (Compiler and Programmer) 11 

Installing the PIC Basic Compiler Software 11 

Installing the EPIC Software 14 

PIC Applications Directory 15 

Path — The Final DOS Commands 1 6 

First Basic Program 18 

Programming the PIC Chip 22 

Troubleshooting EPIC Software: A Few Alternatives 24 

Testing the PIC Microcontroller 28 

The Sol defies s Breadboard 28 

Three Schematics, One Circuit 30 

Wink 32 

Troubleshooting the Circuit 33 

Chapter Review 33 

Parts List 34 

Chapter 3 PIC 16F84 Microcontroller 35 

Harvard Architecture and Memory-Mapped I/O 35 

Binary Fundamentals 38 

Registers and Ports 37 

Accessing the Ports for Output 41 

Electrical Binary, TTL t and CMOS 41 

Counting Program 42 



Copyright 2000 The McGraw-Hill Companies;, Inc. Click Here for Terms of Use, 



vi Contents 



Counting Binary Progression 45 

Basic High and Low Commands 46 

Programming Review 47 

Reading Input Signals 49 

Chapter 4 Reading I/O Lines 51 

The Sutton Command 51 

Dynamic Changes 5 5 

Program 4.2 Features 57 

The Variables Used In Button 58 

Multiple Statements — Single Line 59 

Peek 59 

New Features 61 

Basic Input and Output Commands 62 



ZIF Adapter Sockets 

ZIF Socket 

AC Adapter 64 

Parts List 64 

Chapter 5 PIC Basic Language Reference 65 



Branch 

Button 66 

Call 67 

Eeprom 67 

End 67 

For.,Next 66 

Gosub 60 

Gosub nesting 66 

Goto 69 

High 69 



!2cin 

!2oout 70 

CT.Then 70 

Input 71 

Let 72 

Lookdown 73 

Lookup 73 

Low 74 

Nap 74 

Output 75 

Pause 75 

Peek 75 

Poke 76 

Pot 76 

Pulsln 77 

Pulsout 77 

Pwm 76 

Random 76 

Read 79 

Return 79 

Reverse 79 

Serin 79 

Serout 51 

Sleep 62 



Contents vli 

Sound 83 

Toggle 83 

Write 84 

Chapter 6 Characteristics of the 16F84 Microcontroller 85 

Current Maximums for I/O Port{s) 85 

Clock Oscillators 85 

Reset 87 

PIC Harvard Architecture 90 

Register Map 91 

Chapter 7 Speech Synthesizer 93 

Speech Chip S3 

A Little on Linguistics 94 

Interfacing to the SPO-256 97 

Mode Select 93 

The Circuit 98 

The Program 100 

Prog ram Feat u res 1 00 

Parts List 102 

Chapter 8 Serial Communication and Creating I/O Lines 103 

Creating New I/O Ports 103 

Serial Communication 103 

Output First 104 

Basic Serial 104 

Clear Pin 106 

The Programs 106 

Bit Shift Correcting 109 

Programming Challenge (Simple) 111 

Programming Challenge (Not Simple) 111 

Input I/O 111 

Parts List 115 

Chapter 9 LCD Alphanumeric Display 117 

Error Detection Algorithms 118 

Parity 119 

Serial Formats 119 

Positioning the Cursor 1 20 

Off-Screen Memory 1 21 

Parts List 122 

Chapter 10 Sensors: Resistive, Neural, and Fuzzy Logic 125 

Reading Resistive Sensors 125 

R/C Values 12S 

Scale 1 26 

Pin Exceptions 1 26 

Resistive Sensors 126 

Test Program 1 27 

Fuzzy Logic and Neural Sensors 128 



vlKi Contents 



Fuzzy Logic Lig ht Tracker 1 31 

Program 10.2 134 

Fuzzy Output 137 

Program 10.3 139 

Parts List 141 

Chapter 11 DC Motor Control 143 

The Transistor 143 

First Method 143 

Bidirectional Method 144 

Diodes 146 

Parts List 147 

Chapter 12 Stepper Motor Control 149 

Stepper Motor Construction and Operation 149 

Real-World Motors 153 

First Stepper Circuit 1 S3 

Second Basic Program 157 

Half Stepping 158 

The tl Delay Variable 160 

Troubleshooting 161 

UCN 5804 Dedicated Stepper Motor ICs 1 61 

Parts List 165 

Chapter 13 Servomotor Control 167 

Extending Servomotor Range 169 

Manual Servo Control 171 

M ul tl pie Servomotors 1 72 

Timing and Servomotors 173 

Parts List 173 

Chapter 14 Analog-to-Digital (A/D) Converters 175 

Analog Signal 175 

Digital Equivalents 175 

A/D Converters 176 

Setting the Reference Voltage 1 77 

Voltage Range and Resolution 177 

Interpreting the Results 1 76 

Serial Chip Control 176 

Serial Chip Sequence 176 

Toxic Gas Sensor 179 

Parts List 160 

Chapter 15 Controlling AC Appliances 183 

Inductive and Resistive Loads 163 

CI rcult Construct! on 1 64 

Test Circuit 167 

Smart Control 166 



Contents ix 

Electronic Noses 188 

Parts List 188 

Appendix A 1 91 

Hexadecimal Numbers 1 91 

Program Answers 1 92 

Suppliers Index 1 95 

Index 197 



This page intentionally left blank. 



Preface 



I know you are interested in programming and using PIC microcontrollers* If 
not, you would not have picked up this book and be reading this preface. The 
first question one usually asks when choosing one book over another is, 
"Which book oilers me something more?'* Since everyone is looking for some- 
thing a little different in a book, I can*t address anything specific, but to help 
you make your decision I can state what I feel are the highlights of this book. 



Programming 



The PIC Basic compiler used throughout this book allows ease of using Basic 
language coupled with the sj>eed of assembly language. Basic is a user-friendly 
language, it is easier to learn and master than either assembly or C language. 
When the basic code is compiled to its assembly language equivalents, it is 20 
to 100 times faster than standard Basic code, effectively countering the speed 
advantages C or assembly languages typically offer. The compiled Basic code 
(assembly language equivalent) is programmed into the PIC microcontroller. 
As stated, this methodology increases the code execution 20 to 100 times faster 
than the equivalent interpreted Basic code that is used in other microcontroller 
systems like the Basic Stamp™. 

Cost Savings 

Being able to program PIC microcontroller chips directly reduces the overall 
cost of implementing microcontroller control to a fraction of the cost of other 
systems. In addition, circuit complexity is also minimized. 

Starting at the Beginning 

In terms of programming, this book starts at the ground level. Beginning with 
installing the needed softrware onto your computer's hard drive and proceed- 
ing on from there. We begin with a simple project that blinks two LEDs on and 
off and build more interesting and sophisticated projects out from there. 



Copyright 2000 The McGraw-Hill Companies, Inc. Click Here for Terms of Use. 



This page intentionally left blank. 



PIC Microcontroller 
Project Book 



This page intentionally left blank. 



Chapter 




Microcontroller 



What Is a Microcontroller? 



A microcontroller is an inexpensive single-chip computer. Single-chip com- 
puter means that the entire computer system lies within the confines of the 
integrated circuit chip. The microcontroller on the encapsulated sliver of sil- 
icon has features similar to those of our standard personal computer. 
Primarily, the microcontroller is capable of storing and running a program 
(its most important feature). The microcontroller contains a CPU (central 
processing unit), RAM (random-access memory), ROM (read-only memory), 
I/O (input/output) lines, serial and parallel ports, timers, and sometimes 
other built-in peripherals such as A/D (analog-to-digital) and D/A (digital-to- 
analog) converters. 

Why Use a Microcontroller? 

Microcontrollers > as stated , are inexpensive computers. The microcontroller's 
ability to store and run unique programs makes it extremely versatile. For 
instance, one can program a microcontroller to make decisions (perform 
functions) based on predetermined situations (I/O-line logic) and selections. 
The microcontroller's ability to perform math and logic functions allows it to 
mimic sophisticated logic and electronic circuits. 

Other programs can make the microcontroller behave like a neural circuit 
and/or a fuzzy-logic controller. Microcontrollers are responsible for the "intel- 
ligence" in most smart devices on the consumer market. 

The Future of Electronics Is Here — It's Microcontrollers 

Look in any hobbyist electronics magazine from this country or any other. You 
will see articles that feature the use of microcontrollers, either directly or 



Copyright 2000 The McGraw-Hill Companies^ Inc. Click Here for Terms of Use, 



2 Chapter One 



embedded in the circuit's design. Because of their versatility, microcontrollers 

add a lot of power, control, and options at little coat. It therefore becomes 
essential that the electronics engineer or hobbyist learn to program these 
microcontrollers to maintain a level of competence and to gain the advantages 
microcontrollers provide in his or her own circuit designs. 

If you examine consumer electronics, you will find microcontrollers embed- 
ded in just about everything. This is another reason to become familiar with 
mi c roc on t rollers. 



Designer Computers 



There is a large variety of microcontrollers on the market today. We will focus 
on a few versatile microcontroller chips called PIC chips (or PICMicro chips) 
from Microchip Technology. 



The PIC Chip 



Microchip Technology's series of microcontrollers is called PIC chips. Microchip 
secured a trademark for the name PIC, Microchip uses PIC to describe its 
series of PIC microcontrollers. PIC is generally assumed to mean programma- 
ble interface controller 



Better Than Any Stamp 



Parallax Company sells an easy-to-use series of microcontroller circuits 
called the Basic Stamp, Parallax's Basic Stamps (BS1 and BS2) use 
Microchip Technology's PIC microcontrollers. What makes the Stamps so 
popular and easy to use is that they are programmed using a simplified 
form of the Basic language. Basic-language programming is easy to learn 
and use. This was the Stamps* main advantage over other microcontroller 
systems, which have a much longer learning curve because they force their 
users and developers to learn a niche assembly language, (A niche assem- 
bly language is one that is specific to that company's microcontroller and 
no one else's.) 

The Basic Stamp has become one of the most popular microcontrollers in use 
today. Again, the Basic Stamp s popularity (this bears repeating) is due to its 
easy-to-learn and easy-to-use Basic-language programming. The PIC ? s Basic- 
language system is just as easy to learn and use, and the PIC has enormous 
benefits that make it better than any Stamp, 

The Basic language of the PICBasic compiler that we will use to program 
the PIC chips is similar to that used in the Basic Stamp series. Programming 
PIC chips directly has just become as easy as programming Stamps, Now you 
can enjoy the same easy language the Basic Stamp offers, plus two more very 
important benefits. 



Microcontroller 3 

Belief it one: faster speed 

Our programmed PIC chips will run their program much faster. If we enter 
the identical Basic program into a Basic Stamp and into a PIC chip, the pro- 
grammed PIC chip will run 20 to 100 times faster (depending upon the 

instructions used) than the Basic Stamp. Here's why. 

The BS1 and BS2 Basic Stamp systems use a serial EEPROM memory con- 
nected to the PIC chip to store their programs. The basic commands in the pro- 
gram are stored as basic tokens. Basic tokens are like a shorthand for basic 
commands. When running the program, the Basic Stamp reads each instruc- 
tion (token and data /address) over the serial line from the external EEPROM 
memory, interprets the token (converts token to the ML equivalent the PIC 
can understand), performs the instruction, reads the next instruction, and so 
on. Each and every instruction goes through these serial load, read, interpret, 
then perform steps as the program runs. The serial interface reading routine 
eats up gobs of the microcontroller's CPU time. 

In contrast to this operation, when a PIC chip is programmed using the 
Basic compiler, the Basic program is first converted to a PIC machine- 
language (hex file) program. The ML program is then uploaded into the PIC 
chip. Being the native language of the PIC, this machine-language (ML) code 
does not need to be stored as tokens and interpreted as it runs because the pro- 
gram is written in the PIC chip's native language. 

When the PIC chip runs the program, it reads the ML program instructions 
directly from its on-board memory and performs the instruction. There is no 
serial interface to an external EEPROM to eat up CPU time. The ML instruc- 
tions are read in parallel, not bit by bit as in the serial interface. The ML 
instructions read directly without any basic-token-to-ML-equivalent conver- 
sion required. This enables programmed PIC chips to run their code 20 to 100 
times faster than the same Basic program code in a Basic Stamp, 

Benefit two: much Tower cost 

The next factor is cost. Using PIC chips directly will save you 75 percent of 
the cost of a comparable Basic Stamp, The retail price for the BS1, which has 
256 bytes of programmable memory, is $34,95. The retail price for the BS2, 
which has 2K of programmable memory, is $49.95. The 16F84 PIC microcon- 
troller featured throughout this book is more closely comparable to the BS2 
Stamp. The 16F84 PIC chip we are using has IK of programmable memory. 

The retail cost of the 16F84 PIC chip is $6.95. To this, add the cost of a tim- 
ing crystal, a few capacitors, a few resistors, and a 7805 voltage regulator to 
make a circuit equivalent to that of the Stamp. These components increase the 
total cost to about S10.00 — still well below one-quarter the cost (75 percent 
savings) currently quoted for the BS2. 

And this $10.00 cost for the PIC may be cut substantially in some situa- 
tions. The PIC 16F84 is an expensive microcontroller with rewritable (flash) 



4 Chapter One 

memory. If, for instance, you design a circuit (or product) for manufacture 
that doesn't need to be reprogramnied after it is initially programmed, you 
can use a one-time programmable (OTP) PIC microcontroller and save about 

$2,00 to $3.00 on the PIC microcontroller as compared to the cost of a PIC 
microcontroller with flash (rewritable memory). 
In any case, anyone who uses more than a few Stamps a year will find it well 

worth the investment to completely scrap the Basic Stamp system and jump 
onto this faster and cheaper microcontroller bandwagon. 

If you are an experimenter, developer, or manufacturer or plan to become one, 
the cost savings are too substantial to consider investing in any other system, 

Extra bonus advantage 

The footprint of the 16F84 PIC microcontroller chip embedded in another cir- 
cuit is smaller than the equivalent BS2 Stamp because the Stamps use an 
external serial EEPROM for memory While the BS2 may, at first glance, look 
smaller since it is contained in a 28 -pin DIP package, it is not. You can also 
purchase the 16F84 in surface-mount form and the resulting circuit will have 
a smaller footprint 

PIC Programming Overview 

Programming PIC microcontrollers is a simple three-step process. There's an 
old saying that there's more than one way to skin a cat, and the same can be 
said about programming PIC microcontrollers. When you look at the market, 
you will discover a variety of programmers and compilers for PIC microcon- 
trollers. We will not do a comparison of the products on the market. Instead, 
we will focus on what we have found to be an easy-to-learn and very power- 
ful Basic-language compiler and its associated programmer board. 

Remember, this is an overview. Exact step-by-step instructions are given in 
the next chapter, when we program a PIC with our first test program. 



What to buy 



You need to purchase at least three items to start programming and building 
projects: the PIC Basic compiler program, the EPIC programmer (a program- 
ming carrier board), and the PIC chip itself. I recommend beginning with the 
16F84 PIC microcontroller because it has exactly IK x 14 of rewritable mem- 
ory. This memory allows you to reuse the PIC chip many times to test and 
debug your programs. 

The PICBasic compiler (see Fig. LI) runs on a standard PC, The program may 
be run in DOS or in an "MS-DOS prompt" window in the Windows environment 
From here on out, the MS-DOS prompt window will be referred to simply as a 
DOS window. The DOS program will run on everything from an XT-class PC run- 
ning DOS 3.3 and higher. The program supports a large variety of PIC micro- 
controllers. The compiler generates ML hex code that may be used with other 
programming carrier boards. The cost for PICBasic compiler software is $99.95. 



Microcontroller 5 




Figure 1.1 PICBasic compiler program and manual. 



There is a more expensive compiler called the PICBasic Pro that retails for 
$249.95. Do not purchase this compiler! The PICBasic Pro handles the Peek 
and Poke commands differently than the standard PICBasic Compiler. So 
remember to purchase the standard PICBasic Compiler for $99.95, 

The EPIC programming carrier board (see Fig, 12) has a socket for inserting 
the PIC chip and connecting it to the computer,, via the printer port, for pro- 
gramming. The programming board connects to the computer's printer port 
(parallel port) using a DB25 cable. If the computer has only one printer port and 
there is a printer connected to it, the printer must be temporarily disconnected 
when PIC chips are being programmed. Like the PICBasic compiler, the EPIC 
programming carrier board supports a wide variety of PIC microcontrollers. The 
cost for the EPIC programming board with EPIC programming diskette is 
$59.00, Those who wish to build their own board may purchase a bare PC board 
with program diskette for $34.95, 

The PIC 16F84 pinout is shown in Fig, 1,3, It is a versatile microcontroller 
with flash memory. Flash memory is a term used to describe this type of 



6 Chapter One 




Figure 1,2 EPIC programming carrier board and software. 



rewritable memory. The on-board flash memory can endure a minimum of 
1000 erase/ write cycles > so you can reprogram and reuse the PIC chip at least 
1000 times. The program retention time, between erase/write cycles, is 
approximately 40 years. The 18-pin chip devotes 13 pins to I/O. Each pin may 
be programmed individually for input or output. The pin status (I/O direction 
control) may be changed on the fly via programming. Other features include 
power on resets power-saving sleep mode, power-up timer, and code protection, 



Microcontroller 7 



i 

S 

7 



L_ 



-'.. 



RA2 



RA3 



RAifflDCKI 



MCLR 

RBWINT 
RBI 

R.BZ 

RBI 



RA1 
RAG 

OSC1/CLKFN 

DSCZTCLKOUT 

RB7 

RBfc 

RB4 



IS 

16 

14 
13 
13 

11 

10 



Features 



GENERAL 

ftlSC CF U 35 sin g le ward instruction s 

Operating Speed DC-IQHHz Clonic Input 

IK Prognm Mt^nuty 

14-Bft Yiide instructions 

*-Blt wltfc da^ p&th 

Direct, indirect and relptlvt ^rtHrpssing 

1-DOO erase/write cycles 

PERIPHERAL 

13 UOfJllit Willi iiidividuaJ di red ion eontr-oi 
HighCurrentgjnk/ scarce lor direct LED Jriw 

- 25rmfli sinkmax. p&r |>in 

- 2o ruft source n\zx per pin 
"FflRO; 5-bit tiniErJ"coiinrtef witfi B-blt 
programmable pre^raler 



Figure 1,3 PIC 16FS4 pinout. 



among others- Additional Features and architecture details of the PIC 16F84 
will be given as we continue. 



Step 1: Writing the Basic-language program 

PlCBasic programs are written using a word processor. Any word processor 
that is able to save its text file as ASCII or DOS text may be used. Just about 
every commercial word processor available has this option. Use the Save as 
command and choose MS-DOS text, DOS text, or ASCII text. The text file you 
write with the word processor will be compiled into a program. If you don't own 
a word processor, you can use Windows Notepad, which is included with 
Windows 3.X and Windows 95/98, to write the Basic-language source file. (In 
Windows, look under Accessories .) At the DOS level, you can use the Edit pro- 
gram to write text files. 

The compiler needs the basic program saved ay a standard (MS-DOS) or 
ASCII test file because any special formatting and print codes that are 
unique to an individual word processor are not saved in the ASCII or DOS 
file types. 

When you save the file, save it with a . bas suffix. For example , if you were 
saving a program named wink, you would save it as wink . bas. Saving the file 
with a . bas suffix is an option. The compiler will read the file with or without 
the .bas suffix. The .bas suffix will help you identify your PIC programs in 
a crowded directory. 



8 Chapter One 

Step 2: Using the compiler 

The PICBasie compiler program is started by entering the command Pbc fol- 
lowed by the name of the text file. For example, if the text file we created is 
named wink . has then at the DOS command prompt, we would enter 

Pbc wink.bas 

The Basic compiler compiles the text file into two additional files, a .asm 
(assembly language) file and a .hex (hexadecimal) file- 

The wink. asm file is the assembly language equivalent of the Basic pro- 
gram. The wink , hex file is the machine code of the program written in hexa- 
decimal numbers. It is the , hex file that is loaded into the PIC chip. 

If the compiler encounters errors when compiling the Basic source code, it will 
issue a string of errors it has found and terminate. The errors listed need to be 
corrected in the Basic source code before the program will successfully compile. 

Step 3: Programming the PIC chip 

Connect the EPIC programmer to the computer's printer port using a DB25 
cable. Start the DOS programming software. At a DOS command prompt, enter 

EPIC 

Figure 1.4 is a picture of the programming screen. Use the Open File option 
and select wink .hex from the files displayed in the dialog box. The file will 
load , and numbers will be displayed in the window on the left.. Insert the 
16F84 into the socket, then press the Program button. The PIC microcon- 
troller is programmed and ready to go to work. 

Ready, Steady, Go 

This completes the overview. In Chap, 2 we will provide step -by-step instruc- 
tions for writing the Basic text file and programming it into the PIC chip. You 
will find that, the actual steps shown in Chap, 2 are not much more involved 
than the instructions in the overview. Purchase the components and let's go. 



Parts List 



PICBasie compiler $ 99.95 

EPIC programme r $ 59 .00 

16F84 Microcontroller $ 6.95 

DB25 6-ft cable $ 6.95 

(l)4.0-MHz crystal $2,50 

(2) 22-pF capacitors $0-10 each 

Available from Images Company (see Suppliers Index)* 



MSMISPmwwi fPlt 



Microcontroller 9 



HI 



1 *s 3 let EH ylg a< 

f: 




u rile 



tog t ait 



ead P"C 



erify 






la^T 



case 



B Lt 




Figure 1,4 Screen shot of EPIC programming software (DOS). The program, loaded is wink, hex 



(1) Solder! ess breadboard 
(1) 0.1-jjlF capacitor 

(8) Red LEDs 
(8) 470-11 resistors* 
(1) 4.7-kil resistor 
(8) 10-kfl resistors 

(1) 7805 voltage regulator 

(2) Four-position PC-mounted switches 
(U9-V battery clip 



RadioS hack 
RadioS hack 
RadioShack 
RadioS hack 
RadioShack 
RadioShack 
RadioShack 
RadioShack 
RadioShack 



PN#276-175 

PN#272-1QG9 

PN#2 76-208 

PN#270-1115 

FN#271-1124 

PN#271-1126 

PN#276-1770 

PN#275-1301 

PN#2 70-325 



Available at local RadioShack a tores. Also available from James Electronics 
and JDR Micro Devices (see Suppliers Index), 



'Also available in the 16-pin DIP package. 



This page intentionally left blank. 



Chapter 




Software Installation 
(Compiler and Programmer) 



In this chapter, we provide step-by-step instructions for writing a text file for 
and programming a PIG microcontroller. We begin by loading the PICBasic 
compiler software onto your computer's hard drive and finish by programming 
and testing a PIC microcontroller chip. 

Installing the PICBasic Compiler Software 

The first thing we need to do is copy the PICBasic compiler software onto your 
computer's hard drive. If you are familiar with File Manager (Windows 3-X) or 
Windows Explorer, you can create subdirectories and copy all files with these 
tools. Step-by- step instructions are provided using DOS commands. You can, 
of course, use the same directory names outlined or make up your own. 

The DOS instructions are provided to help the reader and to serve as a 
supplement to the installation directions provided with the software pack- 
ages. The instructions are not meant as a DOS tutorial, More information on 
DOS commands can be found in any number of DOS manuals. Here is a list 
of DOS commands we will be using and what action they perform: 



COMMAND 


ACTION 


cd 


change directory 


md 


make directory 


copy 


copy files 


xcopy 


copy Files and subdirectories 


path 


sets a search path for executable files 


dir 


directory 



Before we can copy the files from our installation diskettes, we need a place 
to copy them to. For the PICBasic compiler we will create a subdirectory called 
pictools on the hard drive and copy the files on the diskette into it. 

11 
Copyright 2000 The McGraw-Hill Companies, Inc. Click Here for Terms of Use, 



12 Chapter Two 



For Windows 3.X, us& the File Manager program to create a subdirectory, 
For Windows 95/98, use the Windows Explorer program to create the subdi- 
rectory. Windows 95/98 users also have the option of opening a DOS window 
within the Windows environment. You can work inside the DOS windows 
using standard DOS commands. 

You also have the option of restarting your computer in MS-DOS mode. In 
most cases you should be able to operate from the DOS window without 
problems- 
Start the DOS window by selecting "MS-DOS Prompt" under the Programs 
menu under the Windows 95/98 "Start* button (see Fig 2.1). When the DOS 
window opens, you are probably starting the DOS session inside the Windows 
subdirectory. Your prompt may look like this: C^ /WINDOWS >. 
The DOS prompt provides vital information. The C: tells us we are on the C 
drive- The /WINDOWS tells us we are in the Windows subdirectory. 

We want to work from the root directory of the computer's hard drive (usu- 
ally the C drive). We accomplish this by using the cd (Change Directory) 
command. 

The cd. , command brings one up a single level in the directory hierarchy- 
Using the cd\ brings one up to the root directory regardless of how deep (how 
many levels) one has moved into subdirectories. The root directory is the top 
of the directory hierarchy. From the Windows subdirectory either command 







3& 



Fleh-ert- 








HJ iswms 



fori 



LtJ Bfttfinekini 
fi)Cir«i 

@| Can) Qiaphci 

HF. PU^ 1 1 <il K 

LwJ IXAD TULLE lUtVAl 

Gg Men»dlV«udBJ«&&ir 
Ug$ Nairn AfiWfM 



J*] Ptm 

jrj Pkifi^ijerK 
£j) QuckljM 

£j Si**j[*lDrWh|fcirK?fl 
■gg 5wpiv 

ijgj SJatUp 
Q VrinCirifc 

C] tFWQH 



'\ US-BOSS*** 



Jlj bfadtaa Emp*p« 



— — ' r 

Figure 2-1 Selecting "MS-DOS Prompt" fTorn Program men 11 




iffifW 



Software Installation (Compiler and Programmer) 13 

may be used. Type cd^or cd\ and hit the Enter key to back up a level in the 
directory. 

C:/WINDOWS>cd. . or C:/WINDOWS>cd\ 

(See Fig, 2.2.) 

You should now be in the C drive root directory; the DOS prompt will change 
to C : />. Once you are in the C drive's root directory, you can start the task at 

hand- 

First, create a subdirectorv on vour hard drive called pictools. (If vou don't 
like the name pictools, choose another name that is more to your liking.) At the 
DOS prompt, enter the "make directory" command (md) followed by a space 
and the name of the directory pic tool a. The complete command may look 
like this: 

C:/> md pictools 

This command creates a subdirectory called pictools. Now let's copy all the 
tiles on the PICBaaic Compiler 3.5-in diskette into the new directory 
Assuming that your 3,5-in disk drive is the A drive, at the DOS prompt, enter 

C:/> xcopy a..*.* pictools /s 

This command copies all the files on the diskette, including the subdirec- 
tories, into the pictools subdirectory (see Fig. 2.2)- With the {ilea safely 



^ 3 H| ■ [ft! fcB| ffp? Aj 



(O copyright Microsoft ceep 1991-1995 

c:\MRd pictools 

C ; V ^xcopy a : * - * pi ctoola /s 

PS-CSKE 
PM . EXE 

RSftD .ME 

rMC\BlZC671.EHC 
rHC\Bl2CS72.EHC 
I1IC\B140(10.INC 



Figure 2,1 Using cd i" change directory J and md f make directory) DOS commands at the DOS 
prompt. 



14 Chapter Two 



loaded onto your hard drive, remove the diskette and store it in a safe place 
in case it is needed in the future. 



Installing the EPIC Software 



We are still in the root directory for the C drive. From here, create another 

subdirectory on your hard drive called epic, (If you don't like the name epic, 
choose another name that is more to your liking.) At the DOS prompt, enter 

Ci/> md epic 

This creates another subdirectory called epic (Fig 2.3). Now let's copy all the 
files on the 3.5-in EPIC diskette into the new epic directory, as we have done 
for the compiler software. Again assuming that your 3.5-in disk drive is the A 
drive, at the DOS prompt, enter 

C:/> xcopy a:*.* epic /s 

This command copies all the files on the EPIC diskette, including the sub- 
directories, into the epic subdirectory as shown in Fig. 2.3. With the files safe- 
ly loaded onto your hard drive „ remove the diskette and store it in a safe place 
in case it is needed in the future. 

As you can see in the last figure , only two files were copied from the A drive 
into the epic directory. The reason is that the EPIC software is compressed in 



hs nns Plum* 



r~^ 3 m - i i 



JM* 



19 A 



C:\>md epic 



b:V>xc&py «:*.* GpLe/a 

|EPiCit3 .e>:e 

2 FtU{5> copied 

\C:\> 




Figure 2.3 Creating epic directory and copy files into it. 



Software Installation (Compiler and Programmer) 15 

the executable file epic203>exe* Tb run this program and decompress the files 
first move into the epic subdirectory by typing in 

C:\ cd epic 

at the DOS prompt and hitting the Enter key (see Fig. 2-4), The DOS prompt 
will change to C:\epio. To run the program type in "epic203* at the DOS 
prompt, hit the Enter key (see Fig. 2,5). When I executed the program, it 
issued a warning (see the bottom of Fig. 2.5) that a readme.txt file already 
exists. Overwrite (y/n)? Answer y 



PIC Applications Directory 



It would be a good idea if we created another subdirectory to store all our 
PICMicro application programs. This will keep all our pictools and epic direc- 
tories clean, neat, and uncluttered. If you are performing these commands in 
the sequence they appear in the book you are currently in the epic subdirec- 
tory We need to move back to the root directory before we do anything more. 
Use the cd (.change directory) command to move back into the root directory 
enter cd. * 

C:\epio -cd. . 

At the DOS prompt, hit the Enter key (see Fig, 2.6). The DOS will change to 
C:\> signaling we are in the root directory. We are ready to create another 



wn niiH r'iL«iic 



H^x 




Figure 2.4 Running cpic2G3.exe program to decompress the EPIC files. 



1 6 Chapter Two 



pummh rpiaa 



r> I:" 



"3 !' 



tfJBT a] 



3H* 



l' : \ .'Cd epic 

PK£F>[ {R} FASTi Seic Extract Utility Version 2.049 02-01-93 
Qo&t, IW>-1W3 PKH&RB ItiGp All Rl-ahts Reserved, R^ffist^c^d version 

pksf>£ teg. u.s, Pat, and m. oil, 

searching EKE; C;/EFrc/EFrc£03,EKE 

inflating: BUILD. ixt 

inflating: DEMCM^ASM 

inflating i DEMG6 4 * HE-: 

inflating: EPICEXE 

inflating: e? EC .him 

Inflating: EPIC. INI 

inflating: EFEC.TXT 

Ext iract ing : E£ ICDIAG - GIF 

Inflating: EPTCWIN.EXE 

Extracting: ICSP.GIF 

Inflating : PICLPT9S .VXD 

I ii flat ing : PicLFTNT. 5 Y3 

infLAtlhgt PM.EXE 

Inflating: PM-Wr 

BKMX; <WL5> Wo ttiingt README -KT olrMdy exists- Oveswit* (Y/llJ 7 



Figure 2.5 EPIC File list inflating. Answer to overwrite Readme _txt is yes i y.i. 

subdirectory called applies. At the DOS prompt in the root directory type in md 
applies and hit the Enter key {see Fig. 2,7). 

Ci\>md applies 

If you don't like the name applies choose another name more to your liking- We 

are almost ready to write our first program. 



Path — The Final DOS Commands 



Path is a DOS command that specifies a search path for program files. For 
example, the following command specifies that DOS is to search for files in the 
three directories listed in addition to the current directory: 

pat h \ t c : \p i ctoo 1 s ; c : \ e p i c ; c • \ wi ndo wfl \ command ; 

Each directory in the path command must be separated by a semicolon (;), The 
first backslash (\) indicates that the search should begin in the root directory 
of the current drive. 

Using the above path command will allow you to run both the compiler 
(PEG) and the programmer (EPIC) from the applications directory (applies). 
This will streamline and simplify using both these programs. Without the path 
command you will have to copy files between directories and change directo- 
ries to run programs. 



-IIS DfiG Pilmhi! 



Software Installation (Compiler and Programmer) 17 



-sx 



r~*z~ -3 ni lal Kjl glff aj 




Figure 2.6 Moving back to the root directory u-uritf the ,:■! DOH command. 



r MS DOS Picwipr 



iy 



*= 3 nLiaJU^F AJ 




Figure 2.7 Creating applies directory and using the path DOS command. 



18 Chapter Two 



The path command may be typed in at the DOS prompt and once you hit the 
Enter key will stay in effect for as long as the DOS window remains open (see 
Fig. 2.7), 

C:\> path \ ; c: \piecools ;c : \epic;c :\windows\£omniand; 

For those who are familiar with DOS commands, the path command can be 
made permanent by entering it into or adding onto an existing path command 
in the autoexec.bat file. For those w r ho are not comfortable with DOS com- 
mands or changing the set-up of the computer, don't touch the autoexec.bat 
file- The autoexec.bat file is an important batch file that is run every time the 
computer starts or is reset. 

If you want to learn more about DOS and the autoexec.bat file to make these 
changes, I recommend purchasing a tutorial book on DOS, 



First Basic Program 



We are now ready to write our first program. Tb write programs, you n^d a 
word processor or text editor. Windows users can use the Notepad program, 
DOS-level users can use the Edit program. 

Since w r e want to store our programs in the subdirectory applies, the first 
step is to move into that directory We will use the cd (change directory) com- 
mand. Enter this at the DOS prompt (see Fig, 2.8). 



IS Fiuwul 



HU 




Figure £.6 Using the cd command and Edit program. 



Software Installation (Compiler and Programmer) 19 



C:\> cd applies 



Once in this directory the prompt changes to 

C: \applics> 

In this example I will be using the free Edit program package with Windows 
to write the program. Start edit by typing edit at the command prompt (see 
Fig- 2.8). 

c : \appl ics> edit 

This starts the edit program (see Fig. 2,9). Enter this program in your word 
processor exactly as it is written: 

"First Basic program to wink two LEDs connected to port B, 
Loop: High "Turn on LED connected to pin RBO 

Low 1 'Turn off LED connected to pin RBI 

Pause 500 "Delay for 0.5 s 

Low "Turn off LED connected to pin RED 

High 1 "Turn on LED connected to pin RBI 

Pause 500 "Delay for 0.5 s 

Goto loop "Go back to loop and blink and wink LEDs forever 

End 

See Fig. 2.10. Save the above as a text file in the applies directory. Use the Save 
function under the File menu, Name the file wink, has (Fig. 2.11). The .has suf- 
fix is optional. The compiler program will load and compile the file whether or 




Figure 2.9 Opening - screen of the Edit program. 



20 Chapter Two 



Compile 



not it has the .has suffix. The suffix helps us remember what type of file it is. If, 
by accident, you saved the file as wink-tat don't get discouraged. You can do a 
Save As from the Edit program (under File menu) and rename the file wilik.bfrS. 
Remember^ if you are using a different word processor, it is important to 
save the program as an ASCII or MS-DOS text file. The reason is that the com* 
piler (the next step) requires the text file (the basic source code) in a DOS or 
ASCII file format. DOS and ASCII text files do not save any special formatting 
and print codes that are unique to individual word processors. 



The PICBasic compiler must be run from DOS or from a DOS window within 
Windows, If you are still working in the same DOS session we started with, 
skip over the next two sentences. If you just started the DOS window, enter 
the path command as specified earlier. Use the cd commands to move into the 
applies directory 

We will run the PICBasic compiler from the applies directory, type the com- 
mand pbc -plfif 84 wink .has at the DOS prompt, and hit the Enter key (see 
Fig. 2.12)- 

c : ,/AP flics >pbe -pi6FS4 wink. has 

The compiler displays an initialization copyright message and begins process- 
ing the Basic source code (see Fig. 2-13). If the Basic source code is without 



i£ ft iMut t.to\ i 



ma 



iiJC 



3 



I"! 



UfeEj^F? a] 



File Edit seateti 



ptiDCL'J Hialp 



T Ftr« BAaic Program to virile two LED r a c&nh&cted to ®&£i B 



loop : High C 
Lov 1 
Pause SOB 
iov 
High 1 
Pause SOI 
Goto loop 
-: n 



'TUtfrt Git LED £oftn*et*& to pLti RBJ 

'Tustrt off LED ccwttfectesd to Pm R&l 

f D4lAy foe rS SfrCOnda 

r Tutti eft LED eonnwtfccl to P in R&Q 

'Turn on LED connected to PTH RBI 

r S«l«y for pS s&condg 

'Go back to loop and blink £ mnlc LEDs foc-evec- 




Figure 2.10 wink.bas progTam written using Edit. 



Software Installation (Compiler and Programmer) 21 



MS-DOS Pitfiirf ton 


^^^^-i»i* 






j **< J 1:1 |al el *|fli a 


Stlit s&arch Vi^w option ft Help 




Fl=Hci» 5Rteir=5x«e«itc Bse=Csttrei Tctb=fe£L fi^ld 



Figure £.1 1 Saving text file as wink.bas. 



4 PiCauit 



BEJ 




Figure 2.12 Running compiler on wink.bas file for the PIC 16F84. 



22 Chapter Two 



errors (and why shouldn't it be?), the compiler will create two additional files. 
If the compiler finds any errors, a list of errors with their line numbers will be 

displayed- Use the line numbers in the error message to locate the line num- 
ber(s) in the .has text file where the errorfs) occurred- The errors need to be 
corrected before the compiler can compile the source code correctly. The most 
common errors are with basic language syntax and usage. 

You can look at the files by using the dir directory command- Type dir at 
the command prompt: 

C:\APPLICS> dir 

and hit Enter (see Fig. 2/14). 

The dir command displays all the files and subdirectories within the sub- 
directory where it is issued. In Fig, 2,14 we can see the two additional files the 
compiler created. One file, the wink. asm file, is the assembler source code file 
that automatically initiates the macroassembler's compiling of the assembly 
code Lo machine-language hex code, The second file created is the hex code file, 
called wink. hex. 



Programming the PIC Chip 



To program the PIC chip, we must connect the EPIC programming carrier 
board (see Fig, 2,15) to the computer. The EPIC board connects to the printer 
port, also called the parallel port. (Either name may be used; they are both cor* 



MIi DOS Fiimist 




Figure 2,13 Compiler initialization messages and compiled program length in words. 



Software Installation (Compiler and Programmer) 23 



3 MS, 0(15 Pit*n>* 






HfjEa 




y 






1 fate J H] ft) 83| ff|W i 


CA applicable 








volume in aeive c Ma no ibmi 
Volume Secial NUabec is 103B-1CCE 1 
Directory of C:\appiics 






<DIR> 21-29-99 19:21a B 
<DIR> 11-29-99 10: 2 Is .. 
Elm ASM 429 U-2B-S9 10!31a WIWK^gM 
WINK HEX 669 11*28-99 10 :31a WIHK.HEX 
BINK SftS 423 11-28-99 10 :30a wink.ba^ 
3 file (a) 1,S2Q b^t^n 
2 die 4s) 241,795,012 bytu fr&e 




C:'\ applies^ 











Figure 2,14 Looking - at the two additional files (.hex and .asm) created using the DOS u dir 
command. 



rett,) A computer may contain up to four parallel {printer) porta. Each port is 
assigned a number from 1 through 4- The computer lists these ports as LPT1 
to LPT4. 

If your computer has only one printer port, disconnect the printer, if one is 
connected, and attach the EPIC programming board using a 6-ft DB25 cable- 
When connecting the programming board to the computer, make sure there 
are no PIC microcontrollers installed on the board. If you have an ac adapter 
for the EPIC programmer, plug it in. If not, attach two fresh 9-V batteries. 
Connect the Batt ON jumper to apply power. The programming board must be 
connected to the printer port with power applied to the programming board 
before starting the software. Otherwise, the software will not register the pro- 
gramming board as connected to the printer port and will give the error mes- 
sage "EPIC Programmer Not Connected." 

When power is applied and the programming board is connected to the 
printer port, the LED programming board on the EPIC programmer board 
may be on or off at this point. Do not insert a PIC microcontroller into the pro- 
gramming board socket until the EPIC programming software is running. 



The EPIC programming board software 

There are two versions of the EPIC software: EPICexe for DOS and 
EPICWIN.exe for Windows. The Windows software is 32-bit. It may be used 



24 Chapter Two 






wa7.w & p/tfflMf su/y 


oV 


EPIC™ 




FtogrjmtJtft 




■J10* V-1 fr *H HH» ■*-«* yw>| **• *~ 





JffA ** 

















Figure 2.15 EPIC programming carrier board. 



with Windows 95, Windows 98, and Windows NT, but not with Windows 3.X. 
It has been my experience that Windows 95 printer drivers often like to retain 
control of the printer (LPT1) port. If this is the case with your computer:, the 
Windows epic program may not function properly* and you may be forced to 
use the DOS-level program. If you receive the error message "EPIC 
Programmer Not Connected" when you start the Windows EPIC program, you 
have the option of either troubleshooting the problem (see Troubleshooting 
EPIC Software, below) or using the EPIC DOS program. 

Using the EPIC DOS version 

If you are using Windows 95 or higher, you tan open a DOS window or restart 
the computer in the DOS mode. If you are using Windows 3. XX, end the 
Windows session. 



Troubleshooting EPIC Software: A Few Alternatives 

If your computer has a single printer port (LFT1), you can add a second 
(LPT2) port for a nominal amount of money. An inexpensive printer card will 
cost about $20.00. If you have never added a card to your computer before, 
don't know the difference between an ISA or PCI, or never performed some 
type of system upgrade to your computer before, then I advise you to bring 
your computer to a computer repair/service store in your area and have them 
perform the upgrade. 



Software Installation (Compiler and Programmer) 25 

There is no guarantee that the EPIC software will work with a second LPT 
port. You may still have to work at the DOS level to get it to function properly. 

For instance, in order for me to run the EPIC DOS program from a DOS 
window in Windows 95 I needed to remove my HP (Hewlett-Packard) printer 
driver first (see Fig. 2.16). I opened the printer driver window and closed down 
(exited) the program. 



Continuing with the wink.bas program 



Assume we are still in the same DOS session and we have just run the PBC 
compiler on the wink.bas program. We are still in the applies directory At the 
DOS prompt, type epic and hit enter to run the DOS version of the EPIC soft- 
ware (see Fig. 2.17). 

IF you are operating out of a DOS window you may get a device conflict mes- 
sage box as shown in Fig. 2.18. We want MS-DOS to control the LPT port so 
the EPIC programming software will work. Select the MS-DOS Prompt and 
hit the OK button, 

EPIC's opening screen is shown in Fig. 2.19. Use the mouse to click on the 
Open button or press Alt-0 on your keyboard. Select the wink. hex file (see 
Fig. 2.20). When the hex file loads, you will see a list of numbers in the win- 
dow on the left (see Fig. 2.21). This is the machine code for your program. On 
the right-hand side of the screen are configuration switches that we need to 
check before we program the PIC chip. 



fflT 



:\ 1'iivuii 



mu 



ZJC 



3 d^ifc 



C : \appLics>di.r 



Di. tec tod 



. ii;:; : 1i J I- mil : :-. 




Mniirr.lrn 



If INK 
WINK 
DIMK 



i mj - ■' ■ ■ 

PiMtf SJSWi^ 




•■ijilimy 






t.ASM 



2 dirts) 



241,795,072 bytttB free 



C:\applic3.> 



Figure 2.16 Exiting printer driver progTam. 



26 Chapter Two 



^JC 



3 n]__|fcJM| tfp? a| 



- :\applic3>dir 

volume in drive c has no label 
IfoiUKe fecial Number is 103B-1CCF 

Directory of C:\appiics 



- 


<DIR> 




_ _ 


<DTR> 




IIEHK 


ASM 


I.T- 


QTNK 


HEX 


6S9 


KNK 


Bft3 

3 fil*49} 


423 




2 dit<sl 


241. 



11-26-99 10:21a 
11-28-99 10:2 la 
I.": 11-28-99 1(1:31* H1HKJUH 

669 11-28-99 lfl! 3 la WINK -HEX 
423 11-26-99 10:3fla irfinic.ba^ 
1,520 bvt« 
241 r 795 f D12 fryr^s irae 



C; \applic3>epic 



Figure 2,17 Running the EPIC program from MS-DOS Prompt window. 



MS EKJ5 l»ri««iL Fait 



r~^ 3 n\ \f&\ \&\ eflff a{ 




Figure 2.1 S Device Conflict window. 



Software Installation (Compiler and Programmer) 27 

Let's go through the configuration switches one by one. 

Device: Seta the device type. Set it for 8X, 

ROM Size (K): Sets the memory size, Choose 1. 

OSC: Sets the oscillator type. Choose XT for crystal. 

Watchdog Timer: Choose On, 

Code Protect: Choose Off. 

Power Up Timer Enable: Choose High. 

After the configuration switches are set, insert the PIC 16F84 microcontroller 
into the socket, Click on Program or press Alt-P on the keyboard to begin 
programming. The EPIC program first looks at the microcontroller chip to see 
if it is blank. If the chip is blank, the EPIC program installs your program into 
the microcontroller. If the microcontroller is not blank, you are given the 
options of cancelling the operation or overwriting the existing program with 
the new program. If there is an existing program in the PIC chip's memory, 
write over it. The machine-language code lines are highlighted as the PIC is 
programmed. When the operation is finished, the microcontroller is pro- 
grammed and ready to run. You can verify the program if you like by hitting 
(or highlighting} the Verify button. This initiates a comparison of the program 
held in memory with the program stored in the PIC microcontroller. 



is Pliant i I'll: 



r^ 3 n\ -lai Eg] £fs Aj 




Figure 2.1 9 EPIC program's opening screen. 



28 Chapter Two 



h Mi. in' rr'ir 



Azhi 




Figure 2,20 Selecting the wink. hex file. 



Testing the PIC Microcontroller 



If you purchased the components described in Chap, !„ you can quickly set up 
the test circuit- If not, you need to purchase those components now to continue. 



The Solderless Breadboard 



For those of us who have not dabbled in electronics very much, I want to 
describe the solderless breadboard (see Fig, 2,22), As the name implies, you 
can breadboard (assemble and connect) electronic components onto it without 
solder. The breadboard is reusable; you can change, modify, or remove circuit 
components on it at any time. This makes it easy to correct any wiring errors. 
The solderless breadboard is an important item for constructing and testing 
the circuits outlined in this book. 

If you wish to make any circuit permanent, you can transfer the components 
onto a standard printed- circuit board and solder them together with the fore- 
knowledge that the circuit functions properly. 

The internal structure of the board is shown in Fig, 2,23, The holes on the 
board are plugs. When a wire or pin is inserted into a hole, it makes intimate 
contact with the metal connector strip inside. The holes are properly spaced so 
that integrated circuits and many other components can be plugged right in. 



Software Installation (Compiler and Programmer) 2d 



"- fr«n*nit EPIC 



MM 



AjtC 



0008 
0010 

ooie 

0020 
0028 
0030 
003$ 
0040 
0048 
0050 

oose 

0060 
0060 



~3 I'm 



EPIC PROGRAMMER VEB 1-41 C AAFFLIC3\WIWK.HEX 



p Device 



OAB4 
1003 
0782 
3480 
3434 
3001 
3001 
2S3E 
2AFF 
0422 
28 4E 
23^ 



0000 
9BSC 
0004 

3907 
3435 
0OA3 
O0A3 
200C 
17*4 
1903 
16*3 
09A2 



DLSD 
2807 
0C84 
3 402 
01S-A 
3 436 
3 OF 4 
30F4 
3MT 

nsoo 

0009 
390? 

09*2 



3Q5F 

0CC4 
3404 
0782 
3437 
204C 
204C 
0530 
2fl67 
30 H 
38P8 
0JLA2 



C03C 
Z0Z1 
1A04 
3408 
3430 
3000 
3000 
2*2C 
2049 
O0A2 

0001 
1903 



3QQD 
0084 



3410 
3431 
2045 
2041 
203E 
200C 
2061 
1D03 
00 63 
0JUL3 



0094 
3907 

1204 
3420 
3432 
3001 
3001 
3007 
0400 
0064 
2954 
3QFF 
0009 



0130 
0394 
019 h 
3440 
3433 
2041 
2045 
205P 
2040 
0023 
2063 
0091 
1293 



ROM SiZfc (K) 



—•——— 



Or- 1-^ __ 



r Hatch clog Tiwei 




-007F 007F 007F O07F 



r powe? up Times Enal 



C:\fcPPlICS\wrNK.Kre 




ead EIC 



( c j g l a r. 



" 



airily 



bout 



■" ■r"-i»;»'"in' ■■?' 



lank? 



rn ■ ■■. ■» .■,■■ ■ 



ras e 



E it 



^■■■■11 ,« ,■ ■? ■ ■ ■ ■ I » W ■' 



L 



Figure 2.21 Wink. hex file loaded into EPIC program. 



i, . xnrnnn nnnrn cggdo nrrnr 

i 6 Id 1B 20 

ac nnoD o no no no nr no nnnnnDG 
bc nnr-P o rippGOD nr pp nn nr-nr-o 

Cr nnnnnnnnnr.n nr. nn nn nnnrn 

DC UDCDUUDOLICUDC: DU GDDCDCD 

EC DDDDDDDDDDDDCDD DDDDDDD 


\ m 

A 

B 
C 


E 

F 
G 

H 

1 

J 

.-" 
'■■.. 


i 


I 


FDDDDDDDDDDDDCDDDDDDDDDD 
GDQDDaDDDDDDaCDDDDDDDaDD 

Hnc-nnaanGnnnocnna nnnnnnn 
I nc nnnannnnnncnnn nnnnnnn 

jnonnGGnnnnnncnnnnnnnnnn 

f^Ynnncn nnnnn nenne dccdc 

1 S 10 15 20 



Figure 2.22 Solderless breadboard. 



You connect components on the board using 22-gauge (solid or stranded) wire 
I prefer to use stranded wire because it has greater flexibility. 

The complete internal wiring structure of the board is shown in Fig. 2.24. 
The X and Y rows are typically used as power supply and ground connections 
The columns below the X row and above the Y row are used for mounting com- 
ponents. 



30 Chapter Two 



o 



X D DGDG aQQQD 
1 B 10 

Ann nana an ana 
Ban nana an anna 
cnnnaQannnann 
Dnnnanannnnnnn 

EDDDQDQDDDDDDDD 



Pddddddddddodgdd 

flDDDDDDDDDDDDDDD 
IJDDaDDaDDDDODQDDO 

Jdddddddddddddddd 



{ )y □ □ □ □ □ 
" 1 5 



□ □ an a 

10 




n 



a a do □ 

14 



^» 



Figure 2-23 Internal structure of the solderless breadboard. 







c 



■3 

I 
J 



o 



10 



IS 



10 



F 
G 

H 
I 
J 



Vi 



Figure 2.24 Complete internal wiring of solderless breadboard. 



Three Schematics, One Circuit 



Figures 2.25, 2.26, and 2,27 are identical schematics of our test circuit, I drew 
three schematics to help orient experimenters who may not be familiar with 
standard electrical drawings. Figure 2.25 shows how the PIC 16F84 micro- 
controller and components appear. There is a legend at the bottom that shows 
the electrical symbols and the typical appearance of the components. Figure 
2,26 is a line drawing showing how the components appear mounted on the 
solderless breadboard. The labels in Fig. 2.26 point out each electrical com- 
ponent. 

If you examine the placement of the components mounted on the solderless 
breadboard with its internal electrical wiring (Fig. 2,24), you can see how the 
components connect to one another and produce a circuit. 



Software Installation (Compiler and Programmer) 31 



*sv 



O 



*.7K< 




has 

HAS 



NCLP 

HHA1NT 

RBI 

RffZ 



2 



0) 

■n 

oo 



Ml 
RAD 

OKaKLKOUl 
VHd 

REn 



It 

IT 



4WZ 



1B 
14 



Z2pF 



aapr 



p»^ 



■14 
11 

ig 



,1uF 



**l 



LED 



FfroiMtar CmufHrH- 



B*etitiE 



9*inbal J 



<r 




Carnpaniint 

A|ipiiDrflii« 




MI-IX J 

tt n 



i/ 



Figure 2,25 FiTst view of components mounted on breadboard. 



Figure 2.27 is the same schematic drawn as a standard electrical drawing, 
with the pin numbers grouped and oriented according to function. For the 
remainder of the book, standard electrical drawings will bo used. 

The schematic shows how few components are needed to get your microcon- 
troller up and running- Primarily you need a pull-up resistor on pin 4 (MCLR), 
a 4-MHz crystal with two 22-pF capacitors, and a 5-V power supply. 

The two LEDs and two current -limiting resistors connected in series with 
the LEDs are the output. They allow us to see that the microcontroller and 
program are functioning. 

Assemble the components on the solderless breadboard as shown in the 
schematic (see Fig. 2.27), When you are finished your work should resemble 
Fig. 2,28. 

While the specifications sheet on the 16F84 states that the microcontroller 
will operate on voltages from 2 to 6 V, I provide a regulated 5-V power supply 
for the circuit- The regulated power supply consists of a 7805 voltage regula- 
tor and two filter capacitors, 



32 Chapter Two 



7805 
Voll 



o 



X □□□□ 
1 

ADDD 
BDDD 
CDDD 
DDDD 
EDDD 



D A 



□ nnn 

5 10 

DDDDOD 
DDDDDDDDDDDDaOl 




DDDDD DTfJ'L 

n nnn nn 

PIC16F84 



nnnnn ddddd 

15 20 

DDDDDDDD 

is. 



c 



Xtal 










GDD| |DDDDDOO( 

Hnn D □ LrtrrjTirrfc^] u 

DDDD DID DUD 



DD 3^ 



n 



D 

u 



rn n OOP nan 

DDE DDDD 

I, 10 f l\ 15 



.1uf 




o 



22 pf 



Red 
LED 



& 



Side 



4.7K 



470 ohm LED's Ground 



Ground 



Figure 2.26 Second view of components mounted on breadboard. 



* CapQ-Crtijrs connected "to cryeials ore 2"2"pF 



+5V 



Q- 




0SC1 




0*4:? 






16 



ifnz 



IS 



& 



2 



PIC 16F8* 



,ci 
.luF 



+5V 



Regul&ted Paw#i* Supply 



6-9V 



+ 



T 




*C3 

]-2V 



7OT5 



T 



4« 

L2Y 



Figure- 2.27 Electrical schematic of wink project. 



Wink 



Apply power to the circuit. The LEDs connected to the chip will alternately 
turn on and off. Wink... wink.,. Now you know how easy it is to program these 
microcontrollers and get them up and running, 

As you gain experience^ using the compiler and programmer will become second 
nature. You won't even consider them as steps anymore. The real challenge will 
be w r riting the best FICBasic programs possible. And that is as it should be. 



Software Installation (Compiler and Programmer) 33 




Figure 2.2B Photograph of wink project. 



Troubleshooting the Circuit 



There is not too much that can go wrong here. If the LEDs don't light up, the 
first thing I would check is the orientation of the LEDs. If they are put in back- 
ward, they will not light. 

Next check your ground wires. See the jumper wires on the right-hand side 
of the solderless breadboard- They bring the ground up to the two 22-pF 
capacitors, 

Check all your connections. Look back at Figs, 2.23 and 2.24 to see how the 
underlying conductive strips relate to the push-in terminals on top of the 
board. 



Chapter Review 



Before we move on to the next chapter, let's review the important steps w r e 
have learned in programming a PIC microcontroller. We will not review the 
installation, because that's typically a one-time job. 
This review assumes w r e are working from DOS. 

Step J- Upon entering DOS, if you are not in the root directory, move to the 
root directory using the cd command cd.. or cd\> 

Step 2. At the DOS prompt enter the path command: 



C:\> path \ ; c: \pictools ;c : \epic;e * \windows\ command? 



34 Chapter Two 

Step 3. Enter the applies directory using the cd command: 

Ci\ cd applies 

Step 4. Start your word processor or the Edit program: 

C:\applics> edit 

Step 5, Write the Basic program. Save the program as an ASCII- type text 

file. Save the file with a ,bas suffix (e.g. ? wink, has). Note that .has is optional. 

Step 6. From the applies directory, run the PIC Basic compiler The command 
line for compiling the wink. has program For a PIC16F84 microcontroller is as 
follows: 

C:\applics> pbc -plGFB4 wirik.bas 

The -pl6FS4 tells the compiler to compile the program for this particular 
microcontroller. The compiler is capable of writing for a large number of PIC 
microcontrollers you will find listed in the compiler manual. The .has after 
the program name is optional. 

The compiler reads the .bas file and, if it finds no errors, generates two 
files, wink. asm and wink. hex. If the compiler finds an error, the program 
needs to be corrected and recompiled. 

Step 7. Connect the EPIC programming board to the computer's parallel 
(printer) port. Turn on the EPIC board power supply. 

Step §. From the applies subdirectory run the EPIC DOS program. 

Ci \applics> epic 

Load the program's .hex file. Insert a PIC 16F84 into the programming 
socket on the programming board. Highlight the Program button and hit the 
Enter key on your keyboard to program the PIC microcontroller. 

Remove the PIC microcontroller chip and test it. 

In the next chapter, we will look at output-programmable attributes of the 

16F84. 



Parts List 



Same components as listed for Chap. 1 



Chapter 




PIC 16F84 Microcontroller 



In this chapter, we begin looking at the PIC 16F84 microcontroller in greater 
detail. What we learn about this microcontroller is applicable to most of the 
other PIC microcontrollers. So, while it appears that we are focusing only on 
the FIC16F84 microcontroller, just keep in mind that it is representative of all 
the other PIC microcontrollers. 

What advantages do other PIC microcontrollers have over the PIC 16FS4? 
Primarily, they boil down to two different advantages: cost and options. For 
instance, the 16C61, while similar to the 16F84, is half the cost of the 16F84, 
However, the 16C61 is an OTP (one-time programmable) microcontroller. 
That's not the type of chip you want to work with when designing and proto- 
typing programs and circuits because chances are that you will need to trou- 
bleshoot and re program the chip before everything is perfected and functions 
the way you want it to function. 

After the prototyping stage is completed, the 16C61 may be the preferable 
choice for the mass production of a product. Let's suppose you create a com- 
mercial product that uses a PIC microcontroller and you are going to mass- 
produce it. Switching from the 16F84 to the 16C84 will save you quite a bit of 
money. 

Aside from cost ? other PIC microcontrollers have unique features that the 
PIC16F84 doesn't have, such as analog-to-digital converters, more RAM, or 
more I/O lines. In this book we will focus on the 16F84, but in my next book 
we shall look at these other microcontrollers. 

Harvard Architecture and Memory-Mapped I/O 

PIC microcontrollers use Harvard architecture. That simply means that the 
memory on the PIC microcontrollers is divided into program memory and data 
memory. The devices also use separate buses to communicate with each mem- 
ory type. The Harvard architecture has an improved bandwidth in comparison 
to traditional computers that use the von Neumann architecture, (von 

35 

Copyright 2000 The McGraw-Hill Companies, Inc. Click Here for Terms of Use, 



36 Chapter Three 



Neumann architecture accesses data and memory over the same bus-) Hie 
Harvard architecture allows for other enhancements. For instance, instruc- 
tions may be sized differently than 8-bit-wide data. 

The data memory in the PIC microcontroller can be further broken down 
into general-purpose RAM and the special function registers (SFRs). 

The registers on the PIC 16FS4 are mapped in the data memory section at 
specific addresses. The PlCBasie language allows us to read and write to these 
registers as if they were standard memory bytes. This is an important concept 
to learn and remember. We read and write to the registers (memory location) 
using the Basic language's Peek (read) and Poke (write) commands. By writing 
numbers into the chips regis ters, we program the chip I/O (via the registers) 
and have it perform the functions we need. 

Although we read and write to the registers using our familiar decimal num- 
bers., to understand what happens inside the register with those numbers 
requires a fundamental understanding of the binary number system. 



Binary Fundamentals 



To access the PIC chip registers efficiently a little binary goes a long way. 
Binary isn't difficult to learn because there are only two values. That's what 
the word binary means: "based on two,* as in the two numbers and 1. Binary 
and 1 can also be compared to an electrical signal controlled by a switch that 
has two values^ ofT(O) and on (1). In binary a digit is called a bit t which stands 
for binary digit. 

An 8-bit digital number, or byte, can hold any decimal value between and 
255, In hexadecimal notation, these same values (0 to 255) are expressed as 00 
to FR We are not going to be learning hex (the hexadecimal number system), 
primarily because we don't need to use hexadecimal notation to write Basic 
programs- It's nice to know hexadecimal notation in the grand scheme of 
things because it is used at times, but it is not essential. What is essential at 
this point is to gain an understanding of binary; stay focused on this. When 
you understand the? binary number system completely then (and only then.) if" 
you are still interested in hexadecimal notation., there is a quick tutorial in the 
Appendix - 

The CPU in the PIC 16F84 uses an 8-bit data bus (pathway). The registers 
in the PIC chip are also 8 bite wide. Thus, a byte is the perfect size to access 
the PIC chip registers. We will read from and write to the PIC microcon- 
troller's registers using the decimal numbers between and 255, which can be 
contained in one 8-bit byte,. 

However^ when we write a decimal number into a register, the microcon- 
troller can only see the binary equivalent of that decimal number (byte). lb 
understand what's happening inside the register, we need to be able to look at 
the binary equivalent of the decimal number (byte) also- Once w r e can do this, 
our ability to effectively and elegantly program the PIC microcontroller is 
greatly enhanced. 



PIC 1 6F84 Microcontroller 37 

Examine Table 3.1. This table shows the decimal- and binary-number equiv- 
alents for the numbers through 31. Using this information, the binary num- 
bers from 32 to 255 can be extrapolated. 

In the table, each decimal number on the left side of the equal sign has its 
binary equivalent on the right side. So when we see a decimal number, the 
microcontroller will see the same number as a series of 8 bits (8 bite to a byte). 



Registers and Ports 



The PIC 16F84 contains two I/O ports, port A and port B. Each port has two 
registers associated with it, the TRIS (Tri State) register and the port register 
address itself. 

The TRIS register controls whether a particular pin on a port is configured 
as an input line or an output, line. Once the ports are configured the user may 
then read or write information to the port using the port register address.. (The 
terms pins and lijies off the PIC 16F84 mean the same thing and are used 
interchangeably throughout the text.) 

On port B we have eight I/O lines available. On port A only five I/O lines are 
available to the user. Figure 3.1 shows the relationship between a binary num- 
ber and the two PIC microcontroller registers that control port B. Let's look at 
the binary-number side. Notice that for each move of the binary 1 to the left, 
the exponential power of 2 is increased by 1. 



TABLE 3. 1 Bl nary Number Table 



= oooooooo 


16 = 


00010000 


32 = DO 100000 


1 = 00000001 


17 - 


00010001 


■ 


2 = 00000010 


18 - 


00010010 


. 


3 = 00000011 


19 = 


00010011 


■ 


4 = 00000100 


20 = 


00010100 


64 = 01000000 


5 = 00000101 


21 = 


00010101 


■ 


6 = 000O0110 


22 - 


00010110 


■ 


7 = 00000111 


23 = 


00010111 


■ 


8 = 000010O0 


24 = 


00011000 


128 = 10000000 


9 = 000010O1 


25 - 


00011001 


■ 


10 = 00001010 


26 = 


00011010 


■ 


11 = 00001011 


27 - 


00011011 


■ 


12 = 00001100 


28 = 


00011100 


255 = 11111111 


13 = 00001101 


29 = 


00011101 




14 = 00001110 


30 = 


00011110 




15 = 00001111 


31 - 


00011111 





38 Chapter Three 



PortB 



TRISB Decimal 134 86 Hex Port B Decimal 6 06 Hex 





Power 


Binary 


af Twa 


CKMMH01 


FM 


QUO MOID 


r' = J 


OWWIOO 


2" = 4 


fihifrlH.6 


2" = » 


ClLMItllMlO 


sr=i* 


001 V0D0P 


7 =3? 


O1O00D00 


2 =64 


IDOODDflD 


a" = us 



i 



RcgtstciLcc a/Inn 



12R ** 31 IB H 4 2 



f- * W -* r*> M r O 

U ID Dl ID It 10 1 1 
U BE BT EC Iff K ffi IE 



Figure 3.1 Port B I/O lines and registers. 



Bit# 


Decimal 


Binary 


BitO 


1 = 


00000001 


Bitl 


2 


00000010 


Bit 2 


4 


00000100 


Bit 3 


8 = 


00001000 


Bit 4 


16 - 


00010000 


Bit 5 


32 - 


00100000 


Bit6 


64 - 


01000000 


Bit 7 


128 = 


10000000 



FDirt»?r 

Binary B * Twa 

4)0001)001 2 C = "1 

D0UCD01C 3h = a 

DDlMlNJ 3= = 4 

DODIDOK) T-W 

ooirjrjgw ^'=^2 

LMflfllHM 2"=e* 

ItiMiUN) 2'-=12S 



i 



EH Ww^lirt/V^iutfH 
Register Locatior 



119 S4 32 1& 4 4 

III ~ 



r- a a ^ n h r s 
Cfl DQ 9 E 1 9 "D ™ ™ 
2 K a c£ ie -tc a ce: 



These are relevant numbers, because each position identifies a bit location and 
bit weight within the 8- bit byte. 

For instance, suppose we wanted to write binary Is at the RB7 and RB4 
locations- To do so, we add their bit weights together, in this case 128 (RB7) 
and 16 (RB4), which equals 144. The binary equivalent of decimal number 144 
is 10010000. If you slide that number into the register, you will see 
that the binary Is are in the RB7 and RB4 positions. Remember this; it is 
important. 

The open TRISB register shown in Fig. 3,1 may be used to examine numbers 
placed in the TRISB, The port B register may be used to examine numbers placed 
at the port B register 



PIC 16F84 Microcontroller 39 



Notice the correlation between the register bit locations, bit weights, and 
port B I/O pins. This correspondence between the bit number, bit weight, and 
the I/O line is used to program and control the port, A few examples will 
demonstrate this relationship. 



Using theTRIS and port registers 



The TRIS register is a 1-byte (8-bit) programmable register on the PIC 
16F84 that controls whether a particular I/O pin is configured as an input 
or an output pin. There is a TRIS register for each port, TRISA controls the 
I/O status for the pins on port A and TRISB controls I/O status for the pins 
on port B. 

If you place a binary at a bit location in TRISB for port B, the corre- 
sponding pin location on port B will become an output pin. If you place a bina- 
ry 1 at a bit location in the TRISB, the corresponding pin on port B will 
become an input pin. The TRISB data memory address for port B is 134 (or 
86h in hex). 

After port B has been configured using TRISB register, the user can read or 
write to the port using the port B address (decimal number 6), 

Here is an example. Suppose we want to make all port B lines output lines. 
To do so we need to put a binary in each bit position in the TRISB register. 
So the number we would write into the register is decimal 0. Now all our I/O 
lines are configured as output lines. 

If we connect an LED (light-emitting diode.) to each output line* we can see 
a visual indication of any number we write to the port B. If we want to turn on 
the LEDs connected to RB2 and RB5, we n^d to place a binary 1 at each bit 
position on the port B register To accomplish this we look at the bit weights 
associated with each line. RB2 has a bit weight of 4, and RB5 has a bit weight 
of 32. We add these numbers together (4 i- 32 = 36) and write that number 
into the port B register. 

When we write the number 36 into the port B register, the LEDs connected 
to RB2 and RB5 will light. 

To configure port A, we use the TRISA register, decimal address 133 (see Fig. 
3.2). On port A, however, only the first 5 bits of the TRISA and the corre- 
sponding I/O lines (RAO to RA4 ) are available for use. Examine the I/O pin out 
on the 16F84 and you will find that there are only live I/O pins {RAO to RA4) 
corresponding to port A. These pins are configured using the TRISA register 
and used through the port A address. 



Register 


Memory location 
i hexadecimal) 


Memory location 
(decimal.! 


Port. A 


05h 


fi 


Port B 


06h 


6 


TRISA 


85h 


133 


TRISB 


86h 


134 



40 Chapter Three 



Port A 



TRISA Decimal 133 85 Hex Port A Decimals 05 Hex 



PtoHvr 

Binary nfTwo 

GCiDWDIM ?=f 

GQfrKJUW > } -> 

C00W1M * =4 

0Q0D1Q(H 2= A 

flOMflDMr £*=16 



Bpl¥fcight i \y«j«e 
R*$la*« Locflrtlom 



e e 



4 2 

_J_ 



3 

LL 






3 5 



o 



Figure 3.2 Port A I/O lines and registers. 



Binary 


Power 

orr*o 


<ici>:moni 


F = i 


*ooftddia 


s'= a 


flOMFCIQO 


?=4 


doom DM 


2* = * 


<08i«W 


2-=ie 



MWeisWValwK ia * 4 2 

Rflf]jr,tflr LMJatifff 3 I 



3r-1 M *- B 

* * «j 5 

DC Of K IE IE 



On power-up and reset, all the I/O pins of port B and port A are initialized 
(configured) as input pins. Of course, we can change this with our program. 

Here is another example. Let's configure port B so that bit 7 (RB7) is an 
input pin and all other pins are output lines. To place binary 0s and Is in the 
proper bit location, we use the bit weights shown in Fig. 3.1. For instance, to 
turn bit 7 on (1) and all other bits off (0), we would write the decimal number 
128 into the TRISB for port B. In Basic, the command Lo write to a register is 
the Poke command. The program line to write the decimal value 128 into the 
TRISB register will look like 

Poke 134, 12B 

The number after the Poke command is the memory address that the com- 
mand will write to — in this case, 134, which is the data memory address of the 
TRISB for port B. The next number, after a comma is the value we want to 
write in that memory address. In this case, it is 128. 

Look at the binary equivalent of the decimal number 128: 

10 

Mentally place each 1 and into the TRISB register locations shown in Fig. 
3.1. See how the 1 fits into the bit 7 place, making that corresponding line an 
input line, while all other bit locations have a written in them, making them 
output lines. 

So by pokeing (writing) this location with a decimal number that represents 
a binary number containing the proper sequence of bits (0s and Is), we can 
configure the pins in the port to be any combination of outputs and inputs that 



PIC 16F84 Microcontroller 41 

we might require. In addition, we can change the configuration of the port "on 
the fly" as the program is running. 

To summarize, pokeing a binary 1 into the TRIS register turns that corre- 
sponding bit/pin on the port to an input pin. Likewise, pokeing a binary will 

turn the bit into an output. 



Accessing the Ports for Output 



Once the port lines have been configured (input or output) using the TRIS reg- 
ister, we can start using the port. To output a binary number at the port, sim- 
ply write the number to the port using the Poke command. The binary 

equivalent of the decimal number will be outputted as shown in our first 
example. To output a high signal on RB2, we could use this command: 

Poke 6 , 4 

where 6 is the memory address for port B and 4 is the decimal equivalent of 
the binary number we want to output, Reading input information on the ports 

will be discussed in Chap. 4. 



Electrical Binary, TTL, and CMOS 



When a pin on port B (RBO to RB7) is configured as an input line, the micro- 
controller can read (via the Peek command) the electrical voltage present on 
that input pin to determine its binary value {0 or 1). 

When a pin on a port is configured as an output, the microcontroller can 
raise the voltage on that pin to i 5 V by placing a binary 1 at the bit location 
on the port- A binary at the bit location will output a zero voltage. 

When a pin (or bit) is set to 1 it may be called "on * "set/ or "high." When a 
bit is set to that may be called "off," "cleared,* or "low* 

In TTL logic, electrically a binary 1 is equal to a positive voltage level 
between 2 and 5 V. A binary is equal to a voltage of to 0.8 V. Voltages 
between 0.8 and 2 V are undefined. 

CMOS has a slightly different definition. Input voltages within 1.5 V of 
ground are considered binary 0, whereas input voltages within L5 V of the 
+ 5*V supply are considered binary 1. 

Digital logic chips (TTL and CMOS) are available in a number of subfami- 
lies—CMOS: 40QQE, 74C, 74HC, 74HCT, 74AC, 74ACT; and TTL: 74LS, 
74ALS, 74AS, 74E These differences become important when you need to 
make different logic families talk to one another. 

CMOS devices swing their outputs rail-to-rail so +5-V CMOS can drive 
TTL, NMOS, and other i 5-V-powered CMOS directly IThe exception to this is 
old-fashioned CMOS (4000B/74OJ TTL devices on the other hand may not 
output sufficient voltage for a CMOS device to see a binary 1, or "high 7 ' signal. 

This could have been a problem, since the PIC 16F84 is a CMOS device. The 
designers of the PIC were thoughtful enough to buffer the I/O lines with TTL 
buffers, thus allowing the PIC I/O lines to accept TTL input levels while outputting 



42 Chapter Three 



full CMOS voltages. This allows us to directly connect TTL logic devices, as well as 
CMOS devices, to our PIC microcontroller without difficulty: 



Counting Program 



To illustrate many of these concepts, I have written a simple Bask program- 
It is a binary counting program that will light eight LEDs connected to port 
B's eight output lines. 

The counting program will light the LEDs in the sequence shown in the 
binary number table. Each binary 1 in a number in the table will be repre- 
sented with a lit LED. Every 250 ms (V 4 s), the count increments. After reach- 
ing the binary number 255 (the maximum value of a byte), the sequence 
re peats , starting from zero. 



Counting in binary by one 



Enter the following program into your word processor exactly as it is written. 
Save it as an ASCII text file (or DOS text) with the .has extension. 

'Program 3.1, Binary Counting 

'Initialize variables 

Symbol TRISB = 134 'Assign TRISB for port B to decimal value: of 134 

Symbol PoitB = G 'Assign the variable ports to the decimal value 6 

'Initialize Port{s} 

Poke TRISB, l Set port B pins to output 

loop : 

For BO = to 255 

Poke FortE, BO x Place BO value at port to light LEDs 

Pause 2 5G 'Without pause ( counting proceeds too fast to see 

Next BO 'Next B£3 value 

Goto loop 

' iitld 

Let's look at the program and decipher it line by line. The first two lines are 
comments, which begin with a single quotation mark (V), 

'Program 3.1, Binary Counting 
'Initialize variables 

The compiler ignores all text following a quotation mark. You should use 
comments liberally throughout your Basic code to explain to yourself what 
you are doing and how you are doing it. What appears obvious to you when 
you are writing a program will become obscure a few months later. All com- 
ments are stripped when the program is compiled into .hex and .asm files, 
so you can add as many comments as you like — they do not take up any pro- 
gram space. 

The following two lines initialize two important variables. The TRISB is 
assigned the decimal value of 134 and the port B represents the port B 
address, decimal value of 6, for subsequent use in the program- 
Technically, we don't need to initialize these variables. We could write the 



PIC 1 6F84 Microcontroller 43 

decimal equivalent (number 134) instead of using the TRISB variable 
when needed by the program. So if we wanted, we could write POKE 134 , 
XX instead of POKE TRISA, XX. However, when initializing variables, 
especially in mure complex programs, using a mnemonic variable for deci- 
mal values makes writing the programs and following the logic easier and 
less error-prone. 

Symbol TRISB = 134 'Assign TRISB for port B to decimal value of 134 
Symbol PortB = £ x As sign the variable PortB the decimal value 6 

The variable TRISB now represents a decimal value of 134, and the variable 
PortB now represents a decimal value of 6, Hereafter in the program, we can 
refer to TRISB without needing to remember its numerical value, and the 
same is true for PortB- The comments following each instruction provide valu- 
able information on what each command is doing. 

1 Initialise Port{s) 

This is a comment that tells what is to follow. 

Poke TRISB, o l set all port B pins to output 

The following line is the command that initializes port B with a zero, mak- 
ing all the port B lines output lines. 

loop; 

This line contains a label called loop. The word loop is clearly identifiable 
as a label because of the colon (:) following the word- Labels can be referred 
to in the program lor jumps (Goto's and on value) and subroutines 
(Gosub's). 

For BO = to 255 

This line defines our variable BO, In standard Bask;, this line would proba- 
bly read for x - to 2 55. In this line we are using one of PICBasic's pre* 
defined variables, BO. The 16F84 has a limited amount of RAM that can be 
accessed for temporary storage. In the case of the 16F84, there are 68 bytes of 
RAM. Of this total area of 68 bytes of RAM, 51 bytes are available for user 
variables and storage. 



User-available RAM 



RAM may be accessed as bytes (8-bit numbers) or words (16-bit numbers). 
PICBasic has predefined a number of variables for us- Byte-sized variables are 
named BO, Bl, B2> B3,..., B5L Word-sized variables are named WO, Wl, 
W2,..., W25. The byte and word variables use the same memory space and 
overlap one another. 

Word variables are made up of two byte-sized variables. For instance, WO 
uses the same memory space of variable bytes BO and Bl. Word variable Wl 
is made up of bytes B2 and B3 > and so on. 



44 Chapter Three 



Word variables 


Byte 


variables 


Bit 


WO 




BO 


BitO, Bitl,..., Bit 7 






Bl 


BitS, Bit9,„., BitlS 


Wl 




B2 
B3 




W2 




B4 
B5 




W39 




B78 
B79 





The variables may be used for number storage. The variables may also be 
given a name that has meaning in the program by using the command Symbol. 
For instance we could rename our variable BO to X to make this program read 
more like a standard Basic -language program. 

We used the Symbol command in the beginning of the program to store the 
variables TRISB and PortB. 

If you write a program that uses more variables than the PIC microcontroller 
has RAM to store, the PICBasic compiler will not generate an error when it 
compiles the program. Your program will simply not function properly. It is up 
to you to keep track of how many variables are being used in the program. For 
the 16F84 S you may use up to 51 bytes or 25 words, or a combination of both. 

When you program other PIC microcontrollers, check their data sheets to 
see how much RAM thev have available. 



Poke PortB, BO 



'Place BO value at port to light LSDs 



This line writes the value BO to PortB. Any binary Is in the number are dis- 
played by a lit LED, 



Pause 2 50 



'Without pause, counting proceeds too fast to see 



This line makes the microcontroller pause for 250 ms (V 4 s|, allowing us 
enough time to see the progression. 



Next BO 



l Next BO value 



This line increments the value of BO and jumps up to the For BO = to 
255 line. If the value of BO equals the end value declared in the line (255), the 
program drops to the next line. 

GOtO loop 

When BO equals 255, the fur-next loop is finished and this line directs the pro- 
gram to jump to the label loop, where the BO value is reinitialized and the 
number counting repeats, starting from zero. 

Figure 3.3 shows the schematic for this program. Figure 3.4 is a photograph of 
this project. Notice that I used a second solderless breadboard to hold the resis- 
tors and LEDs so I wouldn't have to squeeze everything onto a single breadboard- 



PIC 1 6F84 Microcontroller 45 

Programming challenge 

Rewrite the last program, renaming the BO variable X. This will make the pro- 
gram appear more like a "standard* Basic-language program. The programming 
answer is given in the Appendix. 

Counting Binary Progression 

The last program was informative. It showed us how to output electrical sig- 
nals via port B, Those electrical signals may be used for communication and/or 
control. As we shall learn in future chapters, an electrical signal off one pin 
can control just about any household electrical appliance. 

We are not yet finished with our simple circuit- With a little programming 
modification, we can have the same circuit perform a binary progression 
instead of binary counting. What's the difference between a binary progression 
and counting? The binary progression lights each single LED in sequence, 
starting with the first LED, then the second LED, and so on until the last LED 
is lit, after which the progression repeats. When the LEDs are arranged in a 
straight line, it looks as if the lit LED travels from one end of the straight line 
to the other If the LED lights were arranged in a circle, the lit LED would 
appear to travel in a circle. 

'Program 3.2, Binary Progression counting 

'initialize variables 

Symbol TEISB = 134 ^Assign TRISB port B to 134 

Symbol Ports = 6 'Assign the variable Ports the decimal value 6 

'initialize Port{s) 

Do}.-.: trisb, j * set port B pins to output 

loop : 

BO = l % Set variable to l to start counting 



* Capacitor g connected ta Crystal^ 4r-^ ££pf~ 






1-5V 



& 



*1M 






>R6 



>R5 

'iro 



^70 



* P *y.d *ffL «gd ifi ^4 ^ 







ii 



AL 



11 



Jk!_ 



e* 



3 

1 
Id 



a 



^DD 



Ll 



IT§7 



RB5 



KB1 
&6J 



free 



NCLR' 
OSCL 

OStfi 






ft A I 






X] 
fNHz 



PIC 16F81 



CI 

,LjF 



Figure 3-3 Schematic for LED counting project. 



46 Chapter Three 




Figure 3A Photograph of LED counting project. 



El = 

Poke Ports t BO 

Pause 250 

For B2 = to 6 

El = BO * 2 
E0 = Bl 

Poke PortE, BO 
Pause 250 
Next B2 
Goto loop 



x Set variable to 

> Place BO value at port to light LEDs 

'Without pause r this proceeds too fast to see 

'Calculate next binary progressive number 

l set BO to new value 

* Place new value at port to lingfht LEDs 

'Without pause, counting proceeds too fast to see 

'Next loop value 



Programming challenge 

Can you rewrite the binary sequence program above? so that the LEDs light in 
sequence, but do not. turn off until all the LEDs are lit, after which the cycle 
repeats? The answer is given in the Appendix, 



Basic High and Low Commands 



The way we have defined outputting information thus far is the most power- 
ful and elegant way to do so. However, it is not the easiest. The PIC Basic com- 
piler has two Basic-language commands for outputting information on any of 
the Port B pins, High and Low, 



PIC 1 6F84 Microcontroller 47 

These commands are limited to port B; they will not work on port A lines. So 
if your knowledge of the Basic language did not include the Poke command 
and an understanding of binary, you would be unable to use the five I/O lines 
to port A. 

The High command makes the specified pin output high. The pin so defined 
is automatically made into an output pin. This works only with port B pins 
to 7, The command structure is as follows: 

High Pin 

So the command 

High o 

makes pin an output pin and sets it high ( + 5 V). 

The Low command makes the specified pin output low. The pin so defined is 
automatically made into an output pin. This works only with port B pins to 
7. The command structure is as follows: 

Low Pin 

So the command 

LOW 

makes Pin an output pin and sets it low (0 V). 

The High and Low commands are quick and easy commands to use and do 
have their usefulness. Real programming power and versatility is obtained 
using the Poke command. Don't believe it? Try rewriting our simple binary 
counting programs using just the High and Low commands. Call me when 
you're done. 

As a sample program that uses the High and Low commands, here is the 
first program we worked with from Chap- 2. 

Loop; High l Turn on LED connected to pin RBO 

Low l l Turn off LED connected to pin RBI 

Pause 5 00 x Delay for 0.5 s 

Low d x Turn off LED connected to pin RBO 

High l * Turn on LED connected to pin RBI 

Pause 5 00 x Delay for 0.5 s 

Goto loop l Go back to loop and blink, and wink LEDs forever 
End 



Programming Review 



Before we proceed to the next chapter, let*s take time to review the key pro- 
gramming concepts we have used in the last few programs. 



Comments 



Use comments liberally when writing your programs. Use them to describe the 
logic and what the program is doing at that particular point. This will allow 

you to follow and understand the program's logic long after you have written 



48 Chapter Three 



Identifiers 



(and probably forgotten) the program. Comments begin with a single quota- 
tion mark ( x ) or with the word REM. The compiler ignores all characters on the 
line following the quotation mark or the keyword REM. 



Identifiers are names used for line labels and symbols. An identifier may be 
any sequence of letters, digits, and underscores, but it must not start with a 
digit. 

Identifiers may be any number of characters in length; however, the com- 
piler will recognize only the first 32 characters. 

Identifiers are not ease-sensitive, so the labels LOOP:, Loop:, 100P:, and 
loop: will be read equivalently- 



Line labels 



Labels are anchor points or reference points in your program. When you need 
the program to jump to a specific program location through either a Goto, 
Gosub, or Branchy use a label- Labels are easy to use. Use a descriptive word 
(identifier) for a label., such as the word loop: that we used in Programs 3,1 
and 3-2- Loop is descriptive inasmuch as it shows the main loop point for the 
program- 
Labels are identifiers followed by a colon (:). 



Symbols 



Symbols help to make our programs more readable. They use identifiers to 
represent constants, variables, or other quantities- Symbols cannot be used for 
line labels- 

ln our programs, we used the symbol TRISB to represent the decimal num- 
ber 134. The number 134 is the data memory address for the TRISB register 
for port B. The symbol PortB represents the memory address for port B- 
Symbols are easier to remember than numbers- Here are a few examples of the 
symbol keyword usage- 





Symbol 


Five = 5 


'Symbolic constant 




Symbol 


Number = W2 


•■Named word variable 




Symbol 


Evalue = BITO 


"■Named bit variable 




Symbol 


AKA = Evalue 


l An alias for Evalue 


Variables 









Variables are temporary storage for your program. A number of variables have 
been predefined for usage in your programs- Byte-sized (8-bit) variables are 
named BO, Bl ? B2, and so on. Word-sized {16-bit) variables are named WO, Wl, 
W2, and so on- 

Remember these variables overlap and use the same memory space- 



PIC 1 6F84 Microcontroller 49 

The word variables are made up of two byte-sized variables. For instance, 
the 16-bit WO is made up of the two smaller 8-bit BO and Bl variables, Wl is 
made up of B2 and B3, and so on. 

Any of these variables tan be renamed to something more appropriate to a 
program using the Symbol command. 

Take special note of variables BO and Bl because we can read their individ- 
ual bits (BitO, Bitl,<*», Bitl5). The ability to read the bits in these variables is 
very attractive for many bit-checking applications. Since the word variable WO 
is composed of the two bytes BO and Bl, the bit-checking commands will also 
work with this word variable. 

Read the specification sheets on the PIC microcontrollers to determine how 
much free RAM is available. The 16F84 has 68 bytes of free RAM, of which 51 
bytes are available to the user. 



Reading Input Signals 



The programs we have written thus far have dealt only with output-ting bina- 
ry signals that we can see using the LEDs. While this is extremely important, 
it is also just as important to be able to read input off the lines. The status 
(binary state or 1) of a line (signal) may be a digital signal or a switch. In the 
next chapter, we will examine inputting signals to our PIC microcontroller. 



This page intentionally left blank. 



Chapter 




Reading I/O Lines 



In the last chapter, we studied out putting binary numbers (information) to 
port B and viewing the information using miniature red LEDs. In this chap- 
ter* we will be inputting binary information. 

The ability of our microcontroller to read the electrical status of its pin(s) 
allows the microcontroller to see the outside world. The line (pin) status may 
represent a switch, a sensor, or electrical information from another circuit or 
computer. 



The Button Command 



The PlCBasic compiler comes equipped with a simple command to read the 
electrical status of a pin called the Button command. The Button command, 
while useful, has a few limitations. One limitation of this command is that it 
may be used only with the eight pins that make up port B, The I/O pins avail* 
able on port A cannot be read with the Button command. Another limitation is 
that you cannot read multiple pin inputs at once ? but only one pin at a time. 

We will overcome these Button command limitations later on ? using the 
Peek command. But for the time being, let's use and understand the Button 
command. 

As the name implies, the button command is made to read the status of an 
electrical "button" switch connected to a port B pin. Figure 4.1 shows two basic 
switch schematics, a and 6, of a simple switch connected to an I/O pin. 

The Button command structure is as follows: 

Button Pin, Down, £>*2ay r Rat&, V£Lr T Aation ( Lab&l 

Pin Pin number (0 to 7), port B pins only. 

Down State of pin when button is pressed (0 or 1). 

Delay Cycle count before auto-repeat starts (0 to 255). If S no debounce or auto- 

repeat is performed. If 255 t debounce but no auto-repeat is performed. 

Rate Auto- repeat rate (cycles between auto-repeats), (0 to 255). 

51 
Copyright 2000 The McGraw-Hill Companies. Inc. Click Here for Terms of Use. 



52 Chapter Four 



+5V 

o 



Rl 



SW 
B 



+5V 

o 



u 



u 



SW 




I/O Pin 



I/O Pir> 






Figure 4.1 Switches connected to I/O line (pin). 



Var 

Action 
Label 



Byte-sized variable used for delay/repeat countdown, Should be initialized 
to prior to use. 

State of button in order to perform Goto (0 if not pressed, 1 if pressed). 

Point at which execution resumes [{Action is true. 



Let's take another look at the switch schematic in Fig. 4,1 before we start 

using the button switch to visualize how the switches affect the I/O pin elec- 
trically. 

The switch labeled A in Fig. 4,1 connects the I/O pin to a 15- V power supply 
through a 10,000-11 resistor. With the switch open, the electrical status of the 
I/O pin is kept high (binary IX When the switch is closed, the I/O pin connects 
to ground, and the status of the I/O pin is brought low (binary 0), 

The switch labeled B in Fig. 4,1 has an electrical function opposite the 
switch labeled A. In this case, when the switch is open, the I/O pin is connect- 
ed to ground, keeping the I/O pin low (binary 0), When the switch is closed, the 
I/O pin is brought high (binary 1). 

In place of a switch, we can substitute an electrical signal, high or low, that 
can also be read using the Button command. 

Typically the Button command is used inside a program loop, where the pro- 
gram is looking for a change of stale (switch closure). When the state of the I/O 
pin (line) matches the state defined in the Down parameter, the program exe- 
cution jumps out of the loop to the Label portion of the program. 



Debouncing a switch 

Debouncing is a term used to describe eliminating noise from electric switches. 
If you took a high-speed electrical photograph, off an oscilloscope, of an elec- 
tric switch closing or opening, the switch's electric contacts make and break 
electric connections many times over a brief {5- to 20-ms) period of time. This 
making and breaking of electric contacts is called bounce because the contacts 
can be easily visualized as bouncing together and separating. Computers, 



Reading I/O Lines 53 

microcontrollers, and many electronic circuits are fast enough to see this 

bouncing as multiple switch closures (or openings) and respond accordingly. 
These responses are typically called bounce errors. Tb circumvent these bounce 
errors, debounce circuits and techniques have been developed. 
The Button command has deb-ounce features built in. 



Auto-repeat 



If you press a key on your computer keyboard, the character is immediately 
displayed on the monitor If you continue to hold the key down, there is a short 
delay, following which a stream of characters appears on the screen. The 
Button command's auto-repeat function can be set up the same way. 

Button example 

To read the status of a switch off I/O pin 7, here is the command we will use 

in the next program: 

Button 7, , 254 , . Bl, 1, loop 

The next program is similar to Program 3,1 in Chap, 3, inasmuch as it per- 
forms binary counting. However, since we are using PB7 (pin 7) as an input 
and not an output, we lose its bit weight in the number we can output to port 
B. The bit weight for pin 7 is 128, so without pin 7 we can display only num- 
bers up to decimal number 127 (255 - 128 = 127), This is reflected in the first 
loop (pin7/bit 7 = 128). 

The program contains two loops; the first loop counts to 127, and the current 
number's binary equivalent is reflected by the lit LEDs connected to port B, 
The loop continues to count as long as switch SW1 remains open. 

When SW1 is closed, the Button command jumps out of loop 1 into loop 2, 
Loop 2 is a noncounting loop in which the program remains until SW1 is 
reopened. You can switch back and forth between counting and noncounting 
states. 

Figure 4.2 is a schematic of our button test circuit. The difference between 
this schematic and the schematic used in Chap, 3 is that we added a 10-kii 
resistor and switch to pin 7 and removed the LED (see Fig. 4,3). 

1 Program 4 . 1 

Symbol TRISE = 134 'Set TRISB to 134 

symbol Per LB =6 'Set Ports to 6 

'Initialize Port(s) 

Poke TRISB,, 12 B 'Set port B pins 1-6 to output, pin 7 to input 

loopl : x Counting loop 

For BO = to 127 

Poke Ports, BO 'Place: BO value at port B to light LEDs 

El = 'Set Button variable to 0: 

Pause 2 50 'Without pause, counting is too fast to see 

Button 7, 0, 254, 0, El , l , loop2 ' check Button status-if closed, jump 

Next BO 'Next. BO value 

Goto loopl 

loop2 : 'Second loop-not counting 



54 Chapter Four 



+ IdpoC"^3r& ^&nnet*e^ "to cr7S"fca.s are £2pFi 



■5V 



©- 



^H* fo^jfa*fe,«fe 



if 




VDD 



HI LP 



D^C 



n5'7c 



RS)/]Nf 






VSE- 



Figure 4,2 Schematic of test button circuit. 



J] 



'4.7Xn 



CI 



Lb 






15 






PIC 16F8^ 




Figure 4,3 Photograph of test button circuit. 



Reading I/O Lines 55 

Poke ports, 'Turn off all LEDs 

El= % Set Button variable to zero before use 

Button 7, 1, 254 , 0, El , 1 . loopl 'Check Button status-if open, jump back 
Goto loop2 

When the program is run., it begins counting. When the switch is closed,, all 
the LEDs turn oi¥ and it stops counting. When the switch is opened, the count- 
ing resumes, starting from 0. 



Dynamic Changes 



The previous program used one switch to start and stop the counting function. 
Now let's use two switches to dynamically modify the program as it is running. 
What dynamic modification could we make? How about changing the timing 
delay? 

Now we need two switches: one switch to decrease the delay to make count- 
ing go faster, and the other switch to increase the delay to make it go slower 
To connect another switch, we need to borrow another port B line, I decided to 
use line PB6, to monitor another switch status (see schematic in Fig. 4,4 and 
photograph of project in Fig. 4.5). The switch connected to PB7 incrementally 
increases the timing delay to a 1-s maximum time. The switch connected to 
PB6 incrementally decreases the delay to approximately 10 ms. At a 10 -ms 
time delay, the LEDs will be counting so fast it will appear as if all the LEDs 
were lit simultanoously. 



1 Program 4.2 
symbol TRISE = 134 
symbol TRISE = € 

El = 0;B2 = 
Symbol delay = W4 
W4 =25 

'Initialize Port(s) 
Poke TRISB, 192 

loopl : 

For BO = o to 63 
Poke Ports, BO 
Pause delay 

El = 0: B2 = 

But ton 7, 0, 1, , EI , 1, loop2 

Button 6, 0, l, 0, E2 , l . loops 

Next BO 

Goto loopl 

loop2 : 

delay = delay + 10 

El = : Pause 100 

Button 7,, l,, l, 0, El , l , loopl 

If delay > 10 00 Then holdl 
Goto loop2 



'Set TRISE to 134 

'Set Ports to a 

'Initialise delay variable 
'Initialize variable to 2 50 -ms delay 

l Set port B pins 0-5 to output, pins 6 and 7 to 

'input 

'Main counting loop 

'Place SO value at port to light LEDs 

'Without pause, counting is too fast to see 

*Set to before using in Button command 

'Check swi status - if closed jump 

'delay the same 

'Check SW2 status-if closed, jump 

'delay the same 

l Next B0 value 

l loop2 increases time delay 
'Increase delay by 10 m.s 

'Check button status— if opened, jump 

1 increasing 

1 don't go over l-s delay 



56 Chapter Four 



Capacitors connected "to crystals <ire 22pF 



-5V 



]LTV 



-5V 



rj 








'4^1* 



red 



♦TO 



R5 

^7U 



-?>V 



■:> 






P3 

*70r. 



HTQd 



-±^ H ; i Dt ^ i i D3 - -i D -. : ^ :i 

■TV^a T-red -T-rcd JL r»d "Tr 



J±J. 



Ill 






VDD 



U 



HCLF:' 



Li? 



* 



■GS2 

.CO I 

■PSD /INF 



Q'aC L 



Q-ZC± 



L* 












L= 



1=1 



3- 



L3 
L7 



;-!P*t/T(JC<[ 
tiftAS 



RAL 



IT- 



PI C ltF84 



Figure 4.4 Schematic of multiple button test circuit. 




Figure 4-5 Photograph of multiple button test circuit. 



Reading I/O Lines 57 



loop3 : l second loop decreases delay 

delay = delay - 10 * Decrease delay by 10 ins 

B2 = o : Pause 10 

Button 6, l, l, D,E2 , l , loopl l check button status^if opened,, jump 

"■decreasing 

If delay < 20 Then hold2 u Not less than 10- ms delay 
Goto loop 3 

holdl : "Maintain delay at upper limit 

do lay = 100 x Maximum delay 

Goto loop2 l Re turn to the calling loop 

hold2 : "Maintain delay at lower limit 

delay =10 "Minimum delay 

Goto loop3 "Return to the calling loop 



Program 4.2 Features 



lf..Then 



We have introduced a few new program features; let's review them now before 
we continue. Primarily we wrote a standard Basic-language decision-making 
(If-Then) command line. 



In this program, the If ..Then is used to limit the upper and lower limits of the 
timing delay between increments in the binary counting- In standard Basic, 
this line would appear as 

If delay > 10 00 Then delay = 100 

This line would effectively limit the upper limit to 1000 ms or 1 s. However, in 
the PIC Basic compiler language, the If. .Then command cannot, he used in this 
way. While we still have the ability to test two variables with a comparison, 
the Then portion of the If .Then is essentially a Goto, 

If comparison {and/ or comparison) Then LaJbel 

If the condition is true, the program will perform a Goto to the label men* 
turned after Then. If the condition is false, the program continues on the next 
line after the IF. .Then. Let's look at this using a few examples. Suppose the 
variable delay is equal to 1010. The line 

If delay > 10 00 then holdl 

would cause the program execution to jump to the label holdl and continue on 
from there. 

On the other hand, if the delay variable is equal to 990, no action would be 
taken by the line 

If delay > 1000 then holdl 

and program execution would continue on to the next line. 

Unlike the standard Basic language, another statement may not be placed 
after Then. You can only use a Label after Then. 



58 Chapter Four 



For instance the line 

if delay > 1000 then delay = 1000 

is not allowed in PIC Basic, 

Like the standard Basic language, there are multiple comparisons available, 
You can use the following comparisons in the IE /Then command line: 

Var {< f <=, =, <> f >= f >} Value 



Comparison 


Meaning 


< 


Less than 


< = 


Less than or equal to 


= 


Equal to 


<> 


Not equal to 


> = 


Greater than or equal to 


> 


Greater than 



All comparisons must be unsigned. The compiler supports only unsigned 
types. The variable in the comparison must appear on the left. 

In this program, we limit the delay value in the If. .Then line by jumping to 
a small subroutine called holdl if that condition is true. The holdl subrou- 
tine performs the limit function for us. 

If delay > 10 00 Then holdl 

holdl : 

delay = 100 'Maximum delay 

Goto loop2 'Return to the calling loop 

This is a somewhat convoluted way to accomplish the task needed, but it 
works. 



Word variable 



Notice that our delay variable is a 2-byte word variable W4. Can you figure out 
the reason why we need a 2-byte variable? If you think it's because a 1-byte 
variable can hold only a maximum number of 255, and our delay can go up to 
1000, you are right- In order to hold a number greater than 255, we need to 
use at least 2 bytes. So what is the maximum number our 2-byte variable can 
hold? The answer is 65,535. If we used the maximum delay our 2-byte W4 vari- 
able allowed, we would have to wait more than a minute (65,5 s) for each incre- 
ment in the count. 



The Variables Used in Button 



The Button command line states that the byte variable used for delay/repeat 
countdown should be set to initialized to zero prior to use. 



Reading I/O Lines 59 



Multiple Statements — Single Line 



Peek 



As with the standard Basic language, we can place multiple statements on a 
single line. The statements must be separated by a colon (:), The fourth line in 
program 4.2 is an example: Bl = 0:B2 = 0. Here we set the values of variables 
Bl and B2 to zero. 



We can also use the Peek command to check the status of any input line. The 
advantages of the Peek command are as follows: Using Peek, one can read the 
live I/O lines of port A (or the eight I/O lines of port B) at once. This increases 
the versatility of the PIC chip and allows our program to be more concise (leas 
convoluted), shorter, and easier to read. 

To emphasize these points, let's rewrite our last program using the Peek 
command. This program uses the schematic shown in Fig. 4,6. 

Looking at the schematic we can see the RAO and RA1 lines are normally 
kept high (15 V), binary 1 through the 10-kfi resistor. When a switch is closed, 
it connects the pin to ground and the line is brought down to (ground) binary 0. 

A photograph of this project is shown in Fig. 4 J, 



symbol trisb = 134 
Symbol TRISA =13 3 
Symbol PortB = B 
Symbol Port A = 5 
Symbol delay = W3 
W3 = 250 

'Initialize Port (a 
Poke TRISB, 



l set Data Direction Register port B 
l Set Data Directory Register port A 
'Initialize PortB to 6 
'Initialize PortA to 5 
l Set up delay variable 
initialize delay value 

L Set port B pins as output 



+ Sopooto^s conne-cte-d *o zry st»ie are tcpK 



i ■.* * 






>7D 



>4TD 






rj »yg 



P5 

H?|] 



H7C 



l?4 



h P£ 



[ 



-Z't 



fllfl ! /I?L1 



13 



1L 



III 



rm; 
Cut 



J=E 



t 



3L 



^ rt *4-' *^ti» tiw iioa iioz iAm "-L % 



-U 



VDD 



H£lG' 



KUM 

EDO 

P:fi. J 



USC 3 



|-|Fi". a 



HI] 

hm/:nt 

PAHJTDCKC 
Ml 

*55_ 



■J 

16- 






Ji 






PJC l*FS* 



-3] 

'.iff 



Figure 4,6 Schematic using Port A lines, for push buttons. 



60 Chapter Four 




Figure 4.7 Photograph of project using Port A lines for buttons. 



Poke TRISA,3 
loopl : 

For B2 = to 255 
Poke Forts, B2 
pause 250 

Peek Port A, E0 

if bito = o Then loop2 

If bitl = Then loop3 

Next E2 

Goto loopl 

Ioop2 : 

Poke FortE, 

delay = delay + 10 

pause 100 

If delay > 10 00 Then holdl 

Peek Port A, BO 

If bito = l Then loopl 

Goto loopl 

loop3 : 

Poke Ports, 

Peek PortA, SO 

If bit l = l Then loopl 



'Set pin l and pin 2 of port A as input 
* Counting loop 

'Place E2 value at port to light LEDs 

'Without pause, counting proceeds too fast to 

1 see 

'Peek sw status on PortA 

'if swi is closed, jump to loop2 

'If SW2 is closed, jump to loop3 

'Next B2 value 

'Repeat 

'Increment binary counting delay 

'Turn off all LEDs 

' Increase delay by 10 ms 

'Delay or timing changes too quickly 

'Not over 1-s delay 

'Peek swi status on PortA 

'If opened, jump back to loopl 

' Repeat 

'Decrement binary counting delay 

'Turn off all LEDs 

'Peek SW2 status on PortA 

'If opened, jump back to loopl 



Reading I/O Lines 61 

delay = delay - 10 'Decrease delay by 10 tns 

If delay < 10 Then hold2 'If less than 10 ms , hold at 10 

Goto loop3 'Repeat 

holdl : 'Hold at l-s routine 

delay = 990 

Goto loop2 

hold2 : 'Hold at lo-ms routine 

delay = 2 

Goto loop 3 

Program 4.3 may appear as large as Program 4,2, but there is a major dif- 
ference: Program 4.3 is utilizing both ports on the PIC 16F84. We can easily 
see the impact this has by looking' at the schematic in Fig. 4.6. 

In this schematic, we are using the entire port B to light eight LEDs, Since 
we can use the entire port B, we can count to decimal 255, We can do this 
because we can connect the two switches to port A- Incidentally, I could have 
reduced the size of this program by eliminating the lines for the TRISA setup. 

If you remember, upon start-up or reset, all port lines are configured as 
input lines. Since this is how we need port A set up, I could have eliminated 
those lines dealing with the THIS A- Instead I decided to show a standard port 
A setup, even though it wasn't needed in this particular application, as an 
example setup. 



New Features 



Program 4.3 introduced a few new features. The first new command used is 
the Peek command. The Peek command structure is as follows: the command 
Peek is followed by a memory address, then a comma, then a storage variable. 

Peek Addr&ss t Var 

As its name implies, the Peek command allows one to view (or peek at) the 
contents of a specified memory address. Typically the memory address "peeked 
at* is one of the PIC microcontroller's registers. The peeked value is stored in 
a variable Var defined in the command. 

In this program we peeked at the input lines on port A. (Remember,, the lines 
on port A cannot be read using the Button command.) The Peek command 
allows us to look at the two input lines on port A simultaneously. 

Peek Port A, B0 

The Peek command can read an entire byte (8 bits) at once; or, as in the case 
of port A 5 bits, only the lower 5 bits of the peeked value are relevant. 



BitQ.. Bitt 5 



The first 2 bytes of RAM memory, BO and Bl, are special. This is because we 
can test the bit values contained in each byte. IF you remember, for byte B0, 
the bit variables are predefined as BitQ through Bit 7. For byte Bl, the prede- 
fined bit variables are Bit8 to Bit 15. 



62 Chapter Four 



The next two commands used in the program use the bit variables to allow 
us to look at and test the individual bits that make up byte BO, 

If bito = Than loop2 
If bitl = Then loop3 

The logic of the program follows, just before we tested the bit values we 
peeked Port A and saved the results in variable BO. 

Fe#k Fort A t BO 

Then we tested the bits in variable BO using the predefined BitO and Bit! 
variables in the If,. Then commands to see if a switch was closed on either line. 
If it was, the program jumped to the proper subroutine. 



Programming challenge 



Rewrite Program 4,1 using the Peek command instead of the Button com 
mand. The solution is in the Appendix. 



Basic Input and Output Commands 



In our programs., we directly wrote (using the Poke command) to the PIC 
microcontroller TRIS registers (A or B) to set various pins to be either input or 
output lines. By Pokeing the TRIS register, we are able to configure the eight 
pins to port B at one time. In addition, and more important., we can configure 
the five open pins on port A as well. 

However, the PICBasic compiler has two Basic commands for making pins 
either input or output lines. These commands are Input and Output. 
Unfortunately, these two commands work only on port B pins, 

input Pin 

This command makes the specified pin an input line. Only the pin number 
itself, i,e,> to 7, is specified {e.g., not PinO), 
Sample usage: 

Input 2 'Hakes pin 2 an input line. 

The opposite of the input command is the output command, 

output Pin 

This command makes the specified pin an output line. Only the pin number 
itself, i,e.j, to 7, is specified (e.g., not PinO). 
Sample usage: 

Output 'Makes pin an output line. 

Okay, we have established a Foundation on PIC microcontrollers that allows 
us to work on applications. But before we do„ I want to offer a few tips that will 
make programming easier. 



Reading I/O Lines 63 



ZIF Adapter Sockets 



If you have been programming the sample programs into a 16F84> you proba- 
bly realize by now that it is troublesome and inconvenient to insert, the 16F84 
microcontroller into and remove it from the standard socket on the EPIC pro- 
gramming board. 

There is an 18-pin ZIF (zero- force insertion) socket adapter for the EPIC] 
board that allows you to remove and insert the 16FS4 easily and quickly (see 
Fig, 4.8). 

I recommend purchasing the ZIF adapter because it saves a considerable 
amount of time and hassle, not to mention bent ping. 




■ 



Figure 4.6 ZIF sockets. 









64 Chapter Four 
ZIF Socket 



While this is not as critical as the ZIF socket adapter for the EPIC program- 
ming board;, I also placed an 18-pin ZIF socket on my solderless breadboard. 

This allowed me to move the PIC between testing and programming boards 
quickly. 



AC Adapter 



The stock EPIC programming board requires two fresh 9-V batteries. An ac 
adapter that eliminates batteries is available. These three additions to your 
programming arsenal will make programming PIC microcontrollers easier- 



Parts List 



Same components as Chaps, 1 and 3 



Additional components 



(2) 10KO V 4 W resistors 

(2) PC mount push-button switches, normally open (N,0.) 



Optional components 



ZIF socket adapter for programming board 
ZIF socket for solderless breadboard 
AC adapter For programming board 



Chapter 




PICBasic Language Reference 



Before we proceed further into PICMicro applications and projects, this chap- 
tor is devoted to the PICBasic language commands that are available to us. 
The following is a list of PICBasic commands with a quick description. This is 
follow&d by a complete description of each command, in alphabetical order. 

Branch Computed Goto (equivalent to On, . .Goto) 

Button Input on specified pin. 

Call Call assembly language subroutine at specified label. 
Eeprom Define initial contents of on-chip EEPROM- 
End Stop program execution and enter low-power mode. 
For.. Next Execute a defined For-Next loop- 
Gosub Call Basic subroutine at specified label 
Goto Jump program execution to specified label. 
High Make specified pin an output and bring it high, 
I2cin Read bytes from I 2 C device. 
I2cout Write bytes to I a C device. 
If.-Then Compare and Goto if specific condition is true- 
Input Make specified pin an input. 
Let Perform math and assign result to variable, 
Lookdown Search table for value. 
Lookup Fetch value from table- 
Low Make specified pin an output and bring it low- 
Nap Power-down processor for short period of time. 
Output Make specified pin an output. 
Pause Delay ( 1-ms resolution)- 
Peek Read byte from PIC microcontroller register. 
Poke Write byte to PIC microcontroller register- 
Pot Read potentiometer on specified pin. 



6S 



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



66 Chapter Five 



Branch 



Button 



Pulsin Measure pulse width (10-jia resolution), 

Pulsout Generate pulse (10-jjls resolution). 

Pwm Output pulse-width-modulated signal from pin. 

Random Generate pseudorandom number. 

Read Read byte from on-chip EEPROM. 

Return Return from subroutine. 

Reverse Reverse I/O status of pin; input becomes output and vice versa, 

Serin Asynchronous serial input (8N1). 

Serout Asynchronous serial output (8N1). 

Sleep Power-down proce ssor ( 1- s resolution >. 

Sound Generate tone or white noise on specific pin. 

Toggle Make specified pin an output and toggle state. 

Write Write byte to on-chip EEPROM. 



Branch Offset,. (Label 6 1 Label 1 , . . . s Label X) 

Uses Offset (byte variable) to index into the list of labels. Execution continues 
at the indexed label according to the Offset value. For example, it Offset is 0, pro- 
gram execution continues at the first label specified (LabelO) in the list. If the 
Offset value is 1„ then execution continues at the second label in the list. 

Branch Ba , ( label l, lab«l2, label3) 

If B8 = G, then program execution jumps to label 1. 
If B8 = 1, then program execution jumps to label2. 
If B8 = 2, then program execution jumps to labels. 



Button Fin, Down, Delay, .Rate, Var, Action f Label 



Pin Pin number (0 to 7), port B pins only. 

Down State of pin when button is pressed (0 or 1). 

Delay Delay before auto-repeat begins, to 255. 

Rate Auto- repeat rate, to 255 

Var Byte-sized variable needed for delay repeat. Should be initialized to 

before use. 

Action State of pin to perform Goto (0 if not pressed, 1 if pressed). 
Label Point at which program execution continues if Action is true. 

Figure 5.1 shows the schematic for tw r o styles of switches that may be used 
with this command. 



Call 



Eeprom 



End 



PIC Basic Language Reference 67 



Button r r 255 r r B0, , Loop 



This checks for a button pressed on pin and does a Goto to Loop if it is not 
pressed. 



call Lab&l 

Jump to an assembly language routine named Label. 

Call storage 

This jumps to an assembly language subroutine named storage. Before pro- 
gram execution jumps to the storage routine, the next instruction address 
after the Call instruction is saved. When the Return instruction is given by the 
storage routine, the previously saved instruction address is pulled, and pro* 
gram execution resumes at the next instruction after Call. 



Eeprom Location, [constant, constant ( . . . , consuant) 

This command stores constants in consecutive bytes in on-chip EEPROM. It 
works only with PIC microcontrollers that have EEPROM, such as the 16F84 
and 16C84. 

Eeprora 4, (ID, 7 1 3) 

This stores 10, 7, and 3, starting at EEPROM location 4. 



End 



A 



+5V 

o 



LOfcfi- 



-\ 



SW c 



+5V 
? 



B 



SW 



I/O Pin 

c 



I/O Pin 



JD<n 



Figure 5.1 Schematic switches used for Button command. 



68 Chapter Five 



For.. Next 



This command terminates program execution and enters low-power mode by 
executing continuous Nap commands. 



For Index = Start to Stop (SCep [-} Inc) 

Body 
Next Index 

Index is the variable holding the initial value Start. 

Start is the initial value of the variable. Step is the value of the increment. 
If no Step value is specified, it is incremented, by 1 each time a corresponding 
Next statement is encountered. The Step increment value may be positive or 
negative. If Step and Inc are eliminated, the step defaults to positive 1. 

Stop is the final value. When Index = Stop, the corresponding Next state- 
ment stops looping back to For, and execution continues with the next 
PICBasic statement. 

Body is Basic statements that are executed each tinie through the loop. Body 
is optional and may be eliminated, as is the case in time-delay loops. 



For BO = to 127 
Poke FortE, BO 
Next BO 



1 Place BO value at port to light LEDs 
'Next BO value 



Gosub 



This program snippet is from Chap. 4. 



Gosub Label 

Program execution jumps to statements beginning at Label. A Return state- 
ment must be used at the end of the Label subroutine to return program exe- 
cution to the statement following the Gosub statement. 

Gosub statements may be nested. However, nesting should be restricted to 

no more than Four levels. 



GOL-ub wink 



wink; 
High o 
Pause 500 
Low 
Return 



'Execute subroutine named wink 
'Program execution returns to here 
'Other programming goes here 

'Label wink 

'Bringing pin high lights LED 

'Wait 1/2 s 

'Bringing pin low turns off LED 

'Return to main routine 



Gosub nesting 



Nesting is the term used to describe a second Gosub routine called from with- 
in a previous Gosub routine. Because of memory limitations Gosubs can only 
be nested to a maximum of four levels deep. 



Goto 



PICBasic Language Reference 69 



Goto Lab&l 



Program execution jumps to statements beginning at Label 



Goto loop 

loop:: 

For bO = 1 to 10 
Poke ports, bo 
Next 



'Program execution jump to statements beginning at 
1 loop. 



High 



High Pin 

This command makes the specified pin an output pin and brings it high (+5 
V). Only the pin number itself, to 7, is specified in the command. This com- 
mand works only on port B pins. 



High 2 



'Make pin 2 (RB2) an output pin and bring it high 
1 C+5 v) 



I2cin 



1 2 c i n Con trol f Address f Va r 



var] 



This command allows one to read information from serial EEPRQMs using a 
standard two-wire PC interface. The second f , Var) shown in the command is 
used only for 16-bit information. Information stored in a serial EEPROM 
is nonvolatile, meaning that when the power is turned off", the information is 
maintained. 
Here is a list of compatible serial EEPROMs. 



Device 



Capacity 



Control 



Address size 



24LC01B 


128 bytes 


OlOlOxxx 


3 bits 


24LC02B 


25G bytes 


OlOlOxxx 


8 bits 


24LC04B 


512 bytes 


OlOlOxxb 


8 bits 


24LC08B 


IK bytes 


QlOlGxbb 


8 bits 


24LC16B 


2K bytes 


OlOlObbb 


8 bits 


24LC32B 


4K bytes 


HOlOddd 


16 bits 


341.065 


SK bytes 


llOlOddd 


16 bits 



bbb = block selects bits fee,ch block = 256 
ddd = device selects bits. 
xxx = don't care. 



The high-order bit of the Control byte is a flag that indicates whether the 
address being sent is 8 or 16 bits- If the flag is low (0), then the address is 



70 Chapter Five 



8 bits long. Notice that EEPROMs 24LC01B to 24LC16B have the flag set 
to zero (0). 

The lower 7 bits of Control contain a 4-bit control code, followed by the chip 
select or address information. The 4-bit control code for a serial EEPROM is 
1010. Notice that in all the listed serial EEPROMs, this same 4-bit control 
code follows the high-bit flag. 

The I 2 C data and clock lines are predefined in the main PlCBasic library. 
The PC lines are pin (data) and pin 1 (clock) of port A. The 1 2 C lines can be 
reassigned to other pins by changing the equates at the beginning of the I 2 C 
routines in the PEL . INC file. 

Figure 5-2 is a schematic of a 24LC01B connected to a PIC 16F84. 



If.. Then 



symbol control = £01010000 
Symbol address = Be 

address = 32 

I2cin control, address, 



B2 



'Set variable address to B6 
'Set address to equal 32 
1 Read data from SEPROM 
'address 12 into B2 



l2cout 



I2cout Control, Address, Value { f Value) 

The I2cout command allows one to write information to serial EEPROMs 
using a standard two-wire I 2 C interface. The second (, Value) shown in the 
command is used only for 16-bit information. Information stored in a serial 
EEPROM is nonvolatile, meaning that when the power is turned off, the infor- 
mation is maintained. 

When writing to a serial EEPROM, one must wait 10 ms (device-dependent) 
for the Write command to complete before communicating with the device 
becomes possible. If one attempts a I2cin or I2cout before the Write (10 ms) is 
complete, the access will be ignored. Using a Pause 10 statement between mul- 
tiple writes to the serial EEPROM will solve this problem. 

Control and Address are used in the same way as described for the I2cin 
command. 



Symbol control = &01010DOO 
Symbol address = EG 

address = 32 

l2cout control, address, ^16 

Pa-jise 10 

address =33 

I2cout control, address , (21 

Pause 10 



'Set variable address to BG 

'Set address to equal 32 

'Write data number 16 to the l EEPROM 

l at address 32 

'Wait ID ms for write cycle 

'to complete. 



If comp Then Label 

This command performs a comparison test. If the particular condition is met 
(is true), then the program execution jumps to the statements beginning at 



PICBasfic Language Reference 71 



+ 5Y.' ^ 






E 



AO Vcc 

Al 

A£ 

■IDA -i- 



13 
LJ 

a" 
?" 

3 
i" 

2* 



:j 



__ EVLCC']B 



il 



VDD 



f?E7 

RBI 

RBWWT 



H-LR- 



ClEiCl 



osca 



PA? 

RAE 
RAO 



El 



Jt 



*1 

HMMz 



CD 



C3 
.] 



-."- 



PlLlaFSH 



Figure 5.2 Serial EEPROM interface. 



Label. If the condition is not true, program execution continues at the 
next line. 

The Then in the If^Then is essentially a Goto. Another statement cannot be 
placed after the Then; what follows must be a label 

The command compares variables to constants or to other variables. If only 
one variable is used in a comparison, it must be placed on the left. All com- 
parisons are unsigned. 

The following is a list of valid comparisons: 



= 


Equal to 


< 


Greater than 


> 


Less than 


<> 


Not equal to 


<= 


Less than or equal to 


>= 


Greater than or equal to 



If BS <= 2B Then loop 

If the value in variable B8 is less than or equal to 25, then the program jumps 
to loop. 

Binary logic comparisons 

The If .Then command may also be used with two binary logic comparisons, 
AND and OR. 



Input 



input Pin 



72 Chapter Five 



Let 



This command makes the specified pin an input pin. Only the pin number 
itself, to 7, is specified in the command. The command works only on port 

E pins, 

input l "Make pin l {RBI) an input. 



Let Var = value 

Optional: 

where Value = DP value 

Let assigns a value to a variable. 

The value assigned may be 

1. A constant (Let Bl = 27) 

2. The value of another variable (Let Bl = B2) 

3. The result of one or more binary (math) operations 

The operations are performed strictly left to right and all operations are per* 
formed with 16-bit precision. 
Valid operations are 



- 


Addition 


- 


Subtraction 


+ 


Multiplication 


■■[■■■■:= 


Moat significant bit of multiplication 


/ 


Division 


// 


Remainder 


MIN 


Minimum 


MAX 


Maximum 


& 


Bitwise AND 


■ 


Bitwise OR 


A 


Bitwise XOR 


&/ 


Bitwise AND NOT 


:/ 


Bitwise OR NOT 


A/ 


Bitwise XOR NOT 



Sample operations: 

Let Bl = 34 "Assign variable Bl the value of 3 4 {"Let" is optional } 

Let Bl = EO / 2 'Assign variable Bl to BO ' s value shifted right one bit 

x {divided by 2} 

When two 16 -bit numbers are multiplied, the result used is the lower 16 bits 
of the 32-bit answer. 



PICBasic Language Reference 73 



Let Wl = WO * 256 



x Multiply value held in wo by 256 and 
v place result in wi (lower lfi bits) 



If you require the higher-order 16 bits, use the following command: 



Let Wl = WO ** 25 6 



'Multiply value held in WO by 256 and 
'place result in Wl (upper 16 bits) 



Lookdown 



Bitwise operations use standard binary logic and 8-bit bytes, 



El = 101100000 
B2 = 100100010 
Let B2 = B2 k Bl 



The resultant E2 will be %001QQO0Q. 



Lookdown Sval[i& f [cv&lueo t cvaluel, . . . r cvalu&N) , rvalue 

where svalue = search value 

cvalueX = constant values 

rvalue = result value 

The Lookdown command searches through a list of constants (cvalueO > cval- 
uel ? etc.) , comparing each value in the list to the search value (Svalue). If a 
match is found, the physical number of the term (index number) in the list is 
stored in the rvalue (result value) variable. 
A simple example will straighten out any confusion. 



Lookdown 5, {"16, 34, 21, 13, 7 



9, 10, 5 2") f BO 



The command searches through the list of constants and stores the item num- 
ber in BO. In this example, BO will hold the result of 8- (Lookdown begins 
counting from 0, not 1. ) Commas are used to delineate multiple-digit numbers, 

The constant list may be a mixture of numeric and string constants. Each 
character in a string is treated as a separate constant with the character's 
ASCII value. 

If the search value is not in the lookdown list, no action is taken and the val- 
ue of rvalue remains unchanged. 

ASCII values as well as numeric values may be searched. 

serin l, N24 0,E0 'Get hexadecimal character from pin l serially 

Lookdown BO, ( "0123456 7 B9ABCDEF" ) , Bl 

'Convert hexadecimal character in BO to 
'decimal value in Bl. 
serout 0,N240D, {#BD 'Send decimal value to pin serially. 



Lookup 



Lookup Index, {cvalueO, c value 2, . .., (cvalueN) , Value 



74 Chapter Five 



Low 



Nap 



The Lookup command is used to retrieve values from a table of constants 
(cvalueQ) cvaluel, etc.)- The retrieved value is stored in the Value variable. If 
the index is zero ? Value is set to the value of cvalueQ. If the index is set to 1,. 
then Value is set to the value ofcvaluel* and so on. 

If the index number is greater than the number of constants available to 
read, no action is taken and Value remains unchanged. 

The constant may be numbers or string constants. Each character in a 
string is treated as a separate constant equal to the character's ASCII 
value, 

For BO = to E5 "Set up For. .Next loop*p900X 

Lookup BQ r (" Hello l") % Get character number BO from 

"string and place in variable El 
Serout Q..N2400, (Bl) % 5end character in El out on pin 

'serially. 
Next BO H Do next character. 



Low Pin 

This command makes the specified pin an output pin and brings it low (0 V). 
Only the pin number itself, to 7, is specified in the command. The command 
works only on port B pins. 

Low 'Make pin {RBO) an output pin and bring it low 

1 ( v J 



Hap Period 

This command places the PIC microcontroller in low-power mode for varying 
short periods of time. During a Nap, power consumption is reduced to a mini- 
mum. The following table of times is approximate, because the timing cycle is 
derived from the on -board watchdog timer> which is R/C driven and varies 
from chip to chip (and with temperature). 

Period Delay (approximate) 






18 ms 


] 


36 ms 


2 


72 ms 


:-.: 


144 ms 


4 


233 ms 


u 


576 ms 


6 


1.15 s 


7 


2.3 s 



Output 



Pause 



PICBasic Language Reference 75 



Nap 7 



Low-power pause for 2.3 s 



The watchdog timer must be enabled in the EPIC software (see EPIC 
Software) for Nap and Sleep commands to function. If Nap and Sleep com- 
mands are not used, the watchdog timer may be disabled. 



Output Pin 

This command makes the specified pin an output pin. Only the pin number 
itself, to 7, is specified in the command. The command works only on port B 
pins. 

Output 5 'Make pin 5 (RB5) an output. 



Peek 



Pause Period 

This command provides a pause in program execution for the Period in mil- 
liseconds. Period is a 16-bit number that can hold a maximum value of 65,535, 
In milliseconds, that works out to just over one minute (60,000 ms). Unlike the 
other delay functions, Nap and Sleep, the Pause command does not put the 
microcontroller into a low-power mode. This has both an advantage and a dis- 
advantage. The disadvantage is that Pause consumes more power; the advan- 
tage is that the clock is more accurate. 



Pause 2 50 



"Delay for 1/4 s 



Peek. Address, variabl* 

The Peek command reads any of the microcontroller's registers at the Address 
specified and copies the result in Var* This command may be used to read spe- 
cial registers such as A/D converters and additional I/O ports. 

Peek reads the entire 8 bits of the register at once. If extensive bit manipu- 
lation is needed, the user may store the results of the Peek command in either 
B0 or Bl. These two bytes may be also be used as bit variables BitO to Bitl5, 
and extensive bit manipulation is easily performed. Byte B0 is equivalent to 
BitO to Bit 7, and byte Bl is equivalent to Bit8 to BitlS, 

The following example shows how one can check bit status. It assumes that 
the five open pins on port A have been configured as input pins. 



loop; 



Peek PortA, B0 



If BitO = 
If Bitl = 
If Bit2 = 



l Then rout el 
1 Then route2 
1 Then route 3 



'Read port A pins and -copy result 
'into byte B0. 

'If RAG is high, jump to routel 
'If RAl is high, jump to route2 
'If RA3 is high, jump to routed 



76 Chapter Five 



Poke 



If Bit 3 = Then routel 
If Bit 4 = Then routel 
Goto loop 



% lf RA4 is low, jump to rout el 
'If RA5 is low, jump to route2 



The example shows that bits may be checked for high or low status. The 
Peek command also works with pins that are configured as outputs. When 
peeked;, the resultant shows the binary value that has been poked in the 
port register. 



Pot 



Poke Address, Variable 

The Poke command can write to any of the microcontroller's registers at the 
Address specified and copy the value in Var to the register. This command may 
be used to write to special registers such as A/D converters and additional I/O 
ports. 

Poke writes an entire byte (8 bits) to the register at once. 



Poke 134,0 



1 Write binary to DDR for port B r making all pins 
1 output lines. 



Pot Pin, scale, var 

This command reads a potentiometer or other resistive transducer on the Pin 
specified. The programmer may choose any of the port B pins, to 7, to use? 
with this command. 

Resistance is measured by timing the discharge of a capacitor through 
the resistor, usually 5 to 50 kO. Scale is used to adjust varying R/C con- 
stants. For large R/C constants, set Scale to 1. For small R/C constants, set 
Scale to its maximum value of 255, Ideally, if Scale is set correctly, the vari- 
able Var will be set to zero at minimum resistance and to 255 at maximum 
resistance. 

Scale must be determined experimentally Set the device or transducer to 
measure at maximum resistance and read it with Scale set to 255. Under 
these conditions, Var will produce an approximate value for Scale. 

There are many resistive-type transducers that may be read using the Pot 
command. The important thing that distinguishes this command from an ana- 
log-to-digital (A/D) converter is that a converter measures voltage, not resis- 
tance. [Although the voltage drop across the converter may seem to be similar 
to the Pot diagram (Fig. 5.3), it is not J 



Pot 3,2 55. BO 



Eerout 0,N24 0Q, (#B0) 



'Read potentiometer on pin 3 to 
'determine scale. 
'Send pot values out on pin 
'serially . 



PICBasic Language Reference 77 



Pulsout 



YL 



5-"50Krr 



Pin 



CI 



Figure 5.3 Pot command test circuit. 



Pulsin 



Pul sin Pin, state r var 

This command measures the pulse width in 10-)jls increments on the Pin spec- 
ified- II' State is 0, the width of the low portion of the pulse is measured. If 
State is 1, the width of the high portion of the pulse is measured. The mea- 
sured width is stored in variable Var\ The variable Var is a 16-bit number and 
therefore can contain numbers from to 65,535, To calculate the measured 
pulse width, multiple Var by 10 (jls. 

Var * 10 jxs = measured pulse width 

Pulse widths from 10 to 655,350 pus can be measured. 

If the pulse width is larger than the maximum width the microcontroller can 
measure, Var is set to zero. If an 8-bit variable is used for Var, only the lower 
byte (LSB) of the 16-bit measurement is stored. This command may use any 

port B pin from to 7, 



Pulsin 2, 0, W2 



1 Measure low pulse on pin 2 (RE2) and 
'place width measurement * 10 jls in 
l W2 



Pulsout Fin f Period 

This command generates a pulse on the Pin specified. The pulse width is spec- 
ified by Period. The variable Period is a 16-bit number that can range from 
to 65,535. The pulse width is calculated by multiplying the variable Period by 
10 pa; 

Period * 10 jjls = pulse width 

Therefore, pulse widths from 10 to 655,350 jjls may be generated. 

Pulses are generated by toggling the pin twice. Thus, the initial state of the 
pin ? or 1, determines the polarity of the pulse. 



78 Chapter Five 



As a result , if the initial state of the pin is low, Pulsout outputs a positive 
pulse. On the other hand, if the initial state of the pin is high ( + 5 V), 
Pulsuut outputs a negative (0 V) pulse- This command may use any port B 
pin from to 7- The pin used is automatically made into an output pin. 



LOW 6 



Pulaout 6 S 1000 



l Set pin 6 {RB6) to an output and bring it 

l low 

l Send a positive pulse 1D,D0D jlls (10 

1 itls) long out on pin 6 (RBG) . 



Pvvm 



Pwm Pin t Duty t Cycle 

This command outputs a pulse-width-modulation (PWM) train on the Pin 
specified. Each cycle of PWM consists of 256 steps. The Duty cycle for 
each PWM ranges from (0 percent) to 255 (100 percent). This PWM 
cycle is repeated Cycle times. This command may use any port B pin from 
to 7, 

The pin is made an output just prior to pulse generation and reverts to an 
input after generation stops. Thus allows a simple R/C circuit to be used as a 
simple D/A converter. 

The test circuit for this command is shown in Fig. 5.4. 



Fwm 7,126,155 



x Send a. 50 percent duty cycle PWM signal out on 
l pin 7 (RB7) for 155 cycles. 



Random 



Note: If the PWM command is used to control a high-current device, the out 

put signal should be buffered. 



Random Var 



This command generates a pseudorandom number in Var. The variable Var 
must be a 16-bit variable. Random numbers range from 1 to 65 5 635 (zero is not 
produced). 



Pin 



RL 



Analog Out 






Figure 5.4 PWM test circuit. 



PICBasic Language Reference 79 



Serin 



Random W2 



'Generate random number in W2 



Read 



Read Address, Var 

This command reads the on-chip EEPROM (if available) at the specified 
Address; the resultant byte at the address is copied into the Var variable. If 
Address is 255, Var returns with the number of EEPROM bytes available. This 
instruction may be used only with microcontrollers that contain on-chip EEP- 
ROM, such as the 16F84. 



Read 5, BO 



'Read EEPROM location number 5 and copy 
*into BO. 



Return 



Return 



This command causes program execution to return from a called Gosub 
command. 



Gosub sendl 



l Jump to subroutine labeled sendl 
'Program returns here 



Reverse 



sendl: 'Subroutine sendl begins 

serout 0,N24 0Q, {^Hello!"] 'Send "Hello]" out on pin serially 

Return 'Return to main program. 



Reverse Fin 



This command reverses the status of the Pin specified. If Pin is an output, it 
is reversed to an input, and vice versa. Only the pin number itself ? to 7 f is 
specified in the command. The command works only on port B pins- 



Output 3 
Reverse 3 



"Hake pin 3 (RB3) an output pin 

" Change pin 3 (RB3) to an input pin 



serin Pin, Mod&, [ (c?ual { ,Qual } ) , ] Item { , item } 

This command allows the microcontroller to receive serial data on the Pin speci- 
fied. The data are received in standard asynchronous mode using 8 data bits, no 
parity bit, and 1 stop bit. Mode sets the baud rate and TTL polarity as follows: 



80 Chapter Five 



Symbol 


Baud rate 


Polarity 


T2400 


2400 


TTL true 


T1200 


1200 


TTLtrue 


T96G0 


9600 


TTL true 


T300 


300 


TTL true 


N2400 


2400 


TTL inverted 


N1200 


1200 


TTL inverted 


N9600 


9600 


TTL inverted 


N300 


300 


TTL inverted 



The operation of this command is shown in Fig. 5.5. 



* Convert decimal number to hexadecimal 

Loop: 

serin i f N24 0, bo 



Lookup B0, ( V, 012345G7B9ABCDZF' , } , Bl 



Serout 0, N2400, (Bl, 13, 10} 



Goto Loop 



Receive decimal 
number on pin l, 24 00 
Baud; store in B0. 
Use B0 as index 
number and look up 
hex equivalent . 
Transmit hex 
equivalent out on pin 
serially with carriage 
return (13) and line 
feed (10) . 
Do it again. 



Triggers 



The microcontroller can be configured to ignore all serial data until a particu- 
lar byte or sequence of bytes is received. This byte or sequence of bytes is 
called a qualifier and is enclosed within parentheses. If there is more than one 
byte in a qualifier. Serin must receive these bytes in exact order before receiv- 
ing data. If a byte does not match the next byte in a qualifying sequence^, the 
qualification process resets. If this happens , the next byte received is com- 
pared to the first item m the qualification sequence. Once the qualification is 
met, Serin begins receiving data. 



Pi- 1 



PI 





LIB 9 


DBZ5 


RG-?S? T* 


Pir 3 


Pi* ^ 


R£-?3? GKO 


Pir 5 


Fin 7 



Figure 5.5 Serial in from RS-232. 



Serout 



PICBastc Language Reference 81 

The qualifier can be a constant, variable,, or string, Each character of a 

string Is treated as an individual qualifier. 

Serin 1, N240Q, {"A"), BO 

Wait until the character "A" is received serially on pin 1 ? then put the next 
character in BO. 



Serout Pin, Mode, Item {,Item} 

This command allows the microcontroller to transmit serial data on the Pin 
specified. The data are transmitted in standard asynchronous mode using 8 
data bits, no parity bit, and 1 stop bit. Mode sets the baud rate and TTL polar- 

ity as follows: 



Symbol 


Baud rate 


Polarity 


T2400 


2400 


TTL true 


T1200 


1200 


TTL true 


T9GQQ 


9600 


TTL true 


T300 


300 


TTL true 


N2400 


2400 


TTL inverted 


N1200 


1200 


TTL inverted 


N96Q0 


9600 


TTL inverted 


N300 


300 


TTL inverted 


OT2400 


2400 


Open drain 


OT1200 


1200 


Open drain 


OT98O0 


9600 


Open drain 


OT30O 


300 


Open drain 


ON2400 


2400 


Open source 


ONI 200 


120O 


Open source 


ON96O0 


960O 


Open source 


GN300 


300 


Open source 



Serout supports three types of data, which may be mixed and matched freely 
within a single Serout statement. A description of the data types follows: 

1. A string constant is transmitted as a literal string of characters, 

2. A numeric value (either a variable or a constant) will transmit the corre- 
sponding ASCII character This procedure is often used to transmit a car- 
riage return (13) and a line feed (10). 

3. A numeric value preceded by a pound sign (#) will transmit as the ASCII 
representation of its decimal value. For instance, if WO = 123, then #W0 (or 
#123) will transmit as "1", "2" ? "3*. 



82 Chapter Five 



Sleep 



The operation of this command is shown in Fig- 5.6. 

Serout 0,N240Q, {#BD,10} "Send the ASCII value of BO followed by 

*a line feed out pin aerially. 

Note: Single-chip RS-2324evel converters are common and inexpensive 
(Maxim's MAX232) and should be implemented when needed or to ensure 
proper RS-232 communication. 



sleep Period 

This command places the microcontroller in low-power mode for Perixxl^ spec- 
ified in seconds. Since Period is a 16-bit number, delays of up to 65,535 s ( a 
Utile over 18 h) are possible- Sleep uses the watchdog timer (WDT) on the 
microcontroller, which has a resolution of 2-3 s (see Nap command). 



Slt'jp 120 



"Sleep (low- power mode) for 2 min. 



Additional sleep notes 



It has been determined that Sleep may not work properly on all PICMicros- 
During Sleep calibration, the PICMicro is reset- Different devices respond in 
different ways to this reset- Upon reset, many registers may be altered. 
Notably the TRIS registers set all the port pins to inputs. 

However the TRIS register for port B is automatically saved and restored by 
the Sleep routine- Any other port directions must be reset by the user program 
after Sleep. Other registers may also be affected. See the data sheets for a par- 
ticular part for this information. 

To get around potential problems, an uncalibrated version of Sleep has been 
added- This version does not cause a device reset, so it has no effect on any of 
the internal registers. All the registers, including port direction, remain 
unchanged during and after a Sleep instruction. 

However, actual Sleep times will no longer be as accurate and will vary, 
depending on device particulars and temperature- To enable the uncalibrated 
version of Sleep, add the following lines to a PBC program: 



Pm 








OB 9 


COM 


K-s-if^e *x 


Pin £ 


Tin 3 


RS-23Z 3ND 


Pin 5 


Pin 7 



Figure 5-6 Serial out to RS-232. 



PICBasic Language Reference 83 



Sound 



asm 
SLEEPUHCAL = 1 

endasm 



The PICBasic Compiler software is packaged with a PIC Micro macro assem- 
bler (PM.exe'L While we will not write any in-line assembly code, it is available 
to those who have some familiarity with assembly language and PBC library 
routines. The next book will mix assembly and Basic language and use the 

PICMicro macro assembler. 



sound Pin f £ Note, Duration { t Nota, Duration} } 

This command generates tones and/or white noise on the specified Pin. Note 
is silence, notes 1 to 127 are tones, and notes 128 to 255 are white noise. Tones 
and white noises are in ascending order. Duration is a numeric variable from 
to 255 that determines how long the specified note is played. Each increment 
in duration is equivalent to approximately 12 ms. This command may use any 
port B pin from to 7. 

The waveform output is TTL level square waves, A small speaker and capac- 
itor can be driven directly from the microcontroller pin (see Fig. 5.7), Piezo 
speakers may be driven directly. 



Sound 4., -ICG, I C ,E0, 1C-: 



% Flay two notes consecutively on pin 4 

* (RB4) . 



Toggle 



Toggle Pin 

This command inverts the state of the specified Pin. The pin specified is auto- 
matically made into an output pin. This command may use any port B pin 
from to 7. 



High l 

TojiCjlO 1 



% Hake pin l (RBI) high 

% invert state of pin l and bring it low 



Pm 



CI 

LOuF 



Figure 5.7 Simple sound out circuit. 



84 Chapter Five 

Write 



Write Address, valu* 

This command writes the Value to the on-chip EEPROM (if available) at the 
specified Address. This instruction may be used only with microcontrollers 
that contain on-chip EEPROM, such as the 16F84. 

Write 5,BQ * Write the value in BO to EEPROM address 5 



Chapter 




Characteristics of the I6F84 

Microcontroller 



In this chapter, we will look at a few aspects of our PIC 16F84 microcontroller. 



Current Maximums for I/O Port(s) 



Maximum output current sourced by any I/O pin 20 mA 

Maximum input current sunk by any I/O pin 25 mA 

Maximum current sourced by port A 50 niA 

Maximum current sunk by port A 80 mA 

Maximum current sourced by port B 100 mA 

Maximum current sunk by port B 150 mA 

Typical operating current 1,8 mA 

Other factors such as I/O pin loading, operating voltage, and frequency have 

an impact, on the operating current. 

Power-down current in Sleep mode (I/O pins' high-impedance state) 7 jjlA 



Clock Oscillators 



PIC microcontrollers can be operated in four different oscillator modes. We 
select the oscillator mode when we program the microcontroller using the 
EPIC software. We have the option of selecting one of the following modes: 

LP Low-power crystal 

XT Crystal/resonator 

HS High-speed cry at al/ resonator 

RC Resistor/capacitor 

45 

Copyright 2000 The McGraw-Hill Companies, Inc. Click Here for Terms of Use. 



86 Chapter Six 



In the XT, LP, or HS mode, a crystal or ceramic resonator is connected to the 
OCS1/CLKIN and OSC2/CLKOUT pins to establish oscillation (see Fig, 6.1). 
For crystals 2.0 to 10,0 MHz, the recommended capacitance for CI and C2 is 
in the range of 15 to 33 pF Crystals provide accurate timing to within ±50 ppm 
(parts per million). For a 4-MHz crystal, this works out to ±200 Hz. 

A ceramic resonator with built-in capacitors is a three- terminal device that 
is connected as shown in Fig. 6,2. The timing accuracy of resonators is 
approximately ±0,5 percent. For a 4-MHz resonator., this works out to 
±20,000 Hz, 

RC oscillators may be implemented with a resistor and a capacitor (see Fig, 
6,3), While additional cost saving is provided, applications using RC mode 
must be insensitive to timing. In other words, it would be hard to establish RS- 
232 serial communication using an RC oscillator because of the variance in 
component tolerances. 




Figure 6,1 Crystal connected to PIC 16FS4. 



OSC1 




D 



KTAL 



OSC2 



J 




Figure 6.2 Diagram of ceramic resonator with built-in capacitors. 



Characteristics of the 1 6FB4 Microcontroller 87 



+5V 



Vdd = 5 Volts 





R 


C 


F 


Fosc/4 


5K 
10 K 
100 K 


100 pF 
IDOpF 
100 pF 


S.4MHz 
3.0 MHz 
320 KHz 


1.3 MHz 

756 KHz 

B2KHz 



OSC1 



Fosc/4 



OSC2 




Figure 6.3 EC oscillator. 

lb ensure maximum stability with RC oscillators, Microchip recommends 
keeping the R value between 5 and 100 kfl. The capacitor value should be 
greater than 20 pR 

There is not a standard formula for calculating the RC values needed for a 
particular frequency- Microchip provides this information in the form of 
graphs given in the data sheets for particular microcontrollers. 

The RC oscillator frequency, divided by 4, is available on the QSC2/CLK- 
OUT pin. This output can be used for testing and as a clock signal to synchro- 
nize other components. 

An external clock may also be used in the XT, LP, and HS modes. External 
clocks require only a connection to the OSC1 pin (see Fig. 6.4). This is useful 
when we are attempting to design an entire circuit that can be implemented 
with one external clock for all components. Clock accuracy is typically simi- 
lar to the accuracy quoted lor crystals. 



Reset 



The PIC 16FS4 can differentiate between different kinds of resets. During 
reset, most registers are placed in an unknown condition or a "reset state," The 
exception to this is a watchdog timer (WDT) reset during Sleep, because the 
PICBasic compiler automatically stores TRISB register when using the Sleep 
command and reinitializes TRISB after a reset for the resumption of normal 
operation. The following types of resets are possible: 

Power-on reset 

MCLR reset during normal operation 



88 Chapter Six 



Clock 


0SC1 










PIC16F34 




OSC2 





Figure 6.4 External clock. 

MCLR reset during Sleep 

WDT reset during normal operation 

WDT wake-up (during Sleep) 

For the time being, we are concerning ourselves only with the MCLR reset 
during normal operation. The MCLR pin is kept high for normal operation. In 
the event that it is necessary to reset the microcontroller, bring the MCLR pin 
momentarily low (see Fig. 6.5). 

In some cases, you may want to include an optional resistor R2 (100 fl). This 
resistor limits any current flowing into MCLR. 



+5V 



+5V 



R1 



10K 



MCLR 



PIC16F64 



R1 



10K 



10Q ohms 

WsAH 




Figure 6.5 Reset switch. 



o 

E 

-t-r 
B 

a 

8 

LJ 



LJ ra 



49 



3 

ca 



.-.. 



\ 







» 


a: 


K 


D 


* 


* 


V 


in 




LU 







3 

LU 
LU 




E 




a 

*-■ 


^* 


* 


K 


"5 a 


5 H 


DC 9 


uS 




CL 


UL 





/ 



T3 



\ 









L- 






4» 






3 




3- 


0- 




33 


i 


"^ — ^~ 


— rt 


B 




a r- 




S ■*• 


? 






LL 




<£ 



T3 

+-■ 

a 



Iff 

3 



43 







\ 



CI 

2 
3 




♦ 



§«_ 




£ 

a 


lis 










1* 




I 



a 

S 
i 



o 

s 



4D 



90 Chapter Six 



PIC Harvard Architecture 



PIC microcontrollers use a Harvard architecture, which means that the mem- 
ory is divided into program memory and data memory The advantage to this 
architecture is that both memories can be accessed during the same clock 
instruction; this makes it faster than the standard von Neumann architecture, 
which uses a single memory for program and data. Figure 6.6 is a block dia- 
gram of the 16F84. 

User program memory space extends from OxOOOOh to 0x03FFh (0 to 1023 
decimal). Accessing a memory space above 03FFh will cause a wraparound to 
the beginning of the memory space. 



File 

Address 

OOh 

01 h 
02h 
03h 
04h 
05h 
06h 

07h 
oah 

09h 
OAh 

OBh 
QCh 



4Fh 
50h 



7Fh 



Indirect addr. 


Indirect addr. 


TMRO 


OPTION-REG 


PCL 


PCL 


STATUS 


STATUS 


FSR 


FSR 


PORTA 
PORTB 


TRISA 
TRISB 






EEDATA 


EEC ONI 


EEADR 


EECON2 


PC LATH 


PCLATH 


INTCON 


SNTCON 


68 

General 

Purpose 
Registers 
{SRAM} 


Mapped 
[accesses) 
In Bank 







File 
Address 

80r 

81h 
82h 
83h 
84h 
85h 
86h 

8?d 

88h 

89h 

BAh 

8Bh 

8Ch 



DO+i 



FFh 



Bank 



Bank 1 



r 



Unifnplem^nt^d Data 
memory location; read as 



Figure €-.7 Register file map 16FS4. 



Characteristics of the 1 6FB4 Microcontroller 91 



Register Map 



The register map is shown in Fig. 6,7, This memory area is partitioned into 
two spaces called banks. In the diagram you can see the two banks, bank and 
bank 1. The small h behind the numbers under the iile address informs us that 
these are hexadecimal numbers. If you were programming in machine or 
assembly language, you would have to set a bit in the Status Register to move 
between the two banks. Fortunately for us s the PICBasic compiler handles this 
bank switching for us. 

There are two addresses I would like to touch upon. The first is the Reset 
Vector at OOh. Upon power-up or reset, the Program Counter is set to the mem- 
ory location held at 00. 

The Interrupt Vector is shown as FSR 04k Upon an interrupt, the return 
address is saved and the program execution continues at the address held in 
this memory location. On a return from interrupt, the program execution con- 
tinues at the return address previously saved, 

Unfortunately;, we do not have time to work with interrupts, watchdog 
timers, or the Sleep mode in this book. In the next book, we will play with 
these additional features. 



This page intentionally left blank. 



Chapter 




Speech Synthesizer 



This chapter begins our applications. The first project is a speech synthesizer 
that can be embedded into another circuit or project to add speech capabilities. 
You may want to create a talking toaster that will tell you when your toast is 
ready, or a talking VCR. The circuit is activated and the speech selected by 
using high or low logic signals to port A, 

Speech synthesizers {or processors) are available in two formats. The first 
format uses sampled (digitally recorded) speech stored in ROM or EEPROM, 
The second approach uses phonemes of English to construct words. A phoneme 
is a speech sound, 

Each format has its advantages and disadvantages. Digitally recorded 
speech has excellent fidelity, but has a limited vocabulary because of the large 
storage capacity required. The phoneme approach has an unlimited vocabu- 
lary, but the speech fidelity isn't as good as that of sampled speech. Even so ? 
the phoneme approach usually suffices as long as a mechanical (robotic- type) 
voice is acceptable. This is the approach we are using. 

The total cost of this project, including the PIC microcontroher s should be 
less than $25.00. Included in this price are an audio amplifier, filter, volume 
control, and speaker. 

While the speech synthesizer chip is capable of producing an unlimited 
vocabulary? we do not have an unlimited memory in the microcontroller. The 
limited memory in the microcontroller limits the number of words that can be 
stored, but they may be any words you want. 

In later chapters, we interface serial EEPROMs to the microcontroller; 
these can be used to increase word vocabulary 

Speech Chip 

The SPO-256 speech synthesizer chip we are using was discontinued by 
General Instruments a number of years ago. However, there is a good supply of 
chips available from B & S Micro and a few other distributors (see Suppliers 

Copyright 2000 The McGraw-Hill Companies, Inc. Click Here for Terms of Use, 



94 Chapter Seven 



Index). The SPO-256 (see Fig- 7,1) can generate 59 allophones (the electronic 
equivalent of English phonemes) plus five pauses (no sound) of various lengths. 
An allophone table is provided in Table 7.1- 

By concatenating (adding together) allophones, we construct words and sen* 
tences. This may appear difficult at first, but it is not. Once you get the hang 
of it j you can turn out complete sentences in a minute or so. 



A Little on Linguistics 



When we program words for the SPO-256 speech chip, we string together the allo- 
phones shown in Table 7.1- Words and sentences must end with a pause (silence); 
if they do not, the last allophone sent to the chip will drone on continuously 

To pronounce the word cookie, use the following allophones: cookie = KK3, 
UH, KK1, IY, PA2. The decimal addresses for the allophones are sent to the 
SPO-256; this works out to the following numbers: 8, 30, 42, 19, 1. 

The optional data sheet for the SPO-256 has an allophone word list con- 
taining two hundred or so commonly used words (numbers., months, days of 
the week, etc.). If the word you need isn't on the list, you can make the word 
up yourself, using the allophone list. 

The first thing to keep in mind when creating an allophone list for any par- 
ticular word is that there is not a one-to-one correspondence between sounds 
and letters. You need to spell the words phonetically, using the allophone table. 
For instance, CAT becomes KAT, which in allophones becomes KK1, EY, TT1, 



Vss C 1 28 =1 OSC 2 

RSrtCI 2 27^ OSC1 

Rom Disable^ 3 26 n Rom CJqpk 

d H 4 25 ~l SBY RESET 

C2 H 5 CO 24 H Digital Out 

Vddl 7 Q 22 I Test 

SEYL 8 |^ 21 J Serin 

LRQ L 9 JjJ 20 J ALD 

A8L10 S 19 J SE 

A7C 11 18 DA1 

SerOutC 12 17 n A2 

A6 L 13 16 J A3 

A5C 14 15 n A4 

Figure 7.1 Finout of the SPO-256 



Speech Synthesizer 95 



TABLE 7J A No phones 



Decimal address 


Allophono 


Sample word 


Duration (msj 





PA1 


Pause 


10 


1 


PA2 


Pause 


30 


2 


PAS 


Pause 


50 


3 


PA4 


Pause 


11.1 LI 


4 


PAS 


Pause 


200 


5 


OY 


Toy- 


420 


6 


AY 


Buy 


260 


7 


EH 


End 


70 


8 


KK3 


Cat 


120 


9 


PP 


Power 


140 


10 


JH 


Judge 


140 


11 


NN1 


Pin 


140 


12 


IH 


Sit 


70 


13 


TT2 


lb 


140 


14 


RR1 


Plural 


170 


15 


AX 


Succeed 


70 


16 


MM 


My 


ISO 


17 


TT1 


Tart 


100 


IS 


DH1 


They 


290 


19 


IY 


TEfee 


250 


20 


EY 


Beige 


2HU 


21 


DD1 


Should 


70 


22 


UW1 


To 


100 


23 


AO 


Aught 


100 


24 


AA 


Home 


100 


25 


YY2 


Yes 


ISO 


26 


AE 


Pat 


120 


27 


HH1 


Him 


130 


28 


BB1 


Boy 


SO 


29 


TH 


They 


ISO 


30 


UH 


Book 


100 


31 


XJW2 


Food 


26 U 


32 


AW 


Out 


370 


33 


DD2 


Don't 


160 


34 


GG3 


Pig 


140 


35 


W 


Venom 


190 



(continued) 



96 Chapter Seven 



TABLE 7. 1 Allophones (Continued) 



Decimal address 


Alio phone 


Sample word 


Duration (ma) 


36 


GG1 


Gotten 


SO 


37 


SH 


Sharp 


160 


38 


ZH 


Azure 


190 


39 


RR2 


Train 


120 


40 


FF 


Forward 


150 


41 


KK2 


Sky 


190 


42 


KK1 


Came 


160 


43 


ZZ 


Zolu 


210 


44 


NG 


Anchor 


220 


45 


LL 


Lamb 


110 


4B 


WW 


Wood 


180 


47 


XR 


Pair 


360 


48 


WH 


Whine 


200 


49 


YY1 


Yes 


130 


50 


CH 


Chump 


190 


51 


ER1 


Tire 


160 


52 


ER2 


Tire 


300 


53 


OW 


Beau 


240 


54 


DH2 


They 


240 


55 


ss 


Best 


90 


56 


KX'A 


Not 


190 


57 


HH2 


Noc 


ISO 


58 


OR 


Pore 


330 


59 


AR 


Arm 


290 


60 


YR 


Clear 


350 


61 


GG2 


Guide 


40 


62 


EL 


Paddle 


190 


63 


BB2 


Boy 


50 



PAL The decimal addresses for the allophones are 42, 20, 17, 1. Those are the 
numbers we plug into our program to get it to speak. When the word is pro- 
grammed in, listen to it as it plays through the SPQ-256 and decide whether 
we need to improve up cm it. In our cat example, you will find that the KK3 
allophone makes the word sound better. 

The placement of a speech sound within a word can change its pronuncia- 
tion. For instance, look at the two rf's in the word depend. The dPs are pro- 
nounced differently. The DD2 allophone will sound correct in the first d 
position, and the DD1 allophone will sound correct in the second d position, 



Speech Synthesizer 97 

General Instrument recommends using a 3.12-MHz crystal at pins 27 and 
28. I have used a 3,57-MHz TV color burst crystal on many occasions (because 

of its availability and the unavailability of the 3.12-MHz) without any ill 
effects, Thi? change increases the timbre of the speech slightly 



Interfacing to the SPO-256 



The pin out and functions of the SPO-256 are provided in Table 7.2, The SPD- 
256 has eight address lines (Al to A3)* In our application, we need to access 64 
allophones. Therefore, we need to use only address lines Al to A6. The two oth- 
er address lines, A7 and A8, are tied to ground (0). Thus, any access to the SPO- 
256 address bus will include the address we place on Al to A6 S with lines A7 
and A8 = 0. Essentially A7 and AS add nothing to the address. 



TABLE 7.2 SPO-256 Pin Functions 



Pin number 



Name 



Function 



1 


Vss 


2 


Reset 


3 


ROM disable 


4, 5, 6 


C1,C2 T C3 


7 


Vdd 


8 


SBY 



s 



LRQ 



10, 
15, 


11, 
16, 


13. 
17, 


14, 

is 


AS, A7, 48,45, 

A4 ? A3 ? A2 ? A1 


12 








Sex Out 


19 








SE 


20 








ALD 


21 








Ser In 


22 








Test 


23 








Vdl 


24 








Digital Out 


25 








SEY Reset 


26 








ROM clock 


27 








OSC1 


28 








OSC2 



Ground 
Logic 0, reset 

Logic 1, normal operation 
Used with external serial ROM. Logic 1 disables 
Output control lines for use with serial ROM 
Power ( H5 Vdc> 
Standby 

Logic 1, inactive 

Logic 1 active 
Load request 

Logic 1, active 

Logic i inactive 
Address lines 

Serial address out. For use with serial ROM 
Strobe enahle. Normally set to logic 1 iraode 1) 
Address load. Negative pulse loads address into port. 
Serial in. For use with serial ROM 
Grounded for normal operation 
i 5 V de for interface logic 
Digital speech output 
Standby reset. Logic resets 
1.56-MHz clock output for use with serial ROM 
Crystal in. 3.12 MHz 
Crystal out. 3.12 MHz 



98 Chapter Seven 
Mode Select 



The Circuit 



There are two modes available for accessing the chip. Mode (SE = 0) will 
latch an address whenever any of the address pins makes a low-to-high tran- 
sition. You can think of this as an asynchronous mode. 

Mode 1 (SE = 1) latches an address using the ALD pin. When the ALD pin 
is pulsed low, any address on the lines is latched in, To ensure proper syn- 
chronization, there are two pins that can tell the microcontroller when the 
SPO-256 is ready to have the next allophone address loaded- We will use one 
of those pins, called the SBY pin. The SBY goes high while the chip is enunci- 
ating the allophone. As soon as the allophone is completed, the SBY line goes 
low. This signals the microprocessor to load the next allophone address on 
lines Al to A6 and pulse the ALD line low. 



The circuit is shown in Fig, 7.2. The circuit uses two switches to trigger 
speech. It is important to realize that the switches provide digital logic signals 
to the port A pins and, further, that any circuit that can output binary Os and 
Is can be used to trigger the circuit to speak. In other words, you don't need to 
use switches. 

Looking at the schematic, we can see that the RAO and RAl lines are nor- 
mally kept high (4-5 V), binary 1, through the 10-kll resistor. When a switch 
is closed, it connects the pin to ground and the line is brought down to (ground) 
binary 0. I could have arranged the logic signals to the pints ) to be the oppo- 
site. This would change a few commands in the program, but functionally it 
would do the same thing. You choose the logic signal to use based upon the cir- 
cuit you are working with. 

The other important thing to know is that the five open lines on port A may 
be used to trigger up to 31 different speech announcements. The five pins form 
a 5-bit binary number that can be read with the Peek command. This is hinted 
at in the program. We use only two of the five available lines, RAO and RAl, to 
jump to three different words. With a 2-bit number, we have four possible com- 
binations. 

Logic status 



RAO RAl Action 

1 1 None— normal state 

1 Speak word 1 

1 Speak word 2 

Speak word 3 

In a similar fashion, a 3 -bit number allows 8 unique combinations, a 4-bit 
number allows 16, and a 5-bit number allows 31. 



AJ- 
AK 

fr 

k_ 
* 

& 

DP 

3h 

L 

L r 

O 

+- 

Tl 

4. 
■K 
U 

if 



u 

<5 




;- 
go 



Cm 

o 

.y 

S 

m 



99 



100 Chapter Seven 



In the program, word 3 is actually a sentence. This simply demonstrates 
that you are not limited to using single words. 



The Program 



'RSM SPO-25G talker 

symbol TRISB = 134 

Symbol ports = 6 

Symbol port A = 5 

1 1nitialize ports 

Poke TRISB, 12 B 

1 Check line status 

start : 

Pause 200 

Peek portA,bQ 

If bo = Then three 

If bito = Then hello 

If bitl = Then world 

Goto start 



1 Set RB7 as input, set RBO to RB6 as outputs 

1 could be switches or could be TTL logic si 911a Is 

1 Give a human a chance to press a but ton {s) 
1 Read Port A 

'Check both lines first (normally bo = 3) 
'Check line / alternative command: If bo = 2 
'Check line l / alternative command: If bo = l 



"Say word hello 

hello: 

For b3 = to 5 

lookup b3 f {27, 7,45, 15, 53,1} ,b4 

Gosub speak 

Next b3 

Goto start 

-. 

"Say word world 

world : 

For b3 = to 4 

lookup b3, {46, 5B, 62,21, 1} ,b4 

Gosub speak 

Next b3 

Goto start 



"It's not just a word, it's a routine 

"Loop using number of allophones 

'Decimal addresses of allophones 

"Speak subroutine 

"Get next allophone 

"Do it again from the beginning 



"Procedure similar to hello 



"Procedure similar to Hello 



"Say sentence "See you next Tuesday.' 

three : 

For b3 = to 19 

lookup b3, {55, 55, 19, 1,49,22, 1., 11,7, 42,55,13,2, 13, 31,43,2,33, 2 0, 1) , b4 

Gosub speak 

Next b3 

Goto start 



speak : 

Poke portB,b4 

Pause 1 

High 6 

wait z 

Peek portB, bo 

If bit? = Then wait 

Return 



'Subroutine to speak allophones 
'Set up allophone address and bring ALD low 
'Pause 1 ms for everything to stabilize 
'Bring ALD high / alternative 1 Poke ports, 64 

'Look at port B 

'Check SBY line (0 = talking, l = finished) 

'Get next allophone 



Program Features 



Usually each program has a little something different from all the other pro 
grams we looked at so Far, and this program is no exception. 



Speech Synthesizer 101 

Starting from the top, notice how we are using the Peek command: 

Peek portA, bo 

Firsts we are peeking port A, where our two switches are connected, and placing 
the result in variable bO. If neither switch is pressed, there is a logic high ( + 5 V) 
on pins RAO and RAL In binary, this port looks like XXX00011, where each X 
means that the line (pin) is not available for use (read these pins as 0). Following 
the Xs are the binary 0s equal to pins RA4, RA3, and RA2, and finally the bina- 
ry Is equal to pins RA1 and RAO. The decimal equivalent of this binary number 
is 3. If you have forgotten how to read binary numbers, look back to Table 3.1. 

The program interprets this information two ways. First, it looks at the 
number itself: 

If bo = Then three 

The only way bO can be zero is if both switches are closed simultaneously. In 
that case ? the program jumps to the routine labeled three. Otherwise, the pro- 
gram continues to the next line. 

If bito = Then hello 

In this line, we are testing the bit value in the bO byte. This operation can 
be performed only on bytes being held in the bO and bl variables. In general, 
try to leave these tw r o variables alone and use them for bit access. In the event 
that these variables are not available, there are alternative commands that 
you can use, such as those given in the comments as alternative commands. 

If bitd = Then hello "Check line / alternative command: If bo = 2 

The alternative command may be used on any variable (b7, for instance). I 
used shorthand for the alternative command to make it fit on one line; the full 
command would look like this; 

If bo = 2 Then hello 

This checks the number held in the variable. If bit 1 is high, the value of bO 
is 2. The disadvantage is that you must keep the status of the other bits in 
mind when you are checking status in this way 

The Lookup commands are reading numbers rather than ASCII codes, lb 
read numbers, leave out the quotation marks after the parenthesis. ASCII 
codes use the quotation marks s as in "H * 

In the speak subroutine near the end of the program, we use the Peek com- 
mand again ? this time to look at the one input line on port B, the RB7 line. 
Notice, however, that we peek the entire port B (8 bits), even though there is 
only one input line- The I/O status of any line doesn't affect, the usability of the 
Peek command. When we peek an output line (or port), the result shows us the 
status of both the output line(s) and the input lines. After we peek port B, we 
are checking the status of the one input line RB7 using the bit? command. 



102 Chapter Seven 



The input line RB7 is connected to the SBY line of the SPG-256. The SBY 

Hne stays low while the chip is talking; when it finishes, the line goes high- 
This tells the PIC microcontroller that it is ready For the next al lop hone. While 
the chip is talking, with the SBY line low, the program holds in a waiting loop 
until SBY goes high- 

This is also the first program that uses Gosub routines. In general, it is rec- 
ommended that you not nest more than three Gosub routines; if you do, you 
stand a good chance of fouling up the stack. 

What's a stack? Let's just say it's a pointing register that stores return 
addresses on top of one another (a stack). The stack holds the addresses 
arranged in a LIFQ (last in, first out) sequence- 



Parts List 



Components outlined in Chap. 1 



Additional components 



(1) SPO-256 Speech Processor 

(1) S-ohm speaker 

(1) LM386 Audio Amplifier 

(1) 10-kfl potentiometer PC Mount 
(3 ) 0.1- hjlF c apacit or s 

(2) 0,022 capacitors 
(1) 1-pF capacitor 
(1) 10-|±F capacitor 

(1) 100-(jlF capacitor 

(2) Push-button switches, normally open 

(1) lOOktt resistor, V 4 -W 

(2) lOkH resistor, V 4 -W 
(2) 33 kit resistor, V r W 
(1) 1041 resistor, 7 4 -W 
(1) 3,12-MHz crystal 

Available from: Images Company, James Electronics, JDR MicroDe vices, 
and RadioShack (see Suppliers Index). 



Chapter 




Serial Communication and 

Creating I/O Lines 



Creating New I/O Ports 



The speech generator project from the last chapter demonstrates how quickly 
a project can gobble up I/O lines. In complex projects, it*s easy to run out of I/O 
lines. So in this little project, we are going to confront this problem head on 
and see what we can do. 

When we run out of I/O lines, our first thought is usually to upgrade to a 
larger PIC microcontroller, such as the 16F873, which has 22 I/O lines. 
Eventually, however, regardless of the microcontroller chosen, we run out of 
I/O lines. So it's to our benefit to learn how to expand existing I/O lines. In 
this project, we will take two or three I/O lines off port B and expand them to 
eight output lines. Then we will use three or four I/O lines off port B to ere* 
ate eight input lines. Sounds good? Read on. 



Serial Communication 



We will use serial communication to expand our I/O lines. Serial communi- 
cation comes in two flavors, synchronous and asynchronous. Synchron- 
ous communication uses a clock line to determine when information on the 
serial line is valid. Asynchronous communication doesn't use a clock line. In 
lieu of a clocking line, asynchronous communication requires start and stop 
bits in conjunction with strict adherence to timing protocols for its serial com* 
munication to be successful. 

We use synchronous communication with a clocking line in these projects. 



103 
Copyright 2000 The McGraw-Hill Companies;, Inc. Click Here tor Terms of Use, 



104 Chapter Eight 



Output First 



Basic Serial 



To create the output lines, we are going to use a serial-to-parallel converter 
chip, the 74LS164 (see Fig. 8. IX This chip reads 8-bit serial data on pins 1 and 
2 and outputs the data on eight parallel lines (QA to QH). 

If you remember from the command description of the Basic language 
(Chap. 5), we have built-in Serin (serial in) and Serout (serial out) commands. 
Unfortunate ly t we cannot use these Basic commands because their serial for* 
mat uses stop and start bits. Start and stop bits are necessary in asynchronous 
(without a clock.) communication. 

The 74LS1G4 converter chips use a clock line and do not use or require stop 
and start bits. Since there is no way to remove these bits from the standard 
serial Basic commands, we need to program our own serial communication. 

Synchronous communication requires a clocking pulse. The clocking pulse 
determines when the information on the serial line is valid. For the 74LS164, 
it is on the low-to-high transition of the clock pulse that information (value 
or 1.) on the serial line is valid. 



Serial data are transmitted most significant bit (bit 7) first. Since we are writ- 
ing the serial routine, we could change this and send out the least significant 
bit (bit 0) first if we wanted., but we will not; we will stay with this convention. 



FUNCTION TABLE 


Clock 


A 


R 


Outputs 
QA QB .., QH 


X 


X 


X 


L L ... L 


L 


X 


X 


Qa Qb ... Qh 


t 


H 


H 


H Qa ... Qg 


f 


L 


X 


L Qa ... Qg 


t 


X 


L 


L Qa ... Qg 




H = high level L - low level 

X= irrelevant (any input including transitions)! 

'Y = Transition from low to high 

Qa ... Qg = the level after Hi* most recent f transition 

of the clock; fndtcates a one bit shift 

Figure 8 A Pirtout 74LS1G4 serial-to-parallcl chip. 



Serial Communication and Creating I/O Lines 105 

Figure 8.2 illustrates how the serial data are read by the 74LS164 and paral- 
lel in format ion outputted. 

Line B (pin 2) on the 74 LSI 64 is kept high. This allows us to use line A (pin 
1) to send serial data along with the? clocking pulse to pin 8, Notice that in the 
function table in Fig. 8,1 ? lines A and B both need to be high for a high bit to 
be outputtecL We can set either line (A or B) high and use the other to trans- 
mit serial data; it doesn't matter which we chouse. 

Each low-to-high transition on the clocking line accepts another bit offline 
A and outputs that bit to QA- All the existing bit information that is already 
on the QA to QH lines is shifted 1 bit to the left. After eight transitions , a new 
8-bit number is displayed on lines QA to QH of the 74LS164. In Fig- 8.2, we 
are transmitting binary number 10000000 (decimal number 128). I chose this 
number so that you can easily see how bit 7, the high bit, shifts down through 
lines QA to QH. 

What isn't immediately evident is that as bit 7 shifts through lines QA to 
QH, it brings each Q;z line high. If we had an LED attached to each Qn line, 
we could see bit 7 lighting each LED as it shifted with each transition. Only 
after eight transitions will bit 7 be in the right position. So, after the first 
seven transitions, as the serial number is shifting into the 74LS164 paral- 
lel register, the number shown on the 8-bit parallel output will be incorrect. 



B Pin 2 

AMn1 

Clock 



OB 

QC 

QD 
QE 

QF 
QG 

QH 



D 



« 







D 







Start 



n_n_n_n_n_n_n 



Binary numbti-MQQDOttQO 
Decimal Number 123 



Flnl*h 



FLTLT 







Q 



D 



a 



Parallel Out 



Figure 8,2 Serial data in and parallel data out. 



106 Chapter Eight 



This bit shifting can create chaos in a digital circuit. If the circuit that is con- 
nected to the 74LS164 parallel output cannot compensate for this bit shifting, 
wo can correct for thus u^mij; a .second chip, the 74LS373 data octal latch. You 
will find that some circuits can compensate and others cannot. 



Clear Pin 



The 74LSl64s have an optional pin that can help eliminate some of the havoc 
caused by bit shifting. Pin 9 on the 74LS164 is the clear (CLR) pin. It is used 
to clear whatever binary number exists on the parallel output and bring all 
lines (QA to QH) low. The CLR pin is active low. For normal operation, this pin 
is kept high. To clear the number, bring the CLR pin low. 



The Programs 



Program 8.1 



"■Serial interface 

"•Slow program for visual testing interface 

Symbol TRISB = 134 'Assign Data Direction Register port B to 134 

Symbol PortB = 6 'Assign variable FortE the decimal value of 6 

1 initialize port{s} 

Poke TRISB ,0 'Set port B as output port 

start : 

bO = 128 'Put number 12a Uooooooo) into bo 

Gosub serial 'Output the number serially to 74 LSI 64 

Pause 1000 'Wait l s 

bo = 255 'Put number 255 {llllllll) into bo 

Gosub serial 'Output the number serially to 74 LSI 64 

Pause 1000 'Wait l s 

bo = 'Put number {c-ooooooo} into bo 

Gosub serial 'Output the number serially to 74LS164 

Pause ldoo 'Wait l s 

Goto start 'Do it again 

"Serial out routine 

serial s 

pinO = bit? 'Bring pin high or low, depending upon bit 

Pulsout l, l 'Bring CLK line high, then low 

Pause 100 'Optional delay— remove from program 

pinO = bits 'Same as above 

Pulsout 1, 1 'Same as above 

Pause 100 'Optional delay— remove from program 

pinO = bits 

Pul sout 1 ,. 1 

Pause 100 'Optional delay— remove from program 

pino = bit4 

Pulsout 1. 1 

Pause 100 'Optional delay— remove from program 

pino = bit3 

Pulsout l ( . l 

Pause 100 'Optional delay— remove from program 

pino = bit2 

Pulsout l. l 

Pause 100 'Optional delay— remove from program 

pinO = bitl 

Pulsout l,. l 



Serial Communication and Creating I/O Lines 107 



Program 8.2 



Pause 100 'Optional delay-remove from program 

pinO = bito 

Pulsout 1 , 1 

Pause 100 'Optional delay-remove from program 



Low 1 
Return 



The schematic .shown in Fig, 8.3 does not correct for the bit shifting. LEDs 
are connected to the 74LS164 output lines. The program outputs binary 
10000000 (decimal 128), waits a second, outputs 11111111 (decimal 255), waits 
a second, and then outputs 00000000 (decimal 0), 

The first serial program has optional Pause commands (Pause 100) after 
each bit shift to allow you to see how the number shifts into and through the 
register. These Pause commands should be removed when you are using the 
serial routine in an application. Remove the Pause command from the pro- 
gram as shown in Program 8.2. Recompile the program and program it into 
the 16F84, When the program is run, the numbers shift in so quickly that you 
may not see the bit shifting occurring. 



'Serial interface 

Symbol TR1SB = 134 'Assign Data Direction Register port B to 134 

Symbol PortE =6 'Assign variable Ports the decimal value of 6 

'Initialize port(s) 

Poke TRISE,G l set port B as output port 

start : 

bo = 128 'Put number 128 (looooooo) into bo 

Gosub serial 'Output the number serially to 74LS164 

Pause 100 'Wait l s 

bti =2 55 'Put number 2S5 (ill 11 ill) into bo 

Gosub serial 'Output the number serially to 74LS164 

Pause 100 'Wait 1 s 

bo = o 'Put number o (oooooooo) into bO 

Gosub serial 'Output the number serially to 74LS164 

Pause 100 'Wait l s 

Goto start 'Do it again 

'Serial out routine 

serial t 

pinO = bit7 'Bring pin high or low depending upon bit 

Pulsout 1. 1 'Bring CLK line high, then low 

pinO = bit€ 'Same as above 

Pulsout l, 1 'Same as above 

pinO = bits 

Pulsout 1, 1 

pino = bit4 

Pulsout l, l 

pino = bit3 

Pulsout i f l 

pino = bit2 

Pulsout 1 ,- 1 

pinO = bitl 

Pulsout 1, 1 

pinO = bito 

Pulsout 1, 1 

LOW 1 

Return 



J* 

a 





1DB 



Serial Communication and Creating I/O Lines 109 



Bit Shift Correcting 



If you are interfacing to a digital circuit that would be sensitive to the bit shift- 
ing, you can block the bit shifting by using a second chip, the 74LS373 data 
octal latch (see Fig, 8-4). The octal latch is placed between the output of the 
74LS164 and the LEDs (see the schematic in Fig. 8-5)* Remember, in our test- 
ing circuit, the LEDs represent our digital circuit. We tie the OC (Output 
Enable) pin to ground and use the C (Enable Latch) pin (pin 11 on the 
74LS373) to control the data through the 74LS373, 

Data are placed on the D inputs (ID, 2D V „, 8D). When we want the data to 
appear on the Q outputs fit}, 2tj % -. t , 8t}), we raise the C pin momentarily 

The program inputs the data serially to the 74LS164, The data appear on 
the parallel out lines, bit shifting on the inputs of the 74LS373- When the bit 
shifting is finished and the binary number has settled (eight shifts), we raise 
the Enable Latch pin (pin 11.) of the 74LS373; this lets the parallel data flow 
from the input pins to the output pins. Then the Enable Latch pin (pin 11) is 
lowered, leaving the parallel data latched in. 

As the bits shift, the bit shifting is blocked from the LEDs. Only when the 
entire byte has been transmitted do we raise pin 11 (C pin) on the 74LS373, 



1 


* 

ID 
2D 
2Q 

JCfc 

AD 

4P 

♦a 

CiiO 


) 74LS373 


Use 

3D 
TO 
7Q 

*G 
*D 
SO 
VQ 
C 


M 


2 


1? 


3 


11 


4 


1J 


ff 


16 


« 


1fi 


7 


U 


■ 


i3 


a 


12 


i» 


11 







FUNCTION TABLE 


Output 
Enable 

L 


Enable 
Latch 

H 


D 
H 


Output 

H 


L 


H 


L 


L 


L 


L 


X 


Qo 


H 


X 


X 


Z 



C = Enable Latch 



OC = Output Enable 



The eight latth*ft Of the 
LS373, when C Is high 
the Q outputs follow the 
D inputs. When C is low 

the output wilE be latched 
at the curoent data levels. 



Figure 8,4 Octal data latch 74LS373 used to nullify bit shifting in output. 




iMr* ft] rr» j>- b j 

O Q C- -O Q 



li 



W PI x IT" U tv CD 

KJCJ rtDQDQQQOD 



ttthfiWfhfl 



io 



IfHf 



on lb 



4 



I 



-4> 



ysais^* 









» «7V 



r\i *»■■ 



J_I_L 






£* »M W i*» fcjj I— —I f-J « J- l/> ■-> K, 

*- a 



2 

i— 

CL 



fU -H fit 

U <J J 

8 8 £ 

~r r — it 



U-a 







I 



Q 
W 

to 

C 

-i—4 

3 
o 

■ 1—1 

— 

t« 
C 



■ 

£ 

Pi 



110 



Serial Communication and Creating I/O Lines 111 

letting the byte information through to our LEDs ? and then latch in the infor- 
mation. 

Programming Challenge (Simple) 

Rewrite the first serial program so that pin 2 activates the CLR pin on the 
74LS164 to clear the number before loading the next number in. The answer 
is in the Appendix. 

Programming Challenge (Not Simple) 

Take the speech generator project from Chap. 7 and use the 74LS164 IC and 

microcontroller to save four I/O lines and supply the corresponding schematic. 
Hint: You do not need the 74LS373 chip. Why? The answer is in the Appendix. 



Input I/O 



We shall continue by expanding four I/O lines off the PIC microcontroller to 
function like eight input lines. To accomplish this, we will use a 74LS165 
parallel-to-serial converter chip (see Fig. 8.6). The parallel-in, serial-out dia- 
gram is shown in Fig. 8.7. Eight -bit parallel information is placed on the 
eight input lines of the (A to H) 74LS165. The shift load line is brought low 
momentarily to load the parallel information into the chip's registers. The 





FUNCTION TABLE 




Shift/ 
Load 


Clock 


Clock 
Inhibit 


Parallel 

A....H 


Output 
Qh 


L 


X 


X 


a...h 


h 


H 


L 


L 


X 


Qho 


H 


t 


L 


X 


Qgn 


H 


t 


L 


X 


Qgn 


H 


X 


H 


X 


Qho 



3 

4 



3WLD 
GLK 

G 

h 







tli 



CLKINH 

c 
a 



o 
en 



5E« 



15 
U 

IS 
12 
If 

ia 



H = high level L = low level 

X = irrelevant (any input including transitions) 

A = Transition from low to high 



Figure ft.S Pinout for the 74LS1G5 parallel-in, serial-out chip. 



112 Chapter Eight 



Clock Inhibit 



Shift fLo*d 



1 
start 



1 



i 



Clock 

A 

B 

C 
D 

E 

F 
G 

H 




Finish 



o 



£ 

a 

a. 



o 



a 


n 


*— 


^ 


a 


^ 


^" 


1_ 


i^ 


m 


1— 


A 




A 




E 


z 


-3 




£ 


01 


t 


E 


d 


o 


c 


u 


EQ 


Q 



Serial Output 

via Qh 

110 1 

Figure 8,7 Parallel data in and serial data out. 







1 



1 



Clock Inhibit line is then brought from high to low, allowing the information 
to be aerially outputted from pin Qh, in synchronization with the clocking 
pulses provided on pin 2 (CLK). (Note that an inverted serial signal is also 
available from pin 7.) 

To functionally test the chips, circuit, and program, we will input an 8-bit 
number to the 74LS165 using switches and resistors (see schematic in Fig- 
8.8)- This binary number created with the switches and resistors will be seri- 
ally shifted out of the 74LS165 into variable BO- The number in BO will then 
be serially sent out to the 74LSI64 for display 

We could reduce the number of I/O lines taken up bv the 74LS165 bv one if 
we shared the clocking line with the 74LS164. I want to keep the program- 
ming as straightforward as possible, so I will not do this, but you should be 
aware that this feature may be implemented. This would reduce the number 
of lines required to three- 




its 

TT 



•n eg 



c> 



•^i 



Oannoono 



AJ-±S 



Ph. 



L7 



■j=- 



UT- 



« 



■?u 



i~vsu CjtS 



IS* 



fi 



<-j 



c o 



<D O- 



c 



o o 



o 



o 



o a 



*-> 



B^nr 



u 
u 



1 I J 1 I 




c* 



» 



n *■• 



J_J. 



c « « « x zdacfimiliLLiffica 



u-j 









LJ 

in 






l/j 



LI _l 

=-5 









,ji 



« 




c 



w 



I 



I 






113 



114 Chapter Eight 



Program 8.3 



The serial out and serial-in routines could be merged to conserve program- 
ming apace and use the same clocking line. Again,, to keep the program b& 
straightforward as possible^ this option will not be implemented- 



1 Serial Interface 

Symbol TRISE = 134 

Symbol PortB = 6 

'initialize Fort(s) 

Poke TRISE , 4 

Low 5 

High 4 

High 21 

start : 

Gosub serial_in 

Gosub serial_out 

Pause 1000 

Goto start 

'Serial In Routine 

serial_in; 

Pulsout 3,1 

Low 4 

bit? = pinl 

Pulsout 5 . l 

bite = pin2 

Pulsout 5,1 

bits = pin2 

Pulsout 5 1 1 

bit4 = pin2 

Pulsout 5 , l 

bit 3 = pin2 

Pulsout 5 , l 

bit2 = pin2 

Pulsout 5,1 

bitl = pin2 

Pulsout 5 , l 

bitG = pin2 

High 4 

Return 

'Serial out Routine 

serial_out : 

pino = bit7 

Pulsout. 1. 1 

pino = bite 
Pulsout l, I 
pino = bits 
Pulsout l, 1 
pinO = bit4 
Pulsout l, l 
pinO = bit3 
Pulsout 1, 1 
pinO = bit2 
Pulsout l, 1 
pinO = bitl 
Pulsout l, 1 
pino = bito 
Pulsout 1, 1 



'Assign Data Direction Register port B to 134 
'Assign variable PortB to decimal value of 6 

'Set port E Pin2 = input / rest output 

'Set CLK low 

'Bring CLK inhibit high 

'Bring shift /load high 

'Get number from 74LS165 
'Send it out on 74LS1G4 
"Wait so I can see it 
'Do it again 



'Bring shift / load down momentarily 

'Bring CLK inhibit low 

'Load bit into BO 

'Bring CLK pin high f then low 

'Same as above 



'Bring CLK inhibit high 



'Bring pino high or low depending upon bit 
'Bring CLK line low, then high 
'Same as above 
'Same as above 



Serial Communication and Creating I/O Lines 115 



Parts List 



LOW 1 

Return 



The schematic shows that the parallel input lines to the 74LS165 are con- 
nected to V through 10,000-0 resistors. This puts a binary 1 on each input 
line. The switches used in this project are eight-position DIP switches- Each 
switch connects the bottom of a resistor to ground. When a switch is closed, it 
brings that particular pin to ground, or binary 0, By opening and closing the 
switches, we can write a binary number on the parallel input. This informa- 
tion is automatically retrieved from the 74LS165 serially by the PIC micro- 
controller. 

The PIC microcontroller takes the number retrieved from the 74LS165 and 
displays it on the 74LS164, While this project may appear trivial, it is not. 
Using this information, you can set up serial communication routines with 
other chips and systems. In upcoming chapters, we will use a serial routine to 
communicate to a serial analog-to-digital (A/D) converter and use the Basic 
Serout command to generate LCD displays. 



Sanie as Chap- 1 (and Chap- 3 for programming challenge). 



Additional components 



74LS164 Serial-to-parallel IC 

74LS165 Parallel-to-serial IC 

(8) 10-kfl V 4 -W resistors 

(1) 8-position DIP switch 

Available from: Images Company James Electronics, JDR MicroDe vices , and 
RadioShack (see Suppliers Index). 



This page intentionally left blank. 



Chapter 




LCD Alphanumeric Display 



One thing PIC microcontrollers lack is some type of video display. With a dis- 
play the program could tell us what's happening inside the chip as it is run- 
ning. The PIC could also output messages to the user and display the numeric 
value of a variable or register. A display would enhance the versatility of the 
microcontroller when given the ability to communicate and output messages 
to the user. The solution, however, is not a video display but an alphanumer- 
ic LCD display The LCD display we are using has two lines, 40 characters per 
line. The first 16 characters of each line are visible (more about this later). The 
balance of the characters on each line are off-screen. 

The particular LCD module we are using receives standard serial data {RS- 
232) at either 2400 or 9600 baud. Finally we can use the Basic Serout com- 
mands. Asynchronous communication is time-dependent, meaning that it 
requires strict time control and framing of each bit transmitted. The reason is 
that there is no clock line telling the microcontroller when the information on 
the line is valid. Thus, time (starting at the start bit) becomes the sync factor. 

In our previous serial examples, we have always had a clock line. Serial 
communication with a clock line is called synchronous communication. The 
time between transmitting or receiving bits can vary widely from microsec- 
onds to days. The bit becomes valid only when the clock line clocks in the bit. 

To communicate asynchronously (not in sync, or without a clock) requires 
the use of a start bit and a stop bit in addition to the strict time frame. As the 
name implies, the start bit informs the receiver that a byte of information is 
about to be transmitted. The start bit is followed by the bit information (usu- 
ally 8 bits but sometimes 7 bits), which is followed by the stop bit. 

Figure 9.1 illustrates a typical serial data communication, While the line is 
idle, it is in a Mark or Marking condition. The Mark is a binary 1, which may 
be a positive voltage or current. Binary is sometimes referred to as a Space: 
it may be a zero* voltage or zero-current condition. 

To initiate communication, the transmitter sends out a start bit (brings the 
line low). Next„ the 8 data bits are sent. Notice that in this serial communica- 

117 
Copyright 2000 The McGraw-Hill Companies. Inc. Click Here for Terms of Use, 



118 Chapter Nine 



Binary 1 






o 
35 



s 



Start 
LSB 














id 


0- 



Binary 



110 1 

Figure? 9.1 Standard serial output with start and stop bits. 







1 



turn, the LSB (least significant bit) is sent first and the MSB (most significant 
bit) is sent last. This is opposite to our previous synchronous serial communi- 
cation examples, 

A standard 8 -bit data package plus 1 stop bit and 1 start bit equals a total 
of 10 bits. At 2400 baud (bits per second), 240 bytes are transmitted each sec- 
ond. At 9600 baud, a maximum of" 960 bytes can be transmitted per second. 

The frequency (baud rate.) of asynchronous communication must be strict* 
ly adhered to. Since there isn't a clock line, the next bit in the sequence 
must be on the line for a precise increment of time that is determined by the 
baud rate. For instance, at 9600 baud, each bit is on the line for 104 |jls 
(microseconds ). 

In order for things to work correctly, the transmitter and receiver frequency 
cannot vary from the ideal frequency by more than 5 percent. If their respec- 
tive frequencies vary by more than that, during the course of 10 bits being 
transmitted and received, they can (but will not always) fall out of sync by 
more than a bit (104 jjls). This sync error can corrupt the entire byte; received. 

Many people looking at a variance of 5 percent don't see how this could 
cause a problem. Let's do the math real quick and see how it happens. Let's 
assume that the transmitter is 5 percent taster than the ideal frequency and 
the receiver is 5 percent slower than the ideal frequency For our example, the 
ideal frequency is 2400 baud, or 416,6 [is per bit. The transmitter is transmit- 
ting at 2520 baud (2400 plus 5 percent), or 396.8 [is per bit. The receiver is 
receiving at 2280 baud (2400 minus 5 percent), or 438.5 [is per bit. The differ- 
ence is 41-7 jjis per bit. Multiply this difference by 10 bits, and the timing is 
out by 417 (is. This is just a touch longer than the standard bit length of 416,6 
[is at 2400 baud. So it becomes clear that if the frequency varies by more than 
5 percent, the serial communication can fall out of sync, and be corrupted, by 
the time 10 bits have been transmitted and received. 



Error Detection Algorithms 



Full-featured communication packages may contain algorithms that will help 

prevent data corruption if the asynchronous time frame varies. Error detec- 
tion algorithms have not yet become part, of the PICBasic RS-232 communica- 
tion routines. 



LCD Alphanumeric Display 119 



Parity 



The atop bit is used to check each byte transmitted, using a process known as 
parity. Parity may be odd, even, or none. The serial transmission consists of a 
sequence of binary Is and Os. If we choose even parity, the receiver will count 
how many binary Is are transmitted. If the number of Is transmitted is an 
even number, the stop bit will be made a binary G, keeping the number of bina- 
ry Is even. On the other hand, if an odd number of binary Is is transmitted, 
the stop bit will be made a binary 1 to make the number of Is even. 

If parity is set to even and an odd number of binary Is is received, this is 
known as a parity error and the whole byte of information is thrown out. Parity 
errors may be caused by power surges, bad communication lines, or poor inter- 
face connections. The problems become more pronounced at faster baud rates. 

Serial Formats 

The PICBasic compiler has a few standard formats and speeds available. The 
available baud rates are 300, 1200 ? 2400, and 9600. Data are sent as 8 data 
bits, no parity, and 1 stop bit. The mode can be inverted. See the Serin and 
Serout commands in Chap. 5. 

Crystal choice 

When I first started using the Serin and Serout commands, they would not 
work properly After much hair pulling, 1 discovered that I had used a 3.57- 
MHz crystal instead of a 4.0-MHz crystal on the PIC 16F84. As soon as I 
changed the crystal to a 4.0-MHz, the Serin and Serout commands worked per- 
fectly. Later I tried a 4.0-MHz ceramic resonator for the oscillator, and this 
also worked properly. 

Thre-e-wire connection 

The LCD display requires just three wires to function, +5 V, GND, and a ser- 
ial line. The baud rate of the display may be set to either 9600 or 2400 baud. 
The serial format, is 8 data bits, 1 stop bit, and no parity, 

On the back of the LCD display, there is a five-pin header (see Fig. 9.2). The 
live-pin header has two extra pins for +5 V and GND. The pins are arranged 
in a palindrome layout, so a five-pin header may be connected either way and 
still be oriented correctly Instead of using a five-pin header, I opted for a 
three-pin header socket connected to one side of the five-pin header. 

Our first program prints out the message "Hello World.* The cursor (print- 
ing position) automatically moves from left to right. The schematic is shown in 
Fig. 9.3. 

1 LCD Test 
Pause 1000 

Bii rou t 1 , K2 4 . (2 5-4. 1 ) 

Pause 1 

serout i J N24 00, ("Hello world!"} 

End 



120 Chapter Nine 



Front View 

c uuuuuuuuuuuuuu 



o 



o 



o 



Approximate size 



Back View 




BPS switch 



down ■ £4tP0, u p ■ g wo 

Backlight 

Figure 9,2 Drawing of LCD display, front and back views. 



Contrast 



+SV 



GND 



Serial Data 



Duplicate +5V^rd GMD 
connections 



I kept this program small to show how easy it is to get a message out of the 
PIC microcontroller Notice that line 2 of the program [Serout 1,N2400, 
(254,1)] is a command. The LCD screen has 13 commands. All commands 
must be prefixed with the decimal number 254. The display will treat any 
number following the 254 prefix as an instruction. The commands are listed 
in Table 9.L 



Positioning the Cursor 



The cursor may be positioned anywhere on the LCD screen by using the fol- 
lowing command: 254, position number. The position number can be deter* 
mined by looking at Fig. 9.4. If we wanted to move the cursor to position 10 of 
the second Hne> we would use the command serout i, N2400, (254 p 2oi) 



LCD Alphanumeric Display 1 21 



Serial Line 



'2nd 



+ 5V 



11 




9 

r 



w is 

Rftfc 
fWiNI 



MCLR J 



nsci 



Q5C£ 




Ul 
_li 



Rl 



IHHf 
14 



IS. 



1=1 



PIC 16F84 



CI 
.M" 



Figure 9-3 Schematic of LCD serial display to PIC 16F84 microcontroller. 



table 9.1 Instruction Codes for LCD Display 



Code 



Instruction 



1 
2 
■S 

12 
13 
14 
16 
20 
24 
28 



Clear screen 

Send cursor to top left position (home! 

Blank without clearing 

Make cursor invisible/restore display if blanked 

Turn on visible blinking cursor 

Turn on visible underline cursor 

Mover cursor one character left 

Move cursor one character right 

Scroll display one character left (all lines) 

Scroll display one character right fall lines) 



Off-Screen Memory 



Each line of the LCD display holds 40 characters. Only the first 16 characters 
are displayed on the LCD screen. You can use the scroll commands to view the 
hidden text. 

This second program illustrates moving the cursor to the second line (see 
Fig, 9,5). 



122 Chapter Nine 



LCD Display Screen 



Clieractar ^ 



Line 1 



LCD C uiBor Positions 

3 4 £ E 7 B a 1D 11 1? 13 14 15 16 




Lin* 2 



Figure 9.4 LCD display screen, and cursor positions. 




Figure 9.5 Picture of LCD display message 



1 LCD test 
Pause 10 00 

Serout 1, N240D, (254, 1) 

Pause 2 

Serout 1, N24 0G, ("Wherever you go.") 

SCiDUl 1, H24 0, (2 54,192] 

Serout l, W24 0, ("There you are."} 
End 



As we move forward, the LCD display will be invaluable for allowing us to 
peek inside the chip registers. 



Parts List 



Same components as in Chap. 1, 



LCD Alphanumeric Display 1 23 

Additional components 

LCD-01 Serial LCD Module Backlight $ 70-00 

Available from: Images Company, James Electronics, JDR MicroDe vices , and 
RadiuShack (see Suppliers Index). 



This page intentionally left blank. 



Chapter 




Sensors: Resistive, Neural, and 

Fuzzy Logic 



Reading Resistive Sensors 



The Pot command is powerful in scope and capabilities. It allows users to eas- 
ily and accurately read resistive components and sensors. The command can 
read resistive values up to approximately 50 ? 000 f I (50 kfi) in a single program 
line. This command was first reviewed in Chap, 5. 

Pot Fin, SC&1&, V£2? 

This command reads a potentiometer or other resistive component on the Fin. 
specified (see Fig, 10,1). The programmer may choose any of the port B pins, 
to 7, to use with this command. 

Resistance is measured by timing the discharge of a capacitor through the 
resistor, usually 5 to 50 kfl. Scale is used to adjust varying R/C constants. 
For large R/C constants, set Scale to 1. For small R/C constants, set Scale to 
its maximum value of 255. Ideally if Scale is set correctly, the variable Var 
will be set to zero at minimum resistance and to 255 at maximum resistance. 



R/C Values 



Figure 10.2 graphs the decimal values generated by resistance for four common 
capacitor values. This chart should be used as a guide to determine the capac- 
itance one could use for the resistance range one needs to read. For instance, 
using a O.I-julF capacitor, the decimal values from 50 to 250 are equal to resis- 
tance values of 700 to 3500 iL For a 0-022-jjlF capacitor, the same decimal val- 
ues equal a resistance range of 3500 O to 21 kii. Once a range is chosen, the 
scale factor in the command line may be used to fine-tune the response. 

125 
Copyright 2000 The McGraw-Hill Companies. Inc. Click Here for Terms of Use. 



126 Chapter Ten 



k 



21 Pin 



CI 

;cmwf 



Figure 10.1 Resistive sensor 
(potentiometer) and capacitor connected 
to PIC pin. 



Scale 



Scale is determined experimentally. Set the device or transducer to measure 

at maximum resistance and read it with Scale set to 255- Under these condi- 
tions, the numeric value of Var produced will be an approximate "ideal" value 
for Scale. 

Ideally, with a capacitor of the proper value and the proper scale, minimum 
resistance will output a numeric value close to zero and maximum resistance 
will output a numeric output close to 255. 



Pin Exceptions 



I/O pins that are listed as just TTL may be used with the Pot command, Pins 
listed as Schmitt triggers, or 31; do not appear to work with the Pot command. 
With the PICBasic compiler and the 16F84A, we are restricted to using the Pot 
command on port B pins only. It just so happens that three of the port B pins 
(RBO, RB6, and RB7) are listed as combination TTL'ST Pins hated as TTL/ST 
on the 16F84A work with the Pot command. 

The data sheet states that RB6 and RB7 are Schmitt trigger inputs when 
used in serial programming mode- RBO is a Schmitt trigger input when con- 
figured as an external interrupt. 

To ensure that the Pot command works with other PICMicros, look at the 
particular microcontroller^ data sheet for any potential line problems. 



Resistive Sensors 



There are many resistive-type transducers that may be read using the Pot com- 
mand. The important thing to remember is that the Pot command is not an ana- 
log-to-digital (A/D) converter Converters measure analog voltages, not resistance. 
This may at first be confusing, because converters can read a voltage drop 
across a resistor^ and the drawing or schematic of reading a voltage drop may 
be similar in appearance to the Pot diagram: how r ever. the diagrams are not 
the same. To determine the difference, the key point to look for is the absence 
of a voltage source on top of the resistive component being measured with the 
Pot command. A/D converters, on the other hand, will have a voltage or cur- 
rent source connected to the top of the resistor or sensor. 



Sensors: Resistive. Neural, and Fuzzy Logic 127 



POT Command Rssistanco vs Capacitance 



25A_ 



.10 uF .friruF 



,022 uF 



205 



a 15C 

^3 



■5 100 



£ 



so _ 



01 uF 




12 3 4 5 



1» 



35 40 45 



5 20 25 
Resistance in K ohms 

Figure 1 0.2 Graph of numeric readout for various capacitors and resistances. 



50 



Test Program 



Okay, that's enough explanation; let's work with the command a little. The 
first resistive-type sensor we will look at is a flex sensor (see Fig, 10,3). 

Flex sensors have numerous applications. For instance, they may be used as 
robotic whiskers for bump and wall sensors. They have been used to create vir- 
tual reality data gloves, physical measurements, and physics applications. 

The program uses the LCD display from Chap, 9 to provide a visual readout. 
The numeric readout, with the sensor at its maximum resistaiice, provides the 
proper scale factor to use in the command in order to achieve the greatest range 
with this particular sensor, For my test, I plugged the flex sensor into the pro- 
totyping breadboard (see Fig. 10.4 J. The schematic lor the project is shown in 
Fig. 10.5. Record the numeric readout when the sensor is at its maximum resis- 
tance, and use that for a scale factor for best range and accuracy. 



Program 10.1 



"Find seal* factor and/or read the resistive sensor 
start: 



123 Chapter Ten 



4 1/2- 



■*■ 




020 thK 



ftom Inal Resistance at degre&s 10,000 ohms 



C 



Physical DbmBtislons 
Length 4.6" 
Width .2G " 
Thicfc ,020 * 



Approximate fore* 
n traded to deflect end 
90 degrees: 
5 grams 



90' 



Appmwlmate R4filstan&« at 90 degrees 35,000 Ortmo 



Eleatrical Specifieations 

Nominal Resistance at degrees 10,000 ohms 

Approximate Rml9tflnc* atM degrees 36,000 dhrne 



Figure- 1 0.3 Specification sheet on flex sensor. 



POt 1,25 5, BO 

Serout 0,N24Q0, {254, 1} 
serout O r H240Q f (#E0) 
Pause 50 
Goto start 



l Read resistance on pin 1 to 

1 determine scale 

1 Clear LCD screen 

l Send Pot values out on pin serially 

l Wait 1/2 s 

l Do it again 



If the scale factor displayed by Program 10,1 is 255 (or close to 255), the pro- 
gram is already reading the sensor at the best scale (with that particular 
capacitor). 

We read the LCD display to determine that the program and the sensor are 
both working properly. The microcontroller, of course, does not require an LCD 
display in order to read the sensor. It can read the numeric value held in the 
variable and "interpret" the results. 



Fuzzy Logic and Neural Sensors 



We are presented with a few interesting possibilities regarding the interpre- 
tation of sensor readings. Here we can have the microcontroller mimic the 
function of a neural and/or fuzzy logic device. 



Sensors: Resistive, NeuraL and Fuzzy Logic 129 




Figure 10,4 Photograph c?f tlex Henscnr connected to PIC with LCD display. 



Serial Line 



Gnd 



+5V 







Resistive 

Sensor 



i 



-L)l uF 



IS 

]Z 

Id 

IP 

? 



3 
IS 

17 



1+ 



U3 



VOD 



-3B7 

-&£* 

-5B5 

- 5B3 
3B1 

Reo/iiir 



MLLW 



0SC1 



DSCJ 



u 



s 



JW/TOCKI 

- ?jj 

R4Q 



l.7K>n 



1L 



II 



Kl 

IZP 



PIC I6F3* 






Figure 10.5 Schematic of flex sensor and LCD display connected to PIC microcontroller. 



1 30 Chapter Ten 



Fuzzy logic 



In 1965, Lotii Zadah, a professor at the University of California— Berkeley, first 
published a paper on fuzzy logic. Since its inception, fuzzy logic has been both 
hyped and criticized. 

In essence, fuzzy logic attempts to mimic the way people apply logic in 
grouping and feature determination. A few examples should clear this "fuzzy" 
definition. For instance, how is a warm sunny day determined to be not warm 
but hot instead, and by whom? The threshold of when someone considers a 
warm day hot depends on the persons personal heat threshold and the influ- 
ence of his or her environment (see Fig. 10-6), 

There is no universal thermometer that states that at 81;9°F it is warm and 
at 82° F it is hot. Extending this example further, a person living in Alaska has 
a different set of temperature values for hot days from a person living in New 
York, and both these values will be different from those of someone living in 
Florida. And let's not forget seasonal variations. A hot day has a different tem- 
perature scale in winter from that in summer. So what all this boils dow r n to 
is that the opinions of many people concerning the classification of a day as hot 
are grouped together. 

Whether any particular temperature is a member of that group is deter- 
mined by how closely that temperature matches the median value. 

The same idea can be applied to many other things, such as navigation, 
speed, or height. Let's use height for one more example. If we graph the 
height of 1000 people, our graph will resemble the first graph shown in Fig. 
10.7. We can use this graph of heights to classify shortness, average height, 
and tallness. If we applied a hard rule that stated that everyone under 5'7" is 
short and everyone taller than 6'G" is tall,, our graph w r ould resemble the sec- 
ond graph. What this does is classify someone who is 5*11-5* inches tall as 
average, when in actuality the person's height is closer to that of the tall (6'0" 
and over) group. 

Instead of hard rules, people typically use soft and imprecise logic, or fuzzy 
logic. Fuzzy logic uses groups and quantifies the membership in each group. 
Groups overlap, as seen in the fourth graph. So the person who is 5'11,5" tall 
is almost out of the medium group (small membership) and well into the tall 
group (large membership). 



Hot 



Gradation 



Hat 



1 



o 



Warm 



G-2 degrees 

Fahrenheit 



Binary 



Figure 10.6 Two graphs of temperature change, 
gradual and steep. 



Sensors: Resistive. Neural, and Fuzzy Logic 1 31 



Medium 



Medium 



Medium 



M&dlum 






r 






\ 



) 



\jM\l 



SKort 



Tal 




Gaussian Binary Digitized 

Figura 10.7 Four graphs of height: gaussian, binary, digitized, and fuzzy. 



Fuzzy 



Fuzzy logic provides an alternative to the digitized graph (the third graph), 
A high-resolution digitized graph is also accurate in classifying height. Why 
would one choose the fuzzy logic method over a digitized model function'? 
Simplified mathematics and learning functions. 

Tb implement fuzzy logic in a PIC microcontroller, one assigns a numeric 
range to a group. This is what we will do in our next project. 



Fuzzy Logic Light Tracker 



The next project we will build, is a fuzzy logic light tracker. The tracker follows 
a light source using fuzzy logic. 

The sensor needed for the tracker is a cadmium sulfide (CdS) photocell. A 
photocell is a light-sensitive resistor (see Fig. 10.8). Its resistance varies in 
proportion to the intensity of the light falling on its surface. In complete dark- 
ness, the cell produces its greatest resistance. 

There are many types of CdS cells on the market. One chooses a particular 
cell based on its dark resistance and light saturation resistance. The term 
light saturation refers to the state in which increasing the light intensity to 
the CdS cell will not decrease its resistance any further. It is saturated. The 
CdS cell I used has approximately 100 k£l resistance in complete darkness and 
500 ii resistance when totally saturated with light. Under ambient light, resis- 
tance varies between 2.5 and 10 kO. 

To ascertain the proper scale factor, we first decide what capacitor we should 
use for the best overall range. We then connect the sensor to the PIC micro- 
controller and run the scale program. The scale factor is used in the program. 

The project requires two CdS cells. Test each cell separately. There may be 
a wi thin-group variance that may change the scale factor used for a particular 
cell. In this project, I used a 0.022-(j.F capacitor, with the scale parameter set 
at 255 for both cells in the Pot command. 

The schematic is shown in Fig. 10.9. The CdS cells are connected to port B 
pins 2 and 3 (physical pin numbers 8 and 9). The photocells are mounted on a 



132 Chapter Ten 



Cadmium Sulfide 



^N ^ 






/ 



ToPSC 




o 

to 



Electronic Symbols 



Light Intensity 



Figure 10.8 Cadmium sulfide photocell. 



small piece of wood or plastic (see Fig. 10.10). For each CdS cell, two small 
holes are drilled for the wire leads to pass through. Longer wires are soldered 
to these wires and connected to the PIC microcontroller. 

One a / 32 - to V ft -in hole is drilled for the gearbox motor's shaft. The sensor 
array is glued to the gearbox motor shall (see Fig. 10-11). 

The operation of the tracker is shown in Fig. 10.12. When both sensors are 
equally illuminated, their respective resistances are approximately the same. 
As long as each sensor is within ±10 pointy of the other, the PIC program sees 
them as equal and doesn't initiate movement. This provides a group range of 
20 points. This group range is the fuzzy part in fuzzy logic. 

When either sensor falls in shadow, its resistance increases beyond our 
range, and the PIC microcontroller activates the motor to bring both sensors 
under even illumination. 



DC motor control 



The light tracker uses a gearbox motor to rotate the sensor array toward the 
light source (see Fig. 10.13). The gearbox motor shown has a 4000:1 ratio. The 
shaft spins at approximately 1 rpm. You need a suitably slow motor (gearbox) 
to turn the sensor array. 

The sensor array is attached (glued) to the shaft of the gearbox motor. The 
gearbox motor can rotate the sensor array clockwise (CW) or counterclockwise 
(CCW), depending upon the direction of the current flowing through the motor. 

Tb rotate the shaft (and sensor array) CW and CCW, we need a way to 
reverse the current going to the motor. We will use what is known as an H- bridge- 
An H-bridge uses four transistors (see Fig. 10.14). Consider each transistor as a 
simple on and off Switch, as shown in the top portion of the drawing. It*s called 
an H-bridge because the transistors (switches) are arranged in an H pattern. 




E 



■iJ 



U 

"Sb 
o 



P4 

IT? 

£ 
■I 



133 



134 Chapter Ten 



Diodes 



When switches SW1 and SW4 are closed, the motor rotates in one direction. 
When switches SW2 and SW3 are closed, the motor rotates in the opposite 
direction- When all the switches are opened , the motor is stopped. 

The PIC microcontroller controls the H- bridge, which is made of four 
TIP120 Darlington NPN transistors, four 1N514 diodes, and two 10-kQ V r W 
resistors. Pin is connected to transistors Ql and Q4 ? and pin 1 is connect- 
ed to transistors Q3 and Q4, Using either pin or pin 1, the proper transis- 
tors are turned on and off to achieve CW or CCW rotation. The 
microcontroller can stop, rotate CW, or rotate CCW, depending upon the 
reading from the sensor array. 

Make sure that the 10-kll resistors are placed properly or the H-bridge will 
not function. 

The TIP120 Darlington transistors are drawn in the schematic as standard 
NPN transistors. Many H-bridge circuit designs use PNP transistors on the 
high side of the H-bridge, The on resistance of PNP transistors is higher than 
NPN transistors. So, in using NPN transistors exclusively in our H-bridge, we 
achieve a slightly higher efficiency. 



Because the PIC is sensitive to electrical spikes (they may cause a reset or 
lockup), we place diodes across the collector-emitter junction of each transis- 
tor (Ql to Q4). These diodes snub any electrical spikes caused by switching the 

motor's windings on and off. 



Program 10,2 



1 Fuz2y logic light tracker 
start : 
Low a 
Low l 

Pot 2, 2 55, bO 

POt 3,2 55,bl 

If bo = bl Then start 

If bo > bl Then greater 

If bo < bl Then lesser 

greater : 

b2 = bo - bl 

If b2 > 10 Then cw 

Goto start 

lesser: 

b.2 = bl - bo 

If b2 > 10 Then ccw 

Goto start 

CW: 

:-:i:;li o 
Pause 100 
Goto start 

High l 
Pause 100 
Goto start 



'Fin o low 

l Pin l low 

l Read first cds sensor 

'Read second cds sensor 

l lf equal, do nothing 

l lf greater, check how much greater 

l lf lesser, check how much lesser 

'Greater routine 

l Find the difference 

l Ia it within range? If not, go to cw 

l lf it is in range P do it again 

l Lesser routine 

"Find the difference 

l ls it within range? If not go to ccw 

l Do again 

v Turn the sensor array clockwise 

l Turn on H-bridge 

"■Let it turn for a moment 

'Check again 

v Turn the sensor array counterclockwise 

'Turn on H-bridge 

x Let it turn a moment 

'Check again 



Sensors: Resistive, Neural, and Fuzzy Logic 135 



\[2' 



A 



CoS Photocell 



Side View 



.. vane 






■*-- 



wood or plastic 
block, 1/4: fhk, 



1" 



E 






M — " 



/ 



hole for gearbox 
motor shaft 



¥ 



CdS Photocell 



V 



V. 



Top View 

Figure 16.10 Sensor array: 




Figure 10.11 Sensor array connected to shaft of gearbox motor. 



136 Chapter Ten 



' Light ) 
\ Source 



ft 



Side View 



Side View 




Side View 



"A" Cell in shadow 

tracker rotates to 



Equal illunninqtiori 
no movement 



i. r*]i 



B" Cell in shadow 
tracker rotates to 



Figure 10.12 Functional behavior of sensor array. 




Operation 



Fig Lire 10.13 Photograph o f fuzzy light tr acki ng circuit. 



When run, the light tracker will follow a light source. If both CdS cells are 
approximately evenly illuminated, the tracker does nothing, lb test this, cov- 
er one CdS sensor with your linger This should activate the gearbox motor, 

and the shaft should begin to rotate. 



Sensors: Resistive, Neural, and Fuzzy Logic 137 



T 



vSWl 



■- SW2 



M 



\SW3 



H 



1 



\SVM 



o 



r 



\ 5W3 



1 



SWl \ SW2 



-I- 



I 



: 



SM 



\swi I rur 



: 



M 



SWS 



y 



\SWJ 




H-Bridge 

Electrical 
Schematic 



Figure 10.14 H-bridgc function and electrical schematic. 



If the shaft rotates in the direction opposite the light source, reverse 
either the sensor input pins or the output pins to the H-bridge, but not 
both. 



Fuzzy Output 



The output of our fuzzy light tracker is binary. The motor is either on or off, 
rotating clockwise or counterclockwise. In many cases you would want the out- 
put to be fuzzy also. For instance, let s say you're making a fuzzy controller for 
elevators. You would want the elevator to start and stop gradually (fuzzy) not 
abruptly as in binary (on-off). 

Could we change the output of our light tracker and make it fuzzy? Yes. 
Instead of simply switching the motor on, we could feed a PWM (pulse- width- 
modulation) signal that can vary the motor*s speed- 



138 Chapter Ten 



Ideally, the motor's speed would be in proportion to the difference (in resis- 
tance) of the two CdS cells, A large difference would produce a faster speed 
than a small difference. The motor speed would change dynamically (in real 
time) as the tracker brings both CdS cells to equal illumination. 

This output program may be illustrated using fuzzy logic graphics, groups, 
and membership sets. 

In this particular application, creating a fuzzy output for this demonstration 
light tracker unit is overkill* If you want to experiment, begin by using the 
Pulsout and PWM commands to vary the dc motor speed. 



Neural sensors (logic) 



With a small amount of programming, we can change our fuzzy logic sensors 
(CdS photocells) to neural sensors. Neural networks are an expansive topic; we 
are limiting ourselves to one small example. For those who want to pursue 
further study into neural networks, I recommend a book Pve written entitled 
Understanding Neural Networks (ISBN #0-7906-1115-5). 

To create neural sensors, we will take the numeric resistive reading from 
each sensor multiply it by a weight factor, and then sum the results. The 
results are then compared to a tri-level threshold value {see Fig, 10.15), 

Thus, our small program and sensors are performing all the functions 
expected in a neural network. We may even be pioneering a neural first, by 
applying a multivalue threshold scheme. Are multivalue thresholds natural 
or mimicked in nature (biological systems)? The answer is yes. For instance, 
an itch is a extremely low level of pain. The sensation of burning is actually 
the combination of sensing ice cold with warm (ooh). 



lultivalue threshold 



Typically in neural networks, individual neurons have a singular threshold 
(positive or negative) that, once exceeded, activates the output of the neuron. 
In our example, the output is compared to multiple values, with the output 
going to the best fit. 

Instead of thinking of the output as numeric values, think of each numeric 
range as a shape instead; a circle, square;, and triangle will suffice. When the neu- 
ron is summed, it outputs a shape block (instead of a number). The receptor neu- 
rons (LEDs) have a shaped receiver unit that can fit in a shape block. When a 
shape block matches the receiver unit, the neuron becomes active (LED turns on). 

In our case, each output neuron relates to a particular behavior: sleeping, 
hunting, and feeding — behaviors essential for survival in a photo vore- style 
robot. Each output shape represents the current light leveL 

Low light level: The photovore stops hunting and searching for food (light). 
It enters a sleep or hibernation mode. 

Medium light level: The photovore hunts and searches for the brightest 
light areas. 



Sensors: Resistive. Neural, and Fuzzy Logic 13d 



Sensor 
Input A 



Sensor 

Input B 



Output 
Neuron A 




Neuron B 



Figure 10.15 Simple neural sensor. 

High light level: The photovore stops and feeds via solar cells to recharge its 

batteries. 

Instead of building a photovore robot , we will use an LED to distinguish 
among the behavior states (see schematic in Fig. 10.16). You can label the 
LEDs sleeping, hunting, and feeding. Which LED will become active will 
depend upon the light, level received by the CdS cells. The finished project is 
shown in Fig. 10,17. 



Program 10.3 



"Neural demo 
'Set up 
Low 
Low l 
Low 2 
start : 

POt 3, 2 55, b0 
POt 4,2 55,bl 
W2 = b<) * 3 



l LED off: "Sleep* 
l LED 1 off; "Hunt" 
l LED 2 off: "Feed" 

l Read first sensor 
*Read second sensor 
1 Apply weight 



1 40 Chapter Ten 



Cds 

Photocell,! 



^ 



\ 






Sensor ? 



Cds 
Photocell J_ 



* 






y 



M 



Sensor I 






+5V O 



Vcc 



|;.HF:B5 



IF 



HCLft' 

05tl 
05CZ 



,K 



EBD/]NT 



*S *5Z 



1 



n^L-f 



■R3 

47un 



I-ftM/TOCKI 

I, U A p 

V£*S 



'RE 



111 ^ ftl 



,C1 



Ji. 



Jl 



HHHZ 

^1 



-^ 



PIC lbF3+ 



Figure 10.1' 6 Neural microcontroller circuit. 




Figure 10.17 Photograph of neural microcontroller circuit. 



w3 = bl * 2 
w4 = w2 + w3 
'Apply thresholds 
If w4 < 40 Then feed 
If w4 <= 3 00 Then hunt 
If w4 > 3 00 Then snooze 
1 Act ions 



'Apply weight 
'Sum results 

'Lots of light; feed 
'Medium light; hunt 
'Little light; sleep 



Sensors: Resistive, Neural, and Fuzzy Logic 141 



feed:: 
Low 
Low 1 

High 2 
Goto start 
hunt : 
Low 

High l 

LOW 2 

Goto start 
snooze : 

High 

LOW 1 
LOW 2 

Goto start 



x Feeding 



"Hunting 



1 Sleeping don't use keyword sleep 



Parts List 



Components outlined in Chap. L 



Additional components 



(2) CdS photocells 

(1) Flex sensor 

(2) G.022-jlF capacitors 

(1) 0.01-jjlF capacitor 

(4) TIP 120 NPN Darlington transistors 

(2) 10-kil resistors 
(6) 1N514 diodes 
(2) 1-kO resistors 
(1) Gearbox motor 

Available from: Images Company, James Electronics, JDR MicroDevices, and 
RadioShack (see Suppliers Index). 



This page intentionally left blank. 



Chapter 




DC Motor Control 



In this chapter we will look at a few methods of controlling a dc hobby motor. 
A single pin of the 16F84 PIC microcontroller is limited to a maximum out- 
put current of 25 mA. In most cases, this is too feeble a current to power a dc 
motor directly. Instead, we use the output of a PIC pin to turn on and off a 
transistor that can easily control the current needed to run hobby motors. The 
two methods we use incorporate transistors to switch current on and off. 



The Transistor 



The transistor of choice used in most of these examples is a TIP120 NPN tran- 
sistor. The TIP 120 is a Darlington transistor, medium power, 5-A maximum 
current, and designed for general-purpose amplification and low-speed switch- 
ing. The PNP version of this transistor is the TIP 125, 



First Method 



This is a simple on-off motor switch (see Fig. 11.1). When the PIC pin is 
brought high ? the transistor goes into conduction, thereby turning on the dc 
motor The diode across the collector-emitter junction of the transistor protects 
the transistor from any inductive voltage surge caused by switching the motor 
off. For added PIC protection, insert a signal diode and current-limiting resis- 
tor on the output pin. 

1 Program dc motor 

Pause 100 'Wait l s 

:-:i:ih o 'Turn on do motor 

Pause 1000 'Wait 1 s 

Low o 'Turn off dc motor 

End 

In the circuit, notice the 1500-jjlF capacitor. A large capacitor is needed to 
smooth the voltage dips caused by the dc motor's turning on and off Without 

143 

Copyright 2000 The McGraw-Hill Companies, Inc. Click Here for Terms of Use, 



144 Chapter Eleven 



a large capacitor, the sudden dip in voltage may inadvertantly reset the PIC 
microcontroller. A picture of this circuit is shown in Fig. 11.2. 



Bidirectional Method 



An H- bridge allows bidirectional control of a dc motor. To achieve this, it uses 
four transistors (see Fig. 11.3). Consider each transistor as a simple on-off 
switch, as shown in the top portion of the drawing. This circuit is called an H- 
bridge because the transistors (switches) are arranged in an H pattern. 



Vcc 

o 



t-SV 



10Y 



FlMhFHI 



Xl 



£ 



□ 



WHz 



is- 



IE 



H 



iL 



vss 

RAO 

RA1 

RA1 
BM/TOCKI 

RBI 



osce 



USUI 



UHCLP' 



RB£ 

RE4 
RB5 
RBI 

RB7 



YOD 



f 1 

lOKrt 



1? 
lft 
,1 

"3 



"n 

9 
10 
Ji 
,« 

13 



L4 



LIL 



Dl 






O 



npi£D 



1N31* 
5 K 




Figure 11.1 On-off motor switch using TIP120 transistor. 




Figure 11.2 Photograph of circuit. 



DC Motor Control 145 





SW2 



SW4 




SW2 



SWA 



cw 



;cvv 



10K 




H-Biidge 

Electrical Schematic 



Figure 11.3 H-bridge schematic and function. 



When switches SW1 and SW4 are closed, the motor rotates in one direc- 
tion. When switches SW2 and SW3 are closed, the motor rotates in the oppo- 
site direction. When all the switches are open, the motor is stopped. Replace 
the switches with transistors and you have an electronic H-bridge. 

The PIC microcontroller controls an H-bridge made of four TIP120 
Darlington NPN transistors, four IN 5 14 diodes, and two 10-kiJ V,-W resis- 
tors (see Fig. 11,4), The TIP 120 Darlington transistors are drawn in the 
schematic as standard NPN transistors. Pin is connected to transistors 
Ql and Q4. Pin 1 is connected to transistors Q3 and Q4, Using either pin 
or pin I, the proper transistors are turned on and off to achieve clockwise 
(CW) or counterclockwise (CCW) rotation. If, by accident or programming 
error, pins and 1 are brought high simultaneously, this will create a short 
circuit. 



146 C h a pter Eleven 



Diodes 



If the H-bridge is used properly, the microcontroller can stop, rotate CW> or 
rotate CCW the DC motor 

Many H-bridge circuit designs use PNP transistors on the high side of the 
H-bridge, The on resistance of PNP transistors is higher than NPN transis- 
tors. So, in using NPN transistors exclusively in our H- bridge , we achieve a 
slightly higher efficiency. 



Because the PIC is sensitive to electrical spikes (they may cause a reset or 
lockup J, we place diodes across the collector-emitter junction of each transis- 
tor (Ql to Q4). These diodes snub any electrical spikes caused by switching the 
motor's windings on and off- 

A picture of the PIC H-bridge controller is shown in Fig. 11.5. The following 
program rotates the motor CW for 1 s, pauses for 0-5 s, then rotates the motor 
CCW for 1 a, pauses for 0,5 s, and then repeats the sequence. 



'H-bridgft 
Low o 
Low l 
start : 
Pause 5 00 
High l 
Pause 100 
Low 1 
Pause 5 00 



'Pause for 0,5 s 
'Rotate motor in one direction 
l wait l a 
'Stop motor 
'Pause for 0.5 s 



Vcc 




P5 
-a^v* — [x 

Figure 11.4 PIC schematic, using H-bridge to control dc motor. 



DC Motor Control 147 



Hi::ili 

Pause 100 
Low 
Goto start 



'Rotate in opposite direction 
l Wait l s 
'Stop motor 
'Do it again 



Parts List 



Same components as in Chap, 1. 



Additional components 



(4) TIP 120 NPN Darlington transistors 

(2) 10-kil resistors 

(1) Dc motor 

(4) 1N914 signal diodes 

Available from: Images Company, James Electronics, JDR MicroDevices, and 
Radio Shack (see Suppliers Index). 







Figure 11.5 Photograph of complete project.. 



This page intentionally left blank. 



Chapter 




Stepper Motor Control 



In the last chapter, we programmed the PIC microcontroller to control dc motors. 
Along with dc motors, stepper motors and servomotors are types of motors that 
are commonly used. In this chapter we will examine the use of stepper motors. 

Stepper motors provide considerable advantages over dc motors. Under a 
PIC controller, stepper motors may be used for precise positioning in a wide 
range of applications, including robotics, automation, animatronics, and posi- 
tioning control. 

Stepper motors operate differently from dc motors. When power is applied to 
a dc motor, the rotor begins turning smoothly Speed is measured in revolutions 
per minute (rpm) and is a function of voltage, current, and load on the motor. 
Precise positioning of the motor's rotor is usually not possible or desirable. 

A stepper motor, on the other hand, runs on a sequence of electric pulses 
to the windings of the motor. Each pulse rotates the stepper motor's rotor by 
a precise increment. Each increment of the rotor movement is referred to as 
a step — hence the name stepper motor. The incremental steps of the rotor's 
rotation translate to a high degree of positioning control, either rotationally 
or linearly if the stepper motor is configured to produce linear motion. The 
incremental rotation is measured in degrees. 

Stepper motors are manufactured with varying degrees of rotation per step. 
The specifications of any particular stepper motor will always state the degree 
of rotation per step. You can find stepper motors with degrees per step that 
vary from a fraction of a degree (0.12°) to many degrees (e.g. ? 22.5°). 

lb become familiar with stepper motors, we will build a simple stepper 
motor controller from a PIC 16F84 and examine the operating principles of 
stepper motors. 

Stepper Motor Construction and Operation 

Stepper motors are constructed using strong permanent magnets and electro- 
magnets. The permanent magnets are located on the rotating shaft, called the 

149 

Copyright 2000 The McGraw-Hill Companies, Inc. Click Here for Terms of Use, 



150 Chapter Twelve 



rotor. The electromagnets or windings are located on the stationary portion of 
the motor, called the stater > Figure 12.1 illustrates a stepper motor stepping 
through one complete rotation. The statu r, or stationary portion of the motor, 
surrounds the rotor. 

In Fig. 12.1, position 1„ we start with the rotor facing the upper electromag- 
net, which is turned on. lb move the rotor in a clockwise (CW) rotation, the 
upper electromagnet is switched off and the electromagnet to the right is 
switched on. This causes the rotor to rotate 90° CW to align itself with the elec- 
tromagnet, shown in position 2. Continuing in the same manner, the rotor is 
stepped through a full rotation until we end up in the same position as we 
started* shown in position 5, 



Resolution 



The amount of rotation per pulse is the resolution of the stepper motor. In the 
example illustrated in Fig. 12.1, the rotor turned 90° per pulse — not a very 
practical motor. A practical stepper motor has a greater resolution (smaller 
steps); for instance, it may rotate its shaft 1 Q per pulse (or step). Such a motor 
requires 360 pulses (or steps) to complete one revolution. 

When a stepper motor is used for positioning in a linear motion table, each 
step of the motor translates to a precise increment of linear movement. 

Assume that one revolution of the motor is equal to 1 in- of linear travel on 
the table. For a stepper motor that rotates 3.75^ per step, the increment of lin- 
ear movement, is approximately 0.01 in. per step. A stepper motor that rotates 
1.0° per step would give approximately 0.0027 in. per step. The increment of 
movement is inversely proportional to the number of degrees per step. 



Half-stepping 



It is possible to double the resolution of some stepper motors by a process 
known as half-stepping. The process is illustrated in Fig. 12.2. In position I, 
the motor starts with the upper electromagnet switched on, as before. In posi- 
tion II, the electromagnet to the right is switched on while power to the upper 
coil remains on. Since both coils are on, the rotor is equally attracted to both 
electromagnets and positions itself in between the two positions (a half-step). 
In position III, the upper electromagnet is switched off and the rotor completes 
one step. Although I am only showing one half-step, the motor can be half- 
stepped through the entire rotation. 



Other types of stepper motors 



There are four-wire stepper motors. These stepper motors are called bipolar 
and have two coils, with a pair of leads to each coiL Although the circuitry of 
this stepper motor is simpler than that of the motor we are using, this motor 
requires a more complex driving circuit. The circuit must be able to reverse the 
current flow in the coils after it steps. 



off 

rxrri 



+ — H 

on > 

--s 

N 



Off 



iff ty 



off 



1 



Stepper Motor Centre I 1 51 



1 Off 



.off 

nTTTi 



on 



a* * * z 






■■. 



'off 



off 



off 



(si 

T 

N 



Off 



r 



U ' Lj l 






cf* 



■_. 



■". 



off 



on 



off 



■n? 



« * ^?| 



■"■ r" 1 - 



■^ 



r-r 



<L 



off 





+ 


Ni 




on, 




off 


1 


HI 


off 


1 " r r 


- r r 






S 





.. 



"~t 



off 



Figure 12.1 Stepper motor going through one rotation. 



152 Chapter Twelve 



off 



XJ 



+ 



on 



"I 



N 



1 



i 



Off 



p~> n [jfc 

J-J- 



off 



on 



Hi 

s 



<^. 



off 



X 



r 




On 



f 



■**■ **i 






II 






'~i 



,: -. 



off 



Ni 



off 



1 



Off 



r 



z^ 



on 



VI 



£G 



r 



T 



< 



'"i 



Off 



Figure 12.2 Half-stepping. 



Stepper Motor Control 1 53 



Real-World Motors 



The stepper motor illustrated in Figs. 12.1 and 12.2 rotated 90° per step. Real- 
world stepper motors employ a series of mini-poles on the stator and rotor. The 
mini-poles reduce the number of degrees per step and improve the resolution 
of the stepper motor. Although the drawing in Fig. 12.3 appears more complex, 
the operation of the motor is identical to that of the motors shown in Figs. 12,1 
and 12.2. 

The rotor in Fig. 12.3 is turning in a CW rotation. In position I, the north 
pole of the permanent magnet, on the rotor is aligned with the south pole of the 
electromagnet on the stator. Notice that there are multiple positions that are 
all lined up. In position II., the electromagnet is switched off and the coil to its 
immediate left is switched on. This causes the rotor to rotate CW by a precise 
amount. It continues in this same manner for each step. After eight steps, the 
sequence of electric pulses starts to repeat. 

Half-stepping with the multipole arrangement is identical to the half-stepping 
described before. 



First Stepper Circuit 



Figure 12.4 is the schematic for our first test circuit. The output lines from the 
PIC 16F84 are buffered using a 4050 hex buffer chip. Each buffered signal line 
is connected to an NPN transistor. The TIP120 transistor is actually an NPN 
Darlington; in the schematic, it is shown as a standard NPN. The TIP120 tran- 
sistors act like switches, turning on one stepper motor coil at a time. 

Multipole Operation 




Figure 12.3 High-resolution stepper motor. 



I I 




t — i rrvJ-rci r^, 

J L-L 



r^. -jj u~ -d- r- - i o-i ••-* \— 
lD CD (EiiSfflliillz 



•-• c*> i\« ^h o 
W Cj! ttCt Li 



e 



-I 



w 



K 



3 i 

DC 



V 

e 






wn 



tt 



n 



■-Oh-* £ 



3 



i 



rnrfl « 9 p 1 1 




-■■■ 



i 






U j 



"S 



tl 



e 



154 



Stepper Motor Control 1 55 

The diode placed across each transistor protects the transistor from the indue* 
tive surge created when current is switched on and of I in the stepper motor coils. 
The diode provides a safe return path for the reverse current. Without the 
diodes, the transistor will be more prone to failure and/or shorter life. 

Stepper motors 

Figure 12.5 is an electric equivalent circuit of the stepper motor we are using. 
The stepper motor has six wires coming out from the casing. We can see by fol- 
lowing the lines that three leads go to each half of the coil windings, and that 
the coil windings are connected in pairs. This is how unipolar four-phase step- 
per motors are wired. 

So, let's assume that you just picked this stepper motor and didn't know any- 
thing about it. The simplest way to analyze it is to check the electrical resis- 
tance between the leads. By making a table of the resistances measured 
between the leads, you'll quickly Find which wires are connected to which coils. 

Figure 12.6 shows how the resistance of the motor we are using looks. There 
is a 13-41 resistance between the center-tap wire and each end lead, and 26 O 
between the two end leads. The resistance reading from wires originating from 
separate coils will be infinitely high (no connection). For instance, this would 
be the case for the resistance between the blue and brown leads. 

Armed with this information, you can decipher just about any six-wire step- 
per motor you come across and wire it properly into a circuit. The stepper 
motor we are using rotates 1*8° per step. 



Yellow — ' 

White - 
Brown - 



Blue 

Black 

Red 



tth 



N 

t 

s 




Figure 12.5 Electrical equivalent of stepper motor. 



156 Chapter Twelve 



Ye flow 



White 



Brown 



t 
130 



f 

13Q 

I 



260 



Blue 



Black 



1 
130 

I 




26 Q 



130 



Red 



Figure 12.6 Resistance of stepper motor. 



First test circuit and program 

After you are finished constructing the test circuit , program the PIC with the 
following Basic program. The program has been kept small and simple to show 
how easy it is to get a stepper motor moving. Table 12,1 shows that each step 
in the sequence turns on one transistor. Use the table to follow the logic in the 
PICBasic program. 

When you reach the end of the table, the sequence repeats, starting back at 
the top of the table. 



1 stepper motor controller 
symbol TRISE = 134 
Symbol PortB = 6 
symbol ti = be 
ti = 25 

Poke TRISB,0 

start : 

Poke porta, l 
Pause ti 
Poke porta, 2 
Pause ti 
Poke porta, 4 
Pause ti 
Poke porta, B 
Pause ti 
Goto start 



initialize TRISB to 134 

Initialize variable Ports 

Initial ti delay 

Set delay to 25 ius 

Set port B lines output 

Forward rotation sequence 

step l 

Delay 

step 2 

Delay 

Step 3 

Delay 

Step 4 

Delay 

Do it again 



to 6 



Stepper Motor Control 1 57 



TABLE 1 2.1 Full-Stepping 





Transist-ors 




Port B 
output 

(decimal) 


Qi 


Q2 Q3 


Q4 


On 


— — 


— 


1 


— 


On 


— 


2 


— 


On 


— 


4 


— 


— — 


On 


8 



One rotation 



Using whole steps, the stepper motor requires 200 pulses to complete a single 
rotation (36071.8° per step), Having the PIC microcontroller count pulses 
allows it to control and position the stepper motor's rotor. 



Second Basic Program 



This second PICBasie program is far more versatile. The user can modify pro- 
grammed parameters (time delay) as the program is running, using one of the 
four switches connected to port A. Pressing SWI lengthens the delay pause 
between steps in the sequence and consequently makes the stepper motor 
rotate more slowly. Pressing SW2 has the opposite effect. Pressing SW3 makes 
the program halt the stepper motor and stay in a holding loop for as long as 
SW3 is closed (or pressed). Rotation direction (CW or CCW) is controlled with 
the SW4 switch. Pressing the SW4 switch reverses the stepper motor direc- 
tion. The direction stays in reverse for as long as SW4 is pressed (or closed). 



'Stepper motor controller 

Symbol TRISE = 134 

Symbol TRISA = 133 

Symbol ports = 6 

Symbol portA = 5 

Symbol ti = b6 

ti = 100 

Poke TRISB,0 

start : 

sequence 

Poke ports,, l 

Pause ti 

Poke port B, 2 

Pause ti 

Poke ports, 4 

Pause ti 

Poke portB., B 

Pause ti 

Goto -cheek 

st art 2 : 



initialize TRISE to 134 

initialize TRISA to 13 3 

'Initialize variable ports to 6 

"Initialize variable portA to 5 

"■initial ti delay 

l Set delay to 100 ms 

l Set port B lines output 

'Forward stepper motor rotation sequence 

L Step 1 

L Delay 

l step 2 

"■Dela^ 

L step 3 

L Delay 

l Step 4 

"■Delay 

"■Jump to check switch status 

"Reverse motor rotation sequence 



158 Chapter Twelve 



Poke ports, B 

Pause ti 

Poke portB,4 

Pause ti 

Poke ports, 2 

Pause ti 

Poke ports, 1 

Pause ti 

Goto check 

check : 

Peek port A, BO 

if bito = o Then loopl 

If bitl = Then loop2 



Then hold3 
Then start 



if bit2 = 

If bit 3 = o 

Goto start2 

loopl : 

Poke ports, 

ti = ti + s 

Pause 5 

If ti > 2 50 Then holdl 

Peek port A, bo 

if bito = o Then loopl 

Goto check 

loop2 : 

Poke ports, 

ti = ti - 5 

Pause 50 

If ti < 20 Then hold2 

Peek port A, bo 

If bitl = Then loop2 

Goto check 

holdl : 

ti = 245 

GOtO loopl 
hold2 : 
ti = 25 

goto loop2 

hold3 : 

Poke ports, 

Peek portA, bo 

If bit 2 = Then hold3 

Goto check 



Step 1 

Delay 

Step 2 

Delay 

Step 3 

Delay 

Step 4 

Delay 

Jump to check switch status 

Switch status 

Peek the switches 

If SWl is closed, increase ti 

If SW2 is closed, decrease ti 

Stop motor 

Go forward 

Go reverse 

Increase delay 

Turn off transistors 

Increase delay by 5 ms 

Delay 

Limit delay to 25 D rns 

Check switch status 

Still increasing delay? 

If not, jump to main switch status check 

Decrease delay 

Turn off transistors 

Decrease delay by 5 ms 

Pause 

Limit delay to 20 ;i\s 

Check switch status 

Still decreasing delay? 

If not, jump to main switch status check 

Limit upper delay 

To 24 5 ms 

Go back 

Limit lower delay 

To 25 ms 

Go back 

Stop stepper motor 

Turn off transistor 

Check switches 

Keep motor off? 

If not, jump to main switch status check 



The schematic for this program is shown in Fig. 12.7, In the photograph oi 
the circuit (.see Fig, 12.8), the four switches are difficult to make out. They are 
the four bare wire strips behind the PIC microcontroller. The top sides of the 
bare wire strips are connected to +5 V through 10-kil resistors, A wire from 
each switch is connected to the appropriate pin on port A. A single wire is con- 
nected to ground and is used to close any of the switches by touching the bare 
wire strip. 



Half-Stepping 



Half-stepping the motor effectively doubles the resolution. In this instance, it 
will require 400 pulses to complete one rotation. Table 12,2 shows the switch- 



ZQ 



rry <u «-» O 



± 




£uj E but 



QQ ffli d 03 ££i LU [U 

8 

Q_ 



S*-i"y — p_ --" -71 fi,l -"- 



c 1 



n 








> 










a. 


■™ 


fM 




_i 


r_i 


LJ 




u 


ill 


tj'l 




£ 


O 


□ 






to 

> 



TT 









ift 



oS 



tt 






LJ 

i— p 



LT' 



u-^ 



in 









mrm") 



Hi 




3S 



153 



1 60 Chapter Twelve 




Figure 12.& Photograph of circuit. 



TABLE 12.2 Half-Stepping 





Transistors 






Qi 


Q2 


Q3 


Q4 


Port B output (decimal } 


On 


— 


— 


— 


1 


On 


On 


— 


— 


3 


— 


On 


— 





2 


— 


On 


On 





6 


— 


— 


On 





4 


— 


— 


On 


On 


12 


— 


— 


— 


On 


8 


On 


— 


— 


On 


9 



ing logic needed in a program. 

When you reach the end of the table, the sequence repeats, starting back at 
the top of the table, 



The ti Delay Variable 



The ti variable used in each Basic program controls a delay pause whose pur- 
pose is to slow down the output sequence to port B. Without the pause, the 
sequence might run too fast for the stepper motor to respond, causing the step- 
per motor to malfunction. 

You may want to vary the ti variable in the program depending upon your 
PIC crystal speed. You can experiment with the ti variable until you find the 
beat range for your particular PIC, 



Stepper Motor Control 1 61 



Troubleshooting 



If the motor doesn't move at all, check thy diodes. Make sure you have them 
in properly, facing in the direction shown in the schematic. 

If the stepper motor moves slightly and/or quivers back and forth, there are 
a number of possible causes, 

1. If you are using a battery power supply, the batteries may be too weak to 
power the motor properly. Note: Batteries wear out quickly because the cur- 
rent draw from stepper motors is usually high, 

2. If you substituted another transistor for the TIP 120 NPN transistor,, the 
substitute transistor may not be switching properly or the current load of 
the stepper motor may be too great. Solution: Use TIP 120 transistors, 

3. You have the stepper motor improperly wired into the circuit. Check the 
coils using an ohmmeter and rewire if necessary. 

4. The pulse frequency is too high. If the pulses to the stepper motor are 
going faster than the motor can react, the motor will malfunction. The 
solution to this problem is to reduce the pulse frequency. The pulse fre- 
quency is controlled by the ti variable in the program. Increasing the val- 
ue of this variable will slow down the pulse frequency to the stepper 
motor, 

UCN 5804 Dedicated Stepper Motor ICs 

We have controlled the stepper motor directly from the PIC chip. There are 
dedicated integrated circuits that w r e can use to control stepper motors, IF 
we incorporate stepper motor controller chips into the design, the PIC con- 
troller can control multiple stepper motors. These controller chips can do 
most of the grunt work of controlling a stepper motor. This simplifies our 
program and overall circuit while enhancing the hardware — a good combi- 
nation. 

One chip I use frequently is the UCN 5804 stepper motor controller. The 
pinout of the UCN 5804 is shown in Fig, 12,9, Features of the UCN 5804 are 
as follows: 

■ 1.25- A maximum output current (continuous) 

■ 35-V output sustaining voltage 

■ Full- step and half-step outputs 

■ Output enable and direction control 

■ Internal clamp diodes 

■ Power-on reset 

■ Internal thermal shutdown circuitry 



162 Chapter Twelve 



Output b 

Kbd 

Output d 

Ground 

Output c 

Kac 
Output a 



1 



4 
5 



<W 



O 



T> 



OE 



Logic 




Hvct 



15] Output Enable 



14| Direction 



13 

12 



Ground 



jl] Step Input 



10| Half Step 



9 One -Phase 



Figure 12.9 Pinnut of the UCN 5804. 



The schematic for a stepper motor controller using a dedicated IC is shown 
in Fig. 12.10, and a photograph of the circuit is shown in Fig. 12.11- The 
UCN 5804 is powered by a 5-V dc power supply. While it is internally pow- 
ered by 5 V 3 it can control stepper motor voltages up to 35 V. 

Notice in the schematic that there are two re sis tors „ labeled rx and ry, 
that do not show any resistance value. Depending upon the stepper motor, 
these resistors may not be necessary- Their purpose is to limit current 
through the stepper motor to 1.25 A (if necessary). 

Let's look at our 5-V stepper motor. It has a coil resistance of 13 11. The 
current draw of this motor will be 5 V/13 O = 0,385 A or 385 mA, well below 
the 1.25-A maximum rating of the UCN 5804, So in this case resistors rx 
and rv are not needed and mav be eliminated from the schematic. 

mf ml 

Before we move on, however, let's look at one more case, a 12-V stepper 
motor with a phase (coil) resistance of 6 ii. The current drawn by this 
motor is 12 V/6 II = 2 A. This is above the maximum current rating of the 
UCN 5804. To use this stepper motor, you must add the rx and ry resis- 
tors. The rx and ry resistor values should be equal to each other, so that 
each phase will have the same torque. The values chosen for these resis- 
tors should limit the current drawn to 1.25 A or less. In this case, the 
resistors should be at least 4 O (5 to 10 W), With the resistors in place, 
the current drawn is 12 V/10 il= 1.20 A. 

The inputs to the UCN 5804 are compatible with CMOS and TTL S mean- 
ing that we can connect the outputs from our PIC microcontroller directly to 
the UCN 5804 and expect it to function properly. The step input (pin 11) to 
the UCN 5804 is generated by the PIC microcontroller. The Output Enable 
pin enables the stepper motor when held low and disables (stops) the step- 
per motor when brought high (see Fig. 12.10). 



H 



N 



#j 



3 3 



T L** _l 



I i § e l 



E u 



) PIC16F84 



3 3 



s 3 I i I I 



*i I rt 




n 



H" 



o 

E 

a 

a 

to 



|OT^ 



mm 



> 



oh -a 9 




wl Iml ^ Ict- m 




g SF 



^ 



a 






ii- 



it N 

M — I — h* 



I*' 



nj 



(5tSjWJl_JWW^ 



V 



n 



i* m 



Al 



r J WA-" 



H 14 



■CD 



r*. 



XJ 



u 



JW— It 



so 



CD 



o 

00 

i 

Mi 



H 



s 



ii 

5 



3 



163 



164 Chapter Twelve 




Figure 12.11 Photograph of stepper motor circuit with the UCN 5804. 



Pins 10 and 14 on the UCN 5804 are controlled by switches that bring the 
pins to a logic high or low. Pin 10 controls whether the output to the step- 
per motor will be full-step or half-step, and pin 14 controls direction. If we 
want, these options may also be put under the control of the PIC. The pins 
are brought to logic high and low to activate the options in the same way as 
the Output Enable pin was activated- 

The following is a PICBasic program that uses a dedicated stepper motor 1(1 



'Stepper motor w/ UCN 5B04 

Symbol TRISB = 134 

Symbol Ports = 6 

Poke TRISB, 

Lowl 

start : 

Puis out 0, 10 00 

Goto start 



* initialize TRISB to 134 
'initialize variable Ports to 6 
'Set PortE lines output 
"Bring Output Enable low to run 

'Send 10 -ma pulse to UCN 5 804 
4 Do it again 



In this case, I again wrote a simple core program to show how easily you 

can get the stepper motor running. You can, of course, add options to the pro- 
gram to change the pulse frequency, connect the direction and step mode 
pins, etc. 



Stepper Motor Control 1 6 



Parts List 




(1) UCN 5804 


Stepper motor controller chip 


(1)5V 


Stepper motor, unipolar (six-wire) 


(1) 115 V/5 V 


Stepdown wall transformer 


(6) 


1N914 diodes 


CD 


TIP12Q NPN transistors 


CD 


7805 voltage regulator 


CD 


Rectifier, 50-V, 1-A 


CD 


150- jjlF capacitor 


CD 


4050 hex buffer chip 



Available from: Images Company, James Electronics, JDR MicroDe vices ? am 
RadiuShack (see Suppliers Index). 



This page intentionally left blank. 



Chapter 




Servomotor Control 



Servomotors (set* Fig, 13.1), are used in most radio-controlled model airplanes 
and expensive model cars, boats , and helicopters. Because of this hobbyist 
market, servomotors are readily available in a number of stock sizes. 
Servomotors have many applications in animatronics, robotics, and position- 
ing control systems. 

Fundamentally servomotors are geared dc motors with a positional feed- 
back control that allows the rotor to be positioned accurately The specifica- 
tions state that the shaft can be positioned through a minimum of 90° (±45*). 
In reality, we can extend this range closer to 180° (±90° ) by adjusting the posi- 
tional control signal. 

There are three wire leads to a servomotor Two leads are for power, +5 V and 
GND. The third lead feeds a position control signal to the motor The position 
control signal is a single variable-width pulse. The pulse can be varied from 1 to 
2 ms. The width of the pulse controls the position of the servomotor shaft. 

A 1-ms pulse rotates the shaft to the extreme counterclockwise (CCWj posi- 
tion ( -45°). A L5-ms pulse places the shall in a neutral midpoint position (0°). 
A2-ms pulse rotates the shall to the extreme clockwise (CW) position (+45°). 

The pulse width is sent to the servomotor approximately 50 times a second 
(50 Hzh Figure 13,2 illustrates the relationship of pulse width to servomotor 
position. 

The first program sweeps the servomotor back and forth like a radar antenna. 
The schematic is shown in Fig. 13.3. I'm purposely keeping the program small in 
order to illustrate the core programming needed. A picture of this project is 
shown in Fig, 13.4. 

The variable B3 holds the pulse-width value. Suppose we examine the 
Pulsout command 

Pulsout Pin t Period 

Pin> of course > is the pinout. The number used in Period is specified in 10- pus 
(microsecond) units. In the program, we are starting with B3 equaling 100, or 

167 

Copyright 2000 The McGraw-Hill Companies, Inc. Click Here for Terms of Use. 



1 68 Cha pter Th irteen 




Figure 13.1 Picture of hobby 4- to 6-sV (42-oz torque} servomotors. 

100 x 10 jxs = 1000 (is or 1 ms. If we look back at our servo specifications t we 
see that a l*ms pulse rotates thy servo's arm to its leftmost position. 

The program continues to smoothly increment the B3 variable, sweeping the 
servomotor's arm to its rightmost position at B3 = 200 (2 msX At this point, 
the process reverses, and B3 begins to decrement back to 100. 

This sweeping back and forth continues for as long as the program is run. 



"Servo motor program 

'Sweep left to right like a 

b3 = 100 

sweep : 

Pulsout , b3 

Pause 18 

b3 = b3 + l 

If b3 > 2 00 Then sweepback 

Goto sweep 

sweepback: 

b3 = b3 - 1 

Pulsout o, hi 

Pause 18 

If b3 < 100 Then sweep 

Goto sweepback 



radar antenna 

1 initialise at left position 

"■Send signal to servomotor 
"•Transmit signal 50 -SO Ets 
1 increment servo pulse width 
1 2nd of forward sweep? 
1 Ke ep swee p i ncf 

'Decrement servo pulse width 
"■Send pulse to servomotor 
'Send it 50-60 H2 
"End of sweepback? 
'Keep going back 



Servomotor Control 169 



PuJ** Width 1-2 ms 



r- * 



r. 



n 



r. 



P&ricud 18 ms 



Z.J 



1 ins Pulsft Train 
Serw> Motor pQ$l|Ecn 
left 



r 



[ l | 5*rvo Motor Position 

v^ .# nlionange 



.-■- 



N Z nil Puls*3 Train 

► , Strvfl Motor Petition 

y" Fight 



Figure 13.2 Pulse- width train delivered to servomotor Relationship of pulse width to servomotor 
armature position. 



+ 



5tf O 




+5V 



O 



It 



IE" 
II 

10" 

a* 

8 



3 

1 

LJ" 



JL 



RBb 
RBS 
PEh 

PB2 
R& ■ 

PBiMINT 



HCLR J 
OSCl 
OSC2 



RW/TOCKl 
RJL3 

RAL 
PAO 

VS5 

SI 



L* 



LI 



PI 



+MHz 






PIC 16F34 



El 
.luF 



Figure 13.3 Schematic of basic servomotor sweeper controller (automatic). 



Extending Servomotor Range 



A pulse- width variance from 1 to 2 ms will provide a full 90° of rotation. To 

extend this range up to 180% you need to use pulses smaller than 1 ms and 
greater than 2 ms. 

If you decide to extend the rotational movement from your servo, you should 
be aware of certain problems that may arise. In particular, the servomotor has 



170 Chapter Thirteen 




Figure 13.4 Picture of automatic servomotor sweeper. 




Cl 



SPOT 
Cen+er Off C 

Swi"ch 



Figure 13,5 Schematic of manual control servomotor. 



end stops that limit how far the shaft can rotate in either direction. If the PIC 
is sending a signal to the servomotor that is past either end stop, the motor will 

continue to fight against the end stop. In this stalled condition, the servomotor 
will draw increased current and generate greater wear on the gearing inside 
the motor 3 neither of which is desirable. 

There is a within-group variance among servomotors from the same manu- 
facturer as well as a variance among servomotor manufacturers. So while one 



Servomotor Control 1 71 

servo may need a 2,8-ms pulse for a Full rotation extension, another may 
require only a 2-4-ms pulse width. 

When you decide to go out of the prescribed range of acceptable pulse widths 
(1 to 2 ms) for servomotors, you should check the individual servomotor to 
ensure that you are not stalling. 



Manual Servo Control 



This next project allows you to control the servomotor via a few switches. The 
schematic is shown in Fig. 13,5. The switch used is a single-pole, double-throw 
(SPDT) with a center off position. The center off position is essential If there 
is not a center off position, you will need to use two switches instead of one. 

The operation of this switch is simple. To activate the servo, move the switch 
in the upward direction. The servo will begin to rotate in one direction. To stop 
the motor, move the switch to the center off position. To rotate the servo in the 
opposite direction, push the switch lever down. Stop the servo as before, by 
placing the switch in the center off position. The complete project is shown in 
Fig, 13,6, 



"■Manual servo controller 

Symbol porta = 5 

bB. = 150 

start : 

Peek porta, bO 

if bit a = o Then sweepl 

If bitl = o Then sweepr 

Puis out 0,b3 

Pause IS 

Goto start 

sweepl : 

b3. = b3 + 1 

Puis out 0,b3 



'initialize: servo at center position 

"Look at switches on port A 

% is swi pressed? 

% is SW2 pressed? 

'Hold servo in current position 

% Send signal 50-60 Hz 

'Check switches again 

*SW1 is pressed 

" Increment servo pulse width 

'Send signal to servo motor 







Figure 13.6 Picture of manual control servomotor. 



1 72 Cha pter Th irteen 



Pause 18 

if b3 > 2 00 Then holdl 

Goto start 

sweepr : 

b3 = b3 - l 

Pulsout r b3 

Pause 18 

i£ b3 < 100 Then hold2 

Goto start 

holdl : 

b3 = 200 

Goto start 

hold2 : 

b3 = 100 

Goto start 



Transmit signal 50-60 he 

Maximum sweepl value? 

Keep sweeping 

SW2 is pressed 

Decrement servo pulse width 

Send pulse to servomotor 

Send it 50-SO Hz 

Minimum sweepr value? 

Keep going back 

Hold maximum value to 2 00 



Hold minimum value to 100 



Multiple Servomotors 

Using the routines in tht* last servomotor program , you can easily connect 
three servomotors to the PIC 16F84 and still have four open I/O lines avail- 
able for other duties. 

The next project, provides manual control for multiple (two) servomotors. It 
uses the core programming routines from the previous example. 

The schematic adds a switch and a servomotor (see Fig. 13.7). 



'Multiple serve controller program 


Symbol porta = 5 




hJ = 150 




b4 = 15 




start : 




Peek porta, bo 




If bito = Then 


sweepl 


If bitl = Then 


sweepr 


If bit2 = o Then 


sweepl 2 


If bit 3 = o Then 


sweepr 2 


Pulsout , b3 




Pulsout l, b4 




Pause 18 




Goto start 




SWCCp 1 : 




b3 = b3 + 1 




Pulsout , b3 




Pulsout 1, h4 




Pause 18 




If b3 > 200 Then 


holdl 


Goto start 




sweepr s 




hi = b3 - 1 




Pulsout ( b3 




Pulsout 1, b4 




Pause 18 




If b3 < 1D0 Then 


hold2 


Goto start 




holdl ; 




b3 = 200 




Goto start 




hold2 : 




b3 = 100 








"initialize servo l at center position 
H Initialize servo 2 at center position 



Look at switches on port A 

Is SMI pressed? 

is SW2 pressed? 

is SW3 pressed? 

is SW4 pressed? 

Hold servo l in current position 

Hold servo 2 in current position 

Send signal 50-60 Hz 

Check switches again 

swi is pressed 

increment servo pulse width 

Send signal to servo 1 motor 

Hold servo 2 position 

Transmit signal 5 0—60 Hz 

Maximum sweepl value"? 

Keep sweeping 

SW2 is pressed 

Decrement servo pulse width 

Send pulse to servomotor 

Hold servo 2 position 

Send it 50-60 Hz 

Minimum sweepr value? 

Keep going back 

Hold maximum value to 2 00 



'Hold minimum value to 100 



Servomotor Control 1 73 




rCl 

■ L....F 



Figure 13.7 Schematic of multiple servomotor controller (manual J. 



Goto start 

'Sftcond servomotor routine 

sweepl2 : 

b4 = b4 + 1 

Pulsout i,b4 

Pulsout Q f b3 

Pause IS 

if b4 > 2 00 Then hold3 

Goto start 

sweep r 2 : 

b4 = b4 - 1 

Pulsout l, b4 

Pulsout 0, b3 

Pause 18 

If b4 < 100 Then hold4 

Goto start 

hold3 : 

b4 =20 

Goto start 

hold4 : 

b4 = 10 

Goto start 



SW3 is pressed 

Increment servo pulse width 

Send signal to servo 2 motor 

Hold servo 1 position 

Transmit signal SO- 60 Hz 

Maximum sweepl value? 

Keep sweeping 

SW4 is pressed 

Decrement servo pulse width 

Send pulse to servo 2 motor 

Hold servo l position 

send it 50-60 Hz 

Minimum sweepr value? 

Keep going back 

Hold maximum value to 2 00 



Hold ::i_::_:i._.:i. vdl^i Lu 100 



The completed project is shown in Fig. 13.8. 



Timing and Servomotors 



Parts List 



As you experiment with servomotors, it is necessary to feed the pulse signal to 
the servomotor 50 to 60 times per second. It is important to keep this in mind 

when running multiple servomotors or other time-critical applications. 



Same components as in Chap. 1 



174 Chapter Thirteen 




Figure 13.8 Picture of multiple manual servomotor controller. 



Additional components 

For each servomotor: 



(1) Servomotor, 4-6 V, HS 300 (42-oz torque) or equivalent 

(1) SPDT toggle switch with center of!" position 

(2) 10-kO l / r W resistors 

Available from: Images Company, James Electronics., JDR MicroDe vices, and 
RadioShack (see Suppliers Index). 



Chapter 




Analog-to-Digital (A/D) 

Converters 



Analog- to- digital (A/D) converters read an analog voltage and convert it into a 
digital equivalent number that can be read by a computer or microcontroller. 
Moat phenomena in the real world are analog: intensity of light, sound, tem- 
perature, pressure, time, gravity, etc. 



Analog Signal 



Any analog signal, regardless of its origin., is infinitely variable between any 
two points. This holds true no matter how close those two points are. For 
instance, the number of possible volt readings between 1 V and 2 V is infinite. 
Some possible values are LI V, 1.0000001 V, and 1.00000000000000000001 V. 
As you can see, voltage can vary by infinitesimal amounts. 



Digital Equivalents 



A digital equivalent of an analog signal is not infinitely variable. The digital 
equivalent changes in discrete, predefined steps. Figure 14,1 illustrates an 
analog signal and a digital equivalent. Arising voltage (analog signal) plotted 
digitally against time would jump in increments in a staircase-like fashion. 
Each step in the staircase represents a predetermined change in voltage, up 
or down, based upon the resolution and threshold of the A/D converter. 

We can also observe from this drawing that the digital equivalents are updated 
only once per clock cycle. Complete clock cycles are indicated on the drawing as 
vertical tick marks. Therefore, in between complete clock cycles, no (digital) 
change is possible, The rise and fall of the digital equivalent signal change 
must be equal to a multiple of the A/D converter's resolution, indicated on the 
drawing as horizontal tick marks. 



175 

Copyright 2000 The McGraw-Hill Companies, Inc. Click Here for Terms of Use. 



1 76 Chapter Fourteen 



A/D Converters 



There are a number of PIC microcontrollers with built-in A/D converters. Since 
we have done all our work with the PIC 16F84, I will continue to work with 
this chip by connecting an external A/D converter. 

My next book, on PIC microcontrollers, will deal with more advanced PIG 
microcontrollers with built-in A/D converters. 

To minimize the number of I/O lines needed, we will use a serial A/D con- 
verter- The TLC 548 is shown in Fig. 14.2. This serial A/D chip will require just 
three lines off our PIC microcontroller. The specifications on this A/D convert- 
er are as follows: 

CMOS technology 
8-bit resolution 

Reference input voltages (±) 



1 



Analog 
Voltage 




Digital 
Equivalent 



Clock Cycles 



Figure 14.1 Plot of analog signal and digital equivalent. 



Analog- to- Digital (A/D) Converters 1 77 



Conversion time, 17 jjls max 

40,000 samples per second (approxj 

Built-in sample and hold 

Wide power supply range, 3 to 6 V 

4-MHz internal clock 

Low power consumption, 6 mW (typical.) 

This chip is easily interfaced to our microcontroller. 



Setting the Reference Voltage 



Looking at the pinout of the integrated circuit shown in Fig. 14.2 ? we can see 
that there are two pins for setting the reference voltages, REF 4 (pin 1) and 
REF- (pin 3), The voltages placed between these two pins become the range 
of voltages the analog- to- digital converter will read and convert to a digital 
equivalent. 

The voltage difference between these two reference (REF) pins must be at 
least 1 V. REF+ should not be greater than the + power supply to the chip 
(V ). Consequently, REF™ should not be less than the GND supply to the chip. 

If desired, the REF + pin can be tied to V" and the REF- pin can be tied to 
GND. This will allow the chip to read voltages between GND and V . 



Voltage Range and Resolution 



Assuming a V of h 5 V, with REF + tied to V and REF- tied to ground, what 
is the resolution of our converter chip? We take our voltage range from REF 
to REF + , in this case 5 V, and divide by our 8- bit resolution (or 256), which 
equals 5 V/256 = 0.019 V 

Looking back at Fig. 14. 1, we could visualize each upward voltage increment 
(tick mark on vertical axis) as equaling 0.019 V. 

Suppose the sensor or unit from which we need to read a voltage varies by 
only 2 V, say from 1 to 3 V If we wanted to increase the resolution of our A/D 



Top View 



Ref+ 
Analog In 

Ref- 

GND 







v ww y 






1 


1 


H 


8 


I 




2 


O 


7 




1 


3 


Oi 


6 


J 




4 


CO 


5 





I/O Clock 
Data Out 
CS 



Flgum 14.2 Pinout of the TLC 548. 



1 73 Cha pter Fourteen 

converter, we could set REF- to 1 V and REFH- to 3 V. Now what is the reso- 
lution of our A/D converter? It's calculated just as before- We take the voltage 
range from REF- to REF I , in this case 2 V, and divide by 256 (8-bit resolu- 
tion). So 2/256 = 0,0078 V, 

Interpreting the Results 

Suppose the PIC microcontroller is reading the number 100 from the serial 
A/D converter. What does this number represent? Let's go back to our first 
case, where V is 5 V, the voltage range is 5 V, REFH- is tied to V , and REF— 
is tied to ground. Our resolution is 0.019 V. So reading 100 from the A/D chip 
means that it is reading a voltage of 100 x 0.019 V, or L9 V. 

In the second case, where REF- is at 1 V, REF+ is a +3V, range equals 2 
V, and step resolution equals 0.0078 V. Here reading the number 100 from the 
serial A/D converter is equal to a voltage of 1.78 V L(100 X 0.0078 V = 0.78 V); 
0,78 V plus REF- (1 V) = 1,78 VJ, 

Serial Chip Control 

Now that the basic calculations are finished, it's time to actually implement 
the chip. We need three I/O lines to use the serial A/D chip. The CS pin is a 
Chip Select; the small line or bar above the CS nomenclature tells us that the 
pin is active negative. Thus, when the CS pin is brought low, the chip is select- 
ed. A clock signal is sent to the chip's I/O clock pin- We read the serial data 
from the data out pin. 

We will have to create our own serial routine as before, since the RS-232 
communication protocol will foul the chip with its stop and start bits. But we 
will use the RS-232 routine to display the information from our A/D onto our 
LCD display. 

Serial Chip Sequence 

This sequence shows how the serial A/D chip can be accessed easily, 

1. Bring the CS pin low. This immediately places the most significant bit 
(MSB) on the data out pin. 

2. The falling edges of the first four I/O clock cycles shift out the second, third, 
fourth;, and fifth most significant bits. At this point, the on-chip sample and 
hold begin sampling the analog input. 

3. Three more I/O clock cycles bring out the sixth, seventh, and eighth con- 
version bits on the falling edges. 

4. Bring CS high and the I/O clock line low. 

The first schematic is shown in Fig, 14.3. We are using a 5- or 10-kJl poten- 
tiometer. By moving the wiper back and forth, you can see how the number on 
the LCD changes. You can calculate the voltage the number represents by mul- 
tiplying the number on the display by 0.019 V. 



Analog-to-DSgital (A/D) Converters 1 79 



"Serial a/d converter 

Low l 

start : 

Gosub serial_in 

1 LCD routine 

serout 3, K24Q0, (254 f 1) 

Pause l 

Serout 3, K2400, (#b0) 

Pause 100 

Goto start 

'Serial in routine 

serial_in : 

Low 2 

bit 7 = pinO 

Pulsout 1,1 

bite = pi no 

Pulsout 1,1 

bits = pino 

Pulsout 1,1 

bit4 = pino 

Pulsout 1,1 

bit 3 = pino 

Pulsout 1,1 

bit 2 = pino 

Pulsout 1,1 

bitl = pino 

Pulsout 1,1 

bito = pino 

Pulsout 1,1 

High 2 

Return 



program 

1 Bring i/o clock low 



l Let me see display 



'Bring cs down low 
L Load bit 7 into BO 
'Bring CLK pin high 
L Load bit 6 into BO 
"Bring CLK pin high 
L Load bit 5 into BO 
'Bring CLK pin high 
"Load bit 4 into BO 
'Bring CLK pin high 
l l*oad bit 3 into BO 
'Bring CLK pin high 
'Load bit 2 into BO 
'Bring CLK pin high 
'Load bit l into BO 
'Bring CLK pin high 
'Load bit o into BO 

'Bring cs high 



then low 
then low 
then low 
then low 
then low 
then low 
then low 



Toxic Gas Sensor 



A toxic gas sensor responds to a large number of airborne compounds (see Fig, 
14,4). It is a resistive device; when it detects airborne compounds* ite resistance 



Serial 
Line 




.ci 

'.lwF 



Figure 14.3 Test circuit using a lG-kfi potentiometer. 



1 80 Cha pter Fourteen 



Parts List 



decreases. Figure 14.5 is a schematic of the toxic gas sensor project Pins 2 and 5 
on the gas sensor are connected to an internal heater coil. The heater draws 115 
mA at 5 V Pins 4 and 6 are connected together internally., as are pins 1 and 3. 
You can solder wires to the sensor directly or purchase a round six-pin socket. 

Polarity isn't important to the heater coil or resistive element. You may 
notice that as the sensor is operating, it will feel quite warm. Don't be 
alarmed; this is normal. 

Since the sensor has been in storage prior to your receiving it, it will require 
an initial 2-min warm-up period when it is first turned on- The length of the 
warm-up period will decrease with repeated use. After the warm-up period, 
you can test the sensor with a number of household items. 

For the first test, breathe on the sensor. The numbers on the LCD display 
should go up as it detects the carbon dioxide in your breath. For another test, 
release gas from a butane lighter The sensor should react immediately to the 
butane gas. 

Figure 14,6 is a photograph of the complete project. 

In the next chapter, we will use this circuit to make a toxic gas alarm and 
automatic ventilator control. 



Same components as in Chap. 1, 



Additional components 



TLC548 Serial A/D $8 95 
Toxic gas sensor $32.00 

6-pin socket $1.50 

Available from: Images Company (see Suppliers Index) 




MM 

Figure 14,4 Photograph of the toxic gas sensor. 



Ana log-to- Digital (A/D) Converters 1 B1 




* 



*1.G 



5 




"' hottn view ' 



o. 



I 



Pint ^1 heater 

Pms l p. 3 iitteftMi'-y corrected 

Pirtft ^ t 4 iniernnLy connccte-d 



-pm/ToOu 



tlcw !:«« 

-RM 



PIC 1&F8H 






Figure 14,5 Schematic using toxic gas sensor. 




Figure 1 4.6 F holograph of t-oxic gas sensor circuit. 



This page intentionally left blank. 



Chapter 




Controlling AC Appliances 



In our previous work, we connected the output of our PIC microcontrollers 
mostly to CMOS or TTL logic ( + 5 V) applications. What we will do in this chap- 
ter is use the PIC microcontroller output to control ac loads and appliances. 

For our demonstration project, we will take the toxic gas sensor from Chap, 
14 and make an automatic ventilation control system. This project is for 
demonstration purposes only The PIC chip senses the real-world environment 
and then controls a real- world function. It is NOT, under any circumstances, 
to be used in any commercial or private application as a toxic gas detector, con- 
troller, or ventilation control. 

The project is simple: When the PIC microcontroller senses a toxic gas, it 
will turn on an electric fan and keep it on until the gas concentration returns 
to a safe level. 

Before we build our project, we will provide some useful information that 
you will need when designing an ac control system for yourself 

Inductive and Resistive Loads 

Any device we power or control may be called a load. Whatever the electrical 
device (or load) may be, it will fall into one of two electrical categories, induc- 
tive or resistive. The type of device the load is will determine the type of cir- 
cuit used to power and control it. 

It's pretty easy to distinguish an inductive load from a resistive load. An 
inductive device (load) has wire coils and windings in it; examples are motors, 
transformers, relays, and solenoids. A resistive device doesn't have any induc- 
tive coils or wire windings; examples are incandescent lights, toasters, coffee 
makers, and heaters. 

lb control ac loads> we will use an optocoupler triac. The MOC 3010 is an 
optocoupler triac that is packaged as a six-pin DIP chip (see Fig. 15.1). When 
the PIC outputs a high signal ( + 5 V) on one of its I/O pins, connected to pin 1 
on the MOC 3010, it will turn on an internal LED. The internal LED triggers 

183 

Copyright 2000 The McGraw-Hill Companies, line. Click Here for Terms of Use, 



184 Chapter Fifteen 



a photosensitive internal triac (pins 6 and 4) ? which in turn will trigger an 
external triac that powers the load. 



Circuit Construction 



Tb build these circuits, you can not safely use the solderless breadboard. The volt- 
ages and currents are greater than can be safely handled on the breadboard. 

Please be careful. I don't want people accidentally shocking or electrocuting 
themselves. Always be extra careful when building any circuit that uses 
household electric power. The power available from your household electric 
wiring is more than enough to reduce your circuit to a cinder or to give you a 
nasty shock or worse. 

Figure 15.2 shows a resistive-type ac appliance circuit fragment (minus the 
PIC controller)- An inductive appliance controller is shown in Figure 15-3 (again 
minus the PIC microcontroller). The resistor R (in each schematic) is your main 

Li 

load or appliance that is being powered- The triac chosen will determine the max- 
imum power (in watts) that may be safely controlled- The power rating on the tri- 
ac I used (see Parts List.) is 6 A at 200 V, more than enough for a 50-W fan. 

1 advise constructing the inductive-type circuit, since it can be used for both 
resistive and inductive types of appliances. This will eliminate any potential 
questions later on, such as, Is this a resistive or an inductive control circuit? 



MDC5010 




H Figure 15,1 MOC3010 pinout. 



Resistive Load 



RL 




Rl 

LQUrr 



Jl 

HQt>C.]0 



ai 



^z 



Figure 15.2 Resistive ac appliance circuit Fragment. 



Contrail in g AC Appliances 1 85 



Inductive Load 




iaan 






£L 



Ul 
HDC3QIQ 



2M«ro^ z 



CL 




Figure 15.3 Inductive ac appliance circuit fragment. 

The schematic: fragment for resistive loads can be used for comparison with 
the inductive circuit or, if you wish, as a dedicated resistive load controller. 

Since I believe that most readers will be interested in controlling ac appli- 
ances or devices in their home, Fig, 15.4 is the circuit we will build. All the 
components must be soldered to a printed circuit board. Make sure that any 
lines and wiring carrying the household power are adequately insulated and 
covered. 

The triac I used is rated at 200 V at 6 A, which means that it is capable of 
handling 1200 W. In order to pass that much current, the triac would require 
an adequate heat sink. I advise you to keep the maximum power under 250 W. 



"Serial A/D converter and 

Low 1 

start : 

Gos.ub serial_in 

1 LCD routine 

serout 3, N24Q0, (254, 1} 

Pause 1 

serout 3, H24D0, (#b0) 

Pause 100 

If bo > 190 Then fanl 

If bo < 191 Then fan2 

Goto start 

'Serial in routine 

serial_in : 

Low 2 

bit? = pinO 

Pulsout 1,1 

bite = pi no 

Pulsout 1,1 

Bits = pi no 

Pulsout 1,1 

bit4 = pinO 

Pulsout 1,1 

bit 3 = pi no 

Pulsout 1,1 

bit 2 = pi no 

Pulsout 1,1 



toxic gas program 

'Bring I/O clock low 



l Let me see display 
l Turn fan on 
'Turn fan off 



Bring cs down low 
Load bit 7 into BO 
Bring CLK pin high, 
Load bit G into BO 
Bring CLK pin high, 
Load bit s into BO 
Bring CLK pin high, 
Load bit 4 into BO 
Bring CLK pin high, 
Load bit 3 into BO 
Bring CLK pin high, 
Load bit 2 into BO 
Bring CLK pin high, 



then low 
then low 
then low 
then low 
then low 
then low 






w 



*J 



c 



HDh* 




u 

LI 



a 



I 



iy-i 



"JO 

Lw 



U. 



L> 
Irt 
Q 






> 






Jj lA ji m rj -) o 
r\i UiflS ED CHIP CD 



i- 
s 
#. m^y — io 

i*! fc ill L£ te 



t.-« 



LTi 




(86 



Controlling AC Appliances 167 



bitl = pino 
Pulsout 1,1 
bitO = pino 
Pulsout i r -I 
High 2 
Return 
f anl : 
High 4 
Goto start 
f an2 : 
Low 4 
Goto start 



l Load bit l into BO 

1 Bring CLK pin high, then low 

l Load bit o into BO 

* Bring cs high 



Test Circuit 



If you want to test the program and circuit without building thy entire circuit, 
you can. Remove the appliance power control section and replace it with a 
resistor and LED (see Fig. 15.5). When the microcontroller senses toxic gas, it 
turns on the LED, When the gas dissipates, the LED goes off" 




Figure 1 5.5 Schematic for testing circuit and program. 



183 Chapter Fifteen 



Smart Control 



I would like to make a point regarding smart controls: They need feedback to 
determine if a particular action is being performed. To make this point, I wish 
to draw an analogy. 

Let's say that you've just returned from a newspaper stand with your favorite 
magazine. You sit in a chair and reach over to turn on the lamp to read by, but 
there is no light. "Darn.," you say to yourself You look down to the socket to see 
if the lamp is plugged in. It is. You look over to the clock on the wall that's on 
the same fuse as the lamp. The clock is ticking away, so you know you have 
juice going to the lamp. You flick the lamp switch a couple of times, to make 
sure the switch isn't stuck. Now you take the lampshade off the lamp, and, sure 
enough^ a black spot on the bulb lets you know that it's burned out. You replace 
the bulb, the lamp works fine, and you finally get to read the magazine. 

Now, there's nothing remarkable about this incident. But it is a good exam- 
ple of a smart control. When the lamp was turned on, the person knew that 
the light wasn't lit and went through various steps to locate and correct the 
problem. But what about a microcontroller? Had it been the microcontroller's 
job to turn on the lamp, it would not have known whether the light was on, 

lb build a smart control, we must give the microcontroller feedback so that 
it can check to see if the action was successful- For the light example, we might 
use a photocell or photoresistor for a feedback signal. If the feedback gave a 
negative response, the microcontroller could ring an alarm or send a signal. 

Keep this information in mind so that if someday you find that you have 
a need for a smart controller somewhere, your PIC chip can handle it. 



Electronic Noses 



The toxic gas sensor is the forerunner of the electronic nose. High-quality, 
highly selective electronic noses have numerous applications in many indus- 
tries — food spoilage, perfume, medicine, and law enforcement, to name a few. 
The toxic gas sensors are not digital sensors, they are analog. If there is suf- 
ficient within-group variance in the response to compounds, a group of sensors 
can be wired into a neural network for detection of specific odors. 



Parts List 



Same components as in Chaps. 1, 9, and 14, 



Additional components 



MOC3010 optocouple triac RadioShack PN# 276-134 

2N6070 triac (or equivalent.) RadioShack PN# 276-1000 

0.22-p.F capacitor RadioShack PN# 272-1070 

Line cord RadioShack PN# 278-1255 



Controlling AC Appliances 1 89 



470-il V 4 -W resistor RadioShack PN# 271-1317 
180-12 V 4 -W resistor RadioShack PN# RSU 11344702 
L2-kO l / r W resistor RadioShack PN# RSU 11344884 



Miscellaneous components 

Ac appliance small fan 



Available from: Images Company, James Electronics, JDR MicroDevkes, and 

RadioShack (see Suppliers Index). 



This page intentionally left blank. 



Appendix 




Hexadecimal Numbers 



The hexadecimal number system has a base of 16. It was found early on that 
base 16 (hexadecimal) is an ideal number system for working with digital 
computers. The reason this is so is that each nybble (4-bit number) is also 
base 16, so one hexadecimal digit can represent a 4-bit number. 

As computer processors grew, they used larger and larger numbers- 
Regardless of how large these numbers become, they are, for the most part, 
evenly divisible by 4 bits. Early personal computers were 8-bit., then came 
16-bit processors. Current personal computers are 32-bit. Future computers 
will be 64 -bit, then 12 8- bit, and so on. 

The PlCMicro chips do not follow this convention. Instead, they use an odd 
number of bits throughout their internal structure (see Fig. 6,6). 



Decimal 


Binary 


Hexadecimal 





0000 





1 


0001 


1 


2 


0010 


2 


3 


0011 


3 


4 


0100 


4 


5 


0101 


5 


6 


0110 


6 


7 


0111 


7 


8 


1000 


8 


9 


1001 


9 


10 


1010 


A 


11 


1011 


B 


12 


1100 


C 


13 


1101 


D 


14 


1110 


E 


15 


mi 


F 


16 


00O10000 


lOh 



191 
Copyright 2000 The McGraw-Hill Companies, Inc. Click Here for Terms of Use. 



192 Appendix A 



Notice that 10 in hex is equal to 16 in our standard base 10. Sometimes a 
lowercase h is placed behind the number to identify it as a hex number and 
not base 10. An 8-bit number can be represented by 2 hexadecimal digits. The 
hex number FF represents the maximum number 8 bits can hold, 255. 

As with base 10, each number going toward the left is a multiple. For 
instance, 20 in base 10 is really 2 times 10. In hexadecimal, 20 is 2 times 16. 

Many compilers and assemblers use hexadecimal numbers to program code. 
When examining code for the PIC microcontrollers, you will undoubtedly run 
across hexadecimal as well as binary numbers. 



Program Answers 



Chapter 3 



Chapter 4 



1 Program 3 , IB 
Symbol TRISE = 
symbol Ports = 
Symbol X = B0 
'initialize po 
Poke TRISE, o 
loop: 

For X = to 2 

Poke Ports, x 

Pause 250 

Next X 

Goto loop 

1 Program 3 > 2B 

'Program binar 

'initialize va 

symbol TRISE = 

symbol Ports = 

'Initialize po 

Poke TRISB, 

loop: 

SO = 1 

Bl = 

S3 = 1 

Poke Ports, BO 

Pause 2 50 

For B2 = to 

El = B0 * 2 

E0 = Bl 

S3 = B3 +■ Bl 

Poke Ports, B3 
Pause 250 
Next B2 
Poke Ports, o 
Pause 250 
Goto loop 



134 
6 

rt {s) 



SB 



l Set TRISB to 134 

l Set variable Ports to 6 
1 Initialize variable X 

1 set port B pins to output 



'Place X value at port to light LEDs 

1 Pause, or counting proceeds too fast to see 
'Next X value 



y progression counting 
riables 

134 'Assign TRISB to 134 

6 'Assign variable Ports the decimal value of 6 
rt {&} 

x Set port B pins to output 

L Set variable to l to start counting 
v set variable to 

1 Place B0 value at port to light LEDs 

•■without pause, counting proceeds too fast to see 



6 



■■Calculate next binary progressive number 

*Set B0 to new value 

u Hew holding variable 

x Place new value at port to light LEDs 

'Without pause, counting proceeds too fast to s 

"■Next loop value 

■■Reset to D 



1 Program 4 . lb 
Symbol TRISB = 134 
symbol TRISA = 133 



'Set TRISB 
'Set TRISA 



Appendix A 193 



Chapter 8 
Simple 



symbol Ports = 6 

Symbol Port A = 5 

'initialize portfs) 

Poke TRISB,0 

Poke TRISA, 1 

loopl : 

For B2 = to 255 

Poke Ports, B2 

Pause 2 50 

Peek PortA,E0 

If bito = Then loop2 

Mext B2 

Goto loopl 

!oop2 : 

Poke Ports, =0 

Peek PortA,BQ 

If bitO = 1 Then loopl 

Goto loop2 



'initialize variable Ports to 6 
"initialize variable PortA to 5 

'Set port B pins as output 
"Set pin l of port A as input 
'Counting loop 

'Place bo value at port to light LEDs 

'Without pause, counting proceeds too fast to see 

'Peek SW1 status on port A 

'If closed, jump to loop2 

'Next bO value 

'Repeat 

'Noncounting loop 

'Turn off all LEDs 

'Peek swi status on port A 

'If opened, jump back to loopl 

'Repeat 



1 Serial interface 
symbol TRISE = 134 
Symbol Ports = 6 
'Initialize portfs) 
Poke TRISB,0 
Low 2 
start : 
bo = 160 
Gosub serial 
Gosub display 
Pause 100 
bO = 25 5 
Gosub serial 
Gosub display 
Pause 100 
bo = 
Gosub serial 
Gosub display 
Pause 100 
Goto start 
display : 
Pulsout 2,1 
Return 

'Serial out routine 
serial : 
pino = bit7 
Pul sout 1 , 1 
pinO = bite 
Pulsout 1, l 
pino = bits 
Pul sout 1 , 1 
pinO = bit4 
Pulsout l, l 
pino = bit3 
Pul sout l , l 
pinO = bit2 
Pulsout 1, 1 
pino = biti 
Pul sout l , l 



'Assign TRI5B to 134 

'Assign variable Ports the decimal value of 6 

'Set port B as output, port 
'Set Latch Enable low 

'Put number 160 {10 10 oooo) into bo 
'Output the number serially to 74164 

'Wait 1 s 

'Put number 255 {liiimi) into bo 

'Output the number serially to 74164 

"Wait 1 s 

'Put number {oooooooo} into bo 

'Output the number serially to 74164 

'Wait l s 
'Do it again 

'Pulse Latch Enable high 



'Bring pin high or low, depending upon bit 
'Bring CLK line high then low 
1 Same as above 
'Same as above 



194 Appendix A 



Not simple 



pino = bito 
Puis out lj i 
Low l 
Return 



'REM serial SP025S 
Symbol TRISB = 134 
Symbol portb = G 
Symbol porta = 5 
1 initialize ports 
Poke TRISB, 12 9 



1 check, line status 

start : 

Pause 2 00 

Peek porta /bo 

if bfl = Then three 

If bito = Then hello 



1 Set RB7 as input, all others (rbq to RB€) as 

outputs 
1 Could be switch or could be TTL logic signals 



1 Give a human a chance to press a button (s) 

* Read port A 

1 Check both lines first (normally bo = 3) 

1 Check line o/alternative command: If bo = 2 
If bitl = Then world x check line l/alternative command: If bo = l 
Goto start 



"Say word hello 

hello: 

For b3 = to 5 

Lookup b3, {27 r 7,45, 15,53,1) ,bQ 

Gosub speak 
Next b3 
Qoto start 

"Say word world 

world : 

For b3 = to 4 

Lookup b^ {46 P 5 B, £2,21,1} , bQ 

Gosub speak 

Next b3 

Goto start 



l lt*s not just a word, it's a routine 

l Loop using number of allophones 

'Decimal addresses of allophones 

1 speak subroutine 

l Get next allophone 

l Do it again from the beginning 



'Procedure similar to hello 



"Say sentence See you next Tuesday. 

three: "Procedure similar to hello 

For b3 = to 19 

Lookup b3 f {55,55, 19 f 1 8 4 9, 22, 1, 11 , 7 , 42 , 55 , 13 , 2 , 13 , 31 , 43 , 2 , 33 , 2G , 1) t bO 

Gosub speak 
Next b3 
Goto start 



pino = bit7 
Pulsout l r l 
pinO = bit6! 
Pul sout l , l 
pino = bits 
Pulsout 1,1 
pinO = bit4 
Pulsout l f l 
pino = bit3 
Pulsout l, 1 
pinO = bit2 
Pul sout l r l 
pino = bitl 



'Subroutine to speak allophones 
'Set up allophone address 
'Pulse CLK line 



Appendix A 195 



Pulsout 1,1 
pino = bite 
Pul sout l , 1 
Low 6 

PaUSQ 1 

High 6 

wait : 

Peek portb,bO 

If bit7 = Then wait 

Return 



""Bring ALD low 

1 Pause l ras for everything to latch 

1 Bring ALD high 

""Look at port B 

1 check SBY line {0 = talking, l = finished) 

"•Get next allophone 



Suppliers Index 



Images Company 

39 Seneca Loop 

Staten Island, NY 10314 

(718)698-8305 

http ■ //w w w.i magesco . com 

James Electronics 
1355 Shoreway Road 
Belmont, C A 94002 
(650) 592-8097 
http ://\vwwj ameco. com 

JDR Microdevices 
1850 South 10 Street 
San Jose, CA 95112-4108 
(800)538-5005 
http i/Av ww.j dr.com 




^5 

■J 2 






LJ O 










L. 

-: 



tt 



c 
QC cm 






'■■J 



k 



>i** 

-*\/*>^ 



C! 

J-l Ph 

IK * 



N ^ 



+ 



□ 

LJ 



_l 

5 



1*1 



Ll 

5 

Li. 



"J 



LJ 



rs kd m * m cu 






m en m m rn ill Dj CE1 
ii li ft: tt Lt S. KiS: 



ST 

o 

i- 

* n ai -« q 
■^ * -i. i * 

Ct Ct lE tcL ti 



u r i 



IT- 



I' 







X LJLl U LJCJ CQ it 






c^ 



3 

a 

y& 

b 



« 



■-■j 



> 

G- 



nj 



Wxirt 



X 



jj 



jTfQ J U~> ^ rt fu ■* 









£*fll 





a 




* 




q> 


1" 


Lt 


£ 


=- 
m 


ft 


■jT 



Ai 
O 

a_ 

ul 



l-u 



<y 



IV 



._, - 

3 



K 



o 



MI 






ad 

i 

c 
*1 

cu 

r o 

c: 

c 
-i— i 

j3 
c 

"s 

-l-l 

+-• 

a 

i 
■s 



3 

El 



196 



Index 



This page intentionally left blank. 



Index 199 



AC adapters , 64 

AC appliances control, 183-189 

circuit construction guidelines for, 
184-187 

loads, inductive/resistive, 183-184 

noses, electronic, 188 

parts list for, 188-189 

smart controls , 188 

test circuit, 187 
A/D converters [see Analog-to~digital 

converted s)J 
Allophones, 94-96 
Alphanumeric display, LCD (see LCD 

alphanumeric display) 
Analog-to-digital (A/D) converterfs), 175-181 

and digital equivalents of analog 
signal, 175 

parts list for, 180 

reference voltage, setting, 177 

results, interpretation of, 178 

serial chip control/sequence in, 
178-179 

specifications for, 176-177 

toxic gas sensor example, 179-181 

voltage range/resolution for, 177-178 
Auto- repeat, 53 



Button command (Cont): 

structure of, 51 

variables used in, 58-59 
Bytes, 36 



Call command (PICBasic language), 67 

Central processing unit (CPU), 1, 2, 36 

CMOS devices, 41-42 

Comments, 47-48 

Compiler software, 4—5, 8, 11-14 

Cost of PIC chips, 3-4 

CPU (see Central processing unit) 

D 

DC motor control, 143-147 
bidirectional control, 144-146 
diodes for, 146-147 
on-off motor switch, simple, 

143-144 
parts list for, 147 
transistor, choice of, 143 

Debouncing, 52-53 

Diodes: 

in DC motor control, 146-147 
in fuzzy logic sensors, 133, 134 

Dynamic modification, 55-57 



B 

Banks, 91 

Basic language, 2 

Basic Stamps, 2 

Binary, 36, 41-45 

Bit shift correcting, 109-111 

Bits, 36 

Branch command (PICBasic 
language), 66 

Breadboard, solderless, 28-30 

Button command (PICBasic language), 
51-55, 66-67 
auto-repeat function of, 53 
debounce features of, 52-53 
example using, 53-55 



E 

Eeprom command (PICBasic 

language), 67 
EEPROM memory, 2, 3, 93 
Electrical binary, 41 
End command (PICBasic language), 

67-68 
EPIC programming carrier board, 5, 6, 

22-23 
EPIC software: 

installation of, 14-15 
troubleshooting, 24-25 
versions of, 23-24 
Error detection algorithms, 
118-119 



199 



200 Index 



For.- Next command (PICBasic 

language), 68 
Fuzzy logic sensors, 128, 130-138 

DC motor control, 132-134 

diodes in, 134 

light tracker project, 131-137 

theory behind, 130-131 

G 

Gosub command (PICBasic 

language), 68 
Gosub Nesting command (PICBasic 

language), 68 
Goto command (PICBasic language), 69 

H 

Half-stepping, 150, 152, 158, 160 
Harvard architecture, 35-36, 90 
Hexadecimal number system, 36, 

191-192 
High command (Basic), 46-47 



I2cin command (PICBasic 

language), 69-70 
I2cout command (PICBasic language), 70 
Identifiers, 48 

If, .Then command (PICBasic 
language), 57-58, 70-71 
Input command (PICBasic language), 

71-72 
I/O lines, creating, 103-115 
bit shift correcting, 109-111 
CLR pin, clearing, 106 
eight input lines, expanding four I/O 

lines to function like, 111-115 
parts list for, 115 
programs for, 106-108 
and serial communication, 103-106 
I/O lines, reading, 51-64 
Basic I/O commands, 62 
and Button command, 51-55 



I/O lines, reading (Cont): 
dynamic modification, 55-57 
multiple statements, 59-62 
and Peek command, 59-61 
pin 7, status of, 53-55 



LCD alphanumeric display, 117-123 

crystal, choice of, 119 

cursor, positioning of, 120, 122 

error detection algorithms for, 
118-119 

and off-screen memory, 121, 122 

parts list for, 123 

standard formats/speeds available 
for, 119 

three-wire connection for, 119-120 
Let command (PICBasic language), 

72-73 
Light tracker project, 131-137 

circuit schematic, 133 

DC motor control, 132, 134 

diodes in, 133 

operation of, 136-137 
Line labels, 48 
Linguistics, 94, 96-97 
Lookdown command (PICBasic 

language), 73 
Lookup command (PICBasic 

language), 73-74 
Low command (PICBasic language), 

46-47, 74 
Low cost of PIC chips, 3-4 
LPT1 port, 24 
LPT2 port, 24 

M 

Memory, 1-3 

Microcontrollers): 

benefits of using, 1-4 

definition of, 1 

and future of electronics, 
1-2 



Index 201 



Motor controls (see DC motor control; 

Servomotor control; Stepper 

motor control) 
Multiple statements, 59-62 

N 

Nap command {PIC Basic language), 
74-75 

Neural sensors, 128, 138-141 

multivalue threshold with, 138-139 
program, sample, 139, 141 

Noses, electronic, 188 

O 

On-off motor switch, simple, 143-144 
Oscillator modes (PIC 16F84 

microcontroller), 85-87 
Output command (PIC Basic 

language), 75 



Parallax Company, 2 
Parity error, 119 
Path (DOS command), 16-18 
Pause command (PICBasic 

language), 75 
Peek command {PICBasic language), 

59-61, 75-76 
PIC applications subdirectory, creating, 

15^16 
PIC chips, 2 

Basic- language programs for, 7 

compiler program for, 8 

and Harvard architecture, 35—36 

items needed for working with, 4-7 

low cost of, 3-4 

parts list for working with, 8-9 

programming, 4, 8, 22-23 
PICBasic compiler, 4, 46-47 
PICBasic language, 65-84 

Branch command, 66 

Button command, 66-67 

Call command, 67 



PICBasic language (Cont.) 

Eeprom command, 67 

End command, 67-68 

For,. Next command, 68 

Gosub command, 68 

Gosub nesting command, 68 

Goto command, 69 

I2cin command, 69-70 

I2cout command, 70 

l£;Then command, 70-71 

Input command, 71-72 

Let command, 72-73 

Lookdown command, 73 

Lookup command, 73-74 

Low command, 74 

Nap command, 74-75 

Output command, 75 

Pause command, 75 

Peek command, 75-76 

Poke command, 76 

Pot command, 76-77 

programming in, 7 

Pulsin command, 77 

Pulsout command, 77-78 

Pwm command, 78 

Random command, 78-79 

Read command, 79 

Return command, 79 

Reverse command, 79 

Serin command, 79-80 

Serout command, 81-82 

Sleep command, 82-83 

Sound command, 83 

Toggle command, 83 

Triggers command, 80-81 

Write command, 84 
PICBasic Pro compiler, 5 
PIC 16C61 microcontroller, 35 
PIC 16C84 microcontroller, 35 
PIC 16F84 microcontroller, 
5-7, 35-49, 85-91 

CMOS, 41-42 

counting binary program example, 42-45 



202 Index 



PIC 16F84 microcontroller (Cont): 
counting binary progression program 

example, 45—46 
CPU in, 36 

electrical binary, using, 41 
Harvard architecture of, 35-36, 90 
input signals, reading, 49 
I/O ports of, 37-41 
oscillator modes, 85-87 
register map, 90-91 
resets, 87-89 
TRIS Registers, 37-41 
TTL logic devices, 41-42 
user-available RAM, 43-44 
Poke command (PICBasic language), 76 
Pot command (PICBasic 

language), 76-77 
Pulsin command (PICBasic 

language), 77 
Pulsout command (PICBasic 

language), 77-78 
Pwm command (PIC Basic- 
language), 78 

R 

Random command (PICBasic 

language), 78-79 
Random- access memory (RAM), 

1, 43-44 
Read command (PICBasic 

language), 79 
Read-only memory (ROM), 1, 93 
Register map (PIC 16F84 micro- 
controller), 90-91 
Resets (PIC 16F84 microcontroller), 

87-89 
Resistive sensors, 125-129 
pin exceptions with, 126 
program, example, 127-128 
R/C values, 125-126 
reading, 125 
scale for, 126 



Return command (PICBasic 

language), 79 
Reverse command (PICBasic 

language), 79 
ROM (see Read-only memory) 
Rotor, 149-150 

S 

Sensors, 125-141 

fuzzy logic, 128, 130-138 

neural, 128, 138-141 

parts list for, 141 

resistive, 125-129 
Serial communication, 103-106 
Serin command (PICBasic language), 

79^80, 119 
Serout command (PICBasic language), 

81-82, 119, 120 
Servomotor control, 167-174 

and functioning/components of 
servomotors, 167-169 

manual control, 171-172 

multiple servomotors, 172-173 

parts list for, 173, 174 

range, extension of, 169-171 

and timing, 173 
Single-chip computers, 1 
Sleep command (PICBasic language), 

82-83 
Smart controls, 188 
Solderless breadboard, 28-30 
Sound command (PICBasic 

language), 83 
Speech synthesizer project, 93-102 

allophones generated by, 94-96 

circuit schematic, 99 

components needed for, 102 

linguistic background for, 94, 
96-97 

program for, 100-102 

SPO-256 speech synthesizer chip in, 
93-94, 97 



Index 203 



SPO-256 speech synthesizer chip, 

93-94, 97 
Stepper motor control, 149-165 

construction/operation of motor, 
149-152 

dedicated stepper motor controller 
chips, integration of, 161-164 

half-stepping, 150, 152, 158, 160 

mini-poles, use of, 153 

parts list for, 165 

programs, sample, 156-159 

resolution, 150, 151 

test circuits, 153, 159 

ti delay variable, using, 160 

troubleshooting, 161 

types of stepper motors, 150 
Symbols, 48 

T 

Ti variable, 160 

Toggle command (PlCBasic language), 83 

Toxic gas sensor, 179-181 



Transistors, 143 

Triggers command (PlCBasic 
language), 80-81 

TRIS Register, 37^41 

Troubleshooting : 

EPIC software, 24-25 
stepper motor control, 161 
"Wink* program, 33 

TTL logic devices, 4 1-42 



Variables, 48-49 

W 

"Wink" program, 18-22, 25-29 

running, 32 

troubleshooting, 33 
Write command (PlCBasic language), 

84 
Z 

ZIF adapter sockets, 63 
ZIF sockets, 64 



This page intentionally left blank. 



ABOUT THE AUTHOR 

John lovirie is the author of several popular TAB titles that explore the 
frontiers of scientific research. He wrote the cult classic Robots^ 
Androids, and Animatrons, as well as Homemade Holograms: The 
Complete Guide to Inexpensive, Do- it- Your self Holography, Kirlian 
Photography: A Hands-On Guide; Fantastic Electronics: Build Your 
Own Negative-Ion Generator and Other Projects; and A Step into 
Virtual Reality.