BLE 安卓APP控制LED灯的实现(转)

源:BLE 安卓APP控制LED灯的实现

//注:参考AmoMcu源代码修改。

打开APP,检查蓝牙是否打开

BluetoothAdapter mBluetoothAdapter;

 final BluetoothManager bluetoothManager =(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
       mBluetoothAdapter = bluetoothManager.getAdapter();

// Ensures Bluetooth is available on the device and it is enabled. If not,
// displays a dialog requesting user permission to enable Bluetooth.
if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
   Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
   startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}

蓝牙扫描

private void scanLeDevice(final boolean enable) {
if (enable) {
     // Stops scanning after a pre-defined scan period.
             mHandler.postDelayed(new Runnable() {
                 @Override
                 public void run() {
                     mScanning = false;
                     mBluetoothAdapter.stopLeScan(mLeScanCallback);
                 }
             }, SCAN_PERIOD);

             mScanning = true;
             mBluetoothAdapter.startLeScan(mLeScanCallback);
         } else {
             mScanning = false;
             mBluetoothAdapter.stopLeScan(mLeScanCallback);
         }
     }

连接GATT服务
绑定一个服务

Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
    bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
注:BluetoothLeService.java,属于安卓源代码,可以到网上下载回来。
// Code to manage Service lifecycle.
     private final ServiceConnection mServiceConnection = new ServiceConnection() {
         @Override
         public void onServiceConnected(ComponentName componentName, IBinder service) {
             mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
             if (!mBluetoothLeService.initialize()) {
                 Log.e(TAG, "Unable to initialize Bluetooth");
                 finish();
             }
             // Automatically connects to the device upon successful start-up initialization.
             mBluetoothLeService.connect(mDeviceAddress);
         }
         @Override
         public void onServiceDisconnected(ComponentName componentName) {
             mBluetoothLeService = null;
         }
     };

点击某个特征值的响应:
获取前面的数据,不用再次扫描,由扫描页面得到的数据,传过来的

b=getIntent().getExtras();
 tv_addr.setText(b.getString(EXTRAS_DEVICE_ADDRESS));
 mDeviceAddress=b.getString(EXTRAS_DEVICE_ADDRESS);
 tv_name.setText(b.getString(EXTRAS_DEVICE_NAME));
 mDeviceName=b.getString(EXTRAS_DEVICE_NAME);
 tv_rssi.setText(b.getString(EXTRAS_DEVICE_RSSI));

 lv=(ExpandableListView)this.findViewById(R.id.expandableListView1);
 lv.setOnChildClickListener(servicesListClickListner);

 private final ExpandableListView.OnChildClickListener servicesListClickListner =
           new ExpandableListView.OnChildClickListener() {
               @Override
               public boolean onChildClick(ExpandableListView parent, View v, int groupPosition,
                                           int childPosition, long id) {

                   if (mGattCharacteristics != null) {
                       final BluetoothGattCharacteristic characteristic =
                               mGattCharacteristics.get(groupPosition).get(childPosition);

                       //当前目标特征值
                       target_chara=characteristic;

                       final int charaProp = characteristic.getProperties();

                       if ((charaProp | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
                           mNotifyCharacteristic = characteristic;

                           mBluetoothLeService.setCharacteristicNotification(
                                  characteristic, true);
                       }
                      tv_uuid.setText(characteristic.getUuid().toString());
                      Intent intent=new Intent();
                      b.putString("CONNET_SATE", status);
                      b.putString("UUID", characteristic.getUuid().toString());
                      intent.putExtras(b);
                      intent.setClass(MyGattDetail.this, LEDControl.class);
                      startActivity(intent);

                return true;
                   }

                   return false;

              }

   };

读写特征值的数据
读数据:

private static BluetoothGattCharacteristic myCharacteristic=null;
 private static BluetoothLeService mBluetoothLeService;
 mBluetoothLeService.readCharacteristic(myCharacteristic);

注释:readCharacteristic该函数会调用BluetoothGatt.readCharacteristic(BluetoothGattCharacteristic characteristic)

写数据:
mBluetoothLeService.writeCharacteristic(myCharacteristic);
注释:writeCharacteristic该函数会调用BluetoothGatt.writeCharacteristic(BluetoothGattCharacteristic characteristic)

示例代码:

private char[] buffer =new char [] {0x6F,0x0F,0x0F,0x0F,0x0F,0x0F};
 private void send() {
MyGattDetail.write(ConvertString(buffer));
 }

 private String ConvertString(char buffer[]){
String nRcvString;
     StringBuffer tStringBuf=new StringBuffer ();
     tStringBuf.append(buffer);
     nRcvString=tStringBuf.toString();
     return  nRcvString;
 }

 device_name = (TextView) findViewById(R.id.ledpage_devname);

ledButton1 = (ToggleButton) findViewById(R.id.ledpage_led1);
ledButton1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if(isChecked){
buffer[1]=0x01;
}else{
buffer[1]=0x00;
}
send();
}
});

ledButton2 = (ToggleButton) findViewById(R.id.ledpage_led2);
ledButton2.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if(isChecked){
buffer[2]=0x01;

}else{
buffer[2]=0x00;
}
send();
}
});
ledButton3 = (ToggleButton) findViewById(R.id.ledpage_led3);
ledButton3.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
if(isChecked){
buffer[3]=0x01;
}else{
buffer[3]=0x00;
}
send();
}
});

ledButton4 = (ToggleButton) findViewById(R.id.ledpage_led4);
ledButton4.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
if(isChecked){
buffer[4]=0x01;
}else{
buffer[4]=0x00;
}
send();
}
});

使用ToggleButton控件控制LED:

问题:

使用TI的demo会发现打开一个LED会比较慢,偶尔还会失效。也就是说会掉帧,考虑大之前的所写的关于延时值的设置,如下:

Connection Interval(GAPROLE_MIN_CONN_INTERVAL && GAPROLE_MAX_CONN_INTERVAL)- 连接间隔,在BLE的两个设备的连接中使用跳频机制。两个设备使用特定的信道发送和接收数据,然后过一段时间后再使用新的信道(BLE协议栈的链路层处理信道的切换)。两个设备在切换信道后发送和接收数据称为一个连接事件。尽管没有应用数据被发送和接收,两个设备仍旧会交换链路层数据来维持连接。这个连接间隔就是这个两个连接事件的之间的时间间隔。间隔以1.25ms为单元,连接间隔的范围的6-3200既7.5ms-4s(4000ms)之间。

由此可以看出:间隔小,适用于那些需要快速反应的任务。LED灯需要快速的反应,所以经过设置如下:

// Minimum connection interval (units of 1.25ms, 80=100ms) if automatic parameter update request is enabled

#define DEFAULT_DESIRED_MIN_CONN_INTERVAL     6//80

// Maximum connection interval (units of 1.25ms, 800=1000ms) if automatic parameter update request is enabled

#define DEFAULT_DESIRED_MAX_CONN_INTERVAL     80//800

这样子实时体验就有大大的提升。

时间: 2024-08-28 09:19:30

BLE 安卓APP控制LED灯的实现(转)的相关文章

enc28J60 网页控制LED灯

软件IDE:Arduino 1.6.3 1.库的安装: 从https://github.com/jcw/ethercard 下载源码包,解压,复制ethercard-master文件夹到Arduino的安装目录所在的库文件夹下:D:\Program Files (x86)\Arduino\libraries,并且重命名为EtherCard 2.打开Arduino 复制相关代码,保存,编译,上传. 3.设置电脑ip为192.168.2.2 4.浏览器登录192.168.2.1 参考: lucade

嵌入式Linux学习入门:控制LED灯

记录自己linux学习过程,让自己能够一直坚持下去 1.原理图分析: nLED_1, nLED_2, nLED_4, 给低电平则对应LED灯亮,高电平则对应LED灯灭, S3C2440芯片GPF4-GPF6对应nLED_1, nLED_2, nLED_4, 所以代码里面操作GPF4-GPF6就可以控制LED灯亮灭. 2.写代码前了解事项 第一步:将GPF0-GPF4配置为输出功能 第二步:控制GPF0-GPF4输出低电平 3.编写代码 1 .text 2 .global _start 3 _st

arduino入门学习实现语音控制LED灯

