Toggling output pin in PIC C

Discussion in 'Embedded Systems and Microcontrollers' started by TheFish, Jul 15, 2014.

  1. TheFish

    Thread Starter New Member

    Jul 15, 2014
    2
    0
    I have an interrupt handler that toggles an output pin between on and off each time it runs.

    If I use a variable and then assign its value to the port register then it works as expected:

    Code ( (Unknown Language)):
    1.  
    2. toggle = 1 - toggle;
    3. PORTCbits.RC2 = toggle;
    4.  
    ...but If I eliminate the variable, or try to use bitwise logic directly on the pin then the pin just turns on and stays on. None of these work:

    Code ( (Unknown Language)):
    1.  
    2. PORTCbits.RC2 = 1 - PORTCbits.RC2;
    3.  
    Code ( (Unknown Language)):
    1.  
    2. PORTCbits.RC2 = !PORTCbits.RC2;
    3.  
    Code ( (Unknown Language)):
    1.  
    2. PORTCbits.RC2 ^= 1;
    3.  
    Any help is appreciated.
     
  2. NorthGuy

    Active Member

    Jun 28, 2014
    605
    121
    On many PICs pins are analog by default, in which case they always read 0. So you need to make PORTC pins digital.

    Or, if your PIC has LATC, you can use LATC instead of PORTC and this will alleviate the problem.
     
    TheFish likes this.
  3. TheFish

    Thread Starter New Member

    Jul 15, 2014
    2
    0
    That was it. Thanks.

    I need to start paying more attention to datasheets...
     
  4. THE_RB

    AAC Fanatic!

    Feb 11, 2008
    5,435
    1,305
    It is also a very good idea to use a shadow register (or shadow bit) to set the port pin.

    That way you are not reading the pin, which eliminates one type of Read-Modify-Write bug that the hardware has.
     
Loading...