Download as pdf or txt
Download as pdf or txt
You are on page 1of 14

instructables

IOT With Cellular Network With ESP32

by Fernando Koyanagi

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

https://youtu.be/U_KYGe7ZyKM

Step 1: Demonstration

IOT With Cellular Network With ESP32: Page 1


Step 2: Assembly

Step 3: Assembly - Table

Step 4: Ubidots

IOT With Cellular Network With ESP32: Page 2


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

IOT With Cellular Network With ESP32: Page 3


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

IOT With Cellular Network With ESP32: Page 4


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.

IOT With Cellular Network With ESP32: Page 5


Step 10: Ubidots

Log in to Ubidots with your account and click on A popup will appear. Click on "Raw."
Devices
Click the text box, and enter the name of the property.
Click the "+" button in the upper right corner
It has to be exactly what we will send in the json of
Click Blank the .ino. Repeat this for the other property.

Enter the device name. Note the "device label," as Go back to the dashboard by clicking on the Ubidots
this will be used in the "topic" that we will use in .ino logo.

In the list of devices, the device you just created will In the dashboard, click on "Add new Widget"
appear. Click on it.
In the list of Widgets, choose "Double axis"
On the screen that appears, click on "Add Variable."

IOT With Cellular Network With ESP32: Page 6


IOT With Cellular Network With ESP32: Page 7
Step 11: Changing the Data in .ino

IOT With Cellular Network With ESP32: Page 8


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

IOT With Cellular Network With ESP32: Page 9


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);
}

IOT With Cellular Network With ESP32: Page 10


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");


}

IOT With Cellular Network With ESP32: Page 11


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;
}
}

IOT With Cellular Network With ESP32: Page 12


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;
}

IOT With Cellular Network With ESP32: Page 13


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

IOT With Cellular Network With ESP32: Page 14

You might also like