UCPS_WS26-27/UCPSMain/UCPSMain.ino

311 lines
8.9 KiB
C++

#include <LiquidCrystal.h>
#include <dht_nonblocking.h>
#include <SoftwareSerial.h>
#include <WiFiEsp.h>
// ============ Settings you may need to change ============
// Wifi (phone hotspot)
const char wifiSSID[] = "FreeWifi";
const char wifiPASS[] = "temppassword";
// Computer that runs the Go server (IP of the PC in the hotspot network).
// The server prints it when it starts. If the PC gets a new IP, change it here.
const char SERVER_IP[] = "172.20.46.81";
const int SERVER_PORT = 8080;
const unsigned long POLL_INTERVAL = 5000UL; // ask the server every 5 s
const unsigned long FAILSAFE_MS = 30000UL; // no server answer for 30 s -> heating off
const unsigned long SENSOR_STALE_MS = 30000UL; // no valid sensor value for 30 s -> heating off
const float HYSTERESIS = 0.5; // on below (target - 0.5), off at target
// (keep in sync with HYST in index.html)
// ============ Hardware ============
// ESP8266 (Wifi module, AT firmware)
SoftwareSerial wifiSerial(0, 1); // RX, TX
WiFiEspClient client;
// DHT11 + LCD
#define DHT_SENSOR_TYPE DHT_TYPE_11
static const int DHT_SENSOR_PIN = A1;
DHT_nonblocking dht_sensor(DHT_SENSOR_PIN, DHT_SENSOR_TYPE);
LiquidCrystal lcd(7, 8, 9, 10, 11, 12); // RS, EN, D4, D5, D6, D7
// Light sensor and LEDs
int lightPin = A7; // LDR
int dataPin = 4; // DS
int latchPin = 5; // ST_CP
int clockPin = 6; // SH_CP
int leds = 0;
// ============ State ============
const float NO_TEMP = -999.0;
// Outdoor temperature (Open-Meteo)
const unsigned long API_INTERVAL = 60000UL; // 60s
const unsigned long RETRY_INTERVAL = 30000UL; // 30s
unsigned long lastApiFetch = 0;
unsigned long fetchInterval = API_INTERVAL;
float outdoorTemp = NO_TEMP;
// Indoor temperature (DHT11)
float lastIndoorTemp = NO_TEMP;
unsigned long lastIndoorMillis = 0;
// Orders from the server
char modeLetter = '?'; // 'A' automatic, 'M' manual, '?' = no connection yet / lost
float targetTemp = NO_TEMP;
unsigned long lastServerOk = 0;
bool serverEverOk = false;
unsigned long lastPoll = 0;
// MOSFET module (heating elements)
// The heater is only allowed to run while heatRequest is true AND the
// 60 s ON / 5 s OFF cycle below is in its ON phase.
const int mosfetPin = 13;
unsigned long previousMosfetMillis = 0;
bool mosfetState = true; // phase of the cycle (not the pin!)
const unsigned long mosfetOnTime = 60000UL; // 60 seconds ON
const unsigned long mosfetOffTime = 5000UL; // 5 seconds OFF
bool heatRequest = false; // thermostat wants heat
// ============ Wifi ============
bool ensureWifi() {
if (WiFi.status() == WL_CONNECTED) return true;
WiFi.begin(wifiSSID, wifiPASS);
return WiFi.status() == WL_CONNECTED;
}
// Fetch the current outdoor temperature
float fetchOutdoorTemp() {
if (!ensureWifi()) return NO_TEMP;
client.setTimeout(5000);
if (!client.connect("api.open-meteo.com", 80)) return NO_TEMP;
client.print(F("GET /v1/forecast?latitude=49.46998&longitude=8.4819&current=temperature_2m HTTP/1.1\r\n"
"Host: api.open-meteo.com\r\n"
"Connection: close\r\n"
"\r\n"));
float t = NO_TEMP;
if (client.find("\"current\":") && client.find("\"temperature_2m\":")) {
t = client.parseFloat();
}
client.stop();
return t;
}
// Send indoor temp + heating state to the local server, read mode + target back.
// Answer looks like: mode=A;target=21.00
bool pollServer() {
if (!ensureWifi()) return false;
client.setTimeout(3000);
if (!client.connect(SERVER_IP, SERVER_PORT)) return false;
client.print(F("GET /api/arduino?heat="));
client.print(heatRequest ? 1 : 0);
if (indoorValid()) {
client.print(F("&temp="));
client.print(lastIndoorTemp, 1);
}
client.print(F(" HTTP/1.1\r\nHost: "));
client.print(SERVER_IP);
client.print(F("\r\nConnection: close\r\n\r\n"));
bool ok = false;
if (client.find("mode=")) {
char m = 0;
if (client.readBytes(&m, 1) == 1 && client.find("target=")) {
float t = client.parseFloat();
if ((m == 'A' || m == 'M') && t >= 5.0 && t <= 30.0) {
modeLetter = m;
targetTemp = t;
ok = true;
}
}
}
client.stop();
return ok;
}
// ============ Helpers ============
// Write to LCD display
void lcdLine(uint8_t row, const char *text) {
lcd.setCursor(0, row);
uint8_t i = 0;
for (; text[i] != '\0' && i < 16; i++) lcd.write(text[i]);
for (; i < 16; i++) lcd.write(' ');
}
// LEDs for light sensor
void updateShiftRegister() {
digitalWrite(latchPin, LOW);
shiftOut(dataPin, clockPin, LSBFIRST, leds);
digitalWrite(latchPin, HIGH);
}
// Measure temperature
static bool measure_environment(float *temp, float *hum) {
static unsigned long timestamp = millis();
if (millis() - timestamp > 3000ul) {
if (dht_sensor.measure(temp, hum) == true) {
timestamp = millis();
return true;
}
}
return false;
}
bool indoorValid() {
return lastIndoorTemp != NO_TEMP && (millis() - lastIndoorMillis) < SENSOR_STALE_MS;
}
bool serverFresh() {
return serverEverOk && (millis() - lastServerOk) < FAILSAFE_MS;
}
// Thermostat: decides whether heating is wanted
void updateThermostat() {
if (!serverFresh() || !indoorValid() || targetTemp == NO_TEMP) {
heatRequest = false; // fail-safe: no data -> no heat
return;
}
if (lastIndoorTemp < targetTemp - HYSTERESIS) heatRequest = true;
else if (lastIndoorTemp >= targetTemp) heatRequest = false;
// in between: keep the previous decision (hysteresis)
}
void setup() {
pinMode(mosfetPin, OUTPUT);
digitalWrite(mosfetPin, LOW); // heater off from the very start
pinMode(latchPin, OUTPUT);
pinMode(dataPin, OUTPUT);
pinMode(clockPin, OUTPUT);
lcd.begin(16, 2);
lcdLine(0, "Connecting WiFi");
lcdLine(1, "");
wifiSerial.begin(9600);
WiFi.init(&wifiSerial);
if (WiFi.status() == WL_NO_SHIELD) {
lcdLine(0, "ESP not found");
delay(2000);
}
outdoorTemp = fetchOutdoorTemp();
lastApiFetch = millis();
fetchInterval = (outdoorTemp == NO_TEMP) ? RETRY_INTERVAL : API_INTERVAL;
lcd.clear();
mosfetState = true;
previousMosfetMillis = millis();
lastPoll = millis() - POLL_INTERVAL; // poll the server right away
}
void loop() {
unsigned long currentMillis = millis();
// 60 s ON / 5 s OFF cycle (upper limit for the heater)
if (mosfetState) {
if (currentMillis - previousMosfetMillis >= mosfetOnTime) {
mosfetState = false;
previousMosfetMillis = currentMillis;
}
} else {
if (currentMillis - previousMosfetMillis >= mosfetOffTime) {
mosfetState = true;
previousMosfetMillis = currentMillis;
}
}
unsigned long remainingSeconds = 0;
if (mosfetState) {
remainingSeconds = (mosfetOnTime - (currentMillis - previousMosfetMillis)) / 1000;
} else {
remainingSeconds = (mosfetOffTime - (currentMillis - previousMosfetMillis)) / 1000;
}
// Indoor temp
float indoorTemp, indoorHum;
if (measure_environment(&indoorTemp, &indoorHum) == true) {
lastIndoorTemp = indoorTemp;
lastIndoorMillis = currentMillis;
}
// Ask the local server every POLL_INTERVAL (blocks for a moment)
if (currentMillis - lastPoll >= POLL_INTERVAL) {
if (pollServer()) {
lastServerOk = millis();
serverEverOk = true;
}
lastPoll = millis();
currentMillis = millis();
}
if (!serverFresh()) modeLetter = '?';
// Thermostat + heater output
updateThermostat();
bool heaterOn = heatRequest && mosfetState;
digitalWrite(mosfetPin, heaterOn ? HIGH : LOW);
// LCD row 0 (Temp + heater state + countdown of the ON/OFF cycle)
char line0[20];
char tempStr[6];
if (lastIndoorTemp != NO_TEMP) dtostrf(lastIndoorTemp, 4, 1, tempStr);
else strcpy(tempStr, "--- ");
if (heatRequest) {
snprintf(line0, sizeof(line0), "In:%sC %s %2lu", tempStr, heaterOn ? "ON " : "OFF", remainingSeconds);
} else {
snprintf(line0, sizeof(line0), "In:%sC OFF --", tempStr);
}
lcdLine(0, line0);
// API outdoor temp
if (currentMillis - lastApiFetch >= fetchInterval) {
float t = fetchOutdoorTemp();
lastApiFetch = millis();
currentMillis = millis();
if (t != NO_TEMP) {
outdoorTemp = t;
fetchInterval = API_INTERVAL;
} else {
fetchInterval = RETRY_INTERVAL;
}
}
// LCD row 1: outdoor temp, mode letter (A / M / ?) in the bottom right corner
char left[16];
if (outdoorTemp != NO_TEMP) {
char outStr[10];
dtostrf(outdoorTemp, 4, 1, outStr);
snprintf(left, sizeof(left), "Out: %s C", outStr);
} else {
snprintf(left, sizeof(left), "Out: API Error");
}
char line1[20];
snprintf(line1, sizeof(line1), "%-15s%c", left, modeLetter);
lcdLine(1, line1);
// Light sensor LEDs
int reading = analogRead(lightPin);
int numLEDSLit = reading / 57;
if (numLEDSLit > 8) numLEDSLit = 8;
leds = 0;
for (int i = 0; i < numLEDSLit; i++) {
leds = leds + (1 << i);
}
updateShiftRegister();
delay(100);
}