pleasedontcode

Sensor Publisher rev_03

Aug 4th, 2025
649
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /********* Pleasedontcode.com **********
  2.  
  3.     Pleasedontcode thanks you for automatic code generation! Enjoy your code!
  4.  
  5.     - Terms and Conditions:
  6.     You have a non-exclusive, revocable, worldwide, royalty-free license
  7.     for personal and commercial use. Attribution is optional; modifications
  8.     are allowed, but you're responsible for code maintenance. We're not
  9.     liable for any loss or damage. For full terms,
  10.     please visit pleasedontcode.com/termsandconditions.
  11.  
  12.     - Project: Sensor Publisher
  13.     - Source Code NOT compiled for: Arduino Nano ESP32
  14.     - Source Code created on: 2025-08-04 13:43:02
  15.  
  16. ********* Pleasedontcode.com **********/
  17.  
  18. /****** SYSTEM REQUIREMENTS *****/
  19. /****** SYSTEM REQUIREMENT 1 *****/
  20.     /* Publicar las variables de temperatura y humedad en */
  21.     /* formato JSON mediante MQTT, usando la librería DHT */
  22.     /* y el pin D2 del Arduino Nano ESP32. */
  23. /****** SYSTEM REQUIREMENT 2 *****/
  24.     /* Ensure MQTT publishes temperature and humidity in */
  25.     /* JSON format using the DHT sensor on pin D2 of the */
  26.     /* Arduino Nano ESP32, with WiFi connectivity for */
  27.     /* real-time data transmission. */
  28. /****** END SYSTEM REQUIREMENTS *****/
  29.  
  30. /* START CODE */
  31. /****** DEFINITION OF LIBRARIES *****/
  32. #include <DHT.h>                 // https://github.com/adafruit/DHT-sensor-library
  33. #include <WiFi.h>                // WiFi library for ESP32
  34. #include <PubSubClient.h>        // MQTT client library
  35.  
  36. /****** FUNCTION PROTOTYPES *****/
  37. void setup(void);
  38. void loop(void);
  39. void reconnectMQTT(void);
  40. void publishSensorData(void);
  41.  
  42. /***** DEFINITION OF DIGITAL INPUT PINS *****/
  43. const uint8_t TempHum_DHT22_DOUT_PIN_D2 = 2;
  44.  
  45. /****** DEFINITION OF LIBRARIES CLASS INSTANCES*****/
  46. DHT dht(TempHum_DHT22_DOUT_PIN_D2, DHT22);
  47.  
  48. // WiFi credentials
  49. const char* ssid = "your_SSID";             // Replace with your WiFi SSID
  50. const char* password = "your_PASSWORD";     // Replace with your WiFi password
  51.  
  52. // MQTT broker details
  53. const char* mqtt_server = "broker.hivemq.com"; // Replace with your MQTT broker address
  54. const int mqtt_port = 1883;                     // MQTT port
  55. const char* mqtt_topic = "sensor/temperature_humidity"; // MQTT topic
  56.  
  57. WiFiClient espClient;
  58. PubSubClient client(espClient);
  59.  
  60. unsigned long lastPublishTime = 0;
  61. const unsigned long publishInterval = 5000; // Publish every 5 seconds
  62.  
  63. void setup(void)
  64. {
  65.   // Initialize serial communication
  66.   Serial.begin(9600);
  67.  
  68.   // Initialize DHT sensor
  69.   dht.begin();
  70.  
  71.   // Configure WiFi connection
  72.   WiFi.begin(ssid, password);
  73.   Serial.print("Connecting to WiFi");
  74.   while (WiFi.status() != WL_CONNECTED)
  75.   {
  76.     delay(500);
  77.     Serial.print(".");
  78.   }
  79.   Serial.println("\nWiFi connected");
  80.  
  81.   // Configure MQTT server
  82.   client.setServer(mqtt_server, mqtt_port);
  83. }
  84.  
  85. void loop(void)
  86. {
  87.   if (!client.connected())
  88.   {
  89.     reconnectMQTT();
  90.   }
  91.   client.loop();
  92.  
  93.   unsigned long currentMillis = millis();
  94.   if (currentMillis - lastPublishTime >= publishInterval)
  95.   {
  96.     lastPublishTime = currentMillis;
  97.     publishSensorData();
  98.   }
  99. }
  100.  
  101. void reconnectMQTT()
  102. {
  103.   // Loop until reconnected
  104.   while (!client.connected())
  105.   {
  106.     Serial.print("Attempting MQTT connection...");
  107.     // Create a client ID
  108.     String clientId = "ESP32Client-";
  109.     clientId += String(random(0xffff), HEX);
  110.     // Attempt to connect
  111.     if (client.connect(clientId.c_str()))
  112.     {
  113.       Serial.println("connected");
  114.     }
  115.     else
  116.     {
  117.       Serial.print("failed, rc=");
  118.       Serial.print(client.state());
  119.       Serial.println(" try again in 5 seconds");
  120.       delay(5000);
  121.     }
  122.   }
  123. }
  124.  
  125. void publishSensorData()
  126. {
  127.   // Read temperature and humidity
  128.   float humidity = dht.readHumidity();
  129.   float temperature = dht.readTemperature();
  130.  
  131.   // Check if reads are valid
  132.   if (isnan(humidity) || isnan(temperature))
  133.   {
  134.     Serial.println("Failed to read from DHT sensor");
  135.     return;
  136.   }
  137.  
  138.   // Create JSON payload
  139.   String payload = "{";
  140.   payload += "\"temperature\": " + String(temperature, 2) + ",";
  141.   payload += "\"humidity\": " + String(humidity, 2);
  142.   payload += "}";
  143.  
  144.   // Publish JSON payload
  145.   if (client.publish(mqtt_topic, payload.c_str()))
  146.   {
  147.     Serial.println("Published data: " + payload);
  148.   }
  149.   else
  150.   {
  151.     Serial.println("Failed to publish data");
  152.   }
  153. }
  154.  
Advertisement
Add Comment
Please, Sign In to add comment