IOT or Internet of Things is a hot topic these days, but more than that its exciting. I have been a developer for more than 10 years now and although I have designed and built applications that can handle millions of calls and analyze terabytes of data in real time, the most exciting thing I have done in recent times is running a 12 volt DC motor on the click of a button on an app that I built.

In this article, I am going to walk you through step by step in:

Setting up AWS IOT service Setting up your Raspberry PI 3 Model B (although any other version will also do) Make a simple app which has one button to send a signal to AWS IOT service and listen for a response. Get the PI to listen to a topic on AWS IOT service and run a DC motor for a few seconds succeeding which it will send a success status to another topic.

Credits

This is a learning project which me and Sneha Gokarn (the wife :)) took up together.

What will you make

What you will need to build the entire thing

Raspberry PI, I used version 3 model B which comes with WiFi which you will need, US Amazon link, India Amazon link. A standard breadboard (optional, but recommended), US, India. AWS account with admin priviliges, everything that you will build will be in the AWS Free tier and will not cost you anything DC motor, I used a 12 volt, high torque version which can do some heavy lifting, US, India. L298 motor driver on a breakout board to drive your motor and control directions (forward or reverse), this can handle a voltage of 35 volts and drive two motors of upto 2 amps in switchable directions, US, India. Power supply which matches your motor, use an unused power adapter with matching rating, or get a battery with matching voltage and current. If you are gonna go with batteries, I recommend getting a case to hook up multiple AA batteries together, bigger 9V batteries will deplete very fast and are weaker with output current Jumper wires to hook everything up, US, India, also get some regular medium thickness copper wires for better hooking up the DC motor. Multimeter (optional), I would seriously recommend this so that you know what is going on. Hooking up multiple wires quickly add to a lot of resistance and current drops which will leave you scratching your head or blaming the motor, US, India. Smart phone, I will give you code for Android, you can port it to IOS if you like

Disclaimer: I will earn a small fee if you buy the above products via the links I have provided, thanks for your support! This is the only place where I will mention promotional (but useful :)) links.

Setting up your PI

What is Raspberry PI you ask? It is a small credit card sized chip which has a general purpose CPU with nominal amounts of RAM, it is built by the Raspberry PI foundation which is essentially a charity, so you are doing something good whenever you buy a PI, here is a wiki link.

If you just got your Raspberry PI, set it up using the awesome tutorials on the official Raspberry PI website. You should have gotten the SD card loaded with NOOBS software, setup Raspbian OS (optionally with UI) for this tutorial, NOOBS will give you options to install a bunch of other OS’s as well.

Make sure you have internet connectivity on your PI before proceeding further.

Tip: You can connect your PI with an HDMI cable if you chose the UI

version of Raspbian, hook up a mouse on one of the USB ports and

configure Wifi

If you have a Windows laptop, install Putty to SSH into the PI, if you have a MAC then you can simply use regular command line.

If you have never used Putty before, here is a helpful tutorial for windows users.

Mac users can use this tutorial by rackspace.

You can also choose to open the terminal on the pi itself by connecting it to your monitor/ TV, I recommend you learn how to SSH though, it will ease your life later.

TIP: If you have trouble finding your PI’s IP address so as to SSH into it, you can use the NMAP utility available in most popular platforms as explained in this article here.

Now, run the following command to get latest Kernel:

sudo apt-get install rpi-update

sudo rpi-update

To use the AWS IOT SDK:

Install cmake:

sudo apt-get install cmake

Install OpenSSL 1.0.2 developer version:

Add the following text at the end of /etc/apt/sources.list.d/raspi.list:

deb http://ftp.debian.org/debian jessie-backports main

Update the package list:

sudo apt-get update

Install Open SSL:

sudo apt-get -t jessie-backports install libssl-dev

Install AWS IOT SDK:

sudo pip install AWSIoTPythonSDK

Install the GPIO python lib:

sudo pip install RPi.GPIO

Setup AWS IOT Service

We will now setup the AWS IOT service, everything will be under AWS free tier if you are eligible for it and shouldn’t cost you anything, if you are not eligible for the free tier (1 year from starting the account), you should expect no more than a single US dollar for this tutorial.

Some terminologies that you should be aware of:

Thing: A thing is a device, derived from Internet of things a thing can be a Raspberry PI or Adruino etc, basically the end device sitting at the end location.

Thing Shadow: Its a shadow of your thing. Its typically a server / Lambda function sitting in the cloud which unlike your things is way more dependable for communications as the end devices are typically more prone to connection disruptions.

Step 1:

Sign in into the AWS Management console, head over to AWS IOT service home page. Choose “get started” if you have do not have anything in the IOT console yet.

Step 2:

Expand the registry menu from the left pane and click on Things .

Click on Register a thing or Create depending on whether you already have a ‘thing’ present.

Give the thing a name like motorRunner , proceed to click on Create .



Step 3:

Click on the thing card on the Things page that you wind up on after creating the ‘motorRunner’ thing.

Click on Interact from the left pane. Copy and save the Rest API endpoint, you will need this later.

Click on Security from the left pane and click on Create Certificate



Download 4 files from this page before you close and save them for later use:

A certificate for this thing – rename to cloud.pem.crt, note the original file name, it contains the name of your certificate. A public key A private key – rename to cloud.pem.key Root CA certificate – rename the file to root-ca.pem

For ease of communicating, I will be using the names I have asked you to rename the original file to later in the article.

Click on Activate .

Step 4:

Click on Attach a policy and then click on Create a new policy .

In the Action field, type in iot:* , in the Resource Arn field type in * , check the Allow checkbox in the Effect section.

Give the policy a name like motorRunnerPolicy , proceed to click on Create .

Step 5:

In IOT console page click on Certificates from the left pane under the Security heading.

Click on the menu button on the right top corner of the certificate that you had just created (see the name of the original file name), click on Attach Policy . Proceed to attach the policy that you just created.

Step 6:

Again click on the options menu on the top right corner of your certificate in the Certificates pane and choose Attach a thing .

Check the motorRunner thing and then click on Attach .

Configure AWS Cognito

Sign in to the Amazon Cognito console

Click on Manage Federated Identities Button.

Click on Create New Identity Pool



Create a new identity pool called Silo’s Treat.:

The identity pool we are creating must allow access to unauthenticated identities right now, so the checkbox for Enable access to unauthenticated identities option needs to be checked.

After which you’ll come to this step to select 2 roles an authenticated and unauthenticated role.



Under the Unauthenticated Role, paste the below policy, this will give you the required permissions to publish/subscribe/connect to your “thing”.

{

"Version": "2012-10-17",

"Statement": [

{

"Effect": "Allow",

"Action": [

"iot:AttachPrincipalPolicy",

"iot:CreateKeysAndCertificate"

],

"Resource": "*"

},

{

"Effect": "Allow",

"Action": "iot:Connect",

"Resource": "*"

},

{

"Effect": "Allow",

"Action": [

"iot:Subscribe"

],

"Resource": "*"

},

{

"Effect": "Allow",

"Action": [

"iot:Receive"

],

"Resource": "*"

},

{

"Effect": "Allow",

"Action": [

"iot:Publish"

],

"Resource": "XXX/homeProject_Core/req"

}

]

}

Note: homeProject_Core is the thing we want to publish onto.

Note down the identity pool ID. You specify this ID in your mobile application you create in the next section. The app uses this ID when it sends request to Amazon Cognito to request for temporary security credentials.

Disclaimer: The android app in the sample will used unauthenticated version of AWS Cognito and relevant permissions have been added for the same in this tutorial which is meant to get you started only.

Make the Android app

The Android app to connect to the service is present here: https://github.com/maingi4/TreatDropper.Android

Get Android Studio, get the code and get it on your phone. The GitHub repo’s readme will guide you through.

Code for Raspberry PI

Copy the following certificates for AWS IOT to your raspberry PI, the names below are what I mentioned in step 3 under topic setting up AWS IOT service above.

1. root-ca.pem

2. cloud.pem.key

3. cloud.pem.crt

I copied these by a relatively insecure method of uploading it to a public s3 bucket and then firing a wget command from my PI, feel free to use any copy-paste method that you like. If you use this method, don’t forget to immediately delete the certs from the public bucket after downloading them into the Pi.

Move the certificates into a folder in the PI in the path ‘/home/pi/homeAutomation/configuration/certs/’, if you change this path make sure to change the variable certRootPath in the program.py file that I have given later below.

Below is the program.py file which acts as the entry point for the program. The code does the following:

Connects to the AWS IOT service at the endpoint I mentioned in step 3 under topic setting up AWS IOT service . Make sure you put that URL in the code below. Authentication is done via the certificates we had downloaded before. Subscribes to a topic home/runMotor which is published to by our mobile app. Runs the pulse method of the motor_runner class by giving it a period of 2 seconds (motor will run for 2 seconds). Publishes a success status to the home/motorRunStatus topic which the mobile app listens to.

import time import os import motor_runner #import net_check from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient def run_motor(self, params, packet): motor_runner.pulse(2) myMQTTClient.publish('home/motorRunStatus', packet.payload, 0) myMQTTClient = AWSIoTMQTTClient("raspberryPiHome") #random key, if another connection using the same key is opened the previous one is auto closed by AWS IOT myMQTTClient.configureEndpoint("YOUR AWS IOT ENDPOINT HERE", 8883) certRootPath = '/home/pi/homeAutomation/configuration/certs/' myMQTTClient.configureCredentials("{}root-ca.pem".format(certRootPath), "{}cloud.pem.key".format(certRootPath), "{}cloud.pem.crt".format(certRootPath)) myMQTTClient.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing myMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz myMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec myMQTTClient.configureMQTTOperationTimeout(5) # 5 sec myMQTTClient.connect() myMQTTClient.subscribe("home/runMotor", 1, run_motor) def looper(): while True: time.sleep(5) #sleep for 5 seconds and then sleep again #check_internet() looper() def function_handler(event, context): return

Motor runner file, the code does the following:

Sets the numbering system of the PI GPIO pins to ‘Board’, read this article for types of numbering. Configures pins 12 and 36 to mode output . Turns pin 12 to high and the other to low. Sleep for the number of seconds provided as input. Sets pin 12 to low.

We will understand why we are doing the above in the next topic when we make the physical circuit to run the motor.

import RPi.GPIO as GPIO from time import sleep import platform import logging def pulse(secs): if platform.system().lower() != "windows": GPIO.setmode(GPIO.BOARD) Motor1A = 12 Motor1B = 36 GPIO.setup(Motor1A,GPIO.OUT) GPIO.setup(Motor1B,GPIO.OUT) logging.info("Turning motor on") GPIO.output(Motor1A,GPIO.HIGH) GPIO.output(Motor1B,GPIO.LOW) sleep(secs) logging.info("Stopping motor") GPIO.output(Motor1A,GPIO.LOW) GPIO.cleanup()

Copy both program.py and motor_runner.py file into your PI, we will run the program after we make the circuit.

Make the Circuit

First you need to understand the L298N motor driver that we are working with, since I myself understood it by reading this article, it is fitting that I don’t repeat that.

Now, let’s make the circuit.



1. Connect your power to the breadboard, make any power line positive

and the other negative, I would advice to use red for positive and

black for ground (negative) power connections.

2. Connect the ground of the Raspberry Pi to the ground in the breadboard.

3. Connect the positive terminal to the chip input, if the power is < 12V you will also need to add a 5V power to the power regulator enable pin.

4. Connect the motor driver’s ground to the ground in the breadboard.

5. Connect one of output’s of the motor, positive and negative to the motor input terminals, it doesn’t matter which goes where, it will simply control the direction which can be controlled via the PI anyway.

6. Connect GPIO Pins #12 and #36 to the enable pins, make sure you choose the two pins on the same side as the output of the motor driver from where the motor connections are made, read this article for finding out the numbering. The ordering doesn’t matter, this is where you can control the direction of the motor.



That’s it! Make sure the PI python program is running and push the button on the app to run the motor.

Conclusion & Notes

We just learned how to build our first IOT device, use an app to send a signal to the cloud which a device listens to in turn actuating a machine (motor in this case) to interact with the physical world.

If you are thinking of building a network of devices, I recommend using Raspberry PI as the hub and general computing device and smaller and cheaper chips like the popular Adruino for handling individual tasks. When the PI acts as a hub, you should think about using AWS Greengrass which is essentially made for the exact same thing providing support for OTA updates, running Lambda functions on the device securely etc.

If you liked this article, you can choose to follow this blog/subscribe to email alerts (floating follow button {bottom-right} or below comments in mobile) so that you know when any future posts come about.