效果说明:用HTML制作一个简易网页,网页上有两个按钮ON,OFF。 建立Arduino和所制作的网页之间的通讯,但按下ON时,广告灯闪烁,当按下OFF时,广告灯熄灭。 电路图: 代码: - #include<EtherCard.h>
- #include<SPI.h>
- static byte myip[] = {192,168,43,21};//设置本机同网段ip【根据你自己的IP设置】
- static byte gwip[] = {192, 168, 43, 1};
- static byte mymac[] = {0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0x95};
- byte Ethernet::buffer[700];
- BufferFiller bfill;
- int LED_PIN[] = {2, 3, 4, 5};
- int cnt = 0;
- boolean flag = false;
- char *on = "ON";
- char *off = "OFF";
- char *statusLabel;
- char *buttonLabel;
- void light_on()//设置开灯
- {
- if (cnt % 2 == 0)
- {
- for (int i = 0; i < 4; i++)
- {
- digitalWrite(LED_PIN[ i], HIGH);
- delay(100);
- }
- }
- else
- {
- for (int i = 0; i < 4; i++)
- {
- digitalWrite(LED_PIN[ i], LOW);
- delay(100);
- }
- }
- }
- void light_off()//设置关灯
- {
- for (int i = 0; i < 4; i++)
- {
- digitalWrite(LED_PIN[ i], LOW);
- }
- }
- void setup()
- {
- Serial.begin(9600);
- if (!ether.begin(sizeof Ethernet::buffer, mymac, 10))
- Serial.println("Failed to access Ethernet controller");
- if (!ether.staticSetup(myip, gwip))
- Serial.println("Failed to set IP address");
- ether.printIp("LocalIP: ", ether.myip);
- ether.printIp("GWIP: ", ether.gwip);
- Serial.println();
- for (int i = 0; i < 4; i++)
- {
- pinMode(LED_PIN[ i], OUTPUT);
- }
- }
- void loop()
- {
- word len = ether.packetReceive();
- word pos = ether.packetLoop(len);
- if (pos)
- {
- char *data = (char *)Ethernet::buffer + pos;
- if (strstr(data, "GET /?status=ON") != 0)
- {
- Serial.println("Received ON ");
- flag = true;
- }
- if (strstr(data, "GET /?status=OFF") != 0)
- {
- Serial.println("Received OFF ");
- flag = false;
- }
- if (flag)
- {
- statusLabel = on;
- buttonLabel = off;
- }
- else
- {
- statusLabel = off;
- buttonLabel = on;
- }
- bfill = ether.tcpOffset();
- bfill.emit_p(PSTR("HTTP/1.0 200 OK\r\n"
- "Content-Type: text/html\r\nPragma: no-cache\r\n\r\n"
- "<html><head><title>WebLed</title></head>"
- "<body>LED灯 Status: $S "
- "<a href=\"/?status=$S\"><input type=\"button\" value=\"$S\"></a>"
- "</body></html>"),
- statusLabel, buttonLabel, buttonLabel);
- ether.httpServerReply(bfill.position());
- }
- if (flag)
- {
- light_on();
- }
- else
- {
- light_off();
- }
- cnt += 1;
- }
复制代码
效果:
|