Tell me more ×
Electrical Engineering Stack Exchange is a question and answer site for electronics and electrical engineering professionals, students, and enthusiasts. It's 100% free, no registration required.

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.

share|improve this question

2 Answers

up vote 2 down vote accepted

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

share|improve this answer
Ah, that's it! Awesome! – Schnommus Feb 24 '12 at 10:41
;) had the same problem myself a while ago... – Count Zero Feb 24 '12 at 10:45

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?

share|improve this answer
1  
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. – Connor Wolf Feb 24 '12 at 22:35
Ah, I get it now. – Schnommus Feb 25 '12 at 3:27

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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