#include "WiFi.h"
#include"PubSubClient.h"
#define BUTTON_PIN 14 // ESP32 GIOP16 pin connected to button's pin
#define BUZZER_PIN 2 // ESP32 GIOP21 pin connected to Buzzer's pin
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* mqtt_server="broker.mqttdashboard.com";
WiFiClient espclient;
char message_tosend[50];
String messageTemp;
String messages;
String SEND ;
void callback(String topic, byte* message, unsigned int length) {
Serial.print("Message arrived on topic: ");
Serial.print(topic);
Serial.print(". Message: ");
for (int i = 0; i < length; i++) {
Serial.print((char)message[i]);
messages += (char)message[i];
}
Serial.println();
}
PubSubClient client(mqtt_server,1883,callback,espclient);
void setup() {
Serial.begin(9600); // initialize serial
pinMode(BUTTON_PIN, INPUT_PULLUP); // set ESP32 pin to input pull-up mode
pinMode(BUZZER_PIN, OUTPUT); // set ESP32 pin to output mode
Serial.print("connecting");
Serial.print(ssid);
WiFi.begin(ssid,password);
while(WiFi.status()!=WL_CONNECTED){
delay(500);
Serial.print(".");
}
}
void reconnect(){
while(WiFi.status()!=WL_CONNECTED){
delay(500);
Serial.print(".");
}
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
delay(2000);
//Preparing for mqtt send
SEND = messageTemp; //converting temperature (the float variable above) to a string
SEND.toCharArray(message_tosend, SEND.length() + 1); //packaging up the data to publish to mqtt whoa...
if(client.connect("ESP32test1000")){
Serial.println("connected to node-red");
client.publish("buzzer",message_tosend);
}
else{
Serial.print("failed,rc=");
Serial.println(client.state());
delay(500);
}
if (digitalRead(BUTTON_PIN) == LOW) {
Serial.println("The button is being pressed");
digitalWrite(BUZZER_PIN, HIGH); // turn on
tone(BUZZER_PIN,500);
messageTemp="Someon's at the door";
}
else if (digitalRead(BUTTON_PIN) == HIGH) {
Serial.println("The button is unpressed");
digitalWrite(BUZZER_PIN, LOW); // turn off
tone(BUZZER_PIN,0);
messageTemp="No one there";
}
}