ESPHome 2025.9.0-dev
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#include <numbers>
8
9#ifdef USE_ESP8266
10#include <core_esp8266_waveform.h>
11#endif
12#ifdef USE_ESP32_FRAMEWORK_ARDUINO
13#include <esp32-hal-timer.h>
14#endif
15
16namespace esphome {
17namespace ac_dimmer {
18
19static const char *const TAG = "ac_dimmer";
20
21// Global array to store dimmer objects
22static AcDimmerDataStore *all_dimmers[32]; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
23
30static const uint32_t GATE_ENABLE_TIME = 50;
31
35uint32_t IRAM_ATTR HOT AcDimmerDataStore::timer_intr(uint32_t now) {
36 // If no ZC signal received yet.
37 if (this->crossed_zero_at == 0)
38 return 0;
39
40 uint32_t time_since_zc = now - this->crossed_zero_at;
41 if (this->value == 65535 || this->value == 0) {
42 return 0;
43 }
44
45 if (this->enable_time_us != 0 && time_since_zc >= this->enable_time_us) {
46 this->enable_time_us = 0;
47 this->gate_pin.digital_write(true);
48 // Prevent too short pulses
49 this->disable_time_us = std::max(this->disable_time_us, time_since_zc + GATE_ENABLE_TIME);
50 }
51 if (this->disable_time_us != 0 && time_since_zc >= this->disable_time_us) {
52 this->disable_time_us = 0;
53 this->gate_pin.digital_write(false);
54 }
55
56 if (time_since_zc < this->enable_time_us) {
57 // Next event is enable, return time until that event
58 return this->enable_time_us - time_since_zc;
59 } else if (time_since_zc < disable_time_us) {
60 // Next event is disable, return time until that event
61 return this->disable_time_us - time_since_zc;
62 }
63
64 if (time_since_zc >= this->cycle_time_us) {
65 // Already past last cycle time, schedule next call shortly
66 return 100;
67 }
68
69 return this->cycle_time_us - time_since_zc;
70}
71
73uint32_t IRAM_ATTR HOT timer_interrupt() {
74 // run at least with 1kHz
75 uint32_t min_dt_us = 1000;
76 uint32_t now = micros();
77 for (auto *dimmer : all_dimmers) {
78 if (dimmer == nullptr) {
79 // no more dimmers
80 break;
81 }
82 uint32_t res = dimmer->timer_intr(now);
83 if (res != 0 && res < min_dt_us)
84 min_dt_us = res;
85 }
86 // return time until next timer1 interrupt in µs
87 return min_dt_us;
88}
89
91void IRAM_ATTR HOT AcDimmerDataStore::gpio_intr() {
92 uint32_t prev_crossed = this->crossed_zero_at;
93
94 // 50Hz mains frequency should give a half cycle of 10ms a 60Hz will give 8.33ms
95 // in any case the cycle last at least 5ms
96 this->crossed_zero_at = micros();
97 uint32_t cycle_time = this->crossed_zero_at - prev_crossed;
98 if (cycle_time > 5000) {
99 this->cycle_time_us = cycle_time;
100 } else {
101 // Otherwise this is noise and this is 2nd (or 3rd...) fall in the same pulse
102 // Consider this is the right fall edge and accumulate the cycle time instead
103 this->cycle_time_us += cycle_time;
104 }
105
106 if (this->value == 65535) {
107 // fully on, enable output immediately
108 this->gate_pin.digital_write(true);
109 } else if (this->init_cycle) {
110 // send a full cycle
111 this->init_cycle = false;
112 this->enable_time_us = 0;
114 } else if (this->value == 0) {
115 // fully off, disable output immediately
116 this->gate_pin.digital_write(false);
117 } else {
118 auto min_us = this->cycle_time_us * this->min_power / 1000;
119 if (this->method == DIM_METHOD_TRAILING) {
120 this->enable_time_us = 1; // cannot be 0
121 // calculate time until disable in µs with integer arithmetic and take into account min_power
122 this->disable_time_us = std::max((uint32_t) 10, this->value * (this->cycle_time_us - min_us) / 65535 + min_us);
123 } else {
124 // calculate time until enable in µs: (1.0-value)*cycle_time, but with integer arithmetic
125 // also take into account min_power
126 this->enable_time_us = std::max((uint32_t) 1, ((65535 - this->value) * (this->cycle_time_us - min_us)) / 65535);
127
128 if (this->method == DIM_METHOD_LEADING_PULSE) {
129 // Minimum pulse time should be enough for the triac to trigger when it is close to the ZC zone
130 // this is for brightness near 99%
131 this->disable_time_us = std::max(this->enable_time_us + GATE_ENABLE_TIME, (uint32_t) cycle_time_us / 10);
132 } else {
133 this->gate_pin.digital_write(false);
134 this->disable_time_us = this->cycle_time_us;
135 }
136 }
137 }
138}
139
141 // Attaching pin interrupts on the same pin will override the previous interrupt
142 // However, the user expects that multiple dimmers sharing the same ZC pin will work.
143 // We solve this in a bit of a hacky way: On each pin interrupt, we check all dimmers
144 // if any of them are using the same ZC pin, and also trigger the interrupt for *them*.
145 for (auto *dimmer : all_dimmers) {
146 if (dimmer == nullptr)
147 break;
148 if (dimmer->zero_cross_pin_number == store->zero_cross_pin_number) {
149 dimmer->gpio_intr();
150 }
151 }
152}
153
154#ifdef USE_ESP32
155// ESP32 implementation, uses basically the same code but needs to wrap
156// timer_interrupt() function to auto-reschedule
157static hw_timer_t *dimmer_timer = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
159#endif
160
162 // extend all_dimmers array with our dimmer
163
164 // Need to be sure the zero cross pin is setup only once, ESP8266 fails and ESP32 seems to fail silently
165 auto setup_zero_cross_pin = true;
166
167 for (auto &all_dimmer : all_dimmers) {
168 if (all_dimmer == nullptr) {
169 all_dimmer = &this->store_;
170 break;
171 }
172 if (all_dimmer->zero_cross_pin_number == this->zero_cross_pin_->get_pin()) {
173 setup_zero_cross_pin = false;
174 }
175 }
176
177 this->gate_pin_->setup();
178 this->store_.gate_pin = this->gate_pin_->to_isr();
180 this->store_.min_power = static_cast<uint16_t>(this->min_power_ * 1000);
181 this->min_power_ = 0;
182 this->store_.method = this->method_;
183
184 if (setup_zero_cross_pin) {
185 this->zero_cross_pin_->setup();
189 }
190
191#ifdef USE_ESP8266
192 // Uses ESP8266 waveform (soft PWM) class
193 // PWM and AcDimmer can even run at the same time this way
194 setTimer1Callback(&timer_interrupt);
195#endif
196#ifdef USE_ESP32
197 // timer frequency of 1mhz
198 dimmer_timer = timerBegin(1000000);
199 timerAttachInterrupt(dimmer_timer, &AcDimmerDataStore::s_timer_intr);
200 // For ESP32, we can't use dynamic interval calculation because the timerX functions
201 // are not callable from ISR (placed in flash storage).
202 // Here we just use an interrupt firing every 50 µs.
203 timerAlarm(dimmer_timer, 50, true, 0);
204#endif
205}
207 state = std::acos(1 - (2 * state)) / std::numbers::pi; // 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,
218 " Min Power: %.1f%%\n"
219 " Init with half cycle: %s",
220 this->store_.min_power / 10.0f, YESNO(this->init_with_half_cycle_));
222 ESP_LOGCONFIG(TAG, " Method: leading pulse");
223 } else if (method_ == DIM_METHOD_LEADING) {
224 ESP_LOGCONFIG(TAG, " Method: leading");
225 } else {
226 ESP_LOGCONFIG(TAG, " Method: trailing");
227 }
228
229 LOG_FLOAT_OUTPUT(this);
230 ESP_LOGV(TAG, " Estimated Frequency: %.3fHz", 1e6f / this->store_.cycle_time_us / 2);
231}
232
233} // namespace ac_dimmer
234} // namespace esphome
235
236#endif // USE_ARDUINO
virtual void setup()=0
void digital_write(bool value)
Definition gpio.cpp:146
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:73
@ 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:30
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:35
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:91
static void s_gpio_intr(AcDimmerDataStore *store)