Android Things – Electricity Monitoring App

For those who may not know, I live in beautiful sunny South Africa (see my tweets for lots of awesome pictures). A few years ago we battled with a lack of electricity. While “load-shedding” is not so common these days, we have numerous unplanned outages. We even have a few of apps that give out schedules when the electricity is scheduled to go off in your area (see here and here).

While these apps serve a purpose, they are not so good when we have unplanned outages.

Which often leaves me asking myself the following questions:

  • Do I have electricity at home right now?
  • If not, how long has the electricity been out for?
  • Is it okay to eat the contents of my freezer?

Introducing “Electricity Monitor”…

I decided to use a Raspberry Pi 3 running Android Things and Firebase Realtime Database to monitor the electricity in my house.

Mainly because Firebase has a VERY powerful tool for monitoring if a client is connected to your Realtime database or not. By leveraging the onDisconnect()  method on the Firebase Realtime database, the server can automatically change some data (or log a time) when a client disconnects from it.

Setup Requirements

In order to get the app running yourself, you need to:

  1. Checkout the repository here.
  2. Create a new Firebase Project here.
  3. Download the google-service.json file from the Firebase Console to both the app folder and the companion-app folder.
  4. Set the Realtime database rules to be read and write for everyone (Firebase Console -> Database -> Rules). (WARNING: This means there is NO security on our database – you should not have these rules in production)
  5. Deploy the “app” module to the Raspberry Pi or equivalent Android Things device (you need to make sure you have setup your Pi with the Android Things OS).
  6. Deploy the “companion-app” module to your phone.
  7. If you have electricity, you will see a house with lights on and the accumulated time you have had power for. If you don’t have electricity, the Raspberry Pi will lose its power source and trigger the onDisconnect()  callback on the Firebase server. This will then show up in our “companion-app” , it will display how long the electricity has been off for.

There you have it, a way to monitor your power at home using Android Things and Firebase!

Yes I know…

  • There are easier ways to monitor your power at home.
  • This is basically monitoring my Pi’s connection to the internet and not power, which in most cases will be accurate enough for me as I am hardly without internet. (I guess this could be rebranded as – “Do I have Internet at home?”)
  • Yes there is no security on the database right now. Luckily it is not controlling my power and its just a sample (Pull requests are welcome 🙂).
  • You might not understand the need for this app, which is okay, it is useful for me and hopefully fellow South Africans 😃


If you enjoy my blog posts, please consider buying me a cupcake!

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.


Android Things – Building a Distributed Piano with Nearby Connections API

In the previous post, we had a short introduction to some hardware basics for the Software Engineer. We learnt about some different components and how to create a blinking LED with Android Things. In this blog post, we will learn to build a distributed piano with Android Things, a Piezo Speaker and Google’s Nearby API.

Hardware setup for an Android Things Distributed Piano:

You will need:

In order to create the speaker component, set up your breadboard with the piezo by following the diagram below:

Distributed Piano Piezo Speaker Setup
Distributed piano piezo speaker setup

Attach the speakers to a PWM pin (red line in this diagram) and to a GND pin to complete the circuit.

If you remember from the previous blog post, we used the GPIO pin to send an on/off signal to the LED. Because the speaker requires us to send different notes to it, a simple on/off wouldn’t work in this case, which is why we use a PWM pin.

PWM (Pulse Width Modulation) is a technique used to encode a message into a pulsing signal. Its main use is to control the power supplied to electrical devices. PWM is used for things such as controlling servo motors or controlling a piezo.

Software Component

Once the hardware is set up, we can move onto creating the piano apps. The descriptions below will highlight the important parts, the full source code can be found here.

We will create two apps, one that will run on the Android Things compatible board and the other that will act as the companion piano app.

Android Things App

  1. Once we have created a project, make sure to include the dependencies for Android Things, Google Play Services and the speaker driver in your build.gradle. In your AndroidManifest.xml, include the permission to ACCESS_NETWORK_STATE  as we will need this whilst using the Nearby API. Define the SERVICE_ID and make sure your PianoActivity  is set to be the IOT_LAUNCHER.

  2.  In the PianoActivity, we will broadcast that we are allowing “nearby connections” on this device. This code is based off the sample provided here for nearby connections.

  3. On receiving a message from the nearby API, translate the message into a frequency that the speaker will play. This example is using the PWM speaker driver from here.

    That is all that we require for the Android Things component.

Companion Piano Player App

  1. Create a module inside your current project for the companion app. This app will need to include the Nearby Connections API dependency too.
  2. In the layout xml file, we will include a keyboard view and a scrolling bar to scroll the keyboard.  I have extracted the KeyboardView  from the repository that can be found here.
  3. In the activity, create a GoogleApiClient and start listening for any connections that are advertising themselves. For simplicity, we will just connect to the first endpoint that is discovered.

  4. Obtain a reference to the KeyboardView and attach a listener which will trigger when the notes are pressed on and off.
  5. When a note is pressed send a message via Nearby API with the corresponding note frequency to the connected Raspberry Pi. Send a “stop” signal, when the KeyboardView listener detects that the note has stopped playing.

That is how you can make a distributed piano using Android Things. For the full source code check the github repository here.


By using Android Things and the Google Nearby API we could quite easily create a distributed piano. This post demonstrated how easily you can build your own Android Things Piano.

If you manage to play something awesome with this example, please share it with me on twitter @riggaroo. Check this Sia cover by Gautier Mechling:

If you want to get updates from this blog, be sure to subscribe below:

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Android Things – Hardware Basics for the Software Engineer

Android Things is the new kid on the block. It is Google’s embedded platform designed specifically for use with low-powered, IoT (Internet of Things) devices. The Android Things dev preview is available for a few different IoT boards, such as the Raspberry Pi 3, the Intel® Edison and the NXP Pico i.MX6UL.

As someone who has never worked with circuits, I had a bit of a steeper learning curve than others when tinkering with Android Things.  I have studied all the theory around circuits and how they work but we never actually had hands on experience creating circuits. Besides that, school was a long time ago, so I needed to brush up on my theory too.

I think it is important to understand the basics of circuits and hardware components before diving in head first into Android Things development. This post will explain the basics of circuits, hardware components and how we can use this knowledge to build a simple blinking LED with Android Things.

Hardware Components

There are different parts you would typically need to build something with Android Things (or any other IoT platform for that matter) depending on what you want to build.

Breadboard – This is your construction base for prototyping electronics. It allows you to connect different components and wires to create a circuit. When you are finished prototyping, you would typically solder your components together and not use a breadboard anymore. The columns on the edges of the breadboard are connected vertically by conductive metal strips, and the inner rows are connected horizontally. Read more about breadboards here.


Jumper WiresUsed to connect the components of a breadboard together and to connect an IoT board (Raspberry Pi, Arduino etc) to the breadboard.

Jumper Wires
Jumper Wires

Resistors – Components that are used to resist the flow of electrical energy. It converts some of the electrical energy into heat. Resistors can have different resistance. It is important to calculate and use the correct resistor when building circuits. The stripe markings on a resistor reflect the resistance measure. More info on how to calculate resistor values can be found here.


LEDs – Components that convert electrical energy into light energy. LEDs (or Light Emitting Diodes) are polarized components, this means they only allow electricity to flow in one direction. The short leg of the LED is called a cathode(-) and will connect to ground. The long leg of the LED is an anode(+) and will connect to power.

LEDs – Light Emitting Diodes

Push Switch – Component which allows electricity to flow between its two contacts. When the switch is pushed down, the circuit is closed. When the switch is up, the circuit is open. 

Push Switch
Push Switch
Push Switch
Push Switch

And many more components!

Power Calculations

When building a circuit, you need to do some calculations before plugging components into one another. For example, an LED can only handle certain a certain amperage (about 0.023A). If you provide more amps than it can handle, you can risk damaging your LED. This is where resistors come in. In order to build a basic circuit where we have a blinking LED, we need to do some calculations as to what resistor we should use.

This is where Ohm’s Law comes in handy.  Ohm’s Law states that the current through a conductor between two points is directly proportional to the voltage across the two points. This law will help us calculate the resistors we should use when creating our circuits.

Ohm's Law
Ohm’s Law

Ohms Law: V = I * R

This diagram translates into 3 different equations: V = I * R or I = V/R or R = V/I, where V is Voltage (volts), I is Current (amps) and R is Resistance (ohms).


With the Raspberry Pi 3 (and the other Android Things supported boards), there are a couple of GPIO (general purpose input output) pins that give us a physical interface between the Pi and our breadboard. The pins allow us to interact with different components and receive and send information to them. Each board is configured differently and the pins themselves provide different functionality. To understand how these GPIO pins work for each board, you should look at the manufacturer’s pinout diagram.

For example the pinout diagram for the Raspberry Pi 3 can be seen below:

Raspberry Pi 3 Pinout
Raspberry Pi 3 Pinout – Source –

There are 40 pins on the Raspberry Pi 3 and you can see they have different functions. Some pins provide power, some are ground and others will be used for receiving or sending values to our circuit’s components.

Basic circuit for a blinking LED with Android Things

To create the blinking LED example, we need to create a circuit. In this example, we will be using the Raspberry Pi 3. Using the Fritzing tool, I have created this example circuit that we want to build using our components.

Android Things - Raspberry Pi 3 and Blinking LED
Android Things – Raspberry Pi 3 and Blinking LED

In the diagram above, the pins correspond to the Raspberry Pi pinout diagram shown earlier. In this example, we have used a 220Ω resistor, an LED and some jumper wires to connect them all together. We are supplying the circuit with 5V of power from the Raspberry Pi 3.

When applying Ohm’s Law, we can see that the amps that will flow through the LED is I = 5V/220Ω which means I = 0.023A or 23 milliamps (23mA). This value is just about the max you can safely use with the LEDs, which is why we chose a 220Ω resistor. Some LEDs can handle different currents, it is worth checking out the specs for the LED you are using.

When setting up the above circuit with the Raspberry Pi 3, it is important to ensure the pins are used in the correct place as we mentioned before, since the pins have different uses. Make sure to connect the BCM6 pin (as indicated in the pinout diagram) to the 220Ω resistor.

It is also important to place the LED correctly into the breadboard, with the anode(+) (longer leg) connecting to power and the cathode(-) (shorter leg) to ground, otherwise you might not see a blinking LED.

The LED will not blink until we deploy an app to the Raspberry Pi. However, we can test that the circuit closes by connecting it to the 5V power directly instead of the BCM6 pin and the light should stay on at this point (but be sure to reconnect it to the BCM6 pin so that the example code will run).

The connected components on the breadboard can also be viewed as a simple circuit diagram which may be easier to understand:

Circuit Diagram - Android Things
Circuit Diagram – Android Things

Creating a blinking LED Android Things app

We have covered how to set up a basic circuit and discussed some hardware components. Now we need to start making the LED blink. In order to do this, we will create an Android app that sends signals via the Raspberry Pi to make the LED blink.

We need to first install Android Things on our Raspberry Pi 3. The official guide on the Android Things site is great at explaining how to do this, so I won’t go into that detail here. Once we have deployed the Android Things OS and connected to the device via ADB, we can create the project.

  1. Open Android Studio, click “Create New Project” and then create a project using a blank activity named BlinkingActivity
  2. Once our project is created,  add the Android Things dependency. In your app level build.gradle:
  3. Add the <uses-library>  tag into AndroidManifest.xml to indicate that this app requires the Android Things libraries on the device.
  4. Specify the BlinkingActivity to be the launcher activity in the AndroidManifest.xml. This indicates that the activity will run by default when the device is turned on.
  5. We will use the PeripheralManagerService  to control the behaviour of our LED. Open the connection to the pin in onCreate  and close the connection in onDestroy . Set the initial direction of the pin to be DIRECTION_OUT_INITIALLY_LOW which means we are using the pin as an output pin and initially it should be a low voltage supplied to it.
  6. To make the LED blink, we will create a  Handler which we post messages to every 500ms to change the state of the LED. We post to the handler in onCreate . Inside the handler, we invert the current value of the ledGpio  object by calling ledGpio.setValue() . This will blink the LED.
  7. Make sure your device is connected and deploy the app to the device. You should see a blinking LED!The code for this tutorial can be found here:


