Toggling output pin in PIC C

Thread Starter

TheFish

Joined Jul 15, 2014
2
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:

Rich (BB code):
toggle = 1 - toggle;
PORTCbits.RC2 = toggle;
...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:

Rich (BB code):
PORTCbits.RC2 = 1 - PORTCbits.RC2;
Rich (BB code):
PORTCbits.RC2 = !PORTCbits.RC2;
Rich (BB code):
PORTCbits.RC2 ^= 1;
Any help is appreciated.
 

NorthGuy

Joined Jun 28, 2014
611
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.
 

THE_RB

Joined Feb 11, 2008
5,438
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.
 
Top