Ir ao conteúdo
  • Cadastre-se

ESP8266 - A Pequena Maravilha para Comunicação WIFI


aphawk

Posts recomendados

Se isso ainda assim nao funcionar voce pode fazer uma gambiarra, fazer o arduino ler o IR e postar n serial. Da serial o nodemcu iria pegar o resultado e postar no site.... Eu ja fiz isso e deu certo. So ajustar a velocidade do arduino para 115200 e voi-la,não precisa usar nenhum resistor, vai diretão mesmo. Na programação do node voce usa a biblioteca software serial e define um pino para rx e outro para tx, senão da conflito. Ahe voce pode definir qualquer pino, não necessariamente o d0 e o d4

  • Curtir 1
Link para o comentário
Compartilhar em outros sites

Amigos, vai uma vez preciso da ajudinha de vocês! O código abaixo está funcionando certinho, gravando os dados na EEPROM e configurando o Wifi. Mas eu queria adaptá-lo para, se não conseguir conectar, ele iniciar em modo AP:

 

Segue o código!

 

/*
  //////////////////////////

  Comparação das saidas Digitais entre nodeMCU - Arduino

  NodeMCU – Arduino

  D0 = 16;
  D1 = 5;
  D2 = 4;
  D3 = 0;
  D4 = 2;
  D5 = 14;
  D6 = 12;
  D7 = 13;
  D8 = 15;
  D9 = 3;
  D10 = 1;

*/

#include <EEPROM.h>
#include <ESP8266WebServer.h>

///// DADOS EEPROM /////

// Locais dos itens da configuração
#define VERSION_START  500
#define CONFIG_START   6

// ID de Configuração - Toda vez que "alterar" o código, modificar esse valor!
#define CONFIG_VERSION "1d"

// Estrutura de configuração da EEPROM
struct ConfigStruct
{
  char ssid[50];
  char senha[50];
  IPAddress ip;
  IPAddress gateway;

} wifiConfig;

//Porta do WebServer
ESP8266WebServer server(80);

//////////////////////


///// DADOS RELE /////

//Relê
int rele = 2; //LED do nodeMCU

//Situação do Relê
boolean ligado1 = false;

//////////////////////

void saveConfig()
{
  for (unsigned int t = 0; t < sizeof(wifiConfig); t++) {
    EEPROM.write(CONFIG_START + t, *((char*)&wifiConfig + t));
  }
  // Salvando o ID da versão para puxar da EEPROM
  // da proxima vez que for carregar
  EEPROM.write(VERSION_START + 0, CONFIG_VERSION[0]);
  EEPROM.write(VERSION_START + 1, CONFIG_VERSION[1]);
  EEPROM.commit();
}

void loadConfig()
{
  if (EEPROM.read(VERSION_START + 0) == CONFIG_VERSION[0] &&
      EEPROM.read(VERSION_START + 1) == CONFIG_VERSION[1]) {
    // Carregando a estrutura main config
    for (unsigned int t = 0; t < sizeof(wifiConfig); t++)
      *((char*)&wifiConfig + t) = EEPROM.read(CONFIG_START + t);
  }
  else {
    // Configuração inicial do nodeMCU
    String ssid = "TP-LINK_F10B92";
    String senha = "********";
    ssid.toCharArray(wifiConfig.ssid, 50);
    senha.toCharArray(wifiConfig.senha, 50);
    wifiConfig.ip = IPAddress(192, 168, 10, 100);
    wifiConfig.gateway = IPAddress(192, 168, 10, 1);
    saveConfig();
  }
}

