CNC Part ProgrammingIntroduction and ContextComputer numerical control (CNC) part programming is the process of translating a component drawing, manufacturing plan, and tooling requirements into a sequence of machine instructions. These instructions define tool motion, spindle operation, feed rate, coolant, work offsets, and machining cycles. A correct program must produce the intended geometry safely, efficiently, and repeatably. CNC programming is not merely code entry. It is an engineering activity involving coordinate-system selection, geometric interpretation, process planning, cutter and tool compensation, collision avoidance, dimensional verification, and communication with the machine control. Although modern computer-aided manufacturing (CAM) systems generate much CNC code, manual programming remains essential for simple parts, program editing, troubleshooting, process understanding, and verification. This chapter uses common ISO-style conventions. Exact code meanings, syntax, decimal rules, compensation behavior, and canned-cycle formats vary among controllers; therefore, the machine-tool manual always has precedence. Learning ObjectivesAfter studying this chapter, a learner should be able to: - Explain the structure and modal behavior of CNC words, blocks, addresses, G-codes, and M-codes.
- Establish machine, work, and tool coordinate systems using appropriate offsets.
- Create and verify linear and circular interpolation programs.
- Apply cutter compensation, tool nose compensation, canned cycles, and subprograms.
- Distinguish milling and turning programming conventions.
- Check a program for geometry, technology, safety, and controller compatibility.
- Estimate machining time and select suitable feed and speed values.
1. Structure of a CNC ProgramA CNC program consists of blocks. A block normally represents one line of instruction and may contain sequence numbers, preparatory functions, coordinates, feed, speed, tool information, and miscellaneous functions. A typical milling block is: N120 G01 X50.0 Y20.0 F180
Here, N120 is the sequence number, G01 commands linear interpolation, X50.0 Y20.0 specify the programmed endpoint, and F180 specifies feed rate. The interpretation of feed units depends on the control mode, such as millimetres per minute or millimetres per revolution. A CNC word consists of an address letter followed by a numerical value. Common addresses are: | Address | Typical meaning |
|---|
| N | Sequence or block number | | G | Preparatory function or motion mode | | X, Y, Z | Linear-axis coordinates | | A, B, C | Rotary-axis coordinates | | I, J, K | Arc-centre offsets in X, Y, Z directions | | R | Arc radius or canned-cycle retract/increment value | | F | Feed rate | | S | Spindle speed | | T | Tool selection | | H | Tool-length-offset register | | D | Cutter-radius-offset register | | M | Miscellaneous machine function | | P, L | Parameter, dwell, repeat, or subprogram data, depending on control |
A block may contain multiple words, but incompatible commands should not be placed together. Comments are commonly enclosed in parentheses, for example (ROUGH POCKET). Program start and end symbols also vary, but % and M30 are widely used. Modal and Non-modal CommandsA modal command remains active until replaced by another command in the same group or cancelled. For example, after G01, later blocks may continue linear motion without repeating G01. Non-modal commands act only in the block in which they appear. Modal behavior makes programs compact but creates a major verification risk: an omitted command may leave an unintended mode active. Typical modal groups include rapid motion, feed motion, plane selection, absolute/incremental programming, units, coordinate selection, and cutter compensation. Only one code from a modal group should be active at a time. 2. Coordinate Systems and OffsetsMachine CoordinatesMachine coordinates are established by the machine builder and referenced to a machine home or reference position. They are used for machine travel limits, homing, and safe tool changes. The programmer generally should not assume that the machine zero is at the workpiece. Work CoordinatesA work coordinate system defines the programming origin on the part or fixture. Common systems include G54 through G59, although the available range depends on the controller. A work offset stores the relationship between the programmed origin and the machine coordinate system. For a milling job, the origin may be placed at the upper-left corner of the stock, at the centre of a hole pattern, or at the top face of the workpiece. The choice should simplify dimensions, reduce calculation, and support inspection. G90 selects absolute programming: coordinates are measured from the active work origin. G91 selects incremental programming: each coordinate is measured from the current tool position. Absolute programming is usually easier to audit for prismatic geometry; incremental programming can be useful for repeated patterns and local movements.
Tool OffsetsTool offsets compensate for physical tool differences: - Tool length offset, commonly called with
G43 H..., adjusts the programmed Z position for tool length. - Cutter-radius offset, commonly called with
G41 D... or G42 D..., shifts a milling path by the tool radius or a stored wear value. - Turning tool geometry and wear offsets compensate for insert position, tool nose radius, and dimensional wear.
Offsets should be measured using a controlled procedure and documented. A program must not rely on an unverified offset register. Planes and UnitsFor milling, G17 selects the XY plane, G18 the XZ plane, and G19 the YZ plane. Plane selection controls the interpretation of circular interpolation and arc-centre addresses. G20 and G21 commonly select inch and millimetre units. Units should be specified near the beginning of every program rather than inherited from a previous program. A safe initialization line might be: G21 G17 G90 G40 G49 G80
This example selects millimetres, the XY plane, absolute programming, cancels cutter and tool-length compensation, and cancels a canned cycle. The exact safe-start line is controller-specific. 3. G-Codes and M-CodesG-codes control geometry, motion, coordinate modes, and machining cycles. M-codes control machine functions such as spindle rotation, coolant, program stop, and program end. | Function | Common code | Purpose |
|---|
| Rapid positioning | G00 | Move at rapid rate; not for cutting | | Linear interpolation | G01 | Feed along a straight line | | Clockwise arc | G02 | Circular interpolation | | Counterclockwise arc | G03 | Circular interpolation | | Absolute mode | G90 | Coordinates from work origin | | Incremental mode | G91 | Coordinates from current position | | Plane selection | G17/G18/G19 | XY/XZ/YZ arc plane | | Cutter compensation | G40/G41/G42 | Cancel/left/right compensation | | Canned-cycle cancel | G80 | Cancel drilling or other cycle | | Work offset | G54–G59 | Select work coordinate system | | Spindle clockwise | M03 | Start spindle clockwise | | Spindle counterclockwise | M04 | Start spindle counterclockwise | | Spindle stop | M05 | Stop spindle | | Coolant on/off | M08/M09 | Control coolant | | Optional stop | M01 | Stop if optional-stop switch is enabled | | Program end and rewind | M30 | End and reset program |
Codes shown are common, not universal. For example, high-speed machining, probing, rigid tapping, and pallet functions often use manufacturer-specific codes. 4. Linear and Circular InterpolationRapid and Feed MotionG00 positions the tool rapidly. The path may not be a straight line and must therefore be used only where the tool is clear of the workpiece and fixtures. G01 moves at the programmed feed rate along a straight line.
Example: G00 X10.0 Y10.0
G01 Z-2.0 F80
G01 X60.0 F180
The first move positions in the XY plane, the second feeds into the material, and the third cuts to X = 60 mm. Circular InterpolationCircular interpolation requires a plane, direction, endpoint, and either centre definition or radius. In the XY plane, I and J normally specify the signed centre offset from the arc start point in X and Y. G02 is clockwise and G03 counterclockwise when viewed from the positive normal direction of the selected plane. For a circle with centre C(xc,yc) and radius r, a point P(x,y) satisfies: (x − xc)2 + (y − yc)2 = r2 The equation applies to an ideal planar circle and uses consistent linear units. It is useful for checking that the programmed start and end points lie on the intended arc. With centre-offset programming, if the arc starts at Ps(xs,ys), then: I = xc − xs, J = yc − ys For example, in G17, G03 X40 Y20 I0 J10, the arc begins at the current point, ends at (40, 20), and has its centre 0 mm in X and 10 mm in Y from the start. The control determines the radius from these data. The start and end radii must agree within the controller’s tolerance. Radius programming with R is convenient for simple arcs but can be ambiguous for arcs greater than 180°. Centre-offset programming is generally more explicit and is preferred for verification. Feed and Speed RelationshipsFor milling, cutting speed is related to spindle speed by: Vc = (π D n) ÷ 1000 where Vc is cutting speed in m/min, D is cutter diameter in mm, and n is spindle speed in rev/min. Therefore: n = (1000 Vc) ÷ (π D) This relationship assumes a circular cutter and uses the cutter circumference at the selected diameter. For a 10 mm cutter at 100 m/min: n = (1000 × 100) ÷ (π × 10) ≈ 3183 rev/min. If the tool has four teeth and the chip load is 0.05 mm/tooth, feed rate is: F = fz z n where F is feed in mm/min, fz is feed per tooth in mm/tooth, and z is the number of teeth. Thus, F = 0.05 × 4 × 3183 ≈ 637 mm/min. The calculated value must be limited by machine capability, tool manufacturer recommendations, rigidity, and the actual engagement condition. For turning, surface speed and spindle speed are similarly related, with D representing the current work diameter. Constant surface-speed control, often G96, changes spindle speed as diameter changes; a maximum spindle-speed limit is essential. 5. Cutter CompensationWithout cutter compensation, the programmed path usually represents the tool centreline. To machine a contour at its specified dimensions, the centreline must be offset from the contour by the cutter radius. Cutter compensation allows the programmer to describe the part contour while the control calculates the tool-centre path. G41: cutter compensation left of the programmed direction.G42: cutter compensation right of the programmed direction.G40: cancel compensation.
“Left” and “right” are determined while looking in the direction of tool travel, not by a fixed machine-axis direction. A lead-in move is required so that the control can establish the offset before contacting the contour. A lead-out move should be used before cancellation. Typical sequence: G00 X-5 Y10
G01 G41 D01 X0 Y10 F200
G01 X60 Y10
G01 X60 Y40
G01 X0 Y40
G01 X0 Y10
G01 G40 X-5 Y10
The D register must contain the correct radius or wear value. Compensation can fail if the lead-in is too short, the selected radius is larger than the lead-in geometry, the contour contains an impossible corner, or compensation is cancelled while the tool is still engaged. Turning controls commonly use tool nose-radius compensation, often G41/G42, together with a tool orientation or imaginary tool-nose-number parameter. The correct setting depends on approach direction, insert orientation, and control convention. 6. Canned CyclesCanned cycles compress common repeated operations into a standard command. A drilling cycle may specify the hole location, depth, retract plane, feed, and optional dwell. Common milling cycles include: G81: simple drilling.G82: drilling with dwell at depth.G83: peck drilling for deep holes.G84: tapping, often requiring rigid-tapping support.G80: cancel the active cycle.
A representative drilling sequence is: G90 G99 G81 X20 Y20 Z-15 R2 F120
X60 Y20
X60 Y50
X20 Y50
G80
Here, Z-15 is the final depth, R2 is the retract or clearance plane, and G99 commonly returns to the initial plane rather than the program’s initial point. The exact return behavior varies. The cycle remains active for subsequent XY positions; forgetting G80 can cause an unintended hole at a later XY move. For a peck cycle, parameters such as peck depth and retract amount must be specified according to the controller. Deep-hole drilling requires attention to chip evacuation, coolant delivery, tool rigidity, and the possibility that the programmed peck is excessive for the material. 7. Subprograms and RepetitionSubprograms reduce repetition and improve maintainability. A main program calls a subprogram, which contains a reusable sequence. Common conventions use M98 to call a subprogram and M99 to return, but syntax differs among controls. Illustrative structure: Main program: M98 P1000 L4
M30
Subprogram O1000: O1000
G01 X20 F200
G01 Y20
M99
The meaning of P, L, and whether local coordinate shifts are available must be verified. Subprograms are valuable for bolt-hole patterns, repeated slots, identical features, and modular production programs. They introduce risks when a coordinate shift, modal condition, or return level is not clearly controlled. A subprogram should establish or document the modes it requires and should return the tool to a predictable position. 8. Milling and Turning ConventionsMillingMilling programs usually use X and Y for planar motion and Z for tool-axis motion. Positive Z commonly moves away from the workpiece, but machine conventions must be checked. Tool length is typically measured along the spindle axis. Work origins may be placed on the top surface or at the bottom of the stock. A milling safety sequence generally includes tool selection, spindle start, coolant, tool-length compensation, a clearance move, approach, cutting motion, retract, and compensation cancellation. The programmer must account for workholding, tool diameter, axial and radial depth of cut, and chip evacuation. TurningOn a conventional CNC lathe, Z is parallel to the spindle axis and X is radial. Many controls program X in diameter values, although some use radius values. This distinction is critical. If a diameter-programming lathe moves from X50 to X40, the finished diameter changes by 10 mm, whereas a radius-programming control interprets the values differently. Turning commonly uses: G00 for rapid positioning.G01 for straight turning or facing.G02/G03 for tapers and radii.G96 for constant surface speed.G97 for fixed spindle speed.G50 or a controller-specific function for maximum spindle speed.G71 roughing and G70 finishing cycles on many controls.G76 threading cycle on many controls.
A turning program must specify whether the tool approaches from the front or rear, how the insert orientation is represented, and how tool nose radius compensation is applied. Threading requires correct pitch, minor diameter, tool geometry, synchronization, and spindle-speed control. 9. Program VerificationVerification should occur at several levels: - Syntax verification: Check valid addresses, code groups, decimal formats, program numbers, and controller-specific syntax.
- Modal verification: Identify active units, plane, coordinate mode, compensation, feed mode, spindle mode, and canned cycle.
- Geometric verification: Confirm endpoints, radii, depths, slopes, intersections, and stock allowance.
- Technological verification: Check speed, feed, tool selection, depth of cut, coolant, chip control, and tool capacity.
- Machine verification: Check travel limits, work offset, tool length, fixture clearance, spindle direction, and machine-specific behavior.
- Simulation and prove-out: Use backplotting, solid simulation, dry run, single-block execution, reduced rapid override, and controlled first-piece inspection.
A simulation is not a substitute for engineering judgment. It may use incorrect tool dimensions, omit the actual fixture, or fail to model controller-specific behavior. The first physical run should use a verified setup, a qualified operator, and conservative overrides. 10. Worked Example: Milling a Rectangular ProfileConsider a 60 mm × 40 mm rectangular profile programmed from the lower-left corner, with the work origin at the profile’s lower-left top surface. A 10 mm end mill is used, and the cutter path is compensated with G41 D01. The tool approaches from X = −8 mm, Y = 5 mm and cuts the contour at Z = −2 mm. An illustrative program is: `% O0401 (RECTANGULAR PROFILE) G21 G17 G90 G40 G49 G80 G54 T01 M06 S3180 M03 G00 G43 H01 Z50.0 M08 G00 X-8.0 Y5.0 G01 Z-2.0 F80 G01 G41 D01 X0.0 Y5.0 F180 G01 X60.0 Y5.0 G01 X60.0 Y40.0 G01 X0.0 Y40.0 G01 X0.0 Y5.0 G01 G40 X-8.0 Y5.0 G00 Z50.0 M09 M05 M30 %` The example is illustrative, not universally executable. The programmer must confirm that the lead-in establishes compensation correctly, that D01 contains the intended radius or wear value, and that the contour path produces the required finished dimensions. If the programmed contour is the part boundary, the control offsets the tool centreline so that the tool edge follows the boundary. The approach and retract are deliberately outside the work profile. The nominal spindle speed follows from the earlier relationship. For a 10 mm cutter and a cutting speed of 100 m/min, the calculated speed is approximately 3183 rev/min; 3180 rev/min is a practical rounded value if permitted by the tooling and machine. 11. Illustrative Case: First-Article Verification of a Flanged ComponentBackground. A small machine shop must produce an aluminium flange containing an outside profile, four bolt holes, and a central bore. The production drawing uses dimensions from the centre of the flange, while the existing fixture is referenced from its corner. Problem. An initial manually written program produced correct hole spacing but shifted the entire pattern by 0.5 mm. The error arose because the programmer mixed a corner-based work offset with centre-based drawing coordinates. Analysis. The engineer selected a new G54 origin at the flange centre and recorded the fixture-to-part relationship in the setup sheet. A second offset was reserved for inspection or an alternate fixture. The hole pattern was programmed in absolute coordinates, while a subprogram was used for the repeated drilling cycle. The tool list specified drill diameter, gauge length, and offset registers. Approach and solution. Before cutting, the program was checked using a backplot and a coordinate table. The four hole centres were verified against the drawing, and the drilling cycle was cancelled explicitly with G80. The work offset was probed, the actual fixture was included in simulation, and the first run used single block and reduced rapid override. Hole locations were measured with a coordinate measuring machine. Outcome. The first article met the positional tolerance after correcting the work offset. The final production program included a setup comment identifying the origin, a tool-offset table, a safe-start block, explicit compensation cancellation, and a revision record. Learning points. Coordinate-origin decisions are part of process planning, not clerical details. A correct path in the wrong work coordinate system still produces a defective part. Verification must therefore connect the drawing, setup, offsets, program, simulation, and inspection plan. 12. Limitations, Safety, and Professional PracticeCNC code is safety-critical manufacturing information. A typographical error can cause tool breakage, workpiece ejection, machine damage, or injury. Programs should be controlled through revision management, approval, backups, and documented setup instructions. Operators must be trained to use emergency stops, door interlocks, offsets, overrides, and safe restart procedures. Common programming errors include: - incorrect unit selection;
- wrong work offset or tool offset;
- failure to cancel a canned cycle or compensation mode;
- confusing absolute and incremental coordinates;
- incorrect arc direction or plane;
- unsafe rapid motion;
- spindle rotation in the wrong direction;
- inadequate lead-in or lead-out;
- assuming diameter programming on a radius-programming lathe;
- using a feed or speed outside tool and machine limits.
Digital manufacturing also creates governance issues. Postprocessors should be validated rather than assumed correct, programs should be traceable to drawing revisions, and automated or AI-assisted code generation should be treated as a drafting aid requiring human verification. Intellectual property, cybersecurity, and unauthorized program changes must be controlled in networked production environments. 13. Contemporary DevelopmentsCurrent CNC practice increasingly combines CAM simulation, digital twins, probing, adaptive control, tool-condition monitoring, and data collection. In-process probing can update work offsets and detect stock or fixture variation. Digital twins can model machine kinematics and collision risks more realistically than simple two-dimensional backplots. Adaptive control can modify feed according to spindle load, but it does not eliminate the need for sound cutting parameters. Artificial intelligence may assist with feature recognition, parameter recommendation, anomaly detection, and code review. Its output remains dependent on training data, postprocessor quality, machine configuration, and the accuracy of the engineering specification. Accountability for the released program remains with qualified personnel. Best-Practice ChecklistBefore releasing a CNC program, verify that: - units, plane, coordinate mode, and work offset are explicit;
- all tools and offsets are measured and identified;
- spindle speed, feed, coolant, and tool direction are appropriate;
- rapid moves are clear of the workpiece and fixture;
- arc endpoints and centres are geometrically consistent;
- compensation has adequate lead-in and lead-out;
- canned cycles are cancelled when no longer required;
- turning diameter/radius conventions are confirmed;
- subprogram calls, repeats, and returns are correct;
- simulation includes actual stock, tools, and fixtures;
- the program has passed a documented prove-out and inspection plan.
Chapter SummaryCNC part programming converts engineering geometry and process requirements into controlled machine motion. Reliable programming depends on understanding blocks, modal codes, coordinate systems, work offsets, tool offsets, interpolation, compensation, canned cycles, and subprograms. Milling commonly uses X–Y–Z coordinates and cutter-radius compensation, whereas turning uses X and Z, often with diameter programming and tool-nose compensation. Feed and speed calculations must be dimensionally consistent and constrained by tooling and machine capability. Verification must address syntax, modal state, geometry, technology, machine limits, simulation, and first-article inspection. Safe professional practice requires explicit modes, controlled offsets, documented revisions, conservative prove-out, and human responsibility even when CAM or AI tools are used. Key TermsCNC program: A coded sequence controlling a numerical-control machine. Block: One line or instruction unit in a CNC program. Word: An address letter and associated numerical value. Modal code: A code that remains active until replaced or cancelled. G-code: A preparatory command controlling motion or machining mode. M-code: A miscellaneous command controlling machine functions. Machine coordinate system: The coordinate system established by the machine builder. Work coordinate system: A programmable coordinate system located on the workpiece or fixture. Work offset: The stored transformation between work and machine coordinates. Tool-length offset: Compensation for the measured length of a cutting tool. Cutter compensation: Control adjustment for cutter radius relative to a programmed contour. Tool nose compensation: Turning compensation for insert nose radius and orientation. Interpolation: Controlled movement between programmed points. Canned cycle: A predefined cycle for repeated operations such as drilling. Subprogram: A reusable program segment called by a main program. Absolute programming: Coordinate specification from a fixed programmed origin. Incremental programming: Coordinate specification from the current tool position. Backplot: A graphical representation of programmed tool motion. Postprocessor: Software that converts CAM data into controller-specific code. Prove-out: Controlled verification of a program on the actual machine. Review QuestionsShort Answer Questions- What is the difference between a modal and a non-modal CNC command?
- Why is a work offset required in CNC programming?
- What information is normally supplied by I and J in XY-plane circular interpolation?
- What is the purpose of
G80? - Distinguish tool-length compensation from cutter-radius compensation.
Long Answer Questions- Explain the complete structure of a CNC program and discuss the function of common address letters.
- Describe how a milling contour is programmed using cutter compensation, including lead-in, contour motion, lead-out, and cancellation.
- Compare milling and turning coordinate conventions, including the significance of diameter programming on a lathe.
- Explain the stages of CNC program verification from syntax checking to first-article inspection.
- Discuss the advantages and risks of canned cycles and subprograms in production programming.
Analytical / Application Questions- A 12 mm, four-flute milling cutter is selected for a cutting speed of 90 m/min and chip load of 0.04 mm/tooth. Calculate the spindle speed and feed rate, showing units and appropriate rounding.
- A drilling program produces a hole pattern shifted from the drawing although the programmed spacings are correct. Analyze the likely coordinate-system and work-offset causes and propose a verification procedure.
- Develop a verification plan for a turning program that uses constant surface speed, a roughing cycle, tool-nose compensation, and a threading cycle. Identify at least six specific checks before production release.
Multiple Choice Questions with AnswersQuestion 1Which code commonly selects absolute programming on a CNC machine? A. G90 B. G91 C. G40 D. G80 Correct Answer: A. G90 Question 2In the XY plane, what do I and J normally define for an arc? A. Feed and spindle speed B. Tool length and radius C. Centre offsets in X and Y from the arc start D. Hole depth and retract height Correct Answer: C. Centre offsets in X and Y from the arc start Question 3What is the principal purpose of G41 or G42 in milling? A. To select spindle direction B. To apply cutter-radius compensation C. To cancel a canned cycle D. To select the work offset Correct Answer: B. To apply cutter-radius compensation Question 4What is the main danger of using G00 near a workpiece? A. It forces constant surface speed B. It automatically changes the work offset C. Its path and speed may cause a collision if clearance is inadequate D. It cancels tool-length compensation Correct Answer: C. Its path and speed may cause a collision if clearance is inadequate Question 5Which command commonly cancels an active drilling canned cycle? A. G17 B. G43 C. G80 D. G96 Correct Answer: C. G80 Question 6For a 10 mm cutter at 100 m/min, the ideal spindle speed is approximately: A. 318 rev/min B. 1,000 rev/min C. 3,183 rev/min D. 31,830 rev/min Correct Answer: C. 3,183 rev/min Question 7A four-flute cutter runs at 3,183 rev/min with a chip load of 0.05 mm/tooth. What is the approximate feed rate? A. 159 mm/min B. 637 mm/min C. 3,183 mm/min D. 12,732 mm/min Correct Answer: B. 637 mm/min Question 8What is a major advantage of a subprogram? A. It eliminates the need for work offsets B. It allows repeated geometry to be stored and called efficiently C. It automatically measures every tool D. It prevents all modal errors Correct Answer: B. It allows repeated geometry to be stored and called efficiently Question 9On many CNC lathes, the X-axis is commonly programmed in: A. Angular degrees only B. Diameter values C. Tool-length values D. Feed-per-tooth values Correct Answer: B. Diameter values Question 10Why should a CNC program be simulated and then proved out on the machine? A. Simulation makes drawing dimensions unnecessary B. The machine operator does not need to check offsets C. Both code logic and actual machine/setup conditions must be verified D. It guarantees that every controller interprets codes identically Correct Answer: C. Both code logic and actual machine/setup conditions must be verified
|