embedded syatems circuits and programming · chap ter 4 – in put and output devices 41 4.1 ob...

884
EMBEDDED SYSTEMS CIRCUITS and PROGRAMMING Julio Sanchez Maria P. Canton

Upload: others

Post on 14-Sep-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

K13700 Cover 3/26/12 11:27 AM Page 1

C M Y CM MY CY CMY K

During the development of an engineered product, developers often

need to create an embedded system—a prototype—that demonstrates

the operation/function of the device and proves its viability. Offering

practical tools for the development and prototyping phases, Embedded

Systems Circuits and Programming provides a tutorial on microcontroller

programming and the basics of embedded design.

The book focuses on several development tools and resources:

• Standard and off-the-shelf components, such as input/output

devices, integrated circuits, motors, and programmable

microcontrollers

• The implementation of circuit prototypes via breadboards, the

in-house fabrication of test-time printed circuit boards (PCBs),

and the finalization by the manufactured board

• Electronic design programs and software utilities for creating PCBs

• Sample circuits that can be used as part of the targeted

embedded system

• The selection and programming of microcontrollers in the circuit

For those working in electrical, electronic, computer, and software

engineering, this hands-on guide helps you successfully develop

systems and boards that contain digital and analog components

and controls. The text includes easy-to-follow sample circuits and their

corresponding programs, enabling you to use them in your own work.

For critical circuits, the authors provide tested PCB files. Software, code,

and other materials are available at www.crcpress.com.

Computer Science

EMBEDDEDSYSTEMS CIRCUITS

andPROGRAMMING

Julio SanchezMaria P. Canton

EMBEDDEDSYSTEMS CIRCUITS

andPROGRAMMING

Julio SanchezMaria P. Canton

EMBEDDED SYSTEMS CIRCUITSand PROGRAMMING

SanchezCanton

6000 Broken Sound Parkway, NWSuite 300, Boca Raton, FL 33487711 Third AvenueNew York, NY 100172 Park Square, Milton ParkAbingdon, Oxon OX14 4RN, UK

an informa business

K13700

Page 2: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

EMBEDDEDSYSTEMS CIRCUITS

andPROGRAMMING

K13700_FM.indd 1 3/14/12 5:36 PM

Page 3: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

This page intentionally left blankThis page intentionally left blank

Page 4: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

EMBEDDEDSYSTEMS CIRCUITS

andPROGRAMMING

Julio SanchezMaria P. Canton

CRC Press is an imprint of theTaylor & Francis Group, an informa business

Boca Raton London New York

K13700_FM.indd 3 3/14/12 5:36 PM

Page 5: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

CRC PressTaylor & Francis Group6000 Broken Sound Parkway NW, Suite 300Boca Raton, FL 33487-2742

© 2012 by Taylor & Francis Group, LLCCRC Press is an imprint of Taylor & Francis Group, an Informa business

No claim to original U.S. Government worksVersion Date: 20120224

International Standard Book Number-13: 978-1-4398-7931-3 (eBook - PDF)

This book contains information obtained from authentic and highly regarded sources. Reasonable efforts have been made to publish reliable data and information, but the author and publisher cannot assume responsibility for the validity of all materials or the consequences of their use. The authors and publishers have attempted to trace the copyright holders of all material repro-duced in this publication and apologize to copyright holders if permission to publish in this form has not been obtained. If any copyright material has not been acknowledged please write and let us know so we may rectify in any future reprint.

Except as permitted under U.S. Copyright Law, no part of this book may be reprinted, reproduced, transmitted, or utilized in any form by any electronic, mechanical, or other means, now known or hereafter invented, including photocopying, microfilming, and recording, or in any information storage or retrieval system, without written permission from the publishers.

For permission to photocopy or use material electronically from this work, please access www.copyright.com (http://www.copy-right.com/) or contact the Copyright Clearance Center, Inc. (CCC), 222 Rosewood Drive, Danvers, MA 01923, 978-750-8400. CCC is a not-for-profit organization that provides licenses and registration for a variety of users. For organizations that have been granted a photocopy license by the CCC, a separate system of payment has been arranged.

Trademark Notice: Product or corporate names may be trademarks or registered trademarks, and are used only for identifica-tion and explanation without intent to infringe.

Visit the Taylor & Francis Web site athttp://www.taylorandfrancis.com

and the CRC Press Web site athttp://www.crcpress.com

Page 6: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Ta ble of Con tents

Pref ace xix

Chap ter 1 – Real-Time Com put ing 11.0 De fin ing the Em bed ded Sys tem 11.1 Em bed ded Sys tems His tory 21.2 Hard ware Com plex ity 2

1.2.1 Pro ces sor 31.2.2 Microcontrollers 31.2.3 Hard ware and Soft ware 3

1.3 Ex e cu tion in Real-Time 41.3.1 Hard and Soft Real-Time Sys tems 5

Chap ter 2 – Cir cuit Fun da men tals 72.1 Elec tri cal Cir cuit 72.2 Cir cuit Con cepts and Com po nents 82.3 Dig i tal Elec tron ics 92.4 Di ode 10

2.4.1 Light-Emit ting Di ode (LED) 12

2.5 Tran sis tors 132.5.1 Bi po lar Tran sis tor 132.5.2 MOS Tran sis tor 15

Chap ter 3 – Logic Gates and Cir cuit Com po nents 173.1 Logic Gates 173.2 Power Sup plies 183.3 Clocked Logic and Flip-Flops 19

3.3.1 RS Flip-Flop 193.3.2 Clocked Cir cuits 203.3.3 D Flip-Flop 213.3.4 Edge-Trig gered D Flip-Flop 233.3.5 Pre set and Clear Sig nals 233.3.6 D Flip-Flop Wave form Ac tion 243.3.7 Flip-Flop Ap pli ca tions 25

3.4 Dig i tal Clocks 263.4.1 Clock Wave forms 26

v

Page 7: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

3.4.2 TTL Clock 273.4.3 555 Timer 283.4.4 Microcontroller Clocks 29

3.5 Coun ters and Fre quency Di vid ers 293.5.1 Fre quency Di vid ers 303.5.2 JK Flip-Flop Coun ter 303.5.3 Rip ple Coun ters 313.5.4 De cod ing Gates 323.5.5 Syn chro nous Coun ters 333.5.6 Coun ter ICs 353.5.7 Shift Reg is ters 36

3.6 Multiplexers and Demultiplexers 373.6.1 Multiplexers 383.6.2. Demultiplexers 393.6.3 Multi plexer and Demultiplexer ICs 40

Chap ter 4 – In put and Out put De vices 414.1 Ob tain ing In put 414.2 Switches 41

4.2.1 Switch Con tact Bounce 434.2.2 Keypads 44

4.3 Out put De vices 454.3.1 Seven-Seg ment LED 454.3.2 Liq uid Crys tal Dis plays 474.3.3 LCD Tech nol o gies 48

Chap ter 5 – From Cir cuit Sche mat ics to PCB 515.1 Cir cuit Di a gram 51

5.1.1 Sym bols 525.1.2 Tools for Elec tronic Cir cuit De sign 53

5.2 Cir cuit Board De sign 535.2.1 Board De sign Stan dards 545.2.2 Gerber File For mat 54

5.3 De vel op ing the Cir cuit Pro to type 555.3.1 Bread board 56

Lim i ta tions of Bread boards 58 Breadboarding Tools and Tech niques 58

5.3.2 Wire-Wrap ping 595.3.3 Perfboards 60

5.4 Printed Cir cuit Boards 605.4.1 PCB Lay ers 615.4.2 PCB Con nec tors 62

5.5 Mak ing Your Own PCB 625.5.1 Draw ing the CPB Cir cuit 635.5.2 Print ing the PCB 655.5.3 Trans fer ring the PCB Im age 655.5.4 Etch ing the Board 655.5.5 Fin ish ing the Board 665.5.6 Back side Im age 66

vi Em bed ded Sys tems: Cir cuits and Pro gram ming

Page 8: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

5.6 Sur face-Mount Com po nents 665.6.1 SMT Adapt ers 675.6.2 Sol der ing SMT Com po nents 68

5.7 Trou ble shoot ing the Cir cuit Board 685.7.1 Cir cuit Test ing Tools 69

Chap ter 6 – In tro duc ing the Microcontroller 716.1 A Com puter on a Chip 716.2 PICMicro Microcontroller 72

6.2.1 Pro gram ming the PIC 73De vel op ment Boards 74

6.2.2 Prototyping a PIC Cir cuit 75

6.3 PIC Ar chi tec ture 756.3.1 Base line PIC Fam ily 75

PIC10 De vices 75PIC12 De vices 76PIC14 De vices 78

6.3.2 Mid-Range PIC Fam ily 79PIC16 De vices 79

6.3.3 High-Per for mance PIC Fam ily 79PIC18 De vices 80

Chap ter 7 – Ar chi tec ture and In struc tion Set 837.1 Mid-Range PIC Ar chi tec ture 83

7.1.1 Har vard Ar chi tec ture 837.1.2 CISC ver sus RISC 847.1.3 Sin gle-Word In struc tions 857.1.4 In struc tion For mat 867.1.5 Mid-Range De vice Ver sions 877.1.6 Arith me tic-Logic Unit 87

7.2 Data Mem ory Or ga ni za tion 877.2.1 w Reg is ter 877.2.2 Data Reg is ters 88

Mem ory Banks 88SFRs 88GPRs 91

7.2.3 In di rect Ad dress ing 93

7.3 Mid-Range I/O and Pe riph er als 937.3.1 Ports 947.3.2 Tim ers 957.3.3 Cap ture and Com pare Mod ule 957.3.4 Mas ter Syn chro nous Se rial Port 967.3.5 USART Mod ule 967.3.6 A/D Mod ule 96

7.4 Mid-Range PIC Core Fea tures 977.4.1 Os cil la tor 977.4.2 Sys tem Re set 987.4.3 In ter rupts 100

7.5 Mid-Range In struc tion Set 101

Ta ble of Con tents vii

Page 9: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

1027.5.1 STATUS and OPTION Reg is ters 102

7.6 EEPROM Data Stor age 1047.6.1 EEPROM in Mid-Range PICs 105

Chap ter 8 – Em bed ded Sys tems Pro gram ming 1078.1 As sem bly ver sus High-Level Lan guages 107

8.1.2 Em bed ded Sys tems 107

8.2 In te grated De vel op ment En vi ron ment 1088.2.1 In stall ing MPLAB 1098.2.2 MPLAB Pro ject 1118.2.3 Pro ject Build Op tions 1128.2.4 Build ing the Pro ject 1148.2.5 Quickbuild Op tion 114

8.3 Sim u la tors and Debuggers 1158.3.1 MPLAB SIM 1158.3.2 MPLAB Hard ware Debuggers 1178.3.3 Im pro vised Debugger 119

8.4 Pro gram mers 1198.5 En gi neer ing PIC Soft ware 120

8.5.1 Us ing Pro gram Com ments 120Pro gram Header 121Com mented Ban ners 122Com mented Bitmaps 123

8.5.2 De fin ing Data El e ments 123cblock Di rec tive 124

8.5.3 Bank ing Tech niques 124banksel Di rec tive 125Bank Se lec tion Mac ros 125Dep re cated Bank ing In struc tions 126

8.5.4 Pro ces sor and Con fig u ra tion Con trols 126Con fig u ra tion Bits 127

8.5.5 Nam ing Con ven tions 1288.5.6 Errorlevel Di rec tive 131

8.6 Pseudo In struc tions 131

Chap ter 9 – I/O Cir cuits and Pro grams 1339.1 Sim ple In put and Out put 133

9.1.1 16F84A Pro gram ming Tem plate 133

9.2 Tem plate Cir cuits 1349.2.1 MCLR and Os cil la tor Tem plate 1359.2.2 Power Sup plies 135

Volt age Reg u la tor 136

9.3 Sim ple Cir cuits and Pro grams 1369.3.1 Sin gle LED Cir cuit 137

LED Flasher Pro gram 1399.3.2 LED/Pushbutton Cir cuit 1419.3.3 Mul ti ple LED Cir cuit 143

9.4 Seven-Seg ment LED 146

viii Em bed ded Sys tems: Cir cuits and Pro gram ming

Page 10: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

9.5 I/O Demo Board 1479.5.1 TestDemo1 Pro gram 148

9.6 Com par i sons in PIC Pro gram ming 1519.6.1 PIC Carry Flag 152

Chap ter 10 – PIC In ter rupt Sys tem 15310.1 Interrupts 153

10.1.1 16F84 In ter rupts 15310.1.2 In ter rupt Con trol Reg is ter 15310.1.3 OPTION Reg is ter 154

10.2 In ter rupt Sources 15510.2.1 Port B Ex ter nal In ter rupt 15610.2.2 Timer0 In ter rupt 15610.2.3 Port B Line Change In ter rupt 157

Mul ti ple Ex ter nal In ter rupts 15910.2.4 EEPROM Data Write In ter rupt 159

10.3 De vel op ing the In ter rupt Han dler 15910.3.1 Con text Sav ing Op er a tions 160

Sav ing W and STATUS Reg is ters 160

10.4 In ter rupt Pro gram ming 16110.4.1 Pro gram ming the Ex ter nal In ter rupt 161

RB0 In ter rupt Ini tial iza tion 162RB0 ISR 163

10.4.2 Wake-Up from SLEEP Us ing the RB0 In ter rupt 164SleepDemo Pro gram 165

10.4.3 Port B Bits 4-7 Sta tus Change In ter rupt 166RB4-7 In ter rupt Ini tial iza tion 166RB4-7 Change ISR 168

10.5 Sam ple Pro grams 17010.6 Dem on stra tion Pro grams 171

10.6.1 RB0Int Pro gram 17110.6.2 SleepDemo Pro gram 17510.6.3 RB4to7Int Pro gram 177

Chap ter 11 – Tim ers and Coun ters 18311.1 Con trol ling the Time Lapse 183

11.1.1 16F84 Timer0 Mod ule 183 11.1.2 Timer0 Op er a tion 184

Timer0 In ter rupt 185 Timer0 Prescaler 185

11.2 De lays Us ing Timer0 18611.2.1 Long De lay Loops 187

How Ac cu rate Is the De lay? 188

11.3 Timer0 as a Coun ter 18811.4 Timer0 Pro gram ming 189

11.4.1 Pro gram ming a Coun ter 190 Timer/Coun ter Test Cir cuit 190 TimerCounter Pro gram 191 Code De tails 191

Ta ble of Con tents ix

Page 11: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

11.4.2 Timer0 as a De lay Timer 192De lay Timer Cir cuit 192

11.4.3 DelayTimer Pro gram 193Code De tails 193

11.4.4 Vari able Time Lapse 19411.4.5 Vari able Lapse Timer Pro gram 195

Code De tails 19511.4.6 In ter rupt-Driven Timer 19811.4.7 TimerInt Pro gram 198

Code De tails 198

11.5 Watch dog Timer 20111.5.1 Watch dog Timer Pro gram ming 202

11.6 Dem on stra tion Pro grams 20211.6.1 Tmr0Counter pro gram 20211.6.2 Timer0 Pro gram 20511.6.3 LapseTimer Pro gram 20711.6.4 LapseTmrInt Pro gram 211

Chap ter 12 – LCD Hard ware and Pro gram ming 21712.1 Liq uid Crys tal Dis play 217

12.1.1 LCD Fea tures and Ar chi tec ture 21712.1.2 LCD Func tions and Com po nents 218

In ter nal Reg is ters 218Busy Flag 218Ad dress Coun ter 218Dis play Data RAM (DDRAM) 218Char ac ter Gen er a tor ROM (CGROM) 218Char ac ter Gen er a tor RAM (CGRAM) 219Tim ing Gen er a tion Cir cuit 219Liq uid Crys tal Dis play Driver Cir cuit 220Cur sor/Blink Con trol Cir cuit 220

12.1.3 Con nec tiv ity and Pin-Out 220

12.2 In ter fac ing with the HD44780 22112.2.1 Busy Flag or Timed De lay Op tions 22212.2.2 Con trast Con trol 22312.2.3 Dis play Backlight 22312.2.4 Dis play Mem ory Map ping 223

12.3 HD44780 In struc tion Set 22512.3.1 In struc tion Set Over view 225

Clear ing the Dis play 225Re turn Home 226En try Mode Set 226Dis play and Cur sor ON/OFF 226Cur sor/Dis play Shift 226Func tion Set 227Set CGRAM Ad dress 227Set DDRAM Ad dress 227Read Busy Flag and Ad dress Reg is ter 227Write Data 227Read Data 228

12.3.2 A 16F84 8-Bit Data Mode Cir cuit 228

x Em bed ded Sys tems: Cir cuits and Pro gram ming

Page 12: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

12.4 LCD Pro gram ming 22912.4.1 De fin ing Con stants and Vari ables 229

Us ing MPLAB Data Di rec tives 23112.4.2 LCD Ini tial iza tion 232

Func tion Set Com mand 232Dis play Off 233Dis play and Cur sor On 233Set En try Mode 234Cur sor and Dis play Shift 234Clear Dis play 235

12.4.3 Aux il iary Op er a tions 235Time De lay Rou tine 235Puls ing the E Line 237Read ing the Busy Flag 237Bit Merg ing Op er a tions 238

12.4.4 Text Data Stor age and Dis play 240Gen er at ing and Stor ing a Text String 241Dis play ing the Text String 243

12.4.5 Data Com pres sion Tech niques 2444-Bit Data Trans fer Mode 244Mas ter/Slave Sys tems 246

12.5 Sam ple Pro grams 248

Chap ter 13 – An a log-to-Dig i tal and Real-Time Clocks 25113.1 Clocks and the Dig i tal Rev o lu tion 25113.2 A/D Con vert ers 252

13.2.1 Con verter Res o lu tion 25213.2.2 ADC Im ple men ta tion 253

13.3 A/D In te grated Cir cuits 25413.3.1 ADC0331 Sam ple Cir cuit and Pro gram 255

13.4 PIC Onboard A/D Hard ware 25713.4.1 A/D Mod ule on the 16F87x 257

ADCON0 Reg is ter 258ADCON1 Reg is ter 261SLEEP Mode Op er a tion 262

13.4.2 A/D Mod ule Sam ple Cir cuit and Pro gram 262

13.5 Real-Time Clocks 26613.5.1 NJU6355 Real-Time Clock 26613.5.2 RTC Dem on stra tion Cir cuit and Pro gram 268

BCD Con ver sion Pro ce dures 273

13.6 Dem on stra tion Pro grams 27613.6.1 ADF84 Pro gram 27613.6.2 A2DinLCD Pro gram 28813.6.3 RTC2LCD Pro gram 303

Chap ter 14 – Data EEPROM 32114.1 EEPROM Pro gram ming 321

14.1.1 Data EEPROM 321

14.2 EEPROM Pro gram ming 322

Ta ble of Con tents xi

Page 13: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

14.2.1 Read ing EEPROM Data 32314.2.2 EEPROM Data Mem ory Write 323

14.3 EEPROM Pro gram ming Ap pli ca tion 32414.3.1 EECounter Pro gram 324

Code De tails 324

14.4 Dem on stra tion Pro grams 32914.4.1 EECounter Pro gram 32914.4.2 Ser2EEP Pro gram 34114.4.3 I2CEEP Pro gram 358

Chap ter 15 – Step per Mo tors 37915.1 Description and Op er a tion 379

15.1.1 Step per Mo tor Types 381Vari able Re luc tance 381Per ma nent Mag net 381Hy brid 381

15.1.2 Uni po lar Step per Mo tors 38215.1.3 De ter min ing Uni po lar and Bi po lar Wir ing 383

Four-Wire Mo tor 383Six-Wire Uni po lar Mo tor 383Five-Wire Uni po lar 383

15.1.4 Bi po lar Step per Mo tors 384

15.2 Step per Mo tor Con trols 38415.2.1 Step ping Modes 385

Wave Drive Mode 385Full Step Mode 386Half Step Mode 387Microstepping 387

Chap ter 16 – Step per Mo tor Cir cuit Com po nents 38916.1 Cir cuit El e ments 389

16.1.1 In put, Out put, and Feed back 390

16.2 Trans la tor 39016.2.1 PIC Microcontroller as a Trans la tor 390

16.3 Trans la tor/Driv ers 39116.3.1 UCN 5804 39116.3.2 L297 39216.3.3 EDE1204 39416.3.4 SLA7060 and SLA7024 394

16.4 Power Driver 39516.4.1 Uni po lar Driv ers 395

PIC Microcontroller as a Driver 395ULN2803A 395TIP 120 396

16.4.2 Bi po lar Driv ers 39716.4.3 Tran sis tor ized H Bridge 397

Snub ber Di odes 39816.4.4 H Bridge ICs 399

L293D 399L298 400

xii Em bed ded Sys tems: Cir cuits and Pro gram ming

Page 14: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

16.5 Mod ules in Cir cuit Sche mat ics 40016.5.1 Ex am ple 16F84 Trans la tor Mod ules 401

Chap ter 17 – Uni po lar Mo tor Cir cuits and Pro grams 40317.1 Step per Mo tor Con trol Cir cuits 403

17.1.1 Step per Mo tor Cir cuit Sche matic Con ven tions 403

17.2 Mo tor Speed Con trol 40517.2.1 Speed Con trol from Dig i tal In put 40517.2.2 An a log In put Speed Con trol 406

17.3 Uni po lar Mo tor Con trol Cir cuits 40717.3.1 Match ing Cir cuit to Mo tor Power 40717.3.2 16F84 Uni po lar Cir cuit 408

Sam ple Pro gram SMU_PIC16F84.asm 40817.3.3 5804 Uni po lar Cir cuit 411

Sam ple Pro gram SMU_5804.asm 413Gen er at ing the Mo tor Pulses 415In ter rupt-Driven Mo tor Puls ing 416

17.3.4 16F686 PIC Cir cuit 41917.3.5 16F686 Pro gram ming 419

Sam ple Pro gram SMU_PIC16F684.asm 421Sam ple Pro gram SMU_PIC16F684_INT.asm 424

17.3.6 Step per Mo tor Po si tion Con trol 424Sam ple Pro gram SMU_POSITION.asm 425

17.4 Dem on stra tion Pro grams 42717.4.1 SMB_297_293D.asm 42717.4.2 SMU_PIC16F84.asm Pro gram 43117.4.3 SMU_5804.asm 43617.4.4 SMU_5804_INT.asm 44117.4.5 SMU_PIC16F684.asm 44817.4.6 SMU_PIC16F684_INT.asm 45317.4.7 SMU_POSITION.asm 460

Chap ter 18 – Con stant-Volt age Bi po lar Mo tor Con trols 46718.1 Uni po lar ver sus Bi po lar 467

18.1.1 Bi po lar Drive Cir cuits 467

18.2 Sim ple, L293 Bi po lar Cir cuit 46818.2.1 L297- and L293-Based Cir cuit 47118.2.2 Min i mal L297- and L298-based Cir cuit 471

18.3 Dem on stra tion Pro grams 47118.3.1 SMB_L293D.asm 47318.3.2 SMB_297_293D.asm 47818.3.3 SMB_297_298.asm 482

Chap ter 19 – Ad vanced Mo tor Con trols 48719.1 Chop pers and Microstepping 48719.2 Chop per Cir cuit Fun da men tals 48719.3 L297/298 Chop per Cir cuit 490

19.3.1 Set ting the Ref er ence Volt age 491

Ta ble of Con tents xiii

Page 15: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

19.4 A Chop per-Based Demo Board 49219.4.1 Mo tor Cir cuit Power Re quire ments 49219.4.2 Chop per Demo Pro gram 494

19.5 Microstepping 49419.5.1 Microstepping Fun da men tals 497

Microstepping The ory 497Pulse Width Mod u la tion (PWM) 499

19.6 Pro gram ming PWM 50019.6.1 CCP Mod ule 50019.6.2 PWM Cir cuit and Soft ware 50219.6.3 Microstepping by PWM 50519.6.4 Microstepping Sam ple Pro gram 506

19.7 Microstepping ICs 50819.7.1 Al le gro 3955 IC 50819.7.2 3955-Based Cir cuit 51019.7.3 3955 Mo tor Driver Pro gram 512

19.8 Dem on stra tion Pro grams 51419.8.1 PWM_DEMO_873.asm 51419.8.2 PIC_Chop per.asm 51819.8.3 PWM_Micstep.asm 52219.8.4 PIC873_3955.asm 530

Chap ter 20 – Com mu ni ca tions 54320.1 PIC Com mu ni ca tions Over view 54320.2 Se rial Data Trans mis sion 544

20.2.1 Asyn chron ous Se rial Trans mis sion 54420.2.2 Syn chro nous Se rial Trans mis sion 54620.2.3 PIC Se rial Com mu ni ca tions 54620.2.4 RS-232-C Stan dard 547

Es sen tial Con cepts 548Se rial Bit Stream 549Par ity Test ing 549Con nec tors and Wir ing 550Null Mo dem 550Null Mo dem Ca ble 551

20.2.5 EIA-485 Stan dard 553EIA-485 in PIC-based Sys tems 554

20.3 Par al lel Data Trans mis sion 55420.3.1 PIC Par al lel Slave Port (PSP) 555

20.4 PIC “Free-Style” Se rial Pro gram ming 55520.4.1 PIC-to-PIC Se rial Com mu ni ca tions 556

PIC-to-PIC Se rial Com mu ni ca tions Cir cuits 556PIC-to-PIC Se rial Com mu ni ca tions Pro grams 558

20.4.2 Pro gram Us ing Shift Reg is ter ICs 56474HC165 Par al lel-to-Se rial Shift Reg is ter 56574HC164 Se rial-to-Par al lel Shift Reg is ter 568

20.5 PIC Pro to col-Based Se rial Pro gram ming 57020.5.1 RS-232-C Com mu ni ca tions on the 16F84 570

RS-232-C Trans ceiver IC 571PIC-to-PC Com mu ni ca tions 572

xiv Em bed ded Sys tems: Cir cuits and Pro gram ming

Page 16: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

RS-232-C TTY Board 57216F84A UART Em u la tion 573LCD Scroll ing Rou tine 575

20.5.2 RS-232-C Com mu ni ca tions on the 16F87x 57916F87x USART Mod ule 580USART Baud Rate Gen er a tor 58016F87x USART Asyn chron ous Trans mit ter 58316F87x USART Asyn chron ous Re ceiver 584PIC-to-PC RS-232-C Com mu ni ca tions Cir cuit 58516F877 PIC Ini tial iza tion Code 585USART Re ceive and Trans mit Rou tines 589USART Re ceive In ter rupt 590

20.6 Dem on stra tion Pro grams 59320.6.1 SerialSnd Pro gram 59320.6.2 SerialRcv Pro gram 59920.6.3 Serial6465 Pro gram 60420.6.4 TTYUsart Pro gram 60920.6.5 SerComLCD Pro gram 62420.6.6 SerIntLCD Pro gram 642

Ap pen dix A – Re sis tor Color Codes 663

Ap pen dix B – Es sen tial Elec tron ics 665B.1 Atom 665B.2 Iso topes and Ions 666B.3 Static Elec tric ity 667B.4 Elec tri cal Charge 668

B.4.1 Volt age 668B.4.2 Cur rent 668B.4.3 Power 669B.4.4 Ohm’s Law 669

B.5 Elec tri cal Cir cuits 670B.5.1 Types of Cir cuits 670

B.6 Cir cuit El e ments 672B.6.1 Re sis tors 673B.6.2 Re vis it ing Ohm’s Law 673B.6.3 Re sis tors in Se ries and Par al lel 674B.6.4 Ca pac i tors 676B.6.5 Ca pac i tors in Se ries and in Par al lel 677B.6.6 Inductors 678B.6.7 Trans form ers 679

B.7 Semi con duc tors 679B.7.1 In te grated Cir cuits 680B.7.2 Semi con duc tor Elec tron ics 680B.7.3 P-Type and N-Type Sil i con 681B.7.4 Di ode 681

Ta ble of Con tents xv

Page 17: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Ap pen dix C – Nu meric Data 683C.1 Num bers in Com put ing 683

C.1.1 Count ing 683C.1.2 Tally Sys tem 683C.1.3 Ro man Nu mer als 684

C.2 Or i gins of the Dec i mal Sys tem 684C.2.1 Num ber Sys tems for Dig i tal-Elec tron ics 686C.2.2 Po si tional Char ac ter is tics 686C.2.3 Ra dix or Base of a Num ber Sys tem 687

C.3 Types of Num bers 687C.3.1 Whole Num bers 688C.3.2 Signed Num bers 688C.3.3 Ra tio nal, Ir ra tio nal, and Imag i nary Num bers 688

C.4 Ra dix Rep re sen ta tions 689C.4.1 Dec i mal ver sus Bi nary Num bers 689C.4.2 Hex a dec i mal and Oc tal 690

C.5 Num ber Sys tem Con ver sions 691C.5.1 Bi nary-to-ASCII-Dec i mal 692C.5.2 Bi nary-to-Hex a dec i mal Con ver sion 693C.5.3 Dec i mal-to-Bi nary Con ver sion 693

Ap pen dix D – Char ac ter Data 697D.1 Char ac ter Rep re sen ta tions 697

D.1.1 Elec tronic-Dig i tal Ma chines 697

D.2 Char ac ter Rep re sen ta tions 697D.2.1 ASCII 698D.2.2 EBCDIC and IBM 700D.2.3 Unicode 700

D.3 Stor age and En cod ing of In te gers 701D.3.1 Signed and Un signed Rep re sen ta tions 701D.3.2 Word Size 702D.3.3 Byte Or der ing 703D.4.4 Sign-Mag ni tude Rep re sen ta tion 704D.3.5 Ra dix Com ple ment Rep re sen ta tion 705

D.4 En cod ing of Frac tional Num bers 708D.4.1 Fixed-Point Rep re sen ta tions 709D.4.2 Float ing-Point Rep re sen ta tions 710D.4.3 Stan dard ized Float ing-Point Rep re sen ta tions 711D.4.4 IEEE 754 Sin gle For mat 712D.4.5 En cod ing and De cod ing Float ing-Point Num bers 714

D.5 Bi nary-Coded Dec i mals (BCD) 715D.5.1 Float ing-Point BCD 716

Ap pen dix E – Dig i tal Arith me tic and Con ver sions 719E.1 Microcontroller Arith me tic 719E.2 Un signed and Two’s Com ple ment Arith me tic 719

E.2.1 Op er a tions on Dec i mal Num bers 721

E.3 Bit Ma nip u la tions and Aux il iary Op er a tions 723

xvi Em bed ded Sys tems: Cir cuits and Pro gram ming

Page 18: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

E.3.1 Bit Shift and Ro tate 723E.3.2 Com par i son Op er a tions 724E.3.3 Other Sup port Op er a tions 724

E.4 Un signed Bi nary Arith me tic 725E.4.1 Multi-Byte Un signed Ad di tion 725E.4.2 Un signed Mul ti pli ca tion 726E.4.3 Un signed Di vi sion 728

E.5 Signed Bi nary Arith me tic 729E.5.1 Over flow De tec tion in Signed Arith me tic 730E.5.2 Sign Ex ten sion Op er a tions 732E.5.3 Multi-Byte Signed Op er a tions 732

E.6 Data For mat Con ver sions 733E.6.1 BCD Dig its to ASCII Dec i mal 733E.6.2 Un signed Bi nary to ASCII Dec i mal Dig its 734E.6.3 ASCII Dec i mal String to Un signed Bi nary 734E.6.4 Un signed Bi nary to ASCII Hex a dec i mal Dig its 736E.6.5 Signed Nu mer i cal Con ver sions 736

Ap pen dix F – Mid-Range In struc tion Set 739

Ap pen dix G – Printed Cir cuit Boards 777G.1 In tro duc tion 777

G.2 Printed Cir cuit Boards (PCBs) 777

G.3 Parts Lists 778G.4 Build ing Your Own Cir cuit Boards 779

G.4.1 Tools and Ma te ri als 779G.4.2 Sin gle-Sided Demo Board 780G.4.3 PCB Im ages for Demo Board 780

Draw ing the Cir cuit Di a gram 782 Print ing the PCB Di a gram 783 Se lect ing the Pa per 783 Trans fer ring the PCB Im age 784 Etch ing the Board 784 Fin ish ing the Board 784 Com po nent-Side Im age 784

G.5 Ca ve ats 785

Ap pen dix H – Ad di tional Code 787

In dex 863

Ta ble of Con tents xvii

Page 19: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

This page intentionally left blankThis page intentionally left blank

Page 20: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Pref ace

Em bed ded sys tems are ev ery where in our mod ern world. You can find them in au to -mo biles, toys, kitchen ap pli ances, com put ers, air planes, TVs and dig i tal re cord ing de -vices, cell phones, gam ing ma chines, nu clear power plants, space tele scopes; in ev eryelec tronic de vice that fur nishes an in tel li gent, in de pend ent, or con trol la ble func tion -al ity. By def i ni tion an em bed ded sys tem is a com puter de signed to per form one or afew spe cialized func tions, most of ten in real-time. The em bed ded sys tem is usu ally apart of a hard ware or me chan i cal de vice that in cludes other phys i cal com po nents. For ex am ple, a house hold dish washer con tains a cab i net with trays, one or more mo tors,spray ers and jets, de pos its for hold ing soap and other chem i cals, and an em bed dedcom puter sys tem that de ter mines cy cles, modes, and tim ing of the de vice. It is this em -bed ded con trol ler that ac tu ally op er ates the ma chine, and what our book is about.

The au thors con ceived Em bed ded Sys tems: Cir cuits and Pro gram ming as a ref -er ence and a re source kit for en gi neers, sci en tists, and elec tronic en thu si asts whoneed to de velop sys tems and boards that con tain dig i tal com po nents and con trolssome times com bined with an a log de vices. Our book is also in tended as a tu to rial on microcontroller pro gram ming and on the ba sics of em bed ded de sign. The fo cus ison the needs of work ing pro fes sion als in the fields of elec tri cal, elec tronic, com -puter, and soft ware en gi neer ing.

Many en gi neered prod ucts re quire the de vel op ment of one or more em bed dedsys tems. At the com mer cial fab ri ca tion stage the em bed ded sys tem or sys tems arere fined and op ti mized by spe cial ists in or der to fa cil i tate pro duc tion and min i mizecost. How ever, dur ing the de vel op ment and prototyping phases, the de vel oper of ten needs to cre ate an em bed ded sys tem that dem on strates the op er a tion of the de vice,proves its vi a bil ity, or ex er cises its func tion al ity. This ini tial prod uct is of ten calleda pro to type. The avail abil ity of off-the-shelf com po nents, the abun dance of de signand prototyping tools, and the ease with which dig i tal con trol lers can be pro -grammed make it pos si ble for the non-spe cial ist to de velop these boards and con -trol lers. In this book we fo cus on the fol low ing de vel op ment tools and re sources:

• The use of stan dard or off-the-shelf com po nents such as in put/out put de vices, in te -grated cir cuits, mo tors, and pro gram ma ble microcontrollers

• The de vel op ment of cir cuit pro to types and their im ple men ta tion us ing bread -boards, fol lowed by the in-house fab ri ca tion of test-time PCBs, and fi nal ized by theman u fac tured board

xix

Page 21: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

• The avail abil ity and use of de vel op ment tools that fa cil i tate the de sign andprototyping of em bed ded sys tems, such as elec tronic de sign pro grams and soft -ware util i ties for cre at ing printed cir cuit boards

• Sam ple cir cuits that can be used as part of the tar geted em bed ded sys tem

• The se lec tion and pro gram ming of microcontrollers suit able for use in the cir cuit athand

We have aimed at a book that is func tional and hands-on. The re sources fur -nished to the reader in clude sam ple cir cuits with their cor re spond ing pro grams.The cir cuits are de picted and la beled clearly in a way that is easy to fol low and re -use. For some critical cir cuits we pro vide tested PCB files. The sam ple pro gramsare matched to the in di vid ual cir cuits but gen eral pro gram ming tech niques are alsodis cussed in the text. There are ap pen di ces with hands-on in for ma tion and thebook’s on line soft ware pack age in cludes tools, resources, and code list ings. Thesema te ri als are avail able at

http://www.crcpress.com/prod uct/isbn/9781439879047.

Julio Sanchez

Maria P. Canton

xx Pref ace

Page 22: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Chap ter 1

Real-Time Com put ing

1.0 De fin ing the Em bed ded Sys tem

An em bed ded sys tem can be de fined as a com puter sys tem that per forms one or moreded i cated or spe cial ized func tions usu ally with Real-Time con straints. It is the dig i talcon trol ler that is em bed ded as part of sys tem, which also in cludes other hard wareand me chan i cal el e ments. A mod ern dish washer con tains an em bed ded con trol sys -tem. On the other hand, a gen eral-pur pose com puter such as a PC is de signed to meet a va ri ety of user needs. The con trol sys tem in the dish washer does one task: washdishes, while the PC on your desk top can be used in word pro cess ing, brows ing theWeb, bal anc ing your check book, and many other ap pli ca tions.

Em bed ded sys tems are con trolled by one or more dig i tal pro cess ing de vices, typ -i cally a microcontroller or dig i tal sig nal pro ces sor (DSP). The key fea ture of theem bed ded sys tem is that it is ded i cated to a spe cific task. Some times a spe cial izedor ded i cated com puter sys tem, such as the one han dling a dam, or the traf fic in ama jor city, or the op er a tion of a nu clear power plant, is con sid ered an em bed dedsys tem. Al though it is a mat ter of se man tics, we pre fer to ex clude spe cial ized orded i cated com puter sys tems from the em bed ded cat e gory. We also ex clude de vicesbased on nanotechnology be cause in this case it is the mo lec u lar size of the com po -nent that de fines the sys tem. But even ex clud ing spe cial ized com put ing de vices and mo lec u lar-scale com po nents, em bed ded sys tems can range widely in size and com -plex ity; from handheld or por ta ble de vices such as a dig i tal watch to com plex con -trol lers such as the one op er at ing a space ex plo ra tion robot.

A good ex am ple of an em bed ded sys tem, as con sid ered in this con text, is a pro -gram ma ble ther mo stat con trol ling the op er a tion of house hold air con di tion ing andheater sys tems. In real-time the ther mo stat re ceives in for ma tion from a sen sor thatreads the house tem per a ture at pre de ter mined in ter vals. The con trol ler logic thencom pares this tem per a ture value with the one pro grammed for the cur renttime-of-day and turns on or off the AC or the heater component as necessary.

1

Page 23: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

1.1 Em bed ded Sys tems His tory

One of the first rec og niz ably mod ern em bed ded sys tems was the Apollo Guid anceCom puter, de vel oped at the MIT In stru men ta tion Lab o ra tory in 1961. It was theApollo Guid ance Com puter that first ex plored the vi a bil ity of mono lithic in te gratedcir cuits which have be cause be come com mon place. An other early em bed ded sys temwas the Autonetics D-17 guid ance com puter for the Min ute man mis sile, which wasbased on tran sis tors and con tained a hard disk drive as its main mem ory. In 1996, theD-17 con trol ler was re placed with a new com puter that pi o neered the de vel op ment ofin te grated cir cuits. One re sult from these pro jects was the re duc tion in cost of thequad nand gate ICs from $1,000 each to less than $3. Com mer cial ap pli ca tions soonfol lowed.

The in ven tion and de vel op ment of microcontrollers re lates closely to the evo lu -tion of em bed ded sys tems. The in te gra tion of pro cess ing func tions, mem ory, andpro gram ma ble in put and out put op er a tions in a sin gle cir cuit has sim pli fied the de -sign and de vel op ment of em bed ded sys tems, to the point that to day it is dif fi cult tofind an em bed ded sys tem that does not in clude at least one microcontroller. Fur -ther more, the low cost of microcontrollers com pared to full-fledged com puter ICshas fur ther in creased the type of ap pli ca tions for which em bed ded sys tems are com -mer cially vi a ble. All em bed ded sys tems dis cussed in this book con tain amicrocontroller al though some sys tems also in clude other dig i tal com po nents thatpro vide spe cial ized func tion al ity. For ex am ple, an em bed ded sys tem that deals inReal-Time units (such as years, months, days-of-the-week, hours, min utes, and sec -onds) will typ i cally in clude a Real-Time clock IC such as the NJU6355, which willfurnish this functionality.

1.2 Hard ware Com plex ity

To the de vel oper or en gi neer an em bed ded sys tem con sists of hard ware and soft ware.The hard ware typ i cally in cludes a cir cuit board that houses and in ter faces the com po -nents, one or more in te grated cir cuits that pro vide the pro cess ing ca pa bil i ties (usu -ally a microcontroller), and one or more in put and out put de vices that com mu ni catewith the out side world. But not all em bed ded sys tems are stand alone de vices. For ex -am ple, an em bed ded sys tem that turns on and off a step per mo tor and con trols its ro -ta tional speed and di rec tion may be de signed to com mu ni cate with an other sys temthat pro vides the logic and com mand sig nals. In this case the em bed ded mo tor con trolsys tem is ac tu ally a com po nent of a larger con trol sys tem and does not con tain a userin ter face, pro cess ing logic, or other com mand and con trol func tions.

On the other hand, some em bed ded sys tems come close to the func tion al ity of acon ven tional com puter. For ex am ple, an em bed ded sys tem may in clude a com puterscreen with a graph i cal user in ter face, sev eral but tons and con trol de vices, LEDs,net work con nec tions, or even a touch screen. In this case it is the fact that the em -bed ded sys tem is ded i cated to a par tic u lar task that dif fer en ti ates it from a com -puter. But keep in mind that there is no clear de mar ca tion line be tween aso phis ti cated em bed ded sys tem and a spe cial ized com puter. One is free to clas sifysuch bor der line sys tems in ei ther cat e gory. In this sense an ATM ma chine, with its

2 Chap ter 1

Page 24: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

com plex pro cess ing and IO ca pa bil i ties, can be con sid ered either as an embeddedsystem or as a specialized computer.

1.2.1 Pro ces sor

It is vir tu ally im pos si ble to con ceive of an em bed ded sys tem that does not pro videsome pro cess ing, al though, here again, the de mar ca tion line is not al ways clear. Forex am ple, the cir cuit that op er ates a house hold door bell of ten con sists of a sim plepushbutton con trol and a buzzer or bell. Press ing the pushbutton closes the cir cuitthat ac ti vates the sound-pro duc ing el e ment. Be cause there is no logic or pro cess ingsuch a door bell cir cuit could hardly be clas si fied as an em bed ded sys tem. How ever, ifwe add a pro ces sor that se lects a dif fer ent sound pat tern or chime ac cord ing to thetime of day, then the door bell driver could be clas si fied as an em bed ded sys tem. Here,it is the pres ence of a pro cess ing op er a tion that de fines the sys tem.

Em bed ded pro ces sors are usu ally microcontrollers al though it is con ceiv ablethat an em bed ded sys tem can be based on a mi cro pro ces sor. The prin ci pal dif fer -ence be tween the mi cro pro ces sor and the microcontroller is that the lat ter in cludes pe riph eral func tions that simplify its ap pli ca tion and re duce the cost of the IC. Ad di -tion ally, it is usu ally as sumed that a mi cro pro ces sor sys tem con tains more com plexand pow er ful logic; how ever, the ad vent of the Dig i tal Sig nal Pro ces sor (DSP) hasalso di min ished this per cep tion be cause some DSPs match or even exceed theprocessing power of microcomputers.

1.2.2 Microcontrollers

In this book we do not cover em bed ded sys tems based on mi cro pro ces sors or on DSPs be cause the com plex ity of such sys tems clearly ex ceeds our pres ent scope and in ten -tion. But even ex clud ing these high-end de vices, deal ing with the many sources, types, and com plex ity of cur rently avail able microcontrollers can be a daunt ing prop o si tion. Chap ter 5 con tains an over view of microcontrollers from Intel, Micro chip, Motorola,and Atmel of ten found in em bed ded sys tems. How ever, for space con straints andprac ti cal di dac tic con sid er ations, in this book we limit our cov er age to a few pop u larand well-sup ported microcontrollers from Micro chip, all based on its mid-range ar chi -tec ture.

1.2.3 Hard ware and Soft ware

The hard ware com po nents that can be found in an em bed ded sys tem are dif fi cult toenu mer ate. They in clude (but are not lim ited to) the fol low ing el e ments:

• Cir cuit boards

• Pro ces sors (usu ally one or more microcontrollers)

• Tran sis tors

• Logic gates

• Power sup plies

• Clocks and flip-flops

• Fre quency di vid ers, tim ers, and coun ters

Real-Time Com put ing 3

Page 25: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

• Multiplexers and demultiplexers

• Mem o ries and data stor age fa cil i ties

• Com mu ni ca tions con trol lers

• Switches and key pads

• LEDs, seven-segement LEDs, and LCDs

• Mo tors and mo tor con trol de vices

• Sen sors

• So le noids and ac tu a tors

• AC con vert ers and out put de vices

Books can be and have been writ ten on many of these el e ments. In fact, ti tles onsome of them (such as microcontrollers) fill sev eral good-sized shelves. For tu -nately, oth ers are rather sim ple de vices, and their un der stand ing and use is straight -for ward and di rect. For ex am ple, from an em bed ded sys tems de vel oper point ofview, there is not much more that can be done with an LED than to turn it on or off.

By a stretch of the imag i na tion we can con ceive of an em bed ded sys tem that op -er ates solely on the off-the-shelf logic con tained in its dig i tal de vices. How ever, amore com mon sce nario is that the pro cess ing op er a tions of an em bed ded sys temmust be cus tom ized by the de vel oper to meet a spe cific de sign func tion al ity. Thismeans that a pro gram must be de vel oped for the sys tem’s con trol ler. The ref er encein this book’s ti tle to cir cuits and pro gram ming in di cates that its con tents re late toboth the phys i cal elec tron ics and the software component of an embedded system.

1.3 Ex e cu tion in Real-Time

Real-time or re ac tive com put ing re fers to sys tems that are sub ject to a time con -straint. By def i ni tion, a real-time com put ing sys tem is one that in ter acts with the realworld or that has tim ing re quire ments re lated to this in ter ac tion. In gen eral, the re -sponse of a Real-Time sys tem must take place within a spe cific time frame. For ex am -ple, in or der to be ef fec tive, the air-bag sys tem in the steer ing wheel of a car mustde ploy within a cer tain time pe riod af ter the event that ac ti vates it. If the air bag de -ploys ear lier or later than this ideal mo ment, its ac tion would be use less or even coun -ter pro duc tive. Note that the con cept of ex e cu tion in real-time does not mean that thesys tem’s in ter ac tion must take place as fast as pos si ble.

By def i ni tion a real-time sys tem in cludes not only those that must ex e cute withina tem po ral con straint, but also any sys tem that in ter acts with the real world. In em -bed ded sys tems this in ter ac tion with the real world usu ally takes place through sen -sors and ac tu a tors. For ex am ple, the door bell sys tem pre vi ously men tionedex e cutes in Real-Time be cause it is ex pected that the buzzer or chime will soundwithin a short time af ter the pushbutton is depressed.

4 Chap ter 1

Page 26: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

1.3.1 Hard and Soft Real-Time Sys temsReal-Time sys tems are of ten clas si fied as hard and soft. Sys tems that must meet stricttim ing re quire ments are clas si fied as hard while those in which there is a more flex i -ble tol er ance of the tim ing re quire ment are soft RTSs, (Real-Time Sys tems). In thiscon text, the air-bag sys tem men tioned pre vi ously com pletely fails if its strict tim ingre quire ment is not met; there fore, it is a hard RTS. The door bell sys tem, on the otherhand, has a much larger tol er ance in its tim ing re quire ment and can be clas si fied as asoft RTS. The time li ness re quire ment is one of the main is sues in the de sign of a hardreal-time sys tem, but must also be con sid ered in soft RTSs.

De sign con sid er ations in Real-Time sys tems in clude the fol low ing top ics:

• Real-Time op er at ing sys tems

• Sched ul ing

• Real-Time com mu ni ca tions

• Anal y sis of Real-Time com po nents

• Test ing and de bug ging Real-Time sys tems

In this con text our dis cus sion of Real-Time sys tems is lim ited to spe cific cir cuitswith a spe cific Real-Time con straint. Most of the top ics listed above fall within thefield of the o ret i cal com puter science.

Real-Time Com put ing 5

Page 27: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

This page intentionally left blankThis page intentionally left blank

Page 28: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Chap ter 2

Cir cuit Fun da men tals

2.1 Elec tri cal Cir cuitAn elec tri cal net work is a col lec tion of elec tri cal el e ments that can in clude volt agesources, lines, con nec tors, re sis tors, inductors, ca pac i tors, switches, con trol lers, and a host of other stan dard and spe cial com po nents. The cir cuit is a closed-loop elec tri calnet work that pro vides a re turn path for the cur rent and that con tains at least one ac tiveelec tronic com po nent.

Elec tronic cir cuits are clas si fied as an a log, dig i tal, or mixed-sig nal, the lat ter be ing a com bi na tion of the an a log and dig i tal types. Cir cuits con tain dis crete com po nentsof ten pur chased off-the-shelf. These in clude but are not lim ited to re sis tors, ca pac i -tors, inductors, di odes, pro ces sors (such as microcontrollers), as well as in put andout put de vices such as pushbuttons, tog gle switches, light-emit ting di odes, liq uidcrys tal dis plays, ac tu a tors, and mo tors. Dur ing the de vel op ment stage, the cir cuitcom po nents are typ i cally as sem bled on bread boards, perfboards, or stripboards thatal low for eas ily mak ing changes to the cir cuit. Fig ure 2-1 is a pho to graph of a bread -board used in testing a motor driver circuit developed later in the book.

Fig ure 2-1 Bread board Cir cuit for a Mo tor Con trol ler.

7

Page 29: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Once the cir cuit has been tested and de bugged, the com po nents are sol dered on a printed cir cuit board that pro vides a fin ished prod uct. If the prod uct is to be man u -fac tured in large num bers, it is usu ally mod i fied into a pro duc tion ver sion that ischeaper to make, smaller, or both. Fig ure 2-2 shows a printed cir cuit board withcomponents.

Fig ure 2-2 As sem bled Printed Cir cuit Board.

2.2 Cir cuit Con cepts and Com po nentsAll elec tri cal cir cuits have at least some of the fol low ing el e ments.

• A power source to pro duce an elec tri cal potential; it can be a bat tery, an al ter na tor,a gen er a tor, or a con nec tion to some ex ter nal source.

• Con duc tors. These in clude wires and cir cuit boards that pro vide a path for thecurrent.

• Loads, in the form of de vices that use elec tri cal en ergy to pro vide some form ofwork. These in clude lamps, mo tors, ac tu a tors, so le noids, and many oth ers.

• Con trol el e ments such as switches and potentiometers. These com po nents serve toreg u late if any current flows through the cir cuit or its mag ni tude.

• De vices to pro tect the cir cuit from over loads. These in clude fuses and cir cuitbreakers.

• A com mon ground.

Fig ure 2-3 shows a sim ple cir cuit that in cludes con nec tors, a light bulb, a po ten ti -om e ter, a fuse, a bat tery, and a com mon ground.

8 Chap ter 2

Page 30: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 2-3 Un con ven tional Sche mat ics of a Sim ple, An a log Cir cuit.

2.3 Dig i tal Elec tron icsThe cir cuit in Fig ure 2-3 is clas si fied as an an a log cir cuit. The cir cuit is an a log be -cause the an gu lar po si tion of the po ten ti om e ter arm con veys con tin u ous in for ma tionre gard ing the re sult ing bright ness of the light bulb. Dig i tal de vices, on the other hand,use in di vid ual an a log lev els to rep re sent the cir cuit’s ac tion. For ex am ple, the po ten ti -om e ter in Fig ure 2-3 could be re placed with sev eral sets of in-line re sis tors so that these lec tor arm could only be placed in one par tic u lar level of re sis tance, as shown in Fig -ure 2-4. Nev er the less, cir cuits are nei ther dig i tal nor an a log in them selves but in howthe cir cuit val ues and pa ram e ters are in ter preted.

Fig ure 2-4 A Sim ple Dig i tal Cir cuit.

Cir cuit Fun da men tals 9

+

-

+

-

Page 31: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Dig i tal cir cuits are prev a lent in elec tron ics be cause it is eas ier to get a de vice toswitch into one of a num ber of known states than to re pro duce a con tin u ous rangeof val ues. Dig i tal cir cuits are made from logic gates which model sim ple elec tronicrep re sen ta tions of Boolean logic func tions. Dig i tal cir cuits of fer the fol low ing ad -van tages over their an a log counterparts:

• Dig i tal sig nals can be rep re sented and trans mit ted with out deg ra da tion due to wearor noise as long as the 1s and 0s en cod ing the bi nary val ues can be ac cu rately re con -structed.

• The ac cu racy of a dig i tal sys tem can be im proved by in creas ing the num ber of bi -nary dig its used to en code it. The ac cu racy or res o lu tion of an an a log sys tem re -quires im prove ments in the lin ear ity and noise char ac ter is tics of the sig nal chain.

• Dig i tal sys tems can be con trolled by soft ware.

• In for ma tion can be stored dig i tally more con ve niently than an a log.

Dig i tal cir cuits are the ba sic build ing blocks from which mi cro pro ces sors,microcontrollers, com puter sys tems, and vir tu ally all dig i tal elec tronic de vices arecon structed. These build ing blocks are es sen tially sim ple and per form el e men taryfunc tions. The com pli ca tion some times arises from the fact that a sin gle de vice cancon tain thou sands of these primitive components.

Understanding these com po nents re quires view ing them at the proper ab strac tionlevel. To un der stand a sim ple dig i tal de vice it is es sen tial to know how the sim pler com -po nents that make up the de vice op er ate. For ex am ple, to un der stand how a shift reg is -ter works, it is use ful to vi su al ize it in terms of the logic gates from which it is built.Once one un der stands how coun ters and reg is ters work, it is easy to grasp how a com -plex large-scale in te grated cir cuit, such as a se rial port, op er ates.

For tu nately, at any given level of ab strac tion it is not nec es sary to con sider ev erysin gle pos si ble de vice of that class. For ex am ple, once we un der stand the op er a tionof the few prim i tive logic gates, the op er a tion of de vices that con tain more than oneof these pri mary com po nents can be eas ily grasped. In this chap ter we start by ex -plain ing the ba sic facts about di odes and tran sis tors as ba sic dig i tal elec tron ics de -vices; then we dis cuss the prim i tive logic gates that are the build ing blocks of alldig i tal cir cuits, fol lowed by the more com plex cir cuits that are constructed from the elementary logic gates.

2.4 Di odeIn ba sic elec tron ics we learn that the di ode acts as a one-way valve for elec tri cal cur -rent, and that di odes are one of the most pow er ful in ven tions of semi con duc tor phys -ics. The phys i cal and elec tri cal prin ci ples that make a di ode work are dis cussed inba sic elec tron ics and are there fore out side the scope of this book.

Re view ing fun da men tal con cepts, we can state that the diode is a semi con duc torand all semi con duc tors are made pri mar ily of sil i con. The com bi na tion of sil i conand phos pho rous, with an ex tra phos pho rus elec tron, is called an n-type sil i con. Inthis case the n stands for the ex tra neg a tive elec tron. The ex tra elec tron do nated bythe phos pho rus atom can eas ily move through the crys tal; there fore n-type sil i con

10 Chap ter 2

Page 32: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

can carry an elec tri cal current. When a bo ron atom com bines in a clus ter of sil i conat oms, there is a de fi ciency of one elec tron in the re sult ing crys tal. Sil i con with a de -fi cient elec tron is called p-type (p stands for pos i tive). The va cant elec tron po si tionis some times called a “hole.” An elec tron from an other nearby atom can “fall” intothis hole, thereby mov ing the hole to a new lo ca tion. In this case the hole can carrya current in the p-type sil i con.

When voltage is ap plied to the diode it makes the n-type end more pos i tive thanits p-type. Con se quently, elec trons flow in the n to p di rec tion but not in the p to ndi rec tion. This fact makes the diode be have as a one-way fil ter that al lows elec trons to flow in one di rec tion but not in the other one. Fig ure 2-5 shows the p-n junctionin a diode and its elec tri cal sym bol.

Fig ure 2-5 Di ode El e ments and Sym bol.

The gen eral con ven tion is that cur rent flows from pos i tive to neg a tive, al thoughin re al ity elec trons flow is from neg a tive to pos i tive. Benjamin Frank lin is usu allyblamed for the er ro ne ous con ven tion. Cur rent in the di ode in Fig ure 2-5 flows fromthe an ode to the cath ode, but not vice versa.

The elec tri cal sym bol for a di ode re sem bles an ar row point ing in the di rec tion ofcur rent flow. When the an ode volt age of a di ode ex ceeds the cath ode volt age, the di -ode is said to be for ward bi ased. A for ward-bi ased di ode acts like a short cir cuit. Topre vent too much cur rent from flow ing, a re sis tor is usu ally in serted in se ries withthe diode, as in Figure 2-6.

Fig ure 2-6 Di ode and Re sis tor in a Cir cuit.

Cir cuit Fun da men tals 11

+

- cathode

anode

symbol

p-type

n-type

+

-

Currentflow

Page 33: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

The typ i cal di ode, such as the ones used in logic and dis play cir cuits, can han dlea cur rent of 10 to 20 milliamps. For a 5-volt sup ply, a 300-ohm se ries re sis tor lim itsthe cur rent through the di ode to a rea son able value.

2.4.1 Light-Emit ting Di ode (LED)One of the most com mon types of di odes is an LED (light-emitting di ode). The LED isa semi con duc tor de vice that emits in co her ent light when for ward bi ased. The color ofthe light de pends on the chem i cal com po si tion of the semi con duct ing ma te rial. Thefirst prac ti cal LEDs were de vel oped in 1962. LEDs are some times used in elec tronicde vices to sig nal the pres ence of an elec tric cur rent. Like any di ode, the LED con sistsof a chip of semi con duct ing ma te rial im preg nated with im pu ri ties to cre ate a p-n junc -tion. As in all di odes, cur rent flows eas ily from the p-side, or an ode to the n-side, orcath ode, but not in the re verse. The first LEDs were made of gal lium ar se nide. To day,LEDs are made of a va ri ety of ma te ri als so as to pro duce light of dif fer ent col ors. Themost com mon LEDs have a dis tinc tive red color, al though they can also be ob tained inwhite, am ber, green, and blue.

Be cause LEDs are di odes, they will only light with pos i tive elec tri cal po lar ity,that is, when for ward bi ased. When the po lar ity is re versed, very lit tle or no light isemit ted by the LED. Fig ure 2-7 shows a typical LED.

Fig ure 2-7 Po lar ity in a Typ i cal LED.

The po lar ity of a new LED can usu ally be de ter mined by ob serv ing that the lon ger ter mi nal is the an ode. If the ter mi nals have been al tered, then it is pos si ble but riskyto try to de ter mine po lar ity by ob serv ing the LEDs in ter nals. In most LEDs thelarger in ter nal tab is the cath ode, but there are some in which it is not. A more de -pend able clue to the LEDs po lar ity is the flat tab on the LEDs base, which in di catesthe cathode, as in Figure 2-7.

Rat ings vary among the dif fer ent sizes and types of LEDs. Most are rated to op er -ate be tween 1.7 and 3.8 volts and at cur rents of 10 to 40 mA. The light-emit ting ca -pac ity of an LED is mea sured in megacandela or mcd. Small com mer cial LEDsrange from 10 to about 5000 mcd. Once the LED's rat ing is known, and given the cir -cuit’s volt age, it is nec es sary to cal cu late the value of a se ries re sis tor so that thecur rent does not ex ceed the LED’s ca pac ity. For ex am ple, the se ries re sis tor for wir -ing a com mer cial red LED rated at 2.6 VDC and 28 mA on a 5-volt cir cuit can be cal -cu lated as fol lows:

STEP 1: Cal cu late the volt age across the re sis tor by sub tract ing the LED’s for wardvolt age from the sup ply volt age, in this case.

STEP 2: Ap ply Ohm’s law to cal cu late the re quired re sis tor.

12 Chap ter 2

+

-

Flat tab

Page 34: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

The elec tronic sym bol for a LED is some what sim i lar to that for a di ode, asshown in Fig ure 2-8.

Fig ure 2-8 Elec tri cal Sym bol for LED.

A sim ple ex per i ment is to con nect an LED in se ries with a 330-ohm re sis tor to a5-volt power sup ply and then test to see that light is emit ted for one ori en ta tion ofthe di ode and not for the other. This small cir cuit makes a con ve nient probe for de -ter min ing po lar ity in logic cir cuits. If the LED’s cath ode is touched to some point ina cir cuit, the LED lights up if the volt age at that point is less than about a volt ortwo. The LED re mains dark if the volt age is greater than this value. The cir cuit actsas a 1-bit bi nary dig i tal volt me ter. A com mer cial ver sion of this de vice, usu ally withsev eral dif fer ent-col ored LEDs, is called a logic probe.

In ad di tion to LEDs, other di odes, such as the 1N4148, can be used to en sure thatthe cur rent in a cir cuit flows only in one di rec tion. Heft ier di odes are used to makethe DC power sup plies found in com put ers and other elec tronic equip ment. In thisap pli ca tion the al ter nat ing po lar ity of the 110-volt source is con verted by the di odes into a uni di rec tional DC flow.

2.5 Tran sis tors

The tran sis tor is a solid-state semi con duc tor de vice that is used for sig nal am pli fi ca -tion, volt age sta bi li za tion, switch ing, sig nal mod u la tion, and many other func tions. Ina typ i cal cir cuit, a volt age or cur rent is ap plied to a pair of ter mi nals in the tran sis torso as to change the cur rent level through an other pair of ter mi nals. Be cause the power of the out put ter mi nals can be much greater than that of the con trol ling ter mi nals, thetran sis tor can be used to am plify a sig nal. Tran sis tors were de vel oped and first used inthe early 1950s. They are man u fac tured as in di vid ual com po nents or as part of in te -grated cir cuits. Tran sis tors come in two ba sic types: bi po lar and MOS.

2.5.1 Bi po lar Tran sis tor

The bi po lar transistor was the first type of tran sis tor to be com mer cially mass-pro -duced. The ter mi nals of a bi po lar transistor are called the emit ter, the base, and thecol lec tor. Phys i cally, the bi po lar transistor con sists of two n-type re gions sep a rated by a thin p-type re gion or, al ter na tively, by two p-type re gions sep a rated by a thin n-type.A transistor with two n-type re gions is called an NPN transistor. One of the n-type re -gions is called the col lec tor, the other the emit ter, and the cen tral p-type re gion thebase. The NPN bi po lar transistor is shown in Fig ure 2-9.

Cir cuit Fun da men tals 13

Currentflow

Page 35: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 2-9 Bi po lar, NPN Tran sis tor, and Sym bol.

A com mon sim pli fi ca tion is to con sider a bi po lar tran sis tor as two di odes con -nected back to back so that they share a com mon end. Be cause the cen tral base re -gion be tween the col lec tor and emit ter is very thin, the de vice has the uniqueprop erty of serv ing as an am pli fier. When the tran sis tor’s base-to-emit ter p-n junc -tion is for ward bi ased (this could be called the p-n di ode), it cre ates a low re sis -tance in the thin base re gion that al lows a much larger cur rent to flow from the col -lec tor to the emit ter. If the base-emit ter cur rent is turned off, then thecol lec tor-emit ter cur rent is also com pletely turned off. In this case the tran sis tor issaid to be cut off.

Over a given range, the col lec tor-emit ter cur rent is di rectly pro por tional to thebase-emit ter cur rent. In this im ple men ta tion the tran sis tor am pli fies small cur rentsinto larger ones. Tran sis tors used in ra dios and other sound-am pli fy ing ap pli ca tionsare of this type. For larger base cur rents, the tran sis tor acts as if there is nearly ashort cir cuit be tween the col lec tor and the emit ter. In this case the tran sis tor is saidto be in sat u ra tion. The ef fect is that a pos i tive volt age on the base turns on thetran sis tor and pulls the out put low (to about 0.5 volts). When this volt age is re -moved, the tran sis tor is turned off and the out put is high (+5 volts). The ac tion of atran sis tor is that of a cur rent-con trolled switch, as shown in Fig ure 2-10.

Fig ure 2-10 NPN Tran sis tor Used as a Cur rent-Con trolled Switch.

14 Chap ter 2

collector

collectoremitter

emitter

base

baseNPN

TRANSISTORSYMBOLn-type

p-typen-type

+5 V

input

output

Currentflow

Page 36: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

The cir cuit in Fig ure 2-10 op er ates as fol lows: If the in put volt age is held at zerovolts, the p-n base-emit ter junc tion has no cur rent flow ing through it and thus theout put volt age is +5 volts. How ever, if the in put volt age is raised to any value be -tween +2 and +5 volts, a base-emit ter cur rent flows. This, in turn, al lows a col lec -tor-emit ter cur rent to flow and the out put volt age is pulled down to ground(typ i cally be tween 0.5 and 1 volts). An al ter na tive ar chi tec ture for a bi po lar tran sis -tor is called PNP. In this case, the n-type sil i con is sandwiched be tween two p-types, as shown in Fig ure 2-11.

Fig ure 2-11 PNP Tran sis tor and Sym bol.

The PNP tran sis tor in Fig ure 2-11 works in the same way as the NPN tran sis tor,ex cept that in the PNP de sign the base must have a neg a tive volt age with re spect tothe emit ter in or der to turn on the transistor.

2.5.2 MOS Tran sis tor

The sec ond ma jor type of transistor is the metal ox ide semi con duc tor transistor, orMOS. It con sists of two sep a rated n-type re gions em bed ded in p-type sil i con. Al ter na -tively, the MOS can con sist of two p-type re gions em bed ded in n-type silicon. In thefirst case the de vice is called an n-chan nel MOS (or NMOS) transistor, in the sec ondcase it is called a PMOS.

One of the two n-type re gions is called the source, and the other is called thedrain. An area be tween the source and the drain con sists of a metal con tact sep a -rated from the p-type body by a thin layer of nonconductive sil i con di ox ide. Thisarea is called the gate. When a pos i tive volt age is ap plied to the gate, the elec tricfield at tracts a thin layer of elec trons into the p-type re gion un der neath the gate.This pro vides a low re sis tance path be tween the two n-type re gions. Fig ure 2-12shows the con struc tion of an NMOS tran sis tor and the sym bols for the NMOS andPMOS.

Dur ing con struc tion of the MOS tran sis tor, the body is con nected in ter nally tothe source. In the elec tri cal sym bol this is in di cated by the cen tral wire with an ar -row. In the NMOS tran sis tor the di rec tion of the ar row in di cates that elec trons inthe body are at tracted to the gate when a pos i tive volt age is ap plied. This same volt -age re pels electrons in the PMOS.

Cir cuit Fun da men tals 15

collectorcollector

emitter emitter

base

basePNP

TRANSISTORSYMBOLp-type

p-typen-type

Page 37: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 2-12 MOS Tran sis tor and Sym bols.

One of the most valu able fea tures of MOS tran sis tors is that they re quire verysmall cur rents to turn on. This makes MOS tran sis tors be have like volt age-con -trolled switches in a dig i tal cir cuit while bi po lar tran sis tors op er ate as cur rent-con -trolled switches.

16 Chap ter 2

sourcesource

source

source

insulatingoxidelayer drain

drain

gate

gate

gate

N-CHANNEL MOSTRANSISTOR

SYMBOL

P-CHANNEL MOSTRANSISTOR

SYMBOL

p-type

n-type n-type

Page 38: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Chap ter 3

Logic Gates and Cir cuit Com po nents

3.1 Logic GatesA logic gate can be a vir tual or a phys i cal de vice. In ei ther case the logic gate takes oneor more bi nary sig nals as in put and pro duces a bi nary out put as a log i cal func tion. Theba sic log i cal op er a tions of AND, OR, XOR, and NOT are de scribed in ba sic elec tron icsand Boolean al ge bra texts. Al though logic gates can be made from elec tro mag netic re -lays, me chan i cal switches, or op ti cal com po nents, now a days they are nor mally im ple -mented us ing di odes and tran sis tors.

Charles Babbage’s An a lyt i cal En gine, de vised around 1837, used me chan i cal logic gates based on gears. Elec tro mag netic re lays were later used for logic gates, andthese were even tu ally re placed by vac uum tubes, as Lee De For est’s mod i fi ca tion ofthe Flem ing valve can be used as an AND logic gate. In 1937, Claude E. Shan nonwrote a the sis pa per that in tro duced the use of Boolean al ge bra in the anal y sis andde sign of switch ing cir cuits. The first mod ern elec tronic gate was in vented byWalther Bothe in 1924, for which he re ceived part of the 1954 Nobel prize in physics.

The prim i tive types of gate are the AND, OR, and NOT. Ad di tion ally, the XOR gate of fers an al ter na tive ver sion of the OR. All other Boolean op er a tions can be im ple -mented by com bin ing the three prim i tive types. How ever, for con ve nience, othersec ond ary types have been de vel oped. These are called NAND (NOT plus AND),NOR (NOT plus OR), and XNOR (XOR plus NOT). The ad van tage of these sec ond ary logic gates is that they re quire fewer cir cuit el e ments for a given func tion. In fact,the NAND gate is the sim plest of all gates, ex cept for the NOT gate. Fur ther more, aNAND can im ple ment both a NOT and an OR func tion; there fore it can re place AND, OR, and NOT. This means that the NAND gate is the only type ac tu ally needed in areal sys tem. Pro gram ma ble logic ar rays will very of ten con tain noth ing but NANDgates. The symbols for logic gates are shown in Figure 3-1.

The no tion of a bi nary sig nal is based on it be ing in only one of two states: high or low. Con ven tion ally we rep re sent a high sig nal with bi nary digit “1” and a low with a bi nary digit “0.” True and false and high and low are also as so ci ated with bi nary sig -nals, bi nary 0 rep re sent ing false or low, and bi nary 1 rep re sent ing true or high. In

17

Page 39: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

dig i tal elec tron ics volt age is used to en code bi nary 0 and 1. A volt age of about 0.5volts (ac tu ally 0 to 0.8 volts) is in ter preted as logic 0 and a volt age of about 3.5 volts(ac tu ally 2.4 to 5.0 volts) is in ter preted as logic 1. Volt ages from 0.8 to 2.4 volts arenot al lowed. This volt age con ven tion is re ferred to as TTL (tran sis tor-tran sis torlogic).

Fig ure 3-1 Sym bols for Logic Gate.

3.2 Power Sup pliesStan dard logic cir cuits usu ally re quire a power source of +5 volts DC; bat ter ies are one pos si ble source. A D cell bat tery pro duces 1.5 volts, so three of them con nected in se -ries pro duce 4.5 volts DC. An al ter na tive power source can be a stan dard wall out let.To ob tain +5 volts DC from 110 volts AC re quires scal ing down the volt age and con -vert ing al ter nat ing cur rent to di rect cur rent. In ad di tion, most power sup plies in cludea volt age reg u la tor com po nent that en sures that the cir cuit volt age is ex actly +5 volts.The cir cuit in Fig ure 3-2 is a reg u lated 5-volts DC power sup ply.

Fig ure 3-2 Reg u lated, +5 Volts DC Power Sup ply.

18 Chap ter 3

Y

Y

Y

Y

Y

Y

Y

B

B

B

B

B

B

A

A

A

A

A

A

A

AND

NAND

OR

NOR

XOR

XNOR

NOT

12.5VCENTER-TAPPEDTRANSFORMER

110V ACINPUT

+5V DCREGULATED

OUTPUT

0.1mF100mF78L05

IN OUT

+

Page 40: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

In the cir cuit of Fig ure 3-2 the trans former re duces the house hold volt age from110 to about 12 VAC. The di odes rec tify the in put to an os cil lat ing sig nal of about+12 VDC. The 100mF elec tro lytic ca pac i tor smoothes out the os cil la tion pro duc inga largely DC volt age with lit tle rip ple. The 7805 is a volt age reg u la tor that ac cepts an in put volt age from about 8 volts to about 35 volts and pro duces a con stant 5V out -put. Volt age reg u la tor ICs are Zener di odes with a pre cise, re verse-bi ased break -down volt age. The 7805 is usu ally mounted on a metal base with a drilled hole sothat a heat sink can be at tached to it. With a heat sink, the 7805 can pro duce up to 1amp out put. Figure 3-3 shows a 7805 voltage regulator IC.

Fig ure 3-3 7805 Volt age Reg u la tor IC.

3.3 Clocked Logic and Flip-FlopsIn the cir cuit di a grams con sid ered so far, the out puts are en tirely de ter mined by thein puts to these cir cuits. If the in puts change, so do the out puts. How ever, we of tenneed a dig i tal com po nent whose out put re mains un changed even if there is a change in in put. One use for such a cir cuit is to store a bi nary num ber. A flip-flop is a cir cuit thatper forms as a 1-bit mem ory that stores ei ther the value 0 or 1.

3.3.1 RS Flip-FlopA cir cuit with only two sta ble states is said to be bi stable. A tog gle switch that can beei ther OPEN or CLOSED is a bi stable de vice. A flip-flop is an elec tronic cir cuit withtwo sta ble states, as its out put is ei ther 0 or +5 VDC. In dig i tal terms, a flip-flop is set ifit stores a bi nary 1 and re set oth er wise; the RS des ig na tion re fers to these terms. Theflip-flop can also be said to have mem ory be cause its out put will re main set or re set un -til it is in ten tion ally changed. When the flip-flop out put is 0 VDC it can be re garded asstor ing a logic 0 and when its out put is +5 VDC as stor ing a logic 1, flip-flops can becon structed us ing pri mary logic gates. One pos si bil ity is to use two NAND gates, as inFig ure 3-4.

The fact that a NAND gate is equiv a lent to a neg a tive logic OR gate makes theflip-flop eas ier to un der stand. First con sider that the Set in put is pulled low by flip -ping the switch coun ter clock wise and send ing the in put to ground. In this case theout put of the up per gate (1) is forced high be cause the gate’s out put goes high if ei -ther in put 1 or in put 2 is low. Be cause the Re set in put to the lower gate is high (4),then nei ther in put of the lower gate (3 or 4) is low and its out put is low.

Logic Gates and Cir cuit Com po nents 19

output

ground

input

Page 41: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 3-4 NAND Gate-Based RS Flip-Flop.

Note that in put 3 is low be cause the bub ble on the lower OR gate in verts thevalue fed back from the up per OR gate. Now the feed back line from the lower gate(6) sends low to in put 2 on the up per gate, which is in verted by the up per gate bub -ble. So both in puts to the up per gate are high, which de ter mines that the up pergate’s out put re mains high even when the Set in put re turns to a logic high, as wouldbe the case if the switch were turned back to the neu tral po si tion. Thus, the Q out -put of the flip-flop stays high (and the in verted Q out put re mains low). When theflip-flop is in this state, it is said to be set. The flip-flop is placed in the cleared stateby mo men tarily pull ing the Re set in put low. This forces the lower gate’s output to be high and the upper gate’s to be low.

The ac tion of the flip-flop in Fig ure 3-4 is con sis tent with the de scrip tion of a de -vice with two steady states that is con trolled by two cor re spond ing in put lines la -beled Set and Re set. Also, once in ei ther state the de vice will re main in that stateun til the op po site state is en abled, thus “re mem ber ing” its set or re set sta tus. Thecon di tion of two low in put lines is not al lowed in the flip-flop, as shown in the truthtable.

All me chan i cal switches used in elec tronic de vices con tain a spring of some sort.It is this spring that main tains the switch’s con tact in ei ther po si tion, but it alsomakes the switch elec tri cally “bounce” when ever it is ac ti vated. Al though thebounce only takes a few mil li sec onds, it is highly un de sir able be cause the logic level can change be tween high and low sev eral times dur ing this pe riod. If an RS flip-flopis con nected to the switch, the first con tact switches the flip-flop and sub se quentones have no ef fect, thus ef fec tively “debouncing” the switch.

3.3.2 Clocked Cir cuits

So far the cir cuits dis cussed are ex am ples of com bi na torial logic, also called asyn -chron ous. In com bi na torial cir cuits, if we ig nore a few nano sec onds of prop a ga tionde lay, the out puts change as soon as the in puts change. Al though in the ory you canbuild com plex logic cir cuits us ing com bi na torial logic, it is more con ve nient to useclocked logic pulses to en sure high re li abil ity and noise im mu nity. Cir cuits that useclocked im pulses are said to use syn chro nous logic.

20 Chap ter 3

Set Reset Q R

H H no change

L H H L

H L L H

L L disallowed

+5V

1

2

3

4

6 8

75

+5V

SetQ

RReset

Page 42: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

In syn chro nous cir cuits, changes in logic out puts are not al lowed to prop a gateun con strained. The syn chro nous cir cuit is de signed so that logic-level changes canprog ress through the cir cuitry, one stage at a time, un der the con trol of a clock. Be -tween the clock pulses that cause changes to take place, the tem po rary state of thesys tem is stored in mem ory el e ments or flip-flops.

In clocked or syn chro nous logic, all the gates in the sys tem change out puts at thesame time. The out put state of each gate de pends only on the state of the gate in -puts at the time of the clock pulse. In com bi na torial cir cuits, the gates may brieflysee the wrong logic level and cause in cor rect op er a tion of the cir cuit. Clocked logicen sures that gate out puts set tle down dur ing the time be tween clock pulses; thus,only valid logic lev els are pres ent by the time the next clock pulse arrives.

The RS pushbutton in Fig ure 3-4 can not be used in a clocked logic cir cuit be cause its out put changes im me di ately when ever the Set or Re set in puts change. How ever,the cir cuit can be made into a clocked RS flip-flop by add ing two NAND gates, asshown in Figure 3-5.

Fig ure 3-5 A Clocked RS Flip-Flop.

In the clocked flip-flop of Fig ure 3-5, the Set and Re set in puts can change at anytime, but those changes will be ig nored by the flip-flop ex cept dur ing the in ter valwhen the logic high of a clock pulse is pres ent. It is the NAND gates that en sure thatthe Set and Re set lines are read by the cir cuit only when the clock sig nal is high.This de ter mines that the state of the Set or Re set line is stored by the flip-flop onlydur ing the high phase of the clock pulse.

3.3.3 D Flip-Flop

One ob jec tion to the flip-flops in Fig ures 3-4 and 3-5 is that they re quire two data in putlines (which are la beled Set and Re set in the il lus tra tions). In many ap pli ca tions amore con ve nient scheme is to have a sin gle in put line that is read as Set if it is high andRe set oth er wise. To im ple ment this cir cuit so that a sin gle in put line is used we cancon nect an in verter be tween the Set line and the Re set in put. The cir cuit for a D (fromdata) flip-flop is shown in Fig ure 3-6.

Logic Gates and Cir cuit Com po nents 21

Set

Q

RReset

Clock

Page 43: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 3-6 The D Flip-Flop.

The D flip-flop is also called a trans par ent latch, or a D latch. In the D flip-flopthe state of the in put line, called the D (or data) in put, is stored in the flip-flop whena clock pulse oc curs. An ad di tional ad van tage of the D latch is that the dis al lowedstate (see Fig ure 3-4), in which both Set and Re set are si mul ta neously low, can notbe reached ac ci den tally.

We have men tioned that a flip-flop can be used for stor ing bi nary data. To vi su al -ize how this can be done, imag ine four D flip-flops driven by the same clock sig nal.When the clock goes high, in put data is loaded into the flip-flops and ap pears at theout put. When the clock goes low, the out put re tains the data. For ex am ple, sup posefour data in puts, as fol lows:

When the clock sig nal goes high, these four bits are loaded into the D latches, re -sult ing in the out put

This op er a tion is rep re sented in Fig ure 3-7.

Fig ure 3-7 Four Data Bits Stored in D Latches.

22 Chap ter 3

Q

R

Clock

Data

D D D D0 1 2 3 0101=

Q Q Q Q0 1 2 3 0101=

D3

CLKD D D D

Q Q Q QQ Q Q Q

CLK CLK

Clock

CLK

D2 D1 D0

Q3 Q2 Q1 Q0

Page 44: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

In the 4-bit D latch of Fig ure 3-7, the out put data is stored as soon as the clockgoes low. For as long as the clock is low, the D val ues can change with out af fect ingthe Q val ues. The 7475 IC con tains four D flip-flops and is called a quad bi stablelatch. This cir cuit is well suited for han dling 4-bit data bits si mul ta neously (one nib -ble).

3.3.4 Edge-Triggered D Flip-FlopThe D flip-flop or trans par ent latch is avail able in sev eral ver sions. Al though the pureD flip-flop is a use ful IC, it has the draw back that out puts fol low the D in put dur ing theen tire time that the clock line is high. In some cir cuits it is pref er a ble for the flip-flop to store data at a sin gle and unique point in time. The Edge-Trig gered D-type flip-flop ap -proaches this be hav ior. In this de vice, the flip-flop only stores the state of the data lineat the in stant the clock sig nal makes a tran si tion from low to high. Fig ure 3-8 shows anEdge-Trig gered D flip-flop.

Fig ure 3-8 Edge-Trig gered D Latch.

The cir cuit in Fig ure 3-8 is some times called an RC dif fer en ti ated clock in putlatch. In this case, RC stands for the re sis tor/ca pac i tor pair at the in put of the Dlatch. By de sign, the RC time con stant is made smaller than the clock’s pulse width.This de ter mines that the ca pac i tor fully charges when the clock goes high, whichpro duces a nar row pos i tive volt age spike across the re sis tor. Later, the trail ing edgeof the pulse re sults in a nar row neg a tive spike, which in turn en ables the AND gatesfor a brief pe riod. The ef fect is to ac ti vate the AND gates only dur ing the pos i tivespike; the neg a tive spike does noth ing in this cir cuit. The re sult is equiv a lent to sam -pling the value of D for an in stant. At this point in time, D and its com ple ment hit the flip-flop in puts, forc ing Q to set or re set (un less Q is al ready equal to D).

3.3.5 Pre set and Clear Sig nals

The use of flip-flops in dig i tal cir cuits usu ally re quires some way of plac ing the sig nalsin a known state. In this sense a Pre set sig nal is used to make sure that the Set line ishigh, and a Clear sig nal to make sure that the Re set line is high. Al ter na tively, some -times these sig nals are re ferred to as Pre set R and Pre set S. Fig ure 3-9 shows how thePre set and Clear func tions can be im ple mented in an RS flip-flop.

Logic Gates and Cir cuit Com po nents 23

QS

R Q

Clock

Data

Page 45: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 3-9 Im ple ment ing Pre set and Clear.

The OR gates in the cir cuit of Fig ure 3-9 al low se lec tively set ting the S or the Rlines of the Edge-Trig gered D flip-flop. The Pre set and Clear sig nals are called asyn -chron ous in puts be cause they ac ti vate the R or S lines of the flip-flop in de pend entlyof the clock. The D in put, on the other hand, is syn chro nous because it has an ef fectonly when the clock edge sig nal is high. Fig ure 3-10 shows the elec tri cal sym bol fora pos i tive Edge-Trig gered flip-flop with ac tive high Preset and Clear lines.

Fig ure 3-10 D-Type Edge-Trig gered Flip-Flop Sym bol.

The stan dard mode of op er a tion for a D-type flip-flop is to have the Set and Clearin puts high (not ac tive), so that a tran si tion of the clock in put from low to high(called a pos i tive edge) clocks the value of D into Q and the in verse of D into not-Q.The clock tran si tion is re quired be cause noth ing hap pens to Q and not-Q un til a pos -i tive edge oc curs on the clock line.

3.3.6 D Flip-Flop Wave form Ac tion

An easy way to un der stand the in ter ac tion of the var i ous sig nals in a clocked RSflip-flop is by means of a wave form di a gram. The ref er ence cir cuit is the one in Fig ure3-9, which in cludes a clock sig nal, a data in put line, Pre set and Clear lines, Set and Re -set in put lines, and Q and not-Q out put lines. The sig nals are de scribed as fol lows:

24 Chap ter 3

QS

R Q

Clock

Data

Preset

Clear

QD

CLK

Q

PR

CLR

Page 46: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

1. The clock sig nal (CLK) is a square wave that os cil lates be tween a high and a lowstate. It pro vides a syn chro nized beat that co or di nates the var i ous dig i tal de vicespres ent in the cir cuit.

2. The data sig nal is used as a sin gle in put line into the flip-flop. Set ting the data sig nalhigh also sets high the flip-flop’s Set line. A low data sig nal makes the flip-flop Re set line high.

3. The Set sig nal or line is one of the two in puts into the flip-flop. The other one is theRe set line.

4. The Pre set line is used to make the flip-flop Set line ac tive. The Clear sig nal has theef fect of set ting high the Re set line into the flip-flop.

5. The Q and not-Q lines pro vide the flip-flop out put. Q is high if the Set line is high,oth er wise the not-Q line is high.

Fig ure 3-11 is a wave form di a gram for a clocked RS flip-flop.

Fig ure 3-11 Wave form Di a gram for Clocked RS Flip-Flop.

In Fig ure 3-11 note that the clock in put (at the top of the il lus tra tion) pro vides the syn chro ni za tion beat for the flip-flop in puts (R and S) and the out puts (Q andnot-Q). How ever, the Pre set and Clear sig nals are asyn chron ous; that is, they op er -ate in de pend ently of the clock pulse. There fore, when the Pre set line is set high, the S in put line into the flip-flop im me di ately fol lows. How ever, the Q out put line mustwait un til the next ris ing clock pulse, which cor re sponds to the dot-dash line la -beled Set in the il lus tra tion. Sim i larly, the Clear sig nal im me di ately sets the R line;how ever, the not-Q out put is not set un til the next ris ing clock pulse. No tice thatdur ing clock pulse num ber 4, both the R and S lines are held low. This cor re spondsto a hold state dur ing which the output on lines Q and not-Q remains unchanged.

3.3.7 Flip-Flop Ap pli ca tionsThe D-type flip-flop finds many uses in dig i tal tech nol ogy. Per haps the most ob vi ousone is as a mem ory. We have seen that the flip-flop stores the value clocked into it fromthe D line; its value can be read on the out put lines Q and not-Q. A type of mem oryknown as static RAM is im ple mented as a large ar ray of flip-flops with ad dress de cod -ing cir cuitry. This de sign al lows se lect ing which flip-flop is be ing ac cessed by a read or write op er a tion. Pro ces sors, mi cro pro ces sors, and microcontrollers con tain many

Logic Gates and Cir cuit Com po nents 25

Page 47: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

flip-flops, usu ally in the form of reg is ters. These reg is ters are just a group of 8, 16, 32,or 64 flip-flops. Flag reg is ters are also flip-flops that are set or cleared by the re sults ofthe CPU’s in ter nal op er a tions.

Dig i tal de vices in ter face with the out side world by means of in put and out putports. These el e ments are im ple mented as flip-flops. For ex am ple, the logic in agiven cir cuit may re quire turn ing on an LED so as to sig nal that some event has oc -curred. To achieve this, a data line from the dig i tal de vice can be con nected to the Din put of a flip-flop. Then a pulse is sent on an other line to the clock in put. When theclock pulse goes from low to high, the state of the data line at that in stant is clocked into the flip-flop. This state re mains on the Q out put un til a new value is clocked in.An other ex am ple is the 74374 IC, which con tains 8 flip-flops in a sin gle 20-pin DIPpack age. The chip is called an oc tal latch be cause the data is latched into all eightflip-flops all at once by a sin gle clock line.

D-type flip-flops are also used in im ple ment ing more com plex dig i tal in ter faces,such as an in ter rupt sys tem. For ex am ple, a dig i tal de vice that reads in data from anex ter nal source, such as a switch. Each time a new data state is pro duced by theswitch, a flip-flop is set and the out put of this flip-flop is con nected to an in ter ruptre quest line (IRQ) on the de vice. When the IRQ line goes high, the microcontrollersaves its cur rent state and branches off to an in put rou tine that takes some ac tionac cord ing to the state of the switch, for ex am ple, turns on an LED if the switch ishigh. To pre vent the microcontroller from get ting in ter rupted again by the same in -put, the same sig nal is also used to clear the flip-flop un til the next data byte co mesalong.

3.4 Dig i tal ClocksA clock sig nal con sists of a se quence of reg u larly spaced pulses, typ i cally in the formof a square wave. Dig i tal de vices use the ris ing or the fall ing edges of the square waveto op er ate logic cir cuits. Clocks pro vide the heart beat, with out which the sys temwould cease to func tion.

3.4.1 Clock Wave forms

In a dig i tal de vice, such as a microcontroller, the clock fur nishes a pe ri odic wave formthat is used as a syn chro niz ing sig nal. Al though the typ i cal clock wave form is de picted as a square wave (as in Fig ure 3-11), it should be noted that the wave need not be per -fectly sym met ri cal. In fact, a se ries of pos i tive or neg a tive edges can serve as a tim ingpulse in a dig i tal cir cuit. The one re quire ment of a clock pulse is that it be per fectly pe -ri odic.

The ba sic tim ing in ter val for a dig i tal cir cuit, which is equal to one full wave formpe riod, is called the clock cy cle. This de ter mines that all logic el e ments in the cir -cuit, in clud ing gates and flip-flops, must com plete their tran si tions in a time pe riodno lon ger than a com plete clock cy cle.

We can as sume that the ideal clock pro duces a per fectly square wave form that isab so lutely sta ble, as is the one shown in Fig ure 3-12.

26 Chap ter 3

Page 48: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 3-12 Ideal Clock Wave form.

A sta ble and uni form wave form reaches ex actly the same volt age ev ery time it ishigh, for ex am ple, +5 volts. By the same to ken, ev ery time the clock sig nal goes low,the volt age level must be the same, typ i cally 0 volts. In ad di tion, the clock sig nalmust re main at the high and low lev els for the same time, and the time be tween each high and low cy cle must be ex actly the same. This last el e ment is usu ally called thefre quency sta bil ity of the clock. In Fig ure 3-12 the fre quency sta bil ity re fers to thetime it takes for the sig nal to tran si tion from point a to point c dur ing each clock cy -cle. In prac tice, the sta bil ity and uni for mity of the clock sig nal are more im por tantthan the ab so lute value. For ex am ple, it is usu ally ac cept able that the high volt agelevel of the clock sig nal be 4.8 volts in stead of 5 volts, as long as the 4.8-volt level isex actly re pro duced at ev ery clock cy cle.

An other char ac ter is tic of the clock sig nal is the time re quired for clock lev els tochange from high to low and vice versa. Ide ally, this tran si tion could be rep re sentedby a ver ti cal line, as in Fig ure 3-12. This means that the tran si tion is in stan ta neous,which is not achiev able in ac tual cir cuits. In prac tice, some time is re quired for thewave form to tran si tion from low to high, and vice versa. The ac tual graph of thewave form, as can be seen on an os cil lo scope, shows a slightly slop ing side. Cus tom -arily, the ac tual mea sure ment of the tran si tion time is re ferred to as the 10 and 90per cent points. For ex am ple, in a 5-volt wave form, the rise-time is the time it takesfor the volt age to go from 0.5 to 4.5 volts, which are the 10 and 90 percent points forthat waveform.

3.4.2 TTL Clock

A much-used TTL-com pat i ble clock can be built around a 7404 hex in verter IC such asthe one in Fig ure 3-13. The idea is to use two in vert ers to build a two-stage am pli fierwith an over all shift of 360 de grees. The out put sig nal at one of the in vert ers is fedback, through a crys tal, to the first in verter, which de ter mines that the cir cuit os cil -lates at a fre quency de ter mined by the crys tal. Thus, the fre quency of this clock sig nalis de ter mined by the crys tal: val ues be tween 1 and 20 MHz are com mon. The TTL clock cir cuit is shown in Fig ure 3-13.

The crys tal in the cir cuit of Fig ure 3-13 makes the fre quency of os cil la tion verysta ble. The third in verter is used as an out put buffer and al lows driv ing the load sim -u lated by the RC circuit.

Logic Gates and Cir cuit Com po nents 27

Time

a b c

0V

+5V

Page 49: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 3-13 TTL Clock Cir cuit.

The clocks used in dig i tal sys tems need to be sta ble and uni form so that the fre -quency is the same and each pulse is iden ti cal to ev ery other one. To achieve this, avery narrowband fre quency-se lec tive fil ter whose cen ter fre quency does not change is re quired. Quartz crys tals are a good choice for this pur pose be cause they pro videa sta ble, pre ci sion os cil la tor. A quartz crys tal is ac tu ally a thin piece of pol ishedcrys tal line quartz with con tacts plated on each sur face and a lead at tached to eachcon tact. Quartz is a pi ezo elec tric ma te rial, which means that there is one par tic u larelec tri cal fre quency that ex cites the crys tal’s res o nance. It is this very nar row res o -nant fre quency that is used to build a fre quency-se lec tive fil ter whose cen ter fre -quency changes very lit tle as the com po nents age or with changes in tem per a ture.Crys tal os cil la tors are avail able with fre quen cies that range from 10 KHz up to 600MHz. They are typ i cally housed in small metal cases with the fre quency printed onthe out side.

3.4.3 555 TimerOne of the most ver sa tile timer ICs is the TTL-com pat i ble 555 timer. This chip can beused to make many dif fer ent kinds of os cil la tors, pulse gen er a tors, and tim ers. As anos cil la tor, the 555 can be made to pro duce square, sawtooth, or tri an gle waves, and itsfre quency can be mod u lated by an ex ter nal in put. Al though the 555 is not a TTL part,its out put is TTL com pat i ble when it is used with a 5-volt power sup ply.

The 555 has two dis tinct out put lev els, which con tin u ously switch back and forthbe tween these two un sta ble states. Be cause of this os cil la tion, the cir cuit out put isa pe ri odic, rect an gu lar wave form. The fact that nei ther out put is sta ble ac counts for the cir cuit be ing clas si fied as astable or bi stable. The fre quency of os cil la tion aswell as the duty cy cle are ac cu rately con trolled by two ex ter nal re sis tors and a sin -gle tim ing ca pac i tor. Fig ure 3-14 shows the logic sym bol for a 555 timer as well asthe wir ing to implement an asymmetric square-wave generator.

28 Chap ter 3

Clockoutput

Simulatedload

Crystal

GND

+5V

Page 50: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 3-14 555 Timer as a Square Wave Gen er a tor.

3.4.4 Microcontroller ClocksMicrocontrollers, like most dig i tal com po nents, re quire a syn chro niz ing tim ing pulsepro vided by some form of clock ing de vice. There are five com mon ways of im ple ment -ing a timer in a microcontroller:

1. In ter nal clock

2. RC network

3. Crys tal oscillator

4. Ce ramic res o na tor

5. Ex ter nal oscillator

The se lec tion de pends on the spe cific microcontroller, the cir cuit re quire ments,and the cost of each avail able op tion. The cheap est op tion is the re sis tor/ca pac i toros cil la tor cir cuit (RC net work). The dis ad van tages are its slow speed and in her entin ac cu ra cies. Some of the newer gen er a tions of microcontrollers come equippedwith an in ter nal RC os cil la tor that op er ates as a pro gram ma ble timer. Typ i calspeeds are 4 MHz with a 1.5 per cent er ror. The ac tual use and im ple men ta tion ofmicrocontroller clocks are discussed in relation to each specific device.

3.5 Coun ters and Fre quency Di vid ers Coun ters and fre quency di vid ers are ac tu ally the same cir cuitry, used in dif fer entways. Coun ters are one of the most use ful and ver sa tile dig i tal de vices. They can be

Logic Gates and Cir cuit Com po nents 29

TTLcompatible

output

Bypasscapacitor

OUT 3

4

7

8

2

6

1

5

Discharge

+5V

ThresholdTrigger

555

Page 51: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

used to keep track of the num ber of clock cy cles and as an in stru ment for mea sur ingtime and there fore pe riod or fre quency. There are two dif fer ent types of coun ters:syn chro nous and asynchrounous.

3.5.1 Fre quency Di vid ersCir cuit de sign ers of ten need to re duce the fre quency of a wave clock sig nal. One easyway of do ing it is to di vide the fre quency by two by feed ing back the not-Q out put of aD-type flip-flop to its data line. Fig ure 3-15 shows a di vide-by-two cir cuit and its ef fecton the re sult ing wave.

Fig ure 3-15 A Di vide-by-Two Cir cuit.

In the cir cuit of Fig ure 3-15 the fre quency di vi sion oc curs be cause the ris ing edge of each clock in put tog gles the flip-flop’s out put. This re sults from the fact thatwhen the Q out put goes low, the not-Q line goes high and the high feed back sig nal isfed back to the data line, thus can cel ing out the next high wave of the f sig nal.

3.5.2 JK Flip-Flop Coun terOne type of spe cial ized flip-flop is the JK flip-flop. The JK flip-flop is an ideal com po -nent to build a cir cuit that keeps track of the num ber of pos i tive or neg a tive clockedges of the in put clock. The name of this flip-flop re lates to the two vari ables, J and K,that are used as in puts to the cir cuit. Fig ure 3-16 shows one pos si ble cir cuit im ple men -ta tion for the JK flip-flop.

In Fig ure 3-16 the RC com po nents con vert the rect an gu lar wave clock pulse intoa nar row spike. The three-in put AND gates make the cir cuit pos i tive-Edge-Trig -gered. When J and K are both low, both AND gates are dis abled; there fore, clockpulses have no ef fect. This cor re sponds with the first en try in the truth table. WhenJ is low and K is high (sec ond en try in the truth table), the up per gate is dis abled, sothe flip-flop can not be set, which means that it must be re set. When Q is high, thelower gate passes a RESET trig ger as soon as the next pos i tive clock edge ar rives.This forces Q to be come low (the same sec ond en try in the truth table). There fore, J low and K high means that the next pos i tive clock edge will re set the flip-flop.

30 Chap ter 3

f/2output

time

f/2

f

finput

D

Q

Q

Page 52: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 3-16 The JK Flip-Flop Cir cuit.

When J is high and K is low (third en try in the truth table), the lower gate is dis -abled, so it is im pos si ble to re set the flip-flop. How ever, the flip-flop can be re setwhen Q is low be cause in that case not-Q is high; there fore the up per gate passes aSET trig ger on the next pos i tive clock edge. This drives Q into the high state (thethird en try in the truth table). As you can see, J = 1 and K = 0 means that the nextpos i tive clock edge sets the flip-flop (un less Q is al ready high). When J and K areboth high it is pos si ble to set or re set the flip-flop. If Q is high, the lower gate passesa RESET trig ger on the next pos i tive clock edge. On the other hand, when Q is low,the up per gate passes a SET trig ger on the next pos i tive clock edge. Ei ther way, Qchanges to the com ple ment of the last state (see last en try in the truth table). There -fore, J = 1 and K = 1 means the flip-flop will tog gle on the next pos i tive clock edge.

3.5.3 Rip ple Coun ters

The sim plest of all coun ters is called a rip ple counter. A two-bit rip ple counter can becon structed by wir ing to gether two di vide-by-two circuits, as in Fig ure 3-17. String ingto gether two di vide-by-two circuits pro duces a di vide-by-four cir cuit. String ing to -gether three flip-flops pro duces a di vide-by-eight cir cuit, four flip-flops cre ate a di -vide-by-six teen cir cuit, and so on. The counting ac tion of the con nected flip-flops isbased on the fact that each flip-flop changes state be fore it trig gers the next one inline. Thus, each stage per forms as a bit in a bi nary coun ter, the first stage be ing theLSB and the last state the MSB. Be cause the pre ced ing flip-flop acts as a clock for thenext one in line, the flip-flop to the right will tog gle each time its neigh bor to the leftgoes low. In Fig ure 3-17 the sig nal la beled Q0 is the LSB of a two-bit coun ter, while thesig nal la beled Q1 is the most sig nif i cant bit.

Logic Gates and Cir cuit Com po nents 31

QS

R Q

CLK

J

K

CLK J K Q

X L L last state

H L H L

H H L H

H H H toggle

Page 53: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 3-17 Two-Bit Rip ple Coun ter.

In this de sign, each flip-flop is trig gered by the pre vi ous one; thus the count issaid to “rip ple” down the de vice. One ob jec tion to the rip ple coun ter is that thechange in each out put is de ter mined by the pre vi ous out put in the flip-flop chain,which pro duces a few nano sec onds’ time lag from out put line to out put line. Thiscu mu la tive set tling time is why these coun ters are called serial or asynchronous.

Note that the rip ple coun ter of Fig ure 3-17 uses the not-Q line to drive the nextflip-flop in the chain. If a rip ple coun ter is wired so that the Q line drives each nextstage, then the tran si tions take place not when the pre vi ous wave form goes low, but when it goes high. The re sult is that the coun ter counts down in stead of up. In otherwords, in the down coun ter, the count is re duced by one dur ing each clock tran si -tion. Com mer cial coun ters, such as the 74193, can be made to op er ate as anup-coun ter or a down-coun ter by se lect ing the corresponding input line.

3.5.4 De cod ing Gates

A de cod ing gate is a way of con nect ing the out put of a coun ter so that it will sig nal agiven state. For ex am ple, if four D-type flip-flops are wired so as to pro duce a four-bitrip ple coun ter, sim i lar to the one in Fig ure 3-18, the coun ter will rep re sent bi nary dig -its 0000 to 1111. If we wanted to de tect the value 1101 (16 dec i mal), the re sult ing cir -cuit could be de signed as in Fig ure 3-18. This cir cuit uses a NOR gate to in vert thevalue of bit num ber 1. The AND gate serves to trig ger the out put when bits 0, 2, and 3are high and bit 1 is low. This state cor re sponds to the bi nary value 1101.

32 Chap ter 3

Q0

Q0

Q1

Q1

clock

0/0 0/1 1/0 1/1 0/0 ...

waveinput

D D

Q Q

Q Q

Page 54: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 3-18 A De cod ing Gate.

3.5.5 Syn chro nous Coun tersAl though the rip ple coun ter is the sim plest one, it has the pre vi ously men tioned dis ad -van tage that each flip-flop has to wait for its neigh bor to switch states. This de ter -mines that in a rip ple coun ter, the de lay times are ad di tive, and the to tal “set tling” timefor the coun ter is ap prox i mately the de lay mul ti plied by the to tal num ber of flip-flops.In ad di tion, with rip ple coun ters the re sult ing de lay cre ates the pos si bil ity of glitchesoc cur ring at the out put of de cod ing gates. These prob lems can be over come by the use of a syn chro nous or par al lel coun ter.

A coun ter in which each flip-flop is trig gered at ev ery clock beat can be built byob serv ing how count ing takes place in bi nary num bers. Bi nary count ing has theprop erty that when a bit changes from high to low (0 to 1), it sends a tog gle com -mand to its neigh bor to the left. So as sum ing that the low-or der bit changes con sec -u tively from one state to its com ple ment, and start ing from all bits in i tial ized to 0,bi nary count ing can be vi su al ized as in Figure 3-19.

Fig ure 3-19 Vi su al iza tion of Bi nary Count ing.

Logic Gates and Cir cuit Com po nents 33

Q0Q2 Q3

Q1

waveinput

D D D D

1101

Q Q Q Q

Q Q Q Q

0000

0001

0010

0011

0100

0101

0110

0111

. . .1111

Page 55: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 3-20 A Syn chro nous 4-Bit Up Coun ter.

In Fig ure 3-19 the ar rows in di cate the tran si tion from high to low, which is thecom mand for the col umn to the left to change to its com ple ment (tog gle). Us ing this prop erty of bi nary count ing, it is pos si ble to wire four JK flip-flops so that ev eryhigh-to-low tran si tion of a flip-flop trig gers its higher-or der neigh bor to tog gle itsstate. Fig ure 3-20 shows such a sys tem.

In Fig ure 3-20, the first flip-flop (Q0 out put line) has a pos i tive-edge trig geredclock in put. The low est-or der flip-flop tog gles with each ris ing edge of the clock sig -nal (not shown in the il lus tra tion). The sec ond flip-flop to the right tog gles with ev -ery fall ing edge of the sig nal from its neigh bor to the left. And so on to the lastflip-flop in the chain. The ar rows in the wave form por tion of Fig ure 3-20 show thateach suc ceed ing out put bit is tog gled by the tran si tion from high to low of itslower-or dered neigh bor. Also note the dashed line that marks the point where allcoun ters are transitioning from high to low. At this point, all four coun terswrap-around to zero and a new count be gins.

Ob serve that the not-Q out put line tran si tions op po site to the Q out put. That is,when the Q out put line goes high, not-Q goes low, and vice versa. There fore, if thepulse into each suc ces sive flip-flop orig i nated in the not Q-line, in stead of the Q line, then the re sult ing cir cuit would be a syn chro nous coun ter that tran si tions on thepos i tive edge (low-to-high) in stead of on the neg a tive edge. If we ob serve that thenot-Q lines also pro vide a set of ne gated out puts in ref er ence to the Q lines, then itis pos si ble to come up with a cir cuit that serves both as an up- and down-coun ter ac -cord ing to the se lected set of out puts. Such a circuit is shown in Figure 3-21.

34 Chap ter 3

Q0 Q2 Q3Q1

waveinput

J J J J

K

wrap-around point

K K K

+5V

Q Q Q Q

Q Q Q Q

Q0

Q1

Q2

Q3

Page 56: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 3-21 Syn chro nous 4-Bit Up- and Down-Coun ter.

In the coun ter of Fig ure 3-21, the Q out puts gen er ate the up-count se ries whilethe not-Q out puts pro duce the down-count se ries.

3.5.6 Coun ter ICsCoun ters are avail able as stan dard TTL com po nents. The 7493 is an asyn chron ous4-bit rip ple coun ter that counts from 0 to 15. The 7490 is an other ver sion of the rip plecoun ter, called a de cade coun ter, as the count out put is in the range 0 to 9. The 74193 isa 4-bit syn chro nous up/down coun ter in the range 0 to 15. Fig ure 3-22 is a pin di a gramof the 74193.

Fig ure 3-22 Pin Di a gram of the 74193 Syn chro nous Up/Down Coun ter.

Logic Gates and Cir cuit Com po nents 35

Q0

Q0

Q2

Q2

Q3

Q3

Q1

Q1

waveinput

J J J J

K K K K

+5V

Q Q Q Q

Q Q Q Q

74193

14

15

161

13

2

12

3

11

4

10

5

9

6

7

8

+5Vinput B

input A

input D

input C

carry out

borrow out

reset

preset (active low)

output QB

output QA

down clock

up clock

output QC

output QD

0V

Page 57: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

The 74193 is a syn chro nous coun ter so its out put changes pre cisely at each clockpulse. This is con ve nient be cause it al lows for con nect ing its out put to other logicgates and avoids the glitches as so ci ated with rip ple coun ters. In Fig ure 3-22 you can see that the 74193 has sep a rate clock in puts for count ing up and count ing down.The count in creases as the up clock in put be comes high (on the ris ing-edge). Thecount de creases as the down clock in put be comes high (on the ris ing-edge). In bothcases the other clock in put should be high. For nor mal op er a tion the pre set in putshould be high and the re set in put low. When the re set in put is high, it re sets thecount to zero, that is, lines QA to QD are low. The coun ter can be pre set by plac ingany de sired bi nary num ber on in puts A to D and mak ing the pre set in put low. Theseinputs may be left unconnected if not re quired. Sev eral 74193 coun ters can bechained by wir ing a com mon re set line, con nect ing the carry to the up clock line ofthe next coun ter and the bor row to the down line.

3.5.7 Shift Reg is tersThe hard ware im ple men ta tion of bi nary shift and ro tate operations are called shiftcoun ters or shift reg is ters. Shift coun ters are of ten based on the D-type flip-flop. Ac -tu ally, sev eral D-type flip-flops can be chained to gether so that the D out put of onegoes into the D in put of the next one. If all the flip-flops are driven by the same clocksig nal, then the ef fect would be to shift the bits from one flip-flop into the next one ateach ris ing clock pulse. A com mon im ple men ta tion of a shift coun ter is called a par al -lel-in/se rial-out shift reg is ter, as the one in Fig ure 3-23.

Fig ure 3-23 4-Bit Par al lel-in/Se rial-out Shift Coun ter.

The cir cuit in Fig ure 3-23 shows four flip-flops con nected so that the out put ofone feeds into the in put of the next one. Also, a set of NAND gates al low par al leldata in put. When the load sig nal is set high, the flip-flops in the shift reg is ter areloaded si mul ta neously with the logic val ues at the in puts A, B, C, and D. The 74165IC is an 8-bit par al lel-in/se rial-out shift reg is ter with asyn chron ous par al lel load andtwo OR-gated clock in puts. Fig ure 3-24 is a pin diagram of the 74165 IC.

36 Chap ter 3

CLOCK

serialin

load

serialout

CLR

SET

A B C D

D Q

CLR

SETD Q

CLR

SETD Q

CLR

SETD Q

Page 58: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 3-24 Pin Di a gram of 74165 IC.

The se rial in put line in the di a gram of Fig ure 3-23, and in the 74165 IC in Fig ure3-24, al low cas cad ing mul ti ple chips.

Par al lel-in/se rial-out shift reg is ters find com mon use in the im ple men ta tion of se -rial ports. In se rial com mu ni ca tions, data is sent 1 bit at a time over a sin gle wire. Inor der to ac com plish this, data is first loaded into a par al lel-in/se rial-out shift reg is -ter. The in di vid ual bits are then shifted out one at a time. The fre quency of the driv -ing clock in this case cor re sponds to the baud rate be ing used. A sec ond type ofshift reg is ter is used to re ceive the data on a se rial com mu ni ca tions line. In this case the op er a tion is se rial-in/par al lel-out. The cir cuit that ac com plishes this is basedon D-type flip-flops in which the Q out puts are con nected to the D in put lines.

The 74164 IC is one such de vice. In ac tual se rial ports, the trans mit ting and re -ceiv ing shift reg is ters are con tained in a sin gle de vice called a UART.

3.6 Multiplexers and Demultiplexers

It is of ten the case in dig i tal elec tron ics that dif fer ent sig nals must be sent out on a sin -gle out put line, or sev eral sig nals must be re ceived in a sin gle in put line. The dig i talcir cuits that per form these op er a tions are called multiplexers and demultiplexers.Multiplexers and demultiplexers are TTL analogs of the many-to-one and one-to-many me chan i cal switches.

Logic Gates and Cir cuit Com po nents 37

74165

14

15

161

13

2

12

3

11

4

10

5

9

6

7

8

+5Vshift/load

clock inhibit

input D

output Q

clock

input E input D

input F input C

input G input B

input H

serial inputoutput Q

GND

Page 59: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

3.6.1 MultiplexersMultiplexing (also called muxing) is a way of com bin ing the data of two or more in -put chan nels into a sin gle out put chan nel. The hard ware multi plexer, also called amux, com bines sev eral elec tri cal sig nals into a sin gle one. The multi plexer per forms a many-into-one func tion. Some times multi plexers and demultiplexers are com binedinto a sin gle de vice, which is still re ferred to as a “multi plexer.” Fig ure 3-25 shows thesche mat ics di a gram of a multi plexer.

Fig ure 3-25 Multi plexer Sche mat ics.

The truth ta ble in Fig ure 3-25 de scribes the multi plexer op er a tion. The line la -beled “sel” in the il lus tra tion is the se lec tor line. If the se lec tor is low (S = 0), thenin put line B is mir rored in the out put line O. Oth er wise, in put line A is vectored tothe out put. The Boolean ex pres sion for the multi plexer in Fig ure 3-25 is

Of ten, a multi plexer cir cuit is pre ceded by a de coder cir cuit so that in put can becom pressed into fewer lines. For ex am ple, a four-to-one multi plexer re ceives a bi -nary value in the range 0 to 3 (bi nary 00 to 11) on two in put lines and sets high oneof four out put lines ac cord ingly. Fig ure 3-26 shows the cir cuit di a gram for such adevice.

Fig ure 3-26 Two-Bit One-of-Four Multi plexer.

38 Chap ter 3

A

A B S O

0 0 0 B (0)0 0 1 A (0)0 1 0 B (1)0 1 1 A (0)1 0 0 B (0)1 0 1 A (1)1 1 0 B (1)1 1 1 A (1)

B

sel (S)

out (O)

O A S B S= ∧ ∨ ∧ ¬( ) ( )

S1

I1

I2

I3

S0

I0

O

2-to-4 linedecoder

Page 60: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

In the cir cuit of Fig ure 3-26 there are four in put lines. The bi nary value in the twoS lines de ter mines which one of the four lines is cop ied to the multi plexer out put(la beled O). The 2-to-4 line de coder con verts this value into one of four se lec torlines, which will be in one of these four states:

LLLL LLHL LHLL HLLL

Sim i larly, an eight-in put multi plexer has eight data in puts and three bi nary se lec -tion in puts, which are con verted into one-of-eight se lec tion lines by the de coder,while a six teen-in put multi plexer re quires four bi nary dig its in the de coder in put,which are con verted into one-of-six teen se lec tion lines. Al ter na tively, the de codercir cuit can be sim pli fied us ing mul ti ple AND gates and ne gat ing the in put signals, asshown in Figure 3-27.

Fig ure 3-27 Multi plexer with Mul ti ple AND Gates.

In the multi plexer in Fig ure 3-27, one could as sume that the in put bits are bothlow, that is, S1 = 0 and S2 = 0. In this case the first-level NOR gates would change theL sig nals to H. The two high sig nals will go into the first mul ti ple AND gate, asshown by the solid lines in the il lus tra tion. This will de ter mine that the first in putline (I0) will be cop ied to the cir cuit out put. In fact, the four in vert ers at the top ofthe il lus tra tion will per form the func tion of the two-to-four de coder in the cir cuit ofFig ure 3-26.

3.6.2. Demultiplexers

A demultiplexer takes one data in put and a num ber of se lec tion in puts, and re turnsmul ti ple out puts. While the multi plexer per forms a many-into-one op er a tion, thedemultiplexer per forms a one-into-many. For ex am ple, a four-out put demultiplexerhas one data in put line, two se lec tion in puts, and four data out put lines. Fig ure 3-28shows such a cir cuit.

Logic Gates and Cir cuit Com po nents 39

I0

I1

I2

I3

O

S1 S0

Page 61: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 3-28 Two-Bit into Four-of-One Demultiplexer.

A demultiplexer can be made to act as a de coder by hold ing the in put line high.For ex am ple, the cir cuit in Fig ure 3-28 per forms as a bi nary one-to-four-line de coder if the I line is held high. In this case, the bi nary bit pat terns on the two in put linesare con verted into a sin gle out put in one of the four out put lines. Thus, if there were four de vices, each one con nected to one of the out put lines, the demultiplexer cir -cuit would se lect which one is en abled ac cord ing to the bi nary value of the input.

3.6.3 Multi plexer and Demultiplexer ICsSev eral ICs are avail able that per form multiplexing and demultiplexing op er a tions.For ex am ple, the 74138 is a three-line to eight-line de coder and demultiplexer. Withthis IC any of eight in puts can be se lected by plac ing the cor re spond ing 3-bit num beron the de vice’s three ad dress lines. The 74151 is a 1-of-8 data se lec tor/multi plexer.This de vice routes data from eight sources to a sin gle out put line. Here again, a 3-bitse lec tor is used to de ter mine which of the eight in puts is routed to the out put.

An im por tant use of the multi plexer is to en code row and col umn ad dresses ontothe ad dress lines of dy namic RAM, al though more of ten tristate buff ers such as the74541 are used for this. An other im por tant use of multiplexers is in im ple ment ingdual-port mem o ries for video dis plays.

40 Chap ter 3

O0I

O1

O2

O3

S1 S0

Page 62: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Chap ter 4

In put and Out put De vices

4.1 Ob tain ing In put

Elec tronic de vices, in clud ing com put ers and microcontrollers, must of ten re ceive the data and com mands re quired for their op er a tion. In com puter tech nol ogy a com monin put de vice is the key board, which al lows for en ter ing text data as well as key strokeor ders. Al ter nate com puter in put de vices are the mouse, trackballs, light pens, graph i -cal tab lets, scan ners of sev eral de signs, speech rec og ni tion de vices, op ti cal char ac terrec og ni tion hard ware and soft ware, and many oth ers. Al though these de vices are notex cluded from use in microcontroller-based sys tems, a more typ i cal case is thatmicrocontroller in put de vices are much sim pler and lim ited. In this chap ter we dis -cuss the two most com monly used de vices for microcontrollers: the switch and thekey pad. How ever, ded i cated sys tems of ten use spe cial in put de vices; for ex am ple, ara dio re ceiver could be the in put de vice for a ra dio-con trolled sys tem.

4.2 Switches

The elec tri cal switch is a de vice for chang ing cur rent flow in a cir cuit. Al though me -chan i cal switches find use in fields such as rail roads and fluid flow con trol, here we re -fer to switches used in con trol ling elec tri cal power or elec tronic tele com mu ni ca tions. In ab stract terms, the switch is some times re ferred to as a gate, in the same sense asthe logic gates dis cussed in Chap ter 3. The sim plest elec tri cal switch has two com po -nents, called con tacts, that touch to make the cir cuit and sep a rate to break the cir -cuit. The terms “make” and “break” are com monly used in this con text. The se lec tionof ma te rial for the con tacts is im por tant be cause cor ro sion can form an in su lat inglayer that pre vents the switch from per form ing its func tion. One pos si ble so lu tion isplat ing the con tacts with no ble met als, such as gold or sil ver.

In a switch the ac tu a tor is the part that ap plies the op er at ing force to the con -tacts. Com mon switch types are rocker, tog gle, pushbutton, DIP, ro tary, tac tile,slide, keylock, snap-ac tion, thumbwheel, and sev eral oth ers. Fig ure 4-1 shows sev -eral switches com monly found in microcontroller cir cuit boards.

41

Page 63: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 4-1 Com mon Elec tri cal Switches.

The switch con tacts are said to be “closed” when there is no space be tween them, thus al low ing elec tric ity to flow. When the con tacts are sep a rated by a space, theyare said to be “open.” In this case no elec tric ity flows through the switch. Switchesare clas si fied ac cord ing to the var i ous con tact ar range ments. In the nor mally-openswitch, the con tacts are sep a rated un til some force causes them to close. In the nor -mally-closed switch, the con tacts are held to gether un til some force sep a rates them. Some switches can be se lected to op er ate as ei ther nor mally open or nor mallyclosed. The term “pole” is used in ref er ence to a sin gle set of con tacts on a switch.While the term “throw” re fers to the one or more po si tions that a switch can adopt.Fig ure 4-2 shows some com mon switch de signs and their elec tri cal sym bols.

Fig ure 4-2 Switch Sym bols and Types.

42 Chap ter 4

Page 64: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

A multi-throw switch can have two pos si ble tran sient be hav iors as it tran sitsfrom one po si tion to the other one. One pos si bil ity is that the new con tact is madebe fore the old one is bro ken. This make-be fore-break ac tion en sures that the line isnever an open cir cuit. Al ter na tively, there is a break-be fore-make ac tion, where theold con tact is bro ken be fore the new one is made. This mode of switch op er a tionsen sures that the two fixed con tacts are never shorted. Both de signs are in com monuse.

A bi ased switch is one in which the ac tu a tor is au to mat i cally re turned to a cer -tain po si tion, usu ally by the ac tion of a spring. A pushbutton switch is a type ofbiased switch, of which the most com mon type is a push-to-make switch. In thiscase the con tact is made when the but ton is pressed and breaks when it is re leased.A push-to-break switch, on the other hand, breaks con tact when the but ton ispressed. Many other spe cial-func tion switches are avail able, for ex am ple, tiltswitches, such as the mer cury switch, in which con tact is made by a blob of mer -cury float ing in side a glass bulb as the switch is tilted. Other spe cial ized switchesare ac ti vated by vi bra tion, pres sure, fluid level (as in the float switch), lin ear or ro -tary move ment, the turn ing of a key, a ra dio sig nal, or a mag netic field.

4.2.1 Switch Con tact Bounce

Switch con tact bounce is a com mon prob lem of elec tri cal switches. Switch con tactsare metal sur faces that are forced into con tact by an ac tu a tor. Due to mo men tum andelas tic ity, the strik ing ac tion of the con tacts causes a rap idly pul sat ing elec tri cal cur -rent in stead of a clean tran si tion from zero to full cur rent. Par a sitic in duc tance and ca -pac i tance in the cir cuit can fur ther mod ify the wave form, re sult ing in a se ries ofsi nu soi dal os cil la tions.

Switch con tact bounce some times causes prob lems in cir cuits that are not de -signed to cope with os cil lat ing volt ages, par tic u larly in se quen tial dig i tal logic cir -cuits. Sev eral meth ods of switch debouncing have been de vel oped. These can bedi vided into tim ing-based schemes and hys ter esis-based schemes. Tim ing-basedtech niques op er ate by add ing suf fi cient de lay be fore read ing the switch so as to pre -vent the bounce from be ing de tected. The main ad van tage of us ing tim ing to con trolbounc ing is that it does not re quire any spe cial switch de sign. Al ter na tively, it ispos si ble to use hys ter esis to sep a rate the po si tions where the make and break ac -tions are de tected. Hys ter esis re fers to sys tems in which the out put de pends notonly on the in put, but also on the sys tem’s in ter nal state.

The ac tual hard ware cir cuits used in hys ter esis-based switch debouncing be longto three com mon types: RS flip-flops, CMOS gate debouncers, and in te grated RC cir -cuit debouncers. The debouncing ac tion of the RS flip-flop is ob vi ous from its op er -a tion: that is, when the key is in a po si tion in which nei ther con tact is touched (keybounc ing), the in puts are pulled low by the pull-down re sis tors. In this case, the keywill ap pear as be ing pressed.

In put and Out put De vices 43

Page 65: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Al ter na tively, switch debouncing can be ac com plished by means of a CMOSbuffer cir cuit with high in put im ped ance. One such cir cuit is the 4050 hex buffer IC,which has eight in put and eight out put gates. When the switch is pressed, the in putline of the 4050 chip is grounded, and out put is forced low. The out put volt age isalso kept low when the switch is bounc ing by means of the in ter nal re sis tor. The ef -fect is that the switch ac tion is debounced.

Fi nally, switch debouncing can also be im ple mented by means of a sim ple re sis -tor-ca pac i tor cir cuit. The cir cuit ac tion is based on the rate at which the ca pac i torre charges once the ground con nec tion is bro ken by the switch. As long as the ca pac -i tor volt age is be low the thresh old level of the logic zero value, the out put sig nal will con tinue to appear as logic zero.

4.2.2 KeypadsIn the world of microcontroller-based cir cuits, a key pad (also called a nu meric key -pad) is a set of pushbutton switches some times la beled with dig its, math e mat i calsym bols, or let ters of the al pha bet. In this sense, a cal cu la tor key pad con tains the dec -i mal (or oc ca sion ally hex a dec i mal) dig its, the dec i mal point, as well as keys for themath e mat i cal fea tures of the cal cu la tor. Al though in the ory the com puter key board isa key pad, the key pad is usu ally a smaller ar range ment of but tons, or re fers to a part orarea of a com puter key board.

By con ven tion, the keys on cal cu la tor-style keypads and keypads on com puterkey boards are ar ranged such that the keys 123 are on the bot tom row. On the otherhand, tele phone keypads have the 123 keys on the top row, as shown in Fig ure 4-3.

Fig ure 4-3 A 16-Key Tele phone-Style Key pad.

44 Chap ter 4

1

4

7

*

2

5

8

0

3

6

9

#

A

B

C

D

Page 66: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Keypads are usu ally im ple mented as pushbutton switches lo cated in a row andcol umn ma trix. For ex am ple, the lo ca tion of any key on the key pad in Fig ure 4-3can be based on two co or di nates: the row and col umn po si tion for that key. This de -ter mines that in pro cess ing key pad data only eight out puts are re quired: four to de -fine the row and four to de fine the col umn.

De ter min ing which switch on a key pad has been ac ti vated can be done ei ther bypoll ing or by an In ter rupt-Driven rou tine. In the poll ing ap proach, the con trol lerchecks the sta tus of each switch in a loop. In the In ter rupt-Driven rou tine, the ac -tion on a key no ti fies the pro ces sor of a key stroke and a ded i cated rou tine pro ceeds to ex e cute the re quired ac tion. Keypads, like the switches they in cor po rate, re quiredebouncing. The three meth ods of switch debouncing de scribed pre vi ously ap ply to keypads.

4.3 Out put De vices

Elec tronic de vices, in clud ing com put ers and em bed ded sys tems, must of ten pro videdata out put in a hu manly read able form. Here again, com puter tech nol ogy uses manydif fer ent types of out put de vices, in clud ing video dis plays, print ers, plot ters, film re -cord ers, pro jec tors, sound sys tems, and even ho lo graphic de vices. Al though theseout put de vices can not be ex cluded from use in some em bed ded sys tems, a more typ i -cal case is that they of ten make do with much sim pler and lim ited out put means. In this sec tion we dis cuss two com mon out put de vices used in em bed ded sys tems: theSeven-Seg ment LED and the liq uid crys tal dis play. Also note that sim ple de vices,such as LEDs and buzz ers, are some times used as out put de vices. Be cause LEDs werecov ered in Chap ter 2 we de not in clude them in this dis cus sion. Buzz ers are such sim -ple com po nents that their op er a tion does not re quire a de tailed ex pla na tion.

4.3.1 Seven-Segment LED

Dig i tal de vices of ten need to out put a nu meric value. Al though in di vid ual LEDs can becom bined to rep re sent bi nary, dec i mal, or hex a dec i mal dig its, a far more con ve nientde vice is one con sist ing of seven built-in LEDs that can be turned on or off to rep re sent all ten dec i mal dig its and even the six let ters of the hex char ac ter set. Such a cir cuit isfur nished in a sin gle IC called a Seven-Seg ment LED, com mon in clocks, watches, cal -cu la tors, and house hold ap pli ances.

The clas sic scheme of a Seven-Seg ment dis play con sists of plac ing lighted bars in a fig ure-eight pat tern. By se lect ing which bars are lighted, all the dig its and somelet ters of the al pha bet can be rep re sented. In ad di tion, Seven-Seg ment LEDs areusu ally ca pa ble of dis play ing one or two dec i mal points. Fig ure 4-4 shows the lay -out of a Seven-Seg ment LED and the com bi na tions to gen er ate the decimal and hexdigit sets.

Note, in Fig ure 4-4, that two of the let ters (b and d) of the hex a dec i mal set aredis played in low er case while the oth ers are in up per case. This is a lim i ta tion of theSeven-Seg ment LED be cause an up per case let ter “D” would match the one pat ternfor the digit “0,” and an up per case let ter “B” would match the digit “8.”

In put and Out put De vices 45

Page 67: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 4-4 Lay out and Digit Pat terns in a Seven-Seg ment LED.

Some Seven-Seg ment LED dis plays are slanted to make the dig its ap pear in ital -ics. One rea son for the scheme is used in clock dis plays where the two dig its are in -verted so that the dec i mal points ap pear like a co lon be tween the dig its. In ad di tion, Seven-Seg ment dis plays are pack aged in sev eral dif fer ent ways. Some times sev eraldig its are com bined in a sin gle IC. An other vari a tion is in the form of a 14-pin DIP.

Seven-Seg ment dis plays are also fur nished us ing dis play tech nol o gies other thanLEDs. Many line-pow ered de vices and home ap pli ances, such as clocks and mi cro -wave ov ens, use flu o res cent Seven-Seg ment dis plays. Bat tery-pow ered de vices,such as watches and min ia ture dig i tal in stru ments, use Seven-Seg ment liq uid crys tal dis plays. Liq uid crys tal tech nol o gies are covered in sec tions that follow.

The LEDs in a Seven-Seg ment dis play are in ter con nected. The two in ter con nec -tion modes are to wire to gether the cath odes of all in di vid ual LEDs. An other modeis to wire to gether the an odes. In one case the de vice is said to have a com -mon-cath ode and in the other one a com mon-an ode. This scheme sim pli fies the cir -cuit and re duces the num ber of con nec tions, as only one line is nec es sary forcon trol ling each LED. There is no in trin sic ad van tage to ei ther sys tem be cause each one is suited to dif fer ent ap pli ca tions. Fig ure 4-5 shows the pin di a gram for a com -mon-cath ode Seven-Seg ment LED in a DIP pack age.

46 Chap ter 4

a

b

c

a-b-c-d-e-f a-b-c

a-b-c-g-f-e f-g-e-c-d a-f-e-d b-c-d-e-g a-f-g-e-d a-f-g-ea-b-c-f-ga-b-c-d-e-f-g

a-b a-b-g-e-d a-b-g-c-d f-g-b-c a-f-g-c-d a-f-g-e-c-d

e

d

f

g

Page 68: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 4-5 Pin Di a gram for a Com mon Cath ode Seven-Seg ment LED

4.3.2 Liq uid Crys tal Dis playsA liq uid crys tal dis play (LCD) is a pixilated out put de vice ca pa ble of dis play ing ASCIIchar ac ters and dot-based graphics. LCDs can be color or mono chrome ac cord ing totheir con struc tion. One of the ad van tages of LCD dis plays is their very small con sump -tion of elec tric power, which makes them suit able for bat tery-pow ered em bed ded sys -tems.

In op er a tion the liq uid crys tal dis play con sists of two pieces of po lar ized glasswith per pen dic u lar axes of po lar ity. Sandwiched be tween the polarizers is a layer of ne matic crys tals, as shown sche mat i cally in Figure 4-6.

Fig ure 4-6 Sche matic Rep re sen ta tion of an LCD Dis play.

In put and Out put De vices 47

1Anode F

Anode G

Anode E

Anode D

Anode A

Anode B

Anode C

Anode DP

Common cathode

Common cathode

14

2 13

4

12

6 9

7 8

Light

Light

Polarizers

Polarizers

Liquidcrystal

Page 69: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

In the top im age of Fig ure 4-6, light can not pass through the sys tem be cause theliq uid crys tal layer pre serves the orig i nal an gle of vi bra tion of the light. In the lowerim age, the var i ous mol e cule lay ers of the liq uid crys tal are twisted ap prox i mately 90 de grees. This twist ing of the liq uid crys tal also changes the light’s pane of vi bra tion.So when light reaches the sec ond po lar ized fil ter, it vi brates at the same an gle as the fi nal lay ers of mol e cules of the liq uid crys tal and can pass through the po lar izer.Note that the elec tri cal cur rent ap plied to the crys tals has the ef fect of straight en ing the var i ous mol e cule lay ers. When the cur rent is re leased, the var i ous mol e cule lay -ers re sume their twisted form. By vary ing the amount of twist in the liq uid crys talsthe amount of light that passes through can be controlled.

4.3.3 LCD Tech nol o giesDe pend ing on the po si tion ing of the light source, an LCD can be ei ther transmissiveor re flec tive. A transmissive LCD is il lu mi nated from the back and viewed from thefront. This type is com mon in ap pli ca tions that re quire high lev els of il lu mi na tion, as is the case with com puter dis plays and tele vi sion sets. Re flec tive LCDs, on the otherhand, are il lu mi nated by an ex ter nal source. This type finds use in dig i tal watches andcal cu la tors. Re flec tive tech nol ogy pro duces a darker black color than thetransmissive type, as light is forced to pass twice through the liq uid crys tal layer. Be -cause re flec tive LCDs do not re quire a light source they con sume less power than thetransmissive ones. A third type, called transflective LCDs, works ei ther as atransmissive or a re flec tive LCD, de pend ing on the am bi ent light.

LCDs can be color or mono chrome. In color sys tems each in di vid ual pixel con -sists of three cells, which are col ored red, green, and blue. These cells, some timescalled subpixels, are con trolled in de pend ently to yield thou sands (or even mil lions) of pos si ble col ors for screen dots. Most LCDs used in em bed ded sys tems are mono -chrome.

Ac cord ing to dis play tech nol ogy, LCDs can be di vided into al pha nu meric ordot-ad dress able. The al pha nu meric type, most fre quently used in em bed ded ap pli -ca tions, use a ma trix com posed of lin ear el e ments. Fig ure 4-7 shows sev eral pos si -ble elec trode con fig u ra tions of LCDs.

Fig ure 4-7 Elec trode Con fig u ra tions in LCD Dis plays.

48 Chap ter 4

7 segments 16 segments 5 x 7 matrix

Page 70: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

The first two elec trode con fig u ra tions in Fig ure 4-7 are based on lin ear seg mentssim i lar to the ones in Seven-Seg ment LEDs. Seg mented elec trodes are suit able forsim ple al pha nu meric dis plays, as is of ten re quired in small dig i tal de vices such aswatches or cal cu la tors. To dis play en tire char ac ter sets, or graphics, a dot-ad dress -able ma trix ar range ment of elec trodes is nec es sary. This setup is shown in therightmost im age in Fig ure 4-7. How ever, such power co mes at a price, as the moread dress able el e ments in the dis play, the greater the num ber of con nec tions and themore com plex the driver logic re quired to op er ate the sys tem. Note that the 5 x 7ma trix dis play in Fig ure 4-7 ac tu ally con tains eight dot rows. The rea son is that thelow est row is used for dis play ing the cur sor. Most pop u lar LCD displays forembedded systems use the 5 x 7 matrix format.

One way of re duc ing the num ber of elec tri cal con nec tions in an LCD is by amethod called a pas sive ma trix dis play. Here the pix els to be lighted are de ter -mined by the cross ing points be tween the row and the col umn se lec tor elec trodes.For ex am ple, in the 5 x 7 ma trix dis play in Fig ure 4-7, the pixel at the cen ter of thechar ac ter is se lected by pick ing row num ber 4 and col umn num ber 3. The name pas -sive ma trix orig i nates in the fact that each pixel must re tain its state be tween re -fresh cy cles. As the num ber of pix els to be re freshed in creases, so does the timere quired for the re fresh cy cle. As a con se quence of their de sign, pas sive ma trix dis -plays usu ally have slow re sponse times and poor con trast.

In high-res o lu tion and color LCDs, an ac tive ma trix is used. In this de sign, a gridof thin-film tran sis tors is added to the po lar iz ing and color fil ters. Each pixel con -tains its own ded i cated tran sis tor, and each row line and col umn line is ad dressedin di vid u ally. Dur ing the re fresh cy cle, each pixel row is ac ti vated se quen tially. Ac -tive ma trix dis plays are brighter and sharper and have quicker re sponse times thana pas sive ma trix. Ac tive ma trix dis plays are also known as thin-film-tran sis tor orTFT dis plays.

In put and Out put De vices 49

Page 71: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

This page intentionally left blankThis page intentionally left blank

Page 72: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Chap ter 5

From Cir cuit Sche mat ics to PCB

5.1 Cir cuit Di a gramCir cuits are of ten rep re sented in a sim pli fied man ner by means of a cir cuit di a gram,also called an elec tronic sche matic. One pos si ble ap proach is a pic to rial rep re sen ta -tion of the cir cuit com po nents to a given de gree of re al ism. Fig ure 2-3, in Chap ter 2, isan ex am ple of a pic to rial, or quasi-pic to rial, cir cuit rep re sen ta tion. Pic to rial cir cuitrep re sen ta tions have some ap pli ca tion in tu to ri als and ed u ca tion but are not very use -ful to the cir cuit de signer. Block di a grams are an other sim pli fi ca tion in which com po -nents are ab stracted into a box that may show some con nec tions but is lack ing mostelec tronic de tails. Fig ure 5-1 com pares the pic to rial and sche matic draw ings of thesame cir cuit.

Fig ure 5-1 Pic to rial and Sche matic Draw ings of an Elec tri cal Cir cuit. (Im age from Wikimedia Com mons)

51

Page 73: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

The sche matic di a gram de picts the cir cuit us ing sim pli fied, stan dard sym bolsthat show com po nents as well as con nec tions for power and sig nals. The sche maticcir cuit di a gram is the en gi neer’s and cir cuit de signer’s ba sic tool. Un like the blockdi a gram, the cir cuit sche mat ics show the ac tual con nec tions be tween com po nents,how ever, the phys i cal ar range ment of the in di vid ual com po nents need not matchthe ac tual board. This gives the cir cuit de signer the free dom of lo cat ing com po nents in their log i cal po si tions in the di a gram, rather than hav ing to abide by the physicalconstraints of the actual board.

5.1.1 Sym bolsThe ac tual sym bols used in elec tronic sche mat ics have changed over the years andsome have be come ob so lete as the com po nents they rep re sented are no lon ger used;for ex am ple, these days the sym bols for vac uum tubes have mostly a his tor i cal in ter -est. In the United States, IEEE Stan dard 315-1975 pro vides graphics sym bols and class des ig na tion let ters for elec tri cal and elec tronic com po nents used in di a grams anddraw ings. In Brit ain, the cor re spond ing stan dard is des ig nated as IEC 60617. The In -ter na tional Electrotechnical Com mis sion has also ap proved a stan dard for graph i calsym bols that is des ig nated as IEC 60617. This da ta base cur rently in cludes 1,750 dif fer -ent sym bols. Fig ure 5-2 shows some com mon sym bols in the US stan dard. More com -plete lists can be ob tained on line.

Fig ure 5-2 Elec tronic Sym bols in the United States Stan dard. (Im age from Wikimedia Com mons)

52 Chap ter 5

Page 74: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Cir cuit de sign soft ware and in di vid ual com pa nies of ten in tro duce ex ten sions and vari a tions to the stan dard sym bol set. In any case, in tro duc ing ma jor changes to thestan dard sym bols is al most certainly a bad idea.

5.1.2 Tools for Elec tronic Cir cuit De signNot long ago, in te grated cir cuits and em bed ded sys tem boards were de signed by handand laid out man u ally. In the 1970s and 1980s, some cir cuit de sign ers started us ingphotoplotters and geo met ric soft ware to fa cil i tate the pro cess but still most of thepro cess was done man u ally. In the late 1970s, the first place ment and rout ing tools forcir cuit de sign were de vel oped. The com po si tion and fab ri ca tion of com plex VLSI sys -tems fur nished the in cen tive for au to mat ing and sim u lat ing sys tem de sign. The ap -proach still in use to day is to de velop tex tual pro gram ming lan guages that re ceive asin put the de sired be hav ior and gen er ate a de tailed phys i cal de sign of the IC. Some ofthe best-known tools for elec tronic de sign au to ma tion were UNIX util i ties de vel opedat the Uni ver sity of Cal i for nia, Berke ley.

Along these same lines, a con sor tium of uni ver si ties and cir cuit fab ri ca tors de vel -oped the Metal Ox ide Semi con duc tor Im ple men ta tion Ser vice, (or MOSIS.) Thesys tem was used to train stu dents by pro duc ing real, in te grated cir cuits that werelow-cost, re li able, and based on rel a tively sim ple tech nol o gies. In the early 1980s,elec tronic de sign tools ceased to be de vel oped in ter nally by the cir cuit de vel op ment com pa nies and be came a sep a rate busi ness and tech nol ogy. The term EDA, for Elec -tronic De sign Au to ma tion, was coined at this time and the first de sign au to ma tioncon fer ence took place in 1984. Sev eral spe cial ized pro gram ming lan guages were de -vel oped dur ing this pe riod for the hard ware de sign and de scrip tion of elec tronic cir -cuits. Verilog, de vel oped by a pri vate en ter prise, and VHDL, by the US De part mentof De fense, are among the best known. Sim u la tors based on these lan guages alsobe came avail able.

To day the most so phis ti cated and ad vanced cir cuit de sign tools are used in thefield of in te grated cir cuits, which are out side the scope of this book. In this con text we are in ter ested in tools used in the de sign, lay out, and fab ri ca tion of cir cuitboards with nonminiaturized com po nents.

5.2 Cir cuit Board De signThe sche mat ics for an elec tronic cir cuit can be de signed with a pen cil and eraser on apa per nap kin; many cir cuits have started in this man ner. Com put ers can help in this ef -fort through spe cial ized soft ware and gen eral-pur pose draw ing pro grams. Com puterAs sisted De sign (CAD) pack ages, such as Autocad, are pow er ful draw ing tools andusu ally pro vide ded i cated files and at tach ments for cir cuit de sign. Spe cial ized cir cuitde sign pro grams are also avail able, some as freeware, oth ers are fur nished by printedcir cuit board man u fac turers, and still oth ers are com mer cial prod ucts in tended foren gi neers and de sign spe cial ists.

Each cat e gory of cir cuit de sign pro gram has its ad van tages and draw backs. Forex am ple, com mer cial tech ni cal draw ing pro grams, such as Autocad, are pow er fuland well-tested tools, and many pro fes sional de sign ers rely on them. How ever,these pro grams are ex pen sive and come with a steep learn ing curve. If one al ready

From Cir cuit Sche mat ics to PCB 53

Page 75: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

has and uses a com mer cial tech ni cal pack age, then adopt ing this pack age for cir cuit de sign is a prac ti cal op tion. How ever, pur chas ing and learn ing one of these pro -grams to use it ex clu sively in circuit design seems less attractive.

There are a num ber of free cir cuit de sign pro grams avail able on line. A ded i catedweb site at http://www.opencircuit.com serves as a re pos i tory for many of thesefreeware pro grams. Some of these pro grams (such as Magic) are VLSI lay out toolsof lit tle use to the em bed ded systems de vel oper. Other pro grams, such as XCircuit,are suit able for gen eral-pur pose cir cuit de sign. Some com mer cial pro grams have free demo ver sions. An elec tronic cir cuit sim u la tion pro gram that has be come aclas sic in the field is named SPICE. Its ini tial re lease in 1973 was writ ten in For tranbut current ver sions are in C. How ever SPICE is more a cir cuit sim u la tor than a de -sign tool and is mostly suited for use in the de vel op ment of in te grated cir cuits.

An other type of board de sign pro gram are those fur nished by board man u fac tur -ing firms. These pro grams are usu ally com pat i ble with the spe cific man u fac tur ingtech nol ogy of the com pany that fur nishes them. In most cases the sche matic de signap pli ca tion serves as a front end to a board lay out ap pli ca tion that gen er ates the ac -tual board draw ings. One set of such pro grams is the Ex press PCB and Ex press SCH pack age. Ex press SCH is the cir cuit de sign com po nent and Ex press PCB is theboard lay out pro gram. These pro grams are avail able for free down load athttp://www.expresspcb.com. Other sim i lar pro grams can be found on the Internetwebsites of the board man u fac tur ers.

5.2.1 Board De sign Stan dards

Sev eral in dus try stan dards re late to the de sign of printed cir cuit boards. The As so ci a -tion Con nect ing Elec tron ics In dus tries is an or ga ni za tion de voted to stan dard iz ingthe as sem bly and pro duc tion of elec tronic equip ment and as sem blies. It was foundedin 1957 as the In sti tute for Printed Cir cuits (hence IPC) and later named the In sti tutefor In ter con nect ing and Pack ag ing Elec tronic Cir cuits. In 1999, the name was fi nallychanged to its pres ent form (As so ci a tion Con nect ing Elec tron ics In dus tries) but theIPC mon i ker was kept. The IPC pub lishes the most widely ac cepted stan dards for theelec tronic in dus tries. There is an IPC stan dard for ev ery as pect of PCB de sign, man u -fac ture, and test ing. The ma jor doc u ment that cov ers PCB de sign is IPC-2221, “Ge -neric Stan dard on Printed Board De sign.”

5.2.2 Gerber File For mat

The Gerber file for mat is a PCB file con ven tion used by the elec tron ics in dus tries. Thefor mat in cludes cop per lay ers, con nec tions, sol der masks, and leg ends. Al thoughmill ing and drill ing data can be pres ent in the Gerber file, it is more com mon to pro vide this in for ma tion in the Excellon For mat. The Gerber for mat is the de-facto stan dardfor the spec i fi ca tion and trans fer of PCB data. The cur rent ver sion of the for mat isRS-274X, also known as Ex tended Gerber or X-Gerber. An RS-274X file is a hu manlyread able ASCII file that con tains com mands and co or di nates. The fol low ing is an ex -am ple (from Wikimedia Com mons) of a file in Gerber RS-274X for mat.

54 Chap ter 5

Page 76: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

G04 Film Name: paste_top*G04 Or i gin Date: Thu Sep 20 15:54:22 2007*G04 Layer: PIN/PASTEMASK_TOP*%FSLAX55Y55*MOIN*%%IR0*IPPOS*OFA0.00000B0.00000*MIA0B0*SFA1.00000B1.00000*%%ADD28R,.11X.043*%%ADD39O,.07X.022*%...%AMMACRO19*21,1,.0512,.0512,0.0,0.0,45.*%%ADD19MACRO19*%%LPD*%G75*G54D10*X176250Y117500D03*Y130000D03*Y163750D03*...G54D39*X496250Y142500D03*Y137500D03*Y132500D03*Y127500D03*M02*

Gerber files are typ i cally gen er ated by cir cuit de vel op ment soft ware prod ucts ofthe EDA or CAD types dis cussed pre vi ously. The Gerber file can be fed into a PCBfab ri ca tor that is equipped to pro cess the im age and com po nent data by means ofCom puter-As sisted Man u fac tur ing (CAM).

5.3 De vel op ing the Cir cuit Pro to typeThe im ple men ta tion and de vel op ment of most elec tronic cir cuits fol lows sev eralstages in which the prod uct pro gresses through in creas ingly re fined phases. This pro -gres sion en sures that the fi nal prod uct meets all the de sign re quire ments and per -forms as ex pected. The de signer or the en gi neer can not be too care ful in avoid ingman u fac tur ing er rors that later force the scrap ping of mul ti ple com po nents or, atbest, force costly or un sightly cir cuit re pairs. A com mon norm fol lowed by elec tronicfirms is not to pro ceed to fab ri ca tion un til a fin ished and un mod i fied pro to type hasbeen exhaustively tested and eval u ated. Even the text and la bels on the cir cuit boardshould be checked for spell ing er rors and to make sure that the fi nal place ment ofhard ware com po nents will not hide some im por tant in for ma tion printed on the board.

The meth od ol ogy that uses a cy clic pro cess of prototyping, test ing, an a lyz ing,and re fin ing a prod uct is known as it er a tive de sign. The prac ti cal ity of it er a tive de -sign re sults from the fact that changes to a prod uct are eas ier and less ex pen sive toim ple ment dur ing the early stages of the de vel op ment cy cle. The it er a tive de signmodel, also called the spi ral model, can be de scribed by the fol low ing steps:

1. The cir cuit is de signed on pa per, usu ally with the sup port of soft ware as pre vi ouslyde scribed.

2. The pa per cir cuit is checked and eval u ated by ex perts other than the de signer orde sign ers.

From Cir cuit Sche mat ics to PCB 55

Page 77: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

3. A prim i tive hard ware pro to type is de vel oped and tested. Breadboarding andwire-wrap ping are the most com mon tech nol o gies used for this first-level pro to -type.

4. The breadboarded or wire-wrapped pro to type is tested and eval u ated. If changesto de sign are re quired, the de vel op ment pro cess re starts at Step 1.

5. A sec ond-level pro to type is de vel oped, usu ally by means of printed cir cuit boards.This PCB pro to type is eval u ated and tested. If ma jor mod i fi ca tions are re quired,the de vel op ment pro cess is re started at Step 1.

6. A fi nal, third-level, pro to type is de vel oped us ing the same tech nol ogy and num berof sig nal lay ers as will be used in the fi nal prod uct. If mod i fi ca tions and changes are de tected dur ing fi nal test ing, the de vel op ment pro cess is re started at Steps 1, 3, or5 ac cord ing to the na ture of the de fect to be rem e died.

7. If the fi nal pro to type passes all tests and eval u a tions, a short pro duc tion run is or -dered. This short run al lows find ing prob lems in the man u fac tur ing stage that cansome times be rem e died by mak ing mod i fi ca tions to the orig i nal de sign or bychang ing the se lected com po nent or com po nents.

The pre ced ing steps as sume a very con ven tional cir cuit, and a sim ple and lim itedde vel op ment pro cess. The mass pro duc tion of elec tronic com po nents has to con -sider many other factors.

5.3.1 Bread board

One of the most use ful tools in de vel op ing a cir cuit pro to type is a bread board. Thename orig i nated in the early days of ra dio am a teurs who would use a wooden board(some times an ac tual bread board) with in serted nails or thumb tacks to test the wir -ing and com po nents of an ex per i men tal cir cuit. The mod ern bread board is usu allycalled a solderless bread board be cause com po nents and wires can be con nected toeach other with out sol der ing them. The term “plugboard” is also oc ca sion ally used.

The main com po nent of a mod ern solderless bread board is a plas tic block withper fo ra tions that con tact in ter nal, tin-plated spring clips. These clips pro vide thecon tact points. The spac ing be tween holes is usu ally 0.1", which is the stan dardspac ing for pins in many nonminiaturized elec tronic com po nents and in ICs in dualinline (DIP) pack ages. Ca pac i tors, switches, re sis tors, and inductors can be in -serted in the board by cut ting or bend ing their con tact wires. Most boards are ratedfor 1 amp at 5 volts. Fig ure 5-3 shows a pop u lated bread board for a mo tor drivercircuit developed later in this book.

Solderless bread boards come in dif fer ent sizes and de signs. The one in Fig ure 5-3 has the plas tic in ter con nec tion com po nent mounted on a metal base and in cludesfe male ba nana plug ter mi nals suit able for pro vid ing power to the board. Sim plerboards con sist of noth ing more than a per fo rated plas tic block with the cor re -spond ing spring clips un der the per fo ra tions. These can some times serve as mod -ules that can be at tached to each other in or der to accommodate a more complexcircuit.

56 Chap ter 5

Page 78: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 5-3 A Pop u lated Bread board Cir cuit.

On the other hand, more so phis ti cated de vices, some times called dig i tal lab o ra -to ries, in clude with the bread board sev eral cir cuits for pro vid ing power in dif fer entin ten si ties as well as sig nals with the cor re spond ing ad just ers and se lec tors andswitches of sev eral types. Fig ure 5-4 shows the IDL_800 Dig i tal Lab.

Fig ure 5-4 IDL-800 Dig i tal Lab Bread board.

From Cir cuit Sche mat ics to PCB 57

HC 4050-basedUnipolar motor driver

Page 79: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Lim i ta tions of Bread boards

Al though bread boards are valu able tools in prototyping, the cir cuit de sign com mu nity is di vided re gard ing their value. One of the com mon prob lems with bread boards isfaulty con tacts. The spring-loaded clips that are de signed to pro vide con tact be tweencom po nents of ten fail. This leads the op er a tor to be lieve that there is some thingwrong with the cir cuit when it is just a faulty con tact. An other prob lem is thatwire-based con nec tors are of ten lon ger than nec es sary, which in tro duces prob lemsthat may not be re lated to the cir cuit it self. In some sen si tive cir cuits, the rout ing re -quired by the board hard ware may pro duce in ter fer ence or spu ri ous sig nals. The cir -cuit de vel oper must take all these lim i ta tions into ac count when test ing bread boardcir cuits.

An other ma jor lim i ta tion is that a solderless bread board can not ac com mo datesur face mount com po nents. Many other stan dard com po nents are not man u fac -tured to meet the 0.1" spac ing of a stan dard bread board and are also im pos si ble tocon nect. Some times the cir cuit de vel oper can build a break out adapter as a smallPCB that in cludes one or more rows of 0.1" pins. The board-in com pat i ble com po -nent can then be sol dered to the adapter and the adapter plugged into the board.The need to sol der com po nents to the adapter ne gates some of the ad van tages ofthe bread board, but with com po nents that are likely to be reused this may be aviable option.

For ex am ple, a 6P6C male tele phone plug con nec tor does not fit a stan dardbread board. In this case we can build a break out adapter such as the one shown inFig ure 5-5.

Fig ure 5-5 Tele phone Plug Bread board Adapter.

Breadboarding Tools and Tech niques

Sev eral off-the-shelf tools are avail able to fa cil i tate breadboarding and oth ers can bemade in-house. One of the most use ful ones is a set of jumper wires of dif fer ent lengths and colors. These jumper kits are usu ally fur nished in a plas tic or ga nizer. Lon ger, flex -i ble con nec tors are also avail able and come in handy when wir ing large cir cuits.

58 Chap ter 5

Page 80: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Wir ing mis takes are easy to make when breadboarding in te grated cir cuit com po -nents. In this case the op er a tor must fre quently look up the cir cuit di a gram or thecom po nent sche mat ics to de ter mine the ac tion on each IC pin. One so lu tion is touse a draw ing pro gram to pro duce a la beled draw ing of the com po nent’s pin-out.The draw ing is scaled to the same size as the com po nent and then printed on thickpa per or card board. A cut out is then glued, pref er a bly with a non per ma nent ad he -sive, to the top part of the IC so that each pin clearly shows a logo that is rem i nis -cent of its func tion. Fig ure 5-6 shows a por tion of a bread board with a la beled ICused in de vel op ing a circuit described later in this book.

Fig ure 5-6 La beled IC in a Bread board.

Note in Fig ure 5-6 that the 18F452 microcontroller is in serted in a de vice called aZIF (zero in ser tion force socket). When the ZIF socket han dle is lifted, the IC canbe eas ily re moved. ZIF sock ets are of ten used in pro to types and demo boards sothat the com po nent can be eas ily re placed or re-pro grammed.

5.3.2 Wire-Wrap ping

An other pop u lar tech nique used in the cre ation of pro to types and in di vid ual boards iswire-wrap ping. In wire-wrapped cir cuits, a square, gold-plated post is in serted in aper fo rated board. A sil ver-plated wire is then wrapped seven turns around the post,which re sults in 28 con tact points. The sil ver- and gold-plated sur faces cold weld, pro -duc ing con nec tions that are more re li able than the ones on a printed cir cuit board, es -pe cially if the board is sub ject to vi bra tions and phys i cal stress. The use of wire-wrapped boards is com mon in the de vel op ment of tele com mu ni ca tions com po nentsbut solderless bread boards have re placed wire wrap ping in con ven tional pro to typede vel op ment.

From Cir cuit Sche mat ics to PCB 59

Page 81: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

5.3.3 Perfboards Thin sheets of iso lat ing ma te rial with holes at 0.1" spac ing are also used in pro to typede vel op ment and test ing, and in cre at ing one-of-a-kind cir cuits. The holes in theperfboard con tain round or square cop per pads on ei ther one or both sides of theboard. In the perfboard each pad is elec tri cally in su lated. Boards with in ter con nectedpads are some times called stripboards. Com po nents, in clud ing ICs, sock ets, re sis -tors, ca pac i tors, con nec tors, and the like, are in serted into the perfboard holes andsol dered or wire-wrapped on the board’s back side. Fig ure 5-7 shows a cir cuit on aperfboard.

Fig ure 5-7 Cir cuit on a Perfboard.

In this sec tion we have omit ted cir cuit prototyping meth ods and tech niques thathave be come ob so lete, such as point-to-point wir ing and through-hole con struc tion.

5.4 Printed Cir cuit Boards

The meth ods and tech niques de scribed so far, in clud ing bread boards, wire-wrap ping,and perfboards, are used in de vel op ing and test ing the elec tron ics of the cir cuit it self.Once the cir cuit pro to type has been tested and eval u ated, the next step is usu ally thepro duc tion of a cir cuit board that can house the com po nents in a per ma nent man nerand thus be comes a pro to type of the fi nal prod uct. This typ i cally re quires a printedcir cuit board, or PCB, where the com po nents can be me chan i cally housed and elec tri -cally con nected. The PCB is also called a printed wir ing board (PWB) and a printedcir cuit as sem bly (PCA). Very few com mer cially made elec tronic de vices do not haveat least one PCB.

The base of a con ven tional PCB is a nonconductive lam i nate made from an ep oxy resin, with etched con duc tive cop per traces that pro vide path ways for sig nals andpower. PCBs can be pro duced eco nom i cally in large or small vol umes and even in di -vid u ally. Pro duc tion op er a tions on the PCB in clude etch ing, drill ing, rout ing, cre at -ing sol der-re sis tant lay ers, screen print ing, and in stal la tion of com po nents. All ofthese op er a tions can be au to mated in a pro duc tion set ting or done by hand by thehob by ist or when cre at ing a pro to type. PCB tech nol ogy has flour ished be cause thefi nal prod uct is in ex pen sive and re li able. Stan dards re gard ing PCB de sign, as sem -bly, and qual ity con trol are pub lished by IPC. Fig ure 5-8 shows two im ages of a PCB.

60 Chap ter 5

Page 82: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 5-8 PCB Draw ing and Pop u lated Board. (Im age from Wikimedia Com mons)

In Fig ure 5-8 the im age on the left-hand side shows the board as it ap pears in thede sign soft ware. In this ex am ple the board is dou ble sided, so there will be an otherim age for the re verse side. These im age files are used in man u fac tur ing the board.The im age on the right-hand side of Fig ure 5-8 shows the fin ished board pop u latedwith sur face-mount and through-the-hole components.

5.4.1 PCB Lay ers

The sim plest PCBs have all cop per traces and con nec tions on a sin gle layer. Mosthome-made and in-house boards are of this type, and many cir cuits can be eas ily de -signed for sin gle-layer boards. Sin gle-layer boards are easy to man u fac ture and there -fore less ex pen sive but the ma jor ity of com mer cial boards are mul ti lay ered. Thefol low ing are com mon lay ers found in com mer cial PCBs:

• Top cop per layer

• Bot tom cop per layer

• In ner cop per ground plane layer

• In ner cop per power plane layer

• Top sol der mask layer

• Bot tom sol der mask layer

• Silk screen (text) layer

The top and bot tom cop per lay ers and the silk screen layer are pres ent in mostcom mer c ia l boards. In th is case the bot tom sol der layer i s where thethrough-the-hole com po nents are sol dered. Sur face-mount com po nents are sol -dered to the top layer.

From Cir cuit Sche mat ics to PCB 61

Page 83: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

The sol der mask layer is a coat ing ap plied to the top or bot tom lay ers so as to pre -vent sol der ing ex cept on the pads fur nished for this pur pose. These masks pre ventun de sired sol der con nec tions and make sol der ing easier.

The in ner cop per lay ers are only pres ent in boards with four or more lay ers. Dur -ing board man u fac tur ing, any through-the-hole pad can be con nected to or iso latedfrom these in ner lay ers. The in ner lay ers make the boards more com pact and im -prove the noise im mu nity of the cir cuit.

5.4.2 PCB Con nec torsSev eral el e ments in PCBs serve as con nec tors be tween com po nents; these are

• Traces and planes

• Pads

• Vias

• Jump ers

Traces are etched cop per lines that con duct power and sig nals from one point inthe board to an other one. Most PCB lay out pro grams al low con trol ling the widthand style of traces. A tracer width of 0.10" is a good de fault value for traces that con -duct dig i tal and an a log sig nals. Traces that con duct power and ground sig nals areof ten much wider. In fact, ground sig nals are usu ally car ried by ground planes thatare large, po lyg o nally shapes cop per-filled ar eas. These planes are typ i cally used ascon duc tors for ground and power sig nals.

In di vid ual pads are used to pro vide a sol der sur face for a com po nent el e ment.PCB de sign pro grams pro vide stan dard pads that de fine the pad’s di am e ter, itsshape, and the hole di am e ter and tol er ance. A typ i cal pad is cir cu lar in shape, withan out side di am e ter of 0.062" and a hole of 0.029". Square pads are of ten used in pinnumber 1 of an IC component.

Vias are pads used to pass sig nals be tween lay ers. Via pads are typ i cally round.The con nec tion be tween lay ers is made dur ing man u fac tur ing ac cord ing to the in -for ma tion in the PCB draw ing.

Jump ers are con nec tors that can be opened or closed on the board. Break ing atrace and plac ing a jumper al lows the board user to cut off the sig nal to a spe cificpor tion of the cir cuit. Fig ure 5-9 is a screen snap shot of the PCB draw ing de vel opedwith the ExpressPCB ap pli ca tion avail able on line.

5.5 Mak ing Your Own PCBSev eral meth ods are avail able for mak ing printed cir cuit boards on a small scale. Thisap proach is usu ally con ve nient for the ex per i menter and pro to type de vel oper whoneeds to make a sin gle board, of ten as soon as pos si ble. Elec tronic sup ply cat a logs list con ve nient PCB-mak ing kits based on dif fer ent tech nol o gies and us ing vary ing lev elsof com plex ity. The method we de scribe in the sec tions that fol low is one of the sim -plest ones be cause it does not re quire a pho to graphic pro cess. The pro cess con sists of the fol low ing steps:

62 Chap ter 5

Page 84: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 5-9 Screen Snap shot of a PCB De sign Ap pli ca tion.

1. The cir cuit di a gram is drawn on the PC us ing a gen eral-pur pose or spe cial izeddraw ing pro gram.

2. A print out is made of the cir cuit draw ing on pho to graphic pa per us ing a stan dardla ser printer.

3. The print out is trans ferred to a sin gle-sided, cop per-clad cir cuit board blank byiron ing over the back side with a house hold clothes iron.

4. The re sult ing board is placed in an etch ing bath that eats away all the cop per, ex -cept the cir cuit im age ironed onto the board sur face.

5. The board is washed of etchant, cleaned, drilled, and the com po nents sol dered to itin the con ven tional man ner.

6. Op tion ally, an other im age can be ironed onto the back side of the board to pro videcom po nent iden ti fi ca tion, lo gos, etc.

5.5.1 Draw ing the CPB Cir cuit

Any com puter draw ing pro gram serves to draw the PCB. In the sam ples pro vided inthis chap ter we used CorelDraw but there are sev eral spe cial ized PCB draw ing pro -grams avail able on the Internet that can also be used. Fig ure 5-10 is a cir cuit boarddraw ing used for a PIC flasher cir cuit de scribed later in this book.

From Cir cuit Sche mat ics to PCB 63

Page 85: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 5-10 PIC Flasher Cir cuit Board Draw ing.

The small, cir cu lar ob jects in the draw ing are the sol der pads. Fig ure 5-11 zoomsinto the lower right-hand cor ner of Fig ure 5-10 to show the de tails of the sol derpads.

Fig ure 5-11 De tail of Cir cuit Board Pads.

Quite of ten in a PCB draw ing it is nec es sary for a trace to cross be tween twopads. In this case the two pads can be mod i fied so that the trace will not con tact ei -ther one. The mod i fied pads are shown in Fig ure 5-12.

Fig ure 5-12 Mod i fied Cir cuit Boards Pads.

64 Chap ter 5

Page 86: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

5.5.2 Print ing the PCB

The cir cuit di a gram must be printed us ing a la ser printer. Inkjet ton ers do not pro ducean im age that re sists the ac tion of the etchant. Al though in our ex per i ments we usedsev eral mod els of La ser Jet print ers, it is well doc u mented that vir tu ally any la serprinter will work. La ser copi ers have also been used suc cess fully for cre at ing the PCBcir cuit im age.

With the la ser printer method the width of the traces can be come an is sue. Thetraces in the PCB im age of Fig ures 5-11 and 5-12 are two points, which is 0.027".Traces half that width and less have been used suc cess fully with this method but asthe traces be come thin ner the en tire pro cess be comes more crit i cal. For most sim -ple cir cuits, 0.020" traces can be con sid ered a prac ti cal limit. In the pro cess of print -ing the PCB im age, one must be care ful not to touch the glossy side of the pa per orthe printed im age. Note that the pat tern is drawn as if you were look ing from thecom po nent side of the board.

5.5.3 Trans fer ring the PCB Im age

One of the most crit i cal el e ments in this method of pro duc ing PCBs is the pa per usedin print ing the cir cuit. Pin holes in some pa pers can de grade the im age to the point thatthe cir cuit lines (es pe cially if they are very thin) do not etch cor rectly. An other prob -lem re lates to re mov ing the ironed-on pa per from the board with out dam ag ing theboard sur face.

Glossy, coated inkjet printer pa per works well. Even better re sults can be ob -tained with glossy photo pa per. We use a com mon high-gloss pho to graphic pa peravail able from Sta ples and sold un der the name of “pic ture pa per”. The 30 sheets,8-by-10 size, has Sta ples num ber B031420197 1713. The UPC barcode is

7 18103 02238 5.

It has been men tioned that Hewlett-Packard toner car tridges with microfine par -ti cles work better than store-brand toner cartridges.

Trans fer ring the im age onto the board blank is done by ap ply ing heat from a com -mon clothes iron, set on the hot test set ting, onto the pa per/board sand wich. In most irons the hot test set ting is la beled “linen.” Af ter go ing over the back of the pa persev eral times with the hot iron, the pa per be comes fused to the cop per side of theblank board. The board/pa per sand wich is then al lowed to soak in wa ter for about10 min utes, af ter which the pa per can be re moved by peel ing or light scrub bing with a toothbrush.

5.5.4 Etch ing the Board

Once the pa per has been re moved and the board washed with soap and rinsed in cleanwa ter, it is time to pre pare the board for etch ing. The pre lim i nary op er a tions con sistof rub bing the cop per sur face of the board with a Scotchbrite plas tic abra sive pad andthen scrub bing the sur face with a pa per towel soaked with acetone sol vent.

From Cir cuit Sche mat ics to PCB 65

Page 87: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

The etch ing can pro ceed once the board is rubbed and clean. The etch ing so lu -tion con tains ferric chlo ride and is avail able from Ra dio Shack as a so lu tion andfrom Jameco Elec tron ics as a pow der to be mixed by the user. PCB Fer ric Chlo rideetchant should be han dled with rub ber gloves and rub ber apron be cause it stainsthe skin and uten sils. Also, con cen trated acid fumes from ferric chloride so lu tionare toxic and can cause se vere burns. These chem i cals should be han dled ac cord ing to cau tions and warn ings posted on the containers.

The ferric chloride so lu tion should be kept and used in a plas tic or glass con -tainer, never metal. Faster etch ing is ac com plished if the etch ing so lu tion is firstwarmed by plac ing the con tainer in a tub of hot wa ter. Once the board is in the so lu -tion, face up, the con tainer is rocked back and forth. It is also pos si ble to aid in cop -per re moval by rub bing the sur face with a rubber-gloved finger.

5.5.5 Fin ish ing the Board

The etched board should be washed well, first in wa ter and then in lac quer thin ner orac e tone; ei ther sol vent works. It is better to gently rub the board sur face with a pa pertowel soaked in the sol vent. Keep in mind that most sol vents are flam ma ble and ex plo -sive, and also toxic. Once the board is clean, the mount ing holes can be drilled us ingthe sol der pads as a guide. A small elec tric drill at high rev o lu tions, such as a Dremmeltool, works well for this op er a tion. The stan dard drill size for the mount ing holes is0.035". A #60 drill (0.040") also works well. Once all the holes are drilled, the com po -nents can be mounted from the back side and sol dered at the pads.

5.5.6 Back side Im age

The com po nent side (back side) of the PCB can be printed with an im age of the com po -nents or with lo gos or other text. A sin gle-sided blank board has no cop per coat ing onthe back side so the im age is just ironed on with out etch ing. Prob a bly the best time toprint the back side im age is af ter the board has been etched and drilled but be foremount ing the com po nents. Be cause the im age is to be trans ferred di rectly to theboard, it must be a mir ror im age of the de sired graphics and text. Most draw ing pro -grams con tain a mir ror ing trans for ma tion so the back side im age can be drawn us ingthe com po nent side as a guide, and then mir rored hor i zon tally be fore iron ing it on theback side of the board. Fig ure 5-13 shows the back side im age of the sam ple cir cuitboard, be fore and af ter mir ror ing.

No tice on the left-side im age in Fig ure 5-13 that a lighter copy of the cir cuit di a -gram was used to lay out the im age of the back side. Once drawn, the back side draw -ing was mir rored hor i zon tally, as shown in the right-side image.

5.6 Surface-Mount Com po nentsSur face-mount tech nol ogy (also known as SMT) is an elec tronic build ing tech nol ogyin which the com po nents are mounted di rectly onto the sur face of a board with outhav ing to drill holes. Avoid ing the holes and lead wires has led to smaller, more com -pact, and lighter com po nents that have smaller leads or no leads at all. Elec tronicman u fac tur ing in dus tries have largely re placed through-the-hole com po nents withsur face mount.

66 Chap ter 5

Page 88: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 5-13 Graphics and Text for Board Back side Im age.

Because of their size and the di men sions of their sol der pads, sur face-mountcom po nents are con sid er ably more dif fi cult to sol der by hand and to po si tion on the PCB than the through-the-hole type. This dif fi culty is of ten a fac tor when deal ingwith in di vid ual pro duc tion or short run boards that can not be con ve niently adaptedto pro duc tion-scale tech nol o gies. The pro to type maker is of ten in this sit u a tion, towhich we some times must add the com pli ca tion that many com po nents are onlyavail able in sur face-mount de signs.

5.6.1 SMT Adapt ersIn many cases it is pos si ble to pur chase or make an adapter board that al lows us ing asur face mount com po nent on a stan dard bread board or a perfboard. Fig ure 5-5 showsan adapter for a tele phone con nec tor. Sim i larly, it is pos si ble to make or pur chaseadapt ers for sur face-mount for mats.

One pop u lar adapter tech nol ogy is based on flex i ble, ad he sive pads that can beat tached to a stan dard perfboard. This adapter pro vides con nec tions be tween thesur face-mount com po nent and the 0.100" holes and the stan dard board. Fig ure 5-14shows a flex i ble com po nent adapter by the Protoflex company.

Fig ure 5-14 Protoflex SMT to Stan dard Adapter.

From Cir cuit Sche mat ics to PCB 67

16F84

R1L1

L2

L3

L4

L5

L6

L7

L8

C1 O1

Skipanon

Le

d F

lash

er

1.0

+9

-12

v

Gn

d

C2

R9

R2

R3

R4

R5

R6

R7

R8

16F84

R1L1

L2

L3

L4

L5

L6

L7

L8

C1O1

Skipanon

Led Flasher 1.0

+9-12v

Gnd

C2

R9

R2

R3

R4

R5

R6

R7

R8

Page 89: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

5.6.2 Sol der ing SMT Com po nents

Al though more dif fi cult than through-the-hole parts, sur face-mount com po nents canalso be hand-sol dered to boards and adapt ers. For this pur pose, the gen eral-pur posesol der ing iron is not suit able and its use will only lead to dam aged com po nents. Thesol der ing must be per formed with a tem per a ture-con trolled sta tion with a tem per a -ture read out. Ad di tion ally, it is nec es sary to use spe cial sol der ing tips that are de -signed for SMT pins and have the ad e quate form and di men sions. These are usu allyfur nished with the sol der ing sta tion or are avail able sep a rately from the sta tion man u -fac turer. The fol low ing items would be re quired in a min i mal toolkit for sol der ing SMT com po nents:

• Tem per a ture-con trolled sol der ing sta tion

• Sol der ing tips ap pro pri ate for the SMT type

• Sol der

• Sol der ing flux and flux re mover

• Spe cial heat gun for desoldering com po nents

• Desoldering wick (braided)

• Exacto knife

• Wa ter in a spray bot tle

• Tin foil heat shield

• Mag ni fy ing glasses and 10X jew eler’s loupe

• A steady hand

The sol der ing tip must be well tinned and must be fre quently cleaned on a wetsponge. Tips must be re placed as soon as they show signs of ox i da tion or at leastonce per month. The sol der ing tem per a ture should be held to about 700o F so as toavoid dam ag ing the pads. Prob a bly the most dif fi cult part is to get the SMT com po -nent cor rectly aligned with the pad and tacked down. The ac tual sol der ing is eas ierthan it ap pears be cause any sol der that flows across the pins can be eas ily re movedby wip ing it with the de-sol der ing wick in the di rec tion of the pins.

5.7 Trou ble shoot ing the Cir cuit BoardCir cuit board pro to types may not per form cor rectly when first tested. Cir cuit de signer rors and log i cal flaws must be elim i nated first. Then the board must be tested forme chan i cal de fects. These in clude bro ken con nec tions, miss ing pads, prob lems withvias and jump ers, dam aged or de fec tive com po nents, and a host of other pos si bleprob lems and de fects.

Trou ble shoot ing a PCB re quires sys tem at i cally test ing all func tions and op er a -tions for which it was de signed and mak ing sure that all cir cuit com po nents are per -form ing their ex pected func tions. It is usu ally a good idea to fol low a test ingmeth od ol ogy that pro ceeds from the sim plest to the most com pli cated and elim i nat -ing prob lems and defects in that order.

68 Chap ter 5

Page 90: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

5.7.1 Cir cuit Test ing ToolsMany tools and tech niques have been de vel oped for test ing and trou ble shoot ing de -fec tive boards and com po nents. The fun da men tal ones are the logic probe, themultimeter, and the os cil lo scope.

The logic probe is a pen-like de vice that is used in de ter min ing the Boolean state(1 or 0) of a dig i tal cir cuit. Most probes use the cir cuit’s power but some are bat teryop er ated. A typ i cal probe has three dif fer ent-col ored LEDs. The red LED in di cates a high state, the green LED a low state, and an am ber or yel low LED in di cates a pulse. Some logic probes have au di ble out put tones. A more com pli cated de vice is thelogic an a lyzer, which al lows test ing mul ti ple or com pli cated log i cal sig nals. Fig ure5-15 shows a logic probe.

Fig ure 5-15 Logic Probe. (Im age from Wikimedia Com mons)

The multimeter or multitester is a mea sur ing in stru ment that com bines sev eralfunc tions, in clud ing the mea sure ment of volt age, current, and re sis tance. Multi -meters can have an a log or dig i tal read outs. In the an a log ver sion, a nee dle orpointer moves over a cal i brated scale. In the dig i tal ver sion, the read ing is dis played as dec i mal dig its. Multi meters can be handheld de vices or pre cise bench in stru -ments cost ing thou sands of dol lars. Fig ure 5-16 shows a handheld dig i talmultimeter.

Fig ure 5-16 Dig i tal Multimeter. (Im age from Wikimedia Com mons)

From Cir cuit Sche mat ics to PCB 69

Page 91: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Multi meters are used in test ing the voltage, cur rent, and re sis tance in dif fer entparts of a cir cuit. While trou ble shoot ing, the multimeter’s most fre quent use is intest ing con ti nu ity. For this use, the in stru ment is set to emit an au di ble beep when -ever the probes are placed on a closed cir cuit. The op er a tor then pro ceeds to touchvar i ous points in the cir cuit us ing the in stru ment’s probes. If there is an open cir -cuit, the con ti nu ity beep will not be heard.

The most re fined and pow er ful of the three com mon test ing in stru ments is the os -cil lo scope. The os cil lo scope al lows the ob ser va tion of wave shapes by dis play ing atwo-di men sional graph of the sig nal. It is typ i cally used to ob serve elec tri cal eventsthat do not change or that change slowly. Fig ure 5-17 shows the front panel of a ba -sic os cil lo scope.

Fig ure 5-17 Front Panel of Ba sic Os cil lo scope. (Im age from Wikimedia Com mons by Brian S. Elliot – World

Tech ni cal Pub lish ing)

The clas si cal os cil lo scope uses a cath ode ray tube (CRT) to dis play the two-di -men sional graph of the sig nal. More mod ern in stru ments use a liq uid crys tal dis -play (LCD). The ver ti cal con trol knob con trols the am pli tude of the sig nal and thehor i zon tal con trol knob de fines the “sweep” or time base. Os cil lo scopes are fur -nished with a probe that con nects to the in stru ment’s in put port and to the sig nalsource on the cir cuit.

In re cent years com puter-based os cil lo scopes have be come avail able. In this case the user’s com puter per forms as a vir tual os cil lo scope with a probe con nected to ama chine port. Vir tual os cil lo scopes are usu ally less ex pen sive than their hard warecoun ter parts. In any case, the use of an os cil lo scope in sig nal anal y sis is out side thefo cus of this book.

70 Chap ter 5

Page 92: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Chap ter 6

In tro duc ing the Microcontroller

6.1 A Com puter on a ChipA microcontroller is a type of mi cro pro ces sor fur nished in a sin gle in te grated cir cuitand need ing a min i mum of sup port com po nents. Its name is some times ab bre vi atedµC or MCU. It is in fact a small com puter that con tains a pro cess ing el e ment, mem ory,and pe riph er als for in put and out put op er a tions. The prin ci pal fea ture ofmicrocontrollers are self-suf fi ciency and low cost. It is not in tended to be used as acom put ing de vice in the con ven tional sense; that is, a microcontroller is not de signedto be a data pro cess ing ma chine, but rather an in tel li gent core for a spe cial ized ded i -cated sys tem.

Microcontrollers are em bed ded in many con trol, mon i tor ing, and pro cess ing sys -tems. All the ba sic cir cuits dis cussed in this book con tain at least onemicrocontroller. A few microcontrollers are de signed as gen eral-pur pose de vices,es pe cially the type called dig i tal sig nal pro ces sors (DSPs). How ever, mostmicrocontrollers are used in spe cial ized and em bed ded sys tems such as wash ingma chines, tele phones, mi cro wave ov ens, au to mo biles, and weap ons of many kinds.In ad di tion to a pro ces sor, mem ory, and in put/out put fa cil i ties, a microcontrollerusu ally in cludes an in ter nal clock and one or more pe riph er als such as tim ers, coun -ters, an a log-to-dig i tal con vert ers, se rial com mu ni ca tion fa cil i ties, and Watch dog cir -cuits. Fig ure 6-1 shows a PIC 18F8720 microcontroller in an 80-pin TQFP sur face-mount pack age.

Fig ure 6-1 PIC 18F8720 Microcontroller on a Board. (Im age from Wikimedia Com mons)

71

Page 93: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

More than two dozen com pa nies in the United States and abroad man u fac tureand mar ket microcontrollers. They range from 8- to 32-bit de vices. Those at the lowend are in tended for very sim ple cir cuits and pro vide lim ited func tions and pro gram space, while those at the high end have many of the fea tures nor mally as so ci atedwith mi cro pro ces sors. The most pop u lar ones in clude sev eral from Intel (such asthe 8051), from Zilog (de riv a tives of their fa mous Z-80 mi cro pro ces sor), fromMotorola (such as the 68HC05), from Atmel (the AVR), the Par al lax (the BASICStamp), and many from Micro chip. In this book we fo cus on microcontrollers fromMicrochip, popularly called PICs.

Due to their low cost and easy avail abil ity, some microcontrollers have be comevery pop u lar among am a teur sys tem de sign ers. Large hobby com mu ni ties have de -vel oped around the most pop u lar ICs with many ded i cated websites with thou sandsof ex am ples of cir cuits and pro grams cur rently on line. Their pop u lar ity, sup port,and avail abil ity of tech nol ogy sam ples have been fac tors that de ter mined our adop -tion of the PIC microcontrollers for this book.

6.2 PICMicro Microcontroller

PIC is a fam ily of microcontrollers made by Micro chip Tech nol ogy. The orig i nal onewas the PIC1650 de vel oped by Gen eral In stru ments. This de vice was called PIC for“Pro gram ma ble In tel li gent Com puter” al though it is now as so ci ated with “Pro gram -ma ble In ter face Con trol ler.” Micro chip does not use PIC as an ac ro nym; in stead, theypre fer the brand name PICmicro. Pop u lar wis dom re lates that PIC is a reg is teredbrand in Ger many and Micro chip is un able to use it in ter na tion ally. The orig i nal PICwas built to be used with Gen eral In stru ments’s CP1600 pro ces sor, which had poor I/O per for mance. The PIC was de signed to take over the I/O tasks from the CPU, thus im -prov ing per for mance. In 1985, the PIC was up graded with EPROM to pro duce a pro -gram ma ble con trol ler. To day a huge va ri ety of PICs are avail able with many dif fer enton-board pe riph er als and pro gram mem o ries rang ing from a few hun dred words to32K.

The PIC prim i tive in struc tion set var ies in length from about 35 in struc tions forthe low-end de vices to more than 70 for the high-end de vices. The ac cu mu la tor,which is known as the work reg is ter in Micro chip doc u men ta tion, is part of many in -struc tions be cause the PIC con tains no other in ter nal reg is ters ac ces si ble to thepro gram mer. The PICs are pro gram ma ble in their na tive As sem bly lan guage, whichis straight for ward and not dif fi cult to learn. C lan guage and BASIC com pil ers havebeen de vel oped and are avail able from sev eral sources. Open-source Pascal, JAL,and Forth com pil ers are also avail able. Stor ing a pro gram in a PIC microcontrolleris pop u larly re ferred to as “blow ing” a PIC.

One of the rea sons for the com mer cial suc cess of the PIC is the sup port pro videdby Micro chip. This in cludes a pro fes sional-qual ity de vel op ment en vi ron ment calledMPLAB which can be down loaded free from the com pany’s website. The MPLAB pack age in cludes an as sem bler, a linker, a debugger, and a sim u la tor. Micro chip also sells a low-cost in-cir cuit debugger called MPLAB ICD 2. Other de vel op ment prod -ucts in tended for the pro fes sional mar ket are also avail able from Micro chip. The

72 Chap ter 6

Page 94: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Micro chip website fur nishes hun dreds, if not thou sands, of free sup port doc u ments, in clud ing data sheets, application notes, and sample code.

In ad di tion to the doc u ments and prod ucts on the Micro chip website, the PICmicrocontrollers have gained the sup port of many hob by ists, en thu si asts, and en tre -pre neurs who de velop code and sup port prod ucts and pub lish their re sults on theInternet. This com mu nity of PIC us ers is an in valu able source of in for ma tion andknow-how eas ily ac ces si ble to the be gin ner and use ful even to the pro fes sional. One such Internet re source is an open-source col lec tion of PIC tools named GPUTILS,which is dis trib uted un der the GNU Gen eral Pub lic Li cense. GPUTILS in cludes anas sem bler and a linker. The soft ware works on Linux, Mac OS, OS/2, and Win dows.An other prod uct named GPSIM is an open-source simulator featuring PIC hardwaremodules.

6.2.1 Pro gram ming the PIC Pro gram ming a PIC microcontroller re quires the fol low ing tools and com po nents:

1. An As sem bler or high-level lan guage com piler. The soft ware pack age usu ally in -cludes debugger, sim u la tor, and other sup port pro grams.

2. A com puter (usu ally a PC) in which to run the de vel op ment soft ware.

3. A hard ware de vice called a pro gram mer that con nects to the com puter throughthe se rial, par al lel, or USB line. The PIC is in serted in the pro gram mer and “blown”by down loading the ex e cut able code gen er ated by the de vel op ment sys tem. Thehard ware pro gram mer usu ally in cludes the sup port soft ware.

4. A ca ble or con nec tor for wir ing the pro gram mer to the com puter.

5. A PIC microcontroller.

6. PIC pro gram mers.

The de vel op ment sys tem (as sem bler or com piler) and the pro gram mer driver arethe soft ware com po nents. The com puter, pro gram mer, and con nec tors are the hard -ware el e ments. Fig ure 6-2 shows a com mer cial pro gram mer that con nects to theUSB port of a PC. The one in the il lus tra tion is made by MicroPro.

Fig ure 6-2 USB PIC Pro gram mer by MicroPro.

In tro duc ing the Microcontroller 73

Page 95: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Many other pro gram mers are avail able on the mar ket. Micro chip of fers sev eralhigh-end de vices with in-cir cuit se rial pro gram ming (ICSP) and low-voltage pro -gram ming (LVP) ca pa bil i ties. These de vices al low the PIC to be pro grammed in thetar get cir cuit. Some PICs can write to their own pro gram mem ory. This makes pos si -ble the use of so-called bootloaders, which are small res i dent pro grams that al lowload ing user soft ware over the RS-232 or USB lines. Pro gram mer/debugger com bi -na tions are also of fered by Micro chip and other ven dors.

De vel op ment Boards

A de vel op ment board is a dem on stra tion cir cuit that usu ally con tains an ar ray of con -nected and connectable com po nents. Their main pur pose is as a learn ing and ex per i -ment tool. Like pro gram mers, PIC de vel op ment boards come in a wide range of pricesand lev els of com plex ity. Most boards tar get a spe cific PIC microcontroller or a PICfam ily of re lated de vices. Lack ing a de vel op ment board, the other op tion is to buildthe cir cuits one self, a time-con sum ing but valu able ex pe ri ence. Fig ure 6-3 shows theLAB-X1 de vel op ment board for the 16F87x PIC fam ily.

Fig ure 6-3 LAB-X1 De vel op ment Board.

74 Chap ter 6

Page 96: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

The LAB-X1 boards, as well as sev eral other mod els, are prod ucts ofmicroEngineering Labs, Inc. Some of the sam ple pro grams de vel oped for this bookwere tested on a LAB-X1 board. De vel op ment boards from Micro chip and other ven -dors are also available.

6.2.2 Prototyping a PIC Cir cuit

It is a risky prop o si tion to write a PIC pro gram and as sume that it works cor rectlywith out test ing. Test ing a pro gram is not dif fi cult with a de vel op ment board but only if the board is com pat i ble with the microcontroller, and if it pro vides the hard ware thatwe need to test. But of ten one of these el e ments is miss ing, which means that we mustbuild the cir cuit for which the pro gram was de signed. Prototyping op tions and tech -niques, in clud ing bread boards, perfboards, and com mer cial PCBs, were dis cussed inChap ter 5.

6.3 PIC Ar chi tec ture

PIC microcontrollers are clas si fied by Micro chip into three groups: base line,mid-range, and high-per for mance. Within each of the groups, the PIC is re clas si fiedbased on the first two dig its of the PIC’s fam ily type. How ever, this sub-clas si fi ca tionis not very strict be cause there is some over lap. For this rea son we find PICs with 16Xdes ig na tions that be long to the base line fam ily and oth ers that be long to the mid-range group. In the fol low ing sec tions we de scribe the ba sic char ac ter is tics of the var i oussub-groups of the three ma jor PIC fam i lies with 8-bit ar chi tec tures.

6.3.1 Base line PIC Fam ily

This group in cludes mem bers of the PIC10, PIC12, and PIC16 fam i lies. The de vices inthe baseline group have 12-bit pro gram words and are supplied in 6- to 28-pin pack -ages. The microcontrollers in the base line group are de scribed as be ing suit able forbat tery-op er ated ap pli ca tions be cause they have low power re quire ments. The typ i -cal mem ber of the baseline group has a low pin count, flash pro gram mem ory, and lowpower re quire ments. The fol low ing types are in the base line group.

PIC10 De vices

The PIC10 de vices are low-cost, 8-bit, flash-based CMOS microcontrollers. They use33 sin gle-word, sin gle-cy cle in struc tions (ex cept for pro gram branches, which taketwo cy cles.) The in struc tions are 12-bits wide. The PIC10 de vices fea ture power-onand de vice re set, an in ter nal os cil la tor mode that saves hav ing to use ports for an ex -ter nal os cil la tor. They have a power-sav ing SLEEP mode, A Watch dog timer, and op -tional code pro tec tion.

In tro duc ing the Microcontroller 75

Page 97: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

The rec om mended ap pli ca tions of the PIC10 fam ily range from per sonal care ap -pli ances and se cu rity sys tems to low-power re mote trans mit ters and re ceiv ers. ThePICs of this fam ily have a small foot print and are man u fac tured in for mats suit ablefor both through-hole and sur face-mount tech nol o gies. Ta ble 6.1 lists the fea tures of some mem bers of the PIC10 fam ily.

Ta ble 6.1

PIC10F De vices

10F200 10F202 10F204 10F206

Clock:Max i mum Fre quency of Op er a tion (MHz) 4 4 4 4

Mem ory:Flash Pro gramMem ory 256 512 256 512Data Mem ory (bytes) 16 24 16 24

Pe riph er als:Timer Mod ule(s) TMR0 TMR0 TMR0 TMR0Wake-up from Sleep Yes Yes Yes YesCom para tors 0 0 1 1

Fea tures:I/O Pins 3 3 3 3In put Only Pins 1 1 1 1In ter nal Pull-ups Yes Yes Yes YesIn-Cir cuit Se rialPro gram ming Yes Yes Yes YesIn struc tions 33 33 33 33

Pack ages:6-pin SOT-238-pin PDIP

Two other PICs of this se ries are the 10F220 and the 10F222. These ver sions in -clude four I/O pins and two an a log-to-dig i tal con verter chan nels. Pro gram mem oryis 256 words on the 10F220 and 512 in the 10F222. Data mem ory is 16 bytes on theF220 and 23 bytes in the F222.

PIC12 De vices

The PIC12C5XX fam ily are 8-bit, fully static, EEPROM/EPROM/ROM-based CMOSmicrocontrollers. The de vices use RISC ar chi tec ture and have 33 sin gle-word, sin gle-cy cle in struc tions (ex cept for pro gram branches which take two cy cles). Like thePIC10 fam ily, the PIC12C5XX chips have power-on re set, de vice re set, and an in ter naltimer. Four os cil la tor op tions can be se lected, in clud ing a port-sav ing in ter nal os cil la -tor and a low-power os cil la tor. These de vices can also op er ate in SLEEP mode andhave Watch dog timer and code pro tec tion fea tures.

The PIC12C5XX de vices are rec om mended for ap pli ca tions rang ing from per -sonal care ap pli ances, se cu rity sys tems, and low-power re mote trans mit ters and re -ceiv ers. The in ter nal EEPROM mem ory makes pos si ble the stor age of user-de finedcodes and pass words as well as ap pli ance set ting and re ceiver fre quen cies. The var -i ous pack ages al low through-hole or sur face-mount ing tech nol o gies. Ta ble 6.2 liststhe char ac ter is tics of some selected members of this PIC family.

76 Chap ter 6

Page 98: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Ta ble 6.2

PIC 12Cxxx and 12CExxx De vices

Two other mem bers of the PIC12 fam ily are the 12F510 and the 16F506. In most re -spects these de vices are sim i lar to the other mem bers of the PIC12 fam ily pre vi ouslyde scribed. The one dif fer ence is that the 12F510 and 16F506 both have flash pro grammem ory. Ta ble 6.3 lists the most im por tant fea tures of these two PICs.

Two other mem bers of the PIC12F are the 12F629 and 12F675. The dif fer ence be -tween these two de vices is that the 12F675 has a 10-bit an a log-to-dig i tal con verterwhile the 629 does not. Ta ble 6.4 lists some im por tant fea tures of both PICs.

Sev eral mem bers of the PIC12 fam ily (12F635, 12F636, 12F639, and 12F683) areequipped with spe cial power-man age ment fea tures (called nano-watt tech nol ogy).These de vices are spe cially de signed for sys tems that re quire ex tended bat tery life.

In tro duc ing the Microcontroller 77

12C508(A) 12C518 12CE519 12C671 12CE674 12C509A 12C672 12CR509A

Clock: Maximum Frequency of Operation (MHz) 4 4 4 10 10 Memory: EPROM Program Memory 512/1024/1024 512x12 1024x12 1024/2048/ 2048x14 x12 1024x12 RAM Data Memory (bytes) 25/41/41 25 41 128 128 Peripherals: EEPROM Data Memory (bytes) — 16 16 0/0/16 16 Timer Module(s) TMR0 TMR0 TMR0 TMR0 TMR0 A/D Converter (8-bit) Channels — — — 4 4 Features: Wake-up from SLEEP on pin change Yes Yes Yes Yes Yes Interrupt Sources — — — 4 4 I/O Pins 5 5 5 5 5 Input Pins 1 1 1 1 1 Internal Pull-ups Yes/Yes/No Yes Yes Yes Yes In-Circuit Serial Programming Yes/No Yes Yes Yes Yes Number of Instructions 33 33 33 35 35 Packages 8-pin DIP 8-pin DIP 8-pin DIP 8-pin DIP 8-pin DIP SOIC JW,SOIC JW. SOIC SOIC JW

Page 99: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Ta ble 6.3

PIC12F510 and 12F506

Ta ble 6.4

PIC12F629 and 12F675

PIC14 De vices

The sin gle mem ber of this fam ily is the PIC14000. The 14000 is built with CMOS tech -nol ogy, which makes it fully static and gives the PIC an in dus trial tem per a ture range.The 14000 is rec om mended for bat tery charg ers, power sup ply con trol lers, powerman age ment sys tem con trol lers, HVAC con trol lers, and for sens ing and data ac qui si -tion ap pli ca tions. Ta ble 6.5 lists the most im por tant char ac ter is tics of this PIC.

78 Chap ter 6

16F506 12F510 Clock: Maximum Frequency of Operation (MHz) 20 8 Memory: Flash Program Memory 1024 1024 Data Memory (bytes) 67 38 Peripherals: Timer Module(s) TMR0 TMR0 Wake-up from Sleep on Pin Change Yes Yes Features: I/O Pins 11 5 Input Only Pin 1 1 Internal Pull-ups Yes Yes In-Circuit Serial Programming Yes Yes Number of Instructions 33 33 Packages 14-pin PDIP, 8-pin PDIP SOIC, SOIC, TSSOP MSOP

12F629 12F675 Clock: Maximum Frequency of Operation (MHz) 20 20 Memory: Flash Program Memory 1024 1024 Data Memory (SRAM bytes) 64 64 Peripherals: Timers 8/16 bits 1/1 1/1 Wake-up from Sleep on Pin Change Yes Yes Features: I/O Pins 6 6 Analog comparator module Yes Yes Analog-to-digital converter No 10-bit In-Circuit Serial Programming Yes Yes Enhanced Timer1 module Yes Yes Interrupt capability Yes Yes Number of Instructions 35 35 Relative addressing Yes Yes Packages 8-pin PDIP, 8-pin PDIP SOIC, SOIC, DFN-S DFN-S

Page 100: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Ta ble 6.5

PIC14000

6.3.2 Mid-Range PIC Fam ilyThe mid-range PICs in clude mem bers of the PIC12 and PIC16 groups. Ac cord ing toMicro chip, all mid-range PICs have 14-bit pro gram words with ei ther flash or OTP pro -gram mem ory. Those with flash pro gram mem ory also have EEPROM data mem oryand sup port in ter rupts. Some mem bers of the mid-range group have USB, I2C, LCD,USART, and A/D con vert ers. Im ple men ta tions range from 8 to 64 pins. In the fol low ingsub-sec tions we list the ba sic char ac ter is tics of some mid-range PICs.

PIC16 De vices

This is by far the most ex ten sive PIC fam ily. Cur rently, over 80 ver sions of the PIC16are listed in pro duc tion by Micro chip. We se lected a few of the most prom i nent mem -bers of the PIC16 fam ily to list their most im por tant fea tures. The Micro chip websitehas de tailed in for ma tion on any of these de vices. Ta ble 6.6 lists the fea tures of somemem bers of the PIC16 group.

6.3.3 High-Per for mance PIC Fam ilyThe high-per for mance PICs be long to the PIC18 group. They have 16-bit pro gramwords, flash pro gram mem ory, a lin ear mem ory space of up to 2 Mbytes, as well as pro -to col-based com mu ni ca tions fa cil i ties. They all sup port in ter nal and ex ter nal in ter -rupts and a much larger in struc tion set than mem bers of the base line and mid-rangefam i lies.

In tro duc ing the Microcontroller 79

Clock: Maximum Frequency of Operation (MHz) 20 Memory: Flash Program Memory 4096 Data Memory (SRAM bytes) 192 Peripherals: Timers (16 bits with capture) 1 Wake-up from Sleep on Pin Change Yes Features: I/O Pins 22 Analog-to-digital converter 2 channels On-chip temperature sensor 1 On-chip comparator modules 2 In-Circuit Serial Programming Yes Interrupt capability: Internal 6 sources External 5 sources I2C-compatible serial port 1 Number of Instructions 35 Relative addressing Yes Packages 22-pin PDIP, SOIC, SSOP, Windowed CERDIOP

Page 101: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Ta ble 6.6

PIC16 De vices

PIC18 De vices

The PIC18 fam ily has over 70 dif fer ent vari a tions cur rently in pro duc tion. The PIC18fam ily uses 16-bit pro gram words and are fur nished in 18 to 80 pin pack ages. Micro -chip de scribes the PICs in this fam ily as high-per for mance with in te grated A/D con -vert ers. They have 32-level stacks and sup port in ter rupts. The in struc tion set is muchlarger and starts at 79 in struc tions. The PICs in this fam ily have flash pro gram mem -ory, a lin ear mem ory space of up to 2 Mbytes, 8-by-8 bit hard ware mul ti plier, and com -mu ni ca tions pe riph er als and pro to cols. Ta ble 6-7 lists some mem bers of the PIC18fam ily.

Ta ble 6.7

PIC18 De vices

18F222 18F2455 18F2580 18F4580 18F8622

Clock:Max i mum Fre quency MHz

40 48 40 40 40Mem ory:Pro gram mem ory type

flash flash flash flash flashK-bytes 4 24 32 32 64K-words 2 12 16 16 321Data EEPROM 256 256 256 256 1024Pe riph er als:I/O chan nels 25 23 25 36 70ADC chan nels 10 10 8 11 16Com para tors 2 2 0 2 2Tim ers 1/8-bit 1/8-bit 1/8-bit 1/8-bit 2/8-bit

3/16-bit 3/16-bit 3/16-bit 3/16-bit 3/16-bit

(conitnues)

80 Chap ter 6

16C432 16C58 16C770 16F54 16F84A 16F946 Clock: Maximum Frequency MHz 20 40 20 20 20 20 Memory: Program memory type OTP OTP OTP Flash Flash Flash K-bytes 3.5 3 3.5 0.75 1.75 14 K-words 2 2 2 0.5 1 8 Data EEPROM 0 0 0 0 64 256 Peripherals: I/O channels 12 12 16 12 13 53 ADC channels 0 0 6 0 0 8 Comparators 0 0 0 0 0 2 Timers 1/8-bit 1/8-bit 2/8-bit 1/8-bit 1/8-bit 2/8-bit 1/16-bit 1/16-bit Watchdog timer Yes Yes Yes Yes Yes Yes Features: ICSP Yes No Yes No Yes Yes ICD No No No No 0 1 Pin count 20 18 20 18 18 64 Communications - - MPC/SPI - - AUSART Packages 20/CERDIP, 18/CERDIP 20/CERDIP 18/PDIP 18/PDIp 64/TQFP 20/SSOP 18/PDIP 20/PDIP 18/SOIC 18/SOIC 208mil 18/SOIC 20/SOIC 300mil 300mil 300mil 300mil

Page 102: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Ta ble 6.7

PIC18 De vices (con tin ued)

18F222 18F2455 18F2580 18F4580 18F8622

Watch dog timerYes Yes Yes Yes Yes

Fea tures:

EUSART Yes Yes Yes Yes 2ICSP Yes Yes Yes Yes YesICD 1 3 3 3 3Pin count 28 28 28 44 80Com mu ni ca tions

MPC/SPI MPC/SPI/USB MPC/SPI MPC/SP 2-MPC/SPIPack ages

28/PDIP, 28/SOIC 28/QFN 40/PDIP 80/TQFP28/SOIC 28/PDIP 20/PDIP 44/QFN300mil 300mil 300mil 44/TQFP

In tro duc ing the Microcontroller 81

Page 103: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

This page intentionally left blankThis page intentionally left blank

Page 104: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Chap ter 7

Ar chi tec ture and In struc tion Set

7.1 Mid-Range PIC Ar chi tec tureIn Chap ter 6 we an a lyzed the three ma jor PIC fam i lies of 8-bit de vices. From the de -scrip tions and func tion al ity one can see that as the PIC ar chi tec ture in creases in com -plex ity and power, so does the size, in tri cacy, and cost of the de vices. For theem bed ded sys tems cov ered in this book, the PICs of the mid-range fam ily pro videssuf fi cient power and func tion al ity. It can be ar gued that the base line PICs do find ex -ten sive use and are quite prac ti cal for many ap pli ca tions; in fact, some of the em bed -ded sys tems cov ered in the text could have been im ple mented with base line de vices.On the other hand, the base line PICs are quite sim i lar in ar chi tec ture and pro gram -ming to their mid-range rel a tives. In most cases the dif fer ence be tween a base line anda mid-range de vice is that the low-end one lacks some fea tures or has less pro gramspace or stor age. We have not cov ered the im ple men ta tion and pro gram ming of thebase line PICs due to the be lief that some one fa mil iar with mid-range de vices couldeas ily re-de sign a cir cuit and port the code in or der to use a sim pler base linemicrocontroller.

For all these rea sons we have opted to limit our cov er age to the mid-range fam ilyof PICs. Within this fam ily we have con cen trated our at ten tion on the most used,doc u mented, and pop u lar PICs: these are the 16F84 and 16F84A, the 16F877, andthe newer 16F684. Al though other PIC microcontrollers are men tioned in the text,the pro gram ming ex am ples and ap pli ca tions re fer only to these three devices.

We start by men tion ing sev eral gen eral char ac ter is tics of the PIC: Har vard ar chi -tec ture, RISC pro ces sor de sign, sin gle-word in struc tions, ma chine and data mem ory con fig u ra tion, and char ac ter is tic instruction formats.

7.1.1 Har vard Ar chi tec ture The PIC microcontrollers are not based on the von Neumann ar chi tec ture that hasbeen al most ex clu sively adopted in the com puter world. The model of hard ware de -sign adopted for the PIC fam ily is called the Har vard ar chi tec ture. Har vard ar chi tec -ture re fers to a com puter de sign in which data and in struc tion used dif fer ent sig nalpaths and stor age ar eas. Data and in struc tions are not lo cated in the same mem ory

83

Page 105: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

area but in sep a rate ones. One con se quence of the tra di tional von Neumann ar chi tec -ture is that the pro ces sor can ei ther read or write in struc tions or data but can not doboth at the same time, as both in struc tions and data use the same sig nal lines. In a ma -chine based on the Har vard ar chi tec ture, on the other hand, the pro ces sor can readand write in struc tions and data to and from mem ory at the same time. This re sults in afaster, al beit more com plex ma chine. Fig ure 7-1 shows the pro gram and data mem oryspace in a mid-range PIC.

Fig ure 7-1 Mid-Range PIC Mem ory (Har vard Ar chi tec ture).

One of the stron gest ar gu ments in fa vor of the Har vard ar chi tec ture is based onthe speed of ac cess to main mem ory. Mak ing a CPU faster while mem ory ac cess re -mains at the same speed rep re sents lit tle to tal gain, es pe cially if many mem ory ac -cesses are re quired. This sit u a tion is of ten re ferred to as the von Neumannbot tle neck and ma chines that suf fer from it are said to be mem ory bound.

Many microcontrollers, in clud ing the Micro chip PICs, are based on the Har vardar chi tec ture. These de vices have sep a rate stor age for pro gram and data and a re -duced in struc tion set. The mid-range PICs in par tic u lar have 8-bit data words but ei -ther 12-, 14-, or 16-bit pro gram in struc tions. Becausee the in struc tion size is muchwider than the data size, an in struc tion can con tain a full-size data constant.

7.1.2 CISC versus RISC

The CISC (Com plete In struc tion Set Com puter) de sign is based on each low-level in -struc tion per form ing sev eral op er a tions. For ex am ple, one Intel 80x86 opcode candec re ment a coun ter reg is ter, de ter mine the state of a pro ces sor flag, and ex e cute ajump in struc tion if the flag is set or cleared. An other CISC in struc tion moves a num ber of bytes of data con tained in a coun ter reg is ter from an area pointed at by a source reg -is ter, into an other area pointed at by a des ti na tion reg is ter. The Intel 80x86 CPU con -tains about 120 prim i tive op er a tions in its in struc tion set.

The orig i nal de sign idea of the CISC ar chi tec ture was to pro vide high-level in -struc tions, to fa cil i tate the im ple men ta tion of high-level lan guages. Sup pos edly thiswould be achieved through com plex in struc tion sets, mul ti ple ad dress ing modes,

84 Chap ter 7

PICmid-range

CPU

Datamemoryspace

RAM

Programmemoryspace

DATAADDRESS

PROGRAMADDRESS

DATABUS

INSTRUCTIONBUS

Page 106: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

and prim i tive op er a tions that per formed mul ti ple func tions. How ever, in manycases the CISC ar chi tec ture did not re sult in better per for mance be cause the morecom plex the in struc tion set re sulted in greater de cod ing time. At the same time, im -ple ment ing large in struc tion sets re quired more sil i con space and con sid er ablymore de sign ef fort. Some CISC pro ces sors de vel oped in the 1960s and 1970s are theIBM Sys tem/360, the PDP-11, the Motorola 68000 family, and the Intel 80x86 familyof CPUs.

In con trast, a RISC (Re duced In struc tion Set Com puter) ma chine con tains fewerin struc tions and each in struc tion per forms more el e men tary op er a tions. One con se -quence of this is a smaller sil i con area, faster ex e cu tion, and re duced pro gram sizewith fewer ac cesses to main mem ory. The PIC de sign ers have fol lowed the RISCroute. Other CPUs with RISC de sign are the MIPS, the IBM Power PC, and the DECAl pha.

7.1.3 Single-Word In struc tions

One of the con se quences of the PIC’s Har vard ar chi tec ture is that the in struc tions canbe wider than the 8-bit data size. Be cause the de vice has sep a rate buses for in struc -tions and data, it is pos si ble that in struc tions are sized dif fer ently than data items. Be -ing able to vary the num ber of bits in each in struc tion opcode makes pos si ble the op ti -mi za tion of pro gram mem ory and the use of sin gle-word in struc tions that can befetched in one bus cy cle.

In the mid-range PICs, each in struc tion is 14-bits wide and ev ery fetch op er a tionbrings into the ex e cu tion unit one com plete op er a tion code. Be cause each in struc -tion takes up one 14-bit word, the num ber of words of pro gram mem ory in a de viceex actly de ter mines the num ber of pro gram in struc tions that can be stored. Be causevon Neumann in struc tions can span mul ti ple bytes, there is no as sur ance that eachpro gram mem ory lo ca tion con tains the first opcode of a multibyte in struc tion. Forthese rea sons, in struc tion stor age and fetch ing in a von Neumann ma chine becomes a much more complicated issue.

As is the case with con ven tional pro ces sors, the PIC ar chi tec ture has a two-stagein struc tion pipe line. How ever, be cause the fetch por tion of the cur rent in struc tionand the ex e cu tion of the pre vi ous one can over lap in time, one com plete in struc tionis fetched and ex e cuted at ev ery ma chine cy cle. This is known as in struc tionpipelining. Be cause each in struc tion is 14 bits and the pro gram mem ory bus is also14-bits wide, each in struc tion con tains all the nec es sary in for ma tion so that it canbe ex e cuted with out any ad di tional fetch ing. The one ex cep tion is when an in struc -tion mod i fies the con tents of the Pro gram Coun ter. In this case a new in struc tionmust be fetched, which re quires an ad di tional ma chine cy cle.

The PIC clock ing sys tem is de signed so that an in struc tion is fetched, de coded,and ex e cuted ev ery four clock cy cles. In this man ner, a PIC equipped with a 4-MHzos cil la tor clock will beat at a rate of 0.25 ms. Be cause each in struc tion ex e cutes atev ery four clock cy cles, each in struc tion takes 1 ms.

Ar chi tec ture and In struc tion Set 85

Page 107: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

7.1.4 In struc tion For matAll mem bers of the mid-range fam ily of PICs have 14-bit in struc tions in a set of 35 in -struc tions. The for mat for the in struc tions fol lows three dif fer ent pat terns: byte-ori -ented, bit-ori ented, and lit eral and con trol in struc tions. Fig ure 7-2 shows thebitmaps for the three types.

Fig ure 7-2 Mid-Range In struc tion For mats.

86 Chap ter 7

0

0

0

0

<== bits

<== bits

<== bits

<== bits

7 bit file register address

d bit (0 = w, 1 = f)

OPCODE

8-bit immediate value (literal)

OPCODE

11-bit immediate value

OPCODE

7 bit file register address

bit number (3 bits)

OPCODE

Byte-oriented instructions

Literal and control instructions

CALL and GOTO instructions

Bit-oriented instructions

8

8

10

7

7

10

7

6

6

13

13

13

13

Page 108: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

In Fig ure 7-2 note that, in the PIC in struc tion set, the opcode field can be 6- 4- or3-bits wide. It is this scheme that al lows im ple ment ing all 35 dif fer ent in struc tionswith the 14 avail able opcode bits. Also note that in struc tions that ref er ence a filereg is ter do so in a 7-bit field. Be cause the nu mer i cal range of seven bit is 128 val ues,the mid-range PICs that ad dress more than 128 data mem ory lo ca tions must re sortto bank ing. In this case a bit or bit field in the STATUS reg is ter serves to se lect thebank cur rently ad dressed.

A sim i lar sit u a tion arises when ad dress ing pro gram mem ory with an 11-bit field.Eleven bits al low 2048 ad dresses; so if a PIC is to have more than 2K pro gram mem -ory, it is nec es sary to adopt a pag ing scheme in which a spe cial reg is ter is used tose lect which mem ory page the in struc tion is lo cated. Pag ing is only re quired in de -vices that ex ceed the 2K pro gram space limit that can be en coded in 11 bits.

7.1.5 Mid-Range De vice Ver sionsThe names used by Micro chip use dif fer ent code let ters to in di cate the var i ous ver -sions of a de vice. In this case the first let ter fol low ing the fam ily af fil i a tion des ig na torrep re sents the mem ory type of the de vice, as fol lows:

1. The let ter C, as in PIC16Cxxx, re fers to de vices with EPROM type mem ory.

2. The let ters CR, as in PIC16CRxxx, re fer to de vices with ROM type mem ory.

3. The let ter F, as in PIC16Fxxx, re fers to de vices with flash mem ory.

The let ter L im me di ately fol low ing the af fil i a tion des ig na tor re fer to de vices withex tended volt age range. For ex am ple, the PIC16LFxxx des ig na tion cor re sponds tode vices with extended voltage range.

7.1.6 Arith me tic-Logic UnitIn a dig i tal sys tem the cen tral pro cess ing unit (CPU) is the com po nent that ex e cutesthe pro gram in struc tions and pro cesses data. It pro vides the fun da men tal func tion al -ity of a dig i tal sys tem and is re spon si ble for its pro gram ma bil ity. In the PIC ar chi tec -ture the CPU is a por tion of the de vice that fetches and ex e cutes the in struc tions con -tained in a pro gram. The arith me tic-logic unit (ALU) is the CPU el e ment that per -forms arith me tic, bitwise, and log i cal op er a tions. It also con trols the bits in theSTATUS reg is ter as they are changed by the ex e cu tion of the var i ous pro gram in struc -tions. For ex am ple, if the re sult of ex e cut ing an in struc tion is zero, the ALU will set the zero bit in the STATUS reg is ter.

7.2 Data Mem ory Or ga ni za tionThe struc ture and or ga ni za tion of data mem ory in the PIC hard ware also has someunique and in ter est ing fea tures. The pro gram mer ac cus tomed to the flat, ad dress ablemem ory space of the von Neumann com puter with its mul ti ple ma chine reg is ters mayre quire some time to gain fa mil iar ity with the PIC’s data for mats.

7.2.1 w Reg is terCon ven tional ma chine reg is ters do not ex ist in PICs. In stead, there is a sin gle ad dress -able reg is ter called the work reg is ter, or the w reg is ter. The CISC low-level pro gram -

Ar chi tec ture and In struc tion Set 87

Page 109: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

mer used for mul ti ple gen eral pur pose reg is ters into which data can be moved andlater re trieved will need to be come ac cus tomed to work ing with a sin gle ma chine reg -is ter that takes part in prac ti cally ev ery in struc tion. Add to this the lack of an ad dress -able stack and you will see that mid-range PIC pro gram ming is based on a dif fer entpar a digm.

7.2.2 Data Reg is tersThe PIC’s data mem ory con sists of reg is ters, also called file reg is ters. The file reg is -ters be have more like con ven tional vari ables. They can be ad dressed di rectly and in di -rectly. In mid-range PICs, all data reg is ters are 8 bits and come in two types: gen eral-pur pose reg is ters (GPRs) and spe cial-func tion reg is ters (SFRs).

Mem ory Banks

Fig ure 7-2, pre vi ously in this chap ter, shows that the PIC in struc tion for mat de votes 7bits to the ad dress field. A 7-bit ad dress al lows ac cess to 128 mem ory lo ca tions. Be -cause many PICs of the mid-range fam ily have more than 128 bytes of data mem ory, anad dress ing scheme based on mem ory banks must be im ple mented. The mem orybank ing mech a nism adopted by the PICs is ef fec tive, al though not very user-friendly.

The num ber of banks var ies ac cord ing to the amount of avail able RAM, al ways inmul ti ples of 128 bytes. All mid-range PICs have banked mem ory. Bank ing is ac com -plished through the spe cial bank se lect bits in the STATUS reg is ter, de scribed laterin this chap ter. Not all bank ing bits are im ple mented in all de vices. For ex am ple, the 16F84/16F84A con tain two mem ory banks. In this case, bank shift ing re quires a sin -gle bank se lect bit (RP0). In de vices with more than two mem ory banks, bank se lec -tion is as shown in Table 7.1.

Ta ble 7.1

Mid-Range Bank Se lec tion Op tions in Di rect Ad dress ing

BANK STATUS REGISTER ACCESSED BITS (RP1:RP0)

0 0 : 0 1 0 : 1 2 1 : 0 3 1 : 1

Fig ure 7-3 shows how banked mem ory is ac cessed in di rect ad dress ing. The il lus -tra tion re fers to a mid-range PIC with four banks, as is the case with the 16F87x.

SFRs

The spe cial func tion reg is ters are de fined by the de vice ar chi tec ture and have re -served names. For ex am ple, the TMR0 reg is ter is part of the sys tem timer, the STATUSreg is ter holds sev eral pro ces sor flags, and the INTCON reg is ter is used in con trol lingin ter rupts. Some SFRs can be writ ten and read, and oth ers are read-only. Re servedand not-im ple mented SFR bits al ways read as zero. Two SFR reg is ters, which are usedin in di rect ad dress ing, have spe cial char ac ter is tics: one of them (the in di rect ad dressreg is ter) is not a phys i cal reg is ter, and the other one (the FSR reg is ter) is used to ini -tial ize the in di rect pointer. The SFRs are al lo cated start ing at the low est RAM ad dress(ad dress 0).

88 Chap ter 7

Page 110: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 7-3 Mem ory Ac cess in Di rect Ad dress ing.

Fig ure 7-4 is a map of the reg is ter file in the 16F87x fam ily. Ob serve, in Fig ure 7-4, that the gen eral-pur pose reg is ters do not start at the same ad dress off set in eachbank. How ever, there is a com mon area that ex tends from 0x70 to 0x7f that is ac ces -si ble no mat ter which bank is se lected. In ap pli ca tions that re quire fre quent bankswitch ing, this 16-byte area is very valu able real es tate be cause user vari ables cre -ated in it are ac ces si ble no mat ter which bank is cur rently se lected. GPRs cre atedout side this com mon area are only ac ces si ble when the cor re spond ing bank is se -lected.

The reg is ters in bold face in Fig ure 7-4 are ac ces si ble from any bank. These reg is -ters, such as STATUS and the in di rect ad dress ing reg is ters FSR and INDF, must bebank in de pend ent. Also, some reg is ters are mir rored in more than one bank. For ex -am ple, the PORTB reg is ter is ac ces si ble in bank 0 and in bank 2, and the TRISB reg -is ter in bank 1 and bank 3. The mir rored reg is ters were im ple mented to sim plifydata ac cess and min i mize bank changes in applications.

Ar chi tec ture and In struc tion Set 89

0

RP0

<== offset in bank

RP1

00

Bank 0 Bank 1 Bank 2 Bank 3

0x00 0x00 0x00 0x00

0x7f 0x7f 0x7f 0x7f

01 10 11

6

Page 111: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 7-4 16F87x File Reg is ter Map.

Other mem bers of the mid-range PIC group, such as the 16F84 and 16F84A, havea dif fer ent mem ory foot print. Fig ure 7-5 is a bitmap of the 16F84A.

90 Chap ter 7

INDF

TMR0

PCL

STATUS

FSR

PORTA

PORTB

PORTC

PORTD

PORTE

PCLATH

INTCON

PIR1

PIR2

TMR1L

TMR1H

T1CON

TMR2

T2CON

SSPBUF

SSPCON

CCPR1L

CCPR1H

CCP1CON

RCSTA

TXREG

RCREG

CCPR2L

CCPR2H

CCP2CON

ADRESH

ADCON0

INDF

OPTION*

PCL

STATUS

FSR

TRISA

TRISB

TRISC

TRISD

TRISE

PCLATH

INTCON

PIE1

PIE2

PCON

SSPCON2

PR2

SSPADD

SSPTAT

TXSTA

SPBRG

ADRESL

ADCON1

INDF

TMR0

PCL

STATUS

FSR

PORTB

PCLATH

INTCON

EEDATA

EEADR

EEDATH

EEADRH

INDF

OPTION*

PCL

STATUS

FSR

TRISB

PCLATH

INTCON

EECON1

EECON2

Reserved

Reserved

0x00

0x01

0x02

0x03

0x04

0x05

0x06

0x07

0x08

0x09

0x0a

0x0b

0x0c

0x0d

0x0e

0x0f

0x10

0x11

0x12

0x13

0x14

0x15

0x16

0x17

0x18

0x19

0x1a

0x1b

0x1c

0x1d

0x1e

0x1f

0x20

0x80

0x81

0x82

0x83

0x84

0x85

0x86

0x87

0x88

0x89

0x8a

0x8b

0x8c

0x8d

0x8e

0x8f

0x90

0x91

0x92

0x93

0x94

0x95

0x96

0x97

0x98

0x99

0x9a

0x9b

0x9c

0x9d

0x9e

0x9f

0xA0

0x100

0x101

0x102

0x103

0x104

0x105

0x106

0x107

0x108

0x109

0x10a

0X10b

0x10c

0x10d

0x10e

0x10f

0x110

0x180

0x181

0x182

0x183

0x184

0x185

0x186

0x187

0x188

0x189

0x18a

0x18b

0x18c

0x18d

0x18e

0x18f

0x190

GeneralPurpose

Registers

0x7f 0xff

0xef0xf0

0x16f0x170

0x1ef0x1f0

0x17f 0x1ff

GeneralPurpose

Registers

Commonarea

0x70-0x7f

Commonarea

0x70-0x7f

Commonarea

0x70-0x7f

Commonarea

0x70-0x7f

GeneralPurpose

Registers

GeneralPurpose

Registers

Bank 0 Bank 1 Bank 2 Bank 3

* Actual name is OPTION_REG

Page 112: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 7-5 16F84A File Reg is ter Map.

Here again, the gen eral-pur pose reg is ters do not start at the same ad dress off setin each bank. Also note that all GPRs are mapped to bank 0. This de ter mines that, inthe 16F84A, user-de fined reg is ters cre ated in bank 0 are ac ces si ble no mat ter whichbank is cur rently se lected. Fig ure 7-6 is a reg is ter map of the 16F684 PIC.

GPRs

Gen eral-pur pose reg is ters are cre ated and named by the pro gram mer and must be al -lo cated in the re served mem ory space. In the 16F84A, all GPRs are mapped to thesame mem ory area, no mat ter in which bank they are de fined. The GPR mem ory spaceex tends from 0x0c to 0x4f (68 bytes). A much dif fer ent sit u a tion ex ists in the 16F87xPICs, in which only 16 bytes of GPR space are mir rored in all three banks. This is themem ory re ferred to as the com mon area in Fig ure 7-4. In the 16F87x, the to tal avail -able GPR space is as fol lows:

BANK 0 BANK 1 BANK2 BANK3

96 bytes 80 bytes 96 bytes 96 bytes

To tal = 368 bytes

Ar chi tec ture and In struc tion Set 91

INDF

TMR0

PCL

STATUS

FSR

PORTA

PORTB

EEDATA

EEADR

PCLATH

INTCON

INDF

OPTION*

PCL

STATUS

FSR

TRISA

TRISB

EECON1

EECON2

PCLATH

INTCON

0x00

0x01

0x02

0x03

0x04

0x05

0x06

0x07

0x08

0x09

0x0a

0x0b

0x0c

0x80

0x81

0x82

0x83

0x84

0x85

0x86

0x87

0x88

0x89

0x8a

0x8b

0x8c

GeneralPurpose

Registers

0x4f 0xcf

GeneralPurpose

Registers-

mapped tobank 0

-

Bank 0 Bank 1

* Actual name is OPTION_REG

Page 113: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 7-6 16F684 File Reg is ter Map.

92 Chap ter 7

INDF

TMR0

PCL

STATUS

FSR

PORTA

PORTC

PCLATH

INTCON

PIR1

TMR1L

TMR1H

T1CON

TMR2

T2CON

CCPR1L

CCPR1H

CCP1CON

PWM1CON

ECCPAS

WDTCON

CMCON0

CMCON1

ADRESH

ADCON0

INDF

OPTION*

PCL

STATUS

FSR

TRISA

TRISC

PCLATH

INTCON

PIE1

PCON

OSCCON

OSCTUNE

ANSEL

PR2

WPUA

IOCA

VRCON

EEDAT

EEADR

EECON1

EECON2

ADRESL

ADCON1

0x00

0x01

0x02

0x03

0x04

0x05

0x06

0x07

0x08

0x09

0x0a

0x0b

0x0c

0x0d

0x0e

0x0f

0x10

0x11

0x12

0x13

0x14

0x15

0x16

0x17

0x18

0x19

0x1a

0x1b

0x1c

0x1d

0x1e

0x1f

0x20

0x80

0x81

0x82

0x83

0x84

0x85

0x86

0x87

0x88

0x89

0x8a

0x8b

0x8c

0x8d

0x8e

0x8f

0x90

0x91

0x92

0x93

0x94

0x95

0x96

0x97

0x98

0x99

0x9a

0x9b

0x9c

0x9d

0x9e

0x9f

0xa0GeneralPurpose

Registers96

Bytes

0x7f 0xff

0xbf

GeneralPurpose

Registers32

Bytes

Bank 0 Bank 1

* Actual name is OPTION_REG

Page 114: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

7.2.3 In di rect Ad dress ing

The in struc tion set of most pro ces sors, in clud ing the PICs, pro vides a mech a nism forac cess ing mem ory operands in di rectly. In di rect ad dress ing is based on the fol low ingca pa bil i ties:

• The ad dress of a mem ory op er and is loaded into a reg is ter. This reg is ter is called thepointer.

• The pointer reg is ter is then used to in di rectly ac cess the mem ory lo ca tion at the ad -dress it “points to.”

• The value in the pointer reg is ter can be mod i fied (usu ally in cre mented or dec re -ment ed) so as to al low ac cess to other mem ory operands.

In the PIC ar chi tec ture, in di rect ad dress ing is im ple mented us ing two reg is ters:INDF and FSR. The INDF reg is ter, al ways lo cated at mem ory ad dress 0x00 and mir -rored in all banks, is not a phys i cal reg is ter; there fore it can not be di rectly ac cessedby code. The FSR reg is ter is the pointer reg is ter that is in i tial ized to the ad dress of a mem ory op er and. Once a mem ory ad dress is placed in FSR, any ac tion on the INDFreg is ter takes place at the mem ory lo ca tion pointed at by FSR. For ex am ple, if theFSR reg is ter is in i tial ized to mem ory ad dress 0x20, then clear ing the INDF reg is terhas the ef fect of clear ing the mem ory lo ca tion at ad dress 0x20. The ac tion on theINDF reg is ter ac tu ally takes place at the ad dress con tained in the FSR reg is ter. Now if FSR (the pointer reg is ter) is in cre mented and INDF is again cleared, the mem orylo ca tion at ad dress 0x21 will be cleared. In di rect addressing is covered in detail inthe programming chapters later in the book.

7.3 Mid-Range I/O and Pe riph er als

Mid-range de vices con tain spe cial mod ules to im ple ment pe riph eral and I/O func -tions. The more com plex the de vice, the more pe riph eral mod ules are likely to be pres -ent. For ex am ple, a sim ple mid-range PIC like the 16F84A con tains few pe riph eralmod ules, spe cif i cally EEPROM data mem ory, I/O ports, and a timer mod ule. The16F87x PICs, on the other hand, in ad di tion to I/O ports, EEPROM, and three in di vid -ual tim ers, also have a par al lel slave port, a cap ture and com pare (PWM) mod ule, amas ter syn chro nous se rial port (MSSP) mod ule, a uni ver sal asyn chron ous/syn chro -nous re ceiver and trans mit ter (USART) mod ule, and an an a log-to-dig i tal con verter(A/D) mod ule.

Other mem bers of the mid-range fam ily have ad di tional or dif fer ent pe riph eraland I/O mod ules. In the fol low ing sec tions we briefly de scribe the ar chi tec ture ofthe most com mon pe riph eral mod ules. The pro gram ming de tails are cov ered in con -text elsewhere in the book.

Im ple men ta tion of many dif fer ent func tions in a de vice with a small foot print re -quires multiplexing many of the PICs ac cess con nec tions. Fig ure 7-7 shows thepinout of the 16F84A and the 16F877 as well as the mul ti ple func tions of many pinsin either device.

Ar chi tec ture and In struc tion Set 93

Page 115: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 7-7 16F84A and 16F877 Pin Di a grams.

7.3.1 Ports

Ports pro vide PICs with ac cess to the out side world and are mapped to phys i cal pinson the de vice. In some mid-range PICs (see Fig ure 7-7), some pins used in I/O op er a -tions are mul ti plexed with al ter nate func tions of pe riph eral mod ules. A pin ceases tobe a port when a pe riph eral mod ule func tion is ac ti vated for that pin.

Gen eral port pins are bi-di rec tional; there fore they can be con fig ured ei ther as in put or out put. Each port has a cor re spond ing TRIS reg is ter. The set ting in this reg -is ter de ter mines if a port is des ig nated as in put or out put. A value of 1 in the port’sTRIS reg is ter makes the port an in put and a value of 0 makes the mapped port anout put. In put ports are used in com mu ni cat ing with in put de vices, such as switches, keypads, and in put data lines from hard ware de vices. Out put ports are used in com -mu ni cat ing with out put de vices, such as LEDs, Seven-Seg ment dis plays, liq uid-crys -tal dis plays (LCDs), and data output line to hardware devices such as motors.

94 Chap ter 7

16F84RA2

RA3

RA4/TOCKI

MCLR

Vss

RB0/INT

RB1

RB2

RB3

1

2

3

4

5

6

7

8

9

18

17

16

15

14

13

12

11

10

RA1

RA0

OSC1

OSC2

Vdd

RB7

RB6

RB5

RB4

16F877

40

39

38

37

36

35

34

33

32

31

30

29

28

27

26

25

24

23

22

21

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

RB7/PGD

RG6/PGC

RB5

RB4

RB3/PGM

RB2

RB1

RB0/INT

VDD

VSS

RD7/PSP7

RD6/PSP6

RD5/PSP5

RD4/PSP4

RC7/RX/DT

RC6/TX/CK

RC5/SD0

RC4/SDI/SDA

RD3/PSP3

RD2/PSP2

!MCLR/VPP

RA0/AN0

RA1/AN1

RA2/AN2.VREF-

RA3/AN3/VREF+

RA4/TOCKI

RA5/AN4/SS

RE0/!RD/AN5

RE1/!WR/AN6

RE2/!CS/AN7

VDD

VSS

OSC1/CLKIN

OS2/CLKOUT

RC0/T1OSO/T1CKI

RC1/T1OSI/CCP2

RC2/CCP1

RC3/SCK/SCL

RD0/PSP0

RD1/PSP1

Page 116: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Al though port pins are bit mapped, they are read and writ ten as a unit. For ex am -ple, the PORTA reg is ter holds the sta tus of the eight pins pos si bly mapped to port A. Writ ing to a spe cific port writes to the port latches. Write op er a tions to ports are ac -tu ally read-mod ify-write op er a tions. The port pins are first read, then the value ismod i fied, and fi nally writ ten to the port’s data latch. As pre vi ously men tioned, some of the port pins are mul ti plexed; for ex am ple, pin RA4 is mul ti plexed with theTimer0 mod ule clock in put; there fore, it is la beled RA4/T0CKI pin in the de vice’spinout. Other PORTA pins are mul ti plexed with an a log in puts and with other pe riph -eral func tions. The de vice data sheets con tain in for ma tion re gard ing the func tionsas signed to each de vice pin.

7.3.2 Tim ers

Timer mod ules are avail able in all mid-range PICs; in fact, the TIMER0 mod ule is pres -ent in all PICs of the mid-range fam ily. The TIMER0 mod ule has the fol low ing fea tures:

• 8-bit timer/coun ter

• Read able and writable

• 8-bit soft ware pro gram ma ble prescaler

• In ter nal or ex ter nal clock se lect

• In ter rupt on overflow from FFh to 00h

• Edge se lect for ex ter nal clock

Chap ter 11 is de voted en tirely to the ar chi tec ture and pro gram ming of tim ers and coun ters.

7.3.3 Cap ture and Com pare Mod ule

Some mid-range de vices con tain one or more cap ture and com pare mod ules, des ig -nated as Cap ture/Com pare/PWM. In Fig ure 7-7 you can see that one of the func tionsmul ti plexed onto pin 17 of the 16F877 is la beled CCP1 (Cap ture and Com Pare mod ulenum ber 1). The CCP2 mod ule is mul ti plexed onto pin num ber 16. The prin ci pal func -tion of the cap ture and com pare mod ules is to en hance timer op er a tions. Each mod ule con tains the fol low ing el e ments:

A 16-bit reg is ter that can op er ate as a:

A 16-bit Cap ture reg is ter

A 16-bit Com pare reg is ter

A PWM Mas ter/Slave Duty Cy cle reg is ter

When more than one cap ture and com pare mod ule is im ple mented in a sin gle de -vice, they are all iden ti cal in op er a tion. In the 16F877 the two avail able mod ules aredes ig nated CCP1 and CCP2. In each mod ule a Cap ture/Com pare/PWM Register1(CCPR1) is com prised of two 8-bit reg is ters: CCPR1L (low byte) and CCPR1H (highbyte). The CCP1CON reg is ter con trols the operation of CCP1.

Ar chi tec ture and In struc tion Set 95

Page 117: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

The CCP mod ules find use in re cord ing events such as mea sur ing time pe ri ods,count ing, gen er at ing pulses and pe ri odic wave forms, and volt age averaging.

7.3.4 Mas ter Syn chro nous Se rial PortSome mid-range PICs come equipped with hard ware mod ules to im ple ment se rial pro -to cols, in clud ing SPI and I2C. The mod ule that pro vides these in ter faces is called theMas ter Syn chro nous Se rial Port, or MSSP. The MSSP mod ule can op er ate in ei ther the slave or the mas ter mode, as well as in a free bus mode, also called the multi-mas terfunc tion. The MSSP mod ule is use ful for com mu ni cat ing with other pe riph eral ormicrocontroller de vices. The pe riph eral de vices can be se rial EEPROMs, shift reg is -ters, dis play driv ers, or A/D con vert ers, etc. The MSSP mod ule is dis cussed in Chap ter14 in the con text of EEPROM data mem ory pro gram ming.

7.3.5 USART Mod uleThe Uni ver sal Syn chro nous Asyn chron ous Re ceiver Trans mit ter (USART) mod ulein the 16F87x fam ily is also known as a Se rial Com mu ni ca tions In ter face, or SCI. TheUSART mod ule is used in com mu ni cat ing with de vices and sys tems that sup port theRS-232 pro to col, in clud ing com put ers and ter mi nals. It can be con fig ured as an asyn -chron ous full-du plex de vice, as a syn chro nous half-du plex mas ter, or as a syn chro -nous half-du plex slave. In the syn chro nous mode, the USART is use ful incom mu ni cat ing with an a log-to-dig i tal and dig i tal-to-an a log in te grated cir cuits or forac cess ing se rial EEPROMS. The USART is dis cussed ex ten sively in the con text of se -rial com mu ni ca tions and pro gram ming EEPROMS. These top ics are cov ered in Chap -ter 20 and Chap ter 14, re spec tively.

7.3.6 A/D Mod uleUn til re cently A/D con ver sions re quired the use of ded i cated de vices, usu ally in theform of an in te grated cir cuit com po nent. In Micro chip doc u men ta tion, the an a -log-to-dig i tal con ver sions mod ule is re ferred to as ADC. Some mid-range PICs nowcome with on-board A/D hard ware. One of the ad van tages of us ing on-board A/D con -vert ers is sav ing in ter face lines. In ter fac ing with a hard ware an a log-to-dig i tal IC usu -ally re quires three to four lines. A sim i lar func tion can be im ple mented with on-boardA/C hard ware with a sin gle line. This sav ing in I/O lines can be sig nif i cant in many PICcir cuits.

Mid-range PICs equipped with A/D con vert ers have ei ther 8- or 10-bit res o lu tionand can re ceive an a log in put in 2 to 16 dif fer ent chan nels. For ex am ple, the 16F877con tains eight an a log in put chan nels at a 10-bit res o lu tion. A/D con vert ers use asam ple-and-hold ca pac i tor to store the an a log charge and per form a suc ces sive ap -prox i ma tion al go rithm to pro duce the dig i tal re sult. When the con verter res o lu tionis 10 bits these are stored in two 8-bit reg is ters, one of them hav ing only four sig nif i -cant bits. The ADC mod ule on the 16F684 PIC pro vides a 1-bit bi nary out put from asin gle an a log sig nal. The pres ence of this mod ule is some times the rea son forpreferring the 16F684 over its 16F84 and 16F84A predecessors.

The A/D mod ule has high- and low-volt age ref er ence in puts that are se lected bysoft ware. The mod ule can op er ate while the pro ces sor is in SLEEP mode, but only if the A/D clock pulse is de rived from its in ter nal RC os cil la tor.

96 Chap ter 7

Page 118: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

7.4 Mid-Range PIC Core Fea turesCore fea tures re fer to those that ap ply to all mem bers of the mid-range fam ily. It in -cludes the fol low ing el e ments:

• The de vice oscillator

• The re set mech a nism

• CPU ar chi tec ture and op er a tion

• The ALU

• Data mem ory or ga ni za tion

• The in ter rupt sys tem

• The in struc tion set

We have al ready dis cussed the ar chi tec ture and gen eral fea tures of the CPU andthe ALU, as well as to data mem ory or ga ni za tion. The re main ing top ics (os cil la tor,re set, in ter rupts, and in struc tion set) are cov ered in the fol low ing sub-sections.

7.4.1 Os cil la torMid-range PICs re quire a clock sig nal for its op er a tion. The clock sig nal source can beex ter nal to the PIC or an in ter nal os cil la tor. Dif fer ent mid-range PICs sup port dif fer -ent num bers of os cil la tor modes. For ex am ple, the 16F877 and the 16F684 can ex e -cute in any one of eight modes, but in the 16F84 only four os cil la tor modes areavail able. The 16F684 has eight pos si ble clock modes, two of which orig i nate in an in -ter nal os cil la tor.

The os cil la tor mode is se lected at de vice pro gram ming time and can not bechanged at runtime. The con fig u ra tion bits, which are non vol a tile flags set dur ingde vice pro gram ming, de ter mine which os cil la tor mode is used by the pro gram, ac -cord ing to those sup ported by the de vice. Some mid-range PICs (like the 16F684)sup port unique os cil la tor modes that are not gen er ally found in other mem bers ofthe mid-range fam ily. The fol low ing are the most com mon mid-range os cil la tormodes:

1. LP, low fre quency crys tal

2. XT, crys tal res o na tor

3. HS, high speed crys tal res o na tor

4. RC, ex ter nal re sis tor/ca pac i tor

5. EXTRC, ex ter nal re sis tor/ca pac i tor

6. EXTRC, ex ter nal re sis tor/ca pac i tor with CLKOUT

7. INTRC, in ter nal 4-MHz re sis tor/ca pac i tor

8. INTRC, in ter nal 4-MHz re sis tor/ca pac i tor with CLKOUT

The re sis tor/ca pac i tor os cil la tor op tion is the cheap est to im ple ment but also theleast ac cu rate one. This op tion should be used only in sys tems where clock ac cu -racy and con sis tency are not is sues. The low-fre quency crys tal op tion is the one

Ar chi tec ture and In struc tion Set 97

Page 119: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

with the low est power con sump tion and is suit able for sys tems where power con -sump tion is an im por tant fac tor.

The first three os cil la tor modes (LP, XT, and HS) al low se lect ing dif fer ent fre -quency ranges. The HS has the high est fre quency range and con sumes the mostpower. The XT op tion is based on a stan dard crys tal res o na tor and has mid-rangepower con sump tion. The LP op tion has low gain and con sumes the least power ofthe three crys tal modes. The gen eral rule is to use the os cil la tor with the low est pos -si ble gain that still meets the cir cuit re quire ments. The RC mode with EXTRC andCLKOUT fea tures have the same func tion al ity as the straight RC os cil la tor op tion.

The XT op tion (crys tal res o na tor) can be pro vided in a con ve nient ce ramic pack -age. This de vice, called a ce ramic res o na tor, con tains three pins. The ones on theex tremes are con nected to the cor re spond ing os cil la tor in put lines on the PIC, la -beled OSC1 and OSC2. The cen ter pin is con nected to ground. Fig ure 7-8 shows thecir cuit di a gram for an os cil la tor and a crys tal res o na tor.

Fig ure 7-8 Cir cuit Di a grams for a Ce ramic Res o na tor and a Crys tal Os cil la tor.

Al ter na tively, the os cil la tor func tion can be pro vided by an in te grated cir cuit(such as the ICS502) that can gen er ate sev eral dif fer ent clock fre quen cies. Somecir cuits, es pe cially in PIC dem on stra tion boards, con tain jumper pins that al low se -lect ing among several clock rates.

7.4.2 Sys tem Re setThe re set mech a nism is used to place the PIC in a known con di tion, to gain con trol ofa run-away or hung-up pro gram, as a forced in ter rupt in pro gram ex e cu tion, or tomake the de vice ready at pro gram load time. The pro ces sor’s !MCLR pin pro duces there set ac tion when it reads logic zero. The ex cla ma tion sign pre ced ing the pin’s name(or al ter na tively, as a line over the text) in di cates that the ac tion is ac tive-low. To pre -

98 Chap ter 7

XTAL

C1

C2

OSC

Page 120: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

vent ac ci den tal re sets the !MCLR pin must be con nected to the pos i tive volt age sup plythrough a 5K or 10K re sis tor. When a re sis tor serves to place a logic 1 on a line, it iscalled a pull-up re sis tor.

The mid-range PICs are ca pa ble of sev eral re set ac tions:

• Re set dur ing power on (POR)

• !MCLR re set dur ing nor mal op er a tion

• Re set dur ing SLEEP mode

• Watch dog timer re set (WDT)

• Brown-out re set (BOR)

• Par ity er ror re set

The most com mon re set sources are the first two in the pre ced ing list. POR re setserves to bring all PIC reg is ters to an ini tial state, in clud ing the pro gram coun terreg is ter. This ac tion is taken au to mat i cally by the microcontroller. The sec ondsource of a re set ac tion takes place when the !MCLR line is in ten tion ally broughtdown, usu ally by the ac tion of a pushbutton re set switch. This switch is use ful dur -ing pro gram de vel op ment be cause it pro vides a way of force fully re-start ing ex e cu -tion. Fig ure 7-9 shows a typ i cal wir ing of the !MCLR line to pro vide a reset activatedby a pushbutton switch. The cir cuit in cludes an LED that lights up when the poweris on.

Fig ure 7-9 Typical Wir ing of the Re set Switch.

User RAM mem ory is not af fected by a re set. The PICs gen eral-pur pose reg is ters(GPRs are in an un known state dur ing power up and are not changed by re set). SFRreg is ters, on the other hand, are re set to an ini tial state. The ini tial iza tion con di tions for each of the SFRs can be found in the de vice data sheet. The most im por tant ofthese is per haps the pro gram coun ter (PC), which is re set to zero. This ac tion di -rects ex e cu tion to the first in struc tion, ef fec tively re start ing the pro gram.

Ar chi tec ture and In struc tion Set 99

16F84A

+5v

+5v

R=

10

K

R=

38

0 O

hm RA2

RA3

RA4/TOCKI

!MCLR

Vss

RB0/INT

RB1

RB2

RB3

1

2

3

4

5

6

7

8

9

18

17

16

15

14

13

12

11

10

RA1

RA0

OSC1

OSC2

Vdd

RB7

RB6

RB5

RB4

POWERON/OFF LED

RESETSWITCH

Page 121: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Dur ing power-up, the pro ces sor it self ini ti ates a re set when the power sup plyvolt age goes from 1.2 to 1.8V. Sev eral bits in var i ous reg is ters are re lated to the re set ac tion, but these are not avail able in all mid-range de vices. For ex am ple, somehigh-end de vices in the mid-range group, such as the 16F87x, con tain two bits in thePCON reg is ter that are re set re lated. One of them (named !POR) al lows de ter min ing the power-on re set sta tus. The other one (named !BOR) informs about thebrown-out re set sta tus. How ever, the PCON reg is ter does not exist in the 16F84 or16F84A.

7.4.3 In ter rupts

The in ter rupt mech a nism pro vides a way of hav ing the microcontroller re spond toevents as they oc cur, rather than be ing forced to poll de vices in or der to de ter minetheir state. The in ter rupt is said to work like a “tap on the shoul der” of themicrocontroller, call ing its at ten tion to an event that re quires an ac tion or de vice thatneeds ser vic ing. Af ter re spond ing to or ig nor ing the in ter rupt, the CPU re sumes pro -cess ing where it left off.

In com puter tech nol o gies the in ter rupt mech a nism is a com pli cated hard -ware/soft ware sys tem that of ten in cludes a pro gram ma ble in ter rupt con trol ler. Pro -ces sors and mi cro pro ces sors usu ally sup port hard ware and soft ware in ter rupts and maskable and nonmaskable in ter rupts, which can orig i nate in prac ti cally any de vice con nected to the sys tem. In PICs, the in ter rupt mech a nism is much sim pler and var -ies con sid er ably even among members of the same PIC family.

All PICs of the mid-range fam ily sup port in ter rupts to some de gree. The in ter ruptsource usu ally orig i nates in one of the hard ware mod ules, al though some sourcescan gen er ate more than one in ter rupt. For ex am ple, the 16F684 sup ports eleven in -ter rupt sources. The fol low ing are com mon in ter rupt sources in the mid-range fam -ily, al though not all are supported by every PIC.

• INT pin in ter rupt (ex ter nal interrupt)

• TMR0 over flow in ter rupt

• PORTX change in ter rupt

• Com para tor change in ter rupt

• Par al lel slave port in ter rupt

• USART in ter rupts

• Re ceive and trans mit in ter rupt

• A/D con ver sion com plete in ter rupt

• LCD in ter rupt

• Data EEPROM write com plete in ter rupt

• Timer over flow in ter rupts

• CCP in ter rupt

• SSP interrupt

100 Chap ter 7

Page 122: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Sev eral SFRs are re lated to the in ter rupt sys tems. The INTCON reg is ter pro videsin ter rupt en abling and con trol, and the PIE1, PIE2, PIR1, and PIR2 reg is ters havespe cific de vice-re lated func tions. Pro gram ming in ter rupts are dis cussed in the con -text of the cor re spond ing op er a tions later in this book.

7.5 Mid-Range In struc tion SetThe mid-range PIC in struc tion set con sists of 35 in struc tions, di vided into three gen -eral groups:

• Byte-ori ented and byte-wise file reg is ter op er a tions

• Bit-ori ented and bit-wise file reg is ter op er a tions

• Lit eral and con trol in struc tions

Ta ble 7.1 lists and briefly de scribes each in struc tion in the mid-range set.

Ta ble 7.1

Mid-Range PIC In struc tion Set

BITSMNEMONIC OPERAND DESCRIPTION CYCLES AFFECTED

BYTE-ORIENTED OPERATIONS:ADDWF f,d Add w and f 1 C,DC,ZANDWF f,d AND w with f 1 ZCLRF f Clear f 1 ZCLRW - Clear w 1 ZCOMF f,d Com ple ment f 1 ZDECF f,d Dec re ment f 1 ZDECFSZ f,d Dec re ment, skip if 0 1(2) -INCF f,d In cre ment f 1 ZINCFSZ f,d In cre ment, skip if 0 1(2) -IORWF f,d In clu sive OR w and f 1 ZMOVF f,d Move f 1 ZMOVWF f Move w to f 1 -NOP - No op er a tion 1 -RLF f,d Ro tate left 1 C

through carry RRF f,d Ro tate right 1 C

through carrySUBWF f,d Sub tract w from f 1 C,DC,ZSWAPF f,d Swap nib bles in f 1 -XORWF

BIT-ORIENTED OPERATIONSBCF f,b Bit clear in f 1 -BSF f,b Bit set in f 1 -BTFSC f,b Bit test, skip 1 -

if clearBTFSS f,b Bit test, skip 1 -

if set

(con tin ues)

Ar chi tec ture and In struc tion Set 101

Page 123: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Table 7.1

Mid-Range PIC In struc tion Set

BITSMNEMONIC OPERAND DESCRIPTION CYCLES AFFECTED

LITERAL AND CONTROL OPERATIONSADDLW k Add lit eral and w 1 C,DC,ZANDLW k AND lit eral and w 1 ZCALL k Call pro ce dure 2 -CLRWDT - Clear Watch dog timer 1 TO,PDGOTO k Go to ad dress 2 -IORLW k In clu sive OR lit eral 1 Z

with wMOVLW k Move lit eral to w 1 -RETFIE - Re turn from in ter rupt 2 -RETLWk - Re turn lit eral in w 2 -RETURN - Re turn from pro ce dure 2 -SLEEP - Go into SLEEP mode 1 TO,PDSUBLW k Sub tract lit eral and w 1 C,DC,ZXORLW k Ex clu sive OR lit eral 1 Z

with w

Leg end:f = file reg is terd = des ti na tion: 0 = w reg is ter

1 = file reg is terb = bit po si tionk = 8-bit con stant

7.5.1 STATUS and OPTION Reg is ters

The STATUS reg is ter is one of the SFRs in mid-range PICs. The bits in this reg is ter re -flect the arith me tic sta tus of the ALU, the RESET sta tus, and the bits that se lect whichmem ory bank is cur rently be ing ac cessed. Be cause the bank se lec tion bits are in theSTATUS reg is ter, it must be pres ent and at the same rel a tive po si tion in ev ery bank.Fig ure 7-10 is a bitmap of the STATUS reg is ter.

The STATUS reg is ter can be the des ti na tion for any in struc tion. If it is, and the Z,DC, or C bits are af fected, then the write op er a tion to these bits is dis abled. In ad di -tion, the TO and PD bits are not writable. Some in struc tions may have an un ex -pected ac tion on the STATUS reg is ter bits; for ex am ple, the in struc tion

clrf STATUS

clears the up per 3 bits, sets the Z bit, and leaves all other bits un changed. For this rea -son it is rec om mended that only in struc tions that do not change the Z, C, and DC bitsbe used to al ter the STATUS reg is ter. The only ones that qual ify are BCF, BSF, SWAPF,and MOVWF.

102 Chap ter 7

Page 124: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 7-10 STATUS Reg is ter Bitmap.

The OPTION reg is ter is ac tu ally named the OPTION_REG to avoid a name clashwith the op tion in struc tion. The OPTION_REG reg is ter con tains sev eral bits re latedto in ter rupts, the in ter nal tim ers, and the Watch dog timer. Fig ure 7-11, on the fol -low ing page, is a bitmap of the OPTION_REG reg is ter.

Ar chi tec ture and In struc tion Set 103

IRP RP-1 RP-0 TO PD Z DC C

7 6 5 4 3 2 1 0bits:

bit 7 IRP: Register Bank Select bit (used for indirect addressing) 1 = Bank 2, 3 (0x100 - 0x1ff) 0 = Bank 0, 1 (0x000 - 0xff) For devices with only Bank0 and Bank1 the IRP bit is reserved, always maintain this bit clear.bit 6:5 RP1:RP0: Register Bank Select bits (used for direct addressing) 11 = Bank 3 (0x180 - 0x1ff) 10 = Bank 2 (0x100 - 0xx17f) 01 = Bank 1 (0x80 - 0xff) 00 = Bank 0 (0x00 - 0x7f) Each bank is 128 bytes. For devices with only Bank0 and Bank1 the IRP bit is reserved, always maintain this bit clear.bit 4 TO: Time-out bit 1 = After power-up, CLRWDT instruction, or SLEEP instruction 0 = A WDT time-out occurredbit 3 PD: Power-down bit 1 = After power-up or by the CLRWDT instruction 0 = By execution of the SLEEP instructionbit2 Z: Zero bit 1 = The result of an operation is zero 0 = The result of an operation is not zerobit 1 DC: Digit carry/borrow bit for ADDWF, ADDLW, SUBLW, and SUBWF instructions. For borrow the polarity is reversed. 1 = A carry-out from the 4th bit of the result 0 = No carry-out from the 4th bit of the resultbit 0 C: Carry/borrow bit for ADDWF, ADDLW, SUBLW, and SUBWF instructions 1 = A carry-out from the most significant bit 0 = No carry-out from the most significant bit

Page 125: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 7-11 Bitmap of the OPTION_REG Reg is ter.

7.6 EEPROM Data Stor ageEEPROM (pro nounced dou ble-e PROM or e squared PROM) stands for Elec tri -cally-Eras able Pro gram ma ble Read-Only Mem ory. EEPROM mem ory is used in com -put ers and dig i tal de vices as non vol a tile stor age. EEPROM is not RAM, as RAMmem ory is vol a tile and EEPROM re tains its data af ter power is re moved. EEPROMmem ory is found in USB flash drives and in the non vol a tile stor age of sev eralmicrocontrollers, in clud ing many PICs.

The one ad van tage of EEPROM mem ory is that it can be erased and writ ten elec -tron ically, with out re mov ing the chip. The pre de ces sor tech nol ogy, named EPROM,

104 Chap ter 7

RPBU INTEDG TOCS TOSE PSA PS2 PS1 PS0

7 6 5 4 3 2 1 0bits:

bit 7 RBPU: PORTB Pull-up Enable bit 1 = PORTB pull-ups are disabled 0 = PORTB pull-ups are enabled by individual port latch valuesbit 6 INTEDG: Interrupt Edge Select bit 1 = Interrupt on rising edge of INT pin 0 = Interrupt on falling edge of INT pinbit 5 T0CS: TMR0 Clock Source Select bit 1 = Transition on T0CKI pin 0 = Internal instruction cycle clock (CLKOUT)bit 4 T0SE: TMR0 Source Edge Select bit 1 = Increment on high-to-low transition on T0CKI pin 0 = Increment on low-to-high transition on T0CKI pinbit 3 PSA: Prescaler Assignment bit 1 = Prescaler is assigned to the WDT 0 = Prescaler is assigned to the Timer0bit 2-0 PS2:PS0: Prescaler Rate Select bits RATES: bits TMR0 WDT 000 1:2 1:1 001 1:4 1:2 010 1:8 1:4 011 1:16 1:8 100 1:32 1:16 101 1:64 1:32 110 1:128 1:64 111 1:256 1:138

Page 126: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

re quired that the chip be re moved from the cir cuit and placed un der ul tra vi o letlight. EEPROM sim pli fies the eras ing and re writ ing pro cess. In the PIC ar chi tec ture, EEPROM data mem ory re fers to both on-board EEPROM mem ory and to EEPROMmem ory ICs as sep a rate cir cuit com po nents. In gen eral, EEPROM el e ments are clas -si fied ac cord ing to their elec tri cal in ter faces into se rial and par al lel. Most EEPROMmem o ries used in PICs are se rial EEPROMs, also called SEEPROMs. The typ i cal use of se rial EEPROM on-board mem ory and EEPROM on ICs is in the stor age of pass -words, codes, con fig u ra tion set tings, and other in for ma tion to be re mem bered af terthe sys tem is turned off. For ex am ple, a PIC-based se cu rity sys tem can useEEPROM mem ory to store the sys tem pass word. Be cause EEPROM can be writ ten,the user can change this password and the new one will also be remembered.

7.6.1 EEPROM in Mid-Range PICsThe mid-range PICs are equipped with EEPROM mem ory in three pos si ble sizes: 64bytes, 128 bytes, and 256 bytes. EEPROM mem ory al lows read and write op er a tions.This mem ory is not mapped into the pro ces sor’s data or pro gram area, but in a sep a -rate block that is ad dressed through some SFRs. The reg is ters re lated to EEPROM op -er a tions are

• EECON1

• EECON2 (not a phys i cally im ple mented reg is ter)

• EEDAT

• EEADR

EECON1 con tains the con trol bits, and EECON2 is used to ini ti ate the EEPROMread and write op er a tions. The 8-bit data item to be writ ten must first be stored inthe EEDATA reg is ter, while the ad dress of the lo ca tion in EEPROM mem ory isstored in the EEADR reg is ter. The EEPROM ad dress space al ways starts at 0x00 and ex tends lin early to max i mum in the device.

When a write op er a tion is per formed, the con tents of the EEPROM lo ca tion is au -to mat i cally erased. The EEPROM mem ory used in PICs is rated for high erase/writecy cles. EEPROM pro gram ming is the topic of Chap ter 14.

Ar chi tec ture and In struc tion Set 105

Page 127: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

This page intentionally left blankThis page intentionally left blank

Page 128: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Chap ter 8

Em bed ded Sys tems Pro gram ming

8.1 As sem bly versus High-Level Lan guagesSome PIC microcontrollers can be pro grammed in high-level lan guages or in their na -tive ma chine lan guage. Ma chine lan guage pro gram ming is fa cil i tated by the use of anas sem bler pro gram, and thus be comes as sem bly lan guage pro gram ming. Al though as -sem bly lan guage is the most used and pop u lar way of PIC pro gram ming, some PICmicrocontrollers can also be pro grammed in high-level lan guages such as C or BASIC.

The ma jor ar gu ment in fa vor of high-level lan guages is their ease of use and theirfaster learn ing curve. The ad van tages of as sem bly lan guage, on the other hand, arebetter con trol and greater ef fi ciency. An other con sid er ation is that only higher-level PICs can be pro grammed in high-level lan guages. The mid-range PICs, in clud ing the16F877, 16F84, and 16F684 cov ered in this book can only be pro grammed in as sem -bly lan guage, which set tles the pro gram ming lan guage issue in this context.

8.1.2 Em bed ded Sys temsAt the heart of an em bed ded sys tem is a microcontroller (such as a PIC), some timessev eral of them. These de vices are pro grammed to per form one or, at most, a fewtasks. In the most typ i cal case an em bed ded sys tem also in cludes one or more “pe riph -eral” cir cuits that are op er ated by ded i cated ICs or use some func tion al ity con tainedin the microcontroller it self. The term “em bed ded sys tem” re fers to the fact that thede vice is of ten found in side an other one; for in stance, the con trol cir cuit is em bed dedin a mi cro wave oven. Fur ther more, em bed ded sys tems do not have (in most cases)gen eral-pur pose de vices such as hard disk drives, video con trol lers, print ers, and net -work cards.

A typ i cal em bed ded sys tem is a con trol for a mi cro wave oven. In this case thecon trol ler in cludes a timer, so that var i ous op er a tions can be clocked; a tem per a -ture sen sor that pro vides in for ma tion re gard ing the heat in side the oven; per haps amo tor to op tion ally ro tate a ta ble or tray; a sen sor to de tect when the oven door isopen; and a set of pushbutton switches to se lect the var i ous op er a tional op tions. Apro gram run ning on the em bed ded microcontroller reads the com mands and pa ram -e ters that are in put through the key board, pro grams the timer and the ro tat ing ta ble,

107

Page 129: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

de tects the state of the door, and turns the heat ing el e ment on and off as re quired by the user’s se lec tion. Many other daily de vices in clud ing au to mo biles, dig i tal cam -eras, cell phones, and home appliances use embedded systems and many of themare PIC based.

The de vel op ment pro cess of an em bed ded sys tem con sists of the fol low ing steps:

• De fine the sys tem spec i fi ca tions. This step in cludes list ing the func tions that thesys tem is to per form and de ter min ing the tests that will be used to val i date their op -er a tions.

• Se lect the sys tem com po nents ac cord ing to the spec i fi ca tions. This step in cludeslo cat ing the microcontroller that best suits the sys tem as well as the other hard ware com po nents.

• De sign the sys tem hard ware. This in cludes draw ing the cir cuit di a grams.

• Im ple ment a pro to type of the sys tem hard ware by means of breadboards, wirewrapping, or an other prototyping tech nol ogy.

• De velop, load, and test the soft ware. Load ing soft ware into a PIC is re ferred to as“blow ing” the PIC.

• Im ple ment the fi nal sys tem and test hard ware and soft ware.

8.2 In te grated De vel op ment En vi ron mentThe PIC as sem bly lan guage de vel op ment sys tem pro vided pro vided by Micro chip isnamed MPLAB. The pack age is fur nished as an in te grated de vel op ment en vi ron ment(IDE) and can be down loaded from the com pany’s website at www.micro chip.com.One lim i ta tion of the MPLAB pack age is that it is pres ently fur nished only for the PC. If you are a Mac, Unix, or Linux user, you will not be able to use MPLAB. How ever, otherde vel op ment sys tems for Mac and Linux are avail able on the Web. The MPLAB IDE isin tended for soft ware de vel op ment of em bed ded systems. The soft ware in an em bed -ded system is usu ally fixed and can not be eas ily changed. For this rea son it is called“firm ware.” The MPLAB de vel op ment sys tem, or in te grated de vel op mentenvironment, con sists of a sys tem of pro grams that runs on a PC. This soft ware pack -age is de signed to help de velop, edit, test, and de bug PIC code.

In stall ing the MPLAB pack age is straight for ward and sim ple. The pack age in -cludes the fol low ing com po nents:

• MPLAB editor. This tool al lows cre at ing and ed it ing the as sem bly lan guage sourcecode. It be haves very much like any Win dows ed i tor and con tains the stan dard ed i -tor func tions in clud ing cut and paste, search and re place, and undo and redo func -tions.

• MPLAB as sem bler. The as sem bler reads the source file pro duced in the ed i tor andgen er ates ei ther ab so lute or relocatable code. Ab so lute code ex e cutes di rectly inthe PIC. Relocatable code can be linked with other sep a rately as sem bled mod ules or with li brar ies.

• MPLAB linker. This com po nent com bines mod ules gen er ated by the as sem bler with li brar ies or other ob ject files, into a sin gle ex e cut able file in .hex for mat.

108 Chap ter 8

Page 130: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

• MPLAB debuggers. Sev eral debuggers are com pat i ble with the MPLAB de vel op -ment sys tem. Debuggers are used to sin gle-step through the code, breakpoint atcrit i cal places in the pro gram, and watch vari ables and reg is ters as the pro gram ex e -cutes. In ad di tion to be ing a powerful tool for de tect ing and fix ing pro gram er rors,debuggers prove an in ter nal view of the pro ces sor, which is a valu able learn ing tool.

• MPLAB in-cir cuit em u la tors. These are de vel op ment tools that al low per form ingba sic de bug ging func tions while the pro ces sor is in stalled in the cir cuit.

Fig ure 8-1 is a screen im age of the MPLAB pro gram. The ap pli ca tion on the ed i tor win dow is one of the pro grams de vel oped later in this book.

Fig ure 8-1 Screen Im age of the MPLAB IDE.

8.2.1 In stall ing MPLABIn the nor mal in stal la tion, the MPLAB ex e cut able will be placed in the fol low ing path:

C:\Pro gram Files\Micro chip\MPASM Suite

Once the de vel op ment en vi ron ment is in stalled, the soft ware is ex e cuted byclick ing the MPLAB IDE icon or dou ble-click ing the ex e cut able file. It is usu ally agood idea to drag the icon onto the desk top so that the pro gram can be eas ilyactivated.

Once the MPLAB soft ware is in stalled, one should check that the ap pli ca tionswere placed in the cor rect paths and fold ers. Fail ure to do so pro duces as sem -bly-time fail ure er rors with cryp tic mes sages. To check the cor rect path for the soft -ware, open the MPLAB Pro ject menu and se lect the Se lect Lan guage Toolsuitecom mand. Fig ure 8-2 shows the com mand screen in MPLAB ver sion 8.0.

Em bed ded Sys tems Pro gram ming 109

Page 131: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 8-2 MPLAB Se lect Lan guage Toolsuite Screen.

In the Se lect Lan guage Toolsuite win dow, make sure that the file lo ca tions for allexecutables co in cide with the ac tual in stal la tion path for the soft ware. If in doubt,use the <Browse> but ton to nav i gate through the in stal la tion di rec to ries un til theex e cut able pro gram is lo cated. In Fig ure 8-2 the lo ca tion of the mpasmwin.exe isshown. Fol low the same pro cess for all the executables in the Micro chip MPASMToolsuite window.

A more de tailed con trol over the lo ca tion of the var i ous in di vid ual tools is pro -vided by the Set Lan guage Tools Lo ca tion com mand, also in the Pro ject menu. Thiscom mand al lows set ting the in stal la tion path not only to the ma jor suites, but alsoto the in di vid ual tools. Fig ure 8-3 shows the dis play screen of this com mand.

Fig ure 8-3 MPLAB Set Lan guage Tools Lo ca tion Screen.

110 Chap ter 8

Page 132: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

8.2.2 MPLAB Pro jectIn the MPLAB con text, a pro ject is a group of files gen er ated or rec og nized by the IDE.Fig ure 8-4 shows the struc ture of an as sem bly lan guage pro ject.

Fig ure 8-4 MPLAB Pro ject Files.

In Fig ure 8-4 an as sem bly lan guage source file (prog1.asm) and an op tional pro -ces sor-spe cific in clude file are used by the as sem bler pro gram (MPASM) to pro ducean ob ject file (prog1.o). Op tion ally, other sources and other in clude files may formpart of the pro ject. The re sult ing ob ject file, as well as one or more op tional li brar -ies, and a de vice-spe cific script file (de vice.lkr), are then fed to the linker pro gram(MPLINK), which gen er ates a ma chine code file (prog1.hex) and sev eral sup portfiles with list ings, er ror re ports, and map files. It is the .hex file that is used to blowthe PIC.

In ad di tion to the files in Fig ure 8-4, oth ers may also be pro duced by the de vel op -ment en vi ron ment ac cord ing to the se lected tools and op tions. For ex am ple, the as -sem bler or the linker can gen er ate a file with the ex ten sion .cod, which con tainssym bols and ref er ences used in debugging.

Pro jects can be cre ated us ing the <New> com mand in the Pro ject menu. The pro -gram mer then pro ceeds to con fig ure the pro ject man u ally and add to it the re quiredfiles. An al ter na tive op tion that sim pli fies cre at ing a new pro ject is to use the <Pro -ject Wiz ard> com mand in the Pro ject menu. The Wiz ard will prompt for all the de ci -sions and op tions that are required, as follows:

Em bed ded Sys tems Pro gram ming 111

prog1.asm

PxxFyy.inc

sup.lib device.lkr

prog1.lst prog1.mapprog1.hex prog1.err

prog1.o

MPASM(assembler)

MPLINK(linker)

MPLIB(librarian)

Page 133: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

1. De vice se lec tion. Here the pro gram mer se lects the PIC hard ware for the pro ject,for ex am ple 16F84A.

2. Se lect Lan guage Toolsuite. This screen is the same one shown in Fig ure 8-2. Its pur -pose is to make sure that the proper de vel op ment tools and paths are ac tive.

3. Next, the Wiz ard prompts the user for a pro ject name and di rec tory. It is pos si ble tocre ate a new di rec tory at this time.

4. In the next step the user is given the op tion of add ing ex ist ing files to the pro jectand re nam ing these files if nec es sary. Be cause most pro jects re use a tem plate, anin clude file, or other pre ex ist ing re sources, this can be a use ful op tion.

5. Fi nally, the Wiz ard dis plays a sum mary of the pro ject pa ram e ters. When the userclicks on the <Fin ish> but ton the pro ject is cre ated and pro gram ming can be gin.

Fig ure 8-5 is the dis play of the fi nal wiz ard screen.

Fig ure 8-5 Fi nal Screen of the Pro ject Cre ation Wiz ard.

8.2.3 Pro ject Build Op tions

The <Build Op tions: Pro ject> com mand in the Pro ject menu al lows the user to cus -tom ize the de vel op ment en vi ron ment. Of the tabs avail able on the Build Op tionsscreen, the MPASM As sem bler one is prob a bly the most used. The screen is shown inFig ure 8-6.

112 Chap ter 8

Page 134: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 8-6 MPASM As sem bler Tab in the Build Op tions Screen.

The MPASM As sem bler tab al lows per form ing the fol low ing customizations:

1. Dis able/en able case sen si tiv ity. Nor mally the as sem bler is case sen si tive. En ablingthis op tion turns all vari ables and la bels to up per case.

2. Se lect the De fault Radix. Num bers with out for mat ting codes are as sumed to behex, dec i mal, or oc tal ac cord ing to the se lected op tion.

3. The Macro Def i ni tion win dow al lows add ing macro di rec tives. Mac ros are dis -cussed later in this chap ter.

4. The Use Al ter nate Set tings textbox is pro vided for com mand line com mands innon-GUI en vi ron ments.

5. The Re store De faults box turns off all cus tom con fig u ra tions.

Em bed ded Sys tems Pro gram ming 113

Page 135: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

8.2.4 Build ing the Pro jectOnce all the op tions have been se lected, the in stal la tion checked, and the as sem blylan guage source file writ ten or im ported, the de vel op ment en vi ron ment can be madeto build the pro ject. Build ing con sists of call ing the as sem bler, the linker, and anyother sup port pro gram in or der to gen er ate the files shown in Fig ure 8-4 and any oth -ers that may re sult from a par tic u lar pro ject or IDE con fig u ra tion.

The build pro cess is ini ti ated by se lect ing the <Build All> com mand in the Pro ject menu. Once the build ing con cludes, a screen la beled Out put is dis played show ingthe re sults of the build op er a tion. If the build suc ceeded, the last line of the Out putscreen will show this re sult. Fig ure 8-7 shows the out put screen af ter a suc cess fulbuild.

Fig ure 8-7 Out put Win dow Show ing the Build Com mand Re sult.

8.2.5 Quickbuild Op tion

Very of ten dur ing pro to type de vel op ment we need to cre ate a sin gle ex e cut able filewith out hav ing to deal with the com plex ity of a full-fledged pro ject. For this case,MPLAB pro vides the Quickbuild op tion in the Pro ject menu. The re sult ing .hex file can be used to blow a PIC in the con ven tional man ner and con tains all the nec es sary de -bug ging in for ma tion.

We have used the Quickbuild op tion for most of the pro grams de vel oped for thisbook. The typ i cal com mand se quence for us ing the Quickbuild op tion is as fol lows:

1. Make sure the cor rect PIC de vice is se lected by us ing the Con fig ure>Se lect De vicecom mand.

2. Make sure the Quickbuild op tion is ac tive by se lect ing Pro ject>Set Ac tive Pro -ject>None. This places the en vi ron ment in the Quickbuild mode.

114 Chap ter 8

Page 136: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

ResetStep out (of subroutine)Step over (subroutine)Step into (subroutine)AnimateHaltRun (to breakpoint)

Page 137: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

In or der for the sim u la tor to work, the pro gram must first be suc cess fully as sem -bled. The most com monly used sim u la tor method is sin gle-step ping through thecode and break points. A break point is a mark at a pro gram line at which the sim u la -tor will stop and wait for user ac tions.

Break points pro vide a way of in spect ing pro gram re sults at a par tic u lar place inthe code. Sin gle-step ping is ex e cut ing the pro gram one in struc tion at a time. Thethree but tons la beled <Step...> in Fig ure 8-8 are used in sin gle-step ping. The firstone al lows break ing out of a sub rou tine or pro ce dure. The sec ond one is for by pass -ing a pro ce dure or sub rou tine while in step mode. The third one sin gle-steps intothe program instruction that follows.

Break points are set by dou ble-click ing at the de sired line while us ing the ed i tor.The same ac tion re moves an ex ist ing break point. Lines in which break points havebeen placed are marked, on the left doc u ment mar gin, by a let ter “B” en closed in ared cir cle. Right-click ing while the cur sor is on the pro gram ed i tor screen pro vides a con text menu with sev eral sim u la tor-re lated com mands. These in clude com mandsto set and clear break points, to run to the cur sor, and to set the pro gram coun ter tothe code location at the cursor.

The View menu con tains sev eral com mands that pro vide use ful fea tures dur ingpro gram sim u la tion and de bug ging. These in clude com mands to pro gram mem ory,file reg is ters, EEPROM, and spe cial func tion reg is ters. One com mand in par tic u lar,named <Watch>, pro vides a way of in spect ing the con tents of FSRs and GPRs on the same screen. The <Watch> com mand dis plays a pro gram win dow that con tains ref -er ence to all file reg is ters used by the pro gram. The user then se lects which reg is -ters to view and these are shown in the Watch win dow. The Watch window is shownin Figure 8-9.

Fig ure 8-9 Use of Watch Win dow in MPLAB SIM.

116 Chap ter 8

Page 138: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

When the pro gram is in the sin gle-step mode or break point mode, the con tents ofthe var i ous reg is ters can be ob served in the Watch win dow. Those that havechanged be cause the last step or break point are dis played in red. The user can clickon the cor re spond ing ar rows on the Watch win dow to dis play all the sym bols or reg -is ters. The <Add Sym bol> or <Add FSR> but ton is then used to dis play the item onthe Watch screen. Four dif fer ent Watch win dows can be en abled, la beled Watch 1 toWatch 4, at the bot tom of the screen in Figure 8-9.

An other valu able tool avail able from the View menu is the one la beled <Sim u la -tor Trace>. The Sim u la tor Trace win dow pro vides a view of the cur rent ma chine in -struc tion com bined with a win dow that dis plays the source code. The Sim u la torTrace win dow is shown in Figure 8-10.

Fig ure 8-10 MPLAB SIM Sim u la tor Trace Win dow.

8.3.2 MPLAB Hard ware Debuggers

A more pow er ful and ver sa tile de bug ging tool is a hard ware debugger, some timescalled an in-cir cuit debugger. Hard ware debuggers al low trac ing, breakpointing, andsin gle-step ping through code while the PIC is in stalled in the tar get cir cuit. The typ i cal in-cir cuit debugger re quires sev eral hard ware com po nents, as shown in Fig ure 8-11.

Em bed ded Sys tems Pro gram ming 117

Page 139: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 8-11 Com po nents of a Typ i cal Hard ware Debugger.

The em u la tor pod with power sup ply and com mu ni ca tions ca ble pro vides the ba -sic com mu ni ca tions and func tion al ity of the debugger. The com mu ni ca tions line be -tween the PC and the debugger can be an RS-232, a USB, or a par al lel port line. Thepro ces sor mod ule fits into a slot at the front of the pod mod ule. The pro ces sor is de -vice spe cific and pro vides these func tions to the debugger. A flex ca ble con nects the pro ces sor mod ule to an in ter change able de vice adapter that al lows con nect ing tothe sev eral PICs sup ported by the sys tem. The tran si tion socket al lows con nect ingthe de vice adapter to the tar get hard ware. A sep a rate socket al lows con nect inglogic probes to the debugger.

Micro chip pro vides two mod els of their in-cir cuit hard ware debuggers, whichthey call In Cir cuit Em u la tors, or ICE. The ICE 2000 is de signed to work with mostPICs of the mid-range and lower se ries, while the ICE 4000 is for the PIC18xhigh-end fam ily of PICs. Re cently Micro chip has re leased an in-cir cuit debugger des -ig nated as ICD 2 that of fers many of the fea tures of its full-fledged in-cir cuit em u la -tors at much re duced prices. One of the dis ad van tages of the ICD 2 sys tem is that it

118 Chap ter 8

Power cable

Emulator pod

Processormodule

Cable tocircuit

Adapter

Transitionsocket

Logicprobe

connector

Communications cable

Page 140: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

re quires the ex clu sive use of some hard ware and soft ware re sources in the tar get.Fur ther more, the ICD re quires that the sys tem be fully func tional. The ICEs, on theother hand, pro vide mem ory and clock so that the pro ces sor can run code even if itis not con nected to the ap pli ca tion board.

8.3.3 Im pro vised Debugger

The func tion al ity of an ac tual hard ware debugger can be re placed with a lit tle in ge nu -ity and a few lines of code. Most PICs are equipped with EEPROM mem ory. Pro gram -mers (cov ered in the fol low ing sec tion) have the abil ity to read all the data stored inthe PIC, in clud ing EEPROM. These two facts can be com bined in or der to ob tainruntime in for ma tion with out re sort ing to a hard ware debugger.

Sup pose a de fec tive ap pli ca tion is sus pect of not find ing the ex pected value in aPIC port. The de vel oper can write a few lines of code to store the port value on anEEPROM mem ory cell. An end less loop fol low ing this op er a tion en sures that thestored value is not changed. Now the PIC is in serted in the cir cuit and the ap pli ca -tion ex e cuted. When the end less loop is reached, the PIC is re moved from the cir -cuit and placed back in the pro gram mer. The value stored in EEPROM can now bein spected so as to de ter mine the runtime state of the ma chine. In many cases thissim ple trick is less com pli cated and time con sum ing than set ting up a hard waredebugger, even if such a device is available.

8.4 Pro gram mersIn the con text of microcontroller tech nol ogy, a pro gram mer is a de vice that al lowstrans fer ring the pro gram onto the chip. The pro cess is called “burn ing” a PIC, or morecom monly “blow ing” a PIC. Most pro gram mers have three com po nents:

1. A soft ware pack age that runs on the PC

2. A ca ble con nect ing the PC to the pro gram mer

3. A pro gram mer de vice

Doz ens of PIC pro gram mers are avail able on the Internet. By re leas ing the pro -gram ming spec i fi ca tions of the PIC to the pub lic with out re quir ing a nondisclosureagree ment, Micro chip orig i nated a “cot tage in dus try.” The com mer cial pro gram -mers on the Internet range from a “no parts” PIC pro gram mer that has been aroundbe cause 1998, to so phis ti cated de vices cost ing hun dreds of dol lars and pro vid ingmany ad di tional fea tures and re fine ments. For the av er age new PIC user, a nice USB pro gram mer with a ZIF socket and the re quired soft ware can be pur chased forabout $50.00. Build-it-your self versions are available for about half this amount.

An al ter na tive pro gram mer is made pos si ble by the fact that some of the newerflash-based PICs can write to their own pro gram mem ory. This al lows plac ing asmall bootloader pro gram in PIC mem ory that will load an ap pli ca tion over theRS-232 or USB lines.

Fig ure 8-12 is a screen cap ture of the driver soft ware for a pop u lar pro gram merfrom MicroPro.

Em bed ded Sys tems Pro gram ming 119

Page 141: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 8-12 Con trol Pro gram for the DIY MicroPro Pro gram mer.

8.5 En gi neer ing PIC Soft ware

The pro gram de vel oper’s main chal lenge is writ ing code that per forms the task athand. In this con text this means writ ing a PIC as sem bly lan guage pro gram that as sem -bles with out er rors (usu ally af ter some ef fort) and makes the cir cuit per form as in -tended. We have al ready re viewed the de vel op ment en vi ron ment (IDE) and thevar i ous hard ware com po nents and soft ware tools. We now fo cus on the var i ous el e -ments that are used in de vel op ing the pro gram it self.

8.5.1 Us ing Pro gram Com ments

One of the first re al iza tions of nov ice pro gram mers is how quickly we for get the rea -son ing and the logic that went into our code. It is com mon that a few weeks, even a few hours, af ter we coded a rou tine, we find that what was ob vi ous then is now un de ci -pher able and that the ideas that were clear in our minds a short time ago now evadeour un der stand ing. The only so lu tion to the vol a til ity of logic is to write good pro gramcom ments that ex plain, not the el e men tary, but the trains of thought be hind our code.

In PIC as sem bly lan guage, the com ment symbol is the semi co lon (;). The pres -ence of a semi co lon in di cates to the as sem bler that ev ery thing that fol lows, to theend of the line, must be ig nored. Us ing com ments ju di ciously and with good taste isthe mark of the ex pert soft ware en gi neer. Pro grams with few, cryp tic, or con fus ingcom ments fall into the cat e gory of “spa ghetti code.” In the pro gram ming lingo, “spa -ghetti code” re fers to a cod ing style that can not be de ci phered or un der stood. Theworst that can be said about one’s pro gram ming style is that one pro duces spa ghetti code.

120 Chap ter 8

Page 142: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

How we use com ments to ex plain our code or even to dec o rate it is a mat ter ofper sonal pref er ence. How ever, there are cer tain com mon-sense rules that should al -ways be con sid ered:

• Do not use pro gram com ments to ex plain the pro gram ming lan guage or re flect onthe ob vi ous.

• Ab stain from hu mor in com ments. Com edy has a place in the world but it is not inpro grams. By the same to ken, stay away from vul gar ity, rac ist or sex ist re marks,and any thing that could be of fen sive. You can never an tic i pate who will read yourcode.

• Write short, clear, read able com ments that ex plain how the pro gram works. Dec o -rate or em bel lish your code us ing ASCII graphics, ac cord ing to your taste.

Pro gram Header

Ev ery pro gram should have a com mented header that con tains, at least, the fol low ingin for ma tion:

• Pro gram name

• Pro gram mer’s or soft ware com pany’s name

• Copy right no tice, if per ti nent

• Tar get de vice or hard ware

• De vel op ment en vi ron ment

• De vel op ment dates

• Pro gram de scrip tion

Some of these el e ments al low var i ous lev els of de tail. For ex am ple, the tar get de -vice can be a sim ple ref er ence to the PIC for which the pro gram is writ ten, amore-or-less de tailed de scrip tion of the tar get sys tem, or a ref er ence to a cir cuit di a -gram or board draw ing. The de vel op ment en vi ron ment can also be de scribed briefly or in abun dant de tail. The dates en try can be a sin gle item that lists the first or thelast pro gram change, or a de tailed de scrip tion of all pro gram changes, tests, and up -dates. The pro gram de scrip tion can be a short sen tence or a mini-man ual on us ingthe ap pli ca tion. In any case, the level of de tail and the con tents of each cat e gory are de ter mined by the pro gram mer’s style, and the complexity and purpose of theapplication.

The fol low ing lines show the header of one of the pro grams de vel oped for thisbook.

; File name: RTC2LCD.asm; Last Up date: June 6, 2011; Au thors: Sanchez and Canton; Pro ces sor: 16F84A;; Dscription:; Pro gram to dem on strate use of the NJU6355 Real Time Clock; IC. Pro gram uses LCD to dis play re sults in hours, min utes,; and sec onds, as fol lows:;

Em bed ded Sys tems Pro gram ming 121

Page 143: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; Top LCD line: H:xx M:yy S:zz;; Ini tial iza tion val ues are in #de fine state ments that start; with i, such as iYear, iMonth, etc.;; For LCD dis play pa ram e ters see the LCDTest2 pro gram. ;; WARNING:; Code as sumes 4Mhz clock. De lay rou tines must be; ed ited for faster clocke

Com mented Ban ners

Very of ten we need to scroll through the code in search of a par tic u lar line or rou tine.Hav ing ban ners that sig nal crit i cal places in the pro gram fa cil i tate this search. Ban -ners are cre ated us ing com ments and a fram ing sym bol, as in the fol low ing code frag -ment:

;===============================; first text string pro ce dure;===============================storeMS1:; Pro ce dure to store in PIC RAM buffer the mes sage; con tained in the code area la beled msg1; ON ENTRY:; vari able pic_ad holds ad dress of text buffer; in PIC RAM; w reg is ter hold off set into stor age area; msg1 is rou tine that re turns the string char ac ters; an a zero ter mi na tor; in dex is lo cal vari able that hold off set into; text ta ble. This vari able is also used for; tem po rary stor age of off set into buffer ; ON EXIT:; Text mes sage stored in buffer;

Some times the pro gram mer needs to em pha size a pro gram area with a large ban -ner that ex tends from mar gin to mar gin, as follows:

;============================================================;============================================================; L O C A L P R O C E D U R E S ;============================================================;============================================================;==========================; init LCD for 4-bit mode ;==========================initLCD:; Ini tial iza tion for Densitron LCD mod ule as fol lows:; 4-bit in ter face; 2 dis play lines of 20 char ac ters each; cur sor on; left-to-right in cre ment; cur sor shift right; no dis play shift

122 Chap ter 8

Page 144: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Com mented Bitmaps

It is also pos si ble to use com ments to sig nal the func tion of bit fields and in di vid ualbits of an op er and, as in the fol low ing code frag ment:

; OPTION_REG bitmap; 7 6 5 4 3 2 1 0 <= OPTION bits; | | | | | |__|__|_____ PS2-PS0 (prescaler bits); | | | | | Val ues for Timer0; | | | | | 000 = 1:2 001 = 1:4; | | | | | 010 = 1:8 011 = 1:16; | | | | | 100 = 1:32 101 = 1:64; | | | | | 110 = 1:128 *111 = 1:256; | | | | |______________ PSA (prescaler as sign); | | | | *1 = to WDT; | | | | 0 = to Timer0; | | | |_________________ TOSE (Timer0 edge se lect); | | | *0 = in cre ment on low-to-high; | | | 1 = in cre ment in high-to-low; | | |____________________ TOCS (TMR0 clock source); | | *0 = in ter nal clock; | | 1 = RA4/TOCKI bit source; | |_______________________ INTEDG (Edge se lect); | *0 = fall ing edge; |__________________________ RBPU (Pullup en able); *0 = en abled; 1 = dis abled; * in di cates op tions se lected

movlw b’00001000’ ; Value in stalledmovwf OPTION_REG

Clearly com mented bitmaps, ban ners, and many other code em bel lish ments donot add to the qual ity and func tion al ity of the code. It is quite pos si ble to write veryso ber and func tional pro grams with out us ing these gim micks. The de ci sion of howto com ment and how much to dec o rate pro grams is one of style.

8.5.2 De fin ing Data El e mentsMost pro grams will re quire the use of gen eral-pur pose file reg is ters. These reg is tersare al lo cated to mem ory ad dresses re served for this pur pose in the PIC ar chi tec ture.Be cause the ar eas at these mem ory lo ca tions are al ready re served for use as GPRs, the pro gram can ac cess the lo ca tion ei ther by ad dress or by as sign ing a name to the ad -dress. The equ (equate) di rec tory per forms this func tion, as fol lows:

var1 equ 0x0c ; Name var1 is as signed to lo ca tion 0x0c

Ac tu ally the name (in this case var1) be comes an alias for the mem ory ad dress towhich it is linked. From that point on the pro gram ac cesses the same vari able. Pro -gram code can ac cess the mem ory cell at ad dress 0x0c as follows:

movf var1,w ; Con tents of var1 to wor

movf 0x0c,w ; Same vari able to w

In ad di tion to the equ di rec tive, PIC as sem bly lan guage rec og nizes the C-like#de fine di rec tive, so the name as sig na tion could have been done as fol lows:

#de fine var1 0x0c

Em bed ded Sys tems Pro gram ming 123

Page 145: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Al though named vari ables are to be pre ferred over hard-coded ad dresses, thereare times when we need to ac cess an in ter nal el e ment of some multi-byte struc ture.In these cases the hard-coded form could be con ve nient, al though not ab so lutelynecessary.

cblock Di rec tive

An other way of de fin ing mem ory data is by us ing one of the data di rec tives avail able in PIC as sem bly lan guage. Al though there are sev eral of these, per haps the most use ful is the cblock di rec tive. The cblock di rec tive spec i fies an ad dress for the first item andother items listed are al lo cated from this first ad dress. The group ends with the endcdi rec tive. The fol low ing code frag ment shows the use of the cblock/endc di rec tives:

; Re serve 20 bytes for string buffer

cblock 0x20

strData

endc

; Re serve three bytes for ASCII dig its

cblock 0x34

asc100

asc10

asc1

endc

The cblock di rec tive ac tu ally de fines a group of con stants that are as signed con -sec u tive ad dresses in RAM. In the pre vi ous code frag ment the al lo ca tion of 20 bytesfor the buffer named strData is il lu sory be cause no mem ory is ac tu ally re served.The il lu sion works be cause the sec ond cblock starts at ad dress 0x34, which is 20bytes af ter strData; and also be cause the pro gram mer will ab stain from al lo cat ingother vari ables in the buffer space.

8.5.3 Bank ing Tech niques

Hav ing to deal with mem ory banks is one of the ag gra va tions of PIC pro gram ming.Banks are des ig nated start ing with bank 0. All PICs of the mid-range fam ily have atleast two banks, so bank shift ing op er a tions are vir tu ally un avoid able. The is sue ismore how to switch banks des ig nated be cause there are sev eral pos si ble tech niques.

Bank se lec tion is by means of bit RP0 and RP1 in the STATUS reg is ter. Inmid-range PICs with four banks the var i ous com bi na tions are as shown in Ta ble 8.1.

Ta ble 8.1

STATUS Reg is ter Bank Se lec tion Bits

RP1 RP0 BANK ADDRESS RANGE

1 1 *Bank 3 0x180 - 0x1ff 1 0 *Bank 2 0x100 - 0xx17f 0 1 Bank 1 0x80 - 0xff 0 0 Bank 0 0x00 - 0x7f

* RP1 bit is not used in de vices with two banks.

124 Chap ter 8

Page 146: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

The most di rect way to se lect the cur rent bank is by clear ing or set ting the cor re -spond ing bits in the STATUS reg is ter. For ex am ple, to se lect bank 2 in a four-bankde vice, you could code:

bsf STATUS,6 ; Set bit 6 in STATUS reg is terbcf STATUS,5 ; Clear bit 5

banksel Di rec tive

Al ter na tively, the ap pli ca tion can use the banksel di rec tive which se lects the bank inwhich a par tic u lar reg is ter is lo cated. For ex am ple, to se lect the bank in which theADCON1 reg is ter is lo cated, code could be as fol lows:

banksel ADCON1

The banksel di rec tive also works with reg is ters de fined by the user (GPRs).

Bank Se lec tion Mac ros

An al ter na tive way of per form ing bank se lec tion is by cod ing bank se lect mac ros. Amacro is an as sem bler struc ture that al lows de fin ing a se ries of in struc tions that is in -serted in the code ev ery time the macro is ref er enced. The PIC macro lan guage de fines the fol low ing for mat:

la bel macro [arg1, arg2... argn]..endm

In this ex am ple the el lip ses serve as placeholders for PIC in struc tions, as sem blerdi rec tives, macro di rec tives, or macro calls. Mac ros are usu ally de fined at the be gin -ning of the pro gram be cause for ward ref er ences to mac ros are not al lowed. The op -tional ar gu ments passed to the macro (arg1, arg2, etc.) are as signed val ues when the macro is in voked. For ex am ple, the fol low ing mac ros make the cor re spond ing bankse lec tions in a mid-range PIC with four banks:

; Mac ros to se lect the reg is ter banksBank0 MACRO ; Se lect RAM bank 0

bcf STATUS,RP0bcf STATUS,RP1ENDM

Bank1 MACRO ; Se lect RAM bank 1bsf STATUS,RP0bcf STATUS,RP1ENDM

Bank2 MACRO ; Se lect RAM bank 2bcf STATUS,RP0bsf STATUS,RP1ENDM

Bank3 MACRO ; Se lect RAM bank 3bsf STATUS,RP0bsf STATUS,RP1ENDM

Em bed ded Sys tems Pro gram ming 125

Page 147: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Once the bank switch ing mac ros have been de fined, the ap pli ca tion can changebanks sim ply by call ing the macro name; for ex am ple, if we know that the ADCON1reg is ter is in bank 1 we can se lect the bank by call ing

Bank1

At this point in the code, the macro ex pan sion will in sert the cor re spond ing op er -a tions to make the switch.

Which method to use when switch ing banks is a mat ter of per sonal pref er enceand pro gram con straints. Set ting and clear ing the RP1/RP0 bits is sim ple enough but can be er ror-prone. Us ing the banksel di rec tive is con ve nient be cause we do notneed to know in which bank the item is lo cated. The ob jec tion to us ing banksel isthat some un nec es sary bank changes may take place. For ex am ple, if the pro gram is al ready in bank 1 and the banksel di rec tive ap pears with a reg is ter file in that samebank, then the bank switch ing code is gen er ated any way. The use of bank se lec tionmac ros seems like a suit able method for most con di tions. One ad van tage of themacro ap proach is that pro grams for dif fer ent PICs can have their own bank ingmac ros. In this way code can be easily ported to dif fer ent architectures.

Dep re cated Bank ing In struc tions

Sev eral in struc tions in the mid-range in struc tion set have been dep re cated and are nolon ger rec om mended by Micro chip; these in clude tris and op tion. Micro chip’s rea -son for not rec om mend ing these in struc tions is to main tain com pat i bil ity with fu turemid-range prod ucts. From a pro gram mer’s view point, it is dif fi cult to see why us ingthese in struc tions may be un de sir able. In the un likely case that our code will beported to some other fu ture de vice that does not sup port tris or op tion, then it will beeasy enough to mod ify the code at that time.

The tris and op tion in struc tions are con ve nient be cause they al low load ing thecon tents of the w register to the OPTION, TRISA, and TRISB reg is ters di rectly, with -out bank con cerns. For ex am ple, the fol low ing code frag ment sets port line 1 to in -put and all oth ers to out put:

movlw b’00000010’ ; Line 1 is in put

tris PORTA

We con tinue to use the dep re cated in struc tions in pro grams in which there is nocon cern about fu ture con se quences. In pro grams in which por ta bil ity is an is sue, we use the bank ing mac ros dis cussed previously.

8.5.4 Pro ces sor and Con fig u ra tion Con trols

PIC pro grams must de fine the pro ces sor to be used by the de vel op ment soft ware. Theas sem bler pro ces sor di rec tive (and also the list di rec tive) al low de fin ing the PICtype. For ex am ple, a pro gram for the 16F877 would con tain the fol low ing line:

pro ces sor 16f877

126 Chap ter 8

Page 148: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Con fig u ra tion Bits

The PIC microcontrollers con tain a spe cial reg is ter called the con fig u ra tion registerthat al lows cus tom iz ing cer tain pro ces sor fea tures to the needs of the ap pli ca tion. Inthe mid-range PICs, the bits in the con fig u ra tion reg is ter are mapped in pro gram mem -ory lo ca tion 0x2007. This mem ory lo ca tion can only be ac cessed dur ing the pro gram -ming mode, so the bits can not be changed dur ing nor mal pro gram op er a tion. Thecon fig u ra tion bits can not be read at runtime.

Micro chip rec om mends that the con fig u ra tion bit be set by means of the__config di rec tive. The bits are mapped as fol lows:

CP1:CP0: Code Pro tec tion bits

11 = Code pro tec tion off10 = See de vice data sheet01 = See de vice data sheet00 = All mem ory is code pro tected

Some de vices use more or less bits to de ter mine the level of code pro tec tion.Some use a sin gle bit for this pur pose. In this case the en cod ing is as fol lows:

1 = Code pro tec tion off0 = Code pro tec tion on

DP: Data EEPROM Mem ory Code Pro tec tion bit

1 = Code pro tec tion off0 = Data EEPROM Mem ory is code pro tected

BODEN: Brown-out Re set En able bit

1 = BOR en abled0 = BOR dis abled

En abling Brown-out Re set au to mat i cally en ables the Power-up Timer (PWRT) re -gard less of the value of bit PWRTE. En sure that the Power-up Timer is en abled any -time that Brown-out Re set is enabled.

PWRTE: Power-up Timer En able bit

1 = PWRT dis abled0 = PWRT en abled

MCLRE: MCLR Pin Func tion Se lect bit

1 = Pin’s func tion is MCLR0 = Pin’s func tion is as a dig i tal I/O.

MCLR is in ter nally tied to VDD.

WDTE: Watch dog Timer En able bit

1 = WDT en abled0 = WDT dis abled

FOSC1:FOSC0: Os cil la tor Se lec tion bits

Em bed ded Sys tems Pro gram ming 127

Page 149: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

11 = RC os cil la tor10 = HS os cil la tor01 = XT os cil la tor00 = LP os cil la tor

FOSC2:FOSC0: Os cil la tor Se lec tion bits

111 = EXTRC os cil la tor, with CLKOUT110 = EXTRC os cil la tor101 = INTRC os cil la tor, with CLKOUT100 = INTRC os cil la tor011 = Re served010 = HS os cil la tor001 = XT os cil la tor000 = LP os cil la tor

The __config di rec tive is used to em bed con fig u ra tion data in the source file. Al -ter na tively, the con fig u ra tion bits can be set at the time the PIC is blown. The fol -low ing code frag ment shows set ting the con fig u ra tion bits for a 16F877 PIC:

; Switches used in __config di rec tive:; _CP_ON Code pro tec tion ON/OFF ; * _CP_OFF ; * _PWRTE_ON Power-up timer ON/OFF; _PWRTE_OFF ; _BODEN_ON Brown-out re set en able ON/OFF; * _BODEN_OFF ; * _PWRTE_ON Power-up timer en able ON/OFF; _PWRTE_OFF ; _WDT_ON Watchdog timer ON/OFF ; * _WDT_OFF; _LPV_ON Low volt age IC pro gram ming en able ON/OFF; * _LPV_OFF; _CPD_ON Data EE mem ory code pro tec tion ON/OFF; * _CPD_OFF; OSCILLATOR CONFIGURATIONS: ; _LP_OSC Low power crys tal occilator; _XT_OSC Ex ter nal par al lel res o na tor/crys tal ocillator ; * _HS_OSC High speed crys tal res o na tor; _RC_OSC Re sis tor/ca pac i tor ocillator; | (sim plest, 20% er ror); |; |_____ * in di cates setup val ues pres ently se lected;

__CONFIG _CP_OFF & _WDT_OFF & _BODEN_OFF & _PWRTE_ON & _HS_OSC &_WDT_OFF & _LVP_OFF & _CPD_OFF

8.5.5 Nam ing Con ven tionsOne of the style is sues that the pro gram mer must de cide con cerns the con ven tions fol -lowed for pro gram la bels and vari able (reg is ter) names. The MPLAB as sem bler is case sen si tive by de fault, so PORTB and portb can re fer to dif fer ent reg is ters.

The pro gram mer can de fine all the reg is ters (SFRs and GPRs) used by an ap pli ca -tion us ing equ or #de fine di rec tives. A safer ap proach is to im port an in clude file(.inc ex ten sion) fur nished in the MPALB pack age for each dif fer ent PIC. The in clude

128 Chap ter 8

Page 150: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

files have the names of all SFRs and bits used by a par tic u lar de vice. The fol low ingcode frag ment is a list ing of the MPLAB in clude file for the 16f84a:

LIST; P16F84A.INC Stan dard Header File, Ver sion 2.00; Micro chip Tech nol ogy, Inc. NOLIST

; This header file de fines con fig u ra tions, reg is ters, and other; use ful bits of in for ma tion for the PIC16F84 microcontroller.; These names are taken to match the data sheets as closely as ; pos si ble. ; Note that the pro ces sor must be se lected be fore this file is ; in cluded. The pro ces sor may be se lected the fol low ing ways:; 1. Com mand line switch:; C:\ MPASM MYFILE.ASM /PIC16F84A; 2. LIST di rec tive in the source file; LIST P=PIC16F84A; 3. Pro ces sor Type en try in the MPASM full-screen in ter face;===================================================================;; Re vi sion His tory;;===================================================================

;Rev: Date: Rea son:

;1.00 2/15/99 Ini tial Re lease

;===================================================================;; Ver ify Pro ces sor;;===================================================================

IFNDEF __16F84A MESSG “Pro ces sor-header file mis match. Ver ify se lected pro ces sor." ENDIF

;===================================================================;; Reg is ter Def i ni tions;;===================================================================

W EQU H’0000’F EQU H’0001’

;- Reg is ter Files -

INDF EQU H’0000’TMR0 EQU H’0001’PCL EQU H’0002’STATUS EQU H’0003’FSR EQU H’0004’PORTA EQU H’0005’PORTB EQU H’0006’EEDATA EQU H’0008’EEADR EQU H’0009’

Em bed ded Sys tems Pro gram ming 129

Page 151: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

PCLATH EQU H’000A’INTCON EQU H’000B’

OPTION_REG EQU H’0081’TRISA EQU H’0085’TRISB EQU H’0086’EECON1 EQU H’0088’EECON2 EQU H’0089’

;- STATUS Bits -

IRP EQU H’0007’RP1 EQU H’0006’RP0 EQU H’0005’NOT_TO EQU H’0004’NOT_PD EQU H’0003’Z EQU H’0002’DC EQU H’0001’C EQU H’0000’

;- INTCON Bits -

GIE EQU H’0007’EEIE EQU H’0006’T0IE EQU H’0005’INTE EQU H’0004’RBIE EQU H’0003’T0IF EQU H’0002’INTF EQU H’0001’RBIF EQU H’0000’

;- OPTION_REG Bits -

NOT_RBPU EQU H’0007’INTEDG EQU H’0006’T0CS EQU H’0005’T0SE EQU H’0004’PSA EQU H’0003’PS2 EQU H’0002’PS1 EQU H’0001’PS0 EQU H’0000’

;- EECON1 Bits -

EEIF EQU H’0004’WRERR EQU H’0003’WREN EQU H’0002’WR EQU H’0001’RD EQU H’0000’

;====================================================================;; RAM Def i ni tion;;====================================================================

__MAXRAM H’CF’ __BADRAM H’07’, H’50’-H’7F’, H’87’

130 Chap ter 8

Page 152: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

;=====================================================================;; Con fig u ra tion Bits;;=====================================================================

_CP_ON EQU H’000F’_CP_OFF EQU H’3FFF’_PWRTE_ON EQU H’3FF7’_PWRTE_OFF EQU H’3FFF’_WDT_ON EQU H’3FFF’_WDT_OFF EQU H’3FFB’_LP_OSC EQU H’3FFC’_XT_OSC EQU H’3FFD’_HS_OSC EQU H’3FFE’_RC_OSC EQU H’3FFF’

Note that all names in the in clude file are de fined in all-cap i tal let ters. It is prob a -bly a good idea to ad here to this style in stead of cre at ing al ter nate names in lowercase. The C-like #in clude di rec tive is used to re fer to the .inc files at as sem bly time; for ex am ple

#in clude <p16f84a.inc>

8.5.6 Errorlevel Di rec tive This di rec tive al lows con trol ling the warn ing and er ror mes sages pro duced at as sem -bly and link times. One par tic u lar type of warn ing can be dis turb ing: those that re fer to bank changes. Ap pli ca tions of ten turn off bank change-re lated warn ings with the fol -low ing line:

errorlevel -302

8.6 Pseudo In struc tionsIt is some times dis turb ing to read in a code list ing in struc tions that are not part of thestan dard set for the par tic u lar de vice. The rea son this hap pens is that MPLAB in cludes a set of pseudo in struc tions for 12- and 14-bit de vices. A list of all sup ported pseudoin struc tions can be found in the MPLAB doc u men ta tion. In our pro gram ming we pre -fer not to use them be cause they tend to make code less read able. In ci den tally, Micro -chip also rec om mends not us ing the pseudo in struc tions.

Em bed ded Sys tems Pro gram ming 131

Page 153: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

This page intentionally left blankThis page intentionally left blank

Page 154: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Chap ter 9

I/O Cir cuits and Pro grams

9.1 Sim ple In put and Out putIn this chap ter we in tro duce em bed ded cir cuits and pro gram ming op er a tions. Westart with sim ple in put and out put de vices that are con trolled by one of the most ba sicPICs of the mid-range fam ily (the 16F84A). Al though us ing a PIC to con trol an LED orto read a switch is as el e men tary as it gets, these op er a tions are by no means triv ial tothe be gin ner be cause they re quire build ing a work ing cir cuit and de vel op ing and in -stall ing the cor re spond ing PIC pro gram. Later in the chap ter we prog ress to morecom plex in put/out put de vices, in clud ing the Seven-Seg ment LED dis play and cir cuitswith mul ti ple switches. One of the cir cuits uses a bank of mul ti ple LEDs to func tion asa bi nary out put de vice and reads four tog gle switches.

9.1.1 16F84A Pro gram ming Tem plateWe have found that pro gram de vel op ment can be con sid er ably sim pli fied us ing codetem plates. A code tem plate is a pro gram de void of func tion al ity that serves to im ple -ment the most com mon and typ i cal fea tures of an ap pli ca tion. The tem plate not onlysaves the ef fort of re-do ing the same tasks, but also re minds the pro gram mer of pro -gram el e ments that could oth er wise be for got ten. A pro fes sional de vel oper will havecol lected many dif fer ent tem plates over the years, for dif fer ent types of ap pli ca tions,on var i ous pro ces sors. The fol low ing tem plate is for the 16F84A PIC:

;============================================================; File name:; Date:; Au thor:; Pro ces sor:; Ref er ence cir cuit:;=============================================================; Copy right no tice:;=============================================================; Pro gram De scrip tion:;;===========================; con fig u ra tion switches;===========================

133

Page 155: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; Switches used in __config di rec tive:; _CP_ON Code pro tec tion ON/OFF ; * _CP_OFF ; * _PWRTE_ON Power-up timer ON/OFF; _PWRTE_OFF ; _WDT_ON Watchdog timer ON/OFF ; * _WDT_OFF ; _LP_OSC Low power crys tal occilator; * _XT_OSC Ex ter nal par al lel res o na tor ; _HS_OSC High speed crys tal res o na tor (8 to 10 MHz); _RC_OSC Re sis tor/ca pac i tor ocillator; (sim plest, 20% er ror); |; |_____ * in di cates setup val ues

;=========================; setup and con fig u ra tion;=========================

pro ces sor 16f84Ain clude <p16f84A.inc>__config _XT_OSC & _WDT_OFF & _PWRTE_ON & _CP_OFF

;=====================================================; con stant def i ni tions;=====================================================;=====================================================; PIC reg is ter equates;=====================================================;=====================================================; vari ables in PIC RAM;=====================================================

cblock 0x0cendc

;============================================================; pro gram;============================================================

org 0 ; start at ad dress goto main

; Space for in ter rupt han dlersorg 0x08

main:

;============================================================end ; END OF PROGRAM

;============================================================

In ad di tion to the tem plate file, the pro gram de vel oper should keep at hand thenec es sary in clude files. In this case, p16f84a.inc.

9.2 Tem plate Cir cuitsAs the pro gram mer can use a pro gram ming tem plate for de vel op ing 16F84A code, thecir cuit de signer can use a cir cuit tem plate. Very of ten it is pos si ble to build a new cir -cuit by com bin ing com po nents and sec tions of ex ist ing tem plates. In the dis cus sion of sim ple in put and out put cir cuits, we also in tro duce some ba sic cir cuit tem plates forthe 16F84A PIC.

134 Chap ter 9

Page 156: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

9.2.1 MCLR and Os cil la tor Tem plateMost 16F84 cir cuits re quire han dling the MCLR (mas ter clear) pin and the con nec -tions for an ex ter nal os cil la tor. This ba sic cir cuit should also in clude a di a gram of thePIC it self with the pin out, as well as the wir ing of the stan dard com po nents such asthe power and ground. Fig ure 9-1 shows a cir cuit tem plate for the 16F84A.

Fig ure 9-1 16F84A MCLR and Os cil la tor Cir cuit Tem plate.

The cir cuit in Fig ure 9-1 as sumes that the os cil la tor is an ex ter nal par al lel res o na -tor. The cir cuit tem plate in Fig ure 9-1 will not suit ev ery pos si ble cir cuit. Even thesim plest com po nents must some times be con fig ured dif fer ently; for ex am ple, there set line could be wired to a pushbutton switch, or a dif fer ent os cil la tor may beused. In any case, it is al ways eas ier to make mod i fi ca tions to an ex ist ing di a gramthan to start from scratch every time.

9.2.2 Power Sup plies

Ev ery mid-range PIC-based cir cuit board re quires a +5V power source. One pos si blesource of power is one or more bat ter ies. There is an enor mous se lec tion of bat terytypes, sizes, and qual i ties. The most com mon ones for use in ex per i men tal cir cuits arelisted in Ta ble 9.1.

Ta ble 9.1

Com mon Dry Cell Al ka line Bat tery Types

DES IG NA TION VOLTS LENGTH DI AM E TER MM. MM.

D 1.5 61.5 34.2C 1.5 50 26.2AA 1.5 50 14.2AAA 1.5 44.5 10.5AAAA 1.5 42.5 8.3

I/O Cir cuits and Pro grams 135

16F84A

R=10K

R=330Ohm

Osc

LED

+5V

+5V

Page 157: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

All the bat ter ies in Ta ble 9.1 pro duce 1.5 volts. This means that for a PIC with asup ply volt age from 2 to 6 volts, two to four bat ter ies will be ad e quate. Note that inse lect ing the bat tery power source for a PIC-based cir cuit other el e ments, in ad di -tion to the microcontroller it self must be con sid ered, such as the os cil la tor. Hold ersfor sev eral in ter con nected bat ter ies are avail able at electronic supply sources.

Al ter na tively, the power sup ply can be a trans former with 120VAC in put and 3 to12VDC. These are usu ally called AC/DC or plug-in adapt ers or “wall wart.” The mostuse ful type for the ex per i menter are the ones with an ON/OFF switch and sev eralselectable out put volt ages. Color-coded al li ga tor clips at the out put wires are also aconvenience.

Volt age Reg u la tor

A use ful de vice for a typ i cal PIC-based power source is a volt age reg u la tor IC. The7805 volt age reg u la tor is ubiq ui tous in many PIC-based boards with AC/DC adapt ers.The IC is a three-pin de vice whose pur pose is to en sure a sta ble volt age source thatdoes not ex ceed the de vice rat ing. The 7805 is rated for 5V and will pro duce this out put from any in put source in the range 8 to 35V. Be cause the ex cess volt age is dis si pated as heat, the 7805 is equipped with a me tal lic plate in tended for at tach ing a heat sink. Theheat sink is not re quired in a typ i cal PIC ap pli ca tion but it is a good idea to main tain the sup ply volt age closer to the de vice min i mum rather than to its max i mum.

The volt age reg u la tor cir cuit also re quires two ca pac i tors: one elec tro lytic andthe other one not. Fig ure 9-2 shows a power source cir cuit us ing the 7805.

Fig ure 9-2 Volt age Sta bi lizer Cir cuit.

To sim plify the sche mat ics, the volt age reg u la tor and power sup ply com po nentsare of ten not in cluded in the cir cuit di a gram. In this case the power in put lines inthe cir cuit are la beled +5V and the cor re spond ing re turn lines with the con ven tional ground sym bol, as shown in Figure 9.1.

9.3 Sim ple Cir cuits and Pro grams

In the fol low ing sub-sec tions we de scribe very sim ple PIC-based cir cuits that can beas sem bled with very few com po nents us ing a bread board. The cor re spond ing pro -grams ex er cise the cir cuit com po nents. The be gin ner should not skip build ing thesecir cuits and cod ing the pro grams be cause they dem on strate es sen tial hard ware andsoft ware el e ments.

136 Chap ter 9

C=0.1mFEC=100mF

78L05

INOUT

9 -35V DCinput

+5V DCoutput

+

Page 158: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

As a learn ing ex pe ri ence it is a good idea to re verse-en gi neer the code in thesesam ple pro grams. With the pro ces sor’s in struc tion set at hand, listed in Ap pen dix F,pro ceed to fol low the code list ing one in struc tion at a time un til you can un der stand ev ery pro cess ing de tail. This is also a good op por tu nity to learn to use the MPLABen vi ron ment and the sym bolic debugger (MPLAB SIM) dis cussed in Chap ter 8. Thefun da men tal ex er cises for us ing the debugger con sist of in sert ing break points in the code, run ning the pro gram to the break point, step ping through and step ping oversub rou tines, and inspecting variables and PIC registers.

9.3.1 Sin gle LED Cir cuit One of the sim plest cir cuits con sists of a sin gle LED lamp wired to port B, line 0, of a16F84A PIC, as shown in Fig ure 9-3.

Fig ure 9-3 Sim ple LED Cir cuit.

Note that the power source for the cir cuit in Fig ure 9-3 is not shown in the cir cuitsche matic. Typ i cally, a bat tery source or an AC/DC con verter and a volt age sta bi -lizer cir cuit as the one in Fig ure 9-2 would be used.

A pro gram to turn on the LED on port B, line 0, re quires few but es sen tial pro -cess ing op er a tions. Code must per form the fol low ing op er a tions:

• De fine and se lect pro ces sor (in this case, 16F84A).

• Link-in the cor re spond ing in clude file (p16f84A.inc).

• Se lect the oscillator type (in this case, an ex ter nal res o na tor, _XT type).

• Di rect ex e cu tion to the main la bel.

• Ini tial ize port B for out put.

• Set line 0 in port B high.

I/O Cir cuits and Pro grams 137

16

F8

4A

R=10K

R=330Ohm

RA2

RA3

RA4/TOCKI

MCLR

Vss

RB0/INT

RB1

RB2

RB3

1

2

3

4

5

6

7

8

9

18

17

16

15

14

13

12

11

10

RA1

RA0

OSC1

OSC2

Vdd

RB7

RB6

RB5

RB4

Osc

LED

+5V

+5V

Page 159: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

The en tire pro gram is as fol lows:

; File: LEDOn.asm; Date: June 1, 2011; Au thors: Can ton and Sanchez; Pro ces sor: 16F84A;; De scrip tion:; Turn on LED wired to port B, line 0;===========================; switches;===========================; Switches used in __config di rec tive:; _CP_ON Code pro tec tion ON/OFF ; * _CP_OFF ; * _PWRTE_ON Power-up timer ON/OFF; _PWRTE_OFF ; _WDT_ON Watchdog timer ON/OFF ; * _WDT_OFF ; _LP_OSC Low power crys tal oscillator; * _XT_OSC Ex ter nal par al lel res o na tor/crys tal oscillator ; _HS_OSC High speed crys tal res o na tor (8 to 10 MHz); Res o na tor: Murate Erie CSA8.00MG = 8 MHz ; _RC_OSC Re sis tor/ca pac i tor oscillator (sim plest); |; |_______________* in di cates setup val ues

pro ces sor 16f84Ain clude <p16f84A.inc>__config _XT_OSC & _WDT_OFF & _PWRTE_ON & _CP_OFF

;=====================================================; vari ables in PIC RAM;=====================================================; None used;========================================================; m a i n p r o g r a m;========================================================

org 0 ; start at ad dress 0goto main

;=============================; space for in ter rupt han dler;=============================

org 0x04;=============================; main pro gram;=============================main:; Ini tial ize all lines in port B for out put

movlw B’00000000’ ; w = 00000000 bi narytris PORTB ; Set up port B for out put

; Turn on line 0 in port B. All oth ers re main offmovlw B’00000001’

; -------|; -------|____ Line 0 ON; |________ All oth ers off

movwf PORTB; End less loop in ten tion ally hangs up pro gram wait:

goto waitend

138 Chap ter 9

Page 160: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

The pre ced ing pro gram, named LEDOn, can be found in the book’s on line soft -ware.

LED Flasher Pro gram

A dif fer ent pro gram can be used on the same cir cuit to make the LED flash on and off.In this case the pro gram must in clude a de lay loop so as to keep the LED in ei ther theON or the OFF state for a short time pe riod. The de lay loop can be eas ily im ple mentedus ing a file reg is ter as a coun ter. The pro gram logic turns on the LED and counts downto zero; then re sets the coun ter, turns the LED off, and counts down again.

The coun ter rou tine can also be used to dem on strate the cre ation of a sub rou tine, called a pro ce dure in PIC pro gram ming. The pro ce dure is noth ing more than a rou -tine marked by a la bel at its en try point and ter mi nated with a re turn state ment. The pro ce dure is ex e cuted by a call state ment to its ini tial la bel. If the pro ce dure isnamed “de lay”, the pro ce dure call is as fol lows:

call de lay ; Call pro ce dure

.

.

.

Else where in the pro gram,

de lay:

; pro ce dure in struc tions go here

re turn ; End of pro ce dure

The sim plest de lay loop op er ates by wast ing pro ces sor time. Be cause each in -struc tion takes four clock cy cles, the de lay can be ac cu rately cal cu lated by mul ti -ply ing the num ber of in struc tions in the loop by the de vice’s clock speed, di vided by4. The de tails of de lay loops are dis cussed in Chap ter 11 on timers and counters.

Im ple ment ing a timer loop usu ally re quires two coun ters. Be cause the max i mumvalue that can be stored in a reg is ter file is 255, and a de lay of 255 ma chine cy cles isa very short one. In the code sam ple that fol lows we get around this lim i ta tion bycre at ing a dou ble-loop coun ter: the in ner loop counts down 200 cy cles and an outerloop re peats the in ner-loop 200 times. The re sult is that the rou tine re peats 200times 200 times, 40,000 it er a tions, which is suf fi cient for the pur pose at hand. Codeis as follows:

de lay:

movlw .200 ; w = 200 dec i mal

movwf j ; j = w

jloop:

movwf k ; k = w

kloop:

decfsz k,f ; k = k-1, skip next if zero

goto kloop

decfsz j,f ; j = j-1, skip next if zero

goto jloop

re turn

I/O Cir cuits and Pro grams 139

Page 161: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Code as sumes that two vari ables were cre ated in the pro ces sor’s GPR space, asfol lows:

; De clare vari ables at 2 mem ory lo ca tionsj equ 0x0ck equ 0x0d

The list ing for the en tire LEDFlash pro gram, con tained in this book’s soft ware re -source is as fol lows:

; File: LEDFlash.asm; Date: June 2, 2011; Au thors: Can ton and Sanchez; Pro ces sor: 16F84A;; De scrip tion:; Turn on and off LED wired to port B, line 0;===========================; switches;===========================; Switches used in __config di rec tive:; _CP_ON Code pro tec tion ON/OFF ; * _CP_OFF ; * _PWRTE_ON Power-up timer ON/OFF; _PWRTE_OFF ; _WDT_ON Watchdog timer ON/OFF ; * _WDT_OFF ; _LP_OSC Low power crys tal oscillator; * _XT_OSC Ex ter nal par al lel res o na tor/crys tal oscillator ; _HS_OSC High speed crys tal res o na tor (8 to 10 MHz); Res o na tor: Murate Erie CSA8.00MG = 8 MHz ; _RC_OSC Re sis tor/ca pac i tor oscillator (sim plest, 20% er ror); |; |_____ * in di cates setup val ues

pro ces sor 16f84Ain clude <p16f84A.inc>__config _XT_OSC & _WDT_OFF & _PWRTE_ON & _CP_OFF

;=====================================================; vari ables in PIC RAM;=====================================================; De clare vari ables at 2 mem ory lo ca tionsj equ 0x0ck equ 0x0d;========================================================; m a i n p r o g r a m;========================================================

org 0 ; start at ad dress 0goto main

;=============================; space for in ter rupt han dler;=============================

org 0x04;=============================; main pro gram;=============================main:; Ini tial ize all lines in port B for out put

movlw B’00000000’ ; w = 00000000 bi nary

140 Chap ter 9

Page 162: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

tris PORTB ; Set up port B for out put;; Pro gram loop to turn LED on and offLEDonoff:; Turn on line 0 in port B. All oth ers re main off

movlw B’00000001’ ; LED ONmovwf PORTBcall de lay ; Lo cal de lay rou tine

; Turn off line 0 in port B.movlw B’00000000’ ; LED OFFmovwf PORTBcall de laygoto LEDonoff

;================================; de lay sub-rou tine;================================de lay:

movlw .200 ; w = 200 dec i malmovwf j ; j = w

jloop:movwf k ; k = w

kloop:decfsz k,f ; k = k-1, skip next if zerogoto kloopdecfsz j,f ; j = j-1, skip next if zerogoto jloopre turnend

9.3.2 LED/Pushbutton Cir cuitA slightly more com plex cir cuit con tains a pushbutton switch. In this case the pro -gram can mon i tor the state of the pushbutton and turn on the LED when the switch isclosed. Fig ure 9-4 shows one pos si ble wir ing for the LED/pushbutton cir cuit.

Fig ure 9-4 LED/Pushbutton Cir cuit.

I/O Cir cuits and Pro grams 141

16F84

4 MHzOsc

10K Ohms

R=4.7K Ohm

R=330 Ohm

LED

+5 V

+5 V

+5 V

RA2 RA3 T0Tkl MCLR Vss RB0/INT RB1 RB2 RB3

1 2 3 4 5 6 7 8 9

18 17 16 15 14 13 12 11 10

RA1 RA0 OSC1 OSC2 Vdd RB7 RB6 RB5 RB4

Page 163: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

If a switch re ports a zero bit when ac tive it is de scribed as ac tive-low. A switchthat re ports a one bit when pressed is said to be ac tive-high. The pushbutton switch in Fig ure 9-4 is wired ac tive-low. In the same man ner, an out put de vice can be wiredso that it is turned on with a logic 0 and off with logic 1 on the port pin. A de viceturned on by the port cur rent it is said to source the cur rent. When the de vice isturned on when the port re ports logic 0, the line is said to sink the cur rent. PICs and other CMOS de vices op er ate better sink ing than sour cing cur rent. Ta ble 9.2 showsthe max i mum sink and source cur rents for the 16F84 ports.

Ta ble 9.2

Sink and Source Cur rent for 16F84 Ports

SOURCE ANY I/O PIN PORT A PORT B

sink cur rent 25 mA 80 mA 150 mAsource cur rent 20 mA 50 mA 100 mA

The 4.7K-Ohm re sis tor in the cir cuit of Fig ure 9-4 keeps RA0 high un til the switchis pressed. This switch ac tion de ter mines that RA0 reads a bi nary 1 when the switchis re leased and a bi nary 0 (low) when the switch is pressed (ac tive).

To test if the switch in the cir cuit of Fig ure 9-4 is closed, the ap pli ca tion can readport pin RA0. If the value in the port is 1, then the switch is open (re leased); if it is 0, then the switch is closed. The fol low ing pro gram, called LEDandPb, ex er cises thecir cuit in Fig ure 9-4.

; File: LEDandPb.asm; Date: June 2, 2011; Au thors: Can ton and Sanchez; Pro ces sor: 16F84A;; De scrip tion:; Cir cuit with LED wired to RB0 and pushbutton switch,; ac tive low, wired to RA0. Pushbutton ac tion turns LED; OFF when pressed and ON when re leased.;===========================; switches;===========================; Switches used in __config di rec tive:; _CP_ON Code pro tec tion ON/OFF ; * _CP_OFF ; * _PWRTE_ON Power-up timer ON/OFF; _PWRTE_OFF ; _WDT_ON Watchdog timer ON/OFF ; * _WDT_OFF ; _LP_OSC Low power crys tal oscillator; * _XT_OSC Ex ter nal par al lel res o na tor/crys tal oscillator ; _HS_OSC High speed crys tal res o na tor (8 to 10 MHz); Res o na tor: Murate Erie CSA8.00MG = 8 MHz ; _RC_OSC Re sis tor/ca pac i tor oscillator (sim plest, 20% er ror); |; |_____ * in di cates setup val ues

pro ces sor 16f84Ain clude <p16f84A.inc>

142 Chap ter 9

Page 164: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

__config _XT_OSC & _WDT_OFF & _PWRTE_ON & _CP_OFF;=====================================================; vari ables in PIC RAM;=====================================================; Not used in this pro gram;;========================================================; m a i n p r o g r a m;========================================================

org 0 ; start at ad dress 0goto main

;;=============================; space for in ter rupt han dler;=============================

org 0x04;;=============================; main pro gram;=============================main:; Ini tial ize all lines in port B for out put

movlw B’00000000’ ; w = 00000000 bi narytris PORTB ; Set up port B for out put

; Ini tial ize port A, line 0, for in putmovlw B’00000001’ ; w = 00000001 bi narytris PORTA ; Set up RA0 for in put

; Pro gram loop to test state of pushbutton switch;;==============================; read PB switch state;==============================LEDctrl:; Push but ton switch on demo board is wired to port A bit 0; Switch logic is ac tive low

btfss PORTA,0 ; Test. Skip next line if; bit is set

goto turn OFF ; Turn LED off rou tine; At this point port A bit 0 is not set; Switch is pressed (ac tive low ac tion); Turn ON line 0 in port B

bsf PORTB,0 ; RB0 highgoto LEDctrl

turn OFF:; Rou tine to turn OFF LED

bcf PORTB,0 ; RB0 lowgoto LEDctrl

end

The elec tronic file for the LEDandPb pro gram pre vi ously listed can be found inthis book’s on line soft ware.

9.3.3 Mul ti ple LED Cir cuitThe cir cuit in Fig ure 9-5 in tro duces a few more cir cuit and pro gram ming com pli ca -tions be cause it con tains a bat tery of eight LEDs, all wired to port B.

I/O Cir cuits and Pro grams 143

Page 165: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 9-5 Mul ti ple LED Cir cuit.

The cir cuit in Fig ure 9-5 can be pro grammed to do dif fer ent func tions. For ex am -ple, the eight LEDs can be vi su al ized as rep re sent ing an 8-bit bi nary num ber, and the cir cuit can be made to count in bi nary from 0 to 255. Be cause the eight LEDs are allwired to port B, the bi nary count can be stored di rectly in the port reg is ter(PORTB). In this case the LEDs wired to port B lines that hold a bi nary 1 will beturned on and those wired to lines that hold bi nary 0 will be turned off. The fol low -ing pro gram, called LEDCount, performs this operation.

; File: LEDCount.asm; Date: June 3, 2011; Au thors: Can ton and Sanchez; Pro ces sor: 16F84A; De scrip tion:; Cir cuit with eight LEDs wired to RB0 to RB7.; Pro gram dis plays a bi nary count from 0 to 255 on; LEDs.;===========================; switches;===========================; Switches used in __config di rec tive:; _CP_ON Code pro tec tion ON/OFF ; * _CP_OFF ; * _PWRTE_ON Power-up timer ON/OFF; _PWRTE_OFF ; _WDT_ON Watchdog timer ON/OFF

144 Chap ter 9

16F84

R=10K

R=330x8 Ohm

RA2

RA3

RA4/TOCKI

MCLR

Vss

RB0/INT

RB1

RB2

RB3

1

2

3

4

5

6

7

8

9

18

17

16

15

14

13

12

11

10

RA1

RA0

OSC1

OSC2

Vdd

RB7

RB6

RB5

RB4

Osc

+5V

+5V

Page 166: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; * _WDT_OFF ; _LP_OSC Low power crys tal oscillator; * _XT_OSC Ex ter nal par al lel res o na tor/crys tal oscillator ; _HS_OSC High speed crys tal res o na tor (8 to 10 MHz); Res o na tor: Murate Erie CSA8.00MG = 8 MHz ; _RC_OSC Re sis tor/ca pac i tor oscillator (sim plest, 20% er ror); |; |_____ * in di cates setup val ues

pro ces sor 16f84Ain clude <p16f84A.inc>__config _XT_OSC & _WDT_OFF & _PWRTE_ON & _CP_OFF

;=====================================================; vari ables in PIC RAM;=====================================================; De clare vari ables at 2 mem ory lo ca tionsj equ 0x0ck equ 0x0d;========================================================; m a i n p r o g r a m;========================================================

org 0 ; start at ad dress 0goto main

;=============================; space for in ter rupt han dler;=============================

org 0x04;=============================; main pro gram;=============================main:; Ini tial ize all lines in port B for out put

movlw B’00000000’ ; w = 00000000 bi narytris PORTB ; Set up port B for out put

; Set port B bit 0 ONmovlw B’00000000’ ; w := 0 bi narymovwf PORTB ; port B it self := w

; Clear the carry bitbcf STATUS,C

mloop:incf PORTB,f ; Add 1 to reg is ter valuecall de laygoto mloop

;================================; de lay sub-rou tine;================================de lay:

movlw .200 ; w = 200 dec i malmovwf j ; j = w

jloop:movwf k ; k = w

kloop:decfsz k,f ; k = k-1, skip next if zerogoto kloopdecfsz j,f ; j = j-1, skip next if zerogoto jloopre turn

end

I/O Cir cuits and Pro grams 145

Page 167: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

9.4 Seven-Segment LEDA Seven-Seg ment dis play can be con nected to out put ports on the PIC and used to dis -play num bers and some dig its. The cir cuit in Fig ure 9-6 shows one pos si ble wir ingscheme.

Fig ure 9-6 Seven-Seg ment LED Cir cuit.

As the name in di cates, the Seven-Seg ment dis play has seven lin ear LEDs that al -low form ing all the dec i mal and hex dig its and some sym bols and let ters. Once themap ping of the in di vid ual bars of the dis play to the PIC ports has been es tab lished,dig its and let ters can be shown by se lect ing which port lines are set and which arenot. For ex am ple, in the Seven-Seg ment LED of Fig ure 9-6, the digit 2 can be dis -played by set ting seg ments a, b, g, e, and d. In this par tic u lar wir ing, these seg mentscor re spond to port B lines 0, 1, 6, 4, and 5.

Con ver sion of the in di vid ual dig its to port dis play codes can be ac com plished bymeans of a lookup ta ble. The pro cess ing de pends on three spe cial fea tures of PIC as -sem bly lan guage:

1. The pro gram coun ter file reg is ter (la beled PC and lo cated at off set 0x02) holds thead dress in mem ory of the current in struc tion. Be cause each PIC in struc tion takes

146 Chap ter 9

16F84

Osc

a

PWRON

b

cd

e e

f

f

g

g

d

c

b

a

+5V

+5V

+5V

R=

10

K

RA2

RA3

RA4/TOCKI

MCLR

Vss

RB0/INT

RB1

RB2

RB3

1

2

3

4

5

6

7

8

9

18

17

16

15

14

13

12

11

10

RA1

RA0

OSC1

OSC2

Vdd

RB7

RB6

RB5

RB4

220 RX 7

7-segmentLED

Page 168: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

up a sin gle byte (ex cept for those that mod ify the PC), one can jump to con sec u tiveen tries in a ta ble by add ing an in te ger value to the pro gram coun ter.

2. The addwf in struc tion can be used to add a value in the w register to the pro gramcoun ter.

3. The retlw in struc tion re turns to the caller a lit eral value stored in the w register. Inthe case of retlw, the lit eral value is the in struc tion op er and.

If the lookup ta ble is lo cated at a sub rou tine called getcode, then the pro cess ingcan be im ple mented as fol lows:

getcode:

addwf PC,f ; Add value in w reg is ter to pro gram coun ter

retlw 0x3f ; code for num ber 0

retlw 0x06 ; code for num ber 1

retlw 0x5b ; code for num ber 2

...

retlw 0x6f ; code for num ber 9

The call ing rou tine places in the w reg is ter the nu meric value whose code is de -sired, and then calls the ta ble lookup as fol lows:

movlw 0x03 ; Code for num ber 3 de sired

call getcode

movwf PORTB ; Dis play 3 in 7-seg ment dis play

A pro gram and cir cuit to dem on strate pro gram ming the Seven-Seg ment LED isof fered in the fol low ing sec tion.

9.5 I/O Demo BoardDem on stra tion (or demo) boards are a use ful tool in mas ter ing PIC pro gram ming.Many are avail able com mer cially and, like pro gram mers, a cot tage in dus try of PICdemo boards has ap peared on the Internet. Con struct ing your own demo boards is nota dif fi cult task and serves to ac quire cir cuit prototyping skills. Here again, the com po -nents can be placed on a bread board, wire-wrapped onto a spe cial cir cuit board, aprinted cir cuit board can be home-made, or or dered through the Internet. These op -tions have been pre vi ously dis cussed, and Ap pen dix G con tains in struc tions on howto build your own PCB for the dem on stra tion boards used in the book.

Fig ure 9-7 shows the sche mat ics of a sim ple 16F84-based demo board for ex per i -ment ing with sim ple in put and out put de vices, in clud ing a Seven-Seg ment LED, abank of eight LEDs, buzzer, pushbutton switch, and a bank of four tog gle switches.

Note that the Demo Board A in Fig ure 9-7 con tains three jumper switches, la beled J1, J2, and J3. The jumper switches are wired to ground and are used to de-se lect the cor re spond ing com po nent. For ex am ple, if the J1 switch is closed and J2 is open,then port B is dis played on the Seven-Seg ment LED but not in the eight-LED bank.By the same to ken, jumper J3 de-se lects the buzzer.

I/O Cir cuits and Pro grams 147

Page 169: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 9-7 PIC 16F84 Demo Board.

9.5.1 TestDemo1 Pro gram

The fol low ing pro gram ex er cises some of the ex per i ments that can be im ple mentedon the demo board in Fig ure 9-7. The pro gram reads the state of the pushbutton switchwired to port RA4. If the switch is closed, the buzzer is ac ti vated. Oth er wise, thebuzzer is turned off. The pro gram also reads the state of the four tog gle switches wired to the four low-or der lines of port B. The re sult ing value is used to dis play the dec i maldig its 0 to 9 and the hex a dec i mal let ters A through F on the Seven-Seg ment LED. Thecor re spond ing code is ob tained from a lo cal lookup ta ble as de scribed ear lier in thischap ter.

148 Chap ter 9

16F84A

5V regulated power supply

Osc

+5V

+5V

R=

10K

R=

10

K

R=

380

Oh

m

C=0.1mFEC=100mF

78L05

INOUT9 -12V DC+5V DC

+

RA2

RA3

RA4/TOCKI

MCLR

Vss

RB0/INT

RB1

RB2

RB3

1

2

3

4

5

6

7

8

9

18

17

16

15

14

13

12

11

10

RA1

RA0

OSC1

OSC2

Vdd

RB7

RB6

RB5

RB4

10k RX 4

DIP SW X 4

REDPUSHBUTTON

SWITCH

POWERON/OFF LED

RESETSWITCH

PiezoBuzzer

RB0

RB0

RB7

RB1

RB1

GR

EE

N L

ED

SR

ED

LE

DS

RB2

RB2

RB3

RB3

RB4RB4

RB6

RB7

J1

J2

J3

RB6

R=330 OhmX 8

PORT B linesto LEDs 0-7,7-seg LED,and Buzzer

RB5

RB5

a

+5v

b

cd

e e

f

f

g

g

d

c

b

a

7-segmentLED

Page 170: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; File: TestDemo1.asm; Date: June 2, 2011; Au thors: Can ton and Sanchez; Pro ces sor: 16F84A;; De scrip tion:; Pro gram to ex er cise the dem on stra tion cir cuit and board; in Fig ure 9-7;===========================; switches;===========================; Switches used in __config di rec tive:; _CP_ON Code pro tec tion ON/OFF ; * _CP_OFF ; * _PWRTE_ON Power-up timer ON/OFF; _PWRTE_OFF ; _WDT_ON Watchdog timer ON/OFF ; * _WDT_OFF ; _LP_OSC Low power crys tal os cil la tor; * _XT_OSC Ex ter nal par al lel res o na tor/crys tal; os cil la tor ; _HS_OSC High speed crys tal res o na tor (8 to 10 MHz); Res o na tor: Murate Erie CSA8.00MG = 8 MHz ; _RC_OSC Re sis tor/ca pac i tor os cil la tor; |; |_____ * in di cates setup val ues

pro ces sor 16f84Ain clude <p16f84A.inc>__config _XT_OSC & _WDT_OFF & _PWRTE_ON & _CP_OFF

;=====================================================; vari ables in PIC RAM;=====================================================

cblock 0x0c ; Start of blockcount1 ; Coun ter # 1j ; coun ter Jk ; coun ter Kendc

;=======================================================; P R O G R A M;=======================================================

org 0 ; start at ad dress 0goto main

;; Space for in ter rupt han dlers

org 0x08main:; Port A (5 lob) for in put

movlw B’00011111’ ; w := 00001111 bi narytris PORTA ; port A (lines 0 to 4) to in put

; Port bit (8 lines) for out putmovlw B’00000000’ ; w := 00000000 bi narytris PORTB ; port B to out put

;==============================; Pushbutton switch pro cess ing;==============================pbutton:; Pushbut ton switch on demo board is wired to RA4; Switch logic is ac tive low

btfss PORTA,4 ; Test and skip if bit is set

I/O Cir cuits and Pro grams 149

Page 171: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

goto buzzit ; Buz if switch ON; At this point port A bit 4 is set (switch is off)

call buzoff ; Buzzer offgoto readdip ; Read DIP switches

buzzit:call buzon ; Turn on buzzergoto pbutton

;==============================; DIP switch pro cess ing;==============================; Read all bits of port Areaddip:

movf PORTA,w ; Port A bits to w; If board uses ac tive low then all switch bits must be ne gated; This is done by XORing with 1-bits

xorlw b’11111111’ ; In vert all bits in w; Elim i nate all 4 high or der bits

andlw b’00001111’ ; And with mask; Get digit into w

call seg ment ; get digit codemovwf PORTB ; Dis play digitcall de lay ; Give time

; Updade digit and loop coun tergoto pbutton

;*******************************; 7-seg ment ta ble of hex codes;*******************************seg ment:

addwf PCL,f ; PCL is pro gram coun ter latchretlw 0x3f ; 0 coderetlw 0x06 ; 1retlw 0x5b ; 2retlw 0x4f ; 3retlw 0x66 ; 4retlw 0x6d ; 5retlw 0x7d ; 6retlw 0x07 ; 7retlw 0x7f ; 8retlw 0x6f ; 9retlw 0x77 ; Aretlw 0x7c ; Bretlw 0x39 ; Cretlw 0x5b ; Dretlw 0x79 ; Eretlw 0x71 ; Fretlw 0x7f ; Just in case all on

;****************************; piezo buzzer ON;****************************; Rou tine to turn on piezo buzzer on port B bit 7buzon:

bsf PORTB,7 ; Tune on bit 7, port Bre turn

;****************************; piezo buzzer OFF;****************************; Rou tine to turn off piezo buzzer on port B bit 7

150 Chap ter 9

Page 172: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

buzoff:bcf PORTB,7 ; Bit 7 port b clearre turn

;================================; de lay sub-rou tine;================================de lay:

movlw .200 ; w = 200 dec i malmovwf j ; j = w

jloop:movwf k ; k = w

kloop:decfsz k,f ; k = k-1, skip next if zerogoto kloopdecfsz j,f ; j = j-1, skip next if zerogoto jloopre turn

end

9.6 Com par i sons in PIC Pro gram mingThe power and use ful ness of pro grams is due, in great mea sure, to their de ci sion-mak -ing abil ity, and de ci sions are based on com par i son. In a com par i son, code is able tomake de ci sions based on the rel a tive val ues of two operands. For ex am ple, com parethe val ues a and b. If a is greater than b, ex e cute a cer tain coded rou tine; if b is greaterthan a, ex e cute an other one; and if both operands have the same value, then pro ceedto a third code branch.

CISC and even some RISC mi cro pro ces sors con tain a com pare op er a tor in theirin struc tion set. How ever, the com pare can be sub sti tuted, with some in con ve -nience, by a sub trac tion. Be cause there is no com pare op er a tion in the mid-range IC in struc tion set, the pro gram mer is forced to sim u late the com par i son by sub tract ing the w reg is ter from a lit eral value or from a file reg is ter. The sublw and subwf in -struc tions can be used for this. Af ter the sub trac tion takes place, code can make de -ci sions based on the state of the zero and the carry flags. For ex am ple, the fol low ing code frag ment com pares the value in the two reg is ters, la beled OP1 and OP2 re spec -tively, and directs execution to three possible routines:

; De clare vari ables at 2 mem ory lo ca tionsOP1 equ 0x0c ; First op er andOP2 equ 0x0d ; sec ond op er and...main:

movlw 0x30 ; First op er andmovwf OP1 ; to OP1 reg is termovlw 0x50 ; Sec ond op er andmovwf OP2 ; To OP2 reg is termovf OP2,w ; OP2 to w reg is ter (not re ally nec es sary)subwf OP1,w ; Sub tract w (OP2) from OP1btfsc STATUS,2 ; 2 is zero bit. Test zero flag.

; Skip next in struc tion if Z bit = 0,; that is if both num bers are not the; same

goto ops_are_eq ; OP2 = w rou tine

I/O Cir cuits and Pro grams 151

Page 173: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; At this point the zero flag is not set. There fore the two op er and

; are not equal

; Now test the carry flag for OP1 < OP2, in this case C = 1

btfss STATUS,0 ; 0 is carry bit. Test carry flag

; and skip next in struc tion if

; C bit = 1

goto op2big ; OP2 > w rou tine

; Pro cess ing for the case OP1 > OP2

nop

goto done

ops_are_eq:

; Pro cess ing for the case OP1 = OP2l

nop

nop

goto done

op2big:

; Pro cess ing for the case OP1 < OP2

nop

nop

done:

goto done

end

9.6.1 PIC Carry Flag

In mid-range PIC microcontrollers it is some what un usual that the ef fects on the carry flag are dif fer ent in ad di tion than in sub trac tion. Dur ing ad di tion (addwf and addlw),the carry flag in di cates a carry out of the most sig nif i cant bit of the re sult. In this case,C = 1 if there was a carry out, and C = 0 oth er wise. How ever, in sub trac tion, the carryflag is de scribed in the Micro chip doc u men ta tion as be hav ing as an in verted borrow.When two num bers are sub tracted and the re sult is too big to fit in the des ti na tion op -er and, then the carry flag is clear. What this amounts to is that in PIC sub trac tion(sublw and subwf op er a tions), the carry bit is set if there is no carry out of the high-or -der bit. This un usual be hav ior is shown in the pre ced ing code frag ment.

152 Chap ter 9

Page 174: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Chap ter 10

PIC In ter rupt Sys tem

10.1 In ter ruptsAn in ter rupt is an asyn chron ous sig nal call ing for pro ces sor at ten tion. In ter rupts canorig i nate in hard ware or in soft ware. The in ter rupt mech a nism is a way to avoid wast -ing pro ces sor time, be cause with out in ter rupts code has to poll hard ware de vices inin ef fec tive, closed-loops. With in ter rupts the pro ces sor can con tinue to do its workbe cause the in ter rupt mech a nism en sures that the CPU will re ceive a sig nal when everan event oc curs that re quires its at ten tion. PIC microcontrollers pro vide vary ing lev -els of sup port for in ter rupts. We fo cus on in ter rupts on the 16F84. Other mem bers ofthe mid-range PIC fam ily sup port in ter rupts with mi nor vari a tions.

10.1.1 16F84 In ter ruptsFour dif fer ent sources of in ter rupts are avail able in the 16F84. These are dis cussed inthe fol low ing sec tion. One in struc tion named RETFIE (for re turn from in ter rupt) isspe cif i cally re lated to in ter rupt pro cess ing. Its pur pose is to re turn to the pro gramcoun ter the ad dress of the in struc tion that fol lows the lo ca tion in code where the in -ter rupt took place. It does so by load ing into the pro gram coun ter reg is ter the 13-bitad dress saved at the top of the stack. In ad di tion, RETFIE sets the Global In ter ruptEn able bit in the INTCON reg is ter (dis cussed in the fol low ing sec tion) an ac tion thatau to mat i cally reenables in ter rupts.

In ad di tion to the RETFIE in struc tion, two PIC hard ware el e ments re late di rectlyto in ter rupts: the OPTION register and the INTCON (in ter rupt con trol) reg is ter.Both reg is ters are read able and writeable and con tain bits that al low set ting up,con trol ling, and de tect ing the var i ous in ter rupts. The In ter rupt Con trol Register(INTCON) re cords in di vid ual in ter rupt re quests in flag bits. It also con tains the in di -vid ual and global in ter rupt en able bits. The OPTION register has sev eral bits thatmust be ac cessed in or der to ini tial ize in ter rupts.

10.1.2 In ter rupt Con trol Reg is terThe In ter rupt Con trol (INTCON) reg is ter is a read able and writeable reg is ter lo catedat off set 0x08 in bank 0. The INTCON reg is ter con tains two classes of bits: bits to en -able and dis able the var i ous in ter rupt sources, and flag bits that al low de tect ing the

153

Page 175: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

oc cur rence of the var i ous in ter rupts. The bits to en able and dis able in ter rupts havenames that end with the let ter E, while the in ter rupt flag bit names end with the let terF. This has sug gested call ing them the INTCON E and the F bits. Fig ure 10-1 is a bitmapof the INTCON register.

Fig ure 11-1 INTCON Reg is ter Bitmap.

10.1.3 OPTION Reg is terThe OPTION reg is ter is a read able and writeable reg is ter that con tains con trols forcon fig ur ing the prescaler bits and as sign ing them to ei ther Timer0 or the Watch dogTimer; for se lect ing the in cre ment mode on the RA4/TOCKI pin, the Timer0 sourceclock, the rais ing or fall ing edge in the RB0 interrupt; and for en abling and dis ablingthe in ter nal Port B pull-up re sis tors. The OPTION reg is ter is lo cated in Bank1, at ad -dress 0x81. Al though this reg is ter is not di rectly re lated to in ter rupts, sev eral of itsbits are re lated to the var i ous in ter rupts. Fig ure 10-2 is a bitmap of the OPTION reg is -ter.

154 Chap ter 10

GIE

bit 0bit 7

EEIE TOIE INTE RBIE TOIF INTF RBIF

bit 7 GIE: Global Interrupt Enable bit 1 = Enables all unmasked interrupts 0 = Disables all interruptsbit 6 EEIE: EE Write Complete Interrupt Enable bit 1 = Enables the EE Write Complete interrupts 0 = Disables the EE Write Complete interruptbit 5 T0IE: TMR0 Overflow Interrupt Enable bit 1 = Enables the TMR0 interrupt 0 = Disables the TMR0 interruptbit 4 INTE: RB0 Interrupt Enable bit 1 = Enables the RB0 external interrupt 0 = Disables the RB0 external interruptbit 3 RBIE: Port Change Interrupt Enable bit 1 = Enables the RB port change interrupt 0 = Disables the RB port change interruptbit 2 T0IF: TIMER0 Overflow Interrupt Flag bit 1 = TMR0 register has overflowed 0 = TMR0 register did not overflowbit 1 INTF: RB0 External Interrupt Flag bit 1 = The RB0/INT external interrupt occurred 0 = The RB0/INT external interrupt did not occurbit 0 RBIF: RB0-RB3 Port Change Interrupt Flag bit 1 = At least one of the RB7:RB4 pins changed state 0 = None of the RB7:RB4 pins have changed state

Page 176: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Figure10-2 OPTION Reg is ter Bitmap.

10.2 In ter rupt Sources The 16F84 sup ports four dif fer ent sources of in ter rupt:

1. Ex ter nal in ter rupt de tected by line 0 of port B

2. In ter rupts that orig i nate in the timer (TMR0 overflow interrupt)

3. In ter rupts orig i nated in changes of lines RB7 to RB4 in port B

4. EEPROM com plete data write in ter rupt

Other mem bers of the mid-range PIC fam ily sup port ad di tional in ter rupts; for ex -am ple, the 16F684 has ten sources of in ter rupts, as follows:

1. Ex ter nal in ter rupt RA2/INT

2. Timer0 over flow in ter rupt

PIC In ter rupt Sys tem 155

RBPU

bit 0

Prescaler bits

bit 7

INTEDG TOCS TOSE RBIE PS2 PS1 PS0

bit 7 RBPU: Port B Pull-up Enable bit 1 = Port B pull-ups are disabled 0 = Port B pull-ups are enabled by individual port latch valuesbit 6 INTEDG: Interrupt Edge Select bit 1 = Interrupt on rising edge of RB0 0 = Interrupt on falling edge of RB0bit 5 T0CS: TMR0 Clock Source Select bit 1 = Transition on RA4/T0CKI pin 0 = Internal instruction cycle clock (CLKOUT)bit 4 T0SE: TMR0 Source Edge Select bit 1 = Increment on high-to-low transition on RA4/T0CKI pin 0 = Increment on low-to-high transition on RA4/T0CKI pinbit 3 PSA: Prescaler Assignment bit 1 = Prescaler is assigned to the Watchdog Timer 0 = Prescaler is assigned to the Timer0 modulebit 2-0 PS2:PS0: Prescaler Rate Select bits Value Timer0 Rate WDT Rate 000 1:2 1:1 001 1:4 1:2 010 1:8 1:4 011 1:16 1:8 100 1:32 1:16 101 1:64 1:32 110 1:128 1:64 111 1:256 1:128

Page 177: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

3. PORTA change in ter rupts

4/5. Two com para tor in ter rupts

6. A/D in ter rupt

7. Timer1 over flow in ter rupt

8. Timer2 match in ter rupt

9. EEPROM data write in ter rupt

10. Fail-safe clock mon i tor in ter rupt

11. En hanced CCP in ter rupt

In the sec tions that fol low we dis cuss the 16F84 in ter rupt sources.

10.2.1 Port B Ex ter nal In ter ruptThis ex ter nal in ter rupt is trig gered by ei ther the ris ing or fall ing sig nal edge on port B,line 0. Whether the in ter rupt takes place on the ris ing or fall ing edge of the sig nal de -pends on the set ting of the INTEDG bit of the OPTION reg is ter. The port B in ter rupt isuse ful in de tect ing and re spond ing to ex ter nal events, for ex am ple, in mea sur ing thefre quency of a sig nal or in re spond ing with some PIC ac tion to a change in the state of a hard ware de vice. This in ter rupt can be dis abled by clear ing the cor re spond ing bit inthe INTCON reg is ter. If en abled, once the in ter rupt takes place, code must clear thecor re spond ing flag bit be fore reenabling the in ter rupt.

Sup pose there is a cir cuit con tain ing an emer gency switch that the user will ac ti -vate on the oc cur rence of some crit i cal event. One pos si ble ap proach is to check the state of the switch by con tin u ously poll ing the port to which it is wired. But in acom plex pro gram, code would have to en sure that the switch poll ing rou tine iscalled with suf fi cient fre quency so that an emer gency event is de tected im me di -ately. A more ef fec tive so lu tion is to con nect the emer gency switch to line num ber 0of port B and set up the port B ex ter nal in ter rupt source. In this case, when ever theemer gency switch is ac ti vated, the pro gram im me di ately re sponds via the in ter ruptmech a nism. Fur ther more, once the in ter rupt code has been de vel oped and de -bugged, it will con tinue to func tion cor rectly no matter what changes are made tothe rest of the program.

10.2.2 Timer0 In ter ruptThe 16F84 is equipped with a spe cial timer mod ule, named Timer0, which can serveboth as a timer and as a coun ter. The Timer0 mod ule, dis cussed in greater de tail in thenext chap ter, con sists of an 8-bit read able reg is ter op er ated by an in ter nal or ex ter nalclock and at tached to an 8-bit pro gram ma ble prescaler. The prescaler is used to de laythe timer by di vid ing the clock sig nal. The Timer0 mod ule can be setup to in ter rupt onover flow. In this case an in ter rupt is gen er ated when ever the coun ter goes from 0xff to 0x00.

The Timer0 coun ter in ter rupt can be used to mea sure events and to re spond toelapsed pe ri ods. For ex am ple, the timer is used to mea sure events by de ter min ingthe num ber of timer in ter rupts that have taken place be cause an event oc curred, be -cause the timer of each in ter rupt can be de ter mined from the pro ces sor clock speed

156 Chap ter 10

Page 178: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

and the prescaler setup. In this man ner the event time is cal cu lated by mul ti ply ingthe time of each in ter rupt by the num ber of in ter rupts that have oc curred. In thiscase the in ter rupt rou tine would in cre ment a coun ter reg is ter, which is ac ces si bleto code any where in the pro gram. So the ac tual count can be re set from inside oroutside the service routine.

In re spond ing to an elapsed pe riod, the Timer0 in ter rupt ser vice rou tine not onlykeeps track of the time elapsed be cause the event, but also tests for a cer tain coun -ter value that rep re sents the de sired time limit. Once the timer coun ter reaches thispre set limit, the ser vice rou tine re sponds di rectly to the re quired action.

One pow er ful and com mon ap pli ca tion of a Timer0 in ter rupt is in im ple ment ingse rial com mu ni ca tions. In this case the timer in ter rupt is set up to take place at thebaud rate at which the se rial line must be polled for data or at which in di vid ual databits are sent. The sam ple pro gram LapseTmrInt, de vel oped later in this book, dem -on strates this use of the timer interrupt.

10.2.3 Port B Line Change In ter rupt

The third 16F84 in ter rupt source re lates to a change in the value stored in port B lines 4 to 7. When this in ter rupt is en abled, any change in sta tus in any of the four port B pinsla beled RB7, RB6, RB5, and RB4 will trig ger an in ter rupt. The in ter rupt can be set up to take place when the pin sta tus changes from logic 1 to logic0, or vice versa. For this in -ter rupt to take place, port B pins 4 to 7 must be de fined as in put. Oth er wise, the in ter -rupt does not take place.

The port B line change in ter rupt pro vides a mech a nism for mon i tor ing up to fourdif fer ent in ter rupt sources, typ i cally orig i nat ing in hard ware de vices. When the in -ter rupt is en abled, the cur rent state of the port B lines is con stantly com pared to the old val ues. If there is a change in state in any of the four lines, the interrupt isgenerated.

Im ple men ta tion of the line change in ter rupt is not with out com pli ca tions. Thecir cuit and soft ware de signer must take into ac count the char ac ter is tics of the ex -ter nal sig nal be cause only then can code be de vel oped that will cor rectly han dle the var i ous pos si ble sources. Two pieces of in for ma tion that are necessary in this caseare

1. The sig nal’s ris ing edge and fall ing edges

2. The pulse width of the in ter rupt trig ger

The need to de ter mine whether the sig nal is on a ris ing or fall ing edge is to en sure that the ser vice rou tine is en tered only for the de sired edge. For ex am ple, if the de -vice is an ac tive-low pushbutton switch, an in ter rupt will typ i cally be de sired on thesig nal’s fall ing edge, that is, when it goes from high to low.

Knowl edge about the sig nal’s width de ter mines the pro cess ing re quired by theser vice rou tine. This is due to the fact that both the ris ing and the fall ing edge of thesig nal can trig ger the in ter rupt. So, if the trig ger ing sig nal has a small pulse widthcom pared to the time of ex e cu tion of the in ter rupt han dler, then the in ter rupt line

PIC In ter rupt Sys tem 157

Page 179: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

will have re turned to the in ac tive state be fore the ser vice rou tine com pletes and apos si ble false in ter rupt on the sig nal’s fall ing edge is not pos si ble. On the otherhand, if the pulse width of the in ter rupt sig nal is large and the ser vice rou tine com -pletes be fore the sig nal re turns to the in ac tive state, then the sig nal’s fall ing edgecan trig ger a false interrupt. Figure 10-3 shows both situations.

Fig ure 10-3 Sig nal Pulse Width and In ter rupt La tency.

In the con text of Fig ure 11-3 the pe riod be tween the edge that trig gers the in ter -rupt and the ter mi na tion of the in ter rupt han dler is some times called the mis matchpe riod. The mis match pe riod ter mi nates when the ser vice rou tine com pletes andthe cor re spond ing in ter rupt is reenabled. If this hap pens af ter the in ter rupt sig nal is re set, no pos si ble false in ter rupt can take place and no spe cial pro vi sion is re quiredin the han dler. In fact, the in ter rupt han dler will run cor rectly as long as the ser vicerou tine takes lon ger to ex e cute than the in ter rupt fre quency. How ever, if the han -dler ter mi nates be fore the sig nal re turns to its orig i nal state, then the han dler mustmake spe cial pro vi sions to han dle a pos si ble false in ter rupt. In or der to do this, thehan dler must first de ter mine if the in ter rupt took place on the ris ing or the fall ingsig nal edge, which can be done by ex am in ing the cor re spond ing port B line. For ex -am ple, if the in ter rupt is to take place on the ris ing edge only, and the line is low,then it can be ig nored be cause it took place on the fall ing edge.

When an in ter rupt can take place on ei ther the ris ing or the fall ing edge of thetrig ger ing sig nal, the in ter rupt source must have a min i mum pulse width in or der toen sure that both edges are de tected. In this case, the min i mum pulse width is themax i mum time from the edge that trig gered the in ter rupt to the mo ment when thein ter rupt flag is cleared. Oth er wise, the in ter rupt will be lost be cause the in ter ruptmech a nism will be dis abled at the time it takes place.

158 Chap ter 10

Signal

Signal

CASE 1: relatively small pulse width

CASE 2: relatively large pulse width

Rising edgetriggers interrupt

Rising edgetriggers interrupt

Interrupt handlerprogress

Interrupt handlerin progress

Service routine completeInterrupt flag clearNo possible false interrupt

Service routine completeInterrupt flag cleared

Falling edge can triggerfalse interrupt

Page 180: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

The pre ced ing dis cus sion leads di rectly to the pos si bil ity of an in ter rupt tak ingplace while the ser vice rou tine of a pre vi ous in ter rupt is still in prog ress. These arecalled reentrant or nested in ter rupts. Sev eral things must hap pen in or der to al lowreentrant in ter rupts. One of them is that in ter rupts must be reenabled be fore thehan dler ter mi nates. In ad di tion, the ser vice rou tine must be able to cre ate dif fer entin stances of the vari ables in use, usu ally al lo cated in the stack. The lack of a pro -gram-ac ces si ble stack and the PIC in ter rupt mech a nism it self, forces the con clu sion that reentrant in ter rupts should not be at tempted in PIC pro grams.

Mul ti ple Ex ter nal In ter rupts

One of the prac ti cal ap pli ca tions of the port B line change in ter rupt is in han dling sev -eral dif fer ent in ter rupt sources. For ex am ple, a cir cuit can con tain four pushbuttonswitches that ac ti vate four dif fer ent cir cuit re sponses. If the switches are wired to thecor re spond ing pins in port B (RB4 to RB7) and the line change in ter rupt is en abled, the in ter rupt will take place when any one of the four switches changes level, that is, when any one of the in ter rupt lines goes from high to low or from low to high. The in ter rupthan dler soft ware can de ter mine which of the switches changed state and if the change took place on the sig nal’s ris ing or fall ing edge. The cor re spond ing soft ware rou tineswill then han dle each case.

Later in this chap ter we de velop a sam ple pro gram that uses the port B linechange in ter rupt to re spond to ac tion on four pushbutton switches.

10.2.4 EEPROM Data Write In ter rupt

The or i gin of this in ter rupt re lates to the rel a tive slow ness of the EEPROM data writeop er a tion, which is 10 ms on the 16F84. The in ter rupt serves no other func tion than toal low the microcontroller to con tinue ex e cu tion while the data write op er a tion is inprog ress. The in ter rupt ser vice rou tine informs the microcontroller when writ ing hasended through the EEIF bit lo cated in the EECON1 reg is ter. The use of this in ter rupt is con sid ered in Chap ter 14, in the con text of EEPROM data mem ory ac cess and pro -gram ming.

10.3 De vel op ing the In ter rupt Han dlerThe in ter rupt han dler, also called the in ter rupt ser vice rou tine or the ISR, is the code that re ceives con trol upon the oc cur rence of the in ter rupt. Most of the pro gram mingthat goes into the ser vice rou tine is spe cific to the ap pli ca tion; how ever, there are cer -tain house keep ing op er a tions that should be in cluded al most uni ver sally. The fol low -ing list de scribes the struc ture of an in ter rupt ser vice rou tine for the mid-range PICs:

• Pre serve the value of the w reg is ter.

• Pre serve the value of the STATUS register.

• Ex e cute the ap pli ca tion-spe cific op er a tions.

• Re store the value of the STATUS register at the time of the in ter rupt.

• Re store the value of the w reg is ter at the time of the in ter rupt.

• Is sue the RETFIE in struc tion to end the in ter rupt han dler.

PIC In ter rupt Sys tem 159

Page 181: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

In the PIC 16F84, the in ter rupt ser vice rou tine must be lo cated at off set 0x004 incode mem ory. A sim ple org di rec tive takes care of en sur ing this lo ca tion, as in thefol low ing code fragment:

org 0x000 ; Be gin ning of code areagoto start ; Jump to pro gram startorg 0x004 ; Start of Ser vice rou tine.. ; SERVICE ROUTINE GOES HERE.retfie ; End of ISR

start: ; Pro gram starts here

Al ter na tively, code can place a jump at off set 0x004 and lo cate the Ser vice Rou -tine else where in the code. In this case it is im por tant to re mem ber not to call theSer vice Rou tine, but to ac cess it with a goto in struc tion. The rea son is that the callopcode places a re turn ad dress in the stack, which will make the retfie instructionfail.

10.3.1 Con text Sav ing Op er a tionsThe only value au to mat i cally pre served by the in ter rupt mech a nism is the Pro gramCoun ter (PC), which is stored in the stack. Ap pli ca tions of ten need to re store the hard -ware reg is ters in the CPU to the same state as when the in ter rupt took place, so thefirst op er a tion of most in ter rupt han dlers is sav ing the pro ces sor con text. This con -text usu ally in cludes the W and the STATUS reg is ters. Oc ca sion ally at this time the ap -pli ca tion may save other user-de fined reg is ters.

Sav ing W and STATUS Reg is ters

Sav ing the W and the STATUS reg is ters re quires us ing reg is ter vari ables, but the pro -cess must take some other el e ments into ac count. Sav ing the w reg is ter is sim pleenough: its value at the start of the Ser vice Rou tine is stored in a lo cal vari able fromwhich it is re stored at ter mi na tion. But sav ing the STATUS reg is ter can not be donewith MOVF in struc tion be cause this in struc tion changes the zero flag. The so lu tion isto use the SWAPF in struc tion which does not af fect any of the flags. Of course, SWAPF in verts the nib bles in the op er and, so the pro cess must be re peated in or der to re storethe orig i nal state. The fol low ing code frag ment as sumes that file reg is ter vari ablesnamed old_w and old_sta tus were pre vi ously cre ated:

save_cntx:movwf old_w ; Save w reg is terswapf STATUS,w ; STATUS to wmovwf old_sta tus ; Save STATUS

;; In ter rupt han dler op er a tions go here;

swapf old_sta tus,w ; Saved sta tus to wmovfw STATUS ; To STATUS reg is ter

; At this point all op er a tions that change the ; STATUS reg is ter must be avoided, but swapf does not.

swapf old_w,f ; Swap file reg is ter in it selfswapf old_w,w ; re-swap back to wretfie

160 Chap ter 10

Page 182: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

10.4 In ter rupt Pro gram mingIn the sec tions that fol low we dis cuss pro gram ming in ter rupts that orig i nate in port B,line 0, and those that orig i nate in changes of port B lines RB4 to RB7. In ter rupts that re -late to the Timer0 over flow or to EEPROM data write op er a tions are cov ered in thechap ter on EEPROM Data Op er a tions.

10.4.1 Pro gram ming the Ex ter nal In ter ruptIn ter rupts de tected on port B, line 0, are re ferred to as the Ex ter nal In ter rupt source.The name is not the most ad e quate be cause other in ter rupts can also have ex ter nalsources. One of the im por tant uses of this in ter rupt source is to wake the pro ces sorfrom the SLEEP mode. This al lows de vel op ing ap pli ca tions that can run on a smallpower source (such as bat ter ies) be cause the pro gram uses al most no power un tilsome ac tion as so ci ated with the in ter rupt source wakes up the PIC. A sam ple pro gram us ing the RB0 in ter rupt is de vel oped later in this chap ter. Our first sam ple pro gram isa sim ple dem on stra tion of the in stal la tion and ac tion of the in ter rupt. The pro gram isbased on the cir cuit in Fig ure 10-4.

Fig ure 10-4 Cir cuit for RB0 In ter rupt Dem on stra tion.

PIC In ter rupt Sys tem 161

16F84

4 MHzOsc

10K Ohms

4.7K Ohms

2x470 Ohms

green red

+5 V

+5 V

+5 V

RA2 RA3 T0Tkl MCLR Vss RB0/INT RB1 RB2 RB3

1 2 3 4 5 6 7 8 9

18 17 16 15 14 13 12 11 10

RA1 RA0 OSC1 OSC2 Vdd RB7 RB6 RB5 RB4

Page 183: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

In the cir cuit of Fig ure 10-4, a pushbutton switch is wired to the RB0 port. Thisswitch pro duces the in ter rupt when pressed. A red LED is wired to port RB1 and agreen LED to port RB2. The main pro gram flashes the green LED on and off at a rate of ap prox i mately one-half sec ond. The red LED is tog gled on and off when thepushbutton switch is pressed. The switch con tains a 4.7K-Ohm re sis tor that keepsthe port high un til the con tact is made and sent to ground. This makes the switch ac -tive low, and the in ter rupt is pro grammed on the fall ing edge of the sig nal, whichtakes place when the contact is made.

RB0 In ter rupt Ini tial iza tion

In or der to ini tial ize the RB0 in ter rupt the fol low ing op er a tions must take place:

• Port B, line 0, must be in i tial ized for in put.

• The in ter rupt source must be set to take place ei ther on the fall ing or the ris ing edgeof the sig nal.

• The ex ter nal interrupt flag (INTF in the INTCON reg is ter) must be ini tially cleared.

• Global in ter rupts must be en abled by set ting the GIE bit in the INTCON reg is ter.

• The Ex ter nal In ter rupt on RB0 must be en abled by set ting the INTE bit in theINTCON reg is ter.

The fol low ing code frag ment, from the pro gram RB0Int in this book’s soft warepack age, per forms these op er a tions:

org 0x00goto main

;=============================; in ter rupt han dler;=============================

org 0x04goto IntServ

;=============================; main pro gram;=============================main:; Set up in ter rupt on fall ing edge; by clear ing OPTION reg is ter bit 6

movlw b’10111111’op tionmovlw b’11111111’ ; Set port A for in puttris porta ; (not nec es sary for this pro gram)movlw b’00000001’ ; Port B bit 0 is in puttris portb ; all oth ers are out putclrf portb ; All port B to 0

; Ini tially turn on LEDbsf portb,0 ; Set line 0 bit

;============================; setup in ter rupts;============================; Clear ex ter nal in ter rupt flag (intf = bit 1)

bcf INTCON,intf ; Clear flag; En able global in ter rupts (gie = bit 7); En able RB0 in ter rupt (inte = bit 4)

bsf INTCON,gie ; En able global int (bit 7)bsf INTCON,inte ; En able RB0 int (bit 4)

;============================

162 Chap ter 10

Page 184: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; flash LED;============================; Pro gram flashes LED wired to port B, line 2lights:

movlw b’00000010’ ; Mask with bit 1 setxorwf portb,f ; Com ple ment bit 1 call long_de lay ; Lo cal de lay rou tinecall long_de laycall long_de laygoto lights

RB0 ISR

The ser vice rou tine for the RB0 in ter rupt will de pend on the spe cific ap pli ca tion. Nev -er the less, the fol low ing pro cess ing steps should be con sid ered:

• De ter mine if the source is an RB0 interrupt.

• Clear the RB0 interrupt flag (INTF bit) in the INTCON reg is ter.

• Save the con text. Which reg is ters and vari ables need to be saved de pends on thespe cific ap pli ca tion.

• Per form the in ter rupt ac tion.

• Re store the con text.

• Re turn from the in ter rupt with the retfie in struc tion.

In ad di tion, the in ter rupt han dler may have to per form op er a tions that are spe -cific to the ap pli ca tion; for ex am ple, debounce a switch or ini tial ize lo cal vari ables.The fol low ing In ter rupt Ser vice rou tine is from the pro gram RB0Int in this book’s soft ware re source:

;=======================================================; In ter rupt Ser vice Rou tine;=======================================================; Ser vice rou tine re ceives con trol when there is; ac tion on pushbutton switch wired to port B, line 0IntServ:; First test if source is an RB0 in ter rupt

btfss INTCON,INTF ; INTF flag is RB0 in ter ruptgoto notRB0 ; Go if not RB0 or i gin

; Save con textmovwf old_w ; Save w reg is terswapf STATUS,w ; STATUS to wmovwf old_sta tus ; Save STATUS

;=========================; in ter rupt ac tion;=========================; Debounce switch; Logic:; Debounce al go rithm con sists in wait ing un til the; same level is re peated on a num ber of samplings of the; switch. At this point the RB0 line is clear because the; in ter rupt takes place on the fall ing edge. The rou tine; waits un til the low value is read sev eral times.

movlw D’10’ ; Num ber of rep e ti tionsmovwf count2 ; To coun ter

wait:

PIC In ter rupt Sys tem 163

Page 185: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; Check to see that port B bit 0 is still 0 ; If not, wait un til it changes

btfsc portb,0 ; Is bit set?goto exitISR ; Go if bit not 0

; At this point RB0 bit is cleardecfsz count2,f ; Count this it er a tiongoto wait ; Con tinue if not zero

; In ter rupt ac tion con sists of tog gling bit 2 of; port B to turn LED on and off

movlw b’00000100’ ; Xoring with a 1-bit pro duces; the com ple ment

xorwf portb,f ; Com ple ment bit 2, port B ;=========================; exit ISR;=========================exitISR:; Re store con text

swapf old_sta tus,w ; Saved sta tus to wmovfw STATUS ; To STATUS reg is terswapf old_w,f ; Swap file reg is ter in it selfswapf old_w,w ; re-swap back to w

notRB0:; Re set in ter rupt

bcf INTCON,intf ; Clear INTCON bit 1retfie

Note that the in ter rupt han dler listed pre vi ously con tains a debouncing rou tine in or der to clean the switch’s sig nal. In this par tic u lar im ple men ta tion, the de tec tion of a sig nal of the wrong value de ter mines that the in ter rupt is aborted. For the par tic u -lar switch used in the test cir cuit, this ap proach seemed to work better. Al ter na -tively, the rou tine can be de signed so that if a wrong edge is de tected, ex e cu tioncon tin ues in the wait loop. In any case, the en tire com pli ca tion of soft waredebouncing can be avoided by debouncing the switch in hardware.

10.4.2 Wake-Up from SLEEP Us ing the RB0 In ter ruptThe PIC microcontroller sleep mode pro vides a mech a nism for sav ing power that ispar tic u larly use ful in bat tery-op er ated de vices. The sleep mode is ac ti vated by ex e cut -ing the SLEEP in struc tion, which sus pends all nor mal op er a tions and switches off theclock os cil la tor. The sleep mode is suit able for ap pli ca tions that are not re quired torun con tin u ously. For ex am ple, a de vice that re cords tem per a ture at day break can bede signed so that a light-sen si tive switch gen er ates an in ter rupt that turns the de viceon each morn ing. Once the data is re corded, the de vice goes into the sleep mode un tilthe next day break.

Sev eral events can force the de vice to wake-up from the sleep mode:

• A re set sig nal on the !MCLR pin

• Watch dog timer wake-up sig nal, if WDT is en abled

• In ter rupt on RB0 line

• Port change in ter rupt on RB4 to RB7 lines

• EEPROM write com plete in ter rupt

164 Chap ter 10

Page 186: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

In the sleep mode the de vice is placed in a power-down state that gen er ates thelow est power con sump tion. The sys tem clock is turned off in the sleep mode so sig -nals that de pend on the clock can not be used to ter mi nate the sleep. If en abled, theWatch dog Timer is cleared by the sleep in struc tion but keeps run ning. The PD bit inthe STATUS reg is ter is also cleared and the TO bit is set. The ports main tain the sta -tus they had be fore the SLEEP in struc tion was executed.

The TO and PD bits in the STATUS reg is ter can be used to de ter mine the cause ofwake-up, as the TO bit is cleared if a Watch dog Timer wake-up took place. The cor -re spond ing in ter rupt en able bit must be set for the de vice to wake due to an in ter -rupt. Wake-up takes place re gard less of the state of the Gen eral In ter rupt En able(GIE) bit. If the bit is clear, the de vice con tin ues ex e cu tion at the in struc tion fol low -ing SLEEP. Oth er wise, the de vice ex e cutes the in struc tion af ter the SLEEP in struc -tion and then branches to the in ter rupt ad dress. If the ex e cu tion of the in struc tionfol low ing SLEEP is un de sir able, the pro gram should con tain a NOP in struc tion af ter the SLEEP in struc tion.

SleepDemo Pro gram

The pro gram called SleepDemo in this book’s on line soft ware pack age is a triv ial dem -on stra tion of us ing the RB0 in ter rupt to wakeup the pro ces sor from the sleep mode.The pro gram can be tested us ing the cir cuit in Fig ure 10-4. SleepDemo flashes thegreen LED at one-half sec ond in ter vals dur ing twenty it er a tions and then goes into thesleep mode. Press ing the pushbutton switch on line RB0 gen er ates an in ter rupt thatwakes the pro ces sor from the sleep mode. The fol low ing code frag ment shows thecod ing of the main loop in the pro gram:

;============================; flash LED 20 times;============================wakeUp:; Pro gram flashes LED wired to port B, line 2; 20 times be fore en ter ing the sleep state

movlw D’20’ ; Num ber of it er a tionsmovwf count2 ; To coun ter

lights:movlw b’00000010’ ; Mask with bit 1 setxorwf portb,f ; Com ple ment bit 1 call long_de laycall long_de laycall long_de laydecfsz count2 ; Dec re ment coun tergoto lights

; 20 it er a tions have taken placeclrwdt ; Clear WDTsleepnop ; Rec om mended! goto wakeUp ; Re sume ex e cu tion

In the SleepDemo pro gram, the In ter rupt Ser vice Rou tine does noth ing. Its cod -ing is as fol lows:

;=======================================================; In ter rupt Ser vice Rou tine;=======================================================

PIC In ter rupt Sys tem 165

Page 187: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; The in ter rupt ser vice rou tine per forms no op er a tion

IntServ:

bcf INTCON,INTF ; Clear flag

retfie

The ini tial iza tion of the RB0 in ter rupt is iden ti cal to the one in the RB0Int pro -gram pre vi ously listed.

10.4.3 Port B Bits 4-7 Sta tus Change In ter rupt

In the PIC 16F84 microcontroller, a change of in put sig nal on port B, lines 4 to 7, gen er -ates an in ter rupt. This in ter rupt will set the RBIF bit in the INTCON register to in di cate that at least one of the ports has changed value. The port change takes place when theport’s pre vi ous value changes from logic 1 to logic 0, or vice versa. In or der for portpins to rec og nize this in ter rupt, they must have been de fined as in put. If any one of theport pins (4 to 7) is de fined as out put, the in ter rupt will take place. The sta tus changeof the ports is in ref er ence to the last time port B was read.

The prin ci pal ap pli ca tion of this in ter rupt source is in de tect ing sev eral dif fer entin ter rupt sources. Its prin ci pal dis ad van tage is that it forces the dec la ra tion of fourport B lines as in put, al though dur ing pro cess ing not all lines need be rec og nized asin ter rupt sources. The con clu sion is that ap pli ca tions that only need a sin gle ex ter -nal in ter rupt source should use the RB0 in ter rupt de scribed in pre vi ous sec tions.Only ap pli ca tions that re quire more than one ex ter nal in ter rupt should use the portB lines 4 to 7 interrupt on change source.

Be cause the in ter rupt takes place on any sta tus change (high-to-low orlow-to-high) the ser vice rou tine ex e cutes on both sig nal edges. If in ter rupt pro cess -ing is re quired on only one edge, that is, ei ther when the port goes high or low, thenthe fil ter ing must be per formed in soft ware. The cir cuit in Fig ure 10-5 al lows test ing the Port B Sta tus Change Interrupt.

In the cir cuit of Fig ure 10-5, a pushbutton switch is wired to the RB7 port and an -other one to RB4. Both of these switches pro duce the in ter rupt when pressed. A redLED is wired to port RA0 and a green LED to port RA1. The red and green LEDs aretog gled on and off when the cor re spond ing pushbutton switches are pressed. Theswitches con tain a 4.7K-Ohm re sis tor that keeps the port high un til the con tact ismade and sent to ground. This makes both switches ac tive low, and the in ter rupt ispro grammed on the fall ing edge of the sig nal.

RB4-7 In ter rupt Ini tial iza tion

In or der to ini tial ize the RB4-7 change in ter rupt, the fol low ing op er a tions must takeplace:

• Port B lines 4 to 7 must be in i tial ized for in put.

• The in ter rupt source must be set to take place ei ther on the fall ing or the ris ing edgeof the sig nal.

• The RB port change in ter rupt flag (RBIF in the INTCON Reg is ter) must be ini tiallycleared.

166 Chap ter 10

Page 188: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 10-5 Cir cuit for Test ing the Port B Sta tus Change In ter rupt.

• Global in ter rupts must be en abled by set ting the GIE bit in the INTCON reg is ter.

• The RB port change in ter rupt must be en abled by set ting the RBIE bit in theINTCON reg is ter.

• In ter nal pull-ups on port B should be dis abled in the OPTION register.

The fol low ing code frag ment from the pro gram RB4to7Int in this book’s on linesoft ware pack age shows the re quired pro cess ing:

;=============================; main pro gram;=============================main:; Disable port B in ter nal pullups; In ter rupts on fall ing edge of pushbutton ac tion

Movlw b’10111111’op tion

; Wir ing:; 7 6 5 4 3 2 1 0 <= port B; | |_______________ red pushbutton; |________________________ black pushbutton;

PIC In ter rupt Sys tem 167

16F84

4 MHzOsc

10K Ohm

4.7K Ohm 4.7K Ohm

2x470 Ohm

greenred

+5 V

+5 V +5 V

+5 V

RA2 RA3 T0Tkl MCLR Vss RB0/INT RB1 RB2 RB3

1 2 3 4 5 6 7 8 9

18 17 16 15 14 13 12 11 10

RA1 RA0 OSC1 OSC2 Vdd RB7 RB6 RB5 RB4

Page 189: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; 7 6 5 4 3 2 1 0 <= port A; | |_____ red LED; |________ green LED;

movlw b’00000000’ ; Set port A for ouputtris portamovlw b’11110000’ ; Port B bit 0-3 are out put

; bits 4-7 are in puttris portb ; all oth ers are out putclrf portb ; All port B to 0movlw b’00000000’ ; Zero to wmovwf bitsB47 ; Store in lo cal vari able

; Ini tially turn on LEDsbsf porta,0 ; Set LEDs on line 0bsf porta,1 ; and on line 1

;============================; setup in ter rupts;============================; Clear ex ter nal in ter rupt flag (intf = bit 1)

bcf INTCON,rbif ; Clear flag; En able global in ter rupts (gie = bit 7); En able RB0 in ter rupt (inte = bit 4)

bsf INTCON,gie ; En able global int (bit 7)bsf INTCON,rbie ; En able RB0 int (bit 3)

RB4-7 Change ISR

The Ser vice Rou tine for the RB4-7 change in ter rupt will de pend on the spe cific ap pli -ca tion. Nev er the less, the fol low ing pro cess ing steps should be con sid ered:

• De ter mine if the source is an RB4-7 change in ter rupt.

• Clear the RBIF in ter rupt flag in the INTCON reg is ter.

• Save the con text. Which reg is ters and vari ables need to be saved de pends on thespe cific ap pli ca tion.

• Per form the in ter rupt ac tion.

• Re store the con text.

• Re turn from the in ter rupt with the retfie in struc tion.

Here again, the in ter rupt han dler may have to per form op er a tions that are spe -cific to the ap pli ca tion: for ex am ple, debounce a switch or ini tial ize lo cal vari ables.The fol low ing In ter rupt Ser vice rou tine is from the pro gram RB4to7Int in the book’son line soft ware:

;=======================================================; In ter rupt Ser vice Rou tine;=======================================================; Ser vice rou tine re ceives con trol when ever any of; port B lines 4 to 7 change stateIntServ:; First test: make sure source is an RB4-7 in ter rupt

btfss INTCON,rbif ; RBIF flag is in ter ruptgoto notRBIF ; Go if not RBIF or i gin

; Save con textmovwf old_w ; Save w reg is ter

168 Chap ter 10

Page 190: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

swapf STATUS,w ; STATUS to wmovwf old_sta tus ; Save STATUS

;=========================; in ter rupt ac tion;=========================; The in ter rupt oc curs when any of port B bits 4 to 7; have changed sta tus.

movf portb,w ; Read port B bitsmovwf temp ; Save read ingxorwf bitsB47,f ; Xor with old bits, re sult in f

; Test each mean ing ful bit (4 and 7 in this ex am ple)btfsc bitsB47,4 ; Test bit 4goto bit4Chng ; Rou tine for changed bit 4

; At this point bit 4 did not changebtfsc bitsB47,7 ; Test bit 7goto bit7Chng ; Rou tine for changed bit 7

; In valid port line change. Exitgoto pbRelease

;========================; bit 4 change rou tine ;========================; Check for sig nal fall ing edge, ig nore if notbit4Chng:

btfsc portb,4 ; Is bit 4 highgoto pbRelease ; Bit is high. Ig nore

; Tog gling bit 1 of port A turns LED on and offmovlw b’00000010’ ; Xoring with a 1-bit pro duces

; the com ple mentxorwf porta,f ; Com ple ment bit 1, port Agoto pbRelease

;========================; bit 7 change rou tine ;========================; Check for sig nal fall ing edge, ig nore if notbit7Chng:

btfsc portb,7 ; Is bit 7 highgoto exitISR ; Bit is high. Ig nore

; Tog gling bit 0 of port A turns LED on and offmovlw b’00000001’ ; Xoring with a 1-bit pro duces

; the com ple mentxorwf porta,f ; Com ple ment bit 1, port A

;pbRelease:

call de lay ; Debounce switchmovf portb,w ; Read port B into wandlw b’10010000’ ; Elim i nate un used bitsbtfsc STATUS,z ; Check for zerogoto pbRelease ; Wait

; At this point all port B pushbuttons are re leased;=========================; exit ISR;=========================exitISR:; Store new value of port B

movf temp,w ; This port B value to wmovwf bitsB47 ; Store

; Re store con textswapf old_sta tus,w ; Saved sta tus to wmovfw STATUS ; To STATUS reg is terswapf old_w,f ; Swap file reg is ter in it self

PIC In ter rupt Sys tem 169

Page 191: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

swapf old_w,w ; re-swap back to w; Re set,in ter ruptnotRBIF:

bcf INTCON,rbif ; Clear INTCON bit 0retfie

The pro cess ing by the In ter rupt Ser vice rou tine is straight for ward. The code firstde ter mines which line caused the in ter rupt and takes the cor re spond ing ac tion ineach case. In ei ther case, the han dler waits un til all pushbuttons have been re leasedbe fore re turn ing from the in ter rupt. This serves to debounce the switches.

10.5 Sam ple Pro gramsThree sam ple pro grams in this book’s soft ware pack age dem on strate the in ter ruptpro gram ming dis cussed in this chap ter. The pro grams can be ex e cuted in the In ter -rupts Demo Board la beled Demo Board I, shown in Fig ure 10-6.

Fig ure 10-6 A Demo Board for In ter rupts.

This book's on line pack age con tains sup port files and in struc tions for build ingthe demo board in Fig ure 10.6. The sam ple pro grams to dem on strate in ter rupt pro -gram ming are also found the in this pack age. Their func tion is as follows:

• The RB0Int pro gram tests the in ter rupt on port RB0. A pushbutton switch, con -nected to this port, tog gles an LED wired to port B, line 2. An other LED on port B,line 1, flashes on and off at one-half sec ond in ter vals.

170 Chap ter 10

Page 192: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

• The SleepDemo pro gram uses the Ex ter nal In ter rupt on port RB0 to ter mi nate thepower-down state caused by the SLEEP in struc tion. A pushbutton switch is con -nected to port RB0. This pushbutton gen er ates the in ter rupt that ends the SLEEPcon di tion. An LED on port B, line 1, flashes on and off at one-half sec ond in ter valsfor twenty it er a tions. At that time the pro gram en ters the SLEEP con di tion. Press -ing the pushbutton switch on line RB0 gnerates the in ter rupt that ends the SLEEP.

• The RB4to7Int pro gram tests the STATUS change in ter rupt. Pushbutton switchesare con nected to port B lines 4 and 7. A red LED is wired to port RA0 and a greenLED to port RA1. The pushbuttons gen er ate in ter rupts that tog gle the LEDs on andoff.

10.6 Demonstration Pro gramsThe fol low ing pro grams dem on strate the pro gram ming dis cussed in this chap ter.

10.6.1 RB0Int Pro gram; File: RB0Int.ASM; Date: April 2, 2011; Au thors: Sanchez and Canton; Pro ces sor: 16F84A;; De scrip tion:; Pro gram to test in ter rupt on port RB0; A pushbutton switch is con nected to port RB0.; The pushbutton tog gles an LED on port-B, line 2; An other LED on port-B, line 1, flashes on and off; at one-half sec ond in ter vals ;===========================; switches;===========================; Switches used in __config di rec tive:; _CP_ON Code pro tec tion ON/OFF ; * _CP_OFF ; * _PWRTE_ON Power-up timer ON/OFF; _PWRTE_OFF ; _WDT_ON Watchdog timer ON/OFF ; * _WDT_OFF ; _LP_OSC Low power crys tal oscillator; * _XT_OSC Ex ter nal par al lel res o na tor/crys tal oscillator ;; _HS_OSC High speed crys tal res o na tor (8 to 10 MHz); Res o na tor: Murate Erie CSA8.00MG = 8 MHz ; _RC_OSC Re sis tor/ca pac i tor oscillator (sim plest, 20% ;; er ror); |; |_____ * in di cates setup val ues

;=========================

PIC In ter rupt Sys tem 171

Page 193: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; setup and con fig u ra tion;=========================

pro ces sor 16f84Ain clude <p16f84A.inc>__config _XT_OSC & _WDT_OFF & _PWRTE_ON & _CP_OFF

;=====================================================; vari ables in PIC RAM;=====================================================; Lo cal vari ables

cblock 0x0d ; Start of blockJ ; coun ter JK ; coun ter Kcount1 ; Aux il iary coun tercount2 ; ISR coun terold_w ; Con text sav ing old_STATUS ;endc

;========================================================; m a i n p r o g r a m;========================================================

org 0 ; start at ad dress 0goto main

;;=============================; in ter rupt han dler;=============================

org 0x04goto IntServ

;=============================; main pro gram;=============================main:; Set up in ter rupt on fall ing edge; by clear ing OPTION reg is ter bit 6

movlw b’10111111’op tionmovlw b’11111111’ ; Set port a for in puttris PORTAmovlw b’00000001’ ; Port-B bit 0 is in puttris PORTB ; all oth ers are out putclrf PORTB ; All port-B to 0

; Ini tially turn on LEDbsf PORTB,0 ; Set line 0 bit

;============================; setup in ter rupts;============================; Clear ex ter nal in ter rupt flag (INTF = bit 1)

172 Chap ter 10

Page 194: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

bcf INTCON,INTF ; Clear flag; En able global in ter rupts (GIE = bit 7); En able RB0 in ter rupt (INTE = bit 4)

bsf INTCON,GIE ; En able global int (bit 7)bsf INTCON,INTE ; En able RB0 int (bit 4)

;============================; flash LED;============================; Pro gram flashes LED wired to Port-B, line 2lights:

movlw b’00000010’ ; Mask with bit 1 setxorwf PORTB,f ; Com ple ment bit 1 call long_de laycall long_de laycall long_de laygoto lights

;=======================================================; In ter rupt Ser vice Rou tine;=======================================================; Ser vice rou tine re ceives con trol when there is; ac tion on pushbutton switch wired to Port-B, line 0IntServ:; First test if source is an RB0 in ter rupt

btfss INTCON,INTF ; INTF flag is RB0 in ter ruptgoto notRB0 ; Go if not RB0 or i gin

; Save con textmovwf old_w ; Save w reg is terswapf STATUS,w ; STATUS to wmovwf old_STATUS ; Save STATUS

; Make sure that in ter rupt occurred on the fall ing edge; of the sig nal. If not, abort han dler

btfsc PORTB,0 ; Is bit set?goto exitISR ; Go if clear

;=========================; in ter rupt ac tion;=========================; Debounce switch; Logic:; Debounce al go rithm con sists of wait ing un til the; same level is re peated on a num ber of samplings of the; switch. At this point the RB0 line is clear as the; in ter rupt takes place on the fall ing edge. An ini tial; short de lay makes sure that spikes are ig nored.

movlw D’10’ ; Num ber of rep e ti tionsmovwf count2 ; To coun ter

wait:; Check to see that port-B bit 0 is still 0 ; If not, wait un til it changes

PIC In ter rupt Sys tem 173

Page 195: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

btfsc PORTB,0 ; Is bit set?goto exitISR ; Go if bit not 0

; At this point RB0 bit is cleardecfsz count2,f ; Count this it er a tiongoto wait ; Con tinue if not zero

; In ter rupt ac tion con sists of tog gling bit 2 of; port-B to turn LED on and off

movlw b’00000100’ ; Xoring with a 1-bit pro duces; the com ple ment

xorwf PORTB,f ; Com ple ment bit 2, port-B ;=========================; exit ISR;=========================exitISR:; Re store con text

swapf old_STATUS,w ; Saved STATUS to wmovfw STATUS ; To STATUS reg is terswapf old_w,f ; Swap file reg is ter in it selfswapf old_w,w ; re-swap back to w

; Re set,in ter ruptnotRB0:

bcf INTCON,INTF ; Clear INTCON bit 1retfie

;=======================; Pro ce dure to de lay; 10 ma chine cy cles;=======================de lay:

movlw D’4’ ; Re peat 12 ma chine cy clesmovwf count1 ; Store value in coun ter

re peatdecfsz count1,f ; Dec re ment coun tergoto re peat ; Con tinue if not 0re turn

;=============================; long de lay sub-routine; (for de bug ging);=============================long_de lay

movlw D’200’ ; w = 200 dec i malmovwf J ; J = w

jloop: movwf K ; K = wkloop: decfsz K,f ; K = K-1, skip next if zero

goto kloopdecfsz J,f ; J = J-1, skip next if zerogoto jloopre turnend

174 Chap ter 10

Page 196: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

10.6.2 SleepDemo Pro gram

; File: SleepDemo; Date: April 4, 2011; Au thor: Canton and Sanchez; Pro ces sor: 16F84A;; De scrip tion:; Pro gram to use the Ex ter nal In ter rupt on port RB0; to ter mi nate the power-down state caused by the ; SLEEP in struc tion. A pushbutton switch is con nected to; port RB0. The pushbutton gen er ates the in ter rupt that; ends the SLEEP con di tions.; Dem on stra tion:; An LED on port-B, line 1, flashes on and off at 1/2; sec ond in ter vals for 20 it er a tions. At that time the; pro gram en ters the SLEEP con di tion. Pressing the; pushbutton switch on line RB0 gen er ates the in ter rupt; that ends the SLEEP. ;===========================; switches;===========================; Switches used in __config di rec tive:; _CP_ON Code pro tec tion ON/OFF ; * _CP_OFF ; * _PWRTE_ON Power-up timer ON/OFF; _PWRTE_OFF ; _WDT_ON Watchdog timer ON/OFF ; * _WDT_OFF ; _LP_OSC Low power crys tal oscillator; * _XT_OSC Ex ter nal par al lel res o na tor/crys tal oscillator

; _HS_OSC High speed crys tal res o na tor (8 to 10 MHz); Res o na tor: Murate Erie CSA8.00MG = 8 MHz ; _RC_OSC Re sis tor/ca pac i tor oscillator (sim plest, 20%; er ror); |; |_____ * in di cates setup val ues

;=========================; setup and con fig u ra tion;=========================

pro ces sor 16f84Ain clude <p16f84A.inc>__config _XT_OSC & _WDT_OFF & _PWRTE_ON & _CP_OFF

;=====================================================

PIC In ter rupt Sys tem 175

Page 197: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; vari ables in PIC RAM;=====================================================; Lo cal vari ables

cblock 0x0d ; Start of blockJ ; coun ter JK ; coun ter Kcount1 ; Aux il iary coun tercount2 ; Sec ond aux il iary coun terold_w ; Con text sav ing old_STATUS ;endc

;========================================================; m a i n p r o g r a m;========================================================

org 0 ; start at ad dress 0goto main

;;=============================; in ter rupt han dler;=============================

org 0x04goto IntServ

;=============================; main pro gram;=============================main:; Set up in ter rupt on fall ing edge; by clear ing OPTION reg is ter bit 6

movlw b’10111111’op tionmovlw b’11111111’ ; Set port a for in puttris PORTAmovlw b’00000001’ ; Port-B bit 0 is in puttris PORTB ; all oth ers are out putclrf PORTB ; All port-B to 0

;============================; setup in ter rupts;============================; Clear ex ter nal in ter rupt flag (INTF = bit 1)

bcf INTCON,INTF ; Clear flag; En able global in ter rupts (GIE = bit 7); En able RB0 in ter rupt (INTE = bit 4)

bsf INTCON,GIE ; En able global int (bit 7)bsf INTCON,INTE ; En able RB0 int (bit 4)

;============================; flash LED 20 times;============================

176 Chap ter 10

Page 198: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

wakeUp:; Pro gram flashes LED wired to port-B, line 2; 20 times be fore en ter ing the sleep state

movlw D’20’ ; Num ber of it er a tionsmovwf count2 ; To coun ter

lights:movlw b’00000010’ ; Mask with bit 1 setxorwf PORTB,f ; Com ple ment bit 1 call long_de laycall long_de laycall long_de laydecfsz count2,f ; Dec re ment coun tergoto lights

; 20 it er a tions have taken placesleepnop ; Rec om mended! goto wakeUp ; Re sume ex e cu tion

;=======================================================; In ter rupt Ser vice Rou tine;=======================================================; The in ter rupt ser vice rou tine per forms no op er a tionIntServ:

bcf INTCON,INTF ; Clear flagretfie

;=============================; long de lay sub-routine;=============================long_de lay

movlw D’200’ ; w = 200 dec i malmovwf J ; J = w

jloop:movwf K ; K = w

kloop:decfsz K,f ; K = K-1, skip next if zerogoto kloopdecfsz J,f ; J = J-1, skip next if zerogoto jloopre turn

end

10.6.3 RB4to7Int Pro gram

; File: RB4to7Int.ASM; Date: May 26, 2011

PIC In ter rupt Sys tem 177

Page 199: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; Au thors: Sanchez and Canton; Pro ces sor: 16F84A;; De scrip tion:; Pro gram to test the port-B, bits 4 to 7, STATUS; change in ter rupt. Pushbutton switches are con nected; to port-B lines 4 and 7. A red LED is wired to port; RA1 and a green LED to port RA0. The pushbuttons; gen er ate in ter rupts that tog gle the LEDs on and off.;===========================; switches;===========================; Switches used in __config di rec tive:; _CP_ON Code pro tec tion ON/OFF ; * _CP_OFF ; * _PWRTE_ON Power-up timer ON/OFF; _PWRTE_OFF ; _WDT_ON Watchdog timer ON/OFF ; * _WDT_OFF ; _LP_OSC Low power crys tal oscillator; * _XT_OSC Ex ter nal par al lel res o na tor/crys tal oscillator; ; _HS_OSC High speed crys tal res o na tor (8 to 10 MHz); Res o na tor: Murate Erie CSA8.00MG = 8 MHz ; _RC_OSC Re sis tor/ca pac i tor oscillator (sim plest, 20%; er ror); |; |_____ * in di cates setup val ues

;=========================; setup and con fig u ra tion;=========================

pro ces sor 16f84Ain clude <p16f84A.inc>__config _XT_OSC & _WDT_OFF & _PWRTE_ON & _CP_OFF

;=====================================================; vari ables in PIC RAM;=====================================================; Lo cal vari ables

cblock 0x0d ; Start of blockJ ; coun ter JK ; coun ter Kcount1 ; Aux il iary coun tercount2 ; ISR coun terold_w ; Con text sav ing old_STATUS ; bitsB47 ; Stor age for pre vi ous value

; in port-B bits 4-7

178 Chap ter 10

Page 200: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

temp ; Tem po rary stor ageendc

;========================================================; m a i n p r o g r a m;========================================================

org 0 ; start at ad dress 0goto main

;;=============================; in ter rupt han dler;=============================

org 0x04goto IntServ

;=============================; main pro gram;=============================main:; Dis able port-B in ter nal pullups; In ter rupts on fall ing edge of pushbutton ac tion

movlw b’10111111’op tion

; Wiring:; 7 6 5 4 3 2 1 0 <= port-B; | |_______________ red pushbutton; |________________________ black pushbutton;; 7 6 5 4 3 2 1 0 <= Port-A; | |_____ red LED; |________ green LED;

movlw b’00000000’ ; Set Port-A for ouputtris PORTAmovlw b’11110000’ ; Port-B bit 0-3 are out put

; bits 4-7 are in puttris PORTB ; all oth ers are out putclrf PORTB ; All Port-B to 0movlw b’00000000’ ; Zero to wmovwf bitsB47 ; Store in lo cal vari able

; Ini tially turn on LEDsbsf PORTA,0 ; Set LEDs on line 0bsf PORTA,1 ; and on line 1

;============================; set up in ter rupts;============================; Clear ex ter nal in ter rupt flag (intf = bit 1)

bcf INTCON,RBIF ; Clear flag; En able global in ter rupts (GIE = bit 7)

PIC In ter rupt Sys tem 179

Page 201: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; En able RB0 in ter rupt (inte = bit 4) bsf INTCON,GIE ; En able global int (bit 7)bsf INTCON,RBIE ; En able RB0 int (bit 3)

;============================; flash LED;============================; Main pro gram does noth ing. All ac tion takes place in; In ter rupt Ser vice Rou tinelights:

nopgoto lights

;=======================================================; In ter rupt Ser vice Rou tine;=======================================================; Ser vice rou tine re ceives con trol when ever any of; port-B lines 4 to 7 change stateIntServ:; First test: make sure source is an RB4-7 in ter rupt

btfss INTCON,RBIF ; RBIF flag is in ter ruptgoto notRBIF ; Go if not RBIF or i gin

; Save con textmovwf old_w ; Save w reg is terswapf STATUS,w ; STATUS to wmovwf old_STATUS ; Save STATUS

;=========================; in ter rupt ac tion;=========================; The in ter rupt oc curs when any of Port-B bits 4 to 7; have changed STATUS.

movf PORTB,w ; Read Port-B bitsmovwf temp ; Save read ingxorwf bitsB47,f ; Xor with old bits,

; re sult in f; Test each mean ing ful bit (4 and 7 in this ex am ple)

btfsc bitsB47,4 ; Test bit 4goto bit4Chng ; Rou tine for changed bit 4

; At this point bit 4 did not changebtfsc bitsB47,7 ; Test bit 7goto bit7Chng ; Rou tine for changed bit 7

; In valid port line change. Exitgoto pbRelease

;========================; bit 4 change rou tine ;========================; Check for sig nal fall ing edge, ig nore if notbit4Chng:

btfsc PORTB,4 ; Is bit 4 highgoto pbRelease ; Bit is high. Ig nore

180 Chap ter 10

Page 202: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; Tog gling bit 1 of Port-A turns LED on and offmovlw b’00000010’ ; Xoring with a 1-bit pro duces

; the com ple mentxorwf PORTA,f ; Com ple ment bit 1, Port-Agoto pbRelease

;========================; bit 7 change rou tine ;========================; Check for sig nal fall ing edge, ig nore if notbit7Chng:

btfsc PORTB,7 ; Is bit 7 highgoto exitISR ; Bit is high. Ig nore

; Tog gling bit 0 of Port-A turns LED on and offmovlw b’00000001’ ; Xoring with a 1-bit pro duces

; the com ple mentxorwf PORTA,f ; Com ple ment bit 1, Port-A

;pbRelease:

call de lay ; Debounce switchmovf PORTB,w ; Read port-B into wandlw b’10010000’ ; Elim i nate un used bitsbtfsc STATUS,Z ; Check for zerogoto pbRelease ; Wait

; At this point all port-B pushbuttons are re leased;=========================; exit ISR;=========================exitISR:; Store new value of port-B

movf temp,w ; This port-B value to wmovwf bitsB47 ; Store

; Re store con textswapf old_STATUS,w ; Saved STATUS to wmovfw STATUS ; To STATUS reg is terswapf old_w,f ; Swap file reg is ter in it selfswapf old_w,w ; re-swap back to w

; Re set,in ter ruptnotRBIF:

bcf INTCON,RBIF ; Clear INTCON bit 0retfie

;=======================; Pro ce dure to de lay; 10 ma chine cy cles;=======================de lay:

movlw D’6’ ; Re peat 18 ma chine cy clesmovwf count1 ; Store value in coun ter

PIC In ter rupt Sys tem 181

Page 203: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

re peat:decfsz count1,f ; Dec re ment coun tergoto re peat ; Con tinue if not 0re turn

;=============================; long de lay sub-routine; (for de bug ging);=============================long_de lay

movlw D’200’ ; w = 200 dec i malmovwf J ; J = w

jloop:movwf K ; K = w

kloop:decfsz K,f ; K = K-1, skip next if zerogoto kloopdecfsz J,f ; J = J-1, skip next if zerogoto jloopre turn

end

182 Chap ter 10

Page 204: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Chap ter 11

Tim ers and Coun ters

11.1 Con trol ling the Time Lapse

The mid-range PICs con tain fa cil i ties and de vices for con trol ling and ma nip u lat ingtime lapses in a pro gram; these are usu ally in the form of tim ing and count ing op er a -tions. It is dif fi cult to find a PIC ap pli ca tion that does not re quire some form of count -ing or tim ing. In the pro grams pre vi ously de vel oped we have used a sim ple it er a tioncoun ter that pro duces a de lay by means of a loop that im ple ments a de lay by wast ing ase ries of ma chine cy cles. In this chap ter we ex pand the the ory and the use of de layloops, and ex plore the use of the built-in tim ing and count ing cir cuits on the 16F84.The ma te rial pre sented re lates to Chap ter 10 be cause tim ing and count ing op er a tionscan be set up to gen er ate in ter rupts. The in ter rupt-based sam ple pro grams de vel opedin this chap ter can be ex e cuted and tested in Demo Board I de scribed in Chap ter 10.

11.1.1 16F84 Timer0 Mod ule

The ba sic timer fa cil ity on the 16F84 PIC is known as the Timer0 mod ule, as thefree-run ning timer, as the timer/coun ter, or sim ply as TMR0. Timer0 is an in ter nal 8-bitreg is ter that in cre ments au to mat i cally with ev ery PIC in struc tion cy cle un til thecount over flows the timer ca pac ity, which takes place when the timer count goes from 0xff to 0x00. At that time the timer re starts the count.

The Timer0 mod ule is in fact a pe riph eral de vice that adds a spe cific func tion al ity to the microcontroller. Learn ing to pro gram the Timer0 mod ule serves as an in tro -duc tion to pro gram ming PIC pe riph eral de vices. There are few such de vices in the16F84 but other mid-range PICs (such as the 16F877 and the 16F684) con tain otherpe riph er als. These in clude sev eral tim ers, cap ture/com pare mod ules, var i ous se rialand par al lel in ter faces, USART and other com mu ni ca tions hardware, comparators,and converters.

The 16F84 Timer0 mod ule has the fol low ing char ac ter is tics:

183

Page 205: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

• A timer register that is read able and writeable by soft ware

• Can be powered by an ex ter nal or in ter nal clock

• Tim ing edge for ex ter nal clock can be se lected

• 8-bit soft ware pro gram ma ble prescaler

• In ter rupt ca pa bil ity

• Can be used as a timer or as a coun ter

Fig ure 11-1 is a sim pli fied block di a gram of the Timer0 hard ware.

Fig ure 11-1 Timer0 Block Di a gram.

11.1.2 Timer0 Op er a tionBlock di a grams, such as the one in Fig ure 11-1, pro vide valu able and com pact cir cuitin for ma tion. In this ex am ple the block di a gram, which is read left to right, shows thattimer op er a tion can be as signed to the in ter nal clock (OSC/4 in the di a gram) or to thePICs TOCKI pin that is shared with port RA4. Bit 5 of the OPTION reg is ter (la beledTOCS in the di a gram) per forms the se lec tion. If TOCS is set, then the timer is linked tothe RA4/TOCKI pin. In this mode the timer is used as a coun ter. If TOCS is re set, thenthe timer uses the PIC’s in struc tion cy cle clock sig nal. The shaded trap e zoids in the il -lus tra tion de pict multi plexer func tions, some times called mux (see Sec tion 5.5.1).Bits in side the multi plexer sym bol show which in put is se lected by the TOCS bit.

If an ex ter nal source is se lected by set ting the TOCS bit, then bit 4 of the OPTION reg is ter (la beled TOSE) al lows se lect ing whether the timer in cre ments on thehigh-to-low or low-to-high tran si tion of the sig nal on the RA4/TOCKI pin. The XORsym bol with in puts from the TOCKI pin and bit 4 of the OPTION reg is ter in di catethis ac tion. If the TOSE bit is set, then in cre ment takes place on the high-to-lowtran si tion of the TOCKI pin, as it cor re sponds with the log i cal XOR op er a tion. Oth -

184 Chap ter 11

OPTION7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0

7 6 5 4 3 2 1 0

TOSE (Source edge select)TOCS(Clock source select)

PS2-PS0 (Prescaler)

PSA (Prescaler assignment)

TOCKI

INTCON

TOIE

TOIF (TMR0 interrupt)

GIE

TMR0

data bus

OSC/4

Page 206: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

er wise the in cre ment takes place on the low-to-high tran si tion of the TOCKI pin.The gray shad ing of bits 6 and 7 of the OPTION reg is ter (and of other reg is ter bits inthe di a gram) in di cate that these bits are not used in configuring Timer0 operations.

The rightmost multi plexer sym bol de picts the con trol of the prescaler func tion.The prescaler serves as a fre quency di vider for the sig nal and al lows slow ing downthe clock ac tion on Timer0. As shown in Fig ure 11-1, the con trol bit for the prescaler func tion is bit 3 of the OPTION reg is ter, la beled PSA. If this bit is clear, the prescaler is as signed to the Timer0 mod ule. If the PSA bit is set, then the prescaler is as signedto the Watch dog timer. Bits 0, 1, and 2 of the OPTION reg is ter de fine eight pos si bleprescaler settings.

The Timer0 mod ule can be vi su al ized as a reg is ter that in cre ments with ev ery in -struc tion cy cle at one-fourth the clock rate, that is, as a timer. In a PIC equippedwith a 4-Mhz os cil la tor, the timer reg is ter in cre ments at a rate of one pulse per mil li -sec ond with out the prescaler. Be cause there are eight bits in the coun ter reg is ter,the value stored is in the range 0 to 255 dec i mal (shown as TMR0 in the block di a -gram of Fig ure 11-1). When the coun ter over flows, the reg is ter is re set. Theprescaler al lows slow ing down this rate. The var i ous set tings of the prescaler bits of the OPTION reg is ter (bits 0, 1, and 2) al low se lect ing one of eight pos si ble ratedivisors (2, 4, 8, 16, 32, 64, 128, or 256)

Timer0 In ter rupt

PIC ap pli ca tions some times read the timer reg is ter (TMR0) di rectly. Al ter na tively,Timer0 can be set up to gen er ate an in ter rupt at ev ery tran si tion from 0xff to 0x00, thatis, ev ery time the coun ter over flows. The timer reg is ter can be ac cessed in bank 0, off -set 0x01. The timer in ter rupt is en abled by set ting bit 5 (la beled TOIE) of the INTCONreg is ter. In this case the Global In ter rupt En able bit (la beled GIE) of the INTCON reg -is ter must also be set. Once the timer in ter rupt is en abled, the Timer In ter rupt Flag,as signed to bit 2 of the INTCON register (la beled TOIF) will be set on ev ery over flowof the timer reg is ter. At that time an in ter rupt will take place. The TOIF bit (also calledthe Timer0 flag) must be cleared by the in ter rupt han dler so that the timer in ter ruptcan take place again. Later in this chap ter we de velop a sam ple pro gram that usesTimer0 as an in ter rupt source.

Timer0 Prescaler

We have seen that the coun ter prescaler con sists of the three low-or der bits in theOPTION register. These bits al low se lect ing eight pos si ble val ues that serve as a di vi -sor for the coun ter rate. When the prescaler is dis abled, the coun ter rate is one- fourththe pro ces sor’s clock speed. If the prescaler is set to the max i mum value (255) thenone of 255 clock sig nals ac tu ally reach the timer. Ta ble 11.1 shows the prescaler set -tings and their ac tion on the rate of the Timer0 mod ule.

Note that the prescaler can be as signed to ei ther Timer0 or the Watch dog timer,but not to both. If bit 3 of the OPTION reg is ter is set, then the prescaler is as signedto the Watch dog timer. If it is clear it, is as signed to the Timer0 mod ule.

Tim ers and Coun ters 185

Page 207: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Ta ble 11.1

Prescaled Bits Se lected Rates

BIT VALUEBINARY HEX TMR0 RATE

000 0x00 1:2001 0x01 1:4010 0x02 1:8011 0x03 1:16100 0x04 1:32101 0x05 1:64110 0x06 1:128111 0x07 1:256

11.2 De lays Us ing Timer0The sim plest ap pli ca tion of the Timer0 mod ule is to count in struc tion cy cles in a sim -ple de lay loop. Ap pli ca tions in which the Timer0 reg is ter is polled di rectly are said touse a free run ning timer. There are two ad van tage in free run ning tim ers over con ven -tional de lay loops: the prescaler pro vides a way of slow ing down the count, and the de -lay is in de pend ent of the num ber of ma chine cy cles in the loop body. In most cases this means that it is eas ier to im ple ment an ac cu rate time de lay us ing the Timer0 mod ulethan by count ing in struc tion cy cles. The draw back is that Timer0 must first be set upfor this mode of op er a tion.

Cal cu lat ing the time taken by each coun ter it er a tion re quires that we first di vide the clock speed by four to ob tain the in struc tion speed. We know that a PIC run ningon a 4-MHz oscillator clock in cre ments the coun ter ev ery 1 MHz. If the prescaler isnot used, the coun ter reg is ter is in cre mented at a rate of 1 µs, which is the same assay ing that the Timer0 clock beats at a rate of 1,000,000 cy cles per sec ond. If theprescaler is set to the max i mum di vi sor value (256), then each in cre ment of thetimer takes place at a rate of 1,000,000/256 µs, which is ap prox i mately 3,906 µs or3.906 ms. Be cause this is the slow est pos si ble rate of the timer in a ma chine run ningat 4 MHz, it is of ten nec es sary to em ploy sup ple men tary coun ters in or der toachieve lon ger de lays.

The fact that the timer reg is ter (TMR0) is both read able and writeable makes pos -si ble some in ter est ing tim ing tech niques. For ex am ple, an ap pli ca tion can set thetimer reg is ter to an ini tial value and then count up un til the timer over flows or aprede ter mined limit is reached. If the dif fer ence be tween the limit and the ini tialvalue is, let's say, 100, then the rou tine will count 100 times the timer rate per beatinstead of 256.

Two sim ple el e ments can be used in de sign ing a tim ing rou tine with a spe cific de -lay: the num ber of timer it er a tions counted by the Timer0 hard ware and theprescaler as sign ment. Sup pose there is a rou tine that al lows Timer0 to start fromzero and count up. In this case when the count reaches the max i mum value (0xff),the rou tine would have in tro duced a de lay of 256 times the Timer0 clock rate. In this case a prescaler as sign ment can be used to fur ther re duce the num ber of clock

186 Chap ter 11

Page 208: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

beats read by the timer. If we se lect the max i mum value for the prescaler (as sum inga ma chine clock of 4 MHz) then each timer beat will take place at a rate of1,000,000/256, or ap prox i mately 3,906 timer beats per sec ond. Be cause in thisexample the rou tine reads the max i mum num ber of it er a tions in the coun ter reg is -ter (256), the de lay can be cal cu lated by di vid ing the num ber of beats per sec ond(3,906) by the num ber of counts in the de lay loop. In this case 3,906/256 re sults in ade lay of ap prox i mately 15.26 it er a tions per sec ond.

A gen eral for mula for cal cu lat ing the num ber of timer beats per sec ond is as fol -lows:

where T is the num ber of clock beats per sec ond, C is the sys tem clock speed in Hz, P is the value stored in the prescaler, and R is the num ber of it er a tion counted in the TMR0reg is ter. The range of both P and R in this for mula is from 1 to 256. Also no tice that there cip ro cal of T (1/T) gives the time de lay, in sec onds, per it er a tion of the de lay rou tine.

11.2.1 Long De lay Loops

In the pre vi ous sec tion we saw that even us ing the larg est pos si ble prescaler andcount ing the max i mum num ber of timer beats, the lon gest pos si ble timer de lay in a 4-MHz sys tem is ap prox i mately of 1/15 of a sec ond. Add to this that ap pli ca tions mustsome times de vote the prescaler to the Watch dog timer, which im pedes its use inTimer0. With out the prescaler the max i mum de lay is ap prox i mately 3,906 timer beatsper sec ond. Con se quently, ap pli ca tions that must mea sure time in sec onds (or in min -utes, hours, or days) must find ways of keep ing count of large num ber of rep e ti tions of the timer beat.

In im ple ment ing coun ters for larger de lays we must be care ful not to in tro duceround-off er rors. For in stance, in the pre vi ous ex am ple, a timer cy cles at the rate of15.26 times per sec ond. The clos est in te ger to 15.25 is 15, so if we now set up aone-sec ond coun ter by count ing fif teen it er a tions, we would in tro duce an er ror ofap prox i mately 2%. Con sid er ing that (in the pre vi ous ex am ple) each it er a tion of thetimer con tains 256 in di vid ual beats, there are 3,906.25 in di vid ual timer beats persec ond at the max i mum prescaled rate. If we were to im ple ment a timer by keep ingtrack of the in di vid ual prescaled beats (in stead of timer it er a tions), the count would pro ceed from 0 to 3,906 in stead of from 0 to 15. Ap prox i mat ing 3,906.25 by the clos -est in te ger, 3,906, in tro duces a much smaller round-off error than what results fromapproximating 15.26 with 15.

Fi nally, in this same ex am ple, we could elim i nate the prescaler so that the timerbeats at the clock rate, that is, at 1,000,000 beats per sec ond. In this op tion a coun -ter that counts from 0 to 1,000,000 would have no in trin sic er ror due to round-off.

Which so lu tion is more ad e quate de pends on the ac cu racy re quired by the ap pli -ca tion and the re sult ing com plex ity of the code. A timer coun ter in the range 0 to 15can be im ple mented in a sin gle 8-bit reg is ter. A coun ter in the range 0 to 3,906 re -

Tim ers and Coun ters 187

TCPR

=4

Page 209: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

quires two bytes. One to count from 0 to 1,000,000 re quires three bytes. Be causearith me tic op er a tions in the 16F84 are 8-bits, ma nip u lat ing mul ti ple-reg is ter coun -ters re quires more complicated processing.

How Ac cu rate Is the De lay?

The ac tual im ple men ta tion of a de lay rou tine based on multi-byte coun ters pres entssome dif fi cul ties. If the timer reg is ter (TMR0) is used to keep track of timer beats, then de tect ing the end of the count pres ents a sub tle prob lem. In tu itively think ing, our pro -gram could de tect timer over flow by read ing the value in TMR0 and test ing the zeroflag in the sta tus reg is ter. Be cause the movf in struc tion af fects the zero flag, onecould be tempted to code:

wait:

movf tmr0,w ; Timer value into w

btfss sta tus,z ; Was it zero?

goto wait

; If this point is reached tmr0 has over flowed

But there is a prob lem: the timer ticks as each in struc tion ex e cutes. Be cause thegoto in struc tion takes two ma chine cy cles, it is pos si ble that the timer over flowswhile the goto in struc tion is in prog ress; there fore the over flow con di tion wouldnot be de tected. A so lu tion to this prob lem pro posed in the Micro chip doc u men ta -tion is to check for less than a nom i nal value by test ing the carry flag, as fol lows:

wait1:

movlw 0x03 ; 3 to w

subwf tmr0,w ; Sub tract w – tmr0

btfsc sta tus,c ; Test carry

goto wait1

One ad just ment that is some times nec es sary in free run ning tim ers re sults fromthe fact that when the TMR0 reg is ter is writ ten, the count is in hib ited for the fol low -ing two in struc tion cy cles. Soft ware can usu ally com pen sate for this by writ ing anad justed value to the timer reg is ter. If the prescaler is as signed to Timer0, then awrite op er a tion to the timer reg is ter de ter mines that the timer will not incrementfor four clock cycles.

A more el e gant and ac cu rate so lu tion has been de scribed by Ro man Black in aWeb ar ti cle ti tled “Zero-er ror One Sec ond Timer”. Black cred its Bob Ammermanwith the sug ges tion of us ing Bresenham’s al go rithm for cre at ing ac cu rate PIC timer pe ri ods. In the Black-Ammerman method the coun ter works in the back ground, ei -ther by poll ing or In ter rupt-Driven. So the pro gram can con tinue ex e cut ing whilethe coun ter runs. In ei ther case the timer count value is stored in a 3-byte reg is terthat is dec re ment ed by the soft ware. The Internet ar ti cle of fers through cov er age ofthis al go rithm.

11.3 Timer0 as a Coun terTimer0 op er a tions can be as signed to the PIC RA4/TOCKI pin by set ting bit 5 of theOPTION reg is ter (la beled TOCS). This mode is re ferred to as the coun ter mode. Whenthe timer is setup to work as a coun ter, then bit 4 of the OPTION reg is ter (la beled

188 Chap ter 11

Page 210: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

TOSE) al lows se lect ing whether the coun ter in cre ments on the high-to-low orlow-to-high tran si tion of the sig nal.

When an ex ter nal clock in put is pres ent in the RA4/TOCKI pin, the code mustmeet cer tain re quire ments in or der to en sure that the ex ter nal source can be syn -chro nized with the in ter nal clock. When no prescaler is used, the ex ter nal clock in -put must be high and low for at least twice the in ter nal clock rate. In ad di tion, theremust be a re sis tor-ca pac i tor in duced de lay of 20 ns on both the high and low cy cles.When a prescaler is used, the ex ter nal clock in put must be high and low for at leastfour times the rate of the in ter nal clock rate. In ad di tion, there must be a re sis tor-ca -pac i tor in duced de lay of 40 ns on both the high and low cycles.

Once the coun ter mode is en abled, any pulse on pin RA4/TOCKI is au to mat i callycounted in the TMR0 reg is ter. The mech a nism can be com pared to an au to matic in -ter rupt be cause no pro gram ac tion is re quired to keep track of the num ber ofpulses. The rou tine can be coded so that when the timer count over flows an in ter -rupt is gen er ated. The in ter rupt han dler can then in cre ment a sup ple men tary coun -ter so that events that ex ceed 256 pulses can be re corded.

The pro gram named TMR0Counter de vel oped later in this chap ter and con tainedin this book’s on line soft ware is an ex am ple of us ing the coun ter func tion of theTimer0 module.

11.4 Timer0 Pro gram mingSoft ware rou tines that use the Timer0 mod ule range in com plex ity from sim ple de layloops to configurable, In ter rupt-Driven coun ters that must meet high tim ing ac cu racyre quire ments. When the time pe riod to be mea sured does not ex ceed the one that canbe ob tained with the prescaler and the timer reg is ter count, then the cod ing is straight -for ward and the pro cess ing is un com pli cated. But of ten this is not the case. The fol -low ing el e ments should be ex am ined be fore at tempt ing to de sign and code aTimer0-based rou tine:

1. What is the re quired ac cu racy of the timer de lay?

2. Can the prescaler be used, or is the prescaler de voted to the Watch dog timer?

3. Does the pro gram sus pend ex e cu tion while the de lay is in prog ress, or does the ap -pli ca tion con tinue ex e cut ing in the fore ground?

4. Can the timer be In ter rupt-Driven, or must it be polled?

5. Will the de lay be the same on all calls to the timer rou tine, or must the rou tine pro -vide de lays of dif fer ent mag ni tudes?

6. How long must the de lay last?

In this sec tion we ex plore sev eral timer rou tines of dif fer ent com plex ity andmeet ing var i ous con straints. The first one uses the Timer0 mod ule as a coun ter, asde scribed in Sec tion 11.3. Later we de velop a sim ple de lay loop that uses the Timer0 reg is ter in stead of an in struc tion count. We con clude with an In ter rupt-Driven timer rou tine that can be changed to im ple ment different delays.

Tim ers and Coun ters 189

Page 211: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

11.4.1 Pro gram ming a Coun ter The 16F84 can be pro grammed so that port RA4/TOCKI is used to count events orpulses. This is ac com plished by initializing the Timer0 mod ule as a coun ter. If in ter -rupts are not used, the pro cess re quires the fol low ing pre pa ra tory steps:

1. Port A, line 4, (RA4/TOCKI) is de fined for in put.

2. The Timer0 reg is ter (TMR0) is cleared.

3. The Watch dog timer in ter nal reg is ter is cleared by means of the CLRWDT in struc -tion.

4. The OPTION register bits PSA and PSO:PS2 are in i tial ized if the prescaler is to beused.

5. The OPTION register bit TOSE is set so as to in cre ment the count on thehigh-to-low tran si tion of the port pin if the port source is ac tive low. Oth er wise thebit is cleared.

6. The OPTION register bit TOCS is set to se lect ac tion on the RA4/TOCKI pin.

Once the timer is set up as a coun ter, any pulse re ceived on the RA4/TOCKI pin(as long as it meets the re stric tions men tioned in Sec tion 11.3) is counted in theTMR0 reg is ter. Soft ware can read and write to the TMR0 reg is ter, lo cated at ad dress0x01 in bank 0, in or der to ob tain or change the event count. If the timer in ter rupt isen abled when the timer is de fined as a coun ter, the in ter rupt takes place ev ery timethe coun ter over flows, that is, when the count cy cles from 0xff to 0x00.

Timer/Coun ter Test Cir cuit

The cir cuit shown in Fig ure 11-2 con tains a pushbutton switch wired to portRA4/TOCKI and a Seven-Seg ment LED dis play wired to port B lines 0 to 6.

Fig ure 11-2 Test Cir cuit for Timer/Coun ter Pro gram.

190 Chap ter 11

16F84

Osc

a

PWRON

b

cd

e e

f

f

g

g

d

c

b

a

+5v

+5v

+5v

R=

10

K

R=

10

K

RA2

RA3

RA4/TOCKI

MCLR

Vss

RB0/INT

RB1

RB2

RB3

1

2

3

4

5

6

7

8

9

18

17

16

15

14

13

12

11

10

RA1

RA0

OSC1

OSC2

Vdd

RB7

RB6

RB5

RB4

220 RX 7

PB SW

7-segmentLED

Page 212: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Note that the cir cuit in Fig ure 11-2 is a sec tion of the one used by Vir tual Board A (in Fig ure 9.7). Pro grams that ex e cute in the cir cuit of Fig ure 11-2 will also run inVir tual Board A.

TimerCounter Pro gram

The pro gram named TimerCounter in this book’s on line soft ware pack age uses the cir -cuit in Fig ure 11-2 (and in Vir tual Board A) to dem on strate the pro gram ming of theTimer0 mod ule in the coun ter mode. The pro gram de tects and counts ac tion on thepushbutton switch wired to port RA4/TOCKI. The count (in hex dig its in the range0x00 to 0x0f) is dis played in the Seven-Seg ment LED con nected to port B. When us ingVir tual Board A to dem on strate the pro gram, make sure that tog gle switch J1 is closedat the time the pro gram ex e cutes. The pro gram ming of Seven-Seg ment LEDs was dis -cussed in Chap ter 9.

Code De tails

Code first clears the TMR0 reg is ter and the Watch dog timer, as fol lows:

main:; Clear the timer and the Watchdog

clrf TMR0clrwdt

Next, the OPTION reg is ter must be set up as fol lows:

• Dis able the prescaler (ac com plished by set ting the PSA bit that as signs it to theWatch dog timer).

• Set the Timer0 edge se lect bit (TOSE) to in cre ment in the high-to-low sig nal tran si -tion.

• Se lect the RA4/TOCKI pin as a beat source.

The bits of the OPTION reg is ter that are not mean ing ful for this mode of Timer0op er a tion are set to their de fault state, as fol lows:

; Set up the OPTION reg is ter. First move value into wmovlw b’10111000’

; Note that OPTION reg is ter is in bank 1 and its reg is ter; name is OPTION_REG

bsf STATUS,RP0 ; RP0 is bank se lect bitmovwf OPTION_REG ; Copy w to OPTIONbcf STATUS,RP0 ; Bank 0

Now port B must be “trissed” for out put and port A for in put. Port B is alsocleared:

; Setup ports

movlw 0x00 ; Set port B to out puttris PORTBclrf PORTB ; All port B to 0

; Port A. Five low-or der lines set for in putmovlw B’00011111’ ; w = 00011111 bi narytris PORTA ; port A (lines 0 to 4) to in put

Tim ers and Coun ters 191

Page 213: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

At this point, ev ery time the pushbutton switch wired to port A, line RA4/TOCKI,is pressed, one is added to the value in TMR0. Be cause the value to be dis played inthe Seven-Seg ment LED goes from 0 to 0xf, the value in TMR0 must be scaled to this range. This is eas ily ac com plished by mask ing off the four high-or der bits of TMR0at dis play time. Note that a bi nary coun ter is rem i nis cent of the odom e ter in an au -to mo bile, that is, the count pro ceeds from the lower dig its to the higher ones. There -fore mask ing off a se ries of higher-or der dig its does not af fect the count kept in thelower-or der dig its. More clearly, if you were to place a piece of tape over the threehigh-or der dig its of a car’s odom e ter, the value in the un cov ered dig its would con -tinue to be cor rect. Code reads the value in TMR0 into w, masks off the four high-or -der bits, dis plays the re sult ing value, and loops back end lessly, as fol lows:

checkTmr0:movf TMR0,w ; Timer reg is ter to w

; Elim i nate four high or der bitsandlw b’00001111’ ; Mask off high bits

; At this point the w reg is ter con tains a 4-bit value; in the range 0 to 0xf. Use this value (in w) to ; ob tain Seven-Segment dis play code

call seg mentmovwf PORTB ; Dis play switch bitsgoto checkTmr0 ; End less loop

11.4.2 Timer0 as a De lay Timer An other sim ple use of the Timer0 mod ule is to im ple ment a de lay loop. In this ap pli ca -tion the Timer0 mod ule is in i tial ized to use the in ter nal clock by set ting the TOSE bit of the OPTION reg is ter. If the prescaler is to be used, as is of ten the case, the PSA bit iscleared and the de sired pre-scal ing is en tered in bits PS2 to PS0 of the OPTION reg is -ter.

De lay Timer Cir cuit

The cir cuit in Fig ure 11-3 al lows test ing sev eral timer-re lated pro grams de vel oped inthis chap ter. No tice that this cir cuit is a sec tion of the one for Vir tual Board A in Fig ure9.7; there fore ap pli ca tions de vel oped for this cir cuit will also run in the Vir tual BoardA pro gram.

Fig ure 11-3 Cir cuit for Test ing Sev eral Timer Pro grams.

192 Chap ter 11

16F84

R=10K

R=330x4 Ohm R=330x4 Ohm

RA2

RA3

RA4/TOCKI

MCLR

Vss

RB0/INT

RB1

RB2

RB3

1

2

3

4

5

6

7

8

9

RA1

RA0

OSC1

OSC2

Vdd

RB7

RB6

RB5

RB4

Osc

+5v

+5v

Page 214: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

11.4.3 DelayTimer Pro gramThe pro gram named DelayTimer, in this book’s on line soft ware pack age, uses atimer-based de lay loop to flash eight LEDs dis play ing a bi nary value from 0x00 to 0xff.The de lay rou tine ex e cutes in the fore ground, so that pro cess ing is sus pended whilethe count is in prog ress.

Code De tails

Code first clears the Watch dog timer:

; Clear the Watchdog timer and re set prescalerclrwdt

The prescaler is as signed to Timer0 by clear ing the PSA bit, and bits PS2 to PS0are set to as sign a 1:256 prescaler to the timer. The bits of the OPTION reg is ter thatare not mean ing ful for this mode of Timer0 op er a tion are set to their de fault state.Code is as follows:

; Set up the OPTION reg is termovlw b’11010111’

; 7 6 5 4 3 2 1 0 <= OPTION bits; | | | | | |__|__|_____ PS2-PS0 (prescaler bits); | | | | | Val ues for Timer0; | | | | | 000 = 1:2 001 = 1:4; | | | | | 010 = 1:8 011 = 1:16; | | | | | 100 = 1:32 101 = 1:64; | | | | | 110 = 1:128 *111 = 1:256; | | | | |______________ PSA (prescaler as sign); | | | | 1 = to WDT; | | | | *0 = to Timer0; | | | |_________________ TOSE (Timer0 edge se lect); | | | 0 = in cre ment on low-to-high; | | | *1 = in cre ment on high-to-low; | | |____________________ TOCS (TMR0 clock source); | | *0 = in ter nal clock; | | 1 = RA4/TOCKI bit source; | |_______________________ INTEDG (Edge se lect); | *0 = fall ing edge; |__________________________ RBPU (Pullup en able); 0 = en abled; *1 = disabled; Note that OPTION reg is ter is in bank 1 and its reg is ter; name is OPTION_REG

bsf STATUS,RP0 ; RP0 is bank se lect bitmovwf OPTION_REG ; Copy w to OPTIONbcf STATUS,RP0 ; Bank 0

Port B is then “trissed” for out put and cleared. Be cause the pro gram does not useport A, it is ig nored by the code.

; Setup portsmovlw 0x00 ; Set port B to out puttris portbclrf portb ; All port B to 0

The pro gram’s main loop con sists of add ing one to the value in port B so as tobump the count. The de lay rou tine named TM0delay is then called, fol lowed by agoto in struc tion to the loop start.

Tim ers and Coun ters 193

Page 215: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

mloop:incf portb,f ; Add 1 to reg is ter valuecall TM0delaygoto mloop

The de lay pro ce dure named TM0delay pro vides the nec es sary time lapse be tween suc ces sive in cre ments in the count dis played. First the TMR0 reg is ter is cleared tomake sure the tim ing starts cor rectly. Then the value in TMR0 is read into the wregister and the con stant 0xff is sub tracted from W. When the count reaches 0xff,this sub trac tion sets the zero flag. Un til that hap pens, code loops to a la bel namedcy cle. The rou tine re turns to the caller when the time lapses.

TM0delay:; Ini tial ize the timer reg is ter

clrf tmr0 ; Clear SFR for Timer0; Rou tine tests the value in the tmr0 reg is ter by; sub tract ing 0xff from the value in tmr0. The zero flag; is set if tmr0 = 0xffcy cle:

movf tmr0,w ; Timer to w; w has tmr0 reg is ter value

sublw 0xff ; Sub tract max value; Zero flag is set if value in tmr0 = 0xff

btfss sta tus,z ; Test for zerogoto cy cle ; Re peatre turn

11.4.4 Vari able Time LapseA time-lapse rou tine can be de signed so it can be mod i fied (or re con fig ured at calltime) to pro duce a spe cific de lay. This ad just able time-lapse pro ce dure can be a use ful tool in any pro gram mer’s li brary. In pre vi ous sec tions we have de vel oped de lay rou -tines that do so by count ing timer pulses. This same idea can be used to de velop rou -tines that can be ad justed so as to pro duce ac cu rate de lays within a range bymod i fy ing the value of the count.

The rou tine it self can be im ple mented to vary ing de grees of so phis ti ca tion. Onevari a tion is a pro ce dure that re ceives the de sired time lapse as a pa ram e ter. An other one is a pro ce dure that reads the de sired time lapse from pro gram con stants, whichcan be ed ited at as sem bly time. A third op tion, used by the pro gram VariLapse inthis book’s soft ware pack age, uses three vari ables to hold the num ber of ma chinecy cles in the de sired wait pe riod. By us ing ma chine cy cles in stead of time units(such as mi cro sec onds or mil li sec onds), the pro ce dure be comes adapt able to de -vices run ning at dif fer ent clock speeds. Be cause each in struc tion (or Timer0 it er a -tion) re quires four clock cy cles, the de vice’s clock speed in Hz is di vided by four inorder to determine the number of machine cycles per time unit.

For ex am ple, a pro ces sor equipped with an 8-MHz clock ex e cutes at a rate of8,000,000/4 ma chine cy cles per sec ond, that is, 2,000,000 in struc tion cy cles per sec -ond. To pro duce a one-quar ter sec ond de lay re quires a wait pe riod of 2,000,000/4 or500,000 in struc tion cy cles. By the same to ken, a 16F84 run ning at 4 MHz ex e cutes1,000,000 in struc tions per sec ond. In this case, a one-quar ter sec ond de lay would re -quire wait ing 250,000 instruction cycles.

194 Chap ter 11

Page 216: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

11.4.5 Vari able Lapse Timer Pro gramThe pro gram ti tled VariLapse in this book’s soft ware pack age uses Timer0 to pro ducea vari able-lapse de lay. The de lay is cal cu lated based on the num ber of ma chine cy cles nec es sary for the de sired wait pe riod, as de scribed in the pre ced ing para graph. Thepro gram uses the Black-Ammerman meth ods de scribed ear lier in this chap ter, whichre quire a prescaler of 1:2 so that each timer it er a tion takes place at one-half the clockrate.

Code De tails

The pro gram first initializes the OPTION register in or der to achieve the fol low ingsetup:

• The prescaler is as signed to Timer0 (PSA bit) and a 1:2 rate is se lected inOPTION_REG bits 0 to 2.

• The in ter nal clock is se lected as a tim ing source (TOCS bit).

• Tim ing count is set to in cre ment in the high-to-low sig nal tran si tion (TOSE bit).

• OPTION register bits not used by the pro gram are set to their de fault val ues.

• Next, port B is se lected for out put and cleared. Port A is ig nored by the code be -cause it is not used by the pro gram.

The VariLapse pro gram re quires a one-half sec ond de lay and as sumes a 16F84run ning at 4 MHz. The de lay pro ce dure must wait for 500,000 clock beats to takeplace be fore re turn ing to the caller. The value 500,000 re quires three stor age bytes.This is eas ily seen by con vert ing 500,000 to hex a dec i mal: 500,000 = 0x07a120. Atthis point a sim ple dec i mal-to-hex cal cu la tor would be con ve nient. Sev eralscreen-based hex cal cu la tors (in clud ing a screen ver sion of the HP 16C) are avail -able free on the Internet. The pro gram de fines the hex equiv a lent of 500,000 in three constants:

; Con stants for a 1/2 sec ond de lay on a 4 MHz ma chine; 500,000 dec i mal = 0x07a1x20;; 0x07 0xa1 0x20; ---- ---- ----; | | |___ low_byte; | |________ mid_byte; |_____________ high_byte;low_byte equ 0x20mid_byte equ 0xa1high_byte equ 0x07

The ad van tage of us ing equ di rec tives in de fin ing these val ues is that they caneas ily be ed ited in or der to ac com mo date a dif fer ent pro ces sor speed or to changethe de lay. In the sam ple pro gram we coded a pro ce dure called setDelay, whichinitializes three coun ter vari ables us ing the val ues con tained in the con stantslow_byte, mid_byte, and high_byte. The setDelay pro ce dure is coded as fol lows:

; Pro ce dure to ini tial ize lo cal vari ables for a de lay de fined; in pro gram con stants. For a one-half sec ond on a 16F84 at; 4 MHz ini tial iza tion val ues are as fol lows:;

Tim ers and Coun ters 195

Page 217: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; 500,000 = 0x07 0xa1 0x20; ---- ---- ----; | | |___ low_byte; | |________ mid_byte; |_____________ high_bytesetDelay:

movlw high_bytemovwf countHmovlw mid_bytemovwf countMmovlw low_bytemovwf countLre turn

The logic for a 3-byte coun ter con sists of dec re ment ing the low-or der coun ter un -til it ex pires, then the mid-or der coun ter, and when it goes to zero the high-or dercoun ter is dec re ment ed. If the high-or der coun ter ex pires, the de lay con cludes. Theflowchart in Fig ure 11-4 shows this se quence of operations.

Fig ure 11-4 Mul ti ple Coun ter Flowchart.

196 Chap ter 11

START

END

YES

YES

YES

NO

NO

NO

DECREMENT LOW COUNT

LOW COUNT = XX

MID COUNT = YY

DECREMENT MID COUNT

DECREMENT HIGH COUNT

LOW COUNT= 0?

MID COUNT= 0?

HIGH COUNT= 0?

INIT COUNTERS:LOW COUNT = XXMID COUNT = YYHIGH COUNT = ZZ

Page 218: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Ro man Black points out in his Web ar ti cle (men tioned ear lier in this chap ter) that one of the dif fi cul ties of tim ing rou tines based on coun ters is that the ex act count islost by the ma nip u la tions nec es sary to de tect the end of each coun ter it er a tion. Onepos si ble so lu tion is to use in ter rupts to de tect the end of the count. An other one(pro posed by Black) is based on in tro duc ing a 1:2 de lay in the timer by means of theprescaler. Be cause the prescaled timer beats at one-half the in struc tion rate, 128timer cy cles will be re quired for one com plete it er a tion at the full in struc tion rate.This al lows us to test the state of the coun ter’s high-or der bit to de tect when thecount has ex pired. A new count can be started by clear ing this high-or der bit with -out af fect ing the va lid ity of the count held in the re main ing seven bits. The re sult isa timer-coun ter that does not lose step while detecting the end of each iterationlevel.

The de lay rou tine uses the Timer0 reg is ter to pro vide the low-or der level of thecount. Be cause the coun ter counts up from zero, in or der to en sure that the ini tiallow-level de lay count is cor rect, the value 128 – (xx/2) must be cal cu lated, where xx is the value in the orig i nal countL reg is ter. The pro gram per forms the di vi sion by 2by shift ing bits to the right one po si tion. The re sult ing value is sub tracted from 128and the re sult stored in TMR0, as follows:

; First cal cu late xx/2 by bit shift ingbcf STATUS,C ; Clear carry flagrrf countL,f ; Di vide by 2

; now sub tract 128 - (xx/2)movf countL,w ; w holds low-or der bytesublw .128

; Now w has ad justed re sult. Store in TMR0movwf TMR0

The de lay rou tine de tects timer over flow by test ing bit 7 of the TMR0 reg is ter. Ifthe bit is set, then 256 time cy cles have elapsed (ex cept in the first it er a tion) and the mid-or der coun ter reg is ter is dec re ment ed. If the mid-or der reg is ter over flows when it is dec re ment ed, then the high-or der reg is ter is dec re ment ed. If it over flows, thecoun ter has gone to zero and the de lay routine ends, as follows:

; Rou tine tests timer over flow by test ing bit 7 of; the TMR0 reg is ter.cy cle:

btfss TMR0,7 ; Is bit 7 set?goto cy cle ; Wait if not set

; At this point TMR0 bit 7 is set; Clear the bit

bcf TMR0,7 ; All other bits are pre served; Sub tract 256 from beat coun ter by dec re ment ing the; mid-or der byte

decfsz countM,fgoto cy cle ; Con tinue if mid-byte not zero

; At this point the mid-or der byte has over flowed.; High-or der byte must be dec re ment ed.

decfsz countH,fgoto cy cle

; At this point the time cy cle has elapsedre turn

Tim ers and Coun ters 197

Page 219: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

The cir cuit in Fig ure 11-3 and the Vir tual Board A ap pli ca tion can be used to testthe VariLapse pro gram.

11.4.6 Interrupt-Driven TimerIn ter rupt-driven tim ers and coun ters have two ma jor ad van tages over polled rou tines:

1. The time lapse counting take place in the back ground so that the ap pli ca tion cancon tinue to do other work in the fore ground.

2. Pro cess ing can take place with out the prescaler, which can be used for the Watch -dog timer.

De vel op ing a timer rou tine that is In ter rupt-driven is quite sim i lar to de vel op ingany other in ter rupt rou tines. The ini tial iza tion con sists of con fig ur ing the OPTIONand the INTCON reg is ter bits for the task at hand. In the par tic u lar case of an In ter -rupt-Driven timer, the following are nec es sary:

1. The ex ter nal interrupt flag (INTF in the INTCON Reg is ter) must be ini tially cleared.

2. Global in ter rupts must be en abled by set ting the GIE bit in the INTCON reg is ter.

3. The Timer0 overflow in ter rupt must be en abled by set ting the TOIE bit in theINTCON register.

11.4.7 TimerInt Pro gramThe TimerInt pro gram is an In ter rupt-Driven ver sion of the VariLapse pro gram de vel -oped ear lier. Here again, code uses Timer0 to pro duce a vari able-lapse de lay. The de -lay of one-fourth second is cal cu lated based on the num ber of ma chine cy clesnec es sary for the de sired wait pe riod.

Code De tails

In the TimerInt pro gram the prescaler is not used with the timer, so the ini tial iza tioncode sets the PSA bit in the OPTION reg is ter so that the prescaler is as signed to theWatch dog timer. The fol low ing code frag ment is from the TimerInt pro gram:

; Clear the Watchdog timer and re set prescalerclrf TMR0clrwdt

; Set up the OPTION reg is termovlw b’11011000’

; 7 6 5 4 3 2 1 0 <= OPTION bits; | | | | | |__|__|_____ PS2-PS0 (prescaler bits); | | | | | Val ues for Timer0; | | | | | 000 = 1:2 001 = 1:4; | | | | | 010 = 1:8 011 = 1:16; | | | | | 100 = 1:32 101 = 1:64; | | | | | 110 = 1:128 *111 = 1:256; | | | | |______________ PSA (prescaler as sign); | | | | *1 = to WDT; | | | | 0 = to Timer0; | | | |_________________ TOSE (Timer0 edge se lect); | | | 0 = in cre ment on low-to-high; | | | *1 = in cre ment on high-to-low; | | |____________________ TOCS (TMR0 clock source); | | *0 = in ter nal clock

198 Chap ter 11

Page 220: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; | | 1 = RA4/TOCKI bit source; | |_______________________ INTEDG (Edge se lect); | *0 = fall ing edge; |__________________________ RBPU (Pullup en able); 0 = en abled; *1 = disabled; Note that OPTION reg is ter is in bank 1 and its reg is ter; name is OPTION_REG

bsf STATUS,RP0 ; RP0 is bank se lect bitmovwf OPTION_REG ; Copy w to OPTIONbcf STATUS,RP0 ; Bank 0

; Setup portsmovlw 0x00 ; Set port B to out puttris PORTBclrf PORTB ; All port B to 0

; Port A is not used in this pro gram

In ter rupts are set up clear ing the INTF flag in the INTCON reg is ter and set tingthe GIE and TOIE bits.

;============================; setup in ter rupts;============================; Clear ex ter nal in ter rupt flag (INTF = bit 1)

bcf INTCON,INTF ; Clear flag; En able global in ter rupts (GIE = bit 7); En able RB0 in ter rupt (inte = bit 4)

bsf INTCON,GIE ; En able global int (bit 7)bsf INTCON,T0IE ; En able TMR0 over flow in ter rupt

As in the pro gram VariLapse, de vel oped pre vi ously in this chap ter, the timer op er -ates by dec re ment ing a 3-byte coun ter that holds the num ber of timer beats re quired for the de lay. In the case of the TimerInt pro gram, the rou tine that initializes the reg -is ter vari ables from the lo cal con stants (called setDelay) also makes the cor rec tionso that the ini tial value loaded into the TMR0 reg is ter is cor rectly ad justed. Thecode is as follows:

;==============================; Ini tial ize de lay coun ters;==============================; Pro ce dure to ini tial ize lo cal vari ables for a de lay de fined; in pro gram con stants. For a one-half sec ond on a 16F84 at; 4 MHz ini tial iza tion val ues are as fol lows:; 500,000 = 0x07 0xa1 0x20; ---- ---- ----; | | |___ low_byte; | |________ mid_byte; |_____________ high_bytesetDelay:

movlw high_bytemovwf countHmovlw mid_bytemovwf countMmovlw low_bytemovwf countL

; The Timer0 reg is ter pro vides the low-or der level; of the count. Because the coun ter counts up from zero,; in or der to en sure that the ini tial low-level de lay; count is cor rect the value 256 - xx must be cal cu lated

Tim ers and Coun ters 199

Page 221: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; where xx is the value in the orig i nal countL reg is ter.movf countL,w ; w holds low-or der bytesublw .255

; Now w has ad justed re sult. Store in TMR0movwf TMR0re turn

The in ter rupt ser vice rou tine in the TimerInt pro gram re ceives con trol when theTMR0 reg is ter underflows, that is, when the count goes from 0xff to 0x00. The ser -vice rou tine then pro ceeds to dec re ment the mid-range coun ter reg is ter and ad just,if nec es sary, the high-or der coun ter. If the count goes to zero, the han dler tog glesthe LED on port B, line 0, and reinitializes the coun ter vari ables by call ing thesetDelay pro ce dure. The in ter rupt handler is coded as follows:

;=======================================================; In ter rupt Ser vice Rou tine;=======================================================; Ser vice rou tine re ceives con trol when the timer; reg is ter TMR0 over flows, that is, when 256 timer beats; have elapsedIntServ:; First test if source is a Timer0 in ter rupt

btfss INTCON,T0IF ; T0IF is Timer0 in ter ruptgoto notTOIF ; Go if not RB0 or i gin

; If so clear the timer in ter rupt flag so that count con tin uesbcf INTCON,T0IF ; Clear in ter rupt flag

; Save con textmovwf old_w ; Save w reg is terswapf STATUS,w ; STATUS to wmovwf old_STATUS ; Save STATUS

;=========================; in ter rupt ac tion;=========================; Sub tract 256 from beat coun ter by dec re ment ing the; mid-or der byte

decfsz countM,fgoto exitISR ; Con tinue if mid-byte not zero

; At this point the mid-or der byte has over flowed.; High-or der byte must be dec re ment ed.

decfsz countH,fgoto exitISR

; At this point count has ex pired so the pro grammed time; has elapsed. Ser vice rou tine turns the LED on line 0,; port B on and off at ev ery con clu sion of the count.; This is done by XORing a mask with a one-bit at the; port B line 0 po si tion

movlw b’00000001’ ; Xoring with a 1-bit pro duces; the com ple ment

xorwf PORTB,f ; Com ple ment bit 2, port B ; Re set de lay con stants

call setDelay;=========================; exit ISR;=========================exitISR:; Re store con text

swapf old_STATUS,w ; Saved STATUS to wmovfw STATUS ; To STATUS reg is terswapf old_w,f ; Swap file reg is ter in it self

200 Chap ter 11

Page 222: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

swapf old_w,w ; re-swap back to w; Re set,in ter ruptnotTOIF:

retfie

Note that one of the ini tial op er a tions of the ser vice rou tine is to clear the TOIFbit in the INTCON reg is ter. This ac tion reenables the timer in ter rupt and pre ventscount ing cy cles from be ing lost. Be cause the in ter rupt is gen er ated ev ery 256 beatsof the timer, there is no risk that by en abling the timer in ter rupt flag a re-en trant in -ter rupt will take place.

The in ter rupt-based timer pro gram named TimerInt can be tested on the cir cuitshown in Fig ure 11-3 or on Vir tual Board A. Re call that Vir tual Board I is used for in -ter rupts that are based on port B in put lines, which is not the case with the TimerIntprogram.

11.5 Watchdog TimerThe 16F84 con tains an in de pend ent timer with its own clock source called theWWatch dog timer or WDT. The pur pose of the Watch dog timer is to pro vide a way forthe pro ces sor to re cover from a soft ware er ror that im pedes pro gram con tin u a tion,such as an end less loop. The Watch dog timer is not de signed to re cover from hard ware faults, such as a brown-out.

The Watch dog timer hard ware is in de pend ent of the PIC’s in ter nal clock. It has atime-out pe riod from ap prox i mately 18 mil li sec onds to 2.3 sec onds, de pend ing onwhether the prescaler is used. It is also not very ac cu rate be cause it is sen si tive totem per a ture. Ac cord ing to Micro chip doc u men ta tion, un der worst case con di tionsits time-out pe riod can take up to sev eral sec onds. The fol low ing pro gram el e mentsrelate to Watch dog timer op er a tion:

1. Con fig u ra tion bit 2, la beled WDTE, en ables and dis ables the Watch dog timer dur -ing sys tem con fig u ra tion. The WDT can not be set or re set at runtime. It is en abledand dis abled dur ing pro gram ming.

2. The PSA bit in the OPTION register se lects whether the prescaler is as signed to theWatch dog timer or to the Timer0 mod ule.

3. Bits PS2 to PS0 in the OPTION register al low as sign ing eight rates to the Watch dogtimer, from 1:1 to 1:128.

4. Bit 4 of the STATUS register, named the TO bit, is cleared when a time-out con di tion occurrs that orig i nated in the WDT.

5. The power-down bit (PD) in the STATUS register is set af ter the ex e cu tion of theclrwdt in struc tion.

6. The clrwdt in struc tion clears the Watch dog timer. It also clears the prescaler count (if the prescaler is as signed to the Watch dog timer) and sets STATUS bits TO andPD.

The pur pose of the WDT is to pro vide a re covery mech a nism for soft ware er rors.When the WDT timesout, the TO flag in the STATUS reg is ter is cleared and the pro -gram coun ter is re set to 0x000 so that the pro gram re starts. Ap pli ca tions can pre -

Tim ers and Coun ters 201

Page 223: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

vent the re set by is su ing the clrwdt in struc tion be fore the time-out pe riod ends.When clrwdt ex e cutes, the WDT time-out period re starts.

11.5.1 Watch dog Timer Pro gram mingNot much in for ma tion is avail able re gard ing de tails of the op er a tion or prac ti cal usesof the Watch dog timer in the 16F84. How ever, we can see that us ing the WDT in ap pli -ca tions is not just a sim ple mat ter of re start ing the coun ter with the clrwdt in struc tion. The timer is de signed to de tect soft ware er rors that can hangup a pro gram, but howdoes it de tect these er rors and which con di tions trig ger the WDT op er a tion is not clear from the in for ma tion cur rently avail able. For ex am ple, an ap pli ca tion that con tains along de lay loop may de ter mine that the Watch dog timer forces an un timely break outof the loop. The Watch dog timer pro vides a pow er ful er ror-re cov ery mech a nism butits use re quires care ful con sid er ation of pro gram con di tions that could make thetimer mal func tion.

11.6 Demonstration Pro gramsThe fol low ing pro grams dem on strate the pro gram ming dis cussed in this chap ter:

11.6.1 Tmr0Counter pro gram; File name: Tmr0Counter.asm; Date: April 30, 2011; Au thors: Canton and Sanchez; Pro ces sor: 16F84A;; Ref er ence: SevenSeg Cir cuit and Board;; De scrip tion:; Test pro gram for the Timer0 coun ter. The pro gram counts; the num ber of presses of the pushbutton switch on port; RA4/TOCKI and dis play the count on a seven-seg ment LED.; Switch is wired ac tive low.;; Switches used in __config di rec tive:; _CP_ON Code pro tec tion ON/OFF ; * _CP_OFF ; * _PWRTE_ON Power-up timer ON/OFF; _PWRTE_OFF ; _WDT_ON Watch dog Timer ON/OFF ; * _WDT_OFF ; _LP_OSC Low power crys tal oscillator; * _XT_OSC Ex ter nal par al lel res o na tor/crys tal ocillator; ; _HS_OSC High speed crys tal res o na tor (8 to 10 MHz); Res o na tor: Murate Erie CSA8.00MG = 8 MHz ; _RC_OSC Re sis tor/ca pac i tor oscillator ; |; |_____ * in di cates set up val ues

202 Chap ter 11

Page 224: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

;;=========================; set up and con fig u ra tion;=========================

pro ces sor 16f84Ain clude <p16f84A.inc>__config _XT_OSC & _WDT_OFF & _PWRTE_ON & _CP_OFF

;;=====================================================; con stant def i ni tions; (per cir cuit wir ing di a gram);=====================================================#de fine Pb_sw 4 ; Port-A line 4 to pushbut ton switch;;============================; lo cal vari ables;============================

cblock 0x0c ; Start of blockJ ; coun ter JK ; coun ter Kendc

;============================================================; pro gram;============================================================

org 0 ; start at ad dress 0goto main

;; Space for in ter rupt han dlers

org 0x08

main:; Clear the timer and the Watchdog

clrf TMR0clrwdt

; Set up the OPTION regiser bit mapmovlw b’10111000’

; 7 6 5 4 3 2 1 0 <= OPTION bits; | | | | | |__|__|_____ PS2-PS0 (prescaler bits); | | | | | Values for Timer0; | | | | | *000 = 1:2 001 = 1:4; | | | | | 010 = 1:8 011 = 1:16; | | | | | 100 = 1:32 101 = 1:64; | | | | | 110 = 1:128 *111 = 1:256; | | | | |______________ PSA (prescaler as sign); | | | | *1 = to WDT; | | | | 0 = to Timer0; | | | |_________________ TOSE (Timer0 edge se lect); | | | 0 = in cre ment on low-to-high

Tim ers and Coun ters 203

Page 225: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; | | | *1 = in cre ment on high-to-low; | | |____________________ TOCS (TMR0 clock source); | | 0 = in ter nal clock; | | *1 = RA4/TOCKI bit source; | |_______________________ INTEDG (Edge se lect); | *0 = fall ing edge; |__________________________ RBPU (Pullup en able); 0 = en abled; *1 = disabled

op tion; Set up ports

movlw 0x00 ; Set Port-B to out puttris PORTBclrf PORTB ; All Port-B to 0

; Port-A. Five low-order lines set for for in putmovlw B’00011111’ ; w = 00011111 bi narytris PORTA ; Port-A (lines 0 to 4) to

; in put;=================================; Check value in TMR0 and dis play;=================================; Ev ery press of the pushbutton switch con nected to line; RA4/TOCKI adds one to the value in the TMR0 reg is ter.; Loop checks this value, ad justs to the range 0 to 15; and dis plays the re sult in the Seven-Segment LED on; Port-BcheckTmr0:

movf TMR0,w ; Timer reg is ter to w; Eliminate four high or der bits

andlw b’00001111’ ; Mask off high bits; At this point the w reg is ter con tains a 4-bit value; in the range 0 to 0xf. Use this value (in w) to ; ob tain Seven-Segment dis play code

call seg mentmovwf PORTB ; Dis play switch bitsgoto checkTmr0 ; End less loop

;;================================; rou tine to re turns 7-segment; codes;================================seg ment:

addwf PCL,f ; PCL is pro gram coun ter latchretlw 0x3f ; 0 coderetlw 0x06 ; 1retlw 0x5b ; 2retlw 0x4f ; 3retlw 0x66 ; 4

204 Chap ter 11

Page 226: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

retlw 0x6d ; 5retlw 0x7d ; 6retlw 0x07 ; 7retlw 0x7f ; 8retlw 0x6f ; 9retlw 0x77 ; Aretlw 0x7c ; Bretlw 0x39 ; Cretlw 0x5b ; Dretlw 0x79 ; Eretlw 0x71 ; Fretlw 0x7f ; Just in case all onend

11.6.2 Timer0 Pro gram ; File: Timer0.ASM; Date: April 7, 2011; Au thors: Canton and Sanchez; Pro ces sor: a6F84A;; De scrip tion:; Pro gram to dem on strate pro gram ming of the 16F84A; Timer0 mod ule. Pro gram flashes eight LEDs in se quence; count ing from 0 to 0xff. Timer0 is used to de lay; the count.;===========================; switches;===========================; Switches used in __config di rec tive:; _CP_ON Code pro tec tion ON/OFF ; * _CP_OFF ; * _PWRTE_ON Power-up timer ON/OFF; _PWRTE_OFF ; _WDT_ON Watch dog Timer ON/OFF ; * _WDT_OFF ; _LP_OSC Low power crys tal oscillator; * _XT_OSC Ex ter nal par al lel res o na tor/crys tal oscillator ;; _HS_OSC High speed crys tal res o na tor (8 to 10 MHz); Res o na tor: Murate Erie CSA8.00MG = 8 MHz ; _RC_OSC Re sis tor/ca pac i tor oscillator (sim plest, 20%; er ror); |; |_____ * in di cates set up val ues

pro ces sor 16f84Ain clude <p16f84A.inc>

Tim ers and Coun ters 205

Page 227: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

__config _XT_OSC & _WDT_OFF & _PWRTE_ON & _CP_OFF;=====================================================; vari ables in PIC RAM;=====================================================; None in this ap pli ca tion;;========================================================; m a i n p r o g r a m;========================================================

org 0 ; start at ad dress 0goto main

;;=============================; in ter rupt han dler;=============================

org 0x08;=============================; main pro gram;=============================main:; Clear the Watch dog Timer and re set prescaler

clrwdt; Set up the OPTION regiser bit map

movlw b’11010111’; 7 6 5 4 3 2 1 0 <= OPTION bits; | | | | | |__|__|_____ PS2-PS0 (prescaler bits); | | | | | Values for Timer0; | | | | | 000 = 1:2 001 = 1:4; | | | | | 010 = 1:8 011 = 1:16; | | | | | 100 = 1:32 101 = 1:64; | | | | | 110 = 1:128 *111 = 1:256; | | | | |______________ PSA (prescaler as sign); | | | | 1 = to WDT; | | | | *0 = to Timer0; | | | |_________________ TOSE (Timer0 edge se lect); | | | 0 = in cre ment on low-to-high; | | | *1 = in cre ment on high-to-low; | | |____________________ TOCS (TMR0 clock source); | | *0 = in ter nal clock; | | 1 = RA4/TOCKI bit source; | |_______________________ INTEDG (Edge se lect); | *0 = fall ing edge; |__________________________ RBPU (Pullup en able); 0 = en abled; *1 = disabled

op tion; Set up ports

movlw 0x00 ; Set Port-B to out put

206 Chap ter 11

Page 228: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

tris PORTBclrf PORTB ; All Port-B to 0

; Port-A is not used in this pro grammloop:

incf PORTB,f ; Add 1 to reg is ter valuecall TM0delaygoto mloop

;******************************; de lay sub-routine; uses Timer0;******************************TM0delay:; Ini tial ize the timer reg is ter

clrf TMR0 ; Clear SFR for Timer0; Rou tine tests the value in the TMR0 reg is ter by; sub tract ing 0xff from the value in TMR0. The zero flag; is set if TMR0 = 0xffcy cle:

movf TMR0,w ; Timer to w; w has TMR0 reg is ter value

sublw 0xff ; Sub tract max value; Zero flag is set if value in TMR0 = 0xff

btfss STATUS,Z ; Test for zerogoto cy cle ; Re peatre turn

end

11.6.3 LapseTimer Pro gram; File: LapseTimer.ASM; Date: May 1, 2011; Au thors: Canton and Sanchez; Pro ces sor: 16F84A;; De scrip tion:; Using Timer0 to pro duce a vari able-lapse de lay.; The de lay is cal cu lated based on the num ber of ma chine; cy cles nec es sary for the de sired wait pe riod. For; ex am ple, a ma chine run ning at a 4 MHz clock rate; ex e cutes 1,000,000 in struc tions per sec ond. In this; case a 1/2 sec ond de lay re quires 500,000 in struc tions.; The wait pe riod is passed to the de lay rou tine in three; pro gram reg is ters which hold the high-, mid dle-, and; low-order bytes of the coun ter.;===========================; switches;===========================

Tim ers and Coun ters 207

Page 229: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; Switches used in __config di rec tive:; _CP_ON Code pro tec tion ON/OFF ; * _CP_OFF ; * _PWRTE_ON Power-up timer ON/OFF; _PWRTE_OFF ; _WDT_ON Watch dog Timer ON/OFF ; * _WDT_OFF ; _LP_OSC Low power crys tal oscillator; * _XT_OSC Ex ter nal par al lel res o na tor/crys tal oscillator ;; _HS_OSC High speed crys tal res o na tor (8 to 10 MHz); Res o na tor: Murate Erie CSA8.00MG = 8 MHz ; _RC_OSC Re sis tor/ca pac i tor oscillator; |; |_____ * in di cates set up val ues

pro ces sor 16f84Ain clude <p16f84A.inc>__config _XT_OSC & _WDT_OFF & _PWRTE_ON & _CP_OFF

;=====================================================; vari ables in PIC RAM;=====================================================; Lo cal vari ables

cblock 0x0d ; Start of block; 3-byte aux il iary coun ter for de lay.

countH ; High-order bytecountM ; Me dium-order bytecountL ; Low-order byteendc

;========================================================; m a i n p r o g r a m;========================================================

org 0 ; start at ad dress 0goto main

;;=============================; in ter rupt han dler;=============================

org 0x04; goto IntServ;=============================; main pro gram;=============================main:; Clear the Watch dog Timer and re set prescaler

clrf TMR0clrwdt

; Set up the OPTION regiser bitmap

208 Chap ter 11

Page 230: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

movlw b’11010000’; 7 6 5 4 3 2 1 0 <= OPTION bits; | | | | | |__|__|_____ PS2-PS0 (prescaler bits); | | | | | Values for Timer0; | | | | | *000 = 1:2 001 = 1:4; | | | | | 010 = 1:8 011 = 1:16; | | | | | 100 = 1:32 101 = 1:64; | | | | | 110 = 1:128 *111 = 1:256; | | | | |______________ PSA (prescaler as sign); | | | | 1 = to WDT; | | | | *0 = to Timer0; | | | |_________________ TOSE (Timer0 edge se lect); | | | 0 = in cre ment on low-to-high; | | | *1 = in cre ment on high-to-low; | | |____________________ TOCS (TMR0 clock source); | | *0 = in ter nal clock; | | 1 = RA4/TOCKI bit source; | |_______________________ INTEDG (Edge se lect); | *0 = fall ing edge; |__________________________ RBPU (Pullup en able); 0 = en abled; *1 = disabled

op tion; Set up ports

movlw 0x00 ; Set Port-B to out puttris PORTBclrf PORTB ; All Port-B to 0

; Port-A is not used in this pro gram;============================; dis play loop;============================ mloop:; Turn on LED

bsf PORTB,0; Ini tial ize coun ters and de lay

call onehalfSeccall TM0delay

; Turn off LEDbcf PORTB,0

; Re-initialize coun ter and de laycall onehalfSeccall TM0delaygoto mloop

;==================================; vari able-lapse de lay pro ce dure; us ing Timer0;==================================; ON ENTRY:

Tim ers and Coun ters 209

Page 231: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; Vari ables countL, countM, and countH hold; the low-, mid dle-, and high-order bytes; of the de lay pe riod, in timer units ; Rou tine logic:; The prescaler is as signed to Timer0 and set up so; that the timer runs at 1:2 rate. This means that; ev ery time the coun ter reaches 128 (0x80) a to tal; of 256 ma chine cy cles have elapsed. The value 0x80; is de tected by test ing bit 7 of the coun ter; reg is ter.; Note:; The Timer0 reg is ter pro vides the low-order level; of the count. Because the coun ter counts up from zero,; in or der to en sure that the ini tial low-level de lay; count is cor rect the value 128 - (xx/2) must be cal cu lated; where xx is the value in the orig i nal countL reg is ter.; First cal cu late xx/2 by bit shift ingTM0delay:

bcf STATUS,C ; Clear carry flagrrf countL,f ; Di vide by 2

; now sub tract 128 - (xx/2)movf countL,w ; w holds low-order bytesublw d’128’

; Now w has ad justed re sult. Store in TMR0movwf TMR0

; Rou tine tests timer over flow by test ing bit 7 of; the TMR0 reg is ter.cy cle:

btfss TMR0,7 ; Is bit 7 set?goto cy cle ; Wait if not set

; At this point TMR0 bit 7 is set; Clear the bit

bcf TMR0,7 ; All other bits are pre served; Sub tract 256 from beat coun ter by dec re ment ing the; mid-order byte

decfsz countM,fgoto cy cle ; Con tinue if mid-byte not

zero; At this point the mid-order byte has over flowed.; High-order byte must be dec re ment ed.

decfsz countH,fgoto cy cle

; At this point the time cy cle has elapsedre turn

;==============================; set reg is ter vari ables for; one-half sec ond de lay;==============================

210 Chap ter 11

Page 232: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; Pro ce dure to ini tial ize lo cal vari ables for a; de lay of one-half sec ond on a 16F84 at 4 MHz.; Timer is set up for 500,000 clock beats as; fol lows: 500,000 = 0x07 0xa1 0x20; 500,000 = 0x07 0xa1 0x20; ---- ---- ----; | | |___ countL); | |________ countM; |_____________ countHonehalfSec:

movlw 0x07movwf countHmovlw 0xa1movwf countMmovlw 0x20movwf countLre turn

end

11.6.4 LapseTmrInt Pro gram; File: LapseTmrInt.ASM; Date: May 1, 2011; Au thors: Canton and Sanchez; Pro ces sor: 16F84A;; De scrip tion:; Interrupt-Driven ver sion of the LapseTimer pro gram.; Using Timer0 to pro duce a vari able-lapse de lay.; The de lay is cal cu lated based on the num ber of ma chine; cy cles nec es sary for the de sired wait pe riod. For; ex am ple, a ma chine run ning at a 4 MHz clock rate; ex e cutes 1,000,000 in struc tions per sec ond. In this; case a 1/2 sec ond de lay re quires 500,000 in struc tions.; The wait pe riod is passed to the de lay rou tine in three; reg is ter vari ables which hold the high-, mid dle-, and; low-order bytes of the coun ter.;===========================; switches;===========================; Switches used in __config di rec tive:; _CP_ON Code pro tec tion ON/OFF ; * _CP_OFF ; * _PWRTE_ON Power-up timer ON/OFF; _PWRTE_OFF ; _WDT_ON Watch dog Timer ON/OFF ; * _WDT_OFF

Tim ers and Coun ters 211

Page 233: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; _LP_OSC Low power crys tal oscillator; * _XT_OSC Ex ter nal par al lel res o na tor/crys tal oscillator ;; _HS_OSC High speed crys tal res o na tor (8 to 10 MHz); Res o na tor: Murate Erie CSA8.00MG = 8 MHz ; _RC_OSC Re sis tor/ca pac i tor oscillator; |; |_____ * in di cates set up val ues

pro ces sor 16f84Ain clude <p16f84A.inc>__config _XT_OSC & _WDT_OFF & _PWRTE_ON & _CP_OFF

;=====================================================; vari ables in PIC RAM;=====================================================; Lo cal vari ables

cblock 0x0d ; Start of block; 3-byte aux il iary coun ter for de lay.

countH ; High-order bytecountM ; Me dium-order bytecountL ; Low-order byteold_w ; Con text sav ing old_STATUS ; Idemendc

;========================================================; m a i n p r o g r a m;========================================================

org 0 ; start at ad dress 0goto main

;;=============================; in ter rupt han dler;=============================

org 0x04goto IntServ

;=============================; main pro gram;=============================main:; Clear the Watch dog Timer and re set prescaler

clrf TMR0clrwdt

; Set up the OPTION regiser bit mapmovlw b’11011000’

; 7 6 5 4 3 2 1 0 <= OPTION bits; | | | | | |__|__|_____ PS2-PS0 (prescaler bits); | | | | | Values for Timer0

212 Chap ter 11

Page 234: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; | | | | | 000 = 1:2 001 = 1:4; | | | | | 010 = 1:8 011 = 1:16; | | | | | 100 = 1:32 101 = 1:64; | | | | | 110 = 1:128 *111 = 1:256; | | | | |______________ PSA (prescaler as sign); | | | | *1 = to WDT; | | | | 0 = to Timer0; | | | |_________________ TOSE (Timer0 edge se lect); | | | 0 = in cre ment on low-to-high; | | | *1 = in cre ment on high-to-low; | | |____________________ TOCS (TMR0 clock source); | | *0 = in ter nal clock; | | 1 = RA4/TOCKI bit source; | |_______________________ INTEDG (Edge se lect); | *0 = fall ing edge; |__________________________ RBPU (Pullup en able); 0 = en abled; *1 = disabled

op tion; Set up ports

movlw 0x00 ; Set Port-B to out puttris PORTBclrf PORTB ; All Port-B to 0

; Port-A is not used in this pro gram;============================; set up in ter rupts;============================; Clear ex ter nal in ter rupt flag (INTF = bit 1)

bcf INTCON,INTF ; Clear flag; En able global in ter rupts (GIE = bit 7); En able RB0 in ter rupt (inte = bit 4)

bsf INTCON,GIE ; En able global int (bit 7)bsf INTCON,T0IE ; En able TMR0 over flow

; in ter rupt; Init count

call onehalfSec;============================; do-nothing loop;============================ ; All work is per formed by the in ter rupt han dlermloop:

goto mloop;==============================; set reg is ter vari ables for; one-half sec ond de lay;==============================; Pro ce dure to ini tial ize lo cal vari ables for a; de lay of one-half sec ond on a 16F84 at 4 MHz.

Tim ers and Coun ters 213

Page 235: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; Timer is set up for a 500,000 clock beats as; fol lows: 500,000 = 0x07 0xa1 0x20; 500,000 = 0x07 0xa1 0x20; ---- ---- ----; | | |___ countL); | |________ countM; |_____________ countHonehalfSec:

movlw 0x07movwf countHmovlw 0xa1movwf countMmovlw 0x20movwf countL

; The Timer0 reg is ter pro vides the low-order level; of the count. Because the coun ter counts up from zero,; in or der to en sure that the ini tial low-level de lay; count is cor rect the value 256 - xx must be cal cu lated; where xx is the value in the orig i nal countL reg is ter.

movf countL,w ; w holds low-order bytesublw d’255’

; Now w has ad justed re sult. Store in TMR0movwf TMR0re turn

;=======================================================; In ter rupt Ser vice Rou tine;=======================================================; Ser vice rou tine re ceives con trol when there the timer; reg is ter TMR0 over flows, that is, when 256 timer beats; have elapsedIntServ:; First test if source is a Timer0 in ter rupt

btfss INTCON,T0IF ; T0IF is Timer0 in ter ruptgoto notTOIF ; Go if not RB0 or i gin

; If so clear the timer in ter rupt flag so that count con tin uesbcf INTCON,T0IF ; Clear in ter rupt flag

; Save con textmovwf old_w ; Save w reg is terswapf STATUS,w ; STATUS to wmovwf old_STATUS ; Save STATUS

;=========================; in ter rupt ac tion;=========================; Sub tract 256 from beat coun ter by dec re ment ing the; mid-order byte

decfsz countM,fgoto exitISR ; Con tinue if mid-byte not zero

; At this point the mid-order byte has over flowed.

214 Chap ter 11

Page 236: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; High-order byte must be dec re ment ed.decfsz countH,fgoto exitISR

; At this point count has ex pired so the pro grammed time; has elapsed. Ser vice rou tine turns the LED on line 0,; Port-B on and off at ev ery con clu sion of the count.; This is done by xoring a mask with a one-bit at the; Port-B line 0 po si tion

movlw b’00000001’ ; Xoring with a 1-bit pro duces; the com ple ment

xorwf PORTB,f ; Com ple ment bit 2, Port-B ; Re set one-half sec ond coun ter

call onehalfSec;=========================; exit ISR;=========================exitISR:; Re store con text

swapf old_STATUS,w ; Saved STATUS to wmovfw STATUS ; To STATUS reg is terswapf old_w,f ; Swap file reg is ter in it selfswapf old_w,w ; re-swap back to w

; Re set,in ter ruptnotTOIF:

retfie

end

Tim ers and Coun ters 215

Page 237: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

This page intentionally left blankThis page intentionally left blank

Page 238: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Chap ter 12

LCD Hardware and Pro gramming

12.1 Liq uid Crys tal Dis play

Liq uid crys tal dis plays (LCDs) are de vices fre quently used for al pha nu meric out putin microcontroller-based em bed ded systems. Their ad van tages are their re duced size,mod er ate cost, and the con ve nience of mount ing the LCD di rectly on the cir cuitboard. Ac cord ing to their in ter face, LCDs are clas si fied into se rial and par al lel. Se rialLCDs re quire less I/O re sources but ex e cute slower than their par al lel coun ter parts.Al though se rial LCDs re quire less con trol lines, they are con sid er ably more ex pen sivethan the par al lel type. In this chap ter we dis cuss par al lel-driven LCD de vices based onthe Hitachi HD44780 char ac ter-based con trol ler, which is by far the most pop u lar con -trol ler for PIC-driven LCDs. LCD tech nol ogy was dis cussed in Chap ter 4.

12.1.1 LCD Fea tures and Ar chi tec ture

The HD44780 is a dot-matrix liq uid crys tal dis play con trol ler and driver. The de vicedis plays ASCII al pha nu meric char ac ters, Jap a nese kana char ac ters, and some sym -bols. A sin gle HD44780 can dis play up to two 28-character lines. An avail able ex ten -sion driver makes pos si ble ad dress ing up to 80 char ac ters.

The HD44780U con tains a 9,920-bit char ac ter-generator ROM that pro duces a to -tal of 240 char ac ters: 208 char ac ters with a 5 x 8 dot res o lu tion and 32 char ac ters ata 5 x 10 dot res o lu tion. The de vice is ca pa ble of stor ing 64 times 8-bit char ac ter data in its char ac ter gen er a tor RAM. This cor re sponds to eight cus tom char ac ters in 5times 8-dot res o lu tion or four char ac ters in 5 times 10-dot res o lu tion.

The con trol ler is pro gram ma ble to three dif fer ent duty cy cles: 1/8 for one line of 5 × 8 dots with cur sor, 1/11 for one line of 5 × 10 dots with cur sor, and 1/16 for twolines of 5 × 8 dots with cur sor. The built-in com mands in clude clear ing the dis play,hom ing the cur sor, turn ing the dis play on and off, turn ing the cur sor on and off, set -ting dis play char ac ters to blink, shift ing the cur sor and the display left-to-right orright-to-left, and read ing and writ ing data to the char ac ter gen er a tor and to dis playdata ROM.

217

Page 239: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

12.1.2 LCD Func tions and Com po nents

The fol low ing hard ware el e ments form part of the HD44780 con trol ler: two in ter nalreg is ters la beled the data reg is ter and the in struc tion reg is ter, a busy flag, an ad dresscoun ter, a RAM area of dis play data (DDRAM), a char ac ter gen er a tor ROM, a char ac -ter gen er a tor RAM, a tim ing gen er a tion cir cuit, a liq uid crys tal dis play driver cir cuit,and a cur sor and blink con trol cir cuit. The con trol ler it self is of ten re ferred to as theMPU in the Hitachi lit er a ture.

In ter nal Reg is ters

The HD44780 con tains an IR (in struc tion reg is ter) and a DR (data reg is ter). The IR isused to store in struc tion codes, such as those to clear the dis play, de fine an ad dress,or store a bitmap in char ac ter gen er a tor RAM. The IR is writ ten only from the con trol -ler.

The data reg is ter, DR, is used to tem po rarily store data to be writ ten intoDDRAM or CGRAM as well as tem po rarily store data read from DDRAM or CGRAM.Data placed in the data reg is ter is au to mat i cally writ ten into DDRAM or CGRAM byan in ter nal op er a tion.

Busy Flag

When BF (the busy flag) is 1, the HD44780U is in the in ter nal op er a tion mode, and thenext in struc tion not ac cepted. The busy flag is mapped to data bit 7. Soft ware must en -sure that the busy flag is re set (BF = 0) be fore the next in struc tion is en tered.

Ad dress Coun ter

AC (the ad dress coun ter) stores the cur rent ad dress used in op er a tions that ac cessDDRAM or CGRAM. When an in struc tion con tains ad dress in for ma tion, the ad dress isstored in the ad dress coun ter. The RAM area ac cessed—DDRAM or CGRAM—is alsode ter mined by the in struc tion that stores the ad dress in the AC.

The AC is au to mat i cally in cre mented or dec re ment ed af ter each in struc tion thatwrites or reads DDRAM or CGRAM data. The vari a tions and op tions in op er a tionsthat change the AC are de scribed later in this chap ter.

Dis play Data RAM (DDRAM)

DDRAM (the dis play data RAM area) is used to store the 8-bit bitmaps that rep re sentthe dis play char ac ters and graph ics. Dis play data is rep re sented in 8-bit char ac tercodes. When equipped with the ex ten sion, its ca pac ity is 80 times 8 bits, or 80 char ac -ters. The area not used for stor ing dis play char ac ter can be used by soft ware for stor -ing any other 8-bit data. The map ping of DDRAM lo ca tions to the LCD dis play isdis cussed in Sec tion 12.1.3.

Char ac ter Gen er a tor ROM (CGROM)

The char ac ter gen er a tor is a ROM that has the bitmaps for 208 char ac ters in 5 times 8dot res o lu tion or 32 char ac ters in 5 times 10 dot res o lu tion. Fig ure 12-1 shows the stan -dard char ac ter set in the HD44780.

218 Chap ter 12

Page 240: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 12-1 HD44780 Char ac ter Set.

With a few ex cep tions, the char ac ters in the range 0x20 to 0x7f cor re spond tothose of the ASCII char ac ter set. The re main ing char ac ters are Jap a nese kana char -ac ters and spe cial sym bols. The char ac ters in the range 0x0 to 0x1f, ASCII con trolchar ac ters, do not func tion as such in the HD44780. Sending a back space (0x08), abell (0x07), or a car riage re turn (0x0d) code to the con trol ler has no ef fect.

Char ac ter Gen er a tor RAM (CGRAM)

CGRAM (the char ac ter gen er a tor RAM) al lows the cre ation of cus tom ized char ac tersby de fin ing the cor re spond ing 5 x 8 bitmaps. Eight cus tom char ac ters can be stored inthe 5 x 8 dot res o lu tion and four in the 5 x 10 res o lu tion. The cre ation and use of cus -tom char ac ters is ad dressed later in this chap ter.

Tim ing Gen er a tion Cir cuit

This cir cuit pro duces the tim ing sig nals for the op er a tion of in ter nal com po nents cir -cuits such as DDRAM, CGROM, and CGRAM. The tim ing gen er a tion cir cuit is not ac -ces si ble to the pro gram.

LCD Hardware and Pro gramming 219

Page 241: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Liq uid Crys tal Dis play Driver Cir cuit

The liq uid crys tal dis play driver cir cuit con sists of six teen com mon sig nal driv ersand forty seg ment sig nal driv ers. The cir cuit re sponds to the num ber of lines and thechar ac ter font se lected. Once this is done, the cir cuit per forms au to mat i cally and isnot oth er wise ac ces si ble to the pro gram.

Cur sor/Blink Con trol Cir cuit

The cur sor and blink con trol cir cuit gen er ates both the cur sor and the char ac terblink ing. The cur sor or the char ac ter blink ing is ap plied to the char ac ter lo cated in the data RAM ad dress ref er enced in the ad dress coun ter (AC).

12.1.3 Con nec tiv ity and Pin-Out LCDs are pow er ful yet com plex de vices. For tu nately, the pro gram mer does not haveto deal with all the com plex i ties of LCD dis plays be cause these de vices are usu ally fur -nished in a mod ule that in cludes the LCD con trol ler. Fur ther more, most LCDs used inmicrocontroller cir cuits are equipped with the same con trol ler: the Hitachi HD44780.This con trol ler pro vides a rel a tively sim ple in ter face be tween a microcontroller andthe LCD.

But the fact that the HD44780 has be come al most ubiq ui tous in LCD con trol lertech nol ogy does not mean that these de vices are with out com pli ca tions. The firstdif fi culty con fronted by the cir cuit de signer is se lect ing the most ap pro pri ate LCDfor the ap pli ca tion among doz ens (per haps hun dreds) of avail able con fig u ra tions,each one with its own res o lu tion, in ter face tech nol ogy, size, graph ics op tions, pinpat terns, and other in di vid ual fea tures. In this sense, it may be better to ex per i mentwith a sim ple LCD in a bread board cir cuit be fore at tempt ing a fi nal cir cuit withhard ware.

Two com mon con nec tors used with 44780-based LCDs have ei ther four teen pinsin a sin gle row, each pin spaced 0.100" apart, or two rows of eight pins each, alsospaced 0.100" apart. In both cases, the pins are la beled in the LCD board. The twocom mon con nec tors are shown in Fig ure 12-2.

Fig ure 12-2 Typ i cal HD44780 Con nec tor Pin-Outs.

220 Chap ter 12

1

1

1314

2

14

Page 242: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

In LCDs with a backlight op tion, some times the con nec tors have two ex tra pins,usu ally num bered 15 and 16. Pin num ber 15 is con nected to a 5V source for thebacklight and pin num ber 16 to ground. Typ i cal LCD wir ing is shown in Ta ble 12.1.

Ta ble 12.1

Hitachi HD44780 LCD Con trol ler Pin-Out (80 char ac ters or less)

PIN NUMBER SYMBOL DESCRIPTION

1 Vss Ground2 Vcc Vcc (Power sup ply +5V)3 Vee Con trast con trol4 RS Set/re set

0 = in struc tion in put1 = data in put

5 R/W R/W (read/write se lect)0 = write to LCD1 = read LCD data

6 E En able. Clock sig nal toini ti ate data trans fer

7 DB0 Data bus line 08 DB1 Data bus line 19 DB2 Data bus line 210 DB3 Data bus line 311 DB4 Data bus line 412 DB5 Data bus line 513 DB6 Data bus line 614 DB7 Data bus line 7

The pin-out in Ta ble 12-1 re fers to con trol lers that ad dress no more than eightychar ac ters. In ad di tion, some LCDs with LED backlighting con tain two ad di tionalpins, usu ally num bered 15 and 16. In these cases, pin num ber 15 is a +5VDC sourcefor the backlight and pin 16 is the backlight ground.

From the pin-out in Ta ble 12-1, it is ev i dent that the in ter face to the LCD useseight par al lel lines (lines 7 to 14). How ever, it is also pos si ble to drive the LCD us ingjust four lines, sav ing con nec tions on lim ited cir cuits.

The reader should be aware that LCDs are of ten fur nished in cus tom boards thatmay or may not have other aux il iary com po nents. These boards are of ten wired dif -fer ently from the ex am ples shown in Fig ure 12-2. In all cases, the de vice’s doc u men -ta tion and the cor re spond ing data sheets should pro vide the ap pro pri ate wir ingin for ma tion.

12.2 In ter facing with the HD44780The Hitachi 44780 con trol ler al lows par al lel in ter fac ing us ing 4- or 8-bit data paths. Inthe 4-bit mode, each data byte must be di vided into a high-order and a low-order nib ble and are trans mit ted se quen tially, the high nib ble first. In the 8-bit par al lel mode, eachdata byte is trans mit ted from the PIC to the con trol ler as a unit. The ad van tage of us ing the 4-bit mode is greater econ omy of I/O lines on the PIC side. The dis ad van tages areslightly more com pli cated pro gram ming and min i mally slower ex e cu tion speed. Ourfirst ex am ple and cir cuit uses the 8-bit data mode so as to avoid com pli ca tions. Once

LCD Hardware and Pro gramming 221

Page 243: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

the main pro cess ing rou tines are de vel oped, make the nec es sary mod i fi ca tions so asto make pos si ble the 4-bit data mode.

In ad di tion to the data trans mis sion mode, there are other cir cuit op tions to con -sider. Two con trol lines be tween the microcontroller and the HD44780-driven LCDare nec es sary in all cases: one to the RS line to se lect be tween data and in struc tionin put modes, and an other one to the E line to pro vide the pulse that ini ti ates thedata trans fer. The R/W con trol line, which se lects be tween the read and the writemode of the LCD con trol ler, can be con nected or grounded. If the R/W line is notcon nected to a microcontroller port, then the HD44780 op er ates only in the writedata mode and all read op er a tions are un avail able.

12.2.1 Busy Flag or Timed De lay Op tions

Be cause many ap pli ca tions do not read text data from con trol ler mem ory, thewrite-only mode is of ten an at trac tive op tion, es pe cially con sid er ing thatmicrocontroller I/O ports are of ten in short sup ply and that this op tion saves one portfor other du ties. How ever, there is a less ap par ent draw back to not be ing able to readLCD data, which is that the ap pli ca tion is not able to mon i tor the busy flag. This flag,which in di cates that the con trol ler has con cluded its op er a tion, is mapped to bit 7. Be -cause test ing the BF re quires read ing this bit, not con nect ing the R/W line has the ef -fect that ap pli ca tions can not use the busy flag and must rely on tim ing rou tines toen sure that each op er a tion com pletes be fore the next one be gins. The tim ing re quire -ments for each in struc tion are dis cussed in de tail later in this chap ter.

For the cir cuit de signer, to read or not to read con trol ler data is a de ci sion withsev eral trade-offs. Using time de lay rou tines to en sure that each con trol ler op er a -tion has con cluded is a vi a ble op tion that saves one in ter face line. On the otherhand, code that re lies on tim ing rou tines is ex ter nally de pend ent on the clocks andtimer hard ware. If code that re lies on tim ing rou tines is ported to an other cir cuitwith dif fer ent microcontroller, clocks, or timer hard ware, the de lays may changeand the rou tines could fail. Fur ther more, the use of de lay rou tines of ten is not ef fi -cient, as con trol ler op er a tions can ter mi nate be fore the timed de lay has ex pired.

On the other hand, code that reads the busy flag to de ter mine the ter mi na tion of a con trol ler op er a tion is not with out pit falls. If the con trol ler or the cir cuit fails, thenthe pro gram can hang up in an end less loop, wait ing for the busy flag to clear. To beab so lutely safe, the code would have to con tain an ex ter nal wait loop when test ingthe busy flag, so that if the ex ter nal loop ex pires, then the pro cess ing can as sumethat there is a hard ware prob lem and break out of the flag test loop. The pro gram -mer must de cide whether this safety mech a nism for read ing the busy flag is nec es -sary be cause its im ple men ta tion re quires a some what com pli cated ex cep tionre sponse.

In the code sam ples de vel oped in this chap ter, we im ple ment both ways of en sur -ing op er a tion com ple tion. The code also fur nishes a soft ware switch that al lows se -lect ing the pre ferred op tion.

222 Chap ter 12

Page 244: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

12.2.2 Con trast Con trolIn ad di tion to the con trol lines that re quire pro ces sor in ter face, the HD44780 con tainsother con trol lines. One such line is used for the LCD con trast. The con trast con trolline (usu ally la beled Vee) is con nected to pin num ber 3 (see Ta ble 12.1). The ac tual im -ple men ta tion of the con trast con trol func tion var ies ac cord ing to the man u fac turer. In gen eral, for an LCD with a nor mal tem per a ture range, the con trast con trol line iswired as shown in Fig ure 12-3.

Fig ure 12-3 Typ i cal Con trast Ad just ment Cir cuit.

12.2.3 Dis play Backlight

Some LCDs are equipped with an LED backlight so as to make the dis played char ac -ters more vis i ble. In dif fer ent LCDs, backlight is im ple mented in dif fer ent ways. Someman u fac tur ers wire the backlight di rectly to the LCD power sup ply, while oth ers pro -vide ad di tional pins that al low turn ing the backlight on or off in de pend ently of theLCD dis play. Backlit dis plays with four teen pins be long to the first type, while thosewith six teen pins have in de pend ent backlight con trol. If the backlight pins are ad ja -cent to the other dis play pins, then they are num bered 15 and 16. In this case, pin num -ber 15 is wired, through a cur rent lim it ing re sis tor, to the +5V source and pin 16 toground. Some times the cur rent-limiting re sis tor is built into the dis play. This in for ma -tion is avail able in the de vice’s data sheet.

Note that some four-line dis plays use pins 15 and 16 for other pur poses. In thesesys tems, backlight con trol, if avail able, is pro vided by sep a rate pins.

12.2.4 Dis play Mem ory Map ping

The Hitachi HD44780 is a mem ory-mapped sys tem in which char ac ters are dis playedby stor ing their ASCII codes in the cor re spond ing mem ory ad dress as so ci ated witheach digit-display area. The area of con trol ler RAM mapped to char ac ter-display mem -ory has a ca pac ity of eighty char ac ters. This area is known as dis play data RAM orDDRAM.

LCD Hardware and Pro gramming 223

HD44780

+5 V

10K Ohm

1

14

Page 245: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

224 Chap ter 12

In or der to save cir cuitry, the com mon lines of the con trol ler out puts to the liq uid crys tal dis play hard ware are mul ti plexed. In this con text, the duty ra tio of a sys tem is the num ber of mul ti plexed com mon lines. The most com mon duty ra tio is 1/16, al -though 1/8 and 1/11 are found in some sys tems. Be cause the duty ra tio mea sures the num ber of mul ti plexed lines, it also de ter mines the dis play map ping. For ex am ple,in a sin gle-line-by-six teen char ac ter dis play with a 1/16 duty ra tio the first eightchar ac ters are mapped to one set of con sec u tive mem ory ad dresses and the sec ondeight char ac ters to an other set of ad dresses. The rea son is that in ev ery dis play line, six teen com mon ac cess lines are mul ti plexed, in stead of eight. By the same to ken, atwo-line-by-six teen-char ac ter dis play with a 1/16 duty ra tio re quires six teen com -mon lines. In this case, the ad dress of the sec ond lines is not a con tin u a tion of thead dress of the first line, but is in an other ad dress set not con tig u ous to the first one.

For ex am ple, in a typ i cal two-line-by-six teen-char ac ter dis play, the ad dresses ofthe six teen char ac ters in the first line are from 0x00 to 0x0F, while the ad dresses ofthe char ac ters in the sec ond line are from 0x40 to 0x4F. Be cause there are eightymem ory lo ca tions in the con trol ler’s DDRAM, each line con tains stor age for a to talof forty char ac ters. The range of the en tire first line is from 0x00 to 0x27 (forty char -ac ters to tal) but of these, only 16 are ac tu ally dis played. The same ap plies to thesec ond line of 16 char ac ters. In this case, the stor age area is in the range 0x28 to0x4f, but only 16 char ac ters are dis played. In the sin gle-line-by-six teen-char ac terdis play men tioned first the ad dresses of the first eight char ac ters would be a setfrom 0x00 to 0x07 and the ad dresses of the sec ond eight char ac ters in the line arefrom 0x40 to 0x47. Ta ble 12.2 lists the mem ory ad dress map ping of some com monLCD con fig u ra tions.

Ta ble 12.2

7-bit DDRAM Ad dress Map ping for Com mon LCDs

CHARACTERS/ LINE CHARACTER FIRST IN NEXT IN LAST IN ROW NUMBER NUMBER GROUP GROUP GROUP

8/1 1 1 0x00 0x01 0x07 8/2 1 1 0x00 0x01 0x07

2 1 0x40 0x41 0x4716/1 1 1 0x00 0x01 0x07

1 9 0x40 0x41 0x4716/2 1 1 0x00 0x01 0x0f

2 1 0x40 0x41 0x4f20/2 1 1 0x00 0x01 0x13

2 1 0x40 0x41 0x5324/2 1 1 0x00 0x01 0x17

2 1 0x40 0x41 0x5716/4 1 1 0x00 0X01 0x0f

2 1 0x40 0x41 0x4f3 1 0x10 0x11 0x1f4 1 0x50 0x51 0x5f

20/4 1 1 0x00 0x01 0x132 1 0x40 0x41 0x533 1 0x14 0x15 0x274 1 0x54 0x55 0x67

Page 246: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Note that sys tems that ex ceed a to tal of 80 char ac ters re quire two or moreHD44780 con trol lers. Al though the in for ma tion pro vided in Ta ble 12.2 cor re spondsto the map ping in most LCDs, it is a good idea to con sult the data sheet of the spe -cific hard ware in or der to cor rob o rate the ad dress map ping in a par tic u lar de vice.

Ta ble 12.3 con tains the seven low-order bits of DDRAM ad dresses. HD44780 com -mands to set the DDRAM ad dress for read or write op er a tions re quire that thehigh-order bit (bit num ber 7) be set. There fore, to write to DDRAM mem ory ad dress0x07, code uses the value 0x87; and to write to DDRAM ad dress 0x43, code uses0xc3 as the in struc tion op er and.

12.3 HD44780 In struc tion Set The HD44780 in struc tion set in cludes op er a tors to ini tial ize the sys tem and set op er a -tional modes, clear the dis play, ma nip u late the cur sor, set, re set, and con trol au to -matic dis play ad dress shift, set and re set the in ter face pa ram e ters, poll the busy flag,and read and write to CGRAM and DDRAM mem ory.

12.3.1 In struc tion Set Over view

Pin num ber 4 in Ta ble 12.1 se lects two modes of op er a tion on the HD44780 con trol ler:in struc tion and data in put. When the in struc tion mode is en abled (RS pin is set low),the con trol ler re ceives com mands that set up the hard ware and de ter mine its con fig u -ra tion and mode of op er a tion. These com mands are part of the HD44780 in struc tionset shown in Ta ble 12.3.

Ta ble 12.3

HD44780 In struc tion Set

INSTRUCTION RS R/W B7 B6 B5 B4 B3 B2 B1 B0 TIME

Clear Dis play 0 0 0 0 0 0 0 0 0 1 1.64Re turn home 0 0 0 0 0 0 0 0 1 # 1.64En try mode set 0 0 0 0 0 0 0 1 I/D S 37Dis play/Cur sorON/OFF 0 0 0 0 0 0 1 D C B 37Cur sor/dis play shift 0 0 0 0 0 1 S/C R/L # # 37Func tion set 0 0 0 0 1 DL N F # # 37Set CGRAM ad dress 0 0 0 1 ----------- ad dress ----------------- 37Set DDRAM ad dress 0 0 1 ------------------ ad dress ------------------ 37Read busy flag andAd dress reg is ter 0 1 BF ---------------- ad dress ------------------ 0 Write data 1 0 --------------------------- data ------------------- 37Read data 0 1 --------------------------- data ------------------- 37Note: Bits la beled # have no ef fect.

Clear ing the Dis play

Clear ing the dis play fills the dis play with blanks by writ ing the code 0x20 into allDDRAM ad dresses. It also re turns the cur sor to the home po si tion (top-left dis playcor ner) and sets ad dress 0 in the DDRAM ad dress coun ter. Af ter this com mand ex e -cutes, the dis play dis ap pears and the cur sor goes to the left edge of the dis play.

LCD Hardware and Pro gramming 225

Page 247: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Re turn Home

Re turn home re turns the cur sor to home po si tion at the up per left po si tion of the firstchar ac ter line. It sets DDRAM ad dress 0 in the ad dress coun ter and sets the dis play toits de fault sta tus if it was shifted. DDRAM con tents re main un changed.

En try Mode Set

En try mode set sets the di rec tion of cur sor move ment and the dis play shift mode. If B1 (I/D) bit is set, cur sor han dling is set to the in cre ment mode; that is, left-to-right. If thisbit is clear, then cur sor move ment is set to the dec re ment mode, that is, right-to-left.

If B0 (S) bit is set, dis play shift is en abled. In the dis play shift mode, it ap pears as if the dis play moves in stead of the cur sor; oth er wise dis play shift is dis abled. Op er a -tions that read or write to CGRAM and op er a tions that read DDRAM do not shift thedis play.

Dis play and Cur sor ON/OFF

If B2 (D) bit is set, dis play is turned on. Oth er wise, it is turned off. When the dis play isturned off, data in DDRAM is not changed.

If B1 (C) bit is set, the cur sor is turned on. Oth er wise, it is turned off. Op er a tionsthat change the cur rent ad dress in the DDRAM Ad dress reg is ter, like those to au to -mat i cally in cre ment or dec re ment the ad dress, are not af fected by turn ing off thecur sor. The cur sor is dis played at the eighth line in the 5 times 8 char ac ter ma trix.

If B0 (B) bit is set, the char ac ter at the cur rent cur sor po si tion blinks. Oth er wise,the char ac ter does not blink. Note that char ac ter blink ing and cur sor are in de pend -ent op er a tions and that both can be set to work si mul ta neously.

Cur sor/Dis play Shift

Cur sor/dis play shift moves the cur sor or shifts the dis play ac cord ing to the se lectedmode. The op er a tion does not change the DDRAM con tent. Be cause the cur sor po si -tion al ways co in cides with the value in the Ad dress reg is ter, the in struc tion pro videssoft ware with a mech a nism for mak ing DDRAM cor rec tions or to re trieve dis play dataat spe cific DDRAM lo ca tions. Ta ble 12.4 lists the four avail able op tions:

Ta ble 12.4

Cur sor/Dis play Shift Op tions

BITS S/C R/L OPERATION

0 0 Cur sor po si tion is shifted left. Ad dress coun ter is dec re ment ed by one 0 1 Cur sor po si tion is shifted right. Ad dress coun ter is in cre mented by one 1 0 Cur sor and dis play are shifted left 1 1 Cur sor and dis play are shifted right

226 Chap ter 12

Page 248: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Func tion set

Func tion set sets the par al lel in ter face data length, the num ber of dis play lines, andthe char ac ter font. If B4 (DL) bit is set, then the in ter face is set to eight bits. Oth er wiseit is set to four bits. If B3 (N) bit is zero, the dis play is in i tial ized for 1/8 or 1/11 duty cy -cle. When the N bit is set, the dis play is set to 1/16 duty cy cle. Dis plays with mul ti plelines typ i cally use the 1/16 duty cy cle. The 1/16 duty cy cle on a one-line dis play ap -pears as if it were a two-line dis play, that is, the line con sists of two sep a rate ad dressgroups (see Ta ble 12.3).

If B2 (F) bit is set, then the dis play res o lu tion is 5 times 10 pix els. Oth er wise theres o lu tion is 5 times 8 pix els. This bit is not sig nif i cant when the 1/16 duty cy cle isse lected; that is, when the N bit is set.

The func tion set in struc tion should be is sued dur ing con trol ler ini tial iza tion. Noother in struc tion can be ex e cuted be fore this one, ex cept for chang ing the in ter facedata length.

Set CGRAM ad dress

Set CGRAM ad dress sets the CGRAM (char ac ter gen er a tor RAM) ad dress to whichdata is sent or re ceived af ter this op er a tion. The CGRAM ad dress is a 6-bit field in therange 0 to 64 dec i mal. Once a value is en tered in the CGRAM Ad dress reg is ter, data can be read or writ ten from CGRAM.

Set DDRAM ad dress

Set DDRAM ad dress sets the DDRAM (dis play data RAM) ad dress to which data issent or re ceived af ter this op er a tion. The DDRAM ad dress is a 7-bit field in the range 0to 127 dec i mal. Once a value is en tered in the DDRAM Ad dress reg is ter, data can beread or writ ten from CGRAM. DDRAM ad dress map ping is dis cussed in Sec tion 12.1.4.

Read busy flag and Ad dress reg is ter

Read busy flag and Ad dress reg is ter reads the busy flag to de ter mine if an in ter nal op -er a tion is in prog ress and reads the ad dress coun ter con tent. The value in the Ad dressreg is ter is re ported in bits 0 to 6. Bit 7 (BF) is the busy flag bit. This bit is read only. Thead dress coun ter is in cre mented or dec re ment ed by 1 (ac cord ing to the mode set) af terthe ex e cu tion of a data write or read in struc tion.

Write data

Write data writes eight data bits to CGRAM or DDRAM. Be fore data is writ ten to ei thercon trol ler RAM area, soft ware must first is sue a set DDRAM ad dress or set CGRAM ad -dress in struc tion (de scribed pre vi ously). These two in struc tions not only set the nextvalid ad dress in the Ad dress reg is ter, but also se lect ei ther CGRAM or DDRAM forwrit ing op er a tions. What other ac tions take place as data is writ ten to the con trol lerde pends on the set tings se lected by the en try mode set in struc tion. If the di rec tion ofcur sor move ment or data shift is in the in cre ment mode, then the data write op er a tionadds one to the value in the Ad dress reg is ter. If the cur sor move ment is en abled, thenthe cur sor is moved ac cord ingly af ter data write takes place. If the dis play shift modeis ac tive, then the dis played char ac ters are shifted ei ther right or left.

LCD Hardware and Pro gramming 227

Page 249: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Read data

Read data reads eight data bits to CGRAM or DDRAM. Be fore data is read from ei thercon trol ler RAM area, soft ware must first is sue a set DDRAM ad dress or set CGRAM ad -dress in struc tion. These in struc tions not only set the next valid ad dress in the Ad dress reg is ter, but also se lect ei ther CGRAM or DDRAM for writ ing op er a tions. Fail ing to set the cor re spond ing RAM area re sults in read ing in valid data.

What other ac tions take place as data is read from the con trol ler RAM de pendson the set tings se lected by the en try mode set in struc tion. If the di rec tion of cur sormove ment or data shift is in the in cre ment mode, then the data read op er a tion addsone to the value in the Ad dress reg is ter. How ever, dis play is not shifted by a read op -er a tion even if the dis play shift is ac tive.

The cur sor shift in struc tion has the ef fect of chang ing the con tent of the Ad dressreg is ter. So if a cur sor shift pre cedes a data read in struc tion, there is no need to re -set the ad dress by means of an ad dress set com mand.

12.3.2 16F84 8-Bit Data Mode Cir cuitThe first cir cuit pre sented in this chap ter is ex per i men tal. Its pur pose is to ex er ciseLCD dis play func tions in the sim plest forms; therefore, the cir cuit uses 8-bit par al leldata trans mis sion in ter fac ing with a 16F84 microcontroller. The cir cuit is shown inFig ure 12-4.

Fig ure 12-4 16F84 to LCD 8-Bit Mode Cir cuit.

228 Chap ter 12

16F84

HD44780

HD44780 pin out1 GND2 DC +5v3 Contrast adjust4 RS (register select)5 R/W (read/write select)6 E (signal enable)7-14 Data bits 0 to 7

4 MHzOsc

100 Ohms

RESET

+5 V

+5 V

BF

+5 V

E R/W RS

10 K

RA2 RA3RA4/T0Tkl MCLR Vss RB0/INT RB1 RB2 RB3

1 2 3 4 5 6 7 8 9

18 17 16 15 14 13 12 11 10

RA1 RA0 OSC1 OSC2 Vdd RB7 RB6 RB5 RB4

1

14

E

RS

R/W

Page 250: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

In the cir cuit of Fig ure 12-4, three con trol lines are wired be tween themicrocontroller and the LCD. The line des ig na tions are shown in side ovals. The R/W line is not nec es sary, be cause it is pos si ble to de vise a sys tem that does not readLCD data. In the di a gram the R/W line is in cluded be cause it al lows read ing the busy flag in syn chro niz ing op er a tions. Ta ble 12.5 shows the con trol and data con nec tions for the cir cuit in Fig ure 12-4.

Ta ble 12.5

Con nec tions for 16F84/LCD 8-bit Data Mode Cir cuit

16F84 LCD LINEPIN PORTBIT PIN NAME FUNCTION

1 A2 4 RS Se lect in struc tion/ data reg is ter

2 A3 5 R/W Read/write se lect18 A1 6 E En able sig nal13 B7 14 be fore Busy flag6-13 B0-B7 7-14 Data Data lines

12.4 LCD Pro grammingLCD pro gram ming is usu ally de vice spe cific. Be fore at tempt ing to write code, the pro -gram mer should be come fa mil iar with the cir cuit wir ing di a gram, the setup pa ram e -ters, and the spe cific hard ware re quire ments. It is risky to make as sump tions that aspe cific de vice con forms ex actly to the HD44780 in ter face be cause of ten a style sheetcon tains spec i fi ca tions that are not in strict con for mance with the stan dard. In ad di -tion to the PIC setup and ini tial iza tion func tions, code to dis play a sim ple text mes -sage on the LCD screen con sists of the fol low ing dis play-related func tions:

1. De fine the re quired con stants, vari ables, and buff ers.

2. Set up and ini tial ize ports used by the LCD.

3. Ini tial ize the LCD to cir cuit and soft ware spec i fi ca tions.

4. Store text in PIC text buffer.

5. Se lect DDRAM start ad dress on LCD.

6. Dis play text by trans fer ring char ac ters in PIC text buffer to LCD DDRAM.

If the LCD dis play con sists of mul ti ple lines, then the pre vi ous steps 4, 5, and 6are re peated for each line. LCD ini tial iza tion and dis play op er a tions vary ac cord ingto whether the in ter face is 4- or 8-bits and whether the code uses de lay loops orbusy flag mon i tor ing to syn chro nize op er a tions. All of these vari a tions are con sid -ered in the ex am ples in this chap ter.

12.4.1 De fining Con stants and Vari ables

In any pro gram, de fin ing and doc u ment ing con stants and fixed pa ram e ters should bedone cen trally, rather than hard-coded through the code. Cen tral izing the el e mentsthat are vari able un der dif fer ent cir cum stances makes it pos si ble to adapt code to cir -cuit and hard ware changes.

LCD Hardware and Pro gramming 229

Page 251: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Two com mon ways are avail able for de fin ing con stants: the C-like #de fine di rec -tive and the equ (equate) di rec tive. In most cases, it is a mat ter of per sonal pref er -ence which is used, but a gen eral guide line is to use the #de fine state ment to cre ate lit eral con stants; that is, con stants that are not as so ci ated with pro gram reg is ters or vari ables. The equ di rec tive is then used to de fine reg is ters, flags, and lo cal vari -ables.

Ac cord ing to this scheme, an LCD dis play driver pro gram could use #de finestate ments to cre ate lit er als that are re lated to the wir ing di a gram or the spe cificLCD val ues ob tained form the data sheet, such as the DDRAM ad dresses for eachdis play line, as in the fol low ing code frag ment:

;=====================================================

; con stant def i ni tions

; for PIC-to-LCD pin wir ing and LCD line ad dresses

;=====================================================

#de fine E_line 1 ;|

#de fine RS_line 2 ;| => from wir ing di a gram

#de fine RW_line 3 ;|

; LCD line ad dresses (from LCD data sheet)

#de fine LCD_1 0x80 ; First LCD line con stant

#de fine LCD_2 0xc0 ; Sec ond LCD line con stant

By the same to ken, the val ues as so ci ated with PIC reg is ter ad dresses and bit flags are de fined us ing equ, as fol lows:

;=====================================================

; PIC reg is ter equates

;=====================================================

porta equ 0x05

portb equ 0x06

fsr equ 0x04

sta tus equ 0x03

indf equ 0x00

z equ 2

One ad van tage of this scheme is that con stants are eas ier to lo cate, be cause they aregrouped by de vice. Those for the LCD are in the #de fine di rec tives area and those forthe PIC hard ware in an area of equ di rec tives.

There are also draw backs to this ap proach, as sym bols cre ated in #de fine di rec -tives are not avail able for view ing in the MPLAB debuggers. How ever, if the use ofthe #de fine di rec tive is restriced to lit eral con stants, then their view ing dur ing a de -bug ging ses sion is not es sen tial.

MPLAB also sup ports the con stant di rec tive for cre at ing a con stant sym bol. Itsuse is iden ti cal to the equ di rec tive but the lat ter is more com monly found in code.

230 Chap ter 12

Page 252: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Using MPLAB Data Di rec tives

Of ten a pro gram needs to de fine a block of se quen tial sym bols and as sign to each one a cor re spond ing name. In the PIC 16f84, the ad dress space al lo cated to gen eral-pur pose reg is ters al lo cated by the user is of 68 bytes, start ing at ad dress 0x0c. One pos si bleway of al lo cat ing user-defined reg is ters is to use the equ di rec tive to as sign ad dressesin the PIC SRAM space:

Var1 equ 0x0c

Var2 equ 0x0d

Var3 equ 0x0e

Buf1 equ 0x0f ; 10-byte buffer space

Var4 equ 0x19 ; Next vari able

Al though this method is func tional, it de pends on the pro gram mer cal cu lat ing the lo ca tion of each vari able in the PIC’s avail able SRAM space. Al ter na tively, MPLAPpro vides a cblock di rec tive that al lows de fin ing a group of con sec u tive se quen tialsym bols while re fer ring only to the ad dress of the first el e ment in the group. If noad dress is en tered in cblock, then the as sem bler as signs the ad dress. This ad dressis one higher than the fi nal ad dress in the pre vi ous cblock. Each cblock ends withthe endc di rec tive. The fol low ing code frag ment show ing the use of the cblock di -rec tive is from one of the sam ple pro grams for this chap ter:

;=====================================================

; vari ables in PIC RAM

;=====================================================

; Re serve 16 bytes for string buffer

cblock 0x0c

strData

endc

; Leave 16 bytes and con tinue with lo cal vari ables

cblock 0x1d ; Start of block

count1 ; Coun ter # 1

count2 ; Coun ter # 2

count3 ; Coun ter # 3

pic_ad ; Stor age for start of text area

; (la beled strData) in PIC RAM

J ; coun ter J

K ; coun ter K

in dex ; In dex into text ta ble

endc

Note in the pre ced ing code frag ment that the al lo ca tion for the 16-byte bufferspace named strData is en sured by en ter ing the cor re spond ing start ad dress in thesec ond cblock. The PIC microcontrollers do not con tain a di rec tive for re serv ingmem ory ar eas in side cblock, al though the res di rec tive can be used to re servemem ory for in di vid ual vari ables.

LCD Hardware and Pro gramming 231

Page 253: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

12.4.2 LCD Ini tial iza tionLCD ini tial iza tion de pends on the spe cific hard ware in use and on the cir cuit wir ing.In for ma tion about the spe cific LCD can be ob tained from the de vice’s data sheet.Some times, the data sheet in cludes ex am ples of ini tial iza tion val ues for dif fer ent con -di tions and even code list ings. The in for ma tion is usu ally suf fi cient to en sure cor rectini tial iza tion.

A word of warn ing: The pop u lar LCD lit er a ture avail able on line of ten con tainsini tial iza tion “myths” for spe cific com po nents re quir ing that a cer tain mys tery codebe used for no doc u mented rea son, or that a cer tain func tion be re peated a givennum ber of times. The pro gram mer should make sure that the code is ra tio nal andthat ev ery op er a tion is ac tu ally re quired and doc u mented.

Be fore the LCD ini tial iza tion com mands are used, it is nec es sary to set the com -mu ni ca tions lines cor rectly. The E line should be low, the RS line should be low forcom mand, and the R/W line (if con nected) should be low for write mode. Af ter thelines are set ac cord ingly, there should be a 125-ms de lay. Note that, at this point, theLCD busy flag is not yet re li able. The fol low ing code frag ment shows the pro cess -ing:

bcf porta,E_line ; E line lowbcf porta,RS_line ; RS line low for com mandbcf porta,RW_line ; Write modecall de lay_125 ; de lay 125 mi cro sec onds

The pro ce dure de lay_125 in the pre vi ous code frag ment is de scribed later in this chap -ter.

Func tion Set Com mand

Func tion set is the first ini tial iza tion com mand sent to the LCD. The com mand de ter -mines whether the dis play font con sists of 5 times 10 or 5 times 7 pix els. The lat ter isby far the more com mon. It de ter mines the duty cy cle, which is typ i cally 1/8 or 1/11 forsin gle-line dis plays and 1/16 for mul ti ple lines. The in ter face width is also de ter minedin the FUNC TION SET com mand. It is 4 bits or 8 bits. The fol low ing code frag mentshows the com mented code for the Func tion Set com mand:

;***********************|; Func tion Set |;***********************|

movlw 0x38 ; 0 0 1 1 1 0 0 0 (FUNCTION SET); | | | |__ font se lect:; | | | 1 = 5x10 in 1/8 or 1/11; | | | 0 = 1/16 dc; | | |___ Duty cy cle se lect; | | 0 = 1/8 or 1/11; | | 1 = 1/16; | |___ In ter face width; | 0 = 4 bits; | 1 = 8 bits

232 Chap ter 12

Page 254: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; |___ FUNCTION SET COMMAND movwf portbcall pulseE ;pulse E line to force LCD com mand

In the pre ced ing code frag ment, the LCD is in i tial ized to mul ti ple lines, 5 times 7font, and 8-bit in ter face, as in the pro gram LCDTest1 found in this book’s on linesoft ware pack age.

The pro ce dure named pulseE sets the E line bit off and on to force com mand rec -og ni tion by the LCD. The pro ce dure is listed and de scribed later in this chap ter.

Dis play Off

Some ini tial iza tion rou tines in LCD doc u men ta tion and data sheets re quire that thedis play be turned off fol low ing the Func tion Set com mand. If so, the Dis play Off com -mand is ex e cuted as fol lows:

;***********************|; Dis play Off |;***********************|

movlw 0x08 ; 0 0 0 0 1 0 0 0 (DISPLAY ON/OFF); | | | |___ Blink char ac ter at; | | | | Cursor; | | | 1 = on, 0 = off; | | |___ Cursor on/off; | | 1 = on, 0 = off; | |____ Dis play on/off; | 1 = on, 0 = off; |____ COMMAND BIT

movwf portbcall pulseE ; pulse E line to force LCD com mand

Dis play and Cur sor On

Whether or not the dis play is turned off, it must be turned on first. Also, code must se -lect if the cur sor is on or off, and whether the char ac ter at the cur sor po si tion is toblink. The fol low ing com mand sets the cur sor and the dis play on, and the char ac terblink off:

;***********************|; Dis play and Cur sor On |;***********************|

movlw 0x0e ; 0 0 0 0 1 1 1 0 (DISPLAY ON/OFF); | | | |___ Blink char ac ter at; | | | | cur sor; | | | 1 = on, 0 = off; | | |___ Cursor on/off; | | 1 = on, 0 = off; | |____ Dis play on/off; | 1 = on, 0 = off

LCD Hardware and Pro gramming 233

Page 255: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; |____ COMMAND BITmovwf portbcall pulseE ; pulse E line to force LCD com mand

Set En try Mode

The En try Mode command sets the di rec tion of cur sor move ment or dis play shiftmode. Normally, the dis play is set to the in cre ment mode when writ ing in West ern Eu -ro pean lan guages. The En try Mode com mand con trols dis play shift. If en abled, thedis played char ac ters ap pear to scroll. This mode is used to sim u late an elec tronic bill -board ef fect by stor ing more than one line of char ac ters in DDRAM and the then scroll -ing the char ac ters left-to-right. The fol low ing code sets en try mode to in cre ment mode and no shift:

;***********************|; Set En try Mode |;***********************|

movlw 0x06 ; 0 0 0 0 0 1 1 0 (ENTRY MODE SET); | | |___ dis play shift; | | 1 = shift; | | 0 = no shift; | |____ cur sor in cre ment; | mode; | 1 = left-to-right; | 0 = right-to-left; |___ COMMAND BIT

movwf portb ;00000110call pulseE

Op er a tions that read or write to CGRAM and op er a tions that read DDRAM do notshift the dis play.

Cur sor and Dis play Shift

These com mands de ter mine whether the cur sor or the dis play shift ac cord ing to these lected mode. Shifting the cur sor or the dis play pro vides a soft ware mech a nism formak ing DDRAM cor rec tions or for re triev ing dis play data at spe cific DDRAM lo ca -tions. The four avail able op tions ap pear in Ta ble 12.4 pre vi ously in this chap ter. Thefol low ing in struc tions set the cur sor to shift right and dis able dis play shift:

;***********************|; Cur sor/Dis play Shift |;***********************|

movlw 0x14 ; 0 0 0 1 0 1 0 0 (CURSOR/DISPLAY; | | | | | SHIFT)

; | | | |_|___ don’t care; | |_|__ cur sor/dis play shift; | 00 = cur sor shift left; | 01 = cur sor shift right; | 10 = cur sor and dis play

234 Chap ter 12

Page 256: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; | shifted left; | 11 = cur sor and dis play; | shifted right; |___ COMMAND BIT

movwf portb ;0001 1111call pulseE

Clear Dis play

The fi nal ini tial iza tion com mand is usu ally one to clear the dis play. It is en tered as fol -lows:

;***********************|; Clear Dis play |;***********************|

movlw 0x01 ; 0 0 0 0 0 0 0 1 (CLEAR DISPLAY); |___ COMMAND BIT

movwf portb ;0000 0001call pulseEcall de lay_5 ;de lay 5 mil li sec onds af ter init

Note that the last com mand is fol lowed by a 5ms de lay. The de lay pro ce dure de lay_5 islisted and de scribed later in this chap ter.

12.4.3 Aux il iary Op er a tionsSev eral sup port rou tines are re quired for ef fec tive text dis play in LCD de vices. Thesein clude time de lay rou tines for timed ac cess, a rou tine to pulse the E line in or der toforce the LCD to ex e cute a com mand or to read or write text data, rou tines to read thebusy flag when this is the method used for pro ces sor/LCD syn chro ni za tion, and rou -tines to merge data with port bits so as to pre serve the sta tus of port lines not be ing ad -dressed by code.

Time De lay Rou tine

There are sev eral ways of pro duc ing time de lays in PIC microcontrollers. A book byDa vid Benson is de voted al most en tirely to tim ing and count ing rou tines. The pres entcon cern is quite sim ple: to de velop a soft ware rou tine that en sures the time de lay thatmust take place in LCD pro gram ming, as shown in Ta ble 12.3.

One mech a nism for pro duc ing time de lays in PIC pro gram ming is by means of the Timer0 mod ule, a built-in 8-bit timer coun ter. Once en abled, Port-A pin 4, la beledthe TOCKI bit and as so ci ated with file reg is ter 01 (TMR0), is used to time pro ces sorop er a tions. In the par tic u lar case of LCD tim ing rou tines, us ing the Timer0 mod uleseems some what of an over kill, in ad di tion to the fact that it re quires the use of aPort-A line, which is of ten re quired for other pur poses.

Al ter na tively, tim ing rou tines that serve the pur pose at hand can be de vel oped us -ing sim ple de lay loops. In this case, no port line is sac ri ficed and cod ing is con sid er -ably sim pli fied. These rou tines are ge ner i cally la beled soft ware tim ers, in con trastto the hard ware tim ers that de pend on the PIC timer/coun ter de vice de scribed pre -

LCD Hardware and Pro gramming 235

Page 257: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

vi ously. Soft ware tim ers pro vide the nec es sary de lay by means of pro gram loops;that is, by wast ing time. The length of de lay pro vided by the rou tine de pends on theex e cu tion time of each in struc tion and on the num ber of re peated in struc tions.

In struc tions on the PIC 16f84 con sume four clock cy cles. If the pro ces sor clock is run ning at 4 MHz, then one fourth of 4 MHz is the ex e cu tion time for each in struc -tion, which is 1 µs. So if each in struc tion re quires 1 µs, re peat ing 1,000 in struc tionspro duces a de lay of 1 ms. The fol low ing rou tines pro vide con ve nient de lays for LCDin ter fac ing:

;=======================; Pro ce dure to de lay; 125 mi cro sec onds;=======================de lay_125mics:

movlw D’42’ ; Re peat 42 ma chine cy clesmovwf count1 ; Store value in coun ter

re peat:decfsz count1,f ; Dec re ment coun ter (1 cy cle)goto re peat ; Con tinue if not 0 (2 cy cles)

; 42 * 3 = 126re turn ; End of de lay

;=======================; Pro ce dure to de lay; 5 mil li sec onds;=======================de lay_5ms:

movlw D’41’ ; Coun ter = 41movwf count2 ; Store in vari able

de lay:call de lay_125mics ; De lay 41 mi cro sec ondsdecfsz count2,f ; 41 times 125 = 5125 ms

; or ap prox i mately 5 msgoto de layre turn ; End of de lay

Actually, the de lay loop of the pro ce dure named de lay_5ms is not ex actly theprod uct of 41 it er a tions times 125 µs, be cause the in struc tions to dec re ment thecoun ter and the goto to the la bel de lay are also in side the loop. Three in struc tioncy cles must be added to those con sumed by the de lay_125mics pro ce dure. This re -sults in a to tal of 41 * 3 or 123 in struc tion cy cles that must be added to the 5,125 con -sumed by de lay_125mics. In fact, there are sev eral other mi nor de lays by thein struc tions to ini tial ize the coun ters that are not in cluded in the cal cu la tion. In re -al ity, the de lay loops re quired for LCD in ter fac ing need not be ex act, as long as theyare not shorter than the rec om mended min ima.

For cal cu lat ing soft ware de lays in the 16f84, the in struc tion ex e cu tion time is de -ter mined by an ex ter nal clock ei ther in the form of an os cil la tor crys tal, a res o na tor, or an RC os cil la tor fur nished in the cir cuit. The PIC 16f84A is avail able in var i ous

236 Chap ter 12

Page 258: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

pro ces sor speeds, from 4 MHz to 20 MHz. These speeds de scribe the max i mum ca -pac ity of the PIC hard ware. The ac tual in struc tion speed is de ter mined by the clock -ing de vice, so a 20-MHz 16f84A us ing a 4-MHz os cil la tor ef fec tively runs at 4 MHz.

Pulsing the E Line

The LCD hard ware does not rec og nize data as it is placed in the in put lines. When thevar i ous con trol and data pins of the LCD are con nected to ports in the PIC and data isplaced in the port bits, no ac tion takes place in the LCD con trol ler. In or der for the con -trol ler to re spond to com mands or to per form read or write op er a tions, it must be ac ti -vated by pul sat ing (or strobing) the E line. The puls ing or strobing mech a nismre quires that the E line be kept low and then raised mo men tarily. The LCD checks thestate of its lines on the ris ing edge of the E line. Once the com mand has com pleted, theE line is brought low again. The fol low ing code frag ment pulses the E line in the man -ner de scribed:

;========================; pulse E line ;========================pulseE

bsf porta,E_line ; pulse E linebcf porta,E_linecall de lay_125mics ; de lay 125 mi cro sec ondsreturn

Note that the listed rou tine in cludes a 125 µs de lay fol low ing the puls ing op er a -tion. This de lay is not part of the pulse func tion but is re quired by most LCD hard -ware. Some pulse func tions in the pop u lar PIC lit er a ture in clude a no op er a tionopcode (nop) be tween the com mands to set and clear the E line. In most cases thisshort de lay does not hurt, but some LCDs re quire a min i mum time lapse dur ing thepulse and will not func tion cor rectly if the nop is in serted in the code.

Read ing the Busy Flag

Syn chro ni za tion be tween LCD com mands and be tween data ac cess op er a tions isbased on time de lay loops or on read ing the LCD busy flag. The busy flag, which is inthe same pin as the bit 7 data line, is read clear when the LCD is ready to re ceive thenext com mand, read, or write op er a tion, and is set if the de vice is not ready. By read -ing the state of the busy flag, code can ac com plish more ef fec tive syn chro ni za tionthan with time de lay loops. The sam ple pro gram named LCDTest2, in this book’s on -line soft ware pack age, per forms LCD dis play us ing the busy flag method. The fol low -ing pro ce dure shows busy flag syn chro ni za tion:

;========================; busy flag test rou tine;========================; Pro ce dure to test the HD44780 busy flag; Ex e cu tion re turns when flag is clearbusyTest:

movlw b’11111111’ ; All lines to in put tris portb ; in port B

LCD Hardware and Pro gramming 237

Page 259: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

bcf porta,RS_line ; RS line low for con trolbsf porta,RW_line ; Read modebsf porta,E_line ; E line highmovf portb,w ; Read port B into W

; Port B bit 7 is busy flagbcf porta,E_line ; E line lowandlw 0x80 ; Test bit 7, high is busybtfss sta tus,z ; Test zero bit in STATUSgoto busyTest ; Re peat if set

; At this point busy flag is clear; Re set R/W line and port B to out put

bcf porta,RW_line ; Clear R/W linemovlw b’00000000’ ; All lines to out put tris portb ; in port Bre turn

Note that test ing the busy flag re quires set ting the LCD to read mode, which inturn re quires im ple ment ing a con nec tion be tween a PIC port and the R/W line; alsothat the listed pro ce dure con tains no safety mech a nism for de tect ing a hard ware er -ror con di tion in which the busy flag never clears. If such were the case, the pro gram would hang in a for ever loop. To de tect and re cover from this er ror, the rou tinewould have to in clude an ex ter nal tim ing loop or some other means of re cov er ing apos si ble hard ware er ror.

Bit Merging Op er a tions

Of ten, PIC/LCD cir cuits do not use all the lines in an in di vid ual port. In this case, therou tines that ma nip u late PIC/LCD port ac cess should not change the set tings of otherport bits. This sit u a tion is not ex clu sive to LCD in ter fac ing; the dis cus sion that fol lows has many other ap pli ca tions in PIC pro gram ming.

A pro cess ing rou tine can change one or more port lines with out af fect ing the re -main ing ones. For ex am ple, an ap pli ca tion that uses a 4-bit in ter face be tween thePIC and the LCD typ i cally leaves four un used lines in the ac cess port, or uses someof these lines for in ter face con nec tions. In this case, the pro gram ming prob lem canbe de scribed as merg ing bits of the data byte to be writ ten to the port and some ex -ist ing port bits. One op er and is the ac cess port value, and the other one is the newvalue to write to this port. If the op er a tion at hand uses the four high-order port bits, then its four low-order bits must be pre served. The logic re quired is sim ple: AND the cor re spond ing operands with masks that clear the un needed bits and pre serve thesig nif i cant ones, then OR the two operands. The fol low ing pro ce dure shows the re -quired pro cess ing:

;=================; merge bits;=================; Rou tine to merge the 4 high-order bits of the; value to send with the con tents of port B; so as to pre serve the 4 low-bits in port B; Logic:

238 Chap ter 12

Page 260: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; AND value with 1111 0000 mask; AND port B with 0000 1111 mask; At this point low nib ble in value and high; nib ble in port B are al 0 bits:; value = vvvv 0000; port B = 0000 bbbb; OR value and port B re sult ing in:; vvvv bbbb ; ON ENTRY:; w con tain value bits; ON EXIT:; w con tains merged bitsmerge4:

andlw b’11110000’ ; ANDing with 0 clears the; bit. ANDing with 1 pre serves; the orig i nal value

movwf store2 ; Save re sult in vari ablemovf portb,w ; port B to w reg is terandlw b’00001111’ ; Clear high nib ble in port b

; and pre serve low nib bleiorwf store2,w ; OR two operands in wre turn

Note that this par tic u lar ex am ple re fers to merg ing two op er and nib bles. Thecode can be adapted to merge other size bit-fields by mod i fy ing the cor re spond ingmasks. For ex am ple, the fol low ing rou tine merges the high-order bit of one op er and with the seven low-order bits of the sec ond one:

; Rou tine to merge the high-order bit of the first op er and with; the seven low-order bits of the sec ond op er and; ON ENTRY:; w con tains value bits of first op er and; port b is the sec ond op er andmerge1:

andlw b’10000000’ ; ANDing with 0 clears the; bit. ANDing with 1 pre serves; the orig i nal value

movwf store2 ; Save re sult in vari ablemovf portb,w ; port B to w reg is terandlw b’01111111’ ; Clear high-order bit in

; port b and pre serve the; seven low or der bits

iorwf store2,w ; OR two operands in wre turn

Pop u lar PIC lit er a ture de scribes rou tines to merge bit-fields by as sum ing cer taincon di tions in the des ti na tion op er and and then test ing the first op er and bit to de ter -mine if the as sumed con di tion should be pre served or changed. This type of op er a -tion is some times called “bit flip ping,” for ex am ple:

LCD Hardware and Pro gramming 239

Page 261: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

flipBit7:; Code frag ment to test the high-order bit in the vari able named; oprnd1 and pre serve its sta tus in the reg is ter vari able portb

bcf portb,7 ; As sume oprnd1 bit is re setbtfsc oprnd1,7 ; Test op er and bit and skip if

; clear (as sump tion valid)bsf portb,7 ; Set bit if nec es saryre turn

The logic in bit-flip ping rou tines con tains one crit i cal flaw: If the as sumed con di -tion is false then the sec ond op er and is changed im prop erly, even if for only a fewmi cro sec onds. How ever, the in cor rect value can pro duce er rors in ex e cu tion if it isused by an other de vice dur ing this pe riod. Be cause there is no such ob jec tion to themerge rou tines based on mask ing, the pro gram mer should al ways pre fer them.

12.4.4 Text Data Stor age and Dis playText dis play op er a tions re quire some way of gen er at ing the ASCII char ac ters that areto be stored in DDRAM mem ory. Al though the PIC As sem bler con tains sev eral op er a -tors to gen er ate ASCII data in pro gram mem ory, there is no con ve nient way of stor inga string in the gen eral-pur pose reg is ter area. Even if this was pos si ble, SRAM is typ i -cally in short sup ply and text strings gob ble up con sid er able data space.

Sev eral pos si ble ap proaches are avail able. The most suit able one de pends on theto tal string length to be gen er ated or stored, whether the strings are re used in thecode, and other pro gram-related cir cum stances. In this sense, short text-strings canbe pro duced char ac ter-by-character and sent se quen tially to DDRAM mem ory byplac ing the char ac ters in the cor re spond ing port and puls ing the E line.

The fol low ing code frag ment con sec u tively dis plays the char ac ters in the word“Hello.” Code as sumes that the com mand to set the Ad dress reg is ter has been en -tered pre vi ously:

; Gen er ate char ac ters and send di rectly to DDRAMmovlw ‘H’ ; ASCII for H in wmovwf portb ; Store code in port Bcall pulseE ; Pulse E linemovlw ‘e’ ; Con tinuesmovwf portbcall pulseEmovlw ‘l’movwf portbcall pulseEmovlw ‘l’movwf portbcall pulseEmovlw ‘o’movwf portbcall pulseEcall de lay_5

240 Chap ter 12

Page 262: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Note in the pre ced ing frag ment that the code as sumes that the LCD has been in i -tial ized to au to mat i cally in cre ment the Ad dress reg is ter left-to-right. For this rea -son, the Ad dress reg is ter is bumped to the next ad dress with each port ac cess.

Gen er ating and Storing a Text String

An al ter na tive ap proach suit able for gen er at ing and dis play ing lon ger strings con sistsof stor ing the string data in a lo cal vari able (some times called a buffer) and then trans -fer ring the char ac ters, one by one, from the buffer to DDRAM. This kind of pro cess inghas the ad van tage of al low ing the re use of the same string and the dis ad van tage of us -ing up scarce data mem ory. The logic for one pos si ble rou tine con sists of first gen er at -ing and stor ing in PIC RAM the char ac ter string, then re triev ing the char ac ters fromthe PIC RAM buffer and dis play ing them. The char ac ter gen er a tion and stor age logic is shown in Fig ure 12-5.

Fig ure 12-5 Flowchart for String Gen er a tion Logic.

The pro cess ing is dem on strated in the fol low ing pro ce dure.

;===============================; first text string pro ce dure;===============================storeMN:; Pro ce dure to store in PIC RAM buffer the mes sage; con tained in the code area la beled msg1; ON ENTRY:; vari able pic_ad holds ad dress of text buffer; in PIC RAM

LCD Hardware and Pro gramming 241

START

ENDYES

NO

Buffer pointer = 0

Get character usinggenerator

Store character in bufferBump buffer pointer

Character = 0?

Page 263: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; w reg is ter holds off set into stor age area; msg1 is rou tine that re turns the string char ac ters; and a zero ter mi na tor; in dex is lo cal vari able that holds off set into; text ta ble. This vari able is also used for; tem po rary stor age of off set into buffer ; ON EXIT:; Text mes sage stored in buffer;; Store off set into text buffer (passed in the w reg is ter); in tem po rary vari able

movwf in dex ; Store w in in dex; Store base ad dress of text buffer in fsr

movf pic_ad,w ; first dis play RAM ad dress to Waddwf in dex,w ; Add off set to ad dressmovwf fsr ; W to FSR

; Ini tial ize in dex for text string ac cessmovlw 0 ; Start at 0movwf in dex ; Store in dex in vari able

; w still = 0get_msg_char:

call msg1 ; Get char ac ter from ta ble; Test for zero ter mi na tor

andlw 0x0ffbtfsc sta tus,z ; Test zero flaggoto endstr1 ; End of string

; ASSERT: valid string char ac ter in w; store char ac ter in text buffer (by fsr)

movwf indf ; store in buffer by fsrincf fsr,f ; in cre ment buffer pointer

; Re store ta ble char ac ter coun ter from vari ablemovf in dex,w ; Get value into waddlw 1 ; Bump to next char ac termovwf in dex ; Store ta ble in dex in vari ablegoto get_msg_char ; Con tinue

endstr1:re turn

; Rou tine for re turn ing mes sage stored in pro gram areamsg1:

addwf PCL,f ; Ac cess ta bleretlw ‘M’retlw ‘i’retlw ‘n’retlw ‘n’retlw ‘e’retlw ‘s’retlw ‘o’retlw ‘t’

242 Chap ter 12

Page 264: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

retlw ‘a’retlw 0 ; ter mi na tor char ac ter

The aux il iary pro ce dure named msg1, listed in the pre ced ing code frag ment, per -forms the char ac ter-generator func tion by pro duc ing each of the ASCII char ac tersin the mes sage string. Be cause a retlw in struc tion is nec es sary for each char ac ter,one in struc tion space in pro gram mem ory is used for each char ac ter gen er ated, plus a fi nal bi nary zero for the string ter mi na tor.

Dis playing the Text String

Once the string is stored in a lo cal buffer, it is dis played by mov ing each ASCII codefrom the buffer into LCD DDRAM. Here again, we as sume that the LCD has pre vi ouslybeen set to the auto in cre ment mode and that the Ad dress reg is ter has been prop erlyin i tial ized with the cor re spond ing DDRAM ad dress. The fol low ing pro ce dure dem on -strates ini tial iza tion of the DDRAM Ad dress reg is ter to the value de fined in the con -stant named LCD_1:

;========================; Set Ad dress reg is ter; to LCD line 1;========================; ON ENTRY:; Ad dress of LCD line 1 in con stant LCD_1 line1:

bcf porta,E_line ; E line lowbcf porta,RS_line ; RS line low, set up for

; con trolcall de lay_125 ; de lay 125 mi cro sec onds

; Set to sec ond dis play lineMovlw LCD_1 ; Ad dress and com mand bitmovwf portbcall pulseE ; Pulse and de lay

; Set RS line for databsf porta,RS_line ; Set up for datacall de lay_125mics ; De layre turn

Once the Ad dress reg is ter has been set up, the dis play op er a tion con sists oftrans fer ring char ac ters from the PIC RAM buffer into LCD DDRAM. The fol low ingpro ce dure can be used for this:

;=============================; LCD dis play pro ce dure;=============================; Sends 16 char ac ters from PIC buffer, with ad dress stored; in vari able pic_ad, to LCD line pre vi ously se lecteddisplay16:; Set up for data

bcf porta,E_line ; E line low

LCD Hardware and Pro gramming 243

Page 265: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

bsf porta,RS_line ; RS line low for con trol

call de lay_125 ; De lay

; Set up coun ter for 16 char ac ters

movlw D’16’ ; Coun ter = 16

movwf count3

; Get dis play ad dress from lo cal vari able pic_ad

movf pic_ad,w ; First dis play RAM ad dress to W

movwf fsr ; W to FSR

getchar:

movf indf,w ; get char ac ter from dis play RAM

; lo ca tion pointed to by file se lect

; reg is ter

movwf portb

call pulseE ;send data to dis play

; Test for 16 char ac ters dis played

decfsz count3,f ; Dec re ment coun ter

goto nextchar ; Skipped if done

re turn

nextchar:

incf fsr,f ; Bump pointer

goto getchar

Note that the pro ce dure display16, pre vi ously listed, as sumes that the ad dress ofthe lo cal buffer is stored in a vari able called pic_ad. This al lows re us ing the pro ce -dure to dis play text stored at other lo ca tions in PIC RAM.

The pre vi ously listed pro ce dures dem on strate just one of many pos si ble vari a -tions on this tech nique. An other ap proach is to store the char ac ters di rectly inDDRAM mem ory as they are pro duced by the mes sage-returning rou tine, thus avoid -ing the dis play pro ce dure en tirely. In this last case, the pro gram ming saves somedata mem ory space at the ex pense of hav ing to gen er ate the mes sage char ac terseach time they are needed. The most suit able ap proach de pends on the ap pli ca tion.

12.4.5 Data Com pres sion Tech niquesCir cuits based on the par al lel data trans fer of eight data bits re quire eight de voted port lines. As suming that three other lines are re quired for LCD com mands and in ter fac ing(RS, E, and R/W lines), then 11 PIC-to-LCD lines are needed, leav ing two free port lines at the most, on an 16f84 microcontroller. Not many use ful de vices can make do withjust two port lines. Sev eral pos si ble so lu tions al low com press ing the data trans ferfunc tion. The most ob vi ous one is to use the 4-bit data trans fer mode to free four portlines. Other so lu tions are based on ded i cat ing logic com po nents to the LCD func tion.

4-Bit Data Trans fer Mode

One pos si ble so lu tion is to use the ca pa bil ity of the Hitachi 44780 con trol ler that al -lows a par al lel in ter face us ing just four data paths in stead of eight. The ob jec tions arethat pro gram ming in 4-bit mode is slightly more con vo luted and there is a very mi norper for mance pen alty. In 4-bit mode, data must be sent one nib ble at a time, so ex e cu -

244 Chap ter 12

Page 266: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

tion is slower. Be cause the de lay is re quired only af ter the sec ond nib ble, the ex e cu -tion time pen alty for 4-bit trans fers is not very large.

Many of the pre vi ously de vel oped rou tines for 8-bit data mode can be re usedwith out mod i fi ca tion in the 4-bit mode. Oth ers re quire mi nor changes, and there isone spe cific dis play pro ce dure that must be de vel oped ad hoc. The first re quiredchange is in the LCD ini tial iza tion be cause bit 4 in the Func tion Set com mand mustbe clear for a 4-bit in ter face. The re main ing ini tial iza tion com mands should re quireno fur ther change, al though it is a good idea to con sult the data sheet for the LCDhard ware in use.

Dis play ing data us ing a 4-bit in ter face con sists of send ing the high-or der nib blefol lowed by the low-or der nib ble, through the LCD 4-high-or der data lines, usu allyla beled DB5 to DB7. The puls ing of line E fol lows the last nib ble sent. It is usu allythe case in the 16f84 PIC that cir cuit wir ing in the 4-bit mode uses four of five linesin port A, or four of eight lines in port B. Soft ware must pro vide a way of read ingand writ ing to the ap pro pri ate port lines, the ones used in the data trans fer, with outal ter ing the value stored in the port bits ded i cated to other uses. Bit merg ing rou -tines, dis cussed in Sec tion 12.3, are quite suit able for the pur pose at hand.

The fol low ing pro ce dures are de signed to send the two nib bles of a data bytethrough the four high-order lines in port B. The aux il iary pro ce dure named merge4per forms the bit-merging op er a tion while the pro ce dure named send8 does the ac -tual write op er a tion:

;========================; send 2 nib bles in; 4-bit mode;========================; Pro ce dure to send two 4-bit val ues to port B lines; 7, 6, 5, and 4. High-order nib ble is sent first; ON ENTRY:; w reg is ter holds 8-bit value to sendsend8:

movwf store1 ; Save orig i nal valuecall merge4 ; Merge with port B

; Now w has merged bytemovwf portb ; w to port Bcall pulseE ; Send data to LCD

; High nib ble is sentmovf store1,w ; Re cover byte into wswapf store1,w ; Swap nib bles in wcall merge4movwf portbcall pulseE ; Send data to LCDcall de lay_125 re turn

;=================; merge bits

LCD Hardware and Pro gramming 245

Page 267: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

;=================

; Rou tine to merge the 4 high-order bits of the

; value to send with the con tents of port B

; so as to pre serve the 4 low-order bits in port B

; Logic:

; AND value with 1111 0000 mask

; AND port B with 0000 1111 mask

; Now low nib ble in value and high nib ble in

; port B are all 0 bits:

; value = vvvv 0000

; port B = 0000 bbbb

; OR value and port B re sult ing in:

; vvvv bbbb

; ON ENTRY:

; w con tain value bits

; ON EXIT:

; w con tains merged bits

merge4:

andlw b’11110000’ ; ANDing with 0 clears the

; bit. ANDing with 1 pre serves

; the orig i nal value

movwf store2 ; Save re sult in vari able

movf portb,w ; port B to w reg is ter

andlw b’00001111’ ; Clear high nib ble in port b

; and pre serve low nib ble

iorwf store2,w ; OR two operands in w

re turn

The pro gram named LCDTest3 in this book’s on line soft ware pack age is a dem on -stra tion us ing the 4-bit in ter face mode. Fig ure 12-6 shows a PIC/LCD cir cuit that iswired for the 4-bit data trans fer mode.

Note in the cir cuit of Fig ure 12-6 that a to tal of six port lines re main un used. Twoof these lines are in port-A and four in port-B.

Mas ter/Slave Sys tems

To this point we have as sumed that driv ing the LCD is one of the func tions per formedby the PIC microcontroller, which also ex e cutes the other cir cuit func tions. In prac -tice, such a scheme is rarely vi a ble for two rea sons: the num ber of in ter face lines re -quired and the amount of PIC code space used up by the LCD driver rou tines. A moreef fi cient ap proach is to ded i cate a PIC ex clu sively to con trol ling the LCD hard ware,while one or more other microcontrollers per form the main cir cuit func tions. In thisscheme, the PIC de voted to the LCD func tion is re ferred to as a slave while the one that sends the dis play com mands is called the mas ter.

246 Chap ter 12

Page 268: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 12-6 PIC/LCD Cir cuit for 4-Bit Data Mode.

When suf fi cient num bers of in ter face lines are avail able, the con nec tion be tweenmas ter and slave can be sim pli fied us ing a par al lel in ter face. For ex am ple, if fourport lines are used to in ter con nect the two PICs, then six teen dif fer ent com mandcodes can be sent to the slave. The slave reads the com mu ni ca tions lines much likeit would read a mul ti ple tog gle switch. A sim ple pro to col can be de vised so that theslave uses these same in ter face lines to pro vide feed back to the mas ter. For ex am -ple, the slave sets all four lines low to in di cate that it is ready for the next com mand, and sets them high to in di cate that com mand ex e cu tion is in prog ress and that nonew com mands can be re ceived. The mas ter, in turn, reads the com mu ni ca tionslines to de ter mine when it can send an other com mand to the slave.

But us ing par al lel com mu ni ca tions be tween mas ter and slave can be aself-defeating prop o si tion, be cause it re quires at least seven in ter face lines to be

LCD Hardware and Pro gramming 247

16F84

HD44780

HD44780 pin out1 GND2 DC +5v3 Contrast adjust4 RS (register select)5 R/W (read/write select)6 E (signal enable)11-14 Data bits 4 to 7

4 MHzOsc

100 Ohms

RESET

+5 V

+5 V

+5 V

E R/W RS

10 K

RA2 RA3RA4/T0Tkl MCLR Vss RB0/INT RB1 RB2 RB3

1 2 3 4 5 6 7 8 9

18 17 16 15 14 13 12 11 10

RA1 RA0 OSC1 OSC2 Vdd RB7 RB6 RB5 RB4

1

14

E

RS

R/W

Page 269: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

able to send ASCII char ac ters. Be cause the scar city of port lines is the orig i nal rea -son for us ing a mas ter/slave setup, par al lel com mu ni ca tions may not be a good so lu -tion in many cases. On the other hand, com mu ni ca tions be tween mas ter and slavecan take place se ri ally, us ing a sin gle in ter face line. The dis cus sion of us ing se rialin ter face be tween a mas ter and an LCD slave driver PIC is left for the chap ter on se -rial com mu ni ca tions.

12.5 Sam ple Pro gramsThree sam ple pro grams in this book’s soft ware pack age dem on strate the LCD pro -gram ming dis cussed in this chap ter. The pro grams can be ex e cuted in the LCD andReal-Time clock demo board. Sche mat ics for this board are shown in Fig ure 12-7.

Fig ure 12-7 Demo Board B (LCD and Real-Time Clock).

248 Chap ter 12

+5V

R=

10

K

RESET

PB 2

PB 1

HD44780

LCD2 rows x 16

+5V

E

R/W

RS

RS

R/W

E

1

1416F84

RA2

RA3

RA4/TOCKI

MCLR

Vss

RB0/INT

RB1

RB2

RB3

1

2

3

4

5

6

7

8

9

18

17

16

15

14

13

12

11

10

RA1

RA0

OSC1

OSC2

Vdd

RB7

RB6

RB5

RB4

Osc4Mhz

+5V

32.768 kHzCrystal

NJU6355ED

+5v

1

2

3

4

8

7

6

5

+5v

DATA

CLK

CE

IO

X1

X2

GND

Page 270: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

In this book’s soft ware re source you will find sup port files and in struc tions forbuild ing the demo board in Fig ure 12-7, as well as sam ple pro grams to dem on strateLCD programming. All three pro grams as sume that the LCD is driven by the HitachiHD44780 con trol ler and that the dis play sup ports two lines, each one with six teenchar ac ters. The wir ing and base ad dress of each dis play line is stored in #de finestate ments. These state ments can be ed ited to ac com mo date a dif fer ent setup.Their func tion is as fol lows:

• The LCDTest1 pro gram ex er cises the 8-bit PIC-to-LCD in ter face us ing de lay loopsfor in ter face tim ing.

• The LCDTest2 pro gram ex er cises the 8-bit PIC-to-LCD in ter face us ing the busy flagto syn chro nize pro ces sor ac cess.

• The LCDTest3 pro gram ex er cises the 4-bit PIC-to-LCD in ter face. Pro gram uses de -lay loops for in ter face tim ing.

LCD Hardware and Pro gramming 249

Page 271: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

This page intentionally left blankThis page intentionally left blank

Page 272: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Chap ter 13

An a log-to-Dig i tal and Real-Time Clocks

13.1 Clocks and the Dig i tal Rev o lu tion

Dig its are a hu man in ven tion; na ture does not count or mea sure us ing num bers. We mea -sure nat u ral forces and phe nom ena us ing dig i tal rep re sen ta tions, but the forces and phe -nom ena them selves are con tin u ous. Time, pres sure, voltage, current, tem per a ture,hu mid ity, grav i ta tional at trac tion; all ex ist as con tin u ous en ti ties that we mea sure in volts,pounds, hours, am peres, or de grees, so as to better un der stand them and to be able to per -form nu mer i cal cal cu la tions.

In this sense, nat u ral phe nom ena oc cur in an a log quan ti ties. Some times they are dig i -tized so as to fa cil i tate mea sure ments and ma nip u la tions. For ex am ple, a potentiometerin an elec tri cal cir cuit al lows re duc ing the voltage level from the cir cuit max i mum toground, or zero level. In or der to mea sure and con trol the ac tion of the potentiometer,we need to quan tify its ac tion by pro duc ing a dig i tal value within the phys i cal range ofthe cir cuit; that is, we need to con vert an an a log quan tity that var ies con tin u ously be -tween 0 and 5 volts, to a dis crete dig i tal value range. If, in this case, the voltage range ofthe potentiometer is from 5 to 0 volts, we can dig i tize its ac tion into a nu meric range of 0to 500 units, or mea sure the an gle or ro ta tion of the potentiometer disk in de grees from 0 to 180. The de vice that per forms ei ther con ver sion is called an A/D or an a log-to-dig i talcon verter. The re verse pro cess, dig i tal-to-an a log, is also nec es sary, al though not as of tenas A/D. In this chap ter we ex plore A/D con ver sions in PIC soft ware and hard ware.

The sec ond topic of this chap ter is the mea sure ment of time in dis crete (al beit, dig i tal) units. In this con text we speak of “real-time” as years, days, hours, min utes, and so on. So a real-time clock mea sures time in hours, min utes, and sec onds, and a real-time cal en darmea sures it in years, months, weeks, and days. Not all time units are in pro por tional re la -tionship with one an other. There are 60 sec onds in a min ute and 60 min utes in an hour,but 24 hours in a day, and 28, 29, 30, or 31 days in a month. Fur ther more, the months andthe days of the week have tra di tional names. Fi nally, the Gre go rian cal en dar re quiresadd ing a twenty-ninth day to Feb ru ary on any year that is evenly di vis i ble by 4. The de -vice or soft ware to per form all of these time calculations is referred to as a realtimeclock. In this chap ter we dis cuss the use of real-time clocks in PIC cir cuits.

251

Page 273: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 13-1 A/D Con verter Block Di a gram.

13.2 A/D Con verters In elec tron ics, the typ i cal A/D or ADC con verter is a de vice that takes a volt age in putand re turns a bi nary dig i tal num ber. Fig ure 13-1 is a block di a gram of an A/D con verter.

The elec tronic A/C con verter re quires an in put in the form of an elec tri cal volt -age. Nonelectric quan ti ties must be changed into a volt age level be fore the con ver -sion can be per formed. The de vice that per forms this con ver sion is called a trans -ducer. For ex am ple, a dig i tal ba rom e ter must be equipped with a trans ducer thatcon verts the mea sure ment into volt age lev els. The volt age lev els can then be fedinto an A/D con verter and the re sult out put in dig i tal form.

13.2.1 Con verter Res o lu tion

An ideal A/D con verter out puts into an in fi nite num ber of dis crete steps that ex actlyrep re sent the an a log quan tity. Need less to say, such a de vice can not ex ist, and a realA/D con verter must be lim ited to a nu meric range. For ex am ple, the de vice in Fig ure16-1 out puts a volt age range of 0 to +5 volts in four bi nary dig its that rep re sent val uesbe tween 0 and 15. An other A/D con verter may pro duce out put in eight bi nary dig its,and an other in six teen bi nary dig its. The num ber of dis crete val ues in the con ver sionis called the res o lu tion. The con verter’s res o lu tion is usu ally ex pressed in bits. Fig ure16-2 rep re sents an A/C con verter with a volt age range of 0 to +5 volts and a res o lu tionof three bits.

Sup pose that a value of 2.5 volts were in put into the A/D con verter in Fig ure 13-2.Be cause the out put has a res o lu tion in the range 0 to 7, the con verter’s out put would be ei ther 4 or 5. The non lin ear char ac ter is tic of the out put de ter mines aquantization er ror that in creases as the con verter res o lu tion de creases. Con -verters used in PIC cir cuits have a res o lu tion of ei ther 8, 10, or 12 bits. In each casethe out put range, or quantization level, is 0 to 255, 0 to 1023, or 0 to 4095. The volt -age res o lu tion of the con verter is its max i mum volt age range di vided by the num berof quantization lev els. A de vice with a volt age range of 5 volts and a range of 255 lev -els has a volt age res o lu tion of

252 Chap ter 13

+5V

A/DConverter

3 2 1 0 <= bits

Binaryoutput

Analoginput

Page 274: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

13.2.2 ADC Im ple men ta tion

The an a log-to-dig i tal con verter per forms ac cu rately only if the in put volt age is withinthe con verter’s valid range. This range is usu ally se lected by set ting high and low volt -age ref er ences on con verter pins. For ex am ple, if +4 volts is in put into the con verter’spos i tive ref er ence pin and +2 volts into the neg a tive ref er ence pin, then the con -verter’s volt age range lies be tween these val ues. In many PIC ap pli ca tions the con -verter range is se lected as the sys tem’s sup ply volt age and ground, that is, +5 and 0volts. When a dif fer ent range is ex ter nally ref er enced, there is a gen eral re stric tionthat the range can not ex ceed the sys tem’s pos i tive and neg a tive lim its (Vdd and Vss).Also, a min i mum dif fer ence is re quired be tween the high and low volt age ref er ences.

The out put of the ADC is a dig i tal rep re sen ta tion of the orig i nal an a log sig nal. Inthis con text, the term quantization re fers to sub di vid ing a range into small butmea sur able in cre ments. The quantization pro cess can in tro duce a quantization er -ror, which is sim i lar to a round ing er ror.

The time re quired for the hold ing ca pac i tor on the ADC to charge is called the ac -qui si tion time. The hold ing ca pac i tor on the ADC must be given suf fi cient time toset tle to the an a log in put volt age level be fore the ac tual con ver sion is ini ti ated. Oth -er wise, the con ver sion is not ac cu rate. The ac qui si tion time is de ter mined by the im -ped ance of the in ter nal multi plexer and that of the an a log source. The ex actac qui si tion time can be de ter mined from the de vice’s data sheet, al though 10K Ohms is the max i mum rec om mended source im ped ance for 8- and 10-bit con vert ers and2.5K Ohms for 12-bit con vert ers.

An a log-to-Dig i tal and Real-Time Clocks 253

Fig ure 13-2 Con verter Quantization Er ror.

1 2 3 4 5 6 7

Binary output

+5

2.5

Volts

0

Voltage resolution volts mV= = =5

2550 01960 19 60. .

Page 275: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Most an a log-to-dig i tal con vert ers in PIC ap pli ca tions, ei ther in ter nal or ex ter nal,are of the suc ces sive ap prox i ma tion type. The suc ces sive ap prox i ma tion al go -rithm per forms a con ver sion on one bit at a time, be gin ning with the most sig nif i -cant bit and end ing with the least-sig nif i cant bit. To de ter mine each bit in the range,the value of the in put sig nal is tested to see if it is in the up per or lower por tion ofthis range. If in the up per por tion, the con ver sion bit is a 1, oth er wise it is a 0. Thenext most-sig nif i cant bit is then tested in the lower half of the re main ing range. Thepro cess is con tin ued un til the least-sig nif i cant bit has been de ter mined.

13.3 A/D In te grated Cir cuits Sev eral pop u lar in te grated cir cuits are used to per form as A/D con vert ers, amongthem the ADC0831, the LTC1298, and the MAX 190 and MAX 191. The vari a tions con -sist in the res o lu tion and in ter fac ing of the dif fer ent ICs. Of these, the ADC0831, fromNa tional Semi con duc tor, is an 8-bit res o lu tion, se rial in ter face A/D quite suited to ap -pli ca tions for small, mid-range PICs such as the 16F84. The in put range of the 0831 is 0to 5 volts, which matches the TTL voltage lev els used in PIC cir cuits. The 0831 pin di a -gram is shown in Fig ure 13-3.

Fig ure 13-3 ADC0831 Pin Di a gram.

The ADC0831 uses three con trol lines, la beled DO (data out), CLK (clock), and_CS (chip se lect) in Fig ure 13-3. In ter fac ing the ADC0831 re quires three I/O lines. Ofthese, two can be mul ti plexed with other func tions or with other ADC0831. Ac tu ally, only the chip-se lect (CS) pin re quires a ded i cated line. This al lows for sev eral ADCsto be mul ti plexed on the CLK and DO lines as long as each one has its own CS con -nec tion to the microcontroller. In this case, the con trol ler de ter mines which de viceis be ing read by the port to which its CS line is con nected.

The in put volt age range of the ADC0831 is de ter mined by the Vref (pos i tive volt -age ref er ence line) and Vin- (neg a tive volt age ref er ence line) pins. Vref is used toset the max i mum level and Vin- the min i mum. Be cause the ADC0831 has an 8-bitrange, the volt age read ing that matches the Vref value is read as 255 and the onethat matches the Vin- value is read as 0. The min i mum dif fer ence be tween the volt -age lim its is 1 volt.

254 Chap ter 13

ADC08316

7

81

5

2

3

4

_CS

Vin+

Vin-

GND

Vcc

CLK

DO

Vref

ADC0831 PINOUT

_CS - Chip Select (active low)Vin+ - Analog voltage input +Vin- - Analog voltage inpit - GND - GroundVref - Voltage reference DO - Data out CLK - Clock signal Vcc - +5V power

Page 276: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 13-4 ADC0831 Dem on stra tion Cir cuit.

13.3.1 ADC0331 Sam ple Cir cuit and Pro gram

A sim ple cir cuit to il lus trate the ac tion of an an a log-to-dig i tal con verter con sists ofcon nect ing a po ten ti om e ter with the pos i tive volt age ref er ence line, as sown in Fig ure13-4. In the cir cuit the po ten ti om e ter was se lected so as to pro duce a volt age range be -tween 0 and +5 volts. Vref was wired to the cir cuit’s +5V source and Vin- was wired toground. The po ten ti om e ter vari able line was con nected to the ADC0831 Vin+ line andthe other ADC lines to the cor re spond ing 16F84 port B pins.

The sam ple pro gram is called ADF84, and can be found in this book’s on line soft -ware. The ADF84 pro gram uses the ADC0831 to con vert the an a log volt age from thepo ten ti om e ter, in the range +5 to 0 volts, into a dig i tal value in the range 0 to 255.The value read is then dis played on the LCD. The ini tial iza tion rou tine de fines

An a log-to-Dig i tal and Real-Time Clocks 255

+5V

R=

10

K

RESET

HD44780

LCD2 rows x 16

+5V

E

R/W

RS

RS

R/W

E

1

1416F84

RA2

RA3

RA4/TOCKI

MCLR

Vss

RB0/INT

RB1

RB2

RB3

1

2

3

4

5

6

7

8

9

18

17

16

15

14

13

12

11

10

RA1

RA0

OSC1

OSC2

Vdd

RB7

RB6

RB5

RB4

Osc4Mhz

+5V

32.768 kHzCrystal

NJU6355ED

+5V

1

2

3

4

8

7

6

5

+5v

DATA

CLK

CE

IO

X1

X2

GND

Page 277: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

port-B, line 0 as in put be cause this is the one con nected to the DO line. The re main -ing lines in ports A and B are de fined as out put. ADC0831 pro cess ing con sists of asin gle pro ce dure that reads the an a log line and re turns an 8-bit dig i tal value. Thepro cess ing re quired is per formed in the fol low ing steps:

1. The data re turn reg is ter (named rcvdata) is cleared and the bit coun ter reg is ter isin i tial ized to count 8 bits.

2. The ADC0831 is pre pared by bring ing the CS line low and puls ing the CLK line.

3. The CLK line is pulsed and one bit is read from the low-or der bit (DO line) of port B.

4. The bit is shifted into the data re turn reg is ter and the bit coun ter is dec re ment ed.

5. If the bit coun ter is ex hausted, ex e cu tion ends and the ADC is turned off. Oth er wise pro cess ing con tin ues at Step 3.

The fol low ing pro ce dure, from the ADF84 pro gram, reads dig i tal data from theADC0831:

;============================; pro ce dure to read and; con vert an a log line;============================; ON ENTRY:; Code as sumes that the ADC0831 DO line is in i tial ized for; in put, while CLK and CS lines are out put ; from ADC0831 wir ing di a gram. All lines in port B; DO = RB0 ==> INPUT ; CLK = RB1 <== OUTPUT; CS = RB2 <== OUTPUT; ON EXIT:; Re turns 8-bit dig i tal value in the reg is ter rcvdata;ana2dig:; Clear data reg is ter and init coun ter for 8 bits

clrf rcvdata ; Clear reg is termovlw 0x08 ; Ini tial ize coun termovwf bitCount

; Pre pare to read an a log linebcf PORTB,CS ; CS pin low to en able ADCnop ; De lay for 4 MHz clockbsf PORTB,CLK ; Set CLK highnopbcf PORTB,CLK ; Re set CLK to start con ver sionnop

nextB:; Pulse CLK line to read bit from ADC

bsf PORTB,CLK ; CLK highnop bcf PORTB,CLK ; CLK lownop

; Read an a log line and store data, bit by bit

256 Chap ter 13

Page 278: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

movf PORTB,w ; Read all Port-B bitsmovwf store1 ; Store value for laterrrf store1,f ; Ro tate bit into carry flagrlf rcvdata,f ; Ro tate carry flag into

; re sult reg is terdecfsz bitCount,f ; Bump coun ter, skip next

; if coun ter zerogoto nextB

; Value read is stored in rcvdata reg is terbsf PORTB,CLK ; Fi nal clock pulseNopbcf PORTB,CLKnopbsf PORTB,CS ; Turn off ADCcall long_de lay ; Time to set tleReturn

13.4 PIC Onboard A/D Hard wareA few years ago, A/D con ver sions al ways re quired the use of de vices such as the onesde scribed in the pre vi ous sec tions. Now a days, many PIC microcontrollers come withonboard A/D hard ware. One of the ad van tages of us ing onboard A/D con vert ers is sav -ing in ter face lines. The cir cuit shown in Figure13-4 re quires de vot ing three lines to thein ter face be tween the ADC0831 and the PIC 16F84. On the other hand, a sim i lar cir cuit can be im ple mented in a PIC with in ter nal A/C con ver sion by sim ply con nect ing thean a log de vice to the cor re spond ing PIC port. In the PIC world, where I/O lines are of -ten in short sup ply, this ad van tage is not in sig nif i cant.

At the time of writ ing, PICs equipped with A/D con vert ers have ei ther 8- or 10-bitres o lu tion and can re ceive an a log in put in two to six teen dif fer ent chan nels. The16F877 with eight an a log in put chan nels at a 10-bit res o lu tion is dis cussed. Now a -days, these PICs are easy to ob tain. On the other hand, if the res o lu tion re quired ex -ceeds 10 bits, then the de signer has to re sort to an in de pend ent A/D IC, such as theLTC1298, which has a 12-bit res o lu tion, or to oth ers with even higher num bers ofout put bits.

13.4.1 A/D Mod ule on the 16F87xThe PICs of the 16F87x fam ily are equipped with an an a log-to-dig i tal con verter mod -ule. The num ber of lines de pends on the spe cific ver sion of the de vice: 28-pin de viceshave five A/D lines and all oth ers have eight lines. The con verter uses a sam ple andhold ca pac i tor to store the an a log charge and per forms a suc ces sive ap prox i ma tion al -go rithm to pro duce the dig i tal re sult. The con verter res o lu tion is 10 bits, which arestored in two 8-bit reg is ters. One of the reg is ters has only four sig nif i cant bits.

The A/D mod ule has high- and low-volt age ref er ence in puts that are se lected bysoft ware. The mod ule can op er ate while the pro ces sor is in SLEEP mode, but only if the A/D clock pulse is de rived from its in ter nal RC os cil la tor. The mod ule con tainsfour reg is ters ac ces si ble to the ap pli ca tion:

An a log-to-Dig i tal and Real-Time Clocks 257

Page 279: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

1. ADRESH - Re sult High Reg is ter

2. ADRESL - Re sult Low Reg is ter

3. ADCON0 - Con trol Reg is ter 0

4. ADCON1 - Con trol Reg is ter 1

Of these, it is the ADCON0 reg is ter that con trols most of the op er a tions of theA/C mod ule. Port A pins RA0 to RA5 and port E pins RE0 to RE2 are mul ti plexed asan a log in put pins into the A/C mod ule. In the 28-pin ver sions of the 16F87x, portpins RA0 to RA5 pro vide the five in put chan nels. In all other im ple men ta tions of the16F87X, port E pins RE0 to RE2 pro vide the three ad di tional chan nels.

Fig ure 13-5 shows the reg is ters as so ci ated with A/D mod ule op er a tions.

Fig ure 13-5 Reg is ters Re lated to A/C Mod ule Op er a tions.

ADCON0 Reg is ter

The ADCON0 reg is ter is lo cated in bank 0, at ad dress 0x1f. Seven of the eight bits aremean ing ful in A/D con trol and sta tus op er a tions. Fig ure 13-6 is a bitmap of theADCON0 reg is ter.

In Fig ure 13-6, bits 7 and 6, la beled ASCC1 and ADSC0, are the se lec tion bits forthe A/D con ver sion clock. The con ver sion time per bit is de fined as TAD in PIC doc -u men ta tion. A/D con ver sion re quires a min i mum of 12 TAD in a 10-bit ADC. Thesource of the A/D con ver sion clock is soft ware se lected. The four pos si ble op tionsfor TAD are:

1. Fosc/2

2. Fosc/8

3. Fosc/32

4. In ter nal A/D module RC oscillator (var ies be tween 2 and 6 µs)

258 Chap ter 13

ADSC1 ADSC0 CHS2 CHS1 CHS0 GO/DONE ADON

ADFM PCFG3 PCFG2 PCFG1 PCFG0

ADCON0

ADCON1

PIR1

ADRESH

PIE1

ADRESL

INTCON

ADIF

A/D Result Register High Byte

A/D Result Register Low Byte

ADIE

GIE PEIE

7 6 5 4 3 2 1 0 bitsREGISTER

NAME

Page 280: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

The con ver sion time is the an a log-to-dig i tal clock pe riod mul ti plied by the num -ber of bits of res o lu tion in the con verter, plus the two to three ad di tional clock pe ri -ods for set tling time, as spec i fied in the data sheet of the spe cific de vice. Thevar i ous sources for the an a log-to-dig i tal con verter clock rep re sent the main os cil la -tor fre quency di vided by 2, 8, or 32. The third choice is the use of a ded i cated in ter -nal RC clock that has a typ i cal pe riod of 2 to 6 µs. Be cause the con ver sion time isde ter mined by the sys tem clock, a faster clock re sults in a faster con ver sion time.

The A/D con ver sion clock must be se lected to en sure a min i mum Tad time of 1.6µs. The for mula for con vert ing pro ces sor speed (in MHz) into Tad mi cro sec onds isas fol lows:

An a log-to-Dig i tal and Real-Time Clocks 259

ADSC1 ADSC0 CHS2 CHS1 CHS0 GO/DONE ADON

7 6 5 4 3 2 1 0bits:

bit 7-6 ADCS1:ADCS0: A/D Conversion Clock Select bits 00 = FOSC/2 01 = FOSC/8 10 = FOSC/32 11 = FRC (internal A/D module RC oscillator)bit 5-3 CHS2:CHS0: Analog Channel Select bits 000 = channel 0, (RA0=AN0) 001 = channel 1, (RA1=AN1) 010 = channel 2, (RA2=AN2) 011 = channel 3, (RA3=AN3) 100 = channel 4, (RA5=AN4) 101 = channel 5, (RE0=AN5) | not active 110 = channel 6, (RE1=AN6) | in 28-pin 111 = channel 7, (RE2=AN7) | 16F87x PICSbit 2 GO/DONE: A/D Conversion Status bit If ADON = 1: 1 = A/D conversion in progress (setting this bit starts the A/D conversion) 0 = A/D conversion not in progress (this bit is automatically cleared by hardware when the A/D conversion is complete)bit 1 Unimplemented: Read as '0'bit 0 ADON: A/D On bit 1 = A/D converter module is operating 0 = A/D converter module is shut-off and consumes no power

Fig ure 13-6 ADCON0 Reg is ter Bitmap.

Tad Tosc

Tdiv

= 1

Page 281: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Where Tad is A/D con ver sion time, Tosc is the os cil la tor clock fre quency in MHz,and Tdiv is the di vi sor de ter mined by bits ADSC1 and ADSC0 of the ADCON0 reg is -ter. For ex am ple, in a PIC run ning at 10 MHz, if we se lect the Tosc/8 op tion (di vi sorequal 8) the A/D con ver sion time per bit is cal cu lated as fol lows:

In this case, the min i mum rec om mended con ver sion speed of 1.6 µs is achieved.How ever, in a PIC with an os cil la tor speed of 10 MHz, this op tion pro duces a con ver -sion speed of 0.8 µs, less than the rec om mended min i mum. In this case we wouldhave to se lect the di vi sor 32 op tion, giv ing a con ver sion speed of 3.2 µs.

Ta ble 13.1

A/C Con verter Tad at var i ous Os cil la tor Speeds

TAD IN MICROSECONDSOPERATION ADCS1:ADCS0 20MHZ 10MHZ 5MHZ 1.25MHZ

Fosc/2 00 0.1 0.2 0.4 1.6Fosc/8 01 0.4 0.8 1.6 6.4Fosc/32 10 1.6 3.2 6.4 25.6RC 11 2-6 2-6 2-6 2-6

Note: val ues in bold are within the rec om mended lim its

In Ta ble 13.1, con verter speeds of less than 1.6 µs or higher than 10 µs are not rec -om mended. Re call that the Tad speed of the con verter is cal cu lated per bit, so theto tal con ver sion time in a 10-bit de vice (such as the 16F87x) is ap prox i mately theTad speed mul ti plied by 10 bits, plus three ad di tional cy cles; therefore, a de vice op -er at ing at a Tad speed of 1.6 µs re quires 1.6 µs * 13, or 20.8 µs, for the en tire con ver -sion.

Bits CHS2 to CHS0 in the ADCON0 reg is ter (see Fig ure 13-6) de ter mine which ofthe an a log chan nels is se lected. This is re quired, be cause there are sev eral chan nelsfor an a log in put but only one A/2 con verter cir cuitry. So the set ting of this bit fieldde ter mines which of six or eight pos si ble chan nels is cur rently read by the A/C con -verter. An ap pli ca tion can change the set ting of these bits in or der to read sev eralan a log in puts in suc ces sion.

Bit 2 of the ADCON0 reg is ter, la beled GO/DONE, is both a con trol and a sta tusbit. Set ting the GO/DONE bit starts A/D con ver sion. Once con ver sion has stared, the bit in di cates if it is still in prog ress. Code can test the sta tus of the GO/DONE bit inor der to de ter mine if con ver sion has con cluded.

Bit 0 of the ADCON0 reg is ter turns the A/D mod ule on and off. The ini tial iza tionrou tine of an A/D-en abled ap pli ca tion turns on this bit. Pro grams that do not use the A/D con ver sion mod ule leave the bit off to con serve power.

260 Chap ter 13

TadMHz

= =15

8

1 6.

Page 282: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 13-7 Left- and Right-Jus ti fi ca tion of A/D Re sult.

ADCON1 Reg is ter

The ADCON1 reg is ter also plays an im por tant role in pro gram ming the A/D mod ule.Bit 7 of the ADCON1 reg is ter is used to de ter mine the bit jus ti fi ca tion of the dig i tal re -sult. This is pos si ble be cause the 10-bit re sult is re turned in two 8-bit reg is ters; there -fore, the six un used bits can be placed ei ther on the left- or the right-hand side of the16-bit re sult. If ADCON1 bit 7 is set then the re sult is right-jus ti fied, oth er wise it isleft-jus ti fied. Fig ure 13-7 shows the lo ca tion of the sig nif i cant bits.

One com mon use of right jus ti fi ca tion is to re duce the num ber of sig nif i cant bitsin the con ver sion re sult. For ex am ple, an ap pli ca tion on the 16F877 that uses theA/D con ver sion mod ule re quires only 8-bit ac cu racy in the re sult. In this case, codecan left-jus tify the con ver sion re sult, read the ADRESH reg is ter, and ig nore thelow-or der bits in the ADRESL reg is ter. By ig nor ing the two low-or der bits, the 10-bitac cu racy of the A/D hard ware is re duced to eight bits and the con verter per forms as an 8-bit ac cu racy unit.

The bit field la beled PCFG3 to PCFG0 in the ADCON1 reg is ter de ter mines portcon fig u ra tion as an a log or dig i tal and the map ping of the pos i tive and neg a tive volt -age ref er ence pins. The num ber of pos si ble com bi na tions is lim ited by the four bitsal lo cated to this field, so the pro gram mer and cir cuit de signer must se lect the op -tion that is most suited to the ap pli ca tion when the ideal one is not avail able. Ta ble13-2 (in the fol low ing page) shows the port con fig u ra tion op tions.

For ex am ple, there is a cir cuit that calls for two an a log in puts, wired to ports RA0 and RA1, with no ref er ence volt ages. In Ta ble 13-2 we can find two op tions that se -lect ports RA0 and RA1 and are an a log in puts: these are the ones se lected withPCFG bits 0100 and 0101. The first op tion also se lects port RA3 as an a log in put,even though not re quired in this case. The sec ond one also se lects port RA3 as apos i tive volt age ref er ence, also not re quired.

Ei ther op tion works in this case; how ever, any pin con fig ured for an a log in putpro duces in cor rect re sults if used as a dig i tal source. There fore, a chan nel con fig -ured for an a log in put can not be used for non-an a log pur poses. On the other hand, a

An a log-to-Dig i tal and Real-Time Clocks 261

V V V V V V V V

0 0 0 0 0 0 V V

V V 0 0 0 0 0 0

V V V V V V V V

ADRESH

ADRESH

Left-justified (ADFM bit = 0)

Right-justified (ADFM bit = 1)

Legend: V = valid digit 0 = digit always cleared

ADRESL

ADRESL

Page 283: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

chan nel con fig ured for dig i tal in put should not be used for an a log data be cause ex -tra cur rent is con sumed by the hard ware. Finally, chan nels to be used for an a -log-to-dig i tal con ver sion must be con fig ured for in put in the cor re spond ing TRISreg is ter.

SLEEP Mode Op er a tion

The A/D mod ule can be made to op er ate in SLEEP mode. As men tioned pre vi ously,SLEEP mode op er a tion re quires that the A/D clock source be set to RC by set ting bothADCS bits in the ADCON0 reg is ter. When the RC clock source is se lected, the A/Dmod ule waits one in struc tion cy cle be fore start ing the con ver sion. Dur ing this pe riod,the SLEEP in struc tion is ex e cuted, thus elim i nat ing all dig i tal switch ing noise fromthe con ver sion. The com ple tion of the con ver sion is de tected by test ing the GO/DONE bit. If a dif fer ent clock source is se lected, then a SLEEP in struc tion causes the con ver -sion-in-prog ress to be aborted and the A/D mod ule to be turned off.

13.4.2 A/D Mod ule Sam ple Cir cuit and Pro gramThe cir cuit in Fig ure 13-8 is de signed to dem on strate the use of the A/D con verter mod -ule in PICs of the 16F87x fam ily.

262 Chap ter 13

Ta ble 13.2

A/D Con verter Port Con fig u ra tion Op tions

PCFG3: An7 An6 An5 An4 An3 An2 An1 An0 CHAN/

PCFG0 Re2 Re1 Re0 Ra5 Ra3 Ra2 Ra1 Ra0 Vref+ Vref- Refs

0000 A A A A A A A A VDD VSS 8/0

0001 A A A A Vre+ A A A RA3 VSS 7/1

0010 D D D A A A A A VDD VSS 5/0

0011 D D D A Vre+ A A A RA3 VSS 4/1

0100 D D D D A D A A VDD VSS 3/0

0101 D D D D Vre+ D A A RA3 VSS 2/1

011x D D D D D D D D VDD VSS 0/0

1000 A A A A Vre+ Vre- A A RA3 RA2 6/2

1001 D D A A A A A A VDD VSS 6/0

1010 D D A A Vre+ A A A RA3 VSS 5/1

1011 D D A A Vre+ Vre- A A RA3 RA2 4/2

1100 D D D A Vre+ Vre- A A RA3 RA2 3/2

1101 D D D D Vre+ Vre- A A RA3 RA2 2/2

1110 D D D D D D D A VDD VSS 1/0

1111 D D D D Vre+ Vre- D A RA3 RA2 1/2

Legend: D = digital input A = analog input CHAN/Refs = analog channels/voltage reference inputs

Page 284: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 13-8 Dem on stra tion Cir cuit for A/D Con ver sion Mod ule.

Com paring Fig ure 13-8 with Fig ure 13-4, which uses the ADC0831 IC, we no ticethe econ omy of re sources that re sults from se lect ing a PIC with an onboard A/Dmod ule. In the cir cuit of Fig ure 13-4, three microcontroller I/O ports must be usedto con nect the con verter IC to the PIC. In the cir cuit of Fig ure 13-8, the po ten ti om e -ter is con nected di rectly to a sin gle PIC port, sav ing two I/O lines. Con sidering thenum ber of dif fer ent PIC ar chi tec tures that are equipped with onboard A/D con vert -ers, the cir cuit de signer should ex plore this pos si bil ity be fore de cid ing on us ing asep a rate con verter IC. At the same time, re call that two of the three in put lines usedby con verter ICs can be shared. In a de sign with more than one con verter IC, the use of in put lines is not a 3 to1 ra tio.

The cir cuit in Fig ure 13-8 con sists of a 5K po ten ti om e ter wired to an a log port RA0 of a 16F877 PIC. The LCD dis play is used to show three dig its, in the range 0 to 255,

An a log-to-Dig i tal and Real-Time Clocks 263

16F877

+5v

+5v

Pot 1 5K

R=

10

K

40

39

38

37

36

35

34

33

32

31

30

29

28

27

26

25

24

23

22

21

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

RB7/PGD

RG6/PGC

RB5

RB4

RB3/PGM

RB2

RB1

RB0/INT

VDD

VSS

RD7/PSP7

RD6/PSP6

RD5/PSP5

RD4/PSP4

RC7/RX/DT

RC6/TX/CK

RC5/SD0

RC4/SDI/SDA

RD3/PSP3

RD2/PSP2

!MCLR/VPP

RA0/AN0

RA1/AN1

RA2/AN2.VREF-

RA3/AN3/VREF+

RA4/TOCKI

RA5/AN4/SS

RE0/!RD/AN5

RE1/!WR/AN6

RE2/!CS/AN7

VDD

VSS

OSC1/CLKIN

OS2/CLKOUT

RC0/T1OSO/T1CKI

RC1/T1OSI/CCP2

RC2/CCP1

RC3/SCK/SCL

RD0/PSP0

RD1/PSP1

RESET

+5v

HD44780

LCD2 rows x 20

10 MHzOsc

+5 V

E

R/W

RS

1

14

Page 285: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

that rep re sent the rel a tive po si tion of the po ten ti om e ter’s disk. The pro gram calledA2DinLCD, in this book’s on line soft ware, uses the built-in A/D mod ule.

Pro gramming the A/D mod ule con sists of the fol low ing steps:

1. Con fig ure the PIC I/O lines to be used in the con ver sion. All an a log lines are in i tial -ized as in put in the cor re spond ing TRIS registers.

2. Se lect the ports to be used in the con ver sion by set ting the PCFGx bits in theADCON1 reg is ter. Se lects right- or left-jus ti fi ca tion.

3. Se lect the an a log chan nels, se lect the A/D con ver sion clock, and en able the A/Dmodule.

4. Wait the ac qui si tion time.

5. Ini ti ate the con ver sion by set ting the GO/DONE bit in the ADCON0 reg is ter.

6. Wait for the con ver sion to com plete.

7. Read and store the dig i tal re sult.

The fol low ing pro ce dure from the A2DinLCD pro gram in i tial ized the A/D mod ulefor the re quired pro cess ing:

;============================; init A/D mod ule;============================; 1. Pro ce dure to ini tial ize the A/D mod ule, as fol lows:; Con fig ure the PIC I/O lines. Init an a log lines as in put; 2. Se lect ports to be used by set ting the PCFGx bits in the; ADCON1 reg is ter. Se lects right- or left-jus ti fi ca tion.; 3. Se lect the an a log chan nels, se lect the A/D con ver sion; clock, and en able the A/D mod ule.; 4. Wait the ac qui si tion time.; 5. Ini ti ate the con ver sion by set ting the GO/DONE bit in the; ADCON0 reg is ter. ; 6. Wait for the con ver sion to com plete.; 7. Read and store the dig i tal re sult.InitA2D:

Bank1 ; Se lect bank for TRISA reg is termovlw b’00000001’movwf TRISA ; Set Port-A, line 0, as in put

; Se lect the for mat and A/D port con fig u ra tion bits in; the ADCON1 reg is ter; For mat is left-jus ti fied so that ADRESH bits are the; most sig nif i cant; 0 x x x 1 1 1 0 <== value in stalled in ADCON1; 7 6 5 4 3 2 1 0 <== ADCON1 bits; | |__|__|__|____ RA0 is an a log.; | Vref+ = Vdd; | Vref- = Vss; |_________________________ 0 = left-jus ti fied; ADCON1 is in bank 1

264 Chap ter 13

Page 286: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

movlw b’00001110’movwf ADCON1 ; RA0 is an a log. All oth ers dig i tal

; Vref+ = Vdd; Se lect D/A op tions in ADCON0 reg is ter; For a 10-MHz clock the Fosc32 op tion pro duces a con ver sion; speed of 1/(10/32) = 3.2 mi cro sec onds, which is within the; rec om mended range of 1.6 to 10 mi cro sec onds.; 1 0 0 0 0 0 0 1 <== value in stalled in ADCON0; 7 6 5 4 3 2 1 0 <== ADCON0 bits; | | | | | | |____ A/D func tion se lect; | | | | | | 1 = A/D ON; | | | | | |__________ A/D sta tus bit ; | | |__|__|_____________ An a log Chan nel Se lect; | | 000 = Channel 0 (RA0) ; |__|______________________ A/D Clock Se lect; 10 = Fosc/32; ADCON0 is in bank 0

Bank0movlw b’10000001’movwf ADCON0 ; Chan nel 0, Fosc/32, A/D en abled

; De lay for se lec tion to com pletecall delayAD ; Lo cal pro ce durere turn

Once the mod ule is in i tial ized, the an a log line is read by the fol low ing pro ce dure:

;============================; read A/D line;============================; Pro ce dure to read the value in the A/D line and con vert; to dig i talReadA2D:; Ini ti ate con ver sion

Bank0 ; Bank for ADCON0 reg is terbsf ADCON0,GO ; Set the GO/DONE bit

; GO/DONE bit is cleared au to mat i cally when con ver sion endsconvWait:

btfsc ADCON0,GO ; Test bitgoto convWait ; Wait if not clear

; At this point, con ver sion has con cluded; ADRESH reg is ter (bank 0) holds 8 MSBs of re sult; ADRESL reg is ter (bank 1) holds 4 LSBs.; In this ap pli ca tion value is left-jus ti fied. Only the; MSBs are read

movf ADRESH,W ; Dig i tal value to w reg is terre turn

An a log-to-Dig i tal and Real-Time Clocks 265

Page 287: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

The de lay rou tine re quired in this case is coded as fol lows:

;=======================

; de lay pro ce dure

;=======================

; For a 10 MHz clock the Fosc32 op tion pro duces a con ver sion

; speed of 1/(10/32) = 3.2 mi cro sec onds. At 3.2 ms per bit,

; 13 bits re quire ap prox i mately 41 ms. The in struc tion time

; at 10 MHz is 10 ms. 4/10 = 0.4 ms per insctruction. To de lay

; 41 ms, a 10 MHz PIC must ex e cute 11 in struc tions. Add one

; more for safety.

delayAD:

movlw .12 ; Re peat 12 ma chine cy cles

movwf count1 ; Store value in coun ter

repeat11:

decfsz count1,f ; Dec re ment coun ter

goto repeat11 ; Con tinue if not 0

return

13.5 Real-Time ClocksIn the con text of microcontrollers and em bed ded sys tems, real-time clocks (alsocalled RTCs) are in te grated cir cuits de signed to keep track of time in con ven tionalhours, that is, in years, days, hours, min utes, and sec onds. Many real-time clock ICsare avail able with var i ous char ac ter is tics, data for mats, modes of op er a tion, and in -ter faces. Most of the ones used in PIC cir cuits have a se rial in ter face in or der to saveac cess ports. Most RTC chips pro vide a bat tery con nec tion so that time can be keptwhen the sys tem is turned off.

In the sec tions that fol low, we dis cuss one pop u lar RTC chip: the NJU6355, butthis is by no means the only op tion for em bed ded sys tems.

13.5.1 NJU6355 Real-Time Clock

The NJU6355 se ries is a se rial I/O real-time clock used in microcontroller-based em -bed ded sys tems. The IC in cludes its own quartz crys tal os cil la tor, coun ter, shift reg is -ter, volt age reg u la tor, and in ter face con trol ler. The PIC in ter face re quires four lines.Op er ating volt age is TTL level so it can be wired di rectly on the typ i cal PIC cir cuit. The out put data in cludes year, month, day-of-week, hour, min utes, and sec onds. Fig ure13-9 is the pin di a gram for the NJU6355.

NJU6355 out put is in packed BCD for mat, that is, each dec i mal digit is rep re -sented by a 4-bit bi nary num ber. The chip’s logic cor rectly cal cu lates the num ber ofdays in each month as well as the leap years. All un used bits are re ported as bi nary0. Fig ure 13-10 is a bitmap of the for mat ted timer data.

266 Chap ter 13

Page 288: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 13-9 NJU6355 Pin Di a gram.

Timer data is read when the I/O line is low and the CE line is high. Out put fromthe 6355 is LSB first. A to tal of fifty-two sig nif i cant bits are read in bot tom-up or derfor data as shown in Fig ure 13-10. That is, the first bit re ceived is the least-sig nif i -cant bit of the year, then the month, then the day, and so forth. All date items areeight bits, ex cept the day of week, which is four bits. Nonsignificant bits in eachfield are re ported as zero; this means that the value for the tenth month (Oc to ber) is en coded as bi nary dig its 00001010. Re porting un used dig its as zero sim pli fies thecon ver sion into BCD and ASCII.

Fig ure 13-10 NJU6355 Timer Data For mat.

An a log-to-Dig i tal and Real-Time Clocks 267

NJU63556

7

81

5

2

3

4

I/O

XT

_XT

GND

Vcc

DATA

CLK

CE

NJU6355 PINOUT

I/O - Input/Output select XT - Quartz crystal input (f=32.768kHz) _XT - Quartz crystal output GND - Ground CE - Input enable CLK - Clock inputDATA - Serial timer input/output Vcc - +5V power

seconds

year

minutes

hours

day

month

day of week

RANGE:

0 to 59

0 to 99

0 to 59

0 to 23

1 to 31

1 to 12

1 to 7

S6 S5 S4 S3 S2 S1 S0

Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y0

M6 M5 M4 M3 M2 M1 M0

H5 H4 H3 H2 H1 H0

D5 D4 D3 D2 D1 D0

M4 M3 M2 M1 M0

W2 W1 W0

MSB LSB

Page 289: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

The NJU6355 does not re port valid time data un til af ter it has been in i tial ized,even if there are power and clock sig nals into the chip. Ini tial iza tion re quires writ -ing data into the 6355 reg is ters. In or der to write to the IC, code must set the I/O and the CE lines high. At this mo ment, all clock up dates stop and the RTC goes into thewrite mode. In put data is latched in LSB first, start ing with the year and con clud ingwith the min utes. There is no pro vi sion for writ ing sec onds into the RTC, so the to -tal num ber of bits writ ten is 44.

The 6355 con tains a mech a nism for de tect ing con di tions that could com pro misethe clock’s op er a tion, such as low power. In this case, the spe cial value 0xee is writ -ten into each digit of the in ter nal reg is ters to in form pro cess ing rou tines that thetimer has been com pro mised.

The NJU6355 re quires the in stal la tion of an ex ter nal crys tal os cil la tor. The crys -tal must have a fre quency of 32.768 KHz. The time-keep ing ac cu racy of the RTC isde ter mined by the quartz os cil la tor. The ca pac ity of the os cil la tor must match thatof the RTC and of the cir cuit. A stan dard crys tal with a ca pac i tance of 12.5 pF works well for ap pli ca tions that do not de mand high clock ac cu racy. For more ex act ing ap -pli ca tions, the 6355 can be pro grammed to check the clock fre quency and de ter mine its er ror. The chip’s fre quency-check ing mode is de scribed in an NJU6355 Ap pli ca -tion Note avail able from New Ja pan Ra dio Co., Ltd.

13.5.2 RTC Dem on stra tion Cir cuit and Pro gramThe cir cuit shown in Fig ure 13-11 is a sim ple ap pli ca tion of the 6355 RTC. The cir cuituses a NJU6355 in con junc tion with a 16F86 PIC and an LCD. The dem on stra tion pro -gram, named RTC2LCD, sets up RTC and reads clock data in an end less loop. Thehours, min utes, and sec onds are dis played at the top line of the LCD as fol lows:

H:xx M:xx S:xx

where xx rep re sents the two BCD dig its read from the clock and con verted to ASCIIdec i mal for dis play. The pro gram initializes the 6355 to some ar bi trary val ues con -tained in the cor re spond ing #de fine state ments. These val ues are cop ied into pro -gram vari ables by a lo cal pro ce dure and then used to ini tial ize the RTC reg is ters. Twopro ce dures re late to RTC op er a tion: one to ini tial ize the clock hard ware and the otherone to read the cur rent time. In ad di tion, two aux il iary pro ce dures are im ple mented:one to read clock data and one to write clock data. Be cause clock data can be in 8- or4-bit for mats, each pro ce dure con tains a sep a rate en try point to han dle the 4-bit op -tion. The pro ce dure to ini tial ize and the one to write clock data are coded as fol lows:

;============================

; init RTC

;============================

; Pro ce dure to ini tial ize the real time clock chip. If chip

; is not in i tial ized it will not op er ate and the val ues

; read will be in valid.

; because the 6355 op er ates in BCD for mat the stored val ues must

; be con verted to packed BCD.

; Ac cord ing to wir ing di a gram

268 Chap ter 13

Page 290: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; NJU6355 In ter face for set ting time:; DAT PORTB,0 Out put; CLK PORTB,1 Out put; CE PORTB,2 Out put ; IO PORTB,3 Out putsetRTC:

Bank1movlw b’00000000’ ; All lines are out putmovlw TRISBBank0

; Writ ing to the 6355 re quires that the CLK bit be held; low while the IO and CE lines are high

bcf PORTB,CLK ; CLK lowcall de lay_5

An a log-to-Dig i tal and Real-Time Clocks 269

Fig ure 13-11 Real-Time Clock Dem on stra tion Cir cuit.

+5V

R=

10

K

RESET

HD44780

LCD2 rows x 16

+5V

E

R/W

RS

RS

R/W

E

1

1416F84

RA2

RA3

RA4/TOCKI

MCLR

Vss

RB0/INT

RB1

RB2

RB3

1

2

3

4

5

6

7

8

9

18

17

16

15

14

13

12

11

10

RA1

RA0

OSC1

OSC2

Vdd

RB7

RB6

RB5

RB4

Osc4Mhz

+5V

32.768 kHzCrystal

NJU6355ED

+5v

1

2

3

4

8

7

6

5

+5v

DATA

CLK

CE

IO

X1

X2

GND

Page 291: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

bsf PORTB,IO ; IO highcall de lay_5bsf PORTB,CE ; CE high

; Data is stored in RTC as fol lows:; year 8 bits (0 to 99); month 8 bits (1 to 12); day 8 bits (1 to 31); dayOfWeek 4 bits (1 to 7); hour 8 bits (0 to 23); min utes 8 bits (0 to 59); ======; To tal 44 bits; Sec onds can not be writ ten to RTC. RTC sec onds reg is ter; is au to mat i cally in i tial ized to zero

movf year,w ; Get item from stor agecall bin2bcd ; Con vert to BCDmovwf temp1call writeRTC

movf month,wcall bin2bcdmovwf temp1call writeRTC

movf day,wcall bin2bcdmovwf temp1call writeRTC

movf dayOfWeek,w ; day of week is 4-bitscall bin2bcdmovwf temp1call write4RTC

movf hour,wcall bin2bcdmovwf temp1call writeRTC

movf min utes,wcall bin2bcdmovwf temp1call writeRTC

; Donebcf PORTB,CLK ; Hold CLK line lowcall de lay_5bcf PORTB,CE ; and the CE line

; to the RTC

270 Chap ter 13

Page 292: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

call de lay_5bcf PORTB,IO ; RTC in out put modere turn

;============================; write 4/8 bits to RTC;============================; Pro ce dure to write 4 or 8 bits to the RTC reg is ters; ON ENTRY:; temp1 reg is ter holds value to be writ ten; ON EXIT:; noth ingwrite4RTC

movlw .4 ; Init for 4 bitsgoto allBits

writeRTC:movlw .8 ; Init for 8 bits

allBits:movwf coun ter ; Store in bit coun ter

writeBits:bcf PORTB,CLK ; Clear the CLK linecall de lay_5 ; Wait bsf PORTB,DAT ; Set the data line to RTCbtfss temp1,0 ; Send LSBbcf PORTB,DAT ; Clear data linecall de lay_5 ; Wait for op er a tion to

com pletebsf PORTB,CLK ; Bring CLK line high to

val i daterrf temp1,f ; Ro tate bits in stor age decfsz coun ter,1 ; Dec re ment bit coun tergoto writeBits ; Con tinue if not last bitreturn

The fol low ing pro ce dures are used by the RTC2LCD pro gram to read the data inthe RTC reg is ters:

;============================; read RTC data;============================; Pro ce dure to read the cur rent time from the RTC and store; data (in packed BCD for mat) in lo cal time reg is ters.; Ac cord ing to wir ing di a gram; NJU6355 In ter face for read op er a tions:; DAT PORTB,0 In put; CLK PORTB,1 Out put; CE PORTB,2 Out put; IO PORTB,3 Out putGet_Time; Clear Port-B

An a log-to-Dig i tal and Real-Time Clocks 271

Page 293: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

movlw b’00000000’movwf PORTB

; Make data line in putBank1movlw b’00000001’movwf TRISBBank0

; Read ing RTC data re quires that the IO line be low and the; CE line be high. CLK line is held low

bcf PORTB,CLK ; CLK lowcall de lay_125bcf PORTB,IO ; IO line lowcall de lay_125bsf PORTB,CE ; and CE line high

; Data is read from RTC as fol lows:; year 8 bits (0 to 99); month 8 bits (1 to 12); day 8 bits (1 to 31); dayOfWeek 4 bits (1 to 7); hour 8 bits (0 to 23); min utes 8 bits (0 to 59); sec onds 8 bits (0 to 59); ======; To tal 52 bits;

call readRTCmovwf yearcall de lay_125

call readRTCmovwf monthcall de lay_125

call readRTCmovwf daycall de lay_125

; day of week is a 4-bit valuecall read4RTCmovwf dayOfWeekcall de lay_125

call readRTCmovwf hourcall de lay_125

call readRTCmovwf min utes

272 Chap ter 13

Page 294: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

call de lay_125

call readRTCmovwf sec ondsbcf PORTB,CE ; CE line low to end out putre turn

;============================; read 4/8 bits from RTC ;============================; Pro ce dure to read 4/8 bits stored in 6355 reg is ters; Value re turned in w reg is terread4RTC

movlw .4 ; 4 bit readgoto anyBits

readRTC:movlw .8 ; 8 bits read

anyBits:movwf coun ter

; Read 6355 read op er a tion re quires the IO line be set low; and the CE line high. Data is read in the fol low ing or der:; year, month, day, day-of-week, hour, min utes, sec ondsreadBits:

bsf PORTB,CLK; Set CLK high to val i date databsf STATUS,C ; Set the carry flag (bit = 1)

; Op er a tion:; If data line is high, then bit read is a 1-bit; oth er wise bit read is a 0-bit

btfss PORTB,DAT ; Is data line high?; Leave carry set (1 bit) if high

bcf STATUS,C ; Clear the carry bit (make bit 0); At this point the carry bit matches the data line

bcf PORTB,CLK ; Set CLK low to end read; The carry bit is now ro tated into the temp1 reg is ter

rrf temp1,1decfsz coun ter,1 ; Dec re ment the bit coun ter goto readBits ; Con tinue if not last bit

; At this point all bits have been read (8 or 4)movf temp1,0 ; Re sult to wreturn

BCD Con ver sion Pro ce dures

In ad di tion to the RTC pro ce dures to ini tial ize the clock reg is ters and to read clockdata, the ap pli ca tion re quires aux il iary pro ce dures to ma nip u late and dis play data inBCD for mat. BCD encodings are a way of rep re sent ing dec i mal dig its in bi nary form.Two com mon BCD for mats are used: packed and un packed. In the un packed for mat,

An a log-to-Dig i tal and Real-Time Clocks 273

Page 295: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

each byte en codes a sin gle BCD value. In packed form, two BCD dig its are en codedper byte. The 6355 uses the packed BCD for mat.

Be cause pro gram data is usu ally in bi nary form, it is use ful to have a rou tine tocon vert bi nary data into BCD form. A sim ple al go rithm for con vert ing bi nary to BCDis as fol lows:

1. The value 10 is sub tracted from the source op er and un til the re main der is less than0 (carry cleared). The num ber of sub trac tions is the high-or der BCD digit.

2. The value 10 is then added back to the sub tra hend to com pen sate for the last sub -trac tion.

3. The fi nal re main der is the low-or der BCD digit.

The bi nary to BCD con ver sion pro ce dure is coded as fol lows:

;============================; bi nary to BCD con ver sion;============================; Con vert a bi nary num ber into two packed BCD dig its; ON ENTRY:; w reg is ter has bi nary value in range 0 to 99; ON EXIT:; out put vari ables bcdLow and bcdHigh con tain two; un packed BCD dig its; w con tains two packed BCD dig its; Rou tine logic:; The value 10 is sub tracted from the source op er and; un til the re mainder is < 0 (carry cleared). The num ber; of sub trac tions is the high-or der BCD digit. 10 is; then added back to the sub tra hend to com pen sate; for the last sub trac tion. The fi nal re mainder is the; low-or der BCD digit; Vari ables:; inNum stor age for source op er and; bcdHigh stor age for high-or der nib ble; bcdLow stor age for low-or der nib ble; thisDig Digit coun ter bin2bcd:

movwf inNum ; Save copy of source valueclrf bcdHigh ; Clear stor ageclrf bcdLowclrf thisDig

min10:movlw .10subwf inNum,f ; Sub tract 10btfsc STATUS,C ; Did sub tract over flow?goto sum10 ; No. Count sub trac tiongoto fin10

sum10:

274 Chap ter 13

Page 296: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

incf thisDig,f ; In cre ment digit coun tergoto min10

; Store 10th digitfin10:

movlw .10addwf inNum,f ; Ad justmovf thisDig,w ; Get digit coun ter con tentsmovwf bcdHigh ; Store it

; Cal cu late and store low-or der BCD digitmovf inNum,w ; Store units valuemovwf bcdLow ; Store digit

; Com bine both dig itsswapf bcdHigh,w ; High nib ble to HOBsiorwf bcdLow,w ; ORin low nib blere turn

Be cause the pro gram re quires dis play ing val ues en coded in BCD for mat, a rou -tine is nec es sary to con vert two packed BCD dig its into two ASCII dec i mal dig its.The con ver sion logic is quite sim ple, as the BCD digit is con verted to ASCII by add -ing 0x30 to its value. All that is nec es sary is to shift bits in the packed BCD op er andso as to iso late each digit and then add 0x30 to each one. The rou tine’s code is as fol -lows:

;==============================; BCD to ASCII dec i mal; con ver sion;============================== ; ON ENTRY:; w reg is ter has two packed BCD dig its; ON EXIT:; out put vari ables asc10 and asc1 have; two ASCII dec i mal dig its; Rou tine logic:; The low or der nib ble is iso lated and the value 30H; added to con vert to ASCII. The re sult is stored in; the vari able asc1. Then the same is done to the ; high-or der nib ble and the re sult is stored in the; vari able asc10

Bcd2asc:movwf store1 ; Save in putandlw b’00001111’ ; Clear high nib bleaddlw 0x30 ; Con vert to ASCIImovwf asc1 ; Store re sultswapf store1,w ; Re cover in put and swap dig itsandlw b’00001111’ ; Clear high nib bleaddlw 0x30 ; Con vert to ASCIImovwf asc10 ; Store re sultre turn

An a log-to-Dig i tal and Real-Time Clocks 275

Page 297: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

13.6 Demonstration Pro gramsThe fol low ing subsec tions con tain the sam ple pro grams dis cussed in this chap ter.

13.6.1 ADF84 Pro gram; File name: ADCF84.asm; Last Up date: June 8, 2011; Au thors: Sanchez and Canton; Pro ces sor: 16F84A;; De scrip tion:; Pro gram to dem on strate use of the ADC0831 An a log to; Dig i tal con verter with the 16F84 PIC. Pro gram reads the; value of a potentionmeter con nected to Port-A, line 0; and dis plays re sis tance in the range 0 to 255 on the; at tached LCD.; Cir cuit:; ADC0831 16F84 CIRCUIT; PIN LINE; 6 DO ------------- RB0; 7 CLK ------------- RB1; 1 CS ------------- RB2; 2 Vin+ ------------------------------ POT2; 3 Vin- ------------------------------ GND; 5 Vref ------------------------------ +5v; 8 Vcc ------------------------------ +5v;; For LCD dis play pa ram e ters see the LCDTest2 pro gram. ; WARNING:; Code as sumes 4 MHz clock. De lay rou tines must be; ed ited for faster clock;;===========================; switches;===========================; Switches used in __config di rec tive:; _CP_ON Code pro tec tion ON/OFF ; * _CP_OFF ; * _PWRTE_ON Power-up timer ON/OFF; _PWRTE_OFF ; _WDT_ON Watch dog timer ON/OFF ; * _WDT_OFF ; _LP_OSC Low power crys tal os cil la tor; * _XT_OSC Ex ter nal par al lel res o na tor/crys tal os cil la tor

; _HS_OSC High speed crys tal res o na tor (8 to 10 MHz); Res o na tor: Murate Erie CSA8.00MG = 8 MHz ; _RC_OSC Re sis tor/ca pac i tor os cil la tor

276 Chap ter 13

Page 298: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; | (sim plest, 20% er ror); |; |_____ * in di cates setup val ues pres ently se lected

;=========================; setup and con fig u ra tion;=========================

pro ces sor 16f84Ain clude <p16f84A.inc>__config _XT_OSC & _WDT_OFF & _PWRTE_ON & _CP_OFF

errorlevel -302; Sup press bank-re lated warn ing;============================================================; M A C R O S;============================================================; Macros to se lect the reg is ter banks in 16F84Bank0 MACRO ; Se lect RAM bank 0

bcf STATUS,RP0ENDM

Bank1 MACRO ; Se lect RAM bank 1bsf STATUS,RP0ENDM

;=====================================================; con stant def i ni tions; for PIC-to-LCD pin wir ing and LCD line ad dresses;=====================================================#de fine E_line 1 ;|#de fine RS_line 2 ;| => from cir cuit wir ing di a gram #de fine RW_line 3 ;|; LCD line ad dresses (from LCD data sheet)#de fine LCD_1 0x80 ; First LCD line con stant#de fine LCD_2 0xc0 ; Sec ond LCD line con stant; Note: The con stants that de fine LCD dis play line; ad dresses have the high-or der bit set in; or der to fa cil i tate the con trol ler com mand

; De fines from ADC0831 wir ing di a gram; all lines in Port-A#de fine DO 0 ;|#de fine CLK 1 ;| => from cir cuit wir ing di a gram#de fine CS 2 ;|;;=====================================================; vari ables in PIC RAM;=====================================================; Re serve 16 bytes for string buffer

An a log-to-Dig i tal and Real-Time Clocks 277

Page 299: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

cblock 0x0cstrDataendc

; Re serve three bytes for ASCII dig itscblock 0x1dasc100asc10asc1 endc

; Con tinue with lo cal vari ablescblock 0x20 ; Start of blockcount1 ; Coun ter # 1count2 ; Coun ter # 2count3 ; Coun ter # 3pic_ad ; Stor age for start of text areaJ ; Coun ter JK ; Coun ter Kin dex ; In dex into text ta ble (also used

; for aux il iary stor age)store1 ; Lo cal tem po rary stor age store2 ; Stor age # 2rcvdata ; Re ceived databitCount

; Stor age for ASCII dec i mal con ver sion and dig itsinNum ; Source op er andthisDig ; Digit coun terendc

;=========================================================; pro gram;=========================================================

org 0 ; start at ad dress goto main

; Space for in ter rupt han dlersorg 0x08

main:Bank1movlw b’00000000’ ; All lines to out putmovwf TRISA ; in Port-Amovlw b’00000001’ ; B line 0 to in putmovwf TRISBBank0movlw b’00000000’ ; All out puts ports lowmovwf PORTAmovwf PORTB

; Wait and ini tial ize HD44780call de lay_5 ; Al low LCD time to ini tial ize

; it self

278 Chap ter 13

Page 300: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

call de lay_5call initLCD ; Then do forced

ini tial iza tioncall de lay_5 ; Wait again

; Store base ad dress of text buffer in PIC RAMmovlw 0x0c ; Start ad dress for buffermovwf pic_ad ; to lo cal vari able

;======================; first LCD line;======================; Store 16 blanks in PIC RAM, start ing at ad dress stored; in vari able pic_ad

call blank16; Call pro ce dure to store ASCII char ac ters for mes sage; in text buffer

movlw d’0’ ; Off set into buffercall storeMS1 ; Store mes sage text in buffer

; Ini tial ize ADC0831nextAna:

call ana2dig ; Read an a log linecall de lay_125

; Dis play re sultmovf rcvdata,wcall bin2asc ; Con ver sion rou tine

; At this point three ASCII dig its are stored in lo cal; vari ables. Move dig its to dis play area

movf asc1,w ; Unit digitmovwf .26 ; Store in buffermovf asc10,w ; same with other dig itsmovwf .25movf asc100,wmovwf .24

; Dis play line; Set DDRAM ad dress to start of first line

call line1; Call pro ce dure to dis play 16 char ac ters in LCD

call display16 call long_de laygoto nextAna

;============================================================; ini tial ize LCD for 4-bit mode ;============================================================initLCD:; Ini tial iza tion for Densitron LCD mod ule as fol lows:; 4-bit in ter face; 2 dis play lines of 16 char ac ters each; cur sor on

An a log-to-Dig i tal and Real-Time Clocks 279

Page 301: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; left-to-right in cre ment; cur sor shift right; no dis play shift;=======================|; set com mand mode |;=======================|

bcf PORTA,E_line ; E line lowbcf PORTA,RS_line ; RS line lowbcf PORTA,RW_line ; Write modecall de lay_125 ; de lay 125 mi cro sec onds

;***********************|; FUNCTION SET |;***********************|

movlw 0x28 ; 0 0 1 0 1 0 0 0 (FUNCTION SET)call send8 ; 4-bit send rou tine

; Set 4-bit mode com mand must be re peatedmovlw 0x28call send8

;***********************|; DISPLAY AND CURSOR ON |;***********************|

movlw 0x0e ; 0 0 0 0 1 1 1 0 (DISPLAY ON/OFF)call send8

;***********************|; set en try mode |;***********************|

movlw 0x06 ; 0 0 0 0 0 1 1 0 (ENTRY MODE SET)call send8

;;***********************|; cur sor/dis play shift |;***********************|

movlw 0x14 ; 0 0 0 1 0 1 0 0 (CURSOR/DISPLAY ; SHIFT)

call send8;***********************|; clear dis play |;***********************|

movlw 0x01 ; 0 0 0 0 0 0 0 1 (CLEAR DISPLAY)call send8

; Per doc u men ta tioncall de lay_5 ; Test for busyre turn

;;=======================; Pro ce dure to de lay

280 Chap ter 13

Page 302: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; 42 mi cro sec onds;=======================de lay_125:

movlw D’42’ ; Re peat 42 ma chine cy clesmovwf count1 ; Store value in coun ter

re peat:decfsz count1,f ; Dec re ment coun tergoto re peat ; Con tinue if not 0re turn ; End of de lay

;=======================; Pro ce dure to de lay; 5 mil li sec onds;=======================de lay_5:

movlw D’41’ ; Coun ter = 41movwf count2 ; Store in vari able

de lay:call de lay_125 ; De laydecfsz count2,f ; 40 times = 5 mil li sec ondsgoto de layre turn ; End of de lay

;========================; pulse E line ;========================pulseE:

bsf PORTA,E_line ; Pulse E linenopbcf PORTA,E_linere turn

;=============================; long de lay sub-rou tine; (for de bug ging);=============================long_de lay:

movlw D’200’ ; w = 200 dec i malmovwf J ; J = w

jloop:movwf K ; K = w

kloop:decfsz K,f ; K = K-1, skip next if zerogoto kloopdecfsz J,f ; J = J-1, skip next if zerogoto jloopre turn

;=============================; LCD dis play pro ce dure

An a log-to-Dig i tal and Real-Time Clocks 281

Page 303: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

;=============================; Sends 16 char ac ters from PIC buffer with ad dress stored; in vari able pic_ad to LCD line pre vi ously se lecteddisplay16

call de lay_5 ; Make sure not busy; Set up for data

bcf PORTA,E_line ; E line lowbsf PORTA,RS_line ; RS line high for data

; Set up coun ter for 16 char ac tersmovlw D’16’ ; Coun ter = 16movwf count3

; Get dis play ad dress from lo cal vari able pic_admovf pic_ad,w ; First dis play RAM ad dress to Wmovwf FSR ; W to FSR

getchar:movf INDF,w ; get char ac ter from dis play RAM

; lo ca tion pointed to by file se lect; reg is ter

call send8 ; 4-bit in ter face rou tine; Test for 16 char ac ters dis played

decfsz count3,f ; Dec re ment coun tergoto nextchar ; Skipped if donere turn

nextchar:incf FSR,f ; Bump pointergoto getchar

;========================; send 2 nib bles in; 4-bit mode;========================; Pro ce dure to send two 4-bit val ues to Port-B lines; 7, 6, 5, and 4. High-or der nib ble is sent first; ON ENTRY:; w reg is ter holds 8-bit value to sendsend8:

movwf store1 ; Save orig i nal valuecall merge4 ; Merge with Port-B

; Now w has merged bytemovwf PORTB ; w to Port-Bcall pulseE ; Send data to LCD

; High nib ble is sentmovf store1,w ; Re cover byte into wswapf store1,w ; Swap nib bles in wcall merge4movwf PORTBcall pulseE ; Send data to LCDcall de lay_125

282 Chap ter 13

Page 304: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

re turn;=================; merge bits;=================; Rou tine to merge the 4 high-or der bits of the; value to send with the con tents of Port-B; so as to pre serve the 4 low-bits in Port-B; Logic:; AND value with 1111 0000 mask; AND Port-B with 0000 1111 mask; Now low nib ble in value and high nib ble in; Port-B are all 0 bits:; value = vvvv 0000; Port-B = 0000 bbbb; OR value and Port-B re sult ing in:; vvvv bbbb ; ON ENTRY:; w con tain value bits; ON EXIT:; w con tains merged bitsmerge4:

andlw b’11110000’ ; ANDing with 0 clears the; bit. ANDing with 1 pre serves; the orig i nal value

movwf store2 ; Save re sult in vari ablemovf PORTB,w ; Port-B to w reg is terandlw b’00001111’ ; Clear high nib ble in Port-b

; and pre serve low nib bleiorwf store2,w ; OR two operands in wre turn

;========================; blank buffer;========================; Pro ce dure to store 16 blank char ac ters in PIC RAM; buffer start ing at ad dress stored in the vari able; pic_adblank16:

movlw D’16’ ; Setup coun termovwf count1movf pic_ad,w ; First PIC RAM ad dressmovwf FSR ; In dexed ad dress ingmovlw 0x20 ; ASCII space char ac ter

storeit:movwf INDF ; Store blank char ac ter in PIC

RAM; buffer us ing FSR reg is ter

decfsz count1,f ; Done?

An a log-to-Dig i tal and Real-Time Clocks 283

Page 305: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

goto incfsr ; nore turn ; yes

incfsr:incf FSR,f ; Bump FSR to next buffer

; spacegoto storeit

;========================; Set ad dress reg is ter; to LCD line 1;========================; ON ENTRY:; Ad dress of LCD line 1 in con stant LCD_1 line1:

bcf PORTA,E_line ; E line lowbcf PORTA,RS_line ; RS line low, setup for

; con trolcall de lay_5 ; busy?

; Set to sec ond dis play linemovlw LCD_1 ; Ad dress and com mand bitcall send8 ; 4-bit rou tine

; Set RS line for databsf PORTA,RS_line ; Setup for datacall de lay_5 ; Busy?re turn

;===============================; first text string pro ce dure;===============================storeMS1:; Pro ce dure to store in PIC RAM buffer the mes sage; con tained in the code area la beled msg1; ON ENTRY:; vari able pic_ad holds ad dress of text buffer; in PIC RAM; w reg is ter holds off set into stor age area; msg1 is rou tine that re turns the string char ac ters; and a zero ter mi na tor; in dex is lo cal vari able that holds off set into; text ta ble. This vari able is also used for; tem po rary stor age of off set into buffer ; ON EXIT:; Text mes sage stored in buffer;; Store off set into text buffer (passed in the w reg is ter); in tem po rary vari able

movwf in dex ; Store w in in dex; Store base ad dress of text buffer in FSR

284 Chap ter 13

Page 306: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

movf pic_ad,w ; first dis play RAM ad dress to Waddwf in dex,w ; Add off set to ad dressmovwf FSR ; W to FSR

; Ini tial ize in dex for text string ac cessmovlw 0 ; Start at 0movwf in dex ; Store in dex in vari able

; w still = 0get_msg_char:

call msg1 ; Get char ac ter from ta ble; Test for zero ter mi na tor

andlw 0x0ffbtfsc STATUS,Z ; Test zero flaggoto endstr1 ; End of string

; ASSERT: valid string char ac ter in w; store char ac ter in text buffer (by FSR)

movwf INDF ; store in buffer by FSRincf FSR,f ; in cre ment buffer pointer

; Re store ta ble char ac ter coun ter from vari ablemovf in dex,w ; Get value into waddlw 1 ; Bump to next char ac termovwf in dex ; Store ta ble in dex in

vari ablegoto get_msg_char ; Con tinue

endstr1:re turn

; Rou tine for re turn ing mes sage stored in pro gram area; Mes sage has 10 char ac tersmsg1:

addwf PCL,f ; Ac cess ta bleretlw ‘P’retlw ‘o’retlw ‘t’retlw ‘ ‘retlw ‘R’retlw ‘e’retlw ‘s’retlw ‘i’retlw ‘s’retlw ‘t’retlw ‘:’retlw 0

;==============================; bi nary to ASCII dec i mal; con ver sion;============================== ; ON ENTRY:; w reg is ter has bi nary value in range 0 to 255

An a log-to-Dig i tal and Real-Time Clocks 285

Page 307: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; ON EXIT:; out put vari ables asc100, asc10, and asc1 have; three ASCII dec i mal dig its; Rou tine logic:; The value 100 is sub tracted from the source op er and; un til the re mainder is < 0 (carry cleared.) The num ber; of sub trac tions is the dec i mal hun dreds re sult. 100 is; then added back to the sub tra hend to com pen sate; for the last sub trac tion. Now 10 is sub tracted in the; same man ner to de ter mine the dec i mal tenths re sult.; The fi nal re mainder is the dec i mal units re sult.; Vari ables:; inNum stor age for source op er and; asc100 stor age for hun dreds po si tion re sult; asc10 stor age for tenth po si tion re sult; asc1 stor age for unit po si tion re sult; thisDig Digit coun ter bin2asc:

movwf inNum ; Save copy of source valueclrf asc100 ; Clear hun dreds stor ageclrf asc10 ; Tensclrf asc1 ; Unitsclrf thisDig

sub100:movlw .100subwf inNum,f ; Sub tract 100btfsc STATUS,C ; Did sub tract over flow?goto bump100 ; No. Count sub trac tiongoto end100

bump100:incf thisDig,f ;in cre ment digit coun tergoto sub100

; Store 100th digitend100:

movf thisDig,w ; Ad justed digit coun teraddlw 0x30 ; Con vert to ASCIImovwf asc100 ; Store it

; Cal cu late tenth po si tion valueclrf thisDig

; Ad just min u endmovlw .100 ; Min u endaddwf inNum,f ; Add value to min u end to

; com pen sate for lastop er a tionsub10:

movlw .10subwf inNum,f ; Sub tract 10btfsc STATUS,C ; Did sub tract over flow?

286 Chap ter 13

Page 308: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

goto bump10 ; No. Count sub trac tiongoto end10

bump10:incf thisDig,f ;in cre ment digit coun tergoto sub10

; Store 10th digitend10:

movlw .10addwf inNum,f ; Ad just for last subratctmovf thisDig,w ; get digit coun ter con tentsaddlw 0x30 ; Convert to ASCIImovwf asc10 ; Store it

; Cal cu late and store units digitmovf inNum,w ; Store units valueaddlw 0x30 ; Convert to ASCIImovwf asc1 ; Store digitre turn

;==========================================================; ADC0831 pro ce dures;==========================================================;============================; pro ce dure to read and; con vert an a log line;============================; ON ENTRY:; Code as sumes that the ADC0831 DO line is in i tial ized for; in put, while CLK and CS lines are out put ; From ADC0831 wir ing di a gram. All lines in Port-B; DO = RB0 ==> INPUT ; CLK = RB1 <== OUTPUT; CS = RB2 <== OUTPUT; ON EXIT:; Re turns 8-bit dig i tal value in the reg is ter rcvdata;ana2dig:; Clear data reg is ter and init coun ter for 8 bits

clrf rcvdata ; Clear reg is termovlw 0x08 ; Ini tial ize coun termovwf bitCount

; Pre pare to read an a log linebcf PORTB,CS ; CS pin low to en able ADCnop ; De lay for 4 MHz clockbsf PORTB,CLK ; Set CLK highnopbcf PORTB,CLK ; Re set CLK to start

; con ver sionnop

An a log-to-Dig i tal and Real-Time Clocks 287

Page 309: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

nextB:; Pulse CLK line to read bit from ADC

bsf PORTB,CLK ; CLK highnopbcf PORTB,CLK ; CLK lownop

; Read an a log line and store data, bit by bitmovf PORTB,w ; Read all Port-B bitsmovwf store1 ; Store value for laterrrf store1,f ; Ro tate bit into carry flagrlf rcvdata,f ; Ro tate carry flag into

re sult; reg is ter

decfsz bitCount,f ; Bump coun ter, skip next; if coun ter zero

goto nextB; Value read is stored in rcvdata reg is ter

bsf PORTB,CLK ; Fi nal clock pulsenopbcf PORTB,CLKnopbsf PORTB,CS ; Turn off ADCcall long_de lay ; Time to set tlere turn

end

13.6.2 A2DinLCD Pro gram; File name: A2DinLCD.asm; Last re vi sion: June 2, 2011; Au thors: Sanchez and Canton; Pro ces sor: 16F877;; De scrip tion:; Pro gram to dem on strate use of the An a log to Dig i tal; Con verter (A/D) mod ule on the 16F877. Pro gram reads the; value of a potentionmeter con nected to Port-A, line 0; and dis plays re sis tance in the range 0 to 255 on the; at tached LCD.; ; WARNING:; Code as sumes 10 MHz clock. De lay rou tines must be; ed ited for faster clock. Clock speed is also used to; set up the A/D con verter clock.;;===========================; 16F877 switches

288 Chap ter 13

Page 310: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

;===========================; Switches used in __config di rec tive:; _CP_ON Code pro tec tion ON/OFF ; * _CP_OFF ; * _PWRTE_ON Power-up timer ON/OFF; _PWRTE_OFF ; _BODEN_ON Brown-out re set en able ON/OFF; * _BODEN_OFF ; * _PWRTE_ON Power-up timer en able ON/OFF; _PWRTE_OFF ; _WDT_ON Watch dog timer ON/OFF ; * _WDT_OFF; _LPV_ON Low volt age IC pro gram ming en able ON/OFF; * _LPV_OFF; _CPD_ON Data EE mem ory code pro tec tion ON/OFF; * _CPD_OFF; OSCILLATOR CONFIGURATIONS: ; _LP_OSC Low power crys tal os cil la tor; _XT_OSC Ex ter nal par al lel res o na tor/crys tal os cil la tor

; * _HS_OSC High speed crys tal res o na tor; _RC_OSC Re sis tor/ca pac i tor os cil la tor; | (sim plest, 20% er ror); |; |_____ * in di cates setup val ues pres ently se lected

pro ces sor 16f877 ; De fine pro ces sor#in clude <p16f877.inc>__CONFIG _CP_OFF & _WDT_OFF & _BODEN_OFF & _PWRTE_ON &

_HS_OSC & _WDT_OFF & _LVP_OFF & _CPD_OFF; __CONFIG di rec tive is used to em bed con fig u ra tion data; within the source file. The la bels fol low ing the di rec tive; are lo cated in the cor re spond ing .inc file.

errorlevel -302; Sup press bank-re lated warn ing ;============================================================; M A C R O S;============================================================; Macros to se lect the reg is ter banksBank0 MACRO ; Se lect RAM bank 0

bcf STATUS,RP0bcf STATUS,RP1ENDM

Bank1 MACRO ; Se lect RAM bank 1bsf STATUS,RP0bcf STATUS,RP1

An a log-to-Dig i tal and Real-Time Clocks 289

Page 311: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

ENDM

Bank2 MACRO ; Se lect RAM bank 2bcf STATUS,RP0bsf STATUS,RP1ENDM

Bank3 MACRO ; Se lect RAM bank 3bsf STATUS,RP0bsf STATUS,RP1ENDM

;=====================================================; con stant def i ni tions; for PIC-to-LCD pin wir ing and LCD line ad dresses;=====================================================#de fine E_line 1 ;|#de fine RS_line 0 ;| => from wir ing di a gram #de fine RW_line 2 ;|; LCD line ad dresses (from LCD data sheet)#de fine LCD_1 0x80 ; First LCD line con stant#de fine LCD_2 0xc0 ; Sec ond LCD line con stant#de fine LCDlimit .20; Num ber of char ac ters per line#de fine spbrgVal .64; For 2400 baud on 10-MHz clock; Note: The con stants that de fine the LCD dis play; line ad dresses have the high-or der bit set; so as to meet the re quire ments of con trol ler; com mands.;=====================================================; vari ables in PIC RAM;=====================================================; Re serve 20 bytes for string buffer

cblock 0x20strDataendc

; Re serve three bytes for ASCII dig itscblock 0x34asc100asc10asc1 endc

; Datacblock 0x37 ; Start of blockcount1 ; Coun ter # 1count2 ; Coun ter # 2count3 ; Coun ter # 3pic_ad

290 Chap ter 13

Page 312: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

J ; coun ter JK ; coun ter Kin dexstore1 ; Lo cal stor agestore2

; For LCDscroll pro ce dureLCDcount ; Coun ter for char ac ters per lineLCDline ; Cur rent dis play line (0 or 1)endc

; Com mon RAM area for most crit i cal vari ablescblock 0x70

; Stor age for ASCII dec i mal con ver sion and dig itsinNum ; Source op er andthisDig ; Digit coun terendc

;============================================================; P R O G R A M;============================================================

org 0 ; start at ad dress goto main

; Space for in ter rupt han dlersorg 0x08

main:; Wiring:; LCD data to Port-D, lines 0 to 7; E line -> Port-E, 1; RW line -> Port-E, 2; RS line -> Port-E, 0; Set PORTE D and E for out put; First, ini tial ize Port-B by clear ing latches

clrf STATUSclrf PORTB

; Se lect bank 1 to tris Port-D for out putBank1

; Tris Port-D for out put. Port-D lines 4 to 7 are wired; to LCD data lines. Port-D lines 0 to 4 are wired to LEDs.

movlw B’00000000’movwf TRISD ; and Port-D

; By de fault Port-A lines are an a log. To con fig ure them; as dig i tal code must set bits 1 and 2 of the ADCON1; reg is ter (in bank 1)

movlw 0x06 ; bi nary 0000 0110 is code to; make all Port-A lines

dig i talmovwf ADCON1

; Port-B, lines are not used by this ap pli ca tion. Init

An a log-to-Dig i tal and Real-Time Clocks 291

Page 313: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; to out putmovlw b’00000000’movwf TRISB

; Tris Port-E for out put. LCD lines are in Port-Emovwf TRISE ; Tris Port-E

; En able Port-B pullups for switches in OPTION reg is ter; 7 6 5 4 3 2 1 0 <= OPTION bits; | | | | | |__|__|_____ PS2-PS0 (prescaler bits); | | | | | Values for Timer0; | | | | | 000 = 1:2 001 = 1:4; | | | | | 010 = 1:8 011 = 1:16; | | | | | 100 = 1:32 101 = 1:64; | | | | | 110 = 1:128 *111 = 1:256; | | | | |______________ PSA (prescaler as sign); | | | | *1 = to WDT; | | | | 0 = to Timer0; | | | |_________________ TOSE (Timer0 edge se lect); | | | *0 = in cre ment on low-to-high; | | | 1 = in cre ment on high-to-low; | | |____________________ TOCS (TMR0 clock source); | | *0 = in ter nal clock; | | 1 = RA4/TOCKI bit source; | |_______________________ INTEDG (Edge se lect); | *0 = fall ing edge; |__________________________ RBPU (Pullup en able); *0 = en abled; 1 = dis abled

movlw b’00001000’movwf OPTION_REG

; Back to bank 0Bank0

; Clear all out put linesmovlw b’00000000’ movwf PORTDmovwf PORTE

; Wait and ini tial ize HD44780call de lay_5 ; Al low LCD time to ini tial ize

it selfcall initLCD ; Then do forced

ini tial iza tioncall de lay_5 ; (Wait prob a bly not

nec es sary); Clear char ac ter coun ter and line coun ter vari ables

clrf LCDcountclrf LCDline

; Ini tial ize A/D con ver sion linescall InitA2D ; Lo cal pro ce dure

; Store base ad dress of text buffer in PIC RAM

292 Chap ter 13

Page 314: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

movlw 0x20 ; Start ad dress for buffermovwf pic_ad ; to lo cal vari able

; Store 20 blanks in PIC RAM, start ing at ad dress stored; in vari able pic_ad

call blank20; Call pro ce dure to store ASCII char ac ters for mes sage; in text buffer

movlw d’0’ ; Off set into buffercall storeMS1

;============================; read POT dig i tal value;============================readPOT:

call ReadA2D ; Lo cal pro ce dure; w has dig i tal value read from an a log line RA0; Dis play re sult

call bin2asc ; Con ver sion rou tine; At this point three ASCII dig its are stored in lo cal; vari ables. Move dig its to dis play area

movf asc1,w ; Unit digitmovwf 0x2e ; Store in buffermovf asc10,w ; same with other dig itsmovwf 0x2dmovf asc100,wmovwf 0x2c

; Dis play line; Set DDRAM ad dress to start of first lineshowLine:

call line1; Call pro ce dure to dis play 16 char ac ters in LCD

call display20 goto readPOT

;============================================================;============================================================; L O C A L P R O C E D U R E S ;============================================================;============================================================;==========================; init LCD for 4-bit mode ;==========================initLCD:; Ini tial iza tion for Densitron LCD mod ule as fol lows:; 4-bit in ter face; 2 dis play lines of 20 char ac ters each; cur sor on; left-to-right in cre ment; cur sor shift right

An a log-to-Dig i tal and Real-Time Clocks 293

Page 315: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; no dis play shift;=======================|; set com mand mode |;=======================|

bcf PORTE,E_line ; E line lowbcf PORTE,RS_line ; RS line lowbcf PORTE,RW_line ; Write modecall de lay_125 ; de lay 125 mi cro sec onds

;***********************|; FUNCTION SET |;***********************|

movlw 0x28 ; 0 0 1 0 1 0 0 0 (FUNCTION SET)call send8 ; 4-bit send rou tine

; Set 4-bit mode com mand must be re peatedmovlw 0x28call send8

;***********************|; DISPLAY AND CURSOR ON |;***********************|

movlw 0x0e ; 0 0 0 0 1 1 1 0 (DISPLAY ON/OFF)call send8

;***********************|; set en try mode |;***********************|

movlw 0x06 ; 0 0 0 0 0 1 1 0 (ENTRY MODE SET)call send8

;***********************|; cur sor/dis play shift |;***********************|

movlw 0x14 ; 0 0 0 1 0 1 0 0 (CURSOR/DISPLAYSHIFT)

call send8;***********************|; clear dis play |;***********************|

movlw 0x01 ; 0 0 0 0 0 0 0 1 (CLEAR DISPLAY)call send8

; Per doc u men ta tioncall de lay_5 ; Test for busyre turn

;=======================; Pro ce dure to de lay; 125ms. at 10 MHz;=======================de lay_125:

movlw .110 ; Re peat 110 ma chine cy cles

294 Chap ter 13

Page 316: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

movwf count1 ; Store value in coun terre peat:

decfsz count1,f ; Dec re ment coun tergoto re peat ; Con tinue if not 0re turn ; End of de lay

;=======================; Pro ce dure to de lay; 5 mil li sec onds;=======================de lay_5:

movlw .110 ; Coun ter = 110movwf count2 ; Store in vari able

de lay:call de lay_125 ; De laydecfsz count2,f ; 40 times = 5 mil li sec ondsgoto de layre turn ; End of de lay

;========================; pulse E line ;========================pulseE:

bsf PORTE,E_line ; Pulse E linenopbcf PORTE,E_linere turn

;=============================; long de lay sub-rou tine;=============================long_de lay:

movlw .200 ; w de lay countmovwf J ; J = w

jloop:movwf K ; K = w

kloop:decfsz K,f ; K = K-1, skip next if zerogoto kloopdecfsz J,f ; J = J-1, skip next if zerogoto jloopre turn

;=============================; dis play buffer on LCD;=============================; Sends 20 char ac ters from PIC buffer with ad dress stored; in vari able pic_ad to LCD line pre vi ously se lecteddisplay20:

An a log-to-Dig i tal and Real-Time Clocks 295

Page 317: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

call de lay_5 ; Make sure not busy; Set up for data

bcf PORTA,E_line ; E line lowbsf PORTA,RS_line ; RS line high for data

; Set up coun ter for 20 char ac tersmovlw D’20’movwf count3

; Get dis play ad dress from lo cal vari able pic_admovf pic_ad,w ; First dis play RAM ad dress to Wmovwf FSR ; W to FSR

getcharmovf INDF,w ; get char ac ter from dis play RAM

; lo ca tion pointed to by file se lect; reg is ter

call send8 ; 4-bit in ter face rou tine; Test for 16 char ac ters dis played

decfsz count3,f ; Dec re ment coun tergoto nextchar ; Skipped if donere turn

nextchar:incf FSR,f ; Bump pointergoto getchar

;========================; send 2 nib bles in; 4-bit mode;========================; Pro ce dure to send two 4-bit val ues to Port-B lines; 7, 6, 5, and 4. High-or der nib ble is sent first; ON ENTRY:; w reg is ter holds 8-bit value to sendsend8:

movwf store1 ; Save orig i nal valuecall merge4 ; Merge with Port-B

; Now w has merged bytemovwf PORTD ; w to Port-Dcall pulseE ; Send data to LCD

; High nib ble is sentmovf store1,w ; Re cover byte into wswapf store1,w ; Swap nib bles in wcall merge4movwf PORTDcall pulseE ; Send data to LCDcall de lay_125re turn

;==========================; merge bits;==========================

296 Chap ter 13

Page 318: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; Rou tine to merge the 4 high-or der bits of the; value to send with the con tents of Port-B; so as to pre serve the 4 low-bits in Port-B; Logic:; AND value with 1111 0000 mask; AND Port-B with 0000 1111 mask; Now low nib ble in value and high nib ble in; Port-B are all 0 bits:; value = vvvv 0000; Port-B = 0000 bbbb; OR value and Port-B re sult ing in:; vvvv bbbb ; ON ENTRY:; w con tain value bits; ON EXIT:; w con tains merged bitsmerge4:

andlw b’11110000’ ; ANDing with 0 clears the; bit. ANDing with 1 pre serves; the orig i nal value

movwf store2 ; Save re sult in vari ablemovf PORTD,w ; Port-D to w reg is terandlw b’00001111’ ; Clear high nib ble in Port-b

; and pre serve low nib bleiorwf store2,w ; OR two operands in wre turn

;==========================; Set ad dress reg is ter; to LCD line 1;==========================; ON ENTRY:; Ad dress of LCD line 1 in con stant LCD_1 line1:

bcf PORTE,E_line ; E line lowbcf PORTE,RS_line ; RS line low, setup for

; con trolcall de lay_5 ; busy?

; Set to sec ond dis play linemovlw LCD_1 ; Ad dress and com mand bitcall send8 ; 4-bit rou tine

; Set RS line for databsf PORTE,RS_line ; Setup for datacall de lay_5 ; Busy?re turn

;===============================; first text string pro ce dure;===============================storeMS1:

An a log-to-Dig i tal and Real-Time Clocks 297

Page 319: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; Pro ce dure to store in PIC RAM buffer the mes sage; con tained in the code area la beled msg1; ON ENTRY:; vari able pic_ad holds ad dress of text buffer; in PIC RAM; w reg is ter holds off set into stor age area; msg1 is rou tine that re turns the string char ac ters; and a zero ter mi na tor; in dex is lo cal vari able that holds off set into; text ta ble. This vari able is also used for; tem po rary stor age of off set into buffer ; ON EXIT:; Text mes sage stored in buffer;; Store off set into text buffer (passed in the w reg is ter); in tem po rary vari able

movwf in dex ; Store w in in dex; Store base ad dress of text buffer in FSR

movf pic_ad,w ; first dis play RAM ad dress to Waddwf in dex,w ; Add off set to ad dressmovwf FSR ; W to FSR

; Ini tial ize in dex for text string ac cessmovlw 0 ; Start at 0movwf in dex ; Store in dex in vari able

; w still = 0get_msg_char:

call msg1 ; Get char ac ter from ta ble; Test for zero ter mi na tor

andlw 0x0ffbtfsc STATUS,Z ; Test zero flaggoto endstr1 ; End of string

; ASSERT: valid string char ac ter in w; store char ac ter in text buffer (by FSR)

movwf INDF ; store in buffer by FSRincf FSR,f ; in cre ment buffer pointer

; Re store ta ble char ac ter coun ter from vari ablemovf in dex,w ; Get value into waddlw 1 ; Bump to next char ac termovwf in dex ; Store ta ble in dex in vari ablegoto get_msg_char ; Con tinue

endstr1:re turn

; Rou tine for re turn ing mes sage stored in pro gram area; Mes sage has 10 char ac tersmsg1:

addwf PCL,f ; Ac cess ta bleretlw ‘P’retlw ‘o’

298 Chap ter 13

Page 320: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

retlw ‘t’retlw ‘ ‘retlw ‘R’retlw ‘e’retlw ‘s’retlw ‘i’retlw ‘s’retlw ‘t’retlw ‘:’retlw 0

;========================; blank buffer;========================; Pro ce dure to store 20 blank char ac ters in PIC RAM; buffer start ing at ad dress stored in the vari able; pic_adblank20:

movlw D’20’ ; Setup coun termovwf count1movf pic_ad,w ; First PIC RAM ad dressmovwf FSR ; In dexed ad dress ingmovlw 0x20 ; ASCII space char ac ter

storeit:movwf INDF ; Store blank char ac ter in PIC RAM

; buffer us ing FSR reg is terdecfsz count1,f ; Done?goto incfsr ; nore turn ; yes

incfsr:incf FSR,f ; Bump FSR to next buffer spacegoto storeit

;==============================; bi nary to ASCII dec i mal; con ver sion;============================== ; ON ENTRY:; w reg is ter has bi nary value in range 0 to 255; ON EXIT:; out put vari ables asc100, asc10, and asc1 have; three ASCII dec i mal dig its; Rou tine logic:; The value 100 is sub tracted from the source op er and; un til the re mainder is < 0 (carry cleared). The num ber; of sub trac tions is the dec i mal hun dreds re sult. 100 is; then added back to the sub tra hend to com pen sate; for the last sub trac tion. Now 10 is subtracted in the; same man ner to de ter mine the dec i mal tenths re sult.

An a log-to-Dig i tal and Real-Time Clocks 299

Page 321: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; The fi nal re mainder is the dec i mal units re sult.; Vari ables:; inNum stor age for source op er and; asc100 stor age for hun dreds po si tion re sult; asc10 stor age for tens po si tion re sult; asc1 stor age for unit po si tion reslt; thisDig Digit coun ter bin2asc:

movwf inNum ; Save copy of source valueclrf asc100 ; Clear hun dreds stor ageclrf asc10 ; Tensclrf asc1 ; Unitsclrf thisDig

sub100:movlw .100subwf inNum,f ; Sub tract 100btfsc STATUS,C ; Did sub tract over flow?goto bump100 ; No. Count sub trac tiongoto end100

bump100:incf thisDig,f ; In cre ment digit coun tergoto sub100

; Store 100th digitend100:

movf thisDig,w ; Ad justed digit coun teraddlw 0x30 ; Con vert to ASCIImovwf asc100 ; Store it

; Cal cu late tenth po si tion valueclrf thisDig

; Ad just min u endmovlw .100 ; Min u endaddwf inNum,f ; Add value to min u end to

; Com pen sate for last op er a tionsub10:

movlw .10subwf inNum,f ; Sub tract 10btfsc STATUS,C ; Did sub tract over flow?goto bump10 ; No. Count sub trac tiongoto end10

bump10:incf thisDig,f ;in cre ment digit coun tergoto sub10

; Store 10th digitend10:

movlw .10addwf inNum,f ; Ad just for last subractionmovf thisDig,w ; get digit coun ter con tentsaddlw 0x30 ; Convert to ASCII

300 Chap ter 13

Page 322: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

movwf asc10 ; Store it; Cal cu late and store units digit

movf inNum,w ; Store units valueaddlw 0x30 ; Con vert to ASCIImovwf asc1 ; Store digitre turn

;============================================================; An a log to Dig i tal Pro ce dures;============================================================;============================; init A/D mod ule;============================; 1. Pro ce dure to ini tial ize the A/D mod ule, as fol lows:; Con fig ure the PIC I/O lines. Init an a log lines as in put.; 2. Se lect ports to be used by set ting the PCFGx bits in the; ADCON1 reg is ter. Se lect right- or left-jus ti fi ca tion.; 3. Se lect the an a log chan nels, se lect the A/D con ver sion; clock, and en able the A/D mod ule.; 4. Wait the ac qui si tion time.; 5. Ini ti ate the con ver sion by set ting the GO/DONE bit in the; ADCON0 reg is ter. ; 6. Wait for the con ver sion to com plete.; 7. Read and store the dig i tal re sult.InitA2D:

Bank1 ; Se lect bank for TRISA reg is termovlw b’00000001’movwf TRISA ; Set Port-A, line 0, as in put

; Se lect the for mat and A/D port con fig u ra tion bits in; the ADCON1 reg is ter; For mat is left-jus ti fied so that ADRESH bits are the; most sig nif i cant; 0 x x x 1 1 1 0 <== value in stalled in ADCON1; 7 6 5 4 3 2 1 0 <== ADCON1 bits; | |__|__|__|____ RA0 is an a log.; | Vref+ = Vdd; | Vref- = Vss; |_________________________ 0 = left-jus ti fied; ADCON1 is in bank 1

movlw b’00001110’movwf ADCON1 ; RA0 is an a log. All oth ers ;

; dig i tal; Vref+ = Vdd

; Se lect D/A op tions in ADCON0 reg is ter; For a 10 MHz clock the Fosc32 op tion pro duces a con ver sion; speed of 1/(10/32) = 3.2 mi cro sec onds, which is within the; rec om mended range of 1.6 to 10 mi cro sec onds.; 1 0 0 0 0 0 0 1 <== value in stalled in ADCON0

An a log-to-Dig i tal and Real-Time Clocks 301

Page 323: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; 7 6 5 4 3 2 1 0 <== ADCON0 bits; | | | | | | |____ A/D func tion se lect; | | | | | | 1 = A/D ON; | | | | | |__________ A/D sta tus bit ; | | |__|__|_____________ An a log Chan nel Se lect; | | 000 = Chanel 0 (RA0) ; |__|______________________ A/D Clock Se lect; 10 = Fosc/32; ADCON0 is in bank 0

Bank0movlw b’10000001’movwf ADCON0 ; Chan nel 0, Fosc/32, A/D

; en abled; De lay for se lec tion to com plete. (Ex isting rou tine pro vides; more than 20 mi cro sec onds re quired)

call delayAD ; Lo cal pro ce durere turn

;============================; read A/D line;============================; Pro ce dure to read the value in the A/D line and con vert; to dig i talReadA2D:; Ini ti ate con ver sion

Bank0 ; Bank for ADCON0 reg is terbsf ADCON0,GO ; Set the GO/DONE bit

; GO/DONE bit is cleared au to mat i cally when con ver sion endsconvWait:

btfsc ADCON0,GO ; Test bitgoto convWait ; Wait if not clear

; At this point con ver sion has con cluded; ADRESH reg is ter (bank 0) holds 8 MSBs of re sult; ADRESL reg is ter (bank 1) holds 4 LSBs.; In this ap pli ca tion value is left-jus ti fied. Only the; MSBs are read

movf ADRESH,W ; Dig i tal value to w reg is terre turn

;=======================; de lay pro ce dure;=======================; For a 10 MHz clock the Fosc32 op tion pro duces a con ver sion; speed of 1/(10/32) = 3.2 mi cro sec onds. At 3.2 ms per bit; 13 bits re quire ap prox i mately 41 ms. The in struc tion time; at 10 MHz is 10 ms. 4/10 = 0.4 ms per insctruction. To de lay; 41 ms a 10 MHz PIC must ex e cute 11 in struc tions. Add one; more for safety.delayAD:

movlw .12 ; Re peat 12 ma chine cy cles

302 Chap ter 13

Page 324: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

movwf count1 ; Store value in coun terrepeat11:

decfsz count1,f ; Dec re ment coun tergoto repeat11 ; Con tinue if not 0re turn

;============================================================

end ; END OF PROGRAM ;============================================================

13.6.3 RTC2LCD Pro gram; File name: RTC2LCD.asm; Last Up date: June 6, 2011; Au thors: Canton and Sanchez; Pro ces sor: 16F84A;; De scrip tion:; Pro gram to dem on strate use of the NJU6355 Real Time Clock; IC. Pro gram uses LCD to dis play re sults of hours, min utes,; and sec onds, as fol lows:;; Top LCD line: H:xx M:yy S:zz;; Ini tial iza tion val ues are in #de fine state ments that start; with i, such as iYear, iMonth, etc.;; For LCD dis play pa ram e ters see the LCDTest2 pro gram. ; WARNING:; Code as sumes 4 MHz clock. De lay rou tines must be; ed ited for faster clock;;===========================; switches;===========================; Switches used in __config di rec tive:; _CP_ON Code pro tec tion ON/OFF ; * _CP_OFF ; * _PWRTE_ON Power-up timer ON/OFF; _PWRTE_OFF ; _WDT_ON Watchdog timer ON/OFF ; * _WDT_OFF ; _LP_OSC Low power crys tal os cil la tor; * _XT_OSC Ex ter nal par al lel res o na tor/crys tal os cil la tor

; _HS_OSC High speed crys tal res o na tor (8 to 10 MHz); Res o na tor: Murate Erie CSA8.00MG = 8 MHz ; _RC_OSC Re sis tor/ca pac i tor os cil la tor

An a log-to-Dig i tal and Real-Time Clocks 303

Page 325: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; | (sim plest, 20% er ror); |; |_____ * in di cates setup val ues pres ently se lected

;=========================; setup and con fig u ra tion;=========================

pro ces sor 16f84Ain clude <p16f84A.inc>__config _XT_OSC & _WDT_OFF & _PWRTE_ON & _CP_OFF

errorlevel -302; Sup press bank-re lated warn ing;============================================================; M A C R O S;============================================================; Macros to se lect the reg is ter banks in 16F84Bank0 MACRO ; Se lect RAM bank 0

bcf STATUS,RP0ENDM

Bank1 MACRO ; Se lect RAM bank 1bsf STATUS,RP0ENDM

;=====================================================; con stant def i ni tions; for PIC-to-LCD pin wir ing and LCD line ad dresses;=====================================================#de fine E_line 1 ;|#de fine RS_line 2 ;| => from cir cuit wir ing di a gram #de fine RW_line 3 ;|; LCD line ad dresses (from LCD data sheet)#de fine LCD_1 0x80 ; First LCD line con stant#de fine LCD_2 0xc0 ; Sec ond LCD line con stant; Note: The con stants that de fine the LCD dis play line; ad dresses have the high-or der bit set in; or der to fa cil i tate the con trol ler com mand

; De fines from real-time clock wir ing di a gram; all lines in Port-B#de fine DAT 0 ;|#de fine CLK 1 ;| => from cir cuit wir ing di a gram#de fine CE 2 ;|#de fine IO 3 ;|;; De fines for RTC ini tial iza tion (val ues are ar bi trary)#de fine iYear .7#de fine iMonth .6

304 Chap ter 13

Page 326: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

#de fine iDay .5#de fine iDoW .4#de fine iHour .3#de fine iMin .2#de fine iSec .1;=====================================================; PIC reg is ter equates;=====================================================;=====================================================; vari ables in PIC RAM;=====================================================; Re serve 16 bytes for string buffer

cblock 0x0cstrDataendc

; Re serve three bytes for ASCII dig itscblock 0x1dasc100asc10asc1 endc

; Con tinue with lo cal vari ablescblock 0x20 ; Start of blockcount1 ; Coun ter # 1count2 ; Coun ter # 2count3 ; Coun ter # 3pic_ad ; Stor age for start of text areaJ ; Coun ter JK ; Coun ter Kin dex ; In dex into text ta ble (also used

; for aux il iary stor age)store1 ; Lo cal tem po rary stor age store2 ; Stor age # 2

; Stor age for BCD dig itsbcdLow ; Low-or der nib ble of packed BCDbcdHigh ; High-or der nib ble

; Vari ables for Real-Time ClockyearmonthdaydayOfWeek ; Sunday to Sat ur day (1 to 7)hourmin utessec ondstemp1coun ter

; Stor age for BCD con ver sion rou tineinNum ; Source op er and

An a log-to-Dig i tal and Real-Time Clocks 305

Page 327: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

thisDig ; Digit coun terendc

;=========================================================; pro gram;=========================================================

org 0 ; start at ad dress goto main

; Space for in ter rupt han dlersorg 0x08

main:movlw b’00000000’ ; All lines to out putBank1movwf TRISA ; in Port-Amovwf TRISB ; and Port-BBank0movlw b’00000000’ ; All out puts ports lowmovwf PORTAmovwf PORTB

; Wait and ini tial ize HD44780call de lay_5 ; Al low LCD time to ini tial ize

; it selfcall de lay_5call initLCD ; Then do forced

ini tial iza tioncall de lay_5 ; Wait again

; Store base ad dress of text buffer in PIC RAMmovlw 0x0c ; Start ad dress for buffermovwf pic_ad ; to lo cal vari able

;======================; first LCD line;======================; Store 16 blanks in PIC RAM, start ing at ad dress stored; in vari able pic_ad

call blank16; Call pro ce dure to store ASCII char ac ters for mes sage; in text buffer

movlw d’0’ ; Off set into buffercall storeMS1 ; Store mes sage text in buffer

; Ini tial ize real time clockcall initRTC ; Ini tial ize vari ablescall setRTC ; Start clockcall de lay_5 ; Wait for op er a tion to

; con cludenewTime:; Get vari ables from RTC

call Get_Time

306 Chap ter 13

Page 328: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

call de lay_5 ; Waitmovf hour,w ; Get hourscall Bcd2asc ; Con ver sion rou tine

; At this point three ASCII dig its are stored in lo cal; vari ables. Move dig its to dis play area

movf asc1,w ; Unit digitmovwf .15 ; Store in buffermovf asc10,w ; Same with other digitmovwf .14call de lay_5movf min utes,wcall Bcd2asc ; Con ver sion rou tine

; At this point three ASCII dig its are stored in lo cal; vari ables. Move two dig its to dis play area

movf asc1,w ; Unit digitmovwf .20 ; Store in buffermovf asc10,w ; same with other digitmovwf .19call de lay_5

movf sec onds,wcall Bcd2asc ; Con ver sion rou tine

; Move dig its to dis play areamovf asc1,w ; Unit digitmovwf .25 ; Store in buffermovf asc10,w ; same with other digitmovwf .24call de lay_5

; Set DDRAM ad dress to start of first linecall line1

; Call pro ce dure to dis play 16 char ac ters in LCDcall display16 goto newTime

;============================================================; ini tial ize LCD for 4-bit mode ;============================================================initLCD:; Ini tial iza tion for Densitron LCD mod ule as fol lows:; 4-bit in ter face; 2 dis play lines of 16 char ac ters each; cur sor on; left-to-right in cre ment; cur sor shift right; no dis play shift;=======================|; set com mand mode |;=======================|

An a log-to-Dig i tal and Real-Time Clocks 307

Page 329: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

bcf PORTA,E_line ; E line lowbcf PORTA,RS_line ; RS line lowbcf PORTA,RW_line ; Write modecall de lay_125 ; de lay 125 mi cro sec onds

;***********************|; FUNCTION SET |;***********************|

movlw 0x28 ; 0 0 1 0 1 0 0 0 (FUNCTION SET)call send8 ; 4-bit send rou tine

;; Set 4-bit mode com mand must be re peated

movlw 0x28call send8

;;***********************|; DISPLAY AND CURSOR ON |;***********************|

movlw 0x0e ; 0 0 0 0 1 1 1 0 (DISPLAY ON/OFF)call send8

;***********************|; set en try mode |;***********************|

movlw 0x06 ; 0 0 0 0 0 1 1 0 (ENTRY MODE SET)call send8

;;***********************|; cur sor/dis play shift |;***********************|

movlw 0x14 ; 0 0 0 1 0 1 0 0 (CURSOR/DISPLAY; SHIFT)

call send8;***********************|; clear dis play |;***********************|

movlw 0x01 ; 0 0 0 0 0 0 0 1 (CLEAR DISPLAY)call send8

; Per doc u men ta tioncall de lay_5 ; Test for busyre turn

;;=======================; Pro ce dure to de lay; 42 mi cro sec onds;=======================de lay_125

movlw D’42’ ; Re peat 42 ma chine cy clesmovwf count1 ; Store value in coun ter

re peat:

308 Chap ter 13

Page 330: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

decfsz count1,f ; Dec re ment coun tergoto re peat ; Con tinue if not 0re turn ; End of de lay

;;=======================; Pro ce dure to de lay; 5 mil li sec onds;=======================de lay_5:

movlw D’41’ ; Coun ter = 41movwf count2 ; Store in vari able

de lay:call de lay_125 ; De laydecfsz count2,f ; 40 times = 5 mil li sec ondsgoto de layre turn ; End of de lay

;========================; pulse E line ;========================pulseE:

bsf PORTA,E_line ; Pulse E linenopbcf PORTA,E_linere turn

;=============================; long de lay sub-rou tine; (for de bug ging);=============================long_de lay:

movlw D’200’ ; w = 200 dec i malmovwf J ; J = w

jloop:movwf K ; K = w

kloop:decfsz K,f ; K = K-1, skip next if zerogoto kloopdecfsz J,f ; J = J-1, skip next if zerogoto jloopre turn

;=============================; LCD dis play pro ce dure;=============================; Sends 16 char ac ters from PIC buffer with ad dress stored; in vari able pic_ad to LCD line pre vi ously se lecteddisplay16

call de lay_5 ; Make sure not busy; Set up for data

An a log-to-Dig i tal and Real-Time Clocks 309

Page 331: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

bcf PORTA,E_line ; E line lowbsf PORTA,RS_line ; RS line high for data

; Set up coun ter for 16 char ac tersmovlw D’16’ ; Coun ter = 16movwf count3

; Get dis play ad dress from lo cal vari able pic_admovf pic_ad,w ; First dis play RAM ad dress to Wmovwf FSR ; W to FSR

getchar:movf INDF,w ; get char ac ter from dis play RAM

; lo ca tion pointed to by file se lect; reg is ter

call send8 ; 4-bit in ter face rou tine; Test for 16 char ac ters dis played

decfsz count3,f ; Dec re ment coun tergoto nextchar ; Skipped if donere turn

nextchar:incf FSR,f ; Bump pointergoto getchar

;========================; send 2 nib bles in; 4-bit mode;========================; Pro ce dure to send two 4-bit val ues to Port-B lines; 7, 6, 5, and 4. High-or der nib ble is sent first; ON ENTRY:; w reg is ter holds 8-bit value to sendsend8:

movwf store1 ; Save orig i nal valuecall merge4 ; Merge with Port-B

; Now w has merged bytemovwf PORTB ; w to Port-Bcall pulseE ; Send data to LCD

; High nib ble is sentmovf store1,w ; Re cover byte into wswapf store1,w ; Swap nib bles in wcall merge4movwf PORTBcall pulseE ; Send data to LCDcall de lay_125 re turn

;=================; merge bits;=================; Rou tine to merge the 4 high-or der bits of the; value to send with the con tents of Port-B

310 Chap ter 13

Page 332: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; so as to pre serve the 4 low-bits in Port-B; Logic:; AND value with 1111 0000 mask; AND Port-B with 0000 1111 mask; Now low nib ble in value and high nib ble in; Port-B are all 0 bits:; value = vvvv 0000; Port-B = 0000 bbbb; OR value and Port-B re sult ing in:; vvvv bbbb ; ON ENTRY:; w con tain value bits; ON EXIT:; w con tains merged bitsmerge4:

andlw b’11110000’ ; ANDing with 0 clears the; bit. ANDing with 1 pre serves; the orig i nal value

movwf store2 ; Save re sult in vari ablemovf PORTB,w ; Port-B to w reg is terandlw b’00001111’ ; Clear high nib ble in Port-B

; and pre serve low nib bleiorwf store2,w ; OR two operands in wre turn

;========================; blank buffer;========================; Pro ce dure to store 16 blank char ac ters in PIC RAM; buffer start ing at ad dress stored in the vari able; pic_adblank16

movlw D’16’ ; Set up coun termovwf count1movf pic_ad,w ; First PIC RAM ad dressmovwf FSR ; In dexed ad dress ingmovlw 0x20 ; ASCII space char ac ter

storeitmovwf INDF ; Store blank char ac ter in PIC RAM

; buffer us ing FSR reg is terdecfsz count1,f ; Done?goto incfsr ; nore turn ; yes

incfsrincf FSR,f ; Bump FSR to next buffer spacegoto storeit

;========================

An a log-to-Dig i tal and Real-Time Clocks 311

Page 333: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; Set ad dress reg is ter; to LCD line 1;========================; ON ENTRY:; Ad dress of LCD line 1 in con stant LCD_1 line1:

bcf PORTA,E_line ; E line lowbcf PORTA,RS_line ; RS line low, set up for

; con trolcall de lay_5 ; busy?

; Set to sec ond dis play linemovlw LCD_1 ; Ad dress and com mand bitcall send8 ; 4-bit rou tine

; Set RS line for databsf PORTA,RS_line ; Setup for datacall de lay_5 ; Busy?re turn

;===============================; first text string pro ce dure;===============================storeMS1:; Pro ce dure to store in PIC RAM buffer the mes sage; con tained in the code area la beled msg1; ON ENTRY:; vari able pic_ad holds ad dress of text buffer; in PIC RAM; w reg is ter hold off set into stor age area; msg1 is rou tine that re turns the string char ac ters; an a zero ter mi na tor; in dex is lo cal vari able that holds off set into; text ta ble. This vari able is also used for; tem po rary stor age of off set into buffer ; ON EXIT:; Text mes sage stored in buffer;; Store off set into text buffer (passed in the w reg is ter); in tem po rary vari able

movwf in dex ; Store w in in dex; Store base ad dress of text buffer in FSR

movf pic_ad,w ; first dis play RAM ad dress to Waddwf in dex,w ; Add off set to ad dressmovwf FSR ; W to FSR

; Ini tial ize in dex for text string ac cessmovlw 0 ; Start at 0movwf in dex ; Store in dex in vari able

; w still = 0get_msg_char:

312 Chap ter 13

Page 334: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

call msg1 ; Get char ac ter from ta ble; Test for zero ter mi na tor

andlw 0x0ffbtfsc STATUS,Z ; Test zero flaggoto endstr1 ; End of string

; ASSERT: valid string char ac ter in w; store char ac ter in text buffer (by FSR)

movwf INDF ; store in buffer by FSRincf FSR,f ; in cre ment buffer pointer

; Re store ta ble char ac ter coun ter from vari ablemovf in dex,w ; Get value into waddlw 1 ; Bump to next char ac termovwf in dex ; Store ta ble in dex in

vari ablegoto get_msg_char ; Con tinue

endstr1:re turn

; Rou tine for re turn ing mes sage stored in pro gram area; Mes sage has 10 char ac tersmsg1:

addwf PCL,f ; Ac cess ta bleretlw ‘H’retlw ‘:’retlw ‘ ‘retlw ‘ ‘retlw ‘ ‘retlw ‘M’retlw ‘:’retlw ‘ ‘retlw ‘ ‘retlw ‘ ‘retlw ‘S’retlw ‘:’retlw 0

;==============================; BCD to ASCII dec i mal; con ver sion;============================== ; ON ENTRY:; w reg is ter has two packed BCD dig its; ON EXIT:; out put vari ables asc10, and asc1 have; two ASCII dec i mal dig its; Rou tine logic:; The low-or der nib ble is iso lated and the value 30H; added to con vert to ASCII. The re sult is stored in

An a log-to-Dig i tal and Real-Time Clocks 313

Page 335: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; the vari able asc1. Then the same is done to the ; high-or der nib ble and the re sult is stored in the; vari able asc10

Bcd2asc:movwf store1 ; Save in putandlw b’00001111’ ; Clear high nib bleaddlw 0x30 ; Con vert to ASCIImovwf asc1 ; Store re sultswapf store1,w ; Re cover in put and swap dig itsandlw b’00001111’ ; Clear high nib bleaddlw 0x30 ; Con vert to ASCIImovwf asc10 ; Store re sultre turn

;============================================================; 6355 RTC pro ce dures;============================================================;============================; init RTC;============================; Pro ce dure to ini tial ize the real time clock chip. If chip; is not in i tial ized it will not op er ate and the val ues; read will be in valid. ; Because the 6355 op er ates in BCD for mat the stored val ues; must be con verted to packed BCD.; Ac cord ing to wir ing di a gram; NJU6355 In ter face for set ting time:; DAT PORTB,0 Out put; CLK PORTB,1 Out put; CE PORTB,2 Out put ; IO PORTB,3 Out putsetRTC:

Bank1movlw b’00000000’ ; All out put bitsmovlw TRISBBank0

; Writ ing to the 6355 re quires that the CLK bit be held; low while the IO and CE lines are high

bcf PORTB,CLK ; CLK lowcall de lay_5bsf PORTB,IO ; IO highcall de lay_5bsf PORTB,CE ; CE high

; Data is stored in RTC as fol lows:; year 8 bits (0 to 99); month 8 bits (1 to 12); day 8 bits (1 to 31)

314 Chap ter 13

Page 336: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; dayOfWeek 4 bits (1 to 7); hour 8 bits (0 to 23); min utes 8 bits (0 to 59); ======; To tal 44 bits; Sec onds can not be writ ten to RTC. RTC sec onds reg is ter; is au to mat i cally in i tial ized to zero

movf year,w ; Get item from stor agecall bin2bcd ; Con vert to BCDmovwf temp1call writeRTC

movf month,wcall bin2bcdmovwf temp1call writeRTC

movf day,wcall bin2bcdmovwf temp1call writeRTC

movf dayOfWeek,w ; Day of week is 4-bitscall bin2bcdmovwf temp1call write4RTC

movf hour,wcall bin2bcdmovwf temp1call writeRTC

movf min utes,wcall bin2bcdmovwf temp1call writeRTC

; Donebcf PORTB,CLK ; Hold CLK line lowcall de lay_5bcf PORTB,CE ; and the CE line

; to the RTCcall de lay_5bcf PORTB,IO ; RTC in out put modere turn

;============================; read RTC data;============================; Pro ce dure to read the cur rent time from the RTC and store

An a log-to-Dig i tal and Real-Time Clocks 315

Page 337: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; data (in packed BCD for mat) in lo cal time reg is ters.; Ac cord ing to wir ing di a gram; NJU6355 In ter face for read op er a tions:; DAT PORTB,0 In put; CLK PORTB,1 Out put; CE PORTB,2 Out put; IO PORTB,3 Out putGet_Time; Clear Port-B

movlw b’00000000’movwf PORTB

; Make data line in putBank1movlw b’00000001’movwf TRISBBank0

; Read ing RTC data re quires that the IO line be low and the; CE line be high. CLK line is held low

bcf PORTB,CLK ; CLK lowcall de lay_125bcf PORTB,IO ; IO line lowcall de lay_125bsf PORTB,CE ; and CE line high

; Data is read from RTC as fol lows:; year 8 bits (0 to 99); month 8 bits (1 to 12); day 8 bits (1 to 31); dayOfWeek 4 bits (1 to 7); hour 8 bits (0 to 23); min utes 8 bits (0 to 59); sec onds 8 bits (0 to 59); ======; To tal 52 bits

call readRTCmovwf yearcall de lay_125

call readRTCmovwf monthcall de lay_125

call readRTCmovwf daycall de lay_125

; Day of week is a 4-bit valuecall read4RTCmovwf dayOfWeek

316 Chap ter 13

Page 338: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

call de lay_125

call readRTCmovwf hourcall de lay_125

call readRTCmovwf min utescall de lay_125

call readRTCmovwf sec onds

bcf PORTB,CE ; CE line low to end out putre turn

;============================; read 4/8 bits from RTC ;============================; Pro ce dure to read 4/8 bits stored in 6355 reg is ters; Value re turned in w reg is terread4RTC

movlw .4 ; 4 bit readgoto anyBits

readRTCmovlw .8 ; 8 bits read

anyBits:movwf coun ter

; Read 6355 read op er a tion re quires the IO line be set low; and the CE line high. Data is read in the fol low ing or der:; year, month, day, day-of-week, hour, min utes, sec ondsreadBits:

bsf PORTB,CLK; Set CLK high to val i date databsf STATUS,C ; Set the carry flag (bit = 1)

; Op er a tion:; If data line is high, then bit read is a 1-bit; oth er wise bit read is a 0-bit

btfss PORTB,DAT ; Is data line high?; Leave carry set (1 bit) if high

bcf STATUS,C ; Clear the carry bit (make bit 0); At this point the carry bit matches the data line

bcf PORTB,CLK ; Set CLK low to end read; The carry bit is now ro tated into the temp1 reg is ter

rrf temp1,1decfsz coun ter,1 ; Dec re ment the bit coun ter goto readBits ; Con tinue if not last bit

; At this point all bits have been read (8 or 4)movf temp1,0 ; Re sult to w

An a log-to-Dig i tal and Real-Time Clocks 317

Page 339: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

re turn

;============================; write 4/8 bits to RTC;============================; Pro ce dure to write 4 or 8 bits to the RTC reg is ters; ON ENTRY:; temp1 reg is ter holds value to be writ ten; ON EXIT:; noth ingwrite4RTC

movlw .4 ; Init for 4 bitsgoto allBits

writeRTCmovlw .8 ; Init for 8 bits

allBits:movwf coun ter ; Store in bit coun ter

writeBits:bcf PORTB,CLK ; Clear the CLK linecall de lay_5 ; Wait bsf PORTB,DAT ; Set the data line to RTCbtfss temp1,0 ; Send LSBbcf PORTB,DAT ; Clear data linecall de lay_5 ; Wait for op er a tion to

; com pletebsf PORTB,CLK ; Bring CLK line high to

; val i daterrf temp1,f ; Ro tate bits in stor age decfsz coun ter,1 ; Dec re ment bit coun tergoto writeBits ; Con tinue if not last bitre turn

;============================; init time vari ables;============================; Pro ce dure to ini tial ize time vari ables for test ing; Con stants used in ininitialization are lo cated in; #de fine state ments.initRTC:

movlw iYearmovwf yearmovlw iMonthmovwf monthmovlw iDaymovwf daymovlw iDoWmovwf dayOfWeekmovlw iHour

318 Chap ter 13

Page 340: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

movwf hourmovlw iMinmovwf min utesmovlw iSecmovwf sec ondsre turn

;============================; bi nary to BCD con ver sion;============================; Con vert a bi nary num ber into two packed BCD dig its; ON ENTRY:; w reg is ter has bi nary value in range 0 to 99; ON EXIT:; out put vari ables bcdLow and bcdHigh con tain two; packed un packed BCD dig its; w con tains two packed BCD dig its; Rou tine logic:; The value 10 is sub tracted from the source op er and; un til the re mainder is < 0 (carry cleared). The num ber; of sub trac tions is the high-or der BCD digit. 10 is; then added back to the sub tra hend to com pen sate; for the last sub trac tion. The fi nal re mainder is the; low-or der BCD digit; Vari ables:; inNum stor age for source op er and; bcdHigh stor age for high-or der nib ble; bcdLow stor age for low-or der nib ble; thisDig Digit coun ter bin2bcd:

movwf inNum ; Save copy of source valueclrf bcdHigh ; Clear stor ageclrf bcdLowclrf thisDig

min10:movlw .10subwf inNum,f ; Sub tract 10btfsc STATUS,C ; Did sub tract over flow?goto sum10 ; No. Count sub trac tiongoto fin10

sum10:incf thisDig,f ;in cre ment digit coun tergoto min10

; Store 10th digitfin10:

movlw .10addwf inNum,f ; Ad just for last subratctmovf thisDig,w ; get digit coun ter con tentsmovwf bcdHigh ; Store it

An a log-to-Dig i tal and Real-Time Clocks 319

Page 341: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; Cal cu late and store low-or der BCD digitmovf inNum,w ; Store units valuemovwf bcdLow ; Store digit

; Com bine both dig itsswapf bcdHigh,w ; High nib ble to HOBsiorwf bcdLow,w ; OR-in low nib blere turn

;============================================================end ; END OF PROGRAM

;============================================================

320 Chap ter 13

Page 342: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Chap ter 14

Data EEPROM

14.1 EEPROM Pro gram mingThis chap ter is about Elec tri cally-Eras able Pro gram ma ble Read-Only Mem ory.EEPROM mem ory is used in dig i tal de vices as non vol a tile stor age, such as in flashdrives, BIOS chips, and in mem ory stor age fa cil i ties. In PIC microcontrollersEEPROM mem ory is used as semi-per ma nent data stor age be cause EEPROM can beerased and re pro grammed elec tri cally with out re mov ing the chip. The tech nol ogyused be fore the de vel op ment of EEPROM, called EPROM, re quired that the chip be re -moved from the cir cuit and placed un der ul tra vi o let light in or der to erase it. In ad di -tion, EPROM re quired higher-than-TTL volt ages for re pro gram ming while EEPROMdoes not. In this chap ter we re fer to data EEPROM as im ple mented in the mid-rangePICs and in par tic u lar in the 16F84.

14.1.1 Data EEPROM To the PIC pro gram mer, EEPROM data mem ory can re fer ei ther to on-board EEPROMmem ory or to EEPROM mem ory ICs that are fur nished as sep a rate cir cuit com po -nents. EEPROM el e ments are clas si fied ac cord ing to their elec tri cal in ter faces intose rial and par al lel. In this con text we deal only with se rial EEPROMs. The stor age ca -pac ity of Se rial EEPROMs range from a few bytes to 128 ki lo bytes. In PIC tech nol ogythe typ i cal use of se rial EEPROM on-board mem ory and EEPROM ICs is in the stor ageof pass words, codes, con fig u ra tion set tings, and other in for ma tion to be re mem beredaf ter the sys tem is turned off. For ex am ple, a PIC-based au to mated en vi ron ment sen -sor can use EEPROM mem ory to store daily tem per a tures, hu mid ity, air pres sure, andother val ues. Later on this in for ma tion can be down loaded to a PC and the EEPROMstor age erased and re used for new data. In per sonal com put ers, EEPROM mem ory isused to store BIOS code and other sys tem data.

Some early EEPROMs could be erased and re writ ten about 100 times be fore fail -ing, but more re cent EEPROMs tol er ate thou sands of erase-write cy cles. EEPROMmem ory is dif fer ent from Ran dom Ac cess Mem ory (RAM) in that RAM can be re -writ ten mil lions of times. Also, RAM is gen er ally faster to write than EEPROM andcon sid er ably cheaper per unit of stor age. On the other hand, RAM is vol a tile (thecon tents are lost when power is re moved.)

321

Page 343: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

PICs also use EEPROM-type mem ory in ter nally as flash pro gram mem ory and asdata mem ory. In this con text we deal with EEPROM data mem ory. Se rial EEPROMmem ory is also avail able as sep a rate ICs that can be placed on the cir cuit board andac cessed through PIC ports. For ex am ple, the Micro chip 24LC04B EEPROM IC is a4K elec tri cally eras able PROM with a two-wire se rial in ter face that fol lows the I2Ccon ven tion. Pro gram ming se rial EEPROM ICs is not cov ered in this chap ter.

14.2 EEPROM Pro gram mingThe 16F84 and 16F84A con tain 64 bytes of EEPROM data mem ory. This mem ory isboth read able and writable dur ing nor mal op er a tion. It is not mapped in the reg is terfile space but is in di rectly ad dressed through the Spe cial Func tion Reg is tersEECON1, EECON2, EEDATA, and EEADR. The ad dress of EEPROM mem ory starts atlo ca tion 0x00 and ex tends to the max i mum con tained in the PIC, in this case 0x3f. Thefol low ing reg is ters re late to EEPROM op er a tions:

• EEDATA holds the data byte to be read or writ ten.

• EEADR con tains the EEPROM ad dress to be ac cessed by the read or write op er a -tion.

• EECON1 con tains the con trol bits for EEPROM op er a tions.

• EECON2 pro tects EEPROM mem ory from ac ci den tal ac cess. This is not a phys i calreg is ter.

Fig ure 14.1 is a bitmap of the EECON1 reg is ter in the 16F84.

Fig ure 14.1 16F84 EECON1 Reg is ter Bitmap.

322 Chap ter 14

EECON1

bit 0bit 7

WRERREEIF WR RD

bit 7-5 Unimplemented: Read as '0'bit 4 EEIF: EEPROM Write Operation Interrupt Flag bit 1 = The write operation completed (must be cleared in software) 0 = The write operation is not complete or has not been startedbit 3 WRERR: EEPROM Error Flag bit 1 = write operation terminated prematurely 0 = The write operation completedbit 2 WREN: EEPROM Write Enable bit 1 = Allows write cycles 0 = Inhibit write to the EEPROMbit 1 WR: Write Control bit 1 = Initiates a write cycle. Bit is cleared once write is complete. Can only be set in software. 0 = Write cycle to the EEPROM is completebit 0 RD: Read Control bit 1 = Initiates an EEPROM read. Bit is cleared in hardware. Can only be set in software. 0 = Does not initiate an EEPROM read

Page 344: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

The CPU may con tinue to ac cess EEPROM mem ory even if the de vice is codepro tected, but in this case the de vice pro gram mer can not ac cess EEPROM memory.

14.2.1 Read ing EEPROM DataRead ing an EEPROM data mem ory lo ca tion in the 16F84 re quires the fol low ing op er a -tions:

• Bank 0 is se lected and the ad dress of the mem ory to be read is stored in the EEADRreg is ter.

• Bank 1 is se lected and the RD bit is set in the EECON1 register.

• Bank 0 is se lected and data is read from the EEDATA reg is ter.

The fol low ing pro ce dure re turns in the w reg is ter the data stored at the spec i fiedEEPROM mem ory ad dress:

;==============================; read EEPROM 16F84;==============================; Pro ce dure to read EEPROM mem ory. Ad dress of mem ory; lo ca tion to read is passed in lo cal vari able EEMemAdd; On exit: read data in wEERead:

bcf STATUS,RP0 ; Bank 0movf EEMemAdd,w ; Ad dress to wmovwf EEADR ; w to ad dress reg is terbsf STATUS,RP0 ; Bank 1bsf EECON1,RD ; EE Readbcf STATUS,RP0 ; Bank 0movf EEDATA,w ; w = EEDATAre turn

14.2.2 EEPROM Data Mem ory WriteWrit ing to 16F84 EEPROM data mem ory con sists of the fol low ing op er a tions:

• Bank 0 is se lected and the ad dress of the de sired mem ory lo ca tion is stored in theEEADR reg is ter.

• The value to be writ ten is stored in the EEDATA reg is ter.

• Bank 1 is se lected, in ter rupts are dis abled, and the write en able bit (WREN) is set inthe EECON1 register.

• The spe cial val ues 0x55 and 0xaa are writ ten con sec u tively to the EECON2 reg is ter.

• The WR bit is set in the EECON1 register. The EEPROM write takes place au to mat i -cally af ter the WR bit is set.

• In ter rupts are reenabled and bank 0 is se lected.

The fol low ing pro ce dure shows the pro cess ing for the EEPROM write:

;==============================; write EEPROM;==============================; Pro ce dure to write asc1 byte to EEPROM mem ory; Ad dress to write passed in lo cal vari able EEMemAdd

Data EEPROM 323

Page 345: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; Data byte to write is passed in lo cal vari able EEByteEEWrite:; Load byte to write into EE data reg is ter

movf EEByte,w ; Data to wmovwf EEDATA ; Write

; Set write ad dress in EE ad dress reg is termovf EEMemAdd,w ; Ad dress to wmovwf EEADR ; w to ad dress reg is ter

; Write data to EEPROM mem orybsf STATUS,RP0 ; Bank 1bcf INTCON,GIE ; Dis able in ter ruptsbsf EECON1,WREN ; En able Writemovlw 0x55 ; Code # 1movwf EECON2 ; Write 0x55movlw 0xaa ; Code # 2movwf EECON2 ; Write 0xaabsf EECON1,WR ; Set WR bit

; Write op er a tion now takes place au to mat i callybsf INTCON,GIE ; Re-en able in ter ruptsbcf STATUS,RP0 ; Bank 0re turn

Micro chip doc u men ta tion rec om mends that crit i cal ap pli ca tions should ver ifythe write op er a tion by read ing EEPROM mem ory af ter the write op er a tion hastaken place in or der to make sure that the cor rect value was stored.

14.3 EEPROM Pro gram ming Ap pli ca tionThe pro gram EECounter, in this book’s soft ware pack age, is a dem on stra tion ofEEPROM mem ory ac cess on the 16F84 PIC. The pro gram keeps track of the num ber oftimes that the code has ex e cuted by stor ing each it er a tion in EEPROM data mem ory.The pro gram uses the cir cuit shown in Fig ure 14-2. Note that the cir cuit in Fig ure 14-2is com pat i ble with the one em u lated by the Vir tual Board B pro gram.

14.3.1 EECounter Pro gramThe EECounter pro gram, in this book’s soft ware pack age, dem on strates pro gram -ming the onboard EEPROM data mem ory on the 16F84. The pro gram con tainsEEPROM read and write prim i tives that can be re used in other ap pli ca tions. The pro -gram uses LCD dis play to out put re sults. Code keeps track of the num ber of times ithas been run by stor ing each it er a tion in EEPROM mem ory and read ing back thisvalue at ev ery new ex e cu tion cy cle.

Code De tails

In the EECounter pro gram we en coun ter a sit u a tion that is quite com mon in com puterpro grams: An ap pli ca tion must deal with two or more dif fer ent nu meric for mats. Inthe case of the EECounter pro gram a lo cal reg is ter is used to store and ma nip u late abi nary value. But be fore this value can be dis played in the LCD, it must be con verted to a string of ASCII dec i mal dig its. The con ver sion rou tine trans forms an un signed bi -nary value into an ASCII dec i mal string. The pro cess con sists of di vid ing the bi nary by10, add ing 30H to the re main der, and con tin u ing un til the orig i nal bi nary be comeszero. The EECounter pro gram con tains a bi nary-to-ASCII dec i mal con ver sion rou tinecalled bin2asc, and listed next.

324 Chap ter 14

Page 346: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 14-2 Cir cuit for EEPROM Dem on stra tion Pro gram.

;==============================; bi nary to ASCII dec i mal; con ver sion;============================== ; ON ENTRY:; w reg is ter has bi nary value in range 0 to 255; ON EXIT:; out put vari ables asc100, asc10, and asc1 have; three ASCII dec i mal dig its; Rou tine logic:; The value 100 is sub tracted from the source op er and; un til the re mainder is < 0 (carry cleared). The num ber; of sub trac tions is the dec i mal hun dreds re sult. 100 is; then added back to the sub tra hend to com pen sate; for the last sub trac tion. Now 10 is subracted in the; same man ner to de ter mine the dec i mal tenths re sult.; The fi nal re mainder is the dec i mal units re sult.

Data EEPROM 325

+5VR

=1

0K

RESET

HD44780

LCD2 rows x 16

+5V

E

R/W

RS

RS

R/W

E

1

1416F84

RA2

RA3

RA4/TOCKI

MCLR

Vss

RB0/INT

RB1

RB2

RB3

1

2

3

4

5

6

7

8

9

18

17

16

15

14

13

12

11

10

RA1

RA0

OSC1

OSC2

Vdd

RB7

RB6

RB5

RB4

Osc4Mhz

+5V

Page 347: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; Vari ables:; inNum stor age for source op er and; asc100 stor age for hun dreds po si tion re sult; asc10 stor age for tens po si tion re sult; asc1 stor age for unit po si tion reslt; thisDig Digit coun ter bin2asc:

movwf inNum ; Save copy of source valueclrf asc100 ; Clear hun dreds stor ageclrf asc10 ; Tensclrf asc1 ; Unitsclrf thisDig

sub100:movlw .100subwf inNum,f ; Sub tract 100btfsc STATUS,C ; Did sub tract over flow?goto bump100 ; No. Count sub trac tiongoto end100

bump100:incf thisDig,f ;in cre ment digit

coun tergoto sub100

; Store 100th digitend100:

movf thisDig,w ; Ad justed digit coun teraddlw 0x30 ; Con vert to ASCIImovwf asc100 ; Store it

; Cal cu late tenth po si tion valueclrf thisDig

; Ad just min u endmovlw .100 ; Min u endaddwf inNum,f ; Add value to min u end to

; com pen sate for last; op er a tion

sub10:movlw .10subwf inNum,f ; Sub tract 10btfsc STATUS,C ; Did sub tract over flow?goto bump10 ; No. Count sub trac tiongoto end10

bump10:incf thisDig,f ;in cre ment digit coun tergoto sub10

; Store 10th digitend10:

movlw .10addwf inNum,f ; Ad just for last subratctmovf thisDig,w ; get digit coun ter con tents

326 Chap ter 14

Page 348: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

addlw 0x30 ; Con vert to ASCIImovwf asc10 ; Store it

; Cal cu late and store units digitmovf inNum,w ; Store units valueaddlw 0x30 ; Con vert to ASCIImovwf asc1 ; Store digitre turn

Two other pro ce dures, called EERead and EEWrite, per form the EEProm ba sicop er a tions. These pro ce dures were dis cussed and listed in Sec tions 14.4.1 and14.2.2.

;============================; I2C read pro ce dure ;============================; Pro ce dure to read one byte from 24LC04B EEPROM; Steps:; 1. Send START; 2. Send con trol. Wait for ACK; 3. Send ad dress. Wait for ACK; 4. Send RESTART + con trol. Wait for ACK; 5. Switch to re ceive mode. Get data.; 6. Send NACK; 7. Send STOP; 8. Retreive data into w reg is ter ; STEP 1:ReadI2C; Send RESTART. Wait for ACK

Bank1bsf SSPCON2,RSEN ; RESTART Con di tioncall WaitI2C ; Wait for I2C op er a tion

; STEP 2:; Send con trol byte. Wait for ACK

movlw LC04READ ; Con trol bytecall Send1I2C ; Send Bytecall WaitI2C ; Wait for I2C op er a tion

; Now check to see if I2C EEPROM is readyBank1btfsc SSPCON2,ACKSTAT ; Check ACK Sta tus bitgoto ReadI2C ; ACK Poll wait ing for EEPROM

; write to com plete; STEP 3:; Send ad dress. Wait for ACK

Bank0movf EEMemAdd,w ; Load from ad dress reg is tercall Send1I2C ; Send Bytecall WaitI2C ; Wait for I2C op er a tionBank1

Data EEPROM 327

Page 349: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

btfsc SSPCON2,ACKSTAT ; Check ACK Sta tus bitgoto FailI2C ; failed, skipped if

; suc cess ful; STEP 4:; Send RESTART. Wait for ACK

bsf SSPCON2,RSEN ; Gen er ate RESTART Con di tioncall WaitI2C ; Wait for I2C op er a tion

; Send out put con trol. Wait for ACKmovlw LC04WRITE ; Load CONTROL BYTE (out put)call Send1I2C ; Send Bytecall WaitI2C ; Wait for I2C op er a tionBank1btfsc SSPCON2,ACKSTAT ; Check ACK Sta tus bitgoto FailI2C ; failed, skipped if

; suc cess ful; STEP 5:; Switch MSSP to I2C Re ceive mode

bsf SSPCON2,RCEN ; En able Re ceive Mode (I2C); Get the data. Wait for ACK

call WaitI2C ; Wait for I2C op er a tion; STEP 6:; Send NACK to ac knowl edge

Bank1bsf SSPCON2,ACKDT ; ACK DATA to send is 1 (NACK)bsf SSPCON2,ACKEN ; Send ACK DATA now.

; Once ACK or NACK is sent, ACKEN is au to mat i cally cleared; STEP 7:; Send STOP. Wait for ACK

bsf SSPCON2,PEN ; Send STOP con di tioncall WaitI2C ; Wait for I2C op er a tion

; STEP 8:; Read op er a tion has fin ished

Bank0movf SSPBUF,W ; Get data from SSPBUF into W

; Pro ce dure has fin ished and com pleted suc cess fully.re turn

;============================; I2C sup port pro ce dures;============================; I2C Op er a tion failed code se quence; Pro ce dure hangs up. User should pro vide er ror han dling.FailI2C

Bank1bsf SSPCON2,PEN ; Send STOP con di tioncall WaitI2C ; Wait for I2C op er a tion

fail:goto fail

328 Chap ter 14

Page 350: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; Pro ce dure to trans mit one byteSend1I2C

Bank0movwf SSPBUF ; Value to send to SSPBUFre turn

; Pro ce dure to wait for the last I2C op er a tion to com plete.; Code polls the SSPIF flag in PIR1.WaitI2C

Bank0btfss PIR1,SSPIF ; Check if I2C op er a tion donegoto $-1 + ; I2C mod ule is not ready yetbcf PIR1,SSPIF ; I2C ready, clear flagre turn

14.4 Demonstration Pro gramsThe fol low ing sec tions con tain the code list ing for the pro grams dis cussed in thischap ter.

14.4.1 EECounter Pro gram; File name: EECounter.asm; Last Up date: May 22, 2011; Au thors: Sanchez and Canton; Pro ces sor: 16F84A;; De scrip tion:; Pro gram to dem on strate on chip EEPROM data mem ory read; and write op er a tion. Pro gram uses LCD dis play to out put; re sults.; Op er a tion:; The pro gram keeps track of and dis plays the inNum of times; the code has been started.; For LCD dis play pa ram e ters see the LCDTest2 pro gram. ; WARNING:; Code as sumes 4 MHz clock. De lay rou tines must be; ed ited for faster clock;;===========================; switches;===========================; Switches used in __config di rec tive:; _CP_ON Code pro tec tion ON/OFF ; * _CP_OFF ; * _PWRTE_ON Power-up timer ON/OFF; _PWRTE_OFF ; _WDT_ON Watch dog timer ON/OFF ; * _WDT_OFF

Data EEPROM 329

Page 351: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; _LP_OSC Low power crys tal os cil la tor; * _XT_OSC Ex ter nal par al lel res o na tor/crys tal os cil la tor

; _HS_OSC High speed crys tal res o na tor (8 to 10 MHz); Res o na tor: Murate Erie CSA8.00MG = 8 MHz ; _RC_OSC Re sis tor/ca pac i tor os cil la tor; | (sim plest, 20% er ror); |; |_____ * in di cates setup val ues pres ently se lected

;=========================; setup and con fig u ra tion;=========================

pro ces sor 16f84Ain clude <p16f84A.inc>__config _XT_OSC & _WDT_OFF & _PWRTE_ON & _CP_OFF

;=====================================================; con stant def i ni tions; for PIC-to-LCD pin wir ing and LCD line ad dresses;=====================================================#de fine E_line 1 ;|#de fine RS_line 2 ;| => from wir ing di a gram #de fine RW_line 3 ;|; LCD line ad dresses (from LCD data sheet)#de fine LCD_1 0x80 ; First LCD line con stant#de fine LCD_2 0xc0 ; Sec ond LCD line con stant; Note: The con stants that de fine the LCD dis play line; ad dresses have the high-or der bit set in; or der to faciliate the con trol ler com mand ;;=====================================================; vari ables in PIC RAM;=====================================================; Re serve 16 bytes for string buffer

cblock 0x0cstrDataendc

; Re serve three bytes for ASCII dig itscblock 0x1dasc100asc10asc1 endc

; Con tinue with lo cal vari ablescblock 0x20 ; Start of blockcount1 ; Coun ter # 1count2 ; Coun ter # 2

>330 Chap ter 14

Page 352: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

count3 ; Coun ter # 3pic_ad ; Stor age for start of text area

; (la beled strData) in PIC RAMJ ; coun ter JK ; coun ter Kin dex ; In dex into text ta ble (also used

; for aux il iary stor age)store1 ; Lo cal tem po rary stor age store2 ; Stor age # 2

; EEPROM-re lated vari ablesEEMemAdd ; EEPROM ad dress to ac cessEEByte ; Data byte to write

; Stor age for ASCII dec i mal con ver sion and dig itsinNum ; Source op er andthisDig ; Digit coun terendc

;=========================================================; pro gram;=========================================================

org 0 ; start at ad dress goto main

; Space for in ter rupt han dlersorg 0x08

main:movlw b’00000000’ ; All lines to out puttris PORTA ; in Port-Atris PORTB ; and Port-Bmovlw b’00000000’ ; All out put ports lowmovwf PORTAmovwf PORTB

; Wait and ini tial ize HD44780call de lay_5 ; Al low LCD time to ini tial ize

; it selfcall de lay_5call initLCD ; Then do forced

ini tial iza tioncall de lay_5 ; Wait again

; Store base ad dress of text buffer in PIC RAM

movlw 0x0c ; Start ad dress for buffermovwf pic_ad ; to lo cal vari able

; Ini tial ize EEPROM data to 0x0clrf EEMemAdd ; Set ad dress to 0

;======================; first LCD line;======================

Data EEPROM 331

Page 353: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; Store 16 blanks in PIC RAM, start ing at ad dress stored; in vari able pic_ad

call blank16; Call pro ce dure to store ASCII char ac ters for mes sage; in text buffer

movlw d’0’ ; Off set into buffercall storeMS1

;=======================; Read EEPROM mem ory;=======================; EEPROM mem ory ad dress to use is at 10 (0x0a). Vari able; EEMemAdd is al ready in i tial ized.; Fill data for EEPROM is 0xff. This value in di cates; the first it er a tion

call EERead ; Lo cal pro ce dure. Value in wmovwf EEByte ; Save re sult

; EEPROM data still in wincf EEByte,fcall EEWrite

; At this point it er a tion inNum is stored in EEByte; This value must be dis played on the LCD at off set 11; of the first line. This means it must be stored at off set; 11 in the buffer. Because the buffer starts at 0x0c the; it er a tion digit must be stored at off set 0x0c+11=0x17 ShowEEData:; Bi nary data in EEByte

movf EEByte,w ; Value to wcall bin2asc ; Con ver sion rou tine

; At this point three ASCII dig its are stored in lo cal; vari ables. Move dig its to dis play area

movf asc1,w ; Unit digitmovwf 0x18 ; Store in buffermovf asc10,w ; same with other dig itsmovwf 0x17movf asc100,wmovwf 0x16

; Dis play line; Set DDRAM ad dress to start of first lineshowLine:

call line1; Call pro ce dure to dis play 16 char ac ters in LCD

call display16 loopHere:

goto loopHere ;done

;============================================================; ini tial ize LCD for 4-bit mode ;============================================================

332 Chap ter 14

Page 354: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

initLCD:; Ini tial iza tion for Densitron LCD mod ule as fol lows:; 4-bit in ter face; 2 dis play lines of 16 char ac ters each; cur sor on; left-to-right in cre ment; cur sor shift right; no dis play shift;=======================|; set com mand mode |;=======================|

bcf PORTA,E_line ; E line lowbcf PORTA,RS_line ; RS line lowbcf PORTA,RW_line ; Write modecall de lay_125 ; de lay 125 mi cro sec onds

;***********************|; FUNCTION SET |;***********************|

movlw 0x28 ; 0 0 1 0 1 0 0 0 (FUNCTION SET)call send8 ; 4-bit send rou tine

; Set 4-bit mode com mand must be re peatedmovlw 0x28call send8

;***********************|; DISPLAY AND CURSOR ON |;***********************|

movlw 0x0e ; 0 0 0 0 1 1 1 0 (DISPLAY ON/OFF)call send8

;***********************|; set en try mode |;***********************|

movlw 0x06 ; 0 0 0 0 0 1 1 0 (ENTRY MODE SET)call send8

;***********************|; cur sor/dis play shift |;***********************|

movlw 0x14 ; 0 0 0 1 0 1 0 0 (CURSOR/DISPLAY; SHIFT)

call send8;***********************|; clear dis play |;***********************|

movlw 0x01 ; 0 0 0 0 0 0 0 1 (CLEAR DISPLAY)call send8

; Per doc u men ta tion

Data EEPROM 333

Page 355: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

call de lay_5 ; Test for busyre turn

;=======================; Pro ce dure to de lay; 42 mi cro sec onds;=======================de lay_125

movlw D’42’ ; Re peat 42 ma chine cy clesmovwf count1 ; Store value in coun ter

re peatdecfsz count1,f ; Dec re ment coun tergoto re peat ; Con tinue if not 0re turn ; End of de lay

;=======================; Pro ce dure to de lay; 5 mil li sec onds;=======================de lay_5

movlw D’41’ ; Coun ter = 41movwf count2 ; Store in vari able

de laycall de lay_125 ; De laydecfsz count2,f ; 40 times = 5 mil li sec ondsgoto de layre turn ; End of de lay

;========================; pulse E line ;========================pulseE

bsf PORTA,E_line ; Pulse E linenopbcf PORTA,E_linere turn

;=============================; long de lay sub-rou tine; (for de bug ging);=============================long_de lay

movlw D’200’ ; w = 200 dec i malmovwf J ; J = w

jloop:movwf K ; K = w

kloop:decfsz K,f ; K = K-1, skip next if zerogoto kloop

334 Chap ter 14

Page 356: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

decfsz J,f ; J = J-1, skip next if zerogoto jloopre turn

;=============================; LCD dis play pro ce dure;=============================; Sends 16 char ac ters from PIC buffer with ad dress stored; in vari able pic_ad to LCD line pre vi ously se lecteddisplay16

call de lay_5 ; Make sure not busy; Set up for data

bcf PORTA,E_line ; E line lowbsf PORTA,RS_line ; RS line high for data

; Set up coun ter for 16 char ac tersmovlw D’16’ ; Coun ter = 16movwf count3

; Get dis play ad dress from lo cal vari able pic_admovf pic_ad,w ; First dis play RAM ad dress to Wmovwf FSR ; W to FSR

getchar:movf INDF,w ; get char ac ter from dis play RAM

; lo ca tion pointed to by file se lect; reg is ter

call send8 ; 4-bit in ter face rou tine; Test for 16 char ac ters dis played

decfsz count3,f ; Dec re ment coun tergoto nextchar ; Skipped if donere turn

nextchar:incf FSR,f ; Bump pointergoto getchar

;========================; send 2 nib bles in; 4-bit mode;========================; Pro ce dure to send two 4-bit val ues to Port-B lines; 7, 6, 5, and 4. High-or der nib ble is sent first; ON ENTRY:; w reg is ter holds 8-bit value to sendsend8:

movwf store1 ; Save orig i nal valuecall merge4 ; Merge with Port-B

; Now w has merged bytemovwf PORTB ; w to Port-Bcall pulseE ; Send data to LCD

; High nib ble is sentmovf store1,w ; Re cover byte into w

Data EEPROM 335

Page 357: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

swapf store1,w ; Swap nib bles in wcall merge4movwf PORTBcall pulseE ; Send data to LCDcall de lay_125 re turn

;=================; merge bits;=================; Rou tine to merge the 4 high-or der bits of the; value to send with the con tents of Port-B; so as to pre serve the 4 low-bits in Port-B; Logic:; AND value with 1111 0000 mask; AND Port-B with 0000 1111 mask; Now low nib ble in value and high nib ble in; Port-B are all 0 bits:; value = vvvv 0000; Port-B = 0000 bbbb; OR value and Port-B re sult ing in:; vvvv bbbb ; ON ENTRY:; w con tain value bits; ON EXIT:; w con tains merged bitsmerge4:

andlw b’11110000’ ; ANDing with 0 clears the; bit. ANDing with 1 pre serves; the orig i nal value

movwf store2 ; Save re sult in vari ablemovf PORTB,w ; Port-B to w reg is terandlw b’00001111’ ; Clear high nib ble in Port-b

; and pre serve low nib bleiorwf store2,w ; OR two operands in wre turn

;========================; blank buffer;========================; Pro ce dure to store 16 blank char ac ters in PIC RAM; buffer start ing at ad dress stored in the vari able; pic_adblank16

movlw D’16’ ; Set-up coun termovwf count1movf pic_ad,w ; First PIC RAM ad dressmovwf FSR ; In dexed ad dress ingmovlw 0x20 ; ASCII space char ac ter

336 Chap ter 14

Page 358: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

storeitmovwf INDF ; Store blank char ac ter in PIC RAM

; buffer us ing FSR reg is terdecfsz count1,f ; Done?goto incfsr ; nore turn ; yes

incfsr:incf FSR,f ; Bump FSR to next buffer spacegoto storeit

;========================; Set ad dress reg is ter; to LCD line 1;========================; ON ENTRY:; Ad dress of LCD line 1 in con stant LCD_1 line1:

bcf PORTA,E_line ; E line lowbcf PORTA,RS_line ; RS line low, set up for

con trolcall de lay_5 ; busy?

; Set to sec ond dis play linemovlw LCD_1 ; Ad dress and com mand bitcall send8 ; 4-bit rou tine

; Set RS line for databsf PORTA,RS_line ; Setup for datacall de lay_5 ; Busy?re turn

;===============================; first text string pro ce dure;===============================storeMS1:; Pro ce dure to store in PIC RAM buffer the mes sage; con tained in the code area la beled msg1; ON ENTRY:; vari able pic_ad holds ad dress of text buffer; in PIC RAM; w reg is ter holds off set into stor age area; msg1 is rou tine that re turns the string char ac ters; and a zero ter mi na tor; in dex is lo cal vari able that holds off set into; text ta ble. This vari able is also used for; tem po rary stor age of off set into buffer ; ON EXIT:; Text mes sage stored in buffer;; Store off set into text buffer (passed in the w reg is ter)

Data EEPROM 337

Page 359: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; in tem po rary vari able movwf in dex ; Store w in in dex

; Store base ad dress of text buffer in FSRmovf pic_ad,w ; first dis play RAM ad dress to Waddwf in dex,w ; Add off set to ad dressmovwf FSR ; W to FSR

; Ini tial ize in dex for text string ac cessmovlw 0 ; Start at 0movwf in dex ; Store in dex in vari able

; w still = 0get_msg_char:

call msg1 ; Get char ac ter from ta ble; Test for zero ter mi na tor

andlw 0x0ffbtfsc STATUS,Z ; Test zero flaggoto endstr1 ; End of string

; ASSERT: valid string char ac ter in w; store char ac ter in text buffer (by FSR)

movwf INDF ; store in buffer by FSRincf FSR,f ; in cre ment buffer pointer

; Re store ta ble char ac ter coun ter from vari ablemovf in dex,w ; Get value into waddlw 1 ; Bump to next char ac termovwf in dex ; Store ta ble in dex in vari ablegoto get_msg_char ; Con tinue

endstr1:re turn

; Rou tine for re turn ing mes sage stored in pro gram area; Mes sage has 10 char ac tersmsg1:

addwf PCL,f ; Ac cess ta bleretlw ‘I’retlw ‘t’retlw ‘e’retlw ‘r’retlw ‘.’retlw 0x20retlw ‘N’retlw ‘o’retlw ‘.’retlw 0x20retlw 0

;==============================; bi nary to ASCII dec i mal; con ver sion;==============================

338 Chap ter 14

Page 360: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; ON ENTRY:; w reg is ter has bi nary value in range 0 to 255; ON EXIT:; out put vari ables asc100, asc10, and asc1 have; three ASCII dec i mal dig its; Rou tine logic:; The value 100 is sub tracted from the source op er and; un til the re mainder is < 0 (carry cleared). The num ber; of sub trac tions is the dec i mal hun dreds re sult. 100 is; then added back to the sub tra hend to com pen sate; for the last sub trac tion. Now 10 is subtracted in the; same man ner to de ter mine the dec i mal tenths re sult.; The fi nal re mainder is the dec i mal units re sult.; Vari ables:; inNum stor age for source op er and; asc100 stor age for hun dreds po si tion re sult; asc10 stor age for tens po si tion re sult; asc1 stor age for unit po si tion result; thisDig Digit coun ter bin2asc:

movwf inNum ; Save copy of source valueclrf asc100 ; Clear hun dreds stor ageclrf asc10 ; Tensclrf asc1 ; Unitsclrf thisDig

sub100:movlw .100subwf inNum,f ; Sub tract 100btfsc STATUS,C ; Did sub tract over flow?goto bump100 ; No. Count sub trac tiongoto end100

bump100:incf thisDig,f ;in cre ment digit coun tergoto sub100

; Store 100th digitend100:

movf thisDig,w ; Ad justed digit coun teraddlw 0x30 ; Con vert to ASCIImovwf asc100 ; Store it

; Cal cu late tenth po si tion valueclrf thisDig

; Ad just min u endmovlw .100 ; Min u endaddwf inNum,f ; Add value to min u end to

; com pen sate for last; op er a tion

sub10:movlw .10

Data EEPROM 339

Page 361: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

subwf inNum,f ; Sub tract 10btfsc STATUS,C ; Did sub tract over flow?goto bump10 ; No. Count sub trac tiongoto end10

bump10:incf thisDig,f ;in cre ment digit coun tergoto sub10

; Store 10th digitend10:

movlw .10addwf inNum,f ; Ad just for last subractionmovf thisDig,w ; get digit coun ter con tentsaddlw 0x30 ; Convert to ASCIImovwf asc10 ; Store it

; Cal cu late and store units digitmovf inNum,w ; Store units valueaddlw 0x30 ; Convert to ASCIImovwf asc1 ; Store digitre turn

;============================================================; EEPROM pro ce dures;============================================================;==============================; read EEPROM;==============================; Pro ce dure to read EEPROM mem ory. Ad dress of mem ory; lo ca tion to read is stored in lo cal reg is ter EEMemAdd; On exit: read data in wEERead:

bcf STATUS,RP0 ; Bank 0movf EEMemAdd,w ; Ad dress to wmovwf EEADR ; w to ad dress reg is terbsf STATUS,RP0 ; Bank 1bsf EECON1,RD ; EE Readbcf STATUS,RP0 ; Bank 0movf EEDATA,w ; W = EEDATAre turn

;==============================; write EEPROM;==============================; Pro ce dure to write asc1 byte to EEPROM mem ory; Ad dress to write stored in lo cal reg is ter EEMemAdd; Data byte to write is in lo cal reg is ter EEByteEEWrite:; Load byte to write into EE data reg is ter

movf EEByte,w ; Data to w

340 Chap ter 14

Page 362: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

movwf EEDATA ; Write; Set write ad dress in EE ad dress reg is ter

movf EEMemAdd,w ; Ad dress to wmovwf EEADR ; w to ad dress reg is ter

; Write data to EEPROM mem orybsf STATUS,RP0 ; Bank 1bcf INTCON,GIE ; Dis able INTs.bsf EECON1,WREN ; En able Writemovlw 0x55 ; Code # 1movwf EECON2 ; Write 0x55movlw 0xaa ; Code # 2movwf EECON2 ; Write 0xaabsf EECON1,WR ; Set WR bit

; Write op er a tion now takes place au to mat i callybsf INTCON,GIE ; Re-en able in ter ruptsbcf STATUS,RP0 ; Bank 0re turn

end

14.4.2 Ser2EEP Pro gram; File name: Ser2EEP.asm; Last re vi sion: May 22, 2011; Au thors: Canton and Sanchez; PIC: 16F877;; De scrip tion:; Re ceive char ac ter data through RS-232 line and store in; EEPROM data mem ory. Re ceived char ac ters are ech oed on; the sec ond LCD line. When <En ter> key is de tected (code; 0x0d) the text stored in EEPROM mem ory is re trieved and; dis played on the LCD. On start-up, the top LCD line dis plays; the prompt: 'Re ceiving:'. At that time a mes sage 'Rdy-' is; sent through the se rial line so as to test the con nec tion.;; De fault se rial line set ting:; 2400 baud; no par ity; 1 stop bit; 8 char ac ter bits;; Pro gram to use 4-bit PIC-to-LCD in ter face.; Code as sumes that LCD is driven by Hitachi HD44780; con trol ler and PIC 16F977. Dis play sup ports two lines,; each one with 20 char ac ters. The length, wir ing and base; ad dress of each dis play line is stored in #de fine; state ments. These state ments can be ed ited to ac com mo date

Data EEPROM 341

Page 363: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; a dif fer ent set-up.; ; WARNING:; Code as sumes 10 MHz clock. De lay rou tines must be; ed ited for a dif fer ent clock. Clock speed also de ter mines; val ues for baud rate set ting (see spbrgVal con stant).;;===========================; 16F877 switches;===========================; Switches used in __config di rec tive:; _CP_ON Code pro tec tion ON/OFF ; * _CP_OFF ; * _PWRTE_ON Power-up timer ON/OFF; _PWRTE_OFF ; _BODEN_ON Brown-out re set en able ON/OFF; * _BODEN_OFF ; * _PWRTE_ON Power-up timer en able ON/OFF; _PWRTE_OFF ; _WDT_ON Watch dog timer ON/OFF ; * _WDT_OFF; _LPV_ON Low volt age IC pro gram ming en able ON/OFF; * _LPV_OFF; _CPD_ON Data EE mem ory code pro tec tion ON/OFF; * _CPD_OFF; OSCILLATOR CONFIGURATIONS: ; _LP_OSC Low power crys tal os cil la tor; _XT_OSC Ex ter nal par al lel res o na tor/crys tal os cil la tor

; * _HS_OSC High speed crys tal res o na tor; _RC_OSC Re sis tor/ca pac i tor os cil la tor; | (sim plest, 20% er ror); |; |_____ * in di cates setup val ues pres ently se lected

pro ces sor 16f877 ; De fine pro ces sor#in clude <p16f877.inc>__CONFIG _CP_OFF & _WDT_OFF & _BODEN_OFF & _PWRTE_ON &

_HS_OSC & _WDT_OFF & _LVP_OFF & _CPD_OFF

; __CONFIG di rec tive is used to em bed con fig u ra tion data; within the source file. The la bels fol low ing the di rec tive; are lo cated in the cor re spond ing .inc file.

errorlevel -302; Sup press bank-re lated warn ing ;============================================================; M A C R O S;============================================================

342 Chap ter 14

Page 364: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; Macros to se lect the reg is ter banksBank0 MACRO ; Se lect RAM bank 0

bcf STATUS,RP0bcf STATUS,RP1ENDM

Bank1 MACRO ; Se lect RAM bank 1bsf STATUS,RP0bcf STATUS,RP1ENDM

Bank2 MACRO ; Se lect RAM bank 2bcf STATUS,RP0bsf STATUS,RP1ENDM

Bank3 MACRO ; Se lect RAM bank 3bsf STATUS,RP0bsf STATUS,RP1ENDM

;=====================================================; con stant def i ni tions; for PIC-to-LCD pin wir ing and LCD line ad dresses;=====================================================#de fine E_line 1 ;|#de fine RS_line 0 ;| => from wir ing di a gram #de fine RW_line 2 ;|; LCD line ad dresses (from LCD data sheet)#de fine LCD_1 0x80 ; First LCD line con stant#de fine LCD_2 0xc0 ; Sec ond LCD line con stant#de fine LCDlimit .20; Num ber of char ac ters per line#de fine spbrgVal .64; For 2400 baud on 10 MHz clock; Note: The con stants that de fine the LCD dis play; line ad dresses have the high-or der bit set; so as to meet the re quire ments of con trol ler; com mands. ;;==========================================================; Gen eral-Pur pose Vari ables;==========================================================; Lo cal vari ables; Re serve 20 bytes for string buffer

cblock 0x20strDataendc

; Other datacblock 0x34 ; Start of blockcount1 ; Coun ter # 1

Data EEPROM 343

Page 365: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

count2 ; Coun ter # 2count3 ; Coun ter # 3J ; Coun ter JK ; Coun ter KbufAddin dexstore1 ; Lo cal stor agestore2endc

;==============================; Com mon RAM Area;==============================; These GPRs can be ac cessed from any bank.; 15 bytes are avail able, from 0x70 to 0x7f

cblock 0x70; For LCDscroll pro ce dure

LCDcount ; Coun ter for char ac ters per lineLCDline ; Cur rent dis play line (0 or 1)

; Com mu ni ca tions vari ablesnewData ; not 0 if new data re ceivedascValerrorFlags

; EEPROM-re lated vari ablesEEMemAdd ; EEPROM ad dress to ac cessEEByte ; Data byte to writeendc

;============================================================; P R O G R A M;============================================================

org 0 ; start at ad dress goto main

; Space for in ter rupt han dlersorg 0x08

main:; Wiring:; LCD data to Port-D, lines 0 to 7; E line -> Port-E, 1; RW line -> Port-E, 2; RS line -> Port-E, 0; Set PORTE D and E for out put; First, ini tial ize Port-B by clear ing latches

clrf STATUSclrf PORTB

; Se lect bank 1 to TRIS Port-D for out putBank1

; TRIS Port-D for out put. Port-D lines 4 to 7 are wired; to LCD data lines. Port-D lines 0 to 4 are wired to LEDs.

344 Chap ter 14

Page 366: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

movlw B’00000000’movwf TRISD ; and Port-D

; By de fault Port-A lines are an a log. To con fig ure them; as dig i tal code must set bits 1 and 2 of the ADCON1; reg is ter (in bank 1)

movlw 0x06 ; bi nary 0000 0110 is code to; make all Port-A lines dig i tal

movwf ADCON1; Port-B, lines are wired to key pad switches, as fol lows:; 7 6 5 4 3 2 1 0; | | | | |_|_|_|_____ switch rows (out put); |_|_|_|_____________ switch col umns (in put); rows must be de fined as out put and col umns as in put

movlw b’11110000’movwf TRISB

; TRIS Port-E for out putmovlw B’00000000’movwf TRISE ; TRIS Port-E

; En able Port-B pullups for switches in OPTION reg is termovlw b’00001000’movwf OPTION_REG

; Back to bank 0Bank0

; Ini tial ize se rial Port for 2400 baud, 8 bits, no par ity,; 1 stop

call InitSerial; Test se rial trans mis sion by send ing "RDY-"

movlw ‘R’call SerialSendmovlw ‘D’call SerialSendmovlw ‘Y’call SerialSendmovlw ‘-’call SerialSendmovlw 0x20call SerialSend

; Clear all out put linesmovlw b’00000000’ movwf PORTDmovwf PORTE

; Wait and ini tial ize HD44780call de lay_5 ; Al low LCD time to ini tial ize it selfcall initLCD ; Then do forced ini tial iza tioncall de lay_5 ; (Wait prob a bly not nec es sary)

; Clear char ac ter coun ter and line coun ter vari ablesclrf LCDcountclrf LCDline

Data EEPROM 345

Page 367: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; Set dis play ad dress to start of first LCD linecall line1

; Store ad dress of dis play buffermovlw 0x20movwf bufAdd

; Dis play 'Re ceiving: ' mes sage promptcall blank20 ; Clear buffermovlw 0x00 ; Off set in buffercall storeMS1 ; Store mes sage at off setcall display20 ; Dis play mes sage

; Start ad dress of EEPROMclrf EEMemAdd

; Setup for dis play in sec ond linecall line2clrf LCDlineincf LCDline,f ; Set scroll con trol for

; line 2;============================================================; re ceive se rial data, store, and dis play;============================================================re ceive:; Call se rial re ceive pro ce dure

call SerialRcv; HOB of newData reg is ter is set if new data; re ceived

btfss newData,7goto scanExit

; At this point new data was re ceived.movwf EEByte ; Save re ceived char ac ter

; Dis play char ac ter on LCDmovf EEByte,w ; Re cover char ac tercall send8 ; Dis play in LCDcall LCDscroll ; Scroll at end of line

; Store char ac ter in EEPROM at lo ca tion in EEMemAddcall EEWrite ; Lo cal pro ce dureincf EEMemAdd,f ; Bump to next EEPROM

; Check for <En ter> key (0x0d) and ex e cute dis play func tionmovf EEByte,w ; Re cover last re ceivedsublw 0x0dbtfsc STATUS,Z ; Test if <En ter> keygoto isEnter ; Go if <En ter>

; Not <En ter> key, con tinue pro cess ingscanExit:

goto re ceive ; Con tinue;============================; dis play EEPROM data;============================; This rou tine re ceives con trol when the <En ter> key is

346 Chap ter 14

Page 368: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; re ceived.; Ac tion:; 1. Clear LCD; 2. Out put is set to top LCD line; 3. Char ac ters stored in EEPROM are dis played; un til 0x0d code is de tectedisEnter:

call clearLCD; Clear char ac ter coun ter and line coun ter vari ables

clrf LCDcountclrf LCDline

; Read data from EEPROM mem ory, start ing at ad dress 0; and dis play on LCD un til 0x0d ter mi na tor

call line1clrf EEMemAdd ; Start at EEPROM 0

readOne:call EERead ; Get char ac ter

; Store char ac termovwf EEByte ; Save char ac ter

; Test for ter mi na torsublw 0x0dbtfsc STATUS,Z ; Test if 0x0dgoto atEnd ; Go if 0x0d

; At this point char ac ter read is not 0x0d; Dis play on LCD

movf EEByte,w ; Re cover char ac ter; Dis play char ac ter on LCD

call send8 ; Dis play in LCDcall LCDscroll ; Scroll at end of lineincf EEMemAdd,f ; Next EEPROM bytegoto readOne

; End of ex e cu tionatEnd:

goto atEnd

;============================================================;============================================================; L O C A L P R O C E D U R E S ;============================================================;============================================================;==========================; init LCD for 4-bit mode ;==========================initLCD:; Ini tial iza tion for Densitron LCD mod ule as fol lows:; 4-bit in ter face; 2 dis play lines of 16 char ac ters each

Data EEPROM 347

Page 369: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; cur sor on; left-to-right in cre ment; cur sor shift right; no dis play shift;=======================|; set com mand mode |;=======================|

bcf PORTE,E_line ; E line lowbcf PORTE,RS_line ; RS line lowbcf PORTE,RW_line ; Write modecall de lay_125 ; de lay 125 mi cro sec ondsmovlw 0x28 ; 0 0 1 0 1 0 0 0 (FUNCTION SET)call send8 ; 4-bit send rou tine

; Set 4-bit mode com mand must be re peatedmovlw 0x28call send8movlw 0x0e ; 0 0 0 0 1 1 1 0 (DISPLAY ON/OFF)call send8movlw 0x06 ; 0 0 0 0 0 1 1 0 (ENTRY MODE SET)call send8movlw 0x14 ; 0 0 0 1 0 1 0 0 (CURSOR/DISPLAY

; SHIFT)call send8movlw 0x01 ; 0 0 0 0 0 0 0 1 (CLEAR DISPLAY)

; |___ COMMAND BITcall send8call de lay_5 ; Test for busyre turn

.;===========================; pro ce dure to clear LCD;============================clearLCD:

bcf PORTE,E_line ; E line lowbcf PORTE,RS_line ; RS line lowbcf PORTE,RW_line ; Write modecall de lay_125 ; de lay 125 mi cro sec ondsmovlw 0x01 ; 0 0 0 0 0 0 0 1 (CLEAR DISPLAY)

; |___ COMMAND BITcall send8call de lay_5 ; Test for busyre turn

;=======================; Pro ce dure to de lay; 42 mi cro sec onds;=======================de lay_125:

348 Chap ter 14

Page 370: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

movlw .105 ; Re peat 105 ma chine cy clesmovwf count1 ; Store value in coun ter

re peatdecfsz count1,f ; Dec re ment coun tergoto re peat ; Con tinue if not 0re turn ; End of de lay

;=======================; Pro ce dure to de lay; 5 mil li sec onds;=======================de lay_5:

movlw .105 ; Coun ter = 105 cy clesmovwf count2 ; Store in vari able

de lay:call de lay_125 ; De laydecfsz count2,f ; 40 times = 5 mil li sec ondsgoto de layre turn ; End of de lay

;========================; pulse E line ;========================pulseE

bsf PORTE,E_line ; Pulse E linenopbcf PORTE,E_linere turn

;=============================; long de lay sub-rou tine;=============================long_de lay:

movlw D’200’ ; w de lay countmovwf J ; J = w

jloop:movwf K ; K = w

kloop:decfsz K,f ; K = K-1, skip next if zerogoto kloopdecfsz J,f ; J = J-1, skip next if zerogoto jloopre turn

;========================; send 2 nib bles in; 4-bit mode;========================; Pro ce dure to send two 4-bit val ues to Port-B lines; 7, 6, 5, and 4. High-or der nib ble is sent first

Data EEPROM 349

Page 371: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; ON ENTRY:; w reg is ter holds 8-bit value to sendsend8:

movwf store1 ; Save orig i nal valuecall merge4 ; Merge with Port-B

; Now w has merged bytemovwf PORTD ; w to Port-Dcall pulseE ; Send data to LCD

; High nib ble is sentmovf store1,w ; Re cover byte into wswapf store1,w ; Swap nib bles in wcall merge4movwf PORTDcall pulseE ; Send data to LCDcall de lay_125re turn

;==========================; merge bits;==========================; Rou tine to merge the 4 high-or der bits of the; value to send with the con tents of Port-B; so as to pre serve the 4 low-bits in Port-B; Logic:; AND value with 1111 0000 mask; AND Port-B with 0000 1111 mask; Now low nib ble in value and high nib ble in; Port-B are all 0 bits:; value = vvvv 0000; Port-B = 0000 bbbb; OR value and Port-B re sult ing in:; vvvv bbbb ; ON ENTRY:; w con tain value bits; ON EXIT:; w con tains merged bitsmerge4:

andlw b’11110000’ ; ANDing with 0 clears the; bit. ANDing with 1 pre serves; the orig i nal value

movwf store2 ; Save re sult in vari ablemovf PORTD,w ; Port-D to w reg is terandlw b’00001111’ ; Clear high nib ble in Port-b

; and pre serve low nib bleiorwf store2,w ; OR two operands in wre turn

;==========================; Set ad dress reg is ter; to LCD line 2

350 Chap ter 14

Page 372: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

;==========================; ON ENTRY:; Ad dress of LCD line 2 in con stant LCD_2 line2:

bcf PORTE,E_line ; E line lowbcf PORTE,RS_line ; RS line low, setup for

; con trolcall de lay_5 ; Busy?

; Set to sec ond dis play linemovlw LCD_2 ; Ad dress with high-bit setcall send8

; Set RS line for databsf PORTE,RS_line ; RS = 1 for datacall de lay_5 ; Busy?re turn

;==========================; Set ad dress reg is ter; to LCD line 1;==========================; ON ENTRY:; Ad dress of LCD line 1 in con stant LCD_1 line1:

bcf PORTE,E_line ; E line lowbcf PORTE,RS_line ; RS line low, set up for

; con trolcall de lay_5 ; busy?

; Set to sec ond dis play linemovlw LCD_1 ; Ad dress and com mand bitcall send8 ; 4-bit rou tine

; Set RS line for databsf PORTE,RS_line ; Setup for datacall de lay_5 ; Busy?re turn

;==========================; scroll to LCD line 2 ;==========================; Pro ce dure to count the num ber of char ac ters dis played on; each LCD line. If the num ber reaches the value in the; con stant LCDlimit, then dis play is scrolled to the sec ond; LCD line. If at the end of the sec ond line, then LCD is; re set to the first line.LCDscroll:

incf LCDcount,f ; Bump coun ter; Test for line limit

movf LCDcount,wsublw LCDlimit ; Count mi nus limitbtfss STATUS,Z ; Is count minus limit = 0

Data EEPROM 351

Page 373: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

goto scrollExit ; Go if not at end of line; At this point the end of the LCD line was reached; Test if this is also the end of the sec ond line

movf LCDline,wsublw 0x01 ; Is it line 1?btfsc STATUS,Z ; Is LCDline mi nus 1 = 0?goto line2End ; Go if end of sec ond line

; At this point it is the end of the top LCD linecall line2 ; Scroll to sec ond lineclrf LCDcount ; Re set coun terincf LCDline,f ; Bump line coun tergoto scrollExit

; End of sec ond LCD lineline2End:

call initLCD ; Re setclrf LCDcount ; Clear coun tersclrf LCDlinecall line1 ; Dis play to first line

scrollExit:re turn

;=============================; LCD dis play pro ce dure;=============================; Sends 20 char ac ters from PIC buffer with ad dress stored; in vari able bufAdd to LCD line pre vi ously se lecteddisplay20:

call de lay_5 ; Make sure not busy; Set up for data

bcf PORTA,E_line ; E line lowbsf PORTA,RS_line ; RS line high for data

; Set up coun ter for 20 char ac tersmovlw D’20’movwf count3

; Get dis play ad dress from lo cal vari able bufAddmovf bufAdd,w ; First dis play RAM ad dress

; to Wmovwf FSR ; W to FSR

getchar:movf INDF,w ; get char ac ter from dis play

; RAM; lo ca tion pointed to by file; se lect reg is ter

call send8 ; 4-bit in ter face rou tine; Test for 20 char ac ters dis played

decfsz count3,f ; Dec re ment coun tergoto nextchar ; Skipped if donere turn

352 Chap ter 14

Page 374: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

nextchar:incf FSR,f ; Bump pointergoto getchar

;===============================; first text string pro ce dure;===============================storeMS1:; Pro ce dure to store in PIC RAM buffer the mes sage; con tained in the code area la beled msg1; ON ENTRY:; vari able bufAdd holds ad dress of text buffer; in PIC RAM; w reg is ter hold off set into stor age area; msg1 is rou tine that re turns the string char ac ters; and a zero ter mi na tor; in dex is lo cal vari able that hold off set into; text ta ble. This vari able is also used for; tem po rary stor age of off set into buffer ; ON EXIT:; Text mes sage stored in buffer;; Store off set into text buffer (passed in the w reg is ter); in tem po rary vari able

movwf in dex ; Store w in in dex; Store base ad dress of text buffer in FSR

movf bufAdd,w ; first dis play RAM ad dress ; to W

addwf in dex,w ; Add off set to ad dressmovwf FSR ; W to FSR

; Ini tial ize in dex for text string ac cessmovlw 0 ; Start at 0movwf in dex ; Store in dex in vari able

; w still = 0get_msg_char:

call msg1 ; Get char ac ter from ta ble; Test for zero ter mi na tor

andlw 0x0ffbtfsc STATUS,Z ; Test zero flaggoto endstr1 ; End of string

; ASSERT: valid string char ac ter in w; store char ac ter in text buffer (by FSR)

movwf INDF ; store in buffer by FSRincf FSR,f ; in cre ment buffer pointer

; Re store ta ble char ac ter coun ter from vari ablemovf in dex,w ; Get value into waddlw 1 ; Bump to next char ac termovwf in dex ; Store ta ble in dex in

Data EEPROM 353

Page 375: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; vari ablegoto get_msg_char ; Con tinue

endstr1:re turn

; Rou tine for re turn ing mes sage stored in pro gram area; Mes sage has 10 char ac tersmsg1:

addwf PCL,f ; Ac cess ta bleretlw ‘R’retlw ‘e’retlw ‘c’retlw ‘e’retlw ‘i’retlw ‘v’retlw ‘i’retlw ‘n’retlw ‘g’retlw ‘:’retlw 0

;========================; blank buffer;========================; Pro ce dure to store 20 blank char ac ters in PIC RAM; buffer start ing at ad dress stored in the vari able; bufAddblank20:

movlw D’20’ ; Setup coun termovwf count1movf bufAdd,w ; First PIC RAM ad dressmovwf FSR ; In dexed ad dress ingmovlw 0x20 ; ASCII space char ac ter

storeit:movwf INDF ; Store blank char ac ter in PIC RAM

; buffer us ing FSR reg is terdecfsz count1,f ; Done?goto incfsr ; nore turn ; yes

incfsr:incf FSR,f ; Bump FSR to next buffer spacegoto storeit

;==============================================================; com mu ni ca tions pro ce dures;==============================================================; Initiazalize se rial Port for 2400 baud, 8 bits, no par ity,; 1 stop

354 Chap ter 14

Page 376: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

InitSerial:Bank1 ; Macro to se lect bank1

; Bits 6 and 7 of Port-C are mul ti plexed as TX/CK and RX/DT; for USART op er a tion. These bits must be set to in put in the; TRISC reg is ter

movlw b’11000000’ ; Bits for TX and RXiorwf TRISC,f ; OR into TRISc reg is ter

; The asyn chron ous baud rate is cal cu lated as fol lows:; Fosc; ABR = ---------; S*(x+1); where x is value in the SPBRG reg is ter and S is 64 if the high; baud rate se lect bit (BRGH) in the TXSTA con trol reg is ter is; clear, and 16 if the BRGH bit is set. For set ting to 2400 baud; us ing a 10 MHz os cil la tor at a slow baud rate, the for mula; is:;; 10,000,000 10,000,000; ---------- = ---------- = 2,403.84 (0.16% er ror); 64*(64+1) 4160 ;

movlw spbrgVal ; Value in spbrgVal = 64movwf SPBRG ; Place in baud rate gen er a tor

; Setup value: 0010 0000 = 0x20movlw 0x20 ; En able trans mis sion and high baud

; ratemovwf TXSTABank0 ; Bank 0

; Setup value: 1001 0000 = 0x90movlw 0x90 ; En able se rial Port-and con tin u ous

; re cep tionmovwf RCSTA

; clrf errorFlags ; Clear lo cal er ror flags

; reg is terre turn

;==============================; trans mit data;==============================; Test for Trans mit Reg is ter Empty and trans mit data in wSerialSend:

Bank0 ; Se lect bank 0btfss PIR1,TXIF ; check if trans mit ter busygoto $-1 ; wait un til trans mit ter is

not busymovwf TXREG ; and trans mit the datare turn

;==============================

Data EEPROM 355

Page 377: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; re ceive data;==============================; Pro ce dure to test line for data re ceived and re turn value; in w. Over run and fram ing er rors are de tected and; re mem bered in the vari able errorFlags, as fol lows:; 7 6 5 4 3 2 1 0 <== errorFlags; |- not used -- | | |___ over run er ror; |______ fram ing er rorSerialRcv:

clrf newData ; Clear new data re ceivedreg is ter

Bank0 ; Se lect bank 0; Bit 5 (RCIF) of the PIR1 Reg is ter is clear if the USART; re ceive buffer is empty. If so, no data has been re ceived

btfss PIR1,RCIF ; Check for re ceived datare turn ; Exit if no data

; At this point data has been re ceived. First elim i nate; pos si ble er rors: over run and fram ing.; Bit 1 (OERR) of the RCSTA reg is ter de tects over run; Bit 2 (FERR( of the RCSTA reg is ter de tects fram ing er ror

btfsc RCSTA,OERR ; Test for over run er rorgoto OverErr ; Er ror han dlerbtfsc RCSTA,FERR ; Test for fram ing er rorgoto FrameErr ; Er ror han dler

; At this point no er ror was de tected; Re ceived data is in the USART RCREG reg is ter

movf RCREG,w ; get re ceived databsf newData,7 ; Set bit 7 to in di cate new

; data; Clear er ror flags

clrf errorFlagsre turn

;==========================; er ror han dlers;==========================OverErr:

bsf errorFlags,0 ; Bit 0 is over run er ror; Re set sys tem

bcf RCSTA,CREN ; Clear con tin u ous re ceive bitbsf RCSTA,CREN ; Set to re-en able re cep tionre turn

;er ror be cause FERR fram ing er ror bit is set;can do spe cial er ror han dling here - this code sim ply clears; and con tin uesFrameErr:

bsf errorFlags,1 ; Bit 1 is fram ing er rormovf RCREG,W ; Read and throw away bad datare turn

356 Chap ter 14

Page 378: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

;============================================================; lo cal EEPROM data pro ce dures;============================================================; GPRs used in EEPROM-re lated code are placed in the com mon; RAM area (from 0x70 to 0x7f). This makes the reg is ters; ac ces si ble from any bank. ;==============================; read lo cal EEPROM;==============================; Pro ce dure to read EEPROM mem ory; ON ENTRY:; Ad dress of EEPROM mem ory lo ca tion to read is stored in; lo cal reg is ter EEMemAdd; ON EXIT:; Read data in wEERead:

Bank2movf EEMemAdd,W ; EEPROM ad dressmovwf EEADR ; to read fromBank3bcf EECON1,EEPGD ; Point to Data mem orybsf EECON1,RD ; Start readBank2movf EEDATA,W ; Data to w reg is terBank0re turn

;==============================; write lo cal EEPROM;==============================; Pro ce dure to write data byte to EEPROM mem ory; ON ENTRY:; Ad dress to write stored in lo cal reg is ter EEMemAdd; Data byte to write is in lo cal reg is ter EEByteEEWrite:

Bank3Wait2Start:

btfsc EECON1,WR ; Wait forGOTO Wait2Start ; write to fin ishBank2movf EEMemAdd,w ; Ad dress tomovwf EEADR ; SFRmovf EEByte,w ; Data tomovwf EEDATA ; SFRBank3bcf EECON1,EEPGD ; Point to Data mem orybsf EECON1,WREN ; and en able writes

; Dis able in ter rupts. Can be done in any case

Data EEPROM 357

Page 379: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

bcf INTCON,GIE; Write spe cial codes

movlw 0x55 ; First code is 0x55movwf EECON2movlw 0xaa ; Sec ond code is 0xaamovwf EECON2bsf EECON1,WR ; Start write op er a tionnop ; Time for writenop

; Test for end of write op er a tionwait2End:

btfsc EECON1,WR ; Wait un til WR cleargoto wait2End

;; Re-en able in ter rupts if pro gram uses in ter rupts; If not, com ment out next line; bsf INTCON,GIE;

bcf EECON1,WREN ; Pre vent ac ci den tal writesBank0re turn

;============================================================end ; END OF PROGRAM

;============================================================

14.4.3 I2CEEP Pro gram; File name: I2CEEP.asm; Last re vi sion: May 21, 2010; Au thors: Sanchez and Canton; Pro ces sor: 16F877;; De scrip tion:; Re ceive char ac ter data through RS-232 line and store in; 24LC04B EEPROM IC, us ing the I2C se rial pro to col in the; PIC’s MSSP mod ule. Re ceived char ac ters are ech oed on; the sec ond LCD line. When <En ter> key is de tected (code; 0x0d), the text stored in EEPROM mem ory is re trieved and; dis played on the LCD. On start-up the top LCD line dis plays; the prompt: "Re ceiving:". At that time a mes sage 'Rdy-' is; sent through the se rial line so as to test the con nec tion.;; De fault se rial line set ting:; 2400 baud; no par ity; 1 stop bit; 8 char ac ter bits

358 Chap ter 14

Page 380: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

;; Wiring:; 24LC04B SDA line is wired to PIC RC4 (MSSP SDA); 24LC04B SCL line is wired to PIC RC3 (MSSP SCL); 24LC04B A0-A2 and WP lines are not used (GND);; Pro gram to uses 4-bit PIC-to-LCD in ter face.; Code as sumes that LCD is driven by Hitachi HD44780; con trol ler and PIC 16F977. Dis play sup ports two lines,; each one with 20 char ac ters. The length, wir ing, and base; ad dress of each dis play line is stored in #de fine; state ments. These state ments can be ed ited to accommodate; a dif fer ent set-up.; ; WARNING:; Code as sumes 10 Mhz clock. De lay rou tines must be; ed ited for a dif fer ent clock. Clock speed also de ter mines; val ues for baud rate set ting (see spbrgVal con stant).;;===========================; 16F877 switches;===========================; Switches used in __config di rec tive:; _CP_ON Code pro tec tion ON/OFF ; * _CP_OFF ; * _PWRTE_ON Power-up timer ON/OFF; _PWRTE_OFF ; _BODEN_ON Brown-out re set en able ON/OFF; * _BODEN_OFF ; * _PWRTE_ON Power-up timer en able ON/OFF; _PWRTE_OFF ; _WDT_ON Watch dog timer ON/OFF ; * _WDT_OFF; _LPV_ON Low volt age IC pro gram ming en able ON/OFF; * _LPV_OFF; _CPD_ON Data EE mem ory code pro tec tion ON/OFF; * _CPD_OFF; OSCILLATOR CONFIGURATIONS: ; _LP_OSC Low power crys tal os cil la tor; _XT_OSC Ex ter nal par al lel res o na tor/crys tal os cil la tor

; * _HS_OSC High speed crys tal res o na tor; _RC_OSC Re sis tor/ca pac i tor os cil la tor; | (sim plest, 20% er ror); |; |_____ * in di cates setup val ues pres ently se lected

pro ces sor 16f877 ; De fine pro ces sor

Data EEPROM 359

Page 381: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

#in clude <p16f877.inc>__CONFIG _CP_OFF & _WDT_OFF & _BODEN_OFF & _PWRTE_ON &

_HS_OSC & _WDT_OFF & _LVP_OFF & _CPD_OFF

; __CONFIG di rec tive is used to em bed con fig u ra tion data; within the source file. The la bels fol low ing the di rec tive; are lo cated in the cor re spond ing .inc file.

errorlevel -302; Sup press bank-re lated warn ing ;============================================================; M A C R O S;============================================================; Macros to se lect the reg is ter banksBank0 MACRO ; Se lect RAM bank 0

bcf STATUS,RP0bcf STATUS,RP1ENDM

Bank1 MACRO ; Se lect RAM bank 1bsf STATUS,RP0bcf STATUS,RP1ENDM

Bank2 MACRO ; Se lect RAM bank 2bcf STATUS,RP0bsf STATUS,RP1ENDM

Bank3 MACRO ; Se lect RAM bank 3bsf STATUS,RP0bsf STATUS,RP1ENDM

;=====================================================; con stant def i ni tions; for PIC-to-LCD pin wir ing and LCD line ad dresses;=====================================================#de fine E_line 1 ;|#de fine RS_line 0 ;| => from wir ing di a gram #de fine RW_line 2 ;|; LCD line ad dresses (from LCD data sheet)#de fine LCD_1 0x80 ; First LCD line con stant#de fine LCD_2 0xc0 ; Sec ond LCD line con stant#de fine LCDlimit .20; Num ber of char ac ters per line#de fine spbrgVal .64; For 2400 baud on 10 MHz clock; Note: The con stant that de fine the LCD dis play; line ad dresses have the high-or der bit set; so as to meet the re quire ments of con trol ler; com mands.

360 Chap ter 14

Page 382: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

;==========================================================; con stants for I2C ini tial iza tion;==========================================================; I2C con nected to 24LC04B EEPROM.; The MSSP mod ule is in I2C MASTER mode.#de fine LC04READ 0xa0 ; I2C value for read con trol byte#de fine LC04WRITE 0xa1 ; I2C value for write con trol byte

;==========================================================; Gen eral Pur pose Vari ables;==========================================================; Lo cal vari ables; Re serve 20 bytes for string buffer

cblock 0x20strDataendc

; Other datacblock 0x34 ; Start of blockcount1 ; Coun ter # 1count2 ; Coun ter # 2count3 ; Coun ter # 3J ; Coun ter JK ; Coun ter KbufAddin dexstore1 ; Lo cal stor agestore2

; For LCDscroll pro ce dureLCDcount ; Coun ter for char ac ters per lineLCDline ; Cur rent dis play line (0 or 1)Endc

;;==============================; Com mon RAM area;==============================; These GPRs can be ac cessed from any bank.; 15 bytes are avail able, from 0x70 to 0x7f

cblock 0x70; Com mu ni ca tions vari ables

newData ; not 0 if new data re ceivedascValerrorFlags

; EEPROM-re lated vari ablesEEMemAdd ; EEPROM ad dress to ac cessEEByte ; Data byte to writeendc

;============================================================

Data EEPROM 361

Page 383: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; P R O G R A M;============================================================

org 0 ; start at ad dress goto main

; Space for in ter rupt han dlersorg 0x08

main:; Wiring:; LCD data to Port-D, lines 0 to 7; E line -> Port-E, 1; RW line -> Port-E, 2; RS line -> Port-E, 0; Set PORTE D and E for out put; First, ini tial ize Port-B by clear ing latches

clrf STATUSclrf PORTB

; Se lect bank 1 to TRIS Port-D for out putBank1

; TRIS Port-D for out put. Port-D lines 4 to 7 are wired; to LCD data lines. Port-D lines 0 to 4 are wired to LEDs.

movlw B’00000000’movwf TRISD ; and Port-D

; By de fault Port-A lines are an a log. To con fig ure them; as dig i tal code must set bits 1 and 2 of the ADCON1; reg is ter (in bank 1)

movlw 0x06 ; bi nary 0000 0110 is code to; make all Port-A lines dig i tal

movwf ADCON1; Port-B, lines are wired to key pad switches, as fol lows:; 7 6 5 4 3 2 1 0; | | | | |_|_|_|_____ switch rows (out put); |_|_|_|_____________ switch col umns (in put); rows must be de fined as out put and col umns as in put

movlw b’11110000’movwf TRISB

; TRIS Port-E for out putmovlw B’00000000’movwf TRISE ; TRIS Port-E

; En able Port-B pullups for switches in OPTION reg is termovlw b’00001000’movwf OPTION_REG

; Back to bank 0Bank0

; Ini tial ize se rial port for 2400 baud, 8 bits, no par ity; 1 stop

call InitSerial; Test se rial trans mis sion by send ing "RDY-"

movlw ‘R’

362 Chap ter 14

Page 384: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

call SerialSendmovlw ‘D’call SerialSendmovlw ‘Y’call SerialSendmovlw ‘-’call SerialSendmovlw 0x20call SerialSend

; Clear all out put linesmovlw b’00000000’ movwf PORTDmovwf PORTE

; Wait and ini tial ize HD44780call de lay_5 ; Al low LCD time to ini tial ize it selfcall initLCD ; Then do forced ini tial iza tioncall de lay_5

; Clear char ac ter coun ter and line coun ter vari ablesclrf LCDcountclrf LCDline

; Set dis play ad dress to start of first LCD linecall line1

; Store ad dress of dis play buffermovlw 0x20movwf bufAdd

; Dis play "Re ceiving:" mes sage promptcall blank20 ; Clear buffermovlw 0x00 ; Off set in buffercall storeMS1 ; Store mes sage at off setcall display20 ; Dis play mes sage

; Start ad dress of EEPROMclrf EEMemAdd

; Setup for dis play in sec ond linecall line2clrf LCDlineincf LCDline,f ; Set scroll con trol for line 2

; Ini tial ize I2C EEPROM op er a tioncall SetupI2C ; Lo cal pro ce dure

;============================================================; re ceive se rial data, store, and dis play;============================================================re ceive:; Call se rial re ceive pro ce dure

call SerialRcv; HOB of newData reg is ter is set if new data; re ceived

btfss newData,7goto scanExit

Data EEPROM 363

Page 385: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; At this point new data was re ceived.movwf EEByte ; Save re ceived char ac ter

; Dis play char ac ter on LCDmovf EEByte,w ; Re cover char ac tercall send8 ; Dis play in LCDcall LCDscroll ; Scroll at end of line

; Store char ac ter in EEPROM at lo ca tion in EEMemAddcall WriteI2C ; Lo cal pro ce dureincf EEMemAdd,f ; Bump to next EEPROM

; Check for <En ter> key (0x0d) and ex e cute dis play func tionmovf EEByte,w ; Re cover last re ceivedsublw 0x0dbtfsc STATUS,Z ; Test if <En ter> keygoto isEnter ; Go if <En ter>

; Not <En ter> key, con tinue pro cess ingscanExit:

goto re ceive ; Con tinue;============================; dis play EEPROM data;============================; This rou tine re ceives con trol when the <En ter> key is ; re ceived.; Ac tion:; 1. Clear LCD; 2. Out put is set to top LCD line; 3. Char ac ters stored in EEPROM are dis played; un til 0x0d code is de tectedisEnter:

call clearLCD; Clear char ac ter coun ter and line coun ter vari ables

clrf LCDcountclrf LCDline

; Read data from EEPROM mem ory, start ing at ad dress 0; and dis play on LCD un til 0x0d ter mi na tor

call line1clrf EEMemAdd ; Start at EEPROM 0

readOne:call ReadI2C ; Get char ac ter

; Store char ac termovwf EEByte ; Save char ac ter

; Test for ter mi na torsublw 0x0dbtfsc STATUS,Z ; Test if 0x0dgoto atEnd ; Go if 0x0d

; At this point char ac ter read is not 0x0d; Dis play on LCD

movf EEByte,w ; Re cover char ac ter; Dis play char ac ter on LCD

364 Chap ter 14

Page 386: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

call send8 ; Dis play in LCDcall LCDscroll ; Scroll at end of lineincf EEMemAdd,f ; Next EEPROM bytegoto readOne

; End of ex e cu tionatEnd:

goto atEnd

;============================================================;============================================================; L O C A L P R O C E D U R E S ;============================================================;============================================================;==========================; init LCD for 4-bit mode ;==========================initLCD:; Ini tial iza tion for Densitron LCD mod ule as fol lows:; 4-bit in ter face; 2 dis play lines of 16 char ac ters each; cur sor on; left-to-right in cre ment; cur sor shift right; no dis play shift;=======================|; set com mand mode |;=======================|

bcf PORTE,E_line ; E line lowbcf PORTE,RS_line ; RS line lowbcf PORTE,RW_line ; Write modecall de lay_125 ; de lay 125 mi cro sec ondsmovlw 0x28 ; 0 0 1 0 1 0 0 0 (FUNCTION

SET)call send8 ; 4-bit send rou tine

; Set 4-bit mode com mand must be re peatedmovlw 0x28call send8movlw 0x0e ; 0 0 0 0 1 1 1 0 (DISPLAY ON/OFF)call send8movlw 0x06 ; 0 0 0 0 0 1 1 0 (ENTRY MODE SET)call send8movlw 0x14 ; 0 0 0 1 0 1 0 0 (CURSOR/DISPLAY

; SHIFT)call send8movlw 0x01 ; 0 0 0 0 0 0 0 1 (CLEAR DISPLAY)call send8call de lay_5 ; Test for busyre turn

Data EEPROM 365

Page 387: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

.;===========================; pro ce dure to clear LCD;============================clearLCD:

bcf PORTE,E_line ; E line lowbcf PORTE,RS_line ; RS line lowbcf PORTE,RW_line ; Write modecall de lay_125 ; de lay 125 mi cro sec ondsmovlw 0x01 ; 0 0 0 0 0 0 0 1 call send8call de lay_5 ; Test for busyre turn

;=======================; Pro ce dure to de lay; 42 mi cro sec onds;=======================de lay_125:

movlw .105 ; Re peat 105 ma chine cy clesmovwf count1 ; Store value in coun ter

re peat:decfsz count1,f ; Dec re ment coun tergoto re peat ; Con tinue if not 0re turn ; End of de lay

;=======================; Pro ce dure to de lay; 5 mil li sec onds;=======================de lay_5:

movlw .105 ; Coun ter = 105 cy clesmovwf count2 ; Store in vari able

de lay:call de lay_125 ; De laydecfsz count2,f ; 40 times = 5 mil li sec ondsgoto de layre turn ; End of de lay

;========================; pulse E line ;========================pulseE

bsf PORTE,E_line ; Pulse E linenopbcf PORTE,E_linere turn

;=============================

366 Chap ter 14

Page 388: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; long de lay sub-rou tine;=============================long_de lay:

movlw D’200’ ; w de lay countmovwf J ; J = w

jloop:movwf K ; K = w

kloop:decfsz K,f ; K = K-1, skip next if zerogoto kloopdecfsz J,f ; J = J-1, skip next if zerogoto jloopre turn

;========================; send 2 nib bles in; 4-bit mode;========================; Pro ce dure to send two 4-bit val ues to Port-B lines; 7, 6, 5, and 4. High-or der nib ble is sent first; ON ENTRY:; w reg is ter holds 8-bit value to sendsend8:

movwf store1 ; Save orig i nal valuecall merge4 ; Merge with Port-B

; Now w has merged bytemovwf PORTD ; w to Port-Dcall pulseE ; Send data to LCD

; High nib ble is sentmovf store1,w ; Re cover byte into wswapf store1,w ; Swap nib bles in wcall merge4movwf PORTDcall pulseE ; Send data to LCDcall de lay_125re turn

;==========================; merge bits;==========================; Rou tine to merge the 4 high-or der bits of the; value to send with the con tents of Port-B; so as to pre serve the 4 low-bits in Port-B; Logic:; AND value with 1111 0000 mask; AND Port-B with 0000 1111 mask; Now low nib ble in value and high nib ble in; Port-B are all 0 bits:; value = vvvv 0000; Port-B = 0000 bbbb

Data EEPROM 367

Page 389: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; OR value and Port-B re sult ing in:; vvvv bbbb ; ON ENTRY:; w con tain value bits; ON EXIT:; w con tains merged bitsmerge4:

andlw b’11110000’ ; ANDing with 0 clears the; bit. ANDing with 1 pre serves; the orig i nal value

movwf store2 ; Save re sult in vari ablemovf PORTD,w ; Port-B to w reg is terandlw b’00001111’ ; Clear high nib ble in Port-b

; and pre serve low nib bleiorwf store2,w ; OR two operands in wre turn

;==========================; Set ad dress reg is ter; to LCD line 2;==========================; ON ENTRY:; Ad dress of LCD line 2 in con stant LCD_2 line2:

bcf PORTE,E_line ; E line lowbcf PORTE,RS_line ; RS line low, setup for

; con trolcall de lay_5 ; Busy?

; Set to sec ond dis play linemovlw LCD_2 ; Ad dress with high-bit setcall send8

; Set RS line for databsf PORTE,RS_line ; RS = 1 for datacall de lay_5 ; Busy?re turn

;==========================; Set ad dress reg is ter; to LCD line 1;==========================; ON ENTRY:; Ad dress of LCD line 1 in con stant LCD_1 line1:

bcf PORTE,E_line ; E line lowbcf PORTE,RS_line ; RS line low, set up for

; con trolcall de lay_5 ; busy?

; Set to sec ond dis play linemovlw LCD_1 ; Ad dress and com mand bitcall send8 ; 4-bit rou tine

368 Chap ter 14

Page 390: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; Set RS line for databsf PORTE,RS_line ; Setup for datacall de lay_5 ; Busy?re turn

;==========================; scroll to LCD line 2 ;==========================; Pro ce dure to count the num ber of char ac ters dis played on; each LCD line. If the num ber reaches the value in the; con stant LCDlimit, then dis play is scrolled to the sec ond; LCD line. If at the end of the sec ond line, then LCD is; re set to the first line.LCDscroll:

incf LCDcount,f ; Bump coun ter; Test for line limit

movf LCDcount,wsublw LCDlimit ; Count mi nus limitbtfss STATUS,Z ; Is count minus limit = 0goto scrollExit ; Go if not at end of line

; At this point the end of the LCD line was reached; Test if this is also the end of the sec ond line

movf LCDline,wsublw 0x01 ; Is it line 1?btfsc STATUS,Z ; Is LCDline mi nus 1 = 0?goto line2End ; Go if end of sec ond line

; At this point it is the end of the top LCD linecall line2 ; Scroll to sec ond lineclrf LCDcount ; Re set coun terincf LCDline,f ; Bump line coun tergoto scrollExit

; End of sec ond LCD lineline2End:

call initLCD ; Re setclrf LCDcount ; Clear coun tersclrf LCDlinecall line1 ; Dis play to first line

scrollExit:re turn

;=============================; LCD dis play pro ce dure;=============================; Sends 20 char ac ters from PIC buffer with ad dress stored; in vari able bufAdd to LCD line pre vi ously se lecteddisplay20:

call de lay_5 ; Make sure not busy; Set up for data

Data EEPROM 369

Page 391: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

bcf PORTA,E_line ; E line lowbsf PORTA,RS_line ; RS line high for data

; Set up coun ter for 20 char ac tersmovlw D’20’movwf count3

; Get dis play ad dress from lo cal vari able bufAddmovf bufAdd,w ; First dis play RAM ad dress to Wmovwf FSR ; W to FSR

getchar:movf INDF,w ; get char ac ter from dis play RAM

; lo ca tion pointed to by file se lect; reg is ter

call send8 ; 4-bit in ter face rou tine; Test for 20 char ac ters dis played

decfsz count3,f ; Dec re ment coun tergoto nextchar ; Skipped if donere turn

nextchar:incf FSR,f ; Bump pointergoto getchar

;===============================; first text string pro ce dure;===============================storeMS1:; Pro ce dure to store in PIC RAM buffer the mes sage; con tained in the code area la beled msg1; ON ENTRY:; vari able bufAdd holds ad dress of text buffer; in PIC RAM; w reg is ter holds off set into stor age area; msg1 is rou tine that re turns the string char ac ters; and a zero ter mi na tor; in dex is lo cal vari able that holds off set into; text ta ble. This vari able is also used for; tem po rary stor age of off set into buffer ; ON EXIT:; Text mes sage stored in buffer;; Store off set into text buffer (passed in the w reg is ter); in tem po rary vari able

movwf in dex ; Store w in in dex; Store base ad dress of text buffer in FSR

movf bufAdd,w ; first dis play RAM ad dress to Waddwf in dex,w ; Add off set to ad dressmovwf FSR ; W to FSR

; Ini tial ize in dex for text string ac cessmovlw 0 ; Start at 0

370 Chap ter 14

Page 392: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

movwf in dex ; Store in dex in vari able; w still = 0get_msg_char:

call msg1 ; Get char ac ter from ta ble; Test for zero ter mi na tor

andlw 0x0ffbtfsc STATUS,Z ; Test zero flaggoto endstr1 ; End of string

; ASSERT: valid string char ac ter in w; store char ac ter in text buffer (by FSR)

movwf INDF ; store in buffer by FSRincf FSR,f ; in cre ment buffer pointer

; Re store ta ble char ac ter coun ter from vari ablemovf in dex,w ; Get value into waddlw 1 ; Bump to next char ac termovwf in dex ; Store ta ble in dex in

; vari ablegoto get_msg_char ; Con tinue

endstr1:re turn

; Rou tine for re turn ing mes sage stored in pro gram area; Mes sage has 10 char ac tersmsg1:

addwf PCL,f ; Ac cess ta bleretlw ‘R’retlw ‘e’retlw ‘c’retlw ‘e’retlw ‘i’retlw ‘v’retlw ‘i’retlw ‘n’retlw ‘g’retlw ‘:’retlw 0

;========================; blank buffer;========================; Pro ce dure to store 20 blank char ac ters in PIC RAM; buffer start ing at ad dress stored in the vari able; bufAddblank20:

movlw D’20’ ; Setup coun termovwf count1movf bufAdd,w ; First PIC RAM ad dress

Data EEPROM 371

Page 393: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

movwf FSR ; In dexed ad dress ingmovlw 0x20 ; ASCII space char ac ter

storeitmovwf INDF ; Store blank char ac ter in PIC RAM

; buffer us ing FSR reg is terdecfsz count1,f ; Done?goto incfsr ; nore turn ; yes

incfsr:incf FSR,f ; Bump FSR to next buffer spacegoto storeit

;==============================================================; com mu ni ca tions pro ce dures;==============================================================; Initialize se rial port for 2400 baud, 8 bits, no par ity,; 1 stopInitSerial:

Bank1 ; Macro to se lect bank1; Bits 6 and 7 of Port-C are mul ti plexed as TX/CK and RX/DT; for USART op er a tion. These bits must be set to in put in the; TRISC reg is ter

movlw b’11000000’ ; Bits for TX and RXiorwf TRISC,f ; OR into TRISc reg is ter

; The asyn chron ous baud rate is cal cu lated as fol lows:; Fosc; ABR = -------; S*(x+1); where x is value in the SPBRG reg is ter and S is 64 if the high; baud rate se lect bit (BRGH) in the TXSTA con trol reg is ter is; clear, and 16 if the BRGH bit is set. For set ting to 2400 baud; us ing a 10 MHz os cil la tor at a slow baud rate, the for mula; is:; ; 10,000,000 10,000,000; ---------- = ----------- = 2,403.84 (0.16% er ror); 64*(64+1) 4160 ;

movlw spbrgVal ; Value in spbrgVal = 64movwf SPBRG ; Place in baud rate gen er a tor

; Setup value: 0010 0000 = 0x20movlw 0x20 ; En able trans mis sion and high

; baud ratemovwf TXSTABank0 ; Bank 0

; Setup value: 1001 0000 = 0x90movlw 0x90 ; En able se rial port and

; con tin u ous re cep tion

372 Chap ter 14

Page 394: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

movwf RCSTA;

clrf errorFlags ; Clear lo cal er ror flags reg is terre turn

;==============================; trans mit data;==============================; Test for Trans mit Reg is ter Empty and trans mit data in wSerialSend:

Bank0 ; Se lect bank 0btfss PIR1,TXIF ; check if trans mit ter busygoto $-1 ; wait un til trans mit ter is not busymovwf TXREG ; and trans mit the datare turn

;==============================; re ceive data;==============================; Pro ce dure to test line for data re ceived and re turn value; in w. Over run and fram ing er rors are de tected and; re mem bered in the vari able errorFlags, as fol lows:; 7 6 5 4 3 2 1 0 <== errorFlags; |- not used -- | | |___ over run er ror; |______ fram ing er rorSerialRcv:

clrf newData ; Clear new data re ceived reg is terBank0 ; Se lect bank 0

; Bit 5 (RCIF) of the PIR1 Reg is ter is clear if the USART; re ceive buffer is empty. If so, no data has been re ceived

btfss PIR1,RCIF ; Check for re ceived datare turn ; Exit if no data

; At this point data has been re ceived. First elim i nate; pos si ble er rors: over run and fram ing.; Bit 1 (OERR) of the RCSTA reg is ter de tects over run; Bit 2 (FERR( of the RCSTA reg is ter de tects fram ing er ror

btfsc RCSTA,OERR ; Test for over run er rorgoto OverErr ; Er ror han dlerbtfsc RCSTA,FERR ; Test for fram ing er rorgoto FrameErr ; Er ror han dler

; At this point no er ror was de tected; Re ceived data is in the USART RCREG reg is ter

movf RCREG,w ; get re ceived databsf newData,7 ; Set bit 7 to in di cate new

data; Clear er ror flags

clrf errorFlagsre turn

;==========================

Data EEPROM 373

Page 395: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; er ror han dlers;==========================OverErr:

bsf errorFlags,0 ; Bit 0 is over run er ror; Re set sys tem

bcf RCSTA,CREN ; Clear con tin u ous re ceive bitbsf RCSTA,CREN ; Set to re-en able re cep tionre turn

;er ror be cause FERR fram ing er ror bit is set;can do spe cial er ror han dling here - this code sim ply clears; and con tin uesFrameErr:

bsf errorFlags,1 ; Bit 1 is fram ing er rormovf RCREG,W ; Read and throw away bad datare turn

;============================================================; I2C EEPROM data pro ce dures;============================================================; GPRs used in EEPROM-re lated code are placed in the com mon; RAM area (from 0x70 to 0x7f). This makes the reg is ters; ac ces si ble from any bank.;============================; LIST OF PROCEDURES;============================; SetupI2C -- Ini tial ize MSSP mod ule for I2C mode; in hard ware mas ter mode; Con fig ure I2C lines; Set slew rate for 100 Kbps; Set baud rate for 10 MHz; WriteI2C -- Write byte to I2C EEPROM de vice; Data is stored in EEByte vari able; Ad dress is stored in EEMemAdd; ReadI2C -- Read byte from I2C EEPROM de vice; Ad dress stored in EEMemAdd; Read data re turned in w reg is ter;============================; I2C setup pro ce dure;============================SetupI2C:

Bank1movlw b’00011000’iorwf TRISC,f ; OR into TRISC

; Setup MSSP mod ule for Mas ter Mode op er a tionBank0movlw B’00101000’; En ables MSSP and uses ap pro pri ate

; 0 0 1 0 1 0 0 0 Value to in stall; 7 6 5 4 3 2 1 0 <== SSPCON bits in this op er a tion; | | | | |__|__|__|___ Se rial port se lect bits

374 Chap ter 14

Page 396: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; | | | | 1000 = I2C mas ter mode; | | | | Clock = Fosc/(4*(SSPAD+1)); | | | |_______________ UNUSED IN MASTER MODE; | | |__________________ SSP En able; | | 1 = SDA and SCL pins as se rial; | |_____________________ Re ceive overflow in di ca tor; | 0 = no over flow ; |________________________ Write col li sion de tect; 0 = no col li sion de tected

movwf SSPCON ; This is loaded into SSPCON; In put lev els and slew rate as stan dard I2C

Bank1movlw B’10000000’

; 1 0 0 0 0 0 0 0 Value to in stall; 7 6 5 4 3 2 1 0 <== SSPSTAT bits in this op er a tion; | | | | | | | |___ Buffer full sta tus bit READ ONLY; | | | | | | |______ UNUSED in pres ent ap pli ca tion; | | | | | |_________ Read/write in for ma tion READ ONLY; | | | | |____________ UNUSED IN MASTER MODE; | | | |_______________ STOP bit READ ONLY ; | | |__________________ Data ad dress READ ONLY; | |_____________________ SMP bus se lect; | 0 = use nor mal I2C specs; |________________________ Slew rate con trol; 0 = dis abled

movwf SSPSTAT; Set-up Baud Rate; Baud Rate = Fosc/(4*(SSPADD+1)); Fosc = 10 MHz; Baud Rate = 24 for 100 Kbps

movlw .24 ; Value to use movwf SSPADD ; Store in SSPADDBank0re turn

;============================; I2C write pro ce dure;============================; Write one byte to I2C EEPROM 24LC04B; Steps:; 1. Send START; 2. Send con trol. Wait for ACK; 3. Send ad dress. Wait for ACK; 4. Send data. Wait for ACK; 5. Send STOP; STEP 1:WriteI2C:

Bank1

Data EEPROM 375

Page 397: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

bsf SSPCON2,SEN ; Pro duce START Con di tioncall WaitI2C ; Wait for I2C to com plete

; STEP 2:; Send con trol byte. Wair for ACK

movlw LC04READ ; Con trol bytecall Send1I2C ; Send Bytecall WaitI2C ; Wait for I2C to com pletebtfsc SSPCON2,ACKSTAT ; Check ACK bit to see if

; I2C failed, skip if notgoto FailI2C

; STEP 3:; Send ad dress. Wait for ACK

Bank0movf EEMemAdd,w ; Load Ad dress Bytecall Send1I2C ; Send Bytecall WaitI2C ; Wait for I2C op er a tion to com pleteBank1btfsc SSPCON2,ACKSTAT ; Check ACK Sta tus bit to see

; If I2C failed, skip if notgoto FailI2C

; STEP 4:; Send data. Wait for ACK

Bank0movf EEByte,w ; Load Data Bytecall Send1I2C ; Send Bytecall WaitI2C ; Wait for I2C op er a tion to com pleteBank1btfsc SSPCON2,ACKSTAT ; Check ACK Sta tus bit to see

; if I2C failed, skip if notgoto FailI2C

; STEP 5:; Send STOP. Wait for ACK

bsf SSPCON2,PEN ; Send STOP con di tioncall WaitI2C ; Wait for I2C op er a tion to com plete

; WRITE op er a tion has com pleted suc cess fully.Bank0re turn

;============================; I2C read pro ce dure ;============================; Pro ce dure to read one byte from 24LC04B EEPROM; Steps:; 1. Send START; 2. Send con trol. Wait for ACK; 3. Send ad dress. Wait for ACK; 4. Send RESTART + con trol. Wait for ACK; 5. Switch to re ceive mode. Get data.

376 Chap ter 14

Page 398: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; 6. Send NACK; 7. Send STOP; 8. Re trieve data into w reg is ter ; STEP 1:ReadI2C; Send RESTART. Wait for ACK

Bank1bsf SSPCON2,RSEN ; RESTART Con di tioncall WaitI2C ; Wait for I2C op er a tion

; STEP 2:; Send con trol byte. Wait for ACK

movlw LC04READ ; Con trol bytecall Send1I2C ; Send Bytecall WaitI2C ; Wait for I2C op er a tion

; Now check to see if I2C EEPROM is readyBank1btfsc SSPCON2,ACKSTAT ; Check ACK Sta tus bitgoto ReadI2C ; ACK Poll wait ing for EEPROM

; write to com plete; STEP 3:; Send ad dress. Wait for ACK

Bank0movf EEMemAdd,w ; Load from ad dress reg is tercall Send1I2C ; Send Bytecall WaitI2C ; Wait for I2C op er a tionBank1btfsc SSPCON2,ACKSTAT ; Check ACK Sta tus bitgoto FailI2C ; failed, skipped if suc cess ful

; STEP 4:; Send RESTART. Wait for ACK

bsf SSPCON2,RSEN ; Gen er ate RESTART Con di tioncall WaitI2C ; Wait for I2C op er a tion

; Send out put con trol. Wait for ACKmovlw LC04WRITE ; Load CONTROL BYTE (out put)call Send1I2C ; Send Bytecall WaitI2C ; Wait for I2C op er a tionBank1btfsc SSPCON2,ACKSTAT ; Check ACK Sta tus bitgoto FailI2C ; failed, skipped if suc cess ful

; STEP 5:; Switch MSSP to I2C Re ceive mode

bsf SSPCON2,RCEN ; En able Re ceive Mode (I2C); Get the data. Wait for ACK

call WaitI2C ; Wait for I2C op er a tion; STEP 6:; Send NACK to ac knowl edge

Bank1bsf SSPCON2,ACKDT ; ACK DATA to send is 1 (NACK)

Data EEPROM 377

Page 399: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

bsf SSPCON2,ACKEN ; Send ACK DATA now.; Once ACK or NACK is sent, ACKEN is au to mat i cally cleared; STEP 7:; Send STOP. Wait for ACK

bsf SSPCON2,PEN ; Send STOP con di tioncall WaitI2C ; Wait for I2C op er a tion

; STEP 8:; Read op er a tion has fin ished

Bank0movf SSPBUF,W ; Get data from SSPBUF into W

; Pro ce dure has fin ished and com pleted suc cess fully.re turn

;============================; I2C sup port pro ce dures;============================; I2C Op er a tion failed code se quence; Pro ce dure hangs up. User should pro vide er ror han dling.FailI2C

Bank1bsf SSPCON2,PEN ; Send STOP con di tioncall WaitI2C ; Wait for I2C op er a tion

fail:goto fail

; Pro ce dure to trans mit one byteSend1I2C

Bank0movwf SSPBUF ; Value to send to SSPBUFre turn

; Pro ce dure to wait for the last I2C op er a tion to com plete.; Code polls the SSPIF flag in PIR1.WaitI2C

Bank0btfss PIR1,SSPIF ; Check if I2C op er a tion donegoto $-1 ; I2C mod ule is not ready yetbcf PIR1,SSPIF ; I2C ready, clear flagre turn

;===========================================================

378 Chap ter 14

Page 400: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Chap ter 15

Step per Mo tors

15.1 De scrip tion and Op er a tionA sim ple DC mo tor ro tates when a volt age is ap plied to its ter mi nals; there fore its con -trol is quite sim ple. Step per mo tors, on the other hand, con vert elec tri cal pulses intodis crete units of ro ta tional move ment, which can be con trolled in de pend ently andwith out a feed back mech a nism. Typ i cally, the shaft or ro tor is toothed, while thestator con tains sev eral wind ings that are en er gized in a spe cific or der. The elec tro -mag netic at trac tion of the wind ings force the align ment of the toothed ro tor thus pro -duc ing ro ta tion. Fig ure 15-1 is a di a gram of a step per mo tor with eight wind ings andsix teeth on the ro tor.

Fig ure 15-1 Cross-Sec tion of a Typ i cal Step per Mo tor.

1

2

3

4

5

6

7

8

1

2

3

4

5

6

7

8

1

STEP 2STEP 1

STEP 3 STEP 4

2

3

4

5

6

7

8

1

2

3

4

5

6

7

8

A

B

CDE

F

A

BC

D

EF

A

BC

D

EF

A

B

CD

E

F

379

Page 401: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

The mo tor of Fig ure 15-1 be longs to a group called vari able-re luc tance mo tors.Per ma nent mag net and hy brid step per mo tors are also com mon. We have cho senthe VR type for the il lus tra tion due to its sim plic ity.

Step 1 in Fig ure 15-1 shows that wind ings la beled 1 and 5 are ini tially en er gized,forc ing the align ment of ro tor teeth A and D. In Step 2, stator wind ings 2 and 6 areen er gized, forc ing ro tor teeth C and F into align ment and ro tat ing the ro tor clock -wise. Steps 3 and 4 com plete the se quence. At the end of Step 4, the ro tor wouldhave turned 45 de grees, which means that the ro tor moves 5.625 de grees per pulseof the stator wind ing pairs and that, in this case, one com plete rev o lu tion of the ro -tor re quires thirty-two individual pulses.

Ro ta tion of a step per mo tor re quires that the elec tri cal pulses ap plied to thestator wind ings fol low a def i nite se quence. In the mo tor of Fig ure 15-1, the se -quence for clock wise ro ta tion con sists of ap ply ing cur rent to the wind ings la beled1-5, 4-8, 3-7, and 2-6, in that or der. If the pulses were ap plied in some other or der, the ro ta tion of the mo tor would be dif fer ent or would com pletely fail. By the same to -ken, by ap ply ing the pulses in some other or der the mo tor can be made to ro tate in a coun ter clock wise di rec tion. The speed of ro ta tion of a step per mo tors is de ter -mined by the fre quency of the pulses and the amount of ro ta tion by the num ber ofpulses. For ex am ple, the mo tor in Fig ure 15-1 could be made to ro tate 180 de grees(one-half rev o lu tion) by ap ply ing six teen pulses only. These con trols make step permotors powerful devices for use in embedded systems and robotics.

The fol low ing are the fun da men tal char ac ter is tics of step per mo tors in general:

• The mo tor has full torque at stand-still con di tion if the wind ings are en er gized.

• The ro ta tion an gle of the mo tor is de ter mined by its de sign and by the num ber andse quence of the ap plied pulses.

• Po si tion ing error of a step per mo tor is in the range of 3 to 5 per cent. This er ror doesnot ac cu mu late from step to step.

• Step per mo tors have long lives be cause they have no con tact brushes to wear out.

• The po si tion of a step per mo tor can be de ter mined from the num ber of in put pulsesap plied. This fea ture, called open-loop op er a tion, means that mo tor con trol is sim -ple and straight for ward be cause no feed back sig nals or op ti cal send ers are re -quired.

• Step per mo tors have good re sponse at start time and can be rap idly stopped or re -versed.

• Be cause step per mo tors do not have brushes, they do not pro duce elec tri cal arcs,which are un de sir able or even dan ger ous.

Step per mo tors are a good choice in ap pli ca tions that re quire con trol over mo torspeed, an gle of ro ta tion, di rec tion of ro ta tion, po si tion, or syn chro ni za tion. Theyfind fre quent use in ro bot ics, of fice equip ment such as print ers and fax ma chines, in floppy and hard disk drives, in med i cal equip ment, in com puter con trol of ma chinetools (CNC), and in automobiles.

380 Chap ter 15

Page 402: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

15.1.1 Step per Mo tor TypesAl though there are sev eral pos si ble clas si fi ca tions of step per mo tors, the hard warede sign falls into one of three main types:

Vari able Re luc tance

This type, which has been around the lon gest time, con sists of a soft core, which is of -ten toothed, and a stator con tain ing sev eral elec tro mag nets. The term vari able re luc -tance re fers to the prin ci ple that max i mum at trac tion oc curs be tween poles withmin i mum gaps. In Fig ure 15-1, which de picts a vari able re luc tance mo tor, you can seethat in each con sec u tive step the stator wind ings clos est to the ro tor poles, in a clock -wise di rec tion, are en er gized in se quence.

Per ma nent Mag net

These are of ten re ferred to as tin can mo tors. This type, which is the cheap est to buildand most com mon one, con sists of a per ma nent mag net ro tor with out teeth. Fig ure15-2 shows is a sche matic draw ing of a per ma nent mag net type step per mo tor.

Fig ure 15-2 Sche matic of a Per ma nent Mag net Step per Mo tor.

In the mo tor of Fig ure 15-2, the mag netic fields in the ro tor are in line with themo tor shaft and the ro tor does not have teeth. The ro tor mag netic fields al ter natenorth and south. As the wind ings in the stator are en er gized, the poles in the ro torare at tracted to the op po site poles in the stator and the motor rotates.

Hy brid

Hy brid step per mo tors use a com bi na tion of the vari able re luc tance and per ma nentmag net schemes. The ro tor in the hy brid mo tor is both toothed and mag ne tized. Theteeth pro vide a path for the mag netic flux, which in creases the hold ing power and themag netic char ac ter is tics of the mo tor. Be cause of their more com plex con struc tion,hy brid mo tors are con sid er ably more ex pen sive than per ma nent mag net types. At thesame time, they have better res o lu tion, and higher torque and speed.

Step per Mo tors 381

N N SSS

Page 403: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

15.1.2 Uni po lar Step per Mo torsIn elec tron ics, a pole (nor mally la beled North or South) is a re gion where mag neticflux den sity is con cen trated. Both the ro tor and the stator of step per mo tors havepoles. Sim i lar poles re pel each other (NN or SS) and op po site poles at tract (NS or SN).Thus, mag netic at trac tion of un like poles will make the ro tor move un til its northpoles are lo cated op po site the stator south poles, and vice versa.

Al though step per mo tors can be cat a loged in sev eral ways, from a pro gram mingand con trol view point the most use ful clas si fi ca tion is by the num ber of poles. Uni -po lar step per mo tors have two wind ings per phase, one for the di rec tion of eachmag netic field. The mag netic poles can be re versed by se lect ing which wind ing isen er gized. By not hav ing to change the di rec tion of the mag netic field, the cir cuit ofa uni po lar step per mo tor is very sim ple. Fig ure 15-3 de picts a uni po lar step per mo -tor.

Fig ure 15-3 Uni po lar Step per Mo tor Sche mat ics.

Note that the uni po lar mo tor in Fig ure 15-3 has two wind ings per phase, one foreach di rec tion of the mag netic field. The cen ter tap (la beled Vm) is con nected to acom mon line. This ar range ment al lows chang ing the mag netic pole of the wind ingwith out re vers ing the di rec tion of the cur rent flow. The two-phase com mon line issome times joint in ter nally, in which case the mo tor will have five wires. If the com -mon lines are sep a rate for each wind ing, then the mo tor will have six wires. In the il -lus tra tion, the top half of phase A is shown ac ti vated (light gray color). The lowerhalf (la beled phase bar A) is en er gized sep a rately. Sim i larly, the cen ter tap cre atestwo sep a rate phases in stator B, la beled phase B and phase bar B. The pres ence oftwo phases in each wind ing ex plains why uni po lar mo tors are some times re ferredto as four-phase mo tors, while in re al ity they have only two phases.

382 Chap ter 15

N

S

N

S

S

Vm

Phase A

Phase B Phase B

Phase A

Vm

NROTOR

STATOR A

STA

TO

R B

Page 404: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

15.1.3 De ter min ing Uni po lar and Bi po lar Wir ingIt is pos si ble to de ter mine the wir ing of a uni po lar or bi po lar step per mo tor with ei therfour, five, or six leads. The only in stru ment needed for this test is an ohm me ter.

Four-Wire Mo tor

A four-wire mo tor is al ways a bi po lar mo tor. The two wind ings can be eas ily iden ti fiedwith an ohm me ter: two wires that show fi nite re sis tance (closed cir cuit) are the endsof a wind ing.

Six-Wire Uni po lar Mo tor

STEP 1: Find the wires be long ing to each of the two wind ings by mea sur ing re sis -tance be tween wires. There will be two groups of three wires that show fi nite re sis -tance. La bel these groups of three wires as group A and group B.

STEP 2: Two wires in group A will show higher re sis tance than any other com bi na -tion. These are the end leads of the wind ings and should be la beled A and B. Thethird wire in the group is the com mon tap and should be la beled VmA. The com mon lead will show one-half of the re sis tance when tested against wires A or B.

STEP 3: Sim i larly, two wires in group B will show higher re sis tance than any othercom bi na tion. These are the end leads of the wind ings and should be la beled C andD. The third wire in the group is the com mon tap and should be la beled VmB.

STEP 4: Wires A and B should show in fi nite re sis tance when tested against wires C, D, or VmB. By the same to ken, wires C and D should show in fi nite re sis tance(open cir cuit) when tested against wires A, B, or VmA.

Five-Wire Uni po lar

STEP 1: Find a sin gle wire that shows fi nite re sis tance with all the other four wiresin the mo tor. This is the com mon lead and should be la beled Vm.

STEP 2: Find two other wires, ex clud ing Vm, that show fi nite re sis tance with eachother and la bel them A and B, re spec tively.

STEP 3: Sim i larly, the two re main ing wires will show fi nite re sis tance when testedwith each other. They should be la beled C and D.

STEP 4: Wires C and D should show in fi nite re sis tance (open cir cuit) when testedagainst wires A or B. Wires A, B, C, and D should show fi nite re sis tance (closed cir -cuit) when tested against Vm.

Fig ure 15-4 shows the wir ing di a gram for six- and five-wire uni po lar mo tors.

Fig ure 15-4 Six- and Five-Wire Step per Mo tors.

Step per Mo tors 383

VmAVm

VmB

A A

SIX-WIRE STEPPER MOTOR FIVE-WIRE STEPPER MOTOR

C CD D

B B

Page 405: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Some uni po lar step per mo tors are de signed to have two in di vid ual wind ings foreach stator phase. These mo tors, some times called bi fi lar mo tors, have two com -mon leads in each wind ing and the mo tor has a to tal of eight wires. The ad van tageof this de sign is that these mo tors can be op er ated as uni po lar or bi po lar de vices.

15.1.4 Bi po lar Step per Mo torsBi po lar mo tors have a sin gle wind ing per phase. The mo tor op er ates by re vers ing thecur rent flow in the wind ing, thus re vers ing the mag netic poles. Be cause there is a sin -gle wind ing for each phase, there is no cen ter tap and the mo tor has four wires. Fig ure15-5 shows the sche matic of a bi po lar step per mo tor.

Fig ure 15-5 Sche matic of a Bi po lar Step per Mo tor.

The en tire wind ing of a bi po lar mo tor is ac ti vated in each cy cle, while only halfthe wind ing is ac ti vated in a uni po lar mo tor. This re sults in bi po lar mo tors pro duc -ing more torque than uni po lar mo tors of the same size. On the other hand, be causethe cur rent flow in the wind ing must be re versed, bi po lar mo tors re quire more com -plex con trol cir cuitry. The most com mon cir cuit used in re vers ing the po lar ity of bi -po lar mo tors is known as an H bridge. One H bridge is re quired for each wind ing ina bi po lar mo tor. The H bridge is dis cussed later in this chap ter.

15.2 Step per Mo tor Con trols

Step per mo tors can be con trolled by means of gen eral elec tronic cir cuitry, by ICs spe -cially de signed for this pur pose, or by sig nals from mi cro pro ces sors ormicrocontrollers. Very of ten, a step per mo tor cir cuit com bines all three types of com -po nents. The com plex ity of the con trol cir cuitry of a step per mo tor de pends on thetype of mo tor and on the de gree of con trol re quired by the ap pli ca tion. Uni po lar mo -tors, al though less ef fi cient, are eas ier to con trol than bi po lar ones. Also, an ap pli ca -tion that is lim ited to turn ing on and off a step per mo tor, at a fixed speed and ro ta tiondi rec tion, would be sim pler to de sign and build than one that must vary the speed,change the di rec tion, and se lect among sev eral modes of op er a tion. Fig ure 15-6 is apho to graph of a bread board cir cuit for con trol ling a step per mo tor.

384 Chap ter 15

N

S

N

S

S

Ph

ase

A

Phase B

NROTOR

STATOR A

STA

TO

R B

Page 406: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 15-6 Bread board Cir cuit for a Uni po lar Mo tor.

The cir cuit in Fig ure 15-6 uses a 16F84A PIC microcontroller to han dle the sig nals to the uni po lar step per mo tor. The 4050 IC is a noninverting hex buffer that servesto drive the higher cur rent loads of the TIP 120 Dar ling ton tran sis tors. The four di -odes are an ad di tional safety to pro tect the cir cuit from backflows. The two whitepushbuttons, when held down, ac ti vate slow ro ta tion in the for ward and re verse di -rec tions, re spec tively. The dark gray pushbuttons do the same in fast ro ta tion. Thecir cuit and soft ware are de vel oped and explained later in this chapter.

15.2.1 Step ping Modes

The se quence in which the wind ings or wind ing sec tions are ac ti vated in a uni po lar orbi po lar step per mo tor is called the step ping mode. Three step ping modes are mostcom mon, al though a fourth mode, called microstepping, is oc ca sion ally used. Thegen eral char ac ter is tics are as fol lows.

Wave Drive Mode

In this mode a sin gle wind ing is en er gized at a time. The wave mode is easy to im ple -ment in the con trol hard ware but pro vides sig nif i cantly less than the rated torque ofthe mo tor. If the four wind ings of unipolar motors are la beled A, B, C, and D, then in the wave drive mode the wind ings are en er gized in the se quence: A → B → C → D. Fig ure15-7 shows a unipolar motor in the first cy cle of a wave mode se quence.

Step per Mo tors 385

unipolar stepper motor

16F84 PICDIODE X 4

4050 ICTIP 120 X 4

Page 407: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 15-7 Uni po lar Mo tor in Wave Mode Ac ti va tion Se quence.

The straight ar rows in Fig ure 15-7 show the var i ous po si tions of the ro tor as thewind ings are ac ti vated in se quence. The solid ar row rep re sents the orig i nal po si tionof the ro tor and the dashed ar rows the sub se quent po si tions as wind ings B, C, and D are turned on. The ac ti va tion se quence in Fig ure 15-7 re sults in a clock wise ro ta -tion. If the wind ings were ac ti vated in the or der A → D → C → B then the mo torwould ro tate coun ter clock wise. Note that in the wave mode, only 25 per cent of themo tor’s to tal wind ings are en er gized at any time.

Full Step Mode

In the full step mode two wind ings are ac ti vated dur ing each se quence step. Be causethe ro tor is equally at tracted to the two ac tive wind ings, it takes an in ter me di ate po si -tion. If the four wind ings of a unipolar motor are la beled A, B, C, and D, then in the fullstep drive mode the wind ings are en er gized in the se quence: AB → BC → CD → DA.Fig ure 15-8 shows a unipolar motor in the first cy cle of a full step mode se quence.

Fig ure 15-8 Uni po lar Mo tor in Full Step Mode Ac ti va tion Se quence.

386 Chap ter 15

BD

C

WAVE MODEWINDING ACTIVATION

SEQUENCE:ABCD

A

B

N

S

BD

C

FULL STEP MODEWINDING ACTIVATION

SEQUENCE:ABBCCDDA

A

B

N

S

Page 408: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

As in Fig ure 15-7, the straight ar rows show the var i ous po si tions of the ro tor asthe wind ings are ac ti vated in se quence. The ac ti va tion se quence in Fig ure 15-8 re -sults in a clock wise ro ta tion. If the wind ings were ac ti vated in the or der AD → DC→ CB → BA then the mo tor would ro tate coun ter clock wise. In full step mode, 50per cent of the mo tor’s to tal wind ings are en er gized at a time, re sult ing in higher ef fi -ciency than in the wave mode.

Half Step Mode

The half step mode com bines the wind ing ex ci ta tion se quence of the wave mode andthe full step mode in or der to dou ble the num ber of steps in each full rev o lu tion of thero tor. This means that sin gle wind ing and dou ble wind ing ex ci ta tion are gen er ated al -ter na tively, as shown in Fig ure 15-9.

Fig ure 15-9 Uni po lar Mo tor in Half-Step Mode Ac ti va tion Se quence.

Here again the straight ar rows show the var i ous po si tions of the ro tor as thewind ings are ac ti vated in se quence. In the half-step mode, the mo tor ro tatesone-half the an gle dur ing each ac ti va tion cy cle of the wind ings. The ac ti va tion se -quence in Fig ure 15-9 re sults in a clock wise ro ta tion. By re vers ing the or der of thecy cles, the mo tor is made to rotate counterclockwise.

Microstepping

Op er at ing a step per mo tor in any of the three modes dis cussed in this sec tion re sultsin a jer ki ness that var ies ac cord ing to the num ber of steps. This jer ki ness is a di rect re -sult of the abrupt changes in cur rent mag ni tude or di rec tion, which ap ply torque to the ro tor abruptly, as shown by the square wave cur rent changes in Fig ure 15-10.

Fig ure 15-10 Cur rent Tran si tions in Step ping.

Step per Mo tors 387

B BD D

C C

HALF STEP MODEWINDING ACTIVATION

SEQUENCE:ABB

BCC

CDD

DAA

A

STEP 1 STEP 2

A

B

N

S

B

N S

0 90 180 270 360

CURRENT

ROTOR ANGULAR POSITION

Page 409: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

With the wave form shown in Fig ure 15-10, as the volt age rises abruptly, so doesthe at trac tion of the stator wind ings on the mo tor poles. As the volt age de clinesabruptly at the end of each step, the at trac tion is in stantly turned off. This re sults inthe less-than-smooth move ment some times as so ci ated with step per mo tors. Thesquare wave in Fig ure 15-10 ap prox i mately rep re sents the level of at trac tion of thewind ings on the ro tor at var i ous po si tions in the step cycle.

Microstepping re duces or elim i nates this ef fect by vary ing the cur rent in thewind ings so as to pro duce a uni form at trac tion on the ro tor through out the step cy -cle. This can be achieved by mod i fy ing the cur rent ap plied to the wind ings so as tofol low the sine wave form shown by the dot ted line in the il lus tra tion. In this case,the at trac tion on the ro tor is uni form through out the step cy cle and the mo tor ro -tates smoothly. Be cause microstepping re quires con trol over the cur rent lev els, itre sults in more com plex cir cuitry, more so phis ti cated hard ware, and more com plexpro gram ming. Microstepping is cov ered in de tail in Chap ter 19.

388 Chap ter 15

Page 410: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Chap ter 16

Step per Mo tor Cir cuit Com po nents

16.1 Cir cuit El e mentsOver the years, step per mo tor hard ware and soft ware have pro lif er ated and evolved.To day there are scores, if not hun dreds, of ded i cated cir cuits and com po nents that are in tended for step per mo tor ap pli ca tions. In ad di tion, cir cuit de sign ers have foundways of uti liz ing el e ments that were not orig i nally de signed for step per cir cuits butthat have re sulted use ful or eco nom i cal. In this sec tion we cover the most used anduse ful cir cuit el e ments for step per mo tor driv ing and con trol. In this se lec tion wekeep in mind the book’s in ter me di ate scope as well as its fo cus on PICmicrocontrollers. The re sult is that we have ex cluded some in ter est ing cir cuits be -cause of their com plex ity or lim ited use or be cause they are based on con trol lers ornot cov ered in the text.

In gen eral, microcontroller-based step per mo tor cir cuits per form three func tions:

1. The con trol function. The com po nent or com po nents in this spe cial iza tion areaof the cir cuit pro vide the sig nals for op er at ing one or more step per mo tors. Thecon trol phase is a com mand func tion and the cir cuit el e ments are usu ally con ven -tional in put and out put com po nents such as switches, sen sors, potentiometers,key pads, and feed back de vices such as LEDs and LCDs.

2. The trans la tor function. Com po nents of this func tion can be a microcontroller, a spe cial ized IC, or a se ries of in di vid ual hard ware com po nents. The trans la tor reads the in put com mands from the con trol stage of the cir cuit and gen er ates the nec es -sary unipolar or bi po lar con trol sig nals for ac ti vat ing the driver function. The ac -tions to be per formed in clude, but are not lim ited to, for ward or re verse ro ta tion,speed control, stop and re sume com mands, and step ping mode se quence. In thisbook we con sider only microcontrollers in the trans la tor function. Ded i cated ICsthat in clude both trans la tor and driver functions are clas si fied as driv ers.

3. The driver function. Microcontrollers can carry currents up to 20 mA. Be causemost mo tors re quire more power, the driver stage con tains the hard ware that sup -plies this power. In ad di tion, some cir cuits must ma nip u late current polarity andin ten sity that are pro duced by the driver. In sum mary, the driver re ceives the sig -nals gen er ated by the trans la tor and con verts them into pulses of the ad e quate

389

Page 411: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

voltage, current, and po lar ity to drive the step per mo tor. The driver function canalso be called the power stage of the cir cuit or the power driver function.

These three stages are not neatly de lim ited. Of ten, driver IC per forms some func -tions that are typ i cally as so ci ated with the trans la tor stage. For ex am ple, theL297/298 IC pair, pre sented in Chap ter 18, is a two-chip driver that in cludes func -tions typ i cally as so ci ated with the trans la tor. In such cases we have clas si fied cir -cuit com po nents ac cord ing to their prin ci pal func tion or to some didacticalconvenience.

16.1.1 In put, Out put, and Feed backWe can imag ine a cir cuit that pro vides no con trol func tions. For ex am ple, a de vicethat turns on a mo tor when power is ap plied and turns it off when power is cut. Butsuch a sim plis tic op er a tion would be un usual. In a typ i cal cir cuit there will be com po -nents whose func tion is to turn on and off the var i ous modes and ex e cute the dif fer entcom mands and con trols. Oth ers will pro vide in for ma tion re gard ing pos si ble con trolsor the state of modes or de vices. Fi nally, a third group of com po nents can be used tofur nish feed back in for ma tion.

All con ven tional, com mon, and spe cialty cir cuit el e ments can pro vide in put.These in clude tog gle and pushbutton switches, jump ers, po ten ti om eters of var i ousde signs, sen sors, keypads, key boards, or a com puter con nected to the cir cuit. Out -put and feed back are also pro vided by off-the-shelf de vices such as LEDs,Seven-Seg ment LEDs, bar graph dis plays, liq uid crys tal dis plays (LCDs), or even full screens. In most cir cuits these de vices will be con nected to the in put and out putlines of the trans la tor, most of ten a microcontroller, which will mon i tor and drivethese el e ments. The ap pli ca tions and pro gram ming of most in put de vices used inmo tor circuits were dis cussed in Chap ter 9.

16.2 Trans la torOn the Web and in the lit er a ture, there are many cir cuits that both con trol and drivestep per mo tors. Typ i cally these trans la tor/driv ers are not pro gram ma ble de vices;they ei ther orig i nated at a time when microcontrollers were rare and ex pen sive orwere in tended for cir cuits that do not re quire pro gram ma ble logic. To day the abun -dance of pro gram ma ble ICs and their low prices make it dif fi cult to jus tify a step permo tor cir cuit of any com plex ity that does not in clude a microcontroller or mi cro pro -ces sor. In any case, be cause this book is also about pro gram ming, we fo cus on sys -tems with a pro gram ma ble trans la tor stage, spe cif i cally us ing the Micro chipmicrocontrollers (PIC). We clas sify ICs that in clude both trans la tor and driver func -tions as driv ers and re serve the term “trans la tor” for pro gram ma ble de vices.

16.2.1 PIC Microcontroller as a Trans la torWhich PIC we se lect as a mo tor con trol ler trans la tor de pends mostly on the cir cuitchar ac ter is tics and the ap pli ca tion. For ex am ple, in cir cuits that use microstepping(cov ered in de tail later in the book), it is rea son able to se lect a PIC that pro vides pulsewidth modulation (PWM) func tions. Al though microstepping can be achieved in de -vices with out PWM, it is the avail abil ity of PWM hardware that makes it eas i est to varythe current sent to the driver or power stage. Or in a cir cuit that re lies on an a log input,

390 Chap ter 16

Page 412: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

such as a potentiometer for con trol ling mo tor speed, a microcontroller with an an a -log-to-dig i tal mod ule will be quite con ve nient.

At this time, the sim plest and least ex pen sive PIC that can be prac ti cally used formicrostepping ap pli ca tions is the 16F684. This is a 14-pin, 8-bit de vice that con tainsan in ter nal os cil la tor thus mak ing ex ter nal clock ing un nec es sary. The pulse widthmod u la tion is pro vided by an en hanced cap ture, com pare, PMW mod ule. The PWMel e ment is 10 bits wide with one, two, or four out put chan nels with a max i mum fre -quency of 20 KHz. The IC also pro vides an a log-to-dig i tal con ver sions (A/D mod ule),which is con ve nient for driv ing an a log-based mo tor speed con trol de vices. The most im por tant lim i ta tion of the 16F684 is that there are only twelve I/O chan nels avail -able; six chan nels are mapped to port A and six to port C. A com plex ap pli ca tionwith mul ti ple in put and out put re quire ments may run out of port lines in a 16F684.Sev eral other mid-range PICs pro vide one or more PWM mod ules, in ad di tion tomore I/O lines and other spe cial ized func tions. For ex am ple, the 16F87x line hastwenty eight or forty pins, three or five ports, and two PWM mod ules. In this line,the forty-pin 16F877 has been a pop u lar fa vor ite over the years.

Many other ba sic and mid-range PICs are suit able for use in the sim pler step permo tor cir cuits. Con trol ling a step per mo tor di rectly with a PIC microcontroller, orus ing a PIC to send com mands to a ded i cated mo tor con trol ler IC, are quite pop u larand com mon tech niques. In these cases the only re quire ment in the PIC is the avail -abil ity of suf fi cient ports for the in put and out put lines needed by the cir cuit. Al -though the 16F84 has been dep re cated by Micro chip, it is , by far, the most pop u larPIC used as a step per mo tor con trol ler. A large per cent age of the cir cuits avail ableon the Web and in the pop u lar lit er a ture uses the 16F84 or the 16F84A. How ever, cir -cuits that re quire more com plex op er a tions, such as driv ing sev eral in put and out -put de vices, com mu ni cat ing with an LCD, op er at ing a key pad, or driv ing sev eralmo tors, usu ally re quire more powerful PICs. In these cases, the 16F877 is often asuitable alternative.

16.3 Trans la tor/Driv ersThere are many ded i cated ICs, usu ally called step per mo tor con trol lers, that pro videtrans la tor as well as mo tor driv ing func tions. These de vices are some times re ferred to as “trans la tors” in the spe cial ized lit er a ture. The ad van tage of us ing these ICs is thatthey take care of gen er at ing the re quired sig nals in the ap pro pri ate se quence, thusoffloading this task from the microcontroller. It is eas ier for the PIC ap pli ca tion to seta sin gle line low or high to se lect be tween full-step or half-step modes, than to ma nip u -late sev eral lines to pro duce the re quired se quence of steps. In this sec tion we list andde scribe some of the more pop u lar and use ful step per mo tor con trol lers. Many oth ersare avail able that fur ther sim plify spe cific cir cuits or that pro vide func tions usu allyfur nished dur ing the driver stage. The listed con trol lers are a mere sam pling.

16.3.1 UCN 5804This trans la tor/driver is one of the first of its kind and still quite pop u lar. It is fur nished as a six teen-pin IC in tended as a driver for uni po lar step per mo tors. Its max i mum cur -rent rat ing (which is one of its great est lim i ta tions) is 1.25 A per phase at 35V. The ICwill drive four out put lines with con tin u ous out put cur rent. The logic in cludes en -

Step per Mo tor Cir cuit Com po nents 391

Page 413: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

abling out put, di rec tion con trol, half-step and full-step modes, and a step in put linethat is typ i cally driven by a clock IC or a microcontroller. Ther mal pro tec tion dis ablesthe IC when chip tem per a ture is ex ces sive. In ter nal fly-back di odes pro vide pro tec -tion against tran sients, al though ex ter nal di odes are of ten in cluded as a safe guard.One of the cir cuits in Chap ter 17 is based on the UCN 5804. Fig ure 16-1 is a sche maticof the UCN 5804.

Fig ure 16-1 The UCN 5804 Step per Mo tor Con trol ler Pinout.

Al though the 5804 is no lon ger in pro duc tion, it is still readily avail able in theUnited States. The cur rent lim i ta tion of 1.25 A has led to other de signs in which thedriver is brought out side the chip. The Septronics StepGenie is a pop u lar sub sti tutefor the 5804. In the StepGenie, the driver con sists of four ex ter nals HEXFETs thatal low a cur rent rating of 15 A.

16.3.2 L297

An other fac tor in the de mise of the 5804 is the fact that the IC can only drive a uni po larmo tor. A more flex i ble cir cuit de sign is to use a chip, such as the L297, which is alsocom pat i ble with bi po lar driv ers. Be cause uni po lar mo tors can be driven in bi po larmode (with some pos si ble gain in power), this ap proach is of ten pref er a ble.

Typ i cally, the L297 re ceives com mand sig nals from a microcontroller and fur -nishes all the nec es sary drive sig nals to the power el e ment. In driv ing bi po lar mo -tors, it is usu ally com bined with the L298 or the L293E, which are dual, full-bridgedriv ers. A quad Dar ling ton ar ray or HEXFETs can also be used in the power stage.The in put sig nals into the L297 are step (la beled CLOCK), di rec tion, half-step orfull-step, en able, and a re set line. The ENABLE line is ac tive high and can be used to turn on and off the chip’s out put. There is also an out put line la beled HOME that sig -nals that the IC is in its initial state.

A SYNC line is an out put for the chip’s chop per os cil la tor (chop pers are cov eredin Chap ter 19) and can also be used to in put an ex ter nal clock sig nal, al though theL297 has its own os cil la tor. The mo tor out put lines are la beled A, B, C, and D. Sev -eral other pin func tions are also pres ent, in clud ing two in hibit lines, la beled INH1

392 Chap ter 16

+5V

58

04

Out B

K bd

Out D

Vss

Vss

Out C

K ac

Out A

1

2

3

4

5

6

7

8

16

15

14

13

12

11

10

9

Vdd

Enable

Dir

Vss

Vss

Step In

Half Step

One Phase

Page 414: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

and INH2, which are ac tive low con trols for the driv ers. INH1 in hib its the A and Bphases, and INH2 the C and D phases.

The min i mal cir cuit con fig u ra tion for the L297 is shown in Fig ure 16-2.

Fig ure 16-2 Min i mal Cir cuit Wir ing for the L297 IC.

In Fig ure 16-2 the lines la beled RPx are pos si ble con nec tions to a microcontroller port. The lines la beled NC are not con nected in this min i mal cir cuit con fig u ra tionand are left float ing. In other cir cuits, shown later in this chap ter, the un con nectedlines of Fig ure 16-2 are wired to pins in the driver stage. Two lines in hibit con trol ofthe two driver stages. These are la beled INH1 and INH2 in the di a gram. Be causethese lines are ac tive low, they must be held high in the min i mal con fig u ra tion.Other un used lines are ei ther left float ing or brought to ground, as shown in theillustration.

Al though the L297 is of ten em ployed in sim ple driv ers, it is ac tu ally most use fulwhen the cir cuit takes ad van tage of all the ca pa bil i ties of the IC. In one ap pli ca tionthe L297 can be con fig ured in a “chop per” scheme, con sist ing of a closed-loop feed -back sys tem. This ac tion is based on the fact that bi po lar mo tors re quire a high cur -rent at the start of the step, but at some point in the cy cle this cur rent can bere duced to a min i mum un til the next step be gins. The L297 ac com plishes the chop -ping func tion by com par ing the cur rent through the mo tor coil with a ref er ence volt -age on its pin 15 (la beled Vref in Fig ure 16-2). When the coil cur rent ex ceeds theref er ence value it is “chopped off” for the re main der of the power step. A trim merpo ten ti om e ter is in cluded in the cir cuit so as to ad just the ref er ence volt age to pro -vide max i mum torque with min i mal waste of power. Later in this chap ter wedevelop a complete circuit that uses the L297 in this man ner

Step per Mo tor Cir cuit Com po nents 393

+5v

+5V

L2

97

PO

WE

R S

TA

GE

SYNC

GND

HOME

Out A

INH 1

Out B

Out C

INH 2

Out D

ENABLE

1

2

3

4

5

6

7

8

9

10

20

19

18

17

16

15

14

13

12

11

RESET

Half/full

CLOCK

CW/CCW

OSC

Vref

SENS 1

SENS 2

Vs

CTRL

NC

NC

NC

NC

NC

RPx

RPx

RPx

RPx

RPxR

=1

0K

R=

10

K

Page 415: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

16.3.3 EDE1204This is a bi po lar con trol ler some what dif fer ent from the L297. The EDE1204 IC is fur -nished in an 18-pin pack age that pro vides both ex ter nal con trols and self-clock ing.Fig ure 16-3 is a func tional di a gram of the 1204.

Fig ure 16-3 EDE 1204 Step per Mo tor Con trol ler Pinout.

The full-step run mode is ac ti vated by set ting pin 10 low. In this mode, the di rec -tion pin (pin 7) makes the mo tor ro tate clock wise or coun ter clock wise; thehalf-step con trol can be used to dou ble the res o lu tion, and speed con trol pins A, B,and C (pins 11, 12 and 13) al low se lect ing eight pos si ble speeds. This ap pears to re -sult in sixteen pos si ble speeds, eight in full-step mode and eight in half-step mode.In re al ity, three speeds in full-step mode are du pli cated in the half-step mode, so theto tal num ber of dif fer ent speeds is ac tu ally thir teen. When the run pin is set high,then the 1204 goes into the step mode, and the mo tor speed is de ter mined with theclock sig nal re ceived on the step pin (pin 9). In the step mode the di rec tion andhalf-step pins con tinue to be ac tive. The free spin pin (pin 6), which is ac tive low,serves to de ac ti vate both mo tor coils. This re sults in a sus pen sion of the break ingef fect that is char ac ter is tic of step per mo tors. An other in ter est ing fea ture is thatthe IDE 1204 can change the stepping rate while the motor is running.

The self-clock ing fea ture of the 1204, which re sults in speed con trol with out anex ter nal clock sig nal, al lows for sim pli fi ca tion of some sim ple step per mo tor cir -cuits. For ex am ple, it is pos si ble to pro vide speed se lec tion and ro ta tion di rec tionby di rectly read ing in put de vices, thus elim i nat ing the microcontroller el e ment from the cir cuit. Cir cuits in which the microcontroller is over bur dened by other tasks can also benefit from this simplification.

16.3.4 SLA7060 and SLA7024

The SLA7060M, from Al le gro Mi cro sys tems, pro vides both con trol and drive func tions for two-phase, uni po lar step per mo tors. Their prin ci pal fea ture is that they in clude the trans la tor and the driver in a sin gle IC. The SLA7060 can use pulse width mod u la tion(PWM) to con trol the out put cur rent, thus sup port ing microstepping. Microsteppingcir cuits are cov ered in Chap ter 19. The SLA7024M, SLA7026M, and SMA7029M, alsofrom Al le gro, are also two-phase, uni po lar step per mo tor con trol ler/driver ICs, which

394 Chap ter 16

ED

E 1

20

4

COIL B

COIL B

+5v

+5v

GND

Free Spin

Direction

Half-step

Step

1

2

3

4

5

6

7

8

9

18

17

16

15

14

13

12

11

10

COIL A

COIL A

OSC 1

OSC 2

+5v

Speed Ctrl C

Speed Ctrl B

Speed Ctrl A

RUN/STEP

Page 416: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

in clude NMOS FETs that sup port high-cur rent and high-volt age out put. The dif fer -ences in the three ICs are cur rent rat ings and pack age styles.

16.4 Power DriverThe driver phase of a step per mo tor cir cuit pro vides power to the mo tor wind ings atthe nec es sary cur rent. The spe cific com po nents used in this stage de pend on the mo -tor char ac ter is tics as well as the cir cuit de sign. The driver phase com po nents are de -ter mined by the mo tor type: uni po lar or bi po lar.

16.4.1 Uni po lar Driv ersUni po lar cir cuits re quire sim ple driv ers con sist ing of tran sis tors that serve as cur -rent am pli fi ers, and pos si bly di odes to pre vent dam ag ing backflows. The most com -mon tran sis tors used in uni po lar driv ers are Dar ling ton tran sis tors. In ter nally the Dar -ling ton con sists of two bi po lar NPN tran sis tors con nected back-to-back so thecur rent out put of the first one is fur ther am pli fied by the sec ond one. This dou -ble-stage de sign is called a Dar ling ton pair. Dar ling ton pairs come in an ar ray pack -aged in an in te grated cir cuit, such as the ULN2803, or as in di vid ual tran sis tors such asthe TIP120.

PIC Microcontroller as a Driver

We have men tioned that a PIC microcontroller can con ve niently serve as a trans la torby fur nish ing the re quired se quence of power sig nals for a uni po lar step per mo tor. But us ing a PIC microcontroller to drive a step per mo tor pres ents dif fi cul ties. The maincon cern is that the cur rent-car ry ing ca pac ity of a PIC port pin is 20 mA. This meansthat only a very, very small mo tor could be driven di rectly.

Most real-world cir cuits re quire ad di tional am per age for the driver stage. Themost com mon so lu tion is to use sev eral tran sis tors. But here again, the cur rent-car -ry ing ca pac ity of the base pin of some tran sis tors ex ceeds the 20-mA lim i ta tion ofthe PIC port. For ex am ple, the TIP120 Dar ling ton tran sis tor, fre quently used in step -per mo tor cir cuits, can han dle up to 120 mA base cur rent. Al though with small loads it is pos si ble to drive a TIP120 tran sis tor di rectly from a PIC port, a more com monde sign is to use a cur rent gain de vice. In this ap pli ca tion the CMOS 4050 hex non-in -vert ing buffer IC can be placed be tween the PIC and the TIP120 be cause the 4050fur nishes suf fi cient cur rent gain (called fanout) to safely drive the base pin of aTIP120 tran sis tor, even at max i mum loads. One of the cir cuits de vel oped later inthis chap ter uses a PIC16F84 trans la tor and a 4050 IC to drive four TIP120 tran sis -tors.

ULN2803A

This is one of five mem bers of the ULN280x fam ily; the 2803 is com pat i ble with 5VTTL/CMOS in puts and there fore can be con nected di rectly to a PIC microcontrollerport. The IC pack ages eight Dar ling ton pairs in a DIP 18 IC that also in cludes in te gralsup pres sion di odes. All tran sis tors share a com mon emit ter, thus sav ing elec tronichard ware. The cur rent rat ing of the 2803 is of 500 mA at a max i mum of 50V. For driv inga uni po lar step per mo tor only four of the eight di odes are used. Fig ure 16-4 shows thepinout of the ULN2303.

Step per Mo tor Cir cuit Com po nents 395

Page 417: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Figure16-4 ULN 2803 Pinout.

In a typ i cal sys tem, the com mon di ode line of the 2803 (pin 10) is wired to the mo -tor’s power line (which we have la beled Vm). In puts from the trans la tor stage arewired to the IN x lines and the OUT x lines are con nected to the mo tor wind ings.The map ping of the IN lines, to the mo tor wind ings is de ter mined from the mo tor’sstep sequence.

TIP 120

The TIP120, al ready men tioned, is an NPN Dar ling ton tran sis tor in a TO-220 pack age.It is rated at 5 A and 60V. The TIP120 is de scribed as a gen eral-pur pose am pli fier at lowswitch ing speeds. Fig ure 16- 5 shows the TIP120 tran sis tor and its elec tronic sym bol.

Fig ure 16-5 TIP120 Am pli fier Tran sis tor.

The TIP120 con tains an in ter nal di ode but some cir cuits in clude a fast, ex ter nalone on the emit ter pin as ad di tional pro tec tion. In a typ i cal cir cuit, the base pin pro -vides in put from the con trol ler, the col lec tor serves as out put to the mo tor wind ing,and the emit ter line is set to ground.

396 Chap ter 16

UL

N 2

80

3A

IN 1

IN 2

IN 3

IN 4

IN 5

IN 6

IN 7

IN 8

GND

1

2

3

4

5

6

7

8

9

18

17

16

15

14

13

12

11

10

OUT 1

OUT 2

OUT 3

OUT 4

OUT 5

OUT 6

OUT 7

OUT 8

COMMON DIODE

EMITTER

EMITTER

COLLECTOR

COLLECTOR

BASE

BASE

Page 418: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

16.4.2 Bi po lar Driv ersBi po lar mo tors have a sin gle wind ing per phase, and ro ta tion is achieved by re vers ingthe cur rent flow in each wind ing. The most com mon de vice for re vers ing the cur rentflow in a DC cir cuit is called an H bridge.

In op er a tion, the H bridge can be vi su al ized as four switches placed along the ver -ti cal arms of an H-shaped com po nent, as shown in Fig ure 16-6.

Fig ure 16-6 H Bridge Cir cuit Vi su al iza tion.

In an ac tual cir cuit, the four switches, la beled SW A, SW B, SW C, and SW D inFig ure 16-6, take the place of four tran sis tors. In H bridge ter mi nol ogy, switches SWA and SW C are said to be on the left side of the bridge, while SW B and SW D are onthe right side. Switches SW A and SW B are on the high side and SW C and SW D onthe low side of the bridge. When SW A and SW D are closed, the cur rent flowsthrough the mo tor wind ing in one di rec tion. When SW A and SW D are open and SWB and SW C are closed, the cur rent flows in the op po site di rec tion. When all fourswitches are open, there is no flow through the cir cuit. Also note that if SW A andSW C are open (or SW B and SW D), the in put volt age source would be in short cir -cuit and dam age to the com po nents is likely. Be cause a bi po lar step per mo tors hastwo mo tor wind ings, two H bridges are required to drive it.

H bridges can be built us ing in di vid ual com po nents, usu ally MOSFET tran sis tors,and are also fur nished in ded i cated ICs. The L298, dis cussed later in this sec tion, isone such H bridge IC.

16.4.3 Tran sis tor ized H Bridge

When in di vid ual tran sis tors are used it is com mon to se lect two P-chan nel MOSFETsfor the high side of the bridge, and two N-chan nel MOSFETs for the low side. Fig ure16-7 shows a pop u lar H bridge de sign us ing P- and N-chan nel MOSFETs.

Step per Mo tor Cir cuit Com po nents 397

+5v

SW A SW B

SW C

MOTOR WINDING

SW D

Page 419: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 16-7 NPN-PNP Tran sis tor H Bridge.

The two tran sis tors la beled NPN(I) pro vide an in ter face with the IC that sup pliesthe in put sig nals. These tran sis tors can be the 2N2222 or any small-sig nal equiv a -lent. Many NPN-PNP tran sis tor pairs are suit able for the H bridge it self. Thematched pairs with iden ti cal char ac ter is tics are usu ally called com ple men tarytran sis tors. The NPN ZTX690B and the PNP ZTX790B in a TO-92 pack ages, are amatched pairs that de liver up to 2 Amps per coil. The TIP 3055 (NPN) and theTIP2955 (PNP) are also suit able and pro vide a 15 Amp cur rent gain. In te grated cir -cuits, such as the BC847BPN, are tran sis tor pairs that in clude the NPN and PNPcom po nents. Note that the H bridge in Fig ure 16-7 sup plies a sin gle mo tor coil. Todrive a bi po lar mo tor, two such H-bridges are re quired. A more ef fi cient, al beit more com pli cated, cir cuit uses N-chan nel MOSFETs for both the high and the low side.

Snub ber Di odes

When in duc tors are en er gized and de-en er gized the mag netic field in the coil builds up(in the en er giz ing phase) and col lapses (in the de-en er giz ing phase). Dur ing the col -laps ing phase the changes in the mag netic field in the coil cause a current to be in -duced and flow in the op po site di rec tion. This flow re ver sal may dam age theswitch ing transistors and other logic com po nents in the cir cuit. The prob lem can bepre vented by the in stal la tion of diodes in such a way so that they will not con duct dur -ing nor mal op er a tion. But when the fall ing mag netic field causes the current flow tore verse, then diodes con duct the current to ground and away from the transistors andother sen si tive com po nents. These are usu ally caller “snub ber” or “clamp ing” diodes.

The snub ber di odes are shown in the H bridge in Fig ure 16-7. In se lect ing thesedi odes, their cur rent car ry ing ca pac ity and switch ing speed must be con sid ered. Wead dress this prob lem in greater de tail in forth com ing sec tions re lated to mo tordriver cir cuits. The four snub ber di odes in Fig ure 16-7. can be ei ther the 1N4007 orthe 1N5408.

398 Chap ter 16

MotorSupplyVoltage

Mo

tor

Co

il

Inp

ut S

ign

als

NPN (I)

NPN (I)

NPN NPN

PNP PNP

R = 470 Ohm

R=1K

R=1K

R=

47

0 O

hm

Page 420: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

16.4.4 H Bridge ICsAn al ter na tive to the tran sis tor ized H bridge de scribed pre vi ously is the use of an in te -grated cir cuit driver that fur nishes the H bridge func tion, usu ally in ad di tion to otherdriver-level con trols. The cir cuit de signer of ten looks at these ad di tionalfunctionalities in or der to de ter mine if an IC driver is ap pro pri ate, as the H-bridgecom po nent by it self is quite com pat i ble with its tran sis tor-based coun ter part, as inFig ure 16-7.

A con sid er ation some times men tioned in fa vor of the in te grated cir cuit ver sionsof the H bridge, ver sus the tran sis tor ized op tion, is the pos si bil ity of dam age due toim proper bridge switch ac ti va tion with the tran sis tor ized vari a tion. This pos si bil ity is pre cluded with the IC com po nent be cause the dam ag ing con nec tions that canpos si bly dam age cir cuit com po nents are not allowed by the chip’s logic.

Driver ICs are some times de signed to com ple ment the functionalities of a spe -cific step per mo tor con trol ler. This is the case of the L297 (men tioned ear lier in thischap ter) and the L298 driver IC. The L297/298 pair pro vides a pow er ful set of fea -tures as shown by some cir cuits pre sented later in this chapter.

There are hun dreds of step per mo tor driver ICs avail able on the mar ket. A sin glecom pany (Al le gro Mi cro sys tems) pro duces over twenty dif fer ent bi po lar step permo tor driv ers. A list ing of their var i ous step per mo tor con trol prod ucts by spec i fi ca -tions and ap pli ca tions is available at:

http://www.allegromicro.com/en/Prod ucts/Cat e go ries/ICs/mo tor.asp

L293D

The L293D from ST Mi cro elec tron ics, SGS Thomson, and other ven dors, is a twoH-bridge, four-chan nel driver that in cludes the ap pro pri ate snub ber di odes. TheSN754410 from Texas In stru ments is re put edly an im proved sub sti tute for the L293.The L293 is fur nished in a six teen pin DIP. It can drive 1.2 A cur rent per chan nel; it istyp i cally used to drive NEMA teen-size step per mo tors. The L293 can be used to runtwo DC mo tors bi-di rec tion ally (not cov ered in this book) or to con trol the two wind -ings of a bi po lar step per mo tor. Fig ure 16-8 is a pin di a gram of the L293D.

Fig ure 16-8 L293D Bi po lar Mo tor Driver Pinout.

Step per Mo tor Cir cuit Com po nents 399

L2

93

D

ENABLE 1

INPUT 1

OUTPUT 1

GND

GND

OUTPUT 2

INPUT 2

Vm

1

2

3

4

5

6

7

8

16

15

14

13

12

11

10

9

Vs

INPUT 4

OUTPUT 4

GND

GND

OUTPUT 3

INPUT 3

ENABLE 2

Page 421: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

One ad van tage of the L293 is its low price (cur rently un der $2.00); an other is itssim plic ity. There are four in put lines that are typ i cally wired to the trans la tor phase. In or der to turn the mo tor on and off, two en able lines are ei ther held high by wir ingto the pos i tive power sup ply or are con trolled by the trans la tor. The four out putlines are wired to the mo tor coils. Four ground lines are on the cen ter of the IC,which fa cil i tates a PCB large ground that serves as a heat sink. The IC pin 16 is anin put for the logic volt age (typ i cally 5V) and pin 8 is an in put for the mo tor power. Acir cuit us ing the L293D driven by a 16F84 PIC (cir cuit SMB-L293D-1) is pre sented inChap ter 18. A sec ond cir cuit (SMB-L297-293D-1) in which an L297 is used in min i mal con fig u ra tion to drive an L293D is also described.

L298

The L298 is a pop u lar high-cur rent dual bridge driver of ten used in bi po lar step per mo -tor cir cuits. The sup ply cur rent can go up to 46V and 4 A, which al lows the L298, withap pro pri ate heat sinks, to drive NEMA 23 and larger step per mo tors. The IC is of fered in Multiwatt15 (ver ti cal and hor i zon tal) and PowerSO20 Pack ages. Fig ure 16-9 showsthe pinout and me chan i cal data for the L298 driver IC in the ver ti cal con fig u ra tion.

Fig ure 16-9 Pinout and Me chan i cal Data for L298 in Mutiwatt15 Pack age.

Cir cuits that use the L298 as a bi po lar driver range widely in com plex ity. In itssim plest cir cuit ver sion, the L298 re ceives coil in puts through its IN 1 to IN 4 linesand sends out put to the mo tor through the OUT 1 to OUT 4 lines (see Fig ure 16-9).The con trol ler in these cir cuits can be a microcontroller or an other IC. In these sim -ple con fig u ra tions the ENABLE A and ENABLE B lines are held high while theSENSE A and SENSE B lines are wired to ground. In all im ple men ta tions the Vs lineis wired to the cir cuit’s logic volt age sup ply and the Vm line to the mo tor power sup -ply. Be cause the L298 does not in clude snub ber di odes, these must be pro vided sep -a rately. Cir cuit SMB-298-1, pre sented later in Chap ter 18, shows a sim ple cir cuit inwhich the L298 is used mostly as a high-cur rent ca pac ity dou ble-H bridge. Othermore com plex L298 cir cuits are com bined with the L297, or other con trol lers, topro vide chop ping, pulse width mod u la tion, and microstepping. These moreadvanced circuits are discussed in Chapter 19.

16.5 Mod ules in Cir cuit Sche mat icsPre vi ously we clas si fied step per mo tor cir cuit func tions into three types: con trol,trans la tor, and driver. We also noted that many com mer cial de vices in clude func tions

400 Chap ter 16

L2

98

1

3

5

7

9

11

13

15

2

4

6

8

10

12

14

OUT 1

Vm

ENABLE A

GND

IN 3

IN 4

OUT 4

SENSE A

OUT 2

IN 1

IN 2

Vs

ENABLE B

OUT 3

SENSE B

Pin 1

Pin 15

Page 422: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

from more than one group. In this con text we find many cir cuits in which an IC per -forms both trans la tor and driver func tions, or those in which a microcontroller is pro -grammed to drive a step per mo tor, some times with no other sup port than a dig i talbuffer. For prac ti cal pur poses rather than to di vide cir cuits into con trol, trans la tor,and driver stages, it is pref er a ble to modularize as fol lows:

• The con trol and trans la tor stage in clude in put and out put de vices and dig i tal logic.In this stage the in put data is pro cessed and out put is sent to the driver stage or toother cir cuit de vices.

• The driver stage in cludes the power driver function as well as mo tor-spe cific con -trol functions.

Two ad van tages of this modularization are re us abil ity and the pos si bil ity of shuf -fling stages to suit a par tic u lar de sign. The con trol and trans la tor stage can be usedwith sev eral com pat i ble driv ers by de vel op ing ad-hoc soft ware. For ex am ple, a cir -cuit mod ule that con tains sev eral tog gle and pushbutton switches and a 16F84microcontroller can be paired with ei ther a uni po lar or bi po lar driver. In ei ther case, the pro gram run ning on the microcontroller makes the cir cuit suitable for theparticular motor type.

16.5.1 Ex am ple 16F84 Trans la tor Mod ulesFor many step per mo tor con trol ap pli ca tions, the mi cro pro ces sor pro vides state codefor each of four mo tor coil lines. When a mo tor con trol ler IC is pres ent in the cir cuit,the mi cro pro ces sor pro vides a step pulse and one or more mo tor con trols, such as for -ward or re verse di rec tion, mode se lec tion, or en able and dis able con trols. A use ful cir -cuit can be de signed around the 16F84 PIC and sev eral switches, such as the one inFig ure 16-10.

Fig ure 16-10 Pushbutton and Tog gle-switch Con trol and Trans la tor Mod ule.

Step per Mo tor Cir cuit Com po nents 401

+5v

R=

10

K

R=

10K

R=

10

K x 4

R=

10

K

R=

10

K

R=

10

K

RESET

CIRCUIT: IO-PIC16F84-1

16

F8

4A

+5V+5v

RA2

RA3

RA4/TOCKI

MCLR

Vss

RB0/INT

RB1

RB2

RB3

1

2

3

4

5

6

7

8

9

18

17

16

15

14

13

12

11

10

RA1

RA0

OSC1

OSC2

Vdd

RB7

RB6

RB5

RB4

PB1

PB2

Fn1

Fn2

Fn3

Fn4

PB3

PB4

CONTROL AND TRANSLATOR STAGE

Osc

TOGGLESWITCHBANK

TG1

TG2

TG3

TG4

Page 423: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

In cir cuit IO-PIC16F84-1 (Fig ure 16-10), in put can come from any com bi na tion offour pushbutton switches, wired to port A lines RA0 to RA3, or from any of the fourtog gle switches in the bank wired to port B lines RB4 to RB7. Four out put lines areavail able to com mu ni cate with de vices or to pro vide con trols for the driver stage.These four lines are wired to port B, lines B0 to RB3. The cir cuit is in tended as agen eral-pur pose experimenter.

The cir cuit de signer can eas ily mod ify it to suit a spe cific pur pose by elim i nat ingun needed com po nents or re plac ing oth ers. In the cir cuit in Fig ure 16-11 we have re -placed the pushbutton switches with a sec ond bank of toggle switches.

Fig ure 16-11 Tog gle-Switch Based Con trol and Trans la tor Mod ule.

In most of the cir cuit sche mat ics for mo tor con trols pre sented in the fol low ingchap ters, we have sep a rated the con trol and trans la tor stage from the driver stage.How ever, we have ab stained from us ing ge neric stages that do not ex actly fit the cir -cuit at hand. The use of ge neric stages, such as the ones in Fig ure 16-10 and Fig ure16-11, would have re sulted in cir cuits that con tain un used com po nents and there -fore are in ef fi cient and con fus ing. The de vel oper wish ing to ex per i ment with mo torcon trols can build the ge neric con trol and trans la tor stage cir cuits in this pres entsec tion, or the ones con tained in other cir cuit sche mat ics, and use them to con trolthe com pat i ble driver stages. The num ber and type of out puts from a con trol andtrans la tor stage will clearly de fine if it is com pat i ble with a par tic u lar driver. Cir cuitdes ig na tions in the sche mat ics include both the control and translator stage, andthe driver stage.

402 Chap ter 16

16

F8

4A

Osc

+5v

+5V

R=

10

K x 5

R=

10

K x 4

RA2

RA3

RA4/TOCKI

MCLR

Vss

RB0/INT

RB1

RB2

RB3

1

2

3

4

5

6

7

8

9

18

17

16

15

14

13

12

11

10

RA1

RA0

OSC1

OSC2

Vdd

RB7

RB6

RB5

RB4

RESET

TOGGLESWITCHBANK A

TOGGLESWITCHBANK B

CIRCUIT: IO-PIC16F84-2

Fn1

TB2

TB4

TB3

Fn2

Fn3

Fn4 TA4

TA3

TA2

TA1

CONTROL AND TRANSLATOR STAGE

TB1

Page 424: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Chap ter 17

Uni po lar Mo tor Cir cuits and Pro grams

17.1 Step per Mo tor Con trol Cir cuits The cir cuits and pro grams pre sented in this chap ter re late to uni po lar mo tors. Chap -ter 18 is de voted to ba sic cir cuits and pro grams for driv ing bi po lar mo tors. The readershould keep in mind that uni po lar mo tors can be used with bi po lar cir cuits by ig nor ingthe cen ter taps, which can be left float ing. The same is not true of bi po lar mo tors,which re quire vari a tions in the cur rent po lar ity and, there fore, are not com pat i blewith uni po lar cir cuits.

In gen eral, bi po lar mo tors and cir cuits pro vide better per for mance and ef fi ciency than the uni po lar ones. On the other hand, uni po lar cir cuits are eas ier to de sign,code, and fab ri cate. For this rea son, if the re quire ments of the ap pli ca tion al low, auni po lar cir cuit may some times be pref er a ble, de spite its lower efficiency andperformance.

17.1.1 Step per Mo tor Cir cuit Sche matic Con ven tions

The nam ing convention that we have adopted for step per mo tor cir cuits al ways startswith the let ters SM, fol lowed by U for unipolar ap pli ca tions and B for bi po lar. The re -main der of the cir cuit des ig na tion in cludes the names of the one or more ICs in the cir -cuit. For ex am ple: SMU-5804-1 is a unipolar step per mo tor con trol ler that uses the5804 driver IC. The last digit is the cir cuit ver sion, not with stand ing that of ten there isonly one ver sion of the cir cuit. Each cir cuit is fur nished with one or more pro gramsthat ex er cise the cir cuit’s ba sic op er a tions. The names of the source files for the pro -grams also fol low these con ven tions. For ex am ple, the pro gram namedSMU_5804.asm is the source files for driv ing a unipolar step per mo tor cir cuit based on the 5804 IC. The code list ing and the cir cuit di a grams are cross-ref er enced.

In or der to keep the cir cuit di a grams as use ful as pos si ble we have some timesstruc tured or sim pli fied the sche mat ics. For ex am ple, in most cir cuits we have sep a -rated the sche mat ics into stages that are rel a tively in de pend ent. In these cases thecir cuit di a grams con tain dashed-line boxes that in di cate the in di vid ual stages. Fig -ure 17-1 shows a cir cuit that is separated into two stages.

403

Page 425: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 17-1 Ex am ple of Cir cuit Sche matic.

The cir cuit in Fig ure 17-1 is that of a bi po lar step per mo tor con trol ler de scribedin Chap ter 18. Each stage in a cir cuit di a gram is iden ti fied with a vari a tion of the cir -cuit name. In the case of the cir cuit in Fig ure 17-1, the trans la tor and con trol stage is la beled, at the bot tom of the il lus tra tion, SMB-L297-298-1 and the driver stage is la -beled SMB-L297-298-2. The sep a ra tion of a cir cuit into stages is com ple mented byus ing di rected flags that ref er ence the cor re spond ing el e ment in each stage. Theflags are la beled FnX, where X is a se quen tial digit in di cat ing a par tic u lar func tion.For ex am ple, in the di a gram of Fig ure 17-1, the flag la beled Fn1 in the trans la tor and con trol stage is shown to ac cess the L297 ENABLE func tion in the driver stage. Also

404 Chap ter 17

+5V

MotorSupply

L2

93

D

TO

MO

TO

R

ENABLE 1

INPUT 1

OUTPUT 1

GND

GND

OUTPUT 2

INPUT 2

Vm

1

2

3

4

5

6

7

8

16

15

14

13

12

11

10

9

Vs

INPUT 4

OUTPUT 4

GND

GND

OUTPUT 3

INPUT 3

ENABLE 2

+5V

R=4.7K x 2

CIRCUIT: SMB-L293D-1CODE: SMB_L293D.asm

RB0

RB1

RB2

RB3Q1

Q4

Q2

Q3

Osc

+5V

R=

10

K

R=

10

K

R=

10

K

R=

10

K

R=

10

KRESET

16

F8

4A

+5V

RA2

RA3

RA4/TOCKI

MCLR

Vss

RB0/INT

RB1

RB2

RB3

1

2

3

4

5

6

7

8

9

18

17

16

15

14

13

12

11

10

RA1

RA0

OSC1

OSC2

Vdd

RB7

RB6

RB5

RB4

PB0

PB1

Fn1

Fn2

Fn3

Fn4

PB2

PB3

CONTROL AND TRANSLATOR STAGE

Page 426: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

note that not all out puts from the sche mat ics of the trans la tor and con trol stage areused in the driver stage of a particular circuit.

17.2 Mo tor Speed Con trolStep per mo tor speed is de ter mined by two fac tors: the code se quence sent to the mo -tor coils and the pulse rate. These two fac tors are re lated: At the same pulse rate astep per mo tor in wave drive mode runs twice as fast as one in the half step mode. Later in this book we dis cuss microstepping tech niques that re duce the mo tor speed evenfur ther for the same pulse rate.

In any case, within a spe cific drive mode (wave, full, half, or microstep), the mo -tor speed is de ter mined by the rate at which the pulses are sent to the mo tor coils.When a microcontroller is used in the driver stage, as is the case with the cir cuitsand pro grams in this book, then soft ware will de ter mine the pulse rate. In code theac tual pulse rate can be ob tained us ing sim ple de lay coun ters or by In ter rupt-Driven rou tines. Timer-re lated is sues were dis cussed in Chap ter 11. At pres ent we are con -cerned with hard ware de vices that fur nish a way of in put ting mo tor speedinformation into the circuit.

The first is sue in im ple ment ing a mo tor speed con trol mech a nism is the de vice or de vices that pro vides speed se lec tion in for ma tion to the cir cuit. In other words, the cir cuit typ i cally in cludes in put de vices that al low se lect ing the mo tor speed. Thesede vices are ei ther dig i tal or an a log in na ture. A tog gle switch used to se lect be tween a low and a high mo tor speed can be con sid ered a dig i tal in put de vice be cause theswitch can be wired so that it re ports ei ther a high or low state. A po ten ti om e terthat al lows con trol ling mo tor speed within a cer tain range can be con sid ered an an -a log in put de vice be cause the vary ing re sis tance read from the po ten ti om e ter mustbe con verted to a dig i tal value; this value is then used by the microcontroller toselect a motor pulse rate.

17.2.1 Speed Con trol from Dig i tal In putThe sim plest (but not al ways the most con ve nient) mech a nism for con trol ling mo torspeed is an in put de vice that di rectly pro vides dig i tal data or can be eas ily con vertedto dig i tal form. In the sam ple cir cuit SMU-PIC16F84-1 (Fig ure 17-3), slow and fast mo -tor rates are de ter mined by the state pushbutton switches. The switches are wired sothat the pushbuttons re ports a high or low value to a microcontroller port. Be causethe state of the switch can be in ter preted as a bi nary zero or one, the in for ma tion pro -vided by the pushbutton can be con sid ered dig i tal in put. In this same con text, sam plecir cuit SMU-5804-1 (Fig ure 17-4) uses a bank of four tog gle switches to pro vide datathat al lows se lect ing six teen dif fer ent mo tor speeds. The pro gram reads the state ofthe four switches and the bi nary value is then used to se lect the cor re spond ing de layin any one of six teen pos si ble rates.

The use of a bank of switches to se lect mo tor speed has its ad van tages and itsdraw backs. With this scheme the num ber of in di vid ual switches in the bank de ter -mines the num ber of pos si ble speeds. One tog gle switch al lows se lect ing twospeeds, two switches four speeds, three switches eight speeds, and so on. One pos -si ble ad van tage of tog gle-switch-based con trols is that the mo tor speed is se lected

Uni po lar Mo tor Cir cuits and Pro grams 405

Page 427: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

on the board and can not be changed ac ci den tally. It is a suit able op tion for cir cuitsin which the mo tor speed is not changed of ten and can be scaled in dis crete steps.By the same to ken, the tog gle switch bank ap proach is not suit able when the mo torspeed must be eas ily changed or must have a con tin u ous range. An other draw backof switch con trols is that each switch re quires us ing a microcontroller port. Sam plecir cuits SMU-PIC16F84-1 and SMU-5804-1 use dig i tal in puts to con trol mo tor speed.In one case (SMU-PIC16F84-1), pushbutton switches se lect slow or fast mo torspeeds, in the other case (SMU-5804-1), a bat tery of four tog gle switches (see Fig ure 14-4) is used to select one of six teen possible motor speeds.

17.2.2 An a log In put Speed Con trol

An an a log in put de vice pro vides an al ter na tive way of con trol ling mo tor speed. Thepo ten ti om e ter (also called a pot) per forms as a vari able re sis tor and acts as a volt agedi vider. An other an a log de vice for vary ing cir cuit re sis tance is the rheo stat. The rheo -stat is a two-ter mi nal vari able re sis tor that al lows han dling much larger cur rents thana po ten ti om e ter.

Po ten ti om eters are of ten used to ad just an an a log sig nal that is then fed into ahigher-watt age de vice (such as a TRIAC) or con verted to a dig i tal scale. This sec ond op tion is the one most of ten found in microcontroller-driven step per mo tor cir cuits,which also ex plains why rheo stats are not com monly found in these cir cuits. Thetyp i cal cir cuit reads the re sis tance of fered by the cur rent set ting of the po ten ti om e -ter, con verts it to a dig i tal value, and uses this value to de ter mine the pulse rate sent to the mo tor coils. The one new el e ment in a pot-based cir cuit is the con ver sion ofthe an a log value read from the po ten ti om e ter into a scale of dig i tal values that canbe used by the microcontroller.

In this ap pli ca tion the cir cuit de signer can se lect one of two op tions: use an an a -log-to-dig i tal con ver sion de vice, such as the ADC0831, or se lect a microcontrollerthat con tains an an a log-to-dig i tal con verter. These in ter nal an a log-to-dig i tal de vices are re ferred to in the l it er a ture as an A/D or ADC mod ule . Se lect ing amicrocontroller with an ADC mod ule is of ten more eco nom i cal and eas ier to im ple -ment than using a separate analog-to-digital IC.

Many PIC microcontrollers con tain an ADC mod ule. The most suit able one ineach case de pends on the cir cuit re quire ments. Un for tu nately, the pop u lar 16F84,used in many cir cuits in this book, does not con tain an ADC mod ule. On the otherhand, the 16F87x fam ily, which in cludes the forty-pin 16F877 used in many of thisbook’s cir cuits, con tains an ADC mod ule. An in ter est ing op tion for com pact step permo tor cir cuits is the PIC16F684, which also in cludes an ADC com po nent. The16F686 is a small, in ex pen sive de vice with the same in struc tion set as the 16F84 and very sim i lar ar chi tec ture and mem ory struc ture. The chip pro vides twelve I/O ports: six mapped to port A and six to Port C. An in ter nal os cil la tor is pro gram ma ble from31 KHz to 8 MHz, the de fault be ing 4 MHz. This saves hav ing to use an ex ter nal tim -ing de vice. The 16F684 has two timer mod ules and a com para tor. The ADC con -verter has a res o lu tion of ten bi nary digits. The circuit diagram of the 16F684 isshown in Figure 17-2.

406 Chap ter 17

Page 428: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 17-2 Di a gram of the Four teen-Pin Ver sions of the PIC 16F684.

Later in this chap ter we de velop the cir cuit named SMU-PIC16F684-1, which con -t a i n s a 1 6 F 6 8 4 P I C. Tw o s a m p l e p ro g r a m s ( S M U _ PI C 1 6 F 6 8 4 .asm an dSMU_PIC16F684_INT.asm) use the PIC’s ADC to con vert the re sis tance value readfrom the po ten ti om e ter to dig i tal, which is then used to con trol motor speed.

17.3 Uni po lar Mo tor Con trol Cir cuitsUni po lar mo tor con trol cir cuits re quire fewer com po nents and are eas ier to de signand man u fac ture than their bi po lar coun ter parts. In the sim plest pos si ble im ple men -ta tion, a microcontroller (such as a PIC 16F84 or 16F684) can be used as a con trol ler,usu ally com bined with some sim ple de vices that aug ment the cur rent ca pac ity tomatch the needs of the mo tor. Other more com plex cir cuits use ded i cated trans la torsand driv ers to re lieve the microcontroller of some func tions or to pro vide ad di tionalfunctionalities.

17.3.1 Match ing Cir cuit to Mo tor PowerStep per mo tors come in many sizes and power ranges. Some times the mo tor’sdatasheet ex presses the mo tor’s power re quire ments as its max i mum cur rent rat ingper coil. When this value is known, it can be di rectly com pared to the rat ings of the cir -cuit com po nents. For ex am ple, a mo tor rated at 0.8 A can be safely used with a 5804mo tor driver IC that is rated at 1.25 A.

If the datasheet is not avail able or if the mo tor’s cur rent rat ing is not listed, thenwe can de ter mine the mo tor’s power re quire ments by mea sur ing the coil re sis tancewith an ohm me ter or a multimeter. In the case of a uni po lar mo tor, make sure thatthe mea sured value is be tween the ends of the coil and not from the coil cen ter taps. If in doubt use the larger resistance value.

For ex am ple, sup pose you have a 14V step per mo tor and that the mea sured re sis -tance of the wind ings is 5 Ohm. Ohm’s law al lows us to cal cu late:

In the case of a 5804 driver, this value con sid er ably ex ceeds the 1.25 A at which itis rated. Two pos si ble so lu tions are avail able when the mo tor cur rent ex ceeds the

Uni po lar Mo tor Cir cuits and Pro grams 407

16

F6

84

Vdd

RA5

RA4/AN3

RA3/MCLR

RC5

RC4

RC3/AN7

1

2

3

4

5

6

7

14

13

12

11

10

9

8

GND

RA0/AN0

RA1/AN1

RA2/AN2

RC0/AN4

RC1/AN5

RC2/AN6

AE

E

R

IE

8.2

5

14

=

=

=

Page 429: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

ca pac ity of the cir cuit com po nent: the first one is to se lect com po nents with ahigher power rat ing. The sec ond pos si ble so lu tion is to add re sis tance to the mo torcoils. In this case Ohm’s law can be used to de ter mine the to tal coil re sis tance nec -es sary to meet the lim its of the hard ware. In the previous example we can cal cu late

Be cause the mea sured coil re sis tance is 5 Ohm we would need ex ter nal re sis torsof 6 or 7 Ohms so that the to tal coil re sis tance would be ap prox i mately 11.2 Ohms.Also note that the watt age of the re sis tor must also be cal cu lated. In this case theex ter nal re sis tors should be rated for 17 W. Re sis tors of 20 W are commonlyavailable.

In the uni po lar cir cuits that fol low, we have in cluded a re sis tor la beled Rx con -nected to the cen ter tap of the mo tor coils. This re sis tor will only be nec es sary if the mo tor rat ing ex ceeds the cir cuit ca pac ity as de ter mined at its output.

17.3.2 16F84 Uni po lar Cir cuitThe first cir cuit is a sim ple uni po lar mo tor driver that uses the 16F84 PIC as a trans la -tor with a 4050 hex buffer IC and four TIP 120 NPN Dar ling ton tran sis tors as am pli fi -ers. Al though the TIP 120 con tains in ter nal snub ber di odes, ex ter nals ones arepro vided in the cir cuit as ad di tional pro tec tion. Fig ure 17-3 shows the cir cuit sche mat -ics.

The cir cuit SMU-PIC16F84-1/2 in Fig ure 17-3 re ceives in put from four pushbutton switches wired to the microcontroller port A lines 0 to 3. Port B lines 0 to 3 fur nishout puts to the four coils of the uni po lar mo tor via the 4050 hex buffer and the basepins of the TIP 120 tran sis tors. Out put from the four TIP 120 tran sis tors are wired to the re spec tive ends of the mo tor coils. The cen ter taps of the coils are con nected tothe mo tor power source. The re sis tors la beled Rx are only nec es sary if the mo torex ceeds the ca pac ity of the TIP 120 tran sis tors, which is 6 A. The cal cu la tion of theRx re sis tors was dis cussed ear lier in Sec tion 17.3.1.

Sam ple Pro gram SMU_PIC16F84.asm

The pro gram SMU_PIC16F84.asm, in this book’s soft ware pack age, is a driver that ex -er cises the cir cuit. The code as sumes a uni po lar mo tor in one-half step mode and usesa lookup ta ble for the cor re spond ing coil se quence codes. When held down, thepushbuttons wired to ports A3 and A2 ac ti vate slow ro ta tion in the for ward and re -verse di rec tion. Pushbuttons wired to ports A0 and A1 ac ti vate fast for ward and re -verse ro ta tion. The pointer to the lookup ta ble is ei ther in cre mented or dec re ment edac cord ing to the se lected di rec tion. This en sures that changes in the di rec tion of ro ta -tion are ex e cuted smoothly. Fast and slow ex e cu tion are de ter mined by the value of alo cal vari able read by the de lay rou tine.

408 Chap ter 17

Ω=

=

=

2.11

25.1

14

R

R

I

ER

Page 430: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 17-3 Uni po lar Mo tor Driver with the 16F84 PIC.

Uni po lar Mo tor Cir cuits and Pro grams 409

Osc

+5V

+3-15V

R=

10

K

R=

10

K

R=

10

K

R=

10

K

R=

10

K

RESET

TIP 120 x 4

Diodes50V 1A x 4

40

50

+Mv

Out 1

In 1

Out 2

In 2

Out 3

In 3

GND

1

2

3

4

5

6

7

8

16

15

14

13

12

11

10

9

NC

Out 6

In 6

NC

Out 5

In 5

Out 4

In 4

CIRCUIT: SMU-PIC16F84-2 CODE: SMU_PIC16F84.asm

16

F8

4A

+5V

RA2

RA3

RA4/TOCKI

MCLR

Vss

RB0/INT

RB1

RB2

RB3

1

2

3

4

5

6

7

8

9

18

17

16

15

14

13

12

11

10

RA1

RA0

OSC1

OSC2

Vdd

RB7

RB6

RB5

RB4

PB0

PB1

Fn1

Fn2

Fn3

Fn4

Fn1

Fn2

Fn3

Fn4

PB2

PB3

6-wiresteppermotor

CONTROL AND TRANSLATOR STAGE

DRIVER STAGE

Vm

Vm

Rx(see text)

Rx(see text)

Page 431: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

The code ta ble matches the re quire ment of the 42M048A19 uni po lar mo tor man u -fac tured by Airpak. The mo tor is rated for 5VDC at 9.1 Ohms per coil. The de greesper step is 7.5. The ta ble is coded as fol lows:

CodeTable:addwf PCL,f ; Add w to pro gram coun terretlw B’00001010’ ; cy cle = 0retlw B’00001000’ ; 1retlw B’00001001’ ; 2retlw B’00000001’ ; 3retlw B’00000101’ ; 4retlw B’00000100’ ; 5retlw B’00000110’ ; 6retlw B’00000010’ ; 7retlw B’00000000’ ; Ta ble ter mi na tor

Pro cess ing con sists of read ing the state of the four pushbutton switches wired to port A lines and set ting the val ues of the vari ables that con trol di rec tion and mo torspeed. The switches are debounced in soft ware to avoid spu ri ous val ues. The driverthen goes to a rou tine that ob tains the cor re spond ing ta ble code and writes it toport B lines 0 to 3. The pro ce dure named OneTick ob tains the cor re spond ing codefrom the ta ble in for ward or re verse ro ta tion and writes the code to port B. In for -ward di rec tion, the ta ble pointer is in cre mented and it is dec re ment ed in re verse ro -ta tion. The pro ce dure then calls a De lay pro ce dure that waits do ing noth ing. Thedu ra tion of the wait, thus the speed of the mo tor, is de ter mined by the value storedin a local variable. Code is as follows:

;==========================; for ward or re verse; sin gle cy cle pro ce dure;==========================OneTick:; Test for change of di rec tion

btfss di rec tion,0 ; Test for ward bitgoto For ward

; At this point di rec tion ro ta tion is re versegoto Re verse

; Foward di rec tion rou tineFor ward:

movf this_cy cle,w ; Get cur rent cy clecall CodeTable ; Get code from ta blemovwf PORTB ; Store code in portcall De lay

; Bump cy cle coun terincf this_cy cle,f ; Add one

; Test for cy cle num ber 7 (last one in se quence)btfsc this_cy cle,3 ; 1000 = 8goto Re cy cle ; Re set if at end of cy clere turn

Re cy cle:clrf this_cy clere turn

; Re verse di rec tion rou tineRe verse:

movf this_cy cle,w ; Get cur rent cy clecall CodeTable ; Get code from ta blemovwf PORTB ; Store code in portcall De lay

410 Chap ter 17

Page 432: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; Bump cy cle coun terdecf this_cy cle,f ; Sub tract one

; Test for cy cle num ber 0xff (over flow from cy cle # 0)btfsc this_cy cle,4 ; Bit 4 set in di cates over flowgoto Recycle2 ; Re set if at end of cy clere turn

Recycle2:movlw .7 ; First re verse cy clemovwf this_cy cle ; To cy cle coun terre turn

;================================; de lay sub-rou tine;================================De lay:

movf de lay,w ; Load de lay valuemovwf j ; j = w

Jloop:movwf k ; k = w

Kloop:decfsz k,f ; k = k-1, skip next if zerogoto Kloopdecfsz j,f ; j = j-1, skip next if zerogoto Jloopre turn

The com plete list ing for the SMU_PIC16F84 pro gram is found in this book’s soft -ware re source.

17.3.3 5804 Uni po lar Cir cuitEasy in ter fac ing with small-size step per mo tors can be achieved with cir cuits that em -ploy the 5804 IC. As men tioned in Chap ter 16, the 5804 al lows en abling out put, andcon trol ling di rec tion and half-step or full-step modes. A step in put line, which is typ i -cally driven by a clock IC or a microcontroller, can be pro grammed to set the mo torspeed. Sev eral speed con trol mech a nisms are ex am ined in the fol low ing sec tions. The 5804 pro vides ther mal pro tec tion so as to dis able the chip when the safe op er at ingtem per a ture is ex ceeded. In ter nal fly-back di odes are also part of the IC, al though ex -ter nal di odes are some times in cluded as a safe guard.

One lim i ta tion of ten men tioned in re la tion to cir cuits based on the 5804 is the IC’s lim i ta tion of 1.25A per phase. How ever, most teen-size step per mo tors of 5V andgreater fall within this range. For ex am ple, the Airpax 9123 step per mo tor, which issize NEMA 16, is rated at 5 V and 9.1 Ohms per coil. This re sults in a cur rent value of 0.55 A, well be low the 1.2 A rat ing of the cir cuit. Even some larger-than-teen step per mo tors are com pat i ble with the 5804 cir cuit. For ex am ple, a NEMA size 22 uni po larstep per mo tor (2.2 inches wide) rated at 12V, draws only 0.6 A per coil.

The cir cuit in Fig ure 17-4 can re ceive in put from two sets of tog gle switches. Oneset of three switches is wired to 16F84 port A lines 2 to 4. These three switches areused to de ter mine the 5804 mo tor con trols. An other set of four tog gle switches iswired to the 16F84 port B lines 4 to 7 and is used to de ter mine the mo tor speed. Twoport A lines (RA0 and RA1) are un used in the cir cuit. The de vel oper can use theselines for ad di tional controls.

Uni po lar Mo tor Cir cuits and Pro grams 411

Page 433: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 17-4 5804-Based Uni po lar Mo tor Driver Cir cuit.

In cir cuit SMU-5804-1/2 (Fig ure 17-4), there are four con trol lines from the 16F84to the 5804. The line la beled Step In pro vides the strobe pulse to the 5804. The linela beled Dir fur nishes di rec tion con trol, while the lines la beled Half Step and OnePhase al low se lect ing four drive se quences, as follows:

412 Chap ter 17

16

F8

4A

Osc

+5V

+5V

+5V

R=

10

K x

4

RA2

RA3

RA4/TOCKI

MCLR

Vss

RB0/INT

RB1

RB2

RB3

1

2

3

4

5

6

7

8

9

18

17

16

15

14

13

12

11

10

RA1

RA0

OSC1

OSC2

Vdd

RB7

RB6

RB5

RB4

RESET

58

04

Out B

K bd

Out D

Vss

Vss

Out C

K ac

Out A

1

2

3

4

5

6

7

8

16

15

14

13

12

11

10

9

Vdd

Enable

Dir

Vss

Vss

Step In

Half Step

One Phase

TOGGLESWITCHBANK B

TOGGLESWITCHBANK A

CIRCUIT: SMU-5804-1 CODE: SMU_5804.asm

Fn1

TB3

TB1

TB2

Fn2

Fn3

Fn4

Fn1

Fn4

Fn2

Fn3

1

2

3

4

5

6

7

8

Vm

+ -

Diodes50V 1A x 4

6-wiresteppermotor

CONTROL AND TRANSLATOR STAGE

DRIVER STAGE

Vm

Vm

Rx(see text)

Rx(see text)

R=

10

K x

5

TA1

TA2

TA3

TA4

Page 434: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Half Step One Phase Drive mode 0 0 = two phase 0 1 = wave drive 1 0 = half step 1 1 = step in hibit

Note that the di odes in the cir cuit can be omit ted and that the re sis tors la beledRx are nec es sary only if the mo tor ex ceeds the 1.2 A.

Sam ple Pro gram SMU_5804.asm

The pro gram SMU_5804.asm, in this book’s soft ware pack age, is a driver that ex er -cises the SMU-5804-1 cir cuit (Fig ure 17-4). The code reads the three tog gle switcheswired to port A lines 2, 3, and 4 and se lects the speed, di rec tion, and drive mode, as fol -lows:

; PORTA line SW ACTION; 4 1 Fast/slow de lay rate; de lay = 100 / de lay = 50 ; 3 2 For ward/Re verse; Set PORTB to: xxxx xxx0; or: xxxx xxx1; 2 3 Half step / sin gle step; Set PORTB to: xxxx x10x; or: xxxx x01x

The cir cuit con tains pushbuttons wired to ports A0 and A1, which are not used by the sam ple pro gram.

The pro gram first reads port B lines 4 to 7, trissed for in put and wired to the fourtog gle switch bank. The value in the range 0 to 15 read from the four tog gle switches is used to ob tain a de lay code from a lo cal lookup ta ble to de ter mine slow or fastspeed. Code is as follows:

;============================; Read speed con trol tog gles;============================; Read four speed con trol tog gle switches on port; B lines 4 to 7. The swapf in struc tion al lows swap ping; nib bles as they are read from the port

swapf PORTB,w ; Read port B and swap nib blesandlw B’00001111’ ; Mask out 4 high bits

call SpeedTable ; Use value in w to ob tain de laymovwf de lay ; Store code in lo cal vari able

The de lay code ta ble is coded as fol lows:;=============================; De lay ta ble for speed; con trol;=============================; Val ues in ta ble range from 255 to 30 (15 units apart); Ta ble has 16 en tries cor re spond ing to the val ues; rep re sented by the set ting of the 4 speed con trol; tog gle switchesSpeedTable:

addwf PCL,f ; Add w to pro gram coun terretlw .255 ; Slow est speed 0000 = 0retlw .240 ; 0001 = 1retlw .225 ; 0010 = 2

Uni po lar Mo tor Cir cuits and Pro grams 413

Page 435: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

retlw .210 ; 0011 = 3retlw .195 ; 0100 = 4retlw .180 ; 0101 = 5retlw .165 ; 0110 = 6retlw .150 ; 0111 = 7retlw .135 ; 1000 = 8retlw .120 ; 1001 = 9retlw .105 ; 1010 = 10retlw .90 ; 1011 = 11retlw .75 ; 1100 = 12retlw .60 ; 1101 = 13 retlw .45 ; 1110 = 14retlw .30 ; Fast est speed 1111 = 15retlw .0 ; Ter mi na tor

The de vel oper can edit the ta ble to suit the par tic u lar re quire ments of a mo tor orcir cuit.

Af ter the de lay rate has been set, code reads the three port A lines wired that willde ter mine the set tings of the 5804 di rec tion, one-half step, and one phase con trols.Code is as fol lows:

;============================; Read 5804 con trol lines;============================; PORTA bit 4 (wired to tog gle # 1) con trols for ward; or re verse di rec tion by means of PORTB bit 1 (wired; to 5804 di rec tion line on pin 14).

btfsc PORTA,4 ; Di rec tion con trol switchgoto ReverseRot ; En gage re verse ro ta tion

; At this point ro ta tion is for wardbcf PORTB,1 ; Clear bit `goto HalfStepMode

ReverseRot:bsf PORTB,1 ; Set re verse

HalfStepMode:; PORTA bit 3 (wired to tog gle # 2) se lects half-step; mode by means of PORTB bit 2 (wired to 5804 half-step; line on pin 10).

btfsc PORTA,3 ; Half-step mode con trolgoto NoHalfStep ; Dis able half step

; At this point half step is se lectedbsf PORTB,2 ; Set bit `goto OnePhaseMode

NoHalfStep:bcf PORTB,2 ; Turn off half-step con trol

OnePhaseMode:; PORTA bit 2 (wired to tog gle # 3) se lects one phase; mode by means of PORTB bit 3 (wired to 5804 sin gle; phase line on pin 9).

btfsc PORTA,2 ; One phase mode con trolgoto NoOnePhase ; Dis able sin gle step

; At this point sin gle phase is se lectedbsf PORTB,3 ; Set sin gle phase `goto PulseAndDelay

NoOnePhase:bcf PORTB,3 ; Turn off one phasegoto PulseAndDelay

414 Chap ter 17

Page 436: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Note that the code for read ing pushbutton switches (in the sam ple pro gramSMU_16F84.asm) in cludes debouncing. How ever, we have found that debouncingswitch ac tion can usu ally be omit ted when read ing tog gle switches in mo tor-driv ingcir cuits. For this rea son switch debouncing op er a tions are not used in the pro gramSMU_5804.asm.

Gen er at ing the Mo tor Pulses

Note the dif fer ence be tween the sam ple pro gram SMU_16F84 and SMU_5804 re gard -ing the gen er a tion of the mo tor-driv ing pulses. The first pro gram (SMU_16F84) readsthe drive se quence codes from a lo cal ta ble and writes these codes to the port B linesthat are wired to the mo tor coils. In this case the speed of the mo tor is de ter mined bythe rate at which these coil codes are up dated, which, in turn, de pends on the de layrou tine. On the other hand, the sam ple pro gram SMU_5804 re lies on the 5804 IC to pro -duce the cor re spond ing codes. The ac tual se quence gen er ated by the 5804 de pends on whether the half-step or sin gle-step mode has been pre vi ously se lected. This meansthat on the 5804 cir cuit and pro gram, the mo tor coils are driven by the 5804 IC and notby the microcontroller. The de vel oper should not as sume that the code se quence gen -er ated by the con trol ler IC is al ways the same one ex pected by the mo tor. The mo tor’sdatasheet usu ally lists the coil driv ing se quence for each sup ported mode. This se -quence should match the one gen er ated by the con trol ler chip. If this is not the case,then the mo tor coil taps must be relabeled so that they are in ac cor dance with the se -quence gen er ated by the 5804.

When the mo tor is driven by a ded i cated con trol ler, such as the 5804, amicrocontroller is typ i cally re quired to pro duce the pulses or strobes that are im -pressed on the con trol ler’s step line. In cir cuits with out a microcontroller (not cov -ered in this book), a clock or timer IC can be used to gen er ate the strobe pulses. Inthe cir cuit SMU-5804-1, the microcontroller’s port B line 1 is wired to the 5804 linelabeled Step In.

The pulses sent to a spe cific con trol ler can be pos i tive-go ing or neg a tive-go ing. In the pos i tive-go ing pulse, the line is held low and then strobed high. In a neg a -tive-go ing pulse, the line is held high and strobed low. In ei ther case there is a min i -mum time dur ing which the line state (high or low) must be main tained. Ide ally thede vice datasheet will pro vide suf fi cient in for ma tion re gard ing its pulse re quire -ments, but this is not al ways the case. For in stance, the 5804 datasheet does not ex -plic itly state that the pulse must be pos i tive-go ing, al though it is in di rectlysug gested by the state ment in the datasheet that that states that the step in put linemust be low when chang ing state or di rec tion. In ad di tion, there is no spe cific in for -ma tion in the 5804 datasheet re gard ing the du ra tion of the high strobe. The sam plepro gram SMU_5804 con tains a sub-rou tine to pulse the 5804 Step In line. We havecoded ten no-op er a tion codes (nop) to pro duce a de lay of as many ma chine cy cles.Code is as fol lows:

;================================; rou tine to pulse the 5804;================================Pulse:

bsf PORTB,1 ; Bring step line highnop

Uni po lar Mo tor Cir cuits and Pro grams 415

Page 437: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

nopnopnopnopnopnopnopnopnopbcf PORTB,1 ; Step line lowre turn

Clearly the de lay could have been ac com plished more com pactly with a timed orcoun ter-based loop. Note that al though this rou tine works well with the 5804, it isnot ad e quate for a de vice that re quires a neg a tive-go ing pulse or dif fer ent tim ing.Later in this chap ter we will find that the L298 driver re quires a neg a tive-go ing pulse that must be held low for one ma chine cy cle. A dif fer ent pulse rou tine is de vel opedfor L298 circuits.

Interrupt-Driven Mo tor Puls ing

The tim ing of mo tor pulses us ing a de lay rou tine is sim ple to code and in some casesserves its pur pose. How ever, there are more ac cu rate and ef fi cient ways of gen er at inga timed pulse even with the sim plest microcontrollers. Tim ing cir cuits and code werecov ered in Chap ter 11 so we dis cuss only the im ple men ta tion of in ter rupt-based tim -ers in the con text of mo tor con trols. The meth ods de scribed in this sec tion can be im -ple mented in any PIC microcontroller cov ered in the book, al though some times mi nor mod i fi ca tions to the code will be re quired to ac com mo date the var i ous hard ware.

In ter rupt-Driven tim ers have sev eral ad van tages over polled rou tines: One is thatthe tim ing op er a tion is in de pend ent of ap pli ca tion code. Be cause the tim ing takesplace as a back ground op er a tion, changes in the ap pli ca tion it self do not af fect theac cu racy of the timer. An other ad van tage is that the ap pli ca tion can con tinue to doother work in the fore ground with out con cern for the accuracy of the timingroutine.

The Timer0 mod ule, which is avail able in all mid-range PICs, is par tic u larly suited for im ple ment ing an In ter rupt-Driven mo tor puls ing rou tine. In this ap pli ca tionTimer0 has the fol low ing useful features:

• The timer register is read able and writeable by soft ware

• Can be driven by an in ter nal or ex ter nal clock

• Edge of tim ing pulse can be se lected on the high-to-low or low-to-high tran si tion

• 8-bit prescaler is avail able

• Can be In ter rupt driven

In a sim plest im ple men ta tion, the pro gram sets up the Timer0 in ter rupt to takeplace on reg is ter over flow, se lects a suit able prescaler, and chooses the in ter nalclock source. The sam ple pro gram SMU_5804_INT.asm, in this book’s soft warepack age, pro ceeds as follows:

; Clear the Watchdog timer and re set prescaler

416 Chap ter 17

Page 438: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

clrf TMR0clrwdt

; Set up the OPTION reg is termovlw b’11010000’

; 7 6 5 4 3 2 1 0 <= OPTION bits; | | | | | |__|__|_____ PS2-PS0 (prescaler bits); | | | | | Val ues for Timer0; | | | | | *000 = 1:2 001 = 1:4; | | | | | 010 = 1:8 011 = 1:16; | | | | | 100 = 1:32 101 = 1:64; | | | | | 110 = 1:128 111 = 1:256; | | | | |______________ PSA (prescaler as sign); | | | | 1 = to WDT; | | | | *0 = to Timer0; | | | |_________________ TOSE (Timer0 edge se lect); | | | 0 = in cre ment on low-to-high; | | | *1 = in cre ment on high-to-low; | | |____________________ TOCS (TMR0 clock source); | | *0 = in ter nal clock; | | 1 = RA4/TOCKI bit source; | |_______________________ INTEDG (Edge se lect); | *0 = fall ing edge; |__________________________ RBPU (Pullup en able); 0 = en abled; *1 = disabled; Note that OPTION reg is ter is in bank 1 and its reg is ter; name is OPTION_REG

bsf STATUS,RP0 ; RP0 is bank se lect bitmovwf OPTION_REG ; Copy w to OPTIONbcf STATUS,RP0 ; Bank 0

;============================; setup in ter rupts;============================; Clear ex ter nal in ter rupt flag (INTF = bit 1)

bcf INTCON,INTF ; Clear flag; En able global in ter rupts (GIE = bit 7); En able RB0 in ter rupt (inte = bit 4)

bsf INTCON,GIE ; En able global int (bit 7)bsf INTCON,T0IE ; En able TMR0 over flow in ter rupt

Once the Timer0 in ter rupt is set up and in i tial ized, the in ter rupt ser vice rou tinere ceives con trol ev ery time the timer reg is ter over flows. The ser vice rou tine usessim i lar pro cess ing for puls ing the mo tor as the in-line de lay rou tines cov ered pre vi -ously. One change is that two coun ters are now re quired: one that is set from the in -put pro vided by switches or a po ten ti om e ter, and a sec ond, run ning coun ter that isdec re ment ed dur ing each it er a tion of the ser vice rou tine. In the sam ple pro gramSMU_5804_INT.asm, the ISR is coded as follows:

;=======================================================; In ter rupt Ser vice Rou tine;=======================================================; Ser vice rou tine re ceives con trol when timer reg is ter; TMR0 over flows, that is, when 256 timer beats have ; elapsedIntServ:; First test if source is a Timer0 in ter rupt

btfss INTCON,T0IF ; T0IF is Timer0 in ter ruptgoto notTOIF ; Go if not RB0 or i gin

; If so clear the timer in ter rupt flag so that count con tin ues

Uni po lar Mo tor Cir cuits and Pro grams 417

Page 439: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

bcf INTCON,T0IF ; Clear in ter rupt flag; Save con text

movwf old_w ; Save w reg is terswapf STATUS,w ; STATUS to wmovwf old_STATUS ; Save STATUS

;=========================; in ter rupt ac tion;=========================; Decrement the it er a tion coun ter. Exit if not zero

decfsz it er a tion,fgoto exitISR ; Con tinue if coun ter not zero

; At this point the de lay count has ex pired so the pro grammed; time has elapsed.; First re set the it er a tion coun ter

movf de lay,w ; Read de laymovwf it er a tion ; Re set it er a tion coun ter

;================================; Pulse mo tor and de lay;================================; Make sure 5804 Step In line is low be fore strobe; cy cle

bcf PORTB,0 ; Set low call Pulse ; Lo cal pulse mo tor rou tine

;=========================; exit ISR;=========================exitISR:; Re store con text

swapf old_STATUS,w ; Saved STATUS to wmovfw STATUS ; To STATUS reg is terswapf old_w,f ; Swap file reg is ter in it selfswapf old_w,w ; re-swap back to w

; Re set,in ter ruptnotTOIF:

retfie;================================; rou tine to pulse the 5804;================================; Note that 5804 re quires a pos i tive-go ing pulse; there fore the line is held high dur ing the strobe; cy clePulse:

bsf PORTB,0 ; Bring step line highnopnopnopnopnopnopnopnopnopnopbcf PORTB,0 ; Step line lowre turn

418 Chap ter 17

Page 440: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

In the In ter rupt-Driven sam ple pro gram named SMU_5804_INT.asm, mo tor speed is de ter mined by the de lay value read from the lookup ta ble and by the value se -lected for the prescaler. Note that the prescaled de lay can be elim i nated by as sign -ing the prescaler to the Watch dog timer. When the prescaler is as signed to Timer0,the low est re duc tion is in the rate 1:2. How ever, when the prescaler is as signed tothe Watch dog timer no de lay of the Timer0 in ter rupt takes place. In the case of thesam ple pro gram, we could elim i nate the prescaled de lay by set ting bit 3 of theOPTION reg is ter. This would in fact gen er ate the in ter rupt at dou ble the speed.

17.3.4 16F686 PIC Cir cuit

By read ing the state of each switch in a bank of four tog gle switche,s we can ob tain six -teen dis crete val ues that can be used to set the mo tor speed in as many steps (cir cuitSMU-5804-1, Fig ure 17-4). How ever, it is some times nec es sary to devise a cir cuit thatal lows con trol ling mo tor speed with more pre ci sion or more con ve niently than is pro -vided by the dis crete steps of one or more dig i tal in put de vices, for ex am ple, when thecir cuit has to pro vide a finer de gree of mo tor speed con trol or a more user-friendly de -vice than tog gle switches.

Speed con trol po ten ti om eters are of ten suit able for this pur pose. If the mo torspeed con trol is to be avail able dur ing nor mal use, then a con ven tional knob-op er -ated po ten ti om e ter can be se lected. If the mo tor speed is to be set dur ing in stal la -tion or ini tial iza tion, then a trim mer pot on the board may be more suit able. Inei ther case, the an a log re sis tance read ing pro vided by the po ten ti om e ter or trim mer must be con verted to dig i tal so that it can be ma nip u lated by code. The PIC 16F684IC con tains an ADC mod ule that can be used for this pur pose. Fig ure 17-5 is a cir -cuit with po ten ti om e ter speed con trol and a 16F684 PIC.

One ad van tage of po ten ti om e ter or trim mer con trol over tog gle switches is thatthe pot or trim mer re quires a sin gle in put line. On the other hand, a cir cuit that con -tains a po ten ti om e ter must in clude a microcontroller with ADC or a sep a rate an a -log-to-dig i tal conversion IC.

17.3.5 16F686 Pro gram ming

Transitioning from the 16F84 PIC to the 16F684 is straight for ward but not with outsome com pli ca tions. Al though both PICs be long to the same mid-range fam ily and usethe same in struc tion set, there are ar chi tec tural dif fer ences. In the first place, the16F684 is a four teen-pin de vice in PDIP, SOIC, and TSSOP con fig u ra tions, while the16F84 has eigh teen pins. This means that the lat ter PIC can not be re placed with thefor mer one with out mak ing cir cuit changes. The fol low ing are the most no ta ble dif fer -ences be tween these PICs:

• The 16F684 has twelve I/O ports, six as signed to port C and six to port A. The 16F84has thir teen ports: five as signed to port A and eight to port B. There is no port B inthe 16F684.

Uni po lar Mo tor Cir cuits and Pro grams 419

Page 441: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 17-5 Uni po lar Mo tor Driver Cir cuit with 16F684 PIC.

• The gen eral-pur pose reg is ters (GPR) are mapped to ad dresses 0x0c to 0x4f in the16F84 (68 reg is ters). In the 16F684 there are ninety-six GPRs mapped to ad dresses0x20 to 0x7f and thirty-two ad di tional reg is ters mapped to 0xa0 to 0xbf in bank 1.

420 Chap ter 17

+5V

+5V

R=

10

K x 5

RESET

58

04

Out B

K bd

Out D

Vss

Vss

Out C

K ac

Out A

1

2

3

4

5

6

7

8

16

15

14

13

12

11

10

9

Vdd

Enable

Dir

Vss

Vss

Step In

Half Step

One Phase

TOGGLESWITCHES

x 4

CIRCUIT: SMU-PIC16F684-1 CODE: SMU_PIC16F684.asm SMU_PIC16F684_INT.asm SMU_POSITION.asm

TS4

TS2

TS1

1

2

3

4

5

6

7

8

Vm

+ -

Diodes50V 1A x 4

6-wiresteppermotor

CONTROL AND TRANSLATOR STAGE

DRIVER STAGE

Vm

Vm

Rx(see text)

Rx(see text)

16

F6

84

+5V Vdd

RA5

RA4/AN3

RA3/MCLR

RC5

RC4

RC3/AN7

1

2

3

4

5

6

7

14

13

12

11

10

9

8

GND

RA0/AN0

RA1/AN1

RA2/AN2

RC0/AN4

RC1/AN5

RC2/AN6

+5V

Po

t 5K

POT

Fn1

Fn2

Fn3

Fn2

Fn4

Fn1

Fn3

Fn4

TS3

Page 442: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

• The 16F84 re quires an ex ter nal clock source or oscillator while the 16F684 has anin ter nal pre ci sion oscillator. The fre quency of the in ter nal oscillator in the 16F684can be se lected by soft ware be tween 8 MHz and 125 KHz. There is also a 31-KHz in -ter nal oscillator.

• The 16F84 re quires that the mas ter clear line (mapped to pin 5 and la beled MCLR)be held high for IC op er a tion. In the 16F684 the mas ter clear pin (mapped to pin 4) ismul ti plexed with port A line 3. Dur ing ini tial iza tion of the 684, soft ware can se lectbe tween the mas ter clear and the gen eral-pur pose I/O func tion for this line.

• The 16F684 in cludes sev eral pe riph er als that are not avail able in the 16F84. Thesein clude an An a log Com para tor, and A/D Con verter, and an En hanced Cap ture, Com -pare, and PWM mod ule. Other de vices, such as the timer, have ad di tional fea turesand functionalities in the 16F684.

In ad di tion to the fea tures com pared in the pre ced ing list, the 16F684 datasheetclaims many other re fine ments and ad van tages over the 16F84. In the con text ofstep per mo tor soft ware the A/D converter and the PWM module in the 16F684 arepar tic u larly use ful. Port ing code from the 16F84 to the 16F684 con sists mostly oftak ing into ac count the dif fer ences be tween the two ICs. In ad di tion, code that usespar tic u lar fea tures of the 16F684 must ini tial ize and operate these functions.

Sam ple Pro gram SMU_PIC16F684.asm

This sam ple pro gram is de signed for the SMU-PIC16F684-1 cir cuit. The pro gramdrives a uni po lar step per mo tor in half-step mode. The 16F684 PIC con trols aUCN5804 driver, which fur nishes the mo tor con trol. Three tog gle switches on the cir -cuit are wired to ports RA1 to RA3. These are used to turn on and off the di rec tion, half- step and sin gle-phase modes on the 5804. A 5K po ten ti om e ter on port RA0 pro vides in -put to the chip’s ADC. The re sult ing re sis tance value is used to se lect the de lay rate,which, in turn, sets the mo tor speed in a de lay rou tine.

Pro gram vari ables are de fined start ing at ad dress 0x20, as fol lows:

; De clare vari ables at 2 mem ory lo ca tionsj equ 0x20k equ 0x21de lay equ 0x22 ; De lay count

In the sam ple pro gram we use the banksel di rec tive to se lect be tween the twomem ory banks. Al ter na tively we could have used bank se lec tion mac ros or ma nip u -lated the RP0 bit di rectly in code, as dis cussed ear lier in the book.

Ini tial iza tion starts by “trissing“ the ports as re quired by the hard ware de vices. Inthis case, port C is set to out put and port A to in put. Port A line 0 is se lected for an a -log in put be cause this line is con nected to the po ten ti om e ter in the cir cuit. Code isas follows:

Main:; Ini tial ize all line in port C for out put

banksel PORTCclrf PORTCbanksel TRISC ; Pre pare to trisclrf TRISC ; All lines to 0 (out put)

Uni po lar Mo tor Cir cuits and Pro grams 421

Page 443: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; Set PORT A line 0 as an a log

movlw B’00000001’ ; Line 0 is an a log

banksel ANSEL

movwf ANSEL ; Se lect as an a log

; Turn off com para tor

movlw B’00000111’ ; Set ting bits 0, 1, and 2

; sets com para tors off and

; Port C IN pins to dig i tal

banksel CMCON0

movwf CMCON0

; Tris port A for in put

banksel TRISA

movlw B’00111111’ ; All port A lines for in put

clrf TRISA

movwf TRISA

The sec ond ini tial iza tion step con sists of con fig ur ing the os cil la tor. In this casewe have set the os cil la tor to 4 MHz and set the con ver sion clock use by the an a -log-to-dig i tal con verter to the value rec om mended in the 16F684 datasheet. Code isas follows:

; Con fig ure os cil la tor

movlw B’01100001’

; ||| |____ in ter nal clock

; |||________ 4 MHz

banksel OSCCON

movwf OSCCON

; Set con ver sion clock to Tad = 8 * Tosc (ADCS = 001)

movlw B’00010000’

; |||__________ ADCS bits

banksel ADCON1

movwf ADCON1

Fi nally, the A/D con verter mod ule is in i tial ized and turned on, as fol lows:

; Se lect an a log line (AN0) as the an a log in put

; chan nel. Se lect Vcc as the volt age ref er ence.

; Left jus tify re sult

movlw B’00000001’; Bitmap:

; 0 0 0 0 0 0 0 1

; | | | | | x___ 1 = turn on ADC

; | | x_x_x_______ 000 = se lect AN0

; | x_______________ 0 = volt age ref Vcc

; x_________________ 1 = left jus tify

banksel ADCON0

movwf ADCON0

The A/D con verter mod ule in the 16F684 pro vides a 10-bit re sult that is stored intwo ded i cated reg is ters la beled ADRESH and ADRESL. The high-or der bit of theADCON0 reg is ter, la beled the ADFM bit, is used to se lect be tween left- or right-jus ti -fi ca tion of the 10-bit re sult. In ei ther case, there are six bits that are not sig nif i cantand are set to zero by the con ver sion mod ule. The struc tures of the re sult reg is tersare shown in Figure 17-6.

422 Chap ter 17

Page 444: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 17-6 Con ver sion Op tions in the 16F684 A/D Mod ule.

Once the an a log-tdo-igital mod ule has been in i tial ized and an an a log line is de -fined and wired to the po ten ti om e ter, we can per form the read-and-con vert op er a -tion. The first step con sists of set ting bit 1 of the ADCON0 reg is ter (la beled the GObit) to start the con ver sion. Code then tests the state of this bit to de ter mine whenthe con ver sion has com pleted. This is sig naled by the A/D mod ule clear ing the GObit. Processing is as follows:

; 5K pot is wired to port A line 0 which has been setbanksel ADCON0 ; Pre pare to sam plebsf ADCON0,GO ; Start op er a tion

Wait4ADC:btfsc ADCON0,GO ; Wait for com ple tiongoto Wait4ADC ; Loop back if not done

Us ing a po ten ti om e ter to reg u late mo tor speed is usu ally based on us ing the re sis -tance value read from the pot to de ter mine the de lay be tween mo tor pulses. Thus,the higher the re sis tance, the larger the de lay and the slower the mo tor speed. Bythe same to ken, the lower the re sis tance read from the pot, the faster the mo torturns. In most cases the re sis tance value needs to be scaled so that the re sult ing de -lay be tween pulses matches the min i mum and maximum motor speeds desired.

In the case of the 16F684 an a log-to-dig i tal mod ule, the 10-bit re sult stored in theADRESH and ADRESL reg is ters has a nu meric range from 0 to 1023. In most caseswe would not need this many mo tor steps. Pro gram code can ma nip u late the con -ver sion re sults to ad just for the de sired mo tor speed range. For ex am ple, by se lect -ing left-jus ti fi ca tion and read ing only the ADRESH reg is ter, the two low-or der bitsare elim i nated. This will pro duce a re sult in the range 0 to 255 in stead of 0 to 1023.Of ten the con ver sion needs to be scaled fur ther be fore it can be used as a de layvalue. This re quires per form ing bi nary arith me tic on the re sults of the an a -log-to-dig i tal con ver sion. Shift ing bits pro vides an easy way to mul ti ply or di vide by two. Add ing or sub tract ing a con stant serves to trans pose the scale to a higher orlower range.

The sam ple pro gram SMU_PIC16F684.asm reads the high-or der nib ble of aleft-jus ti fied re sult and halves this value by shift ing the bits to the right one po si tion. Then a value of 40 is added to limit the fast est mo tor speed. Code is as fol lows:

Uni po lar Mo tor Cir cuits and Pro grams 423

Result is left-justified

Result is right-justified

ADFM bit = 0

ADFM bit = 1

LEGEND: Grayed bits are not significant

ADRESH

ADRESH

ADRESL

ADRESL

7 6 5 4 3 2 1 0

7 6 5 4 3 2 1 0

7 6 5 4 3 2 1 0

7 6 5 4 3 2 1 0

Page 445: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

banksel STATUS

bcf STATUS,C ; Clear carry to shift

banksel ADRESH

rrf ADRESH,w ; Ro tate in w

; Range is now 0 to 128

addlw .40 ; Add con stant

; Range is now 40 to 168

banksel de lay ; De lay vari able

movwf de lay

This code en sures that the value stored in the vari able named de lay is in therange 40 to 168. This range and scale worked well for the par tic u lar mo tor used intest ing this cir cuit; how ever, this code will need to be mod i fied to suit the char ac ter -is tics of a dif fer ent mo tor or the speed range re quire ments of the ap pli ca tion.

Sam ple Pro gram SMU_PIC16F684_INT.asm

The in ter rupt sys tem of the 16F684 is down ward com pat i ble with that of the 16F84.For this rea son, the In ter rupt-Driven mo tor con trols de vel oped in the sam ple pro gram SMU_5804_INT (which uses the 16F84) can be eas ily ported to an ap pli ca tion thatuses the 16F684.

The pro gram SMU_PIC16F684_INT.asm, in this book’s soft ware pack age, is an In -ter rupt-Driven ver sion of the pro gram SMU_PIC16F684.asm de scribed in the pre vi -ous sec tion. The only mod i fi ca tion re quired in the in ter rupt ser vice rou tine isre plac ing the des ig na tion for the port wired to the 16F84 step line by the one usedby the 16F684.

17.3.6 Step per Mo tor Po si tion Con trol

All the pro grams and ex am ples con sid ered to this point as sume that the step per mo tor ro tates con tin u ously in one di rec tion or the other, that is, that it per forms the con ven -tional func tion of a clas si cal mo tor. The con trol func tions dis cussed so far in cludespeed, di rec tion, and step se quence mode. The mo tor speed is con trolled by the fre -quency with which the step com mands are sent to the hard ware. How ever, be causeeach step code sent to a step per mo tor turns the ro tor by a fixed an gle, it is pos si ble tocon trol the ro tor po si tion by count ing the num ber of steps sent to the drive. For ex am -ple, if a given mo tor in full step mode turns by 2 de grees for each pulse re ceived, thenthe soft ware can make the ro tor turn by 20 de grees by send ing ten con sec u tive pulsesin the se lected di rec tion.

Al though servo mo tors (not cov ered in this book) are de signed to pro vide po si -tion con trol and do so ef fec tively, step per mo tors also have this ca pa bil ity. The useof con ven tional step per mo tors in po si tion con trol func tions is con ve nient in sit u a -tions in which the de vice needs to be lo cated at a cer tain po si tion by the op er a tor.This can be ac com plished by “jog ging” the mo tor, typ i cally by op er at ing one or more pushbuttons. An other ex am ple of po si tion con trol is to pro vide a “slew ing” rate ormode so as to re-po si tion a de vice, for ex am ple, to cor rect the lo ca tion of a step permo tor-con trolled de vice by add ing steps in a given di rec tion.

424 Chap ter 17

Page 446: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Sam ple Pro gram SMU_POSITION.asm

Po si tion con trol op er a tions are mostly ac com plished in soft ware. The cir cuit typ i -cally in cludes an in put source (an a log or dig i tal) that pro vides in for ma tion re gard ingthe di rec tion, amount, or speed of the move ment re quired. The sam ple pro gramSMU_PIC16F84.asm, de scribed ear lier in this chap ter, can be con sid ered a po si tioncon trol ap pli ca tion. In this case, the cir cuit SMU-PIC16F84-1 con tains fourpushbuttons and the pro gram reads the pushbuttons to jog the mo tor in the for ward or re verse di rec tion at a slow or fast slew rate.

The sam ple pro gram SMU_POSITION.asm, in this book’s soft ware pack age, usesthe cir cuit SMU-PIC16F84-1 (Fig ure 17-5) to il lus trate po si tion con trol. In this casethe 5K po ten ti om e ter in the cir cuit is read by the PIC’s ADC mod ule. The re sult ingre sis tance value is used to turn the mo tor a spe cific num ber of steps in ei ther di rec -tion. Pro gram logic is as follows:

1. Dur ing ini tial iza tion, the current po si tion of the potentiometer arm is stored as thelo cal ref er ence point (LRP).

2. The potentiometer is read by code and des ig nated as new ref er ence point (NRP).

3. NRP and LRP are com pared. If they are the same, no ac tion takes place. Ex e cu tioncon tin ues at Step 2.

4. If the NRP is greater than the LRP, then the dif fer ence is the num ber of steps the mo -tor is turned in the clock wise di rec tion.

5. If the NRP is smaller than LRP then the dif fer ence is the num ber of steps the mo toris turned in the coun ter clock wise di rec tion.

6. LRP is now set to NRP.

7. Pro cess ing con tin ues at Step 2.

In the pro gram SMU_POSITION.asm, the val ues of NRP and LRP are stored in lo -cal vari ables called nrp and lrp, re spec tively. The 16F684 PIC is in i tial ized so thatPORTC is out put and PORTA is in put. PORTA line 0 is des ig nated as an a log in putand wired to the po ten ti om e ter. The ADC hard ware is set to left-jus tify the re sult be -cause the pro gram only used the eight high-or der bits of the re sis tance read ing.Once the lo cal vari ables are in i tial ized, code pro ceeds as fol lows:

;================================; Read pot and pulse mo tor;================================ReadPotAndMove:

call De lay ; Wait to up datecall ReadPotbanksel nrpmovwf nrp ; Store re sult

;; Com pare new value with old value by sub trac tion.; Sub trac tion per forms w (new ref er ence po si tion); mi nus lo cal ref er ence po si tion (old value).; If Z flag set nrp == lrp; If carry flag set lrp < nrp ;

subwf lrp,w ; Sub tract w (nrp) from lrp

Uni po lar Mo tor Cir cuits and Pro grams 425

Page 447: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

banksel STATUSbtfsc STATUS,Z ; Test zero flaggoto NoChange ; Go if Z flag is set

; At this point nrp not equal to lrp; Test the carry flag to de ter mine if lrp < nrp

btfss STATUS,C ; Is C flag set?goto MoveLeft ; Go if new big ger than oldgoto MoveRight

;;============================; move left;============================; Move left by dif fer ence be tween new and old read ings; First ob tain ab so lute value of dif fer ence. At this point; lrp > nrpMoveLeft:

banksel lrpmovf lrp,w ; Get lrpsubwf nrp,w ; old (in w) mi nus new banksel ticksmovwf ticks ; Store dif fer ence

; Set con trol ler to re verse ro ta tionbanksel PORTCbsf PORTC,1 ; Set re verse

TickLeft:banksel PORTCbcf PORTC,0 ; Set low call Pulsecall De laybanksel ticks ; Coun terdecfsz ticks,fgoto TickLeft ; Loopgoto Up date

;;==============================; move right;==============================; Move to the right by num ber of ticks in wMoveRight:

banksel ticksmovwf ticks ; Store dif fer ence

; Set for ward ro ta tionbanksel PORTCbcf PORTC,1 ; Clear bit

TickRight:banksel PORTCbcf PORTC,0 ; Set low call Pulsecall De laybanksel ticks ; Coun terdecfsz ticks,fgoto TickRight ; Loop

;;==============================; Up date po si tion con trol;==============================Up date:

banksel nrpmovf nrp,w ; New value to wmovwf lrp

426 Chap ter 17

Page 448: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

NoChange:goto ReadPotAndMove

The lo cal pro ce dures ReadPot, De lay, and Pulse are not listed and can be found in the sam ple code.

17.4 Dem on stra tion Pro gramsThe pro grams listed in the fol low ing sec tion dem on strate the pro gram ming dis cussedin this chap ter.

17.4.1 SMB_297_293D.asm;============================================================; File: SMB_297_293D.asm; Date: No vem ber 6, 2010; Up date: No vem ber 13, 2010; Au thors: Sanchez and Can ton; Pro ces sor: 16F84A; Ref er ence cir cuit: SMB-L297-293D-1 ;; Pro gram De scrip tion:; Pro gram to drive a bi po lar step per mo tor us ing a 16F84 PIC; as a con trol ler, wired to an L297 and a 293D driver. The; pro gram reads the tog gle switch wired to port RA4 to se lect; be tween clock wise or coun ter clock wise ro ta tion. The tog gle; switch wired to line RA3 al lows se lect ing be tween half- or; full-step modes. Slow and fast speeds are de ter mined by the; set ting of the tog gle switch on port line RA3. The pushbutton; switches on cir cuit SMB-L297-293D-1 are not used by thepro gram.; Cir cuit wir ing is as fol lows:;; SLOW/FAST RA2->|--------| ; FULL/HALF RA3->| |; CW/CCW RA4->| |<------- OSC; RESET->| |<------- OSC; GND | | +5v; ENABLE RB0<-| |; CW / CCW RB1<-| |; STEP RB2<-| |; HALF/FULL RB3<-| |; |--------|;;=========================; setup and con fig u ra tion;=========================

pro ces sor 16f84Ain clude <p16f84A.inc>__config _XT_OSC & _WDT_OFF & _PWRTE_ON & _CP_OFF

Uni po lar Mo tor Cir cuits and Pro grams 427

Page 449: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

errorlevel -302;============================================================; con stant def i ni tion;============================================================;;============================================================; vari ables in PIC RAM;============================================================; De clare vari ables at 2 mem ory lo ca tionsj equ 0x0ck equ 0x0dbounce equ 0x0e ; For debounce rou tinede lay equ 0x0f ; De lay count

;============================================================; m a i n p r o g r a m;============================================================

org 0 ; start at ad dress 0goto Main

;=============================; space for in ter rupt han dler;=============================

org 8;=============================; main pro gram;=============================Main:; Clear bit 7 in OPTION_REG to en able port B pullups

bcf OPTION_REG,7; Note: al though en abling the weak pullups on port B; should al low the cir cuit to op er ate with out the; con ven tional 10K pullup re sis tors, we have; found that the weak pullups are un re li able on; the 16F84. There fore we ad vise that the board; in clude the 10K pullups.; Tris PORT A for in put

movlw B'00011111' ; w = 00011111 bi narytris PORTA ; Set up port A for in put

; Tris lines 0 to 3 in port B for out put and; lines 4 to 7 (tog gle switch # 2) for in put

movlw B'11110000' ; RB7-RB4 for in put, rest; for out put

tris PORTB ; Set up port Bclrf PORTB ; Clear all lines

; Set default state for L297 con trol lines, wired as; fol lows:; PORT B BITS ; 7 6 5 4 3 2 1 0 De fault

428 Chap ter 17

Page 450: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; | | | | | | | |____ ENABLE 1 (ac tive); | | | | | | |_______ CW/CCW 0 (CW); | | | | | |__________ CLOCK 1; | | | | |_____________ mode 1 (half step); |__|__|__|________________ NOT USED

movlw B'00001101' ; Half step, cw di rec tionmovwf PORTB

; Ini tial ize de fault value for de lay vari ablemovlw .40movwf de lay ; To de lay vari able

;===============================================================; main con trol mon i tor ing rou tine;===============================================================ControlRtn:; Call pro ce dure to set L297 lines ac cord ing to state of three; tog gle switches wired to port lines A2 to A4

call ReadATogglescall De lay ; De lay nowcall Pulse ; Lo cal pulse mo tor rou tinegoto ControlRtn

;========================================================; Aux il iary procedure to read tog gle switches;========================================================ReadAToggles:; Read PORTA tog gle switches; PORT A TOGGLE ; line SW ACTION; 4 1 0 = CW ro ta tion 1 = CCW; 3 2 0 = full step 1 = half step; 2 3 1 = fast 0 = slow;=============================; set CW or CCW ro ta tion;============================= ; Bit 4 on port A is wired to tog gle # 1; Bit 1 on port B is wired to pin 17 of the L297, which; con trols CW and CCW ro ta tion.

btfsc PORTA,4goto goCCW ; Set ro ta tion bit to CCW

; Bit clear. Set CWbcf PORTB,1 ; Clear port B line 1goto SetStep

goCCW:bsf PORTB,1

;=============================; set half or full step;=============================

Uni po lar Mo tor Cir cuits and Pro grams 429

Page 451: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

SetStep:; Tog gle switch # 2, on port A, line 3, se lects be tween; half step and full step modes. Port B bit 3 is wired; to L297 line 19, which se lects half or full step modes

btfsc PORTA,3goto HalfStep ; Bit is set. Set half step

mode; Bit clear. Set full step mode

bcf PORTB,3 ; Clear port B line 2goto SetSpeed

HalfStep:bsf PORTB,3

;=============================; set fast or slow speed;=============================SetSpeed:; Tog gle switch # 3, on port A, line 2, se lects be tween; fast and slow mo tor speed. If the tog gle is on the de lay; value it is set to 40, if it is off it is set to 80

btfsc PORTA,2goto FastSpeed ; Bit is set. Set fast de lay

; Bit clear. Set slow speedmovlw .80movwf de lay ; To de lay vari ablegoto En able

FastSpeed:movlw .40movwf de lay ; To de lay vari able

;=============================; en able mo tor con trol line;=============================; The L297 is al ways in the ENABLE stateEn able:

bsf PORTB,0 ; Set bit to en ablere turn

;================================; rou tine to pulse the mo tor;================================; L297 CLOCK line is wired to RB2Pulse:

bsf PORTB,2 ; Bring step line highnopnopnopnopnopnop

430 Chap ter 17

Page 452: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

nopnopnopnopbcf PORTB,2 ; Step line lowre turn

;================================; de lay sub-rou tines;================================De lay:

movf de lay,w ; De lay to w reg is termovwf j ; j = w

Jloop:movwf k ; k = w

Kloop:decfsz k,f ; k = k-1, skip next if zerogoto Kloopdecfsz j,f ; j = j-1, skip next if zerogoto Jloopre turnend ;END OF PROGRAM

17.4.2 SMU_PIC16F84.asm Pro gram;============================================================; File: SMU_PIC16F84.asm; Date: Oc to ber 3, 2010; Up date: No vem ber 27, 2010; Au thors: Sanchez and Canton; Pro ces sor: 16F84A; Ref er ence cir cuit: SMU-PIC16F84-1 ;; Pro gram De scrip tion:; Pro gram to drive a uni po lar step per mo tor in one-half step; mode with a 16F84 wired to 4050 hex buffer IC and TIP 120; tran sis tors.; Pro gram uses a lookup ta ble for the se quence codes.;; INPUT:; Pushbuttons wired to ports A3 and A2 ac ti vate slow ro ta tion; in for ward and re verse di rec tion when held down. Pushbuttons; wired to ports A0 and A1 ac ti vate for ward and re verse fast; ro ta tion. Code uses an ac cess code ta ble with a pointer, that; is ei ther in cre mented or dec re ment ed ac cord ing to the; se lected di rec tion. This en sures that re verses in ro ta tion; are ex e cuted smoothly. Fast and slow ex e cu tions are de ter mined; by the value of a lo cal vari able read by the de lay rou tine.

Uni po lar Mo tor Cir cuits and Pro grams 431

Page 453: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

;===========================; demo board cir cuit ;===========================; Port A lines 0 to 3 trised for in put:; 0 ---> Pushbut ton switch A, ac tive low; 1 ---> Pushbut ton switch B, ac tive low; 2 ---> Pushbut ton switch C, ac tive low; 3 ---> Pushbut ton switch D, ac tive low; Port B lines 0 to 3 trissed for out put and wired; as fol lows:; RB0 ---> Q1 mo tor wind ing; RB1 ---> Q4 mo tor wind ing; RB2 ---> Q2 mo tor wind ing; RB3 ---> Q3 mo tor wind ing ;=========================; setup and con fig u ra tion;=========================

pro ces sor 16f84Ain clude <p16f84A.inc>__config _XT_OSC & _WDT_OFF & _PWRTE_ON & _CP_OFFerrorlevel -302

;============================================================; vari ables in PIC RAM;============================================================; De clare vari ables at 2 mem ory lo ca tionsj equ 0x0ck equ 0x0dthis_cy cle equ 0x0e ; Cur rent cy cle coun terdi rec tion equ 0x0f ; Di rec tion con trol

; 0 = for ward; 1 = re verse

bounce equ 0x10 ; Debounce coun terde lay equ 0x11 ; De lay coun ter;============================================================; m a i n p r o g r a m;============================================================

org 0 ; start at ad dress 0goto Main

;=============================; space for in ter rupt han dler;=============================

org 0x08;===================================; look-up ta ble for mo tor;===================================; Se ries 42M048C uni po lar step per mo tors re quire the; fol low ing one-half step drive se quence for clock wise

432 Chap ter 17

Page 454: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; ro ta tion:; | w i n d i n g s | ; STEP Q1 Q2 Q3 Q4 BIN ; 1 ON OFF ON OFF 1010; 2 ON OFF OFF OFF 1000; 3 ON OFF OFF ON 1001; 4 OFF OFF OFF ON 0001 ; 5 OFF ON OFF ON 0101; 6 OFF ON OFF OFF 0100; 7 OFF ON ON OFF 0110; 8 OFF OFF ON OFF 0010; Ta ble is placed low in mem ory to avoid page over laps.;CodeTable:

addwf PCL,f ; Add w to pro gram coun terretlw B’00001010’ ; cy cle = 0retlw B’00001000’ ; 1retlw B’00001001’ ; 2retlw B’00000001’ ; 3retlw B’00000101’ ; 4retlw B’00000100’ ; 5retlw B’00000110’ ; 6retlw B’00000010’ ; 7retlw B’00000000’ ; Ta ble ter mi na tor

;=============================; main pro gram;=============================Main:; Tris PORT A for in put

movlw B’00011111’ ; w = 00011111 bi narytris PORTA ; Set up port A for in put

; Ini tial ize all lines in port B for out putmovlw B’00000000’ ; w = 00000000 bi narytris PORTB ; Set up port B for out putclrf PORTB ; Clear all lines

; Ini tial ize con trol vari ablesclrf this_cy cleclrf di rec tion ; As sume for ward di rec tionmovlw .100 ; Ini tial de lay for fastmovwf de lay ; To vari able

;=============================; read and debounce PORTA; lines 0 to 3;=============================; Switches are ac tive low, so changes in di rec tion take place; if port line is clear. Soft ware debouncing is used to make; sure that spu ri ous switch reads are ig nored.

Uni po lar Mo tor Cir cuits and Pro grams 433

Page 455: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

TestPortA:; First read and debounce PORTA-3

movlw .10 ; Coun termovwf bounce

Wait43:btfsc PORTA,3goto No3Action ; Go if bit is setdecfsz bounce,f ; Dec re ment coun tergoto Wait43

; At this point switch held zero for 10 testsclrf di rec tion ; 0 is forward on di rec tion

switchmovlw .100 ; Slow de lay ratemovwf de lay ; To de lay coun tercall OneTick ; Tick mo torgoto TestPortA

;=============================; read and debounce PORTA-2;=============================No3Action:

movlw .10 ; Coun termovwf bounce

Wait42:btfsc PORTA,2goto No2Action ; Go if bit is setdecfsz bounce,f ; Dec re ment coun tergoto Wait42

; At this point switch held zero for 10 testsmovlw .1 ; 1 is re verse on di rec tion

; switchmovwf di rec tion ; Code to switchmovlw .100 ; Slow de lay ratemovwf de lay ; To de lay coun tercall OneTick ; Tick mo torgoto TestPortA

No2Action:;================================; read and debounce PORTA-1;================================; Debounce PORTA-1TestPortA1:

movlw .10 ; Coun termovwf bounce

Wait41:btfsc PORTA,1goto No1Action ; Go if bit is setdecfsz bounce,f ; Dec re ment coun tergoto Wait41

434 Chap ter 17

Page 456: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; At this point switch held zero for 10 testsclrf di rec tion ; 0 is forward on di rec tion

switchmovlw .40 ; Fast de lay ratemovwf de lay ; To de lay coun tercall OneTick ; Tick mo torgoto TestPortA

;================================; read and debounce PORTA-1;================================No1Action:; Debounce PORTA-0

movlw .10 ; Coun termovwf bounce

Wait40:btfsc PORTA,0goto No0Action ; Go if bit is setdecfsz bounce,f ; Dec re ment coun tergoto Wait40

; At this point switch held zero for 10 testsmovlw .1 ; 1 is re verse on di rec tion

; switchmovwf di rec tion ; Code to switchmovlw .40 ; Fast de lay ratemovwf de lay ; To de lay coun tercall OneTick ; Tick mo torgoto TestPortA

No0Action:goto TestPortA

;==========================; for ward or re verse; sin gle cy cle pro ce dure;==========================OneTick:; Test for change of di rec tion

btfss di rec tion,0 ; Test for ward bitgoto For ward

; At this point di rec tion ro ta tion is re versegoto Re verse

; Forward di rec tion rou tineFor ward:

movf this_cy cle,w ; Get cur rent cy clecall CodeTable ; Get code from ta blemovwf PORTB ; Store code in portcall De lay

; Bump cy cle coun terincf this_cy cle,f ; Add one

; Test for cy cle num ber 7 (last one in se quence)

Uni po lar Mo tor Cir cuits and Pro grams 435

Page 457: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

btfsc this_cy cle,3 ; 1000 = 8goto Re cy cle ; Re set if at end of cy clere turn

Re cy cle:clrf this_cy clere turn

; Re verse di rec tion rou tineRe verse:

movf this_cy cle,w ; Get cur rent cy clecall CodeTable ; Get code from ta blemovwf PORTB ; Store code in portcall De lay

; Bump cy cle coun terdecf this_cy cle,f ; Sub tract one

; Test for cy cle num ber 0xff (over flow from cy cle # 0)btfsc this_cy cle,4 ; Bit 4 set in di cates over flowgoto Recycle2 ; Re set if at end of cy clere turn

Recycle2:movlw .7 ; First re verse cy clemovwf this_cy cle ; To cy cle coun terre turn

;================================; de lay sub-rou tine;================================De lay:

movf de lay,w ; Load de lay valuemovwf j ; j = w

Jloop:movwf k ; k = w

Kloop:decfsz k,f ; k = k-1, skip next if zerogoto Kloopdecfsz j,f ; j = j-1, skip next if zerogoto Jloopre turn

end ;END OF PROGRAM

17.4.3 SMU_5804.asm;============================================================; File: SMU_5804.asm; Date: Oc to ber 3, 2010; Up date: De cem ber 4, 2010; Au thors: Sanchez and Canton; Pro ces sor: 16F84A; Ref er ence cir cuit: SMU-5804-1

436 Chap ter 17

Page 458: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

;; Pro gram De scrip tion:; Pro gram to drive a uni po lar step per mo tor mode with a 16F84; PIC con trol ling a UCN5804 driver.; Three tog gle switches wired to ports A2 to A4 turn on and; off the di rec tion, half step, and sin gle phase modes on the; 5804.; Four tog gle switches wired to ports B4 to B7 pro vide in put; in the range 0 to 15. This value is used to se lect the de lay; rate that de ter mines mo tor speed.;===========================; demo board cir cuit ;===========================; Port A lines 0 to 4 trissed for in put:; 0 -----> NOT WIRED; 1 -----> NOT WIRED; 2 -----> Tog gle switch 3; 3 -----> Tog gle switch 2; 4 -----> Tog gle switch 1; Port B lines 0 to 3 trissed for out put and wired; as fol lows:; PIC 5804; RB0 -----> pin 11 - Step in put; RB1 -----> pin 14 - Di rec tion; RB2 -----> pin 10 - Half step; RB3 -----> pin 9 - One phase; Port B lines 4 to 7 are trissed for in put; RB4 --------------|; RB5 --------------|---- mo tor speed con trol; RB6 --------------| tog gle switches; RB7 --------------|; Set tings for phase con trol:; RB1 (half step) RB3 (one phase); 0 0 = two phase; 0 1 = wave drive; 1 0 = half step; 1 1 = step in hibit; Tog gle switch con trols; PORTA line SW ACTION; 4 TS3 Di rec tion (for ward/re verse); Set PORTB to: xxxx xx0x; or: xxxx xx1x; 3 TS2 One-half step; Set PORTB to: xxxx x0xx; or: xxxx x1xx; 2 TS1 One phase; Set PORTB to: xxxx 0xxx; or: xxxx 1xxx

Uni po lar Mo tor Cir cuits and Pro grams 437

Page 459: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

;=========================; setup and con fig u ra tion;=========================

pro ces sor 16f84Ain clude <p16f84A.inc>__config _XT_OSC & _WDT_OFF & _PWRTE_ON & _CP_OFFerrorlevel -302

;============================================================; vari ables in PIC RAM;============================================================; De clare vari ables at 2 mem ory lo ca tionsj equ 0x0ck equ 0x0dde lay equ 0x11 ; De lay count;============================================================; m a i n p r o g r a m;============================================================

org 0 ; start at ad dress 0goto Main

;=============================; space for in ter rupt han dler;=============================

org 8;=============================; De lay ta ble for speed; con trol;=============================; Val ues in ta ble range from 250 to 25 (15 units apart); Ta ble has 16 en tries cor re spond ing to the val ues; rep re sented by the set ting of the 4 speed con trol; tog gle switchesSpeedTable:

addwf PCL,f ; Add w to pro gram coun terretlw .255 ; Slow est speed 0000 = 0retlw .240 ; 0001 = 1retlw .225 ; 0010 = 2retlw .210 ; 0011 = 3retlw .195 ; 0100 = 4retlw .180 ; 0101 = 5retlw .165 ; 0110 = 6retlw .150 ; 0111 = 7retlw .135 ; 1000 = 8retlw .120 ; 1001 = 9retlw .105 ; 1010 = 10retlw .90 ; 1011 = 11retlw .75 ; 1100 = 12retlw .60 ; 1101 = 13 retlw .45 ; 1110 = 14

438 Chap ter 17

Page 460: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

retlw .30 ; Fastest 1111 = 15retlw .0 ; Ter mi na tor

;=============================; main pro gram;=============================Main:; Tris PORT A for in put

movlw B'00011111' ; w = 00011111 bi narytris PORTA ; Set up port A for in put

; Tris port B low nib ble for out put and high nib ble; for in put

movlw B'11110000' ; w = 11110000 bi narytris PORTB ; Port B lines 0 to 3 are

; out put and lines 4 to 7; are in put

clrf PORTB ; Clear all lines; Set default state for 5801 con trol lines, wired as; fol lows:; PORT B BITS ; 7 6 5 4 3 2 1 0 De fault; | | | | | | | |____ Step in put 0; | | | | | | |_______ Di rec tion 0; | | | | | |__________ One half step 1; | | | | |_____________ One phase 0; |__|__|__|________________ speed con trol in put; Note that 5804 En able line is wired to ground

movlw B'00000100' ; Half step, cw di rec tionmovwf PORTB

; Ini tial ize de fault value for de lay vari ablemovlw .100movwf de lay ; To de lay vari able

;================================; Pulse mo tor and de lay;================================PulseAndDelay:; Make sure 5804 Step In line is low be fore strobe; cy cle

bcf PORTB,0 ; Set low call Pulse ; Lo cal pulse mo tor rou tinecall De lay

;============================; Read speed con trol tog gles;============================; Read four speed con trol tog gle switches on port; B lines 4 to 7. The swapf in struc tion al lows swap ping; nib bles as they are read from the port

swapf PORTB,w ; Read port B and swap nib bles

Uni po lar Mo tor Cir cuits and Pro grams 439

Page 461: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

andlw B'00001111' ; Mask out 4 high bits call SpeedTable ; Use value in w to ob tain

; de laymovwf de lay ; Store code in lo cal vari able

;============================; Read 5804 con trol lines;============================; PORTA bit 4 (wired to tog gle # 1) con trols for ward; or re verse di rec tion by means of PORTB bit 1 (wired; to 5804 di rec tion line on pin 14).

btfsc PORTA,4 ; Di rec tion con trol switchgoto ReverseRot ; En gage re verse ro ta tion

; At this point ro ta tion is for wardbcf PORTB,1 ; Clear bit `goto HalfStepMode

ReverseRot:bsf PORTB,1 ; Set re verse

HalfStepMode:; PORTA bit 3 (wired to tog gle # 2) se lects half-step; mode by means of PORTB bit 2 (wired to 5804 half-step; line on pin 10).

btfsc PORTA,3 ; Half step mode con trolgoto NoHalfStep ; Dis able half step

; At this point half step is se lectedbsf PORTB,2 ; Set bit `goto OnePhaseMode

NoHalfStep:bcf PORTB,2 ; Turn off half step con trol

OnePhaseMode:; PORTA bit 2 (wired to tog gle # 3) se lects one phase; mode by means of PORTB bit 3 (wired to 5804 sin gle; phase line on pin 9).

btfsc PORTA,2 ; One phase mode con trolgoto NoOnePhase ; Dis able sin gle step

; At this point sin gle phase is se lectedbsf PORTB,3 ; Set sin gle phase `goto PulseAndDelay

NoOnePhase:bcf PORTB,3 ; Turn off one phasegoto PulseAndDelay

;================================; rou tine to pulse the 5804;================================; Note that 5804 re quires a pos i tive-go ing pulse; there fore the line is held high dur ing the strobe; cy clePulse:

bsf PORTB,0 ; Bring step line high

440 Chap ter 17

Page 462: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

nopnopnopnopnopnopnopnopnopnopbcf PORTB,0 ; Step line lowre turn

;================================; de lay sub-rou tine;================================De lay:

movf de lay,w ; De lay to w reg is termovwf j ; j = w

Jloop:movwf k ; k = w

Kloop:decfsz k,f ; k = k-1, skip next if zerogoto Kloopdecfsz j,f ; j = j-1, skip next if zerogoto Jloopre turn

end ;END OF PROGRAM

17.4.4 SMU_5804_INT.asm;============================================================; File: SMU_5804_INT.asm; Date: De cem ber 10, 2010; Up date: ; Au thors: Sanchez and Can ton; Pro ces sor: 16F84A; Ref er ence cir cuit: SMU-5804-1;; Pro gram De scrip tion:; This is a ver sion SMU_5804.asm that uses the Timer0; in ter rupt to send pulses to the step per mo tor.; Three tog gle switches wired to ports A2 to A4 turn on and; off the di rec tion, half step, and sin gle phase modes on the; 5804.; Four tog gle switches wired to ports B4 to B7 pro vide in put; in the range 0 to 15. This value is used to se lect the de lay

Uni po lar Mo tor Cir cuits and Pro grams 441

Page 463: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; rate from a lookup ta ble in RAM. This de lay rate is used in; the in ter rupt han dler to de ter mine when a pulse is sent to; the step per mo tor.;===========================; demo board cir cuit ;===========================; Port A lines 0 to 4 trissed for in put:; 0 -----> NOT WIRED; 1 -----> NOT WIRED; 2 -----> Tog gle switch 3; 3 -----> Tog gle switch 2; 4 -----> Tog gle switch 1; Port B lines 0 to 3 trissed for out put and wired; as fol lows:; PIC 5804; RB0 -----> pin 11 - Step in put; RB1 -----> pin 14 - Di rec tion; RB2 -----> pin 10 - Half step; RB3 -----> pin 9 - One phase; Port B lines 4 to 7 are trissed for in put; RB4 --------------|; RB5 --------------|---- mo tor speed con trol; RB6 --------------| tog gle switches; RB7 --------------|; Set tings for phase con trol:; RB1 (half step) RB3 (one phase); 0 0 = two phase; 0 1 = wave drive; 1 0 = half step; 1 1 = step in hibit; Tog gle switch con trols:; PORTA line SW ACTION; 4 TS3 Di rec tion (for ward/re verse); Set PORTB to: xxxx xx0x; or: xxxx xx1x; 3 TS2 One-half step; Set PORTB to: xxxx x0xx; or: xxxx x1xx; 2 TS1 One phase; Set PORTB to: xxxx 0xxx; or: xxxx 1xxx ;=========================; setup and con fig u ra tion;=========================

pro ces sor 16f84Ain clude <p16f84A.inc>__config _XT_OSC & _WDT_OFF & _PWRTE_ON & _CP_OFFerrorlevel -302

442 Chap ter 17

Page 464: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

;============================================================; vari ables in PIC RAM;============================================================; De clare vari ables at 2 mem ory lo ca tionsj equ 0x0ck equ 0x0dde lay equ 0x11 ; De lay countold_w equ 0x12 ; Con text sav ing old_STATUS equ 0x13 ; Idemit er a tion equ 0x14 ; It er a tion coun ter used by

; in ter rupt han dler;============================================================; m a i n p r o g r a m;============================================================

org 0 ; start at ad dress 0goto Main

;=============================; space for in ter rupt han dler;=============================

org 0x04goto IntServ

;=============================; De lay ta ble for speed; con trol;=============================; Val ues in ta ble range from 250 to 25 (15 units apart); Ta ble has 16 en tries cor re spond ing to the val ues; rep re sented by the set ting of the 4 speed con trol; tog gle switchesSpeedTable:

addwf PCL,f ; Add w to pro gram coun terretlw .255 ; Slow est speed 0000 = 0retlw .240 ; 0001 = 1retlw .225 ; 0010 = 2retlw .210 ; 0011 = 3retlw .195 ; 0100 = 4retlw .180 ; 0101 = 5retlw .165 ; 0110 = 6retlw .150 ; 0111 = 7retlw .135 ; 1000 = 8retlw .120 ; 1001 = 9retlw .105 ; 1010 = 10retlw .90 ; 1011 = 11retlw .75 ; 1100 = 12retlw .60 ; 1101 = 13 retlw .45 ; 1110 = 14retlw .30 ; Fast est speed 1111 = 15retlw .0 ; Ter mi na tor

Uni po lar Mo tor Cir cuits and Pro grams 443

Page 465: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

;=============================; main pro gram;=============================Main:; Tris PORT A for in put

movlw B'00011111' ; w = 00011111 bi narytris PORTA ; Set up port A for in put

; Tris port B low nib ble for out put and high nib ble; for in put

movlw B'11110000' ; w = 11110000 bi narytris PORTB ; Port B lines 0 to 3 are

; out put and lines 4 to 7; are in put

clrf PORTB ; Clear all lines; Clear the watch dog timer and re set prescaler

clrf TMR0clrwdt

; Set up the OPTION reg is termovlw b'11010000'

; 7 6 5 4 3 2 1 0 <= OPTION bits; | | | | | |__|__|_____ PS2-PS0 (prescaler bits); | | | | | Val ues for Timer0; | | | | | *000 = 1:2 001 = 1:4; | | | | | 010 = 1:8 011 = 1:16; | | | | | 100 = 1:32 101 = 1:64; | | | | | 110 = 1:128 111 = 1:256; | | | | |______________ PSA (prescaler as sign); | | | | 1 = to WDT; | | | | *0 = to Timer0; | | | |_________________ TOSE (Timer0 edge se lect); | | | 0 = in cre ment on low-to-high; | | | *1 = in cre ment on high-to-low; | | |____________________ TOCS (TMR0 clock source); | | *0 = in ter nal clock; | | 1 = RA4/TOCKI bit source; | |_______________________ INTEDG (Edge se lect); | *0 = fall ing edge; |__________________________ RBPU (Pullup en able); 0 = en abled; *1 = disabled; Note that OPTION reg is ter is in bank 1 and its reg is ter; name is OPTION_REG

bsf STATUS,RP0 ; RP0 is bank se lect bitmovwf OPTION_REG ; Copy w to OPTIONbcf STATUS,RP0 ; Bank 0

;============================; set up in ter rupts

444 Chap ter 17

Page 466: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

;============================; Clear ex ter nal in ter rupt flag (INTF = bit 1)

bcf INTCON,INTF ; Clear flag; En able global in ter rupts (GIE = bit 7); En able RB0 in ter rupt (inte = bit 4)

bsf INTCON,GIE ; En able global int (bit 7)bsf INTCON,T0IE ; En able TMR0 over flow

; in ter rupt; Set default state for 5801 con trol lines, wired as; fol lows:; PORT B BITS ; 7 6 5 4 3 2 1 0 De fault; | | | | | | | |____ Step in put 0; | | | | | | |_______ Di rec tion 0; | | | | | |__________ One half step 1; | | | | |_____________ One phase 0; |__|__|__|________________ speed con trol in put; Note that 5804 En able line is wired to ground

movlw B'00000100' ; Half step, cwdi rec tion

movwf PORTB; Ini tial ize de fault value for de lay vari able

movlw .100movwf de lay ; To de lay vari ablemovwf it er a tion ; To it er a tion coun ter

;============================; Read speed con trol tog gles;============================; Read four speed con trol tog gle switches on port; B lines 4 to 7. The swapf in struc tion al lows swap ping; nib bles as they are read from the portReadControls:

swapf PORTB,w ; Read port B and swap nib blesandlw B'00001111' ; Mask out 4 high bits

call SpeedTable ; Use value in w to ob tainde lay

movwf de lay ; Store code in lo cal vari able;============================; Read 5804 con trol lines;============================; PORTA bit 4 (wired to tog gle # 1) con trols for ward; or re verse di rec tion by means of PORTB bit 1 (wired; to 5804 di rec tion line on pin 14).

btfsc PORTA,4 ; Di rec tion con trol switchgoto ReverseRot ; En gage re verse ro ta tion

; At this point ro ta tion is for wardbcf PORTB,1 ; Clear bit `goto HalfStepMode

Uni po lar Mo tor Cir cuits and Pro grams 445

Page 467: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

ReverseRot:bsf PORTB,1 ; Set re verse

HalfStepMode:; PORTA bit 3 (wired to tog gle # 2) se lects half-step; mode by means of PORTB bit 2 (wired to 5804 half-step; line on pin 10).

btfsc PORTA,3 ; Half step mode con trolgoto NoHalfStep ; Dis able half step

; At this point half step is se lectedbsf PORTB,2 ; Set bit `goto OnePhaseMode

NoHalfStep:bcf PORTB,2 ; Turn off half step con trol

OnePhaseMode:; PORTA bit 2 (wired to tog gle # 3) se lects one phase; mode by means of PORTB bit 3 (wired to 5804 sin gle; phase line on pin 9)

btfsc PORTA,2 ; One phase mode con trolgoto NoOnePhase ; Dis able sin gle step

; At this point sin gle phase is se lectedbsf PORTB,3 ; Set sin gle phase `goto ReadControls

NoOnePhase:bcf PORTB,3 ; Turn off one phasegoto ReadControls

;=======================================================; In ter rupt Ser vice Rou tine;=======================================================; Ser vice rou tine re ceives con trol when the timer; reg is ter TMR0 over flows, that is, when 256 timer beats; have elapsedIntServ:; First test if source is a Timer0 in ter rupt

btfss INTCON,T0IF ; T0IF is Timer0 in ter ruptgoto notTOIF ; Go if not RB0 or i gin

; If so clear the timer in ter rupt flag so that count con tin uesbcf INTCON,T0IF ; Clear in ter rupt flag

; Save con textmovwf old_w ; Save w reg is terswapf STATUS,w ; STATUS to wmovwf old_STATUS ; Save STATUS

;=========================; in ter rupt ac tion;=========================; Decrement the it er a tion coun ter. Exit if not zero

decfsz it er a tion,fgoto exitISR ; Con tinue if coun ter not zero

446 Chap ter 17

Page 468: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; At this point the de lay count has ex pired so the pro grammed; time has elapsed.; First re set the it er a tion coun ter

movf de lay,w ; Read de laymovwf it er a tion ; Re set it er a tion coun ter

;================================; Pulse mo tor and de lay;================================; Make sure 5804 Step In line is low be fore strobe; cy cle

bcf PORTB,0 ; Set low call Pulse ; Lo cal pulse mo tor rou tine

;=========================; exit ISR;=========================exitISR:; Re store con text

swapf old_STATUS,w ; Saved STATUS to wmovfw STATUS ; To STATUS reg is terswapf old_w,f ; Swap file reg is ter in it selfswapf old_w,w ; re-swap back to w

; Re set,in ter ruptnotTOIF:

retfie;================================; rou tine to pulse the 5804;================================; Note that 5804 re quires a pos i tive-go ing pulse; there fore the line is held high dur ing the strobe; cy clePulse:

bsf PORTB,0 ; Bring step line highnopnopnopnopnopnopnopnopnopnopbcf PORTB,0 ; Step line lowre turn

end ;END OF PROGRAM

Uni po lar Mo tor Cir cuits and Pro grams 447

Page 469: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

17.4.5 SMU_PIC16F684.asm;============================================================; File: SMU_PIC16F684.asm; Date: De cem ber 9, 2010; Up date: De cem ber 30, 2010; Au thors: Sanchez and Can ton; Pro ces sor: 16F684A; Ref er ence cir cuit: SMU-PIC16F684-1;; Pro gram De scrip tion:; Pro gram to drive a uni po lar step per mo tor in half step; mode, with a 16F684 PIC con trol ling a UCN5804 driver.; Three tog gle switches wired to ports RA1 to RA3 turn on and; off the di rec tion, half step, and sin gle phase modes on the; 5804.; A 5K po ten ti om e ter on port RA0 pro vides in put to the chip’s; ADC. The re sult ing re sis tance value is used to se lect the; de lay rate which, in turn, de ter mines the mo tor speed.;;===========================; demo board cir cuit ;===========================; Port A lines 0 to 4 trised for in put:; 0 ---> 5K po ten ti om e ter => An a log input; 1 ---> Tog gle switch 3 |; 2 ---> Tog gle switch 2 |=> Dig i tal in put; 3 ---> MCLR func tion | ; 4 ---> Tog gle switch 4 |; 5 ---> NOT WIRED; Port C lines 0 to 3 trissed for out put and wired; as fol lows:; PIC 5804; RC0 ---> pin 11 - Step in put; RC1 ---> pin 14 - Di rec tion; RC2 ---> pin 9 - One phase; RC3 ---> pin 10 - Half Step; Set tings for phase con trol:; RC3 (half step) RC2 (one phase); 0 0 = two phase; 0 1 = wave drive; 1 0 = half step; 1 1 = step in hibit; Tog gle switch con trols; PORTC line SW ACTION; 1 TS3 Di rec tion (for ward/re verse); Set PORTC to: xxxx xx0x; or: xxxx xx1x

448 Chap ter 17

Page 470: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; 2 TS2 One phase; Set PORTC to: xxxx x0xx; or: xxxx x1xx; 3 TS1 One half step; Set PORTC to: xxxx 0xxx; or: xxxx 1xxx ;=========================; setup and con fig u ra tion;=========================

pro ces sor 16f684in clude <p16f684.inc>__CONFIG _MCLRE_OFF & _CP_OFF & _CPD_OFF & _BOD_OFF &

_WDT_OFF & _PWRTE_ON & _INTOSCIO & _FCMEN_OFF & _IESO_OFF

errorlevel -302 ; No reg is ter in bank er ror; mes sages

errorlevel -312 ; No page or bank mes sages;============================================================; vari ables in PIC RAM;============================================================; De clare vari ables at 2 mem ory lo ca tionsj equ 0x20k equ 0x21de lay equ 0x22 ; De lay count;============================================================; m a i n p r o g r a m;============================================================

org 0 ; start at ad dress 0goto Main

;=============================; space for in ter rupt han dler;=============================;=============================; main pro gram;=============================

org 0x08Main:; Ini tial ize all lines in port C for out put

banksel PORTCclrf PORTCbanksel TRISC ; Pre pare to trisclrf TRISC ; All lines to 0 (out put)

; Set PORT A line 0 as an a log movlw B’00000001’ ; Line 0 is

an a logbanksel ANSELmovwf ANSEL ; Se lect as an a log

; Turn off com para tor

Uni po lar Mo tor Cir cuits and Pro grams 449

Page 471: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

movlw B’00000111’ ; Set ting bits 0, 1, and 2; sets

com para tors off and; Port C IN

pins to dig i talbanksel CMCON0movwf CMCON0

; Tris port A for in putbanksel TRISAmovlw B’00111111’ ; All port A lines for in putclrf TRISAmovwf TRISA

; Con fig ure os cil la tormovlw B’01100001’

; ||| |____ in ter nal clock; |||________ 4 MHz

banksel OSCCONmovwf OSCCON

; Set con ver sion clock to Tad = 8 * Tosc (ADCS = 001)movlw B’00010000’

; |||__________ ADCS bitsbanksel ADCON1movwf ADCON1

;=============================; set ADC hard ware;============================= ; Se lect an a log line (AN0) as the an a log in put; chan nel. Se lect Vcc as the volt age ref er ence.; Left jus tify re sult

movlw B’00000001’; Bitmap:; 0 0 0 0 0 0 0 1; | |___| | |___x___ 1 = turn on ADC; | |___x_x_x_______ 000 = se lect AN0; | x_______________ 0 = volt age ref Vcc; x_________________ 0 = left jus tify

banksel ADCON0movwf ADCON0

; Set default state for 5804 con trol lines, wired as; fol lows:; PORT C BITS ; 5 4 3 2 1 0 De fault; | | | | | |____ Step in put 0; | | | | |_______ Di rec tion 1; | | | |__________ One phase 0; | | |_____________ Half step 1; | |________________ MCLR; |___________________ NOT USED; Note that 5804 En able line is wired to ground

450 Chap ter 17

Page 472: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

banksel PORTCmovlw B’00001010’ ; Half step, ccw di rec tionmovwf PORTC

; Ini tial ize de fault value for de lay vari ablemovlw .100banksel de laymovwf de lay ; To de lay vari able

;================================; Pulse mo tor and de lay;================================PulseAndDelay:; Make sure 5804 Step In line is low be fore strobe; cy cle

banksel PORTCbcf PORTC,0 ; Set low call Pulse ; Lo cal pulse mo tor rou tinecall De lay

;============================; Read speed con trol pot;============================; 5K pot is wired to port A line 0, which has been set

banksel ADCON0 ; Pre pare to sam plebsf ADCON0,GO ; Start op er a tion

Wait4ADC:btfsc ADCON0,GO ; Wait for com ple tiongoto Wait4ADC ; Loop back if not done

;=================================; store and dis play re sult;=================================; At this point dig i tal val ues of ADC op er a tion are; found in the PICs ADRESH and ADRESL reg is ters. ; Pro gram uses the 8 high bits in ADRESH, which are; di vided by 2 by shift ing right one bit. A con stant of; 40 is then added to scale and limit the fast est speed.

banksel STATUSbcf STATUS,C ; Clear carry to shiftbanksel ADRESHrrf ADRESH,w ; Ro tate in w

; Range is now 0 to 128addlw .40 ; Add con stant

; Range is now 40 to 168banksel de lay ; De lay vari ablemovwf de lay

;============================; Read 5804 con trol lines;============================; PORTA bit 4 (wired to tog gle # 1) con trols for ward; or re verse di rec tion by means of PORTC bit 1 (wired

Uni po lar Mo tor Cir cuits and Pro grams 451

Page 473: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; to 5804 di rec tion line on pin 14).banksel PORTAbtfsc PORTA,4 ; Di rec tion con trol switchgoto ReverseRot ; En gage re verse ro ta tion

; At this point ro ta tion is for wardbcf PORTC,1 ; Clear bit `goto HalfStepMode

ReverseRot:bsf PORTC,1 ; Set re verse

HalfStepMode:; PORTA bit 2 (wired to tog gle # 2) se lects half-step; mode by means of PORTC bit 3 (wired to 5804 half-step; line on pin 10).

btfsc PORTA,2 ; Half step mode con trolgoto NoHalfStep ; Dis able half step

; At this point half step is se lectedbsf PORTC,3 ; Set bit goto OnePhaseMode

NoHalfStep:bcf PORTC,3 ; Turn off half step con trol

OnePhaseMode:; PORTA bit 1 (wired to tog gle # 3) se lects one phase; mode by means of PORTC bit 2 (wired to 5804 sin gle; phase line on pin 9).

btfsc PORTA,1 ; One phase mode con trolgoto NoOnePhase ; Dis able sin gle step

; At this point sin gle phase is se lectedbsf PORTC,2 ; Set sin gle phase goto PulseAndDelay

NoOnePhase:bcf PORTC,2 ; Turn off one phasegoto PulseAndDelay

;================================; rou tine to pulse the 5804;================================; Note that 5804 re quires a pos i tive-go ing pulse; there fore the line is held high dur ing the strobe; cy clePulse:

banksel PORTCbsf PORTC,0 ; Bring step line highnopnopnopnopnopnopnop

452 Chap ter 17

Page 474: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

nopnopnopbcf PORTC,0 ; Step line lowre turn

;================================; de lay sub-rou tines;================================De lay:

banksel de laymovf de lay,w ; De lay to w reg is termovwf j ; j = w

Jloop:movwf k ; k = w

Kloop:decfsz k,f ; k = k-1, skip next if zerogoto Kloopdecfsz j,f ; j = j-1, skip next if zerogoto Jloopre turn

end ;END OF PROGRAM

17.4.6 SMU_PIC16F684_INT.asm;============================================================; File: SMU_PIC16F684_INT.asm; Date: De cem ber 9, 2010; Up date: De cem ber 29, 2010; Au thor: Julio Sanchez; Pro ces sor: 16F684A; Ref er ence cir cuit: SMU-PIC16F684-1;; Pro gram De scrip tion:; This is a ver sion SMU_PIC16F684.asm that uses the Timer0; in ter rupt to send pulses to the step per mo tor.; Three tog gle switches wired to ports RA1 to RA3 turn on and; off the di rec tion, half step, and sin gle phase modes on the; 5804.; A 5K po ten ti om e ter on port RA0 pro vides in put to the chip's; ADC. The re sult ing re sis tance value is used to se lect the; de lay rate, which, in turn, sets the mo tor speed.;;===========================; demo board cir cuit ;===========================; Port A lines 0 to 4 trissed for in put:; 0 -----> 5K po ten ti om e ter -- An a log in put

Uni po lar Mo tor Cir cuits and Pro grams 453

Page 475: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; 1 -----> Tog gle switch 3 |; 2 -----> Tog gle switch 2 |-- dig i tal in put; 3 -----> MCLR func tion | ; 4 -----> Tog gle switch 4 |; 5 -----> NOT WIRED; Port C lines 0 to 3 trissed for out put and wired; as fol lows:; PIC 5804; RC0 -----> pin 11 - Step in put; RC1 -----> pin 14 - Di rec tion; RC2 -----> pin 9 - One phase; RC3 -----> pin 10 - Half Step; Set tings for phase con trol:; RC3 (half step) RC2 (one phase); 0 0 = two phase; 0 1 = wave drive; 1 0 = half step; 1 1 = step in hibit; Tog gle switch con trols; PORTC line SW ACTION; 1 TS3 Di rec tion (for ward/re verse); Set PORTC to: xxxx xx0x; or: xxxx xx1x; 2 TS2 One phase; Set PORTC to: xxxx x0xx; or: xxxx x1xx; 3 TS1 One half step; Set PORTC to: xxxx 0xxx; or: xxxx 1xxx ;=========================; setup and con fig u ra tion;=========================

pro ces sor 16f684in clude <p16f684.inc>__CONFIG _MCLRE_OFF & _CP_OFF & _CPD_OFF & _BOD_OFF &

_WDT_OFF & _PWRTE_ON & _INTOSCIO & _FCMEN_OFF & _IESO_OFF

errorlevel -302 ; No reg is ter in bank er ror mes sageserrorlevel -312 ; No page or bank mes sages

;============================================================; vari ables in PIC RAM;============================================================; De clare vari ables at 2 mem ory lo ca tionsj equ 0x20k equ 0x21de lay equ 0x22 ; De lay countold_w equ 0x23 ; Con text sav ing

454 Chap ter 17

Page 476: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

old_STATUS equ 0x24 ; Idemit er a tion equ 0x25 ; It er a tion coun ter used by

; in ter rupt han dler;============================================================; m a i n p r o g r a m;============================================================

org 0 ; start at ad dress 0goto Main

;=============================; space for in ter rupt han dler;=============================

org 0x04goto IntServ

;=============================; main pro gram;=============================Main:; Ini tial ize all lines in port C for out put

banksel PORTCclrf PORTCbanksel TRISC ; Pre pare to trisclrf TRISC ; All lines to 0 (out put)

; Set PORT A line 0 as an a log movlw B'00000001' ; Line 0 is an a logbanksel ANSELmovwf ANSEL ; Se lect as an a log

; Turn off com para tormovlw B'00000111' ; Set ting bits 0, 1, and 2

; sets com para tors off and; Port C IN pins to dig i tal

banksel CMCON0movwf CMCON0

; Tris port A for in putbanksel TRISAmovlw B'00111111' ; All port A lines for in putclrf TRISAmovwf TRISA

; Con fig ure os cil la tormovlw B'01100001'

; ||| |____ in ter nal clock; ||________ 4 MHz

banksel OSCCONmovwf OSCCON

; Set con ver sion clock to Tad = 8 * Tosc (ADCS = 001)movlw B'00010000'

; |||__________ ADCS bitsbanksel ADCON1movwf ADCON1

Uni po lar Mo tor Cir cuits and Pro grams 455

Page 477: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

;=============================; setup for in ter rupt;=============================; Clear ex ter nal in ter rupt flag (INTF = bit 1)

banksel INTCONbcf INTCON,INTF ; Clear flag

; En able global in ter rupts (GIE = bit 7); En able RB0 in ter rupt (inte = bit 4)

bsf INTCON,GIE ; En able global int (bit 7)bsf INTCON,T0IE ; En able TMR0 over flow in ter rupt

;============================; Set up the OPTION reg is ter;============================

movlw b'11010000'; 7 6 5 4 3 2 1 0 <= OPTION bits; | | | | | |__|__|_____ PS2-PS0 (prescaler bits); | | | | | Val ues for Timer0; | | | | | *000 = 1:2 001 = 1:4; | | | | | 010 = 1:8 011 = 1:16; | | | | | 100 = 1:32 101 = 1:64; | | | | | 110 = 1:128 111 = 1:256; | | | | |______________ PSA (prescaler as sign); | | | | 1 = to WDT; | | | | *0 = to Timer0; | | | |_________________ TOSE (Timer0 edge se lect); | | | 0 = in cre ment on low-to-high; | | | *1 = in cre ment on high-to-low; | | |____________________ TOCS (TMR0 clock source); | | *0 = in ter nal clock; | | 1 = RA4/TOCKI bit source; | |_______________________ INTEDG (Edge se lect); | *0 = fall ing edge; |__________________________ RBPU (Pullup en able); 0 = en abled; *1 = dis abled

banksel OPTION_REGmovwf OPTION_REG ; Copy w to OPTION

;=============================; set ADC hard ware;============================= ; Se lect an a log line (AN0) as the an a log in put; chan nel. Se lect Vcc as the volt age ref er ence.; Left jus tify re sult

movlw B'00000001'; Bitmap:; 0 0 0 0 0 0 0 1; | |___| | |___x___ 1 = turn on ADC; | |___x_x_x_______ 000 = se lect AN0; | x_______________ 0 = volt age ref Vcc

456 Chap ter 17

Page 478: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; x_________________ 0 = left jus tifybanksel ADCON0movwf ADCON0

; Set default state for 5804 con trol lines, wired as; fol lows:; PORT C BITS ; 5 4 3 2 1 0 De fault; | | | | | |____ Step in put 0; | | | | |_______ Di rec tion 1; | | | |__________ One phase 0; | | |_____________ Half step 1; | |________________ MCLR; |___________________ NOT USED; Note that 5804 En able line is wired to ground

banksel PORTCmovlw B'00001010' ; Half step, ccw di rec tionmovwf PORTC

; Ini tial ize de fault value for de lay vari ablemovlw .100banksel de laymovwf de lay ; To de lay vari ablemovwf it er a tion ; To it er a tion coun ter

;========================================================; com mand mon i tor ing;========================================================;============================; Read speed con trol pot;============================; 5K pot is wired to port A line 0, which has been set; for an a log in put.ReadInputs:

banksel ADCON0 ; Pre pare to sam plebsf ADCON0,GO ; Start op er a tion

Wait4ADC:btfsc ADCON0,GO ; Wait for com ple tiongoto Wait4ADC ; Loop back if not done

;============================; store value in vari able;============================; At this point dig i tal val ues of ADC op er a tion are; found in the PICs ADRESH and ADRESL reg is ters. ; Pro gram uses the 8 high bits in ADRESH, which are; di vided by 2 by shift ing right one bit. A con stant of; 40 is then added to scale and limit the fast est speed.

banksel STATUSbcf STATUS,C ; Clear carry to shiftbanksel ADRESH

Uni po lar Mo tor Cir cuits and Pro grams 457

Page 479: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

rrf ADRESH,w ; Ro tate in w; Range is now 0 to 128

addlw .40 ; Add con stant; Range is now 40 to 168

banksel de lay ; De lay vari ablemovwf de lay

;============================; Read 5804 con trol lines;============================; PORTA bit 4 (wired to tog gle # 1) con trols for ward; or re verse di rec tion by means of PORTC bit 1 (wired; to 5804 di rec tion line on pin 14).

banksel PORTAbtfsc PORTA,4 ; Di rec tion con trol switchgoto ReverseRot ; En gage re verse ro ta tion

; At this point ro ta tion is for wardbcf PORTC,1 ; Clear bit goto HalfStepMode

ReverseRot:bsf PORTC,1 ; Set re verse

HalfStepMode:; PORTA bit 2 (wired to tog gle # 2) se lects half-step; mode by means of PORTC bit 3 (wired to 5804 half-step; line on pin 10).

btfsc PORTA,2 ; Half step mode con trolgoto NoHalfStep ; Dis able half step

; At this point half step is se lectedbsf PORTC,3 ; Set bit goto OnePhaseMode

NoHalfStep:bcf PORTC,3 ; Turn off half step con trol

OnePhaseMode:; PORTA bit 1 (wired to tog gle # 3) se lects one phase; mode by means of PORTC bit 2 (wired to 5804 sin gle; phase line on pin 9).

btfsc PORTA,1 ; One phase mode con trolgoto NoOnePhase ; Dis able sin gle step

; At this point sin gle phase is se lectedbsf PORTC,2 ; Set sin gle phase goto ReadInputs

NoOnePhase:bcf PORTC,2 ; Turn off one phasegoto ReadInputs

;================================; rou tine to pulse the 5804;================================; Note that 5804 re quires a pos i tive-go ing pulse; there fore the line is held high dur ing the strobe

458 Chap ter 17

Page 480: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; cy clePulse:

banksel PORTCbsf PORTC,0 ; Bring step line highnopnopnopnopnopnopnopnopnopnopbcf PORTC,0 ; Step line lowre turn

;=======================================================; In ter rupt Ser vice Rou tine;=======================================================; Ser vice rou tine re ceives con trol when the timer; reg is ter TMR0 over flows, that is, when 256 timer beats; have elapsedIntServ:; First test if source is a Timer0 in ter rupt

banksel INTCONbtfss INTCON,T0IF ; T0IF is Timer0 in ter ruptgoto notTOIF ; Go if not RB0 or i gin

; If so clear the timer in ter rupt flag so that count con tin uesbcf INTCON,T0IF ; Clear in ter rupt flag

; Save con textbanksel old_wmovwf old_w ; Save w reg is terswapf STATUS,w ; STATUS to wmovwf old_STATUS ; Save STATUS

;=========================; in ter rupt ac tion;=========================; Dec re ment the it er a tion coun ter. Exit if not zero

banksel it er a tiondecfsz it er a tion,fgoto exitISR ; Con tinue if coun ter not zero

; At this point the de lay count has ex pired so the pro grammed; time has elapsed.; First re set the it er a tion coun ter

movf de lay,w ; Read de laymovwf it er a tion ; Re set it er a tion coun ter

;================================

Uni po lar Mo tor Cir cuits and Pro grams 459

Page 481: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; Pulse mo tor and de lay;================================; Make sure 5804 Step In line is low be fore strobe; cy cle

banksel PORTCbcf PORTC,0 ; Set low call Pulse ; Lo cal pulse mo tor rou tine

;=========================; exit ISR;=========================exitISR:; Re store con text

banksel old_STATUSswapf old_STATUS,w ; Saved STATUS to wmovfw STATUS ; To STATUS reg is terswapf old_w,f ; Swap file reg is ter in it selfswapf old_w,w ; re-swap back to w

; Re set,in ter ruptnotTOIF:

retfieend ;END OF PROGRAM

17.4.7 SMU_POSITION.asm;============================================================; File: SMU_POSITION.asm; Date: Jan u ary 16, 2011; Up date: Jan u ary 18, 2011; Au thors: Sanchez and Can ton; Pro ces sor: 16F684A; Ref er ence cir cuit: SMU-PIC16F684-1;; Pro gram De scrip tion:; Pro gram to drive a uni po lar step per mo tor in half step; mode, with a 16F684 PIC con trol ling a UCN5804 driver.; A 5K po ten ti om e ter on port RA0 pro vides in put to the chip's; ADC. The re sult ing re sis tance value is used to turn the; mo tor a spe cific num ber of steps. Pro gram op er ates as; fol lows:; 1. The ini tial po si tion of the pot arm is stored as the; lo cal ref er ence point (LRP).; 2. The pot value is read by code and des ig nated as new; ref er ence point (NRP).; 3. NRP and LRP are com pared.; If they are the same, no ac tion takes place.; 3. If the NRP is greater than the LRP, then the dif fer ence; is the amount of steps the mo tor is turned to the; right (clock wise).

460 Chap ter 17

Page 482: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; 5. If the NRP is smaller than LRP, then the dif fer ence is; the num ber of steps the mo tor is turned to the left; (coun ter clock wise).; 6. LRP is now set to NRP.; Pro cess ing con tin ues at STEP 2.;;===========================; demo board cir cuit ;===========================; Port A lines 0 to 4 trissed for in put:; 0 ----------> 5K po ten ti om e ter -- An a log in put; 1 to 4 -----> NOT WIRED; Port C lines 0 to 3 trissed for out put and wired; as fol lows:; PIC 5804; RC0 -----> pin 11 - Step in put; RC1 -----> pin 14 - Di rec tion;; Set tings for phase con trol:; RC3 (half step) RC2 (one phase); 0 0 = two phase; 0 1 = wave drive; 1 0 = half step; 1 1 = step in hibit ;=========================; setup and con fig u ra tion;=========================

pro ces sor 16f684in clude <p16f684.inc>__CONFIG _MCLRE_OFF & _CP_OFF & _CPD_OFF & _BOD_OFF &

_WDT_OFF & _PWRTE_ON & _INTOSCIO & _FCMEN_OFF & _IESO_OFF

errorlevel -302 ; No reg is ter in bank er ror mes sageserrorlevel -312 ; No page or bank mes sages

;============================================================; vari ables in PIC RAM;============================================================; De clare vari ables at 2 mem ory lo ca tionsj equ 0x20k equ 0x21de lay equ 0x22 ; De lay countlrp equ 0x23nrp equ 0x24ticks equ 0x25;============================================================; m a i n p r o g r a m

Uni po lar Mo tor Cir cuits and Pro grams 461

Page 483: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

;============================================================org 0 ; start at ad dress 0goto Main

;=============================; space for in ter rupt han dler;=============================;=============================; main pro gram;=============================

org 0x08Main:; Ini tial ize all lines in port C for out put

banksel PORTCclrf PORTCbanksel TRISC ; Pre pare to trisclrf TRISC ; All lines to 0 (out put)

; Set PORT A line 0 as an a log movlw B'00000001' ; Line 0 is an a logbanksel ANSELmovwf ANSEL ; Se lect as an a log

; Turn off com para tormovlw B'00000111' ; Set ting bits 0, 1, and 2

; sets com para tors off and; Port C IN pins to dig i tal

banksel CMCON0movwf CMCON0

; Tris port A for in putbanksel TRISAmovlw B'00111111' ; All port A lines for in putclrf TRISAmovwf TRISA

; Con fig ure os cil la tormovlw B'01100001'

; ||| |____ in ter nal clock; |||________ 4 MHz

banksel OSCCONmovwf OSCCON

; Set con ver sion clock to Tad = 8 * Tosc (ADCS = 001)movlw B'00010000'

; |||__________ ADCS bitsbanksel ADCON1movwf ADCON1

;=============================; set ADC hard ware;============================= ; Se lect an a log line (AN0) as the an a log in put; chan nel. Se lect Vcc as the volt age ref er ence.; Left jus tify re sult

462 Chap ter 17

Page 484: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

movlw B'00000001'; Bitmap:; 0 0 0 0 0 0 0 1; | |___| | |___x___ 1 = turn on ADC; | |___x_x_x_______ 000 = se lect AN0; | x_______________ 0 = volt age ref Vcc; x_________________ 0 = left-jus tify

banksel ADCON0movwf ADCON0

; Set default state for 5804 con trol lines, wired as; fol lows:; PORT C BITS ; 5 4 3 2 1 0 De fault; | | | | | |____ Step in put 0; | | | | |_______ Di rec tion 1; | | | |__________ One phase 0; | | |_____________ Half step 1; | |________________ MCLR; |___________________ NOT USED; Note that 5804 En able line is wired to ground

banksel PORTCmovlw B'00001010' ; Half step, ccw di rec tionmovwf PORTC

; Ini tial ize de fault value for de lay vari ablemovlw .40banksel de laymovwf de lay ; To de lay vari able

; Read ini tial pot po si tion and storecall ReadPot ; Value is re turned in wbanksel nrpmovwf nrp ; new ref er ence po si tionmovwf lrp ; lo cal ref er ence po si tion

;================================; Read pot and pulse mo tor;================================ReadPotAndMove:

call De lay ; Wait to up datecall ReadPotbanksel nrpmovwf nrp ; Store re sult

; Com pare new value with old value by sub trac tion.; Sub trac tion per forms w (new ref er ence po si tion); mi nus lo cal ref er ence po si tion (old value).; If Z flag set nrp == lrp; If carry flag set lrp < nrp

subwf lrp,w ; Sub tract w (nrp) from lrpbanksel STATUSbtfsc STATUS,Z ; Test zero flag

Uni po lar Mo tor Cir cuits and Pro grams 463

Page 485: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

goto NoChange ; Go if Z flag is set; At this point nrp not equal to lrp; Test the carry flag to de ter mine if lrp < nrp

btfss STATUS,C ; Is C flag set?goto MoveLeft ; Go if new big ger than oldgoto MoveRight

;============================; move left;============================; Move left by dif fer ence be tween new and old read ings; First ob tain ab so lute value of dif fer ence. At this point; lrp > nrpMoveLeft:

banksel lrpmovf lrp,w ; Get lrpsubwf nrp,w ; old (in w) mi nus new banksel ticksmovwf ticks ; Store dif fer ence

; Set con trol ler to re verse ro ta tionbanksel PORTCbsf PORTC,1 ; Set re verse

TickLeft:banksel PORTCbcf PORTC,0 ; Set low call Pulsecall De laybanksel ticks ; Coun terdecfsz ticks,fgoto TickLeft ; Loopgoto Up date

;==============================; move right;==============================; Move to the right by num ber of ticks in wMoveRight:

banksel ticksmovwf ticks ; Store dif fer ence

; Set for ward ro ta tionbanksel PORTCbcf PORTC,1 ; Clear bit

TickRight:banksel PORTCbcf PORTC,0 ; Set low call Pulsecall De laybanksel ticks ; Coun terdecfsz ticks,fgoto T ickRight ; Loop

464 Chap ter 17

Page 486: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

;==============================; Up date po si tion con trol;==============================Up date:

banksel nrpmovf nrp,w ; New value to wmovwf lrp

NoChange:goto ReadPotAndMove

;================================; rou tine to pulse the 5804;================================; Note that 5804 re quires a pos i tive-go ing pulse; there fore the line is held high dur ing the strobe; cy clePulse:

banksel PORTCbsf PORTC,0 ; Bring step line highnopnopnopnopnopnopnopnopnopnopbcf PORTC,0 ; Step line lowre turn

;================================; de lay sub-rou tines;================================De lay:

banksel de laymovf de lay,w ; De lay to w reg is termovwf j ; j = w

Jloop:movwf k ; k = w

Kloop:decfsz k,f ; k = k-1, skip next if zerogoto Kloopdecfsz j,f ; j = j-1, skip next if zerogoto Jloopre turn

Uni po lar Mo tor Cir cuits and Pro grams 465

Page 487: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

;=========================================================

; Lo cal pro ce dure to read speed potentiometr on board

;=========================================================

ReadPot:

; 5K pot is wired to port A line 0, which has been set for

; dig i tal in put

banksel ADCON0 ; Pre pare to sam ple

bsf ADCON0,GO ; Start op er a tion

Wait4ADC:

btfsc ADCON0,GO ; Wait for com ple tion

goto Wait4ADC ; Loop back if not done

;=================================

; store re sult

;=================================

; At this point dig i tal val ues of ADC op er a tion are

; found in the PICs ADRESH and ADRESL reg is ters.

; Pro gram uses the 8 high bits in ADRESH.

banksel ADRESH

movf ADRESH,w ; Value to w

re turn

end ;END OF PROGRAM

466 Chap ter 17

Page 488: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Chap ter 18

Con stant-Volt age Bi po lar Mo tor Con trols

18.1 Uni po lar ver sus Bi po larIn Chap ter 15 we dis cussed the hard ware char ac ter is tics of bi po lar and uni po lar mo -tors. From the cir cuit de signer’s view point, the fun da men tal dif fer ence be tween these mo tor types re lates to the fact that bi po lar mo tors con tain a sin gle wind ing per phase.Be cause there is a sin gle wind ing, the cur rent flow must be re versed in or der for thero tor to turn. An other con se quence of the bi po lar mo tor struc ture is that the en tirewind ing is ac ti vated dur ing each cy cle, while only half the wind ing is ac tive in the uni -po lar de sign. Con se quently, a bi po lar mo tor gen er ates more torque than a uni po larmo tor of the same size.

The bi po lar de sign also has some draw backs. One of them is that, in or der to re -verse cur rent flow in the wind ings, bi po lar mo tors re quire more com plex con trolcir cuitry. The H bridge (dis cussed in Chap ter 16) is a com mon cir cuit com po nentthat is used for this pur pose. There is lit tle dif fer ence in cost be tween uni po lar andbi po lar mo tors of the same weight. How ever, this dif fer ence is more sig nif i cant ifthe in creased torque and ef fi ciency of the bi po lar de sign is taken into ac count. A fi -nal con sid er ation in choos ing be tween uni po lar and bi po lar mo tors is that a uni po -lar mo tor can be used as a bi po lar mo tor by ig nor ing the cen ter taps in the coils. Insummary, the differences can be listed as follows:

• Bi po lar motors re quire more com plex drive cir cuitry than unipolar.

• Bi po lar motors pro duce higher torque than unipolar motors of the same weight.

• There is not much dif fer ence in cost be tween unipolar or bi po lar mo tors of the same weight.

• Stan dard unipolar motors can be used in bi po lar cir cuits.

18.1.1 Bi po lar Drive Cir cuitsBi po lar mo tor cir cuits re quire chang ing cur rent po lar ity dur ing step ping op er a tionsand that this is usu ally ac com plished with an H bridge of one type or an other. We mustnow add that bi po lar step per mo tor per for mance is de pend ent on the drive cir cuit to ahigh de gree. Re call that higher speeds are achieved by re vers ing the stator poles more

467

Page 489: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

quickly, which also re sults in a gain in torque. How ever, in creas ing the re ver sal rate ofthe poles also in creases in duc tance in the wir ing. Here again, the higher in duc tancecan be over come by in creas ing volt age, but this re quires lim it ing the cur rent at thesehigher volt ages.

These con sid er ations have led to two dif fer ent types of bi po lar step per mo tor cir -cuits: one in which the voltage is held con stant and an other one in which thecurrent is held con stant. The con stant-voltage type is some times known as the L/Rdesign. Here L rep re sents the wind ing in duc tance and R the re sis tance. Con stant-current cir cuit types are re ferred to as chop per cir cuits. In chop per drives, thecurrent in each wind ing is held ap prox i mately con stant by vary ing the voltage. Ini -tially, a high voltage is ap plied to each wind ing, which causes the current to risequickly. When the current reaches a spec i fied limit, the voltage is turned off, orchopped. The current now drops un til it reaches an other low limit, in which casethe voltage is turned back on. Chop per drives re quire ad di tional com po nents in or -der to mea sure the wind ing current and to con trol switch ing, but the pay off is thatstep per mo tors can be driven at higher speeds and torques than with con stant-voltage cir cuits.

The con trol and trans la tor stages in many cir cuits de scribed in Chap ter 17, in thecon text of uni po lar mo tors, are com pat i ble with the bi po lar driv ers de scribed in this chap ter. For ex am ple, the con trol and trans la tor stage of cir cuit SMU-PIC16F84-1can be cou pled with sev eral driver stages of bi po lar cir cuits shown in this chap ter.Also con sider that in this chap ter we only dis cuss bi po lar cir cuits of the con stant-volt age type. Chop per cir cuits are pre sented in Chapter 19, together withmicrostepping.

18.2 Sim ple, L293 Bi po lar Cir cuitIn Chap ter 16 we pre sented the L293 IC, which is a two H-bridge, four-chan nel driverthat in cludes snub ber di odes. The L293 can drive 1.2 A per chan nel; it is suit able fordriv ing NEMA teen-size step per mo tors. The L293, and equiv a lent ICs, are lit tle morethan a dou ble H-bridge and they re quire a sep a rate trans la tor to pro vide the mo tor coil se quence via four in put lines. Two en able lines are held high by wir ing to the pos i tivepower sup ply. These lines can also be wired to the trans la tor and used to turn the mo -tor on and off. The four out put lines from the L293 are wired to the mo tor coils. Fourground lines are lo cated on the cen ter of the IC. This de sign fa cil i tates a large groundon the PCB, which serves as a heat sink

Fig ure 18-1 is a sim ple bi po lar cir cuit that uses a microcontroller trans la tor andan L293D driver IC. The SMB-L293D-1 cir cuit is the bi po lar ver sion of the cir cuitSMU-PIC16F84-1 pre sented in Chap ter 17 (see Fig ure 17-3).

The cir cuit in Fig ure 18-1 uses a microcontroller-based trans la tor. In put is pro -vided by means of four pushbutton switches, and mo tor speed, di rec tion, and se -quence mode are de ter mined in soft ware. Al ter na tively, the cir cuit can be eas ilymod i fied to read other in put de vices, such as tog gle switches or po ten ti om eters.These in puts can then be used to con trol mo tor op er a tion.

468 Chap ter 18

Page 490: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 18-1 L293D-Based Bi po lar Mo tor Driver.

Con stant-Volt age Bi po lar Mo tor Con trols 469

+5V

MotorSupply

L2

93

D

TO

MO

TO

R

ENABLE 1

INPUT 1

OUTPUT 1

GND

GND

OUTPUT 2

INPUT 2

Vm

1

2

3

4

5

6

7

8

16

15

14

13

12

11

10

9

Vs

INPUT 4

OUTPUT 4

GND

GND

OUTPUT 3

INPUT 3

ENABLE 2

+5V

R=4.7K x 2

CIRCUIT: SMB-L293D-1CODE: SMB_L293D.asm

RB0

RB1

RB2

RB3Q1

Q4

Q2

Q3

Osc

+5V

R=

10

K

R=

10

K

R=

10

K

R=

10

K

R=

10

K

RESET

16

F8

4A

+5V

RA2

RA3

RA4/TOCKI

MCLR

Vss

RB0/INT

RB1

RB2

RB3

1

2

3

4

5

6

7

8

9

18

17

16

15

14

13

12

11

10

RA1

RA0

OSC1

OSC2

Vdd

RB7

RB6

RB5

RB4

PB0

PB1

Fn1

Fn2

Fn3

Fn4

PB2

PB3

CONTROL AND TRANSLATOR STAGE

Page 491: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

470 Chap ter 18

Fig ure 18-2 Bi po lar Mo tor Driver with L297 and L293 ICs.

+5V

L2

97

SYNC

GND

HOME

Out A

INH 1

Out B

Out C

INH 2

Out D

ENABLE

1

2

3

4

5

6

7

8

9

10

20

19

18

17

16

15

14

13

12

11

RESET

Half/full

CLOCK

CW/CCW

OSC

Vref

SENS 1

SENS 2

Vs

CTRL

+5V

R=10K

CIRCUIT: SMB-L297-293D-2CODE: SMB_297-293D.asm

CIRCUIT: SMB-L297-293D-1CODE: SMB_297-293D.asm

Fn1

Fn2

Fn2

Fn3+5V

+5V

+Vm

L2

93

D

ENABLE 1

INPUT 1

OUTPUT 1

GND

GND

OUTPUT 2

INPUT 2

Vm

1

2

3

4

5

6

7

8

16

15

14

13

12

11

10

9

Vs

INPUT 4

OUTPUT 4

GND

GND

OUTPUT 3

INPUT 3

ENABLE 2

R=

4.7

K x 2

bipolarsteppermotor

DRIVER STAGE

TRANSLATOR AND CONTROL STAGE

16

F8

4A

Osc

+5V

+5V

R=

10

K x 4

R=

10

K

R=

10

K

RA2

RA3

RA4/TOCKI

MCLR

Vss

RB0/INT

RB1

RB2

RB3

1

2

3

4

5

6

7

8

9

18

17

16

15

14

13

12

11

10

RA1

RA0

OSC1

OSC2

Vdd

RB7

RB6

RB5

RB4

RESET

PB 1PB 2

SW 1

SW 2

SW 3DIP SW

Fn2

PB1

PB2SW3

SW1

SW2

Fn2

Fn3 Fn4

Fn5

Fn6

Fn7Fn1

Page 492: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

18.2.1 L297- and L293-Based Cir cuit

For cir cuits in which the mi cro pro ces sor is over loaded, or to im ple ment ad di tional orfiner mo tor con trols, it is pos si ble to in sert an L297 mo tor driver IC be tween the trans -la tor and the H-bridge. The L297 hard ware is de scribed in Chap ter 16. Al though thischip is some times em ployed in sim ple cir cuits, such as the one pres ently de scribed, itis most use ful when the cir cuit takes ad van tage of all the chip’s ca pa bil i ties. For ex am -ple, the L297 can be con fig ured in a “chop per” scheme, de scribed pre vi ously. In Chap -ter 19 we de velop a cir cuit that uses the L297 in this man ner. The cir cuit de signershould eval u ate us ing the L297, or sim i lar ICs, in con stant-voltage cir cuits where most of the IC’s functionalities are un used. Fig ure 18-2 shows a sim ple cir cuit that uses theL293 and L297 ICs.

Note that many of the L297 pins are left float ing in cir cuit SMB-L297-293D-2.These pins cor re spond to fea tures and functionalities of the L297 that are not usedin the cir cuit.

18.2.2 Min i mal L297- and L298-Based Cir cuit

The ma jor lim i ta tion of the L293 IC is its lim i ta tion of 1.2 A peak out put cur rent perchan nel. The L298, on the other hand, al lows up to 3.5 A per chan nel, which tri ples thecur rent-car ry ing ca pac ity of the L293. A sim ple L297/L298 cir cuit is shown in Fig ure18-3.

Cir cuit SMB-L297-298-1 shown in Fig ure 18-3 uses few of the fea tures of both theL297 and the L298. The prin ci pal char ac ter is tic of this cir cuit is its higher ca pac ityas the L298 al lows an op er at ing sup ply volt age of up to 46V and 4 A. The L298 IC in -cludes ca pa bil i ties not used in this cir cuit, such as sens ing the out put volt age. Thisfea ture can be used in in put volt age chop ping, which is im ple mented in cir cuits de -ve l oped in Chap ter 19 . Be cause chop p ing i s not sup por ted by c i r cu i tSMB-L297-298-1, the SENSE A and SENSE B lines of the L298 are wired to ground.The L298 is also used in driv ing relays, solenoids, and DC motors.

Ad di tional tog gle switches in the con trol and trans la tor stage could be used tocon trol other modes or stages. In cir cuit SMB-l297-298-1, one tog gle switch con trolsdi rec tion, an other one se lects be tween full- and half-step modes, a third one iswired to the L297 ENABLE line and al lows turn ing the mo tor on and off. An ad di -tional tog gle switch could be added to the cir cuit to pro vide se lect ing be tween highand low speeds. Be cause there are sev eral un used ports in the trans la tor, it is easyto add more in put sources in or der to con trol other fea tures of the L297. Also notethat the ENABLE, RESET, and both INH lines of the L297 are ac tive low. In the cir -cuit these lines are dis abled ei ther by hold ing them high or by leav ing them float ing.Sim i larly un used lines in the L298 are ei ther grounded or held high with 4.7Kpull-ups. Most of these lines are put to good use in the more pow er ful cir cuits de vel -oped in Chap ter 19.

18.3 Dem on stra tion Pro gramsThe pro grams listed in the fol low ing sec tion dem on strate the pro gram ming dis cussedin this chap ter.

Con stant-Volt age Bi po lar Mo tor Con trols 471

Page 493: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

472 Chap ter 18

Fig ure 18-3 Bi po lar Mo tor Cir cuit with L297 and L298 Driv ers.

bipolarsteppermotor

DRIVER STAGE

+5V

+5V

MOTORSUPPLY

VOLTAGE

L2

97

L2

98

SYNC

GND

HOME

Out A

INH 1

Out B

Out C

INH 2

Out D

ENABLE

1

2

3

4

5

6

7

8

9

10

15

13

11

9

7

5

3

1

14

12

10

8

6

4

2

20

19

18

17

16

15

14

13

12

11

RESET

Half/full

STEP

DIR

OSC

Vref

SENS 1

SENS 2

Vs

CTRL

SENSE B

OUT 3

ENABLE B

Vs

IN 2

IN 1

OUT 2

SENSE A

OUT 4

IN 4

IN 3

GND

ENABLE A

Vm

OUT 1

+5V+5V

R=4.7K

R=4.7K

CIRCUIT: SMB-L297-298-1 CODE: SMB_297_298.asm

Fn1

Fn4

Fn3

Fn2

0.1uF

470 uF

Diodes x 8fast 2A

+

OUTB

OUTA

OUTD

OUTC

16

F8

4A

Osc

+5V

+5V

R=

10

K x

4

RA2

RA3

RA4/TOCKI

MCLR

Vss

RB0/INT

RB1

RB2

RB3

1

2

3

4

5

6

7

8

9

18

17

16

15

14

13

12

11

10

RA1

RA0

OSC1

OSC2

Vdd

RB7

RB6

RB5

RB4

RESET

TOGGLESWITCHBANK B

Fn1

TB3

TB1

TB2

Fn2

Fn3

Fn4

CONTROL AND TRANSLATOR STAGE

Page 494: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Con stant-Volt age Bi po lar Mo tor Con trols 473

18.3.1 SMB_L293D.asmThe program SMB_L293D.asm, listed be low and in this book's soft ware re source, drives a bi po lar step per mo tor in a one-half step mode. The pro gram uses a lookup ta -ble for the se quence codes. Two pushbutton switches, wired to ports A3 and A2, ac ti -vate slow ro ta tion in the for ward or re verse di rec tion. Two other pushbuttons, wiredto ports A0 and A1, con trol slow and fast ro ta tion. Code uses an ac cess code ta ble witha pointer, that is ei ther in cre mented or dec re ment ed ac cord ing to the se lected di rec -tion. Fast and slow ex e cu tion are de ter mined by a lo cal vari able.

;============================================================; File: SMB_L293D.asm; Date: No vem ber 12, 2010; Up date: Jan u ary 3, 2011; Au thors: Sanchez and Can ton; Pro ces sor: 16F84A; Other ICs: L293D bi po lar step per mo tor con trol ler ; Ref er ence cir cuit: SMB-L293D-1;; Pro gram De scrip tion:; Pro gram to drive a bi po lar step per mo tor in a one-half step; mode with a 16F84 PIC and an L293D mo tor driver.; Pro gram uses a lookup ta ble for the se quence codes.; Pushbuttons wired to ports A3 and A2 ac ti vate slow ro ta tion; in for ward and re verse di rec tion. Pushbuttons wired to ports; A0 and A1 per form like wise for fast ro ta tion.; Code uses a ac cess code ta ble with a pointer, that is ei ther; in cre mented or dec re ment ed ac cord ing to the se lected; di rec tion.; This en sures that re verses in ro ta tion are ex e cuted smoothly.; Fast and slow ex e cu tion are de ter mined by the value of a lo cal; vari able read by the de lay rou tine. ;===========================; demo board cir cuit ;===========================; Port A lines 0 to 3 trissed for in put:; 0 -----> Push but ton switch A, ac tive low; 1 -----> Push but ton switch B, ac tive low; 2 -----> Push but ton switch C, ac tive low; 3 -----> Push but ton switch D, ac tive low; Port B lines 0 to 3 trissed for out put and wired; as fol lows:; RB0 -----> A1 mo tor wind ing; RB1 -----> A2 mo tor wind ing; RB2 -----> B1 mo tor wind ing; RB3 -----> B2 mo tor wind ing ;=========================; setup and con fig u ra tion

Page 495: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

;=========================pro ces sor 16f84Ain clude <p16f84A.inc>__config _XT_OSC & _WDT_OFF & _PWRTE_ON & _CP_OFFerrorlevel -302

;============================================================; vari ables in PIC RAM;============================================================; De clare vari ables at 2 mem ory lo ca tionsj equ 0x0ck equ 0x0dthis_cy cle equ 0x0e ; Cur rent cy cle coun terdi rec tion equ 0x0f ; Di rec tion con trol

; 0 = for ward; 1 = re verse

bounce equ 0x10 ; Debounce coun terde lay equ 0x11 ; De lay coun ter;============================================================; m a i n p r o g r a m;============================================================

org 0 ; start at ad dress 0goto Main

;=============================; space for in ter rupt han dler;=============================

org 0x08;===================================; lookup ta ble for mo tor;===================================; Bi po lar step per mo tors re quire the fol low ing one-half; step drive se quence for clock wise ro ta tion:; | w i n d i n g s | ; STEP A1 A2 B1 B2 BIN ; 1 OFF ON OFF ON 0101; 2 OFF ON OFF OFF 0100; 3 OFF ON ON OFF 0110; 4 OFF OFF ON OFF 0010 ; 5 ON OFF ON OFF 1010; 6 ON OFF OFF OFF 1000; 7 ON OFF OFF ON 1001; 8 OFF OFF OFF ON 0001; Ta ble is placed low in mem ory to avoid page over laps.;CodeTable

addwf PCL,f ; Add w to pro gram coun terretlw B'00000101' ; cy cle = 0retlw B'00000100' ; 1retlw B'00000110' ; 2

474 Chap ter 18

Page 496: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

retlw B'00000010' ; 3retlw B'00001010' ; 4retlw B'00001000' ; 5retlw B'00001001' ; 6retlw B'00000001' ; 7retlw B'00000000' ; Ta ble ter mi na tor

;=============================; main pro gram;=============================Main:; Tris PORT A for in put

movlw B'00011111' ; w = 00011111 bi narytris PORTA ; Set up port A for in put

; Ini tial ize all line in port B for out putmovlw B'00000000' ; w = 00000000 bi narytris PORTB ; Set up port B for out putclrf PORTB ; Clear all lines

; Ini tial ize con trol vari ablesclrf this_cy cleclrf di rec tion ; As sume for ward di rec tionmovlw .100 ; Ini tial de lay for fastmovwf de lay ; To vari able

;=============================; read and debounce PORTA; lines 0 to 3;=============================; Switches are ac tive low, so changes in di rec tion take place; if port line is clear. Soft ware debouncing is used to make; sure that spu ri ous switch reads are ig nored. TestPortA:; First read and debounce PORTA-3

movlw .10 ; Coun termovwf bounce

Wait43:btfsc PORTA,3goto No3Action ; Go if bit is setdecfsz bounce,f ; Dec re ment coun tergoto Wait43

; At this point switch held zero for 10 testsclrf di rec tion ; 0 is foward on

; di rec tion switchmovlw . 100 ; Slow de lay ratemovwf de lay ; To de lay coun tergoto OneTick ; Tick mo tor

;=============================; read and debounce PORTA-2;=============================

Con stant-Volt age Bi po lar Mo tor Con trols 475

Page 497: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

No3Action:movlw .10 ; Coun termovwf bounce

Wait42:btfsc PORTA,2goto No2Action ; Go if bit is setdecfsz bounce,f ; Dec re ment coun tergoto Wait42

; At this point switch held zero for 10 testsmovlw .1 ; 1 is re verse on

; di rec tion switchmovwf di rec tion ; Code to switchmovlw .100 ; Slow de lay ratemovwf de lay ; To de lay coun tergoto OneTick ; Tick mo tor

No2Action:;================================; read and debounce PORTA-1;================================; Debounce PORTA-1TestPortA1:

movlw .10 ; Coun termovwf bounce

Wait41:btfsc PORTA,1goto No1Action ; Go if bit is setdecfsz bounce,f ; Dec re ment coun tergoto Wait41

; At this point switch held zero for 10 testsclrf di rec tion ; 0 is forward on

; di rec tion switchmovlw .40 ; Fast de lay ratemovwf de lay ; To de lay coun tergoto OneTick ; Tick mo tor

;================================; read and debounce PORTA-1;================================No1Action:; Debounce PORTA-0

movlw .10 ; Coun termovwf bounce

Wait40:btfsc PORTA,0goto No0Action ; Go if bit is setdecfsz bounce,f ; Dec re ment coun tergoto Wait40

; At this point switch held zero for 10 testsmovlw .1 ; 1 is re verse on

476 Chap ter 18

Page 498: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; di rec tion switchmovwf di rec tion ; Code to switchmovlw .40 ; Fast de lay ratemovwf de lay ; To de lay coun tergoto OneTick ; Tick mo tor

No0Action:goto TestPortA

;==========================; for ward or re verse; sin gle cy cle rou tine;==========================OneTick:; Test for change of di rec tion

btfss di rec tion,0 ; Test for ward bitgoto For ward

; At this point di rec tion ro ta tion is re versegoto Re verse

; Forward di rec tion rou tineFor ward:

movf this_cy cle,w ; Get cur rent cy clecall CodeTable ; Get code from ta blemovwf PORTB ; Store code in portcall De lay

; Bump cy cle coun terincf this_cy cle,f ; Add one

; Test for cy cle num ber 7 (last one in se quence)btfsc this_cy cle,3 ; 1000 = 8goto Re cy cle ; Re set if at end of cy clegoto TestPortA

Re cy cle:clrf this_cy clegoto TestPortA

; Re verse di rec tion rou tineRe verse:

movf this_cy cle,w ; Get cur rent cy clecall CodeTable ; Get code from ta blemovwf PORTB ; Store code in portcall De lay

; Bump cy cle coun terdecf this_cy cle,f ; Sub tract one

; Test for cy cle num ber 0xff (over flow from cy cle # 0)btfsc this_cy cle,4 ; Bit 4 set in di cates over flowgoto Recycle2 ; Re set if at end of cy clegoto TestPortA

Recycle2:movlw .7 ; First re verse cy clemovwf this_cy cle ; To cy cle coun tergoto TestPortA

Con stant-Volt age Bi po lar Mo tor Con trols 477

Page 499: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

;================================; de lay sub-rou tine;================================De lay:

movf de lay,w ; Load de lay valuemovwf j ; j = w

Jloop:movwf k ; k = w

Kloop:decfsz k,f ; k = k-1, skip next if zerogoto Kloopdecfsz j,f ; j = j-1, skip next if zerogoto Jloopre turn

end ;END OF PROGRAM

18.3.2 SMB_297_293D.asmThe sam ple pro gram SMB_297_293D.asm, listed be low and in this book's soft ware re -source, drives a bi po lar step per mo tor us ing a 16F84 PIC as a trans la tor, wired to anL297 and a 293D driver. The pro gram reads the tog gle switch wired to port RA4 to se -lect be tween clock wise or coun ter clock wise ro ta tion. A tog gle switch wired to lineRA3 al lows se lect ing be tween half- or full-step modes. Slow and fast speeds are de ter -mined by the set ting the tog gle switch on port line RA3. The pushbutton switches oncir cuit SMB-L297-293D-1 are not used by the pro gram.

;============================================================; File: SMB_297_293D.asm; Date: No vem ber 6, 2010; Up date: No vem ber 13, 2010; Au thors: Sanchez and Can ton; Pro ces sor: 16F84A; Ref er ence cir cuit: SMB-L297-293D-1 ;; Pro gram De scrip tion:; Pro gram to drive a bi po lar step per mo tor us ing a 16F84 PIC; as a con trol ler, wired to an L297 and a 293D driver. The; pro gram reads the tog gle switch wired to port RA4 to se lect; be tween clock wise or coun ter clock wise ro ta tion. The tog gle; switch wired to line RA3 al lows se lect ing be tween half- or; full-step modes. Slow and fast speeds are de ter mined by the; set ting of the tog gle switch on port line RA3. The pushbutton; switches on cir cuit SMB-L297-293D-1 are not used by the; pro gram.; Cir cuit wir ing is as fol lows:;

478 Chap ter 18

Page 500: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; SLOW/FAST RA2<-|--------| ; FULL/HALF RA3<-| |; CW/CCW RA4- | |<------- OSC; RESET->| |<------- OSC; GND | | +5V; ENABLE RB0<-| |; CW / CCW RB1<-| |; STEP RB2<-| |; HALF/FULL RB3<-| |; |--------|;;=========================; setup and con fig u ra tion;=========================

pro ces sor 16f84Ain clude <p16f84A.inc>__config _XT_OSC & _WDT_OFF & _PWRTE_ON & _CP_OFFerrorlevel -302

;============================================================; con stant def i ni tion;============================================================

;============================================================; vari ables in PIC RAM;============================================================; De clare vari ables at 2 mem ory lo ca tionsj equ 0x0ck equ 0x0dbounce equ 0x0e ; For debounce rou tinede lay equ 0x0f ; De lay count

;============================================================; m a i n p r o g r a m;============================================================

org 0 ; start at ad dress 0goto Main

;=============================; space for in ter rupt han dler;=============================

org 8;=============================; main pro gram;=============================Main:; Clear bit 7 in OPTION_REG to en able port B pullups

bcf OPTION_REG,7; Note: al though en abling the weak pullups on port B; should al low the cir cuit to op er ate with out the

Con stant-Volt age Bi po lar Mo tor Con trols 479

Page 501: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; con ven tional 10K pullup re sis tors, we have; found that the weak pullups are un re li able on; the 16F84. There fore we ad vise that the board; in clude the 10K pullups.; Tris PORT A for in put

movlw B'00011111' ; w = 00011111 bi narytris PORTA ; Set up port A for in put

; Tris lines 0 to 3 in port B for out put and; lines 4 to 7 (tog gle switch # 2) for in put

movlw B'11110000' ; RB7-RB4 for in put, rest for; out put

tris PORTB ; Set up port Bclrf PORTB ; Clear all lines

; Set default state for L297 con trol lines, wired as; fol lows:; PORT B BITS ; 7 6 5 4 3 2 1 0 De fault; | | | | | | | |____ ENABLE 1 (ac tive); | | | | | | |_______ CW/CCW 0 (CW); | | | | | |__________ CLOCK 1; | | | | |_____________ mode 1 (half step); |__|__|__|________________ NOT USED

movlw B'00001101' ; Half step, cw di rec tionmovwf PORTB

; Ini tial ize de fault value for de lay vari ablemovlw .40movwf de lay ; To de lay vari able

;===============================================================; main con trol mon i tor ing rou tine;===============================================================ControlRtn:; Call pro ce dure to set L297 lines ac cord ing to state of three; tog gle switches wired to port lines A2 to A4

call ReadATogglescall De lay ; De lay nowcall Pulse ; Lo cal pulse mo tor rou tinegoto ControlRtn

;========================================================; Aux il iary procedure to read tog gle switches;========================================================ReadAToggles:; Read PORTA tog gle switches; PORT A TOGGLE ; line SW ACTION; 4 1 0 = CW ro ta tion 1 = CCW; 3 2 0 = full step 1 = half step

480 Chap ter 18

Page 502: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; 2 3 1 = fast 0 = slow;=============================; set CW or CCW ro ta tion;============================= ; Bit 4 on port A is wired to tog gle # 1; Bit 1 on port B is wired to pin 17 of the L297 which; con trols CW and CCW ro ta tion.

btfsc PORTA,4goto goCCW ; Set ro ta tion bit to CCW

; Bit clear. Set CWbcf PORTB,1 ; Clear port B line 1goto SetStep

goCCW:bsf PORTB,1

;=============================; set half or full step;=============================SetStep:; Tog gle switch # 2, on port A, line 3, se lects be tween; half step and full step modes. Port B bit 3 is wired; to L297 line 19, which se lects half or full step modes

btfsc PORTA,3goto HalfStep ; Bit is set. Set half

; step mode; Bit clear. Set full step mode

bcf PORTB,3 ; Clear port B line 2goto SetSpeed

HalfStep:bsf PORTB,3

;=============================; set fast or slow speed;=============================SetSpeed:; Tog gle switch # 3, on port A, line 2, se lects be tween; fast or slow mo tor speed. If the tog gle is on, the de lay; value is set to 40, if it is off, it is set to 80

btfsc PORTA,2goto FastSpeed ; Bit is set. Set fast de lay

; Bit clear. Set slow speedmovlw .80movwf de lay ; To de lay vari ablegoto En able

FastSpeed:movlw .40movwf de lay ; To de lay vari able

;=============================; en able mo tor con trol line;=============================

Con stant-Volt age Bi po lar Mo tor Con trols 481

Page 503: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; The L297 is al ways in the ENABLE stateEn able:

bsf PORTB,0 ; Set bit to en ablere turn

;================================; rou tine to pulse the mo tor;================================; L297 CLOCK line is wired to RB2Pulse:

bsf PORTB,2 ; Bring step line highnopnopnopnopnopnopnopnopnopnopbcf PORTB,2 ; Step line lowre turn

;================================; de lay sub-rou tines;================================De lay:

movf de lay,w ; De lay to w reg is termovwf j ; j = w

Jloop:movwf k ; k = w

Kloop:decfsz k,f ; k = k-1, skip next if zerogoto Kloopdecfsz j,f ; j = j-1, skip next if zerogoto Jloopre turn

end ;END OF PROGRAM

18.3.3 SMB_297_298.asmThe pro gram SMB_297_298.asm, listed be low and in this book’s soft ware pack age, is a sim ple, noninterrupt-driven con trol pro gram for cir cuit SMB-L297-298-1 shown in Fig -ure 18-3. The pro gram uses a de lay rou tine to time the mo tor pulses. The three tog gleswitches are read by code and the cor re spond ing L297 con trol lines are set or re set ac -cord ingly. The pro gram could be im proved by mak ing it in ter rupt driven.

482 Chap ter 18

Page 504: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

;============================================================; File: SMB_297_298.asm; Date: No vem ber 6, 2010; Up date: Jan u ary 22, 2011 ; Au thors: Can ton and Sanchez; Pro ces sor: 16F84A; Ref er ence cir cuit: SMB-L297-298-1; SMB-l297-298-2 (chop per) ;; Pro gram De scrip tion:; Pro gram to drive a bi po lar step per mo tor mode with a 16F84; PIC con trol ling an L297 wired to an L298 driver.; Three tog gle switches wired to port RA1, RA2, and RA3; con trol di rec tion, full or half step modes, and set or clear; the L297 ENABLE line. Pro gram sup ports chop per hard ware.;;===========================; demo board cir cuit ;===========================; All port A lines trissed for in put:; 0 <----- NOT USED; 1 <----- Tog gle switch 1 - CW or CCW di rec tion ; 2 <----- Tog gle switch 2 - Half/full step; 3 <----- Tog gle switch 3 - ENABLE line on/off; 4 <----- Tog gle switch 4 - CONTROL line on/off; Port B lines ; PIC L297; RB0 -----> pin 10 - ENABLE; RB1 -----> pin 17 - Di rec tion; RB2 -----> pin 18 - Step in put; RB3 -----> pin 19 - Full / half step; RB4 <----- pin 11 - CTRL line; RB5 <----- |; RB6 <----- |--- NOT USED; RB7 <----- | ; PORT A TOGGLE ; line SW ACTION; 1 1 0 = CW ro ta tion 1 = CCW; 2 2 0 = full step 1 = half step; 3 3 1 = ENABLED 0 = DISABLED; 4 4 0 = CTRL OFF 1 = CTRL ON ;=========================; setup and con fig u ra tion;=========================

pro ces sor 16f84Ain clude <p16f84A.inc>__config _XT_OSC & _WDT_OFF & _PWRTE_ON & _CP_OFF

Con stant-Volt age Bi po lar Mo tor Con trols 483

Page 505: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

errorlevel -302

;============================================================; vari ables in PIC RAM;============================================================; De clare vari ables at 2 mem ory lo ca tionsj equ 0x0ck equ 0x0dde lay equ 0x0e ; De lay count

;============================================================; m a i n p r o g r a m;============================================================

org 0 ; start at ad dress 0goto Main

;=============================; space for in ter rupt han dler;=============================

org 8;=============================; main pro gram;=============================Main:; Tris PORT A for in put

movlw B'00011111' ; w = 00011111 bi narytris PORTA ; Set up port A for in put

; Tris port B for out putmovlw B'00000000' ; All lines for out puttris PORTB ; Set up port Bclrf PORTB ; Clear all lines

; Set default state for L297 con trol linesmovlw B'00001101'

|||||__________ 1 = ENABLE ||||___________ 0 = CW |||____________ 1 = clock pulse ||_____________ 1 = Half step |______________ 0 = Ctrl line off

movwf PORTB; Ini tial ize de fault value for de lay vari able

movlw .100movwf de lay ; To de lay vari able

;===============================================================; main con trol mon i tor ing rou tine;===============================================================ControlRtn:; Call pro ce dure to set L297 lines ac cord ing to state of ; tog gle switches wired to port A; call ReadAToggles

484 Chap ter 18

Page 506: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

call De lay ; De lay nowcall Pulse ; Lo cal pulse mo tor rou tinegoto ControlRtn

;========================================================; Aux il iary procedure to read tog gle switches;========================================================ReadAToggles:; Read PORTA tog gle switches; PORT A TOGGLE ; line SW ACTION; 1 1 0 = CW ro ta tion 1 = CCW; 2 2 0 = full step 1 = half step; 3 3 1 = Set or clear ENABLE line;=============================; set CW or CCW ro ta tion;============================= ; Bit 1 on port A is wired to tog gle switch # 1; Bit 1 on port B is wired to pin 17 of the L297, which; con trols CW and CCW ro ta tion.

btfsc PORTA,1goto goCCW ; Set ro ta tion bit to CCW

; Bit clear. Set CWbcf PORTB,1 ; Clear port B line 1goto SetStep

goCCW:bsf PORTB,1

;=============================; set half or full step;=============================SetStep:; Tog gle switch # 2, on port A, line 2, se lects be tween; half step and full step modes. Port B bit 3 is wired; to L297 line 19, which se lects half or full step modes

btfsc PORTA,2goto HalfStep ; Bit is set. Set half step

; mode; Bit clear. Set full step mode

bcf PORTB,3 ; Clear port B line 2goto TestEnable

HalfStep:bsf PORTB,3

;=============================; en able mo tor con trol line;=============================; Tog gle switch # 3, on port A, line 3, con trols the; L297 ENABLE line, on pin No. 10TestEnable:

btfsc PORTA,3

Con stant-Volt age Bi po lar Mo tor Con trols 485

Page 507: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

goto En able ; Bit is set. Set ENABLE line; Bit clear. Dis able

bcf PORTB,0 ; Clear the ENABLE linere turn

En able:bsf PORTB,0 ; Set bit to en ablere turn

;================================; rou tine to pulse the mo tor;================================; L297 CLOCK line is wired to RB2.; Pulse is neg a tive go ingPulse:

bcf PORTB,2 ; Bring step line highnopnopnopnopbsf PORTB,2 ; Step line lowre turn

;================================; de lay sub-rou tines;================================De lay:; bsf PORTB,2 ; Step line low

movf de lay,w ; De lay to w reg is termovwf j ; j = w

Jloop:movwf k ; k = w

Kloop:decfsz k,f ; k = k-1, skip next if zerogoto Kloopdecfsz j,f ; j = j-1, skip next if zerogoto Jloopre turn

end

486 Chap ter 18

Page 508: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Chap ter 19

Ad vanced Mo tor Con trols

19.1 Chop pers and MicrosteppingIn Chap ter 18 we dis cussed cir cuits and pro grams for bi po lar mo tors that op er ate with a con stant volt age through the coils. In this chap ter we dis cuss con trols in which thecur rent through the coils is held ap prox i mately con stant, in stead of the volt age. Onetype of con stant-cur rent de sign is re ferred to as a “chop per” cir cuit. In the chop per the cur rent in each wind ing is held ap prox i mately con stant by vary ing the volt age. In op -er a tion, a high volt age is ini tially ap plied to each wind ing, caus ing the cur rent to risequickly. When the cur rent reaches a pre de ter mined limit, the volt age is “chopped” offand the cur rent drops. The cy cle con cludes when a pre-de ter mined low cur rent limit is reached and the volt age is turned back on. Chop per drives re quire ad di tional com po -nents in or der to mea sure the cur rent in the wind ings and to per form the nec es saryswitch ing op er a tions. The ad van tage is that mo tors can be driven at higher speeds and torques than in con stant-voltage cir cuits.

In Chap ter 15 we dis cussed the var i ous step ping modes used in driv ing step permo tors. These modes de fine the or der in which the var i ous coils are ac ti vated. Themost com mon ones are the wave-, full-, and half-step modes. In that con text, wealso men tioned an ad di tional step ping mode usu ally called microstepping, in whichthe cur rent in the wind ings is pro gres sively var ied in or der pro duce a more uni format trac tion of the ro tor and re duce the jer ki ness that re sults from the con ven tionalstep ping modes. Be cause microstepping re quires con trol over the cur rent lev els ap -plied to the wind ings, it can be im ple mented as a vari a tion of the chop per tech -niques pre vi ously men tioned. Cir cuits and pro grams that im ple ment microsteppingare also covered in this chapter.

19.2 Chop per Cir cuit Fun da men talsAl though the gen eral con cept of a chop per cir cuit is not very well de fined, it can beviewed as a switch ing op er a tion used to con trol one sig nal with a sec ond one. Powersup plies, am pli fi ers, switched ca pac i tor fil ters, and vari able-fre quency drives arecom mon uses of chop per cir cuits. In the con text of mo tor con trols, a chop per circuitis one in which a con trolled switch is used to limit the cur rent flow ing through a coil.

487

Page 509: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

The op er a tion re quires some way of sens ing the cur rent so that the chop per switchcan be turned on and off as the pre de ter mined cur rent lim its are reached.

Based on this scheme, a cir cuit can be de signed to con trol the cur rent in or der tolimit power dis si pa tion and vary the torque in a mo tor wind ing. One way of lim it ingthe cur rent is by con trol ling the sup ply volt age, which usu ally re quires add ing ex ter -nal re sis tance. The al ter na tive method of cur rent con trol is to vary, for a short timepe riod, the sup ply volt age to val ues sev eral times higher than the nom i nal volt age of the mo tor. Fig ure 19-1 shows the sim pli fied sche mat ics of chopper-based currentregulation.

Fig ure 19-1 Sche mat ics of Chop per-Based Reg u la tion.

Cur rent is sensed by mea sur ing the volt age drop across a known re sis tor, la beledR sense in Fig ure 19-1. Tran sis tor T1, which is con trolled by the sys tem’s step logic,turns the flow on to pro duce the mo tor step. While the step-on state is ac tive, thefol low ing op er a tions take place:

• Tran sis tor T2 turns on the current flow to the mo tor wind ing.

• At each pulse of the chop per’s clock oscillator, the re sis tor la beled R sense pro videsa ref er ence for mea sur ing the current flow in the wind ing. This re sults from the factthat as the current in creases, so does the voltage drop across R sense.

488 Chap ter 19

COMPARATOR

MOTORWINDING

T1

T2

V ref

V sense

R sense

Vm

OSCILLATOR

STEPLOGIC

CHOPPERCONTROL

LOGIC

+5V

Page 510: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

• This voltage is fed to the com para tor where it is matched to an an a log ref er encevoltage de ter mined by the set ting of a trim mer pot. The trim mer pot is ini tially set tomatch the elec tri cal char ac ter is tics of the mo tor in the cir cuit.

• If the value of V sense is the same or ex ceeds the ref er ence voltage (V ref), then thechop per con trol logic turns off transistor T2, which, in turn, shuts off current to thewind ing.

• As the voltage drop across R sense de creases, the com para tor out put changesstates and the con trol logic turns on transistor T2.

• The cy cle con tin ues at each pulse of the oscillator and while the step-on sig nal ishigh.

Fig ure 19-2 shows the var i ous wave forms in a chop per cir cuit.

Fig ure 19-2 Chop per Cir cuit Wave forms.

In Fig ure 19-2 the wave form at the top of the il lus tra tion shows the sawtoothform of the cur rent that re sults from the ac tion of the com para tor, as de ter mined bythe ref er ence volt age. The ac tiv ity of the T2 switch (see Fig ure 19-1) is shown by the wave form at the bot tom of the fig ure. The dash-dot ver ti cal lines show the os cil la tor pe riod, which is typ i cally 20 KHz in step per mo tor cir cuits. The dashed line rep re -sents the pe riod dur ing which switch T1 is on, which cor re sponds to the stepsgenerated by the control logic.

Cur rent con trol meth ods such as chop per cir cuits pro vide sev eral ad van tages instep per mo tor ap pli ca tions:

Ad vanced Mo tor Con trols 489

Current

Time

Step-on period (T1 switch)

Average currentthrough coil

Oscillator period

Comparator action (T2 switch)

T2 on

I = 0

I = 0

T2 off

Page 511: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

• Over heat ing is re duced.

• Torque is in creased.

• Top speed is in creased.

• Ef fi ciency is higher.

• Mo tors of dif fer ent char ac ter is tics can be used with the same cir cuit.

The cir cuit in the fol low ing sec tion al lows im ple ment ing a bi po lar step per mo torcon trol chop per cir cuit. Note that chop per cir cuits can also be used with uni po larmo tors, al though bi po lar ones are by far more com mon. The Al le gro SLA7024M is achop per con trol IC for unipolar motors.

19.3 L297/298 Chop per Cir cuitIn Chap ter 18 we pre sented a sim ple cir cuit based on the L297/298 pair. This cir cuit, la -beled SMB-L297-298-1 and shown in Fig ure 18-3, leaves sev eral un used lines in ei therIC. In fact, in the driver stage of cir cuit SMB-L297-298-1, the only con nec tion be tweenthe 297 and the 298 chips are the four 297 out put lines. The os cil la tor, volt age ref er -ence, sense, and in hibit lines of the 297 are left float ing, and the match ing lines on the298 are ei ther held high or wired to ground. Fig ure 19-3 shows the driver stage of a cir -cuit that can be used to im ple ment chop ping.

Fig ure 19-3 Bi po lar Mo tor Con trol Cir cuit with Chop ping.

490 Chap ter 19

+5V

+5V

MOTORSUPPLY

L2

97

L2

98

SYNC

GND

HOME

Out A

INH 1

Out B

Out C

INH 2

Out D

ENABLE

1

2

3

4

5

6

7

8

9

10

15

13

11

9

7

5

3

1

14

12

10

8

6

4

2

20

19

18

17

16

15

14

13

12

11

RESET

Half/full

CLOCK

CW/CCW

OSC

Vref

SENS 1

SENS 2

Vs

CTRL

SENSE B

OUT 3

ENABLE B

Vs

IN 2

IN 1

OUT 2

SENSE A

OUT 4

IN 4

IN 3

GND

ENABLE A

Vm

OUT 1

+5V

+5V

+5V

+5V

R=10K

R=4.7K

CIRCUIT: SMB-L297-298-2

RB0

RB3

RB2

RB1

SENS2

SENS1

0.1uF

470 uF

R = 0.5 Ohm x 2(nonwire bound)

5 K trimmer

22 K

20 K

3300 pf

0.1 mf

Diodes x 8fast 2A

+

INH2

OUTB

OUTA

OUTD

INH1

OUTC

DRIVER STAGE

bipolarsteppermotor

Page 512: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

The con trol and trans la tor stage of cir cuit SMB-L297-298-1 (in Fig ure 18-3) can be used with the driver stage of the cir cuit in Fig ure 19-3. The fol low ing lines of theL297 re late to the chop per function:

CONTROL: De fines the ac tion of the chop per. When held high, the chop per actson the phase lines A, B, C, and D. When low, the chop per acts on the INH1 and INH2lines. In the pres ent cir cuit, the CONTROL line is held high.

A-B-C-D: Mo tor phase lines con nect ing to the power stage.

ENABLE: When low, dis ables the L297 func tions and brings down the A-B-C-Dlines and the INH1 and INH2. The ENABLE line is pulled low dur ing sys tem ini tial -iza tion.

OSC: Con nected to an RC network to pro duce a clock sig nal that de ter mines thechop ping rate.

INH1: Ac tive low con trol for stages A and B. With a bi po lar H bridge, this func tionen sures the fast de cay of the load current when a wind ing is de-en er gized. Op er -ates in half-step and wave drive modes.

INH2: Same as INH1 for con trol stages C and D.

SENS1 and SENS2: Senses the wind ing current for stages A and B (SENS1) andfor stages C and D (SENS2). Value from the SENS1 and SENS2 lines are fed to thein ter nal com para tor to de ter mine the max i mum load current dur ing chop ping.

RESET: Ac tive low on this line re sets the L297 to its home state.

SYNC: Pro vides an out put of the oscillator pulse use ful in cir cuits with mul ti pleL297 chips. Left float ing in cir cuit SMB-L297-L298-2.

HOME: Open col lec tor out put in di cat ing that the L297 is in its ini tial state. Thisport can be used in counting the num ber of steps made by the mo tor. It is left float -ing in cir cuit SMB-L297-L298-2 be cause the step count can be kept in ter nally by themicrocontroller.

In build ing the cir cuit note that the sense re sis tors must not be wire bound andthat the di odes must be fast and have a 2-amps ca pac ity.

19.3.1 Set ting the Ref er ence Volt ageThe max i mum wind ing cur rent must be cho sen for the par tic u lar mo tor wired to theboard. This value de ter mines the ref er ence volt age that is set by means of the trim meron the Vref line. The gen eral for mula is

where I is the rated cur rent of the mo tor in use and R is value of the sense re sis tors, inthis case 0.51 Ohms. For ex am ple, with a mo tor rated for 0.5 A, the for mula is eval u -ated as fol lows:

In or der to set the cir cuit to the cor rect voltage reference, a volt me ter is con nected to the trim mer pot and +5 volts ap plied to the board. This should be done with theL297 re moved from the board. Al ter na tively, the board may con tain a jumper be tween the trim mer’s move able arm and the L297 Vref pin. In this case, the ad just ment can be

Ad vanced Mo tor Con trols 491

RIVref •=

255.051.05.0 =•=Vref

Page 513: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

made with out hav ing to re move the L297 by open ing the jumper con nec tion and hold -ing low the ENABLE line. In ei ther case the trim mer pot is ad justed so that the voltageon the Vref pin is as de ter mined by the pre vi ous for mula.

19.4 Chop per-Based Demo BoardA dem on stra tion board for test ing and ad just ing chop per-based cir cuits is a valu able con -ve nience for the de vel oper, es pe cially if a multimeter and an os cil lo scope are avail able.The board is par tic u larly use ful in de vel op ing the soft ware that will op er ate the cir cuit,for check ing mo tors of un known con di tion or pa ram e ters, and for ex per i ment ing be forecom mit ting to de sign and hard ware de ci sions. Fig ure 19-4 shows the sche mat ics for achop per-based demo board in tended for bi po lar mo tors that do not ex ceed the ca pac ityof the L297/298 driv ers.

The driver stage of cir cuit DEMO-SMB-01, in Fig ure 19-4, is al most iden ti cal to thedriver stage of cir cuit SMB-L297-298-2 in Fig ure 19-3. The only dif fer ence is the jumperla beled J1 on the L297 Vref pin, which al lows set ting the ref er ence voltage with out re -mov ing the L297 from its socket. The con trol and trans la tor stage is based on the16F84A PIC and con tains an eight-le ver dip switch wired to ports A and B. The LED onport RB7 can be used in test ing that the microcontroller pro gram is ex e cut ing by means of a short pro gram that flashes the LED. It can also be used to re port the state of a pro -gram func tion or con trol. The use of each of the eight DIP switches is left to the de vel -oper.

Ma te ri als list, build ing in struc tions, and PCB im ages for the DEMO-SMB-01 boardcan be found in on line files. Note that the PCB ver sion of the board in cludes a sec ondjumper la beled J2. This jumper al lows powering the mo tor from the same source usedfor the board or from a sep a rate power sup ply. The PCB ver sion also con tains a con -ven tional 78L05 logic power source and a stan dard wall adapter in let. Ide ally, the L297should be mounted on an 20-pin IC socket and the microcontroller on a ZIF adapter.

19.4.1 Mo tor Cir cuit Power Re quire mentsStep per mo tor cir cuits of ten have dif fer ent power re quire ments for the var i ous com po -nents. For ex am ple, the cir cuit SMB-L297-298-2 in Fig ure 19-3 re quires DC power for thePIC 16F84A microcontroller, for the L297, the L298, and the step per mo tor. Three of thesecom po nents can op er ate at a nom i nal 5 volts: the 16F84, the L297 and the 298. Step permo tors, on the other hand, have a wide range of voltage re quire ments, rang ing from 5 to40 volts.

Be cause the clas sic 7805 reg u la tor op er ates at 7.5 to 20 volts, it may be pos si ble topower all com po nents from a sin gle source. This would be the case if the step per mo tor is in the range of 8 to 20 volts and if the source avail able has suf fi cient am per age tocover the needs of both the three ICs and the mo tor. For ex am ple, if the mo tor re quires12 volts at 1 amp, a 12-volt 2-amp source could be tapped to feed both the mo tor andthe 7805 reg u la tor. In this case, the out put of the 7805 pro vides 5 volts for the cir cuitICs while the mo tor re ceives the full power from the source. How ever, if the mo tor re -quire ments ex ceed the 20-volt limit of the 7805, then, circuit re quires two powersources, or the voltage of the power source must be re duced to the 20-volt limit ofthe 7805.

492 Chap ter 19

Page 514: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 19-4 Chop per-Based Demo Board Sche mat ics.

Demo board DEMO-SMB-01 con tains a jumper that al lows se lect ing power to themo tor di rectly from the source used by the board, or from a sep a rate sup ply. Ifjumper J2 (not shown in the cir cuit sche mat ics) is closed, then the mo tor power co -

Ad vanced Mo tor Con trols 493

+5V

+5V

MOTORSUPPLY

L2

97

L2

98

SYNC

GND

HOME

Out A

INH 1

Out B

Out C

INH 2

Out D

ENABLE

1

2

3

4

5

6

7

8

9

10

15

13

11

9

7

5

3

1

14

12

10

8

6

4

2

20

19

18

17

16

15

14

13

12

11

RESET

Half/full

CLOCK

CW/CCW

OSC

Vref

SENS 1

SENS 2

Vs

CTRL

SENSE B

OUT 3

ENABLE B

Vs

IN 2

IN 1

OUT 2

SENSE A

OUT 4

IN 4

IN 3

GND

ENABLE A

Vm

OUT 1

+5V

+5V

+5v

+5V

R=10K

R=4.7K

CIRCUIT: DEMO-SMB-01 CODE: PWM_Demo_873.asm

RB0

RB3

RB2

RB1

SENS2

SENS1

0.1uF

470 uF

R = 0.5 Ohm x 2(non wire bound)

5 K trimmer pot

22 K

20 K

J1

3300 pf

0.1 mf

Diodes x 8fast 2A

+

INH2

OUTB

OUTA

OUTD

INH1

OUTC

DRIVER STAGE

bipolarsteppermotor

CONTROL AND TRANSLATOR STAGE

16

F8

4A

+5V

+5V

R=

10

K

R=

10

K x 8

RA2

RA3

RA4/TOCKI

MCLR

Vss

RB0/INT

RB1

RB2

RB3

1

2

3

4

5

6

7

8

9

18

17

16

15

14

13

12

11

10

RA1

RA0

OSC1

OSC2

Vdd

RB7

RB6

RB5

RB4

RESET

LED

Osc

DIR

SW4

SW5

SW3

STEP

HLF/FL

ENBL

SW2

SW1

SW6

SW7

SW8

SW 4

SW 8

SW 3

SW 7

SW 2

SW 6

SW 1

SW 5

DIP SWx 8

R = 470 OHM

Page 515: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

mes from the same source used for the board. If J2 is open, then mo tor power mustbe fed through sep a rate taps on the bot tom-left cor ner of the demo board.

In de ter min ing the power re quire ments of a step per mo tor, keep in mind that twodif fer ent rat ings are some times listed in the datasheet: the max i mum volt age andthe op er at ing volt age. In the ory, the max i mum volt age should never be ex ceeded, atthe risk of de stroy ing the in ter nal in su la tion in the wind ings. But chop per andmicrostepping cir cuits of ten use five times or more than the rated volt age for shorttime pe ri ods in or der to in crease per for mance and max i mize torque. The prac ti calrule is that as long as the max i mum am per age of the mo tor is not ex ceeded, cur rentlim it ing tech niques allow fluctuations in voltage that produce no harm.

19.4.2 Chop per Demo Pro gramThe sam ple pro gram PIC_Chop per.asm, listed later in this chap ter and in this book’ssoft ware re source, al lows test ing the chop per hard ware in the DEMO-SMB-01 cir cuitshown in Fig ure 19-4. The pro gram drives the mo tor in the for ward or re verse di rec -tion and in full- or half-step modes, but its ex e cu tion proves that the chop per cir cuit isper form ing its ex pected func tions.

19.5 MicrosteppingAbrupt changes in mag ni tude or di rec tion or the cur rent driv ing a step per mo tor re sult in jer ki ness and un even ro ta tion, which is espe cially ob jec tion able at lower mo torspeeds. This jolt ing ac tion re lates to step ping modes, be ing less in half- than in full- orwave-step modes. In some ap pli ca tions the abrupt changes in ro tor speed can havedel e te ri ous ef fects. In fact, the de vel op ment of microstepping is re lated to the abruptmo tion of a turn ta ble used in med i cal tests, which re sulted in spilled sam ples. LarryDurkos, an en gi neer for the com pany that man u fac tured the equip ment, came up witha com puter-con trolled so lu tion to the prob lem based on the tech nique now called“microstepping.” Fig ure 19-5 shows ro tor ac tion in sev eral step ping modes.

Fig ure 19-5 Step per Mo tor Ro ta tion in Var i ous Step ping Modes.

494 Chap ter 19

Full step

o90

o45

o18

Half step Microstep

Page 516: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

In the left-hand step per mo tor of Fig ure 19-5, the ro tor moves through an an gle of 90 de grees for each pulse in the full-step mode. In the step per mo tor at the cen ter ofthe fig ure the ro tor moves 45 de grees in the half-step mode. The ro tor at the rightside of Fig ure 19-5 ro tates through an an gle of 18 de grees in the microstep mode. Byre duc ing the an gle of ro ta tion for each mo tor step, the move ment of the ro tor ismade smoother and less abrupt. In this ex am ple, one full ro ta tion re quires fourpulses in the full-step mode, eight pulses in the half-step mode, and twenty pulses in the microstep mode. Note that the mo tor de picted in the il lus tra tion does not cor re -spond to a real de vice be cause step an gles are usu ally much smaller in actualmotors.

An other fac tor that af fects step per mo tor ro ta tion re lates to the con ven tionalcur rent wave forms. Fig ure 19-6 shows the cur rent tran si tions in a con ven tionalfull-step mode with maximum torque.

Fig ure 19-6 Cur rent Tran si tions in High-Torque Step ping Mode.

The wave form in Fig ure 19-6 shows a volt age that rises abruptly at the start ofeach step; con se quently, so does the at trac tion of the stator wind ings on the mo torpoles. As the volt age de clines abruptly at the end of each step, the at trac tion is in -stantly turned off. This re sults in the less-than-smooth move ment as so ci ated withstep per mo tors in con ven tional pulse modes. The square wave ap prox i mately rep re -sents the at trac tion of the wind ings on the ro tor at var i ous positions in the stepcycle.

The ideal wave form for driv ing a step per mo tor so as to pro duce uni form at trac -tion on the wind ings is a sine wave, as the ones shown in Fig ure 19-7.

Ad vanced Mo tor Con trols 495

0 90 180 270 360CURRENT

COIL A

COIL B

ELECTRICAL ANGLE

Page 517: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 19-7 Sine/Co sine Wave-Shaped Coil Cur rent.

Two sine waves out of phase by 90 de grees (sine and co sine of the elec tri cal an -gle) en sure that the at trac tion of the wind ings on the ro tor will be uni form and thatthe mo tor will move smoothly and qui etly. This is due to the fact that as the cur rentin one coil in creases, the cur rent de creases in the other coil; there fore the torque iscor rectly pro por tioned be tween the two coils at any an gle. Trig o no met ri cally, thepower in each coil (torque) is the square root of the sum of the squares of thecurrent in each coil.

Microstepping re duces or elim i nates this ef fect by vary ing the cur rent in thewind ings so as to pro duce a uni form at trac tion on the ro tor through out the step cy -cle. This can be achieved by mod i fy ing the cur rent ap plied to the wind ings so as tofol low the sine wave form shown by the dot ted line in the il lus tra tion. In this casethe at trac tion on the ro tor is uni form through out the step cy cle and the mo tor ro -tates smoothly. Be cause microstepping re quires con trol over the cur rent lev els it re -sults in more com plex cir cuitry, more so phis ti cated hard ware, and morecomplicated programming.

Microstepping im proves step per mo tor per for mance by of fer ing the fol low ing ad -van tages:

• The mo tor ro tates more smoothly at slow speeds.

• The res o lu tion of the ro tor po si tion ing is in creased due to a smaller step an gle.

• Torque is higher at both low and high step rates.

Microstepping is usu ally im ple mented by con trol ling the cur rent in both mo torcoils. Some microcontroller-based cir cuits con trol the cur rent us ing pulse width

496 Chap ter 19

0 90 180 270 360CURRENT

Sin

Cos

ELECTRICAL ANGLE

Page 518: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

mod u la tion meth ods. These cir cuits and con trols are de scribed in the sec tions thatfollow.

19.5.1 Microstepping Fun da men tals In the field of step per mo tor con trols, the step rate is de fined as the speed at which thecoils are turned on or off. Step rate is mea sured in steps per unit of time, usu ally insteps per sec ond or per mi cro sec ond. The max i mum speed of a mo tor is achievedwhen the step rate is high est. This max i mum speed is de ter mined by the in duc tance inthe mo tor wind ings be cause a de vice with higher wind ing in duc tance takes lon ger toreach the rated coil current. If the time be tween steps is less than the time re quired forcurrent build-up, then the mo tor misses a step or “slips.”

Be cause the step rate is a mea sure of the speed at which the mo tor wind ing cur -rent is turned on and off, we can see that it dou bles in the half-step mode com paredto the full-step mode. By the same to ken, when the ro tor is moved in microsteps, the step rate is in creased by a fac tor de ter mined by the num ber of microsteps in a fullstep. In the case de picted in Fig ure 19-5, the step rate in the microstepping ex am pleis in creased by a fac tor of 20 com pared to the full-step rate be cause there aretwenty microsteps in one full step in this case.

Microstepping The ory

It is easy to see how re duc ing the size of each step im proves the smooth ness of step per mo tor ro ta tion. How ever, given a two-pole mo tor, it is not pos si ble to fur ther re ducethe num ber of steps be yond one-half the step ping rate by ma nip u lat ing the pulse se -quence. We de fine one full elec tri cal cy cle as con sist ing of four full steps. This meansthat a full elec tri cal cy cle con sists of 360 de grees of elec tri cal an gle, which is not thesame as 360 de grees of me chan i cal ro ta tion. At any step an gle one full elec tri cal cy cleof a step per mo tor con sists of four full steps. Hence, one full step cor re sponds to 90de grees of elec tri cal an gle.

In microstepping, the mo tor’s elec tri cal an gle is di vided into smaller, equal unitsby vary ing the cur rent in the stator wind ings. Al though the re sult ing curve does notper fectly match a sine wave, it can be ap prox i mated by choos ing small-enoughsteps, as shown in Figure 19-8.

Fig ure 19-8 Sine Wave Ap prox i ma tion by Dis crete Cur rent Steps.

Ad vanced Mo tor Con trols 497

0 90 180 270 360

ELECTRICAL ANGLE

STEP

Page 519: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

In a step per mo tor, en er giz ing a wind ing pro duces a flux in the air gap that is pro -por tional to the cur rent in the wind ing. If vari a tion is in tro duced in more than onewind ing, then the flux in the air gap is the vec tor sum of the cur rent in the var i ouswind ings. The ro ta tion takes place in the di rec tion of the re sul tant vec tor. In the full step mode, the max i mum rated cur rent is ap plied to the wind ings, re sult ing in a fluxin the air gap of 90 de grees elec tri cal with each pulse. In the half step mode, the flux ro ta tion is of 45 degrees electrical.

In microstepping, the cur rent in the wind ing is ap plied at a frac tion of the ratedvalue. This means that the flux changes by a frac tion of 90 de grees elec tri cal in there sult ing di rec tion. Usu ally a full step is di vided into 4, 8, 16, or 32 changes in cur -rent in ten sity, which are the microsteps. Al though it is pos si ble to di vide a full stepinto more than thirty-two microsteps, it is gen er ally con sid ered that a greater num -ber of steps pro vides no fur ther im prove ment in ro tor mo tion. In a two-wind ingmo tor, the fol low ing for mula can be used to cal cu late the re quired cur rent in thewind ing to achieve a re quired ro ta tion in the flux:

where Ia and Ib are the current in stator wind ings A and B, re spec tively, Irate is therated current of the mo tor, and θ rep re sents the microstep an gle. The vec tor sum ofthe in di vid ual wind ing currents is ex pressed as fol lows:

where S is the re sul tant stator cur rent. Fig ure 19-9 shows the ideal stator cur rent vari -a tions in the two wind ings of a step per mo tor.

Fig ure 19-9 Stator Cur rent Dur ing Microstepping.

498 Chap ter 19

θθ

cos

sin

•=•=

IrateIb

IrateIa

))cos()sin(( 22 θθ •+•= IrateIrateS

1 2 3 4 1 2

current

Winding A

Winding B

steps

Page 520: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

As the cur rent var ies in each wind ing (la beled A and B in Fig ure 19-9), there is acor re spond ing vari a tion in the ro tat ing flux in the air gap. For each step, the ac tualvalue of the flux in the air gap cor re sponds to the value for Irate in the pre vi ousequa tions. It is this ef fect that en sures a con stant ro tat ing torque in microstepping.How ever, in im ple ment ing microstepping it is more ef fec tive to keep the cur rent ineach wind ing con stant dur ing more than half the step, while the cur rent in the otherwind ing is var ied as func tion of the sine of the an gle of rotation, as shown in Figure19-10.

Fig ure 19-10 One-Wind ing-Held-Con stant Phase-Current Di a gram.

Hold ing the cur rent con stant dur ing one-half the step cy cle re sults in the fol low -ing re la tion:

where S is the re sul tant current, Irate is the rated cur rent of the mo tor, and θ rep re -sents the microstep an gle. This scheme is usu ally called high-torque microstepping.

Pulse Width Mod u la tion (PWM)

From the pre vi ous dis cus sion we can see that in or der to im ple ment microstepping,we must find a way of vary ing the current through the coils dur ing the step cy cle. Al -though there are sev eral ways to ac com plish this, the one most suit able formicrcontroller-based cir cuits is to ma nip u late the duty cy cle us ing a tech nique calledpulse width modulation or PWM. The method is par tic u larly con ve nient when themicrocontroller con tains a PWM mod ule. Sev eral mid-range PICs, in clud ing the16F684, the 16F873, the 16F887, and most high-end and DSP de vices, in clude a Cap -ture/Com pare/ PWM (CCP) module that pro vides the re quired func tion al ity. An en -hanced ver sion of the CCP mod ule named ECCP can be found in the currentgen er a tion of PICs.

The ba sic idea of pulse width mod u la tion is to con trol the av er age value of a cur -rent fed to a load by rap idly turn ing on and off the power source. In this con text, aduty cy cle is de fined as the per cent age of the PWM con trol pe riod dur ing which the

Ad vanced Mo tor Con trols 499

0.5 1.5 2.5 3.51 2 43

current

Winding A

Winding B

)22 )sin((( θ•+= IrateIrateS

Page 521: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

sig nal is held high. For ex am ple, a 10V sig nal that is held on 50 per cent of the time(50 per cent duty cy cle) re sults in an av er age volt age of 5V. Fig ure 19-11 shows thefun da men tal el e ments in the con cept of pulse width modulation.

Fig ure 19-11 Pulse Width Mod u la tion Sche mat ics.

In Fig ure 19-11 the duty cy cle is 25 per cent of the PWM pe riod, there fore the re -sult ing av er age cur rent is 25 per cent of its max i mum value. In any case, the re sult -ing cur rent is in the same ra tio to the max i mum cur rent as the duty cy cle is to thePWM pe riod. For ex am ple, if the rated cur rent is 10 A and the duty cy cle is 10 per -cent, then the re sult ing current will be 1 A.

Note that PWM is ef fec tive in de vices that re spond to the cur rent av er age and not to its in stan ta neous value. These in clude light bulbs and DC mo tors. Com mer cialdim mers used in con trol ling house hold lights use a form of pulse width modulation.

19.6 Pro gram ming PWMThe CCP and ECCP mod ules avail able in many mid-range, high-end, and DSP PICs pro -vide the hard ware for easy im ple men ta tion of pulse width mod u la tion as re quired forstep per mo tor con trol. Many de vices con tain sev eral CCP or ECCP mod ules. In ad di -tion to PWM, the CCP and ECCP mod ules pro vide cap ture and com pare op er a tions, asin di cated by the let ter C in the de vice’s name.

Three PICs cov ered in this book con tain one or an other ver sion of the CCP mod -ule: the 16F684, 16F877, and 16F873. When these mod ules are not avail able, it ispos si ble to im ple ment PWM in soft ware as de scribed in the lit er a ture avail able from Micro chip. In this sec tion we dis cuss pulse width mod u la tion us ing the hard waremod ules men tioned pre vi ously. We do not de scribe the re fine ments pro vided by theen hanced ver sion of the mod ule.

19.6.1 CCP Mod uleThe mid-range PICs that pro vide PWM hard ware con tain up to two CCP or ECCP mod -ules. When more than one CCP mod ule is fur nished, all of them share a sin gle clocksource; there fore, the func tion al ity of these mod ules is lim ited be cause they all de -pend on a sin gle clock cy cle. The CCPxCON reg is ters con trol the op er a tion of the CCPde vices. Here x can have the val ues 1 or 2. If a de vice con tains more than one mod ule,then all CCP-re lated reg is ters use the dig its 1 or 2 to iden tify each mod ule. For ex am -

500 Chap ter 19

dutycycle

PWMperiod

average current

Page 522: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

ple, the CCPxL reg is ters are des ig nated ei ther as CCP1L or CCP2L. We will use the xdes ig na tion in the pres ent de scrip tions. The fol low ing are the CCP ba sic reg is ters:

CCPxCON: One or two CCP con trol reg is ters. This reg is ter pro vides mode se lec -tion and ac cess to the two least-sig nif i cant bits of the duty cy cle.

CCPRxL: One or two CCPR reg is ters that store the low byte value in cap ture orcom pare mode and the duty cy cle in PWM mode.

CCPRxH: One or two CCP reg is ters that store the high byte value in cap ture orcom pare mode. It is used by the hard ware for latch ing the duty cy cle in PWM mode. In PWM mode, CCPRxH is read-only.

Fig ure 19-12 is a bitmap of the CCPxCON reg is ter.

Fig ure 19-12 Bitmap of the CCPxCON Reg is ter for PWM Op er a tion.

In PWM mode, two port pins are mul ti plexed for pulse width mod u la tion. TheCCPx pins pro vide the PWM out put in a 10-bit res o lu tion, al though ap pli ca tionssome times ig nore the two low-or der bits and thus re duce the res o lu tion to 8 bits. Inany case, the port pins mapped to the PWM func tion (PORT C in the 16F87x PICs) must have their tris reg is ters set for out put. PWM uses Timer 2 in free run ning mode for a clock sig nal. The PR2 reg is ter is used to set the PWM pe riod, and the CCPRxLreg is ter is used to store the high-or der 8 bits of the duty cy cle while the two low-or -der bits are in CCPxCON reg is ter bits 5 and 4 (see Fig ure 19-12). The du ra tion of thePWM pe riod and duty cy cle are de ter mined by the sys tem’s clock fre quency and theprescaler set ting. Fig ure 19-13 is a bitmap of the PR2 and CCPRxL reg is ters.

Fig ure 19-13 Bitmap of the PR2 and CCPRxL Reg is ters for PWM Op er a tion.

Ad vanced Mo tor Con trols 501

bit 7

bits 5-4 (PWM mode) two LSBs of duty cyclebits 3-0 Mode select bits 11xx = PWM mode

CCPxCON Register

CCPxX CCPxY CCPxM3 CCPxM2 CCPxM1 CCPxM0

bit 0

bit 7

bit 7

bits 7-0 (PWM mode) Timer 2 rate determines PWM period

bits 7-0 (PWM mode) MSBs of duty cycle. LSBs are in CCPxCON register bits 4-5 (see Figure 14-12)

PR2 Register

CCPRxL Register

bit 0

bit 0

Page 523: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

The PWM pe riod and duty cy cle are de ter mined by the fol low ing el e ments:

• The sys tem clock rate and the Timer 2 prescaler which to gether with the value in the PR2 reg is ter de ter mine the Timer 2 rate. This is the PWM pe riod.

• The stetting in bits 5-4 of the CCPxCON reg is ter. These are the two low-or der bits ofthe duty cy cle.

• The set ting of the CCPRxL reg is ter which de ter mines the eight high-or der bits of the duty cy cle.

For ex am ple, as sume a PIC microcontroller run ning at 4 MHz and a Timer 2prescaler of 1:1. In this case the PWM pe riod is de ter mined by the value in the PR2reg is ter. The ac tual for mula for the PWM pe riod is as follows:

The duty cy cle is de ter mined by the bits 5-4 of the CCPxCON (low-or der bits) and the value in the CCPRxL reg is ter (high-or der bits). The ac tual for mula is as fol lows:

Thus, if we store 99 dec i mal in PR2, clear bits 5-4 in the CCPxCON reg is ter, andstore the value 25 dec i mal in the CCPRxL reg is ter, then the duty cy cle will be 25 per -cent of the PWM period.

In op er a tion, the CCP mod ule in PWM mode pro ceeds as fol lows dur ing the PWMcy cle:

• The CCPx pin mapped to the PWM func tion is brought high.

• The duty cy cle is loaded into the CCPRxH reg is ter.

• While the count in CCPRxH re mains greater than the Timer 2 count, the out put onthe CCPx pin is held high.

• When the count in the CCPRxH matches the one in Timer 2, the CCPx out put isbrought low.

• A new cy cle starts when the value in PR2 matches the Timer 2 count.

A change in the duty cy cle will not take ef fect un til the start of the next cy cle.

19.6.2 PWM Cir cuit and Soft ware

Be cause pro gram ming PWM us ing the CCP hard ware is not with out com pli ca tions, itis a good idea to de velop a sim ple board that tests the soft ware rou tines with out thecon trols and re fine ments of the fi nal mo tor con trol cir cuit. One sim ple test cir cuit canbe based on con nect ing an LED to the PWM line and some sim ple means of vary ing theduty cy cle. As the duty cy cle is in creases, so does the bright ness of the LED, and viceversa. Fig ure 19-14 shows such a cir cuit.

502 Chap ter 19

)2(4]1)2[( valuepresetTMRToscPRperiodPWM •••+=

)4:5:( ><= CCPxCONCCPRxLcycledutyPWM

Page 524: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 19-14 Cir cuit for Test ing Pulse Width Mod u la tion.

In the cir cuit in Fig ure 19-14 two pushbutton switches are wired to ports RA0 and RA1, re spec tively. The pushbutton on port RA0 (la beled PB 1) is used to in creasethe duty cy cle and the one on port RA1 to de crease it. The PWM out put is pro ducedon the CCP1 pin to which an LED is wired.

The pro gram PWM_Demo_873.asm, in this book’s soft ware re source, uses theCCP mod ule of the 16F873 PIC to pro duce pulse width mod u la tion. The pro gramstores the duty cy cle in a lo cal vari able and reads the ac tion on the pushbuttonswitches to in crease or de crease its value. Ini tial iza tion is as follows:

;=============================; main pro gram;=============================main:

banksel ADCON1 ; Se lect bankmovlw b’00000111’ ; Turn off A/D, port Amovwf ADCON1banksel PORTAmovlw b’00000111’ ; In put lines on PORTAtris PORTAmovlw B’00000000’ ; w = 00000000 bi narytris PORTC ; Set up port C for out put

Ad vanced Mo tor Con trols 503

16

F8

73

A

MCLR/Vpp

RA0/AN0

RA1/AN1

RA2/AN2/Vref

RA3/AN3/Vref

RA4/TOCKI

RA5/AN4/SS

Vss

OSC1/CLKIN

OSC2/CLKOUT

RC0/T1OS0/TICK1

RC1/T1OS1/CCP2

RC2/CCP1

RC3/SKL./SCL

1

2

3

4

5

6

7

8

9

10

11

12

13

14

28

27

26

25

24

23

22

21

20

19

18

17

16

15

RB7/PGD

RB6/PGC

RB5

RB4

RB3/PGM

RB2

RB1

RB0/INT

Vdd

Vss

RC7/RX/DT

RC6/TX/CK

RC5/SD0

RC4/SFI/SDA

+5V

+5V

RESET

R=

10

K

Osc (4 MHz)

LEDR = 470 OHM

+5V

+5V

R=10K

R=10K

PB 1

PB 2

CIRCUIT: PWM-DEMO-1CODE: PWM_Demo_873.asm

Page 525: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

bcf PORTC,2 ; CCP1 pin low; Set up reg is ters for PWM

banksel INTCON ; Se lect bankbcf INTCON,GIE ; Dis able global in ter ruptsbcf INTCON,PEIE ; And peripheral in ter ruptsbanksel PIE1bcf PIE1,TMR2IE ; Dis able timer 2 in ter ruptsbcf PIE1,CCP1IE ; Dis able CCP1 in ter ruptsbanksel CCP1CONclrf CCP1CON ; Turn off CCP1 mod ulebanksel PR2movlw .255 ; value to loadmovwf PR2 ; into PWM pe riod reg is terbanksel CCP1CONbcf CCP1CON,5 ; Duty cy cle LSBbcf CCP1CON,4 ; Duty cy cle MSB

; Set ini tial duty cy clebanksel dutyCyclemovlw .128 ; Set ini tial duty cy cle to 50%movwf dutyCycle ; Store in lo cal vari ablebanksel CCPR1Lmovwf CCPR1L ; CCPr1l ;bits 9-2 of duty cy cle

; Set prescaler to 1:1, no postscalerbanksel T2CONmovlw b’00000000’movwf T2CON ; Prescaled set and TMR2 offbanksel TMR2clrf TMR2 ; Clear timer 2banksel CCP1CONmovlw b’00001100’ ; CCP1 in PWM mode and turn onmovwf CCP1CONbanksel T2CONbsf T2CON,2 ; Timer 2 on

Once the CCP hard ware has been in i tial ized to the PWM mode, the pro gram pro -ceeds to turn on the LED to the de fault duty cy cle value, which is 50 per cent of max -i mum. Code then mon i tors ac tion on the two pushbutton switches with a de lay loop. If ac tion on pushbutton # 1 is de tected, the duty cy cle is tested for max i mum and ifnot, it is in cre mented by one unit. Sim i larly, pushbutton # 2 dec re ments the duty cy -cle. Code is as follows:

;===============================================================; in put mon i tor ing rou tine;===============================================================LEDon:; Turn on line 2 in port C. All oth ers re main off

banksel PORTCmovlw B’00000100’ ; LED ONmovwf PORTCcall PBAction ; Test pushbutton ac tioncall de lay ; Lo cal de lay rou tinegoto LEDon

;================================; mon i tor pushbuttons; and up date duty cy cle;================================PBAction:

banksel PORTA

504 Chap ter 19

Page 526: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

btfss PORTA,2 ; De crease but ton pressed?goto DutyDown ; Yes, dec re ment duty cy clebtfss PORTA,0 ; In crease but ton pressed?goto DutyUp ; Yes, in cre ment duty cy clere turn ; No ac tion on switches

DutyUp:banksel dutyCyclemovf dutyCycle,w ; Duty cy cle to Wsublw .255 ; Test for max i mumbanksel STATUSbtfsc STATUS,Z ; Re turn if at max i mumre turn

; Duty cy cle not at max i mum valuebanksel dutyCycleincf dutyCycle,f ; In cre ment duty cy clemovf dutyCycle,w ; Duty cy cle to Wbanksel CCPR1Lmovwf CCPR1L ; To con trol reg is terre turn ; Done

DutyDown:banksel dutyCyclemovf dutyCycle,w ; Duty cy cle to Wsublw 0x00 ; Test for min i mumbanksel STATUSbtfsc STATUS,Z ; Re turn if at min i mumre turn

; Duty cy cle not a min i mum valuebanksel dutyCycledecf dutyCycle,f ; Dec re ment duty cy clemovf dutyCycle,w ; New duty cy cle to Wbanksel CCPR1Lmovwf CCPR1L ; To con trol reg is terre turn ; Done

;================================; de lay sub-rou tine;================================de lay:

banksel jmovlw .200 ; w = 200 dec i malmovwf j ; j = w

jloop:movwf k ; k = w

kloop:decfsz k,f ; k = k-1, skip next if zerogoto kloopdecfsz j,f ; j = j-1, skip next if zerogoto jloopre turn

19.6.3 Microstepping by PWMEar lier in this chap ter we dis cussed how microstepping pro duces a uni form at trac tion on the ro tor through out the step cy cle by mod i fy ing the cur rent ap plied to the wind -ings. The ideal mod i fi ca tion re sults in a sine-shaped wave form. The prac ti cal re sult isthat the at trac tion of the coils on the ro tor is uni form through out the step cy cle andthe mo tor ro tates smoothly. In PIC-based cir cuits, microstepping can be im ple mentedby con trol ling the cur rent in both mo tor coils. A con ve nient way of ac com plish ing thisis by pulse width mod u la tion.

Ad vanced Mo tor Con trols 505

Page 527: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

In Sec tion 19.5 we saw how microstepping can be achieved by vary ing the cur -rent in both coils of a step per mo tor in a sine wave pat tern. Fig ure 19-7 shows howthe sine wave can be off set by 90 degress to gen er ate the sine/co sine pat tern thatpro duces a uni form at trac tion on the ro tor. In prac tice, microstepping can be moreef fec tively im ple mented by keep ing the cur rent in one wind ing con stant while thecur rent in the other one fol lows the sine wave shape. This is shown in Fig ure 19-10,ear lier in this chap ter. This scheme is called high-torque microstepping.

Fig ure 19-15 shows an ex am ple of microstepping us ing the high-torque method.The ex am ple matches the code in the sam ple pro gram PWM_Micstep_1.asm, dis -cussed later in this chap ter and found in this book’s soft ware resource.

Fig ure 19-15 Ex am ple of High-Torque Microstepping.

In Fig ure 19-15, while the cur rent in wind ing B cy cles from 0 to Imax (phase 0)and back to 0 (phase 1), the cur rent in wind ing A is held high. In wind 1 the cur rentin the mo tor wind ings are re versed, that is, the cur rent cy cles from 0 to max andback to 0 in mo tor wind ing A while mo tor wind ing B is held high. In the ex am ple inFig ure 19-15, one com plete it er a tion con sists of 32 steps (0 to 31). The first 32 (0 to31) steps are said to be in wind 0, and the sec ond 32 (32 to 63) are in wind 1. Bothwind 0 and wind 1 have two phases (la beled phase 0 and phase 1 in the illustration).

The ex am ple as sumes a duty cy cle ta ble that en codes six teen current val ues.Dur ing phase 0, the duty cy cle ta ble is read top-to-bot tom, that is, the val ues gofrom low to high. Dur ing phase 1 the duty cy cles are read bot tom-to-top, that is, theval ues go from high to low. Ta ble 19-1 shows the val ues in wind ings A and B forphase 1 of wind 1.

19.6.4 Microstepping Sam ple Pro gram

The sam ple pro gram PWM_Micstep_1.asm, listed later in this chap ter and in thisbook’s soft ware re source, uses the PWM-DEMO-1 cir cuit in Fig ure 19-14 to sim u latemicrostepping us ing PWM. The pro gram ma nip u lates the cur rent on two LEDs wiredto PWM lines CCP1 and CCP2. One LED dem on strates the cur rent in the first wind ingof a step per mo tor, and the other LED the cur rent on the sec ond wind ing.

506 Chap ter 19

0 15 31 47 63 microstepsImax

Imin

wind 0

phase 0 phase 1 phase 1phase 0

wind 1

Winding A

Winding B

Page 528: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Ta ble 19.1

Val ues for Phase 1, Wind 1, in Microstepping Ex am ple in Fig ure 19-15

|<===== microStep (phase 0) | WINDING DUTY CYCLE | A B CCP2 CCP1 0 +1 +sin 5.6 100% 9.8% 1 +1 +sin 11.25 100 20 2 +1 +sin 16.8 100 29 3 +1 +sin 22.5 100 38 4 +1 +sin 28 100 47 5 +1 +sin 33.75 100 56 6 +1 +sin 39 100 63 7 +1 +sin 45 100 71 8 +1 +sin 50.6 100 77 9 +1 +sin 56.25 100 83 10 +1 +sin 61.8 100 88 11 +1 +sin 67.5 100 93 12 +1 +sin 73.1 100 95.6 13 +1 +sin 78.75 100 98 14 +1 +sin 84.35 100 99.5 15 +1 +sin 90 100 100

When run ning the pro gram, while one of the LEDs is at max i mum bright ness theother one is cy cled through the low-to-high-to-low cur rent val ues, with the cor re -spond ing changes in bright ness. The ta ble with the six teen duty cy cle changes iscoded as fol lows:

;*******************************; Duty cy cles ta ble;*******************************dcTable16:

addwf PCL,f ; PCL is pro gram coun ter latchretlw .25 ; 0 - 9.8% of 255retlw .51 ; 1 - 20% retlw .74 ; 2 - 29%retlw .97 ; 3 - 38%retlw .120 ; 4 - 47%retlw .143 ; 5 - 56%retlw .161 ; 6 - 63%retlw .181 ; 7 - 71%retlw .196 ; 8 - 77%retlw .212 ; 9 - 83%retlw .224 ; 10 - 88%retlw .237 ; 11 - 93%retlw .244 ; 12 - 95.6%retlw .250 ; 13 - 98%retlw .254 ; 14 - 99.5%retlw .255 ; 15 - 100%retlw .0 ; end marker

The val ues re turned by the ta ble were ob tained by scal ing the range of a byte-size vari able (256 bits) into six teen equally spaced units that fol low a sine curve.

As sum ing suit able hard ware, the pro gram PWM_Micstep_1.asm can be used todrive a bi po lar step per mo tor in microstep mode. In this case, lines CCP1 and CCP2

Ad vanced Mo tor Con trols 507

Page 529: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

will be con nected to the cor re spond ing mo tor wind ings. In con trol ling a step per mo -tor, vari a tions in the de lay loop will change the motor speed.

19.7 Microstepping ICs

Pre vi ously in this chap ter we saw that high-per for mance step per mo tor con trols re -quire cir cuits and soft ware that en sure cur rent con trol (chop per ac tion) as well asmicrostepping. Each one of these meth ods is not with out prob lems and com pli ca -tions, but com bin ing them in a sin gle cir cuit, driven by a sin gle pro gram, us ingnonspecialized com po nents, can be a daunt ing task. The lack of on line ex am ples ofcir cuits and pro grams that com bine chop ping and microstepping seems to con firmthis thought.

One ap proach is to use PWM tech niques to vary the ref er ence volt age (Vref inSec tion 19.3.1) so that it will fol low the sine curve re quired in microstepping. How -ever, be cause the ref er ence volt age is de pend ent on the par tic u lar mo tor used in the cir cuit, the ac tual duty cy cles ta ble would have to be de vel oped to suit the spe cifichard ware. This means that mo tor, cir cuit, and soft ware driver would have to bematched.

For tu nately, man u fac tur ers of elec tronic com po nents have de vel oped in te gratedcir cuits that sim plify cir cuit de sign and pro gram ming. Al le gro’s A3955 and its an -nounced up date the A4975 are two such chips. Be cause the A4975 is not avail able atthis time, we will dis cuss the A3955, with the ca veat that the A4975 is cur rentlyunder development.

19.7.1 Al le gro 3955 IC

The A3955 is sup plied in six teen-pin DIP and a six teen-pin SOIC pack ages. The chip isde signed to drive a sin gle wind ing of a bi po lar step ping mo tor. Two 3955 ICs will be re -quired in the typ i cal mo tor driver cir cuit. The chip’s out put is rated for 1.5 A and a 50Vop er at ing volt age of con tin u ous load. The IC is rated for con tin u ous out put cur rentsto ±1.5 A and op er at ing volt age to 50V. Step ping con trol is avail able in four selectableres o lu tions: full (2 steps), half (4 steps), quar ter (8 steps), and eighth (16 steps). The3955 con tains in ter nal pulse width mod u la tion hard ware that al lows cur rent con -trol. There is also an in ter nal, three-bit, non lin ear dig i tal-to-an a log con verter that al -lows se lect ing full-, half-, quar ter-, or eighth-step modes.

In ter nal cir cuitry in the 3955 de ter mines whether the PWM current-con trolcircuitry op er ates in a slow re cir cu lat ing current-de cay mode, a fast re gen er a tivecurrent-de cay mode, or in a mixed mode. In the mixed mode, the off-time is di videdinto a pe riod of fast current de cay and one of slow current de cay. The powerful mo -tor con trol pro vided by the 3955 re sults from a com bi na tion of a user-selectablecurrent-sens ing resistor, con trol over the ref er ence voltage, a dig i tally se lected out -put current ra tio, and a selectable slow, fast, or mixed current-de cay mode. Fig ure19-16 shows the pinout of the Al le gro 3955.

508 Chap ter 19

Page 530: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 19-16 Al le gro 3955 Microstepping Mo tor Con trol ler Pinout.

The pin la beled PDF (per cent fast de cay) in Fig ure 19-16 is an an a log in put thatal lows se lect ing one of the avail able cur rent de cay modes; the cur rent al lows se lect -ing the per cent age of fast de cay used by the chip, as fol lows:

Vdpf >= 3.5 V ============> slow cur rent de cay mode

Vpdf <= 0.8 V ============> fast cur rent de cay mode

Vpdf >= 1.1 V <= 3.1 V ===> mixed cur rent de cay mode

In a cir cuit with one or more 3955 ICs, the cur rent de cay mode is se lected bymeans of two ex ter nal re sis tors, as shown in Fig ure 19-17.

Fig ure 19-17 Cur rent De cay Mode Se lec tor Cir cuit.

The fol low ing for mula can be ap plied for find ing the val ues of R1 and R2 in Fig -ure 19-17.

The equa tion as sumes that Vcc = 5.0V.

Al ter na tively, the PDF line can be con nected to any other an a log out put, whichcan be a microcontroller port line. Con trol ling the volt age on this out put al lows se -

Ad vanced Mo tor Con trols 509

A3

95

5

16

15

14

13

12

11

10

9

1

2

3

4

5

6

7

8

Vm

OUT B

D0

GND

GND

SENSE

OUT A

D1

PDF

REF

RC

GND

GND

Vs

PHASE

D2

PDF

Vcc

R2

R1

2

)21(6.0ln100

R

RRPDF

+=

Page 531: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

lect ing any of the three de cay modes. One scheme, sug gested by Al le gro, is to se lectthe slow cur rent de cay mode when the load cur rent is in creas ing. This de cay se lec -tion lim its the switch ing losses in the driver, the iron losses in the mo tor, and im -proves the max i mum rate at which the load cur rent can in crease. When the loadcur rent is de creas ing, the mixed cur rent-de cay mode is then se lected. This pro videsa way of reg u lat ing the load cur rent to the de sired level and pre vents tail ing of thecur rent pro file caused by the mo tor’s back-EMF volt age. The sam ple pro gramPIC873_3955_1.asm in this book’s soft ware re source uses this method of decaymode selection.

Three bits in the 3955, la beled D0, D1, and D2 in the chip’s pinout (Fig ure 19-16),are DAC bits used to con trol the out put cur rent to the mo tor wind ing. Ta ble 19.2shows the var i ous cur rents ac cord ing to the DAC data.

Ta ble 19.2

3955 DAC Bits

D2 D1 D0 CURRENT RATIO (IN %)

H H H 100H H L 92.4H L H 83.1H L L 70.7L H H 55.5L H L 38.2L L H 19.5L L L All Out puts Dis abled

In the cir cuit de vel oped later in this chap ter, code reads the cur rent from alookup ta ble and sets the 3955 DAC bits ac cord ingly.

The 3955 in put pin la beled PHASE (see Fig ure 19-16) con trols the di rec tion ofcur rent flow. These bits must be ma nip u lated dur ing microstepping in or der to gofrom one phase of the sine curve to the next one.

An ex ter nal cur rent-sense re sis tor, the value in put on the ref er ence volt age line(la beled REF in Fig ure 19-16), and the set ting of the three DAC bits, de ter mine thepeak mo tor cur rent. When the three DAC bits are set , the max i mum cur rent lim it ing value is de ter mined by the cur rent-sense re sis tor and the volt age on the 3955 REFline.

19.7.2 3955-Based Cir cuit

The cir cuit de scribed in this sec tion con tains two Al le gro 3955 microstepping ICs thatare driven by a PIC 16F873. The only in put con trol de vice is a four-stage dip switchthat se lects for ward and re verse ro ta tion and one of the four step ping modes. Fig ure19-18 shows the SMB-PIC873-3955-1 cir cuit.

510 Chap ter 19

Page 532: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 19-18 Al le gro 3955-Based Microstepping Cir cuit.

Note in the cir cuit in Fig ure 19-18 that microcontroller PORT B is wired to eightcon trol lines in the 3955. The four high-or der bits of port B go to the three DAC bitsand the PHASE bit of wind ing A in the 3955. The four low-or der bits con nect to thesame con trol lines in wind ing B. Bit num ber 0 in the PIC port C is wired to the per centfast de cay (PDF) line of the 3955 con trol ling wind ing A, and bit 1 of port C con nects to the PDF con trol line of the sec ond 3955.

Ad vanced Mo tor Con trols 511

+5v+5V

+5V+5V

++

A3

95

5

A3

95

5

16

15

14

13

12

11

10

9

16

15

14

13

12

11

10

9

1

2

3

4

5

6

7

8

1

2

3

4

5

6

7

8

Vm

OUT B

D0

GND

GND

SENSE

OUT A

D1

Vm

OUT B

D0

GND

GND

SENSE

OUT A

D1

PDF

REF

RC

GND

GND

Vs

PHASE

D2

PDF

REF

RC

GND

GND

Vs

PHASE

D2

R=

39

K

R=

39

K

R=

10

K

R=

10

K

CIRCUIT: SMB-PIC873-3955-1 CODE: PIC873_3955_1.asm

47uF

47uF

MOTORSUPPLY MOTOR

SUPPLY

R = 0.56 Ohm

R = 0.56 Ohm

R = 1 KR = 1 K

R = 4.99K

R = 4.99K

CONTROL AND TRANSLATOR STAGE

DRIVER STAGE

DIODES: 1N4934 x 8

DRIVER STAGE

+5V+5V

+5V

R=10K x 4

R=10K

SW 4

SW 3

SW 2

SW 1

DIP SWx 4

PFD-A

PFD-B

PH-B

PH-A

D2-B

D2-A

D1-B

D1-A

D0-B

D0-A

bipolarsteppermotor

470 pF

470 pF

16

F8

73

A

MCLR/Vpp

RA0/AN0

RA1/AN1

RA2/AN2/Vref

RA3/AN3/Vref

RA4/TOCKI

RA5/AN4/SS

Vss

OSC1/CLKIN

OSC2/CLKOUT

RC0/T1OS0/TICK1

RC1/T1OS1/CCP2

RC2/CCP1

RC3/SKL./SCL

1

2

3

4

5

6

7

8

9

10

11

12

13

14

28

27

26

25

24

23

22

21

20

19

18

17

16

15

RB7/PGD

RB6/PGC

RB5

RB4

RB3/PGM

RB2

RB1

RB0/INT

Vdd

Vss

RC7/RX/DT

RC6/TX/CK

RC5/SD0

RC4/SFI/SDA

Osc

PFD-APFD-B

PH-APH-B

D2-AD2-B

D1-AD1-B

D0-AD0-B

Page 533: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

19.7.3 3955 Mo tor Driver Pro gram

The pro gram named PIC873_3955_1.asm, listed later in this chap ter and in this book’ssoft ware re source, drives a bi po lar step per mo tor us ing microstepping and au to maticcon trol of the cur rent recirculation path. The pro gram is in ter rupt driven and uses thehard ware in the cir cuit named SMB-PIC873-3955-1 shown in Fig ure 19-18. Code as -sumes that four lines in port A are wired to a four-stage dip switch bank. One switchstage (bit num ber 0) se lects for ward or re verse mo tor ro ta tion. The re main ing threestages in the dip switch, which are wired to PORT B bits 1 to 3, al low se lect ing one offour step ping rates or modes sup ported by the 3955.

The pro gram’s op er a tion starts by initializing ports A, B, and C and set ting up atimer-ac ti vated in ter rupt linked to the pro ces sor’s Timer0 line. The main pro gramloop reads the state of the four dip switches and sets up the cor re spond ing lo calvari ables. Mo tor driv ing takes place within the in ter rupt han dler when the pre setde lay coun ter has ex pired. Code then tests if ro ta tion is for ward or re verse and di -rects con trol to the corresponding routine.

The pro gram uses a thirty-two-step ta ble for se lect ing con trol codes and an otherone for the PFD val ues dur ing each cy cle. Each con trol code ta ble en try has eightsig nif i cant bits that de ter mine the set ting of the three port bits mapped to the DACreg is ters and the phase bit for each 3955 IC, as in the fol low ing code fragment:

; Phase con trols (PH-A and PH-B) and DAC codes (DA-x and DB-x) are

; mapped to PORT B lines, as fol lows:

; 7 6 5 4 3 2 1 0 <====== PORT B BITS

; | | | | | | | |___ PHASE B

; | | | | | | |______ DB-2

; | | | | | |_________ DB-1

; | | | | |____________ DB-0

; | | | |_______________ PHASE A

; | | |__________________ DA-2

; | |_____________________ DA-1

; |________________________ DA-0

The ac tual bit val ues are shown in Ta ble 19-3.

Re fer to Ta ble 19.2 to de ter mine the cur rent ap plied to each wind ing by the DACval ues in Ta ble 19.3.

The PIC873_3955_1.asm pro gram uses a vari able (named skip) to de ter mine howmany steps are skipped dur ing each it er a tion. The skip value is added to the ta blepoint ers so that a skip value of 1 moves the pointer to the next en try, a skip value of 2 skips one ta ble en try, and so forth. By se lect ing val ues of 1, 2, 4, and 8 for the skipvari able code can use the same thirty-two en try ta ble to ex e cute in each of the foursup ported modes. A sec ond ta ble, also with thirty-two en tries, con tains the PFDcon trol codes. The skip vari able is also added to the pointer when read ing this ta -ble. The values from the PFD ta ble are read into port C, which has port lines 0 and 1wired to the cor re spond ing con trols in the 3955.

512 Chap ter 19

Page 534: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Ta ble 19.3

Con trol Data for 32 Microsteps

WINDING A WINDING B STEP D0-A D1-A D2-A PH-A PFDA D0-B D1-B D2-B PH-B PFDB

0 0 1 1 0 0 0 1 1 1 0 1 1 0 1 0 1 0 1 1 1 1 0 1 0 1 0 0 1 1 1 1 2 1 0 0 1 0 1 1 1 1 1 3 0 0 0 ? 0 1 1 1 1 1 4 1 0 0 0 0 1 1 1 1 1 5 0 1 0 0 0 0 1 1 1 1 6 1 1 0 0 0 1 0 1 1 1 7

0 0 1 0 1 0 0 1 1 0 8 1 0 1 0 1 1 1 0 1 0 9 0 1 1 0 1 0 1 0 1 0 10 1 1 1 0 1 1 0 0 1 0 11 1 1 1 0 1 0 0 0 ? 0 12 1 1 1 0 1 1 0 0 0 0 13 0 1 1 0 1 0 1 0 0 0 14 1 0 1 0 1 1 1 0 0 0 15

0 0 1 0 0 0 0 1 0 1 16 1 1 0 0 0 1 0 1 0 1 17 0 1 0 0 0 0 1 1 0 1 18 1 0 0 0 0 1 1 1 0 1 19 0 0 0 ? 0 1 1 1 0 1 20 1 0 0 1 0 1 1 1 0 1 21 0 1 0 1 0 0 1 1 0 1 22 1 1 0 1 0 1 0 1 0 1 23

0 0 1 1 1 0 0 1 0 0 24 1 0 1 1 1 1 1 0 0 0 25 0 1 1 1 1 0 1 0 0 0 26 1 1 1 1 1 1 0 0 0 0 27 1 1 1 1 1 ? 0 0 0 0 28 1 1 1 1 1 1 0 0 1 0 29 0 1 1 1 1 0 1 0 1 0 30 1 0 1 1 1 1 1 0 1 0 31

Note: En tries la beled ? are not sig nif i cant be cause they cor re spond to cy cle steps with no cur rent in the mo tor wind ings.

A prac t i ca l ap p l i ca t ion o f the PIC873_3955_1 .asm pro gram and theSMB-PIC873-3955-1 cir cuit will prob a bly re quire some form of mo tor speed con trol.One pos si ble vari a tion could be a sec ond dip switch block to al low se lect ing amongsev eral pos si ble speeds or a con tin u ous con trol that could be po ten ti om e ter based.In ei ther case sev eral port lines are still free in the cir cuit. Be cause the pro gram isin ter rupt-driven, speed con trol can eas ily be achieved by vary ing the value stored in the vari able named it er a tion, which in the de fault ver sion of the pro gram is readfrom the con stant named DELAY. Ad di tional speed con trol may re quire mod i fy ingthe Timer0 prescaler or the timer pa ram e ters.

Ad vanced Mo tor Con trols 513

Page 535: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

19.8 Demonstration ProgramsThe pro grams listed in the fol low ing sec tion dem on strate the the pro gram ming dis -cussed in this chap ter.

19.8.1 PWM_DEMO_873.asm;============================================================; File: PWM_Demo_873.asm; Date: Feb ru ary 26, 2011; Au thors: Can ton and Sanchez; Pro ces sor: 16F873A;; Pro gram De scrip tion:; Dem on stra tion pro gram for Pulse Width Mod u la tion (PWM) on; the 16F873 PIC. Pro gram uses PWM out put on the CCP1 pin to; con trol the bright ness of an LED wired to this same line.; Two pushbutton switches on ports RA0 and RA1 con trol the; duty cy cle:; pushbutton on RA0 --> in creases duty cy cle; pushbutton on RA1 --> de creases duty cy cle.; Os cil la tor: Murata Erie 4 MHz;; Ref er ence Cir cuit: PWM-DEMO;; 16F873; +------------------+; +5v--res0--------| 1 !MCLR RB7 28|---; PB 0 -->| 2 RA0 RB6 27|---; PB 1 -->| 3 RA1 RB5 26|---; ---| 4 RA2 RB4 25|--- ; ---| 5 RA3 RB3 24|---; ---| 6 RA4 RB2 23|---; ---| 7 RA5 RB1 22|---; GRND ---| 8 Vss RB0 21|---; OSC ---| 9 OSC1 20|--- +5v; OSC ---|10 OSC2 19|--- GRND; ---|11 RC0 RD7 18|--- ; ---|12 RC1/CCP2 RD6 17|--- ; LED (PWM) <--|13 RC2/CCP1 RD5 16|--- ; ---|14 RC3 RD4 15|--- ; +------------------+; Leg end:; res0 = 10K re sis tor OSC = 4 MHz os cil la tor; GRND = ground

;===========================; con fig u ra tion switches;===========================

514 Chap ter 19

Page 536: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; Switches used in __config di rec tive:; _CP_ON Code pro tec tion ON/OFF ; * _CP_OFF ; * _PWRTE_ON Power-up timer ON/OFF; _PWRTE_OFF ; _WDT_ON Watch dog timer ON/OFF ; * _WDT_OFF ; _LP_OSC Low power crys tal oscillator; _XT_OSC Ex ter nal par al lel res o na tor oscillator ; * _HS_OSC High speed crys tal res o na tor (8 to 10 MHz); Res o na tor: Murate Erie CSA8.00MG = 8 MHz ; _RC_OSC Re sis tor/ca pac i tor oscillator (sim plest,; | 20% er ror); |; |_____ * in di cates setup val ues;;=========================; setup and con fig u ra tion;=========================

pro ces sor 16f873Ain clude <p16f873A.inc>__config _HS_OSC & _WDT_OFF & _PWRTE_ON & _CP_OFFerrorlevel -302

;============================================================; vari ables in PIC RAM;============================================================j equ 0x20k equ 0x21dutyCycle equ 0x22;============================================================; m a i n p r o g r a m;============================================================

org 0 ; start at ad dress 0goto main

;=============================; space for in ter rupt han dler;=============================

org 0x08;=============================; main pro gram;=============================main:

banksel ADCON1 ; Se lect bankmovlw b'00000111' ; Turn off A/D, port Amovwf ADCON1banksel PORTAmovlw b'00000111' ; In put lines on PORTAtris PORTA

Ad vanced Mo tor Con trols 515

Page 537: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

movlw B'00000000' ; w = 00000000 bi narytris PORTC ; Set up port C for out putbcf PORTC,2 ; CCP1 pin low

; Set up reg is ters for PWMbanksel INTCON ; Se lect bankbcf INTCON,GIE ; Dis able global in ter ruptsbcf INTCON,PEIE ; And peripheral in ter ruptsbanksel PIE1bcf PIE1,TMR2IE ; Dis able timer 2 in ter ruptsbcf PIE1,CCP1IE ; Dis able ccp1 in ter ruptsbanksel CCP1CONclrf CCP1CON ; Turn off CCP1 mod ulebanksel PR2movlw .255 ; value to loadmovwf PR2 ; into PWM pe riod reg is terbanksel CCP1CONbcf CCP1CON,5 ; Duty cy cle LSBbcf CCP1CON,4 ; Duty cy cle MSB

; Set ini tial duty cy clebanksel dutyCyclemovlw .128 ; Set ini tial duty cy cle to 50%movwf dutyCycle ; Store in lo cal vari ablebanksel CCPR1Lmovwf CCPR1L ;ccpr1l

;bits 9-2 of duty cy cle; Set prescaler to 1:1, no postscaler

banksel T2CONmovlw b'00000000'movwf T2CON ; Prescaled set and TMR2 offbanksel TMR2clrf TMR2 ; Clear timer 2banksel CCP1CONmovlw b'00001100' ; CCP1 in PWM mode and turn onmovwf CCP1CONbanksel T2CONbsf T2CON,2 ; Timer 2 on

;===============================================================; in put mon i tor ing rou tine;===============================================================LEDon:; Turn on line 2 in port C. All oth ers re main off

banksel PORTCmovlw B'00000100' ; LED ONmovwf PORTCcall PBAction ; Test pushbutton ac tioncall de lay ; Lo cal de lay rou tinegoto LEDon

516 Chap ter 19

Page 538: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

;================================; mon i tor pushbuttons; and up date duty cy cle;================================PBAction:

banksel PORTAbtfss PORTA,2 ; De crease but ton pressed?goto DutyDown ; Yes, dec re ment duty cy clebtfss PORTA,0 ; In crease but ton pressed?goto DutyUp ; Yes, in cre ment duty cy clere turn ; No ac tion on switches

DutyUp:banksel dutyCyclemovf dutyCycle,w ; Duty cy cle to Wsublw .255 ; Test for max i mumbanksel STATUSbtfsc STATUS,Z ; Re turn if at max i mumre turn

; Duty cy cle not at max i mum valuebanksel dutyCycleincf dutyCycle,f ; In cre ment duty cy clemovf dutyCycle,w ; Duty cy cle to Wbanksel CCPR1Lmovwf CCPR1L ; To con trol reg is terre turn ; Done

DutyDown:banksel dutyCyclemovf dutyCycle,w ; Duty cy cle to Wsublw 0x00 ; Test for min i mumbanksel STATUSbtfsc STATUS,Z ; Re turn if at min i mumre turn

; Duty cy cle not a min i mum valuebanksel dutyCycledecf dutyCycle,f ; Dec re ment duty cy clemovf dutyCycle,w ; New duty cy cle to Wbanksel CCPR1Lmovwf CCPR1L ; To con trol reg is terre turn ; Done

;================================; de lay sub-rou tine;================================de lay:

banksel jmovlw .200 ; w = 200 dec i malmovwf j ; j = w

jloop:movwf k ; k = w

Ad vanced Mo tor Con trols 517

Page 539: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

kloop:decfsz k,f ; k = k-1, skip next if zerogoto kloopdecfsz j,f ; j = j-1, skip next if zerogoto jloopre turn

end ;END OF PROGRAM

19.8.2 PIC_Chopper.asm

;============================================================; File: PIC_Chop per.asm; Date: Sep tem ber 15, 2011 ; Up date: ; Au thors: Sanchez and Can ton; Pro ces sor: 16F84A; Ref er ence cir cuit: DEMO-SMB-01;; Pro gram De scrip tion:; Pro gram to drive a bi po lar step per mo tor mode with a 16F84A; PIC con trol ling an L297 wired to an L298 driver.; Three tog gle switches wired to port RA1, RA2, and RA3; con trol di rec tion, full or half step modes, and set or clear; the L297 ENABLE line. Pro gram sup ports chop per hard ware.;;===========================; demo board cir cuit ;===========================; All port A lines trissed for in put:; 0 <----- NOT USED; 1 <----- Tog gle switch 1 - CW or CCW di rec tion ; 2 <----- Tog gle switch 2 - Half/full step; 3 <----- Tog gle switch 3 - ENABLE line on/off; Port B lines ; PIC L297; RB0 -----> pin 10 - ENABLE; RB1 -----> pin 17 - Di rec tion; RB2 -----> pin 18 - Step in put; RB3 -----> pin 19 - Full / half step; RB4 <----- |; RB5 <----- |; RB6 <----- |--- NOT USED; RB7 <----- | ; PORT A TOGGLE ; line SW ACTION; 1 1 0 = CW ro ta tion 1 = CCW

518 Chap ter 19

Page 540: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; 2 2 0 = full step 1 = half step; 3 3 1 = ENABLED 0 = DISABLED ;=========================; setup and con fig u ra tion;=========================

pro ces sor 16f84Ain clude <p16f84A.inc>__config _XT_OSC & _WDT_OFF & _PWRTE_ON & _CP_OFFerrorlevel -302

;=====================================================; vari ables in PIC RAM;=====================================================; De clare vari ables at 2 mem ory lo ca tionsj equ 0x0ck equ 0x0dde lay equ 0x0e ; De lay coun ter

;============================================================; m a i n p r o g r a m;============================================================

org 0 ; start at ad dress 0goto Main

;=============================; space for in ter rupt han dler;=============================

org 0x04;=============================; main pro gram;=============================Main:; Tris PORT A for in put

banksel PORTAmovlw B'00011111' ; w = 00011111 bi narytris PORTA ; Set up port A for in put

; Tris port B for out putmovlw B'00000000' ; All lines for out puttris PORTB ; Set up port Bclrf PORTB ; Clear all lines

; Set defalt state for L297 con trol linesmovlw B'00001101'

; ||||__________ 1 = ENABLE; |||___________ 0 = CW; ||____________ 1 = clock pulse; |_____________ 1 = Half step;

movwf PORTB

Ad vanced Mo tor Con trols 519

Page 541: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; Ini tial ize de fault value for de lay vari ablebanksel de laymovlw .120movwf de lay ; To de lay vari able

;===============================================================; main con trol mon i tor ing rou tine;===============================================================ControlRtn:; Call pro ce dure to set L297 lines ac cord ing to state of ; tog gle switches wired to port A

call ReadATogglescall De lay ; De lay nowcall Pulse ; Lo cal pulse mo tor rou tinegoto ControlRtn

;========================================================; Aux il iary procedure to read tog gle switches;========================================================ReadAToggles:; Read PORTA tog gle switches; PORT A TOGGLE ; line SW ACTION; 1 1 0 = CW ro ta tion 1 = CCW; 2 2 0 = full step 1 = half step; 3 3 1 = Set or clear ENABLE line;=============================; set CW or CCW ro ta tion;============================= ; Bit 1 on port A is wired to tog gle switch # 1; Bit 1 on port B is wired to pin 17 of the L297 which; con trols CW and CCW ro ta tion.

banksel PORTAbtfsc PORTA,1goto goCCW ; Set ro ta tion bit to CCW

; Bit clear. Set CWbcf PORTB,1 ; Clear port B line 1goto SetStep

goCCW:bsf PORTB,1

;=============================; set half or full step;=============================SetStep:; Tog gle switch # 2, on port A, line 2, se lects be tween; half step and full step modes. Port B bit 3 is wired; to L297 line 19, which se lects half or full step modes

btfsc PORTA,2goto HalfStep ; Bit is set. Set half step mode

; Bit clear. Set full step mode

520 Chap ter 19

Page 542: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

bcf PORTB,3 ; Clear port B line 2goto TestEnable

HalfStep:bsf PORTB,3

;=============================; en able mo tor con trol line;=============================; Tog gle switch # 3, on port A, line 3, con trols the; L297 ENABLE line, on pin No. 10TestEnable:

btfsc PORTA,3goto En able ; Bit is set. Set ENABLE line

; Bit clear. Dis ablebcf PORTB,0 ; Clear the ENABLE linere turn

En able:bsf PORTB,0 ; Set bit to en ablere turn

;================================; rou tine to pulse the mo tor;================================; L297 CLOCK line is wired to RB2.; Pulse is neg a tive go ingPulse:

banksel PORTBbcf PORTB,2 ; Bring step line highnopnopnopnopbsf PORTB,2 ; Step line lowre turn

;================================; de lay sub-rou tines;================================De lay:

banksel PORTBbsf PORTB,2 ; Step line lowbanksel de laymovf de lay,w ; De lay to w reg is termovwf j ; j = w

Jloop:movwf k ; k = w

Kloop:decfsz k,f ; k = k-1, skip next if zerogoto Kloopdecfsz j,f ; j = j-1, skip next if zero

Ad vanced Mo tor Con trols 521

Page 543: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

goto Jloopre turn

end

19.8.3 PWM_Micstep.asm;============================================================; File: PWM_Micstep.asm; Date: Sep tem ber 19, 2011; Au thors: Sanchez and Can ton; Pro ces sor: 16F873A; Test cir cuit: PWM-DEMO-1;; 16F873; +------------------+; +5v--res0--------| 1 !MCLR RB7 28|--- ; ---| 2 RA0 RB6 27|--- ; ---| 3 RA1 RB5 26|---; ---| 4 RA2 RB4 25|---; ---| 5 RA3 RB3 24|--- ; ---| 6 RA4 RB2 23|--- ; ---| 7 RA5 RB1 22|--- ; GR ---| 8 Vss RB0 21|--- ; OSC ---| 9 OSC1 20|--- +5V; OSC ---|10 OSC2 19|--- GR; ---|11 RC0 RD7 18|--- ; GR-res1-LED ---|12 RC1/CCP2 RD6 17|--- ; GR-res1-LED ---|13 RC2/CCP1 RD5 16|--- ; ---|14 RC3 RD4 15|--- ; +------------------+; Leg end:; res0 = 10K re sis tor OSC = 4 MHz os cil la tor; res1 = 470 Ohm GR = ground ;; Os cil la tor: Murata Erie 4 MHz ;; Pro gram De scrip tion:; Test pro gram for microstepping us ing PWM on the 16F873 PIC.; This test pro gram uses a time-de lay loop to cy cle through; 16 steps of the duty cy cle of a bi po lar step per mo tor.; Duty cy cle is in creased un til it reaches the max i mum, then; de creased un til the min i mum.; The LEDs wired to lines CCP1 and CCP2 dem on strate the; vari a tions in cur rent that re sult from the PWM ac tion.;; Cur rent flow in high torque microstepping

522 Chap ter 19

Page 544: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; Chart shows 16 microsteps per step. ; Leg end: - = Wind ing A (CCP1); o = Wind ing B (CCP2); ; 0......15......31......47......63 <= microsteps; Imax -----------------ooooooooooooooo--------------; o o -- o; o o - - o o; o o - - o o; o o - - o o; o o - - o o; o o - - o o; o o - - o o; I = 0 o o - o o; | | |; | -- wind 0 -- | -- wind 1 --|; | ph 0 | ph 1 | ph 0 | ph 1 |; ; Di a gram:; One com plete it er a tion con sists of 64 steps (0 to 63). The; first 32 (0 to 31) steps are in wind 0 and the sec ond 32; (31 to 63) are in wind 1. Both wind 0 and wind 1 have two; phases (ph 0 and ph 1).;; In op er a tion:; While the cur rent in wind ing B cy cles from to 0 to Imax and; back to 0 (wind 0), the cur rent in wind ing A is held high.; In wind 1 the cur rent wind ings are switched, that is, the; cur rent cy cles from 0 to Imax and back to 0 in wind ing A; while wind ing B is held high. A ta ble in mem ory holds the; val ues for 16 duty cy cles re quired for a PWM-gen er ated sine; curve. Dur ing phase 0, the duty cy cle is read top-to-bot tom; from the duty cy cle ta ble, that is, cur rent val ues go; from low to high. Dur ing phase 1 the duty cy cles are read; bot tom-to-top, that is, cur rent val ues go from high to low.; Phase changes are as fol lows:;; Startup value = 0; PHASE microStep RANGE DIRECTION; 0 0 to 15 in creas ing ; 1 15 to 0 de creas ing ;; Val ues in duty cy cle ta ble for 16 microsteps:;; |<------ microStep (phase 0); | WINDING DUTY CYCLE; | A B CCP2 CCP1 ; 0 +1 +sin 5.6 100 9.8

Ad vanced Mo tor Con trols 523

Page 545: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; 1 +1 +sin 11.25 100 20; 2 +1 +sin 16.8 100 29; 3 +1 +sin 22.5 100 38; 4 +1 +sin 28 100 47; 5 +1 +sin 33.75 100 56; 6 +1 +sin 39 100 63; 7 +1 +sin 45 100 71; 8 +1 +sin 50.6 100 77; 9 +1 +sin 56.25 100 83; 10 +1 +sin 61.8 100 88; 11 +1 +sin 67.5 100 93; 12 +1 +sin 73.1 100 95.6; 13 +1 +sin 78.75 100 98; 14 +1 +sin 84.35 100 99.5; 15 +1 +sin 90 100 100; In wind 0 wind ing B is held high and wind ing A changes; In wind 1 wind ing A is held high and wind ing B changes; In ei ther cy cle:; Phase 0 counts up from microStep 0 to 15; Phase 1 counts down from microStep 15 to 0;;===========================================================; 16F873 con fig u ra tion op tions;===========================================================; Switches used in __config di rec tive:; _CP_ON Code pro tec tion ON/OFF ; * _CP_OFF ; * _PWRTE_ON Power-up timer ON/OFF; _PWRTE_OFF ; _BODEN_ON Brown-out re set en able ON/OFF; * _BODEN_OFF ; * _PWRTE_ON Power-up timer en able ON/OFF; _PWRTE_OFF ; _WDT_ON Watch dog timer ON/OFF ; * _WDT_OFF; _LPV_ON Low volt age IC pro gram ming en able ON/OFF; * _LPV_OFF; _CPD_ON Data EE mem ory code pro tec tion ON/OFF; * _CPD_OFF; OSCILLATOR CONFIGURATIONS: ; _LP_OSC Low power crys tal oscillator; _XT_OSC Ex ter nal par al lel crys tal oscillator ; * _HS_OSC High speed crys tal res o na tor; _RC_OSC Re sis tor/ca pac i tor oscillator; | (sim plest, 20% er ror); |; |_____ * in di cates setup val ues pres ently se lected

524 Chap ter 19

Page 546: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

pro ces sor 16f873A ; De fine pro ces sor#in clude <p16f873A.inc>__CONFIG _CP_OFF & _WDT_OFF & _BODEN_OFF & _PWRTE_ON &

_XT_OSC & _WDT_OFF & _LVP_OFF & _CPD_OFF

; Turn off bank ing er ror mes sageserrorlevel -302

;============================================================; vari ables in PIC RAM;============================================================; De clare vari ables at 2 mem ory lo ca tionsj equ 0x20k equ 0x21microStep equ 0x22 ; Range 0 to 15dutyCycle equ 0x23phase equ 0x24 ; 0 = in creas ing 1 = de creas ingwind equ 0x25 ; 0 = wind ing B held high

; 1 = wind ing A held high;============================================================; m a i n p r o g r a m;============================================================

org 0 ; start at ad dress 0goto main

;=============================; space for in ter rupt han dler;=============================

org 0x04;=============================; main pro gram;=============================main:

banksel ADCON1 ; Se lect bankmovlw b'00000110' ; Turn off A/D, port Amovwf ADCON1banksel PORTAmovlw b'00000101' ; In put lines on PORTAtris PORTA

; Make CCP1 (RC2) and CCP2 (RC1) pins out putmovlw B'00000000' ; w = 00000000 bi narytris PORTC ; Set up port C for out putbcf PORTC,2 ; CCP1 pin low

; Set up reg is ters for PWMbanksel INTCON ; Se lect bankbcf INTCON,GIE ; Dis able global in ter ruptsbcf INTCON,PEIE ; And peripheral in ter ruptsbanksel PIE1bcf PIE1,TMR2IE ; Dis able timer 2 in ter ruptsbcf PIE1,CCP1IE ; Dis able ccp1 in ter rupts

Ad vanced Mo tor Con trols 525

Page 547: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

banksel CCP1CONclrf CCP1CON ; Turn off CCP1 mod ulebanksel PR2banksel CCP2CONclrf CCP2CON ; Turn off CCP2 mod ulebanksel PR2movlw .255 ; value to loadmovwf PR2 ; into PWM pe riod reg is ter

; Set ini tial mi cro step to 15 (max i mum)banksel microStepmovlw .0 ; Set ini tial step num ber

movwf microStep ; Store in lo cal vari ablecall dcTable16 ; Duty cy cle now in w

; Set duty cy cle for both PWM linesmovwf dutyCyclebanksel CCPR1Lmovwf CCPR1L ; ccpr1l bits 9-2 of duty cy clebanksel CCPR2Lmovwf CCPR2L ; ccpr1l bits 9-2 of duty cy clebanksel CCP1CONbcf CCP1CON,5 ; Duty cy cle LSBbcf CCP1CON,4 ; Duty cy cle MSBbanksel CCP2CONbcf CCP2CON,5 ; Duty cy cle LSBbcf CCP2CON,4 ; Duty cy cle MSB

; Set prescaler to 1:1, no postscalerbanksel T2CONmovlw b'00000000'movwf T2CON ; Prescaler set and TMR2 offbanksel TMR2clrf TMR2 ; Clear timer 2banksel CCP1CONmovlw b'00001100' ; CCP1 in PWM mode and turn onmovwf CCP1CONbanksel CCP2CONmovlw b'00001100' ; CCP1 in PWM mode and turn onmovwf CCP2CON

; Set timer 2 con trol banksel T2CONbsf T2CON,2 ; Timer 2 on

; Starts up at low est duty cy cle. Set di rec tion to in creas ingbanksel phaseclrf phase ; In creas ing DC modeclrf wind ; Wind ing A held high, wind ing

; goes low-high-low;===============================================================; rou tine to up date duty cy cle;===============================================================

526 Chap ter 19

Page 548: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; In wind = 0 wind ing A (CCP1) is held high and wind ing B; changes; In wind = 1 wind ing B (CCP2) is held high and wind ing A; changes; In ei ther cy cle:; phase = 0 counts down from microStep 15 to 0; phase = 1 counts up from microStep 0 to 15; wind vari able tog gles when phase vari able changes from 1 to 0NextCycle:

call de lay; Test for up or down di rec tion of duty cy cle up date; phase = 0 to in crease duty cy cle; = 1 to de crease duty cy cle

banksel phasemovf phase,w ; Di rec tion switch to Wbtfsc phase,0 ; Test low-or der bit

; De crease duty cy cle if bit 0 is set goto DecreaseDC ; Goes if bit set to

; de crease duty cy cle rou tinegoto IncreaseDCgoto NextCycle ; Not needed

;==============================; in crease the duty cy cle;==============================IncreaseDC:; In cre ment step count if not at max i mum

banksel microStepmovf microStep,w ; Step count to Wsublw .15 ; Test for max i mumbanksel STATUSbtfsc STATUS,Z ; Re turn if at max i mumgoto Reset2Down ; Re verse di rec tion

; Step count not at max i mum value;========================; next higher microstep;========================

banksel microStepincf microStep,f ; Bump step countmovf microStep,w ; Step count to wcall dcTable16 ; Duty cy cle from ta blemovwf dutyCycle ; Store duty cy clecall NewDCgoto NextCycle

Reset2Down:; Clear di rec tion con trol (phase) and re set step; count. Vari able wind is tog gled.

banksel phasebsf phase,0 ; Set bit 0 to de crease

Ad vanced Mo tor Con trols 527

Page 549: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

banksel microStepmovlw .15 ; Set step num bermovwf microStep ; Store in lo cal vari able

; Tog gle vari able windbanksel windmovf wind,w ; Vari able to wxorlw b'00000001' ; XORing with a 1 bit tog gles

; the op er andmovwf wind ; Put back in reg is tergoto NextCycle

;===============================; de crease the duty cy cle;===============================DecreaseDC:; In cre ment step count if not at max i mum

banksel microStepmovf microStep,w ; Step count to Wsublw .0 ; Test for min i mumbanksel STATUSbtfsc STATUS,Z ; Change di rec tion at max i mumgoto Reset2Up ; Re verse di rec tion

; Step count not at min i mum value;========================; next lower microstep;========================

banksel microStepdecf microStep,f ; Bump step count downmovf microStep,w ; Step count to wcall dcTable16 ; Duty cy cle from ta blemovwf dutyCycle ; Store duty cy clecall NewDC ; Lo cal pro ce duregoto NextCycle

Reset2Up:; Set di rec tion con trol (phase) and re set step; count

banksel phasebcf phase,0 ; Clear bit 0 to in creasebanksel microStepmovlw .0 ; Set step num bermovwf microStep ; Store in lo cal vari ablegoto NextCycle

;========================================================; rou tine to up date PWM reg is ters;========================================================; On en try:; w = new duty cy cle; wind = up date mode

528 Chap ter 19

Page 550: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; if wind = 0 wind ing A is held high and B is cy cled; if wind = 1 wind ing B is held high and A is cy cledNewDC:

banksel windbtfsc wind,0 ; Test low-or der bit

; Wind mode 0 if bit cleargoto WindMode1 ; Goes if bit set

; wind mode 0 pro cess ing; Duty cy cle (still in w) to CCP1

banksel CCPR1Lmovwf CCPR1L ; To con trol reg is terbanksel CCP1CONbcf CCP1CON,5 ; Duty cy cle LSBbcf CCP1CON,4 ; Duty cy cle LSB

; Set duty cy cle to max in CCP2 pinmovlw .255banksel CCPR2Lmovwf CCPR2L ; To con trol reg is terbanksel CCP2CONbcf CCP2CON,5 ; Duty cy cle LSBbcf CCP2CON,4 ; Duty cy cle LSBre turn

WindMode1:; wind mode 0 pro cess ing; Duty cy cle (still in w) to CCP2

banksel CCPR2Lmovwf CCPR2L ; To con trol reg is terbanksel CCP2CONbcf CCP2CON,5 ; Duty cy cle LSBbcf CCP2CON,4 ; Duty cy cle LSB

; Set duty cy cle to max in CCP1 pinmovlw .255banksel CCPR1Lmovwf CCPR1L ; To con trol reg is terbanksel CCP1CONbcf CCP1CON,5 ; Duty cy cle LSBbcf CCP1CON,4 ; Duty cy cle LSBre turn

;================================; de lay sub-rou tine;================================de lay:

banksel jmovlw .200 ; w = 200 dec i malmovwf j ; j = w

jloop:movwf k ; k = w

kloop:

Ad vanced Mo tor Con trols 529

Page 551: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

decfsz k,f ; k = k-1, skip next if zerogoto kloopdecfsz j,f ; j = j-1, skip next if zerogoto jloopre turn

;*******************************; Duty cy cles ta ble;*******************************dcTable16:

addwf PCL,f ; PCL is pro gram coun ter latchretlw .25 ; 0 -- 9.8% of 255retlw .51 ; 1 -- 20% retlw .74 ; 2 -- 29%retlw .97 ; 3 -- 38%retlw .120 ; 4 -- 47%retlw .143 ; 5 -- 56%retlw .161 ; 6 -- 63%retlw .181 ; 7 -- 71%retlw .196 ; 8 -- 77%retlw .212 ; 9 -- 83%retlw .224 ; 10 - 88%retlw .237 ; 11 - 93%retlw .244 ; 12 - 95.6%retlw .250 ; 13 - 98%retlw .254 ; 14 - 99.5%retlw .255 ; 15 - 100%retlw .0 ; end marker

end ;END OF PROGRAM

19.8.4 PIC873_3955.asm;============================================================; File: PIC873_3955.asm; Date: April 19, 2011; Up date: Sep tem ber 21, 2011 ; Au thorS: Sanchez and Can ton; Pro ces sor: 16F873A; Ref er ence cir cuit: SMB-PIC873-3955-1;; Pro gram De scrip tion:; 16F873-based bi po lar mo tor con trol pro gram us ing two Al le gro; A3955 driv ers to im ple ment microstepping and au to matic con trol; of the cur rent recirculation path.; Pro gram uses two 32 en try lookup ta bles. One for the phase; in put flow and A3955 DAC con trol codes and a sec ond ta ble for; the per cent fast de cay (PFD) codes.; PORT B and PORT C lines 0 to 7 are trissed for out put and wired

530 Chap ter 19

Page 552: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; as shown in the di a grams be low.; Phase con trols (PH-A and PH-B) and DAC codes (DA-x and DB-x); are mapped to PORT B lines, as fol lows:;; 7 6 5 4 3 2 1 0 <====== PORT B BITS; | | | | | | | |___ PHASE B; | | | | | | |______ DB-2; | | | | | |_________ DB-1; | | | | |____________ DB-0; | | | |_______________ PHASE A; | | |__________________ DA-2; | |_____________________ DA-1; |________________________ DA-0 ;; Per cent fast de cay codes (PFDA and PFDB) are mapped to PORT C; as fol lows:; 7 6 5 4 3 2 1 0 <====== PORT C BITS; | | | | | | | |___ PFD A; | | | | | | |______ PFD B; |__|__|__|__|__|_________ NOT USED;; PORT A is trissed for in put and lines 0 to 3 are wired to a; tog gle switch. Tog gle switch num ber 1 (TS0) de ter mines for ward; and re verse ro ta tion. Tog gle switches 2, 3, and 4 de ter mine; mode, as fol lows:;; 1 2 3 4; |--------------| ON; | | | | | | ; | v v v v |; |--------------| OFF; | | | |___________ ? ? 1 = 2 microsteps (skip = 4); | | |______________ ? 1 ? = 4 microsteps (skip = 2; | |_________________ 1 ? ? = 8 microsteps (skip = 1); | 0 0 0 = full step (skip = 8); |____________________ 1 = for ward ro ta tion; 0 = re verse ro ta tion ;; THIS VERSI0N IS INTERRUPT DRIVEN.;; Mi cro pro ces sor wir ing di a gram:; 16F873; +------------------+; +5v--res0--------| 1 !MCLR RB7 28|--- D0-A; TS0 (ac tive) ----->| 2 RA0 RB6 27|--> D1-A; TS1 (not ac tive)-->| 3 RA1 RB5 26|--> D2-A; TS2 (not ac tive)-->| 4 RA2 RB4 25|--> PHASE A ; TS3 (not ac tive)-->| 5 RA3 RB3 24|--> D0-B

Ad vanced Mo tor Con trols 531

Page 553: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; ---| 6 RA4 RB2 23|--> D1-B; ---| 7 RA5 RB1 22|--> D2-B; GRND ---| 8 Vss RB0 21|--> PHASE B; OSC ---| 9 OSC1 20|--- +5v; OSC ---|10 OSC2 19|--- GRND; PFB-A <--|11 RC0 RD7 18|--- ; PFB-B <--|12 RC1/CCP2 RD6 17|--- ; ---|13 RC2/CCP1 RD5 16|--- ; ---|14 RC3 RD4 15|--- ; +------------------+; Leg end:; res0 = 10K re sis tor OSC = 4 MHz os cil la tor; GRND = ground ;;===========================================================; 16F873 con fig u ra tion op tions;===========================================================; Switches used in __config di rec tive:; _CP_ON Code pro tec tion ON/OFF ; * _CP_OFF ; * _PWRTE_ON Power-up timer ON/OFF; _PWRTE_OFF ; _BODEN_ON Brown-out re set en able ON/OFF; * _BODEN_OFF ; * _PWRTE_ON Power-up timer en able ON/OFF; _PWRTE_OFF ; _WDT_ON Watch dog timer ON/OFF ; * _WDT_OFF; _LPV_ON Low volt age IC pro gram ming en able ON/OFF; * _LPV_OFF; _CPD_ON Data EE mem ory code pro tec tion ON/OFF; * _CPD_OFF; OSCILLATOR CONFIGURATIONS: ; _LP_OSC Low power crys tal oscillator; _XT_OSC Ex ter nal par al lel crys tal oscillator ; * _HS_OSC High speed crys tal res o na tor; _RC_OSC Re sis tor/ca pac i tor oscillator; | (sim plest, 20% er ror); |; |_____ * in di cates setup val ues pres ently se lected

pro ces sor 16f873A ; De fine pro ces sor#in clude <p16f873A.inc>__CONFIG _CP_OFF & _WDT_OFF & _BODEN_OFF & _PWRTE_ON &

_XT_OSC & _WDT_OFF & _LVP_OFF & _CPD_OFF

; Turn off bank ing er ror mes sageserrorlevel -302

532 Chap ter 19

Page 554: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

;;============================================================; c o n s t a n t s;============================================================DELAY set .5 ; De lay coun ter

;============================================================; vari ables in PIC RAM;============================================================; De clare lo cal vari ables start ing at 0x20w_temp equ 0x20 ; For con text sav ingsta tus_temp equ 0x21pclath_temp equ 0x22j equ 0x23 ; De lay rou tine coun tersk equ 0x24this_cy cle equ 0x25 ; Cur rent cy cle coun terit er a tion equ 0x26 ; It er a tion coun ter used by

; in ter rupt han dlerbounce equ 0x27 ; Debounce coun terdi rec tion equ 0x28 ; Di rec tion con trolskip equ 0x29 ; Num ber of steps to skip in

; microstepping modesmode equ 0x2a ; Stor age for cur rent modew_temp1 equ 0xa0 ; Must also be de fined in bank1;;============================================================; m a i n p r o g r a m;============================================================Start:

org 0 ; start at ad dressgoto Main

;=============================; space for in ter rupt han dler;=============================

org 0x04goto IntServ

;=============================; main pro gram;=============================Main:; Tris PORT A for in put

banksel PORTAclrf PORTA

; Con fig ure port A pins as in putbanksel ADCON1movlw 0x06 ; All pins as dig i tal in putsmovwf ADCON1

Ad vanced Mo tor Con trols 533

Page 555: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

banksel TRISAmovlw 0xcf ; Data pat tern for tris

; reg is tersmovwf TRISA

; Tris ports B and C for out putbanksel PORTBmovlw B'00000000' ;All lines to out puttris PORTCtris PORTBclrf PORTB ; Clear all linesclrf PORTC

; Ini tial ize con trol vari ablesbanksel this_cy cle ; Se lect bank 0clrf this_cy cle

; Ini tial ize the it er a tion coun termovlw DELAY ; Read de laymovwf it er a tion ; Set it er a tion coun ter

;=============================; setup for in ter rupt;=============================; Clear ex ter nal in ter rupt flag (INTF = bit 1)

banksel INTCONbcf INTCON,INTF ; Clear flag

; En able global in ter rupts (GIE = bit 7); En able RB0 in ter rupt (inte = bit 4)

bsf INTCON,GIE ; En able global int (bit 7)bsf INTCON,T0IE ; En able TMR0 over flow in ter rupt

;============================; Set up the OPTION reg is ter;============================

movlw b'01010000'; 7 6 5 4 3 2 1 0 <= OPTION bits; | | | | | |__|__|_____ PS2-PS0 (prescaler bits); | | | | | Val ues for Timer0; | | | | | *000 = 1:2 001 = 1:4; | | | | | 010 = 1:8 011 = 1:16; | | | | | 100 = 1:32 101 = 1:64; | | | | | 110 = 1:128 111 = 1:256; | | | | |______________ PSA (prescaler as sign); | | | | 1 = to WDT; | | | | *0 = to Timer0; | | | |_________________ TOSE (Timer0 edge se lect); | | | 0 = in cre ment on low-to-high; | | | *1 = in cre ment on high-to-low; | | |____________________ TOCS (TMR0 clock source); | | *0 = in ter nal clock; | | 1 = RA4/TOCKI bit source; | |_______________________ INTEDG (Edge se lect)

534 Chap ter 19

Page 556: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; | *0 = fall ing edge; |__________________________ RBPU (Pullup en able); *0 = en abled; 1 = dis abled

banksel OPTION_REGmovwf OPTION_REG ; Copy w to OPTION

; Clear di rec tionbanksel di rec tionclrf di rec tion ; Set di rec tion to CW

; Set ini tial step skip fac tormovlw .1 ; For 8 microstepsmovwf skipclrf mode ; Clear modebsf mode,1 ; De fault mode is 8

; microsteps;===============================================================; main con trol mon i tor ing rou tine;===============================================================ControlRtn:

call ReadATogglesgoto ControlRtn

;========================================================; Aux il iary procedure to read tog gle switches;========================================================ReadAToggles:; Read PORTC tog gle switches; PORT A TOGGLE ; line SW ACTION; 0 1 0 = CW ro ta tion 1 = CCW; 1 2 1 = 2 microsteps (skip = 4); 2 3 1 = 4 microsteps (skip = 2); 3 4 1 = 8 microsteps (skip = 1); 1-2-3 2-3-4 0 = full step (skip = 8) ;=============================; set CW or CCW ro ta tion;============================= ; Bit 0 on port A is wired to tog gle # 1; con trols CW and CCW ro ta tion.

btfsc PORTA,0goto goCCW ; Set ro ta tion bit to CCW

; Bit clear. Set CWclrf di rec tiongoto SetMode

goCCW:movlw .1 ; 1 = coun ter clock wisemovwf di rec tion ;

; Read PORT A bits 1, 2, and 3 to de ter mine mode, as fol lows:

Ad vanced Mo tor Con trols 535

Page 557: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; 1 2 3; | | |___________ ? ? 1 = 2 microsteps (skip = 4); | |______________ ? 1 ? = 4 microsteps (skip = 2; |_________________ 1 ? ? = 8 microsteps (skip = 1); 0 0 0 = full step (skip = 8);; Vari able named mode stores cur rently se lected mode, as fol lows:; 7 6 5 4 3 2 1 0 <== mode vari able bitmap; | | | | | | | |___ NOT USED; | | | | | | |______ 1 = 8 MS mode ac tive; | | | | | |_________ 1 = 4 MS mode ac tive; | | | | |____________ 1 = 2 MS mode ac tive; | | | |_______________ 1 = full step mode ac tive; |__|__|__________________ NOT USED; ; Rou tine logic:; Mode con trol tog gle switches are tested low-to-high. If the; first switch found high cor re sponds to the cur rently se lected; mode (as stored in the mode vari able bits) then no ac tion is; taken. Oth er wise, the cur rent mode is set and the skip fac tor; vari able is in i tial ized. The cy cle coun ter vari able is; cleared and the cur rent mode is stored in the mode vari able.SetMode:; Bits are tested high-to-low

btfsc PORTA,1 ; Test 8 MS switchgoto Try4

; 8 microsteps mode switch is ON; Test to see if this is the cur rent mode

btfsc mode ,1 ; Is 8 MS mode ac tive?goto ExitMode ; Exit if ac tive

; At this point 8 MS mode is new modemovlw .1 ; Skip fac tor for 8 MSmovwf skip ; Store in vari ableclrf this_cy cle ; Re set coun terclrf mode ; Re set cur rent modebsf mode,1goto ExitMode

Try4:btfsc PORTA,2 ; Test 4 MS switchgoto Try2

; 4 microsteps mode switch is ON; Test to see if this is the cur rent mode

btfsc mode ,2 ; Is 4 MS mode ac tive?goto ExitMode ; Exit if ac tive

; At this point 4 MS mode is new modemovlw .2 ; Skip fac tor for 8 MSmovwf skip ; Store in vari ableclrf this_cy cle ; Re set coun ter

536 Chap ter 19

Page 558: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

clrf mode ; Re set cur rent modebsf mode,2goto ExitMode

Try2:btfsc PORTA,3 ; Test 2 MS switchgoto FullStep ; No mode bits are set

; 2 microsteps mode switch is ON; Test to see if this is the cur rent mode

btfsc mode,3 ; Is 2 MS mode ac tive?goto ExitMode ; Exit if ac tive

; At this point 2 MS mode is new modemovlw .4 ; Skip fac tor for 4 MSmovwf skip ; Store in vari ableclrf this_cy cle ; Re set coun terclrf mode ; Re set cur rent modebsf mode,3goto ExitMode

;FullStep:; At this point all three mode con trol switches are OFF.; Set full step mode.; First test to see if this is the cur rent mode

btfsc mode,4 ; Is full step mode ac tive?goto ExitMode ; Exit if ac tive

; Set con trols for full step modemovlw .8 ; Skip fac tor for full stepmovwf skip ; Store in vari ableclrf this_cy cle ; Re set coun terclrf mode ; Re set cur rent modebsf mode,4goto ExitMode

ExitMode:re turn

;==============================================================; in ter rupt ser vice rou tine;==============================================================; Ser vice rou tine re ceives con trol when the timer reg is ter; TMR0 over flows, that is, when 256 timer beats have elapsedIntServ:; First test if source is a Timer0 in ter rupt

banksel INTCONbtfss INTCON,T0IF ; T0IF is Timer0 in ter ruptgoto notTOIF ; Go if not RB0 or i gin

; If so clear the timer in ter rupt flag so that count con tin uesbcf INTCON,T0IF ; Clear in ter rupt flag

; Save con textbanksel w_tempmovwf w_temp ; Save w reg is ter

Ad vanced Mo tor Con trols 537

Page 559: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

swapf STATUS,w ; STATUS to wclrf STATUSmovwf sta tus_temp ; Save STATUSmovf PCLATH,w ; Save PCLATHmovwf pclath_tempclrf PCLATH

;=========================; in ter rupt ac tion;=========================; Dec re ment the it er a tion coun ter. Exit if not zero

banksel it er a tiondecfsz it er a tion,fgoto exitISR ; Con tinue if coun ter not zero

; At this point the de lay count has ex pired so the pro grammed; time has elapsed.; First re set the it er a tion coun ter

movlw DELAY ; Read de laymovwf it er a tion ; Re set it er a tion coun ter

;==========================; de ter mine di rec tion;==========================; Read code and PDF data from ta ble and store in ports

movf this_cy cle,w ; Get cur rent cy clecall CodeTable ; Get con trol code from ta blemovwf PORTB ; Write code to portmovf this_cy cle,w ; Get cur rent cy clecall PFDTable ; Get PFD code from ta blemovwf PORTC ; Write code to port

; Test di rec tion switchbtfss di rec tion,0 ; Test for ward bitgoto For ward

; At this point di rec tion ro ta tion is re versegoto Re verse

; Forward di rec tion rou tineFor ward:; In dex cy cle coun ter ac cord ing to skip fac tor

movf skip,w ; Skip fac tor to waddwf this_cy cle,f ; Add to cy cle coun ter

; Test for cy cle num ber 31 (last one in se quence)btfsc this_cy cle,5 ; 100000 = 32goto Re cy cle ; Re set if at end of cy clegoto exitISR ; Done

Re cy cle:clrf this_cy clegoto exitISR

; Re verse di rec tion rou tineRe verse:; In dex cy cle coun ter ac cord ing to skip fac tor

538 Chap ter 19

Page 560: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

movf skip,w ; Skip fac tor to wsubwf this_cy cle,f ; Sub tract from coun ter

; Test for cy cle num ber 0xff (over flow from cy cle # 0)btfsc this_cy cle,7 ; High bit set in di cates over -

flowgoto Recycle2 ; Re set if at end of cy clegoto exitISR

Recycle2:movlw .31 ; First re verse cy clemovwf this_cy cle ; To cy cle coun tergoto exitISR

;=========================; exit ISR;=========================exitISR:; Re store con text

movf pclath_temp,w ; Re storemovwf PCLATHswapf sta tus_temp,wmovwf STATUSswapf w_temp,f ; Swap file reg is ter in it selfswapf w_temp,w ; re-swap back to w

; Re set in ter ruptnotTOIF:

retfie;;===================================; Con trol data for 32 microsteps;===================================; Each full step con sists of 8 microsteps, as fol lows:; WINDING A WINDING B STEP; D0-A D1-A D2-A PH-A PFDA D0-B D1-B D2-B PH-B PFDB; 0 0 1 1 0 | 0 0 1 1 1 0; 1 1 0 1 0 | 1 0 1 1 1 1; 0 1 0 1 0 | 0 1 1 1 1 2; 1 0 0 1 0 | 1 1 1 1 1 3; 0 0 0 ? 0 | 1 1 1 1 1 4; 1 0 0 0 0 | 1 1 1 1 1 5; 0 1 0 0 0 | 0 1 1 1 1 6; 1 1 0 0 0 | 1 0 1 1 1 7;-----------------------------|---------------------------------; 0 0 1 0 1 | 0 0 1 1 0 8; 1 0 1 0 1 | 1 1 0 1 0 9; 0 1 1 0 1 | 0 1 0 1 0 10; 1 1 1 0 1 | 1 0 0 1 0 11; 1 1 1 0 1 | 0 0 0 ? 0 12; 1 1 1 0 1 | 1 0 0 0 0 13; 0 1 1 0 1 | 0 1 0 0 0 14

Ad vanced Mo tor Con trols 539

Page 561: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; 1 0 1 0 1 | 1 1 0 0 0 15;-----------------------------|---------------------------------; 0 0 1 0 0 | 0 0 1 0 1 16; 1 1 0 0 0 | 1 0 1 0 1 17; 0 1 0 0 0 | 0 1 1 0 1 18; 1 0 0 0 0 | 1 1 1 0 1 19; 0 0 0 ? 0 | 1 1 1 0 1 20; 1 0 0 1 0 | 1 1 1 0 1 21; 0 1 0 1 0 | 0 1 1 0 1 22; 1 1 0 1 0 | 1 0 1 0 1 23;-----------------------------|---------------------------------; 0 0 1 1 1 | 0 0 1 0 0 24; 1 0 1 1 1 | 1 1 0 0 0 25; 0 1 1 1 1 | 0 1 0 0 0 26; 1 1 1 1 1 | 1 0 0 0 0 27; 1 1 1 1 1 | ? 0 0 0 0 28; 1 1 1 1 1 | 1 0 0 1 0 29; 0 1 1 1 1 | 0 1 0 1 0 30; 1 0 1 1 1 | 1 1 0 1 0 31;=============================|================================= ;; Phase con trols (PH-A and PH-B) and DAC codes (DA-x and DB-x); are mapped to PORT B lines, as fol lows:;; 7 6 5 4 3 2 1 0 <====== PORT B BITS; | | | | | | | |___ PHASE B; | | | | | | |______ DB-2; | | | | | |_________ DB-1; | | | | |____________ DB-0; | | | |_______________ PHASE A; | | |__________________ DA-2; | |_____________________ DA-1; |________________________ DA-0 ;; Per cent fast de cay codes (PFDA and PFDB) are mapped to PORT C; as fol lows:; 7 6 5 4 3 2 1 0 <====== PORT C BITS; | | | | | | | |___ PFD A; | | | | | | |______ PFD B; |__|__|__|__|__|_________ NOT USED;; Codes for PORT B lines are stored in the lookup ta ble; CodeTable; Codes for PORT C lines are stored in the lookup ta ble; PFDTable ;CodeTable

540 Chap ter 19

Page 562: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

addwf PCL,f ; Add w to pro gram coun -ter

retlw B'00110011' ; cy cle = 0retlw B'11011011' ; 1retlw B'01010111' ; 2retlw B'10011111' ; 3retlw B'00001111' ; 4retlw B'10001111' ; 5retlw B'01000111' ; 6retlw B'11001011' ; 7

; ---------------------------------------------------------retlw B'00100011' ; 8retlw B'10101101' ; 9retlw B'01100101' ; 10retlw B'11101001' ; 11retlw B'11100000' ; 12retlw B'11101000' ; 13retlw B'01100100' ; 14retlw B'10101100' ; 15

;----------------------------------------------------------retlw B'00100010' ; 16retlw B'11001010' ; 17retlw B'01000110' ; 18retlw B'10001110' ; 19retlw B'00001110' ; 20retlw B'10011110' ; 21retlw B'01010110' ; 22retlw B'11011010' ; 23

;----------------------------------------------------------retlw B'00110010' ; 24retlw B'10111100' ; 25retlw B'01110100' ; 26retlw B'11111000' ; 27retlw B'11110000' ; 28retlw B'11111001' ; 29retlw B'01110101' ; 30retlw B'10111101' ; 31retlw 0x0 ; Safety en try

PFDTableaddwf PCL,f ; Add w to pro gram coun -

terretlw B'00000001' ; cy cle = 0retlw B'00000001' ; 1retlw B'00000001' ; 2retlw B'00000001' ; 3retlw B'00000001' ; 4retlw B'00000001' ; 5

Ad vanced Mo tor Con trols 541

Page 563: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

retlw B'00000001' ; 6

retlw B'00000001' ; 7

; -----------------------------------------------------

retlw B'00000010' ; 8

retlw B'00000010' ; 9

retlw B'00000010' ; 10

retlw B'00000010' ; 11

retlw B'00000010' ; 12

retlw B'00000010' ; 13

retlw B'00000010' ; 14

retlw B'00000010' ; 15

;-------------------------------------------------------

retlw B'00000001' ; 16

retlw B'00000001' ; 17

retlw B'00000001' ; 18

retlw B'00000001' ; 19

retlw B'00000001' ; 20

retlw B'00000001' ; 21

retlw B'00000001' ; 22

retlw B'00000001' ; 23

; ------------------------------------------------------

retlw B'00000010' ; 24

retlw B'00000010' ; 25

retlw B'00000010' ; 26

retlw B'00000010' ; 27

retlw B'00000010' ; 28

retlw B'00000010' ; 29

retlw B'00000010' ; 30

retlw B'00000010' ; 31

retlw 0x0 ; Safety en try

end

542 Chap ter 19

Page 564: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Chap ter 20

Com mu ni ca tions

In this chap ter we fo cus on dig i tal com mu ni ca tions tech niques used in PIC in ter fac ing with I/O de vices, in te grated cir cuits, and other forms of pro gram ma ble logic. Com mu -ni ca tions, in gen eral, re fer to the ex change of in for ma tion fol low ing rules, some timescalled a pro to col. Dig i tal and com puter com mu ni ca tions come in two fla vors: se rialand par al lel. Se rial com mu ni ca tions take place when the data is sent one bit at a timeover the com mu ni ca tions chan nel. In par al lel com mu ni ca tions all the bits that com -pose a sin gle sym bol or char ac ter are sent si mul ta neously.

Pop u lar lore regards se rial com mu ni ca tions as slower than par al lel com mu ni ca -tions, but with mod ern-day tech nol o gies this is of ten not the case, as se rial tech -niques of ten match or even ex cel par al lel meth ods in speed and per for mance.Com puter net works such as Ethernet and fi ber-op tic links are able to achieve highper for mance even though they use se rial bit streams. The pref er ence for se rial over par al lel com mu ni ca tions is of ten more re lated to hard ware, be cause par al lel trans -mis sions re quire more com mu ni ca tion lines than se rial trans mis sions.

20.1 PIC Com mu ni ca tions Over view Many com mu ni ca tions stan dards were cre ated with other in ter face and hard ware re -quire ments in mind and are not ide ally suited for PIC ap pli ca tions. For ex am ple,RS-232-C, a se rial pro to col de vel oped over 35 years ago, orig i nated in an age of tele -type writ ers and mo dems. The volt age lev els and cir cuit re quire ments of RS-232-C arenot suited for PIC hard ware. The more mod ern USB stan dard is more suited to PIC in -ter fac ing, but adopt ing a stan dard, RS-232-C, EIA-485, USB, or any other con ven tion,re quires ad her ing to spe cial con fig u ra tions in hard ware and the use of ad hoc soft -ware pro to cols. This com pli ance with a stan dard co mes at a price of added hard warecom po nents and in creased soft ware com plex ity.

When PIC-based cir cuits must in ter face with other sys tems or de vices that fol low these stan dards, then there is no al ter na tive but to de sign cir cuits and write pro -grams that com ply with the stan dards. On the other hand, when the com mu ni ca -tions take place in ded i cated cir cuits, which do not in ter face with de vices or sys -

543

Page 565: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

t e m s t h a t f o l l o w s t a n d a r d c o m m u n i c a t i o n s p r o t o c o l s , t h e n p u r e P I Ccom mu ni ca tions tech niques and hard ware are of ten sim pler and more ef fec tive. Inother words, ad her ing to a com mu ni ca tions pro to col usu ally im plies an ad di tionalcost in soft ware and hard ware com plex ity. Here are two ex am ples: a PIC-based cir -cuit that in ter faces with a PC through the RS-232-C port would be a case where com -pli ance with RS-232-C is re quired. An other case would be a PIC-based cir cuit thatsends se rial data to an onboard LCD dis play. In this case, the cir cuit and the soft -ware need not com ply with any com mu ni ca tions stan dards or pro to cols. Pro gram -mers of ten re fer to tech niques that use se rial com mu ni ca tions with out the pres enceof spe cial ized hard ware, such as UART or USART chips, as bit-bang ing.

In the fol low ing sec tions, we dis cuss se rial and par al lel com mu ni ca tions at theirmost es sen tial level. In the gen eral lit er a ture, com mu ni ca tions con cerns of ten fo cus on trans mis sion speeds, sys tem per for mance, and min i mum pro cess ing time.Typically, PIC ap pli ca tions do not trans fer large data files or com mu ni cate in ter ac -tively on the Internet or in net works. In a typ i cal PIC ap pli ca tion, com mu ni ca tionfunc tions are used to up load stored data to a PC, some times called data-log ging, orto re ceive small data sets or com mands from a host ma chine. In this con text thereare no ma jor con cerns re gard ing super-fast trans mis sion rates or max i mum per for -mance.

20.2 Se rial Data Trans mis sionSe rial com mu ni ca tions take place by trans mit ting and re ceiv ing data in a stream ofcon sec u tive elec tri cal pulses that rep re sent data bits and con trol codes. The Elec -tronic In dus tries As so ci a tion (EIA) has spon sored the de vel op ment of sev eral stan -dards for se rial com mu ni ca tions, such as RS-232-C, RS-422, RS-423, RS 449, EIA232E,and EIA232F, among oth ers. In this des ig na tion the char ac ters RS stand for the wordsRec om mended Stan dard. The old est, sim plest to im ple ment, and most-used se rialcom mu ni ca tions stan dard is the RS-232-C volt age level con ven tion. In the fol low ingsec tions we pres ent the es sen tial con cepts of the RS-232-C stan dard. Most of the ma te -rial also ap plies to the var i ous up dates of the stan dard. Later in the chap ter we brieflydis cuss the EIA485 Stan dard.

20.2.1 Asyn chron ous Se rial Trans mis sion The in for ma tion in a se rial bit stream is con tained in a time-de pend ent wave form,that is, each bit code (data, con trol, or er ror) is trans mit ted for a fixed time pe riod,known as the baud period. The word baud was cho sen to honor the French sci en tistand in ven tor Jean Maurice Emile Baudot who stud ied var i ous se rial encodings in thelate nine teenth cen tury.

The se rial bit streams used in data trans mis sion fol low a very sim ple en cod ing:one bit is trans mit ted dur ing each baud pe riod. A bi nary 1 bit is rep re sented by aneg a tive volt age level and a bi nary 0 bit by a pos i tive volt age. The line con di tiondur ing the logic 1 trans mis sion is called a mark ing state, and the one for a logic 0 aspac ing state. The baud rate is equal to the num ber of bits per sec ond be ing trans -mit ted or re ceived. Note that the volt age lev els that rep re sent a 1 and a 0 bit inRS232 are some what coun ter-in tu itive, as one would ex pect a logic 1 to be rep re -sented with a pos i tive volt age, and not a neg a tive one.

544 Chap ter 20

Page 566: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

One pos si ble ap proach to send ing in for ma tion bit-by-bit is based on the trans mit -ter and re ceiver clocks be ing syn chro nized at the same fre quency. That is, both re -ceiver and trans mit ter op er ate at the same baud rate. Note that the ex pres sion“syn chro nized at the same fre quency” im plies not only that their clocks have thesame speed, but that the high and the low por tions of the wave form co in cide.

In typ i cal asyn chron ous se rial com mu ni ca tions, bits are trans mit ted as sep a rate groups, usu ally seven to ten bits long. Each group is called a char ac ter. The name“char ac ter” re lates to the fact that in al pha nu meric trans mis sions each bit grouprep re sents one nu meric or al pha betic sym bol. In re al ity, the term “char ac ter” is alsoap plied to con trol codes, er ror codes, and other nonalphanumeric encodings.

Each char ac ter is sent in a frame con sist ing of a start bit, fol lowed by a set ofchar ac ter bits, fol lowed (op tion ally) by a par ity bit, and fi nal ized by one or morestop bits. The se rial line is nor mally held mark ing, that is, at a logic 1 state. Thechange from logic high to logic low, sig naled by the start bit, tells the re ceiver that aframe fol lows. The re ceiver reads the num ber of char ac ter bits ex pected ac cord ingto the adopted pro to col un til a logic high, rep re sented by one or more stop bits,marks the end of the frame.

Fig ure 20-1 shows the dif fer ent el e ments in a se rial com mu ni ca tions bit stream.The term asyn chron ous re flects the fact that the time pe riod sep a rat ing char ac tersis vari able. The trans mit ter holds the line to logic high (mark ing state) un til it isready to send. The start bit (spac ing state) is used to sig nal the start of a new char -ac ter. The start bit is also used by the re ceiver to syn chro nize with the trans mit ter.The logic high and low re gions of the sig nal wave oc cur at the same time. This com -pen sates for drifts and small er rors in the baud rate.

Fig ure 20-1 Se rial Com mu ni ca tions Bit Stream.

Com mu ni ca tions 545

Signal

Protocol (in this example): 1 start bit 8 data bits (character) 1 parity bit (parity even) 1 stop bit

START BIT DATA BITS (10010011 = 0x93)

0 1 0 0 1 0 0 1 1 0 1

PARITY BIT

STOP BIT

MARKING STATEMARKING STATE

Page 567: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

This form of trans mit ting se rial data is called asyn chron ous be cause the re ceiverresynchronizes it self to the trans mit ter us ing the start bit of each frame. The lack ofsyn chro ni za tion does not re fer to the bits within each frame, which must be in fact“syn chro nized,” but to the fact that char ac ters need not come at a fixed time in ter -val.

20.2.2 Syn chro nous Se rial Trans mis sion

An al ter na tive ap proach to asyn chron ous se rial data trans mis sion is one in which thechar ac ters are sent in blocks with no fram ing bits sur round ing them. In asyn chron ouscom mu ni ca tions, each char ac ter is framed by a start and a stop sig nal so that the re -ceiver can know ex actly where the char ac ter bits are lo cated. In syn chro nous com -mu ni ca tions, the sender and re ceiver are syn chro nized with a clock or a sig nal that ispart of the data stream.

In the ory, syn chro nous com mu ni ca tions im plies that char ac ters are sent out at acon stant rate, in step with a clock sig nal. This scheme as sumes that a sep a rate line(or wire) is used for the clock sig nal, al though, in some vari a tions, the clock sig nalis con tained in the trans mit ted char ac ters. Al ter na tively, a clock line can be used tosyn chro nize the mo ment in time at which the re ceiver reads the data line. In ei thercase, it is this con tained clock or com mand sig nal that iden ti fies a syn chro noustrans mis sion.

Most leg acy PC com mu ni ca tions sys tems are asyn chron ous, al though theEIA232F stan dard sup ports both syn chro nous and asyn chron ous meth ods. Themost com mon chip used in PC com mu ni ca tions is the UART (Uni ver sal Asyn chron -ous Re ceiver and Trans mit ter). An al ter na tive chip called the USRT is used for syn -chro nous com mu ni ca tions and the USART (Uni ver sal Syn chro nous/Asyn chron ousRe ceiver and Trans mit ter) sup ports both.

Syn chro nous com mu ni ca tions can be block or bit based. The block-based modesare also called char ac ter-based. In this mode, char ac ters are grouped in blocks witheach block hav ing a start ing flag, sim i lar to the start bit used in asyn chron ous com -mu ni ca tions. Once the re ceiver and the trans mit ter are syn chro nized, the trans mit -ter in serts two or more con trol char ac ters known as syn chro nous idle char ac ters,or SYNs. Then the block is sent and the re ceiver places the data in a mem ory stor age area for later pro cess ing. Bit-ori ented meth ods, on the other hand, are used for thetrans mis sion of bi nary data that is not tied to any par tic u lar char ac ter set.

20.2.3 PIC Se rial Com mu ni ca tions

Se rial com mu ni ca tions are of ten used in PIC pro gram ming, mostly due to the scar cityof avail able port lines. For ex am ple, an ap pli ca tion in which a 16F84 PIC needs to readdata in par al lel from eight DIP switches and dis play the re sult, also in par al lel, in eightLEDs, re quires a to tal of 16 avail able port lines. But the 16F84 has only thir teen lines,eight in Port-B and five in Port-A; there fore, the ap pli ca tion would not be fea si ble.

One pos si ble so lu tion is to find some way of read ing the DIP switches se ri ally;this re quires three lines at most. Al ter na tively, the out put data to the LEDs could be

546 Chap ter 20

Page 568: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

trans mit ted se ri ally, thus re duc ing the to tal lines re quired from six teen for par al leltrans mis sion, to six, or even less for se rial trans mis sion.

PIC com mu ni ca tions can be de signed both asynchronously and syn chro nously.Asyn chron ous modes are used when the same or com pat i ble clock sig nals are avail -able to both re ceiver and trans mit ter. For ex am ple, two PICs both run ning at thesame clock rate can trans mit and re ceive data us ing a sin gle com mu ni ca tions line,plus a com mon ground. PIC-to-PIC asyn chron ous data trans mis sion mode is dem on -strated later in this chap ter with both cir cuit and code.

Asyn chron ous com mu ni ca tions can be im ple mented by in cor po rat ing a ded i -cated IC, such as a UART or USART chip, in the cir cuit. PCs usu ally have one ofthese ICs, or func tion ally equiv a lent ones, in their im ple men ta tion of the se rial port. Some PICs in clude one or more se rial cir cuits, which some times in clude a USARTmod ule. For ex am ple, the 16F877 PIC has two se rial com mu ni ca tion mod ules. Oneof them is the Mas ter Asyn chron ous Se rial Port, or MSSP. The other one is aUSART. Later in this chap ter we pres ent se rial com mu ni ca tions pro gram ming ex am -ples us ing the USART mod ule in the 16F877 PIC. Pro grams us ing the MSSP mod uleare found in the chap ter on EEPROM pro gram ming.

When com mu ni ca tions take place be tween a PIC and a de vice that does not con -tain a clock, or whose clock runs at a dif fer ent speed than the PIC’s, then syn chro -nous com mu ni ca tions is used. For ex am ple, a cir cuit can be de signed us ing a shiftreg is ter IC, such as the 74HC164, that per forms an 8-bit se rial-in, par al lel-out func -tion. In the pre vi ous ex am ple, it is pos si ble to re duce the num ber of trans mis sionlines by con nect ing the eight LEDs to the out put ports of the 74HC164. But the74HC164 con tains no in ter nal clock that runs at the speed of the 16F84. Thus, com -mu ni ca tions be tween the PIC and the shift reg is ter IC (74HC164 in this case) re quire a clock or com mand sig nal trans mit ted through a sep a rate line; that is, a syn chro -nous se rial trans mis sion. In this chap ter we pres ent cir cuits and sam ple code show -ing syn chro nous com mu ni ca tions be tween a PIC and one or more shift reg is ter ICs.

20.2.4 RS-232-C Stan dard

RS-232-C was de vel oped jointly by the Elec tronic In dus tries As so ci a tion (EIA), theBell Tele phone Sys tem, and mo dem and com puter man u fac tur ers. The stan dard hasachieved such wide spread ac cep tance that its name is of ten used as a syn onym for these rial port. EIA232F, pub lished in 1997, is the lat est up date of RS-232-C. To day,RS-232-C is grad u ally be ing re placed by USB for lo cal com mu ni ca tions. USB is faster,has lower volt age lev els, and uses smaller con nec tors that are eas ier to wire. USB hassoft ware sup port in most PC op er at ing sys tems. On the other hand, USB is a morecom plex stan dard, re quir ing more com plex soft ware. Fur ther more, se rial ports areused to di rectly con trol hard ware de vices, such as re lays and lamps, be cause theRS-232-C con trol lines can be eas ily ma nip u lated by soft ware. This is not fea si ble withUSB.

In the fol low ing sec tions we de scribe the es sen tial ter mi nol ogy and com mu ni ca -tions prin ci ples of RS-232-C.

Com mu ni ca tions 547

Page 569: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Es sen tial Con cepts

The RS-232-C con ven tion spec i fies that, with re spect to ground, a voltage more neg a -tive than – 3 V is in ter preted as a 1 bit and a voltage more pos i tive than +3 V as a 0 bit.Se rial com mu ni ca tions, ac cord ing to RS-232-C, re quire that trans mit ter and re ceiveragree on a com mu ni ca tions pro to col. The fol low ing ter mi nol ogy re fers to theRS-232-C com mu ni ca tions pro to col:

• Baud pe riod: The rate of trans mis sion mea sured in bits per sec ond, also called thebaud rate. In se rial pro to cols, the trans mit ter and the re ceiver clocks must be syn -chro nized to the same baud period.

• Mark ing state: The time pe riod dur ing which no data is trans mit ted. Dur ing themark ing pe riod, the trans mit ter holds the line at a steady high voltage, in di cat inglogic 0.

• Spac ing state: The time pe riod dur ing which data is trans mit ted. Dur ing the spac -ing pe riod, the trans mit ter holds the line at a steady low voltage, in di cat ing logic 1.

• Start bit: The tran si tion that in di cates that data trans mis sion is about to start. Thevoltage low state that oc curs dur ing the start bit is called the spac ing state.

• Char ac ter bits: The data stream com posed of five, six, seven, or eight bits that en -code the char ac ter trans mit ted. The least sig nif i cant bit is the first one trans mit ted.

• Par ity bit: An op tional bit, trans mit ted fol low ing the char ac ter bits, used in check -ing for trans mis sion er rors. If even par ity is cho sen, the trans mit ter sets or clearsthe par ity bit so as to make the sum of the char ac ter’s 1 bits and the par ity bit an even num ber. In odd par ity, the sum of 1 bits is an odd num ber. If par ity is not cor rect, there ceiver sets an er ror flag in a spe cial reg is ter.

• Stop bits: One or more logic high bits in serted in the stream fol low ing the char ac -ter bits or the par ity bit, if there is one. The stop bit or bits en sure that the re ceiverhas enough time to get ready for the next char ac ter.

• DTE (Data Ter mi nal Equip ment): The de vice at the far end of the con nec tion. Itis usu ally a com puter or ter mi nal. The DTE uses a male DB-25 con nec tor, and uti -lizes twenty-two of the twenty-five avail able pins.

• DCE (Data Cir cuit-ter mi nat ing Equip ment): Re fers to the mo dem or other ter -mi nal of the tele phone line in ter face. DCE has a fe male DB-25 con nec tor, and uti -lizes the same 22 pins as the DTE for sig nals and ground. DB-9 connectors are alsoused.

• Half-du plex: A sys tem that al lows se rial com mu ni ca tions in both di rec tions, butonly one di rec tion at a time. Half-du plex com mu ni ca tions are rem i nis cent of ra diocom mu ni ca tions where one user says the word “Over” to in di cate the end of trans -mis sion. In other words, half-duplex is sim i lar to a one-lane road in which traf ficcon trol lers at each end can di rect flow in ei ther di rec tion, but only in one di rec tionat a time.

• Full-du plex: A full-duplex sys tem al lows com mu ni ca tion in both di rec tions si mul -ta neously. A full-duplex sys tem is rem i nis cent of a two-lane high way in which traf -fic can flow in both di rec tions at once.

548 Chap ter 20

Page 570: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Se rial Bit Stream

In the RS-232-C pro to col, the trans mis sion/re cep tion pa ram e ters are se lected from arange of stan dard val ues. The fol low ing are the most com mon ones:

Baud rate: 50, 110, 300, 600, 1200, 2400, 4800, 9600, and 19200

Data bits: 5, 6, 7, or 8

Par ity bit: Odd, even, or no par ity

Stop bits: 1, 1.5, or 2

RS-232-C de fines DTE (Data Ter mi nal Equip ment) and DCE (Data Cir cuit-ter -mi nat ing Equip ment), some times called Data Com mu ni ca tions Equip ment. Ac -cord ing to the stan dard, the DTE des ig na tion in cludes both ter mi nals andcom put ers and DCE re fers to mo dems, trans duc ers, and other de vices. The se rialport in a com puter is de fined as a DTE de vice.

Par ity Testing

In RS-232 com mu ni ca tions, a bit called a par ity bit may op tion ally be trans mit tedalong with the data. A par ity bit pro vides a sim ple, but not too re li able, er ror test to de -tect data cor rup tion that takes place dur ing trans mis sion. Par ity can be even, odd, ornone. Even or odd par ity re fers to the num ber of 1 bits in each data byte. The par ity bitim me di ately fol lows the data bits.

If even par ity is se lected, the par ity bit is trans mit ted with a value of 0 if the num -ber of high bits is even. For ex am ple, the bi nary value

0110 0011

con tains a to tal of four 1 bits; there fore, the par ity bit is 0. By the same to ken, if evenpar ity is se lected, then the bi nary value

0101 0001

re quires that the par ity bit be 1. One way of de scrib ing the par ity bit is to say that thebit is set to in di cate a par ity er ror; there fore, it serves as a par ity er ror de tec tor. An -other de scrip tion is that the par ity co in cides with the num ber of 1 bits in the data, plusthe par ity bit. Thus, when even par ity is se lected the par ity bit is added to the num berof 1 bits in the data to pro duce an even num ber.

Odd par ity is the op po site of even par ity. If odd par ity were se lected, then the par -ity bit in the pre vi ous ex am ple would be 0. Given odd or even par ity, the sendercounts the num ber of 1 bits and sets or clears the par ity bit ac cord ingly. The re -ceiver, know ing that the par ity is odd or even, can do like wise to de ter mine if thenum ber of 1 bits re ceived matches the re quired par ity set ting.

Par ity er ror check ing is very prim i tive. In the first place, the par ity er ror doesnot iden tify the bit or bits that cause the er ror. Fur ther more, if an even num ber ofbits are in cor rect, then the par ity bit would not show the er ror. On the other hand,over a long trans mis sion, the par ity check is likely to de tect gar bled data.

Com mu ni ca tions 549

Page 571: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Con nec tors and Wiring

The RS-232-C stan dard re quires spe cific hard ware con nec tors with ei ther twenty-fiveor nine pins. The twenty-five-pin con nec tor is called a D-shell con nec tor, or DB-25.The con nec tor with nine pins is called the 9-pin D-shell con nec tor or DB-9. In ad di -tion, the RJ-45 con nec tor (the name stands for Reg is tered-Jack 45) is used fortwisted-pair ca bles. RJ-45 use in RS-232-C se rial in ter face is reg u lated by theEIA/TIA-561 stan dard. A com mon ap pli ca tion of RJ-45 con nec tors is in Ether net ca -bles. Fig ure 20-2 shows the male DB-25, DB-9, and the fe male RJ-45 con nec tors.

Fig ure 20-2 DB-25, DB-9, and RJ-45 Con nec tors.

The func tion as signed to each pin var ies in the com mon con nec tors. Ta ble 20.1lists the as sig na tion of the RS-232-C lines in the dif fer ent hard ware. The ca ble link -ing DTE and DCE de vices is a par al lel straight-through ca ble with no cross-over orself-con nects.

Ta ble 20.1

Def i ni tion of Com mon RS-232-C Lines

CONNECTOR CODEDB-25 DB-9 RJ-45 FUNCTION NAME DIRECTION

1 4 Ground G 2 3 6 Trans mit data TXD Out put 3 2 5 Re ceive data RXD In put 4 7 8 Re quest to send RTS Out put 5 8 7 Clear to send CTS In put 6 6 Data set ready DSR In put 7 5 Chas sis ground G 8 1 2 Car rier de tect CD 20 4 3 Data ter mi nal ready DTR Out put 22 9 1 Ring in di ca tor RI In put

Null Mo dem

The RS-232-C stan dards de scribe the way a com puter com mu ni cates with a pe riph eral de vice, such as a mo dem. In this case, the DTE and DCE lines serve as a com mu ni ca -tions con trol. In this con text, DTE means data ter mi nal equip ment, such as a com -puter, and DCE is the ab bre vi a tion for data com mu ni ca tion equip ment, such as

550 Chap ter 20

DB-25

DB-9RJ-45

1

1

1

13

2514

96

5

8

Page 572: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

mo dems. Of ten, com mu ni ca tions must take place in an en vi ron ment that does not in -clude a mo dem; for ex am ple, com put ers com mu ni cat ing with each other or with other de vices such as a PIC-based board. In these cases, the use of the DTE/DTE com mu ni -ca tion lines in flow con trol is not well de fined.The com mon RS-232-C con trol and datasig nals ap pear in Ta ble 20.2.

Ta ble 20.2

Def i ni tion of Com mon RS-232-C Lines

SIGNAL NAME DIRECTION PURPOSE

CONTROL SIGNALS Re quest to Send DTE -> DCE DTE wishes to send Clear to Send DTE <- DCE Re sponse to Re quest to

Send Data Set Ready DTE <- DCE DCE ready to op er ate Data Ter mi nal Ready DTE -> DCE DTE ready to op er ate Ring In di ca tor DTE <- DCE DTE re ceiv ing tele phone ring ing sig nal Car rier De tect DTE <- DCE DTE re ceiv ing a car rier sig nal DATA SIGNALS Trans mitted Data DTE -> DCE Data gen er ated by DTE Re ceived Data DTE <- DCE Data gen er ated by DCE

The term null mo dem re fers to sit u a tions in which se rial com mu ni ca tions takeplace with out the pres ence of a mo dem. In this case, the con nec tion be tween thecom mu ni cat ing de vices, usu ally a ca ble, is wired in such a way so as to al low datatrans mis sion with out a mo dem.

In Ta ble 20.1, two pins are used in flow con trol: RTS (re quest to send) and CTS(clear to send). In con ven tional RS232 com mu ni ca tion (as is the case when a com -puter com mu ni cates with a mo dem), the RTS sig nal is an out put and DCE an in put.Be fore a char ac ter is sent, the sender sets the RTS line high to asks the DTE’s per -mis sion. Un til the DTE grants per mis sion, no data is sent. The DTE grants its per -mis sion by set ting the CTS line high. If the DCE can not re ceive new data, it keepsthe CTS sig nal low. This in ter face, which pro vides a sim ple mech a nism for flow con -trol in a sin gle di rec tion, is called a hand shake.

In full-du plex trans mis sion, the hand shake must take place in both di rec tions,that is, both de vices must be able to sig nal their sta tus. The DTR (data ter mi nalready) and DSR (data set ready) sig nals can be used for a sec ond level of flow con -trol. Finally, the CD (car rier de tect) sig nal serves as an in di ca tion of the state of amo dem.

Null Mo dem Ca ble

Im ple menting hand shak ing with out a mo dem re quires that we take into ac count thattwo com mu ni cat ing de vices can ex pect to find cer tain sig nals on given lines. For ex -am ple, a de vice checks the CTS sig nal for a high value be fore send ing data. If the CTSsig nal never goes high, trans mis sion does not take place. When a ca ble is wired so thattwo de vices can com mu ni cate with out one of them be ing a mo dem, the ca ble is said tobe a null mo dem.

Com mu ni ca tions 551

Page 573: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

One sim ple ap proach is to com pletely elim i nate hand shak ing. In this case, ca blewir ing in ter con nects the trans mit and the re ceive lines and the ground wire. The re -main ing pins are left un con nected, as shown in the null mo dem ca ble in Fig ure 20-3.

Fig ure 20-3 Null Mo dem with No Hand shak ing.

The three-wire null mo dem ca ble can be used to in ter face de vices that do not usemo dem con trol sig nals. How ever, if one of the de vices checks one of the hand shakelines, such as RTS/CTS, then the three-wire mo dem ca ble fails. To solve this prob -lem, a mo dem ca ble can be de signed so that the hand shake sig nals are in ter con -nected; for ex am ple, DTS to DSR and vice versa. Not know ing which hand shakesig nals are to be used, man u fac tur ers of stan dard mo dem ca bles usu ally in ter con -nect all hand shake lines, as shown in Fig ure 20-4

Fig ure 20-4 Null Mo dem with Full Hand shak ing.

552 Chap ter 20

DB-9(female)

WIRING DB-9 DB-9 Female Male3 TX---------2 RX2 RX---------3 TX5 GND--------5 GND

DB-9(male)

5 4 3 2 1

1 2 3 4 5

9 8 7 6

6 7 8 9

DB-9(female)

WIRING DB-9 DB-9 Female Male2 RX---------3 TX3 TX---------3 RX4 DTR--------6 DSR5 GND--------5 GND6 DSR--------4 DTR7 RTS--------8 CTS8 CTS--------7 RTS

DB-9(male)

5 4 3 2 1

1 2 3 4 5

9 8 7 6

6 7 8 9

Page 574: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Some vari a tions of the full-hand shake null mo dem con nect the DTR to the CDline at each end. Pin num ber 1 (CD) in both male and fe male con nec tors is dum -mied-out to pin num ber 4 (CDR).

A con ven tional, straight-through se rial ca ble can be con verted to null mo dem bymeans of a com mer cial null mo dem adapter that crosses over the cor re spond ingsig nal lines. A con ti nu ity test is used to de ter mine whether a se rial ca ble is wired asnull mo dem or not. If it is null mo dem, pin num ber 2 on one end would show con ti -nu ity with num ber 3 pin on the other end.

A cir cuit tester is used to di ag nose se rial ca bles. The tester, which is plugged into the port con nec tor, con tains an LED for each of the com mu ni ca tions lines. Whenthe cor re spond ing LED lights up, the line is ac tive. LED col ors in di cate pos i tive orneg a tive volt ages, with green usu ally in di cat ing pos i tive and red neg a tive. The lightpat tern is used to iden tify dif fer ent hand shakes. Fig ure 20-5 shows a DB-25 minitester.

Fig ure 20-4 DB-25 RS232 Line Tester.

20.2.5 EIA-485 Stan dard

EIA-485 pro vides a two-wire, half-du plex se rial con nec tion stan dard, also known asRS-485. This con ven tion pro vides a multipoint con nec tion with dif fer en tial sig nal ing.The con nec tion can be made full-du plex us ing four wires. In this stan dard, data is con -veyed by volt age dif fer ences. One po lar ity rep re sents logic 1 and the re verse one logic0. The stan dard re quires that the dif fer ence of po ten tial be at least 0.2 volts, but anyvolt age be tween +12 and – 7 volts al lows cor rect op er a tion.

EIA-485 does not spec ify a data trans mis sion pro to col, mak ing pos si ble the im -ple men ta tion of sim ple, in ex pen sive lo cal net work and com mu ni ca tions links. Itsdata trans mis sion speeds can reach 35 Mbits/s at dis tances of up to 10 m, and 100Kbit/s at dis tances up to 1200 m. The use of a twisted wire pair and the dif fer en tialbal anced line al lows span ning dis tances of up to 4000 m.

Com mu ni ca tions 553

Page 575: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

EIA-485 is of ten used with com mon UARTs and USARTs to im ple ment low-speeddata com mu ni ca tions that re quire min i mal hard ware. It is also found in pro gram ma -ble logic con trol lers that are used with pro pri etary data com mu ni ca tions sys tems.In fac to ries and other elec tri cally charged en vi ron ments, the dif fer en tial fea ture ofEIA-485 makes it re sis tant to elec tro mag netic in ter fer ence from mo tors and otherequip ment. The stan dard also finds use in large sound sys tems, such as those foundin the aters and mu sic events. EIA-485 does not spec ify any con nec tor.

EIA-485 in PIC-based Sys tems

In PIC-based sys tems, EIA-485 is of ten used to pro vide strong se rial sig nals that cantravel up to 4000 m at high baud rates in noisy elec tri cal en vi ron ments. Only two wiresare needed to carry the EIA-485 sig nals. These are usu ally la beled the A and B lines.Once the A/B data line is es tab lished, up to thirty-two de vices can be con nected to it.The sys tem is re ferred to as an EIA-485 net work.

Im ple menting the EIA-485 net work re quires some way of con vert ing the 485 sig -nal lev els to the TTL-lev els in the PIC cir cuit. This is ac com plished by means of aded i cated IC, such as the Texas In stru ments Dif fer en tial Bus Trans ceiver chipcalled the SN75176. The chip ac tu ally con verts 485 sig nals to RS-232-C TTL-level sig -nals. This al lows de vices that tra di tion ally com mu ni cate over RS-232-C se rial con -nec tions to com mu ni cate over a two-wire EIA-485 net work. Fig ure 20-6 shows thepin di a gram of the SN75176.

Fig ure 20-6 Pinout of the SN75176 IC.

In ad di tion to the SN75176, an EIA-485 cir cuit re quires a 485 chip such as theMAX485. In PIC-based sys tems, the EIA-485 is some times used to com mu ni cate with mul ti ple de vices in a chain. It uses the same 8-bit asyn chron ous se rial com mu ni ca -tions for mat as was de scribed pre vi ously for RS-232-C.

20.3 Par al lel Data Trans mis sion

Par al lel com mu ni ca tions is the pro cess of send ing sev eral bits of data si mul ta -neously over in di vid ual data lines. In the com puter en vi ron ment, par al lel com mu ni ca -

554 Chap ter 20

SN751766

7

81

5

2

3

4

RO

_RE

DE

DI

Vcc

B

A

GND

SN75176 PINOUT

B - Inverting receiver inputVcc - 4.75 to 5.25 V DC RO - Receiver output_RE - Receiver output enable A - Non-inverting receiver inputGND - Ground DI - Driver input DE - Driver output enable

VDC

Page 576: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

tions are of ten as so ci ated with a pop u lar printer in ter face de vel oped by Centronicsand some times called the Centronics or printer in ter face. Orig i nally, the Centronicsinterface was de signed for one-way com mu ni ca tions. Later, it was made bi-di rec -tional, al low ing its use in high-speed data trans fers. The Centronics or par al lel printerin ter face is now con sid ered a leg acy port.

In PIC-based sys tems, par al lel com mu ni ca tions of ten re fer to the gen eral prin ci -ple rather than to the spe cific Centronics im ple men ta tion. For ex am ple, wir ing aneight-line tog gle switch to the eight pins of the 16F85 port-B line pro vides par al lelcom mu ni ca tions be tween the switch and the PIC.

PIC cir cuits that use par al lel data trans fers of fer many ad van tages. In the firstplace, par al lel trans mis sion is fast and the soft ware is sim ple to de velop. The hard -ware im ple men ta tion is straight for ward and does not re quire many ad di tional com -po nents. Ex am ples are con nect ing a mul ti ple tog gle switch to each of the lines of aPIC in put port, or each of the pins of a Seven-Seg ment LED to the var i ous pins of aPIC out put port. The dis ad van tages of par al lel sys tems are the dis tance lim i ta tionsand the cost in sys tem re sources. Fur ther more, par al lel data trans fers do not workwell for data trans mis sion over long dis tances. Many of the cir cuits and pro gramscov ered in pre vi ous chap ters use par al lel data trans mis sion tech niques. Be causePIC-based sys tems rarely com mu ni cate with par al lel print ers or use the Centronicsstan dard for data trans fer, no fur ther dis cus sion of the Centronics stan dard is jus ti -fi able in this con text.

20.3.1 PIC Par al lel Slave Port (PSP)Some PICs are equipped with an 8-bit Par al lel Slave Port mod ule (PSP). At pres ent,the PSP is mul ti plexed onto Port D and is found in PICs of the mid-range fam ily, suchas the 16F877. The PSP is also called the mi cro pro ces sor port.

The PSP mod ule pro vides an in ter face mech a nism with one or more mi cro pro ces -sors. The par al lel slave port has an op er at ing speed of 200 ns with a clock rate of 20MHz, as well as sev eral on-chip pe riph eral func tions for im ple ment ing real-world in -ter faces.In PICs equipped with the PSP, the par al lel slave port func tions are as -signed to port D, with some port E bits pro vid ing con trol sig nals. To ini tial ize PSPmode, data di rec tion bits in the TRISE reg is ter that cor re spond to RD, WR, and CS(TRISE<2:0>) are con fig ured as in puts and the con trol bit PSPMODE (TRISE) is set. When the PSP mode is ac tive, port D is asynchronously read able and writablethrough the chip Se lect (RE2/CS), Read (RE0/RD), and Write (RE1/WR) con trol in -puts. At this time, not many gen eral-pur pose ap pli ca tions for the PSP port havebeen doc u mented, out side of its use as a multi-mi cro pro ces sor in ter face. For thisrea son we have ex cluded PSP pro gram ming from this con text.

20.4 PIC “Free-Style” Se rial Pro grammingThis sec tion is about PIC se rial pro gram ming and cir cuit de sign that does not fol lowany spe cific com mu ni ca tions pro to col. In this sense, we have used the ex pres sion“free-style” as op posed to cir cuits and pro grams con strained by the re quire ments of astan dard or con ven tion. Many self-con tained PIC cir cuits that do not in ter face withstan dard ized com po nents can ben e fit from not hav ing to fol low any spe cific stan dard.

Com mu ni ca tions 555

Page 577: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Later in this chap ter, and in other chap ters in the book, we pres ent ex am ples of PIC cir cuitsand pro grams that fol low es tab lished com mu ni ca tions pro to cols. The ti tles of the cor re -spond ing sec tions re fer to the spe cific stan dards or pro to cols; for ex am ple, the sec tion ti tled “PIC RS-232-C Se rial Pro gram ming” found in this chap ter.

The ad van tages of so-called “free-style” cir cuit de sign and pro gram ming are greater ease inde vel op ment and the use of fewer hard ware com po nents. When de signer and pro gram mer are not con strained by the spec i fi ca tions of a stan dard, the cir cuit can be im ple mented with a min -i mal num ber of hard ware com po nents. By the same to ken, soft ware is sim pler and eas ier tode velop.

The fol low ing ex am ples of free-style com mu ni ca tions sys tems are pre sented in the sec tions that fol low:

1. A PIC-to-PIC com mu ni ca tions cir cuit and pro gram. Two pro grams are re quired: one for the re -ceiver PIC and one for the sender.

2. Se rial-to-par al lel and par al lel-to-se rial cir cuit and pro gram. Cir cuit uses 74HC164 and 74HC165ICs.

20.4.1 PIC-to-PIC Se rial Com mu ni ca tionsPer haps the most ob vi ous and straight for ward mode of PIC se rial com mu ni ca tions is one thattakes place be tween two PICs. In this case, one PIC acts as a sender, or mas ter, and the other oneas a re ceiver or slave, al though it is also pos si ble for sender and re ceiver to ex change roles. Con -sider a cir cuit in which one PIC polls the state of a bank of switches and then sends the re sult se ri -ally to a sec ond PIC that con trols a bank of LEDs to be lighted ac cord ing to the switch set tings.The rea son for this cir cuit is that some PICs may not have a suf fi cient num ber of ports to mon i toreight switches and con trol eight LEDs.

PIC-to-PIC Se rial Com mu ni ca tions Cir cuits

Ac tu ally, the sys tem re quired for one PIC read ing data and se ri ally send ing the re sult to an otherPIC that out puts the data can be vi su al ized as two sep a rate cir cuits. One cir cuit is used to read the state of the eight DIP switches and to send the data se ri ally to an other PIC cir cuit that dis plays the re sults. Fig ure 20-7 shows the two PIC-based cir cuits.

Struc tur ally, the cir cuits in Fig ure 20-7 are quite sim i lar to ones de scribed pre vi ously in thisbook. The bot tom cir cuit con tains eight DIP switches wired to ports RB0 to RB7. Apushbutton switch is wired to port RA2 and an LED to port RA3. The se rial out put is throughport RA1. The cir cuit at the top of Fig ure 20-7 has eight LEDs wired to ports RB0 to RB7.There is a pushbutton on port RA2 and an LED on port RA3. In put into the cir cuit is throughport RA0. In the re main der of this de scrip tion we re fer to the bot tom cir cuit as the sendercircuit and PIC, and the one on the top as the re ceiver circuit and PIC.

The pushbuttons are nec es sary so that sender and re ceiver are syn chro nized. In op er a tion,the re ceiver circuit is first ac ti vated by press ing the switch la beled “re ceive ready.” The LEDon the top cir cuit lights to in di cate the ready state. The sender circuit has an LED la beled“ready” that in di cates its state. The user presses the switch la beled “send ready” in the sendercircuit. At this time, the pro gram in the sender reads the state of the DIP switches and sendsthe data out, one bit at a time, through the line labeled “se rial out” in the diagram. The re -ceiver reads the eight bits in its “se rial in” line and lights the LEDs ac cord ingly.

556 Chap ter 20

Page 578: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 20-7 PIC-to-PIC Se rial Com mu ni ca tions Cir cuits.

Com mu ni ca tions 557

16F84Osc

R=

10

K

R=470 Ohm R=

10

K

RA2

RA3

RA4/TOCKI

MCLR

Vss

RB0/INT

RB1

RB2

RB3

1

2

3

4

5

6

7

8

9

18

17

16

15

14

13

12

11

10

RA1

RA0

OSC1

OSC2

Vdd

RB7

RB6

RB5

RB4

RESET

SENDSEND

READYLED

+5V

SERIALOUT

+5V

+5V

10K RX 8

DIP SW(DATA)

16F84Osc

R=

10

K

R=470 Ohm R=

10

K

RA2

RA3

RA4/TOCKI

MCLR

Vss

RB0/INT

RB1

RB2

RB3

1

2

3

4

5

6

7

8

9

18

17

16

15

14

13

12

11

10

RA1

RA0

OSC1

OSC2

Vdd

RB7

RB6

RB5

RB4

RESET

RECEIVEREADYRECEIVE

READYLED

+5V

SERIALIN

+5V

+5V

R=470Xx8 Ohm

Page 579: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

PIC-to-PIC Se rial Com mu ni ca tions Pro grams

The soft ware con sists of two dif fer ent pro grams, one to run in the sender PIC and onein the re ceiver PIC. Asyn chron ous com mu ni ca tions re quire that sender and re ceiverop er ate at the same data speed. Both de vices need not run at the same clock speed, but both must syn chro nize data trans mis sion and re cep tion at the same clock rate. Be -cause the eas i est way to ac com plish this is to have both PICs use the same os cil la tor at the same speed, we make this as sump tion in the pro grams that fol low.

The in struc tion time and clock rate of a PIC are one-fourth of its clock speed.Thus, a PIC with a 4-MHz clock runs at 1,000,000 cy cles per sec ond, and the de faulttimer speed is

Ap prox i mately 3,906 µs per clock cy cle. Al though 3,906 µs is not a stan dard baud rate,the pres ent ap pli ca tion is self-con tained and there is no need to con form to RS-232-Cor any other pro to col.

Be cause it seems more in tu itive to as so ci ate a high volt age with a logic 1 and alow volt age with a logic 0, we will adopt this con ven tion in the cur rent ap pli ca tion.Nev er the less, we will bor row the char ac ter struc ture from the RS-232-C con ven tion, that is, in for ma tion will con tain a start bit, a se ries of eight data bits, and a stop bit.No par ity is im ple mented. Fig ure 20-8 shows the bit struc ture for one char ac ter inour ap pli ca tion.

Fig ure 20-8 Data Struc ture for PIC-to-PIC Ap pli ca tion.

558 Chap ter 20

1 000 000

2563 906 25

, ,, . .= µs per bit

Signal

Edge ofstart bit Protocol (in this example):

1 start bit 8 data bits (character) no parity bit 1 stop bit

START BIT DATA BITS (10010001 = 0x91)

0 1 0 0 1 0 0 1 0 1

STOP BIT

LOGIC ONE STATE

Page 580: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

The sender pro gram, named SerialSnd, per forms the fol low ing ini tial iza tion op er -a tions:

1. Line RA2 is in i tial ized for in put be cause the pushbutton switch is lo cated on thisline. Lines RB0 to RB7 are also in put, as they are con nected to the DIP switch ar ray.

2. The prescaler is as signed to the Watch dog timer so that chan nel TMR0 runs at fullpro ces sor speed.

3. In ter rupts are dis abled.

Ini tial iza tion code is as fol lows:

; Port-A, bit 2 is in put. All oth ers are out putmovlw b’00000100’ ; Port-A bit 2 is in put ; all oth ers are out puttris porta

; Port-B is all in putmovlw b’11111111’tris portbbsf porta,1 ;Mark ing bit

; Pre pare to set prescalerclrf tmr0clrwdt

; Set up OPTION reg is ter for full timer speedmovlw b’11011000’

; 1 1 0 1 1 0 0 0 <= OPTION bits; | | | | | |__|__|_____ PS2-PS0 (prescaler bits); | | | | | Values for Timer0; | | | | | *000 = 1:2 001 = 1:4; | | | | | 010 = 1:8 011 = 1:16; | | | | | 100 = 1:32 101 = 1:64; | | | | | 110 = 1:128 111 = 1:256; | | | | |______________ PSA (prescaler as sign); | | | | *1 = to WDT; | | | | 0 = to Timer0; | | | |_________________ TOSE (Timer0 edge se lect); | | | 0 = in cre ment on low-to-high; | | | *1 = in cre ment in high-to-low; | | |____________________ TOCS (TMR0 clock source); | | *0 = in ter nal clock; | | 1 = RA4/TOCKI bit source; | |_______________________ INTEDG (Edge se lect); | 0 = fall ing edge; | *1 = ris ing edge; |__________________________ RBPU pullups; 0 = en abled; *1 = dis abled

op tion; Dis able in ter rupts

bcf intcon,5 ; Timer0 over flow dis abled

Com mu ni ca tions 559

Page 581: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

bcf intcon,7 ; Global interupts dis abled

Once in i tial ized, the pro gram per forms the fol low ing func tions:

1. The SEND READY LED is turned on.

2. Code mon i tors the SEND pushbutton switch.

3. Once the switch is pressed, the pro gram turns off the SEND READY LED.

4. The state of the DIP switches is ob tained by read ing RB0 to RB7.

5. The byte from port B is sent through the se rial line.

The fol low ing code frag ment shows the pro ce dure to send se rial data:

;============================================================; pro ce dure to send se rial data;============================================================; ON ENTRY:; lo cal vari able dataReg holds 8-bit value to be; trans mit ted through port la beled serialLN; OPERATION:; 1. The timer at reg is ter TMR0 is set to run at; max i mum clock speed, that is, 256 clock beats.; The timer over flow flag in the INTCON reg is ter; is set when the timer cy cles from 0xff to 0x00.; 2. Each bit (start, data, and stop bits) are sent ; at a rate of 256 timer beats. That is, each bit is; held high or low for one full timer cy cle (256; clock beats.) ; 3. The pro ce dure tests the timer overflow flag; (tmrOVF) to de ter mine when the timer cy cle has; ended, that is when 256 clock beats have passed.;sendData:

movlw 0x08 ; Setup shift coun termovwf bitCount

;=======================; send START bit;=======================; Set line low then hold for 256 timer clock beats.

bcf PORTA,serialLN ; Send start bit; First re set timer

clrf TMR0 ; Re set timer coun terbcf INTCON,tmrOVF ; Re set TMR0 over flow flag

; Wait for 256 timer clock beatsstartBit:

btfss INTCON,tmrOVF ; timer over flow?goto startBit ; Wait un til set

; At this point timer has cy cled. Start bit has endedbcf INTCON,tmrOVF ; Clear over flow flag

560 Chap ter 20

Page 582: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

;========================

; send 8 DATA bits

;========================

; Eight data bits are sent through the se rial line

; start ing with the high-or der bit. The data byte is

; stored in the reg is ter named dataReg. The bits are

; ro tated left to the carry flag. Code as sumes the bit

; is zero and sets the se rial line low. Then the carry

; flag is tested. If the carry is set the se rial line

; is changed to high. The line is kept low or high for

; 256 timer beats.

send8:

rlf dataReg,f ; Bit into carry flag

bcf PORTA,serialLN ; 0 to se rial line

; Code can as sume the bit is a zero and set the line

; low because, if low is the wrong state, it will only

; re main for two timer beats. The re ceiver will not

; check the line for data un til 128 timer beats have

; elapsed, so the er ror will be harm less. In any case,

; there is no as sur ance that the pre vi ous line state is

; the cor rect one, so leav ing the line in its pre vi ous

; state could also be wrong.

btfsc STATUS,c ; Test carry flag

bsf PORTA,serialLN ; Bit is set. Fix er ror.

bitWait:

btfss INTCON,tmrOVF ; Timer cy cled?

goto bitWait ; Not yet

; At this point timer has cy cled.

; Test for end of byte, if not, send next bit

bcf INTCON,tmrOVF ; Clear over flow flag

decfsz bitCount,f ; Last bit?

goto send8 ; not yet

;=========================

; hold MARKING state

;=========================

; All 8 data bits have been sent. The se rial line must

; now be held high (MARKING) for one clock cy cle

bsf PORTA,serialLN ; Mark ing state

markWait:

btfss INTCON,tmrOVF ; Done?

goto markWait ; not yet

;=========================

; end of trans mis sion

;=========================

re turn

Com mu ni ca tions 561

Page 583: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

The code com ments ex plain the rou tine’s op er a tion.

The re ceiv ing pro gram, named SerialRcv, runs in the re ceiver PIC. In this case,the se rial line is RA0. In put from the sender pro gram is re ceived through this line.The pro gram per forms the fol low ing ini tial iza tion op er a tions:

1. Lines RA0 and RA2 are in i tial ized for in put be cause the pushbutton switch is lo -cated on RA2 and RA0 is the se rial in put line. Lines RB0 to RB7 are out put be causethey are wired to the eight LEDs.

2. The prescaler is as signed to the Watch dog timer so that chan nel TMR0 runs at fullpro ces sor speed.

3. In ter rupts are dis abled.

Once in i tial ized, code per forms the fol low ing func tions:

1. The SEND READY LED is turned on.

2. Code mon i tors the RECEIVE READY pushbutton switch.

3. Once the switch is pressed, the pro gram turns on the RECEIVE READY LED.

4.Code then mon i tors the se rial line for the first low that in di cates the lead ing edge ofthe start bit.

5. Once the start bit is de tected, code waits for 128 clock cy cles to lo cate the cen ter ofthe start bit. This syn chro nizes the re ceiver with the sender and ac com mo datessmall tim ing er rors.

6. The eight data bits are then re ceived and stored.

7. Af ter wait ing for the stop bit, code turns off the RECEIVE READY LED and sets theeight LEDs ac cord ing to the data re ceived through the se rial line.

The fol low ing code frag ment is the pro ce dure rcvData from the SerialRcv pro -gram:

;============================================================; pro ce dure to re ceive se rial data;============================================================; ON ENTRY:; lo cal vari able dataReg is used to store 8-bit value; re ceived through port (la beled serialLN); OPERATION:; 1. The timer at reg is ter TMR0 is set to run at; max i mum clock speed, that is, 256 clock beats.; The timer over flow flag in the INTCON reg is ter; is set when the timer cy cles from 0xff to 0x00.; 2. When the START sig nal is re ceived, the code; waits for 128 timer beats so as to read data in; the mid dle of the send pe riod.; 3. Each bit (start, data, and stop bits) is read ; at in ter vals of 256 timer beats.; 4. The pro ce dure tests the timer over flow flag; (tmrOVF) to de ter mine when the timer cy cle has

562 Chap ter 20

Page 584: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; ended, that is when 256 clock beats have passed.;=============================================================rcvData:

clrf TMR0 ; Re set timermovlw 0x08 ; Ini tial ize bit coun termovwf bitCount

;=========================; wait for START bit;=========================startWait:

btfsc PORTA,0 ; Is port A0 low?goto startWait ; No. Wait for mark

;=========================; off set 128 clock beats;=========================; At this point the re ceiver has found the fall ing; edge of the start bit. It must now wait 128 timer; beats to syn chro nize in the mid dle of the sender’s; data rate, as fol lows:; |<========= fall ing edge of START bit; |; |-----|<====== 128 clock beats off set; -----------. | .-------; | | <== SIGNAL; ----------- ; |<---256--->|;

movlw 0x80 ; 128 clock beats off setmovwf TMR0 ; to TMR0 coun terbcf INTCON,tmrOVF ; Clear over flow flag

offsetWait:btfss INTCON,tmrOVF ; Timer over flow?goto offsetWait ; Wait un tilbtfsc PORTA,0 ; Test start bit for er rorgoto offsetWait ; Re cy cle if a false

start;==========================; re ceive data;==========================

clrf TMR0 ; Re start timerbcf INTCON,tmrOVF ; Clear over flow flag

; Wait for 256 timer cy cles for first/next data bitbitWait:

btfss INTCON,tmrOVF ; Timer cy cle end?goto bitWait ; Keep wait ing

; Timer has coun ter 256 beatsbcf INTCON,tmrOVF ; Re set over flow flagmovf PORTA,w ; Read Port-A into w

Com mu ni ca tions 563

Page 585: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

movwf temp ; Store value readrrf temp,f ; Ro tate bit 0 into carry flagrlf rcvReg,f ; Ro tate carry into rcvReg bit 0decfsz bitCount,f ; 8 bits re ceivedgoto bitWait ; Next bit

; Wait for one time cy cle at end of re cep tionmarkWait:

btfss INTCON,tmrOVF ; Timer over flow flaggoto markWait ; keep wait ing

;========================; end of re cep tion;========================

re turn

Nei ther the SerialRcv nor the SerialSnd pro grams con tain any hand shake sig nal.The pro grams rely on the user turn ing on the re ceiver be fore the send func tion is ac -ti vated. If this is not the case, the pro grams fail to com mu ni cate. But look ing at thecir cuit di a gram in Fig ure 20-7, we no tice that there are avail able ports in both re -ceiver and sender cir cuits. The cir cuit de signer could in ter con nect two ports, one in the re ceiver and one in the sender, so as to pro vide a hand shake sig nal.

For ex am ple, lines RA4 in both cir cuits can be in ter con nected. Then Port A, line4, in the sender cir cuit is de fined as in put and the same line as out put in the re -ceiver. The re ceiver could then set the hand shake line high to in di cate that it isready to re ceive. The sender mon i tors this same port and does not start the trans -mis sion of each char ac ter un til it reads that the hand shake line is high. In this man -ner, the re ceiver can sus pend trans mis sion at any time and pre vent data from be inglost. At the same time, the “re ceiver ready” and “send ready” LEDs can be elim i -nated.

20.4.2 Pro gram Using Shift Reg is ter ICs The prob lem of han dling mul ti ple in put and out put lines, which was re solved in thepre vi ous ex am ple by us ing two PICs, can also be tack led by means of spe cial-pur posein te grated cir cuits. The term shift reg is ter re fers to the fact that reg is ter in put andout put are con nected in a way that data is shifted-down a set of flip-flops when the cir -cuits are ac ti vated. Many vari a tions of shift reg is ters ICs are avail able, the most pop u -lar ones be ing se rial-in to se rial-out, par al lel-in to par al lel-out, se rial-in to par al lel-out, and par al lel-in to se rial-out. In shift reg is ter ter mi nol ogy, the in and out terms re fer tothe func tion in the reg is ters them selves and are not re lated to the func tions that theseel e ments per form in a par tic u lar cir cuit. Fig ure 20-9 shows an in put/out put cir cuit us -ing shift reg is ters.

The cir cuit in Fig ure 20-9 shows the use of a par al lel-to-se rial IC (74HC165) thatreads the state of eight in put switches, and a se rial-to-par al lel IC (74HC164) thatout puts data to eight LEDs. With out the shift reg is ter ICs, the cir cuit would re quiresix teen ports, more than those avail able in the 16F84. Using the shift reg is ters, onlysix PIC ports are re quired, leav ing eight ports avail able on the PIC. The dem on stra -tion pro gram for the cir cuit in Fig ure 20-9 is called Serial6465.

564 Chap ter 20

Page 586: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 20-9 In put/out put Cir cuit Us ing Shift Reg is ters.

74HC165 Par al lel-to-Se rial Shift Reg is ter

The 74HC165 (some times called the 165) is a par al lel-in, se rial-out high-speed 8-bitshift reg is ter. Fig ure 20-10 shows the pin-out of the 74HC165.

Com mu ni ca tions 565

16F84

Osc

R=

10

K

R=10K

RA2

RA3

RA4/TOCKI

MCLR

Vss

RB0/INT

RB1

RB2

RB3

DI

5V

0

1

2

3

Vss

Load

CLK0

4

5

6

7

!Hout

Vss

1

2

3

4

5

6

7

8

9

18

17

16

15

14

13

12

11

10

RA1

RA0

OSC1

OSC2

Vdd

RB7

RB6

RB5

RB4

Vcc

7

6

5

4

CLR

CLK

Vcc

Enab

3

2

1

0

DI

Hout

RESET

74HC164

74HC165

+5V

+5V

+5V

+5V

+5V

10K RX 8

DIP SW(DATA)

R=470Xx8 Ohm

Page 587: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 20-10 74HC165 Pin-Out.

In the 165, pins 3 to 6 and 11 to 14 (la beled D0 to D7) are used as par al lel data in -put lines. Normally these pins are con nected to in put sources, such as switches orother two-state de vices. Se rial out put takes place through pin num ber 9, la beled se -rial out put Q. An in verted out put is avail able at pin num ber 7. The shift/load con trolline, at pin num ber 1, is used to latch the data into the shift reg is ters of the 165. Forex am ple, as sume that the 165’s in put lines are con nected to sources that can change state in time. These highs and lows are not re corded in ter nally in the 165 un til theshift/load line is pulsed. When this line is pulsed, line val ues are said to be latched.Af ter the data lines are latched, the 165 clock-line is pulsed in or der to se quen tiallyshift out each of the eight bits stored in ter nally. Shifting takes place with the most-sig nif i cant bit first. The ac tual op er a tions are as fol lows:

1. A lo cal data stor age reg is ter is cleared and a lo cal coun ter is in i tial ized for eight databits.

2. The 165 shift/load line is pulsed to re set the shift reg is ter.

3. The sta tus of the se rial out put line (165 pin num ber 9) can now be read to de ter minethe value of the bit shifted out.

4. The bit is stored in a data reg is ter and the bit coun ter is dec re ment ed. If the last bitwas read, the rou tine ends.

5. If not, the clock line is pulsed to shift-out the next bit. Ex e cu tion con tin ues at Step 3.

The wir ing of the 165 nor mally re quires at least three in ter face lines with the PIC. One line con nects to the 165 se rial out put (pin num ber 9), an other one to the clockline (pin num ber 2), and a third one to the shift/load line (pin num ber 1). The eight data lines of the 165 are nor mally wired to the in put source.

566 Chap ter 20

74HC165

14

15

161

13

2

12

3

11

4

10

5

9

6

7

8

+5Vshift/load

clock inhibit

D0

serial output

clock

D4 D3

D5 D2

D6 D1

D7

serial inputserial output

GND

Page 588: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

The fol low ing code frag ment lists a pro ce dure to in ter face a 16F84 PIC with a74HC165 par al lel-to-se rial shift reg is ter:

;============================================================; con stant def i ni tions from wir ing di a gram;============================================================#de fine clk65LN 1 ;| - 74HC165 lines#de fine loadLN 2 ;|...;============================================================; 74HC165 pro ce dure to read par al lel data and send; se ri ally to PIC;============================================================; OPERATION:; 1. Eight DIP switches are con nected to the in put; ports of a 74HC165 IC. Its out put line Hout,; and its con trol lines CLK and load are con nected; to the PIC’s Port-B lines 0, 1, and 2,; re spec tively; 2. Pro ce dure sets a coun ter (bitCount) for 8; it er a tions and clears a data hold ing reg is ter; (dataReg).; 3. Port-B bits are read into w. Only the lsb of; Port-B is rel e vant. Value is stored in a work ing; reg is ter and the mean ing ful bit is ro tated into; the carry flag, then the carry flag bit is; shifted into the data reg is ter.; 4. The it er a tion coun ter is dec re ment ed. If this; is the last it er a tion the rou tine ends. Oth er wise; the bitwise read-and-write op er a tion is re peated.

in165:clrf dataReg ; Clear data reg is termovlw 0x08 ; Ini tial ize coun termovwf bitCountbcf PORTB,loadLN ; Re set shift reg is terbsf PORTB,loadLN

nextBit:movf PORTB,w ; Read Port-B (only LOB is

; mean ing ful in this rou tine)movwf workReg ; Store value in lo cal

; reg is terrrf workReg,f ; Ro tate LOB bit into carry

; flagrlf dataReg,f ; Carry flag into dataRegdecfsz bitCount,f ; Dec re ment bit coun tergoto shiftBits ; Con tinue if not zero

Com mu ni ca tions 567

Page 589: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Return ; doneshiftBits:

bsf PORTB,clk65LN ; Pulse clockbcf PORTB,clk65LNgoto nextBit ; Con tinue

The pro ce dure in165 is in the pro gram Serial6465 listed at the end of this chap ter.

74HC164 Se rial-to-Par al lel Shift Reg is ter

The cir cuit in Fig ure 20-9 also uses a 74HC164 se rial-to-par al lel shift reg is ter for out -put to the eight LEDs. Fig ure 20-11 shows the pin-out of the 74HC164 IC.

Fig ure 20-11 74HC164 Pinout.

Se rial in put into the 164 is through the in put A line (pin num ber 1). Par al lel out -put is through the lines la beled Q0 to Q7. The re set/clear line (on pin 9) and theclock line (on pin 8) pro vide the con trol func tions. The op er a tions are as fol lows:

1. A lo cal data stor age reg is ter holds the 8-bit value that serves as data in put. A lo calcoun ter is in i tial ized for eight data bits.

2. The 164 shift reg is ter is cleared by puls ing the re set/clear line.

3. The first/next bit of the data op er and is placed on the in put line.

4. Bit is shifted in by puls ing the 164 clock line.

5. Bit coun ter is dec re ment ed. If it goes to zero, the rou tine ends.

6. Oth er wise, the bits in the source op er and are shifted and ex e cu tion con tin ues atStep 3.

The fol low ing code frag ment lists a pro ce dure to in ter face a 16F84 PIC with a74HC164 se rial-to-par al lel shift reg is ter:

;=====================================================

; con stant def i ni tions from wir ing di a gram

;=====================================================

#de fine clockLN 1 ;|

568 Chap ter 20

74HC164

12

13

141

11

2

10

3

9

4

8

5

6

7

+5V

Q7

Q6

Q5

Q4

reset/clear

clock

input A

input B

Q0

Q1

Q2

Q3

GND

Page 590: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

#de fine clearLN 2 ;| => 74HC164 lines #de fine dataLN 0 ;|...;============================================================; 74HC164 pro ce dure to send se rial data;============================================================; ON ENTRY:; lo cal vari able dataReg holds 8-bit value to be; trans mit ted through port la beled serialLN; OPERATION:; 1. A lo cal coun ter (bitCount) is in i tial ized to; 8 bits; 2. Code as sumes that the first bit is zero by; set ting the data line low. Then the high-or der; bit in the data reg is ter (dataReg) is tested.; If set, the data line is changed to high.; 3. Bits are shifted in by puls ing the 74HC164; clock line (CLK).; 4. Data bits are then shifted left and the bit; coun ter is tested. If all 8 bits have been sent,; the pro ce dure re turns. out164:; Clear 74HC164 shift reg is ter

bcf PORTA,clearLN ; 74HC164 CLR clear lowbsf PORTA,clearLN ; then high again

; Init coun termovlw 0x08 ; Ini tial ize bit coun termovwf bitCount

sendBit:bcf PORTA,dataLN ; Set data line low (as sume)

; Using this as sump tion is pos si ble be cause the bit is not; shifted in un til the clock line is pulsed.

btfsc dataReg,highBit ; test num ber bit 7bsf PORTA,dataLN ; Change as sump tion if set

;=========================; pulse clock line;=========================; Bits are shifted in by puls ing the 74HC164 CLK line

bsf PORTA,clockLN ; CLK highbcf PORTA,clockLN ; CLK low

;=========================; Ro tate data bits left;=========================

rlf dataReg,f ; Shift left data bitsdecfsz bitCount,f ; Dec re ment bit coun tergoto sendBit ; Re peat if not 8 bits

;=========================; end of trans mis sion

Com mu ni ca tions 569

Page 591: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

;=========================re turn

It is im por tant to note that se rial com mu ni ca tions that use shift reg is ter ICs arede scribed as syn chro nous. Syn chro nous se rial trans mis sion re quires that the sender and re ceiver use the same clock sig nal, or that the sender pro vide sig nal or pulse soas to in di cate to the re ceiver when to read the next data el e ment from the line. Inthe cir cuits dis cussed in this sec tion, the shift/load, re set/clear, and clock lines pro -vide this syn chro nous in ter face be tween the PIC and the shift reg is ter IC.

The pro gram named Serial6465, in this book’s on line soft ware, is a dem on stra tion of PIC-to-shift reg is ter in ter fac ing.

20.5 PIC Pro to col-Based Se rial Pro grammingIn the pre ced ing sec tions we dis cussed cir cuits and de vel oped soft ware us ing PIC se -rial com mu ni ca tions that did not con form to any par tic u lar pro to col or stan dard. Thisstyle is ad e quate for stand-alone ap pli ca tions and cir cuits. On the other hand,PIC-based cir cuits some times com mu ni cate with sys tems that con form to a spe cificcom mu ni ca tions stan dard, for ex am ple, with a PC through its RS-232-C se rial port. Inthis case, the PIC soft ware and hard ware must con form to the pro to col, at least to anop er a tional min i mum that en sures sat is fac tory in ter fac ing with the pro to col-basedsys tem.

In the con text of pro to col-based pro gram ming, two sit u a tions are pos si ble: ei -ther the PIC in use sup ports the com mu ni ca tions stan dard or pro to col, or it doesnot. In the case of the smaller PICs, such as the 16F84, the soft ware em u lates com -mu ni ca tions pro to cols be cause hard ware pro vides no sup port. The more com plexPICs, on the other hand, of ten con tain hard ware mod ules that pro vide a func tion al -ity equiv a lent to that re quired by the var i ous stan dards. In this sense, mid-range andhigh-range PICs of ten in clude hard ware sup port for one or more com mu ni ca tionstan dards and con ven tions. For in stance, the 16F87X PIC fam ily in cludes an MSSP(Mas ter Syn chro nous Se rial Port) mod ule and a USART (Uni ver sal Syn chro -nous/asyn chron ous Re ceiver and Trans mit ter) mod ule.

In the sec tions that fol low we de velop cir cuits and pro grams for cases in whichthe on-board PIC does not con tain hard ware sup port for the stan dard and for casesin which it does. Ex am ples with PICs that do not pro vide hard ware sup port for se -rial com mu ni ca tions use the 16F84. Ex am ples with PICs that pro vide hard ware se -rial com mu ni ca tions sup port use the 16F877, which con tains an MSSP and a USARTmod ule. The 16F877 cir cuits and ap pli ca tions in this chap ter use the pro ces sor’sUSART mod ule. The 16F877 MSSP mod ule is dem on strated in the chap ter onEEPROM pro gram ming.

20.5.1 RS-232-C Com mu ni ca tions on the 16F84The UART (Uni ver sal Asyn chron ous Re ceiver/Trans mit ter) con trol ler is a se rialcom mu ni ca tions IC found in com put ers and other data com mu ni ca tion de vices. In the PC, the UART was orig i nally Na tional Semi con duc tor INS8250. With the in tro duc tionof the PC AT, IBM changed its se rial IC to the NC16450, an im proved 8250. Later PCs

570 Chap ter 20

Page 592: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

adopted the NS16550A UART as their se rial com mu ni ca tions con trol lers. Other ven -dors, in clud ing Intel and West ern Dig i tal, fur nish clones of the NS16550A and otherUARTs.

The UART-based se rial port im ple men ta tion and cir cuitry in the PC is com pli antwith RS/EIA232. For a PIC-based cir cuit to com mu ni cate with a PC’s se rial port, itmust ei ther im ple ment in hard ware or em u late in soft ware the RS-232 sig nals andpro to col. One pos si bil ity is to in clude a UART or UART-like IC in the cir cuit. Butthis op tion is not sim ple to im ple ment be cause RS-232-C re quires volt age lev els thatare not TTL-com pat i ble.

For PIC-based sys tems with out a UART module, a vi a ble ap proach is to em u lateUART func tions in soft ware, at least those re quired for in ter fac ing with the PC hard -ware. This is quite fea si ble due to the avail abil ity of ded i cated ICs that pro videRS-232-C-com pat i ble sig nals and voltage lev els in sys tems in which a ±12 voltsource is not avail able. These chips, some times called RS-232-C Driv ers/Re ceiv ersor Trans ceiv ers, are es pe cially use ful in in ter fac ing UART and USART-based sys -tems with PIC-based hard ware.

RS-232-C Trans ceiver IC

RS-232-C in ter face ICs are avail able from sev eral ven dors, al though the ones fromDal las Semi con duc tors’ Maxim line are prob a bly the most pop u lar. These chips, some -times called RS-232-C driver/re ceiv ers, have in com mon the use of so-calledcharge-pump DC/DC con vert ers that gen er ate, from the +5- volt TTL power source,the po lar i ties and volt age lev els re quired by RS-232-C.

One of the most pop u lar im ple men ta tions of the RS-232-C trans ceiver used inPIC-based sys tems is the MAX232 and its up grade, the MAX202. One im prove mentin the MAX202 is to pro vide some de gree of hu man-body elec tro static dis chargepro tec tion (ESD), a de sir able fea ture in ex per i menter boards. Other ver sions arethe MAX233 and MAX203, which do not re quire ex ter nal ca pac i tors. Other RS-232-Ctrans ceiver ICs with var i ous ad di tional fea tures, such as au to matic shut down, areavail able. Fig ure 20-12 is a pin-out of the MAX232 and MAX202 ICs.

Fig ure 20-12 MAX202 and MAX232 Trans ceiver Pinout.

Com mu ni ca tions 571

MAX202MAX232

+5V

GND

D1out (RS-232)

R1in (RS-232)

R1out (TTL)

D1in (TTL)

D2in (TTL)

R2out (TTL)

C1+

V+

C1-

C2+

C2-

V-

(RS-232) D2out

(RS-232) R2in

16

15

14

13

12

11

10

9

1

2

3

4

5

6

7

8

Page 593: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Note that the MAX232 and MAX202 con sist of two driv ers and two re ceiv ers per chip.Lines 14 and 7 (la beled D1out and D2out) pro vide RS-232-C out put. Lines 13 and 8 (la beled R1in and R2in) are RS-232-C in put. Lines 10 and 11 (la beled D1in and D2in) are TTL (orCMOS) in puts. Lines 9 and 12 (la beled R2out and R1out) are TTL out put. In this des ig na -tion the let ter R stands for re ceiver and the let ter D for driver. The digit 1 in di cates the firstdriver/re ceiver set and the digit 2 the sec ond one. The lines la beled D are wired to ca pac i -tors.

A cir cuit us ing the trans ceiver ICs is sim ple and easy to build. If a sin gle com mu ni ca tion line is re quired, then the TTL in put line can be wired to pin 10 (D2in) and the TTL out put to pin 9 (R2out). The RS-232-C in put is wired to pin 8 (R2in) and the out put to pin 7 (D2out).Later in this sec tion we pres ent a cir cuit that uses the MAX202 with a 16F84 PIC.

PIC-to-PC Com mu ni ca tions

Of ten, a PIC-based cir cuit has to com mu ni cate with a de vice that con forms to a stan dardcom mu ni ca tions pro to col. One of the most com mon cases is a PIC board that in ter faces witha com puter, usu ally a PC or Mac with an RS-232-C port. For ex am ple, a PIC board is placedsome where to col lect in for ma tion, such as tem per a ture, pres sure, and hu mid ity. Be fore thein ter nal stor age ca pac ity of the PIC board is ex hausted, it is con nected to a lap top PC and thedata is down loaded from the PIC board to the com puter. Once this is done, then the lo cal PICmem ory is cleared so that new data can be col lected and stored. This ap pli ca tion, called adata log ger, re quires some way of trans fer ring data from the PIC-based board to the PC. TheRS-232-C line is of ten avail able on the PC end and the re quired in ter face hard ware and pro -gram ming are un com pli cated.

On the PC end, the com mu ni ca tions soft ware can be off-the-shelf ap pli ca tions or spe -cially de vel oped pro grams. If the pur pose is sim ply to down load data to the PC or sendsim ple com mand to the PIC board, then a stan dard util ity is used. For ex am ple, the Win -dows pro gram named Hy per Ter mi nal al lows send ing and re ceiv ing files and com mandsat var i ous baud rates and RS-232-C com mu ni ca tions pa ram e ters. Hy per Ter mi nal is in -cluded with most Win dows ver sions or can be down loaded free from the de vel oper’swebsite.

The PIC board must have a sys tem that con forms to the com mu ni ca tions pro to col ofthe de vice, in this case, the PC. In or der to use the PC’s se rial port, PIC hard ware and soft -ware must be able to gen er ate re quired sig nal lev els, baud rate, and other RS-232-C com -mu ni ca tions pa ram e ters. Hard ware in ter fac ing is im ple mented us ing a trans ceiver chip,such as the MAX232 or 202 pre vi ously de scribed. If the PIC con tains a UART or USARTmod ule, then the com mu ni ca tions soft ware is easy to de velop. This case is ex plored laterin this chap ter.

RS-232-C TTY Board

The terms tele type and tele type writer re fer to an ob so lete elec tro me chani cal type writer thatwas used to send and re ceive in for ma tion through a sim ple com mu ni ca tion chan nel. In amod ern sense, TTY re fers to a sim ple style of com mu ni ca tions where the same de vice sendsand re ceives text mes sages in ter ac tively. The current board is ac tu ally a TTY re ceiver be -cause it does not con tain a key board that al lows sending data. Fig ure 20-13 shows the cir -cuit di a gram for a 16F84-based PC-to-PIC se rial com mu ni ca tions board.

572 Chap ter 20

Page 594: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure 20-13 PC-to-PIC Se rial Com mu ni ca tions Cir cuit.

The cir cuit in Fig ure 20-13 con tains pre vi ously dis cussed com po nents. The LCDis wired in 4-bit mode, with con trol lines for RS (re set), E (pulse), and R/W(read/write). The MAX202 pro vides the TTL-to-RS-232-C con ver sion and vice versa.The phys i cal con nec tion be tween the PC and the PIC board is by means of a DB-9con nec tor and a stan dard null mo dem ca ble. The ca ble is not shown in the cir cuit di -a gram.

16F84A UART Em u la tion

The 16F84A PIC con tains no built-in fa cil i ties for RS-232-C com mu ni ca tions;therefore, a 16F84A ap pli ca tion that com mu ni cates through the se rial port us ing theRS-232-C pro to col must em u late the pro to col in soft ware. The pro grams pre vi ouslyde vel oped for PIC-to-PIC com mu ni ca tions, dis cussed in Sec tion 20.3.1, serve as abase for the UART em u la tion ap pli ca tion. The ma jor dif fer ences be tween a “free-style” PIC com mu ni ca tions pro gram and one that com plies with RS-232-C are the fol -low ing:

Com mu ni ca tions 573

MAX202

+5V

+5V

R=

10

K

R=

10

K

1

2

3

4

5

6

7

8

16

15

14

13

12

11

10

9

Vcc

GND

T1out

R1in

R1out

T1in

T2in

R2out

C1+

V+

C1-

C2+

C2-

V-

T2out

R2in

RESET

HD44780

LCD2 rows x 16

+5V

+5V

E

R/W

RS

RS

R/W

E

1

14

DB-9(female)

5 4 3 2 1

9 8 7 6

16F84

RA2

RA3

RA4/TOCKI

MCLR

Vss

RB0/INT

RB1

RB2

RB3

1

2

3

4

5

6

7

8

9

18

17

16

15

14

13

12

11

10

RA1

RA0

OSC1

OSC2

Vdd

RB7

RB6

RB5

RB4

Osc4MHz

+5V

+

+

+

+

+

0 1. mF

0 1. mF

0 1. mF

0 1. mF

0 1. mF

PB SW1

Page 595: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

1. Data must be trans mit ted and re ceived at one of the stan dard RS-232-C baud rates.The most of ten-used baud rates in this case are 600, 1,200, 2,400, 4,800, 9,600, and19,200.

2. Data must be for mat ted ac cord ing to the pro to col’s con ven tions; that is, a start bit,5, 6, 7, or 8 data bits; the pres ence or ab sence of a par ity bit; and 1, 1½, or 2 stop bits.

3. RS-232-C com mu ni ca tion data is trans mit ted and re ceived with the least-sig nif i -cant bit first.

The first prob lem (trans mit ting and re ceiv ing at a stan dard baud rate) of ten re -quires an ap prox i ma tion. The PIC’s in struc tions ex e cute at the rate of its in ter nalclock, which also de ter mines the rate of its timer mod ule.

The time taken by each coun ter it er a tion is ob tained by di vid ing the PIC’s clockspeed by four. For ex am ple, a PIC run ning on a 4-MHz os cil la tor clock in cre mentsthe coun ter ev ery 1 MHz. The coun ter reg is ter is in cre mented at a rate of 1 µs (as -sum ing no prescaler). If we were to use the un mod i fied timer rate to mea sure bittime, the re sult would be a baud rate of ap prox i mately 3,906. Be cause 3,906 is not astan dard baud rate, the timer is ad justed to ap prox i mate one of the stan dard

RS-232-C baud rates. For ex am ple, at 4,800 baud, the time per bit is

Be cause the timer of a PIC with a 4-MHz clock runs at 1 µs per timer it er a tion, wecould count up from 0 to 208 it er a tions of the coun ter in or der to ap prox i mate thebit time of 208 µs needed at 4,800 baud. In ad di tion, we would have to cal cu lateone-half the bit time be cause syn chro ni za tion re quires off set ting the timer from theedge to the cen ter of the start bit (see Sec tion 20.3.1). In this case, to de lay ap prox i -mately 104 µs we would count up from 0 to 104.

But count ing up is in con ve nient with the PIC timer/coun ter be cause the sig nal ispro duced when the coun ter reaches its max i mum. A better so lu tion is to pre set thetimer coun ter (TMR0) to a cal cu lated value such that the de sired time lapse oc curswhen the timer reg is ter reaches 255. So the ac tual de lays for 4,800 baud are as fol -lows:

DELAY CALCULATION TMR0 PRESET

208 µs 255 minus 208 47

104 µs 255 minus 104 151

Once we have ob tained the clock rate for a stan dard baud rate, it is easy to ob tain slower stan dard rates by slow ing down the clock with the prescaler. For ex am ple, ifthe prescaler is as signed to the timer/coun ter reg is ter with a bit value of 000, thenthe coun ter rate is one-half the unscaled rate. This would pro duce a baud rate of2,400 baud. By the same to ken, as sign ing a 1:4 prescaler to the timer pro duces abaud rate of 1,200 baud us ing the same pre set val ues pre vi ously cal cu lated. Fasterbaud rates are eas ily cal cu lated by the same method.

574 Chap ter 20

1

4 800208 33

,. .= µs

Page 596: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

For matting the data trans mis sion ac cord ing to the RS-232-C pro to col pres ents no ma jor prob lem. In fact, the com mu ni ca tions pro grams pre vi ously listed in this chap -ter use a start bit to com mence char ac ter trans mis sion, fol lowed by eight data bits,and one stop bit to end it, with no par ity bit. This same for mat is com pat i ble withRS-232-C.

The third com pat i bil ity is sue re fers to the bit or der in RS-232-C, which re quiresthat the low-or der bit be trans mit ted first. In pre vi ous ap pli ca tions, we have sentthe high-or der bit first by ro tat ing the bits left in side the hold ing reg is ter and test ing the carry flag. In the RS-232-C rou tine, the bits are ro tated right into the carry flagand then the carry flag is ro tated into the stor age vari able.

The dem on stra tion pro gram for the cir cuit in Fig ure 20-13, named TTYUsart, uses a two-line by six teen-char ac ter LCD to dis play the char ac ters re ceived from the PCthrough the se rial line. The pro gram ini tially sends the test string “Ready-” to the PC to test the data trans mis sion rou tine and to let the PC user know that the PIC boardis ready to re ceive. The pro gram op er ates at 2,400 baud, one start bit, eight databits, no par ity, and one stop bit. The com mu ni ca tions pro gram on the PC must be set to these pa ram e ters.

LCD Scrolling Rou tine

LCDs have lim ited ca pac ity for data dis play. A two-line by six teen-char ac ter LCD fillsthe screen when 32 char ac ters are dis played. For some ap pli ca tions it is con ve nient tohave a pro ce dure that takes some rea son able ac tion when the LCD screen is full. Oneap proach is to de tect when the last char ac ter in the sec ond LCD line is dis played, thenmove the sec ond line to the first line, clear the sec ond line, and con tinue dis play ing atthe start of the sec ond line. This is the stan dard screen han dling for a com puter pro -gram.

An LCD screen scroll rou tine can be called as each char ac ter is dis played. For the scroll to work, the pro gram must keep track of the cur rently se lected LCD line (vari -able LCDline can be 0 for line 1, and 1 for line 2), of the num ber of char ac ters dis -played on that line (vari able LCDcount), and of the to tal ca pac ity of the line(con stant LCDlimit). Given this in for ma tion, the logic for an LCD line scroll ing rou -tine can be as fol lows:

1. Add current char ac ter to LCDcount. If LCDcount is equal to LCD limit, then theend of a line was reached. If not, exit rou tine.

2. If line end reached is for line 1, set current dis play ad dress to start of line 2. Re setvari able LCDcount. Exit rou tine.

3. If line end reached is for line 2, then copy the char ac ters dis played in line 2 to line 1.Clear line 2. Re set the dis play ad dress to the start of line 2. Re set LCDline vari ableto line 2. Re set vari able LCDcount. Exit rou tine.

Of these op er a tions, copy ing the char ac ters from the sec ond line to the first onecan be the most trou ble some. One pos si bil ity is to read the data from the LCD di -rectly. This ap proach re quires that the con nec tion be tween the PIC and the LCD in -clude the R/W line. An other op tion is to cre ate a buffer in RAM and copy eachchar ac ter dis played to this area. In the case of an LCD with six teen char ac ters per

Com mu ni ca tions 575

Page 597: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

line, the buffer re quires a ca pac ity of 16 bytes. Be cause the line in put is “re mem -bered” in the buffer, the pro gram scrolls a line by copy ing the con tents of the bufferto the other line. This al ter na tive does not re quire read ing the LCD and saves im ple -ment ing the R/W line.

Storing the char ac ters re ceived in a lo cal buffer first re quires re serv ing a 16-bytearea (the buffer) in PIC RAM. There are sev eral ways of ac com plish ing this. A sim -ple one is us ing the cblock di rec tive, as shown in the fol low ing code frag ment:

;=====================================================; buffer and vari ables in PIC RAM;=====================================================; Cre ate a 16-byte stor age area

cblock 0x0c ; Start of first data blocklineBuf ; buffer for text stor ageendc

; Leave 16 bytes and con tinue with lo cal vari ables;cblock 0x1c ; Sec ond data blockcount1 ; Coun ter # 1count2 ; Coun ter # 2

. . . other vari ables can go hereendc

In re al ity, the buffer is most likely ac cessed by in di rect ad dress ing, so a buffername (lineBuf in this case) is not re ally nec es sary. This is due to the fact that PIC as -sem bly lan guage does not con tain a di rec tive for find ing the ad dress of a vari able.So the buffer ad dress must be hard-coded or de fined in a con stant. But, in any case,hav ing a buffer name does not cost stor age ca pac ity and it may help make the codeclearer.

In our de sign, the scroll ing rou tine de pends on find ing the char ac ters in the end -ing line stored in the RAM area men tioned in the pre ced ing para graph. The buffer lo -ca tions are ac cessed di rectly by ref er enc ing the ad dress. For ex am ple, the first byte in lineBuf is stored at address 0x0c, the sec ond one at 0xod, and so on. A more ef -fec tive way of us ing a buffer is by cre at ing and keep ing a buffer pointer vari ablethat has the cur rent off set from the start of the buffer. The buffer pointer is thenadded to the buffer’s base ad dress in or der to ac cess the cur rent buffer lo ca tion. In -di rect ad dress ing us ing the FSR and the INDF reg is ters sim pli fies the pro cess, asshown in the fol low ing code frag ment:

; Store char ac ter in lo cal line buffer us ing in di rect; ad dress ing. Byte to store is in rcvData vari able. ; 16-byte buffer named lineBuf starts at ad dress 0x0c; Reg is ter vari able bufPtr holds off set into buffer movlw 0x0c ; Buffer base ad dress

addwf bufPtr,w ; Add pointer in wmovwf FSR ; Value to in dex reg is termovf rcvData,w ; Char ac ter into wmovwf INDF ; Store w in [FSR]incf bufPtr,f ; Bump pointer

576 Chap ter 20

Page 598: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

The ma nip u la tion re quires load ing the base ad dress of the buffer (0x0c in thiscase) in the w reg is ter, add ing the value stored in the buffer pointer vari able(bufPtr), and stor ing the sum in the FSR reg is ter. The char ac ter is then loaded intothe w reg is ter and moved into the INDF reg is ter, which has the ef fect of stor ing it inthe ad dress pointer at by FSR. Con ven tion ally, brack ets are used to in di cate in di rect ad dress ing, so [FSR] means the mem ory lo ca tion ref er enced by the FSR reg is ter.

Once the line char ac ters are stored lo cally, all that is left is the de sign of a linescroll ing rou tine fol low ing the pro cess ing steps pre vi ously listed. The fol low ingpro ce dure per forms the nec es sary op er a tions:

;==========================; scroll LCD line 2 ;==========================; Pro ce dure to count the num ber of char ac ters dis played on; each LCD line. If the num ber reaches the value in the; con stant LCDlimit, then dis play is scrolled to the sec ond; LCD line. If at the end of the sec ond line, then the; sec ond line is scrolled to the first line and dis play; con tin ues at the start of the sec ond line; re set to the first line.LCDscroll:

incf LCDcount,f ; Bump coun ter; Test for line limit

movf LCDcount,wsublw LCDlimit ; Count mi nus limitbtfss STATUS,z ; Is count - limit = 0goto scrollExit ; Go if not at end of line

; At this point the end of the LCD line was reached; Test if this is also the end of the sec ond line

movf LCDline,wsublw 0x01 ; Is it line 1?btfsc STATUS,z ; Is LCDline mi nus 1 = 0?goto line2End ; Go if end of sec ond line

; At this point it is the end of the top LCD linecall line2 ; Scroll to sec ond lineclrf LCDcount ; Re set coun terincf LCDline,f ; Bump line coun tergoto scrollExit

; End of sec ond LCD lineline2End:; Scroll sec ond line to first line. Char ac ters to be; scrolled are stored in buffer start ing at ad dress 0x0c.; 16 char ac ters are to be moved; First clear LCD

call initLCDcall de lay_5 ; Make sure not busy

; Set up for databcf PORTA,E_line ; E line low

Com mu ni ca tions 577

Page 599: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

bsf PORTA,RS_line ; RS line high for data; Set up coun ter for 16 char ac ters

movlw D’16’ ; Coun ter = 16movwf count2

; Get ad dress of stor age buffermovlw 0x0cmovwf FSR ; W to FSR

getchar:movf INDF,w ; get char ac ter from dis play RAM

; lo ca tion pointed to by file se lect; reg is ter

call send8 ; 4-bit in ter face rou tine; Test for 16 char ac ters dis played

decfsz count2,f ; Dec re ment coun tergoto nextchar ; Skipped if done

; At this point scroll op er a tion has con cludedclrf LCDcount ; Clear coun ters

; Stay at line 2clrf LCDlineincf LCDline,fcall line2 ; Set for sec ond line

scrollExit:re turn

nextchar:incf FSR,f ; Bump pointergoto getchar

;============================; clear line buffer;============================; Use in di rect ad dress ing to store 16 blanks in the; buffer lo cated at 0x0c blankBuf:

Bank0movlw 0x0c ; Pointer to RAMmovwf FSR ; To in dex reg is ter

blank16:clrf INDF ; Clear memory pointed at by FSRincf FSR,f ; Bump pointerbtfss FSR,4 ; 000x0000 when bit 4 is set

; count reached 16goto blank16re turn

;========================; Set ad dress reg is ter; to LCD line 1;========================; ON ENTRY:; Ad dress of LCD line 1 in con stant LCD_1

578 Chap ter 20

Page 600: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

line1:

bcf PORTA,E_line ; E line low

bcf PORTA,RS_line ; RS line low, set up forcon trol

call de lay_5 ; busy?

; Set to sec ond dis play line

movlw LCD_1 ; Ad dress and com mand bit

call send8 ; 4-bit rou tine

; Set RS line for data

bsf PORTA,RS_line ; Setup for data

call de lay_5 ; Busy?

; Clear buffer and pointer

call blankBuf

clrf bufPtr ; Pointer

re turn

;========================

; Set ad dress reg is ter

; to LCD line 2

;========================

; ON ENTRY:

; Ad dress of LCD line 2 in con stant LCD_2

line2:

bcf PORTA,E_line ; E line low

bcf PORTA,RS_line ; RS line low, setup forcon trol

call de lay_5 ; Busy?

; Set to sec ond dis play line

movlw LCD_2 ; Ad dress with high-bit set

call send8

; Set RS line for data

bsf PORTA,RS_line ; RS = 1 for data

call de lay_5 ; Busy?

; Clear buffer and pointer

call blankBuf

clrf bufPtr ; Pointer

re turn

The en tire pro gram, named TTYUsart, is found in this book’s on line soft warepack age.

20.5.2 RS-232-C Com mu ni ca tions on the 16F87xThe sec ond al ter na tive for pro to col-com pli ant com mu ni ca tions is us ing a PIC thatpro vides hard ware sup port for the stan dard. The 16F84, our work horse in this book,con tains no such fa cil i ties. How ever, other mid-range PICs do pro vide hard ware sup -port for one or sev eral se rial com mu ni ca tions pro to cols.

Com mu ni ca tions 579

Page 601: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

For the ex am ples that fol low, we have se lected what is per haps the sec ond mostpop u lar PIC of the mid-range fam ily (af ter the 16F84): the 16F87x. The ar chi tec tureand ba sic pro gram ming fa cil i ties of the 16F87x PIC fam ily were dis cussed in Chap -ter 6. At this time, we should re call that 16F87x in cludes the PIC 16F873, 16F874,16F876, and 16F877. For our sam ple pro grams we have se lected the 16F877 be cause it is the most pow er ful one in the group. The 16F877 has an op er at ing fre quency ofup to 20 MHz, 8K of flash pro gram mem ory, 368 bytes of data mem ory, 256 bytes ofEEPROM, five in put/out put ports, and two mod ules for se rial com mu ni ca tions: aMas ter Syn chro nous Se rial Port and a Uni ver sal Syn chro nous/Asyn chron ous Re -ceiver and Trans mit ter. We fo cus on the USART mod ule and leave the MSSP for thechap ter on EEPROM pro gram ming.

16F87x USART Mod ule

The Uni ver sal Syn chro nous Asyn chron ous Re ceiver Trans mit ter (USART) mod ule inthe 16F87X fam ily is also known as a Se rial Com mu ni ca tions In ter face, or SCI. TheUSART mod ule is use ful in com mu ni cat ing with de vices and sys tems that sup portRS-232-C com mu ni ca tions, in clud ing com put ers and ter mi nals. It can be con fig uredas an asyn chron ous full-du plex de vice, as a syn chro nous half-du plex mas ter, or as asyn chro nous half-du plex slave. In the syn chro nous mode, the USART mod ule is usedmostly in com mu ni cat ing with an a log-to-dig i tal and dig i tal-to-an a log in te grated cir -cuits or for ac cess ing se rial EEPROM. Both of these func tions were dis cussed inChap ter 14.

Five reg is ters re late to USART op er a tion in the 16F877: RCSTA, TXREG, RCREG,TXSTA, and SPBRG. The first three are lo cated in bank 0 and the sec ond two in bank 1. TXSTA is the Trans mit Sta tus and Con trol reg is ter and RCSTA is the Re ceive Sta -tus and Con trol reg is ter. Fig ure 20-14 shows the bitmap for the TXSTA reg is ter lo -cated at ad dress 0x98 in bank 1.

The RCSTA reg is ter con tains con trol and sta tus bits for the re ceive func tion. Thereg is ter is found at ad dress 0x18 in bank 0. Fig ure 20-15 is a bitmap of the RCSTAreg is ter.

USART Baud Rate Gen er a tor

In the USART em u la tion pro grams for the 16F84, we were forced to ap prox i mate theRS-232-C baud rate with the sys tem clock. The USART mod ule in the 16F87X PICs con -tains its own baud rate gen er a tor, but it is also de pend ent on the sys tem clock.

Set ting the baud rate in the USART mod ule con sists of ma nip u lat ing the BaudRate Gen er a tor (BRG) unit. The BRG is a ded i cated 8-bit gen er a tor that sup portsboth the asyn chron ous and syn chro nous modes. The SPBRG is an 8-bit reg is ter thatcon trols the rate of a ded i cated timer. In the asyn chron ous mode, the bit la beledBRGH in the TXSTA reg is ter (see Fig ure 20-14) also re lates to the baud rate be cause i t a l l o ws s e t t i n g e i t h e r a s lo w -s p e e d or a h ig h - sp e e d b a u d r a t e . T hebaud-rate-speed-se lect bit is in ac tive in the syn chro nous mode.

580 Chap ter 20

Page 602: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

The for mula for com put ing the baud rate takes into ac count the sys tem os cil la tor speed (Fosc); the set ting of the Baud-Rate-Speed-Se lect bit (BRGH), which is set forthe high-speed mode and cleared for slow-speed, and also the set ting of the SYNCbit in the TXSTA reg is ter, which se lects ei ther asyn chron ous or syn chro nous mode.The for mula is as fol lows:

where ABR rep re sents the Asyn chron ous Baud Rate, x is the value in the SPRGB reg is -

ter (range 0 to 255), S is 64 in the high-speed mode (BRGH bit is 1) and 16 in the slow

speed mode (BRGH bit is 0). Solving the for mula in terms of the value to be placed in

the SPRGB reg is ter, we get

Com mu ni ca tions 581

Fig ure 20-14 Bitmap of the TXSTA Reg is ter.

CSRC

bit 0bit 7

TX9 TXEN SYNC BRGH TRMT TX9D

bit 7 CSRC: Clock Source Select Asynchronous mode Don’t care Synchronous mode 1 = Master mode (internal clock) 0 = Slave mode (external clock)bit 6 TX9: 9-bit Transmit Enable 1 = 9-bit transmission mode 0 = 8-bit transmission modebit 5 TXEN: Transmit Enable 1 = Transmit enabled 0 = Transmit disabledbit 4 SYNC: USART Mode Select 1 = Synchronous mode 0 = Asynchronous modebit 3 Unimplemented: Read as '0'bit 2 BRGH: Baud Rate Speed Select Asynchronous mode 1 = High speed 0 = Low speed Synchronous mode Unusedbit 1 TRMT: Transmit Shift Register Status 1 = TSR empty 0 = TSR fullbit 0 TX9D: 9th bit of transmit data (Can be used as parity bit)

ABRFosc

S x=

+( ),

1

Page 603: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

For ex am ple, to cal cu late the set ting of the SPRGB reg is ter for 9,600 baud, with a16-MHz os cil la tor, at the high-speed rate (S = 64) the equa tion be comes:

582 Chap ter 20

Fig ure 20-15 Bitmap of the RCSTA Reg is ter.

SPEN

bit 0bit 7

RX9 SREN CREN FERR OERR RX9D

bit 7 SPEN: Serial Port Enable 1 = Serial port enabled (Configures RX/DT and TX/CK pins as serial pins) 0 = Serial port disabledbit 6 RX9: 9-bit Receive Enable 1 = 9-bit reception 0 = 8-bit receptionbit 5 SREN: Single Receive Enable Asynchronous mode Don’t care Synchronous master mode 1 = Enables single receive 0 = Disables single receive Synchronous slave mode Unused in this modebit 4 CREN: Continuous Receive Enable Asynchronous mode 1 = Enables continuous receive 0 = Disables continuous receive Synchronous mode 1 = Enables continuous receive until CREN bit is cleared 0 = Disables continuous receivebit 3 Unimplemented: Read as '0'bit 2 FERR: Framing Error bit 1 = Framing error 0 = No framing errorbit 1 OERR: Overrun Error bit 1 = Overrun error (cleared by CREN bit) 0 = No overrun errorbit 0 RX9D: 9th bit of received data (can be used for parity bit)

ABRFosc

S x=

+( )1

x =⋅

FHG

IKJ − = ≈16 000 000

9 600 641 25 042 25

, ,

,.

Page 604: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

In this case, the value to store in the SPRGB reg is ter is 25. The ac tual baud ratecan now be cal cu lated us ing the first equa tion, as fol lows:

The per cent er ror in the baud rate can be es ti mated by di vid ing the dif fer ence be -tween the de sired and the ac tual baud rate by the de sired baud rate. The per cent er -ror is 0.16.

16F87x USART Asyn chron ous Trans mit ter

The USART in the 16F87x PICs uses a nonreturn-to-zero for mat, con sist ing of onestart bit, eight or nine data bits, no par ity, and one stop bit. In com pli ance withRS-232-C, the USART trans mits and re ceives the least-sig nif i cant bit first. Trans mit terand re ceiver units are func tion ally in de pend ent but use the same data for mat andbaud rate.

Al though par ity is not di rectly sup ported by the hard ware, it can be im ple mentedin soft ware us ing the ninth data bit. Fig ure 20-16 shows the 16F87x reg is ters re latedto asyn chron ous trans mis sion.

Fig ure 20-16 16F87x Reg is ters Used in Asyn chron ous Trans mis sion.

The trans mit ter func tion also uses the Trans mit Shift reg is ter (TSR), which isnot mapped in mem ory and is thus not ac ces si ble to code. TSR ob tains its data fromthe read/write trans mit buffer, named TXREG, which is loaded in soft ware af terthe stop bit is re ceived. Then TXREG trans fers the data to TSR and be comes empty.At this time the TXIF flag bit is set. An in ter rupt re lated to the TXIF bit is en -abled/dis abled by set ting/clear ing the TXIE en able bit in the PIE1 reg is ter. How ever, the TXIF flag bit is set re gard less of the state of the TXIE en able bit. The TXIF flag is re set au to mat i cally when new data is loaded into TXREG.

Com mu ni ca tions 583

ABR =⋅ +

=16 000 000

64 25 19615 38

, ,

( ).

SPEN

TX7 TX6 TX5 TX4 TX3 TX2 TX1 TX0

TXSTA

RCSTA

TXREG

PIR1

PIE1

SPBRG

INTCON

TXIF

TXIE

GIE PEIE

(Baud Rate Generator)

7 6 5 4 3 2 1 0

TX9 TXEN SYNC BRGH TRMT TX9D

bitsREGISTER

NAME

Page 605: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

While the TXIF flag in di cates the sta tus of TXREG, the TRMT bit, in TXSTA, re -flects the sta tus of TSR. TRMT is set when TSR is empty. This is a read-only bit. Noin ter rupts are linked to the TRMT bit, so the pro gram has to poll this bit to de ter -mine if TSR is empty. Trans mis sion is en abled by set ting the TXEN bit in TXSTA.The ac tual trans mis sion does not oc cur un til TXREG is loaded with data and thebaud rate gen er a tor (BRG) has pro duced a clock beat. Al ter na tively, trans mis sioncan be started by load ing TXREG and then set ting the TXEN en able bit.

When trans mis sion starts, the (not ac ces si ble) TSR reg is ter usually is empty.There af ter, trans fer ring data to TXREG re sults in a trans fer to TSR, which then pro -duces an empty TXREG. This mech a nism makes pos si ble the back-to-back trans fer.Clear ing the TXEN en able bit dur ing trans mis sion aborts the trans mis sion. This ac -tion also re sets the trans mit ter and sets the TX/CK pin high.

16F87x USART Asyn chron ous Re ceiver

When Asyn chron ous mode is se lected by set ting the SYNC bit in TXSTA, then re cep -tion can be en abled by set ting the CREN bit in the RCSTA reg is ter. Fig ure 20-17 showsthe reg is ters re lated to asyn chron ous re cep tion.

Fig ure 20-17 Reg is ters Used in Asyn chron ous Re cep tion.

The main op er a tional reg is ter is the RSR (Re ceive Shift Reg is ter), which, likeTSR, is not ac ces si ble to ap pli ca tion soft ware. As soon as the stop bit is de tected inthe RX/TX pin, the re ceived data in RSR is trans ferred to RCREG if it is empty. Inthis case, the RCIF flag bit is set. The in ter rupt linked to the RCIF flag is en abled ordis abled by means of the RCIE in the PIE1 reg is ter. The RCIF flag bit is read-onlyand can be cleared only by hard ware; this hap pens when the RCREG reg is ter hasbeen read and is empty.

584 Chap ter 20

SPEN RX9 CREN

RX7 RX6 RX5 RX4 RX3 RX2 RX1 RX0

FERR OERR RX9D

TXSTA

RCSTA

RCREG

PIR1

PIE1

SPBRG

INTCON

RCIF

RCIE

GIE PEIE

(Baud Rate Generator)

7 6 5 4 3 2 1 0

SYNC BRGH

bitsREGISTER

NAME

Page 606: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

RCREG is dou ble-buf fered, mean ing that it is pos si ble for two bytes of data to bestarted si mul ta neously while a third byte be gins shift ing to RSR. If the stop bit is de -tected while RCREG is not empty, then the over run er ror bit (OERR) is set inRCSTA. RCREG op er ates in first-in-first-out or der. When it is read twice, the twobytes are re trieved in this or der.

The over run er ror bit (OERR) in hib its trans fer from RSR into RCREG; there fore,it is im por tant to clear this bit once the er ror is de tected. The fram ing er ror bit(FERR) in the RCSTA reg is ter is set if a stop bit is not de tected.

The fol low ing steps are fol lowed in initializing and ex e cut ing asyn chron ous re -cep tion:

1. The SPBRG reg is ter is set up for the se lected baud rate.

2. Asyn chron ous re cep tion is en abled by clear ing the SYNC bit in the TXSTA registerand set ting the SPEN bit in the RCSTA register.

3. To en able the re ceive data in ter rupt, the RCIE, GIE, and PEIE bits must be set.

4. Re cep tion is ac ti vated by set ting the CREN bit in RCSTA.

5. When re cep tion has con cluded, the RCIF bit in the PIE1 reg is ter is set. At that time,an in ter rupt is gen er ated if the RCIE bit was set.

6. Re ceived data is re trieved by read ing RCREG.

7. If any er ror oc curred, the CREN bit must be cleared.

PIC-to-PC RS-232-C Com mu ni ca tions Cir cuit

To dem on strate se rial com mu ni ca tions with the RS-232-C pro to col we de vel oped acir cuit con sist ing of a 4-by-4 key pad and a 2-line by 20-char ac ter LCD dis play. Char ac -ters typed on the key pad are con verted to ASCII codes for the hex a dec i mal digit set,that is, the nu meral dig its and the let ters A through F. When a key is pressed, the cor re -spond ing ASCII code is dis played in the LCD and trans mit ted through the se rial port to a PC ap pli ca tion. Char ac ters re ceived though the se rial line are dis played on the LCD.Fig ure 20-18 is a wir ing di a gram of the cir cuit.

The pro gram SerComLCD dem on strates the cir cuit in Fig ure 20-18.

16F877 PIC Ini tial iza tion Code

The fol low ing code frag ment shows the ini tial iza tion of the UART mod ule in the16F877 PIC for 2400 baud, 8 bits, no par ity, and one stop bit. No in ter rupts are used inthis ex am ple.

;==============================================================; USART ini tial iza tion pro ce dure;==============================================================; Ini tial ize se rial port for 2400 baud, 8 bits, no par ity,; 1 stopInitSerial:

Bank1 ; Macro to se lect bank1; Bits 6 and 7 of Port C are mul ti plexed as TX/CK and RX/DT

Com mu ni ca tions 585

Page 607: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

586 Chap ter 20

Fig ure 20-18 USART Com mu ni ca tions Cir cuit with PIC 16F877.

16F877

SW1

SW5

SW9

SW13

SW2

SW6

SW10

SW14

SW3

SW7

SW11

SW15

SW4

SW8

SW12

SW16

MAX202

Note:MAX202 IC requirescomponents not shownin this circuit diagram.See device datasheet.

+5V

R=

10

K

40

39

38

37

36

35

34

33

32

31

30

29

28

27

26

25

24

23

22

21

1

2

3

4

5

6

7

8

16

15

14

13

12

11

10

9

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

RB7/PGD

RG6/PGC

RB5

RB4

RB3/PGM

RB2

RB1

RB0/INT

VDD

VSS

RD7/PSP7

RD6/PSP6

RD5/PSP5

RD4/PSP4

RC7/RX/DT

RC6/TX/CK

RC5/SD0

RC4/SDI/SDA

RD3/PSP3

RD2/PSP2

+5v

GND

T1out

R1in

R1out

T1in

T2in

R2out

C1+

V+

C1-

C2+

C2-

V-

T2out

R2in

!MCLR/VPP

RA0/AN0

RA1/AN1

RA2/AN2.VREF-

RA3/AN3/VREF+

RA4/TOCKI

RA5/AN4/SS

RE0/!RD/AN5

RE1/!WR/AN6

RE2/!CS/AN7

VDD

VSS

OSC1/CLKIN

OS2/CLKOUT

RC0/T1OSO/T1CKI

RC1/T1OSI/CCP2

RC2/CCP1

RC3/SCK/SCL

RD0/PSP0

RD1/PSP1

RESET

+5V

HD44780

LCD2 rows x 20

KEYPAD 4 x 4

4 MHzOsc

+5V

+5V

E

R/W

RS

1

14

DB-9(female)

5 4 3 2 1

9 8 7 6

R=270X 4

Page 608: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; for USART op er a tion. These bits must be set to in put in the; TRISC reg is ter

movlw b’11000000’ ; Bits for TX and RXiorwf TRISC,f ; OR into Trisc reg is ter

; The asyn chron ous baud rate is cal cu lated as fol lows:; Fosc; ABR = ---------; S*(x+1); Where x is the value in the SPBRG reg is ter and S is 64 if the; high baud rate se lect bit (BRGH) in the TXSTA con trol reg is ter; is clear, and 16 if the BRGH bit is set. For set ting to 9600; baud using a 4 MHz os cil la tor at a high-speed baud rate the; for mula is:; 4,000,000 4,000,000; ---------- --------- = 9,615 baud (0.16% er ror); 16*(25+1) 416 ;; At slow speed (BRGH = 0); 4,000,000 4,000,000; --------- --------- = 2,403.85 (0.16% er ror); 64*(25+1) 1,664 ;

movlw spbrgVal ; Value in spbrgVal = 25movwf SPBRG ; Place in baud rate gen er a tor

;; TXSTA (Trans mit Sta tus and Con trol Reg is ter) bitmap:; 7 6 5 4 3 2 1 0 <== bits; | | | | | | | |______ TX9D 9th data bit on; | | | | | | | ? (used for par ity); | | | | | | |_________ TRMT Trans mit Shift Reg is ter ; | | | | | | 1 = TSR empty; | | | | | | * 0 = TSR full; | | | | | |____________ BRGH High Speed Baud Rate; | | | | | (Asyn chron ous mode only); | | | | | 1 = high speed (* 4); | | | | | * 0 = low speed; | | | | |__________ NOT USED; | | | |_____________ SYNC USART Mode Se lect; | | | 1 = syncrhonous mode; | | | * 0 = asyn chron ous mode; | | |________________ TXEN Trans mit En able; | | * 1 = trans mit en abled; | | 0 = trans mit disabled; | |___________________ TX9 En able 9-bit Trans mit; | 1 = 9-bit trans mis sion mode; | * 0 = 8-bit mode; |______________________ CSRC Clock Source Se lect; Not used in asyn chron ous mode

Com mu ni ca tions 587

Page 609: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; Syn chro nous mode:

; 1 = Mas ter Mode (in ter nal clock)

; * 0 = Slave mode (ex ter nal clock)

; Setup value: 0010 0000 = 0x20

movlw 0x20 ; En able trans mis sion and high baud rate

movwf TXSTA

Bank0 ; Bank 0

; RCSTA (Re ceive Sta tus and Con trol Reg is ter) bitmap:

; 7 6 5 4 3 2 1 0 <== bits

; | | | | | | | |______ RX9D 9th data bit re ceived

; | | | | | | | ? (can be par ity bit)

; | | | | | | |_________ OERR Over run errror

; | | | | | | ? 1 = er ror (cleared by soft ware

; | | | | | |____________ FERR Framing Er ror

; | | | | | ? 1 = er ror

; | | | | |_______________ NOT USED

; | | | |____________ CREN Con tin u ous Re ceive En able

; | | | Asyn chron ous mode:

; | | | * 1 = En able con tin u ous re ceive

; | | | 0 = Dis ables con tin u ous re ceive

; | | | Syn chro nous mode:

; | | | 1 = En ables un til CREN cleared

; | | | 0 = Dis ables con tin u ous re ceive

; | | |_______________ SREN Sin gle Re ceive En able

; | | ? Asyn chron ous mode = don’t care

; | | Syn chro nous mas ter mode:

; | | 1 = En able sin gle re ceive

; | | 0 = Dis able sin gle re ceive

; | |__________________ RX9 9th-bit Re ceive En able

; | 1 = 9-bit re cep tion

; | * 0 = 8-bit re cep tion

; |_____________________ SPEN Se rial Port En able

; * 1 = RX/DT and TX/CK are se rial pins

; 0 = Se rial port dis abled

; Setup value: 1001 0000 = 0x90

movlw 0x90 ; En able se rial port and con tin u ous

; re cep tion

movwf RCSTA

;

clrf errorFlags ; Clear lo cal er ror flags reg is ter

Return

588 Chap ter 20

Page 610: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

USART Re ceive and Trans mit Rou tines

The trans mit data rou tine is quite sim ple. Code checks the TXIF bit in PIR1. If the bit isset, data is trans mit ted by stor ing the data byte in TXREG. The fol low ing pro ce dureper forms the re quired op er a tions:

;==============================; trans mit data;==============================; Test for Trans mit Reg is ter Empty and trans mit data in wSerialSend:

Bank0 ; Se lect bank 0busyWait:

btfss PIR1,TXIF ; check if trans mit ter busygoto busyWait ; wait un til trans mit ter is not busymovwf TXREG ; and trans mit the datare turn

Re ceiving data is more com pli cated than trans mit ting it. One of the rea sons isthat code must test for and han dle sev eral pos si ble er rors that can oc cur dur ing re -cep tion. The fol low ing code frag ment shows the lo cal vari ables and pro cess ing re -quired for sim ple data re cep tion:

;=====================================================; vari ables in PIC RAM;=====================================================; Lo cal vari ables

cblock 0x20 ; Start of block...

; Com mu ni ca tions vari ablesnewData ; not 0 if new data re ceivedascValerrorFlagsendc

;===========================================================; USART re ceive data pro ce dure;===========================================================; Pro ce dure to test line for data re ceived and re turn value; in w. Over run and fram ing er rors are de tected and; re mem bered in the vari able errorFlags, as fol lows:; 7 6 5 4 3 2 1 0 <== errorFlags; |-- not used --- | |___ over run er ror; |______ fram ing er rorSerialRcv:

clrf newData ; Clear new data re ceived reg is terBank0 ; Se lect bank 0

; Bit 5 (RCIF) of the PIR1 Reg is ter is clear if the USART

Com mu ni ca tions 589

Page 611: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; re ceive buffer is empty. If so, no data has been re ceivedbtfss PIR1,RCIF ; Check for re ceived datare turn ; Exit if no data

; At this point data has been re ceived. First elim i nate; pos si ble er rors: over run and fram ing.; Bit 1 (OERR) of the RCSTA reg is ter de tects over run; Bit 2 (FERR) of the RCSTA reg is ter de tects fram ing er ror

btfsc RCSTA,OERR ; Test for over run er rorgoto OverErr ; Er ror han dlerbtfsc RCSTA,FERR ; Test for fram ing er rorgoto FrameErr ; Er ror han dler

; At this point no er ror was de tected; Re ceived data is in the USART RCREG reg is ter

movf RCREG,w ; get re ceived databsf newData,7 ; Set bit 7 to in di cate new data

; Clear er ror flagsclrf errorFlagsre turn

;==========================; er ror han dlers;==========================; Over run er ror de tectedOverErr:

bsf errorFlags,0 ; Bit 0 is over run er ror; Re set sys temerrExit:

bcf RCSTA,CREN ; Clear con tin u ous re ceive bitbsf RCSTA,CREN ; Set to re-en able re cep tionre turn

; Er ror. FERR fram ing er ror bit is setFrameErr:

bsf errorFlags,1 ; Bit 1 is fram ing er rormovf RCREG,W ; Read and throw away bad datagoto errExit

The pro ce dures listed pre vi ously are from the pro gram SerComLCD in the book’sonline soft ware. The ap pli ca ble cir cuit is shown in Fig ure 20-18.

USART Re ceive In ter rupt

Polled rou tines for se rial com mu ni ca tions are ad e quate when the ap pli ca tion does lit -tle else but check trans mis sion lines. If the ap pli ca tion has other tasks to per form,polled rou tines can waste pro cess ing time and even lose data. In this sense, the sendfunc tion is usu ally less crit i cal. An ap pli ca tion can typ i cally de ter mine when to senddata and have avail able all the data when the send op er a tion ac ti vates. This is of tennot the case in re ceiv ing data, es pe cially in ap pli ca tions that ex e cute full-du plex.

A prac ti cal so lu tion is to use in ter rupts for re ceiv ing char ac ters through the se -rial line. The 60F87x in cludes fa cil i ties for im ple ment ing in ter rupt rou tines by both

590 Chap ter 20

Page 612: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

the send and the re ceive func tions. To en able in ter rupts for the USART re ceive op -er a tion, the fol low ing pre pa ra tory steps are nec es sary:

• 1. Pe riph eral and global in ter rupts must be en abled by set ting bits 6 and 7 of theINTCON register.

• 2. The re ceive in ter rupt must be en abled by set ting the RCIF bit in the PIE1 reg is ter.

The han dler for the se rial re cep tion in ter rupt usu ally per forms the fol low ingfunc tions:

1. The con text is saved. This in cludes, but is not lim ited to, the sta tus reg is ter, the wregister, the PCLATH reg is ter, and the FSR register.

2. Code tests for re ceived data by check ing the RCIF bit in the PIR1 reg is ter. If this bitis clear, the in ter rupt did not orig i nate in re ceived data.

3. Code can also check if the in ter rupt en able bit (RCIE) is set in the RCIE reg is ter. Ifnot en abled, the in ter rupt is re lated to se rial data.

4. The han dler usu ally checks two pos si ble er rors dur ing re cep tion: overflow andfram ing er ror. The first one by check ing the OERR bit and the sec ond one bycheck ing the FERR bit, both in the RCSTA register. If re cep tion er rors have takenplace, the han dler takes ap pro pri ate ac tion.

5. If no er ror is de tected, then the re ceived data can be re trieved from the RCREG.

6. On exit, the in ter rupt han dler re stores the con text and is sues the retfie in struc -tion.

The fol low ing code frag ment lists the vari ables and pro cess ing rou tine for an in -ter rupt han dler for se rial data re cep tion:

=====================================================; vari ables in PIC RAM;=====================================================; Lo cal vari ables

cblock 0x20 ; Start of block...

; Com mu ni ca tions vari ableserrorFlags

; Tem po rary stor age used by in ter rupt han dlertempWtempStatustempPclathtempFsrendc

;============================================================;============================================================; in ter rupt han dler for re ceived char ac ters;============================================================;============================================================IntServ:

Com mu ni ca tions 591

Page 613: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

movwf tempW ; Save Wmovf STATUS,W ; Store STATUS in Wclrf STATUS ; Se lect bank0movwf tempStatus ; Save STATUSmovf PCLATH,W ; Store PCLATH in Wmovwf tempPclath ; Save PCLATHclrf PCLATH ; Se lect pro gram mem ory page 0movf FSR,W ; Store FSR in Wmovwf tempFsr ; Save FSR value

; Test for re ceived data in ter ruptBank0 ; se lect bank0

; 7 6 5 4 3 2 1 0 <= PIR1; |__________________ (RCIF) USART re ceive in ter rupt; flag

Btfsc PIR1,RCIF ; Test bit 5bsf STATUS,RP0 ; Bank 1 if RCIF set

; 7 6 5 4 3 2 1 0 <= PIE1; |__________________ (RCIE) Re ceive in ter rupt en able; bit

btfss PIE1,RCIE ; Test if in ter rupt is en abledgoto IntExit ; Go if not en abled

;==============================; re ceived data;==============================; Rou tine to han dler re ceived data. Over run and fram ing; er rors are de tected and re mem bered in the vari able; errorFlags, as fol lows:; 7 6 5 4 3 2 1 0 <== errorFlags; | -- not used -- | |___ over run er ror; |______ fram ing er ror

Bank0 ; Se lect bank 0; Test for over run and fram ing er rors.; Bit 1 (OERR) of the RCSTA reg is ter de tects over run; Bit 2 (FERR) of the RCSTA reg is ter de tects fram ing er ror

btfsc RCSTA,OERR ; Test for over run er rorgoto OverErr ; Er ror han dlerbtfsc RCSTA,FERR ; Test for fram ing er rorgoto FrameErr ; Er ror han dler

; At this point no er ror was de tected; Re ceived data is in the USART RCREG reg is ter

movf RCREG,w ; Re ceived data into w; Clear er ror flags

clrf errorFlagsgoto IntExit

;==========================; er ror han dlers;==========================; Er rors are re turned as bits in the errorFlags reg is ter

592 Chap ter 20

Page 614: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; 7 6 5 4 3 2 1 0 <= errorFlags; |- not used ---| | |____ over run er ror; |_______ fram ing er ror; Er ror re sponses to be made by main codeOverErr:

bsf errorFlags,0 ; Bit 0 is over run er ror; Re set sys tem

bcf RCSTA,CREN ; Clear con tin u ous re ceive bitbsf RCSTA,CREN ; Set to re-en able re cep tiongoto IntExit

FrameErr:bsf errorFlags,1; Bit 1 is fram ing er rormovf RCREG,W ; Read and throw away bad data

;==============================; in ter rupt han dler exit;==============================IntExit:

Bank0movf tempFsr,w ; Re cover FSR valuemovwf FSR ; Re store in reg is termovf tempPclath,w ; Re cover PCLATH valuemovwf PCLATH ; Re store in reg is termovf tempStatus,W ; Re cover STATUSmovwf STATUS ; Re store in reg is terswapf tempW,F ; Swap file reg is ter in it selfswapf tempW,W ; Re store in reg is terretfie

The pro gram SerIntLCD in this book’s on line soft ware, is an In ter rupt-Drivendem on stra tion for the cir cuit in Fig ure 20-18.

20.6 Demonstration Pro gramsThe sam ple pro grams listed in the fol low ing sec tions re fer to the pro gram ming dis -cussed in this chap ter.

20.6.1 SerialSnd Pro gram; File name: SerialSnd.asm; Date: May 5, 2011; Au thors: Sanchez and Canton; Pro ces sor: 16F84A;; De scrip tion:; Two pro grams to ex er cise se rial com mu ni ca tions be tween; two PIC 16F84A both run ning at 4 MHz. One pro gram sends; data through a sin gle line and the other one re ceives; it. This pro gram is the sender.;

Com mu ni ca tions 593

Page 615: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; Cir cuit:; Port A1 is the se rial trans mis sion line.; Port A2 is an ac tive-low pushbutton switch that; serves to ini ti ate com mu ni ca tions.; Port A3 is a LED that is ON when the pro gram is; ready to send data. Once data starts; be ing sent the LED is turned OFF.; Port-B0-B7 is a 8 x tog gle switch that pro vides; the data byte to be sent.; A pushbutton swtich is in the 16F84 RESET line; and serves to re start the pro gram.;; Com mu ni ca tions pa ram e ters:; Timer chan nel TMR0 is used for syn chro niz ing data; trans mis sion. The timer runs at the max i mum rate of; 256 cy cles per it er a tion. In a 4 MHz sys tem the; timer rate is 1 MHz, thus the bit rate is; 1,000,000/256; which is ap prox i mately 3,906 mi cro sec onds per bit. ;;===========================; switches;===========================; Switches used in __config di rec tive:; _CP_ON Code pro tec tion ON/OFF ; * _CP_OFF ; * _PWRTE_ON Power-up timer ON/OFF; _PWRTE_OFF ; _WDT_ON Watchdog timer ON/OFF ; * _WDT_OFF ; _LP_OSC Low power crys tal oscillator; * _XT_OSC Ex ter nal par al lel crys tal oscillator ; _HS_OSC High speed crys tal res o na tor (8 to 10 MHz); Res o na tor: Murate Erie CSA8.00MG = 8 MHz ; _RC_OSC Re sis tor/ca pac i tor oscillator; | (sim plest, 20% er ror); |; |_____ * in di cates setup val ues pres ently se lected

;=========================; setup and con fig u ra tion;=========================

pro ces sor 16f84Ain clude <p16f84A.inc>__config _XT_OSC & _WDT_OFF & _PWRTE_ON & _CP_OFF

;============================================================; M A C R O S;============================================================

594 Chap ter 20

Page 616: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; Macros to se lect the reg is ter banksBank0 MACRO ; Se lect RAM bank 0

bcf STATUS,RP0ENDM

Bank1 MACRO ; Se lect RAM bank 1bsf STATUS,RP0ENDM

;=====================================================; con stant def i ni tions for pin wir ing;=====================================================#de fine readySW 2 ;|#de fine readyLED 3 ;| => from wir ing di a gram #de fine serialLN 1 ;|;=====================================================; PIC reg is ter flag equates;=====================================================c equ 0 ; Carry flagtmrOVF equ 2 ; Timer over flow bit;======================================================; vari ables in PIC RAM;=====================================================

cblock 0x0d ; Start of blockbitCount ; Coun ter for 8 bitsdataReg ; Data to sendendc

;=========================================================; pro gram;=========================================================

org 0 ; start at ad dress goto main

; Space for in ter rupt han dlersorg 0x04

main:; Port-A, bit 2 is in put. Rest is out put

Bank1movlw b’00000100’ ; Port-A bit 2 is in put

; all oth ers are out putmovwf TRISA

; Port-B is all in putmovlw b’11111111’movwf TRISBBank0bsf PORTA,1 ;Mark ing bit

; Pre pare to set prescalerclrf TMR0

Com mu ni ca tions 595

Page 617: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

clrwdt; Setup OPTION reg is ter for full timer speed

movlw b’11011000’ ; 1 1 0 1 1 0 0 0 <= OPTION bits; | | | | | |__|__|_____ PS2-PS0 (prescaler bits); | | | | | Values for Timer0; | | | | | *000 = 1:2 001 = 1:4; | | | | | 010 = 1:8 011 = 1:16; | | | | | 100 = 1:32 101 = 1:64; | | | | | 110 = 1:128 111 = 1:256; | | | | |______________ PSA (prescaler as sign); | | | | *1 = to WDT; | | | | 0 = to Timer0; | | | |_________________ TOSE (Timer0 edge se lect); | | | 0 = in cre ment on low-to-high; | | | *1 = in cre ment on high-to-low; | | |____________________ TOCS (TMR0 clock source); | | *0 = in ter nal clock; | | 1 = RA4/TOCKI bit source; | |_______________________ INTEDG (Edge se lect); | 0 = fall ing edge; | *1 = ris ing edge; |__________________________ RBPU pullups; 0 = en abled; *1 = disabled

op tion; Dissable in ter rupts

bcf INTCON,5 ; Timer0 over flow disabledbcf INTCON,7 ; Global interrupts disabled

; Turn on ready LEDbsf PORTA,3 ; LED on

;===========================; wait for READY switch; to be pressed;===========================ready2send:

btfsc PORTA,readySWgoto ready2send

;===========================; send se rial data;===========================; At this point pro gram pro ceeds to send data through; the se rial port line; Turn off LED

bcf PORTA,readyLED; Read switches and store in lo cal vari able

movf PORTB,wmovwf dataReg

596 Chap ter 20

Page 618: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

;===========================; call se rial out put; pro ce dure;===========================

call sendData ; call se rial out put pro ce dure;===========================; wait for ever;===========================endloop:

goto endloop

;============================================================; pro ce dure to send se rial data;============================================================; ON ENTRY:; lo cal vari able dataReg holds 8-bit value to be; trans mit ted through port la beled serialLN; OPERATION:; 1. The timer at reg is ter TMR0 is set to run at; max i mum clock speed, that is, 256 clock beats.; The timer over flow flag in the INTCON reg is ter; is set when the timer cy cles from 0xff to 0x00.; 2. Each bit (start, data, and stop bits) is sent ; at a rate of 256 timer beats. That is, each bit is; held high or low for one full timer cy cle (256; clock beats). ; 3. The pro ce dure tests the timer overflow flag; (tmrOVF) to de ter mine when the timer cy cle has; ended, that is, when 256 clock beats have passed.;sendData:

movlw 0x08 ; Set up shift coun termovwf bitCount

;=======================; send START bit;=======================; Set line low then hold for 256 timer clock beats.

bcf PORTA,serialLN ; Send start bit; First re set timer

clrf TMR0 ; Re set timer coun terbcf INTCON,tmrOVF ; Re set TMR0 over flow flag

; Wait for 256 timer clock beatsstartBit:

btfss INTCON,tmrOVF ; timer over flow?goto startBit ; Wait un til set

; At this point timer has cy cled. Start bit has endedbcf INTCON,tmrOVF ; Clear over flow flag

;========================

Com mu ni ca tions 597

Page 619: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; send 8 DATA bits;========================; Eight data bits are sent through the se rial line; start ing with the high-or der bit. The data byte is; stored in the reg is ter named dataReg. The bits are; ro tated left to the carry flag. Code as sumes the bit; is zero and sets the se rial line low. Then the carry; flag is tested. If the carry is set the se rial line ; is changed to high. The line is kept low or high for; 256 timer beats.send8:

rlf dataReg,f ; bit into carry flagbcf PORTA,serialLN ; 0 to se rial line

; Code can as sume the bit is a zero and set the line ; low because, if low is the wrong state, it will only; re main for two timer beats. The re ceiver will not; check the line for data un til 128 timer beats have; elapsed, so the er ror will be harm less. In any case,; there is no as sur ance that the pre vi ous line state is; the cor rect one, so leav ing the line in its pre vi ous; state could also be wrong.

btfsc STATUS,c ; test carry flagbsf PORTA,serialLN ; bit is set. Fix er ror.

bitWait:btfss INTCON,tmrOVF ; Timer cy cled?goto bitWait ; not yet

; At this point timer has cy cled. ; Test for end of byte, if not, send next bit

bcf INTCON,tmrOVF ; clear over flow flagdecfsz bitCount,f ; Last bit?goto send8 ; not yet

;=========================; hold MARKING state;=========================; All 8 data bits have been sent. The se rial line must; now be held high (MARKING) for one clock cy cle

bsf PORTA,serialLN ; Mark ing statemarkWait:

btfss INTCON,tmrOVF ; Done?goto markWait ; not yet

;=========================; end of trans mis sion;=========================

re turn ; done

;=========================================================; end of pro gram;=========================================================

598 Chap ter 20

Page 620: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

end

20.6.2 SerialRcv Pro gram; File name: SerialRcv.asm; Date: May 6, 2011; Au thors: Canton and Sanchez; Pro ces sor: 16F84A;; De scrip tion:; Two pro grams to ex er cise se rial com mu ni ca tions be tween; two PIC 16F84A both run ning at 4 MHz. One pro gram sends; data through a sin gle line and the other one re ceives; it. This pro gram is the re ceiver.;; Cir cuit:; Port A0 is the se rial trans mis sion line ; Port A2 is an ac tive-low pushbutton switch that; serves to ini ti ate com mu ni ca tions.; Port A3 is an LED that is ON when the pro gram is; ready to re ceive data. Once data starts; be ing re ceived the LED is turned OFF.; Port-B0-B7 are 8 LEDs that dis play the data bits; that have been re ceived.; A pushbutton switch is in the 16F84 RESET line; and serves to re start the pro gram.;; Com mu ni ca tions pa ram e ters:; Timer chan nel TMR0 is used for syn chro niz ing data; trans mis sion. The timer runs at the max i mum rate of; 256 cy cles per it er a tion. In a 4 MHz sys tem the; timer rate is 1 MHz, thus the bit rate is; 1,000,000/256; which is ap prox i mately 3,906 mi cro sec onds per bit.;; Upon re ceiv ing the START bit, the pro gram waits for; one half a clock cy cle (128 timer beats) to; synchronize with the sender.;===========================; switches;===========================; Switches used in __config di rec tive:; _CP_ON Code pro tec tion ON/OFF ; * _CP_OFF ; * _PWRTE_ON Power-up timer ON/OFF; _PWRTE_OFF ; _WDT_ON Watchdog timer ON/OFF ; * _WDT_OFF

Com mu ni ca tions 599

Page 621: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; _LP_OSC Low power crys tal oscillator; * _XT_OSC Ex ter nal par al lel crys tal oscillator ; _HS_OSC High speed crys tal res o na tor (8 to 10 MHz); Res o na tor: Murate Erie CSA8.00MG = 8 MHz ; _RC_OSC Re sis tor/ca pac i tor oscillator; | (sim plest, 20% er ror); |; |_____ * in di cates setup val ues pres ently se lected

;=========================; setup and con fig u ra tion;=========================

pro ces sor 16f84Ain clude <p16f84A.inc>__config _XT_OSC & _WDT_OFF & _PWRTE_ON & _CP_OFF

;============================================================; M A C R O S;============================================================; Macros to se lect the reg is ter banksBank0 MACRO ; Se lect RAM bank 0

bcf STATUS,RP0ENDM

Bank1 MACRO ; Se lect RAM bank 1bsf STATUS,RP0ENDM

;=====================================================; con stant def i ni tions for pin wir ing;=====================================================#de fine readySW 2 ;|#de fine readyLED 3 ;| => from wir ing di a gram #de fine serialLN 0 ;|;=====================================================; PIC reg is ter and flag equates;=====================================================c equ 0 ; Carry flagtmrOVF equ 2 ; Timer over flow bit;;======================================================; vari ables in PIC RAM;=====================================================

cblock 0x0c ; Start of blockbitCount ; Coun ter for 8 bitsrcvReg ; Data to sendtempendc

;=========================================================; pro gram

600 Chap ter 20

Page 622: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

;=========================================================org 0 ; start at ad dress goto main

; Space for in ter rupt han dlersorg 0x04

main:Bank1

; Port-A bits 0 and 2 are in put. All oth ers are out putmovlw b’00000101’ ; Port-A setupmovwf TRISA

; Port-B is all out putmovlw b’00000000’ ; Port-B setupMOVWF TRISBBank0

; Turn off all Port-B LEDsclrf PORTB

; And re ceiver reg is terclrf rcvReg

; Pre pare to set prescalerclrf TMR0clrwdt

; Setup OPTION reg is ter for full timer speedmovlw b’11011000’

; 1 1 0 1 1 0 0 0 <= OPTION bits; | | | | | |__|__|_____ PS2-PS0 (prescaler bits); | | | | | Values for Timer0; | | | | | *000 = 1:2 001 = 1:4; | | | | | 010 = 1:8 011 = 1:16; | | | | | 100 = 1:32 101 = 1:64; | | | | | 110 = 1:128 111 = 1:256; | | | | |______________ PSA (prescaler as sign); | | | | *1 = to WDT; | | | | 0 = to Timer0; | | | |_________________ TOSE (Timer0 edge se lect); | | | 0 = in cre ment on low-to-high; | | | *1 = in cre ment on high-to-low; | | |____________________ TOCS (TMR0 clock source); | | *0 = in ter nal clock; | | 1 = RA4/TOCKI bit source; | |_______________________ INTEDG (Edge se lect); | 0 = fall ing edge; | *1 = ris ing edge; |__________________________ RBPU pullups; 0 = en abled; *1 = disabled

op tion; Disable in ter rupts

Com mu ni ca tions 601

Page 623: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

bcf INTCON,5 ; Timer0 over flow disabledbcf INTCON,7 ; Global interrupts disabled

;=========================; wait for READY switch; to be pressed;=========================ready2rcv:

btfsc PORTA,readySW ; Test switchgoto ready2rcv ; loop

; Turn ON the ready-to-re ceive LEDbsf PORTA,readyLED

;===========================; re ceiv ing;===========================

call rcvData ; Call se rial in put pro ce dure;===========================; data re ceived;===========================; Turn ready to re ceive LED off

bcf PORTA,readyLED; Dis play re ceived data

movf rcvReg,w ; Byte re ceived to wmovwf PORTB ; dis play in Port-B

;===========================; wait for ever;===========================endloop:

goto endloop;============================================================; pro ce dure to re ceive se rial data;============================================================; ON ENTRY:; lo cal vari able dataReg is used to store 8-bit value; re ceived through port (la beled serialLN); OPERATION:; 1. The timer at reg is ter TMR0 is set to run at; max i mum clock speed, that is, 256 clock beats.; The timer over flow flag in the INTCON reg is ter; is set when the timer cy cles from 0xff to 0x00.; 2. When the START sig nal is re ceived, the code; waits for 128 timer beats so as to read data in; the mid dle of the send pe riod.; 3. Each bit (start, data, and stop bits) is read ; at in ter vals of 256 timer beats.; 4. The pro ce dure tests the timer overflow flag; (tmrOVF) to de ter mine when the timer cy cle has; ended, that is, when 256 clock beats have passed.

602 Chap ter 20

Page 624: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

;=============================================================rcvData:

clrf TMR0 ; Re set timermovlw 0x08 ; Ini tial ize bit coun termovwf bitCount

;=========================; wait for START bit;=========================startWait:

btfsc PORTA,0 ; Is port A0 low?goto startWait ; No. Wait for mark

;=========================; off set 128 clock beats;=========================; At this point the re ceiver has found the fall ing; edge of the start bit. It must now wait 128 timer; beats to syn chro nize in the mid dle of the sender’s; data rate, as fol lows:; |<========= fall ing edge of START bit; |; |-----|<====== 128 clock beats off set; --------- | .---------; | | <== SIGNAL; ----------- ; |<-- 256--->|;

movlw 0x80 ; 128 clock beats off setmovwf TMR0 ; to TMR0 coun terbcf INTCON,tmrOVF ; Clear over flow flag

offsetWait:btfss INTCON,tmrOVF ; timer over flow?goto offsetWait ; Wait un tilbtfsc PORTA,0 ; Test start bit for er rorgoto offsetWait ; Re cy cle if a false start

;==========================; re ceive data;==========================

clrf TMR0 ; Re start timerbcf INTCON,tmrOVF ; Clear over flow flag

; Wait for 256 timer cy cles for first/next data bitbitWait:

btfss INTCON,tmrOVF ; Timer cy cle end?goto bitWait ; Keep wait ing

; Timer has coun ter 256 beatsbcf INTCON,tmrOVF ; Re set over flow flagmovf PORTA,w ; Read Port-A into wmovwf temp ; Store value readrrf temp,f ; Ro tate bit 0 into carry flag

Com mu ni ca tions 603

Page 625: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

rlf rcvReg,f ; Ro tate carry into rcvReg 0 decfsz bitCount,f ; 8 bits re ceived

goto bitWait ; Next bit; Wait for one time cy cle at end of re cep tionmarkWait:

btfss INTCON,tmrOVF ; timer over flow flaggoto markWait ; keep wait ing

;========================; end of re cep tion;========================

re turn

;=========================================================; end of pro gram;=========================================================

end

20.6.3 Serial6465 Pro gram; File name: Serial6465.asm; Last up date: May 7, 2011; Au thors: Canton and Sanchez; Pro ces sor: 16F84A;; De scrip tion:; Pro gram to ex er cise se rial com mu ni ca tions us ing a; PIC 16F84A and two shift reg is ters: a 74HC164 and a; 74HC165. The 74HC165 in puts 8 lines from a DIP switch; and trans mits set tings to PIC through a se rial line.; PIC sends data se ri ally to an 74HC164 that is wired; to 8 LEDs that dis play the re ceived data. A to tal of; 6 PIC lines are used in in ter fac ing 8 in put switches; to 8 out put LEDs.;; Cir cuit:; * Port A0 is the se rial trans mis sion line that; co mes from the 74HC165.; * Port A1 is wired to the 74HC164 CLOCK pin; * Port A2 is wired to the 74HC164 CLEAR pin; * 74HC164 out put pins 0 to 7 are wired to LEDs.; * Port B0 is wired to the 74HC165 Hout line; * Port B1 is wired to the 74HC165 CLK line; * Port B2 is wired to the 74HC165 load line; * A pushbutton switch is in the 16F84 RESET line; and serves to re start the pro gram; Com mu ni ca tions pro to col:; Com mu ni ca tion be tween PIC and the 74HC164 and ; 74HC165 is syn chro nous as the shift reg is ters

604 Chap ter 20

Page 626: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; clock lines serve to shift in and out the data; bits. ;;===========================; switches;===========================; Switches used in __config di rec tive:; _CP_ON Code pro tec tion ON/OFF ; * _CP_OFF ; * _PWRTE_ON Power-up timer ON/OFF; _PWRTE_OFF ; _WDT_ON Watchdog timer ON/OFF ; * _WDT_OFF ; _LP_OSC Low power crys tal oscillator; * _XT_OSC Ex ter nal par al lel res o na tor oscillator ; _HS_OSC High speed crys tal res o na tor (8 to 10 MHz); Res o na tor: Murate Erie CSA8.00MG = 8 MHz ; _RC_OSC Re sis tor/ca pac i tor oscillator; | (sim plest, 20% er ror); |; |_____ * in di cates setup val ues pres ently se lected

;=========================; setup and con fig u ra tion;=========================

pro ces sor 16f84Ain clude <p16f84A.inc>__config _XT_OSC & _WDT_OFF & _PWRTE_ON & _CP_OFF

;============================================================; M A C R O S;============================================================; Macros to se lect the reg is ter banksBank0 MACRO ; Se lect RAM bank 0

bcf STATUS,RP0ENDM

Bank1 MACRO ; Se lect RAM bank 1bsf STATUS,RP0ENDM

; Note: in the case of the 16F84A the bank se lect mac ros; do not make the code more ef fi cient, but they; do serve to clar ify the bank se lec tion op er a tions.;;=====================================================; con stant def i ni tions from wir ing di a gram;=====================================================#de fine clockLN 1 ;|

Com mu ni ca tions 605

Page 627: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

#de fine clearLN 2 ;| - 74HC164 lines #de fine dataLN 0 ;|;#de fine clk65LN 1 ;| - 74HC165 lines#de fine loadLN 2 ;|;=====================================================; PIC reg is ter and flag equates;=====================================================highBit equ 7 ; High or der bit;======================================================; vari ables in PIC RAM;=====================================================

cblock 0x0d ; Start of blockbitCount ; Coun ter for 8 bitsdataReg ; Data to sendworkReg ; Work reg is ter for bit shiftsendc

;=========================================================; pro gram;=========================================================

org 0 ; start at ad dress goto main

; Space for in ter rupt han dlersorg 0x04

main:; Port-A is all out put

Bank1movlw b’00000000’ movwf TRISA

; Port-B line 0 is in put, all oth ers are out putmovlw b’00000001’movwf TRISBBank0

; Make sure Port-A line 2 (clear line) is highmovlw b’00000100’movwf PORTA

;========================; read in put from 165 IC;========================

call in165 ; Lo cal pro ce dure; dataReg con tains in put;===========================; call se rial out put; pro ce dure;===========================

call out164 ; Call se rial out put pro ce dure;===========================

606 Chap ter 20

Page 628: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; wait for ever;===========================endloop:

goto endloop;============================================================; 74HC164 pro ce dure to send se rial data;============================================================; ON ENTRY:; lo cal vari able dataReg holds 8-bit value to be; trans mit ted through port la beled serialLN; OPERATION:; 1. A lo cal coun ter (bitCount) is in i tial ized to; 8 bits.; 2. Code as sumes that the first bit is zero by; set ting the data line low. Then the high-or der; bit in the data reg is ter (dataReg) is tested.; If set, the data line is changed to high.; 3. Bits are shifted in by puls ing the 74HC164; clock line (CLK).; 4. Data bits are then shifted left and the bit; coun ter is tested. If all 8 bits have been sent,; the pro ce dure re turns. out164:; Clear 74HC164 shift reg is ter

bcf PORTA,clearLN ; 74HC164 CLR clear lowbsf PORTA,clearLN ; then high again

; Init coun termovlw 0x08 ; Ini tial ize bit coun termovwf bitCount

sendBit:bcf PORTA,dataLN ; Set data line low (as sume)

; Using this as sump tion is pos si ble be cause the bit is not; shifted in un til the clock line is pulsed.

btfsc dataReg,highBit ; test num ber bit 7bsf PORTA,dataLN ; Change as sump tion if set

;=========================; pulse clock line;=========================; Bits are shifted in by puls ing the 74HC164 CLK line

bsf PORTA,clockLN ; CLK highbcf PORTA,clockLN ; CLK low

;=========================; Ro tate data bits left;=========================

rlf dataReg,f ; Shift left data bitsdecfsz bitCount,f ; Dec re ment bit coun tergoto sendBit ; Re peat if not 8 bits

;=========================

Com mu ni ca tions 607

Page 629: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; end of trans mis sion;=========================

re turn

;============================================================; 74HC165 pro ce dure to read par al lel data and send; se ri ally to PIC;============================================================; OPERATION:; 1. Eight DIP switches are con nected to the in put; ports of an 74HC165 IC. Its out put line Hout; and its con trol lines CLK and load are con nected; to the PIC’s Port-B lines 0, 1, and 2; re spec tively; 2. Pro ce dure sets a coun ter (bitCount) for eight; it er a tions and clears a data hold ing reg is ter; (dataReg).; 3. Port-B bits are read into w. Only the lsb of; Port-B is rel e vant. Value is stored in a work ing; reg is ter and the mean ing ful bit is ro tated into; the carry flag, then the carry flag bit is; shifted into the data reg is ter.; 4. The it er a tion coun ter is dec re ment ed. If this; is the last it er a tion, the rou tine ends. Oth er wise; the bitwise read-and-write op er a tion is re peated.

in165:clrf dataReg ; Clear data reg is termovlw 0x08 ; Ini tial ize coun termovwf bitCountbcf PORTB,loadLN ; Re set shift reg is terbsf PORTB,loadLN

nextBit:movf PORTB,w ; Read Port-B (only LOB is

; mean ing ful in this rou tine)movwf workReg ; Store value in lo cal

; reg is terrrf workReg,f ; Ro tate LOB bit into carry

; flagrlf dataReg,f ; Carry flag into dataRegdecfsz bitCount,f ; Dec re ment bit coun tergoto shiftBits ; Con tinue if not zerore turn ; done

shiftBits:bsf PORTB,clk65LN ; Pulse clockbcf PORTB,clk65LNgoto nextBit ; Con tinue

;=========================================================

608 Chap ter 20

Page 630: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; end of pro gram;========================================================

end

20.6.4 TTYUsart Pro gram; File name: TTYUsart.asm; Last up date: May 1, 2010; Au thors: Sanchez and Canton; Pro ces sor: 16F84A;; De scrip tion:; Pro gram to em u late USART op er a tion in PIC code. Uses; PIC-to-LCD in ter face. Dis play has two lines, each with; sixteen char ac ters.; Pro gram op er a tion:; Char ac ters re ceived from the RS232 line are dis played on; the LCD. LCD lines scroll au to mat i cally. A pushbutton; ac ti vates the send op er a tion by trans mit ting the text; string: Ready- which is also dis played on the LCD.;; Pro gram com mu ni ca tions and LCD pa ram e ters are stored in; #de fine state ments. These state ments can be ed ited to; ac com mo date a dif fer ent setup. Pro gram uses de lay loops; for in ter face tim ing.;; WARNING:; Code as sumes 4 MHz clock. De lay rou tines must be; ed ited for faster clock.;; BAUD RATE CALCULATIONS:; A 4 MHz clock os cil la tor has a clock fre quency of 1 MHz:; Because the baud rate is the num ber of clock cy cles per; sec ond, for a 4 MHz clock it is:; 1; bit time = ----- sec. = 208.33 mi cro sec onds; 4,800 ; Cal cu lating one-half the baud rate al lows re set ting the; clock from the edge to the cen ter of a time pulse:;; |<======== fall ing edge of start bit; | |<======== cen ter of bit time; >| |< one-half baud rate; | |;__________. | .____________. ; |_____________| |________ ; 208/2 = 104 ; The PIC clock counts up from 0 to 255. So to im ple ment

Com mu ni ca tions 609

Page 631: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; a 104 mi cro sec ond de lay we must start count ing at; clock beat:; 255 - 104 = 151; plus one mi cro sec ond for movlw in struc tion used to; ini tial ize the clock:; 151 + 1 = 152; For one full baud rate de lay:; 255 - 208 = 47 + 1 = 48 ; The fol low ing two con stants are stored in #de fine; state ments:; halfBaud = 152; fullBaud = 48 ; Set ting the prescaler to TMR0 re duces the baud rate; to one-half. Other prescaler val ues will re duce the; baud rate ac cord ingly.;; Wiring di a gram:; RB4-RB7 ===> LCD data lines 4 to 7 (out put); RB0 =======> MAX202 T2in line (out put); RA0 =======> MAX202 R2out line (in put); RA1 =======> LCD E line (out put); RA2 =======> LCD RS line (out put); RA3 =======> LCD R/W line (out put - not used); RA4 =======> Pushbutton switch 1; (in put - ac tive low);;===========================; switches;===========================; Switches used in __config di rec tive:; _CP_ON Code pro tec tion ON/OFF ; * _CP_OFF ; * _PWRTE_ON Power-up timer ON/OFF; _PWRTE_OFF ; _WDT_ON Watchdog timer ON/OFF ; * _WDT_OFF ; _LP_OSC Low power crys tal os cil la tor; * _XT_OSC Ex ter nal par al lel res o na tor/crys tal os cil la tor

; _HS_OSC High speed crys tal res o na tor (8 to 10 MHz); Res o na tor: Murate Erie CSA8.00MG = 8 MHz ; _RC_OSC Re sis tor/ca pac i tor os cil la tor; | (sim plest, 20% er ror); |; |_____ * in di cates setup val ues pres ently se lected

;=========================; setup and con fig u ra tion

610 Chap ter 20

Page 632: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

;=========================pro ces sor 16f84Ain clude <p16f84A.inc>__config _XT_OSC & _WDT_OFF & _PWRTE_ON & _CP_OFF

;============================================================; M A C R O S;============================================================; Macros to se lect the reg is ter banksBank0 MACRO ; Se lect RAM bank 0

bcf STATUS,RP0ENDM

Bank1 MACRO ; Se lect RAM bank 1bsf STATUS,RP0ENDM

;============================================================; con stant def i ni tions; for PIC-to-LCD pin wir ing and LCD line ad dresses;============================================================#de fine E_line 1 ;|#de fine RS_line 2 ;| -- from wir ing di a gram #de fine RW_line 3 ;|; LCD line ad dresses (from LCD data sheet)#de fine LCD_1 0x80 ; First LCD line con stant#de fine LCD_2 0xc0 ; Sec ond LCD line con stant#de fine LCDlimit .16; Num ber of char ac ters per line; 4800 baud clock count down val ues; Code re duces rate to 2400 baud by en ter ing a min i mal; prescaler to TRM0#de fine halfBaud .152 ; For one-half bit time#de fine fullBaud .48 ; For one full bit time;; Note: The con stants that de fine the LCD dis play line; ad dresses have the high-or der bit set in; or der to fa cil i tate the con trol ler com mand ;;=====================================================; buffer and vari ables in PIC RAM;=====================================================; Cre ate a 16-byte stor age area

cblock 0x0c ; Start of first data blocklineBuf ; buffer for text stor ageendc

; Leave 16 bytes and Con tinue with lo cal vari ablescblock 0x1c ; Sec ond data blockcount1 ; Coun ter # 1count2 ; Coun ter # 2

Com mu ni ca tions 611

Page 633: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

J ; coun ter JK ; coun ter Kstore1 ; Lo cal tem po rary stor age store2 ; Stor age # 2

; For LCDscroll pro ce dureLCDcount ; Coun ter for char ac ters per lineLCDline ; Cur rent dis play line (0 or 1)bufPtr ; Buffer pointer

; Vari ables for se rial com mu ni ca tionstempData ; Tem po rary stor age for bit

; ma nip u la tionsrcvData ; Fi nal stor age for re ceived char ac terbitCount ; Bit coun tersendData ; Char ac ter to sendendc

;=========================================================; m a i n p r o g r a m ;=========================================================

org 0 ; start at ad dress goto main

; Space for in ter rupt han dlersorg 0x08

main:Bank1movlw b’00010001’ ; Port-A lines I/O setup

; RA0 = RS232 in put (R2out); RA4 = Pushbutton SW # 1

movwf TRISAmovlw b’00000000’ ; Port-B lines as fol lows:

; RB4-RB7 ===> LCD data lines 4 to 7 (out put); RB0 =======> MAX202 T2in line (out put)

movwf TRISBBank0

; Clear bits in Port-A out put linesbcf PORTA,1bcf PORTA,2bcf PORTA,3movlw b’00000000’ ; All out puts ports lowmovwf PORTB

; Wait and ini tial ize HD44780call de lay_5 ; Al low LCD time to ini tial ize

; it selfcall de lay_5call initLCD ; Then do forced

ini tial iza tioncall de lay_5 ; Wait again

; Set Port-B, line 0 high so start bit is de tected

612 Chap ter 20

Page 634: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

bsf PORTB,0;============================; wait for start com mand;============================; Pro gram waits un til pushbutton num ber 1 is pressed; to con tinue ex e cu tion. Pushbutton 1 is ac tive low; and wired to RA4pb1Wait:

btfsc PORTA,4 ; Test Port-A, line 4goto pb1Wait ; Loop if not clear

;============================; dis play and send "Ready-";============================; Set LCD base ad dress

call line1; Ini tial ize sys tem for UART em u la tion at 2400 baud

call initTTY; Dis play on LCD and test se rial trans mis sion by send ing; the string "Ready-"

movlw ‘R’movwf sendData ; Store in send reg is tercall send8 ; Lo cal LCD dis play pro ce durecall sendTTY ; Lo cal send pro ce duremovlw ‘e’movwf sendData ; Store in send reg is tercall send8 ; Lo cal LCD dis play pro ce durecall sendTTY ; Lo cal send pro ce duremovlw ‘a’movwf sendData ; Store in send reg is tercall send8 ; Lo cal LCD dis play pro ce durecall sendTTY ; Lo cal send pro ce duremovlw ‘d’movwf sendData ; Store in send reg is tercall send8 ; Lo cal LCD dis play pro ce durecall sendTTY ; Lo cal send pro ce duremovlw ‘y’movwf sendData ; Store in send reg is tercall send8 ; Lo cal LCD dis play pro ce durecall sendTTY ; Lo cal send pro ce duremovlw ‘-’movwf sendData ; Store in send reg is tercall send8 ; Lo cal LCD dis play pro ce durecall sendTTY ; Lo cal send pro ce dure

; Init char ac ter coun ter and line coun ter vari ables for; LCD line scroll pro ce dure

movlw 0x06 ; 6 char ac ters al readydis played

movwf LCDcount

Com mu ni ca tions 613

Page 635: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

clrf LCDline ; LCD line coun ter;============================; mon i tor RS232 line;============================nextChar:

call rcvTTY ; Re ceive char ac ter; Store char ac ter in lo cal line buffer us ing in di rect; ad dress ing; 16-byte buffer named lineBuf starts at ad dress 0x0c; Reg is ter vari able bufPtr holds off set into buffer movlw 0x0c ; Buffer base ad dress

addwf bufPtr,w ; Add pointer in wmovwf FSR ; Value to in dex reg is termovf rcvData,w ; Char ac ter into wmovwf INDF ; Store w in [FSR]incf bufPtr,f ; Bump pointer

; Send char ac ter (still in w) call send8 ; Dis play itcall LCDscroll ; Scroll dis play linesgoto nextChar ; Con tinue

;============================================================; ini tial ize LCD for 4-bit mode ;============================================================initLCD:; Ini tial iza tion for Densitron LCD mod ule as fol lows:; 4-bit in ter face; 2 dis play lines of 16 char ac ters each; cur sor on; left-to-right in cre ment; cur sor shift right; no dis play shift;=======================|; set com mand mode |;=======================|

bcf PORTA,E_line ; E line lowbcf PORTA,RS_line ; RS line lowbcf PORTA,RW_line ; Write modecall de lay_125 ; de lay 125 mi cro sec onds

;***********************|; FUNCTION SET |;***********************|

movlw 0x28 ; 0 0 1 0 1 0 0 0 (FUNCTION SET); | | | |__ font se lect:; | | | 1 = 5x10 in 1/8 or 1/11; | | | 0 = 1/16 dc; | | |___ Duty cy cle se lect; | | 0 = 1/8 or 1/11

614 Chap ter 20

Page 636: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; | | 1 = 1/16; | |___ In ter face width; | 0 = 4 bits; | 1 = 8 bits; |___ FUNCTION SET COMMAND

call send8 ; 4-bit send rou tine

; Set 4-bit mode com mand must be re peatedmovlw 0x28call send8

;***********************|; DISPLAY AND CURSOR ON |;***********************|

movlw 0x0e ; 0 0 0 0 1 1 1 0 (DISPLAY ON/OFF); | | | |___ Blink char ac ter; | | | 1 = on, 0 = off; | | |___ Cursor on/off; | | 1 = on, 0 = off; | |____ Dis play on/off; | 1 = on, 0 = off; |____ COMMAND BIT

call send8;***********************|; set en try mode |;***********************|

movlw 0x06 ; 0 0 0 0 0 1 1 0 (ENTRY MODE SET); | | |___ dis play shift; | | 1 = shift; | | 0 = no shift; | |____ in cre ment mode; | 1 = left-to-right; | 0 = right-to-left; |___ COMMAND BIT

call send8

;***********************|; cur sor/dis play shift |;***********************|

movlw 0x14 ; 0 0 0 1 0 1 0 0 (CURSOR/DISPLAY; | | | | | SHIFT); | | | |_|___ don’t care; | |_|__ cur sor/dis play shift; | 00 = cur sor shift left; | 01 = cur sor shift right; | 10 = cur sor and dis play; | shifted left; | 11 = cur sor and dis play

Com mu ni ca tions 615

Page 637: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; | shifted right; |___ COMMAND BIT

call send8;***********************|; clear dis play |;***********************|

movlw 0x01 ; 0 0 0 0 0 0 0 1 (CLEAR DISPLAY); |___ COMMAND BIT

call send8; Per doc u men ta tion

call de lay_5 ; Test for busyre turn

;=======================; Pro ce dure to de lay; 42 mi cro sec onds;=======================de lay_125:

movlw D’42’ ; Re peat 42 ma chine cy clesmovwf count1 ; Store value in coun ter

re peat:decfsz count1,f ; Dec re ment coun tergoto re peat ; Con tinue if not 0re turn ; End of de lay

;=======================; Pro ce dure to de lay; 5 mil li sec onds;=======================de lay_5:

movlw D’41’ ; Coun ter = 41movwf count2 ; Store in vari able

de lay:call de lay_125 ; De laydecfsz count2,f ; 40 times = 5 mil li sec ondsgoto de layre turn ; End of de lay

;========================; pulse E line ;========================pulseE

bsf PORTA,E_line ; Pulse E linenopbcf PORTA,E_linere turn

;=============================; long de lay sub-rou tine

616 Chap ter 20

Page 638: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; (for de bug ging);=============================long_de lay

movlw D’200’ ; w = 200 dec i malmovwf J ; J = w

jloop:movwf K ; K = w

kloop:decfsz K,f ; K = K-1, skip next if zerogoto kloopdecfsz J,f ; J = J-1, skip next if zerogoto jloopre turn

;========================; send 2 nib bles in; 4-bit mode;========================; Pro ce dure to send two 4-bit val ues to Port-B lines; 7, 6, 5, and 4. High-or der nib ble is sent first; ON ENTRY:; w reg is ter holds 8-bit value to sendsend8:

movwf store1 ; Save orig i nal valuecall merge4 ; Merge with Port-B

; Now w has merged bytemovwf PORTB ; w to Port-Bcall pulseE ; Send data to LCD

; High nib ble is sentmovf store1,w ; Re cover byte into wswapf store1,w ; Swap nib bles in wcall merge4movwf PORTBcall pulseE ; Send data to LCDcall de lay_125 re turn

;=================; merge bits;=================; Rou tine to merge the 4 high-or der bits of the; value to send with the con tents of Port-B; so as to pre serve the 4 low-bits in Port-B; Logic:; AND value with 1111 0000 mask; AND Port-B with 0000 1111 mask; Now low nib ble in value and high nib ble in; PortB are all 0 bits:; value = vvvv 0000; PortB = 0000 bbbb

Com mu ni ca tions 617

Page 639: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; OR value and Port-B re sult ing in:; vvvv bbbb ; ON ENTRY:; w con tains value bits; ON EXIT:; w con tains merged bitsmerge4:

andlw b’11110000’ ; ANDing with 0 clears the; bit. ANDing with 1 pre serves; the orig i nal value

movwf store2 ; Save re sult in vari ablemovf PORTB,w ; Port-B to w reg is terandlw b’00001111’ ; Clear high nib ble in Port-B

; and pre serve low nib bleiorwf store2,w ; OR two operands in wre turn

;========================; Set ad dress reg is ter; to LCD line 1;========================; ON ENTRY:; Ad dress of LCD line 1 in con stant LCD_1 line1:

bcf PORTA,E_line ; E line lowbcf PORTA,RS_line ; RS line low, set up for

; con trolcall de lay_5 ; busy?

; Set to sec ond dis play linemovlw LCD_1 ; Ad dress and com mand bitcall send8 ; 4-bit rou tine

; Set RS line for databsf PORTA,RS_line ; Set up for datacall de lay_5 ; Busy?

; Clear buffer and pointercall blankBufclrf bufPtr ; Clear re turn

;========================; Set ad dress reg is ter; to LCD line 2;========================; ON ENTRY:; Ad dress of LCD line 2 in con stant LCD_2 line2:

bcf PORTA,E_line ; E line lowbcf PORTA,RS_line ; RS line low, set up for

; con trolcall de lay_5 ; Busy?

618 Chap ter 20

Page 640: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; Set to sec ond dis play linemovlw LCD_2 ; Ad dress with high-bit setcall send8

; Set RS line for databsf PORTA,RS_line ; RS = 1 for datacall de lay_5 ; Busy?

; Clear buffer and pointercall blankBufclrf bufPtrre turn

;==========================; scroll LCD line 2 ;==========================; Pro ce dure to count the num ber of char ac ters dis played on; each LCD line. If the num ber reaches the value in the; con stant LCDlimit, then dis play is scrolled to the sec ond; LCD line. If at the end of the sec ond line, then the; sec ond line is scrolled to the first line and dis play; con tin ues at the start of the sec ond line; re set to the first line.LCDscroll:

incf LCDcount,f ; Bump coun ter; Test for line limit

movf LCDcount,wsublw LCDlimit ; Count mi nus limitbtfss STATUS,Z ; Is count minus limit = 0goto scrollExit ; Go if not at end of line

; At this point the end of the LCD line was reached; Test if this is also the end of the sec ond line

movf LCDline,wsublw 0x01 ; Is it line 1?btfsc STATUS,Z ; Is LCDline mi nus 1 = 0?goto line2End ; Go if end of sec ond line

; At this point it is the end of the top LCD linecall line2 ; Scroll to sec ond lineclrf LCDcount ; Re set coun terincf LCDline,f ; Bump line coun tergoto scrollExit

; End of sec ond LCD lineline2End:; Scroll sec ond line to first line. Char ac ters to be; scrolled are stored in buffer start ing at ad dress 0x0c.; sixteen char ac ters are to be moved; First clear LCD

call initLCDcall de lay_5 ; Make sure not busy

; Set up for data

Com mu ni ca tions 619

Page 641: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

bcf PORTA,E_line ; E line lowbsf PORTA,RS_line ; RS line high for data

; Set up coun ter for 16 char ac tersmovlw D’16’ ; Coun ter = 16movwf count2

; Get ad dress of stor age buffermovlw 0x0cmovwf FSR ; W to FSR

getchar:movf INDF,w ; get char ac ter from dis play RAM

; lo ca tion pointed to by file se lect; reg is ter

call send8 ; 4-bit in ter face rou tine; Test for 16 char ac ters dis played

decfsz count2,f ; Dec re ment coun tergoto nextchar ; Skipped if done

; At this point scroll op er a tion has con cludedclrf LCDcount ; Clear coun ters

; Stay at line 2clrf LCDlineincf LCDline,fcall line2 ; Set for sec ond line

scrollExit:re turn

nextchar:incf FSR,f ; Bump pointergoto getchar

;============================; clear line buffer;============================; Use in di rect ad dress ing to store 16 blanks in the; buffer lo cated at 0x0c blankBuf:

Bank0movlw 0x0c ; Pointer to RAMmovwf FSR ; To in dex reg is ter

blank16:clrf INDF ; Clear memory pointed at by FSRincf FSR,f ; Bump pointerbtfss FSR,4 ; 000x0000 when bit 4 is set

; count reached 16goto blank16re turn

;============================================================; ini tial ize for TTY;============================================================

620 Chap ter 20

Page 642: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; Pro ce dure to ini tial ize RS232 re cep tion ; As sumes:; 2400 baud; 8 data bits; no par ity; one stop bitinitTTY:; First ini tial ize re ceiver to RS-232-C line pa ram e ters; Dis able global and pe riph eral in ter rupts; 7 6 5 4 3 2 1 0 <= INTCON bitmap; | ? | ? ? ? ? ? (? = un re lated bits); | |________________ Timer0 in ter rupt on over flow; |______________________ Global in ter rupts

bcf INTCON,5 ; Dis able TMR0 in ter ruptsbcf INTCON,7 ; Disable global in ter ruptsclrf TMR0 ; Re set timerclrwdt ; Clear WDT for prescaler

as signBank1

; Set up the OPTION regiser bitmap; 7 6 5 4 3 2 1 0 <= OPTION bits; 1 1 0 1 1 0 0 0 <= setup; | | | | | |__|__|_____ PS2-PS0 (prescaler bits); | | | | | Values for Timer0; | | | | | *000 = 1:2 001 = 1:4; | | | | | 010 = 1:8 011 = 1:16; | | | | | 100 = 1:32 101 = 1:64; | | | | | 110 = 1:128 111 = 1:256; | | | | |______________ PSA (prescaler as sign); | | | | 1 = to WDT; | | | | *0 = to Timer0; | | | |_________________ TOSE (Timer0 edge se lect); | | | 0 = in cre ment on low-to-high; | | | *1 = in cre ment in high-to-low; | | |____________________ TOCS (TMR0 clock source); | | *0 = in ter nal clock; | | 1 = RA4/TOCKI bit source; | |_______________________ INTEDG (Edge se lect); | 0 = fall ing edge; | *1 = ris ing edge; |__________________________ RBPU (Pullup en able); 0 = en abled; *1 = disabled

movlw b’11010000’ ; set up timer/coun termovwf OPTION_REGBank0re turn

;============================================================

Com mu ni ca tions 621

Page 643: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; re ceive char ac ter;============================================================; Re ceive a sin gle char ac ter through the se rial port.; As sumes: 4800 baud, 8 data bits, no par ity, 1 stop bit.; Re ceiving line is Port-A, line 0rcvTTY:

movlw 0x08 ; Coun ter for 8 bitsmovwf bitCount

; The start of char ac ter trans mis sion is sig naled by; the sender by set ting the line lowstartBit:

btfsc PORTA,0 ; Test for low on linegoto startBit ; Go if not low

;=========================; off set to data bit;=========================; At this point the re ceiver has found the fall ing; edge of the start bit. It must now wait one and; one-half the baud rate to syn chro nize in the cen ter; of the sender’s first data bit, as fol lows:; |<========= fall ing edge of START bit; | |<========== cen ter of start bit; | | |<====== cen ter of data bit; |-----|-----|;_____ ___________ __________; | | | | <== SIGNAL; ----------- ---------- ; |<-- 208 -->|h| <====== ms. for 4800 baud; ; Clock start count for one-half bit = 255 - 104 = 151; Clock start count for one full bit = 255 - 208 = 47; One clock cy cle is added for the movwf in struc tion: ; clkHalf = 152 (for one-half bit count down); clkFull = 48 (for one full bit count down)

movlw halfBaud ; Skip one-half bitmovwf TMR0 ; Ini tial ize tmr0 and start countbcf INTCON,2 ; Clear over flow flag

;============================; start bit;============================wait1:

btfss INTCON,2 ; Timer count over flow?goto wait1 ; No, keep wait ing

; At this point we are at the cen ter of the start bitbtfsc PORTA,0 ; Check to see it is still lowgoto startBit ; No, it is high. False start.

; At this point the clock is at the cen ter of the start; bit. The first data bit must be read one full baud

622 Chap ter 20

Page 644: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; pe riod latermovlw fullBaud ; One full bit de laymovwf TMR0 ; Start timerbcf INTCON,2 ; clear tmr0 over flow flag

wait2:btfss INTCON,2 ; End of one full baud pe riod?goto wait2 ; Wait if not end of pe riod

; Timer is now at the cen ter of the first/next data bit; Timer must be re set im me di ately so that code will not; lose synchronization with sender

movlw fullBaud ; Skip to next data bitmovwf TMR0 ; Re start timerbcf INTCON,2 ; Re set over flow flag

; Now the data bit can be read and and storedmovf PORTA,w ; Read Port-Bmovwf tempData ; Store in tem po rary vari ablerrf tempData,f ; Ro tate bit 0 into carry flagrrf rcvData,f ; Ro tate carry flag into

; stor age reg is ter high-or der; bit

decfsz bitCount,f ; End of data?goto wait2 ; Con tinue un til 8 bits re ceived

;============================; stop bit;============================stopWait:

btfss INTCON,2 ; Test timegoto stopWait ; Waitre turn ; Exit

;============================================================; send char ac ter;============================================================; Pro ce dure to send one char ac ter through the RS232 line.; As sumes: 2400 baud, 8 data bits, no par ity, one stop bit; Sending line is Port-B, line 0; ON ENTRY:; vari able sendData holds char ac ter to sendsendTTY:

movlw 0x08 ; Init bit coun termovwf bitCountbcf PORTB,0 ; Low for start bitmovlw fullBaud ; For one baud spacemovwf TMR0 ; Start timerbcf INTCON,2 ; Clear timer flag

start2snd:btfss INTCON,2 ; Full baud done?goto start2snd ; No

Com mu ni ca tions 623

Page 645: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

movlw fullBaud ; Re set for one full bit pe riodmovwf TMR0 ; Start timerbcf INTCON,2 ; Clear flag

; At this point the start bit has been sent; Data fol lowssendOut:

rrf sendData,f ; Ro tate bit into carrybcf PORTB,0 ; As sume data bit is 0btfsc STATUS,c ; Test if carry setbsf PORTB,0 ; Change bit to 1 if clear

; Hold bit for 1 baud pe riodtimeBit:

btfss INTCON,2 ; Wait for baud pe riod to endgoto timeBit ; Loop if not yetmovlw fullBaud ; Re set timermovwf TMR0 ; Start timerbcf INTCON,2 ; Clear flag

; Test for last bitdecfsz bitCount,f ; Count this bitgoto sendOut ; Con tinue if not last bit

; Done. Send stop bitbsf PORTB,0 ; High for stop bit

stopBit:btfss INTCON,2 ; Timer done?goto stopBit ; No

; Set Port-B line 0 high back againbsf PORTB,0call de lay_5 ; And hold re turn

End

20.6.5 SerComLCD Pro gram; File name: SerComLCD.asm; Last re vi sion: May 14, 2011; Au thors: Sanchez and Canton; Pro ces sor: 16F877;; De scrip tion:; De code 4 x 4 key pad, dis play scan code in LCD, and send; ASCII char ac ter through the se rial port. Also re ceive; data through se rial port and dis play on LCD. LCD lines; are scrolled by pro gram.; De fault se rial line set ting:; 2400 baud; no partity; 1 stop bit

624 Chap ter 20

Page 646: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; 8 char ac ter bits;; Pro gram uses 4-bit PIC-to-LCD in ter face.; Code as sumes that LCD is driven by Hitachi HD44780; con trol ler and PIC 16F977. Dis play sup ports two lines; each one with 20 char ac ters. The length, wir ing, and base; ad dress of each dis play line is stored in #de fine; state ments. These state ments can be ed ited to accommodate; a dif fer ent set up.; Key pad switch wir ing (val ues are scan codes):; -- KEYPAD -- ; 0 1 2 3 <= port B0 |; 4 5 6 7 <= port B1 |-- ROWS = OUTPUTS; 8 9 A B <= port B2 |; C D E F <= port B3 |; | | | |; | | | |_____ port B4 |; | | |_________ port B5 |-- COLUMNS = INPUTS; | |_____________ port B6 |; |_________________ port B7 |;; Op er a tions:; 1. Key press ac tion gen er ates a scan code in the range; 0x0 to 0xf.; 2. Scan code is con verted to an ASCII digit and dis played; on the LCD. LCD lines are scrolled as end-of-line is; reached.; 3. Char ac ters typed on the key pad are also trans mit ted; through the se rial port.; 4. Se rial port is polled for re ceived char ac ters. These; are dis played on the LCD.;; WARNING:; Code as sumes 4 MHz clock. De lay rou tines must be; ed ited for faster clock. Clock speed also de ter mines; val ues for baud rate set ting (see spbrgVal con stant).;;===========================; 16F877 switches;===========================; Switches used in __config di rec tive:; _CP_ON Code pro tec tion ON/OFF ; * _CP_OFF ; * _PWRTE_ON Power-up timer ON/OFF; _PWRTE_OFF ; _BODEN_ON Brown-out re set en able ON/OFF; * _BODEN_OFF ; * _PWRTE_ON Power-up timer en able ON/OFF

Com mu ni ca tions 625

Page 647: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; _PWRTE_OFF ; _WDT_ON Watchdog timer ON/OFF ; * _WDT_OFF; _LPV_ON Low volt age IC pro gram ming en able ON/OFF; * _LPV_OFF; _CPD_ON Data EE mem ory code pro tec tion ON/OFF; * _CPD_OFF; OSCILLATOR CONFIGURATIONS: ; _LP_OSC Low power crys tal oscillator; _XT_OSC Ex ter nal par al lel crys tal ocillator; * _HS_OSC High speed crys tal res o na tor; _RC_OSC Re sis tor/ca pac i tor oscillator; | (sim plest, 20% er ror); |; |_____ * in di cates setup val ues pres ently se lected

pro ces sor 16f877 ; De fine pro ces sor#in clude <p16f877.inc>__CONFIG _CP_OFF & _WDT_OFF & _BODEN_OFF & _PWRTE_ON &

_HS_OSC & _WDT_OFF & _LVP_OFF & _CPD_OFF

; __CONFIG di rec tive is used to em bed con fig u ra tion data; within the source file. The la bels fol low ing the di rec tive; are lo cated in the cor re spond ing .inc file.;============================================================; M A C R O S;============================================================; Macros to se lect the reg is ter banksBank0 MACRO ; Se lect RAM bank 0

bcf STATUS,RP0bcf STATUS,RP1ENDM

Bank1 MACRO ; Se lect RAM bank 1bsf STATUS,RP0bcf STATUS,RP1ENDM

Bank2 MACRO ; Se lect RAM bank 2bcf STATUS,RP0bsf STATUS,RP1ENDM

Bank3 MACRO ; Se lect RAM bank 3bsf STATUS,RP0bsf STATUS,RP1ENDM

;=====================================================

626 Chap ter 20

Page 648: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; con stant def i ni tions; for PIC-to-LCD pin wir ing and LCD line ad dresses;=====================================================#de fine E_line 1 ;|#de fine RS_line 0 ;| -- from wir ing di a gram #de fine RW_line 2 ;|; LCD line ad dresses (from LCD data sheet)#de fine LCD_1 0x80 ; First LCD line con stant#de fine LCD_2 0xc0 ; Sec ond LCD line con stant#de fine LCDlimit .20; Num ber of char ac ters per line#de fine spbrgVal .25; For 2400 baud on 4 MHz clock; Note: The con stants that de fine the LCD dis play; line ad dresses have the high-or der bit set; so as to meet the re quire ments of con trol ler; com mands. ;;=====================================================; vari ables in PIC RAM;=====================================================; Lo cal vari ables

cblock 0x20 ; Start of blockcount1 ; Coun ter # 1count2 ; Coun ter # 2count3 ; Coun ter # 3J ; Coun ter JK ; Coun ter Kstore1 ; Lo cal stor agestore2

; For LCDscroll pro ce dureLCDcount ; Coun ter for char ac ters per lineLCDline ; Cur rent dis play line (0 or 1)

; Key pad pro cess ing vari ableskeyMask ; For key pad pro cess ingrowMask ; For mask ing-off key rowsrowCode ; Row ad dend for cal cu lat ing scan coderowCount ; Coun ter for key rows (0 to 3)scanCode ; Fi nal key codenewScan ; 0 if no new scan code de tected

; Com mu ni ca tions vari ablesnewData ; not 0 if new data re ceivedascValerrorFlagsendc

;============================================================; P R O G R A M;============================================================

org 0 ; start at ad dress

Com mu ni ca tions 627

Page 649: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

goto main; Space for in ter rupt han dlers

org 0x08main:; Wiring:; LCD data to Port D, lines 0 to 7; E line -> port E, 1; RW line -> port E, 2; RS line -> port E, 0; Set PORTE D and E for out put; Data mem ory bank se lec tion bits:; RP1:RP0 Bank; 0:0 0 Ports A,B,C,D, and E; 0:1 1 Tris A,B,C,D, and E; 1:0 2; 1:1 3; First, ini tial ize Port-B by clear ing latches

clrf STATUSclrf PORTB

; Se lect bank 1 to tris Port D for out putbcf STATUS,RP1 ; Clear banks 2/3 se lec torbsf STATUS,RP0 ; Se lect bank 1 for tris

; reg is ters; Tris Port D for out put. Port D lines 4 to 7 are wired; to LCD data lines. Port D lines 0 to 4 are wired to LEDs.

movlw B’00000000’movwf TRISD ; and Port D

; By de fault, Port-A lines are an a log. To con fig ure them; as dig i tal code, must set bits 1 and 2 of the ADCON1; reg is ter (in bank 1)

movlw 0x06 ; bi nary 0000 0110 is code to; make all Port-A lines digital

movwf ADCON1; Port-B lines are wired to key pad swtiches, as fol lows:; 7 6 5 4 3 2 1 0; | | | | |_|_|_|_____ switch rows (out put); |_|_|_|_____________ switch col umns (in put); rows must be de fined as out put and col umns as in put

movlw b’11110000’movwf TRISB

; Tris port E for out putmovlw B’00000000’movwf TRISE ; Tris port E

; En able Port-B pullups for switches in OPTION reg is ter; 7 6 5 4 3 2 1 0 <= OPTION bits; | | | | | |__|__|_____ PS2-PS0 (prescaler bits); | | | | | Values for Timer0; | | | | | 000 = 1:2 001 = 1:4

628 Chap ter 20

Page 650: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; | | | | | 010 = 1:8 011 = 1:16; | | | | | 100 = 1:32 101 = 1:64; | | | | | 110 = 1:128 *111 = 1:256; | | | | |______________ PSA (prescaler as sign); | | | | *1 = to WDT; | | | | 0 = to Timer0; | | | |_________________ TOSE (Timer0 edge se lect); | | | *0 = in cre ment on low-to-high; | | | 1 = in cre ment on high-to-low; | | |____________________ TOCS (TMR0 clock source); | | *0 = in ter nal clock; | | 1 = RA4/TOCKI bit source; | |_______________________ INTEDG (Edge se lect); | *0 = fall ing edge; |__________________________ RBPU (Pullup en able); *0 = en abled; 1 = disabled

movlw b’00001000’movwf OPTION_REG

; Back to bank 0bcf STATUS,RP0

; Ini tial ize se rial port for 9600 baud, 8 bits, no par ity; 1 stop

call InitSerial; Test se rial trans mis sion by send ing “RDY-”

movlw ‘R’call SerialSendmovlw ‘D’call SerialSendmovlw ‘Y’call SerialSendmovlw ‘-’call SerialSendmovlw 0x20call SerialSend

; Clear all out put linesmovlw b’00000000’ movwf PORTDmovwf PORTE

; Wait and ini tial ize HD44780call de lay_5 ; Al low LCD time to ini tial ize it selfcall initLCD ; Then do forced ini tial iza tioncall de lay_5 ; (Wait prob a bly not nec es sary)

; Clear char ac ter coun ter and line coun ter vari ablesclrf LCDcountclrf LCDline

; Set dis play ad dress to start of sec ond LCD linecall line1

Com mu ni ca tions 629

Page 651: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

;============================================================; scan key pad ;============================================================; Key pad switch wir ing:; x x x x <= port B0 |; x x x x <= port B1 |-- ROWS = OUTPUTS; x x x x <= port B2 |; x x x x <= port B3 |; | | | |; | | | |_____ port B4 |; | | |_________ port B5 |-- COLUMNS = INPUTS; | |_____________ port B6 |; |_________________ port B7 |; Swtiches are con nected to Port-B lines; Clear scan code reg is ter

clrf scanCode;============================; scan key pad and dis play;============================keyScan:; Port-B lines are wired to pushbutton switches, as fol lows:; 7 6 5 4 3 2 1 0; | | | | |_|_|_|_____ switch rows (out put); |_|_|_|_____________ switch col umns (in put); Key pad pro cess ing:; switch rows are suc ces sively grounded (row = 0); Then col umn val ues are tested. If a col umn re turns 0; in a 0 row, that switch is down.; Ini tial ize row code ad dend

clrf rowCode ; First row is code 0clrf newScan ; No new scan code de tected

; Ini tial ize row countmovlw D’4’ ; Four rows movwf rowCount ; Reg is ter vari ablemovlw b’11111110’ ; All set but LOBmovwf rowMask

keyLoop:; Ini tial ize row eliminator mask:; The row mask is ANDed with the key mask to suc ces sively; mask off each row, for ex am ple:;; |----- row 3; ||---- row 2; |||--- row 1; ||||-- row 0; 0000 1111 <= key mask; AND 1111 1101 <= mask for row 1; ---------

630 Chap ter 20

Page 652: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; 0000 1101 <= row 1 is masked off;; The row mask, which is initally 1111 1110, is ro tated left; through the carry in or der to mask off the next row

movlw b’00001111’ ; Mask off all linesmovwf keyMask ; To lo cal reg is ter

; Set row mask for cur rent rowmovf rowMask,w ; Mask to wandwf keyMask,f ; Up date key maskmovf keyMask,w ; Key mask to wmovwf PORTB ; Mask off Port-B lines

; Read Port-B lines 4 to 7 (col umns are in put)btfss PORTB,4call col0 ; Key col umn pro ce duresbtfss PORTB,5call col1btfss PORTB,6call col2btfss PORTB,7call col3

; In dex to next row by add ing 4 to row codemovf rowCode,w ; Code to waddlw D’4’movwf rowCode

;=========================; shift row mask;=========================; Set the carry flag

bsf STATUS,Crlf rowMask,f ; Ro tate mask bits in stor age

;=========================; end of key pad?;=========================; Test for last key row (max i mum count is 4)

decfsz rowCount,f ; Dec re ment coun tergoto keyLoop

;============================================================;============================================================; dis play, send, and re ceive data;============================================================;============================================================; At this point all keys have been tested.; Vari able newScan = 0 if no new scan code de tected, else; vari able scanCode holds scan code

movf newScan,f ; Copy onto intsef (sets Z; flag)

btfsc STATUS,Z ; Is it zero?goto re ceive

Com mu ni ca tions 631

Page 653: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; At this point a new scan code is de tectedmovf scanCode,w ; To w

; If scan code is in the range 0 to 9, that is, a dec i mal; digit, then ASCII con ver sion con sists of add ing 0x30.; If the scan code rep re sents one of the hex let ters; (0xa to 0xf), then ASCII con ver sion re quires add ing; 0x37

sublw 0x09 ; 9 - w; if w from 0 to 9 then 9 - w = pos i tive (C flag = 1); if w = 0xa then 9 - 10 = -1 (C flag = 0); if w = 0xc then 9 - 12 = -2 (C flag = 0)

btfss STATUS,C ; Test carry flaggoto hexLetter ; Carry clear, must be a let ter

; At this point scan code is a dec i mal digit in the; range 0 to 9. Convert to ASCII by add ing 0x30

movf scanCode,w ; Re cover scan codeaddlw 0x30 ; Convert to ASCIIgoto displayDig

hexLetter:movf scanCode,w ; Re cover scan codeaddlw 0x37 ; Convert to ASCII

displayDig:; Store so it can be sent

movwf ascValcall send8 ; Dis play rou tinecall LCDscrollcall long_de lay ; Debounce

; Re cover ASCIImovf ascVal,wcall SerialSendgoto scanExit

;==========================; re ceive se rial data;==========================re ceive:; Call se rial re ceive pro ce dure

call SerialRcv; HOB of newData reg is ter is set if new data; re ceived

btfss newData,7goto scanExit

; At this point, new data was re ceivedcall send8 ; Dis play in LCDcall LCDscroll ; Scroll at end of line

scanExit:goto keyScan ; Con tinue

;==========================; cal cu late scan code

632 Chap ter 20

Page 654: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

;==========================; The col umn po si tion is added to the row code (stored; in rowCode reg is ter). Sum is the scan code.col0:

movf rowCode,w ; Row code to waddlw 0x00 ; Add 0 (clearly not

nec es sary)movwf scanCode ; Fi nal valueincf newScan,f ; New scan codere turn

col1:movf rowCode,w ; Row code to waddlw 0x01 ; Add 1movwf scanCodeincf newScan,fre turn

col2:movf rowCode,w ; Row code to waddlw 0x02 ; Add 2movwf scanCodeincf newScan,fre turn

col3:movf rowCode,w ; Row code to waddlw 0x03 ; Add 3movwf scanCodeincf newScan,fre turn

;============================================================;============================================================; L O C A L P R O C E D U R E S ;============================================================;============================================================;==========================; init LCD for 4-bit mode ;==========================initLCD:; Ini tial iza tion for Densitron LCD mod ule as fol lows:; 4-bit in ter face; 2 dis play lines of 16 char ac ters each; cur sor on; left-to-right in cre ment; cur sor shift right; no dis play shift;=======================|

Com mu ni ca tions 633

Page 655: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; set com mand mode |;=======================|

bcf PORTE,E_line ; E line lowbcf PORTE,RS_line ; RS line lowbcf PORTE,RW_line ; Write modecall de lay_125 ; de lay 125

mi cro sec onds;***********************|; FUNCTION SET |;***********************|

movlw 0x28 ; 0 0 1 0 1 0 0 0 (FUNCTION SET); | | | |__ font se lect:; | | | 1 = 5x10 in 1/8 or 1/11; | | | 0 = 1/16 dc; | | |___ Duty cy cle se lect; | | 0 = 1/8 or 1/11; | | 1 = 1/16; | |___ In ter face width; | 0 = 4 bits; | 1 = 8 bits; |___ FUNCTION SET COMMAND

call send8 ; 4-bit send rou tine

; Set 4-bit mode com mand must be re peatedmovlw 0x28call send8

;***********************|; DISPLAY AND CURSOR ON |;***********************|

movlw 0x0e ; 0 0 0 0 1 1 1 0 (DISPLAY ON/OFF); | | | |___ Blink char ac ter; | | | 1 = on, 0 = off; | | |___ Cursor on/off; | | 1 = on, 0 = off; | |____ Dis play on/off; | 1 = on, 0 = off; |____ COMMAND BIT

call send8;***********************|; set en try mode |;***********************|

movlw 0x06 ; 0 0 0 0 0 1 1 0 (ENTRY MODE SET); | | |___ dis play shift; | | 1 = shift; | | 0 = no shift; | |____ in cre ment mode; | 1 = left-to-right

634 Chap ter 20

Page 656: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; | 0 = right-to-left; |___ COMMAND BIT

call send8

;***********************|; cur sor/dis play shift |;***********************|

movlw 0x14 ; 0 0 0 1 0 1 0 0 (CURSOR/DISPLAYSHIFT) ; | | | |_|___ don’t care

; | |_|__ cur sor/dis play shift; | 00 = cur sor shift left; | 01 = cur sor shift right; | 10 = cur sor and dis play; | shifted left; | 11 = cur sor and dis play; | shifted right; |___ COMMAND BIT

call send8;***********************|; clear dis play |;***********************|

movlw 0x01 ; 0 0 0 0 0 0 0 1 (CLEAR DISPLAY); |___ COMMAND BIT

call send8; Per doc u men ta tion

call de lay_5 ; Test for busyre turn

;=======================; Pro ce dure to de lay; 42 mi cro sec onds;=======================de lay_125:

movlw D’42’ ; Re peat 42 ma chine cy clesmovwf count1 ; Store value in coun ter

re peatdecfsz count1,f ; Dec re ment coun tergoto re peat ; Con tinue if not 0re turn ; End of de lay

;=======================; Pro ce dure to de lay; 5 mil li sec onds;=======================de lay_5:

movlw D’42’ ; Coun ter = 41movwf count2 ; Store in vari able

Com mu ni ca tions 635

Page 657: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

de laycall de lay_125 ; De laydecfsz count2,f ; 40 times = 5 mil li sec ondsgoto de layre turn ; End of de lay

;========================; pulse E line ;========================pulseE

bsf PORTE,E_line ; Pulse E linenopbcf PORTE,E_linere turn

;=============================; long de lay sub-rou tine;=============================long_de lay

movlw D’200’ ; w de lay countmovwf J ; J = w

jloop: movwf K ; K = wkloop:

decfsz K,f ; K = K-1, skip next if zerogoto kloopdecfsz J,f ; J = J-1, skip next if zerogoto jloopre turn

;========================; send 2 nib bles in; 4-bit mode;========================; Pro ce dure to send two 4-bit val ues to Port-B lines; 7, 6, 5, and 4. High-or der nib ble is sent first; ON ENTRY:; w reg is ter holds 8-bit value to sendsend8:

movwf store1 ; Save orig i nal valuecall merge4 ; Merge with Port-B

; Now w has merged bytemovwf PORTD ; w to Port Dcall pulseE ; Send data to LCD

; High nib ble is sentmovf store1,w ; Re cover byte into wswapf store1,w ; Swap nib bles in wcall merge4movwf PORTDcall pulseE ; Send data to LCD

636 Chap ter 20

Page 658: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

call de lay_125re turn

;==========================; merge bits;==========================; Rou tine to merge the 4 high-or der bits of the; value to send with the con tents of Port-B; so as to pre serve the 4 low-bits in Port-B; Logic:; AND value with 1111 0000 mask; AND Port-B with 0000 1111 mask; Now low nib ble in value and high nib ble in; Port-B are all 0 bits:; value = vvvv 0000; Port-B = 0000 bbbb; OR value and Port-B re sult ing in:; vvvv bbbb ; ON ENTRY:; w con tain value bits; ON EXIT:; w con tains merged bitsmerge4:

andlw b’11110000’ ; ANDing with 0 clears the; bit. ANDing with 1 pre serves; the orig i nal value.

movwf store2 ; Save re sult in vari ablemovf PORTD,w ; Port-B to w reg is ter.andlw b’00001111’ ; Clear high nib ble in Port-B

; and pre serve low nib bleiorwf store2,w ; OR two operands in w.re turn

;==========================; Set ad dress reg is ter; to LCD line 2;==========================; ON ENTRY:; Ad dress of LCD line 2 in con stant LCD_2 line2:

bcf PORTE,E_line ; E line lowbcf PORTE,RS_line ; RS line low, set up for

con trolcall de lay_5 ; Busy?

; Set to sec ond dis play linemovlw LCD_2 ; Ad dress with high-bit setcall send8

; Set RS line for databsf PORTE,RS_line ; RS = 1 for data

Com mu ni ca tions 637

Page 659: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

call de lay_5 ; Busy?re turn

;==========================; Set ad dress reg is ter; to LCD line 1;==========================; ON ENTRY:; Ad dress of LCD line 1 in con stant LCD_1 line1:

bcf PORTE,E_line ; E line lowbcf PORTE,RS_line ; RS line low, set up for

con trolcall de lay_5 ; busy?

; Set to sec ond dis play linemovlw LCD_1 ; Ad dress and com mand bitcall send8 ; 4-bit rou tine

; Set RS line for databsf PORTE,RS_line ; Set up for datacall de lay_5 ; Busy?re turn

;==========================; scroll to LCD line 2 ;==========================; Pro ce dure to count the num ber of char ac ters dis played on; each LCD line. If the num ber reaches the value in the; con stant LCDlimit, then dis play is scrolled to the sec ond; LCD line. If at the end of the sec ond line, then LCD is; re set to the first line.LCDscroll:

incf LCDcount,f ; Bump coun ter; Test for line limit

movf LCDcount,wsublw LCDlimit ; Count mi nus limitbtfss STATUS,Z ; Is count minu limit = 0?goto scrollExit ; Go if not at end of line

; At this point the end of the LCD line was reached; Test if this is also the end of the sec ond line

movf LCDline,wsublw 0x01 ; Is it line 1?btfsc STATUS,Z ; Is LCDline mi nus 1 = 0?goto line2End ; Go if end of sec ond line

; At this point it is the end of the top LCD linecall line2 ; Scroll to sec ond lineclrf LCDcount ; Re set coun terincf LCDline,f ; Bump line coun tergoto scrollExit

638 Chap ter 20

Page 660: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; End of sec ond LCD lineline2End:

call initLCD ; Re setclrf LCDcount ; Clear coun tersclrf LCDlinecall line1 ; Dis play to first line

scrollExit:re turn

;==============================================================; com mu ni ca tions pro ce dures;==============================================================; Initizalize se rial port for 2400 baud, 8 bits, no par ity,; 1 stopInitSerial:

Bank1 ; Macro to se lect bank1; Bits 6 and 7 of Port C are mul ti plexed as TX/CK and RX/DT; for USART op er a tion. These bits must be set to in put in the; TRISC reg is ter

movlw b’11000000’ ; Bits for TX and RXiorwf TRISC,f ; OR into Trisc reg is ter

; The asyn chron ous baud rate is cal cu lated as fol lows:; Fosc; ABR = ---------; S*(x+1); where x is value in the SPBRG reg is ter and S is 64 if the high; baud rate se lect bit (BRGH) in the TXSTA con trol reg is ter is; clear, and 16 if the BRGH bit is set. For set ting to 9600 baud; using a 4 MHz os cil la tor at a high-speed baud rate the for mula; is:; 4,000,000 4,000,000; --------- = --------- = 9,615 baud (0.16% er ror); 16*(25+1) 416 ;; At slow speed (BRGH = 0); 4,000,000 4,000,000; --------- = --------- = 2,403.85 (0.16% er ror); 64*(25+1) 1,664 ;

movlw spbrgVal ; Value in spbrgVal = 25movwf SPBRG ; Place in baud rate gen er a tor

; TXSTA (Trans mit Sta tus and Con trol Reg is ter) bitmap:; 7 6 5 4 3 2 1 0 <== bits; | | | | | | | |______ TX9D 9th data bit on ?; | | | | | | | (used for par ity); | | | | | | |_________ TRMT Trans mit Shift Reg is ter ; | | | | | | 1 = TSR empty; | | | | | | * 0 = TSR full

Com mu ni ca tions 639

Page 661: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; | | | | | |____________ BRGH High Speed Baud Rate; | | | | | (Asyn chron ous mode only); | | | | | 1 = high speed (* 4); | | | | | * 0 = low speed; | | | | |__________ NOT USED; | | | |_____________ SYNC USART Mode Se lect; | | | 1 = syncrhonous mode; | | | * 0 = asyn chron ous mode; | | |________________ TXEN Trans mit En able; | | * 1 = trans mit en abled; | | 0 = trans mit disabled; | |___________________ TX9 En able 9-bit Trans mit; | 1 = 9-bit trans mis sion mode; | * 0 = 8-bit mode; |______________________ CSRC Clock Source Se lect; Not used in asyn chron ous mode; Syn chro nous mode:; 1 = Mas ter Mode (in ter nal clock); * 0 = Slave mode (ex ter nal clock); Setup value: 0010 0000 = 0x20

movlw 0x20 ; En able trans mis sion and high baud; rate

movwf TXSTABank0 ; Bank 0

; RCSTA (Re ceive Sta tus and Con trol Reg is ter) bitmap:; 7 6 5 4 3 2 1 0 <== bits; | | | | | | | |______ RX9D 9th data bit re ceived?; | | | | | | | (can be par ity bit); | | | | | | |_________ OERR Over run errror?; | | | | | | 1 = er ror (cleared by soft ware); | | | | | |____________ FERR Framing Er ror?; | | | | | 1 = er ror ; | | | | |_______________ NOT USED; | | | |____________ CREN Con tin u ous Re ceive En able; | | | Asyn chron ous mode:; | | | * 1 = En ables con tin u ous re ceive; | | | 0 = Dis ables con tin u ous re ceive; | | | Syn chro nous mode:; | | | 1 = En ables un til CREN cleared; | | | 0 = Dis ables continuous re ceive ; | | |_______________ SREN Sin gle Re ceive En able; | | ? Asyn chron ous mode = don’t care; | | Syn chro nous mas ter mode:; | | 1 = En able sin gle re ceive; | | 0 = Dis able sin gle re ceive; | |__________________ RX9 9th-bit Re ceive En able ; | 1 = 9-bit re cep tion; | * 0 = 8-bit re cep tion

640 Chap ter 20

Page 662: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; |_____________________ SPEN Se rial Port En able; * 1 = RX/DT and TX/CK are se rial pins

; 0 = Se rial port dis abled; Setup value: 1001 0000 = 0x90

movlw 0x90 ; En able se rial port and; con tin u ous re cep tion

movwf RCSTA;

clrf errorFlags ; Clear lo cal er ror flags; reg is ter

re turn

;==============================; trans mit data;==============================; Test for Trans mit Reg is ter Empty and trans mit data in wSerialSend:

Bank0 ; Se lect bank 0btfss PIR1,TXIF ; check if trans mit ter busygoto $-1 ; wait un til trans mit ter is

; not busymovwf TXREG ; and trans mit the datare turn

;==============================; re ceive data;==============================; Pro ce dure to test line for data re ceived and re turn value; in w. Over run and fram ing er rors are de tected and; re mem bered in the vari able errorFlags, as fol lows:; 7 6 5 4 3 2 1 0 <== errorFlags; |-- not used - | |__|______ over run er ror; |______ fram ing er rorSerialRcv:

clrf newData ; Clear new data re ceived reg is terBank0 ; Se lect bank 0

; Bit 5 (RCIF) of the PIR1 Reg is ter is clear if the USART; re ceive buffer is empty. If so, no data has been re ceived

btfss PIR1,RCIF ; Check for re ceived datare turn ; Exit if no data

; At this point, data has been re ceived. First elim i nate; pos si ble er rors: over run and fram ing.; Bit 1 (OERR) of the RCSTA reg is ter de tects over run; Bit 2 (FERR( of the RCSTA reg is ter de tects fram ing er ror

btfsc RCSTA,OERR ; Test for over run er rorgoto OverErr ; Er ror han dlerbtfsc RCSTA,FERR ; Test for fram ing er rorgoto FrameErr ; Er ror han dler

Com mu ni ca tions 641

Page 663: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; At this point no er ror was de tected; Re ceived data is in the USART RCREG reg is ter

movf RCREG,w ; get re ceived databsf newData,7 ; Set bit 7 to in di cate new

; data; Clear er ror flags

clrf errorFlagsre turn

;==========================; er ror han dlers;==========================OverErr:

bsf errorFlags,0 ; Bit 0 is over run er ror; Re set sys tem

bcf RCSTA,CREN ; Clear con tin u ous re ceive bitbsf RCSTA,CREN ; Set to re-en able re cep tionre turn

; er ror be cause FERR fram ing er ror bit is set; can do spe cial er ror han dling here - this code sim ply clears; and con tin uesFrameErr:

bsf errorFlags,1 ; Bit 1 is fram ing er rormovf RCREG,W ; Read and throw away bad datare turn

end

20.6.6 SerIntLCD Pro gram; File name: SerIntLCD.asm; Last re vi sion: May 14, 2011; Au thors: Sanchez and Canton; Pro ces sor: 16F877;; Interrupt-Driven ver sion of the SerComLCD pro gram;; De scrip tion:; De code 4 x 4 key pad, dis play scan code in LCD, and send; ASCII char ac ter through the se rial port. Also re ceive; data through se rial port and dis play on LCD. LCD lines; are scrolled by pro gram.; De fault se rial line set ting:; 2400 baud; no partity; 1 stop bit; 8 char ac ter bits;; Pro gram uses 4-bit PIC-to-LCD in ter face.

642 Chap ter 20

Page 664: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; Code as sumes that LCD is driven by Hitachi HD44780; con trol ler and PIC 16F977. Dis play sup ports two lines; each one with twenty char ac ters. The length, wir ing and; base ad dress of each dis play line is stored in #de fine; state ments. These state ments can be ed ited to ac com mo date; a dif fer ent setup.; Key pad switch wir ing (val ues are scan codes):; --- KEYPAD -- ; 0 1 2 3 <= port B0 |; 4 5 6 7 <= port B1 |-- ROWS = OUTPUTS; 8 9 A B <= port B2 |; C D E F <= port B3 |; | | | |; | | | |_____ port B4 |; | | |_________ port B5 |-- COLUMNS = INPUTS; | |_____________ port B6 |; |_________________ port B7 |;; Op er a tions:; 1. Key press ac tion gen er ates a scan code in the range; 0x0 to 0xf.; 2. Scan code is con verted to an ASCII digit and dis played; on the LCD. LCD lines are scrolled as end-of-line is; reached.; 3. Char ac ters typed on the key pad are also trans mit ted; through the se rial port.; 4. Re ceived char ac ters gen er ate an in ter rupt. The in ter rupt; han dler dis plays re ceived char ac ters on the LCD.;; WARNING:; Code as sumes 4 MHz clock. De lay rou tines must be; ed ited for faster clock. Clock speed also de ter mines; val ues for baud rate set ting (see spbrgVal con stant).;;===========================; 16F877 switches;===========================; Switches used in __config di rec tive:; _CP_ON Code pro tec tion ON/OFF ; * _CP_OFF ; * _PWRTE_ON Power-up timer ON/OFF; _PWRTE_OFF ; _BODEN_ON Brown-out re set en able ON/OFF; * _BODEN_OFF ; * _PWRTE_ON Power-up timer en able ON/OFF; _PWRTE_OFF ; _WDT_ON Watchdog timer ON/OFF ; * _WDT_OFF

Com mu ni ca tions 643

Page 665: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; _LPV_ON Low volt age IC pro gram ming en able ON/OFF; * _LPV_OFF; _CPD_ON Data EE mem ory code pro tec tion ON/OFF; * _CPD_OFF; OSCILLATOR CONFIGURATIONS: ; _LP_OSC Low power crys tal os cil la tor; _XT_OSC Ex ter nal par al lel res o na tor/crys tal os cil la tor

; * _HS_OSC High speed crys tal res o na tor; _RC_OSC Re sis tor/ca pac i tor os cil la tor; | (sim plest, 20% er ror); |; |_____ * in di cates setup val ues pres ently se lected

pro ces sor 16f877 ; De fine pro ces sor#in clude <p16f877.inc>__CONFIG _CP_OFF & _WDT_OFF & _BODEN_OFF & _PWRTE_ON &

_HS_OSC & _WDT_OFF & _LVP_OFF & _CPD_OFF

; __CONFIG di rec tive is used to em bed con fig u ra tion data; within the source file. The la bels fol low ing the di rec tive; are lo cated in the cor re spond ing .inc file.;============================================================; M A C R O S;============================================================; Macros to se lect the reg is ter banksBank0 MACRO ; Se lect RAM bank 0

bcf STATUS,RP0bcf STATUS,RP1ENDM

Bank1 MACRO ; Se lect RAM bank 1bsf STATUS,RP0bcf STATUS,RP1ENDM

Bank2 MACRO ; Se lect RAM bank 2bcf STATUS,RP0bsf STATUS,RP1ENDM

Bank3 MACRO ; Se lect RAM bank 3bsf STATUS,RP0bsf STATUS,RP1ENDM

;=====================================================; con stant def i ni tions; for PIC-to-LCD pin wir ing and LCD line ad dresses

644 Chap ter 20

Page 666: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

;=====================================================#de fine E_line 1 ;|#de fine RS_line 0 ;| -- from wir ing di a gram #de fine RW_line 2 ;|; LCD line ad dresses (from LCD data sheet)#de fine LCD_1 0x80 ; First LCD line con stant#de fine LCD_2 0xc0 ; Sec ond LCD line con stant#de fine LCDlimit .20; Num ber of char ac ters per line#de fine spbrgVal .25; For 2400 baud on 4 MHz clock; Note: The con stants that de fine the LCD dis play; line ad dresses have the high-or der bit set; so as to meet the re quire ments of con trol ler; com mands. ;;=====================================================; vari ables in PIC RAM;=====================================================; Lo cal vari ables

cblock 0x20 ; Start of blockcount1 ; Coun ter # 1count2 ; Coun ter # 2count3 ; Coun ter # 3J ; Coun ter JK ; Coun ter Kstore1 ; Lo cal stor agestore2

; For LCDscroll pro ce dureLCDcount ; Coun ter for char ac ters per lineLCDline ; Cur rent dis play line (0 or 1)

; Key pad pro cess ing vari ableskeyMask ; For key pad pro cess ingrowMask ; For mask ing-off key rowsrowCode ; Row ad dend for cal cu lat ing scan coderowCount ; Coun ter for key rows (0 to 3)scanCode ; Fi nal key codenewScan ; 0 if no new scan code de tected

; Com mu ni ca tions vari ablesascValerrorFlags

; Tem po rary stor age used by in ter rupt han dlertempWtempStatustempPclathtempFsrendc

;============================================================; P R O G R A M

Com mu ni ca tions 645

Page 667: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

;============================================================org 0 ; start at ad dress goto main

; Space for in ter rupt han dlersorg 0x04

InterruptCode:goto IntServ ; In ter rupt ser vice rou tine

;============================================================; main pro gram;============================================================main:; Wiring:; LCD data to Port D, lines 0 to 7; E line -> port E, 1; RW line -> port E, 2; RS line -> port E, 0; Set port D and E for out put; Data mem ory bank se lec tion bits:; RP1:RP0 Bank; 0:0 0 Ports A,B,C,D, and E; 0:1 1 Tris A,B,C,D, and E; 1:0 2; 1:1 3; First, ini tial ize Port-B by clear ing latches

clrf STATUSclrf PORTB

; Se lect bank 1 to tris Port D for out putBank1

; Tris Port D for out put. Port D lines 4 to 7 are wired; to LCD data lines. Port D lines 0 to 4 are wired to LEDs.

movlw B’00000000’movwf TRISD ; and Port D

; By de fault Port-A lines are an a log. To con fig ure them; as dig i tal code must set bits 1 and 2 of the ADCON1; reg is ter (in bank 1)

movlw 0x06 ; bi nary 0000 0110 is code to; make all Port-A lines digital

movwf ADCON1; Port-B lines are wired to key pad switches as fol lows:; 7 6 5 4 3 2 1 0; | | | | |_|_|_|_____ switch rows (out put); |_|_|_|_____________ switch col umns (in put); rows must be de fined as out put and col umns as in put

movlw b’11110000’movwf TRISB

; Tris port E for out putmovlw B’00000000’

646 Chap ter 20

Page 668: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

movwf TRISE ; Tris port E; En able Port-B pullups for switches in OPTION reg is ter; 7 6 5 4 3 2 1 0 <= OPTION bits; | | | | | |__|__|_____ PS2-PS0 (prescaler bits); | | | | | Values for Timer0; | | | | | 000 = 1:2 001 = 1:4; | | | | | 010 = 1:8 011 = 1:16; | | | | | 100 = 1:32 101 = 1:64; | | | | | 110 = 1:128 *111 = 1:256; | | | | |______________ PSA (prescaler as sign); | | | | *1 = to WDT; | | | | 0 = to Timer0; | | | |_________________ TOSE (Timer0 edge se lect); | | | *0 = in cre ment on low-to-high; | | | 1 = in cre ment on high-to-low; | | |____________________ TOCS (TMR0 clock source); | | *0 = in ter nal clock; | | 1 = RA4/TOCKI bit source; | |_______________________ INTEDG (Edge se lect); | *0 = fall ing edge; |__________________________ RBPU (Pullup en able); *0 = en abled; 1 = disabled

movlw b’00001000’movwf OPTION_REG

; Back to bank 0Bank0

; Ini tial ize se rial port for 9600 baud, 8 bits, no par ity; 1 stop

call InitSerial; Test se rial trans mis sion by send ing RDY-

movlw ‘R’call SerialSendmovlw ‘D’call SerialSendmovlw ‘Y’call SerialSendmovlw ‘-’call SerialSendmovlw 0x20call SerialSend

; Clear all out put linesmovlw b’00000000’ movwf PORTDmovwf PORTE

; Wait and ini tial ize HD44780call de lay_5 ; Al low LCD time to ini tial ize it selfcall initLCD ; Then do forced ini tial iza tion

Com mu ni ca tions 647

Page 669: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

call de lay_5 ; (Wait prob a bly not nec es sary); Clear char ac ter coun ter and line coun ter vari ables

clrf LCDcountclrf LCDline

; Set dis play ad dress to start of sec ond LCD linecall line1

;============================================================; scan key pad ;============================================================; Key pad switch wir ing:; x x x x <= Port B0 |; x x x x <= Port B1 |-- ROWS = OUTPUTS; x x x x <= port B2 |; x x x x <= port B3 |; | | | |; | | | |_____ port B4 |; | | |_________ port B5 |-- COLUMNS = INPUTS; | |_____________ port B6 |; |_________________ port B7 |; Switches are con nected to Port-B lines; Clear scan code reg is ter

clrf scanCode;============================; scan key pad and dis play;============================keyScan:; Port-B lines are wired to pushbutton switches as fol lows:; 7 6 5 4 3 2 1 0; | | | | |_|_|_|_____ switch rows (out put); |_|_|_|_____________ switch col umns (in put); Key pad pro cess ing:; switch rows are successively grounded (row = 0); Then col umn val ues are tested. If a col umn re turns 0; in a 0 row, that switch is down.; Ini tial ize row code ad dend

clrf rowCode ; First row is code 0clrf newScan ; No new scan code de tected

; Ini tial ize row countmovlw D’4’ ; Four rows movwf rowCount ; Reg is ter vari ablemovlw b’11111110’ ; All set but LOBmovwf rowMask

keyLoop:; Ini tial ize row eliminator mask:; The row mask is ANDed with the key mask to successively; mask off each row, for ex am ple:;; |----- row 3

648 Chap ter 20

Page 670: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; ||---- row 2; |||--- row 1; ||||-- row 0; 0000 1111 <= key mask; AND 1111 1101 <= mask for row 1; ----------; 0000 1101 <= row 1 is masked off;; The row mask, which is initally 1111 1110, is ro tated left; through the carry in or der to mask off the next row

movlw b’00001111’ ; Mask off all linesmovwf keyMask ; To lo cal reg is ter

; Set row mask for cur rent rowmovf rowMask,w ; Mask to wandwf keyMask,f ; Up date key maskmovf keyMask,w ; Key mask to wmovwf PORTB ; Mask off Port-B lines

; Read Port-B lines 4 to 7 (col umns are in put)btfss PORTB,4call col0 ; Key col umn pro ce duresbtfss PORTB,5call col1btfss PORTB,6call col2btfss PORTB,7call col3

; In dex to next row by add ing 4 to row codemovf rowCode,w ; Code to waddlw D’4’movwf rowCode

;=========================; shift row mask;=========================; Set the carry flag

bsf STATUS,Crlf rowMask,f ; Ro tate mask bits in stor age

;=========================; end of key pad?;=========================; Test for last key row (max i mum count is 4)

decfsz rowCount,f ; Dec re ment coun tergoto keyLoop

;============================================================;============================================================; dis play and send data;============================================================;============================================================; At this point all keys have been tested.

Com mu ni ca tions 649

Page 671: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; Vari able newScan = 0 if no new scan code de tected, else; vari able scanCode holds scan code

movf newScan,f ; Copy onto itself btfsc STATUS,Z ; Is it zerogoto ScanExit

; At this point a new scan code is de tectedmovf scanCode,w ; To w

; If scan code is in the range 0 to 9, that is, a dec i mal; digit, then ASCII con ver sion con sists of add ing 0x30.; If the scan code rep re sents one of the hex let ters; (0xa to 0xf), then ASCII con ver sion re quires add ing; 0x37

sublw 0x09 ; 9 - w; if w from 0 to 9 then 9 - w = pos i tive (C flag = 1); if w = 0xa then 9 - 10 = -1 (C flag = 0); if w = 0xc then 9 - 12 = -2 (C flag = 0)

btfss STATUS,C ; Test carry flaggoto hexLetter ; Carry clear, must be a

let ter ; At this point scan code is a dec i mal digit in the; range 0 to 9. Convert to ASCII by add ing 0x30

movf scanCode,w ; Re cover scan codeaddlw 0x30 ; Con vert to ASCIIgoto displayDig

hexLetter:movf scanCode,w ; Re cover scan codeaddlw 0x37 ; Con vert to ASCII

displayDig:; Store so it can be sent

movwf ascValcall send8 ; Dis play rou tinecall LCDscrollcall long_de lay ; Debounce

; Re cover ASCIImovf ascVal,wcall SerialSend

ScanExit:goto keyScan ; Con tinue

;==========================; cal cu late scan code;==========================; The col umn po si tion is added to the row code (stored; in rowCode reg is ter). Sum is the scan codecol0:

movf rowCode,w ; Row code to waddlw 0x00 ; Add 0 movwf scanCode ; Fi nal valueincf newScan,f ; New scan code

650 Chap ter 20

Page 672: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

re turncol1:

movf rowCode,w ; Row code to waddlw 0x01 ; Add 1movwf scanCodeincf newScan,fre turn

col2:movf rowCode,w ; Row code to waddlw 0x02 ; Add 2movwf scanCodeincf newScan,fre turn

col3:movf rowCode,w ; Row code to waddlw 0x03 ; Add 3movwf scanCodeincf newScan,fre turn

;============================================================;============================================================; L O C A L P R O C E D U R E S ;============================================================;============================================================;==========================; init LCD for 4-bit mode ;==========================initLCD:; Ini tial iza tion for Densitron LCD mod ule as fol lows:; 4-bit in ter face; 2 dis play lines of 16 char ac ters each; cur sor on; left-to-right in cre ment; cur sor shift right; no dis play shift;=======================|; set com mand mode |;=======================|

bcf PORTE,E_line ; E line lowbcf PORTE,RS_line ; RS line lowbcf PORTE,RW_line ; Write modecall de lay_125 ; de lay 125

mi cro sec onds;***********************|; FUNCTION SET |;***********************|

Com mu ni ca tions 651

Page 673: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

movlw 0x28 ; 0 0 1 0 1 0 0 0 (FUNCTION SET); | | | |__ font se lect:; | | | 1 = 5x10 in 1/8 or 1/11; | | | 0 = 1/16 dc; | | |___ Duty cy cle se lect; | | 0 = 1/8 or 1/11; | | 1 = 1/16 ); | |___ In ter face width; | 0 = 4 bits; | 1 = 8 bits; |___ FUNCTION SET COMMAND

call send8 ; 4-bit send rou tine

; Set 4-bit mode com mand must be re peatedmovlw 0x28call send8

;***********************|; DISPLAY AND CURSOR ON |;***********************|

movlw 0x0e ; 0 0 0 0 1 1 1 0 (DISPLAY ON/OFF); | | | |___ Blink char ac ter; | | | 1 = on, 0 = off; | | |___ Cursor on/off; | | 1 = on, 0 = off; | |____ Dis play on/off; | 1 = on, 0 = off; |____ COMMAND BIT

call send8;***********************|; set en try mode |;***********************|

movlw 0x06 ; 0 0 0 0 0 1 1 0 (ENTRY MODE SET); | | |___ dis play shift; | | 1 = shift; | | 0 = no shift; | |____ in cre ment mode; | 1 = left-to-right; | 0 = right-to-left; |___ COMMAND BIT

call send8

;***********************|; cur sor/dis play shift |;***********************|

movlw 0x14 ; 0 0 0 1 0 1 0 0 (CURSOR/DISPLAYSHIFT) ; | | | |_|___ don’t care

652 Chap ter 20

Page 674: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; | |_|__ cur sor/dis play shift; | 00 = cur sor shift left; | 01 = cur sor shift right; | 10 = cur sor and dis play; | shifted left; | 11 = cur sor and dis play; | shifted right; |___ COMMAND BIT

call send8;***********************|; clear dis play |;***********************|

movlw 0x01 ; 0 0 0 0 0 0 0 1 (CLEAR DISPLAY); |___ COMMAND BIT

call send8; Per doc u men ta tion

call de lay_5 ; Test for busyre turn

;=======================; Pro ce dure to de lay; 42 mi cro sec onds;=======================de lay_125:

movlw D’42’ ; Re peat 42 ma chine cy clesmovwf count1 ; Store value in coun ter

re peat:decfsz count1,f ; Dec re ment coun tergoto re peat ; Con tinue if not 0re turn ; End of de lay

;=======================; Pro ce dure to de lay; 5 mil li sec onds;=======================de lay_5:

movlw D’42’ ; Coun ter = 41movwf count2 ; Store in vari able

de lay:call de lay_125 ; De laydecfsz count2,f ; 40 times = 5 mil li sec ondsgoto de layre turn ; End of de lay

;========================; pulse E line ;========================pulseE

bsf PORTE,E_line ; Pulse E line

Com mu ni ca tions 653

Page 675: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

nopbcf PORTE,E_linere turn

;=============================; long de lay sub-rou tine;=============================long_de lay

movlw D’200’ ; w de lay countmovwf J ; J = w

jloop:movwf K ; K = w

kloop:decfsz K,f ; K = K-1, skip next if zerogoto kloopdecfsz J,f ; J = J-1, skip next if zerogoto jloopre turn

;========================; send 2 nib bles in; 4-bit mode;========================; Pro ce dure to send two 4-bit val ues to Port-B lines; 7, 6, 5, and 4. High-or der nib ble is sent first; ON ENTRY:; w reg is ter holds 8-bit value to sendsend8:

movwf store1 ; Save orig i nal valuecall merge4 ; Merge with Port-B

; Now w has merged bytemovwf PORTD ; w to Port Dcall pulseE ; Send data to LCD

; High nib ble is sentmovf store1,w ; Re cover byte into wswapf store1,w ; Swap nib bles in wcall merge4movwf PORTDcall pulseE ; Send data to LCDcall de lay_125re turn

;==========================; merge bits;==========================; Rou tine to merge the 4 high-or der bits of the; value to send with the con tents of Port-B; so as to pre serve the 4 low-bits in Port-B; Logic:

654 Chap ter 20

Page 676: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; AND value with 1111 0000 mask; AND Port-B with 0000 1111 mask; Now low nib ble in value and high nib ble in; Port-B are all 0 bits:; value = vvvv 0000; Port-B = 0000 bbbb; OR value and Port-B re sult ing in:; vvvv bbbb ; ON ENTRY:; w con tain value bits; ON EXIT:; w con tains merged bitsmerge4:

andlw b’11110000’ ; ANDing with 0 clears the; bit. ANDing with 1 pre serves; the orig i nal value

movwf store2 ; Save re sult in vari ablemovf PORTD,w ; Port-B to w reg is terandlw b’00001111’ ; Clear high nib ble in Port-B

; and pre serve low nib bleiorwf store2,w ; OR two operands in wre turn

;==========================; Set ad dress reg is ter; to LCD line 2;==========================; ON ENTRY:; Ad dress of LCD line 2 in con stant LCD_2 line2:

bcf PORTE,E_line ; E line lowbcf PORTE,RS_line ; RS line low, setup for

con trolcall de lay_5 ; Busy?

; Set to sec ond dis play linemovlw LCD_2 ; Ad dress with high-bit setcall send8

; Set RS line for databsf PORTE,RS_line ; RS = 1 for datacall de lay_5 ; Busy?re turn

;==========================; Set ad dress reg is ter; to LCD line 1;==========================; ON ENTRY:; Ad dress of LCD line 1 in con stant LCD_1

Com mu ni ca tions 655

Page 677: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

line1:bcf PORTE,E_line ; E line lowbcf PORTE,RS_line ; RS line low, set up for

; con trolcall de lay_5 ; busy?

; Set to sec ond dis play linemovlw LCD_1 ; Ad dress and com mand bitcall send8 ; 4-bit rou tine

; Set RS line for databsf PORTE,RS_line ; Set up for datacall de lay_5 ; Busy?re turn

;==========================; scroll to LCD line 2 ;==========================; Pro ce dure to count the num ber of char ac ters dis played on; each LCD line. If the num ber reaches the value in the; con stant LCDlimit, then dis play is scrolled to the sec ond; LCD line. If at the end of the sec ond line, then LCD is; re set to the first line.LCDscroll:

incf LCDcount,f ; Bump coun ter; Test for line limit

movf LCDcount,wsublw LCDlimit ; Count mi nus limitbtfss STATUS,Z ; Is count minus limit = 0?goto scrollExit ; Go if not at end of line

; At this point the end of the LCD line was reached; Test if this is also the end of the sec ond line

movf LCDline,wsublw 0x01 ; Is it line 1?btfsc STATUS,Z ; Is LCDline mi nus 1 = 0?goto line2End ; Go if end of sec ond line

; At this point it is the end of the top LCD linecall line2 ; Scroll to sec ond lineclrf LCDcount ; Re set coun terincf LCDline,f ; Bump line coun tergoto scrollExit

; End of sec ond LCD lineline2End:

call initLCD ; Re setclrf LCDcount ; Clear coun tersclrf LCDlinecall line1 ; Dis play to first line

scrollExit:re turn

656 Chap ter 20

Page 678: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

;==============================================================; com mu ni ca tions pro ce dures;==============================================================; Initizalize se rial port for 2400 baud, 8 bits, no par ity,; 1 stopInitSerial:

Bank1 ; Macro to se lect bank1; Bits 6 and 7 of Port C are mul ti plexed as TX/CK and RX/DT; for USART op er a tion. These bits must be set to in put in the; TRISC reg is ter

movlw b’11000000’ ; Bits for TX and RXiorwf TRISC,f ; OR into Trisc reg is ter

; The asyn chron ous baud rate is cal cu lated as fol lows:; Fosc; ABR = ---------; S*(x+1); where x is value in the SPBRG reg is ter and S is 64 if the high; baud rate se lect bit (BRGH) in the TXSTA con trol reg is ter is; clear, and 16 if the BRGH bit is set. For set ting to 9600 baud; usign a 4-MHz os cil la tor at a high-speed baud rate the for mula; is:; 4,000,000 4,000,000; --------- = --------- = 9,615 baud (0.16% er ror); 16*(25+1) 416 ;; At slow speed (BRGH = 0); 4,000,000 4,000,000; --------- = ---------- = 2,403.85 (0.16% er ror); 64*(25+1) 1,664 ;

movlw spbrgVal ; Value in spbrgVal = 25movwf SPBRG ; Place in baud rate gen er a tor

; TXSTA (Trans mit Sta tus and Con trol Reg is ter) bitmap:; 7 6 5 4 3 2 1 0 <== bits; | | | | | | | |______ TX9D 9nth data bit on; | | | | | | | ? (used for par ity); | | | | | | |_________ TRMT Trans mit Shift Reg is ter ; | | | | | | 1 = TSR empty; | | | | | | * 0 = TSR full; | | | | | |____________ BRGH High Speed Baud Rate; | | | | | (Asyn chron ous mode only); | | | | | 1 = high speed (* 4); | | | | | * 0 = low speed; | | | | |__________ NOT USED; | | | |_____________ SYNC USART Mode Se lect; | | | 1 = syncrhonous mode; | | | * 0 = asyn chron ous mode; | | |________________ TXEN Trans mit En able

Com mu ni ca tions 657

Page 679: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; | | * 1 = trans mit en abled; | | 0 = trans mit disabled; | |___________________ TX9 En able 9-bit Trans mit; | 1 = 9-bit trans mis sion mode; | * 0 = 8-bit mode; |______________________ CSRC Clock Source Se lect; Not used in asyn chron ous mode; Syn chro nous mode:; 1 = Mas ter Mode (in ter nal clock); * 0 = Slave mode (ex ter nal clock); Setup value: 0010 0000 = 0x20

movlw 0x20 ; En able trans mis sion and low baud ratemovwf TXSTABank0 ; Bank 0

; RCSTA (Re ceive Sta tus and Con trol Reg is ter) bitmap:; 7 6 5 4 3 2 1 0 <== bits; | | | | | | | |______ RX9D 9th data bit re ceived?; | | | | | | | (can be par ity bit); | | | | | | |_________ OERR Over run errror?; | | | | | | 1 = er ror (cleared by soft ware); | | | | | |____________ FERR Framing Er ror?; | | | | | 1 = er ror ; | | | | |_______________ NOT USED; | | | |____________ CREN Con tin u ous Re ceive En able; | | | Asyn chron ous mode:; | | | * 1 = En able con tin u ous re ceive; | | | 0 = Dis ables con tin u ous re ceive; | | | Syn chro nous mode:; | | | 1 = En ables un til CREN cleared; | | | 0 = Dis ables continous re ceive ; | | |_______________ SREN Sin gle Re ceive En able; | | ? Asyn chron ous mode = don’t care; | | Syn chro nous mas ter mode:; | | 1 = En able sin gle re ceive; | | 0 = Dis able sin gle re ceive; | |__________________ RX9 9th-bit Re ceive En able ; | 1 = 9-bit re cep tion; | * 0 = 8-bit re cep tion; |_____________________ SPEN Se rial Port En able; * 1 = RX/DT and TX/CK are se rial pins

; 0 = Se rial port dis abled; Setup value: 1001 0000 = 0x90

movlw 0x90 ; En able se rial port and; con tin u ous re cep tion

movwf RCSTA; En able global and pe riph eral in ter rupts; 7 6 5 4 3 2 1 0 <= INTCON bitmap

658 Chap ter 20

Page 680: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; | | - un re lated --; | |___________________ Pe riph eral in ter rupts en able; |______________________ Global in ter rupts en able

movlw b’11000000’movwf INTCON

; En able re ceive in ter rupt in PIE1 reg is ter; 7 6 5 4 3 2 1 0 <= PIE1 bitmap ; |________________ USART re ceive in ter rupt en able

Bank1movlw b’00100000’movwf PIE1

; Clear er ror flags reg is terBank0clrf errorFlagsre turn

;==============================; trans mit data;==============================; Test for Trans mit Reg is ter Empty and trans mit data in wSerialSend:

Bank0 ; Se lect bank 0btfss PIR1,TXIF ; check if trans mit ter busygoto $-1 ;wait un til trans mit ter is not busymovwf TXREG ;and trans mit the datare turn

;============================================================;============================================================; in ter rupt han dler for re ceived char ac ters;============================================================;============================================================IntServ:

movwf tempW ; Save Wmovf STATUS,W ; Store STATUS in Wclrf STATUS ; Se lect bank0movwf tempStatus ; Save STATUSmovf PCLATH,W ; Store PCLATH in Wmovwf tempPclath ; Save PCLATHclrf PCLATH ; Se lect pro gram mem ory page 0movf FSR,W ; Store FSR in Wmovwf tempFsr ; Save FSR value

; Test for re ceived data in ter ruptBank0 ; se lect bank0

; 7 6 5 4 3 2 1 0 <= PIR1; |__________________ (RCIF) USART re ceive in ter rupt; flag

Com mu ni ca tions 659

Page 681: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

btfsc PIR1,RCIF ; Test bit 5bsf STATUS,RP0 ; Bank 1 if RCIF set

; 7 6 5 4 3 2 1 0 <= PIE1; |__________________ (RCIE) Re ceive in ter rupt en able; bit

btfss PIE1,RCIE ; Test if in ter rupt is en abledgoto IntExit ; Go if not en abled

;==============================; re ceived data;==============================; Rou tine to han dle re ceived data. Over run and fram ing; er rors are de tected and re mem bered in the vari able; errorFlags, as fol lows:; 7 6 5 4 3 2 1 0 <== errorFlags; |- not used -- | | |___ over run er ror; |______ fram ing er ror

Bank0 ; Se lect bank 0; Test for over run and fram ing er rors.; Bit 1 (OERR) of the RCSTA reg is ter de tects over run; Bit 2 (FERR) of the RCSTA reg is ter de tects fram ing er ror

btfsc RCSTA,OERR ; Test for over run er rorgoto OverErr ; Er ror han dlerbtfsc RCSTA,FERR ; Test for fram ing er rorgoto FrameErr ; Er ror han dler

; At this point no er ror was de tected; Re ceived data is in the USART RCREG reg is ter

movf RCREG,w ; Re ceived data into wcall send8 ; Dis play in LCDcall LCDscroll ; Scroll at end of line

; Clear er ror flagsclrf errorFlagsgoto IntExit

;==========================; er ror han dlers;==========================; Er rors are re turned as bits in the errorFlags reg is ter; 7 6 5 4 3 2 1 0 <== errorFlags; |- not used -- | | |___ over run er ror; |______ fram ing er ror; Er ror re sponses to be made by main codeOverErr:

bsf errorFlags,0 ; Bit 0 is over run er ror; Re set sys tem

bcf RCSTA,CREN ; Clear con tin u ous re ceive bitbsf RCSTA,CREN ; Set to re-en able re cep tiongoto IntExit

FrameErr:bsf errorFlags,1; Bit 1 is fram ing er ror

660 Chap ter 20

Page 682: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

movf RCREG,W ; Read and throw away bad data;==============================; in ter rupt han dler exit;==============================IntExit:

Bank0movf tempFsr,w ; Re cover FSR valuemovwf FSR ; Re store in reg is termovf tempPclath,w ; Re cover PCLATH valuemovwf PCLATH ; Re store in reg is termovf tempStatus,W ; Re cover STATUSmovwf STATUS ; Re store in reg is terswapf tempW,F ; Swap file reg is ter in it selfswapf tempW,W ; Re store in reg is terretfieend

Com mu ni ca tions 661

Page 683: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

This page intentionally left blankThis page intentionally left blank

Page 684: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Ap pen dix A

Re sis tor Color Codes

The re sis tor color cod ing sys tem ap plies to car bon film, metal ox ide film, fus ible,pre ci sion metal film, and wirewound re sis tors of the ax ial lead type. This sys tem isem ployed when the sur face area is not suf fi cient to print the ac tual re sis tancevalue. Sev eral color codes are used, the most com mon ones are the 4-band and5-band codes. In the 4-band code, the first two bands rep re sent the mag ni tude of the re sis tance, the third band is a mul ti plier for this value, and the fourth band en codesthe er ror tol er ance. In the 5-band code the first three bands rep re sent the mag ni -tude, the fourth band serves as a mul ti plier, and the fifth band is the er ror tol er ance.

The color codes for the var i ous bands are as fol lows:

663

4-BAND CODE 1st BAND 2nd BAND MULTIPLIER TOLERANCE

5-BAND CODE 1st BAND 2nd BAND 3rd BAND MULTIPLIER TOLERANCE

Page 685: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

COLOR MAGNITUDE MULTIPLIER TOLERANCE

Black 0 1Brown 1 10 1%Red 2 100 2%Or ange 3 1KYel low 4 10KGreen 5 100K 0.5%Blue 6 1M 0.25%Vi o let 7 10M 0.10%Grey 8 0.05%White 9Gold 0.1 5%Sil ver 0.01 10%

To read the re sis tance value, first de ter mine if it is a 4-band or a 5-band en cod ing. Then pro ceed to iden tify the tol er ance band, which is usu ally ei ther gold or sil ver.Starting at the op po site end, read the two or three mag ni tude bands and mul ti plythis value by the mul ti plier band. For ex am ple, a re sis tor with four color bands, red,or ange, brown, and gold, is a 230-Ohm re sis tor with a 5% er ror tol er ance.

There are sev eral on line cal cu la tors that al low you to eas ily find the re sis tancevalue. You can lo cate these cal cu la tors by search ing for the keywords: re sis tor color codes.

664 Ap pen dix A

Page 686: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Appendix B

Essential Elec tron ics

B.1 AtomUn til the end of the nine teenth cen tury it was as sumed that mat ter was com posed ofsmall, in di vis i ble par ti cles called at oms. The work of J.J. Thomp son, Rutherford, andBohr proved that at oms were com plex struc tures that con tained both pos i tive andneg a tive par ti cles. The pos i tive ones were called pro tons and the neg a tive ones elec -trons.

Sev eral mod els of the atom were pro posed: the one by Thomp son as sumed thatthere were equal num bers of pro tons and elec trons in side the atom and that theseel e ments were scat tered at ran dom, as in the leftmost draw ing in Fig ure B-1. Later,in 1913, Rutherford's ex per i ments led him to be lieve that at oms con tained a heavycen tral pos i tive nu cleus with the elec trons scat tered ran domly. So he mod i fiedThomp son's model as shown in the cen ter draw ing. Finally, Neils Bohr theorizedthat elec trons had dif fer ent en ergy lev els, as if they moved around the nu cleus indif fer ent or bits, like plan ets around a sun. The rightmost draw ing rep re sents this or -bital model.

Fig ure B-1 Models of the Atom.

+

+

+

+

+

-

-

-

-

-+

+

++

+

-

-

-

-

-

++

++

+

-

-

-

-

-

665

Page 687: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

In ves ti ga tions also showed that the nor mal atom is elec tri cally neu tral. Pro tons(pos i tively charged par ti cles) have a mass of 1.673 times 10-24 grams. Elec trons (neg -a tively charged par ti cles) have a mass of 9.109 times 10-28 grams. Fur ther more, theor bital model of the atom is not ac tu ally valid be cause or bits have lit tle mean ing atthe atomic level. A more ac cu rate rep re sen ta tion is based on con cen tric spher i calshells about the nu cleus. An ac tive area of re search deals with atomic andsub-atomic struc tures.

The num ber of pro tons in an atom de ter mines its atomic num ber; for ex am ple,the hy dro gen atom has a sin gle pro ton and an atomic num ber of 1, he lium has twopro tons, car bon has six, and ura nium has ninety-two. But when we com pare the ra -tio of mass to elec tri cal charge in dif fer ent at oms we find that the nu cleus must bemade up of more than pro tons. For ex am ple, the he lium nu cleus has twice thecharge of the hy dro gen nu cleus, but four times the mass. The ad di tional mass is ex -plained by as sum ing that there is an other par ti cle in the nu cleus, called a neu tron,which has the same mass as the pro ton but no elec tri cal charge. Fig ure B-2 shows amodel of the he lium atom with two pro tons, two elec trons, and two neu trons.

Fig ure B-2 Model of the He lium Atom.

B.2 Iso topes and Ions

But na ture is not al ways con sis tent with such neat mod els. Whereas in a neu tral atom,the num ber of pro tons in the atomic nu cleus ex actly matches the num ber of elec trons, the num ber of pro tons need not match the num ber of neu trons. For ex am ple, most hy -dro gen at oms have a sin gle pro ton, but no neu trons, while a small per cent age haveone neu tron, and an even smaller one has two neu trons. In this sense, at oms of an el e -ment that con tains dif fer ent num bers of neu trons are iso topes of the el e ment; for ex -am ple wa ter (H2O) con tain ing hy dro gen at oms with two neu trons (deu te rium) iscalled “heavy water.”

An atom that is elec tri cally charged due to an ex cess or de fi ciency of elec trons iscalled an ion. When the dis lodged el e ments are one or more elec trons, the atomtakes a pos i tive charge. In this case it is called a pos i tive ion. When a stray elec troncom bines with a nor mal atom, the re sult is called a neg a tive ion.

666 Ap pen dix B

++

-

-

Page 688: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

B.3 Static Elec tric ityFree elec trons can travel through mat ter or re main at rest on a sur face. When elec -trons are at rest, the sur face is said to have a static elec tri cal charge that can be pos i -tive or neg a tive. When elec trons are mov ing in a stream-like man ner, we call thismove ment an elec tri cal cur rent. Elec trons can be re moved from a sur face by means of fric tion, heat, light, or a chem i cal re ac tion. In this case the sur face be comes pos i tivelycharged.

The an cient Greeks dis cov ered that when am ber was rubbed with wool the am -ber be came elec tri cally charged and would at tract small pieces of ma te rial. In thiscase, the charge is a pos i tive one. Fric tion can cause other ma te ri als, such as hardrub ber or plas tic, to be come neg a tively charged. Ob serving ob jects that have pos i -tive and neg a tive charges we note that like charges re pel and un like charges at tracteach other, as shown in Fig ure B-3.

Fig ure B-3 Like and Un like Charges.

Fric tion causes loosely held elec trons to be trans ferred from one sur face to theother. This re sults in a net neg a tive charge on the sur face that has gained elec trons,and a net pos i tive charge on the sur face that has lost elec trons. If there is no pathfor the elec trons to take to re store the bal ance of elec tri cal charges, these chargesre main un til they grad u ally leak off. If the elec tri cal charge con tin ues build ing, iteven tu ally reaches the point where it can no lon ger be con tained. In this case it dis -charges it self over any avail able path, as is the case with light ning.

Static elec tric ity does not move from one place to an other. While some in ter est -ing ex per i ments can be per formed with it, it does not serve the prac ti cal pur pose ofpro vid ing en ergy to do sus tained work.

Static elec tric ity cer tainly ex ists, and un der cer tain cir cum stances we must al low for it and ac count for its pos si ble pres ence, but it will not be the main theme ofthese pages.

Essential Elec tron ics 667

+ + +- - -

Page 689: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

B.4 Elec tri cal ChargePhys i cists of ten re sort to mod els and the o ries to de scribe and rep re sent some forcethat can be mea sured in the real world. But very of ten these mod els and rep re sen ta -tions are no more than con cepts that fail to phys i cally rep re sent the ob ject. In thissense, no one knows ex actly what grav ity is, or what an elec tri cal charge is. Grav ity,which can be felt and mea sured, is the force be tween masses.

By the same to ken, bod ies in "cer tain elec tri cal con di tions" also ex ert mea sur able forces on one an other. The term "elec tri cal charge" was coined to ex plain these ob -ser va tions.

Three sim ple pos tu lates or as sump tions serve to ex plain all elec tri cal phe nom -ena:

1. Elec tri cal charge ex ists and can be mea sured. Charge is mea sured in Cou lombs, aunit named for the French sci en tist Augustin de Coulomb.

2. Charge can be pos i tive or neg a tive.

3. Charge can nei ther be cre ated nor de stroyed. If two ob jects with equal amounts ofpos i tive and neg a tive charge are com bined on some ob ject, the re sult ing ob jectwill be elec tri cally neu tral and will have zero net charge.

B.4.1 Volt ageOb jects with op po site charges at tract, that is, they ex ert a force upon each other thatpulls them to gether. In this case, the mag ni tude of the force is pro por tional to theprod uct of the charge on each mass. Like grav ity, elec tri cal force de pends in versely on the dis tance squared be tween the two bod ies; the closer the bod ies, the greater theforce. Con se quently, it takes en ergy to pull apart ob jects that are pos i tively and neg a -tively charged, in the same man ner that it takes en ergy to raise a big mass against thepull of grav ity.

The po ten tial that sep a rate ob jects with op po site charges have for do ing work iscalled volt age. Volt age is mea sured in units of volts (V). The unit is named for theItal ian sci en tist Alessandro Volta.

The greater the charge and the greater the sep a ra tion, the greater the stored en -ergy, or volt age. By the same to ken, the greater the volt age, the greater the forcethat drives the charges to gether.

Volt age is al ways mea sured be tween two points that rep re sent the pos i tive andneg a tive charges. In or der to com pare volt ages of sev eral charged bod ies, a com -mon ref er ence point is nec es sary. This point is usu ally called “ground.”

B.4.2 Cur rentElec tri cal charge flows freely in cer tain ma te ri als, called con duc tors, but not in oth -ers, called in su la tors. Metals and a few other el e ments and com pounds are good con -duc tors, while air, glass, plas tics, and rub ber are in su la tors. In ad di tion, there is a third cat e gory of ma te ri als called semi con duc tors; some times they seem to be good con -

668 Ap pen dix B

Page 690: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

duc tors but much less so at other times. Sil i con and ger ma nium are two such semi con -duc tors. We dis cuss semi con duc tors in the con text of in te grated cir cuits in Sec tionB-7 of this ap pen dix.

Fig ure B-4 shows two con nected, op po sitely charged bod ies. The force be tweenthem has the po ten tial for work; there fore, there is volt age. If the two bod ies arecon nected by a con duc tor, as in the il lus tra tion, the pos i tive charge moves along the wire to the other sphere. On the other end, the neg a tive charge flows out on the wire to ward the pos i tive side. In this case, pos i tive and neg a tive charges com bine to neu -tral ize each other un til there are no charge dif fer ences be tween any points in thesys tem.

Fig ure B-4 Con nected Op po site Charges.

The flow of an elec tri cal charge is called a cur rent. Cur rent is mea sured in am -peres (A), also called amps, af ter An dre Am pere, a French math e ma ti cian and phys i -cist. An am pere is de fined as the flow of one Cou lomb of charge in one sec ond.

Elec tri cal cur rent is di rec tional; there fore, a pos i tive cur rent is the flow cur rentfrom a pos i tive point A to a neg a tive point B. How ever, most cur rent re sults fromthe flow of neg a tive-to-positive charges.

B.4.3 Power

Cur rent flow ing through a con duc tor pro duces heat. The heat is the re sult of the en -ergy that co mes from the charge trav el ing across the voltage dif fer ence. The work in -volved in pro duc ing this heat is elec tri cal power. Power is mea sured in units of watts(W), named af ter the Eng lish man James Watt, who in vented the steam en gine.

B.4.4 Ohm’s Law

The re la tionship be tween voltage, current, and power is de scribed by Ohm’s Law,named af ter the Ger man phys i cist Georg Si mon Ohm. Us ing equip ment of his own cre -ation, Ohm de ter mined that the current that flows through a wire is pro por tional to its cross-sec tional area and in versely pro por tional to its length. This al lowed de fin ing the re la tionship be tween voltage, current, and power, as ex pressed by the equa tion:

Essential Elec tron ics 669

+ ++ -

-

- -

--

-

+ +

+ -

++

current flow

P V I= ×

Page 691: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

where P rep re sents the power in watts, V is the voltage in volts, and I is the current inam peres. Ohm's Law can also be for mu lated in terms of voltage, current, and re sis -tance as shown later in this chap ter.

B.5 Elec tri cal Cir cuitsAn elec tri cal net work is an in ter con nec tion of elec tri cal el e ments. An elec tri cal cir -cuit is a net work in a closed-loop, giv ing a re turn path for the cur rent. A net work is acon nec tion of two or more sim ple el e ments, and may not nec es sar ily be a cir cuit.

Al though there are sev eral types of elec tri cal cir cuits, they all have some of thefol low ing el e ments:

1. A power source, which can be a bat tery, al ter na tor, etc., pro duces an elec tri calpotential.

2. Con duc tors, in the form of wires or cir cuit boards, pro vide a path for the current.

3. Loads, in the form of de vices such as lamps, mo tors, etc., use the elec tri cal en ergyto pro duce some form of work.

4. Con trol de vices, such as potentiometers and switches, reg u late the amount ofcurrent flow or turn it on and off.

5. Pro tec tion de vices, such as fuses or cir cuit breakers, pre vent dam age to the sys tem in case of over load.

6. A com mon ground.

Fig ure B-5 shows a sim ple cir cuit that con tains all these el e ments.

Fig ure B-5 Sim ple Cir cuit.

B.5.1 Types of Cir cuitsThere are three com mon types of cir cuits: se ries, par al lel, and se ries-parallel. The cir -cuit type is de ter mined by how the com po nents are con nected. In other words, by how the cir cuit el e ments, power source, load, and con trol and pro tec tion de vices are in ter -con nected. The sim plest cir cuit is one in which the com po nents of fer a sin gle cur rentpath. In this case, al though the loads may be dif fer ent, the amount of cur rent flow ingthrough each one is the same. Fig ure B-6 shows a se ries cir cuit with two light bulbs.

670 Ap pen dix B

+

-

Page 692: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure B-6 Se ries Cir cuit.

In the se ries cir cuit in Fig ure B-6, if one of the light bulbs burn out, the cir cuitflow is in ter rupted and the other one will not light. Some Christ mas lights are wiredin this man ner, and if a sin gle bulb fails the whole string will not light.

In a par al lel cir cuit there is more than one path for cur rent flow. Fig ure B-7shows a cir cuit wired in par al lel.

Fig ure B-7 Par al lel Cir cuit.

In the cir cuit of Fig ure B-7, if one of the light bulbs burns out, the other one willstill light. Also, if the load is the same in each cir cuit branch, so is the cur rent flowin that branch. By the same to ken, if the load in each branch is dif fer ent, so is thecur rent flow in each branch.

The se ries-par al lel cir cuit has some com po nents wired in se ries and oth ers in par -al lel. There fore, the cir cuit shares the char ac ter is tics of both se ries and par al lel cir -cuits. Fig ure B-8 shows the same par al lel cir cuit to which a se ries rheo stat(dim mer) has been added in se ries.

Essential Elec tron ics 671

+

-

+

-

Page 693: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure B-8 Se ries-Parallel Cir cuit.

In the cir cuit of Fig ure B-8 the two light bulbs are wired in par al lel, so if one failsthe other one will not. How ever, the rheo stat (dim mer) is wired in se ries with thecir cuit, so its ac tion af fects both light bulbs.

B.6 Cir cuit El e mentsSo far we have rep re sented cir cuits us ing a pic to rial style. Cir cuit di a grams are moreof ten used be cause they achieve the same pur pose with much less ar tis tic ef fort andare eas ier to read. Fig ure B-9 is a di a gram matic rep re sen ta tion of the cir cuit in Fig ureB-8.

Fig ure B-9 Di a gram of a Se ries-Parallel Cir cuit.

Cer tain com po nents are com monly used in elec tri cal cir cuits. These in cludepower sources, re sis tors, ca pac i tors, inductors, and sev eral forms of semi con duc tor de vices.

672 Ap pen dix B

+

-

VARIABLE RESISTOR(DIMMER)

+

-

Page 694: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

B.6.1 Re sis torsIf the current flow from, say a bat tery, is not con trolled, a short-cir cuit takes placeand the wires can melt or the bat tery may even ex plode. Re sis tors pro vide a way ofcon trol ling the flow of current from a source. A re sis tor is to current flow in an elec tri -cal cir cuit as a valve is to wa ter flow: both el e ments “re sist” flow. Re sis tors are typ i -cally made of ma te ri als that are poor con duc tors. The most com mon ones are madefrom pow dered car bon and some sort of binder. Such car bon com po si tion re sis torsusu ally have a dark-col ored cy lin dri cal body with a wire lead on each end. Color bands on the body of the re sis tor in di cate its value, mea sured in Ohms and rep re sented bythe Greek let ter Ω. The color code for re sis tor bands can be found in Ap pen dix A.

The po ten ti om e ter and the rheo stat are vari able re sis tors. When the knob of a po -ten ti om e ter or rheo stat is turned, a slider moves along the re sis tance el e ment andre duces or in creases the re sis tance. A po ten ti om e ter is used as a dim mer in the cir -cuits of Fig ure B-8 and Fig ure B-9. The photoresistor or photocell is com posed of alight sen si tive ma te rial whose re sis tance de creases when ex posed to light.Photoresistors can be used as light sen sors.

B.6.2 Re visiting Ohm’s Law We have seen how Ohm's Law de scribes the re la tion ship be tween volt age, cur rent,and power. The law is re for mu lated in terms of re sis tance so as to ex press the re la tion -ship be tween volt age, cur rent, and re sis tance, as fol lows:

In this case V rep re sents volt age, I is the cur rent, and R is the re sis tance in thecir cuit. Ohm's Law equa tion can be ma nip u lated in or der to find cur rent or re sis -tance in terms of the other vari ables, as fol lows

Note that the voltage value in Ohm’s Law re fers to the voltage across the re sis tor, in other words, the voltage be tween the two ter mi nal wires. In this sense the voltage is ac tu ally pro duced by the re sis tor, as the re sis tor is re strict ing the flow of chargemuch as a valve or noz zle re stricts the flow of wa ter. It is the re stric tion cre ated bythe re sis tor that forms an ex cess of charge with re spect to the other side of the cir -cuit. The charge dif fer ence re sults in a voltage be tween the two points. Ohm’s Lawis used to cal cu late the voltage if we know the re sis tor value and the current flow.

Essential Elec tron ics 673

V I R= ×

IV

R

RV

I

=

=

Page 695: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure B-10 Ohm's Law Pyr a mid.

A pop u lar mne monic for Ohm’s Law con sists of draw ing a pyr a mid with the volt -age sym bol at the top and cur rent and re sis tance in the lower level. Then, it is easyto solve for each of the val ues by ob serv ing the po si tion of the other two sym bols inthe pyr a mid, as shown in Fig ure B-10.

B.6.3 Re sis tors in Se ries and Par al lelWhen re sis tors are in se ries, the to tal re sis tance equals the sum of the in di vid ualresistances. The di a gram in Fig ure B-11 shows two re sis tors (R1 and R2) wired in se -ries in a sim ple cir cuit.

Fig ure B-11 Re sis tors in Se ries.

In Fig ure B-11 the to tal re sis tance (RT) is cal cu lated by add ing the re sis tance val -ues of R1 and R2; thus, RT = R1 + R2.

In terms of wa ter flow, a se ries of par tially closed valves in a pipe add up to slowthe flow of wa ter.

Re sis tors can also be con nected in par al lel, as shown in Fig ure B-12.

674 Ap pen dix B

V

V

V

V=IR

I=V/R

R=V/I

I

I

I

R

R

R

+

-

R1 R2

Page 696: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure B-12 Re sis tors in Par al lel.

When re sis tors are placed in par al lel, the com bi na tion has less re sis tance thanany one of the re sis tors. If the re sis tors have dif fer ent val ues, then more cur rentflows through the path of least re sis tance. The to tal re sis tance in a par al lel cir cuit is ob tained by di vid ing the prod uct of the in di vid ual re sis tors by their sum, as in thefor mula:

If more than two re sis tors are con nected in par al lel, then the for mula can be ex -pressed as fol lows:

Also note that the di a gram rep re sen ta tion of re sis tors in par al lel can have dif fer -ent ap pear ances. For ex am ple, the cir cuit in Fig ure B-13 is elec tri cally iden ti cal tothe one in Fig ure B-12.

Fig ure B-13 Al ter na tive Cir cuit of Par al lel Re sis tors.

Essential Elec tron ics 675

+

-

R1

R2

RTR R

R R= ×

+1 2

1 2

RT

R R R

=+ +

111

12

13

...

+

-

R1 R2

Page 697: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure B-14 Re sis tors.

Fig ure B-14 shows sev eral com mer cial re sis tors. The in te grated cir cuit at the cen -ter of the im age com bines eight re sis tors of the same value. These de vices are con -ve nient when the cir cuit de sign calls for sev eral iden ti cal re sis tors. The color-codedcy lin dri cal re sis tors in the im age are made of car bon

Ap pen dix A con tains the color codes used in iden ti fy ing re sis tors whose sur facearea does not al low print ing its value.

B.6.4 Ca pac i torsAn el e ment of ten used in the con trol of the flow of an elec tri cal charge is a ca pac i tor.The name orig i nated in the no tion of a “ca pac ity” to store charge. In that sense a ca -pac i tor func tions as a small bat tery. Ca pac i tors are made of two con duct ing sur facessep a rated by an in su la tor. A wire lead is usu ally con nected to each sur face. Two largemetal plates sep a rated by air would per form as a ca pac i tor. More fre quently, ca pac i -tors are made of thin metal foils sep a rated by a plas tic film or an other form of solid in -su la tor. Fig ure B-15 shows a cir cuit that con tains both a ca pac i tor and a re sis tor.

In Fig ure B-15, charge flows from the bat tery ter mi nals, along the con duc torwire, and onto the ca pac i tor plates. Pos i tive charges col lect on one plate and neg a -tive charges on the other plate. The ini tial cur rent is lim ited only by the re sis tanceof the wires and by the re sis tor in the cir cuit. As charge builds up on the plates,charge re pul sion re sists the flow, and the cur rent is re duced. At some point the re -pul sive force from the charge on the plates is strong enough to bal ance the forcefrom the charge on the bat tery, and the cur rent stops.

Fig ure B-15 Ca pac i tor Cir cuit.

676 Ap pen dix B

+

-

Page 698: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

The ex is tence of charges on the ca pac i tor plates means there must be a volt agebe tween the plates. When the cur rent stops this volt age is equal to the volt age in the bat tery. Be cause the points in the cir cuit are con nected by con duc tors, they havethe same volt age, even if there is a re sis tor in the cir cuit. If the cur rent is zero, thereis no volt age across the re sis tor, ac cord ing to Ohm’s law.

The amount of charge on the plates of the ca pac i tor is a mea sure of the value ofthe ca pac i tor. This “ca pac i tance” is mea sured in farads (f), named in honor of theEng lish sci en tist Mi chael Faraday.

The re la tion ship is ex pressed by the equa tion

where C is the ca pac i tance in far ads, Q is the charge in Cou lombs, and V is the volt age.Ca pac i tors of 1 farad or more are rare. Gen erally ca pac i tors are rated in microfarads(µf), one-mil lionth of a farad, or picofarads (pf), one-tril lionth of a farad.

Con sider the cir cuit of Fig ure B-15 af ter the cur rent has sta bi lized. If we now re -move the ca pac i tor from the cir cuit, it still holds a charge on its plates. That is, there is a volt age be tween the ca pac i tor ter mi nals. In one sense, the charged ca pac i tor ap -pears some what like a bat tery. If we were to short-circuit the ca pac i tor's ter mi nals,a cur rent would flow as the pos i tive and neg a tive charges neu tral ize each other. Butun like a bat tery, the ca pac i tor does not re place its charge. So the volt age drops, thecur rent drops, and fi nally there is no net charge and no volt age dif fer ence any where in the cir cuit.

B.6.5 Ca pac i tors in Se ries and in Par al lelLike re sis tors, ca pac i tors can be joined to gether in se ries and in par al lel. Con nectingtwo ca pac i tors in par al lel re sults in a big ger ca pac i tance value, be cause of the largerplate area. Thus, the for mula for to tal ca pac i tance (CT) in a par al lel cir cuit con tain ingca pac i tors C1 and C2 is

Note that the for mula for cal cu lat ing ca pac i tance in par al lel is sim i lar to the onefor cal cu lat ing se ries re sis tance. By the same to ken, where sev eral ca pac i tors arecon nected in se ries, the for mula for cal cu lat ing the to tal ca pac i tance is

Essential Elec tron ics 677

CQ

V=

CT C C= +1 2

CT

C C C

=+ +

111

12

13

...

Page 699: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure B-16 As sorted Com mer cial Ca pac i tors.

Note that the to tal ca pac i tance of a con nec tion in se ries is lower than for any ca -pac i tor in the se ries, con sid er ing that for a given volt age across the en tire group,there is less charge on each plate.

There are sev eral types of com mer cial ca pac i tors, in clud ing my lar, ce ramic, disk, and elec tro lytic. Fig ure B-16 shows sev eral com mer cial ca pac i tors.

B.6.6 In duc tors

In duc tors are the third type of ba sic cir cuit com po nents. An in duc tor is a coil of wirewith many wind ings. The wire wind ings are of ten made around a core of a mag neticma te rial, such as iron. The prop er ties of inductors are de rived from mag netic ratherthan elec tric forces.

When cur rent flows through a coil, it pro duces a mag netic field in the space out sidethe wire. This makes the coil be have just like a nat u ral, per ma nent mag net. Mov ing awire through a mag netic field gen er ates a cur rent in the wire, and this cur rent will flow through the as so ci ated cir cuit. Be cause it takes me chan i cal en ergy to move the wirethrough the field, it is the me chan i cal en ergy that is trans formed into elec tri cal en -ergy. A gen er a tor is a de vice that con verts me chan i cal to elec tri cal en ergy by means ofin duc tion. An elec tric mo tor is the op po site of a gen er a tor. In the mo tor, elec tri cal en -ergy is converted to mechanical energy by means of induction.

The cur rent in an in duc tor is sim i lar to the volt age across a ca pac i tor. In both cases ittakes time to change the volt age from an ini tially high cur rent flow. Such in duced volt -ages can be very high and can dam age other cir cuit com po nents, so it is com mon tocon nect a re sis tor or a ca pac i tor across the in duc tor to pro vide a cur rent path to ab -sorb the in duced volt age. In com bi na tion, in duc tors be have just like re sis tors: in duc -tance adds in se ries. By the same to ken, par al lel con nec tion re duces in duc tion.In duc tion is mea sured in henrys (h), but more commonly in mh, and µh.

678 Ap pen dix B

Page 700: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure B-17 Trans former Sche mat ics.

B.6.7 Trans formers

The trans former is an in duc tion de vice that changes volt age or cur rent lev els. Thetyp i cal trans former has two or more wind ings wrapped around a core made of lam i -nated iron sheets. One of the wind ings, called the pri mary, re ceives a fluc tu at ing cur -rent. The other wind ing, called the sec ond ary, pro duces a cur rent in duced by thepri mary. Fig ure B-17 shows the sche mat ics of a trans former.

The de vice in Fig ure B-17 is a step-up trans former. This is de ter mined by the num -ber of wind ings in the pri mary and sec ond ary coils. The ra tio of the num ber of turnsin each wind ing de ter mines the volt age in crease. A trans former with an equal num -ber of turns in the pri mary and sec ond ary trans fers the cur rent un al tered. This typeof de vice is some times called an iso la tion trans former. A trans former with lessturns in the sec ond ary than in the pri mary coil is a step-down trans former and its ef -fect is to re duce the pri mary volt age at the sec ond ary coil.

Trans formers re quire an al ter nat ing or fluc tu at ing cur rent be cause it is the fluc tu -a tions in the cur rent flow in the pri mary that in duce a cur rent in the sec ond ary. Theig ni tion coil in an au to mo bile is a trans former that con verts the low-level bat teryvolt age to the high-voltage level nec es sary to pro duce a spark.

B.7 Semi con duc tors The word semi con duc tor stems from the prop erty of some ma te ri als that act ei ther asa con duc tor or as an in su la tor, de pend ing on cer tain con di tions. Sev eral el e ments areclas si fied as semi con duc tors, in clud ing silicon, zinc, and ger ma nium. Sil i con is themost widely used semi con duc tor ma te rial be cause it is eas ily ob tained.

In the ul tra-pure form of sil i con, the ad di tion of min ute amounts of cer tain im pu -ri ties (called dop ants) al ters the atomic struc ture of the sil i con. This de ter mineswhether the sil i con can then be made to act as a con duc tor or as a non con duc tor,de pend ing upon the po lar ity of an elec tri cal charge ap plied to it.

In the early days of ra dio, re ceiv ers re quired a de vice called a rec ti fier to de tectsig nals. Ferdinand Braun used the rec ti fy ing prop er ties of the ga lena crys tal, a semi -con duc tor ma te rial com posed of lead sul fide, to cre ate a “cat's whis ker” di ode thatserved this pur pose. This was the first semi con duc tor de vice.

Essential Elec tron ics 679

PRIMARYWIDING

SECONDARYWINDING

Page 701: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

B.7.1 In te grated Cir cuitsUn til 1959, elec tronic com po nents per formed a sin gle func tion; there fore, many ofthem had to be wired to gether to cre ate a func tional cir cuit. Tran sis tors were in di vid u -ally pack aged in small cans. Pack aging and hand wir ing the com po nents into cir cuitswas ex tremely in ef fi cient.

In 1959, at Fairchild Semi con duc tor, Jean Hoerni and Rob ert Noyce de vel oped apro cess which made it pos si ble to dif fuse var i ous lay ers onto the sur face of a sil i con wa fer, while leav ing a layer of pro tec tive ox ide on the junc tions. By al low ing themetal in ter con nec tions to be evap o rated onto the flat tran sis tor sur face the pro cessre placed hand wir ing. By 1961, nearly 90% of all the com po nents man u fac tured were in te grated cir cuits.

B.7.2 Semi con duc tor Elec tron icsTo un der stand the work ings of semi con duc tor de vices, we need to re con sider the na -ture of the elec tri cal charge. Elec trons are one of the com po nents of at oms, and at oms are the build ing blocks of all mat ter. Atoms bond with each other to form mol e cules.Mol e cules of just one type of atom are called el e ments. In this sense, gold, ox y gen, and plu to nium are el e ments be cause they all con sist of only one type of atom. When a mol -e cule con tains more than one atom, it is known as a com pound. Wa ter, which has bothhy dro gen and ox y gen at oms, is a com pound. Fig ure B-18 rep re sents an or bital modelof an atom with five pro tons and three elec trons.

Fig ure B-18 Or bital Model of the Bo ron Atom with Its Va lence Elec trons.

In Fig ure B-18, pro tons carry pos i tive charge and elec trons carry neg a tive charge. Neu trons, not rep re sented in the il lus tra tion, are not elec tri cally charged. Atomsthat have the same num ber of pro tons and elec trons have no net elec tri cal charge.

Elec trons that are far from the nu cleus are rel a tively free to move around be -cause the at trac tion from the pos i tive charge in the nu cleus is weak at large dis -tances. In fact, it takes lit tle force to com pletely re move an outer elec tron from anatom, leav ing an ion with a net pos i tive charge. A free elec tron can move at speedsap proach ing the speed of light (ap prox i mately 186,282 miles per sec ond).

Elec tric cur rent takes place in metal con duc tors due to the flow of free elec trons. Be cause elec trons have neg a tive charge, the flow is in a di rec tion op po site to the

680 Ap pen dix B

++

++

+

--

-

Page 702: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

pos i tive cur rent. Free elec trons trav el ing through a con duc tor drift un til they hitother elec trons at tached to at oms. These elec trons are then dis lodged from their or -bits and re placed by the for merly free elec trons. The newly freed elec trons thenstart the pro cess anew.

B.7.3 P-Type and N-Type Sil i con Semi con duc tor de vices are made pri mar ily of sil i con. Pure sil i con forms rigid crys talsbe cause of its four out er most elec trons. Be cause it con tains no free elec trons, it is nota con duc tor. But sil i con can be made con duc tive by com bin ing it with other el e ments(dop ing) such as bo ron and phos pho rus. The bo ron atom has three outer va lence elec -trons (Fig ure B-18) and the phos pho rus atom has five. When three sil i con at oms andone phos pho rus atom bind to gether, cre at ing a struc ture of four at oms, there is an ex -tra elec tron and a net neg a tive charge.

The com bi na tion of sil i con and phos pho rous, with the ex tra phos pho rus elec -tron, is called an N-type sil i con. In this case, the N stands for the ex tra neg a tive elec -tron. The ex tra elec tron do nated by the phos pho rus atom can eas ily move throughthe crys tal; there fore N-type sil i con can carry an elec tri cal cur rent.

When a bo ron atom com bines with a clus ter of sil i con at oms, there is a de fi ciency of one elec tron in the re sult ing crys tal. Sil i con with a de fi cient elec tron is calledP-type sil i con (P stands for pos i tive). The va cant elec tron po si tion is some timescalled a "hole." An elec tron from an other nearby atom can “fall” into this hole,thereby mov ing the hole to a new lo ca tion. In this case, the hole can carry a cur rentin the P-type sil i con.

B.7.4 Di odeBoth P-type and N-type sil i con con duct elec tric ity. In ei ther case, the con duc tiv ity isde ter mined by the pro por tion of holes or the sur plus of elec trons. By form ing someP-type sil i con in a chip of N-type sil i con, it is pos si ble to con trol elec tron flow so that ittakes place in a sin gle di rec tion. This is the prin ci ple of the di ode, and the p-n ac tion iscalled a pn-junction.

A di ode is said to have a for ward bias if it has a pos i tive volt age across it from the P- to N-type ma te rial. In this con di tion, the di ode acts rather like a good con duc torand cur rent can flow, as in Fig ure B-19.

Fig ure B-19 A For ward Biased Di ode.

Essential Elec tron ics 681

+

-

e e

e

e e

electron flow

hole flow

Page 703: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

If the po lar ity of the volt age ap plied to the sil i con is re versed, then the di ode isre verse-bi ased and ap pears nonconducting. This nonsymmetric be hav ior is due tothe prop er ties of the pn-junc tion. The fact that a di ode acts like a one-way valve forcur rent is a very use ful char ac ter is tic. One ap pli ca tion is to con vert al ter nat ingcur rent (AC) into di rect cur rent (DC). Di odes are so of ten used for this pur posethat they are some times called rec ti fi ers.

682 Ap pen dix B

Page 704: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Appendix C

Num eric Data

C.1 Numbers in ComputingIn or der to per form more ef fi cient dig i tal op er a tions on nu meric data, math e ma ti cians have de vised sys tems and struc tures that dif fer from those used tra di tion ally. Thischap ter pres ents the back ground ma te rial nec es sary for un der stand ing and us ing thenum ber sys tems and nu meric data stor age struc tures em ployed in dig i tal de vices.

C.1.1 CountingThe fun da men tal ap pli ca tion of a num ber sys tem is count ing. A Stone-Age hunter uses his or her fin gers to show other mem bers of the tribe how many mam moths were spot -ted at the bot tom of the ra vine. In this man ner the hunter is able to trans mit a uniquetype of in for ma tion that does not re late to the spe cies, size, or color of the an i mals, but to their num bers. Our minds have the abil ity to cap ture this no tion of “one ness” in de -pend ently of other prop er ties of ob jects.

The most prim i tive method of count ing con sists of us ing ob jects to rep re sent de -grees of one ness. The Stone-Age hunter used fin gers to rep re sent in di vid ual mam -moth. Al ter na tively, the hunter could have re sorted to peb bles, sticks, lines on theground, or scratches on the cave wall to show how many units there were of the ob -ject.

C.1.2 Tally Sys temThe tally sys tem prob a bly orig i nated from notches on a stick or scratches on a cavewall. In its sim plest form, each scratch, notch, or line, rep re sents an ob ject. Themethod is so sim ple and in tu itive that we still re sort to it oc ca sion ally. Tallying re -quires no knowl edge of quan tity and no elab o rate sym bols. Had there been twelvemam moth in the ra vine the cave wall would have ap peared as fol lows:

||||||||||||

A log i cal evo lu tion of the tally sys tem con sists of group ing marks. Be cause wehave five fin gers on each hand, the twelve mam moth could be grouped as fol lows:

||||| ||||| ||

683

Page 705: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Per haps a prim i tive math e mat i cal ge nius added one fi nal so phis ti ca tion to thetally sys tem. By draw ing one tally line di ag o nally the vi su al iza tion is fur ther im -proved, as in this fa mil iar style:

C.1.3 Ro man Nu merals

Ro man nu mer als show how a sim ple graph i cal tally sys tem evolved into a sym bolicnu meric rep re sen ta tion. The first five dig its were en coded with the sym bols:

I, II, III, IIII, and V

The Ro man sym bol V is con ceiv ably a sim pli fi ca tion of the tally en cod ing us ing a di ag -o nal line to com plete the group ing, as shown in Ta ble C.1.

Ta ble C.1

Sym bols in the Ro man Nu mer a tion Sys tem

ROMAN DECIMAL

I 1 V 5 X 10 L 50 C 100 D 500 M 1000

The Ro man nu meral sys tem is based on an add-subtract rule whereby the el e ments ofa num ber, read left-to-right, are ei ther added to or sub tracted from the pre vi ous sumac cord ing to its value. Thereby, the dec i mal num ber 1994 is rep re sented in Ro man nu -mer als as fol lows:

MCMXCIV = M + (C - M) + (X - C) + (I - V)

= 1000 + (1000 - 100) + (100 - 10) + (5 - 1)

= 1000 + 900 + 90 + 4

= 1994

The un cer tainty in the po si tional value of each digit, the ab sence of a sym bol forzero, and the fact that some num bers re quire ei ther one or two sym bols (I, IV, V, IX,and X) com pli cate the rules of arith me tic us ing Ro man nu mer als.

C.2 Or i gins of the Dec i mal Sys temThe one el e ment of our civ i li za tion that has tran scended all cul tural and so cial dif fer -ences is our dec i mal sys tem of num bers. While man kind is yet to agree on the most de -sir able po lit i cal or der, on gen er ally ac cept able rules of moral be hav ior, or on auni ver sal lan guage, the Hindu-Arabic nu mer als have been adopted by prac ti cally allthe na tions and cul tures of the world.

684 Ap pen dix C

Page 706: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

By the ninth cen tury A.D. the Arabs were us ing a ten-sym bol po si tional system ofnum bers that in cluded the spe cial sym bol for 0. The Latin ti tle of the first book onthe sub ject of “In dian num bers” is Liber Algorismi de Numero Indorum. The au -thor is the Arab math e ma ti cian al-Khowarizmi.

De spite of the ev i dent ad van tages of this num ber sys tem, its adop tion in Eu ropetook place only af ter con sid er able de bate and con tro versy. Many schol ars of thetime still con sid ered Ro man nu mer als to be eas ier to learn and more con ve nient forop er a tions on the aba cus. The sup port ers of the Ro man nu meral sys tem, calledabacists, en gaged in in tel lec tual com bat with the algorists, who were in fa vor of theHindu-Arabic nu mer als as de scribed by al-Khowarizmi. For sev eral cen tu riesabacists and algorists de bated about the ad van tages of their sys tems, with the Cath -o lic church of ten sid ing with the abacists. This con tro versy ex plains why theHindu-Arabic nu mer als were not ac cepted into gen eral use in Eu rope un til the be -gin ning of the six teenth cen tury.

It is some times said that the rea son for there be ing ten sym bols in theHindu-Arabic nu mer als is re lated to the fact that we have ten fin gers. How ever, ifwe make a one-to-one cor re la tion be tween the Hindu-Arabic nu mer als and our fin -gers, we find that the last fin ger must be rep re sented by a com bi na tion of two sym -bols, 10. Also, one Hindu-Arabic sym bol, 0, can not be matched to an in di vid ualfin ger. In fact, the dec i mal sys tem of num bers, as used in a po si tional no ta tion thatin cludes a zero digit, is a re fined and ab stract scheme that should be con sid ered one of the great est achieve ments of hu man in tel li gence. We will never know for cer tainif the Hindu-Arabic nu mer als are re lated to the fact that we have ten fin gers, but itspro found ness and use ful ness clearly tran scend this bi o log i cal fact.

The most sig nif i cant fea ture of the Hindu-Arabic nu mer als is the pres ence of aspe cial sym bol, 0, which by it self rep re sents no quan tity. Nev er the less, the spe cialsym bol 0 is com bined with the other ones. In this man ner the nine other sym bols are re used to rep re sent larger quan ti ties. An other char ac ter is tic of dec i mal num bers isthat the value of each digit de pends on its po si tion in a digit string. This po si tionalchar ac ter is tic, in con junc tion with the use of the spe cial sym bol 0 as a place holder,al low the fol low ing rep re sen ta tions:

1 = one

10 = ten

100 = hun dred

1000 = thou sand

The re sult is a count ing scheme where the value of each sym bol is de ter mined byits col umn po si tion. This po si tional fea ture re quires the use of the spe cial sym bol, 0, which does not cor re spond to any unit-amount, but is used as a place holder inmulticolumn rep re sen ta tions. We must mar vel at the in tel li gence, ca pa bil ity for ab -strac tion, and even the sense of hu mor of the mind that con ceived a count ing sys -tem that has a sym bol that rep re sents noth ing. We must also won der about theevo lu tion of math e mat ics, sci ence, and tech nol ogy had this sys tem not been in -vented. One in trigu ing ques tion is whether a po si tional count ing sys tem that in -cludes the zero sym bol is a nat u ral and pre dict able step in the evo lu tion of our

Num eric Data 685

Page 707: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

math e mat i cal thought, or whether its in ven tion was a stroke of ge nius that couldhave been missed for the next two thou sand years.

C.2.1 Num ber Sys tems for Dig i tal-Electronics

The com put ers built in the United States dur ing the early 1940s op er ated on dec i malnum bers. How ever, in 1946, von Neumann, Burks, and Goldstine pub lished atrend-setting pa per ti tled “Pre lim i nary Dis cus sion of the Log i cal De sign of an Elec -tronic Com puting In stru ment,” in which they state:

“In a dis cus sion of the arith me tic or gans of a com put ing ma chine one is nat u -rally led to a con sid er ation of the num ber sys tem to be adopted. In spite of thelong-standing tra di tion of build ing dig i tal ma chines in the dec i mal sys tem,we must feel strongly in fa vor of the bi nary sys tem for our de vice.”

In their pa per, von Neumann, Burks, and Goldstine also con sider the pos si bil ityof a com put ing de vice that uses bi nary-coded dec i mal num bers. How ever, the ideais dis carded in fa vor of a pure bi nary en cod ing. The ar gu ment is that bi nary num -bers are more com pact than bi nary-coded dec i mals. Later in this book you will seethat bi nary-coded dec i mal num bers (called BCD) are used to day in some types ofcom puter cal cu la tions.

In 1941, Konrad Zuse, a Ger man who had done pi o neer ing work in com put ing ma -chines, re leased the first pro gram ma ble com puter de signed to solve com plex en gi -neer ing equa tions. The ma chine, called the Z3, was con trolled by per fo rated stripsof dis carded movie film and used the bi nary num ber sys tem.

The use of the bi nary num ber sys tem in dig i tal cal cu la tors and com put ers wasmade pos si ble by pre vi ous re search on num ber sys tems and on nu mer i cal rep re sen -ta tions, start ing with an ar ti cle by G.W. Leibnitz pub lished in Paris in 1703. Re -searchers con cluded that it is pos si ble to count and per form arith me tic op er a tionsus ing any set of sym bols as long as the set con tains at least two sym bols, one ofwhich must be zero.

In dig i tal elec tron ics the bi nary sym bol 1 is equated with the elec tronic state ON,and the bi nary sym bol 0 with the state OFF. The two sym bols of the bi nary sys temcan also rep re sent con duct ing and nonconducting states, pos i tive or neg a tive, orany other bi-valued con di tion. It was the bi nary sys tem that pre sented theHindu-Arabic dec i mal num ber sys tem with the first chal lenge in 800 years. In dig i -tal-elec tron ics, two steady states are eas ier to im ple ment and more re li able than aten-digit en cod ing.

C.2.2 Po si tional Char ac ter is tics

All mod ern num ber sys tems, in clud ing dec i mal, hex a dec i mal, and bi nary, are po si -tional and in clude the digit zero. It is the po si tional fea ture that is used to de ter minethe to tal value of a multi-digit rep re sen ta tion. For ex am ple, the dig its in the dec i malnum ber 4359 have the fol low ing po si tional weights:

686 Ap pen dix C

Page 708: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

4 3 5 9

| | | |_________________ units

| | |___________________ ten units

| |_____________________ hun dred units

|_______________________ thou sand units

The to tal value is ob tained by add ing the col umn weights of each unit:

4000 --- 4 thou sand units

300 --- 3 hun dred units

+ 50 --- 5 ten units

9 --- 9 unit

----

4359

C.2.3 Ra dix or Base of a Num ber Sys temIn any po si tional num ber sys tem, the weight of each col umn is de ter mined by the to talnum ber of sym bols in the set, in clud ing zero. This is called the base or ra dix of the sys -tem. The base of the dec i mal sys tem is 10 and the base of the bi nary sys tem is 2. The po -si tional value or weight (P) of a digit in a multi-digit num ber is de ter mined by thefor mula

where d is the digit, B is the base or ra dix, and c is the zero-based col umn num ber,start ing from right to left. Note that the in crease in col umn weight from right to left ispurely con ven tional. You could con struct a num ber sys tem in which the col umnweights in crease in the op po site di rec tion. In fact, in the orig i nal Hindu no ta tion, themost sig nif i cant digit was placed at the right.

In ra dix-positional terms, a dec i mal num ber can be ex pressed as a sum of dig itsby the for mula

where i is the sys tem's range and n is its limit.

C.3 Types of Num bers

By the adop tion of spe cial rep re sen ta tions for dif fer ent types of num bers, the use ful -ness of a po si tional num ber sys tem can be ex tended be yond the sim ple count ing func -tion.

Num eric Data 687

P d Bc= ×

dii

i m

n

×=−∑ 10

Page 709: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

C.3.1 Whole Num bers

The dig its of a num ber sys tem, called the pos i tive in te gers or nat u ral num bers, are anor dered set of sym bols. The no tion of an or dered set means that the nu mer i cal sym -bols are as signed a pre de ter mined se quence. A po si tional sys tem of num bers also re -quires the spe cial digit zero that, by it self, rep re sents the ab sence of one ness, ornoth ing, and thus is not in cluded in the set of nat u ral num bers. How ever, 0 as sumes acar di nal func tion when it is com bined with other dig its, for in stance, 10 or 30. Thewhole num bers are the set of nat u ral num bers, in clud ing the num ber zero.

C.3.2 Signed Num bers

A num ber sys tem can also en code di rec tion. We gen er ally use the + and – signs to rep -re sent op po site nu mer i cal di rec tions. The typ i cal il lus tra tion for a set of signed num -bers is as fol lows:

-9 -8 -7 -6 -5 -4 -3 -2 -1 0 +1 +2 +3 +4 +5 +6 +7 +8 +9

neg a tive num bers <- zero -> pos i tive num bers

The num ber zero, which sep a rates the pos i tive and the neg a tive num bers, has nosign of its own; al though in some bi nary encodings we can end up with a neg a tiveand a pos i tive zero.

C.3.3 Ra tio nal, Ir ra tio nal, and Imag i nary Num bers

A num ber sys tem also rep re sents parts of a whole. For ex am ple, when a car pen tercuts one board into two boards of equal length, we can rep re sent the re sult with thefrac tion 1/2; the frac tion 1/2 rep re sents one of the two parts that make up the ob ject.Ra tio nal num bers are those ex pressed as a ra tio of two in te gers, for ex am ple, 1/2, 2/3,5/248. Note that this use of the word “ra tio nal” is re lated to the math e mat i cal con ceptof a ra tio, and not to rea son.

The de nom i na tor of a ra tio nal num ber ex presses the num ber of po ten tial parts.In this sense 2/5 in di cates two of five pos si ble parts. There is no rea son why thenum ber 1 can not be used to in di cate the num ber of po ten tial parts, for ex am ple 2/1,128/1. In this case the ra tio x/1 in di cates x el e ments of an un di vided part. There fore, it fol lows that x/1 = x. The im pli ca tion is that the set of ra tio nal num bers in cludesthe in te gers, be cause an in te ger can be ex pressed as a ra tio us ing a unit de nom i na -tor.

But not all non-in te ger num bers can be writ ten as an ex act ra tio of two in te gers.The dis cov ery of the first ir ra tio nal num ber is usu ally as so ci ated with the in ves ti ga -tion of a right tri an gle by the Greek math e ma ti cian Py thag o ras (ap prox i mately 600B.C.). The Py thag o rean The o rem states that in any right tri an gle the square of thelon gest side (hy pot e nuse) is equal to the sum of the squares of the other two sides.

688 Ap pen dix C

C

a = 1

b = 1

Page 710: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

For this tri an gle, the Py thag o rean the o rem states that

There fore, the length of the hypotenuse in a right tri an gle with unit sides is a num ber,that when mul ti plied by it self, gives 2. This num ber (ap prox i mately 1.414213562) can -not be ex pressed as the ex act ra tio of two in te gers. Other ir ra tio nal num bers are thesquare roots of 3 and 5, as well as the math e mat i cal con stants π and e.

The set of num bers that in cludes the nat u ral num bers, the whole num bers, andthe ra tio nal and ir ra tio nal num bers is called the real num bers. Most com mon math e -mat i cal prob lems are solved us ing real num bers. How ever, dur ing the in ves ti ga tionof squares and roots, we no tice that there can be no real num ber whose square isneg a tive. Math e ma ti cians of the eigh teenth cen tury ex tended the num ber sys tem toin clude op er a tions with roots of neg a tive num bers. They did this by de fin ing animag i nary unit as fol lows:

The imag i nary unit makes pos si ble new set of num bers, called com plex num bers, that con sist of a real part and an imag i nary part. One of the uses of com plex num -bers is in find ing the so lu tion of a qua dratic equa tion. Com plex num bers are alsouse ful in vec tor anal y sis, graph ics, and in solv ing many en gi neer ing, sci en tific, andmath e mat i cal prob lems.

C.4 Ra dix Rep re sen ta tions

The ra dix of a num ber sys tem is the num ber of sym bols in the set, in clud ing zero. Thus, the ra dix of the dec i mal sys tem is 10, and the ra dix of the bi nary sys tem is 2. Dig i talelec tron ics is based on cir cuits that can be in one of two sta ble states. There fore, anum ber sys tem based on two sym bols is better suited for work in dig i tal elec tron ics,be cause each state can be rep re sented by a digit.

C.4.1 Dec i mal ver sus Bi nary Num bers

The bi nary sys tem of num bers uses two sym bols, 1 and 0. It is the sim plest pos si ble setof sym bols with which we can count and per form arith me tic. Most of the dif fi cul ties in learn ing and us ing the bi nary sys tem arise from this sim plic ity. Fig ure C.1 shows six -teen groups of four elec tronic cells each in all pos si ble com bi na tions of two states.

Num eric Data 689

a b c

c

c c

c

2 2 2

22

2

2

+ =

== ×

=

i = −1

Page 711: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure C-1 Elec tronic Cells and Bi nary Num bers

It is in ter est ing to note that bi nary num bers match the phys i cal state of each elec -tronic cell. If we think of each cell as a min ia ture light bulb, then the bi nary num ber1 can be used to rep re sent the state of a charged cell (light ON) and the bi nary num -ber 0 to rep re sent the state of an un charged cell (light OFF).

C.4.2 Hex a dec i mal and Oc talBi nary num bers are con ve nient in dig i tal elec tron ics; how ever, one of their draw -backs is the num ber of sym bols re quired to en code a large value. For ex am ple, thenum ber 9134 is rep re sented in four dec i mal dig its. How ever, the bi nary equiv a lent10001110101110 re quires four teen dig its. In ad di tion, large bi nary num bers are dif fi -cult to re mem ber.

One pos si ble way of com pen sat ing for these lim i ta tions of bi nary num bers is touse in di vid ual sym bols to rep re sent groups of bi nary dig its. For ex am ple, a group ofthree bi nary num bers al low eight pos si ble com bi na tions. In this case, we can usethe dec i mal dig its 0 to 7 to rep re sent each pos si ble com bi na tion of three bi nary dig -its. This group ing of three bi nary dig its gives rise to the fol low ing ta ble:

bi nary oc tal

0 0 0 0

0 0 1 1

0 1 0 2

0 1 1 3

1 0 0 4

1 0 1 5

1 1 0 6

1 1 1 7

690 Ap pen dix C

0 0 0 0

0 1 1 11 0 0 01 0 0 1

1 0 1 11 1 0 01 1 0 11 1 1 01 1 1 1

1 0 1 0

0 1 0 00 1 0 10 1 1 0

0 0 0 10 0 1 00 0 1 1

Page 712: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

The oc tal en cod ing serves as a short hand rep re sen ta tion for groups of three-digitbi nary num bers.

Hex a dec i mal num bers (base 16) are used for rep re sent ing val ues en coded in four bi nary dig its. Be cause there are only ten dec i mal dig its, the hex a dec i mal sys tembor rows the first six let ters of the al pha bet (A, B, C, D, E, and F). The re sult is a setof six teen sym bols, as fol lows:

0 1 2 3 4 5 6 7 8 9 A B C D E F

Most mod ern com put ers are desgined with mem ory cells, reg is ters, and datapaths in mul ti ples of four bi nary dig its. Ta ble C.2 lists some com mon units of mem -ory stor age.

Ta ble C.2

Units of Mem ory Stor age

UNIT BITS HEX DIGITS HEX RANGE

Nib ble 4 1 0 to FByte 8 2 0 to FFWord 16 4 0 to FFFFDoubleword 32 8 0 to FFFFFFFF

In most dig i tal-electronic de vices mem ory ad dress ing is or ga nized in mul ti ples offour bi nary dig its. Here again, the hex a dec i mal num ber sys tem pro vides a con ve -nient way to rep re sent ad dresses. Ta ble C.3 lists some com mon mem ory ad dress ingunits and their hex a dec i mal and dec i mal range.

Ta ble C.3

Units of Mem ory Ad dressing

UNIT DATA PATH ADDRESS RANGEIN BITS DECIMAL HEX

1 para graph 4 0 to 15 0-F1 page 8 0 to 255 0-FF1 ki lo byte 16 0 to 65,535 0-FFFF1 mega byte 20 0 to 1,048,575 0-FFFFF4 giga bytes 32 0 to 4,294,967,295 0-FFFFFFFF

C.5 Num ber Sys tem Con ver sionsWe use dec i mal num bers in our ev ery day life be cause they mean ing fully rep re sentcom mon units used in the real world. To state that a cer tain his tor i cal event took placein the year 7C6 hex a dec i mal would con vey lit tle in for ma tion to the av er age per son.How ever, in com puter sys tems based on two-state elec tronic cells, bi nary rep re sen ta -tions are more con ve nient. Also note that hex a dec i mal and oc tal num bers are handyshort hand for rep re sent ing groups of bi nary dig its.

Nu mer i cal con ver sions be tween po si tional sys tems of dif fer ent ra di ces are based on the num ber of sym bols in the re spec tive sets and on the po si tional value (weight) of each col umn. But meth ods used for man ual con ver sions are not al ways suit ablefor ma chine con ver sions, as we will see in the forth com ing sec tions.

Num eric Data 691

Page 713: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

C.5.1 Bi nary-to-ASCII-DecimalTo man u ally con vert a bi nary num ber to its dec i mal equiv a lent we take into ac countthe po si tional weight of each bi nary digit, as shown in Fig ure C-2.

Fig ure C-2 Bi nary to ASCII Dec i mal Con ver sion Ex am ple

The po si tional weight ta ble in Fig ure C-2 lists the dec i mal value of each bi narycol umn. These weights are pow ers of the sys tem's base (2 in the bi nary sys tem). Inthe digit value ta ble, also in Fig ure C-2, the dec i mal val ues of the bi nary col umnshold ing a 1 digit are added. The sum of the weights of all the 1-dig its in the op er andis the dec i mal equiv a lent of the bi nary num ber. In this case, 10010101 bi nary = 149dec i mal.

The method in Fig ure C-2, al though use ful in man ual con ver sions, is not an al go -rithm for com puter con ver sions. Fig ure C-3 is a flowchart of a low-level bi -nary-to-decimal con ver sion rou tine.

Fig ure C-3 Flowchart for a Bi nary to ASCII Dec i mal Con ver sion

692 Ap pen dix C

1 0 0 1 0 1 0 1

DIGIT VALUE TABLE(digit x weight)1 x 1 = 11 x 4 = 41 x 16 = 161 x 128 = 128total 149

POSITIONAL WEIGHT TABLE(decimal values)72 = 12862 = 6452 = 324

2 = 1632 = 822 = 412 = 20

2 = 1

START

END

YES

NO

SETUP ASCII DIGIT STORAGEINITIALIZE POINTER TO STORAGE

BINARY / 10

REMAINDER + 30H = ASCII DIGIT

ASCII DIGIT TO STORAGESTORAGE POINTER TO NEXT DIGIT

QUOTIENT = BINARY

QUOTIENT = 0?

Page 714: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

The al go rithm for the pro cess ing in Fig ure C-3 can be writ ten as fol lows:

1. Set up and ini tial ize a string stor age area (some times called a buffer) to hold theASCII dec i mal dig its of the re sult. Set up the buffer pointer to the rightmost digitpo si tion of the re sult.

2. Ob tain the re main der of the value di vided by 10.

3. Add 30H to re main der digit to con vert to ASCII rep re sen ta tion.

4. Store re main der digit in buffer and in dex the buffer pointer to the pre ced ing digit.

5. Quo tient of di vi sion by 10 be comes the new bi nary value.

6. End con ver sion rou tine if quo tient is equal to 0. Oth er wise, con tinue at Step 2.

Note that the nu mer i cal dig its are lo cated from 30H to 39H in the ASCII ta ble.This makes is easy to con vert a bi nary digit to ASCII sim ply by add ing 30H. Like -wise, an ASCII digit is con verted to bi nary by sub tract ing 30H.

C.5.2 Bi nary-to-Hexadecimal Con ver sionThe method de scribed in Sec tion 2.4.1 for a bi nary-to-ASCII dec i mal con ver sion canbe adapted to other ra di ces by rep re sent ing the po si tional weight of each bi nary digitin the num ber sys tem to which the con ver sion is to be made. In the case of a bi nary-to-ASCII hex a dec i mal con ver sion the po si tional weight of each bi nary digit is a hex a dec -i mal value. Fig ure C-4 shows the con ver sion of the bi nary value 10010101 into hex a -dec i mal us ing the cor re spond ing po si tional weights.

Fig ure C-4 Bi nary to ASCII Hex a dec i mal Con ver sion Ex am ple

The ma chine con ver sion bi nary-to-ASCII hex a dec i mal is sim i lar to the bi -nary-to-ASCII dec i mal al go rithm de scribed pre vi ously. In the case of the con ver sioninto ASCII hex a dec i mal dig its, the buffer need only hold four ASCII char ac ters, be -cause a 16-bit bi nary can not ex ceed the value FFFFH. In the case of bi nary-to-ASCII hex, the di vi sor for ob tain ing the dig its is 16 in stead of 10.

C.5.3 Dec i mal-to-Binary Con ver sion

Long hand con ver sion of dec i mal into bi nary can be per formed us ing the po si tionalweights to find the bi nary 1 dig its and then sub tract ing this po si tional weight from thedec i mal value. The pro cess is shown in Fig ure C-5.

Num eric Data 693

1 0 0 1 0 1 0 11 0 0 1 0 1 0 1

DIGIT VALUE TABLE(digit x weight)1 x 1H = 1H1 x 4H = 4H1 x 10H = 10H1 x 80H = 80Htotal 95H

POSITIONAL WEIGHT TABLE(hexadecimal values)72 = 80H62 = 40H52 = 20H42 = 10H32 = 8H22 = 4H12 = 2H02 = 1H

Page 715: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure C-5 Ex am ple of Dec i mal-to-Bi nary Con ver sion

In the ex am ple of Fig ure C-5, we start with the dec i mal value 149. Be cause thehigh est power of 2 smaller than 149 is 128, which cor re sponds to bit 7, we set bit 7 in the re sult and per form the sub trac tion:

149 - 128 = 21

At this point the high est po si tional weight smaller that 21 is 16, which cor re -sponds to bit 4. There fore we set bit 4 and per form the sub trac tion:

21 - 16 = 5

The re main ing steps in the con ver sion can be seen in the il lus tra tion. The con ver -sion is fin ished when the re sult of the sub trac tion is 0.

Sup pose there is a nu mer i cal value in the form of a string of ASCII dec i mal, oc tal,or hex a dec i mal dig its. In or der for a pro ces sor to per form sim ple arith me tic op er a -tions on such data, the data must first be con verted to bi nary. The bi nary value isthen loaded into ma chine reg is ters or mem ory cells. How ever, meth ods suited forman ual con ver sion do not al ways make a good com puter al go rithm. Fig ure C.6shows two dec i mal-to-binary con ver sion al go rithms that are suited for ma chinecod ing.

Using the first method of Fig ure C-6, the in di vid ual dec i mal dig its are mul ti pliedby their cor re spond ing po si tional val ues. The fi nal re sult is ob tained by add ing allthe par tial prod ucts. Al though this method is fre quently used, it has the dis ad van -tage that a dif fer ent mul ti plier is used dur ing each it er a tion (1, 10, 100, 1000). Thesec ond method in Fig ure C-6 starts with the high-order ASCII-decimal digit. The cal -cu la tions con sist of mul ti ply ing an ac cu mu lated value by 10. Ini tially, this ac cu mu -lated value is set to 0. Af ter mul ti pli ca tion by 10, the value of the digit is added tothe ac cu mu lated value. The fol low ing al go rithm is based on the sec ond method inFig ure C-6.

694 Ap pen dix C

1 0 0 1 0 1 0 1

149 - 128 = 21 1 0 0 0 0 0 0 0 21 - 16 = 5 0 0 0 1 0 0 0 0 5 - 4 = 1 0 0 0 0 0 1 0 0 1 - 1 = 0 0 0 0 0 0 0 0 1binary result 1 0 0 1 0 1 0 1

POSITIONAL WEIGHTS(decimal values)7

2 = 1286

2 = 645

2 = 3242 = 1632 = 822 = 41

2 = 20

2 = 1

Page 716: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure C-6 Ma chine Con ver sion of ASCII Dec i mal to Bi nary.

1. Set up and ini tial ize to bi nary zero a stor age lo ca tion for hold ing the value ac cu mu -lated dur ing con ver sion. Set up a pointer to the high est-or der ASCII digit in thesource string.

2. Test the ASCII digit for a value in the range 0 to 9. End of rou tine if the ASCII digit isnot in this range.

3. Sub tract 30H from ASCII dec i mal digit.

4. Mul ti ply ac cu mu lated value by 10.

5. Add digit to ac cu mu lated value.

6. In cre ment the pointer to the next digit and con tinue at Step 2.

Fig ure C-7 is a flowchart of the con ver sion al go rithm

Fig ure C-7 Flowchart for ASCII to Ma chine Reg is ter Con ver sion.

Num eric Data 695

3 4 5 9

3 4 5 9

9 x 1 = 95 x 10 = 504 x 100 = 4003 x 1000 = 3000 binary = 3459

0 x 10 + 3 = 33 x 10 + 4 = 3434 x 10 + 5 = 345345 x 10 + 9 = 3459

METHOD NUMBER 1

METHOD NUMBER 2

ASCII DECIMAL DIGITS

ASCII DECIMAL DIGITS

START

END

YES

NO

SETUP BINARY ACCUMULATORINITIALIZE POINTER TO FIRST SOURCE DIGIT

ASCII DIGIT - 30H

POINTER TO NEXT DIGIT

ACCUMULATOR X 10ACCUMULATOR + DIGIT

VALID DIGIT?

Page 717: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

This page intentionally left blankThis page intentionally left blank

Page 718: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Appendix D

Character Data

D.1 Char ac ter Rep re sen ta tionsIn this ap pen dix we re view the var i ous encodings and for mats used for rep re sent ingchar ac ter and nu meric data in dig i tal sys tems. The nu meric for mats al low rep re sent -ing bi nary num bers as signed and un signed in te gers in sev eral forms, bi nary float -ing-point num bers, and dec i mal float ing-point num bers, usu ally called bi nary-codeddec i mals or BCD.

D.1.1 Elec tronic-Digital Ma chinesThe mech a ni za tion of arith me tic is of ten traced back to the aba cus, slide rule, me -chan i cal cal cu la tors, and punch card ma chines. The work of John von Neumann atPrince ton’s In sti tute for Ad vanced Study and Re search marks the first high light in thede sign and con struc tion of a dig i tal-elec tronic cal cu lat ing ma chine. In von Neumann’s de sign, data and in struc tions are stored in a com mon mem ory area. An al ter na tive ap -proach, known as Har vard architecture, was dis carded at first but has re cently beenrevalidated and is in use in sev eral microcontroller fam i lies.

The cal cu lat ing power of the first com puter was ap prox i mately 2,000 op er a tionsper sec ond, while pre vi ous elec tro me chani cal de vices were ca pa ble of per form ingonly three or four op er a tions. To day’s dig i tal ma chines can ex e cute more than a bil -lion in struc tions per sec ond. Tech no log i cal ad vances and min ia tur iza tion tech -niques have re duced the cost and size of com put ing ma chin ery.

D.2 Char ac ter Rep re sen ta tionsOver the years, data rep re sen ta tion is sues have of ten been de ter mined by the var i ouscon ven tions used by the dif fer ent hard ware man u fac turer. Ma chines have had dif fer -ent word lengths and dif fer ent char ac ter sets and have used var i ous schemes for stor -ing char ac ter and data. For tu nately, in mi cro pro ces sor and microcontroller de sign,the en cod ing of char ac ter data has not been sub ject to ma jor dis agree ments.

His torically, the meth ods used to rep re sent char ac ters have var ied widely, but the ba sic ap proach has al ways been to choose a fixed num ber of bits and then map the

697

Page 719: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

var i ous bit com bi na tions to the var i ous char ac ters. Clearly, the num ber of bits ofthe stor age for mat lim its the to tal num ber of dis tinct char ac ters that can be rep re -sented. In this man ner, the 6-bit codes used on a num ber of ear lier com put ing ma -chines al low rep re sent ing 64 char ac ters. This range al lows in clud ing the up per caselet ters, the dec i mal dig its, some spe cial char ac ters, but not the low er case let ters.Com puter man u fac tur ers that used the 6-bit for mat of ten ar gued that their cus tom -ers had no need for low er case let ters. Now a days, 7- and 8-bit codes that al low rep re -sent ing the low er case let ters have been adopted al most uni ver sally.

Most of the world (ex cept IBM) has stan dard ized char ac ter rep re sen ta tions us ing the ISO (In ter na tional Stan dards Or ga ni za tion) code. ISO ex ists in sev eral na -tional vari ants; the one used in the United States is called ASCII, which stands forAmer i can Stan dard Code for In for ma tion In ter change. All mi cro com put ers andmicrocontrollers use ASCII as the code for char ac ter rep re sen ta tion.

D.2.1 ASCIIASCII is a char ac ter en cod ing based on the Eng lish al pha bet. ASCII was first pub -lished as a stan dard in 1967 and was last up dated in 1986. The first 33 codes, re ferredto as non-printing codes, are mostly ob so lete con trol char ac ters. The re main ing 95print able char ac ters (start ing with the space char ac ter) in clude the com mon char ac -ters found in a stan dard key board, the dec i mal dig its, and the up per- and low er casechar ac ters of the Eng lish al pha bet. Ta ble D.1 lists the ASCII char ac ters in dec i mal,hex a dec i mal, and bi nary.

Ta ble D.1

ASCII Char ac ter Rep re sen ta tion

DECIMAL HEX BINARY VALUE

000 000 00000000 an nual (Null char ac ter)001 001 00000001 SOH (Start of Header)002 002 00000010 STX (Start of Text)003 003 00000011 ETX (End of Text)004 004 00000100 EOT (End of Trans mis sion)005 005 00000101 ENQ (En quiry)006 006 00000110 ACK (Ac knowl edg ment)007 007 00000111 BEL (Bell)008 008 00001000 BS (Back space)009 009 00001001 HT (Hor i zon tal Tab)010 00A 00001010 LF (Line Feed)011 00B 00001011 VT (Ver ti cal Tab)012 00C 00001100 FF (Form Feed)013 00D 00001101 CR (Car riage Re turn)014 00E 00001110 SO (Shift Out)015 00F 00001111 SI (Shift In)016 010 00010000 DLE (Data Link Es cape)017 011 00010001 DC1 (XON)(De vice Con trol 1)018 012 00010010 DC2 (De vice Con trol 2)019 013 00010011 DC3 (XOFF)(De vice Con trol 3)020 014 00010100 DC4 (De vice Con trol 4)021 015 00010101 NAK (- Ac knowl edge)022 016 00010110 SYN (Syn chro nous Idle)

(con tin ues)

698 Ap pen dix D

Page 720: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Ta ble D.1

ASCII Char ac ter Rep re sen ta tion (conitnued)

DECIMAL HEX BINARY VALUE

000 000 00000000 an nual (Null char ac ter)023 017 00010111 ETB (End of Trans. Block)024 018 00011000 CAN (Can cel)025 019 00011001 EM (End of Me dium)026 01A 00011010 SUB (Sub sti tute)027 01B 00011011 ESC (Es cape)028 01C 00011100 FS (File Sep a ra tor)029 01D 00011101 GS (Group Sep a ra tor)030 01E 00011110 RS (Re quest to Send)031 01F 00011111 US (Unit Sep a ra tor)032 020 00100000 SP (Space)033 021 00100001 ! (ex cla ma tion mark)034 022 00100010 “ (dou ble quote)035 023 00100011 # (num ber sign)036 024 00100100 $ (dol lar sign)037 025 00100101 % (per cent)038 026 00100110 & (am per sand)039 027 00100111 ‘ (sin gle quote)040 028 00101000 ( (left/open ing pa ren the sis)041 029 00101001 ) (right/clos ing pa ren the sis)042 02A 00101010 * (as ter isk)043 02B 00101011 + (plus)044 02C 00101100 , (comma)045 02D 00101101 - (mi nus or dash)046 02E 00101110 . (dot)047 02F 00101111 / (for ward slash)048 030 00110000 0 (dec i mal dig its ...)049 031 00110001 1050 032 00110010 2051 033 00110011 3052 034 00110100 4053 035 00110101 5054 036 00110110 6055 037 00110111 7056 038 00111000 8057 039 00111001 9058 03A 00111010 : (co lon)059 03B 00111011 ; (semi-colon)060 03C 00111100 < (less than)061 03D 00111101 = (equal sign)062 03E 00111110 > (greater than)063 03F 00111111 ? (ques tion mark)064 040 01000000 @ (AT sym bol)065 041 01000001 A066 042 01000010 B067 043 01000011 C. . .090 05A 01011010 Z091 05B 01011011 [ (left/open ing bracket)092 05C 01011100 \ (back slash)093 05D 01011101 ] (right/clos ing bracket)

(con tin ues)

Character Data 699

Page 721: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Ta ble D.1

ASCII Char ac ter Rep re sen ta tion (conitnued)

DECIMAL HEX BINARY VALUE

094 05E 01011110 ^ (cir cum flex)095 05F 01011111 _ (un der score)096 060 01100000 '097 061 01100001 a098 062 01100010 b099 063 01100011 c...122 07A 01111010 z123 07B 01111011 (left/open ing brace)124 07C 01111100 | (ver ti cal bar)125 07D 01111101 (right/clos ing brace)126 07E 01111110 ~ (tilde)127 07F 01111111 DEL (de lete)

D.2.2 EBCDIC and IBM

In spite of ASCII’s gen eral ac cep tance, IBM con tin ues to use EBCDIC (Ex tended Bi -nary Coded Dec i mal In ter change Code) for char ac ter en cod ing. IBM main frames andmid-range sys tems such as the AS/400 use a wholly in com pat i ble char ac ter set pri mar -ily de signed for punched cards.

EBCDIC uses the full eight bits avail able to it, so there is no place left to im ple -ment par ity check ing. On the other hand, EBCDIC has a wider range of con trol char -ac ters than ASCII.

EBCDIC char ac ter en cod ing is based on Bi nary Coded Dec i mal (BCD), which wedis cuss in Sec tion D.5. There are four main blocks in the EBCDIC code page:

1. The range 0000 0000 to 0011 1111 is re served for con trol char ac ters.

2. The range 0100 0000 to 0111 1111 is for punc tu a tion.

3. The range 1000 0000 to 1011 1111 is for low er case char ac ters.

4. The range 1100 0000 to 1111 1111 is for up per case char ac ters and num bers.

Actually, mi cro pro ces sor and microcontroller de sign need not ad dress how char -ac ter data is en coded. Usually a set of in struc tions al lows ma nip u lat ing 8-bit quan ti -ties, but the pro ces sor need not be con cerned with what the encodings rep re sent.On the other hand, some main frame pro ces sors do have in struc tions that ma nip u -late char ac ter codes. For ex am ple, the EDIT in struc tion on the IBM 370 im ple mentsthe kind of pic ture con ver sion that ap pears in COBOL pro grams.

D.2.3 Unicode

One of the lim i ta tions of the ASCII code is that eight bits are not enough for rep re sent -ing char ac ters sets in lan guages such as Jap a nese or Chi nese which use large char ac -ter sets. This has led to the de vel op ment of encodings that al low rep re sent ing largechar ac ter sets. Unicode has been pro posed as a uni ver sal char ac ter en cod ing stan -dard that can be used for rep re sen ta tion of text for com puter pro cess ing.

700 Ap pen dix D

Page 722: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Unicode at tempts to pro vide a con sis tent way of en cod ing mul ti lin gual text andthus make it pos si ble to ex change text files in ter na tion ally. The de sign of Unicode isbased on the ASCII code, but goes be yond the Latin al pha bet to which ASCII is lim -ited. The Unicode Stan dard pro vides the ca pac ity to en code all the char ac ters usedfor the writ ten lan guages of the world. Like ASCII, Unicode as signs each char ac ter aunique nu meric value and name. Unicode uses three en cod ing forms that use a com -mon rep er toire of char ac ters. These forms al low en cod ing as many as a mil lion char -ac ters.

The three en cod ing forms of the Unicode Stan dard al low the same data to be trans -mit ted in a byte, word, or dou ble-word for mat, that is, in 8-, 16-, or 32-bits per char ac -ter.

• UTF-8 is a way of trans form ing all Unicode char ac ters into a vari able length en cod ingof bytes. In this for mat the Unicode char ac ters cor re spond ing to the fa mil iar ASCIIset have the same byte val ues as ASCII. By the same to ken, Unicode char ac ters trans -formed into UTF-8 can be used with ex ist ing soft ware.

• UTF-16 is de signed to bal ance ef fi cient ac cess to char ac ters with eco nom i cal use ofstor age. It is rea son ably com pact and all the heavily used char ac ters fit into a sin gle16-bit code unit, while all other char ac ters are ac ces si ble via pairs of 16-bit code units.

• UTF-32 is used where mem ory space is no con cern, but fixed width, sin gle code unitac cess to char ac ters is de sired. In UTF-32, each Unicode char ac ter is rep re sented bya sin gle 32-bit code.

D.3 Stor age and En coding of In te gersThe In dian math e ma ti cian Pingala first de scribed bi nary num ber in the fifth cen turyB.C. The mod ern sys tem of bi nary num bers first ap peared in the work of GottfriedLeibniz dur ing the sev en teenth cen tury. Dur ing the mid-nine teenth cen tury, the Brit ishlo gi cian George Boole de scribed a log i cal sys tem that used bi nary num bers to rep re sent log i cal true and false. In 1937, Claude Shannon pub lished his mas ter’s the sis that used Boolean al ge bra and bi nary arithmetic to im ple ment elec tronic re lays and switches.The the sis pa per en ti tled A Sym bolic Anal y sis of Re lay and Switch ing Cir cuits is usu -ally con sid ered the or i gin of mod ern dig i tal cir cuit de sign.

Also in 1937, George Stibitz com pleted a re lay-based com puter that could per formbi nary ad di tion. The Bell Labs Com plex Num ber Com puter, also de signed by Stibitz,was com pleted in Jan u ary 1940. The sys tem was dem on strated to the Amer i canMath e mat i cal So ci ety in Sep tem ber 1940. The at ten dants in cluded John VonNeumann, John Mauchly, and Norbert Wiener. In 1945, von Neumann wrote a sem i nalpa per in which he stated that bi nary num bers were the ideal com pu ta tional for mat.

D.3.1 Signed and Un signed Rep re sen ta tions

For un signed integers there is lit tle doubt that the bi nary rep re sen ta tion is ideal. Suc -ces sive bits in di cate powers of 2, with the most-sig nif i cant bit at the left and the least-sig nif i cant one on the right, as is cus tom ary in dec i mal rep re sen ta tions. Fig ure D-1shows the digit weights and con ven tional bit num ber ing in the bi nary en cod ing.

Character Data 701

Page 723: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure D-1 Bi nary Digit Weights and Num ber ing.

In or der to per form arith me tic op er a tions, the dig i tal ma chine must be ca pa ble of stor ing and re triev ing nu mer i cal data. Nu mer i cal data is stored in stan dard for mats,de signed to min i mize space and op ti mize pro cess ing. His tor i cally, nu meric data was stored in data struc tures de vised to fit the char ac ter is tics of a spe cific ma chine, orthe pref er ences of its de sign ers. It was in 1985 that the In sti tute of Elec tri cal andElec tron ics En gi neers (IEEE) and the Amer i can Na tional Stan dards In sti tute(ANSI) for mally ap proved math e mat i cal stan dards for en cod ing and stor ing nu mer i -cal data in dig i tal de vices.

The elec tronic and phys i cal mech a nisms used for stor ing data have evolved withtech nol ogy. One com mon fea ture of many de vices, from punched tape to in te gratedcir cuits, is that the en cod ing is rep re sented in two pos si ble states. In pa per tape thetwo states are holes and no holes, while in elec tronic me dia they are usu ally thepres ence and ab sence of an elec tri cal charge.

Data stored in pro ces sor reg is ters, in mag netic me dia, in op ti cal de vices, or inpunched tape is usu ally en coded in bi nary. Thus, the pro gram mer and the op er a torcan usu ally ig nore the phys i cal char ac ter is tics of the stor age me dium. In otherwords, the bit pat tern 10010011 can be en coded as holes in a strip of pa per tape, asmag netic charges on a my lar-coated disk, as pos i tive volt ages in an in te grated cir -cuit mem ory cell, or as min ute crat ers on the sur face of a CD. In all cases, 10010011rep re sents the dec i mal num ber 147.

D.3.2 Word SizeIn elec tronic dig i tal de vices the bi stable states are rep re sented by a bi nary digit, orbit. Cir cuit de sign ers group sev eral in di vid ual cells to form a unit of stor age that holds

702 Ap pen dix D

DIGIT POSITIONAL WEIGHT7

2 = 12862 = 6452 = 3242 = 1632 = 822 = 412 = 202 = 1

0 (LEAST SIGNIFICANT BIT)1234567 (MOST SIGNIFICANT BIT)

Page 724: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

sev eral bits. In a par tic u lar ma chine the ba sic unit of data stor age is called the wordsize. Word size in com put ers of ten ranges from 8 to 128 bits, in pow ers of 2.Microcontrollers and other dig i tal de vices some times use word sizes that are de ter -mined by their spe cific ar chi tec tures. For ex am ple, some PIC microcontrollers use a14-bit word size.

In most dig i tal ma chines the small est unit of stor age in di vid u ally ad dress able iseight bits (one byte). In di vid ual bits are not di rectly ad dress able and must be ma nip -u lated as part of larger units of data stor age.

D.3.3 Byte Or der ingThe stor age of a sin gle-byte in te ger can be done ac cord ing to the scheme in Fig ure D-1. How ever, the max i mum value that can be rep re sented in eight bits is the dec i mal num -ber 255. To rep re sent larger bi nary in te gers re quires ad di tional stor age area. Be causemem ory is usu ally or ga nized in byte-size units, any dec i mal num ber larger than 255 re -quires more than one byte of stor age. In this case the en cod ing is pad ded with the nec -es sary lead ing ze ros. Fig ure D-2 is a rep re sen ta tion of the dec i mal num ber 21,141stored in two con sec u tive data bytes.

Fig ure D-2 Rep re sen ta tion of an Un signed In te ger.

One is sue re lated to us ing mul ti ple mem ory bytes to en code bi nary in te gers is the suc ces sive lay out of the var i ous byte-size units. In other words, does the rep re sen ta -tion store the most-sig nif i cant byte at the low est num bered mem ory lo ca tion, orviceversa. For ex am ple, when a 32-bit bi nary in te ger is stored in a 32-bit stor agearea, we can fol low the con ven tional pat tern of plac ing the low-order bit on theright-hand side and the high-order bit on the left, as we did in Fig ure D-1. How ever,if the 32-bit num ber is to be stored into four byte-size mem ory cells, then two pos si -ble stor age schemes are pos si ble, as shown in Fig ure D-3.

Fig ure D-3 Byte Or der ing Schemes.

Character Data 703

= 01010010 10010101 = 21,141

binary

machine storage

decimal

32 bits 32 bits

memory bytesmemory bytes

low low

lowlow

high

LOW-TO-LOW STORAGE SCHEME HIGH-TO-LOW STORAGE SCHEME

high

highhigh

Page 725: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

In the low-to-low stor age scheme, the low-order 8-bits of the op er and are storedin the low-order mem ory byte, the next group of 8-bits are moved to the fol low ingmem ory byte in low-to-high or der, and so on. Con ceiv ably, this scheme can be de -scribed by say ing that the “lit tle end” of the op er and is stored first, that is, in low estmem ory. Ac cord ing to this no tion, the stor age scheme is de scribed as the lit -tle-endian for mat. If the “big-end” of the op er and, that is, the high est val ued bits, isstored in the low mem ory ad dresses, then the byte or der ing is said to be inbig-endian for mat. Some Intel pro ces sors (like those of the 80x86 fam ily) fol lowthe lit tle-endian for mat. Some Motorola pro ces sors (like those of the 68030 fam ily)fol low the big-endian for mat, while oth ers (such as the MIPS 2000) can be con fig -ured to store data in ei ther for mat.

In many sit u a tions the pro gram mer needs to be aware of the byte-orderingscheme; for ex am ple, to re trieve mem ory data into pro ces sor reg is ters so as to per -form multi-byte arith me tic, or to con vert data stored in one for mat to the other one.This last op er a tion is a sim ple byte-swap. For ex am ple, if the hex value 01020304 isstored in four con sec u tive mem ory cells in low-to-high or der (lit tle-endian for mat),it ap pears in mem ory (low-to-high) as the val ues 04030201. Con verting this data tothe big-endian for mat con sists of swap ping the in di vid ual bytes so that they arestored in the or der 01010304. Fig ure D-4 is a di a gram of a byte-swap op er a tion.

Fig ure D-4 Data For mat Con ver sion by Byte Swap ping.

D.4.4 Sign-Magnitude Rep re sen ta tion

Rep re senting signed num bers re quires dif fer en ti at ing be tween pos i tive and neg a tivemag ni tudes. One pos si ble scheme is to de vote one bit to rep re sent the sign. Typicallythe high-order bit is set (1) to de note neg a tives and re set (0) to de note positives. Usingthis con ven tion, the dec i mal num bers 93 and – 93 are rep re sented as fol lows:

01011101 bi nary = 93 dec i mal

11011101 bi nary = -93 dec i mal

|

|----------- sign bit

This way of des ig nat ing neg a tive num bers, called a sign-magnitude rep re sen ta -tion, cor re sponds to the con ven tional way in which we write neg a tive and pos i tivenum bers long hand, that is, we pre cede the num ber by its sign. Sign-magnitude rep -re sen ta tion has the fol low ing char ac ter is tics:

704 Ap pen dix D

23 16

23 16

31 24

31 24

15 8

15 8

7 0

7 0

Page 726: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

1. The ab so lute value of pos i tive and neg a tive num bers is the same.

2. Pos i tive num bers can be dis tin guished from neg a tive num bers by ex am in ing thehigh-or der bit.

3. There are two pos si ble rep re sen ta tions for zero, one neg a tive (10000000B) and onepos i tive (00000000B).

But a ma jor lim i ta tion of sign-magnitude rep re sen ta tion is that the pro cess ing re -quired to per form ad di tion is dif fer ent from that for sub trac tion. Com pli cated rulesare re quired for the ad di tion of signed num bers. For ex am ple, con sid er ing twooperands la beled x and y, the fol low ing rules must be ob served for per form ingsigned ad di tion:

1. If x and y have the same sign, they are added di rectly and the re sult is given the com -mon sign.

2. If x is larger than y, then y is sub tracted from x and the re sult is given the sign of x.

3. If y is larger than x, then x /is sub tracted from y and the re sult is given the sign of y.

4. If ei ther x or y is 0 or – 0, the re sult is the non-zero el e ment.

5. If both x and y are – 0, then the sum is 0.

How ever, there are other nu meric rep re sen ta tions that avoid this sit u a tion. Acon se quence of sign-magnitude rep re sen ta tion is that, in some cases, it is nec es sary to take into ac count the mag ni tude of the operands in or der to de ter mine the sign of the re sult. Also, the pres ence of an en cod ing for neg a tive zero re duces the nu mer i -cal range of the rep re sen ta tion and is, for most prac ti cal uses, an un nec es sary com -pli ca tion. An im por tant lim i ta tion of us ing the high-order bit for rep re sent ing thesign is the re sult ing halv ing of the nu mer i cal range.

D.3.5 Ra dix Com ple ment Rep re sen ta tion

The ra dix com ple ment of a num ber is de fined as the dif fer ence be tween the num berand the next in te ger power of the base that is larger than the num ber. In dec i mal num -bers the ra dix com ple ment is called the ten’s com ple ment. In the bi nary sys tem the ra -dix com ple ment is called the two’s com ple ment. For ex am ple, the ra dix com ple mentof the dec i mal num ber 89 (ten’s com ple ment) is cal cu lated as fol lows:

100 = higher power of 10

- 89

----

11 = ten’s com ple ment of 89

The use of ra dix com ple ments to sim plify ma chine sub trac tion op er a tions canbest be seen in an ex am ple. The op er a tion x = a – b with the fol low ing val ues:

a = 602

b = 353

602

- 353

_____

x = 249

Character Data 705

Page 727: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Note that in the pro cess of per form ing long hand sub trac tion, we had to per formtwo bor row op er a tions. Now con sider that the ra dix com ple ment (ten’s com ple -ment) of 353 is:

1000 - 353 = 647

Using com ple ments we can re for mu late sub trac tion as the ad di tion of the ten’scom ple ment of the sub tra hend, as fol lows:

602 + 647 ______ 1249 |____________ dis carded digit

The re sult is ad justed by dis card ing the digit that over flows the num ber of dig itsin the operands.

In per form ing long hand dec i mal arith me tic there is lit tle ad van tage in re plac ingsub trac tion with ten’s com ple ment ad di tion. The work of cal cu lat ing the ten’s com -ple ment can cels out any other pos si ble ben e fit. How ever, in bi nary arith me tic theuse of ra dix com ple ments en tails sig nif i cant com pu ta tional ad van tages be cause bi -nary ma chines can cal cu late com ple ments ef fi ciently.

The two’s com ple ment of a bi nary num ber is ob tained in the same man ner as theten’s com ple ment of a dec i mal num ber, that is, by sub tract ing the num ber from anin te ger power of the base that is larger than the num ber. For ex am ple, the two’scom ple ment of the bi nary num ber 101 is

1000B = 2^3 = 8 dec i mal (higher power of 2) - 101B = 5 dec i mal _________ _________ 011B = 3 dec i mal

While the two’s com ple ment of 10110B is cal cu lated as fol lows:

100000B = 2^5 = 32 dec i mal (higher power of 2) - 10110B = 22 dec i mal _______ __________ 01010B 10 dec i mal

You can per form the bi nary sub trac tion of 11111B (31 dec i mal) – 10110B (22 dec i -mal) by find ing the two’s com ple ment of the sub tra hend, add ing the two operands,and dis card ing any over flow digit, as fol lows:

11111B = 31 dec i mal + 01010B = 10 dec i mal (two’s com ple ment of 22) _______ 101001B dis card______| 01001B = 9 dec i mal (31 mi nus 22 = 9)

In ad di tion to the ra dix com ple ment rep re sen ta tion, there is a di min ished ra dixrep re sen ta tion that is of ten use ful. This en cod ing, some times called the ra dix-mi -nus-one form, is cre ated by sub tract ing 1 from an in te ger power of the base that islarger than the num ber, then sub tract ing the op er and from this value. In the dec i mal

706 Ap pen dix D

Page 728: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

sys tem, the di min ished ra dix rep re sen ta tion is some times called the nine’s com ple ment.This is due to the fact that an in te ger power of ten, mi nus one, re sults in one or more9-dig its. In the bi nary sys tem, the di min ished ra dix rep re sen ta tion is called the one’scom ple ment. The nine’s com ple ment of the dec i mal num ber 76 is cal cu lated as fol lows:

100 = next high est in te ger power of 10

99 = 100 mi nus 1 - 76 ---- 23 = nine’s com ple ment of 89

The one’s com ple ment of a bi nary num ber is ob tained by sub tract ing the num ber from an in te ger power of the base that is larger than the num ber, mi nus one. For ex am ple, theone’s com ple ment of the bi nary num ber 101 (5 dec i mal) can be cal cu lated as fol lows:

1000B = 2^3 = 8 dec i mal

111B = 1000B mi nus 1 = 7 dec i mal - 101B 5 dec i mal ------ --------- 010B = 2 dec i mal

An in ter est ing fea ture of one’s com ple ment is that it can be ob tained by chang ing ev -ery 1 bi nary digit to a 0 and ev ery 0 bi nary digit to a 1. In this ex am ple, 010B is the one’scom ple ment of 101B. In this con text the 0 bi nary digit is of ten said to be the com ple mentof the 1 bi nary digit, and vice versa. Most mod ern com put ers con tain an in struc tion thatin verts all the dig its of a value by chang ing all 1 dig its into 0, and all 0 dig its into 1. Theop er a tion is also known as log i cal ne ga tion.

Fur ther more, the two’s com ple ment can be ob tained by add ing 1 to the one’s com ple -ment of a num ber. There fore, in stead of cal cu lat ing

100000B - 10110B ------- 01010B

we can find the two’s com ple ment of 10110B as fol lows:

10110B = num ber 01001B = change 0 to 1 and 1 to 0 (one’s com ple ment) + 1B then add 1 --------- 01010B = two’s com ple ment

This al go rithm pro vides a con ve nient way of cal cu lat ing the two’s com ple ment in ama chine equipped with a com ple ment in struc tion. Finally, the two’s com ple ment can beob tained by sub tract ing the op er and from zero and dis card ing the over flow.

The ra dix com ple ment of a num ber is the dif fer ence be tween the num ber and an in te -ger power of the base that is larger than the num ber. Fol low ing this rule, we cal cu late the ra dix com ple ment of the bi nary num ber 10110 as fol lows:

100000B = 2^5 = 32 dec i mal - 10110B = 22 dec i mal ------- ---------- 01010B 10 dec i mal

Character Data 707

Page 729: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

How ever, the ma chine cal cu la tion of the two’s com ple ment of the same value of -ten pro duces a dif fer ent re sult; for ex am ple,

100000000B = 28 = 256 dec i mal

- 00010110B = 22 dec i mal

__________ ___________

11101010B 234 dec i mal

The dif fer ence is due to the fact that in the long hand method we have used thenext-higher in te ger power of the base com pared to the value of the sub tra hend (inthis case, 100000B) while the ma chine cal cu la tions use the next-higher in te gerpower of the base com pared to the op er and’s word size, which is nor mally ei ther 8or 16 bits. In this ex am ple the op er and’s word size is eight bits and the next-high estin te ger power of 2 is 100000000B. In ei ther case, the re sults from two’s com ple mentsub trac tion are valid as long as the min u end is an in te ger power of the base that islarger than the sub tra hend.

For ex am ple, to per form the bi nary sub trac tion of 00011111B (31 dec i mal) mi nus00010110B (22 dec i mal) we can find the two’s com ple ment of the sub tra hend andadd, dis card ing any over flow digit, as fol lows:

00011111B = 31 dec i mal

+ 11101010B = 234 dec i mal (two’s com ple ment of 22)

_________

100001001B

dis card____|

00001001B = 9 dec i mal (31 mi nus 22 = 9)

In ad di tion to the sim pli fi ca tion of sub trac tion, two’s com ple ment arith me tic hasthe ad van tage that there is no rep re sen ta tion for neg a tive 0. It can be ar gued thatthere are cases in which a neg a tive zero no ta tion could be use ful, but in fact this isusu ally un nec es sary. While both the two’s com ple ment and the one’s com ple mentschemes can be used to im ple ment bi nary arith me tic, sys tem de sign ers usu ally pre -fer the two’s com ple ment.

D.4 En coding of Frac tional Num bersIn any po si tional num ber sys tem, the weight of each in te ger digit is de ter mined by thefor mula

P = d * BC

where d is the digit, B is the base or ra dix, and C is the zero-based col umn num ber,start ing from right to left. There fore, the value of a multi-digit pos i tive in te ger to n dig -its can be ex pressed as a sum of the digit val ues:

dn*Bn + dn-1*Bn-1 + dn-2*Bn-2 + ... + d0*B0

where d is the value of the digit and B is the base or ra dix of the num ber sys tem. Thisrep re sen ta tion can be ex tended to rep re sent frac tional val ues. Re calling that we canex tend the se quence to the right of the ra dix point, as fol lows

708 Ap pen dix D

Page 730: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure D-5 Po si tional Weights in a Bi nary Frac tion.

In the dec i mal sys tem, the value of each digit to the right of the dec i mal point iscal cu lated as 1/10, 1/100, 1/1000, and so on. The value of each suc ces sive digit of abi nary frac tion is the re cip ro cal of a power of 2; there fore, the se quence is 1/2, 1/4,1/8, 1/16, ... Fig ure D-5 shows the po si tional weight of the in te ger and frac tional dig -its in a bi nary num ber.

In Chap ter 2 we used the po si tional weights of the bi nary dig its to con vert a bi -nary num ber to its dec i mal equiv a lent. A sim i lar method can be used to con vert thefrac tional part of a bi nary num ber. Using the dec i mal equiv a lents shown in Fig ureD-5 we con vert the bi nary frac tion .10101 to a dec i mal frac tion as fol lows:

.1 0 1 0 1

| | |

.500 _____________________| | |

.125 _________________________| |

.03125 ____________________________|

------

.65625

D.4.1 Fixed-Point Rep re sen ta tions

The en cod ing and stor age of frac tional num bers (also called real num bers) in bi naryform pres ents sev eral dif fi cul ties. The first one is re lated to the rep re sen ta tion of thera dix point. Be cause there are only two sym bols in the bi nary set, and both are usedto rep re sent the nu mer i cal value of the num ber, there is no other sym bol avail able forthe dec i mal point.

Character Data 709

1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1

INTEGER PART72 = 12862 = 6452 = 3242 = 1632 = 822 = 41

2 = 202 = 1

FRACTIONAL PART-1.500 1/2 2-2.250 1/4 2-3.125 1/8 2-4.0625 1/16 2-5.03125 1/32 2-6

.015625 1/64 2-7.0078125 1/128 2-8

.00390625 1/256 2

radix point

xx

nn

− = 1

Page 731: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure D-6 Bi nary Fixed-Point Rep re sen ta tion.

One pos si ble so lu tion is to pre de fine the digit field that rep re sents the in te gerpart and the one that rep re sents the frac tional part. For ex am ple, if a real num ber isto be en coded in two data bytes, we can as sign the high-order byte to en code the in -te ger part and the low-order byte for the frac tional part. In this case, the pos i tivedec i mal num ber 58.125 could be en coded as shown in Fig ure D-6.

In Fig ure D-6 we as sumed that the bi nary point is po si tioned be tween the eighthand the ninth digit of the en cod ing. Fixed-point rep re sen ta tions as sume that what -ever dis tri bu tion of dig its is se lected for the in te ger and the frac tional part of therep re sen ta tion is main tained in all cases. This is the great est lim i ta tion of thefixed-point for mats.

Sup pose we want to store the value 312.250. This num ber is rep re sented in bi nary as fol lows:

312 = 100111000 .250 = .01

In this case, the to tal num ber of bi nary dig its re quired for the bi nary en cod ing is11. The num ber can be phys i cally stored in a 16-digit struc ture (as the one in Fig ureD-6), leav ing five cells to spare. How ever, be cause the fixed-point for mat we haveadopted as signs eight cells to the in te ger part of the num ber, 312.250 can not be en -coded be cause the in te ger part re quires nine bi nary dig its. In spite of this lim i ta tion, the-fixed point for mat was the only one used in early com put ers.

D.4.2 Floating-Point Rep re sen ta tionsAn al ter na tive to fixed-point is not to as sume that the ra dix point has a fixed po si tionin the en cod ing, but to al low it to float, hence the name float ing-point. The idea of sep -a rately en cod ing the po si tion of the ra dix point orig i nated in sci en tific no ta tion,where a num ber is writ ten as a base greater than or equal to 1 and smaller than 10, mul -ti plied by a power of 10. For ex am ple, the value 310.25 in sci en tific no ta tion is writ ten:

A num ber in sci en tific no ta tion has a real part and an ex po nent part. Using theter mi nol ogy of log a rithms, these two parts are some times called the man tissa andthe char ac ter is tic. The fol low ing sim pli fi ca tion of sci en tific no ta tion is of ten usedin com puter work:

3.1025 E2

710 Ap pen dix D

= 00111010 00100000 = 58.125

binary decimal

implied binary point

31025 102. ×

Page 732: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

In the com puter ver sion of sci en tific no ta tion, the mul ti pli ca tion sym bol and thebase are im plied. The let ter E, which is used to sig nal the start of the ex po nent partof the rep re sen ta tions, ac counts for the name “ex po nen tial form.” Num bers smallerthan 1 can be rep re sented in sci en tific no ta tion or in ex po nen tial form us ing neg a -tive pow ers. For ex am ple, the num ber .0004256 can be writ ten:

or as

4.256 E-4

Floating-point rep re sen ta tions pro vide a more ef fi cient use of the ma chine’s stor -age space. For ex am ple, the nu mer i cal range of the fixed-point en cod ing shown inFig ure D-6 is from 255.99609375 to 0.00390625. To im prove this range we can re as -sign the six teen bits of stor age so that four bits are used for en cod ing the ex po nentand twelve bits for the frac tional part, called the significand. In this case the en -coded num ber ap pears as fol lows:

0000 000000000000

+--+ +----------+

¦ |__________ 12-bit frac tional part

¦ (significand)

|___________________ 4-bit ex po nent part

If we were to use the first bit of the ex po nent to in di cate the sign of the ex po nent, then the range of the re main ing three dig its would be 0 to 7. Note that the sign of the ex po nent in di cates the di rec tion in which the dec i mal point is to be moved; this isun re lated to the sign of the num ber. In this ex am ple, the frac tional part (orsignificand) could hold val ues in the range 1,048,575 to 1. The com bined range of ex -po nent and significand al lows rep re sent ing dec i mal num bers in the range 4095 to0.00000001 that con sid er ably ex ceeds the range in the same stor age space infixed-point for mat.

D.4.3 Stan dard ized Floating-Point Rep re sen ta tions

Both the significand and the ex po nent of a float ing-point num ber can be stored as anin te ger, in sign-magnitude, or in ra dix com ple ment form. The num ber of bits as signedto each field var ies ac cord ing to the range and the pre ci sion re quired. For ex am ple,the com put ers of the CDC 6000, 7000, and CYBER se ries used a 96-digit significandwith an 11-digit ex po nent, while the PDP 11 se ries used 55-digit significands and8-digit ex po nents in their ex tended pre ci sion for mats.

Vari a tions, in com pat i bil i ties, and in con sis ten cies in float ing-point for mats led tothe de vel op ment of a stan dard for mat. In March and July 1985, the Com puter So ci -ety of the In sti tute of Elec tric and Elec tronic En gi neers (IEEE) and the Amer i canNa tional Stan dards In sti tute (ANSI) ap proved a stan dard for bi nary float ing-pointarith me tic (ANSI/IEEE Stan dard 754-1985). This stan dard es tab lishes four for matsfor en cod ing bi nary float ing-point num bers. Ta ble D.2 sum ma rizes the char ac ter is -tics of these for mats.

Character Data 711

4 256 10 4. × −

Page 733: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Ta ble D.2

ANSI/IEEE Floating Point For mats

PARAMETER SINGLE SINGLE DOUBLE DOUBLE EXTENDED EXTENDED

to tal bits 32 43 64 79significand bits 24 32 53 64max i mum ex po nent +127 1023 1023 16383min i mum ex po nent −126 1022 −1022 16382ex po nent width 8 11 11 15ex po nent bias +127 --- +1023 ---

D.4.4 IEEE 754 Sin gle For matFig ure D-7 shows the IEEE float ing-point sin gle for mat.

Fig ure D-7 IEEE Floating-Point Sin gle For mat.

If a float ing-point en cod ing is to al low the rep re sen ta tion of signed num bers, itmust de vote one bi nary digit to en code the num ber’s sign. In the IEEE 754 sin gle for -mat in Fig ure D-7, the high-order bit rep re sents the sign of the num ber. A value of 1in di cates a neg a tive num ber.

The ex po nent of a bi nary float ing-point num ber rep re sents the in te ger power ofthe base with which the significand must be mul ti plied. The ex po nent can be storedin in te ger, sign mag ni tude, or ra dix com ple ment rep re sen ta tions. The IEEE 754stan dard for float ing-point arith me tic es tab lishes that the ex po nent be stored in bi -ased form, al though the bias is not de fined in all for mats de fined in the stan dard.

The word bias, in this con text, means a con stant that is added to the ex po nent inor der to de ter mine its fi nal value. The term ex cess-n no ta tion has also been used inthis con text. The con stant is usu ally cal cu lated to be ap prox i mately one-half the nu -mer i cal range of the ex po nent field. For ex am ple, the IEEE sin gle for mat de voteseight dig its for the ex po nent field (see Fig ure D-7). The nu mer i cal range of eight bi -nary dig its is 0 to 255 dec i mal and one-half of this range is ap prox i mately 127.Adding the con stant 127 to all pos i tive ex po nents places them in the range 127 to255. The lower half of the range (1 to 126) is used for neg a tive ex po nents. A 0-valuein the ex po nent field is re served to en code zero and denormals. Denormals are aspe cial type of num ber dis cussed in the fol low ing para graph. Ta ble D.3 shows theval ues of the ex po nent and the bi ased rep re sen ta tion in the IEEE sin gle for mat forfloat ing-point num bers.

712 Ap pen dix D

31

30 22 0 bits

mantissa (23 bits)exponent (8 bits)

sign of the number (1 bit)

Page 734: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Ta ble D.3

In ter pre ta tion of Ex po nent in the IEEE Sin gle For mat

BIASED SIGN OF TRUE EXPONENT NUMBER EXPONENT SIGNIFICAND CLASS

0000 0000 + – 00 ... 00 pos i tive zero – – 00 ... 00 neg a tive zero 11 ... 11 to 00 ... 01 denormals

0000 0001 – –126 00 ... 00 nor malsto to to0111 1111 0 11 ... 111000 0000 – 1 00 ... 00 nor malsto to to1111 1110 127 11 ... 11

1111 1111 + – 00 ... 00 + in fin ity – 00 ... 00 – in fin ity – 10 ... 00 In def i nite – 00 ... 01 to 11 ... 11 Not-a-num ber

Note in Ta ble D.3 that the ex po nent value 00000000B is used to rep re sent zeroand denormal num bers. Denormals, or denormalized num bers, oc cur when the ex -po nent of the num ber is too small to rep re sent in the cor re spond ing float ing-pointfor mat. On the other hand, the ex po nent 11111111B is used to en code num bers thatare too large for the sin gle for mat, or to rep re sent er ror con di tions. The ex po nentrange 00000001B to 11111110B (dec i mal val ues 1 to 254) is used to rep re sent nor -mal num bers, that is, num bers that are within the range of the for mat.

In IEEE 754 float ing-point for mats the high bit of the ex po nent field does not en -code the sign, as is the case in the sign-magnitude form. In stead, the bias 127scheme, men tioned pre vi ously, is used to rep re sent neg a tive and pos i tive ex po -nents. Neg a tive ex po nents are in the range 1 to 127 (see Ta ble D.3) and pos i tive ex -po nents are in the range 128 to 254. In con trast with fixed-point con ven tions, thehigh bit of the ex po nent is set to in di cate a pos i tive ex po nent, and is zero to in di cate a neg a tive ex po nent. The main ad van tage of a bi ased ex po nent is that the num berscan be com pared bitwise, from left to right, to de ter mine the larger one. The num -ber’s true ex po nent is ob tained by sub tract ing the bias.

The third field of the float ing-point rep re sen ta tion is known by sev eral names:frac tional part, man tissa, char ac ter is tic, and significand (see Fig ure D-7). Theword significand is the one most com monly used the lit er a ture. Like the ex po nent,the significand can be stored as an in te ger, or in sign-mag ni tude or ra dix com ple -ment rep re sen ta tions.

A float ing-point bi nary num ber is said to be in nor mal ized form when the firstdigit of its significand is 1. An un-nor mal ized bi nary float ing-point num ber can benor mal ized by suc ces sively shift ing the dig its of the significand to the left, while si -mul ta neously sub tract ing one from the ex po nent. This pro cess is con tin ued un til

Character Data 713

Page 735: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

the high-or der bit of the significand is a bi nary 1. The pro cess does not change thevalue of the num ber, as shift ing the significand bits to the left ef fec tively mul ti pliesthe num ber by 2, while sub tract ing one from the ex po nent di vides the num ber by 2.Clearly, the value of a num ber does not change if it is mul ti plied and di vided by thesame value. Also, note that nor mal iza tion ap plies to the en tire en coded num ber be -cause it re quires ad just ments of both the ex po nent and the significand. There fore, it is not cor rect to speak of a nor mal ized significand or a nor mal ized man tissa; weshould re fer to the significand of a nor mal ized float ing-point num ber.

One ad van tage of the nor mal ized form is that the significand con tains a max i -mum num ber of sig nif i cant bits. How ever, ad di tion and sub trac tion of float ing-point num bers re quire that both operands have the same ex po nent. There fore, be fore per -form ing these op er a tions, it is of ten nec es sary to shift the significand dig its to theright or to the left so that the ex po nents are equal.

The IEEE stan dard takes ad van tage of the fact that a nor mal ized significand of abi nary float ing point starts with a 1 digit. In the sin gle- and dou ble-pre ci sion for -mats, this lead ing bit of the significand is as sumed, in ef fect dou bling the range ofthe rep re sen ta tion. Not so in the ex tended for mats, in which the digit must be ex -plic itly coded. Note that this as sump tion is not valid if the ex po nent is all ze ros. Azero ex po nent and a non-zero significand in di cate a denormal, as shown in Ta bleD.3. Also, the use of an im plicit bit makes nec es sary a spe cial rep re sen ta tion forzero (see Ta ble D.3). This spe cial zero must be han dled sep a rately dur ing arith me tic op er a tions.

D.4.5 En coding and De coding Floating-Point Num bers

The for mats in the IEEE 754 stan dard for bi nary float ing-point arith me tic were de -signed to pro vide max i mum stor age ca pac ity and pro cess ing ef fi ciency. For ex am ple,the ex po nent in the IEEE sin gle for mat, stored in bi ased form, takes up eight bits; how -ever, these eight bits do not fall on a byte bound ary. The ex po nent bits take up sevenbit po si tions in the high-order byte, and one bit po si tion in the next byte, as shown inFig ure D-7. In the same IEEE sin gle en cod ing, the significand takes up seven bits ofthe sec ond byte as well as the third and fourth bytes. The sign of the num ber is thehigh-order bit of the high-order byte. Fig ure D-8 shows the num ber 127.375 stored inthe IEEE float ing-point sin gle for mat.

The en cod ing in Fig ure D-8 is in ter preted as fol lows:

sign of num ber = 0 (pos i tive)

bi ased ex po nent = 10000101B = 133 dec i mal

real ex po nent = 133 - bias = 133 - 127 = 6

significand = 1.1111110 11000000 00000000 (add ing ex plicit digit)

significand is ad justed by mov ing the ra dix point six places

to the right

new significand = 1111111.01100...000

The significand bits are intepreted as fol lows::

in te ger part = 1111111 = 127

frac tional part = .01100..00 = .375

714 Ap pen dix D

Page 736: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

bit value: 11111110-11000000-00000000 = 16,695,296

|------| |---------------|

| |

| |________ frac tional part

|____________________ in te ger part

num ber: 127.375

D.5 Bi nary-Coded Dec i mals (BCD)Floating-point encodings are the most ef fi cient for mat for stor ing nu mer i cal data in adig i tal de vice, and bi nary arith me tic is the fast est way to per form nu mer i cal cal cu la -tions. But other rep re sen ta tions are also use ful. BCD (bi nary-coded dec i mal) is a wayof rep re sent ing dec i mal dig its in bi nary form. There are two com mon ways of en cod -ing dec i mal dig its in bi nary for mat. One is known as the packed BCD for mat and theother one as un packed. In the un packed for mat, each BCD digit is stored in one byte.In packed form, two BCD dig its are en coded per byte. The un packed BCD for mat doesnot use the four high-order bits of each byte, which is wasted stor age space. On theother hand, the un packed for mat fa cil i tates con ver sions and arith me tic op er a tions on some ma chines. Fig ure D.9 shows the mem ory stor age of a packed and un packed BCDnum ber.

Character Data 715

Fig ure D-8 En coding of the Num ber 127.375 in IEEE Sin gle For mat.

0 1 0 0 0 0 1 0

0 1 0 0 0 0 1 0

1 1 1 1 1 1 1 0

1 1 1 1 1 1 1 0

1 1 0 0 0 0 0 0

1 1 0 0 0 0 0 0

0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0

m m m m m m m m

e m m m m m m m

s e e e e e e e

m m m m m m m m

significandfield

implied leading digit

exponentfield

sign of numberfield

10000101 1.1111110 1100000 00000000

42H

42H

FEH

FEH

C0H

C0H

00H

00H

MEMORY LAYOUT OF 127.375IN LITTLE-ENDIAN FORMAT

MEMORY LAYOUT MAP FORIEEE SINGLE FORMAT

LOW ADDRESSLOW ADDRESS

HIGH ADDRESS

HIGH ADDRESS

16 17 18 19 20 21 22 23

8 1 2 3 4 5 6 7

1 2 3 4 5 6 7

8 9 10 11 12 13 14 15

legend:s = sign bite = exponent bitm = mantissa bit

Page 737: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure D-9 Packed and Un packed BCD.

D.5.1 Floating-Point BCDUn like the float ing-point bi nary num bers, bi nary-coded dec i mal rep re sen ta tions andBCD arith me tic have not been ex plic itly de scribed in a for mal stan dard. Each ma -chine or soft ware pack age stores and ma nip u lates BCD num bers in a unique and of tenin com pat i ble way. Some ma chines in clude packed dec i mal for mats, which aresign-magnitude BCD rep re sen ta tions. These in te ger for mats are use ful for con ver -sions and in put-output op er a tions. For per form ing arith me tic cal cu la tions, a float -ing-point BCD en cod ing is re quired. This ap proach pro vides all the ad van tages offloat ing point as well as the ac cu racy of dec i mal encodings.

The BCD float ing-point for mat that we call BCD12 is shown Fig ure D-10.

Fig ure D-10 Map of the BCD12 For mat.

BCD12 re quires 12 bytes of stor age and is de scribed as fol lows:

1. The sign of the num ber (S) is en coded in the leftmost packed BCD digit. There fore, the first four bits are ei ther 0000B (pos i tive num ber) or 0001B (neg a tive num ber).

2. The sign of the ex po nent is rep re sented in the four low-or der bits of the first byte.The sign of the ex po nent is also en coded in one packed BCD digit. As is the casewith the sign of the num ber field, the sign of the ex po nent is ei ther 0000B (pos i tiveex po nent) or 0001B (neg a tive ex po nent)

3. The fol low ing two bytes en code the ex po nent in four packed BCD dig its. The dec i -mal range of the ex po nent is 0000 to 9999.

4. The re main ing nine bytes are de voted to the significand field, con sist ing of eigh -teen packed BCD dig its. Pos i tive and neg a tive num bers are rep re sented with asignificand nor mal ized to the range 1.00...00 to 9.00...99. The dec i mal point fol low -

716 Ap pen dix D

0 0 0 0 1 0 0 1

0 0 0 0 0 1 1 1

0 0 0 0 0 0 1 1 0 1 1 1 1 0 0 1

0 0 0 0 0 0 1 0 0 0 1 0 0 0 1 1

9

7

3 79

2 23

UNPACKED BCD PACKED BCD

S s e e e e m m m m m m m m m m m m m m m m m mS s e e e e m m m m m m m m m m m m m m m m m m

sign o f exponent (1 B CD d igit)

sign o f number (1 B CD d igit)

exponent (4 B CD d igits)significand ( 18 B CD d igits)

Page 738: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

ing the first significand digit is im plied. The spe cial value 0 has an all-zerosignificand.

5. The spe cial value FF hex a dec i mal in the num ber’s sign byte in di cates an in validnum ber.

The struc ture of the BCD12 for mat is de scribed in Ta ble D.4.

Ta ble D.4

Field Struc ture of the BCD12 For mat

CODE FIELD NAME BITS WIDE BCD DIGITS RANGE

S Sign of num ber 4 1 0 – 1 (BCD) S Sign of ex po nent 4 1 0 – 1 (BCD) E Ex po nent 16 4 0 – 9999 M Significand 72 18 0 – 99..99 (18 dig its) ----- For mat size 96 (12 bytes)

Notes: 1. The significand is scaled (nor mal ized) to a num ber in the range 1.00..00 to 9.99..99. 2. The en cod ing for the value zero (0.00..00) is a spe cial case. 3. The spe cial value FFH in the sign byte in di cates an in valid num ber.

The BCD12 for mat, as is the case in all BCD encodings, does not make ideal useof the avail able stor age space. In the first place, each packed BCD digit re quiresfour bits, which in bi nary could serve to en code six ad di tional com bi na tions. At abyte level, the wasted space is of 100 encodings (BCD 0 to 99) out of a pos si ble 256(0 to FFH). The sign field in the BCD12 for mat is waste ful be cause only one bi narydigit is ac tu ally re quired for stor ing the sign. Re gard ing ef fi cient use of stor age,BCD for mats can not com pete with float ing-point bi nary encodings. The ad van tagesof BCD rep re sen ta tions are a greater ease of con ver sion into dec i mal forms, and the pos si bil ity of us ing the pro ces sors’ BCD arith me tic in struc tions.

Character Data 717

Page 739: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

This page intentionally left blankThis page intentionally left blank

Page 740: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Appendix E

Dig i tal Arith me tic and Con ver sions

E.1 Microcontroller Arith me tic

Microcontrollers are not de signed for in ten sive nu meric pro cess ing; there fore, theyare not equipped with many arith me tic op er a tors usu ally found in mi cro pro ces sors. Atyp i cal mid-range microcontroller has in struc tions to add and sub tract in te gers andper haps to in cre ment and dec re ment. Hard ware mul ti pli ca tion is rarely avail able andeven more rare is di vi sion. Like wise, there is usu ally no hard ware sup port for dec i maland float ing-point arith me tic. For this rea son the microcontroller pro gram mer is of -ten chal lenged to pro vide most arith me tic and data pro cess ing op er a tions in soft -ware.

In this dis cus sion we as sume a mid-range microcontroller, such as the PIC 16f8x.These de vices con tain prim i tives for add ing and sub tract ing in te gers, shift ing andro tat ing bits, in cre ment ing and dec re ment ing ma chine reg is ters, some sup port fordec i mal op er a tions and con ver sions, as well as the ba sic logic prim i tives AND, OR,XOR, and NOT. Mul ti pli ca tion and di vi sion op er a tors, as well as float ing-point op er -a tors, are not avail able in the mid-range de vices.

E.2 Un signed and Two’s Com ple ment Arith me tic

In Chap ter 3 we dis cussed the var i ous rep re sen ta tions for signed and un signed bi naryand dec i mal num bers. Arith me tic op er a tions of un signed operands are the sim plest.In this case we as sume that the en cod ing al ways rep re sents a pos i tive num ber and that all bits re late to the num ber’s mag ni tude.

Un signed arith me tic can be bi nary or dec i mal. In a ma chine with 8-bit words, bi -nary arith me tic on un signed num bers uses the en tire range of the for mat. This istrue even when the prim i tive op er a tions are valid in two’s com ple ment form; in fact, it is one of the great ad van tages of two’s com ple ment rep re sen ta tion. Ta ble E.1shows a 4-bit bi nary in sev eral nu meric for mats.

719

Page 741: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Ta ble E.1

In ter pre ta tions of 4-bit Bi nary Num bers

DECIMAL VALUES BINARY 1’S COMPLEMENT 2’S COMPLEMENT UNSIGNED

0111 7 7 70110 6 6 60101 5 5 50100 4 4 40011 3 3 30010 2 2 20001 1 1 10000 0 0 01111 -0 -1 151110 -1 -2 141101 -2 -3 13 1100 -3 -4 121011 -4 -5 111010 -5 -6 101001 -6 -7 91000 -7 -8 8

As sume a ma chine with a 4-bit word size and con sider ad di tion of two un signednum bers:

BINARY DECIMAL0111 7

+ 0110 6------ ----1101 13

Note, in the pre vi ous ex am ple, that if the en cod ing were in two’s com ple mentform, the ad di tion of the pos i tive val ues 6 plus 7 would pro duce a re sult that over -flows the ca pac ity of the rep re sen ta tion. In 4-bit two’s com ple ment rep re sen ta tion,there is no way of en cod ing the value 13.

The ques tion that arises is: In a de vice that per forms two’s com ple ment ad di tion,must we al ways as sume that the operands are in two’s com ple ment form? The an -swer is: No. Signed ad di tion of two’s com ple ment operands and the un signed ad di -tion of in te ger operands can be per formed with iden ti cal pro cess ing and by thesame elec tronic cir cuitry. It is the soft ware that must take into ac count the en cod -ing of the operands in or der to in ter pret the re sults. For ex am ple, in the 4-binarydigit de vice pre vi ously con sid ered, the two’s com ple ment ad di tion of the val ues 6and 7 pro duce an over flow, which can be de tected by ob serv ing the change in thehigh-order bit (the sign bit) of the re sult. There fore, in this case, the re sult of the ad -di tion op er a tion is in valid. How ever, if the same dec i mal val ues rep re sent un signedoperands, then the ad di tion of 7 plus 6 pro duces the valid re sult 13. In ei ther case,the bi nary val ues of the operands, as well as the re sult, are the same.

Microcontrollers usu ally sup port the fun da men tal op er a tions of ad di tion andsub trac tion on signed and un signed in te ger operands with a sin gle prim i tive op er a -tion. The ad di tion and sub trac tion op er a tors in low- and mid-range de vices al lowtwo operands. The more pow er ful microcontrollers sup port ad di tion and sub trac -

720 Ap pen dix E

Page 742: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

tion of three operands, which is use ful in im ple ment ing multi-digit rou tines. In ei -ther case, the soft ware de ter mines if the re sult is signed or un signed by in ter pret ingthe changes in the high-order bit of the operands and by eval u at ing the sta tus flags if these are avail able.

E.2.1 Op er a tions on Dec i mal Num bers

Al though microcontrollers are bi nary de vices, the in struc tion set of ten in cludes op er -a tions for per form ing arith me tic on bi nary coded dec i mal num bers. In Chap ter 3 wesaw that BCD num bers can be stored in packed or un packed form. In packed for mat,two BCD dig its are con tained in each byte. The low-order BCD digit takes up bits 0 to 3and the high-order BCD digit takes up bits 4 to 7. Un packed BCD dig its are stored onedigit per byte; in this case the high-order nib ble is un used. The packed and un packedbi nary coded dec i mal for mats can be seen in Fig ure 3-9.

Microcontroller de sign ers usu ally adopt the packed BCD for mat for rep re sent ingdec i mal operands. One ad van tage of packed BCDs is that the two dec i mal dig its en -coded in a sin gle byte can be rep re sented as hex a dec i mal dig its. For ex am ple, theval ues H24 and H99 rep re sent the packed BCD dig its 24 and 99, re spec tively. Notethat each hex digit is pre ceded by the let ter H to in di cate ra dix 16. In ac tualmicrocontroller pro gram ming, other ways are of ten used for rep re sent ing num bersin hex a dec i mal no ta tion.

The ad di tion and sub trac tion of dec i mal num bers rep re sented in packed BCD can be per formed with bi nary prim i tive op er a tions, com ple mented with some ad di tional ad just ments. In some cases the ad di tion of two BCD num bers in packed for mat maypro duce a valid re sult; for ex am ple

H23 H31 H56

+ H12 H38 H22

---- ---- ----

H35 H69 H78

In the pre vi ous ex am ples the re sults are valid be cause the sum of each digit doesnot ex ceed the range of the BCD for mat. How ever, the fol low ing ad di tions do notpro duce valid BCD re sults:

H33 H31 H56

+ H27 H59 H27

---- ---- ----

H5A H8A H7D

In the case of the first op er a tion, the valid BCD re sult would be 33 + 27 = 60; inthe sec ond one, 31 + 59 = 90; and in the third one, 56 + 27 = 83. A sim ple ad just mentcor rects the er ror, as fol lows:

Dig i tal Arith me tic and Con ver sions 721

Page 743: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

H33 H31 H56+ H27 H59 H27

--- --- ---H5A H8A H7D

+ H 6 H 6 H 6--- --- ---H60 H90 H83

In all three cases, add ing 6 to the pre vi ous sum pro duces the ex pected re sult. The logic for de cid ing when the value 6 must be added is sim ple: If the sum of thelow-order digit is greater than 9 or if the sum pro duced a carry out of the low-ordernib ble, then add 6 to the sum to per form the dec i mal ad just ment. Some high-endmicrocontrollers con tain a prim i tive in struc tion that ex e cutes the dec i mal ad just -ment au to mat i cally, that is, with out hav ing to test the sum. How ever, this in struc -tion is not avail able in low- and mid-range de vices.

Also note that the larg est num ber that can be en coded in packed BCD for mat isthe dec i mal 99. When add ing two BCD dig its, the high-order digit of the sum can notbe greater than 9. If so, then the ca pac ity of the for mat has been ex ceeded and there sult can not be ad justed by the sim ple ad di tion of 6. Here again, a multi-byte pro -cess ing rou tine can be de vel oped in or der to ac com mo date the re sult of BCD ad di -tion when the sum ex ceeds a sin gle byte.

Many microcontrollers are equipped with a flag that in di cates over flow from bi -nary digit num ber 3. This flag, some times called the digit carry or the half carryflag, can be used to de tect that a cal cu la tion has over flowed the stor age ca pac ity offour bi nary dig its. The avail abil ity of this flag sim pli fies the logic nec es sary for ad -just ing bi nary ad di tion of dec i mal operands be cause the value 6 must be addedwhen the digit in the low-or der nib ble is larger than 9, or when there has been acarry to the next digit. The flowchart in Fig ure E-1 shows this pro cess ing.

Fig ure E-1 Flowchart for Two-Byte BCD Ad di tion.

722 Ap pen dix E

START

END

ERROR

YES

YES

YES

NO

NO

NO

A = FIRST PACKED BCDB = SECOND PACKED BCDPERFORM C = A + B

C = C + 6LOW-ORDER NIBBLE> 9?

HIGH-ORDER NIBBLE> 9?

LOW-ORDER NIBBLEOVERFLOW

?

Page 744: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

E.3 Bit Ma nip u la tions and Aux il iary Op er a tionsIn ad di tion to ba sic logic and arith me tic, microcontrollers con tain prim i tive op er a -tors to ma nip u late in di vid ual bits, to com pare operands, to make de ci sions based onthe state of in di vid ual bits and flags, and to con vert data to other for mats. As al ways,the pres ence or ab sence of some of these op er a tions, as well as their de gree of powerand so phis ti ca tion, var ies with the in di vid ual microcontroller. In the fol low ing sub -sec tions we de scribe the most com monly avail able prim i tives.

E.3.1 Bit Shift and Ro tateThe fun da men tal op er a tors to shift and ro tate are use ful in de vel op ing BCD and bi -nary arith me tic rou tines. One in ter est ing use of bit shift ing is in im ple ment ing bi narymul ti pli ca tion and di vi sion rou tines.

Shift op er a tions con sist of trans pos ing to the left or right all the bits in the op er -and. In microcontrollers the op er and is usu ally a pro ces sor reg is ter. For ex am ple,af ter a right shift op er a tion, all the bits in the value 01110101B (75H) are moved onepo si tion to the right, re sult ing in the value 00111010B (3AH). Note that on a rightshift, the rightmost bit dis ap pears and a zero co mes into the high-order bit. By thesame to ken, in a left shift, the high-order bit dis ap pears and a zero co mes into thelow-order bit. Fig ure E-2 shows the ac tion of a left-shift op er a tion.

Fig ure E-2 Left Shift Op er a tion.

The ro tate op er a tion dif fers from the shift in that in the ro tate, the low-order bitis ei ther a copy of the high-order bit or of the carry flag. In the first case, the op er a -tion is a pure ro tate; in the sec ond case, the ro tate is re ferred to as ro -tate-through-carry. Fig ure E-3 shows the ac tion of a left-rotate-through-carry flag.

Fig ure E-3 Ro tate-through-carry Left Op er a tion.

Dig i tal Arith me tic and Con ver sions 723

7 6 5 4 3 2 1 0

7 6 5 4 3 2 1 0

0

BEFORE SHIFTlostbit

AFTER SHIFT

7 6 5 4 3 2 1 0

7 6 5 4 3 2 1 0

7 6 5 4 3 2 1 0

CF

CF

FIRST STEP

SECOND STEP

Page 745: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Note in Fig ure E-3 that the con tents of the carry flag are first cop ied to thelow-order bit of the des ti na tion op er and; then the in di vid ual bits of the source (ingray in the il lus tra tion) are shifted left and moved to the des ti na tion. Finally thehigh-order bit of the source is cop ied to the carry flag.

There are sev eral pos si ble vari a tions of the ro tate op er a tion. The Intel mi cro pro -ces sors dis tin guish be tween arith me tic and logic ro tates. In the arith me tic ro ta tionthe high-order bit is pre served in or der to main tain the sign of the op er and. The ro -tate shown in Fig ure E-3 is the one most com mon in microcontroller hard ware.Clear ing the carry flag be fore the ro tate takes place makes the op er a tion iden ti calto a shift.

E.3.2 Com par i son Op er a tionsAn in ter est ing prop erty of sub trac tion is its use in find ing the rel a tive size of twooperands. This in ter est ing ac tion of sub trac tion is based on the fol low ing logic:

1. If the re sult of a sub trac tion is zero, then both operands were of the same size.

2. If the re sult of a sub trac tion is a pos i tive num ber, then the sub tra hend was smallerthan the min u end.

3. If the re sult of a sub trac tion is a neg a tive num ber, the sub tra hend was larger thanthe min u end.

In a bi nary/dig i tal de vice the re sult of a sub trac tion op er a tion can be de ter minedby ob serv ing the flags. If the zero flag is set, then the operands were the same (case1, above). If the carry flag is set, then the sub tra hend was larger than the min u end(case 3, above). If nei ther the carry nor the zero flag is set, then the re sult ing sub tra -hend was smaller than the min u end (case 2, above). Be cause all microcontrollersof fer some mech a nism for re di rect ing ex e cu tion ac cord ing to the state of the flags,a pro gram can use sub trac tion to make these de ci sions.

The one ob jec tion to the use of sub trac tion in com par ing the size of two operands is that the pro cess will change one of them. To use sub trac tion in com par i son op er a -tions, the pro gram mer has to find some way of pre serv ing the min u end. Al ter na -tively, some de vices con tain a com par i son op er a tor that sets the flags as if asub trac tion had taken place but with out chang ing the operands. High-endmicrocontrollers are equipped with ded i cated com par i son op er a tors but the mid dle- and low-range de vices usu ally are not.

E.3.3 Other Sup port Op er a tions Mid- and high-range microcontrollers con tain other aux il iary bitwise, arith me tic, andlogic op er a tors that can be use ful to the pro gram mer. These in clude in struc tions to

1. In cre ment and dec re ment operands

2. Clear reg is ters or stor age lo ca tions

3. Swap nib bles

4. Clear and set in di vid ual bits

5. Test in di vid ual bits

724 Ap pen dix E

Page 746: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Usu ally, in struc tions to in cre ment and dec re ment and to test in di vid ual bits arealso ca pa ble of re di rect ing ex e cu tion ac cord ing to the re sult. For ex am ple, a spe cial dec re ment can be fol lowed by a jump if dec re ment ing sets the zero flag. Or a bit test in struc tion can in clude a jump that is taken if the tested bit is set or re set.

E.4 Un signed Bi nary Arith me ticBe cause microcontrollers are not used in data pro cess ing, microcontroller pro gram -ming does not usu ally re quire the de vel op ment of pow er ful or so phis ti cated nu mer i -cal rou tines. At the same time, be cause microcontrollers of ten lack prim i tive sup portfor even the most es sen tial cal cu la tions, the pro gram mer makes up for this de fi ciency. For ex am ple, mid-range PIC microcontrollers con tain prim i tive in struc tions forsigned and un signed ad di tion and sub trac tion of byte-size operands. Un signed ad di -tion and sub trac tion op er a tions that ex ceed one byte, as well as un signed mul ti pli ca -tion and di vi sion, must be pro vided in soft ware.

In un signed arith me tic, all bits of the bi nary en cod ing are in ter preted as mag ni -tude bits and all num bers are pos i tive. Ad di tion of un signed bi nary num bers is lim -ited by the ma chine’s word size. For ex am ple, a mid-range PIC microcontrollerper forms un signed ad di tion on 8-bit operands. An over flow of the sum is re portedby the carry flag set. In this case the carry flag clear in di cates that the sum is withinthe stor age ca pac ity of the for mat. In un signed arith me tic pro cess ing, rou tines forex tend ing op er a tions to mul ti ple bytes are straight for ward and rel a tively sim ple.

E.4.1 Multi-Byte Un signed Ad di tionMany microcontrollers are one-byte ma chines, so operands and re sults for arith me ticop er a tions must be con tained within eight bits. The larg est un signed value that can berep re sented in a sin gle byte is the dec i mal num ber 255. But of ten ap pli ca tions re quireadd ing operands that are larger than a sin gle byte and stor ing re sults that ex ceed thislimit. In these cases, multi-byte rou tines be come nec es sary.

The sim plest case is the ad di tion of two un signed byte-size operands whose sumex ceeds 255 dec i mal. This case re quires stor ing the re sult in a two-byte area and de -tect ing those cases in which there is a carry into the high-order byte. In this case the larg est pos si ble operands for byte ad di tion are the hex a dec i mal num bers FF. Ad di -tion is as fol lows:

Bi nary: 1 1 1 1 1 1 1 1 + 1 1 1 1 1 1 1 1 --------------- 1 1 1 1 1 1 1 0 C <=

In this ex am ple the sym bol C <= rep re sents a carry out of the high-order bit, thecase when the sum ex ceeds the ca pac ity of a sin gle byte. In hex a dec i mal, the sum of HFF + HFF = H1FE. You can add two byte-size operands into a two-byte stor agearea us ing byte ad di tion to de ter mine the low-order byte of the re sult and test ing for a carry out of the high-order bit. If there is a carry, then the high-order byte of the re -sult is 1; oth er wise the high-order byte is 0.

Dig i tal Arith me tic and Con ver sions 725

Page 747: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure E-4 Un signed Multi-Byte Ad di tion.

The same logic can be gen er al ized to add more than two byte-size operands aslong as the stor age area for the re sult ex ceeds the size of the operands by one byte.For ex am ple, two word-size operands (16 bits each) can be added into a 3-byte(24-bit) stor age area, or two dou ble-word operands (32 bits) into a 5-byte stor agearea. The gen eral al go rithm for multi-byte ad di tion is shown in Fig ure E-4.

The case shown in Fig ure E-4 con sists of add ing two 4-byte operands into a5-byte sum. The ad di tion of the first two operands as sumes that there is no carry. Inthe re main ing stages there can be a pos si ble carry from the pre vi ous stage if thesum of the two byte-size operands, plus the pre vi ous carry, ex ceed the stor age ca -pac ity of eight bits. The last byte of the re sult is de ter mined solely by the pos si blecarry from the pre vi ous stage.

In Fig ure E-4 we see that multi-byte ad di tion re quires the sum of three val ues inall stages ex cept the first and the last one. Some high-end microcontrollers have ad -di tion op er a tors that ac cept a three-byte op er and. Oth ers have spe cial ad di tionopcodes that au to mat i cally add-in the carry flag. The lat ter op er a tors are re ferred to as add-with-carry. How ever, in most low- and mid-range de vices, the soft ware must take care of in cre ment ing the sum if there is a carry from the pre vi ous stage. The ac -tual multi-byte ad di tion rou tines are de vel oped in the con text of pro gram ming thevar i ous microcontrollers, dis cussed later in this book.

E.4.2 Un signed Mul ti pli ca tionThe case for mul ti pli ca tion can not be gen er al ized be cause high-end microcontrollersusu ally con tain one or more mul ti pli ca tion op er a tors; this is not the case in low- and

726 Ap pen dix E

first 4-byteoperand

second 4-byteoperand

5-byteresult

possiblecarry

+

+

+

+

+

+

+

+

+

=

=

=

=

=

0

0/1

0/1

0/1

0/1

Page 748: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

mid-range de vices. In the first case im ple men ta tion is sim ply by us ing the cor re spond -ing op er a tor. This sec tion ex plains mul ti pli ca tion in de vices that lack a ded i cated mul -ti pli ca tion op er a tion code.

Arith me tically, mul ti pli ca tion is per formed by re peated ad di tion. The mul ti plierrep re sents the num ber of times that the mul ti pli cand must be added to it self. There -fore, 3 times 4 is the same as 3 + 3 + 3 + 3. This fact al lows im ple ment ing mul ti pli ca -tion rou tines in soft ware as long as the de vice con tains an ad di tion op er a tor. Thelogic is based on us ing the mul ti plier as a coun ter. This coun ter is dec re ment ed each time the mul ti pli cand is added to it self. The rou tine ends when the coun ter is ex -hausted, as shown in the flowchart in Fig ure E-5.

Fig ure E-5 Un signed Mul ti pli ca tion Flowchart.

The beauty of the re peated ad di tion al go rithm is its sim plic ity, and its main short -com ing is its slow ness. An al ter na tive way of per form ing mul ti pli ca tion is by shift -ing the bits of the op er and. This method is based on the prop er ties of a bi narypo si tional sys tem in which the value of each digit is a suc ces sive power of 2. There -fore, by shift ing all dig its to the left, the value 0001B (1 dec i mal) suc ces sively be -comes 0010B (2 dec i mal), 0100B (4 dec i mal), 1000B (8 dec i mal), and so on.

Bi nary mul ti pli ca tion by means of bit shift ing has the down side that the mul ti -plier must be a power of 2. Oth er wise, the soft ware must shift by a power of 2 that is smaller than the mul ti plier and then add the mul ti plier as many times as nec es saryto com plete the prod uct. In this man ner, to mul ti ply by 5, we can shift left twice andadd once the value of the mul ti pli cand. To mul ti ply by 7, we would shift left twiceand then add three times the value of the mul ti pli cand. As the mul ti plier gets largerand more dis tant from the smaller power of 2, the num ber of ad di tion op er a tions re -quired is also larger, and the ef fec tive ness of the al go rithm di min ishes.

Dig i tal Arith me tic and Con ver sions 727

START

DONEYES

YES

NO

A = MULTIPLICANDB = MULTIPLIER

PERFORM P = A * BP (PRODUCT) = 0C (COUNTER) = B

P = P + AC = C - 1

COUNTER = 0?

Page 749: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

A third ap proach is based on the ma nip u la tions per formed dur ing long hand mul ti -pli ca tion. For ex am ple, the mul ti pli ca tion of 00101101B (45 dec i mal) by 01101101B(109 dec i mal) can be ex pressed as a se ries of prod ucts and shifts, in the fol low ingman ner:

0 0 1 0 1 1 0 1 B = 45 dec i mal

times 0 1 1 0 1 1 0 1 B = 109 dec i mal

-----------------

0 0 1 0 1 1 0 1

0 0 0 0 0 0 0 0

0 0 1 0 1 1 0 1

0 0 1 0 1 1 0 1

0 0 0 0 0 0 0 0

0 0 1 0 1 1 0 1

0 0 1 0 1 1 0 1

0 0 0 0 0 0 0 0

-------------------------------

0 0 1 0 0 1 1 0 0 1 0 1 0 0 1 B = 4905 dec i mal

The ac tual cal cu la tions in this method of bi nary mul ti pli ca tion are quite sim plebe cause the prod uct by a 0 digit is zero and the prod uct by a 1 digit is the mul ti pli -cand it self. Con se quently, the mul ti pli ca tion rou tine sim ply tests each digit in themul ti plier. If the digit is zero, no ac tion need be per formed; if the digit is one, themul ti pli cand is shifted left and added into an ac cu mu la tor.

The stor age al lo ca tion to hold the prod uct of a mul ti pli ca tion op er a tion is not thesame as that to hold the sum. In multi-byte ad di tion, one ad di tional byte is re quiredto hold the sum. In mul ti pli ca tion, the stor age al lo ca tion must be twice the size ofthe operands. For ex am ple, byte mul ti pli ca tion re quires a two-byte stor age, whilemul ti ply ing two dou ble-byte operands re quires a four-byte stor age al lo ca tion.

E.4.3 Un signed Di vi sion

If mul ti pli ca tion can be re duced to re peated ad di tion, then di vi sion can be con cep tu al -ized as re peated sub trac tion. In the case of di vi sion, the quo tient (re sult) is the num -ber of times the di vi sor must be sub tracted from the div i dend be fore zero or a neg a tive value re sults from the sub trac tion. The flowchart in Fig ure E-6 shows the logic stepsin un signed di vi sion.

In Fig ure E-6 note that the logic tests for a zero di vi sor, as di vi sion by zero ismath e mat i cally un de fined. Also, be cause the op er a tion is un signed, the re sult can -not be neg a tive; there fore, the di vi sor must be larger than the div i dend. Finally, thelogic must con sider the case in which sub tract ing the di vi sor from the re mainderpro duces a neg a tive value, in which case an ad just ment is nec es sary to pro duce avalid quo tient. This ad just ment avoids the need for search ing for a trial di vi sor, as in the case of the com mon long hand di vi sion al go rithm. In ma chine code, the neg a tivere sult is de tected as an over flow (carry flag set) from the sub trac tion.

728 Ap pen dix E

Page 750: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure E-6 Un signed Di vi sion Flowchart.

E.5 Signed Bi nary Arith me ticIn two’s com ple ment and sign-magnitude rep re sen ta tions, the high-order bit rep re -sents the sign of the op er and, while its mag ni tude is rep re sented in the re main ing bits.There fore, in the case of signed num bers, a carry out of the high-order bit is mean ing -less be cause the high-order bit is not a mag ni tude bit. For ex am ple, con sider the fol -low ing op er a tion in an 8-bit de vice that per forms un signed and two’s com ple mentad di tion:

80 = 0101 0000B

+ 90 = 0101 1010B

------------------

170 = 1010 1010B

If the operands are as sumed to be in un signed bi nary for mat, the re sult is valid.How ever, if the operands (the dec i mal val ues 80 and 90) are as sumed to be pos i tivenum bers in two’s com ple ment form, then the re sult is in valid be cause the pos i tivenum ber 170 can not be rep re sented in an 8-bit two’s com ple ment en cod ing.

Dig i tal Arith me tic and Con ver sions 729

START

DONE

ERROR

YES

YES

YES

YES

NO

NO

NO

A = DIVIDENDB = DIVISOR

PERFORM Q = A / BQ (QUOTIENT) = 0R (REMAINDER) = A

Q = Q - 1R = R + B

R = R - BQ = Q + 1

REMINDER < 0?

REMINDER = 0?

DIVISOR = 0?

DIVIDEND <DIVISOR

?

Page 751: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Clearly, multi-byte op er a tions on signed rep re sen ta tions can not be per formediden ti cally as with un signed operands. Ta ble E.2 shows the un signed and two’s com -ple ment rep re sen ta tions of one-byte num bers.

Ta ble E.2

Signed and Un signed Rep re sen ta tions of One-Byte Num bers

BINARY 2’S COMPLEMENT UNSIGNED

0000 0000 0 00000 0001 1 10000 0010 2 20000 0011 3 3

. . . . . . . . .0111 1111 127 1271000 0000 –128 1281000 0001 –127 1291000 0010 –126 1301000 0011 –125 131 . . . . . .1111 1110 –2 2541111 1111 –1 255

E.5.1 Over flow De tec tion in Signed Arith me ticIn un signed ad di tion, the carry flag is mag ni tude re lated. It is set when there is a carryout of the high-order bit of the des ti na tion op er and, which takes place when its ca pac -ity has been ex ceeded. This is usu ally de scribed as an over flow con di tion. How ever, acarry out of the high-order bit of the re sult is not al ways mean ing ful in signed arith me -tic. For ex am ple, sup pose the fol low ing two’s com ple ment ad di tion:

Dec i mal bi nary 127 0111 1111 + 127 0111 1111 ---- --------- ?? 1111 1110

In this case the sum clearly ex ceeds the ca pac ity of the for mat, be cause the larg -est pos i tive value that can be rep re sented in a two’s com ple ment 8-bit for mat is 127(see Ta ble E.2). How ever, the op er a tion did not gen er ate a carry out of thehigh-order bit. There fore, the carry flag could not have been used to de tect the over -flow er ror in this case.

Now con sider the ad di tion of two neg a tive num bers in two’s com ple ment form:

Dec i mal bi nary -4 1111 1100

+ -5 1111 1011 ---- --------- -9 C <= 1111 0111

In this case, the ad di tion op er a tion gen er ated a carry out of the high-order bit;how ever, the sum is ar ith met i cally cor rect. In fact, any ad di tion of neg a tive

730 Ap pen dix E

Page 752: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

operands in two’s com ple ment no ta tion gen er ates a carry out of the most-sig nif i -cant bit.

These two ex am ples show that the carry flag, by it self, can not be used to de tectan er ror or no-error con di tion in two’s com ple ment arith me tic. De tecting an over -flow con di tion in two’s com ple ment rep re sen ta tions re quires ob serv ing the carryinto the high-order bit of the en cod ing as well as the carry out. In both pre vi ous ex -am ples we note that there was a carry into the high-order bit of the re sult. How ever,in the first case, there was no carry out. The gen eral rule is: two’s com ple ment over -flow takes place when the carry into and the carry out of the high-order bit haveop po site val ues. Fig ure E-7 is a flowchart to de tect over flow in signed arith me tic.

Fig ure E-7 De tecting Over flow in Two’s Com ple ment Arith me tic.

Most mi cro pro ces sors and some high-end microcontrollers con tain hard ware fa -cil i ties for de tect ing signed arith me tic over flow. In some cases the hard ware sup -port con sists of a sin gle over flow flag that is set when ever the re sult of anarith me tic op er a tion ex ceeds the ca pac ity of the for mat. In other cases, as in thePIC 18CXX2 fam ily, the sta tus reg is ter con tains a neg a tive bit flag that in di cates a1-bit in the sign bit po si tion, as well as an over flow bit that is set when ever there isan over flow from the mag ni tude bits (0 to 6) into the sign bit (bit 7) of the des ti na -tion op er and. In this de vice, soft ware can test one or both of these flags to de tecttwo’s com ple ment over flow.

In low- and mid-range de vices, with no hard ware sup port for signed arith me tic,de tect ing a two’s com ple ment over flow is by no means sim ple. With out a hard wareflag to re port a carry con di tion into a par tic u lar bit po si tion, soft ware is con frontedwith sev eral pos si ble al ter na tives, but none is sim ple or straight for ward.

Dig i tal Arith me tic and Con ver sions 731

START

OVERFLOW

NOOVERFLOW

YES

YES

YESNO

NO

NO

A = FIRST SIGNED ADDENDB = SECOND SIGNED ADDEND

PERFORM C = A + B

CARRY OUTOF BIT 7

?

CARRY INTOBIT 7

?

CARRY OUTOF BIT 7

?

Page 753: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

E.5.2 Sign Ex ten sion Op er a tionsOb serving the carry into and the carry out of the most-sig nif i cant bit is a valid way ofde tect ing over flow of a two’s com ple ment arith me tic op er a tion. In the ory, the logicde scribed in the flowchart of Fig ure E-7 can be im ple mented in de vices with out hard -ware sup port for signed over flow; how ever, the pro cess ing is com pli cated and there -fore costly in ex e cu tion time. An al ter na tive ap proach is to en sure that the for mat hassuf fi cient ca pac ity to store the arith me tic re sult. The rule de vel oped pre vi ously lets us de ter mine that, for ad di tion and sub trac tion, the des ti na tion for mat must have at least one more byte than the operands. In mul ti pli ca tion, the des ti na tion op er and must beat least twice the size of the source operands.

A sim ple mech a nism for ex tend ing the ca pac ity of two’s com ple ment en cod ing iscalled sign ex ten sion. The pro cess con sists of copy ing the sign bit into thehigh-order bit po si tions of the ex tended en cod ing. For ex am ple, to ex tend a two’scom ple ment 8-bit num ber into 16 bits, copy the sign bit of the orig i nal value (bitnum ber 7) into all the bits of the ex tended byte. The pro cess is shown in Fig ure E-8for both pos i tive and neg a tive operands.

Fig ure E-8 Sign Ex ten sion of Two’s Com ple ment Num bers.

E.5.3 Multi-byte Signed Op er a tionsSigned op er a tions on two’s com ple ment num bers en coded in mul ti ple bytes can beper formed us ing the pro ces sor’s arith me tic prim i tives. Con sider the ad di tion of thenum bers –513 and –523, each one en coded in 16-bit two’s com ple ment form:

dec i mal bi nary HOB LOB

-513 1111 1101 1111 1111-523 1111 1101 1111 0101----- ---------------------

732 Ap pen dix E

1 0 1 1 1 1 0 0

0 0 1 1 1 1 0 0

1 1 1 1 1 1 1 1

0 0 0 0 0 0 0 0

1 0 1 1 1 1 0 0

0 0 1 1 1 1 0 0

Sign extension ofa negative number

Sign extension ofa positive number

Extendedbit

Extendedbit

Page 754: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

-1036 1111 1011 1111 0100

In the pre ced ing ex am ple, add ing the low-order bytes pro duces the sum shown,plus a carry. Adding the high-order bytes plus the carry, and dis card ing the over flow, pro duces the sum of high-order bytes shown above. The re sult is the cor rect valuein two’s com ple ment form. The fact that the re sult did not over flow the ca pac ity ofthe 16-bit for mat can be as cer tained by ob serv ing that there was a carry into the fif -teenth digit, and also a carry out. Carry in and carry out of the sign bit is one of thecon di tions for no over flow in the flowchart of Fig ure E-7.

E.6 Data For mat Con ver sionsQuite of ten, code needs to con vert data into and from dif fer ent nu meric for mats, forex am ple, to dis play ASCII dig its in an out put de vice, or to con vert nu meric key boardin put in ASCII into bi nary or BCD encodings for pro cess ing. In this sec tion we con -sider the logic for the fol low ing cases:

1. BCD dig its to ASCII decimal

2. Bi nary to string of ASCII dec i mal dig its

3. String of ASCII dec i mal dig its to bi nary

4. Bi nary to string of ASCII hex a dec i mal dig its

As in the pre vi ous cases, im ple men ta tion of these con ver sions is de vice de pend -ent and var ies in the dif fer ent hard ware.

E.6.1 BCD Digits to ASCII Dec i malPacked BCD dig its are en coded in one digit per nib ble, as shown in Sec tion E.2.1.Thus, each digit is a bi nary value in the range 0 to 9. Con verting each digit to ASCII con -sists of iso lat ing each nib ble and then chang ing the bi nary into an ASCII rep re sen ta -tion. Note in Ta ble E.1 that the nu meric ASCII dig its start at 30H for the digit zero andex tend to 39H for the digit 9. For this rea son, con vert ing a nu meric digit from bi nary toASCII con sists of add ing 30H. By the same to ken, sub tract ing 30H con verts a sin gleASCII digit to bi nary.

As sume four packed BCD dig its in two con sec u tive mem ory bytes, la beled A andB, where A holds the two low-order dig its; also, a four-digit stor age buffer to whichthe vari able P is a pointer. The con ver sion al go rithm can be de scribed as fol lows:

1. Ini tial ize buffer pointer P to the first stor age lo ca tion.

2. Copy digit A to tem po rary digit T.

3. Mask out four high-or der bits of T.

4. Add 30H to value in T and store in buffer by pointer P.

5. Bump buffer pointer to next digit stor age.

6. Copy digit A to tem po rary digit T.

7. Mask out four low-or der bits in T.

8. Shift four high-or der bits to the right by 4 bits.

Dig i tal Arith me tic and Con ver sions 733

Page 755: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

9. Add 30H to value in T and store in buffer by pointer P.

10. Bump buffer pointer to next digit.

11. Pro ceed with digit B in the same man ner.

E.6.2 Un signed Bi nary to ASCII Dec i mal DigitsOf ten we hold an un signed bi nary num ber in mem ory or a ma chine reg is ter and needto dis play its value to some ASCII-based out put de vice. The pro cess re quires con vert -ing the bi nary value to a string of ASCII dec i mal dig its. The num ber of dec i mal dig itsde pends on the num ber of bits in the bi nary rep re sen ta tion. A one-byte un signed bi -nary re quires three ASCII dec i mal dig its be cause the value ranges from 0 to 255. Atwo-byte un signed bi nary re quires a string of five ASCII dec i mal dig its be cause therange of a two-byte rep re sen ta tion is from 0 to 65,535, and so on. The stor age area forthe ASCII dig its is some times re ferred to as a buffer.

The pro cess of con vert ing bi nary to ASCII dec i mal con sists of di vid ing the bi naryby 10 to ob tain each dec i mal digit, then add ing 30H to the re mainder in or der to turn the digit into ASCII. The pro cess con tin ues un til the orig i nal div i dend is re duced tozero, as shown in the flowchart of Fig ure E-9.

Fig ure E-9 Un signed Bi nary to ASCII Dec i mal String.

E.6.3 ASCII Dec i mal String to Un signed Bi nary

An other con ver sion op er a tion fre quently needed in soft ware is the trans for ma tion ofa string of ASCII dec i mal dig its into bi nary. This type of con ver sion typ i cally ariseswhen the pro gram needs to re ceive in put that must later be pro cessed by the de vice.For ex am ple, the user en ters a nu meric value from a key board and the ap pli ca tionmust pro cess this data in bi nary form.

734 Ap pen dix E

START

DONEYES

NO

B = BINARY NUMBERR (REMAINDER) = 0

BUFFER to HOLD ASCII DIGITSP = BUFFER POINTER

INIT TO LOWEST SIGNIFICANT DIGIT

B = B / 10DIGIT = R + 30HSTORE DIGIT BY P

UPDATE P TO NEXT DIGIT

B = 0?

Page 756: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

In de sign ing the con ver sion rou tine we must first de limit the value range of thein put data so as to al lo cate a suf fi ciently large bi nary for mat to store the re sult. Forex am ple, code can store in a sin gle un signed byte a bi nary in the range 0 to 255, butit re quires two bytes to store one in the range 0 to 65,535. Once the bi nary stor agesize is de ter mined, the con ver sion logic is based on con vert ing each ASCII digit tobi nary, high-to-low, and add ing its value to a pre vi ous sum mul ti plied by 10. Theflowchart in Fig ure E-10 de scribes the con ver sion logic.

Fig ure E-10 Dec i mal String to Un signed Bi nary.

The logic in the flowchart of Fig ure E-10 as sumes that there is some way of de -tect ing the end of the string of ASCII dig its. This could be a ter mi na tor char ac terem bed ded in the string or a coun ter for the num ber of dig its. Here again we use abuffer pointer that is in i tial ized to the least-sig nif i cant digit in the ASCII string. TheASCII digit is con verted to bi nary by sub tract ing 30H and then added to the pre vi ous sum, mul ti plied by 10. For ex am ple, as sume the ASCII string of the dec i mal dig its564.

STRING = ‘564’

FIRST ITERATION:

STEP 1: B = 0

Dig i tal Arith me tic and Con ver sions 735

START

DONEYES

NO

B = BINARY NUMBERA = ASCII DECIMAL DIGIT

BUFFER HOLDS ASCII DIGITSP = BUFFER POINTER

INIT TO HIGHEST SIGNIFICANT DIGIT

A = A - 30HB = (B * 10) + A

UPDATE P TO NEXT DIGIT

A = DIGIT => BY P

END OFASCII STRING

?

Page 757: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

P => HIGH DIGIT IN STRING ‘564’STEP 2: A = ‘5’STEP 3: END OF STRING? NOSTEP 4: A = 4 (‘5’ – 30H = 5) B = (0 * 10) + A = 5 P TO NEXT LOWER DIGITSECOND ITERATION:STEP 2: A = ‘6’STEP 3: END OF STRING? NOSTEP 4: A = 6 (‘6’ – 30H = 6) B = (5 * 10) + A = 56 P TO NEXT LOWER DIGITTHIRD ITERATION:STEP 2: A = ‘4’STEP 3: END OF STRING? NOSTEP 4: A = 4 (‘4’ – 30H = 4) B = (56 * 10) + A = 564 P TO NEXT LOWER DIGITFOURTH ITERATION:STEP 2: A = ??STEP 3: END OF STRING? YESRESULT: B = 564

E.6.4 Un signed Bi nary to ASCII Hex a dec i mal DigitsCon verting a bi nary num ber to a string of ASCII hex dig its is quite sim i lar to con vert -ing from bi nary to an ASCII dec i mal string, as de scribed in Sec tion E.6.2. Here again,the digit space to al lo cate for the ASCII string de pends on the size of the bi nary op er -and. An 8-bit bi nary is rep re sented in two ASCII hex dig its, a 16-bit bi nary in four ASCII hex dig its, and so on.

The pro cess of con vert ing bi nary to ASCII hex a dec i mal con sists of di vid ing thebi nary by 16 to ob tain each hex digit. If the re main ing hex a dec i mal digit is in therange 0 to 9 we add 30H to turn it into the cor re spond ing ASCII digit. If it is in therange A to F, then we must add 40H to con vert to ASCII. The pro cess con tin ues un tilthe orig i nal div i dend is re duced to zero, as shown in the flowchart of Fig ure E-11.

E.6.5 Signed Nu mer i cal Con ver sionsCon ver sion rou tines that use signed operands are usu ally a vari a tion of the un signedones de scribed in pre vi ous sec tions. Al though logic can be de vel oped that di rectly en -codes to and from two’s com ple ment for mat, the more con ve nient ap proach is to de -ter mine the sign of the op er and and then use un signed con ver sion for the digit val ues.For ex am ple, to con vert a signed bi nary in two’s com ple ment form into a string ofASCII dec i mal dig its, the logic first de ter mines if the bi nary op er and is neg a tive orpos i tive. If a pos i tive num ber, then the un signed con ver sion rou tine can be used di -rectly. If the bi nary op er and is a neg a tive num ber, the – sign is placed in the stor agebuffer. Then the two’s com ple ment bi nary is con verted to an un signed num ber so thatthe ASCII dig its can be ob tained with the con ver sion rou tine de scribed in Sec tionE.6.2.

736 Ap pen dix E

Page 758: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure E-11 Un signed Bi nary to ASCII Hex a dec i mal String.

Dig i tal Arith me tic and Con ver sions 737

START

DONEYES

YES

NO

NO

B = BINARY NUMBERR (REMAINDER) = 0

BUFFER TO HOLD ASCII HEX DIGITSP = BUFFER POINTER

INIT TO LOWEST SIGNIFICANT DIGIT

R = R + 30H

PERFORM B = B / 16R = REMAINDER

R = R + 40H

STORE R (DIGIT) BY PUPDATE P TO NEXT DIGIT

B = 0?

0 =< R =< 9?

Page 759: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

This page intentionally left blankThis page intentionally left blank

Page 760: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Ap pen dix F

Mid-Range In struc tion Set

This appendix de scribes the in struc tions in the PIC mid-range fam ily. Not all in struc -tions are im ple mented in all de vices but all of them work in the spe cific PICs dis -cussed in the text, that is, the 16F84A and the 16F877.

Ta ble F.1

Mid-Range PIC In struc tion Set

BITS MNEMONIC OPERAND DESCRIPTION CYCLES AFFECTED

BYTE-ORIENTED OPERATIONS:ADDWF f,d Add w and f 1 C,DC,ZANDWF f,d AND w with f 1 ZCLRF f Clear f 1 ZCLRW - Clear w 1 ZCOMF f,d Com ple ment f 1 ZDECF f,d Dec re ment f 1 ZDECFSZ f,d Dec re ment, skip if 0 1(2) -INCF f,d In cre ment f 1 ZINCFSZ f,d In cre ment, skip if 0 1(2) -IORWF f,d In clu sive OR w and f 1 ZMOVF f,d Move f 1 ZMOVWF f Move w to f 1 -NOP - No op er a tion 1 -RLF f,d Ro tate left through carry 1 CRRF f,d Ro tate right through carry 1 CSUBWF f,d Sub tract w from f 1 C,DC,ZSWAPF f,d Swap nib bles in f 1 -XORWF

BIT-ORIENTED OPERATIONSBCF f,b Bit clear in f 1 -BSF f,b Bit set in f 1 -BTFSC f,b Bit test, skip if clear 1 -BTFSS f,b Bit test, skip if set 1 -

LITERAL AND CONTROL OPERATIONSADDLW k Add lit eral and w 1 C,DC,Z

(con tin ues)

739

Page 761: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Ta ble F.1

Mid-Range PIC In struc tion Set (con tin ued)

BITS MNEMONIC OPERAND DESCRIPTION CYCLES AFFECTED

LITERAL AND CONTROL OPERATIONSANDLW k AND lit eral and w 1 ZCALL k Call pro ce dure 2 -CLRWDT - Clear Watch dog timer 1 TO,PDGOTO k Go to ad dress 2 -IORLW k In clu sive OR lit eral with w 1 ZMOVLW k Move lit eral to w 1 -RETFIE - Re turn from in ter rupt 2 -RETLWk - Re turn lit eral in w 2 -RETURN - Re turn from pro ce dure 2 -SLEEP - Go into SLEEP mode 1 TO,PDSUBLW k Sub tract lit eral and w 1 C,DC,ZXORLW k Ex clu sive OR lit eral 1 Z

with w

Leg end:f = file reg is terd = des ti na tion: 0 = w reg is ter

1 = file reg is terb = bit po si tionk = 8-bit con stant

740 Ap pen dix F

Page 762: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Ta ble F.2

Con ven tions used in In struc tion De scrip tions

FIELD DESCRIPTION

f Reg is ter file ad dress (0x00 to 0x7F)w Working reg is ter (ac cu mu la tor)b Bit ad dress within an 8-bit file reg is ter (0 to 7)k Lit eral field, con stant data or la bel (may be ei ther an 8-bit or an

11-bit value)x Don't care (0 or 1)d Des ti na tion se lect;

d = 0: store re sult in w,d = 1: store re sult in file reg is ter f.

dest Des ti na tion ei ther the w reg is ter or the spec i fied reg is ter filelo ca tion

label La bel nameTOS Top of StackPC Pro gram Coun terPCLATH Pro gram Coun ter High LatchGIE Global In ter rupt En able bitWDT Watch dog Timer!TO Time-out bit!PD Power-down bit[ ] Op tional el e ment

[XXX] Con tents of mem ory lo ca tion pointed at by XXX register( ) Con tents-> As signed to< > Reg is ter bit fieldital ics User de fined term

Mid-Range In struc tion Set 741

Page 763: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

ADDLW Add Lit eral and w

Syn tax: [la bel] ADDLW kOp er ands: k in range 0 to 255Op er a tion: (w) + k -> wSta tus Af fected: C, DC, ZDe scrip tion: The con tents of the w reg is ter are added to

the eight bit lit eral k and the re sult isplaced in the w reg is ter

Words: 1Cycles: 1

Example1:

ADDLW 0x15Be fore In struc tion: w = 0x10

Af ter In struc tion: w = 0x25

Ex am ple 2:

ADDLW var1Be fore In struc tion: w = 0x10

var1 is data memory variable

var1 = 0x37

Af ter In struc tion: w = 0x47

742 Ap pen dix F

Page 764: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

ADDWF Add w and f

Syn tax: [ la bel ] ADDWF f,dOp er ands: f in range 0 to 127

d = 0 / 1Op er a tion: (w) + (f) -> des ti na tionSta tus Af fected: C, DC, ZDe scrip tion: Add the con tents of the w reg is ter with

reg is ter f. If d is 0 the re sult is stored inthe w reg is ter. If d is 1 the re sult is storedback in reg is ter f.

Words: 1Cycles: 1

Ex am ple 1:

ADDWF FSR,0Be fore In struc tion:

w = 0x17FSR = 0xc2

Af ter In struc tion:W = 0xd9FSR = 0xc2

Ex am ple 2:

ADDWF INDF, 1Be fore In struc tion:

w = 0x17FSR = 0xC2Con tents of Ad dress (FSR) = 0x20

Af ter In struc tion:W = 0x17FSR = 0xC2Con tents of Ad dress (FSR) = 0x37

Mid-Range In struc tion Set 743

Page 765: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

BCF Bit Clear f

Syn tax: [ la bel ] BCF f,bOp er ands: f in range 0 to 127

b in range 0 to 7Op er a tion: 0 ->f<b>Sta tus Af fected: NoneDe scrip tion: Bit 'b' in reg is ter f is cleared.Words: 1Cycles: 1

Ex am ple 1:

BCF reg1,7Be fore In struc tion: reg1 = 0xc7 (1100 0111)Af ter In struc tion: reg1 = 0x47 (0100 0111)

Ex am ple 2:

BCF INDF,3Be fore In struc tion: w = 0x17

FSR = 0xc2[FSR]= 0x2f

Af ter In struc tion:w = 0x17FSR = 0xc2[FSR] = 0x27

744 Ap pen dix F

Page 766: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

BSF Bit Set f

Syn tax: [ la bel ] BSF f,bOp er ands: f in range 0 to 127

b in range 0 to 7Op er a tion: 1-> f<b>Sta tus Af fected: NoneDe scrip tion: Bit 'b' in reg is ter f is set.Words: 1Cycles: 1Ex am ple 1:

BSF reg1,6Be fore In struc tion: reg1 = 0011 1010Af ter In struc tion: reg1 = 0111 1010

Ex am ple 2:

BSF INDF,3Be fore In struc tion: w = 0x17

FSR = 0xc2[FSR] = 0x20

Af ter In struc tion:w = 0x17FSR = 0xc2[FSR] = 0x28

Mid-Range In struc tion Set 745

Page 767: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

BTFSC Bit Test f, Skip if Clear

Syn tax: [ la bel ] BTFSC f,bOp er ands: f in range 0 to 127

b in range 0 to 7Op er a tion: skip next in struc tion if (f<b>) = 0Sta tus Af fected: NoneDe scrip tion: If bit b in reg is ter f is 0 then the next

in struc tion is skipped. If bit b is 0 then thenext in struc tion (fetched dur ing the cur rentinstruction ex e cu tion) is dis carded, and a NOPis ex e cuted in stead, mak ing this a 2-cy clein struc tion.

Words: 1Ex am ple :

repeat:btfsc reg1,4goto repeat

Case 1: Be fore In struc tionPC = $ reg1 = xxx0 xxxx

Af ter In struc tionbecause reg1<4>= 0,PC = $ + 2 (goto skipped)

Case 2: Be fore In struc tionPC = $reg1= xxx1 xxxx

Af ter In struc tionbecause FLAG<4>=1,PC = $ + 1 (goto executed)

746 Ap pen dix F

Page 768: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

BTFSS Bit Test f, Skip if Set

Syn tax: [ la bel ] BTFSC f,bOp er ands: f in range 0 to 127

b in range 0 to 7Op er a tion: skip next in struc tion if (f<b>) = 1Sta tus Af fected: NoneDe scrip tion: If bit b in reg is ter f is 1 then the next

in struc tion is skipped. If bit b is 0 then thenext in struc tion (fetched dur ing the cur rentin struc tion ex e cu tion) is dis carded, and a NOPis ex e cuted in stead, mak ing this a 2-cy clein struc tion.

Words: 1Cycles: 1(2)

repeat:btfss reg1,4goto repeat

Case 1: Be fore In struc tionPC = $ Reg1 = xxx1 xxxx

Af ter In struc tionbecause Reg1<4>= 1,PC = $ + 2 (goto skiped)

Case 2: Be fore In struc tionPC = $Reg1 = xxx0 xxxx

Af ter In struc tionbecause Reg1<4>=0,PC = $ + 1 (goto executed)

Mid-Range In struc tion Set 747

Page 769: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

CALL Call Sub-Rou tine

Syn tax: [ la bel ] CALL kOp er ands: k in range 0 to 2047Op er a tion: (PC) + -> TOS,

k-> PC<10:0>,(PCLATH<4:3>)-> PC<12:11>

Sta tus Af fected: NoneDe scrip tion: Call Sub rou tine. First, the 13-bit re turn ad dress

(PC+1) is pushed onto the stack. Theeleven-bit im me di ate ad dress is loaded into PCbits <10:0>. The up per bits of the PC areloaded from PCLATH<4:3>. CALL is a 2-cy cleinstruction.

Words: 1Cycles: 2Ex am ple 1:

Here:call There

Be fore In struc tion:PC = AddressHere

Af ter In struc tion:TOS = Ad dress Here + 1PC = Ad dress There

748 Ap pen dix F

Page 770: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

CLRF Clear f

Syn tax: [ la bel ] CLRF fOp er ands: f in range 0 to 127Op er a tion: 00h ->f

1-> ZSta tus Af fected: ZDe scrip tion: The con tents of reg is ter f are cleared and

the Z bit is set.Words: 1Cycles: 1Ex am ple 1:

clrf reg1Be fore In struc tion: reg1 = 0x5aAf ter In struc tion: reg1 = 0x00

Z = 1

Ex am ple 2:

Clrf INDFBe fore In struc tion: FSR = 0xc2

[FSR]= 0xAAAf ter In struc tion: FSR = 0xc2

[FSR] = 0x00Z = 1

Mid-Range In struc tion Set 749

Page 771: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

CLRW Clear w

Syn tax: [ la bel ] CLRWOp er ands: NoneOp er a tion: 00h -> w

1-> ZSta tus Af fected: ZDe scrip tion: w reg is ter is cleared. Zero bit (Z) is set.Words: 1Cycles: 1Ex am ple 1:

CLRWBe fore In struc tion: w = 0x5AAf ter In struc tion: w = 0x00

Z = 1

750 Ap pen dix F

Page 772: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

CLRWDT Clear Watch dog Timer

Syn tax: [ la bel ] CLRWDTOp er ands: NoneOp er a tion: 00h -> WDT

0 -> WDT prescaler count,1 -> TO1 -> PD

Sta tus Af fected: TO, PDDe scrip tion: CLRWDT in struc tion clears the Watch dog

Timer. It also clears the prescalercount of the WDT. Sta tus bits TO and PD areset. The in struc tion does not change the as sign ment of the WDT prescaler.

Words: 1Cycles: 1Ex am ple 1:

CLRWDTBe fore In struc tion: WDT coun ter= x

WDT prescaler = 1:128Af ter In struc tion: WDT coun ter=0x00

WDT prescaler count=0TO = 1PD = 1WDT prescaler = 1:128

Mid-Range In struc tion Set 751

Page 773: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

COMF Com ple ment f

Syn tax: [ la bel ] COMF f,dOp er ands: f in range 0 to 127

d is 0 or 1Op er a tion: (f) -> des ti na tionSta tus Af fected: ZDe scrip tion: The con tents of reg is ter f are 1’s

com ple mented. If d is 0 the re sult is stored inw. If d is 1 the re sult is stored back in reg is terf.

Words: 1Cycles: 1Ex am ple 1:

comf reg1,0Be fore In struc tion: reg1 = 0x13Af ter In struc tion: reg1 = 0x13

w = 0xEC

Ex am ple 2:

comf INDF,1Be fore In struc tion: FSR = 0xc2

[FSR]= 0xAAAf ter In struc tion: FSR = 0xc2

[FSR] = 0x55

Ex am ple 3:

comf reg1,1Be fore In struc tion: reg1= 0xffAf ter In struc tion: reg1 = 0x00

752 Ap pen dix F

Page 774: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

DECF Dec re ment f

Syn tax: [ la bel ] DECF f,dOp er ands: f in range 0 to 127

d is ei ther 0 or 1Op er a tion: (f) - 1 -> des ti na tionSta tus Af fected: ZDe scrip tion: Dec re ment reg is ter f. If d is 0 the re sult is

stored in the w reg is ter. If d is 1 there sult is stored back in reg is ter f.

Words: 1Cycles: 1Ex am ple 1:

decf count,1Be fore In struc tion: count = 0x01

Z = 0Af ter In struc tion: count = 0x00

Z = 1

Ex am ple 2:

decf INDF,1Be fore In struc tion: FSR = 0xc2

[FSR] = 0x01Z = 0

Af ter In struc tion: FSR = 0xc2[FSR] = 0x00Z = 1

Ex am ple 3:

decf count,0Be fore In struc tion: count = 0x10

w = xZ = 0

Af ter In struc tion: count = 0x10w = 0x0f

Mid-Range In struc tion Set 753

Page 775: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

DECFSZ Dec re ment f, Skip if 0

Syn tax: [ la bel ] DECFSZ f,dOp er ands: f in the range 0 to 127

d is ei ther 0 or 1Op er a tion: (f) - 1 -> des ti na tion; skip if re sult = 0Sta tus Af fected: NoneDe scrip tion: The con tents of reg is ter f are

dec re ment ed. If d is 0 the re sult is placedin the w reg is ter. If d is 1 the re sult isplaced back in reg is ter f.If the re sult is 0, then the next in struc tion(fetched dur ing the cur rent in struc tionex e cu tion) is dis carded and a NOP isex e cuted in stead, mak ing this a 2-cy clein struc tion.

Words: 1Cycles: 1(2)Ex am ple

here:decfsz count,1goto here

Case 1: Be fore In struc tion: PC = $

count = 0x01Af ter In struc tion: count = 0x00

PC = $ + 2 (goto skipped)Case 2:

Be fore In struc tion: PC = $count = 0x04

Af ter In struc tion: count = 0x03PC = $ + 1 (goto executed)

754 Ap pen dix F

Page 776: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

GOTO Un con di tional Branch

Syn tax: [ la bel ] GOTO kOp er ands: 0 £ k £ 2047Op er a tion: k -> PC<10:0>

PCLATH<4:3> ->PC<12:11>Sta tus Af fected: NoneDe scrip tion: GOTO is an un con di tional branch. The eleven-

bit im me di ate value is loaded into PC bits<10:0>. The up per bits of PC are loaded fromPCLATH<4:3>.GOTO is a 2-cy cle in struc tion.

Words: 1Cycles: 2Ex am ple

goto ThereAf ter In struc tion: PC = address of There

Mid-Range In struc tion Set 755

Page 777: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

INCF In cre ment f

Syn tax: [ la bel ] INCF f,dOp er ands: f in the range 0 to 127

d is ei ther 0 or 1Op er a tion: (f) + 1 -> des ti na tionSta tus Af fected: ZDe scrip tion: The con tents of reg is ter f are in cre mented. If

d is 0 the re sult is placed in the w reg is ter. If dis 1 the re sult is placed back in reg is ter f.

Words: 1Cycles: 1Ex am ple 1:

incf count,1Be fore In struc tion: count = 0xff

Z = 0Af ter In struc tion: count = 0x00

Z = 1

Ex am ple 2:

incf INDF,1Be fore In struc tion: FSR = 0xC2

[FSR] = 0xffZ = 0

Af ter In struc tion: FSR = 0xc2[FSR] = 0x00Z = 1

Ex am ple 3:

incf count,0Be fore In struc tion: count = 0x10

w = xZ = 0

Af ter In struc tion: count = 0x10w = 0x11Z = 0

756 Ap pen dix F

Page 778: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

INCFSZ In cre ment f, Skip if 0

Syn tax: [ la bel ] INCFSZ f,dOp er ands: f in the range 0 to 127

d is ei ther 0 or 1Op er a tion: (f) + 1 -> des ti na tion, skip if re sult = 0Sta tus Af fected: NoneDe scrip tion: The con tents of reg is ter f are in cre mented. If

d is 0 the re sult is placed in the w reg is ter. If dis 1 the re sult is placed back in reg is ter f.If the re sult is 0, then the next in struc tion(fetched dur ing the cur rent in struc tionex e cu tion) is dis carded and a NOP is ex e cutedin stead, mak ing this a 2-cy cle in struc tion.

Words: 1Cycles: 1(2)Ex am ple

Here:incfsz count,1goto Here

Case 1:Be fore In struc tion: PC = $

count = 0x10Af ter In struc tion: count = 0x11

PC = $ + 1 (goto executed)Case 2:

Be fore In struc tion: PC = $count = 0x00

Af ter In struc tion: count = 0x01PC = $ + 2 (goto skipped)

Mid-Range In struc tion Set 757

Page 779: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

IORLW In clu sive OR Lit eral with w

Syn tax: [ la bel ] IORLW kOp er ands: k is in range 0 to 255Op er a tion: (w).OR. k -> wSta tus Af fected: ZDe scrip tion: The con tents of the w reg is ter is ORed with

the eight- bit lit eral k. The re sult is placed inthe w reg is ter.

Words: 1Cycles: 1

Ex am ple 1:

iorlw 0x35Be fore In struc tion: w = 0x9aAf ter In struc tion: w = 0xbfF

Z = 0

Ex am ple 2:

iorlw myregBe fore In struc tion: w = 0x9aMyreg is a variable representing a locationin PIC RAM. [Myreg] = 0x37Af ter In struc tion: w = 0x9F

Z = 0

Ex am ple 3:

iorlw 0x00Be fore In struc tion: w = 0x00Af ter In struc tion: w = 0x00

758 Ap pen dix F

Page 780: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

IORWF In clu sive OR w with f

Syn tax: [ la bel ] IORWF f,dOp er ands: f is in the range 0 to 127

d is ei ther 0 or 1Op er a tion: (W).OR. (f) -> des ti na tionSta tus Af fected: ZDe scrip tion: In clu sive OR the w reg is ter with reg is ter f. If d

is 0 the re sult is placed in the w reg is ter. If d is1 the re sult is placed back in reg is ter f.

Words: 1Cycles: 1

Ex am ple 1:

iorwf result,0Be fore In struc tion: result = 0x13

w = 0x91Af ter In struc tion: result = 0x13

w = 0x93Z = 0

Ex am ple 2:

iorwf INDF,1Be fore In struc tion: w = 0x17

FSR = 0xc2[FSR] = 0x30

Af ter In struc tion: w = 0x17FSR = 0xc2[FSR] = 0x37Z = 0

Ex am ple 3:

iorwf result,1Case 1: Be fore In struc tion: result = 0x13

w = 0x91Af ter In struc tion: result = 0x93

w = 0x91Z = 0

Case 2: Be fore In struc tion: result = 0x00w = 0x00

Af ter In struc tion: result = 0x00w = 0x00Z = 1

Mid-Range In struc tion Set 759

Page 781: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

MOVLW Move Lit eral to w

Syn tax: [ la bel ] MOVLW kOp er ands: k in range 0 to 255Op er a tion: k- > wSta tus Af fected: NoneDe scrip tion: The eight bit lit eral k is loaded into w reg is ter.

The don’t cares will as sem ble as 0s.Words: 1Cycles: 1

Ex am ple 1:

movlw 0x5aAf ter In struc tion: w = 0x5A

Ex am ple 2:

movlw myregBe fore In struc tion: w = 0x10

[myreg] = 0x37Af ter In struc tion: w = 0x37

760 Ap pen dix F

Page 782: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

MOVF Move f

Syn tax: [ la bel ] MOVF f,dOp er ands: f is in the range 0 to 127

d is ei ther 0 or 1Op er a tion: (f) -> des ti na tionSta tus Af fected: ZDe scrip tion: The con tents of reg is ter f is moved to a

des ti na tion de pend ent upon the sta tus of d. Ifd = 0, des ti na tion is w reg is ter. If d = 1, thedes ti na tion is file reg is ter f it self. d = 1 isuse ful to test a file reg is ter be cause sta tus flagZ is af fected.

Words: 1Cycles: 1

Ex am ple 1:

movf FSR,0Be fore In struc tion: w = 0x00

FSR = 0xc2

Af ter In struc tion: w = 0xc2

Z = 0

Ex am ple 2:

movf INDF,0Be fore In struc tion: w = 0x17

FSR = 0xc2

[FSR] = 0x00

Af ter In struc tion: w = 0x17

FSR = 0xc2

[FSR] = 0x00

Z = 1

Ex am ple 3:

movf FSR,1Case 1: Be fore In struc tion: FSR = 0x43

Af ter In struc tion: FSR = 0x43

Z = 0

Case 2: Be fore In struc tion: FSR = 0x00

Af ter In struc tion: FSR = 0x00

Z = 1

Mid-Range In struc tion Set 761

Page 783: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

MOVWF Move w to f

Syn tax: [ la bel ] MOVWF fOp er ands: f in range 0 to 127Op er a tion: (w) -> fSta tus Af fected: NoneDe scrip tion: Move data from w reg is ter to reg is ter f.Words: 1Cycles: 1

Ex am ple 1:

movwf OPTION_REGBe fore In struc tion: OPTION_REG = 0xff

w = 0x4f

Af ter In struc tion: OPTION_REG = 0x4f

w = 0x4f

Ex am ple 2:

movwf INDFBe fore In struc tion: w = 0x17

FSR = 0xC2

[FSR] = 0x00

Af ter In struc tion: w = 0x17

FSR = 0xC2

[FSR] = 0x17

762 Ap pen dix F

Page 784: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

NOP No Op er a tion

Syn tax: [ la bel ] NOPOp er ands: NoneOp er a tion: No op er a tionSta tus Af fected: NoneDe scrip tion: No op er a tionWords: 1Cycles: 1Ex am ple

nopBe fore In struc tion: PC = $Af ter In struc tion: PC = $ + 1

Mid-Range In struc tion Set 763

Page 785: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

OPTION Load Op tion Reg is ter

Syn tax: [ la bel ] OPTIONOp er ands: NoneOp er a tion: (w) -> OPTION_REGSta tus Af fected: NoneDe scrip tion: The con tents of the w reg is ter are loaded in the

OPTION_REG reg is ter. This in struc tion issup ported for code com pat i bil ity with

PIC16C5X prod ucts. Be cause OPTION_REGis a readable/writable reg is ter, code candi rectly ad dress it with out us ing this instruction.

Words: 1Cycles: 1Ex am ple:

movlw b’01011100’option

.

764 Ap pen dix F

Page 786: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

RETFIE Re turn from In ter rupt

Syn tax: [ la bel ] RETFIEOp er ands: NoneOp er a tion: TOS -> PC,

1 -> GIESta tus Af fected: NoneDe scrip tion: Re turn from In ter rupt. The 13-bit ad dress at the

Top of Stack (TOS) is loaded in the PC. TheGlobal In ter rupt En able bit, GIE (INTCON<7>),is au to mat i cally set, en abling In ter rupts. This isa 2-cy cle in struc tion.

Words: 1Cycles: 2Ex am ple:

retfieAf ter In struc tion: PC = TOS

GIE = 1

Mid-Range In struc tion Set 765

Page 787: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

RETLW Re turn with Lit eral in w

Syn tax: [ la bel ] RETLW kOp er ands: k in the range 0 to 255Op er a tion: k -> w;

TOS -> PCSta tus Af fected: NoneDe scrip tion: The w reg is ter is loaded with the eight bit lit eral

k. The pro gram coun ter is loaded from the13-bit ad dress at the Top of Stack (the re turnad dress). This is a 2-cy cle in struc tion.

Words: 1Cycles: 2Ex am ple:

movlw 2 ; Load w with desired; Table offset

call table ; When call returns w; con tains value stored; in ta ble

Table:addwf pc ; w = off setretlw .22 ; First table entryretlw .23 ; Second table entryretlw .24...retlw .29 ; Last table entryBe fore In struc tion: w = 0x02Af ter In struc tion: w = .24

766 Ap pen dix F

Page 788: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

RETURN Re turn from Sub-Rou tine

Syn tax: [ la bel ] RETURNOp er ands: NoneOp er a tion: TOS -> PCSta tus Af fected: NoneDe scrip tion: Re turn from sub-rou tine. The stack is POPed

and the Top of Stack (TOS) is loaded intothe pro gram coun ter. This is a 2-cy clein struc tion.

Words: 1Cycles: 2Ex am ple:

returnAf ter In struc tion: PC = TOS

Mid-Range In struc tion Set 767

Page 789: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

RLF Ro tate Left f through Carry

Syn tax: [ la bel ] RLF f,dOp er ands: f in the range 0 to 127

d is ei ther 0 or 1Op er a tion: See de scrip tion be lowSta tus Af fected: CDe scrip tion: The con tents of reg is ter f are ro tated one bit to

the left through the Carry Flag. If d is 0 there sult is placed in the w reg is ter. If d is 1 there sult is stored back in reg is ter f.

Words: 1Cycles: 1

Ex am ple 1:

rlf reg1,0Be fore In struc tion: reg1 = 1110 0110

C = 0Af ter In struc tion: reg1 = 1110 0110

w =1100 1100C =1

Ex am ple 2:

rlf INDF,1Case 1: Be fore In struc tion: w = xxxx xxxx

FSR = 0xc2 [FSR] = 0011 1010C = 1

Af ter In struc tion: w = 0x17FSR = 0xc2 [FSR] = 0111 0101C = 0

Case 2: Be fore In struc tion: w = xxxx xxxxFSR = 0xC2 [FSR] = 1011 1001C = 0

Af ter In struc tion: w = 0x17FSR = 0xC2 [FSR] = 0111 0010C = 1

768 Ap pen dix F

Page 790: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

RRF Ro tate Right f through Carry

Syn tax: [ la bel ] RRF f,dOp er ands: f in the range 0 to 127

d is ei ther 0 or 1Op er a tion: See de scrip tion be lowSta tus Af fected: CDe scrip tion: The con tents of reg is ter f are ro tated one bit to

the right through the Carry Flag. If d is 0 there sult is placed in the w reg is ter. If d is 1 there sult is placed back in reg is ter f.

Words: 1Cycles: 1

Ex am ple 1:

rrf reg1,0Be fore In struc tion: reg1= 1110 0110

w = xxxx xxxxC = 0

Af ter In struc tion: reg1= 1110 0110w = 0111 0011C = 0

Ex am ple 2:

rrf INDF,1Case 1: Be fore In struc tion: w = xxxx xxxx

FSR = 0xc2 [FSR] = 0011 1010C = 1

Af ter In struc tion: w = 0x17FSR = 0xC2[FSR] = 1001 1101C = 0

Case 2: Be fore In struc tion: w = xxxx xxxxFSR = 0xC2[FSR] = 0011 1001C = 0

Af ter In struc tion: w = 0x17FSR = 0xc2[FSR] = 0001 1100C = 1

Mid-Range In struc tion Set 769

Page 791: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

SLEEP

Syn tax: [ la bel ] SLEEPOp er ands: NoneOp er a tion: 00h -> WDT,

0 -> WDT prescaler count,1 -> TO,0 -> PD

Sta tus Af fected: TO, PDDe scrip tion: The power-down sta tus bit PD is cleared.

Time-out sta tus bit TO is set. Watch dog Timerand its prescaler count are cleared. Thepro ces sor is put into SLEEP mode with theos cil la tor stopped. The SLEEP in struc tion doesnot af fect the as sign ment of the WDTprescaler.

Words: 1Cycles: 1Ex am ple:

SLEEP

770 Ap pen dix F

Page 792: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

SUBLW Sub tract w from Lit eral

Syn tax: [ la bel ] SUBLW kOp er ands: k in range 0 to 255Op er a tion: k - (W) -> WSta tus Af fected: C, DC, ZDe scrip tion: The w reg is ter is sub tracted (2’s com ple ment

method) from the eight bit lit eral k. The re sultis placed in the w reg is ter.

Words: 1Cycles: 1

Ex am ple 1:

sublw 0x02Case 1: Be fore In struc tion: w = 0x01

C = xZ = x

Af ter In struc tion: w = 0x01C = 1 if re sult +Z = 0

Case 2: Be fore In struc tion: w = 0x02C = xZ = x

Af ter In struc tion: w = 0x00C = 1 ; re sult = 0Z = 1

Case 3: Be fore In struc tion: w = 0x03C = xZ = x

Af ter In struc tion: w = 0xffC = 0 ; re sult -Z = 0

Ex am ple 2:

sublw myregBe fore In struc tion: w = 0x10

[myreg] = 0x37Af ter In struc tion w = 0x27

C = 1 ; re sult +

Mid-Range In struc tion Set 771

Page 793: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

SUBWF Sub tract w from f

Syn tax: [ la bel ] SUBWF f,dOp er ands: f in the range 0 to 127

d is ei ther 0 or 1Op er a tion: (f) - (W) -> des ti na tionSta tus Af fected: C, DC, ZDe scrip tion: Sub tract (2’s com ple ment method) w reg is ter

from reg is ter f. If d is 0 the re sult is stored in the w reg is ter. If d is 1 the re sult is storedback in reg is ter f.

Words: 1Cycles: 1

Ex am ple :

subwf reg1,1Case 1: Be fore In struc tion: reg1 = 3

w = 2C = xZ = x

Af ter In struc tion: reg1 = 1w = 2C = 1 ; re sult +Z = 0

Case 2: Be fore In struc tion: reg1 = 2w = 2C = xZ = x

Af ter In struc tion: reg1 = 0w = 2C = 1 ; re sult = 0Z = 1

Case 3: Be fore In struc tion: reg1 = 1w = 2C = xZ = x

Af ter In struc tion: reg1 = 0xffw = 2C = 0 ; re sult is -Z = 0

772 Ap pen dix F

Page 794: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

SWAPF Swap Nib bles in f

Syn tax: [ la bel ] SWAPF f,dOp er ands: f in the range 0 to 127

d is ei ther 0 or 1Op er a tion: (f<3:0>) -> des ti na tion<7:4>,

(f<7:4>) -> des ti na tion<3:0>Sta tus Af fected: NoneDe scrip tion: The up per and lower nib bles of reg is ter f are

ex changed. If d is 0 the re sult is placed in wreg is ter. If d is 1 the re sult is placed in reg is terf'.

Words: 1Cycles: 1

Ex am ple 1:

swapf reg,0Be fore In struc tion: reg1 = 0xa5Af ter In struc tion: reg1 = 0xa5

W = 0x5a

Ex am ple 2:

Swapf INDF,1Be fore In struc tion: w = 0x17

FSR = 0xc2[FSR] = 0x20

Af ter In struc tion: w = 0x17FSR = 0xC2[FSR] = 0x02

Ex am ple 3:

swapf reg,1Be fore In struc tion: reg1 = 0xa5Af ter In struc tion: reg1 = 0x5a

Mid-Range In struc tion Set 773

Page 795: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

TRIS Load TRIS Reg is ter

Syn tax: [ la bel ] TRIS fOp er ands: f in the range 5 to 7Op er a tion: (w) -> TRIS reg is ter f;Sta tus Af fected: NoneDe scrip tion: The in struc tion is sup ported for code

com pat i bil ity with the PIC16C5X prod ucts.Be cause TRIS reg is ters are read able andwritable, code can ad dress these reg is tersdi rectly.

Words: 1Cycles: 1

Ex am ple:

movlw B'00000000'tris PORTB

774 Ap pen dix F

Page 796: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

XORLW Ex clu sive OR Lit eral with w

Syn tax: [ la bel] XORLW kOp er ands: k in the range 0 to 255Op er a tion: (w).XOR. k -> WSta tus Af fected: ZDe scrip tion: The con tents of the w reg is ter are XORed with

the eight bit lit eral k. The re sult is placed in thew reg is ter.

Words: 1Cycles: 1

Ex am ple 1:

xorlw b’10101111’Be fore In struc tion: w = 1011 0101Af ter In struc tion: w = 0001 1010

Z = 0

Ex am ple 2:

xorlw myregBe fore In struc tion: w = 0xaf

[Myreg] = 0x37Af ter In struc tion: w = 0x18

Z = 0

Mid-Range In struc tion Set 775

Page 797: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

XORWF Ex clu sive OR w with f

Syn tax: [ la bel ] XORWF f,dOp er ands: f in range 0 to 127

d is ei ther 0 or 1Op er a tion: (W).XOR. (f) -> des ti na tionSta tus Af fected: ZDe scrip tion: Ex clu sive OR the con tents of the w reg is ter

with reg is ter f. If d is 0 the re sult is stored inthe w reg is ter. If d is 1 the re sult is stored backin reg is ter f.

Words: 1Cycles: 1

Ex am ple 1:

xorwf reg,1Be fore In struc tion: w = 1011 0101

reg = 1010 1111Af ter In struc tion: reg = 0001 1010

w = 1011 0101

Ex am ple 2:

xorwf reg,0Be fore In struc tion w = 1011 0101

reg = 1010 1111Af ter In struc tion: reg = 1010 1111

w = 0001 1010

Ex am ple 3:

xorwf INDF,1Be fore In struc tion: w = 1011 0101

FSR = 0xc2[FSR] = 1010 1111

Af ter In struc tion: w = 1011 0101FSR = 0xc2[FSR] = 0001 1010

776 Ap pen dix F

Page 798: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Ap pen dix G

Printed Circuit Boards

G.1 In tro duc tion

For stu dents in courses in elec tri cal, elec tron ics, and com puter en gi neer ing (or forany one in ter ested in these fields), hard ware boards and pro gram mers are a valu ablelearn ing tool. Many such boards are of fered on line at dif fer ent prices and lev els ofcom plex ity. But mak ing your own demo boards is even more valu able than pur chas ing one off the shelf. In this ap pen dix we pro vide in for ma tion and re sources to fa cil i tatemak ing hard ware ver sions of three simple demo boards men tioned in the text.

The reader should note that these hard ware boards are nei ther cheap nor easy tomake. One of the prob lems is that com pa nies that pro duce printed cir cuit boards of -ten re quire or ders for more than one board. For ex am ple, the com pany that we haveof ten used in mak ing printed cir cuit boards (ExpressPCB) pro vides a ProtoPro ser -vice of 4 boards per or der. At the time of this writ ing the cost of a min i mal or der foreach of the book's demo boards was ap prox i mately $180.00. Which re sults in a cost ofap prox i mately $45.00 per board. Also in this ap pen dix we pro vide in for ma tion on pro -duc ing home-made boards but this op tion has its own dif fi cul ties and draw backs.

G.2 Printed Cir cuit Boards (PCBs)

PCBs are a nonconductive sub strates (usu ally of fi ber glass or resin) on which con duc -tive traces and path ways are etched on one or more cop per layers that are lam i natedonto board body. The re sult is an in ex pen sive and re li able me dia to which the elec -tronic com po nents can be at tached, usu ally by weld ing.

Printed cir cuit boards are of ten cre ated us ing a com puter pro gram that fa cil i tates draw ing the traces and plac ing the com po nents onto one or more lay ers. Fig ure G-1is a screen snap shot of the ExpressPCB pro gram (fur nished free on-line byExpressPCB).

777

Page 799: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure G-1 PCB Be ing De veloped with ExpressPCB.

A PCB ed i tor pro gram (such as ExpressPCB) gen er ates a file from which theprinted cir cuit board can be fab ri cated. Of ten the pro grams are pro pri etary of thefirm that man u fac tures the boards. In the case of ExpressPCB, the file with the ex -ten sion .pcb can be sub mit ted on line and the man u fac tured boards are re turned toyou in a few days.

In this book's soft ware pack age we in clude three files in .pcb for mat for the hard -ware ver sion of each of the boards used in the text. The lo ca tion and file names are:

• PCBs/VBA/Demo Board A.pcb

• PCBs/VBB/Demo Board B.pcb

• PCBs/VBI/Demo Board I.pcb

These files can be used in hav ing printed cir cuit boards made by ExpressPCB. Inor der to find out how to go about it you may log on to the com pany's web site atwww.expresspcb.com.

G.3 Parts ListsOnce the printed cir cuits boards have been made, they must be pop u lated with theelec tronic com po nents. In or der to fa cil i tate this step, we are in clud ing a parts list for

778 Ap pen dix G

Page 800: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

each of the boards in this book’s soft ware pack age. The lo ca tion and file names are asfol lows:

• PCBs/VBA/parts demo a

• PCBs/VBB/parts demo b

• PCBs/VBI/parts demo c

The files are in .txt for mat and can be loaded and viewed in any word pro cess ingpro gram or in Microsoft note pad.

In ad di tion to the parts listed, the boards re quire a 9 to 12 volts AC/DC wall or ta -ble-top adapter. The power plug on the adapter should be fe male, 2.5 x 5.5 mm., andcen ter pos i tive po lar ity. Jameco part num ber 189238CJ is suit able. Sim i lar ones areavail able at Ra dio Shack and from other sources.

G.4 Build ing Your Own Cir cuit BoardsSev eral meth ods have been de vel oped for mak ing printed cir cuit boards on a smallscale, as would be con ve nient for the ex per i menter and pro to type de vel oper. If youlook through the pages of any elec tron ics sup ply cat a log, you will find kits and com po -nents based on dif fer ent tech nol o gies of var i ous lev els of com plex ity. The meth ods we de scribe in the fol low ing sec tions are per haps the sim plest be cause they do not re -quire a pho to graphic pro cess.

The pro cess con sists of the fol low ing steps:

1. The cir cuit di a gram is drawn on the PC us ing a gen eral-pur pose or spe cial izeddraw ing pro gram.

2. A print out is made of the cir cuit draw ing on pho to graphic pa per.

3. The print out is trans ferred to a cop per-clad cir cuit board blank by iron ing over thepa per's back side with a house hold clothes iron.

4. The re sult ing board is placed in a fer ric chlo ride etch ing bath that eats away all thecop per, ex cept the cir cuit im age ironed onto the board sur face.

5. The board is washed of the etch ing fluid, cleaned, drilled, and the com po nents sol -dered to it in the con ven tional man ner.

6. Op tion ally, an other im age can be ironed onto the front side of a dou ble-sided boardto pro vide a sec ond con duc tive layer with or with out com po nents.

7. Im ages con tain ing text, iden ti fi ca tion, or lo gos can be ironed onto ei ther side of theboard but are usu ally on the front side.

In this ap pen dix we of fer two ex am ples: the first one con sists of a sim ple demoboard made on a sin gle-sided board with text on the nonconductive side. The sec -ond one is the home-made ver sion of Demo Board A that has two con duc tive sidesand text on the front side.

G.4.1 Tools and Ma te rialsThe fol low ing tools and ma te ri als are re quired for fab ri cat ing the printed cir cuitboard:

Printed Circuit Boards 779

Page 801: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

• A gen eral-pur pose draw ing pro gram or a spe cial ized printed cir cuit draw ing ap pli -ca tion.

• A la ser printer such as La ser Jet or equiv a lent or a la ser copier. Inkjet print ers are not suit able.

• House hold clothes iron.

• Scotch-Brite™ (green) abra sive pads.

• Ac e tone sol vent.

• Cop per-plated cir cuit board blank, sin gle- or dou ble-side ac cord ing to pro ject.

• Fer ric chlo ride etch ing so lu tion for cop per-plated boards.

• Plas tic or glass con tainer for hold ing board dur ing etch ing.

Af ter the board has been etched, it must be drilled and the com po nents sol dered.The fol low ing tools and ma te ri als are nec es sary for this phase:

• Small elec tric drill ca pa ble of high rev o lu tions, such as a Dremmel tool.

• Drill bits 0.035" and 0.040".

• Sol der ing iron or sol der ing gun suit able for elec tronic com po nents.

• Light duty rosin-core sol der.

G.4.2 Sin gle-Sided Demo Board

We have men tioned that hard ware dem on stra tion (or demo) boards are a use ful toolin mas ter ing em bed ded sys tems. Con structing your own demo boards and cir cuits isnot a dif fi cult task. The com po nents can be placed on a bread board, wire-wrappedonto a spe cial cir cuit board. A printed cir cuit boards can be home-made, or one or -dered through the Internet. The book's on line re source con tains de scrip tions of com -mer cial PCBs as well as in struc tions and re sources for ob tain ing com mer cially madeboards for the demo cir cuits used in this book.

We first il lus trate the pro cess with a sim ple board that con tains a 16F84A-PIC,Seven-Seg ment LED, buzzer, pushbutton switch, and a bank of four tog gle switches. Fig ure G-2 shows the sche mat ics for the board and the power sup ply.

G.4.3 PCB Im ages for Demo Board

Com mer cial PCBs con tain cir cuit etch ings on two, four, or more lay ers. Al thoughmulti-lay ered boards ap pear com plex, most cir cuit de sign ers will agree that the morelay ers avail able the eas ier it is to place the com po nents with out in ter fer ence. Dou -ble-sided boards (two con duc tive lay ers) usu ally have the power and in ter face con -nec tions on one layer and the ground plane on an other one. That is the method wefol lowed with the demo boards de scribed in the on line doc u men ta tion and in this ap -pen dix. In this case, two cir cuit board im ages are re quired, one for each con duc tiveplane on the board. In ad di tion, most boards con tain a text im age that in cludes com po -nent place ments, com pany lo gos, model num bers, and other tex tual in for ma tion. Incom mer cially made boards, the text im age is silk-screened onto the board.

780 Ap pen dix G

Page 802: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure G-2 A Sim ple PIC 16F87A Demo Board.

The first home-made board ex am ple in this ap pen dix uses a sin gle-sided boardwith an etched im age on the con duc tive side (bronze layer) and a text im age on theboard’s nonconductive side. Both im ages can be cre ated with a con ven tional draw -ing pro gram, such as Corel Draw, Adobe Il lus tra tor, or Win dows Paint, or with a spe -cial ized ap pli ca tion, such as the one fur nished by ExpressPCB and dis cussed ear lier in this ap pen dix. Fig ure G-3 shows the im ages used for mak ing the PCB for the cir -cuit in Fig ure G-2.

Printed Circuit Boards 781

16

F8

4A

Osc

a

PWRON

b

cd

e e

f

f

g

g

d

c

b

a

+5V

+5V

R=

10

K

R=

10

K

RA2

RA3

RA4/TOCKI

MCLR

Vss

RB0/INT

RB1

RB2

RB3

1

2

3

4

5

6

7

8

9

18

17

16

15

14

13

12

11

10

RA1

RA0

OSC1

OSC2

Vdd

RB7

RB6

RB5

RB4

220 RX 7

10k RX 4

DIP SW

PB SW

PiezoBuzzer

7-segmentLED

C=0.1mFEC=100mF

78L05

INOUT

9 -35V DCinput+5V DC

output

5V regulated power supply

+

Page 803: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Fig ure G-3 Bot tom-Side and Top-Side Layer Im ages for a PCB.

In Fig ure G-3 the im age on the left side is etched on the con duc tive side of theboard, that is, the one with the cop per layer. This is usu ally re ferred to as the bot -tom layer. In this ex am ple the com po nents and the text are placed on the top ornonconductive layer. No tice that the top-side im age must be hor i zon tally mir roredbe fore it is trans ferred to the pho to graphic pa per. This is nec es sary so that the textand graph ics co in cide with the cir cuit etch ings.

Draw ing the Cir cuit Di a gram

Any com puter draw ing pro gram serves this pur pose. We have used CorelDraw™, butthere are sev eral spe cial ized PCB draw ing pro grams avail able on the Internet. No ticein the draw ing in Fig ure G-3 that the cir cuit lo ca tions where the com po nents are to besol dered con sist of small cir cu lar pads, usu ally called sol der pads. Fig ure G-4 zoomsinto a PCB draw ing to show the de tails of the sol der pads.

Fig ure G-4 De tail of Cir cuit Board Pads.

782 Ap pen dix G

Page 804: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Quite of ten it is nec es sary for a cir cuit line to cross be tween two sol der pads. Inthis case the pads can be made smaller or mod i fied so as to al low pass ing a trace be -tween them. Mod ified pads are shown in Fig ure G-5.

Fig ure G-5 Mod i fied Cir cuit Boards Pads.

Print ing the PCB Di a gram

In the method pres ently de scribed the cir cuit di a gram is printed us ing a la ser printer.Inkjet ton ers do not pro duce an im age that re sist the ac tion of the etch ing liq uid. Al -though in our ex per i ments we used La ser Jet print ers, it is well doc u mented that vir tu -ally any la ser printer will work. La ser copi ers have also been used suc cess fully forcre at ing the PCB cir cuit im age.

How ever, with this method the width of the traces can be come an is sue. Thetraces in the PCB im age of Fig ure G-5 are 2 points, which is 0.027". Traces half thatwidth and less have been used suc cess fully; but as the traces be come thin ner the en -tire pro cess turns out more crit i cal. For most sim ple cir cuits, 0.020" traces shouldbe a use ful limit. Be care ful not to touch the glossy side of the pho to graphic pa peror the printed im age with your fin gers.

Se lecting the Pa per

Prac ti tio ners of this method af firm that one of the most crit i cal el e ments is the pa perused in print ing the cir cuit. Pin holes in some pa pers can de grade the im age to thepoint that the cir cuit lines (es pe cially if they are very thin) do not etch cor rectly. An -other prob lem re lates to re mov ing the ironed-on pa per from the board with out dam ag -ing the board sur face.

Glossy, coated inkjet-printer pa per works well (yes, Inkjet pa per on a La ser Jetprinter). Even better re sults can be ob tained with glossy photo pa per. We use a com -mon high-gloss pho to graphic pa per avail able from Sta ples and sold un der the nameof “pic ture pa per.” The 30 sheets, 8-by-10 size, has the Sta ples num ber B0314201971713. The UPC barcode is: 7 18103 02238 5.

Printed Circuit Boards 783

Page 805: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Trans ferring the PCB Im age

Trans ferring the im age onto the board blank is done by ap ply ing heat from a com monclothes iron, set on the hot test set ting, onto the pa per/board sand wich. In most ironsthe hot test set ting is la beled “linen.” Af ter go ing over the back of the pa per sev eraltimes with the hot iron, the pa per be comes fused to the cop per side of the blank board. The board/pa per sand wich is then al lowed to soak in wa ter for about ten min utes, af -ter which the pa per can be re moved by peel ing or light scrub bing with a tooth brush. Ithas been men tioned that Hewlett-Packard toner car tridges with so-called microfinepar ti cles work better than store-brand toner car tridges.

Etch ing the Board

Once the pa per has been re moved and the board washed, it is time to pre pare theboard for etch ing. The pre lim i nary op er a tions con sist of rub bing the cop per sur face of the board with a Scotchbrite abra sive pad and then scrub bing the sur face with a pa pertowel soaked with ac e tone sol vent.

Once the board is rubbed and clean, you can pro ceed to etch the cir cuit. Theetch ing so lu tion con tains fer ric chlo ride and is avail able from Ra dio Shack as a so -lu tion and from Jameco Elec tron ics as a pow der to be mixed by the user. PCB ferricchlo ride etchant should be han dled with rub ber gloves and rub ber apron be cause itstains the skin and uten sils. Also, con cen trated acid fumes from ferric chlo ride so lu -tion are toxic and can cause se vere burns. These chem i cals should be han dled ac -cord ing to cau tions and warn ings posted on the con tain ers.

The ferric chlo ride so lu tion should be used in a plas tic or glass con tainer, neverin metal. Faster etch ing is ac com plished if the etch ing so lu tion is first warmed byplac ing the bot tle in a tub of hot wa ter. Once the board is in the so lu tion, face up,the con tainer is rocked back and for ward. It is also pos si ble to aid cop per re movalby rub bing the sur face with a rub ber-gloved fin ger.

Fin ishing the Board

The etched board should be washed well, first in wa ter and then in lacquer thin ner oracetone, ei ther sol vent works. It is better to just rub the board sur face with a pa pertowel soaked in the sol vent. Keep in mind that most sol vents are flam ma ble and ex plo -sive, and also toxic.

Af ter the board is clean, the mount ing holes can be drilled us ing the sol der padsas a guide. A small elec tric drill at high rev o lu tions, such as a Dremmel tool, workswell for this op er a tion. The stan dard drill size for the mount ing holes is 0.035". A #60 drill (0.040") also works. On line one can pur chase a set of spe cial PCB drill bits ofvar i ous sizes. Once all the holes are drilled, the com po nents can be mounted fromthe front side and sol dered at the pads.

Com po nent-Side Im age

The com po nent side (front side) of the PCB can be printed with an im age of the el e -ments to be mounted or with lo gos or other text. A sin gle-sided blank board has nocop per coat ing on the front side, so the im age is just ironed on with out etch ing. Prob a -bly the best time to print the text im age is af ter the board has been etched and drilled

784 Ap pen dix G

Page 806: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

but be fore mount ing the com po nents. Dou ble-sided boards must be etched andwashed be fore the text im age is trans ferred.

G.5 Ca veatsAs sem bling and sol der ing com po nents onto PCBs re quire some man ual and tech ni calskills, ma te ri als, and spe cial equip ment. We do not rec om mend that you un der takethis task un less you have pre vi ous ex pe ri ence in this area. Nei ther do we pro vide in -for ma tion or as sis tance on how to do it.

The parts listed were avail able at the men tioned sources and the listed prices atthe time of writ ing. Avail abil ity and prices of ten change, so it may not be the casewhen you place your or der.

The sources rec om mended for the PVBs and the elec tronic com po nents are onesthat we have used in the past and are pop u lar with ex per i ment ers and hob by ists.But there are many other sources that can sup ply equiv a lent parts at the same orper haps better prices. The au thors and pub lish ers of this book have no as so ci a tionwith or com mer cial in ter est in any of the sources men tioned.

Printed Circuit Boards 785

Page 807: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

This page intentionally left blankThis page intentionally left blank

Page 808: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

Appendix H

Additional Code

In this ap pen dix we list sev eral pro grams that were de vel oped while writ ing this bookand for some rea son were not used in the text. They are pro vided to the reader as acode grab-bag in the hope that some may find a use ful frag ment or rou tine amongthose listed. Each pro gram con tains a de scrip tion of its pur pose and func tion al ity.The code for the sup ple men tary pro grams is avail able in this book’s on line soft warepack age.

; File: SecondCnt.ASM; Date: April 29, 2011; Au thors: Canton and Sanchez;; De scrip tion:; Using timer0 to de lay one sec ond at a sig nal; rate of 1,000,000 beats per sec ond;===========================; switches;===========================; Switches used in __config di rec tive:; _CP_ON Code pro tec tion ON/OFF ; * _CP_OFF ; * _PWRTE_ON Power-up timer ON/OFF; _PWRTE_OFF ; _WDT_ON Watchdog timer ON/OFF ; * _WDT_OFF ; _LP_OSC Low power crys tal oscillator; * _XT_OSC Ex ter nal par al lel crys tal oscillator ; _HS_OSC High speed crys tal res o na tor (8 to 10 MHz); Res o na tor: Murate Erie CSA8.00MG = 8 MHz ; _RC_OSC Re sis tor/ca pac i tor ocillator; (sim plest, 20% er ror); |; |_____ * in di cates setup val ues

787

Page 809: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

pro ces sor 16f84Ain clude <p16f84A.inc>__config _XT_OSC & _WDT_OFF & _PWRTE_ON & _CP_OFF

;=====================================================; PIC reg is ter equates;=====================================================porta equ 0x05portb equ 0x06sta tus equ 0x03z equ 0x02c equ 0x00tmr0 equ 0x01; countL equ 0x01 ; Alias for tmr0;;=====================================================; vari ables in PIC RAM;=====================================================; Lo cal vari ables

cblock 0x0d ; Start of blockJ ; coun ter JK ; coun ter K

; 3-byte aux il iary coun ter. Low or der byte is kept; in the timer0 reg is ter

countM ; Me dium bytecountH ; High byte

endc;========================================================; m a i n p r o g r a m;========================================================

org 0 ; start at ad dress 0goto main

;;=============================; in ter rupt han dler;=============================

org 0x04; goto IntServ;=============================; main pro gram;=============================main:; Clear the Watchdog timer and re set prescaler

clrf tmr0clrwdt

; Set up the OPTION regiser bitmapmovlw b'11011000'

788 Appendix H

Page 810: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; 7 6 5 4 3 2 1 0 <= OPTION bits; | | | | | |__|__|_____ PS2-PS0 (prescaler bits); | | | | | Values for Timer0; | | | | | *000 = 1:2 001 = 1:4; | | | | | 010 = 1:8 011 = 1:16; | | | | | 100 = 1:32 101 = 1:64; | | | | | 110 = 1:128 *111 = 1:256; | | | | |______________ PSA (prescaler as sign); | | | | 1 = to WDT; | | | | *0 = to Timer0; | | | |_________________ TOSE (Timer0 edge se lect); | | | 0 = in cre ment on low-to-high; | | | *1 = in cre ment in high-to-low; | | |____________________ TOCS (TMR0 clock source); | | *0 = in ter nal clock; | | 1 = RA4/TOCKI bit source; | |_______________________ INTEDG (Edge se lect); | *0 = fall ing edge; |__________________________ RBPU (Pullup en able); 0 = en abled; *1 = disabled

op tion; Setup ports

movlw 0x00 ; Set port B to out puttris portbclrf portb ; All port B to 0

; Port A is not used in this pro grammloop:

bsf portb,0call TM0delaybcf portb,0call TM0delaygoto mloop

;*********************************; one sec ond de lay sub-rou tine; us ing Timer0;*********************************; Rou tine logic:; The prescaler is as signed to timer0 and set up so; that the timer runs at 1:2 rate. This means that; ev ery time the coun ter reaches 128 (0x80), a to tal; of 256 ma chine cy cles have elapsed. The value 0x80; is de tected by test ing bit 7 of the coun ter; reg is ter. This method gives the rou tine a to tal of; 128 ma chine cy cles be fore the next coun ter beat must; be ac knowl edged. TM0delay:; Timer is de signed to count from 0 to 1,000,000

Additional Code 789

Page 811: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; 1,000,000 = 0x0f 0x42 0x40; ---- ---- ----; | | |___ (see note); | |________ countM; |_____________ countH; Note:; The ini tial count of 0x40 (64 dec i mal) is en sured; by initializing the tmr0 reg is ter to count 32 timer; beats at the 1:2 prescaler rate. 128 - 32 = 96 = 0x60 ; Ini tial ize the coun ters:

movlw 0x0fmovwf countHmovlw 0x42movwf countMmovlw 0x60movwf tmr0

; Rou tine tests timer over flow by test ing bit 7 of; the tmr0 reg is ter.cy cle:

movlw 3subwf tmr0,wbtfsc sta tus,cgoto cy cle

; Sub tract 256 from beat coun ter by dec re ment ing the; mid-or der byte

decfsz countM,fgoto cy cle ; Con tinue if mid-byte not

zero; At this point the mid-or der byte has over flowed.; High-or der byte must be dec re ment ed.

decfsz countH,fgoto cy cle

; At this point one sec ond has elapsedre turnend

790 Appendix H

Page 812: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; File name: SevenSeg.asm; Date: April 9, 2011; Au thors: Canton and Sanchez;; Ref er ence: SevenSeg Cir cuit and Board;; De scrip tion:; Test pro gram for read ing four tog gle switches and; dis play ing the rep re sented hex num ber on Seven-Segment; LED. Also con tains a pushbutton switch to ac ti vate a; piezo buzzer. Switches are wired ac tive low.;; Switches used in __config di rec tive:; _CP_ON Code pro tec tion ON/OFF ; * _CP_OFF ; * _PWRTE_ON Power-up timer ON/OFF; _PWRTE_OFF ; _WDT_ON Watchdog timer ON/OFF ; * _WDT_OFF ; _LP_OSC Low power crys tal oscillator; * _XT_OSC Ex ter nal par al lel crys tal oscillator ; _HS_OSC High speed crys tal res o na tor (8 to 10 MHz); Res o na tor: Murate Erie CSA8.00MG = 8 MHz ; _RC_OSC Re sis tor/ca pac i tor oscillator; (sim plest, 20% er ror); |; |_____ * in di cates setup val ues;;=========================; setup and con fig u ra tion;=========================

pro ces sor 16f84Ain clude <p16f84A.inc>__config _XT_OSC & _WDT_OFF & _PWRTE_ON & _CP_OFF

;;=====================================================; con stant def i ni tions; (per cir cuit wir ing di a gram);=====================================================#de fine Pb_sw 4 ; Port A line 4 to pushbut ton switch;;=====================================================; PIC reg is ter equates;=====================================================Porta equ 0x05Portb equ 0x06;============================; lo cal vari ables

Additional Code 791

Page 813: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

;============================cblock 0x0c ; Start of blockJ ; coun ter JK ; coun ter Kendc

;============================================================; pro gram;============================================================

org 0 ; start at ad dress 0goto main

;; Space for in ter rupt han dlers

org 0x08

main:; Port A. Five low-or der lines set for in put

movlw B'00011111' ; w = 00011111 bi narytris porta ; port A (lines 0 to 4) to

in put; Port B. All eight lines for out put

movlw B'00000000' ; w := 00000000 bi narytris portb ; port B to out put

;;===============================; Pushbutton switch pro cess ing;===============================pbutton:; Push but ton switch on demo board is wired to port A bit 4; Switch logic is ac tive low

btfss porta,Pb_sw ; Test and skip if switch bit; set

goto buzzit ; Buzz if switch ON, ; At this point port A bit 4 is set (switch is off)

call buzoff ; Buzzer offgoto readdip ; Read DIP switches

buzzit:call buzon ; Turn on buzzergoto pbutton

;;============================; dip switch mon i tor ing;============================readdip:; Read port A switches

movf porta,w ; Port A bits to w; because board is wired ac tive low then all switch bits; must be ne gated. This is done by XORing with 1-bits

xorlw b'11111111' ; In vert all bits in w

792 Appendix H

Page 814: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; Mask off 4 high-or der bitsandlw b'00001111' ; And with mask

; At this point the w reg is ter con tains a 4-bit value; in the range 0 to 0xf. Use this value (in w) to ; ob tain Seven-Segment dis play code

call seg mentmovwf portb ; Dis play switch bitsgoto pbutton

;================================; rou tine to re turns 7-seg ment; codes;================================seg ment:

addwf PCL,f ; PCL is pro gram coun ter latchretlw 0x3f ; 0 coderetlw 0x06 ; 1retlw 0x5b ; 2retlw 0x4f ; 3retlw 0x66 ; 4retlw 0x6d ; 5retlw 0x7d ; 6retlw 0x07 ; 7retlw 0x7f ; 8retlw 0x6f ; 9retlw 0x77 ; Aretlw 0x7c ; Bretlw 0x39 ; Cretlw 0x5b ; Dretlw 0x79 ; Eretlw 0x71 ; Fretlw 0x7f ; Just in case all on

;============================; piezo buzzer ON;============================; Rou tine to turn on piezo buzzer on port B bit 7buzon:

bsf portb,7 ; Tune on bit 7, port Bre turn

;;============================; piezo buzzer OFF;============================; Rou tine to turn off piezo buzzer on port B bit 7buzoff:

bcf portb,7 ; Bit 7 port b clearre turn

;=============================

Additional Code 793

Page 815: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; long de lay sub-rou tine; (for code test ing);=============================long_de lay

movlw D'200' ; w = 200 dec i malmovwf J ; J = w

jloop: movwf K ; K = wkloop: decfsz K,f ; K = K-1, skip next if zero

goto kloopdecfsz J,f ; J = J-1, skip next

if zerogoto jloopre turnend

794 Appendix H

Page 816: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; File name: TestStr.asm; Date: May 1, 2011; Au thors: Sanchez and Canton;; De scrip tion:; Pro gram to test send ing strings to LCD mem ory di rectly; Pro gram uses de lay loops for in ter face tim ing.; WARNING:; Code as sumes 4 MHz clock. De lay rou tines must be; ed ited for faster clock

; Dis plays: Min ne sota State, Mankato;;===========================; switches;===========================; Switches used in __config di rec tive:; _CP_ON Code pro tec tion ON/OFF ; * _CP_OFF ; * _PWRTE_ON Power-up timer ON/OFF; _PWRTE_OFF ; _WDT_ON Watchdog timer ON/OFF ; * _WDT_OFF ; _LP_OSC Low power crys tal oscillator; * _XT_OSC Ex ter nal par al lel crys tal oscillator ; _HS_OSC High speed crys tal res o na tor (8 to 10 MHz); Res o na tor: Murate Erie CSA8.00MG = 8 MHz ; _RC_OSC Re sis tor/ca pac i tor oscillator; (sim plest, 20% er ror); |; |_____ * in di cates setup val ues

;=========================; setup and con fig u ra tion;=========================

pro ces sor 16f84Ain clude <p16f84A.inc>__config _XT_OSC & _WDT_OFF & _PWRTE_ON & _CP_OFF

;=====================================================; con stant def i ni tions; for PIC-to-LCD pin wir ing and LCD line ad dresses;=====================================================#de fine E_line 1 ;|#de fine RS_line 2 ;| -- from wir ing di a gram #de fine RW_line 3 ;|;; LCD line ad dresses (from LCD datasheet)

Additional Code 795

Page 817: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

#de fine LCD_1 0x80 ; First LCD line con stant#de fine LCD_2 0xc0 ; Sec ond LCD line con stant; Note: The con stants that de fine the LCD dis play line; ad dresses have the high-or der bit set in; or der to faciliate the con trol ler com mand ;;=====================================================; PIC reg is ter equates;=====================================================

porta equ 0x05Portb equ 0x06fsr equ 0x04Status equ 0x03indf equ 0x00z equ 2

;=====================================================; vari ables in PIC RAM;=====================================================; Re serve 16 bytes for string buffer

cblock 0x0cstrDataendc

; Leave 16 bytes and Con tinue with lo cal vari ablescblock 0x1d ; Start of blockcount1 ; Coun ter # 1count2 ; Coun ter # 2count3 ; Coun ter # 3pic_ad ; Stor age for start of text area

; (la beled strData) in PIC RAMJ ; coun ter JK ; coun ter Kin dex ; In dex into text ta ble (also used

; for aux il iary stor age)endc

;============================================================; pro gram;============================================================

org 0 ; start at ad dress goto main

; Space for in ter rupt han dlersorg 0x08

main:movlw b'00000000' ; All lines to out puttris porta ; in port Atris portb ; and port Bmovlw b'00000000' ; All out puts ports lowmovwf porta

796 Appendix H

Page 818: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

movwf portb; Wait and ini tial ize HD44780

call de lay_5 ; Al low LCD time to ini tial ize it self

call initLCD ; Then do forcedini tial iza tion

call de lay_5 ; (Wait prob a bly notnec es sary); Store base ad dress of text buffer in PIC RAM

movlw 0x0c ; Start ad dress of text buffermovwf pic_ad ; to lo cal vari able

;=========================; test rou tine;=========================; Set DDRAM ad dress to start of first line

call line1; Store char ac ters and send di rectly

movlw 'H'movwf portbcall pulseEmovlw 'e'movwf portbcall pulseEmovlw 'l'movwf portbcall pulseEmovlw 'l'movwf portbcall pulseEmovlw 'o'movwf portbcall pulseEcall de lay_5

;=======================; done!;=======================loopHere:

goto loopHere ;done

;************************************************************; INITIALIZE LCD PROCEDURE ;************************************************************initLCD; Ini tial iza tion for Densitron LCD mod ule as fol lows:; 8-bit in ter face; 2 dis play lines of 16 char ac ters each; cur sor on; left-to-right in cre ment

Additional Code 797

Page 819: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; cur sor shift right; no dis play shift;***********************|; COMMAND MODE |;***********************|

bcf porta,E_line ; E line lowbcf porta,RS_line ; RS line low for com mandbcf porta,RW_line ; Write modecall de lay_125 ;de lay 125

mi cro sec onds;***********************|; FUNCTION SET |;***********************|

movlw 0x38 ; 0 0 1 1 1 0 0 0 (FUNCTION SET); | | | |__ font se lect:; | | | 1 = 5x10 in 1/8 or 1/11; | | | 0 = 1/16 dc; | | |___ Duty cy cle se lect; | | 0 = 1/8 or 1/11; | | 1 = 1/16; | |___ In ter face width; | 0 = 4 bits; | 1 = 8 bits; |___ FUNCTION SET COMMAND

movwf portb ;0011 1000call pulseE ;pulseE and de lay

;***********************|; DISPLAY OFF |;***********************|

movlw 0x08 ; 0 0 0 0 1 0 0 0 (DISPLAY ON/OFF); | | | |___ Blink char ac ter; | | | 1 = on, 0 = off; | | |___ Cursor on/off; | | 1 = on, 0 = off; | |____ Dis play on/off; | 1 = on, 0 = off; |____ COMMAND BIT

movwf portbcall pulseE ;pulseE and de lay

;***********************|; DISPLAY AND CURSOR ON |;***********************|

movlw 0x0e ; 0 0 0 0 1 1 1 0 (DISPLAY ON/OFF); | | | |___ Blink char ac ter; | | | 1 = on, 0 = off

798 Appendix H

Page 820: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; | | |___ Cursor on/off; | | 1 = on, 0 = off; | |____ Dis play on/off; | 1 = on, 0 = off; |____ COMMAND BIT

movwf portbcall pulseE ;pulseE and de lay

;***********************|; ENTRY MODE SET |;***********************|

movlw 0x06 ; 0 0 0 0 0 1 1 0 (ENTRY MODE SET); | | |___ dis play shift; | | 1 = shift; | | 0 = no shift; | |____ cur sor in cre ment; | 1 = left-to-right; | 0 = right-to-left; |___ COMMAND BIT

movwf portb ;00000110call pulseE

;***********************|; CURSOR/DISPLAY SHIFT |;***********************|

movlw 0x14 ; 0 0 0 1 0 1 0 0 (CURSOR/DISPLAY; SHIFT); | | | |_|___ don't care; | |_|__ cur sor/dis play shift; | 00 = cur sor shift left; | 01 = cur sor shift right; | 10 = cur sor and dis play; | shifted left; | 11 = cur sor and dis play; | shifted right; |___ COMMAND BIT

;movwf portb ;0001 1111call pulseE

;***********************|; CLEAR DISPLAY |;***********************|

movlw 0x01 ; 0 0 0 0 0 0 0 1 (CLEAR DISPLAY); |___ COMMAND BIT

movwf portb ;0000 0001;

call pulseE

Additional Code 799

Page 821: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

call de lay_5 ;de lay 5 mil li sec onds af ter initre turn

;************************************************************; DELAY AND PULSE PROCEDURES ;************************************************************;=======================; Pro ce dure to de lay; 42 mi cro sec onds;=======================de lay_125

movlw D'42' ; Re peat 42 ma chine cy clesmovwf count1 ; Store value in coun ter

re peatdecfsz count1,f ; Dec re ment coun tergoto re peat ; Con tinue if not 0re turn ; End of de lay

;------------------------------------------------------------;=======================; Pro ce dure to de lay; 5 mil li sec onds;=======================de lay_5

movlw D'41' ; Coun ter = 41movwf count2 ; Store in vari able

de laycall de lay_125 ; De laydecfsz count2,f ; 40 times = 5 mil li sec ondsgoto de layre turn ; End of de lay

;========================; pulse E line ;========================pulseE

bsf porta,E_line ;pulse E linebcf porta,E_linecall de lay_125 ;de lay 125 mi cro sec ondsre turn

;=============================; long de lay sub-rou tine; (for de bug ging);=============================long_de lay

movlw D'200' ; w = 200 dec i malmovwf J ; J = w

jloop: movwf K ; K = wkloop: decfsz K,f ; K = K-1, skip next if zero

goto kloopdecfsz J,f ; J = J-1, skip next if zero

800 Appendix H

Page 822: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

goto jloopre turn

;=============================; LCD dis play pro ce dure;=============================; Sends 16 char ac ters from PIC buffer with ad dress stored; in vari able pic_ad to LCD line pre vi ously se lecteddisplay16:; Set up for data

bcf porta,E_line ; E line lowbsf porta,RS_line ; RS line low for con trolcall de lay_125 ; De lay

; Set up coun ter for 16 char ac tersmovlw D'16' ; Coun ter = 16movwf count3

; Get dis play ad dress from lo cal vari able pic_admovf pic_ad,w ; First dis play RAM ad dress to Wmovwf fsr ; W to FSR

getchar:movf indf,w ; get char ac ter from dis play RAM

; lo ca tion pointed to by file se lect; reg is ter

movwf portbcall pulseE ;send data to dis play

; Test for 16 char ac ters dis playeddecfsz count3,f ; Dec re ment coun tergoto nextchar ; Skipped if donere turn

nextchar:incf fsr,f ; Bump pointergoto getchar

;========================; blank buffer;========================; Pro ce dure to store 16 blank char ac ters in PIC RAM; buffer start ing at ad dress stored in the vari able; pic_adblank16:

movlw D'16' ; Setup coun termovwf count1movf pic_ad,w ; First PIC RAM ad dressmovwf fsr ; In dexed ad dress ingmovlw 0x20 ; ASCII space char ac ter

storeit:movwf indf ; Store blank char ac ter in PIC RAM

; buffer us ing fsr reg is terdecfsz count1,f ; Done?goto incfsr ; no

Additional Code 801

Page 823: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

re turn ; yesincfsr:

incf fsr,f ; Bump fsr to next bufferspace

goto storeit;========================; Set ad dress reg is ter; to LCD line 1;========================; ON ENTRY:; Ad dress of LCD line 1 in con stant LCD_1 line1:

bcf porta,E_line ; E line lowbcf porta,RS_line ; RS line low, set up for

; con trolcall de lay_125 ; de lay 125 mi cro sec onds

; Set to sec ond dis play linemovlw LCD_1 ; Ad dress and com mand bitmovwf portbcall pulseE ; Pulse and de lay

; Set RS line for databsf porta,RS_line ; Setup for datacall de lay_125 ; De layre turn

;========================; Set ad dress reg is ter; to LCD line 2;========================; ON ENTRY:; Ad dress of LCD line 2 in con stant LCD_2 line2:

bcf porta,E_line ; E line lowbcf porta,RS_line ; RS line low, setup for

; con trolcall de lay_125 ; de lay

; Set to sec ond dis play linemovlw LCD_2 ; Ad dress with high-bit setmovwf portbcall pulseE ; Pulse and de lay

; Set RS line for databsf porta,RS_line ; RS = 1 for datacall de lay_125 ; de layre turn

;===============================; first text string pro ce dure;===============================storeMSU:

802 Appendix H

Page 824: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; Pro ce dure to store in PIC RAM buffer the mes sage; con tained in the code area la beled msg1; ON ENTRY:; vari able pic_ad holds ad dress of text buffer; in PIC RAM; w reg is ter holds off set into stor age area; msg1 is rou tine that re turns the string char ac ters; and a zero ter mi na tor; in dex is lo cal vari able that holds off set into; text ta ble. This vari able is also used for; tem po rary stor age of off set into buffer ; ON EXIT:; Text mes sage stored in buffer;; Store off set into text buffer (passed in the w reg is ter); in tem po rary vari able

movwf in dex ; Store w in in dex; Store base ad dress of text buffer in fsr

movf pic_ad,w ; first dis play RAM ad dress to Waddwf in dex,w ; Add off set to ad dressmovwf fsr ; W to FSR

; Ini tial ize in dex for text string ac cessmovlw 0 ; Start at 0movwf in dex ; Store in dex in vari able

; w still = 0get_msg_char:

call msg1 ; Get char ac ter from ta ble; Test for zero ter mi na tor

andlw 0x0ffbtfsc sta tus,z ; Test zero flaggoto endstr1 ; End of string

; ASSERT: valid string char ac ter in w; store char ac ter in text buffer (by fsr)

movwf indf ; store in buffer by fsrincf fsr,f ; in cre ment buffer pointer

; Re store ta ble char ac ter coun ter from vari ablemovf in dex,w ; Get value into waddlw 1 ; Bump to next char ac termovwf in dex ; Store ta ble in dex in vari ablegoto get_msg_char ; Con tinue

endstr1:re turn

; Rou tine for re turn ing mes sage stored in pro gram areamsg1:

addwf PCL,f ; Ac cess ta bleretlw 'M'retlw 'i'

Additional Code 803

Page 825: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

retlw 'n'retlw 'n'retlw 'e'retlw 's'retlw 'o'retlw 't'retlw 'a'retlw 0

;=================================; sec ond text string pro ce dure;=================================storeUniv:; Pro cessing iden ti cal to pro ce dure StoreMSU

movwf in dex ; Store w in in dex; Store base ad dress of text buffer in fsr

movf pic_ad,0 ; first dis play RAM ad dress to Waddwf in dex,0 ; Add off set to ad dressmovwf fsr ; W to FSR

; Ini tial ize in dex for text string ac cessmovlw 0 ; Start at 0movwf in dex ; Store in dex in vari able

; w still = 0get_msg_char2:

call msg2 ; Get char ac ter from ta ble; Test for zero ter mi na tor

andlw 0x0ffbtfsc sta tus,z ; Test zero flaggoto endstr2 ; End of string

; ASSERT: valid string char ac ter in w; store char ac ter in text buffer (by fsr)

movwf indf ; Store in buffer by fsrincf fsr,f ; In cre ment buffer pointer

; Re store ta ble char ac ter coun ter from vari ablemovf in dex,w ; Get value into waddlw 1 ; Bump to next char ac termovwf in dex ; Store ta ble in dex in vari ablegoto get_msg_char2 ; Con tinue

endstr2:re turn

; Rou tine for re turn ing mes sage stored in pro gram areamsg2:

addwf PCL,f ; Ac cess ta bleretlw 'S'retlw 't'retlw 'a'retlw 't'

804 Appendix H

Page 826: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

retlw 'e'retlw ','retlw 0x20retlw 'M'retlw 'a'retlw 'n'retlw 'k'retlw 'a'retlw 't'retlw 'o'retlw 0

end

Additional Code 805

Page 827: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; File: Timer0.ASM; Date: April 27, 2006; Au thor: Julio Sanchez; Pro ces sor: a6F84A;; De scrip tion:; Pro gram to dem on strate pro gram ming of the 16F84A; TIMER0 mod ule. Pro gram flashes eight LEDs in se quence; count ing from 0 to 0xff. Timer0 is used to de lay; the count.;===========================; switches;===========================; Switches used in __config di rec tive:; _CP_ON Code pro tec tion ON/OFF ; * _CP_OFF ; * _PWRTE_ON Power-up timer ON/OFF; _PWRTE_OFF ; _WDT_ON Watchdog timer ON/OFF ; * _WDT_OFF ; _LP_OSC Low power crys tal oscillator; * _XT_OSC Ex ter nal par al lel crys tal oscillator ; _HS_OSC High speed crys tal res o na tor (8 to 10 MHz); Res o na tor: Murate Erie CSA8.00MG = 8 MHz ; _RC_OSC Re sis tor/ca pac i tor oscillator; (sim plest, 20% er ror); |; |_____ * in di cates setup val ues

pro ces sor 16f84Ain clude <p16f84A.inc>__config _XT_OSC & _WDT_OFF & _PWRTE_ON & _CP_OFF

;=====================================================; vari ables in PIC RAM;=====================================================; None in this ap pli ca tion;;========================================================; m a i n p r o g r a m;========================================================

org 0 ; start at ad dress 0goto main

;;=============================; in ter rupt han dler;=============================

org 0x08;=============================

806 Appendix H

Page 828: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; main pro gram;=============================main:; Clear the Watchdog timer and re set prescaler

clrwdt; Set up the OPTION regiser bitmap

movlw b'11010111'; 7 6 5 4 3 2 1 0 <= OPTION bits; | | | | | |__|__|_____ PS2-PS0 (prescaler bits); | | | | | Values for Timer0; | | | | | 000 = 1:2 001 = 1:4; | | | | | 010 = 1:8 011 = 1:16; | | | | | 100 = 1:32 101 = 1:64; | | | | | 110 = 1:128 *111 = 1:256; | | | | |______________ PSA (prescaler as sign); | | | | 1 = to WDT; | | | | *0 = to Timer0; | | | |_________________ TOSE (Timer0 edge se lect); | | | 0 = in cre ment on low-to-high; | | | *1 = in cre ment on high-to-low; | | |____________________ TOCS (TMR0 clock source); | | *0 = in ter nal clock; | | 1 = RA4/TOCKI bit source; | |_______________________ INTEDG (Edge se lect); | *0 = fall ing edge; |__________________________ RBPU (Pullup en able); 0 = en abled; *1 = disabled

op tion; Setup ports

movlw 0x00 ; Set port B to out puttris PORTBclrf PORTB ; All port B to 0

; Port A is not used in this pro grammloop:

incf PORTB,f ; Add 1 to reg is ter valuecall TM0delaygoto mloop

;******************************; de lay sub-rou tine; uses Timer0;******************************TM0delay:; Ini tial ize the timer reg is ter

clrf TMR0 ; Clear SFR for Timer0; Rou tine tests the value in the TMR0 reg is ter by; sub tract ing 0xff from the value in TMR0. The zero flag; is set if TMR0 = 0xff

Additional Code 807

Page 829: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

cy cle:movf TMR0,w ; Timer to w

; w has TMR0 reg is ter valuesublw 0xff ; Sub tract max value

; Zero flag is set if value in TMR0 = 0xffbtfss STATUS,Z ; Test for zerogoto cy cle ; Re peatre turn

End

808 Appendix H

Page 830: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; File: TimerTst.ASM; Date: June 7, 2010; Au thors: Sanchez and Canton;; De scrip tion:; Using the timer to gen er ate a sig nal at 1 MHz;;===========================; switches;===========================; Switches used in __config di rec tive:; _CP_ON Code pro tec tion ON/OFF ; * _CP_OFF ; * _PWRTE_ON Power-up timer ON/OFF; _PWRTE_OFF ; _WDT_ON Watchdog timer ON/OFF ; * _WDT_OFF ; _LP_OSC Low power crys tal oscillator; * _XT_OSC Ex ter nal par al lel crys tal oscillator ; _HS_OSC High speed crys tal res o na tor (8 to 10 MHz); Res o na tor: Murate Erie CSA8.00MG = 8 MHz ; _RC_OSC Re sis tor/ca pac i tor oscillator; (sim plest, 20% er ror); |; |_____ * in di cates setup val ues

pro ces sor 16f84Ain clude <p16f84A.inc>__config _XT_OSC & _WDT_OFF & _PWRTE_ON & _CP_OFF

;=====================================================; PIC reg is ter equates;=====================================================

porta equ 0x05Portb equ 0x06Status equ 0x03z equ 0x02tmr0 equ 0x01

;;=====================================================; vari ables in PIC RAM;=====================================================; Lo cal vari ables

cblock 0x0d ; Start of blockJ ; coun ter JK ; coun ter KcountL ; Aux il iary coun tercountH ; ISR coun ter

Additional Code 809

Page 831: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

endc;========================================================; m a i n p r o g r a m;========================================================

org 0 ; start at ad dress 0goto main

;;=============================; in ter rupt han dler;=============================

org 0x04; goto IntServ;=============================; main pro gram;=============================main:; Clear the Watchdog timer and re set prescaler

clrwdt; Set up the OPTION regiser bitmap

movlw b'11010011'; 7 6 5 4 3 2 1 0 <= OPTION bits; | | | | | |__|__|_____ PS2-PS0 (prescaler bits); | | | | | Values for Timer0; | | | | | 000 = 1:2 001 = 1:4; | | | | | 010 = 1:8 011 = 1:16; | | | | | 100 = 1:32 101 = 1:64; | | | | | 110 = 1:128 *111 = 1:256; | | | | |______________ PSA (prescaler as sign); | | | | 1 = to WDT; | | | | *0 = to Timer0; | | | |_________________ TOSE (Timer0 edge se lect); | | | 0 = in cre ment on low-to-high; | | | *1 = in cre ment on high-to-low; | | |____________________ TOCS (TMR0 clock source); | | *0 = in ter nal clock; | | 1 = RA4/TOCKI bit source; | |_______________________ INTEDG (Edge se lect); | *0 = fall ing edge; |__________________________ RBPU (Pullup en able); 0 = en abled; *1 = disabled

op tion; Set up ports

movlw 0x00 ; Set port B for out puttris portbclrf portb ; All port B to 0

; Port A is not used in this pro grammloop:

810 Appendix H

Page 832: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

bsf portb,0call TM0delaybcf portb,0call TM0delaygoto mloop

;******************************; de lay sub-rou tine; uses Timer0;******************************TM0delay:; Ini tial ize the timer reg is ter

clrf tmr0 ; Clear SFR for Timer0; Rou tine tests the value in the tmr0 reg is ter by; xoring with a mask of all ones. The op er a tion sets; the zero flag if tmr0 is zero.cy cle:

movf tmr0,w ; Timer to w; w has tmr0 reg is ter value

sublw 0xff ; Sub tract max value; Zero flag is set if value in tmr0 = 0xff

btfss sta tus,z ; Test for zerogoto cy cle ; Re peatre turn

end

Additional Code 811

Page 833: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; File name: TTYUsart.asm; Last up date: May 12, 2009; Au thors: Sanchez and Canton; Pro ces sor: 16F84A;; De scrip tion:; Pro gram to em u late USART op er a tion in PIC code. Uses; PIC-to-LCD in ter face. Dis play has two lines, each with; sixteen char ac ters.; Pro gram op er a tion:; Char ac ters re ceived from the RS232 line are dis played on; the LCD. LCD lines scroll au to mat i cally. A pushbutton; ac ti vates the send op er a tion by transmitting the text; string "Ready-", which is also dis played on the LCD.;; Pro gram com mu ni ca tions and LCD pa ram e ters are stored in; #de fine state ments. These state ments can be ed ited to; accommodate a dif fer ent set up. Pro gram uses de lay loops; for in ter face tim ing.;; WARNING:; Code as sumes 4 MHz clock. De lay rou tines must be; ed ited for faster clock;; BAUD RATE CALCULATIONS:; A 4 MHz clock os cil la tor has a clock fre quency of 1 MHz:; because the baud rate is the num ber of clock cy cles per; sec ond, for a 4 MHz clock it is:; 1; bit time = ------ sec. = 208.33 mi cro sec onds; 4,800 ; Cal cu lating one half the baud rate al lows resetting the; clock from the edge to the cen ter of a time pulse:;; |<======== fall ing edge of start bit; | |<======== cen ter of bit time; >| |< one-half baud rate; | |;__________. | .____________. ; |_____________| |________ ; 208/2 = 104 ; The PIC clock counts up from 0 to 255. So to im ple ment; a 104-mi cro sec ond de lay, we must start count ing at; clock beat:; 255 - 104 = 151; plus one mi cro sec ond for movlw in struc tion used to; ini tial ize the clock:; 151 + 1 = 152

812 Appendix H

Page 834: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; For one full baud rate de lay:; 255 - 208 = 47 + 1 = 48 ; The fol low ing two con stants are stored in #de fine; state ments:; halfBaud = 152; fullBaud = 48 ; Set ting the prescaler to TMR0 re duces the baud rate; to one-half. Other prescaler val ues will re duce the; baud rate ac cord ingly.;; Wiring di a gram:; RB4-RB7 ===> LCD data lines 4 to 7 (out put); RB0 =======> MAX202 T2in line (out put); RA0 =======> MAX202 R2out line (in put); RA1 =======> LCD E line (out put); RA2 =======> LCD RS line (out put); RA3 =======> LCD R/W line (out put - not used); RA4 =======> Pushbutton switch 1; (in put - ac tive low);;===========================; switches;===========================; Switches used in __config di rec tive:; _CP_ON Code pro tec tion ON/OFF ; * _CP_OFF ; * _PWRTE_ON Power-up timer ON/OFF; _PWRTE_OFF ; _WDT_ON Watchdog timer ON/OFF ; * _WDT_OFF ; _LP_OSC Low power crys tal oscillator; * _XT_OSC Ex ter nal par al lel crys tal oscillator ; _HS_OSC High speed crys tal res o na tor (8 to 10 MHz); Res o na tor: Murate Erie CSA8.00MG = 8 MHz ; _RC_OSC Re sis tor/ca pac i tor oscillator; | (sim plest, 20% er ror); |; |_____ * in di cates setup val ues pres ently se lected

;=========================; setup and con fig u ra tion;=========================

pro ces sor 16f84Ain clude <p16f84A.inc>__config _XT_OSC & _WDT_OFF & _PWRTE_ON & _CP_OFF

;============================================================; M A C R O S

Additional Code 813

Page 835: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

;============================================================; Macros to se lect the reg is ter banksBank0 MACRO ; Se lect RAM bank 0

bcf STATUS,RP0ENDM

Bank1 MACRO ; Se lect RAM bank 1bsf STATUS,RP0ENDM

;============================================================; con stant def i ni tions; for PIC-to-LCD pin wir ing and LCD line ad dresses;============================================================#de fine E_line 1 ;|#de fine RS_line 2 ;| -- from wir ing di a gram #de fine RW_line 3 ;|; LCD line ad dresses (from LCD datasheet)#de fine LCD_1 0x80 ; First LCD line con stant#de fine LCD_2 0xc0 ; Sec ond LCD line con stant#de fine LCDlimit .16; Num ber of char ac ters per line; 4800 baud clock count down val ues; Code re duces rate to 2400 baud by en ter ing a min i mal; presclaer to TRM0#de fine halfBaud .152 ; For one-half bit time#de fine fullBaud .48 ; For one full bit time;; Note: The con stants that de fine the LCD dis play line; ad dresses have the high-or der bit set in; or der to faciliate the con trol ler com mand. ;;=====================================================; PIC reg is ter and flag equates;=====================================================z equ 2 ; Zero flagc equ 0 ; Carry flag;=====================================================; buffer and vari ables in PIC RAM;=====================================================; Cre ate a 16-byte stor age area

cblock 0x0c ; Start of first data blocklineBuf ; buffer for text stor ageendc

; Leave 16 bytes and Con tinue with lo cal vari ablescblock 0x1c ; Sec ond data blockcount1 ; Coun ter # 1count2 ; Coun ter # 2J ; coun ter JK ; coun ter K

814 Appendix H

Page 836: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

store1 ; Lo cal tem po rary stor age store2 ; Stor age # 2

; For LCDscroll pro ce dureLCDcount ; Coun ter for char ac ters per lineLCDline ; Cur rent dis play line (0 or 1)bufPtr ; Buffer pointer

; Vari ables for se rial com mu ni ca tionstempData ; Tem po rary stor age for bit ma nip u la tionsrcvData ; Fi nal stor age for re ceived char ac terbitCount ; Bit coun tersendData ; Char ac ter to sendendc

;=========================================================; m a i n p r o g r a m ;=========================================================

org 0 ; start at ad dress goto main

; Space for in ter rupt han dlersorg 0x08

main:Bank1movlw b'00010001' ; Port A lines I/O setup

; RA0 = RS232 in put (R2out); RA4 = Pushbutton SW # 1

movwf TRISAmovlw b'00000000' ; Port B lines as fol lows:

; RB4-RB7 ===> LCD data lines 4 to 7 (out put); RB0 =======> MAX202 T2in line (out put) ; RB0 =

movwf TRISBBank0

; Clear bits in port A out put linesbcf PORTA,1bcf PORTA,2bcf PORTA,3movlw b'00000000' ; All out puts ports lowmovwf PORTB

; Wait and ini tial ize HD44780call de lay_5 ; Al low LCD time to ini tial ize

; it selfcall de lay_5call initLCD ; Then do forced ini tial iza tioncall de lay_5 ; Wait again

; Set port B, line 0 high so start bit is de tectedbsf PORTB,0

;============================

Additional Code 815

Page 837: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; wait for start com mand;============================; Pro gram waits un til pushbutton num ber 1 is pressed; to con tinue ex e cu tion. Pushbutton 1 is ac tive low; and wired to RA4pb1Wait:

btfsc PORTA,4 ; Test port A, line 4goto pb1Wait ; Loop if not clear

;============================; dis play and send "Ready-";============================; Set LCD base ad dress

call line1; Ini tial ize sys tem for UART em u la tion at 2400 baud

call initTTY; Dis play on LCD and test se rial trans mis sion by send ing; the string "Ready-"

movlw 'R'movwf sendData ; Store in send reg is tercall send8 ; Lo cal LCD dis play pro ce durecall sendTTY ; Lo cal send pro ce duremovlw 'e'movwf sendData ; Store in send reg is tercall send8 ; Lo cal LCD dis play pro ce durecall sendTTY ; Lo cal send pro ce duremovlw 'a'movwf sendData ; Store in send reg is tercall send8 ; Lo cal LCD dis play pro ce durecall sendTTY ; Lo cal send pro ce duremovlw 'd'movwf sendData ; Store in send reg is tercall send8 ; Lo cal LCD dis play pro ce durecall sendTTY ; Lo cal send pro ce duremovlw 'y'movwf sendData ; Store in send reg is tercall send8 ; Lo cal LCD dis play pro ce durecall sendTTY ; Lo cal send pro ce duremovlw '-'movwf sendData ; Store in send reg is tercall send8 ; Lo cal LCD dis play pro ce durecall sendTTY ; Lo cal send pro ce dure

; Init char ac ter coun ter and line coun ter vari ables for; LCD line scroll pro ce dure

movlw 0x06 ; 6 char ac ters al readydis played

movwf LCDcountclrf LCDline ; LCD line coun ter

;============================

816 Appendix H

Page 838: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; mon i tor RS232 line;============================nextChar:

call rcvTTY ; Re ceive char ac ter; Store char ac ter in lo cal line buffer us ing in di rect; ad dress ing; 16-byte buffer named lineBuf starts at ad dress 0x0c; Reg is ter vari able bufPtr holds off set into buffer movlw 0x0c ; Buffer base ad dress

addwf bufPtr,w ; Add pointer in wmovwf FSR ; Value to in dex reg is termovf rcvData, ; Char ac ter into wmovwf INDF ; Store w in [FSR]incf bufPtr,f ; Bump pointer

; Send char ac ter (still in w) call send8 ; Dis play itcall LCDscroll ; Scroll dis play linesgoto nextChar ; Con tinue

;============================================================; ini tial ize LCD for 4-bit mode ;============================================================initLCD:; Ini tial iza tion for Densitron LCD mod ule as fol lows:; 4-bit in ter face; 2 dis play lines of 16 char ac ters each; cur sor on; left-to-right in cre ment; cur sor shift right; no dis play shift;=======================|; set com mand mode |;=======================|

bcf PORTA,E_line ; E line lowbcf PORTA,RS_line ; RS line lowbcf PORTA,RW_line ; Write modecall de lay_125 ; de lay 125

mi cro sec onds;***********************|; FUNCTION SET |;***********************|

movlw 0x28 ; 0 0 1 0 1 0 0 0 (FUNCTION SET); | | | |__ font se lect:; | | | 1 = 5x10 in 1/8 or 1/11; | | | 0 = 1/16 dc; | | |___ Duty cy cle se lect; | | 0 = 1/8 or 1/11

Additional Code 817

Page 839: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; | | 1 = 1/16 ; | |___ In ter face width; | 0 = 4 bits; | 1 = 8 bits; |___ FUNCTION SET COMMAND

call send8 ; 4-bit send rou tine

; Set 4-bit mode com mand must be re peatedmovlw 0x28call send8

;***********************|; DISPLAY AND CURSOR ON |;***********************|

movlw 0x0e ; 0 0 0 0 1 1 1 0 (DISPLAY ON/OFF); | | | |___ Blink char ac ter; | | | 1 = on, 0 = off; | | |___ Cursor on/off; | | 1 = on, 0 = off; | |____ Dis play on/off; | 1 = on, 0 = off; |____ COMMAND BIT

call send8;***********************|; set en try mode |;***********************|

movlw 0x06 ; 0 0 0 0 0 1 1 0 (ENTRY MODE SET); | | |___ dis play shift; | | 1 = shift; | | 0 = no shift; | |____ in cre ment mode; | 1 = left-to-right; | 0 = right-to-left; |___ COMMAND BIT

call send8

;***********************|; cur sor/dis play shift |;***********************|

movlw 0x14 ; 0 0 0 1 0 1 0 0 (CURSOR/DISPLAY; SHIFT); | | | |_|___ don't care; | |_|__ cur sor/dis play shift; | 00 = cur sor shift left; | 01 = cur sor shift right; | 10 = cur sor and dis play; | shifted left; | 11 = cur sor and dis play

818 Appendix H

Page 840: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; | shifted right; |___ COMMAND BIT

call send8;***********************|; clear dis play |;***********************|

movlw 0x01 ; 0 0 0 0 0 0 0 1 (CLEAR DISPLAY); |___ COMMAND BIT

call send8; Per doc u men ta tion

call de lay_5 ; Test for busyre turn

;=======================; Pro ce dure to de lay; 42 mi cro sec onds;=======================de lay_125

movlw D'42' ; Re peat 42 ma chine cy clesmovwf count1 ; Store value in coun ter

re peatdecfsz count1,f ; Dec re ment coun tergoto re peat ; Con tinue if not 0re turn ; End of de lay

;=======================; Pro ce dure to de lay; 5 mil li sec onds;=======================de lay_5

movlw D'41' ; Coun ter = 41movwf count2 ; Store in vari able

de laycall de lay_125 ; De laydecfsz count2,f ; 40 times = 5 mil li sec ondsgoto de layre turn ; End of de lay

;========================; pulse E line ;========================pulseE

bsf PORTA,E_line ; Pulse E linenopbcf PORTA,E_linere turn

;=============================; long de lay sub-rou tine; (for de bug ging)

Additional Code 819

Page 841: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

;=============================long_de lay

movlw D'200' ; w = 200 dec i malmovwf J ; J = w

jloop: movwf K ; K = wkloop: decfsz K,f ; K = K-1, skip next if zero

goto kloopdecfsz J,f ; J = J-1, skip next if zerogoto jloopre turn

;========================; send 2 nib bles in; 4-bit mode;========================; Pro ce dure to send two 4-bit val ues to port B lines; 7, 6, 5, and 4. High-or der nib ble is sent first; ON ENTRY:; w reg is ter holds 8-bit value to sendsend8:

movwf store1 ; Save orig i nal valuecall merge4 ; Merge with port B

; Now w has merged bytemovwf PORTB ; w to port Bcall pulseE ; Send data to LCD

; High nib ble is sentmovf store1,w ; Re cover byte into wswapf store1,w ; Swap nib bles in wcall merge4movwf PORTBcall pulseE ; Send data to LCDcall de lay_125 re turn

;=================; merge bits;=================; Rou tine to merge the four high-or der bits of the; value to send with the con tents of port B; so as to pre serve the four low-bits in port B; Logic:; AND value with 1111 0000 mask; AND port B with 0000 1111 mask; Now low nib ble in value and high nib ble in; port B are all 0 bits:; value = vvvv 0000; port B = 0000 bbbb; OR value and port B re sult ing in:; vvvv bbbb ; ON ENTRY:

820 Appendix H

Page 842: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; w con tain value bits; ON EXIT:; w con tains merged bitsmerge4:

andlw b'11110000' ; ANDing with 0 clears the; bit. ANDing with 1 pre serves; the orig i nal value

movwf store2 ; Save re sult in vari ablemovf PORTB,w ; port B to w reg is terandlw b'00001111' ; Clear high nib ble in port B

; and pre serve low nib bleiorwf store2,w ; OR two operands in wre turn

;========================; Set ad dress reg is ter; to LCD line 1;========================; ON ENTRY:; Ad dress of LCD line 1 in con stant LCD_1 line1:

bcf PORTA,E_line ; E line lowbcf PORTA,RS_line ; RS line low, set up for

; con trolcall de lay_5 ; busy?

; Set to sec ond dis play linemovlw LCD_1 ; Ad dress and com mand bitcall send8 ; 4-bit rou tine

; Set RS line for databsf PORTA,RS_line ; Setup for datacall de lay_5 ; Busy?

; Clear buffer and pointercall blankBufclrf bufPtr ; Clear re turn

;========================; Set ad dress reg is ter; to LCD line 2;========================; ON ENTRY:; Ad dress of LCD line 2 in con stant LCD_2 line2:

bcf PORTA,E_line ; E line lowbcf PORTA,RS_line ; RS line low, setup for

con trolcall de lay_5 ; Busy?

; Set to sec ond dis play linemovlw LCD_2 ; Ad dress with high-bit set

Additional Code 821

Page 843: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

call send8; Set RS line for data

bsf PORTA,RS_line ; RS = 1 for datacall de lay_5 ; Busy?

; Clear buffer and pointercall blankBufclrf bufPtrre turn

;==========================; scroll LCD line 2 ;==========================; Pro ce dure to count the num ber of char ac ters dis played on; each LCD line. If the num ber reaches the value in the; con stant LCDlimit, then dis play is scrolled to the sec ond; LCD line. If at the end of the sec ond line, then the; sec ond line is scrolled to the first line and dis play; con tin ues at the start of the sec ond line; re set to the first line.LCDscroll:

incf LCDcount,f ; Bump coun ter; Test for line limit

movf LCDcount,wsublw LCDlimit ; Count mi nus limitbtfss STATUS,z ; Is count - limit = 0goto scrollExit ; Go if not at end of line

; At this point the end of the LCD line was reached; Test if this is also the end of the sec ond line

movf LCDline,wsublw 0x01 ; Is it line 1?btfsc STATUS,z ; Is LCDline mi nus 1 = 0?goto line2End ; Go if end of sec ond line

; At this point it is the end of the top LCD linecall line2 ; Scroll to sec ond lineclrf LCDcount ; Re set coun terincf LCDline,f ; Bump line coun tergoto scrollExit

; End of sec ond LCD line;line2End:; Scroll sec ond line to first line. Char ac ters to be; scrolled are stored in buffer start ing at ad dress 0x0c.; 16 char ac ters are to be moved.; First clear LCD

call initLCDcall de lay_5 ; Make sure not busy

; Set up for databcf PORTA,E_line ; E line low

822 Appendix H

Page 844: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

bsf PORTA,RS_line ; RS line high for data; Set up coun ter for 16 char ac ters

movlw D'16' ; Coun ter = 16movwf count2

; Get ad dress of stor age buffermovlw 0x0cmovwf FSR ; W to FSR

getchar:movf INDF,w ; get char ac ter from dis play RAM

; lo ca tion pointed to by file se lect; reg is ter

call send8 ; 4-bit in ter face rou tine; Test for 16 char ac ters dis played

decfsz count2,f ; Dec re ment coun tergoto nextchar ; Skipped if done

; At this point scroll op er a tion has con cludedclrf LCDcount ; Clear coun ters

; Stay at line 2clrf LCDlineincf LCDline,fcall line2 ; Set for sec ond line

scrollExit:re turn

nextchar:incf FSR,f ; Bump pointergoto getchar

;============================; clear line buffer;============================; Use in di rect ad dress ing to store 16 blanks in the; buffer lo cated at 0x0c blankBuf:

Bank0movlw 0x0c ; Pointer to RAMmovwf FSR ; To in dex reg is ter

blank16:clrf INDF ; Clear memory pointed at by FSRincf FSR,f ; Bump pointerbtfss FSR,4 ; 000x0000 when bit 4 is set

; count reached 16goto blank16re turn

;============================================================; ini tial ize for TTY;============================================================; Pro ce dure to ini tial ize RS232 re cep tion

Additional Code 823

Page 845: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; As sumes:; 2400 baud; 8 data bits; no par ity; one stop bitinitTTY:; First ini tial ize re ceiver to RS-232 line pa ram e ters; Dis able global and pe riph eral in ter rupts; 7 6 5 4 3 2 1 0 <= INTCON bitmap; | ? | ? ? ? ? ? (? = un re lated bits); | |________________ Timer0 in ter rupt on over flow; |______________________ Global in ter rupts

bcf INTCON,5 ; Dis able TMR0 in ter ruptsbcf INTCON,7 ; Disable global in ter ruptsclrf TMR0 ; Re set timerclrwdt ; Clear WDT for prescaler

; as signBank1

; Set up the OPTION register bitmap; 7 6 5 4 3 2 1 0 <= OPTION bits; 1 1 0 1 1 0 0 0 <= setup; | | | | | |__|__|_____ PS2-PS0 (prescaler bits); | | | | | Values for Timer0; | | | | | *000 = 1:2 001 = 1:4; | | | | | 010 = 1:8 011 = 1:16; | | | | | 100 = 1:32 101 = 1:64; | | | | | 110 = 1:128 111 = 1:256; | | | | |______________ PSA (prescaler as sign); | | | | 1 = to WDT; | | | | *0 = to Timer0; | | | |_________________ TOSE (Timer0 edge se lect); | | | 0 = in cre ment on low-to-high; | | | *1 = in cre ment in high-to-low; | | |____________________ TOCS (TMR0 clock source); | | *0 = in ter nal clock; | | 1 = RA4/TOCKI bit source; | |_______________________ INTEDG (Edge se lect); | 0 = fall ing edge; | *1 = ris ing edge; |__________________________ RBPU (Pullup en able); 0 = en abled; *1 = disabled

movlw b'11010000' ; set up timer/coun termovwf OPTION_REGBank0re turn

;============================================================; re ceive char ac ter

824 Appendix H

Page 846: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

;============================================================; Re ceive a sin gle char ac ter through the se rial port.; As sumes: 4800 baud, 8 data bits, no par ity, 1 stop bit.; Recieving line is Port A, line 0rcvTTY:

movlw 0x08 ; Coun ter for 8 bitsmovwf bitCount

; The start of char ac ter trans mis sion is sig naled by; the sender by set ting the line lowstartBit:

btfsc PORTA,0 ; Test for low on linegoto startBit ; Go if not low

;=========================; off set to data bit;=========================; At this point the re ceiver has found the fall ing; edge of the start bit. It must now wait one and; one-half the baud rate to syn chro nize in the cen ter; of the sender's first data bit;, as fol lows:; |<========= fall ing edge of START bit; | |<========== cen ter of start bit; | | |<====== cen ter of data bit; |-----------|-----|;_____ ___________ __________; | | | | <== SIGNAL; ----------- ---------- ; |<-- 208 -->|<104>| <====== ms. for 4800 baud; ; Clock start count for one-half bit = 255 - 104 = 151; Clock start count for one full bit = 255 - 208 = 47; One clock cy cle is added for the movwf intruction: ; clkHalf = 152 (for one-half bit count down); clkFull = 48 (for one full bit count down)

movlw halfBaud ; Skip one-half bitmovwf TMR0 ; Ini tial ize tmr0 and start countbcf INTCON,2 ; Clear over flow flag

;============================; start bit;============================wait1:

btfss INTCON,2 ; Timer count over flow?goto wait1 ; No, keep wait ing

; At this point we are at the cen ter of the start bitbtfsc PORTA,0 ; Check to see it is still lowgoto startBit ; No, it is high. False start

; At this point the clock is at the cen ter of the start; bit. The first data bit must be read one full baud

Additional Code 825

Page 847: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; pe riod latermovlw fullBaud ; One full bit de laymovwf TMR0 ; Start timerbcf INTCON,2 ; clear tmr0 over flow flag

wait2:btfss INTCON,2 ; End of one full baud pe riod?goto wait2 ; Wait if not end of pe riod

; Timer is now at the cen ter of the first/next data bit; Timer must be re set im me di ately so that code will not; lose synchronization with sender

movlw fullBaud ; Skip to next data bitmovwf TMR0 ; Re start timerbcf INTCON,2 ; Re set over flow flag

; Now the data bit can be read and storedmovf PORTA,w ; Read port Bmovwf tempData ; Store in tem po rary vari ablerrf tempData,f ; Ro tate bit 0 into carry flagrrf rcvData,f ; Ro tate carry flag into stor age

; reg is ter high-or der bitdecfsz bitCount,f ; End of data?goto wait2 ; Con tinue un til 8 bits re ceived

;============================; stop bit;============================stopWait:

btfss INTCON,2 ; Test timegoto stopWait ; Waitre turn ; Exit

;============================================================; send char ac ter;============================================================; Pro ce dure to send one char ac ter through the RS232 line.; As sumes: 2400 baud, 8 data bits, no par ity, one stop bit; Sending line is Port B, line 0; ON ENTRY:; vari able sendData holds char ac ter to sendsendTTY:

movlw 0x08 ; Init bit coun termovwf bitCountbcf PORTB,0 ; Low for start bitmovlw fullBaud ; For one baud spacemovwf TMR0 ; Start timerbcf INTCON,2 ; Clear timer flag

start2snd:btfss INTCON,2 ; Full baud done?goto start2snd ; Nomovlw fullBaud ; Re set for one full bit

826 Appendix H

Page 848: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; pe riodmovwf TMR0 ; Start timerbcf INTCON,2 ; Clear flag

; At this point the start bit has been sent; Data fol lowssendOut:

rrf sendData,f ; Ro tate bit into carrybcf PORTB,0 ; As sume data bit is 0btfsc STATUS,c ; Test if carry setbsf PORTB,0 ; Change bit to 1 if clear

; Hold bit for 1 baud pe riodtimeBit:

btfss INTCON,2 ; Wait for baud pe riod to endgoto timeBit ; Loop if not yetmovlw fullBaud ; Re set timermovwf TMR0 ; Start timerbcf INTCON,2 ; Clear flag

; Test for last bitdecfsz bitCount,f ; Count this bitgoto sendOut ; Con tinue if not last bit

; Done. Send stop bitbsf PORTB,0 ; High for stop bit

stopBit:btfss INTCON,2 ; Timer done?goto stopBit ; No

; Set port B line 0 high back againbsf PORTB,0call de lay_5 ; And hold re turn

End

Additional Code 827

Page 849: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; File name: I2CEEP.asm; Last re vi sion: May 28, 2010; Au thors: Sanchez and Canton; Pro ces sor: 16F877;; De scrip tion:; Re ceive char ac ter data through RS-232 line and store in; 24LC04B EEPROM IC, us ing the I2C se rial pro to col in the; PIC's MSSP mod ule. Re ceived char ac ters are ech oed on; the sec ond LCD line. When <En ter> key is de tected (code; 0x0d) the text stored in EEPROM mem ory is re trieved and; dis played on the LCD. On startup the top LCD line dis plays; the prompt: "Re ceiving:". At that time a mes sage "Rdy- " is; sent through the se rial line so as to test the con nec tion.;; De fault se rial line set ting:; 2400 baud; no par ity; 1 stop bit; 8 char ac ter bits;; Wiring:; 24LC04B SDA line is wired to PIC RC4 (MSSP SDA); 24LC04B SCL line is wired to PIC RC3 (MSSP SCL); 24LC04B A0-A2 and WP lines are not used (GND);; Pro gram to uses 4-bit PIC-to-LCD in ter face.; Code as sumes that LCD is driven by Hitachi HD44780; con trol ler and PIC 16F877. Dis play sup ports two lines; each one with 20 char ac ters. The length, wir ing, and base; ad dress of each dis play line is stored in #de fine; state ments. These state ments can be ed ited to acommodate; a dif fer ent set up.; ; WARNING:; Code as sumes 10-MHz clock. De lay rou tines must be; ed ited for a dif fer ent clock. Clock speed also de ter mines; val ues for baud rate set ting (see spbrgVal con stant).;;===========================; 16F877 switches;===========================; Switches used in __config di rec tive:; _CP_ON Code pro tec tion ON/OFF ; * _CP_OFF ; * _PWRTE_ON Power-up timer ON/OFF; _PWRTE_OFF ; _BODEN_ON Brown-out re set en able ON/OFF

828 Appendix H

Page 850: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; * _BODEN_OFF ; * _PWRTE_ON Power-up timer en able ON/OFF; _PWRTE_OFF ; _WDT_ON Watchdog timer ON/OFF ; * _WDT_OFF; _LPV_ON Low volt age IC pro gram ming en able ON/OFF; * _LPV_OFF; _CPD_ON Data EE mem ory code pro tec tion ON/OFF; * _CPD_OFF; OSCILLATOR CONFIGURATIONS: ; _LP_OSC Low power crys tal os cil la tor; _XT_OSC Ex ter nal par al lel crys tal os cil la tor ; * _HS_OSC High speed crys tal res o na tor; _RC_OSC Re sis tor/ca pac i tor os cil la tor; | (sim plest, 20% er ror); |; |_____ * in di cates setup val ues pres ently se lected

pro ces sor 16f877 ; De fine pro ces sor#in clude <p16f877.inc>__CONFIG _CP_OFF & _WDT_OFF & _BODEN_OFF & _PWRTE_ON &

_HS_OSC & _WDT_OFF & _LVP_OFF & _CPD_OFF

; __CONFIG di rec tive is used to em bed con fig u ra tion data; within the source file. The la bels fol low ing the di rec tive; are lo cated in the cor re spond ing .inc file.

errorlevel -302; Sup press bank-re lated warn ing ;============================================================; M A C R O S;============================================================; Macros to se lect the reg is ter banksBank0 MACRO ; Se lect RAM bank 0

bcf STATUS,RP0bcf STATUS,RP1ENDM

Bank1 MACRO ; Se lect RAM bank 1bsf STATUS,RP0bcf STATUS,RP1ENDM

Bank2 MACRO ; Se lect RAM bank 2bcf STATUS,RP0bsf STATUS,RP1ENDM

Bank3 MACRO ; Se lect RAM bank 3

Additional Code 829

Page 851: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

bsf STATUS,RP0bsf STATUS,RP1ENDM

;=====================================================; con stant def i ni tions; for PIC-to-LCD pin wir ing and LCD line ad dresses;=====================================================#de fine E_line 1 ;|#de fine RS_line 0 ;| -- from wir ing di a gram #de fine RW_line 2 ;|; LCD line ad dresses (from LCD data sheet)#de fine LCD_1 0x80 ; First LCD line con stant#de fine LCD_2 0xc0 ; Sec ond LCD line con stant#de fine LCDlimit .20; Num ber of char ac ters per line#de fine spbrgVal .64; For 2400 baud on 10 MHz clock; Note: The con stant that de fine the LCD dis play; line ad dresses have the high-or der bit set; so as to meet the re quire ments of con trol ler; com mands.;==========================================================; con stants for I2C ini tial iza tion;==========================================================; I2C con nected to 24LC04B EEPROM.; The MSSP mod ule is in I2C MASTER mode.#de fine LC04READ 0xa0 ; I2C value for read con trol byte#de fine LC04WRITE 0xa1 ; I2C value for write con trol byte

;==========================================================; Gen eral Pur pose Vari ables;==========================================================; Lo cal vari ables; Re serve 20 bytes for string buffer

cblock 0x20strDataendc

; Other datacblock 0x34 ; Start of blockcount1 ; Coun ter # 1count2 ; Coun ter # 2count3 ; Coun ter # 3J ; coun ter JK ; coun ter KbufAddin dexstore1 ; Lo cal stor agestore2

; For LCDscroll pro ce dureLCDcount ; Coun ter for char ac ters per line

830 Appendix H

Page 852: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

LCDline ; Cur rent dis play line (0 or 1)endc

;==============================; Com mon RAM area;==============================; These GPRs can be ac cessed from any bank.; 15 bytes are avail able, from 0x70 to 0x7f

cblock 0x70; Com mu ni ca tions vari ables

newData ; not 0 if new data re ceivedascValerrorFlags

; EEPROM-re lated vari ablesEEMemAdd ; EEPROM ad dress to ac cessEEByte ; Data byte to writeendc

;============================================================; P R O G R A M;============================================================

org 0 ; start at ad dress goto main

; Space for in ter rupt han dlersorg 0x08

main:; Wiring:; LCD data to port D, lines 0 to 7; E line -> port E, 1; RW line -> port E, 2; RS line -> port E, 0; Set PORTE D and E for out put; First, ini tial ize port B by clear ing latches

clrf STATUSclrf PORTB

; Se lect bank 1 to tris port D for out putBank1

; Tris port D for out put. Port D lines 4 to 7 are wired; to LCD data lines. Port D lines 0 to 4 are wired to LEDs.

movlw B'00000000'movwf TRISD ; and port D

;; By de fault port A lines are an a log. To con fig ure them; as dig i tal code must set bits 1 and 2 of the ADCON1; reg is ter (in bank 1)

movlw 0x06 ; bi nary 0000 0110 is code to; make all port A lines

dig i talmovwf ADCON1

Additional Code 831

Page 853: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; Port B lines are wired to key pad switches, as fol lows:; 7 6 5 4 3 2 1 0; | | | | |_|_|_|_____ switch rows (out put); |_|_|_|_____________ switch col umns (in put); rows must be de fined as out put and col umns as in put

movlw b'11110000'movwf TRISB

; Tris port E for out putmovlw B'00000000'movwf TRISE ; Tris port E

; En able port B pullups for switches in OPTION reg is termovlw b'00001000'movwf OPTION_REG

; Back to bank 0Bank0

; Ini tial ize se rial port for 2400 baud, 8 bits, no par ity; 1 stop

call InitSerial; Test se rial trans mis sion by send ing "RDY-"

movlw 'R'call SerialSendmovlw 'D'call SerialSendmovlw 'Y'call SerialSendmovlw '-'call SerialSendmovlw 0x20call SerialSend

; Clear all out put linesmovlw b'00000000' movwf PORTDmovwf PORTE

; Wait and ini tial ize HD44780call de lay_5 ; Al low LCD time to ini tial ize it selfcall initLCD ; Then do forced ini tial iza tioncall de lay_5 ; (Wait prob a bly not nec es sary)

; Clear char ac ter coun ter and line coun ter vari ablesclrf LCDcountclrf LCDline

; Set dis play ad dress to start of first LCD linecall line1

; Store ad dress of dis play buffermovlw 0x20movwf bufAdd

; Dis play "Re ceiving:" mes sage promptcall blank20 ; Clear buffermovlw 0x00 ; Off set in buffer

832 Appendix H

Page 854: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

call storeMS1 ; Store mes sage at off setcall display20 ; Dis play mes sage

; Start ad dress of EEPROMclrf EEMemAdd

; Setup for dis play in sec ond linecall line2clrf LCDlineincf LCDline,f ; Set scroll con trol for line 2

; Ini tial ize I2C EEPROM op er a tioncall SetupI2C ; Lo cal pro ce dure

;============================================================; re ceive se rial data, store, and dis play;============================================================re ceive:; Call se rial re ceive pro ce dure

call SerialRcv; HOB of newData reg is ter is set if new data; re ceived

btfss newData,7goto scanExit

; At this point new data was re ceived.movwf EEByte ; Save re ceived char ac ter

; Dis play char ac ter on LCDmovf EEByte,w ; Re cover char ac tercall send8 ; Dis play in LCDcall LCDscroll ; Scroll at end of line

; Store char ac ter in EEPROM at lo ca tion in EEMemAddcall WriteI2C ; Lo cal pro ce dureincf EEMemAdd,f ; Bump to next EEPROM

; Check for <En ter> key (0x0d) and ex e cute dis play func tionmovf EEByte,w ; Re cover last re ceivedsublw 0x0dbtfsc STATUS,Z ; Test if <En ter> keygoto isEnter ; Go if <En ter>

; Not <En ter> key, con tinue pro cess ingscanExit:

goto re ceive ; Con tinue;============================; dis play EEPROM data;============================; This rou tine re ceives con trol when the <En ter> key is ; re ceived.; Ac tion:; 1. Clear LCD; 2. Out put is set to top LCD line; 3. Char ac ters stored in EEPROM are dis played; un til 0x0d code is de tectedisEnter:

Additional Code 833

Page 855: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

call clearLCD; Clear char ac ter coun ter and line coun ter vari ables

clrf LCDcountclrf LCDline

; Read data from EEPROM mem ory, start ing at ad dress 0; and dis play on LCD un til 0x0d ter mi na tor

call line1clrf EEMemAdd ; Start at EEPROM 0

readOne:call ReadI2C ; Get char ac ter

; Store char ac termovwf EEByte ; Save char ac ter

; Test for ter mi na torsublw 0x0dbtfsc STATUS,Z ; Test if 0x0dgoto atEnd ; Go if 0x0d

; At this point char ac ter read is not 0x0d; Dis play on LCD

movf EEByte,w ; Re cover char ac ter; Dis play char ac ter on LCD

call send8 ; Dis play in LCDcall LCDscroll ; Scroll at end of lineincf EEMemAdd,f ; Next EEPROM bytegoto readOne

; End of ex e cu tionatEnd:

goto atEnd

;============================================================;============================================================; L O C A L P R O C E D U R E S ;============================================================;============================================================;==========================; init LCD for 4-bit mode ;==========================initLCD:; Ini tial iza tion for Densitron LCD mod ule as fol lows:; 4-bit in ter face; 2 dis play lines of 16 char ac ters each; cur sor on; left-to-right in cre ment; cur sor shift right; no dis play shift;=======================|; set com mand mode |;=======================|

bcf PORTE,E_line ; E line low

834 Appendix H

Page 856: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

bcf PORTE,RS_line ; RS line lowbcf PORTE,RW_line ; Write modecall de lay_125 ; de lay 125

mi cro sec ondsmovlw 0x28 ; 0 0 1 0 1 0 0 0 (FUNCTION SET)call send8 ; 4-bit send rou tine

; Set 4-bit mode com mand must be re peatedmovlw 0x28call send8movlw 0x0e ; 0 0 0 0 1 1 1 0 (DISPLAY ON/OFF)call send8movlw 0x06 ; 0 0 0 0 0 1 1 0 (ENTRY MODE SET)call send8movlw 0x14 ; 0 0 0 1 0 1 0 0 (CURSOR/DISPLAY

; SHIFT)call send8movlw 0x01 ; 0 0 0 0 0 0 0 1 (CLEAR DISPLAY)

; |___ COMMAND BITcall send8call de lay_5 ; Test for busyre turn

.;===========================; pro ce dure to clear LCD;============================clearLCD:

bcf PORTE,E_line ; E line lowbcf PORTE,RS_line ; RS line lowbcf PORTE,RW_line ; Write modecall de lay_125 ; de lay 125

mi cro sec ondsmovlw 0x01 ; 0 0 0 0 0 0 0 1 (CLEAR DISPLAY)

; |___ COMMAND BITcall send8call de lay_5 ; Test for busyre turn

;=======================; Pro ce dure to de lay; 42 mi cro sec onds;=======================de lay_125:

movlw .105 ; Re peat 105 ma chine cy clesmovwf count1 ; Store value in coun ter

re peatdecfsz count1,f ; Dec re ment coun tergoto re peat ; Con tinue if not 0re turn ; End of de lay

Additional Code 835

Page 857: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

;=======================; Pro ce dure to de lay; 5 mil li sec onds;=======================de lay_5:

movlw .105 ; Coun ter = 105 cy clesmovwf count2 ; Store in vari able

de laycall de lay_125 ; De laydecfsz count2,f ; 40 times = 5 mil li sec ondsgoto de layre turn ; End of de lay

;========================; pulse E line ;========================pulseE

bsf PORTE,E_line ; Pulse E linenopbcf PORTE,E_linere turn

;=============================; long de lay sub-rou tine;=============================long_de lay

movlw D'200' ; w de lay countmovwf J ; J = w

jloop: movwf K ; K = wkloop: decfsz K,f ; K = K-1, skip next if zero

goto kloopdecfsz J,f ; J = J-1, skip next if zerogoto jloopre turn

;========================; send 2 nib bles in; 4-bit mode;========================; Pro ce dure to send two 4-bit val ues to port B lines; 7, 6, 5, and 4. High-or der nib ble is sent first; ON ENTRY:; w reg is ter holds 8-bit value to sendsend8:

movwf store1 ; Save orig i nal valuecall merge4 ; Merge with port B

; Now w has merged bytemovwf PORTD ; w to port Dcall pulseE ; Send data to LCD

; High nib ble is sent

836 Appendix H

Page 858: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

movf store1,w ; Re cover byte into wswapf store1,w ; Swap nib bles in wcall merge4movwf PORTDcall pulseE ; Send data to LCDcall de lay_125re turn

;==========================; merge bits;==========================; Rou tine to merge the 4 high-or der bits of the; value to send with the con tents of port B; so as to pre serve the 4 low-bits in port B; Logic:; AND value with 1111 0000 mask; AND port B with 0000 1111 mask; Now low nib ble in value and high nib ble in; port B are all 0 bits:; value = vvvv 0000; port B = 0000 bbbb; OR value and port B re sult ing in:; vvvv bbbb ; ON ENTRY:; w con tains value bits; ON EXIT:; w con tains merged bitsmerge4:

andlw b'11110000' ; ANDing with 0 clears the; bit. ANDing with 1 pre serves; the orig i nal value

movwf store2 ; Save re sult in vari ablemovf PORTD,w ; port B to w reg is terandlw b'00001111' ; Clear high nib ble in port b

; and pre serve low nib bleiorwf store2,w ; OR two operands in wre turn

;==========================; Set ad dress reg is ter; to LCD line 2;==========================; ON ENTRY:; Ad dress of LCD line 2 in con stant LCD_2 line2:

bcf PORTE,E_line ; E line lowbcf PORTE,RS_line ; RS line low, setup for

; con trolcall de lay_5 ; Busy?

; Set to sec ond dis play line

Additional Code 837

Page 859: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

movlw LCD_2 ; Ad dress with high-bit setcall send8

; Set RS line for databsf PORTE,RS_line ; RS = 1 for datacall de lay_5 ; Busy?re turn

;==========================; Set ad dress reg is ter; to LCD line 1;==========================; ON ENTRY:; Ad dress of LCD line 1 in con stant LCD_1 line1:

bcf PORTE,E_line ; E line lowbcf PORTE,RS_line ; RS line low, set up for

; con trolcall de lay_5 ; busy?

; Set to sec ond dis play linemovlw LCD_1 ; Ad dress and com mand bitcall send8 ; 4-bit rou tine

; Set RS line for databsf PORTE,RS_line ; Setup for datacall de lay_5 ; Busy?re turn

;==========================; scroll to LCD line 2 ;==========================; Pro ce dure to count the num ber of char ac ters dis played on; each LCD line. If the num ber reaches the value in the; con stant LCDlimit, then dis play is scrolled to the sec ond; LCD line. If at the end of the sec ond line, then LCD is; re set to the first line.LCDscroll:

incf LCDcount,f ; Bump coun ter; Test for line limit

movf LCDcount,wsublw LCDlimit ; Count mi nus limitbtfss STATUS,Z ; Is count - limit = 0goto scrollExit ; Go if not at end of line

; At this point the end of the LCD line was reached; Test if this is also the end of the sec ond line

movf LCDline,wsublw 0x01 ; Is it line 1?btfsc STATUS,Z ; Is LCDline mi nus 1 = 0?goto line2End ; Go if end of sec ond line

; At this point it is the end of the top LCD linecall line2 ; Scroll to sec ond line

838 Appendix H

Page 860: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

clrf LCDcount ; Re set coun terincf LCDline,f ; Bump line coun tergoto scrollExit

; End of sec ond LCD lineline2End:

call initLCD ; Re setclrf LCDcount ; Clear coun tersclrf LCDlinecall line1 ; Dis play to first line

scrollExit:re turn

;=============================; LCD dis play pro ce dure;=============================; Sends 20 char ac ters from PIC buffer with ad dress stored; in vari able bufAdd to LCD line pre vi ously se lecteddisplay20:

call de lay_5 ; Make sure not busy; Set up for data

bcf PORTA,E_line ; E line lowbsf PORTA,RS_line ; RS line high for data

; Set up coun ter for 20 char ac tersmovlw D'20'movwf count3

; Get dis play ad dress from lo cal vari able bufAddmovf bufAdd,w ; First dis play RAM ad dress to wmovwf FSR ; w to FSR

getcharmovf INDF,w ; get char ac ter from dis play RAM

; lo ca tion pointed to by file se lect; reg is ter

call send8 ; 4-bit in ter face rou tine; Test for 20 char ac ters dis played

decfsz count3,f ; Dec re ment coun tergoto nextchar ; Skipped if donere turn

nextchar:incf FSR,f ; Bump pointergoto getchar

;===============================; first text string pro ce dure;===============================storeMS1:; Pro ce dure to store in PIC RAM buffer the mes sage; con tained in the code area la beled msg1; ON ENTRY:

Additional Code 839

Page 861: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; vari able bufAdd holds ad dress of text buffer; in PIC RAM; w reg is ter hold off set into stor age area; msg1 is rou tine that re turns the string char ac ters; and a zero ter mi na tor; in dex is lo cal vari able that hold off set into; text ta ble. This vari able is also used for; tem po rary stor age of off set into buffer ; ON EXIT:; Text mes sage stored in buffer;; Store off set into text buffer (passed in the w reg is ter); in tem po rary vari able

movwf in dex ; Store w in in dex; Store base ad dress of text buffer in FSR

movf bufAdd,w ; first dis play RAM ad dress to waddwf in dex,w ; Add off set to ad dressmovwf FSR ; w to FSR

; Ini tial ize in dex for text string ac cessmovlw 0 ; Start at 0movwf in dex ; Store in dex in vari able

; w still = 0get_msg_char:

call msg1 ; Get char ac ter from ta ble; Test for zero ter mi na tor

andlw 0x0ffbtfsc STATUS,Z ; Test zero flaggoto endstr1 ; End of string

; ASSERT: valid string char ac ter in w; store char ac ter in text buffer (by FSR)

movwf INDF ; store in buffer by FSRincf FSR,f ; in cre ment buffer pointer

; Re store ta ble char ac ter coun ter from vari ablemovf in dex,w ; Get value into waddlw 1 ; Bump to next char ac termovwf in dex ; Store ta ble in dex in vari ablegoto get_msg_char ; Con tinue

endstr1:re turn

; Rou tine for re turn ing mes sage stored in pro gram area; Mes sage has 10 char ac tersmsg1:

addwf PCL,f ; Ac cess ta bleretlw 'R'retlw 'e'retlw 'c'retlw 'e'

840 Appendix H

Page 862: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

retlw 'i'retlw 'v'retlw 'i'retlw 'n'retlw 'g'retlw ':'retlw 0

;========================; blank buffer;========================; Pro ce dure to store 20 blank char ac ters in PIC RAM; buffer start ing at ad dress stored in the vari able; bufAddblank20:

movlw D'20' ; Set up coun termovwf count1movf bufAdd,w ; First PIC RAM ad dressmovwf FSR ; In dexed ad dress ingmovlw 0x20 ; ASCII space char ac ter

storeitmovwf INDF ; Store blank char ac ter in PIC RAM

; buffer us ing FSR reg is terdecfsz count1,f ; Done?goto incfsr ; nore turn ; yes

incfsrincf FSR,f ; Bump FSR to next buffer spacegoto storeit

;==============================================================; com mu ni ca tions pro ce dures;==============================================================; Initialize se rial port for 2400 baud, 8 bits, no par ity,; 1 stopInitSerial:

Bank1 ; Macro to se lect bank1; Bits 6 and 7 of Port C are mul ti plexed as TX/CK and RX/DT; for USART op er a tion. These bits must be set to in put in the; TRISC reg is ter

movlw b'11000000' ; Bits for TX and RXiorwf TRISC,f ; OR into Trisc reg is ter

; The asyn chron ous baud rate is cal cu lated as fol lows:; Fosc; ABR = -----------; S*(x+1); where x is value in the SPBRG reg is ter and S is 64 if the high; baud rate se lect bit (BRGH) in the TXSTA con trol reg is ter is

Additional Code 841

Page 863: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; clear, and 16 if the BRGH bit is set. For set ting to 2400 baud; us ing a 10 MHz os cil la tor at a slow baud rate the for mula; is:; At slow speed (BRGH = 0); 10,000,000 10,000,000; ---------- = ----------- = 2,403.84 (0.16% er ror); 64*(64+1) 4160 ;

movlw spbrgVal ; Value in spbrgVal = 64movwf SPBRG ; Place in baud rate gen er a tor

; Setup value: 0010 0000 = 0x20movlw 0x20 ; En able trans mis sion and high baud

; ratemovwf TXSTABank0 ; Bank 0

; Setup value: 1001 0000 = 0x90movlw 0x90 ; En able se rial port and con tin u ous

; re cep tionmovwf RCSTA

; clrf errorFlags; Clear lo cal er ror flags reg is terre turn

;==============================; trans mit data;==============================; Test for Trans mit Reg is ter Empty and trans mit data in wSerialSend:

Bank0 ; Se lect bank 0btfss PIR1,TXIF ; check if trans mit ter busygoto $-1 ; wait un til trans mit ter is not busymovwf TXREG ; and trans mit the datare turn

;==============================; re ceive data;==============================; Pro ce dure to test line for data re ceived and re turn value; in w. Over run and fram ing er rors are de tected and; re mem bered in the vari able errorFlags, as fol lows:; 7 6 5 4 3 2 1 0 <== errorFlags; -- not used ---- | |___ over run er ror; |______ fram ing er rorSerialRcv:

clrf newData ; Clear new data re ceived reg is terBank0 ; Se lect bank 0

; Bit 5 (RCIF) of the PIR1 Reg is ter is clear if the USART; re ceive buffer is empty. If so, no data has been re ceived

btfss PIR1,RCIF ; Check for re ceived data

842 Appendix H

Page 864: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

re turn ; Exit if no data; At this point data has been re ceived. First elim i nate; pos si ble er rors: over run and fram ing.; Bit 1 (OERR) of the RCSTA reg is ter de tects over run; Bit 2 (FERR) of the RCSTA reg is ter de tects fram ing er ror

btfsc RCSTA,OERR ; Test for over run er rorgoto OverErr ; Er ror han dlerbtfsc RCSTA,FERR ; Test for fram ing er rorgoto FrameErr ; Er ror han dler

; At this point no er ror was de tected; Re ceived data is in the USART RCREG reg is ter

movf RCREG,w ; get re ceived databsf newData,7 ; Set bit 7 to in di cate new data

; Clear er ror flagsclrf errorFlagsre turn

;==========================; er ror han dlers;==========================OverErr:

bsf errorFlags,0 ; Bit 0 is over run er ror; Re set sys tem

bcf RCSTA,CREN ; Clear con tin u ous re ceive bitbsf RCSTA,CREN ; Set to re-en able re cep tionre turn

; er ror be cause FERR fram ing er ror bit is set; can do spe cial er ror han dling here - this code sim ply clears; and con tin uesFrameErr:

bsf errorFlags,1; Bit 1 is fram ing er rormovf RCREG,W ; Read and throw away bad datare turn

;============================================================; I2C EEPROM data pro ce dures;============================================================; GPRs used in EEPROM-re lated code are placed in the com mon; RAM area (from 0x70 to 0x7f). This makes the reg is ters; ac ces si ble from any bank.;============================; LIST OF PROCEDURES;============================; SetupI2C --- Ini tial ize MSSP mod ule for I2C mode; in hard ware mas ter mode; Con fig ure I2C lines; Set slew rate for 100kbps; Set baud rate for 10 MHz; WriteI2C --- Write byte to I2C EEPROM de vice; Data is stored in EEByte vari able

Additional Code 843

Page 865: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; Ad dress is stored in EEMemAdd; ReadI2C --- Read byte from I2C EEPROM de vice; Ad dress stored in EEMemAdd; Read data re turned in w reg is ter;============================; I2C setup pro ce dure;============================SetupI2C:

Bank1movlw b'00011000'iorwf TRISC,f ; OR into TRISC

; Setup MSSP mod ule for Mas ter Mode op er a tionBank0movlw B'00101000'; En ables MSSP and uses ap pro pri ate

; 0 0 1 0 1 0 0 0 Value to in stall; 7 6 5 4 3 2 1 0 <== SSPCON bits in this op er a tion; | | | | |__|__|__|___ Se rial port se lect bits; | | | | 1000 = I2C mas ter mode; | | | | Clock = Fosc/(4*(SSPAD+1)); | | | |_______________ UNUSED IN MASTER MODE; | | |__________________ SSP En able; | | 1 = SDA and SCL pins as se rial; | |_____________________ Re ceive overflow in di ca tor; | 0 = no over flow ; |________________________ Write col li sion de tect; 0 = no col li sion de tected

movwf SSPCON ; This is loaded into SSPCON; In put lev els and slew rate as stan dard I2C

Bank1movlw B'10000000'

; 1 0 0 0 0 0 0 0 Value to in stall; 7 6 5 4 3 2 1 0 <== SSPSTAT bits in this op er a tion; | | | | | | | |___ Buffer full sta tus bit READ ONLY; | | | | | | |______ UNUSED in pres ent ap pli ca tion; | | | | | |_________ Read/write in for ma tion READ ONLY; | | | | |____________ UNUSED IN MASTER MODE; | | | |_______________ STOP bit READ ONLY ; | | |__________________ Data ad dress READ ONLY; | |_____________________ SMP bus se lect; | 0 = use nor mal I2C specs; |________________________ Slew rate con trol; 0 = dis abled

movwf SSPSTAT; Setup Baud Rate; Baud Rate = Fosc/(4*(SSPADD+1)); Fosc = 10 MHz; Baud Rate = 24 for 100 kbps

movlw .24 ; Value to use

844 Appendix H

Page 866: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

movwf SSPADD ; Store in SSPADDBank0re turn

;============================; I2C write pro ce dure;============================; Write one byte to I2C EEPROM 24LC04B; Steps:; 1. Send START; 2. Send con trol. Wait for ACK; 3. Send ad dress. Wait for ACK; 4. Send data. Wait for ACK; 5. Send STOP; STEP 1:WriteI2C:

Bank1bsf SSPCON2,SEN ; Pro duce START Con di tioncall WaitI2C ; Wait for I2C to com plete

; STEP 2:; Send con trol byte. Wair for ACK

movlw LC04READ ; Con trol bytecall Send1I2C ; Send Bytecall WaitI2C ; Wait for I2C to com pletebtfsc SSPCON2,ACKSTAT ; Check ACK bit to see if

; I2C failed, skip if notgoto FailI2C

; STEP 3:; Send ad dress. Wait for ACK

Bank0movf EEMemAdd,w ; Load Ad dress Bytecall Send1I2C ; Send Bytecall WaitI2C ; Wait for I2C op er a tion to com pleteBank1btfsc SSPCON2,ACKSTAT ; Check ACK Sta tus bit to see

; if I2C failed, skip if notgoto FailI2C

; STEP 4:; Send data. Wait for ACK

Bank0movf EEByte,w ; Load Data Bytecall Send1I2C ; Send Bytecall WaitI2C ; Wait for I2C op er a tion to com pleteBank1btfsc SSPCON2,ACKSTAT ; Check ACK Sta tus bit to see

; if I2C failed, skip if notgoto FailI2C

; STEP 5:

Additional Code 845

Page 867: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; Send STOP. Wait for ACKbsf SSPCON2,PEN ; Send STOP con di tioncall WaitI2C ; Wait for I2C op er a tion to com plete

; WRITE op er a tion has com pleted suc cess fully.Bank0re turn

;============================; I2C read pro ce dure ;============================; Pro ce dure to read one byte from 24LC04B EEPROM; Steps:; 1. Send START.; 2. Send con trol. Wait for ACK.; 3. Send ad dress. Wait for ACK.; 4. Send RESTART + con trol. Wait for ACK.; 5. Switch to re ceive mode. Get data.; 6. Send NACK.; 7. Send STOP.; 8. Retreive data into w reg is ter. ; STEP 1:ReadI2C; Send RESTART. Wait for ACK

Bank1bsf SSPCON2,RSEN ; RESTART Con di tioncall WaitI2C ; Wait for I2C op er a tion

; STEP 2:; Send con trol byte. Wait for ACK

movlw LC04READ ; Con trol bytecall Send1I2C ; Send Bytecall WaitI2C ; Wait for I2C op er a tion

; Now check to see if I2C EEPROM is readyBank1btfsc SSPCON2,ACKSTAT ; Check ACK Sta tus bitgoto ReadI2C ; ACK Poll wait ing for EEPROM

; write to com plete; STEP 3:; Send ad dress. Wait for ACK

Bank0movf EEMemAdd,w ; Load from ad dress reg is tercall Send1I2C ; Send Bytecall WaitI2C ; Wait for I2C op er a tionBank1btfsc SSPCON2,ACKSTAT ; Check ACK Sta tus bitgoto FailI2C ; failed, skipped if suc cess ful

; STEP 4:; Send RESTART. Wait for ACK

bsf SSPCON2,RSEN ; Gen er ate RESTART Con di tion

846 Appendix H

Page 868: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

call WaitI2C ; Wait for I2C op er a tion; Send out put con trol. Wait for ACK

movlw LC04WRITE ; Load CONTROL BYTE (out put)call Send1I2C ; Send Bytecall WaitI2C ; Wait for I2C op er a tionBank1btfsc SSPCON2,ACKSTAT ; Check ACK Sta tus bitgoto FailI2C ; failed, skipped if suc cess ful

; STEP 5:; Switch MSSP to I2C Re ceive mode

bsf SSPCON2,RCEN ; En able Re ceive Mode (I2C); Get the data. Wait for ACK

call WaitI2C ; Wait for I2C op er a tion; STEP 6:; Send NACK to ac knowl edge

Bank1bsf SSPCON2,ACKDT ; ACK DATA to send is 1 (NACK)bsf SSPCON2,ACKEN ; Send ACK DATA now.

; Once ACK or NACK is sent, ACKEN is au to mat i cally cleared; STEP 7:; Send STOP. Wait for ACK

bsf SSPCON2,PEN ; Send STOP con di tioncall WaitI2C ; Wait for I2C op er a tion

; STEP 8:; Read op er a tion has fin ished

Bank0movf SSPBUF,W ; Get data from SSPBUF into W

; Pro ce dure has fin ished and com pleted suc cess fully.re turn

;============================; I2C sup port pro ce dures;============================; I2C Op er a tion failed code se quence; Pro ce dure hangs up. User should pro vide er ror han dling.FailI2C

Bank1bsf SSPCON2,PEN ; Send STOP con di tioncall WaitI2C ; Wait for I2C op er a tion

fail:goto fail

; Pro ce dure to trans mit one byteSend1I2C

Bank0movwf SSPBUF ; Value to send to SSPBUFre turn

Additional Code 847

Page 869: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; Pro ce dure to wait for the last I2C op er a tion to com plete.; Code polls the SSPIF flag in PIR1.WaitI2C

Bank0btfss PIR1,SSPIF ; Check if I2C op er a tion donegoto $-1 ; I2C mod ule is not ready yetbcf PIR1,SSPIF ; I2C ready, clear flagre turn

;============================================================end ; END OF PROGRAM

;============================================================

848 Appendix H

Page 870: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; File name: Key2LCD.asm; Date: May 11, 2010; Au thors: Sanchez and Canton;; De scrip tion:; De code 4 x 4 key pad and dis play scan code in LCD.; Pro gram uses 4-bit PIC-to-LCD in ter face.; Code as sumes that LCD is driven by Hitachi HD44780; con trol ler and PIC 16F977. Dis play sup ports two lines; each one with 20 char ac ters. The wir ing and base; ad dress of each dis play line are stored in #de fine; state ments. These state ments can be ed ited to; accomodate a dif fer ent set up.; Key pad switch wir ing (val ues are scan codes):; --- KEYPAD -- ; 0 1 2 3 <= port B0 |; 4 5 6 7 <= port B1 |--- ROWS = OUTPUTS; 8 9 A B <= port B2 |; C D E F <= port B3 |; | | | |; | | | |_____ port B4 |; | | |_________ port B5 |--- COLUMNS = INPUTS; | |_____________ port B6 |; |_________________ port B7 |;; Pro gram op er a tions:; 1. Key press ac tion gen er ates a scan code in the range; 0x0 to 0xf.; 2. Pro gram converts scan code to ASCII digit and dis plays; the digit on the LCD.; 3. When the end of the first LCD line is reached, dis play; con tin ues in the sec ond line. When the end of the; sec ond line is reached, LCD is re set to the first line.;; Pro gram uses de lay loops for in ter face tim ing.; WARNING:; Code as sumes 4 MHz clock. De lay rou tines must be; ed ited for faster clock.;;===========================; 16F877 switches;===========================; Switches used in __config di rec tive:; _CP_ON Code pro tec tion ON/OFF ; * _CP_OFF ; * _PWRTE_ON Power-up timer ON/OFF; _PWRTE_OFF ; _BODEN_ON Brown-out re set en able ON/OFF

Additional Code 849

Page 871: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; * _BODEN_OFF ; * _PWRTE_ON Power-up timer en able ON/OFF; _PWRTE_OFF ; _WDT_ON Watchdog timer ON/OFF ; * _WDT_OFF; _LPV_ON Low volt age IC pro gram ming en able ON/OFF; * _LPV_OFF; _CPD_ON Data EE mem ory code pro tec tion ON/OFF; * _CPD_OFF; OSCILLATOR CONFIGURATIONS: ; _LP_OSC Low power crys tal oscillator; _XT_OSC Ex ter nal par al lel crys tal oscillator ; * _HS_OSC High speed crys tal res o na tor; _RC_OSC Re sis tor/ca pac i tor oscillator; | (sim plest, 20% er ror); |; |_____ * in di cates setup val ues pres ently se lected

pro ces sor 16f877 ; De fine pro ces sor#in clude <p16f877.inc>__CONFIG _CP_OFF & _WDT_OFF & _BODEN_OFF & _PWRTE_ON &

_HS_OSC & _WDT_OFF & _LVP_OFF & _CPD_OFF

; __CONFIG di rec tive is used to em bed con fig u ra tion data; within the source file. The la bels fol low ing the di rec tive; are lo cated in the cor re spond ing .inc file.

;============================================================; con stant def i ni tions; for PIC-to-LCD pin wir ing and LCD line ad dresses;============================================================#de fine E_line 1 ;|#de fine RS_line 0 ;| -- from wir ing di a gram #de fine RW_line 2 ;|; LCD line ad dresses (from LCD datasheet)#de fine LCD_1 0x80 ; First LCD line con stant#de fine LCD_2 0xc0 ; Sec ond LCD line con stant#de fine LCDlimit .20; Num ber of char ac ters per line; Note: The con stants that de fine the LCD dis play line; ad dresses have the high-or der bit set in; or der to faciliate the con trol ler com mand. ;;============================================================; PIC reg is ter equates;============================================================portd equ 0x08porte equ 0x09fsr equ 0x04

850 Appendix H

Page 872: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

sta tus equ 0x03indf equ 0x00z equ 2c equ 0;=============================================================; vari ables in PIC RAM;=============================================================; Re serve 20 bytes for string buffer

cblock 0x20strDataendc

; Leave 16 bytes and Con tinue with lo cal vari ablescblock 0x34 ; Start of blockcount1 ; Coun ter # 1count2 ; Coun ter # 2count3 ; Coun ter # 3pic_ad ; Stor age for start of text area

; (la beled strData) in PIC RAMJ ; coun ter JK ; coun ter Kin dex ; In dex into text ta ble (also used

; for aux il iary stor age)store1 ; Lo cal stor agestore2

; For LCDscroll pro ce dureLCDcount ; Coun ter for char ac ters per lineLCDline ; Cur rent dis play line (0 or 1)

; Key pad pro cess ing vari ableskeyMask ; For key pad pro cess ingrowMask ; For mask ing-off key rowsrowCode ; Row ad ded for cal cu lat ing scan coderowCount ; Coun ter for key rows (0 to 3)scanCode ; Fi nal key codenewScan ; 0 if no new scan code de tectedendc

;============================================================; M A C R O S;============================================================; Macros to se lect the reg is ter banks; Data mem ory bank se lec tion bits:; RP1:RP0 Bank; 0:0 0 Ports A,B,C,D, and E; 0:1 1 Tris A,B,C,D, and E; 1:0 2; 1:1 3Bank0 MACRO ; Se lect RAM bank 0

bcf STATUS,RP0bcf STATUS,RP1

Additional Code 851

Page 873: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

ENDM

Bank1 MACRO ; Se lect RAM bank 1bsf STATUS,RP0bcf STATUS,RP1ENDM

Bank2 MACRO ; Se lect RAM bank 2bcf STATUS,RP0bsf STATUS,RP1ENDM

Bank3 MACRO ; Se lect RAM bank 3bsf STATUS,RP0bsf STATUS,RP1ENDM

;============================================================; M A I N P R O G R A M;============================================================

org 0 ; start at ad dress goto main

; Space for in ter rupt han dlersorg 0x08

main:; Wiring:; LCD data to port D, lines 0 to 7; E line -> port E, 1; RW line -> port E, 2; RS line -> port E, 0; Set ports D and E for out put; First, ini tial ize port B by clear ing latches

clrf STATUSclrf PORTB

; Se lect bank 1 to tris port D for out putBank1

; Tris port D for out put. Port D lines 4 to 7 are wired; to LCD data lines. Port D lines 0 to 4 are wired to LEDs.

movlw B'00000000'movwf TRISD ; and port D

; By de fault port A lines are an a log. To con fig ure them; as dig i tal code must set bits 1 and 2 of the ADCON1; reg is ter (in bank 1)

movlw 0x06 ; bi nary 0000 0110 is code to; make all

port A lines digitalmovwf ADCON1

; Port B lines are wired to key pad swtiches as fol lows:; 7 6 5 4 3 2 1 0

852 Appendix H

Page 874: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; | | | | |_|_|_|_____ switch rows (out put); |_|_|_|_____________ switch col umns (in put); rows must be de fined as out put and col umns as in put

movlw b'11110000'movwf TRISB

; Tris port E for out putmovlw B'00000000'movwf TRISE ; Tris port E

; En able port B pullups for switches in OPTION reg is ter; 7 6 5 4 3 2 1 0 <= OPTION bits; | | | | | |__|__|_____ PS2-PS0 (prescaler bits); | | | | | Values for Timer0; | | | | | 000 = 1:2 001 = 1:4; | | | | | 010 = 1:8 011 = 1:16; | | | | | 100 = 1:32 101 = 1:64; | | | | | 110 = 1:128 *111 = 1:256; | | | | |______________ PSA (prescaler as sign); | | | | *1 = to WDT; | | | | 0 = to Timer0; | | | |_________________ TOSE (Timer0 edge se lect); | | | *0 = in cre ment on low-to-high; | | | 1 = in cre ment on high-to-low; | | |____________________ TOCS (TMR0 clock source); | | *0 = in ter nal clock; | | 1 = RA4/TOCKI bit source; | |_______________________ INTEDG (Edge se lect); | *0 = fall ing edge; |__________________________ RBPU (Pullup en able); *0 = en abled; 1 = disabled;

movlw b'00001000'movwf OPTION_REG

; Back to bank 0Bank0

; Clear all out put linesmovlw b'00000000' movwf portdmovwf porte

; Wait and ini tial ize HD44780call de lay_5 ; Al low LCD time to ini tial ize it selfcall initLCD ; Then do forced ini tial iza tioncall de lay_5 ; (Wait prob a bly not nec es sary)

; Set dis play ad dress to start of sec ond LCD linecall line1

; Clear char ac ter coun ter and line coun ter vari ablesclrf LCDcountclrf LCDline

Additional Code 853

Page 875: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

;========================; scan key pad ;========================; Key pad switch wir ing:; x x x x <= port B0 |; x x x x <= port B1 |--- ROWS = OUTPUTS; x x x x <= port B2 |; x x x x <= port B3 |; | | | |; | | | |_____ port B4 |; | | |_________ port B5 |--- COLUMNS = INPUTS; | |_____________ port B6 |; |_________________ port B7 |; Switches are con nected to port B lines; Clear scan code reg is ter

clrf scanCode;============================; scan key pad and dis play;============================keyScan:; Port B lines are wired to pushbutton swtiches as fol lows:; 7 6 5 4 3 2 1 0; | | | | |_|_|_|_____ switch rows (out put); |_|_|_|_____________ switch col umns (in put); Key pad pro cess ing:; Switch rows are succesively grounded (row = 0); Then col umn val ues are tested. If a col umn re turns 0; in a 0 row, that switch is down.; Ini tial ize row code ad dend

clrf rowCode ; First row is code 0clrf newScan ; No new scan code de tected

; Ini tial ize row countmovlw D'4' ; Four rows movwf rowCount ; Reg is ter vari ablemovlw b'11111110' ; All set but LOBmovwf rowMask

keyLoop:; Ini tial ize row eliminator mask:; The row mask is ANDed with the key mask to successively; mask-off each row, for ex am ple:;; |------- row 3; ||------ row 2; |||----- row 1; ||||---- row 0; 0000 1111 <= key mask; AND 1111 1101 <= mask for row 1; ---------

854 Appendix H

Page 876: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; 0000 1101 <= row 1 is masked off;; The row mask, which is initally 1111 1110, is ro tated left; through the carry in or der to mask-off the next row

movlw b'00001111' ; Mask-off all linesmovwf keyMask ; To lo cal reg is ter

; Set row mask for cur rent rowmovf rowMask,w ; Mask to wandwf keyMask,f ; Up date key maskmovf keyMask,w ; Key mask to wmovwf PORTB ; Mask-off port B lines

; Read port B lines 4 to 7 (col umns are in put)btfss PORTB,4call col0 ; Key col umn pro ce duresbtfss PORTB,5call col1btfss PORTB,6call col2btfss PORTB,7call col3

; In dex to next row by add ing 4 to row codemovf rowCode,w ; Code to waddlw D'4'movwf rowCode

;=========================; shift row mask;=========================; Set the carry flag

bsf STATUS,crlf rowMask,f ; Ro tate mask bits in stor age

;=========================; end of key pad?;=========================; Test for last key row (max i mum count is 4)

decfsz rowCount,f ; Dec re ment coun tergoto keyLoop

;===========================================================;===========================================================; dis play scan code;===========================================================;===========================================================; At this point all keys have been tested.; Vari able newScan = 0 if no new scan code de tected, else; vari able scanCode holds scan code

movf newScan,f ; Copy onto itself (sets z flag)btfsc STATUS,z ; Is it zerogoto scanExit

; At this point a new scan code is de tected

Additional Code 855

Page 877: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

movf scanCode,w ; To w ; If scan code is in the range 0 to 9, that is, a dec i mal; digit, then ASCII con ver sion con sists of add ing 0x30.; If the scan code rep re sents one of the hex let ters; (0xa to 0xf), then ASCII con ver sion re quires add ing; 0x37

sublw 0x09 ; 9 - w; if w from 0 to 9 then 9 - w = pos i tive (c flag = 1); if w = 0xa then 9 - 10 = -1 (c flag = 0); if w = 0xc then 9 - 12 = -2 (c flag = 0)

btfss STATUS,c ; Test carry flaggoto hexLetter ; Carry clear, must be a let ter

; At this point scan code is a dec i mal digit in the; range 0 to 9. Convert to ASCII by add ing 0x30

movf scanCode,w ; Re cover scan codeaddlw 0x30 ; Conver to ASCIIgoto displayDig

hexLetter:movf scanCode,w ; Re cover scan codeaddlw 0x37 ; Conver to ASCII

displayDig:call send8 ; Dis play rou tinecall LCDscroll ; Auto line scroll ing pro ce dure

scanExit:call long_de lay ; Debouncegoto keyScan ; Con tinue

;==========================; cal cu late scan code;==========================; The col umn po si tion is added to the row code (stored; in rowCode reg is ter). Sum is the scan codecol0:

movf rowCode,w ; Row code to waddlw 0x00 ; Add 0 (clearly not nec es sary)movwf scanCode ; Fi nal valueincf newScan,f ; New scan codere turn

col1:movf rowCode,w ; Row code to waddlw 0x01 ; Add 1movwf scanCodeincf newScan,fre turn

col2:movf rowCode,w ; Row code to w

856 Appendix H

Page 878: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

addlw 0x02 ; Add 2movwf scanCodeincf newScan,fre turn

col3:movf rowCode,w ; Row code to waddlw 0x03 ; Add 3movwf scanCodeincf newScan,fre turn

;============================================================; ini tial ize LCD for 4-bit mode ;============================================================initLCD:; Ini tial iza tion for Densitron LCD mod ule as fol lows:; 4-bit in ter face; 2 dis play lines of 16 char ac ters each; cur sor on; left-to-right in cre ment; cur sor shift right; no dis play shift;=======================|; set com mand mode |;=======================|

bcf porte,E_line ; E line lowbcf porte,RS_line ; RS line lowbcf porte,RW_line ; Write modecall de lay_125 ; de lay 125 mi cro sec onds

;***********************|; FUNCTION SET |;***********************|

movlw 0x28 ; 0 0 1 0 1 0 0 0 (FUNCTION SET); | | | |__ font se lect:; | | | 1 = 5x10 in 1/8 or 1/11; | | | 0 = 1/16 dc; | | |___ Duty cy cle se lect; | | 0 = 1/8 or 1/11; | | 1 = 1/16 ; | |___ In ter face width; | 0 = 4 bits; | 1 = 8 bits; |___ FUNCTION SET COMMAND

call send8 ; 4-bit send rou tine

; Set 4-bit mode com mand must be re peatedmovlw 0x28

Additional Code 857

Page 879: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

call send8

;***********************|; DISPLAY AND CURSOR ON |;***********************|

movlw 0x0e ; 0 0 0 0 1 1 1 0 (DISPLAY ON/OFF); | | | |___ Blink char ac ter; | | | 1 = on, 0 = off; | | |___ Curson on/off; | | 1 = on, 0 = off; | |____ Dis play on/off; | 1 = on, 0 = off; |____ COMMAND BIT

call send8;***********************|; set en try mode |;***********************|

movlw 0x06 ; 0 0 0 0 0 1 1 0 (ENTRY MODE SET); | | |___ dis play shift; | | 1 = shift; | | 0 = no shift; | |____ cur sor in cre ment ; | 1 = left-to-right; | 0 = right-to-left; |___ COMMAND BIT

call send8

;***********************|; cur sor/dis play shift |;***********************|

movlw 0x14 ; 0 0 0 1 0 1 0 0 (CURSOR/DISPLAY; SHIFT); | | | |_|___ don't care; | |_|__ cur sor/dis play shift; | 00 = cur sor shift left; | 01 = cur sor shift right; | 10 = cur sor and dis play; | shifted left; | 11 = cur sor and dis play; | shifted right; |___ COMMAND BIT

call send8;***********************|; clear dis play |;***********************|

movlw 0x01 ; 0 0 0 0 0 0 0 1 (CLEAR DISPLAY); |___

COMMAND BIT

858 Appendix H

Page 880: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

call send8; Per doc u men ta tion

call de lay_5 ; Test for busyre turn

;=======================; Pro ce dure to de lay; 42 mi cro sec onds;=======================de lay_125:

movlw D'42' ; Re peat 42 ma chine cy clesmovwf count1 ; Store value in coun ter

re peatdecfsz count1,f ; Dec re ment coun tergoto re peat ; Con tinue if not 0re turn ; End of de lay

;=======================; Pro ce dure to de lay; 5 mil li sec onds;=======================de lay_5:

movlw D'42' ; Coun ter = 41movwf count2 ; Store in vari able

de laycall de lay_125 ; De laydecfsz count2,f ; 40 times = 5 mil li sec ondsgoto de layre turn ; End of de lay

;========================; pulse E line ;========================pulseE

bsf porte,E_line ; Pulse E lineNopbcf porte,E_linere turn

;=============================; long de lay sub-rou tine; (for de bug ging);=============================long_de lay

movlw D'200' ; w de lay countmovwf J ; J = w

jloop: movwf K ; K = wkloop: decfsz K,f ; K = K-1, skip next if zero

goto kloop

Additional Code 859

Page 881: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

decfsz J,f ; J = J-1, skip next if zerogoto jloopre turn

;========================; send 2 nib bles in; 4-bit mode;========================; Pro ce dure to send two 4-bit val ues to port B lines; 7, 6, 5, and 4. High-or der nib ble is sent first; ON ENTRY:; w reg is ter holds 8-bit value to sendsend8:

movwf store1 ; Save orig i nal valuecall merge4 ; Merge with port B

; Now w has merged bytemovwf portd ; w to port Dcall pulseE ; Send data to LCD

; High nib ble is sentmovf store1,w ; Re cover byte into wswapf store1,w ; Swap nib bles in wcall merge4movwf portdcall pulseE ; Send data to LCDcall de lay_125 re turn

;=================; merge bits;=================; Rou tine to merge the 4 high-or der bits of the; value to send with the con tents of port B; so as to pre serve the 4 low-bits in port B; Logic:; AND value with 1111 0000 mask; AND port B with 0000 1111 mask; Now low nib ble in value and high nib ble in; port B are all 0 bits:; value = vvvv 0000; port B = 0000 bbbb; OR value and port B re sult ing in:; vvvv bbbb ; ON ENTRY:; w con tains value bits; ON EXIT:; w con tains merged bitsmerge4:

andlw b'11110000' ; ANDing with 0 clears the; bit. ANDing with 1 pre serves

860 Appendix H

Page 882: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; the orig i nal valuemovwf store2 ; Save re sult in vari ablemovf portd,w ; port B to w reg is terandlw b'00001111' ; Clear high nib ble in port b

; and pre serve low nib bleiorwf store2,w ; OR two operands in wre turn

;========================; Set ad dress reg is ter; to LCD line 1;========================; ON ENTRY:; Ad dress of LCD line 2 in con stant LCD_2 line1:

bcf porte,E_line ; E line lowbcf porte,RS_line ; RS line low, set up for

; con trolcall de lay_5 ; Busy?

; Set to sec ond dis play linemovlw LCD_1 ; Ad dress with

high-bit setcall send8

; Set RS line for databsf porte,RS_line ; RS = 1 for datacall de lay_5 ; Busy?re turn

;========================; Set ad dress reg is ter; to LCD line 2;========================; ON ENTRY:; Ad dress of LCD line 2 in con stant LCD_2 line2:

bcf porte,E_line ; E line lowbcf porte,RS_line ; RS line low, set up for

; con trolcall de lay_5 ; Busy?

; Set to sec ond dis play linemovlw LCD_2 ; Ad dress with high-bit setcall send8

; Set RS line for databsf porte,RS_line ; RS = 1 for datacall de lay_5 ; Busy?re turn

;==========================

Additional Code 861

Page 883: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

; scroll to LCD line 2 ;==========================; Pro ce dure to count the num ber of char ac ters dis played on; each LCD line. If the num ber reaches the value in the; con stant LCDlimit, then dis play is scrolled to the sec ond; LCD line. If at the end of the sec ond line, then LCD is; re set to the first line.LCDscroll:

incf LCDcount,f ; Bump coun ter; Test for line limit

movf LCDcount,wsublw LCDlimit ; Count mi nus limitbtfss STATUS,z ; Is count - limit = 0goto scrollExit ; Go if not at end of line

; At this point the end of the LCD line was reached; Test if this is also the end of the sec ond line

movf LCDline,wsublw 0x01 ; Is it line 1?btfsc STATUS,z ; Is LCDline mi nus 1 = 0?goto line2End ; Go if end of sec ond line

; At this point it is the end of the top LCD linecall line2 ; Scroll to sec ond lineclrf LCDcount ; Re set coun terincf LCDline,f ; Bump line coun tergoto scrollExit

; End of sec ond LCD lineline2End:

call initLCD ; Re setclrf LCDcount ; Clear coun tersclrf LCDlinecall line1 ; Dis play to first line

scrollExit:re turnend

862 Appendix H

Page 884: Embedded Syatems Circuits and Programming · Chap ter 4 – In put and Output Devices 41 4.1 Ob tain ing In put 41 4.2 Switches 41 4.2.1 Switch Con tact Bounce 43 4.2.2 Keypads 44

K13700 Cover 3/26/12 11:27 AM Page 1

C M Y CM MY CY CMY K

During the development of an engineered product, developers often

need to create an embedded system—a prototype—that demonstrates

the operation/function of the device and proves its viability. Offering

practical tools for the development and prototyping phases, Embedded

Systems Circuits and Programming provides a tutorial on microcontroller

programming and the basics of embedded design.

The book focuses on several development tools and resources:

• Standard and off-the-shelf components, such as input/output

devices, integrated circuits, motors, and programmable

microcontrollers

• The implementation of circuit prototypes via breadboards, the

in-house fabrication of test-time printed circuit boards (PCBs),

and the finalization by the manufactured board

• Electronic design programs and software utilities for creating PCBs

• Sample circuits that can be used as part of the targeted

embedded system

• The selection and programming of microcontrollers in the circuit

For those working in electrical, electronic, computer, and software

engineering, this hands-on guide helps you successfully develop

systems and boards that contain digital and analog components

and controls. The text includes easy-to-follow sample circuits and their

corresponding programs, enabling you to use them in your own work.

For critical circuits, the authors provide tested PCB files. Software, code,

and other materials are available at www.crcpress.com.

Computer Science

EMBEDDEDSYSTEMS CIRCUITS

andPROGRAMMING

Julio SanchezMaria P. Canton

EMBEDDEDSYSTEMS CIRCUITS

andPROGRAMMING

Julio SanchezMaria P. Canton

EMBEDDED SYSTEMS CIRCUITSand PROGRAMMING

SanchezCanton

6000 Broken Sound Parkway, NWSuite 300, Boca Raton, FL 33487711 Third AvenueNew York, NY 100172 Park Square, Milton ParkAbingdon, Oxon OX14 4RN, UK

an informa business

K13700