PIC16f877a Notes

download PIC16f877a Notes

of 59

Transcript of PIC16f877a Notes

  • 7/30/2019 PIC16f877a Notes

    1/59

    Developing Embedded Systems - A Tools Introduction

    by Volker SoffelGeneral ManagerMicroController Pros Corporation

    Developing software and hardware for microcontroller based systems involves the use of arange of tools that can includeeditors, assemblers,compilers,debuggers, simulators, emulators and Flash/OTP programmers.To the newcomer to microcontroller development it is often not clear how all of thesedifferent components play together in the development cycle and what differences there arefor example between starter kits, emulators and simulators.

    To complicate matters more, there are quite a number ofdifferent approaches andtechnologies for emulation available that make it difficult for even seasoned embeddedengineers to pick the right tools. With this article, I'll try to give a short explanation of thedifferent tools involved in the microcontroller development cycle, with a particular focus onthe different emulator types and their advantages and disadvantages.

    So let's start out by looking at the typical microcontroller software development cycle withsome of the software and hardware components involved:

    http://microcontrollershop.com/redirect.php?action=url&goto=http://www.ucpros.com&osCsid=8qdtq2emob7vfeskoolagc4c92http://microcontrollershop.com/An%20Embedded%20Tools%20Introduction.php#Assemblers%20or%20(C-)%20Compilers?osCsid=8qdtq2emob7vfeskoolagc4c92http://microcontrollershop.com/An%20Embedded%20Tools%20Introduction.php#Assemblers%20or%20(C-)%20Compilers?osCsid=8qdtq2emob7vfeskoolagc4c92http://microcontrollershop.com/An%20Embedded%20Tools%20Introduction.php#Debugger?osCsid=8qdtq2emob7vfeskoolagc4c92http://microcontrollershop.com/An%20Embedded%20Tools%20Introduction.php#Debugger?osCsid=8qdtq2emob7vfeskoolagc4c92http://microcontrollershop.com/An%20Embedded%20Tools%20Introduction.php#Simulators?osCsid=8qdtq2emob7vfeskoolagc4c92http://microcontrollershop.com/An%20Embedded%20Tools%20Introduction.php#Emulators?osCsid=8qdtq2emob7vfeskoolagc4c92http://microcontrollershop.com/An%20Embedded%20Tools%20Introduction.php#4.%20OTP%20and%20Flash%20Programming?osCsid=8qdtq2emob7vfeskoolagc4c92http://microcontrollershop.com/An%20Embedded%20Tools%20Introduction.php#Microcontroller%20Starter%20Kits?osCsid=8qdtq2emob7vfeskoolagc4c92http://microcontrollershop.com/An%20Embedded%20Tools%20Introduction.php#Technical%20Approaches%20to%20Emulation?osCsid=8qdtq2emob7vfeskoolagc4c92http://microcontrollershop.com/An%20Embedded%20Tools%20Introduction.php#Technical%20Approaches%20to%20Emulation?osCsid=8qdtq2emob7vfeskoolagc4c92http://microcontrollershop.com/An%20Embedded%20Tools%20Introduction.php#Assemblers%20or%20(C-)%20Compilers?osCsid=8qdtq2emob7vfeskoolagc4c92http://microcontrollershop.com/An%20Embedded%20Tools%20Introduction.php#Assemblers%20or%20(C-)%20Compilers?osCsid=8qdtq2emob7vfeskoolagc4c92http://microcontrollershop.com/An%20Embedded%20Tools%20Introduction.php#Debugger?osCsid=8qdtq2emob7vfeskoolagc4c92http://microcontrollershop.com/An%20Embedded%20Tools%20Introduction.php#Simulators?osCsid=8qdtq2emob7vfeskoolagc4c92http://microcontrollershop.com/An%20Embedded%20Tools%20Introduction.php#Emulators?osCsid=8qdtq2emob7vfeskoolagc4c92http://microcontrollershop.com/An%20Embedded%20Tools%20Introduction.php#4.%20OTP%20and%20Flash%20Programming?osCsid=8qdtq2emob7vfeskoolagc4c92http://microcontrollershop.com/An%20Embedded%20Tools%20Introduction.php#Microcontroller%20Starter%20Kits?osCsid=8qdtq2emob7vfeskoolagc4c92http://microcontrollershop.com/An%20Embedded%20Tools%20Introduction.php#Technical%20Approaches%20to%20Emulation?osCsid=8qdtq2emob7vfeskoolagc4c92http://microcontrollershop.com/An%20Embedded%20Tools%20Introduction.php#Technical%20Approaches%20to%20Emulation?osCsid=8qdtq2emob7vfeskoolagc4c92http://microcontrollershop.com/redirect.php?action=url&goto=http://www.ucpros.com&osCsid=8qdtq2emob7vfeskoolagc4c92
  • 7/30/2019 PIC16f877a Notes

    2/59

    Above picture shows the typical microcontrollers firmware development cycle, which involves:

    Writing the code

    Translating the code

    Debugging the code with the help ofdebugging tools, including emulators Programming a Flash or OTP version of the microcontroller to built up a first functional

    prototype of your system

    1. Writing Microcontroller Code

    Software Code for a microcontroller is written in a programming language of choice (oftenAssembler or C). This source code is written with a standardASCII text editor and saved as anASCII text file. Programming in assembler involves learning a microcontroller's specificinstruction set (assembler mnemonics), but results in the most compact and fastest code. Ahigher level language like C is for the most part independent of a microcontroller's specificarchitecture, but still requires some controller specific extensions of the standard language to

    be able to control all of a chip's peripherals and functionality. The penalty for more portablecode and faster program development is a larger code size (20%...40% compared to assembler).

    2. Translating the Code

    Next the source code needs to be translated into instructions the microcontroller can actuallyexecute. A microcontrollers instruction set is represented by "op codes". Op codes are a uniquesequence of bits ("0" and "1") that are decoded by the controller's instruction decode logic andthen executed. Instead of writing opcodes in bits, they are commonly represented ashexadecimal numbers, whereby one hex number represents 4 bits within a byte, so it takestwo hex numbers to represent 8 bits or 1 byte. For that reason a microcontroller's firmware in

    machine readable form is also called Hex-Code and the file that stores that code Hex-File.

    Assemblers, Compilers, Linkers and Librarians

    Assemblers or (C-) Compilers translate the human readable source code into "hex code" thatrepresents the machine instructions (op codes). To support modular code and reusablelibraries of code, most assemblers and compilers today come with Linkers and Librarians.

    Linkers, link code modules saved in different files together into a single final program. At thesame time they take care of a chip's memory allocation by assigning each instruction to amicrocontroller memory addresses in such a way that different modules do not overlap.

    Librarians help you to manage, organize and revision control a library of re-usable codemodules.

    Once the ASCII source code text file has been assembled (with an Assembler) or compiled (witha Compiler) and the files have been linked (with the Linker), the output results in a number offiles that can be used for debugging the software and programming the actualmicrocontroller's memory.

    3. Debugging the Code

    A debugger is a piece of software running on the PC, which has to be tightly integrated withthe emulator that you use to validate your code. For that reason all emulator manufacturersship their own debugger software with their tools, but also compiler manufacturers frequently

    http://microcontrollershop.com/An%20Embedded%20Tools%20Introduction.php#1.%20Writing%20Microcontroller%20Code?osCsid=8qdtq2emob7vfeskoolagc4c92http://microcontrollershop.com/An%20Embedded%20Tools%20Introduction.php#2.%20Translating%20the%20Code?osCsid=8qdtq2emob7vfeskoolagc4c92http://microcontrollershop.com/An%20Embedded%20Tools%20Introduction.php#Debugging%20the%20Code?osCsid=8qdtq2emob7vfeskoolagc4c92http://microcontrollershop.com/An%20Embedded%20Tools%20Introduction.php#Debugging%20Tools?osCsid=8qdtq2emob7vfeskoolagc4c92http://microcontrollershop.com/An%20Embedded%20Tools%20Introduction.php#Emulators?osCsid=8qdtq2emob7vfeskoolagc4c92http://microcontrollershop.com/An%20Embedded%20Tools%20Introduction.php#4.%20OTP%20and%20Flash%20Programming?osCsid=8qdtq2emob7vfeskoolagc4c92http://microcontrollershop.com/An%20Embedded%20Tools%20Introduction.php#1.%20Writing%20Microcontroller%20Code?osCsid=8qdtq2emob7vfeskoolagc4c92http://microcontrollershop.com/An%20Embedded%20Tools%20Introduction.php#2.%20Translating%20the%20Code?osCsid=8qdtq2emob7vfeskoolagc4c92http://microcontrollershop.com/An%20Embedded%20Tools%20Introduction.php#Debugging%20the%20Code?osCsid=8qdtq2emob7vfeskoolagc4c92http://microcontrollershop.com/An%20Embedded%20Tools%20Introduction.php#Debugging%20Tools?osCsid=8qdtq2emob7vfeskoolagc4c92http://microcontrollershop.com/An%20Embedded%20Tools%20Introduction.php#Emulators?osCsid=8qdtq2emob7vfeskoolagc4c92http://microcontrollershop.com/An%20Embedded%20Tools%20Introduction.php#4.%20OTP%20and%20Flash%20Programming?osCsid=8qdtq2emob7vfeskoolagc4c92
  • 7/30/2019 PIC16f877a Notes

    3/59

    include debuggers, which work with certain emulators, into their development suites.

    A Debugger allows you to download your code to the emulator's memory and then control allof the functions of the emulator from a PC. Common debugging features include the capability

    to examine and modify the microcontroller's on-chip registers, data- and program-memory;pausing or stopping program executing at defined program locations by setting breakpoints;single-stepping (execute one instruction at a time) through the code; and looking at a historyof executed code (trace).

    So far we've talked about several different pieces of software: Text Editor, Assembler orCompiler, Linkers, Librarians and Debugger. You can easily imagine that it can become quite atime-consuming challenge to alternate back and forth between all of these programs duringthe debugging process (discover a bug, edit the source code, compile it again, link it again,download the modified code to the emulator, etc.). This is where an integrated developmentenvironment (IDE) comes in.

    An Integrated Development Environment puts all of the previously discussed softwarecomponents under one common unified user interface, so that it becomes possible to make acode change and get the modified code loaded into the emulator with a few mouse clicks,instead of dozens. A good IDE allows you for example to click on a syntax error messageproduced by the compiler and have the source code with the highlighted offending instructionpop up for editing in the text editor. One click of a button and the modified code getsretranslated, linked and downloaded to the emulator. An IDE allows you to store theconfiguration settings for a project - like compiler switches, or what flavor of chip to emulate- so you can easily recreate a project later on. Some IDEs are flexible enough to allow you toincorporate different choices of third party tools (like compilers and debuggers), others onlywork with a manufacturer's own tool chain.

    Debugging Tools

    When it comes to debugging your code and testing your application there are several differenttools you can utilize that differ greatly in terms of development time spend and debuggingfeatures available. In this section we take a look at simulators, microcontroller starterkits and emulators.

    Simulators

    Simulators try to model the behavior of the complete microcontroller in software. Somesimulators go even a step further and include the whole system (simulation of peripheralsoutside of the microcontroller). No matter how fast your PC, there is no simulator on themarket that can actually simulate a microcontroller's behavior in real-time. Simulatingexternal events can become a time-consuming exercise, as you have to manually create"stimulus" files that tell the simulator what external waveforms to expect on whichmicrocontroller pin. A simulator can also not talk to your target system, so functions that relyon external components are difficult to verify. For that reason simulators are best suited totest algorithms that run completely within the microcontroller (like a math routine forexample). They are the perfect tool to complement expensive emulators for largedevelopment teams, where buying an emulator for each developer is financially not feasible.

    Microcontroller Starter Kits

    Starter Kits, commonly bundle a hardware board and in-system programmer with somesoftware components (assembler, linker, debugger, sometimes an IDE and a code-size limited

    http://microcontrollershop.com/An%20Embedded%20Tools%20Introduction.php#Simulators?osCsid=8qdtq2emob7vfeskoolagc4c92http://microcontrollershop.com/An%20Embedded%20Tools%20Introduction.php#Microcontroller%20Starter%20Kits?osCsid=8qdtq2emob7vfeskoolagc4c92http://microcontrollershop.com/An%20Embedded%20Tools%20Introduction.php#Microcontroller%20Starter%20Kits?osCsid=8qdtq2emob7vfeskoolagc4c92http://microcontrollershop.com/An%20Embedded%20Tools%20Introduction.php#Emulators?osCsid=8qdtq2emob7vfeskoolagc4c92http://microcontrollershop.com/An%20Embedded%20Tools%20Introduction.php#Simulators?osCsid=8qdtq2emob7vfeskoolagc4c92http://microcontrollershop.com/An%20Embedded%20Tools%20Introduction.php#Microcontroller%20Starter%20Kits?osCsid=8qdtq2emob7vfeskoolagc4c92http://microcontrollershop.com/An%20Embedded%20Tools%20Introduction.php#Microcontroller%20Starter%20Kits?osCsid=8qdtq2emob7vfeskoolagc4c92http://microcontrollershop.com/An%20Embedded%20Tools%20Introduction.php#Emulators?osCsid=8qdtq2emob7vfeskoolagc4c92
  • 7/30/2019 PIC16f877a Notes

    4/59

    "evaluation" version of a compiler), to allow for very basic emulation and debugging functions.These kits are most predominant with Flash based microcontrollers. The Flash memory allowsan actual sample of the microcontroller to be used to "emulate" itself, by using the includedin-system programmer to download the code into the Flash and execute it.

    To enable some basic debugging, those kit's need to download a small piece of monitor codealong with your own code. This monitor code allows you to stop execution (break) and examinememory and of course uses some of the microcontroller's resources (interrupts; stack-, code-and data-memory; some pins). That's why this approach is called intrusive or non-transparentemulation.

    Included with the starter kits is an evaluation board, whose main purpose it is to get youstarted on your development quickly without the need to develop your own hardware board.The board is typically equipped with a sample of a microcontroller to allow you to execute andevaluate your code. The kits also support the capability to hook up your own hardware if youprefer a setup closer to your final application.

    Do not confuse the evaluation boards with a FLASH or OTP production programmer. Eventhough the kits offer programming capability, the microcontroller sockets on the boards arenot built to withstand hundreds or thousands of insertions and are also not equipped with asocket for all controller packages (sockets only for DIP/PLCC packages, but not for SO or QFPpackages).

    A big advantage of these kits over simulators is that they work in real-time and thus allow foreasy input/output functionality verification. Simulators on the other hand offer typically muchmore powerful debugging features that rival those of high-end emulators. Starter kits,however, are completely sufficient and the cheapest option to develop simple microcontrollerprojects .

    Emulators

    An emulator is a piece of hardware that ideally behaves exactly like the real microcontrollerchip with all its integrated functionality. It is the most powerful debugging tool of all. Amicrocontroller's functions are emulated in real-time and non-intrusively.

    All emulators contain 3 essential functions in different implementation forms:

    The emulator control logic, including emulation memory

    The actual emulation device

    A pin adapter that gives the emulator's target connector the same "package" and pinoutas the microcontroller to be emulated

    Most emulators give you a range of choices of exchangeable pin adapters and emulationdevices to built your own customized emulator that supports the exact derivative and packageof your specific microcontroller.

    An emulator in my definition always works transparent or non-intrusive (of course someemulator manufacturers will disagree). This means none of a microcontroller's on-chipresources or I/O pins are lost due to emulation. If emulation is not transparent, then it's not anemulator, but an evaluation, development or starter kit. If you are developing projects ofmedium to large complexity, a non-intrusive emulator will save you lots of time and grey hair.

    http://microcontrollershop.com/An%20Embedded%20Tools%20Introduction.php#Emulation%20Control%20Logic?osCsid=8qdtq2emob7vfeskoolagc4c92http://microcontrollershop.com/An%20Embedded%20Tools%20Introduction.php#Emulation%20Memory?osCsid=8qdtq2emob7vfeskoolagc4c92http://microcontrollershop.com/An%20Embedded%20Tools%20Introduction.php#Bond-Out%20Emulation%20Chips%20versus%20PLD%20Implementations?osCsid=8qdtq2emob7vfeskoolagc4c92http://microcontrollershop.com/An%20Embedded%20Tools%20Introduction.php#Emulation%20Control%20Logic?osCsid=8qdtq2emob7vfeskoolagc4c92http://microcontrollershop.com/An%20Embedded%20Tools%20Introduction.php#Emulation%20Memory?osCsid=8qdtq2emob7vfeskoolagc4c92http://microcontrollershop.com/An%20Embedded%20Tools%20Introduction.php#Bond-Out%20Emulation%20Chips%20versus%20PLD%20Implementations?osCsid=8qdtq2emob7vfeskoolagc4c92
  • 7/30/2019 PIC16f877a Notes

    5/59

    Emulation Memory

    Because, depending on memory technology, a microcontroller's program memory can not(ROM) or only once (OTP) be programmed, an emulator uses external static RAM as the

    emulated micro's program memory. Even some Flash based microcontrollers can, depending onmanufacturer, only be re-programmed 100 to 1000 times, which warrants the use of externalRAM memory rather than the micro's integrated Flash for emulation. RAM memory allows forcode to be changed quickly and an "indefinite" number of times during the software debuggingprocess.

    Bond-Out Emulation Chips versus PLD Implementations

    As higher-end emulators typically use external RAM memory as program memory, it becomesapparent that in some instances they can not use a standard sample of the emulatedmicrocontroller for emulation purposes. They need special bond-out chips of themicrocontroller to be emulated. Those bond-out chips have additional pins that allow the

    emulator electronics to feed the externally stored program information to the microcontrollerin place of the on-chip memory contents in real time; control the program execution flow; andaccess on-chip registers and data memory.

    Instead of special bond-out chips, some emulator manufacturers program a microcontroller'scomplete functional model into a PLD (programmable logic device). A drawback of thisapproach is that you never know how accurate the PLD model of the microcontroller iscompared to the "real thing". It only works in real-time with models of less complex and slowermicrocontrollers. On the plus side such an emulator can easily be reconfigured to supportmany different derivatives of a microcontroller family.

    Emulation Control Logic

    Contributing to the cost of emulators is the control logic required to recreate functions thatmight be lost due to the emulator using those resources (e.g. some standard I/O pins). Byrecreating such functions with additional logic, those emulators work truly transparent or non-intrusive, which means you have all the pins, all the memory and all the peripheral functionsavailable like with the real microcontroller.

    Even more control logic is required to implement high-end emulator features like complexbreakpoint trigger conditions, external event trigger conditions, loop counters, trace memoryand in some cases even logic analyzer functions.

    Technical Approaches to Emulation

    Existing emulators today use one of several approaches to emulation, which we will cover inthe following sections.

    Base Unit and Probecard

    Many emulators consist of a base unit and a "probecard". The base unit is connected to a PCvia the serial, parallel or USB port. It contains the majority of the emulator electronics, withthe exception of the emulation chip itself. The emulation chip is a special bond-out version ofthe actual microcontroller and is mounted on a separate small PCB, called a probecard. This

    probecard connects via a ribbon cable to the base unit and has a pin adapter at the bottom,which allows the probecard to be plugged into a socket on the actual target application board

  • 7/30/2019 PIC16f877a Notes

    6/59

    in place of the actual microcontroller.

    The advantage of partitioning the emulator into a base unit and separate probecard is that one

    and the same base unit can support many different derivatives of a given microcontrollerarchitecture (e.g. all 8051 devices).

    By purchasing different probecards the emulator can then be changed to support all the on-chip features and packages of your specific microcontroller derivative(s) of choice. Anotheradvantage is that the probecard can be kept relatively small, which makes it easier to plug itinto the target in space constrained applications.

    The probecard approach also minimizes the physical distance of the emulation chip from thelocation of the final microcontroller, minimizing the impact of noise and additionalcapacitive/resistive loading that can become issues when analog peripherals need to beemulated.

    Debug Board Modules (DBM)

    The debug board approach combines all of the emulator electronics and the actualemulation chip onto a single, larger sized PCB. This PCB is typically not housed in an enclosureto save cost.

    The connection to the target system is accomplished by ribbon cables, which provide, on oneend, a connector that can plug into an actual chip package socket of the target system. Thismeans that all pin signals for the microcontroller to be emulated are now routed via thisribbon cable that connects the target system with the debug board, including any analogsignals to be measured by the microcontroller. This is a less than desirable solution if your

    micro has for example high resolution A/D converters and you'd like to make accuratemeasurements also during emulation.

    DBMs are in most cases dedicated to emulating a single specific microcontroller and can not bemodified to support other derivatives of a family. If you want to emulate a new derivative youhave to buy a new DBM. On the plus side DBM's are typically priced lower than emulators usingthe probecard approach. DBM's emulation and debugging capabilites often range above starterkits, but below probecard based emulators, with certain exceptions being the rule (DBM hasall the features of high-end probecard emulator).

  • 7/30/2019 PIC16f877a Notes

    7/59

    Motherboards and Daughtercards

    There are several variations of the concepts discussed above on the market. One such variationis to put probecard and base unit into a single enclosure. The "base unit" in that case is a"motherboard" and the probecard a "daughtercard" that connects onto the motherboard. Thiscombination then directly plugs into the target board via a matching pin socket adapter at thebottom. These emulators can still be adapted to emulate different derivatives by exchangingthe daughtercard.

    Dedicated Emulators

    Then there are several forms of the "dedicated emulator", which only supports a very narrowrange of microcontroller devices (usually micros with identical functionality and pinout, butdifferent memory sizes).

    In some implementations dedicated emulators are nothing more than a Debug Board Module, inothers take the form of base unit and probecard with the probecard not being exchangeable. Athird variant combines base and probecard onto a single non-exchangeable PCB (with orwithout enclosure) that can directly plug into the target system.

    Emulators Using Microcontroller FLASH Memory

    With the advent of FLASH program memory a new approach in microcontroller emulationbecame possible. The electrical erase/write capability of FLASH program memory, incombination with emulation support circuitry and code embedded in the microcontroller,enable each such microcontroller to be its own emulator. Unfortunately this does not workwith all FLASH micros on the market today; especially earlier generation FLASH devices lackthe necessary on-chip emulation support circuitry.

    Flash microcontrollers that have the necessary on-chip emulation support can, regardless ofpackage, be directly soldered into the target application. This, of course, means that now themicrocontroller chip sees the exact same analog environment as the finalized application - abig advantage when it comes to accurately emulating on-chip analog peripherals.

  • 7/30/2019 PIC16f877a Notes

    8/59

    The only connection now required to enable PC based software debugging are a few fullydigital I/O pins of the controller. The "normal" digital function of those I/Os is recreated ona small piece of hardware that sits between the PC and the target system, so that none of thecontroller's I/Os is lost.

    One common on-chip emulation interface for this kind of emulators is the JTAG interface,mostly found on 16-bit and higher microcontrollers. 8-bit devices frequently featureproprietary interfaces to save on cost.

    As opposed to emulators for ROM and OTP devices, Flash emulators do not require RAMmemory to store the program code, but use the microcontroller's on-chip FLASH memory. Thisfurther saves cost and makes those emulators cheaper.

    A disadvantage of using the FLASH memory is that program downloads (required after everycode change) take much longer. The microcontroller's FLASH memory life-time is limited.Depending on manufacturer, the number of write/erase cycles the memory can withstand

    varies anywhere between 100 and 100.000 cycles.

    On the plus side, FLASH emulators at the same time also double-function as a FLASHprogrammer, as the program code has to be downloaded into the chip's memory. Emulators forOTPs or ROMs (than can of course also support the FLASH version of a pin/function compatibledevice, but then in combination with external program memory), do not support anyprogramming functions.

    Another advantage of FLASH emulators is the fact that one and the same emulator can supportall Flash derivatives of a given microcontroller architecture. If a new device with newfunctionality comes out, all you need is a sample of that new device and an update of thedebugger software. No more need to buy new probecards or debug modules for each new

    derivative.

    4. OTP and Flash Programming

    It can't be stretched enough: A starter kit or emulator are no substitute for a production gradeprogrammer. Using the microcontroller sockets on starter kit boards is ok to program one ortwo samples in the lab, but those sockets can not withstand hundreds or thousands ofinsertions. You will also find that starter kits do not include any sockets for surface mountdevices, as those sockets are extremely expensive.

    Out-of-Circuit Programming

    OTP microcontrollers are typically programmed out-of-circuit. That means the microcontrolleris programmed before being soldered on the target board. For that purpose production gradeprogrammers offer a choice of optional, high quality, expensive, zero-insertion-force (ZIF) pinadapters to support different package flavors.

    In-System Programming (ISP)

    FLASH microcontrollers can be programmed both in-circuit (in-system) and out-of-circuit.

    With in-circuit programming the microcontroller is already soldered into the target system and

    can be programmed via one of its communication interfaces (UART, SPI). This requires that youhave the signals required for programming routed to an in-system-programming (ISP) connectorto which an ISP programmer can be hooked up. The ISP connector required varies from

  • 7/30/2019 PIC16f877a Notes

    9/59

    manufacturer to manufacturer and microcontroller to microcontroller, so it is recommendedthat before you start your PCB layout, you decide on which ISP programmer you want to useand find out which ISP connector is required for it.

    As ISP programming is done via a serial interface it is slower than out-of-circuit programmingthat uses parallel data transfers - something you might want to consider if you have toprogram 100 000 devices.

    One big advantage of ISP programmers is the fact that they do not require expensive ZIF socketadapters. All you need is the ISP connector on your board and the microcontroller solderedonto the board to program even the most exotic package.

    Having an ISP connector on your board is a good idea - even if you use out-of-circuitprogramming for production. It enables you to do painless firmware updates or last minute bugfixes without having to disolder the microcontroller first.

  • 7/30/2019 PIC16f877a Notes

    10/59

    Fourth semester BE Degree Examination,(IV Sem Common to EC/TC/ML)

    Model Paper-ISUB-CODE :06EC-42 SUB: MICROCONTROLLERS

    Duration : 3 Hrs Max Marks: 100

    Answer any five questions choosing at least two from each part

    PART AQI.(a) Give the comparison between microprocessor and microcontroller.(6M)b) With neat block diagram explain the architectural features of 805 I(10 M)c) Write the program status word format of 8051 with individual bitoperations (4M)

    Q2. a) Differentiate between the following instructions of 8051microcontroller.(i) SWAP and XCHG(ii) MOVX and MOVC(iii) Bit level ANL and byte level ANL (6M)b) Write an assembly language program to find the square root of anumber and store in Ro . (5M)c) What is the principle of stack memory? .Explain with the help ofPUSH & POP instructions. (6M)d) Calculate time required to PUSH DPTR, B, A, PSW and PC on to thestack. Assume XTAL= I I .0592 MHz (3M)Q3. a) What are the different ranges associated with CALLinstructions of 8051?. (6M)b) Give different steps followed by 8051 in response to interrupt.How we can enable or disable the interrupts? ( 6M)c) Write an assembly program to sort an array in an ascendingorder. (8M)Q4. a) What are the different ways to introduce a delay in 8051 C.Give the three factors which affect the accuracy of the delay.( 6M)b) Write an 8051 C program to toggle the bits of P1 ports continuouslywith a 250 ms delay. (6M)c) Write an 8051 C program to get an 8 bit binary number from P1 ,convert it in to ASCII and save the result in memory location 50H.(8M)PART BQ5. a) What are counting & timing requirements? Explain modes of

    operation of timer / counter with relevant block diagrams(10M)b) Assuming XTAL = 11.0592MHz generate a square wave of 2KHz on P2.3 (6M)c) Assuming XTAL = 11.0592MHz indicate when the TF0 flag israised for the following program.MOV TMOD,# 01HMOV TL0 # 10HMOV TH0, # 1CHSETB TR0 (4M)Q6. a) What is asynchronous serial communication and dataframing (6M)b) Write RS232 standards for DB9 pin out. (8M)c) Write an 8051 C program to receive byte of data serially & put

    them on P1. Set the baud rate to 4800, 8 bit data, 1 stop bit.(6M)

  • 7/30/2019 PIC16f877a Notes

    11/59

    Q7. a) What are external interrupts ? How they are handled in 8051?How level triggered interrupts are reset? How to set INT1 as edgetriggered interrupt? (8M)b) Write a program using interrupts to do the following.i) Receive data serially and set it to P0.ii) Have P1 port to read and transmitted serially and copy

    given to p2.iii) Make timer 0 generate a square wave of 5 KHzfrequency on P0.1.Assume XTAL = 11.0592MHz (12M)Q8 a) Draw the block schematic of stepper motor interfaced to8051 at port P0 for the rotation of 45 degrees inanticlockwise direction. Write a C program for the same.Assume motor step angle as 1.8 degrees per step.(10M)b) Interface 2x16 line LCD to 8051. Write a C code to display" WELCOME" on LCD. (10M)

    B.E/B.TECH.DEGREE EXAM, MAY/JUNE 2007. Fifth SemComputer Science and Engineering

    CS1304 MICROPROCESSORS AND MICROCONTROLLERS

    (Regulation 2004)

    Time: Three hours Maximum: 100 marks

    Answer ALL questions

    PART A (10 2 = 20 marks)

    1. How address and data lines are demultiplexed in 8085?

    2. What is the function performed by SIM instruction in 8085?

    3. What is pipelined architecture?

    4. How the interrupts can be masked/unmasked in 8086?

    5. What are the signals involved in memory bank selection in 8086

    micro processor?

    6. How clock signal is generated n 8086? What is the maximum internal clock

    frequency of 8086?

    7. What is the function of gate signal in 8254 timer?

    8. Write the format of KW1 in 8259.

    9. List the interrupts of 8051 micro controller.

    10. What are register banks in 8051 microcontroller?

    PART B (5 16 = 80 marks)

    11. (a) (i) Explain the various logical and arithmetic instructions available in 8085 microprocessor. (10)

    (ii) Explain the function of various flags of 8085 microprocessor (6)

    Or

    (b) (i) Differentiate between I/O mapped I/O and memory mapped I/O. (6)

    (ii) Write an 8085 assembly language program to convert 8 bit binary to ASCII code. (10)

  • 7/30/2019 PIC16f877a Notes

    12/59

    12. (a) (i) Describe the action taken by 8086 when INTR pin is activated. (6)

    (ii) Write an assembly language program in 8086j to search the largest data in an array. (10)

    Or

    (b) (i) Discuss the various addressing modes of 80896 microprocessor. (10)

    (ii) Explain the following assembler directives used in 8086

    (1) ASSUME

    (2) EQU

    (3) DW (8)

    13. (a) (i) Explain in detail about memory access mechanism in 8086 (8)

    (ii) Explain the function of following 8086 signals.

    (1) HLDA(2) RQ/GTO

    (3) DEN

    (4) ALE. (8)

    Or

    (b) (i) Draw and explain a block diagram showing 8086 in maximum mode configuration. (12)

    (ii) What are the advantages of the multiprocessor systems? (4)

    14. (a) (i) With the help of block diagram explain the operation of USART (8251A) (10)

    (ii) Discuss the salient features of 8259 programmable interrupt controller. (6)

    Or

    (b) (i) Describe the various modes of operations in 8253 programmable intervalTimer. (8)

    (ii) Explain the operation of DMA controller (8237).

    15. (a) With a suitable block diagram, explain the architecture of 8051 microcontroller. (16)

    Or

    (b) Discuss in detail about 8051 based stepper motor control along with necessary hardware and software. (16)

    EC1362--MICROPROCESSOR AND MICROCONTROLLER

    Time: Three hours Maximum marks: 100

    Answer ALL questions

    PART A (10 x 2 =20 marks)

  • 7/30/2019 PIC16f877a Notes

    13/59

    1. What is the significance of I/O ports?

    2.What are the different machine cycles in 8085 Microprocessor?

    3. Write the difference between opcode and operand?

    4.Write the stack related instructions in 8085 Microprocessor?

    5. What is the maximum number of I/O devices that can be connected to 8085 Microprocessor using 8259 ICs?

    6. What is the bit set reset mode of 8255 PPI?

    7. What are the different addressing modes of Microcontroller 8051?

    8. Name the interrupts available Microcontroller 8051?

    9. Name any four bit manipulation instructions in Microcontroller 8051?

    10. How can you perform multiplication using 8051 Microcontroller?

    PART B (5 x 16 = 80)

    11 (a) Draw and explain the timing diagram of the following instructions of 8085 Microprocessor,

    (i) LDA 2050H

    (ii) RET (16)

    (or)

    (b)With necessary diagrams,write short notes on the following:

    (i) RAM memory interfacing

    (ii)ROM memory interfacing

    (iii) Interrupt structure of 8085(16) .

    12. (a) Define addressing mode.Explain the different addressing modes of 8085 with examples . (16)

    (or)

    (b) Write 8085 Assembly language program to perform the following, ab+ac, where a, b and c are 8 bit binary

    numbers.Explain with algorithm and flowchart. (16)

    13 (a)With neat block diagram,explain the architecture of 8251 USART(16)

    (or)

    (b)With necessary diagrams explain the interfacing of Analog to Digital converter with Microprocessor 8085(16)

    14. (a) With functional block diagram,explain the architecture of Microcontroller 8051..(16)

    (or)

  • 7/30/2019 PIC16f877a Notes

    14/59

    (b) Explain the Timer/Counter functional unit of Microcontroller 8051 with relevant diagrams..(16)

    15. (a)Explain the 4X4 Keyboard interfacing with Microcontroller 8051(16)

    (or)

    (b) Explain the Microcontroller 8051 based Stepper motor control(16)

    Elective Paper IV (A): PRACTICALS (90 Hours- 30 Sessions)Embedded Systems and Applications LabMicrocontroller Experiments using 8051 kit1. Multiplication of two numbers using MUL command (later using countermethod forrepeated addition )2. Division of two numbers using DIV command (later using counter methodfor repeatedsubtraction )3. Pick the smallest number among a given set of numbers4. Pick the largest number among a given set of numbers5. Arrange n numbers in ascending order6. Arrange n numbers in descending order7. Generate a specified time delay8. Interface a ADC and a temperature sensor to measure temperature9. Interface a DAC & Generate a stair case wave form with step duration andno. ofsteps as variables

    10. Flash a LED connected at a specified out put port terminal11. Interface a stepper motor and rotate it clock wise or anti clock wisethrough givenangle steps12. Using Keil software write a program to pick the smallest among a given setof numbers13. Using Keil software write a program to pick the largest among a given setof numbers14. Using Keil software write a program to arrange a given set of numbers inascendingorder

    15. Using Keil software write a program to arrange a given set of numbers indescendingorder16. Using Keil software write a program to generate a rectangular wave form ata specifiedport terminalNote: Student has to perform the following experiments(1) 8 Experiments among experiment numbers 1 to 11(2) Any four experiments from 12 to16STUDENTS ARE ENCOURAGED TO DO A SMALL PROJECT WORK DURINGTHIRD

    YEARMODEL QUESTION PAPER

  • 7/30/2019 PIC16f877a Notes

    15/59

    Section ALong answer questions ( 3 x 20 = 60 marks)Two questions each from Unit I & Unit IIOne question each from Unit III & Unit IVSection B

    Short Answer questions ( 5 x 8 = 40 marks)Two questions each from I, III & IVThree questions from Unit IISCHEME OF VALUATION FOR PRACTICALS FOR PAPER III & IV1. Logical expressions Formula/Flowchart 5 marks2. Block Diagram and test tables/Program writing 15 marks3. Observations / Program execution 12 marks4. Result 3 marks5. Record 10 marks6. Viva voce 5 marks

    ------------

    50 marks-----------

    aaa

  • 7/30/2019 PIC16f877a Notes

    16/59

    15.0 INSTRUCTION SET SUMMARYThe PIC16 instruction set is highly orthogonal and is comprised of three basiccategories: Byte-oriented operations Bit-oriented operations

    Literal and control operationsEach PIC16 instruction is a 14-bit word divided into an opcode which specifies theinstruction type and one or more operands which further specify the operation of theinstruction. The formats for each of the categories is presented in Figure 15-1, whilethe various opcode fields are summarized in Table 15-1. Table 15-2 lists theinstructions recognized by the MPASM Assembler. A complete description of eachinstruction is also available in the PICmicro Mid-Range MCU Family ReferenceManual (DS33023).Forbyte-oriented instructions, f represents a file register designator and drepresents a destination designator. The file register designator specifies which fileregister is to be used by the instruction. The destination designator specifies where

    the result of the operation is to be placed. If d is zero, the result is placed in the Wregister. If d is one, the result is placed in the file register specified in the instruction.Forbit-oriented instructions, b represents a bit field designator which selects thebit affected by the operation, while f represents the address of the file in which thebit is located.Forliteral and control operations, k represents an eight or eleven-bit constant orliteral value One instruction cycle consists of four oscillator periods; for an oscillatorfrequency of 4 MHz, this gives a normal instruction execution time of 1 s. Allinstructions are executed within a single instruction cycle, unless a conditional test istrue, or the program counter is changed as a result of an instruction. When thisoccurs, the execution takes two instruction cycles with the second cycle executed asa NOP. All instruction examples use the format 0xhh torepresent a hexadecimal number, where h signifies a hexadecimal digit.

    15.1 READ-MODIFY-WRITE OPERATIONSAny instruction that specifies a file register as part of the instruction performs aRead-Modify-Write (R-M-W) operation. The register is read, the data is modified, andthe result is stored according to either the instructionor the destination designator d. A read operation is performed on a register even ifthe instruction writes to that register.For example, a CLRF PORTB instruction will read PORTB, clear all the data bits,

    then write the result back to PORTB. This example would have the unintended resultthat the condition that sets the RBIF flag would be cleared.

  • 7/30/2019 PIC16f877a Notes

    17/59

  • 7/30/2019 PIC16f877a Notes

    18/59

  • 7/30/2019 PIC16f877a Notes

    19/59

  • 7/30/2019 PIC16f877a Notes

    20/59

  • 7/30/2019 PIC16f877a Notes

    21/59

  • 7/30/2019 PIC16f877a Notes

    22/59

  • 7/30/2019 PIC16f877a Notes

    23/59

  • 7/30/2019 PIC16f877a Notes

    24/59

    PIC-Microcontroller (Peripheral Interface controller)

    Why is PIC preferred?

    PIC is famous with both industrial developers and hobbyists due to:

    1. Wide availability.

    2. Extensive collection of application notes.

    3. Low cost or free development-tools.

    4. serial programming and re-programming with flash memory.

    5. simple RISC instruction set.

    Limitations of PIC

    1. Register bank switching

    2. Stack is not addressable (i.e. not s/w accessible)

    There are various versions of PIC, how they are differentiated.

    X=numbers

    L=letters/alphabets

    PIC XX LL XXX LL - L / PP (PPP)

    PIC-Peripheral interface controller

    XX can be 10,12,14,16,17,18,30....etc

    30 = 24-bit core

    17,18 = 16-bit core

    rest =12/14-bit cores

    LL=type of Program memory

  • 7/30/2019 PIC16f877a Notes

    25/59

    C = OTP Onetime programmable

    CR= ROM factory programmed

    CE= OTP + separate EEPROM

    F = electrically programmable flash

    LF= Low voltage flash

    LC= Low voltage OTP

    LCR=low voltage ROM

    XXX= versions part number

    LL= could indicate:

    A/B=indicates a revision

    T =Part only available on tape/reel

    -L indicates temperature range

    - = 0 to 70 deg C (commercial)

    i = -40 to 70 deg C (Industrial)

    E = -40 to 125 deg C (Automotive)

    PP (PPP) indicates packaging type

    PIC16F877A is available in 4 types of packages

    40-PIN PDIP- plastic dual inline package

    44-PIN PLCC-plastic leaded chip carrier

    44-PIN TQFP-thin quad flat package

    44-PIN QFN-Quad flat package, No leads

    PIC16F87XA Salient Features

    8bit Microcontroller (ALU can process 8-bits in parallel)

    RISC architecture

    Harvard Architecture

    Only 35 single-word instructions

    All single-cycle instructions except for program branches, which are two-cycle Operating speed: DC 20 MHz clock input

  • 7/30/2019 PIC16f877a Notes

    26/59

    Up to 8K x 14 words of Flash Program Memory

    Up to 368 x 8 bytes of Data Memory (RAM)

    Up to 256 x 8 bytes of EEPROM Data Memory

    Watch Dog Timer + 3 timer/counter modules

    Two Capture, Compare, PWM modules

    Serial communication through: MSSP USART

    Parallel Slave Port (PSP) 8 bits wide with external RD, WR and CS controls(40/44-pin only)

    Brown-out detection circuitry for Brown-out Reset (BOR)

    Power On Reset 10-bit, up to 8-channel Analogue-to-Digital Converter (A/D) 2 Comparator modules

    5 I/O ports namely Port A, B, C, D, E

    15 Interrupt sources 8-level deep h/w stack

  • 7/30/2019 PIC16f877a Notes

    27/59

    Architectural Block Diagram of PIC16F877A

  • 7/30/2019 PIC16f877a Notes

    28/59

    ARCHITECTURAL features

    ALU- Arithmetic and logic unitPIC16F877A has a 8-bit ALU which operates on temporary working register (W-

    register) as one of the operands and any other file register or an immediate constant(literal) as the other operand.Depending on the instruction executed the ALU affects the various flags of statusregister.

    W-Regs- Working-registerW-reg is a 8-bit wide reg. It contains one of the operands during execution ofinstructions and may serve as destination for the result of the operation. This hassimilar function as that of accumulator in other controllers and processors.

    STACK

    PIC16F877A has an 8 level deep X 13-bit wide hardware stack. The stack space isnot a part of either program or data memory and the stack pointer is not readable orwriteable.The program counter content are pushed onto the stack when a CALL instruction isexecuted or an INTERRUPT causes a branch. The stack is popped in the event of aRETURN, RETLW or RETFIE instruction execution.The stack operates as a circular buffer i.e. after stack is been pushed 8 times the 9thpush overwrites the first push, the 10th push overwrites the 2nd push.There are no status bits to indicate stack overflow or stack underflow conditions.there are no PUSH or POP instructions.

    8-LEVEL X 13-BIT WIDE HARDWARE STACK

  • 7/30/2019 PIC16f877a Notes

    29/59

    MEMORY ORGANIZATIONThere are three memory blocks in each of the PIC16F87XA devices:

    Up to 8K x 14 words of Flash Program Memory Up to 368 x 8 BITSs of Data Memory (RAM)

    Up to 256 x 8 BITS of EEPROM Data Memory

    The program memory and data memory have separate buses so that concurrentaccess can occurProgram Memory OrganizationThe PIC16F877A device has a 13-bit program counter (PC) capable of addressingan 8K word x 14 bit program memory space. It has 8K words x 14 bits of Flashprogram memory. Accessing a location above the physically implemented addresswill cause a wraparound.Two locations in Program memory are treated in a special way by the CPU:

    After Reset the PC points to 0000H reset vector.

    content of location 0004h interrupt vector is loaded in the PC automatically ifinterrupt occurs when enabled. i.e. at location 0004 a goto ISR can be writtenand the ISR can be anywhere in the 8k program memory between 0005 to1FFF.

    PROGRAM COUNTER

  • 7/30/2019 PIC16f877a Notes

    30/59

    The Program Counter (PC) is 13 bits wide. The low byte comes from the PCLregister which is a readable and writable register. The upper bits (PC) are notreadable, but are indirectly writable through the PCLATH register.PCL = lower byte of program counter. it can be read/written like any other registerPCH=upper bits of PC which are not read able but are indirectly writable through

    PCLATH regPCLATH= PCLATH reg is like any other reg which can be read and written to. It isdifferent from PC i.e. it is a separate entity. Any write to PCL will cause the contentsof PCLATH to be automatically transferred to the higher bits of the 13-bit PC (PCH).

    On any Reset, the upper bits of the PC will be cleared. Below Figure shows the twosituations for the loading of the PC. The upper example in the figure shows how thePC is loaded on a write to PCL (PCLATH PCH). The lower example in thefigure shows how the PC is loaded during a CALL or GOTO instruction(PCLATH PCH)

    Program Memory PagingAll PIC16F87XA devices are capable of addressing a continuous 8K word block ofprogram memory. The CALL and GOTO instructions provide only 11 bits of addressto allow branching within any 2K programmemory page. When doing a CALL or GOTO instruction, the upper 2 bits of theaddress are provided by PCLATH. When doing a CALL or GOTO instruction,the user must ensure that the page select bits areprogrammed so that the desired program memory page is addressed. If a returnfrom a CALL instruction (or interrupt) is executed, the entire 13-bit PC is popped off

    the stack. Therefore, manipulation of the PCLATH bits is not required for theRETURN instructions (which POPs the address from the stack).

  • 7/30/2019 PIC16f877a Notes

    31/59

    Note: The contents of the PCLATH register are unchanged after a RETURN orRETFIE instruction is executed. The user must rewrite the contents of the PCLATHregister for any subsequent subroutine calls orGOTO instructions.

    Example 2-1 shows the calling of a subroutine in page 1 of the program memory.This example assumes that PCLATH is saved and restored by the Interrupt ServiceRoutine (if interrupts are used).

    ORG 0x500BCF PCLATH,4BSF PCLATH,3 ;Select page 1

    ;(800h-FFFh)CALL SUB1_P1 ;Call subroutine in: ;page 1 (800h-FFFh):

    ORG 0x900 ;page 1 (800h-FFFh)SUB1_P1: ;called subroutine

    ;page 1 (800h-FFFh):RETURN ;return to

    ;Call subroutine;in page 0;(000h-7FFh)

    Data Memory Organizationdata memory are of 2 types1) EEPROM data memory2) RAM data memory

    RAM data memory

    The data memory is partitioned into 4 banks which contain the General PurposeRegisters and the Special Function Registers.Each bank extends up to 7Fh (128 bytes). The lower locations of each bank arereserved for the Special Function Registers. Above the Special Function Registers

    are General Purpose Registers, implemented as static RAM. All implemented bankscontain Special Function Registers. Some frequently used Special FunctionRegisters from one bank may be mirrored in another bank for code reduction andquicker access.File registers= memory locations that are addressed by an instruction.Register file Map

  • 7/30/2019 PIC16f877a Notes

    32/59

    Register File Map

  • 7/30/2019 PIC16f877a Notes

    33/59

    GENERAL PURPOSE REGISTER FILEGPR files are on-chip RAM used by programmers to store temporary data duringexecution of programs. each file is a 8-bit register

    SPECIAL FUNCTION REGISTERS

    The Special Function Registers are registers used by the CPU and peripheralmodules for controlling the desired operation of the device. These registers areimplemented as static RAM. The Special Function Registers can be classified intotwo sets: core (CPU) registers related to controlling CPU functions and peripheralregisters that controls in-built peripheral functions.

    CPU registers are: 1) STATUS register, 2) OPTION_REG register, 3) INTCONregister, 4) PIE1 register, 5) PIR1 register, 6) PIE2 register, 7) PIR2 register.

    Status Register (Address 03h,83h,103h,183h)The Status register contains the arithmetic status of the ALU, the Reset status and

    the bank select bits for data memory. The Status register can be the destination forany instruction, as with any other register.

    The register files are addressed from 000 to 1FF which needs a minimum of 9-bits toaddress them. The register file can be accessed either directly, or indirectly, throughthe File Select Register (FSR).There are 2 addressing modes

  • 7/30/2019 PIC16f877a Notes

    34/59

    -> direct addressing mode-> indirect addressing modeIn direct addressing mode the lower 7-bits of the register file is provided by theinstruction itself the other 2 bits come from Bits RP1 (Status) and RP0(Status) the bank select bits of the status register to form the 9-bit register file

    address.

    2.5 Indirect Addressing, INDF and FSR RegistersThe INDF register is not a physical register. Addressing the INDF register will causeindirect addressing. Indirect addressing is possible by using the INDF register. Any

    instruction using the INDF register actually accesses the register pointed to by theFile Select Register, FSR. Reading the INDF register itself, indirectly (FSR = 0) willread 00h. Writing to the INDF register indirectly results in a no operation (althoughstatus bits may be affected). An effective 9-bit address is obtained by concatenatingthe 8-bit FSR register and the IRP bit (Status) as shown in Figure 2-6. A simpleprogram to clear RAM locations 20h-2Fh using indirect addressing is shown inExample 2-2.

    EXAMPLE 2-2: INDIRECT ADDRESSINGMOVLW 0x20 ;initialize pointerMOVWF FSR ;to RAMNEXT CLRF INDF ;clear INDF registerINCF FSR,F ;inc pointerBTFSS FSR,4 ;all done?GOTO NEXT ;no clear nextCONTINUE: ;yes continue

  • 7/30/2019 PIC16f877a Notes

    35/59

  • 7/30/2019 PIC16f877a Notes

    36/59

    Special features of CPU

    All PIC16F87XA devices have a host of features intended to maximize systemreliability, minimize cost through elimination of external components, provide powersaving operating modes and offer code protection. These are:

    - Power-on Reset (POR)- Power-up Timer (PWRT)- Oscillator Start-up Timer (OST)- Brown-out Reset (BOR) Watchdog Timer (WDT) In-Circuit Serial Programming Low-Voltage In-Circuit Serial Programming In-Circuit DebuggerPIC16F87XA devices have a Watchdog Timer which can be shut-off only throughconfiguration bits. It runs off its own RC oscillator for added reliability. There are twotimers that offer necessary delays on power-up. One is the Oscillator Start-up Timer

    (OST), intended to keep the chip in Reset until the crystal oscillator is stable. Theother is the Power-up Timer (PWRT), which provides a fixed delay of 72 ms(nominal) on power-up only. It is designed to keep the part in Reset while the powersupply stabilizes. With these two timers on-chip, most applications need no externalReset circuitry. Sleep mode is designed to offer a very low current power-downmode. The user can wake-up from Sleep through external Reset, Watchdog Timerwake-up or through an interrupt. Several oscillator options are also made available toallow the part to fit the application. The RC oscillator option saves system cost whilethe LP crystal option saves power. A set of configuration bits is used to selectvarious options.

    PCON Register

    The Power Control (PCON) register contains flag bits to allow differentiation betweena Power-on Reset (POR), a Brown-out Reset (BOR), a Watchdog Reset (WDT) andan external MCLR Reset.

  • 7/30/2019 PIC16f877a Notes

    37/59

    Configuration Word(address 2007H)

    The configuration bits can be programmed (read as 0), or left un-programmed (readas 1) to select various device configurations. The erased or un-programmed valueof the Configuration Word register is 3FFFh. These bits are mapped in program

    memory location 2007h. It is important to note that address 2007h is beyond the userprogram memory space which can be accessed only during programming.

  • 7/30/2019 PIC16f877a Notes

    38/59

    OSCILLATOR TYPESThe PIC16F87XA can be operated in four different oscillator modes. The user canprogram two configuration bits (FOSC1 and FOSC0) to select one of these fourmodes: LP-Low-Power Crystal

    XT-Crystal/Resonator HS-High-Speed Crystal/ResonatorRC-Resistor/Capacitor

    ResetThe PIC16F87XA differentiates between various kinds of Reset: Power-on Reset (POR) MCLR Reset WDT Reset Brown-out Reset (BOR)Some registers are not affected in any Reset condition. Their status is unknown on

    POR and unchanged in any other Reset. Most other registers are reset to a Resetstate on Power-on Reset (POR), on the MCLR and WDT Reset, on MCLR Resetduring Sleep and Brownout Reset (BOR). They are not affected by a WDT wake-upwhich is viewed as the resumption of normal operation.

    when this pin is made low (connected to ground) it causes the PIC to resetIt should be noted that a WDT Reset does not drive MCLR pin low.The behaviour of the ESD protection on the MCLR pin differs from previous devicesof this family. Voltages applied to the pin that exceed its specification can result inboth Resets and current consumption outside of device specification during theReset event. For this reason, Microchip recommends that the MCLR pin no longerbe tied directly to VDD. The use of an RCR network, as shown in Figure 14-5, issuggested.

  • 7/30/2019 PIC16f877a Notes

    39/59

    Power-on Reset (POR)A Power-on Reset pulse is generated on-chip when VDD rise is detected (in therange of 1.2V-1.7V). To take advantage of the POR, tie the MCLR pin to VDDthrough an RC network, as described in Section 14.4 MCLR. A maximum risetime for VDD is specified. See Section 17.0 Electrical Characteristics for details.

    When the device starts normal operation (exits the Reset condition), deviceoperating parameters (voltage, frequency, temperature, etc.) must be met to ensureoperation. If these conditions are not met, the device must be held in Reset until theoperating conditions are met. Brown-out Reset may be used to meet the start-upconditions.

    14.6 Power-up Timer (PWRT)The Power-up Timer provides a fixed 72 ms nominal time-out on power-up only fromthe POR. The Power-up Timer operates on an internal RC oscillator. The chip is keptin Reset as long as the PWRT is active. The PWRTs time delay allows VDD to riseto an acceptable level. A configuration bit is provided to enable or disable the PWRT.

    The power-up time delay will vary from chip to chip due to VDD, temperature andprocess variation. See Section 17.0 Electrical Characteristics for details(TPWRT, parameter #33).

    14.7 Oscillator Start-up Timer (OST)The Oscillator Start-up Timer (OST) provides a delay of 1024 oscillator cycles (fromOSC1 input) after the PWRT delay is over (if PWRT is enabled). This helps toensure that the crystal oscillator or resonator has started and stabilized. The OSTtime-out is invoked only for XT, LP and HS modes and only on Power-on Reset orwake-up from Sleep.

    14.8 Brown-out Reset (BOR)The configuration bit, BODEN, can enable or disable the Brown-out Reset circuit. IfVDD falls below VBOR (parameter D005, about 4V) for longer than TBOR(parameter #35, about 100 S), the brown-out situation will reset the device. If VDD falls below VBOR for less than TBOR, a Reset may not occur. Once the brown-outoccurs, the device will remain in Brown-out Reset until VDD rises above VBOR. ThePower-up Timer then keeps the device in Reset for TPWRT (parameter #33, about72 mS). If VDD should fall below VBOR during TPWRT, the Brown-out Resetprocess will restart when VDD rises above VBOR with the Power-up Timer Reset.The Power-up Timer is always enabled when the Brown-out Reset circuit is enabled,

    regardless of the state of the PWRT configuration bit.

    14.9 Time-out SequenceOn power-up, the time-out sequence is as follows: the PWRT delay starts (ifenabled) when a POR Reset occurs. Then, OST starts counting 1024 oscillatorcycles when PWRT ends (LP, XT, HS). When the OST ends, the device comes outof Reset. If MCLR is kept low long enough, the time-outs will expire. Bringing MCLRhigh will begin execution immediately.

    Watchdog Timer (WDT)The Watchdog Timer is a free running, on-chip RC oscillator which does not require

    any external components. This RC oscillator is separate from the RC oscillator of theOSC1/CLKI pin. That means that the WDT will run even if the clock on the

  • 7/30/2019 PIC16f877a Notes

    40/59

    OSC1/CLKI and OSC2/CLKO pins of the device has been stopped, for example, byexecution of a SLEEP instruction. During normal operation, a WDT time-outgenerates a device Reset (Watchdog Timer Reset). If the device is in Sleep mode, aWDT time-out causes the device to wake-up and continue with normal operation(Watchdog Timer Wake-up). The TO bit in the Status register will be cleared upon a

    Watchdog Timer time-out. The WDT can be permanently disabled by clearingconfiguration bit, WDTE (Section 14.1 Configuration Bits). WDT time-out periodvalues may be found in Section 17.0 Electrical characteristics under parameter#31. Values for the WDT prescaler (actually a postscaler but shared with the Timer0prescaler) may be assigned using the OPTION_REG register.Note 1: The CLRWDT and SLEEP instructions clear the WDT and the postscaler, ifassigned to the WDT and prevent it from timing out and generating a device Resetcondition.2: When a CLRWDT instruction is executed and the prescaler is assigned to theWDT, the prescaler count will be cleared but the prescaler assignment is notchanged.

    Power-down Mode (Sleep)Power-down mode is entered by executing a SLEEP instruction. If enabled, theWatchdog Timer will be cleared but keeps running, the PD bit (Status) is cleared,the TO (Status) bit is set and the oscillator driver is turned off. The I/O portsmaintain the status they had before the SLEEP instruction was executed (drivinghigh, low or high-impedance). For lowest current consumption in this mode, place allI/O pins at either VDD or VSS, ensure no external circuitry is drawing current fromthe I/O pin, power-down the A/D and disable external clocks. Pull all I/O pins that arehigh-impedance inputs, high or low externally, to avoid switching currents caused byfloating inputs. The T0CKI input should also be at VDD or VSS for lowest currentconsumption. The contribution from on-chip pull-ups on PORTB should also beconsidered. The MCLR pin must be at a logic high level (VIHMC).14.14.1 WAKE-UP FROM SLEEPThe device can wake-up from Sleep through one of the following events:1. External Reset input on MCLR pin.2. Watchdog Timer wake-up (if WDT was enabled).3. Interrupt from INT pin, RB port change or peripheral interrupt.

    14.15 In-Circuit DebuggerWhen the DEBUG bit in the configuration word is programmed to a 0, the in-circuit

    debugger functionality is enabled. This function allows simple debugging functionswhen used with MPLAB ICD. When the microcontroller has this feature enabled,some of the resources are not available for general use. Table 14-8shows which features are consumed by the background debugger.

  • 7/30/2019 PIC16f877a Notes

    41/59

    To use the in-circuit debugger function of the microcontroller, the design mustimplement In-Circuit Serial Programming connections to MCLR/VPP, VDD, GND,RB7 and RB6. This will interface to the in-circuit debugger module available fromMicrochip or one of the third party development tool companies.

    14.18 In-Circuit Serial ProgrammingPIC16F87XA microcontrollers can be serially programmed while in the endapplication circuit. This is simply done with two lines for clock and data and threeother lines for power, ground and the programming voltage. This allows customers tomanufacture boards with un-programmed devices and then program themicrocontroller just before shipping the product. This also allows the most recentfirmware or a custom firmware to be programmed.When using ICSP, the part must be supplied at 4.5V to 5.5V if a bulk erase will beexecuted. This includes reprogramming of the code-protect, both from an on state toan off state. For all other cases of ICSP, the part may be programmed at the normaloperating voltages. This means calibration values, unique user IDs or user

    code can be reprogrammed or added. For complete details of serial programming,please refer to the PIC16F87XA Flash Memory Programming Specification(DS39589).

    14.19 Low-Voltage (Single-Supply) ICSP ProgrammingThe LVP bit of the configuration word enables low-voltage ICSP programming. Thismode allows the microcontroller to be programmed via ICSP using a VDD source inthe operating voltage range. This only means that VPP does not have to be broughtto VIHH (high voltage input) but can instead be left at the normal operating voltage.In this mode, the RB3/PGM pin is dedicated to the programming function and ceasesto be a general purpose I/O pin. During programming, VDD is applied to the MCLRpin. To enter Programming mode, VDD must be applied to the RB3/PGM providedthe LVP bit is set. The LVP bit defaults to on (1) from the factory. If Low-VoltageProgramming mode is not used, the LVP bit can be programmed to a 0 andRB3/PGM becomesa digital I/O pin. However, the LVP bit may only be programmed when programmingis entered with VIHH on MCLR. The LVP bit can only be charged when using highvoltage on MCLR.It should be noted, that once the LVP bit is programmed to 0, only the High-VoltageProgramming mode isavailable and only High-Voltage Programming mode can be used to program the

    device.When using low-voltage ICSP, the part must be supplied at 4.5V to 5.5V if a bulkerase will be executed. Thisincludes reprogramming of the code-protect bits from an on state to an off state. Forall other cases of low-voltage ICSP, the part may be programmed at the normaloperating voltage. This means calibration values, unique user IDs or user code canbe reprogrammed or added.

  • 7/30/2019 PIC16f877a Notes

    42/59

    I/O PORTSPIC 16F877A has five Ports. Some pins for these I/O ports are multiplexed with analternate function for the peripheral features on the device. In general, when aperipheral is enabled, that pin may not be used as a general purpose I/O pin.

    PORTA

    PORTA is a 6-bit wide, bidirectional port. The registers associated with PORTA are

    PORTA Register

    TRISA Register

    CMCON Register

    CVRCON Register

    ADCON1 Register

    PORTA Register

    PORTA register is an 8bit register which is readable and writable. Only 6 bits (bit0 to

    bit5) are used and the other 2 bits (bit6 and bit7) are unimplemented. This register is

    used to read the data available on the PORTA lines and to write to the PORTA lines.

    Reading the PORTA register reads the status of the pins, whereas writing to it willwrite to the port latch. All write operations are READ-MODIFY-WRITE operations i.e.

    a write to the port implies then the port pins are read, the value is modified and then

    written to the port data latch.

    bit7 bit0

  • 7/30/2019 PIC16f877a Notes

    43/59

    TRISA RegisterIt is PORTA data Direction Register. When a TRISA bit is set, the corresponding

    PORTA line acts as an input line. When a TRISA bit is set to 0, the corresponding

    PORTA line acts as an output line.

  • 7/30/2019 PIC16f877a Notes

    44/59

    Pin RA4 is multiplexed with the Timer0 module clock input to become theRA4/T0CKI pin. Other PORTA pins are multiplexed with analog inputs and theanalog VREF input for both the A/D converters and the comparators. The operationof each pin is selected by clearing/setting the appropriate control bits in the ADCON1and/or CMCON registers.

    PORTBPORTB is an 8-bit wide, bidirectional port. The registers associated with PORTB are

    PORTB Register, TRISB Register and OPTION_REG.

  • 7/30/2019 PIC16f877a Notes

    45/59

    PORTB RegisterPORTB register is readable and writable. This register is used to read the dataavailable on the PORTB lines and to write to the PORTB lines.bit7 bit0

    TRISB Register

    It is PORTB data Direction Register. When a TRISB bit is set, the corresponding

    PORTB line acts as an input line. When a TRISB bit is set to 0, the corresponding

    PORTB line acts as an output line.

    Bit 7 Bit 0

    OPTION_REG Register (Address 81h,181h)The OPTION_REG Register is a readable and writable register, which containsvarious control bits to configure the TMR0 prescaler/WDT postscaler (single

    assignable register known also as the prescaler), the external INT interrupt, TMR0and the weak pull-ups on PORTB.

  • 7/30/2019 PIC16f877a Notes

    46/59

    Three pins of PORTB are multiplexed with the In-Circuit Debugger and Low-VoltageProgramming function: RB3/PGM, RB6/PGC and RB7/PGD.Four of the PORTB pins, RB7:RB4, have an interrupt-on- change feature. Only pinsconfigured as inputs can cause this interrupt to occur (i.e., any RB7:RB4 pinconfigured as an output is excluded from the interrupt-on- change comparison). Theinput pins (of RB7:RB4) are compared with the old value latched on the last read ofPORTB. The mismatch outputs of RB7:RB4 are ORed together to generate the RBport change interrupt with flag bit RBIF (INTCON).This interrupt can wake the device from Sleep. The user, in the Interrupt ServiceRoutine, can clear the interrupt in the following manner:

    a) Any read or write of PORTB. This will end the mismatch condition.b) Clear flag bit RBIF.A mismatch condition will continue to set flag bit RBIF. Reading PORTB will end themismatch condition and allow flag bit RBIF to be cleared.RB0/INT is an external interrupt input pin and is configured using the INTEDG bit(OPTION_REG).Each of the PORTB pins has a weak internal pull-up. A single control bit can turn onall the pull-ups. This is performed by clearing bit RBPU (OPTION_REG). Theweak pull-up is automatically turned off when the port pin is configured as an output.The pull-ups are disabled on a Power-on Reset.

  • 7/30/2019 PIC16f877a Notes

    47/59

    PORT C

    PORTC is an 8-bit wide, bidirectional port.

    PORTC RegisterPORTC register is readable and writable. This register is used to read the dataavailable on the PORTC lines and to write to the PORTC lines.

    bit7 bit0

    TRISC Register

    It is PORTC data Direction Register. When a TRISC bit is set, the corresponding

    PORTC line acts as an input line. When a TRISB bit is set to 0, the corresponding

    PORTC line acts as an output line.

    Bit 7 Bit 0

  • 7/30/2019 PIC16f877a Notes

    48/59

    Port C pins are multiplexed with serial communication peripherals. When enablingthe peripheral functions, care should be taken in defining TRISC bits for eachPORTC pin. Some peripherals override the TRISC bit to make a pin an output, whileother peripherals override the TRISC bit to make a pin an input. Since the TRIS bitoverride is in effect while the peripheral is enabled, read-modify-write instructions

    (BSF, BCF, XORWF) with TRISC as the destination, should be avoided. The usershould refer\to the corresponding peripheral section for the correct TRISC bitsettings.

    PORT D

    It is an 8bit port. Each pin is individually configurable as an input or output.

    PORT D can be configured as an 8bit wide microprocessor port (parallel Slave Port0

    by setting control bit, PSPMODE (TRISE).

    RP0/PSP0 Bit0 Input/Output port pin or Parallel Slave PortBit 0RP0/PSP0 Bit1 Input/Output port pin or Parallel Slave PortBit 1RP0/PSP0 Bit2 Input/Output port pin or Parallel Slave PortBit 2RP0/PSP0 Bit3 Input/Output port pin or Parallel Slave PortBit 3RP0/PSP0 Bit4 Input/Output port pin or Parallel Slave PortBit 4

    RP0/PSP0 Bit5 Input/Output port pin or Parallel Slave PortBit 5RP0/PSP0 Bit6 Input/Output port pin or Parallel Slave PortBit 6RP0/PSP0 Bit7 Input/Output port pin or Parallel Slave PortBit 7

    The registers Associated with PORTD are PORTD, TRISD and TRISE

    PORTD Register

    Address 08

    PORTD register is readable and writable. This register is used to read the data

    available on the PORTD lines and to write to the PORTD lines.

    TRISD Register

  • 7/30/2019 PIC16f877a Notes

    49/59

    It is PORTD data Direction Register. When a TRISD bit is set, the corresponding

    PORTD line acts as an input line. When a TRISD bit is set to 0, the corresponding

    PORTD line acts as an output line.

    PORTE

    It has three pins which are individually configured as inputs and outputs. On power

    on reset, these pins are configured as analog inputs and read as 0.

    The PORTE pins become the I/O control inputs for the microprocessor port when bitPSPMODE (TRISE) is set. In this mode, the user must make certain that theTRISE bits are set and that the pins are configured as digital inputs. Also,ensure that ADCON1 is configured for digital I/O. PORTE pins are multiplexed withanalog inputs. When selected for analog input, these pins will read as 0s.

    PORTE Register

    PORTE register is readable and writable. This register is used to read the data

    available on the PORTE lines and to write to the PORTE lines.

  • 7/30/2019 PIC16f877a Notes

    50/59

    TRISE Register

    It is an 8bit register. It controls the direction of the RE pins, even when they are

    being used as an analog inputs. The user must make sure to keep the pins

    configured as inputs when using them as analog inputs.

    TRISE register

  • 7/30/2019 PIC16f877a Notes

    51/59

  • 7/30/2019 PIC16f877a Notes

    52/59

    CPU registers are: 1) STATUS register, 2) OPTION_REG register, 3) INTCONregister, 4) PIE1 register, 5) PIR1 register, 6) PIE2 register, 7) PIR2 register.

  • 7/30/2019 PIC16f877a Notes

    53/59

  • 7/30/2019 PIC16f877a Notes

    54/59

  • 7/30/2019 PIC16f877a Notes

    55/59

  • 7/30/2019 PIC16f877a Notes

    56/59

  • 7/30/2019 PIC16f877a Notes

    57/59

  • 7/30/2019 PIC16f877a Notes

    58/59

  • 7/30/2019 PIC16f877a Notes

    59/59

    Pin Diagram