Tutorial Esp32

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 44

TUTORIAL ESP32

ESP32 Control Digital Outputs


First, you need set the GPIO you want to control as
an OUTPUT. Use the pinMode() function as follows:

pinMode(GPIO, OUTPUT);

To control a digital output you just need to use


the digitalWrite() function, that accepts as arguments,
the GPIO (int number) you are referring to, and the state,
either HIGH or LOW.

digitalWrite(GPIO, STATE);

All GPIOs can be used as outputs except GPIOs 6 to 11


(connected to the integrated SPI flash) and GPIOs 34, 35, 36
and 39 (input only GPIOs);

ESP32 Read Digital Inputs


First, set the GPIO you want to read as INPUT, using
the pinMode() function as follows:

pinMode(GPIO, INPUT);

To read a digital input, like a button, you use


the digitalRead() function, that accepts as argument, the
GPIO (int number) you are referring to.

digitalRead(GPIO);
All ESP32 GPIOs can be used as inputs, except GPIOs 6 to
11 (connected to the integrated SPI flash).

CIRCUIT CONNECTION.

SOURCE CODE.
// set pin numbers
const int buttonPin = 4; // the number of the pushbutton pin
const int ledPin = 5; // the number of the LED pin

// variable for storing the pushbutton status


int buttonState = 0;

void setup() {
Serial.begin(115200);
// initialize the pushbutton pin as an input
pinMode(buttonPin, INPUT);
// initialize the LED pin as an output
pinMode(ledPin, OUTPUT);
}
void loop() {
// read the state of the pushbutton value
buttonState = digitalRead(buttonPin);
Serial.println(buttonState);
// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH
if (buttonState == HIGH) {
// turn LED on
digitalWrite(ledPin, HIGH);
} else {
// turn LED off
digitalWrite(ledPin, LOW);
}
}

ESP32 LED PWM Controller


The ESP32 has a LED PWM controller with 16 independent
channels that can be configured to generate PWM signals
with different properties.

Here’s the steps you’ll have to follow to dim an LED with


PWM using the Arduino IDE:

1. First, you need to choose a PWM channel. There are 16


channels from 0 to 15.

2. Then, you need to set the PWM signal frequency. For an


LED, a frequency of 5000 Hz is fine to use.

3. You also need to set the signal’s duty cycle resolution:


you have resolutions from 1 to 16 bits. We’ll use 8-bit
resolution, which means you can control the LED brightness
using a value from 0 to 255.

4. Next, you need to specify to which GPIO or GPIOs the


signal will appear upon. For that you’ll use the following
function:

ledcAttachPin(GPIO, channel)
This function accepts two arguments. The first is the GPIO
that will output the signal, and the second is the channel
that will generate the signal.

5. Finally, to control the LED brightness using PWM, you use


the following function:

ledcWrite(channel, dutycycle)

This function accepts as arguments the channel that is


generating the PWM signal, and the duty cycle.

CIRCUIT CONNECTION.

SOURCE CODE.
#define POTENTIOMETER_PIN 36 // ESP32 pin GPIO36 (ADC0) connected to
Potentiometer pin
#define LED_PIN 21 // ESP32 pin GPIO21 connected to LED's pin

// the setup routine runs once when you press reset:


void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(115200);
// declare LED pin to be an output:
pinMode(LED_PIN, OUTPUT);
}
// the loop routine runs over and over again forever:
void loop() {
// reads the input on analog pin A0 (value between 0 and 4095)
int analogValue = analogRead(POTENTIOMETER_PIN);

// scales it to brightness (value between 0 and 255)


int brightness = map(analogValue, 0, 4095, 0, 255);

// sets the brightness LED that connects to pin 3


analogWrite(LED_PIN, brightness);

// print out the value


Serial.print("Analog value = ");
Serial.print(analogValue);
Serial.print(" => brightness = ");
Serial.println(brightness);
delay(100);
}

BLUETOOTH

How the Code Works


This code establishes a two-way serial Bluetooth
communication between two devices.

The code starts by including the BluetoothSerial library.


#include "BluetoothSerial.h"
The next three lines check if Bluetooth is properly enabled.

#if !defined(CONFIG_BT_ENABLED) || !
defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make
menuconfig` to and enable it
#endif
Then, create an instance
of BluetoothSerial called SerialBT:
BluetoothSerial SerialBT;
setup()

In the setup() initialize a serial communication at a baud


rate of 115200.
Serial.begin(115200);

Initialize the Bluetooth serial device and pass as an


argument the Bluetooth Device name. By default it’s
called ESP32test but you can rename it and give it a unique
name.
SerialBT.begin("ESP32test"); //Bluetooth device name

loop()

In the loop(), send and receive data via Bluetooth Serial.


In the first if statement, we check if there are bytes being
received in the serial port. If there are, send that information
via Bluetooth to the connected device.

if (Serial.available()) {
SerialBT.write(Serial.read());
}

SerialBT.write() sends data using bluetooth serial.


Serial.read() returns the data received in the serial port.

The next if statement, checks if there are bytes available to


read in the Bluetooth Serial port. If there are, we’ll write
those bytes in the Serial Monitor.

if (SerialBT.available()) {
Serial.write(SerialBT.read());
}
It will be easier to understand exactly how this sketch
works in the demonstration.
CIRCUIT CONNECTION.

SOURCE CODE.
#include <BluetoothSerial.h>

BluetoothSerial SerialBT;

const int ledPin = 2; // Define the GPIO pin connected to the LED

void setup() {
SerialBT.begin("ESP32_LED_Control"); // Name for the Bluetooth module
pinMode(ledPin, OUTPUT);
}

void loop() {
if (SerialBT.available()) {
char command = SerialBT.read();
if (command == '1') {
digitalWrite(ledPin, HIGH); // Turn the LED on
} else if (command == '0') {
digitalWrite(ledPin, LOW); // Turn the LED off
}
}

}
ESP32: Send Messages to
WhatsApp
CallMeBot WhatsApp API
To send messages to your WhatsApp account with the
ESP32, we’ll use a free API service called CallMeBot service.
You can learn more about CallMeBot at the following link:

 https://www.callmebot.com/

Basically, it works as a gateway that allows you to send a


message to yourself. This can be useful to send alert
messages from the ESP32.

Getting the CallMeBot API


KEY
Before starting using the API, you need to get the CallmeBot
WhatsApp API key. Follow the next instructions (check this
link for the instructions on the official website).
1. Add the phone number +34 644 51 95 23 to your
Phone Contacts. (Name it as you wish);
2. Send the following message: “I allow callmebot to
send me messages” to the new Contact created
(using WhatsApp of course);
3. Wait until you receive the message “API Activated
for your phone number. Your APIKEY is XXXXXX”
from the bot.
Note: If you don’t receive the API key in 2 minutes, please
try again after 24hs. The WhatsApp message from the bot
will contain the API key needed to send messages using the
API.

CallMeBot API
To send a message using the CallMeBot API you need to
make a POST request to the following URL (but using your
information):

https://api.callmebot.com/whatsapp.php?
phone=[phone_number]&text=[message]&apikey=[your_apikey]
 [phone_number]: phone number associated with
your WhatsApp account in international format;
 [message]: the message to be sent, should be URL
encoded.
 [your_apikey]: the API key you received during the
activation process in the previous section.
For the official documentation, you can check the following
link: https://www.callmebot.com/blog/free-api-whatsapp-
messages/

Installing the URLEncode


Library
As we’ve seen previously, the message to be sent needs to
be URL encoded. URL encoding converts characters into a
format that can be transmitted over the Internet. URLs can
only be sent over the Internet using the ASCII character-set.

This will allow us to include characters like ç, ª, º, à, ü in our


messages.

You can encode the message yourself, or you can use a


library, which is much simpler. We’ll use the UrlEncode
library that can be installed on your Arduino IDE.

Go to Sketch > Include Library > Manage Libraries and


search for URLEncode library by Masayuki Sugahara as
shown below.
CIRCUIT CONNECTION.

SOURCE CODE.
This code are using for notify the detection of digital sensor
on ESP32. The whatsapp massage will appear “Motion
Detection”.

#include <WiFi.h>
#include <HTTPClient.h>
#include <UrlEncode.h> // Install library UrlEncode by Masayuki

int led_pin = 21; //connect led to pin 2


int sensor_pin = 18; //connect digital sensor to pin 18

const char* ssid = "HUAWEI nova 11 Pro"; // connect your wifi hostpot mobile
phone
const char* password = "faris1992"; // password wifi

// +international_country_code + phone number


String apiKey = "8215843";// Malaysia +6, example: +0176901560
String phoneNumber = "+60176901560";

void sendMessage(String message){

// Data to send with HTTP POST


String url = "https://api.callmebot.com/whatsapp.php?phone=" + phoneNumber +
"&apikey=" + apiKey + "&text=" + urlEncode(message);
HTTPClient http;
http.begin(url);

// Specify content-type header


http.addHeader("Content-Type", "application/x-www-form-urlencoded");

// Send HTTP POST request


int httpResponseCode = http.POST(url);
if (httpResponseCode == 200){
Serial.print("Message sent successfully");
}
else{
Serial.println("Error sending the message");
Serial.print("HTTP response code: ");
Serial.println(httpResponseCode);
}

// Free resources
http.end();
}

void setup() {
Serial.begin(115200);

pinMode(sensor_pin, INPUT);
pinMode(led_pin, OUTPUT);
digitalWrite (led_pin, LOW);

//initialize wifi connection


WiFi.begin(ssid, password);
Serial.println("Connecting");
while(WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to WiFi network with IP Address: "); // wifi network
ip address
Serial.println(WiFi.localIP());

// Send Message to WhatsAPP


sendMessage("ESP are connected!"); // whatsapp will received message
}

void loop() {
int state = digitalRead(sensor_pin);
if (state == HIGH) { // if motion detected
digitalWrite(led_pin, HIGH); // turn LED ON
sendMessage("Motion Detected!"); //send message
delay(5000);
}
else {
digitalWrite(led_pin, LOW); // turn LED OFF if we have no motion
}

ESP32: Telegram ON/OFF LED


What is Telegram?

 Telegram is a cloud-based instant messaging platform


and communication app.
 It allows users to send and receive messages, make
voice and video calls, and share photos, videos,
documents, and other files.
 Telegram is available for smartphones running various
operating systems, including iOS, Android, and
Windows.

Application:

 We can set the ESP32 to send Alterts, Sensor data,


notifications etc. directly on the Telegram.
 We can send message via Telegram to ESP32 for
certain actions, i.e. Light control, Appliances
control,etc.

Now Let’s start.


Step 1
Open telegram and find BotFather
Now find the Botfather in the result and open it and click ok
start.
Now type /newbot and press enter.

Now set the username for your bot.


Now set the username for your bot (it must me end with bot)

Now you will get the token id, copy this ID and paste in Notepad.
Now search IDBot in search and open it and click on start.

The bot will return the ID after you click on start as shown below.
Let’s Interface the LED to
ESP32

Send the text message to telegram using ESP32


Here, we will be using witnessmenow’s Universal-Arduino-Telegram-Bot library from
GitHub.

https://github.com/witnessmenow/Universal-Arduino-Telegram-Bot

Extract the library and add it to the libraries folder path of Arduino IDE.

For information about how to add a custom library to the Arduino IDE and use examples
from it, refer Adding Library To Arduino IDE in the Basics section.

Now install another library which is Arduinojson library for the above example. We need to
install the Arduinojson library using the Arduino Library Manager.

 Open the Arduino IDE


 Navigate to Sketch ► Include Library ► Manage Libraries…
 The library Manager window will pop up. Now enter Arduinojson into the search box, and
click Install on the Arduinojson option to install version 6.12.2 or higher. As shown below
image.

Control the led using Telegram


Let’s control the LED from telegram using the ESP32 and Arduino IDE.

Before uploading the code make sure you have added your SSID, Password, Token
ID, and Chat ID as follows.
const char* ssid = "ADD_YOUR_SSID";
const char* password = "ADD_YOUR_PASS";
#define BOTtoken " XXXXXXXXXX:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
#define CHAT_ID " XXXXXXXXXX"

CIRCUIT CONNECTION
SOURCE CODE
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#include <ArduinoJson.h>

const char* ssid = "HUAWEI nova 11 Pro";


const char* password = "faris1992";

#define BOTtoken "6729010522:AAFdq23Otazy_ydg1x13MNZ_uxZgGKIp6PE"


#define CHAT_ID "1052043015"

WiFiClientSecure client;
UniversalTelegramBot bot(BOTtoken, client);

int botRequestDelay = 1000;


unsigned long lastTimeBotRan;

const int ledPin = 2;


bool ledState = LOW;

void NewMessagesHandle(int NewMessages) {


Serial.println("NewMessagesHandle");
Serial.println(String(NewMessages));

for (int i=0; i<NewMessages; i++) {


String chat_id = String(bot.messages[i].chat_id);
if (chat_id != CHAT_ID){
bot.sendMessage(chat_id, "Unauthorized user", "");
continue;
}
String text = bot.messages[i].text;
Serial.println(text);

String from_name = bot.messages[i].from_name;

if (text == "/start") {
String welcome = "Welcome, " + from_name + ".\n";
welcome += "Use the following commands to control the LED.\n\n";
welcome += "/led_on to turn ON LED\n";
welcome += "/led_off to turn OFF LED\n";
welcome += "/state to request current LED state \n";
bot.sendMessage(chat_id, welcome, "");
}

if (text == "/led_on") {
bot.sendMessage(chat_id, "The LED is turned ON", "");
ledState = HIGH;
digitalWrite(ledPin, ledState);
}

if (text == "/led_off") {
bot.sendMessage(chat_id, "The LED is turned OFF", "");
ledState = LOW;
digitalWrite(ledPin, ledState);
}

if (text == "/state") {
if (digitalRead(ledPin)){
bot.sendMessage(chat_id, "LED is ON", "");
}
else{
bot.sendMessage(chat_id, "LED is OFF", "");
}
}
}
}

void setup() {
Serial.begin(115200);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, ledState);

WiFi.mode(WIFI_STA); /*Set the WiFi in STA Mode*/


WiFi.begin(ssid, password);
Serial.print("Connecting to ");
Serial.println(ssid);
delay(1000); /*Wait for 1000mS*/
while(WiFi.waitForConnectResult() != WL_CONNECTED){Serial.print(".");}
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("Your Local IP address is: ");
Serial.println(WiFi.localIP()); /*Print the Local IP*/
client.setCACert(TELEGRAM_CERTIFICATE_ROOT);
}

void loop() {
if (millis() > lastTimeBotRan + botRequestDelay) {
int NewMessages = bot.getUpdates(bot.last_message_received + 1);

while(NewMessages) {
Serial.println("Response Received!");
NewMessagesHandle(NewMessages);
NewMessages = bot.getUpdates(bot.last_message_received + 1);
}
lastTimeBotRan = millis();
}
}

NODE RED
Running on Windows

Click this link to install Node Red in Window. https://nodered.org/docs/getting-


started/windows

Install Node.j

Download the latest LTS version of Node.js from the official Node.js home page.
It will offer you the best version for your system.
Run the downloaded MSI file. Installing Node.js requires local administrator
rights; if you are not a local administrator, you will be prompted for an
administrator password on install. Accept the defaults when installing. After
installation completes, close any open command prompts and re-open to
ensure new environment variables are picked up.
This page gives specific instructions on setting up Node-RED in a Microsoft
Windows environment. The instructions are specific to Windows 10. They may
also work for Windows 7 and Windows Server from 2008R2, but it is advisable
not to use them due to lack of current support.

Note : Some of the following instructions mention the "command prompt". Where this is used, it
refers to either the Windows cmd or PowerShell terminal shells. It is recommended to use
PowerShell on all newer versions of Windows as this gives you access to commands and folder
names that are closer to those of Linux/Mac.

Quick Start

1. Install Node.js

Download the latest LTS version of Node.js from the official Node.js home page.
It will offer you the best version for your system.

Run the downloaded MSI file. Installing Node.js requires local administrator
rights; if you are not a local administrator, you will be prompted for an
administrator password on install. Accept the defaults when installing. After
installation completes, close any open command prompts and re-open to
ensure new environment variables are picked up.
Once installed, open a command prompt and run the following command to
ensure Node.js and npm are installed correctly.

Using Powershell: node --version; npm --version

Using cmd: node --version && npm --version

You should receive back output that looks similar to:

v18.15.0
9.5.0

2. Install Node-RED

Installing Node-RED as a global module adds the command node-red to your


system path. Execute the following at the command prompt:

npm install -g --unsafe-perm node-red

3. Run Node-RED

Once installed, you are ready to run Node-RED.

Running on Windows
Once installed, the simple way to run Node-RED is to use the node-red command in
a command prompt: If you have installed Node-RED as a global npm package,
you can use the node-red command:

C:>node-red

How to install Mosquitto MQTT in Window

1. Install Mosquitto in Window


https://mosquitto.org/documentation/

2. Opening/Closing Mosquitto Broker

a. Open Command Prompt (cmd) (run as Administrator) on your computer.


b. Running Mosquitto MQTT Broker: net start mosquitto
c. To stop Mosquitto MQTT Broker: net stop mosquitto
Node-red-dashboard 3.6.1

A set of dashboard nodes for Node-RED

THEORY:

Node-RED is a programming tool for wiring together hardware devices, APIs and
online services in new and interesting ways.

It Provides a browser-based editor that makes it easy to wire together flows


using the wide range of nodes in palette that can be deployed to its runtime in a
single-click.

HTTP being used on request-response is not the best option for transferring
data fast and efficiently. On the other hand, we have MQTT which is lightweight,
fast and best for sending data over different IoT devices.

Understanding Node-Red Components

Before starting Node-RED flow creation process, let us know the name of the
components and its uses
as Figure 1.

The components of
Node-RED are:

● Node library
● Visual Editor
● Current Flow
● Help/Info
● Deploy
● Debug

Figure 1: Node-red window


PART A: Creating a dashboard layout in Node-RED

1. Open command prompt, run node-RED application by using the


command below:
● cd\

● node-red

2. Open Internet Browser such as Mozilla Firefox, and type


http://localhost:1880 at URL area and hit enter. The node-RED page will
appear as shown in Fig.2 below.

Figure 2: Node-RED window


3. Create a new dashboard layout by following step (1) (2) (3) (4) as
illustrated in Fig.3 below:

Figure 3: Dashboard section

at step (3) - “edit”, modify the properties, and click “Update”

Name: My Home
Icon: dashboard
Note:
For Icon symbol you should use a name accordingly to the icon’s names
in this link: https://klarsys.github.io/angular-material-icons

at step (4) - “+group”, modify the properties and click “Update”


Name: Room 1
Tab: My Home

your final dashboard layout will look like Fig.4 below:

Figure 4: Dashboard Layout

TASK PART A:
Modify the dashboard layout to become like illustrated in Figure below:
PART B: Create Node-RED flow

1. Look at Node Section, and search for:


● mqtt in
● json
● mqtt out
● gauge
● switch
● debug

2. Arrange and connect all nodes to become like illustrated in Fig.5 below:

Figure 5: flow Part B

3. Change properties of “mqtt in”, “mqtt out”, “gauge” and “switch” as shown
in Fig.6 (a) - (d) below:

MQTT IN Properties:
Server: 178.128.127.202:1883
Topic: espXX/DHT22
Figure 6 (a): MQTT in node

Note: for topic’s name, change “XX” to your board number such as 01,02,..
and so on

MQTT OUT Properties:


Server: 178.128.127.202:1883
Topic: espXX/room/control

Figure 6 (b): MQTT out node

GAUGE Properties:
Group: [Garden]Humidity
Value format: {{msg.payload.humidity}}
Figure 6 (c): GAUGE node

SWITCH Properties:
Group:[My Home] Room 1
On Payload:{ "value" : "on"}
Off Payload: {"value" : "off"}
Figure 6 (d): SWITCH node

4. Your Node-RED application is ready. Click the Deploy button on the top
right corner.

Then, at the internet browser, open a new tab and type


http://localhost:1880/ui then hit enter
The node-RED dashboard will appear as shown in Fig.7 below:

Figure 7: Node-RED Dashboard

5. Click on the “TAB Button” and observe the dashboard, then write down
your observation in Practical Work Assessment Form.

PART C: MQTT - Node-RED Application using MQTT Box

1. Open MQTT Box and create a new MQTT Client with following setting:

● MQTT Client Name: Node Red Localhost (you can change to any
name)
● Protocol: mqtt/tcp
● Host: 178.128.127.202:1883

2. At MQTT Box, Subscribe to topic: “espXX/room/control”.


3. At MQTT Box, Publish the data with following parameters:

Topic: espXX/DHT22
payload: {"humidity":69.7}
TASK PART C:

a. Open the MQTT Box and Node-RED side by side as shown in Figure below
and click at a switch then observe data received at MQTT Box. Then write
down your observation in Practical Work Assessment Form.

b. Open the MQTT Box and Node-RED side by side as shown in Figure below
and click at a “Publish” button at MQTT Box then observe changing at
Gauge Meter at Node-RED. Then write down your observation in Practical
Work Assessment Form.
PART D: MQTT - Node-RED Application using ESP32

1. Connect a wire as illustrated in Figure below:


GPIO22 LED1
GPIO23 LED2
GPIO25 out DHT22
5V + DHT22
GND - DHT22

2. Once the circuit ready, open Arduino IDE software and rewrite the code
shown in Appendix 1. You may download this code from
https://github.com/kingdiaw/LAB_IBC/blob/main/PW5_partD/PW5_partD.i
no. Change:
 ssid
 password
 broker
 unique_id
 topic_subscribe
 topic_publish
3. Upload the sketch. Before clicking the upload button, go to Tools →
Board, and select the board you’re using. Make sure that Board Node
MCU-32S and select ESP32’s COM port.

4. Press the upload button and wait for the “Done uploading.” message.

5. Open Serial Monitor, wait until WiFi connected.

6. At node-RED, open Debugging Message as shown in Figure below:

7. Open Serial Monitor and node-RED side by side as illustrated in figure


below, then write down your observation in Practical Work Assessment
Form.

TASK:

1. At node-RED, by using appropriate dashboard node, display the


temperature value received from ESP32 at Group: [Garden] Temperature.

2. At node-RED, add another (2) TWO switch node that will publish data with
following JSON format:

1st switch node:

Group: [My Home] Room 2


On Payload: {“value” : “on2”}
Off Payload: {“value” : “off2”}

2nd switch node:

Group: [My Home] Room 2


On Payload: {“value” : “buzOn”}
Off Payload: {“value” : “buzOff”}

3. Connect BUZZER to any GPIO pins of Node-MCU-32S. Modify given code


Appendix 1 to. complete the sub-tasks shown in Table 1. Your code should
have a suitable debugging message. Upload your code into ESP32, then
show your result to your lecturer.

Table 1

Received Message ESP32 DIVKIT respond

{ "value " : "on2" } LED2 turn ON

{ "value " : "off2" } LED2 turn OFF

{ "value " : "buzOn" } BUZZER turn ON

{ "value " : "buzOff" } BUZZER turn OFF


APPENDIX 1

#include <WiFi.h>
#include "DHTesp.h" //DHTesp by beegee_tokyo Version 1.17.0
#include <ArduinoJson.h> //ArduinoJson by Benoit Blanchon Version 6.13.0
#include <MQTT.h> //MQTT by Joel Gaehwiler Version 2.4.7

// Replace the next variables with your SSID/Password combination


const char* ssid = "xxxxxxxxxx";
const char* password = "xxxxxxxxxx";
WiFiClient client;

//MQTT setting
const char* broker ="xxx.xxx.xxx.xxx"; //Server PTSS
const char* unique_id = "espXX";
String topic_subscribe = "espXX/room/control";
String topic_publish = "espXX/DHT22";
MQTTClient mqtt(1024);

//DHT Pin
const byte dhtPin = 25;
DHTesp dht;

// LED Pin
const byte ledPin = 2;
const byte led1 = 22;

//Global Variable
unsigned long ledTick=0;
unsigned long sysTick=0;
float temperature=0.0,humidity=0.0;
const unsigned int TIME_INTERVAL = 15000; //15 Sec

//User Function - setup_wifi()


//------------------------------------------------
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);

WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {


delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
//------------------------------------------------

//User Function - setup_mqtt()


//------------------------------------------------
void setup_mqtt(){
while(!mqtt.connect("esp01")){
Serial.print(".");
delay(500);
}
Serial.println("MQTT connected.");
mqtt.subscribe(topic_subscribe);
}
//------------------------------------------------

//CALL THIS FUNCTION WHEN RECEIVED MESSAGE FROM MQTT


//-------------------------------------------------------------
void messageReveived(String &topic_subscribe, String &payload){
Serial.print("Incoming Topic:");
Serial.println(topic_subscribe);
Serial.print(", Payload");
Serial.println(payload);

//Decode DATA from JSON format


//e.g.: {"value":"on"}
DynamicJsonDocument doc(1024);
deserializeJson (doc,payload);
String value = doc["value"];

Serial.println(value);

//Application according to JSON Data


if(value == "on"){
digitalWrite(led1,HIGH);
Serial.println("LED on");
}
else if(value == "off"){
digitalWrite(led1,LOW);
Serial.println("LED off");
}
}
//------------------------------------------------------------------
void setup() {
Serial.begin(115200);
dht.setup(dhtPin,DHTesp::DHT22);
pinMode(ledPin, OUTPUT);
pinMode(led1,OUTPUT);
mqtt.begin(broker,1883,client);
mqtt.onMessage(messageReveived);
setup_wifi();
setup_mqtt();
}

void loop() {
//MQTT Running
mqtt.loop();
if(!mqtt.connected()){
setup_mqtt();
}

//Publish Payload to MQTT every 15 Sec


if(millis()>sysTick){
sysTick = millis()+TIME_INTERVAL;
humidity = dht.getHumidity();
temperature = dht.getTemperature();
Serial.print(dht.getStatusString());
Serial.print("\t");
Serial.print(humidity, 1);
Serial.print("\t\t");
Serial.print(temperature, 1);
Serial.println();

StaticJsonDocument<200>data;
data["temperature"]=temperature;
data["humidity"]=humidity;

serializeJson(data,Serial);
Serial.println();
serializeJsonPretty(data,Serial);
Serial.println();

String payload;
serializeJson(data,payload);

mqtt.publish(topic_publish,payload);
}

//Blinking LED onboard


if(millis()>ledTick){
ledTick = millis()+300;
digitalWrite(ledPin,digitalRead(ledPin)^1);
}
}

You might also like