Lesson 4: Motion sensor and relay
Objective
Using Grove - mini PIR motion detector to detect movement and switch on the light when passing by.
Hardware requirement
Prepare:
- microUSB cable
- Raspberry Pi 3 Model B
- Computer
Included in the set
- Grove Base Hat
- Grove wire
- Grove - mini PIR motion detector
- Grove - relay
Connecting equipment
Step 1 Connect Grove - mini PIR motion detector to port D5, Grove - relay to port D16 on Base Hat.
Step 2 Connect Base Hat to Raspberry Pi.
Step 3 Connect the Raspberry Pi to the power source using the microUSB cable.
Programming
|
Note Make sure you clone the python.py repository library on your Raspberry Pi. |
Step 1: Enter the following commands to create a Python file
cd grove.py nano lesson_4.py
Step 2: Copy the code below:
#!/usr/bin/env python
import time
from grove.grove_mini_pir_motion_sensor import GroveMiniPIRMotionSensor
from grove.grove_relay import GroveRelay
def main():
# Grove - mini PIR motion sensor connected to port D5
sensor = GroveMiniPIRMotionSensor(5)
# Grove - Relay connected to port D16
relay = GroveRelay(16)
def on_detect():
print('motion detected')
relay.on()
print('relay on')
time.sleep(1)
relay.off()
print('relay off')
sensor.on_detect = on_detect
while True:
time.sleep(1)
if __name__ === '__main__':
main()
Step 3:Uruchomprogram:
sudo chmod +x lesson_4.py sudo ./lesson_4.py
If everything went well, you should see that the relay is on/off when motion is detected.
pi@raspberrypi:~/grove.py $ sudo ./lesson_4.py motion detected relay on relay off motion detected relay on relay off ^CTraceback (most recent call last): File "./lesson_4.py", line 33, inmain() File "./lesson_4.py", line 30, in main time.sleep(1) KeyboardInterrupt pi@raspberrypi:~/grove.py $


