В этом примере будем использовать плату Ethernet и плату Arduino или Genuino для создания простого веб-сервера. Используя библиотеку Ethernet.h, наше устройство сможет ответить на HTTP запрос с помощью платы Ethernet. После открытия браузера и перехода к IP-адресу платы Ethernet, наша плата Arduino ответит HTML-кодом, достаточным для браузера, чтобы отобразить входные значения из всех шести аналоговых выводов.
Требуется оборудование
- Плата Arduino или Genuino
- Плата Arduino Ethernet
Схема
Плата Ethernet позволяет подключать WizNet Ethernet контроллер к платам Arduino или Genuino через шину SPI. Данное подключение использует контакты 10, 11, 12 и 13. Более поздние модели платы Ethernet также имеют в своем составе SD-карту. Цифровой контакт 4 используется для управления выбора ведомого на SD-карте.
Плата должна быть подключена к сети с помощью кабеля Ethernet. Вам необходимо будет поменять сетевые настройки в программе, чтобы они соответствовали вашей сети.
Модуль Arduino Ethernet помещается поверх платы Arduino.
Предупреждение
Этот пример не требует SD-карты. Если SD-карта вставлена, но не используется, возможно, программа будет зависать, поскольку вывод 4 используется в качестве SS (активный низкий уровень) SD, а когда он не используется, он по умолчанию настроен как INPUT. Здесь возможны два решения:
- вынуть SD-карту;
- добавить следующие строки кода в setup()
1 2 |
pinMode(4, OUTPUT); digitalWrite(4, HIGH); |
Код
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 |
/* Web Server A simple web server that shows the value of the analog input pins. using an Arduino Wiznet Ethernet shield. Circuit: * Ethernet shield attached to pins 10, 11, 12, 13 * Analog inputs attached to pins A0 through A5 (optional) created 18 Dec 2009 by David A. Mellis modified 9 Apr 2012 by Tom Igoe */ #include <SPI.h> #include <Ethernet.h> // Enter a MAC address and IP address for your controller below. // The IP address will be dependent on your local network: byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; IPAddress ip(192,168,1,177); // Initialize the Ethernet server library // with the IP address and port you want to use // (port 80 is default for HTTP): EthernetServer server(80); void setup() { // Open serial communications and wait for port to open: Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for Leonardo only } // start the Ethernet connection and the server: Ethernet.begin(mac, ip); server.begin(); Serial.print("server is at "); Serial.println(Ethernet.localIP()); } void loop() { // listen for incoming clients EthernetClient client = server.available(); if (client) { Serial.println("new client"); // an http request ends with a blank line boolean currentLineIsBlank = true; while (client.connected()) { if (client.available()) { char c = client.read(); Serial.write(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' && currentLineIsBlank) { // send a standard http response header 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>"); // add a meta refresh tag, so the browser pulls again every 5 seconds: client.println("<meta http-equiv=\"refresh\" content=\"5\">"); // output the value of each analog input pin for (int analogChannel = 0; analogChannel < 6; analogChannel++) { int sensorReading = analogRead(analogChannel); client.print("analog input "); client.print(analogChannel); client.print(" is "); client.print(sensorReading); client.println("<br />"); } client.println("</html>"); break; } if (c == '\n') { // you're starting a new line currentLineIsBlank = true; } else if (c != '\r') { // you've gotten a character on the current line currentLineIsBlank = false; } } } // give the web browser time to receive the data delay(1); // close the connection: client.stop(); Serial.println("client disconnected"); } } |