39
1 PIC PIC MicroController MicroController

1 PIC MicroController. 2 Fetches instructions and data from one memory. Fetches instructions and data from one memory. Limits Operating BandwidthLimits

Embed Size (px)

Citation preview

Page 1: 1 PIC MicroController. 2 Fetches instructions and data from one memory. Fetches instructions and data from one memory. Limits Operating BandwidthLimits

1

                                                           PIC MicroControllerPIC MicroController

Page 2: 1 PIC MicroController. 2 Fetches instructions and data from one memory. Fetches instructions and data from one memory. Limits Operating BandwidthLimits

2

                                                           

Fetches instructions and Fetches instructions and data from one memory.data from one memory.• Limits Operating BandwidthLimits Operating Bandwidth

Fetches instructions and Fetches instructions and data from one memory.data from one memory.• Limits Operating BandwidthLimits Operating Bandwidth

ProgramProgramMemoryMemory

CPUCPU

DataDataMemoryMemory

8-Bits8-Bits

12/14/16-Bits12/14/16-Bits

HarvardHarvard

ProgramProgramand Dataand DataMemoryMemory

Von NeumannVon Neumann

8-Bits8-BitsCPUCPU

Processor ArchitecturesProcessor Architectures

Two separate memory Two separate memory spaces and addresses for spaces and addresses for instructions and data.instructions and data.

–Increases throughputIncreases throughput–Different program and data Different program and data bus widths are possiblebus widths are possible–Instruction Pipelining easyInstruction Pipelining easy

Two separate memory Two separate memory spaces and addresses for spaces and addresses for instructions and data.instructions and data.

–Increases throughputIncreases throughput–Different program and data Different program and data bus widths are possiblebus widths are possible–Instruction Pipelining easyInstruction Pipelining easy

Page 3: 1 PIC MicroController. 2 Fetches instructions and data from one memory. Fetches instructions and data from one memory. Limits Operating BandwidthLimits

3

                                                           

Memory - General Concepts and UseMemory - General Concepts and Use

ROM stores the fixed program within a ROM stores the fixed program within a microcontroller and also any fixed datamicrocontroller and also any fixed data

• PROM/MASK ROMPROM/MASK ROM High volume, fixed design, custom masksHigh volume, fixed design, custom masks

• EPROMEPROM Erasable using ultraviolet. Long, but limited, lifetime. Erasable using ultraviolet. Long, but limited, lifetime.

Limited number of erase/program cycles (100). Limited number of erase/program cycles (100). Programmed using custom programmer.Programmed using custom programmer.

• EEPROMEEPROM In circuit programming possible. Individual bytes can be In circuit programming possible. Individual bytes can be

erased and rewritten. Up to 100,000 cycles.erased and rewritten. Up to 100,000 cycles.• FLASHFLASH

In circuit reprogramming, based upon erasing and re-In circuit reprogramming, based upon erasing and re-writing fixed size sectors (64/512 bytes etc). Only writing fixed size sectors (64/512 bytes etc). Only withstand 100 to 10,000 cycles.withstand 100 to 10,000 cycles.

Page 4: 1 PIC MicroController. 2 Fetches instructions and data from one memory. Fetches instructions and data from one memory. Limits Operating BandwidthLimits

4

                                                           

Architectural featuresArchitectural features

Alpha 21264Alpha 21264 588 pins588 pins 64-bit Data Path64-bit Data Path 7-stage pipeline7-stage pipeline >15M Transistors>15M Transistors Needs 60W of PowerNeeds 60W of Power 4 Instructions/Cycle4 Instructions/Cycle Up to 1GhzUp to 1Ghz Down to .18 micronDown to .18 micron

PIC 12C804PIC 12C804 8 pins8 pins 8-bit Data Path8-bit Data Path 2-stage pipeline2-stage pipeline ~5,000 Transistors~5,000 Transistors Needs 80uW – 13mWNeeds 80uW – 13mW 1 Inst – 1 or 2 Cycles1 Inst – 1 or 2 Cycles Up to 4MhzUp to 4Mhz Down to .7 micronDown to .7 micron

Page 5: 1 PIC MicroController. 2 Fetches instructions and data from one memory. Fetches instructions and data from one memory. Limits Operating BandwidthLimits

5

                                                           

PICPIC

Developed by Arizona MicrochipDeveloped by Arizona Microchip• Different types available ranging from 18PIN DIP devices with 12 Different types available ranging from 18PIN DIP devices with 12

I/O lines, 1 timer and limited facilitiesI/O lines, 1 timer and limited facilities• Up to 68 pin devices with 3 timers, built in 6 channel ADC, PWM Up to 68 pin devices with 3 timers, built in 6 channel ADC, PWM

and serial modules. and serial modules. • We will focus on the 16F84 and the 16F877We will focus on the 16F84 and the 16F877

Development ToolsDevelopment Tools• MPLab development IDEMPLab development IDE• PICStart Plus programmerPICStart Plus programmer• PICDEM-2 demo boardPICDEM-2 demo board• PIC ICD in circuit debuggerPIC ICD in circuit debugger• PIC-ICE In circuit emulatorPIC-ICE In circuit emulator

