Electronic – PIC18F4580 – PORTD not being read correctly

hardwaremplabpic

I am experiencing a strange problem with reading back the value of PORTD while it is configured as an output. I am writing to LATD to set output on the port. The actual output is as I expect (verified with LEDs), but when I then read the value of PORTD, bits 0:3 always come back as zero…

My first thought was conflict with the ADC, but it is switched off, as are CCP1, ECCP and PSP which also share pins with port D. The code works fine when running in MPLAB SIM but the problem shows up both running normally and debugging with a PICkit3…

Here's the code:

void main (void)
{
   char test;

    ADCON0bits.ADON=0;          //Turn adc off
    ADCON1 = 0x0F;              //Turn individual ADC channels off.
    ECCP1CONbits.ECCP1M = 0;    //Turn off ECCP module
    CCP1CON = 0;                //Disable CCP1
    TRISEbits.PSPMODE = 0;      //Turn off PSP module
    TRISD = 0;                  //PORTD to output
    LATD = 0xFF;                //Set all bits high
    Nop();                      //Wait for output to propagate back to PORTD
    test = PORTD;               //test gets 0xF0???
}

This is really frustrating, all the more so because the hardware actually functions but my self tests keep giving false positives…

Best Answer

I think it's the comparators still being attached - try adding:

CMCON = 0x07;

If you notice in the table CM2:CM0 have to be 111 (rather than 000) to have the pins disconnected and digital. Plus they correspond to pins RD0:RD3:

Comparators Off