Introduction: IOT With Cellular Network With ESP32

About: Do you like technology? Follow my channel on Youtube and my Blog. In them I put videos every week of microcontrollers, arduinos, networks, among other subjects.

Today we’ll discuss about the GPRS modem, or rather, the ESP32 and its use with the cellular telephone network. This is something that works very well. Using the MQTT protocol, we will then send data to the Ubidots dashboard. Use in this assembly a display for feedback of the circuit, in addition to the SIM800L and a cell phone chip. With this project, therefore, we will send temperature and humidity data through GPRS and MQTT, and visualize the data in a line chart.

Step 1: Demonstration

Step 2: Assembly

Step 3: Assembly - Table

Step 4: Ubidots

Step 5: SimpleDHT Library

In the Arduino IDE, go to Sketch-> Include Library-> Manage Libraries ...

Install SimpleDHT

Step 6: PubSubClient Library

In the Arduino IDE, go to Sketch-> Include Library-> Manage Libraries ...

Install PubSubClient

Step 7: TinyGSM Library

In the Arduino IDE, go to Sketch-> Include Library-> Manage Libraries ...

Install TinyGSM

Step 8: TFT_eSPI Library

In the Arduino IDE, go to Sketch-> Include Library-> Manage Libraries ...

Install TFT_eSPI

Step 9: TFT_eSPI Library

Change the display pins in the lib folder.

The pinning is in the User_Setup.h file in

C: \ Users \ \ Documents \ Arduino \ libraries \ TFT_eSPI

Change these defaults to the following values in the image.

Step 10: Ubidots

Log in to Ubidots with your account and click on Devices

Click the "+" button in the upper right corner

Click Blank

Enter the device name. Note the "device label," as this will be used in the "topic" that we will use in .ino

In the list of devices, the device you just created will appear. Click on it.

On the screen that appears, click on "Add Variable." A popup will appear. Click on "Raw."

Click the text box, and enter the name of the property.

It has to be exactly what we will send in the json of the .ino. Repeat this for the other property.

Go back to the dashboard by clicking on the Ubidots logo.

In the dashboard, click on "Add new Widget"

In the list of Widgets, choose "Double axis"

Step 11: Changing the Data in .ino

Step 12: GPRS_ESP32_DHT.ino - Declarations and Variables

#define TINY_GSM_MODEM_SIM800 //Tipo de modem que estamos usando
#include <TinyGsmClient.h> #include <PubSubClient.h> #include <SimpleDHT.h> #include <TFT_sSPI.h> #include <SPI.h> //Token de usuário que pegamos no Ubidots #define TOKEN "BBFF-abcdefghijklmnopqrstuvwxyz0123" //Tópico onde vamos postar os dados de temperatura e umidade (esp32_gprs é o nome do dispositivo no Ubidots) #define TOPIC "/v1.6/devices/esp32_gprs" //id do dispositivo que pegamos no painel do Ubidots #define DEVICE_ID "5c01234567890abc12345678" //URL do MQTT Server #define MQTT_SERVER "mqtt://things.ubidots.com" //Porta padrão do MQTT #define MQTT_PORT 1883 //Pino onde está o DHT22 #define DHT_PIN 27

Step 13: Pinning

//Pinagem em User_Setup.h na pasta da biblioteca
TFT_eSPI display = TFT_eSPI(); //Intervalo entre os envios e refresh da tela #define INTERVAL 10000 //Canal serial que vamos usar para comunicarmos com o modem. Utilize sempre 1 HardwareSerial SerialGSM(1); TinyGsm modemGSM(SerialGSM); TinyGsmClient gsmClient(modemGSM); //Cliente MQTT, passamos a url do server, a porta //e o cliente GSM PubSubClient client(MQTT_SERVER, MQTT_PORT, gsmClient); //Tempo em que o último envio/refresh foi feito uint32_t lastTime = 0; float humidity; //Variável onde iremos armazenar o valor da umidade float temperature; //Variável onde iremos armazenar o valor da temperatura SimpleDHT22 dht; //Objeto que realizará a leitura da umidade e temperatura

Step 14: Setup

void setup()
{ Serial.begin(115200); setupDisplay(); //Inicializa e configura o display setupGSM(); //Inicializa e configura o modem GSM connectMQTTServer(); //Conectamos ao mqtt server //Espera 2 segundos e limpamos o display delay(2000); display.fillScreen(TFT_BLUE); display.setCursor(0, 0); }

Step 15: SetupDisplay

void setupDisplay()
{ display.init(); display.setRotation(1); display.fillScreen(TFT_BLUE); //Limpa o display com a cor azul display.setTextColor(TFT_WHITE, TFT_BLUE); //Coloca o texto como branco com fundo azul display.setTextWrap(true, true);//Ativa quebra de linha display.setTextSize(1); display.setCursor(0, 0, 2); //Posicção x, y e fonte do texto display.println("Setup Display Complete"); }

Step 16: SetupGSM

void setupGSM()
{ display.println("Setup GSM..."); //Inicializamos a serial onde está o modem SerialGSM.begin(9600, SERIAL_8N1, 4, 2, false); delay(3000); //Mostra informação sobre o modem Serial.println(modemGSM.getModemInfo()); //Inicializa o modem if (!modemGSM.restart()) { display.println("Restarting GSM Modem failed"); delay(10000); ESP.restart(); return; } //Espera pela rede if (!modemGSM.waitForNetwork()) { display.println("Failed to connect to network"); delay(10000); ESP.restart(); return; } //Conecta à rede gprs (APN, usuário, senha) if (!modemGSM.gprsConnect("", "", "")) { display.println("GPRS Connection Failed"); delay(10000); ESP.restart(); return; } display.println("Setup GSM Success"); }

Step 17: ConnectMQTTServer

void connectMQTTServer() {
display.println("Connecting to MQTT Server..."); //Se conecta ao device que definimos if (client.connect(DEVICE_ID, TOKEN, "")) { //Se a conexão foi bem sucedida display.println("Connected"); } else { //Se ocorreu algum erro display.print("error = "); display.println(client.state()); delay(10000); ESP.restart(); } }

Step 18: Loop

void loop()
{ //Faz a leitura da umidade e temperatura readDHT(); //Se desconectou do server MQTT if(!client.connected()) { //Mandamos conectar connectMQTTServer(); } //Tempo decorrido desde o boot em milissegundos unsigned long now = millis(); //Se passou o intervalo de envio if(now - lastTime > INTERVAL) { //Publicamos para o server mqtt publishMQTT(); //Mostramos os dados no display showDataOnDisplay(); //Atualizamos o tempo em que foi feito o último envio lastTime = now; } }

Step 19: ReadDHT

void readDHT()
{ float t, h; //Faz a leitura da umidade e temperatura e apenas atualiza as variáveis se foi bem sucedido if (dht.read2(DHT_PIN, &t, &h, NULL) == SimpleDHTErrSuccess) { temperature = t; humidity = h; } }

Step 20: PublishMQTT

void publishMQTT()
{ //Cria o json que iremos enviar para o server MQTT String msg = createJsonString(); Serial.print("Publish message: "); Serial.println(msg); //Publicamos no tópico int status = client.publish(TOPIC, msg.c_str()); Serial.println("Status: " + String(status));//Status 1 se sucesso ou 0 se deu erro }

Step 21: CreateJsonString

String createJsonString()
{ String data = "{"; if(!isnan(humidity) && !isnan(temperature)) { data+="\"humidity\":"; data+=String(humidity, 2); data+=","; data+="\"temperature\":"; data+=String(temperature, 2); } data+="}"; return data; }

Step 22: ShowDataOnDisplay

void showDataOnDisplay()
{ //Reseta a posição do cursor e mostra umidade e temperatura lidas display.setCursor(0, 0, 2); display.println("Humidity: " + String(humidity, 2)); display.println("Temperature: " + String(temperature, 2)); }

Step 23: Files

Download the files

INO

PDF