Guide · Programming
Fanuc Macro B for Beginners: Variables, IF, WHILE and Your First Useful Macro
Learn Fanuc Macro B with small working examples: variables, arithmetic, IF and WHILE, G65 calls with arguments, and a bolt circle macro with safety checks.
On this page
A macro is a program with variables. One macro replaces dozens of similar programs. Most Fanuc, Haas and Mitsubishi controls understand this language. On some Fanuc controls it is an option.
Variables
- #1 to #33: local, used for arguments, empty again after the macro ends.
- #100 to #199: common, usually lost at power off.
- #500 to #999: common, kept after power off.
- #1000 and above: system variables such as offsets and positions. The numbers depend on the control.
An empty variable is not zero. It is #0 (null). That is how you test whether an argument was given.
Arithmetic and decisions
#100=25.4/2
#101=SQRT[#100*#100+10.*10.]
#102=ROUND[#101]
IF [#101 GT 15.] GOTO 100
G01 X#101 F200.
N100 (CONTINUE HERE)Comparisons are EQ, NE, GT, GE, LT and LE. Expressions use square brackets. Round brackets are comments.
A bolt circle macro
Call: G65 P9100 X50. Y50. D60. H8 A0. Z-12. R2. F150.
O9100 (BOLT CIRCLE)
IF [#7 EQ #0] THEN #3000=1 (D MISSING)
IF [#11 LT 1] THEN #3000=2 (H HOLES MISSING)
IF [#1 EQ #0] THEN #1=0
#30=0
WHILE [#30 LT #11] DO1
#31=#1+#30*360/#11
#32=#24+#7/2*COS[#31]
#33=#25+#7/2*SIN[#31]
G90 G00 X#32 Y#33
Z#18
G01 Z#26 F#9
G00 Z#18
#30=#30+1
END1
M99The letters of the G65 line fill fixed variables: A=#1, D=#7, F=#9, H=#11, R=#18, X=#24, Y=#25, Z=#26. #3000=1 (TEXT) stops the machine with an alarm, which is the best protection against a forgotten argument.
Good habits
- Check every argument at the top of the macro.
- Put a comment with a sample call into the first lines.
- Test above the part with single block. Display the variable page while it runs.
- Macros above O9000 can be locked against editing.
For a simple pattern without macros use the bolt circle calculator.
More guides
- 3+2 Machining with G68.2, G254 and CYCLE800: Tilted Work Planes Explained
- Faster or Cheaper? How Cutting Speed Changes the Cost per Part
- First Article Inspection and Setup Sheet: A Checklist for Small Shops
- AI in CNC Programming: What Works Today and What to Watch Out For
- MTConnect vs OPC UA: Connecting CNC Machines for Industry 4.0
- Lights-Out Machining: A Practical Checklist