Backend Coder Logo

PIC Macros for memory bank switching

Published: 18th July 2016

When using General Purpose Registers we need to ensure that we are on the correct memory bank. Otherwise the memory location gets masked to the bank that you are on already which could result in data being read/written to the wrong location.

So it's a good idea to include some macros to easily insert the required code to switch memory banks before you use the GPR registers.

Here is some macro code that you can use and maybe add to a header file to include.

; Macros
BANK0	MACRO
	BCF STATUS, RP0
	BCF STATUS, RP1
	ENDM

BANK1	MACRO
	BSF STATUS, RP0
	BCF STATUS, RP1
	ENDM
	
BANK2	MACRO
	BCF STATUS, RP0
	BSF STATUS, RP1
	ENDM
	
BANK3	MACRO
	BSF STATUS, RP0
	BSF STATUS, RP1
	ENDM

And when you want to switch to a particular memory bank, you just add the macro keyword such as BANK3 before your code block. I saved this code to a macros.inc file and added an include statement at the start of the main program code (#include "macros.inc").