Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <ESP8266WiFi.h>
- #include <PubSubClient.h>
- const char* ssid = "xxx";
- const char* password = "xxxxxxx";
- const char* mqttServer = "192.168.1.xx";
- const int mqttPort = 1883;
- #define LED 5 // D1(gpio5)
- #define BUTTON 4 //D2(gpio4)
- //Let's say you have your push button on pin 4
- int switchState = 0; // actual read value from pin4
- int oldSwitchState = 0; // last read value from pin4
- int lightsOn = 0; // is the switch on = 1 or off = 0
- WiFiClient espClient;
- PubSubClient client(espClient);
- void setup() {
- Serial.begin(115200);
- WiFi.begin(ssid, password);
- while (WiFi.status() != WL_CONNECTED) {
- delay(500);
- Serial.println("Connecting to WiFi..");
- Serial.print("Connected to ");
- Serial.print(ssid);
- Serial.println();
- }
- client.setServer(mqttServer, mqttPort);
- // client.setCallback(callback);
- while (!client.connected()) {
- Serial.println("Connecting to MQTT...");
- if (client.connect("ESP8266Client" )) {
- Serial.print("connected");
- } else {
- Serial.print("failed with state ");
- Serial.print(client.state());
- delay(2000);
- }
- }
- client.publish("home/office/sonoff1", "Remote");
- client.subscribe("home/office/sonoff1");
- pinMode(BUTTON, INPUT); // push button
- pinMode(LED, OUTPUT); // anything you want to control using a switch e.g. a Led
- }
- void loop ()
- {
- switchState = digitalRead(BUTTON); // read the pushButton State
- if (switchState != oldSwitchState) // catch change
- {
- oldSwitchState = switchState;
- if (switchState == HIGH)
- {
- // toggle
- lightsOn = !lightsOn;
- }
- if(lightsOn)
- {
- digitalWrite(LED, HIGH); // set the LED on
- client.publish("home/office/sonoff1", "on");
- }
- else
- {
- digitalWrite(LED, LOW); // set the LED off
- client.publish("home/office/sonoff1", "off");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement