Skip to content
Blog home

projects · By CYOBot · Published · Updated

Test a distance decision in Python before moving a robot

Use a small logic-only Python example to test a threshold, boundary values and missing measurements before adapting a robot sensor example.

CYOBot distance sensor demonstration

A sensor project has at least two separate questions: what did the sensor measure, and what should the program do with that measurement? Start with the second question. You can test a decision using ordinary Python without powering a motor or assuming that a sensor is connected.

The example below returns a stop decision when a distance is at or below a chosen threshold. It also returns a stop decision when no reading is available. The 20-centimetre default is an illustrative input for a software exercise, not a validated safe stopping distance. Real stopping requirements depend on the robot, speed, surface, sensor and control system.

Run this function in Python 3 on a computer. Call it with None, 10, 20 and 21. The expected outputs are True, True, True and False. Testing 20 and 21 checks the boundary, while None makes the unavailable-measurement behaviour explicit. These cases are checked against this exact example in the repository's automated tests. No physical robot or sensor validation is claimed.

Once the logic is understood, find the supported sensor example for your exact model and firmware. Identify how it reports missing or invalid readings before adapting the decision. A numeric value is not automatically a trustworthy measurement: units, stale data and out-of-range readings also matter. Keep the robot stationary and follow the model's documented test instructions while inspecting samples.

Write down the model revision, code version, test inputs and observations. Keep the known working example. Only add physical behaviour after the hardware-specific reading and recovery procedure are understood and supervised appropriately. The decision function alone is not an autonomous navigation controller.

Logic-only Python example

def should_stop(distance_cm, threshold_cm=20):
    if distance_cm is None:
        return True
    return distance_cm <= threshold_cm

Try it step by step

  1. Run the logic example on a computer with Python 3.
  2. Check missing, below-threshold, exact-threshold and above-threshold inputs.
  3. Compare the sensor's actual output format with the assumptions in the function.
  4. Record software tests separately from physical observations.

Related guides and sources