Jump to content

ESP32 Bluetooth: Difference between revisions

From cognifront
CogWikiEditor (talk | contribs)
Created page with "===Interfacing LDR with ESP32 and Transmitting Sensor Data using Bluetooth=== '''Interfacing LDR with ESP32 and Transmitting Sensor Data using Bluetooth''' demonstrates how an LDR sensor can be interfaced with an ESP32 board to measure light intensity and transmit the sensor value wirelessly using Bluetooth. The ESP32 reads the analog value from the LDR and sends the value through Bluetooth to a paired device. <center> '''LDR → ESP32 → Bluetooth → Paired Device'..."
 
CogWikiEditor (talk | contribs)
 
(11 intermediate revisions by the same user not shown)
Line 1: Line 1:
===Interfacing LDR with ESP32 and Transmitting Sensor Data using Bluetooth===
===ESP32 Bluetooth Communication===


'''Interfacing LDR with ESP32 and Transmitting Sensor Data using Bluetooth''' demonstrates how an LDR sensor can be interfaced with an ESP32 board to measure light intensity and transmit the sensor value wirelessly using Bluetooth.
'''ESP32 Bluetooth Communication''' demonstrates how the built-in Bluetooth functionality of the ESP32 can be used for wireless communication between the ESP32 board and a Bluetooth-enabled device such as a smartphone, tablet, or computer.


The ESP32 reads the analog value from the LDR and sends the value through Bluetooth to a paired device.
The ESP32 can send and receive data wirelessly using Bluetooth without requiring a physical serial connection.


<center>
<center>
'''LDR → ESP32 → Bluetooth → Paired Device'''
'''Bluetooth Device → Wireless Communication → ESP32'''
</center>
</center>


== Objectives ==
== Objectives ==


* To study the working of the LDR sensor.
* To study the Bluetooth functionality available in the ESP32.
* To interface the LDR sensor with the ESP32 board.
* To understand how to initialize Bluetooth communication.
* To read the analog value from the LDR.
* To pair the ESP32 with a Bluetooth-enabled device.
* To display the LDR value on the Serial Monitor.
* To send data from the ESP32 to a Bluetooth device.
* To transmit the LDR sensor value using Bluetooth.
* To receive commands or data from a Bluetooth device.
* To control ESP32 peripherals using Bluetooth commands.


== Software ==
== Software ==


* Arduino IDE
* Arduino IDE
* ESP32 Board Package
* ESP32 board package
* BluetoothSerial Library
* Bluetooth-enabled smartphone, tablet, or computer


== Hardware Modules ==
== Hardware Modules ==


* ESP32 Board
* ESP32 Development Board
* LDR Sensor Module
* PC / Laptop
* PC / Laptop
* Bluetooth-enabled device
* Smartphone / Bluetooth-enabled device
* Connecting wires
* External sensors or actuators as required


== Theory ==
== Theory ==


=== Introduction to LDR ===
'''Bluetooth''' is a wireless communication technology used for exchanging data between electronic devices over short distances.


'''LDR''' stands for '''Light Dependent Resistor'''.
The ESP32 contains built-in Bluetooth hardware, allowing it to communicate with compatible Bluetooth devices without requiring an external Bluetooth module.


An LDR is a light-sensitive resistor whose resistance changes according to the intensity of light falling on its surface.
The ESP32 can be programmed to operate as a Bluetooth device with a user-defined device name.
 
The LDR works on the principle of '''Photo-Conductivity'''.
 
As the intensity of light increases, the resistance of the LDR decreases.
 
Similarly, as the intensity of light decreases, the resistance of the LDR increases.


<center>
<center>
'''More Light → Lower LDR Resistance'''
'''ESP32 Bluetooth → Wireless Data Transmission → Smartphone / PC'''
</center>
</center>


<center>
Bluetooth communication can be used for:
'''Less Light → Higher LDR Resistance'''
 
</center>
* Sending sensor readings
* Receiving control commands
* Controlling LEDs
* Controlling buzzers
* Monitoring system status
* Sending data to a mobile application
* Wireless serial communication


The change in resistance can be converted into a corresponding voltage using an LDR sensor circuit or module.
== ESP32 Bluetooth ==


== LDR as an Analog Sensor ==
The ESP32 provides built-in Bluetooth functionality.


The LDR is an '''analog sensor''' because its output changes continuously according to the intensity of light.
For Bluetooth Classic communication in the Arduino environment, the '''BluetoothSerial''' library can be used.


The ESP32 reads the analog voltage using an analog input pin.
The library provides a serial-like interface for sending and receiving data wirelessly.


In this practical, the LDR is connected to:
The basic sequence is:


<center>
<center>
'''ESP32 GPIO 35'''
'''Initialize Bluetooth → Set Device Name → Pair Device → Send/Receive Data'''
</center>
</center>


The analog value is read using the '''analogRead()''' function.
== BluetoothSerial Library ==
 
The '''BluetoothSerial''' library provides functions for Bluetooth Classic communication.
 
The library is included using:
 
<pre>
#include "BluetoothSerial.h"
</pre>
 
A Bluetooth serial object is then created:


<pre>
<pre>
ldrVal = analogRead(ldrPin);
BluetoothSerial SerialBT;
</pre>
</pre>


The sensor reading is stored in the variable '''ldrVal'''.
Bluetooth communication is started using:


== Connections ==
<pre>
SerialBT.begin("ESP32_Demo");
</pre>


{| class="wikitable"
Here, '''ESP32_Demo''' is the Bluetooth device name that appears when searching for the ESP32 from another Bluetooth device.
! Device
! Pin
! ESP32
! Function
|-
| LDR Module
| Data / Output
| GPIO 35
| Analog sensor input
|-
| LDR Module
| VCC
| 3.3V
| Power supply
|-
| LDR Module
| GND
| GND
| Ground
|}


== Bluetooth Communication ==
== Bluetooth Communication ==


The ESP32 has built-in Bluetooth functionality.
Bluetooth communication works in two directions.


The program uses the '''BluetoothSerial''' library to establish Bluetooth Serial communication.
=== Sending Data ===


The following library is included:
The ESP32 can send data to a connected Bluetooth device using:


<pre>
<pre>
#include "BluetoothSerial.h"
SerialBT.print("Hello");
SerialBT.println("ESP32");
</pre>
</pre>


A Bluetooth Serial object is created using:
The '''print()''' function sends data without automatically adding a new line.
 
The '''println()''' function sends data followed by a new line.
 
<center>
'''ESP32 → Bluetooth → Smartphone / PC'''
</center>
 
=== Receiving Data ===
 
The ESP32 can check whether data has been received using:


<pre>
<pre>
BluetoothSerial BT;
SerialBT.available()
</pre>
</pre>


The Bluetooth device is initialized with the name:
Received characters can be read using:


<pre>
<pre>
BT.begin("Sush");
char c = SerialBT.read();
</pre>
</pre>


Therefore, the ESP32 Bluetooth device appears as:
The received characters can then be processed as commands or sensor-control instructions.


<center>
<center>
'''Sush'''
'''Smartphone / PC → Bluetooth → ESP32'''
</center>
</center>


on a device used for Bluetooth pairing.
== Bluetooth Device Name ==


== Bluetooth Data Transmission ==
The ESP32 Bluetooth device name can be specified while starting Bluetooth.


After reading the LDR sensor value, the program converts the value into a character array before transmitting it.
Example:
 
The sensor value is first converted into a '''String''':


<pre>
<pre>
s = String (ldrVal);
SerialBT.begin("ESP32_Demo");
</pre>
</pre>


The String is then converted into a character array:
After Bluetooth is started, the device appears as:


<pre>
'''ESP32_Demo'''
s.toCharArray(msg, 30);
</pre>


The value is transmitted through Bluetooth using:
on the Bluetooth device used for pairing.


<pre>
The name can be changed as required.
BT.print("LDR Val: ");
BT.println(msg);
</pre>


The transmitted data appears in the following format:
For example:


<pre>
<pre>
LDR Val: 1234
SerialBT.begin("MyESP32");
</pre>
</pre>


== Serial Monitor Output ==
== Connections ==


The LDR value is also displayed on the Serial Monitor using:
Bluetooth communication itself does not require external communication wires between the ESP32 and the smartphone or computer.


<pre>
{| class="wikitable"
Serial.println(msg);
! Device
</pre>
! Connection
! Function
|-
| ESP32
| Built-in Bluetooth
| Wireless communication
|-
| Smartphone / PC
| Bluetooth
| Wireless communication
|}
 
External sensors and actuators can be connected to the ESP32 separately depending on the application.


The Serial Monitor is configured at:
== Basic Bluetooth Communication Flow ==


<pre>
The Bluetooth communication process can be summarized as:
Serial.begin(9600);
</pre>


Therefore, the Serial Monitor baud rate should be set to '''9600'''.
# Start the Arduino IDE.
# Include the '''BluetoothSerial''' library.
# Create a Bluetooth serial object.
# Start Bluetooth using '''SerialBT.begin()'''.
# Assign a name to the ESP32 Bluetooth device.
# Search for the ESP32 using a Bluetooth-enabled device.
# Pair/connect the device with the ESP32.
# Send data from the ESP32 using '''SerialBT.print()''' or '''SerialBT.println()'''.
# Check for incoming data using '''SerialBT.available()'''.
# Read incoming data using '''SerialBT.read()'''.
# Process the received data according to the application.


== Algorithm ==
== Algorithm ==
The following algorithm is used to interface the LDR with the ESP32 and transmit its value using Bluetooth:


# Start the Arduino IDE.
# Start the Arduino IDE.
# Include the '''BluetoothSerial''' library.
# Include the '''BluetoothSerial''' library.
# Include the required sensor library definitions.
# Create a '''BluetoothSerial''' object.
# Declare GPIO 35 as the LDR input pin.
# Start Bluetooth communication with a suitable device name.
# Declare variables to store the LDR value and transmitted data.
# Display the Bluetooth status on the Serial Monitor.
# Create a Bluetooth Serial object.
# Wait for a Bluetooth device to connect.
# In the '''void setup()''' function, start Serial communication at '''9600 baud'''.
# Check whether data is available from the Bluetooth device.
# Start Bluetooth with the device name '''Sush'''.
# Read the received data.
# Configure GPIO 35 as an '''INPUT'''.
# Process the received command or data.
# In the '''void loop()''' function, read the LDR value using '''analogRead()'''.
# Send a response using Bluetooth.
# Convert the LDR value into a String.
# Convert the String into a character array.
# Transmit the LDR value through Bluetooth.
# Display the LDR value on the Serial Monitor.
# Wait for '''300 ms'''.
# Repeat the process continuously.
# Repeat the process continuously.
The overall operation is:


<center>
<center>
'''LDR → Analog Reading → ESP32 → Bluetooth → LDR Value'''
'''Start → Initialize Bluetooth → Connect Device → Send/Receive Data → Process Data → Repeat'''
</center>
</center>


== Working ==
== Working ==


The ESP32 reads the analog output of the LDR through '''GPIO 35'''.
When the ESP32 program starts, the Bluetooth interface is initialized using the '''BluetoothSerial''' library.
 
The ESP32 becomes discoverable using the Bluetooth device name specified in the program.
 
After pairing or connecting a smartphone or computer, data can be exchanged wirelessly.


The analog value is stored in the variable '''ldrVal'''.
The ESP32 can send messages using:


<center>
<pre>
'''LDR → GPIO 35 → ldrVal'''
SerialBT.println("Hello from ESP32");
</center>
</pre>
 
It can also receive data from the connected Bluetooth device.
 
For example, a smartphone can send:


The program converts the sensor value into a character array and transmits it through Bluetooth.
<pre>
ON
</pre>


The Bluetooth device is initialized with the name:
The ESP32 can receive this command and use it to control an output device such as an LED.


<center>
Similarly, a command such as:
'''Sush'''
</center>


A paired Bluetooth device receives the transmitted sensor data.
<pre>
OFF
</pre>


At the same time, the sensor value is displayed on the Serial Monitor.
can be used to turn the LED OFF.


<center>
<center>
'''LDR → ESP32 → Bluetooth + Serial Monitor'''
'''Bluetooth Command → ESP32 → Program Processing → Output Control'''
</center>
</center>


The sensor value is transmitted approximately every '''300 ms'''.
<div style="margin-top:15px;">
[[Media:Cognifront-bt-app.zip|<span style="display:inline-block; padding:10px 20px; background:#092328; color:white; border-radius:5px; font-weight:bold; text-decoration:none;">Download Cognifront Bluetooth App</span>]]<br>
Kindly install Cognifront Bluetooth App on your mobile phone (Android Support only) for doing communication with ESP32.
</div>


== Bluetooth Data Format ==
== Example Program ==


The Bluetooth output is transmitted in the following format:
The following program demonstrates basic Bluetooth communication with the ESP32.


<pre>
<pre>
LDR Val: <sensor value>
/*
</pre>
========================================
ESP32 Bluetooth + LM35 + Buzzer Demo
========================================
 
Bluetooth Commands:


For example:
ON        -> Turn LED ON
OFF      -> Turn LED OFF
TEMP      -> Read LM35 Temperature
STATUS    -> Check ESP32 Status
BLINK    -> Blink LED 5 Times
BUZZON    -> Turn Buzzer ON
BUZZOFF  -> Turn Buzzer OFF


<pre>
========================================
LDR Val: 856
Connections:
LDR Val: 872
LDR Val: 901
</pre>


The actual value depends on the light intensity detected by the LDR.
LM35:
VCC  -> 3.3V
OUT  -> GPIO34
GND  -> GND


== Timing ==
Buzzer:
+ -> GPIO25
- -> GND


The program uses a delay of '''300 ms''' between successive sensor readings.
LED:
Built-in LED -> GPIO2


The sequence is:
Bluetooth Device Name:
ESP32_Demo


<center>
========================================
'''Read LDR → Convert Value → Transmit Bluetooth → Display Serial → 300 ms Delay → Repeat'''
*/
</center>


== Program ==
#include "BluetoothSerial.h"


<pre>
BluetoothSerial SerialBT;
// © 2026, Cognifront


#include "BluetoothSerial.h"
#define LED_PIN    2
#define LM35_PIN    34
#define BUZZER_PIN  25


#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
String incomingData = "";
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif


BluetoothSerial BT;
void setup() {


#include<DHT.h>
  pinMode(LED_PIN, OUTPUT);
  pinMode(BUZZER_PIN, OUTPUT);


int ldrPin = 35;
  digitalWrite(LED_PIN, LOW);
int ldrVal;
  digitalWrite(BUZZER_PIN, LOW);
char msg[30];
String s;


void setup()
   Serial.begin(115200);
{
   Serial.begin(9600);


   BT.begin("Sush"); //Bluetooth device name
   // Start Bluetooth
  SerialBT.begin("ESP32_Demo");


   Serial.println("The device started, now you can pair it with bluetooth!");
   Serial.println("Bluetooth Started");


   pinMode(ldrPin, INPUT);
   SerialBT.println("ESP32 Bluetooth Ready");
  SerialBT.println("Commands:");
  SerialBT.println("ON, OFF, TEMP, STATUS");
  SerialBT.println("BLINK, BUZZON, BUZZOFF");
}
}


void loop()
void loop() {
{
 
  ldrVal = analogRead(ldrPin);
  while (SerialBT.available()) {
 
    char c = SerialBT.read();
 
    if (c == '\n') {
 
      incomingData.trim();
      incomingData.toUpperCase();
 
      Serial.print("Received: ");
      Serial.println(incomingData);
 
      // ======================
      // LED ON
      // ======================
      if (incomingData == "ON") {
 
        digitalWrite(LED_PIN, HIGH);
 
        SerialBT.println("LED ON");
      }
 
      // ======================
      // LED OFF
      // ======================
      else if (incomingData == "OFF") {
 
        digitalWrite(LED_PIN, LOW);
 
        SerialBT.println("LED OFF");
      }
 
      // ======================
      // TEMP READ
      // ======================
      else if (incomingData == "TEMP") {
 
        float temperatureC = readTemperature();
 
        SerialBT.print("Temperature: ");
        SerialBT.print(temperatureC);
        SerialBT.println(" °C");
 
        Serial.print("Temperature: ");
        Serial.println(temperatureC);
 
        // Auto buzzer alert
        if (temperatureC > 35) {
 
          digitalWrite(BUZZER_PIN, HIGH);
 
          SerialBT.println("WARNING: HIGH TEMPERATURE!");
        }
        else {
 
          digitalWrite(BUZZER_PIN, LOW);
        }
      }
 
      // ======================
      // STATUS
      // ======================
      else if (incomingData == "STATUS") {
 
        SerialBT.println("ESP32 Running OK");
      }
 
      // ======================
      // BLINK
      // ======================
      else if (incomingData == "BLINK") {
 
        SerialBT.println("Blinking LED");
 
        for (int i = 0; i < 5; i++) {
 
          digitalWrite(LED_PIN, HIGH);
          delay(300);
 
          digitalWrite(LED_PIN, LOW);
          delay(300);
        }
 
        SerialBT.println("Blink Complete");
      }
 
      // ======================
      // BUZZER ON
      // ======================
      else if (incomingData == "BUZZON") {
 
        digitalWrite(BUZZER_PIN, HIGH);
 
        SerialBT.println("Buzzer ON");
      }
 
      // ======================
      // BUZZER OFF
      // ======================
      else if (incomingData == "BUZZOFF") {
 
        digitalWrite(BUZZER_PIN, LOW);
 
        SerialBT.println("Buzzer OFF");
      }


  s = String (ldrVal);
      // ======================
      // UNKNOWN COMMAND
      // ======================
      else {


  s.toCharArray(msg, 30);
        SerialBT.println("Unknown Command");
      }


  BT.print("LDR Val: ");
      incomingData = "";
  BT.println(msg);
    }


  Serial.println(msg);
    else {


   delay(300);
      incomingData += c;
    }
   }
}
 
// =====================================
// FUNCTION: Read LM35 Temperature
// =====================================
float readTemperature() {
 
  int adcValue = analogRead(LM35_PIN);
 
  // Convert ADC to Voltage
  float voltage = adcValue * (3.3 / 4095.0);
 
  // LM35 = 10mV per °C
  float temperatureC = voltage * 100.0;
 
  return temperatureC;
}
}
</pre>
</pre>


== Observation ==
== Example of Command-Based Communication ==
 
Bluetooth can also be used to send commands to the ESP32.
 
For example:
 
{| class="wikitable"
! Command
! Function
|-
| ON
| Turn an output ON
|-
| OFF
| Turn an output OFF
|-
| STATUS
| Send ESP32 status
|-
| SENSOR
| Send sensor reading
|}
 
A command received through Bluetooth can be compared in the program and the required operation can be performed.


Observe the LDR sensor value on the Serial Monitor.
Example:


The value changes according to the intensity of light falling on the LDR.
<pre>
if (command == "ON") {


The same LDR value is transmitted through Bluetooth to the paired device.
  digitalWrite(LED_PIN, HIGH);


The Bluetooth device appears with the name:
  SerialBT.println("LED ON");
}


<center>
else if (command == "OFF") {
'''Sush'''
</center>


The transmitted output follows the format:
  digitalWrite(LED_PIN, LOW);


<pre>
  SerialBT.println("LED OFF");
LDR Val: xxxx
}
</pre>
</pre>
== Applications ==
ESP32 Bluetooth communication can be used in many applications, including:
* Wireless LED control
* Home automation
* Sensor monitoring
* Robot control
* Wireless data logging
* Industrial control systems
* Smart appliances
* Mobile-controlled projects
* Wireless serial communication
== Safety Precautions ==
* Check the ESP32 power supply before starting the experiment.
* Use the correct GPIO pins for external sensors and actuators.
* Do not exceed the GPIO current limits of the ESP32.
* Ensure that the Bluetooth device is properly paired before testing communication.
* Keep the Bluetooth-enabled devices within the appropriate communication range.
* Use suitable driver circuits when controlling high-current loads.
== Observation ==
After starting the program, the ESP32 appears as the configured Bluetooth device name.
After pairing the ESP32 with a smartphone or computer, messages can be transmitted wirelessly.
Observe the transmitted and received data on the Serial Monitor and the connected Bluetooth device.


== Result ==
== Result ==


The ESP32 successfully interfaces with the '''LDR sensor''' through GPIO 35.
The ESP32 successfully communicates with a Bluetooth-enabled device using its built-in Bluetooth interface.


The ESP32 reads the analog LDR value and displays it on the Serial Monitor.
Data can be transmitted from the ESP32 to the connected device, and commands or data can be received by the ESP32 through Bluetooth.


The sensor value is also successfully transmitted wirelessly through '''Bluetooth''' using the Bluetooth device name '''Sush'''.
The Bluetooth interface can therefore be used for wireless monitoring, control, and data communication in ESP32-based applications.

Latest revision as of 05:39, 4 September 2026

ESP32 Bluetooth Communication

ESP32 Bluetooth Communication demonstrates how the built-in Bluetooth functionality of the ESP32 can be used for wireless communication between the ESP32 board and a Bluetooth-enabled device such as a smartphone, tablet, or computer.

The ESP32 can send and receive data wirelessly using Bluetooth without requiring a physical serial connection.

Bluetooth Device → Wireless Communication → ESP32

Objectives

  • To study the Bluetooth functionality available in the ESP32.
  • To understand how to initialize Bluetooth communication.
  • To pair the ESP32 with a Bluetooth-enabled device.
  • To send data from the ESP32 to a Bluetooth device.
  • To receive commands or data from a Bluetooth device.
  • To control ESP32 peripherals using Bluetooth commands.

Software

  • Arduino IDE
  • ESP32 board package
  • Bluetooth-enabled smartphone, tablet, or computer

Hardware Modules

  • ESP32 Development Board
  • PC / Laptop
  • Smartphone / Bluetooth-enabled device
  • External sensors or actuators as required

Theory

Bluetooth is a wireless communication technology used for exchanging data between electronic devices over short distances.

The ESP32 contains built-in Bluetooth hardware, allowing it to communicate with compatible Bluetooth devices without requiring an external Bluetooth module.

The ESP32 can be programmed to operate as a Bluetooth device with a user-defined device name.

ESP32 Bluetooth → Wireless Data Transmission → Smartphone / PC

Bluetooth communication can be used for:

  • Sending sensor readings
  • Receiving control commands
  • Controlling LEDs
  • Controlling buzzers
  • Monitoring system status
  • Sending data to a mobile application
  • Wireless serial communication

ESP32 Bluetooth

The ESP32 provides built-in Bluetooth functionality.

For Bluetooth Classic communication in the Arduino environment, the BluetoothSerial library can be used.

The library provides a serial-like interface for sending and receiving data wirelessly.

The basic sequence is:

Initialize Bluetooth → Set Device Name → Pair Device → Send/Receive Data

BluetoothSerial Library

The BluetoothSerial library provides functions for Bluetooth Classic communication.

The library is included using:

#include "BluetoothSerial.h"

A Bluetooth serial object is then created:

BluetoothSerial SerialBT;

Bluetooth communication is started using:

SerialBT.begin("ESP32_Demo");

Here, ESP32_Demo is the Bluetooth device name that appears when searching for the ESP32 from another Bluetooth device.

Bluetooth Communication

Bluetooth communication works in two directions.

Sending Data

The ESP32 can send data to a connected Bluetooth device using:

SerialBT.print("Hello");
SerialBT.println("ESP32");

The print() function sends data without automatically adding a new line.

The println() function sends data followed by a new line.

ESP32 → Bluetooth → Smartphone / PC

Receiving Data

The ESP32 can check whether data has been received using:

SerialBT.available()

Received characters can be read using:

char c = SerialBT.read();

The received characters can then be processed as commands or sensor-control instructions.

Smartphone / PC → Bluetooth → ESP32

Bluetooth Device Name

The ESP32 Bluetooth device name can be specified while starting Bluetooth.

Example:

SerialBT.begin("ESP32_Demo");

After Bluetooth is started, the device appears as:

ESP32_Demo

on the Bluetooth device used for pairing.

The name can be changed as required.

For example:

SerialBT.begin("MyESP32");

Connections

Bluetooth communication itself does not require external communication wires between the ESP32 and the smartphone or computer.

Device Connection Function
ESP32 Built-in Bluetooth Wireless communication
Smartphone / PC Bluetooth Wireless communication

