arduino环境下ESP32的蓝牙通信

之所以用ESP32是因为它有自带的蓝牙和WIFI等通信功能,我所使用的型号是GOOUUU-esp32 在arduino ade中可以直接找到esp32蓝牙的示例程序 首先在“工具”一栏里选择相应的开发板 然后在“文件-示例”中找到相应的蓝牙示例 图中有两个蓝牙相关的示例后缀为“BT”的是作为从机的蓝牙示例,而后缀为“BTM”的是作为主机的蓝牙示例,这两个是用于两个ESP32之间互相通信时的两个相关示例,这里只说一下从机的示例 点击后缀为“BT”的示例以后系统将给出一下程序

//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("ESP32test"); //Bluetooth device name
  Serial.println("The device started, 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);
}

要用这个程序的话,头文件和定义直接复制即可,主要说一下主程序中的函数的用途

Serial.begin(115200);
  SerialBT.begin("ESP32test"); //Bluetooth device name
  Serial.println("The device started, now you can pair it with bluetooth!");

初始化中的函数一目了然 Serial.begin()用于设置波特率; SerialBT.begin("ESP32test")此函数用于设置其它设备在搜索此设备的蓝牙时显示的名称,这里如果用手机蓝牙搜索的话就会显示ESP32test; Serial.println("The device started, now you can pair it with bluetooth!")此函数用于在对话框中的输出,这里用于提示蓝牙已开始工作

下面loop中的函数是重点

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

下类函数为显示串口缓冲区中当前剩余的字符个数,当它>0时说明串口接收到了信息, Serial.available()此函数为开发板发送的字符个数 SerialBT.available()此函数为开发板接收的字符个数

下类函数为发送和接收的函数 Serial.read()此函数用于存储开发板发送的数据 SerialBT.read()此函数用于存储开发板接收的数据

下类函数为输出函数,用途相同,都是在对话框中显示相应的数据 Serial.write SerialBT.write

经验分享 程序员 微信小程序 职场和发展