CODE UPDATE:
- Fixed missing Blynk widget sync
- All device settings now in one location, including single variable to select between ON/OFF and PWM operation.
/* Wemo / Hue emulation for ESP8266 control with Alexa, Blynk and IFTTT.
*
* https://github.com/tzapu/WiFiManager
* https://github.com/Aircoookie/Espalexa
* https://www.blynk.cc/
*
* Can be configured for either ON/OFF control or analog (PWM). If using a Blynk slider,
* assign a range of 0-255 to the widget.
*
* For IFTTT control, use the Maker Channel with the following settings:
* URL: http://blynk-cloud.com:8080/YOUR_TOKEN/V1 Substitute your own token and vitual pin
* Method: PUT
* Content type: application/json
* Body: {"1"] Use 0 for OFF, 1 for ON. For custom levels use 0-255.
*/
#include <ESP8266WiFi.h>
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h>
#include <Espalexa.h>
#include <ArduinoOTA.h>
#include <BlynkSimpleEsp8266.h>
// Device customizations //////////////////////////////////////////////////////////////////////////////////////////
#define VPIN V1 //Use a unique virtual pin for each device sharing the same Blynk token / dashboard
char auth[] = "YOUR_TOKEN" ; //Get a token from Blynk
char DeviceName[] = "Switch One"; // How you want the switch to be named in the Alexa app
boolean UsingPWM = false; // "False" if using a relay and Blynk button. "True" if using PWM and Blynk slider.
const int OutputPin = D1; // Output pin to a relay or PWM device. The onboard relay on a Sonoff is pin 12.
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Espalexa espalexa;
void setup(){
Serial.begin(115200);
WiFiManager wifi;
wifi.autoConnect("EspalexaSwitch"); // Connect to this access point the first time you use the device
// Initialize the new device
espalexa.addDevice(DeviceName, UpdateSwitch1); //Parameters: (device name, callback function)
espalexa.begin();
pinMode(OutputPin, OUTPUT); // This can be used for either a relay or PWM output
digitalWrite(OutputPin, LOW);
Blynk.config(auth);
ArduinoOTA.begin();
}
void loop()
{
espalexa.loop();
Blynk.run();
ArduinoOTA.handle();
}
//------------ Callback functions. Level can be set from 0-255. -------------
void UpdateSwitch1(uint8_t level) { // Espalexa callback
SetNewLevel(&level);
}
// Handle blynk widget. Can be a switch or a slider
BLYNK_WRITE(VPIN){
uint8_t level = param.asInt();
SetNewLevel(&level);
}
void SetNewLevel(uint8_t * pLevel){
Serial.print("New level= ");
Serial.println(*pLevel);
// If the new level is not 0, turn on the relay or set the output pin's PWM
if (*pLevel) {
if(UsingPWM){
// Incoming level (0-255) multiplied by 4 to align with the ESP's PWM levels (0-1023)
analogWrite(OutputPin, *pLevel * 4);
Blynk.virtualWrite(VPIN, *pLevel);
}
else{
digitalWrite(OutputPin, HIGH);
Blynk.virtualWrite(VPIN, HIGH);
}
}
// Turn off the output pin if the new level is 0
else {
digitalWrite(OutputPin, LOW);
Blynk.virtualWrite(VPIN, LOW);
}
}