Close

Example: Undervoltage alert in Telegram

A project log for Homefixer ESP8266 devboard

A lightweight and simple devboard for ESP8266-12 with 2.54mm breadboard pinout and works with 1V-5.5V batteries

johan-westlundJohan Westlund 01/11/2018 at 20:140 Comments

Preparation:

Here is an example code for node-red for Undervoltage alert to Telegram.

You need to add:

*A bot to the sender node,

*Put the text you want to be sent out in the text node,

*Add chatid in conversation node: https://firstwarning.net/vanilla/discussion/4/create-telegram-bot-and-get-bots-token-and-the-groups-chat-id

*Your topic and Broker to the MQTT node.

 
Arduino code:

Basic work: Wifi connect -> MQTT Broker connect -> Measure Voltage -> Send Voltage over MQTT -> deep sleep "sleepTimsS" seconds

#include <ESP8266WiFi.h>
#include <PubSubClient.h> // MQTT

#define sleepTimeS 600 //Time between updates

// CHANGE
const char* ssid = "ssid";
const char* password = "pass";
const char* mqtt_server = "IP";
String device_topic = "your_topic";
float cal_volt = 6.85; // Calibrate this value if the voltage reading is of

String voltage_topic = device_topic+"/voltage";

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
  
void setup() {
  pinMode(15, OUTPUT);
  digitalWrite(15, HIGH);
  //Wifi
  WiFi.begin(ssid, password);
  int wifiTryConnectCounter = 0;
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    wifiTryConnectCounter++;
    if (wifiTryConnectCounter >= 10)
    {
      ESP.deepSleep(sleepTimeS * 1000000);
    }
  }
  
  //MQTT
  client.setServer(mqtt_server, 1883);   
  // Create a random client ID
  String clientId = "ESP8266Client-";
  clientId += String(random(0xffff), HEX);
  // Attempt to connect
  if (client.connect(clientId.c_str())) {
    //Success
  } else {
    ESP.deepSleep(sleepTimeS * 1000000);
  }
  
  //Sensor
  digitalWrite(15, LOW);
  int sensorValue = analogRead(A0);
  digitalWrite(15, HIGH);
  // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
  float voltage = sensorValue * (cal_volt / 1023.0);
  //Send
  snprintf (msg, 75, "%ld", (int)(voltage * 1000));
  client.publish(voltage_topic.c_str(), msg);

  //Sleep and repeat
  client.loop(); // MQTT work
  ESP.deepSleep(sleepTimeS * 1000000);
}

void loop() {
  // Will not run
}

Discussions