Ezequiel Miranda
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # 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 :)**

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully