javascript - Arduino Webserver Update -


i have small tidbit of code webserver on arduino connected ethernet shield:

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>"); 

is there way can update temperature using javascript don't have redraw page every second? can change temperature?

i not use arduino http server couple of reasons.

  1. performance - micro controller, have limited resources. serving of headers , content can expensive if want interaction real time.

  2. manageability - i'm sure you're aware, it's frustrating having manage source of web page through strings in double quotes on multiple lines that.

the solution

i've found effective way make web controller interface arduino host page somewhere on computer locally or on server if have one. then, make arduino web socket server instead of http server.

this allow communicate using websocket class in javascript, while not having worry overhead of hosting web content.

i've used this web socket server implementation arduino , works great.

here's basic example based on showed us.

arduino

assuming ethernet ethernetserver, , socket websocketserver.

// initialize ethernet , socket server in setup() here ...  void loop(void) {     ethernetclient client = ethernet.available();      if (client.connected() && socket.handshake(client))     {         while (client.connected())         {             string response;              // add temperature response              response += gettmp();              // send response javascript interface             socket.senddata(response);              // update every 250 milliseconds             delay(250);         }     }      // wait let client disconnect     delay(100); } 

javascript

// assuming have <div id="temperature"></div> in document var temperature = document.getelementbyid('temperature');  // whatever ip assigned ethernetserver var ip = '192.168.0.99';  var socket = new websocket('ws://'+ ip);  socket.onmessage = function(e) {     // update temperature text     temperature.innerhtml = e.data; }; 

you can find more information javascript web sockets here.


Comments

Popular posts from this blog

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

php - render data via PDO::FETCH_FUNC vs loop -

The canvas has been tainted by cross-origin data in chrome only -