Microcontrollers Table of Contents Chapter 1. Introduction........................................................................................................... 4 1.1. Introduction ......................................................................................................................................... 4 1.2. Applications of microcontrollers ........................................................................................................ 5 1.3. Memory in a Microcontroller .............................................................................................................. 5 1.3.1. Types of memory ......................................................................................................................... 6 1.3.2. The Chip Select Line.................................................................................................................... 6 1.4. The Input and Output Subsystem ....................................................................................................... 7 1.4.1. Digital I/O .................................................................................................................................... 7 1.4.2. Output Port ................................................................................................................................... 7 1.4.3. Input Port...................................................................................................................................... 8 1.4.4. The I/O Ports ................................................................................................................................ 8 Chapter 2. Peripheral Modules in a Typical Microcontroller ............................................. 10 2.1. Introduction ....................................................................................................................................... 10 2.2. Timer modules .................................................................................................................................. 10 2.2.1. Internal Timer Functions:........................................................................................................... 11 2.3. The Serial Port .................................................................................................................................. 13 2.4. Analogue to Digital Conversion ....................................................................................................... 14 2.5. Special Function Units ...................................................................... Error! Bookmark not defined. 2.5.1. Serial Peripheral Port ................................................................. Error! Bookmark not defined. 2.5.2. CAN Interface ............................................................................ Error! Bookmark not defined. Chapter 3. Software and the Microcontroller Instruction Set .............................................. 16 3.1. An Introduction ................................................................................................................................. 16 3.2. The Programming Requirements for a Microcontroller ................................................................... 16 3.3. Getting your Program to Work Correctly ......................................... Error! Bookmark not defined. 3.4. The PIC Software Development Cycle ............................................ Error! Bookmark not defined. 3.5. Source Code Writing ......................................................................................................................... 17 3.6. The Reset Vectors ............................................................................. Error! Bookmark not defined. 3.7.The Instruction Set and its Use .......................................................................................................... 20 3.7.1. Bit Operations ............................................................................................................................ 20 3.7.2. Branching Instructions ............................................................................................................... 20 3.7.3. Delay Routine ............................................................................................................................ 22 3.7.4. Using the W Register ................................................................................................................. 22 3.7.5. Port Configuration...................................................................................................................... 22 3.7.6. Some other PIC Instructions ...................................................................................................... 24 3.7.7. Bit Setting and Clearing by Masking ......................................................................................... 25 3.7.8. Instructions Using the Destination Flag Bit ............................................................................... 25 3.7.9. The Auto-decrement and Auto-increment Instructions ............................................................. 26 3.7.10. The Purpose of Sub-programs.................................................................................................. 26 3.7.11. The Stack and its use ................................................................................................................ 27 3.7.12. Interrupts .................................................................................. Error! Bookmark not defined. Chapter 4. Microcontroller Peripheral Modules .................................................................. 29 4.1. Introduction ....................................................................................................................................... 29 4.2. Control/Status Registers .................................................................................................................... 31 4.3. Multiplexing of microcontroller pins ................................................................................................ 32 4.4. A study of the peripheral units within a PIC microcontroller ........................................................... 33 4.5. The Timer module used in the PIC ................................................................................................... 34 4.6. Using the Timer Module: .................................................................................................................. 35 4.7. The interrupt register INTCON......................................................... Error! Bookmark not defined. 4.8. The Analogue to Digital (A/D) Conversion Block ........................................................................... 36 4.9. The PIC A/D converter ..................................................................................................................... 36 4.10. The ADCON0 Register ................................................................................................................... 37 4.11. The ADCON1 register .................................................................................................................... 37 Chapter 5. Interfacing to the Outside World ........................................................................ 39 5.1. Introduction ....................................................................................................................................... 39 5.2. Interfacing to the outside world ........................................................................................................ 39 5.2.1. Interfacing example.................................................................................................................... 40 5.3. Digital Signal Levels and Calculating Component Values ............................................................... 40 5.4. Interfacing a number of devices to a microcontroller ....................................................................... 42 Chapter 6. Interfacing External Memory to a Microcontroller ............................................ 45 6.1. Microprocessor Mode ....................................................................................................................... 45 6.2. Using External Memory .................................................................................................................... 47 6.3. Port Controlled External Memory..................................................................................................... 48 6.4. External Memory Write Timing ....................................................................................................... 49 Chapter 7. Assembly Language Programming .................................................................... 51 7.1. Introduction ....................................................................................................................................... 51 7.2. LCD Display Driver Program Example ............................................................................................ 51 7.3. A Program to Drive a Seven Segment Display ................................................................................. 52 7.4. Example of a port sharing both input and output .............................................................................. 54 Appendices ........................................................................................................................... 57 Appendix A Lists and Tables ............................................................................................... 57 Daily Programme Schedule ..................................................................... Error! Bookmark not defined. List of Modules ........................................................................................ Error! Bookmark not defined. List of Exercises ....................................................................................... Error! Bookmark not defined. Appendix B Exercises in programming ............................................................................... 58 Initialisation ............................................................................................................................................. 58 Appendix C DAY ONE: SIMPLE PROGRAMMES .......................................................... 61 Exercise Exercise Exercise Exercise A1. B1. B2. B8. A square wave oscillation................................................................................................. 61 Digital input, digital output .............................................................................................. 61 Multiple outputs: An introduction to Subroutines ............ Error! Bookmark not defined. Delay loops ....................................................................... Error! Bookmark not defined. Appendix D DAY TWO: Modifying Existing Programmes ............. Error! Bookmark not defined. Exercise A4: Nested loops ....................................................................... Error! Bookmark not defined. Exercise B3: Multiplying by two ........................................................... Error! Bookmark not defined. Exercise B3: Group shifting ................................................................... Error! Bookmark not defined. Exercise B4: Digital encoder ................................................................. Error! Bookmark not defined. Exercise B4: Digital encoder or multiplexing........................................ Error! Bookmark not defined. Exercise B5: Digital decoding OR Tree decoder ................................... Error! Bookmark not defined. Project B6: Binary controlled analog output........................................... Error! Bookmark not defined. Appendix E DAY THREE: New Techniques ..................... Error! Bookmark not defined. Analog conversion ................................................................................... Error! Bookmark not defined. Exercise C1: Analogue Input: variable voltage ...................................... Error! Bookmark not defined. Exercise C2: Analogue Output: PWM ..................................................... Error! Bookmark not defined. Exercise C3: Analog sensor to bar indicator ............................................ Error! Bookmark not defined. Exercise D1: ............................................................................................. Error! Bookmark not defined. Appendix F DAY FOUR: The Projects .............................. Error! Bookmark not defined. Project A2: Ramp function .................................................................... Error! Bookmark not defined. Project B7: Introduction to decoding tree ............................................... Error! Bookmark not defined. Project B7: Telephone decoder ............................................................... Error! Bookmark not defined. Project B8: Digital to analog conversion using microcontroller ............. Error! Bookmark not defined. Appendix G The PIC Microcontrollers ................................................................................ 63 Chapter 1. Introduction 1.1. Introduction Microcontrollers Basically, a microcontroller is a device which integrates a number of the components of a microprocessor system onto a single microchip. So a microcontroller combines onto the same silicon chip: The CPU core Memory (both ROM and RAM) Some parallel digital I/O Timer Analog-to-digital converter The programming of microcontrollers is simplified due to the use of RIS or reduced instruction set architecture requiring only 30 to 40 instructions. The PIC16F872 uses 35 instructions. The figure below shows a partially expanded microcontroller showing a number of commonly used sub-units. CPU ROM RAM (PROGRAM AREA) (DATA AREA) REGISTERS INPUT/ OUTPUT TIMER ADDRESS BUS DATA BUS Fig 1 Main components of a microcontroller The figure below shows a single chip microcontroller and CPU. The CPU is the processing module of the microcontroller. Fig 2: A single chip microcontroller The above figure illustrates a typical microcontroller device and the different sub units integrated onto the microcontroller microchip. The heart of the microcontroller is the central processing unit or CPU. The original microcontrollers, designed by Texas Instruments has traditionally been based on an 8-bit central processing unit. For example, Motorola uses a basic 6800 CPU core in their 6805/6808 microcontroller devices. In recent years, microcontrollers have been developed around specifically designed CPU cores for example, the Microchip PIC range of microcontrollers. 1.2. Applications of microcontrollers There is a very wide scope for use of microcontrollers. They are used in a wide number of electronic systems such as: Engine management systems in automobiles. Keyboard of a PC. Electronic measurement instruments (such as digital multimeters and oscilloscopes) Printers, scanners, fax machines, photocopiers. Mobile phones. digital cameras, GPS units, hearing aids. Televisions, radios, CD players, tape recording equipment., and remote control units Environmental monitors, microwave ovens, washing machines, sewing machines Security alarm systems, fire alarm systems, and building services systems. As an exercise, count the number of devices in your home that may operate on a microcontroller. 1.3.Memory in a Microcontroller Typically, the amount of ROM type memory will vary between around 512 bytes and 4096 bytes, although some 16 bit microcontrollers such as the Hitachi H8/3048 can have as much as 128 Kbytes of ROM type memory. ROM type memory, is used to store the program code. ROM memory can be either OTP (One Time Programmable memory), EPROM, or EEPROM. The figure below shows the microcontroller RAM which is used to store data. The PIC16F872 has 2048 bytes of EEPROM program space. The PIC16F872 has 128 bytes of data space and is used for temporary storage of data which may be changed during the operation of the program. Address bus Memory device Data bus Microprocessor read write Fig 3 Microcontroller ROM 1.3.1.Read-only Memory, ROM Microcontrollers use ROM to hold the program code, which is intended to be executed whenever the system is switched on. There are basically three types of ROM: OTP ROM, EPROM and EEPROM. Erasable Programmable Read Only Memory (EPROM). The contents of the memory can be erased from the memory by exposing the memory chip to ultraviolet radiation for a short period of time. It can therefore be reprogrammed many times over. EPROM devices are fitted with a quartz window through which UV is shone to erase the programme. It is advisable to protect this window with an opaque cover as sunlight and fluorescent light holds sufficient UV radiation to corrupt or even erase the programme. This cover should not be removed unless it is intended to reprogram the device. Electrically Erasable Programmable Read Only Memory (EEPROM). These devices are designed so that part or all of the memory contents may be erased electrically through an appropriate program. They are not fitted with a window and cannot be affected by UV light. Microprocessors that use EEPROM are generically known as field-programmable devices. Microchip devices have the letter F in the name, e.g. the PIC16F872, used in this course, is a field-programmable device and can be erased and reprogrammed several times. This makes it ideal as a learning tool. Random Access Memory (RAM) All microprocessor systems need memory that can be both read from and written to. RAM memory is used to store dynamic data (that will change during the operation of the program). So a typical microprocessor system will contain both ROM (could be EPROM, EEPROM, or ROM) to store the program code, and RAM to store dynamic data. 1.3.2.The Chip Select Line The figure below illustrates the basic connections between the microprocessor and external memory. However there may be more than on memory device or the microprocessor may havr to address other types of peripheral devises Fig Basic connections between the microprocessor and its memory devices In the figure we see the addition of address decoding logic to identify a particular range of address values to activate the chip select signal. This way, the memory device can only be selected within a particular range of addresses. The chip select line allows the memory to be either selected (/CS = 0, sometimes referred to as enabled) or not selected (/CS = 1, sometimes referred to as disabled). Address bus Microprocessor Data bus Address decoding logic Address decoding logic Memory device (ROM) Memory device (RAM) read write Fig4 5 Address decoding logic generates a "Chip Select" for the memory device The address decoding logic is simply a decoder that can be used to decode the particular combination of address inputs and activate one (of a number of) chip select outputs. See TTL data book for possible devices such as the 74138 and the 74139. 1.4. The Input and Output Subsystem I/O is input or output (Input/Output). It can be: A number of digital bits formed into a number of digital inputs or outputs called a port. These are usually eight bits wide and thus referred to as a BYTE wide port. ie. byte wide input port, byte wide output port. A serial line from the microprocessor (Transmit or TX) and a serial line to the microprocessor (Receive or RX) allowing serial data in the form of a bit stream to be transmitted or received via a two wire interface. Other I/O devices such as Analogue to Digital Converters (ADC) and Digital to Analogue Converters (DAC), Timer modules, Interrupt controllers etc. (which will be discussed later in the context of microcontrollers). These are relatively complex sub systems that can be obtained as separate ICs. They are connected to the microprocessor in a similar manner to that of the memory devices. Indeed, they often contain their own memory to support internal operations (ie. registers). 1.4.1.Digital I/O A digital I/O port can be realised using a number of D type Flip-Flops. 1.4.2.Output Port figure illustrates a four bit output port. The inputs are connected to the data bus whilst the outputs are connected to whatever output interface is to be controlled. Fig1.4.2.1. A 4-bit output port 1.4.3. Input Port The input port, shown in figure, allows outside world inputs (left hand side of the figure) to be stored in the data latches so they can be read by the microprocessor via the data bus (right hand side of the figure). Fig6 A 4-bit input port The data bus connections must be via tri-state buffers so that the input port is only connected to the data bus when the input port is selected. This is achieved by connecting a chip select signal to the enable input signal line. Note that the tri-state enable is active low. We have covered some of the basic concepts of the microprocessor. There is of course much more but we can pick up on these later. 1.4.4. The I/O Ports The figure shows microcontroller ports which are used to access the outside world. Fig7 Microcontroller ports The digital I/O ports are the means by which the microcontroller interfaces to the environment. Digital I/O tends to be grouped into byte wide ports (8 digital bits) that can be configured as either input bits or output bits. There are some exceptions, such as the microchip PIC 16C54 with one 6-bit RA port and a byte wide RB port. The number of I/O port bits varies, depending upon the size of the microcontroller. Some very simple 8 bit microcontroller have as few as 4 bits of I/O, whilst those at the high end range can have as many as 33 bits of I/O (some 16 bit microcontrollers could have around 78 bits of I/O). A typical interface might look like the one illustrated below in figure. Fig8A typical interfacing example Microcontroller ports can be used to operate LEDs and relays, as well as input the state of switches and logic circuit inputs (not shown in this figure). Not all microcontroller port outputs are able to drive an LED directly; some need to be interfaced via a buffer such as a 7406 open collector inverting buffer. In the example above, the relay is driven by such a buffer. Peripheral Modules in a Typical Microcontroller Introduction Most microcontrollers contain a number of hardware modules. In the past many of these were designed as separate chips in a conventional microprocessor system. Integrating them into a single microcontroller chip allows for greater functionality in a single chip and saves space. Typical devices are: Timer module Serial I/O module Analogue to Digital Converter module The figure shows a single chip microcontroller and CPU. The CPU is the processing module of the microcontroller. Fig9 A Single Chip Microcontroller The diagram above illustrates these modules within a typical microcontroller which also contains ROM and RAM memory and ports to access and control the outside world. 1.5.Timer modules Fig10Timer Output Example The inputs allow the timer to be used to measure the time of an input signal applied to the timer input. The microcontroller counts the number of pulses over a unit of time to determine the speed of rotation, as illustrated in the figure. Fig11 Timer Input Example In this example the rotating shaft produces a single pulse every revolution. The microcontroller measures the time taken for a complete revolution and so determines the angular velocity of the shaft. figure, below, illustrates how a timer output could be used to produce an output pulse train, possibly to drive some external logic. The timer is set up so that an on time and off time can be generated by the timer unit. Fig12 Timer Output Example 1.5.1.Internal Timer Functions: The figure shows the timer in relation to the CPU and other components of a microcontroller. Fig13 Internal Timer Functions The timer unit can also be used for generating a delay. In the figure below, we see an LED prior to being turned on via the port bit PB0. Just prior to turning on the LED, the timer unit is loaded with a count value (the actual value being dictated by the delay time required). In due course the timer unit count value will reach zero, at which point a flag bit will be set. The CPU, on seeing the flag bit set, will turn the LED off. The time taken for the timer unit to decrement the count value to zero will be the time that the LED is on. Fig14Using Timer to Create a Delay Another way of using the timer to create a delay is to cause the timer unit to interrupt the CPU when the timer reaches zero. This can be more efficient in processor time since the microcontroller can be doing other things uninterrupted until the timer reaches zero. The concept of interrupts will be expanded upon later in the course. 1.6.The Serial Port A serial interface is a convenient way to connect to other systems. The figure shows a serial port in relation to components of a microcontroller. Fig15Microcontroller Serial I/O Some microcontrollers have a serial port to allow data to be transmitted to another microcontroller, PC or remote system via a two wire pair. This can be a very convenient way of transmitting data between two devices. A disadvantage can be the slower speed of data transfer that a serial port has over a byte wide parallel data port. The transfer rate can be programmed from within a range of typically 300baud (300 bits per second) to 38400baud. The serial port is usually referred to as a Serial Communications Interface (SCI). Most SCI units contained in microcontroller chips are a sub-set of the more traditional Universal Asynchronous Receiver/Transmitter (UART) unit that is available in the standard PC. The UART has additional signals that allow it to be connected to a modem. This should be borne in mind when considering microcomputer applications that require the use of a modem. Most SCI units can work in asynchronous mode, whilst some also support synchronous working. In the figure below, we see a microcontroller with a SCI unit connected to another system (which could be a PC or another microcontroller) via the transmit and receive pair. It should be pointed out that the logic levels from a SCI port are TTL. Therefore, if the microcontroller is to be connected to a PC, a TTL to RS232 interface chip is required to convert the signal levels from TTL to RS232 levels. A corresponding RS232 to TTL interface chip is included in the PC to perform the necessary signal level translation back to TTL levels for the UART chip used in the PC (a 16050 UART). This has not been shown in the above diagram. Fig16The Serial Port In some applications, a special purpose interface might be designed with its own serial interface. In the figure below, diagram we see a remote display system controlled by a microcontroller via its SCI unit. This arrangement offers a simple interface between the two units and could be the basis for a number of remote “repeater” displays (by re-transmitting the data from one LCD sub-system to another). The other system could be an LCD display with driver hardware and serial to parallel translation. Fig 17 Serial Port to LCD Display 1.7.Analogue to Digital Conversion In the real world signals are often analogue in nature. For example, we might need to monitor (log) analogue signals from a strain gauge, or from a transducer converting temperature to an electrical analogue signal (temperature transducer). Since microcontrollers are sometimes required for these types of applications, some are fitted with an Analogue to Digital Converter (ADC). In most cases, the ADC is of the Successive Approximation type and there are a number of analogue channels (between 4 and 8 is most common). The analogue channel inputs are usually shared with one or more of the digital I/O ports. That is to say they are multiplexed with the digital ports and the decision to select whether the chip pins are to be used for analogue channel inputs or digital ports is made in software (during the initial configuration of the program on reset). The figure below shows the ADC in relation to the other components of a microcontroller. Fig. 18 Analogue to Digital Converter It is uncommon for an ADC to derive more than 10 bits. For more demanding applications the ADC performance needs careful examination. In general, most 8 bit microcontrollers have limited performance due to the limited ADC resolution and CPU performance. They are restricted to simple data logging and measurement applications not requiring high precision. Most 8 bit microcontrollers are unable to perform complex calculations owing to their limited instruction set and speed. For more intensive applications involving complex algorithms, a DSP is a better choice. A simple typical application is illustrated below in the figure. Fig. 19The ADC In the figure, we see a microcontroller being used to measure an analogue signal level and determine hi/low limits. The microcontroller includes an ADC module and one of its digital input ports has been configured (by software) to be an analogue input channel. The software running on the microcontroller will perform an Analogue to Digital conversion of the input signal, then determine whether the input signal is above or below some pre-defined limit. It will then turn on the appropriate LED. We have now covered most of the units found in a microcontroller. Note that not all microcontrollers will contain all of these units. Most manufacturers of microcontroller chips produce a range or family of microcontroller devices. The family will range from simpler (and hence cheaper) microcontrollers with perhaps only I/O ports, and a Timer unit, through to high end devices containing perhaps all of the units discussed so far. Chapter 2. Software and the Microcontroller Instruction Set 2.1.An Introduction In this unit we will look at the assembly language programming requirements for a microcontroller. This will be followed by a detailed look at the instruction set of the PIC microcontroller with examples. Some fundamental programming requirements will be discussed along the way. A microcontroller is designed to control hardware. To this end it has a number of digital I/O ports; it may also have ADC and DAC devices so that it can interact with analogue signals. And finally, it will contain a number of peripheral devices such as timer modules, serial I/O, an ADC unit and perhaps other specialised peripheral modules such as a CAN controller or serial peripheral controller. 2.2.The Programming Requirements for a Microcontroller These are much the same as for any computer. The microcontroller software development will be based around a programming environment which will normally include: A text editor to develop the source program code An Assembler to produce a machine executable program with linked library modules Some form of debugging to allow the program to be tested Access to a programmer to program the target device. The job of the Assembler is to convert the source code produced by the programmer into an object code file. It works by replacing each line of assembly instruction code with the corresponding machine code instruction that will be executed on the target microcontroller. The object code file cannot be executed on the target micro-controller. It needs to be passed through a program called a Linker. The job of the Linker is to take the object file produced by the Assembler and link it with standard library modules (that have already been pre-assembled into object files) to produce a complete working executable file that can be loaded into the memory of the microcontroller. Sometimes the Assembler and Linker are combined into one program so that assembling a source program automatically links it as well. This is the case with the PIC Assembler. The figure below, shows the different stages in the production of a program. Note that the only stage that requires a lot of user input is the initial production of the user source code file. The rest of the program production involves using the Assembler and Linker tools. 'Filename' is the name of the program that the user is developing, thus the output of the Editor is the source file 'filename.asm'. The output of the Assembler is the object file 'filename.obj'. The Linker links the 'filename.obj' with any Library object files that the program might use. It will also link any user object files that the user might want to include. The Linker output is the executable file to run on the target system. Fig. 20Stages in the Production of a Program A program called a Loader takes your executable .hex file from the hard disk and loads it onto the target microcontroller. The original source file will contain instructions about where to place the .hex file in the target microcontroller memory. Typically, this instruction will be: ORG 0000H This instruction ORGanises the target program to be loaded to the target microcontroller memory address 0000 hex. ie. at the address 0000 0000 0000 0000 binary. Other key addresses may also be needed, such as the interrupt vector addresses for any interrupt service routines (isr) that the program may use. Generally, the Loader program is integrated into the development environment so that it is performed by the programmer tools. For example, in the MPLAB PIC development environment, the PICSTART menu will deal with loading the target program into the memory of the EPROM Programmer system which will then program the target microcontroller which has been placed into the zero insertion socket of the programmer system. 2.3.Source Code Writing This section will look at the way in which an assembly language program is structured and introduce some of the assembly language instructions of the PIC microcontroller. The source code for a microcontroller can be written in assembly language or in a high level language such as C (providing a suitable compiler is available). For this part of the course we will use assembly language programming. A typical assembly language program will consist of: some assembler directives sub-routines if they are needed the main program code Assembler directives are a collection of commands that tell the assembler such things as the type of microcontroller being used, its clock speed, etc. They also allow names to be used for memory locations, ports and registers, so making the program more readable. Some assembler directives: The EQU directive associates a name with a physical value such as an address in memory. Name EQU physical_value RTCC EQU 1 ; the timer counter PLC EQU 2 ; the program counter STATUS EQU 3 ; the status register CARRY EQU 4 ; the carry bit (in the status register) DCARRY EQU 1 ; the digit carry bit (in the status register) W EQU 0 ; result destination to W work register F EQU 1 ; result destination to F (file) register Z EQU 2 ; the zero bit (in the status register) After the above equate directives the names can be used instead of register addresses within the PIC microcontroller, ie. meaningful names can be used instead of the numerical values. eg. CLRF RTCC will clear all the bits in the timer counter register (which has the physical address of 1, or 0001 hex). The instruction CLRF 1 would do the same, but the use of the label RTCC makes the instruction more readable. Some of the equates refer to individual bits within a particular register. eg. CARRY EQU 4 refers to the fourth bit in the status register. 6 5 4 3 2 1 0 Carry bit 7 The name CARRY only has meaning when referring to the status register. eg. BCF STATUS,CARRY will clear the carry bit (bit 4) in the status register, A program will typically also include equate directives for the I/O registers. portaEQU 5 ; port A is at the address 5, or 00 0000 0000 0101 PA0 EQU 0 ; these labels simply provide names for each bit PA1 EQU 1 ; of port A PA2 EQU 2 PA3 EQU 3 PA4 EQU 4 PA5 EQU 5 PA6 EQU 6 PA7 EQU 7 portb EQU 6 ; port B is at the address 6, or 00 0000 0000 0110 PB0 ; these labels simply provide names for each bit EQU 0 PB1 EQU 1 PB2 EQU 2 PB3 EQU 3 PB4 EQU 4 PB5 EQU 5 PB6 EQU 6 PB7 EQU 7 ; of port B More of these register labels can be declared for other PIC registers. We can also declare memory equates such as ORG 00h ; This defines the start address of a program GOTO init ; This directs to the program start init ; Your program goes in here END ; Defines the end of the program so the assembler knows where to stop So a complete program structure would look like this: RTCC PLC STATUS CARRY DCARRY W F Z porta PA0 PA1 PA2 PA3 PA4 PA5 PA6 PA7 portb PB0 PB1 PB2 PB3 PB4 PB5 PB6 PB7 ....init END EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU EQU ORG 1 2 3 4 1 0 1 2 5 0 1 2 3 4 5 6 7 6 0 1 2 3 4 5 6 7 00h ; the timer counter ; the program counter ; the status register ; the carry bit (in the status register) ; the digit carry bit (in the status register) ; result destination to W work register ; result destination to F (file) register ; the zero bit (in the status register). ; port A is at the address 5, or 00 00000000 0101 ; these labels simply provide names for each bit ; of port A GOTO init ; This directs to the program start ; port B is at the address 6, or 00 00000000 0110 ; these labels simply provide names for each bit ; of port B ; This defines the start address of a program ; ***** The subroutines start here ***** ; **** the main program starts here ***** ; Your program goes in here ; Defines the end of the program so the assembler knows where to stop 3.7 The PIC Instruction Set The instructions used by the PIC microcontroller, the PIC instruction set falls into three groups: Bit operations Byte operations Literal/Control operations Most of these instructions execute in a single clock cycle. The duration of a single clock cycle depends on the frequency of the clock oscillator which is usually between 4MHz and 20MHz, depending upon the PIC device. To keep EM levels low most general purpose applications will use a 4MHz clock and the execution time is therefore 1µS per instruction. Each memory cycle is made up of four states so the duration of a clock cycle (and hence the instruction execution time) is four times the oscillator period. If the oscillator frequency is 4MHz, the execution time will be 1µS per instruction. If the oscillator frequency is 20MHz, the execution time will be 200nS per instruction. 2.4.The Instruction Set and its Use The following section looks at the PIC instruction set, giving examples of how the instructions are used. 2.4.1.Bit Operations One of the principal requirements of a microcontroller is to control the external environment via the digital I/O ports. Indeed, the first microcontrollers (Intel 8048/8031, Motorola 6801) were basically generic microprocessors with integrated digital I/O and a timer module. Controlling digital I/O often involves turning individual bits on and off, taking care not to affect any other I/O bits. Traditionally this has been achieved by using ANDing and ORing mask operations, but most modern microcontrollers now provide special instructions to selectively set or reset individual bits of a selected port. The PIC has two instructions, one to turn on a selected bit of a port, the other to turn it off. BSF f,b BCF f,b Note that there is no instruction for turning on or off a group of bits. To do this it is necessary to set or reset each bit in turn or use a mask. For example, assuming that all bits of portB start at zero, the effect of three such operators in sequence is shown below: 7654 3210 port bits BSF BSF BCF portb,0 portb,1 portb,0 0000 0001 0000 0011 0000 0010 2.4.2.Branching Instructions All microcontrollers need an instruction to jump out of the program sequence. The instruction to do this on the PIC is the GOTO instruction. GOTO K causes the program to jump to the label/address k. eg. GOTO 0050 causes the program to go to program memory address 0050 hex GOTO instructions cause the program to branch to another part of the program. They are often used to cause the program to loop back to repeat an earlier section of code. For example, the following program code will turn on and off bit 5 of port A in an endless loop: agn BSF BCF GOTO porta,5 porta,5 agn A typical PIC application may involve testing an input bit and performing some action when the bit changes state. For example the input could be the state of a door switch and the action could be to turn on a relay which then switches on a motor. The PIC provides two instructions, Bit Test and Skip if Set (BTFSS) and Bit Test and Skip if Clear (BTFSC). BTFSS f,b BTFSC f,b The figure shows a typical interfacing example and is explained below. Fig. 21Typical Interfacing Example agn BSF BCF BTFSC GOTO BCF portb,0 portb,0 porta,2 agn portb,1 This program will cause bit 0 of portB to pulse on and off while input bit 2 of portA is a 1, ie. while the switch S1 is open. As soon as bit 2 of portA becomes a 0 (when the switch is closed), the program will clear bit 1 of portB and so energise the relay. 2.4.3.Delay Routine In the program above the LED will be turned on and off so rapidly that the flashing action will not be noticed - the LED will appear to be lit at half power. The time to execute an instruction is 1 clock cycle except for the BTFSS/BTFSC instructions which have an additional clock cycle if a skip is involved. Therefore, the number clock cycles for a traverse around the loop of the program is: 1 + 1 + 1 + 1 = 4 clock cycles Assuming a 4MHz crystal for the PIC clock, the clock cycle is 1µs (oscillator frequency /4).The time to complete the program loop once is 4µs. The LED will be off for 1µs and on for 3µs and the flash rate will be 250kHz. Clearly, we will not be able to see the LED flashing. A delay between turning the LED on and off, and another between turning it off and on again will allow the LED flashing to be observed. We will look at how to produce a delay later, but for now assume that a delay routine has been produced as a sub-program. This can be invoked using the instruction CALL delay, where delay is the name of the sub-program. Our program now becomes: agn BSF CALL BCF CALL BTFSC GOTO BCF portb,0 delay portb,0 delay porta,2 agn portb,1 The delay sub-program will simply take up processor time to ensure the LED remains on or off for a reasonable amount of time. 2.4.4. Using the W Register The W register (working register) is particularly important as it is used to obtain literal data values and pass them to other registers in the file register. NOTE: A literal is simply a data value (not an address). Two instructions used to do this are: MOVLW n eg. MOVLW 36h MOVWF f eg. MOVWF portb So now we have a way to place literal data into a selected register. eg. MOVLW MOVWF 12h OPTION moves the literal 12 hex into the OPTION register via the W register. 2.4.5. Port Configuration The ports of the PIC (and indeed of most microcontrollers) can be configured as input or output ports. In fact the individual port bits can be configured as input or output bits independently. The figure below illustrates how the PIC portA can be configured for input or output operation. TRIS is the register to set up the direction of the bits in PORT A. A 1 indicates and input bit. A 0 indicates and ouput bit. Fig. 22 PORT A 16C5x The TRISA register is located at address 85h in the file register map and is used to configure portA for input or output by placing a 1 or a 0 into the bits of the TRIS register. Placing the bit pattern 0110 1110 into the TRISA register would configure portA as illustrated in the figure and described below. Fig. 23 Configuring portA with the TRISA register Bits 7, 4, and 0 are configured as outputs, whilst bits 6, 5, 3, 2, and 1 are inputs. The PIC instructions to do this would be Config BSF MOVELW MOVWF BCF STATUS,5 6Eh TRISA STATUS,5 This code needs some explanation. The default register file is called page 0. The TRISA and TRISB registers are located in the second bank of register files known as page 1. The figure below illustrates the arrangement of the two banks of memory register files. Note that in register bank 0 address 05h accesses porta, while the configuration register TRISA is in register file bank 1 at address 85h. Fig. 24 Two Banks of Memory Register Files To gain access to register bank 1 we need to set bit 5 of the STATUS register to 1. Bit 5 is the register file page select bit. This is most easily done by using the bit set instruction: BSF STATUS,5 To gain access to the default register file bank 0, we simply clear bit 5 in the status register with: BCF STATUS,5 You will notice that some registers (such as the STATUS register) are duplicated in both register banks. The most commonly used bits in the status register are illustrated below. 7 6 IRP 5 4 RP0 TO 3 2 1 Z C 0 STATUS register Where: IRP is the indirect address select bit RP0 is the register file page select bit (as discussed above). TO is the Timer Out bit Z is the Zero flag, set to 1 by any operation resulting in a zero C is the Carry flag, set to 1 by any carry bit generation in an addition operation. 2.4.6.Some other PIC Instructions The following PIC instructions are commonly used: CLRW CleaR the W register. ie. set all its bits to 0. CLRF f CleaR the File register f to zero. This last instruction is useful for setting all the bits in a particular register to zero. eg. CLRF OPTION would set all bits of the OPTION register to zero. Another use: CLRF portb would clear all bits of portB (assuming that it has been configured as an output). Note that a CLRW or a CLRF instruction will set the Z bit in the STATUS register. 2.4.7. Bit Setting and Clearing by Masking The logical AND and OR operators can be used to clear or set bits according to the bit pattern specified as a literal. The literal is known as a mask. Logical ANDing is used to clear selected bits in a byte to zero. ANDLW n The value n is logically ANDed to the contents of the W register and the result placed into the W register. Example: ANDLW 7Bh would logically AND the contents of W with literal 7Bh W n Result 1001 1101 0111 1011 0001 1001 the contents of W (assumed) the literal value 7Bh (the mask) bits 7 and 2 have been cleared by the AND operation 2.4.8. Instructions Using the Destination Flag Bit Many of the PIC instructions can place their result into either the W register (as in previous examples) or into one of the selected file registers. The destination is determined by the value of d (destination select). d=0 destination W register destination file register f (this is the default) d=1 eg. MOVF f,d move/copy the contents of the file register f into the destination d Example MOVLW MOVWF INCF MOVF FCh 35h 35h,1 35h,0 The second instruction moves the contents of W register (the FCh literal) into the memory location 35 hex. The operand 35h is a free memory location in register page 0 (see the register file memory map we looked at earlier; it's also on page 12 of the PIC16C84 data sheet). The third instruction increments (adds one to) the contents of memory location 35h and stores it in 35h again. The final instruction moves (copies) the contents of memory location 35 into the W register (overwriting the value FC placed there by the first instruction). Note that in the last instruction, bit d=0 indicating the destination as the W register. It is good programming practice to use an equate to give the d bit a more meaningful name. W F EQU EQU 0 1 So that the use of this type of instructions used in the above example becomes more readable: MOVLW MOVWF INCF FCh 35h 35h,F ; move literal FC hex into location 35h ; increment contents of memory location 35h MOVF 35h,W ; move contents of 35 hex into W register The following instructions all use the d bit to indicate their destination (d=0 W register, d=1 file register): ADDWF IORWF ANDWF XORWF ADDWF SUBWF COMF INCF DECF RRF RLF SWAPF f,d f,d f,d f,d f,d f,d f,d f,d f,d f,d f,d f,d 2.4.9. The Auto-decrement and Auto-increment Instructions There are two instructions that can be used to create loops that execute for a particular number of times. DECFSZ f,d ;decrement register f and skip the next instruction if zero INCFSZ f,d ;increment register f and skip the next instruction if zero Example next DECFSZ GOTO BSF count next portb,1 The first instruction decrements the contents of memory location count. If it is not equal to zero, the GOTO instruction will be executed. This of course causes the program to loop back to the DECFSZ instruction to decrement count once more. This will continue until the DECFSZ instruction decrements count to zero, at which point the DECFSZ instruction will skip the GOTO instruction and execute the next instruction (in this case setting bit 1 of portB). The two instructions DECFSZ and GOTO take up processor cycles and thus constitute a "delay". The DECFSZ instruction can be used to keep a count of some event taking place, for example we may wish to keep a count of the number of times an input changes from 1 to 0. The INCFSZ instruction behaves in much the same way, but adds one each time it is executed. 2.4.10. The Purpose of Sub-programs A sub-program (or subroutine as it is sometimes called) is a piece of program that can be called from anywhere from within a program by using the instruction CALL name_of_sub_program We have already seen this idea before with the delay sub-program. CALL delay The program instructions comprising the delay sub-program are: delay next MOVLW MOVWF DECFSZ GOTO RETURN FFh count,F count next The sub-program needs to start with a label (delay) and end with the instruction RETURN. When the CALL instruction calls sub-program, the program branches off to the group of instructions following the label delay. On completing the sub-program (ie. on reaching the instruction RETURN) the program branches back to the next instruction in the main program following the CALL instruction. In order to know where to return from a sub-program the PIC microcontroller must know where to branch back to in the main program. This is achieved by storing the next instruction address after the CALL instruction in a special area of memory called the STACK. The RETURN instruction will look at the stack and obtain the return address which it will load into the PIC's program counter (which keeps track of where the next instruction is to be executed in program memory). The next diagram illustrates the STACK mechanism used in the PIC 16Cxx series. 2.4.11. The Stack and its use The figure below shows a stack in use. The CALL instruction (ignore word Interrupt in the diagram for now) places the return address onto the stack and the RETURN instruction gets it back off the STACK and places it in the Program Counter register (PC). These actions all take place without any further action being taken by the programmer. Fig. 25 The Stack PIC16Cxxs The complete program containing both the main program sequence and the sub-program looks like this: agn delay next BSF CALL BCF CALL BTFSC GOTO BCF MOVLW MOVWF DECFSZ GOTO RETURN portb,0 delay portb,0 delay porta,2 agn portb,1 FFh count,F count next Note: The delay produced by this simple sub-program is not very long and something a little more complex would be used in practice. Chapter 3. Microcontroller Peripheral Modules 3.1.Introduction The types of peripheral that are commonly used in a typical microcontroller are: Timer modules Analogue to Digital interfaces Serial I/O modules The instruction set of the microcontroller and use it in a number of key application areas such as turning on and off digital I/O, loop counting and using sub-programs (or sub-routines). Now we look at some of these peripheral hardware modules in some detail using the Microchip PIC as an example of a real microcontroller. The main reasons for choosing the PIC microcontroller are: a) It is the one you will be using in the practicals. b) It is one of the most popular microcontrollers in use today, although, to be fair, there are other microcontrollers available that should be considered as well. (eg. the Motorola 68x05/68x08, the SGS Thompson ST6/ST7 range of microcontrollers and the Hitachi H8 series.) Before examining how PIC peripheral modules are used we need to consider how they are configured and controlled. Peripheral modules were introduced in unit 3 to illustrate the PIC instruction set. Here we examine how they are arranged and used to configure the microcontroller for a particular application. 3.1.1.Configuring and control of peripheral devices using registers All microcontrollers have a number of internal registers and some can contain over a hundred. Each register is simply a set of n bit memory locations that can be addressed at a unique memory address within the memory map of the microcontroller. Typically, these registers are 8 bits wide (byte wide). Some can be written and read while others can only be read. The main purpose of these registers is to configure and control the peripheral modules integrated within. They can be written or read via the instruction set of the microcontroller. 3.1.2.Accessing the Different Devices within the Microcontroller This is achieved by using special registers within the microcontroller. A register is a special memory location which can by accessed by the CPU core. This access is achieved by reading the register (to find out what is in it), or by writing new data into it. The following figure illustrates a byte wide register which is used to read port A of a PIC microcontroller. PortA is assumed to have been configured as an input port. Registers Here we see data 9Dh read from PortA. 76543210 1 0 0 1 1 1 0 19 | D MOVF porta,w ; will copy data from PortA into the CPU W register. The result of this instruction is that the data at the input port A (which happen to be 9D hex) will be moved into the internal register W so it can be acted upon by the microcontroller. In the next example, two PIC assembly instructions are needed to move the data 97 hex out to the output port B. MOVLW 97h will move the literal data 97 hex into register W. MOVWF portb will move the data 97 hex (now contained in the W register) out to the pins of the port B. Writing to Registers.. Here we see data 97 hex written into the output port B. 7 6543210 10010111 9|7 MOVLW 97h ; will copy data 10010111 MOVWF portb ; into the portb via W register. So far we have seen how data can be moved both to and from a port. However, in most microcontrollers the ports can be configured to be either inputs or outputs under program control. Fig. 26 Digital Port Direction Control The arrangement shown above illustrates how this is done. The Direction control register is used to configure the port pins for either input or output, depending upon whether the corresponding bit is set or cleared. If a particular bit in the Direction control register is a 1, the corresponding bit in port A will be configured as an input. If the bit in the Direction control register is a 0, the corresponding bit in port A will be configured as an output. Each digital port has a corresponding direction control register to allow for its configuration. The PIC microcontroller has a direction control register called TRIS (TRI-State) since writing a 1 into a TRIS register bit sets the corresponding port pin bit as an input and hence tri-state. Writing a 0 into a TRIS register bit sets the corresponding port pin as an output. The arrangement is illustrated below. Fig. 27 TRI-State Control Register The TRIS (TRI-State control register) is loaded with a byte of data by moving the data to it from the W register. Hence, if the following instruction sequence was used: MOVLW F0h MOVWF TRISA 7 I 6 I 5 I 4 I 3 O 2 O 1 O 0 O That is, port A bits 7 to 4 would be inputs and port A bits 3 to 0 would be outputs. What would the following sequence result in? MOVWL A5h MOVWF TRISA Top of Form Answer: port bits 7, 5, 2, and 0 would be inputs, and bits 6, 4, 3, 1 outputs. Bottom of Form 3.2.Control/Status Registers Many of the peripheral devices contained within a microcontroller have multiple functionality. That is, they can be used in a number of different ways. The programmer must configure these devices to operate in the way required and to do this, a number of special types of registers are required. These are: Control registers to configure the device to operate in a particular way. eg. the TRIS registers. Status registers to allow a particular device to be monitored to find out its current status. The following figure illustrates a typical arrangement. Fig. 28 Control Status In the figure, a control register is used to enable an interrupt by setting bit 7 of the control register to logic 1. Inside the microcontroller this enables an AND gate whose output is connected to pin 0 of a Status register. The actual interrupt input pin of the microcontroller is connected to the other input of the AND gate so that when an interrupt does occur it will set the status bit 0 to logic 1. By reading the status register the programmer can identify if an interrupt has occurred since if bit 0 is set, then an interrupt has occurred on the input interrupt pin of the microprocessor. Notice that the status register also allows the programmer to see whether the interrupt has been enabled or not by reading bit 7 of the status register. The Control register can be used to control the enabling/disabling of the interrupt. The status register can be read to determine the state (status) of the interrupt enable and the status of the interrupt condition. (Has an interrupt occurred or not?) Most microprocessors and microcontrollers have a STATUS register containing a number of assorted bits which can be read to determine the state of the microprocessor CPU. The PIC has an 8 bit status register containing bits such as the carry bit and the zero bit as well as a number of bits special to the PIC’s architecture. See page 36 of Nigel Gardner's Beginner's Guide to the Microchip PIC for more details on this. Most microcontrollers have a number of status registers, not just the one for the CPU status. Some have registers with both status and control bits in them (for example, the INTCON register in the PIC range of microcontrollers). See the PIC16C84 data sheet for a preview of this particular register. It contains interrupt enable bits (control) and flag bits (status). 3.3. Multiplexing of microcontroller pins We have already seen that a typical microcontroller can share pins between internal peripheral devices to reduce the total number of pins needed. The microcontroller must contain internal multiplexers to do this and these multiplexers are controlled through the use of registers. Fig. 29 Control/Status In the example shown in the figure the input and output pins (7 and 0 respectively) are sharing two functions. Output pin 0 can be either port A bit PA0 or data bus bit D0; bit 2 of the register is used to select the input: either PA0 (sel A = 1) or D0 (sel A = 0). Likewise input pin bit 7 can be configured to be either port A bit PA7 (sel B = 1) or timer T1 output (sel B = 0). Thus two I/O pins can be used to support a number of peripheral devices. The additional complexity is not usually a problem in integrated circuit fabrication, whereas additional pins would result in a larger product size. So most microcontrollers have multiplexed pin functions. Up to now we have been largely looking at microcontrollers in general. We will spend the rest of this unit looking at a particular range of microcontrollers designed and manufactured by the Microchip Corporation. The Microchip PIC has become something of a leader in the microchip market. It uses a very up-to-date architecture (Harvard) and is available in a wide range of different levels of sophistication, from very simple basic devices (16C54/84) through to the more sophisticated microcontrollers (17C42). It is not the most sophisticated microcontroller on the market - try Motorola home page, and look for the 68MC08 with CAN architecture, or the Hitachi H8/3048 for examples of these. 3.4. A study of the peripheral units within a PIC microcontroller The PIC uses peripherals in a way that is typical of other microcontrollers. As part of the assignment you will be invited to compare the PIC architecture with that of a number of other microcontrollers, but more on that later. We will start by looking at the general architecture of the PIC as shown in the figure below. Fig. 30 Block Diagram of PIC The PIC series of microcontrollers is based on a Harvard 8 bit architecture. The Harvard architecture separates the instruction and data buses so that the processor can be executing an instruction while, at the same time, performing data operations between memory and the processor core. This, in effect, makes it a simple Multiple Instruction Multiple Data computer (although limited to only one ALU and one data path, unlike more advanced MIMD computers such as the CRAY or the more modest Transputer). The performance is further advanced by the use of a two-stage pipeline for instructions (see page 10 of the PIC16c84 data sheet included with the PIC Trainer User Manual.This pipeline allows the processor to execute each instruction in one clock cycle. The exception is a branch instruction, which takes two clock cycles to complete. The instruction word is 14 bits wide with a separate 8 bit data bus. Some of the high-end PIC devices have a 16 bit wide instruction word. Some PIC devices come with EPROM memory and can be reprogrammed a number of times by exposing the windowed chip to a strong ultra-violet light source for about 20 minutes. A limited number of PICs make use of electrically erasable memory (EEPROM) that allow them to be re-programmed within the circuit. The turquoise blocks in the PIC block diagram are the main elements of the microcontroller and are typical of any microcontroller. The ALU (Arithmetic Logic Unit) performs the Add/Subtract and shift operations required by any microprocessor. The Program Counter (PC) keeps track of the current instruction being executed in program memory. The Status register is used to determine the status of the current point in the program (such as whether the last instruction produced a zero result (Z bit = 1), or there was a carry (C bit =1), or an interrupt occurred. The stack register is used to keep track of the return address from a subroutine or interrupt, as well as any registers that the programmer may also wish to save there. Most microcontrollers need to be configured for a particular mode of operation (such as microprocessor mode) and for the function of some of the peripheral devices. The configuration, once set, will not change during the life of the device in its final application and can therefore be set in EPROM memory during the programming of the device. The configuration fuses are not fuses in the real sense, but just a number of EPROM memory locations that are programmed. For more information about configuring the PIC16c84, see page 35 of the PIC16c84 data sheet. Like most microcontrollers the PIC chip includes the clock logic. The oscillator circuit is designed to be connected to an external crystal or an external resistor-capacitor network (for low cost applications). See the PIC16c84 data sheet for more details about the clock circuit. The general register stack consists of a number of program registers that are used by the instruction set of the PIC. The number of registers varies between the different PIC devices. All PICs have the following registers, which are 8 bits wide: A W work register. This is used for all arithmetic and logic operations and acts as the workhorse register within the PIC. Status registers. These contain such things as the carry bit and the zero bit, as well as other functions which are dependent upon the particular PIC device. Port registers: These are used to access the port pins of the PIC. Most PICs will have a Port A and a Port B. Other PICs may have more, depending upon the complexity and number of pins available on the device. Option register: This is used to set up the mode used by the PIC's internal timer module, as well as some other functions. INTCON register: This register is used to set up interrupt status in some of the PIC peripheral modules, as well as provide flag bits for these devices. Beyond the register file there is an area of static RAM that can be used as read/write memory, or as user-defined registers. Unlike some of the other registers (such as the Option register and Status register) these memory locations are not connected to any periperal device or the CPU core. 3.5. The Timer module used in the PIC The timer module has three functions: Produce a time delay by means of a counter. Count the number of input pulses arriving Produce an output pulse of a specified duration. The figure below illustrates the basic arrangement of the PIC's timer module. Fig. 31 The Real Time Clock Counter The RTCC is a counter that can be incremented by one of a number of sources. Possible sources can be chosen by setting up the OPTIONs register. The timer module is called a "Real Time Clock Counter" because it can make use of the clock signal of the PIC to increment an 8 bit counter in real time. Most microcontrollers do this as well. In the PIC, the counter can be incremented on every clock pulse, or the clock signal can be gated into a pre-scaler unit so that the clock signal is divided down to a lower frequency. In this way, the timer can be made to count more slowly and hence produce longer delays. The timer register is called the TMR register referred to as TMRO in the PIC16c84. (There is only one timer in this particular PIC, but some PICs have more than one). The TMR register can be loaded with a count value via software. It is then incremented to the maximum value 1111 1111 (255 decimal, FF hex) before rolling over to zero, 0000 000. The action of roll-over to zero causes a flag bit to be set in the INTCON register (bit 2, called TOIF). The microcontroller can read the status of the INTCON register TOIF bit to determine when the timer counter has rolled over. The OPTION register can be used to select the source for the clock pulses going to the timer counter RTCC. See diagram above and table below. Osc/4 is the clock input signal, running at one quarter the crystal frequency used by the PIC. Therefore a PIC using a 4MHz clock will count at 1MHz rate. Bits 7 and 6 are not associated with the control of the timer so they are not described. Bit 5, the RTS bit, defines whether the timer clock source is internal (from the clock signal) or external (from the RTCC pin of the PIC - see PIC16C84 pinout in the PIC trainer manual, pin 3) Bit 4 defines whether the rising edge or the falling edge will be used to increment the timer counter. Bit 3 defines the source for the pre-scaler - either the timer counter or the Watchdog timer. Bits 2, 1 and 0 determine the size of the pre-scaler in terms of 'divide by 2' up to 'divide by 256', as shown. Example To use the timer unit with the internal clock source on a zero to one transition and a 64 divider pre-scaler, the OPTION register should be loaded with 0000 0101. What would be the value to load into the OPTION register in order to use the timer unit with a 128 pre-scaler value and external negative edge triggered pulses to clock the timer counter? Answer: 0011 0110 Remember that when the timer counter overflows to zero, the INTCON register flag bit 2 (TOIF) will be set. This flag bit can be polled (a process of repeatedly reading the flag bit to determine whether it has set) or it can be arranged to cause a processor interrupt. In the second case, an interrupt routine is required. An interrupt routine is like a subroutine only if it is initiated via an event on an interrupt input pin. This interrupt pin can be either one of the PIC interrupt inputs (INT on pin 6 of a PIC16C84) or via one of the internal interrupt inputs. Most of the peripheral modules in the microcontroller can be configured to cause an interrupt of some sort. 3.6. Using the Timer Module: The following program fragment illustrates how the PIC16C84 timer can be configured and used. Note that the INTCON register is zero at power-on reset whereas the OPTION register has all its bits set at poweron reset. Strt chktmr MOVLW MOVWF CLRF BTFSS GOTO BFC 87h OPTION TMR0 INTCON,TOIF chktmr TOIF In this program segment the timer register TMR0 has been set to zero. It will therefore count right through from 0000 0000 to 1111 1111. When it rolls over to 0000 0000 again, the INTCON TOIF bit will be set (and stay set until it is cleared by the bit set instruction shown). This will produce the maximum delay possible for the clock selected and the timer pre-scalarselected. If the Timer interrupt enable bit 5 (TOIE) is set, then the branch and skip instruction (highlighted) is not required since the PIC main program will be interrupted when the timer overflow occurs. However, the clearing of the TOIF must now be done from within the timer interrupt service routine. 3.7. The Analogue to Digital (A/D) Conversion Block The A/D converter block is available on the 16C7x range of PIC microcontrollers. It is an 8 bit successive approximation converter that uses an internal 5 Volt reference source. It is possible to use an external reference voltage source. The equation used to describe the relationship between the analogue input signal and the digital output (sometimes known as the count value) is Vin = Count_Value x Vref -------------------------------------------(1) 2n Where n is the number of digital output bits. Common numbers of output bits are: 8 bits 10 bits 12 bits 14 bits 16 bits giving giving giving giving giving 2n = 2n = 2n = 2n = 2n = 28 210 212 214 216 = = = = = 256 1024 4096 16,384 65,536 The minimum input voltage that can be resolved by the A/D converter is dictated by the smallest input that can be applied to change the output count value from zero to a one in the least significant bit. Therefore: Vin(min) = 1 x Vref -------------------------------------------(2) 2n The maximum input is dictated by the full scale output count value when all digital output bits are logic 1. Therefore: Vin(max) = (2n - 1) x Vref -------------------------------------------(3) 2n The (2n - 1) represents the maximum output count value of the A/D converter. The input range for an 8 bit A/D converter using a 5 V reference can be obtained using equations 2 and 3 as Vin(min) = 19.53 mV and Vin(max) = 4.98 V 4.5.4.1 Quantitisation Error The quantitisation error in an A/D converter is given by: Quantitisation error = 0.5 x Full Scale output -------------------------------------------(4) 2n Therefore for an 8 bit A/D converter using a 5 volt reference the quantitisation error is (0.5 x 5)/256 = 9.76mV 3.8. The PIC A/D converter The A/D converter on the PIC 16C71 has a number of registers to select and control the various options. The A/D input is fed via port A which must be configured for use as an analogue input port. The registers associated with the A/D block are: REG Functions ADCON0 ADCON1 ADRES TRISA PORTA INTCON Channel select, conversion clock on/off, interrupt flag and start/end conversion. Input selection for analogue or digital. Result of A/D conversion (count value) Input/Output select for digital select bits. Input/Output read/write for digital select bits. A/D interrupt enable/disable. Some of these registers are used for other purposes. 3.9. The ADCON0 Register Fig32ADCON0 Control & Status This register is used to set up the A/D converter. The A/D converter has four analogue input channels that it shares with portA bits 0 to 3. It also uses a number of possible A/D converter clocking sources so that the conversion time can be selected for a particular application. The fastest clock is selected with bits 7 and 6 set to 0 and produces a clocking rate that is half the oscillator frequency (ie, a 4MHz clock would give an A/D conversion clock of 2MHz). Bit 0 of the ADCON0 register can be used to enable/disable the A/D converter module. To start a conversion, a logic 1 is written to bit 2 of the ADCON0 register. The same bit can be read by the PIC to determine whether the conversion is complete. A conversion is complete when bit 2 goes to logic 0. If the interrupt bit ADIE (bit 6 of the INTCON register in the 16C71 PIC) is set, the A/D converter will cause an interrupt when the converter has completed a conversion. 3.10. The ADCON1 register Before using the A/D converter the ADCON1 register MUST be configured to make the choice of which port A pins will be used for analogue inputs and which will be used for digital I/O. When using a PIC16c7x type of microcontroller (containing an A/D module) the configuration of the ADCON1 register is very important since it is reset (all bits zero) on power up and this configures port A bits as analogue inputs. This means that if the 16C7x PIC port A pins are being used for digital I/O the device will not be able to control the digital I/O pins in this state. Fig33 ADCON1 Port Control Chapter 4. Interfacing to the Outside World 4.1. Introduction This unit introduces the idea of interfacing the microcontroller to the outside world. That is, to control switches, LED indicators, other computers and in some cases external memory and I/O. In most cases a microcontroller will not need external memory or I/O. This is because the whole idea behind using a microcontroller is to take advantage of the integration of microprocessor, memory, I/O and a selection of peripheral devices on a single chip. There are however, a number of situations where a microcontroller may need to have access to external memory or I/O and for this reason a number of microcontrollers (certainly not all) will provide this facility. A microcontroller that provides this "off chip" memory / I/O option is said to have both microcontroller and microprocessor modes of operation. The microprocessor mode is so named because it is reminiscent of a conventional microprocessor. In microprocessormode there is no internal program memory available, all program memory being made available as external memory (just like in a conventional microprocessor). The PIC can be configured in a slightly different arrangement called Extended Microcontroller mode where the internal program memory is available with an extension of external program memory. The figure below shows the three arrangements. Note that in every case the data memory (RAM) is "on chip". Fig34PIC memory map in three different modes (Source: PIC17C42 data sheet) 4.2. Interfacing to the outside world In most applications the digital I/O ports of the microcontroller are used to interface to the outside world. Typically, we may need to read switches and write to LED indicators, relays, and control LCD displays. We may also need to read and write to external logic and perhaps also communicate with another microcontroller or a PC. In the latter case we could make use of the serial port to interface with the serial I/O communication port of the PC. 4.2.1. Interfacing example Fig. 35 Typical Interfacing Example The digital I/O of a PIC microcontroller is designed to interface to devices that are "TTL compatible". This means that they are designed to work at 5V and can source and sink at least one TTL load. Bottom of Form The typical interfacing arrangements shown in the figure above are quite general and are easy to implement. For example, to interface an LED indicator, one only needs to know the required forward diode current If and the forward voltage Vf of the LED. This is typically 10mA and 1.6V respectively. So in the example the value of the current limiting resistor R1 can be calculated as: R1 = Vdd - Vf = 5V - 1.6V = 340 If 10mA The nearest preferred value is 330 . This assumes zero VCEsat for the output transistor. If a low current LED is used (typically If = 2mA) then the value of R1 will be 1700 or its nearest preferred value of 1800 , giving a diode current of 1.8mA. The relay can likewise be easily interfaced to the microcontroller by first noting its operating current Ir and operating voltage Vp. Most relays will have an operating voltage greater than 5V (although there are some DIL relays that operate from 5V). Then R2 = Vdd - Vp Ir = 12 - 6 = 400 15mA For an operating voltage of 6V and an operating current of 15mA. 4.3. Digital Signal Levels and Calculating Component Values In some cases the microcontroller output will not be able to sink the required current so a buffer device will be required. In the typical interfacing example diagram above, the buffer device would be an "open collector" type so that the output transistor of the buffer would provide a current path to ground when it is turned on. Switches are very easily interfaced, requiring only a "pull-up" resistor. The maximum possible value of the pull-up resistor is dictated by the logic one current IiH which flows out of the input pin. So R3max = Vdd - ViHmin = 5 - 1.8 IiH = 3.2M 1uA These figures are taken from the PIC16C84 data sheet. Note that in practice we would need to choose a resistor value less than this to ensure that the volt drop across R3 was much less than the minimum required. A suitable value would be 100K giving a current through R3 when the switch is open of: (5V - 1.8V) / 100x103 = 32uA In practice, of course, the current into an input would be no more than 1uA so the volt drop across R3 would be no more than 1uA x 100K = 0.1 Volt. Thus the input would be very close to Vdd (5-0.1) Volts. This value of R3 will still consume a little current when the switch is closed. ie. 5V / 100K = 50uA When interfacing external devices to a microcontroller port, one should first look at the electrical characteristics of the microcontroller. The figure taken from the PIC16C84 data sheets, illustrates some of the electrical characteristics for the I/O inputs of the PIC16C84 microcontroller. Fig. 36 Electrical Characteristics of I/O(Source: PIC16C84 data sheet) Note that the permissible supply voltage, VDD, is between 4.5V and 5.5V. The acceptable Input Low Voltage, VIL, is between OV (Vss) and 0.8V or between 0V and 0.16xVDD (= 0.8V). The acceptable Input High Voltage, VIH, is from 0.36VDD to VDD. For a nominal value of VDD = 5V, VIH(min) = 0.36 x 5 = 1.8V. The leakage currents are very low (it is a CMOS device) at 1uA for I/O port inputs. figure 4 shows the lower part of the same figure from which you can see the I/O port output voltage levels: Fig. 37 Electrical Characteristics of I/O (Source: PIC16C84 data sheet) Note the minimum output voltage for logic 1: VOH = VDD - 0.7V = 5 - 0.7 = 4.3V, for an output current of IOH = 3mA and a minimum supply voltage VDD of 4.5V. The PIC devices have what is called a "weak pull-up" resistor connection to all of port B I/O lines. These can be enabled by programming bit 7 of the OPTION register to logic 0. When enabled, any port B I/O bit that is programmed as input will have this weak pull-up resistor connected. The result is that no external pull-up resistors are necessary, thus saving on external components. See Port B and TRISB registers in the PIC16C84 data sheets for details of the internal circuit for each port B bit. Note that port A does not have this feature. Many newer microcontrollers have this built in "weak pull-up" resistor, but most older microcontroller don't. 4.4. Interfacing a number of devices to a microcontroller The more devices you interface to a microcontroller, the more digital I/O ports you require. Some recent microcontrollers (such as the H8/3048) have a large number of digital I/O ports. Most general purpose microcontrollers however have very limited digital I/O capability, for example the PIC range of microcontrollers (particularly the base and medium range devices) have between two, three, and four ports. A typical application might consist of an LCD display, one or two LED indicators, and some panel switches or analogue inputs. The figure below shows a simple temperature monitor. Fig. 38 Typical Micorcontroller Application. Simple Temperature Monitor Here the requirement is to monitor and store temperature readings over a period of time. If the temperature goes above or below predefined limits, Hi/Low LED indicators are illuminated. A four digit LCD display will require twelve digital I/O bits, eight for the segments and decimal point and one for each digit (digit select). If we were to use the PIC16C71 for this project we would be able to assign port B for the display parallel interface, leaving port A for the digit selection (4 bits) and two bits of port A for the Hi and Lo LEDs. In addition, we require an analogue input, giving a total of 15 bits required. The PIC16C71 has two I/O ports Port B (8 bits) and Port A (5 bits) so we are short of two bits to complete the interface. Note that the PIC16C84 does not have an Analogue to Digital Converter, necessary to convert the analogue temperature into a digital value, so it would be unsuitable for this application. We could, of course, choose to use a larger PIC device (such as the PIC16C73 which has three I/O ports, Port A - 6 bits, Port B - 8 bits, and Port C - 8 bits) but this has more pins (28 pins). It would, however, provide for future enhancements to the product. One way of overcoming the I/O limitation of the PIC16C71 is to use a single I/O port for both input and output, changing the port configuration during program execution to read inputs, or write to outputs as required. This idea is used to great effect in the hardware of the MMM PIC micro board. The figure below illustrates an arrangement showing how a seven segment display can be interfaced along with switch inputs. Fig. 39 Interfacing configuration to 7-segment display and switch inputs Note the RA0 and RA1 port bits are connected to both the A1 and A0 switches and the transistor drivers to select the display digits. To drive the display, the RA0 and RA1 bits are configured as outputs. To input from the two switches, the RA0 and RA1 bits are configured as inputs. The two 10K resistors prevent damage to the port when configured as outputs and a switch is closed. Fig. 40 Alternative Switch Configuration In the figure we have the open switches producing a logic 0, going to logic 1 when the switch is closed. This is the arrangement used in the MMM PIC micro board. The 220 ohm resistors are provided to limit the segment current. However, the PIC can directly drive an LED/Segment so in the MMM PIC micro board these resistors are omitted. Chapter 5. Interfacing External Memory to a Microcontroller 5.1. Microprocessor Mode Some microcontroller applications require external memory to supplement the RAM available internally. For example, an application may require additional RAM to store data read in from the external environment in a data logging application. Or more memory may be required to store the application program. Or it may be that the application program is to be updated via a modem and the microcontroller does not support electrically erasable (EEPROM) so external EEPROM program memory needs to be added. Or an application may require more I/O than is available on the microcontroller chip. Or a peripheral device may need to be added (such as an external UART) so that the microcontroller can communicate with a modem. Fig. 41 Microcontroller in expanded mode To allow a microcontroller to use external memory, some microcontrollers can be configured in microprocessor mode, also known as expanded mode. In microprocessor mode some of the internal features of the microcontroller are lost in order to provide an external address and data bus. To see why this is so, consider the figure below. Fig. 42 Features of Expanded Mode Some microcontrollers provide multi-functional pins. This can be seen in the above figure. Each bit is multifunctional. In microcontoller mode it is portB. In microprocessor mode it is a multiplexed Address/Data bus. The microcontroller pins for port B double up as a multiplexed Address and Data bus. For this to work, the microcontroller must contain configuration logic to allow the pins to be used either as an I/O port for digital input or output as a multiplexed Address/Data Bus. Note that at any one time these pins can only be used for one of the two functions. This means that if the microcontroller is to be used in microprocessor mode, then the pins used for the multiplexed Address/Data bus cannot be used for port B I/O and therefore port B I/O is lost. The circuitry for port B is of course still present inside the microcontroller, but it is simply not available for use. This is a very common problem with microcontrollers and fact it is not just limited to configuration. In most cases, a given microcontroller will contain the devices we have discussed in the previous unit (ie. SCI, ADC etc), but they will, in most cases, share the same I/O pins as digital I/O ports. Therefore when we elect to use these devices (SCI/ADC) the digital port features with which they share I/O pins are lost. This means that when deciding upon the particular microcontroller to use in a particular application, we need to consider which of the internal features we intend to use. Then determine how much digital I/O is left for use in our application. Some recent microcontrollers, such as the PIC range, have been designed to provide a more flexible arrangement so that, when an internal peripheral is selected, not all of the I/O port pins are lost. You will have seen an example of this with the use of the ADC in the PIC16C73 where the use of the ADC does not mean losing all of the I/O for portA if, say, two analogue channels are required rather than four. So now let us look at a microcontroller that can be configured to access external memory and I/O. Fig. 43 Microcontroller without External Expansion 8 bit port A can be configured for input or output, as can the 8 bit port B. These are used to access external devices. There is no external memory or I/O. The above figure shows a microcontroller with two ports, A and B. If these two ports are also used for external data and address bus, then when we configure the chip for microprocessor mode, as shown, we obtain: Fig. 44 Microcontroller in expanded mode Port A is now used as part of the address bus, with port B used for both the remaining address bus signals and the data bus. At one time the pins of port B form part of the address bus while, a little later, they are the data bus. This is a common arrangement, called a multiplexed address/data bus configuration. It is common because it uses fewer pins than would be needed for separate address and data bus connections. In order to obtain the multiplexed address and data signals from the port B pins, an external data latch is required. This is used to hold the address bits, when the port B pins change to become the data bus. The purpose of the address strobe is to latch the address bits into the data latch at the right moment, before the port B pins change to become the data bus. Fig. 45 Memory I/O Interface The figure above, illustrates the basic arrangement of a multiplexed Address/Data bus. It is actually very similar to that used for the intel 80X86 processor. The basic address/data multiplexed timing is illustrated below. Fig. 46 Timing for multiplexing address and data information After the address has been strobed into the Address latch it remains there until the next strobe pulse. The strobe pulse is controlled by the microcontroller and will occur at a fixed point during the memory cycle. The main point here is that the address remains fixed until the next address strobe. Note that the memory read (when the read line is asserted) and the memory write (when the write line is asserted) take place towards the end of the data waveform. 5.2. Using External Memory Most microcontrollers allow the external memory to be used for either data or program storage. For example, the Motorola MC68HC11 microcontroller can be used with external memory for program or data since it is seen by the microcontroller as an extension of its memory map. The PIC range of microcontrollers however use a Harvard architecture which has separate data and address busses for program and data memory. The PIC devices that use external memory use the program data and address busses to interface with the external memory so that this memory is normally used for storing program and is typically used to extend the size of the application program. The figure below illustrates the arrangement used with the PIC17C4X range. Fig. 47 Typical external program memory connection diagram (Source: PIC17C4X) What if you want to use external memory for data rather than program? It is possible to use external memory to store data but the data cannot be accessed directly. It should be pointed out that other microcontrollers, such as the 68HC05 and 68HC08 do not have this problem, external memory can be used for either program or data. To access data in external memory with the PIC (both to write data to external memory and to read it from external memory) requires an indirect approach using a number of the PIC's internal registers (Table pointer and Table Latch registers). Is there any other way of interfacing external memory to the PIC? Yes, interface memory directly to the I/O ports of the PIC. 5.3. Port Controlled External Memory The PIC's fast execution time makes it possible to connect an external memory chip to the I/O ports as shown in the figure below. If a 20MHz crystal is used, memory transfer rates are compatible with microcontrollers using a 1MHz instruction cycle and memory mapped external memory. Microchip publish an applications paper on this idea that you might like to read. Fig. 48 Additional port bits required for the Address bus bits of larger memories This arrangement, of course, uses up a large amount of the microcontroller digital I/O but this might not be a problem in some applications. Another idea is to use a slave microcontroller to control the external data memory device and pass all data to/from the main microcontroller via a dedicated port (or if data speed is not an issue, via serial I/O). The serial I/O interfacing of external memory is used to interface some kinds of electrically erasable memory devices. These are called serial EEPROMs and are used to store data that is required to be changed from time to time, but must be held in memory between power up/power down conditions. Again, there is a data sheet available at Microchip's website for reference to see how it is done. For a description of serial EEPROMs, click on the button below. 5.4. External Memory Write Timing When designing an external memory interface, the external memory write and memory read cycle timing must be carefully considered. The figure is taken from the PIC17C4X data sheet. Fig. 49 Memory interface write timing (Source: PIC17C4X data sheet) Each memory cycle involves four clock cycles, Q1 to Q4. Most instructions execute in a single memory cycle so the instruction time is simply the clock period multiplied by four. For example, a microcontroller with a 20MHz oscillator has a clock period of 50ns and memory cycle time Tcy = 200ns. The four states of the memory cycle Q1, Q2, Q3, and Q4 define the four internal states that are an external memory cycle in the PIC. The address is placed onto the address pins of the PIC during Q2 and latched into the external address latch on the falling edge of ALE. The multiplexed Address/data bus pins become the data bus during the Q3 phase and the data is written on the rising edge of the write pulse in the following Q1 period. The time values given in the data sheet are thus: TcdV2adl (150 in the above figure) indicates a minimum time of 0.25Tcy - 30 which would be: 0.25 x 200ns - 30ns = 50ns - 30ns = 20ns. Using the values for a 20MHz oscillator we can obtain the maximum access time from Address Access Time = 0.75 * Tcy - 40ns = 0.75 * 200ns - 40ns = 110ns However, from this should be subtracted the delay time of any address decoding logic that might be used in the design. So if the worst case delay for the address decoding logic is Tpaddr then Address Access Time = 0.75 * Tcy - 40ns - Tpaddr = 110ns - Tpaddr. The Microchip application note TB005 on the use of External RAM gives a specific example of interfacing the PIC17cxx to two MT5c2568 (32Kx8) static RAM chips. In most applications where there is only additional memory and no additional I/O there will not be any external address decoding logic so Tpaddr will be zero. Any external memory chips used should have a memory access time which is less than the address access time of the PIC. So Address Access Time > Memory Access Time. In general, when calculating the worst case address access time, you should determine the slowest delay path from the microcontroller and the device you are trying to access. This will include any address decoding logic chips. The indicated timing values below are important and should be studied from the data sheet. 150 is the Address valid to ALE address setup time, 20ns in our case 151 is the address hold time and is the time required for the address to settle at the output pins of the PIC after the ALE signal has gone low. It is 0ns which means that it is not critical. 152 is the data setup time, the time required for the data bus values to settle at the data pins of the PIC. It is 10ns in our case. 154 is the Write signal pulse time, in our case 50ns. 153 is the time between the end of the write pulse and the point where the data bus outputs become invalid.. Note that the timing values 150 to 152 are minimum values (they will be at least this big), whilst 153 and 154 are typical values (averaged over a number of samples tested). The timing arrangement for the read cycle is similar and should be studied also Chapter 6. Assembly Language Programming Examples 6.1. Introduction In this unit you will look at PIC programs and enter, compile and run the programs within the MPLAB programming environment. One of the most common requirements of an embedded system is to drive a display to output numbers and text. There is a wide range of display systems available, for example LED seven segment displays or LCD alphanumeric displays. Some displays can be driven directly from a microprocessor bus, whilst others can be driven directly from the I/O ports of a microcontroller. The MMM board contains both a seven segment display and an LCD display, both of which are driven via an I/O port. Some microcontrollers, such as the Motorola MC68HC708LN56, have an LCD display driver integrated within the microcontroller. 6.2. LCD Display Driver Program Example Most LCD displays have integrated data latches and decoding logic so the data to be displayed can be loaded in parallel from a microcontroller output port. Other LCD displays have a serial input arrangement and the data to be displayed is transferred by a single digital I/O line, thus saving on the number of digital I/O lines required for the interface. For example, the Lascar DDM4 module (a 4 digit x 7 segment LCD display) requires only three digital I/O connections, as shown in the figure below. Within the module is a Microchip AY0438 segment driver. (Details of the DDM4 and AY0438 interconnections are not shown in the figure). Fig. 50 PIC interface to four-digit 7-segment LCD display module Port B of the PIC is used here to control the display using only three bits. The potentiometer is being used to obtain an analogue input voltage between 0V and 5V. This is converted into a digital value by the integrated ADC in the PIC and is displayed on the LCD display in steps of 20mV. The data to be sent to the LCD display consists of four 8 bit data words. i.e. 32 bits of serial data are transmitted from Port B bit 1 (B1). After the 32 bits of data have been output, the PIC pulses the load line (B0) to latch the data into the display. The PIC software needs to control the Load/Data in/Clock signals and this is achieved with the assembly language code shown below. display MOVLW MOVWF RRF RRF RRF RRF BTFSS GOTO BSF GOTO zero_bit BCF n_bit BCF DECFSZ GOTO BSF NOP BCF RETURN 32 digits digit4,f digit3,f digit2,f digit1,f status,carry zero_bit data n_bit data clock digits,f display+2 load load Each RRF instruction moves the least significant bit of the register into the carry so that the next RRF instruction moves the carry into its most significant bit position. In this way, the four RRF instructions shift the four (32 bit) data out to the last RRF digit1,f instruction shifting the data into the carry so it can be tested to determine the logic level of the data line. The data to be sent to each digit must first be converted into a suitable seven segment code. This can be easily done using a look-up table. The PIC has a very neat way of controlling a look-up table as illustrated in the following assembly code. lookup ADDWF pcl,f RETLW RETLW RETLW RETLW RETLW RETLW RETLW RETLW RETLW RETLW b'01111110 b'00011000 b'10110110 b'10111100 b'11011000 b'11101100 b'11101110 b'00111000 b'11111110 b'11111100 ;load program counter into W register ; g f a b c d e dp display segment corresponding to each bit ;0 ;1 ;2 ;3 ;4 ;5 ;6 ;7 ;8 ;9 The way that this routine works is that prior to entry to the look-up routine, the W register is loaded with the required four bit code (e.g. 4 to display the character four). Then the ADDWF PCL, F instruction adds this value to the program counter. The program counter now points to the next instruction to execute, which is the RETLW instruction that is offset from the ADDWF instruction. In our example, a W register value of 4 would cause the program to jump to the next instruction plus four, which is the RETLW b'11011000 return instruction. The RETLW instruction (load literal into W register and return from sub-routine) returns from the lookup routine with the value 11011000 in the W register which is the required seven segment code to be sent to the display. 6.3. A Program to Drive a Seven Segment Display The figure shows a PIC interface to a single-digit 7-segment display. Fig. 51 PIC interface to a single 7-segment LCD display The next program will illuminate the 7-segment display with the numbers 0 - 9 in sequence. The appropriate data numbers are extracted from a look-up table and output to Port B. The program makes use of the RETLW instruction together with the ADDWF instruction to create an offset within the look-up table. ;************************************************ ;Appropriate values to illuminate a seven segment display ;with numbers 0 - 9 are extracted from a look-up table ;and output on PortB. ;A software delay is incorporated between displaying ;successive values so that they can be observed. ;This program demonstrates software delays ; and look-up tables. ;************************************************ ; list p=16c84 ; ; ****** PROGRAM EQUATES ****** pc EQU 0x02 status EQU 0x03 porta EQU 0x05 portb EQU 0x06 trisa EQU 0x05 trisb EQU 0x06 temp EQU 0x0c value EQU 0x0d outer EQU 0x0e middle EQU 0x0f inner EQU 0x010 rp0 EQU 5 w EQU 0 f EQU 1 ; ; ****** MAIN PROGRAM ****** ORG 0 start BSF status,rp0 MOVLW 0x00 MOVWF trisb MOVLW 0xfe MOVWF trisa BCF status,rp0 BSF porta,0 MOVLW 0xff MOVWF portb ; ; **** DISPLAY COUNT SEQUENCE *** display MOVLW 0x00 MOVWF value MOVWF value begin MOVF value,w CALL get MOVWF portb CALL wait INCF value BTFSC value,3 BTFSS value,1 GOTO begin GOTO display ; ; **** LOOK UP TABLE FOR VALUES **** get ADDWF pc,f RETLW 0xc0 RETLW 0xf9 RETLW 0xa4 RETLW 0xb0 RETLW 0x99 RETLW 0x92 RETLW 0x82 RETLW 0xf8 RETLW 0x80 RETLW 0x90 ; ; **** TIME DELAY ROUTINE (3 nested loops) **** wait ;delay subroutine MOVLW 0x02 ; -outer loop MOVWF outer wait3 MOVLW 0xff ; -middle loop MOVWF middle wait2 MOVLW 0xff ;-inner loop MOVWF inner wait1 DECFSZ inner,f GOTO wait1 ;-inner loop DECFSZ middle,f GOTO wait2 ; -middle loop DECFSZ outer,f GOTO wait3 ; -outer loop endwait return END 6.4. Example of a port sharing both input and output To save on available digital I/O the ports can be used to both output and input. At one instant a port bit can be configured as an input, the next, as an output. The next program example will make use of the hardware arrangement shown in figure below. Fig. 52 PIC interface to a dual 7-segment LCD display showing port sharing In figure Port B is used as an output port to supply the seven segment code to the display segments. Port A is used as an output and as an input; as an output it supplies the digit select to drive the transistor driver; as an input it reads the state of the two switches A0 and A1. When Port A is driven as an output, the 10K resistors prevent a large current from flowing through a switch if it were to be pressed when Port A is outputing a logic 1. The 100K pull-up resistors ensure that when a switch is open, Port A will read a logic 1. This is a very common arrangement. Now consider the following alternative arrangement where the switch logic is the other way around: Fig. 53 Port sharing with switch senses reversed Port A sees a logic 0 when the switch is open, and a logic 1 when the switch is closed. ; Program to control the LED indicators: list p=16F84 ; ; Program Equates. Pc EQU 0x02 Status EQU 0x03 Porta EQU 0x05 Portb EQU 0x06 Trisa EQU 0x05 ;really 0x85 but page change deals with it all. Trisb EQU 0x06 ;same here. Rp0 EQU 5 ;page change bit in status reg. W EQU 0 ;w destination f EQU 1 ;file destination z EQU 2 ;bit 2 of status register (zero flag). Counter EQU 0x0c ;use first available file register as counter. ; ; Main Program ORG 0x00 GOTO start Start ; Set Up ports A and B ----------------------BSF status,rp0 ;flick to page 1 MOVLW 0x00 MOVWF trisb ;portb outputs MOVLW 0xfc ;PA0 and PA1 outputs MOVWF trisa ;porta inputs BCF status,rp0 ;flick to page 0 ;--------------------------------------------------MOVLW 0xff MOVWF portb ;turn off all segments MOVLW 0x00 ;deselect display MOVWF porta MOVLW 0x00 MOVWF counter ;initialise counter. ;---------------------------------------------------; This is the main part of the program. It will ; continue to output numerals to the LED indicator ; for ever, numbers 0 to 9. ;---------------------------------------------------Loop MOVLW 0x01 MOVWF porta ;activate first character Nxt1 MOVF counter,w ;get current counter value CALL segval ;get segment value MOVWF portb ;copy to led segments Tsta41 BTFSS porta,4 ;test pa4 for press GOTO tsta41 Tsta40 BTFSC porta,4 ;test pa4 for release GOTO tsta40 INCF counter,f ;increment segment counter. MOVLW 0x0a ;we are looking for the 10th count. SUBWF counter,w ;test for counter = 0a hex BTFSS status,z ;if it is equal, initialise counter GOTO nxt1 MOVLW 0x00 MOVWF counter ;is zero so initialise counter. GOTO loop ;go do it all again anyway. ;----------------------------------------------------------Segval ; This is the look up table that decodes the decimal ; values 0 to 9 into segment codes to drive the LEDs. ; The segment code is returned in w register. ;----------------------------------------------------------ADDWF pc,f ;add w to program counter RETLW 0xc0 ;code for 0 RETLW 0xf9 ;code for 1 RETLW 0xa4 ;code for 2 RETLW 0xb0 ;code for 3 RETLW 0X99 ;code for 4 RETLW 0X92 ;code for 5 RETLW 0x82 ;code for 6 RETLW 0xf8 ;code for 7 RETLW 0x80 ;code for 8 RETLW 0x98 ;code for 9 ;----------------------------------------------------------End ;end of assembly program. Appendices Core Features of the PIC16F872 : • High-performance RISC CPU • Only 35 single word instructions to learn • All single cycle instructions except for program branches which are two cycle • Operating speed: DC - 20 MHz clock input DC - 200 ns instruction cycle • 2K x 14 words of FLASH Program Memory 128 x 8 bytes of Data Memory (RAM) 64 x 8 bytes of EEPROM Data Memory • Pinout compatible to the PIC16C72A • Interrupt capability (up to 10 sources) • Eight level deep hardware stack • Direct, indirect and relative addressing modes • Power-on Reset (POR) • Power-up Timer (PWRT) and Oscillator Start-up Timer (OST) • Watchdog Timer (WDT) with its own on-chip RC oscillator for reliable operation • Programmable code-protection • Power saving SLEEP mode • Selectable oscillator options • Low-power, high-speed CMOS FLASH/EEPROM technology • Fully static design • In-Circuit Serial Programming (ICSP) via two pins • Single 5V In-Circuit Serial Programming capability • In-Circuit Debugging via two pins • Processor read/write access to program memory • Wide operating voltage range: 2.0V to 5.5V • High Sink/Source Current: 25 mA • Commercial and Industrial temperature ranges • Low-power consumption: - < 2 mA typical @ 5V, 4 MHz - 20 A typical @ 3V, 32 kHz - < 1 A typical standby current Pin Diagram Peripheral Features: • Timer0: 8-bit timer/counter with 8-bit prescaler • Timer1: 16-bit timer/counter with prescaler, can be incremented during sleep via external crystal/clock • Timer2: 8-bit timer/counter with 8-bit period register, prescaler and postscaler • One Capture, Compare, PWM module - Capture is 16-bit, max. resolution is 12.5 ns - Compare is 16-bit, max. resolution is 200 ns - PWM max. resolution is 10-bit • 10-bit multi-channel Analog-to-Digital converter • Synchronous Serial Port (SSP) with SPI (Master Mode) and I2C (Master/Slave) • Brown-out detection circuitry for Brown-out Reset 1 28 RB7/PGD 2 27 RB6/PGC PA1/AN1 3 26 RB5 PA2/AN2 4 25 RB4 PA3/AN3 5 24 RB3/PGM PA4/TOCK1 6 23 RB2 PA5/AN4/SS- 7 22 RB1 VSS 8 9 21 20 RB0/INT OSC2/CLKOUT 10 19 VSS RCO/T1OSD/TACK1 11 6 12 18 RC7/RX/DT 17 RC6/TX/CK 13 14 16 15 RC5/SDO MCLR/VPP/VTH PA0/AN0 OSC1/CLKIN RC1/TIOSO RC2/CCPI RC3/SCK/SCL VDD RC4/SDI/SDA Appendix A Exercises in programming A number of prepared programmes have been installed in a sub-directory SOURCECODES in your computer. The programmes have the type name .ASM, indicating that they are the source code and are written in assembly language, which is made up of abbreviated words, known as nmemonics. You are supplied with a chart that explains the meaning of the nmemonics used for the PIC-series of microcontrollers manufactured by Microchip of Arizona, USA. The programmes written with nmemonics have to be assembled, that is, converted from assembly language to machine code, which consists of a series of one’s and zero’s. These signals are known as the object code or hex code and, when installed in the memory of the microcontroller, will activate it and cause it to perform the tasks needed to execute the programme. The following assembly language programmes are to be found in the subdirectory SOURCECODES: SQUAWAVE.ASM ONETOONE.ASM Initialisation The microcontroller contains a number of registers located in the RAM data space. Some are special purpose registers that have specific functions within the device. Others are general purpose registers that may be designated by the user for storing variable information. For this microcontroller, the general purpose registers occupy 192 addresses ranging form 20h to 7Fh. Use these addresses to define all the variables or temporary storage memory that you require for your programmes. In the initialisation segment of the programme, the instruction EQU is used to equate a variable with a corresponding address. For example: COUNT EQU 20H NUM1 EQU 21H NUM2 EQU 22H NUM3 EQU 23H ; The counter is located at address 20h It is suggested that the following addresses should be retained for the purposes described: Exercises A. Continuously running, no input LIST P=PIC16F872 #INCLUDE "p16f872.inc" ; list directive to define processor ; processor specific variable definitions __CONFIG _BODEN_ON & _XT_OSC & _WDT_OFF & _PWRTE_ON & _CP_OFF & _LVP_OFF ;***** VARIABLE DEFINITIONS***** count1 equ 20h ;user-defined variable count2 equ 21h ;user-defined variable org 00h InitPorts BCF ;processor reset vector ;initialise ports STATUS, IRP BCF STATUS, RP0 BCF STATUS, RP1 CLRF PORTC BSF STATUS, RP0 MOVLW 0x06 MOVWF ADCON1 MOVLW 0xFF MOVWF TRISA CLRF TRISC BCF STATUS, RP0 START CLRF PORTC BSF PORTC, 0 CALL DELAY CALL DELAY CALL DELAY CALL DELAY BCF PORTC, 0 CALL DELAY CALL DELAY CALL DELAY CALL DELAY GOTO START DELAY MOVLW MOVWF loop1 MOVLW MOVWF loop2 DECFSZ 0xFF count1 0xFF count2 count2, 1 GOTO loop2 DECFSZ count1, 1 GOTO loop1 RETURN end ;directive 'end of program'The purpose of these exercises is to introduce the participant to a simple programme that loops on itself. The output is expressed on one channel of Port B and is visualized on an oscilloscope. It will be seen as a continuous oscillation. Appendix B DAY ONE: SIMPLE PROGRAMMES Exercise A1. A square wave oscillation In the programme, SQUAREWAVE.ASM, Channel 0 on Port B is alternatively SET (=1) and CLEARED (=0). In between these instructions, the programme enters a short delay created by two NOP or one GOTO instruction. ; SQUAREWAVE.ASM START BSF PORTB,0 NOP NOP BCF PORTB,0 GOTO START All instructions, except GOTO, take 1 cycle to complete. GOTO takes two cycles. In order for the high and low half-waves to be of equal duration, there are two additional NOPs after BSF to balance the GOTO instruction following BCF. The complete oscillation takes six cycles to complete. With the 4 MHz crystal used in the trainer, the machine cycle is 1 s. Therefore the period of oscillation is 6 s and the frequency of oscillation is 166 kHz, approximately. The period of oscillation may be checked on the oscilloscope. Exercise B1. Digital input, digital output There are four D-9 sockets placed along one side of the MUM-1. These sockets are connected to Port A, channels 0, 1, 2 and 3, respectively. These are the input sockets. The IM-1 has four D-9 plugs on leads. Connect all of the plugs from IM-1 to the input sockets on the MUM-1. The plugs are also identified as 0, 1, 2 and 3, respectively. For ease of use, connect Plug No 0 to Input Socket No 0, etc. The MUM-1 has a D-15 socket on the side opposite to the input. This D-15 socket is connected to the eight pins of Port C, i.e. pins 0 to 7, respectively. OM-1 has eight LEDs, labeled as 0, 1, 2, etc. When the D-15 plug of OM-1 is inserted into the D-15 socket of the MUM-1, LED No 0 is conveniently connected to pin 0 of Port C, LED No 1 to pin 1, etc. The programme titled ONETOONE checks on Switch No 0 and when it is set to 1, it instructed the microcontroller to light up LED No 0, and so on. ; ONETOONE INIT START BCF PORTC, 0 BCF PORTC, 1 BCF PORTC, 2 BCF PORTC, 3 BCF PORTC, 4 BCF PORTC, 5 BCF PORTC, 6 BCF PORTC, 7 BTFSC PORTA, 0 BSF PORTC,0 BTFSC PORTA, 1 BSF PORTC,1 BTFSC PORTA, 2 BSF PORTC,2 BTFSC PORTA, 3 ; Switch off all the LEDs ; Switch No 0 is on, therefore switch on LED No 0 ; Switch No 1 is on, therefore switch on LED No 1 ; Switch No 2 is on, therefore switch on LED No 2 BSF PORTC,3 GOTO START ; Switch No 3 is on, therefore switch on LED No 3 Exercise B1a: Alter the programme so that LED No 1 turns on when Switch No 0 is set. and LED No 0 turns on when Switch No 1 is set. Install this altered programme into the MUM-1 and let it run. Exercise B1b: Replace OM-1 with OM-2, the traffic lights module. Use the switches to turn on the red, yellow, green and white LEDs as needed. Exercise B1c: Replace OM-3 and OM-4 for the output modules. OM-3 is driven from pin No 0 of Port C. Therefore Switch No 0 may be used to turn on the relay in OM-3 and therefore the lamp of OM4. Alter the programme so that Switch 1 OR Switch 0 turn on the lamp. This is the equivalent of an OR-gate. Only when Switch No 0 and No 1 are both off, i.e. reset to 0, will the lamp be turned off. Exercise B1d: Alter the programme so that the switches No 0 and No 1 are used as inputs to an AND-gate, that is, only when both switches are set to 1, should the lamp turn on. Solution for Exercise B1ds: NOLAMP BCF PORTC, 0 ; Initialise by turning off lamp. ANDGAT BTFSC PORTA, 0 ; If No 0 is off, ignore next instructio BTFSS PORTA, 1 ; if No 1 is ON, the both No 0 and No 1 are ON GOTO NOLAMP ; Turn off lamp, check switches again BSF PORTC, 0 ; turn on lamp GOTO ANDGAT ; check switches again, without turning lamp off. Appendix C The PIC Microcontrollers PIC12C5XX Family 8-Pin, 8-Bit CMOS Microcontrollers PIC12CE5XX Family 8-Pin, 8-Bit CMOS Microcontrollers with EEPROM Data Memory PIC12C67X Family 8-Pin, 8-Bit CMOS Microcontrollers with A/D Converter PIC12CE67X Family 8-Pin, 8-Bit CMOS Microcontrollers with A/D Converter and EEPROM Data Memory PIC14000 Family 28-Pin Programmable Mixed Signal Controller PIC16C5X Family & PIC16HV540 EPROM/ROM-Based 8-Bit CMOS Microcontroller Series PIC16C55X Family EPROM-Based 8-Bit CMOS Microcontrollers PIC16C6X Family 8-Bit CMOS Microcontrollers PIC16X62X Family 18-Pin EPROM-Based 8-Bit CMOS Microcontrollers PIC16C64X & PIC16C66X Families 8-Bit EPROM Microcontrollers with Analog Comparators PIC16CE62X Family 8-Bit CMOS Microcontrollers with Analog Comparators and EEPROM Data Memory PIC16C7X Family 8-Bit CMOS Microcontrollers with A/D Converter PIC16C71X Family 18 Pin, 8-Bit CMOS Microcontrollers with A/D Converter PIC16C43X Family 18/20 Pin, 8-Bit CMOS Microcontrollers with LIN bus PIC16C78X Family Microcontroller with programmable analog including A/D, D/A, operational amplifier, comparators and PSMC. PIC16C7XX Family 8-Bit CMOS Microcontrollers with A/D Converter, for USB, PS/2 and Serial Device Applications PIC16C77X Family 28 and 40-Pin, 8-Bit CMOS Microcontrollers with 12-Bit A/D Converter PIC16F87X Family 28/40-Pin, 8-Bit CMOS FLASH Microcontrollers with 10-bit A/D converter PIC16X8X Family 18-Pin, 8-Bit CMOS FLASH/EEPROM Microcontrollers PIC16F7X Family 28/40-pin 8-bit CMOS FLASH Microcontrollers PIC16C9XX Family 8-Bit CMOS Microcontrollers with LCD Driver PIC17C4X Family High-Performance 8-Bit CMOS EPROM/ROM Microcontrollers PIC17C7XX Family High-Performance 8-Bit CMOS EPROM Microcontrollers PIC18CXXX Family Enhanced Architecture 8-Bit Microcontrollers PIC18FXXX Family Enhanced FLASH Microcontroller with full speed USB and 10-bit A/D PIC16F873 Pinout 1 28 RB7/PGD 2 27 RB6/PGC PA1/AN1 3 26 RB5 PA2/AN2 4 25 RB4 PA3/AN3 5 24 RB3/PGM PA4/TOCK1 6 23 RB2 PA5/AN4/SS- 7 22 RB1 VSS 8 9 21 20 RB0/INT OSC2/CLKOUT 10 19 VSS RCO/T1OSD/TACK1 11 6 12 18 RC7/RX/DT 17 RC6/TX/CK 13 14 16 15 RC5/SDO MCLR/VPP/VTH PA0/AN0 OSC1/CLKIN RC1/TIOSO RC2/CCPI RC3/SCK/SCL VDD RC4/SDI/SDA PIC Instruction Set Summary