Skip to content

Instantly share code, notes, and snippets.

@dranger003
Created June 29, 2017 23:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dranger003/44cf49b899acfefd9f868914c1e852ed to your computer and use it in GitHub Desktop.
Save dranger003/44cf49b899acfefd9f868914c1e852ed to your computer and use it in GitHub Desktop.
ESP8266 (WEMOS D1) Zero Cross Triac using Timer0 (higher resolution/quality than Timer1)
#define TIMR_OVRHD 7000
uint8_t _z = 0;
uint32_t _v = 20000;
void ICACHE_RAM_ATTR _ISR0() {
if (_z == 1) {
_z = 2;
timer0_write(ESP.getCycleCount() + 8000); // 8000 = 100us, 80000 = 1ms
digitalWrite(D2, HIGH);
}
else if (_z == 2) {
digitalWrite(D2, LOW);
timer0_detachInterrupt(); // Must detach interrupt handler before next time it is attached to avoid ESP crash
_z = 0;
}
}
void ICACHE_RAM_ATTR _ZC() {
_z = 1;
timer0_attachInterrupt(_ISR0); // Attaching interrupt handler here avoids ESP crash
timer0_write(ESP.getCycleCount() + TIMR_OVRHD + _v);
}
void setup() {
Serial.begin(74880);
timer0_isr_init(); // Attaching the interrupt handler here causes the ESP to crash
pinMode(D2, OUTPUT);
digitalWrite(D2, LOW);
pinMode(D3, INPUT_PULLUP);
attachInterrupt(D3, _ZC, RISING);
Serial.printf("\n\n");
}
uint32_t _t = millis();
uint8_t _d = 1;
void loop() {
uint32_t t = millis();
if (t - _t > 100) {
_v += _d ? 20000 : -20000;
if (_v == 20000 || _v == 640000) _d = !_d;
_t = t;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment