Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <ESP8266WiFi.h>
- #include <PubSubClient.h>
- // WiFi credentials
- char ssid[] = "";
- char pass[] = "";
- // MQTT broker details
- const char* server = "";
- const char* username = "notabot";
- const char* password = "";
- // Change as required
- const char* topic = "Home/mailbox";
- const char* msg = "You Got Mail!";
- byte QoS = 2;
- boolean retain = false;
- WiFiClient espClient;
- PubSubClient mqttClient(espClient);
- void youGotMail() {
- Serial.println("You got mail!");
- while (!mqttClient.connected()) {
- Serial.print("Attempting MQTT connection...");
- // Attempt to connect
- if (mqttClient.connect("espbot", username, password, topic, QoS, retain, msg)) {
- Serial.println("connected");
- // Once connected, publish an announcement...
- if ( mqttClient.publish(topic, msg)) {
- Serial.println("Successfully published.");
- }
- } else {
- Serial.print("failed, rc=");
- Serial.print(mqttClient.state());
- Serial.println(" try again in 5 seconds");
- // Wait 5 seconds before retrying
- delay(5000);
- }
- }
- }
- void setup() {
- Serial.begin(115200);
- while (!Serial) {}
- Serial.print("Reading sensor: ");
- Serial.println(analogRead(A0));
- if (analogRead(A0) > 500) {
- // Connect to WiFi
- WiFi.begin(ssid, pass);
- while (WiFi.status() != WL_CONNECTED) {
- delay(500);
- Serial.print(".");
- }
- if (WL_CONNECTED) {
- Serial.println("Connected!");
- }
- pinMode(A0, INPUT);
- Serial.print("Reading sensor: ");
- Serial.println(analogRead(A0));
- mqttClient.setServer(server, 1883);
- // Run our notification logic
- youGotMail();
- mqttClient.disconnect();
- // I found that not disconnecting caused issues with my router...
- WiFi.disconnect(true);
- }
- // Sleep for 60 seconds
- ESP.deepSleep(60*1000000);
- }
- // The void loop is never reached when using deepSleep()
- // All code must be executed in the setup() function.
- void loop() {
- }
Add Comment
Please, Sign In to add comment