Conectar o Arduino à Internet com um Ethernet Shield VMA04 • AranaCorp (2023)

Etiquetas: Arduino, C/C++, Domótica

(0)

Em alguns projetos, especialmente na domótica, é interessante poder controlar uma placa Arduino pela Internet. Isso é possível com um shield Ethernet.

O shield usado neste tutorial é o VMA04, da Velleman. Você também pode utilizar outro shield, com configuração, pinos e biblioteca diferentes.

Atenção: o Shield VMA04 também existe na versão em kit para soldar KA04. Verifique qual versão deseja comprar.

Pré-requisitos: Conhecimento de HTML/CSS

Material

  • Computador
  • Arduino UNO
  • Cabo USB para ligar o Arduino ao computador
  • Cabo Ethernet
  • Shield Ethernet VMA04

Obs: Escrever uma página web pode tomar muito espaço de memória para uma placa Arduino. Nós usamos o Ethernet Shield VMA04 e uma placa Arduino UNO, mas se achar que a sua página tomará muita memória, opte por um shield W5100.

Visão geral do Ethernet Shield VMA04

Conectar o Arduino à Internet com um Ethernet Shield VMA04 • AranaCorp (1)

O Ethernet Shield VMA04 utiliza o Microchip ENC28J60. Ele usa:

  • os pinos 10 e 2 numa placa Arduino UNO.
  • para o conector ICSP: pinos 11, 12 e 13 numa placa Arduino UNO.

As ligações no caso de um shield são pré-definidas. Verifique a documentação técnica do componente para saber como utilizá-lo (VMA04 datasheet).

Configuração de rede

Para acessar a placa Arduino sem precisar conectá-la ao roteador de Internet, é necessário criar uma ponte entre a conexão WiFi e a conexão Ethernet no seu computador. Para isso, é preciso:

  • Conectar o shield VMA04 ao Arduino
  • Conectar o shield Ethernet ao computador (RJ45).
  • Abrir a Central de Rede e Compartilhamento.
  • Ir para “Alterar configurações da placa”.
  • Selecionar Ethernet(Arduino) e Wifi /(Internet source) e clicar com o botão direito do mouse.
  • Clicar em “Criar ponte”.

Exemplo de código para o Ethernet Shield VMA04

Para interagir com o Ethernet Shield VMA04, utilizamos a biblioteca UIPEthernet.h

  • Ethernet.begin() para iniciar uma conexão de rede.
  • server.begin() para inicializar um servidor.
  • EthernetClient client = server.available() para inicializar um cliente.
  • client.read() para ler dados do cliente.
  • client.print() para enviar dados para o cliente.

UIPEthernet.h

// Enter ip address http://192.168.1.179:80 in your browser// Based on WMA04 ethernet shield#include <UIPEthernet.h>//Ethernetbyte mac[]={0x54, 0x34, 0x41, 0x30, 0x30, 0x31};IPAddress ip(192, 168, 1, 179);EthernetServer server(80);void setup() { Serial.begin(57600); // start the Ethernet connection and the server: Ethernet.begin(mac, ip); server.begin(); Serial.print("IP Address: "); Serial.println(Ethernet.localIP());}void loop() { // listen for incoming clients EthernetClient client = server.available(); if (client){ Serial.println("-> New Connection"); // an http request ends with a blank line boolean currentLineIsBlank = true; while (client.connected()){ if (client.available()){ char c = client.read(); // 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){ client.println("<html><title>Hello World!</title><body><h3>Hello World!</h3></body>"); 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(10); // close the connection: client.stop(); Serial.println("Disconnected\n"); }}

Ao digitar o endereço https://192.168.1.179, uma página com as palavras “Hello Word!” irá aparecer.

Conectar o Arduino à Internet com um Ethernet Shield VMA04 • AranaCorp (2)

Código para visualizar os dados provenientes da placa Arduino

Vamos criar uma função generatePage() para escrever a página HTML. Ela tomará como entrada o cliente que abre e fecha durante o loop infinito loop().

void generatePage(EthernetClient client){ if(x==0){ //output HTML data header client.println(F("HTTP/1.1 200 OK")); client.println(F("Content-Type: text/html")); client.println(); }else{ //header client.print(F("<html><head><title>Arduino</title>")); //meta-refresh page every x seconds client.print(F("<meta http-equiv='refresh' content='1'>")); client.print(F("</head><body bgcolor='black'><br>")); client.print(F("<h1 style='color:green;'>Arduino data</h1>")); client.println("<p style='color:white;'>"); client.print(F("<br><br>Arduino analog input data :<br>")); client.print(F("<br>Page refresh number: ")); client.print(x); //current refresh count client.print("<br><br>"); //output analog input pin for(int i=0;i<6;i++){ client.print("<b>Input A"); client.print(i); client.print(" : </b>"); client.print(analogRead(14+i)); //A0=14, A1=15 ,etc. client.print("<br>"); } client.println("</p>"); client.println(F("<br></body></html>")); } x=x+1; }

O truque na função generatePage é adicionar uma meta tag para que a página recarregue automaticamente [meta http-equiv=”refresh” content=”1″]

Este é o código completo:

// Enter ip address http://192.168.1.179:80 in your browser// Based on WMA04 ethernet shield#include <UIPEthernet.h>//Ethernetbyte mac[]={0x54, 0x34, 0x41, 0x30, 0x30, 0x31};IPAddress ip(192, 168, 1, 179);EthernetServer server(80); //server port//Pageunsigned long int x=0; //set refresh counter to 0String readString;//////////////////////void setup(){ Serial.begin(9600); Ethernet.begin(mac, ip); server.begin(); Serial.println("System initialized"); Serial.print("IP Address: "); Serial.println(Ethernet.localIP());}void loop(){ EthernetClient client = server.available(); if (client) { while (client.connected()) { if (client.available()) { char c = client.read(); if (readString.length() < 100) { readString += c; } //check if HTTP request has ended if (c == '\n') { //check get atring received Serial.println(readString); generatePage(client); delay(1); //stopping client client.stop(); //clearing string for next read readString=""; } } } }}void generatePage(EthernetClient client){ if(x==0){ //output HTML data header client.println(F("HTTP/1.1 200 OK")); client.println(F("Content-Type: text/html")); client.println(); }else{ //header client.print(F("<html><head><title>Arduino</title>")); //meta-refresh page every x seconds client.print(F("<meta http-equiv='refresh' content='1'>")); client.print(F("</head><body bgcolor='black'><br>")); client.print(F("<h1 style='color:green;'>Arduino data</h1>")); client.println("<p style='color:white;'>"); client.print(F("<br><br>Arduino analog input data :<br>")); client.print(F("<br>Page refresh number: ")); client.print(x); //current refresh count client.print("<br><br>"); //output analog input pin for(int i=0;i<6;i++){ client.print("<b>Input A"); client.print(i); client.print(" : </b>"); client.print(analogRead(14+i)); //A0=14, A1=15 ,etc. client.print("<br>"); } client.println("</p>"); client.println(F("<br></body></html>")); } x=x+1; }

Ao digitar o endereço IP do seu Arduino, será exibida uma página com os valores de entrada analógicos atualizados automaticamente.

Conectar o Arduino à Internet com um Ethernet Shield VMA04 • AranaCorp (3)

Código para enviar dados da página web para o Arduino

Veremos agora como controlar as saídas do Arduino a partir da página web. Isso pode ser muito prático para ativar relés para acender luzes, por exemplo.

A ideia aqui é criar botões para cada saída e enviar um comando string (“/?On+pin number”) para o Arduino.

 client.print(F("<input type=button value=ON onmousedown=location.href='/?On4;'>"));
client.print(F("<input type=button value=OFF onmousedown=location.href='/?Off4;'>"));

Estes comandos são depois recuperados pelo Arduino na variável readString. Notamos bem a quantidade de pinos e o comando On/Off associado.

 if (readString.indexOf("4") > 0) { if (readString.indexOf("?On") > 0) { digitalWrite(4, HIGH); Serial.println("LED 4 On"); } if (readString.indexOf("?Off") > 0) { digitalWrite(4, LOW); Serial.println("LED 4 Off"); } }

Este é o código completo com as três saídas digitais disponíveis:

// Enter ip address http://192.168.1.179:80 in your browser// Based on WMA04 ethernet shield#include <UIPEthernet.h>//Ethernetbyte mac[] = {0x54, 0x34, 0x41, 0x30, 0x30, 0x31};IPAddress ip(192, 168, 1, 179);EthernetServer server(80); //server port//Pageunsigned long int x = 0; //set refresh counter to 0String readString;//int digPin[3] = {4, 7, 8};int anaPin[4] = {3, 5, 6, 9};//////////////////////void setup() { Serial.begin(9600); Ethernet.begin(mac, ip); server.begin(); Serial.println("System initialized"); Serial.print("IP Address: "); Serial.println(Ethernet.localIP());}void loop() { EthernetClient client = server.available(); if (client) { while (client.connected()) { if (client.available()) { char c = client.read(); if (readString.length() < 100) { readString += c; } //check if HTTP request has ended if (c == '\n') { //check get atring received Serial.println(readString); processCommand(); generatePage(client); delay(1); //stopping client client.stop(); //clearing string for next read readString = ""; } } } }}void processCommand() { if (readString.indexOf("4") > 0) { if (readString.indexOf("?On") > 0) { digitalWrite(4, HIGH); Serial.println("LED 4 On"); } if (readString.indexOf("?Off") > 0) { digitalWrite(4, LOW); Serial.println("LED 4 Off"); } } if (readString.indexOf("7") > 0) { if (readString.indexOf("?On") > 0) { digitalWrite(7, HIGH); Serial.println("LED 7 On"); } if (readString.indexOf("?Off") > 0) { digitalWrite(7, LOW); Serial.println("LED 7 Off"); } } if (readString.indexOf("8") > 0) { if (readString.indexOf("?On") > 0) { digitalWrite(8, HIGH); Serial.println("LED 8 On"); } if (readString.indexOf("?Off") > 0) { digitalWrite(8, LOW); Serial.println("LED 8 Off"); } }}void generatePage(EthernetClient client) { if (x == 0) { //output HTML data header client.println(F("HTTP/1.1 200 OK")); client.println(F("Content-Type: text/html")); client.println(); } else { //header client.print(F("<html><head><title>Arduino</title>")); //meta-refresh page every x seconds client.print(F("<meta http-equiv='refresh' content='2'>")); client.print(F("</head><body bgcolor='black'><br>")); client.print(F("<h1 style='color:green;'>Arduino Inputs</h1>")); client.println("<p style='color:white;'>"); client.print(F("<br><br>Arduino analog input data :<br>")); client.print(F("<br>Page refresh number: ")); client.print(x); //current refresh count client.print("<br><br>"); //output analog input pin for (int i = 0; i < 6; i++) { client.print("<b>Input A"); client.print(i); client.print(" : </b>"); client.print(analogRead(14 + i)); //A0=14, A1=15 ,etc. client.print(F("<br>")); } client.print(F("</p><br>")); client.print(F("<h1 style='color:green;'>Arduino Outputs</h1>")); client.print(F("<p style='color:white;'>")); //digital output client.print(F("<br><br>Arduino digital outputs :<br><br>")); for (int j = 0; j < 3; j++) { client.print(F("<b>Digital output ")); client.print(digPin[j]); client.print(" : </b>"); client.print(F("<input type=button value=ON onmousedown=location.href='/?On4;'>")); client.print(F("<input type=button value=ON onmousedown=location.href='/?On")); client.print(digPin[j]); client.print(F(";'>")); client.print(F("<input type=button value=OFF onmousedown=location.href='/?Off")); client.print(digPin[j]); client.print(F(";'>")); client.print(F("<br>")); } client.print(F("</p><br>")); //file end client.print(F("<br></body></html>")); } x = x + 1;}
Conectar o Arduino à Internet com um Ethernet Shield VMA04 • AranaCorp (4)

Teste e combine estes exemplos para obter as funcionalidades que deseja. Se tiver algum problema para usar o seu shield Ethernet com o microcontrolador Arduino, sinta-se à vontade para nos deixar um comentário ou mandar uma mensagem.

Aplicação

  • Controlar o seu projeto Arduino via Internet

Referências

Retrouvez nos tutoriels et d’autres exemples dans notre générateur automatique de code
La Programmerie

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

FAQs

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

Connecting the Shield

To use the shield, mount it on top of an Arduino board (e.g. the Uno). To upload sketches to the board, connect it to your computer with a USB cable as you normally would. Once the sketch has been uploaded, you can disconnect the board from your computer and power it with an external power supply.

How do I connect my Arduino to the Ethernet module? ›

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).

Can Arduino be a server with Ethernet shield? ›

By equipping an Arduino with an Ethernet shield you can turn it into a simple web server, and by accessing that server with a browser running on any computer connected to the same network as the Arduino, you can perform a variety of tasks.

How do I assign an IP address to my Arduino Ethernet shield? ›

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 to connect Arduino on Internet? ›

Lets get going!
  1. Step 1: Collect Information About Your Home Network. First things first, you need to find the following information about your home network: ...
  2. Step 2: PLUG N' CHUG! a) Plug the Ethernet shield into your Arduino. ...
  3. Step 3: Setup Port Forwarding. ...
  4. Step 4: Code and Test. ...
  5. Step 5: Build the Circuit. ...
  6. 9 Comments.

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.

Can Arduino use Ethernet? ›

The board also can connect to a wired network via ethernet. When connecting to a network, you will need to provide an IP address and a MAC address. The Ethernet Library is fully supported. The onboard microSD card reader is accessible through the SD Library.

How do I connect my device to Arduino? ›

Step 1: Add the device
  1. Go to Arduino IoT Cloud and open the Devices tab.
  2. Click the Add Device button in the top-right or middle of the page.
  3. Select your device type: ...
  4. Proceed with the instructions to add your device. ...
  5. When finished, your new device will be added to your list of devices.
Sep 20, 2022

How to connect Arduino to computer? ›

How to connect the Arduino ISP. Plug the Arduino ISP on the 6-pin ICSP connector of the Arduino board you want to program, as shown in the picture. Connect the Arduino ISP to your computer with a micro USB cable, and connect the target board to a power source (USB cable or with the power jack).

What is the default IP for Arduino Ethernet shield? ›

By default the IP is “192.168. 1.178”. That also can be found on the arduino code provided.

Which protocol is used by Ethernet shield to communicate with Arduino? ›

Ethernet Shield Rev2
ShieldNameArduino® Ethernet Shield Rev 2
EthernetSupported protocolsIPv4, ICMP, TCP, UDP, ARP, IGMP, PPPoE, MQTT
StorageMicro SD card slot
PowerOperating voltage5V
ConnectorsTinkerKitYes, 6x
8 more rows

What are those shields that can be used to have an Internet access with your Arduino project? ›

Ethernet Shield

The Ethernet Shield allows you to connect your Arduino to the internet . You just have to plug the shield onto the Arduino board and then, connect it to your network.

How do I configure my IP address for Ethernet? ›

Connecting directly to the access point via Ethernet cable:
  1. In Windows, click Start and type network connections. ...
  2. Right click on Ethernet (Local Area Connection) and click Properties.
  3. Select Internet Protocol Version 4 (TCP/IPv4) > and click Properties.
  4. Select Use the following IP address.
Aug 5, 2020

How do I assign an IP address to an Ethernet cable? ›

Set static IP address on Windows 10
  1. Open Settings on Windows 10.
  2. Click on Network & Internet.
  3. Click on “Wi-Fi” or “Ethernet.”
  4. Click on the current network connection.
  5. Under the “IP settings” section, click the Edit button.
  6. Using the drop-down menu, select the Manual option.
  7. Turn on the “IPv4” toggle switch.
Mar 9, 2023

How do I assign an IP address to a LAN connection? ›

Setting the IP address on your PC or mobile computer
  1. Click Start >Settings >Control Panel.
  2. On the control panel, double-click Network Connections.
  3. Right-click Local Area Connection.
  4. Click Properties. ...
  5. Select Internet Protocol (TCP/IP), and then click Properties.
  6. Select Use the Following IP Address.

How to connect Arduino Uno with 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.

Which Arduino Uno Shield can transmit receive data from the internet? ›

The Arduino GSM shield allows an Arduino board to connect to the internet, send and receive SMS, and make voice calls using the GSM library. The shield will work with the Arduino Uno out of the box.

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.

Top Articles
Latest Posts
Article information

Author: Patricia Veum II

Last Updated: 04/01/2024

Views: 5567

Rating: 4.3 / 5 (44 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Patricia Veum II

Birthday: 1994-12-16

Address: 2064 Little Summit, Goldieton, MS 97651-0862

Phone: +6873952696715

Job: Principal Officer

Hobby: Rafting, Cabaret, Candle making, Jigsaw puzzles, Inline skating, Magic, Graffiti

Introduction: My name is Patricia Veum II, I am a vast, combative, smiling, famous, inexpensive, zealous, sparkling person who loves writing and wants to share my knowledge and understanding with you.