Library for HC-SR04 and SRF04 ultrasonic sensors

Showroom for MicroPython related hardware projects.
Target audience: Users wanting to show off their project!
Post Reply
Posts: 18
Joined: Mon Mar 10, 2014 2:57 pm

Library for HC-SR04 and SRF04 ultrasonic sensors

Post by SkG » Fri Jul 04, 2014 7:18 am

Hi all!

Now I've received my ultrasonic sensors (the previous one died, so I orderer two new) I tested my lib for it :)

So here it is if anyone is interested on it: ...

At the moment it only allows one sensor but I plan to make an object that could be initialized with the two pins for each sensor (till 15th July I'm kinda busy).

Posts: 7
Joined: Fri Aug 15, 2014 12:22 pm
Location: Singapore

Re: Library for HC-SR04 and SRF04 ultrasonic sensors

Post by mithru » Wed Aug 20, 2014 11:19 am

Hi Sergio,

I've updated your code to allow more than one sensor. I've made a pull request to your github project page.
I've tested this with two HR-SR04 sensors (added that as example code in the pull request). Do have a look and let me know if something's not working.

My fork of your project is available here:

If you think the update is fine, please do accept the pull request.

EDIT: For the benefit of anyone else reading this looking for the updated library, Sergio has merged the update. The library now features the following:

- multiple sensors accepted
- returns values in cm / inches

Final working library available here (with an example):

User avatar
Posts: 34
Joined: Sun Oct 26, 2014 4:07 am
Location: New Market, Maryland

Re: Library for HC-SR04 and SRF04 ultrasonic sensors

Post by gcarver » Sun Oct 26, 2014 4:27 am

I got my HC-SR04 working thank you very much. However I did have to make a change. I found that if there was nothing withing about 15 inches of the sensor I would end up in an endless loop waiting for the echo value to go to 0. I added a loop limit of 1000 iterations and that fixed the deadlock.

Also of note. I was using x1 and x2 for echo/trig but that would cause pyb.delay() to lockup. I switched to x7 and x8 and that fixed the problem.
End of line...

Post Reply