首页 > 解决方案 > arduino esp32蓝牙接收一整串

问题描述

有没有一种简洁的方式来接收带有 esp32 BluetoothSerial 库的消息字符串,就像Serial.readString(). 这个想法是从智能手机发送消息,接收消息并从该消息中更新变量,这将影响 Arduino 的功能。我也可以将一个字节保存为例如 255 而不是 0xFF 吗?

#include "BluetoothSerial.h"

BluetoothSerial SerialBT;

uint8_t mode = 0;
int speedDelay = 50;
byte color1r, color1g, color1b, color2r, color2g, color2b = 0; // can I save this as a number from 0-255?


String readBTString() {
  return ???     // recieve a string or char from SerialBT ??
}

// this checks if a new message is available and then updates the variables accordingly
bool checkBT() {
  if(SerialBT.available()) {
    char data[35];

    // e.g. "1::0,255,67::255,43,87::30"
    String str = readBTString();
    str.toCharArray(data, 35);

    // update variables from message including updating mode which then effects the loop function
    sscanf(data, "%d::%d,%d,%d::%d,%d,%d::%d", &mode, &color1r, &color1g, &color1b, &color2r, &color2g, &color2b, &speedDelay);
    return true;
  }
  else return false;
}

doSomething(byte r, byte g, byte b, int speedDelay) {
  for (int i = 0; i<255; i++) {
     // do something
     delay(speedDelay);
     if (checkBT()) break; // check if a message is available
  }
}

doSomethingElse(byte r, byte g, byte b, int speedDelay) {
  for (int i = 0; i<255; i++) {
     // do something else
     delay(speedDelay);
     if (checkBT()) break;
  }
}

void setup() {
  SerialBT.begin("BTtest");
}

void loop() {
  switch (mode) // different mode values do different things
  {
  case 0:
    doSomething(color1r,color1g,color1b, speedDelay);
    break;
  case 1:
    doSomethingElse(color1r,color1g,color1b, speedDelay);
    break;
  default:
    doSomething(color1r,color1g,color1b, speedDelay);
    break;
  }
}

标签: c++arduinobluetoothesp32

解决方案


它实际上似乎BluetoothSerial有一种readString方法......我在 Platform.io 上使用 esp32 + Arduino 框架配置,它可以正确编译......


推荐阅读