2022/03/27

Arduino #32 用一塊ESP32來學 IOT (#32 Learn IOT with MQTT + ESP32)

大家好, 今天和大家來分享, Arduino #32 用一塊ESP32來學 IOT (#32 Learn IOT with MQTT + ESP32) 這個影片很適合初學者來觀看學習. 影片內容主要是告訴大家, 只要手上有一塊 ESP32 和一台電腦, 就可以開始學習 IOT 了 ! 看過這個影片, 你會了解學習 IOT 一點都不難喔! 甚至可以延伸作法, 利用 MQTTlens 透過雲端EMQX來做遠端的控制!



參考資料:

如果時間不夠的朋友, 也可以從以下的時間軸挑選想看的部份即可!

影片時間軸:

  • 00:00 開始
  • 00:29 什麼是 MQTT,它是如何運作的?
  • 01:30 你的第一個IOT專案!
  • 01:55 MQTT 程式:pubsubclient
  • 02:40 Arduino IDE: 設定Additional Boards Manager URL
  • 03:09 Arduino IDE 其它設定
  • 03:48 從我的部落格中下載程式並貼在Arduino IDE
  • 04:07 在程式中更改必要的設定
  • 07:27 從 Chrome 瀏覽器啟動 MQTTlens
  • 07:54 在 MQTTlens 新增 EMQX 連線
  • 09:54 訂閱 ESP32上的兩個主題
  • 11:19 從 MQTTlens 發布主題
  • 12:45 本次主要內容摘要

