本文主要是介绍物联网(ESP2866+MQTT+android),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
准备:
- 硬件:ESP8266(某宝)、ESP8266数据线(烧录软件)、杜邦线、面包板、无线路由器(有网)
- 软件:Arduino IDE(官网)、android studio(官网)、EMQX(github)
- 安装ESP8266开发板文件首选项添加8266附加管理器网址:http://arduino.esp8266.com/stable/package_esp8266com_index.json
- 工具开发板管理器,输入8266
- 安装下载(可能会很久、可能会失败很多次......)
- 安装成功后可以在开发板选择:NodeMCU1.0(ESP-12E Module )
- 安装arduion PubSubClient库(项目-》加载库-》管理库搜索“PubSubClient”)安装
选择pubsubclient 示例(mqtt base)修改
-
#include <ESP8266WiFi.h> #include <PubSubClient.h>const char* ssid = "TP-workS"; //修改 const char* password = "HC201902"; //修改 const char* mqtt_server = "........"; //修改 EMQX 服务地址WiFiClient espClient; PubSubClient client(espClient); unsigned long lastMsg = 0; #define MSG_BUFFER_SIZE (50) char msg[MSG_BUFFER_SIZE]; int value = 0;void setup_wifi() {delay(10);Serial.println();Serial.print("Connecting to ");Serial.println(ssid);WiFi.mode(WIFI_STA);WiFi.begin(ssid, password);while (WiFi.status() != WL_CONNECTED) {delay(500);Serial.print(".");}randomSeed(micros());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(); }void reconnect() {while (!client.connected()) {Serial.print("Attempting MQTT connection...");String clientId = "ESP8266Client-";clientId += String(random(0xffff), HEX);// Attempt to connectif (client.connect(clientId.c_str())) {Serial.println("connected");client.publish("outTopic", "hello world"); //发布 outTopic主题client.subscribe("inTopic"); //订阅 inTopic主题} else {Serial.print("failed, rc=");Serial.print(client.state());Serial.println(" try again in 5 seconds");delay(5000);}} }void setup() {Serial.begin(115200);setup_wifi();client.setServer(mqtt_server, 1883); //默认client.setCallback(callback); }void loop() {if (!client.connected()) {reconnect();}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);} }
启动EMQX 服务:进入EMQX解压bin路径:emqx start 启动 点击打开服务地址
- 在监控中(中文在设置 中可修改),即可看到(需新建监控主题:outTopic、inTopic)
这篇关于物联网(ESP2866+MQTT+android)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!