Module for Ultrasonic sensor (HC-SR04)

All ESP8266 boards running MicroPython.
Official boards are the Adafruit Huzzah and Feather boards.
Target audience: MicroPython users with an ESP8266 board.
orsisam
Posts: 9
Joined: Mon Sep 05, 2016 5:58 pm

Re: Module for Ultrasonic sensor (HC-SR04)

Post by orsisam » Tue Sep 27, 2016 1:23 am

Thanks for pythoncoder to help me understood the code.
Thanks for skgsergio to share the code on Github: https://github.com/skgsergio/MicropythonLibs

Finally yesterday I success to modify the code to work with esp8266, I am testing using Wemos D1 Mini board. So, maybe it will compatible with all esp8266 board too. Here the code, hope it will usefull for other:

Code: Select all

##
# Ultrasonic library for MicroPython's pyboard.
# Compatible with HC-SR04 and SRF04.
#
# Copyright 2014 - Sergio Conde Gómez <skgsergio@gmail.com>
# Improved by Mithru Vigneshwara
# Modified by orsisam <orsi.amax@gmail.com> for
# compatibility with esp8266
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
##

#import pyb
import machine
import time

class Ultrasonic:
    def __init__(self, tPin, ePin):
        # WARNING: Don't use PA4-X5 or PA5-X6 as echo pin without a 1k resistor (Attention for PyBoard)
        self.triggerPin = tPin
        self.echoPin = ePin

        # Init trigger pin (out)
        self.trigger = machine.Pin(self.triggerPin)
        self.trigger.init(machine.Pin.OUT, pull=None, value=0)
        #self.trigger.PULL_DOWN()

        # Init echo pin (in)
        self.echo = machine.Pin(self.echoPin)
        self.echo.init(machine.Pin.IN, pull=None)

    def distance_in_inches(self):
        return (self.distance_in_cm() * 0.3937)

    def distance_in_cm(self):
        start = 0
        end = 0

        # Create a microseconds counter.
        #micros = pyb.Timer(2, prescaler=83, period=0x3fffffff)
        #micros.counter(0)

        # Send a 10us pulse.
        self.trigger.high()
        time.sleep_us(10)
        #pyb.udelay(10)
        self.trigger.low()

        # Wait 'till whe pulse starts.
        while self.echo.value() == 0:
            start = time.ticks_us()

        # Wait 'till the pulse is gone.
        while self.echo.value() == 1:
            end = time.ticks_us()

        # Deinit the microseconds counter
        # micros.deinit()

        # take time different between start and end pulse.
        differ = time.ticks_diff(start, end)

        # Calc the duration of the recieved pulse, divide the result by
        # 2 (round-trip) and divide it by 29 (the speed of sound is
        # 340 m/s and that is 29 us/cm).
        dist_in_cm = (differ / 2) / 29

        return dist_in_cm

orsisam
Posts: 9
Joined: Mon Sep 05, 2016 5:58 pm

Re: Module for Ultrasonic sensor (HC-SR04)

Post by orsisam » Tue Sep 27, 2016 1:30 am

mcauser wrote:@orsisam paste your git repo when it's ready and I'll help you test it on some of my D1 minis.
I haven't post to Github for the code, but I share the code here.

orsisam
Posts: 9
Joined: Mon Sep 05, 2016 5:58 pm

Re: Module for Ultrasonic sensor (HC-SR04)

Post by orsisam » Tue Sep 27, 2016 1:44 am

mcauser wrote:The D1 mini has a 5V line, but uses 3V3 logic, so you'll need to use a voltage divider for the Echo pin.
Here's an example of how to do it with a Raspberry Pi

It seems ernitron is right about the current draw being the limiting factor. HC-SR04 has a working current of 15mA but the ESP8266 maximum source/sink current is 12mA per pin.
I see, but I haven't work with this modification. I'll try then.. ;)

User avatar
ernitron
Posts: 84
Joined: Fri Jun 03, 2016 5:53 pm
Location: The Netherlands

Re: Module for Ultrasonic sensor (HC-SR04)

Post by ernitron » Tue Sep 27, 2016 11:21 am

I spot some problems in the double loop:

Code: Select all

while self.echo.value() == 0:
    start = time.ticks_us()
# Wait 'till the pulse is gone.
while self.echo.value() == 1:
    end = time.ticks_us()
If you miss (for some reason) the echo transition you could loop forever in the start and/or never entering in the end loop.
Besides I think that the start counter should be outside the loop otherwise the start will be so close to the end to be useless.
I would write:

Code: Select all

start = time.ticks_us()
while self.echo.value() == 0:
    pass
end = time.ticks_us()
# Wait 'till the pulse is gone.
while self.echo.value() == 1:
    end = time.ticks_us()
Or the more simplified version of my previous excerpt.

User avatar
pythoncoder
Posts: 4670
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: Module for Ultrasonic sensor (HC-SR04)

Post by pythoncoder » Tue Sep 27, 2016 12:53 pm

The data sheet http://www.micropik.com/PDF/HCSR04.pdf indicates that you should time from the 10us trigger to the start of the echo pulse. If I understand the Chinglish, that is. So I'd have thought this would work:

Code: Select all

    self.trigger.high()
    time.sleep_us(10)
    self.trigger.low()
    start = time.ticks_us()
    while self.echo.value() == 0:
        pass
    end = time.ticks_us()
This would still hang if no response were received. This could be fixed with a timeout in the loop, which effectively sets the maximum range:

Code: Select all

    self.trigger.high()
    time.sleep_us(10)
    self.trigger.low()
    start = time.ticks_us()
    while self.echo.value() == 0:
        if time.ticks_diff(start, time.ticks_us()) > THRESHOLD:
            break
    end = time.ticks_us()
Peter Hinch

User avatar
ernitron
Posts: 84
Joined: Fri Jun 03, 2016 5:53 pm
Location: The Netherlands

Re: Module for Ultrasonic sensor (HC-SR04)

Post by ernitron » Tue Sep 27, 2016 7:29 pm

Right @pythoncoder. If you look at my previous snippet is almost what you propose with a counter instead of a Threshold. Threshold usually is set to 38000 (38 millisec).

I am pretty sure the solution (you propose) to power with a steady source WeMos and HC-SR04 will work. I will test it on a breadbord and then solder a prototype very soon. Thanks.

greentree
Posts: 12
Joined: Wed Dec 16, 2015 3:16 am

Re: Module for Ultrasonic sensor (HC-SR04)

Post by greentree » Sun Nov 13, 2016 6:47 pm

Hi! I'm very interested in the potential of using inexpensive acoustic sensors for tide and wave measurements. Thanks for posting your work in progress. Are there any updates on your results and advice?

Lysenko
Posts: 62
Joined: Wed Aug 17, 2016 1:21 pm

Re: Module for Ultrasonic sensor (HC-SR04)

Post by Lysenko » Sun Nov 13, 2016 6:56 pm

greentree wrote:Hi! I'm very interested in the potential of using inexpensive acoustic sensors for tide and wave measurements. Thanks for posting your work in progress. Are there any updates on your results and advice?
I had more success with these:

http://www.sharpsma.com/webfm_send/1489

... in high humidity environments.

User avatar
deshipu
Posts: 1380
Joined: Thu May 28, 2015 5:54 pm

Re: Module for Ultrasonic sensor (HC-SR04)

Post by deshipu » Sun Nov 13, 2016 8:34 pm

@Lysenko unfortunately those are analog sensors, and *require* 5V power, so it's non-trivial to connect them to an ESP8266.

I found a similar sensor that uses I2C for communication instead, and wrote a library for it: https://bitbucket.org/thesheep/micropython-gp2y0e03/src

greentree
Posts: 12
Joined: Wed Dec 16, 2015 3:16 am

Re: Module for Ultrasonic sensor (HC-SR04)

Post by greentree » Mon Nov 14, 2016 12:30 am

Thanks for these suggestions! I have an analog IR distance sensor -- I can work out the the power issues temporarily while I wait for one of the I2C sensors. I'll give it a try.

I'm still interested in the acoustic sensor, if it is workable. Using sound as a sensing mechanism has some intrinsic value in this application (in a teaching setting, where sound is a topic to be covered). Also, they're cheap enough to hand one out to every student!

Post Reply