#從Arduino通過HTTP讀取數值

在本教程中,我想擴展Arduino Web Server教程以讀取由傳感器測量的數值,這樣我們只需打開瀏覽器上的一個頁面就可以看到數據。

例如,我們將使用DHT11傳感器測量溫度,並使用接近傳感器測量對象距離。

我們通過訪問/on URL點亮Arduino上的內置LED,並通過打開/off URL關閉它。其他任何操作都不起作用。

這是來自其他教程的代碼:

#include <SPI.h>
#include <WiFiNINA.h>

WiFiServer server(80);

void setup() {
 char ssid[] = SECRET\_SSID;
 char pass[] = SECRET\_PASS;

 Serial.begin(9600);
 while (!Serial);

 int status = WL\_IDLE\_STATUS;
 while (status != WL\_CONNECTED) {
 Serial.print("Connecting to ");
 Serial.println(ssid);
 status = WiFi.begin(ssid, pass);
 delay(5000);
 }

 Serial.print("IP address: ");
 Serial.println(WiFi.localIP());

 server.begin();
}

void loop() {
 WiFiClient client = server.available();
 if (client) {
 String line = "";
 while (client.connected()) {
 if (client.available()) {
 char c = client.read();
 Serial.write(c);

 if (c != '\n' && c != '\r') {
 line += c;
 }

 if (c == '\n') {
 if (line.length() == 0) {
 client.println("HTTP/1.1 200 OK");
 client.println("Content-Type: text/html");
 client.println("Connection: close"); // the connection will be closed after completion of the response
 client.println();
 client.println("<!DOCTYPE HTML>");
 client.println("<html>");
 client.println("test");
 client.println("</html>");
 break;
 } else {
 line = "";
 }
 }
 }
 }

 client.stop();
 }
}

在最後的else語句中,我們有一個完整的行,因此我們可以在清理之前檢查其內容。在這種情況下,我們可以檢查是否為GET /onGET /off

if (line.startsWith("GET /on ")){
 digitalWrite(LED\_BUILTIN, HIGH);
}
if (line.startsWith("GET /off ")) {
 digitalWrite(LED\_BUILTIN, LOW);
}

就這樣!現在將代碼加載到Arduino並調用/on URL或/off URL。

我在本地網絡路由器上為Arduino保留了一個靜態IP,並將其命名為arduino.local,在我的/etc/hosts文件中,所以訪問http://arduino.local/on打開LED,http://arduino.local/off關閉LED。

以下是完整的程序:

#include <SPI.h>
#include <WiFiNINA.h>

WiFiServer server(80);

void setup() {
 char ssid[] = SECRET\_SSID;
 char pass[] = SECRET\_PASS;

 Serial.begin(9600);
 while (!Serial);

 int status = WL\_IDLE\_STATUS;
 while (status != WL\_CONNECTED) {
 Serial.print("Connecting to ");
 Serial.println(ssid);
 status = WiFi.begin(ssid, pass);
 delay(5000);
 }

 Serial.print("IP address: ");
 Serial.println(WiFi.localIP());

 server.begin();
}

void loop() {
 WiFiClient client = server.available();
 if (client) {
 String line = "";
 while (client.connected()) {
 if (client.available()) {
 char c = client.read();
 Serial.write(c);

 if (c != '\n' && c != '\r') {
 line += c;
 }

 if (c == '\n') {
 if (line.length() == 0) {
 client.println("HTTP/1.1 200 OK");
 client.println("Content-Type: text/html");
 client.println("Connection: close"); // the connection will be closed after completion of the response
 client.println();
 client.println("<!DOCTYPE HTML>");
 client.println("<html>");
 client.println("test");
 client.println("</html>");
 break;
 } else {
 if (line.startsWith("GET /on ")){
 digitalWrite(LED\_BUILTIN, HIGH);
 }
 if (line.startsWith("GET /off ")) {
 digitalWrite(LED\_BUILTIN, LOW);
 }

 line = "";
 }
 }
 }
 }

 client.stop();
 }
}