Page 6: 1 PIC MicroController. 2 Fetches instructions and data from one memory. Fetches instructions and data from one memory. Limits Operating BandwidthLimits

6

                                                           

PIC Architecture - OverviewPIC Architecture - Overview

12-bit, 14-bit or 16-bit Instruction words 12-bit, 14-bit or 16-bit Instruction words Data and Instruction areas are separateData and Instruction areas are separate 8-bit datapath8-bit datapath External clock is internally divided by 4. (e.g. ck External clock is internally divided by 4. (e.g. ck

external 4 MHz = ck internal 1 MHz = 1us/instr)external 4 MHz = ck internal 1 MHz = 1us/instr) Instructions take 1 cycle (1 us) to complete Instructions take 1 cycle (1 us) to complete

(pipeline). Sometimes take 2 cycles.(pipeline). Sometimes take 2 cycles. Single interface method to Data MemorySingle interface method to Data Memory

8-bit, RISC processor, Harvard, memory, I/O 8-bit, RISC processor, Harvard, memory, I/O portsports

Page 7: 1 PIC MicroController. 2 Fetches instructions and data from one memory. Fetches instructions and data from one memory. Limits Operating BandwidthLimits

7

PIC 1684 ProcessorPIC 1684 Processor

Page 8: 1 PIC MicroController. 2 Fetches instructions and data from one memory. Fetches instructions and data from one memory. Limits Operating BandwidthLimits

8

                                                           

PIC MicrocontrollerPIC Microcontroller

Page 9: 1 PIC MicroController. 2 Fetches instructions and data from one memory. Fetches instructions and data from one memory. Limits Operating BandwidthLimits

9

                                                           

Architecture diagramArchitecture diagram

Page 10: 1 PIC MicroController. 2 Fetches instructions and data from one memory. Fetches instructions and data from one memory. Limits Operating BandwidthLimits

10

                                                           

Why is it neat, Architecturally?Why is it neat, Architecturally?

Harvard Architecture – separate program and Harvard Architecture – separate program and data busses ease bandwidth constraints.data busses ease bandwidth constraints.

Fixed instruction widthFixed instruction width PipelinedPipelined Basic architecture is extendableBasic architecture is extendable One simple, flexible interface to memoryOne simple, flexible interface to memory Uniform instruction execution timeUniform instruction execution time Instructions are elegantInstructions are elegant

Page 11: 1 PIC MicroController. 2 Fetches instructions and data from one memory. Fetches instructions and data from one memory. Limits Operating BandwidthLimits

11

                                                           

Who uses the PIC?Who uses the PIC?

In 1990, 20In 1990, 20thth most popular microcontroller most popular microcontroller In 1997, 2In 1997, 2ndnd only to Motorola (which has a huge only to Motorola (which has a huge

customer base)customer base) Lots of smaller users and new users choose the Lots of smaller users and new users choose the

PICPIC Motorola even uses the PIC in some of its Motorola even uses the PIC in some of its

mobile phones!mobile phones!

Page 12: 1 PIC MicroController. 2 Fetches instructions and data from one memory. Fetches instructions and data from one memory. Limits Operating BandwidthLimits

12

                                                           

Peripheral Features:

13 Input/Output pins with individual controlHigh current sink/source with direct LED drive8-bit timer/counter with 8-bit programmable pre-scaler

Power Features:Operation from –55oC to +125oCVoltage Operation from 2.0V to 6.0VNeeds 80uW – 13mW (Atmel AT899C2051 minimum ?? Ckeck !!)Needs 80uW – 13mW (Atmel AT899C2051 minimum ?? Ckeck !!)

• Special features include:

In-Circuit Serial ProgrammingPower-on resetPower-up timerOscillator start-up timerWatch-dog timerPower saving SLEEP modeSelectable oscillator options

PIC FeaturesPIC Features

Page 13: 1 PIC MicroController. 2 Fetches instructions and data from one memory. Fetches instructions and data from one memory. Limits Operating BandwidthLimits

13

                                                           

PIC16F84PIC16F84

8-bit RISC (35 instructions, pipelined)8-bit RISC (35 instructions, pipelined) Program counter 13-bit (points to the current Program counter 13-bit (points to the current

instruction, automatically incremented)instruction, automatically incremented)• Stack to support subroutines/interrupts can hold 8 levels of Stack to support subroutines/interrupts can hold 8 levels of

PCPC

MemoryMemory• Program memory (FLASH) 1024, 14-bit locationsProgram memory (FLASH) 1024, 14-bit locations• Data MemoryData Memory

RAM: 68, 8-bit locationsRAM: 68, 8-bit locations EEPROM: 64, 8-bit locations (slow write access)EEPROM: 64, 8-bit locations (slow write access)

Page 14: 1 PIC MicroController. 2 Fetches instructions and data from one memory. Fetches instructions and data from one memory. Limits Operating BandwidthLimits

14

                                                           

PIC16F84 cont.PIC16F84 cont.

PortsPorts

• Port B: 8 pins (can set in/out via a flag)Port B: 8 pins (can set in/out via a flag)

• Port A: 5 pins, some dual function Port A: 5 pins, some dual function Free TimerFree Timer

• counts 0,1,2...255 according to the (externally attached) clock counts 0,1,2...255 according to the (externally attached) clock oscillator - or according to a signal on pin RA4/TOCK1oscillator - or according to a signal on pin RA4/TOCK1

• Can arrange for an interrupt when it reaches 255Can arrange for an interrupt when it reaches 255 Watchdog timer (WDT)Watchdog timer (WDT)

• For automatic reset – An internal counter with an independent For automatic reset – An internal counter with an independent clock which has a time that is independent of the external clock which has a time that is independent of the external clock. Normal overflow time is 18ms but it can change clock. Normal overflow time is 18ms but it can change depending on power supply and temperature. depending on power supply and temperature. The programmer The programmer can ONLY RESET it. If the programmer does not reset it before can ONLY RESET it. If the programmer does not reset it before overflow occurs, WDT will RESET the Microcontroller and will overflow occurs, WDT will RESET the Microcontroller and will start the program again. It prevents the program of being in start the program again. It prevents the program of being in “LOOP” or gets “locked”. It can be enabled during initial “LOOP” or gets “locked”. It can be enabled during initial configuration.configuration.

Page 15: 1 PIC MicroController. 2 Fetches instructions and data from one memory. Fetches instructions and data from one memory. Limits Operating BandwidthLimits

15

                                                           

Program Memory and Data Memory for PIC16F84Program Memory and Data Memory for PIC16F84

Reset Vector

Interrupt Vector

General Use

000h

004h

3FFh

Program Memory (1Kx14-bits) Flash/ROM Data Memory (8-bits)

INDF TMR0 PCL

STATUS FSR

PORTA PORTB

EEDATA EEADR PCLATH INTCON

RAM

General Use – 68

Bytes

Not Available

INDF OPTION

PCL STATUS

FSR TRISA TRISB

EECON1 EECON2 PCLATH INTCON

RAM

Mem Mirror Bank 0

Not Available

000h 001h 002h 003h 004h 005h 006h 007h 008h 009h 00Ah 00Bh 00Ch

04Fh

050h

07Fh

080h 081h 082h 083h 084h 085h 086h 087h 088h 089h 08Ah 08Bh 08Ch

0CFh

0D0h

0FFh

Bank 0 Bank 1

INDF and FSR – Used for Indirect Addressing

TMR0 – Counter in Memory

PCL and PCLATH – Program Counter

STATUS – CPU general status bits

OPTION – Config. options of microcontroller

TRISA and TRISB – Configurate ports as In or Out

EECON1 and EECON2 – EEPROM Config/ Int and Error

EEDATA and EEADR – EEPROM R/W addr and data

INTCON – Configure and Identify Interrupts

Page 16: 1 PIC MicroController. 2 Fetches instructions and data from one memory. Fetches instructions and data from one memory. Limits Operating BandwidthLimits

16

                                                           

SubroutinesSubroutines

No general purpose stackNo general purpose stack 2-level hardware stack for PC only (it was 2-level hardware stack for PC only (it was

increased in later PIC versions)increased in later PIC versions) ““call” pushes PC onto stack, “return” pops it call” pushes PC onto stack, “return” pops it

back offback off PIC programmers don’t do recursion PIC programmers don’t do recursion

Page 17: 1 PIC MicroController. 2 Fetches instructions and data from one memory. Fetches instructions and data from one memory. Limits Operating BandwidthLimits

17

                                                           

Interrupts on PIC16F84Interrupts on PIC16F84

SourcesSources• Timer interrupt from counter reaching 255Timer interrupt from counter reaching 255• External interrupt on pin RB0/INTExternal interrupt on pin RB0/INT• Interrupts on RB4,5,6,7 pinsInterrupts on RB4,5,6,7 pins• Termination of EEPROM writeTermination of EEPROM write

Each of these can be set/unset by certain flag registersEach of these can be set/unset by certain flag registers Also a global set/unsetAlso a global set/unset When there is a signal causing an interruptWhen there is a signal causing an interrupt AutomaticallyAutomatically

• all (further) interrupts are disabledall (further) interrupts are disabled• present value of program counter is pushed onto the stackpresent value of program counter is pushed onto the stack• set PC to 0004h set PC to 0004h

0004h is the address at which the subroutine to service 0004h is the address at which the subroutine to service the interrupt startsthe interrupt starts

Page 18: 1 PIC MicroController. 2 Fetches instructions and data from one memory. Fetches instructions and data from one memory. Limits Operating BandwidthLimits

18

                                                           

PIC CharacteristicsPIC Characteristics

PIC's Arithmetic and Logic Unit (ALU) is 8 bits wide and has a PIC's Arithmetic and Logic Unit (ALU) is 8 bits wide and has a single accumulator called thesingle accumulator called the working registerworking register or or W registerW register. .

Two-operand arithmetic and logic instructions take W as one operand and Two-operand arithmetic and logic instructions take W as one operand and a file register or a literal (constant) as the second operand.a file register or a literal (constant) as the second operand. In the case of W In the case of W and a file register as operands, one bit in the instruction selects the and a file register as operands, one bit in the instruction selects the destination of the result, which can be either the working register W (value destination of the result, which can be either the working register W (value 0) or the file register (value 1). 0) or the file register (value 1).

