LusoRobótica - Robótica em Português

Robótica => Iniciantes => Tópico iniciado por: r16 em 07 de Abril de 2012, 16:40

Título: [Pedido de Ajuda] Arduino EthernetShield Armazenar um pagina html e imagem dentr
Enviado por: r16 em 07 de Abril de 2012, 16:40
Caros Amigos,,,bom já lá vao alguns dias que ando aqui a matar a cabeça com um problema que nao consigo de forma alguma resolver...primeiro porque nao entendo muito de arduino, depois que sou teimoso e insistente e tudo isso me faz doer a cabeça e fica dificil pensar sozinhoel.
Bom entao o que eu preciso de ajuda??
Eu tenho um shield ethernet com SD com chip wiznet.

E o que eu pretendia era um codigo no arduino que funcionasse dentro do WEBSERVER dele onde contesse uma imagem parecida com esta dentro dele num formato html

(https://lusorobotica.com/proxy.php?request=http%3A%2F%2F4.bp.blogspot.com%2F-S6G5PgB28q4%2FTnb7zaPegmI%2FAAAAAAAAR50%2FpeD5LeP0ar0%2Fs1600%2Fsw_Auto_Giardino-500x293.jpg&hash=6e39211acf48e17b660eb13ea5613b3805181933)

Ou seja quando eu clicasse ai nesses ICONES das lampadas do lado direito, ele acendia um led, e quando clicasse na mesma "imagem" ele desligasse o led.
Mas atencao, eu nao quero ter o site em servidores nenhuns, queria aloja-lo no meu arduino INCLUINDO O CODIGO e essa IMAGEM que seria o interface.
E possivel fazer isso? alguem com disposicao para me ajudar?
PS: Nao tenho conhecimentos gerais de html e nao muito de Arduino, mas estou disposto a aprender com quem tiver Dom de me ajudar
Obrigado


''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Algumas informacao que pode ser importante a quem me quiser ajudar.

# Include
# Include
# Include
# Include
/ ************ ************ STUFF ETHERNET /
mac byte [] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
ip byte [] = {192, 168, 1, 177};
rootFileName char [] = "index.htm";
Servidor servidor (80);
/ ************ STUFF SDCARD ************ /
Cartão Sd2Card;
Volume de SdVolume;
SdFile raiz;
Arquivo SdFile;
/ / Armazena seqüências de erro em flash para economizar RAM
# Define erro (s) error_P (PSTR (s))
vazio error_P (const char * str) {
PgmPrint ("erro:");
SerialPrintln_P (str);
if (card.errorCode ()) {
PgmPrint ("erro SD:");
Serial.print (card.errorCode (), HEX);
Serial.print (',');
Serial.println (card.errorData (), HEX);
}
while (1);
}
void setup () {
Serial.begin (115200);
PgmPrint ("RAM livre:");
Serial.println (FreeRAM ());
/ / Inicializa o cartão SD no SPI_HALF_SPEED para evitar erros de ônibus com
/ / Breadboards. SPI_FULL_SPEED usar para um melhor desempenho.
pinMode (10, OUTPUT); / / colocar o pino SS como uma saída (necessary!)
digitalWrite (10, HIGH); / / mas desligar o chip W5100!
if (card.init (SPI_HALF_SPEED, 4)!) erro ("card.init falhou!");
/ / Inicializar um volume FAT
se o erro ("vol.init falhou!") (volume.init (e cartão)!);
PgmPrint ("Volume é FAT");
Serial.println (volume.fatType (), DEC);
Serial.println ();
se o erro ("openRoot falhou") (root.openRoot (e volume)!);
/ List / arquivo na raiz, com data e tamanho
PgmPrintln ("Arquivos encontrados na raiz:");
root.ls (LS_DATE | LS_SIZE);
Serial.println ();
Lista / / recorrente de todos os diretórios
PgmPrintln ("Arquivos encontrados em todos os dirs:");
root.ls (LS_R);
Serial.println ();
PgmPrintln ("Done");
/ / Depuração completa, iniciar o servidor!
Ethernet.begin (mac, ip);
server.begin ();
}
/ / Como grande o nosso buffer de linha deve ser. 100 é muito!
# Define BUFSIZ 100
void loop ()
{
caractere clientline [BUFSIZ];
char * filename;
int index = 0;
int imagem = 0;
Cliente cliente = server.available ();
if (cliente) {
/ / Um pedido http termina com uma linha em branco
boolean current_line_is_blank = true;
/ / Repor o buffer de entrada
index = 0;
while (client.connected ()) {
if (client.available ()) {
char c = client.read ();
/ / Se não é uma nova linha, adicione o personagem para o buffer
if (c! = '\ n' && c! = '\ r') {
clientline [índice] = c;
index + +;
/ / Estamos muito grande para o buffer? começar a jogar fora de dados
if (index> = BUFSIZ)
index = BUFSIZ -1;
/ / Continuar a ler mais dados!
continuar;
}
/ / Tem um \ n ou \ r nova linha, o que significa que a cadeia é feito
clientline [índice] = 0;
filename = 0;
/ / Imprimi-lo para depuração
Serial.println (clientline);
/ / Procure substring como um pedido para obter o arquivo raiz
if (strstr (clientline, "GET /") = 0) {
filename = rootFileName;
}
if (strstr (clientline, "GET /") = 0) {
/ / Neste momento nenhum espaço após o /, então um arquivo sub-
Se filename = clientline + 5 (nome do arquivo!); / olhar / após o "GET /" (5 caracteres)
/ / Um pequeno truque, procure o "HTTP/1.1" string e
/ / Ligar o primeiro caractere da substring em um 0 a limpá-lo.
(Strstr (clientline, "HTTP"))
  • = 0;

/ / Imprimir o arquivo que queremos
Serial.println (filename);
if (! File.open (& raiz, filename, O_READ)) {
client.println ("HTTP/1.1 404 Not Found");
client.println ("Content-Type: text / html");
client.println ();
client.println ("Arquivo não encontrado
");
quebrar;
}
Serial.println ("Aberto");
client.println ("HTTP/1.1 200 OK");
if (strstr (filename, ". htm") = 0)
client.println ("Content-Type: text / html");
else if (strstr (filename, ". css") = 0)
client.println ("Content-Type: text / css");
else if (strstr (filename, ". png") = 0)
client.println ("Content-Type: image / png");
else if (strstr (filename, ". jpg") = 0)
client.println ("Content-Type: image / jpeg");
else if (strstr (filename, ". gif") = 0)
client.println ("Content-Type: image / gif");
else if (strstr (filename, ".3 gp") = 0)
client.println ("Content-Type: video / mpeg");
else if (strstr (filename, ". pdf") = 0)
client.println ("Content-Type: application / pdf");
else if (strstr (filename, ". js") = 0)
client.println ("Content-Type: application / x-javascript");
else if (strstr (filename, ". xml") = 0)
client.println ("Content-Type: application / xml");
outro
client.println ("Content-Type: text");
client.println ();
int16_t c;
while ((c = file.read ())> = 0) {
/ Descomente / o serial de depuração (slow!)
/ / Serial.print ((char) c);
client.print ((char) c);
}
File.close ();
Else {}
/ / Tudo o resto é um 404
client.println ("HTTP/1.1 404 Not Found");
client.println ("Content-Type: text / html");
client.println ();
client.println ("Arquivo não encontrado
");
}
quebrar;
}
}
/ / Dar tempo ao navegador web para receber os dados
atraso (1);
client.stop ();
}
}



0000000000000000000000000000000000000000000000000000

Aqui fica um video de quase o que eu quero...
Repararem que ele carregou uma pagina HTML dentro do SDcard, mas ele tem DOIS botoes la LED ON e LED off,
eu nao quero esse botoes, eu quero clicar em cima da imagem, ou seja a imagem exemplo LAMPADA é como se fosse um botao,

http://youtu.be/b8QX2j_AZw4 (http://youtu.be/b8QX2j_AZw4)
Título: Re: [Pedido de Ajuda] Arduino EthernetShield Armazenar um pagina html e imagem dentr
Enviado por: r16 em 07 de Abril de 2012, 17:35
Mais informacao que achei:
Penso que estamos proximos do que é pedido:
http://andrew-j-norman.blogspot.pt/2011/12/my-own-web-server.html (http://andrew-j-norman.blogspot.pt/2011/12/my-own-web-server.html)
Título: Re: [Pedido de Ajuda] Arduino EthernetShield Armazenar um pagina html e imagem dentr
Enviado por: senso em 07 de Abril de 2012, 17:59
Então, tens de usar um ecrã com touch-screen e implementas soft-buttons baseados em regiões quadradas/rectangulares do tamanho da imagem do botão.
Título: Re: [Pedido de Ajuda] Arduino EthernetShield Armazenar um pagina html e imagem dentr
Enviado por: r16 em 07 de Abril de 2012, 18:05
Qual e o programa (leve ) indicado para poder agregar a imagem a um index.html?
Título: Re: [Pedido de Ajuda] Arduino EthernetShield Armazenar um pagina html e imagem dentr
Enviado por: microbyte em 07 de Abril de 2012, 21:29
A tua imagem não precisa de estar no Arduino. Podes colocar a imagem na internet, e depois referencias na tag <img src="URL"> o seu URL. ;)
Título: Re: [Pedido de Ajuda] Arduino EthernetShield Armazenar um pagina html e imagem dentr
Enviado por: r16 em 07 de Abril de 2012, 22:42
ok Microbyte e Senso,

Ja consegui alojar o meu index.htm no SD do ethernet shield, e ja consigo acessar a ele pela internet, e quando acesso ele abre essa imagem que defini,

Agora o que pretendo é, por exemplo quando clico em cima dessa imagem na parte da piscina...

que ele me ligue um LED..

Portanto faz tanto codigo no index.html, como codigo no arduino,,, alguem me ajuda nessas modificacoes?

aqui fica o codigo.

#include <LiquidCrystal.h>
#include <SPI.h>
#include <SdFat.h>
#include <SdFatUtil.h>
#include <Ethernet.h>
#define BUFSIZ 128
#define greenLEDandBEEP 2
#define redLEDpin 3
boolean led2 = true;
int hits = 0; // Set the number of hits the hit counter will start at.
int units = 0;
int count = 0;
int photocellPin = 2;
int photocellReading;
LiquidCrystal lcd(4, 5, 6, 7, 8, 9);

//Local ethernet setup
byte mac[] = {
  0x90, 0xA2, 0xDA, 0x00, 0x1C, 0x0E };
byte ip[] = {
  192, 168, 1, 80 };
char rootFileName[] = "index.htm";
Server server(8080);

//SD card stuff
Sd2Card card;
SdVolume volume;
SdFile root;
SdFile file;
#define error(s) error_P(PSTR(s))
void error_P(const char* str) {
  PgmPrint("error: ");
  SerialPrintln_P(str);
  if (card.errorCode()) {
    PgmPrint("SD error: ");
    Serial.print(card.errorCode(), HEX);
    Serial.print(',');
    Serial.println(card.errorData(), HEX);
  }
  while(1);
}

void setup() {
  lcd.begin(16, 2);
  lcd.print("Web Server v2.00");
  lcd.setCursor(0, 1);
  lcd.print("Hits:");

  Serial.begin(9600);

  pinMode(greenLEDandBEEP, OUTPUT);
  pinMode(redLEDpin, OUTPUT);

  PgmPrint("Free RAM: ");
  Serial.println(FreeRam()); 

  pinMode(10, OUTPUT);             
  digitalWrite(10, HIGH);             

  if (!card.init(SPI_HALF_SPEED, 4)) error("card.init failed!");

  if (!volume.init(&card)) error("vol.init failed!");

  PgmPrint("Volume is FAT");
  Serial.println(volume.fatType(),DEC);
  Serial.println();

  if (!root.openRoot(&volume)) error("openRoot failed");

  PgmPrintln("Files found in root:");
  root.ls(LS_DATE | LS_SIZE);
  Serial.println();

  PgmPrintln("Files found in all dirs:");
  root.ls(LS_R);

  Serial.println();
  PgmPrintln("Done");

  Ethernet.begin(mac, ip);
  server.begin();
}


void loop()
{
  if(count >=500)
  { 
    led2 = !led2;
    digitalWrite(redLEDpin, led2);
    count = 0;
  }
  count +=1;

  char clientline[BUFSIZ];
  char *filename;
  int image = 0;
  int index = 0;

  Client client = server.available();
  if (client) {
    boolean current_line_is_blank = true;

    index = 0;

    while (client.connected()) {
      if (client.available()) {
        char c = client.read();

        if (c != '\n' && c != '\r') {
          clientline[index] = c;
          index++;
          if (index >= BUFSIZ)
            index = BUFSIZ -1;

          continue;
        }

        clientline[index] = 0;
        filename = 0;

        Serial.println(clientline);

        if (strstr(clientline, "GET / ") != 0) {
          filename = rootFileName;

        }
        if (strstr(clientline, "GET /") != 0) {
          if (!filename) filename = clientline + 5;

          (strstr(clientline, " HTTP"))[0] = 0;

          Serial.println(filename);

          if (! file.open(&root, filename, O_READ)) {
            client.println("HTTP/1.1 404 Not Found");
            client.println("Content-Type: text/html");
            client.println();
            client.println("<h2>Error 404</h2>");
            client.println("<s2>The file does not exist.<s2>");
            client.println("");
            break;
          }

          Serial.println("Opened!");
          //File types
          client.println("HTTP/1.1 200 OK");
          if (strstr(filename, ".htm") != 0)
            client.println("Content-Type: text/html");
          else if (strstr(filename, ".css") != 0)
            client.println("Content-Type: text/css");
          else if (strstr(filename, ".png") != 0)
            client.println("Content-Type: image/png");
          else if (strstr(filename, ".jpg") != 0)
            client.println("Content-Type: image/jpeg");
          else if (strstr(filename, ".gif") != 0)
            client.println("Content-Type: image/gif");
          else if (strstr(filename, ".3gp") != 0)
            client.println("Content-Type: video/mpeg");
          else if (strstr(filename, ".pdf") != 0)
            client.println("Content-Type: application/pdf");
          else if (strstr(filename, ".js") != 0)
            client.println("Content-Type: application/x-javascript");
          else if (strstr(filename, ".xml") != 0)
            client.println("Content-Type: application/xml");
          else
            client.println("Content-Type: text");
          client.println();

          int16_t c;
          while ((c = file.read()) >= 0) {
            //Serial.print((char)c); //Prints all HTML code to serial (For debuging)
            client.print((char)c); //Prints all HTML code for web page
          }

          //Hit counter math
          if(units >= 2)
          {
            hits ++;
            units = 0;
          }
          units +=1;
          //End hit counter math

          //Print the hit counters and light value
          lcd.setCursor(6, 1);
          lcd.print(hits); //Print hits for LCD hit counter

          client.print("<html><body>"); //HTML code starts here
          client.print("<P align=\"center\">");
          client.print("Hits since reset: ");   
          client.print(hits); //Print hits to client
          client.print("

");

          photocellReading = analogRead(photocellPin);
          client.print("Light reading: ");
          client.print(photocellReading); //Prints light reading to client

          // A few threshholds
          if (photocellReading < 10) {
            client.print(" - Dark");
          }
          else if (photocellReading < 200) {
            client.print(" - Dim");
          }
          else if (photocellReading < 500) {
            client.print(" - Light");
          }
          else if (photocellReading < 800) {
            client.print(" - Bright");
          }
          else {
            client.print(" - Very bright");
          }

          client.print("</p></body></html>"); //HTML code ends here
          //End hit counter and light value

          file.close();

        }
        else {
          client.println("HTTP/1.1 404 Not Found");
          client.println("Content-Type: text/html");
          client.println();
          client.println("<h2>Error 404</h2>");
          client.println("");
        }
        break;
      }
    }
    digitalWrite(greenLEDandBEEP, HIGH);
    delay(1);
    digitalWrite(greenLEDandBEEP, LOW);
    client.stop();
  }

}

//The End /*
Título: Re: [Pedido de Ajuda] Arduino EthernetShield Armazenar um pagina html e imagem dentr
Enviado por: Hugu em 08 de Abril de 2012, 00:35
http://www.echoecho.com/htmlforms14.htm (http://www.echoecho.com/htmlforms14.htm)
http://www.webdevelopersnotes.com/tips/html/using_an_image_as_a_submit_button.php3? (http://www.webdevelopersnotes.com/tips/html/using_an_image_as_a_submit_button.php3?)
http://www.quackit.com/html/codes/html_button.cfm (http://www.quackit.com/html/codes/html_button.cfm)
Título: Re: [Pedido de Ajuda] Arduino EthernetShield Armazenar um pagina html e imagem dentr
Enviado por: r16 em 08 de Abril de 2012, 12:04
Hugu agradeço a ajuda,mas essa parte sera para o index.html, agora o codigo do arduino é o que falta.
Título: Re: [Pedido de Ajuda] Arduino EthernetShield Armazenar um pagina html e imagem dentr
Enviado por: microbyte em 08 de Abril de 2012, 12:41
O index.html vai ser gerado no arduino... Não estou a perceber a tua dúvida.
Título: Re: [Pedido de Ajuda] Arduino EthernetShield Armazenar um pagina html e imagem dentr
Enviado por: r16 em 08 de Abril de 2012, 12:49
Nao micro o meu index.html esta dentro do SD do meu arduino...ethernet shield.

Ou seja nesse index.html esta associada essa imagem que tambem esta no SD , eu quero que quando se clique nela... me ligue um led  um PIn qualquer, e quando se clique novamente na imagem que desligue o led.

Entendes agora?

Ou achas que existia um codigo mais facil?
Título: Re: [Pedido de Ajuda] Arduino EthernetShield Armazenar um pagina html e imagem dentr
Enviado por: poliveira1978 em 08 de Abril de 2012, 17:52
podes implementar o código do teu arduino para responder a alguns parametros no url.
se nos links do html fizeres:
Código: [Seleccione]
<a href="http:<ip do arduino>/?p=<valor>" alteras a resposta do arduino consoante o valor.
algo semelhante ao que está neste post: http://lusorobotica.com/index.php?topic=3958.0 (http://lusorobotica.com/index.php?topic=3958.0)
Título: Re: [Pedido de Ajuda] Arduino EthernetShield Armazenar um pagina html e imagem dentr
Enviado por: microbyte em 08 de Abril de 2012, 22:28
Nao micro o meu index.html esta dentro do SD do meu arduino...ethernet shield.

Ou seja nesse index.html esta associada essa imagem que tambem esta no SD , eu quero que quando se clique nela... me ligue um led  um PIn qualquer, e quando se clique novamente na imagem que desligue o led.

Entendes agora?

Ou achas que existia um codigo mais facil?

Agora é que me baralhaste todo..
Mas pronto... De qualquer maneira, se tens acesso ao código fonte do ficheiro é só alterares para que ele faça o que tu queres. Isto deixou de ser uma questão de electrónica/ethernet shield e passou a ser uma questão de programação HTML que está fora do scope do fórum.
Título: Re: [Pedido de Ajuda] Arduino EthernetShield Armazenar um pagina html e imagem dentr
Enviado por: r16 em 08 de Abril de 2012, 22:40
Nao micro o meu index.html esta dentro do SD do meu arduino...ethernet shield.

Ou seja nesse index.html esta associada essa imagem que tambem esta no SD , eu quero que quando se clique nela... me ligue um led  um PIn qualquer, e quando se clique novamente na imagem que desligue o led.

Entendes agora?

Ou achas que existia um codigo mais facil?

Agora é que me baralhaste todo..
Mas pronto... De qualquer maneira, se tens acesso ao código fonte do ficheiro é só alterares para que ele faça o que tu queres. Isto deixou de ser uma questão de electrónica/ethernet shield e passou a ser uma questão de programação HTML que está fora do scope do fórum.



MicroByte tenho 100% certeza que podes me ajudar mais que o teu ultimo post.
Se leres bem...que penso que não leste, é fácil deduzir que se eu soubesse o que fazer , não vinha cá sequer questionar, mas sim partilhar o que sei.. é somente isso que necessito de ti,caso queiras.. que partilhes o teu saber.. que como já referi no primeiro parágrafo tu sabes...

Eu a parte do html penso que já estou quase desenrascado, agora a parte que falta é qual a parte que tenho que alterar no código do ARDUINO para que ele acenda o led, quando clico na IMAGEM.

Penso que com isto, fui explicito.

Título: Re: [Pedido de Ajuda] Arduino EthernetShield Armazenar um pagina html e imagem dentr
Enviado por: poliveira1978 em 09 de Abril de 2012, 01:24
Sketch que "saquei" do playground, tem radio-buttons em vez de buttons, mas é questão de adaptar.

Código: [Seleccione]
#include <SPI.h>
#include <Ethernet.h>
byte    mac[] =     { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte    ip[] =      { xxx, xxx, xxx, xxx };
byte    gateway[] = { xxx, xxx, xxx, xxx };
byte    subnet[] =  { xxx, xxx, xxx, xxx };
EthernetServer  server(80);
int     ledPin = 4;
int     heatpin = 5;
int     sensorPin = A0;
int     sensorValue = 0;
String  readString = String(30);
boolean LEDON = false;
boolean HEATON = false;

void setup()
{   
    Serial.begin(9600);
    Ethernet.begin(mac, ip, gateway, subnet);
    pinMode(ledPin, OUTPUT);
    pinMode(heatpin, OUTPUT);
    Serial.print("Starting server");
    sensorValue = analogRead(sensorPin);
    Serial.println("Analog in:");
    Serial.println("");
    Serial.println (sensorValue);
    Serial.println("");
    Serial.println("");
}

void loop()
{
    EthernetClient client = server.available();
    if (client)
    {
        while (client.connected())
        {
            if (client.available())
            {
                char c = client.read();
                if (readString.length() < 30)
                {
                    readString.concat(c);
                    Serial.print(c);
                    if (c == '\n')
                    {
                        Serial.println("");
                        Serial.println(readString);
                        Serial.println("");
                        int Le = readString.indexOf("L=");
                        int He = readString.indexOf("H=");
                        Serial.print("L= position: ");
                        Serial.println(Le);
                        Serial.print("H= position: ");
                        Serial.println(He);
                        if (Le > 1)
                        {
                            if (readString.substring(Le,Le+3) == "L=1")
                            {
                                digitalWrite(ledPin, HIGH);
                                Serial.println("ledpin paa");
                                LEDON = true;
                            }
                            if (readString.substring(Le,Le+3)== "L=0")
                            {
                                digitalWrite(ledPin, LOW);
                                Serial.println("ledpin av");
                                LEDON = false;
                            }
                        }
                        if (He > 1)
                        {
                            if (readString.substring(He,(He+3)) == "H=1")
                            {
                                digitalWrite(heatpin, HIGH);
                                Serial.println("heatpin paa");
                                HEATON = true;
                            }
                            if (readString.substring(He,(He+3)) == "H=0")
                            {
                                digitalWrite(heatpin, LOW);
                                Serial.println("heatpin av");
                                HEATON = false;
                            }
                        }
                        client.println("HTTP/1.1 200 OK");
                        client.println("Content-Type: text/html");
                        client.println();
                        client.print  ("<body style=background-color:white>");
                        client.println("<font color=’red’><h1>Arduino Remote control</font></h1>");
                        client.println("<hr />");
                        client.println("<font color=’blue’ size=’5'>Analog input: ");
                        sensorValue = analogRead(sensorPin);
                        client.print(sensorValue);
                        Serial.print(sensorValue);
                        client.println("<br />");
                        client.println("<br />");
                        client.println("<hr />");
                        client.println("<h1>LED control</h1>");
                        client.println("<form method=get name=LED> <input type='radio' name='L' value='1'>LED ON<br><input type='radio' name='L' value='0'>LED OFF<br><input type='radio' name='H' value='1'>HEAT ON<br><input type='radio' name='H' value='0'>HEAT OFF<br><input type=submit value=submit></form>");
                        client.println("<br />");
                        client.print("<font size=’5'>LED status: ");
                        if (LEDON == true) {
                            client.println("<font color=’green’ size=’5'>ON");
                            Serial.print("led on");
                        }
                        else {
                            client.println("<font color=’grey’ size=’5'>OFF");
                            Serial.println("Led off");
                        }
                        client.print("<font size=’5'>Heatpin status: ");
                        if (HEATON == true) {
                            client.println("<font color=’green’ size=’5'>ON");
                            Serial.print("Heat on");
                        }
                        else {
                            client.println("<font color=’grey’ size=’5'>OFF");
                            Serial.println("Heat off");
                        }
                        client.println("<hr />");
                        client.println("</body></html>");
                        readString="";
                        client.stop();
                        Serial.println("stopped client");
                    }
                }
            }
        }
    }
}
Título: Re: [Pedido de Ajuda] Arduino EthernetShield Armazenar um pagina html e imagem dentr
Enviado por: microbyte em 09 de Abril de 2012, 19:12
Nao micro o meu index.html esta dentro do SD do meu arduino...ethernet shield.

Ou seja nesse index.html esta associada essa imagem que tambem esta no SD , eu quero que quando se clique nela... me ligue um led  um PIn qualquer, e quando se clique novamente na imagem que desligue o led.

Entendes agora?

Ou achas que existia um codigo mais facil?

Agora é que me baralhaste todo..
Mas pronto... De qualquer maneira, se tens acesso ao código fonte do ficheiro é só alterares para que ele faça o que tu queres. Isto deixou de ser uma questão de electrónica/ethernet shield e passou a ser uma questão de programação HTML que está fora do scope do fórum.



MicroByte tenho 100% certeza que podes me ajudar mais que o teu ultimo post.
Se leres bem...que penso que não leste, é fácil deduzir que se eu soubesse o que fazer , não vinha cá sequer questionar, mas sim partilhar o que sei.. é somente isso que necessito de ti,caso queiras.. que partilhes o teu saber.. que como já referi no primeiro parágrafo tu sabes...

Eu a parte do html penso que já estou quase desenrascado, agora a parte que falta é qual a parte que tenho que alterar no código do ARDUINO para que ele acenda o led, quando clico na IMAGEM.

Penso que com isto, fui explicito.

Jovem, não me interpretes mal... Eu voltei a ler e percebi perfeitamente o que disseste e continuo a dizer-te que a tua questão é meramente de HTML e nada tem a ver com o Arduino.

Ser um botão ou uma parte de uma imagem é exactamente o mesmo em termos de programação do Arduino.

Mas vamos então debruçar-nos no assunto.
Diz-me uma coisa, o que faz a tua página neste momento (uma screen ajudava)?
Tens botões para acender/apagar as luzes?

Não é má vontade da nossa parte, tens de perceber que às escuras é complicado ajudar. Tens de nos dizer a que nível de desenvolvimento estás e o que tens feito se queres obter alguma ajuda... ;)
Título: Re: [Pedido de Ajuda] Arduino EthernetShield Armazenar um pagina html e imagem dentr
Enviado por: r16 em 10 de Abril de 2012, 16:28
Microbyte, agradeço novamente a tua intenção de querer ajudar.

Vamos entao por partes.

1 Parte:
O sketch que tenho de momento dentro do arduino é este:

Código: [Seleccione]
#include <LiquidCrystal.h>
#include <SPI.h>
#include <SdFat.h>
#include <SdFatUtil.h>
#include <Ethernet.h>
#define BUFSIZ 128
#define greenLEDandBEEP 2
#define redLEDpin 3
boolean led2 = true;
int hits = 0; // Set the number of hits the hit counter will start at.
int units = 0;
int count = 0;
int photocellPin = 2;
int photocellReading;
LiquidCrystal lcd(4, 5, 6, 7, 8, 9);

//Local ethernet setup
byte mac[] = {
  0x90, 0xA2, 0xDA, 0x00, 0x1C, 0x0E };
byte ip[] = {
  192, 168, 1, 80 };
char rootFileName[] = "index.htm";
Server server(8080);

//SD card stuff
Sd2Card card;
SdVolume volume;
SdFile root;
SdFile file;
#define error(s) error_P(PSTR(s))
void error_P(const char* str) {
  PgmPrint("error: ");
  SerialPrintln_P(str);
  if (card.errorCode()) {
    PgmPrint("SD error: ");
    Serial.print(card.errorCode(), HEX);
    Serial.print(',');
    Serial.println(card.errorData(), HEX);
  }
  while(1);
}

void setup() {
  lcd.begin(16, 2);
  lcd.print("Web Server v2.00");
  lcd.setCursor(0, 1);
  lcd.print("Hits:");

  Serial.begin(9600);

  pinMode(greenLEDandBEEP, OUTPUT);
  pinMode(redLEDpin, OUTPUT);

  PgmPrint("Free RAM: ");
  Serial.println(FreeRam()); 

  pinMode(10, OUTPUT);             
  digitalWrite(10, HIGH);             

  if (!card.init(SPI_HALF_SPEED, 4)) error("card.init failed!");

  if (!volume.init(&card)) error("vol.init failed!");

  PgmPrint("Volume is FAT");
  Serial.println(volume.fatType(),DEC);
  Serial.println();

  if (!root.openRoot(&volume)) error("openRoot failed");

  PgmPrintln("Files found in root:");
  root.ls(LS_DATE | LS_SIZE);
  Serial.println();

  PgmPrintln("Files found in all dirs:");
  root.ls(LS_R);

  Serial.println();
  PgmPrintln("Done");

  Ethernet.begin(mac, ip);
  server.begin();
}


void loop()
{
  if(count >=500)
  { 
    led2 = !led2;
    digitalWrite(redLEDpin, led2);
    count = 0;
  }
  count +=1;

  char clientline[BUFSIZ];
  char *filename;
  int image = 0;
  int index = 0;

  Client client = server.available();
  if (client) {
    boolean current_line_is_blank = true;

    index = 0;

    while (client.connected()) {
      if (client.available()) {
        char c = client.read();

        if (c != '\n' && c != '\r') {
          clientline[index] = c;
          index++;
          if (index >= BUFSIZ)
            index = BUFSIZ -1;

          continue;
        }

        clientline[index] = 0;
        filename = 0;

        Serial.println(clientline);

        if (strstr(clientline, "GET / ") != 0) {
          filename = rootFileName;

        }
        if (strstr(clientline, "GET /") != 0) {
          if (!filename) filename = clientline + 5;

          (strstr(clientline, " HTTP"))[0] = 0;

          Serial.println(filename);

          if (! file.open(&root, filename, O_READ)) {
            client.println("HTTP/1.1 404 Not Found");
            client.println("Content-Type: text/html");
            client.println();
            client.println("<h2>Error 404</h2>");
            client.println("<s2>The file does not exist.<s2>");
            client.println("");
            break;
          }

          Serial.println("Opened!");
          //File types
          client.println("HTTP/1.1 200 OK");
          if (strstr(filename, ".htm") != 0)
            client.println("Content-Type: text/html");
          else if (strstr(filename, ".css") != 0)
            client.println("Content-Type: text/css");
          else if (strstr(filename, ".png") != 0)
            client.println("Content-Type: image/png");
          else if (strstr(filename, ".jpg") != 0)
            client.println("Content-Type: image/jpeg");
          else if (strstr(filename, ".gif") != 0)
            client.println("Content-Type: image/gif");
          else if (strstr(filename, ".3gp") != 0)
            client.println("Content-Type: video/mpeg");
          else if (strstr(filename, ".pdf") != 0)
            client.println("Content-Type: application/pdf");
          else if (strstr(filename, ".js") != 0)
            client.println("Content-Type: application/x-javascript");
          else if (strstr(filename, ".xml") != 0)
            client.println("Content-Type: application/xml");
          else
            client.println("Content-Type: text");
          client.println();

          int16_t c;
          while ((c = file.read()) >= 0) {
            //Serial.print((char)c); //Prints all HTML code to serial (For debuging)
            client.print((char)c); //Prints all HTML code for web page
          }

          //Hit counter math
          if(units >= 2)
          {
            hits ++;
            units = 0;
          }
          units +=1;
          //End hit counter math

          //Print the hit counters and light value
          lcd.setCursor(6, 1);
          lcd.print(hits); //Print hits for LCD hit counter

          client.print("<html><body>"); //HTML code starts here
          client.print("<P align=\"center\">");
          client.print("Hits since reset: ");   
          client.print(hits); //Print hits to client
          client.print("
");

          photocellReading = analogRead(photocellPin);
          client.print("Light reading: ");
          client.print(photocellReading); //Prints light reading to client

          // A few threshholds
          if (photocellReading < 10) {
            client.print(" - Dark");
          }
          else if (photocellReading < 200) {
            client.print(" - Dim");
          }
          else if (photocellReading < 500) {
            client.print(" - Light");
          }
          else if (photocellReading < 800) {
            client.print(" - Bright");
          }
          else {
            client.print(" - Very bright");
          }

          client.print("</p></body></html>"); //HTML code ends here
          //End hit counter and light value

          file.close();

        }
        else {
          client.println("HTTP/1.1 404 Not Found");
          client.println("Content-Type: text/html");
          client.println();
          client.println("<h2>Error 404</h2>");
          client.println("");
        }
        break;
      }
    }
    digitalWrite(greenLEDandBEEP, HIGH);
    delay(1);
    digitalWrite(greenLEDandBEEP, LOW);
    client.stop();
  }

}

//The End /*

ora bem, o que esse codigo faz?? Esse codigo , quando eu digito no browser o ip do arduino,ele vai me abrir um index.html que esta armezando no SD juntamente com uma imagem, aqui fica o codigo html do index.html

Código: [Seleccione]
<html>
<body>

<img src="w3schools.jpg" width="104" height="142" />

</body>
</html>


Agora o que eu pretendo?? o que pretendo é saber que resto de código falta ai no index.html, e qual é o codigo que tenho que por aqui:

Código: [Seleccione]
#include <LiquidCrystal.h>
#include <SPI.h>
#include <SdFat.h>
#include <SdFatUtil.h>
#include <Ethernet.h>
#define BUFSIZ 128
#define greenLEDandBEEP 2
#define redLEDpin 3
boolean led2 = true;
int hits = 0; // Set the number of hits the hit counter will start at.
int units = 0;
int count = 0;
int photocellPin = 2;
int photocellReading;
LiquidCrystal lcd(4, 5, 6, 7, 8, 9);

//Local ethernet setup
byte mac[] = {
  0x90, 0xA2, 0xDA, 0x00, 0x1C, 0x0E };
byte ip[] = {
  192, 168, 1, 80 };
char rootFileName[] = "index.htm";
Server server(8080);

//SD card stuff
Sd2Card card;
SdVolume volume;
SdFile root;
SdFile file;
#define error(s) error_P(PSTR(s))
void error_P(const char* str) {
  PgmPrint("error: ");
  SerialPrintln_P(str);
  if (card.errorCode()) {
    PgmPrint("SD error: ");
    Serial.print(card.errorCode(), HEX);
    Serial.print(',');
    Serial.println(card.errorData(), HEX);
  }
  while(1);
}

void setup() {
  lcd.begin(16, 2);
  lcd.print("Web Server v2.00");
  lcd.setCursor(0, 1);
  lcd.print("Hits:");

  Serial.begin(9600);

  pinMode(greenLEDandBEEP, OUTPUT);
  pinMode(redLEDpin, OUTPUT);

  PgmPrint("Free RAM: ");
  Serial.println(FreeRam()); 

  pinMode(10, OUTPUT);             
  digitalWrite(10, HIGH);             

  if (!card.init(SPI_HALF_SPEED, 4)) error("card.init failed!");

  if (!volume.init(&card)) error("vol.init failed!");

  PgmPrint("Volume is FAT");
  Serial.println(volume.fatType(),DEC);
  Serial.println();

  if (!root.openRoot(&volume)) error("openRoot failed");

  PgmPrintln("Files found in root:");
  root.ls(LS_DATE | LS_SIZE);
  Serial.println();

  PgmPrintln("Files found in all dirs:");
  root.ls(LS_R);

  Serial.println();
  PgmPrintln("Done");

  Ethernet.begin(mac, ip);
  server.begin();
}


void loop()
{
  if(count >=500)
  { 
    led2 = !led2;
    digitalWrite(redLEDpin, led2);
    count = 0;
  }
  count +=1;

  char clientline[BUFSIZ];
  char *filename;
  int image = 0;
  int index = 0;

  Client client = server.available();
  if (client) {
    boolean current_line_is_blank = true;

    index = 0;

    while (client.connected()) {
      if (client.available()) {
        char c = client.read();

        if (c != '\n' && c != '\r') {
          clientline[index] = c;
          index++;
          if (index >= BUFSIZ)
            index = BUFSIZ -1;

          continue;
        }

        clientline[index] = 0;
        filename = 0;

        Serial.println(clientline);

        if (strstr(clientline, "GET / ") != 0) {
          filename = rootFileName;

        }
        if (strstr(clientline, "GET /") != 0) {
          if (!filename) filename = clientline + 5;

          (strstr(clientline, " HTTP"))[0] = 0;

          Serial.println(filename);

          if (! file.open(&root, filename, O_READ)) {
            client.println("HTTP/1.1 404 Not Found");
            client.println("Content-Type: text/html");
            client.println();
            client.println("<h2>Error 404</h2>");
            client.println("<s2>The file does not exist.<s2>");
            client.println("");
            break;
          }

          Serial.println("Opened!");
          //File types
          client.println("HTTP/1.1 200 OK");
          if (strstr(filename, ".htm") != 0)
            client.println("Content-Type: text/html");
          else if (strstr(filename, ".css") != 0)
            client.println("Content-Type: text/css");
          else if (strstr(filename, ".png") != 0)
            client.println("Content-Type: image/png");
          else if (strstr(filename, ".jpg") != 0)
            client.println("Content-Type: image/jpeg");
          else if (strstr(filename, ".gif") != 0)
            client.println("Content-Type: image/gif");
          else if (strstr(filename, ".3gp") != 0)
            client.println("Content-Type: video/mpeg");
          else if (strstr(filename, ".pdf") != 0)
            client.println("Content-Type: application/pdf");
          else if (strstr(filename, ".js") != 0)
            client.println("Content-Type: application/x-javascript");
          else if (strstr(filename, ".xml") != 0)
            client.println("Content-Type: application/xml");
          else
            client.println("Content-Type: text");
          client.println();

          int16_t c;
          while ((c = file.read()) >= 0) {
            //Serial.print((char)c); //Prints all HTML code to serial (For debuging)
            client.print((char)c); //Prints all HTML code for web page
          }

          //Hit counter math
          if(units >= 2)
          {
            hits ++;
            units = 0;
          }
          units +=1;
          //End hit counter math

          //Print the hit counters and light value
          lcd.setCursor(6, 1);
          lcd.print(hits); //Print hits for LCD hit counter

          client.print("<html><body>"); //HTML code starts here
          client.print("<P align=\"center\">");
          client.print("Hits since reset: ");   
          client.print(hits); //Print hits to client
          client.print("
");

          photocellReading = analogRead(photocellPin);
          client.print("Light reading: ");
          client.print(photocellReading); //Prints light reading to client

          // A few threshholds
          if (photocellReading < 10) {
            client.print(" - Dark");
          }
          else if (photocellReading < 200) {
            client.print(" - Dim");
          }
          else if (photocellReading < 500) {
            client.print(" - Light");
          }
          else if (photocellReading < 800) {
            client.print(" - Bright");
          }
          else {
            client.print(" - Very bright");
          }

          client.print("</p></body></html>"); //HTML code ends here
          //End hit counter and light value

          file.close();

        }
        else {
          client.println("HTTP/1.1 404 Not Found");
          client.println("Content-Type: text/html");
          client.println();
          client.println("<h2>Error 404</h2>");
          client.println("");
        }
        break;
      }
    }
    digitalWrite(greenLEDandBEEP, HIGH);
    delay(1);
    digitalWrite(greenLEDandBEEP, LOW);
    client.stop();
  }

}

//The End /

Para que quando clique na imagem....do site me faça um digitalwrite ao pino 7 que faz acender um led, e quando clicar novamente na imagem me faca desligar o led com o digitalwrite low.

desta vez fiz me entender? ou nao estou a ser claro ainda?
obrigado
Título: Re: [Pedido de Ajuda] Arduino EthernetShield Armazenar um pagina html e imagem dentr
Enviado por: senso em 10 de Abril de 2012, 16:43
Tens de ir ler uns tutorias de HTML para fazer o que queres..
Título: Re: [Pedido de Ajuda] Arduino EthernetShield Armazenar um pagina html e imagem dentr
Enviado por: r16 em 10 de Abril de 2012, 16:58
Senso.. obrigado.
Título: Re: [Pedido de Ajuda] Arduino EthernetShield Armazenar um pagina html e imagem dentr
Enviado por: Marvin em 10 de Abril de 2012, 17:32
R16, precisas de compreender qual é o evento (se é que existe algum) disparado quando existe um postback no servidor. De seguida então fazer seguir o tratamento desse evento na arduino. Pessoalmente nunca fiz isso, mas isto é como funciona o html e um servidor web.

Se o que eu disse não te faz sentido, então segue o conselho do Senso.
Título: Re: [Pedido de Ajuda] Arduino EthernetShield Armazenar um pagina html e imagem dentr
Enviado por: r16 em 10 de Abril de 2012, 19:14
Faz tudo sentido... so que de tanto que ja escrevi ainda nao compreederam que eu nao sei e qual o codigo que se poe no sketch do arduino..

o codigo da pagina html e uma coisa...


e o codigo do arduino é outra... mas ainda nao entendera essa parte e nao me consigo explicar melhor...ou entao aqui tambem ninguem sabe como se faz, que pode ser esse outro problema.
Título: Re: [Pedido de Ajuda] Arduino EthernetShield Armazenar um pagina html e imagem dentr
Enviado por: poliveira1978 em 10 de Abril de 2012, 20:20
se o que pretendes é alterar o estado da saida:

saida=!saida -> inverte, ou seja:
se ligado -> desliga;
se desligado -> liga;
Título: Re: [Pedido de Ajuda] Arduino EthernetShield Armazenar um pagina html e imagem dentr
Enviado por: r16 em 10 de Abril de 2012, 20:44
 :-\ Desisto..é só tiros ao lado.

é  a ultima vez que me vou explicar... porque já vi que não estao a entender o que quero..

tenho um index.html... com uma imagem... e quero saber qual o codigo que ponho no sketch do arduino, para que quando clico na imagem, me faca um digitalwrite high ao pino7, e quando clicar novamente o digitalwrite low ao pino7.

........uffffff
Título: Re: [Pedido de Ajuda] Arduino EthernetShield Armazenar um pagina html e imagem dentr
Enviado por: senso em 10 de Abril de 2012, 20:49
Precisas de código html que coloque as imagens que queres como botões, e código html que envie uma resposta ao servidor, ou seja o arduino, com essa resposta é um if e um digitalWrite, portanto a tua duvida é unica e simplesmente sobre HTML.
Tens um exemplo com radio-buttons, experimenta-o, se calhar é mais simples usar esses radio-buttons que imagens clicaveis.

Por muito gosto que tenha em ajudar não pesco nada de html, portanto faz como te disse acima e vai ler tutoriais sobre html.
Título: Re: [Pedido de Ajuda] Arduino EthernetShield Armazenar um pagina html e imagem dentr
Enviado por: r16 em 10 de Abril de 2012, 20:57
ok..... entao vamos fazer de outra forma....
 
Este codigo que tenho aqui esta a funcionar em pleno... quando clico no radio botton que diz COZINHA ON ele activa o pino 7, e quando clico em COZINHA OFF ele desliga o pino 7, mas atencao,.. este codigo nada tem haver com o outro pois este gera o html dentro do proprio sketch.

Código: [Seleccione]
#include <SPI.h>
#include <Ethernet.h>

// ethernet configuration
byte mac[] = { 0x90, 0xA2, 0xDA, 0x00, 0x49, 0xD6 };
byte ip[] = { 192, 168, 1, 76 }; // P1 --> { 10, 1, 1, 5 };
EthernetServer server(6969);              // port 80 is default for HTTP

// initial
int LED = 7;          // led is connected to digital pin 3

char c = 0;           // received data
char command[2] = "\0";  // command


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

}


void loop()
{
  EthernetClient client = server.available();
  // detect if current is the first line
  boolean current_line_is_first = true;

  if (client) {
    // an http request ends with a blank line
    boolean current_line_is_blank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        // if we've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so we can send a reply
        if (c == '\n' && current_line_is_blank) {
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println();
         
         [b] // webpage title
         // client.println("<left><p><h1>Arduino + Ethernet Shield Application v1.0</h1></p><left><hr><br />");

         
         
          // button functions
          client.println("<form  method=get name=form>");
          client.println("<button name=b value=1 type=submit style=height:50px;width:100px>Cozinha ON</button>");
          client.println("<button name=b value=2 type=submit style=height:50px;width:100px>Cozinha OFF</button>");
         
         client.println("</form><br />");
         
         
          //<img src="http://4.bp.blogspot.com/-S6G5PgB28q4/Tnb7zaPegmI/AAAAAAAAR50/peD5LeP0ar0/s1600/sw_Auto_Giardino-500x293.jpg" id="Image1" alt="" border="0" style="width:479px;height:324px;"></div>
       

         
          break;
        }
        if (c == '\n') {
          // we're starting a new line
          current_line_is_first = false;
          current_line_is_blank = true;
        }
        else if (c != '\r') {
          // we've gotten a character on the current line
          current_line_is_blank = false;
        }
        // get the first http request
        if (current_line_is_first && c == '=') {
          for (int i = 0; i < 1; i++) {
            c = client.read();
            command[i] = c;
          }
          // LED control
          if (!strcmp(command, "1")) {
            digitalWrite(LED, HIGH);
          }
          else if (!strcmp(command, "2")) {
            digitalWrite(LED, LOW);
          }
        }
      }
    }
    // give the web browser time to receive the data
    delay(1);
    client.stop();
  }
}[/b]



Pronto esse codigo eu tenho a funcionar neste momento e funciona bem,,,
agora quero que me ajudem a passar essa parte do codigo que está em negrito....para este codigo..

Código: [Seleccione]
#include <LiquidCrystal.h>
#include <SPI.h>
#include <SdFat.h>
#include <SdFatUtil.h>
#include <Ethernet.h>
#define BUFSIZ 128
#define greenLEDandBEEP 2
#define redLEDpin 3
boolean led2 = true;
int hits = 0; // Set the number of hits the hit counter will start at.
int units = 0;
int count = 0;
int photocellPin = 2;
int photocellReading;
LiquidCrystal lcd(4, 5, 6, 7, 8, 9);

//Local ethernet setup
byte mac[] = {
  0x90, 0xA2, 0xDA, 0x00, 0x1C, 0x0E };
byte ip[] = {
  192, 168, 1, 80 };
char rootFileName[] = "index.htm";
Server server(8080);

//SD card stuff
Sd2Card card;
SdVolume volume;
SdFile root;
SdFile file;
#define error(s) error_P(PSTR(s))
void error_P(const char* str) {
  PgmPrint("error: ");
  SerialPrintln_P(str);
  if (card.errorCode()) {
    PgmPrint("SD error: ");
    Serial.print(card.errorCode(), HEX);
    Serial.print(',');
    Serial.println(card.errorData(), HEX);
  }
  while(1);
}

void setup() {
  lcd.begin(16, 2);
  lcd.print("Web Server v2.00");
  lcd.setCursor(0, 1);
  lcd.print("Hits:");

  Serial.begin(9600);

  pinMode(greenLEDandBEEP, OUTPUT);
  pinMode(redLEDpin, OUTPUT);

  PgmPrint("Free RAM: ");
  Serial.println(FreeRam()); 

  pinMode(10, OUTPUT);             
  digitalWrite(10, HIGH);             

  if (!card.init(SPI_HALF_SPEED, 4)) error("card.init failed!");

  if (!volume.init(&card)) error("vol.init failed!");

  PgmPrint("Volume is FAT");
  Serial.println(volume.fatType(),DEC);
  Serial.println();

  if (!root.openRoot(&volume)) error("openRoot failed");

  PgmPrintln("Files found in root:");
  root.ls(LS_DATE | LS_SIZE);
  Serial.println();

  PgmPrintln("Files found in all dirs:");
  root.ls(LS_R);

  Serial.println();
  PgmPrintln("Done");

  Ethernet.begin(mac, ip);
  server.begin();
}


void loop()
{
  if(count >=500)
  { 
    led2 = !led2;
    digitalWrite(redLEDpin, led2);
    count = 0;
  }
  count +=1;

  char clientline[BUFSIZ];
  char *filename;
  int image = 0;
  int index = 0;

  Client client = server.available();
  if (client) {
    boolean current_line_is_blank = true;

    index = 0;

    while (client.connected()) {
      if (client.available()) {
        char c = client.read();

        if (c != '\n' && c != '\r') {
          clientline[index] = c;
          index++;
          if (index >= BUFSIZ)
            index = BUFSIZ -1;

          continue;
        }

        clientline[index] = 0;
        filename = 0;

        Serial.println(clientline);

        if (strstr(clientline, "GET / ") != 0) {
          filename = rootFileName;

        }
        if (strstr(clientline, "GET /") != 0) {
          if (!filename) filename = clientline + 5;

          (strstr(clientline, " HTTP"))[0] = 0;

          Serial.println(filename);

          if (! file.open(&root, filename, O_READ)) {
            client.println("HTTP/1.1 404 Not Found");
            client.println("Content-Type: text/html");
            client.println();
            client.println("<h2>Error 404</h2>");
            client.println("<s2>The file does not exist.<s2>");
            client.println("");
            break;
          }

          Serial.println("Opened!");
          //File types
          client.println("HTTP/1.1 200 OK");
          if (strstr(filename, ".htm") != 0)
            client.println("Content-Type: text/html");
          else if (strstr(filename, ".css") != 0)
            client.println("Content-Type: text/css");
          else if (strstr(filename, ".png") != 0)
            client.println("Content-Type: image/png");
          else if (strstr(filename, ".jpg") != 0)
            client.println("Content-Type: image/jpeg");
          else if (strstr(filename, ".gif") != 0)
            client.println("Content-Type: image/gif");
          else if (strstr(filename, ".3gp") != 0)
            client.println("Content-Type: video/mpeg");
          else if (strstr(filename, ".pdf") != 0)
            client.println("Content-Type: application/pdf");
          else if (strstr(filename, ".js") != 0)
            client.println("Content-Type: application/x-javascript");
          else if (strstr(filename, ".xml") != 0)
            client.println("Content-Type: application/xml");
          else
            client.println("Content-Type: text");
          client.println();

          int16_t c;
          while ((c = file.read()) >= 0) {
            //Serial.print((char)c); //Prints all HTML code to serial (For debuging)
            client.print((char)c); //Prints all HTML code for web page
          }

          //Hit counter math
          if(units >= 2)
          {
            hits ++;
            units = 0;
          }
          units +=1;
          //End hit counter math

          //Print the hit counters and light value
          lcd.setCursor(6, 1);
          lcd.print(hits); //Print hits for LCD hit counter

          client.print("<html><body>"); //HTML code starts here
          client.print("<P align=\"center\">");
          client.print("Hits since reset: ");   
          client.print(hits); //Print hits to client
          client.print("
");

          photocellReading = analogRead(photocellPin);
          client.print("Light reading: ");
          client.print(photocellReading); //Prints light reading to client

          // A few threshholds
          if (photocellReading < 10) {
            client.print(" - Dark");
          }
          else if (photocellReading < 200) {
            client.print(" - Dim");
          }
          else if (photocellReading < 500) {
            client.print(" - Light");
          }
          else if (photocellReading < 800) {
            client.print(" - Bright");
          }
          else {
            client.print(" - Very bright");
          }

          client.print("</p></body></html>"); //HTML code ends here
          //End hit counter and light value

          file.close();

        }
        else {
          client.println("HTTP/1.1 404 Not Found");
          client.println("Content-Type: text/html");
          client.println();
          client.println("<h2>Error 404</h2>");
          client.println("");
        }
        break;
      }
    }
    digitalWrite(greenLEDandBEEP, HIGH);
    delay(1);
    digitalWrite(greenLEDandBEEP, LOW);
    client.stop();
  }

}

//The End /


Assim, ja fica a funcionar penso eu.........depois e uma questao de por a imagem em vez dos raddio button.
Título: Re: [Pedido de Ajuda] Arduino EthernetShield Armazenar um pagina html e imagem dentr
Enviado por: senso em 10 de Abril de 2012, 21:03
É meteres isso no teu index.html que lês do cartão SD, simplesmente um tem o html no código do arduino de modo explicito e o outro lê de um cartão.
Título: Re: [Pedido de Ajuda] Arduino EthernetShield Armazenar um pagina html e imagem dentr
Enviado por: CBX em 10 de Abril de 2012, 21:04
lê isto: http://www.nuelectronics.com/estore/index.php?main_page=project_eth (http://www.nuelectronics.com/estore/index.php?main_page=project_eth)

em todos os projectos "arduino web server" tens exemplos disso...
Título: Re: [Pedido de Ajuda] Arduino EthernetShield Armazenar um pagina html e imagem dentr
Enviado por: r16 em 10 de Abril de 2012, 21:08
Certo...
Mas esse ultimo sketch que é o que le o index.html do cartao... nao tem este codigo que é o que me interessa:
So nao sei onde o por sem dar erros na compilacao

Código: [Seleccione]
// button functions
          client.println("<form  method=get name=form>");
          client.println("<button name=b value=1 type=submit style=height:50px;width:100px>Cozinha ON</button>");
          client.println("<button name=b value=2 type=submit style=height:50px;width:100px>Cozinha OFF</button>");
          client.println("<img src=http://4.bp.blogspot.com/-S6G5PgB28q4/Tnb7zaPegmI/AAAAAAAAR50/peD5LeP0ar0/s1600/sw_Auto_Giardino-500x293.jpg>");
         
          client.println("<form  method=get name=form>");
          client.println("<button style="background-color:transparent" name=b value=1 type=submit style=height:400px;width:200px></button>");
          client.println("<button name=b value=2 type=submit style=height:50px;width:100px>Cozinha OFF</button>");
          client.println("</form><br />");

          client.println("</form><br />");
         
         
          //<img src="http://4.bp.blogspot.com/-S6G5PgB28q4/Tnb7zaPegmI/AAAAAAAAR50/peD5LeP0ar0/s1600/sw_Auto_Giardino-500x293.jpg" id="Image1" alt="" border="0" style="width:479px;height:324px;"></div>
       

         
          break;
        }
        if (c == '\n') {
          // we're starting a new line
          current_line_is_first = false;
          current_line_is_blank = true;
        }
        else if (c != '\r') {
          // we've gotten a character on the current line
          current_line_is_blank = false;
        }
        // get the first http request
        if (current_line_is_first && c == '=') {
          for (int i = 0; i < 1; i++) {
            c = client.read();
            command[i] = c;
          }
          // LED control
          if (!strcmp(command, "1")) {
            digitalWrite(LED, HIGH);
          }
          else if (!strcmp(command, "2")) {
            digitalWrite(LED, LOW);
          }
        }
      }
    }
    // give the web browser time to receive the data
    delay(1);
    client.stop();
  }
}



Ou seja eu no index.html que esta no cartao...ja tenho o codigo la todo certinho.. agora e so passar esse que ta ai em cima para dentro do sketch.


Eu ja tentei... mas como nao tou "entendido" na programacao estarei a passa-lo para o sitio incorrecto e da me erro a compilar.
Título: Re: [Pedido de Ajuda] Arduino EthernetShield Armazenar um pagina html e imagem dentr
Enviado por: r16 em 10 de Abril de 2012, 21:10
lê isto: http://www.nuelectronics.com/estore/index.php?main_page=project_eth (http://www.nuelectronics.com/estore/index.php?main_page=project_eth)

em todos os projectos "arduino web server" tens exemplos disso...

Obrigado pelo teu comentario mas se tivesses lido bem, nao se trata disso.
Título: Re: [Pedido de Ajuda] Arduino EthernetShield Armazenar um pagina html e imagem dentr
Enviado por: senso em 10 de Abril de 2012, 21:12
Se já lá tens o html o importante centra-se unica e exclusivamente no client.read()
Título: Re: [Pedido de Ajuda] Arduino EthernetShield Armazenar um pagina html e imagem dentr
Enviado por: r16 em 10 de Abril de 2012, 21:15
Certo,correcto... e precisamente agora essa parte que nao sei transferir de um codigo para o outro.
Título: Re: [Pedido de Ajuda] Arduino EthernetShield Armazenar um pagina html e imagem dentr
Enviado por: Hugu em 11 de Abril de 2012, 00:03
Acho que o problema é que o nosso amigo pensa que o problema é um, mas o que o pessoal está a tentar dizer-te é que é outro e nao aquele que pensas ser.. :P

