You see very different output via bluetooth and Serial Monitor, because you are sending completely different things. On the Serial Monitor you see the sensor reading, since that is exactly, what you send:
Serial.print(sensorreading);
The print()
function will convert the integer variable sensorreading
into human readable text (meaning ASCII encoded text) and send this over Serial.
But then you do this:
SerialBT.write(textToSend[sensorreading]);
textToSend
is a String
object here. So with the parentheses [ ]
you are taking one character of that string. You try to use the sensorreading
th character. Since sensorreading
comes from an analogRead()
, it is most likely, that is value is rather big, meaning bigger than the length of the string. So you are basically reading some random memory, that happens to lie behind your string variable. The write()
function will then send that random data out over your bluetooth serial interface, without any conversion.
I guess you want to transmit the data over bluetooth also in human readable form. So just use the same code as with the Serial
interface (for the Serial Monitor).
And remove all that manual conversion of the measured analog value to a String
. That is not needed. If you want to also display some text, you can just use multiple print()
commands, like this:
Serial.print("Value: ")
Serial.print(sensorreading);
Serial.print(" units");
Note, that it is rather bad to use the String
object at all. The String
class uses dynamic memory allocation, which leads to memory fragmentation, which can eat up your available memory. This is not as important on chips with rather big memory (as the ESP32) than on chips with smaller memory (like the Atmega328p, which is used in Arduino Uno and Nano), but you should still keep that in mind. Instead of the String
class you would work with char
arrays, aka C-strings.