ESPHome  2024.12.2
esp8266_pwm.cpp
Go to the documentation of this file.
1 #ifdef USE_ESP8266
2 
3 #include "esp8266_pwm.h"
4 #include "esphome/core/macros.h"
5 #include "esphome/core/defines.h"
6 #include "esphome/core/log.h"
7 #include "esphome/core/helpers.h"
8 
9 #include <core_esp8266_waveform.h>
10 
11 namespace esphome {
12 namespace esp8266_pwm {
13 
14 static 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 }
27 void HOT ESP8266PWM::write_state(float state) {
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 digital_write(bool value)=0
virtual void turn_off()
Disable this binary output.
Definition: binary_output.h:51
void write_state(float state) override
Definition: esp8266_pwm.cpp:27
virtual void setup()=0
float last_output_
Cache last output level for dynamic frequency updating.
Definition: esp8266_pwm.h:35
virtual uint8_t get_pin() const =0
void setup() override
Initialize pin.
Definition: esp8266_pwm.cpp:16
virtual bool digital_read()=0
Implementation of SPI Controller mode.
Definition: a01nyub.cpp:7
virtual bool is_inverted() const =0
bool state
Definition: fan.h:34
void IRAM_ATTR HOT delay(uint32_t ms)
Definition: core.cpp:26