esp32藍牙通訊

最近想作一個發熱墊,能夠用手機控制。git

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

因此,最後仍是決定直接使用藍牙鏈接。app

硬件選型

雖然選擇了藍牙鏈接,但爲了之後擴展wifi方便,因此硬件選用了esp32,同時有wifi和藍牙鏈接的功能,代碼又兼容arduino,使用很是方便。oop

藍牙鏈接方式

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

溫控方式

使用溫敏電阻便可讀取溫度。ui

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

手機軟件

因爲我不會作安卓軟件,如今只是使用一款「藍牙串口」的app直接發送指令,控制硬件。code

之後仍是要學一下安卓,作一套架子出來。orm

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

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

  
    

  delay(20);
}

file

相關文章
相關標籤/搜索