Posted in

How to write G-code for CNC?

If you’ve ever stood next to a CNC machine as it carves a custom part from a block of aluminum or mils a precise groove in a sheet of acrylic, you’ve probably wondered: what turns a digital design on a screen into that physical, exact component? For us, a CNC machining supplier that’s sent parts to aerospace teams, medical device startups, and custom furniture makers over the last 12 years, the answer is G-code. It’s not just a bunch of random letters and numbers—it’s the language that bridges CAD designs and real-world production. Most new machinists or part designers I talk to think G-code is something you learn in a week, or that fancy CAM software writes it all for you. That’s half true. CAM tools do 90% of the heavy lifting, but understanding how G-code works, how to tweak it, and how to avoid the tiny mistakes that can ruin a $500 billet of titanium is the difference between a good part and a costly redo. Today, I’m breaking down how to write G-code (or at least how to review and adjust it like a pro) from the perspective of someone who’s seen way too many broken tools and delayed orders. CNC Machining

First, let’s start with the basics so we’re all on the same page. G-code (short for “geometric code”) is a standardized programming language for CNC machines, created back in the 1950s by machining pioneers who needed a way to automate what had previously been manual, slow milling. Every line of G-code is a command that tells the machine to move to a specific point, turn the spindle on, move the cutting tool forward, or change a tool. The “G” and “M” words are the backbone here: G-codes control movement (like G00 for rapid moves, G01 for linear cutting, G02/G03 for circular arcs) and M-codes control machine functions (like M03 to turn the spindle clockwise, M08 to turn coolant on, M30 to end the program). When we get a new design from a customer, we first import their CAD file—usually a STEP or IGES file, the industry standard for 3D designs—into our CAM software (we use Mastercam, but Fusion 360 is great for smaller shops too). The CAM generates a rough G-code program, but that’s where the work begins, especially for parts that need tight tolerances. A mistake as small as writing G00 instead of G01 can send a cutting tool slamming into a part at full speed, breaking it and ruining a workpiece.

Let’s walk through a simple example to make this concrete. Say we’re making a 1-inch square aluminum block with a 0.5-inch deep pocket. The first step in G-code is setting up the machine’s coordinate system, which is called the work offset (we use G54 for our main table). The work offset is critical because it tells the machine where “zero” is—so if we set G54 at the top-left corner of our block, all our coordinates will be relative to that point. The first lines of a typical G-code program look something like this:

O0001 (POCKET MILL FOR ALUMINUM BLOCK)
G54 G00 G90 X0 Y0 S15000 M03
G43 H01 Z1.0 M08

Let’s unpack that: O0001 is the program number, just a label so the machine can find the right code. G54 selects our work offset. G00 is a rapid move, so the machine moves as fast as possible to X0 Y0 (our zero point at the top of the block). G90 means we’re working in absolute coordinates, not relative (more on that in a minute). S15000 sets the spindle speed to 15,000 RPM, M03 turns it clockwise. G43 is a tool length offset—H01 refers to the specific tool we’re using, in this case a 1/4-inch end mill—and Z1.0 moves the tool up to 1 inch above the block’s surface, M08 turns on the coolant to keep the tool from overheating. That’s the setup, and if you get even one line wrong here—like writing G91 instead of G90—your tool will move to a totally wrong spot the second it starts cutting.

Next comes the cutting part. For our pocket, we’ll use G01, which is linear interpolation—meaning it moves the tool in a straight line at a set feed rate. The feed rate (set with F) is measured in inches per minute, and for aluminum with a solid carbide end mill, we’d use something like F30 IPM. So to cut the first edge of the pocket, the line would be G01 X0 Y0.5 Z-0.5 F30. Wait, hold on—Z-0.5 means the tool moves down to 0.5 inches below the surface, which is exactly how deep we need the pocket. If we wrote Z0.5, that would cut above the block and do nothing. Simple typo, huge mistake. We also use G02 and G03 for curves—G02 is a clockwise arc, G03 is counterclockwise. For a pocket that has a rounded corner, instead of drawing a straight line, we’d write something like G03 X0.5 Y0.5 I0 J0, where I and J are the offsets from the current X/Y position to the arc’s center. Again, mixing up G02 and G03 here would make the tool carve a bump instead of a smooth curve, and that’s not something we can fix later without reworking the part.

Now, here’s where most new writers (and even some new CAM operators) go wrong: not accounting for tool path compensation. Let’s say you have a part that requires a 0.5-inch hole, and your cutting tool is 0.25 inches wide. If you tell the CAM software to cut a path along the exact edge of the hole, the tool will take away half its diameter, making the hole too small by 0.125 inches. That’s where G41 and G42 come in—cutter radius compensation. G41 is for left compensation (when you’re moving along the path, the tool is to your left) and G42 is right compensation. This lets you program the exact dimension of the part, not the exact path the tool takes, and you can adjust the compensation number later if the tool wears down, instead of re-writing the entire G-code program. For example, if your tool is worn and now 0.24 inches wide instead of 0.25, you just change the compensation value in the machine’s settings, not the G-code line. Skipping cutter compensation or setting it incorrectly is the top reason we have to reject a program from a new customer or trainee—it’s an easy fix in the code, but it’s also the first thing we check when a part’s dimensions are off by a few thousandths of an inch.

Once you get the basics down, writing G-code for more complex parts means learning to handle multiple tools, deep cuts, and material-specific parameters. Let’s say you’re making a part that needs both a pocket and a threaded hole. That means tool changes, which use M06. A typical tool change line would look like: M06 T02, where T02 is the number of the new tool (in this case, a tap for the threads). Before the tool change, you have to make sure the machine is in a safe position—no parts in the way, tool up high enough that it doesn’t crash into the table. That means before M06, you’d have lines like G00 Z2.0 to move the tool up 2 inches, and G00 X1.0 Y2.0 to move it to the tool change position. For deep cuts, like a pocket that’s 1 inch deep in steel, you don’t want to plunge the tool straight down 1 inch in one go—that would snap the end mill in half. Instead, you use pecking cycles, or G-codes like G83 for deep hole drilling or G73 for pecking cycles for milling. G73 will make the tool cut a small amount, retract slightly to break the chip, cut again, and so on, which prevents chips from getting stuck and damaging the tool or part. For steel, we use a lower spindle speed (maybe S8000 instead of 15000 for aluminum) and a slower feed rate (F15 instead of F30), because steel is much harder. That’s something you can’t get from a generic CAM program—you have to adjust those parameters based on the material, the tool type, and the machine you’re using, which is why understanding how to tweak G-code is so important.

Now, I’ll be honest: in 12 years as a CNC machining supplier, we don’t write G-code from scratch anymore. No one does, except maybe hobbyists making tiny parts at home. The CAM software does the bulk of the work, mapping out the tool path based on your CAD design. But that doesn’t mean you can ignore G-code. Most of the time, the CAM program will have a default feed rate for aluminum that’s way too high, or it will set the spindle speed wrong for a 1/8-inch tool, or it will forget to add coolant lines. Even worse, CAM software sometimes generates tool paths that have rapid moves (G00) that pass over clamps or other parts on the machine table, which is a crash waiting to happen. Last year, we got a program from a customer that had a G00 move that went straight through a vise jaw. The CAM software didn’t account for the vise’s position, and if we’d run the code as-is, we would have broken a $300 end mill and ruined a custom jaw. That’s why we always review every line of G-code before we run a job—because even the best CAM tools miss things.

Another common mistake I see new people make is not using comments in their G-code. Comments are lines that start with a parenthesis, like (POCKET CUT 0.5 IN DEEP, ALUMINUM 6061). They don’t do anything for the machine, but they make it way easier to follow the program if something goes wrong. If a part comes out with a groove that’s too shallow, I can go back to the G-code and see exactly what line is supposed to cut to what depth, instead of scrolling through 500 lines of numbers. It’s a small thing, but it saves hours of troubleshooting when something goes wrong.

Wait, let’s talk about tolerances too, because that’s where G-code precision matters most. Most custom parts we make need tolerances of +/- 0.005 inches, and some medical parts need +/- 0.001 inches. The G-code has to be written to match that. If your tolerance is 0.001 inches, you can’t have a feed rate that’s too high, or use a worn tool that shifts 0.002 inches mid-cut. That means setting the machine’s step resolution correctly—most mills have a resolution of 0.0001 inches, so your G-code should use at least three decimal places for coordinates, like X0.500, not X0.5. Using two decimal places might seem fine, but it can add up to a difference over a long path, especially for large parts like custom molds for automotive components.

Let’s also cover some common pitfalls that even experienced machinists run into. First, coordinate system confusion. If you set G54 at the wrong zero point—say, the bottom of the block instead of the top—every cut will be 1 inch too deep, and you’ll waste a whole workpiece. Second, mixing up inch and millimeter units. The G20 code sets inches, G21 sets millimeters, and if you accidentally use G21 when you meant G20, your entire part will be 25.4 times too big. We learned that the hard way 10 years ago, when a new intern wrote a program using G21 for a custom bracket for a customer who used inch units, and we had to scrap a $2,000 billet of titanium. Third, not turning off coolant or stopping the spindle at the end of the program. If you forget M05 (stop spindle) and M09 (turn off coolant), the machine will keep spinning the tool and flooding the table with coolant after the part is done, which can cause rust on the machine or damage to finished parts.

Now, if you’re looking to write your own G-code—either as a hobbyist, a machinist starting out, or a design engineer who wants to understand their parts better—here’s my advice for getting started. First, don’t write from scratch at first. Use a simple CAM tool like Fusion 360 for beginners, which has a free version for hobbyists and small teams. Import a simple 2D design, like a square with a hole, generate a tool path, and post-process it to G-code. Then open the G-code file in a text editor (Notepad++, VS Code, even TextEdit) and walk through each line, cross-referencing it with the design. See what G01 and G02 lines look like, how the coordinates work, and what M-codes do. Next, practice with a simulation tool—most CAM software has a built-in simulator that lets you run the G-code virtually, so you can see if there are any crashes or wrong paths without touching a real machine. Finally, start with small, simple parts first. Don’t jump into a mold for a custom truck part until you’ve written G-code for a 1-inch square block with a single pocket.

For those of you who are working with a CNC machining supplier like us—whether you’re a design engineer at a startup, a product manager at a aerospace company, or a maker working on a personal project—understanding the basics of G-code will make your life easier too. If you send us a CAD file, you can ask us to review the G-code before we run it, or you can request specific adjustments, like changing the spindle speed for a tough material. You’ll also be able to catch mistakes in the CAM program before they become costly errors. Last year, a medical device startup sent us a CAD file with a part that needed a sharp internal corner. The CAM software generated a tool path that used a 0.5-inch end mill, which couldn’t reach the corner without leaving a radius. When we reviewed the G-code, we caught that and swapped in a smaller 0.125-inch end mill, which let us make the part correctly without extra rework. That’s the value of knowing even a little bit about how G-code works.

At the end of the day, G-code is just a tool—like a wrench or a mill. It’s powerful when you know how to use it, and it can cause a lot of damage if you misuse it. We’ve spent 12 years refining our process, from reviewing every line of G-code for every job to adjusting parameters for every material and tool, because we know that the difference between a part that works and a part that gets returned is in the details of that code. If you have a custom part you need made, whether it’s a prototype for a new product, a replacement component for industrial equipment, or a small custom piece for a maker project, we can walk you through the G-code review process, adjust the code to fit your needs, and make sure your part is made to the exact specifications you need. Don’t let a simple G-code mistake derail your project—reach out, and we’ll work with you to make sure your parts come out right, every time.

CNC MillTurn References

  1. Smid, P. (2008). CNC Programming Handbook: A Comprehensive Guide to Practical CNC Programming. Industrial Press.
  2. Mastercam Help Documentation. (2024). G-Code and M-Code Syntax for Mill and Lathe Programming.
  3. Aerospace Industries Association. (2022). Best Practices for CNC Machining and G-Code Programming for Critical Flight Components.
  4. Oberg, E., Jones, F. D., Horton, H. L., & Ryffel, H. H. (2020). Machinery’s Handbook (31st ed.). Industrial Press.

Suzhou Apsertek Technology Co., Ltd.
We’re well-known as one of the leading cnc machining manufacturers and suppliers in China. With abundant experience, we warmly welcome you to buy high quality products made in China here and get free sample from our factory. We also accept customized orders.
Address: Room 227, Building 1, No.2996, Taidong Road, Huangdai Town, Xiangcheng District, Suzhou City, Jiangsu Province, China
E-mail: sales@aspertek.com
WebSite: https://www.aspertek.com/