Skip to content

Instantly share code, notes, and snippets.

@tdmrhn
Last active April 29, 2016 07:00
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 tdmrhn/fcb4f1d8d8d67f76ddac2e1106d9f904 to your computer and use it in GitHub Desktop.
Save tdmrhn/fcb4f1d8d8d67f76ddac2e1106d9f904 to your computer and use it in GitHub Desktop.
mqtt, esp8266, pin control
#include <PubSubClient.h>
#include <ESP8266WiFi.h>
#define MQTT_SERVER "192.168.1.2" // change the mqttbroker address
const char* ssid = "xxxxx"; // your wi-fi name
const char* password = "xxxxx"; // your wi-fi password
const int pin = 0; // in basic esp-01 you can control pin-0 and pin-2
char* clientname = "newesp"; // the mqtt client adress must be unique more than one esp usage
char* sublight = "/test/light"; // the mqtt sub adress
char* publight = "/test/light/confirm"; // the mqtt pub adress
WiFiClient wifiClient;
PubSubClient client(MQTT_SERVER, 1883, callback, wifiClient);
void setup() {
pinMode(pin, OUTPUT);
Serial.begin(115200);
delay(100);
WiFi.begin(ssid, password);
if(WiFi.status() != WL_CONNECTED){
while (WiFi.status() != WL_CONNECTED) {
delay(500);
}
}
}
void loop(){
if (!client.connected()) {
while (!client.connected()) {
if (client.connect(clientname)) {
client.subscribe(sublight); // take commands
}
else{delay(500)}
}
}
client.loop();
delay(10);
}
//MQTT callback
void callback(char* topic, byte* payload, unsigned int length) {
if(payload[0] == '1'){
digitalWrite(pin, HIGH);
client.publish(publight, "1"); // publish the new status
}
else{
digitalWrite(pin, LOW);
client.publish(publight, "0"); // publish the new status
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment