The term microcontroller refers to a chip that integrates the microprocessor and
many I/O device interfaces such as A/D and D/A converters. In microcontroller ...
Note 6 Microcontrollers
1
1. Basics of Microprocessor and Microcontrollers microprocessor refers to the central processing unit (CPU) and its onmemory. The term microcontroller refers to a chip that integrates the
The term
chip microprocessor and many I/O device interfaces such as A/D and D/A converters. In microcontroller applications, the amount of memory typically needed is in the order of tens of kilobytes, as opposed to the hundreds of megabytes memory commonly available in desktop applications. As result, the cost of microcontrollers is less compared to general-purpose computers, which makes them good candidates for embedded controller applications.
1.1 Microcontroller structure A microcontroller has three main components: • a central processing unit (CPU) to recognize and carry out program instructions, • input and output circuitry interfaces to handle communications between the microcontroller and the outside world, and • memory to hold the program instructions and data. Digital signals move from one section to another along paths called buses. A bus, in the physical sense, is just a number of conductors along which electrical signals can be carried. It might be tracks on a printed circuit board or wires in a ribbon cable. The data associated with the processing function of the CPU is carried by the data bus. The information for the address of a specific memory location for the accessing of stored data is carried by the address bus. The signals relating to control actions are carried by the control
bus. The following figure shows a typical microcontroller structure.
Figure 1: Typical microcontroller structure.
2
In modern processors, numbers are stored and represented in binary forms made up of between 8 to 64 bits (1 to 8 bytes) – this is referred to as a Word. The data bus is used to transport a word (consisting of 1 to 8 bytes depending on the processor) to or from the CPU and the memory or the I/O interfaces. Buses transport information in a parallel binary form. They consist of a number of wires, each transporting 1 binary digit or bit. To transport this word, fast processor could use a data bus that would have 64 lines for each bit of the word. Alternatively, this word may be transported in parts, e.g. in 2 parts using a 32 bit bus. Data are stored in memory locations (wide enough to store in a binary form, all bits associated with a word). Each memory location is identified through an address which is essentially a binary number. When a memory location is accessed by the processor, the address of this location is placed on the address bus. Thus, the address bus carries signals which indicate where data is to be found and so the selection of certain memory locations or input or output ports. When a particular address is selected by its address being placed on the address bus, only that location is open to the communications from the CPU. The CPU is thus able to communicate with just one location at a time. A computer with an 8bit data bus has typically a 16-bit wide address bus, i.e. 16 wires. This size of address bus enables 216 locations to be addressed. 216 is 65 536 locations and is usually written as 64 K, where K is equal to 1024. The more memory that can be addressed the greater the volume of data that can be stored and the larger and more sophisticated the programs that can be used. The control bus is the means by which signals are sent to synchronize the separate elements. The system clock signals are carried by the control bus. These signals generate time intervals during which system operations can take place, The CPU sends some control signals to other elements to indicate the type of operation being performed, e.g. whether it needs to READ (receive) a signal or WRITE (send) a signal.
1.2 Central Processing Unit (CPU) The CPU is the section of the processor which processes the data, fetching instructions from memory, decoding them and executing them. It consists of a control unit, an arithmetic and logic unit (ALU), and registers. The control unit determines the timing and sequence of operations. It generates the timing signals used to fetch a program instruction from memory and execute it. The Motorola 6800, for example, uses a clock with a maximum frequency of 1 MHz, i.e. a clock period of 1 microsecond, and instructions require between one and twelve clock cycles. Operations involving the microprocessor are reckoned in terms of the number of cycles they take. The ALU is responsible for performing the actual data manipulation. Internal data that the CPU is currently using is temporarily held in a group of registers while instructions are being executed.
3
There are a number of types of register; the number, the size, and types of register vary from one microprocessor to another. The following are common of registers. 1) Accumulator or Working Register. The accumulator register (in PIC it is referred to as W) is where data for an input to the arithmetic and logic unit is temporarily stored. In order for the CPU to be able to access, i.e. read, instructions or data in the memory it has to supply the address of the required memory word using the address bus. When this has been done, the required instructions or data can be read into the CPU using the data bus. Since only one memory location can be addressed at once, temporary storage has to be used when, for example, numbers are combined. For example, in an addition of two numbers, one of the numbers is fetched from one address and placed in the accumulator register while the CPU fetches the other number from the other memory address. Then the two numbers can be processed by the arithmetic and logic section of the CPU. The result is then transferred back into the accumulator register. The accumulator register is thus a temporary holding register for data to be operated on by the arithmetic and logic unit and also, after the operation, the register for holding the results. It is thus involved in all data transfers associated with the execution of arithmetic and logic operations. 2) Status register, or condition code register or flag register. This contains information concerning the result of the latest process carried out in the arithmetic and logic unit. It contains individual bits with each bit having special significance. The bits are called flags. The status of the latest operation is indicated by each flag with each flag being set or reset to indicate a specific status. For example, they can be used to indicate whether the last operation resulted in a negative result, a zero result, a carry output occurs (e.g. the sum of two binary numbers such as 101 and 110 has resulted in a result (1) 011 which for example is bigger than the microprocessor's word size and carries a 1 overflow), an overflow occurs or the program is to be allowed to be interrupted to allow an external event to occur. The following are common flags.
3) Program counter register (PC) or instruction pointer (IP). This is the register used to allow the CPU to keep track of its position in a program. This register contains the address of the memory location that contains the next program instruction. As each instruction is executed the program counter register is updated so that it contains the address of the memory location where the next instruction to be executed is stored. The program counter is incremented each time so that the CPU executes instructions sequentially unless an instruction, such as a JUMP or a BRANCH, changes the program counter out of that sequence.
4
4) Memory address register (MAR). This contains the address of data. Thus, for example, in the summing of two numbers the memory address register is loaded with the address of the first number. The data at the address is then moved to the accumulator. The memory address of the second number is then loaded into the memory address register. The data at this address is then added to the data in the accumulator. The result is then stored in a memory location addressed by the memory address register. 5) Instruction register (IR). This stores an instruction. After fetching an instruction from the memory, the CPU stores it in the instruction register. It can then be decoded and used to execute an operation. 6) General-purpose registers. These may serve as temporary storage for data or addresses and be used in operations involving transfers between various other registers. 7) Stack pointer register (SP). The stack is a set of memory locations that can be used for data storage by programmers. For example, a programmer or an operation may choose or involve placing a number of values or address locations sequentially within the stack. These values may then be sequentially retrieved in a first-in-first-out or a last-infirst-out basis. The contents of the stack pointer register is an address which defines the top of the stack in RAM.
1.3 Memory The memory unit stores binary data and takes the form of one or more integrated circuits. The data may be program instruction codes or numbers being operated on. The size of the memory is determined by the number of wires in the address bus. The memory elements in a unit consist essentially of large numbers storage cells with each cell capable of storing either a 0 or a 1 bit. The storage cells are grouped in locations with each location capable of storing one word. In order to access the stored word, each location is identified by a unique address. Using a 4 address bus, for example, we can have 16 different addresses with each capable of storing one byte, i.e. a group of eight bits. The size of a memory unit is specified in terms of the number of storage locations available. For example, 1 K memory has 210 (= 1024) locations. There are a number of forms of memory unit as follows. 1) ROM. For data that is stored permanently a memory device called a read-only memory (ROM) is used. ROMs are programmed with the required contents during the manufacture of the integrated circuit. No data can then be written into this memory while the memory chip is in the computer. The data can only be read and is used for fixed programs such as the computer operating systems and programs for dedicated microprocessor applications. They do not lose their content when power is removed. 2) PROM. The term programmable ROM (PROM) is used for ROM chips that can be programmed by the user. Once the PROM has been programmed, it cannot be changed.
5
3) EPROM. The term erasable and programmable ROM (EPROM) is used for ROMs that can be programmed and their contents later altered. A typical EPROM chip contains a series of small electronic circuits, cells, which can store charge. The program is stored by applying voltages to the integrated circuit connection pins and producing a pattern of charged and uncharged cells. The pattern remains permanently in the chip until erased by shining ultraviolet light through a quartz window on the top of the device. This causes all the cells to become discharged. The chip can then be reprogrammed. 4) EEPROM. Electrically erasable PROM (EEPROM) is similar to EPROM. Erasure is by applying a relatively high voltage rather than using ultraviolet light. 5) RAM. Temporary data, i.e. data currently being operated on, is stored in a read/write memory referred to as a random-access memory (RAM). Such a memory can be read or written to. When ROM is used for program storage, then the program is available and ready for use when the system is switched on. Programs stored in ROM are termed firmware. Some firmware must always be present. When RAM is used for program storage then such programs are referred to as software. When the system is switched on, software may be loaded into RAM from some other peripheral equipment such as a keyboard or hard disk or floppy disk.
1.4 Input/output The input/output operation is defined as the transfer of data between the microprocessor and the external world. The term peripheral device is used for pieces of equipment that exchange data with a microprocessor system. Because the speed and characteristics of peripheral devices can differ significantly from those of the microprocessor, they are connected via interface chips. A major function of an interface chip is thus to synchronize data transfers between the microprocessor and peripheral device. In input operations the input device places the data in the data register of the interface chip; this holds the data until it is read by the microprocessor. In output operations the microprocessor places the data in the register until it is read by the peripheral. For the microprocessor to input valid data from an input device, it needs to be certain that the interface chip has correctly latched the input data. It can do this by polling an interrupt. With polling, the interface chip uses a status bit set to 1 to indicate when it has valid data. The microprocessor keeps on checking the interface chip until it detects the status bit as 1. The problem with this method is that the microprocessor is having to wait for this status bit to show, With the interrupt method, the interface chip sends an interrupt signal to the microprocessor when it has valid data; the microprocessor then suspends execution of its main program and executes the routine associated with the interrupt in order to read the data.
6
2. Microcontroller Hardware: PIC 16F877 A micro controller is a single-chip integrated circuit (IC) computer. PIC stands for peripheral interface controller. PIC is a trade name given to a series of microcontrollers manufactured by Microchip Technology, Inc. We will use PIC 16G877 chip for the laboratory experiments.
2.1 Overview The PIC 16G877 microcontroller uses what is called a Harvard architecture to achieve a fast execution speed for a given clock rate. As shown in Figure 3, instructions are fetched from program memory using buses that are distinct from the buses used for accessing variables in data memory, I/O ports and other sub-circuits. 9 Every instruction is coded as a single 14-bit word which determines the operation of the CPU, and fetched over a 14-bit wide bus. Figure 3: Harvard architecture. The pin diagram and the block diagram of the PIC 16F877 are shown in Figure 4 and 5, respectively. The PIC 16F877 has five bidirectional input-output ports, named Ports A to E. Port A is 6-bit-wide port while Port E is 3 bits wide. The other parts B, C, and D are all 8-bit ports. Hence the total number of pins is 6+8+8+8+3 = 33 out of 44 pins DIP package of PIC 16F877 chip. The remaining pins are used for VDD (two pins), VSS(two pins), etc. Most of the pins are software configurable for one of multiple functions between general-purpose I/O and peripheral I/O. Using the register in the chip, one function is selected for each pin under software control.
Fig. 4 Pin diagram of PIC 16F877.
7
Figure 5: PIC 16F877/4 block diagram.
8
2.2 Program Memory The PIC 16F877 microcontroller has 8K of program memory. As shown in Figure 5, it has a 13 bit program counter to access 8K of address (213 = 8192 = 8K). The program memory is partitioned into 4 pages as illustrated in Figure 6, with addresses that span a range of 2K each (00-7F,800-FFF,1000-17FF,1800-1FFF).
Figure 6: Program memory organization
Two addresses in the program memory address space are treated in a special way by the CPU. When the CPU starts up from its reset state, its program counter is automatically cleared to zero. This is illustrated in Figure 7 with the content of address 0000 Hex being a goto Mainline instruction. The second special address, 0004, is automatically loaded into the program counter when an interrupt occurs. As shown in Figure 7, a goto IntService instruction is assigned to this address, to cause the CPU to jump to the beginning of the interrupt service routine, located elsewhere in the memory space.
9
Figure 7: Program memory allocation.
2.3 Data Memory, File Register Structure, and Addressing Modes The Central Processing Unit (CPU) is responsible for using the information in the program memory (instructions) to control the operation of the device. Many of these instructions operate on data stored in data memory. To operate on data memory, the Arithmetic Logical Unit (ALU) is required. In addition to performing arithmetical and logical operations, the ALU specifies the current state of the operation by setting and controlling the value of bits within a special register referred to as the STATUS register. Data memory is made up of 8-bit locations that can be written to, updated, and retrieved any number of times. The data memory is made of two types of registers: (1) the Special Function Registers (SFR), and (2) the General Purpose Registers (GPR). The SFRs control the operation of the device, while GPRs are the general area for data storage. The data memory is banked for both the GPR and SFR areas. The GPR area is banked to allow greater than 96 bytes of general purpose RAM to be addressed. SFRs are for the registers that control the peripheral and core functions. Banking requires the use of control bits for bank selection. These control bits are located in a special SFR register referred to as the STATUS Register. The following figure shows the data memory map organizations, this organization is device dependent. 10
Figure 8: Organization and direct addressing of data memory.
Special Function Registers (SFR) There are many SFRs associated with the various functions and operations of the PIC microcontroller. The reader is referred to the manual for PIC Mid-range MCU Family for further information. Some of the important ones are discussed in this section. W Register
W, the working register, is used as an intermediary storage source for data storage by many instructions (the source of an operand). It may also serve as the destination for the result of the instruction execution. It serves a function similar to that of the accumulator in many other microcontrollers. STATUS Register
The state of results from execution of each instruction is captured by the STATUS register. The contents of the STATUS register are summarized in Figure 9. Its information content includes the C, or carry, bit. When two 8-bit numbers (operands) are added together, a 9-bit result can occur. The ninth bit is placed in the carry bit. The DC, or digit carry, bit signals that a carry from the lower 4 bits occurred during an 8bit addition. This digit carry bit is useful when adding binary-coded-decimal (BCD). The Z, or zero, bit is affected by the execution of many (but not all) arithmetic and logic instructions. Before testing the Z bit following an instruction, it should be ascertained
11
whether the instruction is indeed one of the group that affects the Z bit. For example, the instruction DECF can be used to decrement a variable in RAM, setting the Z bit if the result is zero and clearing it otherwise. The reset status bits, NOT-TO and NOT-PD, are used in conjunction with the PIC's sleep mode. The microcontroller can put itself to sleep to save power during intervals when it has nothing to do. It can be awakened by the occurrence of any of three kinds of events. Upon wakeup, the CPU can check these two reset status bits to determine which kind of event awakened it and then respond accordingly. In direct addressing, the selection of data memory page is performed through RP0 and RP1 as indicated by Figures 8. Similarly, the bit IRP is issued for memory access in indirect addressing. The role of IRP, RP0 and RP1 are further discussed in the following section.
12
Figure 9: STATUS Register SFR and INDF Registers
In direct addressing, seven bits from the instruction and the RP0 and RP1 bits of the STATUS register are used for selection of the memory bank and to indicate the address of memory locations within each bank. Some registers are considered to be so important they are replicated in all banks and may be addressed by using only 7 bits, irrespective of the setting of RP0 and RP1 as shown in Figure 10. Every instruction that can employ the direct addressing mode can, as an alternative, employ the indirect addressing mode. In this alternative mode, the 8 bits of the full address is first written into File Select Register (FSR), and a bit associated with the memory banks used is written into the bit IRP of the STATUS registered. In indirect 13
addressing, then the contents of IRP and the FSR are subsequently loaded into a register referred to as INDF. A subsequent direct access of INDF will actually access the register file. The indirect and direct addressing operations are shown in Figure 11.
Figure 10: DATA Memory Registers
14
Figure 11: Addressing STACK and the STACK Pointer
The program counter is supported by an eight-level stack. When an interrupt occurs, the program counter is automatically pushed onto the stack. Since PIC microcontroller programs are normally designed so further interrupts remain disabled while any interrupt source is being serviced, only one of the eight stack locations is needed to deal with the interrupt return address. The other seven levels can be divided between nested subroutines within the interrupt service routine and nested subroutines within the mainline program. Each time a subroutine is called by a call instruction located at address n in the program memory, the return address (i.e., n + l) is pushed onto the stack. If from within this subroutine another subroutine is called, its return address is pushed onto the stack. This can be repeated as this subroutine calls another, which calls another, which calls another, etc. As each subroutine terminates, its return address is popped off the stack and loaded into the program counter. The return addresses that were pushed onto the stack are popped off of the stack in reverse order. PCLATCH
The final feature of the CPU registers to be discussed is the role of PCLATH. Note that some instructions such as CALL, contain allow specification of 11 bits for moving to a new address. The program counter however needs 13-bits. Bits from a special register referred to as Program Counter Latch (PCLATCH) are used to indicate the remaining two bits of the full 13 bit address. Other Special Function Registers
The PIC microcontroller has number of built in peripheral devices that provide special functionalities such as timers, A/D converters, and generators of signals referred to as PWM that can be used for driving electrical motors. Associated with each of these perieral devices are special registers through which a user can set and specify their mode of operation. For more information on these peripheral functions and their registers refer to the PIC manual.
15
3. Microcontroller Software: PIC 16F877 Software is the term used for the instructions that tell a microprocessor or microcontroller what to do. The collection of instructions that a microprocessor will recognize is its instruction set. The form of the instruction set depends on the microprocessor concerned. The series of instruction that is needed to carry out a particular task is called a program. The microprocessors and microcontrollers recognize instructions in binary format only. These are referred to as machine code instructions. For example, the 14 bit instruction that would put the PIC microcontroller to suspend operation or “sleep” is 00 0000 0110 0011 in binary or 0063 in Hexademimal form. It is difficult to program computers in binary codes, therefore programmers use symbols that are later translated into binary codes. Symbols that have a one-to-one relation to binary code instructions are referred to assembler codes or mnemonics. For example, the PIC symbol corresponding to the “sleep” mode is SLEEP which is much easier to remember and understand than 00 0000 0110 0011.
3.1 Instruction set summary Each PIC 16F877 instruction is a 14-bit word, divided into an opcode which specifies the instruction type and one or more operand which specifies the sources and destinations of the data required by the instruction. The PIC 16F877 instruction set is summarized in Table 1, which is followed by the instruction description. The instruction set is highly orthogonal and is grouped into three basic categories; byteoriented, bit-oriented, and literal and control operations. For byte-oriented operations, ‘f’ represents a file register designator and ‘d’ represents a destination designator. The file register designator specifies which file register is to be used by the instruction. The destination designator specifies where the result of the operation is to be place. If ‘d’ is zero, the result is placed in the W register. If ‘d’ is one, the result is placed in the file register specified in the instruction. For bit-oriented operations, ‘b’ represents a bit field designator which selects the number of the bit affected by the operation, while ‘f’ represents the address of the file in file in which the bit is located. For literal and control operations, ‘k’ represents an eight or eleven bit constant or literal value.
16
Table 1 PIC 16F877 Instruction set
17
Instruction descriptions:
18
19
20
21
22
3.2 Microcontroller Program A microcontroller mainline program typically has the following structure:
The mainline program begins execution when the PIC comes out of reset. It continues running until one of the PIC's interrupt sources requests service. At that point the execution of the mainline code is temporarily suspended. The CPU begins the execution of the interrupt service routine by automatically loading the program counter with 0004 Hex. At the completion of the interrupt service routine, the CPU returns to where it left off in the mainline program.
23
An assembly language program should be considered as a series of instructions to an assembler which will then produce the machine code program. A program written in assembly language consists of a sequence of statements, one statement per line. A statement contains from one to four sections or fields, i.e. Label Opcode Operand Comment The label is used for identifying the instruction line for use with jump statements such as GOTO. The next field is the Opcode that is the instruction or mnemonic for performing a specific operation. The data following the instruction (opcode) is referred to as the operand. The information included in the operand field depends on the opcode preceding it and the addressing mode used. It gives the address of the data to be operated on by the process specified by the opcode. This field may be empty if the instructions given by the opcode do not need any data or address. Numerical data in this field may be hexadecimal (H), decimal (D), or binary (B). With PIC a hexadecimal number such as FF is denoted by H’FF’. Decimal and binary numbers are correspondingly defined by using D or B. The comment field is optional. The comment field is ignored by the assembler during the production of the machine code program. A special symbol is used to indicate the beginning or end of a field, the symbols used depending on the microprocessor machine code assembler concerned. With the PIC family of processors, spaces are used after a label, a space after the op-code, commas between entries in the operand address field and a semicolon before a comment. For example: testline (Label)
btfss Status, Z; (Opcode) (Operand)
test for zero flag (Comment)
In addition, the opcode field may contain directives to the assembler. These are termed pseudo-operations since they appear in the op-code field but are not translated into instructions in machine code. They may define symbols, assign programs and data to certain areas of memory, generate fixed tables and data, indicate the end of the program, etc. Common assembly directives are ORG EQU
This defines the starting memory address. Define a symbol for a numerical value.
24
The following is an example of PIC 16F877 program, which is used to toggle all the bits on port D on and off.
; initialise port to safe conditions start
25
4. Microcontroller Development Tool: 877-TB The 877-TB (target board) enable users to program the PIC 16F877 microcontroller via a serial port on a PC and then run the program at the flick of a switch. The board holds all circuitry necessary to program and run programs developed of the PIC 16F877 microcontroller. Onboard LEDs indicate the current operation (Running a program, Loading a program or Idle), which is controlled using tow switches: a pushbutton to start and stop programs and a slide-switch to switch between the programming and operation mode. As shown in Figure 12, the 877-TB has a variety of connectors fitted, which allow users to connect their own applications. All available I/O lines are assessable via screw terminals located around the perimeter of the PCB. Each terminal is identified on the PCB and is designated with its respective pin on the PIC 16F877. The Board is connected to a serial port of an IMB compatible PC running Microsoft Widows 95 or above, or Window NT4.0 or above. Connect the board to the serial port, as shown in Figure 13, while make sure the PRG/RUN switch is in the PRG position.
Figure 12: 877-TB layout.
26
Figure 13. Connection among the Board and a PC. The communication software consists of a single executable file, which is used to load programs developed using Microchips assembler to the 877-TB via a serial port. The following figure shows the interface, once starting the communication software. More details regarding the use of the software will be illustrated in the lab session.
Figure 14: Interface of the communication software.
27