roo_blink
API Documentation for roo_blink
Loading...
Searching...
No Matches
led_esp32.cpp
Go to the documentation of this file.
2
3#include "esp_err.h"
4#include "roo_logging.h"
5
6#if defined(ESP32)
7
8namespace roo_blink {
9namespace esp32 {
10
11static constexpr ledc_timer_bit_t kDutyRes = LEDC_TIMER_10_BIT;
12static constexpr int kDuty = 1 << kDutyRes;
13
14static constexpr int kFreq = 40000;
15
16GpioLed::GpioLed(int gpio_num, Mode mode, ledc_timer_t timer_num,
17 ledc_channel_t channel)
18 : channel_(channel), mode_(mode) {
19 ledc_timer_config_t ledc_timer = {.speed_mode = LEDC_LOW_SPEED_MODE,
20 .duty_resolution = kDutyRes,
21 .timer_num = timer_num,
22 .freq_hz = kFreq,
23 .clk_cfg = LEDC_AUTO_CLK};
24 ESP_ERROR_CHECK(ledc_timer_config(&ledc_timer));
25
26 // Prepare and then apply the LEDC PWM channel configuration
27 ledc_channel_config_t ledc_channel = {.gpio_num = gpio_num,
28 .speed_mode = LEDC_LOW_SPEED_MODE,
29 .channel = channel,
30 .intr_type = LEDC_INTR_DISABLE,
31 .timer_sel = timer_num,
32 .duty = 0,
33 .hpoint = 0};
34 ESP_ERROR_CHECK(ledc_channel_config(&ledc_channel));
35
36 ledc_fade_func_install(0);
37}
38
39void GpioLed::setLevel(uint16_t level) {
40 ledc_set_duty(LEDC_LOW_SPEED_MODE, channel_, dutyForLevel(level));
41 ledc_update_duty(LEDC_LOW_SPEED_MODE, channel_);
42}
43
44bool GpioLed::fade(uint16_t target_level, roo_time::Duration duration) {
45 ESP_ERROR_CHECK(ledc_set_fade_with_time(LEDC_LOW_SPEED_MODE, channel_,
46 dutyForLevel(target_level),
47 duration.inMillis()));
48
49 ESP_ERROR_CHECK(
50 ledc_fade_start(LEDC_LOW_SPEED_MODE, channel_, LEDC_FADE_NO_WAIT));
51
52 return true;
53}
54
55int GpioLed::dutyForLevel(uint16_t level) const {
56 if (mode_ == ON_LOW) {
57 level = 65535 - level;
58 }
59 return (uint32_t)level * kDuty / 65536;
60}
61
62#if CONFIG_IDF_TARGET_ESP32C3
63static const int kBuiltinLedPin = 8;
64static const GpioLed::Mode kBuiltinLedMode = GpioLed::ON_HIGH;
65#else
66static const int kBuiltinLedPin = 2;
67static const GpioLed::Mode kBuiltinLedMode = GpioLed::ON_HIGH;
68#endif
69
70Led& BuiltinLed() {
71 static GpioLed instance(kBuiltinLedPin, kBuiltinLedMode);
72 return instance;
73}
74
75} // namespace esp32
76} // namespace roo_blink
77
78#endif