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

+1 -1
View File
@@ -59,7 +59,7 @@ everything below, grouped by topic. Comment out what you do not use there.
| `bdwidth_status.py` | exposes bdwidth's motion counter and width to macros (`present: False` with neutral values when no bdwidth is configured, so the macros also work without it), and keeps a USB dropout of bdwidth (port: usb) from shutting down Klipper: the read is retried every 10 s and the port reopened | | `bdwidth_status.py` | exposes bdwidth's motion counter and width to macros (`present: False` with neutral values when no bdwidth is configured, so the macros also work without it), and keeps a USB dropout of bdwidth (port: usb) from shutting down Klipper: the read is retried every 10 s and the port reopened |
| `bdpressure_check.py` | bd_pressure load check (`BDP_CHECK_START/STOP/QUERY`). Needs the load-check firmware from the bd_pressure `load-check-extension` branch; on stock firmware it reports "not available" and does nothing. Also reports how many readings the last `PA_CALIBRATE` got (`pa_points`, `pa_distinct`), used to reject runs with a silent or stuck sensor. | | `bdpressure_check.py` | bd_pressure load check (`BDP_CHECK_START/STOP/QUERY`). Needs the load-check firmware from the bd_pressure `load-check-extension` branch; on stock firmware it reports "not available" and does nothing. Also reports how many readings the last `PA_CALIBRATE` got (`pa_points`, `pa_distinct`), used to reject runs with a silent or stuck sensor. |
| `bdp_guard.py` | nozzle collision guard: while armed (`BDP_GUARD_ARM/DISARM/QUERY`) reads the bd_pressure force every 20 ms over I2C and, in stop mode, shuts Klipper down when it stays above the threshold. Reports reads, peak and errors per phase in the console and klippy.log. When it arms and finds the sensor still in PA mode (an emergency stop during `PA_CALIBRATE`; `FIRMWARE_RESTART` does not reset the sensor), it switches it to probe mode and takes a new zero first. Puts a lock on the sensor's I2C connection that `bdpressure.py` and `bdpressure_check.py` also go through (Klipper allows one I2C request at a time per device). Needs the load-check firmware. | | `bdp_guard.py` | nozzle collision guard: while armed (`BDP_GUARD_ARM/DISARM/QUERY`) reads the bd_pressure force every 20 ms over I2C and, in stop mode, shuts Klipper down when it stays above the threshold. Reports reads, peak and errors per phase in the console and klippy.log. When it arms and finds the sensor still in PA mode (an emergency stop during `PA_CALIBRATE`; `FIRMWARE_RESTART` does not reset the sensor), it switches it to probe mode and takes a new zero first. Puts a lock on the sensor's I2C connection that `bdpressure.py` and `bdpressure_check.py` also go through (Klipper allows one I2C request at a time per device). Needs the load-check firmware. |
| `bdp_touch.py` | `BDP_TOUCH`: lowers the nozzle in 0.005 mm steps and reads the bd_pressure force after each step (its endstop output is not wired), up to a force limit (default 80) or 0.4 mm below the start, then lifts back; reports the height where the force reaches the threshold and the zero-force height from a line fit, and logs the whole curve to klippy.log. `_TOUCH_COMPARE`: alternates that with Beacon's contact probe. Refuses while the bdp_guard is armed or the sensor is in PA mode. Needs the load-check firmware. | | `bdp_touch.py` | `BDP_TOUCH`: lowers the nozzle in one slow continuous move (drip mode, like a homing move) while reading the bd_pressure force as fast as I2C allows (its endstop output is not wired), stops at a force limit (default 80) or 0.5 mm below the start, then lifts back; it must be one quick press, because the sensor re-zeros itself while the force looks steady; reports the height where the force reaches the threshold and the zero-force height from a line fit, and logs the whole curve to klippy.log. `_TOUCH_COMPARE`: alternates that with Beacon's contact probe. Refuses while the bdp_guard is armed or the sensor is in PA mode. Needs the load-check firmware. |
### Scripts (`scripts/`) ### Scripts (`scripts/`)
+116 -47
View File
@@ -1,12 +1,18 @@
# Nozzle touch with bd_pressure, and a comparison with Beacon contact. # 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 # 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 # move. BDP_TOUCH instead lowers the nozzle in one slow continuous move
# force (chk_delta, register 64-65 of the load-check firmware) after each # (drip mode, like a homing move) while a timer reads the force (chk_delta,
# step, until the force reaches STOP or Z reaches the floor. From the # register 64-65 of the load-check firmware) as fast as I2C allows, and
# curve it reports two touch heights: # stops the move when the force reaches STOP. The Z of each reading comes
# threshold z: where the force first reaches THRESHOLD (interpolated # from stepper_z's position at that time. It has to be one quick press:
# between the two steps around it), like an endstop would # 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 # fit z: where a straight line through the readings at or above
# THRESHOLD reaches the no-contact level (the mean of the # THRESHOLD reaches the no-contact level (the mean of the
# readings before the descent): the zero-force touch point # 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 TOUCH_COMPARE macro (macros/sensors/touch_compare.cfg), which heats
# the nozzle and homes first. # the nozzle and homes first.
# #
# Safety: the force only goes to STOP (default 80; a light finger push on # Safety: the move stops when the force reaches STOP (default 80, about
# the nozzle is about 41, a purge 64-246), the descent ends at FLOOR below # 0.3 mm into the bed; a purge peaks at 64-246) and overshoots by what was
# the start, and the nozzle always goes back up to the start height, also # already queued (at most ~0.15 s of the move, ~0.05 mm at 0.3 mm/s). The
# after an error. It refuses to run while the bdp_guard is armed (in stop # 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. # 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 # 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] # sensor: bd_pa # name after "bdpressure" in [bdpressure bd_pa]
# #
# Commands: # Commands:
# BDP_TOUCH [THRESHOLD=15] [STOP=80] [STEP=0.005] [FLOOR=0.4] [SETTLE=0.05] # BDP_TOUCH [THRESHOLD=15] [STOP=80] [SPEED=0.3] [FLOOR=0.5]
# [READS=3] # touch at the current X/Y, starting at the current Z (SPEED in mm/s)
# touch at the current X/Y, starting at the current Z # _TOUCH_COMPARE [N=10] [START=0.1] [THRESHOLD=..] [STOP=..] [SPEED=..]
# _TOUCH_COMPARE [N=10] [START=0.1] [THRESHOLD=..] [STOP=..] [STEP=..]
# the comparison loop; START is the BDP_TOUCH start height above the # the comparison loop; START is the BDP_TOUCH start height above the
# Beacon contact result of the same pair # Beacon contact result of the same pair
# #
# Every touch writes its whole curve to klippy.log ("bdp_touch: curve"), # 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 # Status (printer.bdp_touch): threshold_z, fit_z, peak, noise, slope
# (force per 0.01 mm), points, of the last BDP_TOUCH # (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_EXT = 54 # extension marker 0xBD + version
REG_DELTA = 64 # chk_delta, int16 little-endian REG_DELTA = 64 # chk_delta, int16 little-endian
EXT_MAGIC = 0xBD EXT_MAGIC = 0xBD
STEP_SPEED = 2. # mm/s for the small Z steps
LIFT_SPEED = 5. LIFT_SPEED = 5.
@@ -128,11 +133,13 @@ class BDPTouch:
self.toolhead.manual_move([None, None, z], speed) self.toolhead.manual_move([None, None, z], speed)
self.toolhead.wait_moves() 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.""" """Lower the nozzle from the current Z; returns the result dict."""
self._check_ready(gcmd) self._check_ready(gcmd)
self.toolhead.wait_moves() toolhead = self.toolhead
start = self.toolhead.get_position()[2] toolhead.wait_moves()
startpos = toolhead.get_position()
start = startpos[2]
# New zero with the nozzle free, then the no-contact level and noise # New zero with the nozzle free, then the no-contact level and noise
self.i2c.i2c_write([REG_RESET_PROBE, 1]) self.i2c.i2c_write([REG_RESET_PROBE, 1])
self.reactor.pause(self.reactor.monotonic() + 0.3) self.reactor.pause(self.reactor.monotonic() + 0.3)
@@ -141,37 +148,101 @@ class BDPTouch:
base.append(self._read_delta(1)) base.append(self._read_delta(1))
self.reactor.pause(self.reactor.monotonic() + 0.01) self.reactor.pause(self.reactor.monotonic() + 0.01)
base_mean, noise, _ = _stats(base) 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: try:
z = start movepos = list(startpos)
while True: movepos[2] = start - floor
z = round(z - step, 6) toolhead.drip_move(movepos, speed, done)
if z < start - floor: except self.printer.command_error as e:
raise gcmd.error( error = str(e)
"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
finally: 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) self._move_z(start, LIFT_SPEED)
logging.info("bdp_touch: curve start=%.4f base=%.2f noise=%.2f %s", if error is not None:
start, base_mean, noise, raise gcmd.error("BDP_TOUCH: %s" % error)
" ".join("%.4f:%.1f" % p for p in curve)) # 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 # 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. sign = 1. if curve[-1][1] - base_mean >= 0 else -1.
force = [(zz, sign * (d - base_mean)) for zz, d in curve] 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 thr_z = None
prev = (start, 0.) for i in range(1, len(force) - 2):
for zz, f in force: if all(f >= threshold for zz, f in force[i:i + 3]):
if f >= threshold: (pz, pf), (zz, f) = force[i - 1], force[i]
pz, pf = prev thr_z = zz if f == pf else (
thr_z = pz + (zz - pz) * (threshold - pf) / (f - pf) pz + (zz - pz) * (threshold - pf) / (f - pf))
break break
prev = (zz, f)
fit_z = slope = None fit_z = slope = None
pts = [(zz, f) for zz, f in force if f >= threshold] pts = [(zz, f) for zz, f in force if f >= threshold]
if len(pts) >= 3: if len(pts) >= 3:
@@ -193,10 +264,8 @@ class BDPTouch:
return dict( return dict(
threshold=gcmd.get_float('THRESHOLD', 15., above=0.), threshold=gcmd.get_float('THRESHOLD', 15., above=0.),
stop=gcmd.get_float('STOP', 80., above=0., maxval=150.), stop=gcmd.get_float('STOP', 80., above=0., maxval=150.),
step=gcmd.get_float('STEP', 0.005, minval=0.001, maxval=0.02), speed=gcmd.get_float('SPEED', 0.3, minval=0.05, maxval=1.),
floor=gcmd.get_float('FLOOR', 0.4, above=0., maxval=1.), floor=gcmd.get_float('FLOOR', 0.5, 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))
def _fmt(self, v): def _fmt(self, v):
return "-" if v is None else "%.4f" % 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, " "BDP_TOUCH: threshold z %s, fit z %s, peak %.0f, noise %.1f, "
"%s per 0.01 mm, %d points" "%s per 0.01 mm, %d points"
% (self._fmt(r['threshold_z']), self._fmt(r['fit_z']), r['peak'], % (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'])) r['points']))
def cmd_TOUCH_COMPARE(self, gcmd): def cmd_TOUCH_COMPARE(self, gcmd):
+3 -3
View File
@@ -2,7 +2,7 @@
# and the bd_pressure load-check firmware). See extras/bdp_touch.py. # and the bd_pressure load-check firmware). See extras/bdp_touch.py.
# #
# TOUCH_COMPARE [N=10] [X=175] [Y=175] [TEMP=150] [THRESHOLD=15] [STOP=80] # TOUCH_COMPARE [N=10] [X=175] [Y=175] [TEMP=150] [THRESHOLD=15] [STOP=80]
# [STEP=0.005] [START=0.1] # [SPEED=0.3] [START=0.1]
# Nozzle to TEMP (Beacon contact refuses above 180C), HOME (contact Z), # Nozzle to TEMP (Beacon contact refuses above 180C), HOME (contact Z),
# then N pairs at X/Y: one Beacon contact probe, one BDP_TOUCH starting # then N pairs at X/Y: one Beacon contact probe, one BDP_TOUCH starting
# START mm above the Beacon result. Reports per method the mean, standard # START mm above the Beacon result. Reports per method the mean, standard
@@ -12,7 +12,7 @@
# Nozzle heater off at the end. # Nozzle heater off at the end.
# #
# BDP_TOUCH alone: touch at the current X/Y from the current Z (home first, # BDP_TOUCH alone: touch at the current X/Y from the current Z (home first,
# start 0.1-0.2 mm above the bed). # start 0.1-0.2 mm above the bed). One quick press, see extras/bdp_touch.py.
[bdp_touch] [bdp_touch]
sensor: bd_pa sensor: bd_pa
@@ -33,6 +33,6 @@ gcode:
G90 G90
G1 X{x} Y{y} Z5 F6000 G1 X{x} Y{y} Z5 F6000
M400 M400
_TOUCH_COMPARE N={params.N|default(10)|int} START={params.START|default(0.1)|float} THRESHOLD={params.THRESHOLD|default(15)|float} STOP={params.STOP|default(80)|float} STEP={params.STEP|default(0.005)|float} _TOUCH_COMPARE N={params.N|default(10)|int} START={params.START|default(0.1)|float} THRESHOLD={params.THRESHOLD|default(15)|float} STOP={params.STOP|default(80)|float} SPEED={params.SPEED|default(0.3)|float}
M104 S0 M104 S0
{% endif %} {% endif %}