94
Embedded Hardware

Pic

Embed Size (px)

Citation preview

Page 1: Pic

Embedded Hardware

Page 2: Pic

Embedded System Hardware

Embedded system hardware is used for processing of input to produce output in task specific fashion

Input Interface

Information Processing

System

OutputInterface

Page 3: Pic

Processors

Key requirements:

Energy-efficiency

High Code Density

Microprocessors and Micro-controllers

Page 4: Pic

CPU

General-Purpose Micro-processor

RAM ROM I/O Port

TimerSerial Port

Data Bus

Address Bus

General-Purpose Microprocessor System

Microprocessors

CPU for ComputersNo RAM, ROM, I/O on CPU chip itselfExample: Intel’s x86, Motorola’s 680x0

Many chips on mother-board

Page 5: Pic

What is Micro-controller?Basically, a micro-controller is a device which integrates a number of the components of a microprocessor system onto a single microchip. A micro-controller combines onto the same microchip:

The CPU core Memory (both ROM and RAM) Some parallel digital I/O & more

Page 6: Pic

Micro-controller

Source: www.ami.bolton.uk

Page 7: Pic

Components of a Micro-controller

A Timer module to allow the micro-controller to perform tasks for certain time periods. A serial I/O port to allow data to flow between the micro-controller and other devices such as a PC or another micro-controller. An ADC to allow the micro-controller to accept analogue input data for processing.

Page 8: Pic

Micro-controller

Source : An Introduction to the design of small-scale embedded systems , Tim Wilmshurst, palgrave 2001

Page 9: Pic

Why Micro-controller?Low cost, small packagingLow power consumptionProgrammable, re-programmableLots of I/O capabilitiesEasy integration with circuitsFor applications in which cost, power and space are criticalSingle-purpose

Page 10: Pic

Basics of Architecture

Page 11: Pic

VonNeuman Architecture

Only one bus between CPU and memoryRAM and program memory share the same bus and the same memory, and so must have the same bit widthBottleneck: Getting instructions interferes with accessing RAM ProgramProgram

and Dataand DataMemoryMemory

BUSBUSCPUCPU

Page 12: Pic

Harvard Architecture

Separate program bus and data bus: can be different widths!

Instruction Pipelining easy

ProgramProgramMemoryMemory

CPUCPU

DataDataMemoryMemory

8-Bits8-Bits

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

Page 13: Pic

CISC – Complex Instruction Set Computer

A large number of instructions each carrying out a different permutation of the same operationInstructions provide for complex operationsDifferent instructions of different formatDifferent instructions of different lengthDifferent addressing modesRequires multiple cycles for execution

Page 14: Pic

RISC – Reduced Instruction Set Computer

Instructions for simple operations that can be executed in a single cycleEach instruction of fixed length

Facilitates instruction pipelining

Large general purpose register setCan contain data or address (symmetry)

Load-store ArchitectureNo memory access for data processing instructions

Page 15: Pic

PIC Micro-controller Family

One of the Leading Architectures for low end

applications

Page 16: Pic

PIC Architecture

PICs are “RISC”Reduced Instruction Set Computer

(RISC) Few instructions (usually < 50)Only a few addressing modesExecutes 1 instruction in 1 internal clock cycle (Tcyc)

Page 17: Pic

The PIC Family: Packages

PICs come in a huge variety of packages:

Examples:8 pin : 12C50x (12bit) and 12C67x (14bit)18pin : 16C5X (12bit), 16Cxxx (14bit)28pin : 16C5X (12bit), 16Cxxx (14bit)40pin : 16Cxxx (14bit), 17C4x (16bit)44 - 68pin : 16Cxxx (14bit), 17C4x / 17Cxxx

(16bit)

Page 18: Pic

PIC Mid-range Block Diagram

Ref: PIC architecture reference manual

Page 19: Pic

Peripheral Components

Page 20: Pic

The PIC Family: Speed

PICs require a clock to work.

Can use crystals, clock oscillators, or even an RC circuit.

