Advertisement
fabelizer

ESP32_Client_2_LCD_Pushbutton Code

Feb 12th, 2019
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.90 KB | None | 0 0
  1. /*********
  2. Rui Santos
  3. Complete project details at https://randomnerdtutorials.com
  4. *********/
  5.  
  6. #include <WiFi.h>
  7. extern "C" {
  8. #include "freertos/FreeRTOS.h"
  9. #include "freertos/timers.h"
  10. }
  11. #include <AsyncMqttClient.h>
  12. #include <LiquidCrystal_I2C.h>
  13.  
  14. // Change the credentials below, so your ESP32 connects to your router
  15. #define WIFI_SSID "REPLACE_WITH_YOUR_SSID"
  16. #define WIFI_PASSWORD "REPLACE_WITH_YOUR_PASSWORD"
  17.  
  18. // Change the MQTT_HOST variable to your Raspberry Pi IP address,
  19. // so it connects to your Mosquitto MQTT broker
  20. #define MQTT_HOST IPAddress(192, 168, 1, 4)
  21. #define MQTT_PORT 1883
  22.  
  23. // Create objects to handle MQTT client
  24. AsyncMqttClient mqttClient;
  25. TimerHandle_t mqttReconnectTimer;
  26. TimerHandle_t wifiReconnectTimer;
  27.  
  28. // Set the LCD number of columns and rows
  29. const int lcdColumns = 16;
  30. const int lcdRows = 2;
  31.  
  32. // Set LCD address, number of columns and rows
  33. // if you don't know your display address, run an I2C scanner sketch
  34. LiquidCrystal_I2C lcd(0x27, lcdColumns, lcdRows);
  35.  
  36. // Thermometer icon
  37. byte thermometerIcon[8] = {
  38. B00100,
  39. B01010,
  40. B01010,
  41. B01010,
  42. B01010,
  43. B10001,
  44. B11111,
  45. B01110
  46. };
  47.  
  48. // Define GPIO where the pushbutton is connected to
  49. const int buttonPin = 32;
  50. int buttonState; // current reading from the input pin (pushbutton)
  51. int lastButtonState = LOW; // previous reading from the input pin (pushbutton)
  52. unsigned long lastDebounceTime = 0; // the last time the output pin was toggled
  53. unsigned long debounceDelay = 50; // the debounce time; increase if the output flickers
  54.  
  55. void connectToWifi() {
  56. Serial.println("Connecting to Wi-Fi...");
  57. WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  58. }
  59.  
  60. void connectToMqtt() {
  61. Serial.println("Connecting to MQTT...");
  62. mqttClient.connect();
  63. }
  64.  
  65. void WiFiEvent(WiFiEvent_t event) {
  66. Serial.printf("[WiFi-event] event: %d\n", event);
  67. switch(event) {
  68. case SYSTEM_EVENT_STA_GOT_IP:
  69. Serial.println("WiFi connected");
  70. Serial.println("IP address: ");
  71. Serial.println(WiFi.localIP());
  72. connectToMqtt();
  73. break;
  74. case SYSTEM_EVENT_STA_DISCONNECTED:
  75. Serial.println("WiFi lost connection");
  76. xTimerStop(mqttReconnectTimer, 0); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi
  77. xTimerStart(wifiReconnectTimer, 0);
  78. break;
  79. //DAK added events below to satisfy compiler for enumerated event handler in 'switch' function.
  80. case SYSTEM_EVENT_WIFI_READY:
  81. Serial.println("WIFI Ready!");
  82. break;
  83. case SYSTEM_EVENT_SCAN_DONE:
  84. break;
  85. case SYSTEM_EVENT_STA_START:
  86. break;
  87. case SYSTEM_EVENT_STA_STOP:
  88. break;
  89. case SYSTEM_EVENT_STA_CONNECTED:
  90. break;
  91. case SYSTEM_EVENT_STA_AUTHMODE_CHANGE:
  92. Serial.println("Authmode has CHANGED!");
  93. break;
  94. case SYSTEM_EVENT_STA_LOST_IP:
  95. Serial.println("Lost the IP");
  96. break;
  97. case SYSTEM_EVENT_STA_WPS_ER_SUCCESS:
  98. break;
  99. case SYSTEM_EVENT_STA_WPS_ER_FAILED:
  100. break;
  101. case SYSTEM_EVENT_STA_WPS_ER_TIMEOUT:
  102. break;
  103. case SYSTEM_EVENT_STA_WPS_ER_PIN:
  104. break;
  105. case SYSTEM_EVENT_AP_START:
  106. break;
  107. case SYSTEM_EVENT_AP_STOP:
  108. break;
  109. case SYSTEM_EVENT_AP_STAIPASSIGNED:
  110. break;
  111. case SYSTEM_EVENT_AP_STACONNECTED:
  112. break;
  113. case SYSTEM_EVENT_AP_STADISCONNECTED:
  114. break;
  115. case SYSTEM_EVENT_AP_PROBEREQRECVED:
  116. break;
  117. case SYSTEM_EVENT_GOT_IP6:
  118. break;
  119. case SYSTEM_EVENT_ETH_START:
  120. break;
  121. case SYSTEM_EVENT_ETH_STOP:
  122. break;
  123. case SYSTEM_EVENT_ETH_CONNECTED:
  124. break;
  125. case SYSTEM_EVENT_ETH_DISCONNECTED:
  126. break;
  127. case SYSTEM_EVENT_ETH_GOT_IP:
  128. break;
  129. case SYSTEM_EVENT_MAX:
  130. break;
  131. }
  132. }
  133.  
  134. // Add more topics that want your ESP32 to be subscribed to
  135. void onMqttConnect(bool sessionPresent) {
  136. Serial.println("Connected to MQTT.");
  137. Serial.print("Session present: ");
  138. Serial.println(sessionPresent);
  139. uint16_t packetIdSub = mqttClient.subscribe("esp32/temperature", 0);
  140. Serial.print("Subscribing at QoS 0, packetId: ");
  141. Serial.println(packetIdSub);
  142. }
  143.  
  144. void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
  145. Serial.println("Disconnected from MQTT.");
  146. if (WiFi.isConnected()) {
  147. xTimerStart(mqttReconnectTimer, 0);
  148. }
  149. }
  150.  
  151. void onMqttSubscribe(uint16_t packetId, uint8_t qos) {
  152. Serial.println("Subscribe acknowledged.");
  153. Serial.print(" packetId: ");
  154. Serial.println(packetId);
  155. Serial.print(" qos: ");
  156. Serial.println(qos);
  157. }
  158.  
  159. void onMqttUnsubscribe(uint16_t packetId) {
  160. Serial.println("Unsubscribe acknowledged.");
  161. Serial.print(" packetId: ");
  162. Serial.println(packetId);
  163. }
  164.  
  165. void onMqttPublish(uint16_t packetId) {
  166. Serial.println("Publish acknowledged.");
  167. Serial.print(" packetId: ");
  168. Serial.println(packetId);
  169. }
  170.  
  171. // You can modify this function to handle what happens when you receive a certain message in a specific topic
  172. void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
  173. String messageTemp;
  174. for (int i = 0; i < len; i++) {
  175. //Serial.print((char)payload[i]);
  176. messageTemp += (char)payload[i];
  177. }
  178. if (strcmp(topic, "esp32/temperature") == 0) {
  179. lcd.clear();
  180. lcd.setCursor(1, 0);
  181. lcd.write(0);
  182. lcd.print(" Temperature");
  183. lcd.setCursor(0, 1);
  184. lcd.print(messageTemp);
  185. }
  186.  
  187. Serial.println("Publish received.");
  188. Serial.print(" message: ");
  189. Serial.println(messageTemp);
  190. Serial.print(" topic: ");
  191. Serial.println(topic);
  192. Serial.print(" qos: ");
  193. Serial.println(properties.qos);
  194. Serial.print(" dup: ");
  195. Serial.println(properties.dup);
  196. Serial.print(" retain: ");
  197. Serial.println(properties.retain);
  198. Serial.print(" len: ");
  199. Serial.println(len);
  200. Serial.print(" index: ");
  201. Serial.println(index);
  202. Serial.print(" total: ");
  203. Serial.println(total);
  204. }
  205.  
  206. void setup() {
  207. // Initialize LCD
  208. lcd.init();
  209. // Turn on LCD backlight
  210. lcd.backlight();
  211. // Create thermometer icon
  212. lcd.createChar(0, thermometerIcon);
  213.  
  214. // Define buttonPin as an INPUT
  215. pinMode(buttonPin, INPUT);
  216.  
  217. Serial.begin(115200);
  218.  
  219. mqttReconnectTimer = xTimerCreate("mqttTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast<TimerCallbackFunction_t>(connectToMqtt));
  220. wifiReconnectTimer = xTimerCreate("wifiTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast<TimerCallbackFunction_t>(connectToWifi));
  221.  
  222. WiFi.onEvent(WiFiEvent);
  223.  
  224. mqttClient.onConnect(onMqttConnect);
  225. mqttClient.onDisconnect(onMqttDisconnect);
  226. mqttClient.onSubscribe(onMqttSubscribe);
  227. mqttClient.onUnsubscribe(onMqttUnsubscribe);
  228. mqttClient.onMessage(onMqttMessage);
  229. mqttClient.onPublish(onMqttPublish);
  230. mqttClient.setServer(MQTT_HOST, MQTT_PORT);
  231.  
  232. connectToWifi();
  233. }
  234.  
  235. void loop() {
  236. // Read the state of the pushbutton and save it in a local variable
  237. int reading = digitalRead(buttonPin);
  238.  
  239. // If the pushbutton state changed (due to noise or pressing it), reset the timer
  240. if (reading != lastButtonState) {
  241. // Reset the debouncing timer
  242. lastDebounceTime = millis();
  243. }
  244.  
  245. // If the button state has changed, after the debounce time
  246. if ((millis() - lastDebounceTime) > debounceDelay) {
  247. // And if the current reading is different than the current buttonState
  248. if (reading != buttonState) {
  249. buttonState = reading;
  250. // Publish an MQTT message on topic esp32/led to toggle the LED (turn the LED on or off)P
  251. if (buttonState == HIGH) {
  252. mqttClient.publish("esp32/led", 0, true, "toggle");
  253. Serial.println("Publishing on topic esp32/led topic at QoS 0");
  254. }
  255. }
  256. }
  257. // Save the reading. Next time through the loop, it'll be the lastButtonState
  258. lastButtonState = reading;
  259. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement