ESPHome 2025.9.0-dev
Loading...
Searching...
No Matches
rp2040_pwm.cpp
Go to the documentation of this file.
1#ifdef USE_RP2040
2
3#include "rp2040_pwm.h"
6#include "esphome/core/log.h"
8
9#include <hardware/clocks.h>
10#include <hardware/gpio.h>
11#include <hardware/pwm.h>
12#include <cmath>
13
14namespace esphome {
15namespace rp2040_pwm {
16
17static const char *const TAG = "rp2040_pwm";
18
19void RP2040PWM::setup() { this->setup_pwm_(); }
20
22 pwm_config config = pwm_get_default_config();
23
24 uint32_t clock = clock_get_hz(clk_sys);
25 float divider = ceil(clock / (4096 * this->frequency_)) / 16.0f;
26 if (divider < 1.0f) {
27 divider = 1.0f;
28 }
29 uint16_t wrap = clock / divider / this->frequency_ - 1;
30 this->wrap_ = wrap;
31 ESP_LOGD(TAG, "divider=%.5f, wrap=%d, clock=%d", divider, wrap, clock);
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}
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
virtual uint8_t get_pin() const =0
virtual bool is_inverted() const =0
void write_state(float state) override
float last_output_
Cache last output level for dynamic frequency updating.
Definition rp2040_pwm.h:39
void setup() override
Initialize pin.
bool state
Definition fan.h:0
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7