owned this note
owned this note
Published
Linked with GitHub
# Motion Sensor-Enabled Tracking with Raspberry PI and Azure IoT
## Introduction
Hello Folks
It's Ezex here on the other side of the sscreen :)
Today I bring you an article about some of my recent playground experiments with some technologies focusing on Internet of things.
These are the results of my experiments, which I will show you how to build.
![](https://i.imgur.com/L0guPMC.jpg)
**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 and communicate events between the IoT board and 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:
![](https://i.imgur.com/EzQmq4z.jpg)
## Table of contents
- 1 - Experiment scope
- 1.1 - What do we want to achieve?
- 1.2 - What do we need?
- 2 - Introduction to Raspberry
- 2.1 - Setting up the operating system
- 2.2 - Setting up the remote development environment
- 3 - General purpose input/output (GPIO)
- 4 - Electronic components (PIR sensor)
- 5 - Azure IoT Hub
- 5.1 - Create Azure IoT Hub
- 5.2 - Register IoT device
- 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
### What do we need?
To conduct the experiment we will need:
- Raspberry Pi
- PIR Sensor
- Visual Code editor (If using a remote environment
- Register an Azure account (free service layer for new users) -https://azure.microsoft.com/en-us/free/
- SSH Client
## 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 the 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 look:
![](https://i.imgur.com/zchmFEq.jpg)
## 2.1 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/
## 2.2 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**.
https://code.visualstudio.com/docs/remote/ssh
![](https://i.imgur.com/bD3rzDm.png)
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
- Enable `ssh` connection on Raspberry OS
- Install `node.js` - https://nodejs.org/en/download/
- Install Visual Code editor's extension for remote development on a client computer https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.vscode-remote-extensionpack
As a default your Raspberry Pi comes configured with the following SSH Credentials:
- **User:** `raspberry`
- **Password:** `pi`
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.
![](https://i.imgur.com/Xo9IsVB.png)
**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:
```sh
pinout
```
We will get the next output:
![](https://i.imgur.com/6NLUI3N.png)
## 4 - GPIO libraries
To interact with the GPIO we can choose between different languages and libraries.
For example:
- For **Node.js**, we can use the npm package `onoff` https://www.npmjs.com/package/onoff
- For **Python** the GPIO package https://pypi.org/project/RPi.GPIO/
## 4 - Electtronic Components
In this experiment, we will use a PIR sensor to detect movement.
PIR ([Wikipedia](https://en.wikipedia.org/wiki/Passive_infrared_sensor))
> 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
![](https://i.imgur.com/LMWcMvk.jpg)
## 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.
https://azure.microsoft.com/en-us/free/
### 5.1 - Create IoT Hub
On this main page, you can see your IoT Hub instances
![](https://i.imgur.com/W7iUZlH.png)
Let's create a new instance, so complete the fields required and click the **Review + create** button.
![](https://i.imgur.com/M1yLYjw.png)
Now we have the IoT Hub instance is created:
![](https://i.imgur.com/PXLA8y2.png)
### 5.2 - Register aa new IoT device
The next step will be to register your hardware device.
![](https://i.imgur.com/jQLfpNT.png)
We must choose a device ID; in this case: `myRasperryPi01`
![](https://i.imgur.com/MAu67Wp.png)
Once the new device is created, we click on it and take note of the `Primary Connection String`.
![](https://i.imgur.com/h1Mhbn7.png)
This `Primary Connection String` will allow us to link the IoT device to the Raspberry.
![](https://i.imgur.com/Yotc8MC.png)
## 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.
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**
```javascript
npm init my-iot-demo-project
```
**2 - Install dependencies**
With the next command, we will install the dependencies needed for the application:
```javascript
npm install onoff azure-iot-device azure-iot-device-mqtt
```
Dependencies:
- [onoff]([https://](https://www.npmjs.com/package/onoff))- Access to GPIO
- [azure-iot-device]([https://]([https://www.npmjs.com/package/onoff](https://www.npmjs.com/package/azure-iot-device))) - A set of utilities for IoT devices on azure
- [azure-iot-device-mqtt]([https://]([https://www.npmjs.com/package/onoff](https://www.npmjs.com/package/azure-iot-device-mqtt))) - MQTT client
**3 - Create node.js application**
```js
//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:
```javascript
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.
![](https://i.imgur.com/ZPgTKn9.png)
**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](https://marketplace.visualstudio.com/items?itemName=vsciot-vscode.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
![](https://i.imgur.com/tF2mfzC.png)
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.
![](https://i.imgur.com/weCmIST.png)
## 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 :)**