Some PICs have a built in 4MHz RC clock Not very accurate, but requires no

external components! Instruction speed = 1/4 clock speed

(Tcyc = 4 * Tclk)

Page 21: Pic

Clock Frequency Examples

12C50x 4MHz12C67x 10MHz16Cxxx 20MHz17C4x / 17C7xxx 33MHz18Cxxx 40MHz

Page 22: Pic

Clocking Scheme

Ref: PIC architecture reference manual

Page 23: Pic

Instruction ExecutionClock internally divided by 4 to generate 4 quadrature clocks Instruction cycle consist of 4 Q cyclesPC incremented every Q1Instruction is fetched from program and latched into instruction register by Q4Instruction is decoded and executed in the following Q1 to Q4

Page 24: Pic

Instruction PipeliningFetch takes one cycle, decode and execute takes another cycleWhile execution, next instruction can be fetched

No bus conflict due to Harvard Architecture

If instruction changes PC ( e.g. Branch) extra cycle is required to complete instruction

Page 25: Pic

ALU

d: destination bit

W: working register

Ref: PIC architecture reference manual

Page 26: Pic

Status RegisterStatus register contains

Arithmetic status of ALU operationRESET statusMemory bank select bits

TO: time out; PD: power Down; IRP, RP1, RP0: bank select; Z: zero, DC:digit carry (BCD). C: carry

Page 27: Pic

Memory Organization

Program Memory

Data Memory

Access to both possible in each cycle because of distinct bus

Page 28: Pic

The PIC Family: Program Memory

EPROM (Erasable Programmable Read Only Memory) One Time Programmable (OTP) chips

are EPROM chips, but with no window!

PIC Examples: Any ‘C’ part: 12C50x, 17C7xx, etc.

Page 29: Pic

Program MemoryFLASH

Re-writable (even by chip itself) Much faster to develop on! Finite number of writes (~100k Writes) PIC Examples: Any ‘F’ part: 16F84,

16F87x, 18Fxxx (future) PIC program space is different

for each chip.

Page 30: Pic

Program MemoryMid-range PIC processors have 13 bit Program CounterWidth of program memory bus 14 bitsProgram memory space divided into 4 pages of 2K each

Page 31: Pic

Memory Map

Ref: PIC reference manual

PCLATH (program counter latch high): to jump from one page to another these bits modified

Page 32: Pic

StackMid-range PIC 8-level deep 13 bit wide hardware stack

Not part of program or data memory

PC is pushed onto stack when CALL instruction is executed or Interrupt occursPCLATH is not modified when PUSHed to or POPed from stack

Page 33: Pic

The PIC Family: Data Memory

PICs use general purpose “file registers” for RAM

(each register is 8 bits for all PICs)Programs are stored in program space (not in data space), so low RAM space.

Register File Memory Consist of 2 Components

General Purpose Register (GPR) Files Special Purpose Register (SPR) files

Memory organised into banks16F877 has 4 banks of register

Page 34: Pic

Registers

GPR: Area banked to provide greater than 96 bytes of general purpose RAM

SFR: To control the peripheral and core functions like indirect addressing

Page 35: Pic

SummaryWe have reviewed architectural featuresUnderstood features of processor core of the PIC family of micro-controllersWe shall look at instruction set and peripheral components in the next class

Page 36: Pic

PIC: Instruction SetSimple instruction set : about 35 instructionsInstruction set grouped into 3 categories:

Byte-oriented operationsBit-oriented operationsLiteral and Control operations

Instructions : 14 bit (mid-range)All instructions take one cycle unless conditional test is true or PC is changed as a result of an instruction

Page 37: Pic

Instruction format

Byte-oriented Operation0..6 : 7 bit file register address

7 : d bit ; 0 for destination W8..13: opcode

Bit-oriented Operation0..6: 7 bit file register address7..9: 3-bit bit address within the 8-bit file register10..13: opcode

Page 38: Pic

Instruction FormatLiteral and Control Operations

General0..7 : 8 bit literal (immediate) value8..13: opcode

CALL & GOTO instructions0..10: 11 bit literal value (target address)Upper 2 bits of PC loaded from PCLATH<4:3>11..13: opcode

Page 39: Pic

Addressing ModesDirect Addressing

Ref: PIC reference manual

in status register

Page 40: Pic

Indirect AddressingFull 8-bit register file address is first written into FSR, a special purpose registerFSR serves as address pointer to any address through out the entire register fileSubsequent direct access of INDF (a SFR) will actually access the register file using the content of FSR as a pointer to the location of operand

Page 41: Pic

Indirect Addressing

in status register

Ref: PIC reference manual

Page 42: Pic

InstructionsByte oriented operations

Arithmetic and logical operationsData Movement

Examplesaddwf f,d

Add contents of W with register f, if d=0 store result in W else store in register f; e.g.: addwf 0x20,0

clrf f Contents of register f are cleared and Z bit

(STATUS) is set; e.g.: clrf 0x30movwf f

Move data from W register to register f e.g : movwf 0x04

Page 43: Pic

More Byte oriented instructions

decfsz f,d conditional branching Decrement register f, place result in

f or W depending on value of d; Skip the next instruction if result is zero

e.g.: decfsz 0x20,1

decf f,d Decrement f, place result depending

on value of d, effects Z flag e.g : decf 0x30,0

Page 44: Pic

Literal OperationsImmediate addressing modeExamples

addlw kAdd literal k to register We.g: addlw 0x05

movlw k Move literal k into register W

e.g : movlw 0x21

Page 45: Pic

More on Data transfer Instructions

Move instructions for A constant being written in W register (MOVLW is short for MOVe Literal to W)For data to be copied from W register onto RAM and data from RAM to be copied onto W register (or on the same RAM location, at which point only the status of Z flag changes).

Instruction CLRF writes constant 0 in 'f ' register, and CLRW writes constant 0 in register W. SWAPF instruction exchanges places of the 4-bit nibbles field inside a register.

Page 46: Pic

More on Arithmetic and Logical Instructions

PIC like many microcontrollers supports only subtraction and addition.

Flags C, DC and Z are set depending on a result of addition or subtraction.Since subtraction is performed like addition of a negative value, C flag is inverse following a subtraction.

Logic unit of PIC has capability of performing operations AND, OR, EX-OR, complementing (COMF) and rotation (RLF and RRF).

Page 47: Pic

On Rotation instructions

Rotates the register contents through flag CBits move by one bit to the left (toward bit 7), or to the right (toward bit 0). Bit which "comes out" of a register is written in flag C, and value of C flag is written in a bit on the "opposite side" of the register.Example: rrf f,F(W)

Copy f into F or W, rotate F or W right through the carry bit

Page 48: Pic

Bit Oriented OperationsManipulate bits in control and status registers Examples

bsf f,b Set bit b( where b=0 to 7) in register

f e.g. : bsf 0x03, 5

btfsc f,b Test bit b of register f, skip next

instruction if bit is 0 e.g. : btfsc 0x03, 2

Page 49: Pic

More on Bit operationsInstructions bcf and bsf perform set or clear one bit anywhere in the memory. Bit operations consist of following micro-operations

CPU reads the complete byte CPU changes one bit in it Then writes the entire byte back

Page 50: Pic

Control Instructions Program and Processor ControlExamples

goto k (k – 11 bit) Unconditional branch. Literal k is loaded

into PC; e.g. : goto there (use of labels)

call k (k – 11 bit)Call subroutine at location k; e.g: call sum

Upper 2 bits of PC loaded from PCLATH<4:3>

Page 51: Pic

More Control Instructionsretfie

Return from interrupt service routine and re-enable interrupts

sleepGo to standby mode

clrwdtClear watchdog timer

Page 52: Pic

Directing program flowGOTO, CALL and RETURN instructions like other micro-controllersCall and return instructions use hardware Stack, independent of internal RAM and limited to eight levels'RETLW k' instruction is identical with RETURN instruction, except that before coming back from a subprogram a constant defined by instruction operand ‘k’ is written in W register.

Page 53: Pic

Example CodeDecrement a 16 bit counter:

upper byte of the counter COUNTH & lower byte COUNTL

movf COUNTL,F ; Set Z if lower byte =0btfsc STATUS,Z ; if so, decrement

COUNTHdecf COUNTH,F decf COUNTL,F ; decrement COUNTL

Page 54: Pic

Example CodeExample code to clear 0x20 - 7F:

movlw 0x20movwf FSR

loopclrf INDFincf FSR,Fbtfss FSR,7goto loop

INDF00h

04h

7FhRegister File

FSR

Page 55: Pic

Software: Relative Addressing

PCL = Low byte of the Program CounterCan be read and written.Writing to it sets the address of the next instruction to be executed.

14bit core

Page 56: Pic

Using Relative AddressingTable Look-up:

movlw 0x04 ; Load W with 4call Table ; Call the table subroutinemovwf Result ; Store the result from the tableTable addwf PCL, W ; Jump to(current PCL)+W

retlw 0x00 ; Return with 0x00 in W

retlw 0x23 ; Return with 0x23 in W

retlw 0x33 ; etc.retlw 0x88

Page 57: Pic

Assembly Language Programming

Advantage of using symbolic address and data referencesMPASM assembler for PIC family of processors

Uses specification of the target processor provided in .INC file Assembler directives for specifying configuration details ( bits in device configuration register)Supports MACRO facility

Page 58: Pic

Facility of MACRONew instructions, at assembler level can be created that are sequences of PIC instructionsExample: macro definition

bank1 macro bsf status, RP0 endm

Must be defined before useUse: in the assembly code

bank1 ; to be replaced during assembly process

Page 59: Pic

SummarizingWe have studied instruction set of PIC micro-controllersLooked at small code snippetsWe know about MPASMYou will use these instructions for developing different applications

Page 60: Pic

The PIC Family: Peripherals

Different PICs have different on-board peripheralsSome common peripherals are:

Tri-state (“floatable”) digital I/O pinsAnalog to Digital Converters (ADC) Serial communications: UART (RS-232C), SPI, I2C, CANPulse Width Modulation (PWM) Timers and counters Watchdog timers

Page 61: Pic

Interrupts: a review

An interrupt is any service request that causes the CPU to stop its current execution stream and to execute an instruction stream that services the interruptWhen the CPU finishes servicing the interrupt, it returns to the original execution stream at the point where it left off.Interrupt driven I/O for interfacing with on chip peripherals

Page 62: Pic

Interrupts in PICSources of interrupt are many

INT pin interrupt from external sourcePort B change interrupt (RB7:RB4)Timer overflow interruptsUSART interruptsA/D conversion interruptsLCD interruptothers

Page 63: Pic

Interrupt ManagementUse of register INTCON: Status and Control

Bit 7: Global interrupt enableEnables (if set) all unmasked interrupts or disables all interrupts

Bits 6,5,4,3: For enabling peripheral, timer0, external interrupt, port B bit change interrupts respectivelyBits 2,1,0 : Timer0, INT, port change interrupt flag respectively

Flag bits get set when interrupt occurs regardless of the value of enable bit

Page 64: Pic

Peripheral Interrupts

Managed using PIE and PIR registersPIE registers contain bits for enabling interrupts from individual peripheralsPIR registers contain flag bits for individual peripheral interruptsBit oriented instructions can be used to examine and/or manipulate interrupt control and status registers

Page 65: Pic

Interrupt Processing

When interrupt is responded toGIE bit is cleared to disable other interruptsPC is pushed into stackPC is loaded with 0004hSave STATUS & W register in temporary memory locationsIn the ISR, source of interrupt is determined by polling the interrupt flag bit

Return from interrupt instruction (retfie) exits ISR, sets GIE bit to allow pending interrupt to execute

Page 66: Pic

Interrupt Timing

Ref: PIC reference manual

Page 67: Pic

Interrupt Constraints

Each interrupt source charaterised byMinimum time interval between interrupts from the same sourceMaximum time it takes the CPU to execute interrupt source’s handler

Servicing of interrupts must not be delayed beyond the limit imposed by the timing requirement of the source

Page 68: Pic

Critical RegionA critical region is a sequence of instructions that must be protected from an intervening interrupt or produce erroneous outputIn PIC this problem is handled by

Single cycle read-modify-write instructionsxorwf PORTD,F

Port D data read, XORed with W and written back to port D

Disabling interrupts by clearing GIE bit for the required set of instructions

Page 69: Pic

PIC Peripherals: Digital I/OAll PICs have digital I/O pins, called ‘Ports’

the 8pin 12C508 has 1 Port with 4 digital I/O pinsthe 68pin 17C766 has 9 Ports with 66 digital I/O pins

Ports used to control and monitor external devicesPorts have 2 control registers

TRISX sets whether each pin is an input or outputPORTX sets their output bit levels

Most pins have 25mA source/sink (directly drives LEDs)

Page 70: Pic

Typical Configuration: Port ASetting a TRISA bit put output drivers in high impedance state; clearing a bit in TRISA puts contents of output latch on the pin

Ref: PIC reference manual

Page 71: Pic

Example: Port AAll pins are I/O with associated direction bits in TRISAInitialisation code:clrf STATUS ;bank 0clrf PORTA ; initialises by clearing

output latchesbsf STATUS, RP0 ; select bank1movlw 0xCF ; value used to initialise

data directionmovlwf TRISA ; PortA<3:0>=input,

<5:4>=output

Page 72: Pic

Managing port read/writeBCF/BSF PORTn does the following:

Reads in the PORTn byte Clears/sets the bitWrite the whole byte back.If external input pulls a different output pin low or high during the READ, the read in value will not be what you expect - WORSE, the WRITE will permanently change it that way.

Solution: Use Shadowed I/O (e.g.: set PORTA Bit 0)bsf _PORTA, 0movf _PORTA, Wmovwf PORTA

Page 73: Pic

Synchronous Serial PortSerial interface module for communicating with other devices or micro-controllersModule operates in one of two modes:

Serial Peripheral Interface Inter-integrated circuit (I2C)

Page 74: Pic

PIC Peripherals: TimersAvailable in all PICs.14+ bit cores may generate interrupts on timer overflow.Some 8 bits, some 16 bits, some have prescalersCan use external pins as clock in/clock out

Page 75: Pic

PIC Timers / Timer 08 bit timer/counter with prescalerReadable and writeable8-bit software programmable prescaler

Prescaler can divide the counter input by 2,4,8,16 …256

Internal or external clock setExternal clock connected to bit 4 of Port A

Interrupt on overflow from 0xFF to 0x00Edge Select for external clock

Page 76: Pic

PIC Timers / Timer 116-bit timer/counter Interrupt on overflowReadable and writeableDifferent Operating modes

External crystal can be used

Programmable prescaler

Page 77: Pic

Timer1: Operating ModesSynchronised Timer

Increments every instruction cycle

Synchronised CounterTimer increments on rising edge of external clockExternal clock is synchronised with internal phase clock

Asynchronous CounterTimer increments independent of internal phase clock

Page 78: Pic

Typical Application: Real-time

Clock

Even when processor sleeps, timer1 continues to count in asynchronous mode, on overflow could wake-up the device

Ref: PIC reference manual

Page 79: Pic

PIC Timers / Timer 2

Readable & writable 8-bit timer/counter with prescaler and postscalerInterrupt on overflow

Ref: PIC reference manual

Page 80: Pic

Watchdog TimerFree running on chip RC oscillator which does not require any external componentA WDT time-out generates a device resetIn sleep mode a WDT time-out causes the device to wake-upTo avoid unintended device reset, postscaler has to be changed after clearing watchdog timerWDT is enabled/disabled by a device configuration bit

