This post describes SETF and CLRF Instructions for PIC Microcontroller with relevant examples. SETF
/ CLRF
instructions are used to set / clear all the bits of a file register.
Note: For this tutorial I am using MPLAB X v5.0 but you can use any version upto v5.35. Version 5.35 is last version that included MPASM i.e. the assembler we require to compile the assembly code used in this tutorial. Code given here may not work for later versions.
CLRF: Clear file register f
Syntax: CLRF f,{a}
Length of the Instruction: 2 bytes
Instruction Cycles: 1
Instruction Encoding: 0110 101a ffff ffff
Updated Flags: Z
Destination: The destination is always the file register f
and cannot be changed.
Access Bit: Access bank is used if a = 0
. BSR is used to select the bank if a = 1
. Access bit is optional and the default is a = 0
.
Description: Clears the contents of file register f
.
CLRF Example 1
The following code clears TRISC
register and sets all bits of PORTC
to output. PORTC
is toggled every 250 msecs.
CLRF TRISC ; Make PORTC an output by writing 0's to all bits of TRISC
MOVLW 0x55 ; Load a value into WREG
MOVWF PORTC ; Initialize PORTC by copying WREG to PORTC SFR
BACK
CALL DELAY_250MSEC ; CALL delay subroutine that generates a delay of 250 msecs
COMF PORTC ; Toggle all pins of PORTC
BRA BACK ; Infinite loop
CLRF Example 2
We can clear the contents of any file register in a single line by using the CLRF
instruction. Consider the following code
CLRF 0x01 ; Clear RAM 0x01
This is efficient compared to using MOVLW
followed by MOVWF
. Consider the following code
MOVLW 0x00 ; Load 0x00 into WREG
MOVWF 0x01 ; Initialize 0x01 by copying WREG to it
Above code requires two instructions compared to the CLRF
and also uses twice the code ROM.
SETF: Set file register f
Syntax: SETF f,{a}
Length of the Instruction: 2 bytes
Instruction Cycles: 1
Instruction Encoding: 0110 100a ffff ffff
Updated Flags: None
Destination: The destination is always the file register f
and cannot be changed.
Access Bit: Access bank is used if a = 0
. BSR is used to select the bank if a = 1
. Access bit is optional and the default is a = 0
.
Description: Sets the contents of file register f
to 0xFF
.
SETF Example
The following code sets TRISC
register to 0xFF
and sets all bits of PORTC
as input. PORTC
contents are copied to RAM location 0x60
.
VALUE EQU 0x60 ; RAM Location where PORTC is copied after reading
SETF TRISC ; Make PORTC an input by writing 1's to all bits of TRISC
LOOP
MOVFF PORTC, VALUE ; Copy PORTC value to RAM
BRA LOOP ; Infinite loop