PIC24FJ64GA002 Microcontroller Output Compare and Timers button pressing

Thread Starter


Joined Mar 15, 2020
Hi all,

I am having trouble implementing a program to detect the double-click of a button in order to move my servo to the left, waiting 2 seconds until it is moved back. I am using the output compare module and timer 3 to send my PWM signal to my servo in order to make it move and I have tested it to be working. My problem is that even when I hit the button once, my servo moves.. One problem I can see my program having is it looping really fast and thinking that I am hitting the button more than once? I'm not really sure. I have been troubleshooting this for a while so some advice/tips would be greatly appreciated. My main source file is below:

int main(void)
setup(); //configure timers, output compare module, set up PIC pins for input and output

unsigned int curState = 1, wasPressed = 0, timeBetween = 0;

while (1)
curState = PORTBbits.RB8; //Get current button state

if (curState == 0 && !wasPressed) //check if button was pressed for the first time
TMR2 = 0; //reset timer
overFlow = 0; //variable to track TMR2 overlow
wasPressed = 1; //set variable high to represent the button has been pressed
} else

if (curState == 0 && wasPressed) //check if button was pressed for the second time
wasPressed = 0;
timeBetween = TMR2 + 62500L * overFlow; //calculate time in between button presses
if (timeBetween <= 15624 && timeBetween != 0) //check if time between button presses is less than or equal to 0.25 seconds
setServo(3599); //move servo
timeBetween = 0; //reset variable

curState = 1; //reset curState to indicate no button presses
wait_2ms(); //added to prevent for button debouncing

return (0);

Let me know if any additional code is needed


Joined Mar 10, 2019
All buttons/switches have some contact bounce. You have to "de-bounce" your buttons. Most common way is to wait several milli seconds (like 20 to 30ms) to let the button contacts settle, no more bouncing.
A more elaborate method is to detect the first contact, and do a tight timing loop looking for a bounce, then reset the timer. Once you have no bounce after the timer period, you can be sure the button has settled.