Difficulty Level: Intermediate
This project demonstrates how to send sensor data to a web server using an ESP8266, and display the data on a web page. It's ideal for IoT projects that require remote monitoring of environmental conditions.
Follow these steps to connect the components:
The ESP8266 collects temperature and humidity data from the DHT sensor and sends it to a web server. The web server receives the data and displays it on a browser in real-time.
ESP8266WiFi.h
: For Wi-Fi connectivity on the ESP8266.DHT.h
: For interfacing with the DHT11/DHT22 sensor.WiFi.begin()
: Connects the ESP8266 to a Wi-Fi network using SSID and password.client.connect()
: Establishes a TCP connection with the web server.client.print()
: Sends data (sensor readings) to the web server.dht.readTemperature()
and dht.readHumidity()
: Reads temperature and humidity data from the DHT sensor.Below is the code to send sensor data to the web server:
#include
#include
#define DHTPIN 2 // Pin where the DHT sensor is connected
#define DHTTYPE DHT11 // DHT 11 or DHT22
DHT dht(DHTPIN, DHTTYPE);
// Replace with your network credentials
const char* ssid = "Your_SSID";
const char* password = "Your_PASSWORD";
// Replace with your server address
const char* server = "your_server_ip"; // Could also be a domain like "example.com"
WiFiClient client;
void setup() {
Serial.begin(115200);
dht.begin();
// Connect to Wi-Fi network
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
}
void loop() {
float temp = dht.readTemperature();
float hum = dht.readHumidity();
if (isnan(temp) || isnan(hum)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// If connected to WiFi, send data to the server
if (client.connect(server, 80)) {
Serial.println("Connected to server");
String postStr = "temp=" + String(temp) + "&hum=" + String(hum);
client.println("POST /post-data HTTP/1.1");
client.println("Host: " + String(server));
client.println("Content-Type: application/x-www-form-urlencoded");
client.print("Content-Length: ");
client.println(postStr.length());
client.println();
client.println(postStr);
client.stop();
Serial.println("Data sent to server");
} else {
Serial.println("Connection to server failed");
}
delay(10000); // Wait for 10 seconds before sending the next data
}
The following PHP code will receive the data sent by the ESP8266 and display it on a web page:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$temp = $_POST['temp'];
$hum = $_POST['hum'];
echo "Temperature: " . $temp . " ℃<br>";
echo "Humidity: " . $hum . " %<br>";
} else {
echo "No data received!";
}
?>
This project demonstrates how to send sensor data (temperature and humidity) from an ESP8266 to a web server and display the data on a web page. This can be used to build a remote monitoring system for various applications.