超声波模块HC-SR04测距传感器用树莓PI Python库。

Bluetin-Echo的Python项目详细描述


该传感器使用声波提供测量 传感器和物体之间的距离。它不是最 提供精确的距离传感器,但许多项目没有 需要精确定位。在浏览了Banggood网站之后, 您可以获得5个HC-SR04传感器,价格为5.07英镑(6.86美元)。以及 虽然传感器不是最紧凑的,但它的低价格意味着 一个机器人车辆可以有一个完整的传感器套件安装非常便宜。

您可以在此处找到文章以了解更多详细信息:

Article

示例代码

最简单的测距程序:

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

多个距离测量示例:

"""File: echo_loop.py"""# Import necessary libraries.fromBluetin_EchoimportEcho# Define GPIO pin constants.TRIGGER_PIN=16ECHO_PIN=12# Initialise Sensor with pins, speed of sound.speed_of_sound=315echo=Echo(TRIGGER_PIN,ECHO_PIN,speed_of_sound)# Measure Distance 5 times, return average.samples=5# Take multiple measurements.forcounterinrange(0,10):result=echo.read('cm',samples)# Print result.print(result,'cm')# Reset GPIO Pins.echo.stop()

多传感器回路

"""File: echo_multi_sensor.py"""# Import necessary libraries.fromtimeimportsleepfromBluetin_EchoimportEcho# Define pin constantsTRIGGER_PIN_1=16ECHO_PIN_1=12TRIGGER_PIN_2=26ECHO_PIN_2=19# Initialise two sensors.echo=[Echo(TRIGGER_PIN_1,ECHO_PIN_1),Echo(TRIGGER_PIN_2,ECHO_PIN_2)]defmain():sleep(0.1)forcounterinrange(1,6):forcounter2inrange(0,len(echo)):result=echo[counter2].read('cm',3)print('Sensor {} - {} cm'.format(counter2,round(result,2)))echo[0].stop()if__name__=='__main__':main()

库v0.2.0

测试所有库功能

#!/usr/bin/env python3fromtimeimportsleepfromBluetin_EchoimportEcho""" Define GPIO pin constants """TRIGGER_PIN=17ECHO_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)defmain():"""
        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.speedprint('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.restprint('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_timeoutprint('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_timeoutprint('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_offsetprint('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_codeprint('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_unitprint('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=1result=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=10result=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()

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java JavaFX触控事件未触发Ubuntu 20.04触控笔记本电脑   java如何在AWT中关闭窗口?   java Dagger 2:注入具有构造函数参数的成员   创建对象的Java调用类   对象我想在A.java中添加两个数字,并在B.java中打印结果(如何?)   java如何使用AWS SDK for Android从数字海洋空间下载图像?   java Facebook sdk 4.0.1无法使用Android studio获取某些字段   4分钟后web应用程序(Angular 8和Rest API)中的java自动会话超时   在Eclipse for Java EE developers edition中禁用HTML警告   java按字母顺序排列字符串我错过了什么明显的东西吗?   java在Jshell中println和printf有什么不同