#include "ESP8266WiFi.h" //匯入無線網路程式庫
#include "SSD1306.h" //匯入OLED程式庫
SSD1306 display(0x3C, D2, D1); //宣告使用OLED螢幕物件(位址,SDA,SCL)==SDA>D2,SCL>D1
int soil = 0; //定義要儲存土壤濕度的變數soil
long previousTime = 0; //用來保存前一次狀態的時間
long interval = 2000; //讀取間隔時間,單位為毫秒(miliseconds)
const char *API_KEY = "3HP49CL176OSQ9AC"; //ThingSpeak取得的apiKey,請更換為各組之apikey
const char *HOST = "api.thingspeak.com"; //定義連線至thingspeak網站
const char* MY_SSID = "TCGS-IOT"; //無線基地台SSID名稱
const char* MY_PWD = "22205108"; //無線基地台密碼
void setup()
{
display.init(); //螢幕初始化
display.flipScreenVertically(); //螢幕垂直翻轉
display.setFont(ArialMT_Plain_16); //16字體
display.setTextAlignment(TEXT_ALIGN_LEFT); //置左對齊
connectWifi(); //呼叫網路連線函數
}
void loop()
{
unsigned long currentTime = millis(); //將當前的時間存入變數currentTime
if(currentTime - previousTime > interval) { //如果當前時間扣除前一次保留時間超過間隔時間(interval)就進入執行程式
soil = map(analogRead(A0),885,691,0,100); //map(value, fromLow, fromHigh, toLow, toHigh)
previousTime = currentTime; //離開if時更新時間
send_Data(); //呼叫上傳資料函數
}
display.clear(); //清除螢幕
display.drawString(0, 0, "Group 1"); //x=0,y=0位置顯示組別名稱,請更換為教學模組編號
display.drawString(0, 16, "Soil:"+String(soil)+"%"); //x=0,y=16位置顯示土壤濕度
display.display();//螢幕顯示畫面
}
//網路連線函數
void connectWifi()
{
Serial.print("Connecting to "+*MY_SSID);
WiFi.begin(MY_SSID, MY_PWD); //連線至MY_SSID無線基地台,MY_PWD為連線密碼
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
display.clear(); //清除螢幕
display.drawString(0, 0, "connect Wifi..."); //將connect Wifi...字串放入暫存區
display.display(); //螢幕顯示畫面
}
}
//傳送資料至ThingSpeak網站
void send_Data()
{
WiFiClient client; // 設定 ESP8266 作為 Client 端
if ( !client.connect( HOST, 80 ) ) {
Serial.println("connection failed");
return;
} else {
String URL = "GET /update?key="; // 以GET方式上傳資料到 ThingSpeak伺服器
URL += API_KEY;
URL += "&field1="; //field1上傳PM2.5數據
URL += soil;
URL += " HTTP/1.1\n";
client.print( URL + "Host: " + HOST + "\r\n" +
"Connection: close\r\n\r\n" );
delay(10); // 等待一下下
// 接收ThingSpeak伺服器的回應
unsigned long timeout = millis();
while (client.available() == 0) {
if (millis() - timeout > 5000) {
Serial.println(">>> Client Timeout !");
client.stop();
return;
}
}
// Read all the lines of the reply from server and print them to Serial
// while(client.available()){
String line = client.readStringUntil('\r');
Serial.print(line);
// }
Serial.println();
Serial.println("closing connection");
}
}