You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ESP32通过Arduino IDE向XAMPP发送RFID数据失败问题排查

ESP32无法向XAMPP托管的PHP脚本发送数据的问题排查与修复

核心问题与解决方法

  • localhost地址错误
    ESP32代码中的localhost指代设备自身,而非运行XAMPP的电脑。必须替换为电脑在局域网内的IP地址(可通过电脑网络设置查看,格式如192.168.x.x)。

  • 串口输入含多余字符
    Serial.readStringUntil('\n')读取的内容可能包含换行、回车符,导致POST数据格式异常。添加trim()清理输入:

    String input = Serial.readStringUntil('\n').trim();
    
  • PHP脚本未正确接收数据
    确保script.php正确处理POST请求,示例代码:

    <?php
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $data = $_POST['data'] ?? 'No data received';
        // 写入文件验证接收情况
        file_put_contents('received_log.txt', $data . PHP_EOL, FILE_APPEND);
        echo "Received: " . $data;
    } else {
        echo "Invalid request";
    }
    ?>
    

    同时确认脚本放在XAMPP的htdocs目录下,路径匹配代码中的请求地址。

  • 局域网连通性与防火墙拦截

    • 确认ESP32与电脑处于同一WiFi局域网
    • 检查电脑防火墙是否允许Apache的80端口入站请求
  • 增强调试信息
    打印具体HTTP响应码,便于精准定位问题:

    Serial.print("HTTP Response Code: ");
    Serial.println(httpResponseCode);
    

修正后的完整代码

#include <WiFi.h>
#include <HTTPClient.h>

const char* ssid = "TP-Link_C028";
const char* password = "16810112";
// 替换为你的电脑局域网IP
const char* serverUrl = "http://192.168.1.100/script.php";

void setup() {
  Serial.begin(9600);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }

  Serial.println("Connected to WiFi");
  Serial.print("ESP32 IP Address: ");
  Serial.println(WiFi.localIP());
}

void loop() {
  if (Serial.available()) {
    String input = Serial.readStringUntil('\n').trim();
    Serial.print("Received Serial Input: ");
    Serial.println(input);

    HTTPClient http;

    if (http.begin(serverUrl)) {
      http.addHeader("Content-Type", "application/x-www-form-urlencoded");
      String postData = "data=" + input;

      int httpResponseCode = http.POST(postData);

      Serial.print("HTTP Response Code: ");
      Serial.println(httpResponseCode);

      if (httpResponseCode > 0) {
        String response = http.getString();
        Serial.println("Server Response: " + response);
      } else {
        Serial.println("Error sending data: " + http.errorToString(httpResponseCode));
      }

      http.end();
    } else {
      Serial.println("Failed to initialize HTTP connection");
    }
  }
}

内容的提问来源于stack exchange,提问作者Young-Ja Han

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 22:02:44