当前位置:网站首页>Mqtt+ardunio+esp8266 development (excluding mqtt server deployment)
Mqtt+ardunio+esp8266 development (excluding mqtt server deployment)
2022-06-25 19:54:00 【JINYUBAOO】
Step on the pit for countless times to sort out the most basic connection
Implementation preparation —MQTT agreement
Preface
1. PUBLISH – Release the news
Issuing message control message means that the client sends message to the server ( Or the server ) Transmit a message to the client .
2. SUBSCRIBE - Subscribe to topics
The client sends... To the server SUBSCRIBE The message is used to create one or more subscriptions . In order to forward the application message to the topic matching the subscription , The server will send PUBLISH Message to client .SUBSCRIBE The message also specifies for each subscription QoS Grade , The server will send messages to the client according to the level .
QoS Grade :
a.QoS 0: The sender sends the message only once , No retry ,Broker No confirmation message will be returned . stay Qos0 Under the circumstances ,Broker May not have received the message .
b.QoS 1: The sender sends the message at least once , Make sure that the message arrives Broker,Broker A confirmation message needs to be returned PUBACK. stay Qos1 Under the circumstances ,Broker May receive duplicate messages .
c.QoS 2 :Qos2 Use two-stage confirmation to ensure that messages are not lost and not repeated . stay Qos2 Under the circumstances ,Broker I'm sure I'll get a message , And only once .
If you want to know more MQTT For control message, please click :MQTT Chinese agreement
General process :
picture source : A big man id:liefyuan
( I would like to express my thanks to many leaders , Their articles helped me a lot )
First step Software and hardware preparation
1.ESP8266 CP2102 Internet of things module

2. A number of male to female DuPont lines
3.arduino uno Development board or similar development board .
Software requirements :
arduino ide
A physical picture :
Pin connection :
ESP8266 ------UNO
VCC-----------3.3v
GND----------GND
RX-------------TX PIN2 ( With SoftWareSerialExample)
TX-------------RX PIN3( With SoftWareSerialExample)
Previously used 01TXRX It didn't work , I didn't expect that the soft serial communication was successfully solved .
pubsub Kuco and ESP8266 Development board / Libraries are used alone .
Steps are as follows :
To install ESP8266 Development board ( Use Arduino 1.6.4+):
- stay “ file -> Preferences -> Add development board manager website ” Add the following third web address : http://arduino.esp8266.com/stable/package_esp8266com_index.json
- open “ Tools -> plate -> Board Manager ”, And then to ESP8266 single click “ install ”
- stay “ Tools -> Development board ” Choose from ESP8266
First step Distribution network + Connect
Come on ! We use the library !!!!MQTT There are many libraries , This article will use PubSubClient library . This library can be found in Arduino IDE Found in the library manager of . Tools -> Management of the library -> find PubSubClient Download according to the version you want , Then open the instance 
(1) Connected to the Internet
A、ssid For yourself WIFI The name of the wireless network ,password by WIFI Wireless network password .
B、 utilize WiFi.begin(ssid, password); Connect to the Internet , This function is a function encapsulated in the library , Pass in two key values to connect .
C、 Connect to the network and then take out the connection status for judgment while (WiFi.status() != WL_CONNECTED) {…}
(2) Connect MQTT The server
A、 Define your own server address
B、client.setServer(mqtt_server, 1883); This wrapper function is used to connect MQTT The server ,1883 By default MQTT port
C、client.setCallback(callback); Set callback mode , When ESP8266 This method is called when a subscription message is received
The following is the soft serial port code :10 and 11 It is the development board RX and TX Connect MQTT And ardunio
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11); // RX, TX
void setup()
{
// Open serial communications and wait for port to open:
Serial.begin(115200);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
Serial.println("HELLO!JINYU");
// set the data rate for the SoftwareSerial port
mySerial.begin(115200);
mySerial.println("JINYU");
}
void loop() // run over and over
{
if (mySerial.available())
Serial.write(mySerial.read());
if (Serial.available())
mySerial.write(Serial.read());
}
The third step Subscribe and publish
(3) Subscribe and publish
A、 Instantiation
WiFiClient espClient;
PubSubClient client(espClient);
B、 Define subscription Topic :
const char* TOPIC = “”;
perhaps :client.publish(“outTopic”, “hello world”);// Publish topics and content
client.subscribe(“inTopic”);// At the subscriber inTopic Subject matter .
C、 Serial port monitoring 
At last, the general code is attached :
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// Update these with values suitable for your network.
const char* ssid = "JINYU";
const char* password = "150";
const char* mqtt_server = "123.57.133.**";// Here is the deployment MQTT Server address of the server
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
void setup() {
pinMode(BUILTIN_LED, OUTPUT); // Initialize the BUILTIN_LED pin as an output
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
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());
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
// Switch on the LED if an 1 was received as first character
if ((char)payload[0] == '1') {
digitalWrite(BUILTIN_LED, LOW); // Turn the LED on (Note that LOW is the voltage level
// but actually the LED is on; this is because
// it is acive low on the ESP-01)
} else {
digitalWrite(BUILTIN_LED, HIGH); // Turn the LED off by making the voltage HIGH
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("ESP8266Client")) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish("outTopic", "hello world");
// ... and resubscribe
client.subscribe("inTopic");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
long now = millis();
if (now - lastMsg > 20000) {
// Time delay
lastMsg = now;
++value;
snprintf (msg, 75, "hello world #%ld", value);
Serial.print("Publish message: ");
Serial.println(msg);
client.publish("outTopic", msg);
}
Wrong reflection :
1、 My pin EN Pick up VCC It is not advisable to be normal VCC Pick up VCC
2、 If you use your own hotspot, don't use Chinese, it's easy to make mistakes
3、mqtt_server With :8080
4、RX and TX Be sure to pay attention to the order
5、0 1 Sometimes you can't use , Soft serial port communication is required
If you use lot, Please refer to
id: A vegetarian pill that loves learning — As long as you can use a computer, you can understand the Internet of things tutorial ( Alibaba cloud +esp8266+ Wechat applet )
My subscription debug information 
Finishing up
At the end : Endless learning , I will always be a brother hhhh
边栏推荐
- Is it safe to open a new bond? Is low commission reliable
- The native JS mobile phone sends SMS cases. After clicking the button, the mobile phone number verification code is sent. The button needs to be disabled and re enabled after 60 seconds
- PHP little knowledge record
- Network security detection and prevention exercises (III)
- Tcp/ip test questions (III)
- Is CICC wealth safe? How long does it take to open an account
- How to understand var = a = b = C = 9? How to pre parse?
- 5、 Initialization analysis II of hikaricp source code analysis
- Electronic package to generate EXE file
- Is it safe for tongdaxin to open an account?
猜你喜欢

Bloom filter

ECS 7-day practical training camp (Advanced route) -- day03 -- ecs+slb load balancing practice

Google SEO external chain releases 50+ website platform sharing (e6zzseo)

Leetcode-78-subset

Jsonp function encapsulation

Miner's Diary: why should I go mining on April 5, 2021

Huawei released two promotion plans to promote AI talent development and scientific research innovation

JVM | runtime data area (heap space)

Google cloud SSH enable root password login

mysql load data infile
随机推荐
Embark on a new journey and reach the world with wisdom
最新數據挖掘賽事方案梳理!
Many varieties of EA can be used
Applet Click to return to the top 2 methods
Tcp/ip test questions (I)
Native JS array some method de duplication
ECS 7-day practical training camp (Advanced route) -- day03 -- ecs+slb load balancing practice
Vulnhub range - correlation:2
rmi-registry-bind-deserialization
三、HikariCP获取连接流程源码分析三
QQ robot official plug-in loading configuration method [beta2 version]
Guangzhou Sinovel interactive creates VR Exhibition Hall panoramic online virtual exhibition hall
Network security detection and prevention test questions (I)
Divine reversion EA
What are Baidu collection skills? 2022 Baidu article collection skills
Leetcode-101-symmetric binary tree
Error record: preg_ match(): Compilation failed: range out of order in character class at offset 13
On Oracle full stack virtual machine -- graalvm
Est - il sûr d'ouvrir un compte avec de nouvelles dettes? Une faible Commission est - elle crédible?
JS get the parameters in the URL link