Machine Code – Compiling or Interpreting Machine G-Code

firmwaremachine-code

The G-Code and M-Code that we used to instruct CNC lathe, 3d-Printers and engraving machines, to my understanding, is not a programming language, but a scripting language like Python where scripts such as G00, T01, M18 etc would instruct the micro-controller to call a functions (e.g. some numerical mathematics).

Where are these functions or library of functions? Is there a ISO standard C/C++ libraries that these G-Code call from?

I am trying to understand how a machine "understands" the G-code and where it is fetching the series of logics and movement that the G-code points to. Take Marlin firmware for example. It supposed to parse the G-code and instruct the stepper motors accordingly, but I do not fine the mathematics and the logic by going through the codes. It seems the MCU magically understands what G-Code is and compile the machine binaries and output the respective digital signal.

I believe I am either misunderstanding or missing some information, which I do not find in wikipedia.

Best Answer

G-code was created to be extremely easy to parse by devices with extremely limited computing resources. It's almost more of a data file format than a programming language. There is no "compilation" step. It's interpreted as it is read, line by line, with a small buffer to avoid mechanical issues from timing latency. There's also no "standard library." Firmware typically has to be recompiled for each different combination of microcontroller and motor hardware used, and it takes quite a bit of work to even support what might seem like those minor variations.

In the case of the Marlin firmware, inside the Marlin_main.cpp you have a get_command() function that keeps a queue filled with the commands, and you have a process_next_command() that contains a massive switch statement to pull the next command from the queue and call the appropriate function.

As far as what those individual functions do, that depends a lot on what kind of hardware you have connected, but if you know you have a certain clock rate, a certain type of stepper motors, connected to certain axes, with a certain resolution, connected to certain pins, you can work out the right pins to toggle at the right time to say, move the head in a straight line from a to b along the x axis with a certain speed. From there it's really just a big grind to implement all the different required commands with the correct timing.

Related Topic