Subprograms, Parametric Programming and Custom CyclesIntroductionComputer numerical control (CNC) programs are often introduced as ordered lists of tool motions. In production, however, many components contain repeated holes, pockets, slots, bolt circles, mirrored features, or families of geometrically related parts. Writing every motion explicitly is inefficient and increases the risk of inconsistency. Advanced CNC programming therefore uses subprograms, variables, arithmetic, logic, coordinate transformations, and custom cycles to make programs shorter, more adaptable, and easier to verify. This chapter develops these techniques for a Bachelor-level CNC programming course. The examples use Fanuc/Haas-style macro notation, but exact syntax varies among controllers. A programmer must always consult the machine-tool control manual before transferring code to production. Learning ObjectivesAfter studying this chapter, the reader should be able to: - Explain the purpose and structure of subprograms and macro calls.
- Distinguish local, common, and system variables.
- Use arithmetic, comparison, branching, and looping constructs safely.
- Apply parametric programming to families of parts and repeated features.
- Explain coordinate rotation, scaling, and coordinate translation.
- Design reusable probing and inspection routines.
- Develop custom cycles with error checking and safe recovery.
- Evaluate the benefits and risks of macro programming in production.
1. Subprograms as Reusable Program ModulesA subprogram is a separately numbered CNC program containing a sequence of operations that can be called from a main program. When execution reaches a call, control transfers to the subprogram. On completion, a return command sends control back to the statement following the call. A typical structure is: O0100 (MAIN PROGRAM)
G90 G17 G40 G49 G80
G54
T01 M06
S2500 M03
G43 H01 Z50.0
M98 P1000
M98 P1000 L3
G00 Z100.0
M30
O1000 (HOLE PATTERN SUBPROGRAM)
G00 X20.0 Y20.0
G81 Z-12.0 R2.0 F120.
X80.0
G80
M99 Here, M98 P1000 calls program O1000. The address L3 requests three executions in controllers that support repeated subprogram calls. M99 returns from the subprogram, whereas M30 normally ends and rewinds the main program. Subprogram design principlesA good subprogram has a clear interface, predictable modal behavior, and a defined starting and ending condition. It should document: - required work offset and tool;
- expected units and programming mode;
- coordinate system and plane;
- spindle and coolant assumptions;
- input dimensions or variables;
- safe approach and retract positions;
- return condition and error behavior.
A subprogram should not silently alter important modal states unless that change is intentional and documented. For example, a routine that leaves the control in incremental mode (G91) can cause a serious collision if the calling program assumes absolute mode (G90). Robust routines either restore the original state or explicitly establish all required modes. Subprograms are especially useful for: - repeated drilling or tapping patterns;
- standard roughing and finishing sequences;
- tool-change and probing routines;
- pallet or fixture positions;
- machine-specific handling operations;
- standardized inspection procedures.
A subprogram is primarily a structural reuse mechanism. Parametric programming extends reuse by allowing the same routine to operate on different dimensions or feature counts. 2. Variables and Macro ExpressionsMacro programming treats a CNC program as a small computer program. Variables store values that can be read, calculated, tested, and changed during execution. Common Fanuc-style variable groups include: | Variable range | Typical purpose |
|---|
#1–#33 | Local variables, often used as subprogram arguments | #100–#199 | Common variables, retained for a period defined by the control | #500–#999 | Persistent common variables on many controls | #3000 | Programmable alarm on many controls | #4001 and related | Modal-state system information on some controls | #5001 and related | Machine or work-position information on some controls |
These ranges are not universal. Some controls use different assignments, and options may be required. A variable assignment commonly uses the form: #100 = 25.0
#101 = #100 + 5.0
#102 = [#100 * COS[30.0]] The square brackets group expressions. The controller evaluates arithmetic according to its macro rules. Typical functions include SIN, COS, TAN, SQRT, ABS, FIX, FUP, and ROUND; however, function names and angle conventions must be verified. On many industrial controls, trigonometric functions use degrees rather than radians. Variable classificationLocal variables are appropriate for temporary values within a routine. Common variables are useful for communication between programs, such as setup data or measured offsets. Persistent variables can store production counts, calibration values, or retained parameters, but they require strict access control because an unintended overwrite may affect future jobs. System variables provide information about the machine or control state. Reading a system variable is controller-dependent and should never be assumed from a different control model without verification. Macro argumentsMany controls allow arguments to be passed to a subprogram. A call might conceptually look like: G65 P9000 A50.0 B30.0 C4.0 D12.0 The called macro maps addresses to local variables according to the controller’s argument-assignment table. For example, the macro may interpret A as length, B as width, C as feature count, and D as diameter. Because mappings differ between controls, the macro should include a comment describing its interface. 3. Arithmetic, Logic, Branching and LoopsParametric programs require more than motion commands. They need decision-making and repetition. Conditional branchingA conditional statement tests a logical condition and transfers execution when the condition is true: IF [#100 LE 0] THEN #3000 = 1 (INVALID DEPTH)
IF [#101 EQ 0] GOTO 900 Common relational operators include EQ (equal), NE (not equal), GT (greater than), GE (greater than or equal), LT (less than), and LE (less than or equal). Controller syntax differs; some controls require a particular format for THEN or permit only a GOTO form. LoopingA counter-controlled loop can generate a row of holes: #100 = 0 (INDEX)
#101 = 5 (NUMBER OF HOLES)
#102 = 20.0 (START X)
#103 = 15.0 (PITCH)
N10 IF [#100 GE #101] GOTO 20
#104 = [#102 + #100 * #103]
G00 X#104 Y30.0
G81 Z-10.0 R2.0 F100.
#100 = #100 + 1
GOTO 10
N20 G80 The loop terminates when the index reaches the requested count. A safe loop must initialize its counter, change it on every pass, and have a reachable termination condition. Failure in any of these areas can produce an infinite loop. Numerical example: hole locationsSuppose five holes begin at x0 = 20 mm and have a pitch of p = 15 mm. The position of hole i is: xi = x0 + i p, i = 0, 1, …, n − 1 where n is the number of holes. For n = 5, the positions are 20, 35, 50, 65, and 80 mm. The final position can also be checked using: xlast = x0 + (n − 1)p The units are millimetres provided that x0 and p are in millimetres. This relationship applies to a linear, equally spaced pattern; it does not apply to irregular coordinates. 4. Parametric Programming for Families of PartsA parametric program separates invariant process logic from variable geometry. The invariant logic may include tool selection, approach, cutting conditions, and retract strategy. The variable data may include length, width, depth, spacing, hole count, or tool allowance. For example, a rectangular pocket routine can use parameters for length L, width W, depth d, and step-over s. If the cutter is moved in rectangular passes, the number of passes across the width can be estimated as: N = ⌈W / s⌉ where ⌈ ⌉ means round upward to the next integer. This is a planning relationship, not a complete toolpath equation: the actual path must account for cutter radius, boundary allowance, entry method, and whether the final pass is reduced to avoid overcutting. A simplified parameter-validation block might be: IF [#101 LE 0] THEN #3000 = 1 (LENGTH MUST BE POSITIVE)
IF [#102 LE 0] THEN #3000 = 2 (WIDTH MUST BE POSITIVE)
IF [#103 GE 0] THEN #3000 = 3 (DEPTH MUST BE NEGATIVE)
IF [#104 LE 0] THEN #3000 = 4 (PITCH MUST BE POSITIVE) The alarm number and message format are controller-specific. Validation should occur before spindle motion or cutting begins. Coordinate calculationsFor a rectangular array with origin (x0,y0), column pitch px, row pitch py, column index j, and row index k, the coordinates are: xj,k = x0 + j px yj,k = y0 + k py with j = 0,…,c−1 and k = 0,…,r−1. A nested-loop implementation must reset the column index for each new row. The total feature count is N = rc, assuming every row and column position is populated. 5. Coordinate Rotation, Scaling and TranslationCoordinate transformation permits one programmed feature to be reused at different orientations or sizes. RotationFor a point (x,y) rotated counterclockwise through angle θ about the origin, the transformed coordinates are: x' = x cos θ − y sin θ y' = x sin θ + y cos θ The equations assume a right-handed Cartesian coordinate system and a positive counterclockwise angle. CNC controls commonly implement this function with a coordinate-rotation command such as G68, cancelled by G69. The exact syntax, rotation center, active plane, and interaction with work offsets differ by control. For rotation about a point (xc,yc), translate the point to the rotation center, rotate it, and translate it back: x' = xc + (x − xc)cos θ − (y − yc)sin θ y' = yc + (x − xc)sin θ + (y − yc)cos θ ScalingUniform scaling about the origin uses scale factor s: x' = sx, y' = sy A scale factor greater than one enlarges the programmed geometry; a factor between zero and one reduces it. Scaling also affects arc radii and may interact with cutter compensation, tool offsets, and canned cycles. Nonuniform scaling, if supported, can distort circles into ellipses and should not be used casually in machining. Scaling is most useful when the geometry is dimensionally similar and cutting conditions remain appropriate. It is unsafe to assume that feed, speed, tool engagement, and tolerance automatically scale with geometry. Transformation sequenceTransformations are order-dependent. Translating then rotating generally produces a different result from rotating then translating. A production program should define the transformation center and order explicitly, cancel transformations at the end, and prove the result in graphics simulation or a controlled dry run. 6. Custom Cycles and Reusable MacrosA custom cycle is a user-defined routine that performs a recurring machining or inspection operation. Standard canned cycles are limited to functions provided by the control; custom cycles can include calculations, branching, probing, and acceptance criteria. A robust custom cycle typically follows this sequence: - Receive and document arguments.
- Establish or verify units, plane, compensation, and safe mode.
- Validate dimensions and limits.
- Move to a safe approach point.
- Perform the operation.
- Inspect or calculate the result if required.
- Retract safely.
- Return a status or raise an alarm.
Example: bolt-circle calculationFor n equally spaced holes on a circle of radius R centered at (xc,yc), with starting angle θ0, the hole angle is: θi = θ0 + i(360°/n), i = 0,1,…,n−1 The coordinates are: xi = xc + R cos θi yi = yc + R sin θi The formula assumes a planar circular pattern, equal angular spacing, and degrees when the controller’s trigonometric functions use degrees. For example, with R = 40 mm, n = 4, center at (0,0), and starting angle 0°, the positions are (40,0), (0,40), (−40,0), and (0,−40) mm. A macro can calculate these locations and call a drilling operation at each point. The programmer must verify whether the control permits variable expressions directly in axis words and whether the macro call preserves the desired canned-cycle state. 7. Probing, Inspection and Error CheckingMacro programming is valuable for in-process measurement. A probing routine may: - locate an edge or bore;
- measure workpiece position;
- compare a measured dimension with nominal value;
- update a work offset within a controlled limit;
- stop production when a measurement is out of tolerance.
Let the nominal dimension be dn, the measured dimension be dm, and the permitted bilateral tolerance be ±T. Acceptance requires: |dm − dn| ≤ T For example, if the nominal bore is 20.000 mm, the measured bore is 20.012 mm, and the tolerance is ±0.020 mm, then the deviation is 0.012 mm and the feature passes. If the measured bore is 20.025 mm, the deviation is 0.025 mm and the feature fails. Measurement routines require calibrated probes, stable thermal conditions, correct stylus qualification, and a known relationship between probe readings and machine coordinates. A probing macro should not automatically alter offsets unless the adjustment range, direction, and authorization are clearly defined. A faulty probe, broken stylus, incorrect work offset, or chip on the surface can create a false measurement. A practical governance pattern is to separate: - measurement;
- decision;
- offset correction;
- operator notification.
This separation makes the routine easier to validate and prevents an unexpected measurement from causing an uncontrolled correction. 8. Worked Application: Parametric Drilling of a Product FamilyBackgroundThis illustrative case concerns three aluminum mounting plates. Each plate has a rectangular array of holes, but the number of rows and columns varies. The same drill and machining process are used for all plates. ProblemWriting a separate program for every plate would duplicate the drilling logic. The production team wants one macro that accepts plate origin, row count, column count, and pitches while preventing invalid input. AnalysisThe hole coordinates are: xj = x0 + jpx yk = y0 + kpy The macro must reject zero or negative counts and pitches. It must also ensure that the maximum coordinate remains within the fixture boundary. If the available usable length is Xmax and width is Ymax, the final-hole checks are: x0 + (c − 1)px ≤ Xmax y0 + (r − 1)py ≤ Ymax These checks assume the origin and pitches are expressed in the same work-coordinate system and that the boundary is measured from the same datum. ApproachA controller-specific implementation could use local variables for arguments and nested loops: (ILLUSTRATIVE SYNTAX—VERIFY CONTROL MANUAL)
O9100 (RECTANGULAR HOLE ARRAY)
( A=X0, B=Y0, C=ROWS, D=COLUMNS )
( E=XPITCH, F=YPITCH )
IF [#3 LT 1] THEN #3000 = 10 (INVALID ROW COUNT)
IF [#7 LT 1] THEN #3000 = 11 (INVALID COLUMN COUNT)
IF [#8 LE 0] THEN #3000 = 12 (INVALID X PITCH)
IF [#9 LE 0] THEN #3000 = 13 (INVALID Y PITCH)
#20 = 0 (ROW INDEX)
N100 IF [#20 GE #3] GOTO 190
#21 = 0 (COLUMN INDEX)
N110 IF [#21 GE #7] GOTO 180
#22 = [#1 + #21 * #8]
#23 = [#2 + #20 * #9]
G00 X#22 Y#23
G81 Z-8.0 R2.0 F100.
#21 = #21 + 1
GOTO 110
N180 G80
#20 = #20 + 1
GOTO 100
N190 M99 The variable numbers shown are illustrative because argument mappings differ by controller. The drilling depth, retract plane, and feed must be selected from the tool, material, and process plan rather than copied blindly. OutcomeFor a three-row, four-column array, the macro executes 12 drilling positions. Changing the row count, column count, or pitches changes the feature pattern without rewriting the motion logic. The same routine can be validated once and reused, provided the input range remains within its design limits. Learning pointsThe principal benefit is controlled reuse, not merely fewer lines of code. The macro expresses design intent, supports product variation, and centralizes error checking. Its principal risk is that a defect in the shared routine affects every part, so simulation, revision control, and documented approval are essential. 9. Verification, Safety and Professional PracticeMacro programs require more verification than ordinary linear programs because the final toolpath may not be visible directly in the source code. Important practices include: - use meaningful comments and a written argument list;
- initialize every variable used by the routine;
- validate counts, signs, limits, and units;
- avoid unexplained persistent variables;
- cancel rotation, scaling, cutter compensation, and canned cycles;
- use single-block and graphics simulation before cutting;
- dry-run above the workpiece with reduced rapid and feed rates;
- verify fixture, tool, work offset, and probe assumptions;
- protect production macros from unauthorized editing;
- maintain revision identifiers and change records.
A macro should fail safely. An invalid parameter should cause a controlled alarm before cutting, not produce a plausible but incorrect toolpath. Alarm messages should identify the failed condition clearly. Limitations and controller dependenceThere is no single universal macro language. Differences occur in: - variable ranges;
- argument-to-variable mapping;
- expression syntax;
- trigonometric units;
- macro call commands;
- alarm behavior;
- system-variable addresses;
- nesting depth and loop support;
- interaction with offsets and modal states.
Postprocessors and simulation systems may not reproduce every controller behavior. Consequently, software verification is necessary but not sufficient. Final validation must occur on the target control using a safe, authorized procedure. Contemporary developmentsModern CNC environments increasingly combine macro logic with probing systems, tool-life management, machine monitoring, digital twins, and production databases. These technologies can improve adaptive control and traceability, but connectivity also introduces cybersecurity and governance concerns. Programs should use authenticated files, controlled permissions, backups, and documented approval workflows. Artificial intelligence may assist in code generation or anomaly detection, but generated code must be reviewed by a competent CNC programmer; responsibility for machine safety cannot be delegated to an automated system. Chapter SummarySubprograms provide reusable blocks of CNC instructions, while parametric macros add variables, arithmetic, logic, and iteration. Local, common, persistent, and system variables serve different purposes and must be handled according to the target controller’s documentation. Loops generate repeated features; conditional statements validate inputs and support error handling. Coordinate rotation, scaling, and translation allow one geometry to be reused at different orientations or sizes, but transformations are order-dependent and controller-specific. Custom cycles can combine machining, probing, measurement, and decision-making. Effective macro programming depends on clear interfaces, unit consistency, safe modal control, parameter validation, simulation, and disciplined revision management. Key TermsSubprogram: A separately stored CNC routine called by a main program. Macro: A CNC program containing variables, expressions, logic, or reusable calculations. Local variable: A temporary variable generally associated with a macro execution. Common variable: A variable used to share values between routines. Persistent variable: A retained variable that survives program completion or power cycles on supported controls. System variable: A controller-provided variable representing machine or control information. Argument: An input value passed to a macro. Branch: A transfer of execution based on a condition. Loop: A repeated sequence controlled by a counter or condition. Parametric programming: Programming in which geometry or process data is represented by variables. Canned cycle: A controller-resident routine for a standard machining operation. Custom cycle: A user-defined routine implementing a repeated machining or inspection process. Coordinate rotation: Transformation of coordinates through an angular displacement. Scaling: Multiplication of programmed coordinates by a scale factor. Translation: Shifting coordinates by a specified distance. Probe: A sensing device used to locate or measure a workpiece or tool. Modal state: A control condition that remains active until changed or cancelled. Work offset: A coordinate-system shift relating program coordinates to machine coordinates. Dry run: A controlled verification in which machining is simulated or performed away from the workpiece. Macro alarm: A programmed stop indicating an invalid condition or process failure. Review QuestionsShort Answer Questions- What is the difference between a subprogram and a parametric macro?
- Why must a loop counter be initialized and changed on every iteration?
- What is the purpose of validating macro inputs before tool motion?
- State the coordinate equations for rotating a point about the origin.
- Why must coordinate transformations be cancelled or explicitly managed?
Long Answer Questions- Explain how local, common, persistent, and system variables differ, and give an appropriate CNC application for each.
- Describe the design of a robust custom drilling cycle, from argument reception through safe return.
- Explain the advantages and risks of using parametric programming for a family of parts.
- Discuss the effect of controller dependence on macro portability and verification.
- Explain how probing macros can support closed-loop inspection while avoiding uncontrolled offset changes.
Analytical / Application Questions- Design the logic for a macro that drills a rectangular array while checking counts, pitches, and fixture limits before cutting.
- A four-hole pattern is programmed at radius 30 mm and rotated by 45°. Calculate the coordinates of the holes when the center is at (100, 50) mm, and explain how the pattern could be implemented with a coordinate-rotation command.
- Critically evaluate whether a probing macro should automatically update a work offset when a measured error exceeds the nominal tolerance but remains within a predetermined correction limit.
Multiple Choice Questions with AnswersQuestion 1Which command commonly returns control from a subprogram to the calling program? A. M03 B. M30 C. M99 D. G80 Correct Answer: C. M99 Question 2For five equally spaced points starting at x = 20 mm with a 15 mm pitch, what is the final x-coordinate? A. 65 mm B. 80 mm C. 95 mm D. 100 mm Correct Answer: B. 80 mm Question 3Which condition is essential for a safe counter-controlled loop? A. The counter must remain constant B. The termination condition must be unreachable C. The counter must be initialized and updated D. The loop must use incremental mode Correct Answer: C. The counter must be initialized and updated Question 4For a bolt circle, what determines the angular separation between adjacent holes? A. 360° multiplied by the radius B. 360° divided by the number of holes C. The hole diameter divided by the radius D. The feed rate divided by the spindle speed Correct Answer: B. 360° divided by the number of holes Question 5A measured dimension is 20.012 mm, nominal is 20.000 mm, and tolerance is ±0.020 mm. What is the result? A. Pass, because deviation is 0.012 mm B. Fail, because deviation is 0.012 mm C. Pass, because deviation is 0.032 mm D. Fail, because deviation is 0.020 mm Correct Answer: A. Pass, because deviation is 0.012 mm Question 6What is the principal purpose of a macro argument? A. To pass input data to a reusable routine B. To cancel spindle rotation C. To define the machine serial number D. To replace the work offset permanently Correct Answer: A. To pass input data to a reusable routine Question 7When a point is rotated counterclockwise about the origin, which equation gives the new x-coordinate? A. x' = x cos θ − y sin θ B. x' = x sin θ + y cos θ C. x' = x + y + θ D. x' = x cos θ + y sin θ Correct Answer: A. x' = x cos θ − y sin θ Question 8Why is a controller manual necessary when transferring a macro to another machine? A. All CNC controls use identical variable ranges B. Macro syntax and system-variable assignments vary C. Tool materials change automatically D. Workpiece tolerances are removed by the control Correct Answer: B. Macro syntax and system-variable assignments vary Question 9Which practice best supports safe custom-cycle design? A. Allowing invalid dimensions to proceed to cutting B. Leaving modal states undocumented C. Validating inputs before machining motion D. Using persistent variables without comments Correct Answer: C. Validating inputs before machining motion Question 10What is the main benefit of using a parametric program for a family of similar parts? A. It eliminates the need for simulation B. It allows controlled variation through input parameters C. It guarantees identical cutting forces for all sizes D. It makes controller differences irrelevant Correct Answer: B. It allows controlled variation through input parameters
|