olá por favor, estou com dificuldades no esp8266, to tomando um baile dele , ele parece que tem vida própria !!! rsrs, brincadeira a parte então depois de muito tempo sem comunicação entre o arduino e o esp, consegui fazer eles conversarem, mais ele esta perdendo a comunicação entre o site que envia o comado e o Esp, se eu reiniciar o arduino ele volta a funcionar, alguém outro exemplo de enviar dados para o esp pela web ou o que posso fazer para solucionar isso
já aproveitando tentei usar o esp direto para ligar um rele, mais com quando eu coloco a carga ele perde a comunicação também, qual a diferença entre a porta gpio do esp e do arduino?
obrigado e abraços a todos !!!
#include <SoftwareSerial.h>
#define DEBUG true
//Cria o objeto para usar a biblioteca Sotfware Serial
//RX do arduino é o pino 2
//TX do arduino é o pino 3
//O TX do esp8266 deve ser ligado no pino 2 do arduino
//O RX do esp8266 deve ser ligado no pino 3 do arduino
SoftwareSerial esp8266(2,3);
//declara os pinos do led rgb
int red =11;
int green =12;
int blue =13;
void setup()
{
//um pequeno delay no arduino
//para evitar que envie comandos antes do esp8266 dar o start
delay(500);
//Seta ambas seriais para a velocidade de 9600
Serial.begin(9600);
//(em alguns casos a velocidade do seu esp8266 pode estar diferente desta)
esp8266.begin(9600);
//declara os pinos como saida
pinMode(red,OUTPUT);
digitalWrite(red,LOW);
pinMode(green,OUTPUT);
digitalWrite(green,LOW);
pinMode(blue,OUTPUT);
digitalWrite(blue,LOW);
delay(2000);
//liga o led azul para informar o inicio dos comandos AT
digitalWrite(blue,blue);
//Envia o comandos AT
// reseta o modulo
sendData("AT+RST\r\n",2000,DEBUG);
// configure as access point e estação (ambos)
sendData("AT+CWMODE=3\r\n",1000,DEBUG);
//conecta ao roteador com a senha
//(esta configuração deve ser feita, pois o seu roteador tem nome diferente do meu e senha)
sendData("AT+CWJAP=\"roteador\",\"123456\"r\n",10000,DEBUG);
//Retorna o IP ao qual está conectado e o IP de Station
sendData("AT+CIFSR\r\n",1000,DEBUG);
//Habilita multiplas conexões
sendData("AT+CIPMUX=1\r\n",1000,DEBUG);
//Habilita ao servidor a porta 80
sendData("AT+CIPSERVER=1,80\r\n",1000,DEBUG);
//desliga o led azul ao finalizar os comandos
digitalWrite(blue,LOW);
//liga o led verde para indicar que podera enviar os comandos
//via brownser
digitalWrite(green,HIGH);
delay(2000);
//desliga led verde
digitalWrite(green,LOW);
}
void loop()
{
//verifica se o esp8266 esta enviando mensagem e esta disponivel
if(esp8266.available())
{
if(esp8266.find("+IPD,"))
{
// delay(5000);
//recupera apenas comando ASCII
int connectionId = esp8266.read()-48;
//avança o cursor até a palavra "pin="
esp8266.find("pin=");
//armazena o primeiro numero.. Ex: Se for pino 13 armazenara 1 e logo em seguida multiplica por 10 para o calculo do pino
int pinNumber = (esp8266.read()-48)*10;
//armazena o segundo numero e soma com o primeiro... Ex : Se o numero for 13 a soma sera 10 + 3 que resultara no pino ao qual foi enviado pela pagina Web
pinNumber += (esp8266.read()-48);
//armazena o terceiro dado que correponde ao status do led '1' para ligado e '0' para desligado
int statusLed =(esp8266.read()-48);
//Escreve o satus com o metodo digital Write
//Ex se recebeu 121
//o pino 12 sera ligado
//digitalWrite(12, 1);
digitalWrite(pinNumber, statusLed);
///////////////////////////////////
//Inicia a montagem da pagina web
//////////////////////////////
// finaliza o comando no esp8266
String closeCommand = "AT+CIPCLOSE=";
closeCommand+=connectionId;
closeCommand+="\r\n";
//Encerra a conexao
sendData(closeCommand,1000,DEBUG);
}
}
}
//Metodo que envia os comandos para o esp8266
String sendData(String command, const int timeout, boolean debug)
{
//variavel de resposta do esp8266
String response = "";
// send a leitura dos caracteres para o esp8266
esp8266.println(command);
long int time = millis();
while( (time+timeout) > millis())
{
while(esp8266.available())
{
//Concatena caracter por caractere recebido do modulo esp8266
char c = esp8266.read();
response+=c;
}
}
//debug de resposta do esp8266
if(debug)
{
//Imprime o que o esp8266 enviou para o arduino
Serial.println("Arduino : " + response);
}
return response;
}
Tags:
Fábio, esse problema de cair conexão provavelmente é devido à firmware antigo.
Esse problema já foi relatado no Forum do Fabricante :
http://bbs.espressif.com/index.php?sid=7d362dcdee0fd43c6680f90adef6...
Qual versão do FW esta usando ?
digite esse comando, através da serial
AT+GMR
http://labdegaragem.com/forum/topics/conhecendo-o-esp8266?commentId...
Procedimento para atualizar o FW :
http://labdegaragem.com/forum/topics/conhecendo-o-esp8266?commentId...
Ola Jose, muito obrigado pela atenção,
estou usando a seguinte versão:
v0.9.2.2 AT Firmware
esse código fica um pouco mais estável mais perco a comunicação com facilidade,
outra coisa deste código, que consegui pegar a variável para carregar no navegador pelo pc, mais em smart e tablete ele ignora ----- > If(name)
uma outra coisa é fixar o ip também estou com dificuldades, mais acho que estou fazendo errado
agradeço muito pela sua ajuda !
também estou usando este código,
// Basic Arduino & ESP8266 webserver
//
// uses AltSoftSerial download from https://www.pjrc.com/teensy/td_libs_AltSoftSerial.html
// this can be replaced with the normal software serial
//
String IPLIVRE="192.168.0.20";
String MASCARA="255.255.255.0";
String ROTEADOR="192.168.0.1";
#include <AltSoftSerial.h>
// Arduino pin 8 for RX
// Arduino Pin 9 for TX
AltSoftSerial espSerial;
const bool printReply = true;
const char line[] = "-----\n\r";
int loopCount=0;
char html[50];
char command[20];
char reply[500]; // you wouldn't normally do this
char ipAddress [20];
char name[30];
int lenHtml = 0;
char temp[5];
int Rele1=11;
void setup()
{
Serial.begin(9600);
pinMode(11,OUTPUT);
digitalWrite(Rele1,LOW);
Serial.println("Start\r\n\r\n");
espSerial.begin(9600); // your ESP8266 module's baud rate might be different
// reset the ESP8266
Serial.println("reset the module");
espSerial.print("AT+RST\r\n");
getReply( 2000 );
// configure as a station
Serial.println("Change to station mode");
espSerial.print("AT+CWMODE=1\r\n");
getReply( 1500 );
// connect to the network. Uses DHCP. ip will be assigned by the router.
Serial.println("Connect to a network ");
// Enter the SSID and password for your own network
espSerial.print("AT+CWJAP=\"roteador\",\"123456\"\r\n");
getReply( 10000 );
// get ip address
Serial.println("Get the ip address assigned ny the router");
espSerial.print("AT+CIFSR\r\n");
getReply( 1000 );
// AT+CIPSTA_DEF="192.168.0.235","192.168.0.254","255.255.255.0"
// get ip address
Serial.println("Get the ip address assigned ny the router");
espSerial.print("AT+CIPSTA_DEF=\"192.168.0.199\",\"192.168.0.1\",\"255.255.255.0\"\r\n");
getReply( 1000 );
//cmdESP(cmdMudarIP,"Definindo nosso proprio IP fixo");
// get ip address
Serial.println("Get the ip address assigned ny the router");
espSerial.print("AT+CIFSR\r\n");
getReply( 1000 );
// parse ip address.
int len = strlen( reply );
bool done=false;
bool error = false;
int pos = 0;
while (!done)
{
if ( reply[pos] == 10) { done = true;}
pos++;
if (pos > len) { done = true; error = true;}
}
if (!error)
{
int buffpos = 0;
done = false;
while (!done)
{
if ( reply[pos] == 13 ) { done = true; }
else { ipAddress[buffpos] = reply[pos]; buffpos++; pos++; }
}
ipAddress[buffpos] = 0;
}
else { strcpy(ipAddress,"ERROR"); }
// configure for multiple connections
Serial.println("Set for multiple connections");
espSerial.print("AT+CIPMUX=1\r\n");
getReply( 1500 );
// start server on port 8
Serial.println("Start the server");
espSerial.print("AT+CIPSERVER=1,8888\r\n");
getReply( 1500 );
Serial.println("");
Serial.println("Waiting for page request");
Serial.print("Connect to "); Serial.println(ipAddress);
Serial.println("");
}
void loop()
{
if(espSerial.available()) // check if the ESO8266 is sending data
{
// this is the +IPD reply - it is quite long.
// normally you would not need to copy the whole message in to a variable you can copy up to "HOST" only
// or you can just search the data character by character as you read the serial port.
getReply( 2000 );
bool foundIPD = false;
for (int i=0; i<strlen(reply); i++)
{
if ( (reply[i]=='I') && (reply[i+1]=='P') && (reply[i+2]=='D') ) { foundIPD = true; }
}
if ( foundIPD )
{
loopCount++;
// Serial.print( "Have a request. Loop = "); Serial.println(loopCount); Serial.println("");
// check to see if we have a name - look for name=
bool haveName = false;
int nameStartPos = 0;
for (int i=0; i<strlen(reply); i++)
{
if (!haveName) // just get the first occurrence of name
{
if ( (reply[i]=='n') && (reply[i+1]=='a') && (reply[i+2]=='m') && (reply[i+3]=='e') && (reply[i+4]=='=') )
{
haveName = true;
nameStartPos = i+5;
}
}
}
int connectionId = espSerial.read()-48;
String ET = espSerial.find("name=w"))
//int LerEsp = (espSerial.read());
//if(name[0]=='w') {
// Serial.println("Rele Desligado");
// digitalWrite(Rele1, LOW);
//Matches.
//}
//int LerEsp = (espSerial.read()-48)*10;
//LerEsp += (espSerial.read()-48);
//int statusLed =(espSerial.read()-48);
Serial.print( "############");
Serial.println("");
// Serial.print( LerEsp);
Serial.print( "############");
Serial.println("");
// get the name - copy everything from nameStartPos to the first space character
if (haveName)
{
int tempPos = 0;
bool finishedCopying = false;
for (int i=nameStartPos; i<strlen(reply); i++)
{
if ( (reply[i]==' ') && !finishedCopying ) { finishedCopying = true; }
if ( !finishedCopying ) { name[tempPos] = reply[i]; tempPos++; }
}
name[tempPos] = 0;
}
if (haveName) { Serial.print( "name=");
Serial.println(name); Serial.println("");
}
else { Serial.println( "no name entered");
Serial.println(""); }
// start sending the HTML
strcpy(html,"<html><head></head><body>");
strcpy(command,"AT+CIPSEND=0,25\r\n");
espSerial.print(command);
getReply( 100 );
espSerial.print(html);
getReply( 100 );
//Serial.print( "############");
//Serial.println("");
//String Alvo (name); //it doesn't work
//converte o name para string
//Serial.print(Alvo);
//if(name[0]=='w') {
// Serial.println("Rele Desligado");
// digitalWrite(Rele1, LOW);
//Matches.
//}
//if(name[0]=='r') {
//Serial.println("Rele Desligado");
// digitalWrite(Rele1, HIGH);
//Matches.
//}
strcpy(html,"<p>Served by ESP8266</p>");
strcpy(command,"AT+CIPSEND=0,36\r\n");
espSerial.print(command);
getReply( 100 );
espSerial.print(html);
getReply( 100 );
strcpy(html,"<form action=\""); strcat(html, "\" method=\"GET\">"); strcat(command, "\r\n");
//strcpy(html,"<form action=\""); strcat(html, ipAddress); strcat(html, "\" method=\"GET\">"); strcat(command, "\r\n");
lenHtml = strlen( html );
itoa( lenHtml, temp, 10);
strcpy(command,"AT+CIPSEND=0,");
itoa( lenHtml, temp, 10);
strcat(command, temp);
strcat(command, "\r\n");
espSerial.print(command);
getReply( 100 );
espSerial.print(html);
getReply( 100 );
strcpy(html,"<p>Request number ");
itoa( loopCount, temp, 10);
strcat(html,temp);
strcat(html,"</p>");
// need the length of html
int lenHtml = strlen( html );
strcpy(command,"AT+CIPSEND=0,");
itoa( lenHtml, temp, 10);
strcat(command, temp);
strcat(command, "\r\n");
espSerial.print(command);
getReply( 100 );
espSerial.print(html);
getReply( 100 );
if (haveName)
{
// write name
strcpy(html,"<p>Your name is "); strcat(html, name ); strcat(html,"</p>");
// need the length of html for the cipsend command
lenHtml = strlen( html );
strcpy(command,"AT+CIPSEND=0,"); itoa( lenHtml, temp, 10); strcat(command, temp); strcat(command, "\r\n");
espSerial.print(command);
getReply( 100 );
espSerial.print(html);
getReply( 100 );
}
strcpy(html,"</form>");
strcpy(command,"AT+CIPSEND=0,43\r\n");
espSerial.print(command);
getReply( 100 );
espSerial.print(html);
getReply( 100 );
strcpy(html,"</body></html>");
strcpy(command,"AT+CIPSEND=0,14\r\n");
espSerial.print(command);
getReply( 100 );
espSerial.print(html);
getReply( 1000 );
// close the connection
espSerial.print( "AT+CIPCLOSE=0\r\n" );
getReply( 500 );
espSerial.print( "AT+CIPCLOSE=0\r\n" );
getReply( 500 );
Serial.println("last getReply 1 ");
getReply( 500 );
Serial.println("last getReply 2 ");
getReply( 500 );
} // if(espSerial.find("+IPD"))
} //if(espSerial.available())
delay (100);
// drop to here and wait for next request.
}
String vars;
int varOnOff=0;
void getReply(int wait)
{
int tempPos = 0;
long int time = millis();
while( (time + wait) > millis())
{
while(espSerial.available())
{
char c = espSerial.read();
vars.concat(c);
if (tempPos < 500) { reply[tempPos] = c; tempPos++; }
}
reply[tempPos] = 0;
}
if (printReply) { Serial.println( reply ); Serial.println(line); }
}
Esse firmware é antigo.
Recomendo que atualize-o.
ola tudo bem então eu tentei fazer upgrade conforme seu material acima, mais ele não comunica com arduino, voltei novamente a versão 0018000902 e ele volta a comunicar vc tem algum firme confiável para me passar?
obrigado
Não é possivel atualizar o firmware com o Arduino conectado.
É Preciso usar uma interface USB Serial conforme já informado no Tutorial.
olá bom dia, então o que quis dizer acima que atualizo pelo conversor normal,
só que após terminar e utilizar ele com arduino ou ate mesmo pelo conversor ele não responde os comandos AT
Se o módulo não responde aos comandos AT, provavelmente não conseguiu atualizar o FW.
Tem que funcionar os comandos AT, para poder atualizar o FW.
Verifique as tensões de alimentação, do Módulo ESP8266, certifique-se que as conexões estão corretas.
Tem que responder os comandos AT !
uma coisa importante é que quando coloco a carga do rele - uma lâmpada ele após acionar algumas vezes ele perde a comunicação
Como fez a ligação do Relé ? Foto e diagrama.
então ele é os reles prontos iguais a esse da foto:
http://s3.amazonaws.com/img.iluria.com/product/11AB2C/292F7A/850xN.jpg
o que estou usando é sem acoplador otico
Envie o link do produto, não consigo identifica-lo.
Onde ligou o VCC do modulo do Relé ?
Bem-vindo a
Laboratorio de Garagem (arduino, eletrônica, robotica, hacking)
© 2024 Criado por Marcelo Rodrigues. Ativado por