Arduino Nano ESP32 - Ethernet

Este guia mostra como conectar o Arduino Nano ESP32 à internet ou à sua rede local usando o módulo Ethernet W55010. Você vai aprender o seguinte:

Ethernet do Arduino Nano ESP32

Hardware Necessário

1×Arduino Nano ESP32
1×Cabo USB Tipo-A para Tipo-C (para PC com USB-A)
1×Cabo USB Tipo-C para Tipo-C (para PC com USB-C)
1×W5500 Ethernet Module
1×Ethernet Cable
1×Fios Jumper
1×Protoboard
1×(Recomendado) Placa de Expansão com Bornes de Parafuso para Arduino Nano
1×(Recomendado) Placa de Expansão Breakout para Arduino Nano
1×(Recomendado) Divisor de Alimentação para Arduino Nano ESP32

Or you can buy the following kits:

1×DIYables Sensor Kit (18 sensors/displays)
Divulgação: Alguns dos links desta seção são links de afiliado da Amazon. Podemos receber uma comissão pelas compras feitas por meio desses links, sem custo adicional para você. Agradecemos o seu apoio.

Sobre o módulo Ethernet W5500

O módulo Ethernet W550io tem dois tipos de conexões:

  • Interface RJ45: Conecte-a a um roteador ou switch usando um cabo Ethernet.
  • Interface SPI: Use-a para ligar a uma placa Arduino Nano ESP32. Ela inclui 10 pinos:
    • Pino NC: Deixe este pino desconectado.
    • Pino INT: Deixe este pino desconectado.
    • Pino RST: Este é o pino de reset; conecte-o ao pino RST do Arduino Nano ESP32.
    • Pino GND: Conecte-o ao pino GND do Arduino Nano ESP32.
    • Pino 5V: Não conecte este pino.
    • Pino 3.3V: Conecte-o ao pino 3.3V do Arduino Nano ESP32.
    • Pino MISO: Conecte-o ao pino SPI MISO do Arduino Nano ESP32.
    • Pino MOSI: Conecte-o ao pino SPI MOSI do Arduino Nano ESP32.
    • Pino SCS: Conecte-o ao pino SPI CS do Arduino Nano ESP32.
    • Pino SCLK: Conecte-o ao pino SPI SCK do Arduino Nano ESP32.
    Pinagem do módulo Ethernet
    image source: diyables.io

Diagrama de Ligação entre o Arduino Nano ESP32 e o módulo Ethernet W5500

Diagrama de ligação do Arduino Nano ESP32 com módulo Ethernet

This image is created using Fritzing. Click to enlarge image

image source: diyables.io

Código Arduino Nano ESP32 para o Módulo Ethernet - Fazendo uma requisição HTTP via Ethernet

Este código funciona como um cliente web. Ele envia requisições HTTP ao servidor web em http://example.com/.

/* * Este código de Arduino Nano ESP32 foi desenvolvido por pt.newbiely.com * Este código de Arduino Nano ESP32 é disponibilizado ao público sem nenhuma restrição. * Para tutoriais completos e diagramas de ligação, visite: * https://pt.newbiely.com/tutorials/arduino-nano-esp32/arduino-nano-esp32-ethernet */ #include <SPI.h> #include <Ethernet.h> // replace the MAC address below by the MAC address printed on a sticker on the Arduino Shield 2 byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xEF }; EthernetClient client; int HTTP_PORT = 80; String HTTP_METHOD = "GET"; // or POST char HOST_NAME[] = "example.com"; String PATH_NAME = "/"; void setup() { Serial.begin(9600); delay(1000); Serial.println("Arduino Nano ESP32 - Ethernet Tutorial"); // initialize the Ethernet shield using DHCP: if (Ethernet.begin(mac) == 0) { Serial.println("Failed to obtaining an IP address"); // check for Ethernet hardware present if (Ethernet.hardwareStatus() == EthernetNoHardware) Serial.println("Ethernet shield was not found"); // check for Ethernet cable if (Ethernet.linkStatus() == LinkOFF) Serial.println("Ethernet cable is not connected."); while (true) ; } // connect to web server on port 80: if (client.connect(HOST_NAME, HTTP_PORT)) { // if connected: Serial.println("Connected to server"); // make a HTTP request: // send HTTP header client.println(HTTP_METHOD + " " + PATH_NAME + " HTTP/1.1"); client.println("Host: " + String(HOST_NAME)); client.println("Connection: close"); client.println(); // end HTTP header while (client.connected()) { if (client.available()) { // read an incoming byte from the server and print it to serial monitor: char c = client.read(); Serial.print(c); } } // the server's disconnected, stop the client: client.stop(); Serial.println(); Serial.println("disconnected"); } else { // if not connected: Serial.println("connection failed"); } } void loop() { }

Passos Rápidos

Para começar com o Arduino Nano ESP32, siga estes passos:

  • Se você é novo no Arduino Nano ESP32, consulte o tutorial sobre como configurar o ambiente para o Arduino Nano ESP32 na Arduino IDE.
  • Conecte o Arduino Nano ESP32 ao módulo Ethernet de acordo com o diagrama fornecido.
  • Conecte o módulo Ethernet ao seu roteador ou switch usando um cabo Ethernet.
  • Conecte a placa Arduino Nano ESP32 ao seu computador usando um cabo USB.
  • Abra a Arduino IDE no seu computador.
  • Selecione a placa Arduino Nano ESP32 e a porta COM correspondente.
  • Clique no ícone Libraries na barra esquerda da Arduino IDE.
  • Pesquise “Ethernet”, depois encontre a biblioteca Ethernet de Various
  • Clique no botão Install para instalar a biblioteca Ethernet.
Biblioteca Ethernet para Arduino Nano ESP32
  • Abra o Serial Monitor na Arduino IDE.
  • Copie o código fornecido e cole-o na Arduino IDE.
  • Pressione o botão Upload na Arduino IDE para enviar o código ao Arduino Nano ESP32.
  • Confira o Serial Monitor, que exibirá a saída como abaixo.
∞
Newbiely | Arduino IDE 2.3.8
──
☐
✕
File
Edit
Sketch
Tools
Help
Arduino Nano ESP32
Newbiely.ino
···
8 Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'Arduino Nano ESP32' on 'COM15')
New Line
9600 baud
Arduino Nano ESP32 - Ethernet Tutorial Connected to server HTTP/1.1 200 OK Accept-Ranges: bytes Age: 208425 Cache-Control: max-age=604800 Content-Type: text/html; charset=UTF-8 Date: Fri, 12 Jul 2024 07:08:42 GMT Etag: "3147526947" Expires: Fri, 19 Jul 2024 07:08:42 GMT Last-Modified: Thu, 17 Oct 2019 07:18:26 GMT Server: ECAcc (lac/55B8) Vary: Accept-Encoding X-Cache: HIT Content-Length: 1256 Connection: close <!doctype html> <html> <head> <title>Example Domain</title> <meta charset="utf-8" /> <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> </head> <body> <div> <h1>Example Domain</h1> <p>This domain is for use in illustrative examples in documents. You may use this domain in literature without prior coordination or asking for permission.</p> <p><a href="https://www.iana.org/domains/example">More information...</a></p> </div> </body> </html> disconnected
Ln 11, Col 1
Arduino Nano ESP32 on COM15
2

※ Nota:

Se outro dispositivo na mesma rede tiver o mesmo endereço MAC, isso pode causar problemas.

Código Arduino Nano ESP32 para o Módulo Ethernet - Servidor Web

O código abaixo transforma o Arduino Nano ESP32 em um servidor web. Este servidor envia uma página web simples para os navegadores.

/* * Este código de Arduino Nano ESP32 foi desenvolvido por pt.newbiely.com * Este código de Arduino Nano ESP32 é disponibilizado ao público sem nenhuma restrição. * Para tutoriais completos e diagramas de ligação, visite: * https://pt.newbiely.com/tutorials/arduino-nano-esp32/arduino-nano-esp32-ethernet */ #include <SPI.h> #include <Ethernet.h> // replace the MAC address below by the MAC address printed on a sticker on the Arduino Shield 2 byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xEF }; EthernetServer server(80); void setup() { Serial.begin(9600); delay(1000); Serial.println("Arduino Nano ESP32 - Ethernet Tutorial"); // initialize the Ethernet shield using DHCP: if (Ethernet.begin(mac) == 0) { Serial.println("Failed to obtaining an IP address"); // check for Ethernet hardware present if (Ethernet.hardwareStatus() == EthernetNoHardware) Serial.println("Ethernet shield was not found"); // check for Ethernet cable if (Ethernet.linkStatus() == LinkOFF) Serial.println("Ethernet cable is not connected."); while (true) ; } server.begin(); Serial.print("Arduino Nano ESP32 - Web Server IP Address: "); 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 bool 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"); // the connection will be closed after completion of the response client.println(); client.println("<!DOCTYPE HTML>"); client.println("<html>"); client.println("<body>"); client.println("<h1>Arduino Nano ESP32 - Web Server with Ethernet</h1>"); client.println("</body>"); 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"); } }

Passos Rápidos

  • Copie o código fornecido e cole-o na Arduino IDE.
  • Clique no botão Upload na Arduino IDE para enviar o código à sua placa Arduino Nano ESP32.
  • Verifique o Serial Monitor para ver os resultados, como mostrado.
∞
Newbiely | Arduino IDE 2.3.8
──
☐
✕
File
Edit
Sketch
Tools
Help
Arduino Nano ESP32
Newbiely.ino
···
8 Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'Arduino Nano ESP32' on 'COM15')
New Line
9600 baud
Arduino Nano ESP32 - Ethernet Tutorial Arduino Nano ESP32 - Web Server IP Address: 192.168.0.2
Ln 11, Col 1
Arduino Nano ESP32 on COM15
2
  • Digite o endereço IP fornecido na barra de endereços do seu navegador. Você verá uma página web simples exibida pelo Arduino Nano ESP32.
Servidor Web Ethernet do Arduino Nano ESP32

Tutoriais Relacionados

※ NOSSAS MENSAGENS

  • Fique à vontade para compartilhar o link deste tutorial. Porém, por favor, não use nosso conteúdo em outros sites. Investimos muito esforço e tempo para criar este conteúdo, por favor respeite nosso trabalho!