ESP32's Bluetooth: Everything You Need to Know
In this blog post we will be diving into the world of esp32's Bluetooth capabilities.
The esp32 is famous for its Wi-Fi capabilities but it also has some Bluetooth functionalities like the Bluetooth classic and the BLE that is Bluetooth Low Energy.
In this post we'll be mainly looking at the Bluetooth classic.
ps: Micropython doesn't support bluetooth classic of the esp32(at the time of writing).
let's get started
STEP 1:
First of all for understanding this we are going to look at the examples.
we need the serial to serial BT.
if you have already used Bluetooth with Arduino you will understand it easily, it's similar you can go check out my video.
Code Explanation
In the first line we include the Bluetooth serial library
#include "BluetoothSerial.h"
next if you want to use a pin or password we can set that PIN to access our esp32
const char *pin = "1234";
Here we can set the device name that is if we want to change the name of the esp32 we can do so will be displayed on other devices
String device_name = "ESP32-BT-Slave";
These lines are used to check if the Bluetooth is properly connected
#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif
#if !defined(CONFIG_BT_SPP_ENABLED)
#error Serial Bluetooth not available or not enabled. It is only available for the ESP32 chip.
Then create an instance of Bluetooth serial called serial BT
BluetoothSerial SerialBT;
Next we give the baud rate of 1150200
if you have defined the "USE_PIN" variable that is you have to go in and comment the above variable and if you have defined it you can set a pin for your esp32
#ifdef USE_PIN
SerialBT.setPin(pin);
In this loop, we send and receive data
void loop() {
if (Serial.available()) {
SerialBT.write(Serial.read());
}
if (SerialBT.available()) {
Serial.write(SerialBT.read());
}
delay(20);
}
let us assume the serial Bluetooth device to be our Phone here we check if there are any bytes received in the serial port, if it is available send the data through Bluetooth to this connected device.
serial BT.write() sends the data using Bluetooth serial.
Serial.read() reads the data given to the serial port.
So the esp32 sends whatever data it reads in the serial port to the connected device. In the if statement the complete opposite happens it checks the data available to see your Bluetooth that is our phone, if there are, we will write those bytes or data to the serial monitor.
Comments
Post a Comment