ESP32 Bluetooth
How to Program the ESP32?
The ESP32 can be programmed using different firmware and
programming languages. You can use:
Arduino C/C++ using the Arduino core for the ESP32
Espressif IDF (IoT Development Framework)
Micropython
JavaScript
LUA
https://mcudude.github.io/MiniCore/package_MCUdude_MiniCore_index.json
https://dl.espressif.com/dl/package_esp32_index.json
https://www.silabs.com/developers/usb-to-uart-bridge-vcp-drivers?tab=downloads
https://github.com/earlephilhower/arduino-pico/releases/download/global/
package_rp2040_index.json
https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json
http://arduino.esp8266.com/stable/package_esp8266com_index.json
https://downloads.arduino.cc/packages/package_index.json
Installation guidance for latest arduino with board manager :
https://randomnerdtutorials.com/getting-started-with-esp32/
#include "BluetoothSerial.h"
#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;
void setup() {
Serial.begin(115200);
SerialBT.begin("ESP32test"); //Bluetooth device
name
Serial.println("The device started, now you can
pair it with bluetooth!");
}
void loop() {
if (Serial.available()) {
SerialBT.write(Serial.read());
}
if (SerialBT.available()) {
Serial.write(SerialBT.read());
}
delay(20);
}
DTH11 (Temperature Sensor)
#include "BluetoothSerial.h"
#include "DHT.h"
#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;
DHT dht;
// Define the GPIO pin for the DHT sensor and its type
#define DHT_PIN 4 // Data pin connected to ESP32 GPIO 4
#define DHT_TYPE DHT11 // Or use DHT22 for a different sensor
void setup() {
Serial.begin(115200); // For serial monitor debugging
SerialBT.begin("ESP32_DHT11"); // Bluetooth device name
Serial.println("The device started, now you can pair it !");
dht.setup(DHT_PIN, DHT_TYPE); // Initialize the DHT sensor
delay(1000); // Wait for the sensor to initialize
}
void loop() {
// Read humidity and temperature
float humidity = dht.getHumidity();
float temperature = dht.getTemperature();
// Check if reading was successful
if (isnan(humidity) || isnan(temperature)) {
Serial.println("Failed to read from DHT sensor!");
SerialBT.println("Failed to read from DHT sensor!");
delay(2000);
return;
}
// Prepare the data string
String dataString = "Humidity: " + String(humidity, 1) + " % | Temperature: " + String(temperature, 1)
+ " C";
// Print to Serial Monitor
Serial.println(dataString);
// Send to Bluetooth connected device
SerialBT.println(dataString);
delay(5000); // Wait 5 seconds before reading again
}
Dth11 sensor with web page
#include <WiFi.h>
#include <WebServer.h>
#include "DHT.h"
// Uncomment one of the lines below for whatever DHT sensor type you're using!
//#define DHTTYPE DHT11 // DHT 11
//#define DHTTYPE DHT21 // DHT 21 (AM2301)
#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
/*Put your SSID & Password*/
const char* ssid = "YourNetworkName"; // Enter SSID here
const char* password = "YourPassword"; //Enter Password here
WebServer server(80);
// DHT Sensor
uint8_t DHTPin = 4;
// Initialize DHT sensor.
DHT dht(DHTPin, DHTTYPE);
float Temperature;
float Humidity;
void setup() {
Serial.begin(115200);
delay(100);
pinMode(DHTPin, INPUT);
dht.begin();
Serial.println("Connecting to ");
Serial.println(ssid);
//connect to your local wi-fi network
WiFi.begin(ssid, password);
//check wi-fi is connected to wi-fi network
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected..!");
Serial.print("Got IP: "); Serial.println(WiFi.localIP());
server.on("/", handle_OnConnect);
server.onNotFound(handle_NotFound);
server.begin();
Serial.println("HTTP server started");
}
void loop() {
server.handleClient();
void handle_OnConnect() {
Temperature = dht.readTemperature(); // Gets the values of the temperature
Humidity = dht.readHumidity(); // Gets the values of the humidity
server.send(200, "text/html", SendHTML(Temperature,Humidity));
}
void handle_NotFound(){
server.send(404, "text/plain", "Not found");
}
String SendHTML(float Temperaturestat,float Humiditystat){
String ptr = "<!DOCTYPE html> <html>\n";
ptr +="<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-
scalable=no\">\n";
ptr +="<title>ESP32 Weather Report</title>\n";
ptr +="<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align:
center;}\n";
ptr +="body{margin-top: 50px;} h1 {color: #444444;margin: 50px auto 30px;}\n";
ptr +="p {font-size: 24px;color: #444444;margin-bottom: 10px;}\n";
ptr +="</style>\n";
ptr +="</head>\n";
ptr +="<body>\n";
ptr +="<div id=\"webpage\">\n";
ptr +="<h1>ESP32 Weather Report</h1>\n";
ptr +="<p>Temperature: ";
ptr +=(int)Temperaturestat;
ptr +="°C</p>";
ptr +="<p>Humidity: ";
ptr +=(int)Humiditystat;
ptr +="%</p>";
ptr +="</div>\n";
ptr +="</body>\n";
ptr +="</html>\n";
return ptr;
}
Ultrasonic sensor with Bluetooth code:
#include <BluetoothSerial.h> // Include the BluetoothSerial library
// Ensure Bluetooth is enabled
#if ! defined(CONFIG_BT_ENABLED) || ! defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to enable it.
#endif
BluetoothSerial SerialBT; // Create a Bluetooth serial object
// Pin definitions for the ultrasonic sensor
const int trigPin = 18; // Trigger pin for the sensor
const int echoPin = 19; // Echo pin for the sensor
// Variables for distance measurement
long duration; // Stores the duration of the echo pulse
int distanceCM; // Stores the distance in centimeters
void setup() {
Serial.begin(115200); // Initialize serial communication for debugging
SerialBT.begin("ESP32_Distance"); // Initialize Bluetooth with a device name "ESP32_Distance"
pinMode(trigPin, OUTPUT); // Set the trigger pin as an output
pinMode(echoPin, INPUT); // Set the echo pin as an input
Serial.println("Bluetooth Device Started. Send commands to control the sensor!");
}
void loop() {
// --- Ultrasonic Sensor Measurement ---
// Clear the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Send a 10 microsecond pulse to trigger the sensor
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the duration of the pulse from the echo pin
duration = pulseIn(echoPin, HIGH, 25000); // Timeout in microseconds
// Calculate the distance in centimeters
// Speed of sound = 343 m/s, which is 0.0343 cm/µs.
// distance = (duration * speed of sound) / 2 (for round trip)
distanceCM = duration * 0.0343 / 2;
// --- Bluetooth Communication ---
// Send the distance to the connected Bluetooth device
String distanceString = String(distanceCM) + " cm";
SerialBT.println(distanceString);
Serial.println("Sent: " + distanceString); // Print to Serial Monitor for debugging
delay(1000); // Wait for 1 second before the next reading
}