Created
March 26, 2020 03:41
-
-
Save aamharris/3f07cd2d32b4c81804b1b7e6c5b1987c to your computer and use it in GitHub Desktop.
ESP32 IoT Light Controller with CloudMqtt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <WiFi.h> | |
#include <PubSubClient.h> | |
//replace details with your wifi credentials | |
const char* ssid = "your-ssid"; | |
const char* password = "your-password"; | |
const int buttonPin = 17; | |
const int ledPin = 21; | |
int buttonState = 0; | |
int lastButtonState = 0; | |
bool isLightOn = false; | |
WiFiClient wifiClient; | |
PubSubClient mqttClient(wifiClient); | |
void setup() { | |
Serial.begin(9600); | |
pinMode(buttonPin, INPUT); | |
pinMode(ledPin, OUTPUT); | |
WiFi.begin(ssid, password); | |
while (WiFi.status() != WL_CONNECTED) { | |
delay(500); | |
Serial.print("."); | |
} | |
//replace details with mqtt server and port | |
mqttClient.setServer("your-mqtt-server", port-here); | |
//replace with a client id, username, password | |
if (mqttClient.connect("myClientID", "your-mqtt-username", "your-mqtt-password" )) | |
{ | |
Serial.println("Connection has been established"); | |
mqttClient.subscribe("light"); | |
mqttClient.setCallback(subscribeReceive); | |
} | |
else | |
{ | |
Serial.println("Looks like the server connection failed..."); | |
} | |
} | |
void loop() { | |
mqttClient.loop(); | |
buttonState = digitalRead(buttonPin); | |
if (buttonState != lastButtonState) { | |
if (buttonState == HIGH) { | |
if (isLightOn) { | |
turnLightOff(); | |
} else { | |
turnLightOn(); | |
} | |
} | |
// Delay a little bit to avoid bouncing | |
delay(50); | |
} | |
lastButtonState = buttonState; | |
} | |
void subscribeReceive(char* topic, byte* payload, unsigned int length) | |
{ | |
Serial.println(topic); | |
if (strcmp(topic, "light") == 0) { | |
if (!strncmp((char *)payload, "on", length)) { | |
turnLightOn(); | |
} else { | |
turnLightOff(); | |
} | |
} | |
} | |
void turnLightOn() { | |
digitalWrite(ledPin, HIGH); | |
isLightOn = true; | |
mqttClient.publish("light/state", "on"); | |
} | |
void turnLightOff() { | |
digitalWrite(ledPin, LOW); | |
isLightOn = false; | |
mqttClient.publish("light/state", "off"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment