Battery weather station¶
A BME280 measures temperature, humidity and air pressure; the board wakes up every 10 minutes, stores a reading in SQL Server and goes back to deep sleep. No MQTT broker or cloud service in between, and SQL queries for the daily summary, the pressure trend, and stations that stopped reporting.
Parts and wiring¶
- ESP32 or ESP8266 board. For battery use, pick one with a low-power regulator; many development boards draw several mA even while the chip sleeps.
- BME280 breakout, on I2C:
| BME280 | ESP32 | ESP8266 |
|---|---|---|
| VIN | 3V3 | 3V3 |
| GND | GND | GND |
| SDA | GPIO21 | D2 (GPIO4) |
| SCL | GPIO22 | D1 (GPIO5) |
On the ESP8266, also connect D0 (GPIO16) to RST: the chip wakes from deep sleep by resetting itself through that pin. Disconnect it while uploading if the upload fails.
Set up the database¶
Run setup.sql in your database:
CREATE TABLE dbo.weather (
id INT IDENTITY PRIMARY KEY,
station VARCHAR(32) NOT NULL,
temperature REAL NOT NULL,
humidity REAL NOT NULL,
pressure_hpa REAL NOT NULL,
recorded_at DATETIME2 NOT NULL DEFAULT SYSUTCDATETIME()
);
CREATE INDEX ix_weather_station ON dbo.weather (station, recorded_at);
GO
-- Rejects readings that a working BME280 can't produce (e.g. after
-- a loose wire). THROW makes the call fail on the device.
CREATE PROCEDURE dbo.add_weather
@station VARCHAR(32),
@temperature REAL,
@humidity REAL,
@pressure_hpa REAL
AS
BEGIN
IF @temperature NOT BETWEEN -40 AND 85 OR @humidity NOT BETWEEN 0 AND 100
OR @pressure_hpa NOT BETWEEN 300 AND 1100
THROW 50001, 'Reading out of the BME280''s range', 1;
INSERT INTO dbo.weather (station, temperature, humidity, pressure_hpa)
VALUES (@station, @temperature, @humidity, @pressure_hpa);
END
GO
-- The station may only add readings. Run CREATE LOGIN in master.
CREATE LOGIN weather WITH PASSWORD = '<a long random password>';
CREATE USER weather FOR LOGIN weather;
GRANT EXECUTE ON dbo.add_weather TO weather;
GO
The procedure rejects readings that a BME280 can't produce, with THROW, so
a faulty sensor shows up as failed calls rather than as bad data.
Configure the sketch¶
Install the Adafruit BME280 Library, open weather_station.ino, and fill in the Wi-Fi and database settings at the top. With PlatformIO:
How it works¶
After deep sleep, the board starts from the beginning, so everything happens
in setup(): read the sensor, connect, store, sleep. Nothing is kept from one
wake-up to the next.
// Everything happens in setup(): each wake-up starts the sketch anew
void setup() {
Serial.begin(115200);
if (not bme.begin(0x76) && not bme.begin(0x77)) {
Serial.println("No BME280 found; check the wiring");
sleep_until_next_reading();
}
// Forced mode: one measurement on request, then the sensor sleeps too
bme.setSampling(Adafruit_BME280::MODE_FORCED, Adafruit_BME280::SAMPLING_X1,
Adafruit_BME280::SAMPLING_X1, Adafruit_BME280::SAMPLING_X1,
Adafruit_BME280::FILTER_OFF);
bme.takeForcedMeasurement();
const float temperature = bme.readTemperature();
const float humidity = bme.readHumidity();
const float pressure = bme.readPressure() / 100.0f; // Pa -> hPa
Serial.printf("%.2f C, %.1f %%, %.1f hPa\n", temperature, humidity, pressure);
if (isnan(temperature) || isnan(humidity) || isnan(pressure)) {
// SQL Server can't store NaN; the sensor didn't answer
Serial.println("The BME280 returned no reading");
} else if (not connect_wifi()) {
Serial.println("No Wi-Fi; this reading is lost");
} else if (not store_reading(temperature, humidity, pressure)) {
Serial.println("Could not store the reading");
} else {
Serial.println("Stored");
}
sleep_until_next_reading();
}
void loop() {
// Not reached: deep sleep ends with a restart
}
Each wake-up logs in afresh, with few retries: a station that can't reach the server gives up and sleeps, rather than draining the battery.
static bool store_reading(float temperature, float humidity, float pressure_hpa) {
decltype(driver)::connection_parameters params;
params.server_name = db_server;
params.db_name = db_name;
params.user_name = db_user;
params.password = db_password;
params.app_name = station_name;
params.packet_size = 1024;
params.conn_retry_count = 2;
params.conn_retry_delay_ms = 1000;
if (not(driver.connect(params) == decltype(driver)::e_driver_error_code::success)) {
return false;
}
tdsl::sql_parameter_varchar station{station_name};
tdsl::sql_parameter_float4 t{temperature}, h{humidity}, p{pressure_hpa};
tdsl::sql_parameter_binding values []{station, t, h, p};
return static_cast<bool>(driver.execute_rpc(
tdsl::string_view{"EXEC dbo.add_weather @station = @p0, @temperature = @p1, "
"@humidity = @p2, @pressure_hpa = @p3"},
values));
}
static void sleep_until_next_reading() {
Serial.printf("Sleeping for %u minute(s)\n", static_cast<unsigned>(sleep_minutes));
Serial.flush();
const uint64_t us = uint64_t{sleep_minutes} * 60u * 1000000u;
#if defined(ESP32)
esp_sleep_enable_timer_wakeup(us);
esp_deep_sleep_start();
#else
ESP.deepSleep(us); // wakes up through GPIO16 -> RST
#endif
}
The server stamps each reading with its own clock (DEFAULT
SYSUTCDATETIME()), so the station needs no clock and no NTP.
Reports¶
From queries.sql. The times are in UTC.
The latest reading of each station:
-- The latest reading of each station, and how old it is
SELECT station, temperature, humidity, pressure_hpa, recorded_at,
DATEDIFF(MINUTE, recorded_at, SYSUTCDATETIME()) AS minutes_ago
FROM (
SELECT station, temperature, humidity, pressure_hpa, recorded_at,
ROW_NUMBER() OVER (PARTITION BY station ORDER BY recorded_at DESC, id DESC) AS n
FROM dbo.weather
) AS w
WHERE n = 1;
Daily minimum, maximum and average:
-- Daily minimum, maximum and average, over the last 30 days
SELECT station,
CAST(recorded_at AS DATE) AS day,
MIN(temperature) AS min_temperature,
MAX(temperature) AS max_temperature,
AVG(temperature) AS avg_temperature,
AVG(humidity) AS avg_humidity
FROM dbo.weather
WHERE recorded_at > DATEADD(DAY, -30, SYSUTCDATETIME())
GROUP BY station, CAST(recorded_at AS DATE)
ORDER BY station, day;
The pressure trend over the last 3 hours:
-- Pressure change over the last 3 hours: a fall of more than
-- 3 hPa often means worse weather is on its way
SELECT station,
MAX(CASE WHEN n_new = 1 THEN pressure_hpa END)
- MAX(CASE WHEN n_old = 1 THEN pressure_hpa END) AS change_hpa
FROM (
SELECT station, pressure_hpa,
ROW_NUMBER() OVER (PARTITION BY station ORDER BY recorded_at DESC, id DESC) AS n_new,
ROW_NUMBER() OVER (PARTITION BY station ORDER BY recorded_at ASC, id ASC) AS n_old
FROM dbo.weather
WHERE recorded_at > DATEADD(HOUR, -3, SYSUTCDATETIME())
) AS w
GROUP BY station;
Stations that stopped reporting:
-- Stations that haven't reported for an hour: a flat battery,
-- or out of Wi-Fi range
SELECT station, MAX(recorded_at) AS last_reading
FROM dbo.weather
GROUP BY station
HAVING MAX(recorded_at) < DATEADD(HOUR, -1, SYSUTCDATETIME());
The complete sketch¶
weather_station.ino
#if defined(ESP32)
#include <WiFi.h>
#elif defined(ESP8266)
#include <ESP8266WiFi.h>
#else
#error "This sketch is for the ESP32 and the ESP8266"
#endif
#include <Wire.h>
#include <Adafruit_BME280.h>
#include <tdslite.h>
static const char * wifi_ssid = "<your Wi-Fi name>";
static const char * wifi_password = "<your Wi-Fi password>";
static const char db_server [] = "192.168.1.10";
static const char db_name [] = "home";
static const char db_user [] = "weather";
static const char db_password [] = "<password>";
static const char station_name [] = "garden";
// Minutes between readings
static constexpr uint32_t sleep_minutes = 10;
static tdsl::uint8_t net_buf [2048] = {};
static tdsl::arduino_driver<WiFiClient> driver{net_buf};
static Adafruit_BME280 bme;
static void sleep_until_next_reading() {
Serial.printf("Sleeping for %u minute(s)\n", static_cast<unsigned>(sleep_minutes));
Serial.flush();
const uint64_t us = uint64_t{sleep_minutes} * 60u * 1000000u;
#if defined(ESP32)
esp_sleep_enable_timer_wakeup(us);
esp_deep_sleep_start();
#else
ESP.deepSleep(us); // wakes up through GPIO16 -> RST
#endif
}
static bool connect_wifi() {
WiFi.mode(WIFI_STA);
WiFi.begin(wifi_ssid, wifi_password);
// Don't drain the battery waiting for a network that isn't there
for (int i = 0; i < 30 && WiFi.status() != WL_CONNECTED; i++) {
delay(500);
}
return WiFi.status() == WL_CONNECTED;
}
static bool store_reading(float temperature, float humidity, float pressure_hpa) {
decltype(driver)::connection_parameters params;
params.server_name = db_server;
params.db_name = db_name;
params.user_name = db_user;
params.password = db_password;
params.app_name = station_name;
params.packet_size = 1024;
params.conn_retry_count = 2;
params.conn_retry_delay_ms = 1000;
if (not(driver.connect(params) == decltype(driver)::e_driver_error_code::success)) {
return false;
}
tdsl::sql_parameter_varchar station{station_name};
tdsl::sql_parameter_float4 t{temperature}, h{humidity}, p{pressure_hpa};
tdsl::sql_parameter_binding values []{station, t, h, p};
return static_cast<bool>(driver.execute_rpc(
tdsl::string_view{"EXEC dbo.add_weather @station = @p0, @temperature = @p1, "
"@humidity = @p2, @pressure_hpa = @p3"},
values));
}
// Everything happens in setup(): each wake-up starts the sketch anew
void setup() {
Serial.begin(115200);
if (not bme.begin(0x76) && not bme.begin(0x77)) {
Serial.println("No BME280 found; check the wiring");
sleep_until_next_reading();
}
// Forced mode: one measurement on request, then the sensor sleeps too
bme.setSampling(Adafruit_BME280::MODE_FORCED, Adafruit_BME280::SAMPLING_X1,
Adafruit_BME280::SAMPLING_X1, Adafruit_BME280::SAMPLING_X1,
Adafruit_BME280::FILTER_OFF);
bme.takeForcedMeasurement();
const float temperature = bme.readTemperature();
const float humidity = bme.readHumidity();
const float pressure = bme.readPressure() / 100.0f; // Pa -> hPa
Serial.printf("%.2f C, %.1f %%, %.1f hPa\n", temperature, humidity, pressure);
if (isnan(temperature) || isnan(humidity) || isnan(pressure)) {
// SQL Server can't store NaN; the sensor didn't answer
Serial.println("The BME280 returned no reading");
} else if (not connect_wifi()) {
Serial.println("No Wi-Fi; this reading is lost");
} else if (not store_reading(temperature, humidity, pressure)) {
Serial.println("Could not store the reading");
} else {
Serial.println("Stored");
}
sleep_until_next_reading();
}
void loop() {
// Not reached: deep sleep ends with a restart
}
Going further¶
- Battery life: most of the energy goes into Wi-Fi and the login, a few
seconds per wake-up. A longer
sleep_minuteshelps the most. A static IP address saves the time DHCP takes. - Several stations: give each its own
station_name; the reports group by it. - Readings while offline: a reading that can't be sent is lost. To keep them, store them in RTC memory and send them on the next wake-up.
Related¶
- Log sensor readings: a station that stays connected
- Fit tdslite into a small RAM budget