😏*★,°* :.☆( ̄▽ ̄)/$:.°★ 😏
这篇文章主要介绍ESP8266获取NTP时间及连接MQTT实现远程控制示例。
无专精则不能成,无涉猎则不能通。------梁启超欢迎来到我的博客,一起学习,共同进步。
喜欢的朋友可以关注一下,下次更新不迷路🥞
文章目录
-
- [:smirk:1. ESP8266介绍](#:smirk:1. ESP8266介绍)
- [:blush:2. 获取NTP时间](#:blush:2. 获取NTP时间)
- [:satisfied:3. 连接MQTT远程控制](#:satisfied:3. 连接MQTT远程控制)
😏1. ESP8266介绍
ESP8266
是一款低成本、低功耗的 Wi-Fi 微控制器芯片,广泛应用于物联网 (IoT) 和嵌入式系统中。它具有集成 Wi-Fi 功能,支持通过无线网络与其他设备进行通信,并且相对易于使用,非常适合开发者和工程师进行快速原型设计和小型应用开发。
ESP8266
的主要特点:
1.低功耗:支持低功耗模式,非常适合需要电池供电的应用。
2.Wi-Fi 集成功能:内建 802.11 b/g/n Wi-Fi 协议,支持 station(客户端)和 access point(热点)模式。
3.高性能:基于 32 位的 RISC 处理器,最高主频可达到 80 MHz。
4.支持 SPI、I2C、UART、PWM 等常见通信接口,方便与传感器、显示器等外部设备连接。
除了常见控制器的IO控制、串口通信等功能外,ESP8266主要支持了WiFi连接和网络通信,可用于智能家居、无线传感器网络、远程控制系统等领域。
😊2. 获取NTP时间
可以连接wifi获取当前网络时间,调用NTP时间服务,也可以外接OLED小屏幕来显示做成一个桌面时钟,代码示例:
cpp
#include <ESP8266WiFi.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
// wifi
const char* ssid = "xx";
const char* password = "xxx";
// ntp
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "pool.ntp.org", 28800, 60000);
// 默认灯
#define LED_PIN 2
void setup()
{
// 串口通信
Serial.begin(115200);
// 网络通信
WiFi.mode(WIFI_STA);
WiFi.disconnect();
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
Serial.println(WiFi.localIP());
// ntp
timeClient.begin();
}
void loop()
{
// 网络通信
if (WiFi.status() == WL_CONNECTED)
{
Serial.println("Connected to WiFi");
}
else
{
Serial.println("Disconnected from WiFi");
}
timeClient.update();
Serial.println(timeClient.getFormattedTime());
delay(1000);
}
😆3. 连接MQTT远程控制
MQTT是物联网中常用的协议,开发板连上wifi后,可以连接MQTT服务器,进行消息的收发,可以根据消息控制外设的动作(最简单控制一个灯),代码示例:
cpp
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
// wifi mqtt
WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (50)
char msg[MSG_BUFFER_SIZE];
int value = 0;
const char* ssid = "xxx";
const char* password = "xxx";
const char* mqtt_server = "broker.mqtt-dashboard.com";
// ntp
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "pool.ntp.org", 28800, 60000);
// 默认灯
#define LED_PIN 2
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);
} else {
digitalWrite(BUILTIN_LED, HIGH);
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId = "ESP8266Client-";
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(clientId.c_str())) {
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 setup()
{
pinMode(LED_PIN, OUTPUT);
// 串口通信
Serial.begin(115200);
// 网络通信
WiFi.mode(WIFI_STA);
WiFi.disconnect();
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
Serial.println(WiFi.localIP());
// MQTT
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
// ntp
timeClient.begin();
}
void loop()
{
// 网络通信
if (WiFi.status() == WL_CONNECTED)
{
Serial.println("Connected to WiFi");
}
else
{
Serial.println("Disconnected from WiFi");
}
if (!client.connected())
{
reconnect();
}
if (client.connected())
{
Serial.println("Connected to MQTT");
}
else
{
Serial.println("Disconnected from MQTT");
}
// client.publish("test", "Hello World!");
timeClient.update();
Serial.println(timeClient.getFormattedTime());
client.loop();
unsigned long now = millis();
if (now - lastMsg > 2000) {
lastMsg = now;
++value;
snprintf (msg, MSG_BUFFER_SIZE, "hello world #%ld", value);
Serial.print("Publish message: ");
Serial.println(msg);
client.publish("outTopic", msg);
}
delay(1000);
}
以上。