External sensors and actuators can be connected to the ESP32 separately depending on the application.

Basic Bluetooth Communication Flow

The Bluetooth communication process can be summarized as:

  1. Start the Arduino IDE.
  2. Include the BluetoothSerial library.
  3. Create a Bluetooth serial object.
  4. Start Bluetooth using SerialBT.begin().
  5. Assign a name to the ESP32 Bluetooth device.
  6. Search for the ESP32 using a Bluetooth-enabled device.
  7. Pair/connect the device with the ESP32.
  8. Send data from the ESP32 using SerialBT.print() or SerialBT.println().
  9. Check for incoming data using SerialBT.available().
  10. Read incoming data using SerialBT.read().
  11. Process the received data according to the application.

Algorithm

  1. Start the Arduino IDE.
  2. Include the BluetoothSerial library.
  3. Create a BluetoothSerial object.
  4. Start Bluetooth communication with a suitable device name.
  5. Display the Bluetooth status on the Serial Monitor.
  6. Wait for a Bluetooth device to connect.
  7. Check whether data is available from the Bluetooth device.
  8. Read the received data.
  9. Process the received command or data.
  10. Send a response using Bluetooth.
  11. Repeat the process continuously.

Start → Initialize Bluetooth → Connect Device → Send/Receive Data → Process Data → Repeat

Working

When the ESP32 program starts, the Bluetooth interface is initialized using the BluetoothSerial library.

The ESP32 becomes discoverable using the Bluetooth device name specified in the program.

After pairing or connecting a smartphone or computer, data can be exchanged wirelessly.

The ESP32 can send messages using:

SerialBT.println("Hello from ESP32");

It can also receive data from the connected Bluetooth device.

For example, a smartphone can send:

ON

The ESP32 can receive this command and use it to control an output device such as an LED.

Similarly, a command such as:

OFF

can be used to turn the LED OFF.

Bluetooth Command → ESP32 → Program Processing → Output Control

Download Cognifront Bluetooth App
Kindly install Cognifront Bluetooth App on your mobile phone (Android Support only) for doing communication with ESP32.

Example Program

The following program demonstrates basic Bluetooth communication with the ESP32.

/*
========================================
ESP32 Bluetooth + LM35 + Buzzer Demo
========================================

Bluetooth Commands:

ON        -> Turn LED ON
OFF       -> Turn LED OFF
TEMP      -> Read LM35 Temperature
STATUS    -> Check ESP32 Status
BLINK     -> Blink LED 5 Times
BUZZON    -> Turn Buzzer ON
BUZZOFF   -> Turn Buzzer OFF

========================================
Connections:

LM35:
VCC  -> 3.3V
OUT  -> GPIO34
GND  -> GND

Buzzer:
+ -> GPIO25
- -> GND

LED:
Built-in LED -> GPIO2

Bluetooth Device Name:
ESP32_Demo

========================================
*/

#include "BluetoothSerial.h"

BluetoothSerial SerialBT;

#define LED_PIN     2
#define LM35_PIN    34
#define BUZZER_PIN  25

String incomingData = "";

void setup() {

  pinMode(LED_PIN, OUTPUT);
  pinMode(BUZZER_PIN, OUTPUT);

  digitalWrite(LED_PIN, LOW);
  digitalWrite(BUZZER_PIN, LOW);

  Serial.begin(115200);

  // Start Bluetooth
  SerialBT.begin("ESP32_Demo");

  Serial.println("Bluetooth Started");

  SerialBT.println("ESP32 Bluetooth Ready");
  SerialBT.println("Commands:");
  SerialBT.println("ON, OFF, TEMP, STATUS");
  SerialBT.println("BLINK, BUZZON, BUZZOFF");
}

