Arcade PUB
  • Главная
  • Уроки
  • Датчики
  • Проекты
  • Справочник языка Ардуино
  • Справочник
  • Видео
  • Контакты
  • Поддержать
Уроки  /  3 июня, 2020

Ethernet Shield hr91105a (w5100) . Урок 16. Ардуино

by valentino
Ethernet Shield и электромагнитное реле
Ethernet Shield и электромагнитное реле

Привет! Пришло время подключить Ардуино к интернету. Одно из самых интересных направлений использования Ардуино — это интернет вещей. А управление устройствами на Ардуино через интернет, пожалуй, самое востребованное направление на сегодня. Поэтому сегодня поговорим о дополнительной плате для подключения Ардуино к интернету, об Ethernet Shield.

Содержание

  • 1 Для того, чтобы выполнить этот урок нам понадобиться
  • 2 Ethernet Shield
  • 3 Принципиальная схема
  • 4 Программа
  • 5 Полный текст программы
  • 6 Заключение
  • 7 Похожее

В предыдущем уроке мы говорили о bluetooth модуле и электромагнитном реле. Это тоже часть проектов на Ардуино, которые помогают в интернете вещей и беспроводной передаче информации от Ардуино к приложениям в телефоне или компьютере. Поэтому, посмотрите его, если пропустили или уже забыли.

Реле SRD-05VDC-SL-C. Урок 15. Ардуино

А сегодня мы повторим предыдущий урок, но вместо bluetooth модуля используем подключение через ethernet. Напишем сервер, к которому можно будет подключиться из браузера. И простую веб страницу, на которой можно будет зажигать свет.

Для того, чтобы выполнить этот урок нам понадобиться

  • Ардуино UNO
  • Макетная плата
  • Перемычки
  • Ethernet Shield
  • Реле SRD-05VDC-SL-C
  • Лампа на 220 вольт и патрон к ней
  • Ethernet провод
  • Кабель USB

Об электромагнитном реле мы в прошлый раз мы говорили более подробно. В этом плане сегодняшний проект не измениться. Нам нужно получить на Ардуино управляющий сигнал. И в зависимости от него, включить или выключить реле.

Управляющий сигнал будем получать от платы расширения Ethernet shield и веб страницы, которая будет генерироваться внутри кода. Когда пользователь нажмет на кнопку, чтобы включить свет, сервер получит данные и использует, для управления реле.

Ethernet Shield

В нашем распоряжении оказался ethernet shield hanrun hr91105a или w5100. Он имеет форм фактор для подключения к плате Ардуино Uno.

Он предоставляет доступ к TCP и UDP стекам. А библиотека для работы с ethernet shield позволяет быстро подключить устройство и настроить скетч.

Контакты сверху платы позволяют подключать дополнительные устройства и использовать контакты Ардуино как обычно.

Имейте в виду, при подключении платы, пины 4, 10, 11, 12 и 13 используются для взаимодействия платы с Ардуино. Использовать их для других устройств уже нельзя.

Так же на плате есть слот для карты micro-SD. С его помощью можно сохранять необходимую информацию на карту памяти. Или загружать на нее веб страницы. Памяти внутри Ардуино хватит только на небольшую страницу с парой кнопок.

На плате расширения есть несколько индикаторных светодиодов

  • PWR: показывает, что платы подключены к питанию
  • LINK: показывает, подключение к сетевому устройству и мигает когда плата получает или отправляет данные
  • FULLD: показывает, что интернет соединение full duplex
  • 100M: показывает, что скорость соединения поддерживает 100 Mb/s (а не 10 Mb/s)
  • RX: мигает, когда плата получает данные
  • TX: мигает, когда плата отправляет данные
  • COLL: мигает, когда обнаружены интернет коллизии

Принципиальная схема

Подключим Ethernet shield к материнской плате Ардуино. А электромагнитное реле уже к плате расширения. Используем питание 5 вольт и землю. А для управление реле возьмем 7 цифровой пин.

