之前有利用Arduino UNO + ESP8266 做過同樣的功能,但其實ESP8266是很強悍的晶片,能完全取代Arduino UNO的功能,小小的一片晶片不但體積縮小,也比較省電,接下來就看圖說故事,不多作解釋
<只需要esp01 就可以運作,不再需要Arduino的板子>
<USB to FTDI只是為了燒錄程式到ESP01, 燒錄成功後可以拆下來,記得燒錄時GPIO 0 必須接到GND>
<在Arduino IDE ,開發板記得選ESP8266,序列阜也要選FTDI的那個 port>
<都沒問題的話,從 ThingSpeak就可以看到上傳的資料>
Assembly List
Label | Part Type | Properties |
DHT1 | DHT11 Humitidy and Temperature Sensor | |
LED1 | Red (633nm) LED | 套件 1206 [SMD]; 顏色 Red (633nm) |
R1 | 220Ω Resistor | 接腳間隔 400 mil; 套件 THT; bands 4; tolerance ±5%; 電阻 220Ω |
U1 | ESP8266 WiFi Module | variant variant 1; part number ESP8266 |
元件1 | FTDI Basic Programmer | 類型 Basic; 電壓 5V |
程式碼
#include "ESP8266WiFi.h"
#include <dht11.h>
dht11 DHT11;
#define LED 0
const char* ssid = "ssid";
const char* password = "wifipassword";
const byte dataPin = 2;
const char* host = "api.thingspeak.com";
void setup() {
// put your setup code here, to run once:
pinMode(0,OUTPUT);
Serial.begin(115200);
WiFi.begin(ssid,password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
digitalWrite(LED,HIGH);
Serial.println("");
Serial.println("WiFi connected");
Serial.println(WiFi.localIP());
}
void loop() {
int chk = DHT11.read(dataPin);
// put your main code here, to run repeatedly:
Serial.print("Connecting to " );
Serial.println(host);
// usage WiFiClient
WiFiClient client;
const int httpPort = 80;
if (!client.connect(host, httpPort)) {
Serial.println("connection fialed");
return;
}
client.print(String("GET /") + "update?api_key=thingspeakapikey=" + String(DHT11.temperature) + "&field2=" + String(DHT11.humidity) + "\r\n\r\n");
Serial.println("溫度:"+String(DHT11.temperature)+" === "+"濕度: "+String(DHT11.humidity));
delay(100);
while (client.available()) {
String line = client.readStringUntil('\r');
Serial.print(line);
for (int i=1 ; i<12; i++) {
digitalWrite(LED,HIGH);
delay(300);
digitalWrite(LED,LOW);
delay(300);
digitalWrite(LED,HIGH);
}
}
Serial.println();
Serial.println("closing connection");
delay(300000);
}