【发布时间】:2014-02-07 14:05:28
【问题描述】:
我有一个带有 Wiznet Ethernet Shield 的 Arduino Uno,它可以很好地连接到路由器。但经过一段时间(最多 30 秒)后,它会失去与路由器的连接并离线。有人在代码中看到它的原因吗?
#include <Ethernet.h>
#include <SPI.h>
boolean reading = false;
////////////////////////////////////////////////////////////////////////
//CONFIGURE
////////////////////////////////////////////////////////////////////////
byte ip[] = { 192, 168, 178, 99 };
//byte gateway[] = { 192, 168, 178, 1 };
//byte subnet[] = { 255, 255, 255, 0 };
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; // if need to change the MAC address (Very Rare)
EthernetServer server = EthernetServer(80); //port 80
const int ledPin = 2; // LED Pin
////////////////////////////////////////////////////////////////////////
void setup(){
pinMode(ledPin, OUTPUT); //Pins 10,11,12 & 13 are used by the ethernet shield
digitalWrite(ledPin, LOW);
Ethernet.begin(mac);
server.begin();
}
void loop(){
checkForClient(); // listen for incoming clients, and process qequest.
}
void checkForClient(){
EthernetClient client = server.available();
if (client) {
// an http request ends with a blank line
boolean currentLineIsBlank = true;
boolean sentHeader = false;
while (client.connected()) {
if (client.available()) {
if(!sentHeader){
// send a standard http response header
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println();
sentHeader = true;
}
char c = client.read();
if(reading && c == ' ') reading = false;
if(c == '?') reading = true; //found the ?, begin reading the info
if(reading){
switch (c) {
case 'on':
digitalWrite(ledPin, HIGH);
break;
case 'off':
digitalWrite(ledPin, LOW);
break;
}
}
if (c == '\n' && currentLineIsBlank) break;
if (c == '\n') {
currentLineIsBlank = true;
}else if (c != '\r') {
currentLineIsBlank = false;
}
}
}
delay(1); // give the web browser time to receive the data
client.stop(); // close the connection:
}
}
【问题讨论】:
-
“下线”是什么意思?停止响应 http 请求,停止响应 ARP 请求,路由器不再检测到该端口上的链接,还是其他原因?
-
不是一个完整的答案,但变量 c 是一个字符。它永远不会匹配任何 switch 案例。