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.
Components and supplies
1
ESP32
Tools and machines
1
Arduino IDE
Apps and platforms
1
rogerbit.
Project description
Code
Source code
c
source code
1#include <WiFi.h> 2#include <WiFiClientSecure.h> 3#include <UniversalTelegramBot.h> 4#include <U8g2lib.h> 5// Configuración del display SH1106 usando U8g2 6U8G2_SH1106_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE, /* clock=*/ 22, /* data=*/ 21); 7// Configuración WiFi 8const char* ssid = "Tu-red-WiFi"; 9const char* contrasena = "Tu-Clave-WiFi"; 10// Token del bot de Telegram 11#define TOKEN_BOT "Tu-Token-Telegram" 12// Configuración del buzzer 13const int pinBuzzer = 12; 14const int duracionBuzzer = 100; // Duración del sonido en milisegundos 15// Configuración del botón 16const int pinBoton = 23; 17bool botonPresionado = false; 18WiFiClientSecure cliente; 19UniversalTelegramBot bot(TOKEN_BOT, cliente); 20unsigned long ultimaVezBotCorrio; 21// ID del último chat para enviar respuestas 22String idUltimoChat; 23void setup() { 24 Serial.begin(115200); 25 // Conexión WiFi 26 WiFi.begin(ssid, contrasena); 27 while (WiFi.status() != WL_CONNECTED) { 28 delay(1000); 29 Serial.println("Conectando al WiFi..."); 30 } 31 Serial.println("Conectado al WiFi"); 32 // Configuración del display 33 u8g2.begin(); 34 // Mostrar mensaje inicial en el display 35 u8g2.clearBuffer(); 36 u8g2.setFont(u8g2_font_unifont_t_symbols); 37 u8g2.drawUTF8(0, 10, "Esp. mensaje:"); 38 u8g2.sendBuffer(); 39 // Configuración del buzzer 40 pinMode(pinBuzzer, OUTPUT); 41 digitalWrite(pinBuzzer, LOW); 42 // Configuración del botón 43 pinMode(pinBoton, INPUT_PULLUP); 44 // Configuración de cliente seguro 45 cliente.setCACert(TELEGRAM_CERTIFICATE_ROOT); 46} 47// Función para dividir el mensaje en líneas que se ajusten al ancho del display 48void mostrarTextoLargo(const String &texto) { 49 const int alturaLinea = 10; // Altura de cada línea 50 const int maxLineas = 6; // Máximo número de líneas que caben en el display 51 int indiceInicio = 0; 52 int indiceFin; 53 int linea = 0; 54 while (indiceInicio < texto.length()) { 55 indiceFin = indiceInicio; 56 int anchoLinea = 0; 57 // Encuentra el punto de corte para la línea 58 while (indiceFin < texto.length() && anchoLinea < u8g2.getDisplayWidth()) { 59 indiceFin++; 60 anchoLinea = u8g2.getStrWidth(texto.substring(indiceInicio, indiceFin).c_str()); 61 } 62 // Ajusta el punto de corte para evitar dividir palabras 63 if (indiceFin < texto.length()) { 64 while (indiceFin > indiceInicio && texto[indiceFin] != ' ') { 65 indiceFin--; 66 } 67 } 68 // Muestra la línea en el display 69 u8g2.drawUTF8(0, (linea + 1) * alturaLinea, texto.substring(indiceInicio, indiceFin).c_str()); 70 indiceInicio = indiceFin + 1; 71 linea++; 72 // Si el texto es más largo que el display, desplaza el texto 73 if (linea >= maxLineas) { 74 delay(3000); // Pausa para leer la página actual 75 linea = 0; 76 u8g2.clearBuffer(); 77 } 78 } 79 u8g2.sendBuffer(); 80} 81void loop() { 82 // Verificar si el botón ha sido presionado 83 if (digitalRead(pinBoton) == LOW) { 84 if (!botonPresionado) { 85 // Envía un mensaje a Telegram 86 bot.sendMessage(idUltimoChat, "He leído tu mensaje, puedes enviar otro", ""); 87 // Sonar el buzzer 88 digitalWrite(pinBuzzer, HIGH); 89 delay(duracionBuzzer); 90 digitalWrite(pinBuzzer, LOW); 91 // Mostrar mensaje en el display 92 u8g2.clearBuffer(); 93 u8g2.setFont(u8g2_font_unifont_t_symbols); 94 u8g2.drawUTF8(0, 10, "Mens. enviado!"); 95 u8g2.sendBuffer(); 96 botonPresionado = true; 97 } 98 } else { 99 botonPresionado = false; 100 } 101 // Verificar si hay nuevos mensajes de Telegram 102 if (millis() - ultimaVezBotCorrio > 1000) { 103 int numNuevosMensajes = bot.getUpdates(bot.last_message_received + 1); 104 while (numNuevosMensajes) { 105 Serial.println("Nuevo mensaje recibido"); 106 for (int i = 0; i < numNuevosMensajes; i++) { 107 String idChat = bot.messages[i].chat_id; 108 String texto = bot.messages[i].text; 109 // Guardar el ID del último chat para enviar respuestas 110 idUltimoChat = idChat; 111 // Mostrar mensaje en el display 112 u8g2.clearBuffer(); 113 u8g2.setFont(u8g2_font_unifont_t_symbols); // Selecciona la fuente compatible con Unicode 114 mostrarTextoLargo(texto); 115 // Sonar el buzzer 116 digitalWrite(pinBuzzer, HIGH); 117 delay(duracionBuzzer); 118 digitalWrite(pinBuzzer, LOW); 119 bot.sendMessage(idChat, "Mensaje recibido: " + texto, ""); 120 } 121 numNuevosMensajes = bot.getUpdates(bot.last_message_received + 1); 122 } 123 ultimaVezBotCorrio = millis(); 124 } 125}
Comments
Only logged in users can leave comments