โพสต์นี้ ผมทำเพิ่มมาอีก 1 Proj. คือการตรวจวัดฝุ่น PM 2.5 ครับ รูปแบบก็ไม่ยากมากมาย ขอเก็บไว้ที่นี่ครับ สิ่งที่เพิ่มเติมมาคือ ใน App Blynk คือ แท่งแสดงระดับซ้าย ขวา จะเปลี่ยนสี ไป ตามค่ามาตรฐาน ครับ เช่น ถ้าวัดค่า PM2.5 ได้อยู่ในช่วง 0-25 แท่งจะเป็นสีฟ้า หรือ ค่า PM2.5 ได้อยู่ในช่วง 26-50 แท่งจะเป็นสีเขียว, สีเหลือง สีส้ม, สีแดง ตามลำดับ มีปุ่มปิด เปิดเครื่อง ในกรณีที่ต้องการดูค่าวัดตามช่วงที่เราต้องการ โดยไม่เปิดเครื่องทั้งวัน หรือจะเปิดเครื่องทั้งวันก็ได้ ตามต้องการครับ อีกส่วนหนึ่งคือการส่งข้อมมูลไปแสดงที่ thingspeak
URL ของผมครับ ดูตัวอย่างได้ นายอิทธิรงค์ ทองย้อย - ThingSpeak IoT
Code
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h>
#include <FS.h>
#include <DNSServer.h>
#include <ArduinoJson.h>
#define BLYNK_MAX_SENDBYTES 1200
#include <BlynkSimpleEsp8266.h>
//------------------------------ การกำหนดค่าในส่วนของ Blynk ------------------------------------------------//
#define BLYNK_DEBUG
#define BLYNK_PRINT Serial
int blynkIsDownCount = 0;
char blynk_token[34] = "P1jrAF48xwP82xcloZny6h33-y6xbtrv";//ใส่ Blynk_token ของเราที่ Blynk ส่งมาทาง Email ตอน Create Project ใหม่//ของจริง
BlynkTimer timer;
//---------------------------------- กำหนดหมายเลขของขาของ Node MCU ESP 8266 --------------------------------------------//
#define D0 16 // ใช้ไฟ LED สีฟ้า ของบอร์ด MCU ESP8266 ให้มีสัญญาณไฟกระพริบ ตาม Code ที่เขียน
#define D3 0 // ใช้เป็นปุ่มกด เพื่อเข้า AP Config ได้ตามความต้องการของผู้ใช้
#define D5 14
//------------------------------------------------------------------------------------------------------------------------//
#include <Scheduler.h>
bool shouldSaveConfig = false;
//callback notifying us of the need to save config
void saveConfigCallback () {
Serial.println("Should save config");
shouldSaveConfig = true;
}
//------------------------------------------------------------------------------------------------------------------------//
//-------------สำหรับ Server local ที่แจกให้ เพิ่ม **** แค่ 2 บรรทัดนี้-------------- (ถ้าเป็น Blynk Server ปกติไม่ต้องใส่) ----------//
char server[] = "oasiskit.com";
int port = 8080;
//------------------------------------------------------------------------------------------------------------------------//
unsigned int pm1 = 0;
unsigned int pm2_5 = 0;
unsigned int pm10 = 0;
#include <SoftwareSerial.h>
SoftwareSerial mySerial(D7, D6); // RX, TX
//PM 2.5
WidgetLED led_10(V10);//ฟ้า
WidgetLED led_11(V11);//เขียว
WidgetLED led_12(V12);//เหลือง
WidgetLED led_13(V13);//ส้ม
WidgetLED led_14(V14);//แดง
WidgetLED led_15(V15);//M/C ON OFF
int ThingSpeakloop;
BLYNK_WRITE(V9)
{
int pinValue = param.asInt();
if (pinValue == 1 ) {
led_15.off();
ThingSpeakloop = 0;
}
if (pinValue == 0 ) {
led_15.on();
ThingSpeakloop = 1;
}
}
//การเชื่อมต่อ Blynk Server
class Task_1 : public Task {
protected:
void setup() { }
void loop() {
if (ThingSpeakloop == 1) {
digitalWrite(D5, 1);
}
if (ThingSpeakloop == 0) {
digitalWrite(D5, 0);
}
//-----------------------------------------------------------------------------------------------------------//
if (Blynk.connected())
{
Blynk.run();
digitalWrite(D0, LOW);
} else {
digitalWrite(D0, LOW);
delay(200);
digitalWrite(D0, HIGH);
delay(200);
}
//-----------------------------------------------------------------------------------------------------------//
timer.run();//ให้เวลาของ Blynk ทำงาน
delay(300);
}
} Task_1_task;
// DUST Check
class Task_2 : public Task {
protected:
void setup() { }
void loop() {
int index = 0;
char value;
char previousValue;
while (mySerial.available()) {
value = mySerial.read();
if ((index == 0 && value != 0x42) || (index == 1 && value != 0x4d)) {
Blynk.virtualWrite(V1, "\xF0\x9F\x98\xB1");
break;
}
if (index == 4 || index == 6 || index == 8 || index == 10 || index == 12 || index == 14) {
previousValue = value;
}
else if (index == 5) {
pm1 = 256 * previousValue + value;
}
else if (index == 7) {
pm2_5 = 256 * previousValue + value;
Blynk.virtualWrite(V1, pm2_5);
Blynk.virtualWrite(V3, pm2_5);
}
else if (index == 9) {
pm10 = 256 * previousValue + value;
;
} else if (index > 15) {
break;
}
index++;
}
while (mySerial.available()) mySerial.read();
//แสดง สี LED ใน Blynk PM2.5
if (pm2_5 >= 0 && pm2_5 <= 25)
{
led_10.on();
led_11.off();
led_12.off();
led_13.off();
led_14.off();
Blynk.setProperty(V3, "color", "#3bccff");
}
if (pm2_5 >= 26 && pm2_5 <= 50)
{
led_10.off();
led_11.on();
led_12.off();
led_13.off();
led_14.off();
Blynk.setProperty(V3, "color", "#92d050");
}
if (pm2_5 >= 51 && pm2_5 <= 100)
{
led_10.off();
led_11.off();
led_12.on();
led_13.off();
led_14.off();
Blynk.setProperty(V3, "color", "#ffff00");
}
if (pm2_5 >= 101 && pm2_5 <= 200)
{
led_10.off();
led_11.off();
led_12.off();
led_13.on();
led_14.off();
Blynk.setProperty(V3, "color", "#ffa200");
}
if (pm2_5 >= 201)
{
led_10.off();
led_11.off();
led_12.off();
led_13.off();
led_14.on();
Blynk.setProperty(V3, "color", "#ff3b3b");
}
//-------------------------------------------------------------------------
if (ThingSpeakloop == 1) {
ThingSpeak();
}
if (ThingSpeakloop == 0) {
ThingSpeak0();
}
delay(2000);
}//loop
} Task_2_task;
//------------------------------------------------------------------------------------------------------------------------//
//********************************************* void setup **************************************************//
//------------------------------------------------------------------------------------------------------------------------//
void setup() {
//-------IO NODE MCU Esp8266-------//
pinMode(D0, OUTPUT); //กำหนดโหมดใช้งานให้กับขา D0 เป็นขา สัญญาณไฟ ในสภาวะต่างๆ
pinMode(D3, INPUT_PULLUP);//กำหนดโหมดใช้งานให้กับขา D3 เป็นขา กดปุ่ม ค้าง เพื่อตั้งค่า AP config
pinMode(D5, OUTPUT);
// ให้ LED ทั้งหมดดับก่อน
digitalWrite(D0, LOW);//ให้หลอด LED สีฟ้าดับก่อน
digitalWrite(D5, 0);//Relay High Active
//-------------------------------//
Serial.begin(115200);
while (!Serial) ;
mySerial.begin(9600);
//-------------------------------//
//read configuration from FS json
Serial.println("mounting FS...");//แสดงข้อความใน Serial Monitor
if (SPIFFS.begin()) {
Serial.println("mounted file system");//แสดงข้อความใน Serial Monitor
if (SPIFFS.exists("/config.json")) {
//file exists, reading and loading
Serial.println("reading config file");//แสดงข้อความใน Serial Monitor
File configFile = SPIFFS.open("/config.json", "r");
if (configFile) {
Serial.println("opened config file");
size_t size = configFile.size();
// Allocate a buffer to store contents of the file.
std::unique_ptr<char[]> buf(new char[size]);
configFile.readBytes(buf.get(), size);
DynamicJsonBuffer jsonBuffer;
JsonObject& json = jsonBuffer.parseObject(buf.get());
json.printTo(Serial);
if (json.success()) {
Serial.println("\nparsed json");//แสดงข้อความใน Serial Monitor
strcpy(blynk_token, json["blynk_token"]);
} else {
Serial.println("failed to load json config");//แสดงข้อความใน Serial Monitor
}
}
}
} else {
Serial.println("failed to mount FS");//แสดงข้อความใน Serial Monitor
}
//end read
//************************** AP AUTO CONNECT ********************************************//
WiFiManagerParameter custom_blynk_token("blynk", "blynk token", blynk_token, 34);
//WiFiManager
//Local intialization. Once its business is done, there is no need to keep it around
WiFiManager wifiManager;
//set config save notify callback
wifiManager.setSaveConfigCallback(saveConfigCallback);
wifiManager.addParameter(&custom_blynk_token);
for (int i = 5; i > -1; i--) { // นับเวลาถอยหลัง 5 วินาทีก่อนกดปุ่ม AP Config
digitalWrite(D0, HIGH);
delay(500);
digitalWrite(D0, LOW);
delay(500);
Serial.print (String(i) + " ");//แสดงข้อความใน Serial Monitor
}
if (digitalRead(D3) == LOW) {
digitalWrite(D0, LOW);
Serial.println("Button Pressed");//แสดงข้อความใน Serial Monitor
wifiManager.resetSettings();//ให้ล้างค่า SSID และ Password ที่เคยบันทึกไว้
// wifiManager.autoConnect(); ใช้สร้างชื่อแอคเซสพอยต์อันโนมัติจาก ESP + ChipID
if (!wifiManager.autoConnect("PUYIOT AP CONFIG")) {
Serial.println("failed to connect and hit timeout");//แสดงข้อความใน Serial Monitor
delay(3000);
//reset and try again, or maybe put it to deep sleep
ESP.reset();
delay(5000);
}
}
Serial.println("Connected.......OK!)");//แสดงข้อความใน Serial Monitor
strcpy(blynk_token, custom_blynk_token.getValue());
//save the custom parameters to FS
if (shouldSaveConfig) {
Serial.println("saving config");//แสดงข้อความใน Serial Monitor
DynamicJsonBuffer jsonBuffer;
JsonObject& json = jsonBuffer.createObject();
json["blynk_token"] = blynk_token;
File configFile = SPIFFS.open("/config.json", "w");
if (!configFile) {
Serial.println("failed to open config file for writing");//แสดงข้อความใน Serial Monitor
}
json.printTo(Serial);
json.printTo(configFile);
configFile.close();
//end save
}
//************************** จบ AP AUTO CONNECT *****************************************//
Serial.println("local ip"); //แสดงข้อความใน Serial Monitor
delay(100);
Serial.println(WiFi.localIP());//แสดงข้อความใน Serial Monitor
Serial.println("gateway");
delay(100);
Serial.println(WiFi.gatewayIP());
Serial.println("subnetMask");
delay(100);
Serial.println(WiFi.subnetMask());
Serial.println("SSID");
delay(100);
Serial.println(WiFi.SSID());
Serial.println("Password");
delay(100);
Serial.println(WiFi.psk());
// Blynk.config(blynk_token);////เริ่มการเชื่อมต่อ Blynk Server แบบปกติ
Blynk.config(blynk_token, server, port);
////เริ่มการเชื่อมต่อ Blynk Server*********สำหรับ Server local ที่แจกให้ เพิ่ม, server, port แค่นี้จบ
timer.setInterval(30000L, reconnecting); //Function reconnect
Scheduler.start(&Task_1_task);
Scheduler.start(&Task_2_task);
Scheduler.begin();
}
//------------------------------------------------------------------------------------------------------------------------//
//********************************************* จบ void setup **************************************************//
//------------------------------------------------------------------------------------------------------------------------//
//------------------------------------------------------------------------------------------------------------------------//
//********************************************* void Loop ***************************************************//
//------------------------------------------------------------------------------------------------------------------------//
void loop() {
}
//------------------------------------------------------------------------------------------------------------------------//
//********************************************* จบ void Loop **************************************************//
//------------------------------------------------------------------------------------------------------------------------//
//------------------------------------------------------------------------------------------------------------------------//
void reconnecting()
{
if (!Blynk.connected())
{
blynkIsDownCount++;
BLYNK_LOG("blynk server is down! %d times", blynkIsDownCount);
Blynk.connect(5000);
}
}
void ThingSpeak()
{
// ThingSpeak Settings //
char thingSpeakAddress[] = "api.thingspeak.com";
String writeAPIKey = "O02LH10111PD05ONZ3"; // คีย์จากเมนู key Api แบบ Write API Key
WiFiClient client;
String PM_2_5 = (String) pm2_5;// แปลงเป็น string ให้หมด ThingSpeak
String data = "field5=" + PM_2_5 ; // แปลงเป็น string ให้หมด
if (client.connect(thingSpeakAddress, 80)) {
client.print("POST /update HTTP/1.1\n");
client.print("Host: api.thingspeak.com\n");
client.print("Connection: close\n");
client.print("X-THINGSPEAKAPIKEY: " + writeAPIKey + "\n");
client.print("Content-Type: application/x-www-form-urlencoded\n");
client.print("Content-Length: ");
client.print(data.length());
client.print("\n\n");
client.print(data); //
}
digitalWrite(D5, 1);
//Serial.println("ThingSpeakloop");
delay(3000);
}
void ThingSpeak0()
{
// ThingSpeak Settings //
char thingSpeakAddress[] = "api.thingspeak.com";
String writeAPIKey = "O02LH10111PD05ONZ3"; // คีย์จากเมนู key Api แบบ Write API Key
WiFiClient client;
String dataoff = "0";// แปลงเป็น string ให้หมด ThingSpeak
String data = "field5=" + dataoff ; // แปลงเป็น string ให้หมด
if (client.connect(thingSpeakAddress, 80)) {
client.print("POST /update HTTP/1.1\n");
client.print("Host: api.thingspeak.com\n");
client.print("Connection: close\n");
client.print("X-THINGSPEAKAPIKEY: " + writeAPIKey + "\n");
client.print("Content-Type: application/x-www-form-urlencoded\n");
client.print("Content-Length: ");
client.print(data.length());
client.print("\n\n");
client.print(data); //
}
digitalWrite(D5, 0);
//Serial.println("ThingSpeakloop");
delay(3000);
}
BLYNK_CONNECTED()
{
Blynk.setProperty(V10, "color", "#3bccff");
Blynk.setProperty(V11, "color", "#92d050");
Blynk.setProperty(V12, "color", "#ffff00");
Blynk.setProperty(V13, "color", "#ffa200");
Blynk.setProperty(V14, "color", "#ff3b3b");
Blynk.syncAll();//ให้ซิงค์ข้อมูลทั้งหมดล่าสุดจาก Blynk Server
}
*** ข้อสำคัญ ใครเอา ProJ ผมไปลองกรุณาเปลี่ยน Blynk/ Line Token เป็นของตนเองด้วยนะครับ