Arduino reboota sozinho quando acrescento mais código dentro da minha função.

Pessoal preciso de ajuda.

Tenho uma placa Arduino UNO com Atmega32 e uma shield wifi da Asynclabs com Microship MRF24WB

Bom baixei toda a biblioteca para esta shild atualizada do GitHub.

Um dos exemplos eu consegui fazer funcionar perfeitamente. 

Neste exemplo é possível conectar à placa via conexão Ad Hoc wifi e se eu digito o IP da placa no browser do meu computador aparace uma página de Hello Word.

Acontece que eu quero passar dados via query string, ou seja pela URL.

O que é possível alterando a função sendMyPage neste IF aqui:  

   // Check if the requested URL matches "/"
    if (strcmp(URL, "/") == 0) {

Bom daí digitei por exemplo o seguinte no meu browser:  192.168.1.2/?data=@123@erico@sao paulo@

E fiz uma função que faz o parse destes dados extraíndo eles da URL, separando eles das @.

O problema é que quando coloco esta função de parce dentro da função sendMyPage minha placa fica doida.  Ou ela reboota ou trava.

Bom fui investigar no Include relacionado a esta função (não sei bem como funciona mas parece que a função é criada em tempo de execução)  veja o que tem no include:

/*
 * Function for serving web pages
 */

typedef boolean (*pageServingFunction)(char* URL);

E a função que tem no exemplo é esta (arquivos estão anexados)

boolean sendMyPage(char* URL) {
 
    // Check if the requested URL matches "/"
    if (strcmp(URL, "/") == 0) {
        // Use WiServer's print and println functions to write out the page content
        WiServer.print("<html>");
        WiServer.print("Hello World!");
        WiServer.print("</html>");
        
        // URL was recognized
        return true;
    }
    // URL not found
    return false;
}

Não pode ser o tamanho do meu programa pois olha o que aparece quando termino de compilar: Binary sketch size: 22.520 bytes (of a 32.256 byte maximum)

Alguma alma caridosa pode me explicar porquê minha placa fica loca quando eu adciona uma função de parse dendtro desta outra sendMyPage??

Exibições: 961

Anexos

Responder esta

Respostas a este tópico

Talvez não seja problema no tamanho do executavel, mas sim do consumo de memória, já tive esses problemas aqui

Rapaz... esses shields wifi, blackwidows(o arduino com wifi embutido) sao muuuuuuuuito chatos, eu desisti deles nos meus projetos, agora só uso o ethernet shield comum com um bridge wifi plugado nele :P

bom, eu fiz muita coisa com essa biblioteca wifi, e talvez eu possa ajudar

eu nunca consegui(e tentei bastante) recuperar parametros com ela, do tipo

http://ipdoarduino:porta/?variavel=valor

de forma satisfatoria...

masssssssssssssss... consegui como se fosse virtual folders, assim:

http://ipdoarduino:porta/red

http://ipdoarduino:porta/white , etc , etc

exemplo:

boolean sendMyPage(char* URL) {
    if (strcmp(URL, "/red") == 0) redState = !redState;
    if (strcmp(URL, "/white") == 0) whiteState = !whiteState;
    if (strcmp(URL, "/green") == 0) greenState = !greenState;
    digitalWrite(redPin, redState);
    digitalWrite(whitePin, whiteState);
    digitalWrite(greenPin, greenState);
    // Check if the requested URL matches "/"
   // if (strcmp(URL, "/") == 0) {
        // Use WiServer’s print and println functions to write out the page content
        WiServer.print("<html>");
        WiServer.print("Controle de Luzes no BlackWidow<br><br>");
        printLightStatus("red", redState);
        printLightStatus("white", whiteState);
        printLightStatus("green", greenState);
        WiServer.print("Voce requisitou a pagina: ");
        WiServer.print(URL);
        WiServer.print("<br>Blackwidow online por: ");
        WiServer.print(millis());
        WiServer.print(" milissegundos<br>");
        WiServer.print("</html>");
        // URL was recognized
        return true;
    //}
    // URL not found
    return false;
}

é um começo pra vc tentar.

sketch completo:

#include <WiServer.h>

#define WIRELESS_MODE_INFRA    1
#define WIRELESS_MODE_ADHOC    2

// Wireless configuration parameters —————————————-
unsigned char local_ip[] = {192,168,2,120};    // IP address of WiShield
unsigned char gateway_ip[] = {192,168,2,1};    // router or gateway IP address
unsigned char subnet_mask[] = {255,255,255,0};    // subnet mask for the local network
const prog_char ssid[] PROGMEM = {"tplink"};        // max 32 bytes

unsigned char security_type = 1;    // 0 – open; 1 – WEP; 2 – WPA; 3 – WPA2

// WPA/WPA2 passphrase
const prog_char security_passphrase[] PROGMEM = {"passphrase"};    // max 64 characters

// WEP 128-bit keys
// sample HEX keys
prog_uchar wep_keys[] PROGMEM = {                                    0xXX, 0xXX, 0xXX, 0xXX, 0xXX, 0xXX, 0xXX, 0xXX, 0xXX, 0xXX, 0xXX, 0xXX, 0xXX,    // Key 0
                                    0xXX, 0xXX, 0xXX, 0xXX, 0xXX, 0xXX, 0xXX, 0xXX, 0xXX, 0xXX, 0xXX, 0xXX, 0xXX,    // Key 1
                                    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,    0x00,    // Key 2
                                    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,    0x00    // Key 3
                                };

// setup the wireless mode
// infrastructure – connect to AP
// adhoc – connect to another WiFi device
unsigned char wireless_mode = WIRELESS_MODE_INFRA;

unsigned char ssid_len;
unsigned char security_passphrase_len;
// End of wireless configuration parameters —————————————-

int redState = 0;
int whiteState = 0;
int greenState = 0;

int redPin = 5;
int whitePin = 6;
int greenPin = 7;

// This is our page serving function that generates web pages
boolean sendMyPage(char* URL) {
    if (strcmp(URL, "/red") == 0) redState = !redState;
    if (strcmp(URL, "/white") == 0) whiteState = !whiteState;
    if (strcmp(URL, "/green") == 0) greenState = !greenState;
    digitalWrite(redPin, redState);
    digitalWrite(whitePin, whiteState);
    digitalWrite(greenPin, greenState);
    // Check if the requested URL matches "/"
   // if (strcmp(URL, "/") == 0) {
        // Use WiServer’s print and println functions to write out the page content
        WiServer.print("<html>");
        WiServer.print("Controle de Luzes no BlackWidow<br><br>");
        printLightStatus("red", redState);
        printLightStatus("white", whiteState);
        printLightStatus("green", greenState);
        WiServer.print("Voce requisitou a pagina: ");
        WiServer.print(URL);
        WiServer.print("<br>Blackwidow online por: ");
        WiServer.print(millis());
        WiServer.print(" milissegundos<br>");
        WiServer.print("</html>");
        // URL was recognized
        return true;
    //}
    // URL not found
    return false;
}

void printLightStatus( String lightName, int lightState) {
  WiServer.print(" A luz ");
  WiServer.print(lightName);
  WiServer.print(" esta ");
        if(lightState ==0) {
            WiServer.print(" <b>desligada</b> <a href=/");
            WiServer.print(lightName);
            WiServer.print(">Ligar</a><br>");
        } else {
          WiServer.print(" <b>ligada</b> <a href=/");
            WiServer.print(lightName);
            WiServer.print(">Desligar</a><br>");
        }
}

void setup() {
  // Initialize WiServer and have it use the sendMyPage function to serve pages
  WiServer.init(sendMyPage);
  // Enable Serial output and ask WiServer to generate log messages (optional)
  Serial.begin(57600);
  WiServer.enableVerboseMode(true);
  pinMode(redPin, OUTPUT);
  pinMode(whitePin, OUTPUT);
  pinMode(greenPin, OUTPUT);
}

void loop(){

  // Run WiServer
  WiServer.server_task();
  delay(10);
}

obviamente mascarei minha chave wep, ehheh... nem era mais a mesma, mas troquei por segurança

Wagner..  cara achei que estava sozinho com esta frustração.
Muito obrigado por me ajudar.  Vou tentar com virtual folders mesmo.

Mas fica uma dúvida para quem é expert em programação em C de microcontroladores.
Como funciona ests função?  Como ela interage com o include WiServer.h que contêm esta declaração : typedef boolean (*pageServingFunction)(char* URL);


Acho que entendendo isto, é possível fazer o que você já quis fazer, e o que eu estou tentando.  Talvez seja preciso alterar a declaração que está no include.


Essa é a declaração de um "ponteiro" para uma função, desse jeito a classe permite que você crie uma função que será executada pela classe em determinado momento.

Quando você faz a inicialização da classe, você usa a função "init"
 WiServer.init(sendMyPage);
Nessa função init, você está indicando que a função pageServingFunction aponta para a função sendMyPage.

Obrigado pela explicação marcelo.

Aproveitando..  é possível fazer alguma alteração na função ou na declaração do ponteiro, de forma que eu nõ tenha mais estes problemas?  Ou é como vc falou na sua 1a resposta... um problema de consumo de memoria.  Se for a memória o que vc sugere? Troco o microcontrolador? Por qual?

Muito obrigado mesmo!

Eu achei sei lá aonde um exemplo e aqui rodou legal no modo parametro.. uso um Leonardo com Shield com Wiznet:


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

// Ethernet configuration
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; // MAC Address
byte ip[] = { 192,168,0, 2 }; // IP Address
Server server(80); // Server Port 80

// RCSwitch configuration
RCSwitch mySwitch = RCSwitch();
int RCTransmissionPin = 7;

// More to do...
// You should also modify the processCommand() and
// httpResponseHome() functions to fit your needs.

/**
* Setup
*/
void setup() {
Ethernet.begin(mac, ip);
server.begin();
mySwitch.enableTransmit( RCTransmissionPin );
}

/**
* Loop
*/
void loop() {
char* command = httpServer();
}

/**
* Command dispatcher
*/
void processCommand(char* command) {
if (strcmp(command, "1-on") == 0) {
mySwitch.switchOn(1,1);
} else if (strcmp(command, "1-off") == 0) {
mySwitch.switchOff(1,1);
} else if (strcmp(command, "2-on") == 0) {
mySwitch.switchOn(1,2);
} else if (strcmp(command, "2-off") == 0) {
mySwitch.switchOff(1,2);
}
}

/**
* HTTP Response with homepage
*/
void httpResponseHome(Client c) {
c.println("HTTP/1.1 200 OK");
c.println("Content-Type: text/html");
c.println();
c.println("<html>");
c.println("<head>");
c.println( "<title>RCSwitch Webserver Demo</title>");
c.println( "<style>");
c.println( "body { font-family: Arial, sans-serif; font-size:12px; }");
c.println( "</style>");
c.println("</head>");
c.println("<body>");
c.println( "<h1>RCSwitch Webserver Demo</h1>");
c.println( "<ul>");
c.println( "<li><a href=\"./?1-on\">Switch #1 on</a></li>");
c.println( "<li><a href=\"./?1-off\">Switch #1 off</a></li>");
c.println( "</ul>");
c.println( "<ul>");
c.println( "<li><a href=\"./?2-on\">Switch #2 on</a></li>");
c.println( "<li><a href=\"./?2-off\">Switch #2 off</a></li>");
c.println( "</ul>");
c.println( "<hr>");
c.println( "<a href=\"http://code.google.com/p/rc-switch/\">http://code.google.com/p/rc-switch/</a>;");
c.println("</body>");
c.println("</html>");
}

/**
* HTTP Redirect to homepage
*/
void httpResponseRedirect(Client c) {
c.println("HTTP/1.1 301 Found");
c.println("Location: /");
c.println();
}

/**
* HTTP Response 414 error
* Command must not be longer than 30 characters
**/
void httpResponse414(Client c) {
c.println("HTTP/1.1 414 Request URI too long");
c.println("Content-Type: text/plain");
c.println();
c.println("414 Request URI too long");
}

/**
* Process HTTP requests, parse first request header line and
* call processCommand with GET query string (everything after
* the ? question mark in the URL).
*/
char* httpServer() {
Client client = server.available();
if (client) {
char sReturnCommand[32];
int nCommandPos=-1;
sReturnCommand[0] = '\0';
while (client.connected()) {
if (client.available()) {
char c = client.read();
if ((c == '\n') || (c == ' ' && nCommandPos>-1)) {
sReturnCommand[nCommandPos] = '\0';
if (strcmp(sReturnCommand, "\0") == 0) {
httpResponseHome(client);
} else {
processCommand(sReturnCommand);
httpResponseRedirect(client);
}
break;
}
if (nCommandPos>-1) {
sReturnCommand[nCommandPos++] = c;
}
if (c == '?' && nCommandPos == -1) {
nCommandPos = 0;
}
}
if (nCommandPos > 30) {
httpResponse414(client);
sReturnCommand[0] = '\0';
break;
}
}
if (nCommandPos!=-1) {
sReturnCommand[nCommandPos] = '\0';
}
// give the web browser time to receive the data
delay(1);
client.stop();

return sReturnCommand;
}
return '\0';
}

Eduardo!!

Diminui a querystring para menos de 30 caracteres e funcionou sem problemas!!

É isso!  Muito obrigado Edu!!  valeu mesmo!!  Quando eu terminar meu projeto mostrarei para vocês!

Agora porque só aceita até 30??

RSS

© 2024   Criado por Marcelo Rodrigues.   Ativado por

Badges  |  Relatar um incidente  |  Termos de serviço