SensESP 3.0.1
Universal Signal K sensor toolkit ESP32
Loading...
Searching...
No Matches
pwm_output.cpp
Go to the documentation of this file.
1#include "sensesp.h"
2
3#include "pwm_output.h"
4
5#include <algorithm>
6
7namespace sensesp {
8
9// For info on frequency and resolution for ESP32, see
10// https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/peripherals/ledc.html#ledc-api-supported-range-frequency-duty-resolution
11
12std::map<uint8_t, int8_t> PWMOutput::channel_to_pin_;
13
14PWMOutput::PWMOutput(int pin, int pwm_channel, int channel_frequency,
15 int channel_resolution)
16 : ValueConsumer<float>(),
17 pwm_channel_{static_cast<uint8_t>(pwm_channel)},
18 channel_frequency_{channel_frequency},
19 channel_resolution_{channel_resolution},
20 pwmrange_{static_cast<int>(pow(2, channel_resolution) - 1)} {
21 if (pin >= 0) {
22 pwm_channel_ = assign_channel(pin, pwm_channel);
23 }
24}
25
26void PWMOutput::set(const float& new_value) { set_pwm(new_value); }
27
28int PWMOutput::assign_channel(int pin, int pwm_channel) {
29 if (pwm_channel == -1) {
30 // Do a search for the next available channel
31 std::map<uint8_t, int8_t>::iterator it;
32 pwm_channel = 0;
33 do {
34 pwm_channel++;
35 it = channel_to_pin_.find(pwm_channel);
36 } while (it != channel_to_pin_.end());
37 }
38
39 channel_to_pin_[pwm_channel] = pin;
40
41 ESP_LOGD(__FILENAME__, "PWM channel %d assigned to pin %d", pwm_channel, pin);
42
43 pinMode(pin, OUTPUT);
44 ledcSetup(pwm_channel, channel_frequency_, channel_resolution_);
45 ledcAttachPin(pin, pwm_channel);
46
47 return pwm_channel;
48}
49
50void PWMOutput::set_pwm(float value) {
51 std::map<uint8_t, int8_t>::iterator it;
53 if (it != channel_to_pin_.end()) {
54 int pin = it->second;
55 int const output_val = value * pwmrange_;
56 ESP_LOGD(__FILENAME__, "Outputting %d to pwm channel %d (pin %d)",
57 output_val, pwm_channel_, pin);
58 ledcWrite(pwm_channel_, output_val);
59 } else {
60 ESP_LOGW(__FILENAME__, "No pin assigned to channel %d. Ignoring set_pwm()",
62 }
63}
64
65} // namespace sensesp
void set_pwm(float value)
PWMOutput(int pin=-1, int pwm_channel=-1, int channel_frequency=5000, int channel_resolution=13)
static std::map< uint8_t, int8_t > channel_to_pin_
Definition pwm_output.h:59
int assign_channel(int pin, int pwm_channel=-1)
virtual void set(const float &new_value) override
A base class for piece of code (like a transform) that accepts data for input. ValueConsumers can acc...