button_matrix.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /*
  2. * SPDX-FileCopyrightText: 2023-2024 Espressif Systems (Shanghai) CO LTD
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. #include "esp_log.h"
  7. #include "driver/gpio.h"
  8. #include "button_matrix.h"
  9. static const char *TAG = "matrix button";
  10. #define MATRIX_BTN_CHECK(a, str, ret_val) \
  11. if (!(a)) \
  12. { \
  13. ESP_LOGE(TAG, "%s(%d): %s", __FUNCTION__, __LINE__, str); \
  14. return (ret_val); \
  15. }
  16. esp_err_t button_matrix_init(const button_matrix_config_t *config)
  17. {
  18. MATRIX_BTN_CHECK(NULL != config, "Pointer of config is invalid", ESP_ERR_INVALID_ARG);
  19. MATRIX_BTN_CHECK(GPIO_IS_VALID_GPIO(config->row_gpio_num), "row GPIO number error", ESP_ERR_INVALID_ARG);
  20. MATRIX_BTN_CHECK(GPIO_IS_VALID_GPIO(config->col_gpio_num), "col GPIO number error", ESP_ERR_INVALID_ARG);
  21. // set row gpio as output
  22. gpio_config_t gpio_conf = {0};
  23. gpio_conf.intr_type = GPIO_INTR_DISABLE;
  24. gpio_conf.mode = GPIO_MODE_OUTPUT;
  25. gpio_conf.pull_down_en = GPIO_PULLDOWN_ENABLE;
  26. gpio_conf.pin_bit_mask = (1ULL << config->row_gpio_num);
  27. gpio_config(&gpio_conf);
  28. // set col gpio as input
  29. gpio_conf.mode = GPIO_MODE_INPUT;
  30. gpio_conf.pin_bit_mask = (1ULL << config->col_gpio_num);
  31. gpio_config(&gpio_conf);
  32. return ESP_OK;
  33. }
  34. esp_err_t button_matrix_deinit(int row_gpio_num, int col_gpio_num)
  35. {
  36. //Reset an gpio to default state (select gpio function, enable pullup and disable input and output).
  37. gpio_reset_pin(row_gpio_num);
  38. gpio_reset_pin(col_gpio_num);
  39. return ESP_OK;
  40. }
  41. uint8_t button_matrix_get_key_level(void *hardware_data)
  42. {
  43. uint32_t row = MATRIX_BUTTON_SPLIT_ROW(hardware_data);
  44. uint32_t col = MATRIX_BUTTON_SPLIT_COL(hardware_data);
  45. gpio_set_level(row, 1);
  46. uint8_t level = gpio_get_level(col);
  47. gpio_set_level(row, 0);
  48. return level;
  49. }