Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Code for remote device to control one sonoff basic switch at a time.
- The correct name must be entered in the publish and subscribe statements.
- The commented pin numbers were used for a ESP8266-01 board
- The current board is a Wemos D1 mini pro
- This code is largely the work of individuals on the Arduino forum.
- Without their help, it would not exist.
- Kentm
- */
- #include <ESP8266WiFi.h>
- #include <PubSubClient.h>
- const char* ssid = ".....";
- const char* password = ".......";
- const char* mqttServer = "192.168.1....";
- const int mqttPort = 1883;
- #define mqtt_publish "home/office/sonoff1"
- #define mqtt_subscribe "home/office/sonoff1"
- #define mqtt_sub1 "on"
- #define mqtt_sub2 "off"
- #define LED 5 // D1(gpio5)
- #define BUTTON 4 //D2(gpio4)
- bool lightsOn = false;
- WiFiClient espClient;
- PubSubClient client(espClient);
- void setup() {
- Serial.begin(115200);
- pinMode(BUTTON, INPUT_PULLUP); // push button
- pinMode(LED, OUTPUT); // anything you want to control using a switch e.g. a Led
- delay(500);
- Serial.print("Connecting to WiFi...");
- WiFi.begin(ssid, password);
- while (WiFi.status() != WL_CONNECTED)
- {
- delay(500);
- }
- Serial.print("Connected to ");
- Serial.println(ssid);
- client.setServer(mqttServer, mqttPort);
- client.setCallback(callback);
- Serial.print("Connecting to MQTT...");
- while (!client.connected())
- {
- if (client.connect("ESP8266Client" ))
- {
- Serial.println("connected");
- }
- else
- {
- Serial.print("failed with state ");
- Serial.println(client.state());
- delay(2000);
- }
- }
- client.subscribe(mqtt_subscribe);
- client.publish(mqtt_publish, "Remote");
- }
- void loop ()
- {
- client.loop(); // MQTT houskeeping
- if(digitalRead(BUTTON) == LOW) // Button pressed (LOW)
- {
- lightsOn = !lightsOn; // Toggle light state
- if(lightsOn)
- {
- client.publish(mqtt_publish, mqtt_sub1);
- }
- else
- {
- client.publish(mqtt_publish, mqtt_sub2);
- }
- delay(50); // Switch debounce
- while(digitalRead(BUTTON) == LOW) // Wait for button to be released
- {
- delay(10); // Short delay to yield else WDT reset will happen
- }
- }
- delay(100);
- }
- void callback(char* topic, byte * data, unsigned int length)// Callback for subscribed MQTT topics
- {
- Serial.print(topic);
- Serial.print(": ");
- for (int i = 0; i < length; i++)
- {
- Serial.print((char)data[i]);
- }
- Serial.println();
- if (strncmp(topic, mqtt_subscribe, strlen(mqtt_subscribe)) == 0) // Check it's the right topic
- {
- if (strncmp((char*)data, mqtt_sub1, strlen(mqtt_sub1)) == 0) // Check it's the right data
- {
- lightsOn = true;
- }
- if (strncmp((char*)data, mqtt_sub2, strlen(mqtt_sub2)) == 0) // Check it's the right data
- {
- lightsOn = false;
- }
- }
- digitalWrite(LED, lightsOn);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement