micro controller & micro processor

111
1/28/13 1 Microprocessor and Microcontroller 66428 Dr. Sufyan Samara Course Outline Objec>ves: Provides and overview of Microcontroller architecture, Address modes and instruc>on sets. Subrou>nes and interrupts. Handling soKware tools including IDE, editor, assembler, simulator and C compiler. Interface techniques including parallel, serial, >mer, and analogue peripheral interface. Course outline: THE MICROPROCESSOR, THE MICROCONTROLLERS, AND THIER ARCHITECTUREs Internal Microprocessor Architecture Internal Microcontroller Architecture Overview of memories The Microchip PIC family Microcontrollers Program memory and the stack, Memory and memory map Data and Special Func>on register memory The Configura>on Word Some issues of >ming, pipelining, power up, and reset. Parallel ports and the clock oscillator Microchip instruc>on set and the MPLAB Working with C programs and simulators Working with ADC and DAC Serial and parallel interfaces

Upload: ola-mashaqi-an-najah-national-university

Post on 22-Nov-2014

1.536 views

Category:

Education


13 download

DESCRIPTION

 

TRANSCRIPT

  • 1. 1/28/13 1 Microprocessor and Microcontroller 66428 Dr. Sufyan Samara Course Outline Objec>ves: Provides and overview of Microcontroller architecture, Address modes and instruc>on sets. Subrou>nes and interrupts. Handling soKware tools including IDE, editor, assembler, simulator and C compiler. Interface techniques including parallel, serial, >mer, and analogue peripheral interface. Course outline: THE MICROPROCESSOR, THE MICROCONTROLLERS, AND THIER ARCHITECTUREs Internal Microprocessor Architecture Internal Microcontroller Architecture Overview of memories The Microchip PIC family Microcontrollers Program memory and the stack, Memory and memory map Data and Special Func>on register memory The Congura>on Word Some issues of >ming, pipelining, power up, and reset. Parallel ports and the clock oscillator Microchip instruc>on set and the MPLAB Working with C programs and simulators Working with ADC and DAC Serial and parallel interfaces
  • 2. 1/28/13 2 Course outline cont. Microprocessors The Intel 8088/8086 Architecture, addressing modes and memory mapping Address modes and instruc@on sets Data-Addressing Modes Program Memory-Addressing Modes and stacks Intel Instruc>on set and the MASM assembler Working with @me: interrupts, counters and @mers Basic interrupt processing Working with interrupts The main idea counters and >mers Working with >mers A look over the larger microcontrollers 16- bit microcontrollers 32-bit microcontrollers Textbook: Microchip PIC mid range manual from the microchip web site Exams First Exam 24/2/2013 Second Exam 31/3/2013 Project Deadline 22/4/2013 Final Exam decided by the UNI
  • 3. 1/28/13 3 Microcontroller architecture. Address modes and instruc>on sets. Subrou>nes and interrupts. Handling soKware tools including IDE, editor, assembler, simulator and C compiler. Interface techniques including parallel, serial, >mer, and analogue peripheral interface. History In the year 1969, rst microprocessor was born. In 1971 Intel obtained the right to sell this integrated circuit. Before that Intel bought the license from the Japanese company BUSICOM company which rst came with the idea. During that year, a microprocessor called the 4004 appeared on the market. The rst 4-bit microprocessor with the speed of 6000 opera>ons per second. Not long aKer that, American company CTC requested from Intel and Texas Instruments to manufacture 8-bit microprocessor. In April 1972 the rst 8-bit microprocessor called the 8008 appeared on the market. It was able to address 16Kb of memory, had 45 instruc>ons and the speed of 300 000 opera>ons per second. That microprocessor was the predecessor of all todays microprocessors. In April 1974, Intel launched 8-bit processor called the 8080. Address 64Kb of memory, had 75 instruc>ons and ini>al price was $360. In another company called Motorola launched 8-bit microprocessor 6800. At the WESCON exhibi>on in the USA in 1975, MOS Technology announced that it was selling processors 6501 and 6502 at $25 each. In response to the compe>tor, both Motorola and Intel cut the prices of their microprocessors to $69.95. Due to low price, 6502 became very popular so it was installed into computers such as KIM-1, Apple I, Apple II, Atari, Commodore, Acorn, Oric, Galeb, Orao, Ultra and many others. Soon appeared several companies manufacturing the 6502 (Rockwell, Sznertek, GTE, NCR, Ricoh, Commodore took over MOS Technology). Other companies such as Zilog Inc have their own microprocessor. In 1976 Zilog announced the Z80. When designing this microprocessor Faggin The new processor was compa>ble with the 8080, i.e. it was able to perform all the programs wriien for the 8080. Apart from that, many other features was included so that the Z80 was the most powerful microprocessor at that >me. It was able to directly address 64Kb of memory, had 176 instruc>ons, a large number of registers, built in op>on for refreshing dynamic RAM memory, single power supply, greater opera>ng speed etc. The Z80 was a great success and everybody replaced the 8080 by the Z80. In 1976 Intel came up with an upgraded version of 8-bit microprocessor called the 8085. However, the Z80 was so much beier that Intel lost the baile. Even though a few more microprocessors appeared later on the market (6809, 2650, SC/MP etc.), everything was actually decided. There were no such great improvements which could make manufacturers to change their mind, so the 6502 and Z80 along with the 6800 remained chief representa>ves of the 8-bit microprocessors of that >me.
  • 4. 1/28/13 4 uProcessors < uControllers < SoCs Microprocessors (uP) dier from microcontrollers (uC) uC: suited for controlling I/O devices that requires a minimum component count uP: suited for processing informa>on in computer systems Instruc>on sets: uP: processing intensive powerful addressing modes instruc>ons to perform complex opera>ons & manipulate large volumes of data processing capability of MCs never approaches those of MPs large instruc>ons -- e.g., 80X86 7-byte long instruc>ons uC: cater to control of inputs and outputs instruc>ons to set/clear bits boolean opera>ons (AND, OR, XOR, NOT, jump if a bit is set/cleared), etc. Extremely compact instruc>ons, many implemented in one byte (Control program must oKen t in the small, on-chip ROM) Hardware & Instruc>onset support: uC: built-in I/O opera>ons, event >ming, enabling & senng up priority levels for interrupts caused by external s>muli uP: usually require external circuitry to do similar things (e.g, 8255 PPI, 8259 etc)
  • 5. 1/28/13 5 Microprocessors (uP) and microcontrollers (uC) Bus widths: uP: very wide large memory address spaces (>4 Gbytes) lots of data (Data bus: 32, 64, 128 bits wide) uC: narrow rela>vely small memory address spaces (typically kBytes) less data (Data bus typically 4, 8, 16 bits wide) Clock rates: uP very fast (> 1 GHz) uC: Rela>vely slow (typically 10-20 MHz) since most I/O devices being controlled are rela>vely slow Cost: uPs expensive (oKen > $100) uCs cheap (oKen $1 - $10) 4-bit: < $1.00 8-bit: $1.00 - $8.00 16-32-bit: $6.00 - $20.00
  • 6. 1/28/13 6 A generic microcontroller System-on-a-chip Compare to lab-on-a-chip ideas
  • 7. 1/28/13 7 Example: PSoC (Cypress) Example of circuit No>ce the processor/controller What does it do?
  • 8. 1/28/13 8 Find the microcontroller
  • 9. 1/28/13 9 Can you guess what this circuit does?
  • 10. 1/28/13 10 Memory types Vola>le. This is memory that only works as long as it is powered. It loses its stored value when power is removed, but can be used as memory for temporary data storage. commonly been called RAM (Random Access Memory) Non-vola>le. This is memory that retains its stored value even when power is removed. hard disk In an embedded system it is achieved using non-vola>le semiconductor memory, commonly been called ROM (Read-Only Memory) An ideal memory reads and writes in negligible >me, retains its stored value indenitely, occupies negligible space and consumes negligible power. In prac>ce no memory technology meets all these happy ideals Memory cont. Sta>c RAM (SRAM) Each memory cell is designed as a simple ip-op. Data is held only as long as power is supplied (vola>le). Consume very liile power, and can retain its data down to a low voltage (around 2 V). Each cell taking six transistors, SRAM is not a high-density technology. EPROM (Erasable Programmable Read-Only Memory) erased by exposing it to intense ultraviolet light. each memory cell is made of a single MOS transistor (very high density and robust) Within the transistor there is embedded a oa>ng gate. Using a technique known as hot electron injec>on (HEI), the oa>ng gate can be charged. When it is not charged, the transistor behaves normally and the cell output takes one logic state when ac>vated. When it is charged, the transistor no longer works properly and it no longer responds when it is ac>vated. The charge placed on the oa>ng gate is totally trapped by the surrounding insulator. Hence EPROM technology is non-vola>le. Requires quartz window and ceramic packaging. As a technology, EPROM has now almost completely given way to Flash
  • 11. 1/28/13 11 Memory cont. EEPROM (Electrically Erasable Programmable Read-Only Memory) Uses oa>ng gate technology. This is known as NordheimFowler tunnelling (NFT). With NFT, it is possible to electrically erase the memory cell as well as write to it. To allow this to happen, a number of switching transistors need to be included around the memory element itself, so the high density of EPROM is lost. EEPROM is non-vola>le Because the charge on the oa>ng gate is totally trapped by the surrounding insulator Write and erase byte by byte. Flash A further evolu>on of oa>ng-gate technology. can only erase in blocks. Non-vola>le Organizing memory Two important buses Address Data Two architectures Von Neumann architecture One bus for data and one for address Serve for memory and others (program and I/O) Disadvantages: uses the same data bus for all sizes (areas) of memory Shared between many things, can be used for one thing at a >me The Harvard architecture Every memory area gets its own address bus and its own data bus Disadvantages: Complex Data and program are separated (tables inside program memory cant be treated as data)
  • 12. 1/28/13 12 (a) The Von Neumann way. (b) The Harvard way uC Many families Each family is generally the same processor core with dierent peripherals combina>on and dierent memory size. One core might be 8-bit with limited power, another 16-bit and another a sophis>cated 32-bit machine. Because the core is xed for all members of one family, the instruc>on set is xed and users have liile diculty in moving from one family member to another.
  • 13. 1/28/13 13 Microcontroller packaging and appearance Usually plas>c or ceramic are used as the packaging material. Interconnec>on with the outside world is provided by the pins on the package Dual-in-line package (DIP), with its pins arranged in two rows along the longer sides of the IC, the pin spacing being 0.1 inches Other incudes: Pin grid array (PGA), leadless chip carrier (LCC) packages, Small-outline integrated circuit (SOIC), Plas>c leaded chip carrier (PLCC) packages, plas>c quad at pack(PQFP), and thin small-outline packages (TSOP) Used when number of pins is very large compared to IC size A collec>on of microprocessors and microcontrollers old and new. From leK to right: PIC 12F508, PIC 16F84A, PIC 16C72, Motorola 68HC705B16, PIC 16F877, Motorola 68000 Microchip and the PIC microcontroller Has a wide range of dierent families 8-bit, 16-bit, 32-bit All 8-bit PIC microcontrollers are lowcost, self-contained, pipelined, RISC, use the Harvard structure, have a single accumulator (the Working, or W, register), with a xed reset vector. Microchip oer 8-bit microcontrollers with four dierent prexes, 10-, 12-, 16-, and 18-, for example 10F200, or 18F242. We call each a Series, for example 12 Series, 16 Series, 18 Series. Each Series is iden>ed by the rst two digits of the device code. Leiers are used as follows: The C insert implies CMOS technology The F insert indicates incorpora>on of Flash memory technology (s>ll using CMOS as the core technology). An A aKer the number indicates a technological upgrade on the rst issue device. An X indicates that a certain digit can take a number of values. For example, the 16C84, the 16F84, and the 16F84A. In some cases microcontrollers of one Series can fall into more than one family.
  • 14. 1/28/13 14 Comparison of 8-bit PIC families Every member of any one family shares the same core architecture and instruc>on set. The processing power is dened to some extent by the parameters quoted, for example the instruc>on word size, and the number of instruc>ons. An introduc>on to PIC microcontrollers using the Baseline Series We will look at the PIC 12F508/509. The only dierence between the 508 and 509 is that the laier has slightly larger program and data memories.
  • 15. 1/28/13 15 The architecture of the 12F508 The architecture of the 12F508 cont. As this microcontroller is a RISC computer, each instruc>on word must carry not only the instruc>on code itself, but also any address or data informa>on needed. Depending on the instruc>on itself, ve bits of the instruc>on word may carry address informa>on and hence be sent down the Direct Addr bus to the address mul>plexer (Addr MUX). Eight bits of the instruc>on word may carry a data byte that is to be used as literal data for the execu>on of that instruc>on. This goes to the mul>plexer (MUX), which feeds into the ALU. Finally, there is the instruc>on data itself, which feeds into the Instruc>on Decode and Control unit. A Power-on Reset func>on detects when power is applied and holds the microcontroller in a Reset condi>on while the power supply stabilizes. The MCLR input can be used to place the CPU in a Reset condi>on and to force the program to start again. An internal clock oscillator (Internal RC OSC) is provided so that no external pins whatsoever need be commiied to this func>on. External oscillator connec>ons can, however, be made, using input/output pins GP4 and GP5. The oscillator signal is condi>oned for use through the microcontroller in the Timing Genera>on unit. The Watchdog Timer is a safety feature, used to force a reset in the processor if it crashes.
  • 16. 1/28/13 16 The PIC 16F877 We will concentrate on just one device, the PIC 16F877 A good range of features and allows most of the essen>al techniques to be explained. It has a set of serial ports built in, which are used to transfer data to and from other devices, as well as analogue inputs, which allow measurement of inputs such as temperature. All standard types of microcontrollers work in a similar way, so analysis of one will make it possible to understand all the others. MCU The microcontroller contains the same main elements as any computer system: Processor Memory Input/Output In a PC, these are provided as separate chips, linked together via bus connec>ons on a printed circuit board, but under the control of the microprocessor (CPU). A bus is a set of lines which carry data in parallel form which are shared by the peripheral devices. The system can be designed to suit a par>cular applica>on, with the type of CPU, size of memory and selec>on of input/output (I/O) devices tailored to the system requirements. In the microcontroller, all these elements are on one chip. This means that the MCU (microcontroller) for a par>cular applica>on must be chosen from the available range to suit the requirements.
  • 17. 1/28/13 17 Execu>on, revisited Memory, revisited
  • 18. 1/28/13 18 Input and Output Ports are based on a data register, and set of control registers, which pass the data in and out in a controlled manner, oKen according to a standard protocol (method of communica>on). There are two main types of port: (a) Parallel port, the data is usually transferred in and out 8 bits at a >me (b) Serial port, the data is transmiied 1 bit at a >me on a single line. Poten>ally, the parallel port is faster, but needs more pins; on the other hand, the port hardware and driver soKware are simpler, because the serial port must organize the data in groups of bits, usually 1 byte at a >me, or in packets, as in a network PIC 16F877 Architecture Microcontrollers contain all the components required for a processor system in one chip: a CPU, memory and I/O. A complete system can therefore be built using one MCU chip and a few I/O devices such as a keypad, display and other interfacing circuits.
  • 19. 1/28/13 19 Some members of the PIC mid-range family Some members of the PIC mid-range family cont.
  • 20. 1/28/13 20 An architecture overview of the PIC16F877 PIC 16F877 Pin IN/Out The chip can be obtained in dierent packages, such as conven>onal 40-pin DIP (Dual In-Line Package), square surface mount or socket format. Most of the pins are for input and output, and arranged as 5 ports: port A (5 pins), port B(8), C(8), D(8) and E(3), giving a total of 32 I/O pins. These can all operate as simple digital I/O pins, but most have more than one func>on. The mode of opera>on of each is selected by ini>alizing various control registers within the chip. Note, in par>cular, that Ports A and E become ANALOGUE INPUTS by default (on power up or reset), so they have to set up for digital I/O if required.
  • 21. 1/28/13 21 PIC 16F877 Pin IN/Out cont. Port B is used for downloading the program to the chip ash ROM (RB6 and RB7), and RB0 and RB4RB7 can generate an interrupt. Port C gives access to >mers and serial ports. Port D can be used as a slave port, with Port E providing the control pins for this func>on. PIC 16F877 Pin IN/Out cont. The chip has two pairs of power pins (VDD=5 V nominal and Vss =0 V) (11,12 or 31, 32), and either pair can be used. The chip can work down to about 2 V supply, for baiery and power-saving opera>on. A low-frequency clock circuit using only a capacitor and resistor to set the frequency can be connected to CLKIN, or a crystal oscillator circuit can be connected across CLKIN and CLKOUT. MCLR is the reset input; when cleared to 0, the MCU stops, and restarts when MCLR=1. This input must be >ed high allowing the chip to run if an external reset circuit is not connected. It is usually a good idea to incorporate a manual reset buion in all but the most trivial applica>ons.
  • 22. 1/28/13 22 PIC 16F877 Pin IN/Out cont. PIC 16F877 Block Diagram
  • 23. 1/28/13 23 PIC16F877 block diagram cont. The main program memory is ash ROM, which stores a list of 14-bits instruc>ons. Instruc>ons are fed to the execu>on unit, and used to modify the RAM le registers. The le register include special control registers, the port registers and a set of general purpose registers which can be used to store data temporarily. A separate working register (W) is used with the ALU (Arithme>c Logic Unit) to process data. Various special peripheral modules provide a range of I/O op>ons PIC16F877 block diagram cont. There are 512 RAM File Register addresses (01FFh), which are organized in 4 banks (03), each bank containing 128 addresses. The default (selected on power up) is Bank 0 which is numbered from 0 to 7Fh, Bank 1 from 80h to FFh and so on. These contain both Special Func>on Registers (SFRs), which have a dedicated purpose, and the General Purpose Registers (GPRs). The le registers are mapped as seen in the next slid. The SFRs may be shown in the block diagram as separate from the GPRs, but they are in fact in the same logical block, and addressed in the same way. Deduc>ng the SFRs from the total number of RAM loca>ons, and allowing for some registers which are repeated in more than one bank, leaves 368 bytes of GPR (data) registers.
  • 24. 1/28/13 24 Assume the following circuit
  • 25. 1/28/13 25 Test Programs The rst test program, will simply light a set of LEDs connected to Port B in a binary count sequence, by incremen>ng Port B data register. Show in simulator (pr) The second test program, will use two input push buions aiached to Port D to control the output (start, stop and reset). The program will also include a delay so that the output is slower, and visible to the user. Detailed design of the interfacing will be covered later. A simple CR clock will be used, which is set to 40 kHz (C 4.7 nF, R 5 k (preset), CR 25 s). This will give an instruc>on execu>on >me of 100 s. Show in Simulator The PIC Program Both programs are wriien as a source code (a simple text le) on a PC host computer. Compiler is MPLAB (downloadable from www.microchip.com). The instruc>ons are selected from the pre-dened PIC instruc>on set (see next slid) according to the opera>onal sequence required. The source code le is saved as PROGNAME.ASM. The source code is assembled (converted into machine code) by the assembler program MPASM, which creates the list of binary instruc>on codes. As this is normally displayed as hexadecimal numbers, it is saved as PROGNAME.HEX. The hex le is then downloaded to the PIC chip from the PC by placing the MCU in a programming unit which is aiached to the serial port of PC, or by connec>ng the chip to a programmer aKer nng it in the applica>on board (in-circuit programming). The hex code is transferred in serial form via Port B into the PIC ash program memory. A list le is created by the assembler, which shows the source code and machine code in one text le.
  • 26. 1/28/13 26 First Test Program 1
  • 27. 1/28/13 27 First Test Program cont. The program lis>ng includes the source code at the right, with source line numbers, the hex machine code and the memory loca>on where each instruc>on is stored (00000004). Direc>ve are not converted into machine code (e.g. PROCESSOR and END) The 877 has 8k of program memory, that is, it can store a maximum 8192 14-bit instruc>ons. The reset vector (the execu>on start address) is 0x000. Let us look at a typical instruc>on to see how the program instruc>ons are executed. Source code: MOVLW 05A Hex code: 305A (4 hex digits) Binary code: 0011 0000 0101 1010 (16 bits) Instruc>on: 11 00xx kkkk kkkk (14 bits) The instruc>on means: Move a Literal (given number, 5Ah) into the Working register. The source code consists of a mnemonic MOVLW and operand 05A. This assembles into the hex code 305A, and is stored in binary in program memory as 11 0000 0101 1010. First Test Program cont. In the instruc>on set table, shown previously, it is seen that the rst 4 bits (11 00) are the instruc>on code, the next two are unused (xx, appearing as 00 in the binary code) and the last 8 are the literal value (5A). The literal is represented as kkkk kkkk since it can have any value from 00000000 to 11111111 (00FF). The format of other instruc>ons depends mainly on the number of bits required for the operand (data to be processed). The number of op-code bits can vary from 3 to all 14, depending on the number of bits needed for the operand. This is dierent from a conven>onal processor, such as the Pen>um, where the op-code and operand are each created as a whole number of bytes. The PIC instruc>on is more compact, as is the instruc>on set itself, for greater speed of opera>on. This denes it as a RISC (Reduced Instruc>on Set Computer) chip.
  • 28. 1/28/13 28 Second test program The second program contains many of the basic program elements, see next slide. It contains the machine code, memory address and list le line number as before. There are addi>onal comments to aid program analysis and debugging. Note that two types of labels are used in program to represent numbers. Label equates are used at the top of the program to declare labels for the le registers which will be used in the program. Address labels are placed in the rst column to mark the des>na>on for GOTO and CALL instruc>ons.
  • 29. 1/28/13 29 Chip Congura>on Word The assembler direc>ve __CONFIG is included at the top of the program, which sets up aspects of the chip opera>on which cannot be subsequently changed without reprogramming. The congura>on word is a special area of program memory located outside the normal range (address 2007h) and stores chip congura>ons such as the clock type. Done by loading the congura>on bits with a suitable binary code (see next slide). Chip Congura>on Word
  • 30. 1/28/13 30 CODE PROTECTION Normally, the program machine code can be read back to the programming host computer, be disassembled and the original source program recovered. This can be prevented if commercial or security considera>ons require it. The code protec>on bits (CP1:CP0) disable reads from selected program areas. Program memory may also be wriien from within the program itself, disabled via the WRT bit. Data EEPROM may also be protected from external reads in the same way via the CPD bit, while internal read and write opera>ons are s>ll allowed, regardless of the state-of-the code protec>on bits. bit 13-12, bit 5-4 CP1:CP0: FLASH Program Memory Code Protec>on bit, All of the CP1:CP0 pairs have to be given the same value to enable the code protec>on scheme listed. 11 = Code protec>on o 10 = 1F00h to 1FFFh code protected 01 = 1000h to 1FFFh code protected 00 = 0000h to 1FFFh code protected IN-CIRCUIT DEBUGGING In-circuit debugging (ICD) allows the program to be downloaded aKer the chip has been ied in the applica>on circuit, and allows it to be tested with the real hardware. The normal debugging techniques of single stepping, breakpoints and tracing can be applied in ICD mode.
  • 31. 1/28/13 31 LOW VOLTAGE PROGRAMMING Normally, when the chip is programmed, a high voltage (1214 V) is applied to the PGM pin (RB3). To avoid the need to supply this voltage during in-circuit programming (e.g. during remote reprogramming), a low-voltage programming mode is available. Using this op>on means that RB3 is not then available for general I/O func>ons during normal opera>on. POWER-UP TIMER When the supply power is applied to the programmed MCU, the start of program execu>on should be delayed un>l the power supply and clock are stable, otherwise the program may not run correctly. The power-up >mer may therefore be enabled (PWRTE 0) as a maier of rou>ne. It avoids the need to reset the MCU manually at start up, or connect an external reset circuit, as is necessary with some microprocessors. At a clock frequency of 4 MHz, this works out to 256s.
  • 32. 1/28/13 32 BROWN-OUT RESET Brown out refers to a short dip in the power-supply (PSU) voltage, caused by mains supply uctua>on, or some other supply fault, which might disrupt the program execu>on. If the Brown-Out Detect Enable bit (BODEN) is set, a PSU glitch of longer than about 100 s will cause the device to be held in reset un>l the supply recovers, and then wait for the power-up >mer to >me out, before restar>ng. The program must be designed to recover automa>cally. WATCHDOG TIMER The watchdog >mer is designed to automa>cally reset the MCU if the program malfunc>ons, by stopping or genng stuck in loop. This could be caused by an undetected bug in the program, an unplanned sequence of inputs or supply fault. A separate internal oscillator and counter automa>cally generates a reset about every 18 ms, unless this is disabled in the congura>on word. If the watchdog >mer is enabled, it should be regularly reset by an instruc>on in the program loop (CLRWDT) to prevent the reset. If the program hangs, and the watchdog >mer reset instruc>on not executed, the MCU will restart, and (possibly) con>nue correctly, depending on the nature of the fault.
  • 33. 1/28/13 33 RC OSCILLATOR The MCU clock drives the program along, providing the >ming signals for program execu>on. The RC (resistorcapacitor) clock is cheap and useful. It allows opera>ng with the internal clock driver circuit, to generate the clock. The >me constant (product R X C) determines the clock period. A variable resistor can be used to give a manually adjustable frequency, although it is not very stable or accurate. CRYSTAL (XTAL) OSCILLATOR Used for greater precision uses the hardware >mers to make accurate measurements generate precise output signals Normally, it is connected across the clock pins with a pair of small capacitors (15 pF) to stabilize the frequency. The crystal acts as a self-contained resonant circuit, where the quartz or ceramic crystal vibrates at a precise frequency when subject to electrical s>mula>on. A convenient value (used in our examples later) is 4 MHz; this gives an instruc>on cycle >me of 1 s This is the maximum frequency allowed for the XT congura>on senng. Opera>ng at higher frequency requires the selec>on of the HS congura>on op>on. Each instruc>on takes four clock cycles
  • 34. 1/28/13 34 CONFIGURATION SETTINGS The default senng for the congura>on bits is 3FFF, which means The code protec>on is o In-circuit debugging disabled Program write enabled Low-voltage programming enabled Brown-out reset enabled Power-up >mer disabled Watchdog >mer enabled RC oscillator selected. A typical senng for basic development work would enable in-circuit debugging, enable the power-up >mer This would minimize the possibility of a faulty start-up. For reliable star>ng, disable the watchdog >mer and use the XT oscillator type. By default, the watchdog >mer is enabled. PIC Instruc>on Set It consists of 35 separate instruc>ons, some with alternate result des>na>ons. The default des>na>on for the result of an opera>on is the le register, but the working register W is some>mes an op>on.
  • 35. 1/28/13 35 PIC Instruc>on Set cont. PIC Instruc>on Set cont.
  • 36. 1/28/13 36 MOVE instruc>on The contents of a register are copied to another. No>ce that we cannot move a byte directly from one le register to another, it has to go via the working register. To put data into the system from the program (a literal) we must use MOVLW to place the literal into W ini>ally. It can then be moved to another register as required. To move a byte from W to a le register, MOVWF is used. To move it the other way, MOVF F,W is used, where F is any le register address. MOVF F,F is also available. Can be used to test a register without changing it. REGISTER Register opera>ons aect only a single register, and all except CLRW (clear W) operate on le registers. Clear sets all bits to zero (00h) Decrement decreases the value by 1 Increment increases it by 1. Swap exchanges the upper and lower four bits (nibbles). Complement inverts all the bits, which in eect negates the number. Rotate moves all bits leK or right, including the carry ag in this process. Clear and set a bit operate on a selected bit, where the register and bit need to be specied in the instruc>on.
  • 37. 1/28/13 37 ARITHMETIC & LOGIC Addi>on and subtrac>on uses the carry ag. If the result generates an extra bit (e.g. FF + FF = 1FE), or requires a borrow (e.g. 1FEFF = FF), the carry ag is used. Logic opera>ons are carried out on bit pairs (e.g. 00001111 AND 01010101= 00000101). TEST, SKIP & JUMP Condi>onal jumps are ini>ated using a bit test and condi>onal skip, followed by a GOTO or CALL. The bit test can be made on any le register bit. This could be a port bit, to check if an input has changed, or a status bit in a control register. BTFSC (Bit Test and Skip if Clear) and BTFSS (Bit Test and Skip if Set) are used to test the bit and skip the next instruc>on, or not, according to the state of the bit tested. DECFSZ and INCFSZ embody a commonly used test decrement or increment a register and jump depending on the eect of the result on the zero ag (Z is set if result 0). The bit test and skip may be followed by a single instruc>on to be carried out condi>onally, but GOTO and CALL allow a block of condi>onal code. Using GOTO label simply transfers the program execu>on point to some other point in the program indicated by a label in the rst column of the source code line. A CALL label means that the program returns to the instruc>on following the CALL when RETURN is encountered at the end of the subrou>ne. Another op>on is RETLW (Return with Literal in W). See the KEYPAD. RETFIE (Return From Interrupt) will be explained later.
  • 38. 1/28/13 38 CONTROL NOP simply does nothing for one instruc>on cycle (four clock cycles). very useful for punng short delays in the program SLEEP stops the program, such that it can be restarted with an external interrupt. The unused loca>ons contain the code 3FFF (all 1 s), which is a valid instruc>on (ADDLW FF). CLRWDT means clear the watchdog >mer. If the program gets stuck in a loop or stops for any other reason, it will be restarted automa>cally by the watchdog >mer. To stop this from happening, the watchdog >mer must be reset at regular intervals of less than, say, 10 ms, within the program loop, using CLRWDT. OPTIONAL INSTRUCTIONS TRIS was an instruc>on originally provided to make port ini>aliza>on simpler. It selects register bank 1 so that the TRIS data direc>on registers (TRISA, TRISB, etc.) can be loaded with a data direc>on code (e.g. 0output). The manufacturer no longer recommends use of this instruc>on, although it is s>ll supported The assembler direc>ve BANKSEL can be used It gives more exible access to the registers in banks 1, 2, 3. The other op>on is to change the bank select bits in the STATUS register directly, using BSF and BCF. OPTION, providing special access to the OPTION register, is the other instruc>on, which is no longer recommended. It can be replaced by BANKSEL to select bank 1 which contains the OPTION register, which can then be accessed directly.
  • 39. 1/28/13 39 Program Execu>on The program counter keeps track of program execu>on; it clears to zero on power up or reset. With 8k of program memory, a count from 0000 to 1FFF (8191) requires (13 bits). The PCL (Program Counter Low) register (SFR 02) contains the low byte, and this can be read or wriien like any other le register. The high byte is only indirectly accessible via PCLATH (Program Counter Latch High, SFR 0Ah). SUBROUTINES A label is used at the start of the subrou>ne When a subrou>ne is called (Using the CALL instruc>on), the des>na>on address is copied into the program counter the return address (the one following the CALL) is pushed onto the stack In the PIC, there are 8 stack address storage levels, which are used in turn. The subrou>ne is terminated with a RETURN instruc>on causes the program to go back to the original posi>on and con>nue. achieved by popping the address from the top of the stack and replacing it in the program counter. CALL and RETURN must always be used in sequence to avoid a stack error, and a possible program crash. In the PIC, the stack is not directly accessible
  • 40. 1/28/13 40 INTERRUPTS The stack is used when an interrupt is processed. An interrupt is eec>vely a call and return which is ini>ated by an external hardware signal Forces the processor to jump to a dedicated instruc>on sequence, an Interrupt Service Rou>ne (ISR). For example, the MCU can be set up so that when a hardware >mer >mes out (nishes its count), the process required at that >me is called via a >mer interrupt. When an interrupt signal is received, the current instruc>on is completed and the address of the next instruc>on (the return address) is pushed into the rst available stack loca>on. The ISR is called The ISR is terminated with the instruc>on RETFIE (return from interrupt), which causes the return address to be pulled from the stack. Program execu>on then restarts at the original loca>on. If necessary, the registers must be saved at the beginning of the ISR, and restored at the end, in spare set of le registers.
  • 41. 1/28/13 41 PAGE BOUNDARIES Jump instruc>ons (CALL or GOTO) provide only an 11-bit des>na>on address, so the program memory is eec>vely divided into four 2k blocks, or pages. A jump across the program memory page boundary requires the page selec>on bits to be modied by the user program. Sec>ons 2.3 and 2.4 in the 16F877 data sheet contain detail how to handle these problems. Special Func>on Registers Program Counter (PCL) PCL contains the low 8 bits of the program counter the upper bits (PC) are accessed via PCLATH. PCL is incremented during each instruc>on The contents replaced during a GOTO, CALL (program address) or RETURN (stack).
  • 42. 1/28/13 42 The STATUS register The status register records the result of certain opera>ons, MCU power status and includes the bank selec>on bits It is recommended, that only BCF, BSF, SWAPF and MOVWF instruc>ons are used to alter the STATUS register, because these instruc>ons do not aect the Z, C or DC bits from the STATUS register.
  • 43. 1/28/13 43 ZERO FLAG (Z) This is set when the result of a register opera>on is zero, and cleared when it is not zero. Bit test and skip instruc>ons use this ag for condi>onal branching. these do not aect the zero ag itself. A typical use of the zero ag is to check if two numbers are the same by subtrac>ng and applying bit test and skip to the Z bit. CARRY FLAG (C) This ag is only aected by add, subtract and rotate instruc>ons. When two 8-bit numbers give a 9-bit sum. The carry bit must then be included in subsequent calcula>ons to give the right result. When subtrac>ng, the carry ag must be set ini>ally, because it provides the borrow digit (if required) in the most signicant bit of the result. If the carry ag is cleared aKer a subtrac>on, it means the result was nega>ve Taken together, the zero and carry ags allow the result of an arithme>c opera>on to be detected as posi>ve, nega>ve or zero, as shown in next slide.
  • 44. 1/28/13 44 Arithme>c results DIGIT CARRY (DC) A le register can be seen as containing 8 individual bits, or 1 byte. It can also be used as two 4-bit nibbles. The digit carry records a carry from the most signicant bit of the low nibble (bit 3). (same as auxiliary carry in Intel) Allows 4-bit hexadecimal arithme>c to be carried out in the same way as 8-bit binary arithme>c uses the carry ag C.
  • 45. 1/28/13 45 REGISTER BANK SELECT (RP1:RP0) The PIC 16F877 le register RAM is divided into four banks of 128 loca>ons, banks 03 At power on reset, bank 0 is selected by default. To access the others, these register bank select bits must be changed, Some registers are repeated in more than one bank, making it easier and quicker to access them when switched to that bank. Ex: status register repeats in all banks. A block of GPRs at the end of each bank repeat, so that their data contents are available without changing banks. The pseudo-opera>on BANKSEL can be used. The operand for BANKSEL is any register in that bank, or its In eect, BANKSEL detects the bank bits in the register address and copies them to the status register bank select bits. Register bank select
  • 46. 1/28/13 46 POWER STATUS BITS There are two read only bits in the status register which indicate the overall MCU status. The Power Down (PD) bit is clear to zero when SLEEP mode is entered. The Time Out (TO) bit is cleared when a watchdog >me out has occurred. Parallel input/output To transfer data between uC CPU and the outside world switches, keypads, light-eminng diodes (LEDs), displays, external sensors (analog-to-digital converter), motors or other actuators, and sending serial data to an external memory.
  • 47. 1/28/13 47 Ports There are ve parallel ports in the PIC 16F877, labelled AE. All pins can be used as bit- or byte-oriented digital input or output with Some having alternate func>ons depending on the ini>aliza>on of the relevant control registers. The TRIS (data direc>on) register bits in bank 1, default to 1, senng the ports B, C and D as inputs. Ports A and E are set to ANALOGUE INPUT by default, because the analogue control register ADCON1 in bank 1 defaults to 0 - - - 0000. To set up these ports for digital I/O, this register must be loaded with the code x - - - 011x (x dont care),e.g. 06h. ADCON1 can be ini>alized with bit codes that give a mixture of analogue and digital I/O on Ports A and E. ADCON1 is in bank 1 so BANKSEL is needed to access it. Port func>ons
  • 48. 1/28/13 48 Two bits of a possible digital output port Two bits of a possible digital input port
  • 49. 1/28/13 49 Combine the two circuits to create a programmable bidirec>onal input/output pin Timers The PIC 16F877 has three hardware >mers. Used to carry out >ming opera>ons simultaneously with the program. Ex.: Genera>ng a pulse every second at an output. Timer0 uses an 8-bit register TMR0, le register address 01. The register counts from 0 to 255, and then rolls over to 00 again. When the register goes from FF to 00, an overow ag, T0IF, bit 2 in the Interrupt Control Register INTCON, address 0B, is set. The >mer register is incremented via a clock input from either the MCU oscillator (fOSC) or an external pulse train at RA4. If the internal clock is used, the register acts as a >mer. The >mers are driven from the instruc>on clock (fOSC/4). If the chip is driven from a crystal of 4 MHz, the instruc>on clock will be 1 MHz, and the >mer will update every 1us.
  • 50. 1/28/13 50 Timers cont. A >mer can work as a counter. Counts external pulses >mers can also be used as counters. Timer0, can be controlled by a pre-scaler, see next slide. The pre-scaler is a divide by N register, where N 2, 4, 8, 16, 32, 64, 128 or 256, meaning that the output count rate is reduced by this factor. This extends the count period or total count by the same ra>o, giving a greater range to the measurement. The watchdog >mer interval can also be extended, if this is selected as the clock source. The pre-scale select bits, and other control bits for Timer0 are found in OPTION_REG. BLOCK DIAGRAM OF THE TIMER0/WDT PRESCALER
  • 51. 1/28/13 51 OPTION_REG REGISTER Each of the PORTB pins has a weak internal pull-up. A single control bit can turn on all the pull-ups. This is performed by clearing bit RBPU (OPTION_REG). The weak pull-up is automa>cally turned o when the port pin is congured as an output. The pull-ups are disabled on a Power-on Reset. RB0/INT is an external interrupt input pin and is congured using the INTEDG bit (OPTION_REG). Typical congura>ons for Timer0
  • 52. 1/28/13 52 Timers cont. Timer1 is a 16-bit counter, consis>ng of TMR1H and TMR1L (addresses 0E AND 0F). When the low byte rolls over from FF to 00, the high byte is incremented. The maximum count is therefore 65535, which allows a higher count without sacricing accuracy. Timer2 is an 8-bit counter (TMR2) with a 4-bit pre-scaler, 4-bit post-scaler and a comparator. It can be used to generate Pulse Width Modulated (PWM) output which is useful for driving DC motors and servos, among other things. These >mers can also be used in capture and compare modes, which allow external signals to be more easily measured. Indirect File Register Addressing File register 00 (INDF) is used for indirect le register addressing. The address of the register is placed in the le select register (FSR). When data is wriien to or read from INDF, it is actually wriien to or read from the le register pointed to by FSR. This is most useful for carrying out a read or write on a con>nuous block of GPRs, For example, when saving data being read in from a port over a period of >me. Since nine bits are needed to address all le registers (0001FF), the IRP bit in the status register is used as the extra bit.
  • 53. 1/28/13 53 Direct and indirect addressing of the le registers Interrupt Control Registers The registers involved in interrupt handling are INTCON, PIR1, PIR2, PIE1, PIE2 and PCON. Interrupts are external hardware signals which force the MCU to suspend its current process, and carry out an Interrupt Service Rou>ne (ISR). In PIC when an interrupt occurs the program execu>on jumps to address 004. By default, interrupts are disabled. If interrupts are to be used the main program start address needs to be 0005, or higher, and a GOTO start (or similar label) placed at address 0000. A GOTO ISR instruc>on can then be placed at 004, using the ORG direc>ve, which sets the address at which the instruc>on will be placed by the assembler. The Global Interrupt Enable bit (INTCON, GIE) must be set to enable the interrupt system. The individual interrupt source is then enabled. For example, the bit INTCON, T0IE is set to enable the Timer0 overow to trigger the interrupt sequence. When the >mer overows, INTCON, T0IF (Timer0 Interrupt Flag) is set to indicate the interrupt source, and the ISR called. The ags can be checked by the ISR to establish the source of the interrupt, if more than one is enabled.
  • 54. 1/28/13 54 Interrupt sources and control bits Macros, Special Instruc>ons, Assembler Direc>ves Another structured Supplementary instruc>ons
  • 55. 1/28/13 55 Program Design and owcharts There are two main forms of owchart. Data owcharts: used to represent complex data processing systems Program ow charts: used to represent overall program structure and sequence, but not the details. Previous Example ow chart
  • 56. 1/28/13 56 Flowchart implementa>on Input & Output (Interfacing) Switch Input input loading and debouncing.
  • 57. 1/28/13 57 Switch Debouncing Delay Schmit trigger capacitor Timer and Interrupts Allows the MCU to proceed with other tasks while carrying out a >ming opera>on concurrently. Ex: debouncing If a hardware >mer is started when the switch is rst closed, the closure can be conrmed by retes>ng the input aKer a >me delay to check if it is s>ll closed. Alterna>vely, the switch input can be processed aKer the buion is released, rather than when it is closed. The system responds when the switch is released rather than when it is pressed.
  • 58. 1/28/13 58 Timer 0 Show (LED1H design and code) which illustrates the use of a hardware >mer and the use of interrupt. TMR0 (Timer0) is located at le register address 01. It operates as an 8-bit binary up counter, driven from an external or internal clock source. The count increments with each input pulse, and a ag is set when it overows from FF to 00. It can be pre-loaded with a value so that the >me out ag is set aKer the required interval. For example, if it is pre-loaded with the number 15610, it will overow aKer 100 counts (25610).
  • 59. 1/28/13 59 Keypad Input A keypad is simply an array of push buions connected in rows and columns, so that each can be tested for closure with the minimum number of connec>ons. There are 12 keys on a phone type pad (09, #, ), arranged in a 3X4 matrix. The columns are labelled 1, 2, 3 and the rows A, B, C, D. Keypad Input cont. If we assume that all the rows and columns are ini>ally high, a keystroke can be detected by senng each row low in turn and checking each column for a zero. In the KEYPAD circuit, the 7 keypad pins are connected to Port D. Bits 47 are ini>alized as outputs, and bits 02 used as inputs. The input pins are pulled high to logic 1. The output rows are also ini>ally set to 1.
  • 60. 1/28/13 60 Keypad opera>on If a 0 is now output on row A, there is no eect on the inputs unless a buion in row A is pressed. If these are checked in turn for a 0, a buion in this row which is pressed can be iden>ed as a specic combina>on of output and input bits. A simple way to achieve this result is to increment a count of keys tested when each is checked, so that when a buion is detected, the scan of the keyboard is terminated with current key number in the counter. This works because the (non-zero) numbers on the keypad arranged in order: Row A 1, 2, 3 Row B 4, 5, 6 Row C 7, 8, 9 Row D *, 0, # Following this system, the star symbol is represented by a count of 10 (0Ah), zero by 11(0Bh) and hash by 12 (0C). Show Keypad design and code. Calculator
  • 61. 1/28/13 61 The calculator operates as follows: To perform a calcula>on, press a number key, then an opera>on key, then another number and then equals. The calcula>on and result are displayed. For the divide opera>on, the result is displayed as result and remainder. Pseudo code for the calculator CALC Single digit calculator produces two digit results. Hardware: x12 keypad, 2x16 LCD, P16F887 MCU MAIN Ini>alise PortC = keypad RC0 RC3 = output rows RC4 RC7 = input columns PortD = LCD RD1, RD2 = control bits RD4 RD7 = data bits CALL Ini>alise display Scan Keypad REPEAT CALL Keypad input, Delay 50ms for debounce CALL Keypad input, Check key released IF rst key, load Num1, Display character and restart loop IF second key, load sign, Display character and restart loop IF third key, load Num2 Display character and restart loop IFfourth key, CALL Calculate result IF Kh key, Clear display ALWAYS
  • 62. 1/28/13 62 Subrou>nes Included LCD driver rou>nes Ini>alise display Display character Keypad Input Check row A, IF key pressed, load ASCII code Check row B, IF key pressed, load ASCII code Check row C, IF key pressed, load ASCII code Check row D, IF key pressed, load ASCII code ELSE load zero code Calculate result IF key = +, Add IF key = -, Subtract IF key = x, Mul>ply IF key = /, Divide Add Add Num1 + Num2 Load result, CALL Two digits Subtract Subtract Num1 Num2 IF result nega>ve, load minus sign, CALL Display character Load result, CALL Display character Subrou>nes cont. Mul>ply REPEAT Add Num1 to Result Decrement Num2 UNTIL Num2= 0 Load result, CALL Two digits Divide REPEAT Subtract Num2 from Num1 Increment Result UNTIL Num1 nega>ve Add Num2 back onto Num1 for Remainder Load Result, CALL Display character Load Remainder, CALL Display character Two digits Divide result by 10, load MSD, CALL Display character Load LSD, CALL Display character
  • 63. 1/28/13 63 Show calc code and design ADC Registers used ADCON0 ADCON1 The output from the converter is stored in ADRESH (analogue to digital conversion result, high byte) and ADRESL (low byte). Show ADC code and design (VINTEST)
  • 64. 1/28/13 64 8-bit Conversion The 16F877 MCU has eight analogue inputs available, at RA0, RA1, RA2, RA3, RA5, RE0, RE1 and RE2. RA2 and RA3 may be used as reference voltage inputs, senng the minimum and maximum values for the measured voltage range. These inputs default to analogue opera>on, so the register ADCON1 has to be ini>alized explicitly to use these pins for digital input or output. The ADC converts an analogue input voltage (e.g. 0 2.56V) to 10-bit binary, but only the upper 8 bits of the result are used, giving a resolu>on of 10 mV per bit ((1/256) X 2.56 V). ADC block diagram
  • 65. 1/28/13 65 ADC OPERATION The inputs are connected to a func>on selector block which sets up each pin for analogue or digital opera>on according to the 4-bit control code loaded into the A/D port congura>on control bits, PCFG0PCFG3 in ADCON1. The code used, 0011, sets Port E as digital I/O, and Port A as analogue inputs with AN3 as the posi>ve reference input. The analogue inputs are then fed to a mul>plexer which allows one of the eight inputs to be selected at any one >me. This is controlled by the three analogue channel select bits, CHS0CHS2 in ADCON0. In the example, channel 0 is selected (000), RA0 input. If more than one channel is to be sampled, these select bits need to be changed between ADC conversions. The conversion is triggered by senng the GO/DONE bit, which is later cleared automa>cally to indicate that the conversion is complete. ADC control registers
  • 66. 1/28/13 66 ADC Test Circuit ADC clock The speed of the conversion is selected by bits ADSC1 and ADSC0. The ADC operates by successive approxima>on; this means that the input voltage is fed to a comparator, and if the voltage is higher than 50% of the range, the MSB of the result is set high. The voltage is then checked against the mid-point of the remaining range, and the next bit set high or low accordingly, and so on for 10 bits. This takes a signicant amount of >me: the minimum conversion >me is 1.6 s per bit, making 16 s for a 10-bit conversion. The ADC clock speed must be selected such that this minimum >me requirement is sa>sed; The MCU clock is divided by 2, 8 or 32 as necessary. Our simulated test circuit is clocked at 4 MHz. This gives a clock period of 0.25 s. We need a conversion >me of at least 1.6 s; if we select the divide by 8 op>on, the ADC clock period will then be 8 X 0.25 = 2 s, which is just longer than the minimum required. The select bits are therefore set to 01.
  • 67. 1/28/13 67 Power-up and Reset When the microcontroller powers up, it must start running its program from its beginning for the 16F84A it is from reset vector. Done by explicit circuitry which is built in to detect power-up. Then SFRs are set so that peripherals are ini>ally in a safe and disabled state. This is called Reset. In the 16F84A there is a Reset input, MCLR (Master Clear), on pin 4; As long as this is held low, the microcontroller is held in Reset. When it is taken high, program execu>on starts. If the pin is taken low while the program is running, then program execu>on stops immediately and the microcontroller is forced back into Reset mode. This is important because Both the power supply and the clock oscillator take a nite amount of >me to stabilize. So the program should only start only when every thing stabilized, but when? If a resistor capacitor circuit is connected to the Reset input, then when power is applied, the capacitor voltage rises according to the RC >me constant, which can be made as big as is wanted. For a certain >me, because it is rising compara>vely slowly, the Reset input is at Logic 0. Thus, the microcontroller can be held in Reset while its power supply stabilizes and while the clock oscillator starts up. Power-up and Reset cont. But what if the power is switched o and then on again quickly A cruel and challenging thing to do to any electronic device. The capacitor wouldnt have >me to discharge and the Reset condi>on might not be properly applied when power is applied again. More dangerously, the capacitor voltage might exceed the voltage supplied to the microcontroller and excessive current could then ow from the capacitor into the Reset input. Can be solved by adding a simple discharge diode This ensures that the capacitor discharges more or less at the same rate as the VDD supply. The resistor RS is also included to limit current into the Reset input if the capacitor voltage does inadvertently exceed the voltage supplied to the microcontroller or another fault condi>on occurs.
  • 68. 1/28/13 68 Power-up and Reset If the designer wishes to include a Reset buion, then circuit can be applied. This is par>cularly useful for prototype circuits, where a large amount of tes>ng is expected. Then it is convenient to be able to reset a program that may have crashed. R is a pull-up resistor, whose value can be in the range 10-100 k. In a commercial device it is usually not desirable to have a Reset buion; the aim here is to design the product so that reset by the user is never needed. On-chip Reset One of Microchips goals is to minimize the number of external components needed for their microcontrollers. The 16F84A includes some clever on-chip reset circuitry. Reset Components unnecessary (except when a switch is needed). A Power-up Timer is included on-chip, which can be enabled by the user with bit 3 of the Congura>on Word. The 16F84A detects that power has been applied and the Power-up Timer then holds the controller in Reset for a xed >me. Once this is over the microcontroller leaves Reset and program execu>on Begins. In the internal reset circuit of the 16F84A, the actual reset to the CPU, Chip_Reset, is generated by a ip-op, which appears to the right of the diagram, see next slide. The ip-op has two inputs, S (Set) and R (Reset). The CPU enters Reset mode when Chip_Reset goes low, which is caused by the S line going high. It stays there un>l the ip-op is cleared, caused by the R line going high. So what causes a reset? The S input to the ip-op goes high, via a three-input OR gate, if any of the following goes high: External Reset, from the MCLR line. Time-out Reset, from the Watchdog Timer (WDT); this is designed to occur if a program crash occurs. Power-on Reset, output of the circuit that detects power being applied (VDD Rise Detect).
  • 69. 1/28/13 69 On-chip Reset cont. On-chip Reset cont. When the R input to the ip-op is ac>vated, the Chip_Reset line returns to 1 and the PIC microcontroller is enabled. The three requirements to be sa>sed here, determined by the inputs to the associated AND gate, are that both power supply and oscillator have stabilized, and that any demand for Reset has been cleared. Achieved by, the Power-up Timer (PWRT) and the Oscillator Start-up Timer (OST). The Power-up Timer can be enabled by senng its bit in the Congura>on Word. The Oscillator Start-up Timer is enabled via the Enable OST line. Set automa>cally by the user oscillator senng in the Congura>on Word. Enables it for all oscillator modes except RC. The Power-up Timer is clocked by its own on-chip RC oscillator, and when enabled counts 1024 cycles of its oscillator before senng its output to 1. This >me dura>on turns out to be around 72 ms. If all lines are high, i.e. both counters have completed their count and there is no demand for a Reset, then the ip-op is cleared. The CPU accordingly leaves the Reset condi>on and starts running.
  • 70. 1/28/13 70 On-Chip Reset Port electrical characteris>cs
  • 71. 1/28/13 71 Pull-up/pull-down resistor Programming with PIC C Names make them t their func>on Use mixed case names to improve the readability ErrorCheck is easier than ERRORCHECK Prex names with a lowercase leier of their type, again to improve readability: g Global gLog; r Reference rStatus(); s Sta>c sValueIn;
  • 72. 1/28/13 72 Braces{} and spaces Braces or curly brackets can be used in the tradi>onal UNIX way if (condi>on) { . } or the preferred method which is easier to read if (condi>on) { . } Indent text only as needed to make the soKware readable. Keep line lengths to 78 characters for compa>bility between monitors and printers. TIPs Where the compiler allows it, always put the constant on the leK hand side of an equality / inequality comparison, If one = is omiied, the compiler will nd the error for you. if ( 6 == ErrorNum) Set all variables to a known values to prevent oa>ng or random condi>ons int a=6, b=0; Use comments
  • 73. 1/28/13 73 Genng Started A simple program is the Press buion turn on LED. main bss porta,switch ;test for switch closure goto main ;loop un>l pressed bsf portb,led ;turn on led lp1 bsc porta,switch ;test for switch open goto lp1 ;loop un>l released bcf portb,led ;turn o led goto main ;loop back to start IN PIC C main() { set_tris_b(0x00); //set port b as outputs while(true) { if (input(PIN_A0)) //test for switch closure output_high(PIN_B0); //if closed turn on led else output_low(PIN_B0); //if open turn o led } }
  • 74. 1/28/13 74 C Fundamentals The topics discussed are Program structure Components of a C program #pragma main #include direc>ve prin statement Variables Constants Comments Func>ons C keywords
  • 75. 1/28/13 75 The Structure of C Programs Preprocessor direc>ve The two most common preprocessor direc>ves are the #dene direc>ve, which subs>tutes text for the specied iden>er, and the #include direc>ve, which includes the text of an external le into a program. Declara>on: A declara>on establishes the names and aiributes of variables, func>ons, and types used in the program. Global variables are declared outside func>ons and are visible from the end of the declara>on to the end of the le. A local variable is declared inside a func>on and is visible form the end of the declara>on to the end of the func>on. Deni>on: A deni>on establishes the contents of a variable or func>on. A deni>on also allocates the storage needed for variables and func>ons. Expression: An expression is a combina>on of operators and operands that yields a single value. Statement: Statements control the ow or order of program execu>on in a C program. Func>on: A func>on is a collec>on of declara>ons, deni>ons, expressions, and statements that performs a specic task. Braces enclose the body of a func>on. Func>ons may not be nested in C. main Func>on
  • 76. 1/28/13 76 THE 8086 INTERNAL ORGANIZATION Pipelining The CPU could either fetch or execute at a given >me. CPU had to fetch an instruc>on from the memory, then execute it, then fetch again and execute it and so on.. Pipelining is the simplest form, is to allow the CPU to fetch and execute at the same >me. Note that the fetch and execute >mes can be dierent. Intel implemented the concept of pipelining by splinng the internal structure of 8088/86 into two sec>ons. The execu>on unit (EU) The bus interface unit (BIU) These two sec>ons work simultaneously. BIU accesses memory and peripherals while the EU executes the instruc>ons previously fetched.
  • 77. 1/28/13 77 Registers of 8086 Microprocessor In the CPU, registers are used to store informa>on temporarily. The informa>on can be one or two bytes of data, or the address of data. In 8088/8086 General-purpose registers can be accessed as either16-bit or 8-bit registers. All other registers can be accessed as full 16-bit registers. Ex: AX The bits of the registers are numbered in descending order: Registers of 8086 Microprocessor Dierent registers are used for dierent func>ons. The rst leier of each general register indicates its use. AX is used for the accumulator. BX is used for base addressing register. CX is used for counter loop opera>ons. DX is used to point out data in I/O opera>ons. Note: the general registers can be accessed as full 16 bits (such as AX), or as the high byte only (AH) or low byte only (AL). The others are not!!
  • 78. 1/28/13 78 INTRODUCTION TO ASSEMBLY PROGRAMMING Machine Language: Programs consist of 0s and 1s are called machine language. Assembly Languages provided mnemonics for machine code instruc>ons. Mnemonics refer to codes and abbrevia>ons to make it easier for the users to remember. Low / High level languages: Assembly Language is a low-level language. Deals directly with the internal structure of CPU. Assembler translates Assembly language program into machine code. In high-level languages, Pascal, Basic, C; the programmer does not have to be concerned with internal details of the CPU. Compilers translate the program into machine code. Assembly Language programming: Assembly Language program consists of series of lines of Assembly language instruc>ons. Instruc>on consists of a mnemonic and two operands. MOV instruc>on MOV des>na>on, source; copy source operand to des>na>on mnemonic operands Example: (8-bit ) MOV CL,55H ;move 55H into register CL MOV DL,CL ;move/copy the contents of CL into DL (now DL=CL=55H) MOV BH,DL ;move/copy the contents of DL into BH (now DL=BH=55H) MOV AH,BH ;move/copy the contents of BH into AH (now AH=BH=55H) Example: (16-bit) MOV CX,468FH ;move 468FH into CX (now CH =46 , CL=8F) MOV AX,CX ;move/copy the contents of CX into AX (now AX=CX=468FH) MOV BX,AX ;now BX=AX=468FH MOV DX,BX ;now DX=BX=468FH MOV DI,AX ;now DI=AX=468FH MOV SI,DI ;now SI=DI=468FH MOV DS,SI ;now DS=SI=468FH MOV BP,DS ;now BP=DS=468FH Data can be moved among all registers except the ag register. There are other ways to load the ag registers. To be studied later. Source and des>na>on registers have to match in size. Data can be moved among all registers (except ag reg.) but data can be moved directly into nonsegment registers only. You cant move data segment registers directly. Examples: MOV BX,14AFH ;move 14AFH into BX (legal) MOV SI,2345H ;move 2345H into SI (legal) MOV CS,2A3FH ;move 2A3FH into CS (illegal) MOV FR,BX ;move the content of BX into FR (illegal) MOV DS,14AFH ;move 14AFH into DS (illegal) Values cannot be loaded directly into (CS,DS,SS and ES) MOV AX,1234H ; load 1234H into AX MOV SS,AX ;load the value in AX into SS Sizes of the values: MOV BX,2H ; BX=0002H, BL:02H, BH:00H MOV AL,123H ; illegal (larger than 1 byte) MOV AX,3AFF21H ; illegal (larger than 2 bytes)
  • 79. 1/28/13 79 ADD instruc>on ADD des>na>on, source ; add the source operand to des>na>on mnemonic operands Ex: MOV AL,24H ;move 24H into AL MOV DL,11H ;move 11H into DL ADD AL,DL ;AL=AL+DL (AL=35H) (DL =11H) MOV CH,24H ;move 24H into CH MOV BL,11H ;move 11H into BL ADD CH,BL ;CH=CH+BL (CH=35H) MOV CH,24H ;load one operand into CH ADD CH,11H ;add the second operand to CH (CH=35H) If one register data is followed by an immediate data, it is called the immediate operand. MOV CH,24H ADD CH,11H 8-bit registers can hold FFH (255) maximum. Addi>on of larger numbers can be performed by the 16-bit nonsegment registers. MOV AX,34EH MOV DX,6A5H ADD DX,AX ;DX=DX+AX (DX=9F3H) MOV CX,34EH ADD CX,6A5H ;CX=34EH+6A5=9F3H PROGRAM SEGMENTS A segment is an area of memory that includes up to 64K bytes and begins an address evenly divisible by 16 (such an address ends in 0H). Assembly Language Program consists of Four segments: code segment : contains the program code (instruc>ons) data segment : used to store data (informa>on) to be processed by the program stack segment: used to store informa>on temporarily. Extra segment: used also to store data (not commonly used) Logical and Physical Address Physical Address is the 20-bit address that actually put on the address bus. (in 8086) Has a range of 00000H FFFFFH Oset Address is a loca>on within 64K byte segment range. Has a range of 0000H FFFFH Logical Address consists of segment address and oset address.
  • 80. 1/28/13 80 Addressing in Code segment To execute a program, the 8086 fetches the instruc>ons from the code segment. The logical address of an instruc>on consists CS (Code Segment) and IP(instruc>on pointer) Physical Address is generated by shiKing the CS one hex digit to the leK and adding IP. Example: CS:IP => 2500:95F3H Start with CS 2500 ShiK leK, mult by 10, or just add zero so that CS 25000 Add IP 2E5F3 (25000+95F3) The microprocessor will retrieve the instruc>on in turn memory loca>ons star>ng from 2E5F3 Ex: If CS=24F6H and IP=634AH, determine: a) The logical address b) The oset address c) The physical address d) The lower range of the code segment e) The upper range of the code segment Answer: a) The logical address is; 24F6:634A b) The oset address is; 634A c) The Physical address is; 24F60+634A= 2B2AA d) The lower range of the code segment: 24F6:0000 => 24F60+0000 =24F60 e) The upper range of the code segment: 24F6:FFFF => 24F60+FFFF=34F5F Data segment The area of memory allocated strictly for data is called data segment. Just as the code segment is associated with CS and IP as segment register and oset. The data segment uses DS and an oset value. In 8086 BX, SI and DI are used to hold the oset address.
  • 81. 1/28/13 81 Using the data segment Assume that a program is needed to add 5 bytes of data (25H, 12H, 15H,1FH and 2BH) One way: MOV AL,00H ;ini>alize AL ADD AL,25H ADD AL,12H ADD AL,15H code and data are mixed ADD AL,1FH ADD AL,2BH ; AL=25+12+15+1F+2B Other way: Assume that the oset for data segment begins at 200H DS:0200 = 25 DS:0201 = 12 DS:0202 = 15 within data segment DS:0203 = 1F DS:0204 = 2B MOV AL,0 ;clear AL ADD AL,[0200] ;add the contents of DS:200 to AL ADD AL,[0201] ;add the contents of DS:201 to AL ADD AL,[0202] ;add the contents of DS:202 to AL ADD AL,[0203] ;add the contents of DS:203 to AL ADD AL,[0204] ;add the contents of DS:204 to AL Liile endian conven>on Given 8-bit (1-byte) data, bytes are stored one aKer the other in the memory. However given16-bit (2-bytes) of data how are date stored? Ex: MOV AX,35F3H :load 35F3H into AX MOV [1500],AX : copy contents of AX to oset 1500H In such a case the low byte goes to the low memory loca>on and high byte goes to the high memory loca>on. DS:1500 = F3 DS:1501 = 35 This conven>on is called liile endian conven>on: This conven>on is used by Intel. The big endian conven>on is the opposite, where the high byte goes to the low address and low byte goes to the high address. Motorolla microprocessor uses this conven>on.
  • 82. 1/28/13 82 MEMORY MAP OF THE IBM PC The 20-bit address of the 8086/8088 allows 1M byte of (1024 K bytes) memory space with the address range 00000-FFFFF. The alloca>on of the memory is called a memory map. MEMORY MAP OF THE IBM PC cont. RAM: Memory loca>ons from 00000H to 9FFFFH (640K) are set aside for RAM. In an IBM PC the DOS opera>ng system rst allocates the available RAM on the PC for its own use and let the rest be used for applica>ons such as word processors. The amount of memory used by DOS varies among its various versions. That is why we do not assign any values for the CS, DS, SS, and ES. Memory management func>ons within DOS handle this for the opera>ng system. Video RAM: Memory loca>ons from A0000H to BFFFFH (128K) are set aside for video. This amount varies depending on the video board installed on the PC. ROM: Memory loca>ons from C0000H to FFFFFH (256K) are set aside for ROM. First 64 K bytes is used by BIOS (Basic Input/Output System) ROM. Some of the remaining space is used for adapter cards. Func>on of BIOS ROM: CPU can only execute programs that are stored in memory, there must be some permanent (nonvola>le) memory to hold the programs telling the CPU what to do when the power is turned on. BIOS contains programs to test RAM and other components connected to the CPU.
  • 83. 1/28/13 83 STACK What is a stack, and why is it needed? The stack is a sec>on of read/write memory (RAM) used by the CPU to store informa>on temporarily. CPU needs this storage area since there are only limited number of registers. How stacks are accessed SS (stack segment) and SP (stack pointer) must be loaded to access stack in the memory. Every register in the CPU (except segment registers and SP) can be stored in the stack and loaded from the stack. Stack: PUSHING OPERATIONS Storing the CPU register in the stack is called a push. Ex: SP=1236, AX=24B6, DI=85C2, and DX=5F93, show the contents of the stack as each instruc>on is executed. PUSH AX, PUSH DI, PUSH DX
  • 84. 1/28/13 84 Popping the stack Loading the contents of the stack into the CPU register is called a pop. Ex: assume that the stack is shown below, and SP=18FA, show the contents of the stack and registers as each of the following instruc>ons is executed. POP CX, POP DX, POP BX THE FLAG REGISTER (FR) AND BIT FIELDS The ag register is a 16-bit register some>mes referred as the status register. Although the register is 16-bit. Not all the bits are used. Condi>onal ags: 6 of the ags are called the condi>onal ags, meaning that they indicate some condi>on that resulted aKer an instruc>on was executed. These 6 are: CF, PF, AF, ZF, SF, and OF. The 16 bits of the ag registers:
  • 85. 1/28/13 85 THE FLAG REGISTER (FR) AND BIT FIELDS CF, the Carry Flag: This ag is set whenever there is a carry out, either from d7 aKer an 8-bit opera>on, or from d15 aKer a 16-bit data opera>on. PF, the Parity Flag: AKer certain opera>ons, the parity of the results low-order byte is checked. If the byte has an even number of 1s, the parity ag is set to 1; otherwise, it is cleared. AF, the Auxiliary Carry Flag: If there is a carry from d3 to d4 of an opera>on this bit is set to 1, otherwise cleared (set to 0). ZF, the Zero Flag: The ZF is set to 1 if the result of the arithme>c or logical opera>on is zero, otherwise, it is cleared (set to 0). SF, the Sign Flag: MSB is used as the sign bit of the binary representa>on of the signed numbers. AKer arithme>c or logical opera>ons the MSB is copied into SF to indicate the sign of the result. TF, the Trap Flag: When this ag is set it allows the program to single step, meaning to execute one instruc>on at a >me. Used for debugging purposes. IF, Interrupt Enable Flag: This bit is set or cleared to enable or disable only the external interrupt requests. DF, the Direc>on Flag: This bit is used to control the direc>on of the string opera>ons. OF, the Overow Flag: This ag is set whenever the result of a signed number opera>on is too large, causing the high-order bit to overow into the sign bit. Flag Register and ADD instruc>on The ag bits aected by the ADD instruc>ons are: CF, PF, AF, ZF, SF and OF. Ex: Show how the ag register is aected by the addi>on of 38H and 2FH. CF = 0 since there is no carry beyond d7 PF = 0 since there is odd number of 1`s in the result AF = 1 since there is a carry from d3 to d4 ZF = 0 since the result is not zero SF = 0 since d7 of the result is zero Ex: Show how the ag register is aected by the following addi>on CF = 0 since there is no carry beyond d15 PF = 0 since there is odd number of 1s in the lower byte AF = 1 since there is a carry from d3 to d4 ZF = 0 since the result is not zero SF = 1 since d15 of the result is 1 Note that the MOV instruc>ons have no eect on the ag
  • 86. 1/28/13 86 Use of zero ag for looping Zero ag is used to implement the program loops. Loop refers to a set of instruc>ons that is repeated a number of >mes. The following example shows the implementa>on of the loop concept in the program which adds 5 bytes of data. Ex: MOV CX,05 ; CX holds the loop count MOV BX,0200H ; BX holds the oset data address MOV AL,00 ; ini>alize AL ADD_LP: ADD AL,[BX] ; add the next byte to AL INC BX ; increment the data pointer DEC CX ; decrement the loop counter JNZ ADD_LP ; jump to the next itera>on if the counter not zero 80X86 ADDRESSING MODES The CPU can access operands (data) in various ways, called addressing modes. In 80x86 there are 7 addressing modes Register Immediate Direct register indirect based rela>ve indexed rela>ve based indexed rela>ve Register addressing mode: involves the use of registers memory is not accessed, so faster source and des>na>on registers must match in size. Ex: MOV BX,DX MOV ES,AX ADD AL,BH MOV AL,CX ;not possible
  • 87. 1/28/13 87 80X86 ADDRESSING MODES cont. Immediate addressing mode: source operand is a constant possible in all registers except segment and ag registers. Ex: MOV BX,1234H ; move 1234H into BX MOV CX,223 ; load the decimal value 547 into CX ADD AL,40H ; AL=AL+40H MOV DS,1234H ;illegal (ask what to do) Direct addressing mode: address of the data in memory comes immediately aKer the instruc>on operand is a constant The address is the oset address. The oset address is put in a rectangular bracket Ex: MOV DL,[2400] ; move contents of DS:2400H into DL Ex: Find the physical address of the memory loca>on and its content aKer the execu>on of the following opera>on. Assume DS=1512H MOV AL,99H MOV [3518],AL Physical address of DS:3518 => 15120+3518=18638H The memory loca>on 18638H will contain the value 99H 80X86 ADDRESSING MODES cont. Register indirect addressing mode: The address of the memory loca>on where the operand resides is held by a register. SI, DI and BX registers are used as the pointers to hold the oset addresses. They must be combined with DS to generate the 20-bit physical address Ex: MOV AL,[BX] ; moves into AL the contents of the memory loca>on pointed to by DS:BX