需要的准备的硬件arduino+PC+麦克风实现语音命令控制LED灯的亮灭. 首先需要将写好的arduino程序烧录到arduino uno主板中,下面是代码如下: int val;//定义变量val int ledpin=10;//定义数字接口13 void setup() { Serial.begin(9600);//设置波特率为9600,这里要跟软件设置相一致.当接入特定设备(如:蓝牙)时,我们也要跟其他设备的波特率达到一致. pinMode(ledpin,OUTPUT);//设置数字10

arduino 红外遥控器控制LED灯

/* 日期:2016.9.1 功能:红外遥控器控制LED灯 开,关,闪烁 元件: 跳线公公头 * 5 led, 220欧电阻 红外接收管,红外遥控 接线: 红外灯面向自己从左到右分别接 IO3, GND, 5V LED 负极接GND 正极串联电阻接 IO5 红外1-9口编码: FF30CF 1 FF18E7 2 FF7A85 3 FF10EF 4 FF38C7 5 FF5AA5 6 FF42BD 7 FF4AB5 8 FF52AD 9 参考:http://www.arduino.cn/threa

socket通信——多角度控制LED灯亮灭

今天以物联网网关(网关链接)以服务器,在多个客户端就做一个非常简单的功能:点亮或熄灭网关上的LED灯.目前想到了三种方式,分别是:TCP&UDP测试工具.自编Java客户端和Mono Android客户端.相信这会很有意思的. 1.服务器端 在使用或编写客户端之前,首先来看看服务器端代码,其专门通过串口烧进网关内部 OutputPort led = new OutputPort((Cpu.Pin)GPIO_NAMES.PF8, false); Socket sc; Socket ss = new

云中树莓派(4):利用声音传感器控制Led灯

云中树莓派(1):环境准备 云中树莓派(2):将传感器数据上传到AWS IoT 并利用Kibana进行展示 云中树莓派(3):通过 AWS IoT 控制树莓派上的Led 云中树莓派(4):利用声音传感器控制Led灯 1. 声音传感器及其配置 声音传感器如下图所示: 将 VCC 引脚接入树莓派 5V 引脚,将 GND 引脚接入树莓派 GND 引脚,将 OUT 引脚接入树莓派 GPIO20. 要注意,模块在环境声音强度达不到设定阈值时,OUT输出高电平(1),当外界环境声音强度超过设定阈值时,模块O

利用DoHome APP和音箱控制LED灯实验参考步骤

准备材料: Arduino Uno 一块 Arduino 扩展板        购买链接 DT-06模块一个       购买链接 安卓手机一个 小度音箱一个 小灯珠一个 杜邦线若干 1.DT-06固件的烧录 1.1打开ESP模块下载工具ESPFlashDownloadTool,选择需要下载的固件,填写下载地址,推荐使用  ESP8266 Download TOOL,配置信息如下: 1.2 选择实际的串口,选择下载速度 1.3点击ERASE,先插除,再点击START,开始下载 工具下载及详细请看

TI-RTOS 控制LED灯

TI将FreeRtos放在自家芯片上,于是得到了TI-RTOS,两者的区别我还不太清楚,近日因为项目需要,开始试用TI-RTOS,先来一个点灯的实验吧,算是 hello world. 这次手上的板子是 CC1310 LaunchPad Rev 1.3, 上面有两个灯,两个按键,照常理先调灯的驱动会更简单些.打算做成一个灯亮,一个灯1秒闪一次. 这样的功能一般是和定时器,IO打交道,不过在os上,定时可以暂时用task_sleep来代替,好在TI-RTOS默认启用这个模块的,用起来相当方便. IO

arduino + ld3320语音识别模块实现语音控制LED灯

材料准备: 1.arduino UNO开发板 2.LD3320语音识别模块 面包板,杜邦线,LED灯等 接线: LE3320     ----      arduino 1.3.3v(两个都接)  --  3.3v 2.GND(两个都接)  --  GND 3.MISO  --  D12 4.MOSI  --  D11 5.SCK  --  D13 6.NSS  --  D4 7.NC  --  空着 8.RST  --  D9 9.WR  -- GND 10.IRQ  -- D2 8号引脚串联