Page 81: Pic

PIC Peripherals: CCP Modules

Capture/Compare/PWM (CCP)Each module contains a 16 bit register which can operate as 16-bit capture, 16-bit compare or as 10-bit PWM master-slave duty cycle registerCapture counts external pin changesCompare will interrupt when the timer equals the value in a compare register

Page 82: Pic

Capture Capture mode records value of timer1 when events like rising edge or falling edge occurs on pin CCPxWhen capture is made, interrupt request flag bit is set

Page 83: Pic

CompareContent of register compared with Timer1 register pair valueWhen match occurs, voltage level at CCPx pin is changed depending on the value of control bits

Page 84: Pic

PWM

Pulse Width Modulation Duty Cycle often expressed as a percentage of the period.Average DC voltage will be approximately the same percentage of the “on” voltage.Typical uses:

Intensity controlMotor controlTemperature control

Page 85: Pic

PWM ModeIn pulse width modulation mode, CCPx pin produces up to a 10-bit resolution PWM output

Since CCPx pin is multiplexed with the port data latch, the corresponding TRIS bit must be cleared

Coupled with Timer2 for producing outputPeriod and duty cycle of timer2 output manipulated for obtaining desired PWM waveform

Page 86: Pic

PWM: Block diagram

Ref: PIC reference manual

Page 87: Pic

PWM: Set upSteps required for setting up PWM

Establish the PWM period by writing to PR2 registerEstablish the PWM duty cycle by writing onto CCPRxL & CCPxCON<5:4> bitsMake CCPx pin an output Establish TMR2 prescale value and enable timer by writing to T2CONConfigure CCP module for PWM operation

Page 88: Pic

PWM: A simple application Speed control of a DC motor

Vary the Thigh and Tlow of the output waveform.When the duty ratio is changed the speed of the Motor is changed as average DC input changes

Page 89: Pic

PIC Peripherals: ADCsConverts an analog input signal to 8-bit digital value

Generates result via successive approximation

Input analog channel, Conversion clock, Analog reference voltage is software selectableCan operate even while the device in sleep mode.Can generate an interrupt on ADC conversion done

Result written on to ADRES register

Page 90: Pic

More PIC PeripheralsSome devices have 8-bit parallel slave port

Multiplexed onto one of devices I/O portFor interfacing with 8-bit peripherals or microprocessors

USART (universal synchronous and asynchronous receiver transmitter)

Can be configured as a full duplex channel for communication with or peripheral devices like CRT

LCD ModuleGenerates timing control to drive LCD panelAlso provides control of pixel data

Page 91: Pic

More PIC PeripheralsEEPROM data memory

Readable and writable under normal operationsNot mapped directly in register file spaceIndirectly accessed using SFR

In-circuit programmer Serial in-circuit programming support

Page 92: Pic

PIC: ExamplesLow End: 12C508

8pin package (DIP)12bit core - 33 instructions1us instruction time (Tclk = 4MHz)512 12bit program memory25 8bit data memory or registers (“File registers”)2 level hardware stack (no interrupts)5 GPIO pins, 1 input only (25mA source/sink)Features: Internal pullups, wake up on pin change, internal oscillator

Peripherals: Timer, Watch Dog Timer

Page 93: Pic

PIC ExamplesMid Range: 16F876

28pin package (DIP)14bit core - 35 instructions200ns instruction time (Tclk = 20MHz)8,092 14bit FLASH program memory368 8bit data memory or registers (“File registers”)256 8bit EEPROM (nonvolatile) data registers8 level hardware stack (interrupts enabled)22 GPIO (20mA source / 25mA 7sink)Peripherals: 5ch 10bit ADC, USART/I2C/SPI, 16bit & 8bit timersFeatures: Brown out detect, In-Circuit Debugger (ICD)

Page 94: Pic

SummaryWe have studied PIC family of processors

ArchitectureInstruction setPeripherals

PIC processors are well suited for low-end and mid-range applications