ESP32-MQTT
Aim:
To
interface Wi-Fi module with ESP32 to receive data from cloud using RDL ESP32
Development board.
Description:
Interfacing wi-fi module with the cloud MQTT to receive and send
data using ESP32 microcontroller.
Hardware required:
ESP32-Microcontroller
development board.
Pin connection:
Procedure:
Uploading
and Receiving Data from Cloud using ESP32
2.
Create an instance which will be used in the program
to publish data to the cloud.
3. Select the Instance name (test_1) and use the
details of the same in the code. Include the
code.
5.
Enter the details given under server, port, user,
ssl port in the given program.
const char*
mqttServer =”m16.mqtt.com”; const int mqttPort = 18215;
const char*
mqttUser = “ofmydmjh”;;
const char*
mqttPassword = “c5goIEjTCGRn”;
6.
In order to send a message to the
CloudMQTT, include the line client.publish("topic_name", "Message");
7.
To send data from CloudMQTT ,include the line client.subscribe("Topic_name");\
5. 8. The following code prints the received data from the
cloud in the Serial Monitor void callback(char* topic, byte* payload, unsigned
int length)
{
uint8_t s;
Serial.print("Message
arrived in topic: ");
Serial.println(topic);
Serial.print("Message:");
for (int i =
0; i < length; i++)
{
s= payload[i];
Serial.write(s);
}
}
5.
The final Program:
#include <WiFi.h>
#include <PubSubClient.h> const char* ssid = "userid";
const char*
password = "*********";
/* Details from the instance created */
const char*
mqttServer = "m16.cloudmqtt.com"; const int mqttPort = 18215;
const char*
mqttUser = "ofmydmjh";
const char*
mqttPassword = "c5g0IEjTCGRn"; WiFiClient
espClient;
PubSubClient client(espClient); void setup(void)
{
Serial.begin(115200); WiFi.begin(ssid, password);
/* Connecting ESP8266 to WiFi */
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.write('.');
}
Serial.println("Connected to the WiFi
network"); client.setServer(mqttServer, mqttPort);
client.setCallback(callback);
/* Connecting to CloudMqtt */ while (!client.connected())
{
Serial.println("Connecting to MQTT...");
if (client.connect("ESP32Client",
mqttUser, mqttPassword ))
{
Serial.println("connected");
}
else
{
Serial.print("failed with state ");
Serial.print(client.state()); delay(2000);
}
}
/* Sending message to Topic "test1" */ client.publish("ABC", "Hello from RDL_IOT");
client.subscribe("test"); //Receives
message sent to the topic "test"
}
/* This function is used to print the incoming data sent
to the topic "test" */ void
callback(char* topic, byte* payload, unsigned int length)
{
uint8_t s;
Serial.print("Message arrived in topic: ");
Serial.println(topic);
Serial.print("Message:");
for (int
i = 0; i <
length; i++)
{
s= payload[i];
Serial.write(s);
}
}
void loop(void)
{
client.loop();
}
Output: