ESPHome 2025.9.0-dev
Loading...
Searching...
No Matches
esp8266_pwm.cpp
Go to the documentation of this file.
1#ifdef USE_ESP8266
2
3#include "esp8266_pwm.h"
6#include "esphome/core/log.h"
8
9#include <core_esp8266_waveform.h>
10
11namespace esphome {
12namespace esp8266_pwm {
13
14static const char *const TAG = "esp8266_pwm";
15
17 this->pin_->setup();
18 this->turn_off();
19}
21 ESP_LOGCONFIG(TAG, "ESP8266 PWM:");
22 LOG_PIN(" Pin: ", this->pin_);
23 ESP_LOGCONFIG(TAG, " Frequency: %.1f Hz", this->frequency_);
24 LOG_FLOAT_OUTPUT(this);
25}
27 this->last_output_ = state;
28
29 // Also check pin inversion
30 if (this->pin_->is_inverted()) {
31 state = 1.0f - state;
32 }
33
34 auto total_time_us = static_cast<uint32_t>(roundf(1e6f / this->frequency_));
35 auto duty_on = static_cast<uint32_t>(roundf(total_time_us * state));
36 uint32_t duty_off = total_time_us - duty_on;
37
38 if (duty_on == 0) {
39 // This is a hacky fix for servos: Servo PWM high time is maximum 2.4ms by default
40 // The frequency check is to affect this fix for servos mostly as the frequency is usually 50-300 hz
41 if (this->pin_->digital_read() && 50 <= this->frequency_ && this->frequency_ <= 300) {
42 delay(3);
43 }
44 stopWaveform(this->pin_->get_pin());
45 this->pin_->digital_write(this->pin_->is_inverted());
46 } else if (duty_off == 0) {
47 stopWaveform(this->pin_->get_pin());
48 this->pin_->digital_write(!this->pin_->is_inverted());
49 } else {
50 startWaveform(this->pin_->get_pin(), duty_on, duty_off, 0);
51 }
52}
53
54} // namespace esp8266_pwm
55} // namespace esphome
56
57#endif
virtual void setup()=0
virtual void digital_write(bool value)=0
virtual bool digital_read()=0
virtual uint8_t get_pin() const =0
virtual bool is_inverted() const =0
float last_output_
Cache last output level for dynamic frequency updating.
Definition esp8266_pwm.h:35
void write_state(float state) override
void setup() override
Initialize pin.
virtual void turn_off()
Disable this binary output.
bool state
Definition fan.h:0
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
void IRAM_ATTR HOT delay(uint32_t ms)
Definition core.cpp:29