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:33:56
- ********* 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. */
- /****** END SYSTEM REQUIREMENTS *****/
- /* START CODE */
- /****** DEFINITION OF LIBRARIES *****/
- #include <DHT.h> // https://github.com/adafruit/DHT-sensor-library
- /****** FUNCTION PROTOTYPES *****/
- void setup(void);
- void loop(void);
- void publishSensorData(float temperature, float humidity);
- /***** 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);
- // Placeholder for MQTT client object
- // Include your MQTT client library and instantiate the client here
- // For example:
- // #include <PubSubClient.h>
- // WiFiClient espClient;
- // PubSubClient mqttClient(espClient);
- void setup(void)
- {
- // put your setup code here, to run once:
- pinMode(TempHum_DHT22_DOUT_PIN_D2, INPUT_PULLUP);
- dht.begin();
- // Initialize MQTT connection here
- // For example:
- // mqttClient.setServer(mqtt_server, mqtt_port);
- // connectMQTT();
- }
- void loop(void)
- {
- // put your main code here, to run repeatedly:
- // Read temperature and humidity
- float temperature = dht.readTemperature(); // Celsius
- float humidity = dht.readHumidity();
- // Check if any reads failed and handle errors
- if (isnan(temperature) || isnan(humidity)) {
- // Handle sensor read error
- return;
- }
- // Publish sensor data in JSON format
- publishSensorData(temperature, humidity);
- // Delay between readings, e.g., 2 seconds
- delay(2000);
- }
- void publishSensorData(float temperature, float humidity)
- {
- // Format JSON string
- char jsonBuffer[128];
- snprintf(jsonBuffer, sizeof(jsonBuffer), "{\"temperature\":%.2f,\"humidity\":%.2f}", temperature, humidity);
- // Publish via MQTT
- // Replace 'mqttClient' with your MQTT client object
- // Example:
- // if (mqttClient.connected()) {
- // mqttClient.publish("sensor/data", jsonBuffer);
- // }
- // For this example, we'll just print to Serial
- Serial.println(jsonBuffer);
- }
Advertisement
Add Comment
Please, Sign In to add comment