o<m21> sub

; Move Carousel to the tool change position - OUT
; then unload any tool in the spindle into the current pocket
; Parameter #3991 is used to track the current tool loaded it in the spindle (persistently)
; #<atc_z_tool_change_height> is the height you spindle needs to be at to clamp/unclamp a tool form the ATC (Set via INI [ATC]Z_TOOL_CHANGE_HEIGHT)
; #<atc_z_tool_clearance_height> is the clearance height you spindle needs to be at to safely clear the ATC (Set via INI [ATC]Z_TOOL_CLEARANCE_HEIGHT)
(PRINT, o<m21>)

#<atc_z_tool_change_height> = -3.9000
o100 if [EXISTS[#<_ini[atc]z_tool_change_height>]]
    #<atc_z_tool_change_height> = #<_ini[atc]z_tool_change_height>
o100 endif
#<atc_z_tool_clearance_height> = [#<_ini[AXIS_Z]MAX_LIMIT>-0.01]
o110 if [EXISTS[#<_ini[atc]z_tool_clearance_height>]]
    #<atc_z_tool_clearance_height> = #<_ini[atc]z_tool_clearance_height>
o110 endif

M65 P1 ; switch off carousel in solenoid
M66 P1 L3 Q1

M5 M9
G90
G0 G53 Z#<atc_z_tool_change_height> ; rapid move to above the tool change height

;M19 R0 Q3 ; orient spindle

M64 P0 ; Move Carousel out
M66 P1 L3 Q5 ; check for carousel out sensor
o120 if [#5399 LT 0]
    M65 P0 ; switch off atc out solenoid
    (abort, ATC not in position)
o120 endif

M24 ; activate drawbar, release the tool
M5 ; turn off spindle lock

G0 G53 Z#<atc_z_tool_clearance_height> ; move z to clear height

#3991 = 0; save fact there is now no tool in the spindle

(PRINT, o<m21> endsub)
o<m21> endsub [1]

M2
