ESPHome 2026.3.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,
22 "ESP8266 PWM:\n"
23 " Frequency: %.1f Hz",
24 this->frequency_);
25 LOG_PIN(" Pin: ", this->pin_);
26 LOG_FLOAT_OUTPUT(this);
27}
29 this->last_output_ = state;
30
31 // Also check pin inversion
32 if (this->pin_->is_inverted()) {
33 state = 1.0f - state;
34 }
35
36 auto total_time_us = static_cast<uint32_t>(roundf(1e6f / this->frequency_));
37 auto duty_on = static_cast<uint32_t>(roundf(total_time_us * state));
38 uint32_t duty_off = total_time_us - duty_on;
39
40 if (duty_on == 0) {
41 // This is a hacky fix for servos: Servo PWM high time is maximum 2.4ms by default
42 // The frequency check is to affect this fix for servos mostly as the frequency is usually 50-300 hz
43 if (this->pin_->digital_read() && 50 <= this->frequency_ && this->frequency_ <= 300) {
44 delay(3);
45 }
46 stopWaveform(this->pin_->get_pin());
47 this->pin_->digital_write(this->pin_->is_inverted());
48 } else if (duty_off == 0) {
49 stopWaveform(this->pin_->get_pin());
50 this->pin_->digital_write(!this->pin_->is_inverted());
51 } else {
52 startWaveform(this->pin_->get_pin(), duty_on, duty_off, 0);
53 }
54}
55
56} // namespace esp8266_pwm
57} // namespace esphome
58
59#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:2
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
void HOT delay(uint32_t ms)
Definition core.cpp:27
int stopWaveform(uint8_t pin)