@R16: nao consegues meter já o teu codigo html num servidor gratuito para o pessoal ver o que está feito ou nao no teu html (bem co ficheiro html em txt!)

E ja agora, posta fotos dos equipamentos/hardware que estás a usar! Convem saber que toutch-screen estás a usar e como tens o teu arduino/ethernet shield ligado?
Título: Re: [Pedido de Ajuda] Arduino EthernetShield Armazenar um pagina html e imagem dentr
Enviado por: r16 em 15 de Abril de 2012, 00:13
Viva, já consegui resolver o meu problema.
Agora so falta descobrir um ponto... que não consigo resolver e dai peço ajuda.

o codigo que esta a funcionar e este:

Código: [Seleccione]
#include <Ethernet.h>
#include <SPI.h>
/*
    Simple Ethernet Test

 Arduino server outputs simple text to browser

     The circuit:
     * Arduino Duemilanove
 * Arduino Ethernet shield
 * Basic FTDI breakout 5V
 *LED connected to GND and digital pin 4 via resistor

 By Minde
     http://www.sciencprog.com/
 */

byte mac[] = { 0x90, 0xA2, 0xDA, 0x00, 0x49, 0xD6 };
byte ip[]    = {192,168,1,70}; // IP address of WiShield
byte gateway[]  = {192,168,1,254}; // router or gateway IP address
byte subnet[] = {255,255,255,0};


Server server(6969);        //server port
int ledPin = 4;  // LED pin
int LEDpin = 7;
String state = String(3);
word Adc = 0;
String readString = String(30); //string for fetching data from address
boolean LEDON = false; //LED status flag



void Pasword();
void Portada();


void setup(){
  //start Ethernet
  Ethernet.begin(mac, ip, gateway, subnet);
  //Set pin 4 to output
  pinMode(LEDpin,OUTPUT);
 
  digitalWrite(LEDpin,LOW);
  state = "OFF";
String state = String(3);
  //enable serial datada print
  Serial.begin(9600);
}


void loop(){
  // Create a client connection
 
  Client client = server.available();
  if (client) {
    while (client.connected()){   
      char c = client.read();
      if (readString.length() < 30){
         readString += c;
      }
      Serial.print(c);
      if (c == '\n') {     
        if(readString.trim() == ("GET /?C=1678 HTTP/1.1")){
          //client.println("<h1>Clave Ok</h1>");
          Portada();
       }else{
          //client.println("<h1>Clave Erronea</h1>");
       }     
   
   
       //client.println("HTTP/1.1 200 OK");
       //client.println("Content-Type: text/html");
       client.println();
       client.print("<body style=background-color:#ffffff>");     

       client.println("<h1>Control de Acceso</h1>");       
       client.println("<form method=get name=LED>");
       client.println("<input type=""password"" name=C>");
     
     
       client.println("<input type=submit value=submit></form>");
     

       //clearing string for next read
       readString="";
       //stopping client
       client.stop();     
    }
  }
}
}



