我尝试做一个tx(pc)-rx(arduino),tx(arduino)-rx(pc)连接,从客户端发送一个字符串“Hello World!:)”,用xamarin.forms格式,以便从串行端口接收用BLE解码的相同字符串。在我发送字符串的那一刻,它工作得很好,因为我在arduino的串行监视器上看到了完美的字符串,但当解码时,字符串与发送的字符串不一样。
代码:Arduino:
void loop(){
if (BT.available() > 0 ){
c = BT.readString();
str_len = c.length() +1;
char char_array[str_len];
c.toCharArray(char_array, str_len);
int i = 0;
while(i<str_len){
char_array_aux[i] = char_array[i];
i++;
}
char_array_aux[str_len] = "\n";
}
int i = 0;
while(i<str_len){
if(char_array_aux[i] == "\n")
BT.end();
BT.print(char_array_aux[i]);
i++;
}
}
Xamarin.Forms应用程序发送/接收消息功能:
public async Task sendAndReceiveString()
{
//Guid characteristics = Id {0000ffe1-0000-1000-8000-00805f9b34fb} System.Guid
//Guid services = Id {0000ffe0-0000-1000-8000-00805f9b34fb} System.Guid
var stringToSend = "Hello World! :)";
var services = await deviceConn.GetServicesAsync();
IService service = services[0];
var characteristics = await service.GetCharacteristicsAsync();
var characteristic = characteristics[0];
try
{
//Write message
byte[] bytes = Encoding.ASCII.GetBytes(stringToSend);
await characteristic.WriteAsync(bytes);
//Read Message
byte[] answ = await characteristic.ReadAsync();
string answ_str = Encoding.ASCII.GetString(answ);
msgSended = "Message sended:" + stringToSend;
msgReceived = "Message received: " + answ_str;
}
调试日志:
Sended string: Hello world! :)
Received string: Hello world! :)
Hello world! :)
He
我不知道如何使用蓝牙缓冲区正常工作。如果有人知道,请让我知道。
先谢谢你了。
你好,劳尔。
1条答案
按热度按时间3z6pesqy1#
我刚修好了!我刚用
BT.readStringUntil("\n");
代替了readString()
且缓冲器不会溢出。