一、前言
1、能够使用Arduino的软串口控制Esp8266接入网络,可以看看我的前两个博客。
2、了解MQTT协议,阿里云搭建MQTT服务器。
3、需要的库文件
WiFiEsp库是一个Arduino的封装好AT指令的WiFi操作库,可以使用Arduino的软串口操作
PubSubClient是一个用于Esp8266发布/订阅MQTT消息的库。
链接:https://pan.baidu.com/s/1mAaIbO3-SzVaN-jaaFwVbw
提取码:ol2p
4、修改Esp8266串口波特率为9600
使用AT指令输入AT+UART_DEF=9600,8,1,0,0,如何使用AT指令请看Arduino Esp8266开发 (一)AT指令调试
5、参考的文章网址
二、Arduino代码
#include "DHT.h"
#include <WiFiEspClient.h>
#include <WiFiEsp.h>
#include <WiFiEspUdp.h>
#include <PubSubClient.h>
#include "SoftwareSerial.h"
#define WIFI_AP "xxxx" //你家Wifi名称
#define WIFI_PASSWORD "****" //密码
// DHT
#define DHTPIN 10 //DHT引脚
#define DHTTYPE DHT11
// 初始化DHT11传感器
DHT dht(DHTPIN, DHTTYPE);
char MqttServer[] = "1.11.111.0"; //MQTT服务器的IP地址(阿里云公网IP)
WiFiEspClient espClient; // 初始化以太网客户端对象 -- WiFiEspClient.h
PubSubClient client(espClient); // 初始化MQTT库PubSubClient.h的对象
SoftwareSerial mySerial(2, 3); // RX, TX,声明一个软串口
int status = WL_IDLE_STATUS;
unsigned long lastSend;
void setup() {
Serial.begin(9600);
dht.begin();
InitWiFi(); // 连接WiFi
client.setServer( MqttServer, 1883 ); // 连接WiFi之后,连接MQTT服务器
lastSend = 0;
}
void loop() {
status = WiFi.status();
if ( status != WL_CONNECTED) {
while ( status != WL_CONNECTED) {
Serial.print("[loop()]Attempting to connect to WPA SSID: ");
Serial.println(WIFI_AP);
// 连接WiFi热点
status = WiFi.begin(WIFI_AP, WIFI_PASSWORD);
delay(500);
}
Serial.println("[loop()]Connected to AP");
}
if ( !client.connected() ) {
reconnect();
}
if ( millis() - lastSend > 1000 ) { // 用于定时1秒钟发送一次数据
getAndSendTemperatureAndHumidityData(); // 获取温湿度数据发送到MQTT服务器上去
lastSend = millis();
}
client.loop();
}
/*
* 读取温湿度数据,然后发送到MQTT服务器上去
*/
void getAndSendTemperatureAndHumidityData()
{
Serial.println("Collecting temperature data.");
// 大概250ms读取一次
float h = dht.readHumidity();
float t = dht.readTemperature();
// 查看是否读取温湿度失败的
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(t);
Serial.print(" *C ");
String temperature = String(t);
String humidity = String(h);
Serial.print( "Sending temperature and humidity : [" );
Serial.print( temperature ); Serial.print( "," );
Serial.print( humidity );
Serial.print( "] -> " );
// 构建一个 JSON 格式的payload的字符串
String payload = "{";
payload += "\"temperature\":"; payload += temperature; payload += ",";
payload += "\"humidity\":"; payload += humidity;
payload += "}";
char attributes[100];
payload.toCharArray( attributes, 100 );
client.publish( "DHT11", attributes ); //发布名字为“DHT11”的主题
Serial.print("[publish]-->>");
Serial.println( attributes );
}
/**
*Wifi连接初始化
*/
void InitWiFi()
{
// 初始化软串口,软串口连接ESP模块
mySerial.begin(9600);
// 初始化ESP模块
WiFi.init(&mySerial);
// 检测WiFi模块在不在,宏定义:WL_NO_SHIELD = 255,WL_IDLE_STATUS = 0,
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
while (true);
}
Serial.println("[InitWiFi]Connecting to AP ...");
// 尝试连接WiFi网络
while ( status != WL_CONNECTED) {
Serial.print("[InitWiFi]Attempting to connect to WPA SSID: ");
Serial.println(WIFI_AP);
status = WiFi.begin(WIFI_AP, WIFI_PASSWORD);
delay(500);
}
Serial.println("[InitWiFi]Connected to AP");
}
/**
* MQTT客户端断线重连函数
*/
void reconnect() {
// 一直循环直到连接上MQTT服务器
while (!client.connected()) {
Serial.print("[reconnect]Connecting to MQTT Server ...");
// 尝试连接connect是个重载函数 (clientId, username, password)
if ( client.connect("mqttx_f4bb1f54", "zky", "135") ) {
//设置客户端ID(自定义),用户名,密码
Serial.println( "[DONE]" );
} else {
Serial.print( "[FAILED] [ mqtt connect error code = " );
Serial.print( client.state() );
Serial.println( " : retrying in 5 seconds]" );// Wait 5 seconds before retrying
delay( 5000 );
}
}
}
三、效果
1、登录EMQ X Dashboard
2、连接客户端
3、订阅
4、发送和接收