Como conectar seu Arduino UNO/Nano à internet usando o módulo Ethernet W5100 (2023)

Print 🖨 PDF 📄

Tempo de leitura: 7 minutes

A maioria dos dispositivos IoT conectados hoje estão conectados à Internet por meio de uma conexão wi-fi. Embora uma conexão Wi-Fi permita o acesso remoto à Internet, ela tem suas próprias limitações. Por exemplo, na maioria das aplicações industriais para um dispositivo estacionário, a Ethernet geralmente é escolhida em vez da conexão Wi-Fi simplesmente porque é mais confiável e segura. Além disso, como a Ethernet é uma conexão com fio, ela oferece melhor velocidade e menor latência. Já trabalhamos em muitos projetos de IoT, a maioria dos quais foi construída em torno de ESP8266, ESP32 ou Raspberry Pi. Como sabemos, esses dispositivos têm um modem Wi-Fi embutido que permite que você se conecte à internet. Mas se você está trabalhando com uma humilde placa Arduino UNO ou Nano e deseja conectar seu Arduino à Internet, então você tem duas opções populares. Uma opção é usar um ESP8266 com Arduino e a segunda opção é conectar um módulo Ethernet com Arduino.

Neste projeto, vamos usar a última opção para controlar um LED pela Internet fazendo a interface do Arduino com o módulo Ethernet W5100. O módulo Ethernet é usado para estabelecer a comunicação entre o computador e o Arduino em uma LAN ou rede com fio. Este artigo foi escrito presumindo que o leitor tenha um conhecimento básico de rede de computadores, o que inclui o conhecimento de como conectar computadores ao hub/roteador com cabos RJ45, endereços IP e MAC, etc.

Conteudo

Módulo Ethernet W5100

Como conectar seu Arduino UNO/Nano à internet usando o módulo Ethernet W5100 (1)

Estamos usando o módulo Ethernet W5100. É um módulo habilitado para internet com um único chip e recursos completos para estabelecer uma conexão com a internet. Em termos simples, este módulo permite que a placa Arduino se conecte à Internet. Ao utilizar este módulo, podemos completar a ligação à internet sem o suporte de um Sistema Operacional. Ele também oferece suporte a protocolos TCP/IP com fio como TCP, PPPoE, Ethernet, UDP, ICMP, IPv4, etc. Ele oferece suporte aos modos de operação full-duplex e half-duplex. Ele suporta conexões ADSL e até quatro conexões de soquete simultâneas.

O módulo Ethernet também usa a biblioteca Arduino Ethernet para escrever esboços que se conectam à Internet usando este módulo. Ele se encaixa em todas as versões do Arduino como UNO, NANO, mega 1280, mega 2560 e outros. O funcionamento e a funcionalidade do módulo Ethernet W5100 são muito semelhantes aos de um escudo Ethernet Arduino, o que significa que você pode fazer tudo o que quiser com um escudo Ethernet Arduino. Como vantagem, custa metade do preço de um shield.

Como conectar seu Arduino UNO/Nano à internet usando o módulo Ethernet W5100 (2)

Diagrama de circuito para conectar o módulo Ethernet Arduino W5100

Como conectar seu Arduino UNO/Nano à internet usando o módulo Ethernet W5100 (3)

O circuito consiste em Arduino Nano e Módulo Ethernet W5100 (este projeto também seria possível com Ethernet Arduino Shield e Arduino UNO). A conexão entre os módulos Arduino e Ethernet é feita conforme mostrado no diagrama de circuito.

  • Conecte os pinos 5V e GND do Arduino Nano aos pinos +5 e G do Módulo Ethernet, respectivamente (essas conexões fornecem energia para o Módulo Ethernet).
  • Conecte os pinos 9, 10, 11,12 e 13 do Arduino a R, SS, MO, MI, CK do módulo Ethernet respectivamente (estes fazem a comunicação entre Arduino e Ethernet sobre SPI).

Código Arduino para obter dados do Módulo Ethernet W5100

O arquivo de cabeçalho SPI é incluído para usar os protocolos de comunicação com o módulo Ethernet.

#include <SPI.h>

O arquivo de cabeçalho Ethernet tem a biblioteca para rodar webclient/webserver sobre Ethernet.

#include <Ethernet.h>

O endereço físico Mac é definido para o módulo Ethernet.

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

O número 192.168.0.12 é o endereço IP. Onde “0” depende do host (gateway padrão) da rede à qual você está conectado, verifique isso executando ipconfig no prompt de comando.

byte ip[] = { 192, 168, 0, 12 }; byte gateway[] = { 192, 168, 0, 12 }; byte subnet[] = { 255, 255, 255, 0 };

Como conectar seu Arduino UNO/Nano à internet usando o módulo Ethernet W5100 (4)

