Difficulty Level: Intermediate
This project demonstrates how to log sensor data remotely by sending it to a web server using the ESP8266 and HTTP protocol. The ESP8266 reads data from a sensor and sends it to a web server that can store the data for later analysis.
Connect the ESP8266 module to the Arduino as follows:
Install the following libraries in the Arduino IDE:
This Arduino sketch reads data from the DHT22 sensor and sends it to a remote server using HTTP GET requests:
#include
#include
// WiFi credentials
const char* ssid = "yourSSID";
const char* password = "yourPASSWORD";
// Server settings
const char* server = "yourserver.com"; // Replace with your web server
// DHT22 setup
#define DHTPIN D4 // Pin for the DHT22 sensor
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
WiFiClient client;
void setup() {
Serial.begin(115200);
delay(10);
dht.begin();
// Connect to WiFi
Serial.println();
Serial.println("Connecting to WiFi");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println("WiFi connected");
}
void loop() {
// Read temperature and humidity from DHT22
float humidity = dht.readHumidity();
float temperature = dht.readTemperature();
if (isnan(humidity) || isnan(temperature)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Log data to server
if (client.connect(server, 80)) {
String url = "/log_data.php?temperature=";
url += String(temperature);
url += "&humidity=";
url += String(humidity);
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + server + "\r\n" +
"Connection: close\r\n\r\n");
delay(10);
// Check server response
while (client.available()) {
String line = client.readStringUntil('\r');
Serial.print(line);
}
// Disconnect from server
client.stop();
}
delay(60000); // Log data every 60 seconds
}
The code reads data from the DHT22 sensor and connects to a web server using the ESP8266 Wi-Fi module. It sends the temperature and humidity data to the server in the form of an HTTP GET request. The server script (PHP, Python, etc.) logs the data for later analysis.
You’ll need a server-side script (e.g., PHP) to handle incoming data and store it. Here's an example of a basic PHP script:
The PHP script accepts temperature and humidity values via the GET method. It then opens a file (or database) to store the data. You can expand this by adding database logging (e.g., MySQL).
Once the Arduino is programmed and connected to Wi-Fi, it will begin sending sensor data to the server at regular intervals. Open the serial monitor to view the status of data transmission. On the server, check the log file or database to verify that the data is being saved correctly.
This remote data logging system enables you to collect and store sensor data over the internet. The project can be expanded with additional sensors or communication protocols to suit various IoT applications.