# Tactiverge Academy — companion code for "The sense–think–act loop in time"
# Lesson: https://tactiverge.win/academy/robotics-foundations/introduction-to-robotics/sense-think-act/
# Licence: MIT (see https://tactiverge.win/open-engineering/). Examples appear in lesson order.

# ── Example 1 ────────────────────────────────────────
# A robot drives at 0.8 m/s (0.8 mm per ms) towards a wall 1200 mm away.
# It commands "stop" as soon as a reading shows 300 mm or less.
# Whole millimetres and milliseconds keep the arithmetic exact.

def stopping_gap(loop_ms, latency_ms):
    t = 0
    while True:
        measured_at = max(t - latency_ms, 0)       # the reading is this old
        reading = 1200 - 8 * measured_at // 10      # distance it reports, mm
        if reading <= 300:
            return 1200 - 8 * t // 10               # true gap when it stops
        t += loop_ms                                # wait for the next loop

for loop_ms, latency_ms in [(10, 0), (100, 0), (100, 80), (200, 80)]:
    gap = stopping_gap(loop_ms, latency_ms)
    print(f"loop {loop_ms:3d} ms, latency {latency_ms:2d} ms: stops {gap:3d} mm from the wall")
