13.07.2015 Views

Peripheral Interface Controller

Peripheral Interface Controller

Peripheral Interface Controller

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

www.microchip.com


10k1 _____MCLROSC1/CLKIN4MHz Crystal22pF13150150OSC2/CLKOUTPIC16F877A141211EPT3016Vss Vdd33RB00.1uF34RB122pF10uF78051N4001+9VProgram code for the project:void main(){TRISB = 0;PORTB = 0;while(1){PORTB.F0 = ~PORTB.F0;PORTB.F1 = ~PORTB.F0;delay_ms(500);}}The Flashing LED Project Schematic


Program code for the project:void main(){unsigned short i = 0; //Variable for counting 0 to 60char text[5];//Variable to hold string value of iTRISB = 0;//Set PORTB as outputLcd_Init(&PORTB);//Initialize LCD connected to PORTBLcd_Cmd(Lcd_CLEAR); //Clear displayLcd_Cmd(Lcd_CURSOR_OFF);//Turn off LCD cursorLcd_Out(1, 1, "Counts to 60:");//Message at first linewhile(1){ShortToStr(i, text);//Convert number i to stringLcd_Out(2,1,&text[2]); //Print string at line 2i++;//Increment iif(i>60) i = 0; //Reset i to 0 if more than 60}}delay_ms(1000);//Delay 1 second


void interrupt(){time_out = 1;INTCON.TMR0IF = 0; //Reset TMR0 interrupt flagTMR0 = 133;}void task1(){if(count==250){ShortToStr(number, text); //Convert number to stringLcd_Out(2,1,&text[2]); //Print string at line 2number++;//Increment numberif(number>60) number = 0; //Reset number to 0 if more than 60}}void task2(){count++;if(count>250) count = 1;}void main(){setup();while(1){time_out = 0;task1();task2();while(!time_out);}


unsigned count, T, rate;unsigned short n, previous;char text[6];void setup(){TRISB = 0;TRISD = 1;PORTD = 0;OPTION_REG = 0b10000100;//and prescaler 32Lcd_Init(&PORTB);Lcd_Cmd(Lcd_CLEAR);Lcd_Cmd(Lcd_CURSOR_OFF);Lcd_Out(1, 1, "Interval:");Lcd_out(2, 1, "Rate:");Lcd_Out(1, 13, "ms");Lcd_out(2, 9, "/min");TMR0 = 133;INTCON = 0b10100000;n = 0;t = 0;}void interrupt(){count++;INTCON.TMR0IF = 0;TMR0 = 133;}//No pull-up at PortB, TMR0 source internal//Initialize LCD connected to PORTB//Clear display//Turn off LCD cursor//Global interrupt & TMR0 interrupt enabled,//Reset TMR0 interrupt flagvoid task1(){previous = 0;n++;if(n > 2) n = 1;}void task2(){if(n == 1){count = 0;}if(n == 2){T = count*4;WordToStr(T, text);Lcd_Out(1,10,&text[2]);}}void main(){setup();while(1){if (Button(&PORTD, 0, 1, 0)) previous = 1;if (previous && Button(&PORTD, 0, 1, 1)){task1();task2();}}}


NOTES


SK40CUIC-SUIC00B


User-Defined Functions• ANSI C (Standard C Language)• Assembly Language Code


Tutorial 1LED Blink


Tutorial 1LED BlinkUsingMPLAB


Using the build infunction libraryfunction (.h)


Main CodeDONE


Tutorial 1LED BlinkUsingMicroC


Default settingPIC ConfigMCLR means Master Clear, and functions as the Reset pin on the PICmicro, causing the PIC to be held in a reset state as long as MCLR is at 0volts. When MCLR is connect to VDD instead, then the PIC begins runningby executing the first instruction in program memory.


Sample code available in the MicroC tutorial it self.void main() {PORTB = 0;TRISB = 0;while(1) {PORTB = ~PORTB;Delay_ms(1000);}}// Initialize PORTB// Configure PORTB as output// toggle PORTB// one second delayMMUvoid main(){TRISB = 0;PORTB = 0;while(1){PORTB.F0 = ~PORTB.F0;PORTB.F1 = ~PORTB.F0;delay_ms(500);}}VideoYoutubevoid main(){TRISB = 0X00;while(1){PORTB = 0XFF;Delay_ms(500);PORTB = 0x00;Delay_ms(500);}}


LCD <strong>Interface</strong>


LCD Interfacing and Programming• A 16 x 2 (16 characters, 2 lines) alphanumericLCD is used to display settings and status tothe user.• The Hitachi HD44780 LCD controller is thestandard for such LCDs.• LCDs based on HD44780 has 3 control pinsand 8 data pins for 8-bit parallel data transfer.TCC 2007 26


Hitachi HD44780-based LCD module pin outCont…Pin Symbol Level I/O Description1 V SS- - Power supply (GND)2 V CC- - Power supply (+5V)3 V EE- - Contrast adjust4 RS 0/1 I Register Select:RS = 0: Instruction RegisterRS = 1: Data Register5 R/W 0/1 I Read/Write:R/W = 0: Write to LCD moduleR/W = 1: Read from LCD module6 EN 1, 10 I Enable signal7 DB0 0/1 I/O Data bus line 0 (LSB)8 DB1 0/1 I/O Data bus line 19 DB2 0/1 I/O Data bus line 210 DB3 0/1 I/O Data bus line 311 DB4 0/1 I/O Data bus line 412 DB5 0/1 I/O Data bus line 513 DB6 0/1 I/O Data bus line 614 DB7 0/1 I/O Data bus line 7 (MSB)TCC 2007 27


Cont…2 additional lines for LCD backlight: Pin 15 for +5V and Pin 26 for ground.VCC and VSS are the +5V voltage supply terminal and ground terminal of the LCD.VEE is the voltage supply terminal for controlling the LCD contrast.V CC+5VV EEV SSTCC 2007 28


Cont… RS is a control pin used to select the instructionregister or data register inside the LCD. The instruction register is selected when RS = 0 forsending of instructions such as clear display, cursor athome, and etc to the LCD. The data register is selected if RS = 1, this allows theuser to send data to be displayed on the LCD throughthe 8-bit data bus.TCC 2007 29


Cont… R/W is a control pin used to select the readoperation or write operation of the LCD. If R/W = 1, the LCD will output data to be readby the user on the 8-bit data bus. The LCD will read data/instruction from 8-bitdata bus if R/W = 0.TCC 2007 30


Cont…EN is a control pin used to notify the LCD when sending it data.To send data to the LCD, EN must be 0 when attempting to set the othertwo control pins (RS and R/W) or to put data on the 8-bit data bus.Once both of the control and data signals are ready, bring EN to 1 and waitfor the minimum amount of time required by the LCD datasheet, and endby bringing EN to 0 again.DB0DB7DataENt DSWt HR/Wt AS t PWHt AHRSt PWH : Enable pulse width = 220ns (min.)t DSW : Data setup time = 60ns (min.)t H : Data hold time = 10ns (min.)t AS : R/W and RS setup time = 40ns (min.)t AH : R/W and RS hold time = 10ns (min.)TCC 2007 31


Cont…• DB0 DB8 are bi-directional 8-bit data pins used to senddata/instruction to the LCD or to read the contents of the LCDinternal registers.• To display alphanumerical characters on the LCD, ASCII codesfor the letters ‘A’ ‘Z’, ‘a’ ‘z’, or number ‘0’ ‘9’ are sent toDB0 DB7 pins while making RS = 1, R/W = 0, and a high-tolow(1 0) pulse to EN.• Instruction codes are sent to LCD through DB0 DB8 whilemaking RS = 0, R/W = 0, and a high-to-low (1 0) pulse toEN.TCC 2007 32


Cont…TCC 2007 33


Cont…• 4-bit LCD initializationas specified by Hitachi:TCC 2007 34


LED Tutorial 1


Cont…4-bit LCD connectionTCC 2007 36


MikroC LCD Library Functions• Lcd_Init(&PORT) – initializes LCD at PORT with the followingpin settings:– D7 – port.7– D6 – port.6– D5 – port.5– D4 – port.4– E – port.3– RS – port.2– RW – port.0• Lcd_Cmd(command) – sends command to LCD, e.g.:LCD_CLEAR – clear display, LCD_CURSOR_OFF – turn offcursor.• Lcd_Out(row, col, text) – prints text on LCD at specified rowand column.TCC 2007 37


MikroC Program Example for LCD Interfacing• A program to display counting from 0 to 60:void main(){unsigned short i = 0; //Variable for counting 0 to 60char text[5];//Variable to hold string value of iTRISB = 0;//Set PORTB as outputLcd_Init(&PORTB);//Initialize LCD connected to PORTBLcd_Cmd(Lcd_CLEAR); //Clear displayLcd_Cmd(Lcd_CURSOR_OFF);//Turn off LCD cursorLcd_Out(1, 1, "Counts to 60:"); //Message at first linewhile(1){ShortToStr(i, text);//Convert number i to stringLcd_Out(2,1,&text[2]); //Print string at line 2i++;//Increment iif(i>60) i = 0; //Reset i to 0 if more than 60delay_ms(1000);//Delay 1 second}}TCC 2007 38


LED Tutorial 2


http://picnote.blogspot.com/2008/10/mikroc-hello-world-lcd-example.html40


Test LCDchar *text = "Hello World!";char mytext[3];int i;void main() {// pic16f887// ANSEL = 0x00; //Digital I/O for PORTA// ANSELH = 0x00; //Digital Input for PORTBThe source code in MikroC// pic16f877ACMCON = 0x07; //Set PORTA to Digital inputTRISB = 0; // PORTB is outputTRISA = 0x07; //PORTA as the input/output 0000 0111i=0;Lcd_Init(&PORTB); // Initialize LCD connected to PORTBLcd_Cmd(Lcd_CLEAR); // Clear displayLcd_Cmd(Lcd_CURSOR_OFF); // Turn cursor offLcd_Out(1, 1, text); // Print text to LCD, 2nd rowwhile(1){while(i


Micro-controller CourseEngr. ShashikumarPIC16F877A"<strong>Peripheral</strong> <strong>Interface</strong> <strong>Controller</strong> “Introduction


Why use PIC16F877?PIC16F877 Microcontroller Microchip are themost commonly used because;• Flash PIC development board whichaccommodates this microcontroller are widelyuse world wide in reached facility's anduniversities for experiments.


• Why PIC is popular?Introduction low cost ,wide availability with high clock speed availability of low cost or free development tools Only 37 instructions to remember serial programming and re-programming with flashmemory capability Its code is extremely efficient, allowing the PIC to runwith typically less program memory than its largercompetitors PIC is very small and easy to implement for non-complexproblems and usually accompanies to themicroprocessors as an interface


PIC16F877A – Introduction– 8-bit RISC core– 35 single-word instructions– All single-cycle instructions except for program branches, which are two-cycle– Operating speed from DC to 20MHz clock input– 8k x 14-bit Flash Program Memory– 368 x 8-bit RAM Data Memory– 256 x 8-bit EEPROM Data Memory– 5 I/O ports with a total of 33 I/O lines– Two 8-bit and one 16-bit timers/counters– 2 Capture, Compare, PWM modules– Synchronous Serial Port (SSP) with SPI (master mode) and I2C (master/slave)– Universal Synchronous Asynchronous Receiver Transmitter (USART/SCI) with 9-bitaddress detection– 8 bits wide Parallel Slave Port (PSP) with external RD, WR and CS controls– 10-bit 8-channel Analog-to-Digital Converter (A/D)– 2 analog comparators– 15 interrupt sources– Brown-out Reset (BOR)– Watchdog Timer (WDT) with its own on-chip RC oscillator for reliableoperation– In-Circuit Serial Programming via two pins– In-Circuit Debug (ICD) via two pins45


Microcontroller (MCU) Overview• CPU, Memory (ROM, RAM),I/O and <strong>Peripheral</strong>s in onechip.• Can store and executeprogram to perform dataprocessing or decisionmaking.• Heart of many embeddedapplications.ThumCC 2007 46


Simplified Architecture DiagramCentralProcessingUnitMainMemorysystem busI/OdeviceI/OdeviceI/OdeviceI/Odevice


RISC vs. CISCTwo Different Architectures• Harvard Architectures• Von-Neumann Architecture(newer arch.)Used in : Atmel, AVR, PIC, etc.For example, PICs use:-Data memory (RAM): a small number of 8bit registers.- Program memory (ROM): 12bit, 14bit or 16bit wide (inEPROM, FLASH, or ROM).Used in: 80X86, 8051, 68HC11, etc.Bottleneck: Getting instructionsinterferes with accessing RAM• Reduced Instruction Set Computer (RISC)– Few instructions(usually < 50)– Only a few addressing modes– Executes 1 instruction in 1 internal clockcycle (Tcyc)• Complex Instruction Set Computer (CISC)– Many instructions(usually > 100)– Several addressing modes– Usually takes more than 1 internal clockcycle (Tcyc) to execute


Data memoryCPU8 bits 14 bitsProgrammemoryHarvard architecture in PICMicro MCUsProgram MemoryHarvard ArchitectureFile RegisterAddressArrayInstructionData MemoryLibraryFunctions (.h)49


Micro-controller CourseEngr. ShashikumarPIC16F877A"<strong>Peripheral</strong> <strong>Interface</strong> <strong>Controller</strong> “Memory


The PIC Family: Data Memory12C50816C71C16F87717C76625B RAM36B RAM368B RAM + 256B ofnonvolatile EEPROM902B RAM• PICs use general purpose “File registers” for RAM (each register is 8bits for all PICs)The PIC Family: Program Memory12C508 512 12bit instructions16C71116F87717C7661024 (1k)8192 (8k)16384 (16k)14bit instructions14bit instructions16bit instructions• Technology: EPROM, FLASH, or ROM• It varies in size from one chip to another.


PIC MemoryFile Register (RAM)AddressArrayInstruction, Data(Functions)• 368 Bytes Registers as Data Memory : Special Function Registers: used tocontrol peripherals and PICbehaviors General Purpose Registers: usedto a normal temporary storagespace (RAM)• The PIC16F877A has an8192 Bytes (8k) 14bitinstruction programmemory• Technology Flash, EPROMor ROM• 256 Bytes of nonvolatile EEPROM


Cont…• Program memory – flash memory to keep the program codesas well as larger amount of data.• EEPROM memory is used non-volatile variable data storage.• The volatile static RAM is mainly used to store variables anddata during program execution.• PIC16F877A has a 13-bit program counter for addressing the8k × 14-bit program memory space.ThumCC 2007 53


Cont…• The data memory is also known as file registers, with each location accessible justlike a register.• Data memory is divided into 4 banks which comprise the General PurposeRegisters and the Special Function Registers (SFRs).• Only one bank can be selected at a time using the bank select bits (RP0 and RP1) inthe STATUS register (bit 5 and 6).• Each bank extends up to 128 bytes, with the lower locations reserved for SFRs.• Some frequently used Special Function Registers (STATUS, PCL, FSR etc.) from onebank are mirrored in other banks for code reduction and quicker access.• The General Purpose Registers are located above the Special Function Registers,and are used for temporary data storage.ThumCC 2007 54


0x00 (Hex.)00 H (Hex.)0,1111,1111 (Bin)9bitPIC16F877A96 Dec.96 Address96 bytes76543210 File address 76543210 File address 76543210 File address 76543210 File addressIndirect addr 1 00H Indirect addr 1 80H Indirect addr 1 100H Indirect addr 1 180HTMR0PCLSTATUSFSRPORTAPORTBPORTCPORTDPORTEPCLATHINTCONPIR1PIR2TMR1LTMR1HT1CONTMR2T2CONSSPBUFSSPCONCCPR1LCCPR1HCCP1CONRSCTATXREGRCREGCCPR2LCCPR2HCCP2CONADRESHADCON0GeneralPurposeRegisters96 bytes01H02H03H04H05H06H07H08H09H0AH0BH0CH0DH0EH0FH10H11H12H13H14H15H16H17H18H19H1AH1BH1CH1DH1EH1FH20H7FHRAM & EPROMOPTION_REGPCLSTATUSFSRTRISATRISBTRISCTRISDTRISEPCLATHINTCONPIE1PIE2PCONSSPCON2PR2SSPADDSSPSTATTXSTASPBRGCMCONCVRCONADRESLADCON1GeneralPurposeRegisters80 bytesAccesses70H – 7FH81H82H83H84H85H86H87H88H89H8AH8BH8CH8DH8EH8FH90H91H92H93H94H95H96H97H98H99H9AH9BH9CH9DH9EH9FHA0HEFHF0HFFHTMR0PCLSTATUSFSRPORTBPCLATHINTCONEEDATAEEADREEDATHEEADRHGeneralPurposeRegisters96 bytesAccesses70H – 7FH101H102H103H104H105H106H107H108H109H10AH10BH10CH10DH10EH10FH110H16FH170H17FHOPTION_REGPCLSTATUSFSRTRISBPCLATHINTCONEECON1EECON2Reserved 2Reserved 2GeneralPurposeRegisters96 bytesAccesses70H – 7FHBank 0 Bank 1 Bank 2 Bank 3181H182H183H184H185H186H187H188H189H18AH18BH18CH18DH18EH18FH190H1EFH1F0H1FFH1 Address8bit = 1byte9bit1FF Hex. = 511 Dec.511 Address511 bytes4088 bitsUnimplemented data memory locations,read as ‘0’Note: 1. Not a physical register.2. There registers are reserved and should not be used55


PIC16F877AThe mostimportantregistershaveaddressesin all thefour banksThe data memory is devided into 4 memory banks


PIC16F877AROM , EPROM or FlashProgram memory mapTakes a max of 8 addresses, the ninthaddress will write over the first.When the controlleris reset, programexecution startsfrom hereIf interrupted, programexecution continues from here14bit7 6 5 4 3 2 1 08191 (Dec.)


Power-on Reset


Register Addressing ModesImmediate Addressing:Movlw H’0F’Indirect Direct Addressing:• Uses Full 78 bits register of 14 bit address instruction is written to identify the special a register function file address register 8th FSR and 9th bit• comes INDF from is used RP0 to and get the RP1 content bits of STATUS of the address register. pointed by FSR• i.e. Exp : A sample Z equ D’2’ program to clear ; Z=2 RAM locations H’20’ – H’2F:MOVLW 0x20 ;initialize pointerbtfss STATUS, Z ; test if the 3rd bit of the STATUS register is setNEXTCONTINUE: ;yes continueMOVWF FSR ;to RAMCLRF INDF ;clear INDF registerINCF FSR,F ;inc pointerBTFSS FSR,4 ;all done?GOTO NEXT ;no clear next


InstructionMemoryPIC16F877A Block DiagramDataMemoryInstructionBusmust beinvolved inallarithmeticoperationsMostimportantregister inthe PICData Bus


Micro-controller CourseEngr. ShashikumarPIC16F877A"<strong>Peripheral</strong> <strong>Interface</strong> <strong>Controller</strong> “CLOCK


The Clock Source


• The PIC Family: Cores Architecture Differences 12bit cores with 33 instructions: 12C50x, 16C5x 14bit cores with 35 instructions: 12C67x,16Cxxx 16bit cores with 58 instructions: 17C4x,17C7xx ‘Enhanced’ 16bit cores with 77 instructions: 18Cxxx12C50x4MHzThe PIC Family:Clock Speed12C67x16Cxxx17C4x / 17C7xxx18Cxxx10MHz20MHz33MHz40MHzInstruction speed = 1/4 clock speed (Tcyc = 4 * Tclk)


Clock and Instruction Cycles• Instruction Clock– Clock from the oscillator enters a microcontroller via OSC1 pin where internal circuit of amicrocontroller divides the clock into four even clocks Q1, Q2, Q3, and Q4 which do not overlap.– These four clocks make up one instruction cycle (also called machine cycle) during which oneinstruction is executed.– Execution of instruction starts by calling an instruction that is next in string.– Instruction is called from program memory on every Q1 and is written in instruction register on Q4.– Decoding and execution of instruction are done between the next Q1 and Q4 cycles. On thefollowing diagram we can see the relationship between instruction cycle and clock of the oscillator(OSC1) as well as that of internal clocks Q1-Q4.– Program counter (PC) holds information about the address of the next instruction.Operating speed: Example, 20 MHz clock input = 200 ns instruction cycle


• Instruction Pipeline Flow


PIC16F877A Block DiagramKeep thecontroller Keep the inResets reset controller state the in untilcontroller power reset Resets state reaches the after until aspecified an the controller acceptable oscillator time after islevel started detecting & steady & stableBrown-OutconditionBrown-out: when the supplying voltage fallsbelow a trip point (BV DD ).This ensures that the device does notcontinue program execution outside the validoperation range of the deviceTypically used in AC line or large batteryapplication where large loads maybeswitched in and cause the device voltage totemporarily fall below the specified operatingminimum


Power supply for the circuitany volt below 5V PIC need to shutdown•Can choose either AC to DC adaptor or 9V-12V battery to power up the circuit.Higher input voltage will produce more heat at LM7805 voltage regulator.• Typical voltage is 12V. Anyhow, LM7805 will still generate some heat at 12V. Thereare two type of power connector for the circuit, DC plug (J1) and 2510-02 (PowerConnector).• Normally AC to DC adaptor can be plugged to J1 type connector.•D2 is use to protect the circuit from wrong polarity supply.•C3 and C10 is use to stabilize the voltage at the input side of the LM7805 voltageregulator.•While the C8 and C11 is use to stabilize the voltage at the output side of the LM7805voltage supply.• LED is a green LED to indicate the power status of the circuit. R10 is resistor toprotect LED from over current that will burn the LED


Micro-controller CourseEngr. ShashikumarPIC16F877A"<strong>Peripheral</strong> <strong>Interface</strong> <strong>Controller</strong> “REGISTEREach peripheral has a set of SFRs to control its operation.


Cont…• The Special Function Registers are registers used bythe CPU and peripheral modules for controlling thedesired operation of the devices.• All SFRs (including the Program Counter) are mappedin the data memory (implemented as static RAM).• The SFRs can be divided into two categories: core(CPU) and peripheral.ThumCC 2007 70


Micro-controller CourseEngr. ShashikumarREGISTER = SFR = Special Function RegisterUses a series of “Special Function Registers” for controlling peripherals and PIC behaviors.1. MAIN_REG contains2. OPTION_REG contains various control bits to configurethe TMR0 prescaler/WDT postscaler ,the External INTInterrupt, TMR0 and the weak pull-ups on PORTB3. STATUS Bank select bits, ALU bits (zero, borrow, carry)4. INTCON Interrupt control: interrupt enables, flags, etc.5. PORT InterruptPIC Family Control Registers


Micro-controller CourseEngr. Shashikumar1.REGISTER9ProgrammableSettings


Cont…9 programmable settings of the16F877A microcontroller.73


1. CP 2. CDP• Code Protection – prevents reading of memory byexternal devices, includes flash program memory anddata EEPROM memory.• CP bit for flash program memory.• CPD bit for data EEPROM memory.• Protect intellectual property of designer.• Does not affect internal access to program and dataEEPROM memory.74


3. WRT 0 4. WRT 1• Flash Memory Write Enable – bits WRT0 and WRT1.• Determine which section of program memory can bewritten during program execution.bit 10-9 WRT1:WRT0 Flash Program Memory Write Enable bits11 = Write protection off; all program memory may be written to by EECON control10 = 0000h to 00FFh write-protected; 0100h to 1FFFh may be written to by EECON control01 = 0000h to 07FFh write-protected; 0800h to 1FFFh may be written to by EECON control00 = 0000h to 0FFFh write-protected; 1000h to 1FFFh may be written to by EECON control75


5. LVP• Low Voltage Programming (LVP) – enables LVP ICSP.• When enabled, MCU enters programming mode after a risingedge at the PGM (RB3) pin followed by another rising edge atthe MCLR pin.• When disabled, pin PGM (RB3) can be used as digital I/O pin.76


6. PWTEN• Power-up Timer Enable – enables power-up timer.• Power-up timer keeps the PIC in reset for 72 ms afterit is powered up.• Timer operates on an internal RC oscillator.• The time delay allows V DD to stabilize.• PIC remains in reset 1024 oscillator clock cycles afterpower up timer expires to ensure oscillator circuit isworking properly.77


7. BOREN• Brown-out Reset Enable – BOREN bit, enablesBrown-out reset.• Brown-out – decrease in the supply voltage.• PIC is reset when supply voltage falls below 4V.• Must be disabled if the low-voltage version(PIC16LF877A) is used at less than 4V supply.78


8. WDT• Watchdog Timer Enable – WDTEN bit, enables the watchdogtimer.• WDT – a free running timer with its own RC oscillator,overflows in 18 ms. Will reset the PIC when overflowed.• A mechanism to prevent software failure.• Instructions are inserted in the user program to clear the WDT– WDT does not overflow if program flows normally.• WDT overflows in software failure to reset the PIC.• Overflow interval can be extended by the prescaler setting inOPTION_REG register.79


9. FOSC 1 & FOSC 0• Oscillator Selection – FOSC1 & FOSC0 bits.• To select the type of oscillators used for the microcontroller.• Frequency range DC – 4 MHz.• Available types: RC, LP, XT, HS.• RC – Resistor Capacitor Oscillator.• LP – low power crystal, 5 – 200 kHz.• XT – normal crystal, 0.1 – 4 MHz.• HS – high speed crystal, 4 – 20 MHz.80


Micro-controller CourseEngr. Shashikumar2.OPTION_REG6ProgrammableSettings


Timer Applications• Referred as timer/counters in PIC documentation.• Comprise of flip-flops.• Called timer when increments based on a internal clocksource.• Called counter when increments based on external clocksource, to count the number of incoming pulses.• 3 timers in PIC16F877A: TMR0, TMR1 & TMR2.• Can be accessed as special function registers.• Applications: generate timing signal, measuring time, toinvoke tasks at certain intervals, counting amount of pulses,etc.TCC 2007 82


Cont…• Timers are referred as timer/counters in PIC documentation.• Comprise of flip-flops.• Called timer when increments based on a internal clock source.• Called counter when increments based on external clock source, to countthe number of incoming pulses.• 3 timers in PIC16F877A: TMR0 (8-bit), TMR1 (16-bit) & TMR2 (8-bit).• Can invoke interrupts when they overflow.• Applications: generate timing signal, measuring time, to invoke tasks atcertain intervals, counting amount of pulses, etc.ThumCC 2007 83


TMR0• A 8 bit, free-runningtimer.• 2 available sources:internal clock and RA4.• Source and prescalerselection throughOPTION_REG.TCC 2007 84


Timer 0 Block Diagram


Special Function RegisterOPTION_REG Register


Micro-controller CourseEngr. Shashikumar3.STATUS6ProgrammableSettings


Special Function Register”STATUS Register“


Micro-controller CourseEngr. Shashikumar4.INTCON6ProgrammableSettings


Special Function Register”INTCON Register“


Interrupt Control: INTCON Register• A SFR that contains variousenable and flag bits fordifferent interrupt sources.• Enable bits turn on or offvarious interrupt sources.• Flag bits are set when aninterrupt condition occurs.TCC 2007 91


Cont…• Sets TMR0IF interrupt flag when it overflows.• TMR0 interrupt is controlled by TMR0IE bit ofINTCON register.• Can be used to trigger events at fixed intervals.• Interrupt interval = 4/F osc x prescaler x 256• TMR0 can be written with a value to change theoverflow interval.• Writing to TMR0 causes 2 cycle inhibit, eg: writing100 to TMRO will cause an equivalent of 158 countsin stead of 156 counts.TCC 2007 92


Micro-controller CourseEngr. ShashikumarPIC16F877A"<strong>Peripheral</strong> <strong>Interface</strong> <strong>Controller</strong> “PORT


• PIC16F877A has 8 Analog Input channels (ADC)• 10 bit resolution• Basic registers used forADC conversion• ADCON0• ADCON1• 5 Channels on PORT A• 3 Channels on PORT E• PIC16F877A hasDigital ports• 8 Channels on PORT B• 8 Channels on PORT C• 8 Channels on PORT D94


A – for Advance16F877The microcontroller pins have multiple functionsPIC16F877A in 40 – pin DIP package.


PIC16F877A Pin LayoutADC PORTA inputs(Port A and Port E)Counter 0externalPORTEinputPORTBPORTDPORTCPORTCPORTD


Micro-controller CourseEngr. Shashikumar5.PORT6ProgrammableSettings


Push Button as input for PICmicrocontroller• One I/O pin is needed for one push button as input of PIC microcontroller. Theconnection of the push button to the I/O pin is shown in figure above.• The I/O pin should be pull up to 5V using a resistor (with value range 1K-10K)and this configuration will result an active-low input.• When the button is being pressed, reading of I/O pin will be in logic 0, whilewhen the button is not pressed, reading of that I/O pin will be logic 1.


Parallel I/O Ports• Set port direction TRISX {1 IN, 0 OUT}• Set an output value PORTX• Read an input value PORTX• Set an output value and then read back theoutput value LATAX


<strong>Peripheral</strong>s• <strong>Peripheral</strong>s – special circuits integrated into themicrocontroller to perform specific tasks, enablingthe microcontroller to interact with the outsideworld.• <strong>Peripheral</strong>s examples: Timers, CCP, ADC, MSSP andUSART.• All peripherals can be accessed through specialfunction registers (SFR) which are data memorymapped and use the data memory bus.ThumCC 2007 100


I/O Ports• PIC16F877A has 33 I/O lines grouped into 5 I/O ports.• Some of the I/O lines are multiplexed with analternate function for the peripheral features – cannotbe used as general purpose I/O when peripheral isenabled.• Each I/O port has two SFRs – TRISx and PORTx.• TRISx register determines the direction of the port –input or output.• Setting a bit in the TRISx register causes thecorresponding bit in the I/O port becomes an input(tristate condition) while clearing the bit makes it anoutput.• Reading the PORTx register reads the status of the I/Oport while writing to it will write to the port latch.ThumCC 2007 101


<strong>Peripheral</strong> Features5 Digital I/O PortsThree timer/counter modules• Timer0: 8-bit timer/counter with 8-bit pre-scaler• Timer1: 16-bit timer/counter with pre-scaler, can be incremented during SLEEP viaexternal crystal/clock• Timer2: 8-bit timer/counter with 8-bit period register, pre-scaler and post-scalerA 10-bit ADC with 8 inputsTwo Capture, Compare, PWM modules• Capture is 16-bit, max. resolution is 12.5 ns• Compare is 16-bit, max. resolution is 200 ns• PWM max. resolution is 10-bitSynchronous Serial Port (SSP) with SPI (Master mode) and I2C (Master/Slave)Universal Synchronous Asynchronous Receiver Transmitter (USART/SCI) with 9-bitaddress detectionParallel Slave Port (PSP) 8-bits wide, with external RD, WR and CS controls


PIC <strong>Peripheral</strong>s: Ports (Digital I/O)• Ports are basically digital I/O pins which exist in all PICs• The PIC16F877A have the following ports: PORT A has 6 bit wide, Bidirectional PORT B,C,D have 8 bit wide, Bidirectional PORT E has 3 bit wide, Bidirectional• Ports have 2 control registers TRISx sets whether each pin is an input (1) or output (0) PORTx sets their output bit levels or contain their input bit levels• Pin functionality “overloaded” with other features• Most pins have 25mA source/sink thus it can drive LEDs directly


Cont…• ADC converts analog signal voltage to digital value bycomparing it to the reference voltage.• PIC16F877A is equipped with a 10 bit ADC multiplexedbetween 8 inputs.• The ADC shares pins with PORTA and PORTE.• Protection diodes in PORTA and PORTE preventsmeasurement of negative voltage.• Bi-polar waveforms must be level shifted.• PORTA and PORTE are set as analog pins by default, need tochange setting in ADCON1 register if those ports are used asdigital I/O.ThumCC 2007 104


PIC <strong>Peripheral</strong>s: Analogue to DigitalConverterOnly available in 14bit and 16bit coresFs (sample rate) < 54KHzthe result is a 10 bit digital numberCan generate an interrupt when ADC conversion isdone


PIC <strong>Peripheral</strong>s: Analogue to DigitalConverter• The A/D module has four registers. These registers are:A/D Result High Register (ADRESH)A/D Result Low Register (ADRESL)A/D Control Register0 (ADCON0)A/D Control Register1 (ADCON1)• Multiplexed 8 channel inputsMust wait T acq to charge up sampling capacitor• Can take a reference voltage different from that of the controller


Micro-controller CourseEngr. ShashikumarINTERRUPT


Micro-controller CourseEngr. ShashikumarPIC16F877A"<strong>Peripheral</strong> <strong>Interface</strong> <strong>Controller</strong> “UART


Cont…• PIC16F877A has two serial ports: MSSP and USART.• MSSP – Master Synchronous Serial Port, works in synchronousserial mode, can be configured for SPI or I 2 C operation.• USART - Universal Synchronous Asynchronous ReceiverTransmitter, works in both synchronous and asynchronousoperation, can be connected to RS-232 serial port inasynchronous mode.ThumCC 2007 109


PIC <strong>Peripheral</strong>s: USART: UARTSynchronous communication: i.e., with clock signalSPI = Serial <strong>Peripheral</strong> <strong>Interface</strong> 3 wire: Data in, Data out, Clock Master/Slave (can have multiple masters) Very high speed (1.6Mbps) Full speed simultaneous send and receive (Full duplex)I2C = Inter IC 2 wire: Data and Clock Master/Slave (Single master only; multiple masters clumsy) Lots of cheap I2C chips available; typically < 100kbps


Micro-controller CourseEngr. ShashikumarPIC16F877A"<strong>Peripheral</strong> <strong>Interface</strong> <strong>Controller</strong> “CAPTURE


Cont…• CCP module – 3 functions: Capture, Compare and PWM.• 2 such modules in PIC16F877A: CCP1 & CCP2.• CCP modules interact with TMR1 and TMR2.• Capture mode operates like a stop watch – upon detection of an externaleven at the respective CCP pin, the current value of TMR1 will be recordedin CCPRxL and CCPRxH and an interrupt can be triggered.• Compare mode compares a 16 bit value with current TMR1 value andchanges the state of respective CCP pins or trigger an interrupt upon amatch.• PWM mode generates pulse width modulation signal at configurablefrequency and duty cycle for power control or low cost DAC applications.ThumCC 2007 113


Micro-controller CourseEngr. ShashikumarEND

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!