Webserver sensordata with esp8266
Send Sensor Data to a Web Server via ESP8266

Send Sensor Data to a Web Server via ESP8266

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.

Project Overview

In this project, we will:

  • Use an ESP8266 to read temperature and humidity from a DHT11 sensor.
  • Send the data to a web server using HTTP POST requests.
  • Process the received data on the server using PHP.
  • Display real-time data on a web page using JavaScript and Chart.js.

PureVPN – 84% Off for a Limited Time!

As seen in Forbes, PCMag & TechRadar

High-Speed VPN for Streaming & Security 6,500+ Servers in 78+ Countries Unblocks Netflix, Hulu, BBC iPlayer & More

– 84% OFF + 5 Extra Months FREE!

🔗 Claim Your 84% Discount Now!

Components Required

  • 1 x ESP8266 (ESP-01 or NodeMCU)
  • 1 x DHT11 or DHT22 Temperature and Humidity Sensor
  • 1 x 10kΩ pull-up resistor
  • Jumper wires
  • Breadboard

Setting Up the ESP8266

Before uploading the code, ensure that your ESP8266 is set up correctly:

  1. Install the ESP8266 Board Manager in Arduino IDE.
  2. Install the required libraries: ESP8266WiFi and DHT.
  3. Check that your ESP8266 firmware is updated.
  4. Configure the Arduino IDE to use the correct board and COM port.

Wiring Diagram

For the DHT Sensor

  • Connect the VCC pin of the DHT sensor to the 3.3V pin on the ESP8266.
  • Connect the GND pin of the DHT sensor to the GND pin on the ESP8266.
  • Connect the DATA pin to GPIO2 (D4 on NodeMCU) on the ESP8266.
Exclusive Prime Email Offer

Arduino Code

Below is the optimized Arduino code to send sensor data to the web server:


#include 
#include 
#include 

#define DHTPIN 2  // Pin where the DHT sensor is connected
#define DHTTYPE DHT11  // DHT 11 or DHT22

DHT dht(DHTPIN, DHTTYPE);

const char* ssid = "Your_SSID";
const char* password = "Your_PASSWORD";
const char* server = "your_server_ip";

WiFiClient client;

void setup() {
  Serial.begin(115200);
  dht.begin();
  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 (client.connect(server, 80)) {
    Serial.println("Connected to server");

    StaticJsonDocument<200> jsonDoc;
    jsonDoc["temp"] = temp;
    jsonDoc["hum"] = hum;
    String postData;
    serializeJson(jsonDoc, postData);
    
    client.println("POST /api/receive-data.php HTTP/1.1");
    client.println("Host: " + String(server));
    client.println("Content-Type: application/json");
    client.print("Content-Length: ");
    client.println(postData.length());
    client.println();
    client.println(postData);
    
    client.stop();
    Serial.println("Data sent to server: " + postData);
  } else {
    Serial.println("Connection to server failed");
  }

  delay(10000);
}
    

Server-Side Code (PHP)

The following PHP script receives JSON data from the ESP8266 and processes it securely:


<?php
header("Content-Type: application/json");

$data = json_decode(file_get_contents("php://input"));

if (!isset($data->temp) || !isset($data->hum)) {
    echo json_encode(["status" => "error", "message" => "Invalid data"]);
    exit();
}

$temp = filter_var($data->temp, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
$hum = filter_var($data->hum, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);

if ($temp === false || $hum === false) {
    echo json_encode(["status" => "error", "message" => "Invalid temperature or humidity values"]);
    exit();
}

// Log data to a file (Optional)
file_put_contents("sensor_data.log", date('Y-m-d H:i:s') . " | Temp: $temp °C | Hum: $hum %\n", FILE_APPEND);

// Return response
echo json_encode(["status" => "success", "temp" => $temp, "hum" => $hum]);
?>
    

JSON API for Data Handling

Instead of directly printing data, we can store it and serve it as a JSON API.


{"status":"error"}    

Data Visualization

We can display real-time temperature and humidity values using JavaScript and Chart.js.


<canvas id="sensorChart"></canvas>

    

Upload and Test

  1. Upload the Arduino code to your ESP8266 using the Arduino IDE.
  2. Ensure the server-side PHP script is hosted on a web server (Apache, Nginx, etc.).
  3. Open the Serial Monitor in the Arduino IDE to check the Wi-Fi connection status and whether the data is being sent.
  4. Access the PHP page on your server to see the temperature and humidity values displayed.

Enhancements & Next Steps

  • Store the sensor data in a database for historical analysis.
  • Implement MQTT to improve real-time communication.
  • Send email or push notifications when temperature exceeds a certain threshold.
  • Integrate with a cloud service like Firebase or AWS IoT.

Conclusion

This project successfully demonstrated how to send sensor data (temperature and humidity) from an ESP8266 to a web server and visualize it in real time. It forms a solid foundation for developing IoT-based remote monitoring solutions.

Contact Us

Microautomation logo featuring a modern, abstract design with interconnected gears, circuit lines, and microcontroller elements, symbolizing automation and technology.

If you have any questions or inquiries, feel free to reach out to us at Microautomation.no@icloud.com .

Follow our Socials for the newest updates!

Follow us on Facebook Follow us on Reddit Follow us on Instagram