Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
7 years, 11 months ago.
How to read the data received by Bluetooth
Hi. If I send two characters at a time to Bluetooth, but the getc () function can only read one character at a time, how can I read the data that Bluetooth receives without causing data loss? Thanks.
Question relating to:
1 Answer
7 years, 11 months ago.
Hello Zhang,
You could try to setup suitable Rx buffer and receive data in a while loop in main . With NUCLEO-F072RB for example as below:
#include "mbed.h"
#define RX_MAX 10
Serial pc(USBTX, USBRX);
Serial bt(PB_6, PA_10);
int main(void) {
char rxBuf[RX_MAX];
int i = 0;
bool rxBufOverflow = false;
pc.baud(115200);
bt.baud(115200);
pc.printf("Ready to receive data over Bluetooth.\r\n\r\n");
while (1) {
while (bt.readable()) {
if (i < RX_MAX)
rxBuf[i++] = bt.getc();
else {
bt.getc();
rxBufOverflow = true;
}
}
if (i > 0) {
printf("Data received:");
for (int j = 0; j < i; j++)
printf(" 0x%.2x", rxBuf[j]);
printf("\r\n");
if (rxBufOverflow) {
printf("Error: Rx buffer overflow -> Some data lost!\r\n");
rxBufOverflow = false;
}
printf("\r\n");
i = 0;
}
}
}
Or receive data in a while loop using interrupt service routine:
#include "mbed.h"
#define RX_MAX 10
Serial pc(USBTX, USBRX);
Serial bt(PB_6, PA_10);
char rxBuf[RX_MAX];
volatile int i = 0;
volatile bool rxBufOverflow = false;
void onBluetoothReceived(void) {
while (bt.readable()) {
if (i < RX_MAX)
rxBuf[i++] = bt.getc();
else {
bt.getc();
rxBufOverflow = true;
}
}
}
int main(void) {
pc.baud(115200);
bt.baud(115200);
bt.attach(&onBluetoothReceived, Serial::RxIrq);
pc.printf("Ready to receive data over Bluetooth.\r\n\r\n");
while (1) {
if (i > 0) {
printf("Data received:");
for (int j = 0; j < i; j++)
printf(" 0x%.2x", rxBuf[j]);
printf("\r\n");
if (rxBufOverflow) {
printf("Error: Rx buffer overflow -> Some data lost!\r\n");
rxBufOverflow = false;
}
printf("\r\n");
i = 0;
}
}
}