/* Callback function called by the Timer System Service to debounce the switch and blink the LED. This will run every APP_LED_BLINK_DELAY milliseconds as long as the timer object exists. */ void APP_TimerCallback2 ( uintptr_t context, uint32_t tickCount ) { uint32_t portBits2; /* If in a blinking state, blink the LED. */ if ( appData.state == APP_STATE_BLINK_LED_DEBOUNCE_RELEASE || appData.state == APP_STATE_BLINK_LED_NO_PRESS_DETECT || appData.state == APP_STATE_BLINK_LED_DEBOUNCE_PRESS) { /* Change state of I/O Port pin connected to LED. */ BSP_LEDToggle(APP_BSP_LED); } /* Debounce switch press. */ /* If the switch is not pressed, and we are in a state looking to confirm a press, debounce the switch. */ if ( ! appData.switchIsPressed) { if ( appData.state == APP_STATE_LED_OFF_DEBOUNCE_PRESS || appData.state == APP_STATE_BLINK_LED_DEBOUNCE_PRESS) { appData.timeoutCounter++; portBits2 = PLIB_PORTS_Read(PORTS_ID_0, APP_SWITCH_PORT); /* If pressed switch puts 0 on pin, test for a 0 on pin. */ if (APP_PRESS_EQUALS_1_OR_0 == 0) { /* If pin = 1, switch is still bouncing. Reset count. */ if ( (1 << APP_SWITCH_BIT) & portBits2) { appData.debounceCounter = 0; } /* Pin = 0. Switch is stable. Increment count. */ else { appData.debounceCounter++; } } /* If pressed switch puts 1 on pin, test for a 1 on pin. */ else { /* If pin = 0, switch is still bouncing. Reset count. */ if ( !((1 << APP_SWITCH_BIT) & portBits2)) { appData.debounceCounter = 0; } /* Pin = 1. Switch is stable. Increment count. */ else { appData.debounceCounter++; } } /* If switch is pressed for APP_DEBOUNCE_COUNT counts, switch press confirmed (switch debounced). Set switchIsPressed flag */ if (appData.debounceCounter >= APP_DEBOUNCE_COUNT) { appData.switchIsPressed = true; } } } /* Debounce switch release. */ /* If the switch is pressed, and we are in a state looking to confirm a switch release (no press), debounce the switch. */ else { if ( appData.state == APP_STATE_BLINK_LED_DEBOUNCE_RELEASE || appData.state == APP_STATE_LED_OFF_DEBOUNCE_RELEASE ) { portBits2 = PLIB_PORTS_Read(PORTS_ID_0, APP_SWITCH_PORT); /* If released switch puts 1 on pin, test for a 1 on pin. */ if (APP_PRESS_EQUALS_1_OR_0 == 0) { /* If pin = 0, switch is still bouncing. Reset count. */ if ( !((1 << APP_SWITCH_BIT) & portBits2) ) { appData.debounceCounter = 0; // reset count } /* Pin = 1. Switch is stable. Increment count. */ else { appData.debounceCounter++; } } /* If released switch puts 0 on pin, test for a 0 on pin. */ else { /* If pin = 1, switch is still bouncing. Reset count. */ if ( (1 << APP_SWITCH_BIT) & portBits2 ) { appData.debounceCounter = 0; } /* Pin = 0. Switch is stable. Increment count. */ else { appData.debounceCounter++; } } /* If switch is released for APP_DEBOUNCE_COUNT counts, switch release confirmed (switch debounced). Clear switchIsPressed flag */ if (appData.debounceCounter >= APP_DEBOUNCE_COUNT) { appData.switchIsPressed = false; } } } }