#include <DHT.h>
#include <ESP8266WiFi.h>
#define Buzzer 2 //接蜂鳴器
#define DHTPIN 0 //接DHT22
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE,11);
//*-- IoT Information
#define SSID "修改無線網路名稱" //無線網路名稱
#define PASS "修改無線網路密碼" //無線網路密碼
#define HOST "pm25.tn.edu.tw" //PM2.5網站網址
#define PORT 80
String PMgps = "修改學校經緯度座標"; //學校經緯度座標
String schoolcode = "修改學校代碼"; //學校代碼
int no = 0; //設備編號,可設定0~255,在監測網上可區別一校多個設備
long updateInterval = 1200000; //傳送資料時間間隔,測試完請設定1800000(30分鐘)
long resettime =86400000; //每24小時自動重開機
//sharp GP2Y1051 二代 start
int incomeByte[7];
int data;
int z=0;
int sum, count;
float average_pm2d5,sum_2s;
unsigned long error, starttime, buzzerStart, updateStart;
void updateSensor( float T)
{
if(T>=200) {
digitalWrite(Buzzer,HIGH);
buzzerStart=millis(); //設定Buzzer告警開始時間
}
if(abs(millis()-buzzerStart)>2000){
digitalWrite(Buzzer,LOW);
}
if(abs( millis() - updateStart) > updateInterval | updateStart == 0 ){
float h = dht.readHumidity();
float t = dht.readTemperature();
WiFiClient client;
if( !client.connect( HOST, PORT ) )
{
return;
}
else
{
String getStr = "GET /xoops/api.php?schoolcode=" + schoolcode + "&no=" + no + "&pm25=" + T + "&t=" + t + "&h=" + h +"&gps=" + PMgps + " HTTP/1.1\r\n";
client.print( getStr );
client.print( "Host: pm25.tn.edu.tw\n" );
client.print( "Connection: close\r\n\r\n" );
delay(2000);
client.stop();
updateStart = millis(); //重設上傳時間
}
}
}
void setup()
{
Serial.begin( 2400 );
Serial.println( SSID );
WiFi.begin( SSID, PASS );
dht.begin();
starttime=millis(); //設定Sharp感測器開始的擷取時間
updateStart = millis(); //設定第一次即上傳
delay(2000);
pinMode(Buzzer,OUTPUT);
}
void loop(){
if(starttime >= resettime) {
ESP.restart();
}
while (Serial.available()>0){
data=Serial.read();
if(data == 170){
z=0;
incomeByte[z]=data;
}
else{
z++;
incomeByte[z]=data;
}
if(z==6)
{
sum=incomeByte[1]+ incomeByte[2]+ incomeByte[3] + incomeByte[4];
if(incomeByte[5]==sum && incomeByte[6]==255 )
{
float vo=(incomeByte[1]*256.0+incomeByte[2])/1024.0*5.00;
float pm = vo*700;
sum_2s=sum_2s + pm;
count++;
if(abs(millis()-starttime)>2000){
average_pm2d5=(sum_2s/count)*1.00;
updateSensor(average_pm2d5);
Serial.print("PM2.5_Average = ");
Serial.println(average_pm2d5,2);
starttime=millis();
sum_2s=0;
count=0;
}
}
else{
z=0;
Serial.flush();
data='/0';
for(int m=0;m<7;m++){
incomeByte[m]=0;
}
}
z=0;
}
}
}