String 通过蓝牙接收字符串数据-ESP32

String 通过蓝牙接收字符串数据-ESP32,string,bluetooth,esp32,arduino-ide,String,Bluetooth,Esp32,Arduino Ide,我在通过蓝牙接收字符串数据时遇到了问题,更具体地说,在随后的使用中 #include "BluetoothSerial.h" String text = ""; #if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED) #error Bluetooth is not enabled! Please run `make menuconfig` to and enable i

我在通过蓝牙接收字符串数据时遇到了问题,更具体地说,在随后的使用中

#include "BluetoothSerial.h"

String text = "";

#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("ESP32"); //Bluetooth device name
;}

void loop() {
  if (SerialBT.available() > 0) {
    text = SerialBT.readStringUntil('\n');
    Serial.println(text);
    if(text == "go") {
       Serial.println("Info");
    }
  }
  delay(20);
}
当我将某些内容作为字符串数据发送时,
SerialBT.println(text)函数工作正常,但下一个函数
if(text==“go”)
不再工作。 这两个字符串不相同

对于普通的连续剧,一切正常


如何解决这个问题?

我知道蓝牙发送了一些额外的变量,但我不知道如何检测和删除它们。 但我已经找到了解决办法

首先,我使用了
text=SerialBT.read()
以检测额外字符。蓝牙在字符串数据末尾发送额外字符。 因此,我随后使用
text.remove(text.length()-1,1),一切都已正常工作

完成代码:

void loop() {
  if (SerialBT.available() > 0) {
    text = SerialBT.readStringUntil('\n');
    text.remove(text.length()-1, 1);
    Serial.println(text);
    if(text == "go") {
      Serial.println("Info");
    }
  }
  delay(20);
}

我会假设
文本
实际上包含的不仅仅是“go”,这就是它们不相等的原因。如果(text.indexOf(“go”)>0)
,您能试试吗?这将搜索go并返回
文本中的位置。如果找不到-1,则返回编辑将有助于了解实际比较的内容。编写一些代码来输出
文本中的每个字符
,以便了解比较失败的原因。这应该会给你答案。