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.
kevinkk525
Posts: 969
Joined: Sat Feb 03, 2018 7:02 pm

Re: Module for Ultrasonic sensor (HC-SR04)

Post by kevinkk525 » Wed Jun 05, 2019 8:04 am

As the comment in the code says it outputs meters.

You can use my library for comparison (you have to remove project specific imports and base class first though): https://github.com/kevinkk525/pysmartno ... /hcsr04.py
Kevin Köck
Micropython Smarthome Firmware (with Home-Assistant integration): https://github.com/kevinkk525/pysmartnode

RajaRamesh
Posts: 51
Joined: Wed May 08, 2019 10:54 am

Re: Module for Ultrasonic sensor (HC-SR04)

Post by RajaRamesh » Wed Jun 05, 2019 4:23 pm

kevinkk525 wrote:
Wed Jun 05, 2019 8:04 am
As the comment in the code says it outputs meters.

You can use my library for comparison (you have to remove project specific imports and base class first though): https://github.com/kevinkk525/pysmartno ... /hcsr04.py
Thank you for sharing the details Kevin. According to my knowledge i updated the code to read distance(removed mqtt, temperature code) and i am confused with below code. can you help me in modifying below code to read distance without temperature.

Code: Select all

def _read(self):
        """
        Returns distance in cm.
        Optionally compensated by temperature in °C.
        :return: float
        """
        val = []
        warnings = 0  # probably not going to happen that both warning types occur at the same time
        warning = "minimum distance reached or different problem"
        for _ in range(20):
            try:
                pt = self._pulse()
                if pt > 175:  # ~3cm, sensor minimum distance, often read although other problems
                    val.append(pt)
                else:
                    warnings += 1
            except OSError as e:
                warning = e
                warnings += 1
            time.sleep_ms(10)
        pt = 0
        for i in range(len(val)):
            pt += val[i]
        pt /= len(val)
        if temp is None:
            dt = (pt / 2) / 29.14
        else:
            dt = (pt / 2) * ((331.5 + (0.6 * temp)) / 10000)
        if dt < 0:
            await _log.asyncLog("warn", "Sensor reading <0")
            return None
        try:
            dt = round(dt, self._pr)
            dt += self._off
        except Exception as e:
            await _log.asyncLog("error", "Error rounding value {!s}".format(dt))
            return dt

kevinkk525
Posts: 969
Joined: Sat Feb 03, 2018 7:02 pm

Re: Module for Ultrasonic sensor (HC-SR04)

Post by kevinkk525 » Wed Jun 05, 2019 4:44 pm

Remove all the log instructions and add an optional parameter temp to the function like in my code. (temp=None)

It only corrects with a temperature if it gets one.
I'm currently not at home and only with my phone so can't give you a stripped down version.
Kevin Köck
Micropython Smarthome Firmware (with Home-Assistant integration): https://github.com/kevinkk525/pysmartnode

kevinkk525
Posts: 969
Joined: Sat Feb 03, 2018 7:02 pm

Re: Module for Ultrasonic sensor (HC-SR04)

Post by kevinkk525 » Wed Jun 05, 2019 4:49 pm

Code: Select all

async def _read(self) -> float:
        """
        Returns distance in cm.
        Optionally compensated by temperature in °C.
        :return: float
        """
        val = []
        warnings = 0  # probably not going to happen that both warning types occur at the same time
        warning = "minimum distance reached or different problem"
        for _ in range(20):
            try:
                pt = self._pulse()
                if pt > 175:  # ~3cm, sensor minimum distance, often read although other problems
                    val.append(pt)
                else:
                    warnings += 1
            except OSError as e:
                warning = e
                warnings += 1
            await asyncio.sleep_ms(10)
        if warnings > 10:  # half sensor readings are bad
            print("error", "Too many bad sensor readings, error: {!s}".format(warning))
            return None
        # removing extreme values
        val.remove(max(val))
        val.remove(max(val))
        val.remove(min(val))
        val.remove(min(val))
        pt = 0
        for i in range(len(val)):
            pt += val[i]
        pt /= len(val)
        if temp is None:
            dt = (pt / 2) / 29.14
        if dt < 0:
            print("warn", "Sensor reading <0")
            return None
        try:
            dt = round(dt, self._pr)
            dt += self._off
        except Exception as e:
            print("error", "Error rounding value {!s}".format(dt))
            return dt
        return dt

Kevin Köck
Micropython Smarthome Firmware (with Home-Assistant integration): https://github.com/kevinkk525/pysmartnode

RajaRamesh
Posts: 51
Joined: Wed May 08, 2019 10:54 am

Re: Module for Ultrasonic sensor (HC-SR04)

Post by RajaRamesh » Fri Jun 07, 2019 6:04 am

kevinkk525 wrote:
Wed Jun 05, 2019 4:49 pm

Code: Select all

async def _read(self) -> float:
        """
        Returns distance in cm.
        Optionally compensated by temperature in °C.
        :return: float
        """
        try:
            dt = round(dt, self._pr)
            dt += self._off
        except Exception as e:
            print("error", "Error rounding value {!s}".format(dt))
            return dt
        return dt
Thank you Kevin. i will check and get back to you.

RajaRamesh
Posts: 51
Joined: Wed May 08, 2019 10:54 am

Re: Module for Ultrasonic sensor (HC-SR04)

Post by RajaRamesh » Sat Jun 08, 2019 2:23 pm

RajaRamesh wrote:
Fri Jun 07, 2019 6:04 am
kevinkk525 wrote:
Wed Jun 05, 2019 4:49 pm
Thank you Kevin. i will check and get back to you.
Hi Kevin, Now i can see the distance in cm. But, first it is display's error in rounding value. why is it happening?
try:
dt = round(dt, self._pr)
dt += self._off
except Exception as e:
print("error", "Error rounding value {!s}".format(dt))
return dt
Distance in cm.jpg
Distance in cm.jpg (28.29 KiB) Viewed 5391 times

kevinkk525
Posts: 969
Joined: Sat Feb 03, 2018 7:02 pm

Re: Module for Ultrasonic sensor (HC-SR04)

Post by kevinkk525 » Sat Jun 08, 2019 2:27 pm

I guess self._pr isn't defined. you can replace it with 2
self._offs should be 0
Kevin Köck
Micropython Smarthome Firmware (with Home-Assistant integration): https://github.com/kevinkk525/pysmartnode

RajaRamesh
Posts: 51
Joined: Wed May 08, 2019 10:54 am

Re: Module for Ultrasonic sensor (HC-SR04)

Post by RajaRamesh » Sat Jun 08, 2019 2:52 pm

kevinkk525 wrote:
Sat Jun 08, 2019 2:27 pm
I guess self._pr isn't defined. you can replace it with 2
self._offs should be 0
Thank you Kevin for your help.

Post Reply