BDP_TOUCH: one quick continuous press instead of small steps

Stepping down 0.005 mm at a time found no touch even 0.25 mm into the bed
(peak 16): the sensor sets a new baseline by itself while the force looks
steady, and the slow ramp looked steady. A quick press gave about 25 per
0.1 mm. BDP_TOUCH now lowers the nozzle in one drip-mode move (SPEED,
default 0.3 mm/s) while a timer reads the force every few ms and stops the
move at STOP; Z per reading comes from stepper_z's past position, the halt
position is recovered like homing.py does. The threshold needs 3 readings
in a row, and the curve is logged also when no touch was found.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
mangavalkandClaude Opus 5.5 committed 2026-11-02 17:24:12 +01:00
1 parent b16961dba3
commit 7761e8f803
3 files changed
+120 -51

No files matched your search

+116 -47
View File
@@ -1,12 +1,18 @@
# Nozzle touch with bd_pressure, and a comparison with Beacon contact.
#
# The bd_pressure endstop output is not wired, so it cannot stop a homing
# move. BDP_TOUCH instead lowers the nozzle in small steps and reads the
# force (chk_delta, register 64-65 of the load-check firmware) after each
# step, until the force reaches STOP or Z reaches the floor. From the
# curve it reports two touch heights:
# threshold z: where the force first reaches THRESHOLD (interpolated
# between the two steps around it), like an endstop would
# move. BDP_TOUCH instead lowers the nozzle in one slow continuous move
# (drip mode, like a homing move) while a timer reads the force (chk_delta,
# register 64-65 of the load-check firmware) as fast as I2C allows, and
# stops the move when the force reaches STOP. The Z of each reading comes
# from stepper_z's position at that time. It has to be one quick press:
# the sensor sets a new baseline by itself while the force looks steady,
# so stepping down slowly (tried: 0.005 mm steps, 0.25 mm in 33 s) kept
# the reading near zero. A quick press measured 2026-11-02 at 150C: about
# 25 per 0.1 mm (0.1 mm 27, 0.2 mm 52, 0.3 mm 73, 0.4 mm 92).
# From the curve it reports two touch heights:
# threshold z: where the force first reaches THRESHOLD (3 readings in
# a row, interpolated), like an endstop would
# fit z: where a straight line through the readings at or above
# THRESHOLD reaches the no-contact level (the mean of the
# readings before the descent): the zero-force touch point
@@ -18,10 +24,11 @@
# the TOUCH_COMPARE macro (macros/sensors/touch_compare.cfg), which heats
# the nozzle and homes first.
#
# Safety: the force only goes to STOP (default 80; a light finger push on
# the nozzle is about 41, a purge 64-246), the descent ends at FLOOR below
# the start, and the nozzle always goes back up to the start height, also
# after an error. It refuses to run while the bdp_guard is armed (in stop
# Safety: the move stops when the force reaches STOP (default 80, about
# 0.3 mm into the bed; a purge peaks at 64-246) and overshoots by what was
# already queued (at most ~0.15 s of the move, ~0.05 mm at 0.3 mm/s). The
# descent ends at FLOOR below the start, and the nozzle always goes back up
# to the start height, also after an error. It refuses to run while the bdp_guard is armed (in stop
# mode the touch would shut Klipper down) or while the sensor is in PA mode.
#
# Install: copy to ~/klipper/klippy/extras/bdp_touch.py (install.sh links
@@ -31,15 +38,14 @@
# sensor: bd_pa # name after "bdpressure" in [bdpressure bd_pa]
#
# Commands:
# BDP_TOUCH [THRESHOLD=15] [STOP=80] [STEP=0.005] [FLOOR=0.4] [SETTLE=0.05]
# [READS=3]
# touch at the current X/Y, starting at the current Z
# _TOUCH_COMPARE [N=10] [START=0.1] [THRESHOLD=..] [STOP=..] [STEP=..]
# BDP_TOUCH [THRESHOLD=15] [STOP=80] [SPEED=0.3] [FLOOR=0.5]
# touch at the current X/Y, starting at the current Z (SPEED in mm/s)
# _TOUCH_COMPARE [N=10] [START=0.1] [THRESHOLD=..] [STOP=..] [SPEED=..]
# the comparison loop; START is the BDP_TOUCH start height above the
# Beacon contact result of the same pair
#
# Every touch writes its whole curve to klippy.log ("bdp_touch: curve"),
# so it can be analysed later.
# also when it found no touch, so it can be analysed later.
#
# Status (printer.bdp_touch): threshold_z, fit_z, peak, noise, slope
# (force per 0.01 mm), points, of the last BDP_TOUCH
@@ -53,7 +59,6 @@ MODE_PA = 7
REG_EXT = 54 # extension marker 0xBD + version
REG_DELTA = 64 # chk_delta, int16 little-endian
EXT_MAGIC = 0xBD
STEP_SPEED = 2. # mm/s for the small Z steps
LIFT_SPEED = 5.
@@ -128,11 +133,13 @@ class BDPTouch:
self.toolhead.manual_move([None, None, z], speed)
self.toolhead.wait_moves()
def touch(self, gcmd, threshold, stop, step, floor, settle, reads):
def touch(self, gcmd, threshold, stop, speed, floor):
"""Lower the nozzle from the current Z; returns the result dict."""
self._check_ready(gcmd)
self.toolhead.wait_moves()
start = self.toolhead.get_position()[2]
toolhead = self.toolhead
toolhead.wait_moves()
startpos = toolhead.get_position()
start = startpos[2]
# New zero with the nozzle free, then the no-contact level and noise
self.i2c.i2c_write([REG_RESET_PROBE, 1])
self.reactor.pause(self.reactor.monotonic() + 0.3)
@@ -141,37 +148,101 @@ class BDPTouch:
base.append(self._read_delta(1))
self.reactor.pause(self.reactor.monotonic() + 0.01)
base_mean, noise, _ = _stats(base)
curve = []
# One continuous move down to the floor in drip mode (like a homing
# move), stopped early from a timer as soon as the force reaches
# STOP. Stepping with pauses does not work: the sensor sets a new
# baseline by itself while the force looks steady, so a slow press
# (seen: 0.25 mm in 33 s) stays near zero.
toolhead.flush_step_generation()
kin = toolhead.get_kinematics()
steppers = kin.get_steppers()
kin_spos = {s.get_name(): s.get_commanded_position() for s in steppers}
start_mcu = {s.get_name(): s.get_mcu_position() for s in steppers}
zstep = [s for s in steppers if s.get_name() == 'stepper_z'][0]
done = self.reactor.completion()
samples = [] # (print_time, delta)
state = {'errors': 0}
def poll(eventtime):
# Never raise here: an exception in a timer shuts Klipper down
if done.test():
return self.reactor.NEVER
try:
t0 = self.reactor.monotonic()
data = bytearray(
self.i2c.i2c_read([REG_DELTA], 2)['response'])
t1 = self.reactor.monotonic()
if len(data) == 2:
d = data[0] | (data[1] << 8)
d = d - 0x10000 if d & 0x8000 else d
pt = toolhead.mcu.estimated_print_time((t0 + t1) / 2.)
samples.append((pt, d))
if abs(d - base_mean) >= stop:
done.complete(True)
return self.reactor.NEVER
else:
state['errors'] += 1
except Exception:
state['errors'] += 1
if state['errors'] == 1:
logging.exception("bdp_touch: read failed")
if state['errors'] > 20:
done.complete(False) # stop the move: no sensor
return self.reactor.NEVER
return eventtime + 0.002
timer = self.reactor.register_timer(poll, self.reactor.NOW)
error = None
try:
z = start
while True:
z = round(z - step, 6)
if z < start - floor:
raise gcmd.error(
"BDP_TOUCH: no touch within %.3f mm (peak %.0f)"
% (floor, max([abs(d) for zz, d in curve] or [0])))
self._move_z(z, STEP_SPEED)
self.reactor.pause(self.reactor.monotonic() + settle)
d = self._read_delta(reads)
curve.append((z, d))
if abs(d - base_mean) >= stop:
break
movepos = list(startpos)
movepos[2] = start - floor
toolhead.drip_move(movepos, speed, done)
except self.printer.command_error as e:
error = str(e)
finally:
touched = done.test() and done.wait() is True
if not done.test():
done.complete(None)
self.reactor.unregister_timer(timer)
# Where the steppers stopped (as homing.py does after a drip
# move), then back up to the start height
toolhead.flush_step_generation()
halt = dict(kin_spos)
for s in steppers:
name = s.get_name()
halt[name] += ((s.get_mcu_position() - start_mcu[name])
* s.get_step_dist())
haltpos = list(kin.calc_position(halt))[:3] + startpos[3:]
toolhead.set_position(haltpos)
self._move_z(start, LIFT_SPEED)
logging.info("bdp_touch: curve start=%.4f base=%.2f noise=%.2f %s",
start, base_mean, noise,
" ".join("%.4f:%.1f" % p for p in curve))
if error is not None:
raise gcmd.error("BDP_TOUCH: %s" % error)
# Z at each reading, from stepper_z's position at that time
z0 = zstep.mcu_to_commanded_position(start_mcu['stepper_z'])
curve = [(round(start + zstep.mcu_to_commanded_position(
zstep.get_past_mcu_position(pt)) - z0, 5), d)
for pt, d in samples]
logging.info("bdp_touch: curve start=%.4f base=%.2f noise=%.2f "
"touched=%s lowest=%.4f errors=%d %s", start, base_mean,
noise, touched, haltpos[2], state['errors'],
" ".join("%.4f:%d" % p for p in curve))
if state['errors'] > 20:
raise gcmd.error("BDP_TOUCH: bd_pressure stopped answering")
if not touched:
raise gcmd.error(
"BDP_TOUCH: no touch within %.3f mm (peak %.0f)"
% (floor, max([abs(d - base_mean) for zz, d in curve] or [0])))
# The sign of the force depends on the gauge: take it from the end
sign = 1. if curve[-1][1] - base_mean >= 0 else -1.
force = [(zz, sign * (d - base_mean)) for zz, d in curve]
# Threshold: the first of 3 readings in a row at or above it
# (one noisy reading does not count), interpolated
thr_z = None
prev = (start, 0.)
for zz, f in force:
if f >= threshold:
pz, pf = prev
thr_z = pz + (zz - pz) * (threshold - pf) / (f - pf)
for i in range(1, len(force) - 2):
if all(f >= threshold for zz, f in force[i:i + 3]):
(pz, pf), (zz, f) = force[i - 1], force[i]
thr_z = zz if f == pf else (
pz + (zz - pz) * (threshold - pf) / (f - pf))
break
prev = (zz, f)
fit_z = slope = None
pts = [(zz, f) for zz, f in force if f >= threshold]
if len(pts) >= 3:
@@ -193,10 +264,8 @@ class BDPTouch:
return dict(
threshold=gcmd.get_float('THRESHOLD', 15., above=0.),
stop=gcmd.get_float('STOP', 80., above=0., maxval=150.),
step=gcmd.get_float('STEP', 0.005, minval=0.001, maxval=0.02),
floor=gcmd.get_float('FLOOR', 0.4, above=0., maxval=1.),
settle=gcmd.get_float('SETTLE', 0.05, minval=0., maxval=1.),
reads=gcmd.get_int('READS', 3, minval=1, maxval=10))
speed=gcmd.get_float('SPEED', 0.3, minval=0.05, maxval=1.),
floor=gcmd.get_float('FLOOR', 0.5, above=0., maxval=1.))
def _fmt(self, v):
return "-" if v is None else "%.4f" % v
@@ -210,7 +279,7 @@ class BDPTouch:
"BDP_TOUCH: threshold z %s, fit z %s, peak %.0f, noise %.1f, "
"%s per 0.01 mm, %d points"
% (self._fmt(r['threshold_z']), self._fmt(r['fit_z']), r['peak'],
r['noise'], "-" if r['slope'] is None else "%.0f" % r['slope'],
r['noise'], "-" if r["slope"] is None else "%.1f" % r["slope"],
r['points']))
def cmd_TOUCH_COMPARE(self, gcmd):