ESP8266 + Arduino IDE 1.6.5 + DHT22 + SHT20 溫濕度感應器
#include <Wire.h>
#include <DHT.h>
#include "SparkFunHTU21D.h"
#include <ESP8266WiFi.h>
#define DHTPIN 4
#define DHTTYPE DHT22
// Wifi definition
const char* ssid = "Buffalo9F-2";
const char* password = "0227057373";
const char* server = "184.106.153.149";
String apiKey = "P1UO6DM0KA8X79SQ";
WiFiClient client;
//Create an instance of the object
HTU21D myHumidity;
DHT dht(DHTPIN, DHTTYPE);
void reConnectAP()
{
int i = 0;
WiFi.begin(ssid, password);
while ((WiFi.status() != WL_CONNECTED) && (i < 100)) {
delay(500);
Serial.print(".");
i = i++;
}
if (WiFi.status() == WL_CONNECTED) {
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
myHumidity.begin();
dht.begin();
}
}
void setup()
{
int i;
Serial.begin(9600);
Serial.print("Connecting to ");
Serial.println(ssid);
reConnectAP();
}
void loop()
{
if (WiFi.status() != WL_CONNECTED) {
reConnectAP();
return;
}
// SHT20
float humd = myHumidity.readHumidity();
float temp = myHumidity.readTemperature();
// dht22
float dhth = dht.readHumidity();
// Read temperature as Celsius (the default)
float dhtt = dht.readTemperature();
if (isnan(humd) || isnan(temp) || isnan(dhth) || isnan(dhtt)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
Serial.print("Sending sht20 data to thingspeak.com\n");
if (client.connect(server, 80)) { // "184.106.153.149" or api.thingspeak.com
String postStr = apiKey;
postStr += "&field1=";
postStr += String(temp);
postStr += "&field2=";
postStr += String(humd);
postStr += "&field3=";
postStr += String(dhtt);
postStr += "&field4=";
postStr += String(dhth);
postStr += "\r\n\r\n";
client.print("POST /update HTTP/1.1\n");
client.print("Host: api.thingspeak.com\n");
client.print("Connection: close\n");
client.print("X-THINGSPEAKAPIKEY: " + apiKey + "\n");
client.print("Content-Type: application/x-www-form-urlencoded\n");
client.print("Content-Length: ");
client.print(postStr.length());
client.print("\n\n");
client.print(postStr);
Serial.print(postStr);
Serial.print("\n");
Serial.print("SHT20 Temperature:");
Serial.print(temp, 1);
Serial.print("C");
Serial.print("SHT20 Humidity:");
Serial.print(humd, 1);
Serial.print("%");
Serial.println();
Serial.print("DHT22 Temperature:");
Serial.print(dhtt, 1);
Serial.print("C");
Serial.print("DHT22 Humidity:");
Serial.print(dhth, 1);
Serial.print("%");
Serial.println();
client.stop();
}
delay(20000);
}
雖然還有一個設備沒接上,先用我的角蛙缸測試一下 :
躲在土中的角蛙 |
養殖缸的底部用過濾網加高土,避免積水在土中 |
下方為土壤濕度計 SHT20 上方為環境溫濕度計 DHT22 |
數據顯示在Thinkspeak |
看了 Thingspeak 數據之後,突然發現 SHT20 傳回的相對濕度超過 100%,看來又要除錯了。
留言
張貼留言
請多指教