Motion Sensor-Enabled Tracking with Raspberry PI and Azure IoT

Ezequiel Miranda
Devjam
Published in
8 min readJun 28, 2021

Introduction

Hello Folks

It’s Ezex here on the other side of the screen :)

Today I bring you an article about some of my recent playground experiments with some technologies focusing on the Internet of things.

These are the results of my experiments, which I will show you how to build.

Disclaimer: I’m pretty new on the IoT world, so I will present this case as an experiment. In which I start simply playing with these technologies.

In this first experiment, we will implement a Proof of concept for the next use case:

“As an IoT developer, I want to connect a Passive Infrared sensor to a Raspberry Pi4, detect movements in a room and communicate these events to a dedicated IoT cloud service”

To achieve this, we will test the integration between Raspberry Pi 4, a PIR sensor, Node.js development environment, Azure IoT Hub, To implement the next cloud application design:

Table of contents

  1. Experiment scope
  2. Introduction to Raspberry
  3. General-purpose input/output (GPIO)
  4. Electronic components (PIR sensor)
  5. Azure IoT Hub
  6. Create a demo App(Node.js)

1. Experiment scope

What do we want to achieve?

- Setting up the Raspberry OS
- Setting up the development environment
- Creating an application service (send sensor events to Azure IoT Hub)
- Monitoring cloud IoT hub messages

2 . Introduction to Raspberry

For the hardware part, I chose a Raspberry Pi 4. For those who don’t know, a Raspberry Pi is a series of small single-board computers. This small piece of hardware enables the installation of a series of different operating systems.

The Raspberry Pi comes with a GPIO pins module that allows you to connect different electronic components.

How it looks:

Setting up the operating system

The officially supported operating system is Raspberry Pi OS (Previously called Raspbian), and under the hood is a Debian-based operating system for Raspberry Pi.

For proper instruction on installing the OS on your hardware. follow this link

https://www.raspberrypi.org/software/

Setting up the remote development environment

To develop and run our code, we can choose between using the raspberry OS environment directly or connecting to it remotely through SSH.

We are using node.js for our application, so if it is not pre-installed on the environment, you will need to download and install it.

Tasks to complete on this step

As a default, your Raspberry Pi comes configured with the following SSH Credentials:

User: raspberryPassword: pi

But is very recommended you change to new ones.

At this point, we should able to connect our Visual Code editor to a remote host (Raspberry Pi) and map the disk in order to code and run the code remotely.

3. Raspberry GPIO

GPIO is an input/output system for general purpose, which has a series of pins you can connect sensors, actuators, and other electronic components.

The number and type of pins will vary depending on the Raspberry model.

Pins types:
- 5V
- 3V
- Ground
- Multipurpose pin

To find proper information about the module on your device, you can look at the official documentation.

Also, you can use software such as Pinout (Already installed on Raspberry OS).

This GPIO Pinout is an interactive reference to the Raspberry Pi GPIO pins, and a guide to the Raspberry Pi’s GPIO interfaces.

https://pinout.xyz/

Running the CLI application on your console:

pinout

We will get the next output with the description of the pins:

GPIO libraries

To interact with the GPIO we can choose between different languages and libraries.

For example:

4. Electronic Components

In this experiment, we will use a PIR sensor to detect movement.

PIRWikipedia

A passive infrared sensor is an electronic sensor that measures infrared light radiating from objects in its field of view. They are most often used in PIR-based motion detectors. PIR sensors are commonly used in security alarms and automatic lighting applications

In order to connect our PIR sensor on the Raspberry we should connect with the appropriate pins:

  • (-) — To any GND pin (Pin 6 on this example)
  • (3.3v) — Pin number 1 for providing the power
  • (s) — Connect the signal pint to any GPIO pin, in this tutorial we use the GPIO number 27.

5. Create an Azure IoT Hub

In this part of the article, we will start playing with Azure IoT Hub, but first I will give a little introduction to the features of this Azure Service.

Azure IoT Hub is a managed service for bidirectional communication between IoT devices and Azure.

For this use case, we will use device-to-cloud communication.

Device-to-cloud:

Your devices can send data, alerts, events to the IoT hub and can also connect with other Azure services.

