When moving to my new apartment I wanted a way of measuring the temperature, which I found a nice excuse to play with some wireless hardware and APIs. Since I still had some Wemos D1 Minis laying around. Below is the code used to sent the temperature and humidity to Telegram. If you would want to use it, please, update the constants to make it match with your DHT setup, API keys, and WiFi Setup.
// ESP core libraries.
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266WiFiMulti.h>
#include <WiFiClientSecureBearSSL.h>
// Uses the Adafruit DHT sensor library.
#include <DHT.h>
// Pin connected to the DHT sensor.
#define DHTPIN 14
// Set the temperature sensor type to the DHT22 one, the library supports
// multiple.
#define DHTTYPE DHT22
#define API_KEY "TELEGRAM API KEY HERE"
#define CHAT_ID "Telegram chat id here"
// Intervals of measurements and messages.
#define TELEGRAM_UPDATE_INTERVAL_IN_MILIS 600000
#define MEASUREMENT_INTERVAL_IN_MILIS 2000
// Initialize DHT sensor.
DHT dht(DHTPIN, DHTTYPE);
const char* ssid = "WiFi SSID";
const char* password = "WiFi Password";
ESP8266WiFiMulti WiFiMulti;
// Contain the timestamps of last measurement.
unsigned long lastMeasurement, lastUpdate = 0;
// Will contain the measurements abd calculated heat index for both Fahrenheit
// and Celsius.
float humitiyMeasurement, temperatureCelsiusMeasurement,
temperatureFahrenheitMeasurement, heatIndexFahrenheitMeasurement,
heatIndexCelsiusMeasurement;
void setupWifi() {
// Switch off the internal LED.
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(ledPin, LOW);
// Connect to WiFi network.
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFiMulti.addAP(ssid, password);
// Wait on WiFi to connect. List of possible status codes is available here:
// https://realglitch.com/2018/07/arduino-wifi-status-codes/
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print("Waiting on WiFi, status: ")
Serial.print(WiFi.status());
Serial.println("");
}
Serial.println("");
Serial.println("WiFi connected");
}
void setup() {
Serial.begin(9600);
delay(500);
setupWifi();
dht.begin();
}
void sendMeasurement() {
// Wait a bit between measurements.
if (lastUpdate != 0 && millis() < lastUpdate +
TELEGRAM_UPDATE_INTERVAL_IN_MILIS) return;
lastUpdate = millis();
// Setup client for SSL communication, in which we disable verification of the
// certificates. WARNING DISABLING CERTIFICATE VERIFICATION, ALLOWS THE DATA
// TO BE INTERCEPTED. Don't do this in production, but for playing around at
// home with non sensitive data this is fine.
std::unique_ptr<BearSSL::WiFiClientSecure>client(
new BearSSL::WiFiClientSecure);
client->setInsecure();
HTTPClient https;
// Begin HTTPS connection.
if (https.begin(*client, "https://api.telegram.org/bot" + API_KEY +
"/sendMessage")) {
Serial.print("[HTTPS] GET...\n");
// Start connection and send HTTP header.
int httpCode = https.GET();
https.addHeader("Content-Type", "application/json");
// Message to be showed in chat.
String message = "Humidity: " + String(humitiyMeasurement, 2) +
"% \nTemperature: " +
String(temperatureCelsiusMeasurement, 2) + "°C " +
String(temperatureFahrenheitMeasurement, 2) +
"°F \nHeat index: " +
String(heatIndexCelsiusMeasurement, 2) + "°C " +
String(heatIndexFahrenheitMeasurement, 2) + "°F!";
https.POST("{\"chat_id\": " + CHAT_ID + ", \"text\": \"" + message + "\"}");
// HttpCode will be negative on error.
if (httpCode > 0) {
// HTTP communication finished.
Serial.printf("[HTTPS] GET... code: %d\n", httpCode);
// Log response.
Serial.println(https.getString());
} else {
Serial.printf("[HTTPS] GET... failed, error: %s\n",
https.errorToString(httpCode).c_str());
}
https.end();
} else {
Serial.printf("[HTTPS] Unable to connect\n");
}
}
void updateMeasurement() {
// Wait a bit between measurements.
if (lastMeasurement != 0 && millis() - MEASUREMENT_INTERVAL_IN_MILIS <=
lastMeasurement) return;
lastMeasurement = millis();
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (its a very slow
// sensor).
humitiyMeasurement = dht.readHumidity();
// Read temperature as Celsius.
temperatureCelsiusMeasurement = dht.readTemperature();
// Read temperature as Fahrenheit.
temperatureFahrenheitMeasurement = dht.readTemperature(true);
// Check if any reads failed and exit early (to try again in a bit).
if (isnan(humitiyMeasurement) || isnan(temperatureCelsiusMeasurement) ||
isnan(temperatureFahrenheitMeasurement)) {
Serial.println(F("Failed to read from DHT sensor!"));
return;
}
// Compute heat index for Fahrenheit and Celsius according to:
// http://www.wpc.ncep.noaa.gov/html/heatindex_equation.shtml
heatIndexFahrenheitMeasurement = dht.computeHeatIndex(
temperatureFahrenheitMeasurement, humitiyMeasurement);
heatIndexCelsiusMeasurement = dht.computeHeatIndex(
temperatureCelsiusMeasurement, humitiyMeasurement, false);
}
void loop() {
if (WiFi.status() != WL_CONNECTED) {
setupWifi();
}
updateMeasurement();
sendMeasurement();
}