This is a record of obtaining temperature, humidity, and pressure with the BME280 and sending it directly to Graphite via ESP32’s Wi-Fi connection. There will be no explanation of Graphite or Grafana.
Items Used
Item Name | Purchase |
---|---|
ESP-32S | AliExpress Amazon 楽天 |
BME280 | AliExpress Amazon 楽天 |
Connection Diagram
The BME280 and ESP-32S are connected via I2C. The GPIO21 of ESP-32S serves as SDA, and GPIO22 serves as SCL.
ESP-32S | BME280 |
---|---|
3.3V | VIN |
GND | GND |
GPIO21 | SDA |
GPIO22 | SCL |
Content
- Connect to Wi-Fi
- Query NTP server to get the time
- Create a timer interrupt to send data every second
Code
#include <Arduino.h>
#include <WiFi.h>
#include <Wire.h>
#include <Adafruit_BME280.h>
#include <Ticker.h>
#include <WiFiUdp.h>
#include <time.h>
// Wi-Fi
const char SSID[] = "";
const char PASSWORD[] = "";
// NTP Server
const char NTP_SERVER[] = "ntp.nict.jp";
// Graphite
IPAddress graphite(192,168,0,10);
// Ticker
Ticker ticker;
bool flagTicker = false;
// BME280 Sensor
Adafruit_BME280 bme;
void setTicker() {
flagTicker = true;
}
// UDP
WiFiUDP udp;
void setup() {
Serial.begin(115200);
while (!Serial);
if (!bme.begin(0x76)) {
Serial.println("BME280 sensor error!");
while (1);
}
// Wi-Fi connection
WiFi.begin(SSID, PASSWORD);
Serial.print("WiFi connecting");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(100);
}
IPAddress ipaddr, gateway;
ipaddr = WiFi.localIP();
gateway = WiFi.gatewayIP();
Serial.println("WiFi Connected.");
Serial.print("IPAddr:");
Serial.println(ipaddr);
Serial.print("Gateway:");
Serial.println(gateway);
// NTP
configTime(9 * 3600L, 0, NTP_SERVER);
// ms
struct timeval tv;
int ms = 0;
while(1) {
if (gettimeofday(&tv, NULL) != 0) {
Serial.println("error gettimeofday.");
}else{
ms = tv.tv_usec / 1000LL;
}
if(ms == 0) {
ticker.attach_ms(1000, setTicker);
Serial.println("set ticker");
break;
}
}
}
void send() {
time_t now;
time(&now);
udp.beginPacket(graphite, 2003);
udp.println("sec.esp32.temperature " + String(bme.readTemperature()) + " " + now);
udp.println("sec.esp32.humidity " + String(bme.readHumidity()) + " " + now);
udp.println("sec.esp32.pressure " + String(bme.readPressure() / 100) + " " + now);
udp.endPacket();
}
void loop() {
if(flagTicker) {
send();
flagTicker = false;
}
}
Libraries Used
Visualizing with Grafana
I was able to obtain sensor data from the BME280 using the ESP32, accumulate it in Graphite (go-carbon) via Wi-Fi, and visualize it with Grafana.
Data is added every second, allowing for quite real-time data acquisition. Since power consumption was also kept below 0.5W, it seems convenient for collecting data at home.