.. note::

    Hello, welcome to the SunFounder Raspberry Pi & Arduino & ESP32 Enthusiasts Community on Facebook! Dive deeper into Raspberry Pi, Arduino, and ESP32 with fellow enthusiasts.

    **Why Join?**

    - **Expert Support**: Solve post-sale issues and technical challenges with help from our community and team.
    - **Learn & Share**: Exchange tips and tutorials to enhance your skills.
    - **Exclusive Previews**: Get early access to new product announcements and sneak peeks.
    - **Special Discounts**: Enjoy exclusive discounts on our newest products.
    - **Festive Promotions and Giveaways**: Take part in giveaways and holiday promotions.

    👉 Ready to explore and create with us? Click [|link_sf_facebook|] and join today!

.. _2.2.8_py:

2.2.8 Ultrasonic Sensor Module
==============================

Introduction
--------------

The ultrasonic sensor uses ultrasonic to accurately detect objects and
measure distances. It sends out ultrasonic waves and converts them into
electronic signals.

Required Components
------------------------------

In this project, we need the following components. 

.. image:: ../img/list_2.2.5.png

It's definitely convenient to buy a whole kit, here's the link: 

.. list-table::
    :widths: 20 20 20
    :header-rows: 1

    *   - Name	
        - ITEMS IN THIS KIT
        - LINK
    *   - Raphael Kit
        - 337
        - |link_Raphael_kit|

You can also buy them separately from the links below.

.. list-table::
    :widths: 30 20
    :header-rows: 1

    *   - COMPONENT INTRODUCTION
        - PURCHASE LINK

    *   - :ref:`cpn_gpio_extension_board`
        - |link_gpio_board_buy|
    *   - :ref:`cpn_breadboard`
        - |link_breadboard_buy|
    *   - :ref:`cpn_wires`
        - |link_wires_buy|
    *   - :ref:`cpn_ultrasonic_sensor`
        - |link_ultrasonic_buy|

Schematic Diagram
-----------------

.. image:: ../img/image329.png


Experimental Procedures
-----------------------

**Step 1:** Build the circuit.

.. image:: ../img/image220.png

**Step 2:** Go to the folder of the code.

.. raw:: html

   <run></run>

.. code-block::

    cd ~/raphael-kit/python/

**Step 3:** Run the executable file.

.. raw:: html

   <run></run>

.. code-block::

    sudo python3 2.2.8_Ultrasonic.py

With the code run, the ultrasonic sensor module detects the distance
between the obstacle ahead and the module itself, then the distance
value will be printed on the screen.

**Code**

.. note::

    You can **Modify/Reset/Copy/Run/Stop** the code below. But before that, you need to go to  source code path like ``raphael-kit/python``. After modifying the code, you can run it directly to see the effect.


.. raw:: html

    <run></run>

.. code-block:: python

    import RPi.GPIO as GPIO
    import time

    TRIG = 16
    ECHO = 18

    def setup():
        GPIO.setmode(GPIO.BOARD)
        GPIO.setup(TRIG, GPIO.OUT)
        GPIO.setup(ECHO, GPIO.IN)

    def distance():
        GPIO.output(TRIG, 0)
        time.sleep(0.000002)

        GPIO.output(TRIG, 1)
        time.sleep(0.00001)
        GPIO.output(TRIG, 0)

        while GPIO.input(ECHO) == 0:
            a = 0
        time1 = time.time()
        while GPIO.input(ECHO) == 1:
            a = 1
        time2 = time.time()

        during = time2 - time1
        return during * 340 / 2 * 100

    def loop():
        while True:
            dis = distance()
            print ('Distance: %.2f' % dis )
            time.sleep(0.3)

    def destroy():
        GPIO.cleanup()

    if __name__ == "__main__":
        setup()
        try:
            loop()
        except KeyboardInterrupt:
            destroy()

**Code Explanation**

.. code-block:: python

    def distance():

This function is used to realize the function of ultrasonic sensor by
calculating the return detection distance.

.. code-block:: python

    GPIO.output(TRIG, 1)
    time.sleep(0.00001)
    GPIO.output(TRIG, 0)

This is sending out a 10us ultrasonic pulse.

.. code-block:: python

    while GPIO.input(ECHO) == 0:
        a = 0
    time1 = time.time()

This empty loop is used to ensure that when the trigger signal is sent,
there is no interfering echo signal and then get the current time.

.. code-block:: python

    while GPIO.input(ECHO) == 1:
        a = 1
    time2 = time.time()

This empty loop is used to ensure that the next step is not performed
until the echo signal is received and then get the current time.

.. code-block:: python

    during = time2 - time1

Execute the interval calculation.

.. code-block:: python

    return during * 340 / 2 * 100

The distance is calculated in the light of time interval and the speed
of sound propagation. The speed of sound in the air: 340m/s.

Phenomenon Picture
------------------

.. image:: ../img/image221.jpeg