Files
heat_control/thermo_sensor/thermo_sensor.ino
T

87 lines
1.6 KiB
Arduino

#include "DHT.h"
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include "config.h"
#define DHTPIN 5
#define DHTTYPE DHT22
#define READ_INTERVAL 1000
WiFiUDP udp;
DHT dht(DHTPIN, DHTTYPE);
char id[64];
void setup()
{
Serial.begin(115200);
Serial.println("Initialised...");
dht.begin();
WiFi.begin(WIFI_NAME, WIFI_PASS);
Serial.print("Connecting");
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println();
Serial.print("Connected, IP address: ");
Serial.println(WiFi.localIP());
uint8_t macAddr[6];
WiFi.macAddress(macAddr);
sprintf(id, "%02x:%02x:%02x:%02x:%02x:%02x", macAddr[0], macAddr[1], macAddr[2], macAddr[3], macAddr[4], macAddr[5]);
Serial.printf("Connected, mac address: %s\n", id);
}
char payload[1024];
void Convert(float v, char* s)
{
if (isnan(v))
{
strcpy(s, "null");
}
else
{
sprintf(s, "%.3f", v);
}
}
void ReadAndSend()
{
float h = dht.readHumidity();
float t = dht.readTemperature();
char h_str[15];
char t_str[15];
Convert(h, h_str);
Convert(t, t_str);
int len = snprintf(payload, sizeof(payload), "{\"t\":%s,\"h\":%s,\"id\":\"%s\",\"ip\":\"%s\"}", t_str, h_str, id, WiFi.localIP().toString().c_str());
Serial.print("Sending payload:\n");
Serial.println(payload);
if (!udp.beginPacket(REMOTE_IP, REMOTE_PORT))
{
Serial.println("Error with destination ip or port");
return;
}
udp.write(payload, len);
udp.endPacket();
}
unsigned long last_read = 0;
void loop()
{
unsigned long current = millis();
if (current < last_read || current - last_read >= READ_INTERVAL)
{
ReadAndSend();
last_read = current;
}
}