Android Things is an exciting IoT platform to start prototyping with. The ability to access Google APIs on this platform and use the Android development tools (such as Android Studio) is what differentiates this platform from the other IoT platforms. This blog post serves as a starting point for understanding different hardware components and how to start interacting with them with Android Things.

If you liked this blog post, please consider subscribing for more!

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Thanks to  @joshliebe and @blundell_apps for reviewing this blog post.


How to Stage Rollout Features using Firebase Remote Config (Android & iOS)

The Google Play Store has a great feature called “Staged Rollout“. It allows you to slowly release your app to a percentage of your user base. This feature is not available on the iTunes App Store. Using Firebase Remote Config, we can do much more than just stage rollout an entire app – we can stage rollout individual features within an iOS or Android app. 

By using the Google Play Store staged rollout feature, we can see how well a new version of our app is performing in the field without impacting our entire user base.

This is how it works: When uploading an APK on the Google Play Console, selecting the dropdown caret next to the giant Publish Now button allows publishing your app as a staged rollout. You can then choose a percentage of your user base that will receive the update. Random users will be chosen from this percentage and will have the update available to them for download.Staged Rollout in Google Play Store

The staged rollout feature on the Google Play Store has helped my team detect issues that weren’t found during the testing or development phase.

After using the staged rollout feature for a while, I assumed this was a standard feature and when asking iOS developers, it became clear to me that this isn’t available on iTunes.

When I was using Firebase Remote Config, I found something extremely handy. By leveraging the User in Random Percentile conditional, you can easily achieve a similar type of staged rollout in your iOS and Android apps without relying on the app stores to do it for you.

In this blog post, we will cover how to implement a staged rollout feature in your apps, focusing on the Android implementation (but iOS is very similar). If you are interested, check out my previous post on “A/B Testing your app using Firebase Remote Config“.[adwords_square]

Create feature flag and staged rollout conditional

  1. To set up your Firebase Project – follow the instructions here for Android and here for iOS.
  2. Navigate to Remote Config on the Firebase Dashboard. Create a conditional and use the “User in Random Percentile” to target 0 – 10% of your users. Name this conditional relative to the  parameter that you are going to define next.Staged Rollout percentage in Firebase Conditional
  3.  Create a new parameter called “feature_add_friends“, set the default value to false and the value for the above created conditional to true. Staged Rollout conditional

Use the feature flag

Within your app, you can now consume the parameter as you would any other variable from Firebase Remote Config and the server will decide if you should see the feature or not.

The part you should be interested in, is line 38 – 45, where we fetch the parameter and use it in the app. [adwords_square]

Rollout to more users

Once your feature has been released onto the app stores and users start to download it, you will be able to gauge how well it is performing. When you gain more confidence with your feature, you can slowly increase the percentage to more users.Increase staged rollout percentage.

When you are happy for all your users to use the new feature, you can simply remove the conditional altogether.

That is all you need to do in order to stage rollout a feature using Firebase Remote Config! Let me know what you think on Twitter – @riggaroo.

If you enjoyed this blog post, please consider buying me a cupcake!



A/B Test your App using Firebase Remote Config

Last week I was in Nairobi and Cape Town giving a talk on Remote Config and Test Lab in Firebase. I had such a great time and thought I should share some of the content I presented online.

What is A/B Testing?

