ESPHome 2025.5.0
Loading...
Searching...
No Matches
ac_dimmer.cpp
Go to the documentation of this file.
1#ifdef USE_ARDUINO
2
3#include "ac_dimmer.h"
5#include "esphome/core/log.h"
6#include <cmath>
7
8#ifdef USE_ESP8266
9#include <core_esp8266_waveform.h>
10#endif
11#ifdef USE_ESP32_FRAMEWORK_ARDUINO
12#include <esp32-hal-timer.h>
13#endif
14
15namespace esphome {
16namespace ac_dimmer {
17
18static const char *const TAG = "ac_dimmer";
19
20// Global array to store dimmer objects
21static AcDimmerDataStore *all_dimmers[32]; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
22
29static const uint32_t GATE_ENABLE_TIME = 50;
30
34uint32_t IRAM_ATTR HOT AcDimmerDataStore::timer_intr(uint32_t now) {
35 // If no ZC signal received yet.
36 if (this->crossed_zero_at == 0)
37 return 0;
38
39 uint32_t time_since_zc = now - this->crossed_zero_at;
40 if (this->value == 65535 || this->value == 0) {
41 return 0;
42 }
43
44 if (this->enable_time_us != 0 && time_since_zc >= this->enable_time_us) {
45 this->enable_time_us = 0;
46 this->gate_pin.digital_write(true);
47 // Prevent too short pulses
48 this->disable_time_us = std::max(this->disable_time_us, time_since_zc + GATE_ENABLE_TIME);
49 }
50 if (this->disable_time_us != 0 && time_since_zc >= this->disable_time_us) {
51 this->disable_time_us = 0;
52 this->gate_pin.digital_write(false);
53 }
54
55 if (time_since_zc < this->enable_time_us) {
56 // Next event is enable, return time until that event
57 return this->enable_time_us - time_since_zc;
58 } else if (time_since_zc < disable_time_us) {
59 // Next event is disable, return time until that event
60 return this->disable_time_us - time_since_zc;
61 }
62
63 if (time_since_zc >= this->cycle_time_us) {
64 // Already past last cycle time, schedule next call shortly
65 return 100;
66 }
67
68 return this->cycle_time_us - time_since_zc;
69}
70
72uint32_t IRAM_ATTR HOT timer_interrupt() {
73 // run at least with 1kHz
74 uint32_t min_dt_us = 1000;
75 uint32_t now = micros();
76 for (auto *dimmer : all_dimmers) {
77 if (dimmer == nullptr) {
78 // no more dimmers
79 break;
80 }
81 uint32_t res = dimmer->timer_intr(now);
82 if (res != 0 && res < min_dt_us)
83 min_dt_us = res;
84 }
85 // return time until next timer1 interrupt in µs
86 return min_dt_us;
87}
88
90void IRAM_ATTR HOT AcDimmerDataStore::gpio_intr() {
91 uint32_t prev_crossed = this->crossed_zero_at;
92
93 // 50Hz mains frequency should give a half cycle of 10ms a 60Hz will give 8.33ms
94 // in any case the cycle last at least 5ms
95 this->crossed_zero_at = micros();
96 uint32_t cycle_time = this->crossed_zero_at - prev_crossed;
97 if (cycle_time > 5000) {
98 this->cycle_time_us = cycle_time;
99 } else {
100 // Otherwise this is noise and this is 2nd (or 3rd...) fall in the same pulse
101 // Consider this is the right fall edge and accumulate the cycle time instead
102 this->cycle_time_us += cycle_time;
103 }
104
105 if (this->value == 65535) {
106 // fully on, enable output immediately
107 this->gate_pin.digital_write(true);
108 } else if (this->init_cycle) {
109 // send a full cycle
110 this->init_cycle = false;
111 this->enable_time_us = 0;
113 } else if (this->value == 0) {
114 // fully off, disable output immediately
115 this->gate_pin.digital_write(false);
116 } else {
117 auto min_us = this->cycle_time_us * this->min_power / 1000;
118 if (this->method == DIM_METHOD_TRAILING) {
119 this->enable_time_us = 1; // cannot be 0
120 // calculate time until disable in µs with integer arithmetic and take into account min_power
121 this->disable_time_us = std::max((uint32_t) 10, this->value * (this->cycle_time_us - min_us) / 65535 + min_us);
122 } else {
123 // calculate time until enable in µs: (1.0-value)*cycle_time, but with integer arithmetic
124 // also take into account min_power
125 this->enable_time_us = std::max((uint32_t) 1, ((65535 - this->value) * (this->cycle_time_us - min_us)) / 65535);
126
127 if (this->method == DIM_METHOD_LEADING_PULSE) {
128 // Minimum pulse time should be enough for the triac to trigger when it is close to the ZC zone
129 // this is for brightness near 99%
130 this->disable_time_us = std::max(this->enable_time_us + GATE_ENABLE_TIME, (uint32_t) cycle_time_us / 10);
131 } else {
132 this->gate_pin.digital_write(false);
133 this->disable_time_us = this->cycle_time_us;
134 }
135 }
136 }
137}
138
140 // Attaching pin interrupts on the same pin will override the previous interrupt
141 // However, the user expects that multiple dimmers sharing the same ZC pin will work.
142 // We solve this in a bit of a hacky way: On each pin interrupt, we check all dimmers
143 // if any of them are using the same ZC pin, and also trigger the interrupt for *them*.
144 for (auto *dimmer : all_dimmers) {
145 if (dimmer == nullptr)
146 break;
147 if (dimmer->zero_cross_pin_number == store->zero_cross_pin_number) {
148 dimmer->gpio_intr();
149 }
150 }
151}
152
153#ifdef USE_ESP32
154// ESP32 implementation, uses basically the same code but needs to wrap
155// timer_interrupt() function to auto-reschedule
156static hw_timer_t *dimmer_timer = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
158#endif
159
161 // extend all_dimmers array with our dimmer
162
163 // Need to be sure the zero cross pin is setup only once, ESP8266 fails and ESP32 seems to fail silently
164 auto setup_zero_cross_pin = true;
165
166 for (auto &all_dimmer : all_dimmers) {
167 if (all_dimmer == nullptr) {
168 all_dimmer = &this->store_;
169 break;
170 }
171 if (all_dimmer->zero_cross_pin_number == this->zero_cross_pin_->get_pin()) {
172 setup_zero_cross_pin = false;
173 }
174 }
175
176 this->gate_pin_->setup();
177 this->store_.gate_pin = this->gate_pin_->to_isr();
179 this->store_.min_power = static_cast<uint16_t>(this->min_power_ * 1000);
180 this->min_power_ = 0;
181 this->store_.method = this->method_;
182
183 if (setup_zero_cross_pin) {
184 this->zero_cross_pin_->setup();
188 }
189
190#ifdef USE_ESP8266
191 // Uses ESP8266 waveform (soft PWM) class
192 // PWM and AcDimmer can even run at the same time this way
193 setTimer1Callback(&timer_interrupt);
194#endif
195#ifdef USE_ESP32
196 // 80 Divider -> 1 count=1µs
197 dimmer_timer = timerBegin(0, 80, true);
198 timerAttachInterrupt(dimmer_timer, &AcDimmerDataStore::s_timer_intr, true);
199 // For ESP32, we can't use dynamic interval calculation because the timerX functions
200 // are not callable from ISR (placed in flash storage).
201 // Here we just use an interrupt firing every 50 µs.
202 timerAlarmWrite(dimmer_timer, 50, true);
203 timerAlarmEnable(dimmer_timer);
204#endif
205}
207 state = std::acos(1 - (2 * state)) / 3.14159; // RMS power compensation
208 auto new_value = static_cast<uint16_t>(roundf(state * 65535));
209 if (new_value != 0 && this->store_.value == 0)
211 this->store_.value = new_value;
212}
214 ESP_LOGCONFIG(TAG, "AcDimmer:");
215 LOG_PIN(" Output Pin: ", this->gate_pin_);
216 LOG_PIN(" Zero-Cross Pin: ", this->zero_cross_pin_);
217 ESP_LOGCONFIG(TAG, " Min Power: %.1f%%", this->store_.min_power / 10.0f);
218 ESP_LOGCONFIG(TAG, " Init with half cycle: %s", YESNO(this->init_with_half_cycle_));
220 ESP_LOGCONFIG(TAG, " Method: leading pulse");
221 } else if (method_ == DIM_METHOD_LEADING) {
222 ESP_LOGCONFIG(TAG, " Method: leading");
223 } else {
224 ESP_LOGCONFIG(TAG, " Method: trailing");
225 }
226
227 LOG_FLOAT_OUTPUT(this);
228 ESP_LOGV(TAG, " Estimated Frequency: %.3fHz", 1e6f / this->store_.cycle_time_us / 2);
229}
230
231} // namespace ac_dimmer
232} // namespace esphome
233
234#endif // USE_ARDUINO
virtual void setup()=0
void digital_write(bool value)
Definition gpio.cpp:147
virtual uint8_t get_pin() const =0
void attach_interrupt(void(*func)(T *), T *arg, gpio::InterruptType type) const
Definition gpio.h:88
virtual ISRInternalGPIOPin to_isr() const =0
void write_state(float state) override
InternalGPIOPin * gate_pin_
Definition ac_dimmer.h:60
InternalGPIOPin * zero_cross_pin_
Definition ac_dimmer.h:61
AcDimmerDataStore store_
Definition ac_dimmer.h:62
bool state
Definition fan.h:0
uint32_t IRAM_ATTR HOT timer_interrupt()
Run timer interrupt code and return in how many µs the next event is expected.
Definition ac_dimmer.cpp:72
@ INTERRUPT_FALLING_EDGE
Definition gpio.h:42
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
uint32_t IRAM_ATTR HOT micros()
Definition core.cpp:29
uint32_t cycle_time_us
Time between the last two ZC pulses.
Definition ac_dimmer.h:26
bool init_cycle
Set to send the first half ac cycle complete.
Definition ac_dimmer.h:34
uint32_t disable_time_us
Time since last ZC pulse to disable gate pin. 0 means no disable.
Definition ac_dimmer.h:32
uint32_t enable_time_us
Time since last ZC pulse to enable gate pin. 0 means not set.
Definition ac_dimmer.h:30
uint16_t min_power
Minimum power for activation.
Definition ac_dimmer.h:24
uint32_t crossed_zero_at
Time (in micros()) of last ZC signal.
Definition ac_dimmer.h:28
uint8_t zero_cross_pin_number
Zero-cross pin number - used to share ZC pin across multiple dimmers.
Definition ac_dimmer.h:18
uint16_t value
Value of the dimmer - 0 to 65535.
Definition ac_dimmer.h:22
uint32_t timer_intr(uint32_t now)
Function called from timer interrupt Input is current time in microseconds (micros()) Returns when ne...
Definition ac_dimmer.cpp:34
ISRInternalGPIOPin gate_pin
Output pin to write to.
Definition ac_dimmer.h:20
ISRInternalGPIOPin zero_cross_pin
Zero-cross pin.
Definition ac_dimmer.h:16
DimMethod method
Dimmer method.
Definition ac_dimmer.h:36
void gpio_intr()
GPIO interrupt routine, called when ZC pin triggers.
Definition ac_dimmer.cpp:90
static void s_gpio_intr(AcDimmerDataStore *store)