Термосенсор умеет отправлять показания по UDP куда скажут

This commit is contained in:
ftc
2021-04-10 14:16:07 +03:00
parent 54f7581094
commit 087db98d98
3 changed files with 72 additions and 16 deletions
+1
View File
@@ -0,0 +1 @@
thermo_sensor/config.h
+5
View File
@@ -0,0 +1,5 @@
#define WIFI_NAME "your wi-fi name"
#define WIFI_PASS "you wi-fi password"
#define REMOTE_ADDR "IP address of host to send data to"
#define REMOTE_PORT 7000
+66 -16
View File
@@ -1,36 +1,86 @@
#include "DHT.h" #include "DHT.h"
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include "config.h"
#define DHTPIN 5 #define DHTPIN 5
#define DHTTYPE DHT22 #define DHTTYPE DHT22
#define READ_INTERVAL 1000
WiFiUDP udp;
DHT dht(DHTPIN, DHTTYPE); DHT dht(DHTPIN, DHTTYPE);
char id[64];
void setup() { void setup()
{
Serial.begin(115200); Serial.begin(115200);
Serial.println("Initialised..."); Serial.println("Initialised...");
dht.begin(); 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);
} }
void loop() char payload[1024];
{
delay(1500);
void Convert(float v, char* s)
{
if (isnan(v))
{
strcpy(s, "null");
}
else
{
sprintf(s, "%.3f", v);
}
}
void ReadAndSend()
{
float h = dht.readHumidity(); float h = dht.readHumidity();
float t = dht.readTemperature(); float t = dht.readTemperature();
if (isnan(h) || isnan(t)) { char h_str[15];
Serial.println("Error. Can't get humidity/temperature."); char t_str[15];
Convert(h, h_str);
Convert(t, t_str);
int len = snprintf(payload, sizeof(payload), "{\"t\":%s,\"h\":%s,\"id\":\"%s\"}", t_str, h_str, id);
Serial.print("Sending payload:\n");
Serial.println(payload);
if (!udp.beginPacket(REMOTE_IP, REMOTE_PORT))
{
Serial.println("Error with destination ip or port");
return; return;
} }
udp.write(payload, len);
Serial.print("Temperature: "); udp.endPacket();
Serial.print(t); }
Serial.print(" "); unsigned long last_read = 0;
Serial.print("Humidity: "); void loop()
Serial.print(h); {
unsigned long current = millis();
Serial.println(); if (current < last_read || current - last_read >= READ_INTERVAL)
{
ReadAndSend();
last_read = current;
}
} }