Lesson 5: Ultrasonic distance sensor and relay

Objective

In this lesson we will use the Grove - ultrasonic distance sensor to measure the distance when someone comes close, the light on the Grove - relay should switch on.

Hardware requirement

Prepare:

  • microUSB cable
  • Raspberry Pi
  • Computer

Included in the set

  • Grove Base Hat
  • Grove wire
  • Grove - Ultrasonic distance sensor
  • Grove - Relay

Connecting equipment

Step 1 Connect Grove - Ultrasonic distance sensor 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_5.py

Step 2: Copy the following code

  1. #!/usr/bin/env python
  2.  
  3. import time
  4.  
  5. from grove.grove_relay import GroveRelay
  6. from grove.grove_ultrasonic_ranger import GroveUltrasonicRanger
  7.  
  8. def main():
  9. # Grove - Ultrasonic Ranger connected to port D5
  10. sensor = GroveUltrasonicRanger(5)
  11.  
  12. # Grove - Relay connected to port D16
  13. relay = GroveRelay(16)
  14.  
  15. while True:
  16. distance = sensor.get_distance()
  17. print('{} cm'.format(distance))
  18.  
  19. if distance < 20:
  20. relay.on()
  21. print('relay on')
  22.  
  23. time.sleep(1)
  24.  
  25. relay.off()
  26. print('relay off')
  27.  
  28. continue
  29.  
  30. time.sleep(1)
  31.  
  32. if __name__ === '__main__':
  33. main()

Step 3:Uruchomprogram

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

If everything goes well, a change in light intensity should cause a change in the angle of rotation of the servo.

  1. pi@raspberrypi:~/grove.py $ sudo ./lesson_5.py
  2. 253.722585481 cm
  3. 253.739028141 cm
  4. 252.896341784 cm
  5. 1.20442489098 cm
  6. relay on
  7. relay off
  8. 4.51762100746 cm
  9. relay on
  10. relay off
  11. 253.985668051 cm
  12. ^CTraceback (most recent call last):
  13. File "./lesson_5.py", line 34, in
  14. main()
  15. File "./lesson_5.py", line 31, in main
  16. time.sleep(1)
  17. KeyboardInterrupt
  18. pi@raspberrypi:~/grove.py $

Now compare your results from the fourth and fifth lessons. Can you list the advantages and disadvantages of Grove - a mini PIR motion detector and Grove ultrasonic distance sensor?

Table of contents

Botland.store - shop for makers!