通过插入W5100 以太网盾板,实现Arduino NUO 接入以太网的想法
#include <Ethernet.h>
//#include <SPI.h>
//mac地址可以是随便的48位地址,只要设备间不相互冲突就行
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress staticIP(192,168,31,159);
EthernetServer server(80);
void connectToInternet()
{
if (Ethernet.begin(mac) == 0)//看看DHCP是否能动态分配ip给Arduino
{
Serial.print("[ERROR] Failed to Configure Ethernet using DHCP");
Ethernet.begin(mac, staticIP);//DHCP不能动态分配,就静态设置ip给Arduino
}
delay(1000);
Serial.println("[INFO] Connection Successsful");
Serial.print("");
printConnectionInformation();
Serial.println("-------------------------");
Serial.println("");
}
void printConnectionInformation()
{
Serial.print("[INFO] IP Address: ");
Serial.println(Ethernet.localIP());
Serial.print("[INFO] Subnet Mask: ");
Serial.println(Ethernet.subnetMask());
Serial.print("[INFO] Gateway: ");
Serial.println(Ethernet.gatewayIP());
Serial.print("[INFO] DNS: ");
Serial.println(Ethernet.dnsServerIP());
}
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
connectToInternet();
server.begin();
}
void loop()
{
//当有客户连接服务器时,服务器available函数会返回一个客户端对象用以向客户反馈信息
EthernetClient client = server.available();
if (client) {
// an http request ends with a blank line
boolean current_line_is_blank = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();
// if we've gotten to the end of the line (received a newline
// character) and the line is blank, the http request has ended,
// so we can send a reply
if (c == 'n' && current_line_is_blank) {
// send a standard http response header
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println();
// output the value of each analog input pin
client.print("welcome to tinyos electronics");
client.println("<br />");
client.print("//*************************************");
client.println("<br />");
client.print("");
client.println("<br />");
client.print("//*************************************");
client.println("<br />");
for (int i = 0; i < 6; i++) {
client.print("analog input ");
client.print(i);
client.print(" is ");
client.print(analogRead(i));
client.println("<br />");
}
break;
}
//有的教程里也有用(c == '\n')和 (c != '\r')的
//2018-12-16补充试验,用(c == '\n')和 (c != '\r')的话,客户端连接不上服务器,不能用啊
if (c == 'n') {
// we're starting a new line
current_line_is_blank = true;
} else if (c != 'r') {
// we've gotten a character on the current line
current_line_is_blank = false;
}
}
}
client.stop();
}
}
下载程序运行如下图(路由器动态分配了ip)
连接正常时以太网盾板FULLD,100M,LINK,PWR四个led灯都需要亮,不亮的话重启下试试