Files
ESP32asServer/5exampleAddingTemperature/5exampleAddingTemperature.ino

222 lines
5.3 KiB
Arduino
Raw Normal View History

2026-01-04 22:27:45 +01:00
#include <WiFi.h>
#include <WebServer.h>
#include <ESPmDNS.h>
#include <time.h>
#include <Wire.h>
#include <Adafruit_BMP085.h> // Works for BMP180 too
// ================== CHANGE THESE ==================
const char* ssid = "Bertovic";
const char* password = "18072019";
// mDNS name => http://myhome.local/
const char* mdnsName = "myhome";
// NTP
const char* ntpServer = "pool.ntp.org";
// Timezone example: Europe/Zagreb (CET = UTC+1). This offset version does NOT auto-handle DST.
const long gmtOffset_sec = 3600; // UTC+1
const int daylightOffset_sec = 0;
// BMP180 I2C pins (your values)
// NOTE: On many ESP32 boards, GPIO 6/7 are not usable (often connected to flash).
// If it doesn't work, use e.g. SDA=21, SCL=22 (common defaults).
#define SDA_PIN 7
#define SCL_PIN 6
// ==================================================
WebServer server(80);
Adafruit_BMP085 bmp;
bool bmpOk = false;
float lastTempC = NAN;
unsigned long lastTempReadMs = 0;
String getTimeString() {
struct tm timeinfo;
if (!getLocalTime(&timeinfo)) return "Time not ready";
char buf[32];
strftime(buf, sizeof(buf), "%H:%M:%S", &timeinfo);
return String(buf);
}
String getDateString() {
struct tm timeinfo;
if (!getLocalTime(&timeinfo)) return "";
char buf[64];
strftime(buf, sizeof(buf), "%A, %d %B %Y", &timeinfo);
return String(buf);
}
void updateTemperatureIfNeeded() {
// Read BMP180 at most once per second
if (!bmpOk) return;
unsigned long now = millis();
if (now - lastTempReadMs < 1000) return;
lastTempReadMs = now;
float t = bmp.readTemperature();
lastTempC = t;
// Optional Serial output (like your original code)
Serial.print("Temperature: ");
Serial.print(lastTempC);
Serial.println(" °C");
}
String getTempString() {
updateTemperatureIfNeeded();
if (!bmpOk) return "Sensor not detected";
if (isnan(lastTempC)) return "Reading...";
char buf[16];
// 1 decimal place, e.g. 23.4 °C
snprintf(buf, sizeof(buf), "%.1f °C", lastTempC);
return String(buf);
}
void handleRoot() {
String page = R"rawliteral(
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>ESP32 Temperature</title>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;600;900&display=swap" rel="stylesheet">
<style>
html, body {
height: 100%;
margin: 0;
font-family: 'Inter', sans-serif;
background: linear-gradient(135deg, #0b132b, #1c2541, #3a506b);
color: white;
}
.container {
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
text-align: center;
padding: 24px;
box-sizing: border-box;
}
.temp {
font-size: clamp(4.5rem, 14vw, 8rem);
font-weight: 900;
letter-spacing: 1px;
line-height: 1;
}
.time {
margin-top: 12px;
font-size: clamp(2.2rem, 6vw, 3.6rem);
font-weight: 600;
opacity: 0.9;
}
.date {
margin-top: 10px;
font-size: 1.1rem;
opacity: 0.8;
}
.small {
margin-top: 18px;
font-size: 0.9rem;
opacity: 0.6;
}
</style>
</head>
<body>
<div class="container">
<div class="temp" id="temp">--.- °C</div>
<div class="time" id="time">--:--:--</div>
<div class="date" id="date"></div>
<div class="small">myhome.local • ESP32</div>
</div>
<script>
async function update(){
try {
document.getElementById('temp').textContent =
await (await fetch('/temp', { cache: 'no-store' })).text();
document.getElementById('time').textContent =
await (await fetch('/time', { cache: 'no-store' })).text();
document.getElementById('date').textContent =
await (await fetch('/date', { cache: 'no-store' })).text();
} catch (e) {}
}
update();
setInterval(update, 1000);
</script>
</body>
</html>
)rawliteral";
server.send(200, "text/html", page);
}
void handleTime() { server.send(200, "text/plain", getTimeString()); }
void handleDate() { server.send(200, "text/plain", getDateString()); }
void handleTemp() { server.send(200, "text/plain", getTempString()); }
void setup() {
Serial.begin(115200);
delay(1000);
// I2C init with your custom pins
Wire.begin(SDA_PIN, SCL_PIN);
Serial.println("Initializing BMP180...");
bmpOk = bmp.begin();
if (!bmpOk) {
Serial.println("Could not find BMP180 sensor!");
} else {
Serial.println("BMP180 detected!");
}
// Wi-Fi
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nWiFi connected!");
Serial.print("ESP32 IP: ");
Serial.println(WiFi.localIP());
// mDNS
if (!MDNS.begin(mdnsName)) {
Serial.println("mDNS start FAILED");
} else {
Serial.print("mDNS started: http://");
Serial.print(mdnsName);
Serial.println(".local/");
}
// Time sync
configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
// Web routes
server.on("/", handleRoot);
server.on("/time", handleTime);
server.on("/date", handleDate);
server.on("/temp", handleTemp);
server.begin();
Serial.println("HTTP server started");
}
void loop() {
server.handleClient();
updateTemperatureIfNeeded(); // keep temp fresh even if nobody is polling
}