gpio.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #include "kbf/gpio.h"
  2. #include <esp_log.h>
  3. #include <esp_sleep.h>
  4. #include "kbf.h"
  5. #include "kbf/macros.h"
  6. using namespace kbf;
  7. gpio::Output::Output(int pin) : pin(static_cast<gpio_num_t>(pin)) {
  8. ESP_LOGI(TAG, "setting GPIO %d to OUTPUT mode", pin);
  9. CHECK(gpio_reset_pin(this->pin));
  10. CHECK(gpio_set_direction(this->pin, GPIO_MODE_OUTPUT));
  11. }
  12. void gpio::Output::high() const {
  13. gpio_set_level(pin, 1);
  14. }
  15. void gpio::Output::low() const {
  16. gpio_set_level(pin, 0);
  17. }
  18. bool gpio::Output::isHigh() const {
  19. return gpio_get_level(pin);
  20. }
  21. void gpio::Output::startPulse(int delay_ms, int limit) {
  22. ESP_LOGI(TAG, "starting pulse on GPIO %d; delay = %d, limit = %d", pin, delay_ms, limit);
  23. string taskName = "kbf_gpio_p" + std::to_string(pin);
  24. if (pulseTask != nullptr && pulseTask->isRunning()) {
  25. ESP_LOGE(TAG, "pulse task already running");
  26. ABORT("fix me");
  27. }
  28. pulseDelay = delay_ms;
  29. pulseLimit = limit;
  30. delete pulseTask;
  31. pulseTask = new Task(taskName, pulseCallback, this);
  32. }
  33. void gpio::Output::stopPulse() {
  34. ESP_LOGI(TAG, "stopping pulse on GPIO %d", pin);
  35. if (pulseTask == nullptr) {
  36. ESP_LOGE(TAG, "pulse task not running");
  37. ABORT("fix me");
  38. }
  39. pulseTask->stop();
  40. low();
  41. }
  42. void gpio::Output::pulseCallback(void *arg_ptr) {
  43. auto output = static_cast<Output *>(arg_ptr);
  44. int count = 0;
  45. while (output->pulseLimit < 0 || count++ < output->pulseLimit) {
  46. output->high();
  47. kbf::sleep(output->pulseDelay);
  48. output->low();
  49. kbf::sleep(output->pulseDelay);
  50. }
  51. }