Sensor HC-SR04 - Range Sensor with Electric IMP

Hello everyone,

Does anyboby could help me to connect an Range Sensor (HC-SR04 - Datasheet: ) to the Electric IMP and send the distance information to Pachube/Cosm ?



That sensor requires accurate timing to basically ‘count’ the distance. While an imp might be able to do it (sending the pulse, then sleeping 10uS every time and count how many sleeps it took before you get the reply), it wont be very accurate.

If you want more accuracy, you could use a Arduino for example to do the high-resolution counting, then sending its value over a uart to the imp.


The imp hardware is capable of accurate timing, we’ve just not implemented an API for this yet. It’ll come, but no date on that one.

Any update on an api for timing pulses?

release-23 has gapless SPI (finally) so you could do a spi readblob and see when the pin changes state, then count the number of clocks it took… that should work?

I also got this ‘HC-SR04’ module to test a new idea.
Documentation for the module states that you should send a pulse to the module and then wait for a pulse to return. The width of this pulse is in direct proportion to the distance is senses.

Hugo, or anyone else, could you elaborate on the idea of using the spi.readblob? How would this practically work?


I used the same idea as Hugo had but with serial Port12:
After sending the trigger puls i send with high baudrate charakters out; The amount of characters depends on how long your distances-max are you want to measure. I only need up to 15cm. then you make a external AND-Funktion with logik or diodes: Input 1 of AND-Gate is TX, Input 2 is Echo Puls of HCSR04, Output AND goes to RX. That means you receive Characters only during Echo Puls is High.

function US_scann()
local i=0;
local result=0;

result =;
if(result == -1)break;
server.log("Char-anz: "+(i));

Heh! Interesting! You can minimize the lookups the interpreter is doing by assigning variables to your pins/peripherals, eg:

local p7 = hardware.pin7;
for(local a=0;a<100;a++) p7.write(0);

…is faster than…

for(local a=0;a<100;a++) hardware.pin7.write(0);

You can go even quicker with bindenv, see devwiki.