KHAN WAHID 2010-11 (Term 1)
EE331 Microprocessor
Chapter 3
Introduction to PIC Introduction to PIC Microcontroller Microcontroller –– Part 2Part 2
Dr. KHAN WAHID2010-11 (Term 1)
2EE 331: Microprocessor
PIC16F84A Microcontroller
We have so far discussed the Fetch unit
Now let us look into the Execute unit
Dr. KHAN WAHID2010-11 (Term 1)
3EE 331: Microprocessor
Execute UnitThe execute unit is responsible for reading data from the Data store or literal data from the instructionProcess it as commanded by the Instruction decoder using the ALU
The outcome is placed either in the Working register (W) or back in the Data store, overwriting the original data
Dr. KHAN WAHID2010-11 (Term 1)
4EE 331: Microprocessor
ALUAccept data from two sources:
A byte directly from a specified File in the Data store
addwf h’20’,f: ADDs the contents of W to the content in File h’20’
A literal byte held as part of the instruction code
addlw 5: ADDs the literal 5 to W
The outcome in the former case can be directed either back into the Data store depending on the destination bit
Dr. KHAN WAHID2010-11 (Term 1)
5EE 331: Microprocessor
7
Data Flow inside 16F84Aaddwf h’20’, f
000111_1_0100000000111_1_0100000
0001110100000
ffffffff
d=0 d=1
ffffffff
**Read-modify-write operation
Dr. KHAN WAHID2010-11 (Term 1)
6EE 331: Microprocessor
STATUS RegisterHolds three flag bits used to tell the software something about the outcome from an instruction
For instance, carry-out, zero, etc.
Carry flag (C)holds the carry out from the last addition operation. Subtraction operation sets this bit if no borrow outExample: 24−12 = 12 (B=0, C=1) and 12−24 = 88 (B=1, C=0)Note that: 24−24 = 0 => sets both Z and C (C=1, Z=1)Also functions as an input/output bit for the rotate instructions (rrf, rlf)
??
Dr. KHAN WAHID2010-11 (Term 1)
7EE 331: Microprocessor
STATUS RegisterDigit Carry flag (DC)
Similar to CHolds the carry out from the lower nibble to the upper nibble
from bit 3 to bit 4Example: BCD
Hold complement of the borrow out from bit 3 to bit 4
Zero flag (Z) This is set whenever the outcome of the instruction is zero (i.e., ALU output is zero), otherwise it is cleared
Dr. KHAN WAHID2010-11 (Term 1)
8EE 331: Microprocessor
STATUS Register (Z, DC, C)
C
DC
Z
8-input NOR
Dr. KHAN WAHID2010-11 (Term 1)
9EE 331: Microprocessor
STATUS Register (Z, DC, C)Find out the instructions that affect the STATUS register
All ALU operations, movf, clrf, clrw, comf, etc.
Dr. KHAN WAHID2010-11 (Term 1)
10EE 331: Microprocessor
STATUS Register – ExamplesE4.3 (pp. 91): A smart programmer has decided to copy the contents of the Status register into File h’40’ for safekeeping so that it can be returned later without alteration. Do you see any problem?
**SAQ4.3: Given the effect of the movf instruction on the Z flag (as in E4.3), how could you use this instruction to determine if the contents of any File is zero?
movf h’20’, f ;This will copy the contents of h’20’;back into h’20’ and on the way set the ;Z flag if the contents are h’00’
Bit 2 (Z) of the Status register may invariably be forced to 0. Why?
Dr. KHAN WAHID2010-11 (Term 1)
11EE 331: Microprocessor
STATUS RegisterPower Down (NOT_PD)
Cleared when the sleep instruction is executed
The sleep instruction is used to disable the oscillator and place the MCU in a low current mode (typically < 1uA)
Time Out (NOT_TO)Cleared when the Watchdog timer times outBoth PD and TO can only be read; they cannot be directly be altered by the program, and they are set to 1 on a Power-on reset
Register Page 0 (RP0)Used to select register bank on Data store
Not implemented
Dr. KHAN WAHID2010-11 (Term 1)
12EE 331: Microprocessor
Data Store68x8 Data store has two banks
RPO is used to select Bank0/Bank1RP0 = 0 => select Bank 0RP0 = 1 => select Bank 1What is the advantage?
hex
Use bcf instruction
Dr. KHAN WAHID2010-11 (Term 1)
13EE 331: Microprocessor
Data Store68x8 Data store has two banks
RPO is used to select Bank0/Bank1Recall address bits from “File direct”instruction structure7-bits => 128 addresses
How to represent say, 85h (b1000_0101)?
RPO gives an effective 8th address bitEffectively 256-file Data store
4Fh => 79d; CFh => 207d
hex
Dr. KHAN WAHID2010-11 (Term 1)
14EE 331: Microprocessor
Data StoreTwo types of registers or “files” in PIC MCU
Special-function register (SFR)To control and monitor the state of the MCU and its various peripheral devices
E.g., TMR0, PCL, STATUS, FSR, etc.General-purpose register (GPR)
Used for general purpose storage – 68 x 8Bank0 (0C to 4F)Bank1 (8C to CF) – mapped to Bank0
Most commonly used SFRs are normally mirrored across all bank – as they’re frequently accessed, it would be inefficient to switch banks back and forth
hex
Dr. KHAN WAHID2010-11 (Term 1)
15EE 331: Microprocessor
ExampleConsider a code fragment where it is desired to set the state of File h’86’(TRISB) to the pattern b’00001111’
hex
bcfBit Clear File enables the programmer to zero any bit in any File => bcf h’20’,7 clears bit 7 in File h’20’. All other bits remain unaltered.bsfBit Set File enables the programmer to set any bit in any File => bsf h’31’,3 sets bit 3 in File h’31’. All other bits remain unchanged.
Self-study – Assembler directives (pp. 87-88)
Dr. KHAN WAHID2010-11 (Term 1)
16EE 331: Microprocessor
Addressing ModeDirect addressing mode (7-bits)Indirect addressing mode (8-bits) –using FSR and INDF (virtual)
File Select Register (FSR) – holds addressINDF – holds contentTo trigger this mode, the internal logic detects whenever the Data store address is b’000_0000’
The 8-bit contents of the FSR is switched onto the Data store’s address bus
Advantage: the location of the operand can be altered as the program progresses; that is, at run time => we can randomly access the content of data store
Dr. KHAN WAHID2010-11 (Term 1)
18EE 331: Microprocessor
Indirect Addressing: ExampleSuppose we wish to clear the contents of all File registers in Bank0 of a PIC16F84; that is, File h’0C’ – File h’4F’
The obvious way to do this is to use the clrf (CLeaRFile) instruction 68 timesEfficient method: use indirect addressing
Dr. KHAN WAHID2010-11 (Term 1)
19EE 331: Microprocessor
Indirect Addressing: ExampleSuppose we wish to clear the contents of all File registers in Bank0 of a PIC16F84; that is, File h’0C’ – File h’4F’
The obvious way to do this is to use the clrf (CLeaRFile) instruction 68 timesEfficient method: use indirect addressing
Dr. KHAN WAHID2010-11 (Term 1)
21EE 331: Microprocessor
Timer / CounterMeasure the time between two ‘events’ – these events may both be externally generated, or alternatively, the first is generated by the MCU and the second happens some time later, as a response
Seem easy – start the counter running when the first event occurs and stop it on the second
In practice, this poses a number of challengesFor an accurate measurement, the start and stop of the counter must be perfectly synchronized with the events The best way of doing this is by using an asynchronous interrupt
Dr. KHAN WAHID2010-11 (Term 1)
22EE 331: Microprocessor
Timer / CounterFor an 8-bit counter: maximum time measured is 256us
This is an obvious disadvantage => how to count more?May be overcome in several ways by using a slower oscillator, registers with more bits, or very commonly using a prescaler
Timer with a PrescalerAn electronic device used to reduce a frequency by a pre-determined factor (frequency division)
The division rate can be changed from within the program
Dr. KHAN WAHID2010-11 (Term 1)
23EE 331: Microprocessor
Timer / CounterFor an 8-bit counter: maximum time measured is 256us
This is an obvious disadvantage=> how to count more?May be overcome in several ways by using a slower oscillator, registers with more bits, or very commonly using a prescaler
Timer with a PrescalerAn electronic device used to reduce a frequency by a pre-determined factor (frequency division)
The division rate can be changed from within the program
fOSC
fOSC/2
fOSC/4
fOSC/8
fOSC/16
Dr. KHAN WAHID2010-11 (Term 1)
24EE 331: Microprocessor
Timer / CounterTimer with an Interrupt
When the maximum count (i.e. 256 for an 8-bit counter) is exceeded, the timer will be automatically reset and counting will start from zero againAt the same time, a special signal (called interrupt) is set which starts another counter (details will follow later)
Dr. KHAN WAHID2010-11 (Term 1)
25EE 331: Microprocessor
Timer 0 (TMR0)All PIC MCU have at least one basic timer, Timer 0 (TMR0) – nothing but an 8-bit counter
TMR0 register is directly mapped into memory location h’01’ of Bank0TMR0 can be operated as a timer or as a counter:
Timer: run by internal Q4 phase clock (fosc/4)Counter: run by external clock via the T0CKI pin
Dr. KHAN WAHID2010-11 (Term 1)
26EE 331: Microprocessor
Timer 0 (TMR0)Either clock source can be frequency divided by a 8-bit Prescaler counter controlled by OPTION_REG [PS2:PS1:PS0]
Division ratio: 2PS+1
Set PSA (= 1) to turn it off
Dr. KHAN WAHID2010-11 (Term 1)
27EE 331: Microprocessor
Timer 0 (TMR0)Either clock source can be frequency divided by a 8-bit Prescaler counter controlled by OPTION_REG [PS2:PS1:PS0]
Division ratio: 2PS+1
Set PSA (= 1) to turn it OFF
Dr. KHAN WAHID2010-11 (Term 1)
28EE 331: Microprocessor
Timer 0 (TMR0)The output of the second MUX is synchronized with the internal clock before becoming the actual input of the counter (TMR0)
When the counter overflows, it sets the timer overflow flag, TOIF (one of four interrupts)
Dr. KHAN WAHID2010-11 (Term 1)
29EE 331: Microprocessor
OPTION_REGT0SE (Timer 0 Set Edge): to select which edge of a pulse – 0 for rising edge and 1 for falling edgeT0CS (Timer 0 Clock Select): to select the clock source as either the internal clock (= 0) or a transition at the T0CKI pin
In Timer mode (TOCS=0), if the TMR0 register is written (e.g., movwf TMR0), the increment is inhibited for the following two instruction cycles
The user can work around this by writing an adjusted value (desired + 2) to the TMR0 register
In Counter mode (TOCS=1), when an external clock is used, TMR0 must meet certain requirements which ensure that the external clock is synchronized with the internal phase clock (TOSC)
Also, there is a delay in the actual incrementing of Timer0 after synchronization
Dr. KHAN WAHID2010-11 (Term 1)
30EE 331: Microprocessor
OPTION_REGT0SE (Timer 0 Set Edge): to select which edge of a pulse – 0 for rising edge and 1 for falling edgeT0CS (Timer 0 Clock Select): to select the clock source as either the internal clock (= 0) or a transition at the T0CKI pin
The remaining two bits configure external interrupt edge select and electrical properties of Port B inputs (to be covered later)
Let’s see a few examples showing the use of TMR0
Dr. KHAN WAHID2010-11 (Term 1)
31EE 331: Microprocessor
Watchdog TimerAn on-chip timer that resets MCU after a certain time – set by the user
Necessary to ensure flawless functioning of the microcontroller during its run-timeRun by a separate on-chip oscillator within the MCU
Watchdog timer may be disabled by the user, before downloading the program onto the MCU using “Configuration Word”
No changes can be made once the program start running
Dr. KHAN WAHID2010-11 (Term 1)
32EE 331: Microprocessor
Watchdog TimerThe Watchdog timer is a free-running on-chip oscillator that does not need any external components
Designed to reset the MCU after certain time, unless periodically set by user with the instruction clrwdt (CLeaRWatch Dog Timer)Ensures that the MCU eventually resets if due to an electrical disturbance or a software bug, the processor malfunctions, etc.Nominal timeout period is 18ms, unless scaled up by postscalar
PSA (Pre-Scale Assignment) = 1 turns ON the postscaler for Watchdog timer (2PS)
Remember, PSA=1 turns OFF prescaler for TMR0
The same Prescalermodule of TMR0
Dr. KHAN WAHID2010-11 (Term 1)
33EE 331: Microprocessor
Watchdog TimerTimeout with postscaler
2PS x 18msMaximum: PS[2:0] = 111 => 27x18ms = 2.3s – MCU resets itselfWhen WDT times out, NOT_TO bit in STATUS register is cleared
Dr. KHAN WAHID2010-11 (Term 1)
34EE 331: Microprocessor
Watchdog Timer - ExampleTimeout with postscaler
2PS x 18msMaximum: PS[2:0] = 111 => 27x18ms = 2.3s – MCU resets itselfWhen WDT times out, NOT_TO bit in STATUS register is cleared
Dr. KHAN WAHID2010-11 (Term 1)
35EE 331: Microprocessor
Program Counter Low (PCL), PCLATHOccasionally it is necessary for a program to modify the state of the PC (13-bits) at run time (e.g., goto, etc.)To allow for this, the lower byte of the PC is directly accessible as PCL (8-bits)Need additional SFR: PCLATH – Program Counter LATch High register (the upper 5-bits of the PC)
PCLATH cannot be altered alone – has to coincide with PCL – all 13-bits are altered simultaneously
**Problem: E4.2 (pp. 94)
Dr. KHAN WAHID2010-11 (Term 1)
36EE 331: Microprocessor
Data EEPROMNot a part of MPU – accessed through SFR (EEDATA, EEADR) as a peripheral deviceAny byte can be addressed by EEADR registerand then read from or written to via the EEDATA register controlled by EECON1 and EECON2registersEECON1
Enables writing
Initiates writing
Dr. KHAN WAHID2010-11 (Term 1)
37EE 331: Microprocessor
Data EEPROM - ReadEECON2
The EEPROM CONtrol 2 is not a physically implemented register (used for Write only)It always reads as zero
EEPROM Matrix1,000,000 minimum (107 typical) Erase/Write cycle endurance for each cell at 5V and 25°CMaximum Erase/Write cycle time 8 ms (4ms typical)Data retention greater than 40 years (100 years for the PIC16F62X group)
PIC16F62X
Dr. KHAN WAHID2010-11 (Term 1)
38EE 331: Microprocessor
Data EEPROM - ReadEECON2
The EEPROM CONtrol 2 is not a physically implemented register (used for Write only)It always reads as zero
EE_GET subroutine
Dr. KHAN WAHID2010-11 (Term 1)
39EE 331: Microprocessor
Data EEPROM - WriteEECON2
The EEPROM CONtrol 2 is not a physically implemented register (used for Write only)To unlock the write cycle, a defined sequence needs to be followed: by moving h’55’followed directly by h’AA’ into this virtual location (with no INT)
Deliberately designed to convolute the process as security against accidental alteration
Required sequence for writing
Dr. KHAN WAHID2010-11 (Term 1)
40EE 331: Microprocessor
PIC16F84A Memory Summary
Non-volatile memory is computer memory that can retain the stored information even when not powered. Examples of non-volatile memory include ROM, flash memory, hard disks, floppy disks, magnetic tape, etc.
Dr. KHAN WAHID2010-11 (Term 1)
41EE 331: Microprocessor
Parallel Input/Output PortsPIC16F84A has 13 I/O lines:
PortA has five I/O lines mapped into PORTA (only lower 5-bits)PortB has eight I/O lines mapped into PORTB (all bits)Conceptually they can be considered as a File with their contents visible to the outside world
TRISA and TRISB are used to configure the data flow – input (1) or output (0)
Example: Make Port B pins RB[6:0] an input and pin RB7 an output
Dr. KHAN WAHID2010-11 (Term 1)
42EE 331: Microprocessor
Building Parallel Interface
Output PortInput Port
Dr. KHAN WAHID2010-11 (Term 1)
43EE 331: Microprocessor
Building Parallel InterfaceInput/Output Port(PORTA)
PORTA
TRISA
Dr. KHAN WAHID2010-11 (Term 1)
44EE 331: Microprocessor
I/O Ports – Port A/BReading from a port pin set as input (TRISB = 1)
Here the TRIS buffer is disabled and the state of the Data flip flop remains unchangedFor instance, movf h’06’,w reads the state of Port B input pins into the Working register
Writing to a port pin configured as an output (TRISB = 0)
Here the TRIS buffer is enabled and the Data flip flop altered by the processor writing to the portFor instance, if all Port B pins RB[7;0] are set as output, movlw b’10101010’ followed by movwf h’06’ sets the Port B pins to HLHLHLHL (H = High, L = Low)
Dr. KHAN WAHID2010-11 (Term 1)
45EE 331: Microprocessor
I/O Ports – Port B[3:0]Similar configuration with some enhancements:
The incoming data is latched –(WHY?)
“Weak pull-up” resistors can be switched on, for all port bits used as inputs by clearing the bit NOT_RBPU in the OPTION_REG register – (WHY?)
RB0 (bit 0) is also the external interrupt input and has a Schmitt trigger interface – (WHY?)
RB3:RB0
Dr. KHAN WAHID2010-11 (Term 1)
46EE 331: Microprocessor
Port B – Why Weak Pull-Up?Many applications involve reading the state of arrays of switches
Rather than using relatively more expensive single-pole double-throw (SPDT) switch to give the two logic states, most switches (e.g., keypad) are single throw (SPST) typesIn these situations an external pull-up resistor is needed to convert the open-circuit state to a High-state voltageThe value of such pull-up resistors should not be too low, as a large current will flow, nor too high or else noise will be induced from external sources
A good compromise: 10 – 100 kΩ
Dr. KHAN WAHID2010-11 (Term 1)
47EE 331: Microprocessor
Port B – Why Weak Pull-Up?In order to simplify the interface of such devices, Port B inputs have optional internal pull-up resistors
So that the port is not “floating”when configured as input and no external pull-up resistor is presentCalled “weak pull-ups” - around 20 kΩThese resistors (P-channel FET) are switched in only if NOT_RBPU is 0
All eight pull-ups resistors are switched OFF when the port is configured as outputs
At start-up, NOT_RBPU resets to 1, and so the pull-up resistors are OFF by default
Dr. KHAN WAHID2010-11 (Term 1)
48EE 331: Microprocessor
I/O Ports – Port B[0] – RB0/INTSchmitt Trigger
Has two input thresholds: ‘positive-going’ is higher than the ‘negative-going’If a signal starting from a low value passes the ‘negative-going’ threshold - nothing happensBut, if it crosses the ‘positive-going’threshold, the output changes stateThus, small fluctuations (e.g., noise) do not cause any change in output
RB3:RB0
Dr. KHAN WAHID2010-11 (Term 1)
49EE 331: Microprocessor
I/O Ports – Port B[7:4]For the higher four bits (RB4 to RB7), the data value is also latched as input data is read
The previous input value, from the last time the port was read, is retained on another latch
Its stored value is compared with the current input value. Any difference is detected by an Exclusive OR gate, whose output can generate an interrupt => set RBIF
RB7:RB4
Dr. KHAN WAHID2010-11 (Term 1)
50EE 331: Microprocessor
How to Initialize Ports?h’CF’ = b’1100_1111’
Dr. KHAN WAHID2010-11 (Term 1)
51EE 331: Microprocessor
ExamplesE4.4 (pp. 92): Show how you would set up the following SPRs in Bank 1 as listed:
OPTION_REG <= b’10101111’TRISA <= b’00011110’TRISB <= b’11111111’
SAQ4.5: Based on the configuration of E4.4, write a program to pulse pin RA1 High for 4 us and then Low. You may assume a clock crystal of 4 MHz.SAQ4.6: How could you bring pin RA1 High, then pulse RA0 four times and then RA1 is to go Low again? Your solution should include the setting for TRISA.
TRISX direction:Input (1) or Output (0)
Dr. KHAN WAHID2010-11 (Term 1)
52EE 331: Microprocessor
PIC84A on-chip power-up and reset circuitry
Power-up and ResetWhat happens when power is applied?How long does it take to reset all elements?Both the power supply and the clock oscillator take finite time to stabilize, and in a complex system power to different parts of the circuit may become stable at different times
Then, how can the “start of program execution” be delayed until power has stabilized?
External reset circuit
Dr. KHAN WAHID2010-11 (Term 1)
53EE 331: Microprocessor
(to run PWRT only)
16F84A On-chip RESET16F84A on-chip power-up and reset circuitry
1024 cycles (on-chip Osc) = 72ms
1024 cycles (main Osc) = 1024 x 250ns= 256us (for 4MHz)
1 01 1
S QR Q= → =
= → =
1
11
NOT (fosc/4)
Dr. KHAN WAHID2010-11 (Term 1)
54EE 331: Microprocessor
16F84A On-chip RESET16F84A on-chip power-up and reset circuitry
VDD and MCLR are tied together (very common setup)
Triggers PWRT
Triggers OST
MCU leaves reset state
(72 ms)
1024Tosc
Dr. KHAN WAHID2010-11 (Term 1)
56EE 331: Microprocessor
Configuration Word (Secret)A special part of Program memory
“secret” location at h’2007’Allows the user to define certain configurable features of the MCU at the time of program download – NO CHANGE is possible until the next time MCU is programmedNOT accessible within the program, or while the program is running
Sets OST
Dr. KHAN WAHID2010-11 (Term 1)
57EE 331: Microprocessor
Example 4.5Write a program to increment a packed BCD (pp. 92-93)
SAQ: Solution available from author’s websitehttp://seng.ulster.ac.uk/eme/sidk/quintessential/Chapters_2ed/book.htm
Dr. KHAN WAHID2010-11 (Term 1)
58EE 331: Microprocessor
AcknowledgmentsThese slides have been prepared by Khan Wahid and may contain material copyrighted by:
The Quintessential PIC® Microcontroller, Sid Katzen, 2nd edition, 2005, ISBN: 978-1-85233-942-5Designing Embedded Systems with PIC Microcontrollers: Principles and Applications, Tim Wilmshurt, 2007, ISBN: 978-0750667555PIC16F84A Data Sheet, 35007b, Microchip Technology Inc. Microprocessors/Microcontrollers – Course Notes, Delmar Cengage Leaning, ISBN: 1435453816PIC Microcontroller and Embedded Systems using Assembly and C for PIC18, Mazidi, Mckinlay, Causey, 2008PIC Microcontrollers, Milan Verle, free online (www.mikroe.com/en/books/picmcubook/)