S&B Volcano vaporizer remote control with Pi Pico W
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.0KB

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