Microchip® Advanced Software Framework

Debounce filter on a button

In this use case, a simple debounce filter on a button will be set up.

Setup steps

Prerequisites

For the setup code of this use case to work, the following must be added to the project:

  1. System Clock Management
  2. Programmable Multilevel Interrupt Controller
  3. General Purpose Input/Output
  4. Real Time Counter (RTC)
  5. Configuration info for the timeout service must be added to the conf_timeout.h file (located in the config folder):
    #define TIMEOUT_CLOCK_SOURCE_HZ 1024
    #define TIMEOUT_COUNT 1
    #define TIMEOUT_TICK_HZ 100
  6. Configuration info for the RTC driver must be added to the conf_rtc.h file (located in the config folder):
    #define CONFIG_RTC_PRESCALER RTC_PRESCALER_DIV1_gc
    #define CONFIG_RTC_CLOCK_SOURCE CLK_RTCSRC_ULP_gc

Example code

The following must be added to the project:

#define DEBOUNCE_TIMEOUT 0
#define DEBOUNCE_TICKS (50 * TIMEOUT_TICK_HZ / 1000)

Add to application initialization:

Workflow

  1. Initialize system clock:
  2. Initialize the PMIC driver:
  3. Initialize timeout service:
    • timout_init();

Example code

Add to application C-file:

bool button_previous_state_pressed = false;
while (1) {
button_pressed = gpio_pin_is_low(GPIO_PUSH_BUTTON_0);
if (button_previous_state_pressed != button_pressed) {
button_previous_state_pressed = button_pressed;
}
if (button_pressed) {
gpio_toggle_pin(LED0_GPIO);
}
}
}

Workflow

  1. Create a variable to hold state of push button:
  2. Create a variable to hold previous state of push button:
    • bool button_previous_state_pressed;
  3. Get button state:
  4. Check if button state has changed since last iteration:
    • if (button_previous_state_pressed != button_pressed)
  5. Start debounce timeout:
  6. Set previous state of button:
  7. Check if debounce timeout has expired:
  8. Check if button is pressed down:
    • if (button_pressed)
  9. Toggle led: