文章目录
- 一、前言
- 二、代码
- 三、运行
一、前言
ESP32支持经典蓝牙和低功耗蓝牙(BLE),经典蓝牙可在计算机上模拟出一个串口,使得ESP32可以以串口的方式和计算机通信。
二、代码
#include "BluetoothSerial.h"
String device_name = "ESP32-BT-Slave";
// Check if Bluetooth is available
#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif
// Check Serial Port Profile
#if !defined(CONFIG_BT_SPP_ENABLED)
#error Serial Port Profile for Bluetooth is not available or not enabled. It is only available for the ESP32 chip.
#endif
BluetoothSerial SerialBT;
void setup() {
Serial.begin(115200);
SerialBT.begin(device_name); //Bluetooth device name
//SerialBT.deleteAllBondedDevices(); // Uncomment this to delete paired devices; Must be called after begin
Serial.printf("The device with name \"%s\" is started.\nNow you can pair it with Bluetooth!\n", device_name.c_str());
}
void loop() {
if (Serial.available()) {
SerialBT.write(Serial.read());
}
if (SerialBT.available()) {
Serial.write(SerialBT.read());
}
delay(20);
}
三、运行
将程序编译并下载到ESP32 开发板中,通过计算机的蓝牙连接ESP32 ,连接后计算机上会出现一个新的串口(我计算机上的是COM12),打开串口调试软件(这里是Putty)和Ardunio的串口监视器,两者可以收到来自对方的信息。