APIs, concepts, guides, and more
G-Code

Use G-Code to specify coordinated motions in Cartesian space for specialized machines, with support for basic codes and a user interface for building or using pre-built configurations.

Note
The RapidCode G-Code Parser and Executor are not a replacement for a true CNC controller. It is not a simple drop-in replacement for a full function CNC provided by companies who offer turn-key solutions in this field. However, the flexibility of the RMP motion controller as well as interoperability with PathMotion and arbitrary kinematic robot models make it ideal for designing specialized machines that use G-Code as the motion command source.

๐Ÿ”น What is G-Code?

G-Code is a programming language for specifying coordinated motions in cartesian space used by many manufacturing machines.

RapidCode API G-Code Sample

๐Ÿ”น How does G-Code work?

In the RapidCode API, G-Code parsing requires the creation of a Robot instance, which requires the kinematic model to be specified, and a MultiAxis instance that contains all of the axes used during the execution of the G-Code file. Machines with linear prime or redundant axes can also be configured by specifying the axis to link their motion to using LinearModelBuilder.

You can find the full set of G-Code functions in our Gcode class.

๐Ÿ”น User Interface

Build your user interface using our Gcode class or use our G-Code UI built into RapidSetup.

RapidSetup: G-Code UI

๐Ÿ”น Supported Codes

Note
We currently support a set of G-codes focused mainly on path motion.
For additional G-code support, please Contact Us.
Code Description Explanation
G0 Rapid positioning Rapid motion to a point in Cartesian space via the quickest path (not always linear), using default axis settings (DefaultVelocitySet)
G1 Linear interpolation Coordinated linear motion between points in cartesian space
G2 Circular interpolation, clockwise Clockwise arc motion about a center point to an end point
G3 Circular interpolation, counter clockwise Counter clockwise arc motion about a center point to an end point
G4 Dwell Pauses all axes for the specified time in seconds, which may be fractional.
G9 Exact stop check (non-modal) Placed before a motion group command, the machine will come to a complete stop at end of the move before continuing to the next. Only remains active for one line.
G17 XY plane selection G2/3 commands happen on the XY plane (Default mode)
G18 ZX plane selection G2/3 commands happen on the ZX plane
G19 YZ plane selection G2/3 commands happen on the YZ plane
G20 Programming in inches (in) Distances after this command will be interpreted as inches. Rotations are always in degrees
G21 Programming in millimeters (mm) Distances after this command will be interpreted as mm. Rotations are always in degrees
G54-G59 Work Offset Applies a pre-configured XYZ offset relative to home(origin) to all motions.
G61 Exact Stop Check (modal) The machine will come to a complete stop at end of the move before continuing to the next for all future moves until G64 is called.
G64 Cancel Exact Stop Reset to default cutting mode (cancel G61)
G90 Absolute programming Distances after this command will be interpreted as absolute (relative to origin 0,0,0)
G91 Incremental programming (relative) Distances after this command will be interpreted as incremental (relative to current position at start of move)
G92 Coordinate System Offset Sets the current (absolute) position to have the specified coordinate values by moving the origin.

๐Ÿ”น M-Code Support

M-codes are handled through user-defined callbacks (GcodeCallback).

There are two ways to register callbacks:

  • Gcode.MCodeCallbackRegister(mCode, callback, containsMotion): Registers a callback for a specific M-code (preferred).
    Passing nullptr as the callback will unregister the callback for that M-code.
  • Gcode.CallbackRegister(callback, containsMotion):
    Registers a single catch-all callback used when no per-code handler exists.
    Passing nullptr as the callback will unregister the catch-all callback.

When running a G-code program, the interpreter:

  1. Finishes any prior motion.
  2. Executes the registered callback for that specific M-code (via Gcode.MCodeCallbackRegister).
  3. If none exists, executes the catch-all callback (via Gcode.CallbackRegister), if registered.
  4. If containsMotion=true, re-processes subsequent motion to reflect the updated position.
  5. Continues program execution.

While both methods can be used, MCodeCallbackRegister is the preferred way to handle M-codes.

๐Ÿ”น Not Yet Supported

Warning
G-Code is not running in the RMP firmware but instead, an internal RapidCode thread that buffers motions to the RMP
(Getters and setters will not work across multiple applications at the same time)

๐Ÿ“œ Sample Code

G-Code with Free Axis

Setup and run a simple G-Code program.

  • C#

    /* This sample demonstrates how to set up and run G-Code motion with a Robot object.
    Shows how to create a kinematic model, load G-Code programs, and execute them.
    Includes callback handling for M-codes and monitoring execution progress.
    */
    using RSI.RapidCode; // RSI.RapidCode.dotNET;
    using System.Threading;
    Console.WriteLine("๐Ÿ“œ Motion: G-Code");
    // get rmp objects
    try
    {
    Helpers.CheckErrors(controller);
    // sample G-Code program
    string gcodeProgram = @"G91; Sets the programming mode to RELATIVE
    G64; Turns off exact stop mode (Default)
    G1 X1.0 Y0.0 Z0.0 A1.0 F60.0; Move on USERUNIT in positive x direction at 60in/min. Moves Free axis A to position 1.0.
    G3 X1 Y1 I0 J1; Counter clockwise arc with a center point of 0,1,0 and end point of 1,1,0 relative to the current position
    M80; Show how to use an M-code with GcodeCallback!";
    // set robot axis labels
    const string xLabel = "X-Axis";
    const string yLabel = "Y-Axis";
    const string zLabel = "Z-Axis";
    const string aLabel = "A-Axis";
    // get the 4 axis needed for XYZA robot
    Axis xAxis = controller.AxisGet(Constants.AXIS_0_INDEX);
    Axis yAxis = controller.AxisGet(Constants.AXIS_1_INDEX);
    Axis zAxis = controller.AxisGet(Constants.AXIS_2_INDEX);
    Axis aAxis = controller.AxisGet(Constants.AXIS_3_INDEX);
    // configure phantom axes
    // set axis labels
    xAxis.UserLabelSet(xLabel);
    yAxis.UserLabelSet(yLabel);
    zAxis.UserLabelSet(zLabel);
    aAxis.UserLabelSet(aLabel);
    // create multi-axis object for joints
    MultiAxis jointsMultiAxis = controller.MultiAxisGet(0);
    Axis[] axes = [xAxis, yAxis, zAxis, aAxis];
    jointsMultiAxis.AxesAdd(axes, axes.Length);
    jointsMultiAxis.ClearFaults();
    jointsMultiAxis.AmpEnableSet(true);
    // create kinematic model
    const string modelName = "RSI_XYZA";
    const double scaling = 1.0;
    const double offset = 0.0;
    LinearModelBuilder builder = new(modelName);
    builder.JointAdd(new LinearJointMapping(0, CartesianAxis.X) { ExpectedLabel = xLabel, Scaling = scaling, Offset = offset });
    builder.JointAdd(new LinearJointMapping(1, CartesianAxis.Y) { ExpectedLabel = yLabel, Scaling = scaling, Offset = offset });
    builder.JointAdd(new LinearJointMapping(2, CartesianAxis.Z) { ExpectedLabel = zLabel, Scaling = scaling, Offset = offset });
    builder.FreeAxisAdd(new ModelAxisMapping(3) { ExpectedLabel = aLabel, Scaling = scaling, Offset = offset });
    // set free axis accel & decel before creating the robot object
    // create Robot object
    Robot robot = Robot.RobotCreate(controller, jointsMultiAxis, builder, MotionController.AxisFrameBufferSizeDefault);
    // set robot acceleration
    robot.Gcode.AccelerationRateSet(1000);
    // the free axis index refers to the index in the RobotPosition freeAxes array
    robot.Gcode.FreeAxisLetterSet(gcodeLetter: 'A', freeAxisIndex: 0);
    // register callback for M-code commands (note: callback class would need to be defined separately)
    SampleGcodeCallback callback = new();
    robot.Gcode.CallbackRegister(callback);
    try
    {
    // load and prepare G-Code for execution
    robot.Gcode.Load(gcodeProgram);
    }
    catch (Exception e)
    {
    Console.WriteLine($"Error loading G-Code: {e.Message}");
    Helpers.CheckErrors(robot.Gcode); // get additional G-Code error details
    throw;
    }
    // print motion details
    Console.WriteLine($"G-Code Line Count: {robot.Gcode.LineCountGet()}");
    Console.WriteLine($"G-Code Error Log Count: {robot.Gcode.ErrorLogCountGet()}");
    Console.WriteLine($"G-code estimated run time: {robot.Gcode.DurationGet()} seconds");
    // start motion
    robot.Gcode.Run();
    // monitor execution
    Int64 activeLineNumber = 0;
    do
    {
    Thread.Sleep(200);
    if (activeLineNumber != robot.Gcode.ExecutingLineNumberGet()) // only write if on new line
    {
    activeLineNumber = robot.Gcode.ExecutingLineNumberGet();
    Console.WriteLine($"G-Code Line Number: {activeLineNumber}");
    }
    } while (robot.Gcode.IsRunning());
    Helpers.CheckErrors(robot.Gcode); // check for motion errors
    // cleanup
    Robot.RobotDelete(controller, robot);
    Console.WriteLine("โœ… G-Code motion completed successfully");
    }
    // handle errors as needed
    finally
    {
    controller.Delete(); // dispose
    }
    public class SampleGcodeCallback : GcodeCallback
    {
    public override void Execute(GcodeCallbackData data)
    {
    Console.WriteLine("G-Code Callback executed: " + data.LineNumber + " " + data.LineText);
    // if you want to notify the Gcode object that there's an error processing, set its error details:
    // data.UserError.number = RSIErrorMessage.RSI_ERROR_MESSAGE_DYNAMIC;
    // data.UserError.text = "This is an error from the callback.";
    }
    }
    static void ConfigurePhantomAxis(Axis phantomAxis)
    Configures a phantom axis on the controller.
    Definition _helpers.cs:144
    static void CheckErrors(RapidCodeObject rsiObject)
    Checks for errors in the given RapidCodeObject and throws an exception if any non-warning errors are ...
    Definition _helpers.cs:15
    Helpers class provides static methods for common tasks in RMP applications.
    Definition _helpers.cs:5
    void UserLabelSet(const char *const userLabel)
    Set the axis User defined Label.
    Represents a single axis of motion control. This class provides an interface for commanding motion,...
    Definition rsi.h:5870
    void DefaultAccelerationSet(double acceleration)
    Set the default acceleration in UserUnits.
    void DefaultDecelerationSet(double deceleration)
    Set the default deceleration in UserUnits.
    Axis * AxisGet(int32_t axisNumber)
    AxisGet returns a pointer to an Axis object and initializes its internals.
    static constexpr int32_t AxisFrameBufferSizeDefault
    The default value of the AxisFrameBufferSize, also the minimum allowable value.
    Definition rsi.h:854
    static MotionController * Get()
    Get an already running RMP EtherCAT controller.
    void Delete(void)
    Delete the MotionController and all its objects.
    MultiAxis * MultiAxisGet(int32_t motionSupervisorNumber)
    MultiAxisGet returns a pointer to a MultiAxis object and initializes its internals.
    Represents the RMP soft motion controller. This class provides an interface to general controller con...
    Definition rsi.h:800
    void AxesAdd(Axis **axes, int32_t axisCount)
    Represents multiple axes of motion control, allows you to map two or more Axis objects together for e...
    Definition rsi.h:10804
    void ClearFaults()
    Clear all faults for an Axis or MultiAxis.
    int32_t AmpEnableSet(bool enable, int32_t ampActiveTimeoutMilliseconds=AmpEnableTimeoutMillisecondsDefault, bool overrideRestrictedState=false)
    Enable all amplifiers.
    CartesianAxis
    This enum specifies which Cartesian axis a LinearJointMapping maps a robot joint to.

Changing Linear Units G-Code

How changing linear units affects vel and accel setters.

  • C#

    /* This sample demonstrates how changing linear units affects G-Code velocity and acceleration setters.
    Shows how to work with different unit systems in G-Code and understand the impact on motion parameters.
    */
    using RSI.RapidCode; // RSI.RapidCode.dotNET;
    Console.WriteLine("๐Ÿ“œ Motion: G-Code Units");
    // get rmp objects
    try
    {
    Helpers.CheckErrors(controller);
    // set robot axis labels
    const string xLabel = "X-Axis";
    const string yLabel = "Y-Axis";
    const string zLabel = "Z-Axis";
    const string aLabel = "A-Axis";
    const string bLabel = "B-Axis";
    const string cLabel = "C-Axis";
    // get the 6 axis needed for XYZABC robot
    Axis xAxis = controller.AxisGet(Constants.AXIS_0_INDEX);
    Axis yAxis = controller.AxisGet(Constants.AXIS_1_INDEX);
    Axis zAxis = controller.AxisGet(Constants.AXIS_2_INDEX);
    Axis aAxis = controller.AxisGet(Constants.AXIS_3_INDEX);
    Axis bAxis = controller.AxisGet(Constants.AXIS_4_INDEX);
    Axis cAxis = controller.AxisGet(Constants.AXIS_5_INDEX);
    // configure phantom axes
    // set axis labels
    xAxis.UserLabelSet(xLabel);
    yAxis.UserLabelSet(yLabel);
    zAxis.UserLabelSet(zLabel);
    aAxis.UserLabelSet(aLabel);
    bAxis.UserLabelSet(bLabel);
    cAxis.UserLabelSet(cLabel);
    // create multi-axis object for joints
    MultiAxis jointsMultiAxis = controller.MultiAxisGet(0);
    Axis[] axes = [xAxis, yAxis, zAxis, aAxis, bAxis, cAxis];
    jointsMultiAxis.AxesAdd(axes, axes.Length);
    jointsMultiAxis.ClearFaults();
    // create kinematic model with centimeters
    const LinearUnits units = LinearUnits.Centimeters;
    const string modelName = "RSI_XYZABC_Centimeters";
    const double scaling = 1.0;
    const double offset = 0.0;
    // build model
    LinearModelBuilder builder = new(modelName);
    builder.UnitsSet(units);
    builder.JointAdd(new LinearJointMapping(0, CartesianAxis.X) { ExpectedLabel = xLabel, Scaling = scaling, Offset = offset });
    builder.JointAdd(new LinearJointMapping(1, CartesianAxis.Y) { ExpectedLabel = yLabel, Scaling = scaling, Offset = offset });
    builder.JointAdd(new LinearJointMapping(2, CartesianAxis.Z) { ExpectedLabel = zLabel, Scaling = scaling, Offset = offset });
    builder.JointAdd(new LinearJointMapping(3, CartesianAxis.Roll) { ExpectedLabel = aLabel, Scaling = scaling, Offset = offset });
    builder.JointAdd(new LinearJointMapping(4, CartesianAxis.Pitch) { ExpectedLabel = bLabel, Scaling = scaling, Offset = offset });
    builder.JointAdd(new LinearJointMapping(5, CartesianAxis.Yaw) { ExpectedLabel = cLabel, Scaling = scaling, Offset = offset });
    // create Robot object
    Robot robot = Robot.RobotCreate(controller, jointsMultiAxis, builder, MotionController.AxisFrameBufferSizeDefault);
    // note: to use the above kinematic model you must have a gantry (linear 1:1 kinematics)
    // and each linear axis must have its user units scaled to millimeters
    // this will return none - a gcode unit hasn't been established so it will use path units
    // if path units are not set it will use user units
    Console.WriteLine($"Initial G-Code units: {robot.Gcode.UnitsGet()}");
    robot.Gcode.AccelerationRateSet(10); // sets G-Code acceleration to 10 Centimeters per MINUTE squared
    robot.Gcode.FeedRateSet(10); // sets G-Code velocity to 10 Centimeters per MINUTE
    Console.WriteLine($"Acceleration rate (cm/minยฒ): {robot.Gcode.AccelerationRateGet()}");
    Console.WriteLine($"Feed rate (cm/min): {robot.Gcode.FeedRateGet()}");
    robot.Gcode.UnitsSet(LinearUnits.Inches); // this is the same as executing G-Code line G20
    Console.WriteLine($"G-Code units after setting to inches: {robot.Gcode.UnitsGet()}");
    robot.Gcode.AccelerationRateSet(10); // sets G-Code acceleration to 10 Inches per MINUTE squared
    robot.Gcode.FeedRateSet(10); // sets G-Code velocity to 10 Inches per MINUTE
    Console.WriteLine($"Acceleration rate (in/minยฒ): {robot.Gcode.AccelerationRateGet()}");
    Console.WriteLine($"Feed rate (in/min): {robot.Gcode.FeedRateGet()}");
    // cleanup
    Robot.RobotDelete(controller, robot);
    }
    // handle errors as needed
    finally
    {
    controller.Delete(); // dispose
    }
    LinearUnits
    Unit types. For Cartesian Robot/G-Code use.