CircuitGizmos

Electronic Products for Creative Minds

  • Home
  • Gizmo Store/Products
  • Documentation/Datasheets
  • Projects/Libraries
  • GizmoBlog
  • Services/Contact
    • Design
    • Contact Gizmo!
  • Your Gizmo Cart
    • Your Account
You are here: Home / GizmoBlog / MMBasic Language / Input and Output / Measuring Distance

Measuring Distance

Using a HC-SR04 ultrasonic sensor and the DISTANCE() function you can measure the distance to a target.

This device can be found on eBay for about $4 and it will measure the distance to a target from 3cm to 3m. It works by sending an ultrasonic sound pulse and measuring the time it takes for the echo to be returned.

In MMBasic you use the DISTANCE function:


d = DISTANCE(trig, echo)


Where trig is the I/O pin connected to the “trig” input of the sensor and echo is the pin connected “echo” output of the sensor. You can also use 3-pin devices and in that case only one pin number is specified.

The value returned is the distance in centimetres to the target or -1 if no target was detected. If you repeatedly call this function you must arrange for a delay of at least 60mS between
each call otherwise errors may occur (caused by an echo from the previous sound pulse).

The I/O pins are automatically configured by this function but note that they should be 5V capable as the HC-SR04 is a 5V device. You can use multiple sensors connected to different I/O pins or even sharing the one trigger pin if care is taken to prevent one sensor from interfering with another.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

A Ton of Documentation

Open all | Close all

Projects made by Gizmo, Friends, and Members

open all | close all

Recent GizmoBlog Musings

  • Altair 8800 using a ColorMax!
  • Re-energizing the ColorMax, Pt. 3

Visit us!

  • Facebook

Electronic Products for Creative Minds

CircuitGizmos is your source for electronic products that help you create your embedded projects. Here at CircuitGizmos.com you will find a friendly store filled with creative products and all of the documentation that you need to use these gizmos.

We create devices that we believe make electronics fun, but we also know that our products are used for professional designs. For decades we have designed products for commercial, military, and medical industries. Our gizmos here are great for engineers and hobbyists alike.

Copyright © 2008+ CircuitGizmos, L.L.C. All rights reserved

Image already added

Recently Viewed Products

Copyright © 2025 · Generate Pro Theme on Genesis Framework · WordPress · Log in