Md. Khairul Alam
Published © CC BY

Motion Controlled AWS IoT Button

You can use it as remote switch, anti theft beacon, counter, movement detector and so on.

IntermediateFull instructions provided6,702
Motion Controlled AWS IoT Button

Things used in this project

Story

Read more

Schematics

PIR Connection to Raspberry Pi

Fritzing source file

Beacon connection-image

Beacon connection-source

Code

sensor-client.js

JavaScript
This code is for MQTT publisher. aws-iot sdk is used for the development of this Node.js code. When any movement is detected it publish 1 to the topic(topic/test).
var awsIot = require('aws-iot-device-sdk');

var myThingName = 'raspberry-pi';

var thingShadows = awsIot.thingShadow({
   keyPath: './private.pem.key',   // path of private key
  certPath: './certificate.pem.crt', // path of certificate
    caPath: './rootCA.pem',  // path of root file
  clientId: myThingName,
    region: 'us-west-2'  // your region
});

mythingstate = {
  "state": {
    "reported": {
      "ip": "unknown"
    }
  }
}

var networkInterfaces = require( 'os' ).networkInterfaces( );
mythingstate["state"]["reported"]["ip"] = networkInterfaces['wlan0'][0]['address'];

// PIR sensor connected to pin 7
// You can use any gpio pin 
// install npm button library first
var Gpio = require('onoff').Gpio,
button = new Gpio(7, 'in', 'both');

// json data for dynamoDB
var msg = "{\"key\":\"value\"}";

thingShadows.on('connect', function() {
  console.log("Connected...");
  console.log("Registering...");
  thingShadows.register( myThingName );

  // An update right away causes a timeout error, so we wait about 2 seconds
  setTimeout( function() {
    console.log("Updating my IP address...");
    clientTokenIP = thingShadows.update(myThingName, mythingstate);
    console.log("Update:" + clientTokenIP);
  }, 2500 );


  // Code below just logs messages for info/debugging
  thingShadows.on('status',
    function(thingName, stat, clientToken, stateObject) {
       console.log('received '+stat+' on '+thingName+': '+
                   JSON.stringify(stateObject));
    });

  thingShadows.on('update',
      function(thingName, stateObject) {
         console.log('received update '+' on '+thingName+': '+
                     JSON.stringify(stateObject));
      });

  thingShadows.on('delta',
      function(thingName, stateObject) {
         console.log('received delta '+' on '+thingName+': '+
                     JSON.stringify(stateObject));
      });

  thingShadows.on('timeout',
      function(thingName, clientToken) {
         console.log('received timeout for '+ clientToken)
      });

  thingShadows
    .on('close', function() {
      console.log('close');
    });
  thingShadows
    .on('reconnect', function() {
      console.log('reconnect');
    });
  thingShadows
    .on('offline', function() {
      console.log('offline');
    });
  thingShadows
    .on('error', function(error) {
      console.log('error', error);
    });
	
  
  //Watch for motion detection. high for any movement
  button.watch(function(err, value) {
   console.log("Movement detected ")
   delete mythingstate['version']; //Cleanup to post to AWS
   mythingstate["state"]["reported"]["button"] = value
   buttonStateResponse = thingShadows.update(myThingName, mythingstate);
   thingShadows.publish('topic/test', value.toString()); // publish message
   console.log("Update:" + buttonStateResponse);
  });

});

action-client.py

Python
This Python code is for subscriber, when movement detected it receive 1 from the broker and makes a gpio pin high. Paho mqtt is used for developing the program.
import paho.mqtt.client as mqtt
import ssl
import json
import RPi.GPIO as GPIO
import time

# make sure python gpio library is installed
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
actionPin = 23 # Broadcom pin 23 (P1 pin 16)
GPIO.setup(actionPin, GPIO.OUT) # LED pin set as output
GPIO.output(actionPin, GPIO.LOW)

def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    client.subscribe("topic/test")

def on_message(client, userdata, msg):
    
     if str(msg.payload) == '1':
        print("Movement Detected")
        print(str(msg.payload))
        GPIO.output(actionPin, GPIO.HIGH)  # gpio pin high
        time.sleep(.1)
        GPIO.output(actionPin, GPIO.LOW)
        #time.sleep(0.075)
        
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.tls_set(ca_certs='rootCA.pem', certfile='certificate.pem.crt', keyfile='private.pem.key', tls_version=ssl.PROTOCOL_SSLv23)
client.tls_insecure_set(True)
client.connect("A3JRA11PV5KIYG.iot.us-west-2.amazonaws.com", 8883, 60)
client.loop_forever()

Github repo

Credits

Md. Khairul Alam

Md. Khairul Alam

64 projects • 567 followers
Developer, Maker & Hardware Hacker. Currently working as a faculty at the University of Asia Pacific, Dhaka, Bangladesh.

Comments