ESP-WROOM-32 - Introdução

Gurigraphics - Aug 3 - - Dev Community

1. Introdução


ESP32-WROOM-32 é um pequeno e poderoso módulo de hardware baseado no ESP32 desenvolvido pela empresa Espressif Systems. Possui WiFi, Bluetooth e diversos recursos opensource: IDEs, SDKs, bibliotecas, firmwares. É um kit de desenvolvimento que pode ser utilizado em uma ampla variedade de aplicações, desde redes de sensores de baixa potência até tarefas mais exigentes, como reconhecimento de voz, streaming de audio, decodificação de MP3, servidores web, emuladores de video games, etc

Baixo consumo

Uma bateria 18650 3200mAh/3.7v em um projeto com consumo médio de 80mA, a estimativa de duração seria: 3200/80 = 40 horas

Especificações

  • Processador: Xtensa 32-Bit LX6 Dual Core
  • Clock: 80 à 240 MHz (Ajustável)
  • Memória ROM: 448KB
  • Memória SRAM: 520Kb
  • Memória Flash Externa: 32-Bit de acesso e 4Mb
  • Tensão de Alimentação: 2,7 à 3,6 VDC
  • Tensão de nível lógico: 3,3VDC (não tolera 5V)
  • Corrente de consumo: 80mA (típica)
  • Corrente de consumo: 500mA (máxima)
  • Interfaces: Cartão SD, UART(3 canais), SPI (3 canais), SDIO, I2C (2 canais), I2S (2 canais), IR, PWM LED (2 canais) e PWM motor (3 canais)
  • Tipos GPIO: Digital IO (36), ADC 12-Bits (16 canais), DAC 8-Bits (2 canais), Sensor Capacitivo (10 canais); LNA pré-amplificador; WiFi 802.11 b/g/n: 2.4 à 2.5 GHz
  • Segurança WiFi: WPA / WPA2 / WPA2-Enterprise / WPS
  • Criptografia WiFi: AES / RSA / ECC / SHA
  • Bluetooth: 4.2 BR / EDR e BLE ( Bluetooth Low Energy)
  • RTC: Integrado de 8Kb (Slown / Fast)
  • Sensor integrado: Temperatura e Hall
  • Temperatura de trabalho: -40° à +85° C
  • Dimensões: 25,5 x 18,0 x 3,1 mm

Datasheet

https://www.espressif.com/sites/default/files/documentation/esp32-wroom-32_datasheet_en.pdf

Drivers Windows: CP210x Universal Windows Driver

https://www.silabs.com/developers/usb-to-uart-bridge-vcp-drivers?tab=downloads


2. Instalação


  1. Abra o Gerenciador de dispositivos
  2. Clique com o botão direito do mouse no dispositivo para atualizar o driver
    Gerenciador de dispositivos
    Caso não apareça nenhuma porta o problema pode ser o cabo. Alguns cabos USB funcionam apenas para carga e não para comunicação serial

  3. Clique em selecionar drivers no meu computador
    Selecionar pasta

  4. Selecione a pasta dos drivers
    Selecioanar drivers


3. Blink Hello World com Arduino IDE


  1. Faça o download e instale a Arduino IDE: https://www.arduino.cc/en/software

  2. Clique em "Files" e "Preferences"
    Arduino IDE

  3. Cole o link e clique em "Ok":
    https://dl.espressif.com/dl/package_esp32_index.json
    Arduino IDE

  4. Clique em "Tools". Em "Boards" selecione Esp32 > Esp32 Dev Module
    Arduino IDE

  5. Clique em "Tools". E selecione a porta serial em "Port"
    Arduino IDE

  6. Crie um novo projeto

  7. Código

int LED_BUILTIN = 2;

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  digitalWrite(LED_BUILTIN, HIGH);
  delay(1000);

  digitalWrite(LED_BUILTIN, LOW);
  delay(1000);
}
Enter fullscreen mode Exit fullscreen mode

Clique em upload para compilar e enviar
Arduino IDE

O Led azul do módulo deverá ficar piscando no intervalo de 1 segundo


4. Led Hello World com Arduino IDE


  1. Conecte o pino 19 do módulo no lado A de um resistor de 1k
  2. Conecte o lado B do resistor no pólo positivo do Led (a perna maior)
  3. Conecte o lado negativo do Led no pino GND

ESP32 Simulador wokwi

  1. Código
int LED_BUILTIN = 19;

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  digitalWrite(LED_BUILTIN, HIGH);
  delay(1000);

  digitalWrite(LED_BUILTIN, LOW);
  delay(1000);
}
Enter fullscreen mode Exit fullscreen mode

Clique em upload para compilar e enviar
O Led deverá ficar piscando no intervalo de 1 segundo

Teste este exemplo em um simulador online
https://wokwi.com/projects/405174739980527617


5. Webserver com Arduino IDE


  1. Conecte o pino 19 do módulo no lado A de um resistor de 1k
  2. Conecte o lado B do resistor no pólo positivo do Led (a perna maior)
  3. Conecte o lado negativo do Led no pino GND
  4. No pino 18 faça o mesmo com outro Led
  5. Edite no código o seu "WIFI_NAME" e "WIFI_PASSWORD"
#include <WiFi.h>

char ssid[] = "WIFI_NAME";
char pass[] = "WIFI_PASSWORD";

// Set web server port number to 80
WiFiServer server(80);

// Variable to store the HTTP request
String header;

// Auxiliar variables to store the current output state
String output26State = "off";
String output27State = "off";

// Assign output variables to GPIO pins
const int output26 = 18;
const int output27 = 19;

// Current time
unsigned long currentTime = millis();
// Previous time
unsigned long previousTime = 0; 
// Define timeout time in milliseconds (example: 2000ms = 2s)
const long timeoutTime = 2000;

void setup() {
  Serial.begin(115200);
  // Initialize the output variables as outputs
  pinMode(output26, OUTPUT);
  pinMode(output27, OUTPUT);
  // Set outputs to LOW
  digitalWrite(output26, LOW);
  digitalWrite(output27, LOW);

  // Connect to Wi-Fi network with SSID and password
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, pass);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  // Print local IP address and start web server
  Serial.println("");
  Serial.println("WiFi connected.");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  server.begin();
}

void send(WiFiClient client) {

  // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
  // and a content-type so the client knows what's coming, then a blank line:
  client.println("HTTP/1.1 200 OK");
  client.println("Content-type:text/html");
  client.println("Connection: close");
  client.println();

  // turns the GPIOs on and off
  if (header.indexOf("GET /26/on") >= 0) {
    Serial.println("GPIO 26 on");
    output26State = "on";
    digitalWrite(output26, HIGH);
  } else if (header.indexOf("GET /26/off") >= 0) {
    Serial.println("GPIO 26 off");
    output26State = "off";
    digitalWrite(output26, LOW);
  } else if (header.indexOf("GET /27/on") >= 0) {
    Serial.println("GPIO 27 on");
    output27State = "on";
    digitalWrite(output27, HIGH);
  } else if (header.indexOf("GET /27/off") >= 0) {
    Serial.println("GPIO 27 off");
    output27State = "off";
    digitalWrite(output27, LOW);
  }

  // Display the HTML web page
  client.println("<!DOCTYPE html><html lang='pt-br'>");
  client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
  client.println("<link rel=\"icon\" href=\"data:,\">");
  // CSS to style the on/off buttons 
  // Feel free to change the background-color and font-size attributes to fit your preferences
  client.println("<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}");
  client.println(".button { background-color: #4CAF50; border: none; color: white; padding: 16px 40px;");
  client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}");
  client.println(".button2 {background-color: #555555;}</style></head>");

  // Web Page Heading
  client.println("<body><h1>ESP32 Web Server</h1>");

  // Display current state, and ON/OFF buttons for GPIO 26  
  client.println("<p>GPIO 26 - State " + output26State + "</p>");
  // If the output26State is off, it displays the ON button       
  if (output26State=="off") {
    client.println("<p><a href=\"/26/on\"><button class=\"button\">ON</button></a></p>");
  } else {
    client.println("<p><a href=\"/26/off\"><button class=\"button button2\">OFF</button></a></p>");
  } 

  // Display current state, and ON/OFF buttons for GPIO 27  
  client.println("<p>GPIO 27 - State " + output27State + "</p>");
  // If the output27State is off, it displays the ON button       
  if (output27State=="off") {
    client.println("<p><a href=\"/27/on\"><button class=\"button\">ON</button></a></p>");
  } else {
    client.println("<p><a href=\"/27/off\"><button class=\"button button2\">OFF</button></a></p>");
  }
  client.println("</body></html>");

  // The HTTP response ends with another blank line
  client.println();
}

void loop(){
  WiFiClient client = server.available();   // Listen for incoming clients

  if (client) {                             // If a new client connects,
    currentTime = millis();
    previousTime = currentTime;
    Serial.println("New Client.");          // print a message out in the serial port
    String currentLine = "";                // make a String to hold incoming data from the client
    while (client.connected() && currentTime - previousTime <= timeoutTime) {  // loop while the client's connected
      currentTime = millis();
      if (client.available()) {             // if there's bytes to read from the client,
        char c = client.read();             // read a byte, then
        Serial.write(c);                    // print it out the serial monitor
        header += c;
        if (c == '\n') {                    // if the byte is a newline character
          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          if (currentLine.length() == 0) {

            send(client);

            // Break out of the while loop
            break;
          } else { // if you got a newline, then clear currentLine
            currentLine = "";
          }
        } else if (c != '\r') {  // if you got anything else but a carriage return character,
          currentLine += c;      // add it to the end of the currentLine
        }
      }
    }
    // Clear the header variable
    header = "";
    // Close the connection
    client.stop();
    Serial.println("Client disconnected.");
    Serial.println("");
  }
}
Enter fullscreen mode Exit fullscreen mode
  1. Clique em "Upload" para compilar e enviar
  2. Clique no botão "Serial Monitor" Serial Monitor
  3. Selecione a opção: 115200 baud
    Baud

  4. Pressione o botão do módulo que fica do lado esquerdo da entrada USB

  5. Verifique a mensagem serial enviada no console

01:16:47.973 -> Connecting to WIFI_NAME
01:16:48.599 -> .....
01:16:50.596 -> WiFi connected.
01:16:50.596 -> IP address: 
01:16:50.596 -> 192.168.1.12
Enter fullscreen mode Exit fullscreen mode
  1. Visite este endereço de IP no navegador do computador ou celular para controlar remotamente os Leds. Para acessar este IP você precisa estar conectado na mesma rede

Webserver

Referências:

https://randomnerdtutorials.com/esp32-web-server-arduino-ide/
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . .
Terabox Video Player