carlosvolt
Published © LGPL

Beeper with telegram bot and esp32

In this tutorial, you will learn how to configure and use an ESP32 device to receive Telegram messages and display them on an SH1106 display

IntermediateProtip90
Beeper with telegram bot and esp32

Story

Read more

Code

Source code

C/C++
Source code
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#include <U8g2lib.h>
// Configuración del display SH1106 usando U8g2
U8G2_SH1106_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ 22, /* data=*/ 21);
// Configuración WiFi
const char* ssid = "Tu-red-WiFi";
const char* contrasena = "Tu-Clave-WiFi";
// Token del bot de Telegram
#define TOKEN_BOT "Tu-Token-Telegram"
// Configuración del buzzer
const int pinBuzzer = 12;
const int duracionBuzzer = 100;  // Duración del sonido en milisegundos
// Configuración del botón
const int pinBoton = 23;
bool botonPresionado = false;
WiFiClientSecure cliente;
UniversalTelegramBot bot(TOKEN_BOT, cliente);
unsigned long ultimaVezBotCorrio;
// ID del último chat para enviar respuestas
String idUltimoChat;
void setup() {
  Serial.begin(115200);
  // Conexión WiFi
  WiFi.begin(ssid, contrasena);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Conectando al WiFi...");
  }
  Serial.println("Conectado al WiFi");  
  // Configuración del display
  u8g2.begin();  
  // Mostrar mensaje inicial en el display
  u8g2.clearBuffer();
  u8g2.setFont(u8g2_font_unifont_t_symbols);
  u8g2.drawUTF8(0, 10, "Esp. mensaje:");
  u8g2.sendBuffer();  
  // Configuración del buzzer
  pinMode(pinBuzzer, OUTPUT);
  digitalWrite(pinBuzzer, LOW);
  // Configuración del botón
  pinMode(pinBoton, INPUT_PULLUP);
  // Configuración de cliente seguro
  cliente.setCACert(TELEGRAM_CERTIFICATE_ROOT);
}
// Función para dividir el mensaje en líneas que se ajusten al ancho del display
void mostrarTextoLargo(const String &texto) {
  const int alturaLinea = 10;  // Altura de cada línea
  const int maxLineas = 6;     // Máximo número de líneas que caben en el display
  int indiceInicio = 0;
  int indiceFin;
  int linea = 0; 
  while (indiceInicio < texto.length()) {
    indiceFin = indiceInicio;
    int anchoLinea = 0;
    // Encuentra el punto de corte para la línea
    while (indiceFin < texto.length() && anchoLinea < u8g2.getDisplayWidth()) {
      indiceFin++;
      anchoLinea = u8g2.getStrWidth(texto.substring(indiceInicio, indiceFin).c_str());
    }
    // Ajusta el punto de corte para evitar dividir palabras
    if (indiceFin < texto.length()) {
      while (indiceFin > indiceInicio && texto[indiceFin] != ' ') {
        indiceFin--;
      }
    }
    // Muestra la línea en el display
    u8g2.drawUTF8(0, (linea + 1) * alturaLinea, texto.substring(indiceInicio, indiceFin).c_str());
    indiceInicio = indiceFin + 1;
    linea++;    
    // Si el texto es más largo que el display, desplaza el texto
    if (linea >= maxLineas) {
      delay(3000);  // Pausa para leer la página actual
      linea = 0;
      u8g2.clearBuffer();
    }
  }
  u8g2.sendBuffer();
}
void loop() {
  // Verificar si el botón ha sido presionado
  if (digitalRead(pinBoton) == LOW) {
    if (!botonPresionado) {
      // Envía un mensaje a Telegram
      bot.sendMessage(idUltimoChat, "He leído tu mensaje, puedes enviar otro", "");      
      // Sonar el buzzer
      digitalWrite(pinBuzzer, HIGH);
      delay(duracionBuzzer);
      digitalWrite(pinBuzzer, LOW);      
      // Mostrar mensaje en el display
      u8g2.clearBuffer();
      u8g2.setFont(u8g2_font_unifont_t_symbols);
      u8g2.drawUTF8(0, 10, "Mens. enviado!");
      u8g2.sendBuffer();
      botonPresionado = true;
    }
  } else {
    botonPresionado = false;
  }
  // Verificar si hay nuevos mensajes de Telegram
  if (millis() - ultimaVezBotCorrio > 1000) {
    int numNuevosMensajes = bot.getUpdates(bot.last_message_received + 1);
    while (numNuevosMensajes) {
      Serial.println("Nuevo mensaje recibido");
      for (int i = 0; i < numNuevosMensajes; i++) {
        String idChat = bot.messages[i].chat_id;
        String texto = bot.messages[i].text;        
        // Guardar el ID del último chat para enviar respuestas
        idUltimoChat = idChat;        
        // Mostrar mensaje en el display
        u8g2.clearBuffer();
        u8g2.setFont(u8g2_font_unifont_t_symbols); // Selecciona la fuente compatible con Unicode
        mostrarTextoLargo(texto);        
        // Sonar el buzzer
        digitalWrite(pinBuzzer, HIGH);
        delay(duracionBuzzer);
        digitalWrite(pinBuzzer, LOW);        
        bot.sendMessage(idChat, "Mensaje recibido: " + texto, "");
      }
      numNuevosMensajes = bot.getUpdates(bot.last_message_received + 1);
    }
    ultimaVezBotCorrio = millis();
  }
}

Credits

carlosvolt
34 projects • 4 followers
Contact

Comments

Please log in or sign up to comment.