Article Preview
Buy Now
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):
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.










