#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>
// Wi-Fi credentials
const char* ssid = "937";
const char* password = "937937937...";
// API endpoint
const char* serverName = "http://192.168.1.109:8001/api/environment/";
// Interval for sending data
unsigned long previousMillis = 0;
const long interval = 5000; // 5 seconds
// LED pin (change it if it's not the built-in LED)
const int ledPin = LED_BUILTIN;
void setup() {
Serial.begin(115200); // Start the Serial communication
pinMode(ledPin, OUTPUT); // Initialize the LED pin as an output
connectToWiFi(); // Connect to Wi-Fi
}
void loop() {
unsigned long currentMillis = millis();
if ((unsigned long)(currentMillis - previousMillis) >= interval) {
previousMillis = currentMillis;
if (WiFi.status() == WL_CONNECTED) { // Check if we are still connected to the Wi-Fi
sendEnvironmentData(); // Send environment data
} else {
connectToWiFi(); // If not connected, try to connect again
}
}
}
void connectToWiFi() {
Serial.println("Connecting to Wi-Fi");
WiFi.begin(ssid, password); // Connect to the specified Wi-Fi network
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("Wi-Fi connected");
}
void sendEnvironmentData() {
// Simulate environment data
float temperature = 24.5; // Replace with real sensor data
float humidity = 60; // Replace with real sensor data
// Use ArduinoJson library to create JSON object
StaticJsonDocument<200> jsonDoc;
jsonDoc["temperature"] = temperature;
jsonDoc["humidity"] = humidity;
char jsonData[200];
serializeJson(jsonDoc, jsonData);
// Create a WiFiClient object to pass to the HTTPClient
WiFiClient client;
// Send the HTTP POST request
HTTPClient http;
http.begin(client, serverName); // Use the new API
http.addHeader("Content-Type", "application/json"); // Set the content type to JSON
int httpResponseCode = http.POST(jsonData); // Send the actual POST request
// ... the rest of your code remains unchanged ...
}
void blinkLED() {
digitalWrite(ledPin, LOW); // Turn the LED on (Note that LOW is usually the voltage level
// but due to internal LED wiring, LOW actually turns it on)
delay(250); // Keep it on for 250 milliseconds
digitalWrite(ledPin, HIGH); // Turn the LED off
delay(250); // Keep it off for 250 milliseconds
}
esp8266通过post向局域网django发送数据
最新推荐文章于 2024-01-30 14:46:06 发布