Arduino网络编程实战-Ethernet篇-Web服务器 Web服务器 Arduino Ethernet Shield V1 允许 Arduino 板连接到互联网。 它基于 Wiznet W5100ethernet 芯片(数据表)。 Wiznet W5100 提供支持 TCP 和 UDP 的网络 (IP) 堆栈。 它最多支持四个同时套接字连接。
本次实例将演示如何实现一个简单的Web服务器。
1、硬件准备
Arduino Mega 2560
Arduino Ethernet Shield
路由器(推荐可以上网、开启DHCP)
网线一条
电脑一台
2、软件准备
Arduino IDE
网络调试软件(推荐使用通信猫 )
3、代码实现 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 #include <SPI.h> #include <Ethernet.h> #define USE_STATIC 0 byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; #if USE_STATIC IPAddress ip(192, 168, 0, 177); #endif EthernetServer server(8080); void setup() { Serial.begin(9600); Serial.println("Ethernet Web Server Example"); #if USE_STATIC Ethernet.begin(mac,ip); #else Ethernet.begin(mac); #endif if (Ethernet.hardwareStatus() == EthernetNoHardware) { Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); while (true) { delay(1); } } if (Ethernet.linkStatus() == LinkOFF) { Serial.println("Ethernet cable is not connected."); while(true){ delay(1); } } Serial.print("IP:"); Serial.println(Ethernet.localIP()); Serial.print("Subnet Mask:"); Serial.println(Ethernet.subnetMask()); Serial.print("Gateway:"); Serial.println(Ethernet.gatewayIP()); Serial.print("DNS Server:"); Serial.println(Ethernet.dnsServerIP()); server.begin(); Serial.print("server started"); } void loop() { // 监听客户端连接 EthernetClient client = server.available(); if (client) { Serial.println("new client"); boolean currentLineIsBlank = true; while (client.connected()) { if (client.available()) { char c = client.read(); Serial.write(c); // 如果接收到换行符并且该行为空白,则表示http请求已结束,因此可以发送回复 if (c == '\n' && currentLineIsBlank) { // 发送一个标准的 http 响应头 client.println("HTTP/1.1 200 OK"); client.println("Content-Type: text/html"); client.println("Connection: close"); // 响应完成后将关闭连接 client.println(); client.println("<!DOCTYPE HTML>"); client.println("<html>"); // TODO: 此处可以输入HTML页面 // 注意:字符串不能太长,否则会导致烧写失败 // 可以分多行 client.print("<H2>"); client.print("Hello,"); client.print("<font "); client.print("color=\"red\">"); client.print("Arduino "); client.print("Mega2560 "); client.print("Network "); client.print("Programming."); client.print("</font></H2>"); client.println(); client.println("</html>"); break; } if (c == '\n') { // 新行 currentLineIsBlank = true; } else if (c != '\r') { // 当前行的字符内容 currentLineIsBlank = false; } } } // 给网络浏览器时间来接收数据 delay(1); // 关闭连接 client.stop(); Serial.println("client disconnected"); } }
4、运行结果
文章来源: https://iotsmart.blog.csdn.net/article/details/122741086
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!