Skip to content

Instantly share code, notes, and snippets.

@ChipCE
Last active November 9, 2024 05:36
Show Gist options
  • Save ChipCE/95fdbd3c2f3a064397f9610f915f7d02 to your computer and use it in GitHub Desktop.
Save ChipCE/95fdbd3c2f3a064397f9610f915f7d02 to your computer and use it in GitHub Desktop.
Klipper bed mesh on print area only macro install guide

READ THIS FIRST

Adaptive bed mesh is merged into klipper master branch. You can use this feature without this custom macro. Official klipper adaptive bed mesh

Klipper mesh on print area only install guide

What this macro do

  • This macro will dynamically changing the bed mesh area based on the size of the parts will be printed. The fw will only probe on the area that the part will be printed (plus mesh_area_offset value)

Setup guide

  • (1) Add the following macro to your printer config, this will replace the default BED_MESH_CALIBRATE command.
[gcode_macro BED_MESH_CALIBRATE]
rename_existing: BED_MESH_CALIBRATE_BASE
; gcode parameters
variable_parameter_AREA_START : 0,0
variable_parameter_AREA_END : 0,0
; the clearance between print area and probe area 
variable_mesh_area_offset : 5.0
; number of sample per probe point
variable_probe_samples : 2
; minimum probe count
variable_min_probe_count : 4
; scale up the probe count, should be 1.0 ~ < variable_max_probe_count/variable_min_probe_count
variable_probe_count_scale_factor : 1.0
; enable preference index
variable_enable_reference_index : False
gcode:
    {% if params.AREA_START and params.AREA_END %}
        {% set bedMeshConfig = printer["configfile"].config["bed_mesh"] %}
        {% set safe_min_x = bedMeshConfig.mesh_min.split(",")[0]|float %}
        {% set safe_min_y = bedMeshConfig.mesh_min.split(",")[1]|float %}
        {% set safe_max_x = bedMeshConfig.mesh_max.split(",")[0]|float %}
        {% set safe_max_y = bedMeshConfig.mesh_max.split(",")[1]|float %}

        {% set area_min_x = params.AREA_START.split(",")[0]|float %}
	{% set area_min_y = params.AREA_START.split(",")[1]|float %}
	{% set area_max_x = params.AREA_END.split(",")[0]|float %}
	{% set area_max_y = params.AREA_END.split(",")[1]|float %}

	{% if bedMeshConfig.probe_count.split(",")|length == 2 %}
            {% set meshPointX = bedMeshConfig.probe_count.split(",")[0]|int %}
            {% set meshPointY = bedMeshConfig.probe_count.split(",")[1]|int %}
        {% else %}
            {% set meshPointX = bedMeshConfig.probe_count.split(",")[0]|int %}
            {% set meshPointY = bedMeshConfig.probe_count.split(",")[0]|int %}
        {% endif %}

	{% set meshMaxPointX = meshPointX %}
	{% set meshMaxPointY = meshPointY %}


        {% if (area_min_x < area_max_x) and (area_min_y < area_max_y) %}
            {% if area_min_x - mesh_area_offset >=  safe_min_x %}
                {% set area_min_x = area_min_x - mesh_area_offset %}
            {% else %}
                {% set area_min_x = safe_min_x %}
            {% endif %}

            {% if area_min_y - mesh_area_offset >=  safe_min_y %}
                {% set area_min_y = area_min_y - mesh_area_offset %}
            {% else %}
                {% set area_min_y = safe_min_y %}
            {% endif %}

            {% if area_max_x + mesh_area_offset <=  safe_max_x %}
                {% set area_max_x = area_max_x + mesh_area_offset %}
            {% else %}
                {% set area_max_x = safe_max_x %}
            {% endif %}

            {% if area_max_y + mesh_area_offset <=  safe_max_y %}
                {% set area_max_y = area_max_y + mesh_area_offset %}
            {% else %}
                {% set area_max_y = safe_max_y %}
            {% endif %}

            {% set meshPointX = (meshPointX * (area_max_x - area_min_x) / (safe_max_x - safe_min_x) * probe_count_scale_factor)|round(0)|int %}
            {% if meshPointX < min_probe_count %}
                {% set meshPointX = min_probe_count %}
            {% endif %}
	    {% if meshPointX > meshMaxPointX %}
                {% set meshPointX = meshMaxPointX %}
            {% endif %}

            {% set meshPointY = (meshPointY * (area_max_y -area_min_y ) / (safe_max_y - safe_min_y) * probe_count_scale_factor )|round(0)|int %}
            {% if meshPointY < min_probe_count %}
                {% set meshPointY = min_probe_count %}
            {% endif %}
	    {% if meshPointY > meshMaxPointY %}
                {% set meshPointY = meshMaxPointY %}
            {% endif %}

            {% set algorithm = "bicubic" %}
	    {% if "algorithm" in bedMeshConfig %}
	        {% set algorithm = bedMeshConfig.algorithm %}
            {% endif %}
            {% if meshPointX >=7 or meshPointY >=7 %}
                {% set algorithm = "bicubic" %}
            {% endif %}

            {% if enable_reference_index %}
                {% set referenceIndex = (meshPointX * meshPointY / 2 - 1 )|round(0)|int %}
                BED_MESH_CALIBRATE_BASE mesh_min={area_min_x},{area_min_y} mesh_max={area_max_x},{area_max_y} probe_count={meshPointX},{meshPointY} samples={probe_samples|int} algorithm={algorithm} relative_reference_index={referenceIndex}
            {% else %}
                BED_MESH_CALIBRATE_BASE mesh_min={area_min_x},{area_min_y} mesh_max={area_max_x},{area_max_y} probe_count={meshPointX},{meshPointY} samples={probe_samples|int} algorithm={algorithm}
            {% endif %}
        {% else %}
            BED_MESH_CALIBRATE_BASE
        {% endif %}
    {% else %}
        BED_MESH_CALIBRATE_BASE
    {% endif %}
  • (2) Go to slicer setting and replace the old bed mesh gcode the following command.

Prusa Slicer
BED_MESH_CALIBRATE AREA_START={first_layer_print_min[0]},{first_layer_print_min[1]} AREA_END={first_layer_print_max[0]},{first_layer_print_max[1]}

Ideal maker
BED_MESH_CALIBRATE AREA_START={print_pos_min_x},{print_pos_min_y} AREA_END={print_pos_max_x},{print_pos_max_y}

Cura slicer
BED_MESH_CALIBRATE AREA_START=%MINX%,%MINY% AREA_END=%MAXX%,%MAXY%

*(Cura slicer plugin) To make the macro to work in Cura slicer, you need to install the post process plugin click here to download (based on frankbags's script)
- In cura menu Help -> Show configuration folder.
- Copy the python script from the above link in to scripts folder.
- Restart Cura
- In cura menu Extensions -> Post processing -> Modify G-Code and select Klipper print area mesh

For user using single command START_PRINT

  • (*) If you use single command start gcode like START_PRINT BED_TEMP={material_bed_temperature_layer_0} EXTRUDER_TEMP={material_print_temperature_layer_0} .You might need to add parameter parsing to BED_MESH_CALIBRATE inside START_PRINT. This is an example, also check my macro sample
[gcode_macro START_PRINT]
variable_parameter_EXTRUDER_TEMP: 190
variable_parameter_BED_TEMP: 60
; gcode parameters for area bed mesh
variable_parameter_AREA_START : 0,0
variable_parameter_AREA_END : 0,0
gcode:
    # preheat, homing, etc
    BED_MESH_CALIBRATE AREA_START={params.AREA_START|default("0,0")} AREA_END={params.AREA_END|default("0,0")}
    # the rest of your start macro here

And you will need to change Slicer start gcode to this

  • Cura: START_PRINT EXTRUDER_TEMP={material_print_temperature_layer_0} BED_TEMP={material_bed_temperature_layer_0} AREA_START=%MINX%,%MINY% AREA_END=%MAXX%,%MAXY%
  • Prusa slicer: START_PRINT EXTRUDER_TEMP=[first_layer_temperature] BED_TEMP=[first_layer_bed_temperature] AREA_START={first_layer_print_min[0]},{first_layer_print_min[1]} AREA_END={first_layer_print_max[0]},{first_layer_print_max[1]}

change logs

  • 2022/07/21
    • Added force lagrange algorithm for mesh with lower than 3 points
    • Added enable_reference_index config flag

The code does not work?

  • I will try to help if possible, you will have to post ALL of your configs, your slicer start gcode and your sliced gcode.
  • If I'm cannot or too slow to respose, our discord members might help you. Check our discord here
@sgoph
Copy link

sgoph commented Feb 7, 2023

Can someone please explain what this section does:

{% set algorithm = "lagrange" %}
{% if "algorithm" in bedMeshConfig and meshPointX >=4 and meshPointY >=4 %}
{% set algorithm = bedMeshConfig.algorithm %}
{% endif %}

Is it setting the algorithm to lagrange if the mesh points are 4 or greater? Or.. Is it setting the algorithm to whatever is set in printer.cfg if the points are >=4?

If I wanted to increase the number of probe points calculated for any given print area, would I just increase the scale factor (ie 1.25, 1.5, 1.75)?

Thanks!

@ChipCE
Copy link
Author

ChipCE commented Feb 7, 2023

@sgoph It's not that well writen, but similar to this.

{% set algorithm = bedMeshConfig.algorithm %} {% if meshPointX <4 and meshPointY <4 %} {% set algorithm = "lagrange" %} {% endif %} Bicubic need 4 points or more so we will need to force change to lagrange if the meshPoints are under 4.

Yes. Increase the scale factor will do it.

@whi-tw
Copy link

whi-tw commented Feb 9, 2023

I'm working on a macro which enables per-object meshes if:

  1. 'Label Objects' is turned on in the slicer
  2. moonraker is set up with:
    [file_manager]
    enable_object_processing: True
    
  3. klipper is configured with [exclude_object]

This will make a single small mesh for every item on the bed and load it dynamically when the object starts printing:

https://github.com/whi-tw/klipper-adaptive-mesh/releases/tag/v0.0.2 (adaptive_bed_mesh.cfg in the Assets section)

This has the benefit of the meshes being very detailed, as they are only made on the area of each object - no wasted space.

If anyone wants to give it a go, please leave feedback on the repo with any issues.

@rstudner
Copy link

Minor help request from y'all experts... for some reason I can't seem to get this right.

My Ender bed isn't very flat (hah!)

So if I have it calculate a mesh for a smaller object in the center of the bed, when it moves fromt he post-purge line to the center, it'll scratch/drag my nozzle on the way over.

Trying to get it to move up 1mm, navigate to 'skirt/brim/whatever' start ,then lower back down 1mm

@ChipCE
Copy link
Author

ChipCE commented Feb 14, 2023

@rstudner This macro cannot be changed to fix your problem. But modify your start gcode can fix that. Post your start gcode here and i will try to look at it.

@andrewt27
Copy link

andrewt27 commented Feb 19, 2023

@ChipCE Hi, I have a fairly large distance between the nozzle and the sensor (57mm). With large print I get errors like this
!! Move out of range: -27.016 86.484 5.000 [0.000]
How to compensate it?

Edit:
[SOLVED] I have changed x min in config:
[bed_mesh]
...
mesh_min: 57, 10
...

@kllxdababy
Copy link

22:13
Internal error on command:"PRINT_START"
22:13
Internal error on command:"BED_MESH_CALIBRATE"
22:13
Internal error on command:"BED_MESH_CALIBRATE_BASE"

Getting this error after my voron does QGL and homes.

Here is my print start macro:
[gcode_macro PRINT_START]
variable_parameter_EXTRUDER_TEMP: 190
variable_parameter_BED_TEMP: 30

gcode parameters for area bed mesh

variable_parameter_AREA_START : 0,0
variable_parameter_AREA_END : 0,0
gcode:
G32 ; home all axes
G90 ; absolute positioning
G1 Z20 F3000 ; move nozzle away from bed
BED_MESH_CALIBRATE AREA_START={params.AREA_START|default("0,0")} AREA_END={params.AREA_END|default("0,0")}

@Zephyrus67
Copy link

Where exactly did you get %MINX% etc. from in Cura slicer? in my Cura that does not pass anything but the %MINX% and similar.

I am already using the "START_PRINT BED_TEMP=110 EXTRUDER_TEMP=255" part but the definition of area does not seem to work

@Zephyrus67
Copy link

Sorry. I didnt see the part where the plugin is mentioned...got it working now.

@Zephyrus67
Copy link

Zephyrus67 commented Mar 3, 2023

But will you not need a "BED_MESH_PROFILE Load=default" in your printer.cfg to actually load the saved mesh? With normal BED_MESH_CALIBRATE you need to.

@1yrik
Copy link

1yrik commented Mar 10, 2023

The script works great, mostly. I have one issue (more of a minor inconvenience) where the Klipper gives a "Must home axis first: 0.000 0.000 5.000 [0.000]" on 3 consecutive lines. I just have to manually home the printer and then it works great, it's still just an inconvenience. My though is just that a G28 (I have a G28 macro) needs to be thrown in somewhere, I'm just not sure where exactly...
Thanks in advance for any help!
8% Printing - ETA_ 21_12 - handletest gcode - Google Chrome 2023-03-09 8_36_18 PM

@ChipCE
Copy link
Author

ChipCE commented Mar 10, 2023

@1yrik I think you need to edit your start gcode. This override macro is the same as the original BED_MESH_CALIBRATE, it can be called without homed axis.

@1yrik
Copy link

1yrik commented Mar 10, 2023

@ChipCE I know I have to add in a "G28" somewhere, I'm just not sure where. I'll take another look and see if anything obvious needs changing.

@Matei-alt
Copy link

When I boot up my printer after doing said changes I get this error. How can I fix this?
image

@ChipCE
Copy link
Author

ChipCE commented Mar 14, 2023

@Matei-alt seem like you dont have [bed_mesh] enabled in your config.

@Matei-alt
Copy link

@ChipCE Oh, I tought "this will replace the default BED_MESH_CALIBRATE command." meant to just replace that whole thing. Sorry for bothering you.

@mattfox27
Copy link

I have a question when probing begins the probe almost drags across the bed, like it does not go up it stays on the bed moves to the left then goes up a little and back down, is that correct?

@frankbags
Copy link

frankbags commented Mar 25, 2023

That's normal behavior if you have the option under [bltouch] stow_on_each_sample: false

https://www.klipper3d.org/BLTouch.html#multi-probing-without-stowing

if you have no clearance issues then it shouldn't be a problem, it does save a lot of time when building a mesh

@mattfox27
Copy link

Ya the probe was actually touching the bed as it moved to the next point which was causing false readings. I have to add a line in mesh section like horizontal_Z_probe: 8. This wasn't the exact line but something similar

@screech24
Copy link

Anyone using Bambu Studio or Orcaslicer ? I cant seem to get this to work using either of those slicers.. using the prusaslicer settings ... "START_PRINT EXTRUDER_TEMP=[first_layer_temperature] BED_TEMP=[first_layer_bed_temperature] AREA_START={first_layer_print_min[0]},{first_layer_print_min[1]} AREA_END={first_layer_print_max[0]},{first_layer_print_max[1]}"

@FraLem89
Copy link

M190 S[bed_temperature_initial_layer_single]
M109 S[nozzle_temperature_initial_layer]
M117
PRINT_START EXTRUDER=[nozzle_temperature_initial_layer] BED=[bed_temperature_initial_layer_single] PRINT_MIN={first_layer_print_min[0]},{first_layer_print_min[1]} PRINT_MAX={first_layer_print_max[0]},{first_layer_print_max[1]}

@DaKlassiker
Copy link

DaKlassiker commented Apr 17, 2023

Unknown command:"AREA_START=158.387,158.396"

it does the full bed then. Any ideas? i´m using klicky probe

Superslicer:
PRINT_START BED=[first_layer_bed_temperature] EXTRUDER={first_layer_temperature[initial_extruder]+extruder_temperature_offset[initial_extruder]} CHAMBER=[chamber_temperature]
AREA_START={first_layer_print_min[0]},{first_layer_print_min[1]} AREA_END={first_layer_print_max[0]},{first_layer_print_max[1]}

[gcode_macro PRINT_START]
variable_parameter_AREA_START : 0,0
variable_parameter_AREA_END : 0,0

gcode:
{% set FILAMENT = params.FILAMENT|default('Default')|string %}
{% set MIN_TEMP = params.EXTRUDER|int * 0.9 %}
{% set BED_TEMP = params.BED|default(0)|int %}
{% set EXTRUDER_TEMP = params.EXTRUDER|default(0)|float %}
{% set chamber = params.CHAMBER|default(0)|int %}

SET_GCODE_VARIABLE MACRO=PRINT_START VARIABLE=chambertemp VALUE={chamber}

{% if params.FILAMENT == 'ABS' %}
	{% set nevermore_fan_speed = 0.70 %}
  
{% elif params.FILAMENT == 'ASA' %}
    {% set nevermore_fan_speed = 0.70 %}

{% elif params.FILAMENT == 'PETG' %}
	{% set nevermore_fan_speed = 0.40 %}
	
{% elif params.FILAMENT == 'PLA' %}
	{% set nevermore_fan_speed = 0 %}

{% elif params.FILAMENT == 'WOOD' %}
	{% set nevermore_fan_speed = 0 %}
	
{% else %} 
	{% set nevermore_fan_speed = 0 %}
{% endif %}

SET_FAN_SPEED FAN=Nevermore SPEED={nevermore_fan_speed}
#SET_FILAMENT_SENSOR SENSOR=filament_sensor ENABLE=1
M107
M117 {params.FILAMENT}
M190 S{BED_TEMP} #M140
G28
G90
 {% if printer["temperature_sensor chamber"].temperature < chamber %}              
    HEATSOAK T={BED_TEMP} MOVE=1                                                         
    M190 S{BED_TEMP}                                                                    
    TEMPERATURE_WAIT SENSOR="temperature_sensor chamber" MINIMUM={chamber}          
{% else %}                                                                         
    {% if printer.heater_bed.temperature < (BED_TEMP-2) %}                               
        HEATSOAK T={BED_TEMP} MOVE=1                                                     
        M190 S{BED_TEMP}                                                                 
    {% else %}                                                                      
        HEATSOAK T={BED_TEMP} MOVE=0                                                   
    {% endif %}
{% endif %} 
M106 S0                                                                              
LEDWHITE 
ATTACH_PROBE_LOCK                                                              
QUAD_GANTRY_LEVEL                                                                  
G28 Z                                                                           
G90                                                                               
G0 Z20                                                                              
G0 X{printer.toolhead.axis_maximum.x/2} Y{printer.toolhead.axis_maximum.y/2} F19500 
BED_MESH_CALIBRATE AREA_START={params.AREA_START|default("0,0")} AREA_END={params.AREA_END|default("0,0")}
DOCK_PROBE_UNLOCK                                                                   
M109 S{EXTRUDER_TEMP}
SETACTUAL_ETMP
G1 E-1 F300
CALIBRATE_Z                                                                       
G92 E0                                                                             
PRIME_NOZZLE

@ChipCE
Copy link
Author

ChipCE commented Apr 18, 2023

@DaKlassiker your Prusa start gcode is splitted into 2 lines. They must be in the same line.

@HelioSG
Copy link

HelioSG commented May 3, 2023

@ChipCE
Dear, I'm trying to use the macro Klipper mesh on print area only, but I'm getting an error message:
"Internal error on command:"BED_MESH_CALIBRATE_BASE"
Once the underlying issue is corrected, use the
"FIRMWARE_RESTART" command to reset the firmware, reload the
config, and restart the host software." Could you help me

@gtollini
Copy link

gtollini commented May 6, 2023

@ChipCE
Klipper has a minimum probe distance which isn't addressed by the current script. This can easily be solved by adding:

{% if (area_max_x - area_min_x) / meshMaxPointX < 1 %}
  {% set meshPointX = (area_max_x - area_min_x)|int %}
{% endif %}

And

{% if (area_max_y - area_min_y) / meshMaxPointY < 1 %}
  {% set meshPointY = (area_max_y - area_min_y)|int %}
{% endif %}

After the checks at lines 69-71 and 77-79.

@ChipCE
Copy link
Author

ChipCE commented May 7, 2023

@gtollini Thank for point out the bug!

I have some question about your fix code

{% if (area_max_x - area_min_x) / meshMaxPointX < 1 %}
  {% set meshPointX = (area_max_x - area_min_x)|int %}
{% endif %}
  • in the first line, we check if the probe distance is smaller than 1 or not, {% if (area_max_x - area_min_x) / meshMaxPointX < 1 %} should be {% if (area_max_x - area_min_x) / meshPointX < 1 %}
  • Why set {% set meshPointX = (area_max_x - area_min_x)|int %}? We set the mesh to 1mm distance with this?

@DocKuro
Copy link

DocKuro commented May 8, 2023

Hello, I'm trying to get this script to work, I added the macro and modified the START_PRINT line on superslicer; now the generated GCODE for my sample print looks like this:

START_PRINT EXTRUDER_TEMP=195 BED_TEMP=60 AREA_START=118.669,78.6702 AREA_END=231.35,191.33

The macro generate the points, but then fails calling the BED_MESH_CALIBRATE_BASE, so I made some try and generated a command that should cover my area, like this:

BED_MESH_CALIBRATE_BASE mesh_min=118.669,78.6702 mesh_max=231.35,191.33 probe_count=4,5 samples=5 algorithm=bicubic

The macro returns this output:

// Generating new points...
// bed_mesh: generated points
// Index | Tool Adjusted | Probe
// 0 | (129.3, 34.1) | (118.7, 78.7)
// 1 | (166.8, 34.1) | (156.2, 78.7)
// 2 | (204.4, 34.1) | (193.8, 78.7)
// 3 | (241.9, 34.1) | (231.3, 78.7)
// 4 | (241.9, 62.2) | (231.3, 106.8)
// 5 | (204.4, 62.2) | (193.8, 106.8)
// 6 | (166.8, 62.2) | (156.2, 106.8)
// 7 | (129.3, 62.2) | (118.7, 106.8)
// 8 | (129.3, 90.4) | (118.7, 135.0)
// 9 | (166.8, 90.4) | (156.2, 135.0)
// 10 | (204.4, 90.4) | (193.8, 135.0)
// 11 | (241.9, 90.4) | (231.3, 135.0)
// 12 | (241.9, 118.6) | (231.3, 163.2)
// 13 | (204.4, 118.6) | (193.8, 163.2)
// 14 | (166.8, 118.6) | (156.2, 163.2)
// 15 | (129.3, 118.6) | (118.7, 163.2)
// 16 | (129.3, 146.7) | (118.7, 191.3)
// 17 | (166.8, 146.7) | (156.2, 191.3)
// 18 | (204.4, 146.7) | (193.8, 191.3)
// 19 | (241.9, 146.7) | (231.3, 191.3)
// Klipper state: Shutdown
!! Internal error on command:"BED_MESH_CALIBRATE_BASE"

and the Fluidd UI error message says list index out of range
The points look all valid to me (print area is 350x310), could you point me to something else to look at?

@DocKuro
Copy link

DocKuro commented May 8, 2023

Well, it was easier than expected, I just had to enable the reference_index calculation in your macro
variable_enable_reference_index : True

@HelioSG check if this helps you too since your error looked very similar to mine.
Basically if you set a relative_reference_index in your [bed_mesh] configuration section, you have to enable its dynamic calculation, otherwise the index will not be relevant and its index could be outside the number of points generated, giving the aforementioned error.

@louispires
Copy link

Got it working good on my 400³ V-Core 3 - However 1 thing I noticed was the default BED MESH is saved as RATOS, this now saves it under DEFAULT, which during each layer change, causes these two log entries:
image

Not a BIG deal but if I could save this as RATOS, then it shouldn't load the BED mesh multiple times...

@ChipCE
Copy link
Author

ChipCE commented May 11, 2023

@louispires you can add BED_MESH_PROFILE LOAD= SAVE= REMOVE= to set the profile name you want to save to or load from.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment