Advertisement
fabelizer

ESP32_Client_1_LED_DS18B20 Code

Feb 12th, 2019
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.29 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 <OneWire.h>
  13. #include <DallasTemperature.h>
  14.  
  15. // Change the credentials below, so your ESP32 connects to your router
  16. #define WIFI_SSID "REPLACE_WITH_YOUR_SSID"
  17. #define WIFI_PASSWORD "REPLACE_WITH_YOUR_PASSWORD"
  18.  
  19. // Change the MQTT_HOST variable to your Raspberry Pi IP address,
  20. // so it connects to your Mosquitto MQTT broker
  21. #define MQTT_HOST IPAddress(192, 168, 1, XXX)
  22. #define MQTT_PORT 1883
  23.  
  24. // Create objects to handle MQTT client
  25. AsyncMqttClient mqttClient;
  26. TimerHandle_t mqttReconnectTimer;
  27. TimerHandle_t wifiReconnectTimer;
  28.  
  29. String temperatureString = ""; // Variable to hold the temperature reading
  30. unsigned long previousMillis = 0; // Stores last time temperature was published
  31. const long interval = 5000; // interval at which to publish sensor readings
  32.  
  33. const int ledPin = 25; // GPIO where the LED is connected to
  34. int ledState = LOW; // the current state of the output pin
  35.  
  36. // GPIO where the DS18B20 is connected to
  37. const int oneWireBus = 32;
  38. // Setup a oneWire instance to communicate with any OneWire devices
  39. OneWire oneWire(oneWireBus);
  40. // Pass our oneWire reference to Dallas Temperature sensor
  41. DallasTemperature sensors(&oneWire);
  42.  
  43. void connectToWifi() {
  44. Serial.println("Connecting to Wi-Fi...");
  45. WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  46. }
  47.  
  48. void connectToMqtt() {
  49. Serial.println("Connecting to MQTT...");
  50. mqttClient.connect();
  51. }
  52.  
  53. void WiFiEvent(WiFiEvent_t event) {
  54. Serial.printf("[WiFi-event] event: %d\n", event);
  55. switch(event) {
  56. case SYSTEM_EVENT_STA_GOT_IP:
  57. Serial.println("WiFi connected");
  58. Serial.println("IP address: ");
  59. Serial.println(WiFi.localIP());
  60. connectToMqtt();
  61. break;
  62. case SYSTEM_EVENT_STA_DISCONNECTED:
  63. Serial.println("WiFi lost connection");
  64. xTimerStop(mqttReconnectTimer, 0); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi
  65. xTimerStart(wifiReconnectTimer, 0);
  66. break;
  67. }
  68. }
  69.  
  70. // Add more topics that want your ESP32 to be subscribed to
  71. void onMqttConnect(bool sessionPresent) {
  72. Serial.println("Connected to MQTT.");
  73. Serial.print("Session present: ");
  74. Serial.println(sessionPresent);
  75. // ESP32 subscribed to esp32/led topic
  76. uint16_t packetIdSub = mqttClient.subscribe("esp32/led", 0);
  77. Serial.print("Subscribing at QoS 0, packetId: ");
  78. Serial.println(packetIdSub);
  79. }
  80.  
  81. void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
  82. Serial.println("Disconnected from MQTT.");
  83. if (WiFi.isConnected()) {
  84. xTimerStart(mqttReconnectTimer, 0);
  85. }
  86. }
  87.  
  88. void onMqttSubscribe(uint16_t packetId, uint8_t qos) {
  89. Serial.println("Subscribe acknowledged.");
  90. Serial.print(" packetId: ");
  91. Serial.println(packetId);
  92. Serial.print(" qos: ");
  93. Serial.println(qos);
  94. }
  95.  
  96. void onMqttUnsubscribe(uint16_t packetId) {
  97. Serial.println("Unsubscribe acknowledged.");
  98. Serial.print(" packetId: ");
  99. Serial.println(packetId);
  100. }
  101.  
  102. void onMqttPublish(uint16_t packetId) {
  103. Serial.println("Publish acknowledged.");
  104. Serial.print(" packetId: ");
  105. Serial.println(packetId);
  106. }
  107.  
  108. // You can modify this function to handle what happens when you receive a certain message in a specific topic
  109. void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
  110. String messageTemp;
  111. for (int i = 0; i < len; i++) {
  112. //Serial.print((char)payload[i]);
  113. messageTemp += (char)payload[i];
  114. }
  115. // Check if the MQTT message was received on topic esp32/led
  116. if (strcmp(topic, "esp32/led") == 0) {
  117. // If the LED is off turn it on (and vice-versa)
  118. if (ledState == LOW) {
  119. ledState = HIGH;
  120. } else {
  121. ledState = LOW;
  122. }
  123. // Set the LED with the ledState of the variable
  124. digitalWrite(ledPin, ledState);
  125. }
  126.  
  127. Serial.println("Publish received.");
  128. Serial.print(" message: ");
  129. Serial.println(messageTemp);
  130. Serial.print(" topic: ");
  131. Serial.println(topic);
  132. Serial.print(" qos: ");
  133. Serial.println(properties.qos);
  134. Serial.print(" dup: ");
  135. Serial.println(properties.dup);
  136. Serial.print(" retain: ");
  137. Serial.println(properties.retain);
  138. Serial.print(" len: ");
  139. Serial.println(len);
  140. Serial.print(" index: ");
  141. Serial.println(index);
  142. Serial.print(" total: ");
  143. Serial.println(total);
  144. }
  145.  
  146. void setup() {
  147. // Start the DS18B20 sensor
  148. sensors.begin();
  149. // Define LED as an OUTPUT and set it LOW
  150. pinMode(ledPin, OUTPUT);
  151. digitalWrite(ledPin, LOW);
  152.  
  153. Serial.begin(115200);
  154.  
  155. mqttReconnectTimer = xTimerCreate("mqttTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast<TimerCallbackFunction_t>(connectToMqtt));
  156. wifiReconnectTimer = xTimerCreate("wifiTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast<TimerCallbackFunction_t>(connectToWifi));
  157.  
  158. WiFi.onEvent(WiFiEvent);
  159.  
  160. mqttClient.onConnect(onMqttConnect);
  161. mqttClient.onDisconnect(onMqttDisconnect);
  162. mqttClient.onSubscribe(onMqttSubscribe);
  163. mqttClient.onUnsubscribe(onMqttUnsubscribe);
  164. mqttClient.onMessage(onMqttMessage);
  165. mqttClient.onPublish(onMqttPublish);
  166. mqttClient.setServer(MQTT_HOST, MQTT_PORT);
  167.  
  168. connectToWifi();
  169. }
  170.  
  171. void loop() {
  172. unsigned long currentMillis = millis();
  173. // Every X number of seconds (interval = 5 seconds)
  174. // it publishes a new MQTT message on topic esp32/temperature
  175. if (currentMillis - previousMillis >= interval) {
  176. // Save the last time a new reading was published
  177. previousMillis = currentMillis;
  178. // New temperature readings
  179. sensors.requestTemperatures();
  180. temperatureString = " " + String(sensors.getTempCByIndex(0)) + "C " +
  181. String(sensors.getTempFByIndex(0)) + "F";
  182. Serial.println(temperatureString);
  183. // Publish an MQTT message on topic esp32/temperature with Celsius and Fahrenheit temperature readings
  184. uint16_t packetIdPub2 = mqttClient.publish("esp32/temperature", 2, true, temperatureString.c_str());
  185. Serial.print("Publishing on topic esp32/temperature at QoS 2, packetId: ");
  186. Serial.println(packetIdPub2);
  187. }
  188. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement