Skip to content

Commit 59c1f49

Browse files
authored
Create lightswitch.ino
1 parent 6f48f1c commit 59c1f49

File tree

1 file changed

+223
-0
lines changed

1 file changed

+223
-0
lines changed

RentersLightSwitch/lightswitch.ino

Lines changed: 223 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,223 @@
1+
/* Works with NODEMCU, SG90 servo, and micro PIR sensor */
2+
3+
#include <ESP8266WiFi.h>
4+
#include <PubSubClient.h>
5+
#include <Servo.h>
6+
#include <ArduinoOTA.h>
7+
#include <ArduinoJson.h>
8+
9+
// Update these with values suitable for your network.
10+
const char* ssid = "WIFINETWORK";
11+
const char* password = "WIFIPASSWORD";
12+
const char* mqtt_server = "MQTTSERVER.local";
13+
const char* mqtt_username = "MQTT_USERNAME";
14+
const char* mqtt_password = "MQTT_PASSWORD";
15+
const int mqtt_port = 1883;
16+
const int BUFFER_SIZE = 300;
17+
bool stateOn = false;
18+
int pirValue;
19+
int pirStatus;
20+
int stateStatus;
21+
String switchStatus;
22+
String motionStatus;
23+
char message_buff[100];
24+
25+
26+
#define PIN_SERVO D1
27+
#define PIN_PIR D5
28+
29+
const char* on_cmd = "ON";
30+
const char* off_cmd = "OFF";
31+
32+
/**************************** FOR OTA **************************************************/
33+
#define SENSORNAME "lightswitch" //change this to whatever you want to call your device
34+
#define OTApassword "OTA_PASSWORD" //the password you will need to enter to upload remotely via the ArduinoIDE
35+
int OTAport = 8266;
36+
37+
/************* MQTT TOPICS (change these topics as you wish) **************************/
38+
const char* switch_state_topic = "lightswitch/current";
39+
const char* switch_set_topic = "lightswitch/set";
40+
41+
Servo myservo; // create servo object to control a servo
42+
WiFiClient espClient;
43+
PubSubClient client(espClient);
44+
45+
void setup_wifi() {
46+
delay(100);
47+
// We start by connecting to a WiFi network
48+
Serial.print("Connecting to ");
49+
Serial.println(ssid);
50+
WiFi.begin(ssid, password);
51+
while (WiFi.status() != WL_CONNECTED)
52+
{
53+
delay(500);
54+
Serial.print(".");
55+
}
56+
randomSeed(micros());
57+
Serial.println("");
58+
Serial.println("WiFi connected");
59+
Serial.println("IP address: ");
60+
Serial.println(WiFi.localIP());
61+
}
62+
63+
void callback(char* topic, byte* payload, unsigned int length)
64+
{
65+
Serial.print("Command from MQTT broker : [");
66+
Serial.print(topic);
67+
Serial.print(" Message is:");
68+
for(int i=0;i<length;i++)
69+
{
70+
if((int)payload[i]>194||(int)payload[i]<0)
71+
break;
72+
myservo.write((int)payload[i]);
73+
delay(1000);
74+
myservo.write(65);// tell servo to go to neutral
75+
Serial.print((int)payload[i]);//print the rotation angle for debug
76+
Serial.print("]");
77+
Serial.println();
78+
79+
if (payload[0] == 51 && stateStatus != 1) {
80+
switchStatus = "OFF";
81+
sendState();
82+
stateStatus = 1;
83+
}
84+
85+
if (payload[0] == 80 && stateStatus != 2) {
86+
switchStatus = "ON";
87+
sendState();
88+
stateStatus = 2;
89+
}
90+
}
91+
}//end callback
92+
93+
void reconnect() {
94+
// Loop until we're reconnected
95+
while (!client.connected())
96+
{
97+
Serial.print("Attempting MQTT connection...");
98+
// Create a random client ID
99+
String clientId = "lightswitch-";
100+
clientId += String(random(0xffff), HEX);
101+
// Attempt to connect
102+
//if you MQTT broker has clientID,username and password
103+
//please change following line to if (client.connect(clientId,userName,passWord))
104+
if (client.connect(SENSORNAME, mqtt_username, mqtt_password))
105+
{
106+
Serial.println("connected");
107+
//once connected to MQTT broker, subscribe command if any
108+
client.subscribe(switch_set_topic);
109+
} else {
110+
Serial.print("failed, rc=");
111+
Serial.print(client.state());
112+
Serial.println(" try again in 5 seconds");
113+
// Wait 6 seconds before retrying
114+
delay(6000);
115+
}
116+
}
117+
} //end reconnect()
118+
119+
/* JSON */
120+
bool processJson(char* message) {
121+
StaticJsonBuffer<BUFFER_SIZE> jsonBuffer;
122+
123+
JsonObject& root = jsonBuffer.parseObject(message);
124+
125+
if (!root.success()) {
126+
Serial.println("parseObject() failed");
127+
return false;
128+
}
129+
130+
if (root.containsKey("state")) {
131+
if (strcmp(root["state"], on_cmd) == 0) {
132+
stateOn = true;
133+
}
134+
else if (strcmp(root["state"], off_cmd) == 0) {
135+
stateOn = false;
136+
}
137+
}
138+
}
139+
140+
/* SEND STATE */
141+
void sendState() {
142+
StaticJsonBuffer<BUFFER_SIZE> jsonBuffer;
143+
144+
JsonObject& root = jsonBuffer.createObject();
145+
146+
root["state"] = (String)switchStatus;
147+
root["motion"] = (String)motionStatus;
148+
149+
char buffer[root.measureLength() + 1];
150+
root.printTo(buffer, sizeof(buffer));
151+
152+
Serial.println(buffer);
153+
client.publish(switch_state_topic, buffer, true);
154+
}
155+
156+
/* CHECK SENSOR */
157+
bool checkBoundSensor(float newValue, float prevValue, float maxDiff) {
158+
return newValue < prevValue - maxDiff || newValue > prevValue + maxDiff;
159+
}
160+
161+
void setup() {
162+
Serial.begin(115200);
163+
pinMode(PIN_PIR, INPUT);
164+
setup_wifi();
165+
client.setServer(mqtt_server, mqtt_port);
166+
client.setCallback(callback);
167+
myservo.attach(PIN_SERVO); // attaches the servo on pin D1 to the servo object
168+
169+
/* OTA SETUP */
170+
ArduinoOTA.setPort(OTAport);
171+
// Hostname defaults to esp8266-[ChipID]
172+
ArduinoOTA.setHostname(SENSORNAME);
173+
174+
// No authentication by default
175+
ArduinoOTA.setPassword((const char *)OTApassword);
176+
177+
ArduinoOTA.onStart([]() {
178+
Serial.println("Starting");
179+
});
180+
ArduinoOTA.onEnd([]() {
181+
Serial.println("\nEnd");
182+
});
183+
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
184+
Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
185+
});
186+
ArduinoOTA.onError([](ota_error_t error) {
187+
Serial.printf("Error[%u]: ", error);
188+
if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
189+
else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
190+
else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
191+
else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
192+
else if (error == OTA_END_ERROR) Serial.println("End Failed");
193+
});
194+
ArduinoOTA.begin();
195+
196+
/* WIFI SETUP */
197+
Serial.println("Ready");
198+
Serial.print("IP Address: ");
199+
Serial.println(WiFi.localIP());
200+
}
201+
202+
void loop() {
203+
if (!client.connected()) {
204+
reconnect();
205+
}
206+
client.loop();
207+
ArduinoOTA.handle();
208+
//PIR CODE
209+
pirValue = digitalRead(PIN_PIR); //read state of the
210+
211+
/* PIR STATUS */
212+
if (pirValue == LOW && pirStatus != 1) {
213+
motionStatus = "standby";
214+
sendState();
215+
pirStatus = 1;
216+
}
217+
218+
else if (pirValue == HIGH && pirStatus != 2) {
219+
motionStatus = "motion detected";
220+
sendState();
221+
pirStatus = 2;
222+
}
223+
}

0 commit comments

Comments
 (0)