我正在使用Raspberry Pi 3的内部蓝牙,并且正在编写一个c ++代码来连接Windows PC的蓝牙。在PC端,我使用Matlab,并且能够将字节发送到树莓派。但是,当我尝试从树莓派向PC发送字节时,出现以下错误:
“传输端点未连接”
Matlab说“读取失败:在超时时间内未返回指定的数据量”。
另一个有趣的事情是,当我尝试从Matlab发送三个以上的字节时,树莓派只会收到前三个,就好像其余的都不存在一样。如果我连续使用两次读取,则我可以获取6个字节,依此类推。只是指出这个奇怪的事实,因为我认为这可能与我的主要问题有关,这是一个线索。
我也尝试过使用菜单栏上的蓝牙符号手动发送文件,并且可以正常工作。因此,c ++代码应该做一些不同的事情来导致此问题。
我的问题可能是什么原因造成的?如何使用C ++将数据从树莓派发送到计算机?
我的代码如下:(引用的网站:http : //people.csail.mit.edu/albert/bluez-intro/index.html)
#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);
bdaddr_t tempBDADDR = {0};
// bind socket to port 1 of the first available
// local bluetooth adapter
loc_addr.rc_family = AF_BLUETOOTH;
loc_addr.rc_bdaddr = tempBDADDR;
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);
}
int status = 0;
// send a message
if( status == 0 ) {
status = write(s, "hello!", 6);
}
if( status < 0 ) perror("uh oh");
// close connection
close(client);
close(s);
return 0;
}
Matlab方面直截了当:
b = Bluetooth('raspberrypi', 1);
fopen(b);
fwrite(b, uint('1234'));
input = fread(b,6)
fclose(b);
clear('b');
编辑:
只是弄清楚,当我使用以下行时,我没有得到“传输端点未连接”的信息。但是,这仅允许我以客户端身份进行连接,而matlab仅具有客户端类型的连接。因此,现在,我能够从另一个套接字向我的计算机发送数据,而不会出现任何错误,但是无法使用matlab读取它。
status = connect(s, (struct sockaddr *)&addr, sizeof(addr));
只是想通了。留在这里,以防其他人也有帮助。
接受连接后,将返回一个新的描述符(以及一个新的套接字)。这与connect()有很大的不同。所以我在下一行是错误的。
status = write(s, "hello!", 6);
更改为
status = write(client, "hello!", 6);
像魅力一样运作。
(参考:http : //users.pja.edu.pl/~jms/qnx/help/tcpip_4.25_en/prog_guide/sock_advanced_tut.html)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句