All writing
Automation7 min read

FANUC Macro B in 20 minutes: variables, IF, WHILE, and G65

Macro B turns a G-code program into a program: variables, math, decisions, and loops, running right on the control. Here's everything you need to write your first useful macro, in the order you'll need it.

Visitors talking in front of a wall of CNC control panels and drive units at a machine-tool exhibition

Plain G-code is a list of coordinates. Custom Macro B (FANUC's name; most people just say "Macro B") makes it a language: variables, arithmetic, IF, WHILE, and subprograms that take arguments. It runs on the control itself, with no PC and no post-processor, and it's behind most of the clever stuff you've seen on a shop floor: family-of-parts programs, probing routines, automatic offset updates, bolt circles you type as one line.

This is the 20-minute version: enough to read and write real macros, in the order you'll need the pieces. You can paste the variable, math, and loop examples below into the Macro B Playground on this site, which runs a FANUC-style interpreter in your browser and plots the toolpath, so you can try each idea without risking a spindle. (The playground covers the everyday subset; it doesn't do G65 calls, so test the bolt circle there by setting #24, #25, #18… at the top instead.)

Check the option, check the manual

Custom Macro is an option on many older FANUC controls and standard on many newer ones; the variable ranges and some behaviours also vary by model and parameter settings. Everything here reflects common 0i/30i-series behaviour. Confirm details in the Custom Macro section of your control's operator manual before you run anything on a machine.

Minute 1–4: variables

Every variable is a # followed by a number. The number decides its scope and lifetime, which is the single most important thing to learn first:

RangeTypeLifetimeUse it for
#0Null ("vacant")Always empty, read-onlyTesting whether a variable was set
#1–#33LocalOnly inside the current macro callArguments and scratch math
#100–#199Common, volatileCleared at power-off (by default)Values shared between programs in one session
#500–#999Common, retainedSurvive power-offCounters, settings, probe results you keep
#1000 and upSystemControl's own stateOffsets, positions, alarms, modal state
Exact common-variable ranges depend on the control and options (some have only #100–#149 and #500–#549). Check before you claim a block of them.
#1 = 25.0          (local: lives only in this program level)
#100 = #1 * 2      (common: visible to every program until power-off)
#501 = #501 + 1    (retained: a part counter that survives power cycles)

Keep a variable map

The #500s are global and permanent, so two macros from two programmers will eventually collide on #510. Keep a one-page map of which retained variables belong to which macro, taped inside the control cabinet door or in your program repo. It's the cheapest bug prevention in CNC.

Minute 5–8: math

Arithmetic is what you'd expect, with two FANUC quirks: square brackets [ ] group expressions (round brackets are comments), and trig works in degrees.

#1 = 40.0                       (radius)
#2 = 30.0                       (angle, DEGREES)
#3 = #1 * COS[#2]               (X = 34.641)
#4 = #1 * SIN[#2]               (Y = 20.000)
#5 = SQRT[#3 * #3 + #4 * #4]    (back to 40.0)
#6 = ATAN[#4] / [#3]            (angle back: 30.0 - note the FANUC two-bracket form)
#7 = FIX[7.8]                   (7  - round toward zero)
#8 = FUP[7.2]                   (8  - round away from zero)
#9 = ROUND[7.5]                 (8)
#10 = ABS[-3.2]                 (3.2)

Functions bind tightest, then * and /, then + and -. When in doubt, add brackets: they cost nothing and the next person to read the macro will thank you.

Minute 9–12: decisions and loops

Comparisons use letters, not symbols: EQ, NE, GT, GE, LT, LE. There are two forms of IF, and one loop:

IF [#1 GT 50.0] GOTO 100          (jump to block N100 if true)
IF [#2 EQ 0] THEN #2 = 1          (single assignment if true)

#10 = 0                           (loop counter)
WHILE [#10 LT 8] DO1              (DO1...END1 - loop labels 1 to 3 can nest)
  #11 = #10 * 45.0                (angle of this hole)
  (...do something per hole...)
  #10 = #10 + 1
END1

N100 M30

WHILE loops can nest three deep, using labels DO1/END1, DO2/END2, DO3/END3. A loop that never terminates is a real hazard on a machine, so always increment the counter before you write the body, out of habit.

Minute 13–16: G65, macros with arguments

This is where Macro B pays off. G65 P<program> calls a macro as a subprogram and passes letter arguments that land in local variables. Under the standard mapping (Argument Specification I), the letters map like this:

LetterVariableLetterVariableLetterVariable
A#1I#4R#18
B#2J#5S#19
C#3K#6T#20
D#7M#13U#21
E#8Q#17V#22
F#9H#11W / X / Y / Z#23 / #24 / #25 / #26
G, L, N, O, and P can't be used as arguments. I, J, K come out-of-order on purpose (#4–#6); memorize the table or keep it on the control.

So G65 P9100 X0. Y0. R40. H8. Z-12. F120. arrives inside O9100 as #24=0, #25=0, #18=40, #11=8, #26=-12, #9=120. A bolt-circle macro then reads like the description of a bolt circle:

O9100 (BOLT CIRCLE: X Y CENTER, R RADIUS, H HOLES, Z DEPTH, F FEED)
IF [#18 EQ #0] THEN #3000 = 1 (R RADIUS MISSING)
IF [#11 EQ #0] THEN #3000 = 2 (H HOLE COUNT MISSING)
IF [#11 LE 0] THEN #3000 = 3 (H MUST BE POSITIVE)
#30 = 0                                  (hole index)
WHILE [#30 LT #11] DO1
  #31 = #30 * 360.0 / #11                (angle of hole)
  #32 = #24 + #18 * COS[#31]
  #33 = #25 + #18 * SIN[#31]
  G0 X#32 Y#33
  G1 Z#26 F#9
  G0 Z2.0
  #30 = #30 + 1
END1
M99

Notice the first three lines: validate arguments before you move anything. An unset argument reads as vacant (#0), and in arithmetic vacant behaves like zero, so a forgotten R would otherwise drill eight holes in the same spot at the centre. #3000 = n (MESSAGE) stops the program with a custom alarm. (The EQ #0 test checks for vacant, which is different from zero; it's one of the few places that distinction matters.)

Minute 17–20: system variables worth memorizing

VariableWhat it isTypical use
#3000User alarm (write a number + message)Stop on bad arguments or failed checks
#3006Stop with messagePrompt the operator, e.g. "FLIP PART"
#3901 / #3902Parts machined / parts requiredRead or bump the part counter
#4001–#4022Active modal G-codes (by group)Save and restore G90/G91, plane, etc.
#4120Active T codeKnow which tool is in the spindle
#5021–#5023Current machine position X, Y, ZPosition checks in safe routines
#5041–#5043Current work position X, Y, ZLogging, probing math
#5221–#5223G54 X, Y, Z work offsetUpdate offsets after probing (G55 = #5241, +20 per offset)
Common 0i/30i assignments. Offset and tool-offset variable numbers in particular depend on the control and options; verify before writing to them.

Writing to offset variables is how probing macros close the loop: measure a bore, compute the error, write it to the work offset, and the next part is corrected automatically. Those same variables are what a PC can read remotely; see reading FANUC macro variables from a PC.

The gotchas that bite everyone once

  • Type the decimal point. In G65 arguments and in motion words, a value without a decimal point can be interpreted in the control's least input increment rather than millimetres, so R40 may arrive as 0.040. Write R40., always. It's the most common first-macro bug.
  • Lookahead reads ahead of motion. The control processes macro statements before the preceding motion blocks finish. Reading a position variable (#5021…) right after a move can return a value from before the move completed. Check your manual for how to force a wait on your control before trusting position reads.
  • Vacant isn't zero. #1 EQ 0 and #1 EQ #0 are different tests. Use #0 to check for missing arguments.
  • Retained variables remember your bugs. A wrong value in #510 survives power cycles. Initialise counters deliberately and print them in the program header comment while developing.
  • Single-block and dry-run first. A macro with a loop and a sign error is a very fast way to drive a tool into a vise. Prove it in the playground or the control's graphics, then single-block it with the feed override low.
Macro B is the cheapest automation in the shop: no PC, no license beyond the option, and it runs exactly where the problem is.

Where to go next: generating G-code from Python is the PC-side alternative when logic outgrows the control, and where CNC cycle time actually hides shows where macros like these save real minutes.

Frequently asked questions

What is FANUC Macro B?+

Custom Macro B is FANUC's built-in programming extension for G-code. It adds variables (#1, #100, #500…), arithmetic and trig functions, IF/GOTO, WHILE/DO/END loops, and G65 macro calls with letter arguments, all running on the CNC control itself.

What is the difference between #100 and #500 variables?+

Both are common (global) variables visible to all programs. #100–#199 are typically cleared when the control powers off, while #500–#999 are retained through power cycles. Exact ranges depend on the control and its options.

How do G65 arguments map to variables?+

Under Argument Specification I: A=#1, B=#2, C=#3, I=#4, J=#5, K=#6, D=#7, E=#8, F=#9, H=#11, M=#13, Q=#17, R=#18, S=#19, T=#20, U=#21, V=#22, W=#23, X=#24, Y=#25, Z=#26. G, L, N, O, and P cannot be used as arguments.

How many levels can WHILE loops be nested in FANUC macros?+

Three, using the loop labels DO1/END1, DO2/END2, and DO3/END3. Labels can be reused for loops that don't overlap.

Muerus Rodrigues

Applications Engineer

Get in touch

Keep reading

Home
Projects
Blog
Tools
Code
Stepsmith
Contact
LinkedIn
Request Résumé