android:手机与BLE-CC41-A蓝牙模块通信

来源:互联网 发布:避孕套 知乎 编辑:程序博客网 时间:2024/06/08 11:52

原创地址:http://blog.csdn.net/bigtree_mfc/article/details/53783585


手机蓝牙的开启、搜索就不再多说,和手机之间的蓝牙通信一样。

需要注意的安卓系统6.0以后使用蓝牙搜索设备需要添加定位权限,6.0以前的系统不需要。


说明:

手机蓝牙与手机蓝牙通信是使用socket方式,这种方式一般都是传统蓝牙,蓝牙8个版本,4.0以前的都是传统蓝牙。

手机蓝牙与蓝牙模块通信是使用GATT协议,这个是BLE蓝牙4.0以上才用到的技术。


关于手机与蓝牙模块通信:下载官方的demo

如果能理解透彻那么关于手机与蓝牙模块通信就完全没有问题了。


蓝牙4.0以后不需要进行配对。


工具:

BLE-CC41-A蓝牙模块、USB转TTL接头、杜邦线。

将蓝牙模用转化接头接到电脑上,通过串口调试工具就可以查看收发的数据了。

USB转TTL在淘宝上有卖,几块钱,一般给的资料会有调试工具的。当然价格便宜肯定会有坑爹的,我买的接头刚开始试了很久都不能用,后来发现问题竟然是USB转TTL出厂的时候把RX和TX竟然印反了!!!

USB转TTL接头引脚:5.0V、VCC、3.3V、TXD、RXD、GND




引脚接法:5.0V接+5V、TXD接TX、RXD接RX、GND接GND。


步骤:

一、建立GATT连接

将上面的demo中BluetoothLeService.java添加到我们自己用的项目中。

首先判断蓝牙打开,然后添加

//联机Intent gattServiceIntent = new Intent(Bluetooth.this, BluetoothLeService.class);bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);//绑定服务

搜索蓝牙设备,显示到ListView中,根据我前面的手机与手机通信,在点击ListView中某一项你要连接的设备,在ListView响应函数中添加

if (BluetoothAdapter.checkBluetoothAddress(al[arg2]))// 检查地址是否有效,正确返回true{mBluetoothLeService.connect(al[arg2]);//al[arg2]为蓝牙mac地址} else {toast("蓝牙地址有问题");}

注:private BluetoothLeService mBluetoothLeService;

添加

private final ServiceConnection mServiceConnection = new ServiceConnection() {        @Override        public void onServiceConnected(ComponentName componentName, IBinder service)         {            mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();            if (!mBluetoothLeService.initialize())             {                     finish();            }        }        @Override        public void onServiceDisconnected(ComponentName componentName)         {            mBluetoothLeService = null;        }};
那么这样就OK了,已经建立了GATT连接,如果现在有蓝牙模块,上面有个提示灯, 在没有建立连接时灯是一直闪烁的,建立GATT连接后灯是保持常亮。

/************************这个是网上的,建立GATT连接*************************/

这里我们讲的是Android设备作为client端,连接GATT Server。
连接GATT Server,你需要调用BluetoothDevice的connectGatt()方法。此函数带三个参数:Context、autoConnect(boolean)和BluetoothGattCallback对象。
调用示例: 
mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
 
函数成功,返回BluetoothGatt对象,它是GATT profile的封装。通过这个对象,我们就能进行GATT Client端的相关操作。BluetoothGattCallback用于传递一些连接状态及结果。
 
注:BluetoothGatt常规用到的几个操作示例:
 
connect() :连接远程设备。
discoverServices() : 搜索连接设备所支持的service。
disconnect():断开与远程设备的GATT连接。
close():关闭GATT Client端。
readCharacteristic(characteristic) :读取指定的characteristic。
setCharacteristicNotification(characteristic, enabled) :设置当指定characteristic值变化时,发出通知。
getServices() :获取远程设备所支持的services。
 
注:
1、某些函数调用之间存在先后关系。例如首先需要connect上才能discoverServices。
2、 一些函数调用是异步的,需要得到的值不会立即返回,而会在BluetoothGattCallback的回调函数中返回。例如 discoverServices与onServicesDiscovered回调,readCharacteristic与 onCharacteristicRead回调,setCharacteristicNotification与 onCharacteristicChanged回调等。
 /******************************************/

二、传输数据、获取数据
demo中只有获取数据显示,也就是读的功能,没有写的功能,需要在BluetoothLeService.java里面添加写
public void wirteCharacteristic(BluetoothGattCharacteristic characteristic,String add) {                if (mBluetoothAdapter == null || mBluetoothGatt == null)         {              Log.w(TAG, "BluetoothAdapter not initialized");              return;          }                  characteristic.setValue(add);//add为传输的数据              mBluetoothGatt.writeCharacteristic(characteristic);             }  

注:private BluetoothGattCharacteristic ch;
private static final UUID MY_UUID = UUID.fromString("0000ffe1-0000-1000-8000-00805f9b34fb");
蓝牙模块中数据传输的uuid:ch
//所有服务的uuidprivate void displayGattServices(List<BluetoothGattService> gattServices) //下拉列表框初始{        if (gattServices == null)         return;                    for (BluetoothGattService gattService : gattServices) // 遍历出gattServices里面的所有服务          {                          List<BluetoothGattCharacteristic> gattCharacteristics = gattService.getCharacteristics();                // 遍历每条服务里的所有Characteristic              for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics)             {                    if(MY_UUID.equals(gattCharacteristic.getUuid()))            {            ch = gattCharacteristic;                                  mBluetoothLeService.setCharacteristicNotification(ch, true);            }            }        }}

三、传输数据给蓝牙模块
String add = et1.getText().toString();
mBluetoothLeService.wirteCharacteristic(ch,add);

四、获取蓝牙模块发送过来的数据
注:tv = (TextView)findViewById(R.id.textview1);
//通过广播接收器接收来自BLEService中的广播发出的信号private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {        @Override        public void onReceive(Context context, Intent intent)         {        //Toast.makeText(DeviceControlActivity.this,"显示",Toast.LENGTH_SHORT).show();            final String action = intent.getAction();            if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) //连接            {                      toast("连接");            }             else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) //断开            {            toast("断开");            }             else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action))             {            toast("列表");            }             else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action))             {            toast("显示");            //显示蓝牙发过来的数据                displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));//显示数据            }        }};

private void displayData(String data) {        if (data != null)         {        String add = "";        add = tv.getText().toString();        if(!add.equals(""))        tv.setText(add + "\n" + data);//显示数据值        else        tv.setText(data);        }}



一些我开发时遇到的问题:

http://bbs.csdn.net/topics/392067215

http://bbs.csdn.net/topics/392064444

http://bbs.csdn.net/topics/392069728


0 0
原创粉丝点击