# 10. 经典蓝牙串口SPP

示例代码主要演示了蓝牙串口和串口之间相互转发信息，来源于ESP32的官方例程，简单易懂。所以说明中主要解释代码中出现的概念。

### 1. 蓝牙协议

目前主要的蓝牙协议分为2类，基于RFCOMM的传统蓝牙（HS/BR/EDR）和基于GATT的蓝牙低功耗（BLE）。

传统蓝牙速度较快，具体应用协议多，如面向音频的A2DP，蓝牙串口SPP等。但功耗较高，且接入苹果设备需要MFi（Made For iOS）的芯片及认证。

蓝牙低功耗（BLE，Bluetooth Low Energy）可以自行定义各种GATT的Profile，自身也配置了常用的Profile（如设备信息、电池等），功耗低用途广，可以用在苹果设备上，缺点是比起传统蓝牙速度比较慢。蓝牙低功耗多用于手环/智能手表/信标等数据量低但是对功耗敏感的设备上。

### 2. 经典蓝牙串口 （ SPP）

本示例使用的是基于传统蓝牙的SPP协议，自带全部的串口协议。当计算机或安卓手机连接配对后会在系统自动生成一个串口号进行通讯，使用体验和普通有线串口没有太大区别。

```
//This example code is in the Public Domain (or CC0 licensed, at your option.)
//By Evandro Copercini - 2018
//
//This example creates a bridge between Serial and Classical Bluetooth (SPP)
//and also demonstrate that SerialBT have the same functionalities of a normal Serial

#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;

void setup() {
  Serial.begin(115200);
  SerialBT.begin("BTSPP_Test");          //Bluetooth device name
  Serial.println("The device started,");
  Serial.println("Now you can pair it with bluetooth!");
}

void loop() {
  if (Serial.available()) {
    SerialBT.write(Serial.read());
  }
  if (SerialBT.available()) {
    Serial.write(SerialBT.read());
  }
  delay(20);
}
```

蓝牙低功耗串口将在下一章演示，本质上是配置了一个串口的Profile, 需要主机软件支持。
