Electronic – Strange port behavior (PIC24F)

iomplabpicpickit

I was just trying to get port IO working with this code:

#include "p24Fxxxx.h" // This header will choose the right device header

#define FCY 16000000UL // Running at 16 MIPS = Fosc/2

#include <PIC24F_plib.h>
#include <libpic30.h>

// Configuration setup
_CONFIG1( FWDTEN_OFF & GWRP_OFF & GCP_OFF & JTAGEN_OFF & ICS_PGx3 )
_CONFIG2( FCKSM_CSDCMD & OSCIOFNC_ON & POSCMOD_HS & FNOSC_FRCPLL & I2C1SEL_PRI & PLL96MHZ_ON & PLLDIV_NODIV & IESO_OFF & IOL1WAY_OFF );
_CONFIG3( SOSCSEL_IO );

int main() {
    TRISB = 0;
    PORTB = 0;

    PORTBbits.RB0 = 1;
    PORTBbits.RB4 = 1;

    while(1) {
        __delay_ms( 200 );
    }
}

So I breakpoint on the __delay_ms instruction, and take a peek at the LATB registers:

enter image description here

(As pictured, only LATB4 is switched on – confirmed with a multimeter)

Also, if I comment out the PORTBbits.RB4 = 1; line, LATB0 is turned on (but not LATB4)

Is the second call overwriting it somehow? Maybe, because PORTB = 0b10001; alone works.

I'm using a PIC24FJ64GB002, MPLAB X, C30 and a PICkit 3. I realise that MPLAB X isn't 100% stable – but something this simple should work.

If some PIC guru could point me in the right direction, that'd be awesome.

Best Answer

Instead of PORTxbits.RBx rather use LATxbits.LATx, when you set/reset your pins to avoid this problem.