0% found this document useful (0 votes)
95 views29 pages

Lab 3 - A Smart Home With 2 Gateways and A Cloud: Nctu Introduction To Iot Fall 2020

The document describes a smart home system simulation using two Raspberry Pi gateways, various IoT sensors and actuators, and a cloud server. The system monitors temperature and humidity, controls lights and fans, and detects intruders. It is divided into three sections: 1) Temperature monitoring turns on a fan if temperature or humidity exceeds thresholds. 2) Automatic LED controls light brightness based on light sensors. 3) Intruder detection sends notifications, triggers a buzzer, and captures photos if motion is detected.

Uploaded by

Kanha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
95 views29 pages

Lab 3 - A Smart Home With 2 Gateways and A Cloud: Nctu Introduction To Iot Fall 2020

The document describes a smart home system simulation using two Raspberry Pi gateways, various IoT sensors and actuators, and a cloud server. The system monitors temperature and humidity, controls lights and fans, and detects intruders. It is divided into three sections: 1) Temperature monitoring turns on a fan if temperature or humidity exceeds thresholds. 2) Automatic LED controls light brightness based on light sensors. 3) Intruder detection sends notifications, triggers a buzzer, and captures photos if motion is detected.

Uploaded by

Kanha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Lab 3 - A Smart Home with 2 Gateways and a Cloud

NCTU introduction to IoT


Fall 2020

1
Outline
• Lab Objective
• System Specification
• Topology
• Section 1 – Temperature Monitoring
• Section 2 – Automatic LED
• Section 3 – Intruder Detection

2
Lab Objective
• Simulate the smart home system
• Using 2 Raspberry Pi’s as Gateways
• Connecting 4 types of IoT sensors
• Connecting 3 types of actuators
• Collaborate with MediaTek Cloud Sandbox server (MCS)
• Capable to collaborate more than one Raspberry Pi
• Capable to make the complex IoT system

3
System Specification – Topology
Camera

GPIO19
PIR sensor
2 1
API
API Buzzer
GPIO8
API

GPIO17
GPIO22 GPIO17 GPIO26
GPIO25
GPIO22

Light sensor
Light sensor Relay module LED
DHT sensor
DHT sensor
Fan
4
How to Build it?

Section 1:Temperature/Humidity too high → Turn on the fan.

Section 2: Brightness in the room → Luminates the LED.

Section 3: Intruder detected → Send a Line Notification + Play the


buzzer + Capture a photo.

5
System Specification – Section 1 (1/4)

2 1 Measure temp/humidity
API
API
by DHT sensors.

Raspberry Pi 1 and 2
GPIO22
GPIO22 send the data to MCS.

DHT sensor Relay module


DHT sensor
Fan 6
System Specification – Section 1 (2/4)

1
1st Raspberry Pi API

retrieves the data from 2nd Raspberry Pi,

calculates the average,

sends back to MCS.

Relay module
DHT sensor
Fan
7
System Specification – Section 1 (3/4)

1
( Avg Temp > 27˚C ) or ( Avg Humidity > 80% ), API

MCS sets on the Fancontrol data channel.

1st Raspberry Pi receives the signal,


GPIO26

turns on the fan through relay module.

Relay module
DHT sensor
Fan
8
System Specification – Section 1 (4/4)

9
System Specification – Section 2 (1/3)

Click on the LightAutomation Measure light level

button on MCS to start. by light sensors.


2 1 1st and 2nd Raspberry Pi
API API
send the data to MCS.

GPIO17
GPIO17

Light sensor
LED
Light sensor

10
System Specification – Section 2 (2/3)

1
API

1st Raspberry Pi retrieves the data of


2nd Raspberry Pi, chooses the darker
GPIO25

one’s value, modulates the luminance


of LED.
LED Light sensor

11
System Specification – Section 2 (3/3)

12
System Specification – Section 3 (1/4)

This alarm system keeps running.

Detect an intruder by PIR sensor. GPIO19 PIR sensor

Pi 1
Buzzer

13
System Specification – Section 3 (2/4)

If detected,

1st Raspberry Pi plays the buzzer to PIR sensor

Pi 1
give a warning and sends a line notify
GPIO8 Buzzer

to the owner immediately. API

14
System Specification – Section 3 (2/4)

Then, 1st Raspberry Pi captures the


image from Camera and send it into PIR sensor

MCS Pi 1

Camera
API

15
System Specification – Section 3 (3/3)
Start

Intruder Detected No Sleep for 2s

Yes

Raspberry Pi 1 sends Line


Notification through Line API

Raspberry Pi 1 plays the buzzer

Raspberry Pi 1 captures the


photo, then send it to MCS

16
System Components
Hardware
Component Name Model Functionality
3x Raspberry Pi 4 Model B, 1 GB RAM Gateway
1x LED Red Visible LED
2x LDR Sensor GL55 Measure the light level
2x Capacitor 1 µF, 50 V Construct RC circuits
3x Resistor 1 kΩ Adjust the voltage
1x PIR sensor HW–416–B Detect the motion
1x Buzzer G-S&S Alarm the intruder
2x DHT sensor AM2302 Measure temp/humidity
2x Fan Raspberry Pi cooling fan Cool down the room
1x Relay module 4–channel 5V Adjust the voltage
1x Camera Raspberry Pi Camera Capture the images
Bread board EIC–1104 Build electronic circuits
Dupont wire Male to Male/Male to Female/Female to Female Construct circuits
17
MCS Dashboard

18
How to Send Notification via Line

• Register at https://notify-
bot.line.me/my/
• Log in by using your Line
account
• Click “Generate Token”

19
MCS Restriction

• Data channel
• Function cannot use the data of other data channels to compute.
• Solution:Retrieves the data, does the computation like average of temp/humidity in
Raspberry.

• ”Bad Access” if query too often


• Solution:Raspberry Pi sends the measured data all at once every 30 seconds.

20
Implementation Photos (1/2)
1st Raspberry Pi

21
Implementation Photos (2/2)
2nd Raspberry Pi

22
1st Raspberry Pi (Source Code) (1/4)
import RPi.GPIO as GPIO sensor = Adafruit_DHT.DHT11
import lineTool pin = 21 #BCM
import time
import http.client, urllib ## Device ID from MCS
import json deviceId = "DkXsnJRf"
import Adafruit_DHT deviceKey = "KUvi9AgEkz9cfEho"
import requests
import socket def linenotify(a,b):
import picamera lineTool.lineNotify(a,b)
from picamera import PiCamera
import numpy as np def play(p, frequency, tempo):
import base64 p.ChangeFrequency(frequency)
time.sleep(0.5 * tempo)
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD) def bell():
token=”INSERT_YOUR_TOKEN_HERE" C4 = 262 # Do
msg="Intruder detected!" E4 = 330 # Mi

PIR_pin=35 music = [C4, E4]


GPIO.setup(PIR_pin,GPIO.IN) M_1 = C4
M_3 = E4
ledPin = 22
ldrPin = 12 GPIO.setup(24, GPIO.OUT)
GPIO.setup(ledPin,GPIO.OUT) p = GPIO.PWM(24, 50)
p.start(15) # 0 <= DV <= 100
fan_pin = 37
fan_pin2 = 36 play(p, M_3, 1)
GPIO.setup(fan_pin, GPIO.OUT) play(p, M_1, 1)
GPIO.setup(fan_pin2, GPIO.OUT)
p.stop
PWM_FREQ=200
pwm=GPIO.PWM(ledPin,PWM_FREQ)
pwm.start(0) #Start control PWM and initialize to 0 23
1st Raspberry Pi (Source Code) (2/4)
# Set MediaTek Cloud Sandbox (MCS) Connection def readLDR(PIN):
def post_to_mcs(payload): reading=0
headers = {"Content-type": "application/json", "deviceKey": deviceKey} GPIO.setup(PIN, GPIO.OUT)
not_connected = 1 GPIO.output(PIN, False)
while (not_connected): time.sleep(0.1)
try: GPIO.setup(PIN, GPIO.IN)
conn = http.client.HTTPConnection("api.mediatek.com:80") while (GPIO.input(PIN)==False):
conn.connect() reading=reading+1
not_connected = 0 return reading
except (http.client.HTTPException, socket.error) as ex:
print ("Error: %s" % ex) def PWM_LED(lightlevel):
time.sleep(10) # sleep 10 seconds duty_cycle=lightlevel/100 #duty_cycle:0~100
if(duty_cycle>=100):duty_cycle=100
conn.request("POST", "/mcs/v2/devices/" + deviceId + "/datapoints", pwm.ChangeDutyCycle(duty_cycle)
json.dumps(payload), headers)
response = conn.getresponse() def turnonFAN(fan_input):
#print( response.status, response.reason, json.dumps(payload), GPIO.output(fan_input, False)
time.strftime("%c"))
data = response.read() def turnoffFAN(fan_input):
conn.close() GPIO.output(fan_input, True)

def get_to_mcs(channelID):
host = "http://api.mediatek.com"
endpoint = "/mcs/v2/devices/" + deviceId + "/datachannels/" + channelID +
"/datapoints"
url = host + endpoint
headers = {"Content-type": "application/json", "deviceKey": deviceKey}
r = requests.get(url,headers=headers)
value = (r.json()["dataChannels"][0]["dataPoints"][0]["values"]["value"])
return value
24
1st Raspberry Pi (Source Code) (3/4)
while(True):
## Average Temperature and Humidity then post it to MCS
try:
Temperature_Avg = (temp + Temperature2)/2
## Light Sensor
print ("AVG : ", Temperature_Avg)
LightLevel1 = readLDR(ldrPin)
Humidity2 = get_to_mcs(str(5))
Lightlevel2 = get_to_mcs(str(12))
Humidity_Avg=(humidity+Humidity2)/2
LightAutomation=get_to_mcs(str(9))
payload =
if(LightLevel1-Lightlevel2>0):
{"datapoints":[{"dataChnId":"3","values":{"value":str(Temperatur
Lightlevel_min=Lightlevel2
e_Avg)}},{"dataChnId":"6","values":{"value":str(Humidity_Avg)}}]
else:Lightlevel_min=LightLevel1
}
post_to_mcs(payload)
## Read Temperature 1 and post it to MCS
humidity,temp = Adafruit_DHT.read_retry(sensor, pin)
## FANControl 1
payload =
if (get_to_mcs(str(7)) == 1):
{"datapoints":[{"dataChnId":"4","values":{"value":humidity}},{"dataChn
get_to_mcs(str(7))
Id":"1","values":{"value":temp}},{"dataChnId":"11","values":{"value":s
turnonFAN(fan_pin)
tr(LightLevel1)}}]}
post_to_mcs(payload)
elif(get_to_mcs(str(7)) == 0):
turnoffFAN(fan_pin)
if(LightAutomation==1):
print("Light automation activates.")
## FANControl 2
PWM_LED(Lightlevel_min)
if (get_to_mcs(str(8)) == 1):
turnonFAN(fan_pin2)
else:
elif(get_to_mcs(str(8)) == 0):
print("Light automation deactivates.")
turnoffFAN(fan_pin2)
PWM_LED(0)

## Read Temperature 2
Temperature2 = get_to_mcs(str(2))
print ("Debug Temp : ", Temperature2)
25
1st Raspberry Pi (Source Code) (4/4)
# PIR Setup
i=GPIO.input(PIR_pin)
if(i==0):
print("No intruder.")
time.sleep(2)
elif(i==1):
print("Intruder detected.")
linenotify(token,msg)
camera = PiCamera()
camera.resolution = (720,480)
camera.start_preview()
camera.capture('intruder.jpg')
camera.stop_preview()
with open("intruder.jpg","rb") as img_file:
EncodeBytes = base64.b64encode(img_file.read())
EncodeStr = str(EncodeBytes, "utf-8")
payload = {"datapoints":[{"dataChnId":"20","values":{"value":EncodeStr}}]}
post_to_mcs(payload)
bell()
time.sleep(2)
except KeyboardInterrupt:
break

GPIO.cleanup()

26
2nd Raspberry Pi (Source Code)
# Import Libraries # Set MediaTek Cloud Sandbox (MCS) Connection
import time def post_to_mcs(payload):
import http.client, urllib headers = {"Content-type": "application/json", "deviceKey":
import json deviceKey}
import Adafruit_DHT not_connected = 1
import RPi.GPIO as GPIO while (not_connected):
import requests try:
Import socket conn = http.client.HTTPConnection("api.mediatek.com:80")
conn.connect()
not_connected = 0
# Set Pin for Sensors except (http.client.HTTPException, socket.error) as ex:
#LDR print ("Error: %s" % ex)
GPIO.setmode(GPIO.BOARD) time.sleep(10) # sleep 10 seconds
GPIO.setwarnings(False)
conn.request("POST", "/mcs/v2/devices/" + deviceId +
ldrPin = 36 "/datapoints", json.dumps(payload), headers)
response = conn.getresponse()
sensor = Adafruit_DHT.DHT11 print( response.status, response.reason, json.dumps(payload),
pin = 21 time.strftime("%c"))
data = response.read()
# Set MediaTek Cloud Sandbox (MCS) Key conn.close()
deviceId = ”YOUR_DEVICE_ID"
deviceKey = ”YOUR_DEVICE_KEY" # Post MediaTek Cloud Sandbox (MCS)
while True:
# Set Function for Reading LDR [humidity,temp] = Adafruit_DHT.read_retry(sensor, pin)
def readLDR(PIN): print("temp = %.02f C humidity =%.02f%%"%(temp, humidity))
reading=0 ldr_reading = readLDR(ldrPin)
GPIO.setup(PIN, GPIO.OUT) print("LDR : ", ldr_reading)
GPIO.output(PIN, False) payload =
time.sleep(0.1) {"datapoints":[{"dataChnId":"5","values":{"value":humidity}},{"dataChn
GPIO.setup(PIN, GPIO.IN) Id":"2","values":{"value":temp}},{"dataChnId":"12","values":{"value":s
while (GPIO.input(PIN)==False): tr(ldr_reading)}}]}
reading=reading+1 post_to_mcs(payload) 27
return reading time.sleep(5)
Assignment 3 - Specification
• Objectives:
• IoT with Complex Sensors and Actuators
• Collaborate 2 Raspberry Pi’s with MCS
• Upload to E3 before 12/21 (Mon) at 23:59PM
• Assignment 3 – deliverables
• Report (2-4 pages)
• Explain the objectives
• Explain the specification of sensors and actuators used
• Explain the system design
• Flowchart of your system
• Explain your python and javascript source codes
• The differences with example codes
• The detail of how your scripts work
• Source Codes
• 3~5-minute demo video (just the URL of video)
• Report can be written in Chinese, and for Video, it must be delivered in English or with English
Caption
• Zip the above files into one compressed file and upload
• Q&A? Post on E3 discussion board
28
Thank You

29

You might also like