void Portada(){
while(1){
  // Create a client connection
  Client client = server.available();
 if (client) {
    // 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 (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.println("<form  method=get name=form>");
         
          client.println("<img src='http://dl.dropbox.com/u/6916111/tvoff.png' style=\"position:fixed;left:68px;top:80px;width:636px;height:431px;z-index:1;padding:0;\">");
          if (state == "ON") { 
       //   client.print("TESTE ");       
          client.println("<img src='http://dl.dropbox.com/u/6916111/tvon.png' type='image' style=\"position:fixed;left:254px;top:146px;width:146px;height:93px;z-index:2;padding:0;\">");
          client.println("<a href=\"./?LED=F\" src='http://dl.dropbox.com/u/6916111/off.png' type='image' style=\"position:fixed;left:254px;top:146px;width:146px;height:93px;z-index:2;padding:0;\">");
}

else {
client.println("<img src='http://dl.dropbox.com/u/6916111/off.png' type='image' style=\"position:fixed;left:254px;top:146px;width:146px;height:93px;z-index:2;padding:0;\">");
          client.println("<a href=\"./?LED=T\" src='http://dl.dropbox.com/u/6916111/tvon.png' type='image' style=\"position:fixed;left:254px;top:146px;width:146px;height:93px;z-index:2;padding:0;\">");
}

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

         
          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();
     }
      }
}
void Pasword();