Steps:
- Create account
- Create IoT Hub instance
- Register device

Create account

If you are new to the Azure environment you can apply for a free account and get 12 months of free services.

3.1 Create IoT Hub

On this main page, you can see your IoT Hub instances

Let’s create a new instance, so complete the fields required and click the Review + create button.

Now we have the IoT Hub instance is created:

5.2 — Register a new IoT device

The next step will be to register your hardware device.

We must choose a device ID; in this case: myRasperryPi01

Once the new device is created, we click on it and take note of the Primary Connection String.

6 . Create a demo App(Node.js)

At this point, we will start coding our application the node.js script which is responsible for communication events captured by the sensor and sending those to the IoT Hub.

Comment

For communication from the device to the cloud, we will use Message Queuing Telemetry Transport (MQTT) client provided by Azure.

The application will:

  • Detect movement in the room with a PIR sensor
  • Light up the LED
  • Send event messages to the IoT Hub (Using MQTT)

Steps:

1 — Create a new node.js app

npm init my-iot-demo-project

2 — Install dependencies

With the next command, we will install the dependencies needed for the application:

npm install onoff azure-iot-device azure-iot-device-mqtt

Dependencies:

3 — Create node.js application

//index.js// Importing dependencies
const Gpio = require('onoff').Gpio;
const Client = require('azure-iot-device').Client;
const Message = require('azure-iot-device').Message;
const MqttProtocol = require('azure-iot-device-mqtt').Mqtt;
// Set up GPIO pin
const PIR = new Gpio(27, "in", 'both');
var client, connectionString
const connectionStringParam = '<YOUR_CONNECTION_STRING_PARAM' // from the Azure IOT device registration;
// Start MQTT Client
function startClient() {
console.log(`[Application] - Running`)
lightUpLED()
setTimeout(lightDownLED, 1000)
connectionString = process.env['connectionString'] || connectionStringParam;
client = Client.fromConnectionString(connectionString, MqttProtocol);
return client
}
// Send messages to Cloud (Azure IoT Hub Instance)
function sendMessage() {
const now = new Date()
var contentEvent = JSON.stringify({
time: now, room: 4, message: 'A person has entered the room'
})
var message = new Message(contentEvent.toString('utf-8'));
message.contentEncoding = 'utf-8';
message.contentType = 'application/json';
client.sendEvent(message, (err) => {
if (err) {
console.error('[Device] - Failed to send message to Azure IoT Hub due to:\n\t' + err.message);
}
else {
console.log('[Device] - Message sent to Azure IoT Hub');
console.log(message)
}
})
}// Init application and setting event listener for PIR sensor.
// A valid config.json IoT Device is needed to start the application
// The application will send a new event to the IoTHub every time the sensor detects a person
(function () {
try {
client = startClient()
PIR.watch(sendMessage)

} catch (err) {
console.error('Failed to start the client:\n\t' + err.message);
return;
}
})();

Run project

To start our application, we will run the following command:

node index.js

Anytime the sensor detects movements the application will send new event data to the cloud, also we will get a message log on the console.

5 — Monitor the messages received by your Hub

If you are using Visual Code Editor, you can install the next plugin and monitor the events sent to the IoT Hub on the output console.

Visual Code plugin: azure-iot-tools

Once the plugin is installed, you will see a new section on the editor, Azure IoT Hub in which you can inspect the devices connected to your IoT Hub. In this case, the Raspberry Pi

Each time your application detects a person moving in the room, a message will be received by the IoT default Built-in endpoint, as shown above.

Wrapping up

At this point, we have finished our experiment: we have set up our Raspberry Pi, connected the PIR sensor to it, set up our development environment, created our node.js application, and sent events detected by the sensor to the Azure IoT Hub instance.

Thank you for your interest! Any feedback is welcome :)

I work at Sytac.io; We are a consulting company in the Netherlands, we employ around ~100 developers across the country at A-grade companies like KLM, ING, ABN-AMRO, TMG, Ahold Delhaize, and KPMG. Together with the community, we run DevJam, check it out and subscribe if you want to read more stories like this one. Alternatively, look at our job offers if you are seeking a great job!

--

--