//Página principal
void handleRoot()
{
  ligado1 = false;
  // HTML da pagina principal
  String html = "<html><head><title>On Home</title>";
  html += "<meta http-equiv='Content-Type' content='charset=utf-8'>";
  html += "<meta name='viewport' content='width=device-width, initial-scale=1, user-scalable=no'>";
  html += "<meta name='apple-mobile-web-app-status-bar-style' content='black'>";
  html += "<meta name='apple-mobile-web-app-capable' content='yes' />";
  html += "<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css'>";
  html += "<link rel='icon' href='http://www.blocodochapolin.com.br/arduino/img/icone.png' type='image/x-icon' />";
  html += "<link rel='apple-touch-icon-precomposed' href='http://www.blocodochapolin.com.br/arduino/img/icone.png'>";
  html += "<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>";
  html += "<script src='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js'></script>";
  html += "</head>";
  html += "<style>.navbar-header { width:100%;  height:50px; } .navbar-brand{ width:100%; }</style>";
  html += "<body>";
  html += "<nav class='navbar navbar-inverse text-center' role='navigation'><div class='navbar-header'><div class='navbar-brand'>On House</div></div></nav>";
  html += "<div class='container' align='center'>";
  html += "<hr>";
  html += "<div class='panel panel-default'>";
  html += "<div class='panel-heading text-center'><b>Sala</b></div>";
  html += "<div class='panel-body'>";
  html += "<div class='btn-group btn-group-justified'>";
  html += "<a href='/rele1?estado=on' class='btn btn-success'>Ligar</a>";
  html += "<a href='/rele1?estado=off' class='btn btn-danger'>Desligar</a>";
  html += "</div>";
  html += "</div>";
  html += "</div>"; html += "<div id='estado1' style='display:none'>";
  html += (ligado1);
  html += "</div>";
  html += "</div></div>";
  //Script JS para não abrir uma nova página Bootstrap
  html += "<script language='JavaScript' type='text/javascript'>";
  html += "var a=document.getElementsByTagName('a');";
  html += "for(var i=0;i<a.length;i++)";
  html += "{";
  html += "a[i].onclick=function()";
  html += "{";
  html += "window.location=this.getAttribute('href');";
  html += "return false";
  html += "}";
  html += "}";
  html += "</script>";
  //Fim da instrução
  html += "</body></html>";
  // Enviando HTML para o servidor
  server.send(200, "text/html", html);
}

void rele1() {
  String state = server.arg("estado");
  if (state == "on") {
    digitalWrite(rele, HIGH);
    ligado1 = true;
  }
  else if (state == "off") {
    digitalWrite(rele, LOW);
    ligado1 = false;
  }

  // HTML da pagina "rele1"
  String html = "<html><head><title>On Home</title>";
  html += "<meta http-equiv='Content-Type' content='charset=utf-8'>";
  html += "<meta name='viewport' content='width=device-width, initial-scale=1, user-scalable=no'>";
  html += "<meta name='apple-mobile-web-app-status-bar-style' content='black'>";
  html += "<meta name='apple-mobile-web-app-capable' content='yes' />";
  html += "<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css'>";
  html += "<link rel='icon' href='http://www.blocodochapolin.com.br/arduino/img/icone.png' type='image/x-icon' />";
  html += "<link rel='apple-touch-icon-precomposed' href='http://www.blocodochapolin.com.br/arduino/img/icone.png'>";
  html += "<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>";
  html += "<script src='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js'></script>";
  html += "</head>";
  html += "<style>.navbar-header { width:100%;  height:50px; } .navbar-brand{ width:100%; }</style>";
  html += "<body>";
  html += "<nav class='navbar navbar-inverse text-center' role='navigation'><div class='navbar-header'><div class='navbar-brand'>On House</div></div></nav>";
  html += "<div class='container' align='center'>";
  html += "<hr>";
  html += "<div class='panel panel-default'>";
  html += "<div class='panel-heading text-center'><b>Sala</b></div>";
  html += "<div class='panel-body'>";
  html += "<div class='btn-group btn-group-justified'>";
  html += "<a href='/rele1?estado=on' class='btn btn-success'>Ligar</a>";
  html += "<a href='/rele1?estado=off' class='btn btn-danger'>Desligar</a>";
  html += "</div>";
  html += "</div>";
  html += "</div>";
  html += "<div id='estado1' style='display:none'>";
  html += (ligado1);
  html += "</div>";
  html += "</div></div>";
  //Script JS para não abrir uma nova página Bootstrap
  html += "<script language='JavaScript' type='text/javascript'>";
  html += "var a=document.getElementsByTagName('a');";
  html += "for(var i=0;i<a.length;i++)";
  html += "{";
  html += "a[i].onclick=function()";
  html += "{";
  html += "window.location=this.getAttribute('href');";
  html += "return false";
  html += "}";
  html += "}";
  html += "</script>";
  //Fim da instrução
  html += "</body></html>";
  // Enviando HTML para o servidor
  server.send(200, "text/html", html);
}

void configWifi()
{
  String html = "<html><head><title>Configurar WiFi</title>";
  html += "<style>body { background-color: #cccccc; font-family: Arial, Helvetica, Sans-Serif; Color: #000088; }</style>";
  html += "</head><body>";
  html += "<h1>Exemplo 3 - Configurar WiFi</h1>";
  html += "<form method=POST>";
  html += "<p>SSID: <input name=txtSSID type=text value=\"";
  html += wifiConfig.ssid;
  html += "\" /></p>";
  html += "<p>Senha: <input name=txtSenha type=text value=\"";
  html += wifiConfig.senha;
  html += "\" /></p>";
  html += "<p>IP: <input name=txtIP type=text value=\"";
  html += wifiConfig.ip[0];
  html += ".";
  html += wifiConfig.ip[1];
  html += ".";
  html += wifiConfig.ip[2];
  html += ".";
  html += wifiConfig.ip[3];
  html += "\" /></p>";
  html += "<p>Gateway: <input name=txtGateway type=text value=\"";
  html += wifiConfig.gateway[0];
  html += ".";
  html += wifiConfig.gateway[1];
  html += ".";
  html += wifiConfig.gateway[2];
  html += ".";
  html += wifiConfig.gateway[3];
  html += "\" /></p>";
  html += "<p><input name=button1 type=submit value=Enviar /></p></form>";
  html += "</body></html>";

  server.send(200, "text/html", html);
}

void configWifiSubmit()
{
  String html = "<html><head><title>Configurar WiFi Submit</title>";
  html += "<style>body { background-color: #cccccc; font-family: Arial, Helvetica, Sans-Serif; Color: #000088; }</style>";
  html += "</head><body>";
  html += "<h1>Exemplo 3 - Configurar WiFi</h1>";
  html += "<p>Dados gravados com sucesso!</p>";

  String ssid = server.arg("txtSSID");
  String senha = server.arg("txtSenha");
  String ip = server.arg("txtIP");
  String gateway = server.arg("txtGateway");
  ssid.toCharArray(wifiConfig.ssid, 50);
  senha.toCharArray(wifiConfig.senha, 50);
  wifiConfig.ip.fromString(ip);
  wifiConfig.gateway.fromString(gateway);

  html += "<p>SSID: <b>";
  html += wifiConfig.ssid;
  html += "</b></p>";
  html += "<p>Senha: <b>";
  html += wifiConfig.senha;
  html += "</b></p>";
  html += "<p>IP: <b>";
  html += ip;
  html += "</b></p>";
  html += "<p>Gateway: <b>";
  html += gateway;
  html += "</b></p>";
  html += "<form method=GET>";
  html += "<p><input name=button2 type=submit value=Voltar /></p></form>";
  html += "</body></html>";

  server.send(200, "text/html", html);

  saveConfig();
  ESP.restart();
}

void setup()
{
  // Iniciando Serial
  Serial.begin(115200);

  // Iniciando EEPROM
  EEPROM.begin(512);

  // Carrega configuração da EEPROM
  // Se não existir, cria
  loadConfig();

  //Se for o LED do nodeMCU, é o inverso: LOW (ligado), HIGH (desligado)
  pinMode(rele, OUTPUT);
  digitalWrite(rele, LOW);

  // Iniciando WiFi - Definido em loadconfig!
  WiFi.begin(wifiConfig.ssid, wifiConfig.senha);
  IPAddress subnet(255, 255, 255, 0);
  WiFi.config(wifiConfig.ip, wifiConfig.gateway, subnet);

  //Define o modo Estação
  WiFi.mode(WIFI_STA);

  // Aguardando conectar na rede
  Serial.println("");
  Serial.print("Aguarde, conectando");
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.println('.');
  }

  // Mostrando IP
  Serial.println("Conectado com sucesso!");
  Serial.println("Servidor Iniciado!");
  Serial.print("Acesse o IP pelo seu browser: http://");
  Serial.print(WiFi.localIP());

  // Atribuindo urls para funções
  // Quando não especificado método, uma função trata todos
  server.on("/", handleRoot);

  // Chamada do método GET
  server.on("/rele1", HTTP_GET, rele1);
  server.on("/config", HTTP_GET, configWifi);
  server.on("/config", HTTP_POST, configWifiSubmit);

  // Iniciando servidor
  server.begin();

}

void loop()
{
  // No loop só precisa dessa função
  server.handleClient();
}

Quem puder ajudar, desde já agradeço! =)

Link para o comentário
Compartilhar em outros sites

@Papibakigrafo

 

 

bool testWifi(void) {
  int c = 0;
  Serial.println("Waiting for Wifi to connect");  
  while ( c < 20 ) {
    if (WiFi.status() == WL_CONNECTED) { return true; } 
    delay(500);
    Serial.print(WiFi.status());    
    c++;
  }
  return false;
} 

		
void setup(){	
	
	WiFi.mode(WIFI_STA);//station
	WiFi.config(ip, gateway, subnet);


  String esid="NomeDaRede";
  String epass = "SenhaDaRede";
  
  boolean AP=false;
  if ( esid.length() > 1 ) {
      WiFi.begin(esid.c_str(), epass.c_str());
      if (!testWifi()) {//se não conectou, inicializa como AP
        AP=true; 
      }
  }  
  
  
  if(AP){
    Serial.println("Conexao falhou, o sistema entrara em modo Access Point.");
    WiFi.mode(WIFI_AP);//Access Ponit
    WiFi.softAP("ESP_Wifi", "");//nome da rede e senha do AP
    IPAddress myIP = WiFi.softAPIP();
    Serial.println("AP IP address: ");
    Serial.println(myIP);
  }else{
    Serial.println("Web Server ativo em: http://");
    Serial.print(WiFi.localIP());
  }
}

 

Na função testWifi(), tem a configuração de quantas vezes você quer que ele tente conectar, no caso está em 20x:  while ( c < 20 ) {} 

Link para o comentário
Compartilhar em outros sites

@ViniciusKruz, consegui adaptar ao meu código! Obrigado!

 

Só um probleminha que encontrei: está demorando uma eternindade em abrir a página principal em modo AP. Nem sei o tempo exato, mas deixei mais de 2 minutos e não abriu a página.

 

EDIT: já descobri o porque: meu CSS e JS estão na internet =/

  • Curtir 1
Link para o comentário
Compartilhar em outros sites

Em 14/11/2016 às 21:20, ViniciusKruz disse:

Encontrei uma coisinha muito legal, pesquisando sobre o SPIFFS, se trata de uma biblioteca que faz upload dos nossos arquivos e imagens em uma pasta no computador diretamente na memória flash do ESP, abaixo tem o link explicando como instalar na IDE do Arduíno:

http://www.esp8266.com/viewtopic.php?f=32&t=10081

 

Depois de feito o processo de instalação acima, passa-se a ter acesso também ao FSWebServer, que além de mostrar os gráficos dos estados dos pinos do ESP, ainda tem uma página que gerencia os arquivos hospedados na flash. Instalei pra testar, vejam as imagens:

 

Tela de status dos GPIOS e tela de edição/upload e criação de novos arquivos (qualquer semelhança com o ESP8266Basic não é mera coincidência rsrsrs)

Instalei, coloquei o estilo.css na pasta data, onde est[a o meu .ino e j[a cliquei em Steck Data Upload. Só isso?

Como faço para "ler"o arquivo estilo.css?

Link para o comentário
Compartilhar em outros sites

Apareceu nada.

 

Not Found: /edit

 

----------------

Eu fiz o seguinte: instalei o arquivo .jar, abri a pasta onde est[a o meu código, e tinha a pasta data. Coloquei os arquivos de JS e CSS dentro da pasta. Depois, com meu código aberto, deu STECK UPLOAD.

 

Mudei os caminhos dos arquivos CSS e JS e dei UPLOAD no meu código.

  • Curtir 2
Link para o comentário
Compartilhar em outros sites

7 minutos atrás, ViniciusKruz disse:

Pode ser que ele não esteja conectando na sua rede, veja as configurações: nome e senha da rede

adicionado 0 minutos depois

const char* ssid = "wifi-ssid";
const char* password = "wifi-password";

Na primeira vez mudei e conectou, mas ficou reiniciando. Agora ta dando isso:

 

feznZKq.jpg

 

  • Curtir 1
Link para o comentário
Compartilhar em outros sites

@Papibakigrafo

 

Desabilita ou coloca false nesta linha do setup: DBG_OUTPUT_PORT.setDebugOutput(true);

 

Esses pontinhos aí é o sistema tentando se conectar, se não aparecer a mensagem com o endereço do esp pode ser que não tenha se conectado.

 

Você viu que o sistema listou seus arquivos na memória?

  • Curtir 1
Link para o comentário
Compartilhar em outros sites

Eu fiz o seguinte:

 

1) Fiz o download do ESP8266FS e coloquei dentro da pasta tools do arduino;

2) Abri o meu código, e depois cliquei em Sketch > Mostrar a página do sketch;

3) Cliquei em Tools > Esp8266 Sketch Data Upload... demorou uns 2 minutos.

4) Apareceu a pasta "data", então coloquei os arquivos la.

3) Cliquei em Tools > Esp8266 Sketch Data Upload mais uma vez.

 

Fiz algo errado?

 

 

Sim, eu vi que ele listou. O que faço agora?

  • Curtir 1
Link para o comentário
Compartilhar em outros sites

Você fez certo mas e o sketh FSBrouser?

 

/* 
  FSWebServer - Example WebServer with SPIFFS backend for esp8266
  Copyright (c) 2015 Hristo Gochkov. All rights reserved.
  This file is part of the ESP8266WebServer library for Arduino environment.
 
  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.
  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  Lesser General Public License for more details.
  You should have received a copy of the GNU Lesser General Public
  License along with this library; if not, write to the Free Software
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
  
  upload the contents of the data folder with MkSPIFFS Tool ("ESP8266 Sketch Data Upload" in Tools menu in Arduino IDE)
  or you can upload the contents of a folder if you CD in that folder and run the following command:
  for file in `ls -A1`; do curl -F "file=@$PWD/$file" esp8266fs.local/edit; done
  
  access the sample web page at http://esp8266fs.local
  edit the page by going to http://esp8266fs.local/edit
*/
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <FS.h>

#define DBG_OUTPUT_PORT Serial

const char* ssid = "wifi-ssid";
const char* password = "wifi-password";
const char* host = "esp8266fs";

ESP8266WebServer server(80);
//holds the current upload
File fsUploadFile;

//format bytes
String formatBytes(size_t bytes){
  if (bytes < 1024){
    return String(bytes)+"B";
  } else if(bytes < (1024 * 1024)){
    return String(bytes/1024.0)+"KB";
  } else if(bytes < (1024 * 1024 * 1024)){
    return String(bytes/1024.0/1024.0)+"MB";
  } else {
    return String(bytes/1024.0/1024.0/1024.0)+"GB";
  }
}

String getContentType(String filename){
  if(server.hasArg("download")) return "application/octet-stream";
  else if(filename.endsWith(".htm")) return "text/html";
  else if(filename.endsWith(".html")) return "text/html";
  else if(filename.endsWith(".css")) return "text/css";
  else if(filename.endsWith(".js")) return "application/javascript";
  else if(filename.endsWith(".png")) return "image/png";
  else if(filename.endsWith(".gif")) return "image/gif";
  else if(filename.endsWith(".jpg")) return "image/jpeg";
  else if(filename.endsWith(".ico")) return "image/x-icon";
  else if(filename.endsWith(".xml")) return "text/xml";
  else if(filename.endsWith(".pdf")) return "application/x-pdf";
  else if(filename.endsWith(".zip")) return "application/x-zip";
  else if(filename.endsWith(".gz")) return "application/x-gzip";
  return "text/plain";
}

bool handleFileRead(String path){
  DBG_OUTPUT_PORT.println("handleFileRead: " + path);
  if(path.endsWith("/")) path += "index.htm";
  String contentType = getContentType(path);
  String pathWithGz = path + ".gz";
  if(SPIFFS.exists(pathWithGz) || SPIFFS.exists(path)){
    if(SPIFFS.exists(pathWithGz))
      path += ".gz";
    File file = SPIFFS.open(path, "r");
    size_t sent = server.streamFile(file, contentType);
    file.close();
    return true;
  }
  return false;
}

void handleFileUpload(){
  if(server.uri() != "/edit") return;
  HTTPUpload& upload = server.upload();
  if(upload.status == UPLOAD_FILE_START){
    String filename = upload.filename;
    if(!filename.startsWith("/")) filename = "/"+filename;
    DBG_OUTPUT_PORT.print("handleFileUpload Name: "); DBG_OUTPUT_PORT.println(filename);
    fsUploadFile = SPIFFS.open(filename, "w");
    filename = String();
  } else if(upload.status == UPLOAD_FILE_WRITE){
    //DBG_OUTPUT_PORT.print("handleFileUpload Data: "); DBG_OUTPUT_PORT.println(upload.currentSize);
    if(fsUploadFile)
      fsUploadFile.write(upload.buf, upload.currentSize);
  } else if(upload.status == UPLOAD_FILE_END){
    if(fsUploadFile)
      fsUploadFile.close();
    DBG_OUTPUT_PORT.print("handleFileUpload Size: "); DBG_OUTPUT_PORT.println(upload.totalSize);
  }
}

void handleFileDelete(){
  if(server.args() == 0) return server.send(500, "text/plain", "BAD ARGS");
  String path = server.arg(0);
  DBG_OUTPUT_PORT.println("handleFileDelete: " + path);
  if(path == "/")
    return server.send(500, "text/plain", "BAD PATH");
  if(!SPIFFS.exists(path))
    return server.send(404, "text/plain", "FileNotFound");
  SPIFFS.remove(path);
  server.send(200, "text/plain", "");
  path = String();
}

void handleFileCreate(){
  if(server.args() == 0)
    return server.send(500, "text/plain", "BAD ARGS");
  String path = server.arg(0);
  DBG_OUTPUT_PORT.println("handleFileCreate: " + path);
  if(path == "/")
    return server.send(500, "text/plain", "BAD PATH");
  if(SPIFFS.exists(path))
    return server.send(500, "text/plain", "FILE EXISTS");
  File file = SPIFFS.open(path, "w");
  if(file)
    file.close();
  else
    return server.send(500, "text/plain", "CREATE FAILED");
  server.send(200, "text/plain", "");
  path = String();
}

void handleFileList() {
  if(!server.hasArg("dir")) {server.send(500, "text/plain", "BAD ARGS"); return;}
  
  String path = server.arg("dir");
  DBG_OUTPUT_PORT.println("handleFileList: " + path);
  Dir dir = SPIFFS.openDir(path);
  path = String();

  String output = "[";
  while(dir.next()){
    File entry = dir.openFile("r");
    if (output != "[") output += ',';
    bool isDir = false;
    output += "{\"type\":\"";
    output += (isDir)?"dir":"file";
    output += "\",\"name\":\"";
    output += String(entry.name()).substring(1);
    output += "\"}";
    entry.close();
  }
  
  output += "]";
  server.send(200, "text/json", output);
}

void setup(void){
  DBG_OUTPUT_PORT.begin(115200);
  DBG_OUTPUT_PORT.print("\n");
  DBG_OUTPUT_PORT.setDebugOutput(true);
  SPIFFS.begin();
  {
    Dir dir = SPIFFS.openDir("/");
    while (dir.next()) {    
      String fileName = dir.fileName();
      size_t fileSize = dir.fileSize();
      DBG_OUTPUT_PORT.printf("FS File: %s, size: %s\n", fileName.c_str(), formatBytes(fileSize).c_str());
    }
    DBG_OUTPUT_PORT.printf("\n");
  }
  

  //WIFI INIT
  DBG_OUTPUT_PORT.printf("Connecting to %s\n", ssid);
  if (String(WiFi.SSID()) != String(ssid)) {
    WiFi.begin(ssid, password);
  }
  
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    DBG_OUTPUT_PORT.print(".");
  }
  DBG_OUTPUT_PORT.println("");
  DBG_OUTPUT_PORT.print("Connected! IP address: ");
  DBG_OUTPUT_PORT.println(WiFi.localIP());

  MDNS.begin(host);
  DBG_OUTPUT_PORT.print("Open http://");
  DBG_OUTPUT_PORT.print(host);
  DBG_OUTPUT_PORT.println(".local/edit to see the file browser");
  
  
  //SERVER INIT
  //list directory
  server.on("/list", HTTP_GET, handleFileList);
  //load editor
  server.on("/edit", HTTP_GET, [](){
    if(!handleFileRead("/edit.htm")) server.send(404, "text/plain", "FileNotFound");
  });
  //create file
  server.on("/edit", HTTP_PUT, handleFileCreate);
  //delete file
  server.on("/edit", HTTP_DELETE, handleFileDelete);
  //first callback is called after the request has ended with all parsed arguments
  //second callback handles file uploads at that location
  server.on("/edit", HTTP_POST, [](){ server.send(200, "text/plain", ""); }, handleFileUpload);

  //called when the url is not defined here
  //use it to load content from SPIFFS
  server.onNotFound([](){
    if(!handleFileRead(server.uri()))
      server.send(404, "text/plain", "FileNotFound");
  });

  //get heap status, analog input value and all GPIO statuses in one json call
  server.on("/all", HTTP_GET, [](){
    String json = "{";
    json += "\"heap\":"+String(ESP.getFreeHeap());
    json += ", \"analog\":"+String(analogRead(A0));
    json += ", \"gpio\":"+String((uint32_t)(((GPI | GPO) & 0xFFFF) | ((GP16I & 0x01) << 16)));
    json += "}";
    server.send(200, "text/json", json);
    json = String();
  });
  server.begin();
  DBG_OUTPUT_PORT.println("HTTP server started");

}
 
void loop(void){
  server.handleClient();
}

 

  • Curtir 2
Link para o comentário
Compartilhar em outros sites

@ViniciusKruz agora conecta, mas da esse erro:

 

scandone
state: 0 -> 2 (b0)
state: 2 -> 3 (0)

Connecting to TP-LINK_F10B92
state: 3 -> 5 (10)
add 0
aid 3
cnt 

connected with TP-LINK_F10B92, channel 1
dhcp client start...
chg_B1:-40
.....ip:192.168.10.53,mask:255.255.255.0,gw:192.168.10.1
.
Connected! IP address: 192.168.10.53
Open http://esp8266fs.local/edit to see the file browser
HTTP server started
handleFileRead: /edit.htm

UAHauHAUahAUa já to quase desistindo

 

Fiz o firmware do espbasic, e depois format firmware e upei o FSBrowser pra poder aparecer isso.

Link para o comentário
Compartilhar em outros sites

7 horas atrás, Papibakigrafo disse:

ip:192.168.10.53,mask:255.255.255.0,gw:192.168.10.1 . Connected! IP address: 192.168.10.53 Open http://esp8266fs.local/edit to see the file browser HTTP server started handleFileRead: /edit.htm

 

Uai, ta conectado, não tem erro aí não, olha as configurações:

Servidor inicializado: HTTP server started

IP: 192.168.10.53

Agora basta você entrar no seu navegador e digitar:   192.168.10.53/edit

 

 

Observação:

Estas informações abaixo não são erros, isso aí é porque aquela linha que te falei, está habilitada, isso é um debug habilitado pela serial.

 

7 horas atrás, Papibakigrafo disse:

scandone state: 0 -> 2 (b0) state: 2 -> 3 (0) Connecting to TP-LINK_F10B92 state: 3 -> 5 (10) add 0 aid 3 cnt

 

Link para o comentário
Compartilhar em outros sites

Visitante
Este tópico está impedido de receber novas respostas.

Sobre o Clube do Hardware

No ar desde 1996, o Clube do Hardware é uma das maiores, mais antigas e mais respeitadas comunidades sobre tecnologia do Brasil. Leia mais

Direitos autorais

Não permitimos a cópia ou reprodução do conteúdo do nosso site, fórum, newsletters e redes sociais, mesmo citando-se a fonte. Leia mais

×
×
  • Criar novo...