o que se esta a passar é:
assim que acedo ao meu shield atraves do browser
ele entra OK , e faz o que tem a fazer que é:

Mostrar um campo onde se coloca a password e depois fazer submit a um botao e prosseguir para a pagina principal.

Ate ai tudo certo.

O que está mal, é se eu fechar o browser e voltar a colocar o ip do meu shield no browser,ele ja nao pede a senha mas sim entra directamente na pagina principal e eu nao quero isso.

Alguem sabe resolver?

Obrigado
Título: Re: [Pedido de Ajuda] Arduino EthernetShield Armazenar um pagina html e imagem dentr
Enviado por: senso em 15 de Abril de 2012, 14:31
Isso não será por causa do browser guardar cookies/cache?
Título: Re: [Pedido de Ajuda] Arduino EthernetShield Armazenar um pagina html e imagem dentr
Enviado por: r16 em 15 de Abril de 2012, 14:55
Ja me disseram isso noutro lado mas sabes porque acho que nao tem muita logica?
 Porque se eu te der o site a ti... depois de eu aqui ter aqui tambem ter entrado e ter pedido pass... a ti nao te a vai pedir.


E se eu desligar o arduino e voltar a ligar... ja pede novamente...
Por isso acho que nao tem haver com isso.


Alias testei tambem no telemovel e noutros pc e acontece sempre a mesma coisa.. deve faltar algo ai no codigo.
Título: Re: [Pedido de Ajuda] Arduino EthernetShield Armazenar um pagina html e imagem dentr
Enviado por: zedlav em 15 de Abril de 2012, 17:20
Boas.

Não testei mas só de olhar para o código diria que a variavel "state" uma vez ficando "ON" ficará sempre nesse estado, é por isso que quem se ligar a seguir ao primeiro cliente que meteu a passaword vai ter acesso directo.
Título: Re: [Pedido de Ajuda] Arduino EthernetShield Armazenar um pagina html e imagem dentr
Enviado por: r16 em 15 de Abril de 2012, 17:28
Boas.

Não testei mas só de olhar para o código diria que a variavel "state" uma vez ficando "ON" ficará sempre nesse estado, é por isso que quem se ligar a seguir ao primeiro cliente que meteu a passaword vai ter acesso directo.

zedlav nao porque o proprio codigo mae de onde eu tirei para adaptar ao meu codigo nao tinha esse state e ja acontecia o mesmo...
esse state é para outra coisa que eu sei.
Título: Re: [Pedido de Ajuda] Arduino EthernetShield Armazenar um pagina html e imagem dentr
Enviado por: zedlav em 15 de Abril de 2012, 17:50
Tens razão não é disso.
Título: Re: [Pedido de Ajuda] Arduino EthernetShield Armazenar um pagina html e imagem dentr
Enviado por: r16 em 15 de Abril de 2012, 17:52
Se quiseres ajudar teria todo o gosto em saber que havia mais um interessado querer me ajudar a acabar o projecto. falta apenas isso
Título: Re: [Pedido de Ajuda] Arduino EthernetShield Armazenar um pagina html e imagem dentr
Enviado por: Wolfz em 01 de Julho de 2012, 22:56
Tirem-me só uma duvida, afinal conseguimos colocar uma pagina html no ethernet shield (SD) e conseguimos visualizala com o arduino?
Título: Re: [Pedido de Ajuda] Arduino EthernetShield Armazenar um pagina html e imagem dentr
Enviado por: senso em 01 de Julho de 2012, 23:16
Sim, é possivel.
Título: Re: [Pedido de Ajuda] Arduino EthernetShield Armazenar um pagina html e imagem dentr
Enviado por: CBX em 01 de Julho de 2012, 23:20
edit: o senso adiantou-se, fica um exemplo:

http://arduino.cc/forum/index.php/topic,51138.0.html (http://arduino.cc/forum/index.php/topic,51138.0.html)
Título: Re: [Pedido de Ajuda] Arduino EthernetShield Armazenar um pagina html e imagem dentr
Enviado por: Wolfz em 02 de Julho de 2012, 00:19
Obrigado. Já peguei no codigo e compilei so para ver se me aparecia algum erro, e aparece-me o mesmo erro e mais alguns que aparece com o código que tem o site que o r16 utiliza.


Citar









sketch_jul01b.cpp:22:19: error: SdFat.h: No such file or directory
sketch_jul01b.cpp:23:23: error: SdFatUtil.h: No such file or directory
sketch_jul01b:41: error: no matching function for call to 'Server::Server(int)'

As of Arduino 1.0, the Server class in the Ethernet library has been renamed to EthernetServer.

C:\Users\João\Documents\arduino-1.0\hardware\arduino\cores\arduino/Server.h:4: note: candidates are: Server::Server()
C:\Users\João\Documents\arduino-1.0\hardware\arduino\cores\arduino/Server.h:4: note:                 Server::Server(const Server&)
sketch_jul01b:41: error: cannot declare variable 'server' to be of abstract type 'Server'
C:\Users\João\Documents\arduino-1.0\hardware\arduino\cores\arduino/Server.h:4: note:   because the following virtual functions are pure within 'Server':
C:\Users\João\Documents\arduino-1.0\hardware\arduino\cores\arduino/Print.h:48: note:    virtual size_t Print::write(uint8_t)
C:\Users\João\Documents\arduino-1.0\hardware\arduino\cores\arduino/Server.h:6: note:    virtual void Server::begin()
sketch_jul01b:44: error: 'Sd2Card' does not name a type
sketch_jul01b:45: error: 'SdVolume' does not name a type
sketch_jul01b:46: error: 'SdFile' does not name a type
sketch_jul01b:47: error: 'SdFile' does not name a type
sketch_jul01b.cpp: In function 'void error_P(const char*)':
sketch_jul01b:50: error: 'PgmPrint' was not declared in this scope
sketch_jul01b:51: error: 'SerialPrintln_P' was not declared in this scope
sketch_jul01b:52: error: 'card' was not declared in this scope
sketch_jul01b.cpp: In function 'void setup()':
sketch_jul01b:72: error: 'PgmPrint' was not declared in this scope
sketch_jul01b:73: error: 'FreeRam' was not declared in this scope
sketch_jul01b:78: error: 'card' was not declared in this scope
sketch_jul01b:78: error: 'SPI_HALF_SPEED' was not declared in this scope
sketch_jul01b:80: error: 'volume' was not declared in this scope
sketch_jul01b:80: error: 'card' was not declared in this scope
sketch_jul01b:83: error: 'volume' was not declared in this scope
sketch_jul01b:86: error: 'root' was not declared in this scope
sketch_jul01b:88: error: 'PgmPrintln' was not declared in this scope
sketch_jul01b:89: error: 'root' was not declared in this scope
sketch_jul01b:89: error: 'LS_DATE' was not declared in this scope
sketch_jul01b:89: error: 'LS_SIZE' was not declared in this scope
sketch_jul01b:93: error: 'LS_R' was not declared in this scope
sketch_jul01b.cpp: In function 'void loop()':
sketch_jul01b:118: error: 'class Server' has no member named 'available'
sketch_jul01b:118: error: cannot declare variable 'client' to be of abstract type 'Client'
C:\Users\João\Documents\arduino-1.0\hardware\arduino\cores\arduino/Client.h:7: note:   because the following virtual functions are pure within 'Client':
C:\Users\João\Documents\arduino-1.0\hardware\arduino\cores\arduino/Client.h:12: note:    virtual size_t Client::write(uint8_t)
C:\Users\João\Documents\arduino-1.0\hardware\arduino\cores\arduino/Client.h:13: note:    virtual size_t Client::write(const uint8_t*, size_t)
C:\Users\João\Documents\arduino-1.0\hardware\arduino\cores\arduino/Client.h:14: note:    virtual int Client::available()
C:\Users\João\Documents\arduino-1.0\hardware\arduino\cores\arduino/Client.h:15: note:    virtual int Client::read()
C:\Users\João\Documents\arduino-1.0\hardware\arduino\cores\arduino/Client.h:17: note:    virtual int Client::peek()
C:\Users\João\Documents\arduino-1.0\hardware\arduino\cores\arduino/Client.h:18: note:    virtual void Client::flush()
C:\Users\João\Documents\arduino-1.0\hardware\arduino\cores\arduino/Client.h:10: note:    virtual int Client::connect(IPAddress, uint16_t)
C:\Users\João\Documents\arduino-1.0\hardware\arduino\cores\arduino/Client.h:11: note:    virtual int Client::connect(const char*, uint16_t)
C:\Users\João\Documents\arduino-1.0\hardware\arduino\cores\arduino/Client.h:16: note:    virtual int Client::read(uint8_t*, size_t)
C:\Users\João\Documents\arduino-1.0\hardware\arduino\cores\arduino/Client.h:19: note:    virtual void Client::stop()
C:\Users\João\Documents\arduino-1.0\hardware\arduino\cores\arduino/Client.h:20: note:    virtual uint8_t Client::connected()
C:\Users\João\Documents\arduino-1.0\hardware\arduino\cores\arduino/Client.h:21: note:    virtual Client::operator bool()
sketch_jul01b:153: error: 'file' was not declared in this scope
sketch_jul01b:153: error: 'root' was not declared in this scope
sketch_jul01b:153: error: 'O_READ' was not declared in this scope
sketch_jul01b:189: error: 'file' was not declared in this scope
sketch_jul01b:237: error: 'file' was not declared in this scope

Obrigado e desculpem o encomodo ;)

Já agora se me poderem adicionar no msn para me darem uma ajuda agradecia.
joaocarlosveloso@hotmail.com
Título: Re: [Pedido de Ajuda] Arduino EthernetShield Armazenar um pagina html e imagem dentr
Enviado por: senso em 02 de Julho de 2012, 00:43
Não tens as bibliotecas SdFat, por isso é que dá esses erros todos.
Título: Re: [Pedido de Ajuda] Arduino EthernetShield Armazenar um pagina html e imagem dentr
Enviado por: Wolfz em 02 de Julho de 2012, 00:56
Já saquei este e continua a dar a mesma coisa :S

http://code.google.com/p/sdfatlib/downloads/detail?name=sdfatlib20111205.zip&can=2&q= (http://code.google.com/p/sdfatlib/downloads/detail?name=sdfatlib20111205.zip&can=2&q=)
Título: Re: [Pedido de Ajuda] Arduino EthernetShield Armazenar um pagina html e imagem dentr
Enviado por: Wolfz em 02 de Julho de 2012, 18:03
alguem me pode arranjar a libraria SDFat visto que a que arranjei não está a funcionar