Presentation is loading. Please wait.

Presentation is loading. Please wait.

Objectives At the end of this class you will:

Similar presentations


Presentation on theme: "Objectives At the end of this class you will:"— Presentation transcript:

1 Academic Partnership Program Mid-Range Family Peripheral Configuration, C Programming and PICDEM2

2 Objectives At the end of this class you will:
Understand the basic PIC® peripherals and their associated registers Have “HANDS ON” experience initializing Mid-Range peripherals using the “HI-TECH PICC” C compiler Be able to implement peripherals not covered here Understand interrupts and polling Write your own application code from “scratch” You will have gained experience with Mid-Range family peripherals and Microchip’s documentation standards allowing you to easily understand peripherals not specifically covered in this class. You will also be able to write an application program “from scratch” including the ability to operate peripherals, set up the system clocking and power saving modes, debug the program and generate production code

3 Agenda Brief review of Mid-Range Architecture, Instruction Set and Tools Using Hi-TECH’s C compiler with MPLAB Lab0-HI-TECH Compiler and LED KnightRider Lab1-LCD Library Interrupts on the Mid-Range PICmicro Lab2-External Interrupt Lab (Buttons) Peripheral discussion: Input/Output Ports Timers Timer0 Timer1 Lab3-Timer1/Watch RTC Lab Timer2 Lab4-Timer2 Lab

4 Agenda (cont.) Capture / Compare / PWM Module (CCP) Analog Comparator
Lab5-PWM & Lab6-Output Compare Labs Analog Comparator Analog to Digital Converters (ADC) Lab7 - ADC Voltmeter Lab I2C with the Master Synchronous Serial Port Lab8 - Temp Sensor I2C Lab Lab9 - EEPROM I2CLab Universal Asynchronous & Synchronous Receiver & Transmitter (USART) Lab10- UART Hyperterminal Lab

5 Mid-Range Family Basic Architecture

6 PIC® MCU and dsPIC® DSC Family Roadmap
32-bit PIC32 16-bit dsPIC33 Functionality dsPIC30 PIC24H PIC24F PIC18 8-bit Here is an overview of Microchip’s entire Microcontroller and Digital Signal Control portfolio: Microchip’s offers a broad range of products from our basic, low-cost and small package Baseline MCUs through to our high-performance feature rich PIC32 products. We also feature a Digital Signal Controller or DSC product line that combines a 16-bit Microcontroller with some of the functionality of a Digital Signal Processor. In today’s class we will focus on the Mid-Range and Enhanced Mid-Range 8-bit Microcontrollers Enhanced Mid-Range Mid-Range Mid-Range Baseline Performance

7 PIC® MCU and dsPIC® Family Roadmap
PIC24H dsPIC33 16-bit PIC32 32-bit Functionality PIC18 8-bit Let’s begin with an overview of our Mid-Range products. Enhanced Mid-Range Mid-Range Mid-Range Baseline Performance

8 Mid-Range PIC® Architecture
Up-to 16MHz Flash Program Memory Up-to 14KB or 8K individual addresses Oscillator Data Memory Up-to 368bytes CPU Single Interrupt 8-bits 14-bits Shown here is a simplified block diagram of our 8-bit Mid-Range products. These devices are offered in a variety of packages from 8 to 64-pins. At the core of the Microcontroller is our Central Processing Unit. Mid-Range devices can operate at up-to 16MHZ from a configurable, internal oscillator and up to 20MHz from an external crystal oscillator. Note that there are two memory spaces shown here: Program Memory and Data Memory. Each memory location connects to the Central Processing Unit via its own individual bus. This allows for such architectural advantages as long instruction words and simultaneous fetch of the next instruction while a current instruction is executing. Peripherals 8 to 64-pin Packages

9 Mid-Range PIC® Architecture
1 Up-to 16MHz One 14-bit Register Flash Program Memory Up-to 14KB or 8K individual addresses Oscillator Program Memory Address 1 Program Memory Address 2 Data Memory Up-to 368bytes Program Memory Address 3 CPU Single Interrupt Program Memory Address 4 8-bits Program Memory Address 5 14-bits Program memory is 14-bits wide meaning that at each program memory address, a 14-bit value or word will reside. Each 14-bit value represents some unique instruction or value that will ultimately tell the CPU how to operate. The CPU will fetch each 14-bit instruction sequentially every 4 oscillator periods or instruction cycle. Therefore, if the device has been configured to utilize its internal 16MHz oscillator, instructions will execute at a frequency of 4MHz. This will be covered in more detail when we look at Timer peripherals later in this presentation. Program Memory will store the code written by the user that has been downloaded to the device using a hardware programmer. Each 14-bit address will hold a single assembly instruction. Peripherals 8 to 64-pin Packages

10 Mid-Range Instruction Set
35 single word instructions All are single cycle except for program branches Byte Oriented Operations Bit Oriented Operations addwf f,d andwf f,d clrf f clrw - comf f,d decf f,d decfsz f,d incf f,d incfsz f,d iorwf f,d movf f,d movwf f nop - rlf f,d rrf f,d subwf f,d swapf f,d xorwf f,d Add W and f AND W with f Clear f Clear W Complement f Decrement f Decrement f, Skip if 0 Increment f Increment f, Skip if 0 Inclusive OR W with f Move f Move W to f No Operation Rotate Left f through Carry Rotate Right f through Carry Subtract W from f Swap nibbles in f Exclusive OR W with f bcf f,b bsf f,b btfsc f,b btfss f,b Bit Clear f Bit Set f Bit Test f, Skip if Clear Bit Test f, Skip if Set Literal and Control Operations addlw k andlw k call k clrwdt - goto k iorlw k movlw k retfie - retlw k return - sleep - sublw k xorlw k Add literal and W AND literal with W Call subroutine Clear Watchdog Timer Go to address Inclusive OR literal with W Move literal to W Return from interrupt Return with literal in W Return from Subroutine Go into standby mode Subtract W from literal Exclusive OR literal with W There are 35 assembly instructions available for the Mid-Range Devices. These instructions are explained at the back of any of our datasheets. Today we will be programming in C. However, it is important to remember, any line of C code can generate multiple lines of assembly code in the background with each assembly instruction occupying one of our 14-bit program memory addresses. This will be demonstrated later.

11 Mid-Range PIC® Architecture
Up-to 16MHz Flash Program Memory Up-to 14KB or 8K individual addresses Oscillator Data Memory Up-to 368bytes CPU Single Interrupt 8-bits 14-bits Let’s take a closer look at data memory… Peripherals 8 to 64-pin Packages

12 Mid-Range PIC® Architecture
Up-to 16MHz 1 Flash Program Memory Up-to 14KB or 8K individual addresses 8-bit Address 1 Oscillator 8-bit Address 2 8-bit Address 3 8-bit Address 4 Data Memory Up-to 368bytes 8-bit Address 5 CPU Single Interrupt 8-bit Address 6 8-bits 14-bits 8-bit Address 7 8-bit Address 8 Data memory on these Mid-Range devices is 8-bits wide meaning that each address will contain an 8-bit value that can either be read from or written to by the central processing unit during normal run-time operation. Data Memory serves two main purposes. For instance, it is here that any variables declared within the user’s code or firmware will be stored. Peripherals 8 to 64-pin Packages

13 How are Memory Spaces Organized?
Program Memory Program Memory Mid-Range : Up-to 4 pages x 2K 14-bit addresses Data Memory Mid-Range: Up-to 4 BANKS x bit addresses PAGE0 PAGE1 PAGE2 PAGE3 Data Memory Each memory space, program memory and data memory, has its own unique organization of registers. Program memory for example, is divided in pages. Each page will contain 2K or bit address locations. On the mid-range device, there is a maximum of 4 x 2K pages. Data memory on the other hand is divided in banks. Each bank will contain up-to bit addresses. Program Memory and Data Memory sizes will differ amongst devices in the Mid-Range family. Therefore, the individual datasheet for a specific device will need to be referred to. In this class, we will be using a device that has the maximum amount of memory available within this product family. BANK 1 2 3

14 Data Memory Map SFR Special Function Registers Special Function
000h 080h 100h 180h Special Function Registers Special Function Registers SFR SFR 10Fh 18Fh 110h 190h 01Fh 09Fh 020h 0A0h 128 Bytes General Purpose Registers General Purpose Registers General Purpose Registers General Purpose Registers Data memory is broken up into banks. This memory is affected by the Program Code stored in program memory. It will store variable data information as well as configure the Special Function Registers. This is the RAM. A part may have up to 4 banks, and a bank may contain up to 128 bytes of data memory depending on the PICmicro used. It is only possible to access registers in the currently selected bank. Two bits in the STATUS register are used to determine the currently bank selection and are discussed later in this presentation. Each bank begins with the Special Function Registers (SFRs). These are used to control the functionality of the PICmicro and its peripherals. These will be discussed further later in the presentation Each bank also contains General Purpose Registers (GPRs). These are available for the programmers usage. There is also a shared section of Data Memory at the bottom of each bank. This data memory can be accessed from any bank. One of the key features of the PICmicro architecture is the use of register file concept. This concept means all RAM locations, peripherals and I/O ports are organized as a simple bank of registers. Therefore, all instructions can operate on any register and you don’t have to load things from RAM into a register to do functions on them. 0EFh 16Fh 1EFh Shared Shared Shared 07Fh 0FFh 17Fh 1FFh Bank Bank Bank Bank3

15 Special Function Registers (SFRs)
Configure MCU and Peripherals operation Status Operation Interrupts Fixed at the specified addresses PORTB 06h TRISB 86h PORTC 07h TRISC 87h PORTD 08h TRISD 88h PORTE 09h TRISE 89h PCLATH 0Ah PCLATH 8Ah INTCON 0Bh INTCON 8Bh PIR1 0Ch PIE1 8Ch SFR registers are used to configure the microcontroller as well as configure, control, and utilize the on-board peripherals These registers will always remain fixed at specific addresses in data memory. The include file at the beginning of any code contains the addresses for the specific PICmicro used. Otherwise, the user would need to assign these addresses at the beginning of the code. Using the latter method, if one wished, they could rename these registers to anything they wanted. Some SFR registers can be accessed from any bank and do not require a bank change to manipulate their respective bits. As shown in the previous slide a similar concept occurs with the shared RAM registers. PIR2 0Dh PIE2 8Dh Bank Bank1

16 Mid-Range PIC® Architecture
Up-to 16MHz Flash Program Memory Up-to 14KB or 8K individual addresses Oscillator Data Memory Up-to 368bytes CPU Single Interrupt 8-bits 14-bits Let’s take a closer look at the peripherals available in the Mid-Range family. Peripherals 8 to 64-pin Packages

17 Mid-Range PIC® Peripherals
General Purpose I/O Timer-based Analog Multiple PORTs (1) 16-bit Timer (2) 8-bit Timers Capture/Compare/PWM Comparator(s) 10-bit ADC Voltage Reference Communication Human Interface SPI/I2C AUSART/EUSART Capacitive Touch LCD

18 PIC® MCU and dsPIC® Family Roadmap
PIC24H dsPIC33 16-bit PIC32 32-bit Functionality PIC18 8-bit Enhanced Mid-Range Recently, Microchip revisited the Mid-Range family and made some improvements. More Memory, faster operation and more room for peripherals. This updated version of the Mid-Range product line is called the Enhanced Mid-Range family. Mid-Range Mid-Range Baseline Performance

19 Enhanced Mid-Range PIC® Architecture
Up-to 32MHz Flash Program Memory Up-to 56KB or 32K individual addresses Oscillator Data Memory Up-to 4KB CPU Single Interrupt with Hardware Context Save 8-bits 14-bits Note that this family continues to utilize the separate 14-bit Program Memory and 8-bit Data Memory architecture. Both memory spaces have been significantly expanded with program memory extended to 56KB from 14KB and Data Memory extended to 4KB from 368 bytes. Peripherals 8 to 64-pin Packages

20 How are Memory Spaces Organized?
Program Memory Program Memory Mid-Range : Up-to 4 pages x 2K 14-bit addresses Enhanced Mid-Range: Up-to 8 pages x 2K 14-bit addresses Data Memory Mid-Range: Up-to 4 BANKS x bit addresses Enhanced Mid-Range: Up-to 32 BANKS x bit addresses PAGE0 PAGE1 PAGE2 PAGE3 PAGE4 PAGE5 PAGE6 PAGE7 Note, that since the Special Function Registers in data memory are used to control peripheral functions, extended this space means that we can now add more peripherals than we ever could have done on the older Mid-Range core. Data Memory 1 2 3 BANK 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

21 Enhanced Mid-Range PIC® Architecture
Up-to 32MHz Flash Program Memory Up-to 56KB or 32K individual addresses Oscillator Data Memory Up-to 4KB CPU Single Interrupt with Hardware Context Save 8-bits 14-bits Peripherals 8 to 64-pin Packages

22 Enhanced Mid-Range PIC® Peripherals
General Purpose I/O Timer-based Analog Multiple PORTs (1) 16-bit Timer (2) 8-bit Timers Capture/Compare/PWM Comparator(s) 10-bit ADC Voltage Reference Communication Human Interface SPI/I2C AUSART/EUSART Capacitive Touch LCD

23 Enhanced Mid-Range PIC® Peripherals
General Purpose I/O Timer-based Analog Multiple PORTs Same as Mid-Range but with more integration and room to grow! (1) 16-bit Timer (2) 8-bit Timers Capture/Compare/PWM Comparator(s) 10-bit ADC Voltage Reference Communication Human Interface SPI/I2C AUSART/EUSART Capacitive Touch LCD

24 Side-by-Side Comparison
Existing Enhanced Instruction Length 14 bits Addressable Program Memory 14 KB Maximum Up-to 56KB Max RAM and Register space 446 Bytes Up-to 4KB Instruction Count 35 49 Hardware Stack 8 16 With optional RESET Capabilities Interrupt Handling Software Context Saving Automatic Hardware Context Saving File Select Registers 1x9 bit 2x16 bit (FSRxH:FSRxL) 2x8-bit INDFx Linear GPR Map Access to Program Memory Space While maintaining the instruction word at 14-bits, addressable program memory has been extended to 57 Kbytes allowing up-to 32K of instructions on the enhance Mid-Range architecture. This is a dramatic increase from the existing architecture at 8K instructions. The user now has lot more room for more involved firmware applications along with optimization when programming in C. Data Memory has been extended to more than 3Kbytes from 446bytes on the existing architecture. As I mentioned, not only does this increase available General Purpose RAM, but now there is more room for future peripheral expansion. With the new enhanced architecture comes 14 new instructions that enable the embedded engineer to optimize firmware applications by implementing faster code with less overhead. The hardware stack has been increased from 8 to 16 levels with optional reset capabilities on overflow or underflow conditions. Furthermore, the stack is now completely accessible from Bank 31 in the extended Data Memory space. More on this later. Another nice feature is the new hardware context save during interrupts. Traditionally, a software handling routine is required on the existing architecture to save some of the core registers during an interrupt. Now this is done automatically with these registers saved on any interrupt and restored on a return. Finally, indirect addressing has been enhanced with the addition of two 16-bit file select registers allowing not only access to data memory but program memory as well. Additionally, three new instructions are included in the new instruction set specifically for FSR support.

25 Side-by-Side Comparison
Existing Enhanced Instruction Length 14 bits Addressable Program Memory 14 KB Maximum Up-to 56KB Max RAM and Register space 446 Bytes Up-to 4KB Instruction Count 35 49 Hardware Stack 8 16 With optional RESET Capabilities Interrupt Handling Software Context Saving Automatic Hardware Context Saving File Select Registers 1x9 bit 2x16 bit (FSRxH:FSRxL) 2x8-bit INDFx Linear GPR Map Access to Program Memory Space Enhanced Mid-Range MCUs Designated as PIC16F1xxx While maintaining the instruction word at 14-bits, addressable program memory has been extended to 57 Kbytes allowing up-to 32K of instructions on the enhance Mid-Range architecture. This is a dramatic increase from the existing architecture at 8K instructions. The user now has lot more room for more involved firmware applications along with optimization when programming in C. Data Memory has been extended to more than 3Kbytes from 446bytes on the existing architecture. As I mentioned, not only does this increase available General Purpose RAM, but now there is more room for future peripheral expansion. With the new enhanced architecture comes 14 new instructions that enable the embedded engineer to optimize firmware applications by implementing faster code with less overhead. The hardware stack has been increased from 8 to 16 levels with optional reset capabilities on overflow or underflow conditions. Furthermore, the stack is now completely accessible from Bank 31 in the extended Data Memory space. More on this later. Another nice feature is the new hardware context save during interrupts. Traditionally, a software handling routine is required on the existing architecture to save some of the core registers during an interrupt. Now this is done automatically with these registers saved on any interrupt and restored on a return. Finally, indirect addressing has been enhanced with the addition of two 16-bit file select registers allowing not only access to data memory but program memory as well. Additionally, three new instructions are included in the new instruction set specifically for FSR support.

