Arduino--ESP8266--ESP-01学习笔记--发布、订阅
2017-12-18 10:43
961 查看
参考博客:https://sonyarouje.com/2016/03/15/mqtt-communication-with-arduino-using-esp8266-esp-01/
#include <WiFiEsp.h> #include <WiFiEspClient.h> #include <WiFiEspUdp.h> #include "SoftwareSerial.h" #include <PubSubClient.h> IPAddress server(101, 200, 46, 138); char ssid[] = "liefyuan"; // your network SSID (name) char pass[] = "123456789"; // your network password int status = WL_IDLE_STATUS; // the Wifi radio's status // Initialize the Ethernet client object WiFiEspClient espClient; PubSubClient client(espClient); SoftwareSerial soft(2,3); // RX, TX void setup() { // initialize serial for debugging Serial.begin(9600); // initialize serial for ESP module soft.begin(9600); // initialize ESP module WiFi.init(&soft); // check for the presence of the shield if (WiFi.status() == WL_NO_SHIELD) { Serial.println("WiFi shield not present"); // don't continue while (true); } // attempt to connect to WiFi network while ( status != WL_CONNECTED) { Serial.print("Attempting to connect to WPA SSID: "); Serial.println(ssid); // Connect to WPA/WPA2 network status = WiFi.begin(ssid, pass); } // you're connected now, so print out the data Serial.println("You're connected to the network"); //connect to MQTT server client.setServer(server, 1883); client.setCallback(callback); } //print any message received for subscribed topic 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 loop() { // put your main code here, to run repeatedly: if (!client.connected()) { reconnect(); } client.loop(); } void reconnect() { // Loop until we're reconnected while (!client.connected()) { Serial.print("Attempting MQTT connection..."); // Attempt to connect, just a name to identify the client if (client.connect("arduinoClient")) { Serial.println("connected"); // Once connected, publish an announcement... client.publish("command","hello world"); // ... and resubscribe client.subscribe("presence"); } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" try again in 5 seconds"); // Wait 5 seconds before retrying delay(5000); } } }
相关文章推荐
- Arduino--ESP8266--ESP-01学习笔记--连接WiFi、连接MQTT服务器、web显示
- ESP8266-01学习笔记01:如何使用USB转串口对ESP-01进行入门调试、烧录固件?
- ESP8266 SDK学习笔记(一):ESP8266 SDK结构
- 【Arduino学习笔记】手把手教你使用ESP8266----②调试篇
- 【Arduino学习笔记】手把手教你使用ESP8266----③整合Arduino篇
- Redis学习笔记四:独立功能之发布与订阅
- 六 redis学习笔记之发布订阅
- 基于Protues的Arduino学习笔记01-Arduino UNO实验板设计
- redis学习笔记 发布与订阅
- 六 redis学习笔记之发布订阅
- 玩转 ESP8266 Arduino 笔记01 开发环境搭建
- React-Native傻瓜式学习笔记(三):基于事件发布/订阅的网络请求工具类封装
- Apache ActiveMQ学习笔记【mq的方式有两种:点到点和发布/订阅】
- 发布与订阅消息--Redis学习笔记八
- ROS学习笔记2 消息发布与订阅
- Redis学习笔记(九) 命令进阶:Pub/Sub(发布/订阅)操作
- StackExchange.Redis学习笔记(五) 发布和订阅
- Redis学习笔记8--Redis发布/订阅
- Redis学习笔记(八)--频道发布和消息订阅
- 《Redis设计与实现》学习笔记-发布与订阅、事务、慢查询日志