This destination is generically called This destination is generically called d d and specifically called and specifically called ww or or ff by the by the assembler. For example, the instruction assembler. For example, the instruction addwf fr1, waddwf fr1, w adds file register adds file register fr1 fr1 and and WW leaving the result in leaving the result in WW, while , while addwf fr1, faddwf fr1, f   does the same addition, does the same addition, but leaves the result in file register but leaves the result in file register fr1fr1. .

This allows some unconventional operations such as This allows some unconventional operations such as subwf fr1, wsubwf fr1, w which which performs the operation:  performs the operation:  fr1 -  w  => w. fr1 -  w  => w.

NOTE: DEC and Intel notations for Assembly Language:NOTE: DEC and Intel notations for Assembly Language:• Intel => SUB A, R1 => A = A - R1Intel => SUB A, R1 => A = A - R1

• DEC => SUB A, R1 => A - R1 = R1 (PIC uses this notation)DEC => SUB A, R1 => A - R1 = R1 (PIC uses this notation)

Page 19: 1 PIC MicroController. 2 Fetches instructions and data from one memory. Fetches instructions and data from one memory. Limits Operating BandwidthLimits

19

PIC Mid-range Microcontrollers - InstructionsPIC Mid-range Microcontrollers - Instructions

Page 20: 1 PIC MicroController. 2 Fetches instructions and data from one memory. Fetches instructions and data from one memory. Limits Operating BandwidthLimits

                                                           

The PIC Family: CoresThe PIC Family: Cores

PICs come with 1 of 4 CPU ‘cores’:PICs come with 1 of 4 CPU ‘cores’:

12bit12bit cores with 33 instructions: cores with 33 instructions: 12C50x, 16C5x12C50x, 16C5x

14bit14bit cores with 35 instructions: cores with 35 instructions: 12C67x,16Cxxx12C67x,16Cxxx

16bit16bit cores with 58 instructions: cores with 58 instructions: 17C4x,17C7xx17C4x,17C7xx

‘‘Enhanced’ 16bitEnhanced’ 16bit cores with 77 instructions: cores with 77 instructions: 18Cxxx 18Cxxx

Page 21: 1 PIC MicroController. 2 Fetches instructions and data from one memory. Fetches instructions and data from one memory. Limits Operating BandwidthLimits

                                                           

The PIC Family: SpeedThe PIC Family: Speed

PICs require a clock to work.PICs require a clock to work.

Can use crystals, clock oscillators, or even an RC circuit.Can use crystals, clock oscillators, or even an RC circuit. Some PICs have a built in 4MHz RC clockSome PICs have a built in 4MHz RC clock

Not very accurate, but requires no external components!Not very accurate, but requires no external components! Instruction speed = 1/4 clock speed (TInstruction speed = 1/4 clock speed (Tcyccyc = 4 * T = 4 * Tclkclk) ) All PICs can be run from DC to their maximum spec’d speed:All PICs can be run from DC to their maximum spec’d speed:

12C50x12C50x 4MHz 4MHz

12C67x12C67x 10MHz10MHz

16Cxxx16Cxxx 20MHz20MHz

17C4x / 17C7xxx17C4x / 17C7xxx 33MHz33MHz

18Cxxx18Cxxx 40MHz40MHz

Page 22: 1 PIC MicroController. 2 Fetches instructions and data from one memory. Fetches instructions and data from one memory. Limits Operating BandwidthLimits

                                                           

The PIC Family: PeripheralsThe PIC Family: Peripherals

Different PICs have different on-chip Different PICs have different on-chip peripheralsperipherals

Some common peripherals are:Some common peripherals are:• Tri-state (“floatable”) digital I/O pinsTri-state (“floatable”) digital I/O pins

• Analog to Digital Converters (ADC) (8, 10 and 12bit, 50ksps)Analog to Digital Converters (ADC) (8, 10 and 12bit, 50ksps)

• Serial communications: UART (RS-232C), SPI, ISerial communications: UART (RS-232C), SPI, I22C, CANC, CAN

• Pulse Width Modulation (PWM) (10bit)Pulse Width Modulation (PWM) (10bit)

• Timers and counters (8 and 16bit)Timers and counters (8 and 16bit)

• Watchdog timers, LCD driversWatchdog timers, LCD drivers

Page 23: 1 PIC MicroController. 2 Fetches instructions and data from one memory. Fetches instructions and data from one memory. Limits Operating BandwidthLimits

                                                           

PIC Peripherals: USART: USRTPIC Peripherals: USART: USRT Synchronous communication: i.e., with clock signalSynchronous communication: i.e., with clock signal

SPI = Serial Peripheral InterfaceSPI = Serial Peripheral Interface• 3 wire: Data in, Data out, Clock3 wire: Data in, Data out, Clock

• Master/Slave (can have multiple masters)Master/Slave (can have multiple masters)

• Very high speed (1.6Mbps)Very high speed (1.6Mbps)

• Full speed simultaneous send and receive (Full duplex)Full speed simultaneous send and receive (Full duplex)

II22C = Inter ICC = Inter IC• 2 wire: Data and Clock2 wire: Data and Clock