Como conectar seu Arduino UNO/Nano à internet usando o módulo Ethernet W5100 (5)

Apenas para referência, este gateway padrão de uma rede diferente é mostrado abaixo.

Como conectar seu Arduino UNO/Nano à internet usando o módulo Ethernet W5100 (6)

Isso cria um servidor local na porta 80 que pode ser acessado posteriormente pelos clientes.

EthernetServer server(80);

Isso lê a resposta do cliente quando o usuário acessa o servidor web.

String readString;

A função de configuração inicializa o pino do LED para saída e inicializa o módulo Ethernet com os parâmetros fornecidos (endereço Mac, endereço IP, gateway, máscara de sub-rede) e, finalmente, o servidor é iniciado pela função “server.begin()”

int ledPin = 2;void setup(){ pinMode(ledPin, OUTPUT); Ethernet.begin(mac, ip, gateway, subnet); server.begin(); }

Na função de loop, criamos uma conexão de cliente e verificamos se alguém está tentando acessar o endereço IP atribuído por meio de um navegador.

void loop(){ EthernetClient client = server.available(); if (client) { while (client.connected()) { if (client.available()) {

Se conectado, continue verificando se o cliente está enviando alguma mensagem de volta ao servidor

char c = client.read();

Em seguida, leia a resposta HTTP caractere por caractere e armazene os caracteres na variável readString definida pelo usuário.

if (readString.length() < 100) { readString += c;}

Se a solicitação HTTP foi encerrada – 0x0D é Carriage Return \n ASCII

if (c == 0x0D) {

Assim que recebermos uma resposta OK, começamos a exibir a página da web, e abaixo está o código HTML.

client.println("HTTP/1.1 200 OK");client.println("Content-Type: text/html");client.println();client.println("<HTML>");client.println("<HEAD>");client.println("<TITLE> ARDUINO ETHERNET</TITLE>");client.println("</HEAD>");client.println("<BODY>");client.println("<hr>");client.println("<H1 style=\"color:green;text-align:center\">ARDUINO ETHERNET LED CONTROL</H1>");client.println("<hr>");client.println("<br>");

Quando o usuário clica no hiperlink LIGAR LED, ele/ela é redirecionado para a URL \?LEDON, que acende ainda mais o LED.

client.println("<H2 style=\"text-align:center\"><a href=\"/?LEDON\"\">Ligar LED</a><br></H2>");

Semelhante ao código acima, isso redireciona o usuário para a URL “DESLIGAR LED”.

client.println("<H2 style=\"text-align:center\"><a href=\"/?LEDOFF\"\">Turn Off LED</a><br></H2>");

Parte restante do código HTML-

client.println("<br>");client.println("</BODY>");client.println("</HTML>");delay(10);client.stop();

Controle o pino do Arduino para ligar e desligar o LED dependendo da URL para a qual os usuários são redirecionados.

if(readString.indexOf("?LEDON") > -1) { digitalWrite(ledPin, HIGH);} else { if(readString.indexOf("?LEDOFF") > -1) { digitalWrite(ledPin, LOW); }}

limpar string para a próxima leitura

 readString=""; } } } }}

Conectando o Arduino ao PC ou porta Ethernet do roteador

Para conectar os dois (PC e Arduino) juntos, precisamos de um cabo adequado (cabo cruzado CAT-6) se a porta Ethernet do PC não tiver sensor de direção automática. Caso o seu PC suporte detecção direta automática, basta conectar um cabo comum que vem com o roteador.

Como conectar seu Arduino UNO/Nano à internet usando o módulo Ethernet W5100 (7)

Como conectar seu Arduino UNO/Nano à internet usando o módulo Ethernet W5100 (8)

Neste cabo especial TX+/TX- e RX+/RX- são trocados.

Em qualquer caso, se você não tem uma porta Ethernet em seu PC ou não quer comprar um cabo especial, você pode seguir nosso método para conectar o módulo Ethernet a uma porta de rede LAN do roteador.

Como conectar seu Arduino UNO/Nano à internet usando o módulo Ethernet W5100 (9)

LED piscando na Internet usando o módulo Ethernet no Arduino

Depois de fazer as conexões acima, conecte-se ao roteador usando seu PC ou telefone celular. Em seguida, abra qualquer navegador da web e vá para este URL “http://192.168.0.12” (no seu caso, digite seu endereço IP Ethernet que você configurou no código). Agora, você pode controlar o LED por meio da página da web. Quando o usuário clica em “Ligar LED” na página da web, o LED acende no circuito. Quando “DESLIGAR LED” é clicado, o LED é DESLIGADO no circuito. Este comando é executado usando a conexão com fio do módulo Ethernet. A página do servidor web é mostrada na figura abaixo.

