• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
MKT-porter
博客园    首页    新随笔    联系   管理    订阅  订阅
esp8266 wifi热点http服务器互传
 
 

 

模块1   http服务器建立 热点分享 等待数据

#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <ArduinoJson.h>

const char* apSSID = "love";           // 替换为你的Wi-Fi名称
const char* apPassword = "love123456"; // 替换为你的Wi-Fi密码
const int port = 80;   
ESP8266WebServer server(port);  // 设置服务器监听80端口

// 处理未找到的路由
void handleNotFound() {
  String message = "File Not Found\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += (server.method() == HTTP_GET) ? "GET" : "POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";
  for (uint8_t i = 0; i < server.args(); i++) {
    message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
  }
  server.send(404, "text/plain", message);
}

void setup() {
  Serial.begin(9600);  // 启动串口监视器,输出调试信息

  // 创建Wi-Fi热点
  WiFi.mode(WIFI_AP);  // 设置为热点模式
  WiFi.softAP(apSSID, apPassword);  // 启动热点并设置SSID和密码

  Serial.println("创建Wi-Fi热点 ");
  // 打印热点名称和密码
  Serial.print("Access Point SSID: ");
  Serial.println(apSSID);  // 打印热点名称
  Serial.print("Access Point Password: ");
  Serial.println(apPassword);  // 打印热点密码
  
  // 获取热点的IP地址并打印
  IPAddress IP = WiFi.softAPIP();
  Serial.print("获取热点的IP地址并打印: ");
  Serial.println(IP);
  
  // 设置HTTP GET请求的路由
  server.on("/", HTTP_GET, handleRoot);
  server.onNotFound(handleNotFound);
  
  // 启动服务器
  server.begin();
  Serial.println("HTTP server started");
}

unsigned long previousMillis = 0;  // 上次打印的时间
const long interval = 1000;        // 每1秒打印一次

void loop() {
  /* 不能有其他代码干扰
  int sensorValue = analogRead(A0);
  unsigned long currentMillis = millis();  // 获取当前的毫秒数
  // 检查是否已经到了每1秒一次的时机
  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;  // 更新上次打印的时间     
    String msg = "压力数据:" + String(sensorValue);
    Serial.println(msg);  // 打印压力数据
  }
 */
  server.handleClient();  // 处理客户端请求
}

// 处理根目录的请求,读取A0引脚的值并返回
void handleRoot() {
  int sensorValue = analogRead(A0);  // 读取A0引脚的模拟值

  // 创建 JSON 对象
  StaticJsonDocument<200> doc;
  doc["A0"] = sensorValue;

  // 将 JSON 数据转换为字符串
  String response;
  serializeJson(doc, response);

  Serial.println(response);  // 打印压力数据

  // 返回读取到的数据
  server.send(200, "application/json", response);
}

  

模块2  链接热点,http请求模块1获取数据

#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <SoftwareSerial.h>
#include <ArduinoJson.h>
#include <WiFiClient.h>
#include <ESP8266HTTPClient.h>

const char* ssid = "love";  // 第一个 ESP8266 创建的热点的 SSID
const char* password = "love123456";  // 第一个 ESP8266 创建的热点的密码
const char* host = "192.168.4.1";  // 第一个 ESP8266 的 IP 地址(假设为 192.168.4.1)
const int port = 80;  // 修改为 8080 端口

WiFiClient client;  // 用于 HTTP 客户端连接
SoftwareSerial softSerial(D2, D1);  // 软串口,D2 为 RX,D1 为 TX

unsigned long previousMillis = 0;  // 上次获取数据的时间
const long interval = 2000;        // 每两秒请求一次数据

void setup() {
  Serial.begin(9600);  // 启动串口调试
  softSerial.begin(9600);  // 启动软串口
  
  WiFi.mode(WIFI_STA);
  // 连接到第一个 ESP8266 创建的 Wi-Fi 热点
  WiFi.begin(ssid, password);

  Serial.println("Connecting to WiFi...");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("\nConnected to WiFi");

  // 打印连接的 IP 地址
  Serial.print("自己的 IP Address: ");
  Serial.println(WiFi.localIP());
  
  Serial.print("连接服务器IP Host: ");
  Serial.println(host);
  Serial.print("Port: ");
  Serial.println(port);
}

void loop() {
  unsigned long currentMillis = millis();  // 获取当前的毫秒数

  // 每两秒请求一次数据
  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;

    HTTPClient http;  // 创建一个 HTTP 客户端

    Serial.print("[HTTP] begin...\n");
    if (http.begin(client, host, port, "/")) {  // 使用 HTTPClient 连接到目标主机

      Serial.print("[HTTP] GET...\n");
      // 开始连接并发送 HTTP 请求
      int httpCode = http.GET();

      // httpCode 会为负数表示错误
      if (httpCode > 0) {
        // HTTP 头已发送,服务器响应头已处理
        Serial.printf("[HTTP] GET... code: %d\n", httpCode);

        String response_;
        // 如果文件找到,返回服务器的数据
        if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
          response_ = http.getString();
          Serial.println("Received data: ");
          Serial.println(response_);

          // 解析 JSON 响应
          StaticJsonDocument<200> doc;
          DeserializationError error = deserializeJson(doc, response_);

          if (error) {
            Serial.print("JSON parsing failed: ");
            Serial.println(error.c_str());
          } else {
            // 提取 A0 数据
            int A0Value = doc["A0"];
            //Serial.print("A0 value: ");
            //Serial.println(A0Value);

            // 将 A0 数据通过软串口转发
            //softSerial.print("A0 value: ");
            softSerial.println(response_);
          }
        }
      } else {
        // 如果请求失败,打印错误信息
        Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
      }
      http.end();  // 结束 HTTP 连接
    } else {
      Serial.println("Connection failed, check the following:");
      Serial.print("Host: ");
      Serial.println(host);
      Serial.print("Port: ");
      Serial.println(port);
    }
  }
}

  

 

posted on 2025-03-01 01:29  MKT-porter  阅读(96)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3