• Master/Slave (Single master only; multiple masters clumsy)Master/Slave (Single master only; multiple masters clumsy)

• Lots of cheap ILots of cheap I22C chips available; typically < 100kbpsC chips available; typically < 100kbps(For example, 8pin EEPROM chips, ADC, DACs, etc.)(For example, 8pin EEPROM chips, ADC, DACs, etc.)

Page 24: 1 PIC MicroController. 2 Fetches instructions and data from one memory. Fetches instructions and data from one memory. Limits Operating BandwidthLimits

                                                           

PIC Peripherals: TimersPIC Peripherals: Timers

Available in all PICs.Available in all PICs. 14+bit cores may generate interrupts on timer overflow.14+bit cores may generate interrupts on timer overflow. Some 8bits, some 16bits, some have prescalersSome 8bits, some 16bits, some have prescalers Can use external pins as clock in/clock outCan use external pins as clock in/clock out

(ie, for counting events or using a different Fosc)(ie, for counting events or using a different Fosc) Warning: some peripherals share Timer resourcesWarning: some peripherals share Timer resources

Page 25: 1 PIC MicroController. 2 Fetches instructions and data from one memory. Fetches instructions and data from one memory. Limits Operating BandwidthLimits

                                                           

PIC Peripherals: Misc.PIC Peripherals: Misc. Sleep Mode: PIC shuts down until external interrupt (or internal Sleep Mode: PIC shuts down until external interrupt (or internal

timer) wakes it up.timer) wakes it up. Interrupt on pin change: Generate an interrupt when a digital input Interrupt on pin change: Generate an interrupt when a digital input

pin changes state (for example, interrupt on keypress).pin changes state (for example, interrupt on keypress). Watchdog timer: Resets chip if not cleared before overflowWatchdog timer: Resets chip if not cleared before overflow Brown out detect: Resets chip at a known voltage levelBrown out detect: Resets chip at a known voltage level LCD drivers: Drives simple LCD displaysLCD drivers: Drives simple LCD displays Future: CAN bus, 12bit ADC, better analog functionsFuture: CAN bus, 12bit ADC, better analog functions

VIRTUAL PERIPHERALS:VIRTUAL PERIPHERALS:• Peripherals programmed in software. UARTS, timers, and more can be done in Peripherals programmed in software. UARTS, timers, and more can be done in

software (but it takes most of the resources of the machine)software (but it takes most of the resources of the machine)

Page 26: 1 PIC MicroController. 2 Fetches instructions and data from one memory. Fetches instructions and data from one memory. Limits Operating BandwidthLimits

                                                           

Selecting your PICSelecting your PIC See Microchip Line card for the entire list of PICs :See Microchip Line card for the entire list of PICs :

http://www.microchip.com/10/Lit/rLit/00148d1/index.htmhttp://www.microchip.com/10/Lit/rLit/00148d1/index.htm

See the Digikey catalog for pricing information.See the Digikey catalog for pricing information.http://www.digikey.comhttp://www.digikey.com

Page 27: 1 PIC MicroController. 2 Fetches instructions and data from one memory. Fetches instructions and data from one memory. Limits Operating BandwidthLimits

                                                           

Low End: 12C508Low End: 12C508 8pin package (DIP, SO)8pin package (DIP, SO) 12bit core - 33 instructions12bit core - 33 instructions 1us instruction time (Tclk = 4MHz)1us instruction time (Tclk = 4MHz) 512 12bit 512 12bit programprogram memory memory 25 8bit 25 8bit datadata memory or registers (“File memory or registers (“File

registers”)registers”) 2 level hardware stack (no interrupts)2 level hardware stack (no interrupts) 5 GPIO pins, 1 input only (25mA 5 GPIO pins, 1 input only (25mA

source/sink)source/sink) Features: Features: Internal pullups, wake up on pin Internal pullups, wake up on pin

change, internal oscillatorchange, internal oscillator Peripherals: Peripherals: Timer, Watch Dog TimerTimer, Watch Dog Timer $1.88$1.88(1), $1.25(100), $9.65(W)(1), $1.25(100), $9.65(W)

Page 28: 1 PIC MicroController. 2 Fetches instructions and data from one memory. Fetches instructions and data from one memory. Limits Operating BandwidthLimits

                                                           

Mid Range: 16F876Mid Range: 16F876 28pin package (DIP, SO)28pin package (DIP, SO) 14bit core - 35 instructions14bit core - 35 instructions 200ns instruction time (Tclk = 20MHz)200ns instruction time (Tclk = 20MHz) 8,092 14bit 8,092 14bit FLASHFLASH programprogram memory memory 368 8bit 368 8bit datadata memory or registers memory or registers

(“File registers”)(“File registers”) 256 8bit 256 8bit EEPROMEEPROM (nonvolatile) data (nonvolatile) data

registersregisters 8 level hardware stack (interrupts 8 level hardware stack (interrupts

enabled)enabled) 22 GPIO (20mA source / 25mA 7sink)22 GPIO (20mA source / 25mA 7sink) Peripherals: 5ch 10bit ADC, Peripherals: 5ch 10bit ADC,

USART/I2C/SPI, 16bit & 8bit timersUSART/I2C/SPI, 16bit & 8bit timers Features: Brown out detect, Features: Brown out detect, In-Circuit In-Circuit

Debugger (ICD)Debugger (ICD) $11.00(1), $5.89(100)$11.00(1), $5.89(100)

Page 29: 1 PIC MicroController. 2 Fetches instructions and data from one memory. Fetches instructions and data from one memory. Limits Operating BandwidthLimits

                                                           

High End: 17C766High End: 17C766 84pin PLCC package84pin PLCC package 16bit core - 58 instructions16bit core - 58 instructions 121ns instruction time (Tclk = 121ns instruction time (Tclk =

33MHz)33MHz) 16,384 16bit 16,384 16bit programprogram memory memory 902 8bit 902 8bit datadata memory or registers memory or registers 16 level hardware stack (priority 16 level hardware stack (priority

interrupts)interrupts) 66 GPIO (20mA source / 35mA sink)66 GPIO (20mA source / 35mA sink) Features: Features: 8x8 multiply8x8 multiply, BOD, , BOD,

microprocessor modemicroprocessor mode Peripherals:Peripherals:

• 2x 16bit + 2x 8bit timer, WDT, 2x 16bit + 2x 8bit timer, WDT, 2x 2x USARTUSART, 4x CCP, , 4x CCP,

• 12ch 10bit ADC, 12ch 10bit ADC, $20.25(1), $10.53(100), $18.38(W)$20.25(1), $10.53(100), $18.38(W)

Page 30: 1 PIC MicroController. 2 Fetches instructions and data from one memory. Fetches instructions and data from one memory. Limits Operating BandwidthLimits

                                                           

12C508, 16F876, 17C766 Uses12C508, 16F876, 17C766 Uses 12C50812C508

• Inexpensive controllers, glue logic, simple tasksInexpensive controllers, glue logic, simple tasks

• E.g., quadrature decoding, digital interfacingE.g., quadrature decoding, digital interfacing

16F87616F876• Multitasking programs, serial communicationMultitasking programs, serial communication

• E.g., Cheap data acquisition system and digital I/O system for PC off E.g., Cheap data acquisition system and digital I/O system for PC off COM ports, data loggingCOM ports, data logging

17C76617C766• RTOS, low end DSP, communications, big moosey applicationsRTOS, low end DSP, communications, big moosey applications

• E.g., FEC converter, Rocket Flight Computer, cheap FFT chipE.g., FEC converter, Rocket Flight Computer, cheap FFT chip

Page 31: 1 PIC MicroController. 2 Fetches instructions and data from one memory. Fetches instructions and data from one memory. Limits Operating BandwidthLimits

                                                           

Getting ready to code!Getting ready to code!

ALWAYSALWAYS have the data sheet for your PIC: have the data sheet for your PIC:

http://www.microchip.com/ http://www.microchip.com/

There are just too many details you have to know!There are just too many details you have to know!

Example: See PIC12C508 data sheetExample: See PIC12C508 data sheet

Page 32: 1 PIC MicroController. 2 Fetches instructions and data from one memory. Fetches instructions and data from one memory. Limits Operating BandwidthLimits

                                                           

Cool ThingsCool Things Application Notes - www.microchip.comApplication Notes - www.microchip.com

• Almost everything you could imagineAlmost everything you could imagine RTOS for the 17CXXX familyRTOS for the 17CXXX family DSP for the 16CXX family - Inc. FFTs and IIR filtersDSP for the 16CXX family - Inc. FFTs and IIR filters Micropower applicationsMicropower applications All sorts of tricks and tips and in depth explanationsAll sorts of tricks and tips and in depth explanations

• Code listed in the notes is available as well!Code listed in the notes is available as well!

PIC BooksPIC Books• Desbravando o PIC – Editora Erica – David José de Souza (portuguese)Desbravando o PIC – Editora Erica – David José de Souza (portuguese)

• Introduction to PICs (Predko)Introduction to PICs (Predko)

Page 33: 1 PIC MicroController. 2 Fetches instructions and data from one memory. Fetches instructions and data from one memory. Limits Operating BandwidthLimits

33

                                                           

PIC Assembly LanguagePIC Assembly Language

The PIC16F8X adopts the PDP11 paradigm (for the destination designator d is the The PIC16F8X adopts the PDP11 paradigm (for the destination designator d is the second operand in a two register operand instruction) in a non-orthogonal way, second operand in a two register operand instruction) in a non-orthogonal way, however, as the above three different mov instructions clearly show. It would be however, as the above three different mov instructions clearly show. It would be much clearer to write, for example:  mov fr, w,   mov w, fr and mov # literal, w (as did much clearer to write, for example:  mov fr, w,   mov w, fr and mov # literal, w (as did the PDP11). the PDP11).

As an example, (adapted from PIC's datasheet) this program fragment fills the 68 General As an example, (adapted from PIC's datasheet) this program fragment fills the 68 General Purpose Registers (GPR) addresses 0xC thru 0x4F, with the constant Purpose Registers (GPR) addresses 0xC thru 0x4F, with the constant

oxFF:    oxFF:    movlw    0xc movlw    0xc  ;  oxc => w;  oxc => w

      movwf    FSR movwf    FSR  ; 0xc => FSR; 0xc => FSR

loop:loop:

     movlw    0x50 movlw    0x50  ; 0x50 => W (last GPR number + 1); 0x50 => W (last GPR number + 1)

     clrf    INDF clrf    INDF  ;clear memory at address (FSR);clear memory at address (FSR)

     decf INDF,1decf INDF,1 ; set memory at addr (FSR) to FF; set memory at addr (FSR) to FF

     incf  FSR, 1 incf  FSR, 1  ; FSR points to next file register; FSR points to next file register

     subwf    FSR, w subwf    FSR, w  ; (FSR) - 50h => W; (FSR) - 50h => W

     bnz loopbnz loop ; if result # 0 goto loop; if result # 0 goto loop

Page 34: 1 PIC MicroController. 2 Fetches instructions and data from one memory. Fetches instructions and data from one memory. Limits Operating BandwidthLimits

34

                                                           

PIC – More ExamplesPIC – More Examples

As a more elaborate example of pointer addressing with INDF and FSR, this As a more elaborate example of pointer addressing with INDF and FSR, this programprogram computes the computes the first few elements of the Fibonacci sequence (recall from your Math classes that the Fibonacci first few elements of the Fibonacci sequence (recall from your Math classes that the Fibonacci sequence is computed using the last two elements to find the next one: you start with the first sequence is computed using the last two elements to find the next one: you start with the first two elements 0 and 1 and next you get: 1, 2, 3, 5, 8, 13, 21, 34, and so on). The xchg macro fits two elements 0 and 1 and next you get: 1, 2, 3, 5, 8, 13, 21, 34, and so on). The xchg macro fits nicely into this example. You can also look at the program code below: count, nicely into this example. You can also look at the program code below: count, f0f0 and and f1f1 are are scratchpad variables; computed Fibonacci numbers are stored in a table starting at file register scratchpad variables; computed Fibonacci numbers are stored in a table starting at file register fibfib; ; f0f0 and and f1f1 store the last two computed Fibonacci numbers; up to 12 Fibonacci numbers store the last two computed Fibonacci numbers; up to 12 Fibonacci numbers numbers can be computed with 8 bit precision. numbers can be computed with 8 bit precision.

Computing the first 12 Fibonacci numbers: Computing the first 12 Fibonacci numbers:     movlw fibmovlw fib ; table address => w; table address => w    movwf FSRmovwf FSR ; table address => FSR; table address => FSR    movl d'12', wmovl d'12', w ; compute 12 Fibonacci numbers; compute 12 Fibonacci numbers    mov w, countmov w, count ; count them,; count them,    clrf f0 clrf f0  ; 1st Fibonacci number is 0; 1st Fibonacci number is 0    clrf f1clrf f1   incf f1incf f1 ; 2nd Fibonacci number is 1; 2nd Fibonacci number is 1loop:loop:      mov f0, wmov f0, w ;  f0 =>w;  f0 =>w   add f1, wadd f1, w ; f0+f1 =>w; f0+f1 =>w   movwf INDFmovwf INDF ; store f0 + f1 in current table entry; store f0 + f1 in current table entry      xchg f1, wxchg f1, w ; f1=> w,   f0+f1 =>f1; f1=> w,   f0+f1 =>f1      mov w, f0mov w, f0 ; move previous f1 value to f0; move previous f1 value to f0      incf FSRincf FSR ; FSR points no next table entry; FSR points no next table entry   decbnz count,loopdecbnz count,loop ;count-1 => count,   if # 0 goto loop;count-1 => count,   if # 0 goto loop

Page 35: 1 PIC MicroController. 2 Fetches instructions and data from one memory. Fetches instructions and data from one memory. Limits Operating BandwidthLimits

35

                                                           

PIC -FSRPIC -FSR

La primera posición (00H) de la La primera posición (00H) de la memoria RAM, no esta implementada memoria RAM, no esta implementada físicamente, y es la llamada dirección físicamente, y es la llamada dirección indirecta.indirecta.Si en cualquier instrucción se opera Si en cualquier instrucción se opera con la dirección 00H, en realidad se con la dirección 00H, en realidad se estará operando con la dirección a la estará operando con la dirección a la que apunte el contenido del registro que apunte el contenido del registro FSRFSR ubicado en la posición 04H de la ubicado en la posición 04H de la RAM RAM El registro El registro FSRFSR además de servir de además de servir de para seleccionar el banco, sirve como para seleccionar el banco, sirve como puntero para este tipo de puntero para este tipo de direccionamiento.direccionamiento.Para seleccionar el banco, se usa el Para seleccionar el banco, se usa el bit de más pero del registro FSR y el bit de más pero del registro FSR y el bit IRP del registro de estado.bit IRP del registro de estado.Por ejemplo si el FSR contiene el valor Por ejemplo si el FSR contiene el valor 14, una instrucción que opere sobre la 14, una instrucción que opere sobre la dirección 0, operará en realidad sobre dirección 0, operará en realidad sobre la dirección 14.la dirección 14.Se puede decir en este ejemplo que la Se puede decir en este ejemplo que la posición 14 de memoria RAM fue posición 14 de memoria RAM fue direccionada en forma indirecta a direccionada en forma indirecta a través del puntero FSR. través del puntero FSR.

Page 36: 1 PIC MicroController. 2 Fetches instructions and data from one memory. Fetches instructions and data from one memory. Limits Operating BandwidthLimits

36

                                                           

PIC-TEMPOPIC-TEMPO

En este ejemplo contemplaremos la utilidad del temporizador, y el En este ejemplo contemplaremos la utilidad del temporizador, y el respectivo señalizador T0IF que se activa por desbordamiento del respectivo señalizador T0IF que se activa por desbordamiento del registro TMR0, nuevamente pido paciencia para esperar que cargue registro TMR0, nuevamente pido paciencia para esperar que cargue el esquema animado.el esquema animado.EL valor que se carga e el registro OPTION, corresponde a la EL valor que se carga e el registro OPTION, corresponde a la configuración del registro TMR0 como temporizador, un predivisor configuración del registro TMR0 como temporizador, un predivisor de frecuencia con un rango de 256 y asignado al TMR0.de frecuencia con un rango de 256 y asignado al TMR0.

AnalicemosAnalicemos Este ejercicio pretende temporizar un segundo, de tal manera que Este ejercicio pretende temporizar un segundo, de tal manera que cada segundo se apagen y se enciendan leds conectados al puerto cada segundo se apagen y se enciendan leds conectados al puerto B.B.En el programa cargamos al registro TMR0 con cualquier valor, en En el programa cargamos al registro TMR0 con cualquier valor, en este caso con un valor decimal de 216; entonces en la fórmula de este caso con un valor decimal de 216; entonces en la fórmula de temporización tendremos un valor de 39, que es el valor que le falta temporización tendremos un valor de 39, que es el valor que le falta el TMR0 para desbordarse (llegar a 255).el TMR0 para desbordarse (llegar a 255).Configurado el predivisor con un rango de 256, solamente haría Configurado el predivisor con un rango de 256, solamente haría falta un registro auxiliar falta un registro auxiliar auxaux cargado con un valor de 100 para cargado con un valor de 100 para alcanzar el segundoalcanzar el segundoComprobando tenemos: 100x39x256 = 0.99seg, aproximadamente 1 Comprobando tenemos: 100x39x256 = 0.99seg, aproximadamente 1 segundo.segundo.Cada vez que se desborda el TMR0, se activa el señalizador T0IF (bit Cada vez que se desborda el TMR0, se activa el señalizador T0IF (bit 2 del registro INTCON), y explorando la instrucción btfss se salta a 2 del registro INTCON), y explorando la instrucción btfss se salta a la instrucción: la instrucción: decfsz aux,1decfsz aux,1Esta nueva instrucción significa, Esta nueva instrucción significa, decrementar el registro f y saltar si Z=1. Es decir decrementa una decrementar el registro f y saltar si Z=1. Es decir decrementa una unidad al registro aux y el nuevo valor se deposita en el mismo unidad al registro aux y el nuevo valor se deposita en el mismo registro aux.registro aux.Si fuera: Si fuera: decfsz aux,0decfsz aux,0EL valor decrementado no se depositaría en EL valor decrementado no se depositaría en aux, sino en el registro de trabajo W.aux, sino en el registro de trabajo W.

Cada 39x256 veces se decrementa en uno el valor de auxCada 39x256 veces se decrementa en uno el valor de auxEn el preciso instante en que aux = 0; se activa el En el preciso instante en que aux = 0; se activa el bit Zbit Z (bit 2 del (bit 2 del registro de estado STATUS).registro de estado STATUS).El bit Z se pone a 1 cuando una operación de la ALU es 0. El bit Z se pone a 1 cuando una operación de la ALU es 0.

Page 37: 1 PIC MicroController. 2 Fetches instructions and data from one memory. Fetches instructions and data from one memory. Limits Operating BandwidthLimits

37

                                                           

Page 38: 1 PIC MicroController. 2 Fetches instructions and data from one memory. Fetches instructions and data from one memory. Limits Operating BandwidthLimits

38

                                                           

Where can I find more info?Where can I find more info?

http://www.microchip.comhttp://www.microchip.com John Peatman’s excellent ECE4175 classJohn Peatman’s excellent ECE4175 class

• And corresponding excellent bookAnd corresponding excellent book

http://www.piclist.comhttp://www.piclist.com http://www.geocities.com/picmaniaco/indice.htmlhttp://www.geocities.com/picmaniaco/indice.html

Page 39: 1 PIC MicroController. 2 Fetches instructions and data from one memory. Fetches instructions and data from one memory. Limits Operating BandwidthLimits

39

                                                           

LiteratureLiterature

“Design with PIC Microcontrollers” by John B. Peatman, published by Prentice Hall, ISBN 0-13-759259-0.

"The C Programming Language - Second Edition", Brian W. Kernigan & Dennis M. Ritchie, Prentice Hall, 1988.

Neuron C, http://www.echelon.com

“Programming Embedded Systems, in C and C++”, M. Barr, publ. byO’Reilly, ISBN 1-56592-354-5

“The Art of Electronics” by P. Horowitz and W.Hill. Published by Cambridge University Press, ISBN 0-521-37095-7