Cheap MQTT Doorbell using NodeMCU ESP8266 V3

A project Based on https://community.home-assistant.io/t/mqtt-doorbell/15081i approached the making a mqtt doorbell using arduino input pullup

#include
#include

//WIFI
const char* wifi_ssid = “”;
const char* wifi_password = “”;

//MQTT
const char* mqtt_server = “”;
const char* mqtt_user = “”;
const char* 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, 19932);
}

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 );
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *