2
\$\begingroup\$

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.

\$\endgroup\$

2 Answers 2

2
\$\begingroup\$

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

\$\endgroup\$
2
  • \$\begingroup\$ Ah, that's it! Awesome! \$\endgroup\$ Feb 24, 2012 at 10:41
  • \$\begingroup\$ ;) had the same problem myself a while ago... \$\endgroup\$
    – Count Zero
    Feb 24, 2012 at 10:45
2
\$\begingroup\$

Writing to an element of a bitfield will generally cause a read-modify-write operation to be performed. In particular, the line

PORTBbits.RB4 = 1;

will have the same behavior as

PORTB = PORTB | (1<<4);

My PIC is a bit rusty, but I believe that reading PORTB will return the current state of the pins, rather than the value last written?

\$\endgroup\$
2
  • 1
    \$\begingroup\$ This is correct. So if you set two pins in rapid succession, the first pin does not have time to rise above the input threshold. Therefore, since the second operation reads back the physical state of the pin, and the pin has not changed state yet, the second operation clobbers the first. \$\endgroup\$ Feb 24, 2012 at 22:35
  • \$\begingroup\$ Ah, I get it now. \$\endgroup\$ Feb 25, 2012 at 3:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.