# ESP32與HC-05配對
###### tags: `esp32`
###### 撰寫時間 : 2021/12/19
## 需求
使用ESP32內建的藍芽與裝在Arduino系列板子的模組HC-05配對。
## 流程
參照[單晶片lab6結報 藍芽配對](https://hackmd.io/@arduino/report-6#藍芽配對)。
1. 獲得ESP32內建藍芽的地址。
```cpp
#include "esp_bt_device.h"
#include "esp_bt_main.h"
bool initBluetooth() {
if (!btStart()) {
Serial.println("Failed to initialize controller");
return false;
}
if (esp_bluedroid_init() != ESP_OK) {
Serial.println("Failed to initialize bluedroid");
return false;
}
if (esp_bluedroid_enable() != ESP_OK) {
Serial.println("Failed to enable bluedroid");
return false;
}
}
void printDeviceAddress() {
const uint8_t* point = esp_bt_dev_get_address();
// This function takes no arguments and
// returns the six bytes of the Bluetooth device address.
// Note that the six bytes will be returned as a pointer to an array of uint8_t,
// which we will store on a variable.
for (int i = 0; i < 6; i++) {
char str[3];
sprintf(str, "%02X", (int)point[i]);
Serial.print(str);
if (i < 5) {
Serial.print(":");
}
}
}
void setup() {
Serial.begin(115200);
initBluetooth();
printDeviceAddress();
}
void loop() {}
```
2. 將以下程式燒錄至ESP32
```cpp
#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;
char *pin = "1234"; //建立連接時的密碼,不設置與hc05連接不上
void setup() {
Serial.begin(115200);
SerialBT.setPin(pin);
SerialBT.begin("ESP32test"); //Bluetooth device name
Serial.println("The device started, now you can pair it with bluetooth!");
}
```
3. 將以下程式燒錄至Arduino系列板子,並將模組HC-05的key接5V,進入AT mode。
```cpp
#include <SoftwareSerial.h>
// Pin10為RX,接HC05的TXD
// Pin11為TX,接HC05的RXD
SoftwareSerial BT(10, 11);
char val;
void setup() {
Serial.begin(38400);
Serial.println("BT is ready!");
// HC-05默認,38400
BT.begin(38400);
}
void loop() {
if (Serial.available()) {
val = Serial.read();
BT.print(val);
}
if (BT.available()) {
val = BT.read();
Serial.print(val);
}
}
```
2. 輸入以下AT指令。
- 所有AT參數恢復為原廠設定
```cpp
AT+ORGL
```
- 設定角色為主端
```cpp
AT+ROLE=1
```
- 設定配對密碼與ESP32一致
```cpp
AT+PSWD=1234
```
- 初始化SPP規範庫便於查詢周邊信號
```cpp
AT+INIT
```
- 連接模式 : 指定藍芽位置
```cpp
AT+CMODE=0
```
- 設定要連線ESP32的slave地址,須將前面獲得從端地址的逗號`:`改為冒號`,`
```cpp
AT+BIND = 7C87,CE,4AB68E
```
3. 當HC-05提示燈快閃2下後停2秒,代表已配對成功,運作中。
## 當ESP32的藍芽與WIFI同時開啟時,會產生錯誤
原因 : ESP32的默認程式存儲區域大小為1M,超過這個大小就會報錯。
解決方法:
1. 修改分區表,[教學文](https://www.cnblogs.com/zornlink/p/11408925.html)。<br>

2. 打開Arduino IDE,給APP分區較大的空間。

## 參考資料
- [ESP32 Arduino: Getting the Bluetooth Device Address](https://techtutorialsx.com/2018/03/09/esp32-arduino-getting-the-bluetooth-device-address/)
- [HC05 蓝牙模块 连接 ESP32 经典蓝牙](https://blog.csdn.net/qq_43064082/article/details/106041797)
- [ESP32 通过 arduino方式 同时开启蓝牙wifi](https://blog.csdn.net/qq_43064082/article/details/105991274)