change_bounce.c - uses a change notification interrupt to detect switch bounceΒΆ

Demonstrates the use of change notification interrupt to detect switch bounce.

 
#include "pic24_all.h"

volatile uint8_t bcnt;
//Interrupt Service Routine for Change Notification
void _ISRFAST _CNInterrupt (void) {
  _CNIF = 0;    //clear the change notification interrupt bit
  bcnt++;       //increment the bounce count
}


#define SW1             _RB13           //switch state
#define SW1_PRESSED()   (SW1==0)        //switch test
#define SW1_RELEASED()  (SW1==1)        //switch test
/// Switch1 configuration
inline void CONFIG_SW1()  {
  CONFIG_RB13_AS_DIG_INPUT();     //use RB13 for switch input
  ENABLE_RB13_PULLUP();           //enable the pullup
  ENABLE_RB13_CN_INTERRUPT();     //CN13IE = 1
}

int main (void) {
  configBasic(HELLO_MSG);
  /** Configure the switch ***********/
  CONFIG_SW1();  //enables individual CN interrupt also
  /** Configure Change Notification general interrupt  */
  _CNIF = 0;         //Clear the interrupt flag
  _CNIP = 2;         //Choose a priority
  _CNIE = 1;         //enable the Change Notification general interrupt
  while (1) {
    bcnt = 0;
    outString("Press & release switch... ");
    while (SW1_RELEASED());
    DELAY_MS(DEBOUNCE_DLY );
    while (SW1_PRESSED());
    DELAY_MS(DEBOUNCE_DLY );
    if (bcnt != 2) outString("..bounced: ");
    else outString("..no bounce: ");
    outUint8(bcnt);
    outString("\n");
  }
}