用C写蓝牙通讯程序:扫描、读取、发送
来源:互联网 发布:国债期货模拟软件 编辑:程序博客网 时间:2024/06/05 10:26
在Linux下,通过bluez 蓝牙库可以用C语言轻松实现蓝牙通信。在ubuntu下可以用 apt-get install libbluetooth-dev 安装该库。下面是几个简单示例。
一个简单的扫描程序,得到周边的蓝牙从机设备名和地址:
读和写示例:
一个简单的扫描程序,得到周边的蓝牙从机设备名和地址:
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <sys/socket.h>
- #include <bluetooth/bluetooth.h>
- #include <bluetooth/hci.h>
- #include <bluetooth/hci_lib.h>
- int main(int argc, char **argv)
- {
- inquiry_info *ii = NULL;
- int max_rsp, num_rsp;
- int dev_id, sock, len, flags;
- int i;
- char addr[19] = { 0 };
- char name[248] = { 0 };
- dev_id = hci_get_route(NULL);
- sock = hci_open_dev( dev_id );
- if (dev_id < 0 || sock < 0) {
- perror("opening socket");
- exit(1);
- }
- len = 8;
- max_rsp = 255;
- flags = IREQ_CACHE_FLUSH;
- ii = (inquiry_info*)malloc(max_rsp * sizeof(inquiry_info));
-
- num_rsp = hci_inquiry(dev_id, len, max_rsp, NULL, &ii, flags);
- if( num_rsp < 0 ) perror("hci_inquiry");
- for (i = 0; i < num_rsp; i++) {
- ba2str(&(ii+i)->bdaddr, addr);
- memset(name, 0, sizeof(name));
- if (hci_read_remote_name(sock, &(ii+i)->bdaddr, sizeof(name),
- name, 0) < 0)
- strcpy(name, "[unknown]");
- printf("%s %s\n", addr, name);
- }
- free( ii );
- close( sock );
- 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 addr = { 0 };
- int s, status, len=0;
- char dest[18] = "00:12:01:31:01:13";
- char buf[256];
- // 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));
-
- if(status){
- printf(" failed to connect the device!\n");
- return -1;
- }
-
- do{
- len = read(s, buf, sizeof buf);
-
- if( len>0 ) {
- buf[len]=0;
- printf("%s\n",buf);
- write(s, buf, strlen(buf));
- }
- }while(len>0);
- close(s);
- return 0;
- }
阅读全文
0 0
- 用C写蓝牙通讯程序:扫描、读取、发送
- 用C写蓝牙通讯程序:扫描、读取、发送
- 用C写的邮件发送程序
- 以前用c写的单片机通讯程序
- 微信小程序蓝牙通讯蓝牙模块demo
- 微信小程序蓝牙通讯蓝牙模块demo
- 用C写的一个读取BIOS时间的程序
- 蓝牙通讯模块(C#)
- android 蓝牙通讯实现手机蓝牙的开启,并扫描附近可见的蓝牙设备
- 安卓通讯之《蓝牙单片机通讯助手》②扫描设备、连接设备和双向通讯。
- 蓝牙通讯程序定制5000元
- 用汇编语言写ESMTP邮件发送程序
- 微信硬件蓝牙扫描绑定JSAPI发送数据
- 微信硬件蓝牙扫描绑定JSAPI发送数据
- 蓝牙扫描
- 蓝牙通讯
- C写的一个读取BIOS时间的程序
- 在windows下用C语言写socket通讯实例
- [bzoj1180][CROATIAN2009]OTOCI Link-Cut-Tree
- JMeter-认识GUI界面基本元素及作用
- C语言:函数
- js三种弹出框的方式
- Ignatius and the Princess I(bfs+优先队列+输出路径)
- 用C写蓝牙通讯程序:扫描、读取、发送
- 通俗理解卷积神经网络
- node-webkit开发桌面应用
- 一个真正免费使用的微信营销平台
- 51nod 1681 公共祖先
- nginx+LVS+keepalived实现企业高可用
- golang p2p udp server
- 有效减小apk大小的方式
- DC/OS微服务平台搭建