Ei kuvausta
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

buttons.c 2.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. * buttons.c
  3. *
  4. * Copyright (c) 2024 Thomas Buck (thomas@xythobuz.de)
  5. *
  6. * This program is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * See <http://www.gnu.org/licenses/>.
  17. */
  18. #include <stdio.h>
  19. #include "pico/stdlib.h"
  20. #include "buttons.h"
  21. #define DEBOUNCE_DELAY_MS 50
  22. static const uint gpio_num[NUM_BTNS] = {
  23. 5, // BTN_A
  24. 6, // BTN_B
  25. 7, // BTN_C
  26. 8, // BTN_REC
  27. 11, // BTN_CLICK
  28. };
  29. struct button_state {
  30. uint32_t last_time;
  31. bool current_state, last_state;
  32. };
  33. static struct button_state buttons[NUM_BTNS];
  34. static void (*callback)(enum buttons, bool) = NULL;
  35. void buttons_init(void) {
  36. for (uint i = 0; i < NUM_BTNS; i++) {
  37. gpio_init(gpio_num[i]);
  38. gpio_set_dir(gpio_num[i], GPIO_IN);
  39. gpio_pull_up(gpio_num[i]);
  40. buttons[i].last_time = 0;
  41. buttons[i].current_state = false;
  42. buttons[i].last_state = false;
  43. }
  44. }
  45. void buttons_callback(void (*fp)(enum buttons, bool)) {
  46. callback = fp;
  47. }
  48. void buttons_run(void) {
  49. for (uint i = 0; i < NUM_BTNS; i++) {
  50. bool state = !gpio_get(gpio_num[i]);
  51. uint32_t now = to_ms_since_boot(get_absolute_time());
  52. if (state != buttons[i].last_state) {
  53. buttons[i].last_time = now;
  54. }
  55. if ((now - buttons[i].last_time) > DEBOUNCE_DELAY_MS) {
  56. if (state != buttons[i].current_state) {
  57. printf("btn %d now %s\n", i, state ? "pressed" : "released");
  58. buttons[i].current_state = state;
  59. if (callback) {
  60. callback(i, state);
  61. }
  62. }
  63. }
  64. buttons[i].last_state = state;
  65. }
  66. }