Special

Introducing the “Welcome to Xojo” Bundle!

New to Xojo and looking for guidance? We've put together a terrific bundle to welcome you! Xojo Bundle

This bundle includes six back issues of the magazine -- all of year 23 in printed book and digital formats -- plus a one-year subscription (beginning with 24.1) so you'll be learning all about Xojo for the next year. It's the perfect way to get started programming with Xojo. And you save as much as $35 over the non-bundle price!

This offer is only available for a limited time as supplies are short, so hurry today and order this special bundle before the offer goes away!

Article Preview


Buy Now

Issue 24.4 ('Encryption')
Instant purchase and download via GumRoad!

FEATURE

Pre-Emptive Ultrasonic Range Sensor

Sensing Distance with Raspberry Pi, Xojo, and lgpio

Issue: 24.4 (July/August 2026)
Author: Eugene Dakin
Author Bio: Eugene works as a Senior Oilfield Technical Specialist. He has university degrees in the disciplines of Engineering, Chemistry, Biology, Business, and a Ph.D. in Chemical Engineering. He is the author of dozens of books on Xojo available on the xdevlibrary.com website.
Article Description: No description available.
Article Length (in bytes): 17,638
Starting Page Number: 13
Article Number: 24403
Resource File(s):

Download Icon project 24403.zip Updated: 2026-07-01 15:25:39

Related Link(s): None

Excerpt of article text...

Ultrasonic range sensors like the HC-SR04 are inexpensive, widely available, and extremely useful for Raspberry Pi projects. Whether you're measuring tank levels, detecting vehicles, or experimenting with robotics, this sensor is often the first step into real-world distance sensing.

But if you've ever tried to use Xojo's built-in GPIO triggers, callbacks, or event-driven timing, you may have noticed something: they're not always reliable. Timing jitter, missed edges, and thread contention can all introduce errors—especially when measuring microsecond-scale pulses.

For this article, we'll bypass the usual trigger-based approach entirely. Instead, we use a pre-emptive loop inside a Xojo Thread, combined with the excellent lgpio C library, to create a stable, consistent ultrasonic pulse measurement system.

This approach avoids interrupts and relies on tight polling with nanosecond timestamps, giving us a surprisingly accurate measurement routine written in pure Xojo using Declares created with Eugene's lgpio wrapper (freely available at https://github.com/eugenedakin/lgpio-GPIO).

Why Pre-Emptive Looping Instead of Triggers?

The HC-SR04 works like this:

...End of Excerpt. Please purchase the magazine to read the full article.