void loop() {

  while (SerialBT.available()) {

    char c = SerialBT.read();

    if (c == '\n') {

      incomingData.trim();
      incomingData.toUpperCase();

      Serial.print("Received: ");
      Serial.println(incomingData);

      // ======================
      // LED ON
      // ======================
      if (incomingData == "ON") {

        digitalWrite(LED_PIN, HIGH);

        SerialBT.println("LED ON");
      }

      // ======================
      // LED OFF
      // ======================
      else if (incomingData == "OFF") {

        digitalWrite(LED_PIN, LOW);

        SerialBT.println("LED OFF");
      }

      // ======================
      // TEMP READ
      // ======================
      else if (incomingData == "TEMP") {

        float temperatureC = readTemperature();

        SerialBT.print("Temperature: ");
        SerialBT.print(temperatureC);
        SerialBT.println(" °C");

        Serial.print("Temperature: ");
        Serial.println(temperatureC);

        // Auto buzzer alert
        if (temperatureC > 35) {

          digitalWrite(BUZZER_PIN, HIGH);

          SerialBT.println("WARNING: HIGH TEMPERATURE!");
        }
        else {

          digitalWrite(BUZZER_PIN, LOW);
        }
      }

      // ======================
      // STATUS
      // ======================
      else if (incomingData == "STATUS") {

        SerialBT.println("ESP32 Running OK");
      }

      // ======================
      // BLINK
      // ======================
      else if (incomingData == "BLINK") {

        SerialBT.println("Blinking LED");

        for (int i = 0; i < 5; i++) {

          digitalWrite(LED_PIN, HIGH);
          delay(300);

          digitalWrite(LED_PIN, LOW);
          delay(300);
        }

        SerialBT.println("Blink Complete");
      }

      // ======================
      // BUZZER ON
      // ======================
      else if (incomingData == "BUZZON") {

        digitalWrite(BUZZER_PIN, HIGH);

        SerialBT.println("Buzzer ON");
      }

      // ======================
      // BUZZER OFF
      // ======================
      else if (incomingData == "BUZZOFF") {

        digitalWrite(BUZZER_PIN, LOW);

        SerialBT.println("Buzzer OFF");
      }

      // ======================
      // UNKNOWN COMMAND
      // ======================
      else {

        SerialBT.println("Unknown Command");
      }

      incomingData = "";
    }

    else {

      incomingData += c;
    }
  }
}

// =====================================
// FUNCTION: Read LM35 Temperature
// =====================================
float readTemperature() {

  int adcValue = analogRead(LM35_PIN);

  // Convert ADC to Voltage
  float voltage = adcValue * (3.3 / 4095.0);

  // LM35 = 10mV per °C
  float temperatureC = voltage * 100.0;

  return temperatureC;
}

Example of Command-Based Communication

Bluetooth can also be used to send commands to the ESP32.

For example:

Command Function
ON Turn an output ON
OFF Turn an output OFF
STATUS Send ESP32 status
SENSOR Send sensor reading

A command received through Bluetooth can be compared in the program and the required operation can be performed.

Example:

if (command == "ON") {

  digitalWrite(LED_PIN, HIGH);

  SerialBT.println("LED ON");
}

else if (command == "OFF") {

  digitalWrite(LED_PIN, LOW);

  SerialBT.println("LED OFF");
}

Applications

ESP32 Bluetooth communication can be used in many applications, including:

  • Wireless LED control
  • Home automation
  • Sensor monitoring
  • Robot control
  • Wireless data logging
  • Industrial control systems
  • Smart appliances
  • Mobile-controlled projects
  • Wireless serial communication

Safety Precautions

  • Check the ESP32 power supply before starting the experiment.
  • Use the correct GPIO pins for external sensors and actuators.
  • Do not exceed the GPIO current limits of the ESP32.
  • Ensure that the Bluetooth device is properly paired before testing communication.
  • Keep the Bluetooth-enabled devices within the appropriate communication range.
  • Use suitable driver circuits when controlling high-current loads.

Observation

After starting the program, the ESP32 appears as the configured Bluetooth device name.

After pairing the ESP32 with a smartphone or computer, messages can be transmitted wirelessly.

Observe the transmitted and received data on the Serial Monitor and the connected Bluetooth device.

Result

The ESP32 successfully communicates with a Bluetooth-enabled device using its built-in Bluetooth interface.

Data can be transmitted from the ESP32 to the connected device, and commands or data can be received by the ESP32 through Bluetooth.

The Bluetooth interface can therefore be used for wireless monitoring, control, and data communication in ESP32-based applications.