ESPHome  2023.3.2
rp2040_pwm.cpp
Go to the documentation of this file.
1 #ifdef USE_RP2040
2 
3 #include "rp2040_pwm.h"
4 #include "esphome/core/defines.h"
5 #include "esphome/core/helpers.h"
6 #include "esphome/core/log.h"
7 #include "esphome/core/macros.h"
8 
9 #include <hardware/clocks.h>
10 #include <hardware/gpio.h>
11 #include <hardware/pwm.h>
12 #include <cmath>
13 
14 namespace esphome {
15 namespace rp2040_pwm {
16 
17 static const char *const TAG = "rp2040_pwm";
18 
20  ESP_LOGCONFIG(TAG, "Setting up RP2040 PWM Output...");
21 
22  this->setup_pwm_();
23 }
24 
26  pwm_config config = pwm_get_default_config();
27 
28  uint32_t clock = clock_get_hz(clk_sys);
29  float divider = ceil(clock / (4096 * this->frequency_)) / 16.0f;
30  uint16_t wrap = clock / divider / this->frequency_ - 1;
31  this->wrap_ = wrap;
32 
33  pwm_config_set_clkdiv(&config, divider);
34  pwm_config_set_wrap(&config, wrap);
35  pwm_init(pwm_gpio_to_slice_num(this->pin_->get_pin()), &config, true);
36 }
37 
39  ESP_LOGCONFIG(TAG, "RP2040 PWM:");
40  LOG_PIN(" Pin: ", this->pin_);
41  ESP_LOGCONFIG(TAG, " Frequency: %.1f Hz", this->frequency_);
42  LOG_FLOAT_OUTPUT(this);
43 }
44 void HOT RP2040PWM::write_state(float state) {
45  this->last_output_ = state;
46 
47  // Also check pin inversion
48  if (this->pin_->is_inverted()) {
49  state = 1.0f - state;
50  }
51 
52  if (this->frequency_changed_) {
53  this->setup_pwm_();
54  this->frequency_changed_ = false;
55  }
56 
57  gpio_set_function(this->pin_->get_pin(), GPIO_FUNC_PWM);
58  pwm_set_gpio_level(this->pin_->get_pin(), state * this->wrap_);
59 }
60 
61 } // namespace rp2040_pwm
62 } // namespace esphome
63 
64 #endif
void setup() override
Initialize pin.
Definition: rp2040_pwm.cpp:19
InternalGPIOPin * pin_
Definition: rp2040_pwm.h:35
virtual uint8_t get_pin() const =0
void write_state(float state) override
Definition: rp2040_pwm.cpp:44
Definition: a4988.cpp:4
float last_output_
Cache last output level for dynamic frequency updating.
Definition: rp2040_pwm.h:39
virtual bool is_inverted() const =0
bool state
Definition: fan.h:34