Saturday, October 4, 2008

Quintessential Pic Micro Controller


Sid Katzen The Quintessential PIC Microcontroller SPIN Springer’s internal project number, if known No edu Engineering – Monograph (English) for se November 8, 2000 l, u cia er om rc t fo tio ca nly no Springer-Verlag Berlin Heidelberg New York London Paris Tokyo Hong Kong Barcelona Budapest http://i-tronics.blogspot.com/ Contents List of Figures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . List of Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . VI XI List of Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . XIV Part I 1. 2. 3. The Fundamentals Digital Representation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Logic Circuitry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Stored Program Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . for ot N 4. 5. 6. 7. 8. 9. Part II The PIC16F84 Microcontroller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77 The Instruction Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105 Subroutines and Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137 Interrupt Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171 Assembly language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197 High-Level Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231 The Outside World me co The Software ial rc us , ef edu or tio ca nly no 3 17 41 Part III 10. The Real World . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253 11. One Byte at a Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271 http://i-tronics.blogspot.com/ VI Contents 12. One Bit at a Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305 13. Time is of the Essence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361 14. Take the Rough with the Smooth . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391 15. To Have and to Hold . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431 16. A Case Study . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455 Appendices A. B. C. D. 14-bit Core Instruction Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 475 Special Purpose Register Structure for the PIC16C74B . . . . . . . . . 477 C Instruction Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 479 Acronyms and Abbreviations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481 Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 485 for ot N me co al, rci ef us edu or tio ca nly no http://i-tronics.blogspot.com/ List of Figures 1.1 1.2 1.3 1.4 1.5 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 2.10 2.11 2.12 2.13 2.14 2.15 2.16 2.17 2.18 2.19 2.20 2.21 2.22 2.23 2.24 3.1 3.2 3.3 3.4 The NOT operation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The AND function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The inclusive-OR operation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The XOR operation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Detecting sign over?ow. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . for ot N me co The 74LS00 quad 2-I/P NAND package. . . . . . . . . . . . . . . . . . . . . . . Output structures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Open-collector bu?ers driving a party line. . . . . . . . . . . . . . . . . . . Sharing a bus. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The 74LS138 and ’139 MSI natural decoders. . . . . . . . . . . . . . . . . The 74LS688 octal equality detector. . . . . . . . . . . . . . . . . . . . . . . . . Addition. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Implementing a programmable adder/subtractor. . . . . . . . . . . . The 74LS382 ALU. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A ROM-implemented 1-bit adder. . . . . . . . . . . . . . . . . . . . . . . . . . . . The 2764 Erasable PROM. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Floating-gate MOSFET link . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The R S latch. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Using a R S latch to debounce a switch. . . . . . . . . . . . . . . . . . . . . . . The D latch and ?ip ?op. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The 74LS74 dual D ?ip ?op. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The 74LS377 octal D ?ip ?op array. . . . . . . . . . . . . . . . . . . . . . . . . . The 74LS373 octal D latch array. . . . . . . . . . . . . . . . . . . . . . . . . . . . . An 8-bit ALU-accumulator processor. . . . . . . . . . . . . . . . . . . . . . . . The SISO shift register. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The T ?ip ?op. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A modulo-16 ripple counter. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Generating timing waveforms. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The 6264 8196 × 8 RAM. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . al, rci ef us edu or tio ca 12 13 13 14 15 18 19 20 20 21 23 24 25 25 26 27 27 29 30 31 32 33 34 35 36 36 37 38 39 42 44 45 50 nly no An elementary von Neumann computer. . . . . . . . . . . . . . . . . . . . . . An elementary Harvard architecture computer. . . . . . . . . . . . . . . Executing the 1st instruction whilst fetching down the 2nd. . . Parallel fetch and execute streams. . . . . . . . . . . . . . . . . . . . . . . . . . . http://i-tronics.blogspot.com/ VIII List of Figures 3.5 3.6 3.7 3.8 3.9 3.10 3.11 3.12 4.1 4.2 4.3 4.4 4.5 4.6 5.1 5.2 5.3 5.4 6.1 6.2 6.3 6.4 6.5 6.6 6.7 6.8 6.9 7.1 7.2 7.3 7.4 7.5 7.6 8.1 8.2 8.3 8.4 8.5 8.6 8.7 Programmer’s model. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The indirect mechanism. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Circular shifts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The process. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Visualization of the task process. . . . . . . . . . . . . . . . . . . . . . . . . . . . Division by repetitive subtracting. . . . . . . . . . . . . . . . . . . . . . . . . . . Double-precision shifting. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A 7-bit pseudo-random number generator. . . . . . . . . . . . . . . . . . . An example of a system based on a microcontroller. . . . . . . . . . Architecture of the PIC16F84 microcontroller . . . . . . . . . . . . . . . Showing how all of the PC are altered when writing to PCL. . . . Internal clock sequencing waveforms. . . . . . . . . . . . . . . . . . . . . . . . The PIC16F84 Status register . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Data store memory map. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54 57 61 65 65 68 70 70 81 85 86 87 89 92 General 14-bit core Status register. . . . . . . . . . . . . . . . . . . . . . . . . . . The indirect mechanism. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The ith section of the compare-update sequence. . . . . . . . . . . . . Generating a 13-bit Program-store address. . . . . . . . . . . . . . . . . . . Modular hardware implementing a PC. . . . . . . . . . . . . . . . . . . . . . . Subroutine calling. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Using the hardware stack hold return addresses. . . . . . . . . . . . . Nested subroutines. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . System view of K × 100 ms delay subroutine. . . . . . . . . . . . . . . . . The 7-segment display. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . System diagram for the byte multiplication subroutine. . . . . . . The stack frame. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Finding the square root of an integer. . . . . . . . . . . . . . . . . . . . . . . . for ot N me co al, rci ef us edu or tio ca 109 109 112 114 nly no 138 140 141 142 145 148 150 154 162 172 175 176 178 188 195 198 202 211 213 219 221 222 Detecting and measuring an external event. . . . . . . . . . . . . . . . . . Responding to an interrupt request. . . . . . . . . . . . . . . . . . . . . . . . . . The ?ag:mask pair. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The PIC 16F84’s interrupt logic. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Oven safety hardware. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Echo sounding hardware. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Conversion from assembly-level source to machine code. . . . . Absolute assembly-level code translation. . . . . . . . . . . . . . . . . . . . Relocatable assembly-level code translation. . . . . . . . . . . . . . . . . . Linking three source ?les. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Code building and testing tools. . . . . . . . . . . . . . . . . . . . . . . . . . . . . MPLAB window. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . MPLAB screen shot. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . http://i-tronics.blogspot.com/ List of Figures IX 9.1 9.2 9.3 9.4 10.1 10.2 10.3 10.4 10.5 10.6 10.7 10.8 10.9 11.1 11.2 11.3 11.4 11.5 11.6 11.7 11.8 11.9 11.10 11.11 11.12 11.13 11.14 11.15 Conversion from high-level source code to machine code. . . . . Onion skin view of the steps leading to executable code. . . . . . Simulating our example program in MPLAB. . . . . . . . . . . . . . . . . . The active-low die patterns. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Pinout for a variety of PIC family members. . . . . . . . . . . . . . . . . . Typical supply current versus clocking frequency. . . . . . . . . . . . Equivalent output circuit. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Typical oscillator con?gurations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . Con?guration word for the PIC16F83/4. . . . . . . . . . . . . . . . . . . . . . Manually resetting the PIC. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The sequence of events leading to startup on power-up. . . . . . Brown-out reset. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . An alternative brown-out circuit. . . . . . . . . . . . . . . . . . . . . . . . . . . . . The mid-range PIC 16CXX series Parallel Ports A and B. . . . . . . A simpli?ed typical I/O port line. . . . . . . . . . . . . . . . . . . . . . . . . . . . Reading and writing to a port bit set to input or output. . . . . . Sinking and sourcing current. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Port A I/O pin driver structure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Interfacing switches to a port line. . . . . . . . . . . . . . . . . . . . . . . . . . . Port B’s weak pull-up option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Interfacing to a keypad. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The Port B change feature. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A multi-zone intruder alarm. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Source current against voltage. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The stepper motor. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Using port expansion to drive three 7-segment displays. . . . . . Scanning a 3-digit 7-segment array. . . . . . . . . . . . . . . . . . . . . . . . . . Low-level output voltage against sink current. . . . . . . . . . . . . . . . 233 234 242 250 254 256 257 258 261 263 264 267 269 272 273 275 276 278 280 280 281 285 287 290 294 298 299 304 for ot N me co al, rci ef us edu or tio ca nly no 12.1 12.2 12.3 12.4 12.5 12.6 12.7 12.8 12.9 12.10 12.11 12.12 12.13 12.14 The smart card. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305 Serial interface to a 3-digit 7-segment display. . . . . . . . . . . . . . . . 307 Logic functional diagram of the 74HCT595 octal shift register. 309 Serially interfacing to a DAC0800 digital to analog converter. 310 Serially interfacing to the multi-zone intruder alarm. . . . . . . . . 311 The MAX549A SPI dual 8-bit DAC. . . . . . . . . . . . . . . . . . . . . . . . . . . 314 SPI waveforms for the MAX549A. . . . . . . . . . . . . . . . . . . . . . . . . . . . 316 Multiple MAX549As on the one SPI circuit. . . . . . . . . . . . . . . . . . . 316 The basic Serial Synchronous Port. . . . . . . . . . . . . . . . . . . . . . . . . . . 317 The SSP CONtrol and STATus registers. . . . . . . . . . . . . . . . . . . . . . 318 SSP SPI-mode master waveforms. . . . . . . . . . . . . . . . . . . . . . . . . . . . 321 A multidrop SPI communications network. . . . . . . . . . . . . . . . . . . 322 Data transfer on the I2 C bus. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325 Sharing the SCL and SDA bus lines. . . . . . . . . . . . . . . . . . . . . . . . . . . 326 http://i-tronics.blogspot.com/ X List of Figures 12.15 12.16 12.17 12.18 12.19 12.20 12.21 12.22 12.23 12.24 12.25 13.1 13.2 13.3 13.4 13.5 13.6 13.7 13.8 13.9 13.10 13.11 14.1 14.2 14.3 14.4 14.5 14.6 14.7 14.8 14.9 14.10 14.11 14.12 14.13 14.14 14.15 14.16 14.17 14.18 A I2 C packet transmission. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The MAXIM MAX518 I2 C dual digital to analog converter. . . . . Minimum timing relationships for the Fast I2 C mode. . . . . . . . . Transmitting the string "PIC" in the asynchronous mode . . . . . The PIC USART con?gured for asynchronous communication. Some signalling con?gurations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Communicating with a PC via an RS-232 link. . . . . . . . . . . . . . . . . The 24XXX series of I2 C serial EEPROMs. . . . . . . . . . . . . . . . . . . . . EEPROM Read and Write waveforms. . . . . . . . . . . . . . . . . . . . . . . . . Interfacing the DS1820 1-Wire digital thermometer. . . . . . . . . . A LCD display. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The integral PIC Watchdog timer. . . . . . . . . . . . . . . . . . . . . . . . . . . . The Option register. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Simpli?ed equivalent circuit for Timer 0. . . . . . . . . . . . . . . . . . . . . Counting cans of beans on a conveyer belt. . . . . . . . . . . . . . . . . . . Functional equivalent circuit for Timer 1 . . . . . . . . . . . . . . . . . . . . The CCP1 module set to Compare mode. . . . . . . . . . . . . . . . . . . . . Capturing the time of an event. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A simpli?ed equivalent circuit for Timer 2. . . . . . . . . . . . . . . . . . . Pulse width modulation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Timer 2 and the PWM CCP mode. . . . . . . . . . . . . . . . . . . . . . . . . . . . . An event manifesting itself as a pulse duration. . . . . . . . . . . . . . 327 328 329 336 342 347 349 352 355 356 360 362 363 365 366 372 375 377 379 380 381 387 for ot N me co Analog world – digital processing. . . . . . . . . . . . . . . . . . . . . . . . . . . The quantizing process. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The analog–digital process. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Illustrating aliasing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Initializing the 8-4-2-1 capacitor network. . . . . . . . . . . . . . . . . . . . Simpli?ed view of the A/D converter. . . . . . . . . . . . . . . . . . . . . . . . The successive approximation process. . . . . . . . . . . . . . . . . . . . . . The 8-bit 8-channel analog to digital conversion module. . . . . Con?guring the analog inputs for Port A and Port E. . . . . . . . . . . Interrupt control for the ADC module. . . . . . . . . . . . . . . . . . . . . . . R-2R digital-to-analog conversion. . . . . . . . . . . . . . . . . . . . . . . . . . . . The Maxim MAX506 quad 8-bit D/A converter. . . . . . . . . . . . . . . Generating a continuous sawtooth using a MAX506 DAC. . . . . Bu?ered data acquisition. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A level-shifting resistor network. . . . . . . . . . . . . . . . . . . . . . . . . . . . . ECG detection strategy. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A controllable external voltage circuit. . . . . . . . . . . . . . . . . . . . . . . Pinning for the PIC16C71. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . al, rci ef us edu or tio ca nly no 391 393 396 397 398 400 402 404 405 408 416 418 419 420 423 426 429 429 15.1 The PIC16F8X Data EEPROM module. . . . . . . . . . . . . . . . . . . . . . . . . 433 15.2 The PIC16F8X EECON1 register. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 434 http://i-tronics.blogspot.com/ List of Figures XI 15.3 15.4 15.5 15.6 15.7 15.8 16.1 16.2 16.3 16.4 16.5 The ?rst 32 bytes of EEPROM. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The PIC16F87X ?ash and Data EEPROM storage system. . . . . . . The PIC16F87X EEPROM Control register 1. . . . . . . . . . . . . . . . . . . View of the ?ash Program module. . . . . . . . . . . . . . . . . . . . . . . . . . . Con?guration word for the PIC16F87X devices. . . . . . . . . . . . . . . Watchdog timer period versus temperature. . . . . . . . . . . . . . . . . . The annunciator hardware. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The modular software structure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . The Main process. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Programming the PIC from MPLAB. . . . . . . . . . . . . . . . . . . . . . . . . . . The Microchip PICSTART Plus programmer. . . . . . . . . . . . . . . . . . 438 440 441 445 445 448 456 458 468 472 473 for ot N me co al, rci ef us edu or tio ca nly no http://i-tronics.blogspot.com/ for ot N me co al, rci ef us edu or tio ca nly no http://i-tronics.blogspot.com/ List of Tables 1.1 1.2 1.3 3.1 5.1 5.2 5.3 5.4 6.1 6.2 8.1 8.2 8.3 8.4 8.5 8.6 8.7 7-bit ASCII characters. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Some common bit groupings. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Di?erent ways of representing the quantities decimal 0…20. . Our BASIC computer’s instruction set. . . . . . . . . . . . . . . . . . . . . . . Move instructions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Arithmetic. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Logic instructions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Program Counter instructions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Subroutine and interrupt handling instructions. . . . . . . . . . . . . . 139 The 7-segment lookup table showing byte[N] being extracted. 149 for ot N 9.1 me co The listing ?le root.lst. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The absolute 8-bit Intel format object-code ?le root.hex. . . . The error ?le . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Part of Microchip’s ?le p16f84.inc. . . . . . . . . . . . . . . . . . . . . . . . . The pic16f84.lkr linker command ?le. . . . . . . . . . . . . . . . . . . . . The output linker map ?le rms.asm. . . . . . . . . . . . . . . . . . . . . . . . . The resulting absolute object ?le rms.hex. . . . . . . . . . . . . . . . . . . al, rci ef us edu or tio ca 53 115 117 121 127 nly no 5 6 7 206 206 207 209 212 218 219 Resulting assembly-level CCS compiler output after linking. . . 240 10.1 PIC16F83/4 Special-Purpose Register ?le reset summary. . . . . 263 10.2 Power-up reset and sleep timeouts. . . . . . . . . . . . . . . . . . . . . . . . . 265 10.3 Reset conditions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266 11.1 Summary of mid-range PIC parallel I/O provision. . . . . . . . . . . . 272 11.2 Energization pattern for the eight ?eld directions. . . . . . . . . . . . 294 12.1 The SSP Mode bits. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319 14.1 Quantization parameters. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 394 14.2 ADC clocking frequency versus device crystal frequency. . . . . 401 14.3 Con?guring the ADC port pins in the PIC16C73/74 devices. . . 405 http://i-tronics.blogspot.com/ for ot N me co al, rci ef us edu or tio ca nly no http://i-tronics.blogspot.com/ List of Programs for ot N 3.1 3.2 3.3 3.4 3.5 3.6 3.7 3.8 4.1 4.2 5.1 5.2 5.3 5.4 5.5 5.6 5.7 5.8 5.9 5.10 5.11 6.1 6.2 6.3 6.4 6.5 6.6 6.7 6.8 6.9 6.10 6.11 6.12 6.13 me co Clearing a block of ?les the linear way. . . . . . . . . . . . . . . . . . . . . . . Clearing a block of ?les using a repeating loop. . . . . . . . . . . . . . . Simple single-precision addition of two byte variables. . . . . . . . A more accurate single-precision addition. . . . . . . . . . . . . . . . . . . The double-precision add program. . . . . . . . . . . . . . . . . . . . . . . . . . Dividing by ten. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Multiplying by nine. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A 7-bit pseudo-random number generator. . . . . . . . . . . . . . . . . . . Incrementing a packed BCD byte. . . . . . . . . . . . . . . . . . . . . . . . . . . . Adding two packed BCD numbers. . . . . . . . . . . . . . . . . . . . . . . . . . . Finding the maximum temperature the linear way. . . . . . . . . . . . Finding the maximum temperature using a loop structure. . . . Division by repetitive subtraction. . . . . . . . . . . . . . . . . . . . . . . . . . . Shifting to ?nd the highest set bit. . . . . . . . . . . . . . . . . . . . . . . . . . . Triple-precision shifting to ?nd the number of set bits. . . . . . . Multiplying by three. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Double-precision decrement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Bi-quinary error detection. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Binary to 2-digit BCD conversion. . . . . . . . . . . . . . . . . . . . . . . . . . . . Average daily temperature. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . multiplication by ten. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A 100 ms delay subroutine. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A K × 100 ms delay subroutine. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . An alternative K × 100 ms delay subroutine. . . . . . . . . . . . . . . . . The software 7-segment decoder. . . . . . . . . . . . . . . . . . . . . . . . . . . . The byte multiplication subroutine. . . . . . . . . . . . . . . . . . . . . . . . . . Implementing a byte multiply using a stack model. . . . . . . . . . . Dividing by three . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Coding a 208 µs delay. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A 1-second delay program. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Binary to 3-digit BCD conversion. . . . . . . . . . . . . . . . . . . . . . . . . . . . Coding the square root subroutine. . . . . . . . . . . . . . . . . . . . . . . . . . Using a software stack to pass parameters. . . . . . . . . . . . . . . . . . . The software 7-segment decoder revisited. . . . . . . . . . . . . . . . . . . al, rci ef us edu or tio ca 56 57 64 64 66 67 69 71 101 103 111 113 118 124 125 126 128 130 131 132 133 144 146 147 149 152 157 158 159 160 161 163 166 166 nly no http://i-tronics.blogspot.com/ XVI List of Programs for ot N 7.1 7.2 7.3 7.4 7.5 7.6 8.1 8.2 8.3 8.4 9.1 9.2 9.3 9.4 11.1 11.2 11.3 11.4 11.5 11.6 11.7 11.8 12.1 12.2 12.3 12.4 12.5 12.6 12.7 12.8 12.9 12.10 12.11 12.12 12.13 12.14 12.15 12.16 13.1 13.2 13.3 13.4 13.5 13.6 me co Background program for the pea canning packer. . . . . . . . . . . . . Event counting foreground software. . . . . . . . . . . . . . . . . . . . . . . . . Oven safety. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Saving and restoring the context for the PIC16C74 processor. Coding the real-time clock ISR. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Incrementing a packed-BCD byte with maximum value of 99. . Absolute assembly-level code for our square-root module. . . . The main relocatable source ?le main.asm. . . . . . . . . . . . . . . . . . . The relocatable source ?le sqr.asm. . . . . . . . . . . . . . . . . . . . . . . . . The relocatable source ?le root2.asm. . . . . . . . . . . . . . . . . . . . . . . A simple function coded in C. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Coding the square root function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . Linearizing a K-type thermocouple. . . . . . . . . . . . . . . . . . . . . . . . . . Generating the root-mean square value of two variables. . . . . . Scanning the keypad. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Noise ?ltered keypad scanning. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Interacting with the intruder hardware. . . . . . . . . . . . . . . . . . . . . . A digital comparator with hysteresis. . . . . . . . . . . . . . . . . . . . . . . . Driving a stepper motor. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Coding the keypad device driver in C. . . . . . . . . . . . . . . . . . . . . . . . Displaying the decimal equivalent of a binary byte. . . . . . . . . . . Displaying a 3-digit decimal number on a scanning readout. . Displaying the decimal equivalent of a binary byte. . . . . . . . . . . Input serial byte subroutine. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Interacting with the MAX549A dual-channel SPI DAC. . . . . . . . . Using the SSP for SPI data input and output. . . . . . . . . . . . . . . . . . Interfacing to the MAX549A in C. . . . . . . . . . . . . . . . . . . . . . . . . . . . A crystal frequency-independent short delay macro. . . . . . . . . . Low-level I2 C subroutines. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Interacting with the MAX518 dual-channel I2 C DAC. . . . . . . . . . Interfacing to the MAX518 in C. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A baud-rate delay macro. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Asynchronous formatted input and output subroutines. . . . . . The USART-based I/O subroutines. . . . . . . . . . . . . . . . . . . . . . . . . . . Updating Program 11.4’s trip value. . . . . . . . . . . . . . . . . . . . . . . . . . Reading in a byte using the I2 C protocol. . . . . . . . . . . . . . . . . . . . . Incrementing the non-volatile odometer count. . . . . . . . . . . . . . . Reading and writing on a 1-Wire system. . . . . . . . . . . . . . . . . . . . . The bean counter Interrupt Service Routine. . . . . . . . . . . . . . . . . . Measuring the ECG waveform period to a resolution of 1 ms. . Generating a 15 minute data logger timebase. . . . . . . . . . . . . . . . Capturing the instant of time an ECG R-point occurs. . . . . . . . . Pulse-Width Modulation using Timer 0. . . . . . . . . . . . . . . . . . . . . . . Tachometer software. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . al, rci ef us edu or tio ca 181 183 187 191 193 194 200 214 215 216 236 245 246 247 283 284 288 292 293 297 301 302 308 312 315 320 323 331 332 334 335 338 340 345 350 351 354 358 368 370 374 378 384 386 nly no http://i-tronics.blogspot.com/ List of Programs XVII 13.7 14.1 14.2 14.3 14.4 14.5 14.6 14.7 14.8 14.9 15.1 15.2 15.3 15.4 15.5 15.6 15.7 15.8 15.9 15.10 16.1 16.2 16.3 16.4 16.5 16.6 for ot N me co Measuring the duration of a pulse. . . . . . . . . . . . . . . . . . . . . . . . . . . 388 Taking a reading from channel n. . . . . . . . . . . . . . . . . . . . . . . . . . . . 407 Interrupt-driven subroutine to read channel n. . . . . . . . . . . . . . . 410 The ISR for our interrupt-driven ADC software. . . . . . . . . . . . . . . 411 Digitizing Channel 1 of a PIC16C71 device. . . . . . . . . . . . . . . . . . . 412 A digital/analog comparator with hysteresis. . . . . . . . . . . . . . . . . 414 Bu?ered interrupt-driven data acquisition. . . . . . . . . . . . . . . . . . . 421 Sleep conversion in C. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 422 ECG peak picking. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425 An implementation of the ECG peak picker in C. . . . . . . . . . . . . . 427 Retrieving a byte from the EEPROM Data module. . . . . . . . . . . . . 434 Putting a byte into the EEPROM Data module. . . . . . . . . . . . . . . . . 436 Incrementing the non-volatile odometer count in Data EEPROM. 437 Reading a word from the ?ash Program store. . . . . . . . . . . . . . . . 442 Writing to ?ash Program memory. . . . . . . . . . . . . . . . . . . . . . . . . . . 443 Squaring an integer. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 444 C-based coding for the odometer. . . . . . . . . . . . . . . . . . . . . . . . . . . . 446 The Sauna Power-up reset sequence and ISR. . . . . . . . . . . . . . . . . 450 Reading a new period count. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 451 Updating the Sauna EEPROM. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 452 The timebase software. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461 The data display function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463 The initialization code. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465 The Diagnostic process. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 466 The Set-time process. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 467 The Main process. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 471 al, rci ef us edu or tio ca nly no http://i-tronics.blogspot.com/ PART I The Fundamentals for ot N • • • • This book is about microcontrollers (MCUs). These are digital engines modelled after the architecture of a stored-program computer and integrated on to a single very large-scale integrated circuit together with support circuitry, memories and peripheral interface devices. Although the MCU is often confused with its better known cousin the microprocessor in its role of the driving force of the ubiquitous personal computer, the vast majority of both microprocessors and microcontrollers are embedded into an assemblage of other digital components. The ?rst microprocessors in the early 1970s were marketed as an alternative way of implementing digital circuitry. Here the task would be determined by a series of instructions encoded as binary code groups in read-only memory. This is more ?exible than the alternative approach of wiring hardware integrated circuits in the appropriate manner. The microcontroller is simply the embodiment of this original role of the integrated computer. We will look at embedded MCUs in a general digital processing context in Parts II and III. Here our objective is to lay the foundation for this material. We will be covering: Digital code patterns. Binary arithmetic. Digital circuitry. Computer architecture and programming. me co al, rci ef us edu or tio ca nly no This will by no means be a comprehensive review of the subject, but there are many other excellent texts in this area1 which will launch you into greater depths. 1 Such as S.J. Cahill’s Digital and Microprocessor Engineering, 2nd edn., Prentice Hall, 1993. http://i-tronics.blogspot.com/ for ot N me co al, rci ef us edu or tio ca nly no http://i-tronics.blogspot.com/ CHAPTER 1 Digital Representation for ot N To a computer or microprocessor, the world is seen in terms of patterns of digits. The decimal (or denary) system represents quantities in terms of the ten digits 0…9. Together with the judicious use of the symbols +, - and . any quantity in the range ±8 can be depicted. Indeed non-numeric concepts can be encoded using numeric digits. For example the American Standard Code for Information Interchange (ASCII) de?nes the alphabetic (alpha) characters A as 65, B = 66…Z = 90 and a = 97, b = 98…z = 122 etc. Thus the string “Microprocessor” could be encoded as “77, 105, 99, 114, 111, 112, 114, 111, 99, 101, 115, 115, 111, 114”. Provided you know the context, that is what is a pure quantity and what is text, then just about any symbol can be coded as numeric digits.1 Electronic circuits are not very good at storing and processing a multitude of di?erent symbols. It is true that the ?rst American digital computer, the ENIAC (Electronic Numerical Integrator And Calculator) in 1946 did its arithmetic in decimal2 but all computers since handle data in binary (base 2) form. The decimal (base 10) system is really only convenient for humans, in that we have ten ?ngers.3 Thus in this chapter we will look at the properties of binary digits, their groupings and processing. After reading it you will: me co al, rci ef us edu or tio ca nly no • Understand why a binary data representation is the preferred base for • Know how a quantity can be depicted in natural binary, hexadecimal • Be able to apply the rules of addition and subtraction for natural binary quantities. • Know how to multiply by shifting left. • Know how to divide by shifting right and propagating the sign bit. • Understand the Boolean operations of NOT, AND, OR and XOR. and binary coded decimal. digital circuitry. The information technology revolution is based on the manipulation, computation and transmission of digitized information. This informa1 Of course there are lots of encoding standards, for example the 6-dot Braille code for the visually impaired. 2 As did Babbage’s mechanical computer of a century earlier. 3 And ten toes, but base-20 systems are rare. http://i-tronics.blogspot.com/ 4 The Quintessential PIC Microcontroller tion is virtually universally represented as aggregrates of binary digits (bits).4 Most of this processing is e?ected using microprocessors, and it is sobering to re?ect that there is more computing power in a singing birthday card than existed on the entire planet in 1950! Binary is the universal choice for data representation, as an electronic switch is just about the easiest device that can be implemented using a transistor. Such 2-state switches are very small; they change state very quickly and consume little power. Furthermore, as there are only two states to distinguish between, a binary depiction is likely to be resistant to the e?ects of noise. The upshot of this is that both the packing density on a silicon chip and switching rate can be very high. Although a switch on its own does not represent much computing power; ?ve million switches changing at 100 million times a second, manage to present at least a facade of intelligence! The two states of a bit are conventionally designated logic 0 and logic 1 or just 0 & 1. A bit may be represented by two states of any number of physical quantities; for example electric current or voltage, light, pneumatic pressure. Most microprocessors use 0 V (or ground) for state 0 and 3 – 5 V for state 1, but this is not universal. For instance, the RS232 serial port on your computer uses nominally +12 V for state 0 and -12 V for state 1. A single bit on its own can only represent two states. By dealing with groups of bits, rather more complex entities can be coded. For example the standard alphanumeric characters can be coded using 7-bit groups of digits. Thus the ASCII code for “Microprocessor” becomes: for ot N 1001101 1101001 1100011 1110010 1101111 1110000 1110010 1101111 1100011 1100100 1110011 1110011 1101111 1110010 Unicode is an extension of ASCII and with its 16-bit code groups is able represent characters from many languages and mathematical symbols. The ASCII code is unweighted, as the individual bits do not signify a particular quantity; only the overall pattern has any signi?cance. Other examples are the die code on gaming dice and 7-segment code of Fig. 6.6 on page 148. Here we will deal with natural binary weighted codes, where the position of a bit within the number ?eld determines its value or weight. In an integer binary number the rightmost digit is worth 20 = 1, the next left column 21 = 2 and so on to the nth column which is worth 2n-1 . For example the decimal number one thousand nine hundred and ninety eight is represented as 1×103 +9×102 +9×101 +8×100 or 1998. 4 The binary base is not a new fangled idea invented for digital computer; many cultures have used base 2 numeration in the past. The Harapp¯n civilisation existed more than a 4000 years ago in the Indus river basin. Found in the ruins of the Harapp¯n city of a Mohenjo-Daro, in the beadmakers’ quarter, was a set of stone pebble weights. These were in ratios that doubled in the pattern, 1,1,2,4,8,16…, with the base weight of around 25g (˜ 1oz). Thus bead weights were expressed by digits which represented powers of 2; that is in binary. me co al, rci ef us edu or tio ca nly no http://i-tronics.blogspot.com/ 1. Digital Representation Table 1.1: 7-bit ASCII characters. MS nybble LS nybble 5 NUL SOH STX ETX EOT ENQ ACK BEL BS HT LF DLE DC1 DC2 DC3 DC4 NAK SYN ETB CAN EM SP ! " # $ % & ’ ( ) 0 1 2 3 4 5 6 7 8 @ A B C D E F G P Q R S T U V W X ‘ a b c d e f p q r s t u v No for t om c FF CR SO SI VT cia er ESC FS GS RS US SUB us l, * + , . / 9 : ; ef edu or H I Y Z [ \ } ^ J K L M N O tio ca g w x y z { | } ~ DEL h i j k l m n o nly no < = > ? _ In natural binary the same quantity is 1 × 210 + 1 × 29 + 1 × 28 + 1 × 27 + 1×26 +0×25 +0×24 +1×23 +1×22 +0×21 +1×20 , or 11111001101b. Fractional numbers may equally well be represented by columns to the right of the binary point using negative powers of 2. Thus 1101.11b is equivalent to 14.75. As can be seen from this example, binary numbers are rather longer than their decimal equivalent; on average a little over three times. Nevertheless, 2-way switches are considerably simpler than 10-way devices, so the binary representation is preferable. An n-digit binary number can represent up to 2n patterns. Most computers store and process groups of bits. For example the ?rst micropro- http://i-tronics.blogspot.com/ 6 The Quintessential PIC Microcontroller cessor, the Intel 4004, handled its data four bits (a nybble) at a time. Many current processors cope with blocks of 8 bits (a byte), 16 bits (a word), or 32 bits (a long-word). 64-bit (a quad-word) devices are on the horizon. These groupings are shown in Table 1.2. The names illustrated are somewhat de-facto, and variations are sometimes encountered. As in the decimal number system, large binary numbers are often expressed using the pre?xes k (kilo), M (mega) and G (giga). A binary kilo is 210 = 1024; for example 64 kbyte of memory. In an analogous way, a binary mega is 220 = 1, 048, 576; thus a 1.44 Mbyte ?oppy disk. Similarly a 2 Gbyte hard disk has a storage capacity of 2 × 230 = 2, 147, 483, 648 bytes. The former representation is certainly preferable. Table 1.2: Some common bit groupings. Bit (0-1) (1 bit) (4 bits) (8 bits) (16 bits) 0-1 0-15 0-255 0-65,535 Nybble (0000-1111) Byte Word (0000 0000-11111 1111) (0000 0000 0000 0000-1111 1111 1111 1111) Long-word (32 bits) (0000 0000 0000 0000 0000 0000 0000 0000-1111 1111 1111 1111 1111 1111 1111 1111) for ot N Long binary numbers are not very human friendly. In Table 1.2, binary numbers were zoned into ?elds of four digits to improve readability. Thus the address of a data unit stored in memory might be 1000 1100 0001 0100 0000 1010b. If each group of four can be given its own symbol, 0…9 and A…F, as shown in Table 1.3, then the address becomes 8C140Ah; a rather more manageable characterization. This code is called hexadecimal, as there are 16 symbols. Hexadecimal (base-16) numbers are a viable number base in their own right, rather than just being a convenient binary representation. Each column is worth 160 , 161 , 162 . . . 16n in the normal way.5 Binary Coded Decimal is a hybrid binary/decimal code extensively used at the input/output ports of a digital system (see Example 11.5 on page 298). Here each decimal digit is individually replaced by its 4-bit binary equivalent. Thus 1998 is coded as (0001 1001 1001 1000)BCD . This is very di?erent from the equivalent natural binary code; even if it is represented by 0s and 1s. As might be expected, arithmetic in such can do hexadecimal arithmetic. 5 Many scienti?c calculators, including that in the Accessories group under Windows 95, me co al, rci 0-4,294,967,295 ef us edu or tio ca nly no http://i-tronics.blogspot.com/ 1. Digital Representation Table 1.3: Di?erent ways of representing the quantities decimal 0…20. Decimal 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 Natural binary 00000 00001 00010 00011 00100 00101 00110 00111 01000 01001 01010 01011 01100 01101 01110 01111 10000 10001 10010 10011 10100 Hexadecimal 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 11 12 13 14 Binary 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0001 0001 0001 0001 0001 0001 0001 0001 0001 0001 0010 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 0000 7 for ot N a hybrid system is di?cult, and BCD is normally converted to natural binary at the system input and processing is done in natural binary before being converted back (see Program 5.9 on page 131). The rules of arithmetic are the same in natural binary6 as they are in the more familiar base 10 system, indeed any base-n radix scheme. The simplest of these is addition, which is a shorthand way of totalling quantities, as compared to the more primitive counting or incrementation process. Thus 2+4 = 6 is rather more e?cient than 2+1 = 3; 3+1 = 4; 4 + 1 = 5; 5 + 1 = 6. However, it does involve memorizing the rules of addition.7 In decimal this involves 45 rules, assuming that order is irrelevant; from 0 + 0 = 0 to 9 + 9 = 18. Binary addition is much simpler as it is covered by only three rules: me co al, rci ef us edu or tio ca nly no 0+0 0+1 1+0 1+1 =0 =1 = 10 (0 carry 1) Based on these rules, the least signi?cant bit (LSB) is totalized ?rst, passing a carry if necessary to the next left column. The process ends with 6 Sometimes 7 Which called 8-4-2-1 code after the weightings of the ?rst four lowest columns. you had to do way back in the mists of time in primary/elementary school! http://i-tronics.blogspot.com/ 8 The Quintessential PIC Microcontroller the most signi?cant bit (MSB) column, its carry being the new MSD of the sum. For example: 1 01 001 1 2 63 1 8 42 6 84 21 96 + 37 11 Carries Augend Addend Sum 1100000 + 0100101 11 Carries Augend Addend Sum 133 10000101 (a) Decimal (b) Binary Just as addition implements an up count, subtraction corresponds to a down count, where units are removed from the total. Thus 8 - 5 = 3 is the equivalent of 8 - 1 = 7; 7 - 1 = 6; 6 - 1 = 5; 5 - 1 = 4; 4 - 1 = 3. The technique of decimal subtraction you are familiar with applies the subtraction rules commencing from LSB and working to the MSB. In any given column were a larger quantity is to be taken away from a smaller quantity, a unit digit is borrowed from the next higher column and given back after the subtraction is completed. Based on this borrow principle, the subtraction rules are given by: 0 1 0 1 1 for ot N For example: 1 01 me co 1 Borrows - - - - 0 1 0 1 = = = = 0 1 1 0 al, rci Borrowing 1 from the higher column ef us 63 1 42 6 84 21 edu or tio ca nly no 96 - 37 59 Minuend Subrahend Difference 1100000 - 0100101 11 1111 Minuend Subrahend Borrows 0111011 Difference (a) Decimal (b) Binary Although this familiar method works well, there are several problems implementing it in digital circuitry. • How can we deal with situations where the minuend is larger than the subtrahend? • How can we distinguish between positive and negative quantities? • Can a digital system’s adder circuits be coerced into subtracting? To illustrate these points, consider the following example: http://i-tronics.blogspot.com/ 1. Digital Representation 9 37 - 96 1 Minuend Subtrahend Difference (- 59) (a) Decimal 0100111 - 1100000 1 Minuend Subtrahend Difference (- 0111001) (b) Binary 41 1000111 Normally when we know that the when Minuend is greater than the Subtrahend, the two operands are interchanged and a minus sign is appended to the outcome; that is -(Subtrahend - Minuend). If we do not swap, as in (a) above, then the outcome appears to be incorrect. In fact 41 is correct, in that this is the di?erence between 59 (the correct outcome) and 100. 41 is described as the 10’s complement of 59. Furthermore, the fact that a borrow digit was generated from the MSD indicates that the di?erence is negative, and therefore appears in this 10’s complement form. Converting from 10’s complement decimal numbers to the ‘normal’ magnitude form is simply a matter of inverting each digit and then adding one to the outcome. A decimal digit is inverted by computing its di?erence from 9. Thus the 10’s complement of 3941 is -6059: 3941 ? 6058; +1 = -6059 for ot N However, there is no reason why negative numbers should not remain in this complement form – just because we are not familiar with this type of notation. The complement method of negative quantity representation of course applies to binary numbers. Here the ease of inversion (0 ? 1; 1 ? 0) makes this technique particularly attractive. Thus in our example above: 1000111 ? 0111000; +1 = -0111001 me co al, rci ef us edu or tio ca nly no Again, negative numbers should remain in a 2’s complement form. This complement process is reversible. Thus: complement ? normal ? Signed decimal numeration has the luxury of using the symbols + and - to denote positive and negative quantities. A 2-state system is stuck with 1s and 0s. However, looking at the last example gives us a clue on how to proceed. A negative outcome gives a borrow back out to the highest column. Thus we can use this MSD as a sign bit, with 0 for + and 1 for -. This gives 1,1000111b for -59 and 0,01110011b for +59. Although for clarity the sign bit has been highlighted above using a comma delimiter, the advantage of this system is that it can be treated in all arithmetic processes in the same way as any other ordinary bit. Doing this, the outcome will give the correct sign: http://i-tronics.blogspot.com/ 10 The Quintessential PIC Microcontroller 0,1100000 1,1011011 1 (+96) (- 37) (+59) 0,0100101 1,0100000 1 (+37) (- 96) (- 59) 0,0111011 1,1000101 (a) Minuend less than subtrahend (b) Minuend greater than subtrahend From this example we see that if negative numbers are in a signed 2’s complement form, then we no longer have the requirement to implement hardware subtractors, as adding a negative number is equivalent to subtracting a positive number. Thus A - B = A + (-B). Furthermore, once numbers are in this form, the outcome of any subsequent processing will always remain 2’s complement signed throughout. There are two di?culties associated with signed 2’s complement arithmetic. The ?rst of these is over?ow. It is possible that adding two positive or two negative numbers will cause over?ow into the sign bit; for instance: 0,1000 (+8) 0,1011 (+11) 1 1,0011 (- 13!!!) (a) Sum of two +ve numbers gives - ve tf No om rc o 1 In (a) the outcome of (+8) + (+11) is -13! The 24 numerical digit has over?owed into the sign position (actually, 10011b = 19 is the correct outcome). Example (b) shows a similar problem for the addition of two signed negative numbers. Over?ow can only happen if both operands have the same sign bits. Detection is then a matter of determining this situation with an outcome that di?ers. See Fig. 1.5 for a logic circuit to implement this over?ow condition. The ?nal problem concerns arithmetic on signed operands with different sized ?elds. For instance: 0,0011001 (+25) 0,011 (+03) ???? 0,0011001 (+25) 1,101 (- 03) ???? cia er us l, ef edu or 1 1,1000 (- 8) 1,0101 (- 11) tio ca nly no 0,1101 (+3!!!) (b) Sum of two - ve numbers gives +ve 0,0011001 (+25) 0,0000011 (+03) 11 0,0011001 (+25) 1,1111101 (- 03) 1 1 111 1 0,0011100 (+28) (a) Extending a positive number 0,0010110 (+22) (b) Extending a negative number http://i-tronics.blogspot.com/ 1. Digital Representation 11 Both the examples involve adding an 8-bit to a 16-bit operand. Where the former is positive, the data may be increased to 16 bits by padding with 0s. The situation is slightly less intuitive where negative data requires extension. Here the prescription is to extend the data by padding out with 1s. In the general case the rule is simply to pad out data by propagating the sign bit left. This technique is known as sign extension. Multiplication by the nth power of two is simply implemented by shifting the data left n places. Thus 00101(5) << 01010(10) << 10100(20) multiplies 5 by 22 , where the << operator is used to denote shifting left. The process works for signed numbers as well: 0,00000011 << 0,00000110 << 0,00001100 << 0,00011000 ( 3) ( 6) (12) (24) 1,11111101 << 1,11111010 << 1,11110100 << 1,11101000 ( ¡3) ( - 6) (- 12) (- 24) 0,00000110 (3 x 2) + 0,00011000 (3 x 8) 0,00011110 (3 x 10 = 30) (a) +3 x 8 = +24 (b) - 3 x 8 = - 24 for ot N Should the sign bit change polarity, then a magnitude bit has over?owed. Some computers/microprocessors have a Arithmetic Shift Left process that signals this situation, as opposed to the standard Logic Shift Left used in unsigned number shifts. Multiplication by non-powers of 2 can be implemented by a combination of shifting and adding. Thus as shown in (c) above, 3 × 10 is implemented as (3 × 8) + (3 × 2) = (3 × 10) or (3 << 3) + (3 << 1). In a similar fashion, division by powers of 2 is implemented by shifting right n places. Thus 1100(12) >> 0110(6) >> 0011(3) >> 0001.1(1.5). This process also works for signed numbers: me co al, rci ef us edu or (c) +3 x 10 = 30 tio ca nly no 0,1111.000 >> 0,0111.100 >> 0,0011.110 >> 0,0001.111 (+15) (+7.5) (+3.75) (+1.875) 1,0001.000 >> 1,1000.100 >> 1,1100.010 >> 1,11110.001 (- 15) (- 7.5) (- 3.75) (- 1.875) 0001.1 1010 1111.0 - 1010 0101 - 101.0 000.0 (c) 15/10 = 1.5 (a) +15/8 = 1.875 (b) - 15/8 = - 1.875 Notice that rather than always shifting in 0s, the sign bit should be propagated in from the left. Thus positive numbers shift in 0s and negative numbers shift in 1s. This is known as Arithmetic Shift Right as opposed to Logic Shift Right which always shifts in 0s. Division by non powers of 2 is illustrated in (c) above. This shows the familiar long division process used in decimal division. This is an http://i-tronics.blogspot.com/ 12 The Quintessential PIC Microcontroller analagous process to the shift and add technique for multiplication, using a combination of shifting and subtracting. Arithmetic is not the only way to manipulate binary patterns. George Boole8 in the mid-19th century developed an algebra dealing with symbolic processing of logic propositions. This Boolean algebra deals with variables which can be true or false. In the 1930s it was realised that this mathematical system could equally well be used to analyze switching networks and thus binary logic systems. Here we will con?ne ourselves to looking at the fundamental logic operations of this switching algebra. A 0 1 f 1 0 A f=A A 1 f=A (a) Truth table (b) Alternative logic symbols Fig. 1.1 The NOT operation. The inversion or NOT operation is represented by overscoring. Thus f = A states that the variable f is the inverse of A; that is if A = 0 then f = 1 and if A = 1 then f = 0. In Fig. 1.1(a) this transfer characteristic is presented in the form of a truth table. By de?nition, inverting twice for ot N returns a variable to its original state; thus f = f.9 Logic function implementations are normally represented in an abstract manner rather than as a detailed circuit diagram. The NOT gate is symbolized as shown in Fig. 1.1(b). The circle always represents inversion in a logic diagram, and is often used in conjunction with other logic elements, such as in Fig. 1.2(c). The AND operator gives an all or nothing function. The outcome will only be true when every one of the n inputs are true. In Fig. 1.2 two input variables are shown, and the output is symbolized as f = B · A, where · is the Boolean AND operator. The number of inputs is not limited to two, and in general f = A(0) · A(1) · A(2) · · · A(n). The AND operator is ?rst professor of mathematics at Queen’s College, Cork. days of yore when logic circuits were built out of discrete devices, such as diodes, resistors and transistors, problems due to sneak current paths were rife. In one such laboratory experiment the output lamp was rather dim, and the lecturer in charge suggested that two NOTs in series in a suspect line would not disturb the logic but would block o? the unwanted current leak. On returning sometime later, the students complained that the remedy had had no e?ect. On investigation the lecturer discovered two knots in the o?ending wire – obviously not tied tightly enough! 9 In 8 The me co al, rci ef us edu or tio ca nly no http://i-tronics.blogspot.com/ 1. Digital Representation 13 BA f 0 0 1 1 0 1 0 1 0 0 0 1 B A B A & f=B A BA f 0 0 1 1 0 1 0 1 1 1 1 0 B A B A & f=B A f=B A f=B A (a) Truth table (b) Alternative logic symbols (c) NAND Fig. 1.2 The AND function. sometimes called a logic product, as ANDing (cf. multiplying) any bit with logic 0 always yields a 0 output. If we consider B as a control input and A as a stream of data, then consideration of the truth table shows that the output follows the data stream when B = 1 and is always 0 when B = 0. Thus the circuit can be considered to be acting as a valve, gating the data through on command. The term gate is generally applied to any logic circuit implementing a fundamental Boolean operator. Most practical AND gate implementations have an inverting output. The logic of such implementations is NOT AND, or NAND for short, and is symbolized as shown in Fig. 1.2(c). tf No co or 0 0 1 1 0 1 0 1 0 1 1 1 BA f me B A B A al, rci >1 ef us edu or 0 1 0 1 1 0 0 0 B A B A tio ca nly no f=B+A BA f 0 0 1 1 f=B+A f=B+A >1 f=B+A (a) Truth table (b) Alternative logic symbols (c) NOR Fig. 1.3 The inclusive-OR operation. The inclusive-OR operator gives an anything function. Here the outcome is true when any input or inputs are true (hence the = 1 label in the logic symbol). In Fig. 1.3 two inputs are shown, but any number of variables may be ORed together. ORing is sometimes referred to as a logic sum, and the + used as the mathematical operator; thus f = B + A. In an analogous manner to the AND gate detecting all ones, the OR gate can be used to detect all zeroes. This is illustrated in Fig. 2.19 on page 35 where an 8-bit zero outcome brings the output of the NOR gate to 1. http://i-tronics.blogspot.com/ 14 The Quintessential PIC Microcontroller Considering B as a control input and A as data (or vice versa), then from Fig. 1.3(a) we see that the data is gated through when B is 0 and inhibited (always 1) when B is 1. This is a little like the inverse of the AND function. In fact the OR function can be expressed in terms of AND using the duality relationship A + B = B · A. This states that the NOR function can be implemented by inverting all inputs into an AND gate. AND, OR and NOT are the three fundamental Boolean operators. There is one more operation commonly available as an electronic gate; the Exclusive-OR operator (XOR). The XOR function is true if only one input is true (hence the =1 label in the logic symbol). Unlike the inclusive-OR, the situation where both inputs are true gives a false outcome. BA f 00 01 10 11 0 1 1 0 B A B A =1 f=B+A BA f 0 0 1 1 0 1 0 1 1 0 0 1 B A B A f=B+A f=B+A =1 (a) Truth table (b) Alternative logic symbols for ot N If we consider B is a control input and A as data (they are fully interchangeable) then: • When B = 0 then f = A; that is the output follows the data input. input. Thus an XOR gate can be used as a programmable inverter. Another useful property considers the XOR function as a logic di?erentiator. The XOR truth table shows that the gate gives a true output if the two inputs di?er. Alternatively, the ENOR truth table of Fig. 1.4(c) shows a true output when the two inputs are the same. Thus an ENOR gate can be considered to be a 1-bit equality detector. The equality of two n-bit words can be tested by ANDing an array of ENOR gates (see Fig. 2.6 on page 23), each generating the function Bk ? Ak ; that is: n-1 • When B = 1 then f = A; that is the output is the inverse of the data me co al, rci Fig. 1.4 The XOR operation. ef us (c) ENOR edu or tio ca f=B+A nly no fB=A = k=0 Bk ? Ak As a simple example of the use of the XOR/XNOR gates, consider the problem of detecting sign over?ow (see page 10). This occurs if both the sign bits of word B and word A are the same (SB ? SA ) AND the sign http://i-tronics.blogspot.com/ 1. Digital Representation 15 bit of the outcome word C is not the same as either of these sign bits, say SB ? SC . The logic diagram for this detector is shown in Fig. 1.5 and implements the Boolean function: (SB ? SA ) · (SB ? SC ) SA SB SC SA = SB V SC = SB V is true if: (Sign A = Sign B) AND (Sign C = Sign B) Fig. 1.5 Detecting sign over?ow. Finally, the XOR function can be considered as detecting when the number of true inputs are odd. By cascading n + 1 XOR gates, the overall parity function is true if the n-bit word has an odd number of ones. Some measure of error protection can be obtained by adding an additional bit to each word, so that overall the number of bits is odd. This oddness can be checked at the receiver and any deviation indicates corruption. for ot N me co al, rci ef us edu or tio ca nly no http://i-tronics.blogspot.com/ for ot N me co al, rci ef us edu or tio ca nly no http://i-tronics.blogspot.com/ CHAPTER 2 Logic Circuitry We have noted that digital processing is all about transmission, manipulation and storage of binary word patterns. Here we will extend the concepts introduced in the last chapter as a lead into the architecture of the computer and microprocessor. We will look at some relevant logic functions, their commercial implementations and some practical considerations. After reading this chapter you will: • Understand the properties and use of active pull-up, open-collector and • • • • • • • • • • • • for ot N 3-state output structures. Appreciate the logic structure and function of the natural decoder. See how a MSI implementation of an array of ENOR gates can compare two words for equality. Understand how a 1-bit adder can be constructed from gates, and can be extended to deal with the addition of two n-bit words. Appreciate how the function of an ALU is so important to a programmable system. Be aware of the structure and utility of a read-only memory (ROM). Understand how two cross-coupled gates can implement a R S latch. Appreciate the di?erence between a D latch and D ?ip ?op. Understand how an array of D ?ip ?ops or latches can implement a register. See how a serial connection of D ?ip ?ops can perform a shifting function. Understand how a D ?ip ?op can act as a frequency divide by two, and how a cascade of these can implement a binary count. See how an ALU/PIPO register can implement an accumulator processor unit. Appreciate the function of a RAM. me co al, rci ef us edu or tio ca nly no The ?rst integrated circuits, available at the end of the 1960s, were mainly NAND, NOR and NOT gates. The most popular family of logic functions was, and still is, the 74 series transistor transistor logic (TTL); introduced by Texas Instruments and soon copied by all the major major semiconductor manufacturers. http://i-tronics.blogspot.com/ 18 The Quintessential PIC Microcontroller [74LS00] 3Y 3A 3B 4Y 4A 4B 8 9 10 11 12 13 7 6 5 4 3 2 1 1A Vcc 2Y 2B 2A 1Y 1B 1A 1B 2A 2B 3A 3B 4A 4B (1) (2) (4) (5) (9) (10) (12) (13) & (3) 1Y (6) 2Y (8) 3Y (11) GND 14 4Y (a) DIL package (b) ANSI/IEC logic symbol Fig. 2.1 The 74LS00 quad 2-I/P NAND package. for ot N The 74LS001 comprises four 2-input NAND gates in a 14-pin package. The integrated circuit (IC) is powered with a 5 ± 0.25 V supply between VCC2 (usually about 5 V) and GND.The logic outputs are 2.4 – 5 V High and 0 – 0.4 V for Low. Most IC logic families require a 5 V supply, but 3 V versions are becoming available, and some CMOS implementations can operate with a range of supplies between 3 V and 15 V. The 74LS00 IC is shown in Fig. 2.1(a) in its Dual In-Line (DIL) package. Strictly it should be described as a positive-logic quad 2-I/P NAND, as the electrical equivalent for the two logic levels 0 and 1 are Low (L is around ground potential) and High (H is around Vcc,3 usually about 5 V). If the relationship 0 ? H; 1 ? L is used (negative logic) then the 74LS00 is actually a quad 2-I/P NOR gate. The ANSI/IEC4 logic symbol of Fig. 2.1(b) denotes a Low electrical potential by using the polarity symbol. The ANSI/IEC NAND symbol shown is thus based on the real electrical operation of the circuit. In this case the logic coincides with a me co al, rci ef us edu or tio ca nly no 1 The LS stands for “Low-power Schottky transistor”. There are very many other versions, such as ALS (Advanced LS), AS (Advanced Schottky) and HC (High-speed Complementary metal-oxide transistor – CMOS). These family variants di?er in speed and power consumption, but for a given number designation have the same logic function and pinout. 2 For historical reasons the positive supply on logic ICs are usually designated as V CC; the C referring to a bipolar’s transistor Collector supply. Similarily ?eld-e?ect circuitry sometimes use the designation VDD for Drain voltage. The zero reference pin is normally designated as the ground point (GND), but sometimes the VEE (for emitter) or VSS (for Drain) label is employed. 3 For historical reasons the positive supply on logic ICs are usually designated as V CC; the C referring to a bipolar’s transistor Collector supply. Similarily ?eld-e?ect circuitry sometimes use the designation VDD for Drain voltage. The zero reference pin is normally designated as the ground point (GND), but sometimes the VEE (for emitter) or VSS (for Drain) label is employed. 4 The American National Standards Institution/International Electrotechnical Commission. http://i-tronics.blogspot.com/ 2. Logic Circuitry 19 positive-logic NAND function. The & operator shown in the top block is assumed applicable to the three lower gates. The output structure of a 74LS00 NAND gate is active pull-up. Here both the High and Low states are generated by connection via a lowresistance switch to Vcc or GND respectively. In Fig. 2.2(a) these switches are shown for simplicity as metallic contacts, but they are of course transistor derived. +Vcc Phase splitter High/Low Off/Low +Vcc Phase splitter EN High/Low/Off Internal logic state Internal logic state Internal logic state (a) Push/pull (Totem-pole) (b) Open-collector (open-drain) (c) Three-state Fig. 2.2 Output structures. for ot N Logic circuits, such as the 74LS00, change output state in around 10 nanoseconds.5 To be able to do this, the capacitance of any interconnecting conductors and other logic circuits’ inputs must be rapidly discharged. Mainly for this reason, active pull-up (sometimes called totem-pole) outputs are used by most logic circuits. There are certain circumstances where alternative output structures have some advantages. The open-collector (or open-drain) con?guration of Fig. 2.2(b) provides a ‘hard’ Low state, but the High state is in fact an open-circuit. The Highstate voltage can be generated by connecting an external resistor to either Vcc or indeed to a di?erent power rail. Non-orthodox devices, such as relays, lamps or light-emitting diodes, can replace this pull-up resistor. The output transistor is often rated with a higher than usual current and/or voltage rating for such purposes. The application of most interest to us here is illustrated in Fig. 2.3. Here four open-collector gates share a single pull-up resistor. Note the use of the symbol to denote an open-collector output. Assume that there are four peripheral devices, any of which may wish to attract the attention of the processor (eg. computer or microprocessor). If this processor has only one Attention pin, then the four Signal lines must be wire-ORed together as shown. With all Signals inactive (logic 0) the outputs of all bu?er NOT gates are o? (state H), and the party line is pulled up to +V by RL. If any Signal line is activated (logic 1), as in Sig_1, then the output of the corresponding bu?er gate goes hard Low. This pulls me co al, rci ef us edu or tio ca nly no 5A nanosecond is 10-9 s, so 100,000,000 transitions each second is possible. http://i-tronics.blogspot.com/ 20 The Quintessential PIC Microcontroller Sig_0 Sig_3 0 Sig_2 0 Sig_1 0 1 0 0 +V RL Off Off Off/0/Off Off To processor Fig. 2.3 Open-collector bu?ers driving a party line. the party line Low, irrespective of the state of the other signal lines, and thus interrupts the processor. From master controller Select_0 0 Select_1 EN 1 OFF Thing 0 d 00 ON d d 01 d 02 tf No co or Data bus me cia r 03 us l, d 10 EN Thing 1 d 11 d ef 12 Select_2 0 edu or EN tio ca d 23 nly no OFF Thing 2 20 d 13 d d 21 d 22 d d d d To master 10 11 12 13 Fig. 2.4 Sharing a bus. The three-state structure of Fig. 2.2(c) has the properties of both the preceeding output structures. When enabled, the two logic states are represented in the usual way by high and low voltages. When disabled, the output is open circuit irrespective of the activities of the internal logic circuitry and any change in input state. A logic output with this three-state is indicated by the symbol. As an example of the use of this structure, consider the situation depicted in Fig. 2.4. Here a master controller wishes to read one of several devices, all connected to this master over a set of party lines. As this data highway or Data bus is a common resource, so only the selected device can be allowed access to the bus at any one time. The access has to be withdrawn immediately the data has been read, so that another device http://i-tronics.blogspot.com/ 2. Logic Circuitry 21 can use the resource. As shown in the diagram, each Thing connected to the bus outputs, designated by the symbol. When selected, only the active logic levels will drive the bus lines. The 74LS244 octal (×8) 3state (sometimes called tri-state or TRIS) bu?er has high-current outputs (designated by the symbol) speci?cally designed to charge/discharge the capacitance associated with long bus lines. Integrated circuits with a complexity of up to 12 gates are categorised as Small-Scale Integration (SSI). Gate counts upwards to 100 on a single IC are Medium-Scale Integration (MSI), up to 1000 are known as LargeScale Integration (LSI) and over this, Very Large-Scale Integration (VLSI). Memory chips and microprocessors are examples of this latter category. B G A G X/Y [1/2 x 74LS139] No for t G2B G2A G1 (a) The 74LS139 dual 2- to 4-line decoder. me co (5) (4) (6) ial rc Y 0 us , Y 2 ef B A 3 edu or (1,15) EN (3,13) 1 0 (2,14) tio ca 3 (9,7) 3 (6,10) Y 2 2 (5,11) Y 1 1 (4,12) Y 0 0 Y nly no G 0 0 0 0 1 EN C B A 0 0 0 0 0 0 0 0 1 0 0 0 0 1 1 1 1 0 0 1 1 0 0 1 1 0 1 0 1 0 1 0 1 B A Y0 Y Y2 Y 1 3 0 0 1 1 X 0 1 0 1 X 0 1 1 1 1 1 0 1 1 1 1 1 0 1 1 1 1 1 0 1 Y 1 Y X/Y [74LS138] 7 6 (7) (9) Y Y 7 Y0 Y1 Y2 Y3 Y4 Y5 Y6 Y7 0 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 0 & EN 5 4 3 C B A (3) 2 (2) 1 (1) 0 2 1 0 6 (10) Y 5 (11) Y 4 (12) Y 3 (13) Y 2 (14) Y 1 (15) Y 0 XXX 11111111 (b) The 74LS138 3- to 8-line decoder Fig. 2.5 The 74LS138 and ’139 MSI natural decoders. http://i-tronics.blogspot.com/ 22 The Quintessential PIC Microcontroller for ot N The NAND gate networks shown in Fig. 2.5 are typical MSI-complexity ICs. Remembering that the output of a NAND gate is logic 0 only when all its inputs are logic 1 (see Fig. 1.2(c) on page 13) then we see that for any combination of the Select inputs B A (21 20 ) in Fig. 2.5(a) only one gate will go to logic 0. Thus output Y2 will be activated when B A = 10. The associated truth table shows the circuit decodes the binary address B A so that address n selects output Yn. The 74LS139 is described as a dual 2 to 4-line natural decoder. Dual because there are two such circuits in the one chip. The symbol X/Y denotes converting code X (natural binary) to code Y (unary – one of n). The Enable input G is connected to all gates in parallel. Thus the decoder function only operates if G is Low (logic 0). If G is High, then irrespective of the state of B A (the X entries in the truth table denote a ‘don’t care’ situation) all outputs remain deselected – logic 1. An example of the use of the 74LS139 is given in Fig. 2.23. The 74LS138 of Fig. 2.5(b) is similar, but implements a 3 to 8-line decoder function. The state of the three address lines C B A (22 21 20 ) n selects one only of the eight outputs Yn. The 74LS138 has three Gate inputs which generate an internal Enable signal G2B · G2A · G1. Only if both G2A and G2B are Low and G1 is High will the device be enabled. The 74LS138 is used in Fig 11.10 on page 287 to decode microcontroller port lines to enable several devices to communicate to the one port. A large class of ICs implement arithmetic operations. The gate array illustrated in Fig. 2.6 detects when the 8-bit byte P7…P0 is identical to the byte Q7…Q0. Eight ENOR gates each give a logic 1 when its two input bits Pn, Qn are identical, as described on page 14. Only if all eight bit pairs are the same, will the output NAND gate go Low. The 74LS688 Equality comparator also has a direct input G into this NAND gate, acting as an overall Enable signal. The ANSI/IEC logic symbol, shown in Fig. 2.6(b) uses the COMP label to denote the arithmetic comparator function. The output is pre?xed with the numeral 1, indicating that its operation P=Q is dependent on any input qualifying the same numeral; that is G1. Thus the active-Low Enable input G1 gates the active-Low output, 1P=Q. One of the ?rst functions beyond simple gates to be integrated into a single IC was that of addition. The truth table of Fig. 2.7(a) shows the Sum (S) and Carry-Out (C1) resulting from the addition of the two bits A and B and any Carry-In (C0). For instance row 6 states that adding two 1s with a Carry-In of 0 gives a Sum of 0 and a Carry-Out of 1 (1 + 1 + 0 =10). To implement this row we require to detect the pattern 1 1 0; that is A · B · C0 ; which is gate 6 in the logic diagram. Thus we have by ORing all applicable patterns together for each output: me co al, rci ef us edu or tio ca nly no S C1 = = (A · B · C0) + (A · B · C0) + (A · B · C0) + (A · B · C0) (A · B · C0) + (A · B · C0) + (A · B · C0) + (A · B · C0) http://i-tronics.blogspot.com/ 2. Logic Circuitry 23 P7 Q7 P6 Q6 P5 Q5 P4 Q4 P3 Q3 P2 Q2 P1 Q1 P0 Q0 G (17) (18) P7=Q7 1 [74LS688] G1 17 (15) (16) P6=Q6 (13) (14) P5=Q5 15 13 7 (11) (12) P4=Q4 (19) 11 8 P P=Q 6 4 2 (8) (9) P3=Q3 0 7 (6) (7) P2=Q2 1P=Q 19 18 16 (4) (5) P1=Q1 14 12 9 (2) (3) Q P0=Q0 7 5 (1) Enable 3 (a) Logic function Fig. 2.6 The 74LS688 octal equality detector. for ot N Using such a circuit for each column of a binary addition, with the Carry-Out from column k-1 feeding the Carry-In of column k means that the addition of any two n-bit words can be simultaneously implemented. As shown in Fig. 2.7(b), the 74LS283 adds two 4-bit nybbles in 25 ns. In practice the ?nal Carry-Out C4 is generated using additional circuitry to avoid the delays inherent on the carries rippling though each stage from the least to the most signi?cant digit. n 74LS283s can be cascaded to implement addition for words of 4 × n width. Thus two 74LS283s perform a 16-bit addition in 45 ns; the extra time being accounted for by the carry propagation between the two units. Adders can of course be coaxed into subtraction by inverting the minuend and adding one, that is 2’s complementation. An Adder/Subtractor circuit could be constructed by feeding the minuend word through an array of XOR gates acting as programmable inverters (see page 14). The Mode line Add/Sub in Fig. 2.8 that controls these inverters also feeds the Carry-In, e?ectively adding one when in the Subtract mode. Extending this line of argument leads to the Arithmetic Logic Unit (ALU). An ALU is a circuit which can undertake a selection of arithmetic and logic processes on input data as controlled by Mode inputs. The 74LS382 in Fig. 2.9 processes two 4-bit operands in eight ways, as controlled by the three Select bits S2 S1 S0 and tabulated in Fig. 2.9(a). Besides me co al, rci ef us edu or 0 (b) ANSI/IEC logic symbol tio ca nly no http://i-tronics.blogspot.com/ 24 The Quintessential PIC Microcontroller A B C0 0 1 2 3 4 5 6 7 0 0 0 0 1 1 1 1 0 0 1 1 0 0 1 1 0 1 0 1 0 1 0 1 S C1 0 1 1 0 1 0 0 1 0 0 0 1 0 1 1 1 A B C0 A B C0 A B C0 A B C0 A B C0 A B C0 A B C0 1 2 S Sum out 1+2+4+7 4 7 5 C1 Carry out 3+5+6+7 6 (a) One-bit addition B4 A4 (11) (12) 3 B3 (15) A3 (14) B2 (2) A2 (3) B1 (6) A1 Carry-out C4 (9) B C1 S A C0 C1 B S A C0 C1 B S A (10) S4 (b) The 74LS283 four-bit adder for ot N addition and subtraction, the logic operations of AND, OR and XOR are supported. The 74LS382 even generates the 2’s complement over?ow function (see page 10). As we shall see, the ALU is the heart of the computer and microprocessor architectures. By feeding the Select inputs with a series of mode words, a program of operations can be performed by the ALU. Such operation codes are stored in an external memory, and are accessed sequentially by the computer’s control circuits. Sequences of program operation codes are normally stored in an LSI Read-Only Memory (ROM). Consider the architecture illustrated in Fig. 2.10. This is essentially a 3 to 8-line decoder driving an 8 × 2 array of diodes. The 3-bit address selects only row n for each input combination n. If a diode is connected to this row, then it conducts and brings the appropriate column Low. The inverting 3-state output bu?er consequently gives a High for each connected diode and Low where the link is broken. The pattern of diode links then de?nes the output code for each input. For illustrative purposes, the structure has been programmed to me co ial rc us , S3 (13) e fo (1) edu r B C0 C1 S (4) A tio ca (5) nly no C0 Carry-in (7) C0 S2 S1 Fig. 2.7 Addition. http://i-tronics.blogspot.com/ 2. Logic Circuitry 25 Word A Word B ADD/SUB A4 C4 A3 A2 A1 B4 B3 B2 B1 C0 S4 S3 S2 S1 Carry/Borrow out Sum/Difference Fig. 2.8 Implementing a programmable adder/subtractor. S2S1S0 0 0 0 0 1 1 1 1 0 0 1 1 0 0 1 1 0 1 0 1 0 1 0 1 Operation tf No co or Clear (F=0000) Subtract (B-A) Subtract (A-B) Add (A+B) EOR (A + B) OR (A + B) AND (A B) Preset (F=1111) me al, rci Word A (17) (19) (1) ef us (3) Word B Mode Select S edu or (4) (7) (6) tio ca (5) (15) nly no Carry-In (16) (18) (2) A3 A2 A1 A0 B3 B2 B1 B0 S2 S1 S0 C(n) ALU [74LS382] C(n+4) (14) OVR (13) F3 F2 F1 F0 (12) (11) (9) (8) Carry-Out (a) Function table Overflow Function Output F (b) Logic diagram/pinning Fig. 2.9 The 74LS382 ALU. implement the 1-bit full adder of Fig. 2.7(a), but any two functions of three variables can be generated. The diode matrix look-up table shown here is known as a Read-Only Memory (ROM), as its ‘memory’ is in the diode pattern, which is programmed in when the device is manufactured. Early devices, which were typically decoder/32 × 8 matrices, usually came in user-programmable versions in which the links were implemented with fusible links. By using http://i-tronics.blogspot.com/ 26 The Quintessential PIC Microcontroller +V Chip Select CS 0 X/Y G 0 1 2 3 1 1 1 1 1 0 1 1 1 0 Address 4 1 0 1 A 4 2 1 5 6 7 B C0 Output Enable OE 0 tf No om rc o a high voltage, a selection of diodes could be taken out of contact. Such devices are called Programmable ROMs (PROMs). Fuses are messy when implementing the larger sizes of VLSI PROM necessary to store computer programs. For example, the 27C64 PROM shown in Fig. 2.11 has the equivalent of 65,536 fuse/diode pairs, and this is a relatively small device capable of storing 8192 bytes of memory. The 27C64 uses electrical charge on the ?oating gate of a metal-oxide ?eld-e?ect transistor (MOSFET) as the programmable link, with another MOSFET to replace the diode. Charge can be tunnelled onto this isolated gate by, again, using a high voltage. Once on the gate, the electric ?eld keeps the link MOSFET conducting. This charge takes many decades to leak away, but this can be dramatically reduced to about 30 minutes by exposure to intensive ultra-violet radiation. For this reason the 27C64 is known as an Erasable PROM (EPROM). When an EPROM is designed for reusability, a quartz window is integrated into the package, as shown in Fig. 2.11. Programming is normally done externally with special equipment, known as PROM programmers, or colloquially as PROM blasters. Versions without windows are referred to as One-Time Programmable (OTP) ROMs, as they cannot easily be erased once programmed. They cia er Fig. 2.10 A ROM-implemented 1-bit adder. us l, ef 0 S edu or 1 tio ca nly no C1 Output data http://i-tronics.blogspot.com/ 2. Logic Circuitry 27 VPP 1 A12 2 A7 3 A6 4 A5 5 A4 6 A3 7 A2 8 A1 9 A0 10 D0 11 D1 12 D2 13 VSS 14 28 VDD 27 PGM 26 25 A8 24 A9 23 A11 22 OE 21 A10 20 CE 19 D7 18 D6 17 D5 16 D4 15 D3 EPROM A0 A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 A11 A12 CS 0 8192x8 [2764] A A A A A A A A A 0 8191 D0 D1 D2 D3 D4 D5 D6 D7 12 [POWER DOWN] & OE (a) Dual in-line package are however, much cheaper to produce and are thus suitable for small to medium-scale production runs. for ot N me co X al, rci TR2 Fig. 2.11 The 2764 Erasable PROM. ef us (b) Logic symbol edu or Y EN tio ca nly no V PP G22 G21 TR 1 V DD D2 S2 Programmable element D1 G1 S1 Fig. 2.12 Floating-gate MOSFET link http://i-tronics.blogspot.com/ A le ab ss re itch dd sw 28 The Quintessential PIC Microcontroller for ot N Figure 2.12 shows a simpli?ed representation of such a ?oating-gate MOSFET link. The cross-point device is a metal-oxide enhancement nchannel ?eld-e?ect transistor TR1, rather than a diode. This MOSFET has its gate G1 connected to the X line and its source S1 to the Y line. If its drain D1 were connected to the positive supply and the X line is selected (positive), then the Y line too becomes positive (positive-logic 1) as TR1 is conducting (switch is on). However, if TR1 is disconnected from VDD then it does not conduct and the output on the Y line is logic 0. Transistor TR2 is in series with VDD and thus acts as the programmable element. Transistor TR2 has an extra unconnected gate buried in the silicon dioxide insulation layer. Normally there is no charge on this gate and TR2 is o?. If the programming voltage VPP is pulsed high to typically 20 – 25 V, negative charges tunnel across the extemely thin insulation surrounding the buried gate. This permanently turns TR2 on and thus connects TR1 to its supply. This shows up as a logic 1 on the Y line when selected by the internal memory decoder. This charge remains more or less permanently on the buried gate until it is exposed to ultra-violet light. The high-energy light photons knock electrons (negative charges) out of the buried (?oating) gate6 e?ectively discharging in around 20 minutes and wiping out all stored information. There are PROM structures which can be erased electrically, often in situe in the circuit. These are known variously as Electrically-Erasable PROMs (EEPROMs) or ?ash memories. In the former case a large negative pulse at VPP causes the captured electrons on the buried gate to tunnel back out. Generally the negative voltage is generated on the chip, which saves having to provide an additional external supply. The ?ash variant of EEPROM relies on hot electron injection rather than tunneling to charge the ?oating gate. The geometry of the cell is approximately half the size of a conventional EEPROM cell which increases the memory density. Programming voltages are also somewhat lower. Most modern EPROM/EEPROMs are fairly fast, taking around 150 ns to access and read. Programming is slow, at perhaps 10 ms per word, but this is an infrequent activity. Flash EEPROM programs around 1000 times faster, in around 10 µs per cell. me co al, rci ef us edu or tio ca nly no All the circuits shown thus far are categorised as combinational logic. They have no memory in the sense that the output simply depends only on the present input, and not the sequence of events leading up to that input. Logic circuits, such as latches, counters, registers and read/write memories are described as sequential logic. Their output not only depends on the current input, but the sequence of prior inputs. is called the Einstein e?ect. Einstein was awarded his Nobel prize for this discovery and not for his theories of relativity, as these were considered too revolutionary! 6 This http://i-tronics.blogspot.com/ 2. Logic Circuitry 29 RS 00 01 10 Q Q (no change) 1 (set) 0 (reset) R R Q S S Q (a) Defining RS latch truth table (b) Logic symbol with true/complement outputs 0R X 0 0 X 1 1 0 Q R X 0 Q 0 1 0 X 0 Q S (c) Setting the latch 0 X 0 X 1 Q S (d) Resetting the latch Fig. 2.13 The R S latch. for ot N Consider a typical door bell push-switch. When you press such a switch the bell rings, and it stops as soon as you release it. This switch has no memory. Compare this with a standard light switch. Set the switch and the light comes on. Moreover it remains on when you remove the stimulus (usually your ?nger!). To turn the light o? you must reset the switch. Again it remains o? when the input is taken away. This type of switch is known as a bistable, as it has two stable states. E?ectively it is a 1-bit memory cell, that can store either an on or o? state inde?nitely. A read-write memory, such as the 6264 device of Fig. 2.24, implements each bistable cell using two cross-coupled transistors. Here we are not concerned with this microscopic view. Instead, consider the two cross-coupled NOR gates of Fig. 2.13. Remembering from Fig. 1.3(c) on page 13 that any logic 1 into a NOR gate will always give a logic 0 output irrespective of the state of the other inputs, allows us to analyse the circuit: me co al, rci ef us edu or tio ca nly no • If the S input goes to 1, then output Q goes to 0. Both inputs to the top gate are now 0 and thus output Q goes to 1. If the S input now goes back to 0, then the lower gate remains 0 (as the Q feedback is 1) and the top gate output also remains unaltered. Thus the latch is set by pulsing the S input. • If the R input goes to 1, then output Q goes to 0. Both inputs to the bottom gate are now 0 and thus output Q goes to 1. If the R input now goes back to 0, then the upper gate remains 0 (as the Q feedback is 1) and the bottom gate output also remains unaltered. Thus the latch is reset by pulsing the R input. http://i-tronics.blogspot.com/ 30 The Quintessential PIC Microcontroller In the normal course of events – that is assuming that the R and S inputs are not both active at the same time7 then the two outputs are always complements of each other, as indicated by the logic symbol of Fig. 2.13(b). +V S Q R Q +V Fig. 2.14 Using a R S latch to debounce a switch. for ot N There are many bistable implementations. For example, replacing the NOR gates by NAND gives a R S latch, where the inputs are active on a logic 0. The circuit illustrated in Fig. 2.14 shows such a latch used to debounce a mechanical switch. Manual switches are frequently used as inputs to logic circuits. However, most metallic contacts will bounce o? the destination contact many times over a period of several tens of milliseconds before settling. For instance, using a mechanical switch to interrupt a computer/microprocessor will give entirely unpredictable results. In Fig. 2.14, when the switch is moved up and hits the contact the latch is set. When the contact is broken, the latch remains unchanged, provided that the switch does not bounce all the way back to the lower contact. The state will remain Set no matter how many bounces occur. By symmetry, the latch will reset when the switch is moved to the bottom contact, and remain in this Reset state on subsequent bounces. The D latch is an extension to the R S latch, where the output follows the D (Data) input when the C (Control) input is active (logic 1 in our example) and freezes when C is inactive. The D latch can be considered me co al, rci ef us edu or tio ca nly no they where, then both Q and Q go to 0. On relaxing the inputs, the latch will end up in one of its stable states, depending on the relaxation sequence. The response of a latch to a simultaneous Set and Reset is not part of the latch de?nition, shown in Fig. 2.13(a), but depends on its implementation. For example, trying to turn a light switch on and o? together could end in splitting it in two! 7 If http://i-tronics.blogspot.com/ 2. Logic Circuitry 31 CD 10 11 0X Q 0 (transparent) 1 Q (freeze) 1D C1 (b) D latch logic diagram 1D C1 (a) D latch truth table CD 0 1 0X 1X X Q 0 (sample) 1 Q Q (hold) Q (c) D flip flop truth table (d) D flip flop logic diagram Fig. 2.15 The D latch and ?ip ?op. for ot N to be a 1-bit memory cell where the datum is retained at its value at the end of the sample pulse. In Fig. 2.15(b) the dependency of the Data input with its Control is shown by the symbology C1 and 1D. The 1 pre?x to D shows that it depends on any signal with a 1 su?x, in this case the C input. That is C1 clocks in the 1D data. A ?ip ?op is also a 1-bit memory cell, but the datum is only sampled on an edge of the control (known here as the Clock) input. The D ?ip ?op described in Fig. 2.15(c) is triggered on a / (as illustrated in the truth table as ?), but \ clocked ?ip ?ops are common. The edge-triggered activity is denoted as on a logic diagram, as shown in Fig. 2.15(d). The 74LS74 shown in Fig. 2.16 has two D ?ip ?ops in the one SSI circuit. Each ?ip ?op has an overriding Reset (R) and Set (S) input, which are asynchronous – that is not controlled by the Clock input. MSI functions include arrays of four, six and eight ?ip ?ops all sampling simultaneously with a common Clock input. The 74LS377 shown in Fig. 2.17 consists of eight D ?ip ?ops all clocked by the same single Clock input C, which is gated by input G. Thus the 8-bit data 8D…1D is clocked in on the / of C if G is Low. In the ANSI/ISO logic diagram shown in Fig. 2.17(b), this dependency is indicated as G1?1C2?2D, which states that G enables the Clock input, which in turn acts on the Data inputs. Arrays of D ?ip ?ops are known as registers; that is read/write memories that hold a single word. The 74LS377 is technically known as a parallel-in parallel-out (PIPO) register, as data is entered in parallel (that is all in one go) and is available to read at one go. D latch arrays are also available, such as the 74LS373 octal PIPO register shown in Fig. 2.18, in which the eight D ?ip ?ops are replaced by D latches. In addition the me co al, rci ef us edu or tio ca nly no http://i-tronics.blogspot.com/ 32 The Quintessential PIC Microcontroller +5V 2CLR 2D 2CK 2SET 2Q 2Q [74LS74] 4 3 S C1 1D R 9 8 6 5 2 1 10 11 12 10 1CLR (a) Logic function for ot N latch outputs have a 3-state capability. This is useful if data is to be captured and later put onto a common data bus to be read subsequently as desired by a computer. A pertinent example of the use of a PIPO register is shown in Fig. 2.19. Here an 8-bit ALU is coupled with an 8-bit PIPO register, accepting as its input the ALU output, and in turn feeding one input word back to the ALU. This register accumulates the outcome of a series of operations, and is sometimes called an Accumulator or Working register. To describe the operation of this circuit, consider the problem of adding two words A and B. The sequence of operations, assuming the ALU is implemented by cascading two 74LS382s might be: 1. Program step. • Mode = 000 (Clear). • Pulsing Execute loads the ALU output (0000 0000) into the register. • Data out is zero (0000 0000). 2. Program step. • Fetch Word A down to the ALU input. • Mode = 011 (Add). • Pulse / \ Execute to load the ALU output (Word A + zero) into the register. • Data out is Word A. 3. Program step. • Fetch Word B down to the ALU input. • Mode = 011 (Add). • / \ Execute to load the ALU output (Word B + Word A) into the register. 14 1 me co 13 2 1D C Q C1 1D S Q 1CK 12 3 1SET 11 4 8 9 Q Q 1D S C1 C 7 Fig. 2.16 The 74LS74 dual D ?ip ?op. al, rci http://i-tronics.blogspot.com/ 5 1Q 6 1Q 13 GND (b) ANSI/IEC logic symbol ef us edu or tio ca nly no 2. Logic Circuitry 33 G 1 11 C 1 11 [74LS377] G1 1C2 19 1D 3 C1 1D 2 4 C1 1D 18 2D 2D 1Q 17 16 3D 5 7 C1 1D 6 8 C1 1D 2Q 14 15 4D 3Q 13 12 5D 9 13 C1 1D 12 14 C1 1D 4Q 8 6D 5Q 7D 15 17 C1 1D 8D 18 tf No co or me al, rci 16 ef us 6Q 7Q 8Q edu or 4 3 7 tio ca 6 5 2 9 nly no (a) Logic function Fig. 2.17 The 74LS377 octal D ?ip ?op array. • Data out is Word B plus Word A. The sequence of operation codes, that is 000 – 100 – 100 constitutes the program. In practice each instruction would also contain the address (where relevant) in memory of the data to be processed; in this case the locations of Word A and Word B. Each outcome of a process will have associated properties. For example it may be zero or have a carry-out. Such properties may be signi?cant in the future progress of the program. In the diagram three D ?ip ?ops, clocked by Execute, are used to grab this status information. In this situation the ?ip ?ops are usually known as ?ags (or sometimes semaphores). Thus we have Z (Zero), C (Carry from bit 7) and DC (BCD Carry from bit 3) ?ags, which form a Code Condition or Status register. C1 1D 19 (b) ANSI/IEC logic symbol http://i-tronics.blogspot.com/ 34 The Quintessential PIC Microcontroller LE 11 1 OE 1 11 [74LS377] EN C1 19 1D 3 18 2 4 C1 1D 1D 2D 1Q 17 16 C1 1D 5 7 3D 2Q 14 15 C1 1D 6 8 4D 3Q 13 12 5D 9 13 4Q 8 9 7 12 6D 14 5Q 7D 15 17 6Q 8D 18 ot N for (a) Logic function me co ial rc us , 16 19 7Q for e 3 4 edu tio ca 6 5 2 nly no There are various other forms of register. The 4-bit shift register of Fig. 2.20(a) is an example of a serial-in serial-out (SISO) structure. In this instance the data held in the nth D ?ip ?op is presented to the input of the (n+1)th stage. On receipt of a clock pulse (or shift pulse in this context), this data moves into this (n + 1)th ?ip ?op, i.e. e?ectively moving from stage n to stage n + 1. As all ?ip ?ops are clocked simultaneously, the entire word moves once right on each shift pulse. In the example of Fig. 2.20 a 4-bit external data nybble is fed into the left-most stage bit by bit as synchronised by the clock. After four shift pulses the serial 4-bit word is held in the register. To get it out again, four further shifts moves the wrod bit by bit out of the shift register, this is SISO. If the individual ?ip ?ops are accessible then the data can be accessed at one go, that is serial-in parallel-out. C1 1D C1 1D C1 1D C1 1D C1 1D 8Q (b) ANSI/IEC logic symbol Fig. 2.18 The 74LS373 octal D latch array. http://i-tronics.blogspot.com/ 2. Logic Circuitry 35 Mode Data in P7 P6 P5 P4 P3 P2 P1 P0 S7 S6 S5 [ALU] C4 C8 0 M- 3 S4 S3 S2 S1 DC 1D C1 1D C1 1D C1 Status C Z S0 Q7 Q6 Q5 Q4 Q3 Q2 Q1 Q0 Working register Execute for ot N me co al, rci Data out ef us edu or C1 Fig. 2.19 An 8-bit ALU-accumulator processor. The logic diagram of Fig. 2.20(b) uses the ? symbol a?ected by the clock input to indicate the shift action, C1 ?. SRG4 indicates a Shift ReGister 4-stage architecture. An example of an 8-stage shift register is given in Fig. 12.2 on page 307. Other architectures include parallel-in serial-out which is useful for parallel to serial conversion. Counting registers (counters) increment or decrement on each clock pulse, according to a binary sequence. Typically an n-bit counter can perform a count of 2n states. Some can also be loaded in parallel and thus act as a store. Consider the negative-edge triggered D ?ip ?op shown in Fig. 2.21 where its Q output is connected back to the 1D input. On each \ at the Clock input C1 the data at the 1D input will be latched in to appear at the Q output. As it is the complement of this output that is fed back to the input, then the next time the ?ip ?op is clocked the opposite logic http://i-tronics.blogspot.com/ 1D tio ca nly no 36 The Quintessential PIC Microcontroller Optional parallel output Q0 Q1 Q2 Q3 Serial-in data Shift clock 1D C1 1D C1 1D C1 1D C1 Serial-out data (a) A 4-bit shift register (1011) 0 0 0 0 (101) 1 0 0 0 0 Shift clock SRG4 C1 (10) 1 1 1 0 1 0 0 0 Serial-in data 1D Q0 Q1 (1) 0 1 1 0 0 0 1 1 0 1 (b) Shifting 1011 into the register (c) The ANSII/IEC logic symbol for a SIPO register No for t om c a cia er 1D C1 Fig. 2.20 The SISO shift register. us l, Q for e a edu c d Q2 Serial-out data/Q 3 tio ca nly no Time b e T T T T T b Output Q a b c d e Input Fig. 2.21 The T ?ip ?op. state will be latched in. This constant alternation is called toggling and is depicted on the diagram by T. The output waveform resulting from a constant frequency input pulse train is half this frequency. This waveform is a precision squarewave, provided that the input frequency remains constant. This T ?ip ?op is sometimes known as a binary or a divide-by-2. T ?ip ?ops can of course be cascaded, as shown in Fig. 2.22(a). Here four \ triggered ?ip ?ops are chained, with the output of binary n http://i-tronics.blogspot.com/ 2. Logic Circuitry 37 Count 1D C1 1D C1 1D C1 1D C1 QA 2 (a) Cascading toggle flip flops QB 4 QC 8 QD 16 Count QA QB QC QD 0 0 0 0 1 0 0 0 0 1 0 0 1 1 0 0 0 0 1 0 1 0 1 0 0 1 1 1 1 1 0 0 0 1 0 0 0 1 1 1 0 0 (b) Resulting waveforms for ot N clocking binary n + 1. Thus if the input Count frequency was 8 KHz, then QA would be a 4 kHz square waveform and similarily QB would measure in at 2 kHz, QC at 1 kHz, QD at 500 Hz. me co al, rci 0 ef us 0 1 1 edu or 0 0 1 1 1 1 0 tio ca 1 0 1 1 1 1 1 1 1 1 1 nly no 0 0 0 0 Fig. 2.22 A modulo-16 ripple counter. The waveform QA of Fig. 2.22(b) was derived in the same manner as in Fig. 2.21. QB is toggled on each \ of QA and likewise for the subsequent outputs. Marking a high as logic 1 and a low as logic 0 gives the 24 (16) positive-logic binary patterns as time advances, with the count rolling over back to state 0 on a continual basis. Each pattern remains in the register until the next event clocks the chain; an event being de?ned in our example as a \ at Count. Examining the sequence shows it to be a natural 8-4-2-1 binary up count, incrementing from 0000b to 1111b. In fact the circuit is a modulo-16 binary counter. A modulo-n count is the sequence taking only the ?rst n numbers into account.8 any number can be converted to its modulo-n equivalent by dividing by n. The remainder, or modulus, will be a number from 0 to n - 1. 8 Mathematically http://i-tronics.blogspot.com/ 38 The Quintessential PIC Microcontroller In theory there is no limit to the number of stages that can be cascaded. Thus using eight T ?ip ?ops would give a modulo-256 (28 ) counter. In practice there is a small propagation delay through each stage and this limits the ultimate frequency. For example the 74LS74 dual D ?ip ?op of Fig. 2.16 has a maximum propagation from an event at its Clock input to output of 25 ns. The maximum toggling frequency for a single stage, such as in Fig. 2.21, is given as 25 MHz. An 8-stage counter thus has a maximum ripple-through time of 200 ns. If such a ripple counter were 1 clocked at the resulting 5 MHz ( 200 ns ) then no sooner than one particular code pattern has stabilized then the next one would begin to appear. This is only really a problem if the various states of the counter are to be decoded and used to control other logic. The decoding logic, such as shown in Fig. 2.23, may inadvertently respond to these short transient states and cause havoc. In such cases more sophisticated synchronous counter con?gurations are more applicable where the ?ip ?ops are clocked simultaneously and steered by the appropriate logic con?guration to count in the desired sequence. The circuit illustrated here implements an up count. If the complement Q lines are used as the outputs, but with the clocking arrangements remaining the same, then the count sequence will decrement, that is a down count. Likewise using / triggered ?ip ?ops, such as the 74LS74 dual ?ip ?op (see Fig. 2.23), are used as the storage element, then the count will be down. It is easily possible to use some simple logic to combine the two functions to produce a programmable up/down counter. It is also feasible to provide logic to load the ?ip ?op array in parallel with any number and then count up or down from that point. Such an arrangement can be thought of as a parallel-in counting register. for ot N me co al, rci ef us edu or tio ca nly no X/Y [1/2 x 74LS139] EN 0 1 2 1 0 3 Ph_1 Ph_2 Ph_3 Ph_4 A 1D C1 [74LS74] B 1D C1 2 to 4-line decoder Clock Modulo-4 counter Fig. 2.23 Generating timing waveforms. http://i-tronics.blogspot.com/ 2. Logic Circuitry 39 As well as the more obvious use of a counter register to totalize the number of events, such as cans of peas coming along a conveyor belt, there are other uses. One of these is to time a sequence of operations. In Fig. 2.23 a modulo-4 counter is used to address one section of a 74LS139 2 to 4-line decoder, see Fig. 2.5(a). This detects each of the four states of the counter, and the outcome is four time-separated outputs that can be used to sequence, say, the operation of a computer’s control section logic. As a practical point, the complement Q ?ip ?op outputs have been used to address the decoder to compensate for the / triggered action that would normally give a down count. Larger counters with the appropriate decoding circuitry can be used to generate fairly sophisticated sequences of control operations. The term register is commonly applied to a read/write memory that can store a single binary word, typically 4 – 64 bits. Larger memories can be constructed by grouping n such registers and selecting one of n. Such a structure is sometimes known as a register ?le. For example, the 74LS670 is a 4 × 4 register ?le with a separate 4-bit data input and data output and separate 2-bit address. This means that any register can be read at any time, independently of any concurrent writing process. 1 A12 2 tf No co or A6 4 A5 5 A4 6 A3 7 A2 8 A1 9 A0 10 I/O0 11 I/O1 12 I/O2 13 VSS 14 A7 3 me al, rci 28 VDD 27 R/W 26 CE2 25 A8 24 A9 23 A11 22 OE 21 A10 20 CE1 19 I/O7 18 I/O6 17 I/O5 16 I/O4 15 I/O3 A0 A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 ef us 0 edu or RAM 8192x8 [6264] 2A 1AD 2A 1AD 0 A 8191 2A 1AD 2A 1AD 2A 1AD tio ca nly no I/O7 I/O6 I/O5 I/O4 I/O3 I/O2 I/O1 I/O0 A11 A12 CS2 CS1 OE R/W 12 & [WRITE] EN1 & [READ] EN2 2A 1AD 2A 1AD 2A 1AD (a) Dual in-line package (b) Logic symbol Fig. 2.24 The 6264 8196 × 8 RAM. http://i-tronics.blogspot.com/ 40 The Quintessential PIC Microcontroller for ot N Larger read/write memories are normally known as read-write RandomAccess Memories, or RAMs for short. The term random-access indicates that any memory word may be selected with the same access time, irrespective of its position in the memory matrix.9 This contrasts with a magnetic tape memory, where the reel must be wound to the sector in question – and if this is at the end of the tape! For our example, Fig. 2.24 shows the 6264 RAM. This has a matrix of 65,536 (216 ) bistables organized as an array of 8192 (213 ) words of 8 bits. Word n is accessed by placing the binary pattern of n on the 13-bit Address pins A12…A0. When in the Read mode (Read/Write = 1), word n will appear at the eight data outputs (I/O7…I/O0) as determined by the state n of the address bits. The A symbol at the input/outputs (as was the case in Fig. 2.11) indicates this addressibility. In order to enable the 3-state output bu?ers, the Output Enable input must be Low. The addressed word is written into if R/W is Low. The data to be written into word n is applied by the outside controller to the eight I/O pins. This bi-directional tra?c is a feature of computer buses. In both cases, the RAM chip as a whole is enabled when CS1 is Low and CS2 is High. Depending on the version of the 6264, this access from enabling takes around 100 – 150 ns. There is no upper limit to how long the data can be held, provided power is maintained. For this reason, the 6264 is described as static (SRAM). Rather than using a transistor pair bistable to implement each bit of storage, data can be stored as charge on the gate-source capacitance of a single ?eld-e?ect transistor. Such charge leaks away in a few milliseconds, so needs refreshed on a regular basis. Dynamic RAMs (DRAMs) are cheaper to fabricate than SRAM equivalents and obtainable in larger capacities. They are usually found where very large memories are to be implemented, such as found in a personal computer. In such situations, the expense of refresh circuitry is more than amortized by the reduction in cost of the memory devices. Both types of Read/Write memories are volatile, that is they do not retain their contents if power is removed. Some SRAMs can support existing data at a very low holding current and lower than normal power supply voltage. Thus a backup battery can be used in such circumstances to keep the contents intact for many months. me co al, rci ef us edu or tio ca nly no speaking, ROMs should also be described as random access, but custom and practice has reserved the term for read-write memories. 9 Strictly http://i-tronics.blogspot.com/ CHAPTER 3 Stored Program Processing If we take the Arithmetic Logic Unit (ALU)/Working register pair depicted in Fig. 2.19 on page 35 and feed it with function codes, then we have in essence a programmable processing unit. These command codes may be stored in digital memory and constitute the system’s program. By fetching these instructions down one at a time we can execute this program. Memory can also hold data on which the ALU operates. This structure, together with its associated data paths, decoders and logic circuitry is known as a digital computer. In Part 2 we will see that microcontroller architecture is modelled on that of the computer. As a prelude to this we will look at the architecture and operating rhythm of the computer structure and some characteristics of its programming. Although this computer is strictly hypothetical, it has been very much ‘designed’ with our book’s target microcontroller in mind. After reading this chapter you will: for ot N • • • • • • • Understand the Harvard structure with its separate program and data memories, and how it compares to the more common von Neumann architecture. Understand the parallel fetch and execute rhythm and its interaction with the Program and Data stores and the internal processor registers. Understand the concept of a File address as a pointer to where data is located in the Data store. Comprehend the structure of an instruction and appreciate that the string of instructions necessary to implement the task is known as a program. Have an understanding of a basic instruction set, covering data movement, arithmetic, logic and skipping categories. Understand how Literal, Register Direct, File Direct, File Indirect and Absolute address modes permit an instruction to target an operand for processing. To be able to write short programs using a symbolic assembly-level language and appreciate its one-to-one relationship to machine code. me co al, rci ef us edu or tio ca nly no The architecture of the great majority of general-purpose computers and microprocessors is modelled after the von Neumann model shown in http://i-tronics.blogspot.com/ 42 The Quintessential PIC Microcontroller Fig. 3.1.1 The few electronic computers in use up to the late 1940s either only ever ran one program (like the war time code breaking Colossus) or else needed partly rewired to change their behavior (for example the ENIAC). The web site entry for this chapter gives historical and technical details of these prehistorical machines. Memory Data Program code The outside world Input interface port Data highway Output interface port Processing unit (ALU) Control for ot N Von Neumann’s great leap forward was to recognise that the program could be stored in memory along with any data. The advantage of this approach is ?exibility. To alter the program simply load the bit pattern into the appropriate area of memory. In essence, the von Neumann architecture comprises a Central Processing Unit (CPU), a memory and a common connecting highway carrying data back and forth. In practice the CPU must also communicate with the environment outside the computer. For this purpose data to and from suitable interface ports are also funnelled through the data highway. Looking at these elements in a little more detail. Neumann was a Hungarian mathematician working for the American Manhattan nuclear weapons program during the 2nd World war. After the war he became a consultant for the Moore School of Electrical Engineering at the University of Pennsylvania’s EDVAC computer project, for which he was to employ his new concept where the program was to be stored in memory along with its data. He published his ideas in 1946 and EDVAC became operational in 1951. Ironically, a somewhat lower key project at Manchester University made use of this approach and the Mark 1 executed its ?rst stored program in June 1948! This was closely followed by Cambridge University’s EDSAC which ran its program in May 1949, almost two years ahead of EDVAC. 1 Von me co Fig. 3.1 An elementary von Neumann computer. al, rci Cl oc Central Processing Unit (CPU) ef us edu or tio ca The outside world nly no http://i-tronics.blogspot.com/ k 3. Stored Program Processing 43 The Central Processing Unit The CPU consists of the ALU/working register together with the associated control logic. Under the management of the control unit, program instructions are fetched from memory, decoded and executed. Data resulting from, or used by, the program is also accessed from memory. This fetch and execute cycle constitutes the operating rhythm of the computer and continues inde?nitely, as long as the system is activated. Memory Memory holds the bit patterns which de?ne the program. These sequences of instructions are known as the software. The word is a play on the term hardware; as such patterns do not correspond to any physical rearrangement of the circuitry. Memory holding software should ideally be as fast as the CPU, and normally uses semiconductor technologies, such as that described in the last chapter.2 This memory also holds data being processed by the program. Program memories appear as an array of cells, each holding a bit pattern. As each cell ultimately feeds the single data highway, a decoding network is necessary to select only one cell at a time for interrogation. The computer must target its intended cell for connection by driving this decoder with the appropriate code or address. Thus if location 602Eh is to be read, then the pattern 0110 0000 0010 1110b must be presented to the decoder. For simplicity, this address highway is not shown in Figs. 3.1 and 3.2. for ot N This addressing technique is known as random access, as it takes the same time to access a cell regardless of where it is situated in memory. Most computers have large backup memories, usually magnetic or optical disk-based or magnetic tape, in which case access does depend on the cell’s physical position. Apart from this sequential access problem, such media are normally too slow to act as the main memory and are used for backup storage of large arrays of data (eg. student exam records) or programs that must be loaded into main memory before execution. The Interface Ports To be of any use, a computer must be able to interact with its environment. Although conventionally one thinks of a keyboard and screen, any of a range of physical devices may be read and controlled. Thus the ?ow of fuel injected into a cylinder together with engine speed may be used to alter the instant of spark ignition in the combustion chamber of a gas/petrol engine. me co al, rci 6 ef us 0 2 edu or E tio ca nly no wasn’t always so; the earliest practical large high-speed program memories used miniature ferrite cores (donuts) that could be magnetized in any one of two directions. Core memories were in use from the 1950s to the early 1970s, and program memory is sometimes still referred to as core. 2 This http://i-tronics.blogspot.com/ 44 The Quintessential PIC Microcontroller Data Highway All the elements of the von Neumann computer are wired together with the one common data highway, or bus. With the CPU acting as the master controller, all information ?ow is back and forward along these shared wires. Although this is e?cient, it does mean that only one thing can happen at any time. This phenomena is sometimes known as the von Neumann bottleneck. Memory Program code Control The outside world Input interface port for ot N me co al, rci ef us Data highway Processing unit (ALU) edu or Output interface port tio ca The outside world nly no Program Data Memory Fig. 3.2 An elementary Harvard architecture computer. The Harvard architecture illustrated in Fig. 3.2 is an adaptation of the standard von Neumann structure, that separates the shared memory into entirely separate Program and Data stores. The diagram shows two physically distinct buses used to carry information to the CPU from these disjoint memories. Each memory has its own Address bus and thus there is no interaction between a Program cell and a Data cell’s address. The two memories are said to lie in separate memory spaces. The Data store is sometimes known as the File store, with each location n being described as File n. The fetch instruction down – decode it – execute sequence, the so called fetch and execute cycle, is fundamental to the understanding of http://i-tronics.blogspot.com/ highway Cl oc k 3. Stored Program Processing 45 the operation of the computer. To illustrate this operating rhythm we look at a simple program that takes a variable called NUM_1, then adds 65h (101d) to it and ?nally assigns the resultant value to the variable called NUM_2. In the high-level language C this may be written as:3 NUM_2 = NUM_1 + 101; Program memory (Code store) movf Data memory (File store) 00F 00 01 0805 05,w 000 addlw 001 65h movwf 002 06 003 3E65 011 0086 010 012 013 01F 02 03 020 021 022 023 02F NUM_1 NUM_2 04 030 031 Program address bus 032 Prog 033 03F PC 001 Program Counter tf No co or me addlw 65h 3E65 Instruction Register 1 al, rci IR1 IR2 ID Central Processing Unit (CPU) FAR FDR ef us BASIC Fetch Unit Control signals to internal resources edu or 05 File Address Register Fil ea dd res sb u tio ca DATA1 05 DATA2 06 07 nly no movf 05,w 0805 Instruction Register 2 Instruction Decoder Fig. 3.3 A snapshot of the CPU executing the ?rst instruction whilst fetching down the second instruction. A rather more detailed close-up of our computer, which I have named BASIC (for Basic All-purpose Stored Instruction Computer) is shown in be expressed as NUM_2 := NUM_1 + 101 3 If you are more familiar with PASCAL or Modula-2, ram data bus File data bus File Data Register Execute Unit ALU Pass through Arithmetic Logic Unit W DATA1 Working Register Internal data transfer bus then this program statement would http://i-tronics.blogspot.com/ s DATA1 46 The Quintessential PIC Microcontroller Fig. 3.3. This shows the CPU and memories, together with the two data highways (or buses) and corresponding address buses. The CPU can broadly be partitioned into two sectors. The leftmost circuitry deals with fetching down the instruction codes and sequentially presenting them to the Instruction decoder. The rightmost sector executes each instruction, as controlled by this Instruction decoder. Looking ?rst at the fetch process: Program Counter Instructions are normally stored sequentially in Program memory, and the PC is the counter register that keeps track of the current instruction word. This up-counter (see Fig. 2.22 on page 37) is sometimes called (perhaps more sensibly) an Instruction Pointer. As the PC is connected to the Execution unit – via the internal data bus – the ALU can be used to manipulate this register and disrupt the orderly execution sequence. In this way various Goto and Skip to another part of the program operations can be implemented. Instruction Register 1 The contents of the Program store cell pointed to by the PC, that is instruction word n, is latched into IR1 and held for processing during the next cycle. Instruction Register 2 During the same cycle as instruction word n is being fetched, the previously fetched instruction word n - 1 in IR1 is moved into IR2 and feeds the Instruction decoder. for ot N Instruction Decoder The ID is the ‘brains’ of the CPU, deciphering the instruction word in IR2 and sending out the appropriate sequence of signals to the execution unit as necessary to locate the operand in the Data store (if any) and to con?gure the ALU to its appropriate mode. In the diagram the instruction shown is movf 5,w (MOVe File 5 to the Working register). me co al, rci ef us edu or tio ca nly no The Execution sector deals with accesses to the Data store and con?guring the ALU. Execution circuitry is controlled from the Instruction Decoder, which is in turn commanded by Instruction word n - 1 in IR2. File Address Register When the CPU wishes to access a cell (or ?le) in the Data store, it places the ?le address in the FAR. This directly addresses the memory via the File address bus. As shown in the diagram, File 5 is being read from the Data store and the resulting datum is latched into the CPU’s File Data Register. File Data Register This is a bi-directional register which either: http://i-tronics.blogspot.com/ 3. Stored Program Processing 47 • Holds the contents of an addressed ?le if the CPU is executing a Read cycle. This is the case for instruction 1 (movf 5,w) that moves (reads) a datum from File 5 into the Working register. • Holds the datum that a CPU wishes to send out (Write) to an addressed ?le. This Write cycle is implemented for instruction 3 (movwf 6) that moves (writes) out the contents of the Working register to File 6. Arithmetic Logic Unit The ALU carries out an arithmetic or logic operation as commanded by its function code (see Fig. 2.9 on page 25) as generated by the Instruction Decoder. Working Register W is the ALU’s working register, generally holding one of an instruction’s operands, either source or destination. For example, subwf 20,w subtracts the contents of the Working register from the contents of File 20 and places the di?erence back in W. Some computers call this a Data register or Accumulator register. In our BASIC computer, each instruction word in the Program store is 14 bits long. Some of these bits code the operation, for example 000111b for Add and 000110b for Exclusive-OR. This portion of the Instruction word is called the operation code or op-code (see Chapter 5). The rest of the instruction word bits generally relate to where in the Data store the operand is or sometimes a literal (constant) operand, such as in addlw 6 (ADD Literal 6 to W). For example the instruction word for SUBtract File from W (subfw) is structured as op-code d ???f, where: No for t • The op-code for Subtract is 000010b or 02h. • d is the destination for the di?erence, with 0 for W and 1 for a ?le, as speci?ed below. • ???f is the 7-bit address of the subtrahend ?le (and destination if d is 1), from 00h through to 7Fh. me co al, rci ef us edu or tio ca nly no For example subwf 20h,w is coded as 000010 0 0100000 b or 0220h. As the Program and Data stores are separate entities, their cell size need not be the same. In our case each ?le holds an 8-bit byte datum. In consequence both the ALU and Working register are also byte sized. Generally the ALU size de?nes the size of the computer, and so BASIC could be described as an 8-bit machine. Real computers range in size from one bit up to 64 bits. From the previous example we see that seven bits of the instruction code are reserved for the ?le address, and thus the Data store has a maximum capacity for direct access limited to 128 (27 ) 8-bit ?les. The Program memory capacity is a function of the Program Counter. If this were 10 bits wide, then the Program store could directly hold 1024 (210 ) 14-bit instructions. OK. We have got our CPU with its Program and Data stores. Let us look at the program itself. There are three instructions http://i-tronics.blogspot.com/ 48 The Quintessential PIC Microcontroller in our illustrative software, and as we have already observed the task is to copy the value of a byte-sized variable NUM_1 plus 101d (65h) into a variable called NUM_2. This is symbolized as: NUM_2 = NUM_1 + 101; We see from our diagram that the variable named NUM_1 is simply a symbolic representation for “the contents of File 5” (which is shown as DATA1), and similarly NUM_2 is a much prettier way of saying “the contents of File 6” (shown as DATA2). Now as far as the computer is concerned, starting at location 000h our program is: 00100000000101 11111001100101 00000010000110 Unless you are a CPU this is not much fun! Using hexadecimal5 is a little better. 0805 3E65 0086 4 for ot N but is still instantly forgettable. Furthermore, the CPU still only understands binary, so you are likely to have to use a translator program running on, say a PC, to translate from hexadecimal to binary. If you are going to use a computer as an aid to translate your program, known as source code, to binary machine code, known as object code, then it makes sense to go the whole hog and express the program symbolically. Here the various instructions are represented by mnemonics (eg. clrf for CLeaR File, subwf for SUBtract File from W) and variables’ addresses are given names. Doing this our program becomes: me co al, rci ef us edu or tio ca nly no movf NUM_1,w addlw 101 movwf NUM_2 ; Copy the variable NUM_1 to W ; Add the literal constant 101 decimal to it ; Copy NUM_1+101 into NUM_2 where the text after a semicolon is comment, which makes the program easier to understand by the tame human programmer. Chapter 8 is completely devoted to the process of translation from this assembly-level source code to machine-readable binary. Here it is only necessary to look at the general symbolic form of an instruction, which is: instruction mnemonic , know; I have programmed this way back in the primitive middle 1970s. that we are only using hexadecimal notation as a human convenience. If you took an electron microscope and looked inside these cells you would only ‘see’ the binary patterns indicated. 5 Remember 4I http://i-tronics.blogspot.com/ 3. Stored Program Processing 49 for ot N A few instructions have no explicit operand, such as return (RETURN from subroutine) and nop (No OPeration); however, the majority have one, two or even three operands. For instance, the operation Clear on its own does not make sense. Clear what? Thus we need to say “clear the destination ?le”; for example clrf 20h to clear File 20h. Here Operand A is the ?le address 20h. This could be written as (f) <- 00, where the brackets mean “contents of” and <- means “becomes”. This notation is called register transfer language (rtl). Many instructions have two operands. Thus the instruction incf f,d takes a copy of the contents of the speci?ed ?le plus one and places this in either the Working register (d = w) or back in the ?le itself (d = f). For example, incf 20h,w means “deposit the contents of File 20h plus one in the Working register”. In rtl this is W <- (f20) + 1. Three-operand instructions are common. For example, addwf f,d adds the W register’s contents to the speci?ed ?le’s contents and deposits the result either in W or in the ?le itself. Thus addwf 20h,f means “add the contents of W to that of File 20h and put the outcome in File 20h” or (f20) <- W + (f20). Of course this is not a true 3-operand instruction as the destination must be one of the two source locations; that is W or 1 File 20h. It is more accurately described as a 2 2 -operand instruction! All three instructions in our exemplar program have two operands, of which the Working register is either the source or/and destination. Where an instruction has a choice of destination d – as in movf f,d – then this is indicated appropriately as Operand B. Thus in our program movf 5,w. Where the source or destination is ?xed as the Working register then this is indicated in the mnemonic itself, as in addlw (ADD Literal to W) and movwf (MOVe W to File). The ?rst and last instructions specify an absolute ?le, which is an actual location in the Data store. In a large program it is easier for us humans to give these variables symbolic names, such as NUM_1 for File 5 and NUM_2 for File 6. Of course we must somewhere tell the assembler (the program that does the translation) that NUM_1 and NUM_2 equate to addresses File 5 and File 6 respectively. The middle instruction addlw 101 adds a constant number or literal (that is 101d or 65h) to W rather than a variable in memory. This literal is actually stored as part of the instruction word bit pattern (see page 107). In rtl this instruction implements the function W <- W + 65. In some cases it may be desirable to give a literal a symbolic name. In writing programs using assembly-level symbolic representation, it is important to remember that each instruction has a one to one correspondence to the underlying machine instructions and its binary code. In Chapter 9 we will see that high-level languages loose that 1:1 relationship. The essence of computer operation is the rhythm of the fetch and execute cycles. Here each instruction is successively brought down from me co al, rci ef us edu or tio ca nly no http://i-tronics.blogspot.com/ 50 The Quintessential PIC Microcontroller the Program store (fetched), interpreted and then executed. As any execution memory access will be on the Data store and as each store has its own busses, then the fetch and execution processes can progress in parallel. Thus while instruction n is being fetched, instruction n - 1 is being executed. In Fig. 3.3 the instruction codes for both the imminent and current instructions are held in the two Instruction registers IR1 and IR2 respectively. This structure is known as a pipeline, with instructions being fetched into one end and ‘popping out’ into the Instruction decoder at the other end. Figure 3.4 below shows the time line of our 3-instruction exemplar program, quantized in clock cycles. During each clock cycle, except for the ?rst, both a fetch and an execution is proceeding simultaneously. Cycle 1 Fetch stream , IR1 Fetch movf 5,w Cycle 2 Fetch addlw 65h Cycle 3 Fetch movwf 6 Execute stream, IR2 Execute movf 5,w for ot N In order to illustrate the sequence in a little more detail, let us trace through our specimen program. We assume that our computer (that is the Program Counter) has been reset to 000h and has just ?nished the Cycle 1 fetch. Fetch (Fig. 3.3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Cycle 2 me co Fig. 3.4 Parallel fetch and execute streams. al, rci e fo us Execute addlw 65h edu r Time tio ca Fetch next instr Execute movwf 6 Cycle 4 nly no • Increment the Program Counter to point to instruction 2. • Simultaneously move the instruction word 1 down the pipeline (from Instruction register 1 to Instruction register 2). • Program Counter (001h) to Program address bus. • The instruction word 2 then appears on the Program data bus and is loaded into Instruction register 1. Execute (Fig. 3.3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Cycle 2 • The operand address 05h (i.e. NUM_1) to the File Address register and out onto the File address bus. • The resulting datum at NUM_1 is read onto the File data bus and loaded into the File Data register. http://i-tronics.blogspot.com/ 3. Stored Program Processing 51 • The ALU is con?gured to the Pass Through mode, which feeds the datum through to the Working register. Fetch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Cycle 3 • Increment the Program Counter to point to instruction 3. • Simultaneously move the instruction word 2 down the pipeline (from Instruction register 1 to Instruction register 2). • Program Counter (002h) to Program address bus. • The instruction word 3 then appears on the Program data bus and is loaded into the pipeline at Instruction register 1. Execute . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Cycle 3 of instruction word 2) is added to the datum in W. • The ALU output, NUM_1 + 65h, is placed in W. • The ALU is con?gured to the Add mode and the literal (which is part Fetch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Cycle 4 • • • • Increment the Program Counter to point to instruction 4. Simultaneously move instruction word 3 down the pipeline to IR2. Program Counter (003h) to Program address bus. The instruction word 4 then appears on the Program data bus and is loaded into the pipeline at IR1. for ot N Execute . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Cycle 4 • The operand address (i.e. NUM_2) 06h to the File Address register and out onto the File address bus. • The ALU is con?gured to the Pass Through mode, which feeds the contents of W through to the File Data register and onto the File data bus. • The datum in the File Data register is written into the Data store at the address on the File address bus and becomes the new datum in NUM_2. me co al, rci ef us edu or tio ca nly no Notice how the Program Counter is automatically advanced during each fetch cycle. This sequential advance will continue inde?nitely unless an instruction to modify the PC occurs, such as goto 200h. This would place the address 200h into the PC, overwriting the normal incrementing process, and e?ectively causing the CPU to jump to whatever instruction was located at 200h. Thereafter, the linear progression would continue. Although our program doesn’t do very much, it only takes around 1 µs to implement each instruction. A million unimpressive operations each second can amount to a great deal! Nevertheless, it hardly rates highly in http://i-tronics.blogspot.com/ 52 The Quintessential PIC Microcontroller for ot N the annals of software, so we will wrap up our introduction to computing by looking at some slightly more sophisticated examples. Writing a program is somewhat akin to building a house. Given a known range of building materials, the builder simply puts these together in the right order. Of course there are tremendous skills in all this; poor building techniques lead to houses that leak, are drafty and eventually may fall down! It is possible to design a house at the same time as it is being built. Whilst this may be quite feasible for a log cabin, it is likely that the ?nal result will not remain rain proof very long, nor will it be economical, maintainable, ergonomic or very pretty. It is rather better to employ an architect to design the edi?ce before building commences. Such a design is at an abstract level, although it is better if the designer is aware of the technical and economic properties of the available building materials. Unfortunately much programming is of the ‘on the hoof’ variety, with little thought of any higher-level design. In the software arena this means devising strategies and designing data structures in memory. Again, it is better if the design algorithms keep in mind the materials of which the program will be built; in our case the machine instructions. At the level of our examples in this chapter, it will be this coding (building) task we will be mostly concerned with. Later chapters will cover more advanced structures which will help this process, and we will get more practice at devising strategies and data structures. In order to code software we must have a knowledge of the register architecture of the computer/microcontroller and of the individual instructions. Figure 3.5 shows the programming model we will use for our exercises. This shows all registers that can be ‘got at’ by the programmer. I have added three registers to the previous complement that actually are part of the Data store rather than the CPU but have a special signi?cance for the programmer. File 0 and File 4 are a pair of Address registers working in tandem to point to an object in memory, as described further on in Fig. 3.6. The Status Register6 STATUS comprises two bits in File 3 that are used to tell the software something about the outcome from an instruction. Thus the C ?ag (bit 0 in File 3) primarily holds the Carry out from the last Addition operation. For instance (in decimal) 5 + 2 = 7C0; 5 + 9 = 4C1. It also functions as the complement of the Borrow out from a Subtraction operation. For example 5 - 2 = 3B1; 5 - 9 = 6B0. The Z ?ag (bit 2 in File 3) is set if the result of the last operation is zero. Table 3.1 shows all the instructions supported by the BASIC computer. Before looking at these, let us discuss the concept of the address mode. Most instructions act on data, which may be in internal CPU registers or out in the Data store. Thus the location of such operands must be part of the instruction. It isn’t su?cient to simply state clr – Clear what? There me co al, rci ef us edu or tio ca nly no 6 Some processors use the term Code Condition register. http://i-tronics.blogspot.com/ 3. Stored Program Processing 53 Table 3.1: Our BASIC computer’s instruction set. Instruction Arithmetic Add W and F Add Literal and W Clear F Clear W Increment F Decrement F Subtract W from F Subtract W from L Movement Move F Move W to F Move Literal to W Logic AND W and F AND Literal and W Complement F Inclusive OR W and F Inclusive OR Literal and W Rotate left F andwf andlw comf iorwf iorlw rlf movf movwf movlw f,d f L f,d L f f,d L f,d f,d f,d L f,b f,b f f (d) <- (f) W <- (f) W <- #L addwf addlw clrf clrw incf decf subwf sublw f,d L f f,d f f,d L (d) <- W + (f) W <- #L + W (f) <- 00 (f) <- 00 (d) <- (f) + 1 (d) <- (f) - 1 (d) <- (f) - W W <- #L - W Mnemonic Operation Flags ZC v v v v v v v v v v v • • • • v v tf No om rc o Skip and Jump Rotate right F rlr eXclusive OR W and F xorwf eXclusive OR Literal and W xorlw Bit Test F, Skip if Clear Bit Test F, Skip if Set Decrement F, Skip if Zero Go to address Increment F, Skip if Zero btfsc btfss decfsz goto incfsz cia er us l, e fo (d) ++(f) == 0 ? PC++ : v • v v• • •• • v• PC • •• v PC • v C d L ++ A?S1:S2 : : : : : : : Flag operates normally E?ective address Carry or Borrow, bit 0 in F3 Destination; 0 = W, 1 = ?le 8-bit Literal Increment IF A is True THEN DO S1 ELSE DO S2 • b Z W == -- : : : : : : Flag not a?ected Bit b (0–7) in ?le Zero, bit 2 in F3 Working register Equivalent to Decrement http://i-tronics.blogspot.com/ 54 The Quintessential PIC Microcontroller 7 0 Working register 9 F2 0 Program Counter 7 F0 0 Indirect Pointer register F4 File Select register Address register pair 2 for ot N are di?erent ways of specifying the operand location. These are known as address modes. Inherent A few instructions, not shown in Table 3.1, do not explicitly refer to any location. For example return for RETURN from subroutine.. Register Direct Here the operand is speci?ed to be in the Working register. For example: clrw ; Clear the Working register me co al, rci Status register (F3) ef us Z edu C or 0 tio ca nly no Fig. 3.5 Programmer’s model. Most instructions specify at least one operand should be in W. In many cases W can be both a source and the destination operand. For instance: addwf f,w ; Add W to a file and put the answer in W where W initially holds one of the two source datum bytes, and ends up holding the outcome datum. http://i-tronics.blogspot.com/ 3. Stored Program Processing 55 Literal This address mode is used to specify an operand which is constant data rather than a location. For example: addlw 120 ; Add the constant 120 (#120) decimal to W Only special literal instructions are used with this type of data, such as movlw and sublw. The destination of this type of instruction is always W. The sublw instruction sometimes causes confusion as it actually takes away the contents of W from the literal byte and not vice versa. Thus sublw 1 does not subtract one from the contents of W (i.e. decrement W) but 1 - W. To decrement the contents of W use addlw -1 (i.e. addlw 0FFh). Note the use of the # symbol in the rtl description to denote that the following number is constant data. A few instructions can test or modify a single bit in a File. For instance: btfsc 3Fh,6 ; Test File 3Fh bit 6; skip next instr. IF Clear in which Operand B is the ?xed literal 6, specifying the bit position in Operand A’s speci?ed File. In both kinds of literal instruction the constant is encoded as part of the instruction word. In the former, eight bits of the 14-bit word is used, and in the latter three bits (see Appendix A). File Direct Here the totally ?xed ?le address of the operand, either source or/and destination is directly speci?ed. For example: for ot N clrf 20h clears the byte out at File 20h. In many cases the same ?le can be both source and destination. Thus: incf 20h,f ; Put the contents of File 20h plus 1 into File 20h me co ; Clear the byte at File store address 20h al, rci ef us edu or tio ca nly no as opposed to the Working register: incf 20h,w ; Put the contents of File 20h plus one into W which uses File Direct addressing for Operand A and Register Direct for Operand B. The main characteristic of this address mode is that the location of the operand is ?xed as an integral part of the program, and thus cannot be changed as execution progresses. Although directly specifying its address may seem to be the obvious way to locate an object in the Data store, in some situations this technique is rather in?exible. Suppose we wished to clear all ?le registers from 0Ch through to 3Fh in the File store, say to hold an array of 52 byte elements. The obvious http://i-tronics.blogspot.com/ 56 The Quintessential PIC Microcontroller Program 3.1 Clearing a block of ?les the linear way. CLEAR_ARRAY clrf 0Ch ; Clear File 12 clrf 0Dh ; and File 13 clrf 0Eh ; Each clrf clrf 0Fh ; uses one instruction word clrf 10h ; in the Program store clrf 11h ; File 17 cleared clrf 12h ; and so on .... ... .... ... clrf 3Eh ; Clear File 62; nearly there clrf 3Fh ; Clear File 63; Phew! way to do this is shown in Program 3.1, which uses a clrf instruction for each byte. Although it works, it is rather ine?cient, and the mind boggles if you wanted to clear, say, a 1 Kbyte File store. There has got to be a better way! for ot N File Indirect Indirect addressing uses an address register to hold the address of an operand. This address register thus acts as a pointer into the Program store. The term indirect is used as this address register does not hold the operand datum itself, only a pointer address to it. The advantage of this seemingly perverse way of accessing data in the Data store, is that the e?ective address (ea) is a variable and this can be altered by the program as it progresses. This ea is the contents of this special pointer address register. In our BASIC computer the File Select Register (FSR) is implemented as File 4 in the File store. The indirect mechanism is evoked when the dummy address File 0 (there is no physical ?le at location 0 in the Data store) is used for the operand address, as shown in Fig. 3.6.7 Thus, for example, if the contents of File 4 happened to be 20h then: me co al, rci ef us edu or tio ca nly no movwf 0 ; Store datum in W out to place pointed to by File 4 will e?ectively copy the contents of W out to File 20h. This seems rather an obscure way of doing things, but by way of a justi?cation let us revisit our array clearing example of Program 3.1. Repeating the same thing 52 times on successive ?le locations is a dubious way of doing this. Why not use a pointer into the array, and increment this pointer each time we do a Clear? That is, rather than using a constant address for the destination operand use a variable e?ective address. Program 3.2 follows the scheme by folding the linear structure of the previous program into a loop, shown shaded. The execution path keeps this all seems rather complicated, I have kept in mind the microcontroller that we will be examining in the following chapters. 7 Although http://i-tronics.blogspot.com/ 3. Stored Program Processing 57 F0 actually In st r uc tio n re fe re nc in g sends this address F4 ou t to th e Fi le st o re Fig. 3.6 The indirect mechanism. circulating around the clrf instruction, which is ‘walked’ through the array of ?les by advancing the pointer in File 4, the FSR, on each pass through the loop. Eventually the pointer moves beyond the desired range and the program then exits the loop and continues onto the next section of code. Program 3.2 has many new features, especially as we haven’t yet reviewed the instruction set. for ot N Go here if FSR is not equal to 30h me co CLOOP ; Now Program 3.2 Clearing a block of ?les using a repeating loop. various registers & bits for readibility ; Give File 4 the name FSR (File Select Reg.) ; Give File 3 the name SR (Status Register) ; The Z flag is bit 2 of the SR al, rci ef us edu or tio ca nly no ; Name the FSR equ 4 SR equ 3 Z equ 2 ; Now for the program proper CLEAR_ARRAY movlw 0Ch ; Put start address in W movwf FSR ; and into the FSR as a pointer clrf incf check, is movf sublw btfss goto .... 0 ; FSR,f ; pointer FSR,w ; 40h ; SR,Z ; CLOOP ; .... Clear byte pointed to by FSR Increment pointer in FSR at top yet? Copy the pointer address into W Compare with the end address (40h) IF Zero flag in SR is set THEN fini ELSE do the next pass thru the loop Leave if FSR = 30h ; Next part of the program http://i-tronics.blogspot.com/ 58 The Quintessential PIC Microcontroller Phase 1 From the point of view of readability, variables, registers and individual status and control bits should be given a relevant name. For example, btfss STATUS,Z (Bit Test File Skip if Set) which checks the Z ?ag (bit 2 in File 3) and skips the following instruction if set (that is the outcome of the previous instruction is zero) can be written in two ways; both of which are functionally identical: btfss btfss 3,2 ; IF bit 2 of File 3 is set THEN finished STATUS,Z ; IF Zero flag in STATUS is set THEN finished Obviously the latter is preferable. Although this might seem to be a cosmetic exercise, clarity reduces the chance of error and makes debugging and subsequent alteration easier. Realistic programs, rather than the code fragment illustrated here, use many variables and register bits, so lucidity is all the more important. The three header lines of our program illustrate the means whereby the programmer tells the assembler translator program to substitute numbers for names. For example the line: FSR equ 4 states that when the programmer uses the name FSR as an operand, it is to be substituted by the number 4 (that is File 4). The equ directive means “equivalent to”. A directive is a pseudo instruction in that it does not usually produce actual machine code but rather is a means of passing information from the programmer to the assembler program. for ot N Phase 2 The ?rst two proper instructions initialize the File Select Register to point to the ?rst byte to be cleared, by moving the constant 0Ch into the Working register and then out to File 4. Nearly all loop instructions involve some setting up before entry. Phase 3 The key Clear instruction uses the File Indirect address mode by specifying the phantom File 0 as the destination address. This line has a label associated with it called CLOOP. The assembler knows that this is a label and not an instruction as it appears in the leftmost column of the source ?le. Lines without labels should begin with an indent of at least one space. Each pass around the loop involves an incrementation of the pointer. This is done by using the incf FSR,f instruction to increment the FSR ?le. Notice that the destination here is speci?ed as a ?le and not the W register. Phase 4 Unless you wish to go round the loop forever, we need a mechanism to eventually exit. In our case this is done by comparing the contents of the me co al, rci ef us edu or tio ca nly no http://i-tronics.blogspot.com/ 3. Stored Program Processing 59 FSR pointer ?le with the constant 40h, that is with one over the top target ?le 3Fh. The comparison mechanism is to copy the contents of the FSR pointer into W and then subtract W from the literal 40h using sublw 40h. If they are equal then the Z ?ag will be set and in this event the next btfss instruction will skip over the following goto LOOP instruction, out of the loop. Until this happens, the goto instruction will move the execution back up to the beginning of the loop and the process is repeated with the FSR advanced to point to the next ?le to be cleared. All together our loop version takes eight machine instructions against the 52 of the linear equivalent. However, it does take longer to execute as the six instructions in the loop are repeated 52 times! Absolute The goto instruction forces the execution to directly transfer to the speci?ed address by simply overwriting the Program Counter with the e?ective address – for example goto 145h puts 145h into the PC. It contrasts with the various Skip instructions (see page 61) which simply branch over the following instruction, wherever they are encountered. This latter type of branch is called relative, as opposed to the absolute transfer of execution used by the goto instruction. Having covered the address modes, let us look brie?y at the instruction set in Table 3.1. Instructions have been divided into four groups as follows. Arithmetic This covers the Addition, Subtraction, Incrementation, Decrementation and Clearing operations. Addition is possible between data in W and out in the File store, with the sum being placed either in the same ?le or in W. Similarly subtraction of W from a ?le is implemented, with the di?erence being placed in the same ?le or W. Both instructions come in a literal version, where W is added to/subtracted from an 8-bit constant, with the outcome remaining in the Working register. Notice that in the latter case the variable in W is subtracted from the literal rather than the more obvious subtraction of the literal from W. The contents of any ?le can be incremented or decremented using incf and decf respectively. The outcome is usually put back into the ?le but the Working register can alternatively be speci?ed as the destination. Any ?le can be cleared with clrf, for instance clrf 20h. In the same manner the Working register can be zeroed with clrw. Movement This category of instructions copy a datum from source to destination. In all cases the contents of the source remains unaltered. movf reads (loads) a byte from the File store, usually into the Working register; eg. movf 20h,w. It is possible to specify the seemingly useless operation of copying a ?le’s datum on top of itself, such as in move 20h,f. However, for ot N me co al, rci ef us edu or tio ca nly no http://i-tronics.blogspot.com/ 60 The Quintessential PIC Microcontroller this does have the side e?ect of setting the Z ?ag if the datum is zero but in any case not altering a ?le’s contents. This can be used to implement a Test for Zero operation. Other instructions in this category write (store) the contents of W out into the File store (eg. movwf 20h copies W into File 20h) or a literal into W (eg. movlw 6 puts the constant 06h into W). Logic The comf instruction inverts (complements or NOTs) all bits in the speci?ed ?le (see Fig. 1.1 on page 12). For example: 10001110 F 20h comf 20h 01110001 F 20h The andwf instruction bitwize ANDs (see Fig. 1.2 on page 13) the contents of the Working register to that of a speci?ed ?le, with the outcome being either in W or in the ?le. For example: 00001111 W andwf 20h,f 10010111 F 20h It is also possible to AND a constant to W by using the andlw variant. Whilst the AND operation can be used to zero (mask) any bit or bits in the speci?ed ?le, the Inclusive-OR equivalent instructions can set to one any bit or bits in the destination. For example, ORing W with the literal 10000000b (80h): tf No co or 00001110 remembering from Fig. 1.3 on page 13 that ORing with a logic 1 always results in a logic 1 outcome and ORing with zero does not alter the original data, leads to the outcome that the most signi?cant bit position of W is set and the other bits remain unaltered. The xorwf and xorlw instructions provide for the eXclusive-OR operation. You will recall from page 14 that XORing with a 0 leaves a data bit unchanged, whilst XORing with a 1 inverts (or toggles) that bit. Thus, for example if we wished to invert both bits 0 and 7 of W: 10001110 W xorlw 81h me W iorlw 80h al, rci ef us W edu or 00000111 tio ca F 20h nly no 10001110 00001111 W Two instructions are provided that can shift the contents of any ?le once left or right, with the outcome either remaining in the ?le or appearing in the W register. As shown in Fig. 3.7 the outgoing bit (bit 7 for rlf f,d and bit 0 for rrf f,d) is placed in the C ?ag, whilst the incoming bit at the opposite end is the previous value of C. Because of this ‘circular’ action these instructions are said to implement a Rotate data through the Carry operation. http://i-tronics.blogspot.com/ 3. Stored Program Processing Bit 0, File 3 Bit 0, File 3 61 C Bit 7 Bit 7 Bit 0 C Bit 0 rrf rlf (a) Rotate Right File (b) Rotate Left File Fig. 3.7 Circular shifts. for ot N Skip and Jump These instructions alter the state of the Program Counter, e?ectively interrupting the progressive ?ow of the program and causing processing to branch to another point in the code. The simplest of these instructions is goto. This overwrites the PC with the absolute destination address. For instance, goto 200h will change the PC to 200h and cause the program ?ow to ‘jump’ to whatever instruction is located at this address. Another example is instruction 8 in Program 3.2 where execution jumps back up to the beginning of the loop at address CLOOP. The goto instruction causes an unconditional absolute jump in the program ?ow, implementing a ‘Jump Always’ operation. The remaining four instructions are conditional in that the smooth program progression is interrupted only if the outcome matches the speci?ed state. For instance decfsz decrements the speci?ed ?le contents and if and only if the outcome is zero the following instruction is skipped over. Four instructions in our set come into this category, in that they increment the PC if some condition is ful?lled. Remembering that each instruction occupies one word in Program memory, incrementing the PC is equivalent to skipping over the following instruction. This relative skipover action is in contrast with the absolute always jump to the speci?ed address action of the goto instruction. The four relative instructions are: me co al, rci ef us edu or tio ca nly no btfsc Bit Test File & Skip if Clear by-passes the next instruction if the speci?ed bit in the ?le in question is zero. For example btfsc 3,02h skips if bit 2 in File 3 is clear. btfss Bit Test File & Skip if Set by-passes the next instruction if the speci?ed bit in the ?le in question is one. For example btfss 3,02h skips if bit 2 in File 3 is one. http://i-tronics.blogspot.com/ 62 The Quintessential PIC Microcontroller decfsz DECrement File & Skip if outcome is Zero subtracts one from the speci?ed ?le and by-passes the next instruction if the outcome is zero. For example decfsz 30h,f skips if the content of 30h once decremented is zero. The decremented value is placed back in the ?le in this example but W is an alternative destination, as in decfsz 30h,w. incfsz INCrement File & Skip if outcome is Zero adds one to the speci?ed ?le and by-passes the next instruction if the outcome is zero. For example incfsz 30h,f skips if the content of 30h once incremented is zero. The incremented value is placed back in the ?le in this example but W is an alternative destination, as in incfsz 30h,w. Actually the Program Counter is located in the Data store as File 2. Thus manipulating this ?le can implement a computed relative skip. For example: movf 2,w addlw 6 movwf 2 ; Bring the current value of the PC into W ; Add six to it ; Update PC, that is hop forward six places for ot N More details of this technique are given on page 86. As more sophisticated example of the use of conditional Skip instructions and the absolute goto instructions, consider the problem of repeating a sequence 16 times. The most e?cient approach to the coding is to construct a program loop and keep track of the number of times the processor executes the encapsulated instructions. In the following listing File 22h is used as the counter, initialised to 16 before the loop is entered. At the end of the sequence the count is decremented using decfsz and normally the next instruction, which transfers the PC back up to the start of the loop, is executed. However, eventually the count reaches zero and the goto LOOP instruction is skipped over, with execution consequently exiting the loop. Traditionally the potentially skipped over instruction is shown indented as a matter of style. me co movlw movwf 16 22h al, rci ef us edu or tio ca nly no ; Set up constant #16 ; and put in File 22h for use as a counter ; Now for the sequence of instructions to be repeated 16 times LOOP ..... ... ; DO this ..... ... ; DO that ..... ... ; DO the other ; Count mechanism decfsz 22h ; Decrement count. IF zero THEN exit loop -goto LOOP ; ELSE repeat loop | | ..... ... <-- http://i-tronics.blogspot.com/ 3. Stored Program Processing 63 The incfsz instruction works in a similar manner, but for an up count, skipping when the target ?le over?ows FF ? 00h. As an exercise, repeat the example but using incfsz in place of decfsz.The ++(f) and --(f) rtl symbology used to describe the incfsz and decfsz instructions indicate that the contents of the designated ?le is augmented or decremented before testing for zero. The other set of skip instructions uses the state of any bit b in any ?le to force a conditional skip. Thus if it is desired that the program transfers to an instruction located at label REAL_TIME if bit 2 of File 0Bh is logic 1, then we can use the btfsc (Bit Test File & Skip on Clear) instruction thus: btfsc goto 0Bh,2 REAL_TIME ; Bit Test File 0Bh bit 2. IF==0 THEN skip ; ELSE == 1, GOTO REAL_TIME In Table 3.1 the rtl language description of this instruction is given as b==0?PC++:PC, which can be read as: 1. Is the speci?ed bit (b) equivalent to (==) zero (?). 2. If true then increment the PC (PC++), that is skip. 3. Else it is false, so leave the PC alone. Similarly the -- rtl operator is used to indicate decrementation. Examples for ot N Write a program to add the byte contents in File memory called NUM1 (File 20h) to NUM2 (File 21h). The outcome is to be in SUM_H and SUM_L (File 22h and File 23h respectively) in the order high:low byte. Solution Example 3.1 me co al, rci ef us edu or tio ca nly no This is similar to our load-add-store program on page 48 but the second operand is a byte variable in memory rather than a constant. The three instructions to implement this are shown in Program 3.3. The variable NUM1 is simply fetched down into the Working register and then added to variable NUM2. The outcome of this is then copied into the sum byte SUM_L. Of course this will only work if the outcome of the addition can ?t into a single byte; that is no more than FFh (255d). If, for example, both NUM1 and NUM2 were FFh, then the outcome would be 1 FFh. Thus we need to reserve two bytes for the sum; an upper byte and a lower byte; named SUM_H and SUM_L in Program 3.4 in File 22h and File 23h respectively. In this implementation we simply zero the upper byte of the sum in advance, and after the addition skip around the Increment of instruction 6 if the http://i-tronics.blogspot.com/ 64 The Quintessential PIC Microcontroller Program 3.3 Simple single-precision addition of two byte variables. NUM1 equ 0020h NUM2 equ 0021h SUM_L equ 0022h SP_ADD movf NUM1,w addwf NUM2,w movwf SUM_L ; Get the first memory byte ; Add to it the second byte and put the ; outcome in memory as the lower sum byte Program 3.4 A more accurate single-precision addition of two byte variables. NUM1 equ 0020h NUM2 equ 0021h SUM_L equ 0022h SUM_H equ 0023h STATUS equ 03 SP_ADD clrf SUM_H movf NUM1,w addwf NUM2,w movwf SUM_L ; Prepare the upper sum byte by zeroing it ; Get the first memory byte ; Add to it the second byte and put the ; outcome in memory as the lower sum byte btfsc STATUS,0 ; IF carry is clear (SR bit 0) THEN finish incf SUM_H,f ; ELSE increment higher sum byte EXIT for ot N Carry ?ag (bit 0 in File register 3) is Clear (Bit Test File and Skip on Clear). The upper sum byte can only ever be either 00h or 01h. Example 3.2 me co F22h ... ..... al, rci ; Next part of the program ef us edu or tio ca nly no Write a program routine that will add two 16-bit numbers giving a 17bit sum. The augend is located in the two memory locations F20h:F21h F20h F21h in the order high:low byte thus F23h AUGEND_H AUGEND_L . The addend is similarly situated ADDEND_H ADDEND_L . The sum is stored as three bytes in the order F24h F25h F26h high:middle:low thus Solution SUM_H SUM_M SUM_L . Although BASIC is only capable of directly implementing 8-bit arithmetic, operations of any length are possible by breaking down the process into byte-sized chunks. In the case of addition, this involves a sequence of byte operations from the least to the most signi?cant digits with any carry from the nth digit byte being added into the n+1th summation. The least signi?cant addition has a presumed carry-in of 0 and the carry-out from http://i-tronics.blogspot.com/ 3. Stored Program Processing 65 the most signi?cant addition becomes the highest bit of the outcome. For example FF FFh + FF FFh = 1 FF FFh (65, 535d + 65, 635d = 131, 070d). F20h F21h AUGEND_H AUGEND_L F24h F25h F26h SUM_H SUM_M SUM_L F22h F23h ADDEND_H ADDEND_L Fig. 3.8 The process. The overall process is diagrammatically shown in Fig. 3.8. However, given that we need to implement the process as a sequence of steps executable by the byte-sized instructions of Table 3.1 then the next step is to produce a task listing. 1. Add the low bytes of the augend and addend, generating the low byte of the sum and carry C1. for ot N me co F22h F25h SUM_M F20h F20h AUGEND_H AUGEND_L al, rci F21h F23h ef us C1 edu or C1 C2 tio ca F20h nly no F21h AUGEND_H AUGEND_L F22h F23h ADDEND_H ADDEND_L ADDEND_H ADDEND_L F24h F26h SUM_L F24h SUM_H F25h SUM_M F26h SUM_L SUM_H (a) Adding the least-significant bytes (b) And the most-significant bytes F21h AUGEND_H AUGEND_L C2 F22h F23h ADDEND_H ADDEND_L F24h SUM_H F25h SUM_M F26h SUM_L (c) The most-significant sum byte is the last carry-out Fig. 3.9 Visualization of the task process. http://i-tronics.blogspot.com/ 66 The Quintessential PIC Microcontroller 2. Add the high bytes of the augend and addend plus the last carry-out C1 to give the middle byte of the sum and a new carry-out C2. 3. The high byte of the sum is the last carry-out C2, either 0 or 1. Given that this is our ?rst program of any substance, a detailed visualization of this task list will be useful. For most instances detail at this level is not helpful and subsequently we will use a more abstract visualization known as a ?ow chart (see Example 3.3). Once a task list has been established then the next step is to implement this as a sequence of instructions, that is the program. One possible is shown in Program 3.5. In the listing the three tasks are identi?ed by an appropriate comment. Task 1 This comprises a Load-Add-Store sequence to add the lower byte of the addend to that of the similarly signi?cant augend. The outcome byte is Program 3.5 The double-precision add program. equ 020h equ 021h equ 022h equ 023h equ 024h equ 025h equ 026h equ 03 ; STATUS flag register equ 0 ; The C flag SUM_M SUM_H AUGEND_H AUGEND_L ADDEND_H ADDEND_L SUM_H SUM_M SUM_L STATUS C tf No co or ; Task 1 DP_ADD clrf clrf me al, rci ef us edu or tio ca nly no ; Zero the 2 upper bytes of the sum movf AUGEND_L,w ; Get LSB of the augend addwf ADDEND_L,w ; Add LSB of addend movwf SUM_L ; and put it away ; Was there a carry C1? ; IF yes THEN add to middle sum byte ; ; ; ; Get MSB of the augend Now add to MSB of the addend Was there a carry C2? IF so THEN add to high byte sum ; Tasks 2 and 3 btfsc STATUS,C incf SUM_M movf addwf btfsc incf AUGEND_H,w ADDEND_H,w STATUS,C SUM_H addwf SUM_M,f btfsc STATUS,C incf SUM_H .... ..... ; Add the outcome to mid sum byte ; Was there a carry C2 from this? ; IF so THEN add to high sum byte ; Next program http://i-tronics.blogspot.com/ 3. Stored Program Processing 67 stored in memory at File 26h (SUM_L) and the Carry ?ag bit (bit 0 in File 3) is set as appropriate to C1. Task 2 If there was a carry-out from Task 1 then the precleared middle byte of the sum is incremented as the carry-in C1. Then the upper bytes of the addend and augend are added. The ?nal outcome of SUM_M (in File 25h) is determined by adding its current state (00h or 01h) to the outcome of this addition. Task 3 Either of the two additions in Task 2 can result in a carry-out. The C ?ag in the STATUS register can be tested after each addition and if set, the upper byte of the sum SUM_H (File 26h) is incremented to add C2, as shown in Fig. 3.8(c). There will not be a carry-out generated by both the Task 2 additions. Example 3.3 Write a program to divide the byte in the Working register by ten. The quotient is to be in File 20h and the remainder in W. Solution for ot N Division is the process in ?nding how many times the divisor (ten in our case) can be subtracted from the dividend without under?owing, that is producing a borrow. The ?ow chart shown in Fig. 3.10 outlines the task list to implement our algorithm. Initializing the quotient to -1 means that the subtract and increment loop can begin by incrementing, and this process will continue until a borrow is produced after the subtraction by ten process. A me co clrf decf al, rci ef us edu or tio ca nly no QUOTIENT equ STATUS equ DIV_10 020h 03 Program 3.6 Dividing by ten. ; Where the quotient will be stored ; Where STATUS reg. flags are located QUOTIENT ; 1: Zero quotient QUOTIENT,f ; 1: Initial value is -1 QUOTIENT,f ; 2: Increment quotient ; 3: Subtract ten from dividend ; 4: Leave loop if borrow (bit 0 = 0) ; 4: ELSE repeat increment and subtract ; 5: Add ten to give remainder ; Next program DIV_LOOP incf addlw -10 btfsc STATUS,0 goto DIV_LOOP addlw 10 .... ..... http://i-tronics.blogspot.com/ 68 The Quintessential PIC Microcontroller borrow-out indicates that the last subtraction was not successful in that the divisor (i.e. ten) was larger than the residue it was subtracted from. That is the outcome is negative. The loop count on exit represents the number of successful subtractions and thus the quotient. The coding in Program 3.6 closely follows the ?ow chart, with comment numbers referring to the statement boxes. The actual subtract constant ten is implemented by adding minus ten! This is because the more obvious sublw 10 instruction actually subtracts W from ten and not ten from W. Notice the mechanism for exiting the loop by testing and skipping if bit 0 in STATUS is clear after this subtraction. Remembering that bit 0 in File 3 is the Carry ?ag doubling as the Borrow ?ag, then a borrow out is indicated if this bit is zero after the subtraction. On exit ten is added back on to compensate for the last unsuccessful subtraction and the outcome then gives the remainder. No for t me co al, rci ef us LOOP Quotient = -1 edu or tio ca nly no Increment quotient Subtract ten from dividend No Borrow? Yes Add ten to give remainder End Fig. 3.10 Division by repetitive subtracting. http://i-tronics.blogspot.com/ 3. Stored Program Processing Example 3.4 69 As part of a program to convert degrees Celsius to Fahrenheit it is necessary to multiply the byte in W by nine. Devise a suitable coding. Solution There are two ways of multiplying. The fundamental de?nition of multiplication is repetitive addition, thus we could add the datum nine times to implement our speci?ed function. An alternative approach is the shift and add technique outlined on page 11. Thus the ×9 function is implemented as ×8 + ×1. The former is carried out by shifting left three times (i.e. 23 ). Thus we have: W × 9 = W × 8 + W × 1 = (W << 3) + W No matter what technique is used, the outcome by de?nition will be larger than either the multiplier or multiplicand. In this case we need two bytes. In the coding of Program 3.7 the two memory locations File 20h and File 21h are used to hold the high byte and the low byte respectively of the ?nal 2-byte product. By copying the multiplicand from W to the low byte and clearing the upper byte we make an extended 2-byte version of the multiplicand in Data memory. Shifting left is implemented by using Program 3.7 Multiplying by nine. 3 ; STATUS register flags 0 ; Carry flag is bit0 020h ; High byte of the product 021h ; Low byte PRODUCT_L PRODUCT_H ; Move the multiplicand to memory ; Extend it to 2 bytes to give x8 of product of product of product for ot N STATUS C PRODUCT_H PRODUCT_L MUL_9 me co movwf clrf equ equ equ equ al, rci ef us edu or tio ca nly no ; Now shift the double byte multplicand three times bcf STATUS,C ; Clear carry rlf PRODUCT_L,f ; Shift left low byte rlf PRODUCT_H,f ; and the high byte bcf STATUS,C ; Clear carry rlf PRODUCT_L,f ; Shift left low byte rlf PRODUCT_H,f ; and the high byte bcf STATUS,C ; Clear carry rlf PRODUCT_L,f ; Shift left low byte rlf PRODUCT_H,f ; and the high byte ; Now add the original value giving x8 + x1 = x9 addwf PRODUCT_L,f ; Add to lower byte btfsc STATUS,C ; and any carry to the upper byte incf PRODUCT_H,f end http://i-tronics.blogspot.com/ 70 The Quintessential PIC Microcontroller C PRODUCT_L 1 0 bcf CCR,C C 2 rlf PRODUCT_L,f PRODUCT_H 3 rlf PRODUCT_H,f Fig. 3.11 Double-precision shifting. the rlf (Rotate Left File) instruction twice, beginning with the lower byte. As well as shifting the byte PRODUCT_L left once, the most signi?cant bit is moved into the Carry ?ag. Subsequently rotating the contents of the high byte PRODUCT_H moves this Carry in as the new least signi?cant bit and shifts the high byte left as shown in Fig. 3.11. Of course the Carry ?ag needs to be cleared prior to this process. This 3-instruction double-precision routine is repeated three times to give the required ×8 function. Adding the original multiplicand, which is still in W gives the ?nal ×9 function. Example 3.5 for ot N The circuit diagram of Fig. 3.12 shows a 7-bit pseudo-random number generator (PRNG) based on a shift register with an Exclusive-OR gate feedback. Devise a routine to continually send these 127 binary random numbers to a port located at File 06. The routine must initialize the PRN to any non-zero value. me co al, rci ef us edu or tio ca nly no 1D Data in = B5 + B6 Sample rate B6 B5 B4 B3 B2 B1 B0 C1 Fig. 3.12 A 7-bit pseudo-random number generator. http://i-tronics.blogspot.com/ 3. Stored Program Processing 71 Solution A suitable task list is: 1. Initialize the number to 01. 2. DO forever. (a) Rotate shift a copy of the number once left so that bits 5 & 6 are aligned. (b) Bitwise XOR the number and its shifted copy. (c) Rotate the outcome twice left to pop out bit 6 into the C ?ag, which will be B6?B5. (d) Rotate the original number once left with C becoming the new bit 0. Program 3.8 A 7-bit pseudo-random number generator. equ 6 equ 0x20 equ 0x21 movlw movwf rlf xorwf rlf rlf movwf rlf movwf goto 1 NUMBER PORTB NUMBER TEMP PRNG P_LOOP ; Initial value of random number is 01 ; Make a copy in memory NUMBER,f ; Shift number to align bits 5 & 6 NUMBER,f ; Bitwize XOR them NUMBER,f ; Shift twice left to put 5XOR6 in Carry NUMBER,f TEMP,f TEMP,w PORTB for ot N me co al, rci ; Put original number in memory ; >> with carry coming in, and put in W ; and send this new random number out ; and repeat ef us edu or tio ca nly no P_LOOP The listing in Program 3.8 follows the task list fairly closely. The value of the number is temporarily saved in memory so that it can be processed without altering the original number down in W. This is done by specifying the destination to be the ?le, eg. rlf NUMBER,f. After rotating left once left, bit 5 in the shifted copy in NUMBER is aligned with the original bit 6 in W. After exclusive ORing the two, with the destination again being in File memory (xorwf NUMBER,f), bit 6 in NUMBER is now B5?B6. Shifting twice left puts this bit in the Carry ?ag. Finally rotating the original pseudo-random number in W moves that pattern once left with the new least-signi?cant bit being the Carry ?ag, that is B5?B6 as speci?ed in the diagram. The ?rst 32 hexadecimal values output are: 02 04 08 10 20 41 83 06 0C 18 30 61 C2 85 0A 14 http://i-tronics.blogspot.com/ 72 The Quintessential PIC Microcontroller 28 51 A3 47 8F 1E 3C 79 F2 E4 C8 91 22 45 8B 16 … The sequence will repeat after 127 output values. What would happen if the initial value of the random number was zero? Self-assessment questions 3.1 How could you simply with one instruction toggle bit 0 of any ?le register? 3.2 As part of a Data memory testing procedure each ?le in the range File 0Ch through File 2Fh is to be set to the pattern 01010101b (55h). Using Program 3.2 as a model, write a suitable coding to implement this task. 3.3 Write a program to subtract the double-byte datum which is located in File 22:23h, called NUM_2, from NUM_1 in File 20:21h. The doublebyte di?erence is to be in File 24:25h. Remember, if there is a borrow from the lower byte subtraction then an additional one must be subtracted from NUM_1 in the upper byte subtraction. Assume that NUM_2 is smaller or equal to NUM_1. If this were not so how could you determine this situation after the routine has been completed? 3.4 Write a routine that will determine how many hundreds there are in a byte in Data memory at File 20h. The outcome, which is to be in W, will either be 02h, 01h or 00h. For example if the contents of File 20 are FFh (decimal 255) then the outcome will be two. Hint: Try subtracting the number 200 from that in W and examining the Carry/borrow ?ag. If no borrow then try 100. Again if no borrow then the number must be less than 100. 1 3 for ot N me co al, rci ef us edu or tio ca nly no 3.5 The binary approximation to the fraction is: 1 1 1 1 1 1 1 1 =-+- + - + ··· 3 2 4 8 16 32 64 128 Using this series, write a program that will divide a byte in the Working register by three, with the quotient being in the same register at the end. You can use File 20h and File 21h as temporary storage for the quotient and shifting number respectively. The outcome up to 1 is 0.3359375, which is within 0.78% of the exact value. With an 128 8-bit datum there is no point in including any further elements in the series. http://i-tronics.blogspot.com/ 3. Stored Program Processing 73 3.6 Write a routine that will count the number of ones in the Working register. For example if W were 01110011b then the outcome in File 20h would be 05h. Hint: Continually shift the number, while incrementing the count when the shifted-out bit in the Carry ?ag is one. Either do this eight times or else exit when the residue is zero. Remember if taking the latter approach that the Carry ?ag must be cleared before rotating the number! You may use File 21h as a temporary store for the shifting number. 3.7 Data from an array of data memory between File 30h and File 4Fh is to be transmitted byte by byte to a distant computer over the internet. In order to allow the receiver to examine the data and check for transmission errors it is proposed to append a single byte which is the 2’s complement (i.e. the negative value, see page 9) of the 8-bit sum of all the data bytes together. If all the received data bytes plus this checksum byte are similarly added then the outcome should be zero if no error has occurred. Code a routine to scan through this data, placing this checksum in File 20h. See Example 3.2 for a template. 3.8 One simple way of encrypting a data byte is to reverse the order of bits. For example 10111100b ? 00111101b. Write a routine to implement this reversal on a data byte in File 20h. The encrypted outcome is to be in the Working register. You can use location File 21h as a temporary workspace and W as a loop counter. Hint: Use the Rotate Right and Rotate Left File instruction eight times. If you use W as the loop register then use the instruction addlw -1 as a decrement W operation. for ot N 3.9 Parity is a simple technique to protect digital data from corruption by noise. Odd parity adds a single bit to a word in such a way as to ensure the overall packet has an odd number of 1s. Write a routine that takes an 8-bit byte stored at File 20h and alters its most signi?cant bit to comply with this speci?cation. You can assume that bit 7 is always 0 before the routine begins. Hint: Determine if a binary number is odd or even by counting the number of bits as in SAQ 3.6 and then examining its least signi?cant bit. All powers of two are even except 20 = 1. Thus if this bit is 1 then the number is odd. me co al, rci ef us edu or tio ca nly no http://i-tronics.blogspot.com/ for ot N me co al, rci ef us edu or tio ca nly no http://i-tronics.blogspot.com/ PART II The Software In Part I we developed the concept of the Havard architecture, ending up with our somewhat simpli?ed BASIC computer. Although BASIC was entirely ?ctitious, it was designed with an eye to the MCU that forms the basis for the rest of this book. This part of the text looks mainly at the software aspects of our chosen MCU, the mid-range Microchip PIC family. We will be covering: • The internal structure of the MCU. • The instruction set. • Address modes. • • • • The assembly translation process. Interrupt handling. Subroutines and modular program design. The high-level language C. ot N for me co al, rci ef us edu or tio ca nly no http://i-tronics.blogspot.com/ for ot N me co al, rci ef us edu or tio ca nly no http://i-tronics.blogspot.com/ CHAPTER 4 The PIC16F84 Microcontroller In this chapter we introduce the PIC16F84 MCU, which we will use as our baseline exemplar for the rest of the text. Here we will primarily look at internal structure, reserving external interfacing considerations for Part 3 of the book. After reading this chapter you should: • Recognize the di?erence between a microprocessor and microcon• • • • • • • for ot N troller. Understand the Harvard-based architecture with its parallel fetch and execute units. Appreciate the function, structure and memory map of the unrelated Program and Data stores. Be able to interpret the Status register bits that control memory paging and hold the C, DC and Z ?ags. Know how to manipulate the contents of the Program Counter in conjunction with the PCLATH special-purpose ?le register. Understand the interaction between the clock phases and the internal sequence of micro-operations. Appreciates the principle of banking in the Data store and its relationship to the RP0 control bit in the Status register. Know what peripheral functions are integral to the PIC16F84. me co al, rci ef us edu or tio ca nly no What exactly is a microcontroller unit? In a nutshell, a microcontroller is a MicroProcessor Unit (MPU) which is integrated with memory and input/output peripheral interface functions on the (usually) one integrated circuit. In essence it is a MPU with on-board system support circuitry. Thus we begin by investigating the origins of the MPU. From a historical perspective the story begins in 1968 when Robert Noyce (one of the inventors of the integrated circuit), Gordon Moore1 and Andrew Grove left the Fairchild Corporation and founded their own company, which they called Intel.2 Within three years, Intel had developed all the basic types of semiconductor memories used today – dynamic and static RAMs and EPROMs. law stated in 1964 that the number of elements on a chip would double every 18 months, although this was subsequently revised to 2 years. 2 Reputed to stand for INTELligence or INTegrated ELectronics. 1 Moore’s http://i-tronics.blogspot.com/ 78 The Quintessential PIC Microcontroller for ot N As a sideline Intel also designed large-scale integrated circuits to customers’ speci?cations. In 1970 they were approached by the Nippon Calculating Machine Corporation, and asked to manufacture a suitable chip set for a line of calculators to be named Busicom. At that time calculators were a fast-evolving product and any LSI devices were likely to be superseded within a few years. This of course would reduce an LSI product’s pro?tability and increase its cost. Engineer Ted Ho? – reputedly while on a topless beach in Tahiti – came up with a revolutionary way to tackle this project. Why not make a simple computer central computing unit (CPU) on silicon? This could then be programmed to implement the calculator functions, and as time progressed these could be enhanced by developing this software. Besides giving the chip a longer and more pro?table life, Intel were in the business of making memories – and computer-like architectures need lots of memory. Truly a brain wave. The Japanese company endorsed the Intel design for its simplicity and ?exibility in late 1969, rather than the conventional implementation. Federico Faggin joined Intel in spring 19703 and by the end of the year had produced working samples of the ?rst chip set. This could only be sold to the Nippon Calculating Machine Corporation, but by the middle of 1971, in return for a price reduction, Intel were given the right to sell the chip set to anyone for non-calculator purposes. Intel was dubious about the market for this device, but went ahead and advertised the 4004 “Micro-Programmable Computer on a Chip” in the Electronic News of November 1971. The term microprocessor unit was not coined until 1972. The 4004 created a lot of interest as a means of introducing ‘intelligence’ into electronic products. The 4004 MPU featured a von Neumann architecture using a four-bit data bus, with direct addressing of 512 bytes of memory. Clocked at 108 kHz, it was implemented with a transistor count of 2300.4 Within a year the eight-bit 200 kHz 8008 appeared, addressing 16 Kbytes and needing a 3500 transistor implementation. Four bits is satisfactory for the BCD digits used in calculators but eight bits is more appropriate for intelligent data terminals (like cash registers) which need to handle a wide range of alphanumeric characters. The 8008 was replaced by the 80805 in 1974, and then the slightly modi?ed 8085 in 1976. The 8085 is still the current Intel eight-bit device. Strangely, 4-bit MPUs were to outsell all other sizes until the early 1990s. The MPU concept was such a hit that many other electronic manufactures clambered on to the bandwagon. In addition, many designers jumped ship and set up shop on their own, such as Zilog. By 1976 there me co al, rci ef us edu or tio ca nly no was later to found Zilog (last word (Z) in Integrated LOGic) which became notable with the Z80 MPU – a rather superior Intel 8085. 4 Compare with the Pentium Pro (also known as the P6 or 80686) at around 5.5 million! 5 Designed by Masatoshi Shima, who went on to design the 8080-compatible Z80 for Zilog. 3 He http://i-tronics.blogspot.com/ 4. The PIC16F84 Microcontroller 79 were 54 di?erent MPUs either available or announced. For example, one of the most successful families was based on the 6800 introduced by Motorola.6 The Motorola 6800 had a clean and ?exible architecture, could be clocked at 2 MHz and address up to 64 Kbyte of memory. The 6802 (1977) even had 128 bytes of on-board memory and an internal clock oscillator. By 1979 the improved 6809 represented the last in the line of these eight-bit devices, competing mainly with the Intel 8085, Zilog Z80 and MOS Technology’s 6502. The MPU was not really devised to power conventional computers, but a small calculator company called MITS,7 faced with bankruptcy, took a ?nal desperate gamble in 1975 and decided to make and market a computer. This primitive machine, designed by Ed Roberts, was based on the 8080 MPU and interacted with the operator using front panel toggle switches and lamps – no keyboard and VDU. The Altair8 was advertised for $500, and within a month MITS had $250,000 in the bank for advance orders. This ?rst Personal Computer (PC) spawned a generation of computer hackers. Thus an unknown 19-year-old Harvard computer science student, Bill Gates, and a visiting friend, Paul Allen, in December 1975 noticed a picture of the Altair9 on the front cover of Popular Electronics and decided to write software for this primordial PC. They called Ed Robert with a blu?, telling him that they had just about ?nished a version of the BASIC programming language that would run on the Altair. Thus was the Microsoft Corporation born. for ot N In a parallel development, 22 Altair owners in San Francisco set up the Home-brew club. Two members were Steve Jobs and Steve Wozniak. As a club demonstration, they built a PC which they called the Apple.10 By 1978 the Apple II made $700,000; in 1979 sales were $7 million, and then $48 million… The Apple II was based around the low-cost 6502 MPU which was produced by a company called MOS Technology. It was designed by Chuck Peddle, who was also responsible for the 6800 MPU, and had subsequently left Motorola. The 6502 bore an uncanny resemblance to the Motorola 6800 family and indeed Motorola sued to prevent the related 6501 MPU being sold, as it even had the same pinout as the 6800. The 6502 was one of the main players in PC hardware by the end of the 1970s, being hence the name “motor” and “ola” – as in pianola. It has the largest share of the world-wide microcontroller market at the time of writing (1999). 7 Located next door to a massage parlor in New Mexico. 8 After a planet in Star Trek. 9 The picture was just a mock up, they actually were not yet available; an early example of computer ‘vaporware’! 10 Jobs was a fruitarian and had previously worked in an apple orchard. 6 Motorola was launched in the 1930s to manufacture motor car radios, me co al, rci ef us edu or tio ca nly no http://i-tronics.blogspot.com/ 80 The Quintessential PIC Microcontroller for ot N the computing engine of the BBC series and Commodore PETs amongst many others. What really powered up Apple II sales was the VisiCalc spreadsheet package. When the business community discovered that the PC was not just a toy, but could do ‘real’ tasks, sales took o?. The same thing happened to the IBM PC. Reluctantly introduced by IBM in 1981, the PC was powered by an Intel 8088 MPU clocked at 4.77 MHz together with 128 Kbyte of RAM, a twin 360 Kbyte disk drive and a monochrome textonly VDU. The operating system was Microsoft’s PC/MS-DOS version 1.0. The spreadsheet package here was Lotus 1-2-3. By the end of the 1970s the technology of silicon VLSI fabrication had progressed to the stage that several tens of thousands transistors could be integrated on the one chip. Microprocessor designers were quick to exploit this capability in one of two ways. The better known of these was to increase the size of the ALU and buses/memory capacity. Intel were the ?rst with the 29,000-transistor 8086, introduced in 1978 as a 16-bit version of the 8085 MPU.11 It was designed to be compatible with its eight-bit predecessor in both hardware and software aspects. This was wise commercially, in order to keep the 8085’s extensive customer base from looking at competitor products, but technically dubious. It was such previous experience that led IBM to use the 8088 version, which had a reduced eight-bit data bus and 20-bit address bus12 to save board space. In 1979 Motorola brought out its 16-bit o?ering called the 68000 and its eight-bit data bus version, the 68008 MPU. However, internally it was 32-bit, and this has provided compatibility right up to the 68060 introduced in 1995 and ColdFire RISC device launched in 1997. With a much smaller eight-bit customer base to worry about, the 68000 MPU was an entirely new design and technically much in advance of its 80X86 rivals. The 68000 was adopted by Apple for its Macintosh series of PCs. However, the Apple Mac only accounts for less than 5% of PC sales. Motorola MPUs have been much more successful in the embedded microprocessor market, the area of smart instrumentation from egg timers to aircraft management systems. Of course, this is just the area which MPUs were developed for in the ?rst place, and the number, if not the pro?le and value, of devices sold for this purpose exceeds those for computers by more than an order of magnitude. In this applications area an MPU is ‘buried’ in the application circuit together with memory and various input and output interface circuits. The MPU with its program acts as the controller of the system by virtue of the software in program memory. Over 3.5 billion microprocessor and me co al, rci ef us edu or tio ca nly no the Intel 8086 architecture-based MPUs are by far the largest selling MPU for computer-based circuitry. 12 A 220 address space is 1 Mbyte, and this is why for backwards compatibility MS-DOS was limited to 1 Mbyte of conventional memory. 11 and http://i-tronics.blogspot.com/ 4. The PIC16F84 Microcontroller 81 related devices are sold each year for embedded control, making up over 90% of the MPU market. The second way of using the additional integrated circuit complexity that became available by the end of the 1970s was to keep a relatively simple CPU and use the extra silicon ‘real estate’ to implement on-board memory and input/output interface. In doing so, simple embedded control systems on the one chip became possible and the overall chip count to implement a given function was thereby considerably reduced. The majority of control tasks require relatively little computing power, but the reduction in size (and therefore cost) is vital. A simple example of this is the intelligent smart card, which has a processor integrated into the card itself. Such microprocessor-based devices were called MicroController Units (MCUs).13 For example there are about 100 microcontrollers hidden in every home; in the washing machine, microwave oven, telephones, electronic games and so on. About 20 more lurk in the average family car.14 Microcontroller G5 MPU Gear box G4 G3 G2 for ot N Reset trip mi/km me co G1 al, rci Counter SRG49 ef us Output ports edu or D tio ca nly no Tacho pulse SRG28 D Fig. 4.1 An example of a system based on a microcontroller. term microcomputer was an alternative term but was easily confused with early personal computers and has dropped into disuse. 14 New Scientist, vol. 59, no. 2141, 4th July 1998, pp. 139. 13 The http://i-tronics.blogspot.com/ Input ports Odometer Trip program memory Data memory Non-volatile store 82 The Quintessential PIC Microcontroller for ot N • • • • • • In terms of architecture, referring back to Figs. 3.1 and 3.2 on pages 42 and 44 respectively, the microprocessor is the central processor unit, whereas the microcontroller is the complete functioning computer-like system. As an example, consider the electronics of a car odometer monitoring system displaying total distance since manufacture and also a trip odometer. The main system input signal is a tachometer generating pulses on each rotation of the engine ?ywheel, which when totalized gives the number of engine revolutions – and the pulse to pulse duration could also give the road speed. Of course the actual road distance depends on the gearing of the engine, and thus we need to know which of the ?ve gear ratios has been chosen by the driver at any time. This is shown as ?ve lines G1…G5 originating from the gear box. One signal will be high for the appropriate forward gear, with neutral and reverse being ignored. Additional inputs are used to give a manufacturer’s option of a mile or kilometer display, and a user input to reset the trip display to zero. The display itself consists of seven 7-segment digits (see Fig. 6.6 on page 148) to indicate up to (optimistically) . . As there are so many segments to control (49 in total), Fig. 4.1 shows the display data fed via a single digital line, shunted serially into a shift register – see Fig. 2.20 on page 36. A second line provides clock pulses for the register with 49 clock pulses being needed to refresh the display.15 The trip odometer display comprises four digits, which will record up to . . Similarly two output lines are used to feed and clock the shift register, and 28 clock pulses are needed to shift in a new 4-digit trip display. The resource budget (list of subsystem functions) for this system is: • An edge-triggered input for the tachometer pulse train, connected to a me co al, rci ef us edu or tio ca nly no counter/timer to totalize engine revolutions. Seven static digital input lines to interface to the gear ratio, mi/km option and trip reset. Four output digital lines to clock the two shift registers and provide segment data. A microprocessor to do the calculations and to read/write to the input/ output ports respectively. Program memory, usually ROM of some kind. Data memory for temporary storage of program variables, usually static RAM. Non-volatile storage for physical variables, such as total distance and distance since trip reset. This functionality could be implemented onto a single integrated circuit, and in this situation would be known as a microcontroller, that is a mi15 Many displays have this shift register built in as a complete subsystem. http://i-tronics.blogspot.com/ 4. The PIC16F84 Microcontroller 83 croprocessor integrated with its support circuitry giving a complete microcomputer function. Of course the resource budget listed above is speci?c to our example. Although the core functions (microprocessor and memory) are common to a wide range of applications, the input/output (I/O) interface needs to be tailored to the task in hand. Some typical I/O functions are: • I/O to interface to a serial bit stream of various synchronous and asyn• Counter/timer functions to totalize input events and to generate precision time-varying digital output signals. • Analog to digital multiplex/conversion to be able to read and digitize analog inputs. • Digital to analog conversion to output analog signals. • Display ports to drive multi-digit liquid crystal displays. chronous protocols. for ot N This alternative approach to using additional silicon resources led to the ?rst MCUs in the late 1970s. For example the 35,000 transistor Motorola 6801, designed in response to a speci?c application from an car manufacturer, used the existing 6800 MPU as a core, with 2048 bytes of ROM program memory, 128 bytes of data RAM, 29 I/O lines and a 16bit timer. With the viability of the MCU approach vindicated, a range of families, each based on a speci?c core but with individual family members having a di?erent selection of I/O facilities, was introduced by the leading MPU manufacturers. For example, the Motorola 68HC11 family (a development of the 6801 MCU) uses a slightly enhanced 6800 core. The 68HC12 and 68HC16 families use 16-bit cores but are designed to be upwardly compatible with the 8-bit 68HC11. It was quickly realised that many embedded applications did not even need the power of the (antique) 6800 core, and the 68HC05 family16 had a severely reduced core by lower price. Actually 4-bit MCUs outsold all other kinds of processor until the early 1990s and 8-bit MCUs, now the most popular, are likely to continue in this role for the foreseeable future. All these MPUs and MCUs were based on the von Neumann architecture (see Fig. 3.1 on page 42) used by mainframe computers. The alternative Harvard architecture (see Fig. 3.2 on page 44), which is chie?y distinguished by having a separate memory space for program and data, originated at Harvard university for a US Defence department computing project, but was rejected in favor of a rival von Neumann design from Princeton university. The ?rst MPU using this architecture was the Signetics 8X300, and this was adapted by General Instruments in the mid 1970s for use as a Peripheral Interface Controller (PIC) which was designed to be a programmable I/O port for their 16-bit CP1600 MPU. me co al, rci ef us edu or tio ca nly no 68HC05 has found a niche as the computing engine of smart cards, where highpower computing is not a priority. 16 The http://i-tronics.blogspot.com/ 84 The Quintessential PIC Microcontroller General Instruments sold o? their microelectronics division in 1988 to a start up company called Arizona Microchip Technology. Microchip’s main product was, and is still, a series of microcontroller families based on this PIC architecture. Their ?rst family was introduced in 1989 with the PIC16C5X series. These Harvard processors are based on a set of only 33 instructions. All instructions are coded in a single 12-bit word. This use of a primordial instruction set is known as Reduced Instruction Set Computer (RISC) and contrasts with the Complex Instruction Set Computer (CISC) model used in most computers/MPUs where several hundred instructions/modes are provided, and because of their number take several memory words to encode. The combination of single-word instructions, the simpli?ed instruction decoder implicit with the RISC paradigm and the Harvard separate Program and Data buses gives a fast, e?cient and cost e?ective processor implementation. The PIC16C5XX 12-bit core family features between 512 and 2048-instruction Program stores implemented as One-Time Programmable (OTP) EEPROM (see page 26), 25 to 73 bytes of Data memory, 12 or 20 I/O pins in the 18- and 28-pin package respectively, and an 8-bit timer. The PIC12CXXX family are 8-pin equivalents. By 1992 the PIC16CXXX family family based on a 14-bit core enabled easier addressing of larger Program spaces and additional peripheral devices, such as 16-bit timers and A/D converters as well as interrupt handling. The RISC instruction set is virtually identical to the 12-bit core, with a total of 35 instructions. The 16-bit PIC17CXXX core, introduced in 1997, has 58 instruction, with a multiplying ALU and further interface capabilities. It is complemented by the extended 16-bit core PIC18CXXX family introduced in 1999 with 77 instructions more oriented towards high-level language compiler needs. Of the three families, the 14-bit core is a good compromise between low-cost and ease of use. The PIC16F84, which is the baseline exemplar of this book, is a member of this mid-range family. From the software point of view all devices with the same core are identical. However, there is a di?erent mix of I/O facilities from the hardware perspective, but with much commonalty. For example, the 16C74 supports an 8-channel analog input port, the PIC16C66 a synchronous serial port and the PIC16F84 a non-volatile data memory. All three devices have similar parallel I/O, timer and interrupt handling facilities. The architecture of the PIC16F84 is shown in a simpli?ed form in Fig. 4.2. Although initially this looks rather complex, it is little more than the architecture of our BASIC computer of Fig. 3.3 on page 45 but with interface ports connected to the internal File store data bus. You should revise this material now as background to our discussion. In essence the PIC family is based on a Harvard structure with its separate Program and Data store, and with peripheral interface ports mapped onto the Data ?le for ot N me co al, rci ef us edu or tio ca nly no http://i-tronics.blogspot.com/ 4. The PIC16F84 Microcontroller 85 Vdd 14 Program store Flash ROM 1K x 14 Program data bus 14 13 Vss 5 Program address bus PIC16F84 F 02h EEPROM data memory F 08h EEPROM data File data bus 8 8 Program Counter PLATH F 0Ah Pipeline Instruction reg 1 Instruction reg 2 8-level stack RAM Register file 68 x 8 Data store EEPROM data memory 64 x 8 F 09h EEPROM address 8 File address bus Address mux 7 Direct address 8 Indirect address F 04h Timer File select reg. 8 Literal data op-code 7 8 8 File value Timer counter Prescaler Data mux MCLR 4 Instruction decoder & control Q1 Q2 Q3 Q4 Working reg. 8 8 OSC1 16 ALU 8 SLEEP RP0 Z DC C Status register d bit from instruction F 03h I/O port A OSC2 15 Oscillator and timing generation 0 1 F 0Bh Power-up timer Oscillator start-up Power-on Reset Watchdog timer Int control for ot N me co ial rc se ,u F 86h TRISB F 06h Port B for RB5 RB6 RB7 13 12 11 duc e TRISA F 85h tio a F 05h RA4/TOCKI 3 RA3 2 nly no 1 F 01h F 81h RA2 RA1 18 Port A RA0 17 I/O port B RB0/INT RB1 RB2 RB3 RB4 10 7 8 9 Fig. 4.2 Architecture of the PIC16F84 microcontroller store address space. That is the various ports appear to the software to be in the Data store. In more detail we have: Central Processor Unit As a consequence of the Harvard architecture, the CPU is split between the fetch and execution function, both of which operate in parallel with a minimum of interaction. Fetch The fetch section comprises a 13-bit Program Counter (PC) addressing the Program store via the Program address bus, and a two-deep Instruction pipeline through which 14-bit instructions via the Program data bus progress through to the Instruction decoder – see Fig. 3.3 on page 45. The Program Counter is actually located in the Data ?le store at location File 2 and is labelled as PCL (Program Counter Low byte) in Fig. 4.6. http://i-tronics.blogspot.com/ 6 86 The Quintessential PIC Microcontroller This means that it can be accessed and manipulated by the software in the same manner as any other ?le register. For example, if the contents of the Working register were n, then the instruction addwf 2,f (see page 49) overwrites File 2 (i.e. the PC) with its original value plus n – that is skip forward n places. A practical example is given in Program 6.4 on page 149. There is one problem with this example, which arises because the PC is actually 13-bits wide and File 2 only holds the lower eight bits, PC[7…0]. The upper ?ve bits, PC[12…8] are held in a ‘buried’ register; that is not directly accessible to the programmer. Actually any instruction that directly writes to File 2, such as our example above, does change all 13 PC bits as shown in Fig. 4.3. Not only will the 8-bit outcome of the instruction addwf 2,f be placed in the lower byte of the PC but the lower ?ve bits of the PC bu?er register at File 0Ah, labelled PCLATH (for Program Counter LATch High byte) in Fig. 4.3, are automatically copied into the high byte of the Program Counter. The PCLATH ?le data register is cleared when the PIC is reset and so an instruction like our example will usually result in an address in the ?rst 256-byte ‘page’ of program memory unless PLATH is loaded with a non-zero value. Thus care needs to be taken when altering the state of the PC by writing to PCL in this manner; especially if the outcome over?ows its 8-bit ?eld. Instructions that indirectly alter the value of the PC, such as goto, will also use part of the contents of PCLATH in updating the PC. Such instructions carry an 11-bit address as part of the instruction code. Here bits PCLATH[4:3] are moved over to the corresponding PC bits 12 & 11 to give a complete 13-bit PC update – see Fig. 5.4 on page 114. for ot N Associated with the Program Counter is an area of buried storage that can stack up to eight copies of the PC. The current value of the PC is pushed into this stack when a subroutine is called or an interrupt is serviced. Conversely a return from a subroutine or interrupt causes the PCL 12 87 0 me co al, rci ef us edu or tio ca nly no Program Counter File 02h Outcome from ALU. For example, movwf PCL or addwf PCL,f PCLATH 7 4 0 File 0Ah Fig. 4.3 Showing how all 13 bits of the Program Counter are altered when writing to PCL. http://i-tronics.blogspot.com/ 4. The PIC16F84 Microcontroller 87 last stacked PC value to be popped out again into the PC. Details are given in Chapters 6 and 7. The PIC microcontrollers have an integral oscillator that generates the internal timing sequences. The oscillator frequency fosc is normally controlled by an external crystal (or ceramic)-capacitor network across the device OSC1 and OSC2 pins – see Fig. 10.4 on page 258. A resistorcapacitor connected to OSC1 may be used as the timing elements where lower precision and frequency stability is not an issue. In this case 1 OSC2/CLKOUT outputs a signal of frequency 4 × fosc. Alternatively an external oscillator can be used as the master clock into OSC1/CLKIN. The PIC16F84 has a maximum frequency fOSC of 10 MHz but there is no minimum. As we shall see (Fig. 10.2 on page 256) the lower the frequency the smaller is the power consumption. Unless otherwise stated, we will assume a fosc of 4 MHz for the rest of the text. The internal oscillator/clock circuitry must be con?gured to the appropriate mode, as described in Fig. 10.5 on page 261. This is normally done when code is blasted into the Program store ?ash EEPROM. When the PIC is powered up (external supply voltage is applied) a 72 ms internal reset pulse is generated by the Power-up timer after the supply rises above approximately 2 volts, followed by 1024 clock pulses, counted by the Oscillator Start-Up timer to ensure that the internal oscillator has stabilised. This latter guard timer only operates for crystal-type oscillator modes – see Table 86 on page 258. The Power-Up timer does not operate if an external reset is applied to the Master CLeaR (MCLR) pin. for ot N me co al, rci f osc Q1 Q2 Q3 Q4 ef us edu or tio ca nly no Program stream Execute stream Fetch inst. n Fetch inst. n+1 Fetch inst. n+2 Fetch inst. n+3 Execute inst. n Execute inst. n+1 Execute inst. n+2 Cycle n Cycle n+1 Cycle n+2 Time Cycle n+3 Fig. 4.4 Internal clock sequencing waveforms. http://i-tronics.blogspot.com/ 88 The Quintessential PIC Microcontroller The clock input/crystal frequency at the OSC1 pin is divided by four to generate four internal non-overlapping quadrature clocks, as shown in Fig. 4.4. The clock-related sequence of operations in the fetch unit are: Q1: Increment the Program Counter and copy onto the Program store address bus. Q4: Read the instruction code o? the Program store data bus into Instruction register 1 and at the same time move the previous instruction down the pipeline into Instruction register 2, where it is presented to the Instruction decoder. Execute The execution circuitry is centered around the Arithmetic Logic Unit (ALU) – see Fig. 2.19 on page 35. The ALU processes data from up to two sources. One of these is the 8-bit Working register. The other can be multiplexed either from a ?le in the Data store or an 8-bit literal, which is part of the instruction code – see page 107. For example addwf 20h,w and addlw 5 respectively add the contents of W to that of File 20h or the constant 5 to W. The outcome can be switched back into W (eg. addwf 20h,w) or into the register ?le (eg. addwf 20h,f) as controlled by the single Destination bit in the instruction code – see page 107. Where an operand is a ?le, the execution unit can generate the Data store address in one of two ways – see Fig. 4.6. • Directly via a 7-bit address ?eld in the instruction – see page 107. Seven for ot N bits can only directly address up to 128 ?les. This can be increased to 256 ?les if the state of the RP0 (Register Page bit 0) bit in the Status register (see Fig. 4.5) is also multiplexed in as part of the Data store address. Where RP0 is zero, then register ?les 00 – 7Fh can be addressed, this address page being known as Bank 0. With RP0 set to one, then Bank 1 is addressed, ranging from 80 – FFh; see Fig. 4.6. RP0 is cleared when the PIC is reset and the Bit Set File and Bit Clear File instructions may be used alter its state. For example, bsf 3,5 sets bit 5 (RP0) in the Status register –see Fig. 4.5. • Indirectly using the File Select Register in conjunction with Indirect addressing, as described in Fig. 3.6 on page 57. In this situation the 8-bit address in the FSR is used to address the Data store whenever the virtual location File 0 is addressed. Here potentially all 256 ?les in both banks can be addressed irrespective of the state of RP0. me co al, rci ef us edu or tio ca nly no The three ?ag bits in the Status register STATUS are associated with the ALU, giving status information concerning the outcome from an instruction, as shown in Fig. 4.5. Carry ?ag Bit 0 of the Status register is the C ?ag. This primarily holds the Carry out from the last addition operation. Subtraction operations activate this bit as the complement of the Borrow out. For example, 24 - 12 = 12B1 and http://i-tronics.blogspot.com/ 4. The PIC16F84 Microcontroller 89 12 - 24 = 88B0. C also functions as an input/output bit for the Rotate instructions, as shown in Fig. 3.7 on page 61. The label R/W ? in Fig. 4.5 indicates that this bit can be read from or written to and has an indeterminate value on a power-up reset – its value does not alter on any other type of reset. Digit Carry ?ag Bit 1 of the Status register is the DC ?ag. This operates in the same manner as the standard C ?ag but holds the Carry out from the lower nybble to the upper nybble; that is from bit 3 to bit 4. In the same manner DC holds the complement of the Borrow out from bit 3 to bit 4. Knowledge of the Carry activity between the lower and upper halves of the byte is useful where binary coded decimal data is being manipulated. Here each nybble holds a 4-bit representation of the decimal digits 0…9 (see page 6) and the half carry then indicates carries between decimal decades. Zero ?ag Bit 2 of the Status register is the Z ?ag. This is set whenever the outcome of the instruction is zero, otherwise it is cleared. tf No co or Register File Bank Select Bank 0 (File 00 - 7Fh) 0 Bank 1 (File 80 - FFh) 1 erc m (R/W 0) (R/W 0) (R/W 0) al, i 7 Status register (SR ) File 6 5 4 3 2 1 RP0 TO PD (R 1) ef us (R 1) edu or 3 tio ca nly no Z DC C 0 (R/W ?) (R/W ?) (R/W ?) Carry/Borrow Digit Carry/Borrow Zero Time-Out Watchdog time-out 0 clrwdt/sleep instructions 1 Power Down By sleep instruction 0 By clrwdt instruction 1 Fig. 4.5 The PIC16F84 Status register Unlike most MCUs, there are no instructions to speci?cally clear or set a ?ag, such as sec for SEt Carry.17 However, as the Status register is accessible as a ?le in the Data store, then any instruction that can alter the contents of a ?le can potentially change the state of a ?ag. There is a potential problem in that many of these instructions a?ect one or 17 For example the Motorola 6800/5/11 families. http://i-tronics.blogspot.com/ 90 The Quintessential PIC Microcontroller more ?ags (see Table 3.1 on page 53) as part of their execution logic and this overrides any change that would result from the outcome of the instruction’s execution. For example, clrf 3 actually sets the Z ?ag to 1. The Bit Clear File and Bit Set File instructions are recommended where an individual bit in the Status register needs to be altered, as these instructions do not inherently a?ect these ?ags. For instance, bsf 3,0 (Set Bit 0 in File 3) is equivalent to sec and bcf 3,2 (Clear Bit 2 in File 3) is equivalent to clz. STATUS also holds the RP0 bank switching bit. The TO and PD readonly bits shown in Fig. 4.5 give information on what type of reset last occurred (Power-Up when power was applied to the device, Watchdog when the Watchdog timer timed out or External by bringing the MCLR pin low) or if awakened from the sleep instruction. As these are designated as read-only, they cannot be altered as part of the software, only monitored. These status bits will be discussed in Part 3 of the book. In the normal Harvard manner, the execution unit is separated from the fetch unit, with distinct data bus, address bus and stores. It is of course controlled via the Instruction decoder which is fed from the bottom of the pipeline in the fetch unit. The fetch Program Counter is in the Data store’s address space so the execution unit can e?ect the fetch sequence by altering the Program Counter, as shown in Program 6.4 on page 149. The execute unit is also sequenced by the same four clock phases as the fetch unit operating in parallel. Q1: Q2: Q3: Q4: Decode instruction. Read from Data store. Process data in ALU. Write into Data store. for ot N me co al, rci ef us edu or tio ca nly no Program store The majority of PIC devices use EPROM for program memory. As EPROM can only be erased using UV radiation (see Fig. 2.11 on page 27) once the software has been programmed into the Program store it can be considered e?ectively permanently in situ. Such devices are known as One-Time Programmable (OTP). Where it is likely that program code will need to be subsequently altered, the MCU may be housed in a ceramic package with a quartz window, allowing for erasure in around 20 minutes. An alternative approach is to implement the Program store using EEPROM technology – see page 28. This allows the ‘?xed’ data to be erased electrically without the expense of a UV transparent package and the time delay inherent with this technology. Using this approach, code can even be reprogrammed in the ?eld, to subsequently upgrade software, without the device having to be removed from the circuit board. Thus, say, a modem’s algorithm or a PC’s BIOS can be upgraded over a computer network by the user. Microchip’s strategy is to substantially increase the http://i-tronics.blogspot.com/ 4. The PIC16F84 Microcontroller 91 number of EEPROM devices but at the time of writing (2000) most devices are EPROM based. The 16F84 holds its program code in an internal ?ash EEPROM (see page 28) memory18 holding 1024 (210 ) instructions, each of 14-bits width. This memory is accessed from the fetch unit via the 14-bit Program data bus into the pipelined Instruction register 1, and is addressed via the Program address bus by the lower ten bits of the Program Counter PC[9…0]. The address range is 000…3FFh. As the Program Counter is 13 bits wide, other members of the 14-bit core family can potentially interact with a 213 = 8 kbyte-instruction Program store; for example, the PIC16F876/7 – see Fig. 15.4 on page 440. The structure of 14-bit PIC instructions are discussed in Chapter 5. All members of the mid-range PIC family use address 000h as the Reset vector (the place the PIC goes to when it is reset, for the startup of the program) and 004h for the Interrupt vector – the place the PIC goes to whenever it gets an interrupt request. Data store The Data store comprises 81 8-bit locations known as ?le registers or just ?les for short. The contents of any location in the Data store may be moved into or out of the Working register. The PIC16F84’s ?le registers are located in the Data store’s memory map as shown in Fig. 4.6. The registers can be categorised as Special-Purpose Registers (SPRs) used by the core CPU and peripheral modules for status information and controlling the desired operation of the device. The remaining implemented General-Purpose Registers (GPR) can be used by the programmer for temporary storage of program variables. There are two ways an instruction can target a datum in the Data store. Each ?le register has an address, which is listed in Fig. 4.6. For example PORTA is located at File 05. for ot N me co al, rci ef us edu or tio ca nly no Directly Any instruction which can process a datum in the Data store can directly specify the e?ective address using seven binary bits which are part of the binary program code, the details of which are given on page 107. By itself this can address a base range of 00–7Fh. However, we see from Fig. 4.6 that this address is augmented by the RP0 bit19 in the Status register to give an e?ective 8-bit address. If RP0 is 0 (as it is after reset) the range is 00–7Fh, that is Bank 0. If RP0 is made 1 then the range is 80–FFh; that is 18 The older PIC16C84 uses normal EEPROM but otherwise has the same Program store architecture. However, the Data store is rather smaller. 19 Actually the Data store model for the mid-range PICs is based around four 128-byte banks with STATUS[6:5] holding two bank select bits RP1:RP0 (see Fig 5.1 on page 109) to give an e?ective maximum capacity of 29 = 512 register ?les. Devices such as the PIC16F87X lines implement the complete model. The 8-bit ?le address for File Indirect memory access is augmented by bit STATUS[7], known as IRP (Indirect Register Page). This gives two 256-byte Indirect pages. http://i-tronics.blogspot.com/ 92 The Quintessential PIC Microcontroller Direct addressing d0 d6 RP0 File address 00h 01h 02h 03h 04h 05h 06h 07h 08h 09h 0Ah 0Bh 0Ch File address 80h 81h 82h 83h 84h 85h 86h 87h 88h 89h 8Ah 8Bh 8Ch IND IND TMR0 PCL STATUS FSR PORTA PORTB Unimplemented OPTION PCL STATUS FSR TRISA TRISB Unimplemented EEDATA PCLATH tf No om rc o File 4 erc ial INTCON Images of the 68 68 General Purpose General Purpose register files register files us , EEADR for e EECON1 EECON2 PCLATH INTCON edu tio ca nly no 4Fh 50h Unimplemented Unimplemented CFh D0h Access File 0 (IND) 7Fh FFh Indirect addressing File Select Register d0 d7 Fig. 4.6 Data store memory map. http://i-tronics.blogspot.com/ 4. The PIC16F84 Microcontroller 93 Bank 1. For example, to set the contents of File register TRISB (File 86h) to all 1s and then to read the contents of the File register PORTB into the Working register, we need the following program: PORTB equ 06 ; Register file in Bank 0 TRISB equ 86h ; Register file in Bank 1 STATUS equ 03 ; Status register RP0 equ 5 ; RP0 is bit 5 in STATUS ; --------------------------------------------bsf STATUS,RP0; Set RP0 to 1 -- select Bank 1 movlw 0FFh ; Bit pattern 11111111b movwf TRISB ; Sent to TRISB bcf STATUS,RP0; Select Bank 0 movf PORTB,w ; Read the state of PORTB Indirectly If the Indirect address mode is used, as was described in Fig. 3.6 on pageref3:?g-Indirect, then the 8-bit address in the File Select Register (FSR) is used as the e?ective. As we have an 8-bit address in this situation any location in the two banks are accessible with not bank switching required. The same example as described above is then implemented as: PORTB equ 06 ; Register file in Bank 0 TRISB equ 86h ; Register file in Bank 1 STATUS equ 03 ; Status register RP0 equ 5 ; RP0 is bit 5 in STATUS ; --------------------------------------------movlw TRISB ; Set up the pointer to locate TRISB movwf FSR movlw 0FFh ; Bit pattern 11111111b movwf INDF ; Sent to TRISB bcf STATUS,RP0; Select Bank 0 movf PORTB,w ; Read the state of PORTB movlw PORTB ; Set up the pointer to locate Port B movwf FSR movf PORTB,w ; Read the state of PORTB for ot N me co al, rci ef us edu or tio ca nly no Although there is no Bank switching required, this code segment is actually longer than the previous solution! However, Indirect addressing is useful when one location in Bank 1 requires frequent access. The bottom 12 locations of both banks are reserved for SPRs. Although the exact location can vary across members of the mid-range family, common registers; for example, PCL and PORTA tend to have the same location. For instance, see Appendix B. Of these, we have already met most of those involved with the core function: INDF The INDirect File at File 0 is not physically implemented as a register. Instructions accessing this virtual location actually put the contents of the FSR onto the Data store address bus, as described in Fig. 3.6 on page 57. http://i-tronics.blogspot.com/ 94 The Quintessential PIC Microcontroller PCL The Program Counter Low byte is addressed as File 2. Its relationship with the total 13-bit PC is described on Fig. 4.3. STATUS The Status register can be accessed in File 3. As can be seen from Fig. 4.5, this ?le holds the three code condition bits plus several status bits and the Data store page bit RP0. FSR The File Select Register at File 4 holds the indirect address used when the instruction refers to the virtual INDF address. PCLATH File 0Ah holds the LATch High byte for the Program Counter, as described in Fig. 4.3. INTCON The INTerrupt CONtrol register at File 0Bh holds the mask and status bits controlling the response of the MCU to interrupts. Its operation is described in Chapter 7. Most devices have interrupt-related bits in other registers – for example see Fig. 14.10 on page 408. All these core SPRs are images in both memory banks. The remaining nine SPRs relate to the con?guration and control of the various peripheral interface devices. More details will be given on individual peripheral SPRs in Part 3 of the book in the appropriate chapters. The 68 GPRs are located from File 0Ch through File 4Fh and are mirrored in Bank 1.20 Thus the instruction clrf 4Fh and clrf 0Cfh are identical and target the same physical location irrespective of the state of the Register Page bit RP0 setting. The remaining ?le locations are not implemented and read as 00h, as does location File 07h/File 87h – which is reserved for PORTC and TRISC in devices with 28+ pins. for ot N me co al, rci ef us edu or tio ca nly no Peripheral functions Each member of the PIC family has its unique set of integrated peripheral devices. However, all PICs have parallel input/output and timer facilities. As well as these standard facilities, the PIC16F84 has a peripheral 64byte EEPROM which can be used as a small data store not dependent on continuous power to retain its contents; i.e. non-volatile. Each of these peripheral facilities are described in detail in Part 3 of the book, but for completeness are brie?y cataloged here together with their associated SPRs. These registers are used to con?gure the function of their target peripheral interface, to control and monitor their status. Parallel input/output The ability to externally alter or monitor several digital lines at the same time is a virtually universal facility on microprocessor-based systems. GPR mirroring is not as a rule a feature of the more sophisticated members of the family. 20 This http://i-tronics.blogspot.com/ 4. The PIC16F84 Microcontroller 95 Apart from the 8-pin PIC12XXX series, all PICs have a minimum of 12 such external input/output lines. Some have much more, such as the 40-pin PIC16C74 which has 33 I/O lines. The PIC16F84 has 13 I/O lines, divided up into two ports. Port A has ?ve I/O lines mapped into the Data store address space at File 5. The remaining eight lines are allocated to Port B at File 6. These ports can be thought of as a ‘window’ into the Data store in that data written to File 5 or File 6 appear to the outside world on the corresponding pins; pins RA4…RA0 and RB7…RB0 respectively – see Fig. 10.1 on page 254. However, the electrical and logic behavior of these ports is more complex than that of a purely internal register ?le. This will be discussed in Chapter 11 but as an example a port bit must be con?gurable as either an output (so that the CPU can control the state of the associated pin) or an input (so that the CPU can read the state of this pin). To do this, each Port register has an associated Data Direction register, which Microchip call TRISA and TRISB, which map to File 85h and File 86h respectively (the term TRIS stands for TRIState – see Fig. 11.2 on page 273. These registers lie in the less convenient Bank 1 as they are usually set up at the beginning of the program and never subsequently altered. As an example, consider that we wish to make Port B bits 6…0 an input and bit 7 an output. Then the setting up code would be: STATUS RP0 TRISB PORTB equ equ equ equ tf No co or bsf STATUS,RP0 movlw 7Fh movwf TRISB erc m 03 05 86h 06 al, i ; ; ; ; Status register is at File 03 Bank switch bit is 5 in STATUS Data Direction register at File 86h Port B itself is at File 06 ef us edu or tio ca nly no ; Bank 1 ; Binary pattern 0111111 ; makes RB7 output, RB6...RB0 input As an example, subsequently pin RB7 can be pulsed high and then low as follows: bsf nop nop bcf PORTB,7 PORTB,70 ; Pin RB7 high (set bit 7) ; Delay a short time ; by putting in a few NO Operations ; then low (clear bit 7 with the assumption that the CPU is still in Bank 0. The registers associated with parallel I/O are: PORTA, File 05h Only the lower ?ve bits are implemented in this register ?le, feeding through to pins RA4…RA0. Pin RA4 is shared with the Timer peripheral. The upper three bits read as zero. http://i-tronics.blogspot.com/ 96 The Quintessential PIC Microcontroller TRISA, File 85h This is used to bitwise con?gure Port A bits as input or output. Setting TRISA[n] to 1 sets bit PORTA[n] as an input and to 0 as an output. Any type of reset sets the TRIS bits to 1 and the associated port bits to input. PORTB, File 06h A bi-directional 8-bit port connected to pins RB7…RB0. Bit RB0 doubles as a hardware interrupt input. TRISB, File 86h This is used to bitwise con?gure Port B bits as input or output. Details are the same as TRISA. Timer Most MCUs have facilities to either measure elapsed time and/or to generate digital on/o? waveforms with well de?ned durations. This is normally based around one or more counters that are incremented either from an external pulse or internal clock. For instance, if an automatic packing machine needs to count cans of beans going along a conveyer belt, then a photoelectric-based transducer could act as the timer input. If a new packing carton needed to be in place every 24 cans then an internal 8-bit counter would be set to E8h (-24). When the counter over?ows from FFh to 00h then an interrupt (see Chapter 7) would be generated and the MCU then take the appropriate action. All PIC MCUs have at least a basic timer/counter known as Timer 0 (TMR0). The read/write TMR0 counter register at File 1 can be clocked from the outside world via the T0CKI (Timer 0 ClocK In) pin, which is shared with the RA4 Port A pin. Alternatively, the incrementing source can be the internal Q4 phase clock, which is one quarter of the crystal frequency. For example, for a 4 MHz crystal this is 1 MHz. Either clock source can be frequency divided by a buried 8-bit prescale counter. This divide ratio is controlled by the lower three PreScale bits of the OPTION_REG register at File 81h (see Fig. 13.2 on page 363), labelled PS2:PS1:PS0. The ratio is then 2PS+1 . For example, if PS[2 : 0] = 111 then f the counter will increment at 256 , where f is the clock source frequency. The prescaler can be disconnected by setting bit 3 of OPTION_REG to 1. This will give a direct connection between pulse source and counter. Writing to the Timer 0 register also zeros the Prescaler counter (for example movlw 0F8h, movwf 1) enabling the time period to begin from true zero time. When this PSA (Pre-Scale Assignment) bit is 1 the prescaler becomes a postscaler to the Watchdog timer – see Fig. 13.1 on page 362. The Watchdog timer is designed to reset the MCU unless periodically preset by the user’s program with the instruction clrwdt (CLeaR WatchDog Timer). This ensures that the PIC will eventually reset if due to an electrical disturbance or a software bug, the processor malfunctions, perhaps for ot N me co al, rci ef us edu or tio ca nly no http://i-tronics.blogspot.com/ 4. The PIC16F84 Microcontroller 97 by jumping into an unprogrammed part of the Program store. This will disrupt the periodic preset. If the prescaler is assigned to the Timer then the Watchdog timer will periodically time-out (count down through zero) after approximately 18 ms.21 With PSA set to 1 then 2PS 18 ms Watchdog time-outs are required before the processor is reset. Thus, with PS[2 : 0] = 111, 27 = 128 time-outs gives a period to MCU reset of nominally 2.3 s. Thus the software must use the clrwdt instruction before this period elapses to prevent reset. This instruction also clears the Prescale counter. If it does time-out, then the TO bit in the Status register will be cleared. If desired the Watchdog timer may be disabled at the same time as code is programmed into the Program store. Various con?guration bits (known as fuses) are located by the ?ash EEPROM programmer in location File 2007h (see Fig. 10.5 on page 261), which is not accessible during the normal run mode. Such details are normally hidden to the operator by the EEPROM programmer’s operative software. Registers relating to Timer 0 are: TMR0, File 1 Sometimes known as the Real-Time Clock/Counter (RTCC), is an 8-bit upcounter register that keeps tally of clock events. It may be preset to any byte value by moving data from W and read at any time. When it over?ows from FFh to 00h it sets the T0IF (Timer 0 Interrupt Flag) in the INTCON (INterrupT CONtrol) register – see Fig. 7.4 on page 178. This may be used to generate an interrupt. OPTION_REG, File 81h Six bits in this register in Bank 1 at File 81h are used in conjunction with the timer – see Fig. 13.2 at page 363. for ot N • PS2, PS1, PS0 at bits 2,1,0 respectively control the prescale ratio 2PS-1 for the timer or postscale ratio 2PS for the Watchdog timer. • T0SE (Timer 0 Set Edge) at bit 4 allows the programmer to select which edge of a pulse at the T0CKI pin will increment the counter; a 0 for / and 1 for \ . • T0CS (Timer 0 Clock Select) at bit 5 allows the programmer to select the clock source as either the internal clock (= 0) or a transition at the T0CKI pin. me co al, rci ef us edu or tio ca nly no The remaining two bits con?gure external interrupt edge select and electrical properties of Port B inputs. Data EEPROM The PIC16F84 has a block of 64 bytes of data that does not require power to retain its contents. This non-volatile memory is not part of the (volatile) Data store and is accessed through SPRs as a peripheral device. Any byte can be addressed and then read from or written to via the nominal due to process variations, 7 – 33 ms, and in addition is rather dependent on supply voltage and temperature. 21 Time-out is very http://i-tronics.blogspot.com/ 98 The Quintessential PIC Microcontroller EEDATA register as addressed by the EEADR register and controlled by the EECON1 and EECON2 control ?le registers. Data EEPROM has a minimum endurance of 1,000,000 writes and such data is retained for upwards of 40 years. Some typical uses of a non-volatile depository would be to hold the number of pages printed in a laser printer or total miles/kilometers travelled in a car. Details of the Read and Write protocols are given in Chapter 15, but are brie?y reviewed here for completeness. Read 1. Put address (00 – 3Fh) into EEADR. 2. Set RD (bit 0 of EECON1) to 1 to set to the ReaD mode. 3. Read the addressed contents in EEDATA. Write 1. Put address into EEADR. 2. Put data into EEDATA. 4. Put code 55h into EECON2. 5. Put code AAh into EECON2. 3. Set WREN (bit 2 of EECON1) to 1 to WRite ENable. 6. Begin the Write cycle by setting WR (bit 1 of EECON1) to 1. Writing, which is normally an infrequent act, is deliberately made circuitous to protect against accidental changes to the EEPROM. The register EECON2 does not actually exist, but the interlock writing 55h followed directly by AAh to File 89h is a necessary part of unlocking the target byte. Interrupts can disrupt this sequence and should be inhibited if used. Writing takes around 50 ms to complete, and sets the EEIF (EEPROM Interrupt Flag) bit 4 of EECON1 after this time, and this can be used to interrupt the processor. The WRERR (WRite ERRor) bit 3 of EECON1 is set if a Write cycle is prematurely terminated, say, by an External reset. Registers associated with the Data EEPROM are: EEDATA, File 08h This contains the addressed data after a Read action and holds data to be written into the addressed byte during a Write action. EEADR, File 09h The 6-bit address of the target byte is placed here before a Read or Write cycle. EECON1, File 88h This holds the control and status bits that: • Trigger an EEPROM Read. • Enable a Write action. for ot N me co al, rci ef us edu or tio ca nly no http://i-tronics.blogspot.com/ 4. The PIC16F84 Microcontroller 99 Details are given in Fig. 15.2 on page 434. • Trigger an EEPROM Write. • Signals a premature end to a Write cycle. • Signals a Write cycle has been completed. EECON2, File 89h The EEPROM CONtrol 2 is not a physical register and reads as zero. This address is used as the target for the Write cycle unlocking sequence which is implemented by moving 55h followed directly by AAh into this virtual location. Examples Example 4.1 Discuss how the performance of the PIC architecture is improved by incorporating pipelining into the design of the instruction-fetch unit. Do you forsee any problems associated with handling Jump instructions (such as goto) in connection with the pipeline structure? Solution for ot N The pipeline is a precondition for the parallel operation of the fetch and execution units. That is, in order to allow the execution of instruction n whilst the next instruction n + 1 is being fetched from the Instruction store, internal storage must be provided to present the instruction code to the Instruction decoder. As all instructions are the same size, that is 14 bits, then the pipeline register structure and control is considerably simpli?ed. Most conventional CISC processors have instructions that vary considerably in length. For example the 68HC11 MCU core has instructions that cover the range one through four bytes; that is the fetch phase can take between one and four bus transactions. Some more sophisticated processors have multi-stage pipelines with each stage feeding part of the execution circuitry. Thus several streams of execution activity can occur simultaneously. The problem with pipelines is that they presuppose that the program instructions will be executed sequentially as they are stored in memory. However, instructions that disrupt this smooth running and move on the Program Counter require that the pipeline be emptied so that the instruction code of the destination travels down to the end of the pipe. For example, if instruction k is goto n, then instruction k + 1 will be in the ?rst stage of the pipeline by the time the processor knows that the next step is actually to be instruction n. Thus a null instruction cycle needs to be executed which simply brings this instruction code into the pipeline but does not execute instruction k+1 whose code is at the end of me co al, rci ef us edu or tio ca nly no http://i-tronics.blogspot.com/ 100 The Quintessential PIC Microcontroller the pipeline. This is sometimes known as ?ushing the pipeline. Instructions such as goto need two clock cycles to execute. Conditional Skip instructions, such as incfsz and btfsc take two cycles when the skip is implemented and one otherwise. All other instructions always take one cycle. Example 4.2 Can you determine why after a subtraction, or addition of a negative number (eg. addlw -6), the setting of the C ?ag is the complement of the borrow-out. Hint: Look at 2’s complement arithmetic on page 9. Solution The solution lies in the method of subtraction by 2’s complementing the subtrahend. The subtract instructions convert the subtrahend to their 2’s complement form and then con?gure the ALU to add. After the addition there can be two outcomes, depending on the relative magnitude of the minuend and subtrahend. 1. Where the subtrahend is greater than the minuend then the outcome is negative and there is no carry-out. An example of this situation is: 06 - 0A 00000110 + 11110110 = (0) 11111100 or - 4 (no carry). 2. Where the subtrahend is less than the minuend then the outcome is positive and there is a carry-out. An example of this situation is: 0A - 06 00001010 + 11111010 = (1) 00000100 or + 4 (carry). for ot N In both cases the Carry ?ag acts as an inverted borrow. This is in keeping with the RISC philosophy of the PIC family, to keep the processor ‘lean and mean’. In any case this non inversion means that subtraction can be implemented by adding negative data, eg. addlw -6. This is translated by the assembler to addlw 0FCh, where FCh is of course the 2’s complement of 6. me co al, rci ef us edu or tio ca nly no Example 4.3 Write a program to increment a packed BCD quantity located in Data memory at File 20h. Solution Two Binary-Coded Decimal (BCD) digits may be packed into a single byte to represent numbers up to 99. For example 0100 1001 File 20h represents BCD 49. Incrementing a number stored in this hybrid decimalbinary form using the normal binary addition rules may give an incorrect result. For example 01001001 + 1 (49 + 1) gives 01001010 (4Ah) after addition, but should give 01010000 (50h). Similarly, 10011001 + 1 (99 + 1) gives 10011010 (9Ah) instead of 00000000 Carry 1 (1 00h). http://i-tronics.blogspot.com/ 4. The PIC16F84 Microcontroller 101 From these examples it can be seen that whenever any of the BCD decades equals ten after incrementation then it should be zeroed and one added to any higher decade. Based on this increment and add algorithm we can formulate the task list. 1. Increment the packed BCD byte using normal binary arithmetic. 2. IF the lower nybble of the outcome is ten then add six to the outcome. 3. IF the upper nybble of the outcome is ten then add six to it. for ot N Program 4.1 Incrementing a packed BCD byte. ;************************************************************** ;* FUNCTION: Increments a BCD datum giving a BCD outcome * ;* ENTRY : BCD in F20h * ;* EXIT : BCD+1 in F20h * ;* EXAMPLE : 10011000 (98) + 1 = 10011001 (99) * ;* ************************************************************ ; STATUS equ 3 ; The Status register C equ 0 ; Carry flag is bit 0 DC equ 1 ; Digit Carry flag is bit 1 BCD equ 20h ; The BCD number is in File 20h ; ---------------------------------------------------------BCD_INC incf BCD,w ; Binary inc BCD number and put in W addlw 6 ; Add six btfss STATUS,DC ; Needed IF produced a half carry addlw -6 ; ELSE not needed ; Now check the upper digit by adding 6 to it and checking Carry addlw 60h ; Add 60h (ie six to upper digit) btfss STATUS,C ; Needed IF caused a Carry addlw -60h ; ELSE cancel the correction factor ; The incremented and corrected BCD number is now in W movwf BCD ; Put it out in memory END ..... ..... me co al, rci ef us edu or tio ca nly no Program 4.1 gives an e?cient implementation of this task list. After incrementing using normal binary rules, six is added to the previous outcome and the DC ?ag checked for activity. This ?ag will only be set when the original nybble was ten (0Ah + 6 = 1 0h). In this case the add six operation is allowed to stand as the necessary correction otherwise it is cancelled by subtraction. The upper nybble (BCD digit) is checked and corrected in the same manner, but this time it is the full Carry ?ag that is tested. If this is set, then the addition of 60h is allowed to stand, otherwise it is subtracted. This Carry ?ag could be used to set a hundreds digit if desired, to show over?ow from 99 to 100. An alternative approach would be to subtract nine before incrementation and if the Z ?ag is set then leave the digit at zero and increment the higher digit; otherwise add ten. Repeat for the upper digit. http://i-tronics.blogspot.com/ 102 The Quintessential PIC Microcontroller Write a routine that will add two packed BCD numbers at File 20h and File 21h. The outcome is to be in File 22h for the hundred’s digit and File 23h for the tens and unit digits. Solution Example 4.4 As in the case of Example 4.3 the binary addition of numbers that are already in BCD form may need correction afterwards. Again, a correction will be needed where the digit outcome is greater than nine. The situation is more complex in this case as the sum of two digits can be anywhere between zero and 19 (9 + 9 + 1(carry-in) = 19). The illegal range 10 to 19 may be determined by applying the criterion: • Check for the range Ah to Fh (10 to 15) — for example, 3 + 9 = Ch (3 + 9 = 12). • Otherwise check if there was a carry out to the next decade — for example, 9 + 9 = 1 2h (9 + 9 = 18). In both cases the digit may be corrected by adding six to ‘jump over’ the six illegal BCD states. Based on this course a possible task list is: 1. Add the two packed BCD bytes using normal binary arithmetic. 2. IF the addition results in a full Carry THEN Hundreds = 1 3. IF the addition results in a half Digit Carry OR IF the unit BCD nybble is greater than nine THEN add six to the outcome. for ot N 4. IF the last correction (if any) resulted in a full Carry OR IF the tens BCD nybble is greater than nine THEN add six to the upper nybble of the outcome. Program 4.2 directly implements this strategy. The full Carry ?ag is tested three times. 1. Directly after the addition – for example, 99h + 99h = 1 32h. 2. After the ?rst correction where six is added to the lower digit – for example, 77h + 88h = FFh; FFh + 06h = 1 05h. 3. After the second correction where six is added to the upper digit – for example, 70h + 80h = F0h; F0h + 60h = 1 40h. me co al, rci ef us edu or tio ca nly no If the ?ag is set at any point then the hundreds digit will be one; the maximum value in this case is 99 + 99 = 198. A nybble is tested for over nine by subtracting ten. If a carry (half or full depending on which digit is being tested) is not generated then the original nybble must have been ten or greater. I have actually implemented the subtract ten operation by adding -10; that is addlw -10. This is because the sublw instruction actually takes the value in the Working register away from the literal and not the other way around – see also page 55. http://i-tronics.blogspot.com/ 4. The PIC16F84 Microcontroller 103 Program 4.2 Adding two packed BCD numbers. ;********************************************************************* ;* FUNCTION: Adds two packed BCD datums giving a BCD outcome * ;* ENTRY : BCD_1 in F20h, BCD_2 in F21h * ;* EXIT : SUM_H (hundreds digit) in F22h * ;* EXIT : SUM_L (tens:units digit) in F23h * ;* EXAMPLE : 10011001 (99) + 10011001 (99) = 00000001 10011000 (198) * ;* ******************************************************************* ; BCD_1 equ 20h ; The first tens:units BCD number BCD_2 equ 21h ; The second tens:units BCD number SUM_H equ 22h ; The hundreds digit of the outcome SUM_L equ 23h ; The tens:units digits of the outcome STATUS equ 03h ; The Status register C equ 0 ; holding the Carry flag at bit0 DC equ 1 ; and the Digit half Carry at bit1 ; Task 1: Add the two numbers using natural binary rules BCD_ADD clrf movf addwf movwf SUM_H BCD_1,w BCD_2,w SUM_L ; ; ; ; Zero the hundreds digit Get the first packed BCD number Add the second number and put away as the uncorrected result ; Task 2: Was there a full Carry from this binary addition? rlf SUM_H,f ; Rotate Carry into hundreds digit ; Task 3: Was there a Digit half Carry from the binary addition? btfsc STATUS,DC ; IF DC=0 THEN skip goto ADJUST_1 ; ELSE an adjustment is needed ; or if not, is the unit BCD digit greater than nine? addlw -0Ah ; Take away ten btfss STATUS,DC ; Did this give a Digit carry? goto TENS_CHECK ; IF it did THEN not >9 ; ------------------------------------------------------------------ADJUST_1 movlw 6 ; Correct the units digit by adding six addwf SUM_L,f ; with the adjusted value back in the file btfsc STATUS,C ; IF this gives a full Carry incf SUM_H,f ; THEN record a hundreds digit ; ------------------------------------------------------------------; Task 4: Was there a full Carry from the previous correction (if any)? TENS_CHECK btfsc SUM_H,0 ; IF yes THEN hundreds digit will be 01h goto ADJUST_2 ; and the tens digit will need adjustment ; or IF not, is the tens BCD digit >9? movf SUM_L,w ; Get the current partly corrected sum addlw -0A0h ; Take away ten from the tens digit btfss STATUS,C ; Did this give a Carry? goto FINISH ; IF it did THEN not >9 ; ------------------------------------------------------------------ADJUST_2 movlw 60h ; Correct by adding 6 to the tens digit addwf SUM_L,f ; with the adjusted value back in the file btfsc STATUS,C ; IF this generates a Carry incf SUM_H,f ; THEN record a hundreds digit ; ------------------------------------------------------------------FINISH .... ..... for ot N me co al, rci ef us edu or tio ca nly no http://i-tronics.blogspot.com/ 104 The Quintessential PIC Microcontroller Self-assessment questions 4.1 The PIC16F877 mid-range MCU has a 8 kbyte Program store, which can hold up to 8192 14-bit instructions located in the range 0000 – 1FFFh. As part of a certain program, execution has to be transferred from the bottom quarter of this map to 1000h. Given that the goto instruction can only directly access 11-bit addresses (0000 – 07FFh), how could you engineer a jump to this address, i.e. goto 1000h? 4.2 Write a routine to decrement a packed BCD quantity, as in Example 4.3. Hint: Devise a simple test to activate the relevant carry ?ag if the digit is Fh. 4.3 Write a routine to add ten onto a packed BCD byte located in File 20h. Hint: This is similar to Example 4.3 but only the tens digit is augmented. 4.4 Where microprocessors are used in a general-purpose computing environment, the program is normally loaded into and run from read/write RAM memory. This means that the system can run a wordprocessor one minute and a spreadsheet program the next. Of course this means of operation is not applicable to embedded applications, where the program is stored in some variety of non-volatile read-only memory. Discuss why this is so and the virtues of ROM, EPROM and EEPROM implementations of non-volatile storage. for ot N 4.5 The following routine is designed to do nothing other than defer execution of the main routine by 1282 µs in a PIC MCU which is being clocked using a 4 MHz crystal. Taking into account pipelining, verify this ?gure. DELAY D_LOOP clrf incf decf decfsz goto .... 20h 20h 20h 20h D_LOOP ..... ; ; ; ; Clear count Increment and cancel by decrementation Decrement until zero me co al, rci ef us edu or tio ca nly no 4.6 Can you devise an algorithm and task list to subtract two packed BCD numbers located as in Example 4.4. The outcome packed byte is to be in File 23h and File 22h is to hold the over?ow carry – that is the negative indicator. This over?ow is to be zero if there was a full borrow out, otherwise one. For example 45h - 29h = (01)16h (that is 45 - 29 = +16) and 29h - 45h = (00)84h (29 - 45 = -84) where 84 is the ten’s complement of 16. http://i-tronics.blogspot.com/ CHAPTER 5 The Instruction Set for ot N • • • • If you like to think of writing a program as analogous to preparing an elaborate meal, then for any given cooking appliance, such as a microwave oven or electric stove (the hardware) there are a range of processes. These processes – for example, steaming, frying, boiling – are analogous to the instruction set which can be implemented by the CPU. The various ingredients that can be handled by a process are the instruction’s data. Such data may lie in an internal register or out in the Data store. There are several di?erent ways of specifying the e?ective address (ea) of an operand. These are known as address modes. In keeping with the PIC microcontrollers’ RISC-like philosophy, the mid-range core have a total of only 35 instructions. Each instruction code is contained in a 14-bit word which holds the instruction operation code, address or data and destination bit. We have covered most of these instructions and address modes when discussing our BASIC computer back in Chapter 3; now would be a good time to go over this material. As we will begin this chapter by examining PIC’s address modes and how they are incorporated into an instruction’s binary word, we will use BASIC’s instruction set listed in Table 3.1 on page 53 for our illustrative examples. The latter part of the chapter looks at the full instruction set in some detail. After reading this chapter you will: me co al, rci ef us edu or tio ca nly no • Know that an address mode is the way an instruction pin-points its data. Understand how Inherent, Literal, Register Direct, File Direct, File Indirect, Bit and Absolute address modes permit an instruction to target an operand for processing. Know that Movement instructions, copying data in-between the Working register and the Data store, are the most used of the instruction categories. Appreciate that the processor can directly implement the common arithmetic operations of Addition, Subtraction, Incrementation and Decrementation. Know that data in the Data store can be rotate-shifted through the C ?ag. http://i-tronics.blogspot.com/ 106 The Quintessential PIC Microcontroller • Understand how to use the four basic logic instructions to invert, set, clear, toggle, bit test and di?erentiate data. • Know how to compare or test data for di?erences and relative magnitude, and take appropriate action. • Understand how the program ?ow can be diverted, based on the state of any bit or a zero value in a Data ?le. • Recognize how the binary structure of the instruction word impacts on the usage of instructions. Virtually all instructions act on data; either outside in its Data or Program memory space, or inside in an internal CPU register. Thus the 14bit instruction code must include bits which inform the CPU’s instruction decoder where this data is being held. The exception to this are the few Inherent instructions, such as nop (No Operation) and return (RETURN from subroutine). Before looking at the instruction set we will discuss the various techniques used to specify the location of any operands. The general symbolic form of an instruction is: instruction mnemonic , for ot N where operand A is the source data or its location and operand B the destination. For example movf 20h,w (MOVe File) which copies data source out of File 20h to its destination in the Working register. 1 There are some variations on this structure. 2 2 -operand instructions are common. For example, addwf FILE,d adds the W register’s contents to the speci?ed ?le’s contents and deposits the result either in W or back in the ?le register itself. Thus addwf 20h,f means “add the contents of W to that of File 20h and put the outcome in File 20h” or in Register Transfer Language (rtl, see page 49) (f20) <- W + (f20). Of course this is not a true 3-operand instruction as the destination must be one of the two source locations; that is W or File 20h. A few instructions have only a destination speci?ed; for example, clrf 20h, and the inherent instructions have no explicit operands. Instructions can be classi?ed by their address mode. me co al, rci ef us edu or tio ca nly no Inherent 0000000 ??????? The instructions listed in Appendix A, clrwdt (CLeaR WatchDog Timer), retfie (RETurn From Interrupt and Enable), nop, return and sleep do not explicitly refer to operands in memory or in the Working register. At the binary code level, all these instructions are coded with the upper seven bits zero. For example, clrwdt has a machine code of 00000000000100b. http://i-tronics.blogspot.com/ THE ESSENCE OF THE PIC MICROCONTROLLER 107 Register Direct ?????? 0 ??????? The PIC series has only one CPU register that can be explicitly speci?ed by an instruction; the Working register. Where the destination is to be W then bit 7 of the instruction code is always 0. For example clrw is coded as 0000000000011b. Many instructions can either use W or the source ?le as the destination, and this is coded by setting bit 7 to 0 or 1 respectively. In Appendix A, bit 7 is marked as d for destination (see also File Direct addressing) for applicable instructions. Where W is one of the source operands, the instruction normally shows this as part of the mnemonic. Thus movwf f copies W to the speci?ed ?le register. Literal 11 ???? LLLLLLL Literal instructions use the lower eight instruction word bits to specify a source operand which is constant data rather than data in a register. For example addlw 06 is coded as 11111000000110b. The destination of this type of instruction is always the Working register, and this is shown in the mnemonic. Thus in our example, the sum W + 6 is copied back into W. In rtl this is expressed as W <- W + #6 where the # (pound or hash) symbol denotes that the following number is a constant or literal rather than a ?le address. for ot N File Direct 00 ???? d ???f Instructions that specify that their source or destination operand lies in a ?le register use this address mode. The value of the ?le address is coded into the lower seven bits; denoted as ???f. For instance the code for clrf 20h is 00 0001 1 0100000. Most instructions altering the contents of a ?le register can ‘dump’ the outcome either in the Working register or else back in the ?le. Bit 7 of the instruction code, labelled d, can specify the destination as in the following example: incf incf 20h,w 20h,f ; Coded as 00 1010 0 0100000 ; Coded as 00 1010 1 0100000 me co al, rci ef us edu or tio ca nly no In both cases the contents of File 20h (File 01000000b) are incremented. In the former instance, the outcome is put in W leaving the ?le contents unchanged (d = 0), whilst in the latter the original data is overwritten (d = 1). http://i-tronics.blogspot.com/ 108 The Quintessential PIC Microcontroller The main characteristic of this type of address mode is that the location of the operand is ?xed as an integral part of the program, and thus cannot be altered as the program progresses. In some cases, such as in Program 5.1, this technique is rather in?exible. As only seven bits of the instruction code are reserved for the ?le address, only ?les from 00 – 7Fh may be directly accessed using this technique. However, from Fig. 4.6 on page 92 we see that the PIC16F84’s Data store maps the register ?les in the range 00 – FFh, requiring an 8-bit address. The PIC16F84 gets round this by employing the RP0 bit in the Status register as a surrogate most-signi?cant address bit – see Fig. 4.5 on page 89. This Register Page control bit can be altered, like any other read/write ?le register bit, to switch back and forth between Bank 0 (RP0 = 0) and Bank 1 (RP0 = 1). The full 14-bit core CPU model has the capability of interacting with a 512-register ?le Data store. Devices with this size of Data store, such as the PIC16F87X line, have to deal with four banks of up to 128 register ?les. This requires a 9-bit address. Here the Status register, shown in Fig. 5.1, has two page select bits, RP1:RP0 which must be set up prior to using the File Direct address mode. For example, in such a Data store with a ?le address range 000 – 1FFh, in order to clear File 17Fh (File 10 111 1111b) we need to set RP1:RP0 to 10: bsf STATUS,6 bcf STATUS,5 clrf 17Fh for ot N Program 15.4 on page 442 is an example making use of this extended bank switching. File Indirect me co al, rci ; Make RP1 = 1 ; Make RP0 = 0 (Bank 2) ; Clear File 17Fh ef us edu or tio ca nly no 00 ???? d 0000000 Where data in the Data store is to be accessed, specifying its location directly as an address constant seems the obvious way to go; for example, clrf 20h. However, as we saw back in Program 3.1 on page 56, this may not always be the most e?cient approach. This is especially the case when an array of data, such as a sequential set of readings, is to be processed. Most MPU/MCU devices have one or more Address registers, sometimes known as Index registers. These are designed to hold the address in memory of the operand; that is they act as a pointer. Such processors use one or more Indexed or Indirect address modes which look to the appropriate pointer register to specify the operand location, rather than have the address as a ?xed part of the instruction code. The advantage of this indirect approach of addressing a data operand is that the address can easily be altered as the program progresses. Thus, for example, an http://i-tronics.blogspot.com/ THE ESSENCE OF THE PIC MICROCONTROLLER 109 X/Y 3 2 1 0 Bank 3 Bank 2 Bank 1 Bank 0 (File 180 - 1FFh) (File 100 - 17Fh) (File 080 - 0FFh) (File 000 - 07Fh) 1 0 7 Status register (SR ) File 3 Register File Bank Select decoder IRP RP1 RP0 TO PD (R/W 0) (R/W 0) (R/W 0) (R 1) 6 5 4 3 Z DC C 2 1 0 (R 1) (R/W ?) (R/W ?) (R/W ?) Indirect Register File Bank Select Bank 0/1 (File 000 - 0FFh) 0 Bank 2/3 (File 100 - 1FFh) 1 Time-Out Watchdog time-out 0 clrwdt/sleep instructions 1 Power Down By sleep instruction 0 By clrwdt instruction 1 Carry/Borrow Digit Carry/Borrow Zero Fig. 5.1 General 14-bit core Status register. virtual location F0 actually in st r re uct fe io re n nc d in ire g c th tly is sends this address F4 Pointer A ny Fig. 5.2 The indirect mechanism. http://i-tronics.blogspot.com/ ou t INDF FSR to th e Fi le for ot N array of data may be cleared by using an address register to point to the target location, and repeating in a loop while incrementing that pointer register. The PIC family does not have dedicated CPU Address/Index registers to perform this indirect holding function. Instead, the pointer address is that contained in the File Select Register (FSR), which is File 4 in the Data store, see Fig. 4.6 on page 92. To activate the indirect mechanism, the normal File Direct address mode is used, but with File 0 as the target me co al, rci ef us edu or tio ca nly no st or e 110 The Quintessential PIC Microcontroller location. File 0, the INDF (INDirect File) register, is a virtual location, that is it is not physically implemented. Its sole use is to trigger the use of the contents of the FSR as the operand address, as shown in Fig. 5.2. Thus the instruction clrf 0 will actually clear the ?le whose 8-bit address is that in File 4. Of course the contents of the Special-Purpose Register (SPR) FSR can be altered at any time, for example incremented on each pass through a loop. This is the approach taken in Program 3.2 on page 57, which clears an array of Data-store memory. Although this approach to indirect addressing may seem rather convoluted, it does not require additional clock cycles to execute, unlike the alternative techniques used by other MPU/MCUs. A more sophisticated example than that of Program 3.2 involves the sampling of temperature hourly over a daily period. With the assumption that the resulting array of 24 byte values are in situ in the Data store between File 30h and File 47h, we are required to scan through the array looking for the maximum temperature. By the end of the routine this is to be in File 48h. To implement this procedure we ?rst need a strategy or task list. One possibility would be: 1. 2. 3. 4. 5. 6. 7. Initialize Maximum as Temp[0]. IF Temp[1] > Maximum THEN Maximum = Temp[1]. IF Temp[2] > Maximum THEN Maximum = Temp[2]. IF Temp[3] > Maximum THEN Maximum = Temp[3]……. …etc. IF Temp[23] > Maximum THEN Maximum = Temp[23]. End. ot N for How can we code Temp[i] > Maximum? If we subtract Maximum from Temp[i], that is Temp[i] - Maximum, then if a borrow is not generated (C ?ag set) we know that the former is higher than the latter and Maximum needs updated. Based on this, a possible coding is given in Program 5.1. In this linear coding the comparison is implemented by ?rst bringing the current maximum into the Working register (movf MAXIMUM,w), then subtracting it from the appropriate direct address, eg. for Temp[2] or File 32h, subwf TEMP_0+2,w. This subtraction will set the C ?ag (that is N) if there is no borrow out, and in that situation the instruction btfss will skip to the update sequence. This simply copies down the appropriate temperature byte and copies it again up to the register ?le holding Maximum, eg. movf TEMP_0+2,w – movwf MAXIMUM. The process outlined here has to be coded 24 times, with some small saving in the initial setting of Maximum to Temp[0] and the fact that this value is already in W for the Temp[1] comparison. This gives a total of 139 instructions. Execution time depends a little on the number of times Maximum has to be updated. However, taking a worse-case scenario and remembering that goto takes two cycles to implement as does btfss me co al, rci ef us edu or tio ca nly no http://i-tronics.blogspot.com/ THE ESSENCE OF THE PIC MICROCONTROLLER 111 Program 5.1 Finding the maximum temperature the linear way. STATUS equ 3 ; Status register is File 3 TEMP_0 equ 30h ; Array starts @ File 30h MAXIMUM equ 48h ; Maximum value to be in File 48h NB equ 0 ; Carry/Not Borrow flag is bit0 ; Task1: Initialize Maximum as Temp[0] MAX_DAILY movf TEMP_0,w ; Get it movwf MAXIMUM ; and put it in as first maximum ; Task2: Check is Temp[1] > subwf TEMP_0+1,w btfss STATUS,NB goto TASK3 movf TEMP_0+1,w movwf MAXIMUM ; Task3: Check is Temp[2] > TASK3 movf MAXIMUM,w subwf TEMP_0+2,w btfss STATUS,NB goto TASK4 movf TEMP_2,w movwf MAXIMUM ; Task4: Check is Temp[3] > TASK4 movf MAXIMUM,w subwf TEMP_0+3,w btfss STATUS,NB goto TASK5 movf TEMP_0+3,w movwf MAXIMUM ; Task5 TASK5 Maximum? ; Temp[1] - Maximum ; IF no borrow (NB==1) THEN update ; Skip update ; Update by getting Temp[1] ; which is the new maximum Maximum? ; Get current maximum ; Temp[2] - Maximum ; IF no borrow (NB==1) THEN update ; Skip update ; Update by getting Temp[2] ; which is the new maximum Maximum? ; Get current maximum ; Temp[3] - Maximum ; IF no borrow (NB==1) THEN update ; Skip update ; Update by getting Temp[3] ; which is the new maximum for ot N me co al, rci ef us edu or tio ca nly no and so on ..... ...... is Temp[23] MAXIMUM,w TEMP_0+23,w STATUS,NB FINI TEMP_0+23,w MAXIMUM ...... > ; ; ; ; ; ; Maximum? Get current maximum Temp[23] - Maximum IF no borrow (NB==1) THEN update Skip update Update by getting Temp[23] which is the new maximum ; Task24: Check TASK24 movf subwf btfss goto movf movwf FINI ..... when a skip occurs, then this gives 188 clock cycles to execute; that is 188 µs for a 4 MHz crystal. Now Program 5.1 is rather a long program for a small task. This is because the complete sequence of compare-update instructions have to be implemented 23 times. Each sequence is identical, except the next ele- http://i-tronics.blogspot.com/ 112 The Quintessential PIC Microcontroller TEMP[i] - MAXIMUM skip No (TEMP[i]>=MAXIMUM) Borrow? NEXT btfss STATUS,NB goto NEXT {MAXIMUM=TEMP[i]} MAXIMUM = TEMP[i] Yes (TEMP[i] Maximum THEN Maximum = Temp[i]. (b) Increment i. (c) Repeat WHILE i < 24. 4. End. for ot N me co al, rci ef us edu or tio ca nly no The implementation of Program 5.2 uses the same compare-update sequence, but this time with the Indirect address mode to access the data byte Temp[i]. The contents of the File Select Register here holds the address of Temp[i] and is initialized in Task 2. After each loop pass, this pointer is incremented and then compared by subtraction from the ?rst address beyond the array; that is TEMP_0 + 24. If they are equal then the Z ?ag will be set and the goto LOOP instruction skipped over out of the loop. This Indirect mode coding takes 14 instructions; that is 10% of the linear version. However, it does take rather longer to execute, due to the overhead of incrementing the pointer1 and checking for range on each PIC 17CXXX and 18CXXX series have auto incrementing and decrementing versions of Indirect addressing and more than one Indirect pointer register. 1 The http://i-tronics.blogspot.com/ THE ESSENCE OF THE PIC MICROCONTROLLER 113 Program 5.2 Finding the maximum temperature using a loop structure. INDF equ 0 ; INDirect File register STATUS equ 3 ; Status register is File 3 FSR equ 4 ; File Status Register TEMP_0 equ 30h ; Array starts @ File 30h MAXIMUM equ 48h ; Maximum value to be in File 48h Z equ 2 ; Zero flag is bit2 of STATUS NB equ 0 ; Carry/Not Borrow flag is bit0 ; Task1: Clear maximum MAX_DAILY clrf MAXIMUM ; Task2: Point to Temp[0] movlw TEMP_0 movwf FSR ; Put address of first temp byte ; in the pointer register ; Task3: DO ; Task3A: IF Temp[i] > Maximum THEN Maximum = Temp[i] LOOP movf MAXIMUM,w ; Get current maximum temperature subwf INDF,w ; Temp[i] - Maximum btfss STATUS,NB ; IF no borrow (NB==1) THEN update goto NEXT ; Skip update movf INDF,w ; Update by getting Temp[i] movwf MAXIMUM ; which is the new maximum ; Task3B: Increment i NEXT incf FSR,f for ot N ; Task3C: REPEAT WHILE i < movf FSR,w sublw TEMP_0+18h btfss STATUS,Z goto LOOP ; Task4: END me co al, rci ; i++ 24 ; Get pointer address ; Take away end address (Temp[24]) ; IF equal THEN end ; ELSE repeat ef us edu or tio ca nly no loop pass. The worst-case run time is 291 µs against 188 µs, assuming a 4 MHz crystal. One advantage of the Indirect address mode is that the pointer address is eight bits wide. Thus it is not necessary to use the RP0 bit to switch between Bank 0 and Bank 1 of the Data store. The full 14-bit core model allows for four 128-byte banks of register ?les. The Status register of Fig. 5.1 shows the IRP (Indirect Register Page) bit which is used for family members with three or four register ?le banks. In such a device, if the temperature array of Program 5.2 were located in File 130h through File 147h then IRP would need to be set to 1 at the beginning of the routine (bsf STATUS,7) and cleared at the end. The rest of the code is unaltered. Microchip recommend that the IRP (and RP1) bits in http://i-tronics.blogspot.com/ 114 The Quintessential PIC Microcontroller the Status register are left in their zero reset state in family members, such as the PIC16F84, that do not have data storage above Bank 1. Bit 01 ?? nnn ???f Four instructions (as speci?ed by the two ?? bits above) either alter or test the state of a single bit within a register ?le. In this situation the instruction word has an embedded 3-bit code nnn de?ning the bit number from 0 through 7, as well as the ?le address coded in the normal way. Thus the instruction bcf 20h,7 (Bit Clear bit 7 in File 20h) is coded as 01 00 111 0100000. The other instructions are bsf (Bit Set in File, coded as 01), btfsc (Bit Test File and Skip if Clear, coded as 10) and btfss (Bit Test File and Skip if Set, coded as 11). Absolute 10 ? aaaaaaaaaaa Two instructions allow the program to jump to another instruction anywhere in the Program store. These are goto and call (CALL or goto a subroutine, see Chapter 6). The 14-bit core allocates eleven bits of the instruction word to this absolute instruction address2 in the Program store. Thus goto 400h would be coded as 10 1 10000000000. Similarly call 530h is 10 0 10100110000. ot N for me co al, rci 12 11 ef us edu or 0 tio ca nly no Program Counter aaaaaaaaaaa goto aaaaaaaa 7 4 3 0 PCLATH File 0Ah Fig. 5.4 Generating a 13-bit Program-store address for the goto and call instructions. This 11-bit address can directly locate any instruction in a Program store of up to 211 = 2 Kbyte capacity. However, the mid-range core has confuse this with the register ?le address in the Data store – in the Havard structure the two stores are logically distinct with di?erent address spaces. 2 Don’t http://i-tronics.blogspot.com/ THE ESSENCE OF THE PIC MICROCONTROLLER 115 a 13-bit Program Counter which can potentially address a Program store of up to 8 Kbyte instructions; for example the PIC16C74 has a 4 Kbyte store. To cope with this situation, when a goto or call instruction is executed, the absolute 11-bit address is transferred into the PC together with bits 3:4 of the PCLATH (Program Counter LATch High) to make up an e?ective 13-bit Program-store address. This process is shown in Fig. 5.4 – see also Fig. 4.3 on page 86. PCLATH is cleared on Reset, so the goto range is normally 000 – 7FFh. This covers all the address range for a 2 Kbyte store. For members with larger Program stores then a far goto and far call (i.e. beyond 7FFh) has to be implemented by twiddling bits PCLATH[4:3]. For example, in the PIC16C74 a goto 800h is coded as: bsf PCLATH,3 bcf PCLATH,4 goto 800h ; Make PCLATH(4:3) = 01 ; Go to it! So far we have classi?ed instructions by the method they pin-point their operands. The alternative approach is to catalog the instruction set by function. On this basis the 14-bit core PIC’s instruction set can conveniently be divided into six groups, of which four will be examined here. Those relevant to subroutines and interrupts are listed in the next two chapters, and control instructions pertaining to internal operation of the MCU hardware are left to Chapter 10. The complete instruction set is given for reference in Appendix A on page 475. for ot N Movement instructions Around one in three instructions move data around without alteration. With this in mind the instructions in Table 5.1 will be the most used in the repertoire. All three Move instructions can copy byte data to or from the Working register. Table 5.1: Move instructions. Operation Flags Mnemonic Z DC C k • v f,d f • f,d • Description me co al, rci ef us edu or tio ca nly no Move Literal to W movlw File movf W to ?le movwf Swap File swapf • • • • Copies a datum byte • [W] <- #kk • [d] <- [f] • [f] <- [W] Interchanges ?le nybbles • [d] <- [F(3:0)][F(7:4)] • W [] #kk Flag not a?ected Working register Contents of 8-bit constant v f d Flag operates in the normal way File register Destination, W or a ?le register http://i-tronics.blogspot.com/ 116 The Quintessential PIC Microcontroller • movlw copies the speci?ed 8-bit constant (or literal) to W. For example, movlw 80h initializes W to 10000000b. This instruction only a?ects the Working register and thus cannot be used directly to set up a ?le register to a constant value. • movwf is used to copy out or store the contents of W into a register ?le. For example, the following code fragment will initialize the contents of File 22h to 80h: movlw movwf 80h 22h ; Set contents of W to 80h ; and copy to File 22h ot N for or example, movf 22h,w loads W with the contents of File 22h. The destination of this instruction can also be the ?le itself, giving rise to seemingly useless instructions, such as movf 22h,f which copies the contents of File 22h back on top of itself! However, the process does activate the Z ?ag, which will be set if the ?le contents are zero, and of course this datum is not a?ected by the instruction. Thus movf FILE,f is equivalent to the missing tstf FILE instruction; that is TeST File for zero, that is commonly available in other MPU/MCUs. Thus the contents of any ?le register can be checked for zero by this means using a single instruction. An alternative technique needs to be used to test the contents of the Working register for zero. Given that most instructions acting on a ?le can specify either the same ?le or the Working register as the destination, then a Move operation can be considered an implicit part of such instructions. As an example, for some situations to increment the contents of a ?le and then move it to W could be coded either as: incf movf • movf can copy (or load) the contents of any register ?le into W. For me co 22h,f 22h,w 22h,w al, rci ef us edu or tio ca nly no ; Increment File 22h’s contents ; and copy it into W incf ; Copy the incremented File 22h’s contents to W Of course the latter does not actually change the state of the ?le. The ?nal instruction swapf swaps the top and bottom 4-bit nybbles in a ?le. Thus, for example, if File 22h was 1001 0111b then swapf 22h,f will yield 0111 1001b. If desired, the outcome destination could be speci?ed as W, eg. swapf 22h,w. As swapf does not a?ect any ?ag, this latter form can be used as a transparent replacement for movf 22h,w which does alter the Z ?ag. Of course it does interchange the two nybbles in the process. Program 7.2 on page 183 shows this swap instruction used in this role. Arithmetic The PIC processors implement the normal byte-sized binary Add and Subtract instructions, as discussed on page 47, to add or subtract register http://i-tronics.blogspot.com/ THE ESSENCE OF THE PIC MICROCONTROLLER 117 ?le contents to/from the Working register. In addition the W register may be added to or subtracted from an 8-bit constant. Table 5.2: Arithmetic. Operation Add Clear Literal to W W to File File W Bit File File Bit Flags Mnemonic Z DC C Description v addlw k v addwf f,d clrf clrw bcf decf incf bsf f v v • • • • • • v v v v v v Decrement Increment Set Subtract f,n • f,d f,d f,n • v W from literal sublw k v W from File subwf f,d #0 #00 #kk fn Single zero bit Zero byte 8-bit constant Bit n of ?le for ot N As an example that uses most of the instructions in Table 5.2 consider the problem of dividing the contents of File 24h by an 8-bit divisor in W. The simplest way of doing this is to continually subtract the divisor from the dividend, keeping a count until a borrow is generated. The residue left after this last subtraction is the remainder with one divisor subtraction to many. Thus adding the divisor once can restore the remainder if this is needed. A possible implementation based on this approach is given in Program 5.3. Here the quotient is cleared before entering the loop, using the clrf instruction. The loop itself simply increments the quotient using the incf instruction and then subtracts W (the divisor) from File 24h – subwf 24h,f. Both Subtract instructions generate a complement borrow out, which is represented by the C ?ag in the Status register – labelled NB for Not Borrow in the program. Thus the loop is exited when the Carry ?ag is clear after the subtract, which represents a borrow out. On leaving the loop, the contents of File 20h needs to be decremented, as the last subtract was one too many. Using the decf instruction allows this correction to be applied directly on the ?le register. me co al, rci #1 #01 n ef us v Binary addition v [W] <- [W] + #kk [d] <- [W] + [f] Zeroes destination byte or bit • [f] <- #00 • [W] <- #00 • [fn ] <- #0 Subtract one, produce no borrow • [f] <- [f] - #01 Add one, produce no carry • [f] <- [f] + #01 Sets any bit in a ?le to one • [fn ] <- #1 v Binary subtraction v [W] <- #kk - [W] [d] <- [f] - [W] Single one bit Byte 01h 3-bit bit speci?er 0 – 7 edu or tio ca nly no http://i-tronics.blogspot.com/ 118 The Quintessential PIC Microcontroller Program 5.3 Division by repetitive subtraction. STATUS equ 3 ; Status register is File 3 NB equ 0 ; Carry/Not Borrow flag is bit0 QUOTIENT equ 20h ; Quotient is held in File 20h REMAINDER equ 21h ; The remainder is put here DIVIDEND equ 24h ; The dividend is here at the start DIV LOOP clrf incf subwf btfsc goto decf addwf movwf ..... QUOTIENT QUOTIENT,f DIVIDEND,f STATUS,NB LOOP QUOTIENT,f DIVIDEND,w REMAINDER ...... ; Zero the loop count ; ; ; ; ; ; ; ; Record one loop pass DIVIDEND - DIVISOR IF a borrow (NB==0) THEN exit loop ELSE do another subtract/count Compensate for one inc too many Add divisor to residue which gives the remainder Next routine No for t The remainder can be determined from the residue left in the original dividend ?le. This represents one divisor subtracted too many. Thus, addwf DIVIDEND,w cancels this last action and this remainder outcome, now in W, is copied into File 21h. The addlw instruction can be used to add an 8-bit constant to W. Subtraction can also be carried out with this instruction by adding the 2’s complement of the literal subtrahend. For example. addlw F9h or addlw -7 will e?ectively subtract seven from the contents of W. Thus if [W] was 88h before this operation then the state of W after is 81h: 1000 1000 + 1111 1001 1000 0001 me co al, rci 81h ef us edu or tio ca nly no W = 88h -7 = F9h Rather confusingly this is not the same as sublw 7 as this subtracts W from 7, that is [W] <- 7-[W].3 Although the arithmetic instructions act on byte operands, operations on word sizes of greater than 8-bit precision are possible with the help of the Carry/Not-Borrow ?ag. The process for the addition of two n-byte objects is given by the task list: 1. For = 0 to n - 1 DO (a) Clear SUM. (b) SUM[i] = NUM1[i] + NUM2[i]. (c) IF Carry[i] = 1 THEN increment SUM[i+1]. (d) Increment i. 2. End. 3 This foible is a major cause of errors in programming, and you should think carefully before using this instruction. http://i-tronics.blogspot.com/ THE ESSENCE OF THE PIC MICROCONTROLLER 119 Example 3.2 on page 64 gives a practical implementation of this algorithm. Multiple-precision subtraction is carried out in a similar manner, using the Not-Borrow ?ag. Example 5.4 implements a 16-bit - 8-bit subtraction. Data in memory can be incremented or decremented apparently in situ, although in reality it is transferred from the Data store into a temporary register, incremented or decremented using the ALU and transferred back to the Data store – a type of read-modify-write action. However, it still takes only one bus cycle to implement. These instructions are especially useful in counting passes through a loop, as in Program 5.3 where QUOTIENT is located in the Data store at File 20h. However, incf is not quite the same as a addlf 1,20h type of instruction as it does not alter the state of the Carry ?ag. Thus if you wanted to increment a 32-bit number in Data memory at File 22:3:4:5h then this is how you would have to do it: QP_INC incf 22h,f ; Increment byte 1 btfss STATUS,Z ; IF not overflowed to zero goto NEXT ; THEN finished incf 23h,f ; Increment byte 2 btfss STATUS,Z ; again IF not overflowed to zero goto NEXT ; THEN finished incf 24h,f ; Increment byte 3 btfss STATUS,Z ; IF not overflowed to zero incf 25h,f ; increment byte 4 ..... ...... ; Next code fragment No for t NEXT This depends on the algorithm IF when byte n is incremented it wraps around from FFh to zero THEN increment byte n + 1. See Example 5.1 for a multiple-precision decrement routine. One of the more important operations is the comparison of the magnitude of the two numbers. Mathematically this can be done by subtracting the datum (designated [f] for either a register ?le or a literal) from the contents of the Working register [W]. The outcome gives the actual magnitude di?erence between the operands, but in most cases it is su?cient to determine the relative magnitude of the quantities – eg. is W higher than the datum? This is determined by checking the state of the C and Z ?ags in the Status register. Working register higher than datum . . . . . . . . . . . . . . . . No borrow, non-zero Working register equal to datum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Zero Working register lower than datum . . . . . . . . . . . . . . . . . . . . .Borrow, non-zero In terms of our processor, the C ?ag represents the complement of the borrow after subtraction and the Z ?ag is set on a zero outcome. This gives: me co al, rci ef us edu or tio ca nly no http://i-tronics.blogspot.com/ 120 The Quintessential PIC Microcontroller [W] Higher than or equal [f] : [W]-[f] gives no borrow; (C = 1). [W] Equal to [f] : [W]-[f] gives Zero; (Z = 1). [W] Lower than [f] : [W]-[f] gives a borrow; (C = 0). Consider as an example a fuel tank with a capacity of 255 liters, with a sensor at the bottom of the tank indicating the remaining volume of fuel as a linear function of pressure. Assume that the sensor represents the capacity as a byte that can be accessed at Port B (see page 95), which we give the name FUEL. We wish to write a routine that will light an ‘empty’ light (at bit 0 at Port A) if the capacity is below 20 liters and ring an alarm buzzer (bit 1 at Port A) if below 5 liters. Both output peripherals are active on logic 0. This is how it could be coded: STATUS C Z FUEL DISPLAY LAMP BUZZER ALARM equ equ equ equ equ equ equ 3 0 2 6 5 0 1 ; ; ; ; ; ; ; File 3 is the Status register Bit0 is the Carry flag and bit2 is the zero flag File 6 is Port B File 5 is Port A Bit0 of which is the warning lamp and bit1 is the buzzer movf addlw btfss bcf movf addlw btfss bcf FUEL,w -5 STATUS,C DISPLAY,BUZZER FUEL,w -14h STATUS,C DISPLAY,LAMP ..... ot N for NEXT: me co ..... al, rci ef us ; ; ; ; ; ; ; ; Read fuel gauge into W W-5 to compare. IF C==1 THEN no borrow & FUEL HIGHER OR SAME and sound buzzer Get fuel gauge again into W W-20 to compare. IF C==1 THEN no borrow & FUEL HIGHER OR SAME and light lamp edu or tio ca nly no ; Continue After each subtraction the Carry/borrow ?ag will be logic 1 (that is no borrow) if the datum in the Working register (the fuel reading) is higher or the same as the literal being subtracted – it is being compared with. The addlw -k instruction can be replaced by the more obvious sublw k.4 Remembering that this subtracts W from the constant, that is k - W, then the following Skip on Set (btfss) instructions must be replaced by Skip on Clear (btfsc) to give the same sense of magnitude. The contents of the Working register can be tested for zero in the same way, that is addlw 0 or sublw 0. If W were zero then the outcome of this tstw type of instruction will set the Z ?ag. We have already seen that the instruction movf xx,f can be used in the same way as a tst f instruction to test File xx for zero. Note the use of the bcf (Bit Clear in File) instruction to clear the appropriate bit in Port A, which we assume to Compare instruction of most MPU/MCUs is a subtract which sets the ?ags in the appropriate way, but which ‘throws away’ the di?erence outcome; that is does not overwrite the operand. A type of non-destructive subtract. 4 The http://i-tronics.blogspot.com/ THE ESSENCE OF THE PIC MICROCONTROLLER 121 be initially set to output. In the same manner the bsf instruction could be used to turn o? the lamp and buzzer at the beginning of the routine, as shown on page 125. Logic and Shifting instructions All four basic logic operations are provided, as shown in Table 5.3. The simplest of these is comf which inverts (or 1’s COMplements) all bits in a ?le register. For example: 10001110 File 22h comf22h,f 01110001 File 22h Alternatively the outcome can be placed in W with the original contents being unchanged; eg. comf 22h,w. There is no instruction comw to explicitly invert the contents of the Working register, but this can be accomplished in one bus cycle by subtracting from 11111111b; eg. sublw 0FFh: For example: 11111111 Literal 0FFh Working register - 10001110 1’s complement of W 01110001 Table 5.3: Logic instructions. Operation AND Complement tf No om rc o Inclusive-OR eXclusive-OR Rotate ?le shift v Literal to W andlw k v W to File andwf f,d File comf f,d erc al, i Flags Mnemonic Z DC C ef us • • • • • • • • • • • • • • • • b7 b0 edu or tio ca nly no Description Logic bitwise AND [W] <- [W] · #kk [d] <- [W] · [f] Invert or NOT (1’s complement) [d] <- [f] Logic bitwise inclusive-OR [W] <- [W] + #kk [d] <- [W] + [f] Logic bitwise exclusive-OR [W] <- [W] ? #kk [d] <- [W] ? [f] Circular shift into Carry v v Literal to W iorlw k v W to File iorwf f,d v Literal to W xorlw k v W to File xorwf f,d Left Right rlf rrf f,d • f,d • C 7 7 file 0 file 0 C · ? Boolean bitwise AND Boolean bitwise exclusive-OR + [f] Boolean bitwise inclusive-OR Bitwise inverse of the ?le contents The andwf instruction bitwise ANDs the Working register together with the contents of any ?le register, with the outcome being placed either in that same ?le or in W. Similarly the andlw instruction bitwise ANDs W with a byte literal. http://i-tronics.blogspot.com/ 122 The Quintessential PIC Microcontroller ANDing an input with a 0 always gives a 0 output, whilst with a 1 does not change the logic value. For example: 10001110 W andlw 0Fh 00001110 W which zeros the upper nybble of the Working register. ANDing is normally used to clear any bit or bits in the destination operand. Thus andlw b’00000011’5 clears the upper six bits in the Working register and leaves the lower two bits untouched. Of course, the bcf instruction can be used to clear a single bit in a ?le register. Another use of ANDing is to check the state of any bit or bits in a datum; for example: andlw btfsc goto b’11000000’ STATUS,Z ALL_ZERO ; Check bits 7 & 6 ; IF not both zero THEN skip ; ELSE == 00, so go to ALL_ZERO routine No for t By ANDing the Working register with 11000000b, the outcome will be all zero only if both bits 7 and 6 of W are 0. In this case the Z ?ag will be set and the following Bit Test File Skip on Clear will not be taken and the program will transfer to ALL_ZERO. If a single bit in a ?le register is being tested for zero then the btfsc instruction (see Table 5.4) is a more e?cient process. The iorwf and iorlw instructions implement the Inclusive-OR operation in the same way as for AND. ORing with a 0 leaves the source bit unchanged whereas ORing with a 1 sets the bit to a 1 irrespectively. Thus ORing is normally used to set any group of bits in the destination operand. For example: 10001110 me co W al, rci ef us W edu or tio ca nly no iorlw 03 10001111 sets the two least signi?cant bits to one. The xorwf and xorlw instructions provide for the eXclusive-OR operation. You will recall from page 14 that XORing with a 0 leaves a data bit unchanged, whilst XORing with a 1 inverts (or toggles) that bit. Thus, for example if we wished to invert both bits 0 and 7 of W: For example: 10001110 xorlw 81h W 00001111 W Another use for XOR is to isolate changes between two bit patterns. From the truth table on page 14 we see that only when the two inputs di?er is the output 1. Consider as an example a program routine that continually monitors Port B to which has been connected eight switches. This routine is waiting until someone moves a switch. 5 Notice the assembler notation used to represent numbers in binary, see page 223. http://i-tronics.blogspot.com/ THE ESSENCE OF THE PIC MICROCONTROLLER 123 START movf movwf PORTB,w 20h PORTB,w 20h,w STATUS,Z S_LOOP ; Get initial state of switches ; Put away at File 20h ; ; ; ; Sample switches Check for alterations Skip out if check gives non zero ELSE check again S_LOOP movf xorwf btfsc goto Two possible scenarios are: 10011110 10001110 W W xorwf 20h,w xorwf 20h,w 10011110 10011110 File 20h File 20h = = 00000000 00010000 W W Z=1 Z=0 for ot N The outcome in W re?ects any changes. In the ?rst case there are no di?erences between the latest sample and the original switch settings put away in File 20h. In the second situation Switch 4 has just been thrown from 1 to 0. You can determine which switch changed by shifting the outcome (the change byte) right, counting until the residue is zero. You can also determine the type of change (0 ? 1 or 1 ? 0) by ANDing the change byte to the original switch settings in File 20h, i.e. andwf 20h,w. If the outcome at bit 4 is a 0, then the change must have been 0 ? 1, and vice versa. The PIC 12/14-bit cores have two instructions which can shift a datum byte in a ?le register one place left or right. Both rlf and rrf are known as Circular or Rotate instructions. These shift left or right respectively with the incoming bit injected in from the Carry ?ag and outgoing bit popped out into the same C ?ag. This circular action is emphasized in Fig. 3.7 on page 61.6 One use of the shifting operation is to bitwise examine a datum. Suppose you want to determine the position of the leftmost logic 1 bit in File 20h, with this information being put in the Working register. For example, if the pattern is: me co al, rci ef us edu or tio ca nly no 00101111 File 20h 00000101 W (bit 5) This can be realised by continually shifting the pattern under investigation right, counting the number of times until the residue is zero. The coding given in Program 5.4 uses the Working register as a counter. The data byte in File 20h is successively shifted right and the count incremented. As the Carry ?ag is cleared each time before the shift, logic 0s are brought in from the left.7 Eventually the residue will become all zeros PIC17CXXX series use the mnemonics rlcf and rrcf for Rotate Left/Right through Carry. The change allows for rlnc and rrnc for Rotate Left/Right Not through Carry. 7 MPU/MCUs that have Logic Shift instructions always shift in 0s irrespective of the state of the C ?ag. 6 The http://i-tronics.blogspot.com/ 124 The Quintessential PIC Microcontroller and the process terminated. Thus 00010111 (1) 00000101 (3) 00000010 (4) 00000001 (5) 00001011 (2) 00000000. Program 5.4 Shifting to ?nd the highest set bit. ; Data is in File 20h, position of highest set bit to be in W HIGH_BIT clrw ; Zero the count ; WHILE data is HLOOP bcf rrf btfsc goto not zero, STATUS,C 20h,f STATUS,Z FINI shift right and increment count ; Carry flag cleared ; Shift rightmost bit into Carry ; IF not zero THEN continue ; ELSE exit ; Continue by adding one to count ; and do another shift FINI addlw 1 goto HLOOP ..... ...... for ot N Shifting right pops out the rightmost bit into the Carry ?ag. Replacing btfsc STATUS,Z by btfsc STATUS,C would determine the position of the rightmost bit. In many situations repetitively shifting into the Carry ?ag can be used to examine the data on a bit by bit basis. For instance, we could modify our program to totalize the number of set bits in the byte, as in Program 5.5. Program 5.4 did not distinguish between no bits set (00000000b) and bit 0 set (00000001b). How could you modify the program to do so? The Rotate instructions can be used for multiple-precision shifting operations. Remembering that a Rotate takes in the Carry bit and in turn saves its ejected bit in C, consider as an example a 24-bit word stored in the data store at 24 File 30h 16 15 File 31h 8 7 File 32h 0 which can be shifted right once by the sequence: me co al, rci ef us edu or tio ca nly no bcf STATUS,C ; Zero Carry rrf 30h,f rrf 31h,f rrf 32h,f ; ; ; b16/ C b8 / C 0 0 C C C C ? ? ? File 30h File 31h File 32h b16 b8 b0 Consider that we wish to count the number of bits set to 1 in this triple-byte datum. One solution is shown in Program 5.5. Here the 24-bit word is shifted right (it could equally well have been left) until the word is all zero with the state of the Carry ?ag controlling the incrementation of the Working register. The multiple-precision zero test is implemented http://i-tronics.blogspot.com/ THE ESSENCE OF THE PIC MICROCONTROLLER 125 Program 5.5 Triple-precision shifting to ?nd the number of set bits. COUNT_BIT clrw ; Zero the count ; WHILE data is not zero, shift right and increment counter BLOOP bcf STATUS,C ; Clear Carry flag rrf 30h,f ; Shift right all three bytes rrf 31h,f rrf 32h,f btfsc STATUS,C ; IF no carry then skip addlw 1 ; ELSE add one to count ; Now check for a triple-byte zero movf 32h,f ; Test rightmost byte btfss STATUS,Z ; IF zero THEN try middle byte goto BLOOP ; ELSE shift again movf 31h,f ; Test middle byte btfss STATUS,Z ; IF zero THEN try leftmost byte goto BLOOP ; ELSE shift again movf 30h,f ; Test leftmost byte btfss STATUS,Z ; IF zero THEN try middle byte goto BLOOP ; ELSE shift again EXIT ..... ...... ; Exit with the count in W by testing each byte in turn for zero and going back to the top of the loop if any byte test gives a non-zero outcome. Shifting can be used to multiply and divide data by powers of two. For example, to divide by eight shift left three times: 00011000 tf No co or 00000110 00001100 me File 20h File 20h File 20h al, rci (24) (12) (6) rrf 20h,f rrf 20h,f ef us edu or File 20h File 20h File 20h tio ca nly no 00001100 00000110 00000011 (12) (6) (3) ÷2 ÷4 ÷8 rrf 20h,f where we are assuming that the Carry ?ag is cleared before each shift. In general shifting n places right gives a 2n division and similarly to the left gives multiplication by the same factor – see page 11. As an example consider that the byte in File 22h (called MULTIPLICAND) is to be multiplied by 3 to give a 2-byte product in File 24:5h (PRODUCT_H and PRODUCT_L respectively). The implementation of Program 5.6 relies on factoring ×3 as ×2 + ×1. The former is implemented by shifting a 16-bit extension of the byte multipicand (upper byte zeroed) once left. The single byte multiplicand is then added to the 2-byte subproduct to give the desired outcome. Example 5.5 gives the more complex case of multiplying by ten. Program Counter instructions The instructions listed in Table 5.4 modify in some way the setting of the Program Counter. The most elementary of these is nop. No OPer- http://i-tronics.blogspot.com/ 126 The Quintessential PIC Microcontroller Program 5.6 Multiplying by three. 3 ; The Status register 0 ; Bit0 of which is the Carry bit 22h ; File 22h is the multiplicand 24h ; File 24h is the High byte of the product 25h ; File 25h is the Low byte of the product STATUS C MULTIPLICAND PRODUCT_H PRODUCT_L MULT_3 equ equ equ equ equ movf MULTIPLICAND,w ; Get xplicand from File 22h movwf PRODUCT_L ; and put as lower product byte clrf PRODUCT_H ; and extend to a 16-bit datum ; Now shift left 16 bits bcf STATUS,C ; Clear carry rlf PRODUCT_L,f rlf PRODUCT_H,f ; giving x2 ; Now add multiplicand (still in W) to give x2 + x1 = x3 addwf PRODUCT_L,f ; Lower byte btfsc STATUS,C ; plus any carry incf PRODUCT_H,f .... .... ation does not alter the state of the system in any way, but the PC will increment as a consequence of the instruction code being fetched from the Instruction store. Thus its sole outcome is [PC] <- [PC] + 1. This takes one bus cycle, so its main use is to implement a short delay, 1 µs for a 4 MHz clock rate. For example, to pulse Port A’s pin low for 2 µs and then high we have: for ot N me co bcf nop nop bsf PORTA,0 PORTA,0 al, rci ef us edu or tio ca nly no ; Pin RA0 low ; for 2 us ; and now high with the assumption that bit 0 of Port A has been set up as an output (see page 95) and that bit 0 (pin RA0) was high before entering the routine. The goto instruction is an absolute jump instruction allowing the program to transfer to the speci?ed instruction anywhere in the Program store. The process has been described in Fig. 5.4. The remaining four instructions can skip over the following command if some condition is met. The pair decfsz (DECrement File and Skip on Zero) and incfsz (INCrement File and Skip on Zero) augment the speci?ed ?le contents and then if the outcome is zero the PC is further incremented. Strangely, the Z ?ag is not a?ected by these instructions. A typical use for these instructions is to count the number of passes through a loop. For example, suppose it is necessary to pulse Port A pin RA0 low 20 times. http://i-tronics.blogspot.com/ THE ESSENCE OF THE PIC MICROCONTROLLER 127 Table 5.4: Program Counter instructions. Flags Mnemonic Z DC C goto nop btfsc btfss aaa • Operation Absolute jump Goto an instruction No operation Bit test and skip Bit clear in File Bit set in File Decrement and skip on zero File Increment and skip on zero File Description • •• f,n • f,n • • • • • decfsz f,d • incfsz f,d • Goto a ?xed instruction • [PC] <- aaa Do nothing • [PC] <- [PC] + 1 Check bit in ?le and skip if true • PC++ IF fn == 0 • PC++ IF fn == 1 Decrement & skip if result is #00 • d <- f--, PC++ IF [f] == #00 Increment & skip if result is #00 • d <- f++, PC++ IF [f] == #00 ++ aaa Increment contents -Absolute 11-bit instruction address Decrement contents movlw movwf LOOP bcf nop nop bsf nop nop d’20’ 30h PORTA,0 PORTA,0 ; ; ; ; Put decimal 20 into W & initialize File 30 as a loop counter Pin RA0 low for 2 us for ot N me co decfsz goto ..... 30h,f LOOP ...... al, rci ; and now high ; for 2 us ef us edu or tio ca nly no ; Count down ; Repeat loop if not zero ; ELSE escape the loop Notice the assembler notation d’20’ for decimal 20 – see page 223. This is equivalent to 14h but more readily understood by the programmer. The btfsc (Bit Test File and Skip if Clear) and btfss (Bit Test File and Skip if Set) instructions have been used extensively in programs both here and in Chapter 3. Besides their obvious use in changing the program ?ow based on the state of a speci?ed bit in any register ?le, they allow decisions to be make on the state of the various ?ags in the Status register. Thus in Program 5.5 the series of btfss STATUS,Z (or the more unreadable btfss 3,2) instructions enable the program loop to be exited when the Z ?ag is set, that is on a series of zero outcomes. Similarly btfsc STATUS,C allows the count action to be skipped over when the C ?ag is clear. Neither instruction a?ects the ?ags. All four skip instructions take two cycles to execute when the skip occurs but only one when the condition is not met. As described in Example 4.1 on page 99, the former situation needs to ?ush the instruction pipeline. This is to re?ect the fact that the pre-fetched instruction code http://i-tronics.blogspot.com/ 128 The Quintessential PIC Microcontroller sitting in stage one of the pipeline is not going to be the next instruction executed. This accounts for the additional bus cycle execution time as the true destination instruction has now to be fetched. Examples Code a program to decrement a 2-byte number at File 26:27h ordered as high:low byte, remembering that decf does not alter the Carry/Borrow ?ag. Solution Example 5.1 The task list to implement this job is: 1. IF the least signi?cant byte in File 27h is zero THEN decrement the most signi?cant byte. 2. Always decrement the least signi?cant byte. Program 5.7 gives one possible implementation based directly on this algorithm. Extension to an n-byte word is obvious. for ot N me co equ equ equ equ movf btfsc decf decf al, rci ef us edu or tio ca nly no STATUS Z MSB LSB Program 5.7 3 ; 2 ; 26h ; 27h ; LSB,f STATUS,Z MSB,f LSB,f ; ; ; ; Double-precision decrement. The Status register Bit2 of which is the Zero bit The Most Significant byte The Least Significant Byte Test for LSbyte zero. IF not THEN ship MSbyte decrement ELSE must decrement MSByte Always decrement LSbyte Example 5.2 Some early computers used a bi-quinary code to represent BCD digits. This is a 7-bit code with only two bits set to one for any combination: http://i-tronics.blogspot.com/ THE ESSENCE OF THE PIC MICROCONTROLLER 129 01 01 01 01 01 10 10 10 10 10 00001 00010 00100 01000 10000 00001 00010 00100 01000 10000 0 1 2 3 4 5 6 7 8 9 Although this is highly ine?cient (with only ten out of a possible 128 code combinations being used as compared to the 16 combinations of the 4-bit natural code) it does have the advantage that it is very easy to determine when an error has occurred. Determine an error-detection routine to check the byte in File 20h. Assume that the most-signi?cant bit is zero. If an error occurs then the Working register is to be set to FFh, otherwise zero. Solution All we need to do here is to determine when there are more or less than two bits set to one. Based on this approach we have the task list: 1. Count the number of ones in the bi-quinary byte. 2. Zero W. 3. IF count is not two THEN make FFh to signal an error. for ot N Program 5.8 shows a possible coding implementing this algorithm. Here the loop continually shifts the bi-quinary byte left until the residue is zero. When the carry bit is set, the bit count is incremented. On exit from the loop, two is subtracted from the bit tally after moving into W. If it is zero then the routine is completed and the 00h setting of W shows a correct outcome. Otherwise FFh is placed in W to show an error situation. This is equivalent to decimal -1 and is traditionally used to note an error situation. As there are only ten legal combinations out of 128 possibilities used in this code the likelihood of an undetected error is rather small. Example 5.3 me co al, rci ef us edu or tio ca nly no Write a routine to convert a binary number of magnitude no greater than 63h (decimal 99) in File 20h to two BCD digits in File 21:2h ordered as Tens:Units – see page 6. Solution A possible algorithm to implement this binary to BCD conversion is to divide by ten; this generates a quotient between 0 and 9 (remember the http://i-tronics.blogspot.com/ 130 The Quintessential PIC Microcontroller Program 5.8 Bi-quinary error detection. 3 ; Status register is File 3 0 ; Carry flag is bit0 2 ; Zero flag is bit2 20h ; Bi-quinary byte is in File 20h 21h ; The bit count is put here COUNT STATUS,C BI_QUIN,f STATUS,C COUNT,f BI_QUIN,f STATUS,Z LOOP COUNT,w 2 STATUS,Z 0FFh ...... ; Bit count is cleared ; ; ; ; ; ; ; ; ; ; ; ; Clear carry flag Rotate code left IF no Carry popped out THEN skip the count increment Test if residue is zero IF zero THEN skip out of loop ELSE repeat shift and count Get count Compare with two IF ZERO finished with W == 00 ELSE put FFh (-1) in W and exit STATUS C Z BI_QUIN COUNT equ equ equ equ equ BI_QUINARY clrf LOOP bcf rlf btfsc incf movf btfss goto movf sublw btfss movlw ..... maximum value is 99) and a remainder. The quotient is the number of tens and the remainder will be the number of units. We have already seen how to divide by an arbitrary variable datum byte in Program 5.3. Here in Program 5.9 we wish to divide by a constant ten. This simpli?es the coding somewhat with the addlw -d’10’ (or addlw -0Ah) instruction used to take away the literal ten. Keeping a count in the TENS ?le register gives the number of subtractions until a borrow is generated. The required number of tens is one less than this tally; that is the number of successful subtractions. Adding that one extra ten back again to the residue gives the remainder, which is the units tally. for ot N me co al, rci ef us edu or tio ca nly no Example 5.4 Using Program 5.2 as a template write a program to evaluate the average temperature over the 24 hours. Solution Finding the average involves walking through the array adding each element to a 2-byte grand total. On completion divide by 24 to give the function: 23 i=0 Temp[i] 24 http://i-tronics.blogspot.com/ THE ESSENCE OF THE PIC MICROCONTROLLER 131 Program 5.9 Binary to 2-digit BCD conversion. 3 ; Status register is File 3 0 ; Carry/Not Borrow flag is bit0 20h ; Binary byte is in File 20h 21h ; The quotient is put here 22h ; The remainder is put here STATUS NB BINARY TENS UNITS equ equ equ equ equ ; First divide by ten BIN_2_BCD clrf TENS movf BINARY,w LOOP incf addlw btfsc goto decf addlw movwf ..... TENS,f -d’10’ STATUS,NB LOOP TENS,f d’10’ UNITS ...... ; Zero the loop count ; Get binary byte into W ; ; ; ; ; ; ; ; Record one ten subtracted Subtract decimal ten IF a borrow (NB==0) THEN exit loop ELSE do another subtract/count Compensate for one inc too many Add ten to residue which gives the remainder Next routine This gives the task list: for ot N 1. Clear AVERAGE. 2. Point to Temp[0] (i = 0). 3. DO (a) Add Temp[i] to the 2-byte grand total. (b) Increment i. (c) Repeat WHILE i < 24. 4. Divide by 24. 5. End. me co al, rci ef us edu or tio ca nly no Program 5.10 directly implements the task list, summing each datum byte by adding to the double-byte location File 48:9h, which has been cleared before entry to the loop. Division is accomplished by repetitively subtracting 24 from the ?nal total. This is similar to the ÷10 routine of Program 5.9 but this time the single-byte constant is taken o? the doublebyte dividend. The number of successful subtracts is the quotient, which in this case is the truncated average. Of course it would be more accurate to round up if the remainder was more than half of the divisor. Example 5.5 Write a routine to multiply a byte in File 22h by ten. The 2-byte product is to be located at File 23:4h giving OVERFLOW F 21h MULTIPLICAND F 22h × 10 = PRODUCT_H F 23h PRODUCT_L File 24h where File 21h is used to extend the single-byte multiplicand to a 16-bit double-byte datum. Solution http://i-tronics.blogspot.com/ 132 The Quintessential PIC Microcontroller ×8 + ×2 operation. Thus: 1. 2. 3. 4. The task list implemented in Program 5.11 splits the ×10 task into a Multiply multiplicand by eight (shift left three times). Multiply multiplicand by two (shift left once). Add the two 16-bit partial products. End. Program 5.10 Average daily temperature. 0 ; INDirect File register 3 ; Status register is File 3 4 ; File Status Register 30h ; Array starts @ File 30h 48h ; Grand total to be in File 48:9h 4Ah ; Average byte is to be here 2 ; Zero flag is bit2 of STATUS 0 ; Carry flag is bit0 0 ; The alternative name is Not Borrow INDF STATUS FSR TEMP_0 SUM AVERAGE Z C NB equ equ equ equ equ equ equ equ equ ; Task1: Clear grand total AV_DAILY clrf SUM ; MSbyte sum zeroed clrf SUM+1 ; LSbyte sum zeroed ; Task2: Point to Temp[0] movlw TEMP_0 movwf FSR ; Put address of first temp byte ; in the pointer register ot N for ; Task3: DO ; Task3A: Add Temp[i] to the double-byte grand sum LOOP1 movf INDF,w ; Get Temp[i] addwf SUM+1,f ; Add LSB sum to it and put away btfsc STATUS,C ; IF no carry, don’t increment MSB incf SUM,f ; ELSE pass carry on ; Task3B: Increment i NEXT incf FSR,f ; Task3C: REPEAT WHILE i < movf FSR,w sublw TEMP_0+18h btfss STATUS,Z goto LOOP1 me co al, rci ef us edu or tio ca nly no ; i++ 24 ; Get pointer address ; Take away end address (Temp[24]) ; IF equal THEN end ; ELSE repeat ; Task4: Divide by 24 to give the average clrf AVERAGE ; Zero the average LOOP2 movlw incf subwf btfsc goto movlw subwf btfsc goto decf ..... d’24’ AVERAGE,f SUM+1,f STATUS,NB LOOP2 1 SUM,f STATUS,NB LOOP2 AVERAGE,f ...... ; ; ; ; ; ; ; ; ; Put the constant 24 in W Record one subtract 24 Take away 24 from the sum LSB IF borrow out, goto high byte ELSE do next subtract IF a borrow (NB==0) THEN exit loop ELSE do another subtract/count Compensate for one inc too many Next routine ; Subtract one from high byte http://i-tronics.blogspot.com/ THE ESSENCE OF THE PIC MICROCONTROLLER 133 Program 5.11 multiplication by ten. 3 ; Status register is File 3 21h ; Overflow to the multiplicand 22h ; Multiplicand byte 23h ; High byte of product 24h ; Low byte of product 0 ; Carry flag is bit0 by eight ; Get Xcand byte ; giving the lower product byte ; extended to 16 bits ; Clear Carry ; Now shift word left ; three times STATUS OVERFLOW MULTIPLICAND PRODUCT_H PRODUCT_L C equ equ equ equ equ equ ; Task1: Multiply multiplicand MUL_10 movf MULTIPLICAND,w movwf PRODUCT_L clrf PRODUCT_H bcf STATUS,C rlf PRODUCT_L,f rlf PRODUCT_H,f rlf PRODUCT_L,f rlf PRODUCT_H,f rlf PRODUCT_L,f rlf PRODUCT_H,f ; Task2: Multiply multiplicand clrf OVERFLOW rlf MULTIPLICAND,f rlf OVERFLOW,f ; Task3: Add X8 movf addwf btfsc incf movf addwf ..... and X2 MULTIPLICAND,w PRODUCT_L,f STATUS,C OVERFLOW,f OVERFLOW,w PRODUCT_H,f ...... ; Note Carry out here is zero by two ; Extend Xcand to 16 bits for ot N me co al, rci ef us ; ; ; ; ; ; ; edu or tio ca nly no Get LSB of X2 Add to LSB of X8 Skip if no carry ELSE add one onto MSByte Get MSB of X2 Add to MSB of X8 Next routine The coding copies the 1-byte multiplicand into the lower byte of the product to be. Clearing the upper byte extends the datum to 16 bits. Clearing the Carry ?ag and then shifting left three times gives the ×8 subproduct. As the upper byte is initially clear then the Carry ?ag is always zero after each double-byte shift, as it is going into the second ×2 shift routine. This is done on the extended multiplicand memory space and the resulting subproduct added to ?rst datum. This addition is simpli?ed as the shifted upper byte of the ×2 subproduct is small and so any carry from the lower byte addition is accounted for by simply incrementing the upper byte of this datum before the upper bytes are added. There will be no carry out from this latter addition. http://i-tronics.blogspot.com/ 134 The Quintessential PIC Microcontroller Self-assessment questions 5.1 Can you deduce what function the following code fragment performs on the data byte in the Working register? addwf subwf FILE,w FILE,w 5.2 How could you extend Example 5.3 to give an outcome as packed BCD in File 21h? Hint: Consider making use of the swapf instruction. 5.3 Develop Example 5.3 to give a 3-digit BCD outcome; removing the restriction that the original binary byte should be limited to decimal 99. The outcome is to be in File 21:2:3h. 5.4 Extend Example 5.1 to decrement a quad-precision 32-bit word located at File 26:7:8:9h, most signi?cant byte ?rst. 5.5 Example 5.4 evaluated the average of an array of hourly temperature samples by summing all bytes and then subtracting 24 until the residue dropped below zero. Write an extension to this program to round the average to the nearest integer; that is if the remainder is more than 12 then round up. 5.6 Write a routine to multiply a byte in File 22h by 13. The 2-byte product is to be located at File 23:4h. The memory map for this is OVERFLOW F 21h MULTIPLICAND F 22h × 13 = PROD_H F 23h PROD_L F 24h where File 21h is used to extend the single-byte multiplicand to a 16bit double byte datum. Note that this will require three shift and add processes. for ot N me co al, rci ef us edu or tio ca nly no 5.7 A simple digital low-pass ?lter can be implemented using the algorithm: Array[i] = Sn-1 Sn-2 Sn + + 2 4 4 where Sn is the nth sample from an eight-bit analog to digital converter located at Port B. Write a routine assuming that the three byte memory locations to store Sn , Sn-1 and Sn-2 are located at File 20:1:2h respectively. The outcome Array[i] is to be located at File 48h. 5.8 A certain television show has eight contestants which are evenly divided into Team A and Team B. Each member has a switch, giving logic 1 when pressed, which may all be read simultaneously by the http://i-tronics.blogspot.com/ THE ESSENCE OF THE PIC MICROCONTROLLER 135 microcontroller at Port B. Team A switches appear on the lower four bits of the port. Write a routine that will: • Decide when a response to the question has been made – any switch closed. • Determine the team identity that has responded, by clearing File 20h for Team A and setting it to any non-zero value to signify Team B. • Ascertain which team member pressed his or her switch by putting the member number 0–3 in File 21h. for ot N me co al, rci ef us edu or tio ca nly no http://i-tronics.blogspot.com/ for ot N me co al, rci ef us edu or tio ca nly no http://i-tronics.blogspot.com/ CHAPTER 6 Subroutines and Modules Good software should be con?gured as a set of interacting modules rather than one large program working straight through from beginning to end. There are many advantages to modular programming, which is almost mandatory when code lengths exceed a few hundred lines or when a project is being developed by a team. What form should should such modules take? In order to answer this question we will look at the use of program structures designed to facilitate this modular approach and the instructions associated with it. After completing this chapter you will: • Appreciate the need for modular programming. • Have an understanding of the structure of the stack and its use in the • Understand the term nested subroutine. • See how parameters can be passed to a subroutine, by copy or refercall–return subroutine and interrupt mechanisms. for ot N ence, and altered or returned to the caller. • Be able to write a subroutine having a minimal impact on its environment. • Be able to synthesize a software stack to open and close a frame in the Data store to pass parameters and provide a temporary workspace. me co al, rci ef us edu or tio ca nly no Take a look at the inside of your personal computer. It will probably look something like the photograph in Fig. 6.1, with a motherboard hosting the MPU, assorted memory and other support circuitry, and a variable number of expansion sockets. Into this will be plugged a disk controller card and a video card. There may be others, such as a soundboard, modem or network card. Each of these plug-in cards has a distinct and separate logical task and they interact via the services supplied by the main board – the motherboard. There are many advantages to this modular construction. • Flexibility; that is it is relatively easy to upgrade or recon?gure by • Can reuse from previous systems. • Can buy in standard boards or design specialist boards in-house. • Easy to maintain. adding or replacing plug-in cards. http://i-tronics.blogspot.com/ 138 The Quintessential PIC Microcontroller Fig. 6.1 Modular hardware implementing a PC. for ot N Of course there are a few disadvantages. A fully integrated motherboard is smaller and potentially cheaper than an equivalent mother/daughterboard con?guration. It is also likely to be more reliable, as input and output signals do not have to traverse sockets/plugs. However, when they do occur, faults are often more di?cult to track down and rectify. Modular programming uses the same principle to construct “software circuits”, i.e. programs. A formal de?nition of modular programming1 is: me co al, rci ef us edu or tio ca nly no An approach to programming in which separate logical tasks are programmed separately and joined later. Thus to write a program in a modular fashion we need to decompose the speci?cation into a number of stand-alone routines, each implementing a well-de?ned task. Such a module should be relatively short, be well documented and easy for a human, not necessarily the original programmer, to understand. The advantages of a modular program are similar to those for modular hardware, but even more compelling: • Each module can be tested, debugged and maintained on a stand-alone basis. This makes for overall reliability. • Can be reused from previous projects or bought in from outside. • Easier to update by changing modules. 1 From Chambers Science and Technology Dictionary, Cambridge University Press, 1988. http://i-tronics.blogspot.com/ 6. Subroutines and Modules 139 Deciding how to segment a program into individual stand-alone tasks is where the real expertise lies. The actual coding of such tasks as subprograms is no di?erent than the examples we have given in previous chapters, such as that shown in Program 5.11 on page 133. There are a few additional instructions associated with such sub-programs, and these are listed in Table 6.1. We will look at these and some useful techniques in constructing software in the remainder of the chapter. Table 6.1: Subroutine and interrupt handling instructions. Operation Call Call subroutine Mnemonic call return retlw aaa Description Transfer to subroutine Push PC on to stack, PC <- Transfer back to caller Pull original PC back from Stack Put literal in W and return as above Return from subroutine for ot N Program modules may be entered by calling from other software or by a hardware event external to the processor. This may be a voltage at one of the processor pins or an internal peripheral interface wanting service, such as the Timer over?owing. In the former case modules at assembly level are universally known as subroutines, as they are in some high-level languages such as FORTRAN and BASIC.2 In the latter they are classi?ed as interrupt service routines or interrupt handlers. The techniques for writing these interrupt modules and their entry and exit techniques are su?ciently di?erent to warrant a separate treatment in Chapter 7. Here we will look at subroutines. Subroutines are the analog of hardware plug-in cards. Consider the situation where a 0.1 second (100 ms) delay task is to be implemented. This may be needed to alert an aircraft pilot to look at the control panel warning lights for various scenarios (such as low fuel or overheating) by sounding a buzzer for a short time. In a modular program, this delay would be implemented by coding a 100 ms subroutine which would be called by the main program as necessary. This is represented diagrammatically in Fig. 6.2. In essence, calling up a subroutine involves nothing more than placing the address of the ?rst subroutine instruction in the Program Counter (PC); that is doing a goto. Thus, if our delay subroutine were located at 400h, then goto 400h would seem to do the trick. Assuming the programmer has labelled the subroutine entry point, usually the ?rst instruction, DELAY_100MS, as in Program 6.1, then we have goto DELAY_100MS. me co al, rci ef us edu or tio ca nly no 2 Other high-level languages use the terms function (C and Pascal) or procedure (Pascal). http://i-tronics.blogspot.com/ 140 The Quintessential PIC Microcontroller 100 ms delay Subroutine return Program call More program Main flow call Even more program Fig. 6.2 Subroutine calling. for ot N The problem really is how to get back again! Somehow the MPU has to remember from where in the caller program the subroutine was entered so that it can return to the next instruction in the caller’s sequence. This can be seen in Fig. 6.2, where the jumping-o? point can be from anywhere in the main program, or indeed from another subroutine – the latter process is called nesting – see Fig. 6.4. One possibility is to place this address in a designated Address register or memory location prior to jumping o?. This can then be moved back into the PC at the end of the subroutine as the return mechanism. This approach breaks down whenever one subroutine wishes to call another. Then the secondary subroutine will overwrite the return address of the ?rst, and the main program can never be regained. To get around this problem, more than one register or memory location could be used to hold a stack of return addresses. This last-in ?rst-out stack structure is shown in Fig. 6.3(a). The 14-bit core PICs have a stack of eight 13-bit registers which are exclusively used to hold subroutine return addresses.3 This structure, shown in Fig. 6.3, is known as a hardware stack. This stack is outside the PIC’s normal memory map, so its contents cannot be altered by any normal process.4 Associated with this stack is a 3-bit counter which points to the next available register in the stack. This Stack Pointer (SP) cannot be explicitly altered by any instruction but it is automatically incremented each time a call instruction is executed. call is similar to a goto instruction, but before the speci?ed instruction address is put into the Program Counter the current value of PC is pushed into the stack. This is the address of the instruction after the call instruction, as the PC has already been me co al, rci ef us edu or tio ca nly no 12-bit core devices have only two 11-bit stack registers and the 16-bit core PICs have a 16-deep stack. 4 Most MPU/MCUs use an area of normal RAM together with a dedicated address register to implement their stack. This is much more ?exible than a dedicated hardware stack but needs a more complex instruction set to manipulate the Stack pointer and to push and pull/pop data into and out of the stack. 3 The http://i-tronics.blogspot.com/ 6. Subroutines and Modules 141 incremented and the PIC is fetching this next instruction into the pipeline at the same time as the call instruction is being executed – see Fig. 4.4 on page 87. Hardware stack SP 000b 0 1 2 3 4 5 6 7 (a) Before Caller’s address Hardware stack Caller’s address SP Hardware stack Caller’s address 000b SP 001b PC DELAY_100MS (b) Calling (call DELAY_100MS) ot N for In Fig. 6.3(b) the situation is shown after a call to a subroutine labelled DELAY_100MS. The execution sequence of this call DELAY_100MS is: 1. Copy the 13-bit contents of the PC into the stack register pointed to by the Stack Pointer. This will be the address of the instruction following the call instruction. 2. The Stack Pointer is decremented. 3. The destination address DELAY_100MS, that is the location of the entry point instruction of the subroutine, overwrites the original state of the PC. E?ectively this causes the program execution to transfer to the subroutine. me co Fig. 6.3 Using the hardware stack hold return addresses. al, rci e fo us edu r tio ca nly no PC Caller’s address (c) Returning (return) Apart from the pushing of the return address into the stack in steps 1 and 2, call acts exactly like a plain goto. Thus call requires two bus cycles for execution as the pipeline needs to be ?ushed to remove the next caller instruction which is already in situ. This similarity also applies to the extension of its 11-bit absolute address in the call instruction word to a 13-bit Program store address using bits 3 & 4 of the PCLATH register, as shown in Fig. 5.4 on page 114. Far calls to subroutines located between http://i-tronics.blogspot.com/ 142 The Quintessential PIC Microcontroller 07FFh and 1FFFh are not required for the PIC16F84 and the majority of other 14-bit core PICs that have Program store capacities of not more than 2048 instructions. The exit point from the subroutine should be a return instruction. This reverses the push action of call and pulls the return address back from the stack into the PC – as shown in Fig. 6.3(c). The execution sequence of return is: 1. Decrement the Stack Pointer. 2. Copy the address in the stack register pointed to by the Stack Pointer into the Program Counter. Thus no matter whence the subroutine was called form it will return to the instruction just past the original call instruction when the subroutine has been completed. retlw (RETurn Literal value in W)5 is similar to the plain return instruction but places the speci?ed constant byte in the Working register. Thus retlw -1 could be used to return with W set to FFh (-1 decimal) to, say, indicate an error situation. Both Return instructions ?ush the pipeline and therefore take two bus cycles to execute. SR2 PC2 SR1 for ot N SP (a) Two-deep nesting stack PC1 me co PC1 al, rci PC1 PC2 ef us edu or tio ca nly no Main program stack SP stack PC1 PC2 SP stack PC1 PC2 SP (b) call SR1 (c) call SR2 (d) return (e) return Fig. 6.4 Nested subroutines. The beauty of the stack mechanism is its handling of nested subroutines. Consider the situation in Fig. 6.4 where the main program calls the ?rst-level subroutine SR1 which in turn calls the second-level subroutine SR2. In order eventually to get back to the main program, the outward progression sequence must be exactly matched by the inward 5 The 12-bit core PICs have only this retlw variant. http://i-tronics.blogspot.com/ 6. Subroutines and Modules 143 path. This pattern is matched by the last-in ?rst-out (LIFO) structure of the stack mechanism, which can handle any arbitrary nesting sequence to any depth of eight subroutines automatically. It can even handle the (painful) situation where a subroutine calls itself! Such a subroutine is known as recursive. As we shall see in the next Chapter 7, the stack mechanism is also used to handle interrupts. Thus, in a system using both subroutines and interrupts the nesting depth will be somewhat less. The technique is so useful that virtually all MPU/MCUs support subroutines in this manner. As the stack-Stack Pointer mechanism is part of the PICs hardware and requires no initialization, from the programmer’s perspective only the following points are relevant: • The subroutine should be invoked using the call instruction. • The entry point to a subroutine should be labelled, and this label is • The exit point from the subroutine should be either return or retlw, with the latter being used when a known constant is to be in the Working register on return – see Program 6.4. then the name of that subroutine. for ot N As an example, let us code the 0.1 second (100 ms) delay subroutine of Fig. 6.2. Creating a delay in software is simply a matter of doing nothing for the appropriate duration. A common way of doing this is to count down an initial constant to zero. By choosing an appropriate constant, the delay can be tailored to the desired value. Obviously, this delay will depend on the PIC’s oscillator rate. For the examples in this chapter we will assume a clock rate of 4 MHz, giving a bus cycle of 1 µs. Consider the single-byte count code fragment: D_LOOP me co decfsz goto al, rci COUNT,f D_LOOP ef us edu or tio ca nly no ; [(N-1)*1] + 2 cycles ; [(N-1)*2] cycles This continually decrements the initial setting N of the register ?le labelled COUNT, dropping out when it reaches zero. The total delay is contributed by both instructions as: 1. The decfsz takes one cycle to execute, except when N reaches zero, in which case two cycles are needed as the pipeline needs to be ?ushed – see page 127. This gives a total execution time of [(N - 1) × 1] + 2. 2. As the loop exits by skipping over the goto instruction, this is only executed N - 1 times; each time taking two bus cycles. This contribution is thus (N - 1) × 2. The total delay is thus: [(N - 1) × 1] + 2 + (N - 1) × 2 = [(N - 1) × 3] + 2 = (N × 3) - 1 http://i-tronics.blogspot.com/ 144 The Quintessential PIC Microcontroller The maximum delay is when COUNT is initialized to zero which gives an e?ective value for N of 256.6 In this situation the number of cycles in this code fragment is 767, plus the few cycles calling the subroutine (2˜), clearing COUNT (1˜) and returning from the subroutine (2˜), giving a total of 772˜. With a clock rate of 4 MHz, each cycle takes 1 µs (see Fig. 4.4 on page 87) giving a total ceiling 772 µs delay. Program 6.1 A 100 ms delay subroutine. ; ************************************************************ ; * FUNCTION: Delays for around 100ms with a 4MHz crystal * ; * ENTRY : None * ; * EXIT : Flags and W altered; Files 30:1h zero * ; ************************************************************ COUNT_H equ 30h ; 2-byte counter COUNT_L equ 31h ; at File 30:1h N equ d’130’ ; Delay parameter DELAY_100MS movlw movwf clrf D_LOOP decfsz goto decfsz goto FINI return N COUNT_H COUNT_L COUNT_L,f D_LOOP COUNT_H,f D_LOOP ; Set up high count to 130, 1˜ ; 1˜ ; and low count to 256, 1˜ ; ; ; ; ot N for Program 6.1 uses two register ?les to extend this count. Whenever COUNT_L has decremented to zero, COUNT_H is decremented. This inner loop takes (256 × 3) - 1 cycles in the normal way and is repeated H times, where H is the initial setting of COUNT_H. Only when this second byte reaches zero is the outer loop exited and execution returned to the caller. This second count contributes (H × 3) - 1 cycles to the total. We thus need to determine the unknown value of H to give a total of 100, 000 - 7 cycles, taking into account the call, return and the three setting up instructions. H × [(256 × 3) - 1] + (H × 3) - 1 767H + 3H - 1 H me co al, rci Decrement LS count to zero taking in all H*[(256*3)-1]˜ Repeat for the MS byte taking in all (H*3)-1˜ ef us edu or tio ca nly no = 100, 000 - 7 = 99, 993 ˜ 130 This gives an actual delay of 100.107 ms; an error of less than 0.11%. Each incremental change in H gives an alteration of ±770 µs. The maximum delay available with this structure is 197 ms; however, adding one or more nop instructions at the beginning of the inner loop 6 If N is zero then it will decrement 00 ? FF ? FE ? · · · 01 ? 00 and exit. http://i-tronics.blogspot.com/ 6. Subroutines and Modules 145 will increase the total delay by H × 256 cycles and the same technique used in the inner loop adds H cycles for ?ne tuning. Example 6.3 gives an example of a very long triple count delay subroutine. Our 100 ms delay program is an example of a double-void subroutine, in that no parameters (cf. signals in our hardware analog) are sent to it and nothing is returned – just the side e?ect of a delay (and the alteration of two register ?les, W and some Status register ?ags). Most subroutines process parameters made available at entry time and provide data at return time. As a simple example, consider the extension of Program 6.1 to give a delay of K × 100 ms, where K is a byte parameter ‘sent’ by the caller. The system view of this function is shown in Fig. 6.5 as a single input signal of range 1– 256, with no output signal – that is with a void output. This diagram also documents the location of all local variables used internally by the subroutine. This latter attribute is useful in checking for multiple usage of a ?le register between di?erent subroutines and callers. Notice the double line vertical borders commonly used in ?ow diagrams to denote modules or subroutines. tf No co or movlw call me K (1 -- 256) in W ial rc us , ef Internal workspace COUNT_H COUNT_L K edu or File 30h File 31h File 32h tio ca nly no DELAY_K100MS Fig. 6.5 System view of K × 100 ms delay subroutine. As there is only one input byte-sized parameter, the most convenient place to place K is in the Working register. Thus to call up a 5-second delay, the caller could use the sequence: 50 DELAY_K100MS ; 50 x 0.1s gives 5 seconds ; Go to it! The actual subroutine itself in Program 6.2 implements the task list: 1. DO: (a) Delay 100ms. (b) Decrement K. 2. WHILE (K > 0). 3. End. The actual coding simply copies the parameter from W into File 32h before entering the following delineated coding, which is identical to Program 6.1 and gives a single 100 ms delay. On completion of the delay K http://i-tronics.blogspot.com/ 146 The Quintessential PIC Microcontroller Program 6.2 A K × 100 ms delay subroutine. ; ************************************************************ ; * FUNCTION: Delays for around K x 100 ms @ 4MHz * ; * EXAMPLE : K = 100, delays 10 seconds * ; * ENTRY : K in W, range 1 - 256 * ; * EXIT : Flags and W altered; Files 30:1:2h zero * ; ************************************************************ COUNT_H equ 30h ; 2-byte counter COUNT_L equ 31h ; at File 20:1h K equ 32h ; Temporary storage for K N equ d’130’ ; Delay parameter DELAY_K100MS movwf K ; Put K away in a register file ; Set up high count to 130 ; and low count to 256 ; ; ; ; ; Task 1: DO 100ms delay movlw N movwf COUNT_H clrf COUNT_L DK_LOOP decfsz COUNT_L,f goto DK_LOOP decfsz COUNT_H,f goto DK_LOOP ; Task 2: Decrement K decfsz K,f Decrement LS count to zero taking in all H*[(256*3)-1]˜ Repeat for the MS byte taking in all (H*3)-1˜ ot N for ; Task 3: WHILE K > 0 goto DK_LOOP FINI return me co al, rci ef us edu or tio ca nly no ; REPEAT WHILE K > 0 is decremented in situ and the delay block repeated until K reaches zero. Thus the 100 ms block is repeated K times. As K is tested for zero after the 100 ms delay is executed7 an initial value of K = 0 will be treated as K = 256, giving a delay range of 00.1– 25.6 s. Testing before the loop8 would give a range 0–25.5 s. Actually, the delay will be a few µs longer than the plain 100 ms delay subroutine, due to the three additional instructions outside the delineated code block. As W is needed to set up COUNT_H it could not be used directly to hold K during the subroutine. In fact, if the caller had known that File 32h was used by the subroutine to hold K then it could have been passed directly through this register ?le. However, the less the caller has to know about the ‘innards’ of its subroutines the better it will be, on the basis 7 Known 8 Known to C programmers as a DO-WHILE loop. to C programmers as a WHILE loop. http://i-tronics.blogspot.com/ 6. Subroutines and Modules 147 that a subroutine should disturb its environment as little as possible. DELAY_K100MS is not very good in this respect, using three ?le registers for its internal use and altering the Working register. As an example of what could go wrong, Program 6.3 shows an implementation of the task list but calling the 100 ms block as the existing Program 6.1 subroutine; that is a nested subroutine. Here File 30h is used as a store for K oblivious to the fact the this register ?le is used by subroutine DELAY_100MS as one of its counters. The e?ect of this interaction is to make K zero on return from DELAY_100MS, which when decremented at Task 2 will always give a non-zero outcome. Thus the delay is in?nite and the system locks up! Simply changing K equ 30h to K equ 32h ?xes the problem; but if another member of the team with responsibility for the DELAY_100MS subroutine alters its internal storage map without communicating this to other team members then catastrophe may occur! Thus even though each subroutine could have been passed when tested on its own, certain combinations of calling sequences could cause failure. We will return to this problem later. Program 6.2 is still void in that no data was returned to the caller on exit. For our next example we will code a subroutine that will activate a decimal readout. Many numeric electronic displays are based on a selective activation of seven segments in the manner shown in Fig. 6.6. for ot N ; ; ; ; ; ; ; K Program 6.3 An alternative K × 100 ms delay subroutine. ************************************************************ * FUNCTION: Delays for around K x 100 ms @ 4MHz * * EXAMPLE : K = 100, delays 10 seconds * * RESOURCE: DELAY_100MS called * * ENTRY : K in W, range 1 - 256 * * EXIT : Flags and W altered; Files 30:1h zero * ************************************************************ equ 30h ; Temporary storage for K K ; Put K away in a register file me co al, rci ef us edu or tio ca nly no DELAY_K100MS movwf ; Task 1: DO 100ms delay DK_LOOP call DELAY_100MS ; Task 2: Decrement K decfsz K,f ; Task 3: WHILE K > 0 goto DK_LOOP FINI return ; Decrement K ; REPEAT WHILE K > 0 http://i-tronics.blogspot.com/ 148 The Quintessential PIC Microcontroller These segments are typically implemented using light-emitting diodes (see Fig. 11.13 on page 298) or electrodes in a liquid-crystal cell. N (0 -- 9) in W (a) System view SVN_SEG S (7-segment) in W a f g e d c 1000000 1111011 10100100 0110000 gfedcba 0011001 0010010 0000010 b 1111000 (b) The 7-segment font Fig. 6.6 The 7-segment display. for ot N The system description of our subroutine is shown in Fig. 6.6(a). Here the input signal is a 4-bit binary code representing the ten decimal digits as 0000 – 1001b in the Working register. The output, also in W, is the corresponding 7-segment code to activate the digit as listed in Table 6.2. This code assumes that a segment is lit/opaque on a binary 0 and unlit/clear on a binary 1. Most MPU/MCUs deal with look-up tables by storing the codes as part of the program memory and copying the Nth byte out of the table as the mapping function. In the 12- and 14-bit core PICs the Havard structure makes code in the Program store inaccessible to the program – but see Fig. 15.6 on page 445 for an exception. Instead, look-up tables are implemented as a series of retlw instructions, each returning a constant byte. This structure is shown in Table 6.2. As each retlw places an 8-bit code in W, I have arbitrarily made the unused bit 7 a logic 1. In developing a coding based on this table structure, the mechanism for element N extraction is to execute the Nth retlw instruction. This will place the instruction literal in the Working register and then do a normal return form subroutine back to the caller. In the example shown, if N is seven then the 7th retlw is executed returning with the code 11111000b for in W. The coding shown in Program 6.4 implements this selection mechanism by simply adding N, which is in W, to the lower byte of the Program Counter – that is PCL in File 2. PC then points to the Nth retlw as desired. me co al, rci ef us edu or tio ca 0000000 0010000 nly no http://i-tronics.blogspot.com/ 6. Subroutines and Modules 149 Table 6.2: The 7-segment lookup table showing byte[N] being extracted. 0 1 2 3 4 5 6 N? 7 8 9 retlw b’11000000’ retlw b’11111001’ retlw b’10100100’ retlw b’10110000’ retlw b’10011001’ retlw b’10010010’ retlw b’10000010’ retlw b’11111000’ retlw b’10000000’ retlw b’10010000’ ; ; ; ; ; ; ; ; ; ; = Table[N] for ot N PCL Although this approach does work, there are limitations. Any alteration of the PCL register will cause both these eight bits together with the lowermost ?ve bits of the PCLATH to be moved into the 13-bit PC – as described in Fig. 4.3 on page 86. This means that if the instruction addwf PCL,f causes the 8-bit PCL to over?ow or if the contents of the PCLATH does not match the upper bits in the full PC, then the outcome stored into the PC will not be as the programmer wished – see Example 6.7. This is not easy to check, as the programmer is unlikely to know in advance where the subroutine is located in memory, that is what value the PC will have at the beginning of the subroutine. Even if he/she checks the assembler listing ?le (see Table 8.1 on page 206) for the value of SVN_SEG, this can change if subsequent alterations are made to other parts of the me co equ al, rci ef us edu or tio ca nly no Program 6.4 The software 7-segment decoder. 2 ; Low byte of PC is at File 2 PCL,f xgfedcba b’11000000’ b’11111001’ b’10100100’ b’10110000’ b’10011001’ b’10010010’ b’10000010’ b’11111000’ b’10000000’ b’10010000’ ; Add N to PCL giving PC + N ; ; ; ; ; ; ; ; ; ; Code Code Code Code Code Code Code Code Code Code for for for for for for for for for for 0 1 2 3 4 5 6 7 8 9 SVN_SEG addwf ; retlw retlw retlw retlw retlw retlw retlw retlw retlw retlw http://i-tronics.blogspot.com/ 150 The Quintessential PIC Microcontroller program. It is possible to devise code to allow this address boundary to be crossed, but at the expense of complexity – see Example 6.7. The Microchip application note AN556 Implementing a Table Read gives techniques for dealing with these problems. The code in Program 6.4 takes no account of the possibility that the datum in W is greater than 09h. Of course it shouldn’t be, but robust code should cope with all contingencies even if it is technically erroneous. This is especially true if the code module is to be reusable for general-purpose applications. What would happen if this situation arose and how could you add to the code to gracefully return an error code, say -1, in this eventuality? Using W to transfer information to and fro a subroutine is limited to a single byte datum each way. Where several pieces of information of byte or greater sizes are to be passed, then ?le registers must be pressed into service for this conduit. An example of this is shown in Program 6.5 where two byte datums, labelled MULTIPLICAND and MULTIPLIER are to be multiplied giving a 16-bit outcome labelled PRODUCT_L:PRODUCT_H. MULTIPLIER (0 -- 255) in File 20h MULTIPLICAND (0 -- 255) in File 21h No for t The principle of the multiplication algorithm coded in Program 6.5 is a generalized version of that used by previous multiplication routines, such as Program 5.11 on page 133. Here the multiplier ten was decomposed to ×2 + ×8 which could be implemented by shifting once and three times respectively. In the more general case the multiplicand is shifted left and the nth shifted word added to the product if bit n of the multiplier is 1. Doing this eight times gives: 7 me co Fig. 6.7 System diagram for the byte multiplication subroutine. al, rci ef us MUL Internal workspace MULTIPLICAND_H edu or File 30h tio ca nly no PRODUCT_L:PRODUCT_H (0 -- 65,535) in File 2E:Fh Product = n=0 (multiplicand< PRODUCT_L clrf 0 decf FSR,f ; FSR ---> PRODUCT_H clrf 0 decf FSR,w ; Now reset Pseudo Stack Pointer movwf PSP ; to Bottom Of Frame ; Task 3: DO ; Task 3A: Shift multiplier right once incf FSR,f incf FSR,f incf FSR,f ; FSR ---> MULTIPLIER MUL_LOOP bcf STATUS,C ; Clear carry rrf 0,f for ot N me co incf movf decf decf decf addwf decf btfsc incf incf incf movf decf decf addwf al, rci ef us edu or tio ca nly no ; Task 3B: IF Carry == 1 THEN add multiplicand to product btfss STATUS,C ; IF C == 1 THEN do addition goto MUL_CONT ; ELSE skip this task FSR,f 0,w FSR,f FSR,f FSR,f 0,f FSR,f STATUS,C 0,f FSR,f FSR,f 0,w FSR,f FSR,f 0,f ; FSR ---> MULTIPLICAND ; DO addition ; ; ; ; ; FSR ---> PRODUCT_L First the low bytes FSR ---> PRODUCT_H IF no carry THEN do high bytes ELSE add carry ; FSR ---> MULTIPLICAND_H ; Next the high bytes ; FSR ---> PRODUCT_H http://i-tronics.blogspot.com/ 6. Subroutines and Modules 157 Program 6.6 (continued.) Implementing a byte multiply using a stack model. ; Task 3C: Shift multiplicand right once MUL_CONT movf PSP,w ; Reset FSR to the bottom of frame addlw 5 movwf FSR ; FSR ---> MULTIPLICAND bcf STATUS,C ; Zero Carry-in rlf 0,f decf FSR,f decf FSR,f ; FSR ---> MULTIPLICAND_H rlf 0,f ; Task 3D: incf movf btfss goto WHILE multiplier not zero FSR,f ; FSR ---> MULTIPLIER 0,f ; Test multiplier for zero STATUS,Z MUL_LOOP ; IF not THEN go again ; Task 4: End and clean up stack incf FSR,f ; FSR ---> Top Of Frame movf FSR,w ; Now reset Pseudo Stack Pointer movwf PSP ; To TOF return ; Finished for ot Examples N Example 6.1 its use of scarce data memory in large software systems. However, in programs running on low and mid-range PICs are often not very complex. Furthermore the small Program memory (1024 instructions for the PIC16F84) may further restrict the use of this relatively extravagant technique. Where real-time execution time is critical the additional burden of stack handling is unlikely to be worthwhile. me co al, rci ef us edu or tio ca nly no The binary series approximation to the fraction 1 1 1 1 1 1 1 1 =-+- + - + ··· 3 2 4 8 16 32 64 128 1 3 is: Using this series, write a subroutine that will divide a byte in the Working register by three with the quotient being returned in the same W regis1 ter. The actual value of the summation up to 128 is 0.3359375, which is within 0.78% of the exact value. With an 8-bit datum there is no point in including any further elements in the series, but where 16-bit operands are being processed then further elements up to the desired accuracy can be summed in the same manner. http://i-tronics.blogspot.com/ 158 The Quintessential PIC Microcontroller Solution The fractions 2 , 4 , 8 etc. can be easily generated by shifting right. The coding listed in Program 6.7 simply repetitively shifts the number as copied to a temporary location in register ?le File 33h right. Notice that it is necessary to clear the Carry ?ag before each shift as both the previous Rotate and Subtract instructions can alter its state. As the subwf instruction subtracts the contents of W (the sub quotient) from the datum in the speci?ed ?le register then the outcome being built up in W will oscillate in sign as desired. In situations where the series element signs Program 6.7 Dividing by three ************************************************************ * FUNCTION: Divides a 16-bit word by three * * EXAMPLE : Dividend = FFh (255d), Quotient = 55h (85d) * * ENTRY : Dividend N in W * * EXIT : Quotient Q = N in W * * EXIT : File 33h altered * ************************************************************ ; Temporary work byte 1 1 1 ; ; ; ; ; ; ; ; Local declarations DIV_TEMP equ 33h DIV_3 movwf DIV_TEMP movlw 0 bcf STATUS,C for ot N me co rrf DIV_TEMP,f movf DIV_TEMP,w bcf STATUS,C rrf DIV_TEMP,f subwf DIV_TEMP,w bcf STATUS,C rrf DIV_TEMP,f subwf DIV_TEMP,w bcf STATUS,C rrf DIV_TEMP,f subwf DIV_TEMP,w bcf STATUS,C rrf DIV_TEMP,f subwf DIV_TEMP,w bcf STATUS,C rrf DIV_TEMP,f subwf DIV_TEMP,w bcf STATUS,C rrf DIV_TEMP,f subwf DIV_TEMP,w return al, rci ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; Copy N into memory ; Clear quotient ; Clear Carry flag N/2 Q = N(1/2) Clear Carry flag N/4 Q = N/4-Q = N(+1/4-1/2) Clear Carry flag N/8 Q = N/8-Q = N(1/8-1/4+1/2) Clear Carry flag N/16 Q = N/16-Q = N(1/16-1/8+1/4-1/2) Clear Carry flag N/32 Q = N/32-Q = N(1/32-1/16+1/8-1/4+1/2) Clear Carry flag N/64 Q = N(1/64-1/32+1/16-1/8+1/4-1/2) Clear Carry flag N/128 Q = N(1/128-1/64+1/32-1/16+1/8-1/4+1/2) Return with quotient in W ef us edu or tio ca nly no http://i-tronics.blogspot.com/ 6. Subroutines and Modules 159 are not so regular then a further ?le register must be used to build up the quotient. The coding in Program 6.7 can be considered as the shift and subtract analog of the shift and add process outlined in Program 6.5 above. Execution takes 27 cycles including call and return. It can easily 2 be extended to generate the fraction 3 by omitting the ?rst shift right, thereby e?ectively multiplying the series by two. The rest of the program remains the same. Example 6.2 Write a subroutine to give a ?xed 208 µs delay. Assume a 4 MHz processor clock rate. Solution For a short time period like this the code fragment of page 143 provides adequate delay. The solution shown in Program 6.8 is identical to this coding terminated by a return instruction. Program 6.8 Coding a 208 µs delay. 34h ; Temp location to hold count down d’67’ ; The delay parameter is decimal 67 COUNT N equ equ DELAY_208 movlw movwf D_LOOP for ot N me co decfsz goto return al, rci N COUNT ; The delay parameter, 1˜ ; Stored in File 34h , 1˜ ef us edu or , 2˜ tio ca nly no COUNT,f ; [(N-1)*1] + 2 cycles D_LOOP ; [(N-1)*2] cycles ; Finish In order to calculate the parameter the time equation is: 2(call) + 1 + 1 + (N × 3 - 1) + 2 N ×3 N = = = 208 µs 203 67 This gives a total delay of 206 µs. Adding two nop instructions just before the return instruction will add the two extra µs. See Program 12.10 on page 338. Example 6.3 At the other end of the spectrum write a subroutine to give a delay of one second. http://i-tronics.blogspot.com/ 160 The Quintessential PIC Microcontroller Solution For a delay as long as this we need to extend Program 6.1 to use a larger count. In the coding of Program 6.9 three ?le registers are used to give a triple loop. File register COUNT2 is initialized to the value H whilst the other two ?le registers are cleared giving an e?ective count range of 256. The outer loop exits the program when COUNT2 reaches zero. This single pass therefore contributes (H × 3) - 1 cycles to the total delay. Each pass through the COUNT1 loop takes (256 × 3) - 1 cycles and there are H passes giving a contribution of H × [(256 × 3) - 1] cycles. In the same manner the inner loop based on decrementing COUNT0 runs H × 256 times each pass contributing (256 × 3) - 1 cycles to the total. Thus we have a total delay of: (H × 3) - 1 + H × [(256 × 3) - 1] + H × 256 × [(256 × 3) - 1] + 6 Equating this to 106 ( µs per second) gives H ˜ 5. The actual delay with an H of 5 is 0.985615 s which is accurate to 1.4%. If desired the shortfall of 14,385 cycles can be made up by adding nop instructions to the middle count loop. Each such instruction gives an extra 1280 cycles. The for ot N COUNT0 COUNT1 COUNT2 H ; ************************************************************* ; * FUNCTION: Delays for approx one second for a 4 MHz XTAL * ; * ENTRY : None * ; * EXIT : Status altered. W destroyed, Files 34:5:6h zero * ; ************************************************************* DELAY_1_S movlw H ; Put 5 as the MS count, 1˜ movwf COUNT2 ; 1˜ clrf COUNT1 ; Set lower counts to 256, 1˜ clrf COUNT0 ; 1˜ D_LOOP decfsz COUNT0,f ; Dec LSB count, H*256*[(256*3)-1]˜ goto D_LOOP ; to zero decfsz COUNT1,f ; Then dec NSB count, H*[(256*3)-1]˜ goto D_LOOP ; to zero and then repeat decfsz COUNT2,f ; Then dec MSB count, (H*3)-1˜ goto D_LOOP ; to zero and then repeat return ; 2˜ me co equ equ equ equ Program 6.9 A 1-second delay program. 34h ; 3-byte counter at F 34h 35h ; and F 35h 36h ; and F 36h 5 ; The delay constant al, rci ef us edu or tio ca nly no http://i-tronics.blogspot.com/ 6. Subroutines and Modules 161 maximum delay possible with this program is 50.46 s for H = 0 (e?ectively 256). Example 6.4 Design a subroutine to convert a binary byte passed in W to a 3-digit BCD equivalent in HUNDREDS (File 30h), TENS (File 31h) and UNITS (File 32h). Solution We have already coded a routine to implement this mapping in Example 5.3 on page 129. However this was restricted to a range 0–99, that is two digits. Nevertheless we can extend the technique used there by ?rst subtracting and counting hundreds from the original binary byte. After this has been computed then the residue will be less than 100 and the rest of the coding will be the same, as shown in Program 6.10. Thus a suitable task list would be: 1. Divide by 100; the remainder is the hundreds digit. 2. Divide the quotient by ten; the remainder is the tens digit. 3. The quotient is the units digit. Program 6.10 Binary to 3-digit BCD conversion. ************************************************************ * FUNCTION: Converts a binary byte in W to three BCD digits* * EXAMPLE : Binary = FFh (255d), HUNDREDS = 02h * * EXAMPLE : TENS = 02h, UNITS = 05h * * ENTRY : Binary in W * * EXIT : HUNDREDS = hundreds digits, TENS = tens digit * * EXIT : UNITS = units digit. W holds units * ************************************************************ No for t ; ; ; ; ; ; ; ; ; First divide by a hundred BIN_2_BCD clrf HUNDREDS LOOP100 incf addlw btfsc goto HUNDREDS,f -d’100’ STATUS,NB LOOP100 me co al, rci ef us ; ; ; ; edu or tio ca nly no ; Zero the loop count Record one hundred subtracted Subtract decimal hundred IF a borrow (NB==0) THEN exit loop ELSE do another subtract/count decf HUNDREDS,f addlw d’100’ ; Next divide by ten clrf TENS LOOP10 incf addlw btfsc goto TENS,f -d’10’ STATUS,NB LOOP10 ; Compensate for one inc too many ; Add a hundred to residue ; Zero the loop count ; ; ; ; ; ; ; ; Record one ten subtracted Subtract decimal ten IF a borrow (NB==0) THEN exit loop ELSE do another subtract/count Compensate for one inc too many Add ten to residue which gives the remainder and return to caller decf TENS,f addlw d’10’ movwf UNITS return http://i-tronics.blogspot.com/ 162 The Quintessential PIC Microcontroller Example 6.5 Write a subroutine to evaluate the square root of a 16-bit integer located in File 26:7h. The 8-bit outcome is to be returned in the Working register. Solution The crudest way of doing this is to try every possible integer k from 1 upwards, generating k2 by multiplication and checking that the outcome is no more than n. A slightly more sophisticated approach is based on the relationship: k= i=0 2 k (2 × i) + 1 On this basis a possible structure for this function is: 1. Zero the loop count 2. Set variable I (the magic number) to 1 3. DO forever: (a) Take I from Number (b) IF the outcome is under zero THEN BREAK out (c) ELSE increment the loop count (d) Add 2 to I v 4. Return loop count as Number That is sequentially subtract the series 1, 3, 5, 7, 9, 11…from Number until under?ow occurs; with the tally of successful passes being the square tf No co or 65 -1 64 -3 61 -5 56 -7 49 -9 40 -11 29 -13 16 -15 1 -17 -16 me al, rci ef us number edu or SQRT tio ca nly no count = 0 count = 0 count = 1 count = 2 count = 3 count = 4 count = 5 no i=0 LOOP: count = count + 1 number = number - i count = 6 count = 7 i=i+2 <0? yes count = 8 Return Terminate with square root = 8 count (a) An example (b) Flowchart of the process Fig. 6.9 Finding the square root of an integer. http://i-tronics.blogspot.com/ 6. Subroutines and Modules 163 root. An example giving 65 = 8 is given in Fig. 6.9(a) using this series approach. A ?owchart visualizing the task list is also given in Fig. 6.9(b). v Program 6.11 Coding the square root subroutine. ; Global declarations STATUS equ 3 ; Status register is File 3 C equ 0 ; Carry flag is bit0 NB equ 0 ; Alternative name Not Borrow NUM_H equ 26h ; Number low byte NUM_L equ 27h ; Number high byte ; ; ; ; ; ; ************************************************************ * FUNCTION: Calculates the square root of a 16-bit integer * * EXAMPLE : Number = FFFFh (65,535d), Root = FFh (255d) * * ENTRY : Number in File 26:7h * * EXIT : Root in W. Files 26:7h and 35:6:7h altered * ************************************************************ ; The loop count ; Magic number high ; Magic number low ; Local declarations COUNT equ 35h I_H equ 36h I_L equ 37h ; Task 1: Zero loop count SQR_ROOT clrf COUNT ; Task 2: Set magic number I to one clrf I_L clrf I_H incf I_L,f ; Task 3: DO ; Task 3(a): Number - I SQR_LOOP movf I_L,w subwf NUM_L,f movf I_H,w btfss STATUS,NB addlw 1 subwf NUM_H,f for ot N me co al, rci ; ; ; ; ; ; ef us edu or tio ca nly no Get low byte magic number Subtract from low byte Number Get high byte magic number Skip if No Borrow out Return borrow Subtract high bytes ; Task 3(b): IF underflow THEN exit btfss STATUS,NB ; IF No Borrow THEN continue goto SQR_END ; ELSE the process is complete ; Task 3(c): ELSE increment loop count incf COUNT,f ; Task 3(d): Add two to the magic number movf I_L,w addlw 2 btfsc STATUS,C ; IF no carry THEN done incf I_H,f ; ELSE add carry to upper byte I movwf I_L goto SQR_LOOP ; Task 4: Return loop count as the square root SQR_END movf COUNT,w ; Copy into W return http://i-tronics.blogspot.com/ 164 The Quintessential PIC Microcontroller The coding in Program 6.11 follows the task list closely. The maximum v value of the loop count is FFh, as 65535 = 255. Thus a single byte at File 35h is reserved for this local variable. Similarly the maximum possible value of the magic number is 511 (1FFh) and so the two registers File 36:7h are reserved for this local variable. This of course means that Task 3(a) entails a double-byte subtraction. The coding is somewhat simpli?ed as the high byte of I, that is I_H, is never more than 01h and so a borrow from the lower byte can be added to a copy of I_H before the high-byte subtract to return the borrow without over?ow. If a borrow is generated from this high-byte subtraction the outcome is under zero and the loop is exited. Otherwise COUNT is incremented and I augmented by two. Actually the latter is always twice COUNT plus one, so COUNT is not needed. Instead, on return the 16-bit value I can be shifted once right. This divides by 2 and by throwing away the one that pops out into the carry, e?ectively subtracts by one – I is always odd and so its least signi?cant bit is always 1. Try coding this alternative arrangement. Example 6.6 Repeat Example 5.5, which multiplies a byte by ten, but using a software stack for data storage and parameter passing. You may assume that the multiplicand byte is in memory at File 46h. Solution The global declarations for the subroutine of Program 6.12 and calling procedure is: No for t PSP equ 0Ch ; Holds the Pseudo Stack Pointer TOS equ 2Fh ; File 2Fh is the initial Top Of Stack INDF equ 0 ; INDirect File FSR equ 04 ; File Select Register XCAND equ 46h ; Multiplicand byte STATUS equ 3 ; Status register is File 3 C equ 0 ; Carry flag is bit0 ; The main routine sets up the Pseudo stack pointer (PSP) MAIN movlw TOS ; Set up the PSP movwf PSP ; to the initial Top Of Stack ; ..........................and so on ; Get ready to call up the X10 subroutine movf PSP,w ; 1st point to current stack position movwf FSR ; Now copy multiplicand onto the stack movf XCAND,w ; Copy multiplicand into W movwf INDF ; and onto the stack decf FSR,w ; Point down one call X10 ; Now call subroutine ; On return PSP is returned to original position ; and product is at PSP+3:PSP+2 NEXT_MAIN ..... ... ; Continuation of main routine me co al, rci ef us edu or tio ca nly no http://i-tronics.blogspot.com/ 6. Subroutines and Modules 165 Program 6.12 uses the same technique as the original routine. First the multiplicand is shifted left once to multiply by two and then two further shifts multiplies by eight. The two resulting 16-bit data are then added to give the product. In the same manner as Program 6.6, the File Select Register is moved up and down to point the the appropriate datum as the Program 6.12 Using a software stack to pass parameters and to provide a workspace. (continued next page). ; ************************************************************ ; * FUNCTION: Xs byte XCAND by 10 giving double-byte product * ; * EXAMPLE : 64h x 0Ah = 3E8h (100d x 10d = 1000d) * ; * ENTRY : Multiplicand pushed into software stack at PSP * ; * EXIT : Product_H:_L in PSP-3:PSP-2 * ; ************************************************************ X10 movf PSP,w ; Point FSR at current stack position movwf FSR clrf INDF ; Zero XCAND overflow ; Now multiply by two by shifting 16-bit XCAND left once bcf STATUS,C ; Clear Carry-in incf FSR,f ; Point to the XCAND LSB rlf INDF,f ; Shift left LSB decf FSR,f ; Point to MSB rlf INDF,f ; Shift left MSB ; Add to 16-bit incf movf decf decf movwf incf movf decf decf movwf tf No co or me subproduct FSR,f ; INDF,w ; FSR,f ; FSR,f INDF ; FSR,f ; INDF,w ; FSR,f ; FSR,f INDF ; al, rci ef us edu or tio ca nly no Point to XCANDx2_L Get it Point at PROD_L Update it with XCANDx2_L Point to XCANDx2_H Get it Point at PROD_H Update it with XCANDx2_H to give x8 Point to XCANDx2_L Clear Shift Point Shift Carry-in left LSB to MSB left MSB ; Now shift left twice more incf FSR,f ; incf FSR,f incf FSR,f bcf STATUS,C ; rlf INDF,f ; decf FSR,f ; rlf INDF,f ; incf FSR,f rlf INDF,f ; decf FSR,f ; rlf INDF,f ; Shift left LSB Point to MSB Shift left MSB http://i-tronics.blogspot.com/ 166 The Quintessential PIC Microcontroller Program 6.12 (continued.) Using a software stack to pass parameters and to provide a workspace. ; Add to 16-bit subproduct incf FSR,f ; Point to XCANDx8_L movf INDF,w ; Get it decf FSR,f ; Point at PROD_L decf FSR,f addwf INDF,f ; Update it with XCANDx8_L incf FSR,f ; Point to XCANDx8_H btfsc STATUS,C ; IF Carry set THEN inc XCANDx8_H incf INDF,f movf INDF,w ; ELSE get it decf FSR,f ; Point at PROD_H decf FSR,f addwf INDF,f ; Update it with XCANDx8_H return ; ************************************************************ program progresses. The double-byte product can be accessed relative to the Pseudo Stack Pointer by the caller. Unlike Program 6.6 this PSP is not altered when pushing out the multiplicand nor in the subroutine. This is because the subroutine is a dead end in that it can never call another subroutine. Thus a new stack frame need not be formed. Example 6.7 for ot N In order to ensure that the 7-segment decoder subroutine of Program 6.4 does not cause the PCL register to over?ow when the o?set is added, a programmer has used the directive org (ORiGin – see page 200) to tell the assembler to locate the subroutine at the absolute instruction address 700h – as shown in Program 6.13. When the subroutine is tested by calling from another part of the program in the store somewhere lower than 700h the system fails and performs unpredictably. What has gone wrong? me co al, rci ef us edu or tio ca nly no Program 6.13 The software 7-segment decoder revisited. org 700h ; Start the subroutine at 700h SVN_SEG addwf PCL,f ; Add N to PCL giving PC + N retlw b’11000000’ ; Code for 0 retlw b’11111001’ ; Code for 1 retlw b’10100100’ ; Code for 2 retlw b’10110000’ ; Code for 3 retlw b’10011001’ ; Code for 4 retlw b’10010010’ ; Code for 5 retlw b’10000010’ ; Code for 6 retlw b’11111000’ ; Code for 7 retlw b’10000000’ ; Code for 8 retlw b’10010000’ ; Code for 9 http://i-tronics.blogspot.com/ 6. Subroutines and Modules 167 Solution The system goes berserk because on reset the PCLATH register is zeroed. Summoning the subroutine using call 700h the value of the PC becomes 0700h but the value of the PCLATH register remains unaltered. Later when the addwf PCL,f instruction is executed the full 13-bit Program Counter is updated with the bottom eight bits from the PCL register and the top ?ve bits from the PCLATH register – as described in Fig. 4.3 on page 86. Thus instead of the execution branching to one of the retlw instruction it will jump somewhere in Program memory in the area 0000 – 00FFh! This will happen even though adding the o?set in W will not cause over?ow of the PCL register, as was the original intention. One way of avoiding this error would be to set the PCLATH to page 7 prior to the call, thus causing the Program Counter to be advanced to location 07NNh as desired instead of 00NNh. movlw movwf movf call 07h PCLATH NN,w SVN_SEG ; ; ; ; Prepare to point PCL to page7 of Program store Get the decimal number NN into W Call up the subroutine for ot N Even with this kludge the table is limited to 254 entries before the addition over?ows the PCL register causing a malfunction. In any case it is considered bad practice for the programmer to specify the absolute location of sections of program code, as it is possible to overwrite code that the assembler places itself. Anyway with large programs it is error prone to try and keep tabs on the location of a myriad of modules. One way around the pro

0 comments:

 
© free template by Blogspot tutorial