【问题标题】:Arduino Webserver UpdateArduino 网络服务器更新
【发布时间】:2014-05-30 01:07:11
【问题描述】:

我的 arduino 上的网络服务器有一小段代码,连接到以太网屏蔽:

client.println("<html><head><title>ArduServ</title></head><body>");
client.print("Current Temperature: ");client.println(getTMP());
client.println("<form method=get>Input:<input type=text size=25 name=inp><input type=submit value=submit></form>");
client.println("</body></html>");

有没有一种方法可以使用 javascript 更新温度,这样我就不必每秒钟都重新绘制页面?我可以改变温度吗?

【问题讨论】:

    标签: javascript arduino webserver ethernet


    【解决方案1】:

    出于几个原因,我个人不会将 Arduino 用作 HTTP 服务器。

    1. 性能 - 作为微控制器,您的资源有限。如果您希望交互是实时的,则提供所有标题和内容可能会很昂贵。

    2. 可管理性 - 我相信您知道,不得不通过多行双引号中的字符串来管理网页的源代码真的很令人沮丧。 p>

    解决方案

    我发现为 Arduino 制作 Web 控制器界面的最有效方法是将页面托管在本地计算机上的某个位置,或者甚至在服务器上(如果有的话)。然后,让 Arduino 成为 Web 套接字服务器而不是 HTTP 服务器。

    这将允许您使用 JavaScript 中的 WebSocket 类轻松进行通信,而不必担心托管 Web 内容的开销。

    我已经为 Arduino 使用了 this 网络套接字服务器实现,效果很好。

    这是一个基于您向我们展示的基本示例。

    阿杜诺

    假设ethernet 是EthernetServer,而socket 是WebSocketServer。

    // initialize the ethernet and socket server in setup() here ...
    
    void loop(void)
    {
        EthernetClient client = ethernet.available();
    
        if (client.connected() && socket.handshake(client))
        {
            while (client.connected())
            {
                String response;
    
                // add the temperature to the response 
                response += getTMP();
    
                // send the response to the JavaScript interface
                socket.sendData(response);
    
                // update every 250 milliseconds
                delay(250);
            }
        }
    
        // wait to let the client fully disconnect
        delay(100);
    }
    

    JavaScript

    // assuming you have something like <div id="temperature"></div> in the document
    var temperature = document.getElementById('temperature');
    
    // whatever IP that was assigned to the EthernetServer
    var ip = '192.168.0.99';
    
    var socket = new WebSocket('ws://'+ ip);
    
    socket.onmessage = function(e) {
        // update the temperature text
        temperature.innerHTML = e.data;
    };
    

    您可以找到有关 JavaScript Web 套接字here 的更多信息。

    【讨论】:

    • 我如何初始化 WebSocketServer 以及我必须包含什么来获得它?
    • 下载主存储库here,然后将其移至 Documents/Arduino/libraries/ 文件夹。您可以从File &gt; Examples 打开 Arduino IDE 中的示例项目之一。 Web Socket 实际上不需要任何初始化,只需要以太网服务器。
    猜你喜欢
    • 2016-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多