程式碼:


  1. /*
  2. Basic ESP8266 MQTT example
  3. This sketch demonstrates the capabilities of the pubsub library in combination
  4. with the ESP8266 board/library.
  5. It connects to an MQTT server then:
  6. - publishes "hello world" to the topic "outTopic" every two seconds
  7. - subscribes to the topic "inTopic", printing out any messages
  8. it receives. NB - it assumes the received payloads are strings not binary
  9. - If the first character of the topic "inTopic" is an 1, switch ON the ESP Led,
  10. else switch it off
  11. It will reconnect to the server if the connection is lost using a blocking
  12. reconnect function. See the 'mqtt_reconnect_nonblocking' example for how to
  13. achieve the same result without blocking the main loop.
  14. To install the ESP8266 board, (using Arduino 1.6.4+):
  15. - Add the following 3rd party board manager under "File -> Preferences -> Additional Boards Manager URLs":
  16. http://arduino.esp8266.com/stable/package_esp8266com_index.json
  17. - Open the "Tools -> Board -> Board Manager" and click install for the ESP8266"
  18. - Select your ESP8266 in "Tools -> Board"
  19. */
  20.  
  21. #include <WiFi.h>
  22. #include <PubSubClient.h>
  23. #include <EasyButton.h>
  24. #define LED 2 //built-in LED on ESP32
  25.  
  26. // Update these with values suitable for your network.
  27. const char *ssid = "WiFi-SSID";
  28. const char *password = "WiFi-PASSWORD";
  29.  
  30. // Define your client ID on EMQX
  31. String mqtt_ClientID = "stonez56_IOT_Station_";
  32.  
  33. // Define your topics to subscribe / publish
  34. const char* sub_topic = "stonez56/esp32s";
  35. const char* pub_led_topic = "stonez56/esp32s_led_state";
  36. const char* pub_init_topic = "stonez56/esp32s_is_back";
  37.  
  38. // EMQX broker parameters
  39. const char *mqtt_server = "broker.emqx.io";
  40. const char *mqtt_userName = "emqx";
  41. const char *mqtt_password = "public";
  42.  
  43. WiFiClient espClient;
  44. PubSubClient client(espClient);
  45. unsigned long lastMsg = 0;
  46. #define MSG_BUFFER_SIZE (50)
  47. char msg[MSG_BUFFER_SIZE];
  48. int value = 0;
  49.  
  50. void setup_wifi()
  51. {
  52. delay(10);
  53. // We start by connecting to a WiFi network
  54. Serial.println();
  55. Serial.print("Connecting to ");
  56. Serial.println(ssid);
  57.  
  58. WiFi.mode(WIFI_STA);
  59. WiFi.begin(ssid, password);
  60.  
  61. while (WiFi.status() != WL_CONNECTED)
  62. {
  63. delay(500);
  64. Serial.print(".");
  65. }
  66.  
  67. randomSeed(micros());
  68.  
  69. Serial.println("");
  70. Serial.println("WiFi connected");
  71. Serial.println("IP address: ");
  72. Serial.println(WiFi.localIP());
  73. }
  74.  
  75. void callback(char *topic, byte *payload, unsigned int length)
  76. {
  77. Serial.print("Message arrived [");
  78. Serial.print(topic);
  79. Serial.print("] ");
  80. for (int i = 0; i < length; i++)
  81. {
  82. Serial.print((char)payload[i]);
  83. }
  84. Serial.println();
  85.  
  86. payload[length] = '\0';
  87. String message = (char *)payload;
  88. if (strcmp(topic, sub_topic) == 0)
  89. {
  90. if (message == "off")
  91. {
  92. digitalWrite(LED, LOW); //Turn off
  93. client.publish(pub_led_topic, "off");
  94. }
  95. if (message == "on")
  96. {
  97. digitalWrite(LED, HIGH); //Turn on
  98. client.publish(pub_led_topic, "on");
  99. }
  100. }
  101.  
  102. /* Switch on the LED if an 1 was received as first character
  103. // if ((char)payload[0] == '1')
  104. // {
  105. // digitalWrite(BUILTIN_LED, LOW); // Turn the LED on (Note that LOW is the voltage level
  106. // // but actually the LED is on; this is because
  107. // // it is active low on the ESP-01)
  108. // }
  109. // else
  110. // {
  111. // digitalWrite(BUILTIN_LED, HIGH); // Turn the LED off by making the voltage HIGH
  112. // } */
  113. }
  114.  
  115. void reconnect()
  116. {
  117. // Loop until we're reconnected
  118. while (!client.connected())
  119. {
  120.  
  121. Serial.println("Attempting EMQX MQTT connection...");
  122. // Create a random client ID
  123. mqtt_ClientID += String(random(0xffff), HEX);
  124. // Attempt to connect
  125. if (client.connect((mqtt_ClientID, mqtt_userName, mqtt_password)))
  126. {
  127. Serial.print(" connected with Client ID: ");
  128. Serial.println(mqtt_ClientID);
  129. // Once connected, publish an announcement...
  130. client.publish(pub_init_topic, "Hi, I'm online!");
  131. // ... and resubscribe
  132. client.subscribe(sub_topic);
  133. }
  134. else
  135. {
  136. Serial.print("failed, rc=");
  137. Serial.print(client.state());
  138. Serial.println(" try again in 5 seconds");
  139. // Wait 5 seconds before retrying
  140. delay(5000);
  141. }
  142. }
  143. }
  144.  
  145. void setup()
  146. {
  147. pinMode(LED, OUTPUT); // Initialize the _LED pin as an output
  148. digitalWrite(LED, LOW); //default ESP32 LOW is turn off
  149.  
  150. Serial.begin(115200);
  151. setup_wifi();
  152. client.setServer(mqtt_server, 1883);
  153. client.setCallback(callback);
  154. }
  155.  
  156. void loop()
  157. {
  158.  
  159. if (!client.connected())
  160. {
  161. reconnect();
  162. }
  163. client.loop();
  164.  
  165. /* unsigned long now = millis();
  166. // if (now - lastMsg > 2000)
  167. // {
  168. // lastMsg = now;
  169. // ++value;
  170. // snprintf(msg, MSG_BUFFER_SIZE, "hello world #%ld", value);
  171. // Serial.print("Publish message: ");
  172. // Serial.println(msg);
  173. // client.publish("stonez56/esp32s_button_pushed", msg);
  174. // } */
  175. }