jschuh / klipper-macros

A collection of useful macros for the Klipper 3D printer firmware
GNU General Public License v3.0
921 stars 167 forks source link

klipper-macros

This is a collection of macros for the Klipper 3D printer firmware. I originally created this repo just to have a consistent set of macros shared between my own 3D printers. But since I've found them useful, I thought other people might as well.

What can I do with these?

Most of these macros improve basic functionality (e.g. selectable build sheets ) and Klipper compatability with g-code targeting Marlin printers. However, there are also some nice extras:

A few warnings...

Troubleshooting

Reporting Bugs

If you've followed the troubleshooting steps and were unable to resolve the issue you can report a bug via Github. I will probably respond within a few days (almost certainly within a week). I probably won't respond through other channels (e.g. Discord, Twitter), because I don't find them useful for handling bug reports.

Some important things to remember when reporting bugs:

Note: Reports that do not follow the above guidelines will likely be closed without any other action taken.

Contributing

I'm happy to accept bugfix PRs. I'm also potentially open to accepting new features or additions. However, I may decline the PR if it's something I'm not interested in or just looks like it would be a hassle for me to maintain.

Formatting

There's no standard style for Klipper macros, so please just try to follow the style in the files. That stated, here are a few rules to remember:

Commit Messages

These are the rules for commit messages, but you can also just look at the commit log and follow the observed pattern:

Installation

To install the macros, first clone this repository inside of your printer_data/config directory with the following command.

git clone https://github.com/jschuh/klipper-macros.git

Then paste the below sections into your printer.cfg to get started. Or even better, paste all of it into a seperate file in the same path as your config, and include that file. That will make it easier if you want to remove these macros in the future.

You may need to customize some settings for your own config. All configurable settings are in globals.cfg, and can be overridden by creating a corresponding variable with a new value in your [gcode_macro _km_options] section. Do not directly modify the variable declarations in globals.cfg. The macro initialization assumes certain default values, and direct modifications are likely to break things in very unexpected ways.

Note: The paths in this README follow Moonraker's data folder structure. You may need to change them if you are using a different structure.

Note: Make sure you don't currently have any macros that provide the same basic function as the macros in this repository (e.g. the default Mainsail or fluidd macros). As a rule, you should avoid using multiple sets of macros that override the same base macro (unless you really know what you're doing) because conflicting macros can cause all sorts of weird and frustrating problems.

Note: If you have a [homing_override] section you will need to update any G28 commands in the gcode part to use G28.6245197 instead (which is the renamed version of Klipper's built-in G28). Failure to do this will cause G28 commands to error out with the message Macro G28 called recursively.

Klipper Setup

# All customizations are documented in globals.cfg. Just copy a variable from
# there into the section below, and change the value to meet your needs.

[gcode_macro _km_options]
# These are examples of some likely customizations:
# Any sheets in the below list will be available with a configurable offset.
#variable_bed_surfaces: ['smooth_1','texture_1']
# Length (in mm) of filament to load (bowden tubes will be longer).
#variable_load_length: 90.0
# Hide the Octoprint LCD menu since I don't use it.
#variable_menu_show_octoprint: False
# Customize the filament menus (up to 10 entries).
#variable_menu_temperature: [
#  {'name' : 'PLA',  'extruder' : 200.0, 'bed' : 60.0},
#  {'name' : 'PETG', 'extruder' : 230.0, 'bed' : 85.0},
#  {'name' : 'ABS',  'extruder' : 245.0, 'bed' : 110.0, 'chamber' : 60}]
# Length of filament (in millimeters) to purge at print start.
#variable_start_purge_length: 30 # This value works for most setups.
gcode: # This line is required by Klipper.
# Any code you put here will run at klipper startup, after the initialization
# for these macros. For example, you could uncomment the following line to
# automatically adjust your bed surface offsets to account for any changes made
# to your Z endstop or probe offset.
#  ADJUST_SURFACE_OFFSETS

# This line includes all the standard macros.
[include klipper-macros/*.cfg]
# Uncomment to include features that require specific hardware support.
# LCD menu support for features like bed surface selection and pause next layer.
#[include klipper-macros/optional/lcd_menus.cfg]
# Optimized bed leveling
#[include klipper-macros/optional/bed_mesh.cfg]

# The sections below here are required for the macros to work. If your config
# already has some of these sections you should merge the duplicates into one
# (or if they are identical just remove one of them).
[idle_timeout]
gcode:
  _KM_IDLE_TIMEOUT # This line must be in your idle_timeout section.

[pause_resume]

[respond]

[save_variables]
filename: ~/printer_data/variables.cfg # UPDATE THIS FOR YOUR PATH!!!

[virtual_sdcard]
path: ~/gcode_files # UPDATE THIS FOR YOUR PATH!!!
on_error_gcode: CANCEL_PRINT

[display_status]

Slicer Configuration

PrusaSlicer / SuperSlicer

PrusaSlicer and its variants are fairly easy to configure. Just open Printer Settings → Custom G-code for your Klipper printer and paste the below text into the relevant sections.

Start G-code

M190 S0 ; Remove this if autoemit_temperature_commands is off in Prusa Slicer 2.6 and later
M109 S0 ; Remove this if autoemit_temperature_commands is off in Prusa Slicer 2.6 and later
_PRINT_START_PHASE_INIT EXTRUDER={first_layer_temperature[initial_tool]} BED=[first_layer_bed_temperature] MESH_MIN={first_layer_print_min[0]},{first_layer_print_min[1]} MESH_MAX={first_layer_print_max[0]},{first_layer_print_max[1]} LAYERS={total_layer_count} NOZZLE_SIZE={nozzle_diameter[0]}
; Insert custom gcode here.
_PRINT_START_PHASE_PREHEAT
; Insert custom gcode here.
_PRINT_START_PHASE_PROBING
; Insert custom gcode here.
_PRINT_START_PHASE_EXTRUDER
; Insert custom gcode here.
_PRINT_START_PHASE_PURGE

; This is the place to put slicer purge lines if you haven't set a non-zero
; variable_start_purge_length to have START_PRINT automatically calculate and 
; perform the purge (e.g. if using a Mosaic Palette, which requires the slicer
; to generate the purge).

Additional SuperSlicer Start G-code

If you're using SuperSlicer you can add the following immediately before the PRINT_START line from above. This will perform some added bounds checking and will allow you to use the random print relocation feature without requiring exclude_object entries in the print file.

PRINT_START_SET MODEL_MIN={bounding_box[0]},{bounding_box[1]} MODEL_MAX={bounding_box[3]},{bounding_box[4]}

End G-code

PRINT_END

Before layer change G-code

;BEFORE_LAYER_CHANGE
;[layer_z]
BEFORE_LAYER_CHANGE HEIGHT=[layer_z] LAYER=[layer_num]

After layer change G-code

;AFTER_LAYER_CHANGE
;[layer_z]
AFTER_LAYER_CHANGE

Ultimaker Cura

Cura is a bit more difficult to configure, and it comes with the following known issues:

Accepting the caveats, the macros work quite well with Cura if you follow the configuration steps listed below.

Start G-code

M190 S0
M109 S0
_PRINT_START_PHASE_INIT EXTRUDER={material_print_temperature_layer_0} BED={material_bed_temperature_layer_0} NOZZLE_SIZE={machine_nozzle_size}
; Insert custom gcode here.
_PRINT_START_PHASE_PREHEAT
; Insert custom gcode here.
_PRINT_START_PHASE_PROBING
; Insert custom gcode here.
_PRINT_START_PHASE_EXTRUDER
; Insert custom gcode here.
_PRINT_START_PHASE_PURGE

; This is the place to put slicer purge lines if you haven't set a non-zero
; variable_start_purge_length to have START_PRINT automatically calculate and 
; perform the purge (e.g. if using a Mosaic Palette, which requires the slicer
; to generate the purge).

End G-code

PRINT_END

Post Processing Plugin

Use the menu item for Extensions → Post Processing → Modify G-Code to open the Post Processing Plugin and add the following four scripts. The scripts must be run in the order listed below and be sure to copy the strings exactly, with no leading or trailing spaces.

Search and Replace
Search and Replace
Insert at layer change
Search and Replace

Moonraker Configuration

Once you have the macros working and are comfortable using them, you can have Moonraker keep them up to date by adding the following into your moonraker.conf.

[update_manager klipper-macros]
type: git_repo
origin: https://github.com/jschuh/klipper-macros.git
path: ~/printer_data/config/klipper-macros # UPDATE THIS FOR YOUR PATH!!!
primary_branch: main
is_system_service: False
managed_services: klipper

Note: I'd advise against adding the auto-update entries to Moonraker until you have everything working well, because it can make uninstallation a bit harder due to Moonraker's autoupdate behavior.

Removal

If you choose to uninstall these macros you basically need to reverse the installation steps. However, the most critical parts are listed below.

Klipper Configuration Removal

Ensure that you remove the following from your Klipper config (and any included configs):

If you do not have Moonraker autoupdates configured you can delete the klipper-macros directory with something like the following command (adjusted for your own paths):

rm -rf ~/printer_data/config/klipper-macros

Slicer Configuration Removal

If you do not want to change your slicer config, you should be able to leave it as is, because it generates only a small amount of additional gcode, and the basic parameters should work with any other PRINT_START macros.

Moonraker Configuration Removal

If you've configured Moonraker auto-updates you will need to remove the entire [update_manager klipper-macros] section and restart moonraker prior to deleting the klipper-macros directory, otherwise Moonraker may attempt to recreate it. You may also find that it takes a few Moonraker update checks and restarts before the klipper-macros section disappears from the UI.

Command Reference

Customization

All features are configured by setting variable_ values in the [gcode_macro _km_options] section. All available variables and their purpose are listed in globals.cfg.

Note: PRINT_START specific customizations are covered in more detail below.

Bed Mesh Improvements

BED_MESH_CALIBRATE_FAST

Wraps the Klipper BED_MESH_CALIBRATE command to scale and redistribute the probe points so that only the appropriate area in MESH_MIN and MESH_MAX is probed. This can dramatically reduce probing times for anything that doesn't fill the first layer of the bed. If the MESH_MIN and MESH_MAX arguments are provided to PRINT_START it will automatically use this for bed mesh calibration (so long as a [bed_mesh] section is detected in your config).

The following additional configuration options are available from globals.cfg.

Note: See the optional section for additional macros.

Note: The bed mesh optimizations are silently disabled for delta printers.

Note: If the bed_mesh config includes a relative_reference_index then the index point selected in the optimized mesh will be the point closest to the index point in the mesh from the config. However, if a RELATIVE_REFERENCE_INDEX parameter is supplied directly to this macro it will be used unmodified.

BED_MESH_CHECK

Checks the [bed_mesh] config and optionally supplied parameters. Will warn (or optionally abort) if mesh_min or mesh_max could allow a move out of range during BED_MESH_CALIBRATE. This is run implictily at Klipper startup and as part of BED_MESH_CALIBRATE_FAST.

Bed Surface

Provides a set of macros for selecting different bed surfaces with corresponding Z offset adjustments to compensate for their thickness. All available surfaces must be listed in the variable_bed_surfaces array. Corresponding LCD menus for sheet selection and babystepping will be added to Setup and Tune if lcd_menus.cfg is included. Any Z offset adjustments made in the LCD menus, console, or other clients (e.g. Mainsail, Fluidd) will be applied to the current sheet and persisted across restarts.

ADJUST_SURFACE_OFFSETS

Adjusts surface offsets to account for changes in the Z endstop position or probe Z offset. A message to invoke this command will be shown in the console when a relevant change is made to printer.cfg.

LOAD_SURFACE_MESH

Attempts to load a mesh associated with the specified surface.

MAKE_SURFACE_MESH

Generates a mesh associated with the specified surface. If variable_start_try_saved_surface_mesh is true then START_PRINT will load this mesh when the surface is selected (and skip the mesh leveling step if it was specified).

SET_SURFACE_ACTIVE

Sets the provided surface active (from one listed in listed in variable_bed_surfaces) and adjusts the current Z offset to match the offset for the surface. If no SURFACE argument is provided the available surfaces are listed, with active surface preceded by a *.

SET_SURFACE_OFFSET

Directly sets the the Z offset of SURFACE to the value of OFFSET. If no argument for SURFACE is provided the current active surface is used. If no argument for OFFSET is provided the current offset is displayed.

Note: The SET_GCODE_OFFSET macro is overridden to update the offset for the active surface. This makes the bed surface work with Z offset adjustments made via any interface or client.

Beep

Implements the M300 command (if a corresponding pwm_cycle_time beeper or [output_pin beeper] section is present). This command causes the speaker to emit an audible tone.

M300

Emits an audible tone.

Draw

Provides convenience methods for extruding along a path and drawing purge lines.

Note: The drawing macros require every extruder config(s) to have correct nozzle_diameter and filament_diameter settings.

DRAW_LINE_TO

Extrudes a line of filament at the specified height and width from the current coordinate to the supplied XY coordinate (using the currently active extruder).

Note: The Z axis position must be set prior to caling this macro. The HEIGHT parameter is used only to calculate the extrusion volume.

SET_DRAW_PARAMS

Sets the default parameters used by DRAW_LINE_TO. This is helpful in reducing DRAW_LINE_TO command line lengths (particluarly important when debugging in the console).

DRAW_PURGE_LINE

Moves to a position at the front edge of the first print layer and purges the specified length of filament as a line (or rows of lines) in front of the supplied print area. If no print area is specified the purge lines are drawn at the front edge of the maximum printable area. If no printable area is set it defaults to the respective axis limits.

Note: You must set variable_print_min and variable_print_max if the X and Y axis limits in your config allow your toolhead to move outside the printable area (e.g. for dockable probes or purge buckets).

Note: If your print touches the front edge of the bed it will overlap with with the extrusions from DRAW_PURGE_LINE.

Fans

Implements scaling parameters that alter the behavior of the M106 command. Once set, these parameters apply to any fan speed until they are cleared (by default this happens at the start and end of the print).

SET_FAN_SCALING

Sets scaling parameters for the extruder fan.

RESET_FAN_SCALING

Filament

LOAD_FILAMENT / UNLOAD_FILAMENT

Loads or unloads filament to the nozzle.

Marlin Compatibility

Heaters

Adds scaling parameters that can alter the behavior of the specified heater. Once set, these parameters apply to any temperature target on that heater until the scalaing parameters are cleared. A zero target temperature will turn the heater off regardless of scaling parameters.

SET_HEATER_SCALING

Sets scaling parameters for the specified heater. If run without any arguments any currently scaled heaters and thier scaling parameters will be listed. By default the scaling is cleared at the start and end of a print.

Note: a zero target temperature will turn the heater off regardless of scaling parameters.

RESET_HEATER_SCALING

Clears current heater scaling.

Note: if no HEATER argument is specified scaling parameters will be reset for all heaters.

SET_HEATER_TEMPERATURE_SCALED

The scaled version of Klipper's SET_HEATER_TEMPERATURE. All arguments are the same and the function is identical, except that scaling values are applied.

TEMPERATURE_WAIT_SCALED

The scaled version of Klipper's TEMPERATURE_WAIT. All arguments are the same and the function is identical, except that scaling values are applied.

Marlin Compatibility

Note: Both SET_HEATER_TEMPERATURE and TEMPERATURE_WAIT are not overriden and will not scale values. This means that heater scaling adjustments made in clients like Mainsail and Fluidd will not be scaled (because that seemed like the clearest behavior). The custom LCD menus will also replace the temperature controls with non-scaling versions. If you use the stock menus you'll get scaled values.

Kinematics

G28

Extends the G28 command to add lazy homing by not re-homing already homed axes when the O argument is included (equivalent to the same argument in Marlin). See Klipper G28 documentation for general information and detail on the other arguments.

Note: If you have a [homing_override] section you will need to update any G28 commands in the gcode part to use G28.6245197 instead (which is the renamed version of Klipper's built-in G28). Failure to do this will cause G28 commands to error out with the message Macro G28 called recursively.

LAZY_HOME

Homes the specified axes; by default omits any axes that are already homed.

Layer Triggers

Provides the capability to run user-specified g-code commands at arbitrary layer changes.

GCODE_AT_LAYER

Runs abritrary, user-provided g-code commands at the user-specified layer or height. If no arguments are specified it will display all currently scheduled g-code commands along with their associated layer or height.

CANCEL_ALL_LAYER_GCODE

Cancels all g-code commands previously scheduled at any layer or height.

Convenient Layer Change Macros

Note: If any triggers cause an exception the current print will abort. The convenience macros above validate their arguments as much as is possible to reduce the chances of an aborted print, but they cannot entirely eliminate the risk of a macro doing something that aborts the print.

Park

Implements toolhead parking.

PARK

Parks the toolhead.

Note: If a print is in progress the larger of the tallest printed layer or the current Z position will be used as the current Z position, to avoid collisions with already printed objects during a sequential print.

Marlin Compatibility

Pause, Resume, Cancel

PAUSE

Pauses the current print.

RESUME

CANCEL_PRINT

Cancels the print and performs all the same functions as PRINT_END.

Marlin Compatibility

Print Start and End

PRINT_START

Sets up the printer prior to starting a print (called from the slicer's print start g-code). A target CHAMBER temperature may be provided if a [heater_generic chamber] section is present in the klipper config. If MESH_MIN and MESH_MAX are provided, then BED_MESH_CALIBRATE will probe only the area within the specified rectangle, and will scale the number of probes to the appropriate density (this can dramatically reduce probe times for smaller prints).

These are the customization options you can add to your [gcode_macro _km_options] section to alter PRINT_START behavior:

You can further customize the PRINT_START macro by declaring your own override wrapper. This can be useful for things like loading mesh/skew profiles, or any other setup that may need to be performed prior to printing.

Here's a skeleton of a PRINT_START override wrapper:

[gcode_macro PRINT_START]
rename_existing: KM_PRINT_START
gcode:

  # Put macro code here to run before PRINT_START.

  KM_PRINT_START {rawparams}

  # Put macro code here to run after PRINT_START but before the print gcode

Note: You can use this same pattern to wrap other macros in order to account for customizations specific to your printer. E.g. If you have a dockable probe you may choose to wrap BED_MESH_CALIBRATE with the appropriate docking/undocking commands.

PRINT_START Phases

The recommended slicer start gcode breaks PRINT_START into the phases below. This approach allows for pausing or cancelling, and inserting custom gcode between the phases (e.g. to set status LEDs, deploy/dock probes, load filament). The phases are described in order below:

PRINT_END

Parks the printhead, shuts down heaters, fans, etc, and performs general state housekeeping at the end of the print (called from the slicer's print end g-code).

Print Status Events

Note: This is a brand new feature that will likely evolve in the near future. Statuses will probably be added and/or removed as I get a better sense of how they're being used. Keep that in mind as you integrate this into your own setup.

The following events are fired during during the printing process, and the GCODE_ON_PRINT_STATUS command associates custom gcode with these events. This custom gcode can be used to set LEDs, emit beeps, or perform any other operations you may want to run at a given status in the printing process.

GCODE_ON_PRINT_STATUS

Associates a gcode command with a specific status and sets the parameters for when and how the status event fires.

Print Status Event Example

Below is a simple example of how to set up a status event config. The calls to GCODE_ON_PRINT_STATUS are placed in the gcode of the [gcode_macro _km_options] config section, so that they will be run once at printer start. When the printer enters the ready state at startup the command will echo TYPE=LEAVE WHEN=IDLE LAST_STATUS=none NEXT_STATUS=ready to the console, and when it leaves the ready state to begin printing it will echo TYPE=ENTER WHEN=PRINTING LAST_STATUS=ready NEXT_STATUS=homing.

[gcode_macro _km_options]
# Any options variables declared here
gcode:
  GCODE_ON_PRINT_STATUS STATUS=ready COMMAND="STATUS_TEST" ARGS=1 WHEN=ALWAYS TYPE=BOTH

[gcode_macro status_test]
variable_extruder: 0
gcode:
  M118 STATUS_TEST {rawparams}

Velocity

These are some basic wrappers for Klipper's analogs to some of Marlin's velocity related commands, such as accelleration, jerk, and linear advance.

Marlin Compatibility

Optional Configs

Bed Mesh

BED_MESH_CALIBRATE and G29

Overrides the default BED_MESH_CALIBRATE to use BED_MESH_CALIBRATE_FAST instead, and adds the G29 command.

Configuration:

[include klipper-macros/optional/bed_mesh.cfg]

Requirements: A properly configured bed_mesh section.

LCD Menus

Adds relevant menu items to an LCD display and improves some existing functionality. See the customization section above for more information on how to configure specific behaviors.

Configuration:

[include klipper-macros/optional/lcd_menus.cfg]

Requirements: A properly configured display section.