ESPHome  2024.10.2
ac_dimmer.cpp
Go to the documentation of this file.
1 #ifdef USE_ARDUINO
2 
3 #include "ac_dimmer.h"
4 #include "esphome/core/helpers.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 
15 namespace esphome {
16 namespace ac_dimmer {
17 
18 static const char *const TAG = "ac_dimmer";
19 
20 // Global array to store dimmer objects
21 static AcDimmerDataStore *all_dimmers[32]; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
22 
29 static const uint32_t GATE_ENABLE_TIME = 50;
30 
34 uint32_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 
72 uint32_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 
90 void 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  if (this->method == DIM_METHOD_TRAILING) {
118  this->enable_time_us = 1; // cannot be 0
119  this->disable_time_us = std::max((uint32_t) 10, this->value * this->cycle_time_us / 65535);
120  } else {
121  // calculate time until enable in µs: (1.0-value)*cycle_time, but with integer arithmetic
122  // also take into account min_power
123  auto min_us = this->cycle_time_us * this->min_power / 1000;
124  this->enable_time_us = std::max((uint32_t) 1, ((65535 - this->value) * (this->cycle_time_us - min_us)) / 65535);
125 
126  if (this->method == DIM_METHOD_LEADING_PULSE) {
127  // Minimum pulse time should be enough for the triac to trigger when it is close to the ZC zone
128  // this is for brightness near 99%
129  this->disable_time_us = std::max(this->enable_time_us + GATE_ENABLE_TIME, (uint32_t) cycle_time_us / 10);
130  } else {
131  this->gate_pin.digital_write(false);
132  this->disable_time_us = this->cycle_time_us;
133  }
134  }
135  }
136 }
137 
139  // Attaching pin interrupts on the same pin will override the previous interrupt
140  // However, the user expects that multiple dimmers sharing the same ZC pin will work.
141  // We solve this in a bit of a hacky way: On each pin interrupt, we check all dimmers
142  // if any of them are using the same ZC pin, and also trigger the interrupt for *them*.
143  for (auto *dimmer : all_dimmers) {
144  if (dimmer == nullptr)
145  break;
146  if (dimmer->zero_cross_pin_number == store->zero_cross_pin_number) {
147  dimmer->gpio_intr();
148  }
149  }
150 }
151 
152 #ifdef USE_ESP32
153 // ESP32 implementation, uses basically the same code but needs to wrap
154 // timer_interrupt() function to auto-reschedule
155 static hw_timer_t *dimmer_timer = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
157 #endif
158 
160  // extend all_dimmers array with our dimmer
161 
162  // Need to be sure the zero cross pin is setup only once, ESP8266 fails and ESP32 seems to fail silently
163  auto setup_zero_cross_pin = true;
164 
165  for (auto &all_dimmer : all_dimmers) {
166  if (all_dimmer == nullptr) {
167  all_dimmer = &this->store_;
168  break;
169  }
170  if (all_dimmer->zero_cross_pin_number == this->zero_cross_pin_->get_pin()) {
171  setup_zero_cross_pin = false;
172  }
173  }
174 
175  this->gate_pin_->setup();
176  this->store_.gate_pin = this->gate_pin_->to_isr();
177  this->store_.zero_cross_pin_number = this->zero_cross_pin_->get_pin();
178  this->store_.min_power = static_cast<uint16_t>(this->min_power_ * 1000);
179  this->min_power_ = 0;
180  this->store_.method = this->method_;
181 
182  if (setup_zero_cross_pin) {
183  this->zero_cross_pin_->setup();
184  this->store_.zero_cross_pin = this->zero_cross_pin_->to_isr();
185  this->zero_cross_pin_->attach_interrupt(&AcDimmerDataStore::s_gpio_intr, &this->store_,
187  }
188 
189 #ifdef USE_ESP8266
190  // Uses ESP8266 waveform (soft PWM) class
191  // PWM and AcDimmer can even run at the same time this way
192  setTimer1Callback(&timer_interrupt);
193 #endif
194 #ifdef USE_ESP32
195  // 80 Divider -> 1 count=1µs
196  dimmer_timer = timerBegin(0, 80, true);
197  timerAttachInterrupt(dimmer_timer, &AcDimmerDataStore::s_timer_intr, true);
198  // For ESP32, we can't use dynamic interval calculation because the timerX functions
199  // are not callable from ISR (placed in flash storage).
200  // Here we just use an interrupt firing every 50 µs.
201  timerAlarmWrite(dimmer_timer, 50, true);
202  timerAlarmEnable(dimmer_timer);
203 #endif
204 }
206  state = std::acos(1 - (2 * state)) / 3.14159; // RMS power compensation
207  auto new_value = static_cast<uint16_t>(roundf(state * 65535));
208  if (new_value != 0 && this->store_.value == 0)
209  this->store_.init_cycle = this->init_with_half_cycle_;
210  this->store_.value = new_value;
211 }
213  ESP_LOGCONFIG(TAG, "AcDimmer:");
214  LOG_PIN(" Output Pin: ", this->gate_pin_);
215  LOG_PIN(" Zero-Cross Pin: ", this->zero_cross_pin_);
216  ESP_LOGCONFIG(TAG, " Min Power: %.1f%%", this->store_.min_power / 10.0f);
217  ESP_LOGCONFIG(TAG, " Init with half cycle: %s", YESNO(this->init_with_half_cycle_));
218  if (method_ == DIM_METHOD_LEADING_PULSE) {
219  ESP_LOGCONFIG(TAG, " Method: leading pulse");
220  } else if (method_ == DIM_METHOD_LEADING) {
221  ESP_LOGCONFIG(TAG, " Method: leading");
222  } else {
223  ESP_LOGCONFIG(TAG, " Method: trailing");
224  }
225 
226  LOG_FLOAT_OUTPUT(this);
227  ESP_LOGV(TAG, " Estimated Frequency: %.3fHz", 1e6f / this->store_.cycle_time_us / 2);
228 }
229 
230 } // namespace ac_dimmer
231 } // namespace esphome
232 
233 #endif // USE_ARDUINO
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
uint32_t enable_time_us
Time since last ZC pulse to enable gate pin. 0 means not set.
Definition: ac_dimmer.h:30
uint32_t cycle_time_us
Time between the last two ZC pulses.
Definition: ac_dimmer.h:26
uint32_t crossed_zero_at
Time (in micros()) of last ZC signal.
Definition: ac_dimmer.h:28
uint32_t IRAM_ATTR HOT micros()
Definition: core.cpp:27
uint16_t min_power
Minimum power for activation.
Definition: ac_dimmer.h:24
DimMethod method
Dimmer method.
Definition: ac_dimmer.h:36
bool init_cycle
Set to send the first half ac cycle complete.
Definition: ac_dimmer.h:34
void write_state(float state) override
Definition: ac_dimmer.cpp:205
static void s_gpio_intr(AcDimmerDataStore *store)
Definition: ac_dimmer.cpp:138
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
uint16_t value
Value of the dimmer - 0 to 65535.
Definition: ac_dimmer.h:22
ISRInternalGPIOPin gate_pin
Output pin to write to.
Definition: ac_dimmer.h:20
void dump_config() override
Definition: ac_dimmer.cpp:212
Implementation of SPI Controller mode.
Definition: a01nyub.cpp:7
uint32_t disable_time_us
Time since last ZC pulse to disable gate pin. 0 means no disable.
Definition: ac_dimmer.h:32
void digital_write(bool value)
Definition: gpio.cpp:121
void gpio_intr()
GPIO interrupt routine, called when ZC pin triggers.
Definition: ac_dimmer.cpp:90
bool state
Definition: fan.h:34
uint8_t zero_cross_pin_number
Zero-cross pin number - used to share ZC pin across multiple dimmers.
Definition: ac_dimmer.h:18