Saltar a contenido

Ejemplo 1: LED y Button Push

Vamos probar los LEDs y los botón pulsador, vamos hacer un ejemplo de funcionamiento.

1. Pines

ESP32-S3 Descripciónn
LED 1
LED 2
LED 3
LED 4
BottonPush 1
BottonPush 2
BottonPush 3
BottonPush 4

2. Codigo

#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <SPI.h>
#include <Adafruit_GFX.h>
#include <Adafruit_ST7789.h>
#include <driver/i2s_std.h>

#include <AudioFileSourceHTTPStream.h>
#include <AudioFileSourceBuffer.h>
#include <AudioGeneratorMP3.h>
#include <AudioOutputI2S.h>

/* ============================================================
 *  PINES  (tal cual los tienes en tus tres archivos)
 * ============================================================ */

// ---- INMP441 -> I2S_NUM_1 ----
#define I2S_WS      41
#define I2S_SD      40
#define I2S_SCK     42
#define MIC_PORT    I2S_NUM_1

// ---- Pantalla ST7789 -> SPI ----
#define TFT_SCLK    12    // SCL
#define TFT_MOSI    11    // SDA
#define TFT_RST     10    // RES
#define TFT_DC       9    // DC
#define TFT_CS       8    // CS

// ---- MAX98357A -> I2S_NUM_0 ----
#define I2S_DOUT    17
#define I2S_BCLK    15
#define I2S_LRC     16
#define I2S_PORT    I2S_NUM_0

// ---- Boton (unico pin nuevo: libre en tu montaje) ----
//  Conectar entre GPIO 4 y GND. Sin resistencia externa.
#define PIN_BOTON    4

/* ============================================================
 *  CONFIGURACION
 * ============================================================ */

const char* WIFI_SSID = "iPhone de Agile";
const char* WIFI_PASS = "12345678";
const char* WIT_TOKEN = "EMK25LNMMWG4XMJO7F4A35HYB7OYUMEA";  // Server Access Token

#define TFT_ANCHO           240
#define TFT_ALTO            240   // cambia a 320 si tu panel es 240x320

#define SEGUNDOS_GRABACION    3   // cuanto graba al presionar
#define SEGUNDOS_MOSTRAR      3   // cuanto se muestra el texto
#define GANANCIA_MIC         11   // sube a 12-14 si satura, baja a 9-10 si suena bajo
#define VOLUMEN_PARLANTE    0.7   // 0.0 a 1.0
#define IDIOMA_TTS         "es"

/* ============================================================
 *  INTERNO
 * ============================================================ */

#define TASA_MUESTREO   16000
#define BYTES_TOTALES   (TASA_MUESTREO * 2 * SEGUNDOS_GRABACION)
#define TAM_BLOQUE      512

SPIClass spiTFT(FSPI);
Adafruit_ST7789 tft = Adafruit_ST7789(&spiTFT, TFT_CS, TFT_DC, TFT_RST);

i2s_chan_handle_t rxMic = NULL;

AudioGeneratorMP3         *mp3    = nullptr;
AudioFileSourceHTTPStream *fuente = nullptr;
AudioFileSourceBuffer     *buffer = nullptr;
AudioOutputI2S            *salida = nullptr;

// ------------------------------------------------------------
//  PANTALLA
// ------------------------------------------------------------
void pantallaInicio() {
  tft.fillScreen(ST77XX_BLACK);
  tft.setTextWrap(true);
  tft.setTextColor(ST77XX_WHITE);
  tft.setTextSize(3);
  tft.setCursor(10, 60);
  tft.println("PRESIONE");
  tft.setCursor(10, 95);
  tft.println("BOTON PARA");
  tft.setCursor(10, 130);
  tft.println("HABLAR");
}

void mostrar(const String& titulo, uint16_t colorTitulo,
             const String& cuerpo = "", int tamCuerpo = 2) {
  tft.fillScreen(ST77XX_BLACK);
  tft.setTextWrap(true);

  tft.setTextColor(colorTitulo);
  tft.setTextSize(2);
  tft.setCursor(8, 12);
  tft.println(titulo);

  if (cuerpo.length() > 0) {
    tft.drawFastHLine(0, 40, TFT_ANCHO, ST77XX_WHITE);
    tft.setTextColor(ST77XX_WHITE);
    tft.setTextSize(tamCuerpo);
    tft.setCursor(8, 55);
    tft.println(cuerpo);
  }
}

// ------------------------------------------------------------
//  MICROFONO INMP441 -> I2S_NUM_1
// ------------------------------------------------------------
//  IMPORTANTE: se usa el driver I2S NUEVO (i2s_std.h).
//  El driver antiguo (driver/i2s.h) provoca el error
//  "CONFLICT! The new i2s driver can't work along with the
//  legacy i2s driver" porque ESP8266Audio ya usa el nuevo.
void iniciarMicrofono() {
  i2s_chan_config_t chan_cfg = I2S_CHANNEL_DEFAULT_CONFIG(MIC_PORT, I2S_ROLE_MASTER);
  chan_cfg.dma_desc_num  = 8;
  chan_cfg.dma_frame_num = 256;
  chan_cfg.auto_clear    = false;

  ESP_ERROR_CHECK(i2s_new_channel(&chan_cfg, NULL, &rxMic));   // solo RX

  i2s_std_config_t std_cfg = {
    .clk_cfg  = I2S_STD_CLK_DEFAULT_CONFIG(TASA_MUESTREO),
    .slot_cfg = I2S_STD_PHILIPS_SLOT_DEFAULT_CONFIG(
                  I2S_DATA_BIT_WIDTH_32BIT, I2S_SLOT_MODE_MONO),
    .gpio_cfg = {
      .mclk = I2S_GPIO_UNUSED,
      .bclk = (gpio_num_t)I2S_SCK,
      .ws   = (gpio_num_t)I2S_WS,
      .dout = I2S_GPIO_UNUSED,
      .din  = (gpio_num_t)I2S_SD,
      .invert_flags = { .mclk_inv = false, .bclk_inv = false, .ws_inv = false },
    },
  };

  // El INMP441 con L/R a GND habla por el canal izquierdo
  std_cfg.slot_cfg.slot_mask = I2S_STD_SLOT_LEFT;

  ESP_ERROR_CHECK(i2s_channel_init_std_mode(rxMic, &std_cfg));
  ESP_ERROR_CHECK(i2s_channel_enable(rxMic));
}

// ------------------------------------------------------------
//  GRABAR Y ENVIAR A WIT.AI
//  Se transmite mientras se graba (no se guarda todo en RAM).
// ------------------------------------------------------------
String escuchar() {
  WiFiClientSecure cliente;
  cliente.setInsecure();
  cliente.setTimeout(15000);

  if (!cliente.connect("api.wit.ai", 443)) return "";

  cliente.println("POST /speech?v=20230215 HTTP/1.1");
  cliente.println("Host: api.wit.ai");
  cliente.print("Authorization: Bearer ");
  cliente.println(WIT_TOKEN);
  cliente.println("Content-Type: audio/raw;encoding=signed-integer;bits=16;rate=16000;endian=little");
  cliente.print("Content-Length: ");
  cliente.println(BYTES_TOTALES);
  cliente.println("Connection: close");
  cliente.println();

  int32_t crudo[TAM_BLOQUE];
  int16_t pcm[TAM_BLOQUE];
  size_t  enviados = 0;

  // Descartar el primer bloque: suele traer basura del arranque del DMA
  {
    size_t basura = 0;
    i2s_channel_read(rxMic, crudo, sizeof(crudo), &basura, 200 / portTICK_PERIOD_MS);
  }

  while (enviados < BYTES_TOTALES) {
    size_t leidos = 0;
    i2s_channel_read(rxMic, crudo, sizeof(crudo), &leidos, portMAX_DELAY);
    int n = leidos / sizeof(int32_t);

    // El INMP441 entrega 32 bits: lo pasamos a 16 bits con ganancia
    for (int i = 0; i < n; i++) {
      int32_t v = crudo[i] >> GANANCIA_MIC;
      if (v >  32767) v =  32767;
      if (v < -32768) v = -32768;
      pcm[i] = (int16_t)v;
    }

    size_t bytes = n * sizeof(int16_t);
    if (enviados + bytes > BYTES_TOTALES) bytes = BYTES_TOTALES - enviados;

    cliente.write((uint8_t*)pcm, bytes);
    enviados += bytes;
  }

  String respuesta = "";
  unsigned long limite = millis() + 15000;
  while (cliente.connected() && millis() < limite) {
    while (cliente.available()) {
      respuesta += (char)cliente.read();
      limite = millis() + 3000;
    }
    delay(10);
  }
  cliente.stop();

  // Wit devuelve varios JSON parciales: tomamos el ultimo "text"
  String texto = "";
  int pos = respuesta.lastIndexOf("\"text\"");
  if (pos >= 0) {
    int ini = respuesta.indexOf('"', respuesta.indexOf(':', pos)) + 1;
    int fin = ini;
    while (fin < (int)respuesta.length()) {
      if (respuesta[fin] == '\\') { fin += 2; continue; }
      if (respuesta[fin] == '"') break;
      fin++;
    }
    if (ini > 0 && fin > ini) texto = respuesta.substring(ini, fin);
  }
  return texto;
}