Принципиальная схема подключения Ethernet shield и реле
Принципиальная схема подключения Ethernet shield и реле

Программа

Смысл проекта такой же как и с bluetooth. Плата должна получить от нас сигнал и установить реле в нужное состояние. Тогда подключенное к реле оборудование включится или выключится соответственно.

Используем пример из библиотеки Ethernet.

Откроем скетч из Меню File -> Examples -> Ethernet -> WebServer

Здесь используются библиотеки <SPI.h> и <Ethernet.h>

Вы можете задать mac адрес и ip адрес для вашей платы. Ip адрес должен подходить для вашей локальной сети. HTTP сервер будет работать на 80 порту как обычно. А реле подключим к 7 пину.

// 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, 0, 177);
EthernetServer server(80);
int RelayPin = 7; 

В функции setup() настраиваем все необходимые функции для работы через интернет. И раскомментируем строку Ethernet.init(10);

  // You can use Ethernet.init(pin) to configure the CS pin
  Ethernet.init(10);  // Most Arduino shields

Настроим пин для реле на вывод и выключим его.

  // start the server
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());

  pinMode(RelayPin, OUTPUT);
  digitalWrite(RelayPin, 0);

Теперь разберемся с циклом loop(). Каждый раз, когда к серверу подключается новый клиент, мы должны передать ему веб страницу с необходимой информацией. Используем монитор последовательного порта для отладки программы. Информацию от клиента мы будем получать через http заголовки и для этого считаем всю информацию, которую мы можем получить при соединении к серверу.

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;
    String readString = "";
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        
        readString += c;

Таким образом мы получили строку, в которой будет вся имеющаяся информация. В том числе о хосте, рефферере и данных о браузере. Из-за того, что данные в рефферере и хосте будут дублироваться, а нам нужна только строка хоста, уберем лишнюю информацию.

        //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) {

          readString.replace("http://192.168.0.177/LightOff?", "refferer");
          readString.replace("http://192.168.0.177/LightOn?", "refferer");
          
          Serial.println(readString);

Теперь мы можемиспользовать информацию о состоянии реле и сформировать нужную веб страницу для пользователя.

          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println("Connection: close");  // the connection will be closed after completion of the response
          client.println();
      
          client.println("<!DOCTYPE HTML>");
          client.println("<html>");
          // output the value of each analog input pin
          
          if(readString.indexOf("LightOn") > 0) {
            digitalWrite(RelayPin, 1);
          } else {
            digitalWrite(RelayPin, 0);
          }

          int Relay = digitalRead(RelayPin);
          String ButtonText = "";
          String ButtonLink = "";
          
          if( Relay ){
            ButtonText = " LightOff ";
            ButtonLink = "/LightOff";
          } else {
            ButtonText = " LightOn ";
            ButtonLink = "/LightOn";
          }
          
          client.print("<div style='height: 100vh;width: 100%;border: 1px solid black;'><h1 style='text-align:center;'>Relay is ");
          client.print(Relay);
          client.println("</h1><br />");

          client.print("<div style='text-align:center;'><form action='");
          client.print(ButtonLink);
          client.print("'> <input type='submit' style='box-shadow:inset 0px -3px 7px 0px #29bbff;background:linear-gradient(to bottom, #2dabf9 5%, #0688fa 100%);background-color:#2dabf9;border-radius:3px;border:1px solid #0b0e07;display:inline-block;cursor:pointer;color:#ffffff;font-family:Arial;font-size:15px;padding:9px 23px;text-decoration:none;text-shadow:0px 1px 0px #263666;' value='");
          client.print(ButtonText);
          client.print("' /></div></form>");
          
          client.println("</div></html>");

          break;

В итоге получим кнопку со ссылкой на включение реле, если реле выключено. И наоборот, на выключение, если свет включен в настоящий момент.

Полный текст программы

#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, 0, 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);

int RelayPin = 7; 

