-
Notifications
You must be signed in to change notification settings - Fork 0
/
Custom_Sonoff.ino
127 lines (100 loc) · 2.25 KB
/
Custom_Sonoff.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#include <ESP8266WiFi.h>
#include <Espalexa.h>
// define the GPIO connected with Relays
#define RelayPin1 13 //D1
#define RelayPin2 12 //D2
//direct callback functions
void device1Changed(uint8_t brightness);
void device2Changed(uint8_t brightness);
// device names
String Device_1_Name = "SmartSwitch";
String Device_2_Name = "Green light";
Espalexa espalexa;
// prototypes
boolean connectWifi();
// WiFi Credentials
const char* ssid = "MY_SSID";
const char* password = "MY_SSID_Password";
boolean wifiConnected = false;
void setup()
{
Serial.begin(115200);
pinMode(RelayPin1, OUTPUT);
pinMode(RelayPin2, OUTPUT);
// Initialise wifi connection
wifiConnected = connectWifi();
if (wifiConnected)
{
// Define your devices here.
espalexa.addDevice(Device_1_Name, device1Changed);
espalexa.begin();
}
else
{
while (1)
{
Serial.println("Cannot connect to WiFi. Please check data and reset the ESP.");
delay(2500);
}
}
}
void loop()
{
espalexa.loop();
delay(1);
}
//our callback functions
void device1Changed(uint8_t brightness){
//Control the device
if (brightness == 255)
{
digitalWrite(RelayPin1, HIGH);
digitalWrite(RelayPin2, HIGH);
Serial.println("Device1 ON");
}
else if (brightness == 0)
{
digitalWrite(RelayPin1, LOW);
digitalWrite(RelayPin2, LOW);
Serial.println("Device1 OFF");
}
else
{
int brigh_perc = (brightness/255.)*100;
analogWrite(RelayPin1, brightness);
Serial.print("Device1 Brightness: ");
Serial.print(brigh_perc);
Serial.println("%");
}
}
// connect to wifi returns true if successful or false if not
boolean connectWifi()
{
boolean state = true;
int i = 0;
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.println("");
Serial.println("Connecting to WiFi");
// Wait for connection
Serial.print("Connecting...");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
if (i > 20) {
state = false; break;
}
i++;
}
Serial.println("");
if (state) {
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
else {
Serial.println("Connection failed.");
}
return state;
}