#include #include #include #include #define DHTPIN 1 #define DHTTYPE DHT22 DHT dht(DHTPIN, DHTTYPE,11); LiquidCrystal_I2C lcd(0x27,16,2); // Check I2C address of LCD, normally 0x27 or 0x3F //*-- IoT Information #define SSID "無線網路名稱" #define PASS "無線網路密碼" #define HOST "pm25.tn.edu.tw" #define PORT 80 String PMgps = "學校經緯度座標"; String schoolcode = "學校代碼"; int no = 0; //設備編號,可設定0~255,在監測網上可區別一校多個設備 long updateInterval = 1200000; //傳送資料時間間隔,測試完請設定1800000(30分鐘) long updateLcd = 10000; //LCD更新時間間隔 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, updateStart, updateStart2; void updateSensor( float T) { if(abs( millis() - updateStart2) > updateLcd ) { float h = dht.readHumidity(); float t = dht.readTemperature(); lcd.clear(); lcd.print("PM2.5:"); lcd.print(T,1); lcd.setCursor(11,0); lcd.print("ug/m3"); lcd.setCursor(0,1); lcd.print("T:"); lcd.print(t,1); lcd.print("'C H:"); lcd.print(h,1); lcd.print("%"); updateStart2 = millis(); } 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 ); lcd.begin(0,2); // In ESP8266-01, SDA=0, SCL=2 lcd.backlight(); dht.begin(); starttime=millis(); //設定Sharp感測器開始的擷取時間 updateStart = millis(); //設定第一次即上傳 updateStart2 = millis(); //LCD更新計時器 } void loop(){ //每24小時重開機 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; } } } ``` 預設每10秒刷新一次螢幕資訊,每20鐘上傳資料到資訊中心,修改好後上傳到ESP-01(詳細上傳方式請參閱第1章) ### 電路接線圖 線太多看起來有點複雜,不過對顏色就不會錯了,圖片忘了標示上排電源是5V,下排電源3.3V ![](http://maker.tn.edu.tw/uploads/tad_book3/image/eps01_powerboard_lcd1602i2c_pm25_dht22_bb.png)接好線路,插上變壓器,打完收工 圖示中T代表溫度,H代表溼度 ![](http://maker.tn.edu.tw/uploads/tad_book3/image/DSCF2352.jpg)
進階搜尋