大家好, 今天和大家來分享, Arduino #48集, 用一塊ESP32來學 IOT (#32 Learn IOT with MQTT + ESP32) 這個影片很適合初學者來觀看學習.
影片內容主要是告訴大家, 只要手上有一塊 ESP32 和一台電腦, 就可以開始學習 IOT 了 ! 看過這個影片, 你會了解學習 IOT 一點都不難喔! 甚至可以延伸作法, EMQX MQTT web client 透過雲端EMQX來做遠端的控制!
![]() |
使用 MQTT 來幫助你快速完成第一個 IoT專案 |
有幾位朋友寫信來告知, MQTTLens 這個 Chrome 流覽器插件(extension) 已經無法再使用了, 所以我把這個教學的流程, 整理一下, 改用了 EMQX 本身自有的 MQTT web client 來做這個教學.
這個是一個專門為初學者來開發的一個系列, 所以會講的比較詳細, 相信各位只要仔細收看內容並進行實作, 一定會收獲滿滿滿。好, 那我們就開始吧今天的練習吧~
如果時間不夠的朋友, 也可以從以下的時間軸挑選想看的部份即可!
影片時間軸:
00:00 開始
01:03 什麼是 MQTT,它是如何運作的?
02:29 打造你的第一個MQTT IOT專案!
03:34 MQTT 程式:pubsubclient
04:27 Arduino IDE: 設定Additional Boards Manager URL
04:55 Arduino IDE 其它設定
05:22 從我的部落格中下載程式並貼在Arduino IDE
05:51 在程式中更改必要的設定
08:55 使用 EMQX MQTT web client
09:34 EMQX 簡易設定
11:39 訂閱 ESP32上的主題
14:30 從EMQX MQTT client 訂閱主題
16:52 從EMQX MQTT client 發佈主題 Stonez56/esp32s
- EMQX MQTT Web Client
https://www.emqx.io/online-mqtt-client/ - Pubsubclient library: https://github.com/knolleary/pubsubclient/blob/master/examples/mqtt_esp8266/mqtt_esp8266.ino
- Additional Boards Manager URL: https://arduino.esp8266.com/stable/package_esp8266com_index.json,https://dl.espressif.com/dl/package_esp32_index.json
- Source code: https://stonez56.blogspot.com/
- /*
- Basic ESP8266 MQTT example
- This sketch demonstrates the capabilities of the pubsub library in combination
- with the ESP8266 board/library.
- It connects to an MQTT server then:
- - publishes "hello world" to the topic "outTopic" every two seconds
- - subscribes to the topic "inTopic", printing out any messages
- it receives. NB - it assumes the received payloads are strings not binary
- - If the first character of the topic "inTopic" is an 1, switch ON the ESP Led,
- else switch it off
- It will reconnect to the server if the connection is lost using a blocking
- reconnect function. See the 'mqtt_reconnect_nonblocking' example for how to
- achieve the same result without blocking the main loop.
- To install the ESP8266 board, (using Arduino 1.6.4+):
- - Add the following 3rd party board manager under "File -&nbgt; Preferences -&nbgt; Additional Boards Manager URLs":
- http://arduino.esp8266.com/stable/package_esp8266com_index.json
- - Open the "Tools -&nbgt; Board -&nbgt; Board Manager" and click install for the ESP8266"
- - Select your ESP8266 in "Tools -&nbgt; Board"
- */
- #include &nblt;WiFi.h&nbgt;
- #include &nblt;PubSubClient.h&nbgt;
- #include &nblt;EasyButton.h&nbgt;
- #define LED 2 //built-in LED on ESP32
- // Update these with values suitable for your network.
- const char *ssid = "Stonez24";
- const char *password = "a0101010101a";
- // Define your client ID on EMQX
- String mqtt_ClientID = "stonez56_IOT_Station_";
- // Define your topics to subscribe / publish
- const char* sub_topic = "stonez56/esp32s";
- const char* pub_led_topic = "stonez56/esp32s_led_state";
- const char* pub_init_topic = "stonez56/esp32s_is_back";
- // EMQX broker parameters
- const char *mqtt_server = "broker.emqx.io";
- const char *mqtt_userName = "emqx";
- const char *mqtt_password = "public";
- 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);
- // We start by connecting to a WiFi network
- 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 &nblt; length; i++)
- {
- Serial.print((char)payload[i]);
- }
- Serial.println();
- payload[length] = '\0';
- String message = (char *)payload;
- if (strcmp(topic, sub_topic) == 0)
- {
- if (message == "off")
- {
- digitalWrite(LED, LOW); //Turn off
- client.publish(pub_led_topic, "LED off");
- }
- if (message == "on")
- {
- digitalWrite(LED, HIGH); //Turn on
- client.publish(pub_led_topic, "LED on");
- }
- if (message == "flash")
- {
- digitalWrite(LED, LOW); //LED flashing 2 times
- delay(200);
- digitalWrite(LED, HIGH);
- delay(200);
- digitalWrite(LED, LOW);
- delay(200);
- digitalWrite(LED, HIGH);
- delay(200);
- digitalWrite(LED, LOW);
- client.publish(pub_led_topic, "LED flashed 2 times");
- }
- }
- /* 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 active 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.println("Attempting EMQX MQTT connection...");
- // Create a random client ID
- mqtt_ClientID += String(random(0xffff), HEX);
- // Attempt to connect
- if (client.connect((mqtt_ClientID, mqtt_userName, mqtt_password)))
- {
- Serial.print(" connected with Client ID: ");
- Serial.println(mqtt_ClientID);
- // Once connected, publish an announcement...
- client.publish(pub_init_topic, "Hi, I'm online!");
- // ... and resubscribe
- client.subscribe(sub_topic);
- }
- 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, OUTPUT); // Initialize the _LED pin as an output
- digitalWrite(LED, LOW); //default ESP32 LOW is turn off
- 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 &nbgt; 2000)
- // {
- // lastMsg = now;
- // ++value;
- // snprintf(msg, MSG_BUFFER_SIZE, "hello world #%ld", value);
- // Serial.print("Publish message: ");
- // Serial.println(msg);
- // client.publish("stonez56/esp32s_button_pushed", msg);
- // } */
- }