element14 Community
element14 Community
    Register Log In
  • Site
  • Search
  • Log In Register
  • 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 & Tria Boards Community
    • Dev Tools
    • Manufacturers
    • Multicomp Pro
    • Product Groups
    • Raspberry Pi
    • RoadTests & Reviews
  • About Us
  • 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
      • Japan
      •  Korea (Korean)
      •  Malaysia
      •  New Zealand
      •  Philippines
      •  Singapore
      •  Taiwan
      •  Thailand (Thai)
      • Vietnam
      • 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
Raspberry Pi Projects
  • Products
  • Raspberry Pi
  • Raspberry Pi Projects
  • More
  • Cancel
Raspberry Pi Projects
Blog How to Build your Own Security System Using Android Things
  • Blog
  • Documents
  • Events
  • Polls
  • Members
  • Mentions
  • Sub-Groups
  • Tags
  • More
  • Cancel
  • New
Join Raspberry Pi Projects to participate - click to join for free!
  • Share
  • More
  • Cancel
Group Actions
  • Group RSS
  • More
  • Cancel
Engagement
  • Author Author: anpivey
  • Date Created: 15 Aug 2018 3:45 PM Date Created
  • Views 1728 views
  • Likes 4 likes
  • Comments 4 comments
  • security systems
  • android things
  • raspberri pi
  • security iot
  • iot
  • raspberry_pi_projects
  • pir sensor
Related
Recommended

How to Build your Own Security System Using Android Things

anpivey
anpivey
15 Aug 2018

image

In this tutorial, we will send an event to Wia using Android Things.

Components

  • Raspberry Pi (We used a Raspberry Pi 3 Model)
  • PIR Sensor
  • USB Cable
  • Jumper wires

You will also need Android Studio and a Wia account. You can download the latest version of Android Studio here.

Wia is a cloud platform to support your Internet of Things devices. You can sign up or login here.

Getting Started

First, we need to install Android Things onto the raspberry pi. Click here to go to the Android Things console, and sign in using a google account.

Create a product and choose Raspberry Pi as the SOM, name it what you like, and save.

image

 

You will be taken to this page. Click on your model:

 

image

Click on NEW and choose Start from scratch from the drop down menu.

Name your build. Keep all of the default settings by clicking Next on each step. Then click create build.

Your build is now available for download. Download the file and choose production.

image

Once the file has downloaded, unzip it. The file will take a moment to expand. You will get a .img file.

image

Burning the SD Card

Next, burn the image to the SD card. We used Etcher to do this. You can download Etcher here.

Insert the SD card into your computer and open Etcher. Select the image we just downloaded and select the SD card, then click Flash. Then, remove the SD card from your computer and insert it into the raspberry pi.

image

Connect the raspberry pi to an ethernet cable and use a USB to connect the raspberry pi to a 5V power source. Use an HDMI to connect the raspberry pi to a monitor and obtain the IP address. You will need the IP address later.

Wiring the Hardware

 

image

Use this diagram to help you connect the hardware:

image

Connect a USB to the raspberry pi and your computer. Connect the HDMI cable to a monitor and the raspberry pi.

Set up your space in Wia

If you don't already have a Wia account, you can sign up here, it's free.

In the Wia dashboard, click Create a New Space. In the left sidebar, navigate to Devices and click Add Device. We used the Raspberry Pi 3 Model B. Name your device anything you like.

image

Once your device is added, navigate to the Configuration tab. Here you will find your device's secret key, which starts with d_sk. You will need this key later.

image

 

Development

Open Android Studio and start a new project. Fill in the required fields:

image

 

Click next. For the target devices, select only Android Things

image

Click next. Choose Empty Activity
image

Click next and then Finish.

In the left sidebar, click Gradle Scripts > build.gradle (Module: app), and enter this line of code in dependencies:

implementation 'io.wia:wia-android-sdk:0.3.1'

Your screen should look like this:

image

 

Now, it's time to connect the raspberry pi to our project. You need to know the IP address of the raspberry pi for this step. In the terminal, run this command:

adb connect Your-Raspberry-Pi-IP-address)

Open Android Studio. Copy and paste this code into MainActivity.java:

 

import android.app.Activity;

import android.os.Bundle;

 

 

import android.util.Log;

 

 

import com.google.android.things.pio.Gpio;

import com.google.android.things.pio.PeripheralManager;

 

 

 

 

import io.reactivex.Observable;

import io.reactivex.android.schedulers.AndroidSchedulers;

import io.reactivex.schedulers.Schedulers;

import io.wia.Wia;

 

 

import io.wia.WiaEvent;

 

 

 

 

public class MainActivity extends Activity implements MotionsSensor.Listener {

 

 

    private static final String GPIO_PIN = "BCM18";

    private PirMotionSensor motionSensor;

    private static final String TAG = "TEST";

    private Gpio mGpio;

 

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        PeripheralManager pms = PeripheralManager.getInstance();

        try {

            mGpio = pms.openGpio(GPIO_PIN);

            motionSensor = new PirMotionSensor(mGpio, this);

            motionSensor.startup();

        } catch (Exception ex) {

            Log.d(TAG, "failing", ex);

        }

        Log.d(TAG, "IN ON CREATE FUNCTION.");

 

 

        Wia.initialize(new Wia.Configuration.Builder(this.getApplicationContext())

                .server("https://api.wia.io/v1")

                .build()

        );

        //replace this with your own device secret key

        Wia.accessToken("your-device-secret-key");

 

 

    }

 

 

    @Override

    public void onMovement() {

        Log.d(TAG, "in onMovement");

        Log.d(TAG, "MOVEMENT DETECTED");

        Observable<WiaEvent> result = Wia.createEvent("motion");

        result.subscribeOn(Schedulers.io())

                .observeOn(AndroidSchedulers.mainThread())

                .subscribe(response -> {

                    Log.d(TAG, "In onMovement function");

                }, error -> {

                    Log.d(TAG, "ERROR IN MOVEMENT EVENT");

                });

    }

 

In the code, locate this line, around line 45 in Android Studio:

 

//replace this with your own device secret key

        Wia.accessToken("your-device-secret-key");

 

Change "your-device-secret-key" to your own device secret key. This can be found in the Wia Dashboard in your space > device > configurations. The key starts with d_sk.

In the left hand menu, navigate to App > Java and right click on the package name. Choose New > New Java Class and name it PirMotionSensor.

image

 

Then, copy and paste this code into the class PirMotionSensor :

import android.util.Log;

 

 

import com.google.android.things.pio.Gpio;

import com.google.android.things.pio.GpioCallback;

 

 

import java.io.IOException;

 

 

public class PirMotionSensor implements MotionsSensor {

    private final Gpio bus;

    private final MotionsSensor.Listener listener;

 

 

    PirMotionSensor(Gpio bus, Listener listener) {

        this.bus = bus;

        this.listener = listener;

    }

 

 

    @Override

    public void startup() {

        try {

            bus.setDirection(Gpio.DIRECTION_IN);

            bus.setActiveType(Gpio.ACTIVE_HIGH);

            bus.setEdgeTriggerType(Gpio.EDGE_FALLING);

        } catch (IOException e) {

            throw new IllegalStateException("Sensor can't start", e);

        }

        try {

            bus.registerGpioCallback(callback);

        } catch (IOException e) {

            throw new IllegalStateException("Sensor can't register callback", e);

        }

    }

 

 

    private final GpioCallback callback = new GpioCallback() {

        @Override

        public boolean onGpioEdge(Gpio gpio) {

            listener.onMovement();

            return true; // True to continue listening

        }

    };

 

 

    @Override

    public void shutdown() {

        bus.unregisterGpioCallback(callback);

        try {

            bus.close();

        } catch (IOException e) {

            Log.e("TEST", "Failed to shut down. You might get errors next time you try to start.", e);

        }

    }

 

 

}

In the lefthand menu, navigate again to App > Java and right click on the package name. Choose New > New Java Class. In the pop-up screen, change the field Kind to Interface instead of Class. Name the interface MotionsSensor.

image

 

Then, copy and paste this code into the interface:

public interface MotionsSensor {

    void startup();

 

 

    void shutdown();

 

 

    interface Listener {

        void onMovement();

    }

}

Click run and in the next screen choose Google_Iot_rpi3 as the device.

Go back to the Wia Dashboard. In the debugger tab, you can see your events appearing in real time! Each time motion is detected, and event is being sent to Wia.

To take this a step farther, you can use the Wia platform to send you a notification when motion is detected.

Wia Flows

In the left sidebar, navigate to Flows and add a new flow. Name it anything you like. From the Trigger tab, drag over a Create Event node. Name this node motion and select your device.

Next, in the Logic tab, drag over a run-function node. Copy and paste this code into the box:

if (input.body.name == "motion") {

  output.body.data = "motion detected";

}

else {

  output.body.data = "no motion";

}

Connect the nodes by dragging the orange dots.

image

 

Then, in the Action tab, drag over a Notification node. Enter "Motion detected!" as the message. When motion is detected, this flow will send a notification to the Wia mobile app.

 

image

PIR Sensor Sensitivity Measures

The PIR Sensor allows you to change the Delay Time as well as the Sensitivty Level.

The PIR Sensor is a digital device. This means that it reads two values: HIGH and LOW. When the sensor detects movement, it reads HIGH. Otherwise, it reads LOW.

The Delay setting determines how long the PIR Sensor will read HIGH after it has detected a motion. The Sensitivity Sensor determines the proximity at which the PIR Sensor will register a movement. This sensor is more accurate when it is set to a lower proximity level. You can control these settings using the orange panels located directly across from the pins you used to wire your device.

  • Sign in to reply

Top Comments

  • dixonselvan
    dixonselvan over 7 years ago +2
    Hi anpivey , Thanks for sharing this useful tutorial.
  • anpivey
    anpivey over 7 years ago in reply to dixonselvan +2
    Glad you enjoyed it!
  • DAB
    DAB over 7 years ago +2
    Nice post. DAB
  • genebren
    genebren over 7 years ago

    Very cool tutorial.  I am looking to update my security system (existing system, left by prior owner) into a customize project, and this looks like an interesting approach.

    Thanks for sharing.

    Gene

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • More
    • Cancel
  • DAB
    DAB over 7 years ago

    Nice post.

     

    DAB

    • Cancel
    • Vote Up +2 Vote Down
    • Sign in to reply
    • More
    • Cancel
  • anpivey
    anpivey over 7 years ago in reply to dixonselvan

    Glad you enjoyed it!

    • Cancel
    • Vote Up +2 Vote Down
    • Sign in to reply
    • More
    • Cancel
  • dixonselvan
    dixonselvan over 7 years ago

    Hi anpivey,

     

    Thanks for sharing this useful tutorial.

    • Cancel
    • Vote Up +2 Vote Down
    • Sign in to reply
    • More
    • Cancel
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