- 01100 ms schedule
- 0210 µs trigger
- 0325 ms maximum wait
- 04Update outputs
Open the sketch directory
In Arduino IDE open beacon/beacon.ino. Keep beacon.hpp in the same sketch directory. Select the UNO R4 WiFi target and the verified USB port, then compile and upload.
The complete sketch was compiled and linked with Arduino UNO R4 Boards 1.6.0 and Arduino CLI 1.5.1 on 8 November 2026. It needs no extra Arduino libraries. The download's README contains the exact CLI commands. A successful build establishes that the adapter uses the target's SDK correctly; complete the wiring and device checks below to validate the physical instrument.
#include "beacon.hpp"
constexpr int trigger_pin = 7, echo_pin = 8;
constexpr int red_pin = 4, yellow_pin = 5, green_pin = 6;
Zone zone = Zone::unknown;
std::uint32_t last_sample = 0;
void setup() {
Serial.begin(115200);
pinMode(trigger_pin, OUTPUT);
digitalWrite(trigger_pin, LOW);
pinMode(echo_pin, INPUT);
pinMode(red_pin, OUTPUT);
pinMode(yellow_pin, OUTPUT);
pinMode(green_pin, OUTPUT);
}
void loop() {
const auto now = static_cast<std::uint32_t>(millis());
if (!due(now, last_sample, 100)) return;
last_sample = now;
digitalWrite(trigger_pin, LOW);
delayMicroseconds(2);
digitalWrite(trigger_pin, HIGH);
delayMicroseconds(10);
digitalWrite(trigger_pin, LOW);
const auto duration = static_cast<std::uint32_t>(pulseIn(echo_pin, HIGH, 25000UL));
const auto mm = distance_mm(duration);
zone = zone_for(mm, zone);
digitalWrite(red_pin, zone == Zone::close);
digitalWrite(yellow_pin, zone == Zone::caution);
digitalWrite(green_pin, zone == Zone::clear);
Serial.print("distance_mm=");
Serial.print(mm);
Serial.print(" zone=");
Serial.println(zone == Zone::unknown ? "unknown" : zone == Zone::close ? "close" : zone == Zone::caution ? "caution" : "clear");
}pulseIn blocks while waiting for an echo, but the explicit 25,000 microsecond timeout bounds that wait. This is a cooperative loop with a bounded blocking sensor call, not a fully nonblocking acquisition driver. The small trigger delays establish the pulse; they are not the 100 ms scheduling mechanism.
The loop records the sample start time and updates LEDs from a single returned zone. Serial output names both the millimetre value and the zone, so an all-off display can be diagnosed as unknown.
Observe the complete path
Open the serial monitor at 115200 baud. Move a broad flat object slowly through the configured bands. Verify the text agrees with the LED. If duration repeatedly becomes zero, investigate power, common ground, module wiring and target shape before changing the C++ policy.
Try it
Disconnect power, remove ECHO, reconnect power and verify that the loop still reports missing readings. Restore the connection with power disconnected. A finite timeout is useful only if the rest of the program can recover afterward.