Source code :
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
/*
Browse to IP of ESP. Use GET variables to configure settings:
b = brightness (0-200)
ex1: View current settings (json): http://ip.of.esp/
ex2: Set brightness to 50% : http://ip.of.esp/?b=100
*/
const char* ssid = "YOUR SSID";
const char* password = "YOUR PASSWORD";
const byte zcPin = 2;
const byte outPin = 13;
int curBrightness = 0;
int dimDelay;
ESP8266WebServer server(80);
void setup(void)
{
pinMode(zcPin, INPUT);
pinMode(outPin, OUTPUT);
digitalWrite(outPin, 0);
Serial.begin(115200);
Serial.println("");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.print("\nConnected: ");
Serial.println(WiFi.localIP());
server.on("/", []()
{
if (server.arg("b") != "")
{
curBrightness = (byte) server.arg("b").toInt();
if (curBrightness > 200) curBrightness = 200; //more and the light will flick...
dimDelay = (200-curBrightness)*40; //50Hz = 20000µs per period.... 10000 µs per half period
}
String s = "{\n \"b\":";
s += curBrightness;
s += "\n}";
server.send(200, "text/plain", s);
});
server.begin();
Serial.println("HTTP server started");
attachInterrupt(zcPin, zcDetect, FALLING); //falling edge has the more delay, so easier to synchronize than rising edge...
}
void loop(void)
{
server.handleClient(); //Do Wifi stuff
}
void zcDetect() // Interupt routine to handle zero crossing
{
if (curBrightness == 0)
{
digitalWrite(outPin, 0); //fully shut down the triac
}
else if (curBrightness == 200)
{
digitalWrite(outPin, 1); //fully open the triac
}
else
{
delayMicroseconds(dimDelay); //wait "delay" for first half period
digitalWrite(outPin, 1); //generate the pulse for the MOC input
delayMicroseconds(100);
digitalWrite(outPin, 0);
delayMicroseconds(9900); //jumpt to the second hald period
digitalWrite(outPin, 1); //generate the pulse for the MOC input
delayMicroseconds(100);
digitalWrite(outPin, 0);
}
}
Quite simple by the way !
JP