#include #include #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" ); client.stop(); updateStart = millis(); //重設上傳時間 } } } void setup() { Serial.begin( 2400 ); WiFi.begin( SSID, PASS ); dht.begin(); starttime=millis(); //設定Sharp感測器開始的擷取時間 updateStart = millis(); //設定第一次即上傳 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); 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; } } } ``` ### 電路接線圖 完整組裝請參考盛南老師畫的電路圖 ![](http://maker.tn.edu.tw/uploads/tad_book3/image/fmCSekA.png) 接好線路後,因為ESP-01主控板並沒有連接到電腦,無法從本機序列埠得知連線狀況,只能上監測網站等看看資料是否有上傳成功了 ![](http://maker.tn.edu.tw/uploads/tad_book3/image/DSCF2345.jpg)
進階搜尋