void setup() {
  // You can use Ethernet.init(pin) to configure the CS pin
  Ethernet.init(10);  // Most Arduino shields
  //Ethernet.init(5);   // MKR ETH shield
  //Ethernet.init(0);   // Teensy 2.0
  //Ethernet.init(20);  // Teensy++ 2.0
  //Ethernet.init(15);  // ESP8266 with Adafruit Featherwing Ethernet
  //Ethernet.init(33);  // ESP32 with Adafruit Featherwing Ethernet

  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  Serial.println("Ethernet WebServer Example");

  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip);

  // Check for Ethernet hardware present
  if (Ethernet.hardwareStatus() == EthernetNoHardware) {
    Serial.println("Ethernet shield was not found.  Sorry, can't run without hardware. :(");
    while (true) {
      delay(1); // do nothing, no point running without Ethernet hardware
    }
  }
  if (Ethernet.linkStatus() == LinkOFF) {
    Serial.println("Ethernet cable is not connected.");
  }

  // start the server
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());

  pinMode(RelayPin, OUTPUT);
  digitalWrite(RelayPin, 0);
}


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;
    String readString = "";
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        
        readString += c;
        
        //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) {

          readString.replace("http://192.168.0.177/LightOff?", "refferer");
          readString.replace("http://192.168.0.177/LightOn?", "refferer");
          
          Serial.println(readString);
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println("Connection: close");  // the connection will be closed after completion of the response
          client.println();
      
          client.println("<!DOCTYPE HTML>");
          client.println("<html>");
          // output the value of each analog input pin
          
          if(readString.indexOf("LightOn") > 0) {
            digitalWrite(RelayPin, 1);
          } else {
            digitalWrite(RelayPin, 0);
          }

          int Relay = digitalRead(RelayPin);
          String ButtonText = "";
          String ButtonLink = "";
          
          if( Relay ){
            ButtonText = " LightOff ";
            ButtonLink = "/LightOff";
          } else {
            ButtonText = " LightOn ";
            ButtonLink = "/LightOn";
          }
          
          client.print("<div style='height: 100vh;width: 100%;border: 1px solid black;'><h1 style='text-align:center;'>Relay is ");
          client.print(Relay);
          client.println("</h1><br />");

          client.print("<div style='text-align:center;'><form action='");
          client.print(ButtonLink);
          client.print("'> <input type='submit' style='box-shadow:inset 0px -3px 7px 0px #29bbff;background:linear-gradient(to bottom, #2dabf9 5%, #0688fa 100%);background-color:#2dabf9;border-radius:3px;border:1px solid #0b0e07;display:inline-block;cursor:pointer;color:#ffffff;font-family:Arial;font-size:15px;padding:9px 23px;text-decoration:none;text-shadow:0px 1px 0px #263666;' value='");
          client.print(ButtonText);
          client.print("' /></div></form>");
          
          client.println("</div></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");
  }
}

Если все настроено правильно, то зайдя по адресу указанному в настройках IPAddress ip(192, 168, 0, 177) мы увидим веб страницу.

И нажав на кнопку мы сможем управлять реле, соединенным с платой Ардуино.

Web страница на Ардуино
Web страница на Ардуино
Управление светом через интернет на Ардуино
Управление светом через интернет на Ардуино

Заключение

Мы использовали Ethernet shield для Ардуино, чтобы подключить устройство к интернету. И настроили управление светом через веб страницу сгенерированную на Ардуино.

Естественно, вы можете использовать такую схему для управления любыми устройствами. А использование электромагнитного реле дает возможность включать и выключать электрические приборы с любой нагрузкой.

Похожее

Tags

  • Интернет вещей

Навигация по записям

Bluetooth чат на Ардуино. Проекты. Ардуино
Датчик влажности почвы. Датчики. Ардуино

Share your thoughts Отменить ответ

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Новое видео на канале

https://youtu.be/bvzX-edTdS0

Свежие записи

  • Много кнопок на одном пине. Урок 20. Ардуино
  • Как управлять Ардуино ДУ пультом. Проекты. Ардуино
  • ИК приемник KY-022. Датчики. Ардуино
  • Фоторезистор KY-018. Датчики. Ардуино
  • Пульсометр KY-039. Датчики. Ардуино

