Skip to main content

Raspberry Pi Python Library for Ultrasonic Module HC-SR04 Distance Measuring Transducer.

Project description

This sensor uses sound waves to provide a means to measure the distance between the sensor and an object. It is not the most accurate distance sensor available, but many projects do not need pinpoint accuracy. After a quick look at Banggood website, you can get five HC-SR04 sensors for 5.07 GBP (6.86 USD). And while the sensor is not the most compact, its low price means a robot vehicle can have a full sensor kit fitted very cheaply.

You can find the article here for more details:

Article.

Example Code

Simplest Program for Distance Measuring:

# Import necessary libraries.
from Bluetin_Echo import Echo

# Define GPIO pin constants.
TRIGGER_PIN = 16
ECHO_PIN = 12
# Initialise Sensor with pins, speed of sound.
speed_of_sound = 315
echo = Echo(TRIGGER_PIN, ECHO_PIN, speed_of_sound)
# Measure Distance 5 times, return average.
samples = 5
result = echo.read('cm', samples)
# Print result.
print(result, 'cm')
# Reset GPIO Pins.
echo.stop()

Example for Taking Multiple Distance Measurements:

"""File: echo_loop.py"""
# Import necessary libraries.
from Bluetin_Echo import Echo

# Define GPIO pin constants.
TRIGGER_PIN = 16
ECHO_PIN = 12
# Initialise Sensor with pins, speed of sound.
speed_of_sound = 315
echo = Echo(TRIGGER_PIN, ECHO_PIN, speed_of_sound)
# Measure Distance 5 times, return average.
samples = 5
# Take multiple measurements.
for counter in range(0, 10):
    result = echo.read('cm', samples)
    # Print result.
    print(result, 'cm')

# Reset GPIO Pins.
echo.stop()

Loop Through Multiple Sensors

"""File: echo_multi_sensor.py"""
# Import necessary libraries.
from time import sleep

from Bluetin_Echo import Echo

# Define pin constants
TRIGGER_PIN_1 = 16
ECHO_PIN_1 = 12
TRIGGER_PIN_2 = 26
ECHO_PIN_2 = 19

# Initialise two sensors.
echo = [Echo(TRIGGER_PIN_1, ECHO_PIN_1)
        , Echo(TRIGGER_PIN_2, ECHO_PIN_2)]

def main():
    sleep(0.1)
    for counter in range(1, 6):
        for counter2 in range(0, len(echo)):
            result = echo[counter2].read('cm', 3)
            print('Sensor {} - {} cm'.format(counter2, round(result,2)))

    echo[0].stop()

if __name__ == '__main__':
    main()

Library v0.2.0

Test All Library Features

#!/usr/bin/env python3

from time import sleep
from Bluetin_Echo import Echo

""" Define GPIO pin constants """
TRIGGER_PIN = 17
ECHO_PIN = 18
""" Calibrate sensor with initial speed of sound m/s value """
SPEED_OF_SOUND = 343
""" Initialise Sensor with pins, speed of sound. """
echo = Echo(TRIGGER_PIN, ECHO_PIN, SPEED_OF_SOUND)


