#include "BluetoothSerial.h" // For Bluetooth Serial functionality
#include "DHT.h" // For the DHT sensor
// This checks if Bluetooth is enabled in the ESP32's configuration.
// It's a good practice check, though Wokwi usually handles this.
#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif
BluetoothSerial SerialBT; // Create an object for Bluetooth Serial
// --- DHT Sensor Pin Definition ---
#define DHTPIN 4 // GPIO pin where the DHT22 data pin is connected.
// This corresponds to pin '4' (or 'D4') on your ESP32 board.
#define DHTTYPE DHT22 // Specify the type of DHT sensor (DHT22 or DHT11)
DHT dht(DHTPIN, DHTTYPE); // Initialize the DHT sensor object
void setup() {
Serial.begin(115200); // Start serial communication for debugging (visible in Wokwi Serial Monitor)
// Start Bluetooth Serial with a device name.
// This name will be visible when scanning for Bluetooth devices on your smartphone.
SerialBT.begin("ESP32_DHT22_Sensor");
Serial.println("Bluetooth device started under the name: ESP32_DHT22_Sensor");
Serial.println("Ready to pair with a Bluetooth Serial Terminal app on your phone.");
dht.begin(); // Initialize the DHT sensor
Serial.println("DHT22 sensor initialized.");
}
void loop() {
// Read temperature and humidity from the DHT22 sensor
float humidity = dht.readHumidity();
float temperature = dht.readTemperature(); // Reads temperature in Celsius by default
// float temperatureF = dht.readTemperature(true); // Uncomment to read in Fahrenheit
// Check if the sensor readings are valid (isnan stands for "is not a number")
if (isnan(humidity) || isnan(temperature)) {
String errorMsg = "Failed to read from DHT sensor!";
Serial.println(errorMsg);
// You could also send an error message over Bluetooth if desired
// SerialBT.println(errorMsg);
} else {
// Format the sensor data into a string
// String(value, decimalPlaces) formats a float to a string with specified decimal places.
String dataString = "Temp: " + String(temperature, 1) + "°C, Hum: " + String(humidity, 0) + "%";
// Print the data to the Wokwi Serial Monitor for debugging
Serial.print("Sending data via Bluetooth: ");
Serial.println(dataString);
// Send the data string over Bluetooth Serial
SerialBT.println(dataString);
}
// Wait for a few seconds before sending the next reading
delay(5000); // Sends data every 5 seconds (5000 milliseconds). Adjust as needed.
}