﻿Sub Main()																	'CNC tool offset Macro for MACH3'This macro is a Copy of the Bo Andersen, August 2015. Thanks for make a video with this Script explained''This macro picks up one tool at the time from the ATX' Probes each tool on a fixed touch plate, and updates the mach3 tool database parameter "Z Offset"'Using the z offset value together with G43 Hxx then each tool is compensated for it's lenght (where xx is the tool number)'So there will be no need to touch-off each tool after a tool change. As a real CNC is supposed to work :-)'This macro always starts with tool 1 thought tool xx (user is promted on how many tool to update) Tool Number = 0 is not allowed.'Bo Andersen, August 2015'''Misc info:'Z-Acis is homing in positive directuion, so all MC are negative values'1 input is used. Probe input, And must be defined in MACH3 ports and pins.'A different coordinate system in used this macro and values will be overwritten (Default coord system number 254)'Tools with a tool number = 0 is not supported in this macro.'''Abbreviations:' DRO = Digital Read Out' M.C. = Machine Coordinates'''====Variables===MaxToolNum = 8													'Maximum number of tools in ATC, in order to check if a legal tool number is usedFirstToolNum = 0												'First tool to probe (0 is dummy value)LastToolNum = 0													'Last tool to probe (0 is dummy value)CurrentToolNum = 0												'The tool number currently being processed'------- Safety Check: Is the probe enabled in Ports in Pins of MACH3? -----If IsSuchSignal (22) = 0 Then											'Is a probe input enabled in mach3 ?Message "Somebody forgot to enable the Probe pin in mach3...."							'Then write an error message to the user		Exit Sub													'exitEnd If'-------Safety Check: Is the fixed touch plate already active/grounded ? ----If GetOEMLED (825) ThenMessage "Engineer to the bad bad probe: You are grounded !"Exit SubEnd If'-------Safety Check: Spindle are running? ----If GetOEMLED (11) ThenMessage "Are you mad ? STOP the spindle!!"Exit SubEnd If'-------Safety Check: Wait for any movement to complete ----While IsMoving()												'Wait for all axis movementsSleep(100)													'Sleeps while waiting, this frees up CPU usageWend														'End of the loop'-------User input the firts tool to probe-----While FirstToolNum = 0 Or FirstToolNum > MaxToolNum								'Loop here, until you get a valid tool numberFirstToolNum = Question ("Posa la PRIMERA eina a mesurar: [1-" & MaxToolNum & "]")				'User Inpit a number between 1 and  MaxToolNumWend														'End of while loop'-------User input the Last tool to probe-----While LastToolNum < FirstToolNum Or LastToolNum > MaxToolNum							'Loop here, until you get a valid tool numberLastToolNum = Question ("Posa la ULTIMA eina a mesurar: [" & FirstToolNum & "-" & MaxToolNum & "]")		'User Input a number between FirstToolNum amb MaxToolNumWend														'End of while loop'------- Creating a loop for processing the selected tool range ------CurrentToolNum = FirstToolNum											'Set the current tool numner = first tool numberCode "G49"													'Cancel Z tool lenght offsetIf FirstToolNum = LastToolNum ThenCall Probe(CurrentToolNum)											'Goto probe sequenceElseWhile CurrentToolNum <> (LastToolNum + 1)									'Run in this while loop until CurrentToolNum = LastToolNumCall Probe(CurrentToolNum)											'call the probing sub routineCurrentToolNum = CurrentToolNum + 1										'Increase the currentoolnum with 1 and run loop againWend														'end of while loop when: CurrentToolNum = LasToolNumEnd IfCode "G43 H" & GetCurrentTool()											'Re-activate Z tool lenght offset for current tool in spindleSleep(250)													'Wait for DRO UpdateEnd Sub														'End of main program.'------------ Probing sub routine ------------Sub Probe(CurrentToolNum)											'The tool change and probing sub-routineXPos = 120													'X-Machine coords of the fixed touchYPos = 312													'Y-Machine coords of the fixed touchZProbeStart = -100.00												'Z-M.C. height above fixed touch plate, where the probing startsZProbeMax = -165.00												'Z-M.C. the probe is supposed to touch, before this depth is reached.ZRetract = 2.00													'POSITIVE VALUE!! number of units to retract the z-axis.ProbeFeed1 = 300												'Feed of the first probe run ProbeFeed2 = 50													'Feed of the second probe runCoSystemNum = 253												'Coordinate system number to use for this macro, value must be (1-254).CurrentFeedRate = GetOEMDRO(818)										'Read current feed rate'====Caññ fpr a tool change=====Message "Current Tool Num = " & CurrentToolNum									'Writes message to user which to is being processed'Code "M6 T" & CurrentToolNum											'Warning: You CANNOT call your normal "M6 Txx here. 														'so we need to replicate the tool change code in this script (for avoid call another script in this script and avoid problems)Call ATC(CurrentToolNum)											'Call the tool change sub-program, asking for tool numberWhile IsMovingSleep(100)Wend'----Get in position and Zero Z-Axis ----Message "Coordinate system number = " & CoSystemNum								'debugCode "G59 P" & CoSystemNum											'Swith to a different coordinate systemCode "G53 G00 Z0.0"												'Move tool to upper most position (Z= 0.0 M.C)(Z-axis homing in positive)Sleep(100)WendMessage "Xpos = " & Xpos & "YPos = " & Ypos									'debug messageCode "G53 G00 X" & XPos & "Y" & Ypos										'move tool over the touch plate locationWhile IsMovingSleep(100)WendMessage "Zero Z DRO"												'Debug...SetOEMDRO(802, 0.0000)												'Reset the Z-Axis work DRO to 0.0, now both MC and work are the sameSleep(250)'--------First probe run ------------Message " Z Probe Start = " & ZProbeStart 									'DebugCode "G53 G00 Z" & ZProbeStart											'MC rapid down to probe starting positionWhile IsMovingSleep(100)WendCode "G01 F" & ProbeFeed1											'Change the feedrateCode "G31 Z" & ZProbeStart											'Do the actual probing, at 1st feed rateWhile IsMoving()												'wait for touchSleep(100)Wend														'end of while loopProbeDist = GetVar(2002)											'Read Z-axis value of probe touch plateMessage "Getvar 2002 = "& ProbeDist										'debug'--------Segona pasada de eina al touch plate ------------Code "G00 Z" & ProbeDist + ZRetract										'Retract "Zretact" units before starting 2nd probe Code "G01 F" & ProbeFeed2											'change feedrate to second feed rateCode "G31 Z" & ZProbeMax											'probing at second feed rateWhile IsMoving()												'wait for probing to finishSleep(100)Wend														'end of while loopProbeDist2 = GetVar(2002)											'Read the z-axis value of probe touch pointMessage "Getvar 2002 = "& ProbeDist2										'debugSetToolParam(CurrentToolNum,2,ProbeDist2+150)									'set CurrentToolNum with parameter 2 = 2 offset, to the probesdist2+150 (150 is my aprox machine distance from the top where my regular tools are proved)														'It's for try to have a positive number for avoid some problems when deactivate a tool lenght offser and you have a huge length or an offset you might end up that you're out of bounds or you'll hit a soft limit or something like that														'So adding +150 to the probedist gives a tool lenght offset arround -10 to +50														'depending on your machine this number can be changedSleep(250)													'Wait fir ToolParam to updateDoOEMButton(316)												'Save Tool table databaseCode "G53 G00 Z-5.0"												'Move spindle almost to top (-5)Code "G59 P1"													'Reactivate coords G54End Sub														'FINAL DE LA RUTINADE PROBING'---------------M6 Start, Tool change routine------------''''--- Variables:------NewTool = CurrentToolNum										'Tool number of the tool to change toOldTool = GetCurrentTool()										'Tool number of the tool to change from (tool in spindle)WorkX = GetToolChangeStart(0)										'X position from where the tool change was initiatedWorkY = GetToolChangeStart(1)										'Y position from where the tool change was initiated		WorkZ = GetToolChangeStart(2)										'Z position from where the tool change was initiatedMaxToolNum = 8												'Maximum number of tools, in order to check if a legal tool number is requiredToolTreverse = -75											'M.C. Height while moving from one tool pisition to another with safe heigh for avoid colisions of tools with tool holderSafeZ = -5												'Extra safe ZDrawBar = Output11											'Output Port of mach3Airblow = Output12											'Output Port of mach3----- i need to change this i use airblow and drawbar at same time and i use output12 for pneumatic tool holderXpos = 0												'X Height of each individual tool in tool holder (0 is dummy value)YPos = 0												'Y Height of each individual tool in tool holder (0 is dummy value)ZPos = 0												'Z Height of each individual tool in tool holder (0 is dummy value)YPosSlide = 570.00											'Distance from bed toolholder to start sliding the tool into holder (this number is only for test in air without danger of break something, when this script work i go to put the correct numbers)While OldTool = 0 Or OldTool > MaxToolNum								'When mach3 boots up the current tool is always number T00, so i need to change it because it because in this script tool 0 doesnt work and if the tool is more than maxtoolnum too.OldTool = Question ("Invalid tool number in Spindle! Enter: [1-" & MaxToolNum & "]")			WendIf NewTool = 0 Or NewTool > MaxToolNum Then								'Check if the requested tool is within range of the changer (from 1 to maxtoolnum)Message "Invalid tool number request ! [Tool #" & NewTool & "]"						'If no stop the programCode "M30"												'STOP program, reason is that tool length compensation is controlled in the Exit Sub												'Then exit this tool change routineEnd IfIF NewTool = OldTool Then										'If the new tool is identical to the old tool	Exit Sub											'I dont need a tool change because i have the correct tool in spindleEnd IfCode "G00 G53 Z" & SafeZ										'Goto safe traversing height. Rapid move to machine coords of SafeZ height configured in script'----Place old tool in bed holder----Call ToolPos (OldTool,XPos, Ypos, ZPos)									'Call the sub routine to get coords for old tool positionCode "G53 X" & Xpos & "Y" & YPosSlide									'Move to sliding positionCode "G53 Z" & ToolTreverse										'Move spindle to tool traversing heightWhile IsMoving()											'Wait for movement to finishSleep(100)Wend' ActivateSignal(Airblow)										'DEACTIVATED!!!! Turn on the air blow deactivated because i use airblow and opencollet in the same output (same time)Code "G53 Z" & ZPos											'Move down to place tool in the changerCode "G53 Y" & Ypos											'Slide tool into bed holderWhile IsMoving()											'wait for movement to finishSleep(100)																		WendActivateSignal(DrawBar)											'Activate the drabar and release the toolSleep(1000)												'Wait 1 second for open the drawbarCode "G53 Z" & ToolTreverse										'Move to safe tool traversind height'------- Pick up new tool from bed holder ---------Call ToolPos (NewTool,XPos, YPos, ZPos)									'Call the sub routine to get coordinates for new tool positionCode "G53 X" & Xpos & "Y" & YPos									'Move to new tool positionCode "G53 Z" & ZPos											'Down to dis-engage the toolWhile IsMoving()											'Wait for movement to finishSleep(100)WendDeActivateSignal(DrawBar)										'Deactivate the drawbar and clamp the tool' DeActivateSignal(Airblow)										'DISABLED!! Deactivate the airblowSleep(6000)												'Wait for drawbar to engage (6 seconds for the moment i need to test how many time need when all works)Code "G53 Y" & YPosSlide										'Move tool out the tool holder (sliding)Code "G53 Z" & SafeZ											'Move to Z safeSetCurrentTool(NewTool)											'Now set the new tool as current toolSleep(250)												'Wait for DRO to update'End Sub'--- Find the coordinates of the tool positions in the Bed-Tool holder ----Sub ToolPos(ByVal ToolNumber As Integer, ByRef XPos, ByRef YPos, ByRef ZPos)		'Subtoutine to find tool location coordinates	Select Case ToolNumber		Case is = 1								'If the tool number is 1 then read these XYZ positions					Xpos = 112.25					'Here specify  the Machine coords of the tool 1 position.					Ypos = 304.79					'same for all cases					Zpos = -80.00		Case is = 2					Xpos = 212.25					Ypos = 304.79					Zpos = -80.00					Case is = 3					Xpos = 312.25					Ypos = 304.79					Zpos = -80.00		Case is = 4					Xpos = 412.25					Ypos = 304.79					Zpos = -80.00		Case is = 5					Xpos = 512.25					Ypos = 304.79					Zpos = -80.00		Case is = 6					Xpos = 612.25					Ypos = 304.79					Zpos = -80.00		Case is = 7					Xpos = 711.50					Ypos = 304.79					Zpos = -80.00		Case is = 8					Xpos = 111.50					Ypos = 304.79					Zpos = -50.00						End Select	End Sub 