Skip to content

Instantly share code, notes, and snippets.

@brent20
Created May 13, 2017 18:22
Show Gist options
  • Save brent20/2e0785ec52ef94c3b59ec40b59f2cfbb to your computer and use it in GitHub Desktop.
Save brent20/2e0785ec52ef94c3b59ec40b59f2cfbb to your computer and use it in GitHub Desktop.
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
//WIFI
const char* wifi_ssid = "wifi";
const char* wifi_password = "wifi-password";
//MQTT
const char* mqtt_server = "mqtt server ip";
const char* mqtt_user = "mqtt username";
const char* mqtt_password = "mqtt password";
const char* clientID = "Doorbell";
//VARS
const char* doorbell_topic = "home/outdoors/doorbell";
const int doorbellPin = D3;
int doorbellState = 0;
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
Serial.begin(115200);
pinMode(doorbellPin, INPUT_PULLUP);
pinMode(LED_BUILTIN, OUTPUT); // Initialize the LED_BUILTIN pin as an output
setup_wifi();
client.setServer(mqtt_server, 1883);
}
void blink_now(){
digitalWrite(LED_BUILTIN, LOW);
delay(1000);
digitalWrite(LED_BUILTIN, HIGH);
delay(1000);
}
void setup_wifi() {
//Turn off Access Point
WiFi.mode(WIFI_STA);
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(wifi_ssid);
WiFi.begin(wifi_ssid, wifi_password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
blink_now();
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
blink_now();
// Attempt to connect
if (client.connect(clientID, mqtt_user, mqtt_password)) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish(doorbell_topic, "Doorbell connected to MQTT");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
doorbellState = digitalRead(doorbellPin);
if ( doorbellState == LOW ) {
// Put your code here. e.g. connect, send, disconnect.
Serial.println("Doorbell is pressed!");
client.publish(doorbell_topic, "on", true);
blink_now();
delay( 5000 );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment