How do the bank switching in PIC assembler?

c0m4 picture c0m4 · May 5, 2009 · Viewed 9.5k times · Source

I'm getting confused by bank switching in PIC assembler... This works for putting a 'Q' on the usart:

bsf PORTB,1         ;Set Transmit DIR (PORTB (0x6) not mirrored in other banks)
movlw 'Q'           ;'Q' to work reg
movwf TXREG         ;work reg to TXREG (TXREG (0x19) not mirrored in other banks)
clrwdt              ;Clear watchdog
btfss TXSTA,TRMT    ;Wait until 'Q' is shifted (TXSTA is 0x18, not mirrored)
goto $-2
bcf PORTB,1         ;Set Recive DIR

And this works just as good:

BCF 0x3, 0x5        ;Switch to bank 0
BCF 0x3, 0x6
bsf PORTB,1         ;Set Transmit DIR
movlw 'Q'           ;'Q' to work reg
movwf TXREG         ;work reg to TXREG 
BSF 0x3, 0x5        ;Switch to bank 1
clrwdt              ;Clear watchdog
btfss TXSTA,TRMT    ;Wait until 'Q' is shifted
goto $-2
BCF 0x3, 0x5        ;Switch to bank 0
bcf PORTB,1         ;Set Recive DIR

I have checked that the compiler does not do any bank switching when I'm not watching... When do HAVE to switch bank?

Answer

sybreon picture sybreon · May 5, 2009

It's best to just use BANKSEL to do your bank switching automatically. It is a special assembler directive the tells the assembler to switch to the correct bank. So, if you wish to access PORTB, just BANKSEL(PORTB) before using it.

PS: PORTB is in BANK0 on the PIC16 family, not BANK1 as in your code.