Chinaunix首页 | 论坛 | 博客
  • 博客访问: 84425
  • 博文数量: 25
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 11
  • 用 户 组: 普通用户
  • 注册时间: 2015-07-24 11:34
文章分类
文章存档

2015年(25)

我的朋友

分类: 嵌入式

2015-07-24 16:44:12

在Linux下,通过bluez 蓝牙库可以用C语言轻松实现蓝牙通信。在ubuntu下可以用 apt-get install libbluetooth-dev 安装该库。下面是几个简单示例。

一个简单的扫描程序,得到周边的蓝牙从机设备名和地址:

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <sys/socket.h>
  5. #include <bluetooth/bluetooth.h>
  6. #include <bluetooth/hci.h>
  7. #include <bluetooth/hci_lib.h>

  8. int main(int argc, char **argv)
  9. {
  10.     inquiry_info *ii = NULL;
  11.     int max_rsp, num_rsp;
  12.     int dev_id, sock, len, flags;
  13.     int i;
  14.     char addr[19] = { 0 };
  15.     char name[248] = { 0 };

  16.     dev_id = hci_get_route(NULL);
  17.     sock = hci_open_dev( dev_id );
  18.     if (dev_id < 0 || sock < 0) {
  19.         perror("opening socket");
  20.         exit(1);
  21.     }

  22.     len = 8;
  23.     max_rsp = 255;
  24.     flags = IREQ_CACHE_FLUSH;
  25.     ii = (inquiry_info*)malloc(max_rsp * sizeof(inquiry_info));
  26.     
  27.     num_rsp = hci_inquiry(dev_id, len, max_rsp, NULL, &ii, flags);
  28.     if( num_rsp < 0 ) perror("hci_inquiry");

  29.     for (i = 0; i < num_rsp; i++) {
  30.         ba2str(&(ii+i)->bdaddr, addr);
  31.         memset(name, 0, sizeof(name));
  32.         if (hci_read_remote_name(sock, &(ii+i)->bdaddr, sizeof(name),
  33.             name, 0) < 0)
  34.         strcpy(name, "[unknown]");
  35.         printf("%s %s\n", addr, name);
  36.     }

  37.     free( ii );
  38.     close( sock );
  39.     return 0;
  40. }

读和写示例:

  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <sys/socket.h>
  4. #include <bluetooth/bluetooth.h>
  5. #include <bluetooth/rfcomm.h>

  6. int main(int argc, char **argv)
  7. {
  8.     struct sockaddr_rc addr = { 0 };
  9.     int s, status, len=0;
  10.     char dest[18] = "00:12:01:31:01:13";
  11.     char buf[256];
  12.     // allocate a socket
  13.     s = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);

  14.     // set the connection parameters (who to connect to)
  15.     addr.rc_family = AF_BLUETOOTH;
  16.     addr.rc_channel = (uint8_t) 1;
  17.     str2ba( dest, &addr.rc_bdaddr );

  18.     // connect to server
  19.     status = connect(s, (struct sockaddr *)&addr, sizeof(addr));

  20.     
  21.     if(status){
  22.         printf(" failed to connect the device!\n");
  23.         return -1;
  24.     }

  25.     
  26.     do{
  27.         len = read(s, buf, sizeof buf);
  28.     
  29.      if( len>0 ) {
  30.          buf[len]=0;
  31.          printf("%s\n",buf);
  32.          write(s, buf, strlen(buf));
  33.      }
  34.     }while(len>0);

  35.     close(s);
  36.     return 0;
  37. }



阅读(1422) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~