No Description
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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*
  2. * buttons.c
  3. *
  4. * Copyright (c) 2022 - 2023 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 "pico/stdlib.h"
  19. #include "config.h"
  20. #include "log.h"
  21. #include "buttons.h"
  22. static const uint gpio_num[NUM_BTNS] = {
  23. 15, // BTN_A
  24. 17, // BTN_B
  25. 19, // BTN_X
  26. 21, // BTN_Y
  27. 2, // BTN_UP
  28. 18, // BTN_DOWN
  29. 16, // BTN_LEFT
  30. 20, // BTN_RIGHT
  31. 3, // BTN_ENTER
  32. };
  33. struct button_state {
  34. uint32_t last_time;
  35. bool current_state, last_state;
  36. };
  37. static struct button_state buttons[NUM_BTNS];
  38. static void (*callback)(enum buttons, bool) = NULL;
  39. void buttons_init(void) {
  40. for (uint i = 0; i < NUM_BTNS; i++) {
  41. gpio_init(gpio_num[i]);
  42. gpio_set_dir(gpio_num[i], GPIO_IN);
  43. gpio_pull_up(gpio_num[i]);
  44. buttons[i].last_time = 0;
  45. buttons[i].current_state = false;
  46. buttons[i].last_state = false;
  47. }
  48. }
  49. void buttons_callback(void (*fp)(enum buttons, bool)) {
  50. callback = fp;
  51. }
  52. void buttons_run(void) {
  53. for (uint i = 0; i < NUM_BTNS; i++) {
  54. bool state = !gpio_get(gpio_num[i]);
  55. uint32_t now = to_ms_since_boot(get_absolute_time());
  56. if (state != buttons[i].last_state) {
  57. buttons[i].last_time = now;
  58. }
  59. if ((now - buttons[i].last_time) > DEBOUNCE_DELAY_MS) {
  60. if (state != buttons[i].current_state) {
  61. //debug("btn %d now %s", i, state ? "pressed" : "released");
  62. buttons[i].current_state = state;
  63. if (callback) {
  64. callback(i, state);
  65. }
  66. }
  67. }
  68. buttons[i].last_state = state;
  69. }
  70. }