Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#include "ThingSpeak.h"
#include <ESP8266WiFi.h>
#include <DHT.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
//------------------------------------------------------------------
#define DHTPIN D4 // Chân kết nối với DHT22
#define DHTTYPE DHT22 // Loại cảm biến là DHT22
DHT dht(DHTPIN, DHTTYPE);
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
}
Serial.println(F("DHTxx test!"));
dht.begin();
WiFi.mode(WIFI_STA);
ThingSpeak.begin(client);
}
void loop() {
// float h = random(100);
// float t = random(70);
float h = dht.readHumidity(); // Đọc độ ẩm
float t = dht.readTemperature(); //Đọc nhiệt độ
// Kiểm tra ko đọc được thì báo lỗi
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// 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);
// In dữ liệu debug
Serial.print("Temperature: ");
Serial.print(t);
Serial.print(" oC Humidity: ");
Serial.print(h);
// 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