99% of this code is from a RANDOM NERD TUTORIAL on the web. The code compiles and runs and I see whatever I send from my tablet appear in the SERIAL window….but when I send “end” the program never detects it. I can’t figure out why? Any help would be appreciated
#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; int G_count = 0; void setup() { Serial.begin(115200); SerialBT.begin("ESP32test"); //Bluetooth device name Serial.println("The device started, now you can pair it with bluetooth!"); } void loop() { String message = ""; char incomingChar; if (SerialBT.available()) { char incomingChar = SerialBT.read(); if (incomingChar != '\n') { message += String(incomingChar); } else { message = ""; } Serial.write(incomingChar); } if (message == "end") { Serial.println("GOT MESSAGE"); Serial.println(message); delay(1000); } }
Hi.
What does it print in the serial monitor when you send “end”?
If you send other messages ares they printed on the Serial monitor?
Regards,
Sara
So I figured out the issue. Apparently the following two lines need to be declared prior to the setup() and not in the loop() String message = “”;char incomingChar; That being said, I don\’t understand why?
Hi Donald.
With the declaration on the loop(), every time it runs the loop(), the message variable is redeclared as an empty String.
With the declaration on the setup(), the variable keeps its previous value until we attribute a new value.
message += String(incomingChar);
However, I don’t understand why it works in a way and doesn’t work on the other way.
Regards,
Sara
Hi Sara
Thanks for your help. What you said makes sense. With the bad code, I was able to see each letter coming in “incomingChar” but I didn’t see the letters accumulate to make the “message”. Now I understand why.