Simplified Programming Technology for Macro Programs in CNC Machining - ST
  • À propos
  • Blog
  • Contact

Simplified Programming Technology for Macro Programs in CNC Machining

CNC Macro Programming: How to Simplify Your Code and Stop Writing Repetitive Blocks

There is a moment every CNC programmer hits. You are staring at a part with forty identical holes drilled in a circle, or a contoured surface defined by a mathematical curve, and you realize you are about to write the same G-code block forty times. Or worse — you are about to write a parametric equation by hand in hundreds of lines of linear moves.

That is where macro programming saves you. A macro is not some advanced feature reserved for aerospace shops. It is a way to use variables, loops, and conditional logic inside your CNC program to replace hundreds of lines with a handful. Once you understand the basics, you start seeing patterns everywhere that were begging to be macroed.

This guide shows you how macros actually work on the shop floor, the specific patterns they replace, and the traps that turn a clever macro into a debugging nightmare.


What a Macro Actually Does Inside the Controller

A CNC macro is a block of code stored in the program memory that uses variables instead of fixed numbers. Where a normal program says G01 X50.000 Y25.000 F300, a macro says G01 X#1 Y#2 F#3. The controller substitutes the actual values when it runs.

The real power comes from three features: variables, loops, and math functions. Variables let you change one number and have it update everywhere that number appears. Loops let you repeat a sequence without copying and pasting. Math functions let you calculate positions on the fly using trigonometry, algebra, or any formula you can write.

Most controllers support two macro systems. Fanuc uses custom macro B with G65/G66 calls and system variables. Siemens uses parametric programming with R parameters. Haas has its own macro dialect. The syntax differs, but the logic is identical across all of them. If you learn the concept on one controller, you can translate it to another in an afternoon.


The Patterns That Beg for a Macro

Drilling Holes on a Bolt Circle

This is the classic first macro every programmer writes. You have eight holes on a 100mm bolt circle. Without a macro, you calculate each X and Y position by hand, write eight separate G81 blocks, and hope you did not transpose a digit.

With a macro, you define the bolt circle radius, the starting angle, the number of holes, and the depth. The macro loops through each hole, calculates X and Y using cosine and sine, drills, and moves to the next position. The entire operation fits in fifteen lines instead of eighty.

The math is simple: X = center_X + radius × cos(angle), Y = center_Y + radius × sin(angle). The controller does the trigonometry in real time. You change the radius or the hole count and the whole pattern updates automatically. No re-calculation. No re-typing.

Machining a Radius or Contour Defined by an Equation

Suppose you need to machine a parabolic curve or an elliptical pocket. The shape is defined by an equation, not by a series of line segments. Writing it out as tiny linear moves produces a faceted surface that does not match the CAD model.

A macro steps through the curve in small increments, calculates the X and Y position at each step using the equation, and feeds the tool along the true curve. The result is a smooth surface that matches the drawing within machine tolerance. You control the step size — smaller steps mean smoother surface but longer cycle time. Find the balance that works for your finish requirement.

This same technique applies to tapers, helical ramps, and any geometry that follows a mathematical relationship. Instead of approximating with line segments, you program the actual equation and let the controller compute every point.

Repetitive Pocketing or Slotting Patterns

A part with six identical pockets spaced evenly around a flange is another perfect macro candidate. Define the pocket geometry once. Use a loop to rotate the starting position by 60 degrees for each pocket. The macro cuts the first pocket, rotates the tool position, cuts the second, and so on.

What used to take two hundred lines of code now takes thirty. And when the engineer changes the pocket depth or the number of pockets, you edit one variable instead of hunting through the entire program.


Writing Macros That Do Not Break in Production

Use Local Variables, Not System Variables

Every controller has system variables that are always available — things like current position, spindle speed, feed rate. They are convenient but dangerous in a macro. If your macro reads a system variable and something else in the program changes it mid-execution, your macro produces the wrong result with no warning.

Local variables are isolated to the macro itself. They do not interfere with the rest of the program. Always use local variables for your calculations. Treat system variables as read-only inputs, not as storage.

On Fanuc, local variables are #1 through #33 and #100 through #199. On Siemens, they are R1 through R999. The exact range varies, but the principle is the same — keep your math inside the macro, away from the main program.

Initialize Every Variable Before You Use It

A variable that has never been assigned a value does not equal zero. It equals whatever was left in that memory location from the last program that ran. This is the single most common cause of macro errors that do not show up until the third part.

At the start of every macro, set every variable you plan to use. Zero them out or assign them a known value. This takes two extra lines of code and prevents the kind of random error that makes you suspect the machine is haunted.

Avoid Nested Loops Unless You Have To

A loop inside a loop works fine in theory. In practice, it multiplies the number of iterations and makes debugging painful. If you have a pattern that requires two levels of nesting, break it into two separate macros and call one from the other. It is easier to read, easier to test, and easier to fix when something goes wrong.

Most shop-floor macros use a single loop. If you find yourself nesting three or four deep, you are probably overcomplicating the logic. Step back and see if the pattern can be simplified before you code it.


Parametric Programming vs Custom Macro: Knowing the Difference

Parametric Programming

Parametric programming treats the entire program as a function of variables. You write the program once using parameter names instead of numbers. At runtime, you pass the actual values into the parameters and the controller runs the program with those values substituted everywhere.

This is powerful for families of parts. You write one program for a bracket. Change three parameters — length, width, hole diameter — and the same program machines a different bracket. No editing. No copying. Just new parameter values at the top of the program.

Parametric programming is common on Siemens and Heidenhain controllers. Fanuc supports it through macro B with variable substitution, but the workflow is less streamlined.

Custom Macro with G65 and G66

Fanuc custom macro B uses G65 to call a macro and G66 to call it in a modal loop. G65 runs the macro once and returns. G66 runs it repeatedly at every block until you cancel with G67.

G66 is useful for patterns like drilling a row of holes where each block triggers the same macro with a different position. The controller passes the current X and Y into the macro as variables, the macro drills, and the controller moves to the next position automatically.

The danger with G66 is forgetting the G67 cancel. If you leave G66 active and the next block is a rapid move, the controller will try to run the macro on a rapid — which usually means the tool slams into the part at rapid speed. Always pair G66 with G67 in the same block or immediately after.


Trigonometric Macros: The Real Workhorse

Sine and Cosine for Circular Patterns

The most used math functions in CNC macros are sine and cosine. They convert an angle and a radius into X and Y offsets. This is the backbone of every bolt circle, every polar coordinate pattern, and every rotational machining operation.

On Fanuc, the functions are FUP, FIX, FUP for rounding, and SIN, COS for trigonometry. On Siemens, they are R0=SIN(R1), R0=COS(R1). The syntax differs but the math is identical.

A typical bolt circle macro looks like this in concept: set the radius, set the starting angle, set the angular increment (360 divided by number of holes), then loop. In each iteration, calculate X and Y using cosine and sine, move to that position, drill, and increment the angle. Six lines of logic replace dozens of lines of hardcoded positions.

Square Root and Absolute Value for Geometry

Square root shows up constantly when you calculate distances between points or when you work with Pythagorean relationships. Absolute value is useful when you need a positive number regardless of direction — common when calculating step-over distances or clearance values.

These functions let you write geometry-driven macros that adapt to any input. Give the macro two points and it calculates the distance. Give it a radius and a chord length and it calculates the sagitta. The controller does the math. You just feed it the inputs.


Common Macro Mistakes That Wreck Production Runs

Forgetting That Angles Are in Degrees, Not Radians

This one bites constantly. Most CNC controllers expect trigonometric functions to receive angles in degrees. If you feed in radians by mistake, your cosine of 90 degrees becomes the cosine of 90 radians, which is a completely different number. The tool moves to a random position and you get a crash or a gouge.

Always confirm the angle mode on your controller. On Fanuc, the default is degrees. On some older or specialized controllers, it might be radians or grads. Check the setting before you write a single line of trigonometry.

Using GOTO Without a Label

GOTO jumps to a label in the program. If the label does not exist, the controller throws an alarm and the program stops. This sounds obvious, but in a long macro with many jumps, it is easy to misspell a label or delete it during editing.

Use structured programming instead of GOTO when possible. Loops and conditional statements (IF/THEN/ELSE) are easier to read and harder to break. Reserve GOTO for cases where the logic genuinely requires a jump — like skipping a section of code based on a condition.

Not Testing the Macro on Scrap First

A macro that looks perfect on the screen can behave differently on the machine. Backlash, servo lag, and rounding errors in the controller math all add up. Always run a macro on scrap material before you put it on a real part. Watch the tool path on the graphic. Check the first few positions manually. If the spacing is off by even 0.01mm, fix the macro before it touches production stock.


When Macros Are Not the Answer

Macros are powerful but they are not always the right tool. If a pattern appears only once in a program, writing a macro adds complexity without saving time. The break-even point is usually around three to five repetitions. Below that, hardcode it. Above that, macro it.

Also, macros make programs harder to read for operators who did not write them. If your shop has high turnover or multiple programmers sharing programs, keep macros simple and well-commented. A macro that saves you ten minutes of typing but takes another programmer an hour to understand is not a net win.

The best macros are the ones you write once and reuse forever. Build a personal library. Every time you solve a pattern with a macro, save it. The next time the same pattern shows up — and it will — you pull the macro from the library, change two or three variables, and you are done. That library is worth more than any CAM software.

Share:

WhatsApp
Whatsapp Moi
QR Code WhatsApp
Service d'usinage CNC fiable en Chine | SINO-TOOLS
(0/8)