Use Adafruit dht library instead of SimpleDHT
[manu/arduino-maison.git] / cave / cave.ino
1 #include <WiFi.h>
2 #include <WiFiUdp.h>
3 #include <HCSR04.h>
4 #include <Adafruit_Sensor.h>
5 #include <DHT.h>
6 #include <DHT_U.h>
7
8 #include "cave-config.h"
9
10 const char*    wifi_ssid = WIFI_SSID;
11 const char*    wifi_pass = WIFI_PASS;
12
13 // Grafana
14 IPAddress      influxdb_ip(INFLUXDB_IP);
15 long           influxdb_port = INFLUXDB_PORT;
16 unsigned int   localPort = 2390;
17 // MilliSeconds
18 long unsigned  poll_int = POLL_INT;
19 String city = CITY;
20 String location = LOCATION;
21 WiFiUDP Udp;
22
23 // TRIGGER, ECHO
24 UltraSonicDistanceSensor distanceSensor(14, 12);
25
26 // Temp
27 #define DHTPIN 27
28 #define DHTTYPE DHT22
29 DHT_Unified dht(DHTPIN, DHTTYPE);
30
31 void setup() {
32
33   #if defined(DEBUG)
34   Serial.begin(115200);
35   Serial.print("Connecting to ");
36   Serial.println(wifi_ssid);
37   #endif
38
39   WiFi.mode(WIFI_STA);
40   WiFi.begin(WIFI_SSID, WIFI_PASS);
41
42   while (WiFi.status() != WL_CONNECTED) {
43     delay(500);
44     #if defined(DEBUG)
45     Serial.print(".");
46     #endif
47   }
48
49   #if defined(DEBUG)
50   Serial.println("WiFi connected");
51   Serial.println("IP address: ");
52   Serial.println(WiFi.localIP());
53   #endif
54
55   dht.begin();
56   sensor_t sensor;
57   dht.temperature().getSensor(&sensor);
58   dht.humidity().getSensor(&sensor);
59
60 }
61
62 void loop() {
63   delay(POLL_INT);
64
65   sensors_event_t event;
66   
67   dht.temperature().getEvent(&event);
68   if (isnan(event.temperature)) {
69       #if defined(DEBUG)
70       Serial.println("DHT 22 temperature error");
71       #endif
72   } else {
73       #if defined(DEBUG)
74       Serial.println("Temperature: "+String(event.temperature));
75       #endif
76       sendToInfluxDB("temperature,city="+city+",location="+location, "value", String(event.temperature));
77       double water_dist = distanceSensor.measureDistanceCm(event.temperature);
78       #if defined(DEBUG)
79       Serial.println("Distance: "+String(water_dist));
80       #endif
81       sendToInfluxDB("water_well,city="+city+",location="+location, "distance", String(water_dist));
82   }
83   dht.humidity().getEvent(&event);
84   if (isnan(event.relative_humidity)) {
85       #if defined(DEBUG)
86       Serial.println("DHT 22 humidity error");
87       #endif
88   } else {
89       #if defined(DEBUG)
90       Serial.println("Humidity: "+String(event.relative_humidity));
91       #endif
92       sendToInfluxDB("humidity,city="+city+",location="+location, "value", String(event.relative_humidity));
93   }
94 }
95
96 void sendToInfluxDB(String measure, String key, String value) {
97   String line = measure+" "+key+"="+value;
98   Udp.begin(localPort);
99   Udp.beginPacket(influxdb_ip, influxdb_port);
100   Udp.print(line);
101   Udp.endPacket();
102 }