A/B testing is the process of experimentally testing your UI on different audiences in order to determine the best (or most profitable) user experience.  Firebase Remote Config enables us to do A/B testing by allowing us to randomly segment our app audiences easily.

Example A/B Test

In this example, we are going to test out a different version of a checkout button that we have in our app.

A/B test we will run using Firebase Remote config.

For variant A of the experiment, we want to show a pink “Checkout” button. For variant B we want to show a blue “Cart” button. For the rest of our users, we will show the original “Finished” button.

Now for the fun part, setting up the experiment![adwords_square]

Set up Firebase Remote Config for A/B Testing

  1. Create a Firebase Project.
  2. Head to Remote Config section.
  3. Create a parameter – let’s call this parameter experiment_variant. Make the default value return no_experiment.Setting up parameter in Firebase Remote Config
  4. Click “Add value for Condition”. Then click “Define a new Condition”. Give it the name “Variant A”. We will select “User in Random Percentile” as the conditional. We will then choose the users from 0% – 10% that will receive variant A as their experiment. Click “Create Condition“.Adding a A/B Testing conditional to use with Firebase Remote Config
  5.  Now you will see that conditional appear for the experiment_variant parameter. Assign  variant_a to the value that should be returned for that variant.Conditional in Firebase Remote Config
  6. We will repeat the same for variant B, by creating a conditional for the users from 10% – 20%. This means that only 20% of the entire user base will be running the experiment and 80% will see no change in the standard UI. The percentage of the experiment is totally up to you. Variant B for Firebase Remote ConfigThen return variant_b for the parameter value:All variants in Firebase Remote Config
  7. Make sure to update and publish the changes. We have completed the server side setup of our experiment.

Setting up the A/B Test on Android Devices

Once you have configured the server, the hard part is done! The next section will cover how to get setup for Android but the code is really similar for iOS too – so don’t be deterred!

  1. In your android app, make sure you have the Firebase dependencies set up. Place the following in your top level build.gradle:
  2. Add the following in your app level build.gradle:
  3. Download google-services.json file from Firebase console and add it to your app/ folder.
  4. Create a remote config defaults file in the res/xml folder like the one below. This file will be used if the user has no internet connection when loading up the app for the first time.
  5. Initialise Firebase remote config. This is also where we set the defaults to the file we created in the previous step.
  6. Then fetch the remote config values. Firebase will automatically cache the values for the specified time that you provide. By default, it caches for 12 hours.
  7. In order to run our experiment, we should fetch the experiment_variant parameter from our remote config and use it in our app.

    In this example, we fetch the parameter and set a custom analytics user property with the variant that has been assigned to the current device. This will allow us to properly track how our A/B test is performing.  In the conditional, we are free to make the changes we want to the app. We can set the text to different things and change the colours depending on the variant.
  8. Now that we have the experiment running, we need to track when a user clicks on the “Checkout” button in order to determine which button variant a user is more likely to tap on. We then log the event to Firebase analytics which will include the user property that we set previously.

    It is worth noting that there are a bunch of default events and parameters that you can make use of with Firebase Analytics. [adwords_square]
  9. In order to determine the success of your A/B test, you need to analyse your data to decide which UI is the most successful. After logging into the console, we can see there were 24 counts of the “CheckoutClicked” event.firebase_analytics_ab_testingAfter applying the filter for the user property “Experiment = Variant A”, we can see that 19 of the 24 clicks were from variant A of the experiment (granted this was just me clicking around in my sample app – but you get the idea).

Variant A filters - Remote config

For larger data sets where the result of the experiment may not be obvious at first, you can export your events to BigQuery. This will allow you to make more complex deductions from your experiments.

For now at least, we know the clear winner (in this very large test 😬) is Variant A – the pink checkout button wins!

AB Testing variant A winner

There you have it, an easy way to experiment with your UI using Firebase Remote Config.

Sample code can be found here (It is not very complex as all the hard work is done by the Firebase APIs.) 😊

Happy AB Testing!

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.