Thursday, January 14, 2016

IoT: Is someone there? RPi, Arduino and Firebase!

"This blog is about detecting motion and showing it on a Web page. IoT device will identify movement and publish status to a service on cloud. A web page integrated with the service will show the status on screen. Also, let's glow green LED when no motion is detected and red when there is movement."
Here is a quick demo -

Arduino with Raspberry Pi (RPi)

Using Arduino to interface with motion sensor. Code in Arduino detects motion and lights a red LED and sends high to connected Raspberry Pi pin as well. The RPi is integrated with Firebase on Cloud. Used REST API to update a flag in Firebase data source. A web page that shows default status that no moment detected (safe) will change with the flag on Firebase to notify movement (Someone's there).

Following picture depicts Arduino, RPi and motion sensor connections I have.
RPi is powering Arduino, 5v on RPi is connected to vin on Arduino. Ground to ground and RPi board pin 3/GPIO02 to Arduino pin 9. Arduino detects motion from the sensor and sends high signal to RPi on this pin.

Motion sensor has three pins. It's powered by 5v pin on Arduino. Ground to ground and pin 8 receives input from the sensor. Value will be high whenever the sensor detects motion.

In the video, got green and red LEDs indicating motion on the device. It's standard LED connections. Here is a picture.


Arduino sends high to pin 6 by default; It sends high on pin 7 and pin 9 when motion is detected. 7 lights red LED And high signal on 9 makes RPi update cloud service indicating motion. 

Code on Arduino

#define greenLed 6 #define redLed 7
#define motionSensor 8
#define rpi 9
void setup(){
Serial.begin(9600);
pinMode(greenLed, OUTPUT);
pinMode(redLed, OUTPUT);
pinMode(motionSensor, INPUT);
pinMode(rpi, OUTPUT);
}
void loop(){
delay(500); // If High motion is detected.
if(digitalRead(motionSensor) == HIGH){
lightRed();
digitalWrite(rpi, HIGH);
}else{
lightGreen();
digitalWrite(rpi, LOW);
}
}
void lightRed(){
digitalWrite(greenLed, LOW);
digitalWrite(redLed, HIGH);
}
void lightGreen(){
digitalWrite(redLed, LOW);
digitalWrite(greenLed, HIGH);
}
Following Python code on RPi updates Firebase Cloud back end that motion is detected (or vice versa). a page integrated with this data source shows the status on a web page. This code is using Firebase REST API to update status flag.

import RPi.GPIO as GPIO import time
import http.client
import json
arduinoPin = 3
GPIO.setmode(GPIO.BOARD)
GPIO.setup(arduinoPin, GPIO.IN)
while True:
if GPIO.input(arduinoPin) == GPIO.HIGH:
print('Switching ON...')
client = http.client.HTTPSConnection('vencki-iot-sample.firebaseio.com')
client.request('PUT','/proximityWarning.json', '{"isClose":true}')
response = client.getresponse()
print (response.reason)
else:
print('Switching OFF...')
client = http.client.HTTPSConnection('vencki-iot-sample.firebaseio.com')
client.request('PUT','/proximityWarning.json', '{"isClose":false}')
response = client.getresponse()
print (response.reason)
time.sleep(2)
print('quitting...')
GPIO.cleanup()

Saturday, January 2, 2016

IoT: Hello World - Toggle LED with a button on a Web Page

"This blog is about toggling LED on or off with a button click on a web page, from a phone or a desktop."

Happy New Year! I recently started exploring long pending IoT in my things to learn. I'm planning to document as tryout samples. As a Hello World I tried out blinking LED using a Raspberry Pi 2, took it little further, toggled LED on or off as you tap on a button in a web page.

Here is a quick demo-

Why Raspberry Pi? 

I've a choice (available with me) between Arduino and Raspberry Pi. With Arduino, I would need to buy additional WiFi module. Arduino can do one job at a time and it can do that well. It works great with direct sensor interactions, may it be temperature sensor, proximity sensor etc.

Raspberry Pi is a computer in it self. It comes with LAN cable connectivity, I could connect a 300 INR (5 USD appx) Wifi dongle and get it connected to Internet. I'm using Raspbian. Microsoft has Windows 10 IoT core which could be installed on a (micro) SD card and used with Raspberry Pi 2.

There is a choice of programing languages with Raspberry Pi. In this sample I'm using more popular Python.

Web Page that toggles LED

Just needed a central location on cloud to store on/off state. It could be anything. Firebase is a good solution for such things. And I believe it's a good platform for IoT going forward. 
  • Firebase is literally no setup, ready made cloud back-end. 
  • It's no schema and JSON data store. 
  • Easy to get and update data with REST API and setup security rules. 
  • It's backed by Google Cloud if you are thinking scalability.
I uploaded a simple page with button that flips a flag on Firebase as you click on the button. This page is deployed to Firebase hosting service. Raspberry Pi uses this flag, turns LED on if the value is true (and vice versa).

Raspberry Pi Setup

Raspberry Pi 2 has a 40 pin layout. Refer to below picture- pins are 
  • GPIO (General Purpose Input/Output) - could be used in code to set a value HIGH or LOW to interface with sensors and devices.
  • Ground
  • 3.3 volts and 5 volts power
Reference - http://www.element14.com/community/docs/DOC-73950/l/raspberry-pi-2-model-b-gpio-40-pin-block-pinout
Here is the connection to LED. Positive on LED connects to Pin 7/GIPO04 and ground on LED connects to a resistor which in turn connects to ground on pin 06. Resistor is to make sure too much current doesn't get pass through the LED which could damage it. 
Below is the Python code that looks for flag value on cloud and toggles LED. Read through comments for explanation

import RPi.GPIO as GPIO 
import time 
import http.client 
import json 

pin = 7 
GPIO.setmode(GPIO.BOARD) 
# Board mode is safer option to use with pin numbers matching between older and 
# newer versions of Raspberry Pi, hence no confusion 
GPIO.setup(pin, GPIO.OUT) 
while True: 
  client = http.client.HTTPSConnection('<< firebase URL>>')
  client.request('GET','/LED.json') 
  httpResponse = client.getresponse() 
  dataStream = httpResponse.read() 
  dataString = str(dataStream, 'utf-8') 
  switchLedOn = json.loads(dataString) 
  print(switchLedOn) 
  # switchLedOn holds true/false as user toggles the switch 
  # with a button on the web page. 
  
  if (switchLedOn): 
     print('Switching ON...') 
     GPIO.output(pin, GPIO.HIGH) 
 else: 
     print('Switching OFF...') 
     GPIO.output(pin, GPIO.LOW) 

 time.sleep(2) 
 #retry after 2 seconds. 

GPIO.cleanup()

Complete sample is uploaded to Github. Happy Coding and Happy New Year.