Arduino,esp8266和正在提供的网页

问题描述 投票:0回答:1

我正在研究有关使用esp8266连接到Arduino Uno的教程,并通过Ajax为网页提供服务,该网页检索json文件(也由Arduino提供)。该教程(此处不会链接到该教程)看起来像是虚构的作品,因为作者使用这样的Strings构建网页:

    String webpage = "<!DOCTYPE html><html><head><meta name=\"viewport\" content=\"width=device-width, minimumscale=1.0, maximum-scale=1.0, initial-scale=1\" />";
    webpage += "<style>body { background-color: #cccccc; text-align: center; max-width: 400px; margin: 10px auto; } #datavalues { max-width: 400px; display: block; margin-top: 30px; }</style>";
    webpage += "</head><body>";
    webpage += "<div id=\"datavalues\">";
    webpage += "<h1>Light: </h1><div id=\"light\">";
    webpage += lightval;
    webpage += "</div>";
    webpage += "<h1>Count: </h1><div id=\"count\">";
    webpage += count;
    webpage += "</div>";
    webpage += "</div>";
    webpage += "<script>function loadDoc() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var obj = JSON.parse(this.responseText); document.getElementById(\"light\").innerHTML = obj.data[0].datavalue; document.getElementById(\"count\").innerHTML = obj.data[1].datavalue; } }; xhttp.open(\"GET\", \"data.json\", true); xhttp.send(); } var timedEvent = setInterval(function(){ loadDoc(); }, 2000);</script>";
    webpage += "</body></html>";

并且当您对其进行测试时,似乎网页对于String而言太长,或者uno内存不足。我一直在尝试使用c类型的字符串(读取它们更有效),如下所示:

    char webpage[1024] = "<!DOCTYPE html><html><head><meta name=\"viewport\" content=\"width=device-width, minimumscale=1.0, maximum-scale=1.0, initial-scale=1\" />";
    strcat(webpage, "<style>body { background-color: #cccccc; text-align: center; max-width: 400px; margin: 10px auto; } #datavalues { max-width: 400px; display: block; margin-top: 30px; }</style>");

但是似乎并没有太大的区别。有没有办法从arduino提供如此大小的网页? /构建和提供服务的最有效方法是什么?

string server arduino esp8266
1个回答
1
投票

取决于Arduino(UNO)上的可用内存,您可以将HTML移至progmem示例代码

//HTML Code Start-----------------------------------
static const char PROGMEM INDEX_HTML[] = R"rawliteral(
<!doctype html>
<html>
.... your page code here
        <script>
   ...even with javascript
       </script>
     </body>
 </html>
 )rawliteral";
//HTML Code END-----------------------------------

然后您将在响应中使用它(带有类似简单网络服务器的库或Uno的类似库),如

 server.on("/index.html", HTTP_GET, []() {
    server.send(200, "text/html", (const char *)INDEX_HTML);
});

对于仅通过wifi发送,您会做一个

  client.print(...);

[以最小的页面开始(编译后观察内存)-下一步应该是在esp中托管Web功能(SPIFFS / LittleFS),并通过串行方式与arduino连接并与引脚交换数据。最后提示:切勿使用Arduino String类和通信任务-它将使堆碎片化,并使Arduino / ESP崩溃。而是使用预定义的char数组和指针。

© www.soinside.com 2019 - 2024. All rights reserved.