Questions about this topic? Sign up to ask in the talk tab.

PIC programming

From Security101 - Blackhat Techniques - Hacking Tutorials - Vulnerability Research - Security Tools
(Redirected from PIC Programming)
Jump to: navigation, search

The 8-BIT PIC MCU known as the PIC16F877A has only 35 single-word instructions, making it perfect for beginners. This article requires a programming utility/assembler called MPLABX set up in conjunction with a physical PIC16F877A device. Test code will be initially be run through the simulator and eventually executed using MPLAB ICD3, an in circuit debugger.

PIC programming requires a basic understanding of assembly and Bitwise math


Contents

Installing MPLABX & GPUTILS

Installing MLABX via AUR (covered in this article):

Terminal

localhost:~ $ sudo yaourt -S microchip-mplabx-bin

Installing GPUTILS (not covered in this article):

Terminal

localhost:~ $ sudo pacman -S gputils

Device overview

RPU0j.png
When connecting this device take care to use a power supply that outputs 2-5 volts of power.

If necessary, a small breadboard power supply with an LM7805 and a few 10uF capacitors to keep out high frequency noise and peaks which can damage the pins of the PIC can be made. Tie the reset line to a pull up resistor to keep the device from resetting.

The PIC16F877A is a popular device used in the industry because of its low price, ease of use, and many features. Many hobbyists and robot enthusiasts have used this PIC for a vast range of projects. Be careful to note that both PWM channels run on the same timer so only one frequency can be set, but independently can control each channel. The PIC must be setup properly for the RAx (where x is the pin number) pins to be used as digital, this will be discussed later.

Device Program Memory SRAM (Bytes) EEPROM I/O 10-BIT A/D CCP (PWM) MSSP USART Timers 8/16-BIT Comparators
Bytes / # Single Word Instructions SPI / Master I2C
PIC16F877A 14.3K / 8,192 368 256 33 8 2 Yes/Yes Yes 2/1 2

ROM and RAM

There are three seperate areas of memory on the PIC16F877A: Electrically Erasable Programmable Read Only Memory (EEPROM), program memory (Read-Only Memory, ROM), and data memory (Random Access Memory, RAM). The PIC's memory is diagrammed below. EEPROM is not mapped to the register files so it has to be accessed through special function registers which will be outlined later. Programs can be flashed to the device (if using one) via a programmer like a pickit3 or ICD3, but the programs outlined in this article will use a simulator.

PC<12:0>
Stack level 1
Stack level 2
....
Stack level 8
Reset Vector (0000h)
...
Interrupt Vector (0004h)
Page 0 (0005h-07FFh)
Page 1 (0800h-0FFFh)
Page 2 (1000h-17FFh)
Page 3 (1800h-1FFFh)

Pages 0-3 are program memory which are organized into banks, different special function registers (SFR) can be accessed and changed based on the type of memory currently being used.

EEPROM

EEPROM memory is saved through power cycles and can be changed during operation. On the PIC16F877A there are 256 locations where data can be written to and read from, only six SFR's are necessary to read/write EEPROM data.

SFR Purpose
EECON1 Control register
EECON2 Used for write sequences
EEDATA 8-bit data for R/W
EEDATH Holds 14-bit data for R/W with EEDATA
EEADR Can access 256 locations.
EEADRH Holds 13-bit memory address being access with EEDATA

Manipulating Data

SFR (Special Function Registers)

Special Function Registers are memory locations that have a specific purpose or purposes (i.e. TRISA are by default analog, but some can also be used as digital input) depending on the current memory bank in use. The 4 different banks (0-3) and their corresponding SFR's can be found on page 19 of the PIC16F877A datasheet. For example, the direction of the PORTB ports can be changed by switching to bank 1 using the STATUS SFR and setting TRISB accordingly.

include <P16F877A.INC>              ; make these easier on us and include equates
 
RES_VECT CODE 0x0000                ; processor reset vector
    GOTO    START                   ; go to beginning of program
 
MAIN_PROG CODE                      ; let linker place main program
 
START                               ; start of our program
    BSF   STATUS,RP0                ; set current bank to bank 0
    MOVLW 0x00                      ; move 0x00 to the W (Working register)
    MOVWF TRISB                     ; move working register into TRISB
    BCF   STATUS,RP0                ; set current bank to bank 1
 
    BSF   PORTB,3                   ; set bit HIGH at RB3
    END                             ; end

General Purpose Registers

General Purpose Registers allow us to store data temporarily. GPRs can be defined with the instructions EQU, CBLOCK, and RES. The next example shows how to use the GPRs.

include <P16F877A.INC>
 
ISPUSHED EQU 0x70        ; ISPUSHED is at location 0x70
 
RES_VECT CODE 0x0000           
    GOTO    START                  
 
MAIN_PROG CODE          
 
START
    BSF   STATUS,RP0
    MOVLW 0x00
    MOVWF TRISB
    BCF   STATUS,RP0
    CLRF  PORTB
 
    BSF   PORTB,3
    MOVLW 0x01
    MOVWF ISPUSHED
    END

The above code used ISPUSHED EQU 0x70 to assign the label ISPUSHED to the address 0x70. There are also other ways using RES depending on whether or not the code is absolute or relocatable. In the second part of the code, the value 0x01 is moved from the working register to ISPUSHED. A GPR can be defined sequentially using the CBLOCK directive. BSF is used to set bits and conversely BCF to clear individual bits. To move data between the WREG and an SFR use MOVLW. Data can be moved from W to a SFR using MOVWF.

CBLOCK 0x70
  tmp1       ; address 0x70
  tmp2       ; address 0x71
ENDC

Programming

With a little bit of prior assembly experience, PIC programming is very easy and a command reference list will be provided at the end of this section. Start a project in MPLABX by going to File->New Project. The first step will be to include the PIC's header file.

include <P16F877A.INC>

Configuration bits
Configuration bits set fuses on the PIC such as toggling the watchdog timer, code protection, and other features. The configuration bit manager can be used in MPLABX or in the source file.

__config ( _BODEN_ON & _WDT_OFF & _HS_OSC & _LVP_OFF )

Comments
Comments are a way to document code for easier reading. PIC assembly language uses the semicolon (;) to insert a comment.

BUTTON_HIGH EQU 0x01     ; This is a comment

So far the test file should look like the following:

include <P16F877A.INC>
__config ( _BODEN_ON & _WDT_OFF & _HS_OSC & _LVP_OFF )
 
org 0x00
    GOTO START
org 0x04
    ; Interrupt routines go here
START
    ; Program code goes here
END

NOTE: org is used to align the code to a certain address. 0000h is the reset vector and ISR routines are at 0004h, as noted in the memory table. This will force the first piece of code to be executed at START.

Lets add some code to our project then build and simulate it.

Simulation

Create a new project in MPLABX and add the following source code. Be sure when selecting the debugger to use select MPLAB Simulator so code can be simulated and stepped through.

include <P16F877A.INC>
__config ( _BODEN_ON & _WDT_OFF & _HS_OSC & _LVP_OFF )
 
ISPUSHED EQU 0x70        ; ISPUSHED is at location 0x70
 
RES_VECT CODE 0x0000           
    GOTO    START                  
 
MAIN_PROG CODE          
 
START
    BSF   STATUS,RP0
    MOVLW 0x00
    MOVWF TRISB
    BCF   STATUS,RP0
    CLRF  PORTB
 
    BSF   PORTB,3
    MOVLW 0x01
    MOVWF ISPUSHED
    END

Once the source is saved build the project (press the hammer button), then select Debug->Debug Main Project and at the bottom of the MPLAB window click the Variables tab. Next, right click in the box and click New Watch click the SFR radio button and type or select PORTB then click ok you should see it show up in the window you can click next to it to expand all the registers. We could specifically watch RB3 button for the sake of this article we will watch them all. If we press the Reset button on the top right which looks like a refresh button it should high your GOTO START click the down pointing button by Reset and it will step line by line through your code. Once you hit MOVWF ISPUSHED look at the contents of RB3.. shows 0x01! If we wanted we could add a watch to WREG which will show contents of working register.

PIC16F877A Command list

Example code

Light an LED

;-----------------------------------------------------------------------------
; This code is written strictly for blackhatlibrary.net
; written by rj
;
; Turn on an LED connected to RB1
;-------------------------------------------------------------------------------
     include <p16f877a.inc>
    __config ( _boden_off & _wdt_off & _hs_osc  )
    errorlevel -302
 
    org 0x00
         goto  start
    org 0x04
 
start
    bsf   status,rp0
    movlw 0x00
    movwf trisb
    bcf   status,rp0
    bsf   PORTB,1
end

Writing to EEPROM

;-----------------------------------------------------------------------------
; This code is written strictly for blackhatlibrary.net
; written by rj
;
; EEPROM example program.
;------------------------------------------------------------------------------
    include <p16f877a.inc>
    __config ( _boden_off & _wdt_off & _hs_osc  )
    errorlevel -302
 
    org 0x00
         goto  start
    org 0x04
 
start
    bcf   status,rp0
    bsf   status,rp1    ; Bank 2
    movlw 0x02          ; Memory address of EEPROM to write to
    movwf eeadr         ; Move it into EEADR
    movlw 0x3           ; Literal value 0x03 will be written
    movwf eedata        ; to EEPROM address 0x02
    bsf   status,rp0    ; switch to Bank 3
    bcf   eecon1,eepgd  ; Point to data memory
    bsf   eecon1,wren   ; WREN must be set to enable writes
    bcf   intcon,gie    ; Disable interuptts
 
    ;---------------------------------------------------------------------------
    ; Required sequence to write to EEPROM memory
    ;---------------------------------------------------------------------------
    movlw 0x55
    movwf eecon2
    movlw 0xaa
    movwf eecon2
    bsf eecon1,wr
 
    bsf   intcon,gie    ; Enable interuppts
    bcf   eecon1,wren   ; Disable program operations
end

Command List

Most instructions only take 1 cycle, except for branches which take 2.

Instruction
ADDWF
ANDWF
CLRF
CLRWF
COMF
DECF
DECFSZ
INCF
INCFSZ
IORWF
MOVF
MOVWF
NOP
RLF
RRF
SUBWF
SWAPF
XORWF
BCF
BSF
BTFSC
BTFSS
ADDLW
ANDLW
CALL
CLRWDT
GOTO
IORLW
MOVLW
RETFIE
RETLW
RETURN
SLEEP
SUBLW
XORLW

PIC programming is part of a series on programming.
[ Decompile ]
Personal tools
 


VPS-Heaven now accepting BitCoin!



Our research is made possible by your support.