我正在尝试使用 Arduino、Android 应用程序和路由器制作无线灯光控制设备(开/关/调光)。
我正在使用路由器将 Arduino 设置为静态 IP 192.168.1.2。我正在从 Android 应用程序向 IP 地址 192.168.1.2 发送字符串(“1”-关闭、“2”-降低亮度、“3”-增加亮度、“4”-打开)。我已经使用Arduino Wi-Fi shield将 Arduino连接到 Internet,并使用以下代码设置了 WifiServer:
char ssid[] = "NAME"; // Your network SSID (name)
char pass[] = "PASS"; // Your network password (use for WPA, or use as key for WEP)
int keyIndex = 0; // Your network key Index number (needed only for WEP)
int status = WL_IDLE_STATUS;
WiFiServer server(23);
boolean alreadyConnected = false; // Whether or not the client was connected previously.
void setup() {
// Start serial port:
Serial.begin(9600);
// Attempt to connect to Wi-Fi network:
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
status = WiFi.begin(ssid, pass);
// Wait 10 seconds for connection:
delay(10000);
}
// Start the server:
server.begin();
// You're connected now, so print out the status:
printWifiStatus();
}
我遇到的主要问题是如何接受和打印来自 Android 设备的字符串。我必须这样做的当前代码是:
// Listen for incoming clients
WiFiClient client = server.available();
if (client) {
// An HTTP request ends with a blank line
boolean newLine = true;
String line = "";
while (client.connected() && client.available()) {
char c = client.read();
Serial.print(c);
// If you've gotten to the end of the line (received a newline
// character) and the line is blank, the HTTP request has ended,
// so you can send a reply.
if (c == '\n' && newLine) {
// Send a standard HTTP response header
//client.println("HTTP/1.1 200 OK");
//client.println("Content-Type: text/html");
//client.println();
}
if (c == '\n') {
// You're starting a new line
newLine = true;
Serial.println(line);
line = "";
}
else if (c != '\r') {
// You've gotten a character on the current line
newLine = false;
line += c;
}
}
Serial.println(line);
// Give the web browser time to receive the data
delay(1);
// Close the connection:
//client.stop();
}
}
我将此代码基于博客文章Android Arduino Switch with a TinyWebDB hack,但此代码用于以太网屏蔽。Android 应用程序是使用MIT App Inventor制作的,与博文中的类似。
TLDR,如何使用 Arduino Wi-Fi shield 获取字符串?