Метки

  • Bluetooth
  • RGB Светодиоды
  • WIFI
  • Двигатели
  • Звук
  • Игры
  • Интернет вещей
  • Лего
  • Основное
  • Программирование
  • Уроки

Купить стартовый набор Ардуино UNO на Aliexpress

Стартовый набор Ардуино Уно

Купить набор датчиков для Ардуино 45 штук на Aliexpress

набор датчиков для Ардуино

arcadepub

Hi there! How to control button debounce without c Hi there! How to control button debounce without code. Lets see.

Please subscribe to my instagram and youtube channel as well.

#arcadepub #diy #doityourself #learn #smarthome #ардуино #аркадныйпаб #сделайсам #умныйдом #arduino #circuit #arduinoproject
Hello there! Let's write a program to control ard Hello there!  Let's write a program to control arduino by ir.

Please subscribe to my instagram and youtube channel as well.

#arcadepub #diy #doityourself #learn #smarthome #ардуино #аркадныйпаб #сделайсам #умныйдом #arduino #circuit #arduinoproject
Hey! How are you doing? How do you think, we can c Hey! How are you doing? How do you think, we can control arduino program by ir? I bet we can. 

Please subscribe to my instagram and youtube channel as well.

#arcadepub #diy #doityourself #learn #smarthome #ардуино #аркадныйпаб #сделайсам #умныйдом #arduino #circuit #arduinoproject
Hello! There is a second video on my youtube chann Hello! There is a second video on my youtube channel. I've just added subtitles, so you can see how to use if and else structures and for() loop in arduino program. Enjoy, and do NOT forget to subscribe. 
https://youtu.be/8AHfAQyNAqU

#arcadepub #diy #doityourself #learn #smarthome #ардуино #аркадныйпаб #сделайсам #умныйдом #arduino #circuit #youtube
Hi there! How is it going? Photo resistor and lase Hi there! How is it going? Photo resistor and laser are here. Look at graphics and try to understand how it works!

Please subscribe to my instagram and youtube channel as well.

#arcadepub #diy #doityourself #learn #smarthome #ардуино #аркадныйпаб #сделайсам #умныйдом #arduino #circuit #arduinoproject
Here is ky-039 heart beat arduino module. Do you l Here is ky-039 heart beat arduino module. Do you like it? Write in the comments below!

Please subscribe to my instagram and youtube channel as well.

#arcadepub #diy #doityourself #learn #smarthome #ардуино #аркадныйпаб #сделайсам #умныйдом #arduino #circuit #arduinoproject
Its Magic lights with ky-027 arduino module. Do yo Its Magic lights with ky-027 arduino module. Do you like it?  Write in the comments below!

Please subscribe to my instagram and youtube channel as well.

#arcadepub #diy #doityourself #learn #smarthome #ардуино #аркадныйпаб #сделайсам #умныйдом #arduino #circuit #arduinoproject
Arduino and #laser are together. Please subscribe Arduino and #laser are together.

Please subscribe to my instagram and youtube channel as well.

#arcadepub #diy #doityourself #learn #smarthome #ардуино #аркадныйпаб #сделайсам #умныйдом #arduino #circuit #arduinoproject
Do you know how gyroscope modul works with arduino Do you know how gyroscope modul works with arduino? 

Please subscribe to my instagram and youtube channel as well.

#arcadepub #diy #doityourself #learn #smarthome #ардуино #аркадныйпаб #сделайсам #умныйдом #arduino #circuit #rfid #arduinoproject
Do you know how you can use rfid module with ardui Do you know how you can use rfid module with arduino? 

Please subscribe to my instagram and youtube channel as well.

#arcadepub #diy #doityourself #learn #smarthome #ардуино #аркадныйпаб #сделайсам #умныйдом #arduino #circuit #rfid #arduinoproject
It is almost done Please subscribe to my youtube It is almost done

Please subscribe to my youtube channel as well.

