智慧物聯 — 空氣品質檢測

實作目標

我們將建置一個空氣品質監測站, 透過一個 MQ-135 氣體感測器, 定時將檢測到空氣品質數據上傳至雲端物聯網數據平台上 (這裡我用的是資策會服創所的雲端數據服務平台 IDEAS Chain 來演示, 當然你也可以使用其他服務平台, 或自己架一個也行)。 當檢測到空氣品質出現異常數據時, 例如二氧化碳濃度值過高時, 就能自動送出即時訊息通知使用者 (這裡我用以一個 LED 來演示, 當數據異常時 LED 亮, 正常時則滅)。

MQ-135 空氣品質檢測感測器模組

實體接線圖

範例程式碼

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

WiFiClient client;
HTTPClient http;

#define AP_ID "Your AP SSID"
#define AP_PWD "Your AP password"
const String access_token = "Your Device Access Token";

int value_sensor = 0;
int value_led = 0;

void connectWiFi() {
WiFi.begin(AP_ID, AP_PWD);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
}
Serial.println("");
Serial.print("WiFi ");
Serial.print(AP_ID);
Serial.println ("connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}

void post(String device_key, String data){
Serial.print("[HTTP] begin...\n");
http.begin(client, "http://iiot.ideaschain.com.tw/api/v1/"+device_key+"/telemetry"); //Specify destination device by its access token
http.addHeader("Content-Type", "application/json");
Serial.print("[HTTP] POST...\n");
int httpCode = http.POST(data);
if (httpCode > 0) {
Serial.printf("[HTTP] POST... code: %d\n", httpCode);
if (httpCode == HTTP_CODE_OK) {
const String& payload = http.getString();
Serial.println("received payload:\n<<");
Serial.println(payload);
Serial.println(">>");
}
}
else {
Serial.printf("[HTTP] POST... failed, error: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
}

void setup() {
pinMode(LED_BUILTIN, OUTPUT)
Serial.begin(115200);
delay(10);
while (!Serial) { ; }
connectWiFi();
}

void loop(){
value_sensor = analogRead(0);
value_led = (value_sensor >= 700) ? 0:1 ;
digitalWrite(LED_BUILTIN, value_led);
Serial.println();
Serial.println("Sensor Value:"+String(value_sensor)+", LED:"+String(value_led));
String data = "{\"sensor\":"+String(value_sensor)+"\", led\":"+String(value_led)+"}";
post(access_token, data);
delay(5000);

量測結果

在 IDEAS Chain 雲端物聯網數據平台上, 你可即時看到剛剛上傳的資料與圖表, 範例如下:

--

--

Maker & Freelancer

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store