101 Commits
Author SHA1 Message Date
Kevin O'Connor f54b7b9376 sos_filter: Fix validate_section_index() check
A section_idx equal to max_sections is also invalid.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-06-11 17:59:02 -04:00
Kevin O'Connor 5666b88c69 ar100: Convert to or1k-elf toolchain
The more.musl.cc site is blocking downloads from all github actions,
which makes it difficult to use that site for the ar100 cross build
toolchain.  Convert to the openrisc or1k-elf toolchain as a
replacement.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-06-08 14:15:50 -04:00
Kevin O'Connor 889be5b275 docs: Fix typo in Benchmarks.md
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-06-08 12:23:02 -04:00
Timofey Titovets 607d0b4237 input_shaper: fix printer obj reference
Signed-off-by: Timofey Titovets <nefelim4ag@gmail.com>
2025-06-06 15:43:29 -04:00
Kevin O'Connor d120a313b7 docs: Note 'config' object shouldn't be accessed after initial load
Update Code_Overview.md to note that the config object should not be
stored after the "config loading phase".

Remove a few inadvertent cases where a 'config' object was stored
in module member variables.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-06-04 13:46:28 -04:00
Dmitry Butyugin 4d4b9684a5 input_shaper: Track kinematics updates by dual_carriage
Signed-off-by: Dmitry Butyugin <dmbutyugin@google.com>
2025-06-04 13:40:58 -04:00
Kevin O'Connor 14cbb8dd2d rp2040: Prefer larger postdiv1 on rp2040 chips
The rp2040 uses a pll vco divider of 6.  Prefer setting postdiv1=6 and
postdiv2=1 (instead of the previous postdiv1=3 and postdiv2=2).

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-06-02 14:10:42 -04:00
Kevin O'Connor aa3388cc59 klippy-requirements: Update setuptools revision to 78.1.1
A security vulnerability was found in setuptools - increase package
dependency to fixed version.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-06-02 13:31:17 -04:00
Timofey Titovets d6902240dd htu21: fix crash on unknown dev id
Signed-off-by: Timofey Titovets <nefelim4ag@gmail.com>
2025-06-02 13:17:41 -04:00
Kevin O'Connor 105ce35e1b stm32: Add comments on PLL frequency requirements to clock setup code
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-06-02 13:15:53 -04:00
Kevin O'Connor c0ca4c5cc7 docs: Update benchmarks with stm32g431 chip
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-06-02 13:15:48 -04:00
Kevin O'Connor cfa48fe39f stm32: Run stm32g431 at 170Mhz
The chip supports 170Mhz, so no need to run at 150Mhz.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-05-31 15:20:12 -04:00
Ingo Donasch 2dd73d0431 print_stats: Fix for filament statistics bug in print_stats.py for toolchangers (#6946)
added extruder:activate_extruder event hook to print_stats.py to update self.last_epos

Signed-off-by: Ingo Donasch <ingo@donasch.net>
2025-05-31 13:06:44 -04:00
Kevin O'Connor d25602e88d docs: Update CAN bus command rate benchmarks
Add a benchmark for the rp2350 device when running via CAN bus.
Remove the old stm32f042 CAN bus benchmark as that test predates a
number of importnat CAN bus code changes and is likely no longer
accurate.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-05-31 12:24:40 -04:00
Kevin O'Connor 1f3b4cc749 stm32: Fix spi overflow issue on stm32h7
Completely filling the spi transmit fifo could lead to a situation
where the rx fifo overflows.  Make sure not to write past the rx fifo
size.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-05-30 20:36:09 -04:00
Kevin O'Connor 8e58f8fb39 rp2040: Fix spi overflow issue
Completely filling the spi transmit fifo could lead to a situation
where the rx fifo overflows.  Make sure not to write past the rx fifo
size.

Also, be sure to wait for the transmission to fully complete before
exiting spi_transfer().

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-05-30 16:34:49 -04:00
Timofey Titovets f4130aa948 rp2040: spi - enable fifo
Signed-off-by: Timofey Titovets <nefelim4ag@gmail.com>
2025-05-30 15:18:07 -04:00
Kevin O'Connor de182b1d14 stm32: Support using CANBUS on PB5/PB6 on stm32h7 chips
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-05-30 15:15:13 -04:00
Kevin O'Connor f5956b5395 stm32: Simplify Kconfig HAVE_STM32_CANBUS checks
Avoid unnecessary (HAVE_STM32_CANBUS && MACH_STM32xx) checks in
Kconfig.  The HAVE_STM32_CANBUS is a helper symbol for all the chips
that support canbus, there's no need to mix it with a check for a chip
that is already known to have canbus.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-05-30 15:15:13 -04:00
Kevin O'Connor 8d7e487149 sos_filter: Improve error checking on section_idx
Validate host provided index prior to accessing memory using that
index.

Also, consistently use a uint8_t for max_sections (to account for
integer overflow issues).

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-05-29 19:30:45 -04:00
Kevin O'Connor eb43b20e3b load_cell_probe: Avoid peeking directly at config.section member variable
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-05-29 19:17:45 -04:00
Gareth Farrington 388fe1b23f docs: Load Cell Probe Documentation
Add documentation updates for Homing & Probing with load cell probe

Signed-off-by: Gareth Farrington <gareth@waves.ky>
2025-05-29 19:11:05 -04:00
Gareth Farrington f6d878a898 filter_workbench: Add Filter Workbench
Add a filter workbench Jupiter notebook to help printer developers tune filters based on probing data

Signed-off-by: Gareth Farrington <gareth@waves.ky>
2025-05-29 19:10:51 -04:00
Gareth Farrington b3e894f241 load_cell_probe: Create LoadCellProbe
Initial setup of Load Cell Probing. This implementation supports triggering from the Load Cell Probe on the MCU. It also supports, optiopnal, filtering of the force signal by sos filter to eliminate drift caused by bowden tubes or other mechanical causes.

Signed-off-by: Gareth Farrington <gareth@waves.ky>
2025-05-29 19:10:21 -04:00
Gareth Farrington 3dbac01e1d probe: Create ProbeVirtualEndstopDeprecation
As probes stop supporting `probe:z_virtual_endstop` this class will give users a polite and specific configuration error.

Signed-off-by: Gareth Farrington <gareth@waves.ky>
2025-05-29 19:08:32 -04:00
Gareth Farrington 69507a0354 sensor_hx71x: Update Sensors to report to load_cell_probe
Signed-off-by: Gareth Farrington <gareth@waves.ky>
2025-05-29 19:07:49 -04:00
Gareth Farrington 42c9031c81 load_cell_probe: Create load_cell_probe MCU object
Implement MCU features that enable using an adc to stop an axis

Signed-off-by: Gareth Farrington <gareth@waves.ky>
2025-05-29 19:06:48 -04:00
Gareth Farrington cb0c38f7d8 sos_filter: Second Order Sections MCU Filter
This is an implementation of the SOS fliltering algorithm that runs on the MCU.

The filter opperates on data in fixed point format to avoid use of the FPU as klipper does not support FPU usage.

This host object handles duties of initalizing and resetting the filter so client dont have to declare their own commands for these opperations. Clients can select how many integer bits they want to use for both the filter coefficients and the filters output value. An arbitrary number of filter sections can be configured. Filters can be designed on the fly with the SciPy library or loaded from another source.

Signed-off-by: Gareth Farrington <gareth@waves.ky>
2025-05-29 19:01:38 -04:00
Timofey Titovets 0181023954 lis2dw: if spi is used - disable i2c
Signed-off-by: Timofey Titovets <nefelim4ag@gmail.com>
2025-05-26 18:44:29 -04:00
Timofey Titovets 07b3726d31 stm32: h7 spi - add a delay on SCK polarity change
Signed-off-by: Timofey Titovets <nefelim4ag@gmail.com>
2025-05-26 18:44:29 -04:00
Timofey Titovets 28a4baf95c spi_software: add a delay on mode change
Signed-off-by: Timofey Titovets <nefelim4ag@gmail.com>
2025-05-26 18:44:29 -04:00
Timofey Titovets 14685bf77f rp2040: add a delay on SCK polarity change
Signed-off-by: Timofey Titovets <nefelim4ag@gmail.com>
2025-05-26 18:44:29 -04:00
Dmitry Butyugin b1011e3fb1 dual_carriage: Fixed input shaper stepper kinematics initialization
Signed-off-by: Dmitry Butyugin <dmbutyugin@google.com>
2025-05-22 14:44:09 -04:00
Kevin O'Connor 17b8ce4c6b docs: Remove SHAPER_CALIBRATE and usb-to-canbus bridge warning in CANBUS.md
There have been several optimization to the usb to canbus bridge code
since that statement and it is likely many setups can run a
SHAPER_CALIBRATE with all activity on a single 1mbit canbus.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-05-19 12:54:26 -04:00
Kevin O'Connor 9090377bbc stm32: Allow stm32g4 chips to select a bootloader
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-05-19 12:31:46 -04:00
JamesH1978 2d4589949c docs: Update Installation.md - Flash loop protection (#6935)
Added a paragraph about flash loop protection on some motherboards. It has been noted that not all people know about the need to change the bin filename on some stock boards or other methods that may hinder progress.

Signed-off-by: James Hartley <james@hartleyns.com>
2025-05-19 12:30:39 -04:00
Timofey Titovets 8c01be8c75 stm32: spi enable fifo if supported (#6936)
Signed-off-by: Timofey Titovets <nefelim4ag@gmail.com>
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-05-19 12:24:29 -04:00
Timofey Titovets 3a015cd00d stm32: H7 spi enable use of fifo
Signed-off-by: Timofey Titovets <nefelim4ag@gmail.com>
2025-05-19 12:21:33 -04:00
Kevin O'Connor 841a9ca2f7 stm32: Avoid read-modify-write register access in stm32h7_spi.c
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-05-16 12:26:52 -04:00
Kevin O'Connor fe9eff8ce3 docs: Fix index.md links
Use relative links in index.md and correct the location of the COPYING
file.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-05-16 12:14:45 -04:00
Rowland 82f540bb73 docs: BED_MESH_CALIBRATE makes a mesh that is immediately available. (#6919)
The docs aren't particularly clear that if you generate a mesh in our start g-code, you can just use it without additional commands. This is causing issues with support on r/klippers

Signed-off-by: Rowland Straylight <rowlandstraylight@gmail.com>
2025-05-14 13:53:10 -04:00
Kevin O'Connor ed36041b67 resonance_tester: Fix typo
Fix typo introduced in 307c03e48.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-05-13 11:14:30 -04:00
Kevin O'Connor 1af219fad6 klippy_requirements: Update dependencies to support Python v3.13
Signed-off-by: Timofey Titovets <nefelim4ag@gmail.com>
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-05-12 21:51:53 -04:00
Kevin O'Connor 6c1d5d912a manual_stepper: Support LIMIT_VELOCITY and LIMIT_ACCEL when using gcode axis
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-05-12 20:15:03 -04:00
Kevin O'Connor ee0bc3d697 manual_stepper: Support position_min and position_max options
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-05-12 20:15:03 -04:00
Kevin O'Connor 64e01f03a2 manual_stepper: Support INSTANTANEOUS_CORNER_VELOCITY on gcode axes
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-05-12 20:15:03 -04:00
Kevin O'Connor 7201f41664 manual_stepper: Support registering as an additional axis
Add a new G-Code command that can register a manual_stepper as an
additional axis on standard G-Code G1 commands.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-05-12 20:15:03 -04:00
Kevin O'Connor d40fd2190d gcode_move: Support additional toolhead axes
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-05-12 20:15:03 -04:00
Kevin O'Connor 4c21e1d00f gcode_move: Internally track an axis_map to map gcode axis names
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-05-12 20:15:03 -04:00
Kevin O'Connor 2082300309 z_thermal_adjust: Support toolhead positions with more than 4 axes
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-05-12 20:15:03 -04:00
Kevin O'Connor 53acdfd0a5 skew_correction: Support toolhead positions with more than 4 axes
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-05-12 20:15:03 -04:00
Kevin O'Connor a537ae0ceb exclude_object: Support toolhead positions with more than 4 axes
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-05-12 20:15:03 -04:00
Kevin O'Connor 307c03e480 resonance_tester: Support toolhead positions with more than 4 axes
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-05-12 20:15:03 -04:00
Kevin O'Connor 64d6f110a9 bed_tilt: Support toolhead positions with more than 4 axes
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-05-12 20:15:03 -04:00
Kevin O'Connor 447908ce0c bed_mesh: Support toolhead positions with more than 4 axes
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-05-12 20:15:03 -04:00
Kevin O'Connor bb281834b0 toolhead: Initial support for adding extra axes to toolhead moves
Add a new add_extra_axes() to support adding additional axes.  Once
called, toolhead.get_position() will return a list object with more
than 4 items, and toolhead.move() requires the same size list.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-05-12 20:15:03 -04:00
Kevin O'Connor 9dbfc76d9d force_move: No need to pass 4 parameters to toolhead.set_position()
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-05-12 20:15:03 -04:00
Kevin O'Connor ae536b4786 toolhead: Only alter XYZ coordinates on set_position() calls
It's not valid to alter the extruder position from a call to
set_position(), so don't allow callers to attempt that.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-05-12 20:15:03 -04:00
Kevin O'Connor 8928c394cf toolhead: Support unregister_step_generator() call
Allow both registering and unregistering step generation callbacks.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-05-12 20:15:03 -04:00
Kevin O'Connor 01422da951 extruder: Remove update_move_time() call
The toolhead can obtain the underlying extruder trapq via
extruder.get_trapq().

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-05-12 20:15:03 -04:00
Kevin O'Connor f06eeb5c7a extruder: Rename extruder.move() to extruder.process_move()
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-05-12 20:15:03 -04:00
Dmitry Butyugin ca83c13f37 generic_cartesian: Fixed safe_z_home and manual_probe for new kinematics
Signed-off-by: Dmitry Butyugin <dmbutyugin@google.com>
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-05-10 20:16:00 -04:00
Dmitry Butyugin 8627c94d6a stepper: Fix broken manual_stepper rail naming (#6929)
The naming got broken during refactoring for generic_cartesian.

Signed-off-by: Dmitry Butyugin <dmbutyugin@google.com>
2025-05-10 20:10:54 -04:00
Kevin O'Connor 6f87a4e685 stepper: Minor code tweak - remove unneeded parenthesis
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-05-09 12:58:01 -04:00
Kevin O'Connor b5aea5b774 stepper: Minor code reorg - remove unneeded HAVE_OPTIMIZED_PATH definition
Make it more clear that stepper_load_next() has three separate code
paths - one for each of the optimized stepper_event_X() functions.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-05-09 12:38:25 -04:00
Kevin O'Connor fd55dd9e9d stepper: Also ensure minimum time after dir change and next step
In practice the host will not schedule any steps immediately after a
direction change (due to acceleration limits and the host
"step+dir+step filter").  However, there is also no harm in enforcing
a minimum duration in the mcu.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-05-09 09:52:05 -04:00
Kevin O'Connor 885f63cff0 stepper: Ensure minimum time between step pin and dir pin change
Commit 8faed8d9 made it possible to utilize stepper_event_full() while
utilizing tmc "step on both edges" optimation.  That commit would
ensure a minimum step pulse duration, but it did not ensure a minimum
duration between step pin and dir pin changes.  Commits 0d27195f and
554ae78d optimized the gpio handling on stm32h7 chips, which could
potentially cause a very small amount of time between step pin and dir
pin changes.

Enforce a minimum time after a step pin update before updating the dir
pin.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-05-09 09:52:05 -04:00
Kevin O'Connor efabe63357 stepper: Move timer checks from stepper_event_full() to stepper_load_next()
This simplifies the stepper_event_full() and makes it easier to
implement more complex checks.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-05-09 09:52:05 -04:00
Kevin O'Connor 1dc9aa8e19 stepper: Free stepper_move struct near top of stepper_load_next()
Move up the freeing of the stepper_move struct and setting of
s->position in stepper_load_next().  This simplifies the code and
will make it easier to add more logic to this function.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-05-09 09:52:05 -04:00
Matszwe02 9aba1a8536 gcode_macro: more descriptive "unable to parse as a literal" error - display faulty command
Signed-off-by: Mateusz Szwedka <matszwe02@gmail.com>
2025-05-08 11:37:38 -04:00
JamesH1978 81277154d2 config: Update CR6-SE 2021 config with board revision (#6924)
As per #6923 this PR adds the fact that this config works for the late revision CR-ERA_V1.1.0.3 board as well.

Signed-off-by: James Hartley <james@hartleyns.com>
2025-05-08 11:36:04 -04:00
JamesH1978 d444289111 config: Update CR6-SE 2020 config with board revision (#6923)
It has been noted that there are 3 possible boards with 2 possible configs, which we have both of, but this one does not state that it is for the 4.5.2 early kickstarter version. Which was causing some confusion.

Signed-off-by: James Hartley <james@hartleyns.com>
2025-05-08 11:35:38 -04:00
Dmitry Butyugin 89ffbbed4c dual_carriage: Fixed broken safe_distance parameter
Signed-off-by: Dmitry Butyugin <dmbutyugin@google.com>
2025-05-07 14:23:39 -04:00
Dmitry Butyugin cc6736c3e3 kinematics: Generic Cartesian kinematics implementation (#6815)
* tests: Added a regression test for generic_cartesian kinematics

* kinematics: An intial implementation of generic_cartesian kinematics

* generic_cartesian: Refactored kinematics configuration API

* generic_cartesian: Use stepper instead of kinematic_stepper in configs

* generic_cartesian: Added SET_STEPPER_KINEMATICS command

* generic_cartesian: Fixed parsing of section names

* docs: Generic Caretsian kinematics documentation and config samples

* generic_cartesian: Implemented multi-mcu homing validation

* generic_cartesian: Fixed typos in docs, minor fixes

* generic_cartesian: Renamed `kinematics` option to `carriages`

* generic_cartesian: Moved kinematic_stepper.py file

* idex_modes: Internal refactoring of handling dual carriages

* stepper: Refactored the code to not store a reference to config object

* config: Updated example-generic-cartesian config

* generic_cartesian: Restricted SET_STEPPER_CARRIAGES and exported status

* idex_modes: Fixed handling stepper kinematics with input shaper enabled

* config: Updated configs and tests for SET_DUAL_CARRIAGE new params

* generic_cartesian: Avoid inheritance in the added classes

Signed-off-by: Dmitry Butyugin <dmbutyugin@google.com>
2025-05-06 18:06:36 -04:00
Kevin O'Connor 1cc6398074 klippy-requirements: Add comments to each of the requirements
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-05-02 13:52:20 -04:00
Eric Callahan 1e045e8ee0 build: add msgspec python requirement
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-05-02 12:19:13 -04:00
Eric Callahan f7e33df99d webhooks: support msgspec json serialization
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-05-02 12:19:13 -04:00
Kevin O'Connor 4504c0333f docs: Update stm32h723 benchmarks now that it runs at 520Mhz
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-05-02 12:06:59 -04:00
Kevin O'Connor 554ae78d8c stm32: Run stm32h723 at 520Mhz
Increase speed of stm32h723 chips from 400Mhz to 520Mhz.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-05-02 11:44:31 -04:00
Kevin O'Connor ee79d0e307 stm32: Support over 400Mhz main clock in stm32h7_adc.c
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-05-02 11:44:31 -04:00
Kevin O'Connor 7b697105b3 stm32: Use 12Mhz nominal internal clock in stm32f0_i2c.c
Increase the internal nominal clock from 8Mhz to 12Mhz - this improves
support for higher chip frequencies.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-05-02 11:44:31 -04:00
Kevin O'Connor 3cf8899a5a docs: Note canbus_query.py limitations in CANBUS_Troubleshooting.md
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-04-29 13:52:57 -04:00
Kevin O'Connor b7c243db19 docs: Note functioning canbus required even in bridge mode in CANBUS.md
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-04-29 13:02:34 -04:00
Kevin O'Connor 5b2f8104c7 neopixel: Round up in nsecs_to_ticks()
The rp2040 operates at a fast internal clock with a relatively slow
external timer and dividing down could result in a too small delay.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-04-28 19:55:30 -04:00
Kevin O'Connor cf3bedfbdc stm32: Enable VOS0 power mode on stm32h723 if frequency above 400Mhz
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-04-28 19:36:55 -04:00
Kevin O'Connor 7f4f696f10 stm32: Don't try to set incorrect PWR->CR3 register on stm32h7
It's not valid to set BYPASS and LDOEN at the same time.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-04-28 19:36:55 -04:00
Kevin O'Connor 9c37a918db stm32: Set the PLL frequency equal to CONFIG_CLOCK_FREQ on stm32h723
There is no reason to use a higher internal PLL frequency.  This
change also makes it possible to enable higher clock frequencies on
the stm32h723.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-04-28 19:36:55 -04:00
Kevin O'Connor f2b68fef73 stm32: Avoid read-modify-write register updates in stm32h7 clock_setup()
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-04-28 19:36:55 -04:00
Kevin O'Connor c352617c30 stm32: Use enable_pclock() in stm32h7 clock_setup()
Use the helper functions to enable the peripheral clock instead of
directly manipulating the clock enable bits.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-04-28 19:36:55 -04:00
Kevin O'Connor 5d1f773ffb stm32h7: Always clear AHB1ENR at startup on stm32h7
Entirely clear the AHB1ENR register.  There is no need to modify
AHB1LPENR.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-04-28 19:36:55 -04:00
Kevin O'Connor da8e0a6e50 docs: Update date of cycle_time change in Config_Changes.md
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-04-28 19:36:12 -04:00
Kevin O'Connor 42faa962fc mcu: Decrease mcu.max_nominal_duration() to 3 seconds from 5
This allows the mcu to utilize faster internal speeds.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-04-28 19:28:52 -04:00
Kevin O'Connor 0f94f6c8e3 heaters: Confirm heater setting in mcu every 3 seconds instead of 5
Increase the confirmation rate of heater enable settings.  This allows
the mcu to utilize faster internal speeds.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-04-28 19:28:52 -04:00
Kevin O'Connor c917bd893d pwm_tool: Use mcu.min_schedule_time() and mcu.max_nominal_duration()
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-04-28 19:28:52 -04:00
Kevin O'Connor d57bc253c5 led: Use mcu.min_schedule_time() and mcu.max_nominal_duration()
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-04-28 19:28:52 -04:00
Kevin O'Connor 0dce120a20 pwm_cycle_time: Use mcu.min_schedule_time() and mcu.max_nominal_duration()
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-04-28 19:28:52 -04:00
Kevin O'Connor ab61b0a435 output_pin: Use mcu.min_schedule_time() and mcu.max_nominal_duration()
Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-04-28 19:28:52 -04:00
Kevin O'Connor cc919a5f8d mcu: Add new min_schedule_time() and max_nominal_duration() helpers
Add a function that returns the minimum amount of time the host needs
to reserve for messages to be sent from host to micro-controller.

Add a function that returns the maximum amount of time (in seconds)
that all micro-controllers should be able to schedule future timers
at.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-04-28 19:28:52 -04:00
Kevin O'Connor 8e107b2280 basecmd: Update stats timing check to support 32bit duration
Use a 32bit duration check instead of the previous 31bit check.

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
2025-04-28 19:28:52 -04:00
Wulfsta f1e0730701 lis3dh: increase scale from 8g to 16g
Signed-off-by: Luke Vuksta <wulfstawulfsta@gmail.com>
2025-04-28 19:27:43 -04:00
Timofey Titovets 2e82fc4790 spi_flash: fix hw bus
_try_send_command() expects a list of args,
But receives a string.

Fixes abc76ee963.

Signed-off-by: Timofey Titovets <nefelim4ag@gmail.com>
2025-04-28 15:58:55 -04:00
106 changed files with 5246 additions and 667 deletions

No files matched your search

+138
View File
@@ -0,0 +1,138 @@
# This file is an example config file for cartesian style printers.
# One may copy and edit this file to configure a new printer with
# a generic cartesian kinematics.
# DO NOT COPY THIS FILE WITHOUT CAREFULLY READING AND UPDATING IT
# FIRST. Incorrectly configured parameters may cause damage.
# See docs/Config_Reference.md for a description of parameters.
[carriage x]
position_endstop: 0
position_max: 300
homing_speed: 50
endstop_pin: ^PE5
[carriage y]
position_endstop: 0
position_max: 200
homing_speed: 50
endstop_pin: ^PJ1
[extra_carriage y1]
primary_carriage: y
endstop_pin: ^PB6
[carriage z]
position_endstop: 0.5
position_max: 100
endstop_pin: ^PD3
[dual_carriage u]
primary_carriage: x
position_endstop: 300
position_max: 300
homing_speed: 50
endstop_pin: ^PE4
[stepper my_stepper_x]
carriages: x+y
step_pin: PF0
dir_pin: PF1
enable_pin: !PD7
microsteps: 16
rotation_distance: 40
[stepper my_stepper_u]
carriages: u-y1
step_pin: PH1
dir_pin: PH0
enable_pin: !PA1
microsteps: 16
rotation_distance: 40
[stepper my_stepper_y0]
carriages: y
step_pin: PF6
dir_pin: !PF7
enable_pin: !PF2
microsteps: 16
rotation_distance: 40
[stepper my_stepper_y1]
carriages: y1
step_pin: PE3
dir_pin: !PH6
enable_pin: !PG5
microsteps: 16
rotation_distance: 40
[stepper my_stepper_z0]
carriages: z
step_pin: PL3
dir_pin: PL1
enable_pin: !PK0
microsteps: 16
rotation_distance: 8
[stepper my_stepper_z1]
carriages: z
step_pin: PG1
dir_pin: PG0
enable_pin: !PH3
microsteps: 16
rotation_distance: 8
[extruder]
step_pin: PA4
dir_pin: PA6
enable_pin: !PA2
microsteps: 16
rotation_distance: 33.5
nozzle_diameter: 0.400
filament_diameter: 1.750
heater_pin: PB4
sensor_type: EPCOS 100K B57560G104F
sensor_pin: PK5
control: pid
pid_Kp: 22.2
pid_Ki: 1.08
pid_Kd: 114
min_temp: 0
max_temp: 250
[extruder1]
step_pin: PC1
dir_pin: PC3
enable_pin: !PC7
microsteps: 16
rotation_distance: 33.5
nozzle_diameter: 0.400
filament_diameter: 1.750
heater_pin: PB5
sensor_type: EPCOS 100K B57560G104F
sensor_pin: PK7
control: pid
pid_Kp: 22.2
pid_Ki: 1.08
pid_Kd: 114
min_temp: 0
max_temp: 250
[heater_bed]
heater_pin: PH5
sensor_type: EPCOS 100K B57560G104F
sensor_pin: PK6
control: watermark
min_temp: 0
max_temp: 110
[mcu]
serial: /dev/ttyACM0
[printer]
kinematics: generic_cartesian
max_velocity: 500
max_accel: 3000
max_z_velocity: 20
max_z_accel: 100
+2 -1
View File
@@ -1,4 +1,5 @@
# This file contains pin mappings for the stock 2020 Creality CR6-SE.
# This file contains pin mappings for the stock 2020 Creality CR6-SE
# with the early 4.5.2 board only.
# To use this config, during "make menuconfig" select the STM32F103
# with a "28KiB bootloader" and serial (on USART1 PA10/PA9)
# communication.
+3 -1
View File
@@ -1,4 +1,6 @@
# This file contains pin mappings for the Creality CR6-SE with Rev. 4.5.3 Motherboard (Late 2020/2021) as the heater pins changed.
# This file contains pin mappings for the Creality CR6-SE
# with Rev. 4.5.3 Motherboard (Late 2020/2021) as the heater pins changed.
# This config also works for the CR-ERA_V1.1.0.3
# To use this config, during "make menuconfig" select the STM32F103
# with a "28KiB bootloader" and serial (on USART1 PA10/PA9)
# communication.
+177
View File
@@ -0,0 +1,177 @@
# This file contains a configuration snippet for a CoreXYUV
# printer with an independent dual extruder moving over X and Y axes.
# See docs/Config_Reference.md for a description of parameters.
[carriage x]
position_endstop: 0
position_max: 300
homing_speed: 50
endstop_pin: ^PE5
[carriage y]
position_endstop: 0
position_max: 200
homing_speed: 50
endstop_pin: ^PJ1
[dual_carriage u]
primary_carriage: x
safe_distance: 70
position_endstop: 300
position_max: 300
homing_speed: 50
endstop_pin: ^PE4
[dual_carriage v]
primary_carriage: y
safe_distance: 50
position_endstop: 200
position_max: 200
homing_speed: 50
endstop_pin: ^PD4
[stepper a]
carriages: x+y
step_pin: PF0
dir_pin: PF1
enable_pin: !PD7
microsteps: 16
rotation_distance: 40
[stepper b]
carriages: u-v
step_pin: PH1
dir_pin: PH0
enable_pin: !PA1
microsteps: 16
rotation_distance: 40
[stepper c]
carriages: x-y
step_pin: PF6
dir_pin: !PF7
enable_pin: !PF2
microsteps: 16
rotation_distance: 40
[stepper d]
carriages: u+v
step_pin: PE3
dir_pin: !PH6
enable_pin: !PG5
microsteps: 16
rotation_distance: 40
[extruder]
step_pin: PA4
dir_pin: PA6
enable_pin: !PA2
microsteps: 16
rotation_distance: 33.5
nozzle_diameter: 0.400
filament_diameter: 1.750
heater_pin: PB4
sensor_type: EPCOS 100K B57560G104F
sensor_pin: PK5
control: pid
pid_Kp: 22.2
pid_Ki: 1.08
pid_Kd: 114
min_temp: 0
max_temp: 250
[gcode_macro PARK_extruder]
gcode:
SET_DUAL_CARRIAGE CARRIAGE=x
SET_DUAL_CARRIAGE CARRIAGE=y
G90
G1 X0 Y0
[gcode_macro T0]
gcode:
PARK_{printer.toolhead.extruder}
ACTIVATE_EXTRUDER EXTRUDER=extruder
SET_DUAL_CARRIAGE CARRIAGE=x
SET_DUAL_CARRIAGE CARRIAGE=y
[extruder1]
step_pin: PC1
dir_pin: PC3
enable_pin: !PC7
microsteps: 16
rotation_distance: 33.5
nozzle_diameter: 0.400
filament_diameter: 1.750
heater_pin: PB5
sensor_type: EPCOS 100K B57560G104F
sensor_pin: PK7
control: pid
pid_Kp: 22.2
pid_Ki: 1.08
pid_Kd: 114
min_temp: 0
max_temp: 250
[gcode_macro PARK_extruder1]
gcode:
SET_DUAL_CARRIAGE CARRIAGE=u
SET_DUAL_CARRIAGE CARRIAGE=v
G90
G1 X300 Y200
[gcode_macro T1]
gcode:
PARK_{printer.toolhead.extruder}
ACTIVATE_EXTRUDER EXTRUDER=extruder1
SET_DUAL_CARRIAGE CARRIAGE=u
SET_DUAL_CARRIAGE CARRIAGE=v
# A helper script to activate copy mode
[gcode_macro ACTIVATE_COPY_MODE]
gcode:
SET_DUAL_CARRIAGE CARRIAGE=x MODE=PRIMARY
SET_DUAL_CARRIAGE CARRIAGE=y MODE=PRIMARY
G1 X0 Y0
ACTIVATE_EXTRUDER EXTRUDER=extruder
SET_DUAL_CARRIAGE CARRIAGE=u MODE=PRIMARY
SET_DUAL_CARRIAGE CARRIAGE=v MODE=PRIMARY
G1 X150 Y100
SET_DUAL_CARRIAGE CARRIAGE=u MODE=COPY
SET_DUAL_CARRIAGE CARRIAGE=v MODE=COPY
SYNC_EXTRUDER_MOTION EXTRUDER=extruder1 MOTION_QUEUE=extruder
# A helper script to activate mirror mode
[gcode_macro ACTIVATE_MIRROR_MODE]
gcode:
SET_DUAL_CARRIAGE CARRIAGE=x MODE=PRIMARY
SET_DUAL_CARRIAGE CARRIAGE=y MODE=PRIMARY
G1 X0 Y0
ACTIVATE_EXTRUDER EXTRUDER=extruder
SET_DUAL_CARRIAGE CARRIAGE=u MODE=PRIMARY
SET_DUAL_CARRIAGE CARRIAGE=v MODE=PRIMARY
G1 X300 Y100
SET_DUAL_CARRIAGE CARRIAGE=u MODE=MIRROR
SET_DUAL_CARRIAGE CARRIAGE=v MODE=COPY
SYNC_EXTRUDER_MOTION EXTRUDER=extruder1 MOTION_QUEUE=extruder
[printer]
kinematics: generic_cartesian
max_velocity: 300
max_accel: 3000
max_z_velocity: 5
max_z_accel: 100
## An optional input shaper support
#[input_shaper]
## The section is intentionally empty
#
#[delayed_gcode init_shaper]
#initial_duration: 0.1
#gcode:
# SET_DUAL_CARRIAGE CARRIAGE=u
# SET_DUAL_CARRIAGE CARRIAGE=v
# SET_INPUT_SHAPER SHAPER_TYPE_X=<dual_carriage_x_shaper> SHAPER_FREQ_X=<dual_carriage_x_freq> SHAPER_TYPE_Y=<dual_carriage_y_shaper> SHAPER_FREQ_Y=<dual_carriage_y_freq>
# SET_DUAL_CARRIAGE CARRIAGE=x MODE=PRIMARY
# SET_DUAL_CARRIAGE CARRIAGE=y MODE=PRIMARY
# SET_INPUT_SHAPER SHAPER_TYPE_X=<primary_carriage_x_shaper> SHAPER_FREQ_X=<primary_carriage_x_freq> SHAPER_TYPE_Y=<primary_carriage_y_shaper> SHAPER_FREQ_Y=<primary_carriage_y_freq>
+21
View File
@@ -380,6 +380,27 @@ and might later produce asynchronous messages such as:
The "header" field in the initial query response is used to describe
the fields found in later "data" responses.
### load_cell_probe/dump_taps
This endpoint is used to subscribe to details of probing "tap" events.
Using this endpoint may increase Klipper's system load.
A request may look like:
`{"id": 123, "method":"load_cell/dump_force",
"params": {"sensor": "load_cell", "response_template": {}}}`
and might return:
`{"id": 123,"result":{"header":["probe_tap_event"]}}`
and might later produce asynchronous messages such as:
```
{"params":{"tap":'{
"time": [118032.28039, 118032.2834, ...],
"force": [-459.4213119680034, -458.1640702543264, ...],
}}}
```
This data can be used to render:
* The time/force graph
### pause_resume/cancel
This endpoint is similar to running the "PRINT_CANCEL" G-Code command.
+6 -1
View File
@@ -497,7 +497,8 @@ _Default Adaptive Margin: 0_
Initiates the probing procedure for Bed Mesh Calibration.
The mesh will be saved into a profile specified by the `PROFILE` parameter,
The mesh will be immediately ready to use when the command completes and saved
into a profile specified by the `PROFILE` parameter,
or `default` if unspecified. The `METHOD` parameter takes one of the following
values:
@@ -561,6 +562,10 @@ load the `default` profile it is recommended to add
`BED_MESH_PROFILE LOAD=default` to either their `START_PRINT` macro or their
slicer's "Start G-Code" configuration, whichever is applicable.
Note that this is not required if a new mesh is generated with
`BED_MESH_CALIBRATE` in the `START_PRINT` macro or the slicer's "Start G-Code"
and may produce unexpected results, especially with adaptive meshing.
Alternatively the old behavior of loading a profile at startup can be
restored with a `[delayed_gcode]`:
+39 -15
View File
@@ -250,22 +250,22 @@ results were obtained by running an STM32F407 binary on an STM32F446
### STM32H7 step rate benchmark
The following configuration sequence is used on STM32H7:
The following configuration sequence is used on STM32H723:
```
allocate_oids count=3
config_stepper oid=0 step_pin=PA13 dir_pin=PB5 invert_step=-1 step_pulse_ticks=40
config_stepper oid=1 step_pin=PB2 dir_pin=PB6 invert_step=-1 step_pulse_ticks=40
config_stepper oid=2 step_pin=PB3 dir_pin=PB7 invert_step=-1 step_pulse_ticks=40
config_stepper oid=0 step_pin=PA13 dir_pin=PB5 invert_step=-1 step_pulse_ticks=52
config_stepper oid=1 step_pin=PB2 dir_pin=PB6 invert_step=-1 step_pulse_ticks=52
config_stepper oid=2 step_pin=PB3 dir_pin=PB7 invert_step=-1 step_pulse_ticks=52
finalize_config crc=0
```
The test was last run on commit `0d27195f` with gcc version
The test was last run on commit `554ae78d` with gcc version
`arm-none-eabi-gcc (Fedora 14.1.0-1.fc40) 14.1.0`.
| stm32h723 | ticks |
| -------------------- | ----- |
| 1 stepper | 60 |
| 3 stepper | 183 |
| 1 stepper | 70 |
| 3 stepper | 181 |
### STM32G0B1 step rate benchmark
@@ -286,6 +286,25 @@ The test was last run on commit `247cd753` with gcc version
| 1 stepper | 58 |
| 3 stepper | 243 |
### STM32G4 step rate benchmark
The following configuration sequence is used on the STM32G431:
```
allocate_oids count=3
config_stepper oid=0 step_pin=PA0 dir_pin=PB5 invert_step=-1 step_pulse_ticks=17
config_stepper oid=1 step_pin=PB2 dir_pin=PB6 invert_step=-1 step_pulse_ticks=17
config_stepper oid=2 step_pin=PB3 dir_pin=PB7 invert_step=-1 step_pulse_ticks=17
finalize_config crc=0
```
The test was last run on commit `cfa48fe3` with gcc version
`arm-none-eabi-gcc (Fedora 14.1.0-1.fc40) 14.1.0`.
| stm32g431 | ticks |
| ---------------- | ----- |
| 1 stepper | 47 |
| 3 stepper | 208 |
### LPC176x step rate benchmark
The following configuration sequence is used on the LPC176x:
@@ -422,7 +441,7 @@ Pico and Pico 2 boards.
(*) Note that the reported rp2040 ticks are relative to a 12Mhz
scheduling timer and do not correspond to its 200Mhz internal ARM
processing rate. It is expected that 5 scheduling ticks corresponds to
processing rate. It is expected that 3 scheduling ticks corresponds to
~42 ARM core cycles and 14 scheduling ticks corresponds to ~225 ARM
core cycles.
@@ -463,18 +482,23 @@ When the test completes, determine the difference between the clocks
reported in the two "uptime" response messages. The total number of
commands per second is then `100000 * mcu_frequency / clock_diff`.
Note that this test may saturate the USB/CPU capacity of a Raspberry
Pi. If running on a Raspberry Pi, Beaglebone, or similar host computer
then increase the delay (eg, `DELAY {clock + 20*freq} get_uptime`).
Where applicable, the benchmarks below are with console.py running on
a desktop class machine with the device connected via a high-speed
hub.
The USB tests may exceed the CPU capacity of a Raspberry Pi. If
running on a Raspberry Pi, Beaglebone, or similar host computer then
increase the delay (eg, `DELAY {clock + 20*freq} get_uptime`). Where
applicable, the benchmarks below are with console.py running on a
desktop class machine with the device connected via a super-speed hub.
The CAN bus tests may saturate the USB host controller of a Raspberry
Pi (when testing via a standard gs_usb USB to CAN bus adapter). Where
applicable, the CAN bus benchmarks below are with console.py running
on a desktop class machine with a USB to CAN bus adapter connected via
a super-speed USB hub.
| MCU | Rate | Build | Build compiler |
| ------------------- | ---- | -------- | ------------------- |
| stm32f042 (CAN) | 18K | c105adc8 | arm-none-eabi-gcc (GNU Tools 7-2018-q3-update) 7.3.1 |
| atmega2560 (serial) | 23K | b161a69e | avr-gcc (GCC) 4.8.1 |
| sam3x8e (serial) | 23K | b161a69e | arm-none-eabi-gcc (Fedora 7.1.0-5.fc27) 7.1.0 |
| rp2350 (CAN) | 59K | 17b8ce4c | arm-none-eabi-gcc (Fedora 14.1.0-1.fc40) 14.1.0 |
| at90usb1286 (USB) | 75K | 01d2183f | avr-gcc (GCC) 5.4.0 |
| ar100 (serial) | 138K | 08d037c6 | or1k-linux-musl-gcc 9.3.0 |
| samd21 (USB) | 223K | 01d2183f | arm-none-eabi-gcc (Fedora 7.4.0-1.fc30) 7.4.0 |
+8 -4
View File
@@ -125,10 +125,14 @@ iface can0 can static
frequency. As a result, it is recommended to use a CAN bus frequency
of 1000000 when using "USB to CAN bus bridge mode".
Even at a CAN bus frequency of 1000000, there may not be sufficient
bandwidth to run a `SHAPER_CALIBRATE` test if both the XY steppers
and the accelerometer all communicate via a single "USB to CAN bus"
interface.
* It is only valid to use USB to CAN bridge mode if there is a
functioning CAN bus with at least one other node available (in
addition to the bridge node itself). Use a standard USB
configuration if the goal is to communicate only with the single USB
device. Using USB to CAN bridge mode without a fully functioning CAN
bus (including terminating resistors and an additional node) may
result in sporadic errors even when communicating with the bridge
node.
* A USB to CAN bridge board will not appear as a USB serial device, it
will not show up when running `ls /dev/serial/by-id`, and it can not
+17
View File
@@ -118,6 +118,23 @@ necessary to increase the `txqueuelen` above the recommended value
of 128. However, as above, care should be taken when selecting a new
value to avoid excessive round-trip-time latency.
## Use `canbus_query.py` only to identify nodes never previously seen
It is only valid to use the
[`canbus_query.py` tool](CANBUS.md#finding-the-canbus_uuid-for-new-micro-controllers)
to identify micro-controllers that have never been previously
identified. Once all nodes on a bus are identified, record the
resulting uuids in the printer.cfg, and avoid running the tool
unnecessarily.
The tool is implemented using a low-level mechanism that can cause
nodes to internally observe bus errors. These internal errors may
result in communication interruptions and may result is some nodes
disconnecting from the bus.
It is not valid to use the tool to "ping" if a node is connected. Do
not run the tool during an active print.
## Obtaining candump logs
The CAN bus messages sent to and from the micro-controller are handled
+5
View File
@@ -286,6 +286,11 @@ The following may also be useful:
during the `load_config()` or "connect event" phases. Use either
`raise config.error("my error")` or `raise printer.config_error("my
error")` to report the error.
* Do not store a reference to the `config` object in a class member
variable (nor in any similar location that may persist past initial
module loading). The `config` object is a reference to a "config
loading phase" class and it is not valid to invoke its methods after
the "config loading phase" has completed.
* Use the "pins" module to configure a pin on a micro-controller. This
is typically done with something similar to
`printer.lookup_object("pins").setup_pin("pwm",
+5
View File
@@ -8,6 +8,11 @@ All dates in this document are approximate.
## Changes
20250428: The maximum `cycle_time` for pwm `[output_pin]`,
`[pwm_cycle_time]`, `[pwm_tool]`, and similar config sections is now 3
seconds (reduced from 5 seconds). The `maximum_mcu_duration` in
`[pwm_tool]` is now also 3 seconds.
20250418: The manual_stepper `STOP_ON_ENDSTOP` feature may now take
less time to complete. Previously, the command would wait the entire
time the move could possibly take even if the endstop triggered
+316 -6
View File
@@ -84,8 +84,9 @@ The printer section controls high level printer settings.
[printer]
kinematics:
# The type of printer in use. This option may be one of: cartesian,
# corexy, corexz, hybrid_corexy, hybrid_corexz, rotary_delta, delta,
# deltesian, polar, winch, or none. This parameter must be specified.
# corexy, corexz, hybrid_corexy, hybrid_corexz, generic_cartesian,
# rotary_delta, delta, deltesian, polar, winch, or none.
# This parameter must be specified.
max_velocity:
# Maximum velocity (in mm/s) of the toolhead (relative to the
# print). This value may be changed at runtime using the
@@ -712,6 +713,172 @@ anchor_z:
# These parameters must be provided.
```
### Generic Cartesian Kinematics
See [example-generic-cartesian.cfg](../config/example-generic-caretesian.cfg)
for an example generic Cartesian kinematics config file.
This printer kinematic class allows a user to define in a pretty flexible
manner an arbitrary Cartesian-style kinematics. In principle, the regular
cartesian, corexy, hybrid_corexy can be defined this way too. However,
more importantly, various otherwise unsupported kinematics such as
inverted hybrid_corexy or corexyuv can be defined using this kinematic.
Notably, the definition of a generic Cartesian kinematic deviates
significantly from the other kinematic types. It follows the following
convention: a user defines a set of carriages with certain range of motion
that can move independently from each other (they should move over the
Cartesian axes X, Y, and Z, hence the name of the kinematic) and
corresponding endstops that allow the firmware to determine the position
of carriages during homing, as well as a set of steppers that move those
carriages. The `[printer]` section must specify the kinematic and
other printer-level settings same as the regular Cartesian kinematic:
```
[printer]
kinematics: generic_cartesian
max_velocity:
max_accel:
#minimum_cruise_ratio:
#square_corner_velocity:
#max_accel_to_decel:
#max_z_velocity:
#max_z_accel:
```
Then a user must define the following three carriages: `[carriage x]`,
`[carriage y]`, and `[carriage z]`, e.g.
```
[carriage x]
endstop_pin:
# Endstop switch detection pin. If this endstop pin is on a
# different mcu than the stepper motor(s) moving this carriage,
# then it enables "multi-mcu homing". This parameter must be provided.
#position_min: 0
# Minimum valid distance (in mm) the user may command the carriage to
# move to. The default is 0mm.
position_endstop:
# Location of the endstop (in mm). This parameter must be provided.
position_max:
# Maximum valid distance (in mm) the user may command the stepper to
# move to. This parameter must be provided.
#homing_speed: 5.0
# Maximum velocity (in mm/s) of the carriage when homing. The default
# is 5mm/s.
#homing_retract_dist: 5.0
# Distance to backoff (in mm) before homing a second time during
# homing. Set this to zero to disable the second home. The default
# is 5mm.
#homing_retract_speed:
# Speed to use on the retract move after homing in case this should
# be different from the homing speed, which is the default for this
# parameter
#second_homing_speed:
# Velocity (in mm/s) of the carriage when performing the second home.
# The default is homing_speed/2.
#homing_positive_dir:
# If true, homing will cause the carriage to move in a positive
# direction (away from zero); if false, home towards zero. It is
# better to use the default than to specify this parameter. The
# default is true if position_endstop is near position_max and false
# if near position_min.
```
Afterwards, a user specifies the stepper motors that move these carriages,
for instance
```
[stepper my_stepper]
carriages:
# A string describing the carriages the stepper moves. All defined
# carriages can be specified here, as well as their linear combinations,
# e.g. x, x+y, y-0.5*z, x-z, etc. This parameter must be provided.
step_pin:
dir_pin:
enable_pin:
rotation_distance:
microsteps:
#full_steps_per_rotation: 200
#gear_ratio:
#step_pulse_duration:
```
See [stepper](#stepper) section for more information on the regular
stepper parameters. The `carriages` parameter defines how the stepper
affects the motion of the carriages. For example, `x+y` indicates that
the motion of the stepper in the positive direction by the distance `d`
moves the carriages `x` and `y` by the same distance `d` in the positive
direction, while `x-0.5*y` means the motion of the stepper in the positive
direction by the distance `d` moves the carriage `x` by the distance `d`
in the positive direction, but the carriage `y` will travel distance `d/2`
in the negative direction.
More than a single stepper motor can be defined to drive the same axis
or belt. For example, on a CoreXY AWD setups two motors driving the same
belt can be defined as
```
[carriage x]
endstop_pin: ...
...
[carriage y]
endstop_pin: ...
...
[stepper a0]
carriages: x-y
step_pin: ...
dir_pin: ...
enable_pin: ...
rotation_distance: ...
...
[stepper a1]
carriages: x-y
step_pin: ...
dir_pin: ...
enable_pin: ...
rotation_distance: ...
...
```
with `a0` and `a1` steppers having their own control pins, but
sharing the same `carriages` and corresponding endstops.
There are situations when a user wants to have more than one endstop
per axis. Examples of such configurations include Y axis driven by
two independent stepper motors with belts attached to both ends of the
X beam, with effectively two carriages on Y axis each having an
independent endstop, and multi-stepper Z axis with each stepper having
its own endstop (not to be confused with the configurations with
multiple Z motors but only a single endstop). These configurations
can be declared by specifying additional carriage(s) with their endstops:
```
[extra_carriage my_carriage]
primary_carriage:
# The name of the primary carriage this carriage corresponds to.
# It also effectively defines the axis the carriage moves over.
# This parameter must be provided.
endstop_pin:
# Endstop switch detection pin. This parameter must be provided.
```
and the corresponding stepper motors, for example:
```
[extra_carriage y1]
primary_carriage: y
endstop_pin: ...
[stepper sy1]
carriages: y1
...
```
Notably, an `[extra_carriage]` does not define parameters such as
`position_min`, `position_max`, and `position_endstop`, but instead
inherits them from the specified `primary_carriage`, thus sharing
the same range of motion with the primary carriage.
For the references on how to configure IDEX setups, see the
[dual carriage](#dual-carriage) section.
### None Kinematics
It is possible to define a special "none" kinematics to disable
@@ -2207,8 +2374,8 @@ for an example configuration.
### [dual_carriage]
Support for cartesian and hybrid_corexy/z printers with dual carriages
on a single axis. The carriage mode can be set via the
Support for cartesian, generic_cartesian and hybrid_corexy/z printers with
dual carriages on a single axis. The carriage mode can be set via the
SET_DUAL_CARRIAGE extended g-code command. For example,
"SET_DUAL_CARRIAGE CARRIAGE=1" command will activate the carriage defined
in this section (CARRIAGE=0 will return activation to the primary carriage).
@@ -2235,7 +2402,7 @@ typically be achieved with
or a similar command.
See [sample-idex.cfg](../config/sample-idex.cfg) for an example
configuration.
configuration with a regular Cartesian kinematic.
```
[dual_carriage]
@@ -2249,7 +2416,7 @@ axis:
# error. If safe_distance is not provided, it will be inferred from
# position_min and position_max for the dual and primary carriages. If set
# to 0 (or safe_distance is unset and position_min and position_max are
# identical for the primary and dual carraiges), the carriages proximity
# identical for the primary and dual carriages), the carriages proximity
# checks will be disabled.
#step_pin:
#dir_pin:
@@ -2263,6 +2430,83 @@ axis:
# See the "stepper" section for the definition of the above parameters.
```
For an example of dual carriage configuration with `generic_cartesian`
kinematic, see the following configuration
[sample](../config/example-generic-caretesian.cfg).
Please note that in this case the `[dual_carriage]` configuration deviates
from the configuration described above:
```
[dual_carriage my_dc_carriage]
primary_carriage:
# Defines the matching primary carriage of this dual carriage and
# the corresponding IDEX axis. Valid choices are x, y, z.
# This parameter must be provided.
#safe_distance:
# The minimum distance (in mm) to enforce between the dual and the primary
# carriages. If a G-Code command is executed that will bring the carriages
# closer than the specified limit, such a command will be rejected with an
# error. If safe_distance is not provided, it will be inferred from
# position_min and position_max for the dual and primary carriages. If set
# to 0 (or safe_distance is unset and position_min and position_max are
# identical for the primary and dual carriages), the carriages proximity
# checks will be disabled.
endstop_pin:
#position_min:
position_endstop:
position_max:
#homing_speed:
#homing_retract_dist:
#homing_retract_speed:
#second_homing_speed:
#homing_positive_dir:
...
```
Refer to [generic cartesian](#generic-cartesian) section for more information
on the regular `carriage` parameters.
Then a user must define one or more stepper motors moving the dual carriage
(and other carriages as appropriate), for instance
```
[carriage x]
...
[carriage y]
...
[dual_carriage u]
primary_carriage: x
...
[stepper dc_stepper]
carriages: u-y
...
```
`[dual_carriage]` requires special configuration for the input shaper.
In general, it is necessary to run input shaper calibration twice -
for the `dual_carriage` and its `primary_carriage` for the axis they
share. Then the input shaper can be configured as follows, assuming the
example above:
```
[input_shaper]
# Intentionally empty
[delayed_gcode init_shaper]
initial_duration: 0.1
gcode:
SET_DUAL_CARRIAGE CARRIAGE=u
SET_INPUT_SHAPER SHAPER_TYPE_X=<dual_carriage_x_shaper> SHAPER_FREQ_X=<dual_carriage_x_freq> SHAPER_TYPE_Y=<y_shaper> SHAPER_FREQ_Y=<y_freq>
SET_DUAL_CARRIAGE CARRIAGE=x
SET_INPUT_SHAPER SHAPER_TYPE_X=<primary_carriage_x_shaper> SHAPER_FREQ_X=<primary_carriage_x_freq> SHAPER_TYPE_Y=<y_shaper> SHAPER_FREQ_Y=<y_freq>
```
Note that `SHAPER_TYPE_Y` and `SHAPER_FREQ_Y` must be the same in both
commands in this case, since the same motors drive Y axis when either
of the `x` and `u` carriages are active.
It is worth noting that `generic_cartesian` kinematic can support two
dual carriages for X and Y axes. For reference, see for instance a
[sample](../config/sample-corexyuv.cfg) of CoreXYUV configuration.
### [extruder_stepper]
Support for additional steppers synchronized to the movement of an
@@ -2317,6 +2561,13 @@ printer kinematics.
# Endstop switch detection pin. If specified, then one may perform
# "homing moves" by adding a STOP_ON_ENDSTOP parameter to
# MANUAL_STEPPER movement commands.
#position_min:
#position_max:
# The minimum and maximum position the stepper can be commanded to
# move to. If specified then one may not command the stepper to move
# past the given position. Note that these limits do not prevent
# setting an arbitrary position with the `MANUAL_STEPPER
# SET_POSITION=x` command. The default is to not enforce a limit.
```
## Custom heaters and sensors
@@ -4898,6 +5149,65 @@ data_ready_pin:
# and 'analog_supply'. Default is 'internal'.
```
### [load_cell_probe]
Load Cell Probe. This combines the functionality of a [probe] and a [load_cell].
```
[load_cell_probe]
sensor_type:
# This must be one of the supported bulk ADC sensor types and support
# load cell endstops on the mcu.
#counts_per_gram:
#reference_tare_counts:
#sensor_orientation:
# These parameters must be configured before the probe will operate.
# See the [load_cell] section for further details.
#force_safety_limit: 2000
# The safe limit for probing force relative to the reference_tare_counts on
# the load_cell. The default is +/-2Kg.
#trigger_force: 75.0
# The force that the probe will trigger at. 75g is the default.
#drift_filter_cutoff_frequency: 0.8
# Enable optional continuous taring while homing & probing to reject drift.
# The value is a frequency, in Hz, below which drift will be ignored. This
# option requires the SciPy library. Default: None
#drift_filter_delay: 2
# The delay, or 'order', of the drift filter. This controls the number of
# samples required to make a trigger detection. Can be 1 or 2, the default
# is 2.
#buzz_filter_cutoff_frequency: 100.0
# The value is a frequency, in Hz, above which high frequency noise in the
# load cell will be igfiltered outnored. This option requires the SciPy
# library. Default: None
#buzz_filter_delay: 2
# The delay, or 'order', of the buzz filter. This controle the number of
# samples required to make a trigger detection. Can be 1 or 2, the default
# is 2.
#notch_filter_frequencies: 50, 60
# 1 or 2 frequencies, in Hz, to filter out of the load cell data. This is
# intended to reject power line noise. This option requires the SciPy
# library. Default: None
#notch_filter_quality: 2.0
# Controls how narrow the range of frequencies are that the notch filter
# removes. Larger numbers produce a narrower filter. Minimum value is 0.5 and
# maximum is 3.0. Default: 2.0
#tare_time:
# The rime in seconds used for taring the load_cell before each probe. The
# default value is: 4 / 60 = 0.066. This collects samples from 4 cycles of
# 60Hz mains power to cancel power line noise.
#z_offset:
#speed:
#samples:
#sample_retract_dist:
#lift_speed:
#samples_result:
#samples_tolerance:
#samples_tolerance_retries:
#activate_gcode:
#deactivate_gcode:
# See the "[probe]" section for a description of the above parameters.
```
## Board specific hardware support
### [sx1509]
+2 -1
View File
@@ -190,12 +190,13 @@ represent total number of steps per second on the micro-controller.
| SAM4E8E | 2500K | 1674K |
| SAMD51 | 3077K | 1885K |
| AR100 | 3529K | 2507K |
| STM32G431 | 3617K | 2452K |
| STM32F407 | 3652K | 2459K |
| STM32F446 | 3913K | 2634K |
| RP2040 | 4000K | 2571K |
| RP2350 | 4167K | 2663K |
| SAME70 | 6667K | 4737K |
| STM32H723 | 6667K | 6557K |
| STM32H723 | 7429K | 8619K |
If unsure of the micro-controller on a particular board, find the
appropriate [config file](../config/), and look for the
+110 -12
View File
@@ -174,8 +174,10 @@ The following commands are available when the
[ADAPTIVE_MARGIN=<value>]`: This command probes the bed using generated points
specified by the parameters in the config. After probing, a mesh is generated
and z-movement is adjusted according to the mesh.
The mesh is immediately active after successful completion of `BED_MESH_CALIBRATE`.
The mesh will be saved into a profile specified by the `PROFILE` parameter,
or `default` if unspecified.
or `default` if unspecified. If ADAPTIVE=1 is specified then the profile
name will begin with `adaptive-` and should not be saved for reuse.
See the PROBE command for details on the optional probe parameters. If
METHOD=manual is specified then the manual probing tool is activated - see the
MANUAL_PROBE command above for details on the additional commands available
@@ -341,15 +343,18 @@ The following command is available when the
enabled.
#### SET_DUAL_CARRIAGE
`SET_DUAL_CARRIAGE CARRIAGE=[0|1] [MODE=[PRIMARY|COPY|MIRROR]]`:
`SET_DUAL_CARRIAGE CARRIAGE=<carriage> [MODE=[PRIMARY|COPY|MIRROR]]`:
This command will change the mode of the specified carriage.
If no `MODE` is provided it defaults to `PRIMARY`. Setting the mode
to `PRIMARY` deactivates the other carriage and makes the specified
carriage execute subsequent G-Code commands as-is. `COPY` and `MIRROR`
modes are supported only for `CARRIAGE=1`. When set to either of these
modes, carriage 1 will then track the subsequent moves of the carriage 0
and either copy relative movements of it (in `COPY` mode) or execute them
in the opposite (mirror) direction (in `MIRROR` mode).
If no `MODE` is provided it defaults to `PRIMARY`. `<carriage>` must
reference a defined primary or dual carriage for `generic_cartesian`
kinematics or be 0 (for primary carriage) or 1 (for dual carriage)
for all other kinematics supporting IDEX. Setting the mode to `PRIMARY`
deactivates the other carriage and makes the specified carriage execute
subsequent G-Code commands as-is. `COPY` and `MIRROR` modes are supported
only for dual carriages. When set to either of these modes, dual carriage
will then track the subsequent moves of its primary carriage and either
copy relative movements of it (in `COPY` mode) or execute them in the
opposite (mirror) direction (in `MIRROR` mode).
#### SAVE_DUAL_CARRIAGE_STATE
`SAVE_DUAL_CARRIAGE_STATE [NAME=<state_name>]`: Save the current positions
@@ -715,6 +720,46 @@ is specified then the toolhead move will be performed with the given
speed (in mm/s); otherwise the toolhead move will use the restored
g-code speed.
### [generic_cartesian]
The commands in this section become automatically available when
`kinematics: generic_cartesian` is specified as the printer kinematics.
#### SET_STEPPER_CARRIAGES
`SET_STEPPER_CARRIAGES STEPPER=<stepper_name> CARRIAGES=<carriages>
[DISABLE_CHECKS=[0|1]]`: Set or update the stepper carriages.
`<stepper_name>` must reference an existing stepper defined in `printer.cfg`,
and `<carriages>` describes the carriages the stepper moves. See
[Generic Cartesian Kinematics](Config_Reference.md#generic-cartesian-kinematics)
for a more detailed overview of the `carriages` parameter in the
stepper configuration section. Note that it is only possible
to change the coefficients or signs of the carriages with this
command, but a user cannot add or remove the carriages that the stepper
controls.
`SET_STEPPER_CARRIAGES` is an advanced tool, and the user is advised
to exercise an extreme caution using it, since specifying incorrect
configuration may physically damage the printer.
Note that `SET_STEPPER_CARRIAGES` performs certain internal validations
of the new printer kinematics after the change. Keep in mind that if it
detects an issue, it may leave printer kinematics in an invalid state.
This means that if `SET_STEPPER_CARRIAGES` reports an error, it is unsafe
to issue other GCode commands, and the user must inspect the error message
and either fix the problem, or manually restore the previous stepper(s)
configuration.
Since `SET_STEPPER_CARRIAGES` can update a configuration of a single
stepper at a time, some sequences of changes can lead to invalid
intermediate kinematic configurations, even if the final configuration
is valid. In such cases a user can pass `DISABLE_CHECKS=1` parameters to
all but the last command to disable intermediate checks. For example,
if `stepper a` and `stepper b` initially have `x-y` and `x+y` carriages
correspondingly, then the following sequence of commands will let a user
effectively swap the carriage controls:
`SET_STEPPER_CARRIAGES STEPPER=a CARRIAGES=x+y DISABLE_CHECKS=1`
and `SET_STEPPER_CARRIAGES STEPPER=b CARRIAGES=x-y`, while
still validating the final kinematics state.
### [hall_filament_width_sensor]
The following commands are available when the
@@ -851,9 +896,9 @@ uncalibrated load cells.
`LOAD_CELL_CALIBRATE [LOAD_CELL=<config_name>]`: Start the guided calibration
utility. Calibration is a 3 step process:
1. First you remove all load from the load cell and run the `TARE` command
1. Next you apply a known load to the load cell and run the
2. Next you apply a known load to the load cell and run the
`CALIBRATE GRAMS=nnn` command
1. Finally use the `ACCEPT` command to save the results
3. Finally use the `ACCEPT` command to save the results
You can cancel the calibration process at any time with `ABORT`.
@@ -861,7 +906,8 @@ You can cancel the calibration process at any time with `ABORT`.
`LOAD_CELL_TARE [LOAD_CELL=<config_name>]`: This works just like the tare button
on digital scale. It sets the current raw reading of the load cell to be the
zero point reference value. The response is the percentage of the sensors range
that was read and the raw value in counts.
that was read and the raw value in counts. If the load cell is calibrated a
force in grams is also reported.
### LOAD_CELL_READ load_cell="name"
`LOAD_CELL_READ [LOAD_CELL=<config_name>]`:
@@ -869,6 +915,39 @@ This command takes a reading from the load cell. The response is the percentage
of the sensors range that was read and the raw value in counts. If the load cell
is calibrated a force in grams is also reported.
### [load_cell_probe]
The following commands are enabled if a
[load_cell config section](Config_Reference.md#load_cell_probe) has been
enabled.
### LOAD_CELL_TEST_TAP
`LOAD_CELL_TEST_TAP [TAPS=<taps>] [TIMEOUT=<timeout>]`: Run a testing routine
that reports taps on the load cell. The toolhead will not move but the load cell
probe will sense taps just as if it was probing. This can be used as a
sanity check to make sure that the probe works. This tool replaces
QUERY_ENDSTOPS and QUERY_PROBE for load cell probes.
- `TAPS`: the number of taps the tool expects
- `TIMEOOUT`: the time, in seconds, that the tool waits for each tab before
aborting.
### Load Cell Command Extensions
Commands that perform probes, such as [`PROBE`](#probe),
[`PROBE_ACCURACY`](#probe_accuracy),
[`BED_MESH_CALIBRATE`](#bed_mesh_calibrate) etc. will accept additional
parameters if a `[load_cell_probe]` is defined. The parameters override the
corresponding settings from the
[`[load_cell_probe]`](./Config_Reference.md#load_cell_probe) configuration:
- `FORCE_SAFETY_LIMIT=<grams>`
- `TRIGGER_FORCE=<grams>`
- `DRIFT_FILTER_CUTOFF_FREQUENCY=<frequency_hz>`
- `DRIFT_FILTER_DELAY=<1|2>`
- `BUZZ_FILTER_CUTOFF_FREQUENCY=<frequency_hz>`
- `BUZZ_FILTER_DELAY=<1|2>`
- `NOTCH_FILTER_FREQUENCIES=<list of frequency_hz>`
- `NOTCH_FILTER_QUALITY=<quality>`
- `TARE_TIME=<seconds>`
### [manual_probe]
The manual_probe module is automatically loaded.
@@ -925,6 +1004,25 @@ scheduled to run after the stepper move completes, however if a manual
stepper move uses SYNC=0 then future G-Code movement commands may run
in parallel with the stepper movement.
`MANUAL_STEPPER STEPPER=config_name GCODE_AXIS=[A-Z]
[LIMIT_VELOCITY=<velocity>] [LIMIT_ACCEL=<accel>]
[INSTANTANEOUS_CORNER_VELOCITY=<velocity>]`: If the `GCODE_AXIS`
parameter is specified then it configures the stepper motor as an
extra axis on `G1` move commands. For example, if one were to issue a
`MANUAL_STEPPER ... GCODE_AXIS=R` command then one could issue
commands like `G1 X10 Y20 R30` to move the stepper motor. The
resulting moves will occur synchronously with the associated toolhead
xyz movements. If the motor is associated with a `GCODE_AXIS` then
one may no longer issue movements using the above `MANUAL_STEPPER`
command - one may unregister the stepper with a `MANUAL_STEPPER
... GCODE_AXIS=` command to resume manual control of the motor. The
`LIMIT_VELOCITY` and `LIMIT_ACCEL` parameters allow one to reduce the
speed of `G1` moves if those moves would result in a velocity or
acceleration above the specified limits. The
`INSTANTANEOUS_CORNER_VELOCITY` specifies the maximum instantaneous
velocity change (in mm/s) of the motor during the junction of two
moves (the default is 1mm/s).
### [mcp4018]
The following command is available when a
+19
View File
@@ -139,6 +139,25 @@ print board is not connected with USB to the host, due to some boards
being able to feed power back to the board and stopping a flash from
occurring.
Please note, that most print boards that use SD cards for flash will
implement some kind of flash loop protection for when the sd card is left
in place. There are two common methods:
Filename Change Required (usually "stock" print boards):
These boards require the firmware file to have a different name each
time you flash (for example, firmware1.bin, firmware2.bin, etc.).
If you reuse the same filename, the board may ignore it and not update.
Automatic File Renaming (usually aftermarket print boards:
Other boards allow using the same filename, commonly firmware.bin,
but after flashing, the board renames the file to firmware.cur.
This helps indicate the firmware was successfully flashed and prevents
it from flashing again on the next startup.
Before flashing, make sure to check which behavior your board follows.
For common micro-controllers using Atmega chips, for example the 2560,
the code can be flashed with something
similar to:
+376 -9
View File
@@ -27,26 +27,28 @@ $ LOAD_CELL_DIAGNOSTIC
```
Things you can check with this data:
* The configured sample rate of the sensor should be close to the 'Measured
samples per second' value. If it is not you may have a configuration or wiring
issue.
samples per second' value. If it is not you may have a configuration or wiring
issue.
* 'Saturated samples' should be 0. If you have saturated samples it means the
load sell is seeing more force than it can measure.
load sell is seeing more force than it can measure.
* 'Unique values' should be a large percentage of the 'Samples
Collected' value. If 'Unique values' is 1 it is very likely a wiring issue.
Collected' value. If 'Unique values' is 1 it is very likely a wiring issue.
* Tap or push on the sensor while `LOAD_CELL_DIAGNOSTIC` runs. If
things are working correctly ths should increase the 'Sample range'.
things are working correctly ths should increase the 'Sample range'.
## Calibrating a Load Cell
Load cells are calibrated using the `LOAD_CELL_CALIBRATE` command. This is an
interactive calibration utility that walks you though a 3 step process:
1. First use the `TARE` command to establish the zero force value. This is the
`reference_tare_counts` config value.
`reference_tare_counts` config value.
2. Next you apply a known load or force to the load cell and run the
`CALIBRATE GRAMS=nnn` command. From this the `counts_per_gram` value is
calculated. See [the next section](#applying-a-known-force-or-load) for some
suggestions on how to do this.
`CALIBRATE GRAMS=nnn` command. From this the `counts_per_gram` value is
calculated. See [the next section](#applying-a-known-force-or-load) for some
suggestions on how to do this.
3. Finally, use the `ACCEPT` command to save the results.
You can cancel the calibration process at any time with `ABORT`.
@@ -73,11 +75,13 @@ printer bed or toolhead can tolerate without damage. Do try to use at least 1Kg
of force, most printers should tolerate this without issue.
When calibrating make careful note of the values reported:
```
$ CALIBRATE GRAMS=555
// Calibration value: -2.78% (-59803108), Counts/gram: 73039.78739,
Total capacity: +/- 29.14Kg
```
The `Total capacity` should be close to the theoretical rating of the load cell
based on the sensor's capacity. If it is much larger you could have used a
higher gain setting in the sensor or a more sensitive load cell. This isn't as
@@ -120,3 +124,366 @@ a macro:
```
{% set tare_counts = printer.load_cell.tare_counts %}
```
# Load Cell Probes
## Related Documentation
* [load_cell_probe Config Reference](Config_Reference.md#load_cell_probe)
* [load_cell_probe G-Code Commands](G-Codes.md#load_cell_probe)
* [load_cell_probe Statuc Reference](Status_Reference.md#load_cell_probe)
## Load Cell Probe Safety
Because load cells are a direct nozzle contact probe there is a risk of
damage to your printer if too much force is used. The load cell probing system
includes a number of safety checks that try to keep your machine safe from
excessive force to the toolhead. It's important to understand what they are
and how they work as you can defeat most of them with poorly chosen config
values.
#### Calibration Check
Every time a homing move starts, load_cell_probe checks
that the load_cell is calibrated. If not it will stop the move with an error:
`!! Load Cell not calibrated`.
#### `counts_per_gram`
This setting is used to convert raw sensor counts into grams. All the safety
limits are in gram units for your convenience. If the `counts_per_gram`
setting is not accurate you can easily exceed the safe force on the toolhead.
You should never guess this value. Use `LOAD_CELL_CALIBRATE` to find your load
cells actual `counts_per_gram`.
#### `trigger_force`
This is the force in grams that triggers the endstop to halt the homing move.
When a homing move starts the endstop tares itself with the current reading
from the load cell. `trigger_force` is measured from that tare value. There is
always some overshoot of this value when the probe collides with the bed,
so be conservative. e.g. a setting of 100g could result in 350g of peak force
before the toolhead stops. This overshoot will increase with faster probing
`speed`, a low ADC sample rate or [multi MCU homing](Multi_MCU_Homing.md).
#### `reference_tare_counts`
This is the baseline tare value that is set by `LOAD_CELL_CALIBRATE`.
This value works with `force_safety_limit` to limit the maximum force on the
toolhead.
#### `force_safety_limit`
This is the maximum absolute force, relative to `reference_tare_counts`,
that the probe will allow while homing or probing. If the MCU sees this
force exceeded it will shut down the printer with the error `!! Load cell
endstop: too much force!`. There are a number of ways this can be triggered:
The first risk this protects against is picking too large of a value for
`drift_filter_cutoff_frequency`. This can cause the drift filter to filter out
a probe event and continue the homing move. If this happens the
`force_safety_limit` acts as a backup protection.
The second problem is probing repeatedly in one place. Klipper does not retract
the probe when doing a single `PROBE` command. This can result
in force applied to the toolhead at the end of a probing cycle. Because
external forces can vary greatly between probing locations,
`load_cell_probe` performs a tare before beginning each probe. If you repeat
the `PROBE` command, load_cell_probe will tare the endstop at the current force.
Multiple cycles of this will result in ever-increasing force on the toolhead.
`force_safety_limit` stops this cycle from running out of control.
Another way this run-away can happen is damage to a strain gauge. If the metal
part is permanently bent it wil change the `reference_tare_counts` of the
device. This puts the starting tare value much closer to the limit making it
more likely to be violated. You want to be notified if this is happening
because your hardware has been permanently damaged.
The final way this can be triggered is due to temperature changes. If your
strain gauges are heated their `reference_tare_counts` may be very different
at ambient temperature vs operating temperature. In this case you may need
to increase the `force_safety_limit` to allow for thermal changes.
#### Load Cell Endstop Watchdog Task
When homing the load_cell_endstop starts a task on the MCU to trac
measurements arriving from the sensor. If the sensor fails to send
measurements for 2 sample periods the watchdog will shut down the printer
with an error `!! LoadCell Endstop timed out waiting on ADC data`.
If this happens, the most likely cause is a fault from the ADC. Inadequate
grounding of your printer can be the root cause. The frame, power supply
case and pint bed should all be connected to ground. You may need to ground
the frame in multiple places. Anodized aluminum extrusions do not conduct
electricity well. You might need to sand the area where the grounding wire
is attached to make good electrical contact.
## Load Cell Probe Setup
This section covers the process for commissioning a load cell probe.
### Verify the Load Cell First
A `[load_cell_probe]` is also a `[load_cell]` and G-code commands related to
`[load_cell]` work with `[load_cell_probe]`. Before attempting to use a load
cell probe, follow the directions for
[calibrating the load cell](Load_Cell.md#calibrating-a-load-cell) with
`CALIBRATE_LOAD_CELL` and checking its operation with `LOAD_CELL_DIAGNOSTIC`.
### Verify Probe Operation With LOAD_CELL_TEST_TAP
Use the command `LOAD_CELL_TEST_TAP` to test the operation of the load cell
probe before actually trying to probe with it. This command detects taps,
just like the PROBE command, but it does not move the z axis. By default, it
listens for 3 taps before ending the test. You have 30 seconds to do each
tap, if no taps are detected the command will time out.
If this test fails, check your configuration and `LOAD_CELL_DIAGNOSTIC`
carefully to look for issues.
Load cell probes don't support the `QUERY_ENDSTOPS` or `QUERY_PROBE`
commands. Use `LOAD_CELL_TEST_TAP` for testing functionality before probing.
### Homing Macros
Load cell probe is not an endstop and doesn't support `endstop:
prove:z_virtual_endstop`. For the time being you'll need to configure your z
axis with an MCU pin as its endstop. You won't actually be using the pin but
for the time being you have to configure something.
To home the axis with just the probe you need to set up a custom homing
macro. This requires setting up
[homing_override](Config_Reference.md#homing_override).
Here is a simple macro that can accomplish this. Note that the
`_HOME_Z_FROM_LAST_PROBE` macro has to be separate because of the way macros
work. The sub-call is needed so that the `_HOME_Z_FROM_LAST_PROBE` macro can
see the result of the probe in `printer.probe.last_z_result`.
```gcode
[gcode_macro _HOME_Z_FROM_LAST_PROBE]
gcode:
{% set z_probed = printer.probe.last_z_result %}
{% set z_position = printer.toolhead.position[2] %}
{% set z_actual = z_position - z_probed %}
SET_KINEMATIC_POSITION Z={z_actual}
[gcode_macro _HOME_Z]
gcode:
SET_GCODE_OFFSET Z=0 # load cell probes dont need a Z offset
# position toolhead for homing Z, edit for your printers size
#G90 # absolute move
#G1 Y50 X50 F{5 * 60} # move to X/Y position for homing
# soft home the z axis to its limit so it can be moved:
SET_KINEMATIC_POSITION Z={printer.toolhead.axis_maximum[2]}
# Fast approach and tap
PROBE PROBE_SPEED={5 * 60} # override the speed for faster homing
_HOME_Z_FROM_LAST_PROBE
# lift z to 2mm
G91 # relative move
G1 Z2 F{5 * 60}
# probe at standard speed
PROBE
_HOME_Z_FROM_LAST_PROBE
# lift z to 10mm for clearance
G91 # relative move
G1 Z10 F{5 * 60}
```
### Suggested Probing Temperature
Currently, we suggest keeping the nozzle temperature below the level that causes
the filament to ooze while homing and probing. 140C is a good starting
point. This temperature is also low enough not to scar PEI build surfaces.
Fouling of the nozzle and the print bed due to oozing filament is the #1 source
of probing error with the load cell probe. Klipper does not yet have a universal
way to detect poor quality taps due to filament ooze. The existing code may
decide that a tap is valid when it is of poor quality. Classifying these poor
quality taps is an area of active research.
Klipper also lacks support for re-locating a probe point if the
location has become fouled by filament ooze. Modules like `quad_gantry_level`
will repeatedly probe the same coordinates even if a probe previously failed
there.
Give the above it is strongly suggested not to probe at printing temperatures.
### Hot Nozzle Protection
The Voron project has a great macro for protecting your print surface from the
hot nozzle. See [Voron Tap's
`activate_gcode`](https://github.com/VoronDesign/Voron-Tap/blob/main/config/tap_klipper_instructions.md)
It is highly suggested to add something like this to your config.
### Nozzle Cleaning
Before probing the nozzle should be clean. You could do this manually before
every print. You can also implement a nozzle scrubber and automate the process.
Here is a suggested sequence:
1. Wait for the nozzle to heat up to probing temp (e.g. `M109 S140`)
1. Home the machine (`G28`)
1. Scrub the nozzle on a brush
1. Heat soak the print bed
1. Perform probing tasks: QGL, bed mesh etc.
### Temperature Compensation for Nozzle Growth
If you are probing at a safe temperature, the nozzle will expand after
heating to printing temperatures. This will cause the nozzle to get longer
and closer to the print surface. You can compensate for this with
[[z_thermal_adjust]](Config_Reference.md#z_thermal_adjust). This adjustment will
work across a range of printing
temperatures from PLA to PC.
#### Calculating the `temp_coeff` for `[z_thermal_adjust]`
The easiest way to do this is to measure at 2 different temperatures.
Ideally these should be the upper and lower limits of the printing
temperature range. E.g. 180C and 290C. You can perform a `PROBE_ACCURACY` at
both temperatures and then calculate the difference of the `average z` at both.
The adjustment value is the change in nozzle length divided by the change in
temperature. e.g.
```
temp_coeff = -0.05 / (290 - 180) = -0.00045455
```
The expected result is a negative number. Positive values for `temp_coeff` move
the nozzle closer to the bed and negative values move it further away.
Expect to have to move the nozzle further away as it gets longer when hot.
#### Configure `[z_thermal_adjust]`
Set up z_thermal_adjust to reference the `extruder` as the source of temperature
data. E.g.:
```
[z_thermal_adjust nozzle]
temp_coeff=-0.00045455
sensor_type: temperature_combined
sensor_list: extruder
combination_method: max
min_temp: 0
max_temp: 400
max_z_adjustment: 0.1
```
## Continuous Tare Filters for Toolhead Load Cells
Klipper implements a configurable IIR filter on the MCU to provide continuous
tareing of the load cell while probing. Continuous taring means the 0 value
moves with drift caused by external factors like bowden tubes and thermal
changes. This is aimed at toolhead sensors and moving beds that experience lots
of external forces that change while probing.
### Installing SciPy
The filtering code uses the excellent [SciPy](https://scipy.org/) library to
compute the filter coefficients based on the values your enter into the config.
Pre-compiled SciPi builds are available for Python 3 on 32 bit Raspberry Pi
systems. 32 bit + Python 3 is strongly recommended because it will streamline
your installation experience. It does work with Python 2 but installation can
take 30+ minutes and require installing additional tools.
```bash
~/klippy-env/bin/pip install scipy
```
### Filter Workbench
The filter parameters should be selected based on drift seen on the printer
during normal operation. A Jupyter notebook is provided in scripts,
[filter_workbench.ipynb](../scripts/filter_workbench.ipynb), to perform a
detailed investigation with real captured data and FFTs.
### Filtering Suggestions
For those just trying to get a filter working follow these suggestions:
* The only essential option is `drift_filter_cutoff_frequency`. A conservative
starting value is `0.5`Hz. Prusa shipped the MK4 with a setting of `0.8`Hz and
the XL with `11.2`Hz. This is probably a safe range to experiment with. This
value should be increased only until normal drift due to bowden tube force is
eliminated. Setting this value too high will result in slow triggering and
excess force going through the toolhead.
* Keep `trigger_force` low. The default is `75`g. The drift filter keeps the
internal grams value very close to 0 so a large trigger force is not needed.
* Keep `force_safety_limit` to a conservative value. The default value is 2Kg
and should keep your toolhead safe while experimenting. If you hit this limit
the `drift_filter_cutoff_frequency` value may be too high.
## Suggestions for Load Cell Tool Boards
This section covers suggestions for those developing toolhead boards that want
to support [load_cell_probe]
### ADC Sensor Selection & Board Development Hints
Ideally a sensor would meet these criteria:
* At least 24 bits wide
* Use SPI communications
* Has a pin can be used to indicate sample ready without SPI communications.
This is often called the "data ready" or "DRDY" pin. Checking a pin is much
faster than running an SPI query.
* Has a programmable gain amplifier gain setting of 128. This should eliminate
the need for a separate amplifier.
* Indicates via SPI if the sensor has been reset. Detecting resets avoids
timing errors in homing and using noisy data at startup. It can also help
users
track down wiring and grounding issues.
* A selectable sample rate between 350Hz and 2Khz. Very high sample rates don't
turn out to be beneficial in our 3D printers because they produce so much
noise
when moving fast. Sample rates below 250Hz will require slower probing speeds.
They also increase the force on the toolhead due to longer delays between
measurements. E.g. a 500Hz sensor moving at 5mm/s has the same safety factor
as
a 100Hz sensor moving at only 1mm/s.
* If designing for under-bed applications, and you want to sense multiple load
cells, use a chip that can sample all of its inputs simultaneously. Multiplex
ADCs that require switching channels have a settling of several samples after
each channel switch making them unsuitable for probing applications.
Implementing support for a new sensor chip is not particularly difficult with
Klipper's `bulk_sensor` and `load_cell_endstop` infrastructure.
### 5V Power Filtering
It is strongly suggested to use larger capacitors than specified by the ADC chip
manufacturer. ADC chips are usually targeted at low noise environments, like
battery powered devices. Sensor manufacturers suggested application notes
generally assume a quiet power supply. Treat their suggested capacitor values as
minimums.
3D printers put huge amounts of noise onto the 5V bus and this can ruin the
sensor's accuracy. Test the sensor on the board with a typical 3D printer power
supply and active stepper drivers before deciding on smoothing capacitor sizes.
### Grounding & Ground Planes
Analog ADC chips contain components that are very vulnerable to noise and
ESD. A large ground plane on the first board layer under the chip can help with
noise. Keep the chip away from power sections and DC to DC converters. The board
should have proper grounding back to the DC supply.
### HX711 and HX717 Notes
This sensor is popular because of its low cost and availability in the
supply chain. However, this is a sensor with some drawbacks:
* The HX71x sensors use bit-bang communication which has a high overhead on the
MCU. Using a sensor that communicates via SPI would save resources on the tool
board's CPU.
* The HX71x lacks a way to communicate reset events to the MCU. Klipper detects
resets with a timing heuristic but this is not ideal. Resets indicate a
problem with wiring or grounding.
* For probing applications the HX717 version is strongly preferred because
of its higher sample rate (320 vs 80). Probing speed on the HX711 should be
limited to less than 2mm/s.
* The sample rate on the HX71x cannot be set from klipper's config. If you have
the 10SPS version of the sensor (which is widely distributed) it needs to
be physically re-wired to run at 80SPS.
+15
View File
@@ -316,6 +316,15 @@ The following information is available for each `[load_cell name]`:
- 'min_force_g': The minimum force in grams, over the last polling period.
- 'max_force_g': The maximum force in grams, over the last polling period.
## load_cell_probe
The following information is available for `[load_cell_probe]`:
- all items from [load_cell](Status_Reference.md#load_cell)
- all items from [probe](Status_Reference.md#probe)
- 'endstop_tare_counts': the load cell probe keeps a tare value independent of
the load cell. This re-set at the start of each probe.
- 'last_trigger_time': timestamp of the last homing trigger
## manual_probe
The following information is available in the
@@ -570,6 +579,12 @@ on a cartesian, hybrid_corexy or hybrid_corexz robot
- `carriage_1`: The mode of the carriage 1. Possible values are:
"INACTIVE", "PRIMARY", "COPY", and "MIRROR".
On a `generic_cartesian` kinematic, the following information is
available in `dual_carriage`:
- `carriages["<carriage>"]`: The mode of the carriage `<carriage>`. Possible
values are "INACTIVE" and "PRIMARY" for the primary carriage and "INACTIVE",
"PRIMARY", "COPY", and "MIRROR" for the dual carriage.
## virtual_sdcard
The following information is available in the
+5 -7
View File
@@ -8,14 +8,12 @@ title: Welcome
The Klipper firmware controls 3d-Printers. It combines the power of a
general purpose computer with one or more micro-controllers. See the
[features document](https://www.klipper3d.org/Features.html) for more
information on why you should use the Klipper software.
[features document](Features.md) for more information on why you
should use the Klipper software.
Start by [installing Klipper software](https://www.klipper3d.org/Installation.html).
Start by [installing Klipper software](Installation.md).
Klipper software is Free Software. Read the
[documentation](https://www.klipper3d.org/Overview.html), see the
[license](COPYING), or
[documentation](Overview.md), see the [license](../COPYING), or
[download](https://github.com/Klipper3d/Klipper) the software. We
depend on the generous support from our
[sponsors](https://www.klipper3d.org/Sponsors.html).
depend on the generous support from our [sponsors](Sponsors.md).
+9 -1
View File
@@ -21,7 +21,7 @@ SOURCE_FILES = [
'pollreactor.c', 'msgblock.c', 'trdispatch.c',
'kin_cartesian.c', 'kin_corexy.c', 'kin_corexz.c', 'kin_delta.c',
'kin_deltesian.c', 'kin_polar.c', 'kin_rotary_delta.c', 'kin_winch.c',
'kin_extruder.c', 'kin_shaper.c', 'kin_idex.c',
'kin_extruder.c', 'kin_shaper.c', 'kin_idex.c', 'kin_generic.c'
]
DEST_LIB = "c_helper.so"
OTHER_FILES = [
@@ -106,6 +106,12 @@ defs_trapq = """
defs_kin_cartesian = """
struct stepper_kinematics *cartesian_stepper_alloc(char axis);
"""
defs_kin_generic_cartesian = """
struct stepper_kinematics *generic_cartesian_stepper_alloc(double a_x
, double a_y, double a_z);
void generic_cartesian_stepper_set_coeffs(struct stepper_kinematics *sk
, double a_x, double a_y, double a_z);
"""
defs_kin_corexy = """
struct stepper_kinematics *corexy_stepper_alloc(char type);
@@ -154,6 +160,7 @@ defs_kin_shaper = """
, int n, double a[], double t[]);
int input_shaper_set_sk(struct stepper_kinematics *sk
, struct stepper_kinematics *orig_sk);
void input_shaper_update_sk(struct stepper_kinematics *sk);
struct stepper_kinematics * input_shaper_alloc(void);
"""
@@ -224,6 +231,7 @@ defs_all = [
defs_kin_cartesian, defs_kin_corexy, defs_kin_corexz, defs_kin_delta,
defs_kin_deltesian, defs_kin_polar, defs_kin_rotary_delta, defs_kin_winch,
defs_kin_extruder, defs_kin_shaper, defs_kin_idex,
defs_kin_generic_cartesian,
]
# Update filenames to an absolute path
+52
View File
@@ -0,0 +1,52 @@
// Generic cartesian kinematics stepper position calculation
//
// Copyright (C) 2024 Dmitry Butyugin <dmbutyugin@google.com>
//
// This file may be distributed under the terms of the GNU GPLv3 license.
#include <stddef.h> // offsetof
#include <stdlib.h> // malloc
#include <string.h> // memset
#include "compiler.h" // __visible
#include "itersolve.h" // struct stepper_kinematics
#include "trapq.h" // move_get_coord
struct generic_cartesian_stepper {
struct stepper_kinematics sk;
struct coord a;
};
static double
generic_cartesian_stepper_calc_position(struct stepper_kinematics *sk
, struct move *m, double move_time)
{
struct generic_cartesian_stepper *cs = container_of(
sk, struct generic_cartesian_stepper, sk);
struct coord c = move_get_coord(m, move_time);
return cs->a.x * c.x + cs->a.y * c.y + cs->a.z * c.z;
}
void __visible
generic_cartesian_stepper_set_coeffs(struct stepper_kinematics *sk
, double a_x, double a_y, double a_z)
{
struct generic_cartesian_stepper *cs = container_of(
sk, struct generic_cartesian_stepper, sk);
cs->a.x = a_x;
cs->a.y = a_y;
cs->a.z = a_z;
cs->sk.active_flags = 0;
if (a_x) cs->sk.active_flags |= AF_X;
if (a_y) cs->sk.active_flags |= AF_Y;
if (a_z) cs->sk.active_flags |= AF_Z;
}
struct stepper_kinematics * __visible
generic_cartesian_stepper_alloc(double a_x, double a_y, double a_z)
{
struct generic_cartesian_stepper *cs = malloc(sizeof(*cs));
memset(cs, 0, sizeof(*cs));
cs->sk.calc_position_cb = generic_cartesian_stepper_calc_position;
generic_cartesian_stepper_set_coeffs(&cs->sk, a_x, a_y, a_z);
return &cs->sk;
}
+1
View File
@@ -77,5 +77,6 @@ dual_carriage_alloc(void)
struct dual_carriage_stepper *dc = malloc(sizeof(*dc));
memset(dc, 0, sizeof(*dc));
dc->m.move_t = 2. * DUMMY_T;
dc->x_scale = dc->y_scale = 1.0;
return &dc->sk;
}
+32 -18
View File
@@ -166,6 +166,38 @@ shaper_commanded_pos_post_fixup(struct stepper_kinematics *sk)
sk->commanded_pos = is->orig_sk->commanded_pos;
}
static void
shaper_note_generation_time(struct input_shaper *is)
{
double pre_active = 0., post_active = 0.;
if ((is->sk.active_flags & AF_X) && is->sx.num_pulses) {
pre_active = is->sx.pulses[is->sx.num_pulses-1].t;
post_active = -is->sx.pulses[0].t;
}
if ((is->sk.active_flags & AF_Y) && is->sy.num_pulses) {
pre_active = is->sy.pulses[is->sy.num_pulses-1].t > pre_active
? is->sy.pulses[is->sy.num_pulses-1].t : pre_active;
post_active = -is->sy.pulses[0].t > post_active
? -is->sy.pulses[0].t : post_active;
}
is->sk.gen_steps_pre_active = pre_active;
is->sk.gen_steps_post_active = post_active;
}
void __visible
input_shaper_update_sk(struct stepper_kinematics *sk)
{
struct input_shaper *is = container_of(sk, struct input_shaper, sk);
if ((is->orig_sk->active_flags & (AF_X | AF_Y)) == (AF_X | AF_Y))
is->sk.calc_position_cb = shaper_xy_calc_position;
else if (is->orig_sk->active_flags & AF_X)
is->sk.calc_position_cb = shaper_x_calc_position;
else if (is->orig_sk->active_flags & AF_Y)
is->sk.calc_position_cb = shaper_y_calc_position;
is->sk.active_flags = is->orig_sk->active_flags;
shaper_note_generation_time(is);
}
int __visible
input_shaper_set_sk(struct stepper_kinematics *sk
, struct stepper_kinematics *orig_sk)
@@ -190,24 +222,6 @@ input_shaper_set_sk(struct stepper_kinematics *sk
return 0;
}
static void
shaper_note_generation_time(struct input_shaper *is)
{
double pre_active = 0., post_active = 0.;
if ((is->sk.active_flags & AF_X) && is->sx.num_pulses) {
pre_active = is->sx.pulses[is->sx.num_pulses-1].t;
post_active = -is->sx.pulses[0].t;
}
if ((is->sk.active_flags & AF_Y) && is->sy.num_pulses) {
pre_active = is->sy.pulses[is->sy.num_pulses-1].t > pre_active
? is->sy.pulses[is->sy.num_pulses-1].t : pre_active;
post_active = -is->sy.pulses[0].t > post_active
? -is->sy.pulses[0].t : post_active;
}
is->sk.gen_steps_pre_active = pre_active;
is->sk.gen_steps_post_active = post_active;
}
int __visible
input_shaper_set_shaper_params(struct stepper_kinematics *sk, char axis
, int n, double a[], double t[])
+6
View File
@@ -96,6 +96,7 @@ class ADS1220:
self.printer, self._process_batch, self._start_measurements,
self._finish_measurements, UPDATE_INTERVAL)
# Command Configuration
self.attach_probe_cmd = None
mcu.add_config_cmd(
"config_ads1220 oid=%d spi_oid=%d data_ready_pin=%s"
% (self.oid, self.spi.get_oid(), self.data_ready_pin))
@@ -108,6 +109,8 @@ class ADS1220:
cmdqueue = self.spi.get_command_queue()
self.query_ads1220_cmd = self.mcu.lookup_command(
"query_ads1220 oid=%c rest_ticks=%u", cq=cmdqueue)
self.attach_probe_cmd = self.mcu.lookup_command(
"ads1220_attach_load_cell_probe oid=%c load_cell_probe_oid=%c")
self.ffreader.setup_query_command("query_ads1220_status oid=%c",
oid=self.oid, cq=cmdqueue)
@@ -126,6 +129,9 @@ class ADS1220:
def add_client(self, callback):
self.batch_bulk.add_client(callback)
def attach_load_cell_probe(self, load_cell_probe_oid):
self.attach_probe_cmd.send([self.oid, load_cell_probe_oid])
# Measurement decoding
def _convert_samples(self, samples):
adc_factor = 1. / (1 << 23)
-1
View File
@@ -321,7 +321,6 @@ class ADS1X1X_pin:
def __init__(self, chip, config):
self.mcu = chip.mcu
self.chip = chip
self.config = config
self.invalid_count = 0
+10 -9
View File
@@ -186,7 +186,8 @@ class BedMesh:
self.last_position[2] -= self.fade_target
else:
# return current position minus the current z-adjustment
x, y, z, e = self.toolhead.get_position()
cur_pos = self.toolhead.get_position()
x, y, z = cur_pos[:3]
max_adj = self.z_mesh.calc_z(x, y)
factor = 1.
z_adj = max_adj - self.fade_target
@@ -202,19 +203,19 @@ class BedMesh:
(self.fade_dist - z_adj))
factor = constrain(factor, 0., 1.)
final_z_adj = factor * z_adj + self.fade_target
self.last_position[:] = [x, y, z - final_z_adj, e]
self.last_position[:] = [x, y, z - final_z_adj] + cur_pos[3:]
return list(self.last_position)
def move(self, newpos, speed):
factor = self.get_z_factor(newpos[2])
if self.z_mesh is None or not factor:
# No mesh calibrated, or mesh leveling phased out.
x, y, z, e = newpos
x, y, z = newpos[:3]
if self.log_fade_complete:
self.log_fade_complete = False
logging.info(
"bed_mesh fade complete: Current Z: %.4f fade_target: %.4f "
% (z, self.fade_target))
self.toolhead.move([x, y, z + self.fade_target, e], speed)
self.toolhead.move([x, y, z + self.fade_target] + newpos[3:], speed)
else:
self.splitter.build_move(self.last_position, newpos, factor)
while not self.splitter.traverse_complete:
@@ -1273,7 +1274,7 @@ class MoveSplitter:
self.z_offset = self._calc_z_offset(prev_pos)
self.traverse_complete = False
self.distance_checked = 0.
axes_d = [self.next_pos[i] - self.prev_pos[i] for i in range(4)]
axes_d = [np - pp for np, pp in zip(self.next_pos, self.prev_pos)]
self.total_move_length = math.sqrt(sum([d*d for d in axes_d[:3]]))
self.axis_move = [not isclose(d, 0., abs_tol=1e-10) for d in axes_d]
def _calc_z_offset(self, pos):
@@ -1286,7 +1287,7 @@ class MoveSplitter:
raise self.gcode.error(
"bed_mesh: Slice distance is negative "
"or greater than entire move length")
for i in range(4):
for i in range(len(self.next_pos)):
if self.axis_move[i]:
self.current_pos[i] = lerp(
t, self.prev_pos[i], self.next_pos[i])
@@ -1301,9 +1302,9 @@ class MoveSplitter:
next_z = self._calc_z_offset(self.current_pos)
if abs(next_z - self.z_offset) >= self.split_delta_z:
self.z_offset = next_z
return self.current_pos[0], self.current_pos[1], \
self.current_pos[2] + self.z_offset, \
self.current_pos[3]
newpos = list(self.current_pos)
newpos[2] += self.z_offset
return newpos
# end of move reached
self.current_pos[:] = self.next_pos
self.z_offset = self._calc_z_offset(self.current_pos)
+7 -5
View File
@@ -24,12 +24,14 @@ class BedTilt:
def handle_connect(self):
self.toolhead = self.printer.lookup_object('toolhead')
def get_position(self):
x, y, z, e = self.toolhead.get_position()
return [x, y, z - x*self.x_adjust - y*self.y_adjust - self.z_adjust, e]
pos = self.toolhead.get_position()
x, y, z = pos[:3]
z -= x*self.x_adjust + y*self.y_adjust + self.z_adjust
return [x, y, z] + pos[3:]
def move(self, newpos, speed):
x, y, z, e = newpos
self.toolhead.move([x, y, z + x*self.x_adjust + y*self.y_adjust
+ self.z_adjust, e], speed)
x, y, z = newpos[:3]
z += x*self.x_adjust + y*self.y_adjust + self.z_adjust
self.toolhead.move([x, y, z] + newpos[3:], speed)
def update_adjust(self, x_adjust, y_adjust, z_adjust):
self.x_adjust = x_adjust
self.y_adjust = y_adjust
+2 -2
View File
@@ -52,7 +52,7 @@ class PhaseCalc:
class EndstopPhase:
def __init__(self, config):
self.printer = config.get_printer()
self.name = config.get_name().split()[1]
self.name = " ".join(config.get_name().split()[1:])
# Obtain step_distance and microsteps from stepper config section
sconfig = config.getsection(self.name)
rotation_dist, steps_per_rotation = stepper.parse_step_distance(sconfig)
@@ -118,7 +118,7 @@ class EndstopPhase:
return delta * self.step_dist
def handle_home_rails_end(self, homing_state, rails):
for rail in rails:
stepper = rail.get_steppers()[0]
stepper = rail.get_endstops()[0][0].get_steppers()[0]
if stepper.get_name() == self.name:
trig_mcu_pos = homing_state.get_trigger_position(self.name)
align = self.align_endstop(rail)
+19 -17
View File
@@ -82,24 +82,25 @@ class ExcludeObject:
self._reset_state()
self._unregister_transform()
def _get_extrusion_offsets(self):
offset = self.extrusion_offsets.get(
self.toolhead.get_extruder().get_name())
def _get_extrusion_offsets(self, num_coord):
ename = self.toolhead.get_extruder().get_name()
offset = self.extrusion_offsets.get(ename)
if offset is None:
offset = [0., 0., 0., 0.]
self.extrusion_offsets[self.toolhead.get_extruder().get_name()] = \
offset
offset = [0.] * num_coord
self.extrusion_offsets[ename] = offset
if len(offset) < num_coord:
offset.extend([0.] * (len(num_coord) - len(offset)))
return offset
def get_position(self):
offset = self._get_extrusion_offsets()
pos = self.next_transform.get_position()
for i in range(4):
offset = self._get_extrusion_offsets(len(pos))
for i in range(len(pos)):
self.last_position[i] = pos[i] + offset[i]
return list(self.last_position)
def _normal_move(self, newpos, speed):
offset = self._get_extrusion_offsets()
offset = self._get_extrusion_offsets(len(newpos))
if self.initial_extrusion_moves > 0 and \
self.last_position[3] != newpos[3]:
@@ -122,9 +123,9 @@ class ExcludeObject:
if (offset[0] != 0 or offset[1] != 0) and \
(newpos[0] != self.last_position_excluded[0] or \
newpos[1] != self.last_position_excluded[1]):
offset[0] = 0
offset[1] = 0
offset[2] = 0
for i in range(len(newpos)):
if i != 3:
offset[i] = 0
offset[3] += self.extruder_adj
self.extruder_adj = 0
@@ -137,17 +138,18 @@ class ExcludeObject:
self.extruder_adj = 0
tx_pos = newpos[:]
for i in range(4):
for i in range(len(newpos)):
tx_pos[i] = newpos[i] - offset[i]
self.next_transform.move(tx_pos, speed)
def _ignore_move(self, newpos, speed):
offset = self._get_extrusion_offsets()
for i in range(3):
offset[i] = newpos[i] - self.last_position_extruded[i]
offset = self._get_extrusion_offsets(len(newpos))
for i in range(len(newpos)):
if i != 3:
offset[i] = newpos[i] - self.last_position_extruded[i]
offset[3] = offset[3] + newpos[3] - self.last_position[3]
self.last_position[:] = newpos
self.last_position_excluded[:] =self.last_position
self.last_position_excluded[:] = self.last_position
self.max_position_excluded = max(self.max_position_excluded, newpos[3])
def _move_into_excluded_region(self, newpos, speed):
+1 -1
View File
@@ -142,7 +142,7 @@ class ForceMove:
logging.info("SET_KINEMATIC_POSITION pos=%.3f,%.3f,%.3f"
" set_homed=%s clear_homed=%s",
x, y, z, set_homed_axes, clear_homed_axes)
toolhead.set_position([x, y, z, curpos[3]], homing_axes=set_homed_axes)
toolhead.set_position([x, y, z], homing_axes=set_homed_axes)
toolhead.get_kinematics().clear_homing_state(clear_homed_axes)
def load_config(config):
+2 -2
View File
@@ -178,8 +178,8 @@ class GCodeMacro:
literal = ast.literal_eval(value)
json.dumps(literal, separators=(',', ':'))
except (SyntaxError, TypeError, ValueError) as e:
raise gcmd.error("Unable to parse '%s' as a literal: %s" %
(value, e))
raise gcmd.error("Unable to parse '%s' as a literal: %s in '%s'" %
(value, e, gcmd.get_commandline()))
v = dict(self.variables)
v[variable] = literal
self.variables = v
+31 -17
View File
@@ -1,6 +1,6 @@
# G-Code G1 movement commands (and associated coordinate manipulation)
#
# Copyright (C) 2016-2021 Kevin O'Connor <kevin@koconnor.net>
# Copyright (C) 2016-2025 Kevin O'Connor <kevin@koconnor.net>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import logging
@@ -14,6 +14,8 @@ class GCodeMove:
self.reset_last_position)
printer.register_event_handler("toolhead:manual_move",
self.reset_last_position)
printer.register_event_handler("toolhead:update_extra_axes",
self._update_extra_axes)
printer.register_event_handler("gcode:command_error",
self.reset_last_position)
printer.register_event_handler("extruder:activate_extruder",
@@ -42,6 +44,7 @@ class GCodeMove:
self.base_position = [0.0, 0.0, 0.0, 0.0]
self.last_position = [0.0, 0.0, 0.0, 0.0]
self.homing_position = [0.0, 0.0, 0.0, 0.0]
self.axis_map = {'X':0, 'Y': 1, 'Z': 2, 'E': 3}
self.speed = 25.
self.speed_factor = 1. / 60.
self.extrude_factor = 1.
@@ -102,35 +105,46 @@ class GCodeMove:
'extrude_factor': self.extrude_factor,
'absolute_coordinates': self.absolute_coord,
'absolute_extrude': self.absolute_extrude,
'homing_origin': self.Coord(*self.homing_position),
'position': self.Coord(*self.last_position),
'gcode_position': self.Coord(*move_position),
'homing_origin': self.Coord(*self.homing_position[:4]),
'position': self.Coord(*self.last_position[:4]),
'gcode_position': self.Coord(*move_position[:4]),
}
def reset_last_position(self):
if self.is_printer_ready:
self.last_position = self.position_with_transform()
def _update_extra_axes(self):
toolhead = self.printer.lookup_object('toolhead')
axis_map = {'X':0, 'Y': 1, 'Z': 2, 'E': 3}
extra_axes = toolhead.get_extra_axes()
for index, ea in enumerate(extra_axes):
if ea is None:
continue
gcode_id = ea.get_axis_gcode_id()
if gcode_id is None or gcode_id in axis_map or gcode_id in "FN":
continue
axis_map[gcode_id] = index
self.axis_map = axis_map
self.base_position[4:] = [0.] * (len(extra_axes) - 4)
self.reset_last_position()
# G-Code movement commands
def cmd_G1(self, gcmd):
# Move
params = gcmd.get_command_parameters()
try:
for pos, axis in enumerate('XYZ'):
for axis, pos in self.axis_map.items():
if axis in params:
v = float(params[axis])
if not self.absolute_coord:
absolute_coord = self.absolute_coord
if axis == 'E':
v *= self.extrude_factor
if not self.absolute_extrude:
absolute_coord = False
if not absolute_coord:
# value relative to position of last move
self.last_position[pos] += v
else:
# value relative to base coordinate position
self.last_position[pos] = v + self.base_position[pos]
if 'E' in params:
v = float(params['E']) * self.extrude_factor
if not self.absolute_coord or not self.absolute_extrude:
# value relative to position of last move
self.last_position[3] += v
else:
# value relative to base coordinate position
self.last_position[3] = v + self.base_position[3]
if 'F' in params:
gcode_speed = float(params['F'])
if gcode_speed <= 0.:
@@ -169,7 +183,7 @@ class GCodeMove:
offset *= self.extrude_factor
self.base_position[i] = self.last_position[i] - offset
if offsets == [None, None, None, None]:
self.base_position = list(self.last_position)
self.base_position[:4] = self.last_position[:4]
def cmd_M114(self, gcmd):
# Get Current Position
p = self._get_gcode_position()
@@ -227,7 +241,7 @@ class GCodeMove:
# Restore state
self.absolute_coord = state['absolute_coord']
self.absolute_extrude = state['absolute_extrude']
self.base_position = list(state['base_position'])
self.base_position[:4] = state['base_position'][:4]
self.homing_position = list(state['homing_position'])
self.speed = state['speed']
self.speed_factor = state['speed_factor']
@@ -255,7 +269,7 @@ class GCodeMove:
kinfo = zip("XYZ", kin.calc_position(dict(cinfo)))
kin_pos = " ".join(["%s:%.6f" % (a, v) for a, v in kinfo])
toolhead_pos = " ".join(["%s:%.6f" % (a, v) for a, v in zip(
"XYZE", toolhead.get_position())])
"XYZE", toolhead.get_position()[:4])])
gcode_pos = " ".join(["%s:%.6f" % (a, v)
for a, v in zip("XYZE", self.last_position)])
base_pos = " ".join(["%s:%.6f" % (a, v)
+2 -2
View File
@@ -1,6 +1,6 @@
# Tracking of PWM controlled heaters and their temperature control
#
# Copyright (C) 2016-2020 Kevin O'Connor <kevin@koconnor.net>
# Copyright (C) 2016-2025 Kevin O'Connor <kevin@koconnor.net>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import os, logging, threading
@@ -11,7 +11,7 @@ import os, logging, threading
######################################################################
KELVIN_TO_CELSIUS = -273.15
MAX_HEAT_TIME = 5.0
MAX_HEAT_TIME = 3.0
AMBIENT_TEMP = 25.
PID_PARAM_BASE = 255.
MAX_MAINTHREAD_TIME = 5.0
+8 -2
View File
@@ -45,7 +45,7 @@ class StepperPosition:
class HomingMove:
def __init__(self, printer, endstops, toolhead=None):
self.printer = printer
self.endstops = endstops
self.endstops = [es for es in endstops if es[0].get_steppers()]
if toolhead is None:
toolhead = printer.lookup_object('toolhead')
self.toolhead = toolhead
@@ -71,7 +71,9 @@ class HomingMove:
sname = stepper.get_name()
kin_spos[sname] += offsets.get(sname, 0) * stepper.get_step_dist()
thpos = self.toolhead.get_position()
return list(kin.calc_position(kin_spos))[:3] + thpos[3:]
cpos = kin.calc_position(kin_spos)
return [cp if cp is not None else tp
for cp, tp in zip(cpos, thpos[:3])] + thpos[3:]
def homing_move(self, movepos, speed, probe_pos=False,
triggered=True, check_triggered=True):
# Notify start of homing/probing move
@@ -233,6 +235,10 @@ class Homing:
for s in kin.get_steppers()}
newpos = kin.calc_position(kin_spos)
for axis in force_axes:
if newpos[axis] is None:
raise self.printer.command_error(
"Cannot determine position of toolhead on "
"axis %s after homing" % "xyz"[axis])
homepos[axis] = newpos[axis]
self.toolhead.set_position(homepos)
+22 -16
View File
@@ -15,7 +15,7 @@ from . import bus
# Si7013 - Untested
# Si7020 - Untested
# Si7021 - Tested on Pico MCU
# SHT21 - Untested
# SHT21 - Tested on Linux MCU.
#
######################################################################
@@ -34,7 +34,7 @@ HTU21D_COMMANDS = {
}
HTU21D_RESOLUTION_MASK = 0x7E;
HTU21D_RESOLUTION_MASK = 0x7E
HTU21D_RESOLUTIONS = {
'TEMP14_HUM12':int('00000000',2),
'TEMP13_HUM10':int('10000000',2),
@@ -42,31 +42,40 @@ HTU21D_RESOLUTIONS = {
'TEMP11_HUM11':int('10000001',2)
}
ID_MAP = {
0x0D: 'SI7013',
0x14: 'SI7020',
0x15: 'SI7021',
0x31: 'SHT21',
0x01: 'SHT21',
0x32: 'HTU21D',
}
# Device with conversion time for tmp/resolution bit
# The format is:
# <CHIPNAME>:{id:<ID>, ..<RESOlUTION>:[<temp time>,<humidity time>].. }
HTU21D_DEVICES = {
'SI7013':{'id':0x0D,
'SI7013':{
'TEMP14_HUM12':[.11,.12],
'TEMP13_HUM10':[ .7, .5],
'TEMP12_HUM08':[ .4, .4],
'TEMP11_HUM11':[ .3, .7]},
'SI7020':{'id':0x14,
'SI7020':{
'TEMP14_HUM12':[.11,.12],
'TEMP13_HUM10':[ .7, .5],
'TEMP12_HUM08':[ .4, .4],
'TEMP11_HUM11':[ .3, .7]},
'SI7021':{'id':0x15,
'SI7021':{
'TEMP14_HUM12':[.11,.12],
'TEMP13_HUM10':[ .7, .5],
'TEMP12_HUM08':[ .4, .4],
'TEMP11_HUM11':[ .3, .7]},
'SHT21': {'id':0x31,
'SHT21': {
'TEMP14_HUM12':[.85,.29],
'TEMP13_HUM10':[.43, .9],
'TEMP12_HUM08':[.22, .4],
'TEMP11_HUM11':[.11,.15]},
'HTU21D':{'id':0x32,
'HTU21D':{
'TEMP14_HUM12':[.50,.16],
'TEMP13_HUM10':[.25, .5],
'TEMP12_HUM08':[.13, .3],
@@ -128,19 +137,16 @@ class HTU21D:
if self._chekCRC8(rdevId) != checksum:
logging.warning("htu21d: Reading deviceId !Checksum error!")
rdevId = rdevId >> 8
deviceId_list = list(
filter(
lambda elem: HTU21D_DEVICES[elem]['id'] == rdevId,HTU21D_DEVICES)
)
if len(deviceId_list) != 0:
logging.info("htu21d: Found Device Type %s" % deviceId_list[0])
guess_dev = ID_MAP.get(rdevId, "Unknown")
if guess_dev == self.deviceId:
logging.info("htu21d: Found Device Type %s" % guess_dev)
else:
logging.warning("htu21d: Unknown Device ID %#x " % rdevId)
if self.deviceId != deviceId_list[0]:
if self.deviceId != guess_dev:
logging.warning(
"htu21d: Found device %s. Forcing to type %s as config.",
deviceId_list[0],self.deviceId)
"htu21d: Found device %s. Forcing to type %s as config." %
(guess_dev, self.deviceId))
# Set Resolution
params = self.i2c.i2c_read([HTU21D_COMMANDS['READ']], 1)
+7
View File
@@ -53,6 +53,7 @@ class HX71xBase:
self._finish_measurements, UPDATE_INTERVAL)
# Command Configuration
self.query_hx71x_cmd = None
self.attach_probe_cmd = None
mcu.add_config_cmd(
"config_hx71x oid=%d gain_channel=%d dout_pin=%s sclk_pin=%s"
% (self.oid, self.gain_channel, self.dout_pin, self.sclk_pin))
@@ -64,10 +65,13 @@ class HX71xBase:
def _build_config(self):
self.query_hx71x_cmd = self.mcu.lookup_command(
"query_hx71x oid=%c rest_ticks=%u")
self.attach_probe_cmd = self.mcu.lookup_command(
"hx71x_attach_load_cell_probe oid=%c load_cell_probe_oid=%c")
self.ffreader.setup_query_command("query_hx71x_status oid=%c",
oid=self.oid,
cq=self.mcu.alloc_command_queue())
def get_mcu(self):
return self.mcu
@@ -83,6 +87,9 @@ class HX71xBase:
def add_client(self, callback):
self.batch_bulk.add_client(callback)
def attach_load_cell_probe(self, load_cell_probe_oid):
self.attach_probe_cmd.send([self.oid, load_cell_probe_oid])
# Measurement decoding
def _convert_samples(self, samples):
adc_factor = 1. / (1 << 23)
+33 -4
View File
@@ -69,6 +69,8 @@ class AxisInputShaper:
ffi_lib.input_shaper_set_shaper_params(
sk, self.axis.encode(), self.n, self.A, self.T)
return success
def is_enabled(self):
return self.n > 0
def disable_shaping(self):
if self.saved is None and self.n:
self.saved = (self.n, self.A, self.T)
@@ -89,6 +91,8 @@ class InputShaper:
def __init__(self, config):
self.printer = config.get_printer()
self.printer.register_event_handler("klippy:connect", self.connect)
self.printer.register_event_handler("dual_carriage:update_kinematics",
self._update_kinematics)
self.toolhead = None
self.shapers = [AxisInputShaper('x', config),
AxisInputShaper('y', config)]
@@ -103,17 +107,23 @@ class InputShaper:
return self.shapers
def connect(self):
self.toolhead = self.printer.lookup_object("toolhead")
dual_carriage = self.printer.lookup_object('dual_carriage', None)
if dual_carriage is not None:
for shaper in self.shapers:
if shaper.is_enabled():
raise self.printer.config_error(
'Input shaper parameters cannot be configured via'
' [input_shaper] section with dual_carriage(s) '
' enabled. Refer to Klipper documentation on how '
' to configure input shaper for dual_carriage(s).')
return
# Configure initial values
self._update_input_shaping(error=self.printer.config_error)
def _get_input_shaper_stepper_kinematics(self, stepper):
# Lookup stepper kinematics
sk = stepper.get_stepper_kinematics()
if sk in self.orig_stepper_kinematics:
# Already processed this stepper kinematics unsuccessfully
return None
if sk in self.input_shaper_stepper_kinematics:
return sk
self.orig_stepper_kinematics.append(sk)
ffi_main, ffi_lib = chelper.get_ffi()
is_sk = ffi_main.gc(ffi_lib.input_shaper_alloc(), ffi_lib.free)
stepper.set_stepper_kinematics(is_sk)
@@ -121,8 +131,27 @@ class InputShaper:
if res < 0:
stepper.set_stepper_kinematics(sk)
return None
self.orig_stepper_kinematics.append(sk)
self.input_shaper_stepper_kinematics.append(is_sk)
return is_sk
def _update_kinematics(self):
if self.toolhead is None:
# Klipper initialization is not yet completed
return
ffi_main, ffi_lib = chelper.get_ffi()
kin = self.toolhead.get_kinematics()
for s in kin.get_steppers():
if s.get_trapq() is None:
continue
is_sk = self._get_input_shaper_stepper_kinematics(s)
if is_sk is None:
continue
old_delay = ffi_lib.input_shaper_get_step_generation_window(is_sk)
ffi_lib.input_shaper_update_sk(is_sk)
new_delay = ffi_lib.input_shaper_get_step_generation_window(is_sk)
if old_delay != new_delay:
self.toolhead.note_step_generation_scan_time(new_delay,
old_delay)
def _update_input_shaping(self, error=None):
self.toolhead.flush_step_generation()
ffi_main, ffi_lib = chelper.get_ffi()
+7 -8
View File
@@ -1,6 +1,6 @@
# Support for PWM driven LEDs
#
# Copyright (C) 2019-2024 Kevin O'Connor <kevin@koconnor.net>
# Copyright (C) 2019-2025 Kevin O'Connor <kevin@koconnor.net>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import logging
@@ -97,17 +97,15 @@ class LEDHelper:
for i in range(self.led_count):
set_template(gcmd, self.tcallbacks[i], self._check_transmit)
PIN_MIN_TIME = 0.100
MAX_SCHEDULE_TIME = 5.0
# Handler for PWM controlled LEDs
class PrinterPWMLED:
def __init__(self, config):
self.printer = printer = config.get_printer()
# Configure pwm pins
ppins = printer.lookup_object('pins')
max_duration = printer.lookup_object('mcu').max_nominal_duration()
cycle_time = config.getfloat('cycle_time', 0.010, above=0.,
maxval=MAX_SCHEDULE_TIME)
maxval=max_duration)
hardware_pwm = config.getboolean('hardware_pwm', False)
self.pins = []
for i, name in enumerate(("red", "green", "blue", "white")):
@@ -128,11 +126,12 @@ class PrinterPWMLED:
for idx, mcu_pin in self.pins:
mcu_pin.setup_start_value(color[idx], 0.)
def update_leds(self, led_state, print_time):
mcu = self.pins[0][1].get_mcu()
min_sched_time = mcu.min_schedule_time()
if print_time is None:
eventtime = self.printer.get_reactor().monotonic()
mcu = self.pins[0][1].get_mcu()
print_time = mcu.estimated_print_time(eventtime) + PIN_MIN_TIME
print_time = max(print_time, self.last_print_time + PIN_MIN_TIME)
print_time = mcu.estimated_print_time(eventtime) + min_sched_time
print_time = max(print_time, self.last_print_time + min_sched_time)
color = led_state[0]
for idx, mcu_pin in self.pins:
if self.prev_color[idx] != color[idx]:
+6 -3
View File
@@ -34,7 +34,7 @@ LIS_I2C_ADDR = 0x19
# Right shift for left justified registers.
FREEFALL_ACCEL = 9.80665
LIS2DW_SCALE = FREEFALL_ACCEL * 1.952 / 4
LIS3DH_SCALE = FREEFALL_ACCEL * 3.906 / 16
LIS3DH_SCALE = FREEFALL_ACCEL * 11.718 / 16
BATCH_UPDATES = 0.100
@@ -145,6 +145,9 @@ class LIS2DW:
"This is generally indicative of connection problems\n"
"(e.g. faulty wiring) or a faulty lis2dw chip."
% (dev_id, LIS2DW_DEV_ID))
if self.bus_type == SPI_SERIAL_TYPE:
# Disable I2C
self.set_reg(REG_LIS2DW_CTRL_REG2_ADDR, 0x06)
# Setup chip in requested query rate
# ODR/2, +-16g, low-pass filter, Low-noise abled
self.set_reg(REG_LIS2DW_CTRL_REG6_ADDR, 0x34)
@@ -167,8 +170,8 @@ class LIS2DW:
self.set_reg(REG_LIS2DW_CTRL_REG1_ADDR, 0x97)
# Disable all filtering
self.set_reg(REG_LIS2DW_CTRL_REG2_ADDR, 0)
# Set +-8g, High Resolution mode
self.set_reg(REG_LIS2DW_CTRL_REG4_ADDR, 0x28)
# Set +-16g, High Resolution mode
self.set_reg(REG_LIS2DW_CTRL_REG4_ADDR, 0x38)
# Enable FIFO
self.set_reg(REG_LIS2DW_CTRL_REG5_ADDR, 0x40)
# Stream mode
+658
View File
@@ -0,0 +1,658 @@
# Load Cell Probe
#
# Copyright (C) 2025 Gareth Farrington <gareth@waves.ky>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import logging, math
import mcu
from . import probe, sos_filter, load_cell, hx71x, ads1220
np = None # delay NumPy import until configuration time
# constants for fixed point numbers
Q2_INT_BITS = 2
Q2_FRAC_BITS = (32 - (1 + Q2_INT_BITS))
Q16_INT_BITS = 16
Q16_FRAC_BITS = (32 - (1 + Q16_INT_BITS))
class TapAnalysis:
def __init__(self, samples):
nd_samples = np.asarray(samples, dtype=np.float64)
self.time = nd_samples[:, 0]
self.force = nd_samples[:, 1]
# convert to dictionary for JSON encoder
def to_dict(self):
return {
'time': self.time.tolist(), 'force': self.force.tolist(),
'is_valid': True,
}
# Access a parameter from config or GCode command via a consistent interface
# stores name and constraints to keep things DRY
class ParamHelper:
def __init__(self, config, name, type_name, default=None, minval=None,
maxval=None, above=None, below=None, max_len=None):
self._config_section = config.get_name()
self._config_error = config.error
self.name = name
self._type_name = type_name
self.value = default
self.minval = minval
self.maxval = maxval
self.above = above
self.below = below
self.max_len = max_len
# read from config once
self.value = self.get(config=config)
def _get_name(self, gcmd):
return self.name.upper() if gcmd else self.name
def _validate_float(self, description, error, value, above, below):
above = above or self.above
if above is not None and value <= above:
raise error("%s must be above %s" % (description, above))
below = below or self.below
if below is not None and value >= below:
raise error("%s must be below %s" % (description, below))
# support for validating individual options in a list of floats
def _validate_float_list(self, gcmd, values, above, below):
if gcmd:
description = ("Error on '%s': %s" % (
gcmd.get_commandline(), self._get_name(gcmd)))
error = gcmd.error
else:
description = ("Option '%s' in section '%s'" % (
self._get_name(gcmd), self._config_section))
error = self._config_error
if self.max_len is not None and len(values) > self.max_len:
raise error(
"%s has maximum length %s" % (description, self.max_len))
for value in values:
self._validate_float(description, error, value, above, below)
def _get_int(self, config, gcmd, minval, maxval):
get = gcmd.get_int if gcmd else config.getint
return get(self._get_name(gcmd), self.value, minval or self.minval,
maxval or self.maxval)
def _get_float(self, config, gcmd, minval, maxval, above, below):
get = gcmd.get_float if gcmd else config.getfloat
return get(self._get_name(gcmd), self.value, minval or self.minval,
maxval or self.maxval, above or self.above, below or self.below)
def _get_float_list(self, config, gcmd, above, below):
# this code defaults to the empty list, never return None
default = (self.value or [])
if gcmd:
# if the parameter isn't part of the command, return the default
if not self._get_name(gcmd) in gcmd.get_command_parameters():
return default
# parameter exists, always prefer whatever is in the command
value = gcmd.get(self._get_name(gcmd), default='')
# Return an empty list for empty value
if len(value.strip()) == 0:
return []
try:
float_list = [float(p.strip()) for p in value.split(',')]
except:
raise gcmd.error("Error on '%s': unable to parse %s" % (
gcmd.get_commandline(), value))
else:
float_list = config.getfloatlist(self._get_name(gcmd),
default=default)
if float_list:
self._validate_float_list(gcmd, float_list, above, below)
return float_list
def get(self, gcmd=None, minval=None, maxval=None, above=None, below=None,
config=None):
if config is None and gcmd is None:
return self.value
if self._type_name == 'int':
return self._get_int(config, gcmd, minval, maxval)
elif self._type_name == 'float':
return self._get_float(config, gcmd, minval, maxval, above, below)
else:
return self._get_float_list(config, gcmd, above, below)
def intParamHelper(config, name, default=None, minval=None, maxval=None):
return ParamHelper(config, name, 'int', default, minval=minval,
maxval=maxval)
def floatParamHelper(config, name, default=None, minval=None, maxval=None,
above=None, below=None):
return ParamHelper(config, name, 'float', default, minval=minval,
maxval=maxval, above=above, below=below)
def floatListParamHelper(config, name, default=None, above=None, below=None,
max_len=None):
return ParamHelper(config, name, 'float_list', default, above=above,
below=below, max_len=max_len)
# container for filter parameters
# allows different filter configurations to be compared
class ContinuousTareFilter:
def __init__(self, sps=None, drift=None, drift_delay=None, buzz=None,
buzz_delay=None, notches=None, notch_quality=None):
self.sps = sps
self.drift = drift
self.drift_delay = drift_delay
self.buzz = buzz
self.buzz_delay = buzz_delay
self.notches = notches
self.notch_quality = notch_quality
def __eq__(self, other):
if not isinstance(other, ContinuousTareFilter):
return False
return (
self.sps == other.sps and self.drift == other.drift and
self.drift_delay == other.drift_delay and self.buzz ==
other.buzz and self.buzz_delay == other.buzz_delay and
self.notches == other.notches and self.notch_quality ==
other.notch_quality)
# create a filter design from the parameters
def design_filter(self, error_func):
design = sos_filter.DigitalFilter(self.sps, error_func, self.drift,
self.drift_delay, self.buzz, self.buzz_delay, self.notches,
self.notch_quality)
fixed_filter = sos_filter.FixedPointSosFilter(
design.get_filter_sections(), design.get_initial_state(),
Q2_INT_BITS, Q16_INT_BITS)
return fixed_filter
# Combine ContinuousTareFilter and SosFilter into an easy-to-use class
class ContinuousTareFilterHelper:
def __init__(self, config, sensor, cmd_queue):
self._sensor = sensor
self._sps = self._sensor.get_samples_per_second()
max_filter_frequency = math.floor(self._sps / 2.)
# setup filter parameters
self._drift_param = floatParamHelper(config,
"drift_filter_cutoff_frequency", default=None, minval=0.1,
maxval=20.0)
self._drift_delay_param = intParamHelper(config, "drift_filter_delay",
default=2, minval=1, maxval=2)
self._buzz_param = floatParamHelper(config,
"buzz_filter_cutoff_frequency", default=None,
above=min(80.0, max_filter_frequency - 1.0),
below=max_filter_frequency)
self._buzz_delay_param = intParamHelper(config, "buzz_filter_delay",
default=2, minval=1, maxval=2)
self._notches_param = floatListParamHelper(config,
"notch_filter_frequencies", default=[], above=0.,
below=max_filter_frequency, max_len=2)
self._notch_quality_param = floatParamHelper(config,
"notch_filter_quality", default=2.0, minval=0.5, maxval=6.0)
# filter design specified in the config file, used for defaults
self._config_design = ContinuousTareFilter() # empty filter
self._config_design = self._build_filter()
# filter design currently inside the MCU
self._active_design = self._config_design
self._sos_filter = self._create_filter(
self._active_design.design_filter(config.error), cmd_queue)
def _build_filter(self, gcmd=None):
drift = self._drift_param.get(gcmd)
drift_delay = self._drift_delay_param.get(gcmd)
buzz = self._buzz_param.get(gcmd)
buzz_delay = self._buzz_delay_param.get(gcmd)
# notches must be between drift and buzz:
notches = self._notches_param.get(gcmd, above=drift, below=buzz)
notch_quality = self._notch_quality_param.get(gcmd)
return ContinuousTareFilter(self._sps, drift, drift_delay, buzz,
buzz_delay, notches, notch_quality)
def _create_filter(self, fixed_filter, cmd_queue):
return sos_filter.SosFilter(self._sensor.get_mcu(), cmd_queue,
fixed_filter, 4)
def update_from_command(self, gcmd, cq=None):
gcmd_filter = self._build_filter(gcmd)
# if filters are identical, no change required
if self._active_design == gcmd_filter:
return
# update MCU filter from GCode command
self._sos_filter.change_filter(
self._active_design.design_filter(gcmd.error))
def get_sos_filter(self):
return self._sos_filter
# check results from the collector for errors and raise an exception is found
def check_sensor_errors(results, printer):
samples, errors = results
if errors:
raise printer.command_error("Load cell sensor reported errors while"
" probing: %i errors, %i overflows" % (
errors[0], errors[1]))
return samples
class LoadCellProbeConfigHelper:
def __init__(self, config, load_cell_inst):
self._printer = config.get_printer()
self._load_cell = load_cell_inst
self._sensor = load_cell_inst.get_sensor()
self._rest_time = 1. / float(self._sensor.get_samples_per_second())
# Collect 4 x 60hz power cycles of data to average across power noise
self._tare_time_param = floatParamHelper(config, 'tare_time',
default=4. / 60., minval=0.01, maxval=1.0)
# triggering options
self._trigger_force_param = intParamHelper(config, 'trigger_force',
default=75, minval=10, maxval=250)
self._force_safety_limit_param = intParamHelper(config,
'force_safety_limit', minval=100, maxval=5000, default=2000)
def get_tare_samples(self, gcmd=None):
tare_time = self._tare_time_param.get(gcmd)
sps = self._sensor.get_samples_per_second()
return max(2, math.ceil(tare_time * sps))
def get_trigger_force_grams(self, gcmd=None):
return self._trigger_force_param.get(gcmd)
def get_safety_limit_grams(self, gcmd=None):
return self._force_safety_limit_param.get(gcmd)
def get_rest_time(self):
return self._rest_time
def get_safety_range(self, gcmd=None):
counts_per_gram = self._load_cell.get_counts_per_gram()
# calculate the safety band
zero = self._load_cell.get_reference_tare_counts()
safety_counts = int(counts_per_gram * self.get_safety_limit_grams(gcmd))
safety_min = int(zero - safety_counts)
safety_max = int(zero + safety_counts)
# don't allow a safety range outside the sensor's real range
sensor_min, sensor_max = self._load_cell.get_sensor().get_range()
if safety_min <= sensor_min or safety_max >= sensor_max:
cmd_err = self._printer.command_error
raise cmd_err("Load cell force_safety_limit exceeds sensor range!")
return safety_min, safety_max
# calculate 1/counts_per_gram in Q2 fixed point
def get_grams_per_count(self):
counts_per_gram = self._load_cell.get_counts_per_gram()
# The counts_per_gram could be so large that it becomes 0.0 when
# converted to Q2 format. This would mean the ADC range only measures a
# few grams which seems very unlikely. Treat this as an error:
if counts_per_gram >= 2**Q2_FRAC_BITS:
raise OverflowError("counts_per_gram value is too large to filter")
return sos_filter.to_fixed_32((1. / counts_per_gram), Q2_INT_BITS)
# McuLoadCellProbe is the interface to `load_cell_probe` on the MCU
# This also manages the SosFilter so all commands use one command queue
class McuLoadCellProbe:
WATCHDOG_MAX = 3
ERROR_SAFETY_RANGE = mcu.MCU_trsync.REASON_COMMS_TIMEOUT + 1
ERROR_OVERFLOW = mcu.MCU_trsync.REASON_COMMS_TIMEOUT + 2
ERROR_WATCHDOG = mcu.MCU_trsync.REASON_COMMS_TIMEOUT + 3
def __init__(self, config, load_cell_inst, sos_filter_inst, config_helper,
trigger_dispatch):
self._printer = config.get_printer()
self._load_cell = load_cell_inst
self._sos_filter = sos_filter_inst
self._config_helper = config_helper
self._sensor = load_cell_inst.get_sensor()
self._mcu = self._sensor.get_mcu()
# configure MCU objects
self._dispatch = trigger_dispatch
self._cmd_queue = self._dispatch.get_command_queue()
self._oid = self._mcu.create_oid()
self._config_commands()
self._home_cmd = None
self._query_cmd = None
self._set_range_cmd = None
self._mcu.register_config_callback(self._build_config)
self._printer.register_event_handler("klippy:connect", self._on_connect)
def _config_commands(self):
self._sos_filter.create_filter()
self._mcu.add_config_cmd(
"config_load_cell_probe oid=%d sos_filter_oid=%d" % (
self._oid, self._sos_filter.get_oid()))
def _build_config(self):
# Lookup commands
self._query_cmd = self._mcu.lookup_query_command(
"load_cell_probe_query_state oid=%c",
"load_cell_probe_state oid=%c is_homing_trigger=%c "
"trigger_ticks=%u", oid=self._oid, cq=self._cmd_queue)
self._set_range_cmd = self._mcu.lookup_command(
"load_cell_probe_set_range"
" oid=%c safety_counts_min=%i safety_counts_max=%i tare_counts=%i"
" trigger_grams=%u grams_per_count=%i", cq=self._cmd_queue)
self._home_cmd = self._mcu.lookup_command(
"load_cell_probe_home oid=%c trsync_oid=%c trigger_reason=%c"
" error_reason=%c clock=%u rest_ticks=%u timeout=%u",
cq=self._cmd_queue)
# the sensor data stream is connected on the MCU at the ready event
def _on_connect(self):
self._sensor.attach_load_cell_probe(self._oid)
def get_oid(self):
return self._oid
def get_mcu(self):
return self._mcu
def get_load_cell(self):
return self._load_cell
def get_dispatch(self):
return self._dispatch
def set_endstop_range(self, tare_counts, gcmd=None):
# update the load cell so it reflects the new tare value
self._load_cell.tare(tare_counts)
# update internal tare value
safety_min, safety_max = self._config_helper.get_safety_range(gcmd)
args = [self._oid, safety_min, safety_max, int(tare_counts),
self._config_helper.get_trigger_force_grams(gcmd),
self._config_helper.get_grams_per_count()]
self._set_range_cmd.send(args)
self._sos_filter.reset_filter()
def home_start(self, print_time):
clock = self._mcu.print_time_to_clock(print_time)
rest_time = self._config_helper.get_rest_time()
rest_ticks = self._mcu.seconds_to_clock(rest_time)
self._home_cmd.send([self._oid, self._dispatch.get_oid(),
mcu.MCU_trsync.REASON_ENDSTOP_HIT, self.ERROR_SAFETY_RANGE, clock,
rest_ticks, self.WATCHDOG_MAX], reqclock=clock)
def clear_home(self):
params = self._query_cmd.send([self._oid])
# The time of the first sample that triggered is in "trigger_ticks"
trigger_ticks = self._mcu.clock32_to_clock64(params['trigger_ticks'])
# clear trsync from load_cell_endstop
self._home_cmd.send([self._oid, 0, 0, 0, 0, 0, 0, 0])
return self._mcu.clock_to_print_time(trigger_ticks)
# Execute probing moves using the McuLoadCellProbe
class LoadCellProbingMove:
ERROR_MAP = {
mcu.MCU_trsync.REASON_COMMS_TIMEOUT: "Communication timeout during "
"homing",
McuLoadCellProbe.ERROR_SAFETY_RANGE: "Load Cell Probe Error: load "
"exceeds safety limit",
McuLoadCellProbe.ERROR_OVERFLOW: "Load Cell Probe Error: fixed point "
"math overflow",
McuLoadCellProbe.ERROR_WATCHDOG: "Load Cell Probe Error: timed out "
"waiting for sensor data"
}
def __init__(self, config, mcu_load_cell_probe, param_helper,
continuous_tare_filter_helper, config_helper):
self._printer = config.get_printer()
self._mcu_load_cell_probe = mcu_load_cell_probe
self._param_helper = param_helper
self._continuous_tare_filter_helper = continuous_tare_filter_helper
self._config_helper = config_helper
self._mcu = mcu_load_cell_probe.get_mcu()
self._load_cell = mcu_load_cell_probe.get_load_cell()
self._z_min_position = probe.lookup_minimum_z(config)
self._dispatch = mcu_load_cell_probe.get_dispatch()
probe.LookupZSteppers(config, self._dispatch.add_stepper)
# internal state tracking
self._tare_counts = 0
self._last_trigger_time = 0
def _start_collector(self):
toolhead = self._printer.lookup_object('toolhead')
# homing uses the toolhead last move time which gets special handling
# to significantly buffer print_time if the move queue has drained
print_time = toolhead.get_last_move_time()
collector = self._load_cell.get_collector()
collector.start_collecting(min_time=print_time)
return collector
# pauses for the last move to complete and then
# sets the endstop tare value and range
def _pause_and_tare(self, gcmd):
collector = self._start_collector()
num_samples = self._config_helper.get_tare_samples(gcmd)
# use collect_min collected samples are not wasted
results = collector.collect_min(num_samples)
tare_samples = check_sensor_errors(results, self._printer)
tare_counts = np.average(np.array(tare_samples)[:, 2].astype(float))
# update sos_filter with any gcode parameter changes
self._continuous_tare_filter_helper.update_from_command(gcmd)
self._mcu_load_cell_probe.set_endstop_range(tare_counts, gcmd)
def _home_start(self, print_time):
# start trsync
trigger_completion = self._dispatch.start(print_time)
self._mcu_load_cell_probe.home_start(print_time)
return trigger_completion
def home_start(self, print_time, sample_time, sample_count, rest_time,
triggered=True):
return self._home_start(print_time)
def home_wait(self, home_end_time):
self._dispatch.wait_end(home_end_time)
# trigger has happened, now to find out why...
res = self._dispatch.stop()
# clear the homing state so it stops processing samples
self._last_trigger_time = self._mcu_load_cell_probe.clear_home()
if res >= mcu.MCU_trsync.REASON_COMMS_TIMEOUT:
error = "Load Cell Probe Error: unknown reason code %i" % (res,)
if res in self.ERROR_MAP:
error = self.ERROR_MAP[res]
raise self._printer.command_error(error)
if res != mcu.MCU_trsync.REASON_ENDSTOP_HIT:
return 0.
return self._last_trigger_time
def get_steppers(self):
return self._dispatch.get_steppers()
# Probe towards z_min until the load_cell_probe on the MCU triggers
def probing_move(self, gcmd):
# do not permit probing if the load cell is not calibrated
if not self._load_cell.is_calibrated():
raise self._printer.command_error("Load Cell not calibrated")
# tare the sensor just before probing
self._pause_and_tare(gcmd)
# get params for the homing move
toolhead = self._printer.lookup_object('toolhead')
pos = toolhead.get_position()
pos[2] = self._z_min_position
speed = self._param_helper.get_probe_params(gcmd)['probe_speed']
phoming = self._printer.lookup_object('homing')
# start collector after tare samples are consumed
collector = self._start_collector()
# do homing move
return phoming.probing_move(self, pos, speed), collector
# Wait for the MCU to trigger with no movement
def probing_test(self, gcmd, timeout):
self._pause_and_tare(gcmd)
toolhead = self._printer.lookup_object('toolhead')
print_time = toolhead.get_last_move_time()
self._home_start(print_time)
return self.home_wait(print_time + timeout)
def get_status(self, eventtime):
return {
'tare_counts': self._tare_counts,
'last_trigger_time': self._last_trigger_time,
}
# Perform a single complete tap
class TappingMove:
def __init__(self, config, load_cell_probing_move, config_helper):
self._printer = config.get_printer()
self._load_cell_probing_move = load_cell_probing_move
self._config_helper = config_helper
# track results of the last tap
self._last_result = None
self._is_last_result_valid = False
# webhooks support
self._clients = load_cell.ApiClientHelper(config.get_printer())
name = config.get_name()
header = {"header": ["probe_tap_event"]}
self._clients.add_mux_endpoint("load_cell_probe/dump_taps",
"load_cell_probe", name, header)
# perform a probing move and a pullback move
def run_tap(self, gcmd):
# do the descending move
epos, collector = self._load_cell_probing_move.probing_move(gcmd)
# collect samples from the tap
toolhead = self._printer.lookup_object('toolhead')
toolhead.flush_step_generation()
move_end = toolhead.get_last_move_time()
results = collector.collect_until(move_end)
samples = check_sensor_errors(results, self._printer)
# Analyze the tap data
ppa = TapAnalysis(samples)
# broadcast tap event data:
self._clients.send({'tap': ppa.to_dict()})
self._is_last_result_valid = True
self._last_result = epos[2]
return epos, self._is_last_result_valid
def get_status(self, eventtime):
return {
'last_z_result': self._last_result,
'is_last_tap_valid': self._is_last_result_valid
}
# ProbeSession that implements Tap logic
class TapSession:
def __init__(self, config, tapping_move, probe_params_helper):
self._printer = config.get_printer()
self._tapping_move = tapping_move
self._probe_params_helper = probe_params_helper
# Session state
self._results = []
def start_probe_session(self, gcmd):
return self
def end_probe_session(self):
self._results = []
# probe until a single good sample is returned or retries are exhausted
def run_probe(self, gcmd):
epos, is_good = self._tapping_move.run_tap(gcmd)
self._results.append(epos)
def pull_probed_results(self):
res = self._results
self._results = []
return res
class LoadCellProbeCommands:
def __init__(self, config, load_cell_probing_move):
self._printer = config.get_printer()
self._load_cell_probing_move = load_cell_probing_move
self._register_commands()
def _register_commands(self):
# Register commands
gcode = self._printer.lookup_object('gcode')
gcode.register_command("LOAD_CELL_TEST_TAP",
self.cmd_LOAD_CELL_TEST_TAP, desc=self.cmd_LOAD_CELL_TEST_TAP_help)
cmd_LOAD_CELL_TEST_TAP_help = "Tap the load cell probe to verify operation"
def cmd_LOAD_CELL_TEST_TAP(self, gcmd):
taps = gcmd.get_int("TAPS", 3, minval=1, maxval=10)
timeout = gcmd.get_float("TIMEOUT", 30., minval=1., maxval=120.)
gcmd.respond_info("Tap the load cell %s times:" % (taps,))
reactor = self._printer.get_reactor()
for i in range(0, taps):
result = self._load_cell_probing_move.probing_test(gcmd, timeout)
if result == 0.:
# notify of error, likely due to timeout
raise gcmd.error("Test timeout out")
gcmd.respond_info("Tap Detected!")
# give the user some time for their finger to move away
reactor.pause(reactor.monotonic() + 0.2)
gcmd.respond_info("Test complete, %s taps detected" % (taps,))
class LoadCellPrinterProbe:
def __init__(self, config):
cfg_error = config.error
try:
global np
import numpy as np
except:
raise cfg_error("[load_cell_probe] requires the NumPy module")
self._printer = config.get_printer()
# Sensor types supported by load_cell_probe
sensors = {}
sensors.update(hx71x.HX71X_SENSOR_TYPES)
sensors.update(ads1220.ADS1220_SENSOR_TYPE)
sensor_class = config.getchoice('sensor_type', sensors)
sensor = sensor_class(config)
self._load_cell = load_cell.LoadCell(config, sensor)
# Read all user configuration and build modules
config_helper = LoadCellProbeConfigHelper(config, self._load_cell)
self._mcu = self._load_cell.get_sensor().get_mcu()
trigger_dispatch = mcu.TriggerDispatch(self._mcu)
continuous_tare_filter_helper = ContinuousTareFilterHelper(config,
sensor, trigger_dispatch.get_command_queue())
# Probe Interface
self._param_helper = probe.ProbeParameterHelper(config)
self._cmd_helper = probe.ProbeCommandHelper(config, self)
self._probe_offsets = probe.ProbeOffsetsHelper(config)
self._mcu_load_cell_probe = McuLoadCellProbe(config, self._load_cell,
continuous_tare_filter_helper.get_sos_filter(), config_helper,
trigger_dispatch)
load_cell_probing_move = LoadCellProbingMove(config,
self._mcu_load_cell_probe, self._param_helper,
continuous_tare_filter_helper, config_helper)
self._tapping_move = TappingMove(config, load_cell_probing_move,
config_helper)
tap_session = TapSession(config, self._tapping_move, self._param_helper)
self._probe_session = probe.ProbeSessionHelper(config,
self._param_helper, tap_session.start_probe_session)
# printer integration
LoadCellProbeCommands(config, load_cell_probing_move)
probe.ProbeVirtualEndstopDeprecation(config)
self._printer.add_object('probe', self)
def get_probe_params(self, gcmd=None):
return self._param_helper.get_probe_params(gcmd)
def get_offsets(self):
return self._probe_offsets.get_offsets()
def start_probe_session(self, gcmd):
return self._probe_session.start_probe_session(gcmd)
def get_status(self, eventtime):
status = self._cmd_helper.get_status(eventtime)
status.update(self._load_cell.get_status(eventtime))
status.update(self._tapping_move.get_status(eventtime))
return status
def load_config(config):
return LoadCellPrinterProbe(config)
+25 -10
View File
@@ -5,6 +5,14 @@
# This file may be distributed under the terms of the GNU GPLv3 license.
import logging, bisect
# Helper to lookup the Z stepper config section
def lookup_z_endstop_config(config):
if config.has_section('stepper_z'):
return config.getsection('stepper_z')
elif config.has_section('carriage z'):
return config.getsection('carriage z')
return None
class ManualProbe:
def __init__(self, config):
self.printer = config.get_printer()
@@ -14,9 +22,13 @@ class ManualProbe:
self.gcode.register_command('MANUAL_PROBE', self.cmd_MANUAL_PROBE,
desc=self.cmd_MANUAL_PROBE_help)
# Endstop value for cartesian printers with separate Z axis
zconfig = config.getsection('stepper_z')
self.z_position_endstop = zconfig.getfloat('position_endstop', None,
note_valid=False)
zconfig = lookup_z_endstop_config(config)
if zconfig is not None:
self.z_position_endstop = zconfig.getfloat('position_endstop', None,
note_valid=False)
self.z_endstop_config_name = zconfig.get_name()
else:
self.z_position_endstop = self.z_endstop_config_name = None
# Endstop values for linear delta printers with vertical A,B,C towers
a_tower_config = config.getsection('stepper_a')
self.a_position_endstop = a_tower_config.getfloat('position_endstop',
@@ -67,11 +79,13 @@ class ManualProbe:
return
z_pos = self.z_position_endstop - kin_pos[2]
self.gcode.respond_info(
"stepper_z: position_endstop: %.3f\n"
"%s: position_endstop: %.3f\n"
"The SAVE_CONFIG command will update the printer config file\n"
"with the above and restart the printer." % (z_pos,))
"with the above and restart the printer." % (
self.z_endstop_config_name, z_pos,))
configfile = self.printer.lookup_object('configfile')
configfile.set('stepper_z', 'position_endstop', "%.3f" % (z_pos,))
configfile.set(self.z_endstop_config_name, 'position_endstop',
"%.3f" % (z_pos,))
cmd_Z_ENDSTOP_CALIBRATE_help = "Calibrate a Z endstop"
def cmd_Z_ENDSTOP_CALIBRATE(self, gcmd):
ManualProbeHelper(self.printer, gcmd, self.z_endstop_finalize)
@@ -83,11 +97,12 @@ class ManualProbe:
else:
new_calibrate = self.z_position_endstop - offset
self.gcode.respond_info(
"stepper_z: position_endstop: %.3f\n"
"%s: position_endstop: %.3f\n"
"The SAVE_CONFIG command will update the printer config file\n"
"with the above and restart the printer." % (new_calibrate))
configfile.set('stepper_z', 'position_endstop',
"%.3f" % (new_calibrate,))
"with the above and restart the printer." % (
self.z_endstop_config_name, new_calibrate))
configfile.set(self.z_endstop_config_name, 'position_endstop',
"%.3f" % (new_calibrate,))
def cmd_Z_OFFSET_APPLY_DELTA_ENDSTOPS(self,gcmd):
offset = self.gcode_move.get_status()['homing_origin'].z
configfile = self.printer.lookup_object('configfile')
+84 -2
View File
@@ -1,8 +1,9 @@
# Support for a manual controlled stepper
#
# Copyright (C) 2019-2021 Kevin O'Connor <kevin@koconnor.net>
# Copyright (C) 2019-2025 Kevin O'Connor <kevin@koconnor.net>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import logging
import stepper, chelper
from . import force_move
@@ -11,7 +12,7 @@ class ManualStepper:
self.printer = config.get_printer()
if config.get('endstop_pin', None) is not None:
self.can_home = True
self.rail = stepper.PrinterRail(
self.rail = stepper.LookupRail(
config, need_position_minmax=False, default_position_endstop=0.)
self.steppers = self.rail.get_steppers()
else:
@@ -21,6 +22,8 @@ class ManualStepper:
self.velocity = config.getfloat('velocity', 5., above=0.)
self.accel = self.homing_accel = config.getfloat('accel', 0., minval=0.)
self.next_cmd_time = 0.
self.pos_min = config.getfloat('position_min', None)
self.pos_max = config.getfloat('position_max', None)
# Setup iterative solver
ffi_main, ffi_lib = chelper.get_ffi()
self.trapq = ffi_main.gc(ffi_lib.trapq_alloc(), ffi_lib.trapq_free)
@@ -28,6 +31,10 @@ class ManualStepper:
self.trapq_finalize_moves = ffi_lib.trapq_finalize_moves
self.rail.setup_itersolve('cartesian_stepper_alloc', b'x')
self.rail.set_trapq(self.trapq)
# Registered with toolhead as an axtra axis
self.axis_gcode_id = None
self.instant_corner_v = 0.
self.gaxis_limit_velocity = self.gaxis_limit_accel = 0.
# Register commands
stepper_name = config.get_name().split()[1]
gcode = self.printer.lookup_object('gcode')
@@ -88,6 +95,10 @@ class ManualStepper:
triggered, check_trigger)
cmd_MANUAL_STEPPER_help = "Command a manually configured stepper"
def cmd_MANUAL_STEPPER(self, gcmd):
if gcmd.get('GCODE_AXIS', None) is not None:
return self.command_with_gcode_axis(gcmd)
if self.axis_gcode_id is not None:
raise gcmd.error("Must unregister from gcode axis first")
enable = gcmd.get_int('ENABLE', None)
if enable is not None:
self.do_enable(enable)
@@ -99,14 +110,85 @@ class ManualStepper:
homing_move = gcmd.get_int('STOP_ON_ENDSTOP', 0)
if homing_move:
movepos = gcmd.get_float('MOVE')
if ((self.pos_min is not None and movepos < self.pos_min)
or (self.pos_max is not None and movepos > self.pos_max)):
raise gcmd.error("Move out of range")
self.do_homing_move(movepos, speed, accel,
homing_move > 0, abs(homing_move) == 1)
elif gcmd.get_float('MOVE', None) is not None:
movepos = gcmd.get_float('MOVE')
if ((self.pos_min is not None and movepos < self.pos_min)
or (self.pos_max is not None and movepos > self.pos_max)):
raise gcmd.error("Move out of range")
sync = gcmd.get_int('SYNC', 1)
self.do_move(movepos, speed, accel, sync)
elif gcmd.get_int('SYNC', 0):
self.sync_print_time()
# Register as a gcode axis
def command_with_gcode_axis(self, gcmd):
gcode_move = self.printer.lookup_object("gcode_move")
toolhead = self.printer.lookup_object('toolhead')
gcode_axis = gcmd.get('GCODE_AXIS').upper()
instant_corner_v = gcmd.get_float('INSTANTANEOUS_CORNER_VELOCITY', 1.,
minval=0.)
limit_velocity = gcmd.get_float('LIMIT_VELOCITY', 999999.9, above=0.)
limit_accel = gcmd.get_float('LIMIT_ACCEL', 999999.9, above=0.)
if self.axis_gcode_id is not None:
if gcode_axis:
raise gcmd.error("Must unregister axis first")
# Unregister
toolhead.remove_extra_axis(self)
toolhead.unregister_step_generator(self.rail.generate_steps)
self.axis_gcode_id = None
return
if (len(gcode_axis) != 1 or not gcode_axis.isupper()
or gcode_axis in "XYZEFN"):
if not gcode_axis:
# Request to unregister already unregistered axis
return
raise gcmd.error("Not a valid GCODE_AXIS")
for ea in toolhead.get_extra_axes():
if ea is not None and ea.get_axis_gcode_id() == gcode_axis:
raise gcmd.error("Axis '%s' already registered" % (gcode_axis,))
self.axis_gcode_id = gcode_axis
self.instant_corner_v = instant_corner_v
self.gaxis_limit_velocity = limit_velocity
self.gaxis_limit_accel = limit_accel
toolhead.add_extra_axis(self, self.get_position()[0])
toolhead.register_step_generator(self.rail.generate_steps)
def process_move(self, print_time, move, ea_index):
axis_r = move.axes_r[ea_index]
start_pos = move.start_pos[ea_index]
accel = move.accel * axis_r
start_v = move.start_v * axis_r
cruise_v = move.cruise_v * axis_r
self.trapq_append(self.trapq, print_time,
move.accel_t, move.cruise_t, move.decel_t,
start_pos, 0., 0.,
1., 0., 0.,
start_v, cruise_v, accel)
def check_move(self, move, ea_index):
# Check move is in bounds
movepos = move.end_pos[ea_index]
if ((self.pos_min is not None and movepos < self.pos_min)
or (self.pos_max is not None and movepos > self.pos_max)):
raise move.move_error()
# Check if need to limit maximum velocity and acceleration
axis_ratio = move.move_d / abs(move.axes_d[ea_index])
limit_velocity = self.gaxis_limit_velocity * axis_ratio
limit_accel = self.gaxis_limit_accel * axis_ratio
if not move.is_kinematic_move and self.accel:
limit_accel = min(limit_accel, self.accel * axis_ratio)
move.limit_speed(limit_velocity, limit_accel)
def calc_junction(self, prev_move, move, ea_index):
diff_r = move.axes_r[ea_index] - prev_move.axes_r[ea_index]
if diff_r:
return (self.instant_corner_v / abs(diff_r))**2
return move.max_cruise_v2
def get_axis_gcode_id(self):
return self.axis_gcode_id
def get_trapq(self):
return self.trapq
# Toolhead wrappers to support homing
def flush_step_generation(self):
self.sync_print_time()
+8 -9
View File
@@ -1,6 +1,6 @@
# PWM and digital output pin handling
#
# Copyright (C) 2017-2024 Kevin O'Connor <kevin@koconnor.net>
# Copyright (C) 2017-2025 Kevin O'Connor <kevin@koconnor.net>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import logging, ast
@@ -11,8 +11,6 @@ from .display import display
# G-Code request queuing helper
######################################################################
PIN_MIN_TIME = 0.100
# Helper code to queue g-code requests
class GCodeRequestQueue:
def __init__(self, config, mcu, callback):
@@ -27,6 +25,7 @@ class GCodeRequestQueue:
def _handle_connect(self):
self.toolhead = self.printer.lookup_object('toolhead')
def _flush_notification(self, print_time, clock):
min_sched_time = self.mcu.min_schedule_time()
rqueue = self.rqueue
while rqueue:
next_time = max(rqueue[0][0], self.next_min_flush_time)
@@ -49,7 +48,7 @@ class GCodeRequestQueue:
if action == "delay":
pos -= 1
del rqueue[:pos+1]
self.next_min_flush_time = next_time + max(min_wait, PIN_MIN_TIME)
self.next_min_flush_time = next_time + max(min_wait, min_sched_time)
# Ensure following queue items are flushed
self.toolhead.note_mcu_movequeue_activity(self.next_min_flush_time)
def _queue_request(self, print_time, value):
@@ -59,9 +58,10 @@ class GCodeRequestQueue:
self.toolhead.register_lookahead_callback(
(lambda pt: self._queue_request(pt, value)))
def send_async_request(self, value, print_time=None):
min_sched_time = self.mcu.min_schedule_time()
if print_time is None:
systime = self.printer.get_reactor().monotonic()
print_time = self.mcu.estimated_print_time(systime + PIN_MIN_TIME)
print_time = self.mcu.estimated_print_time(systime + min_sched_time)
while 1:
next_time = max(print_time, self.next_min_flush_time)
# Invoke callback for the request
@@ -72,7 +72,7 @@ class GCodeRequestQueue:
action, min_wait = ret
if action == "discard":
break
self.next_min_flush_time = next_time + max(min_wait, PIN_MIN_TIME)
self.next_min_flush_time = next_time + max(min_wait, min_sched_time)
if action != "delay":
break
@@ -184,8 +184,6 @@ def lookup_template_eval(config):
# Main output pin handling
######################################################################
MAX_SCHEDULE_TIME = 5.0
class PrinterOutputPin:
def __init__(self, config):
self.printer = config.get_printer()
@@ -194,8 +192,9 @@ class PrinterOutputPin:
self.is_pwm = config.getboolean('pwm', False)
if self.is_pwm:
self.mcu_pin = ppins.setup_pin('pwm', config.get('pin'))
max_duration = self.mcu_pin.get_mcu().max_nominal_duration()
cycle_time = config.getfloat('cycle_time', 0.100, above=0.,
maxval=MAX_SCHEDULE_TIME)
maxval=max_duration)
hardware_pwm = config.getboolean('hardware_pwm', False)
self.mcu_pin.setup_cycle_time(cycle_time, hardware_pwm)
self.scale = config.getfloat('scale', 1., above=0.)
+5
View File
@@ -15,6 +15,11 @@ class PrintStats:
self.gcode.register_command(
"SET_PRINT_STATS_INFO", self.cmd_SET_PRINT_STATS_INFO,
desc=self.cmd_SET_PRINT_STATS_INFO_help)
printer.register_event_handler("extruder:activate_extruder",
self._handle_activate_extruder)
def _handle_activate_extruder(self):
gc_status = self.gcode_move.get_status()
self.last_epos = gc_status['position'].e
def _update_filament_usage(self, eventtime):
gc_status = self.gcode_move.get_status(eventtime)
cur_epos = gc_status['position'].e
+13 -2
View File
@@ -174,8 +174,8 @@ class ProbeCommandHelper:
# Helper to lookup the minimum Z position for the printer
def lookup_minimum_z(config):
if config.has_section('stepper_z'):
zconfig = config.getsection('stepper_z')
zconfig = manual_probe.lookup_z_endstop_config(config)
if zconfig is not None:
return zconfig.getfloat('position_min', 0., note_valid=False)
pconfig = config.getsection('printer')
return pconfig.getfloat('minimum_z_position', 0., note_valid=False)
@@ -265,6 +265,17 @@ class HomingViaProbeHelper:
self.results = []
self.mcu_probe.multi_probe_end()
class ProbeVirtualEndstopDeprecation:
def __init__(self, config):
self._name = config.get_name()
self._printer = config.get_printer()
# Register z_virtual_endstop pin
self._printer.lookup_object('pins').register_chip('probe', self)
def setup_pin(self, pin_type, pin_params):
raise self._printer.config_error(
"Module [%s] does not support `probe:z_virtual_endstop`"
", use a pin instead." % (self._name,))
# Helper to read multi-sample parameters from config
class ProbeParameterHelper:
def __init__(self, config):
+11 -9
View File
@@ -1,12 +1,9 @@
# Handle pwm output pins with variable frequency
#
# Copyright (C) 2017-2023 Kevin O'Connor <kevin@koconnor.net>
# Copyright (C) 2017-2025 Kevin O'Connor <kevin@koconnor.net>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
PIN_MIN_TIME = 0.100
MAX_SCHEDULE_TIME = 5.0
class MCU_pwm_cycle:
def __init__(self, pin_params, cycle_time, start_value, shutdown_value):
self._mcu = pin_params['chip']
@@ -22,6 +19,8 @@ class MCU_pwm_cycle:
self._shutdown_value = max(0., min(1., shutdown_value))
self._last_clock = self._cycle_ticks = 0
self._set_cmd = self._set_cycle_ticks = None
def get_mcu(self):
return self._mcu
def _build_config(self):
cmd_queue = self._mcu.alloc_command_queue()
curtime = self._mcu.get_printer().get_reactor().monotonic()
@@ -77,9 +76,6 @@ class PrinterOutputPWMCycle:
def __init__(self, config):
self.printer = config.get_printer()
self.last_print_time = 0.
cycle_time = config.getfloat('cycle_time', 0.100, above=0.,
maxval=MAX_SCHEDULE_TIME)
self.last_cycle_time = self.default_cycle_time = cycle_time
# Determine start and shutdown values
self.scale = config.getfloat('scale', 1., above=0.)
self.last_value = config.getfloat(
@@ -89,8 +85,12 @@ class PrinterOutputPWMCycle:
# Create pwm pin object
ppins = self.printer.lookup_object('pins')
pin_params = ppins.lookup_pin(config.get('pin'), can_invert=True)
max_duration = pin_params['chip'].max_nominal_duration()
cycle_time = config.getfloat('cycle_time', 0.100, above=0.,
maxval=max_duration)
self.mcu_pin = MCU_pwm_cycle(pin_params, cycle_time,
self.last_value, self.shutdown_value)
self.last_cycle_time = self.default_cycle_time = cycle_time
# Register commands
pin_name = config.get_name().split()[1]
gcode = self.printer.lookup_object('gcode')
@@ -102,7 +102,8 @@ class PrinterOutputPWMCycle:
def _set_pin(self, print_time, value, cycle_time):
if value == self.last_value and cycle_time == self.last_cycle_time:
return
print_time = max(print_time, self.last_print_time + PIN_MIN_TIME)
min_sched_time = self.mcu_pin.get_mcu().min_schedule_time()
print_time = max(print_time, self.last_print_time + min_sched_time)
self.mcu_pin.set_pwm_cycle(print_time, value, cycle_time)
self.last_value = value
self.last_cycle_time = cycle_time
@@ -112,8 +113,9 @@ class PrinterOutputPWMCycle:
# Read requested value
value = gcmd.get_float('VALUE', minval=0., maxval=self.scale)
value /= self.scale
max_duration = self.mcu_pin.get_mcu().max_nominal_duration()
cycle_time = gcmd.get_float('CYCLE_TIME', self.default_cycle_time,
above=0., maxval=MAX_SCHEDULE_TIME)
above=0., maxval=max_duration)
# Obtain print_time and apply requested settings
toolhead = self.printer.lookup_object('toolhead')
toolhead.register_lookahead_callback(
+4 -6
View File
@@ -1,12 +1,10 @@
# Queued PWM gpio output
#
# Copyright (C) 2017-2023 Kevin O'Connor <kevin@koconnor.net>
# Copyright (C) 2017-2025 Kevin O'Connor <kevin@koconnor.net>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import chelper
MAX_SCHEDULE_TIME = 5.0
class error(Exception):
pass
@@ -137,16 +135,16 @@ class PrinterOutputPin:
# Determine pin type
pin_params = ppins.lookup_pin(config.get('pin'), can_invert=True)
self.mcu_pin = MCU_queued_pwm(pin_params)
max_duration = self.mcu_pin.get_mcu().max_nominal_duration()
cycle_time = config.getfloat('cycle_time', 0.100, above=0.,
maxval=MAX_SCHEDULE_TIME)
maxval=max_duration)
hardware_pwm = config.getboolean('hardware_pwm', False)
self.mcu_pin.setup_cycle_time(cycle_time, hardware_pwm)
self.scale = config.getfloat('scale', 1., above=0.)
self.last_print_time = 0.
# Support mcu checking for maximum duration
max_mcu_duration = config.getfloat('maximum_mcu_duration', 0.,
minval=0.500,
maxval=MAX_SCHEDULE_TIME)
minval=0.500, maxval=max_duration)
self.mcu_pin.setup_max_duration(max_mcu_duration)
# Determine start and shutdown values
self.last_value = config.getfloat(
+6 -5
View File
@@ -127,7 +127,8 @@ class ResonanceTestExecutor:
def run_test(self, test_seq, axis, gcmd):
reactor = self.printer.get_reactor()
toolhead = self.printer.lookup_object('toolhead')
X, Y, Z, E = toolhead.get_position()
tpos = toolhead.get_position()
X, Y = tpos[:2]
# Override maximum acceleration and acceleration to
# deceleration based on the maximum test frequency
systime = reactor.monotonic()
@@ -166,10 +167,10 @@ class ResonanceTestExecutor:
# The move first goes to a complete stop, then changes direction
d_decel = -last_v2 * half_inv_accel
decel_X, decel_Y = axis.get_point(d_decel)
toolhead.move([X + decel_X, Y + decel_Y, Z, E], abs_last_v)
toolhead.move([nX, nY, Z, E], abs_v)
toolhead.move([X + decel_X, Y + decel_Y] + tpos[2:], abs_last_v)
toolhead.move([nX, nY] + tpos[2:], abs_v)
else:
toolhead.move([nX, nY, Z, E], max(abs_v, abs_last_v))
toolhead.move([nX, nY] + tpos[2:], max(abs_v, abs_last_v))
if math.floor(freq) > math.floor(last_freq):
gcmd.respond_info("Testing frequency %.0f Hz" % (freq,))
reactor.pause(reactor.monotonic() + 0.01)
@@ -183,7 +184,7 @@ class ResonanceTestExecutor:
decel_X, decel_Y = axis.get_point(d_decel)
toolhead.cmd_M204(self.gcode.create_gcode_command(
"M204", "M204", {"S": old_max_accel}))
toolhead.move([X + decel_X, Y + decel_Y, Z, E], abs(last_v))
toolhead.move([X + decel_X, Y + decel_Y] + tpos[2:], abs(last_v))
# Restore the original acceleration values
self.gcode.run_script_from_command(
"SET_VELOCITY_LIMIT ACCEL=%.3f MINIMUM_CRUISE_RATIO=%.3f"
+4 -1
View File
@@ -3,6 +3,7 @@
# Copyright (C) 2019 Florian Heilmann <Florian.Heilmann@gmx.net>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from . import manual_probe
class SafeZHoming:
def __init__(self, config):
@@ -11,7 +12,9 @@ class SafeZHoming:
self.home_x_pos, self.home_y_pos = x_pos, y_pos
self.z_hop = config.getfloat("z_hop", default=0.0)
self.z_hop_speed = config.getfloat('z_hop_speed', 15., above=0.)
zconfig = config.getsection('stepper_z')
zconfig = manual_probe.lookup_z_endstop_config(config)
if zconfig is None:
raise gcmd.error('Missing Z endstop config for safe_z_homing')
self.max_z = zconfig.getfloat('position_max', note_valid=False)
self.speed = config.getfloat('speed', 50.0, above=0.)
self.move_to_previous = config.getboolean('move_to_previous', False)
+1 -2
View File
@@ -9,7 +9,6 @@ from . import probe
class ScrewsTiltAdjust:
def __init__(self, config):
self.config = config
self.printer = config.get_printer()
self.screws = []
self.results = {}
@@ -33,7 +32,7 @@ class ScrewsTiltAdjust:
default='CW-M3')
# Initialize ProbePointsHelper
points = [coord for coord, name in self.screws]
self.probe_helper = probe.ProbePointsHelper(self.config,
self.probe_helper = probe.ProbePointsHelper(config,
self.probe_finalize,
default_points=points)
self.probe_helper.minimum_points(3)
+2 -2
View File
@@ -59,12 +59,12 @@ class PrinterSkew:
skewed_x = pos[0] - pos[1] * self.xy_factor \
- pos[2] * (self.xz_factor - (self.xy_factor * self.yz_factor))
skewed_y = pos[1] - pos[2] * self.yz_factor
return [skewed_x, skewed_y, pos[2], pos[3]]
return [skewed_x, skewed_y] + pos[2:]
def calc_unskew(self, pos):
skewed_x = pos[0] + pos[1] * self.xy_factor \
+ pos[2] * self.xz_factor
skewed_y = pos[1] + pos[2] * self.yz_factor
return [skewed_x, skewed_y, pos[2], pos[3]]
return [skewed_x, skewed_y] + pos[2:]
def get_position(self):
return self.calc_unskew(self.next_transform.get_position())
def move(self, newpos, speed):
+232
View File
@@ -0,0 +1,232 @@
# Second Order Sections Filter
#
# Copyright (C) 2025 Gareth Farrington <gareth@waves.ky>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
MAX_INT32 = (2 ** 31)
MIN_INT32 = -(2 ** 31) - 1
def assert_is_int32(value, error):
if value > MAX_INT32 or value < MIN_INT32:
raise OverflowError(error)
return value
# convert a floating point value to a 32 bit fixed point representation
# checks for overflow
def to_fixed_32(value, int_bits):
fractional_bits = (32 - (1 + int_bits))
fixed_val = int(value * (2 ** fractional_bits))
return assert_is_int32(fixed_val, "Fixed point Q%i overflow"
% (int_bits,))
# Digital filter designer and container
class DigitalFilter:
def __init__(self, sps, cfg_error, highpass=None, highpass_order=1,
lowpass=None, lowpass_order=1, notches=None, notch_quality=2.0):
self.filter_sections = []
self.initial_state = []
self.sample_frequency = sps
# an empty filter can be created without SciPi/numpy
if not (highpass or lowpass or notches):
return
try:
import scipy.signal as signal
except:
raise cfg_error("DigitalFilter require the SciPy module")
if highpass:
self.filter_sections.append(
self._butter(highpass, "highpass", highpass_order))
if lowpass:
self.filter_sections.append(
self._butter(lowpass, "lowpass", lowpass_order))
for notch_freq in notches:
self.filter_sections.append(self._notch(notch_freq, notch_quality))
if len(self.filter_sections) > 0:
self.initial_state = signal.sosfilt_zi(self.filter_sections)
def _butter(self, frequency, btype, order):
import scipy.signal as signal
return signal.butter(order, Wn=frequency, btype=btype,
fs=self.sample_frequency, output='sos')[0]
def _notch(self, freq, quality):
import scipy.signal as signal
b, a = signal.iirnotch(freq, Q=quality, fs=self.sample_frequency)
return signal.tf2sos(b, a)[0]
def get_filter_sections(self):
return self.filter_sections
def get_initial_state(self):
return self.initial_state
# container that accepts SciPy formatted SOS filter data and converts it to a
# selected fixed point representation. This data could come from DigitalFilter,
# static data, config etc.
class FixedPointSosFilter:
# filter_sections is an array of SciPy formatted SOS filter sections (sos)
# initial_state is an array of SciPy formatted SOS state sections (zi)
def __init__(self, filter_sections=None, initial_state=None,
coeff_int_bits=2, value_int_bits=15):
filter_sections = [] if filter_sections is None else filter_sections
initial_state = [] if initial_state is None else initial_state
num_sections = len(filter_sections)
num_state = len(initial_state)
if num_state != num_sections:
raise ValueError("The number of filter sections (%i) and state "
"sections (%i) must be equal" % (
num_sections, num_state))
self._coeff_int_bits = self._validate_int_bits(coeff_int_bits)
self._value_int_bits = self._validate_int_bits(value_int_bits)
self._filter = self._convert_filter(filter_sections)
self._state = self._convert_state(initial_state)
def get_filter_sections(self):
return self._filter
def get_initial_state(self):
return self._state
def get_coeff_int_bits(self):
return self._coeff_int_bits
def get_value_int_bits(self):
return self._value_int_bits
def get_num_sections(self):
return len(self._filter)
def _validate_int_bits(self, int_bits):
if int_bits < 1 or int_bits > 30:
raise ValueError("The number of integer bits (%i) must be a"
" value between 1 and 30" % (int_bits,))
return int_bits
# convert the SciPi SOS filters to fixed point format
def _convert_filter(self, filter_sections):
sos_fixed = []
for section in filter_sections:
nun_coeff = len(section)
if nun_coeff != 6:
raise ValueError("The number of filter coefficients is %i"
", must be 6" % (nun_coeff,))
fixed_section = []
for col, coeff in enumerate(section):
if col != 3: # omit column 3
fixed_coeff = to_fixed_32(coeff, self._coeff_int_bits)
fixed_section.append(fixed_coeff)
elif coeff != 1.0: # double check colum 3 is always 1.0
raise ValueError("Coefficient 3 is expected to be 1.0"
" but was %f" % (coeff,))
sos_fixed.append(fixed_section)
return sos_fixed
# convert the SOS filter state matrix (zi) to fixed point format
def _convert_state(self, filter_state):
sos_state = []
for section in filter_state:
nun_states = len(section)
if nun_states != 2:
raise ValueError(
"The number of state elements is %i, must be 2"
% (nun_states,))
fixed_state = []
for col, value in enumerate(section):
fixed_state.append(to_fixed_32(value, self._value_int_bits))
sos_state.append(fixed_state)
return sos_state
# Control an `sos_filter` object on the MCU
class SosFilter:
# fixed_point_filter should be an FixedPointSosFilter instance. A filter of
# size 0 will create a passthrough filter.
# max_sections should be the largest number of sections you expect
# to use at runtime. The default is the size of the fixed_point_filter.
def __init__(self, mcu, cmd_queue, fixed_point_filter, max_sections=None):
self._mcu = mcu
self._cmd_queue = cmd_queue
self._oid = self._mcu.create_oid()
self._filter = fixed_point_filter
self._max_sections = max_sections
if self._max_sections is None:
self._max_sections = self._filter.get_num_sections()
self._cmd_set_section = [
"sos_filter_set_section oid=%d section_idx=%d"
" sos0=%i sos1=%i sos2=%i sos3=%i sos4=%i",
"sos_filter_set_section oid=%c section_idx=%c"
" sos0=%i sos1=%i sos2=%i sos3=%i sos4=%i"]
self._cmd_config_state = [
"sos_filter_set_state oid=%d section_idx=%d state0=%i state1=%i",
"sos_filter_set_state oid=%c section_idx=%c state0=%i state1=%i"]
self._cmd_activate = [
"sos_filter_set_active oid=%d n_sections=%d coeff_int_bits=%d",
"sos_filter_set_active oid=%c n_sections=%c coeff_int_bits=%c"]
self._mcu.register_config_callback(self._build_config)
def _build_config(self):
cmds = [self._cmd_set_section, self._cmd_config_state,
self._cmd_activate]
for cmd in cmds:
cmd.append(self._mcu.lookup_command(cmd[1], cq=self._cmd_queue))
def get_oid(self):
return self._oid
# create an uninitialized filter object
def create_filter(self):
self._mcu.add_config_cmd("config_sos_filter oid=%d max_sections=%d"
% (self._oid, self._max_sections))
self._configure_filter(is_init=True)
# either setup an init command or send the command based on a flag
def _cmd(self, command, args, is_init=False):
if is_init:
self._mcu.add_config_cmd(command[0] % args, is_init=True)
else:
command[2].send(args)
def _set_filter_sections(self, is_init=False):
for i, section in enumerate(self._filter.get_filter_sections()):
args = (self._oid, i, section[0], section[1], section[2],
section[3], section[4])
self._cmd(self._cmd_set_section, args, is_init)
def _set_filter_state(self, is_init=False):
for i, state in enumerate(self._filter.get_initial_state()):
args = (self._oid, i, state[0], state[1])
self._cmd(self._cmd_config_state, args, is_init)
def _activate_filter(self, is_init=False):
args = (self._oid, self._filter.get_num_sections(),
self._filter.get_coeff_int_bits())
self._cmd(self._cmd_activate, args, is_init)
# configure the filter sections on the mcu
# filters should be an array of filter sections in SciPi SOS format
# sos_filter_state should be an array of zi filter state elements
def _configure_filter(self, is_init=False):
num_sections = self._filter.get_num_sections()
if num_sections > self._max_sections:
raise ValueError("Too many filter sections: %i, The max is %i"
% (num_sections, self._max_sections,))
# convert to fixed point to find errors
# no errors, state is accepted
# configure MCU filter and activate
self._set_filter_sections(is_init)
self._set_filter_state(is_init,)
self._activate_filter(is_init)
# Change the filter coefficients and state at runtime
# fixed_point_filter should be an FixedPointSosFilter instance
# cq is an optional command queue to for command sequencing
def change_filter(self, fixed_point_filter):
self._filter = fixed_point_filter
self._configure_filter(False)
# Resets the filter state back to initial conditions at runtime
# cq is an optional command queue to for command sequencing
def reset_filter(self):
self._set_filter_state(False)
self._activate_filter(False)
+2 -3
View File
@@ -16,7 +16,6 @@ class ZThermalAdjuster:
self.printer = config.get_printer()
self.gcode = self.printer.lookup_object('gcode')
self.lock = threading.Lock()
self.config = config
# Get config parameters, convert to SI units where necessary
self.temp_coeff = config.getfloat('temp_coeff', minval=-1, maxval=1,
@@ -110,12 +109,12 @@ class ZThermalAdjuster:
# Apply Z adjustment
new_z = pos[2] + self.z_adjust_mm
self.last_z_adjust_mm = self.z_adjust_mm
return [pos[0], pos[1], new_z, pos[3]]
return [pos[0], pos[1], new_z] + pos[3:]
def calc_unadjust(self, pos):
'Remove Z adjustment'
unadjusted_z = pos[2] - self.z_adjust_mm
return [pos[0], pos[1], unadjusted_z, pos[3]]
return [pos[0], pos[1], unadjusted_z] + pos[3:]
def get_position(self):
position = self.calc_unadjust(self.next_transform.get_position())
+11 -13
View File
@@ -29,14 +29,11 @@ class CartKinematics:
self.rails.append(stepper.LookupMultiRail(dc_config))
self.rails[3].setup_itersolve('cartesian_stepper_alloc',
dc_axis.encode())
dc_rail_0 = idex_modes.DualCarriagesRail(
self.rails[self.dual_carriage_axis],
axis=self.dual_carriage_axis, active=True)
dc_rail_1 = idex_modes.DualCarriagesRail(
self.rails[3], axis=self.dual_carriage_axis, active=False)
self.dc_module = idex_modes.DualCarriages(
dc_config, dc_rail_0, dc_rail_1,
axis=self.dual_carriage_axis)
self.printer, [self.rails[self.dual_carriage_axis]],
[self.rails[3]], axes=[self.dual_carriage_axis],
safe_dist=dc_config.getfloat(
'safe_distance', None, minval=0.))
for s in self.get_steppers():
s.set_trapq(toolhead.get_trapq())
toolhead.register_step_generator(s.generate_steps)
@@ -52,9 +49,10 @@ class CartKinematics:
def calc_position(self, stepper_positions):
rails = self.rails
if self.dc_module:
primary_rail = self.dc_module.get_primary_rail().get_rail()
rails = (rails[:self.dc_module.axis] +
[primary_rail] + rails[self.dc_module.axis+1:])
primary_rail = self.dc_module.get_primary_rail(
self.dual_carriage_axis)
rails = (rails[:self.dual_carriage_axis] +
[primary_rail] + rails[self.dual_carriage_axis+1:])
return [stepper_positions[rail.get_name()] for rail in rails]
def update_limits(self, i, range):
l, h = self.limits[i]
@@ -67,8 +65,8 @@ class CartKinematics:
rail.set_position(newpos)
for axis_name in homing_axes:
axis = "xyz".index(axis_name)
if self.dc_module and axis == self.dc_module.axis:
rail = self.dc_module.get_primary_rail().get_rail()
if self.dc_module and axis == self.dual_carriage_axis:
rail = self.dc_module.get_primary_rail(self.dual_carriage_axis)
else:
rail = self.rails[axis]
self.limits[axis] = rail.get_range()
@@ -93,7 +91,7 @@ class CartKinematics:
# Each axis is homed independently and in order
for axis in homing_state.get_axes():
if self.dc_module is not None and axis == self.dual_carriage_axis:
self.dc_module.home(homing_state)
self.dc_module.home(homing_state, self.dual_carriage_axis)
else:
self.home_axis(homing_state, axis, self.rails[axis])
def _check_endstops(self, move):
+2 -2
View File
@@ -17,10 +17,10 @@ class DeltesianKinematics:
self.rails = [None] * 3
stepper_configs = [config.getsection('stepper_' + s)
for s in ['left', 'right', 'y']]
self.rails[0] = stepper.PrinterRail(
self.rails[0] = stepper.LookupRail(
stepper_configs[0], need_position_minmax = False)
def_pos_es = self.rails[0].get_homing_info().position_endstop
self.rails[1] = stepper.PrinterRail(
self.rails[1] = stepper.LookupRail(
stepper_configs[1], need_position_minmax = False,
default_position_endstop = def_pos_es)
self.rails[2] = stepper.LookupMultiRail(stepper_configs[2])
+20 -19
View File
@@ -1,6 +1,6 @@
# Code for handling printer nozzle extruders
#
# Copyright (C) 2016-2022 Kevin O'Connor <kevin@koconnor.net>
# Copyright (C) 2016-2025 Kevin O'Connor <kevin@koconnor.net>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import math, logging
@@ -185,8 +185,6 @@ class PrinterExtruder:
gcode.register_mux_command("ACTIVATE_EXTRUDER", "EXTRUDER",
self.name, self.cmd_ACTIVATE_EXTRUDER,
desc=self.cmd_ACTIVATE_EXTRUDER_help)
def update_move_time(self, flush_time, clear_history_time):
self.trapq_finalize_moves(self.trapq, flush_time, clear_history_time)
def get_status(self, eventtime):
sts = self.heater.get_status(eventtime)
sts['can_extrude'] = self.heater.can_extrude
@@ -199,26 +197,29 @@ class PrinterExtruder:
return self.heater
def get_trapq(self):
return self.trapq
def get_axis_gcode_id(self):
return 'E'
def stats(self, eventtime):
return self.heater.stats(eventtime)
def check_move(self, move):
axis_r = move.axes_r[3]
def check_move(self, move, ea_index):
if not self.heater.can_extrude:
raise self.printer.command_error(
"Extrude below minimum temp\n"
"See the 'min_extrude_temp' config option for details")
axis_r = move.axes_r[ea_index]
axis_d = move.axes_d[ea_index]
if (not move.axes_d[0] and not move.axes_d[1]) or axis_r < 0.:
# Extrude only move (or retraction move) - limit accel and velocity
if abs(move.axes_d[3]) > self.max_e_dist:
if abs(axis_d) > self.max_e_dist:
raise self.printer.command_error(
"Extrude only move too long (%.3fmm vs %.3fmm)\n"
"See the 'max_extrude_only_distance' config"
" option for details" % (move.axes_d[3], self.max_e_dist))
" option for details" % (axis_d, self.max_e_dist))
inv_extrude_r = 1. / abs(axis_r)
move.limit_speed(self.max_e_velocity * inv_extrude_r,
self.max_e_accel * inv_extrude_r)
elif axis_r > self.max_extrude_ratio:
if move.axes_d[3] <= self.nozzle_diameter * self.max_extrude_ratio:
if axis_d <= self.nozzle_diameter * self.max_extrude_ratio:
# Permit extrusion if amount extruded is tiny
return
area = axis_r * self.filament_area
@@ -228,13 +229,13 @@ class PrinterExtruder:
"Move exceeds maximum extrusion (%.3fmm^2 vs %.3fmm^2)\n"
"See the 'max_extrude_cross_section' config option for details"
% (area, self.max_extrude_ratio * self.filament_area))
def calc_junction(self, prev_move, move):
diff_r = move.axes_r[3] - prev_move.axes_r[3]
def calc_junction(self, prev_move, move, ea_index):
diff_r = move.axes_r[ea_index] - prev_move.axes_r[ea_index]
if diff_r:
return (self.instant_corner_v / abs(diff_r))**2
return move.max_cruise_v2
def move(self, print_time, move):
axis_r = move.axes_r[3]
def process_move(self, print_time, move, ea_index):
axis_r = move.axes_r[ea_index]
accel = move.accel * axis_r
start_v = move.start_v * axis_r
cruise_v = move.cruise_v * axis_r
@@ -244,10 +245,10 @@ class PrinterExtruder:
# Queue movement (x is extruder movement, y is pressure advance flag)
self.trapq_append(self.trapq, print_time,
move.accel_t, move.cruise_t, move.decel_t,
move.start_pos[3], 0., 0.,
move.start_pos[ea_index], 0., 0.,
1., can_pressure_advance, 0.,
start_v, cruise_v, accel)
self.last_position = move.end_pos[3]
self.last_position = move.end_pos[ea_index]
def find_past_position(self, print_time):
if self.extruder_stepper is None:
return 0.
@@ -287,20 +288,20 @@ class PrinterExtruder:
class DummyExtruder:
def __init__(self, printer):
self.printer = printer
def update_move_time(self, flush_time, clear_history_time):
pass
def check_move(self, move):
def check_move(self, move, ea_index):
raise move.move_error("Extrude when no extruder present")
def find_past_position(self, print_time):
return 0.
def calc_junction(self, prev_move, move):
def calc_junction(self, prev_move, move, ea_index):
return move.max_cruise_v2
def get_name(self):
return ""
def get_heater(self):
raise self.printer.command_error("Extruder not configured")
def get_trapq(self):
raise self.printer.command_error("Extruder not configured")
return None
def get_axis_gcode_id(self):
return 'E'
def add_printer_objects(config):
printer = config.get_printer()
+358
View File
@@ -0,0 +1,358 @@
# Code for generic handling the kinematics of cartesian-like printers
#
# Copyright (C) 2024-2025 Dmitry Butyugin <dmbutyugin@google.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import copy, itertools, logging, math
import gcode, mathutil, stepper
from . import idex_modes
from . import kinematic_stepper as ks
def mat_mul(a, b):
if len(a[0]) != len(b):
return None
res = []
for i in range(len(a)):
res.append([])
for j in range(len(b[0])):
res[i].append(sum(a[i][k] * b[k][j] for k in range(len(b))))
return res
def mat_transp(a):
res = []
for i in range(len(a[0])):
res.append([a[j][i] for j in range(len(a))])
return res
def mat_pseudo_inverse(m):
mt = mat_transp(m)
mtm = mat_mul(mt, m)
pinv = mat_mul(mathutil.matrix_inv(mtm), mt)
return pinv
class MainCarriage:
def __init__(self, config, axis):
self.rail = stepper.GenericPrinterRail(config)
self.axis = ord(axis) - ord('x')
self.axis_name = axis
self.dual_carriage = None
def get_name(self):
return self.rail.get_name(short=True)
def get_axis(self):
return self.axis
def get_rail(self):
return self.rail
def add_stepper(self, kin_stepper):
self.rail.add_stepper(kin_stepper.get_stepper())
def is_active(self):
if self.dual_carriage is None:
return True
return self.dual_carriage.get_dc_module().is_active(self.rail)
def set_dual_carriage(self, carriage):
old_dc = self.dual_carriage
self.dual_carriage = carriage
return old_dc
def get_dual_carriage(self):
return self.dual_carriage
class ExtraCarriage:
def __init__(self, config, carriages):
self.name = config.get_name().split()[-1]
self.primary_carriage = config.getchoice('primary_carriage', carriages)
self.endstop_pin = config.get('endstop_pin')
def get_name(self):
return self.name
def get_axis(self):
return self.primary_carriage.get_axis()
def get_rail(self):
return self.primary_carriage.get_rail()
def add_stepper(self, kin_stepper):
self.get_rail().add_stepper(kin_stepper.get_stepper(),
self.endstop_pin, self.name)
class DualCarriage:
def __init__(self, config, carriages):
self.printer = config.get_printer()
self.rail = stepper.GenericPrinterRail(config)
self.primary_carriage = config.getchoice('primary_carriage', carriages)
if self.primary_carriage.set_dual_carriage(self) is not None:
raise config.error(
"Redefinition of dual_carriage for carriage '%s'" %
self.primary_carriage.get_name())
self.axis = self.primary_carriage.get_axis()
if self.axis > 1:
raise config.error("Invalid axis '%s' for dual_carriage" %
self.primary_carriage.get_axis_name())
self.safe_dist = config.getfloat('safe_distance', None, minval=0.)
def get_name(self):
return self.rail.get_name(short=True)
def get_axis(self):
return self.primary_carriage.get_axis()
def get_rail(self):
return self.rail
def get_safe_dist(self):
return self.safe_dist
def get_dc_module(self):
return self.printer.lookup_object('dual_carriage')
def is_active(self):
return self.get_dc_module().is_active(self.rail)
def get_dual_carriage(self):
return self.primary_carriage
def add_stepper(self, kin_stepper):
self.rail.add_stepper(kin_stepper.get_stepper())
class GenericCartesianKinematics:
def __init__(self, toolhead, config):
self.printer = config.get_printer()
self._load_kinematics(config)
for s in self.get_steppers():
s.set_trapq(toolhead.get_trapq())
toolhead.register_step_generator(s.generate_steps)
self.dc_module = None
if self.dc_carriages:
pcs = [dc.get_dual_carriage() for dc in self.dc_carriages]
primary_rails = [pc.get_rail() for pc in pcs]
dual_rails = [dc.get_rail() for dc in self.dc_carriages]
axes = [dc.get_axis() for dc in self.dc_carriages]
safe_dist = {dc.get_axis() : dc.get_safe_dist()
for dc in self.dc_carriages}
self.dc_module = dc_module = idex_modes.DualCarriages(
self.printer, primary_rails, dual_rails, axes, safe_dist)
zero_pos = (0., 0.)
for acs in itertools.product(*zip(pcs, self.dc_carriages)):
for c in acs:
dc_module.get_dc_rail_wrapper(c.get_rail()).activate(
idex_modes.PRIMARY, zero_pos)
dc_rail = c.get_dual_carriage().get_rail()
dc_module.get_dc_rail_wrapper(dc_rail).inactivate(zero_pos)
self._check_kinematics(config.error)
for c in pcs:
dc_module.get_dc_rail_wrapper(c.get_rail()).activate(
idex_modes.PRIMARY, zero_pos)
dc_rail = c.get_dual_carriage().get_rail()
dc_module.get_dc_rail_wrapper(dc_rail).inactivate(zero_pos)
else:
self._check_kinematics(config.error)
# Setup boundary checks
max_velocity, max_accel = toolhead.get_max_velocity()
self.max_z_velocity = config.getfloat('max_z_velocity', max_velocity,
above=0., maxval=max_velocity)
self.max_z_accel = config.getfloat('max_z_accel', max_accel,
above=0., maxval=max_accel)
self.limits = [(1.0, -1.0)] * 3
# Register gcode commands
gcode = self.printer.lookup_object('gcode')
gcode.register_command("SET_STEPPER_CARRIAGES",
self.cmd_SET_STEPPER_CARRIAGES,
desc=self.cmd_SET_STEPPER_CARRIAGES_help)
def _load_kinematics(self, config):
carriages = {a : MainCarriage(config.getsection('carriage ' + a), a)
for a in 'xyz'}
dc_carriages = []
for c in config.get_prefix_sections('dual_carriage '):
dc_carriages.append(DualCarriage(c, carriages))
for dc in dc_carriages:
name = dc.get_name()
if name in carriages:
raise config.error("Redefinition of carriage %s" % name)
carriages[name] = dc
self.carriages = dict(carriages)
self.dc_carriages = dc_carriages
ec_carriages = []
for c in config.get_prefix_sections('extra_carriage '):
ec_carriages.append(ExtraCarriage(c, carriages))
for ec in ec_carriages:
name = ec.get_name()
if name in carriages:
raise config.error("Redefinition of carriage %s" % name)
carriages[name] = ec
self.kin_steppers = self._load_steppers(config, carriages)
self.all_carriages = carriages
self._check_carriages_references(config.error)
self._check_multi_mcu_homing(config.error)
def _check_carriages_references(self, report_error):
carriages = dict(self.all_carriages)
for s in self.kin_steppers:
for c in s.get_carriages():
carriages.pop(c.get_name(), None)
if carriages:
raise report_error(
"Carriage(s) %s must be referenced by some "
"stepper(s)" % (", ".join(carriages),))
def _check_multi_mcu_homing(self, report_error):
for carriage in self.carriages.values():
for es in carriage.get_rail().get_endstops():
stepper_mcus = set([s.get_mcu() for s in es[0].get_steppers()
if s in carriage.get_rail().get_steppers()])
if len(stepper_mcus) > 1:
raise report_error("Multi-mcu homing not supported on"
" multi-mcu shared carriage %s" % es[1])
def _load_steppers(self, config, carriages):
return [ks.KinematicStepper(c, carriages)
for c in config.get_prefix_sections('stepper ')]
def get_steppers(self):
return [s.get_stepper() for s in self.kin_steppers]
def get_primary_carriages(self):
carriages = [self.carriages[a] for a in "xyz"]
if self.dc_module:
for a in self.dc_module.get_axes():
primary_rail = self.dc_module.get_primary_rail(a)
for c in self.carriages.values():
if c.get_rail() == primary_rail:
carriages[a] = c
return carriages
def _get_kinematics_coeffs(self):
matr = {s.get_name() : list(s.get_kin_coeffs())
for s in self.kin_steppers}
offs = {s.get_name() : [0.] * 3 for s in self.kin_steppers}
if self.dc_module is None:
return ([matr[s.get_name()] for s in self.kin_steppers],
[0. for s in self.kin_steppers])
axes = [dc.get_axis() for dc in self.dc_carriages]
orig_matr = copy.deepcopy(matr)
for dc in self.dc_carriages:
axis = dc.get_axis()
for c in [dc.get_dual_carriage(), dc]:
m, o = self.dc_module.get_transform(c.get_rail())
for s in c.get_rail().get_steppers():
matr[s.get_name()][axis] *= m
offs[s.get_name()][axis] += o
return ([matr[s.get_name()] for s in self.kin_steppers],
[mathutil.matrix_dot(orig_matr[s.get_name()],
offs[s.get_name()])
for s in self.kin_steppers])
def _check_kinematics(self, report_error):
matr, _ = self._get_kinematics_coeffs()
det = mathutil.matrix_det(mat_mul(mat_transp(matr), matr))
if abs(det) < 0.00001:
raise report_error(
"Verify configured stepper(s) and their 'carriages' "
"specifications, the current configuration does not "
"allow independent movements of all printer axes.")
def calc_position(self, stepper_positions):
matr, offs = self._get_kinematics_coeffs()
spos = [stepper_positions[s.get_name()] for s in self.kin_steppers]
pinv = mat_pseudo_inverse(matr)
pos = mat_mul([[sp-o for sp, o in zip(spos, offs)]], mat_transp(pinv))
for i in range(3):
if not any(pinv[i]):
pos[0][i] = None
return pos[0]
def update_limits(self, i, range):
l, h = self.limits[i]
# Only update limits if this axis was already homed,
# otherwise leave in un-homed state.
if l <= h:
self.limits[i] = range
def set_position(self, newpos, homing_axes):
for s in self.kin_steppers:
s.set_position(newpos)
for axis_name in homing_axes:
axis = "xyz".index(axis_name)
for c in self.carriages.values():
if c.get_axis() == axis and c.is_active():
self.limits[axis] = c.get_rail().get_range()
break
def clear_homing_state(self, clear_axes):
for axis, axis_name in enumerate("xyz"):
if axis_name in clear_axes:
self.limits[axis] = (1.0, -1.0)
def home_axis(self, homing_state, axis, rail):
# Determine movement
position_min, position_max = rail.get_range()
hi = rail.get_homing_info()
homepos = [None, None, None, None]
homepos[axis] = hi.position_endstop
forcepos = list(homepos)
if hi.positive_dir:
forcepos[axis] -= 1.5 * (hi.position_endstop - position_min)
else:
forcepos[axis] += 1.5 * (position_max - hi.position_endstop)
# Perform homing
homing_state.home_rails([rail], forcepos, homepos)
def home(self, homing_state):
self._check_kinematics(self.printer.command_error)
# Each axis is homed independently and in order
for axis in homing_state.get_axes():
carriage = self.carriages["xyz"[axis]]
if carriage.get_dual_carriage() != None:
self.dc_module.home(homing_state, axis)
else:
self.home_axis(homing_state, axis, carriage.get_rail())
def _check_endstops(self, move):
end_pos = move.end_pos
for i in (0, 1, 2):
if (move.axes_d[i]
and (end_pos[i] < self.limits[i][0]
or end_pos[i] > self.limits[i][1])):
if self.limits[i][0] > self.limits[i][1]:
raise move.move_error("Must home axis first")
raise move.move_error()
def check_move(self, move):
limits = self.limits
xpos, ypos = move.end_pos[:2]
if (xpos < limits[0][0] or xpos > limits[0][1]
or ypos < limits[1][0] or ypos > limits[1][1]):
self._check_endstops(move)
if not move.axes_d[2]:
# Normal XY move - use defaults
return
# Move with Z - update velocity and accel for slower Z axis
self._check_endstops(move)
z_ratio = move.move_d / abs(move.axes_d[2])
move.limit_speed(
self.max_z_velocity * z_ratio, self.max_z_accel * z_ratio)
def get_status(self, eventtime):
axes = [a for a, (l, h) in zip("xyz", self.limits) if l <= h]
ranges = [c.get_rail().get_range()
for c in self.get_primary_carriages()]
axes_min = gcode.Coord(*[r[0] for r in ranges], e=0.)
axes_max = gcode.Coord(*[r[1] for r in ranges], e=0.)
return {
'homed_axes': "".join(axes),
'axis_minimum': axes_min,
'axis_maximum': axes_max,
}
cmd_SET_STEPPER_CARRIAGES_help = "Set stepper carriages"
def cmd_SET_STEPPER_CARRIAGES(self, gcmd):
toolhead = self.printer.lookup_object('toolhead')
toolhead.flush_step_generation()
stepper_name = gcmd.get("STEPPER")
steppers = [stepper for stepper in self.kin_steppers
if stepper.get_name() == stepper_name
or stepper.get_name(short=True) == stepper_name]
if len(steppers) != 1:
raise gcmd.error("Invalid STEPPER '%s' specified" % stepper_name)
stepper = steppers[0]
carriages_str = gcmd.get("CARRIAGES").lower()
validate = not gcmd.get_int("DISABLE_CHECKS", 0)
old_carriages = stepper.get_carriages()
old_kin_coeffs = stepper.get_kin_coeffs()
stepper.update_carriages(carriages_str, self.all_carriages, gcmd.error)
new_carriages = stepper.get_carriages()
if new_carriages != old_carriages:
stepper.update_kin_coeffs(old_kin_coeffs)
raise gcmd.error("SET_STEPPER_CARRIAGES cannot add or remove "
"carriages that the stepper controls")
pos = toolhead.get_position()
stepper.set_position(pos)
if not validate:
return
if self.dc_module:
dc_state = self.dc_module.save_dual_carriage_state()
pcs = [dc.get_dual_carriage() for dc in self.dc_carriages]
axes = [dc.get_axis() for dc in self.dc_carriages]
for acs in itertools.product(*zip(pcs, self.dc_carriages)):
for c in acs:
self.dc_module.get_dc_rail_wrapper(c.get_rail()).activate(
idex_modes.PRIMARY, pos)
self.dc_module.get_dc_rail_wrapper(
c.get_dual_carriage().get_rail()).inactivate(pos)
self._check_kinematics(gcmd.error)
self.dc_module.restore_dual_carriage_state(dc_state, move=0)
else:
self._check_kinematics(gcmd.error)
def load_kinematics(toolhead, config):
return GenericCartesianKinematics(toolhead, config)
+8 -10
View File
@@ -12,7 +12,7 @@ class HybridCoreXYKinematics:
def __init__(self, toolhead, config):
self.printer = config.get_printer()
# itersolve parameters
self.rails = [ stepper.PrinterRail(config.getsection('stepper_x')),
self.rails = [ stepper.LookupRail(config.getsection('stepper_x')),
stepper.LookupMultiRail(config.getsection('stepper_y')),
stepper.LookupMultiRail(config.getsection('stepper_z'))]
self.rails[1].get_endstops()[0][0].add_stepper(
@@ -29,16 +29,14 @@ class HybridCoreXYKinematics:
# dummy for cartesian config users
dc_config.getchoice('axis', ['x'], default='x')
# setup second dual carriage rail
self.rails.append(stepper.PrinterRail(dc_config))
self.rails.append(stepper.LookupRail(dc_config))
self.rails[1].get_endstops()[0][0].add_stepper(
self.rails[3].get_steppers()[0])
self.rails[3].setup_itersolve('corexy_stepper_alloc', b'+')
dc_rail_0 = idex_modes.DualCarriagesRail(
self.rails[0], axis=0, active=True)
dc_rail_1 = idex_modes.DualCarriagesRail(
self.rails[3], axis=0, active=False)
self.dc_module = idex_modes.DualCarriages(
dc_config, dc_rail_0, dc_rail_1, axis=0)
self.printer, [self.rails[0]], [self.rails[3]], axes=[0],
safe_dist=dc_config.getfloat(
'safe_distance', None, minval=0.))
for s in self.get_steppers():
s.set_trapq(toolhead.get_trapq())
toolhead.register_step_generator(s.generate_steps)
@@ -69,8 +67,8 @@ class HybridCoreXYKinematics:
rail.set_position(newpos)
for axis_name in homing_axes:
axis = "xyz".index(axis_name)
if self.dc_module and axis == self.dc_module.axis:
rail = self.dc_module.get_primary_rail().get_rail()
if self.dc_module and axis == 0:
rail = self.dc_module.get_primary_rail(axis)
else:
rail = self.rails[axis]
self.limits[axis] = rail.get_range()
@@ -93,7 +91,7 @@ class HybridCoreXYKinematics:
def home(self, homing_state):
for axis in homing_state.get_axes():
if self.dc_module is not None and axis == 0:
self.dc_module.home(homing_state)
self.dc_module.home(homing_state, axis)
else:
self.home_axis(homing_state, axis, self.rails[axis])
def _check_endstops(self, move):
+8 -10
View File
@@ -12,7 +12,7 @@ class HybridCoreXZKinematics:
def __init__(self, toolhead, config):
self.printer = config.get_printer()
# itersolve parameters
self.rails = [ stepper.PrinterRail(config.getsection('stepper_x')),
self.rails = [ stepper.LookupRail(config.getsection('stepper_x')),
stepper.LookupMultiRail(config.getsection('stepper_y')),
stepper.LookupMultiRail(config.getsection('stepper_z'))]
self.rails[2].get_endstops()[0][0].add_stepper(
@@ -29,16 +29,14 @@ class HybridCoreXZKinematics:
# dummy for cartesian config users
dc_config.getchoice('axis', ['x'], default='x')
# setup second dual carriage rail
self.rails.append(stepper.PrinterRail(dc_config))
self.rails.append(stepper.LookupRail(dc_config))
self.rails[2].get_endstops()[0][0].add_stepper(
self.rails[3].get_steppers()[0])
self.rails[3].setup_itersolve('corexz_stepper_alloc', b'+')
dc_rail_0 = idex_modes.DualCarriagesRail(
self.rails[0], axis=0, active=True)
dc_rail_1 = idex_modes.DualCarriagesRail(
self.rails[3], axis=0, active=False)
self.dc_module = idex_modes.DualCarriages(
dc_config, dc_rail_0, dc_rail_1, axis=0)
self.printer, [self.rails[0]], [self.rails[3]], axes=[0],
safe_dist=dc_config.getfloat(
'safe_distance', None, minval=0.))
for s in self.get_steppers():
s.set_trapq(toolhead.get_trapq())
toolhead.register_step_generator(s.generate_steps)
@@ -69,8 +67,8 @@ class HybridCoreXZKinematics:
rail.set_position(newpos)
for axis_name in homing_axes:
axis = "xyz".index(axis_name)
if self.dc_module and axis == self.dc_module.axis:
rail = self.dc_module.get_primary_rail().get_rail()
if self.dc_module and axis == 0:
rail = self.dc_module.get_primary_rail(axis)
else:
rail = self.rails[axis]
self.limits[axis] = rail.get_range()
@@ -93,7 +91,7 @@ class HybridCoreXZKinematics:
def home(self, homing_state):
for axis in homing_state.get_axes():
if self.dc_module is not None and axis == 0:
self.dc_module.home(homing_state)
self.dc_module.home(homing_state, axis)
else:
self.home_axis(homing_state, axis, self.rails[axis])
def _check_endstops(self, move):
+188 -112
View File
@@ -1,10 +1,10 @@
# Support for duplication and mirroring modes for IDEX printers
#
# Copyright (C) 2021 Fabrice Gallet <tircown@gmail.com>
# Copyright (C) 2023 Dmitry Butyugin <dmbutyugin@google.com>
# Copyright (C) 2023-2025 Dmitry Butyugin <dmbutyugin@google.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import logging, math
import collections, logging, math
import chelper
INACTIVE = 'INACTIVE'
@@ -14,18 +14,36 @@ MIRROR = 'MIRROR'
class DualCarriages:
VALID_MODES = [PRIMARY, COPY, MIRROR]
def __init__(self, dc_config, rail_0, rail_1, axis):
self.printer = dc_config.get_printer()
self.axis = axis
self.dc = (rail_0, rail_1)
def __init__(self, printer, primary_rails, dual_rails, axes,
safe_dist={}):
self.printer = printer
self.axes = axes
self._init_steppers(primary_rails + dual_rails)
self.primary_rails = [
DualCarriagesRail(printer, c, dual_rails[i],
axes[i], active=True)
for i, c in enumerate(primary_rails)]
self.dual_rails = [
DualCarriagesRail(printer, c, primary_rails[i],
axes[i], active=False)
for i, c in enumerate(dual_rails)]
self.dc_rails = collections.OrderedDict(
[(c.rail.get_name(short=True), c)
for c in self.primary_rails + self.dual_rails])
self.saved_states = {}
safe_dist = dc_config.getfloat('safe_distance', None, minval=0.)
if safe_dist is None:
dc0_rail = rail_0.get_rail()
dc1_rail = rail_1.get_rail()
safe_dist = min(abs(dc0_rail.position_min - dc1_rail.position_min),
abs(dc0_rail.position_max - dc1_rail.position_max))
self.safe_dist = safe_dist
self.safe_dist = {}
for i, dc in enumerate(dual_rails):
axis = axes[i]
if isinstance(safe_dist, dict):
if axis in safe_dist:
self.safe_dist[axis] = safe_dist[axis]
continue
elif safe_dist is not None:
self.safe_dist[axis] = safe_dist
continue
pc = primary_rails[i]
self.safe_dist[axis] = min(abs(pc.position_min - dc.position_min),
abs(pc.position_max - dc.position_max))
self.printer.add_object('dual_carriage', self)
self.printer.register_event_handler("klippy:ready", self._handle_ready)
gcode = self.printer.lookup_object('gcode')
@@ -40,58 +58,93 @@ class DualCarriages:
'RESTORE_DUAL_CARRIAGE_STATE',
self.cmd_RESTORE_DUAL_CARRIAGE_STATE,
desc=self.cmd_RESTORE_DUAL_CARRIAGE_STATE_help)
def get_rails(self):
return self.dc
def get_primary_rail(self):
for rail in self.dc:
if rail.mode == PRIMARY:
return rail
def _init_steppers(self, rails):
ffi_main, ffi_lib = chelper.get_ffi()
self.dc_stepper_kinematics = []
self.orig_stepper_kinematics = []
steppers = set()
for rail in rails:
c_steppers = rail.get_steppers()
if not c_steppers:
raise self.printer.config_error(
"At least one stepper must be "
"associated with carriage: %s" % rail.get_name())
steppers.update(c_steppers)
for s in steppers:
sk = ffi_main.gc(ffi_lib.dual_carriage_alloc(), ffi_lib.free)
orig_sk = s.get_stepper_kinematics()
ffi_lib.dual_carriage_set_sk(sk, orig_sk)
self.dc_stepper_kinematics.append(sk)
self.orig_stepper_kinematics.append(orig_sk)
s.set_stepper_kinematics(sk)
def get_axes(self):
return self.axes
def get_primary_rail(self, axis):
for dc_rail in self.dc_rails.values():
if dc_rail.mode == PRIMARY and dc_rail.axis == axis:
return dc_rail.rail
return None
def toggle_active_dc_rail(self, index):
def get_dc_rail_wrapper(self, rail):
for dc_rail in self.dc_rails.values():
if dc_rail.rail == rail:
return dc_rail
return None
def get_transform(self, rail):
dc_rail = self.get_dc_rail_wrapper(rail)
if dc_rail is not None:
return (dc_rail.scale, dc_rail.offset)
return (0., 0.)
def is_active(self, rail):
dc_rail = self.get_dc_rail_wrapper(rail)
return dc_rail.is_active() if dc_rail is not None else False
def toggle_active_dc_rail(self, target_dc):
toolhead = self.printer.lookup_object('toolhead')
toolhead.flush_step_generation()
pos = toolhead.get_position()
kin = toolhead.get_kinematics()
for i, dc in enumerate(self.dc):
dc_rail = dc.get_rail()
if i != index:
if dc.is_active():
dc.inactivate(pos)
target_dc = self.dc[index]
axis = target_dc.axis
for dc in self.dc_rails.values():
if dc != target_dc and dc.axis == axis and dc.is_active():
dc.inactivate(pos)
if target_dc.mode != PRIMARY:
newpos = pos[:self.axis] + [target_dc.get_axis_position(pos)] \
+ pos[self.axis+1:]
newpos = pos[:axis] + [target_dc.get_axis_position(pos)] \
+ pos[axis+1:]
target_dc.activate(PRIMARY, newpos, old_position=pos)
toolhead.set_position(newpos)
kin.update_limits(self.axis, target_dc.get_rail().get_range())
def home(self, homing_state):
kin.update_limits(axis, target_dc.rail.get_range())
def home(self, homing_state, axis):
kin = self.printer.lookup_object('toolhead').get_kinematics()
enumerated_dcs = list(enumerate(self.dc))
if (self.get_dc_order(0, 1) > 0) != \
self.dc[0].get_rail().get_homing_info().positive_dir:
dcs = [dc for dc in self.dc_rails.values() if dc.axis == axis]
if (self.get_dc_order(dcs[0], dcs[1]) > 0) != \
dcs[0].rail.get_homing_info().positive_dir:
# The second carriage must home first, because the carriages home in
# the same direction and the first carriage homes on the second one
enumerated_dcs.reverse()
for i, dc_rail in enumerated_dcs:
self.toggle_active_dc_rail(i)
kin.home_axis(homing_state, self.axis, dc_rail.get_rail())
dcs.reverse()
for dc in dcs:
self.toggle_active_dc_rail(dc)
kin.home_axis(homing_state, axis, dc.rail)
# Restore the original rails ordering
self.toggle_active_dc_rail(0)
self.toggle_active_dc_rail(dcs[0])
def get_status(self, eventtime=None):
return {('carriage_%d' % (i,)) : dc.mode
for (i, dc) in enumerate(self.dc)}
def get_kin_range(self, toolhead, mode):
status = {'carriages' : {dc.get_name() : dc.mode
for dc in self.dc_rails.values()}}
if len(self.dc_rails) == 2:
status.update({('carriage_%d' % (i,)) : dc.mode
for i, dc in enumerate(self.dc_rails.values())})
return status
def get_kin_range(self, toolhead, mode, axis):
pos = toolhead.get_position()
axes_pos = [dc.get_axis_position(pos) for dc in self.dc]
dc0_rail = self.dc[0].get_rail()
dc1_rail = self.dc[1].get_rail()
if mode != PRIMARY or self.dc[0].is_active():
dcs = [dc for dc in self.dc_rails.values() if dc.axis == axis]
axes_pos = [dc.get_axis_position(pos) for dc in dcs]
dc0_rail = dcs[0].rail
dc1_rail = dcs[1].rail
if mode != PRIMARY or dcs[0].is_active():
range_min = dc0_rail.position_min
range_max = dc0_rail.position_max
else:
range_min = dc1_rail.position_min
range_max = dc1_rail.position_max
safe_dist = self.safe_dist
safe_dist = self.safe_dist[axis]
if not safe_dist:
return (range_min, range_max)
@@ -101,7 +154,7 @@ class DualCarriages:
range_max = min(range_max,
axes_pos[0] - axes_pos[1] + dc1_rail.position_max)
elif mode == MIRROR:
if self.get_dc_order(0, 1) > 0:
if self.get_dc_order(dcs[0], dcs[1]) > 0:
range_min = max(range_min,
0.5 * (sum(axes_pos) + safe_dist))
range_max = min(range_max,
@@ -113,9 +166,9 @@ class DualCarriages:
sum(axes_pos) - dc1_rail.position_max)
else:
# mode == PRIMARY
active_idx = 1 if self.dc[1].is_active() else 0
active_idx = 1 if dcs[1].is_active() else 0
inactive_idx = 1 - active_idx
if self.get_dc_order(active_idx, inactive_idx) > 0:
if self.get_dc_order(dcs[active_idx], dcs[inactive_idx]) > 0:
range_min = max(range_min, axes_pos[inactive_idx] + safe_dist)
else:
range_max = min(range_max, axes_pos[inactive_idx] - safe_dist)
@@ -131,14 +184,14 @@ class DualCarriages:
# which actually permits carriage motion.
return (range_min, range_min)
return (range_min, range_max)
def get_dc_order(self, first, second):
if first == second:
def get_dc_order(self, first_dc, second_dc):
if first_dc == second_dc:
return 0
# Check the relative order of the first and second carriages and
# return -1 if the first carriage position is always smaller
# than the second one and 1 otherwise
first_rail = self.dc[first].get_rail()
second_rail = self.dc[second].get_rail()
first_rail = first_dc.rail
second_rail = second_dc.rail
first_homing_info = first_rail.get_homing_info()
second_homing_info = second_rail.get_homing_info()
if first_homing_info.positive_dir != second_homing_info.positive_dir:
@@ -148,50 +201,69 @@ class DualCarriages:
if first_rail.position_endstop > second_rail.position_endstop:
return 1
return -1
def activate_dc_mode(self, index, mode):
def activate_dc_mode(self, dc, mode):
toolhead = self.printer.lookup_object('toolhead')
toolhead.flush_step_generation()
kin = toolhead.get_kinematics()
axis = dc.axis
if mode == INACTIVE:
self.dc[index].inactivate(toolhead.get_position())
dc.inactivate(toolhead.get_position())
elif mode == PRIMARY:
self.toggle_active_dc_rail(index)
self.toggle_active_dc_rail(dc)
else:
self.toggle_active_dc_rail(0)
self.dc[index].activate(mode, toolhead.get_position())
kin.update_limits(self.axis, self.get_kin_range(toolhead, mode))
self.toggle_active_dc_rail(self.get_dc_rail_wrapper(dc.dual_rail))
dc.activate(mode, toolhead.get_position())
kin.update_limits(axis, self.get_kin_range(toolhead, mode, axis))
def _handle_ready(self):
# Apply the transform later during Klipper initialization to make sure
# that input shaping can pick up the correct stepper kinematic flags.
for dc in self.dc:
dc.apply_transform()
for dc_rail in self.dc_rails.values():
dc_rail.apply_transform()
cmd_SET_DUAL_CARRIAGE_help = "Configure the dual carriages mode"
def cmd_SET_DUAL_CARRIAGE(self, gcmd):
index = gcmd.get_int('CARRIAGE', minval=0, maxval=1)
carriage_str = gcmd.get('CARRIAGE', None)
if carriage_str is None:
raise gcmd.error('CARRIAGE must be specified')
if carriage_str in self.dc_rails:
dc_rail = self.dc_rails[carriage_str]
else:
dc_rail = None
if len(self.dc_rails) == 2:
try:
index = int(carriage_str.strip())
if index < 0 or index > 1:
raise gcmd.error('Invalid CARRIAGE=%d index' % index)
dc_rail = (self.dual_rails if index
else self.primary_rails)[0]
except ValueError:
pass
if dc_rail is None:
raise gcmd.error('Invalid CARRIAGE=%s specified' % carriage_str)
mode = gcmd.get('MODE', PRIMARY).upper()
if mode not in self.VALID_MODES:
raise gcmd.error("Invalid mode=%s specified" % (mode,))
if mode in [COPY, MIRROR]:
if index == 0:
if dc_rail in self.primary_rails:
raise gcmd.error(
"Mode=%s is not supported for carriage=0" % (mode,))
"Mode=%s is not supported for carriage=%s" % (
mode, dc_rail.get_name()))
curtime = self.printer.get_reactor().monotonic()
kin = self.printer.lookup_object('toolhead').get_kinematics()
axis = 'xyz'[self.axis]
axis = 'xyz'[dc_rail.axis]
if axis not in kin.get_status(curtime)['homed_axes']:
raise gcmd.error(
"Axis %s must be homed prior to enabling mode=%s" %
(axis, mode))
self.activate_dc_mode(index, mode)
(axis.upper(), mode))
self.activate_dc_mode(dc_rail, mode)
cmd_SAVE_DUAL_CARRIAGE_STATE_help = \
"Save dual carriages modes and positions"
def cmd_SAVE_DUAL_CARRIAGE_STATE(self, gcmd):
state_name = gcmd.get('NAME', 'default')
self.saved_states[state_name] = self.save_dual_carriage_state()
def save_dual_carriage_state(self):
pos = self.printer.lookup_object('toolhead').get_position()
self.saved_states[state_name] = {
'carriage_modes': [dc.mode for dc in self.dc],
'axes_positions': [dc.get_axis_position(pos) for dc in self.dc],
}
return {'carriage_modes': {dc.get_name() : dc.mode
for dc in self.dc_rails.values()},
'carriage_positions': {dc.get_name() : dc.get_axis_position(pos)
for dc in self.dc_rails.values()}}
cmd_RESTORE_DUAL_CARRIAGE_STATE_help = \
"Restore dual carriages modes and positions"
def cmd_RESTORE_DUAL_CARRIAGE_STATE(self, gcmd):
@@ -200,69 +272,73 @@ class DualCarriages:
if saved_state is None:
raise gcmd.error("Unknown DUAL_CARRIAGE state: %s" % (state_name,))
move_speed = gcmd.get_float('MOVE_SPEED', 0., above=0.)
move = gcmd.get_int('MOVE', 1)
self.restore_dual_carriage_state(saved_state, move, move_speed)
def restore_dual_carriage_state(self, saved_state, move, move_speed=0.):
toolhead = self.printer.lookup_object('toolhead')
toolhead.flush_step_generation()
if gcmd.get_int('MOVE', 1):
if move:
homing_speed = 99999999.
move_pos = list(toolhead.get_position())
cur_pos = []
for i, dc in enumerate(self.dc):
self.toggle_active_dc_rail(i)
homing_speed = min(homing_speed, dc.get_rail().homing_speed)
carriage_positions = saved_state['carriage_positions']
dcs = list(self.dc_rails.values())
for dc in dcs:
self.toggle_active_dc_rail(dc)
homing_speed = min(homing_speed, dc.rail.homing_speed)
cur_pos.append(toolhead.get_position())
move_pos = list(cur_pos[0])
dl = [saved_state['axes_positions'][i] - cur_pos[i][self.axis]
for i in range(2)]
primary_ind = 0 if abs(dl[0]) >= abs(dl[1]) else 1
self.toggle_active_dc_rail(primary_ind)
move_pos[self.axis] = saved_state['axes_positions'][primary_ind]
dc_mode = INACTIVE if min(abs(dl[0]), abs(dl[1])) < 0.000000001 \
else COPY if dl[0] * dl[1] > 0 else MIRROR
if dc_mode != INACTIVE:
self.dc[1-primary_ind].activate(dc_mode, cur_pos[primary_ind])
self.dc[1-primary_ind].override_axis_scaling(
abs(dl[1-primary_ind] / dl[primary_ind]),
cur_pos[primary_ind])
dl = [carriage_positions[dc.get_name()] - cur_pos[i][dc.axis]
for i, dc in enumerate(dcs)]
for axis in self.axes:
dc_ind = [i for i, dc in enumerate(dcs) if dc.axis == axis]
if abs(dl[dc_ind[0]]) >= abs(dl[dc_ind[1]]):
primary_ind, secondary_ind = dc_ind[0], dc_ind[1]
else:
primary_ind, secondary_ind = dc_ind[1], dc_ind[0]
primary_dc = dcs[primary_ind]
self.toggle_active_dc_rail(primary_dc)
move_pos[axis] = carriage_positions[primary_dc.get_name()]
dc_mode = INACTIVE if min(abs(dl[primary_ind]),
abs(dl[secondary_ind])) < .000000001 \
else COPY if dl[primary_ind] * dl[secondary_ind] > 0 \
else MIRROR
if dc_mode != INACTIVE:
dcs[secondary_ind].activate(dc_mode, cur_pos[primary_ind])
dcs[secondary_ind].override_axis_scaling(
abs(dl[secondary_ind] / dl[primary_ind]),
cur_pos[primary_ind])
toolhead.manual_move(move_pos, move_speed or homing_speed)
toolhead.flush_step_generation()
# Make sure the scaling coefficients are restored with the mode
self.dc[0].inactivate(move_pos)
self.dc[1].inactivate(move_pos)
for i, dc in enumerate(self.dc):
saved_mode = saved_state['carriage_modes'][i]
self.activate_dc_mode(i, saved_mode)
for dc in dcs:
dc.inactivate(move_pos)
for dc in self.dc_rails.values():
saved_mode = saved_state['carriage_modes'][dc.get_name()]
self.activate_dc_mode(dc, saved_mode)
class DualCarriagesRail:
ENC_AXES = [b'x', b'y']
def __init__(self, rail, axis, active):
def __init__(self, printer, rail, dual_rail, axis, active):
self.printer = printer
self.rail = rail
self.dual_rail = dual_rail
self.sks = [s.get_stepper_kinematics() for s in rail.get_steppers()]
self.axis = axis
self.mode = (INACTIVE, PRIMARY)[active]
self.offset = 0.
self.scale = 1. if active else 0.
ffi_main, ffi_lib = chelper.get_ffi()
self.dc_stepper_kinematics = []
self.orig_stepper_kinematics = []
for s in rail.get_steppers():
sk = ffi_main.gc(ffi_lib.dual_carriage_alloc(), ffi_lib.free)
orig_sk = s.get_stepper_kinematics()
ffi_lib.dual_carriage_set_sk(sk, orig_sk)
# Set the default transform for the other axis
ffi_lib.dual_carriage_set_transform(
sk, self.ENC_AXES[1 - axis], 1., 0.)
self.dc_stepper_kinematics.append(sk)
self.orig_stepper_kinematics.append(orig_sk)
s.set_stepper_kinematics(sk)
def get_rail(self):
return self.rail
def get_name(self):
return self.rail.get_name()
def is_active(self):
return self.mode != INACTIVE
def get_axis_position(self, position):
return position[self.axis] * self.scale + self.offset
def apply_transform(self):
ffi_main, ffi_lib = chelper.get_ffi()
for sk in self.dc_stepper_kinematics:
for sk in self.sks:
ffi_lib.dual_carriage_set_transform(
sk, self.ENC_AXES[self.axis], self.scale, self.offset)
self.printer.send_event('dual_carriage:update_kinematics')
def activate(self, mode, position, old_position=None):
old_axis_position = self.get_axis_position(old_position or position)
self.scale = -1. if mode == MIRROR else 1.
+92
View File
@@ -0,0 +1,92 @@
# Kinematic stepper class for generic cartesian kinematics
#
# Copyright (C) 2024 Dmitry Butyugin <dmbutyugin@google.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import logging, re
import stepper, chelper
def parse_carriages_string(carriages_str, printer_carriages, parse_error):
nxt = 0
pat = re.compile('[+-]')
coeffs = [0.] * 3
ref_carriages = []
while nxt < len(carriages_str):
match = pat.search(carriages_str, nxt+1)
end = len(carriages_str) if match is None else match.start()
term = carriages_str[nxt:end].strip()
term_lst = term.split('*')
if len(term_lst) not in [1, 2]:
raise parse_error(
"Invalid term '%s' in '%s'" % (term, carriages_str))
if len(term_lst) == 2:
try:
coeff = float(term_lst[0])
except ValueError:
raise error("Invalid float '%s'" % term_lst[0])
else:
coeff = -1. if term_lst[0].startswith('-') else 1.
if term_lst[0].startswith('-') or term_lst[0].startswith('+'):
term_lst[0] = term_lst[0][1:]
c = term_lst[-1]
if c not in printer_carriages:
raise parse_error("Invalid '%s' carriage referenced in '%s'" %
(c, carriages_str))
carriage = printer_carriages[c]
j = carriage.get_axis()
if coeffs[j]:
raise error("Carriage '%s' was referenced multiple times in '%s'" %
(c, carriages_str))
coeffs[j] = coeff
ref_carriages.append(carriage)
nxt = end
return coeffs, ref_carriages
class KinematicStepper:
def __init__(self, config, printer_carriages):
self.printer = config.get_printer()
self.stepper = stepper.PrinterStepper(config)
self.kin_coeffs, self.carriages = parse_carriages_string(
config.get('carriages'), printer_carriages, config.error)
if not any(self.kin_coeffs):
raise config.error(
"'%s' must provide a valid 'carriages' configuration" %
self.stepper.get_name())
self.stepper.setup_itersolve(
'generic_cartesian_stepper_alloc',
self.kin_coeffs[0], self.kin_coeffs[1], self.kin_coeffs[2])
self.stepper_sk = self.stepper.get_stepper_kinematics()
# Add stepper to the carriages it references
for sc in self.carriages:
sc.add_stepper(self)
def get_name(self, short=False):
name = self.stepper.get_name(short)
if short and name.startswith('stepper '):
return name[8:]
return name
def get_stepper(self):
return self.stepper
def get_kin_coeffs(self):
return tuple(self.kin_coeffs)
def get_active_axes(self):
return [i for i, c in enumerate(self.kin_coeffs) if c]
def get_carriages(self):
return self.carriages
def update_kin_coeffs(self, kin_coeffs):
self.kin_coeffs = kin_coeffs
ffi_main, ffi_lib = chelper.get_ffi()
ffi_lib.generic_cartesian_stepper_set_coeffs(
self.stepper_sk, kin_coeffs[0], kin_coeffs[1], kin_coeffs[2])
def update_carriages(self, carriages_str, printer_carriages, report_error):
kin_coeffs, carriages = parse_carriages_string(
carriages_str, printer_carriages,
report_error or self.printer.command_error)
if report_error is not None and not any(kin_coeffs):
raise report_error(
"A valid string that references at least one carriage"
" must be provided for '%s'" % self.get_name())
self.carriages = carriages
self.update_kin_coeffs(kin_coeffs)
def set_position(self, coord):
self.stepper.set_position(coord)
+1 -1
View File
@@ -11,7 +11,7 @@ class PolarKinematics:
# Setup axis steppers
stepper_bed = stepper.PrinterStepper(config.getsection('stepper_bed'),
units_in_radians=True)
rail_arm = stepper.PrinterRail(config.getsection('stepper_arm'))
rail_arm = stepper.LookupRail(config.getsection('stepper_arm'))
rail_z = stepper.LookupMultiRail(config.getsection('stepper_z'))
stepper_bed.setup_itersolve('polar_stepper_alloc', b'a')
rail_arm.setup_itersolve('polar_stepper_alloc', b'r')
+3 -3
View File
@@ -10,14 +10,14 @@ class RotaryDeltaKinematics:
def __init__(self, toolhead, config):
# Setup tower rails
stepper_configs = [config.getsection('stepper_' + a) for a in 'abc']
rail_a = stepper.PrinterRail(
rail_a = stepper.LookupRail(
stepper_configs[0], need_position_minmax=False,
units_in_radians=True)
a_endstop = rail_a.get_homing_info().position_endstop
rail_b = stepper.PrinterRail(
rail_b = stepper.LookupRail(
stepper_configs[1], need_position_minmax=False,
default_position_endstop=a_endstop, units_in_radians=True)
rail_c = stepper.PrinterRail(
rail_c = stepper.LookupRail(
stepper_configs[2], need_position_minmax=False,
default_position_endstop=a_endstop, units_in_radians=True)
self.rails = [rail_a, rail_b, rail_c]
+15
View File
@@ -135,3 +135,18 @@ def matrix_sub(m1, m2):
def matrix_mul(m1, s):
return [m1[0]*s, m1[1]*s, m1[2]*s]
######################################################################
# Matrix helper functions for 3x3 matrices
######################################################################
def matrix_det(a):
x0, x1, x2 = a
return matrix_dot(x0, matrix_cross(x1, x2))
def matrix_inv(a):
x0, x1, x2 = a
inv_det = 1. / matrix_det(a)
return [matrix_mul(matrix_cross(x1, x2), inv_det),
matrix_mul(matrix_cross(x2, x0), inv_det),
matrix_mul(matrix_cross(x0, x1), inv_det)]
+10 -1
View File
@@ -1,6 +1,6 @@
# Interface to Klipper micro-controller code
#
# Copyright (C) 2016-2024 Kevin O'Connor <kevin@koconnor.net>
# Copyright (C) 2016-2025 Kevin O'Connor <kevin@koconnor.net>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import sys, os, zlib, logging, math
@@ -545,6 +545,11 @@ class MCU_adc:
# Main MCU class
######################################################################
# Minimum time host needs to get scheduled events queued into mcu
MIN_SCHEDULE_TIME = 0.100
# Maximum time all MCUs can internally schedule into the future
MAX_NOMINAL_DURATION = 3.0
class MCU:
error = error
def __init__(self, config, clocksync):
@@ -868,6 +873,10 @@ class MCU:
return int(time * self._mcu_freq)
def get_max_stepper_error(self):
return self._max_stepper_error
def min_schedule_time(self):
return MIN_SCHEDULE_TIME
def max_nominal_duration(self):
return MAX_NOMINAL_DURATION
# Wrapper functions
def get_printer(self):
return self._printer
+49 -30
View File
@@ -56,7 +56,8 @@ class MCU_stepper:
def get_mcu(self):
return self._mcu
def get_name(self, short=False):
if short and self._name.startswith('stepper_'):
if short and self._name.startswith('stepper'):
# Skip an extra symbol after 'stepper'
return self._name[8:]
return self._name
def units_in_radians(self):
@@ -315,23 +316,21 @@ def parse_step_distance(config, units_in_radians=None, note_valid=False):
# Stepper controlled rails
######################################################################
# A motor control "rail" with one (or more) steppers and one (or more)
# A motor control carriage with one (or more) steppers and one (or more)
# endstops.
class PrinterRail:
class GenericPrinterRail:
def __init__(self, config, need_position_minmax=True,
default_position_endstop=None, units_in_radians=False):
# Primary stepper and endstop
self.stepper_units_in_radians = units_in_radians
self.printer = config.get_printer()
self.name = config.get_name()
self.steppers = []
self.endstops = []
self.endstop_map = {}
self.add_extra_stepper(config)
mcu_stepper = self.steppers[0]
self.get_name = mcu_stepper.get_name
self.get_commanded_position = mcu_stepper.get_commanded_position
self.calc_position_from_coord = mcu_stepper.calc_position_from_coord
self.endstop_pin = config.get('endstop_pin')
# Primary endstop position
mcu_endstop = self.endstops[0][0]
self.query_endstops = self.printer.load_object(config, 'query_endstops')
mcu_endstop = self.lookup_endstop(self.endstop_pin, self.name)
if hasattr(mcu_endstop, "get_position_endstop"):
self.position_endstop = mcu_endstop.get_position_endstop()
elif default_position_endstop is None:
@@ -380,6 +379,13 @@ class PrinterRail:
raise config.error(
"Invalid homing_positive_dir / position_endstop in '%s'"
% (config.get_name(),))
def get_name(self, short=False):
if short:
if self.name.startswith('stepper'):
# Skip an extra symbol after 'stepper'
return self.name[8:]
return self.name.split()[-1]
return self.name
def get_range(self):
return self.position_min, self.position_max
def get_homing_info(self):
@@ -394,16 +400,8 @@ class PrinterRail:
return list(self.steppers)
def get_endstops(self):
return list(self.endstops)
def add_extra_stepper(self, config):
stepper = PrinterStepper(config, self.stepper_units_in_radians)
self.steppers.append(stepper)
if self.endstops and config.get('endstop_pin', None) is None:
# No endstop defined - use primary endstop
self.endstops[0][0].add_stepper(stepper)
return
endstop_pin = config.get('endstop_pin')
printer = config.get_printer()
ppins = printer.lookup_object('pins')
def lookup_endstop(self, endstop_pin, name):
ppins = self.printer.lookup_object('pins')
pin_params = ppins.parse_pin(endstop_pin, True, True)
# Normalize pin name
pin_name = "%s:%s" % (pin_params['chip_name'], pin_params['pin'])
@@ -415,19 +413,32 @@ class PrinterRail:
self.endstop_map[pin_name] = {'endstop': mcu_endstop,
'invert': pin_params['invert'],
'pullup': pin_params['pullup']}
name = stepper.get_name(short=True)
self.endstops.append((mcu_endstop, name))
query_endstops = printer.load_object(config, 'query_endstops')
query_endstops.register_endstop(mcu_endstop, name)
self.query_endstops.register_endstop(mcu_endstop, name)
else:
mcu_endstop = endstop['endstop']
changed_invert = pin_params['invert'] != endstop['invert']
changed_pullup = pin_params['pullup'] != endstop['pullup']
if changed_invert or changed_pullup:
raise error("Printer rail %s shared endstop pin %s "
"must specify the same pullup/invert settings" % (
self.get_name(), pin_name))
raise self.printer.config_error(
"Printer rail %s shared endstop pin %s "
"must specify the same pullup/invert settings" % (
self.get_name(), pin_name))
return mcu_endstop
def add_stepper(self, stepper, endstop_pin=None, endstop_name=None):
if not self.steppers:
self.get_commanded_position = stepper.get_commanded_position
self.calc_position_from_coord = stepper.calc_position_from_coord
self.steppers.append(stepper)
if endstop_pin is not None:
mcu_endstop = self.lookup_endstop(
endstop_pin, endstop_name or stepper.get_name(short=True))
else:
mcu_endstop = self.lookup_endstop(self.endstop_pin, self.name)
mcu_endstop.add_stepper(stepper)
def add_stepper_from_config(self, config):
stepper = PrinterStepper(config, self.stepper_units_in_radians)
self.add_stepper(stepper, config.get('endstop_pin', None))
def setup_itersolve(self, alloc_func, *params):
for stepper in self.steppers:
stepper.setup_itersolve(alloc_func, *params)
@@ -441,13 +452,21 @@ class PrinterRail:
for stepper in self.steppers:
stepper.set_position(coord)
def LookupRail(config, need_position_minmax=True,
default_position_endstop=None, units_in_radians=False):
rail = GenericPrinterRail(config, need_position_minmax,
default_position_endstop, units_in_radians)
rail.add_stepper_from_config(config)
return rail
# Wrapper for dual stepper motor support
def LookupMultiRail(config, need_position_minmax=True,
default_position_endstop=None, units_in_radians=False):
rail = PrinterRail(config, need_position_minmax,
default_position_endstop, units_in_radians)
default_position_endstop=None, units_in_radians=False):
rail = LookupRail(config, need_position_minmax,
default_position_endstop, units_in_radians)
for i in range(1, 99):
if not config.has_section(config.get_name() + str(i)):
break
rail.add_extra_stepper(config.getsection(config.get_name() + str(i)))
rail.add_stepper_from_config(
config.getsection(config.get_name() + str(i)))
return rail
+60 -21
View File
@@ -21,14 +21,14 @@ class Move:
self.timing_callbacks = []
velocity = min(speed, toolhead.max_velocity)
self.is_kinematic_move = True
self.axes_d = axes_d = [end_pos[i] - start_pos[i] for i in (0, 1, 2, 3)]
self.axes_d = axes_d = [ep - sp for sp, ep in zip(start_pos, end_pos)]
self.move_d = move_d = math.sqrt(sum([d*d for d in axes_d[:3]]))
if move_d < .000000001:
# Extrude only move
self.end_pos = (start_pos[0], start_pos[1], start_pos[2],
end_pos[3])
self.end_pos = ((start_pos[0], start_pos[1], start_pos[2])
+ self.end_pos[3:])
axes_d[0] = axes_d[1] = axes_d[2] = 0.
self.move_d = move_d = abs(axes_d[3])
self.move_d = move_d = max([abs(ad) for ad in axes_d[3:]])
inv_move_d = 0.
if move_d:
inv_move_d = 1. / move_d
@@ -65,11 +65,13 @@ class Move:
def calc_junction(self, prev_move):
if not self.is_kinematic_move or not prev_move.is_kinematic_move:
return
# Allow extruder to calculate its maximum junction
extruder_v2 = self.toolhead.extruder.calc_junction(prev_move, self)
max_start_v2 = min(extruder_v2, self.max_cruise_v2,
prev_move.max_cruise_v2, prev_move.next_junction_v2,
prev_move.max_start_v2 + prev_move.delta_v2)
# Allow extra axes to calculate maximum junction
ea_v2 = [ea.calc_junction(prev_move, self, e_index+3)
for e_index, ea in enumerate(self.toolhead.extra_axes)]
max_start_v2 = min([self.max_cruise_v2,
prev_move.max_cruise_v2, prev_move.next_junction_v2,
prev_move.max_start_v2 + prev_move.delta_v2]
+ ea_v2)
# Find max velocity using "approximated centripetal velocity"
axes_r = self.axes_r
prev_axes_r = prev_move.axes_r
@@ -257,11 +259,14 @@ class ToolHead:
self.trapq = ffi_main.gc(ffi_lib.trapq_alloc(), ffi_lib.trapq_free)
self.trapq_append = ffi_lib.trapq_append
self.trapq_finalize_moves = ffi_lib.trapq_finalize_moves
# Motion flushing
self.step_generators = []
self.flush_trapqs = [self.trapq]
# Create kinematics class
gcode = self.printer.lookup_object('gcode')
self.Coord = gcode.Coord
self.extruder = kinematics.extruder.DummyExtruder(self.printer)
extruder = kinematics.extruder.DummyExtruder(self.printer)
self.extra_axes = [extruder]
kin_name = config.get('kinematics')
try:
mod = importlib.import_module('kinematics.' + kin_name)
@@ -303,8 +308,8 @@ class ToolHead:
if not self.can_pause:
clear_history_time = flush_time - MOVE_HISTORY_EXPIRE
free_time = sg_flush_time - self.kin_flush_delay
self.trapq_finalize_moves(self.trapq, free_time, clear_history_time)
self.extruder.update_move_time(free_time, clear_history_time)
for trapq in self.flush_trapqs:
self.trapq_finalize_moves(trapq, free_time, clear_history_time)
# Flush stepcompress and mcu steppersync
for m in self.all_mcus:
m.flush_moves(flush_time, clear_history_time)
@@ -349,8 +354,9 @@ class ToolHead:
move.start_pos[0], move.start_pos[1], move.start_pos[2],
move.axes_r[0], move.axes_r[1], move.axes_r[2],
move.start_v, move.cruise_v, move.accel)
if move.axes_d[3]:
self.extruder.move(next_move_time, move)
for e_index, ea in enumerate(self.extra_axes):
if move.axes_d[e_index + 3]:
ea.process_move(next_move_time, move, e_index + 3)
next_move_time = (next_move_time + move.accel_t
+ move.cruise_t + move.decel_t)
for cb in move.timing_callbacks:
@@ -457,7 +463,7 @@ class ToolHead:
ffi_main, ffi_lib = chelper.get_ffi()
ffi_lib.trapq_set_position(self.trapq, self.print_time,
newpos[0], newpos[1], newpos[2])
self.commanded_pos[:] = newpos
self.commanded_pos[:3] = newpos[:3]
self.kin.set_position(newpos, homing_axes)
self.printer.send_event("toolhead:set_position")
def limit_next_junction_speed(self, speed):
@@ -470,8 +476,9 @@ class ToolHead:
return
if move.is_kinematic_move:
self.kin.check_move(move)
if move.axes_d[3]:
self.extruder.check_move(move)
for e_index, ea in enumerate(self.extra_axes):
if move.axes_d[e_index + 3]:
ea.check_move(move, e_index + 3)
self.commanded_pos[:] = move.end_pos
want_flush = self.lookahead.add_move(move)
if want_flush:
@@ -498,10 +505,38 @@ class ToolHead:
break
eventtime = self.reactor.pause(eventtime + 0.100)
def set_extruder(self, extruder, extrude_pos):
self.extruder = extruder
# XXX - should use add_extra_axis
prev_ea_trapq = self.extra_axes[0].get_trapq()
if prev_ea_trapq in self.flush_trapqs:
self.flush_trapqs.remove(prev_ea_trapq)
self.extra_axes[0] = extruder
self.commanded_pos[3] = extrude_pos
ea_trapq = extruder.get_trapq()
if ea_trapq is not None:
self.flush_trapqs.append(ea_trapq)
def get_extruder(self):
return self.extruder
return self.extra_axes[0]
def add_extra_axis(self, ea, axis_pos):
self._flush_lookahead()
self.extra_axes.append(ea)
self.commanded_pos.append(axis_pos)
ea_trapq = ea.get_trapq()
if ea_trapq is not None:
self.flush_trapqs.append(ea_trapq)
self.printer.send_event("toolhead:update_extra_axes")
def remove_extra_axis(self, ea):
self._flush_lookahead()
if ea not in self.extra_axes:
return
ea_index = self.extra_axes.index(ea) + 3
ea_trapq = ea.get_trapq()
if ea_trapq in self.flush_trapqs:
self.flush_trapqs.remove(ea_trapq)
self.commanded_pos.pop(ea_index)
self.extra_axes.pop(ea_index - 3)
self.printer.send_event("toolhead:update_extra_axes")
def get_extra_axes(self):
return [None, None, None] + self.extra_axes
# Homing "drip move" handling
def drip_update_time(self, next_print_time, drip_completion, addstepper=()):
# Transition from "NeedPrime"/"Priming"/main state to "Drip" state
@@ -585,12 +620,13 @@ class ToolHead:
def get_status(self, eventtime):
print_time = self.print_time
estimated_print_time = self.mcu.estimated_print_time(eventtime)
extruder = self.extra_axes[0]
res = dict(self.kin.get_status(eventtime))
res.update({ 'print_time': print_time,
'stalls': self.print_stall,
'estimated_print_time': estimated_print_time,
'extruder': self.extruder.get_name(),
'position': self.Coord(*self.commanded_pos),
'extruder': extruder.get_name(),
'position': self.Coord(*self.commanded_pos[:4]),
'max_velocity': self.max_velocity,
'max_accel': self.max_accel,
'minimum_cruise_ratio': self.min_cruise_ratio,
@@ -605,6 +641,9 @@ class ToolHead:
return self.trapq
def register_step_generator(self, handler):
self.step_generators.append(handler)
def unregister_step_generator(self, handler):
if handler in self.step_generators:
self.step_generators.remove(handler)
def note_step_generation_scan_time(self, delay, old_delay=0.):
self.flush_step_generation()
if old_delay:
+34 -22
View File
@@ -3,28 +3,40 @@
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license
import logging, socket, os, sys, errno, json, collections
import logging, socket, os, sys, errno, collections
import gcode
REQUEST_LOG_SIZE = 20
try:
import msgspec
except ImportError:
import json
# Json decodes strings as unicode types in Python 2.x. This doesn't
# play well with some parts of Klipper (particuarly displays), so we
# need to create an object hook. This solution borrowed from:
#
# https://stackoverflow.com/questions/956867/
#
json_loads_byteify = None
if sys.version_info.major < 3:
def json_loads_byteify(data, ignore_dicts=False):
if isinstance(data, unicode):
return data.encode('utf-8')
if isinstance(data, list):
return [json_loads_byteify(i, True) for i in data]
if isinstance(data, dict) and not ignore_dicts:
return {json_loads_byteify(k, True): json_loads_byteify(v, True)
for k, v in data.items()}
return data
# Json decodes strings as unicode types in Python 2.x. This doesn't
# play well with some parts of Klipper (particuarly displays), so we
# need to create an object hook. This solution borrowed from:
#
# https://stackoverflow.com/questions/956867/
#
json_loads_byteify = None
if sys.version_info.major < 3:
def json_loads_byteify(data, ignore_dicts=False):
if isinstance(data, unicode):
return data.encode('utf-8')
if isinstance(data, list):
return [json_loads_byteify(i, True) for i in data]
if isinstance(data, dict) and not ignore_dicts:
return {json_loads_byteify(k, True): json_loads_byteify(v, True)
for k, v in data.items()}
return data
def json_dumps(obj):
return json.dumps(obj, separators=(',', ':')).encode()
def json_loads(data):
return json.loads(data, object_hook=json_loads_byteify)
else:
json_dumps = msgspec.json.encode
json_loads = msgspec.json.decode
REQUEST_LOG_SIZE = 20
class WebRequestError(gcode.CommandError):
def __init__(self, message,):
@@ -42,7 +54,7 @@ class WebRequest:
error = WebRequestError
def __init__(self, client_conn, request):
self.client_conn = client_conn
base_request = json.loads(request, object_hook=json_loads_byteify)
base_request = json_loads(request)
if type(base_request) != dict:
raise ValueError("Not a top-level dictionary")
self.id = base_request.get('id', None)
@@ -269,8 +281,8 @@ class ClientConnection:
def send(self, data):
try:
jmsg = json.dumps(data, separators=(',', ':'))
self.send_buffer += jmsg.encode() + b"\x03"
jmsg = json_dumps(data)
self.send_buffer += jmsg + b"\x03"
except (TypeError, ValueError) as e:
msg = ("json encoding error: %s" % (str(e),))
logging.exception(msg)
+1 -1
View File
@@ -8,7 +8,7 @@ set -eu
MAIN_DIR=${PWD}
BUILD_DIR=${PWD}/ci_build
export PATH=${BUILD_DIR}/pru-elf/bin:${PATH}
export PATH=${BUILD_DIR}/or1k-linux-musl-cross/bin:${PATH}
export PATH=${BUILD_DIR}/or1k-elf/bin:${PATH}
PYTHON=${BUILD_DIR}/python-env/bin/python
PYTHON2=${BUILD_DIR}/python2-env/bin/python
+8 -10
View File
@@ -39,20 +39,18 @@ tar xJf ${CACHE_DIR}/${PRU_ARCHIVE}
######################################################################
# Install or1k-linux-musl toolchain
# Install or1k toolchain
######################################################################
echo -e "\n\n=============== Install or1k-linux-musl toolchain\n\n"
TOOLCHAIN=or1k-linux-musl-cross
TOOLCHAIN_ZIP=${TOOLCHAIN}.tgz
GCC_VERSION=10
TOOLCHAIN_ZIP_V=${TOOLCHAIN}-${GCC_VERSION}.tgz
URL=https://more.musl.cc/${GCC_VERSION}/x86_64-linux-musl/
if [ ! -f ${CACHE_DIR}/${TOOLCHAIN_ZIP_V} ]; then
wget "${URL}/${TOOLCHAIN_ZIP}" -O "${CACHE_DIR}/${TOOLCHAIN_ZIP_V}"
echo -e "\n\n=============== Install or1k toolchain\n\n"
OR1K_ARCHIVE="or1k-elf-12.0.1-20220210-20220304.tar.xz"
OR1K_REL="or1k-12.0.1-20220210-20220304"
OR1K_URL="https://github.com/openrisc/or1k-gcc/releases/download/${OR1K_REL}/${OR1K_ARCHIVE}"
if [ ! -f ${CACHE_DIR}/${OR1K_ARCHIVE} ]; then
wget "${OR1K_URL}" -O "${CACHE_DIR}/${OR1K_ARCHIVE}"
fi
cd ${BUILD_DIR}
tar xf ${CACHE_DIR}/${TOOLCHAIN_ZIP_V}
tar xJf ${CACHE_DIR}/${OR1K_ARCHIVE}
######################################################################
+517
View File
@@ -0,0 +1,517 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "1b19a52d-7873-4e84-a4d6-62476b172f7f",
"metadata": {},
"source": [
"# Filter Workbench\n",
"This is a Python notebook file that contains code to help with designing and testing filters for the `[load_cell_probe]` feature."
]
},
{
"cell_type": "markdown",
"id": "f4e9e2cd-8f40-442e-a772-484ed071c535",
"metadata": {},
"source": [
"## Requirements\n",
"This notebook uses the following Python libraries:\n",
"* [NumPy](https://numpy.org/)\n",
"* [SciPy](https://scipy.org/)\n",
"* [Matplotlib](https://matplotlib.org/)"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "4cc50350-8937-48d7-8131-148f0c099f64",
"metadata": {},
"outputs": [],
"source": [
"import scipy.signal as signal\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt"
]
},
{
"cell_type": "markdown",
"id": "5bae3233-a5d4-49f3-ab4b-60072c92d5fc",
"metadata": {},
"source": [
"## Test Data\n",
"This notebook uses a sample probe event from the `[load_cell_probe]` to demonstrate how the filter acts on real printer data. A sample is provided here from a Voron2.4. You can replace this with data from your own printer by capturing a probing event via the websocket."
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "05baaf49-d621-4921-bb79-cf64d982d4a2",
"metadata": {},
"outputs": [],
"source": [
"probe_data = '{\"force\":[-0.7860722706944084,-0.5571985419653606,0.07492889928629543,-0.546299792978263,-0.19753982539114248,0.09672639726049047,0.7942463324347315,-1.494490954855747,-1.9195421653525502,-0.6879835298105308,-0.7206797767718233,0.16211889118307557,0.14032139320888054,0.6089675996540738,-0.21933732336533754,-0.36102106019760527,-0.840566015629896,-0.9822497524621637,-1.494490954855747,1.731538745325118,1.2083987939444372,-0.862363513604091,0.053131401312100396,0.9032338223057067,-0.6879835298105308,-2.1593146430686954,-1.6252759427009171,-1.0476422463847488,0.9468288182540968,0.36919512193792836,0.07492889928629543,-0.5027047970298729,-0.4155148051330928,1.0449175591379745,0.7070563405379514,0.06403015029919791,-0.6770847808234333,-0.9277560075266761,-1.0040472504363587,-0.7860722706944084,0.3038026280153433,0.42368886687341595,0.33649887497663583,-0.15394482944275242,-0.19753982539114248,-0.37191980918470274,-0.7642747727202134,-0.4591098010814829,0.03133390333790536,0.3256001259895383,-0.2738310683008251,-0.5898947889266531,-0.24113482133953257,-1.0149459994234562,0.8269425793960241,4.848580955635008,4.772289712725325,-0.7206797767718233,-2.5189733596429136,0.4345876158605135,-0.4809072990556779,3.1592748626348928,2.766919899099382,0.48908136079600106,-2.0067321572493304,-3.4017720275978123,-1.7124659345976974,0.9468288182540968,2.5707424173316267,2.211083700757409,0.7179550895250489,-1.9086434163654526,-0.19753982539114248,1.6552475024154354,1.5789562595057527,-1.0367434973976513,-1.2547184771396016,-2.192010890029988,-1.9958334082622327,-0.6661860318363357,0.3256001259895383,-0.35012231121050774,0.4127901178863185,0.23841013409275819,0.7288538385121465,-0.07765358653306981,0.09672639726049047,-0.8950597605653836,0.34739762396373336,0.053131401312100396,0.06403015029919791,-0.9604522544879687,-1.4290984609331618,-0.42641355412019033,0.8378413283831216,1.7860324902606055,0.47818261180890353,-0.9386547565137736,-1.7560609305460875,-0.11034983349436235,0.6307650976282688,-1.3419084690363818,-2.617062100526791,-1.2547184771396016,0.20571388713146563,2.745122401125187,0.739752587499244,-0.35012231121050774,0.2602076320669532,2.2655774456928963,1.9168174781057759,2.2982736926541887,0.42368886687341595,-0.36102106019760527,-0.3283248132363127,-0.6988822787976283,-0.7751735217073109,-0.15394482944275242,-1.8432509224428675,-2.0176309062364277,1.0885125550863646,0.5326763567443912,0.020435154350807845,-3.1946957968429595,-3.5434557644300804,0.5871701016798787,2.0149062189896534,0.03133390333790536,-1.9304409143396477,0.22751138510566066,0.07492889928629543,0.8596388263573166,0.5326763567443912,-0.42641355412019033,-1.178427234229919,-1.2874147241008942,-0.09945108450726484,0.7506513364863415,0.129422644221783,-0.6879835298105308,-0.9168572585395786,0.9795250652153893,0.9250313202799018,1.3391837817896073,-0.4482110520943854,-0.8078697686686034,0.4999801097830986,2.1020962108864336,1.9059187291186783,-0.05585608855887477,-1.7778584285202825,0.5544738547185861,0.5435751057314887,0.6307650976282688,0.6525625956024638,-0.8950597605653836,-1.0585409953718463,-0.12124858248145988,0.20571388713146563,-0.1321473314685574,0.5217776077572936,-1.9631371613009403,-0.546299792978263,0.9468288182540968,-0.7533760237331159,-0.6443885338621407,-1.3310097200492843,0.009536405363710327,1.2628925388799248,1.2846900368541199,-1.4073009629589668,-3.5325570154429826,-1.5489846997912347,1.6770450003896304,1.143006300021852,-0.1430460804556549,-2.780543335333254,-3.41267077658491,-1.9304409143396477,-0.5136035460169704,1.9713112230412633,-1.178427234229919,-1.603478444726722,-0.12124858248145988,2.025804967976751,1.6443487534283379,-1.243819728152504,-2.7696445863461565,1.3500825307767048,1.6334500044412403,0.14032139320888054,-1.9849346592751353,-5.058381873636635,-3.63064575632686,-0.21933732336533754,1.3173862838154125,0.6852588425637564,-1.4399972099202594,-2.170213392055793,-1.6688709386493072,0.8705375753444141,1.5789562595057527,0.1839163891572706,-2.4099858697719383,-3.0639108089977896,0.2711063810540507,1.8950199801315808,-1.494490954855747,-2.355492124836451,-1.6797696876364048,-0.05585608855887477,0.8487400773702192,-1.9413396633267452,-2.9985183150752044,-1.83235217345577,0.3256001259895383,0.45638511383470853,2.701527405176797,-1.4181997119460643,-3.1728982988687644,-0.5571985419653606,0.7724488344605365,0.9032338223057067,-0.5680972909524581,-2.4753783636945235,-1.6361746916880147,0.6307650976282688,-0.7424772747460183,-0.7860722706944084,-2.845935829255839,-1.7996559264944774,0.5544738547185861,1.186601295970242,1.8296274862089956,-2.0721246511719156,-1.5380859508041371,0.10762514624758798,0.03133390333790536,-0.5027047970298729,1.54626001254446,-0.4155148051330928,-2.3009983799009635,-0.42641355412019033,-0.6879835298105308,-0.840566015629896,-1.0367434973976513,-1.3855034649847717,0.17301764017017307,1.8296274862089956,2.3091724416412864,-1.5271872018170396,-4.088393213784956,-0.42641355412019033,1.Line truncated
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "e0a4aed6-808d-4700-9244-4a6f1729c891",
"metadata": {},
"outputs": [],
"source": [
"import json\n",
"sample_probe = json.loads(probe_data)"
]
},
{
"cell_type": "markdown",
"id": "90e0d110-098b-4198-8963-1acafee4131b",
"metadata": {},
"source": [
"## Sensor Information\n",
"Fill out the sensor's sample frequency, in samples per second, below. This must match the frquency of the captured data in `probe_data`."
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "c1d9d273-ab4a-4b91-a60b-78b3c8c7b6af",
"metadata": {},
"outputs": [],
"source": [
"sensor_frequency = 330"
]
},
{
"cell_type": "markdown",
"id": "750af414-88fe-4cf5-8a80-8340777ebd82",
"metadata": {},
"source": [
"## Filter Design\n",
"Here you design the filter by combining various filter types from SciPy. An example is provided that combines 2 filters.\n",
"\n",
"### Filter Requirements:\n",
"* The filter must be in the SOS (Second Order Sections) format.\n",
"* The filter must be normalized. (hint: SciPy always produces normalized filters by default)\n",
"* The filter must have no more than 5 sections\n",
"* Filter must be assigned to the `filter_design` global"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "71a4fb21-312d-4855-b764-e323cca8c293",
"metadata": {},
"outputs": [],
"source": [
"# set filter settig here. If you dont want a filter to be used, assign `None` to it\n",
"drift_filter_cutoff_frequency = 0.8\n",
"buzz_filter_cutoff_frequency = 150.0\n",
"notch_filter_frequencies = [50.0, 60.0]\n",
"notch_quality = 2.0"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "f379abb0-a734-4a39-a539-31e9aabd035b",
"metadata": {},
"outputs": [],
"source": [
"### Sample Filter Design ###\n",
"filters = []\n",
"\n",
"# The drift filter is a butterworth highpass filter to remove bowden tube bending effects and high frequency noise\n",
"if drift_filter_cutoff_frequency:\n",
" drift_filter = signal.butter(2, drift_filter_cutoff_frequency, btype=\"highpass\", fs=sensor_frequency, output=\"sos\")\n",
" filters.append(drift_filter)\n",
"\n",
"# The buzz filter is a butterworth highpass filter designed to remove stepper buzz\n",
"if buzz_filter_cutoff_frequency:\n",
" buzz_filter = signal.butter(2, buzz_filter_cutoff_frequency, btype=\"lowpass\", fs=sensor_frequency, output=\"sos\")\n",
" filters.append(buzz_filter)\n",
"\n",
"# The notch filter is an iirnotch filter designed to remove noise at a specific frequency\n",
"# such as powerline noise at 60Hz\n",
"if notch_filter_frequencies:\n",
" if len(notch_filter_frequencies) > 2:\n",
" raise \"Klipper supports a max of 2 notch frequencies\"\n",
" for freq in notch_filter_frequencies:\n",
" b, a = signal.iirnotch(freq, notch_quality, fs=sensor_frequency)\n",
" # convert notch from b,a format to sos\n",
" notch_sos = signal.tf2sos(b, a)\n",
" filters.append(notch_sos)\n",
"\n",
"# combine filters as stacked second order sections\n",
"filter_design = np.vstack(filters)"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "b59e5c73-6e4f-4f9e-a0ff-50e1cb2ec6d3",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"SUCCESS: filter_design OK: \n",
" [[ 0.98928717 -1.97857434 0.98928717 1. -1.97845957 0.97868911]\n",
" [ 0.81698985 1.6339797 0.81698985 1. 1.60020175 0.66775766]\n",
" [ 0.8047659 -0.93362005 0.8047659 1. -0.93362005 0.60953181]\n",
" [ 0.77302066 -0.64224877 0.77302066 1. -0.64224877 0.54604131]]\n"
]
}
],
"source": [
"# filter checks\n",
"if len(filter_design) > 4:\n",
" print(\"ERROR: filter_design has more than 5 sections!: \\n\", filter_design)\n",
"elif not np.all(filter_design == filter_design[0,:], axis = 0)[3]:\n",
" print(\"ERROR: filter_design his not normalized!: \\n\", filter_design)\n",
"else:\n",
" print(\"SUCCESS: filter_design OK: \\n\", filter_design)"
]
},
{
"cell_type": "markdown",
"id": "496ab746-28ae-410a-9a75-d9ecc6d32624",
"metadata": {},
"source": [
"### Calculate Filter Initial Consitions (zi)\n",
"This block automatically calculates the filters starting conditions using `signal.sosfilt_zi`.\n",
"\n",
"On the MCU, the tare functionality zeros out the grams value so the inital zi matrix doesnt have to be calculated and there will be no filter settling time."
]
},
{
"cell_type": "code",
"execution_count": 16,
"id": "e3c30cf6-05f4-4e7d-ac2c-e433e8e31ef7",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"filter_zi: \n",
" [[-0.98928717 0.98928717]\n",
" [ 0. 0. ]\n",
" [ 0. 0. ]\n",
" [ 0. 0. ]]\n"
]
}
],
"source": [
"filter_zi = signal.sosfilt_zi(filter_design)\n",
"print(\"filter_zi: \\n\", filter_zi)"
]
},
{
"cell_type": "markdown",
"id": "bd9dd68d-66f6-40a8-873d-77e42eae29ce",
"metadata": {},
"source": [
"## Display Filter Frequency Response\n",
"This block plots the filter's response to sinals from 0 up to the [nyquist frequency]() which is 1/2 the `sensor_frequency`. "
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "6dc22c70-904f-48d7-bb8f-f4404652b122",
"metadata": {
"jupyter": {
"source_hidden": true
}
},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAA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4+reJRt+USHRvFY7YUGYRqelLigrCs9ddghsvS8aj/92LXVkFePS7/bgkSo2Bw02IDefnTFUYHCnQhWE1Zo58Lcygw9R+yZjaLxkHcorx3sZj+GbXKezKKsCcj3egW8sw3JPWEcM6tGDGoImx2QR2ZuXju12nsWp3Ds6XXLgEkEoF9EqKwOXtW+Cy1g1bK4aoKbikVQS+vm0g3t14DM/9+Bf+zFPjqn9twts3XYrurcLlbp7iMDhSoMJy1hzJoWN8KJ697hLcO6YjPvjtON7beAx7ThXh5hVbMbh9DBZd1RVtW4TI3UyqxYncMvx76wl8t+s0ThWUS9vDA3UY1rEFRnSKxeD2LRDFYWvyM2q1CrOHtMGlKeG4ZcUm5BQZMfnNTVg+pSfGdIuXu3mKwuBIgfIdmaNwBkeyiAnR4560jkgfmIo3fjmCDzb9jQ2HzmPMi+sxe3AbzLuiPddMUhiL1YafD+Tgky32/yun4AANRneNx4QeiRjULgYBtV3Ej8gPdE0Mw/zuVqzKj8OGw7m4/ZPteO66HriuTyu5m6YYDI4UqKDcPpWfw2ryig7R46FxXXBj/xQs+t9erDtwDq+tO4Kf95/Fi1N7onOC966rRxfHaLZiY44Kz7/Line truncated
"text/plain": [
"<Figure size 640x480 with 1 Axes>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"# Plot the frequency response\n",
"plt.figure(1)\n",
"plt.clf()\n",
"w, h = signal.sosfreqz(filter_design, fs=sensor_frequency)\n",
"db = 20 * np.log10(np.maximum(np.abs(h), 1e-5))\n",
"plt.plot(w, db, label=\"`filter_design` Frequency Response\")\n",
"plt.xlabel('Frequency (Hz)')\n",
"plt.ylabel('Gain [dB]')\n",
"plt.grid(True)\n",
"plt.legend(loc='best')\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"id": "901a1cba-a299-422b-acfc-d7ea4be5567c",
"metadata": {},
"source": [
"## Test Filter Performance\n",
"Test `filter_design` on `probe_data`. This shows plots of the filters performance when filtering the force graph in `probe_data`.\n",
"\n",
"To help decorate the graphs please prvide the desired trigger threashold of the probe:"
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "502465f6-b578-4b3e-beb4-20ae2e9e7560",
"metadata": {},
"outputs": [],
"source": [
"trigger_force_grams = 60"
]
},
{
"cell_type": "code",
"execution_count": 11,
"id": "0631fb3c-8e54-403e-9da5-cffaa5c1136e",
"metadata": {
"jupyter": {
"source_hidden": true
}
},
"outputs": [],
"source": [
"# perform filtering\n",
"time = sample_probe['time']\n",
"force = sample_probe['force']\n",
"\n",
"approach_time = time[:-400]\n",
"approach_force = force[:-400]\n",
"approach_zi = filter_zi * approach_force[0]\n",
"filtered_approach_force, zf = signal.sosfilt(filter_design, approach_force, zi=approach_zi)\n",
"\n",
"tap_time = time[-400:]\n",
"tap_force = force[-400:]\n",
"tap_zi = filter_zi * tap_force[0]\n",
"filtered_tap_force, zf = signal.sosfilt(filter_design, tap_force, zi=tap_zi)\n",
"\n",
"# graphing functions\n",
"def fft_graph(force, sample_frequency, label):\n",
" # Plot an FFT of the filtered signal:\n",
" from scipy.fft import fft, fftfreq\n",
" # Number of sample points\n",
" N = len(force)\n",
" # sample spacing\n",
" T = 1.0 / sample_frequency\n",
" x = np.linspace(0.0, N*T, N, endpoint=False)\n",
" yf = fft(force)\n",
" xf = fftfreq(N, T)[:N//2]\n",
" plt.plot(xf, 2.0/N * np.abs(yf[0:N//2]), label=label)\n",
" plt.legend(loc='best')\n",
" plt.grid()\n",
" plt.show()\n",
"\n",
"def force_graph(force, filtered_force, time, trigger_force_grams):\n",
" plt.figure(figsize=(12,5))\n",
" plt.plot(time, force, label='Raw Force')\n",
" plt.plot(time, filtered_force, label='Filtered Force')\n",
" plt.axhline(y=trigger_force_grams, color='r', linestyle='-')\n",
" plt.axhline(y=-trigger_force_grams, color='r', linestyle='-')\n",
" plt.legend(loc='best')\n",
" plt.show()"
]
},
{
"cell_type": "markdown",
"id": "f88c0490-d378-4d56-b8cb-2497ec638b68",
"metadata": {},
"source": [
"### Test 1: Probe approach\n",
"This plots the time before the tap. This looks at how well the filter rejects background noise during the probing phase"
]
},
{
"cell_type": "markdown",
"id": "30e4ed61-7bab-4d2e-87d1-5cd2e4251b66",
"metadata": {},
"source": [
"#### `force` vs force filtered with `filter_design`\n",
"In this graph we are looking to see the 'Filtered Force' line remain inside the red lines denoting the trigger force. A Properly filtered force grpah will be horizontal."
]
},
{
"cell_type": "code",
"execution_count": 12,
"id": "af04e393-fe9b-4657-89d7-6ec079d820ce",
"metadata": {},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAA90AAAGsCAYAAADAL8TLAAAAOnRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjEwLjAsIGh0dHBzOi8vbWF0cGxvdGxpYi5vcmcvlHJYcgAAAAlwSFlzAAAPYQAAD2EBqD+naQAAi61JREFUeJzs3Xd4FMUfx/H35dIIJKGEJAQChN577yAdbNgBBUUU6aDyE0FAEVARGyqKFUXFgh1QEJAivffeQgmhJkBIu7vfH5tccrlLA45QPq/nyZO73dnd2b29vf3OzM6YbDabDRERERERERG55jzyOgMiIiIiIiIityoF3SIiIiIiIiJuoqBbRERERERExE0UdIuIiIiIiIi4iYJuERERERERETdR0C0iIiIiIiLiJgq6RURERERERNzEM68zcLWsVivHjx/H398fk8mU19kRERERERGRW5zNZuPChQuEhYXh4ZF1XfZNH3QfP36c8PDwvM6GiIiIiIiI3GYiIyMpUaJElmlu+qDb398fMHY2ICAgj3MjIiIiIiIit7rY2FjCw8Pt8WhWbvqgO7VJeUBAgIJuERERERERuW5y8oizOlITERERERERcRMF3SIiIiIiIiJuoqBbRERERERExE1u+me6RUREREREsmO1WklMTMzrbMhNwsvLC7PZfE3WpaBbRERERERuaYmJiRw8eBCr1ZrXWZGbSMGCBQkNDc1RZ2lZUdAtIiIiIiK3LJvNxokTJzCbzYSHh+PhoSdsJWs2m424uDiio6MBKFas2FWtT0G3iIiIiIjcspKTk4mLiyMsLAw/P7+8zo7cJPLlywdAdHQ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t28f27Zto3nz5uzfv58lS5Zw/vx56tati7+/f5b5CAwMtOcjPZvN5vSMuquG1PkzVI7my5cv021ZU5qYz5kzh+LFizvMc1n5ehNw69k2bNgwmjRpwsSJE3nwwQdZs2YN06dPN0paME74oUOHMnHiRMqXL0/58uWZOHEifn5+dO/e3Z1ZExERERERuamMHTuWTp068cwzzxAWFsayZcto0qQJ/fv3t6fZv3+/wzLVqlWjSJEivPrqq9SsWZOAgABatmzJpEmTOHfuHC1btrzi/FSpUoXly5c7TFuxYgUVKlSw13K7UqNGDRYuXOiyr64qVarg4+PDkSNHripvNxK3jtNdv359fvnlF7777juqVavG+PHjeeedd+jRo4c9zYgRIxg6dCj9+/enXr16HDt2jPnz52db2iIiIiIiInI7adWqFVWrVmXixIkAlCtXjnXr1vH333+zZ88eXnrpJdauXeuwjMlkokWLFsycOZNWrVoBRtCbmJjIwoUL7dOuxLPPPsvChQsZP348e/bsYcaMGbz//vs899xzWS43cuRI1q5dS//+/dmyZQu7du1i2rRpnD59Gn9/f5577jmGDRvGjBkz2L9/Pxs3buSDDz5gxowZV5zXvOTWoBuga9eubN26lfj4eHbu3GkfLiyVyWRi3LhxnDhxgvj4eJYsWUK1atXcnS0REREREZGbzvDhw/nkk0+IjIykX79+dOvWjYceeoiGDRty5swZh1rvVK1bt8ZisdgDbJPJRPPmzQFo1qzZFeelTp06/PDDD8yaNYtq1aoxZswYXnnlFXr37p3lchUqVGD+/Pls3ryZBg0a0LhxY3777Tc8PY2G2OPHj2fMmDFMmjSJypUr06FDB/744w8iIiKuOK95ya29l18PsbGxBAYG5qjXOBERERERub3Ex8dz8OBBIiIi8M3YGZZIFrI6d3ITh7q9pltERERERETkdqWgW0RERERERMRNFHSLiIiIiIiIuImCbhERERERERE3UdAtIiIiIiIi4iYKukVERERERETcREG3iIiIiIiIiJso6BYRERERERFxEwXdIiIiIiIiN5FWrVoxdOhQ+/vSpUvzzjvv5Fl+XDGZTPz66695nY0bgoJuERERERGRG0zv3r0xmUxOf/v27ePnn39m/PjxmS57MwS8We3frcYzrzMgIiIiIiIizjp27MgXX3zhMK1o0aKYzebrsv2kpCS8vLzctv7M9u9KJCYm4u3tfS2ydc2ppltEREREROQG5OPjQ2hoqMOf2Wx2al6eXunSpQG49957MZlM9vcAf/zxB3Xr1sXX15cyZcrw8ssvk5ycbJ9vMpn46KOPuPvuu8mfPz+vvvpqjpbbu3cvLVq0wNfXlypVqrBgwYKr2j+AJUuW0KBBA3x8fChWrBgvvPCCwzZbtWrFwIEDGT58OEFBQbRr1w6A7du306VLFwICAvD396d58+bs37/fvtwXX3xB5cqV8fX1pVKlSnz44Yc5yuvVUE23iIiIiIjcPmw2SIrLm217+YHJ5NZNrF27luDgYL744gs6duxoD2L//vtvevbsyXvvvWcPRJ966ikAxo4da19+7NixTJo0ibfffhuz2ZztclarlW7duhEUFMSqVauIjY3NtEAgp44dO0bnzp3p3bs3X331Fbt27aJv3774+voybtw4e7oZM2bwzDPP8N9//2Gz2Th27BgtWrSgVatWLFq0iICAAP777z97sP7JJ58wduxY3n//fWrXrs3GjRvp27cv+fPnp1evXleV56wo6BYRERERkdtHUhxMDMubbb94HLzz5zj5n3/+SYECBezvO3XqxI8//pjlMqnNswsWLEhoaKh9+oQJE3jhhRfswWWZMmUYP348I0aMcAi6u3fvzhNPPGF//+ijj2a53D///MPOnTs5dOgLine truncated
"text/plain": [
"<Figure size 1200x500 with 1 Axes>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"force_graph(approach_force, filtered_approach_force, approach_time, trigger_force_grams)"
]
},
{
"cell_type": "markdown",
"id": "a4f51bc6-783e-4ace-be0d-a6c9b527e864",
"metadata": {},
"source": [
"#### FFT of `probe_data` before and after filtering"
]
},
{
"cell_type": "code",
"execution_count": 13,
"id": "6976546f-6984-488d-96f4-4c6c4b8a0a71",
"metadata": {
"jupyter": {
"source_hidden": true
}
},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAiwAAAGdCAYAAAAxC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5vHStXrtSQIUN8wzWZPXu2Ro4cqdjYWN1yyy2aPXu26dCH1+tVaWmpnnzySc2ZM0eRkZG65557dOONNyo/P9+3PTt27NDf/vY3LV68WE6nU3fccYfuuusuzZs3zzfPP//5T8XGxmrZsmUyDEPHjx/XiBEjNGDAAK1bt04HDx7UnXfeqbvvvltz5syRJB07dkzjx49XTk6OJOn555/XyJEjtXXrVsXGxsrr9So7O1slJSV688031bFjR3311Vey2Wy+/aK0tFTPPPOM3njjDYWFhWnChAl66KGHfG07U1W9qpY/069//WstWLBAc+bMUXp6up555hldeeWV2rp1q+x2uwzDkCRNmTJFTz/9tC644AK1atVKjz76qP7yl7/oueee06WXXqri4mJ9/fXXvjYOHz5cl156qfLy8hQREaEnn3xSI0aMUEFBQY29Uf7a6W96feermscwDLnd7mq9MIF+VjRoYHnjjTcUGxtba29MlS5dumju3Lnq2bOnnE6nXnjhBf30pz/V5s2b1blz5xqXmTlzpmbMmFFt/PLly4PaLXn0aLgkmzYXbJa3qCBo620KcnNzQ90ES6EeZlauR0REhJKTk3X8+HG5XC6VuTwa9PzakLRlzeSBio4MrBvd7XZryZIliouLk8fj8Z3n9+STT/r+aJOkyZMn+/4/atQorVq1Su+8845GjBghSRo0aJByc3OVmZmp3Nxc3XjjjXrnnXf06aefqlOnTlqzZo3uvPNO0zpP5/V6NWfOHD399NNyOp0aOXKkHnroIRUUFPh608vLy+V2uzVz5kzf4YKXXnpJAwYMUF5envr16yeXy6Xy8nK9+OKLateunaSTn+3jxo3TY489pqSkJLndbsXExOi5557zffnOnj1bpaWleumll9SiRQt16NBBTz31lG666Sb99re/VWJiovr3729q89NPP6333ntPH374oUaMGKF//etf+vTTT7Vu3Tp16tRJkjRkyBBJJ/8Armr/M888o4yMDEnSbbfdpmeeeabWulT18Fx66aWmy3iXLl2qjh07atasWXrllVf005/+VJL07LPPKjc3V6+99pruu+8+lZWVSZIeeeQRDRgwQJJUUlKiF198UU8//bSuu+46SVLbtm110UUXyel0+sLTc8895wu+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jRokNxut8LCwnw98bXd0CwsLEx2u71a2wzDqHMZSUpPT/f9js7c5kDqERv7w37SokUL37prel3DMNSvXz/99a9/rTatbdu2NS5TVzsDmX7mfLW17cx5bTZbjZ8LgX5ONNh9WGbPnq1+/fqZ0mmgDMNQQUGBKT0DQEOx2WyKiYxo0J/oyPAax//YZxg99thjevbZZ7Vv3z5JJ/9YHDx4sO666y716dNHnTp10jfffGNapkePHmrTpo2eeOIJ9erVS3FxcRo6dKhWrVqlvLw8DR06tNbXO3z4sBYvXqz58+eroKDA9HP8+HF9+OGHvnkrKyu1YcMG3/DWrVt19OhRdenSxTeuqKjI13ZJWrNmjcLCwur8ouzWrZsKCgp04sQJ37h///vfpuVWr16t++67TyNHjlT37t3lcDh8JxpL0kUXXaRvv/1W27Ztq/V1gqlTp06KjIzUxx9/7BvndruLine truncated
"text/plain": [
"<Figure size 640x480 with 1 Axes>"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAiwAAAGdCAYAAAAxCSikAAAAOnRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjEwLjAsIGh0dHBzOi8vbWF0cGxvdGxpYi5vcmcvlHJYcgAAAAlwSFlzAAAPYQAAD2EBqD+naQAAWIpJREFUeJzt3XlcVFX/B/DPAAOICi4oiyKSuZHmghq4V4ppLi2m5ZPmk9bPbNFs06wntcWsVLRSW0yyJ5V61MwkFcsd3BDcF1QEFRBBYFhkmOX+/pgYucwwzAzDzGX4vF8vXsq9594598uZud8599xzZYIgCCAiIiKSMBdHV4CIiIioOkxYiIiISPKYsBAREZHkMWEhIiIiyWPCQkRERJLHhIWIiIgkjwkLERERSR4TFiIiIpI8N0dXwFa0Wi0yMjLQuHFjyGQyR1eHiIiIzCAIAgoLCxEYGAgXl6r7UZwmYcnIyEBQUJCjq0FERERWuHbtGlq3bl3leqdJWBo3bgxAd8De3t42269KpcLOnTsRGRkJuVxus/3WZYyJGOMhxng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tVbtngPM2EhIskqvy2Line truncated
"text/plain": [
"<Figure size 640x480 with 1 Axes>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"fft_graph(approach_force, sensor_frequency, \"Raw Approach Force FFT\")\n",
"fft_graph(filtered_approach_force, sensor_frequency, \"Filtered Approach Force FFT\")"
]
},
{
"cell_type": "markdown",
"id": "83869a95-ba19-49b6-b503-2129f4131424",
"metadata": {},
"source": [
"### Test 2: Tap Phase\n",
"This plots the time of the tap. This looks at how well the filter performed during the tap."
]
},
{
"cell_type": "markdown",
"id": "94a213ae-66d0-4ae7-8126-d24b41fba683",
"metadata": {},
"source": [
"#### `force` vs force filtered with `filter_design`\n",
"For the tap we want to see the 'Filtered Force' line cross the red boundaries to trigger the endstop. If the 'Filtered Force' stays inside the red lines then the tap would not have triggered the endstop and a crash of the toolhead would result.\n",
"\n",
"Pay attention to how much lag there is between the 'Raw Force' graph and the 'Filtered Force' lines. Significant lag will subject the printer to higher forces before triggering."
]
},
{
"cell_type": "code",
"execution_count": 14,
"id": "bd7173d7-b048-48b5-aea5-27d1477fa949",
"metadata": {},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAA+UAAAGsCAYAAAC7CwYHAAAAOnRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjEwLjAsIGh0dHBzOi8vbWF0cGxvdGxpYi5vcmcvlHJYcgAAAAlwSFlzAAAPYQAAD2EBqD+naQAAoF9JREFUeJzs3Xd8U/X+x/FX0pHuTRdQ9t5DpgioCF7FgRtFuSpur4r+vOq9V1Eveq9ex1Wv46pXcG/cCoiyBGQIyN7QQimFQvdImuT3x7cNlJZNOW3zfj4eeeTk5CT5dCbv8102r9frRUREREREREROObvVBYiIiIiIiIj4K4VyEREREREREYsolIuIiIiIiIhYRKFcRERERERExCIK5SIiIiIiIiIWUSgXERERERERsYhCuYiIiIiIiIhFAq0u4FTweDxkZmYSGRmJzWazuhwRERERERFp4LxeLwUFBaSmpmK3H7o93C9CeWZmJk2bNrW6DBEREREREfEzGRkZNGnS5JD3+0Uoj4yMBMw3IyoqyuJqREREREREpKHLz8+nadOmvjx6KH4Ryiu7rEdFRSmUi4iIiIiIyClzpCHUmuhNRERERERExCIK5SIiIiIiIiIWUSgXERERERERsUitjimfPXs2Tz/9NEuWLGHnzp1MmTKFiy66yHf/2LFjmTx5cpXH9O3blwULFvhul5WVcd999/HBBx9QUlLCWWedxcsvv3zY2etERERERESOldvtxuVyWV2G1BNBQUEEBASc8PPUaigvKiqiW7du/PGPf+SSSy6p8ZgRI0bw1ltv+W4HBwdXuf/uu+/m66+/5sMPPyQ+Pp57772X888/nyVLlpyUb4CIiIiIiPg3r9dLVlYWubm5Vpci9UxMTAzJyclHnMztcGo1lJ977rmce+65hz3G4XCQnJxc4315eXm8+eabvPPOO5x99tkAvPvuuzRt2pQff/yR4cOHn/SaRURERETEv1QG8sTERMLCwk4oYIl/8Hq9FBcXk52dDUBKSspxP5flS6LNnDmTxMREYmJiGDx4MBMnTiQxMRGAJUuW4HK5OOecc3zHp6am0rlzZ+bNm3fIUF5WVkZZWZnvdn5+fu1+ESIiIiIiUi+53W5fII+Pj7e6HKlHQkNDAcjOziYxMfG4e3JbOtHbueeey3vvvcdPP/3EM888w6JFizjzzDN9gTorK4vg4GBiY2OrPC4pKYmsrKxDPu+TTz5JdHS079K0adNa/TpERERERKR+qhxDHhYWZnElUh9V/t6cyFwElraUX3HFFb7tzp0707t3b5o1a8a3337LqFGjDvk4r9d72C4lDz74IOPHj/fdzs/PVzAXEREREZFDUpd1OR4n4/emTi2JlpKSQrNmzdiwYQMAycnJOJ1O9u3bV+W47OxskpKSDvk8DoeDqKioKhcRERERERGRuqZOhfKcnBwyMjJ8g+R79epFUFAQ06dP9x2zc+dOVq5cyYABA6wqU0REREREROSkqNXu64WFhWzcuNF3e8uWLSxbtoy4uDji4uKYMGECl1xyCSkpKWzdupWHHnqIhIQELr74YgCio6O54YYbuPfee4mPjycuLo777ruPLl26+GZjFxEREREREamvarWlfPHixfTo0YMePXoAMH78eHr06MHDDz9MQEAAK1as4MILL6Rt27Zcd911tG3blvnz5xMZGel7jueee46LLrqIyy+/nIEDBxIWFsbXX3+tNcpFRERERMSvjR07FpvNhs1mIzAwkLS0NG699dZqw39r25AhQ3x1HHgpLy8/pXXUV7XaUj5kyBC8Xu8h7586deoRnyMkJIQXX3yRF1988WSWJiIiInJqFO+FvAxo1AECg62uRkQamBEjRvDWW29RXl7O6tWruf7668nNzeWDDz44pXWMGzeOxx57rMq+wMDji5tOp5PgYP/5f1mnxpSLiIiINAgl+2DWU/Dv7vBUC3jtDPjvEMhea+4vL7OyOhE5Aq/XS7Gz3JLL4Ro1a+JwOEhOTqZJkyacc845XHHFFUybNs13v9vt5oYbbqBFixaEhobSrl07/v3vf/vuX7FiBXa7nT179gCwb98+7HY7l112me+YJ598kv79+x+2jrCwMJKTk6tcKn322Wd06tQJh8NB8+bNeeaZZ6o8tnnz5vz9739n7NixREdHM27cOAB++eUXBg8eTFhYGLGxsQwfPtzXC8Dr9fLUU0/RsmVLQkND6datG59++ukxfe/qCkuXRBMRERFpUDxumPcizH4anIX79wc4IHuVCebhjSAvHRr3hsvfhujGlpUrIjUrcbnp+PCRe/XWhtWPDScs+Phi2ubNm/nhhx8ICgry7fN4PDRp0oSPP/6YhIQE5s2bx0033URKSgqXX345nTt3Jj4+nlmzZnHJJZcwe/Zs4uPjmT17tu85Zs6cyeDBg4+rpiVLlnD55ZczYcIErrjiCubNm8dtt91GfHw8Y8eO9R339NNP87e//Y2//vWvACxbtoyzzjqL66+/nhdeeIHAwEB+/vln3G43AH/961/5/PPPeeWVV2jTpg2zZ8/mmmuuoVGjRsddq1Vs3mM9FVMP5efnEx0dTV5enpZHExERkdqxbxt8eTtsnWNuJ3WGgXdB67PBUw5TboZNP1V9TGQKXPUhpHY/5eWKiFFaWsqWLVto0aIFISEhABQ7y+tFKB87dizvvvsuISEhuN1uSktLAXj22We55557Dvm422+/nV27dvlali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rdDiOeBHsgrPwMvv6TZmMXEQDGjh2Line truncated
"text/plain": [
"<Figure size 1200x500 with 1 Axes>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"force_graph(tap_force, filtered_tap_force, tap_time, trigger_force_grams)"
]
},
{
"cell_type": "markdown",
"id": "62286828-e971-4e43-a1d7-f412ec45af06",
"metadata": {},
"source": [
"#### FFT of `probe_data` before and after filtering"
]
},
{
"cell_type": "code",
"execution_count": 15,
"id": "222956e3-df60-4152-a914-3741f9e46c57",
"metadata": {
"jupyter": {
"source_hidden": true
}
},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAigAAAGgCAYAAACABpytAAAAOnRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjEwLjAsIGh0dHBzOi8vbWF0cGxvdGxpYi5vcmcvlHJYcgAAAAlwSFlzAAAPYQAAD2EBqD+naQAAR2xJREFUeJzt3Xt8FNX9P/7X7O7sLTdygWwWAgQFqYSiXERDhaAmiAVrqaJCFXtRKkJNwRsfaw1eQNEiLVSr1Q/SWj7Y/ip+qbVCaCGI0RoDKBfLRUK4xgiE3DbZnd09vz82O2Szm2QTNju5vJ6Pxz7Izs7OnnlnQl4558yMJIQQICIiIupCdFo3gIiIiKg5BhQiIiLqchhQiIiIqMthQCEiIqIuhwGFiIiIuhwGFCIiIupyGFCIiIioy2FAISIioi6HAYWIiIi6HAYUIiIi6nLaHVC2b9+O6dOnw263Q5IkvPvuuy2uO3fuXEiShJUrVwYsdzqdWLBgAVJSUhATE4Obb74ZJ06caG9TiIiIqIcytPcNdXV1GDVqFH70ox/hBz/4QYvrvfvuu/jPf/4Du90e9FpeXh7+/ve/Y/369UhOTsaiRYswbdo0lJSUQK/Xt9kGr9eLU6dOIS4uDpIktXcXiIiISANCCNTU1MBut0Ona6OPRFwEAGLDhg1By0+cOCH69+8v9u7dKwYNGiReeukl9bXz588LWZbF+vXr1WUnT54UOp1OfPDBB2F97vHjxwUA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c2bdqEgwcP4oknnkBxcXHAe/zzUN566y1kZ2cD8P3Cdrlc+Ne//qUua69LL70U77zzDnbv3o3PP/8cs2bNUiedNvXRRx9h+fLlOHjwIH73u9/hr3/9Kx588MEOfebs2bNhNpsxZ84c7N27F1u3bsWCBQtw1113qcM7odx5552w2Wy45ZZb8NFHH+HIkSP429/+ho8//hgA8Ktf/Qp//OMfkZ+fj3379uHLL7/E22+/jV/+8pcdamdXxoDShF53oQfFwyEeIqKLsnDhQvzhD3/A8ePHMXfuXEyfPh133nknxo8fj7Nnz2LevHlB75k8eTI8Ho8aRiRJwrXXXgsA+M53vtOhdrz00ktITExEVlYWpk+fjilTpmD06NFB6y1atAglJSW48sor8fTTT+PXv/41pkzp2Bwgq9WKTZs24dy5cxg3bhxuvfVWXH/99Vi9enWr7zMajdi8eTP69euHm266CSNHjsRzzz2n3hV4ypQpeO+991BQUIBx48bh6quvxooVKzBo0KAOtbMrk0R7T3bvAqqrq5GQkICqqirEx8dHbLtCCGQsfh8A8Mlj2bD1iWnjHb2Doih4//33cdNNNwWcNthbsR7BWJNgHalJQ0MDSktLkZGR0ep8gu7I6/WiurpaPYunqxk8eDDy8vKQl5cXtc/s6jXpqNaO4/b8/u45FYkASZLUXhQO8RAREWmHAaUZ/6nGbg7xEBERaYZn8TRj0EtwugE3r9ZGRNRrhDqrh7TFHpRm2INCRESkPQaUZgyNE5U4B4WItNINz10gUkXq+GVAacZ/sTb2oBBRtPnP9nE4HBq3hKjj/Ffo9Z8a3VGcg9KM3DjEo7AHhYiiTK/Xo0+fPqioqADgu5ZGW5da7y68Xi9cLhcaGhp61Cm1F6Mn1sTr9eKbb76B1WqFwXBxEYMBpRl940HCC7URkRZsNhsAqCGlpxBLine truncated
"text/plain": [
"<Figure size 640x480 with 1 Axes>"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAh8AAAGdCAYAAACyzRGfAAAAOnRFWHRTb2Z0d2FyZQBN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P/Px8SJIU8tV6ilUhBPLz85GRkYG4uDjMmzcPRUVFYS90XwWUAacc80FERKS1Hrd8jBs3DpWVlcrXoUOHlH1PPfUUNmzYgE2bNqGwsBB2ux25ubmor68Pa6H7SrTtdmH2ICIi0kyPw0dMTAzsdrvyNXjwYADBVo+NGzdizZo1WLRoEcaPH4/NmzfD6XRiy5YtYS94X8ir2LLbhYiISHs9XtultLQUGRkZsFgsmDFjBtatW4cRI0agrKwMVVVVyMvLU461WCyYO3cudu/ejaVLl7b7fG63G263W7nvcDgABBflaW9Bp76Qn08OGxKCI039fhH217pUyO9br++/LdaHGutEjXUSivWhpsc66cl7lYTo/r/97777LpxOJ0aNGoUzZ87g8ccfx5EjR1BUVISSkhJcddVVOH36NDIyMpTH3HfffSgvL8f777/f7nPm5+dj7dq1qu1btmyB1Wrt9hvpidWfGuEOSPjBZX68cNSIgRaBX03Line truncated
"text/plain": [
"<Figure size 640x480 with 1 Axes>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"fft_graph(tap_force, sensor_frequency, \"Raw Tap Force FFT\")\n",
"fft_graph(filtered_tap_force, sensor_frequency, \"Filtered Tap Force FFT\")"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.13.2"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
+14 -5
View File
@@ -2,11 +2,20 @@
# the Klipper host software (Klippy). These package requirements are
# typically installed via the command:
# pip install -r klippy-requirements.txt
cffi==1.14.6
pyserial==3.4
# greenlet is used by the reactor.py code
greenlet==2.0.2 ; python_version < '3.12'
greenlet==3.0.3 ; python_version >= '3.12'
greenlet==3.1.1 ; python_version >= '3.12'
# cffi is used by "chelper" code and by greenlet
cffi==1.14.6 ; python_version < '3.12'
cffi==1.17.1 ; python_version >= '3.12'
# Jinja2 is used by gcode_macro.py
Jinja2==2.11.3
markupsafe==1.1.1 # Needed by Jinja2
# pyserial is used by serialhdl.py (for USB and UART mcu connections)
pyserial==3.4
# python-can is used by serialhdl.py (for canbus mcu connections)
python-can==3.3.4
markupsafe==1.1.1
setuptools==75.6.0 ; python_version >= '3.12' # Needed by python-can
setuptools==78.1.1 ; python_version >= '3.12' # Needed by python-can
# msgspec is an optional dependency of webhooks.py
msgspec==0.19.0 ; python_version >= '3.9'
+3 -1
View File
@@ -1302,7 +1302,9 @@ class MCUConnection:
else:
if bus not in bus_enums:
raise SPIFlashError("Invalid SPI Bus: %s" % (bus,))
bus_cmds = SPI_BUS_CMD % (SPI_OID, bus, SPI_MODE, SD_SPI_SPEED)
bus_cmds = [
SPI_BUS_CMD % (SPI_OID, bus, SPI_MODE, SD_SPI_SPEED),
]
if cs_pin not in pin_enums:
raise SPIFlashError("Invalid CS Pin: %s" % (cs_pin,))
cfg_cmds = [ALLOC_OIDS_CMD % (1,),]
+8
View File
@@ -177,6 +177,14 @@ config NEED_SENSOR_BULK
depends on WANT_ADXL345 || WANT_LIS2DW || WANT_MPU9250 || WANT_ICM20948 \
|| WANT_HX71X || WANT_ADS1220 || WANT_LDC1612 || WANT_SENSOR_ANGLE
default y
config WANT_LOAD_CELL_PROBE
bool
depends on WANT_HX71X || WANT_ADS1220
default y
config NEED_SOS_FILTER
bool
depends on WANT_LOAD_CELL_PROBE
default y
menu "Optional features (to reduce code size)"
depends on HAVE_LIMITED_CODE_SIZE
config WANT_ADC
+2
View File
@@ -27,3 +27,5 @@ src-$(CONFIG_WANT_ADS1220) += sensor_ads1220.c
src-$(CONFIG_WANT_LDC1612) += sensor_ldc1612.c
src-$(CONFIG_WANT_SENSOR_ANGLE) += sensor_angle.c
src-$(CONFIG_NEED_SENSOR_BULK) += sensor_bulk.c
src-$(CONFIG_NEED_SOS_FILTER) += sos_filter.c
src-$(CONFIG_WANT_LOAD_CELL_PROBE) += load_cell_probe.c
+1 -1
View File
@@ -1,4 +1,4 @@
CROSS_PREFIX=or1k-linux-musl-
CROSS_PREFIX=or1k-elf-
dirs-y += src/generic src/ar100 lib/ar100
CFLAGS += -O3
+8 -1
View File
@@ -299,6 +299,13 @@ command_get_uptime(uint32_t *args)
}
DECL_COMMAND_FLAGS(command_get_uptime, HF_IN_SHUTDOWN, "get_uptime");
// Similar to timer_is_before(), but handles full 32bit duration
static int
timer_has_elapsed(uint32_t start, uint32_t cur, uint32_t duration)
{
return (uint32_t)(cur - start) >= duration;
}
#define SUMSQ_BASE 256
DECL_CONSTANT("STATS_SUMSQ_BASE", SUMSQ_BASE);
@@ -322,7 +329,7 @@ stats_update(uint32_t start, uint32_t cur)
nextsumsq = 0xffffffff;
sumsq = nextsumsq;
if (timer_is_before(cur, stats_send_time + timer_from_us(5000000)))
if (!timer_has_elapsed(stats_send_time, cur, timer_from_us(5000000)))
return;
sendf("stats count=%u sum=%u sumsq=%u", count, sum, sumsq);
if (cur < stats_send_time)
+298
View File
@@ -0,0 +1,298 @@
// Load Cell based end stops.
//
// Copyright (C) 2025 Gareth Farrington <gareth@waves.ky>
//
// This file may be distributed under the terms of the GNU GPLv3 license.
#include "basecmd.h" // oid_alloc
#include "command.h" // DECL_COMMAND
#include "sched.h" // shutdown
#include "trsync.h" // trsync_do_trigger
#include "board/misc.h" // timer_read_time
#include "sos_filter.h" // fixedQ12_t
#include "load_cell_probe.h" //load_cell_probe_report_sample
#include <stdint.h> // int32_t
#include <stdlib.h> // abs
// Q2.29
typedef int32_t fixedQ2_t;
#define FIXEDQ2 2
#define FIXEDQ2_FRAC_BITS ((32 - FIXEDQ2) - 1)
// Q32.29 - a Q2.29 value stored in int64
typedef int64_t fixedQ32_t;
#define FIXEDQ32_FRAC_BITS FIXEDQ2_FRAC_BITS
// Q16.15
typedef int32_t fixedQ16_t;
#define FIXEDQ16 16
#define FIXEDQ16_FRAC_BITS ((32 - FIXEDQ16) - 1)
// Q48.15 - a Q16.15 value stored in int64
typedef int64_t fixedQ48_t;
#define FIXEDQ48_FRAC_BITS FIXEDQ16_FRAC_BITS
#define MAX_TRIGGER_GRAMS ((1 << FIXEDQ16) - 1)
#define ERROR_SAFETY_RANGE 0
#define ERROR_OVERFLOW 1
#define ERROR_WATCHDOG 2
// Flags
enum {FLAG_IS_HOMING = 1 << 0
, FLAG_IS_HOMING_TRIGGER = 1 << 1
, FLAG_AWAIT_HOMING = 1 << 2
};
// Endstop Structure
struct load_cell_probe {
struct timer time;
uint32_t trigger_grams, trigger_ticks, last_sample_ticks, rest_ticks;
uint32_t homing_start_time;
struct trsync *ts;
int32_t safety_counts_min, safety_counts_max, tare_counts;
uint8_t flags, trigger_reason, error_reason, watchdog_max
, watchdog_count;
fixedQ16_t trigger_grams_fixed;
fixedQ2_t grams_per_count;
struct sos_filter *sf;
};
static inline uint8_t
overflows_int32(int64_t value) {
return value > (int64_t)INT32_MAX || value < (int64_t)INT32_MIN;
}
// returns the integer part of a fixedQ48_t
static inline int64_t
round_fixedQ48(const int64_t fixed_value) {
return fixed_value >> FIXEDQ48_FRAC_BITS;
}
// Convert sensor counts to grams
static inline fixedQ48_t
counts_to_grams(struct load_cell_probe *lce, const int32_t counts) {
// tearing ensures readings are referenced to 0.0g
const int32_t delta = counts - lce->tare_counts;
// convert sensor counts to grams by multiplication: 124 * 0.051 = 6.324
// this optimizes to single cycle SMULL instruction
const fixedQ32_t product = (int64_t)delta * (int64_t)lce->grams_per_count;
// after multiplication there are 30 fraction bits, reduce to 15
// caller verifies this wont overflow a 32bit int when truncated
const fixedQ48_t grams = product >>
(FIXEDQ32_FRAC_BITS - FIXEDQ48_FRAC_BITS);
return grams;
}
static inline uint8_t
is_flag_set(const uint8_t mask, struct load_cell_probe *lce)
{
return !!(mask & lce->flags);
}
static inline void
set_flag(uint8_t mask, struct load_cell_probe *lce)
{
lce->flags |= mask;
}
static inline void
clear_flag(uint8_t mask, struct load_cell_probe *lce)
{
lce->flags &= ~mask;
}
void
try_trigger(struct load_cell_probe *lce, uint32_t ticks)
{
uint8_t is_homing_triggered = is_flag_set(FLAG_IS_HOMING_TRIGGER, lce);
if (!is_homing_triggered) {
// the first triggering sample when homing sets the trigger time
lce->trigger_ticks = ticks;
// this flag latches until a reset, disabling further triggering
set_flag(FLAG_IS_HOMING_TRIGGER, lce);
trsync_do_trigger(lce->ts, lce->trigger_reason);
}
}
void
trigger_error(struct load_cell_probe *lce, uint8_t error_code)
{
trsync_do_trigger(lce->ts, lce->error_reason + error_code);
}
// Used by Sensors to report new raw ADC sample
void
load_cell_probe_report_sample(struct load_cell_probe *lce
, const int32_t sample)
{
// only process samples when homing
uint8_t is_homing = is_flag_set(FLAG_IS_HOMING, lce);
if (!is_homing) {
return;
}
// save new sample
uint32_t ticks = timer_read_time();
lce->last_sample_ticks = ticks;
lce->watchdog_count = 0;
// do not trigger before homing start time
uint8_t await_homing = is_flag_set(FLAG_AWAIT_HOMING, lce);
if (await_homing && timer_is_before(ticks, lce->homing_start_time)) {
return;
}
clear_flag(FLAG_AWAIT_HOMING, lce);
// check for safety limit violations
const uint8_t is_safety_trigger = sample <= lce->safety_counts_min
|| sample >= lce->safety_counts_max;
// too much force, this is an error while homing
if (is_safety_trigger) {
trigger_error(lce, ERROR_SAFETY_RANGE);
return;
}
// convert sample to grams
const fixedQ48_t raw_grams = counts_to_grams(lce, sample);
if (overflows_int32(raw_grams)) {
trigger_error(lce, ERROR_OVERFLOW);
return;
}
// perform filtering
const fixedQ16_t filtered_grams = sosfilt(lce->sf, (fixedQ16_t)raw_grams);
// update trigger state
if (abs(filtered_grams) >= lce->trigger_grams_fixed) {
try_trigger(lce, lce->last_sample_ticks);
}
}
// Timer callback that monitors for timeouts
static uint_fast8_t
watchdog_event(struct timer *t)
{
struct load_cell_probe *lce = container_of(t, struct load_cell_probe
, time);
uint8_t is_homing = is_flag_set(FLAG_IS_HOMING, lce);
uint8_t is_homing_trigger = is_flag_set(FLAG_IS_HOMING_TRIGGER, lce);
// the watchdog stops when not homing or when trsync becomes triggered
if (!is_homing || is_homing_trigger) {
return SF_DONE;
}
if (lce->watchdog_count > lce->watchdog_max) {
trigger_error(lce, ERROR_WATCHDOG);
}
lce->watchdog_count += 1;
// A sample was recently delivered, continue monitoring
lce->time.waketime += lce->rest_ticks;
return SF_RESCHEDULE;
}
static void
set_endstop_range(struct load_cell_probe *lce
, int32_t safety_counts_min, int32_t safety_counts_max
, int32_t tare_counts, uint32_t trigger_grams
, fixedQ2_t grams_per_count)
{
if (!(safety_counts_max >= safety_counts_min)) {
shutdown("Safety range reversed");
}
if (trigger_grams > MAX_TRIGGER_GRAMS) {
shutdown("trigger_grams too large");
}
// grams_per_count must be a positive fraction in Q2 format
const fixedQ2_t one = 1 << FIXEDQ2_FRAC_BITS;
if (grams_per_count < 0 || grams_per_count >= one) {
shutdown("grams_per_count is invalid");
}
lce->safety_counts_min = safety_counts_min;
lce->safety_counts_max = safety_counts_max;
lce->tare_counts = tare_counts;
lce->trigger_grams = trigger_grams;
lce->trigger_grams_fixed = trigger_grams << FIXEDQ16_FRAC_BITS;
lce->grams_per_count = grams_per_count;
}
// Create a load_cell_probe
void
command_config_load_cell_probe(uint32_t *args)
{
struct load_cell_probe *lce = oid_alloc(args[0]
, command_config_load_cell_probe, sizeof(*lce));
lce->flags = 0;
lce->trigger_ticks = 0;
lce->watchdog_max = 0;
lce->watchdog_count = 0;
lce->sf = sos_filter_oid_lookup(args[1]);
set_endstop_range(lce, 0, 0, 0, 0, 0);
}
DECL_COMMAND(command_config_load_cell_probe, "config_load_cell_probe"
" oid=%c sos_filter_oid=%c");
// Lookup a load_cell_probe
struct load_cell_probe *
load_cell_probe_oid_lookup(uint8_t oid)
{
return oid_lookup(oid, command_config_load_cell_probe);
}
// Set the triggering range and tare value
void
command_load_cell_probe_set_range(uint32_t *args)
{
struct load_cell_probe *lce = load_cell_probe_oid_lookup(args[0]);
set_endstop_range(lce, args[1], args[2], args[3], args[4]
, (fixedQ16_t)args[5]);
}
DECL_COMMAND(command_load_cell_probe_set_range, "load_cell_probe_set_range"
" oid=%c safety_counts_min=%i safety_counts_max=%i tare_counts=%i"
" trigger_grams=%u grams_per_count=%i");
// Home an axis
void
command_load_cell_probe_home(uint32_t *args)
{
struct load_cell_probe *lce = load_cell_probe_oid_lookup(args[0]);
sched_del_timer(&lce->time);
// clear the homing trigger flag
clear_flag(FLAG_IS_HOMING_TRIGGER, lce);
clear_flag(FLAG_IS_HOMING, lce);
lce->trigger_ticks = 0;
lce->ts = NULL;
// 0 samples indicates homing is finished
if (args[3] == 0) {
// Disable end stop checking
return;
}
lce->ts = trsync_oid_lookup(args[1]);
lce->trigger_reason = args[2];
lce->error_reason = args[3];
lce->time.waketime = args[4];
lce->homing_start_time = args[4];
lce->rest_ticks = args[5];
lce->watchdog_max = args[6];
lce->watchdog_count = 0;
lce->time.func = watchdog_event;
set_flag(FLAG_IS_HOMING, lce);
set_flag(FLAG_AWAIT_HOMING, lce);
sched_add_timer(&lce->time);
}
DECL_COMMAND(command_load_cell_probe_home,
"load_cell_probe_home oid=%c trsync_oid=%c trigger_reason=%c"
" error_reason=%c clock=%u rest_ticks=%u timeout=%u");
void
command_load_cell_probe_query_state(uint32_t *args)
{
uint8_t oid = args[0];
struct load_cell_probe *lce = load_cell_probe_oid_lookup(args[0]);
sendf("load_cell_probe_state oid=%c is_homing_trigger=%c trigger_ticks=%u"
, oid
, is_flag_set(FLAG_IS_HOMING_TRIGGER, lce)
, lce->trigger_ticks);
}
DECL_COMMAND(command_load_cell_probe_query_state
, "load_cell_probe_query_state oid=%c");
+10
View File
@@ -0,0 +1,10 @@
#ifndef __LOAD_CELL_PROBE_H
#define __LOAD_CELL_PROBE_H
#include <stdint.h> // uint8_t
struct load_cell_probe *load_cell_probe_oid_lookup(uint8_t oid);
void load_cell_probe_report_sample(struct load_cell_probe *lce
, int32_t sample);
#endif // load_cell_probe.h
+1 -1
View File
@@ -34,7 +34,7 @@ typedef unsigned int neopixel_time_t;
static __always_inline neopixel_time_t
nsecs_to_ticks(uint32_t ns)
{
return timer_from_us(ns * 1000) / 1000000;
return DIV_ROUND_UP(timer_from_us(ns * 1000), 1000000);
}
static inline int
+4 -2
View File
@@ -97,6 +97,8 @@ get_pclock_frequency(uint32_t reset_bit)
return FREQ_SYS;
}
// PLL (rp2xxx) input: 5 to 100Mhz, vco: 750 to 1600Mhz
static void
xosc_setup(void)
{
@@ -111,8 +113,8 @@ static void
pll_setup(pll_hw_t *pll, uint32_t mul, uint32_t postdiv)
{
// Setup pll
uint32_t refdiv = 1, fbdiv = mul, postdiv2 = 2, postdiv1 = postdiv/postdiv2;
if (postdiv1 > 0x07) {
uint32_t refdiv = 1, fbdiv = mul, postdiv2 = 1, postdiv1 = postdiv;
while (postdiv1 > 0x07) {
postdiv1 >>= 1;
postdiv2 <<= 1;
}
+21 -5
View File
@@ -10,6 +10,7 @@
#include "internal.h" // pclock, gpio_peripheral
#include "hardware/structs/spi.h" // spi_hw_t
#include "hardware/regs/resets.h" // RESETS_RESET_SPI*_BITS
#include "board/misc.h" // timer_is_before
DECL_ENUMERATION("spi_bus", "spi0_gpio0_gpio3_gpio2", 0);
@@ -115,24 +116,39 @@ spi_prepare(struct spi_config config)
spi_hw_t *spi = config.spi;
if (spi->cr0 == config.cr0 && spi->cpsr == config.cpsr)
return;
uint32_t diff = spi->cr0 ^ config.cr0;
spi->cr1 = 0;
spi->cr0 = config.cr0;
spi->cpsr = config.cpsr;
spi->cr1 = SPI_SSPCR1_SSE_BITS;
// Give time for state to update before caller changes CS pin
uint32_t end = timer_read_time() + timer_from_us(1);
if (diff & SPI_SSPCR0_SPO_BITS)
while (timer_is_before(timer_read_time(), end))
;
}
#define MAX_FIFO 8 // Max rx fifo size (don't tx past this size)
void
spi_transfer(struct spi_config config, uint8_t receive_data,
uint8_t len, uint8_t *data)
{
uint8_t *wptr = data, *end = data + len;
spi_hw_t *spi = config.spi;
while (len--) {
spi->dr = *data;
while (!(spi->sr & SPI_SSPSR_RNE_BITS))
;
while (data < end) {
uint32_t sr = spi->sr & (SPI_SSPSR_TNF_BITS | SPI_SSPSR_RNE_BITS);
if (sr == SPI_SSPSR_TNF_BITS && wptr < end && wptr < data + MAX_FIFO)
spi->dr = *wptr++;
if (!(sr & SPI_SSPSR_RNE_BITS))
continue;
uint8_t rdata = spi->dr;
if(receive_data)
if (receive_data)
*data = rdata;
data++;
}
// Wait for any remaining SCLK updates before returning
while ((spi->sr & (SPI_SSPSR_TFE_BITS|SPI_SSPSR_BSY_BITS))
!= SPI_SSPSR_TFE_BITS)
;
}
+16
View File
@@ -11,6 +11,7 @@
#include "command.h" // DECL_COMMAND
#include "sched.h" // sched_add_timer
#include "sensor_bulk.h" // sensor_bulk_report
#include "load_cell_probe.h" // load_cell_probe_report_sample
#include "spicmds.h" // spidev_transfer
#include <stdint.h>
@@ -21,6 +22,7 @@ struct ads1220_adc {
struct spidev_s *spi;
uint8_t pending_flag, data_count;
struct sensor_bulk sb;
struct load_cell_probe *lce;
};
// Flag types
@@ -94,6 +96,11 @@ ads1220_read_adc(struct ads1220_adc *ads1220, uint8_t oid)
if (counts & 0x800000)
counts |= 0xFF000000;
// endstop is optional, report if enabled and no errors
if (ads1220->lce) {
load_cell_probe_report_sample(ads1220->lce, counts);
}
add_sample(ads1220, oid, counts);
}
@@ -111,6 +118,15 @@ command_config_ads1220(uint32_t *args)
DECL_COMMAND(command_config_ads1220, "config_ads1220 oid=%c"
" spi_oid=%c data_ready_pin=%u");
void
ads1220_attach_load_cell_probe(uint32_t *args) {
uint8_t oid = args[0];
struct ads1220_adc *ads1220 = oid_lookup(oid, command_config_ads1220);
ads1220->lce = load_cell_probe_oid_lookup(args[1]);
}
DECL_COMMAND(ads1220_attach_load_cell_probe,
"ads1220_attach_load_cell_probe oid=%c load_cell_probe_oid=%c");
// start/stop capturing ADC data
void
command_query_ads1220(uint32_t *args)
+16
View File
@@ -12,6 +12,7 @@
#include "command.h" // DECL_COMMAND
#include "sched.h" // sched_add_timer
#include "sensor_bulk.h" // sensor_bulk_report
#include "load_cell_probe.h" // load_cell_probe_report_sample
#include <stdbool.h>
#include <stdint.h>
@@ -24,6 +25,7 @@ struct hx71x_adc {
struct gpio_in dout; // pin used to receive data from the hx71x
struct gpio_out sclk; // pin used to generate clock for the hx71x
struct sensor_bulk sb;
struct load_cell_probe *lce;
};
enum {
@@ -175,6 +177,11 @@ hx71x_read_adc(struct hx71x_adc *hx71x, uint8_t oid)
counts = hx71x->last_error;
}
// probe is optional, report if enabled
if (hx71x->last_error == 0 && hx71x->lce) {
load_cell_probe_report_sample(hx71x->lce, counts);
}
// Add measurement to buffer
add_sample(hx71x, oid, counts, false);
}
@@ -198,6 +205,15 @@ command_config_hx71x(uint32_t *args)
DECL_COMMAND(command_config_hx71x, "config_hx71x oid=%c gain_channel=%c"
" dout_pin=%u sclk_pin=%u");
void
hx71x_attach_load_cell_probe(uint32_t *args) {
uint8_t oid = args[0];
struct hx71x_adc *hx71x = oid_lookup(oid, command_config_hx71x);
hx71x->lce = load_cell_probe_oid_lookup(args[1]);
}
DECL_COMMAND(hx71x_attach_load_cell_probe, "hx71x_attach_load_cell_probe oid=%c"
" load_cell_probe_oid=%c");
// start/stop capturing ADC data
void
command_query_hx71x(uint32_t *args)
+167
View File
@@ -0,0 +1,167 @@
// Second Order sections Filter implementation using Fixed Point math
//
// Copyright (C) 2025 Gareth Farrington <gareth@waves.ky>
//
// This file may be distributed under the terms of the GNU GPLv3 license.
#include "basecmd.h" // oid_alloc
#include "command.h" // DECL_COMMAND
#include "sched.h" // shutdown
#include "sos_filter.h" // sos_filter
typedef int32_t fixedQ_coeff_t;
typedef int32_t fixedQ_value_t;
// filter strucutre sizes
#define SECTION_WIDTH 5
#define STATE_WIDTH 2
struct sos_filter_section {
// filter composed of second order sections
fixedQ_coeff_t coeff[SECTION_WIDTH]; // aka sos
fixedQ_value_t state[STATE_WIDTH]; // aka zi
};
struct sos_filter {
uint8_t max_sections, n_sections, coeff_frac_bits, is_active;
uint32_t coeff_rounding;
// filter composed of second order sections
struct sos_filter_section filter[0];
};
inline uint8_t
overflows_int32(int64_t value) {
return value > (int64_t)INT32_MAX || value < (int64_t)INT32_MIN;
}
// Multiply a coefficient in fixedQ_coeff_t by a value fixedQ_value_t
static inline fixedQ_value_t
fixed_mul(struct sos_filter *sf, const fixedQ_coeff_t coeff
, const fixedQ_value_t value) {
// This optimizes to single cycle SMULL on Arm Coretex M0+
int64_t product = (int64_t)coeff * (int64_t)value;
// round up at the last bit to be shifted away
product += sf->coeff_rounding;
// shift the decimal right to discard the coefficient fractional bits
int64_t result = product >> sf->coeff_frac_bits;
// check for overflow of int32_t
if (overflows_int32(result)) {
shutdown("fixed_mul: overflow");
}
// truncate significant 32 bits
return (fixedQ_value_t)result;
}
// Apply the sosfilt algorithm to a new datapoint
// returns the fixedQ_value_t filtered value
int32_t
sosfilt(struct sos_filter *sf, const int32_t unfiltered_value) {
if (!sf->is_active) {
shutdown("sos_filter not property initialized");
}
// an empty filter performs no filtering
if (sf->n_sections == 0) {
return unfiltered_value;
}
fixedQ_value_t cur_val = unfiltered_value;
// foreach section
for (int section_idx = 0; section_idx < sf->n_sections; section_idx++) {
struct sos_filter_section *section = &(sf->filter[section_idx]);
// apply the section's filter coefficients to input
fixedQ_value_t next_val = fixed_mul(sf, section->coeff[0], cur_val);
next_val += section->state[0];
section->state[0] = fixed_mul(sf, section->coeff[1], cur_val)
- fixed_mul(sf, section->coeff[3], next_val)
+ (section->state[1]);
section->state[1] = fixed_mul(sf, section->coeff[2], cur_val)
- fixed_mul(sf, section->coeff[4], next_val);
cur_val = next_val;
}
return (int32_t)cur_val;
}
// Create an sos_filter
void
command_config_sos_filter(uint32_t *args)
{
uint8_t max_sections = args[1];
uint32_t size = offsetof(struct sos_filter, filter[max_sections]);
struct sos_filter *sf = oid_alloc(args[0]
, command_config_sos_filter, size);
sf->max_sections = max_sections;
sf->is_active = 0;
}
DECL_COMMAND(command_config_sos_filter, "config_sos_filter oid=%c"
" max_sections=%c");
// Lookup an sos_filter
struct sos_filter *
sos_filter_oid_lookup(uint8_t oid)
{
return oid_lookup(oid, command_config_sos_filter);
}
// Check that a section index parameter is valid
static void
validate_section_index(struct sos_filter *sf, uint8_t section_idx)
{
if (section_idx >= sf->max_sections)
shutdown("Filter section index larger than max_sections");
}
// Set one section of the filter
void
command_sos_filter_set_section(uint32_t *args)
{
struct sos_filter *sf = sos_filter_oid_lookup(args[0]);
// setting a section marks the filter as inactive
sf->is_active = 0;
uint8_t section_idx = args[1];
validate_section_index(sf, section_idx);
// copy section data
const uint8_t arg_base = 2;
for (uint8_t i = 0; i < SECTION_WIDTH; i++) {
sf->filter[section_idx].coeff[i] = args[i + arg_base];
}
}
DECL_COMMAND(command_sos_filter_set_section
, "sos_filter_set_section oid=%c section_idx=%c"
" sos0=%i sos1=%i sos2=%i sos3=%i sos4=%i");
// Set the state of one section of the filter
void
command_sos_filter_set_state(uint32_t *args)
{
struct sos_filter *sf = sos_filter_oid_lookup(args[0]);
// setting a section's state marks the filter as inactive
sf->is_active = 0;
// copy state data
uint8_t section_idx = args[1];
validate_section_index(sf, section_idx);
const uint8_t arg_base = 2;
sf->filter[section_idx].state[0] = args[0 + arg_base];
sf->filter[section_idx].state[1] = args[1 + arg_base];
}
DECL_COMMAND(command_sos_filter_set_state
, "sos_filter_set_state oid=%c section_idx=%c state0=%i state1=%i");
// Set one section of the filter
void
command_sos_filter_activate(uint32_t *args)
{
struct sos_filter *sf = sos_filter_oid_lookup(args[0]);
uint8_t n_sections = args[1];
if (n_sections > sf->max_sections)
shutdown("Filter section index larger than max_sections");
sf->n_sections = n_sections;
const uint8_t coeff_int_bits = args[2];
sf->coeff_frac_bits = (31 - coeff_int_bits);
sf->coeff_rounding = (1 << (sf->coeff_frac_bits - 1));
// mark filter as ready to use
sf->is_active = 1;
}
DECL_COMMAND(command_sos_filter_activate
, "sos_filter_set_active oid=%c n_sections=%c coeff_int_bits=%c");
+12
View File
@@ -0,0 +1,12 @@
#ifndef __SOS_FILTER_H
#define __SOS_FILTER_H
#include <stdint.h>
struct sos_filter;
int32_t sosfilt(struct sos_filter *sf
, const int32_t unfiltered_value);
struct sos_filter *sos_filter_oid_lookup(uint8_t oid);
#endif // sos_filter.h
+9 -6
View File
@@ -40,18 +40,21 @@ DECL_COMMAND(command_spi_set_sw_bus,
"spi_set_sw_bus oid=%c miso_pin=%u mosi_pin=%u sclk_pin=%u"
" mode=%u pulse_ticks=%u");
void
spi_software_prepare(struct spi_software *ss)
{
gpio_out_write(ss->sclk, ss->mode & 0x02);
}
static void
spi_delay(uint32_t end)
{
while (timer_is_before(timer_read_time(), end));
}
void
spi_software_prepare(struct spi_software *ss)
{
gpio_out_write(ss->sclk, ss->mode & 0x02);
uint32_t end = timer_read_time() + ss->sck_ticks;
spi_delay(end);
}
void
spi_software_transfer(struct spi_software *ss, uint8_t receive_data
, uint8_t len, uint8_t *data)
+58 -33
View File
@@ -17,15 +17,12 @@
DECL_CONSTANT("STEPPER_STEP_BOTH_EDGE", 1);
#if CONFIG_INLINE_STEPPER_HACK && CONFIG_WANT_STEPPER_OPTIMIZED_BOTH_EDGE
#define HAVE_OPTIMIZED_PATH 1
#define HAVE_EDGE_OPTIMIZATION 1
#define HAVE_AVR_OPTIMIZATION 0
#elif CONFIG_INLINE_STEPPER_HACK && CONFIG_MACH_AVR
#define HAVE_OPTIMIZED_PATH 1
#define HAVE_EDGE_OPTIMIZATION 0
#define HAVE_AVR_OPTIMIZATION 1
#else
#define HAVE_OPTIMIZED_PATH 0
#define HAVE_EDGE_OPTIMIZATION 0
#define HAVE_AVR_OPTIMIZATION 0
#endif
@@ -71,32 +68,63 @@ stepper_load_next(struct stepper *s)
return SF_DONE;
}
// Load next 'struct stepper_move' into 'struct stepper'
// Read next 'struct stepper_move'
struct move_node *mn = move_queue_pop(&s->mq);
struct stepper_move *m = container_of(mn, struct stepper_move, node);
s->add = m->add;
s->interval = m->interval + m->add;
if (HAVE_OPTIMIZED_PATH && s->flags & SF_OPTIMIZED_PATH) {
s->time.waketime += m->interval;
if (HAVE_AVR_OPTIMIZATION)
s->flags = m->add ? s->flags|SF_HAVE_ADD : s->flags & ~SF_HAVE_ADD;
s->count = m->count;
} else {
// It is necessary to schedule unstep events and so there are
// twice as many events.
s->next_step_time += m->interval;
s->time.waketime = s->next_step_time;
s->count = s->flags & SF_SINGLE_SCHED ? m->count : (uint32_t)m->count*2;
}
uint32_t move_interval = m->interval;
uint_fast16_t move_count = m->count;
int_fast16_t move_add = m->add;
uint_fast8_t need_dir_change = m->flags & MF_DIR;
move_free(m);
// Add all steps to s->position (stepper_get_position() can calc mid-move)
if (m->flags & MF_DIR) {
s->position = -s->position + m->count;
gpio_out_toggle_noirq(s->dir_pin);
s->position = (need_dir_change ? -s->position : s->position) + move_count;
// Load next move into 'struct stepper'
s->add = move_add;
s->interval = move_interval + move_add;
if (HAVE_EDGE_OPTIMIZATION && s->flags & SF_OPTIMIZED_PATH) {
// Using optimized stepper_event_edge()
s->time.waketime += move_interval;
s->count = move_count;
} else if (HAVE_AVR_OPTIMIZATION && s->flags & SF_OPTIMIZED_PATH) {
// Using optimized stepper_event_avr()
s->time.waketime += move_interval;
s->count = move_count;
s->flags = move_add ? s->flags | SF_HAVE_ADD : s->flags & ~SF_HAVE_ADD;
} else {
s->position += m->count;
// Using fully scheduled stepper_event_full() code (the scheduler
// may be called twice for each step)
uint_fast8_t was_active = !!s->count;
uint32_t min_next_time = s->time.waketime;
s->next_step_time += move_interval;
s->time.waketime = s->next_step_time;
s->count = (s->flags & SF_SINGLE_SCHED ? move_count
: (uint32_t)move_count * 2);
if (was_active && timer_is_before(s->next_step_time, min_next_time)) {
// Actively stepping and next step event close to the last unstep
int32_t diff = s->next_step_time - min_next_time;
if (diff < (int32_t)-timer_from_us(1000))
shutdown("Stepper too far in past");
s->time.waketime = min_next_time;
}
if (was_active && need_dir_change) {
// Must ensure minimum time between step change and dir change
if (s->flags & SF_SINGLE_SCHED)
while (timer_is_before(timer_read_time(), min_next_time))
;
gpio_out_toggle_noirq(s->dir_pin);
uint32_t curtime = timer_read_time();
min_next_time = curtime + s->step_pulse_ticks;
if (timer_is_before(s->time.waketime, min_next_time))
s->time.waketime = min_next_time;
return SF_RESCHEDULE;
}
}
move_free(m);
// Set new direction (if needed)
if (need_dir_change)
gpio_out_toggle_noirq(s->dir_pin);
return SF_RESCHEDULE;
}
@@ -155,27 +183,24 @@ stepper_event_full(struct timer *t)
gpio_out_toggle_noirq(s->step_pin);
uint32_t curtime = timer_read_time();
uint32_t min_next_time = curtime + s->step_pulse_ticks;
s->count--;
if (likely(s->count & 1 && !(s->flags & SF_SINGLE_SCHED)))
uint32_t count = s->count - 1;
if (likely(count & 1 && !(s->flags & SF_SINGLE_SCHED)))
// Schedule unstep event
goto reschedule_min;
if (likely(s->count)) {
if (likely(count)) {
s->next_step_time += s->interval;
s->interval += s->add;
if (unlikely(timer_is_before(s->next_step_time, min_next_time)))
// The next step event is too close - push it back
goto reschedule_min;
s->count = count;
s->time.waketime = s->next_step_time;
return SF_RESCHEDULE;
}
uint_fast8_t ret = stepper_load_next(s);
if (ret == SF_DONE || !timer_is_before(s->time.waketime, min_next_time))
return ret;
// Next step event is too close to the last unstep
int32_t diff = s->time.waketime - min_next_time;
if (diff < (int32_t)-timer_from_us(1000))
shutdown("Stepper too far in past");
s->time.waketime = min_next_time;
return stepper_load_next(s);
reschedule_min:
s->count = count;
s->time.waketime = min_next_time;
return SF_RESCHEDULE;
}
+11 -10
View File
@@ -206,9 +206,10 @@ config CLOCK_FREQ
default 180000000 if MACH_STM32F446
default 216000000 if MACH_STM32F765
default 64000000 if MACH_STM32G0
default 150000000 if MACH_STM32G431
default 170000000 if MACH_STM32G431
default 170000000 if MACH_STM32G474
default 400000000 if MACH_STM32H7 # 400Mhz is max Klipper currently supports
default 520000000 if MACH_STM32H723
default 400000000 if MACH_STM32H743 || MACH_STM32H750
default 80000000 if MACH_STM32L412
default 64000000 if MACH_N32G45x && STM32_CLOCK_REF_INTERNAL
default 128000000 if MACH_N32G45x
@@ -285,7 +286,7 @@ config STM32_DFU_ROM_ADDRESS
choice
prompt "Bootloader offset"
config STM32_FLASH_START_2000
bool "8KiB bootloader" if MACH_STM32F1 || MACH_STM32F070 || MACH_STM32G0 || MACH_STM32F0x2
bool "8KiB bootloader" if MACH_STM32F1 || MACH_STM32F070 || MACH_STM32G0 || MACH_STM32G4 || MACH_STM32F0x2
config STM32_FLASH_START_5000
bool "20KiB bootloader" if MACH_STM32F103
config STM32_FLASH_START_7000
@@ -446,7 +447,7 @@ choice
select CANSERIAL
config STM32_CANBUS_PA11_PA12_REMAP
bool "CAN bus (on PA9/PA10)" if LOW_LEVEL_OPTIONS
depends on HAVE_STM32_CANBUS && (MACH_STM32F042 || MACH_STM32F070x6)
depends on MACH_STM32F042
select CANSERIAL
config STM32_CANBUS_PA11_PB9
bool "CAN bus (on PA11/PB9)"
@@ -458,15 +459,15 @@ choice
select CANSERIAL
config STM32_MMENU_CANBUS_PI9_PH13
bool "CAN bus (on PI9/PH13)" if LOW_LEVEL_OPTIONS
depends on HAVE_STM32_CANBUS && MACH_STM32F4
depends on (MACH_STM32F4 && HAVE_STM32_CANBUS)
select CANSERIAL
config STM32_MMENU_CANBUS_PB5_PB6
bool "CAN bus (on PB5/PB6)" if LOW_LEVEL_OPTIONS
depends on HAVE_STM32_CANBUS && MACH_STM32F4
depends on (MACH_STM32F4 && HAVE_STM32_CANBUS) || MACH_STM32H7
select CANSERIAL
config STM32_MMENU_CANBUS_PB12_PB13
bool "CAN bus (on PB12/PB13)" if LOW_LEVEL_OPTIONS
depends on (HAVE_STM32_CANBUS && MACH_STM32F4) || HAVE_STM32_FDCANBUS
depends on (MACH_STM32F4 && HAVE_STM32_CANBUS) || HAVE_STM32_FDCANBUS
select CANSERIAL
config STM32_MMENU_CANBUS_PD0_PD1
bool "CAN bus (on PD0/PD1)" if LOW_LEVEL_OPTIONS
@@ -499,13 +500,13 @@ choice
bool "CAN bus (on PB8/PB9)"
config STM32_CMENU_CANBUS_PI9_PH13
bool "CAN bus (on PI9/PH13)"
depends on HAVE_STM32_CANBUS && MACH_STM32F4
depends on (MACH_STM32F4 && HAVE_STM32_CANBUS)
config STM32_CMENU_CANBUS_PB5_PB6
bool "CAN bus (on PB5/PB6)"
depends on (HAVE_STM32_CANBUS && MACH_STM32F4) || (HAVE_STM32_FDCANBUS && MACH_STM32G0B1)
depends on (MACH_STM32F4 && HAVE_STM32_CANBUS) || MACH_STM32H7 || MACH_STM32G0B1
config STM32_CMENU_CANBUS_PB12_PB13
bool "CAN bus (on PB12/PB13)"
depends on (HAVE_STM32_CANBUS && MACH_STM32F4) || HAVE_STM32_FDCANBUS
depends on (MACH_STM32F4 && HAVE_STM32_CANBUS) || HAVE_STM32_FDCANBUS
config STM32_CMENU_CANBUS_PD0_PD1
bool "CAN bus (on PD0/PD1)"
depends on HAVE_STM32_CANBUS || HAVE_STM32_FDCANBUS
+21 -7
View File
@@ -106,9 +106,7 @@ spi_setup(uint32_t bus, uint8_t mode, uint32_t rate)
gpio_peripheral(spi_bus[bus].sck_pin, spi_bus[bus].sck_af, 0);
// Configure CR2 on stm32 f0/f7/g0/l4/g4
#if CONFIG_MACH_STM32F0 || CONFIG_MACH_STM32F7 || \
CONFIG_MACH_STM32G0 || CONFIG_MACH_STM32G4 || \
CONFIG_MACH_STM32L4
#ifdef SPI_CR2_FRXTH
spi->CR2 = SPI_CR2_FRXTH | (7 << SPI_CR2_DS_Pos);
#endif
}
@@ -137,15 +135,31 @@ spi_prepare(struct spi_config config)
spi->CR1 = config.spi_cr1;
}
#ifdef SPI_CR2_FRXTH // stm32 f0/f7/g0/l4/g4 supports buffering
#define CAN_BUFFER 1
#else
#define CAN_BUFFER 0
#endif
void
spi_transfer(struct spi_config config, uint8_t receive_data,
uint8_t len, uint8_t *data)
{
SPI_TypeDef *spi = config.spi;
while (len--) {
writeb((void*)&spi->DR, *data);
while (!(spi->SR & SPI_SR_RXNE))
;
uint8_t *wptr = data;
uint8_t *end = data + len;
while (data < end) {
if (CAN_BUFFER) {
uint32_t sr = spi->SR & (SPI_SR_TXE | SPI_SR_RXNE);
if ((sr == SPI_SR_TXE) && wptr < end)
writeb((void*)&spi->DR, *wptr++);
if (!(sr & SPI_SR_RXNE))
continue;
} else {
writeb((void*)&spi->DR, *data);
while (!(spi->SR & SPI_SR_RXNE))
;
}
uint8_t rdata = readb((void*)&spi->DR);
if (receive_data)
*data = rdata;
+2
View File
@@ -52,6 +52,8 @@ gpio_clock_enable(GPIO_TypeDef *regs)
RCC->AHBENR;
}
// PLL (f0) input: 1 to 24Mhz, output: 16 to 48Mhz
#if !CONFIG_STM32_CLOCK_REF_INTERNAL
DECL_CONSTANT_STR("RESERVE_PINS_crystal", "PF0,PF1");
#endif
+9 -9
View File
@@ -149,17 +149,17 @@ i2c_setup(uint32_t bus, uint32_t rate, uint8_t addr)
gpio_peripheral(ii->sda_pin, ii->function | GPIO_OPEN_DRAIN, 1);
// Set 100Khz frequency and enable
uint32_t nom_i2c_clock = 8000000; // 8mhz internal clock = 125ns ticks
uint32_t scll = 40; // 40 * 125ns = 5us
uint32_t sclh = 32; // 32 * 125ns = 4us
uint32_t sdadel = 4; // 4 * 125ns = 500ns
uint32_t scldel = 10; // 10 * 125ns = 1250ns
uint32_t nom_i2c_clock = 12000000; // 12mhz internal clock (83.3ns tick)
uint32_t scll = 60; // 60 * 83.3ns = 5us
uint32_t sclh = 48; // 48 * 83.3ns = 4us
uint32_t sdadel = 6; // 6 * 83.3ns = 500ns
uint32_t scldel = 15; // 15 * 83.3ns = 1250ns
// Clamp the rate to 400Khz
if (rate >= 400000) {
scll = 10; // 10 * 125ns = 1250ns
sclh = 4; // 4 * 125 = 500ns
sdadel = 3; // 3 * 125 = 375ns
scldel = 4; // 4 * 125 = 500ns
scll = 15; // 15 * 83.3ns = 1250ns
sclh = 6; // 6 * 83.3 = 500ns
sdadel = 4; // 4 * 83.3 = 333ns
scldel = 6; // 6 * 83.3 = 500ns
}
uint32_t pclk = get_pclock_frequency((uint32_t)i2c);
+2
View File
@@ -51,6 +51,8 @@ gpio_clock_enable(GPIO_TypeDef *regs)
RCC->APB2ENR;
}
// PLL (f103) input: 1 to 25Mhz, output: 16 to 72Mhz
// Main clock setup called at chip startup
static void
clock_setup(void)
+5
View File
@@ -57,6 +57,11 @@ gpio_clock_enable(GPIO_TypeDef *regs)
RCC->AHB1ENR;
}
// PLL (f207) input: 0.95 to 2.1Mhz, vco: 192 to 432Mhz, output: 24 to 120Mhz
// PLL (f401) input: 0.95 to 2.1Mhz, vco: 192 to 432Mhz, output: 24 to 84Mhz
// PLL (f405/7) input: 0.95 to 2.1Mhz, vco: 100 to 432Mhz, output: 24 to 168Mhz
// PLL (f446) input: 0.95 to 2.1Mhz, vco: 100 to 432Mhz, output: 12.5 to 180Mhz
#if !CONFIG_STM32_CLOCK_REF_INTERNAL
DECL_CONSTANT_STR("RESERVE_PINS_crystal", "PH0,PH1");
#endif
+2
View File
@@ -57,6 +57,8 @@ gpio_clock_enable(GPIO_TypeDef *regs)
RCC->AHB1ENR;
}
// PLL (f765) input: 0.95 to 2.1Mhz, vco: 100 to 432Mhz, output: 24 to 216Mhz
#if !CONFIG_STM32_CLOCK_REF_INTERNAL
DECL_CONSTANT_STR("RESERVE_PINS_crystal", "PH0,PH1");
#endif
+2
View File
@@ -97,6 +97,8 @@ gpio_clock_enable(GPIO_TypeDef *regs)
RCC->IOPENR;
}
// PLL (g0) input: 2.66 to 16Mhz, vco: 96 to 344Mhz, output: 12 to 64Mhz
#if !CONFIG_STM32_CLOCK_REF_INTERNAL
DECL_CONSTANT_STR("RESERVE_PINS_crystal", "PF0,PF1");
#endif
+8 -3
View File
@@ -1,6 +1,6 @@
// Code to setup clocks and gpio on stm32g4
//
// Copyright (C) 2019 Kevin O'Connor <kevin@koconnor.net>
// Copyright (C) 2019-2025 Kevin O'Connor <kevin@koconnor.net>
//
// This file may be distributed under the terms of the GNU GPLv3 license.
@@ -76,6 +76,8 @@ gpio_clock_enable(GPIO_TypeDef *regs)
RCC->AHB2ENR;
}
// PLL (g4) input: 2.66 to 16Mhz, vco: 96 to 344Mhz, output: 2.06 to 170Mhz
#if !CONFIG_STM32_CLOCK_REF_INTERNAL
DECL_CONSTANT_STR("RESERVE_PINS_crystal", "PF0,PF1");
#endif
@@ -85,14 +87,14 @@ enable_clock_stm32g4(void)
{
uint32_t pll_base = 4000000, pll_freq = CONFIG_CLOCK_FREQ * 2, pllcfgr;
if (!CONFIG_STM32_CLOCK_REF_INTERNAL) {
// Configure 150Mhz PLL from external crystal (HSE)
// Configure PLL from external crystal (HSE)
uint32_t div = CONFIG_CLOCK_REF_FREQ / pll_base - 1;
RCC->CR |= RCC_CR_HSEON;
while (!(RCC->CR & RCC_CR_HSERDY))
;
pllcfgr = RCC_PLLCFGR_PLLSRC_HSE | (div << RCC_PLLCFGR_PLLM_Pos);
} else {
// Configure 150Mhz PLL from internal 16Mhz oscillator (HSI)
// Configure PLL from internal 16Mhz oscillator (HSI)
uint32_t div = 16000000 / pll_base - 1;
pllcfgr = RCC_PLLCFGR_PLLSRC_HSI | (div << RCC_PLLCFGR_PLLM_Pos);
RCC->CR |= RCC_CR_HSION;
@@ -134,6 +136,9 @@ clock_setup(void)
enable_pclock(PWR_BASE);
PWR->CR3 |= PWR_CR3_APC; // allow gpio pullup/down
if (CONFIG_CLOCK_FREQ > 150000000)
// Enable "range 1 boost" mode
PWR->CR5 = 0;
// Wait for PLL lock
while (!(RCC->CR & RCC_CR_PLLRDY))
+64 -79
View File
@@ -49,6 +49,10 @@ lookup_clock_line(uint32_t periph_base)
uint32_t bit = 1 << ((periph_base - D2_APB2PERIPH_BASE) / 0x400);
return (struct cline){.en=&RCC->APB2ENR, .rst=&RCC->APB2RSTR, .bit=bit};
} else {
if (periph_base == FDCAN2_BASE)
// FDCAN1 and FDCAN2 share same clock enable
return (struct cline){.en=&RCC->APB1HENR, .rst=&RCC->APB1HRSTR,
.bit = RCC_APB1HENR_FDCANEN};
uint32_t offset = ((periph_base - D2_APB1PERIPH_BASE) / 0x400);
if (offset < 32) {
uint32_t bit = 1 << offset;
@@ -78,6 +82,9 @@ gpio_clock_enable(GPIO_TypeDef *regs)
RCC->AHB4ENR;
}
// PLL1 (h723) input: 2 to 16Mhz, vco: 192 to 836Mhz, output: 1.5 to 550Mhz
// PLL1 (h743v) input: 2 to 16Mhz, vco: 192 to 960Mhz, output: 1.5 to 480Mhz
#if !CONFIG_STM32_CLOCK_REF_INTERNAL
DECL_CONSTANT_STR("RESERVE_PINS_crystal", "PH0,PH1");
#endif
@@ -86,123 +93,100 @@ DECL_CONSTANT_STR("RESERVE_PINS_crystal", "PH0,PH1");
static void
clock_setup(void)
{
#if !CONFIG_MACH_STM32H723
// Ensure USB OTG ULPI is not enabled
CLEAR_BIT(RCC->AHB1ENR, RCC_AHB1ENR_USB2OTGHSULPIEN);
CLEAR_BIT(RCC->AHB1LPENR, RCC_AHB1LPENR_USB2OTGHSULPILPEN);
#endif
// Set this despite correct defaults.
// "The software has to program the supply configuration in PWR control
// register 3" (pg. 259)
// Only a single write is allowed (pg. 304)
PWR->CR3 = (PWR->CR3 | PWR_CR3_LDOEN) & ~(PWR_CR3_BYPASS | PWR_CR3_SCUEN);
// Enable low dropout regulator
PWR->CR3 = PWR_CR3_LDOEN;
while (!(PWR->CSR1 & PWR_CSR1_ACTVOSRDY))
;
// (HSE 25mhz) /DIVM1(5) (pll_base 5Mhz) *DIVN1(192) (pll_freq 960Mhz)
// /DIVP1(2) (SYSCLK 480Mhz)
// Setup pll1 frequency
uint32_t pll_base = CONFIG_STM32_CLOCK_REF_25M ? 5000000 : 4000000;
// Only even dividers (DIVP1) are allowed
uint32_t pll_freq = CONFIG_CLOCK_FREQ * 2;
uint32_t pll_freq = CONFIG_CLOCK_FREQ * (CONFIG_MACH_STM32H723 ? 1 : 2);
uint32_t rcc_cr = RCC_CR_HSION;
if (!CONFIG_STM32_CLOCK_REF_INTERNAL) {
// Configure PLL from external crystal (HSE)
RCC->CR |= RCC_CR_HSEON;
while(!(RCC->CR & RCC_CR_HSERDY))
RCC->CR = rcc_cr = rcc_cr | RCC_CR_HSEON;
while (!(RCC->CR & RCC_CR_HSERDY))
;
MODIFY_REG(RCC->PLLCKSELR, RCC_PLLCKSELR_PLLSRC_Msk,
RCC_PLLCKSELR_PLLSRC_HSE);
MODIFY_REG(RCC->PLLCKSELR, RCC_PLLCKSELR_DIVM1_Msk,
(CONFIG_CLOCK_REF_FREQ/pll_base) << RCC_PLLCKSELR_DIVM1_Pos);
RCC->PLLCKSELR = RCC_PLLCKSELR_PLLSRC_HSE
| ((CONFIG_CLOCK_REF_FREQ/pll_base) << RCC_PLLCKSELR_DIVM1_Pos);
} else {
// Configure PLL from internal 64Mhz oscillator (HSI)
// HSI frequency of 64Mhz is integer divisible with 4Mhz
pll_base = 4000000;
MODIFY_REG(RCC->PLLCKSELR, RCC_PLLCKSELR_PLLSRC_Msk,
RCC_PLLCKSELR_PLLSRC_HSI);
MODIFY_REG(RCC->PLLCKSELR, RCC_PLLCKSELR_DIVM1_Msk,
(64000000/pll_base) << RCC_PLLCKSELR_DIVM1_Pos);
RCC->PLLCKSELR = RCC_PLLCKSELR_PLLSRC_HSI
| ((64000000/pll_base) << RCC_PLLCKSELR_DIVM1_Pos);
}
// Set input frequency range of PLL1 according to pll_base
// 3 = 8-16Mhz, 2 = 4-8Mhz
MODIFY_REG(RCC->PLLCFGR, RCC_PLLCFGR_PLL1RGE_Msk, RCC_PLLCFGR_PLL1RGE_2);
// Disable unused PLL1 outputs
MODIFY_REG(RCC->PLLCFGR, RCC_PLLCFGR_DIVR1EN_Msk, 0);
// Enable PLL1Q and set to 100MHz for SPI 1,2,3
MODIFY_REG(RCC->PLLCFGR, RCC_PLLCFGR_DIVQ1EN, RCC_PLLCFGR_DIVQ1EN);
MODIFY_REG(RCC->PLL1DIVR, RCC_PLL1DIVR_Q1,
(pll_freq / FREQ_PERIPH - 1) << RCC_PLL1DIVR_Q1_Pos);
// This is necessary, default is not 1!
MODIFY_REG(RCC->PLLCFGR, RCC_PLLCFGR_DIVP1EN_Msk, RCC_PLLCFGR_DIVP1EN);
RCC->PLLCFGR = (2 << RCC_PLLCFGR_PLL1RGE_Pos)
// Enable PLL1Q (used by some peripherals)
| RCC_PLLCFGR_DIVQ1EN
// Enable PLL1P (for cpu clock)
| RCC_PLLCFGR_DIVP1EN;
// Set multiplier DIVN1 and post divider DIVP1
// 001 = /2, 010 = not allowed, 0011 = /4 ...
MODIFY_REG(RCC->PLL1DIVR, RCC_PLL1DIVR_N1_Msk,
(pll_freq/pll_base - 1) << RCC_PLL1DIVR_N1_Pos);
MODIFY_REG(RCC->PLL1DIVR, RCC_PLL1DIVR_P1_Msk,
(pll_freq/CONFIG_CLOCK_FREQ - 1) << RCC_PLL1DIVR_P1_Pos);
RCC->PLL1DIVR = ((pll_freq/pll_base - 1) << RCC_PLL1DIVR_N1_Pos)
// Set PLL1Q frequency (some peripherals directly use pll1_q_ck)
| ((pll_freq/FREQ_PERIPH - 1) << RCC_PLL1DIVR_Q1_Pos)
// Set PLL1P cpu clock frequency
| ((pll_freq/CONFIG_CLOCK_FREQ - 1) << RCC_PLL1DIVR_P1_Pos);
// Pwr
MODIFY_REG(PWR->D3CR, PWR_D3CR_VOS_Msk, PWR_D3CR_VOS);
while (!(PWR->D3CR & PWR_D3CR_VOSRDY))
;
// Enable VOS0 (overdrive)
if (CONFIG_CLOCK_FREQ > 400000000) {
RCC->APB4ENR |= RCC_APB4ENR_SYSCFGEN;
#if !CONFIG_MACH_STM32H723
SYSCFG->PWRCR |= SYSCFG_PWRCR_ODEN;
#else
PWR->CR3 |= PWR_CR3_BYPASS;
#endif
// Enable VOS1 power mode (or VOS0 if freq>400Mhz)
if (CONFIG_MACH_STM32H723) {
PWR->D3CR = (CONFIG_CLOCK_FREQ > 400000000 ? 0 : 3) << PWR_D3CR_VOS_Pos;
while (!(PWR->D3CR & PWR_D3CR_VOSRDY))
;
} else {
PWR->D3CR = 3 << PWR_D3CR_VOS_Pos;
while (!(PWR->D3CR & PWR_D3CR_VOSRDY))
;
if (CONFIG_CLOCK_FREQ > 400000000) {
enable_pclock((uint32_t)SYSCFG);
#ifdef SYSCFG_PWRCR_ODEN
SYSCFG->PWRCR |= SYSCFG_PWRCR_ODEN;
#endif
while (!(PWR->D3CR & PWR_D3CR_VOSRDY))
;
}
}
SCB_EnableICache();
SCB_EnableDCache();
// Set flash latency according to clock frequency (pg.159)
// Set flash latency according to clock frequency
uint32_t flash_acr_latency = (CONFIG_CLOCK_FREQ > 450000000) ?
FLASH_ACR_LATENCY_4WS : FLASH_ACR_LATENCY_2WS;
MODIFY_REG(FLASH->ACR, FLASH_ACR_LATENCY_Msk, flash_acr_latency);
MODIFY_REG(FLASH->ACR, FLASH_ACR_WRHIGHFREQ_Msk, FLASH_ACR_WRHIGHFREQ_1);
FLASH->ACR = flash_acr_latency | (2 << FLASH_ACR_WRHIGHFREQ_Pos);
while (!(FLASH->ACR & flash_acr_latency))
;
// Set HPRE, D1PPRE, D2PPRE, D2PPRE2, D3PPRE dividers
// 480MHz / 2 = 240MHz rcc_hclk3
MODIFY_REG(RCC->D1CFGR, RCC_D1CFGR_HPRE, RCC_D1CFGR_HPRE_3);
// 240MHz / 2 = 120MHz rcc_pclk3
MODIFY_REG(RCC->D1CFGR, RCC_D1CFGR_D1PPRE, RCC_D1CFGR_D1PPRE_DIV2);
// 240MHz / 2 = 120MHz rcc_pclk1
MODIFY_REG(RCC->D2CFGR, RCC_D2CFGR_D2PPRE1, RCC_D2CFGR_D2PPRE1_DIV2);
// 240MHz / 2 = 120MHz rcc_pclk2
MODIFY_REG(RCC->D2CFGR, RCC_D2CFGR_D2PPRE2, RCC_D2CFGR_D2PPRE2_DIV2);
// 240MHz / 2 = 120MHz rcc_pclk4
MODIFY_REG(RCC->D3CFGR, RCC_D3CFGR_D3PPRE, RCC_D3CFGR_D3PPRE_DIV2);
// Set HPRE clock to div 2 (CONFIG_CLOCK_FREQ/2) and set
// peripheral clocks another div 2 (CONFIG_CLOCK_FREQ/4)
RCC->D1CFGR = RCC_D1CFGR_HPRE_DIV2 | RCC_D1CFGR_D1PPRE_DIV2;
RCC->D2CFGR = RCC_D2CFGR_D2PPRE1_DIV2 | RCC_D2CFGR_D2PPRE2_DIV2;
RCC->D3CFGR = RCC_D3CFGR_D3PPRE_DIV2;
// Switch on PLL1
RCC->CR |= RCC_CR_PLL1ON;
RCC->CR = rcc_cr = rcc_cr | RCC_CR_PLL1ON;
while (!(RCC->CR & RCC_CR_PLL1RDY))
;
// Switch system clock source (SYSCLK) to PLL1
MODIFY_REG(RCC->CFGR, RCC_CFGR_SW_Msk, RCC_CFGR_SW_PLL1);
RCC->CFGR = RCC_CFGR_SW_PLL1;
while ((RCC->CFGR & RCC_CFGR_SWS_Msk) != RCC_CFGR_SWS_PLL1)
;
// Set the source of FDCAN clock
MODIFY_REG(RCC->D2CCIP1R, RCC_D2CCIP1R_FDCANSEL, RCC_D2CCIP1R_FDCANSEL_0);
// Set the source of FDCAN clock to pll1_q_ck
RCC->D2CCIP1R = 1 << RCC_D2CCIP1R_FDCANSEL_Pos;
// Configure HSI48 clock for USB
// Configure USB to use HSI48 clock
if (CONFIG_USB) {
SET_BIT(RCC->CR, RCC_CR_HSI48ON);
while((RCC->CR & RCC_CR_HSI48RDY) == 0);
SET_BIT(RCC->APB1HENR, RCC_APB1HENR_CRSEN);
SET_BIT(RCC->APB1HRSTR, RCC_APB1HRSTR_CRSRST);
CLEAR_BIT(RCC->APB1HRSTR, RCC_APB1HRSTR_CRSRST);
CLEAR_BIT(CRS->CFGR, CRS_CFGR_SYNCSRC);
SET_BIT(CRS->CR, CRS_CR_CEN | CRS_CR_AUTOTRIMEN);
CLEAR_BIT(RCC->D2CCIP2R, RCC_D2CCIP2R_USBSEL);
SET_BIT(RCC->D2CCIP2R, RCC_D2CCIP2R_USBSEL);
RCC->CR = rcc_cr = rcc_cr | RCC_CR_HSI48ON;
while ((RCC->CR & RCC_CR_HSI48RDY) == 0)
;
enable_pclock((uint32_t)CRS);
CRS->CFGR &= ~CRS_CFGR_SYNCSRC;
CRS->CR = (CRS->CR & CRS_CR_TRIM) | CRS_CR_CEN | CRS_CR_AUTOTRIMEN;
RCC->D2CCIP2R = RCC_D2CCIP2R_USBSEL;
}
}
@@ -239,6 +223,7 @@ armcm_main(void)
RCC->APB2ENR = 0x00000000;
RCC->APB3ENR = 0x00000000;
RCC->APB4ENR = 0x00000000;
RCC->AHB1ENR = 0x00000000;
SCB->VTOR = (uint32_t)VectorTable;
+8 -6
View File
@@ -160,10 +160,11 @@ static const uint8_t adc_pins[] = {
#define ADC_CKMODE 0b11
#define ADC_ATICKS 0b110
#define ADC_ATICKS_H723_ADC3 0b111
// stm32h7: clock=25Mhz, Tsamp=387.5, Tconv=394, total=15.76us
// stm32h723 adc3: clock=50Mhz, Tsamp=640.5, Tconv=653, total=13.06us
// stm32l4: clock=20Mhz, Tsamp=247.5, Tconv=260, total=13.0us
// stm32g4: clock=37.5Mhz, Tsamp=247.5, Tconv=260, total=6.933us
// 400Mhz stm32h7: clock=25Mhz, Tsamp=387.5, Tconv=394, total=15.76us
// 520Mhz stm32h723: clock=32.5Mhz, Tsamp=387.5, Tconv=394, total=12.12us
// 520Mhz stm32h723 adc3: clock=65Mhz, Tsamp=640.5, Tconv=653, total=10.05us
// 80Mhz stm32l4: clock=20Mhz, Tsamp=247.5, Tconv=260, total=13.0us
// 170Mhz stm32g4: clock=42.5Mhz, Tsamp=247.5, Tconv=260, total=6.118us
// Handle register name differences between chips
#if CONFIG_MACH_STM32H723
@@ -231,8 +232,9 @@ gpio_adc_setup(uint32_t pin)
} else {
// Use linear calibration on stm32h7
cr |= ADC_CR_ADCALLIN;
// Set boost mode on stm32h7 (adc clock is at 25Mhz)
cr |= 0b10 << ADC_CR_BOOST_Pos;
// Set boost mode on stm32h7
uint32_t boost = CONFIG_CLOCK_FREQ > 400000000 ? 0b11 : 0b10;
cr |= boost << ADC_CR_BOOST_Pos;
// Set 12bit samples on the stm32h7
adc->CFGR = ADC_CFGR_JQDIS | (0b110 << ADC_CFGR_RES_Pos);
}
+32 -27
View File
@@ -1,6 +1,6 @@
// SPI functions on STM32H7
//
// Copyright (C) 2019 Kevin O'Connor <kevin@koconnor.net>
// Copyright (C) 2019-2025 Kevin O'Connor <kevin@koconnor.net>
//
// This file may be distributed under the terms of the GNU GPLv3 license.
@@ -9,6 +9,7 @@
#include "gpio.h" // spi_setup
#include "internal.h" // gpio_peripheral
#include "sched.h" // sched_shutdown
#include "board/misc.h" // timer_is_before
struct spi_info {
SPI_TypeDef *spi;
@@ -100,12 +101,6 @@ spi_setup(uint32_t bus, uint8_t mode, uint32_t rate)
while ((pclk >> (div + 1)) > rate && div < 7)
div++;
spi->CFG1 |= (div << SPI_CFG1_MBR_Pos) | (7 << SPI_CFG1_DSIZE_Pos);
CLEAR_BIT(spi->CFG1, SPI_CFG1_CRCSIZE);
spi->CFG2 |= ((mode << SPI_CFG2_CPHA_Pos) | SPI_CFG2_MASTER | SPI_CFG2_SSM
| SPI_CFG2_AFCNTR | SPI_CFG2_SSOE);
spi->CR1 |= SPI_CR1_SSI;
return (struct spi_config){ .spi = spi, .div = div, .mode = mode };
}
@@ -115,40 +110,50 @@ spi_prepare(struct spi_config config)
uint32_t div = config.div;
uint32_t mode = config.mode;
SPI_TypeDef *spi = config.spi;
// Reload frequency
spi->CFG1 = (spi->CFG1 & ~SPI_CFG1_MBR_Msk);
spi->CFG1 |= (div << SPI_CFG1_MBR_Pos);
// Reload mode
spi->CFG2 = (spi->CFG2 & ~SPI_CFG2_CPHA_Msk);
spi->CFG2 |= (mode << SPI_CFG2_CPHA_Pos);
// Load frequency
spi->CFG1 = (div << SPI_CFG1_MBR_Pos) | (7 << SPI_CFG1_DSIZE_Pos);
// Load mode
uint32_t cfg2 = ((mode << SPI_CFG2_CPHA_Pos) | SPI_CFG2_MASTER
| SPI_CFG2_SSM | SPI_CFG2_AFCNTR | SPI_CFG2_SSOE);
uint32_t diff = spi->CFG2 ^ cfg2;
spi->CFG2 = cfg2;
uint32_t end = timer_read_time() + timer_from_us(1);
if (diff & SPI_CFG2_CPOL_Msk)
while (timer_is_before(timer_read_time(), end))
;
}
#define MAX_FIFO 8 // Limit tx fifo usage so rx fifo doesn't overrun
void
spi_transfer(struct spi_config config, uint8_t receive_data,
uint8_t len, uint8_t *data)
{
uint8_t rdata = 0;
uint8_t *wptr = data, *end = data + len;
SPI_TypeDef *spi = config.spi;
MODIFY_REG(spi->CR2, SPI_CR2_TSIZE, len);
spi->CR2 = len << SPI_CR2_TSIZE_Pos;
// Enable SPI and start transfer, these MUST be set in this sequence
SET_BIT(spi->CR1, SPI_CR1_SPE);
SET_BIT(spi->CR1, SPI_CR1_CSTART);
spi->CR1 = SPI_CR1_SSI | SPI_CR1_SPE;
spi->CR1 = SPI_CR1_SSI | SPI_CR1_CSTART | SPI_CR1_SPE;
while (len--) {
writeb((void *)&spi->TXDR, *data);
while((spi->SR & (SPI_SR_RXWNE | SPI_SR_RXPLVL)) == 0);
rdata = readb((void *)&spi->RXDR);
if (receive_data) {
while (data < end) {
uint32_t sr = spi->SR & (SPI_SR_TXP | SPI_SR_RXP);
if (sr == SPI_SR_TXP && wptr < end && wptr < data + MAX_FIFO)
writeb((void*)&spi->TXDR, *wptr++);
if (!(sr & SPI_SR_RXP))
continue;
uint8_t rdata = readb((void *)&spi->RXDR);
if (receive_data)
*data = rdata;
}
data++;
}
while ((spi->SR & SPI_SR_EOT) == 0);
while ((spi->SR & SPI_SR_EOT) == 0)
;
// Clear flags and disable SPI
SET_BIT(spi->IFCR, 0xFFFFFFFF);
CLEAR_BIT(spi->CR1, SPI_CR1_SPE);
spi->IFCR = 0xFFFFFFFF;
spi->CR1 = SPI_CR1_SSI;
}
+2
View File
@@ -68,6 +68,8 @@ gpio_clock_enable(GPIO_TypeDef *regs)
RCC->AHB2ENR;
}
// PLL (L412) input: 4 to 16Mhz, vco: 96 to 344Mhz, output: 12 to 80Mhz
#if !CONFIG_STM32_CLOCK_REF_INTERNAL
DECL_CONSTANT_STR("RESERVE_PINS_crystal", "PC14,PC15");
#endif
Loaded 100 of 106 files, more files were not shown because too many files have changed in this diff. Show more