#include <SoftwareSerial.h>
#include <DHT.h>
// Pin definitions
#define RX 0
#define TX 1
const int dhtPin = 2; // DHT sensor pin (digital pin 2)
String AP = "Wokwi-GUEST"; // SSID
String PASS = ""; // WiFi Password
// Sensor variables
float temperature = 0.0;
float humidity = 0.0;
DHT dht(dhtPin, DHT11);
SoftwareSerial esp8266(RX, TX);
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
esp8266.begin(115200);
dht.begin();
// Connect to WiFi
sendCommand("AT", 5, "OK");
sendCommand("AT+CWMODE=1", 5, "OK");
sendCommand("AT+CWJAP=\"" + AP + "\",\"" + PASS + "\"", 20, "OK");
}
void loop() {
// put your main code here, to run repeatedly:
// humidity = readHumidity();
// delay(1000);
}
// Function to read temperature
float readTemperature() {
float temp = dht.readTemperature();
Serial.println("Temperature: " + String(temp) + " °C");
return isnan(temp) ? 0.0 : temp;
}
// Function to read humidity
float readHumidity() {
float hum = dht.readHumidity();
Serial.println("Humidity: " + String(hum) + "%");
return isnan(hum) ? 0.0 : hum;
}
// Function to send an AT command to the ESP8266 module
void sendCommand(String command, int maxTime, char* readReplay) {
Serial.print("Sending command: ");
Serial.println(command);
boolean found = false;
int countTimeCommand = 0;
while (countTimeCommand < maxTime) {
esp8266.println(command);
if (esp8266.find(readReplay)) {
found = true;
break;
}
countTimeCommand++;
delay(100); // Add a delay to avoid flooding the module
}
if (found) {
Serial.println("Command successful");
} else {
Serial.println("Command failed");
}
}Loading
esp-01
esp-01