|
我的蓝牙模块通信问题,PC和开发板之间采用蓝牙通信,能发不能收,附带测试源码
[复制链接]
采用BLUEZ蓝牙协议栈
客户端,开发板上:
#include
#include
#include
#include
#include "bluetooth/bluetooth.h"
#include "bluetooth/l2cap.h"
struct sockaddr_l2 cli_addr;
int clientfd,result,byte;
int cli_len;
char msg[100],i;
char ch[]="00:1f:81:00:02:50";
void cli_init(){
clientfd=socket(PF_BLUETOOTH,SOCK_SEQPACKET,0);
if(clientfd==-1)
{
perror("clinet init error");
exit(0);
}
printf("init socket...\n");
cli_addr.l2_family=AF_BLUETOOTH;
cli_addr.l2_psm=htobs(0x1001); //use this,do not why;
str2ba (ch,&cli_addr.l2_bdaddr);
printf("client inited socket!\n");
}
void cli_connect(){
cli_len=sizeof(cli_addr);
if((result=connect(clientfd,(struct sockaddr *)&cli_addr,cli_len))==-1){
perror("client connect error");
exit(0);
}
printf("have connect!");
}
void cli_send(){
printf("will input\n");
while(scanf("%s",msg))
{
printf("scanfed!\n");
if((byte=write(clientfd,msg,100))==-1)
{
perror("send");
exit(EXIT_FAILURE);
}
printf("%s\n",msg);
}
}
int main(int argc,char *argv[]){
cli_init();
cli_connect();
cli_send();
}
服务端,PC上(虚拟机linux):
#include
#include
#include
#include
#include "bluetooth/bluetooth.h"
#include "bluetooth/l2cap.h"
struct sockaddr_l2 ser_addr,cli_addr;
int serverfd,bindfd,result,ser_listen_msg;
int client,byte,cli_len;
char msg[1024];
char init(){
serverfd=socket(PF_BLUETOOTH,SOCK_SEQPACKET,0);
if(serverfd==-1)
{
printf("init error");
exit(-1);
}
printf("init socket...\n");
ser_addr.l2_family=AF_BLUETOOTH;
ser_addr.l2_bdaddr=*BDADDR_ANY;
ser_addr.l2_psm=htobs(0x1001);
printf("inited socket!\n");
}
void ser_bind(){
bindfd=bind(serverfd,(struct sockaddr *)&ser_addr,sizeof(ser_addr));
if(bindfd==-1)
{ perror("bind error");
exit(bindfd);
}
printf("bind ok!\n");
}
void ser_listen(){
ser_listen_msg=listen(serverfd,10);
if(ser_listen_msg==-1){
perror("listen error");
exit(ser_listen_msg);
}
printf("listening^^\n");
}
void ser_accept(){
cli_len=sizeof(cli_addr);
client=accept(serverfd,(struct sockaddr *)&cli_addr,&cli_len);
if(client==-1)
{
perror("accept error\n");
}
printf("accpent ok!\n");
}
void ser_recv(){
while(1){
if((byte=read(client,msg,1024))==-1)
printf("have no msg");
}
char temp[]="hello"; //here is test
strcpy(msg,temp);
printf("%s\n",msg);
}
void end(){
shutdown(serverfd,2);
shutdown(client,2);
}
int main()
{
init();
ser_bind();
ser_listen();
ser_accept();
ser_recv();
end();
}
|
|