def main():
        """
        Test class properties and methods.
        """

        print('\n+++++ Properties +++++\n')

        """
        Check that the sensor is ready to operate.
        """
        print('Sensor ready? {}'.format(echo.is_ready))
        sleep(0.06)
        print('Sensor ready? {}'.format(echo.is_ready))

        """
        You can adjust the speed of sound to fit environmental conditions.
        """
        speed = echo.speed
        print('Speed of sound Setting: {}m/s'.format(speed))
        echo.speed = speed

        """
        This setting is important because it allows a rest period between
        each sensor activation. Accessing the sensor within a rest period
        will result in a Not Ready (2) error code. Reducing the value of
        this setting can cause unstable sensor readings.
        """
        restTime = echo.rest
        print('Sensor rest time: {}s'.format(restTime))
        echo.rest = restTime

        """
        The default is fine for this property. This timeout prevents the
        code from getting stuck in an infinite loop in case the sensor
        trigger pin fails to change state.
        """
        triggerTimeout = echo.trigger_timeout
        print('Sensor trigger timeout: {}s'.format(triggerTimeout))
        echo.trigger_timeout = triggerTimeout

        """
        Read and update sensor echo timeout.
        The is an alternative way to set a maximum sensor scan distance
        using a time value.
        """
        echoTimeout = echo.echo_timeout
        print('Sensor echo timeout: {}s'.format(echoTimeout))
        echo.echo_timeout = echoTimeout

        """
        This property adds a time offset to the max sensor distance
        setting. Adjust this property value to stop the sensor out of range
        error appearing below the maximum distance setting during operation.
        """
        echoOffset = echo.echo_return_offset
        print('Sensor echo time offset: {}s'.format(echoOffset))
        echo.echo_return_offset = echoOffset

        """
        Read this property to get the error code following a sensor read.
        The error codes are integer values; 0 = Good, 1 = Out of Range and
        2 = Not Ready.
        """
        errorCode = echo.error_code
        print('Error code from last sensor read: {}'.format(errorCode))

        """
        The default sensor scan distance is set to 3m. The following property
        will allow an alternate max scan distance setting. Any sensor echos
        that fall outside the set distance will cause an out of range error.
        Units mm, cm, m and inch are supported.
        You can tune the sensor to match the max distance setting using the
        echo_return_offset property.
        """
        echo.max_distance(30, 'cm')

        """
        This property sets the default measuring unit, which works with
        the new send and samples methods. Set this property once with your
        prefered unit of measure. Then use the send method to return sensor
        results in that unit you set. Class default is cm on initialisation.
        """
        defaultUnit = echo.default_unit
        print('Current Unit Setting: {}'.format(defaultUnit))
        echo.default_unit = defaultUnit

        """
        Test using each unit of measure.
        """
        print('\n+++++ Single sample sensor reads. +++++\n')
        sleep(0.06)
        averageOf = 1
        result = echo.read('mm', averageOf)
        print('{:.2f} mm, Error: {}'.format(result, echo.error_code))
        sleep(0.06)
        result = echo.read('cm', averageOf)
        print('{:.2f} cm, Error: {}'.format(result, echo.error_code))
        sleep(0.06)
        result = echo.read('m', averageOf)
        print('{:.2f} m, Error: {}'.format(result, echo.error_code))
        sleep(0.06)
        result = echo.read('inch', averageOf)
        print('{:.2f} inch, Error: {}'.format(result, echo.error_code))

        """
        Then, get an average of multiple reads.
        """
        print('\n+++++ Return an average of multiple sensor reads. +++++\n')
        sleep(0.06)
        averageOf = 10
        result = echo.read('mm', averageOf)
        print('Average: {:.2f} mm'.format(result))
        sleep(0.06)
        result = echo.read('cm', averageOf)
        print('Average: {:.2f} cm'.format(result))
        sleep(0.06)
        result = echo.read('m', averageOf)
        print('Average: {:.2f} m'.format(result))
        sleep(0.06)
        result = echo.read('inch', averageOf)
        print('Average: {:.2f} inch'.format(result))

        """
        Get a single sensor read using the default unit of measure.
        Check error codes after each sensor reading to monitor operation
        success.
        """
        print('\n+++++ Single sensor read using the default unit of measure. +++++\n')
        sleep(0.06)
        echo.default_unit = 'm'
        result = echo.send()
        print('{:.2f} m, Error: {}'.format(result, echo.error_code))

        """
        Get an average value from multiple sensor readings. Returns an average of
        only the good sensor reads. The average value is returned with
        the number of samples used to make the average sum calculation.
        """
        print('\n+++++ Return an average from multiple sensor reads. +++++')
        print('+++++ Returns two values; average and good samples. +++++\n')
        sleep(0.06)
        echo.default_unit = 'm'
        result, samples = echo.samples(10)
        print('Average: {:.2f} m, From {} good samples'.format(result, samples))

        """ Reset GPIO Pins. """
        echo.stop()


if __name__ == "__main__":
        main()

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

Bluetin_Echo-0.2.0.tar.gz (7.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

Bluetin_Echo-0.2.0-py3-none-any.whl (8.7 kB view details)

Uploaded Python 3

File details

Details for the file Bluetin_Echo-0.2.0.tar.gz.

File metadata

  • Download URL: Bluetin_Echo-0.2.0.tar.gz
  • Upload date:
  • Size: 7.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.0.1 requests-toolbelt/0.9.1 tqdm/4.32.1 CPython/3.7.3

File hashes

Hashes for Bluetin_Echo-0.2.0.tar.gz
Algorithm Hash digest
SHA256 edc5c0ba50bd4d430f12a5f16af501ee90eeddbc25d8fcd1a18801c3970184cf
MD5 c7204ab23e1a10c51b9fc2e9f70f6462
BLAKE2b-256 e6c95f67b9fa933ad9d3ead886f2c007a11880d1970abaf5d1dd90bac8d2aad6

See more details on using hashes here.

File details

Details for the file Bluetin_Echo-0.2.0-py3-none-any.whl.

File metadata

  • Download URL: Bluetin_Echo-0.2.0-py3-none-any.whl
  • Upload date:
  • Size: 8.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.0.1 requests-toolbelt/0.9.1 tqdm/4.32.1 CPython/3.7.3

File hashes

Hashes for Bluetin_Echo-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 abf9c0d37a9bd84a8fe6824d63b46b5a9d7546a1381134813cae9fbba7bb0679
MD5 98610b76eed14dc4f99f198f47417b17
BLAKE2b-256 1d7d5ad3e2a10ff13a14b29310734b3fdd1e5e2b38cae7b8ccec4df782caad37

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page