element14 Community
element14 Community
    Register Log In
  • Site
  • Search
  • Log In Register
  • About Us
  • Community Hub
    Community Hub
    • What's New on element14
    • Feedback and Support
    • Benefits of Membership
    • Personal Blogs
    • Members Area
    • Achievement Levels
  • Learn
    Learn
    • Ask an Expert
    • eBooks
    • element14 presents
    • Learning Center
    • Tech Spotlight
    • STEM Academy
    • Webinars, Training and Events
    • Learning Groups
  • Technologies
    Technologies
    • 3D Printing
    • FPGA
    • Industrial Automation
    • Internet of Things
    • Power & Energy
    • Sensors
    • Technology Groups
  • Challenges & Projects
    Challenges & Projects
    • Design Challenges
    • element14 presents Projects
    • Project14
    • Arduino Projects
    • Raspberry Pi Projects
    • Project Groups
  • Products
    Products
    • Arduino
    • Avnet Boards Community
    • Dev Tools
    • Manufacturers
    • Multicomp Pro
    • Product Groups
    • Raspberry Pi
    • RoadTests & Reviews
  • Store
    Store
    • Visit Your Store
    • Choose another store...
      • Europe
      •  Austria (German)
      •  Belgium (Dutch, French)
      •  Bulgaria (Bulgarian)
      •  Czech Republic (Czech)
      •  Denmark (Danish)
      •  Estonia (Estonian)
      •  Finland (Finnish)
      •  France (French)
      •  Germany (German)
      •  Hungary (Hungarian)
      •  Ireland
      •  Israel
      •  Italy (Italian)
      •  Latvia (Latvian)
      •  
      •  Lithuania (Lithuanian)
      •  Netherlands (Dutch)
      •  Norway (Norwegian)
      •  Poland (Polish)
      •  Portugal (Portuguese)
      •  Romania (Romanian)
      •  Russia (Russian)
      •  Slovakia (Slovak)
      •  Slovenia (Slovenian)
      •  Spain (Spanish)
      •  Sweden (Swedish)
      •  Switzerland(German, French)
      •  Turkey (Turkish)
      •  United Kingdom
      • Asia Pacific
      •  Australia
      •  China
      •  Hong Kong
      •  India
      •  Korea (Korean)
      •  Malaysia
      •  New Zealand
      •  Philippines
      •  Singapore
      •  Taiwan
      •  Thailand (Thai)
      • Americas
      •  Brazil (Portuguese)
      •  Canada
      •  Mexico (Spanish)
      •  United States
      Can't find the country/region you're looking for? Visit our export site or find a local distributor.
  • Translate
  • Profile
  • Settings
1 Meter of Pi
  • Challenges & Projects
  • Design Challenges
  • 1 Meter of Pi
  • More
  • Cancel
1 Meter of Pi
Blog Gr0G - 17 - Remote UI (2)
  • Blog
  • Forum
  • Documents
  • Polls
  • Files
  • Events
  • Mentions
  • Sub-Groups
  • Tags
  • More
  • Cancel
  • New
  • Share
  • More
  • Cancel
Group Actions
  • Group RSS
  • More
  • Cancel
Engagement
  • Author Author: amgalbu
  • Date Created: 26 Dec 2020 9:31 AM Date Created
  • Views 414 views
  • Likes 3 likes
  • Comments 0 comments
  • 1meterofpi
  • gr0g 1
  • 1meter of pi
Related
Recommended

Gr0G - 17 - Remote UI (2)

amgalbu
amgalbu
26 Dec 2020

Here is a list of the posts in this challenge

Gr0G - 01 - Introduction

Gr0G - 02 - Why aeroponics?

Gr0G - 03 - High-pressure system design

Gr0G - 04 - Mechanical design

Gr0G - 05 - Electrical design

Gr0G - 06 - Building the box

Gr0G - 07 - Playing with the Gertbot

Gr0G - 08 - Installing LEDs

Gr0G - 09 - The control board

Gr0G - 10 - Software design

Gr0G - 11 - Building the box (2)

Gr0G - 12 - Building the high-pressure system

Gr0G - 13 - Building the high-pressure system (2)

Gr0G - 14 - Piping

Gr0G - 15 - Improvements

Gr0G - 16 - Remote UI

Gr0G - 17 - Remote UI (2)

Gr0G - 18 - Conclusions

 

Source code available at https://github.com/ambrogio-galbusera/gr0g, https://github.com/ambrogio-galbusera/gr0g-ble-android and https://github.com/ambrogio-galbusera/gr0g-ble

 

Let's now talk about the Android app that connects to the Gr0G through Bluetooth LE

 

Permissions

In order to use Bluetooth features in your application, you must declare two permissions. The first of these is BLUETOOTH. You need this permission to perform any Bluetooth communication, such as requesting a connection, accepting a connection, and transferring data.

The other permission that you must declare is ACCESS_FINE_LOCATION. Your app needs this permission because a Bluetooth scan can be used to gather information about the location of the user. This information may come from the user's own devices, as well as Bluetooth beacons in use at locations such as shops and transit facilities. Many sample apps also include ACCESS_COARSE_LOCATION and BLUETOOTH_ADMIN, but these are not strictly required

The permissions have to be added to AndroidManifest.xml file

 

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ag.gr0g.readwrite"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Device scanning

An activity (ScanActivity) has been implemented to perform a scan for BLE devices. The activity implements the BluetoothAdapter.LeScanCallback interface, required by the startLScan function. Such interface defines just a function, which i invoke whenever a new BLE device is detected

 

    @Override
    public void onLeScan(final BluetoothDevice newDeivce, final int newRssi,
            final byte[] newScanRecord) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mDeviceAdapter.update(newDeivce, newRssi, newScanRecord);
            }
        });
    }

 

The method simply adds a new entry to the mDeviceAdapter, which is the datasource for the list widget

 

The code to initialize the Bluetooth adapter is in the init() method. Here we ensure that BLE is supported and then get the Bluetooth adapter object

 

        if (!BleUtil.isBLESupported(this)) {
             ...
            return;
        }


        // BT check
        BluetoothManager manager = BleUtil.getManager(this);
        if (manager != null) {
            mBTAdapter = manager.getAdapter();
        }
        if (mBTAdapter == null) {
            ...
            return;
        }
        if (!mBTAdapter.isEnabled()) {
            ...
            return;
        }

 

Finally we can start the scan (see startScan() method)

 

mBTAdapter.startLeScan(this);

 

 

Accessing Gr0G data

When a BLE device is clicked in the list, the DeviceActivity is opened. This activity receives the Bluetooth device that has been selected as an extra parameter.

The DeviceActivity has the following layout

 

image

 

The first think to do, is to connect to the device itself

 

mConnGatt = mDevice.connectGatt(this, false, mGattcallback);

 

the mGattCallback is an instance of the class BluetoothGattCallback and implements these methods

 

onConnectionStateChanged

public void onConnectionStateChange(BluetoothGatt gatt, int status,int newState) {
    // handle device connection / disconnection
}

 

It is very common to see a status 133 in this method when trying to connect to a device, especially while you are developing your code. The status 133 can have many causes and some of them you can control:

  1. Make sure you always call close() when there is a disconnection. If you don’t do this you’ll get a 133 for sure next time you try.
  2. Make sure you always use TRANSPORT_LE when calling connectGatt()
  3. Restart your phone if you see this while developing. You may have corrupted the stack by debugging and it is in a state where it doesn’t behave normal again. Restarting your phone may fix things.
  4. Make sure your device is advertising. The connectGatt with autoconnect set to false times out after 30 seconds and you will receive a 133.
  5. Change the batteries of your device. Devices typically start behaving erratically when they battery level is very low.

In my case, I had to apply option 2 and make a connect retry in case of disconnection

 

public void onConnectionStateChange(BluetoothGatt gatt, int status,int newState) {
   // handle device connection / disconnection
   ....
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
   mStatus = newState;

   mConnGatt = mDevice.connectGatt(null, false, mGattcallback, BluetoothDevice.TRANSPORT_LE);
   mStatus = BluetoothProfile.STATE_CONNECTING;

 

onServiceDiscovered

This method is called when a new service has been discovered. In our implementation, the UI controls are properly initialized by storing a Characteristic object in the UI control's tag

 

onCharacteristicRead

This method is called whenever a characteristic read operation has completed. A characteristic is read by code like this (v is a View object). In this app, I created a task (UpdateDataTask) that reads characteristics every 2 seconds

 

BluetoothGattCharacteristic ch = (BluetoothGattCharacteristic) v.getTag();
if (mConnGatt.readCharacteristic(ch)) {
    // success
}

 

All the characteristic values are sent as double. To extract the value, we use the following code

 

final byte[] bvalue = characteristic.getValue();
reverse(bvalue);
double value = ByteBuffer.wrap(bvalue).getDouble();

where

  1. get the array of byte sent by the BLE device
  2. reverse the bytes order in the array
  3. convert the array of byte to a double

 

onCharacteristicWrite

This method is called whenever a characteristic write operation has completed. A characteristic is read by code like this (v is a View object). A characteristic is written when

  1. the value of either temperature setpoint or humidity setpoint is changed
  2. the light switch's status changes
  3. the light release button is clicked

 

BluetoothGattCharacteristic ch = (BluetoothGattCharacteristic) mHumiditySetpoint
   .getTag();
ch.setValue(new byte[] { (byte) Integer.parseInt(mHumiditySetpoint.getText().toString()) });
if (mConnGatt.writeCharacteristic(ch)) {
  setProgressBarIndeterminateVisibility(true);
}

 

Source code

The full source code of the application is available at https://github.com/ambrogio-galbusera/gr0g-ble-android

The app has been developed with Android Studio

 

Useful links

These are some useful links and posts about BLE on Android

https://developer.android.com/guide/topics/connectivity/bluetooth

https://medium.com/@martijn.van.welie/making-android-ble-work-part-1-a736dcd53b02

https://medium.com/@shahar_avigezer/bluetooth-low-energy-on-android-22bc7310387a

  • Sign in to reply
element14 Community

element14 is the first online community specifically for engineers. Connect with your peers and get expert answers to your questions.

  • Members
  • Learn
  • Technologies
  • Challenges & Projects
  • Products
  • Store
  • About Us
  • Feedback & Support
  • FAQs
  • Terms of Use
  • Privacy Policy
  • Legal and Copyright Notices
  • Sitemap
  • Cookies

An Avnet Company © 2025 Premier Farnell Limited. All Rights Reserved.

Premier Farnell Ltd, registered in England and Wales (no 00876412), registered office: Farnell House, Forge Lane, Leeds LS12 2NE.

ICP 备案号 10220084.

Follow element14

  • X
  • Facebook
  • linkedin
  • YouTube