BMP280+ThingSpeak loT

 BMP280+ThingSpeak IoT

ESP32真的是個方便又神奇的版子,3個月前我還在猶豫要不要跨足
研究ESP32,帶著一份不安的心,買了一些書開始學,至今約三個月
,覺得之前有玩Arduino因為語言相通,省去了一些時間,只是比較
略顯不足的是esp32沒有5V倒是有點可惜,另外我覺得優勢是內建WIFI
和藍芽,不用又外接,並且也支援mpython,這讓我無形中不會因為只
玩esp32用了C語言,而忘了Python。
今天呢就心血來潮想玩一下云端數據圖形化,之前看了很多網上大神們
都有提及ThingSpeak這個和感測器結合一起用,昨天剛研究了BMP280剛好
可以派上用場。

這裡就直接接結合WIFI和ThingSpeak IoT的使用


以下因節省時間,引用別的作者的文章,出處https://randomnerdtutorials.com/esp32-thingspeak-publish-arduino/
轉到 ThingSpeak,然後單擊“免費入門”按鈕創建一個新帳戶。此帳戶與 Mathworks 帳戶相關聯。因此,如果您已有 Mathworks 帳戶,則應使用該帳戶登錄。

創建新頻道
帳戶準備好後,登錄,打開“頻道”標籤並選擇“我的頻道”。

按“新頻道”按鈕創建一個新頻道。



為您的頻道輸入名稱並添加說明。

可以自定義圖表,轉到您的私人視圖選項卡,然後單擊編輯圖標。





完成後,按“保存”按鈕。
要將值從 ESP32 發送到 ThingSpeak,您需要寫入 API 密鑰。打開“API 密鑰”
選項卡並將寫入 API 密鑰複製到一個安全的地方,因為您稍後會需要它。






安裝 ThingSpeak 庫
要將傳感器讀數發送到 ThingSpeak,我們將使用 thingspeak-arduino 庫。您可以通過 Arduino 庫管理器安裝此庫。轉到 Sketch Include Library Manage Libraries... 並在 Library Manager 中搜索“ThingSpeak”。安裝 MathWorks 的 ThingSpeak 庫。



程式碼

#include <WiFi.h>
#include <Wire.h>
#include <SPI.h>
#include <Adafruit_BMP280.h>
#include <ThingSpeak.h>

const char* ssid="CTK";
const char* password="ctk674011";
const char* APIKey="X0V369ZQ4VM9YGA8";

WiFiClient client;

Adafruit_BMP280 bmp; // I2C

unsigned long lastTime=0;
unsigned long currenTime=millis();

void setup() {
  Serial.begin(115200);
  
  if (!bmp.begin()) {
    Serial.println(F("Could not find a valid BMP280 sensor, check wiring or "
                      "try a different address!"));
    while (1delay(10);
  }
  WiFi.mode(WIFI_STA);
  ThingSpeak.begin(client);

  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED){
    Serial.print(".");
  }
  Serial.println("Connected successful!");
}

void loop() {
  float temp=bmp.readTemperature();
  int x=ThingSpeak.writeField(11, temp, APIKey);
  if (x==200){
    Serial.println("request successful!");
  }
}

解析

匯入所須的模組
#include <WiFi.h>
#include <Wire.h>
#include <SPI.h>
#include <Adafruit_BMP280.h>
#include <ThingSpeak.h>

WIFI和API的KEY
const char* ssid="基地台名稱";
const char* password="基地台密碼";
const char* APIKey="X0V36---------";

WIFI的客戶端
WiFiClient client;


BMP280指定對象
Adafruit_BMP280 bmp; // I2C

BMP280初始化
if (!bmp.begin()) {
    Serial.println(F("Could not find a valid BMP280 sensor, check wiring or "
                      "try a different address!"));
    while (1) delay(10);
  }

WIFI連線設定與設定成STA模式
WiFi.mode(WIFI_STA);

WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED){
    Serial.print(".");
  }
  Serial.println("Connected successful!");
}

ThingSpeak初始化
ThingSpeak.begin(client);

loop()裡面
讀取溫度和上傳數至到ThingSpeak
如果成功發布讀數,此函數將返回代碼 200。
// 寫入 ThingSpeak。一個通道最多有 8 個字段,最多可以存儲 8 個不同的字段。
// 通道中的信息片段。在這裡,我們寫入字段 1。
//ThingSpeak.writeField(11, temp, APIKey)第一個1代表頻道,第二個1代表字段

float temp=bmp.readTemperature();
  int x=ThingSpeak.writeField(1, 1, temp, APIKey);
  if (x==200){
    Serial.println("request successful!");
  }































留言

這個網誌中的熱門文章