Odd Issue with PIC18F45K20

Discussion in 'Embedded Systems and Microcontrollers' started by Stuntman, Oct 26, 2011.

  1. Stuntman

    Thread Starter Active Member

    Mar 28, 2011
    This is a simple problem I recently ran into in programming a PIC18F45K20.

    The simple problem, if I set one of the outputs (read, one bit in PORTA), at least some of the other bits are cleared. Here is some test code I wrote to show the problem:

    If I run this code, only pin RA1 toggles high and low. RA0 stays low (except for the 1 execution step it is high before RA1).

    If I switch this code to use pins RB0 and RB1, the pins toggle simultaneously as they should.

    I have not used the PIC18F series extensively, but haven't found a reason in the datasheet or errata.


  2. hexreader

    Senior Member

    Apr 16, 2011
    Instead of RA0, use LATA0

    Always use LATx register for output, PORTx register for input.

    Google Read-Modify-Write or RMW for the reason why.

    Also check that analogue is disabled for PORTA.
    The datasheet I/O Ports section should explain what is needed.
    Probably something like ANSEL = 0;

    Hope this helps
  3. Stuntman

    Thread Starter Active Member

    Mar 28, 2011

    Very sharp!

    Not knowing about this RMW I looked into this issues to find this:


    I modified the code with LATx and voila, did all it was supposed to.

    But I couldn't help but investigate why these pins were not reading correctly. In the actual code, this activation of the PORTA pin that cleared the others is far away from direct succession of the previous PORTA operation, making timing a non-issue.

    Just in case, I tried timing things out again, and no change. I tried pullups on the pins with no change.

    Your idea about the ANSEL byte was one my first thoughts on this problem, but was disregarded as the datasheet stated the ANSEL bit does not affect digital output. To humor myself, I actually set the ANSEL and ANSELH bits high. Now, when running the test, RA0 stayed high while RA1 flashed. So I put a small 10 cycle delay between RA0=0 and RA1=0. This solved the problem using PORTA functions.

    Great tip, and some interesting findings on this chip.
  4. ErnieM

    AAC Fanatic!

    Apr 24, 2011
    READ-modify-Write starts with a READ.

    With ANSEL set to make the I/O analog ALL reads return zero.

    When you execute RA1=1; you read PORTA, set bit 1, then write it back. However, if it reads zero for RA0 then it immediately resets this pin when RA1 is set.
  5. nigelwright7557

    AAC Fanatic!

    May 10, 2008
    The PIC reads the actual values on the port pins and not the output latch hence the odd results.