先到thingspeak官網,之前沒註冊的話就辦一個
https://thingspeak.com/login?skipSSOCheck=true
選CHANNEL,點mychannels
點 new channel
選channel settings,照下圖新增資料欄位
好了之後拉到最下面按SAVE
點Private View ,在下面的" Field 1 Chart " ,點右邊那隻筆
因為範例會顯示出三個數值的曲線,所以先依照下圖順序設定三個視窗鎖鑰顯示的內容
接著選API KEYS,待會會用到 Write API KEY
下面是範例程式碼
//https://randomnerdtutorials.com/esp32-thingspeak-publish-arduino/
#include <WiFi.h>
#include "ThingSpeak.h"
const char* ssid = "你的熱點"; // your network SSID (name)
const char* password = "熱點密碼"; // your network password
WiFiClient client;
//輸入您的頻道號以及您的寫入 API 密鑰
unsigned long myChannelNumber = 1;
const char * myWriteAPIKey = "0ICFB705K2YI5Y69";
// Timer variables
unsigned long lastTime = 0;
unsigned long timerDelay = 15000;//極限時間,在短可能會來不及處理請求
// Variable to hold temperature readings
int randvalue1;
int randvalue2;
int randvalue3;
void setup() {
Serial.begin(115200); //Initialize serial
WiFi.mode(WIFI_STA);
ThingSpeak.begin(client); // Initialize ThingSpeak
}
void loop() {
if ((millis() - lastTime) > timerDelay) {
// Connect or reconnect to WiFi
if(WiFi.status() != WL_CONNECTED){
Serial.print("Attempting to connect");//沒連上的顯示
while(WiFi.status() != WL_CONNECTED){
WiFi.begin(ssid, password);
delay(3000);
}
Serial.println("\nConnected.");//連上的顯示
}
// Get a new temperature reading
randvalue1 = random(50);
Serial.print("randvalue1: ");
Serial.println(randvalue1);
randvalue2 = random(100);
Serial.print("randvalue2: ");
Serial.println(randvalue2);
randvalue3 = random(20);
Serial.print("randvalue3: ");
Serial.println(randvalue3);
ThingSpeak.setField(1, randvalue1);
ThingSpeak.setField(2, randvalue2);
ThingSpeak.setField(3, randvalue3);
// Write to ThingSpeak. There are up to 8 fields in a channel, allowing you to store up to 8 different
// pieces of information in a channel. Here, we write to field 1.
int x = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
//uncomment if you want to get randvalue1 in Fahrenheit
//int x = ThingSpeak.writeField(myChannelNumber, 1, randvalue1, myWriteAPIKey);
if(x == 200){
Serial.println("Channel update successful.");
}
else{
Serial.println("Problem updating channel. HTTP error code " + int(x));
}
lastTime = millis();
}
}
下圖是執行結果:
了解前面的方法之後可以嘗試下面的教學
ESP32- 以ThingSpeak為例ESP32透過HTTP POST 傳值給ThingSpeak