#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;
void setup() {
SerialBT.begin("BTMODE");
Serial.begin(115200);
}
int k;
void loop() {
while (SerialBT.available()) {
k=SerialBT.read();
Serial.println(k);
}
}
the above is my code and the outputs i get for entering 3 is : 51 13 10 what's to be done?
CodePudding user response:
You are neither sending nor receiving an int
. 51 13 10
is a sequence of ASCII characters '3' <carriage-return> <line-feed>
, which would be expected if you typed the string at a terminal for example.
You then receive individual characters and print thier integer value.
You either need to send binary data, and recombine the individual bytes into an integer (for which both sides would need to agree on both the size and byte order in an integer), or you read a line and interpret the string and a decimal representation of an integer.
For example:
void loop()
{
static char input[32] = "" ;
static int input_index = 0 ;
while (SerialBT.available())
{
char c = SerialBT.read() ;
if( c != '\r' && c != '\n' )
{
input[input_index] = c ;
input_index = (input_index 1) % (sizeof(input) - 1) ;
}
else if( input_index > 0 )
{
k = atoi( input ) ;
SerialBT.println( k ) ;
input_index = 0 ;
}
input[input_index] = '\0' ;
}
}
Note that here also you can replace:
while (SerialBT.available())
with:
if (SerialBT.available())
since it is already in the loop()
. Doing so may lead to more deterministic behaviour for other code in loop()
, because it will only read one character per iteration rather than all available, which will take a variable amount of time to process.