26 Development Tools

27 Integrated Development Environment (IDE)
MPLAB® IDE MPLAB Integrated Development Environment (IDE) Editor Software Simulators MPASM Assembler MPSIM Simulator MPLAB C Compilers Microchip’s MPLAB Integrated Development Environment or IDE, provides a single integrated toolset for all of Microchip’s MCUs and DSCs. The environment also features an MPSIM simulator that can be used to simulate any of our products before purchasing any silicon. This environment also features the ability to utilize any of Microchip’s MPLAB C or HI-TECH C compilers along with select Third Party compilers all within MPLAB to provide a single unified graphical user interface. HI-TECH C Compilers Third-Party C Compilers

28 Integrated Development Environment (IDE)
MPLAB® IDE MPLAB Integrated Development Environment (IDE) Editor Software Simulators MPASM Assembler MPSIM Simulator FREE Academic Versions Available!!! MPLAB C Compilers Note that Microchip offers free lite versions of all of our compilers that have no-time periods or code-size restrictions for our complete product line. HI-TECH C Compilers Third-Party C Compilers

29 Integrated Development Environment (IDE)
MPLAB® IDE MPLAB Integrated Development Environment (IDE) Editor Software Simulators MPASM Assembler MPSIM Simulator MPLAB C Compilers Numerous Software Libraries for: USB Ethernet Graphics DSP and more!! Furthermore, Microchip also features a variety of software libraries for specific devices to reduce the code development on such code-intensive applications as USB, Ethernet, Digital Signal Processing algorithms and much more. HI-TECH C Compilers Third-Party C Compilers

30 Integrated Development Environment (IDE)
MPLAB® IDE MPLAB Integrated Development Environment (IDE) Editor Project Manager Software Simulators HW Debug Programmers MPASM Assembler MPSIM Simulator MPLAB REAL ICE MPLAB PM3 MPLAB C Compilers MPLAB ICD3 Software simulators like MPSIM are great but are heavily reliant on the processing speed of the computer that the code is being simulated on. Therefore, Microchip also offers a number of hardware debuggers and emulators that can be used to not only program the Microcontroller, but also run the code on the device, while in circuit with feedback directly into MPLAB. This allows the user to observe in-circuit changes to any registers on the device within the environment. HI-TECH C Compilers PICkit 3 Third-Party C Compilers

31 Microchip’s Updated Debugging and Emulation Product Line
MPLAB® REAL ICE™ Features/Speed/Trace MPLAB® ICD 3 PICkit™3 High Speed USB 2.0, Run, Halt, SS Software Breakpoints, Complex Trigger/Breakpoint, Real-Time Watch, Stopwatch, Program, Read, Trace, Logic Probes, Performance Pak All of Microchip’s Flash PIC MCUs and dsPIC DSCs High Speed USB 2.0, Run, Halt, SS Software Breakpoints, Complex Breakpoints, Stopwatch, Program, Read, All of Microchip’s Flash PIC® MCUs and dsPIC® DSCs Full Speed USB, Run, Halt, SS, Breakpoints, Program, Read Selected devices $44.95 $189 $499.98

32 Tools Used in This Class

33 Tools Used in this Class
PIC16F877A Microcontroller: Operating Speed: Up-to 8MHz Internal Oscillator (2 MHz Instruction Cycle) Program Memory: 14KB or 8K 14-bit Addresses Data Memory: 368 bytes (4 BANKS) The PIC16F877A features the following operational characteristics. Peripherals: Timer Based: Timers: 2 x 8-bit, 1 x 16-bit Capture/Compare/PWM Module Communications: EUSART I2C/SPI Module Analog: 8 channel, 10-bit ADC 2 x Comparators

34 MPLAB® ICD 2 Uses ICSPTM (In Circuit Serial ProgrammingTM) to connect to the PICmicro. ICD 2 as a Debugger: Can run your program in real time Step through program one instruction at a time View Data Memory with watch windows ICD 2 as a Programmer: Reads, Writes & Erases: Data Memory Program Memory EEPROM Programs configuration bits The In-Circuit Debugger uses two dedicated hardware lines (microcontroller pins used only during debugging mode) that control In Circuit Serial Programming™ (ICSP™) of the PICmicro The ICD 2 debug features are built into the microcontroller and activated by programming the debug code into the target processor. There is some shared overhead expense that includes one stack level, some general purpose file registers and a small area of program memory when in the debug In order to use the ICD 2, it will be necessary to implement a small amount of interface circuitry to the PICmicro. However, the low cost of the ICD 2 and its programming and debug capabilities make these simple circuit modifications well worth the effort.

35 PICDEM® 2 Plus Board 18, 28 and 40-pin DIP sockets 16 x 2 LCD Module
LEDs 16 x 2 LCD Module 9V to 5V regulator Analog Pot EEPROM RS232 Connector 18, 28 and 40-pin DIP sockets 32.768kHz XT ICD Connector Push button Switches Piezo Buzzer I2C Based Temp Sensor

36 “HI-TECH PICC” C Compiler with MPLAB

37 HI-TECH C® Compiler We now offer arguably the best embedded C compiler on the market in three packages for the PIC10/12/16 Families: Lite Mode FREE! OCG is not available with minimal level of optimization Standard Mode $495 OCG is not available with some level of optimization PRO Mode $1195 Features Omniscient Code Generation™ (OCG) with Very High Levels of Optimization To develop applications in C on Microchip’s Mid-Range and Enhanced Mid-Range devices three versions of our HI-Tech C compilers are available. Today we will be using the Lite Mode or FREE version of the compiler. The main difference between the Lite mode, Standard and PRO modes, are the levels of Omiscient Code Generation or OCG capabilities. OCG is a method of optimizing code to help reduce program memory utilized for your application. For example, if your code declares and defines a function that is never used during run-time, then OCG will remove this function from program memory so that space can be used for other purposes. There is a lot more to it than that. For more information please see the User’s Guide for the compiler being used.

38 Code Size Generation Comparison of the Three Modes
100% 50% smaller than Lite Mode 80% 30% smaller than STD Mode Percentage of Code Generated using Lite Mode 50% Here is a code-size generation comparison for the same firmware on the different compiler levels. Lite Mode Standard Mode PRO Mode with OCG™

39 HI-TECH C® PRO Lite Mode Compiler
FREEWARE! No Memory Restrictions No Time Limits Supports all PIC® Microcontroller and dsPIC® DSC devices OCG™ Optimizations are not available

40 Advantages of Using C Faster Development Cycle Easier to Develop Code
Algorithms more easily written in C Easier to Develop Code Bank Switching and Paging handled by compiler Easier to Debug Code C’s implementation of control structures and decision branches well tested

41 Disadvantages of C Higher Memory Utilization Program Execution Time
C Takes more Program Memory space than Assembly in most applications Program Execution Time More instructions per task = more time per task Execution time of C programs needs to be verified Time critical tasks are typically coded in assembly

42 Configuring Registers with PICC
GIE PEIE TMR0IE INTE RBIE TMR0IF INTF RBIF bit 7 bit 0 INTCON (Interrupt Control Register) GIE TMR0IE Example: Enable Global Interrupts and Timer0 Interrupts 3 ways to do this……. INTCON = 0xA0; /* write all bits in “INTCON” * register using hex */ 1 Notice two different comment examples 2 INTCON = 0b ; //write all bits using binary 3 GIE = 1; //set the Global Interrupt bit TMR0IE = 1; //set the Timer0 Interrupt bit

43 Assembly code can be inserted into C code
Mixing Assembly with C Assembly code can be inserted into C code 2 ways to do this……. asm(“movlw 10h”); // Insert one assembly asm(“movwf 120h”); // instruction at a time 1 Should the user plan to use assembly code within their C program (In-Line) there are two methods available to them: by using the asm() directive, each line is inserted one at a time Using the #asm/#endasm directives allows insertion of code as blocks #asm // Insert a block of movlw 10h // instructions using the movwf 120h // “#asm” directive #endasm 2

44 Manipulating C Objects in Assembler
#include <pic.h> unsigned char var; void main (void) { TRISB = 0X00; var = 1; #asm rlf _var rlf _var //move 2 bits to the left #endasm PORTB = var; while(1); } Defines an 8-bit register called “var” Underscore needed in order to manipulate in assembly

45 Lab 0: HiTech C and LED Knight Rider

46 Lab 0: HiTech C and LED Knight Rider
Goals: Work with HI-TECH C-Lite and MPLAB® IDE environment to create a C-Based Project To Do: Follow the slides Expected Result: Successfully build the project and program the device

47 Lab 0: HiTech C and LED Knight Rider
Objective: To Make the LEDs turn on one at a time from left to right then back to left. Learn how to use Hi-Tech C Compiler built-in delay function.

48 Lab 0: HiTech C and LED Knight Rider
Create a new project using Project Wizard

49 Lab 0: HiTech C and LED Knight Rider
Click Next and Select your device You will see this window, Enter the project name as “MyFirstPICCProject” And give the project directory path as C:\RTC\201_PRC\Lab0_PICC The project file will be created

50 Lab 0: HiTech C and LED Knight Rider
Select the Language toolsuite: HI-TECH Compiler *need to install if not present, FREE Hi-TECH Lite

51 Lab 0: HiTech C and LED Knight Rider
Click next and type the filename of your project

52 Lab 0: HiTech C and LED Knight Rider
Click next Now let us select the device on which we work, In our case we will be working on PIC16F877A To select this device Click on Configure select “Select Device”

53 Lab 0: HiTech C and LED Knight Rider
Click finish to start coding your first embedded program

54 Lab 0: HiTech C and LED Knight Rider
Select View>Project to see your project files (is empty) To program the configuration fuses we can write the code in the source code file using “__CONFIG( )” or We can select using this option. Click on configure, select configuration bits, you get the window

55 Lab 0: HiTech C and LED Knight Rider
Click a New File and Save it as “Lab1.c” on your folder

56 Lab 0: HiTech C and LED Knight Rider
Add the c file and start coding your embedded project

57 Lab 0: Source Code Type this or just add the c file from /RTC/LAB0-HT_LED other delay sample:

58 Lab 0: HiTech C and LED Knight Rider
Add source file “KnightRider.c” to the project (located ..\RTC\Lab0-HT_KnightRider Now we need to add the source files to the project, To add source file to project right click on source files Select add files by navigating through the path of the file Note that, in this example, we are leaving our template, header, and linker files in the common directory. This allows all projects using these files to benefit from any enhancements or bug fixes which may be made to the files in future MPLAB releases or that are made for this project. It is also a common practice to copy the files into a local project directory. This allows the project to use a more condensed directory structure, but requires manually updating these files if they are changed in future releases.

59 Lab 0: HiTech C and LED Knight Rider
Config Bits Set in Code in these labs

60 Lab 0: HiTech C and LED Knight Rider
Two ways to Build

61 Lab 0: HiTech C and LED Knight Rider
Add header file to the project C:\Program Files\HI-TECH Software\PICC\9.70\include

62 Lab 0: HiTech C and LED Knight Rider
Output window after a successful build!!!

63 Lab 0: HiTech C and LED Knight Rider
Viewing disassembly listing

64 Lab 0: HiTech C and LED Knight Rider
Selecting the programmer To program the device we need to select the programer. To select the programmer click on programmer select, “select programmer” and select the programmer, In this case let us select “MPLAB ICD2”.

65 Lab 0: HiTech C and LED Knight Rider
Connect to the Programmer Connect to the programmer. The option can be set to automatically connect to the programmer under the “Settings…” option. Successful Connection

66 Lab 0: HiTech C and LED Knight Rider
Program the device Finally we need to program the device. To program the device 2 ways are there Either click on programmer and select program or click on this ICON.

67 Lab 0: HiTech C and LED Knight Rider
Unplug the ICD2 cable or click here to release the device from reset

68 Library

69 LAB 1.0 – LCD Library

70 Lab 1: LCD Library Open the project “LCD_MSG” and Program the Device
located ..\RTC\Lab1-LCDLibrary

71 Lab 1: LCD Library LCD library consist of two files:
“LCD_lib.c” Source File Functions Codes Ex. LCD_init(){ … } LCD_send(,){ ….} “LCD_lib.h” Header File Function Definitions Should be included on the main file when using the library #include “LCD_lib.h”

72 Lab 1: LCD Library Using the library on LCD_main.c Source File

73 Interrupts

74 Polling and Interrupts
Often we would like the processor to perform a task if a specific event occurs Two methods to check if this event has occurred: Polling: Continuously check for event at various points in the code Interrupts: “INTERRUPTS” the Main program and starts an Interrupt Service Routine when an event occurs Many times, it is useful to have the processor execute a section of code but only when a specific event occurs. The event could be anything from an external signal from an off-chip device that sets a register bit on the microcontroller, an overflow of a counter within the PICmicro, or the completion of a communication sequence with another device. The processor will need to have some way of knowing when this event has occurred so it can perform the required task. Two methods to accomplish this is polling or using interrupts. Polling is implemented within the main code by periodically checking for a particular event. While interrupts do not need a checking process to monitor for an event but rather notify the process when and if the event occurs.

75 *wasted processor clock cycle
Polling Example Keep testing PORTB bit 0 (RB0) to see if it has been set. When it does get set, clear PORTA bit 0 (RA0). RA0 = 1 RB0 = 0 ?? RA0 = 0 NO YES RA0 = 1; //Set bit 0 of PORTA while(RB0 == 0); //Loop while bit 0 //of PORTB is 0 RA0 = 0; //Clear bit 0 of PORTA As you can see, polling is an effective way of checking to see if a specific event exists. If so, the processor will execute a different instruction than it otherwise would have. However, this method can use up precious clock cycles within the processor that could have been used doing something else. While the processor is waiting for the specific event to occur, in this case if RB0 = 1, no other code can be executed. This could prove to be a problem especially when your code must be accurately synchronized with the clock of an off chip device and the event is randomly occurring. The solution would be to utilize an interrupt which allows normal program execution to continue until the event actually takes place. Polling is still a valuable resource and will be implemented later for prioritizing interrupts. *wasted processor clock cycle

76 Main( ) program execution
Interrupt Example //=====Main Routine=========== void main (void) { } //==Interrupt Service Routine== void interrupt isr (void) Main( ) program execution no interrupt Execute ISR( ) interrupt flag set ISR completed Main program code This slide shows a very general overview of the use of an interrupt. A few comments on the code example given: The state diagram demonstrates that unless an interrupt occurs (associated flag bit is not set), the interrupt service routine located at the interrupt vector will not be executed and the Main code of the program will continue execution. Once an interrupt occurs (associated flag bit is set): the processor will finish its current instruction and the address of the next instruction in the program counter will be stored onto the top of the stack. The function qualifier interrupt may be applied to any number of C function definitions to allow them to be called directly from the hardware interrupts. The compiler will process the interrupt function differently to any other functions, generating code to save and restore any registers used and exit using the appropriate instruction. The program counter will then point to address 004h (interrupt vector) and begin sequentially executing the code at that point. Once the ISR is completed, the address value at the top of the stack is placed back into the Program Counter. The processor can now continue program execution at the point it left off prior to the interrupt occurring. Interrupt Service Routine (ISR)

77 Enabling Interrupts Processor must be told that interrupts will be used A number of registers with interrupt enable bits do this: Interrupt Control (INTCON) Peripheral Interrupt Enable 1 (PIE1) Peripheral Interrupt Enable 2 (PIE2)

78 Interrupt Logic Interrupt GIE PEIE TMR0IE TMR0IF INTE INTF RBIE RBIF
This diagram illustrates what happens internally to the PIC Microcontroller to determine if an interrupt has occurred. Not every interrupt is shown here Each interrupt enable bit is ANDed with its interrupt flag bit. This ensures that only interrupts that are enabled will cause the processor to interrupt The results of all the AND gates are ORed together to determine if any single interrupt has occurred. Finally, this is ANDed together with the Global Interrupt Enable (GIE) bit to determine if the Microcontroller should interrupt or not. The diagram is not completely symmetrical. Interrupts on the top are Core interrupts. They are mask able by their individual interrupt enable bits and the global interrupt enable bit. The interrupts on the bottom are Peripheral interrupts. They’re mask-able by their individual interrupt enable bits, the global interrupt enable bit.. And an additional PEripheral Interrupt Enable bit. ADIE ADIF PEIE Other peripherals

79 INTCON Register (Core Interrupts)
Global Interrupt Enable GIE Peripheral Interrupt Enable PEIE Timer0 Interrupt Enable TMR0IE External Interrupt Enable INTE PORTB change Interrupt Enable RBIE Description Enable Bits Must be set to use any Interrupts any Peripheral Interrupts GIE PEIE TMR0IE INTE RBIE TMR0IF INTF RBIF The INTCON register contains the various enable and flag bits for TMR0 register overflow, PORTB change and RB0/INT pin interrupts. The Global Interrupt Enable bit (GIE) must be set for any interrupt to occur. When an interrupt request is received, the GIE bit will clear to avoid other interrupts from interfering with ISR execution. The GIE must then be set following ISR to enable future interrupts . This is easily accomplished by using the retfie instruction which sets the GIE and returns from the interrupt service code simultaneously. If using a peripheral interrupt, Peripheral Interrupt Enable bit (PEIE) must be set. This then allows the programmer to individually set bits in subsequent peripheral interrupt registers to include or exclude various peripheral interrupts. It is important to note that, regardless of the state of its corresponding enable bit or the global interrupt bit GIE, the interrupt flag bits will set when the associated interrupt condition occurs. User software should ensure the appropriate interrupt flag bits are cleared prior to enabling an interrupt Flag Bits Description Flags will set even if interrupts aren’t enabled! TMR0IF Timer0 Overflow Interrupt Flag INTF RB0/INT External Interrupt Flag RBIF PORTB Change Interrupt Flag

80 Enabling a Core Interrupt
void interrupt isr (void) { //clear External Interrupt //flag to enable interrupts //after this ISR INTF = 0; //<ISR code> } PROGRAM COUNTER “while(1);” address “while(1);” address STACK void main (void) { <code to set up PORTB > // initialize INTCON INTCON = 0b ; //enable an external //interrupt on the INT pin INTE = 1; //enable global interrupts GIE = 1; while(1) ; //loop forever } INTCON 1 1 1 GIE INTE INTF GIE bit Automatically Set by Hardware GIE bit Automatically Cleared by Hardware Interrupt Detected on “RB0/INT” Pin

81 Peripheral Interrupts
Two registers ENABLE interrupts for peripherals Peripheral Interrupt Enable 1 (PIE1) Peripheral Interrupt Enable 2 (PIE2) Two registers display peripheral REQUESTS for an interrupt (Flags) Peripheral Interrupt Request 1 (PIR1) Peripheral Interrupt Request 2 (PIR2) With the PEIE bit enabled in the INTCON register, software may now be used to configure individual peripheral interrupts. There are two peripheral interrupt enable registers on the PIC16F877 device along with two associated peripheral interrupt flag registers PIE1/PIR1 and PIE2/PIR2. Again, if a PICmicro other than the PIC16F877 is used, refer to the datasheet as the number of peripheral interrupt registers and their contents may vary. *Flags will set even if interrupts are not enabled!!

82 PIE1 and PIR1 Registers* PIE1 Register (Peripheral Interrupt Enables)
ADIE RCIE TXIE SSPIE CCP1IE TMR2IE TMR1IE PIR1 Register (Peripheral Interrupt Requests) ADIF RCIF TXIF SSPIF CCP1IF TMR2IF TMR1IF Enable Flag Condition ADIE ADIF ADC conversion complete RCIE RCIF AUSART receive buffer is full TXIE TXIF AUSART transmit buffer is full The Peripheral Interrupt Enable 1 register and its associated Peripheral Interrupt Request register 1 contain the enabling and flag bits for the following peripheral events Analog to digital conversion completed Enhanced Universal Serial Asynchronous Receive Transmit (EUSART) interrupts detect whether a receive or transmit buffer is full and ready for processing Master Synchronous Serial Port event interrupt. This will include: SPI or I2C Slave/Master transmission/reception has taken place I2C condition such as START/STOP condition initiated and completed by MSSP module RESTART condition initiated and completed by MSSP ACK (acknowledge) condition initiated and completed by MSSP START/STOP condition occurred while MSSP was idle A Capture or Compare Match has occurred on Timer1 related to the Capture/Compare peripheral Timer2 value has matched the period value define in PR2 when using a Pulse Width Modulated signal on the CCP peripheral module An overflow has occurred on Timer1 (i.e. FFFFh0000h) SSPIE SSPIF I2C or SPI Interrupt CCP1IE CCP1IF Timer1 register capture or compare match TMR2IE TMR2IF Timer2 value and PR2 period value match TMR1IE TMR1IF Timer1 register has overflowed *Check individual datasheets for bit locations

83 PIE2 and PIR2 Registers* PIE2 Register (Interrupt Enables)
OSCFIE C2IE C1IE EEIE BCLIE ULPWUIE CCP2IE PIR2 Register (Interrupt Flags) OSCFIF C2IF C1IF EEIF BCLIF ULPWUIF CCP2IF Enable Flag Condition OSCFIE OSCFIF System Oscillator Failed C2IE C2IF Comparator2 output changed C1IE C1IF Comparator1 output changed The PIE2 and PIR2 registers are shown in the above slide. The enables and flags are for the following interrupt events Oscillator failure, Comparator output change Write operations verification Bus collisions Wake-up events Capture and compare match events As with the INTCON register shown earlier, interrupt flags for both PIR1 and PIR2 will set when an interrupt condition has occurred. However, to use the flags in your code it will be necessary to enable the GIE, PEIE and the associated PIEx enable bits. EEIE EEIF Write operation completed BCLIE BCLIF Bus collision occurred in MSSP I2C mode ULPWUIE ULPWUIF Wake-up condition occurred CCP2IE CCP2IF Timer1 Capture or Compare match occurred *Check individual datasheets for bit locations

84 Enabling a Peripheral (Timer 1) Interrupt
void interrupt isr (void) { //Clear the interrupt flag TMR1IF = 0; // <ISR code> } Program Counter “while(1);” address “while(1);” address Stack void main (void) { //clear the interrupt flag TMR1IF = 0; //enable Timer 1 interrupt TMR1IE = 1; //Enable peripheral and //global interrupts PEIE = 1; GIE = 1; // <code to set up Timer1> while(1); //loop forever } INTCON 1 1 GIE PEIE PIE1 The following example will show what is needed to enable a peripheral interrupt. Using Timer1 as an example, the program counter will step through the code sequentially. The key registers are shown on the bottom right and will have individual bits set or cleared in accordance with the code on the left. This example will also highlight what happens with the Global Interrupt Enable bit, loading the stack during an interrupt and clearing the individual interrupt flag within the ISR. *Note: Timer1 module configuration is mentioned but not shown as this will be covered later in the presentation. Important points to mention: GIE bit must be set to ‘1’ for any interrupt to occur The GIE bit is cleared when an interrupt flag is detected and set automatically with completion of the ISR( ) This will ensure that no other interrupt will disrupt the current interrupt’s service routine PEIE bit in INTCON must be set to enable peripheral interrupts Software should ensure that the interrupt flag in the Peripheral Interrupt Result register is cleared during initialization The interrupt flag will set when its associate event occurs regardless of whether or not the PEIE or GIE bits are set Software will need to clear the flag to allow further interrupts to occur for that peripheral 1 TMR1IE PIR1 1 TMR1IF Timer1 Overflow!

85 Interrupt Latency Interrupt Latency:
Time from interrupt event to execution of instruction at address 0004h Synchronous interrupts (typically internal) latency is 3 instruction cycles (Tcy) Asynchronous interrupts (typically external) latency is 3 – 4 instruction cycles The microcontroller can be configured to receive internal and/or external interrupts. The sources for these interrupts can include the following: Internal Interrupts: Completion of ADC conversion Timer rolling over form its maximum value back to zero Information received on the USART etc…. External Interrupts: may be an event occurring on a PORTB pin configured for interrupts. Any change from an external signal noted on this pin could trigger the processor to perform a specific task related to the change. Interrupt Latency Interrupt latency is defined as the time from the interrupt event (the interrupt flag bit gets set) to the time that the instruction at address 0004h starts execution (when that interrupt is enabled). For synchronous interrupts (typically internal), the latency is 3TCY. For asynchronous interrupts (typically external), such as the INT or Port RB Change Interrupt, the interrupt latency will be TCY (instruction cycles). The exact latency depends upon when the interrupt event occurs in relation to the instruction cycle. The latency is the same for both one and two cycle instructions. main() ISR CPU EXECUTION TRACE

86 Context Saving During an interrupt: Key registers you may want saved:
Only the PC value is saved (on the stack) Registers changed in the Interrupt Service Routine (ISR) are permanently changed Key registers you may want saved: Working register Status PCLATH (Program Counter Latch High) User defined registers

87 Interrupt Priority Mid-Range PIC microcontrollers treat all Interrupts with the same priority The user must do the following: Determine source of interrupt Determine the order in which the interrupts are serviced.

88 Interrupt Priority Example
void interrupt isr (void) { //Check various interrupt flags and respond //accordingly //If the RBIF flag is set, then perform the PORTB_ISR subroutine if (RBIF) PORTB_ISR ( ); //If TMR2IF flag is set, then perform the Timer2_ISR subroutine if (TMR2IF) Timer2_ISR ( ); //If the TMR1IF flag is set, then perform the Timer1_ISR subroutine if (TMR1IF) Timer1_ISR ( ); } Note that all context saving is done automatically by the C compiler!

89 External Interrupt Hands on Lab

90 External Interrupts The objective of this is to:
Learn how to set up and enable an external interrupt on the Mid-Range PIC Become more familiar with the MPLAB IDE, the PICdem2 Plus and the ICD2 Debugger Building a Project Using the ICD to set a break point

91 Lab 2: External Interrupt and Pooling
*disconnect J6

92 External Interrupt Lab Overview
Interrupt Vector Main Program Clear Variables Set S3FLAG Initialize (RB0) for S3 input and RA4 for S2 input Set some delay Enable Interrupts Clear IF Monitor RA4 by pooling and RB0 by interrupt, incr. press_count Return to Main

93 Lab Specifics Code is located in \RTC\Lab2-INT
The S3 switch is connected to the “RBO/INT” pin on PORTB, S2 is connected to RA4 pin on PORTA The “press_count” register will display the sum of times S3 and S2 has been pushed. Use MPLAB and the ICD to set a “breakpoint” in the code to view the changing value of the register named “press_count”

94 What you need to know The function of the INTCON register bits
Jumper “J6” must be removed in order for the “INTE” pin to work How to setup break points and a “Watch Window” in MPLAB

95 External Interrupt Lab Solution

96 Peripherals

97 I/O Overview Up to 35 bi-directional Input/Output pins
some multiplexed with peripheral functions High drive capability 25mA source or sink Direct, single cycle bit manipulation Most I/O’s have ESD protection After Reset: Analog capable pins come up as Analog Digital I/O pins come up as Input Discuss: Pin to Pin compatibility while migrating to large memory. Microchip offers true pin to pin compatibility across the PICmicros very minimal to no change in the hardware. Software compatibility while migrating to new PICmicros All the controllers in the family use the same address space for SFRs and also the instruction set. Advantages of High/Source ports No need for external buffers while driving LEDs, Small Signal Transistors etc. Depending on which peripherals are enabled, some or all of the pins may not be available as general purpose I/O. In general, when a peripheral is enabled, the associated pin may not be used as a general purpose I/O pin. *IMPORTANT: Since some of the I/O’s default to analog inputs on the PIC16F877, these pins need to be configured to digital if needed. Otherwise, the code will not function. Furthermore, there is potential for damage to the PICmicro if an analog signal is received on a pin configured for digital input due to excessive current draw. All write operations are read-modify-write operations. Therefore, a write to a port implies that the port pins are read, this value is modified and then written to the PORT data latch.

98 PORTx and TRISx Registers
Every PORT (A, B, C, D, E) will have a corresponding direction register TRISx PORTB Register RB7 RB6 RB5 RB4 RB3 RB2 RB1 RB0 Data Configures Data Direction The PORTB register is shown in the above slide along with its corresponding data direction register TRISB. Setting a bit in the TRISB register will disable the output driver and make the corresponding PORTB pin and input. Clearing a bit in TRISB will enable the output driver and put the contents of the latch on the selected pin. PORTB Tri-State Register (TRISB) TRISB7 TRISB6 TRISB5 TRISB4 TRISB3 TRISB2 TRISB1 TRISB0 1 = corresponding PORTB pin is an INPUT 0 = corresponding PORTB pin is an OUTPUT

99 Configuring Analog Inputs for Digital
I/O’s with digital and analog capabilities default to analog on reset *IMPORTANT: Since some of the I/O’s default to analog inputs on the PIC16F887, these pins need to be configured to digital if needed. Otherwise, the code will not function. Furthermore, there is potential for damage to the PICmicro if an analog signal is received on a pin configured for digital input due to excessive current draw. To configure analog/digital pins, the Analog Select registers are used. The state of the ANSEL/ANSELH bits have no affect on digital output functions. A pin with TRIS clear and ANSELH set will still operate as a digital output, but the Input mode will be analog. This can cause unexpected behavior when executing read-modify-write instructions on the affected port. The PIC16F887 pins that need to be configured using these registers are AN0AN13 and correspond to the numbering convention within the analog select registers Notice that most, but not all, PORTB pins are configurable for analog. This will become important to remember in the upcoming labs.

100 Configuring Analog Inputs for Digital
Two ways to configure Analog inputs as Digital: 1) Analog Select Registers (ANSEL and ANSELH) For devices with > 8 analog pins OR 2) ADC Control register 1 (ADCON1) For devices with 8 or less analog pins ANS7 ANS6 ANS5 ANS4 ANS3 ANS2 ANS1 ANS0 ANS13 ANS12 ANS11 ANS10 ANS9 ANS8 Analog Select Register (ANSEL) Analog Select High Register (ANSELH) 1 = Pin assigned as Analog Input 0 = Digital I/O *IMPORTANT: Since some of the I/O’s default to analog inputs on the PIC16F887, these pins need to be configured to digital if needed. Otherwise, the code will not function. Furthermore, there is potential for damage to the PICmicro if an analog signal is received on a pin configured for digital input due to excessive current draw. To configure analog/digital pins, the Analog Select registers are used. The state of the ANSEL/ANSELH bits have no affect on digital output functions. A pin with TRIS clear and ANSELH set will still operate as a digital output, but the Input mode will be analog. This can cause unexpected behavior when executing read-modify-write instructions on the affected port. The PIC16F887 pins that need to be configured using these registers are AN0AN13 and correspond to the numbering convention within the analog select registers Notice that most, but not all, PORTB pins are configurable for analog. This will become important to remember in the upcoming labs. ADFM ADCS2 ADC Control Register 1 (ADCON1) PCFG3 PCFG2 PCFG1 PCFG0 Port Configuration Bits

101 Configuring Analog Inputs for Digital
Vdd AN7 AN6 AN5 AN4 AN1 AN0 AN3 AN2 PCFG <3:0> *IMPORTANT: Since some of the I/O’s default to analog inputs on the PIC16F887, these pins need to be configured to digital if needed. Otherwise, the code will not function. Furthermore, there is potential for damage to the PICmicro if an analog signal is received on a pin configured for digital input due to excessive current draw. To configure analog/digital pins, the Analog Select registers are used. The state of the ANSEL/ANSELH bits have no affect on digital output functions. A pin with TRIS clear and ANSELH set will still operate as a digital output, but the Input mode will be analog. This can cause unexpected behavior when executing read-modify-write instructions on the affected port. The PIC16F887 pins that need to be configured using these registers are AN0AN13 and correspond to the numbering convention within the analog select registers Notice that most, but not all, PORTB pins are configurable for analog. This will become important to remember in the upcoming labs. ADFM ADCS2 ADC Control Register 1 (ADCON1) PCFG3 PCFG2 PCFG1 PCFG0 Port Configuration Bits

102 Initializing Digital I/O with ADCON1 register (PIC16F877A)
Example: Initializing PORTB bits RB<7:4> as digital inputs and RB<3:0> as digital outputs //---configure PORTB for digital PORTB = 0x00; //Clear PORTB ADCON1 = 0x06; //Configure as all digital //---Set up direction of each PORTB pin TRISB = 0b ; //1 = input, 0 = output First, the PORTB register is initialized to all 0’s The Analog Select Register bits are cleared thereby configuring PORTB as digital i/o Next, the PORTB direction register is selected and the corresponding bits configured for input and output.

103 Initializing Digital I/O with ANSEL and ANSELH registers (PIC16F887)
Example: Initializing PORTB bits RB<7:4> as digital inputs and RB<3:0> as digital outputs //---configure PORTB for digital PORTB = 0x00; //Clear PORTB ANSLEH = 0x00; //Configure as all digital ANSEL = 0x00; //---Set up direction of each PORTB pin TRISB = 0b ; // 1 = input, 0 = output First, the PORTB register is initialized to all 0’s The Analog Select Register bits are cleared thereby configuring PORTB as digital i/o Next, the PORTB direction register is selected and the corresponding bits configured for input and output.

104 PORTB Interrupt & Weak Pull-Up Options
All PORTB pins have Interrupt-on-Change and Weak Pull-Up options Weak Pull-Up PORTB Register (WPUB) WPUB7 WPUB6 WPUB5 WPUB4 WPUB3 WPUB2 WPUB1 WPUB0 1 RB3 1 = Pull-up enabled 0 = Pull-up disabled Devices without WPUB register use RBPU bit in OPTION register Interrupt-On-Change PORTB Register (IOCB) IOCB7 IOCB6 IOCB5 IOCB4 ICOB3 IOCB2 IOCB1 IOCB0 1 1 = Interrupt-on-change enabled 0 = Interrupt-on-change disabled Devices without IOCB rely on RBIE bit in INTCON RB4 In addition to being used as General Purpose I/O, PORTB has an interrupt-on-change option and a weak pull-up option. Each pin on PORTB has an individually configurable internal weak pull-up. In the past, on previous PICmicros, not all of the PORTB pins had weak pull-ups. This has changed on the PIC16F887 used in this presentation. The pull-up ensures that noise will not affect the state of the pin leading to misreads. Important to note, this resistance is weak and can be overpowered. PORTB pins have individually configurable interrupt-on-change capability. This feature is enabled in the Interrupt-On-Change register by setting the corresponding bit. Any change on the configured pin will trigger the RBIF flag in INTCON. Reading or writing to PORTB will end the mismatch condition and allow flag bit RBIF to be cleared. The flag will not be cleared unless PORTB is either READ or WRITTEN to first. If more than one interrupt-on-change is used, the polling method can be used to prioritize individual interrupts. HIGH LOW Interrupt Control Register (INTCON) GIE PEIE TMR0IE INTE RBIE TMR0IF INTF RBIF RBIF *PORTB must first be read/written and then RBIF can be cleared in software

105 Timers

106 Timers Timers are used for many functions: PIC16F877 has 3 timers
timing reference to generate an event count the number of events waveform generation etc... PIC16F877 has 3 timers Timer0 Timer1 Timer2

107 Timer Comparison TIMER0 TIMER1 TIMER2 SIZE OF REGISTER 8-bits (TMR0)
16-bits (TMR1H:TMR1L) 8-bits (TMR2) CLOCK SOURCE (Internal) Fosc/4 (External ) T0CKI pin T1CKI pin or Timer 1 oscillator (T1OSC) None CLOCK SCALING AVAILABLE (Resolution) Prescaler 8-bits (1:21:256) Prescaler 3-bits (÷1,÷2,÷4,÷8) Prescaler (1:1,1:4,1:8) Postscaler (1:11:16) INTERRUPT EVENT and FLAG LOCATION On overflow FFh00h (T0IF in INTCON) On overflow FFFFh0000h (TMR1IF in PIR1) TMR2 matches PR2 (TMR2IF in PIR2) CAN WAKE PIC FROM SLEEP? NO YES

108 Timer 0 Block Diagram OPTION register 8 prescaler
DATA BUS Fosc/4 8 synchronize T0CKI pin scaled clock TMR0 PS2 PS1 PS0 TMR0 RATE 1:2 1 1:4 1:8 1:16 1:32 1:64 1:128 1:256 prescaler Watchdog Timer WDT out OPTION register RBPU INTEDG TOCS TOSE PSA PS2 PS1 PS0 Timer0 is mainly controlled by setting bits within the OPTION register. TOCS: Timer0 Clock Source Select When using an external clock source always refer to the electrical specifications of the datasheet to ensure that timing requirements are met. T0SE: Timer0 Source Edge Select bit This bit provides the option of selecting either the positive or negative going transition edge of the clock source whichever best suits the design PSA: Prescaler Select bit The prescaler used by Timer0 is also used by the Watchdog Timer. Precautions must be used when switching the prescaler from Timer0 to the Watchdog timer. The Watchdog Timer will reset the PICmicro when it overflows from FFh00h. The datasheet for the PIC16F877 provides an instruction sequence that should be included within the code when switching the prescaler from Timer0 to the Watchdog Timer to avoid generation of an unintended PICmicro reset. PS<2:0> bits: Prescaler Rate Select bits There are 8 prescaler options for the Timer0 module ranging from 1:2 to 1:256 on the PIC16F877. In order to have a 1:1 value the prescaler will need to be assigned to the Watchdog Timer. The prescaler is not readable or writeable but any instruction that writes to the TMR0 register will clear the prescaler. Prescaler Rate Select Bits Prescaler Assignment 1= prescaler assigned to WDT 0= prescaler assigned to Timer 0 TMR0 Clock Source Select 1 = TOCK1, 0 = Fosc/4 Source Edge Select 1 = increment TMR0 on high-to-low transition 0 = increment TMR0 on low-to-high transition

109 Timer 0 Block Diagram DATA BUS Fosc/4 8 synchronize T0CKI pin scaled clock TMR0 prescaler Watchdog Timer TMR0IF INTCON register If the external clock source (TOCKI) is used it will be synchronized to the internal clock If an external clock source is used on TOCKI, the signal is synchronized to the TMR0 register by sampling the prescaler output. Therefore, the high and low periods of the external clock source must meet the timing requirements as shown in the Electrical Specifications section of the PICmicro datasheet. Timer0 overflows set the TMR0IF bit in the INTCON register. This bit must be cleared following any ISR to ensure further interrupts related to Timer0 can occur. The TMR0IE bit in INTCON must be enabled for interrupts on the module to be used. Timer 0 is readable or writeable Timer 0 interrupt flag is set on TMR0 roll-over (FF to 00)

110 Timer0 Initialization CONTINUE 1 YES T0IF = 0? 1 1 NO TMR0 INTCON T0IE
//Make sure the Timer0 count //register (TMR0) is clear TMR0 = 0X00; //Disable the Timer0 interrupt //and clear the flag bit T0IE = 0; T0IF = 0; /*Setup the following in the OPTION_REG Timer0 increment from internal clock with a prescaler of 1:16*/ OPTION = 0b ; /*The TMR0 interrupt is disabled, do polling on the Timer0 overflow flag bit*/ While (!T0IF); <continue> INTCON 1 T0IE T0IF YES This interrupt flag will set on Timer0 overflow even if all interrupts are disabled T0IF = 0? OPTION_REG 1 1 TOCS PSA PS<2:0> NO ASSIGNS PRESCALER TO TIMER0 SELECTS 1:16 TIMER0 RATE SELECTS INTERNAL CLOCK CONTINUE

111 Timer1 Block Diagram TMR1H TMR1L Timer1 Control Register (T1CON)
T1OSI T1 OSC synchronize T1OS0 prescaler Fosc/4 T1CKI pin TMR1H TMR1L Enable Timer1 Control Register (T1CON) TMR1ON T1GINV TMR1GE T1CKPS1 T1CKPS0 T1OSCEN T1SYNC TMR1CS TMR1ON The TMR1CS bit of the T1CON register is used to select the clock source. When TMR1CS = 0, the clock source is FOSC/4. When TMR1CS = 1, the clock source is supplied externally. When the internal clock source is selected the TMR1H:TMR1L register pair will increment on multiples of FOSC as determined by the Timer1 prescaler. When the external clock source is selected, the Timer1 module may work as a timer or a counter. When counting, Timer1 is incremented on the rising edge of the external clock input T1CKI. In addition, the Counter mode clock can be synchronized to the microcontroller system clock or run asynchronously. If an external clock oscillator is needed (and the microcontroller is using the INTOSC without CLKOUT), Timer1 can use the LP oscillator as a clock source A low-power kHz crystal oscillator is built-in between pins T1OSI (input) and T1OSO (amplifier output). The oscillator is enabled by setting the T1OSCEN control bit of the T1CON register. The oscillator will continue to run during Sleep.The Timer1 oscillator is identical to the LP oscillator. The user must provide a software time delay to ensure proper oscillator start-up. TRISC0 and TRISC1 bits are set when the Timer1 oscillator is enabled. RC0 and RC1 bits read as ‘0’ and TRISC0 and TRISC1 bits read as ‘1’. Timer1 has four prescaler options allowing 1, 2, 4 or 8 divisions of the clock input. The T1CKPS bits of the T1CON register control the prescale counter. The prescale counter is not directly readable or writable; however, the prescaler counter is cleared upon a write to TMR1H or TMR1L. T1CKPS1 T1CKPS0 scale 1 1:8 1:4 1:2 1:1 Timer1 On 1 = Enable Timer1 LP Oscillator Enable 1 = T1OSC selected 0 = T1CKI can be used Clock Source Select 1 = External (T1CKI) 0 = Internal (FOSC/4)

112 Timer1 Block Diagram TMR1H TMR1L Timer1 Control Register (T1CON)
T1OSI T1 OSC synchronize T1OS0 prescaler Fosc/4 T1CKI pin TMR1H TMR1L Enable Timer1 Control Register (T1CON) TMR1ON T1GINV TMR1GE T1CKPS1 T1CKPS0 T1OSCEN T1SYNC TMR1CS TMR1ON If control bit T1SYNC of the T1CON register is set, the external clock input is not synchronized. The timer continues to increment asynchronous to the internal phase clocks. The timer will continue to run during Sleep and can generate an interrupt on overflow, which will wake-up the processor. However, special precautions in software are needed to read/write the timer Timer1 gate source is software configurable to be the T1G pin or the output of Comparator C2. This allows the PICmicro to directly time external events using T1G or analog events using Comparator C2. The output of the TMR1 Gate source will enable Timer1 to start counting or disable Timer1 from counting. This feature is useful to time Low or High transitions of either the comparator 2 output or T1G input. To select between measure High transitions or Low transitions, set or clear the T1GINV bit in T1CON respectively. Timer1 Gate Enable and Timer1 Gate Invert are available on some devices Timer1 External Clock Input Synchronization 1 = do not synchronize external clock input 0 = synchronize external clock input with internal clock (Fosc/4)

113 Timer1 Interrupt Setup TMR1L TMR1H PIR1 PIE1 INTCON 0 0 0 0 0 0 0 0
void main (void) { //Clear the Timer1 interrupt flag TMR1IF = 0; //Enable Timer1 interrupt TMR1IE = 1; //Enable Global and Peripheral Interrupts PEIE = 1; GIE = 1; } PIR1 1 TMR1IF PIE1 1 The Timer1 register pair (TMR1H:TMR1L) increments to FFFFh and rolls over to 0000h. When Timer1 rolls over, the Timer1 interrupt flag bit of the PIR1 register is set. To enable the interrupt on rollover, you must set these bits: • Timer1 interrupt enable bit of the PIE1 register • PEIE bit of the INTCON register • GIE bit of the INTCON register The interrupt is cleared by clearing the TMR1IF bit in the Interrupt Service Routine. Note: The TMR1H:TTMR1L register pair and the TMR1IF bit should be cleared before enabling interrupts. TMR1IE INTCON 1 1 GIE PEIE

114 TMR1H:TMR1L INCREMENTING
Timer1 Initialization TMR1H //Make sure the TMR1 registers are clear TMR1H = 0X00; TMR1L = 0X00; //Make sure the TMR1IF flag in PIR1 //is cleared TMR1F = 0; /*Setup T1CON register for internal clock with 1:8 prescaler, Timer1 is stopped and T1 osc is disabled*/ T1CON = 0b ; //Start Timer1 incrementing TMR1ON = 1; //The TMR1 interrupt is disabled, do polling //on the TMR1IF overflow bit while(!TMR1IF); //Continue TMR1L OVERFLOW!! TMR1H:TMR1L INCREMENTING PIR1 1 TMR1IF T1CON 1 1 1 TMR1CS TMR1ON T1SYNC T1CKPS<1:0> Select internal clock (Fosc/4) Synchronize external clock output Scale input clock to 1:8

115 Timer 1 Lab

116 LAB 3.0 – Timer1 and Real Time Clock

117 Timer1 Lab Objective of this lab is to become familiar with the operation of Timer1 AND To gain experience enabling Peripheral Interrupts Learn how to use RTC kHz clock

118 Lab Overview Interrupt Vector Main Program
Save Context Configure Timer1 Config Register EXT CLK, PRESCALE 1:1, T1OSCEN Clear IF Load initial value to TMR1H:L Load initial value to TMR1H:L Enable Timer1, Global and Peripheral Interrupts then TMR1ON Set T1FLAG Main Loop Return to main Update Time if T1FLAG is TRUE Clear T1FLAG

119 Lab Specifics The code for the lab is in
RTC\Lab3-Timer1_RTC Within LCD_T1_RTC.c complete the following Set Timer 1 clock source to External RTC Set Timer 1 pre-scaler to 1:1 Load Timer 1 with 0x8000 (65,356 –32768) Start Timer 1 Enable Timer 1, Global and Peripheral Interrupts

120 What you need to know Register Operations of INTCON, T1CON, TMR1H, TMR1L and PIE1 With a value of 0x8000 and a pre-scaler of 1:1, Timer1 will overflow every 1,000,000 cycles: 1 second The interrupt vector code to set t1flag has been provided to increment the actual time

121 Timer 1 Solution

122 Lab Questions Question:
Was Timer 1 still running during the time it took to service the Interrupt? Answer: Yes What effect did this have on the value to be placed to reload TMR1L and TMR1H? Everything – to be precise the latency of reloading Timer1 should be considered.

123 Timer2 Block Diagram TMR2 COMPARATOR PR2
OUTPUT TMR2 Prescaler 1:1, 1:4, 1:16 Fosc/4 COMPARATOR Postscaler 1:1  1:16 PR2 The clock input to the Timer2 module is the system instruction clock (FOSC/4). The clock is fed into the Timer2 prescaler, which has prescale options of 1:1, 1:4 or 1:16. The output of the prescaler is then used to increment the TMR2 register. The values of TMR2 and PR2 are constantly compared to determine when they match. TMR2 will increment from 00h until it matches the value in PR2. When a match occurs, two things happen: • TMR2 is reset to 00h on the next increment cycle. • The Timer2 postscaler is incremented The match output of the Timer2/PR2 comparator is then fed into the Timer2 postscaler. The postscaler has postscale options of 1:1 to 1:16 inclusive. The output of the Timer2 postscaler is used to set the TMR2IF interrupt flag bit in the PIR1 register. The TMR2 and PR2 registers are both fully readable and writable. On any Reset, the TMR2 register is set to 00h and the PR2 register is set to FFh. Timer2 is turned on by setting the TMR2ON bit in the T2CON register to a ‘1’. Timer2 is turned off by clearing the TMR2ON bit to a ‘0’. The Timer2 prescaler is controlled by the T2CKPS bits in the T2CON register. The Timer2 postscaler is controlled by the TOUTPS bits in the T2CON register. The prescaler and postscaler counters are cleared when: • A write to TMR2 occurs. • A write to T2CON occurs. • Any PICmicro Reset occurs (Power-on Reset, MCLR Reset, Watchdog Timer Reset, or Brown-out Reset). Timer2 Control Register (T2CON) TOUTPS3 TOUTPS2 TOUTPS1 TOUTPS0 TMR2ON T2CKPS1 T2CKPS0 T2CKPS1 T2CKPS0 Scale 1:1 1 1:4 X 1:16 Timer2 ON 1 = Timer2 enabled

124 Timer2 Block Diagram TMR2 COMPARATOR PR2
TOUTPS3 TOUTPS2 TOUTPS1 TOUTPS0 SCALE 1:1 1 1:2 1:3 1:4 1:5 1:6 1:7 1:8 1:9 1:10 1:11 1:12 1:13 1:14 1:15 1:16 TMR2 OUTPUT TMR2 Prescaler 1:1, 1:4, 1:16 Fosc/4 COMPARATOR Postscaler 1:1  1:16 PR2 The clock input to the Timer2 module is the system instruction clock (FOSC/4). The clock is fed into the Timer2 prescaler, which has prescale options of 1:1, 1:4 or 1:16. The output of the prescaler is then used to increment the TMR2 register. The values of TMR2 and PR2 are constantly compared to determine when they match. TMR2 will increment from 00h until it matches the value in PR2. When a match occurs, two things happen: • TMR2 is reset to 00h on the next increment cycle. • The Timer2 postscaler is incremented The match output of the Timer2/PR2 comparator is then fed into the Timer2 postscaler. The postscaler has postscale options of 1:1 to 1:16 inclusive. The output of the Timer2 postscaler is used to set the TMR2IF interrupt flag bit in the PIR1 register. The TMR2 and PR2 registers are both fully readable and writable. On any Reset, the TMR2 register is set to 00h and the PR2 register is set to FFh. Timer2 is turned on by setting the TMR2ON bit in the T2CON register to a ‘1’. Timer2 is turned off by clearing the TMR2ON bit to a ‘0’. The Timer2 prescaler is controlled by the T2CKPS bits in the T2CON register. The Timer2 postscaler is controlled by the TOUTPS bits in the T2CON register. The prescaler and postscaler counters are cleared when: • A write to TMR2 occurs. • A write to T2CON occurs. • Any PICmicro Reset occurs (Power-on Reset, MCLR Reset, Watchdog Timer Reset, or Brown-out Reset). Timer2 Control Register (T2CON) TOUTPS3 TOUTPS2 TOUTPS1 TOUTPS0 TMR2ON T2CKPS1 T2CKPS0 T2CKPS1 T2CKPS0 Scale 1:1 1 1:4 X 1:16 Timer2 ON 1 = Timer2 enabled

125 Timer2 Block Diagram TMR2 1 1 1 1 1 0 0 0 1 1 1 1 0 1 1 0
OUTPUT TMR2 Prescaler 1:1, 1:4, 1:16 Fosc/4 COMPARATOR Postscaler 1:1  1:16 PR2 PIR1 1 1 TMR2IF Timer2 Control Register (T2CON) TOUTPS3 TOUTPS2 TOUTPS1 TOUTPS0 TMR2ON T2CKPS1 T2CKPS0

126 Timer2 Initialization TMR2 = PR2 1 1 1 1 1 1 1 TMR2 INCREMENTING TMR2
/*Disable the Timer2 interrupts in the PIE1 register. Make sure the Timer2 interrupt flag in PIR1 is cleared. */ TMR2IE = 0; TMR2IF = 0; /*Setup T2CON register for: Postscaler = 1:15 Prescaler = 1:16 Timer2 is off */ T2CON = 0b ; //Make sure the TMR2 register is clear TMR2 = 0X00; //Load the period register PR2 = 0b ; //Start Timer2 incrementing TMR2ON = 1; //The Timer2 interrupt is disabled, //do polling on the interrupt flag while(!TMR2IF); TMR2 INCREMENTING TMR2 = PR2 PIE1 TMR2IE PIR1 1 TMR2IF T2CON 1 1 1 1 1 TOUTPS<3:0> T2CKPS<1:0> TMR2ON Postscaler set to 1:15 Timer2 is OFF Prescaler set to 1:16 PR2 1

127 Timer2 Initialization TMR2 = PR2 1 1 1 1 1 1 1 TMR2 INCREMENTING TMR2
TOUTPS3 TOUTPS2 TOUTPS1 TOUTPS0 SCALE 1:1 1 1:2 1:3 1:4 1:5 1:6 1:7 1:8 1:9 1:10 1:11 1:12 1:13 1:14 1:15 1:16 /*Disable the Timer2 interrupts in the PIE1 register. Make sure the Timer2 interrupt flag in PIR1 is cleared. */ TMR2IE = 0; TMR2IF = 0; /*Setup T2CON register for: Postscaler = 1:15 Prescaler = 1:16 Timer2 is off */ T2CON = 0b ; //Make sure the TMR2 register is clear TMR2 = 0X00; //Load the period register PR2 = 0b ; //Start Timer2 incrementing TMR2ON = 1; //The Timer2 interrupt is disabled, //do polling on the interrupt flag while(!TMR2IF); TMR2 = PR2 TMR2 INCREMENTING PIE1 TMR2IE PIR1 1 TMR2IF T2CON 1 1 1 1 1 T2CKPS1 T2CKPS0 Scale 1:1 1 1:4 X 1:16 TOUTPS<3:0> T2CKPS<1:0> TMR2ON Postscaler set to 1:15 Timer2 is OFF Prescaler set to 1:16 PR2 1

128 Timer 2 Lab

129 Timer 2 Lab The Goal of Lab 3 is to become familiar with the following : Setting the Prescaler value Setting the Postscaler value Turning on Timer2 Setting the Interrupt enable bits needed for Timer2 to successfully generate an interrupt

130 Lab Overview Interrupt Vector Main Program Save Context
Initialize PORT B Set up Timer2 Period, Prescaler, Postscaler Increment counter the number of times Timer2 has interrupted Output 4 LSBs of count to LEDs Enable interrupts NOP Restore context Return to main

131 Lab Specifics Code for this lab is in
\RTC\Lab4-Timer2 Complete the following sections of code Set Timer 2 prescaler to a value of 4 Set Timer 2 postscaler to a value of 13 Turn Timer 2 on Configure the GIE and PEIE bits in the Interrupt Control register (INTCON) Configure the Timer2 Interrupt Enable bit in the Timer2 Configuration register (T2CON)

132 What you need to know Special Function Registers (SFRs) needed for this lab are: INTCON…(Interrupt Control) PIE1……..(Peripheral Interrupt Enable 1) PR2……...(Timer2 Period Register) T2CON…..(Timer2 Control) With the Period register (PR2) set to 250, the prescaler at 4, and the postscaler at 13, Timer2 will interrupt every 13 ms (about 1/80 second) with a 4Mhz oscillator (Fosc/4 = 1Mhz).

133 Timer 2 Lab Solution

134 Lab Questions Question:
Like Timer1, does Timer2 keep running during the Interrupt Service Routine (ISR)? Answer: Yes it does! In the Timer1 Lab, our ISR had to reload Timer1 to produce the proper period (100K cycles). ISR clock cycles prior to reloading Timer1 needed to be accounted for to ensure a precise interrupt period. Did we need to reload and account for ISR clock cycles for Timer2? No, Timer2 automatically resets itself to “0” and continues counting after a match with the period register (PR2).

135 Capture/Compare/PWM Module

136 Capture/Compare/PWM (CCP) Overview
Times the duration of an external event using an input pin Compare Changes an output pin or generates an interrupt when a specific amount of time has passed Pulse Width Modulation (PWM) Creates a reconfigurable, steady duty-cycle, square wave output at a defined frequency Provides enhanced features for various bridge connectivity * Module interfaces with Timers 1 and 2 The Enhanced Capture/Compare/PWM module allows the user to time and control different events. Capture mode: the peripheral allows the timing of the duration of an event Compare mode: provides the capability to trigger an external event when a defined period of time has passed PWM mode: generates a Pulse-Width-Modulated signal of varying frequency and duty-cycle

137 Capture/Compare/PWM (CCP) Overview
Times the duration of an external event using an input pin Compare Changes an output pin or generates an interrupt when a specific amount of time has passed Pulse Width Modulation (PWM) Creates a reconfigurable, steady duty-cycle, square wave output at a defined frequency Provides enhanced features for various bridge connectivity * Module interfaces with Timers 1 and 2 CCP MODE Timer Resource Capture Timer 1 Compare PWM Timer 2 The Enhanced Capture/Compare/PWM module allows the user to time and control different events. Capture mode: the peripheral allows the timing of the duration of an event Compare mode: provides the capability to trigger an external event when a defined period of time has passed PWM mode: generates a Pulse-Width-Modulated signal of varying frequency and duty-cycle

138 CCP Control Register CCP1 Control Register (CCP1CON) P1M1 P1M0 CCP1X
CCP1Y CCP1M3 CCP1M2 CCP1M1 CCP1M0 BIT FUNCTION CCP1M<3:0> CCP Mode Select Bits configure the module as Input Capture, Output Compare, or PWM CCP1<X:Y> PWM duty cycle 2 LSB’s (8 MSB’s located in CCPR1L) P1M<1:0> These PWM output configuration bits are available for Enhanced CCP (ECCP) modules only. They provide half-bridge or full-bridge output steering control. EECP Mode Select bits (CCP1M): These bits are the main control bits of the module. Here, the module is configure for one of the three possible modes (CAPTURE/COMPARE/PWM). Further configuration such as edge detection for capture modes, compare special events, and interrupt selection is also enabled here. These bits are also how the user accesses the module’s prescaler when using Capture mode PWM Output Configuration bits(P1M<1:0>): These bits are used to configure the PWM module as either a standard, single PWM output or make use of the Enhanced features on some PICmicros including the PIC16F887. These enhanced modes ease the interface of the module with bridge networks used in motor control designs. Duty Cycle Least Significant bits: these bits are concatenated with the 8 MSB’s located in CCPR1L to provide a 10-bit resolution. The CCPx<X:Y> bits are also referred to as DCxB[1:0] on the PIC16887. The CCP2CON register has many of the same features as CCP1CON. However, enhanced PWM configuration is not included as well as compare mode “toggle” on the CCPx pin.

139 CCP Control Register CCP1 Control Register (CCP1CON) P1M1 P1M0 CCP1X
CCP1Y CCP1M3 CCP1M2 CCP1M1 CCP1M0 BIT FUNCTION CCPxM3 CCPxM2 CCPxM1 CCPxM0 CCP Mode Selected Capture/Compare/PWM off (resets CCP module) 1 Unused (reserved) Compare mode, toggle output on match Capture mode, every falling edge Capture mode, every rising edge Capture mode, every 4th rising edge Capture mode, every 16th rising edge Compare mode, set output on match Compare mode, clear output on match Compare mode, generate software interrupt on match Compare mode, trigger special event x PWM mode CCP1M<3:0> CCP Mode Select Bits configure the module as Input Capture, Output Compare, or PWM CCP1<X:Y> PWM duty cycle 2 LSB’s (8 MSB’s located in CCPR1L) P1M<1:0> These PWM output configuration bits are available for Enhanced CCP (ECCP) modules only. They provide half-bridge or full-bridge output steering control. EECP Mode Select bits (CCP1M): These bits are the main control bits of the module. Here, the module is configure for one of the three possible modes (CAPTURE/COMPARE/PWM). Further configuration such as edge detection for capture modes, compare special events, and interrupt selection is also enabled here. These bits are also how the user accesses the module’s prescaler when using Capture mode PWM Output Configuration bits(P1M<1:0>): These bits are used to configure the PWM module as either a standard, single PWM output or make use of the Enhanced features on some PICmicros including the PIC16F887. These enhanced modes ease the interface of the module with bridge networks used in motor control designs. Duty Cycle Least Significant bits: these bits are concatenated with the 8 MSB’s located in CCPR1L to provide a 10-bit resolution. The CCP2CON register has many of the same features as CCP1CON. However, enhanced PWM configuration is not included as well as compare mode “toggle” on the CCPx pin.

140 Capture Mode TMR1H TMR1L CCPRxH CCPRxL Prescaler ÷1, 4, 16
CCPxIF in PIRx CCPx TMR1H TMR1L CCPRxH CCPRxL Edge Detect and Single Buffered System Clock (Fosc) In capture mode, two registers CCPRxH (Capture/Compare/PWM Result High) and CCPRxL (Capture/Compare/PWM Result Low) capture the value of the 16-bit TMR1 register at specified events on the CCPx pin on the PICmicro: The CCPx signal can be scaled to 1 of 3 scaling values. When the CCP module is turned off or the module is not in Capture mode, the prescaler is cleared. Any reset will clear the prescaler counter. There are a variety of user defined events that are configure in the CCP1M bits of the CCP1CON register: Every falling edge Every rising edge Every 4th rising edge Every 16th rising edge When an event is detected, the CCPxIF flag in PIRx is set. This flag as with other peripheral interrupts needs to be cleared in software. Furthermore, the current value in TMR1H:TMR1L registers is copied into the CCPRxH:CCPRxL registers. Note: This is a single buffered system which means: If another capture occurs before the value in the CCPRxH:CCPRxL is read, the old captured value is overwritten by the new captured value. Also, the Timer 1 bust be running in Timer mode or Synchronized Counter mode for the CCP module to use the capture feature In Asynchronous Counter Mode, the capture operation may not work P1M1 P1M0 CCP1X CCP1Y CCP1M3 CCP1M2 CCP1M1 CCP1M0 CCPxCON

141 Capture Mode TMR1H TMR1L CCPRxH CCPRxL Prescaler ÷1, 4, 16
CCPxIF in PIRx CCPx TMR1H TMR1L CCPRxH CCPRxL CCPxM3 CCPxM2 CCPxM1 CCPxM0 MODE 1 Capture every falling edge Capture every rising edge Capture every 4th rising edge Capture every 16th rising edge Edge Detect and Single Buffered System Clock (Fosc) In capture mode, two registers CCPRxH (Capture/Compare/PWM Result High) and CCPRxL (Capture/Compare/PWM Result Low) capture the value of the 16-bit TMR1 register at specified events on the CCPx pin on the PICmicro: The CCPx signal can be scaled to 1 of 3 scaling values. When the CCP module is turned off or the module is not in Capture mode, the prescaler is cleared. Any reset will clear the prescaler counter. There are a variety of user defined events that are configure in the CCP1M bits of the CCP1CON register: Every falling edge Every rising edge Every 4th rising edge Every 16th rising edge When an event is detected, the CCPxIF flag in PIRx is set. This flag as with other peripheral interrupts needs to be cleared in software. Furthermore, the current value in TMR1H:TMR1L registers is copied into the CCPRxH:CCPRxL registers. Note: This is a single buffered system which means: If another capture occurs before the value in the CCPRxH:CCPRxL is read, the old captured value is overwritten by the new captured value. Also, the Timer 1 bust be running in Timer mode or Synchronized Counter mode for the CCP module to use the capture feature In Asynchronous Counter Mode, the capture operation may not work P1M1 P1M0 CCP1X CCP1Y CCP1M3 CCP1M2 CCP1M1 CCP1M0 CCPxCON

142 Capture Initialization
TMR1H CCP1 Pin ;Turn off CCP module CCP1CON = 0x00; ;Make sure Timer1 is off TMR1ON = 0; ;Clear Timer1 registers TMR1H = 0x00; TMR1L = 0x00; ;Disable all interrupts for CCP CCP1IF = 0; CCP1IE = 0; ;Set CCP1 pin for input TRISC = 0; ;Set Capture for every 4th rising edge CCP1CON = b’ ’; ;Start Timer1 incrementing TMR1ON = 1; ;Test the interrupt flag for capture while (!CCP1IF); 1 1 1 1 TMR1L Current Timer1 Value TIMER1 INCREMENTING!! 4th 3rd 2nd 1st Rising Edge Detected!! CCPR1H CCPR1L Captured! PIR1 1 CCP1IF CCP1CON 1 1 T1CON 1 TMR1ON

143 Does TMR1H:TMR1L = CCPRxH:CCPRxL
Compare Mode TMR1H TMR1L COMPARATOR Does TMR1H:TMR1L = CCPRxH:CCPRxL ?? NO CCPRxH CCPRxL YES YES CCPxIF in PIRx OUTPUT LOGIC CCPx Compare Mode: In compare mode, the 16-bit CCPRx registers are constantly compared against the current values in the TMR1H and TMR1L registers. Once a match occurs, the user can define certain events as shown in the table above. There are few special points to be made about this module: Timer1 must be running in either Timer mode or Synchronized Counter mode. When the generate software interrupt mode is selected (CCPxM<3:0> bits), the CCPx is not controlled by the module anymore. Special Event Trigger: This mode will clear the Timer1 and start an ADC conversion if the ADC module is enabled. The CCP module will not control the CCPx pin in this mode. The Special Event Trigger output will trigger immediately upon a match between the TMR1H:TMR1L and CCPRxH:CCPRxL registers. Special Event Trigger CCP1CON P1M1 P1M0 CCP1X CCP1Y CCP1M3 CCP1M2 CCP1M1 CCP1M0

144 Does TMR1H:TMR1L = CCPRxH:CCPRxL
Compare Mode TMR1H TMR1L COMPARATOR Does TMR1H:TMR1L = CCPRxH:CCPRxL ?? NO CCPRxH CCPRxL YES YES CCPxIF in PIRx CCPxM3 CCPxM2 CCPxM1 CCPxM0 MODE 1 Set output on match (CCPxIF is set) Clear output on match (CCPxIF is set) Generate software interrupt on match (CCPxIF is set CCP1 pin unaffected) Trigger special event (CCPxIF is set, CCP1 resets TMR1 or TMR2 and starts an A/D conversion if enabled) OUTPUT LOGIC CCPx Compare Mode: In compare mode, the 16-bit CCPRx registers are constantly compared against the current values in the TMR1H and TMR1L registers. Once a match occurs, the user can define certain events as shown in the table above. There are few special points to be made about this module: Timer1 must be running in either Timer mode or Synchronized Counter mode. When the generate software interrupt mode is selected (CCPxM<3:0> bits), the CCPx is not controlled by the module anymore. Special Event Trigger: This mode will clear the Timer1 and start an ADC conversion if the ADC module is enabled. The CCP module will not control the CCPx pin in this mode. The Special Event Trigger output will trigger immediately upon a match between the TMR1H:TMR1L and CCPRxH:CCPRxL registers. Special Event Trigger P1M1 P1M0 CCP1X CCP1Y CCP1M3 CCP1M2 CCP1M1 CCP1M0

145 Compare Initialization
TMR1H //Turn off the CCP module CCPICON = 0x00; //Turn off Timer1 TMR1ON = 0; //Clear Timer1 result registers TMR1H = 0x00; TMR1L = 0x00; //Disable CCP1 interrupt and make sure //its flag is clear CCP1IE = 0; CCP1IF = 0; //Make CCP1 pin output TRISC2 = 0; //Initialize Compare to set output on match CCP1CON = 0b ; //Load compare value into CCPR1H:CCPR1L CCPR1H = 0b ; CCPR1L = 0x00; //Start Timer1 incrementing TMR1ON = 1; //Test CCP1IF for Timer1 match with CCPR1x While (!CCP1IF) TMR1L TMR1H:TMR1L = (CCPR1H:CCPR1L Value) TIMER1 INCREMENTING!! CCPR1H 1 CCPR1L T1CON 1 TMR1ON CCP1CON 1 PIR1 1 CCP1IF

146 PWM Mode Generates a Pulse-Width Modulated (PWM) signal on the CCP1 and CCP2 pins Duty cycle, period and resolution determined by the following registers Period Register PR2 Timer2 Control T2CON 2 Duty Cycle Registers CCPRxL 2 CCP Control Registers CCPxCON Description Register The PWM mode on the PIC16F887 provides a 10-bit resolution PWM output on the CCPx pin. This module enables user control over all aspects of the output waveform including period, pulse-width and duty cycle. Note that in PWM mode CCPRxH is a read only register.

147 PWM Block Diagram CCPR1L CCPR1H 10 10 COMPARATOR TMR2 = CCPR1H
Period 1 Period 2 DUTY CYCLE VALUE DUTY CYCLE VALUE CCPR1L CCP1<X:Y> 10 DOUBLE BUFFER CCPR1H LATCH 10 Period Start CCP1 Output Pin COMPARATOR TMR2 = CCPR1H TMR2 = CCPR1H 10 R S Latch TMR2 incrementing TMR2 Reset to 0’s TMR2 Reset to 0’s (1) 1 PWM period is specified by the PR2 register. When TMR2 is equal to PR2: TMR2 is cleared CCPx pin is set Duty Cycle value in CCPRxL is latched into CCPRxH The 8-bit CCPRxH is concatenated with a 2-bit internal latch to accommodate the 10-bit value from CCPRxL. The CCP1<X:Y> bits from CCPxCON concatenate with the 8-bit CCPRxL register to provide the duty cycle value. By latching the value in CCPRxL into CCPRxH, a double buffering of the duty cycle value is obtained. This provides a glitchless PWM operation. The CCPx pin will be cleared when the value in TMR2 matches the 10-bit duty cycle value now located in CCPRxH. Since TMR2 is an 8-bit register, two extra bits need to be provided for a 10-bit comparison with the duty cycle value. Therefore, TMR2 register is concatenated with either 2-bits from the internal system clock (Fosc) if the prescaler value is set to 1:1, or TMR2 is concatenated with 2 bits from the prescaler itself if any other prescale value is selected. 8 CCP1 pin TMR2 = PR2 COMPARATOR TMR2 = PR2 TMR2 = PR2 8 Note (1): TMR2 is concatenated with the 2-bit FOSC, or 2-bits from Prescaler to create 10-bit time base PR2

148 PWM Initialization 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 Prescaler bits
TMR2 //Turn off CCP1 pin by setting TRISC bit HIGH TRISC2 = 1; //Turn off Timer2 TMR2ON = 0; //Clear Timer2 TMR2 = 0x00; //Set up Period and Duty Cycle PR2 = 0b ; //Load a Period Value CCPR1L = 0b ; //Load a Duty Cycle Value //Configure CCP module for PWM // and LSB’s of Duty Cycle = b’10’ CCP1CON = 0b ; //Turn CCP1 pin back on (make it an output) TRISC2 = 0; //Start the PWM by turning on Timer2 //Configure Prescaler and Postscaler to 1:1) T2CON = 0b ; PR2 1 1 1 1 1 1 1 CCPR1L 1 1 1 1 1 CCP1CON 1 1 1 duty cycle LSBs DC1B<1:0> PWM Mode CCP1M <3:0> T2CON The output from the CCPx pin is turned off and interrupts are disabled Timer2 is cleared to zero and a value of 127 in binary is loaded into the period register to produce a 64uS period. This value was derived by the equation on the previous slides and is implemented using an 8MHz clock source which is the value of the internal oscillator on the PIC16F887 device. The duty cycle is implemented at 25% by loading a value of 31 in binary into CCPR1L. The lower 2 bits will be implemented in the CCP1CON register’s duty cycle LSB bits with a value of 2. When concatenated with the CCPR1L bits this will produce a value of 126 decimal which produces a pulse width lasting approximately 16uS or a 25% duty cycle. The CCP1CON register is configured to produce a single PWM output with P1A or CCP1 as active-high. The duty cycle LSB bits are also loaded at this time. The CCP1 pin is turned on by clearing the TRIS2 bit thereby enabling the PWM output The TMR2ON bit is set to begin Timer2 incrementing producing the PWM output. Note that by keeping the postscaler and prescaler bits cleared produces a 1:1 ratio of the Timer2 clock source. 1 Prescaler bits TOUTPS<3:0> Prescaler bits T2CKPS<1:0> TMR2ON

149 Pulse Width Modulation (PWM) Lab

150 LAB 5.0 – CCP1 PWM Tone `

151 PWM Lab Objectives Become familiar with the CCP module configuration and operation in PWM mode Gain additional exposure to Timer2 configuration Learn to integrate standard C Library into your code, “stdlib.h” for rand() function

152 PWM Lab Overview The PWM waveform is output on the CCP1 pin (RC2) that will emit random tones on the PICdem2 plus onboard buzzer. When the lab is completed, a random duty cycle at a period of 256*PreScale/(Fosc/4) will drive the buzzer

153 PWM Lab Overview Main Code Load PR2 value Set up RC2 as output pin
Load CCPR1L for 50% duty cycle Configure CCP as 8-bit PWM Turn on Timer2 w/ 1:16 pre scaler Assign CCPR1L a Random Value

154 PWM Lab Specifics Code for the lab is in \RTC\Lab5-CCP1 PWM
Complete the following sections Configure PORTC pin 2 ( CCP1) as an output Set CCP in PWM mode Clear CCP1X and CCP1Y (8-bit PWM) Configure Timer2 with 1:16 pre-scaler Use a rnd() function to load CCPR1L a random duty cycle

155 What you need to know The code to load PR2 (Timer2) and to set a 50% duty cycle has been provided. These values can be seen in the code The CCP1 pin is RC2 (Pin 2 of PORTC) on the PIC16F877 Registers needed to complete this lab are: TRISC T2CON CCP1CON

156 PWM Lab Solution

157 PWM Lab Questions Question:
Why didn’t we have to enable the interrupts for the PWM to work? Answer: PWM will run concurrently with the PICmicro MCU without slowing the processor down.

158 Output Compare Lab

159 Output Compare Lab Goals of the lab are to gain experience with the following: Setting up the CCP for Output Compare Configure the Special Event Flag to reset Timer1 Configure the CCP to generate an Interrupt on Timer1 overflow Using an Interrupt Vector to modify the interval between Interrupts

160 Compare Lab Overview This lab configures the CCP into output compare mode driven by Timer1 An Interrupt is used to change the sound of the buzzer During the Interrupt Service Routine (ISR): The RC2/CCP1 pin (connected to buzzer) is toggled The ISR period is reduced: The Compare Register (CCPR1L) is decremented The Timer1 count registers are reset The combination of a reduced period and the CCPR1L roll-over will cause the buzzer to emit a chirping sound

161 Configure CCP as Output Compare
Compare Lab Overview Interrupt Vector Main Program Save Context Configure CCP as Output Compare Clear IF Initialize Timer1 Toggle CCP Output Pin Initialize PORT C Drives Buzzer Decrement CCPR1L Turn on timer1 Reset Timer1 NOP RETURN TO MAIN

162 Compare Lab Specifics The code for the is in \RTC\Lab6-CCP1 OC
Complete the following sections: Configure the CCP as an Output Compare that sets the Special Event Flag and CCP1IF Configure Timer1 with a clock source of Fosc/4 and a pre-scaler of 1:8 Enable all Special Function Registers need to allow the CCP interrupt to occur

163 What you need to know The registers needed to complete this lab are
INTCON (Interrupt Control) T1CON (Timer 1 Control CCP1CON (CCP1 Control) PIE1 (Peripheral Interrupt Enable) The Interrupt Vector has been provided The Value of CCPR1L will “rollover” from 0 to 0xFF and continue to decrement

164 Compare Lab Solution

165 Compare Lab Question Question:
The PWM did not require an interrupt in order to work. Do we need an interrupt to operate in output compare mode? Answer: Not necessarily Peripherals always set their associated interrupt flag, so you have the choice of polling or directly responding to the interrupt. The choice is based on the need of your application.

166 Comparators

167 Comparator Overview Comparator Module:
Compares analog input voltage to a reference and outputs a digital result Vref Vin Vout Comp Analog Input (Vin) Reference Voltage (Vref) Output (Vout) The comparator module is an extremely important component when implementing mixed signals (analog and digital). It provides a means of interpreting various input voltage levels and output a digital response accordingly. The PIC16F887 device implements two comparators, C1 and C2. Comparator 2 has the added capability of being linked to Timer 1. A single comparator is shown along with the relationship between the analog input levels and the digital output. When the analog input signal increases beyond the boundary defined by the voltage reference, the comparator output will become a digital HIGH level Conversely, if the input signal decreases across the Vref voltage, the comparator will now output a digital LOW level.

168 Comparator Reference Voltage
Voltage Reference can be either: External from a device pin Internally generated with the Voltage Reference Module Provides 16 selectable voltages from 0 to 75% of VDD Some devices can also scale VREF+ and VREF- Some devices also have a fixed reference (0.6V) Independent of VDD VREF+ VDD VREN VREF- 8R R CVREF VROE To Comparators and ADC Module 4 VR<3:0> 15 VRSS = 1 VRSS = 0 VRR This module provides an internally generated voltage reference There are two configurable ranges of 16 voltages each The output voltage can be set to Vss (0V) with no power consumption This allows the comparator to detect a zero-crossing while not consuming additional current The comparator voltage reference is derived from Vdd (5V) This means that if any fluctuations occur to Vdd, the ratiometric voltage will fluctuate accordingly The fixed voltage reference is independent of Vdd.

169 Comparator Interrupts
An Interrupt occurs when the comparator output changes Some devices share one flag for both comparators Some devices have independent flags Must read the comparator output before clearing interrupt flags Outputs found in the comparator control register (CMCON or CMxCON0) Resets the output mismatch condition

170 Comparators and Sleep Mode
Comparators remain active in Sleep A Comparator output change will wake-up core After wake-up, the instruction following the SLEEP instruction or an Interrupt Service Routine (ISR) is executed To enable a wake-up from low-power SLEEP mode, the comparator must be enable prior to the SLEEP instruction. Associated interrupt enable bits in PIE2 and the peripheral interrupt enable bit in INTCON must also be set. Upon wake-up, the PIC will automatically execute the next instruction in the user’s code following the SLEEP instruction. However, by enabling the global interrupt enable bit in INTCON prior to SLEEP, the PIC will execute an interrupt service routine on wake-up. On any reset, all associated comparator resets are reset and both comparators and reference voltages are turned off.

171 Analog-to-Digital Converter (ADC)

172 ADC Overview Analog-to-Digital Converter Module
Converts analog input signal into an 8 or 10-bit binary value Selectable internal or external reference voltage Interrupt can be generated after conversion is completed The interrupt can wake the PICmicro from SLEEP The PIC16F887 implements a 10-bit ADC module with up to 14 input channels. This system provides a high resolution output from the module ensuring a very accurate binary representation of the input. The module’s reference voltages can be either internal from the Vdd source voltage for positive Vref and Vss for negative Vref or external user defined voltages. Refer to datasheet electrical specifications for minimum and maximum ranges. Interrupt flags are set upon completion of the conversion process. The ADC module can be used to wake the PIC from sleep mode. The ADIE enable must be set in PIE2 register as well as PEIE in the INTCON register. The processor will execute the next instruction immediately following the SLEEP instruction in program code. Alternately, by enabling the GIE bit in INTCON, an ISR code block could be executed instead. ADC Analog Input Signal ADC Output

173 ADC Control Registers The ADC implements two control registers
ADCON0 and ADCON1 Devices with > 8 analog inputs do not have same bits shown below ADC Control Register 0 (ADCON0) ADCS1 ADCS0 CHS2 CHS1 CHS0 GO/DONE ADON BIT FUNCTION ADCS<1:0> A/D Conversion Clock Select bits Use with ADCS2 in ADCON1 Register ADCON0 sets the fundamental components of the ADC peripheral ADCSx: The A/D Conversion Clock Select bits give the programmer the option of using a variety of clock frequencies. A newer addition is the ability to use the new factory calibrated internal RC oscillator available on the PIC itself. It should be noted that for a 10-bit conversion at least 11 clock cycles will be required to acquire an accurate binary representation of the analog signal. Therefore, care when selecting the clock source that an adequate sample frequency as related to the frequency of the input signal should be taken. The PIC16F887 offers 14 analog channels that can be used for A/D inputs. The ANSEL and ANSELH registers must be configured accordingly ensuring that the input is set for analog input. Setting the GO/DONE bit begins the A/D conversion. This bit can then be monitored in software as it will return to zero when the conversion process is finished. CHSx bits Analog Channel Select bits GO/DONE 1 = A/D Conversion in progress 0 = A/D Conversion is completed ADON Enables the ADC module

174 ADC Control Registers The ADC implements two control registers
ADCON0 and ADCON1 Devices with > 8 analog inputs do not have same bits shown below ADC Control Register 1 (ADCON1) ADFM ADCS2 PCFG3 PCFG2 PCFG1 PCFG0 BIT FUNCTION ADFM ADC Result Registers Format bit 1 = Right Justified, 0 = Left Justified Register ADCON0 sets the fundamental components of the ADC peripheral ADCSx: The A/D Conversion Clock Select bits give the programmer the option of using a variety of clock frequencies. A newer addition is the ability to use the new factory calibrated internal RC oscillator available on the PIC itself. It should be noted that for a 10-bit conversion at least 11 clock cycles will be required to acquire an accurate binary representation of the analog signal. Therefore, care when selecting the clock source that an adequate sample frequency as related to the frequency of the input signal should be taken. The PIC16F887 offers 14 analog channels that can be used for A/D inputs. The ANSEL and ANSELH registers must be configured accordingly ensuring that the input is set for analog input. Setting the GO/DONE bit begins the A/D conversion. This bit can then be monitored in software as it will return to zero when the conversion process is finished. ADCS2 A/D Conversion Clock Select bit Use with ADCS<1:0> in ADCON0 PCFG<3:0> Port Configuration Bits Configures I/O as analog or digital

175 ADC Result Registers 10 bit ADC result in is placed in two registers
ADRESH and ADRESL Left or Right Justified Determined by Format Select bit (ADFM) in ADCON1 register ADRESH ADRESL MSB LSB Left Justified (ADFM = 0) Since this is a 10-bit value, two result registers, A/D Result High and A/D Result Low, store the ADC value following conversion. The result registers can also be formatted in how the result is stored (justification) ADRESH ADRESL MSB LSB Right Justified (ADFM = 1)

176 Conversion clock scaler
ADC Module Diagram Conversion clock scaler Fosc VREF+ pin AN0 AN1 AN2 Start Conversion ADC AN3 Conversion Complete AN4 AN5 AN6 Left Justified ADRESH ADRESL AN7 Holding Capacitor Right Justified VREF- pin ADCON0 ADCS1 ADCS0 CHS2 CHS1 CHS0 GO/DONE ADON Vss ADCON1 ADFM ADCS2 PCFG3 PCFG2 PCFG1 PCFG0

177 Conversion clock scaler
ADC Module Diagram Vdd AN7 AN6 AN5 AN4 AN1 AN0 AN3 AN2 PCFG <3:0> Conversion clock scaler Port Config Bits Fosc VREF+ pin AN0 AN1 AN2 Start Conversion ADC AN3 Conversion Complete AN4 AN5 AN6 AN7 Left Justified ADRESH Holding Capacitor Right Justified ADRESL VREF- pin ADCON0 ADCS1 ADCS0 CHS2 CHS1 CHS0 1 GO/DONE ADON Vss ADCON1 1 ADFM ADCS2 PCFG3 PCFG2 PCFG1 PCFG0

178 Timing Considerations for ADC
When an A-to-D channel is selected time must be taken for the holding capacitor to charge All 10 bit conversions take 11 cycles to complete User must select the appropriate ADC clocking based on the system clock frequency The minimum time that the ADC can work is given in the electrical specifications. The user must the select the appropriate clock source to drive the adc within the specifications. The option for the clock source are set in ADCON0 register. Hold time for the charging capacitor must be set when a channel is selected.

179 Analog-to-Digital Conversion LAB

180 LAB 7.0 – ADC Module Voltmeter

181 ADC Lab This Lab will familiarize you with: Setting up the ADC module
Operating a peripheral from the “Main” program, not an interrupt vector Using the value read from one peripheral (ADC) and calculate the actual voltage then display it into the LCD.

182 ADC Lab Overview Main Program Configure Format and Analog Input
Select the Channel Input AN0 Select the ADC Conversion Clock Turn on ADC Continued on next page

183 ADC Lab Overview (cont.)
Continued from Previous Page Main Loop Start ADC ADC done? NO YES Get ADC value in ADRESH:ADRESL Convert to Actual Voltage and Display to LCD

184 ADC Lab Specifics Complete the following sections of code in the project \RTC\Lab7-ADC Voltmeter Configure the ADC to return a left justified value Set ADC Conversion Clock to FOSC/64 Turn on ADC unit Complete the code to start an ADC and wait for the conversion to finish in the main control loop

185 What you need to know ADCON1 and ADCON0 special function registers are used to complete this lab

186 ADC Solution

187 MASTER SYNCHRONOUS SERIAL PORT (MSSP) MODULE

188 We will cover I2C mode only
MSSP Overview The MSSP module can operate in one of two modes: SPI (Serial Peripheral Interface) 3 pins are used Serial Data Out (SDO) Serial Data In (SDI) Serial Clock (SCK) I2C (Inter-Integrated Circuit) Full Master mode Slave mode (with general address call) 2 pins are used Serial Clock (SCL) Serial Data (SDA) The MSSP Control Register (SSPCON) determines which mode you are in. The Master Synchronous Serial Port (MSSP) module is a serial interface useful for communicating with other peripheral or microcontroller devices. These peripheral devices may be Serial EEPROMs, shift registers, display drivers, A/D converters, etc. This module is very large and would be difficult to cover all aspects of the MSSP within the time boundaries of this course. Therefore, we will concentrate on the I2C used in Master mode. Inter-Integrated Circuit Communications (I2C) is a synchronous protocol meaning that data transfer between two device is accurately timed using a shared clock source. Other protocols, such as RS-232, are asynchronous meaning that it is up to each device to ensure that timing requirements are met. This requires a highly accurate oscillator that is stable over broad temperature ranges. These oscillators are more expensive and consume a lot more power than cheaper clock sources. This protocol utilizes only 2 buses: SCL: Serial Clock Signal Master generated clock that controls when data is sent and when it is received SDA: Serial Data Signal This bus transmits all of the data We will cover I2C mode only

189 I2C Conditions Conditions : START (S) STOP (P) ACKNOWLEDGE (A)
RESTART (R) NEGATIVE or NOT-ACKNOWLEDGE (N) SDA SDA released while SCL is still HIGH SDA pulled LOW while SCL is still HIGH SCL Recipient does not drive SDA LOW Stop condition quickly followed by a Start condition SDA goes LOW during 9th clock pulse of SCL A number of conditions are used to ensure that data is transmitted successfully between devices. It is not important to know the electrical characteristics of how each condition works as part of an introduction to MSSP. The PIC will automatically generates these conditions once a required bit is set or cleared. This will be discussed when the SSPCON2 register is examined later. These conditions include: START This condition is a signal to all devices connected to the bus that one device is about to transmit. As a result, all connected devices will listen as the transmission may be for one of them. STOP This signal tells all the devices connected that the bus is once again available. The bus is said to be “idle” when it is available for use by any device. At the point the STOP condition is received, the device that received the data will write to its registers (if not already processed). ACK A connected device will transmit this condition to confirm to the master that it has successfully received the data. RESTART Many times during the transmission, it may be necessary to transmit more information but a device reset is required. NACK This condition signals the master that it did not receive the transferred information.

190 External IC EEPROM Read
+5V SCL MASTER PIC SDA EEPROM GOTO ADDRESS WRITE MODE STOP DATA READ MODE BUSY BUSY LISTEN Presenter: This slide is fairly animation intense. However, we feel that for a peripheral such as this, it necessitates a visual walk through to help reinforce the concepts. The <click> located throughout the instructor’s notes indicates when to proceed to the next animation sequence. Pull-ups will be needed on the clock and data lines of the I2C, the values of which will depend on the desired speed. 2.2k is quite sufficient for the example but if you desire higher speed for later experimentation, consider using a 1k resistor for each pull-up. Let’s look at an example: The PIC micro, configured in Master mode, generates the clock for the serial clock line <click> <click> Next, the PIC initiates the START condition which is transmitted via the serial data bus. This places all slaves connected to the I2C buses in a listening mode The PIC then transmits an Address byte <click>. This identifies which slave device it wishes to communicate with and since the other devices aren’t identified they will see that the data bus is in use or busy. The address byte will also contain a bit that places the EEPROM into write mode to receive information from the PICmicro. <click> The EEPROM generates an ACKNOWLEDGE and transmits it to the PIC <click> Since we need to read a specific piece of data, the PIC now sends the address specifying the area in the EEPROM it wishes to retrieve the data. The address is transmitted along the data bus and the EEPROM points to the specific address. <click> Another ACKNOWLEDGE is generated by the EEPROM and is transmitted to inform the PIC EEPROM is at the required address. The PIC needs to next read the data. In order to accomplish this, it will need to place the EEPROM into a Read mode. <click> A RESTART is transmitted to the EEPROM which tells the device to get ready to receive further instructions. The RESTART command enables the PIC or any other transmitting device to maintain control of the data line. Otherwise, if a STOP condition were sent at this point, and another device wanted to use the line, the PIC would be forced to wait until the bus was “idle” and once again available. Also, the other devices connected to the I2C system are once again placed into a listening mode. This allows the PIC to maintain control of the data line and communicate with a different device. <click> The PIC sends the EEPROM’s address, calling it . Again, the other devices now see that the data line is busy and unavailable for them to transmit. The address also contains a bit that places the EEPROM into a READ mode. <click> The EEPROM generates another ACKNOWLEDGE and transmits to the PIC that it is ready to transmit the data at the previously specified address. <click> Data is now loaded into to a buffer on the EEPROM and then transmitted to the PIC. <click> The PIC has received the data and generates a NACK. Normally a NACK or ,Negative ACKNOWLEDGE, is generated to identify an error in transmission. However, according to this specific EEPROM’s datasheet, a NACK must be sent prior to concluding the communication. This informs the EEPROM to stop transmitting data. Otherwise, if an ACK were sent at this point, the EEPROM would send the next byte of data. Again, the datasheet for individual IC peripherals you may use will specify any special communication protocols required. The NACK is transmitted and the EEPROM immediately stops data transmission. Finally, to return the data line to an idle state and make it available to other devices, the PIC generates the STOP condition. <click> Once transmitted, the PIC relinquishes control and the communication is terminated. LISTEN LISTEN EEPROM MEMORY ADDRESS SLAVES ACK RESTART START STOP SLAVE ADDRESS ACK DATA NACK

191 MSSP Control Registers (I2C mode)
1 of 3: MSSP Status Register (SSPSTAT) SMP CKE D/A P S R/W UA BF CONTROL BITS DETECTION BITS (FLAGS) BIT FUNCTION SMP Slew Rate Control bit CKE Not used in I2C mode D/A Last byte Rx/Tx was data or address Other registers are used in the MSSP/ I2C module. However, for an introduction to this peripheral, discussing the following registers will be sufficient. The datasheet for the individual device you are using should be referred to for a more in depth look at the MSSP and the available registers for the module. The SSPSTAT has 1 control bit SMP: Used for sampling purposes when MSSP is configured for SPI mode. In I2C mode, this bit enables or disables a slew rate control process. If the I2C clock is running at 400kbps, this could lead to Electro-Magnetic Interference that could potentially affect external devices or even other modules on the PIC. When enabled, the SCL clock signal transition is smoothed thereby reducing the amount of noise. SSPSTAT register is used mainly as a reference for events that are associated with the I2C module. Will set certain bits high or low depending on certain events. D/A bit indicates whether the last transmitted or received byte was data or an address. Start/Stop condition detected R/W bit is used in two ways. If the I2C is configured as a slave, this bit will indicate if the data in the buffer was used Read or was Written by the PIC. In master mode, this bit indicates if transmission is still in progress. BF indicates if the buffer, SSPBUF, is full. Once the buffer is full, the data can be safely transmitted to the system or processed by the PIC accurately. P Stop Condition Detected S Start Condition Detected R/W Slave :READ/WRITE or Master = transmit in progress UA Address needs to be updated BF The SSPBUF register is full

192 MSSP Control Registers (I2C mode)
1 of 3: MSSP Status Register (SSPSTAT) SMP CKE D/A P S R/W UA BF CONTROL BITS DETECTION BITS (FLAGS) BIT FUNCTION SMP Slew Rate Control bit CKE Not used in I2C mode D/A Last byte Rx/Tx was data or address Other registers are used in the MSSP/ I2C module. However, for an introduction to this peripheral, discussing the following registers will be sufficient. The datasheet for the individual device you are using should be referred to for a more in depth look at the MSSP and the available registers for the module. The SSPSTAT has 1 control bit SMP: Used for sampling purposes when MSSP is configured for SPI mode. In I2C mode, this bit enables or disables a slew rate control process. If the I2C clock is running at 400kbps, this could lead to Electro-Magnetic Interference that could potentially affect external devices or even other modules on the PIC. When enabled, the SCL clock signal transition is smoothed thereby reducing the amount of noise. SSPSTAT register is used mainly as a reference for events that are associated with the I2C module. Will set certain bits high or low depending on certain events. D/A bit indicates whether the last transmitted or received byte was data or an address. Start/Stop condition detected R/W bit is used in two ways. If the I2C is configured as a slave, this bit will indicate if the data in the buffer was used Read or was Written by the PIC. In master mode, this bit indicates if transmission is still in progress. BF indicates if the buffer, SSPBUF, is full. Once the buffer is full, the data can be safely transmitted to the system or processed by the PIC accurately. P Stop Condition Detected S Start Condition Detected R/W Slave :READ/WRITE or Master = transmit in progress UA Address needs to be updated BF The SSPBUF register is full

193 MSSP Control Registers (I2C mode)
2 of 3: MSSP Control Register 1 (SSPCON) WCOL SSPOV SSPEN CKP SSPM3 SSPM2 SSPM1 SSPM0 CONTROL BITS DETECTION BITS (FLAGS) BIT FUNCTION WCOL Write Collision Detected SSPOV A write to the SSPBUF before previous value processed SSPEN Enables MSSP module CKP Enables clock The MSSP control register contain 2 Error Detection bits: WCOL: Indicates when a Write Collision has occurred. This condition exists when a device has tried to write to the data bus while it is in use by another device. SSPOV: indicates that a write to SSPBUF buffer has occurred before the previous data was processed SSPCON also contains the control bits SSPEN and the SSPMx mode select bits SSPEN: simply enables the MSSP module CKP: Enables the SCL clock While the SSPM<3:0> bit configure the mode the module will function in. These modes include: Master mode, Slave Mode, Multiple Master Mode and so on…Some modes apply specifically to the I2C while others only to SPI. SSPM3 Mode Select Bit Mode Select bits SSPM2 SSPM1 SSPM0

194 MSSP Control Registers (I2C mode)
SSPM3 SSPM2 SSPM1 SSPM0 Mode SPI Master mode, clock = FOSC/4 1 SPI Master mode, clock = FOSC/16 SPI Master mode, clock = FOSC/64 SPI Master mode, clock = TMR2 output/2 SPI Slave mode, clock = SCK pin, SS pin control enabled SPI Slave mode, clock = SCK pin, SS pin control disabled, SS can be used as I/O pin I2C Slave mode, 7-bit address I2C Slave mode, 10-bit address I2C Master mode, clock = FOSC / (4 * (SSPADD+1)) Reserved I2C firmware controlled Master mode (Slave idle) I2C Slave mode, 7-bit address with Start and Stop bit interrupts enabled I2C Slave mode, 10-bit address with Start and Stop bit interrupts enabled 2 of 3: MSSP Control Register 1 (SSPCON) WCOL SSPOV SSPEN CKP SSPM3 SSPM2 SSPM1 SSPM0 CONTROL BITS DETECTION BITS (FLAGS) BIT FUNCTION WCOL Write Collision Detected SSPOV A write to the SSPBUF before previous value processed SSPEN Enables MSSP module CKP Enables clock The MSSP control register contain 2 Error Detection bits: WCOL: Indicates when a Write Collision has occurred. This condition exists when a device has tried to write to the data bus while it is in use by another device. SSPOV: indicates that a write to SSPBUF buffer has occurred before the previous data was processed SSPCON also contains the control bits SSPEN and the SSPMx mode select bits SSPEN: simply enables the MSSP module CKP: Enables the SCL clock While the SSPM<3:0> bit configure the mode the module will function in. These modes include: Master mode, Slave Mode, Multiple Master Mode and so on…Some modes apply specifically to the I2C while others only to SPI. SSPM3 Mode Select Bit Mode Select bits SSPM2 SSPM1 SSPM0

195 MSSP Control Registers (I2C mode)
3 of 3: MSSP Control Register 2 (SSPCON2) GCEN ACKSTAT ACKDT ACKEN RCEN PEN RSEN SEN CONTROL BITS DETECTION BITS (FLAGS) BIT FUNCTION GCEN Generates an interrupt when a call is received (slave mode) ACKSTAT 0 = Acknowledge received from slave (transmit mode) ACKDT 0 = ACK 1 = NACK (receive mode) ACKEN Initiate ACK/NACK condition (Transmits ACKDT bit) The SSPCON 2 register contains various bits specific to communication with the PIC in I2C mode. The PIC will automatically generate the required condition depending on the bit set. This frees the user from needing to know all the required electrical characteristics of each condition. GCEN: Allows an interrupt to be generated when an I2C “General Call Address” is generated. This feature is almost never used. It is provided on the MSSP module to make it backward compatible with older and/or slower systems. ACKSTAT: Is used when the PIC is in transmit mode. The receiving device will transmit an ACK thereby clearing this bit. Otherwise, the NACK is assumed. ACKDT/ACKEN: This ACKDT bit is set to indicate a NACK from the PIC or cleared for an ACK. The condition is not initiated until the ACKEN bit is set and the response transmitted. RCEN: Will place the PIC into receive mode PEN: Once this bit is enabled, the PIC will initiate a STOP condition RSEN: This bit initiates the RESTART condition when enabled SEN: Initiates the START condition RCEN Enables receive mode PEN Initiates a STOP condition RSEN Initiates a RESTART condition SEN Initates a START condition SEN Initiates a START condition

196 MSSP Control Registers (I2C mode)
3 of 3: MSSP Control Register 2 (SSPCON2) GCEN ACKSTAT ACKDT ACKEN RCEN PEN RSEN SEN CONTROL BITS DETECTION BITS (FLAGS) BIT FUNCTION GCEN Generates an interrupt when a call is received (slave mode) ACKSTAT 0 = Acknowledge received from slave (transmit mode) ACKDT 0 = ACK 1 = NACK (receive mode) ACKEN Initiate ACK/NACK condition (Transmits ACKDT bit) The SSPCON 2 register contains various bits specific to communication with the PIC in I2C mode. The PIC will automatically generate the required condition depending on the bit set. This frees the user from needing to know all the required electrical characteristics of each condition. GCEN: Allows an interrupt to be generated when an I2C “General Call Address” is generated. This feature is almost never used. It is provided on the MSSP module to make it backward compatible with older and/or slower systems. ACKSTAT: Is used when the PIC is in transmit mode. The receiving device will transmit an ACK thereby clearing this bit. Otherwise, the NACK is assumed. ACKDT/ACKEN: This ACKDT bit is set to indicate a NACK from the PIC or cleared for an ACK. The condition is not initiated until the ACKEN bit is set and the response transmitted. RCEN: Will place the PIC into receive mode PEN: Once this bit is enabled, the PIC will initiate a STOP condition RSEN: This bit initiates the RESTART condition when enabled SEN: Initiates the START condition RCEN Enables receive mode PEN Initiates a STOP condition RSEN Initiates a RESTART condition SEN Initates a START condition SEN Initiates a START condition

197 Tx/Rx Buffer (SSPBUF) Buffer register containing Tx and Rx data
SSPBUF interfaces to a shift register (SSPSR) for shifting data in or out When full, the Buffer Full (BF) bit in the SSPSTAT register is set Any write to the SSPBUF register during Tx/Rx of data will be ignored, and the write collision detect bit (WCOL) of the SSPCON register will be set The SSPBUF register is simply an 8-bit register to hold the data that will be transmitted by the PIC or the data that has been received by the PIC.

198 I2C Address Register (SSPADD)
Slave mode: Contains the slave address of the PIC Compared against the received value Master mode: Used to calculate the clock speed (BAUD rate) of the I2C system. The SSPADD has two functions depending on which mode the PIC MSSP module is in. If the MSSP is configured as a Slave, the SSPADD the holds the user defined address of the PIC. If the PIC receives an address byte from the I2C Master, the received value is compared to the value in SSPADD. If there is a match, and the GCEN bit in SSPCON2 is set, an interrupt flag (SSPIF) will be set in the PIR1 register. This register can also be used in conjunction with a masking register that allows the user to place some of the bits into a “Don’t Care” state. This allows the PIC to receive data along with another device whose address may be similar but not the same as the PIC’s. (for more information refer to the datasheet) In Master mode, the SSPADD register takes on a completely different role. Since the PIC is now in charge of generating the SCL clock signal, the SSPADD is used in the above equation to determine it’s frequency or BAUD rate. BAUD RATE = *NOTE: FOSC is the frequency of the oscillator not the Instruction Clock TCY

199 MSSP Interrupts The MSSP interrupt flag (SSPIF) is set in the PIR1 register with the following events: START condition STOP condition Tx or Rx complete Acknowledge transmit RESTART condition As with any interrupt, the peripheral enable bit (PEIE) and the global interrupt enable bit (GIE) in the INTCON register must be set as well as the SSPIE bit in the PIE1 register. The interrupts can then be prioritized with polling as you would with any other interrupt.

200 MSSP I2C LAB

201 LAB 8.0 – Temp Sensor via MSSP I2C

202 Temp Sensor I2C Lab This Lab will familiarize you with:
Setting up the MSSP I2C module Understand and use an I2C library. Learn how to communicate to a TC74 Temp Sensor via I2C interface. Display the Temperature on LCD

203 Temp Sensor Lab Overview
Main Program Initialize I2C Module Send an I2C Read Byte Sequence with RTR command to TC74 Send an I2C Receive Byte to Read the Temperature on TC74 Display Temp on LCD and LED

204 LAB 8.0 – Temp Sensor via MSSP I2C

205 LAB 8.0 – Temp Sensor via MSSP I2C

206 LAB 9.0 – Saving on EEPROM via MSSP I2C

207 EEPROM I2C Lab This Lab will familiarize you with:
Setting up the MSSP I2C module Understand and use an I2C library. Learn how to write/read a byte on the EEPROM via I2C interface. Verify that the data was not erased at power down.

208 EEPROM I2C Lab Overview Main Program *Bypass on next power-up
Initialize I2C Module Send an I2C Write Byte Sequence on 0x0101 address of the EEPROM *Bypass on next power-up Send an I2C Read Byte Sequence on 0x0101 address of the EEPROM Display Data Byte on LCD Power Down

209 LAB 9.0 – Saving on EEPROM via MSSP I2C

210 LAB 9.0 – Saving on EEPROM via MSSP I2C

211 ADDRESSABLE Universal Synchronous Asynchronous Receiver Transmitter (AUSART)

212 AUSART Overview Serial I/O communications peripheral Main Functions:
Sometimes called Serial Communications Interface (SCI) Main Functions: Can be synchronous or asynchronous Can receive and transmit Full-duplex asynchronous transmit and receive Half-duplex synchronous master and slave Most common use RS-232 communications to a PC serial port Needs driver for RS-232 level shifter Enhanced (EUSART) features allow interface with a Local Interconnect Network (LIN) bus system Synchronous operation implements a clock and data line while asynchronous does not implement the clock line and each PICmicro must ensure accurate timing of processes. Full duplex operation means that both transmission and reception can occur at the same time while half duplex means that transmission and reception can only occur one at a time. Full duplex operation is made possible since there is no clock signal in asynchronous operation and one pin can be used for transmission while the other is used for reception. Full duplex mode is useful for communications with peripheral systems such as CRT terminals and personal computers. Half duplex synchronous mode is intended for communications with peripheral devices such ADC or DAC integrated circuits, serial EEPROMs or other microcontrollers. These devices typically do not have internal clocks for baud rate generation and require the external clock signal provided by a master synchronous device. Transmission and reception can be independently enabled. However, when the serial port is enabled, the EUSART will control both pins and one cannot be used for general purpose I/O while the other is used for transmission or reception. EUSART will most commonly be used in asynchronous mode with the RS-232 protocol. The PIC does not transmit or receive in the RS-232 voltage levels, therefore, a driver will need to be implemented between the PIC and the receiving/transmitting device. More on this later in the presentation. The Enhanced USART implemented on the PIC16F887 contains features making it ideally suited for use in LIN bus systems: Automatic detection and calibration of the baud rate Wake-up on Break reception 13-bit Break character transmit This presentation will focus primarily on Asynchronous EUSART operation as it relates to the RS-232 format

213 AUSART Registers Baud rate generator registers
SPBRG (8 bit for AUSART) SPBRG and SPBRGH (16 bit for EUSART) Transmit status and control TXSTA Receive status and control RCSTA Transmit data register TXREG Receive data register RCREG Baud rate registers are used to set the baud rate for the system. The rate at which data is transmitted or received must always be set using these registers unless the USART is being used in a synchronous slave mode. TXSTA and RCSTA are used to control transmission and reception. There are some overlapping functions requiring both registers to always be used. The TXREG and RCREG registers are used to write data to be transmitted and read the received data.

214 TXSTA Register CSRC TX9 TXEN SYNC SENB BRGH TRMT TX9D Bit Function
Clock Source Select 1 = Master Mode (clock generated internally from BRG) 0 = Slave Mode (clock from external source) TX9 Ninth bit transmission enable TXEN Transmit Enable bit, 1 = Tx enabled, 0 = Tx disabled SYNC AUSART Mode , 1 = Synchronous Mode, 0 = Asynchronous Mode SENB For EUSART only 1 = Send sync break character bit 0 = Sync break transmission is completed The TXSTA register is used to control transmission CSRC: is used for synchronous mode only to select either an internally configured or external clock source TX9: Ninth bit transmission enable transmits the value at bit position TX9D in addition to the eight bits in the TXREG. This bit can be used for parity checking TXEN: enables transmission. If set, writes to the TXREG register will cause a transmission to be initiated (if the serial port has been enabled) SYNC: this bit is cleared to enable asynchronous operation SENB: Used to send special Break character sequences that are required by the LIN bus standard. For more information visit the Microchip website and search for LIN. BRGH Selects between HIGH or LOW speed Baud rate options. More on this later in the presentation TRMT: This bit indicates whether or not there is data in the transmit shift register. Data written into the TXREG is loaded into the transmit shift register when it is empty. The transmit shift register is internal and is not readable. BRGH Baud Rate Select, 1 = High Speed, 0 = Low Speed TRMT Transmit Shift Register (TSR) status 1 = TSR empty, 0 = TSR is full TX9D Ninth bit of transmit data

215 RCSTA Register SPEN RX9 SREN CREN ADDEN FERR OERR RX9D Bit Function
Serial Port Enable 1 = Serial port enabled (configures RX/DT and TX/CK pins as serial port pins) 0 = Serial port disabled RX9 1 = Enable 9-bit data reception, 0 = 8-bit data SREN Synchronous mode (Master), 1 = enable single Rx, 0 = disable single Rx CREN Continuous Receive Enable, 1 = enable, 0 = disable ADDEN Address Detect Enable bit 1 = enable (enable interrupt and load the Rx buffer when RSR<9> is set) 0 = disable and use 9th bit for parity RCSTA is used to control reception of data. However, it does have other functions as well. SPEN: enables the entire serial port for both transmission and reception also configures both port pins associated with the EUSART to their EUSART functions. RX9: enables the PICmicro for nine bit reception. This ninth bit will be read from the RX9D bit. SREN: enables single receive. This will result in only as many clock cycles generated as there are data bits in a single character. Automatically cleared at the completion of one character not used in asynchronous mode CREN: this bit enables continuous reception. When set, clocks are continuously generated until CREN is cleared. CREN takes precedence over the SREN bit ADDEN: enables address detection in nine bit asynchronous mode and is only available on PICmicros with addressable EUSARTs. When set, only data that has the ninth data bit set will be received FERR: indicates a framing error. This occurs when the stop bit was not detected. These errors are often a result of incorrect baud rates. OERR: indicates an overrun error. This occurs when a complete byte was received when the FIFO was still full with the two previous bytes. The new data will be lost and no further data will be received until the CREN bit has been cleared and set once again by software. FERR 1 = framing error occurred (Stop bit not detected) OERR 1 = Overrun error occurred (FIFO was still full when other data was loaded) RX9D Ninth bit of received data

216 Transmit Block Diagram
DATA BUS TXIE TXREG Interrupt TXIF Set TXIF Clear TXIF MSB LSB TXEN Pin Buffer and Control TX/DT pin Transmit Shift Register (TSR) SPEN Enables Serial Port Baud Rate Generator The TXREG is the transmit buffer which receives its data directly from the data bus. Writing to this buffer initiates the transmission process. Transmit Interrupt Flag: Located in PIR1 register, the TXIF flag is set when the EUSART transmitter is enabled AND there is no data in the TXREG. This flag is only cleared when the TSR is busy with a character and a new character is queued in the TXREG. The TXIF is not cleared immediately, it clears in the second instruction cycle following the write execution. Polling this flag immediately following the TXREG write will return invalid results. Transfer of the data from TXREG into the will only occur if all the data bits in the Transmit Shift Register from the previous transmission data have been shifted out. Otherwise, the data will be held in the TXREG. Transfer of data from the TXREG into the TSR will occur in one instruction clock cycle (Tcy). Transmission of the Start bit, data bits and Stop bit sequence commences immediately following the transfer of the data to the TSR from TXREG. TSR Status: The TSR register is not available to the user and is not mapped into memory. Status of this register is indicated by the TRMT bit in TXSTA. This is a read only bit. This bit will remain clear until all bits within the TSR register have been shifted out and then it will be set. The user may poll this bit to determine the TSR status. 9-bit Characters: The TX9D in TXSTA must be written before the 8 LSBs are written into TXREG. All 9 bits are transferred simultaneously into the TSR shift register immediately after TXREG is written. TRMT TX9D TX9 Set TRMT bit Indicates shift register is empty Ninth data bit Clear TMRT bit TSR has data in it

217 Receive Block Diagram RX/DT pin Data Bus Enable Serial Port
SPEN Receive Shift Register (RSR) RX/DT pin Pin Buffer and Control Data Recovery STOP STOP START START RX9 Baud Rate Generator FIFO Set RCIF flag Clear RCIF flag RCREG The asynchronous mode shown in the above slide would typically be used for RS-232 systems. The data recovery block is a high-speed shifter that operates at 16 times the baud rate. Once all 8 or 9 bits have been shifted into the RSR, data is immediately transferred into a FIFO register. This register provides a buffer that allows reception of two characters (complete 8 or 9-bit data) with the beginning of a third before the EUSART receiver need to be serviced. Data can only be accessed from the RCREG register. The Receive interrupt flag (RCIF) in PIR1 is set whenever there is an unread character inside the FIFO register. Error bits: Framing Error (FERR) The framing bit located in the RCSTA register represents the status of the unread character in the FIFO register. This means that the FERR bit must be read before reading the RCREG!! The FERR bit indicates that a STOP bit was not received at the expected time. This error bit does not need to be cleared but can be forced clear by resetting the SPEN (Serial Port Enable) bit in RCSTA. Receive Overrun Error: An overrun error (OERR) will set the OERR bit in the RCSTA register. This error indicates that a third character has been received in its entirety before the FIFO is accessed. As previously mentioned, the FIFO buffer can hold two characters in their entirety while a third character begins to be accessed but is not completely received. This error is cleared by either clearing the CREN (Constant Receive Enable) bit in RCSTA or by clearing the SPEN (Serial Port Enable) in the RCSTA register. RCIE RCIF RX9D Interrupt Data Bus

218 USART LAB

219 Lab 10: USART

220 USART Lab This Lab will familiarize you with:
Setting up the USART module in asynchronous transmit configuration Learn how to transmit message to the PC HyperTerminal

221 UART Lab Overview Main Program
Assign UART SPBRG register a baud rate Set the mode and enable the port. SPEN and SYNC Enable the transmission. TXEN Load the Data on TXREG and wait for transmission to complete by pooling on TXIF and TRMT

222 Lab 10: USART

223 Lab 10: USART Open hyperterminal and start a new connection
Start Menu>Programs>Accessories>Communications

224 Lab 10: USART Connect to COMx you are using

225 Lab 10: USART Configure the properties below

226 Lab 10: USART The MCU will send the message continuously

227 PIC16 Peripherals (201 PRC) Wrap Up

228 Peripherals Class Wrap-up
We created a C-project in MPLAB that used HITECH’s “PICC Lite” compiler We learned the following peripherals: I/O ports Interrupt structure and processing Timers (Timer0, Timer1, Timer2) CCP Module ( Output Compare, Input Capture, PWM) Comparators and Analog-to-Digital Converters Voltage Reference AUSART – Serial Port I2C using the MSSP module

229 Resources Free software downloads Microchip’s Product Selector Tools:
Academic Program Homepage Free software downloads Microchip’s Product Selector Tools: Order tools: DON’T FORGET, ACADEMICS RECEIVE A 25% DISCOUNT!! Mid-Range Specific WebPages:

230 Thank You!! Please complete the review form

231 Trademarks The Microchip name and logo, the Microchip logo, Accuron, dsPIC, KeeLoq, microID, MPLAB, PIC, PICmicro, PICSTART, PRO MATE, PowerSmart, rfPIC and SmartShunt are registered trademarks of Microchip Technology Incorporated in the U.S.A. and other countries. AmpLab, FilterLab, Migratable Memory, MXDEV, MXLAB, SEEVAL, SmartSensor and The Embedded Control Solutions Company are registered trademarks of Microchip Technology Incorporated in the U.S.A. Analog-for-the-Digital Age, Application Maestro, dsPICDEM, dsPICDEM.net, dsPICworks, ECAN, ECONOMONITOR, FanSense, FlexROM, fuzzyLAB, In- Circuit Serial Programming, ICSP, ICEPIC, Linear Active Thermistor, Mindi, MiWi, MPASM, MPLIB, MPLINK, MPSIM, PICkit, PICDEM, PICDEM.net, PICLAB, PICtail, PowerCal, PowerInfo, PowerMate, PowerTool, REAL ICE, rfLAB, rfPICDEM, Select Mode, Smart Serial, SmartTel, Total Endurance, UNI/O, WiperLock and ZENA are trademarks of Microchip Technology Incorporated in the U.S.A. and other countries. SQTP is a service mark of Microchip Technology Incorporated in the U.S.A. All other trademarks mentioned herein are property of their respective companies.


Download ppt "Objectives At the end of this class you will:"

Similar presentations


Ads by Google