Skip to content

Instantly share code, notes, and snippets.

@kates
Last active July 29, 2021 02:25
Show Gist options
  • Save kates/9d8b33587b01694898e3f874142db5f3 to your computer and use it in GitHub Desktop.
Save kates/9d8b33587b01694898e3f874142db5f3 to your computer and use it in GitHub Desktop.
Simple IRQ Button Debounce for Raspberry Pi Pico
#include <stdio.h>
#include "hardware/irq.h"
#include "hardware/gpio.h"
#include "pico/stdlib.h"
#include "pico/time.h"
static const uint8_t DEBOUNCE = 50;
static bool pressed = false;
static int32_t alarm_id = 0;
int64_t enable_button(alarm_id_t alarm_id, void *user_data) {
pressed = false;
return 0;
}
void gpio_callback(uint gpio, uint32_t events) {
if (pressed) {
cancel_alarm(alarm_id);
} else {
pressed = true;
printf("Button pressed: %d\n", gpio);
}
alarm_id = add_alarm_in_ms(DEBOUNCE, enable_button, NULL, false);
}
int main() {
const uint LED_PIN = PICO_DEFAULT_LED_PIN;
const uint32_t events = GPIO_IRQ_LEVEL_HIGH;
const uint8_t sleep_time = 250;
stdio_init_all();
gpio_init(LED_PIN);
gpio_set_dir(LED_PIN, GPIO_OUT);
gpio_init(21);
gpio_pull_down(21);
gpio_init(15);
gpio_pull_down(15);
gpio_init(16);
gpio_pull_down(16);
gpio_set_irq_enabled_with_callback(21, events, true, &gpio_callback);
gpio_set_irq_enabled(16, events, true);
gpio_set_irq_enabled(15, events, true);
while(1) {
gpio_put(LED_PIN, 1);
sleep_ms(sleep_time);
gpio_put(LED_PIN, 0);
sleep_ms(sleep_time);
}
}
// vim: sw=4 ts=4 et
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment