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

  1. cd grove.py
  2. nano lesson_4.py

Step 2: Copy the code below:

  1. #!/usr/bin/env python
  2.  
  3. import time
  4.  
  5. from grove.grove_mini_pir_motion_sensor import GroveMiniPIRMotionSensor
  6. from grove.grove_relay import GroveRelay
  7.  
  8. def main():
  9. # Grove - mini PIR motion sensor connected to port D5
  10. sensor = GroveMiniPIRMotionSensor(5)
  11.  
  12. # Grove - Relay connected to port D16
  13. relay = GroveRelay(16)
  14.  
  15. def on_detect():
  16. print('motion detected')
  17.  
  18. relay.on()
  19. print('relay on')
  20.  
  21. time.sleep(1)
  22.  
  23. relay.off()
  24. print('relay off')
  25.  
  26. sensor.on_detect = on_detect
  27.  
  28. while True:
  29. time.sleep(1)
  30.  
  31. if __name__ === '__main__':
  32. main()

Step 3:Uruchomprogram:

  1. sudo chmod +x lesson_4.py
  2. sudo ./lesson_4.py

If everything went well, you should see that the relay is on/off when motion is detected.

  1. pi@raspberrypi:~/grove.py $ sudo ./lesson_4.py
  2. motion detected
  3. relay on
  4. relay off
  5. motion detected
  6. relay on
  7. relay off
  8. ^CTraceback (most recent call last):
  9. File "./lesson_4.py", line 33, in
  10. main()
  11. File "./lesson_4.py", line 30, in main
  12. time.sleep(1)
  13. KeyboardInterrupt
  14. pi@raspberrypi:~/grove.py $

Table of contents

Botland.store - shop for makers!