Utilizando Ethernet Board Enc28j60 Com Arduino Uno
Arduino Uno + Ethernet Enc28j60 + UIPEthernet library
Existe muito conteúdo sobre arduino com ethernet shield. Existe uma quantidade enorme de modelos de placas, chip's, bibliotecas, etc, e isso acaba gerando uma bagunça enorme, um exemplo que alguém cria para um determinado shield utilizando uma determinada biblioteca, com uma determinada ligação, bom acho que vocês entederam.
Na biblioteca Ethernet padrão que acompanha a IDE do arduino é feita para funcionar com o Ethernet Shield W5100. Ele é ótimo para prototipação rápida e simples, mas se vc quiser utilizar em um projeto final é um tanto caro gastar um shield inteiro apenas para fazer a conexão com a internet. Quando eu digo caro, quero dizer que existem opção mais baratas e é aí que entra o nossa board Enc28j60.
Diferente do Ethernet shield W5100, o Enc28j60 não se acopla ao arduino, ela é um board que é ligado através de dupont cable (aqueles cabos coloridos com conectores) ou qualquer outro fio (tem gente que usa cabo de rede). É possível comprar em sites como aliexpress, dx, etc por menos que R$ 10,00 reais. Ele não possui leitor de cartões micro sd como o W5100 mas sempre vejo anúncios onde ele é vendido junto com um board leitor de cartão.
Blz, então vou mostrar agora o esquema de ligação dos jumpers. As siglas estão impressas na placa ao lado dos jumpers.
ENC28J60 | Arduino UNO | Arduino Mega |
5v | 5v | 5v |
CLKOUT | ||
WOL | ||
Reset | Reset | Reset |
INT | 2 | 2 |
GND | GND | GND |
SCK | 13 | 52 |
SO | 12 | 50 |
SI | 11 | 51 |
CS | 10 | 53 |
Aqui a foto do esquema no UNO
Library/Biblioteca
É aqui que geralmente existe muita confusão. Existem muitas bibliotecas para a implementação do código para utilizar o enc28j60. Se você pesquisar no google sobre exemplos e tutoriais, provavelmente seu código não irá funcionar devido as constantes evolução das bibliotecas e a diversidade e falta de padrão entre os códigos. Na data que escrevo este texto, existem duas librarys que são mais utilizadas: EthernetCard e UIPEthernet. Eu optei pela UIPEthernet pela simplicidade do código e pela compatibilidade com a library Ethernet padrão do Arduino. Qualquer código para o W5100 com pequenas modificações funcionará com a library UIPEthernet. Então faça o download https://github.com/ntruchsess/arduino_uip e descompacte na pasta das library do Arduino. No linux fica /usr/share/arduino/library. É preciso dar permissão de acesso para usuários se você não estiver logado como root. É preciso renomear a pasta para UIPEthernet e editar o arquivo /library/Enc28j60Network.h
Adicione isso ao arquivo:
#if defined(__AVR_ATmega2560__) || defined(__AVR_ATmega1280__)
#define ENC28J60_CONTROL_CS 48
#define SPI_MOSI 51
#define SPI_MISO 50
#define SPI_SCK 52
#else;
#define ENC28J60_CONTROL_CS 10
#define SPI_MOSI 11
#define SPI_MISO 12
#define SPI_SCK 13
#endif;
Se você estava com a IDE aberta é preciso reiniciar a IDE. Já é possível abrir os exemplos que vem junto com a library no menu File/Examples/UIPEthernet da IDE do arduino. Vou colocar um exemplo de hello world.
#include <SPI.h>
#include <UIPEthernet.h>
// Set your own MAC address for the Ethernet module here:
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// Set your own IP address for the Ethernet module here:
IPAddress ip(192,168,1,50);
EthernetServer server(80);
// You can access your Arduino server at http://192.168.1.50
void setup()
{
// Start Ethernet connection and web server
Ethernet.begin(mac, ip);
server.begin();
}
void loop()
{
// Listen for incoming connections
EthernetClient client = server.available();
long time = millis();
if (client) // If a user is connected
{
// An HTTP request from the client ends with two end
// of line characters (\n x2). We'll need code to check
// for that.
boolean currentLineIsBlank = true;
// This flag is used to check if the first end of line character
// was sent by the client.
while (client.connected()) // While web client is connected
{
if (client.available())
{
char c = client.read();
// Received two end of line characters (\n). Client has finished
// sending the request.
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"); // Close the connection once the page is fully loaded
client.println("Refresh: 2"); // Refresh the page automatically every 2 seconds
client.println(); // End of HTTP Response header
// Send HTML page
client.println("<!DOCTYPE HTML>"); // Start of HTML document
client.println("<html>"); // Start of HTML code
client.println("<head><title>Hello World!</title></head>"); // Set page title
client.println("<body>"); // Start of HTML body
client.println("<h1>Hello World!</h1>"); // Set header
// 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(": ");
client.print(sensorReading);
client.println("<br />");
}
// Display server uptime
client.println("<p>Server has been running for ");
client.println(time);
client.println(" ms.</p>");
client.println("</body></html>"); // End of body and HTML page
break; // End of transmission
}
// If client sent one end of line character (\n),
// raise the flag and see if the next character is another
// end of line character
if (c == '\n')
{
currentLineIsBlank = true;
}
// If client sends a character that isn't an end of line character,
// reset the flag and wait for the end of line character.
else if (c != '\r')
{
currentLineIsBlank = false;
}
}
}
// Give the web browser time to receive the data
delay(1);
// Close the connection
client.stop();
}
}
Pronto! Agora você pode criar seus próprios projetos utilizando a rede com um componente barato sem precisar gastar um ethernet shield W5100.
Categoria: arduino
Tags: ['arduino,ethernet,c++,enc28j60']