#arcadepub #diy #doityourself #learn #smarthome #ардуино #аркадныйпаб #сделайсам #умныйдом #arduino #circuit #flower #autowatering #arduinoproject #robot #spiderbot
Begin to make a spider bot. Please subscribe to Begin to make a spider bot. 

Please subscribe to my youtube channel as well.

#arcadepub #diy #doityourself #learn #smarthome #ардуино #аркадныйпаб #сделайсам #умныйдом #arduino #circuit #flower #autowatering #arduinoproject #robot #spiderbot
Hello folks! There are 1000 of us on my instagram Hello folks! There are 1000 of us on my instagram account. And i want to tell thanks to each of you!
I'd like to tell more about this project. And that's why i made a video on youtube channel. 
It is in russian, but i have added english subtitles. 
I'm gonna tell you about many intriguing Arduino projects.
So, please, take a look at video. And subscribe to my youtube channel as well. 

#arcadepub #diy #doityourself #learn #smarthome #ардуино #аркадныйпаб #сделайсам #умныйдом #arduino #circuit #flower #autowatering
How can we know that flower needs to be watered. L How can we know that flower needs to be watered. Like and Subscribe to know more.

#arcadepub #diy #doityourself #learn #smarthome #ардуино #аркадныйпаб #сделайсам #умныйдом #arduino #circuit #flower #autowatering
How to turn light on by clapping. Like and Subscri How to turn light on by clapping. Like and Subscribe to know more.

#arcadepub #diy #doityourself #learn #smarthome #ардуино #аркадныйпаб #сделайсам #умныйдом #arduino #circuit
Is it possible to turn light on over the internet? Is it possible to turn light on over the internet? Like and Subscribe to know more.

#arcadepub #diy #doityourself #learn #smarthome #ардуино #аркадныйпаб #сделайсам #умныйдом #arduino #circuit
Is communicating vessels for light impossible? Pro Is communicating vessels for light impossible? Probably not. Like and Subscribe to know more.

#arcadepub #diy #doityourself #learn #smarthome #ардуино #аркадныйпаб #сделайсам #умныйдом #arduino #circuit
#ky-033 line tracking #arduino sensor. How does #ky-033 line tracking #arduino sensor. How does it work? It is really simple to know. Like and Subscribe to know more.

#arcadepub #diy #doityourself #learn #smarthome #ардуино #аркадныйпаб #сделайсам #умныйдом #arduino #circuit
Do you want to know how #wifi module #esp01 for #a Do you want to know how #wifi module #esp01 for #arduino works? Write in the comments below and subscribe.

#arcadepub #diy #doityourself #learn #smarthome #ардуино #аркадныйпаб #сделайсам #умныйдом #arduino #circuit
#ky-036 metal touch #arduino sensor. How does it w #ky-036 metal touch #arduino sensor. How does it work? It is really simple to know.

#arcadepub #diy #doityourself #learn #smarthome #ардуино #аркадныйпаб #сделайсам #умныйдом #arduino #circuit
Загрузи больше…

ArcadePUB @ 2020

arduino@arcadepub.ru

На сайте вы найдете уроки, проекты и обзоры всего, что связано с ардуино.

Аркадные игры и автоматы.

DIY проекты

Метки

  • Bluetooth
  • RGB Светодиоды
  • WIFI
  • Двигатели
  • Звук
  • Игры
  • Интернет вещей
  • Лего
  • Основное
  • Программирование
  • Уроки

Свежие записи

  • Много кнопок на одном пине. Урок 20. Ардуино
  • Как управлять Ардуино ДУ пультом. Проекты. Ардуино
  • ИК приемник KY-022. Датчики. Ардуино
  • Фоторезистор KY-018. Датчики. Ардуино
  • Пульсометр KY-039. Датчики. Ардуино

Навигация

  • Главная
  • Уроки
  • Датчики
  • Проекты
  • Справочник языка Ардуино
  • Справочник
  • Видео
  • Контакты
  • Поддержать

Дополнительно

Поддержать

Контакты

YouTube
Patreon
VK
Instagram
Twitter