Skip to content

Instantly share code, notes, and snippets.

@jpaulickcz
Created December 18, 2022 13:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpaulickcz/14b7caf69a49cb62fc2a2603f76c0dfd to your computer and use it in GitHub Desktop.
Save jpaulickcz/14b7caf69a49cb62fc2a2603f76c0dfd to your computer and use it in GitHub Desktop.
Publish DS18B20 sensor readings over MQTT with a ESP8266/Wemos D1 Mini board
// LIBRARIES
#include <ESP8266WiFi.h> // Library for connecting to a WiFi network
#include <PubSubClient.h> // Library for MQTT communication
#include <OneWire.h> // Library for interacting with 1-Wire devices
#include <DallasTemperature.h> // Library for reading temperature from Dallas Temperature sensors
// Define the pin number that the 1-Wire bus is connected to
#define ONE_WIRE_BUS 2
// WIFI SETTINGS
#define wifi_ssid "WIFINAME" // WiFi network name
#define wifi_password "PASSWORD" // WiFi network password
#define mqtt_server "MQQTBROKER" // MQTT broker address
// MQTT SETTINGS
#define temperature_topic "sensor/balcony/water_temperature" // MQTT topic to publish temperature on
#define client_id "balcony-water" // MQTT client ID (must be different if more Wemos/ESP8266 are connecting to the MQTT broker)
// TEMP SENSOR SETTINGS
OneWire oneWire(ONE_WIRE_BUS); // Create an instance of the OneWire class for the 1-Wire bus on pin ONE_WIRE_BUS
DallasTemperature sensors(&oneWire); // Create an instance of the DallasTemperature class to read temperature from the 1-Wire bus
float Celcius = 0; // Variable to store the temperature in degrees Celsius
// Declare variables for WiFi and MQTT communication
WiFiClient espClient;
PubSubClient client(espClient);
// SETUP
void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
}
void setup_wifi() {
delay(10);
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(".");
}
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...");
// Attempt to connect
// If you do not want to use a username and password, change next line to
// if (client.connect("ESP8266Client")) {
if (client.connect(client_id)) {
Serial.println("connected");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
// Constants for various intervals and thresholds
const int PUBLISH_INTERVAL_MILLIS = 300000; // 5 minutes in milliseconds
const float TEMP_CHANGE_THRESHOLD = 0.5; // Change threshold in degrees Celsius
const int MIN_PUBLISH_INTERVAL_MILLIS = 2000; // 2 seconds in milliseconds
const float MIN_ACCEPTABLE_TEMP = -20; // Minimum acceptable temperature in degrees Celsius
const float MAX_ACCEPTABLE_TEMP = 40; // Maximum acceptable temperature in degrees Celsius
// Variables to store the last temperature reading and the time of the last published temperature
float lastTemp = 0;
long lastPublishTime = 0;
void loop() {
// Read temperature from sensor
sensors.requestTemperatures(); // Request temperature readings from the sensor
float temp = sensors.getTempCByIndex(0); // Get the temperature reading in degrees Celsius
Serial.print("Reading temperature... ");
Serial.print(temp); // Print the temperature reading to the serial console
Serial.println(" °C");
// Check if temperature is within acceptable range
if (temp < MIN_ACCEPTABLE_TEMP || temp > MAX_ACCEPTABLE_TEMP) {
// If the temperature is out of range, print an error message to the serial console
Serial.println("Error: temperature out of range. Check wiring.");
Serial.print("Temperature reading: ");
Serial.print(temp);
Serial.println(" °C");
// Publish the error message and temperature reading on a different MQTT topic
client.publish("error-merak-teploty-vody-meri", String(temp).c_str());
// Pause for 1 second before continuing
delay(1000);
return; // Return from the function to prevent further processing
}
// Calculate time since last publish
long now = millis(); // Get the current time in milliseconds
long timeSinceLastPublish = now - lastPublishTime; // Calculate the time since the last published temperature
// Check if it's time to publish temperature
if ((timeSinceLastPublish > PUBLISH_INTERVAL_MILLIS || abs(temp - lastTemp) > TEMP_CHANGE_THRESHOLD) && timeSinceLastPublish > MIN_PUBLISH_INTERVAL_MILLIS) {
lastPublishTime = now; // Update the time of the last published temperature
lastTemp = temp; // Update the last temperature reading
// Print a message to the serial console indicating that the temperature was published
Serial.print("Published temperature: ");
Serial.print(String(temp).c_str());
Serial.println(" °C");
client.publish(temperature_topic, String(temp).c_str(), true);
}
delay(1000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment