#include <WiFi.h>
#include <PubSubClient.h>
#include <DHT.h>
// ThingSpeak channel and API key
const char* channel_id = "2386058";
const char* write_api_key = "N4TG1ZJPUP6WAQKK";
// DHT Sensor setup
#define DHTPIN 14 // The GPIO pin connected to the DHT sensor
#define DHTTYPE DHT22 // The type of DHT sensor
DHT dht(DHTPIN, DHTTYPE);
// WiFi credentials
const char* ssid = "Wokwi-GUEST"; // The SSID of the WiFi network
const char* password = ""; // WiFi password
// MQTT server details
const char* mqtt_server = "mqtt3.thingspeak.com"; // The MQTT server address
const int mqtt_port = 1883; // MQTT server port
const char* mqtt_client_id = "IRYhDzcdIyofNCILITQAGzI"; // MQTT client ID
const char* mqtt_username = "IRYhDzcdIyofNCILITQAGzI"; // MQTT username
const char* mqtt_password = "5b1PT/XYjBAbyEtbZEew2oPb"; // MQTT password
WiFiClient espClient;
PubSubClient mqtt_client(espClient);
void setup() {
Serial.begin(115200); // Start serial communication at 115200 baud
dht.begin(); // Initialize the DHT sensor
connectToWiFi(); // Connect to WiFi network
mqtt_client.setServer(mqtt_server, mqtt_port); // Setup MQTT connection
}
void loop() {
// Ensure MQTT connection is maintained
if (!mqtt_client.connected()) {
reconnectMQTT();
}
mqtt_client.loop();
// Read and publish sensor data every 2 seconds
static unsigned long lastPublishTime = 0;
if (millis() - lastPublishTime > 2000) {
lastPublishTime = millis();
readAndPublishSensorData();
}
}
void connectToWiFi() {
Serial.print("Connecting to Wi-Fi");
WiFi.begin(ssid, password);
// Wait until connected to WiFi
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println(" Connected!");
}
void reconnectMQTT() {
// Reconnect to MQTT server if disconnected
while (!mqtt_client.connected()) {
Serial.print("Attempting MQTT connection...");
if (mqtt_client.connect(mqtt_client_id, mqtt_username, mqtt_password)) {
Serial.println("connected");
} else {
Serial.print("failed, rc=");
Serial.print(mqtt_client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void readAndPublishSensorData() {
// Read humidity and temperature from DHT sensor
float humidity = dht.readHumidity();
float tempC = dht.readTemperature();
// Check if any readings failed and exit early (to try again).
if (isnan(humidity) || isnan(tempC)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Print the humidity and temperature values to the serial monitor
Serial.printf("Humidity: %.1f%% Temperature: %.1f°C\n", humidity, tempC);
// Prepare data string for ThingSpeak
String data = String("field1=") + String(tempC, 1) +
"&field2=" + String(humidity, 1);
char dataChar[100];
data.toCharArray(dataChar, 100);
// Publish the data to ThingSpeak
if (mqtt_client.publish("channels/2386058/publish", dataChar)) {
Serial.println("Publish successful");
} else {
Serial.println("Publish failed");
}
}