Tutorial: ESP32 Bluetooth Classic | How to get started with ESP32 | Arduino IDE
Introduction
ESP32 features a builtin WiFi and Bluetooth capabilities. In this tutorial, we will focus to the Bluetooth classic because Bluetooth LE deserves a separate tutorial.
Circuit Diagram
Video Demonstration
Call To Action
If you find this tutorial as helpful, please consider supporting me by Subscribing to my Youtube channel.
Thank you and have a good day.
Source Code
1 #include <BluetoothSerial.h>
2
3 // Pin assignments
4 #define BLUE_LED 25
5 #define GREEN_LED 26
6 #define RED_LED 27
7
8 // Instantiate a bluetooth serial
9 BluetoothSerial SerialBT;
10
11 // Variable for LED states
12 bool bluLedState = false;
13 bool grnLedState = false;
14 bool redLedState = false;
15
16 // Character buffer for incoming bluetooth data
17 char bufferData[8]; // holds the char data,
18 // increase this if you will use longer commands
19 char bufferIndex = 0; // holds the position of the char in the buffer
20
21 void setup() {
22 // Create the Bluetooth device name
23 SerialBT.begin("ESP32-BT");
24
25 // Set the pin directions
26 pinMode(BLUE_LED, OUTPUT);
27 pinMode(GREEN_LED, OUTPUT);
28 pinMode(RED_LED, OUTPUT);
29 }
30
31 void loop() {
32 manageBT();
33 }
34
35 void manageBT() {
36
37 // Manage the incoming bluetooth data
38 if (SerialBT.available()) {
39 // read a single character from BT and store it in a char variable inchar
40 char inchar = (char) SerialBT.read();
41
42 if (inchar != 'n') { // checks if character is not Carriage Return
43 bufferData[bufferIndex++] = inchar; // if not, store it in our buffer
44 } else { // else,
45 bufferIndex = 0; // reset our buffer index
46 memset(bufferData, 0, sizeof(bufferData)); // and our buffer
47 }
48 }
49
50 // Execute a specific task according to bluetooth command
51 // String compare function basically compares the 2 string
52 // and if characters are the same, returns 0
53 if (strcmp(bufferData, "Red:1") == 0) {
54 redLedState = true;
55 SerialBT.println("Red LED On");
56 } else if (strcmp(bufferData, "Red:0") == 0) {
57 redLedState = false;
58 SerialBT.println("Red LED Off");
59 } else if (strcmp(bufferData, "Grn:1") == 0) {
60 grnLedState = true;
61 SerialBT.println("Green LED On");
62 } else if (strcmp(bufferData, "Grn:0") == 0) {
63 grnLedState = false;
64 SerialBT.println("Green LED Off");
65 } else if (strcmp(bufferData, "Blu:1") == 0) {
66 bluLedState = true;
67 SerialBT.println("Blue LED On");
68 } else if (strcmp(bufferData, "Blu:0") == 0) {
69 bluLedState = false;
70 SerialBT.println("Blue LED Off");
71 }
72
73 // Update the LED state
74 digitalWrite(BLUE_LED, bluLedState);
75 digitalWrite(GREEN_LED, grnLedState);
76 digitalWrite(RED_LED, redLedState);
77 }
Posts in this series
- Tutorial: ESP32 Web Server | ESP32 WiFi in Access Point Mode
- Tutorial: ESP32 Web Server | Control something through ESP32 WiFi in Station Mode
No comments yet!