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

cd grove.py
nano lesson_5.py

Step 2: Copy the following code

#!/usr/bin/env python

import time

from grove.grove_relay import GroveRelay
from grove.grove_ultrasonic_ranger import GroveUltrasonicRanger

def main():
    # Grove - Ultrasonic Ranger connected to port D5
    sensor = GroveUltrasonicRanger(5)

    # Grove - Relay connected to port D16
    relay = GroveRelay(16)

    while True:
        distance = sensor.get_distance()
        print('{} cm'.format(distance))

        if distance < 20:
            relay.on()
            print('relay on')

            time.sleep(1)

            relay.off()
            print('relay off')

            continue

        time.sleep(1)

if __name__ === '__main__':
    main()

Step 3:Uruchomprogram

sudo chmod +x lesson_5.py
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.

pi@raspberrypi:~/grove.py $ sudo ./lesson_5.py
253.722585481 cm
253.739028141 cm
252.896341784 cm
1.20442489098 cm
relay on
relay off
4.51762100746 cm
relay on
relay off
253.985668051 cm
^CTraceback (most recent call last):
  File "./lesson_5.py", line 34, in 
    main()
  File "./lesson_5.py", line 31, in main
    time.sleep(1)
KeyboardInterrupt
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!