Embedded systems are everywhere: in vehicles, in household appliances, in climate monitoring systems in urban spaces, in agribusiness, and so on. However, one of the most important uses of embedded systems is with regard to security.
The reason for this is simple: as long as using sensors suitable for what you want to monitor and having the resources to work (energy, connectivity, etc.), the embedded systems are like guardians who work 24 hours a day, 7 days a week, and who they will rarely err in their role.
Thus, embedded systems are especially useful in critical security systems, such as monitoring and fire alarms, for example.
Therefore, in this article, you will learn how to make an embedded system that monitors flammable gases in the environment and, through Telegram, you will be warned when there are detectable flammable gases in the environment.
Thus, from anywhere in the world, you will be able to find out about any dangerous situation regarding flammable gases, something that can be very useful for remote monitoring and quick action in case of fire.
In detail, you will learn:
- How to Program ESP32 with Arduino IDE
- How to create a bot on Telegram to be used by your ESP32
- How to monitor flammable gases in the environment with the MQ-2 sensor
- How to make ESP32 use the created Telegram bot and send you flammable gas detection alerts via Telegram
What is Telegram?
Telegram is a Russian instant messaging application / service, currently the main competitor of WhatsApp, and having versions for Android, iOS, and the late (or almost) Windows Phone.
Its main differentials are being open-source (which concerns the application), allowing the creation of bots, secret chats with messages that self-destruct (with expiration date) and from the beginning a very light and efficient web interface for use on computers (something that, until a few years ago, did not exist on WhatsApp).
Developing the project “Monitoring of flammable gases with ESP32 and Telegram”The schematic circuit of the project can be seen in figure 1.
In terms of hardware, this project makes use of the following components:
- 01 x ESP32 (ESP32 Devkit 1)
- 01 x micro-USB cable
- 01 x MQ-2 sensor (monitoring of flammable gases and smoke)
- 02 x 3.6kΩ / 1 / 4W resistors
- Male-male jumpers
- 01x 800 point protoboards
- 01 x 5V / 2A switched DC power supply, for powering the project without the computer (optional)
In general terms, the project's schematic circuit has three main parts: ESP32 Devkit 1, voltage divider, and MQ-2 sensor (monitoring of flammable gases and smoke). See the details of these parts in detail below.
ESP32 Devkit 1 - OverviewThe ESP32 Devkit 1 consists of a complete development board, containing good processing and memories for an embedded device, wi-fi connectivity, Bluetooth connectivity (classic and BLE), a good number of GPIOs available for development and multiple communication interfaces (I²C, UART, SPI, etc.).
In addition, ESP32 has two processors, making it a dual-core solution for IoT projects. In general, it is a (great) evolution, in terms of computational resources and the number of communication interfaces, of the well-known NodeMCU (ESP8266).
In addition, it has a very inviting cost, being one of the best alternatives for prototypes and products that involve Internet of Things concepts and that require good processing capacity, memories, and connectivity.
Unfortunately, the ESP32 Devkit 1 does not have a perfect shape to fit protoboards, which requires less conventional maneuvers for use with protoboards, as shown in the schematic circuit of the project in figure 1, where only one side was connected to the protoboard.
Even so, the ESP32 Devkit 1 is a very interesting option for both professionals and hobbyists / makers who want to do compact projects at a very competitive cost.
Voltage divider circuitAs you can see in figure 1, there is a voltage divider between the digital signal (D0) of the MQ-2 sensor (flammable gases and smoke) and the ESP32.
This is necessary because the sensor works with a voltage of 5V, while the ESP32 Devkit 1 works with a maximum voltage of 3.3V. Therefore, it is necessary to adjust the voltage of the digital sensor output signal to the level allowed by ESP32 Devkit 1.
The voltage divider is available for this task. The voltage divider causes the voltage delivered to the ESP32 Devkit 1 to be half that provided by the sensor, sufficient for the ESP32 to differentiate between high and low logic levels within its working voltage limits. In this way, it is possible to use the sensor normally with the ESP32 Devkit 1.
MQ-2 sensor (flammable gases and smoke)The MQ-2 is a sensor capable of detecting flammable gases and smoke in the air, and the detected gases can be in concentrations in the range of 300 to 10, 000 ppm (parts per million).
This sensor is capable of detecting, in addition to smoke, the following flammable gases: LPG (Liquefied Petroleum Gas), methane, propane, butane, hydrogen, alcohol, natural gas, and other gases with flammable potential.
The MQ-2 is available for sale in the form of the standalone sensor and in the form of a module, which is the form we use in this article. The sensor in the form of a module can be seen in figure 2.
The MQ-2 module has 4 terminals, which are:
- VDC: supply (5V)
- GND: ground (0V)
- A0: analog output (0..5V)
- D0: digital output (0V or 5V)
In this project, we will make use of the digital output of the MQ-2 module. This output goes to a high level (5V) when flammable gases or smoke are detected in the air and, in the absence of these, it remains low (0V).
The amount/concentration of smoke and or flammable gases that causes the digital output to go high is regulated by a potentiometer, located behind the MQ-2 module. This potentiometer can be seen in figure 3.
In general terms, it is recommended that the pot is slightly above the minimum, to reduce the chances of false detection of smoke and/or flammable gases.
Programming ESP32 on the Arduino IDEESP32 Devkit 1 can be programmed in the Arduino IDE so that the development of projects with it is very similar to what is done with any common Arduino.
This facilitates both the development of new projects and the port/transfer of other projects made on other hardware/platforms to the ESP32 Devkit 1.
Instalação da biblioteca para usar o Telegram no ESP32
You must install the UniversalTelegramBot library, the library that allows you to use Telegram on ESP32.
This library can be installed simply and quickly via Arduino IDE, in the library manager (Sketch> Include Library> Manage Libraries).
Insert its name (UniversalTelegramBot) in the search field and install its latest version.
Creating a Telegram bot
ESP32 will alert you to flammable / smoke gases detected from Telegram, using a Telegram bot.
Therefore, a Telegram bot needs to be created. To create a Telegram bot, follow the procedure below:
- All bot management in Telegram is done through a botmaster, called Bot Father (@BotFather). The first step is to find him on Telegram and start a conversation with him.
- To start creating your Telegram bot, type the command/new bot in the chat with @BotFather.
- @BotFather will be asked to provide a name for your Telegram bot. Enter a name without spaces and special characters (for example: projeto_alerta_gas_bot).
- Then, if the name is approved by @BotFather (approval is required to ensure that there is no bot with the same name), you will be asked to provide a username for your bot. You can use the bot's own name for the username, this ending in bot.
- If the username is approved by @BotFather (approval is required to ensure that there is no bot with the same username), your bot will be created! You will receive a token (a unique key for your bot) and the address to "chat" with your bot. Keep this token in a safe place, it will be needed in the project's source code.
Next, I'll show you how you will get your Chat Id.
Obtaining the Chat Id of your Telegram account
The ChatId of your personal Telegram account is a unique code/key for your account so that it will allow the Telegram bot to send messages only to you (as if it were your contact on Telegram).
To obtain this ChatId, follow the procedure below:
- Look for the Chat ID Echo bot (@chatid_echo_bot). This bot is used to provide the ChatId of your personal Telegram account
- Send the message/command / to start to @chatid_echo_bot
- Then @chatid_echo_bot will return your ChatId. Keep this token in a safe place, it will be needed in the project's source code.
Next, I will present to you the complete project code.
Source code of the project
At this point, everything is ready to implement the project!
The source code of the project can be found below.
The way to program ESP32 Devkit 1 with this source code is very similar to programming any other common Arduino: copy and paste it into your Arduino IDE, change the contents of the ssid_wifi and password_wifi variables respectively with the name and password of the wi-fi network that ESP32 Devkit 1 should connect to, compile and upload/schedule ESP32 Devkit 1.
Also, don't forget to replace your Telegram bot's token (obtained with @BotFather) in BOT_TELEGRAM_TOKEN and replace the ChatId of your personal Telegram account (obtained with @chatid_echo_bot) in auth_id.
Read the source code comments carefully to fully understand it.
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
/* Definição do sensor de gás */
#define GPIO_SENSOR_GAS 34
/* Definição do token de seu Bot Telegram
(valor obtido no @BotFather) */
#define BOT_TELEGRAM_TOKEN " "
#define TEMPO_ESPERA_SENSOR 100 //ms
/* Wifi */
/* Coloque aqui o SSID (nome da rede wifi) que o
ESP32 deve se conectar
*/
char ssid_wifi[] = " ";
/* Coloque aqui o password (senha da rede wifi) que o
ESP32 deve se conectar
*/
char password_wifi[] = " ";
/* Variáveis e objetos para usar o wifi e Bot Telegram */
WiFiClientSecure client;
UniversalTelegramBot bot(BOT_TELEGRAM_TOKEN, client);
/* Coloque aqui o auth_id de sua conta telegram
(auth_id da conta que o bot deve alertar sobre o gás
*/
String auth_id = " ";
/* Protótipos */
void init_wifi(void);
void conecta_wifi(void);
void verifica_conexao_wifi(void);
void configura_gpio_sensor_gas(void);
/* Função: inicializa wi-fi
* Parametros: nenhum
* Retorno: nenhum
*/
void init_wifi(void)
{
WiFi.mode(WIFI_STA);
WiFi.disconnect();
delay(100);
Serial.println("------WI-FI -----");
Serial.print("Conectando-se a rede: ");
Serial.println(ssid_wifi);
Serial.println("Aguarde...");
conecta_wifi();
}
/* Função: conecta-se a rede wi-fi
* Parametros: nenhum
* Retorno: nenhum
*/
void conecta_wifi(void)
{
/* Se ja estiver conectado, nada é feito. */
if (WiFi.status() == WL_CONNECTED)
return;
/* refaz a conexão */
WiFi.begin(ssid_wifi, password_wifi);
while (WiFi.status() != WL_CONNECTED)
{
delay(100);
Serial.print(".");
}
Serial.println();
Serial.print("Conectado com sucesso a rede wi-fi ");
Serial.println(ssid_wifi);
Serial.print("IP: ");
Serial.println(WiFi.localIP());
}
/* Função: verifica se a conexao wi-fi está ativa
* (e, em caso negativo, refaz a conexao)
* Parametros: nenhum
* Retorno: nenhum
*/
void verifica_conexao_wifi(void)
{
conecta_wifi();
}
/* Função: configura GPIO para leitura do sensor de gás
* Parametros: nenhum
* Retorno: nenhum
*/
void configura_gpio_sensor_gas(void)
{
pinMode(GPIO_SENSOR_GAS, INPUT);
}
void setup()
{
Serial.begin(115200);
/* Configura GPIO para leitura do sensor de gás */
configura_gpio_sensor_gas();
/* Inicialização e conexao wifi */
init_wifi();
conecta_wifi();
}
void loop()
{
/* Verifica se conexão wifi está ok.
Caso não estiver, refaz a conexão. */
verifica_conexao_wifi();
/* Verifica se há detecção de gás */
if (digitalRead(GPIO_SENSOR_GAS) == HIGH)
{
/* Avisa, por Telegram, a detecção do gás */
bot.sendMessage(auth_id, "ALERTA: Gas detectado!", "");
Serial.println("Gas detectado! Avisando usuario pelo Telegram...");
/* Aguarda detecção de gás acabar
(para notificar via Telegram só uma vez) */
while(digitalRead(GPIO_SENSOR_GAS) == HIGH)
{
delay(1);
}
/* Espera alguns ms para evitar que, se ocorrer
oscilações da saída digital do sensor, sejam
erroneamente detectadas como alertas. */
delay(TEMPO_ESPERA_SENSOR);
}
}
Now, I'm going to introduce you to the complete functioning of this project.
The project works as follows: once connected and connected to wifi, it will already be operating as a Telegram bot.
When it detects flammable gases and/or smoke, it will send a message via Telegram directly to you, as shown in figure 4.
In this way, just connect the project in a location with access to the wifi network that it is programmed and ready!
Now, I'll offer the electronic project in a PCBGOGO Printed Circuit Board to construct this project.
Constructing a PCBGOGO Printed Circuit BoardFrom the electronic schematic, was developed a printed circuit board to construct a project in a kitchen. The Printed circuit board is presented below in the 3D view.
The project is simples and was developed with PCBGOGO and Robô Lúdico Brazil. Now, I'll offer the Electronic Schematic of the project in the figure below.
The electronic schematic was developed the layout design as is shown below.
After this, this the result in the 2D View.
After you solder the electronic components to the PCBGOGO printed circuit board, you can install your device in a case and install it next to your stove.
The system will monitor and send the alert information to your Telegram.
ConclusionI am grateful to PCBGOGO PCB Factory for offering the electronic boards for assembling the project.
In addition, I am grateful to the Playful Robot School of Brazil for making all the knowledge available to develop this project.
The files for the electronic board and source code are attached to this project.
Comments
Please log in or sign up to comment.