Skip to content

Instantly share code, notes, and snippets.

@hocarm
Created November 16, 2019 04:51
Show Gist options
  • Save hocarm/49966aaeae453d5c4977ad808d85a532 to your computer and use it in GitHub Desktop.
Save hocarm/49966aaeae453d5c4977ad808d85a532 to your computer and use it in GitHub Desktop.
#include "ThingSpeak.h"
#include <ESP8266WiFi.h>
//---------------- Fill in your credentails ---------------------
char ssid[] = "xxx"; // your network SSID (name), tên wifi
char pass[] = "xxxxx"; // your network password, password
unsigned long myChannelNumber = 1; // Replace the 0 with your channel number, channel của bạn
const char * myWriteAPIKey = "xxxxx"; // Paste your ThingSpeak Write API Key between the quotes, write API key
//------------------------------------------------------------------
WiFiClient client;
int number = 0;
void setup() {
//Mở port với baudrate 9600
Serial.begin(9600);
while (!Serial) {
; // Chờ kết nối USB, phục vụ công tác debug
}
WiFi.mode(WIFI_STA);
ThingSpeak.begin(client);
}
void loop() {
float h = random(100);
float t = random(70);
// Connect or reconnect to WiFi
if (WiFi.status() != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
// Serial.println(SECRET_SSID);
while (WiFi.status() != WL_CONNECTED) {
WiFi.begin(ssid, pass);
Serial.print(".");
delay(5000);
}
Serial.println("\nConnected.");
}
// Ghi dữ liệu lên 1 field
// int x = ThingSpeak.writeField(myChannelNumber, 1, t, myWriteAPIKey);
// int y = ThingSpeak.writeField(myChannelNumber, 2, t, myWriteAPIKey);
// Ghi dữ liệu lên nhiều field
int x = ThingSpeak.setField(1, h); //setField(field, value)
int y = ThingSpeak.setField(2, t); //setField(field, value)
int z = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
// Kiểm tra return code
if (z == 200) {
Serial.println("Channel update successful.");
}
else {
Serial.println("Problem updating channel. HTTP error code " + String(z));
}
delay(20000); // Chờ 20s trước khi gửi dữ liệu mới
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment