Sunday, 25 June 2017

How to receive data from MQTT Cloud to Raspberry Pi

How to receive data from MQTT Cloud to Raspberry Pi


# Open https://accounts.adafruit.com
# Import standard python modules.
import RPi.GPIO as GPIO

import sys

# Import Adafruit IO MQTT client.
from Adafruit_IO import MQTTClient

GPIO.setmode(GPIO.BCM)

# Set to your Adafruit IO key & username below.
ADAFRUIT_IO_USERNAME      = 'Your Adafruit IO user name'# to find your username
ADAFRUIT_IO_KEY           = 'Your Adafruit IO Key'  # to find in io.adafruit
                                                 

# Set to the ID of the feed to subscribe to for updates.
FEED_ID1 = 'output1'
FEED_ID2 = 'output2'

GPIO.setup(23, GPIO.OUT)
GPIO.output(23, GPIO.LOW)
GPIO.setup(2, GPIO.OUT)
GPIO.output(2, GPIO.LOW)



# Define callback functions which will be called when certain events happen.
def connected(client):
 
    print 'Connected to Adafruit IO!  Listening for {0} changes...'.format(FEED_ID1)
    print 'Connected to Adafruit IO!  Listening for {0} changes...'.format(FEED_ID2)

     # Subscribe to changes on a feed named DemoFeed.
    client.subscribe(FEED_ID1)
    client.subscribe(FEED_ID2)


def disconnected(client):
    # Disconnected function will be called when the client disconnects.
    print 'Disconnected from Adafruit IO!'
    sys.exit(1)

def message(client, feed_id, payload):
    # Message function will be called when a subscribed feed has a new value.
    # The feed_id parameter identifies the feed, and the payload parameter has
    # the new value.
    print 'Feed {0} received new value: {1}'.format(feed_id, payload)
    if feed_id=="output1" and payload=="1":
           GPIO.output(23, GPIO.HIGH)
    if feed_id=="output1" and payload=="0":
        GPIO.output(23, GPIO.LOW)
    if feed_id=="output2" and payload=="1":
        GPIO.output(2, GPIO.HIGH)
    if feed_id=="output2" and payload=="0":
        GPIO.output(2, GPIO.LOW)



    #print 'Feed {0} received new value: {1}'.format(feed_id, payload)


# Create an MQTT client instance.
client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)

# Setup the callback functions defined above.
client.on_connect    = connected
client.on_disconnect = disconnected
client.on_message    = message

# Connect to the Adafruit IO server.
client.connect()

client.loop_blocking()




Circuit Diagram:



Security System using MQTT Cloud and Ultasonic Sensor

Security System using MQTT Cloud and Ultasonic Sensor


from Adafruit_IO import Client
aio = Client('Your Adafruit IO Key')

import RPi.GPIO as GPIO
import time
import signal
import sys

# use Raspberry Pi board pin numbers
GPIO.setmode(GPIO.BCM)

# set GPIO Pins
pinTrigger = 18
pinEcho = 24

def close(signal, frame):
print("\n ultrasonic distance detection...\n")
GPIO.cleanup()
sys.exit(0)

signal.signal(signal.SIGINT, close)

# set GPIO input and output channels
GPIO.setup(pinTrigger, GPIO.OUT)
GPIO.setup(pinEcho, GPIO.IN)

while True:
# set Trigger to HIGH
GPIO.output(pinTrigger, True)
# set Trigger after 0.01ms to LOW
time.sleep(0.00001)
GPIO.output(pinTrigger, False)

startTime = time.time()
stopTime = time.time()

# save start time
while 0 == GPIO.input(pinEcho):
startTime = time.time()

# save time of arrival
while 1 == GPIO.input(pinEcho):
stopTime = time.time()

# time difference between start and arrival
TimeElapsed = stopTime - startTime
# multiply with the sonic speed (34300 cm/s)
# and divide by 2, because there and back
distance = (TimeElapsed * 34300) / 2

print ("Distance: %.1f cm" % distance)
#        if distance <= 20:
       aio.send('Gauge', distance)
#       aio.send('MSG', "Detected")        
time.sleep(1)
#        else:
                   aio.send('Gauge', distance)
#          aio.send('MSG', "Not Detected")
#        
#
       
data = aio.receive('Gauge')
print('Received value: {0}'.format(data.value))


Circuit Diagram:



How to send Sensor( Ultrasonic) data to MQTT Cloud Server

How to send Sensor( Ultrasonic) data to MQTT Cloud Server:


from Adafruit_IO import Client
aio = Client('Your Adafruit IO Key')

import RPi.GPIO as GPIO
import time
import signal
import sys

# use Raspberry Pi board pin numbers
GPIO.setmode(GPIO.BCM)

# set GPIO Pins
pinTrigger = 18
pinEcho = 24

def close(signal, frame):
print("\n Ultrasonic distance detection \n")
GPIO.cleanup()
sys.exit(0)

signal.signal(signal.SIGINT, close)

# set GPIO input and output channels
GPIO.setup(pinTrigger, GPIO.OUT)
GPIO.setup(pinEcho, GPIO.IN)

while True:
# set Trigger to HIGH
GPIO.output(pinTrigger, True)
# set Trigger after 0.01ms to LOW
time.sleep(0.00001)
GPIO.output(pinTrigger, False)

startTime = time.time()
stopTime = time.time()

# save start time
while 0 == GPIO.input(pinEcho):
startTime = time.time()

# save time of arrival
while 1 == GPIO.input(pinEcho):
stopTime = time.time()

# time difference between start and arrival
TimeElapsed = stopTime - startTime
# multiply with the sonic speed (34300 cm/s)
# and divide by 2, because there and back
distance = (TimeElapsed * 34300) / 2

print ("Distance: %.1f cm" % distance)
#      
       aio.send('Guage', distance)
#        
#
       
data = aio.receive('Gauge')
print('Received value: {0}'.format(data.value))

Circuit Diagram:




How to send Text to MQTT Cloud Server.

How to send Text to MQTT Cloud Server.



from Adafruit_IO import Client
aio = Client('Your Adafruit IO Key')

import RPi.GPIO as GPIO
import time
import signal
import sys

# use Raspberry Pi board pin numbers
GPIO.setmode(GPIO.BCM)

while True:

aio.send('text', "Hello")
print('Received value: {0}'.format(data.value))

Circuit Diagram:



Saturday, 27 May 2017

Object Detection using Raspberry pi and OpenCv

Object Detection using Raspberry pi and OpenCv


import numpy as np
import cv2
import io
import picamera

stream = io.BytesIO()

with picamera.PiCamera() as camera:
    camera.resolution = (320, 240)
    camera.capture(stream, format='jpeg')

buff = numpy.fromstring(stream.getvalue(), dtype=numpy.uint8)


img = cv2.imdecode(buff, 1)

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')

watch_cascade = cv2.CascadeClassifier('haarcascade_watch.xml')

while 1:
    ret, img = cap.read()
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)
   
    watches = watch_cascade.detectMultiScale(gray, 50, 50)
    
   
    for (x,y,w,h) in watches:
        cv2.rectangle(img,(x,y),(x+w,y+h),(255,255,0),2)

    for (x,y,w,h) in faces:
        cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)

        
        roi_gray = gray[y:y+h, x:x+w]
        roi_color = img[y:y+h, x:x+w]
        eyes = eye_cascade.detectMultiScale(roi_gray)
        for (ex,ey,ew,eh) in eyes:
            cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)

    cv2.imshow('picture.jpg',img)


  

Face and Eye Detection using Raspberry pi and OpenCv

Face and Eye  Detection using Raspberry pi and OpenCv:


import io
import picamera
import cv2
import numpy


stream = io.BytesIO()

with picamera.PiCamera() as camera:
    camera.resolution = (320, 240)
    camera.capture(stream, format='jpeg')


buff = numpy.fromstring(stream.getvalue(), dtype=numpy.uint8)


img = cv2.imdecode(buff, 1)


face_cascade = cv2.CascadeClassifier('/home/pi/opencvfolder/haarcascade_frontalface_alt.xml')
eye_cascade = cv2.CascadeClassifier('/home/pi/opencvfolder/haarcascade_eye.xml')

#Convert to grayscale
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

faces = face_cascade.detectMultiScale(gray, 1.3, 5)

print "Found "+str(len(faces))+" face(s)"

#Draw a rectangle around every found face

for (x,y,w,h) in faces:
        cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
        roi_gray = gray[y:y+h, x:x+w]
        roi_color = img[y:y+h, x:x+w]

        eyes = eye_cascade.detectMultiScale(roi_gray)
        for (ex,ey,ew,eh) in eyes:
            cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)

cv2.imwrite('picture.jpg',img)


Face Detection using Raspberry pi and OpenCv

Face Detection using Raspberry pi and OpenCv


import io
import picamera
import cv2
import numpy

stream = io.BytesIO()

with picamera.PiCamera() as camera:
    camera.resolution = (320, 240)
    camera.capture(stream, format='jpeg')

buff = numpy.fromstring(stream.getvalue(), dtype=numpy.uint8)

image = cv2.imdecode(buff, 1)

face_cascade = cv2.CascadeClassifier('/usr/share/opencvfolder/haarcascade_frontalface_alt.xml')

#Convert to grayscale
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)

faces = face_cascade.detectMultiScale(gray, 1.1, 5)

print "Found "+str(len(faces))+" face(s)"

for (x,y,w,h) in faces:
    cv2.rectangle(image,(x,y),(x+w,y+h),(255,255,0),2)

cv2.imwrite('picture.jpg',image)