通过蓝牙连续传输数据

我想生成0到100之间的随机数,并通过蓝牙连续地从Raspberry Pi(运行Linux)传输到embedded式(x86)PC(也运行Linux)。 我的C代码基于以下内容:

客户端: –

#include <stdio.h> #include <unistd.h> #include <sys/socket.h> #include <bluetooth/bluetooth.h> #include <bluetooth/rfcomm.h> int main(int argc, char **argv) { struct sockaddr_rc addr = { 0 }; int s, status; char dest[18] = "01:23:45:67:89:AB"; // allocate a socket s = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM); // set the connection parameters (who to connect to) addr.rc_family = AF_BLUETOOTH; addr.rc_channel = (uint8_t) 1; str2ba( dest, &addr.rc_bdaddr ); // connect to server status = connect(s, (struct sockaddr *)&addr, sizeof(addr)); // send a message if( status == 0 ) { status = write(s, "hello!", 6); } if( status < 0 ) perror("uh oh"); close(s); return 0; } 

服务器端: –

 #include <stdio.h> #include <unistd.h> #include <sys/socket.h> #include <bluetooth/bluetooth.h> #include <bluetooth/rfcomm.h> int main(int argc, char **argv) { struct sockaddr_rc loc_addr = { 0 }, rem_addr = { 0 }; char buf[1024] = { 0 }; int s, client, bytes_read; socklen_t opt = sizeof(rem_addr); // allocate socket s = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM); // bind socket to port 1 of the first available // local bluetooth adapter loc_addr.rc_family = AF_BLUETOOTH; loc_addr.rc_bdaddr = *BDADDR_ANY; loc_addr.rc_channel = (uint8_t) 1; bind(s, (struct sockaddr *)&loc_addr, sizeof(loc_addr)); // put socket into listening mode listen(s, 1); // accept one connection client = accept(s, (struct sockaddr *)&rem_addr, &opt); ba2str( &rem_addr.rc_bdaddr, buf ); fprintf(stderr, "accepted connection from %s\n", buf); memset(buf, 0, sizeof(buf)); // read data from the client bytes_read = read(client, buf, sizeof(buf)); if( bytes_read > 0 ) { printf("received [%s]\n", buf); } // close connection close(client); close(s); return 0; } 

虽然这适用于单个string,但我无法传输整数。 此外,对于连续的数据stream,我只是有一个for循环运行的服务器和客户端(例如)还是有更好的方法来做到这一点?

实际上你想通过BT RFCOMM套接字发送一个Integer类型的数据,但是你的基本例子需要发送string 。 您的解决方案是简单地将您的号码转换为字符串( C语言中的char数组)。

您的代码来自Albert S. Huang在BT编程伟大BT编程教程中的宝贵作品

将这些更改应用于您的代码。

客户

  // send char integer[4]; // buffer *((int*)integer) = 73232; // 73232 is data which I want to send. //send( cs, integer, 4, 0 ); // send it // send a message to server if( status == 0 ) { status = write(s, integer, 4); if (status == 4){ printf("Send data to server done\n"); } } else if( status < 0 ){ perror("send message to server Failed\n"); } 

它发送73232到服务器。

服务器

 char integer [4]; bytes_read = read(client, integer, 4); /*if( bytes_read > 0 ) { printf("received [%s]\n\n", buf); }*/ printf("int: %x\n", integer[0]);//10 printf("int: %x\n", integer[1]);//1e printf("int: %x\n", integer[2]);//1 printf("int: %x\n", integer[3]);//0 

和服务器成功地收到你的号码的每一个块。 但是,正如你所看到的(我把它们写成评论),它们是以LE的形式存储的。

73232 => 01 1e 10

(我们可以为每个数字添加一个前导0位)

提示 :您可以使用在线十进制到十六进制转换器。 dec_to_HEX

你因为endian而以倒置的形式捕获它们。

在这一点上,你有他们,可以做一些其他的操作。

正如你在例子中所说的,你的号码必须由一个随机函数产生,它的返回值(你的随机数)是通过BT套接字发送的。

我的解决方案基于堆栈的答案