你好!欢迎来到深圳市颖特新科技有限公司!
语言
当前位置:首页 >> 技术中心 >> 单片机入门 >> 单片机连接蓝牙4.0心得分享

单片机连接蓝牙4.0心得分享

关键字:单片机 蓝牙 作者:admin 来源:不详 发布时间:2018-05-18  浏览:1

 最近公司要搞一个智能硬件,通过APP连接硬件,发指令达到某些目的,对于从没有接触过蓝牙的小白,简直是两眼一抹黑,于是从网上找例子,找攻略,例子和代码都不是自己想要的,于是只能求助于谷歌API,拿着某翻译,一个个对着看,终于调试成功了,下面直接上思路及代码。

1、从谷歌官网下载一份demo(通用的),对于任何串口,只要符合规范,这个demo都能调试。

2、谷歌官方代码共有4个类,其中两个比较重要,如下:

BluetoothleService 蓝牙服务:里面有蓝牙的连接,写入命令后,蓝牙所返回的协议(这个协议是厂家给你的)

DeviceControlActivity 设备控制类:连上蓝牙后进入这个界面,会出现一大堆服务,及服务的特征

3、了解两个类,接下来我们要连上蓝牙给单片机发送指令,首先打开DeviceControlActivity类,找到如下代码:

//如果该char可写

if ((charaProp | BluetoothGattCharacteristic.PROPERTY_WRITE) > 0) {

LayoutInflater factory = LayoutInflater.from(parent.getContext());

final View textEntryView = factory.inflate(R.layout.dialog, null);

final EditText editTextName = (EditText) textEntryView.findViewById(R.id.editTextName);

final EditText editTextNumEditText = (EditText)textEntryView.findViewById(R.id.editTextNum);

AlertDialog.Builder ad1 = new AlertDialog.Builder(parent.getContext());

ad1.setTitle("WriteCharacteristic");

ad1.setView(textEntryView);

ad1.setPositiveButton("确定", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int i) {

byte[] value = new byte[20];

value[0] = (byte) 0x00;

if(editTextName.getText().length() > 0){

//write string

WriteBytes= editTextName.getText().toString().getBytes();

}else if(editTextNumEditText.getText().length() > 0){

WriteBytes= hex2byte(editTextNumEditText.getText().toString().getBytes());

}

characteristic.setValue(value[0],

BluetoothGattCharacteristic.FORMAT_UINT8, 0);

characteristic.setValue(WriteBytes);

mBluetoothLeService.writeCharacteristic(characteristic);

}

});

ad1.setNegativeButton("取消", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int i) {

}

});

ad1.show();

}

以上这段代码就是写入命令的代码,起初我在这里栽了跟头,发现一件事,直接输入命令,此处的返回和协议文档是对不上的,于是我做了如下修改:

if ((charaProp | BluetoothGattCharacteristic.PROPERTY_WRITE) > 0) {

byte[] bytes = hexStringToBytes("XXXXXXXXXXXX");

// characteristic.setValue(new byte[]{0xXX,0xXX,0xXX,0xXX,0xXX, (byte) 0xB2, (byte) 0xXX});

characteristic.setValue(bytes);

boolean status = mBluetoothLeService.writeCharacteristic(characteristic);

Log.e("shjysoft_info","状态:"+status);

}

先把协议的16进制的字符串变成字节,然后放到特征里面,写进去,然后就成功了,但是没有接触过蓝牙的朋友会有疑问,给哪个服务哪个特征写,这边我也遇到 过,我跑过去问前辈们,前辈们说了一句,一个一个试,没错,你一个一个点,哪个返回正确就是哪个

编辑:admin  最后修改时间:2018-05-18

联系方式

0755-82591179

传真:0755-82591176

邮箱:vicky@yingtexin.net

地址:深圳市龙华区民治街道民治大道973万众润丰创业园A栋2楼A08

Copyright © 2014-2023 颖特新科技有限公司 All Rights Reserved.  粤ICP备14043402号-4