Термосенсор умеет отправлять показания по UDP куда скажут
This commit is contained in:
@@ -0,0 +1 @@
|
||||
thermo_sensor/config.h
|
||||
@@ -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
|
||||
@@ -1,36 +1,86 @@
|
||||
#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() {
|
||||
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);
|
||||
}
|
||||
|
||||
void loop()
|
||||
{
|
||||
delay(1500);
|
||||
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();
|
||||
|
||||
if (isnan(h) || isnan(t)) {
|
||||
Serial.println("Error. Can't get humidity/temperature.");
|
||||
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\"}", 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;
|
||||
}
|
||||
|
||||
Serial.print("Temperature: ");
|
||||
Serial.print(t);
|
||||
|
||||
Serial.print(" ");
|
||||
|
||||
Serial.print("Humidity: ");
|
||||
Serial.print(h);
|
||||
|
||||
Serial.println();
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user