Como conectar seu Arduino UNO/Nano à internet usando o módulo Ethernet W5100 (10)

Como conectar seu Arduino UNO/Nano à internet usando o módulo Ethernet W5100 (11)

Espero que você tenha gostado do projeto e aprendido a usar o módulo Ethernet W5100 com Arduino para enviar e receber dados pela internet. Se você tiver alguma dúvida, deixe-as na seção de comentários abaixo ou use nosso fórum de Eletrônicos.

Código

#include <SPI.h> //protocolo para se comunicar com o módulo ethernet#include <Ethernet.h> //biblioteca para executar cliente/servidor web sobre ethernetbyte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //endereço mac físico definido para o módulo ethernet/*o número 0 no endereço IP depende do host da rede à qual você está conectado, verifique isso executando ipconfig no prompt de comando*/byte ip[] = { 192, 168, 0, 12 }; // Endereço IP na LAN - precisa mudar de acordo com o seu endereço de redebyte gateway[] = { 192, 168, 0, 12 }; // acesso à internet via roteadorbyte subnet[] = { 255, 255, 255, 0 }; //máscara de sub-redeEthernetServer server(80); //porta onde o servidor pode ser acessadoString readString; // para ler a resposta do usuário / clienteint ledPin = 2; // Led está conectado ao pino 2void setup(){ pinMode(ledPin, OUTPUT); //pino selecionado para controlar //start Ethernet Ethernet.begin(mac, ip, gateway, subnet); //inicializar ethernet server.begin(); //inicie o servidor}void loop(){ // Crie uma conexão de cliente EthernetClient client = server.available(); // verifique se alguém tentou acessar o endereço IP atribuído em um navegador if (client) { // se conectado, continue verificando se o cliente está enviando alguma mensagem de volta ao servidor while (client.connected()) { if (client.available()) { char c = client.read(); // ler solicitação HTTP caractere por caractere if (readString.length() < 100) { // armazena caracteres em string readString += c; } //se a solicitação HTTP foi encerrada - 0x0D é Carriage Return \n ASCII if (c == 0x0D) { //exibir a página da web client.println("HTTP/1.1 200 OK"); //enviar nova página client.println("Content-Type: text/html"); client.println(); client.println("<HTML>"); client.println("<HEAD>"); client.println("<TITLE> ARDUINO ETHERNET</TITLE>"); client.println("</HEAD>"); client.println("<BODY>"); client.println("<hr>"); client.println("<H1 style=\"color:green;text-align:center\">ARDUINO ETHERNET LED CONTROL</H1>"); client.println("<hr>"); client.println("<br>"); //criando um link para redirecionar o usuário para ligar a luz client.println("<H2 style=\"text-align:center\"><a href=\"/?LEDON\"\">Ligar o LED</a><br></H2>"); //criando um link para redirecionar o usuário para desligar a luz client.println("<H2 style=\"text-align:center\"><a href=\"/?LEDOFF\"\">Desligue o LED</a><br></H2>"); client.println("<br>"); client.println("</BODY>"); client.println("</HTML>"); delay(10); // parando o cliente client.stop(); // controlar pin Arduino com URL if(readString.indexOf("?LEDON") > -1) // verifica o LEDON { digitalWrite(ledPin, HIGH); // definir o pino alto } else{ if(readString.indexOf("?LEDOFF") > -1) // verifica se há LEDOFF { digitalWrite(ledPin, LOW); // definir o pino baixo } } // limpar string para a próxima leitura readString=""; } } } }}

0 Compart.

FAQs

How do I connect my Arduino Nano to Ethernet? ›

Connect pin 5V and GND pins of Arduino Nano to +5 and G pin of Ethernet Module respectively (These connections supply power to the Ethernet Module). Connect pin 9, 10, 11,12, and 13 of Arduino to R, SS, MO, MI, CK of the Ethernet module respectively (These make the communication between Arduino and Ethernet over SPI).

How to connect Arduino Uno to Internet? ›

Setting your board
  1. Upload the sketch sample attached here to your Arduino UNO.
  2. Download Telnet Client for Android.
  3. Connect to your ESP8266 Wifi.
  4. Once connected, get the IP address.
  5. Open Telnet Client on Android phone.
  6. create connection by clicking connect , Add IP and port 80.

How do I connect my Arduino Ethernet shield to the internet? ›

The Arduino Ethernet Shield V1 connects your Arduino to the internet in mere minutes. Just plug this module onto your Arduino board, connect it to your network with an RJ45 cable (not included) and follow a few simple instructions to start controlling your world through the internet.

How to connect Arduino Uno to Nano? ›

  1. Step 1: Preparing Programmer. Attach your Arduino to PC. Now, go to.. File > Examples > ArduinoISP > ArduinoISP. ...
  2. Step 2: Preparing Arduino IDE. When wiring is done. Now we have to do some settings in IDE. Go to Tools > Board & select Arduino Nano. ...
  3. 4 People Made This Project!
  4. 39 Comments. VincentT57. 2 months ago.

Can Arduino connect to Ethernet? ›

The Arduino software includes a Wire library to simplify use of the TWI bus; see the documentation for details. For SPI communication, use the SPI library. The board also can connect to a wired network via ethernet.

Can Arduino Nano connect to Internet? ›

The board comes with Wi-Fi® connectivity and Arduino IoT Cloud compatibility. This allows you to create IoT applications in your own projects. The Nano 33 IoT is Bluetooth® enabled allowing you to control peripheral devices via bluetooth and start implementing Bluetooth® Low Energy applications.

How to connect Arduino to internet without WiFi? ›

Connecting via the Ethernet

The first option for connecting your Arduino to the internet is via an Ethernet cable. If you are using an Arduino board that comes with a built-in Ethernet port such as an Arduino Yún, then you can skip the 'Hardware requirements' section and the circuit design description given below.

How do I know if my Arduino is connected to the Internet? ›

In order to check if your board is connected to the Arduino IDE, you can go to Tools -> Port. It should show all the available COM ports. Now, you can disconnect your board. If one COM port disappears, then you can be sure that your board was connected and detected by the Arduino IDE.

Does Arduino need Internet connection? ›

The Arduino Software (IDE) makes it easy to write code and upload it to the board offline. We recommend it for users with poor or no internet connection.

Does Arduino Uno have Ethernet port? ›

The Arduino Ethernet is the same shape as the normal Arduino Uno, with headers to connect wires or shields. However, the Ethernet jack is a little taller than USB so if you want to plug in a shield, you may need to 'lift' it with some stacking headers.

How do I find my Arduino Ethernet shield IP address? ›

Go to Configuration Parameters > Hardware Implementation > Ethernet shield properties. The Arduino board by default gets its IP address through DHCP. Alternatively, you can assign a static IP address to the board by the selecting the Use static IP address and disable DHCP check box and specifying the IP address.

How do I connect my Arduino Nano to my computer? ›

It uses the Atmel ATmega 328P microprocessor chip.
  1. Install the required device driver. ...
  2. Install the Arduino programming environment. ...
  3. Connect your Arduino Nano via the USB cable to your Mac/PC. ...
  4. Start the Arduino Software. ...
  5. Select an Example Program. ...
  6. Compile the Example Program. ...
  7. Upload the Executable Program to the Nano.

What connection does Arduino Nano use? ›

The Arduino Nano is a small, complete, and breadboard-friendly board based on the ATmega328 (Arduino Nano 3.x). It has more or less the same functionality of the Arduino Duemilanove, but in a different package. It lacks only a DC power jack, and works with a Mini-B USB cable instead of a standard one.

How to connect Arduino Nano with WiFi module? ›

Learn How to Setup the Wifi Module ESP8266 by Using Just Arduino...
  1. Step 1: Turn on Your ESP8266 Module. Turn On Your ESP8266 Module by Using Arduino Nano 3.3V Dc Output Pin. ...
  2. Step 2: Schematic Diagram. ...
  3. Step 3: Open Arduino IDE. ...
  4. Step 4: Send at Commands to Your ESP8266 Module.

Why won t my Arduino Nano connect? ›

A common reason for the board not appearing on a port is a problem with the USB connection: The board needs to be connected to your computer with a data USB cable. Make sure the USB cable is not damaged. Test your cable with a different device, or try using a different cable.

What port should I use for Arduino Nano? ›

Overview. The Arduino Nano is a small, complete, and breadboard-friendly board based on the ATmega328 (Arduino Nano 3.x). It has more or less the same functionality of the Arduino Duemilanove, but in a different package. It lacks only a DC power jack, and works with a Mini-B USB cable instead of a standard one.

What cable is needed for Arduino Nano? ›

USB 2.0 Cable Type A/B.

Top Articles
Latest Posts
Article information

Author: Tyson Zemlak

Last Updated: 20/12/2023

Views: 5565

Rating: 4.2 / 5 (43 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Tyson Zemlak

Birthday: 1992-03-17

Address: Apt. 662 96191 Quigley Dam, Kubview, MA 42013

Phone: +441678032891

Job: Community-Services Orchestrator

Hobby: Coffee roasting, Calligraphy, Metalworking, Fashion, Vehicle restoration, Shopping, Photography

Introduction: My name is Tyson Zemlak, I am a excited, light, sparkling, super, open, fair, magnificent person who loves writing and wants to share my knowledge and understanding with you.