esp8266通过post向局域网django发送数据

#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
}

  • 10
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

菌菌的快乐生活

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值