#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);
}
}
以上是我的代碼,我輸入 3 得到的輸出是:51 13 10 要做什么?
uj5u.com熱心網友回復:
您既不發送也不接收int. 51 13 10是一個 ASCII字符 序列,例如,如果您在終端上鍵入'3' <carriage-return> <line-feed>字串,這是預期的。
然后您會收到單個字符并列印它們的整數值。
您要么需要發送二進制資料,然后將各個位元組重新組合成一個整數(為此雙方需要就整數的大小和位元組順序達成一致),或者您讀取一行并解釋字串和十進制表示一個整數。
例如:
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' ;
}
}
請注意,您也可以在此處替換:
while (SerialBT.available())
和:
if (SerialBT.available())
因為它已經在loop(). 這樣做可能會導致 中其他代碼的行為更具確定性loop(),因為每次迭代它只會讀取一個字符,而不是所有可用字符,這將花費可變的時間來處理。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/485116.html
標籤:C Arduino 蓝牙 嵌入式 arduino-esp32
上一篇:復制在c中具有不同列的二維陣列
下一篇:程式在C中中途停止執行
