I have a problem with receiving string data via Bluetooth, and more specifically with its subsequent use.
#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);
}
When I send something as string data, the SerialBT.println(text); function works fine, but the next function if(text == "go") no longer works.
The two character strings are not the same.
For normal Serial, everything works fine.
How to fix this?
1 Answer
I knew Bluetooth was sending some extra variables, but I didn't know how to detect and delete them. But I have already found a solution.
Firstly, I used text = SerialBT.read(); to detect extra char. Bluetooth send extra char at the end of string data.
So, I then used text.remove(text.length()-1,1);, and everything is already working correctly.
Completed code:
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);
}