1. This example demonstrates how to use the Android Bluetooth 2.0 SDK developed by WITMOTION
2. This routine will demonstrate how to search and connect Bluetooth 2.0 sensors, and control the sensors
3. Please be familiar with the use of Wit-motion Bluetooth 2.0 before using the routine, and understand the protocol of the sensor
Routine directory
libs: Project dependencies
java: Project source code
MainActivity: On the main page of the project, the routine has only one activity, and all logic codes are in this activity
Routine dependency
This routine depends on the wit-sdk project. If you want to port it to your own app, please port the wit-sdk.aar under the lib folder in the routine to your app
This project needs to be connected to Bluetooth, so you need to obtain permission from the customer. If you need to port it to your app, please make sure that your app also applies for the following permissions
AndroidManifest.xml Main manifest file permission statement
Please declare the following permissions in your program's main manifest file
Before using Bluetooth, please call WitBluetoothManager.initInstance to initialize the Bluetooth manager. When initializing the Bluetooth manager, the Bluetooth manager will apply for permission from the user
/*** activity when created** @author huangyajun* @date 2022/6/29 8:43*/@OverrideprotectedvoidonCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);// Initialize the Bluetooth manager, here will apply for Bluetooth permissionsWitBluetoothManager.initInstance(this);// Start search buttonButton startSearchButton =findViewById(R.id.startSearchButton);startSearchButton.setOnClickListener((v) -> {startDiscovery(); });// Stop search buttonButton stopSearchButton =findViewById(R.id.stopSearchButton);stopSearchButton.setOnClickListener((v) -> {stopDiscovery(); });// Calibration buttonButton appliedCalibrationButton =findViewById(R.id.appliedCalibrationButton);appliedCalibrationButton.setOnClickListener((v) -> {handleAppliedCalibration(); });// Start field calibration buttonButton startFieldCalibrationButton =findViewById(R.id.startFieldCalibrationButton);startFieldCalibrationButton.setOnClickListener((v) -> {handleStartFieldCalibration(); });// End magnetic field calibration buttonButton endFieldCalibrationButton =findViewById(R.id.endFieldCalibrationButton);endFieldCalibrationButton.setOnClickListener((v) -> {handleEndFieldCalibration(); });// Read 03 register buttonButton readReg03Button =findViewById(R.id.readReg03Button);readReg03Button.setOnClickListener((v) -> {handleReadReg03(); });// Automatically refresh the data threadThread thread =newThread(this::refreshDataTh); destroyed =false;thread.start();}
Search device
After applying for permission, you can let the Bluetooth manager start searching for Bluetooth devices
Search bluetooth
The following is the code for searching Bluetooth. You need to get the Bluetooth manager, and then call the startDiscovery method. If you need to get the device found by the Bluetooth manager, you need to call registerObserver. After finding the device, you will be notified of the found Bluetooth device through the onFoundSPP method of register Observer
publicvoidstartDiscovery() {// 关闭所有设备// Turn off all devicefor (int i =0; i <bwt901clList.size(); i++) {Bwt901cl bwt901cl =bwt901clList.get(i);bwt901cl.removeRecordObserver(this);bwt901cl.close(); }// 清除所有设备// Erase all devicesbwt901clList.clear();// 开始搜索蓝牙// Start searching for bluetoothtry {// 获得蓝牙管理器// get bluetooth managerWitBluetoothManager bluetoothManager =WitBluetoothManager.getInstance();// 注册监听蓝牙// Monitor communication signalsbluetoothManager.registerObserver(this);// 指定要搜索的蓝牙名称// Specify the Bluetooth name to search forWitBluetoothManager.DeviceNameFilter=Arrays.asList("HC-06");// 开始搜索// start searchbluetoothManager.startDiscovery(); } catch (BluetoothBLEException e) {e.printStackTrace(); } catch (Exception e) {thrownewRuntimeException(e); } }
After starting the search, the onFoundDual method will be called when the device is found. Here, the device is connected immediately after the device is found.
/** * 找到双模蓝牙时 * This method will be called back when data needs to be recorded * * @author huangyajun * @date 2022/6/29 8:46 */ @OverridepublicvoidonFoundDual(BluetoothBLE bluetoothBLE) {// 创建蓝牙2.0传感器连接对象// Create a Bluetooth 2.0 sensor connection objectBwt901cl bwt901cl =newBwt901cl(bluetoothBLE);// 避免重复连接// Avoid duplicate connectionsfor(int i =0; i <bwt901clList.size(); i++){if(Objects.equals(bwt901clList.get(i).getDeviceName(),bwt901cl.getDeviceName())){return; } }// 添加到设备列表// add to device listbwt901clList.add(bwt901cl);// 注册数据记录// Registration data recordbwt901cl.registerRecordObserver(this);// 打开设备// Turn on the devicetry {bwt901cl.open(); } catch (OpenDeviceException e) {// 打开设备失败// Failed to open devicee.printStackTrace(); } }
Stop searching
After starting the search, the Bluetooth manager will not stop the search by itself, you need to call its stopDiscovery method to stop the search
The data of the sensor can be obtained through the getDeviceData method, getDeviceData needs to receive a key value, and this key value is stored in the WitSensorKey class
/*** get data from a device** @author huangyajun* @date 2022/6/29 11:37*/privateStringgetDeviceData(Bwt901cl bwt901cl) {StringBuilder builder =newStringBuilder();builder.append(bwt901cl.getDeviceName()).append("\n"); builder.append(getString(R.string.accX)).append(":").append(bwt901cl.getDeviceData(WitSensorKey.AccX)).append("g \t");
builder.append(getString(R.string.accY)).append(":").append(bwt901cl.getDeviceData(WitSensorKey.AccY)).append("g \t");
builder.append(getString(R.string.accZ)).append(":").append(bwt901cl.getDeviceData(WitSensorKey.AccZ)).append("g \n");
builder.append(getString(R.string.asX)).append(":").append(bwt901cl.getDeviceData(WitSensorKey.AsX)).append("°/s \t");
builder.append(getString(R.string.asY)).append(":").append(bwt901cl.getDeviceData(WitSensorKey.AsY)).append("°/s \t");
builder.append(getString(R.string.asZ)).append(":").append(bwt901cl.getDeviceData(WitSensorKey.AsZ)).append("°/s \n");
builder.append(getString(R.string.angleX)).append(":").append(bwt901cl.getDeviceData(WitSensorKey.AngleX)).append("° \t");
builder.append(getString(R.string.angleY)).append(":").append(bwt901cl.getDeviceData(WitSensorKey.AngleY)).append("° \t");
builder.append(getString(R.string.angleZ)).append(":").append(bwt901cl.getDeviceData(WitSensorKey.AngleZ)).append("° \n");
builder.append(getString(R.string.hX)).append(":").append(bwt901cl.getDeviceData(WitSensorKey.HX)).append("\t");builder.append(getString(R.string.hY)).append(":").append(bwt901cl.getDeviceData(WitSensorKey.HY)).append("\t");builder.append(getString(R.string.hZ)).append(":").append(bwt901cl.getDeviceData(WitSensorKey.HZ)).append("\n");builder.append(getString(R.string.t)).append(":").append(bwt901cl.getDeviceData(WitSensorKey.T)).append("\n"); builder.append(getString(R.string.electricQuantityPercentage)).append(":").append(bwt901cl.getDeviceData(WitSensorKey.ElectricQuantityPercentage)).append("\n");
builder.append(getString(R.string.versionNumber)).append(":").append(bwt901cl.getDeviceData(WitSensorKey.VersionNumber)).append("\n");
returnbuilder.toString();j}
Record data
When the device is turned on, you can call the registerRecordObserver method of bwt901cl, and when the sensor data is updated, bwt901cl will call the onRecord method to notify you of the recorded data
/*** This method will be called back when a Bluetooth 2.0 device is found** @author huangyajun* @date 2022/6/29 10:01*/@OverridepublicvoidonFoundSPP(BluetoothSPP bluetoothSPP) {// Create a Bluetooth 2.0 sensor connection objectBwt901cl bwt901cl =newBwt901cl(bluetoothSPP);// Avoid duplicate connectionsfor(int i =0; i <bwt901clList.size(); i++){if(Objects.equals(bwt901clList.get(i).getDeviceName(),bwt901cl.getDeviceName())){return; } }// Add to device listbwt901clList.add(bwt901cl);// Registration data recordbwt901cl.registerRecordObserver(this);// Turn on the devicetry {bwt901cl.open(); } catch (OpenDeviceException e) {// Failed to open devicee.printStackTrace(); }}/*** This method will be called back when data needs to be recorded** @author huangyajun* @date 2022/6/29 8:46*/@OverridepublicvoidonRecord(Bwt901cl bwt901cl) {String deviceData =getDeviceData(bwt901cl);Log.d(TAG,"device data [ "+bwt901cl.getDeviceName() +"] = "+ deviceData);}
Set sensor
Accelerometer Calibration
Accelerometer calibration can be done by calling AppliedCalibration of Bwt901cl. Remember to unlock the register before accumulator calibration
/*** Have all devices accelerometer calibrated** @author huangyajun* @date 2022/6/29 10:25*/privatevoidhandleAppliedCalibration() {for (int i =0; i <bwt901clList.size(); i++) {Bwt901cl bwt901cl =bwt901clList.get(i);// Unlock registerbwt901cl.unlockReg();// Send commandbwt901cl.appliedCalibration(); }Toast.makeText(this,"OK",Toast.LENGTH_LONG).show()}
Magnetic Field Calibration
You can control the start and end of magnetic field calibration by calling the startFieldCalibration and endFieldCalibration methods of Bwt901cl. After starting the magnetic field calibration, please rotate 2-3 circles around each of the x y z axes of the sensor. If you don’t know the magnetic field calibration, you can consult our technical staff support.
Start Magnetic Field Calibration
/*** Make all devices start magnetic field calibration** @author huangyajun* @date 2022/6/29 10:25*/privatevoidhandleStartFieldCalibration() {for (int i =0; i <bwt901clList.size(); i++) {Bwt901cl bwt901cl =bwt901clList.get(i);// Unlock registerbwt901cl.unlockReg();// Send commandbwt901cl.startFieldCalibration(); }Toast.makeText(this,"OK",Toast.LENGTH_LONG).show();}
End magnetic field calibration
/*** Let all devices end the magnetic field calibration** @author huangyajun* @date 2022/6/29 10:25*/privatevoidhandleEndFieldCalibration() {for (int i =0; i <bwt901clList.size(); i++) {Bwt901cl bwt901cl =bwt901clList.get(i);// Unlock registerbwt901cl.unlockReg();// Send commandbwt901cl.endFieldCalibration(); }Toast.makeText(this,"OK",Toast.LENGTH_LONG).show();}
Read sensor register
This time demonstrates how to read the 03 register of the sensor, use the sendProtocolData method to read the sensor data, and get the data of the register through getDeviceData after reading.
/*** Read the data of register 03** @author huangyajun* @date 2022/6/29 10:25*/privatevoidhandleReadReg03() {for (int i =0; i <bwt901clList.size(); i++) {Bwt901cl bwt901cl =bwt901clList.get(i);// The sendProtocolData method must be used, and the device will read the register value using this methodint waitTime =200;// Send the command of the command and wait for 200ms bwt901cl.sendProtocolData(new byte[]{(byte) 0xff, (byte) 0xAA, (byte) 0x27, (byte) 0x03, (byte) 0x00}, waitTime);
// Get the value of register 03String reg03Value =bwt901cl.getDeviceData("03"); // If it is read up, reg03Value is the value of the register, if not read up, you can enlarge the waitTime, or read it several times
Toast.makeText(this,bwt901cl.getDeviceName() +" reg03Value: "+ reg03Value,Toast.LENGTH_LONG).show(); }}