// ------------------------------------------------------------
//  TEXTO A VOZ -> MAX98357A en I2S_NUM_0
// ------------------------------------------------------------
String urlEncode(const String& s) {
  String out = "";
  const char* hex = "0123456789ABCDEF";
  for (unsigned int i = 0; i < s.length(); i++) {
    char c = s[i];
    if (isalnum((unsigned char)c)) out += c;
    else if (c == ' ') out += '+';
    else {
      out += '%';
      out += hex[(c >> 4) & 0xF];
      out += hex[c & 0xF];
    }
  }
  return out;
}

void hablar(const String& texto) {
  String url = "http://translate.google.com/translate_tts?ie=UTF-8&client=tw-ob&tl=";
  url += IDIOMA_TTS;
  url += "&q=" + urlEncode(texto);

  salida = new AudioOutputI2S(0, AudioOutputI2S::EXTERNAL_I2S);  // I2S_NUM_0
  salida->SetPinout(I2S_BCLK, I2S_LRC, I2S_DOUT);
  salida->SetGain(VOLUMEN_PARLANTE);

  fuente = new AudioFileSourceHTTPStream(url.c_str());
  buffer = new AudioFileSourceBuffer(fuente, 4096);
  mp3    = new AudioGeneratorMP3();
  mp3->begin(buffer, salida);

  while (mp3->isRunning()) {
    if (!mp3->loop()) mp3->stop();
  }

  delete mp3;    mp3    = nullptr;
  delete buffer; buffer = nullptr;
  delete fuente; fuente = nullptr;
  delete salida; salida = nullptr;
}

// ------------------------------------------------------------
//  SETUP
// ------------------------------------------------------------
void setup() {
  Serial.begin(115200);

  pinMode(PIN_BOTON, INPUT_PULLUP);

  spiTFT.begin(TFT_SCLK, -1, TFT_MOSI, TFT_CS);
  tft.init(TFT_ANCHO, TFT_ALTO);
  tft.setSPISpeed(40000000);
  tft.setRotation(0);           // 0-3 segun como tengas montada la pantalla
  tft.fillScreen(ST77XX_BLACK);

  mostrar("Conectando WiFi", ST77XX_YELLOW);
  WiFi.mode(WIFI_STA);
  WiFi.begin(WIFI_SSID, WIFI_PASS);
  while (WiFi.status() != WL_CONNECTED) {
    delay(400);
    Serial.print(".");
  }
  Serial.println("\nWiFi OK: " + WiFi.localIP().toString());

  iniciarMicrofono();
  pantallaInicio();
}

// ------------------------------------------------------------
//  LOOP
// ------------------------------------------------------------
void loop() {
  if (digitalRead(PIN_BOTON) == LOW) {
    delay(50);                                          // antirrebote
    if (digitalRead(PIN_BOTON) != LOW) return;
    while (digitalRead(PIN_BOTON) == LOW) delay(10);    // esperar que suelte

    mostrar("Escuchando...", ST77XX_GREEN, "Hable ahora", 2);
    String texto = escuchar();
    Serial.println("Reconocido: " + texto);

    if (texto.length() == 0) {
      mostrar("No se entendio", ST77XX_RED, "Intente de nuevo", 2);
      delay(2000);
      pantallaInicio();
      return;
    }

    mostrar("Usted dijo:", ST77XX_CYAN, texto, 2);
    delay(SEGUNDOS_MOSTRAR * 1000);

    mostrar("Reproduciendo", ST77XX_MAGENTA, texto, 2);
    hablar("Se dijo: " + texto);

    pantallaInicio();
  }
  delay(20);
}