Skip to content

Instantly share code, notes, and snippets.

@jcreager
Created June 27, 2020 23:34
Show Gist options
  • Save jcreager/709cf599ed8d3942d2ac10ca20219bd5 to your computer and use it in GitHub Desktop.
Save jcreager/709cf599ed8d3942d2ac10ca20219bd5 to your computer and use it in GitHub Desktop.
FlashForth code to control the hc-sr04 ultrasonic distance sensor
\ Example code for using the hc-sr04 ultrasonic distance sensor
\ to measure distance in cm.
\ Requires math.txt and us.txt from flashforth repo
-hc-sr04
marker -hc-sr04
\ ports and registers
$0008 constant trig \ pin 11
$0010 constant echo \ pin 12
$0023 constant pinb
$0024 constant ddrb
$0025 constant portb
343 constant sound-speed \ speed of sound 0.0343 meters/ms
3960 constant max-range \ max range of sensor
sound-speed 10 / 2/ constant min-range \ min range of sensor
: init-hc-sr04 ( -- )
trig ddrb mset \ set pin as output
echo ddrb mclr \ set pin as input
;
\ toggle trigger pin
: trigger! ( -- ) portb c@ trig xor portb c! ;
\ check if echo pin is high or low
: echo? ( -- f ) pinb c@ echo and 0= if false else true then ;
\ 8 cycle pulse
: pulse! ( -- ) trigger! #10 us trigger! ;
\ Times how long it takes from echo to go from high to low in ms
\ First loop waits for echo pin to go to high and places ticks on r stack
\ Second loop waits for echo pin to go to low
: pulse-ms ( -- u )
begin echo? dup if ticks >r then until
begin echo? 0= until
ticks r> -
;
\ capture distance
\ calculate distance supplying time in ms and speed of sound
: dist? ( -- u ) pulse! pulse-ms sound-speed 2 */ ;
\ measure speed
: speed ( -- u ) dist? #1000 ms dist? swap - ;
\ format distance
: fmt-dist ( u -- caddr u ) 0 <# # [char] . hold #s rot sign #> ;
\ show distance formatted as centimeters
: show-dist ( u -- )
dist?
dup max-range > if ." too far " drop exit then
dup min-range < if ." too close " drop exit then
fmt-dist type ." cm"
;
init-hc-sr04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment