# This file contains pin mappings for the stock 2020 Creality Ender 3
# V2. To use this config, during "make menuconfig" select the
# STM32F103 with a "28KiB bootloader" and serial (on USART1 PA10/PA9)
# communication.

# If you prefer a direct serial connection, in "make menuconfig"
# select "Enable extra low-level configuration options" and select
# serial (on USART3 PB11/PB10), which is broken out on the 10 pin IDC
# cable used for the LCD module as follows:
# 3: Tx, 4: Rx, 9: GND, 10: VCC

# Flash this firmware by copying "out/klipper.bin" to a SD card and
# turning on the printer with the card inserted. The firmware
# filename must end in ".bin" and must not match the last filename
# that was flashed.

# See docs/Config_Reference.md for a description of parameters.


###########################################################
##                       SuperSlicer Filename Format
###########################################################

# {input_filename_base}_{filament_type[0]}_nozzle-{nozzle_diameter}_layer-{layer_height}mm_{fill_density}%_{temperature[0]}C_{total_weight}gr_{print_time}.gcode

###########################################################
##                       Serial Connection 
###########################################################

[mcu]
serial: /dev/serial/by-id/usb-1a86_USB_Serial-if00-port0
restart_method: command

[temperature_sensor raspberry_pi]
sensor_type: temperature_host
min_temp: 10
max_temp: 100

[temperature_sensor mcu_temp]
sensor_type: temperature_mcu
min_temp: 0
max_temp: 100

###########################################################
##                       Printer 
###########################################################

[firmware_retraction]
retract_length: 6
retract_speed: 25 # (60) old
unretract_extra_length: 0
unretract_speed: 20 # (60) old

[printer]
kinematics: cartesian
max_velocity: 300
#max_accel: 7000 # For tests
max_accel_to_decel: 1000 # TEST it first
max_accel: 3000
max_z_velocity: 5
max_z_accel: 150
square_corner_velocity: 10.0 # TEST it first

[input_shaper]
shaper_freq_x: 40.42 # Calculated
shaper_freq_y: 33.90 # Calculated
#shaper_freq_x: 45.5 # OLD
#shaper_freq_y: 46.8 # OLD
#shaper_freq_x: 43.5 # NEW TEST
#shaper_freq_y: 38.5 # NEW TEST
shaper_type: mzv
#shaper_type_x: mzv / ei
#shaper_type_y: mzv / ei

[respond]
default_type: command

[pause_resume]
#recover_velocity: 50.0

[fan]
pin: PA0

[virtual_sdcard]
path: ~/gcode_files

###########################################################
##                       Probe 
###########################################################

[bltouch]
sensor_pin: ^PB1
control_pin: PB0
pin_move_time: 0.680
pin_up_reports_not_triggered: True
pin_up_touch_mode_reports_triggered: True
x_offset: -43
y_offset: -7.5
#z_offset: 3.910
#bltouch: z_offset: 3.270
probe_with_touch_mode: true    # If stow_on_each_sample is True Make probe_with_touch_mode False 
stow_on_each_sample: false   # If probe_with_touch_mode is True Make stow_on_each_sample False


[safe_z_home]
home_xy_position: 117.5,117.5 # Change coordinates to the center of your print bed
speed: 50
z_hop: 10 # Move up 10mm
z_hop_speed: 5

###########################################################
##                       Extruder 
###########################################################

[extruder]
#max_extrude_cross_section: 6
max_extrude_only_distance: 350.0
step_pin: PB4
dir_pin: PB3
enable_pin: !PC3
microsteps: 16
rotation_distance: 22.288    
# rotation_distance: 34.406 (from the initial config)
pressure_advance: 0.704
gear_ratio: 3:1 # BMG gear ratio
nozzle_diameter: 0.400
filament_diameter: 1.750
heater_pin: PA1
sensor_type: EPCOS 100K B57560G104F
sensor_pin: PC5
control: pid
# tuned for stock hardware with 200 degree Celsius target
pid_Kp: 21.527
pid_Ki: 1.063
pid_Kd: 108.982
min_temp: 0
max_temp: 250

###########################################################
##                       Mesh 
###########################################################
[bed_mesh]
speed: 120
horizontal_move_z: 5
mesh_min: 15, 15
mesh_max: 192, 192
probe_count: 3,3
mesh_pps: 2,3 # TEST
algorithm: bicubic
fade_start: 1
fade_end: 10
fade_target: 0
#mesh_x_pps = 2
#mesh_y_pps = 2

###########################################################
##                       Steppers 
###########################################################

[stepper_x]
step_pin: PC2
dir_pin: PB9
enable_pin: !PC3
microsteps: 16
rotation_distance: 40
endstop_pin: ^PA5
position_endstop: 0
position_max: 235
homing_speed: 100

[stepper_y]
step_pin: PB8
dir_pin: PB7
enable_pin: !PC3
microsteps: 16
rotation_distance: 40
endstop_pin: ^PA6
position_endstop: 0
position_max: 235
homing_speed: 100

[stepper_z]
step_pin: PB6
dir_pin: !PB5
enable_pin: !PC3
microsteps: 16
rotation_distance: 8
endstop_pin: probe:z_virtual_endstop
#position_endstop: 0.0
position_max: 250
position_min: -3

###########################################################
##                       Heater Bed 
###########################################################
 
[heater_bed]
heater_pin: PA2
sensor_type: EPCOS 100K B57560G104F
sensor_pin: PC4
control: pid
# tuned for stock hardware with 50 degree Celsius target
pid_Kp: 54.027
pid_Ki: 0.770
pid_Kd: 948.182
min_temp: 0
max_temp: 130

###########################################################
##                       Screen
###########################################################
[display_status]

 # https://www.reddit.com/r/klippers/comments/q6gl65/ender_3_v2_display_help/
 # https://github.com/bustedlogic/DWIN_T5UIC1_LCD
 # https://github.com/GalvanicGlaze/DWIN_T5UIC1_LCD/wiki

###########################################################
##                  Manual Bed Leveling
###########################################################
[bed_screws]
screw1: 35,35
screw1_name: front left screw
screw2: 35,195
screw2_name: rear left screw
screw3: 195,195
screw3_name: rear right screw
screw4: 195,35
screw4_name: front right screw

###########################################################
##                   Screw Adjustment
###########################################################
[screws_tilt_adjust]
screw1: 75,35
screw1_name: front left screw
screw2: 75,192
screw2_name: rear left screw
screw3: 230,192
screw3_name: rear right screw
screw4: 230,35
screw4_name: front right screw
horizontal_move_z: 5
speed: 50
screw_thread: CW-M4

###########################################################
##                       Arc support 
###########################################################

[gcode_arcs]
resolution: 0.2

###########################################################
##                       Marcos
###########################################################
 
# https://albertogrespan.com/blog/3d-printing/klipper-on-an-ender-3/
# https://github.com/Klipper3d/klipper/blob/master/docs/G-Codes.md
# https://www.reddit.com/r/klippers/comments/kj2h5r/stepbystep_guide_for_ender_3_v2_klipper_w_bltouch/
 
# --------------------------- Start Print ----------------------------

[gcode_macro START_PRINT]
#variable_bed_temp: 50
#variable_extruder_temp: 205
gcode:
    # Home
    {% if printer.homed_axes != 'XYZ' %}
      G28		
    {% endif %}

    # Prime line
    M117 PRIME LINE
    PRIME_LINE
    
    # Print message on LCD
    M117 Start printing...

# --------------------------------------------------------------------

# --------------------------- Start Print PLA ----------------------------

[gcode_macro START_PRINT_PLA]
# variable_bed_temp: 50
# variable_extruder_temp: 210
gcode:
    {% set T_BED = params.T_BED|default(50)|float %}
    {% set T_EXTRUDER = params.T_EXTRUDER|default(210) %}
    
    # Print message on LCD
    M117 Start Homing
    
    # Use absolute coordinates
    G92
    
    # Start heating and continue
    M117 Waiting for temperature
    M140 S{T_BED}
    M109 S{T_EXTRUDER}
    M190 S{T_BED} # wait till bed temp is reached, then continue

    # Use absolute coordinates
    G90

    # Reset the G-Code Z offset (adjust Z offset if needed)
    #z_offset: 3.270
    #SET_GCODE_OFFSET Z=3.270
    START_PRINT

# --------------------------------------------------------------------

# --------------------------- Start Print PETG ----------------------------

[gcode_macro START_PRINT_PETG]
# variable_parameter_T_BED: 60
# variable_parameter_T_EXTRUDER: 225
gcode:
    {% set T_BED = params.T_BED|default(60)|float %}
    {% set T_EXTRUDER = params.T_EXTRUDER|default(225)|float %}
    
    # Use absolute coordinates
    G92
    
    # Start bed heating and continue
    M117 Waiting for temperature
    M140 S{T_BED}
    M109 S{T_EXTRUDER}
    M190 S{T_BED} # wait till bed temp is reached, then continue

    # Use absolute coordinates
    G90
    
    # Reset the G-Code Z offset (adjust Z offset if needed)
    z_offset: 3.270
    SET_GCODE_OFFSET Z=3.270
    START_PRINT
 
# --------------------------------------------------------------------

# ---------------------------- End Print -----------------------------

[gcode_macro END_PRINT]
variable_machine_depth: 235
gcode:
    # Relative positionning
    G91
    # Unload little filament
    G1 E-5 Z+10 F3000
    G1 E-10 F1500
    # Print message on LCD
    M117 Done printing :)
    # Turn off bed, extruder, and fan
    M140 S0
    M104 S0
    M106 S0
    M107 ; turn off fan
    # Absolute positionning
    G90
    # absolute xy
    G1 X10 Y200 F2000
    M84
    #BED_MESH_CLEAR

# --------------------------------------------------------------------

# ---------------------------- Prime Line -----------------------------

# prime the nozzle 
[gcode_macro PRIME_LINE]
gcode: 
    # Reset Extruder    
    G92 E0
    G1 Z10 F240
    # Move the nozzle very close to the bed
    G1 X2 Y10 F3000
    G1 Z0.28 F240
    # Wait for bed to reach temperature
    #M190 S{bed_temp}
    # Set and wait for nozzle to reach temperature
    #M109 S{extruder_temp}
    G1 E10 F100 # load little filament
    # Reset Extruder
    G92 E0
    # Move Z Axis up
    G1 Z2.0 F5000
    # Move to start position
    G1 X2.1 Y20 Z0.28 F300
    # Draw the first line
    G1 X2.1 Y150 Z0.28 F1500 E15
    # Move to side a little
    G1 X2.4 Y150 Z0.28 F1500.0
    # Draw the second line
    G1 X2.4 Y20 Z0.28 F1500.0 E30
    # Reset Extruder
    G92 E0
    # Move Z Axis up
    G1 Z2.0 F300
    M117 Start Printing...
 
# ---------------------------- Countdown -----------------------------

#[gcode_macro COUNTDOWN]
#default_parameter_MSG: "Time: "      
#default_parameter_TIME: 10      
#gcode:        
  # countdown 
#  {% for s in range(TIME|int, 0, -1) %}
#  # dwell 1 second
#  G4 P1000
#  # echo
#  M117 {params.MSG} {s}s
#  M118 {params.MSG} {s}s     
#  {% endfor %}

# --------------------------------------------------------------------

# ---------------------------- Load Filament -------------------------

[gcode_macro LOAD_FILAMENT]
# M701
gcode:
  SAVE_GCODE_STATE NAME=loading_filament
  M117 Loading Filament
  M83
  G92 E0.0
  LOW_TEMP_CHECK
  G1 E320 F300  # length of bowden tube till cold-end (~420mm) 
  G1 E20 F100  # some extra to prime the nozzle --> slower 
  G92 E0.0
  RESTORE_GCODE_STATE NAME=loading_filament

# --------------------------------------------------------------------

# ---------------------------- Unload Filament -----------------------

[gcode_macro UNLOAD_FILAMENT]
# M702
gcode:
  SAVE_GCODE_STATE NAME=unloading_filament
  M125 # park
  M117 Unloading Filament 
  LOW_TEMP_CHECK
  G91 # set relative
  G1 E10 F100 
  G92 E0.0
  G1 E-20 F1000
  G1 E-300 F400 # the E is the length of the bowden tube (420mm) + 100 mm. 
  G92 E0.0
  RESTORE_GCODE_STATE NAME=unloading_filament

# --------------------------------------------------------------------

# ---------------------------- Pause ---------------------------------


[gcode_macro PAUSE]
description: Pause the actual running print
rename_existing: PAUSE_BASE
# change this if you need more or less extrusion
variable_extrude: 1.0
gcode:
  ##### read E from pause macro #####
  {% set E = printer["gcode_macro PAUSE"].extrude|float %}
  ##### set park positon for x and y #####
  # default is your max posion from your printer.cfg
  {% set x_park = printer.toolhead.axis_maximum.x|float - 5.0 %}
  {% set y_park = printer.toolhead.axis_maximum.y|float - 5.0 %}
  ##### calculate save lift position #####
  {% set max_z = printer.toolhead.axis_maximum.z|float %}
  {% set act_z = printer.toolhead.position.z|float %}
  {% if act_z < (max_z - 2.0) %}
      {% set z_safe = 2.0 %}
  {% else %}
      {% set z_safe = max_z - act_z %}
  {% endif %}
  ##### end of definitions #####
  PAUSE_BASE
  G91
  {% if printer.extruder.can_extrude|lower == 'true' %}
    G1 E-{E} F2100
  {% else %}
    {action_respond_info("Extruder not hot enough")}
  {% endif %}
  {% if "xyz" in printer.toolhead.homed_axes %}
    G1 Z{z_safe} F900
    G90
    G1 X{x_park} Y{y_park} F6000
  {% else %}
    {action_respond_info("Printer not homed")}
  {% endif %}

# --------------------------------------------------------------------

# ---------------------------- Resume --------------------------------

[gcode_macro RESUME]
rename_existing: RESUME_BASE
description: Resume the actual running print
              
gcode:
  ##### read E from pause macro #####
  {% set E = printer["gcode_macro PAUSE"].extrude|float %}
  #### get VELOCITY parameter if specified ####
  {% if 'VELOCITY' in params|upper %}
    {% set get_params = ('VELOCITY=' + params.VELOCITY)  %}
  {%else %}
    {% set get_params = "" %}
  {% endif %}
  ##### end of definitions #####
  {% if printer.extruder.can_extrude|lower == 'true' %}
    G91
    G1 E{E} F2100
  {% else %}
    {action_respond_info("Extruder not hot enough")}
  {% endif %}  
  RESUME_BASE {get_params}

# --------------------------------------------------------------------

# ---------------------------- Cancel Print --------------------------

[gcode_macro CANCEL_PRINT]
description: Cancel the actual running print
rename_existing: CANCEL_PRINT_BASE
gcode:
  #TURN_OFF_HEATERS
  G91 # Set all axes to relative
  # G90 # Absolute positionning
  CANCEL_PRINT_BASE
  G1 Z10 # Raise Z more
  G1 X10 Y200 F2000 # Absolute xy
  # G1 X0 Y{machine_depth}
  M84 X Y E ; disable motors

# --------------------------------------------------------------------

# ------------------------- Filament Change --------------------------
# M600: Filament Change. This macro will pause the printer, move the
# tool to the change position, and retract the filament 50mm. Adjust
# the retraction settings for your own extruder. After filament has
# been changed, the print can be resumed from its previous position
# with the "RESUME" gcode.


#[gcode_macro FILAMENT_CHANGE1]
# M600
#default_parameter_X: 50
#default_parameter_Y: 0
#default_parameter_Z: 10
#gcode:
#    SAVE_GCODE_STATE NAME=M600_state
#    PAUSE
#    G91
#    G1 E-.8 F2700
#    G1 Z{Z}
#    G90
#    G1 X{X} Y{Y} F3000
#    G91
#    G1 E-50 F1000
#    RESTORE_GCODE_STATE NAME=M600_state
    

# filament change 
[gcode_macro FILAMENT_CHANGE]
# M600
gcode:
  M117 Filament Change
  M118 Filament Change
  SAVE_GCODE_STATE NAME=filament_change
  PAUSE
  LOW_TEMP_CHECK
  G91 # relative
  G1 E-1 F300 # retract 1
  M125 # park
  M702 # unload
  M117 New filament
  M118 New filament
  COUNTDOWN TIME=25 MSG="Switch"
  M701
  COUNTDOWN TIME=10 MSG="Clean"
  RESUME
  M117 Resuming
  M118 Resuming
  RESTORE_GCODE_STATE NAME=filament_change
  M117 Printing..
  M118 Printing..

# --------------------------------------------------------------------

# ------------------------- Motors Off -------------------------------

[gcode_macro MOTORS_OFF] 
gcode:
  M84 X Y E ; disable motors

# --------------------------------------------------------------------

# ------------------------- Bed Mesh Calibrate -----------------------

#[gcode_macro CALIBRATE]
#gcode:
#  G28
#  M118 Start clibrating...
#  BED_MESH_CALIBRATE
#  G0 X0 Y0 Z10 F6000
#  BED_MESH_PROFILE save=default
#  SAVE_CONFIG

[gcode_macro CALIBRATE]
gcode:
  G28
  {% set t = params.T|default(0)|float %}

  {% if printer.idle_timeout.state == "Printing" %}
    {action_respond_info("This command cannot be used while printing")}
  {% elif printer.toolhead.homed_axes != "xyz" %}
    {action_respond_info("Please home XYZ first")}
  {% else %}
    SAVE_GCODE_STATE NAME=G29_state
    # G90
    # G1 Z10 F240
    {% if t > 30.0 %}
      M190 S{t}
    {% endif %}
    BED_MESH_CALIBRATE
    {% if 'S' in params %}
      M140 S{params.S}
    {% endif %}
    G28
    BED_MESH_CALIBRATE
    #G90
    #G1 Z10 F240
    G1 X150 Y155 F6000
    BED_MESH_PROFILE save=default
    RESTORE_GCODE_STATE NAME=G29_state MOVE=0
  {% endif %}

#--------------------------------------------------------------------

# ------------------------- Low Temp Check --------------------------
# LOW_TEMP_CHECK checks if there is a setpoint for the  extruder. Untested! 
# - If this setpoint is reached, continue. 
# - If not, heat to setpoint.
# - If no setpoint, heat to parameter T (default@200)
[gcode_macro LOW_TEMP_CHECK]
gcode:
    {% set T_EXTRUDER = params.T_EXTRUDER|default(205) %}
    {% if printer.extruder.target != 0 %} # if there is a setpoint for extruder
        {% if printer.extruder.temperature < printer.extruder.target %} # if not reached, heat
            M118 Heating from {printer.extruder.temperature} to {printer.extruder.target}.
            M109 S{printer.extruder.target|float} 
        {% endif %}
    {% else %} # if no setpoint for extruder
        {% if printer.extruder.target < T_EXTRUDER %}  # heat to T.
            M118 No setpoint, heating to {T_EXTRUDER}.
            M109 S{T_EXTRUDER}
        {% endif %}
    {% endif %}

#*# <---------------------- SAVE_CONFIG ---------------------->
#*# DO NOT EDIT THIS BLOCK OR BELOW. The contents are auto-generated.
#*#
#*# [bed_mesh default]
#*# version = 1
#*# points =
#*# 	0.015000, -0.030000, -0.007500
#*# 	-0.032500, -0.055000, 0.005000
#*# 	0.002500, -0.045000, 0.005000
#*# tension = 0.2
#*# min_x = 15.0
#*# algo = bicubic
#*# y_count = 3
#*# mesh_y_pps = 2
#*# min_y = 15.0
#*# x_count = 3
#*# max_y = 192.0
#*# mesh_x_pps = 2
#*# max_x = 192.0
#*#
#*# [bltouch]
#*# z_offset = 3.290