Arduino html自动刷新用于常量数据流

时间:2014-02-19 18:33:42

标签: html arduino

我们正在努力让Arduino更新服务的网页,而无需刷新页面。我们目前的代码如下。现在页面尽可能快地刷新(大约每秒一次),但我们想要更新数据而不必刷新。有没有办法用html做到这一点?

感谢您的帮助!

void loop() {
  WiFiClient client = server.available();   // listen for incoming clients

  if (client) {                             // if you get a client,
  Serial.println("new client");           // print a message out the serial port
  String currentLine = "";                // make a String to hold incoming data from the     client
  while (client.connected()) {            // loop while the client's connected
    if (client.available()) {             // if there's bytes to read from the client,
      char c = client.read();             // read a byte, then
      Serial.write(c);                    // print it out the serial monitor
      if (c == '\n') {                    // if the byte is a newline character

        // if the current line is blank, you got two newline characters in a row.
        // that's the end of the client HTTP request, so send a response:
        if (currentLine.length() == 0) {
          // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
          // and a content-type so the client knows what's coming, then a blank line:
          client.println("HTTP/1.1 200 OK");
          client.println("Content-type:text/html");

          client.println();

          voltageReading = analogRead(A0);

          //meta-refresh page as fast as possible
          client.print("<HEAD>");
          client.print("<meta http-equiv=\"refresh\" content=\"0\">");
          client.print("<TITLE />Smart 3 Phase Relay TCNJ</title>");
          client.print("</head>");
          // the content of the HTTP response follows the header:
          client.print("Voltage Reading: ");
          client.print(voltageReading);

          // The HTTP response ends with another blank line:
          client.println();
          // break out of the while loop:
          break;
        }
          else {      // if you got a newline, then clear currentLine:
          currentLine = "";
        }
      }
      else if (c != '\r') {    // if you got anything else but a carriage return character,
      currentLine += c;      // add it to the end of the currentLine
    }

    // Check to see if the client request was "GET /H" or "GET /L":
    if (currentLine.endsWith("GET /H")) {
      digitalWrite(9, HIGH);               // GET /H turns the LED on
    }
    if (currentLine.endsWith("GET /L")) {
      digitalWrite(9, LOW);                // GET /L turns the LED off
    }
  }
}
// close the connection:
client.stop();
Serial.println("client disonnected");
}
}

1 个答案:

答案 0 :(得分:1)

HTML是无连接的,这意味着您无法知道数据是否已更改。据说你只能“拉”,而ajax仍然拉,但它需要xml / json数据而不是所有的html。

但据我所知,您需要一种“推送”技术,这意味着服务器可以在可用时向客户端发送新数据;可以使用“WebSocket”,但它需要服务器重写来支持协议,或者你可以使用library websocket可以像普通套接字一样使用(浏览器强制执行某些安全限制,主要是你只能连接到HTML服务器的同一域/ ip),这意味着一旦建立连接,你就可以打印和读取就像你使用Serial一样!