Cesare A. Perani
Published

Like a Bat with HC SR04

How to use HC SR04 to measure distance (with noise filter).

BeginnerProtip809
Like a Bat with HC SR04

Things used in this project

Story

Read more

Schematics

Connections with Raspberry PI

Code

pwb-DVC-HCSR04-01.pwk

Plain text
This App is in source/executable POWER-KI code and require:
- PowerBerry SUP on your IOT Board;
- POWER-KI on your desktop.
(See www.PowerBerry.tech for instruction).
No preview (download only).

VAR: HC-SR04

Plain text
This listing is provided for documentation. POWER-KI programs should be edited with Workbench.
=========================================================================
(VAR) HCSR04
--------------------------------------------------
eTime:   (elapsed time)
mTime:   (measured time)
distance:   (distance)
SV: 
NV: 
Lis: 
VT: 
md: 
--------------------------------------------------
========================================
(MTHD) Init
--------------------------------------------------
PinOut:   (Output pin)
PinInp:   (Echo pin)
refDat:   (Reference to the da)
gpio: 
trg: 
tmo: 
ntmo: 
step: 
--------------------------------------------------
..............................
gpio=HIO_GPIOnew;
trg=TRIG(£\HCSR04\TRIG,"trg_pin,trg_val,trg_edge,trg_tmrUs");

HIO_GPIOset(gpio,pinInp,0,trg);
..............................
(WHILE) while
 Loop
--------------------------------------------------
_COND_: 
--------------------------------------------------
..............................
_COND_= runFlg@\Main;
..............................
(DO) do
..............................
#if(~lis==0);lis=lis_new;#end;
ntmo=0;
md=0;

#while(runFlg@\Main);
mTime=£;

HIO_GPIOpulse(gpio,pinOut,1,10);

tmo=tmr+500;
#while(!mTime and runFlg@\Main and tmr<tmo);
sleep(5);
#end;


#if(tmr>=tmo);#skip;ntmo=ntmo+1;#end;

#while(1);

#if(mtime > 38000 or mTime<58*4);#break;#end;

#if(LIS_NUM(lis)<3);
LIS_ADD(lis,mTime);
#break;
#end;

LIS_SORT(lis,£ASC);
mTime=LIS_POS(lis,2);
lis_clr(LIS);

#if(abs(mTime-md) > md*.4);SV=0;NV=0;#end;

#if(NV>=5); SV=SV-md;NV=NV-1;#end;
SV=SV+mTime;
NV=NV+1;
md=SV/NV;

distance=FLT(md/58,0);

#break;
#end;

sleep(20);
#end;
..............................
..............................
HIO_GPIOset(gpio,pinInp,0,£);
trash(gpio);
trash(trg);
..............................
========================================
(MTHD) TRIG
--------------------------------------------------
trg_pin: 
trg_val: 
trg_edge: 
trg_tmrUs: 
--------------------------------------------------
..............................
#if(trg_edge);
eTime=trg_tmrUs;
#else;
#while(1);
#if(~eTime);
mTime=trg_tmrUs-etime;
eTime=£;
#break;
#end;
yield;
#end;
#end;
..............................
========================================

Credits

Cesare A. Perani

Cesare A. Perani

10 projects • 14 followers
Software Architect

Comments