Skip to content

Instantly share code, notes, and snippets.

@aamharris
Created March 26, 2020 03:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aamharris/3f07cd2d32b4c81804b1b7e6c5b1987c to your computer and use it in GitHub Desktop.
Save aamharris/3f07cd2d32b4c81804b1b7e6c5b1987c to your computer and use it in GitHub Desktop.
ESP32 IoT Light Controller with CloudMqtt
#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