Arduino蜂箱监控数据无法在PHP网页显示的问题求助
蜂箱监控系统数据接收与显示问题
我是PHP页面编程新手,搭建了Arduino蜂箱监控系统,系统通过http.POST(jsonData)发送实时温度、重量数据到局域网内群晖NAS上的PHP7.4 Web服务器(IP:192.168.0.5,HTTP端口:9978,未启用HTTPS)。Arduino设备IP为192.168.0.52,发送端代码运行后提示“Data sent successfully”,但服务器网页无法显示接收的数据。已尝试修改网页中的IP地址,仍无效果,请求技术支持。
Arduino发送端代码
#include <HTTPClient.h> #include <WiFi.h> #include <Ethernet.h> const char* host = "192.168.0.5"; //web server synology NAS const int port = 9978; // http port Synology const char* ssid = "nettUser"; const char* password = "nettPass"; //web login char username[] = "serverUser"; char userpassword[] = "serverPass"; void loop() { // Read sensor values and store in temperature and humidity // Read the temperature and weight values float temperature = 25.0; // for php test purpose, fixed values float weight = 50.0; // Create a JSON object to store the data String jsonData = "{\"temperature\":" + String(temperature) + ",\"weight\":" + String(weight) + "}"; // Create an instance of the HTTPClient class HTTPClient http; // Make a POST request to the server http.begin("http://" + String(host) + ":" + String(port)); http.addHeader("Content-Type", "application/json"); http.setAuthorization(username, userpassword); int httpCode = http.POST(jsonData); // Check the response code if (httpCode > 0) { Serial.println("Data sent successfully"); } else { Serial.println("Error sending data"); } // Close the connection http.end(); Serial.print("[WiFi] IP address: "); Serial.println(WiFi.localIP()); Serial.println(temperature_f); Serial.println(humidity_f); delay(5000); } }
服务器端index.php代码
<html> <head> <script> function updateData() { const xhr = new XMLHttpRequest(); xhr.open("GET", "http://192.168.0.52:80"); xhr.onreadystatechange = function() { if (xhr.readyState === XMLHttpRequest.DONE) { if (xhr.status === 200) { const data = JSON.parse(xhr.responseText); document.getElementById("temperature").innerHTML = data.temperature; document.getElementById("weight").innerHTML = data.weight; } else { console.error(xhr.statusText); } } }; xhr.send(); } setInterval(updateData, 1000); </script> </head> <body> <h1>HiveMon - v 1</h3> <h3>Temperature: <span id="temperature"></span>℃</h3> <h3>Weight: <span id="weight"></span>%</h3> </body> </html>
问题分析与修复方案
你的核心问题是数据流转逻辑完全错误,当前代码没打通Arduino→服务器→网页的数据流,以下是具体问题和修复步骤:
1. 服务器缺失POST数据接收逻辑
当前的index.php只是静态HTML页面,没有处理Arduino发送的POST请求的PHP代码,导致Arduino发的数据根本没被服务器接收保存。
修复:新增数据接收接口
在NAS的Web目录下创建save_data.php文件,用来接收并存储Arduino的POST数据:
<?php // 验证HTTP基本认证(和Arduino代码里的账号密码对应) $expectedUser = 'serverUser'; $expectedPass = 'serverPass'; if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW']) || $_SERVER['PHP_AUTH_USER'] !== $expectedUser || $_SERVER['PHP_AUTH_PW'] !== $expectedPass) { header('WWW-Authenticate: Basic realm="Hive Monitor"'); header('HTTP/1.0 401 Unauthorized'); echo 'Unauthorized'; exit; } // 接收JSON数据 $jsonData = file_get_contents('php://input'); $data = json_decode($jsonData, true); if ($data && isset($data['temperature'], $data['weight'])) { // 将数据保存到文件(简单存储,生产环境可改用数据库) $file = 'hive_data.json'; file_put_contents($file, json_encode($data)); http_response_code(200); echo 'Data saved'; } else { http_response_code(400); echo 'Invalid data'; } ?>
同时修改Arduino代码里的请求地址,指向这个新接口:
// 原代码:http.begin("http://" + String(host) + ":" + String(port)); // 修改为: http.begin("http://" + String(host) + ":" + String(port) + "/save_data.php");
2. 网页前端请求方向错误
当前网页JS是向Arduino(192.168.0.52:80)发GET请求,但Arduino并没有开启HTTP服务响应这个请求,自然拿不到数据。正确逻辑是网页向NAS服务器请求已存储的数据。
修复:修改前端JS代码
修改index.php里的JS部分,改为从服务器读取保存的hive_data.json:
<html> <head> <script> function updateData() { const xhr = new XMLHttpRequest(); // 加时间戳避免浏览器缓存旧数据 xhr.open("GET", "hive_data.json?" + new Date().getTime()); xhr.onreadystatechange = function() { if (xhr.readyState === XMLHttpRequest.DONE) { if (xhr.status === 200) { try { const data = JSON.parse(xhr.responseText); document.getElementById("temperature").innerHTML = data.temperature; document.getElementById("weight").innerHTML = data.weight; } catch(e) { console.error('解析数据失败:', e); } } else { console.error('请求失败:', xhr.statusText); } } }; xhr.send(); } setInterval(updateData, 1000); </script> </head> <body> <h1>HiveMon - v 1</h1> <!-- 修正原代码里的标签闭合错误 --> <h3>Temperature: <span id="temperature"></span>℃</h3> <h3>Weight: <span id="weight"></span>kg</h3> <!-- 修正不合理的单位 --> </body> </html>
3. Arduino代码的小问题
- 代码里引用了未定义的
temperature_f和humidity_f,会导致编译错误,直接删除这两行:
// 删掉以下两行 Serial.println(temperature_f); Serial.println(humidity_f);
- 缺失WiFi初始化逻辑,补充
setup()函数:
void setup() { Serial.begin(115200); // 连接WiFi WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.println("Connecting to WiFi..."); } Serial.println("Connected to WiFi"); }
验证步骤
- 将
save_data.php和修改后的index.php上传到NAS的Web服务目录,确保端口9978能正常访问。 - 上传修改后的Arduino代码到设备,打开串口监视器确认WiFi连接成功且数据发送正常。
- 访问
http://192.168.0.5:9978/index.php,查看温度和重量是否正常显示。
内容的提问来源于stack exchange,提问作者Leia
相关产品推荐
相关产品推荐

