Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /********* Pleasedontcode.com **********
- Pleasedontcode thanks you for automatic code generation! Enjoy your code!
- - Terms and Conditions:
- You have a non-exclusive, revocable, worldwide, royalty-free license
- for personal and commercial use. Attribution is optional; modifications
- are allowed, but you're responsible for code maintenance. We're not
- liable for any loss or damage. For full terms,
- please visit pleasedontcode.com/termsandconditions.
- - Project: Sensor Publisher
- - Source Code NOT compiled for: Arduino Nano ESP32
- - Source Code created on: 2025-08-04 13:43:02
- ********* Pleasedontcode.com **********/
- /****** SYSTEM REQUIREMENTS *****/
- /****** SYSTEM REQUIREMENT 1 *****/
- /* Publicar las variables de temperatura y humedad en */
- /* formato JSON mediante MQTT, usando la librerÃa DHT */
- /* y el pin D2 del Arduino Nano ESP32. */
- /****** SYSTEM REQUIREMENT 2 *****/
- /* Ensure MQTT publishes temperature and humidity in */
- /* JSON format using the DHT sensor on pin D2 of the */
- /* Arduino Nano ESP32, with WiFi connectivity for */
- /* real-time data transmission. */
- /****** END SYSTEM REQUIREMENTS *****/
- /* START CODE */
- /****** DEFINITION OF LIBRARIES *****/
- #include <DHT.h> // https://github.com/adafruit/DHT-sensor-library
- #include <WiFi.h> // WiFi library for ESP32
- #include <PubSubClient.h> // MQTT client library
- /****** FUNCTION PROTOTYPES *****/
- void setup(void);
- void loop(void);
- void reconnectMQTT(void);
- void publishSensorData(void);
- /***** DEFINITION OF DIGITAL INPUT PINS *****/
- const uint8_t TempHum_DHT22_DOUT_PIN_D2 = 2;
- /****** DEFINITION OF LIBRARIES CLASS INSTANCES*****/
- DHT dht(TempHum_DHT22_DOUT_PIN_D2, DHT22);
- // WiFi credentials
- const char* ssid = "your_SSID"; // Replace with your WiFi SSID
- const char* password = "your_PASSWORD"; // Replace with your WiFi password
- // MQTT broker details
- const char* mqtt_server = "broker.hivemq.com"; // Replace with your MQTT broker address
- const int mqtt_port = 1883; // MQTT port
- const char* mqtt_topic = "sensor/temperature_humidity"; // MQTT topic
- WiFiClient espClient;
- PubSubClient client(espClient);
- unsigned long lastPublishTime = 0;
- const unsigned long publishInterval = 5000; // Publish every 5 seconds
- void setup(void)
- {
- // Initialize serial communication
- Serial.begin(9600);
- // Initialize DHT sensor
- dht.begin();
- // Configure WiFi connection
- WiFi.begin(ssid, password);
- Serial.print("Connecting to WiFi");
- while (WiFi.status() != WL_CONNECTED)
- {
- delay(500);
- Serial.print(".");
- }
- Serial.println("\nWiFi connected");
- // Configure MQTT server
- client.setServer(mqtt_server, mqtt_port);
- }
- void loop(void)
- {
- if (!client.connected())
- {
- reconnectMQTT();
- }
- client.loop();
- unsigned long currentMillis = millis();
- if (currentMillis - lastPublishTime >= publishInterval)
- {
- lastPublishTime = currentMillis;
- publishSensorData();
- }
- }
- void reconnectMQTT()
- {
- // Loop until reconnected
- while (!client.connected())
- {
- Serial.print("Attempting MQTT connection...");
- // Create a client ID
- String clientId = "ESP32Client-";
- clientId += String(random(0xffff), HEX);
- // Attempt to connect
- if (client.connect(clientId.c_str()))
- {
- Serial.println("connected");
- }
- else
- {
- Serial.print("failed, rc=");
- Serial.print(client.state());
- Serial.println(" try again in 5 seconds");
- delay(5000);
- }
- }
- }
- void publishSensorData()
- {
- // Read temperature and humidity
- float humidity = dht.readHumidity();
- float temperature = dht.readTemperature();
- // Check if reads are valid
- if (isnan(humidity) || isnan(temperature))
- {
- Serial.println("Failed to read from DHT sensor");
- return;
- }
- // Create JSON payload
- String payload = "{";
- payload += "\"temperature\": " + String(temperature, 2) + ",";
- payload += "\"humidity\": " + String(humidity, 2);
- payload += "}";
- // Publish JSON payload
- if (client.publish(mqtt_topic, payload.c_str()))
- {
- Serial.println("Published data: " + payload);
- }
- else
- {
- Serial.println("Failed to publish data");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment