Estou com dificuldades, encontrei um tópico ensinado acender/apagar um led pela web mais estava usando outra shield (ENC28J60) a minha shield é a W5100, o código está rodando no Arduíno consigo pingar no ip dele mais não acesso a pagina HTML. 

Alguém me ajuda?! segue o código:

#include <SPI.h>
#include <Ethernet.h>

// Objetivo: transformar Arduino Uno em um webserver capaz de ficar escutando a porta 80
// para receber pedido de um browser cliente e ligar ou desligar um led

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192, 168, 0, 104 };
int ledPin = 9; // Define o pino digital 9 do led a ser ligado/desligado
char buffer[128]; // Armazena caracteres que o webserver lê do browser
int i = 0; // Endereço posição array buffer

EthernetServer server(80); // Inicia servidor na porta 80

void setup() {
Ethernet.begin(mac, ip);
server.begin();
pinMode(ledPin, OUTPUT);
}

void loop() {
EthernetClient cliente = server.available();
if (cliente) {
boolean linhaVazia = true;
while (cliente.available()) {
char c = cliente.read();
if (c == '\n' && linhaVazia) { // Se o fim da linha for '\n' e a linha estiver em branco significa fim da solicitação HTTP
cliente.println("HTTP/1.1 200 OK");
cliente.println("Content-Type: text/html\n");
cliente.println("<html><body><h3>Resposta do Arduino</h3><br />");
if (strstr(buffer, "?statusled=on")) {
cliente.println("LED ligado");
digitalWrite(ledPin, HIGH);
}
else
if (strstr(buffer, "?statusled=off")) {
cliente.println("LED desligado");
digitalWrite(ledPin, LOW);
}
else
cliente.println("Não foi possível ligar ou desligar o LED");
cliente.println("</body></html>");
break;
}
if (c == '\n')
linhaVazia = true;
else
if (c != '\r') { // Ainda existem caracteres a serem lidos
linhaVazia = false;
buffer[i++] = c;
}
}
delay(10); // Permite ao browser receber a resposta
cliente.stop(); // Desconecta cliente do servidor
}
}

Exibições: 4958

Responder esta

Respostas a este tópico

Veja Coloque esse código. Lembre de modificar o IP e estou usando o LED na Porta 8.

#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(127,0,0, 1);
// 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 LEDpin = 8;
String readString = String(30);
String state = String(3);

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

//Configura o PINO 8 com saída
pinMode(LEDpin,OUTPUT);

//Iniciar o PINO 8 0V
digitalWrite(LEDpin,LOW);
state = "OFF";
}

void loop()
{
// listen for incoming clients
//server.available()= Ler total de bytes disponível no buffer
EthernetClient client = server.available();

if (client) {
// an http request ends with a blank line
boolean currentLineIsBlank = true;
// client.connected() = verifica se está conectado 1 0u 0

while (client.connected()) {

if (client.available()) {
//mostra o códico ASCII decimal do q está lendo
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 (readString.length() < 30) {
readString.concat(c);
}

if (c == '\n' && currentLineIsBlank) {
// send a standard http response header
int LED = readString.indexOf("LED=");

if (readString.substring(LED,LED+5) == "LED=T") {
digitalWrite(LEDpin,HIGH);
state = "ON";
}
else if (readString.substring(LED,LED+5) == "LED=F") {
digitalWrite(LEDpin,LOW);
state = "OFF";
}



client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println();

client.print("LED is ");
client.print(state);
client.print("<br><br>");


if (state == "ON") {
client.println("<a href=\"./?LED=F\">Turn Off<a>");
}
else {
client.println("<a href=\"./?LED=T\">Turn On<a>");
}

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);
readString = "";
// close the connection:
client.stop();
}
}

Cara aparece a pagina HTML "It Works" mais nada de botões liga e desliga....

você colocou o IP do seu arduino? ou IP de um servidor web? Este código que te enviei é para o arduino ser weberver ... o IP deve ser o do Arduino.

Cara, desculpa mais não intendi. Eu mudei o IP do seu codigo para outro, configurei minha conexão local para a mesma rede e abri no navegador. O ip do meu arduino é o da ethShiel né?! o que eu declaro no codigo...

Sou iniciante ainda desculpa se estou sendo muito superficial.

Obrigado pela ajuda.

Cara, coloque o IP do Shield. e acesse pelo navegador.

como usar dois leds ou mais?

Caro Emerson,

É possivel acrescentar qe que forma 02 ou mais leds ao código acima?

Grato

Jesé

amigo, comprei um ethernet shield e nunca consegui fazer nada com ele. consegui agora com essa programação que voce postou. como eu faria para ligar mais leds?

aguardo retorno e muito obrigado.

Emerson, aqui rodou beleza! 

Você sabe como adicionar um botão no arduino, para acender e apagar por ele, e o status ser atualizado na html ? 

Usei o código do Emerson e funciona blz. Código enxuto e limpo.. agora é só brincar. São milhões de possibilidades !

Obrigada Emerson.

RSS

© 2024   Criado por Marcelo Rodrigues.   Ativado por

Badges  |  Relatar um incidente  |  Termos de serviço