esp32藍牙通信


最近想做一個發熱墊,可以用手機控制。

一開始思考過用wifi接入米家進行控制,這樣還能使用語音助手。但后來仔細思索一番,發現使用場景不對。如果使用wifi連接,那意味着只能在室內使用了。

所以,最后還是決定直接使用藍牙連接。

硬件選型

雖然選擇了藍牙連接,但為了以后擴展wifi方便,所以硬件選用了esp32,同時有wifi和藍牙連接的功能,代碼又兼容arduino,使用非常方便。

藍牙連接方式

  1. 初步設想是把硬件的mac地址生成二維碼,手機軟件掃描二維碼獲取mac地址,進行連接及發送溫度設置等指令。
  2. 后來發現,貌似可以直接用設備名進行藍牙連接,如此一來便可以把所有的硬件設備都設置為相同的設備名,又可以省去二維碼,着實不錯。
  3. 最后是在查資料時看到一種藍牙廣播的方式,不過尚未來及做實驗,日后有機會倒可以試試。

溫控方式

使用溫敏電阻即可讀取溫度。

  1. 最簡單的溫控可以是直接用繼電器開關進行控制。設置溫度的上下區間,加熱到上區間停止,低於下區間則重啟加熱。
  2. 高階一點的是用pwm的方式調整發熱電阻的功率,離目標溫度越接近則功率越小,如此即可實現平滑溫度曲線。甚至於再不行,還可上pid閉環控制算法,疊加上之前的誤差,實時調整。

file

file

file

手機軟件

由於我不會做安卓軟件,現在只是使用一款“藍牙串口”的app直接發送指令,控制硬件。

以后還是要學一下安卓,做一套架子出來。

esp32程序

//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;
char START_FLAG = '$';
char END_FLAG = '#';
int TEMPERATURE_MIN = 0;
int TEMPERATURE_MAX = 50;

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

void SerialBT_sendMsg(String msg) {
  int i = 0;
  for (i = 0; i < msg.length(); i++) {
    SerialBT.write(msg[i]);
  }
}

int NONE = 0;
int START = 1;
int pre_status = NONE;

int num = 0;
void loop() {
  if (SerialBT.available()) {
    char msg_char = SerialBT.read();
    if (msg_char == START_FLAG) {
      num = 0;
      pre_status = START;
    } else if (msg_char == END_FLAG && pre_status == START) {
      if (num >= TEMPERATURE_MIN && num <= TEMPERATURE_MAX) {
        String msg = String("set temperature to " + String(num) + "\n");
        SerialBT_sendMsg(msg);
      }
      num = 0;
      pre_status = NONE;
    } else if (isDigit(msg_char) && pre_status == START) {
      num = num * 10 + (msg_char - '0');
    } else {
      num = 0;
      pre_status = NONE;![file](https://img2020.cnblogs.com/other/2317513/202103/2317513-20210306154439467-2081275567.jpg)
    }

    // SerialBT_sendMsg(String(String(msg_char) + "\n"));
  }

  
    

  delay(20);
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM