#include "ESP8266WiFi.h" //匯入WiFi程式庫
#include "SSD1306.h"
#include "TridentTD_LineNotify.h" //匯入TridentTD_LineNotify程式庫
SSD1306 display(0x3C, D2, D1); //(位址,SDA,SCL)==SDA>D2,SCL>D1
#define LINE_TOKEN "ISP90uFz000000000000000000000QON4" //複製你的LINE權杖
long previousTime = 0; // 用來保存前一次狀態的時間
long interval = 500; // 讀取間隔時間,單位為毫秒(miliseconds)
float voice_value=0; //宣告一個資料型態為float的全域變數voice_value
const char *API_KEY = "XRCOLW1LYAHVABX1"; //ThingSpeak取得的apiKey,請更換為各組之apikey
const char *HOST = "api.thingspeak.com"; //定義連線至thingspeak網站的IP位址
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)就進入執行程式
int i=analogRead(A0);
voice_value=i*(3.3/1020)*50;
previousTime = currentTime; // 離開if時更新時間
send_Data(); //呼叫上傳資料函數
}
if(voice_value>90){
String temp="聲音:"+String(voice_value)+"db"; //設定temp字串
LINE.setToken(LINE_TOKEN); //設定要傳遞的權杖
LINE.notify("\n" + temp ); //發送資料至LINE
}
display.clear(); //清除螢幕
display.drawString(0, 0, "Group 1"); //x=0,y=0位置顯示Group 1
display.drawString(0, 16, "voice:"+String(voice_value)); //x=0,y=16位置顯示聲音感測器類比值
display.display();//螢幕顯示畫面
}
void connectWifi() //網路連線函數
{
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();//螢幕顯示畫面
}
}
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上傳聲音感測器分貝數據
URL += voice_value;
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");
}
}