Unit 2 - Notes
Unit 2: PIC18 Architecture
Introduction to PIC Microcontrollers
A PIC (Peripheral Interface Controller) is a family of microcontrollers manufactured by Microchip Technology. Originally developed for general-purpose I/O control, they have evolved into a vast and popular family of devices used in countless embedded systems.
Key Characteristics:
- RISC Architecture: They are based on a Reduced Instruction Set Computer (RISC) architecture, which features a small, highly optimized set of instructions.
- Harvard Architecture: They use a Harvard memory architecture, which has separate memory and buses for program code and data. This allows for simultaneous fetching of instructions and data, improving performance.
- Cost-Effective: PICs are known for their low cost, making them suitable for both hobbyist projects and mass-produced commercial products.
- Wide Range of Devices: The PIC family includes devices from simple 6-pin 8-bit controllers (PIC10) to powerful 100-pin 32-bit controllers (PIC32), catering to a wide variety of applications.
- Integrated Peripherals: Most PICs include a rich set of built-in peripherals such as timers, Analog-to-Digital Converters (ADCs), USARTs for serial communication, and more.
- Low Power Consumption: Many PIC devices feature "eXtreme Low Power" (XLP) technology, making them ideal for battery-powered applications.
PIC Architecture
The core architecture of PIC microcontrollers, especially the 8-bit families like PIC18, is defined by two key principles: Harvard Architecture and a RISC instruction set.
1. Harvard Architecture
In a Harvard architecture, the memory is physically separated into two distinct spaces:
- Program Memory (ROM/Flash): Stores the application code (the instructions to be executed).
- Data Memory (RAM): Stores variables, temporary data, and special function registers (SFRs).
Each memory space has its own dedicated bus (address bus and data bus).
Advantages:
- Increased Bandwidth: The CPU can fetch an instruction from program memory and access data from data memory simultaneously in a single clock cycle. This overlapping is a form of instruction pipelining and significantly increases execution speed compared to a Von Neumann architecture.
- Differing Bus Widths: The bus width for program and data memory can be different. For example, in a PIC18, instructions are 16 bits wide, while data is 8 bits wide. This allows for efficient instruction encoding while maintaining a standard 8-bit data path.
2. RISC (Reduced Instruction Set Computer)
PIC microcontrollers employ a RISC design philosophy.
Characteristics:
- Small Instruction Set: The total number of instructions is small (e.g., the PIC18 has 75 standard instructions and 8 extended instructions).
- Fixed-Length Instructions: All instructions are the same length (16 bits for PIC18), which simplifies the instruction decoding hardware.
- Single-Cycle Execution: Most instructions execute in a single instruction cycle (which is composed of four oscillator clock cycles). Branch instructions typically take two cycles.
- Load/Store Architecture: Only
loadandstoreinstructions can access data memory. All arithmetic and logic operations are performed on registers within the CPU.
Introduction to the PIC18F458
The PIC18F458 is a high-performance, 8-bit microcontroller from the popular PIC18 family. It is often used in educational settings and industrial applications due to its robust feature set.
Key Features of PIC18F458:
- CPU: High-performance RISC CPU.
- Operating Speed: Up to 40 MHz oscillator input (10 MIPS - Million Instructions Per Second).
- Program Memory (Flash): 32 KB. This is where the user's C or Assembly code is stored.
- Data Memory (SRAM): 1,536 Bytes. Used for variables and the stack.
- Data EEPROM: 256 Bytes. Non-volatile memory for storing configuration data that needs to persist through power cycles.
- I/O Ports: 5 ports (PORTA, PORTB, PORTC, PORTD, PORTE) providing up to 34 I/O pins.
- Peripherals:
- Timers: Four timers (Timer0, Timer1, Timer2, Timer3).
- Capture/Compare/PWM (CCP): Two modules for signal measurement and generation.
- Analog-to-Digital Converter (ADC): 10-bit resolution with 8 input channels.
- Communication:
- Master Synchronous Serial Port (MSSP) supporting SPI and I2C protocols.
- Enhanced Addressable USART for serial communication (e.g., RS232).
- CAN (Controller Area Network) Module: A key feature for automotive and industrial communication networks.
- Interrupts: Multiple internal and external interrupt sources.
- Package: Commonly available in a 40-pin Dual In-line Package (DIP).
Program Counter (PC) and Program ROM Space in PIC18
Program Counter (PC)
The Program Counter is one of the most critical registers in the CPU. Its sole function is to hold the memory address of the next instruction to be fetched and executed.
- Size: In the PIC18 family, the PC is 21 bits wide.
- Addressing Capability: A 21-bit address bus allows the microcontroller to access 221 = 2,097,152 (2M) memory locations. Since each instruction in the PIC18 is 16 bits (2 bytes), the PC can address up to 4 MB of program memory. The PIC18F458 itself only has 32 KB, but the architecture supports much larger devices.
- Operation:
- The CPU places the address from the PC onto the program memory address bus.
- The 16-bit instruction at that address is fetched into the instruction register.
- The PC is automatically incremented by 2 (since each instruction is 2 bytes long) to point to the next instruction in sequence.
- The current instruction is decoded and executed.
- Modification: The PC's value can be changed by instructions that alter the program flow, such as
GOTO(jump),CALL(subroutine call),RETURN, and conditional branches (BC,BNZ, etc.).
Program ROM Space (Flash)
This is the non-volatile memory that stores the application code. The memory map has specific, important locations.
- Reset Vector (Address
0x000000): When the PIC18 is powered on or reset, the PC is loaded with0x000000. The CPU begins executing the instruction at this address. Typically, aGOTO Maininstruction is placed here to jump to the start of the main program. - High-Priority Interrupt Vector (Address
0x000008): When a high-priority interrupt occurs, the CPU finishes its current instruction, saves the PC's current address onto the stack, and jumps to0x000008to execute the Interrupt Service Routine (ISR). - Low-Priority Interrupt Vector (Address
0x000018): When a low-priority interrupt occurs, the CPU jumps to0x000018to execute its ISR.
The Hardware Stack
The PIC18 has a dedicated hardware stack used for storing the return address (the value of the PC) during subroutine calls (CALL) and interrupts.
- Size: The stack is 31 levels deep. This means you can have a maximum of 31 nested subroutine calls and interrupts.
- Pointers: The Stack Pointer (STKPTR) register keeps track of the top of the stack (TOS).
- Operation:
- PUSH: When a
CALLor interrupt occurs, the current PC value is pushed onto the top of the stack. - POP: When a
RETURN,RETFIE, orRETLWinstruction is executed, the address at the top of the stack is popped back into the PC, and program execution resumes from where it left off.
- PUSH: When a
Core CPU Registers
PIC WREG Register
The Working Register (WREG) is an 8-bit register that acts as the primary accumulator for the CPU. It is not part of the data memory (File Register) and has no address.
- Function: It is the most frequently used register in the PIC.
- Operand Source: For many instructions, especially arithmetic and logical operations, one of the operands must be in the WREG register.
- Data Transfer Hub: Moving data between different locations in the file register or between peripherals and the file register often involves a two-step process using WREG as an intermediary.
MOVF fileReg, W: Move data from a file register to WREG.MOVWF WREG, fileReg: Move data from WREG to a file register.
File Register
The "File Register" is the PIC term for the entire data memory space (RAM). It is a collection of 8-bit registers organized into banks. The PIC18 architecture supports up to 4096 bytes of data memory.
It is divided into two main types of registers:
- General Purpose Registers (GPRs): This is the user-accessible RAM used for storing application variables, temporary data, and buffers.
- Special Function Registers (SFRs): These are registers dedicated to controlling the operation of the microcontroller and its on-chip peripherals. Examples include:
PORTA,TRISA: For controlling I/O Port A.T0CON: For configuring Timer0.ADCON0: For controlling the A/D converter.STATUS: The CPU status register.
Memory Banking
Because an 8-bit instruction can only hold an 8-bit address (for accessing 256 locations), but the PIC18 has 4096 possible locations, a banking scheme is used.
- The 4096-byte data memory is divided into 16 banks of 256 bytes each.
- The Bank Select Register (BSR), a 4-bit SFR, is used to select which of the 16 banks is currently active.
- When an instruction accesses a memory location, the 4 bits from the BSR are combined with the 8-bit address from the instruction to form a full 12-bit address (
16 banks * 256 bytes/bank = 4096 bytes).
The Access Bank
To simplify access to commonly used SFRs and some GPRs, the PIC18 implements an "Access Bank." This is a virtual bank composed of the first 96 bytes of Bank 0 (SFRs) and the last 160 bytes of Bank 15 (GPRs). Any register in the Access Bank can be accessed directly by an instruction without needing to set the BSR first.
STATUS Register
The STATUS register is an 8-bit SFR that holds critical information about the state of the CPU and the result of the last arithmetic or logic operation.
| Bit | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
|---|---|---|---|---|---|---|---|---|
| Name | - | - | - | N | OV | Z | DC | C |
-
C (Bit 0) - Carry Flag:
- Set (1): If an addition operation results in a carry-out from the most significant bit (MSB, bit 7), or if a subtraction results in a borrow.
- Cleared (0): Otherwise.
- Use: Essential for performing multi-byte arithmetic.
-
DC (Bit 1) - Digit Carry/Borrow Flag:
- Set (1): If an addition operation results in a carry-out from the 4th bit (LSB of the high nibble), or a subtraction results in a borrow from the 4th bit.
- Cleared (0): Otherwise.
- Use: Primarily used for Binary Coded Decimal (BCD) arithmetic.
-
Z (Bit 2) - Zero Flag:
- Set (1): If the result of an arithmetic or logic operation is zero.
- Cleared (0): If the result is non-zero.
- Use: Commonly used for loop counters and comparing values (e.g.,
SUBWF f, Wfollowed byBZ(Branch if Zero)).
-
OV (Bit 3) - Overflow Flag:
- Set (1): If the result of a signed arithmetic operation is too large to fit in the 8-bit result, causing an overflow. This occurs when adding two positive numbers yields a negative result, or adding two negative numbers yields a positive result.
- Cleared (0): Otherwise.
- Use: Used in signed number arithmetic to detect errors.
-
N (Bit 4) - Negative Flag:
- Set (1): If the MSB (bit 7) of the result of an arithmetic or logic operation is 1.
- Cleared (0): If the MSB is 0.
- Use: Indicates the sign of the result in signed arithmetic (1 = negative, 0 = positive).
PIC Configuration Registers
Configuration registers (or "configuration bits" / "fuses") are a special set of registers in non-volatile memory that define the fundamental hardware configuration of the PIC microcontroller.
- When are they set? They are programmed once when the hex file is loaded onto the chip. They cannot be changed by the program while it is running.
- How are they set? They are defined in the source code using special directives called
pragmas.
It is critical to set these correctly, as incorrect settings can prevent the oscillator from starting, disable the debugger, or cause the chip to behave unexpectedly.
Common PIC18F458 Configuration Settings
(The exact names may vary slightly with the compiler, e.g., MPLAB XC8)
// Example Configuration Bits for PIC18F458 using XC8 Compiler
// Oscillator Selection: HS (High-Speed) crystal oscillator
#pragma config OSC = HS
// Watchdog Timer (WDT): Disabled
#pragma config WDT = OFF
// Power-up Timer (PWRT): Enabled
#pragma config PWRT = ON
// Brown-out Reset (BOR): Enabled
#pragma config BOREN = ON
// Low-Voltage ICSP Programming: Disabled (RB5 is a general I/O pin)
#pragma config LVP = OFF
// Code Protection Block 0: Disabled (code can be read)
#pragma config CP0 = OFF
Key Settings Explained:
- Oscillator Selection (FOSC/OSC): This is the most important setting. It tells the PIC where its clock signal is coming from (e.g., an external high-speed crystal
HS, an internal oscillatorINTIO, an external resistor-capacitorRC). The CPU will not run if this is set incorrectly. - Watchdog Timer (WDTEN/WDT): The WDT is an independent timer that will reset the microcontroller if it's not periodically cleared by the software. This is a fail-safe mechanism to recover from software freezes. It can be enabled or disabled.
- Power-up Timer (PWRTEN/PWRT): When enabled, this creates a fixed delay (typically ~72ms) after power is applied before the code starts executing. This ensures the power supply is stable.
- Brown-out Reset (BOREN/BOR): This feature monitors the VDD (supply voltage). If the voltage drops below a certain threshold (the brown-out voltage), it holds the PIC in reset. This prevents unpredictable behavior or memory corruption that can occur at low voltages.
- Low-Voltage Programming (LVP): The PIC18 can be programmed using either high-voltage or low-voltage mode. Disabling LVP frees up the PGM pin (usually RB5) for use as a general-purpose I/O.
- Code Protection (CPx): These bits can be set to prevent the program memory from being read out by an external programmer, protecting intellectual property. Once set, they can usually only be erased by a full chip erase.