ESPHome 2025.5.0
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 ESP_LOGCONFIG(TAG, "Setting up ESP8266 PWM Output...");
18 this->pin_->setup();
19 this->turn_off();
20}
22 ESP_LOGCONFIG(TAG, "ESP8266 PWM:");
23 LOG_PIN(" Pin: ", this->pin_);
24 ESP_LOGCONFIG(TAG, " Frequency: %.1f Hz", this->frequency_);
25 LOG_FLOAT_OUTPUT(this);
26}
28 this->last_output_ = state;
29
30 // Also check pin inversion
31 if (this->pin_->is_inverted()) {
32 state = 1.0f - state;
33 }
34
35 auto total_time_us = static_cast<uint32_t>(roundf(1e6f / this->frequency_));
36 auto duty_on = static_cast<uint32_t>(roundf(total_time_us * state));
37 uint32_t duty_off = total_time_us - duty_on;
38
39 if (duty_on == 0) {
40 // This is a hacky fix for servos: Servo PWM high time is maximum 2.4ms by default
41 // The frequency check is to affect this fix for servos mostly as the frequency is usually 50-300 hz
42 if (this->pin_->digital_read() && 50 <= this->frequency_ && this->frequency_ <= 300) {
43 delay(3);
44 }
45 stopWaveform(this->pin_->get_pin());
46 this->pin_->digital_write(this->pin_->is_inverted());
47 } else if (duty_off == 0) {
48 stopWaveform(this->pin_->get_pin());
49 this->pin_->digital_write(!this->pin_->is_inverted());
50 } else {
51 startWaveform(this->pin_->get_pin(), duty_on, duty_off, 0);
52 }
53}
54
55} // namespace esp8266_pwm
56} // namespace esphome
57
58#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:28