14、ESP32 Bluetooth

一、经典蓝牙

        ESP32 上的内置经典蓝牙相比低功耗蓝牙较为简单,可以和 Android 智能手机之间交换数据。例程手机蓝牙控制 led 开关:

#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

const int ledPin = 2;

String message = "";

BluetoothSerial SerialBT;   // 蓝牙结构名称

void setup()
{
    Serial.begin(115200);

    pinMode(ledPin, OUTPUT);
    digitalWrite(ledPin , LOW);

    SerialBT.begin("ESP32_Blue");    // 蓝牙名称
    Serial.println("The device started, now you can pair it with bluetooth!");
}

void loop()
{
    if (SerialBT.available())   //判断蓝牙串口是否收到数据
    {
        char c = SerialBT.read();   //将收到的数据读取出来,下面分别处理
        // String res = SerialBT.readString();   //将收到的数据读取出来,下面分别处理
        if (c != '\n')
        {
            message += String(c);
        }
        else
        {
            message = "";
        }
        Serial.write(c);
    }

    if (message == "led_on")
    {
        digitalWrite(ledPin, HIGH);
    }
    else if (message == "led_off")
    {
        digitalWrite(ledPin, LOW);
    }

    delay(10);
}

        烧录到 ESP32 开发板后,可以在手机端用蓝牙串口工具连接到 ESP32 蓝牙࿰

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

无敌暴龙战士朵拉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值