RepRapFirmware G-Code Guide
RepRapFirmware G-Code Guide
This page describes the RepRapFirmware supported G-codes, originally based on the
information from the RepRap wiki G-code page.
G-Codes are a widely used machine control language. They are human readable
and editable. This page describes the RepRapFirmware supported G-codes.
RepRapFirmware follows the philosophy of "G-code everywhere", in essence the
users or external program's interaction with the firmware should be through G-
codes. There are G-codes for all supported control and configuration inputs along
with status and debugging information.
Introduction
A typical piece of G-code sent to a machine running RepRapFirmware might look
like this (The meaning of these codes (and more) is explained below on this page.)
T0
G-Code Everywhere
be entered by user one line at time, for example during configuration or testing
originate from macros that are triggered on startup, on certain events (such as
error conditions), or called by the user or UI.
be from a g-code file which are normally stored on the on-board or external SD
card.
The advantage of "G-code everywhere" is the same commands can be send from
any of the G-Code sources, and originate from the user, a UI, macro or file and it
will generate the same response from the firmware. This greatly improves the ease
and power of firmware configuration and operation.
G-Code Structure
This section explains the elements that make up a G-Code command.
Command Order
The general rule on command order in config.g is: don't try to change the
parameters of anything that you haven't already created and doesn't exist by
default.
For example:
Don't refer to any axis letter or extruder number that you haven't created using
M584 (except that XYZ already exist by default)
Don't refer to any temperature sensor in M950 or M106 before you create it
using M308
Don't refer to a heater in M307, M140, M141, M143 or m563 before you create
it using M950
Comments
G-Code comments begin at a semicolon, and end at the end of the line:
T0 ; This is a comment
G92 E0
;So is this
G28
Alternatively, comments can be enclosed in brackets, but they must start and end
on the same line:
Fields
A RepRap G-Code is a list of fields that are separated by white spaces or line
breaks. A field can be interpreted as a command, parameter, or for any other
special purpose. It consists of one letter directly followed by a number, or can be
only a stand-alone letter (Flag). The letter gives information about the meaning of
the field (see the list below in this section). Numbers can be integers (128)
or fractional numbers (12.42), depending on context. For example, an X coordinate
can take integers (X175) or fractionals (X17.62), but selecting extruder number
2.76 would make no sense. In this description, the numbers in the fields are
represented by nnn as a placeholder.
In RepRapFirmware 3.01 and later, instead of a number you may use an expression
enclosed in braces, for example {2+2}. See GCode Meta Commands for details of
the supported expression types.
Case sensitivity
Quoted strings
Example: to add SSID MYROUTER with password ABCxyz;" 123 to the WiFi network
list, use command:
Checking
This is an optional feature that is seldom used as g-code files are normally printed
form the on-board SD card.
N: Line number
Example: N123
If present, the line number should be the first field in a line. For G-code stored in
files on SD cards the line number is usually omitted.
*: Checksum
Example: *71
If present, the checksum should be the last field in a line, but before a comment.
For G-code stored in files on SD cards the checksum is usually omitted.
Method
The checksum "cs" for a G-Code string "cmd" (including its line number) is
computed by exor-ing the bytes in the string up to and not including the *
character as follows:
int cs = 0;
cs = cs ^ cmd[i];
and the value is appended as a decimal integer to the command after the *
character.
In RepRapFirmware 3.01 and later, if the line begins with a recognised keyword
(optionally preceded by N and a line number, and/or space or tab characters) then
that whole line of GCode is interpreted as a meta-command. Recognised keywords
are:
A line that does not start with one of these keywords must start with command
letter G, M or T or be empty apart from white space and comments. Exception:
when in CNC or Laser mode, if a line does not start with a G, M or T command but
nevertheless has other fields, and the previous line that included a command was a
G0, G1, G2 or G3 command, then the previous command will be repeated with
values from the new fields. This is to support GCode generated for CNC machines.
Important: a command that invokes a macro file must be the last command in that
line of GCode, because any following commands on the same line will not be
executed.
Buffering
"0:/ is root of the on board SD card in stand alone mode, or equivalent folder in
SBC mode (/opt/dsf/sd/)
Long file names (e.g. longer than 8.3 format) are supported, file names with spaces
are supported.
Full paths, including all directories and subdirectories are limited to 120 characters.
e.g.:
0:/gcodes/0123456789/012.gcode
counts as 30 characters
Live editing
As a general rule, any G or M command can be sent at any time. This means all
settings can be changed 'on the fly', i.e. while printing. This does not take into
account logical considerations, or individual pre-requisites for individual
commands. For example, sending new values for M566 'jerk', M201 'acceleration',
or M203 'max speed' while printing is a great way to tune these values. However,
while it is theoretically possible to change M563 'define a tool' while printing, it's
probably not a good idea.
G-commands
G0 & G1: Move
G0: Rapid move
G4: Dwell
G10: (XYZUVWABC and L parameters) Sets tool offset or coordinate system origin
(absolute or relative current position) for specific tool
G10: Retract
G10: (no parameters) Retracts filament then performs any zlift/hop according to
settings of M207
G11: Unretract
G17: Sets XY as the active plane for interpreting the tool path of an arc (G2 or G3)
G18: Select XZ plane for arc moves
G18: Sets XZ as the active plane for interpreting the tool path of an arc (G2 or G3)
G19: Sets YZ as the active plane for interpreting the tool path of an arc (G2 or G3)
G28: Home
G28: Move all axes, or the specified ones, to establish a known position for them,
for example by moving an axis motor until an endstop switch is triggered
G29: Uses a Z probe to measure the bed height at 4 or more points to determine
its tilt and overall flatness, then enables mesh compensation so that the nozzle will
remain parallel to the bed
G38.4: Probe away from workpiece, stop on loss of contact, signal error if failure
G68: Rotates the coordinate system in the current plane as selected by G17, G18 or
G19.
G90: All coordinates from this command onwards are absolute, relative to the
origin of the machine
G91: All coordinates from this command onwards are relative to the last position.
G92: Sets position of axes by manually specifying values for the axis positions
M-commands
M0: Stop or Unconditional stop
M0: After finishing any moves left in buffer, runs either cancel.g or stop.g, then sets
motors to idle and turns heaters off (unless specified not to)
M1: After finishing any moves left in buffer, runs either cancel.g or sleep.g, then
turns off all motors and heaters
M3: In CNC mode turns on spindle clockwise, in Laser mode turns on laser power
M5: In CNC mode turns off spindle, in Laser mode turns off laser power
M17: Enables all stepper motors when used without parameters, or use axes
parameters to enable selectively
M18: Disables all stepper motors when used without parameters, or use axes
parameters to enable selectively
M20: Lists files on the SD card. Use parameters to list files in subdirectories or on
secondary SD card
M24: The machine prints from the file selected with the M23 command. If the print
was previously paused with M25, printing is resumed from that point.
M25: The machine pauses printing at the current position within the file.
M26: Set the file offset in bytes from the start of the SD card file selected by M23.
M27: Reports the number of bytes processed in the format bytes processed / bytes
total in file
M28: The specified file is created (or overwritten if it exists) on the SD card and all
subsequent commands sent to the machine are written to that file.
M29: Stop writing to SD card
M29: File opened by M28 command is closed, and all subsequent commands sent
to the machine are executed as normal.
M32: The specified file is selected from the SD card and starts printing. Does the
same as M23 and M24.
M36: Returns information for the specified SD card file in JSON format.
M36.1: Returns the data for a thumbnail image in a GCode file in JSON format.
M37: Enters/leaves simulation mode, or runs the specified file in simulation mode
allows the electronics to compute an accurate printing time, taking into account
the maximum speeds, accelerations etc. that are configured.
M38: Used to compute a hash of a file on the SD card and returns a hexadecimal
string which is the SHA1 of the file.
M39: Returns information about the SD card in the specified slot in the requested
format.
M42: Switch I/O pin
M73: Generated by some slicers to inform the firmware about the state of the print
so that it can provide a better estimate of the remaining print time.
M80: Turns on the ATX power supply from standby mode to fully operational mode
using the power supply control pin on the External 5V header.
M84: Stop the stepper motor idle hold on all axes and extruder.
M99: Returns from an M98 call. This is not required to return from the end of a
macro and the macro naturally returns at the end of file.
M104: Sets the active and standby temperature of the current or specified tool to
the temperature specified, and returns control to the host immediately (i.e. before
that temperature has been reached by the extruder).
M105: Reports the current and target temperatures of all active heaters.
M106: Fan On
M109: Sets extruder temperature and waits until within 2.5°C of target.
M110: Sets the current line number in the running Gcode file.
M111: Enables or disables debugging features, for the module number specified by
the P parameter.
M112: Any moves in progress are immediately terminated, then RepRap shuts
down. All motors and heaters are turned off. It can be started again by pressing the
reset button or power cycling the board.
M116: Wait
M116: waits for all temperatures, or a specified tool or heater's temperature, and
other slowly-changing variables to arrive at their set values.
M117: Causes the given message to be shown in the status line on an attached LCD
or if no LCD is attached, this message will be reported on the web interface.
M120: Push
M120: Push the state of the machine onto a stack. Called automatically when a
macro file is run.
M121: Pop
M122: Diagnose
M135: Deprecated. Sets the PID to measure temperatures and calculate the power
to send to the heaters
M141: Configures heaters as chamber heaters and sets active and standby
temperatures, turns heaters on and returns control to the host immediately.
M150: Sets RGB colours and brightness for Dotstar and NeoPixel LEDs.
M190: Sets the temperature of the bed and waits for the temperature to be
reached.
M191: Set the temperature of the build chamber and waits for the temperature to
be reached.
M200: Enables or disables volumetric extrusion per extruder, and sets the filament
diameter.
M201.1: Set the acceleration that axes should use for special types of move that
should be done using reduced acceleration, eg probing and stall homing.
M204: Sets the maximum acceleration for printing and/or travel moves as a whole.
M205: Sets the maximum allowable speed change (sometimes called 'jerk speed')
of each motor when changing direction, in mm/sec.
M206: Deprecated. The specified values will be subtracted from the coordinates
given in G0, G1 and related commands.
M207: Sets the retract length used by the G10 and G11 firmware retraction and
reprime commands.
M208: The specified values set the software limits for axis travel in the specified
direction. The axis limits are also the positions assumed when an endstop is
triggered.
M221: Sets extrude factor override percentage for the specified extruder.
M226: Initiates a pause in the same way as if the pause button is pressed, except
that execution of all prior GCode commands in the same input stream is completed
first.
M290: Applies the specified additional offset to the Z coordinate for all future
moves, and to apply the offset to moves that have already been queued if this can
be done.
M300: Play beep sound via connected LCD, or if no LCD, via web interface.
M301: Sets Proportional (P), Integral (I) and Derivative (D) values for hot end.
M303: This command computes the process model parameters (see M307), which
are in turn used to calculate the PID constants.
M305: Sets or reports the parameters for each temperature sensor. If using RRF 3,
use M308 instead.
M307: Sets or reports the parameters for the heating process model, for each
heater.
M309: Sets or reports the feedforward PWM setting for a specified tool. Supported
in RepRapFirmware v3.4 and later
M350: Sets or reports the microstepping mode for each defined axis.
M374: Saves the mesh grid parameters and height map into the specified file, or
the default file heightmap.csv if no filename was specified.
M375: Loads the default grid (without parameters), or grid specified by filename.
Equivalent to G29 S1.
M376: When using bed mesh compensation, specifies the height over which bed
compensation tapers. Full bed compensation is applied at Z=0, tapering down to
no bed compensation by the specified height.
M400: Finishes all current moves and and thus clears the buffer. Same as G4 P0.
M401: Runs macro file sys/deployprobe#.g (where # is the specified probe number)
if it exists, otherwise sys/deployprobe.g if it exists.
M402: Retract z-probe
M402: Runs macro file sys/retractprobe#.g (where # is the specified probe number)
if it exists, otherwise sys/retractprobe.g if it exists.
M404: Sets filament width and nozzle diameter. Used for slicers that report filament
volume, from which RRF calculates length for job status reporting.
M450: Report mode the machine is running; FFF (ie 3D printer), Laser or CNC.
M486: Used to identify objects on the print bed and selectively cancel them if
necessary.
M502: Sets all machine parameters to the values defined in config.g, ignoring the
config-override.g file so that any changes that were saved by M500 are not applied.
M505: Following this command, files that would normally be fetched from /sys/ (for
example, homing files and system macro files in RepRapFirmware) are fetched from
the specified folder instead. This command can be used to allow multiple
configurations to be maintained easily.
M540: Set MAC address
M540: Sets the MAC address of the machine, creating a unique identifier for the
Duet on the network.
M550: Sets the name of the machine. Also used for mDNS local network discovery.
M552: Sets the IP address of the machine and enables/disables network access.
M555: Sets the firmware to a mode where its input and (especially) output behaves
similar to other established firmware.
M556: This tells firmware the tangents of the angles between the axes of the
machine. Obtained by printing then measuring a test part.
M557: Defines the grid used by G29 to create a bed height mesh.
M558: Set Z probe type
M559: Upload file, with parameters for file size and CRC-32 check. Was used in RRF
3.1 and earlier to upload files to /sys.
M560: Upload file, as M559, with terminating string. Was used in RRF 3.1 and
earlier to upload files to /www.
M561: Cancels any bed-plane fitting as the result of probing (or anything else) and
returns the machine to moving in the user's coordinate system.
M562: If the heater has switched off and locked because it has detected a fault, this
will reset the fault condition and allow you to use the heater again.
M564: Allows or forbids movement of axes that have not been homed and/or limits
movement to within axis boundaries.
M566: Sets the maximum allowable speed change (sometimes called 'jerk speed')
of each motor when changing direction.
M567: Set tool mix ratios
M567: Sets the mix ratio for a tool. When a move command contains a single E
value but the current tool uses multiple extruders, each extruder will extrude the
amount specified in the E parameter times the mix value for that tool.
M568: Set tool parameters to values specified. Active and standby temperatures,
spindle RPM and heater state.
M569: Set motor driver direction, enable polarity, mode and step pulse timing
M569: Sets stepper driver parameters to values specified. Parameters include motor
direction, enable, minimum step pulse width, interval, direction setup and hold
time, and other stepper driver features.
M569.1: Set the configuration parameters of a closed loop driver. Supported for
drivers attached to Duet 3 Expansion 1HCL board.
M569.2: Reads the specified register and returns the value of that register, or if a
value is specified, that value is written to the specified register.
M569.3: Report a current motors encoder position to the host in units of arc
degrees (1/360'ths of turns), relative to set reference position.
M569.4: Tell one or more motor drivers to apply a specified torque regardless of
position.
M569.5: Closed loop data collection
M569.5: Collect performance data from a drive whilst in closed loop mode.
M570: Sets time and temperature parameters for the detection of heater
anomalies.
M571: Turns on the defined output pin whenever extrusion is being done, and
turns it off when the extrusion is finished.
M572: Sets the pressure advance coefficient for the specified extruder.
M573: Gives a running average (usually taken over about five seconds) of the PWM
to the specified heater.
M574: Defines the pin name, position and type of endstop or sensor that the
machine has for an axis.
M578: Fires specified inkjet head using the specified bit pattern. Not enabled in
firmware by default.
M579: Scales the specified axes by the given amount, to get prints exactly the right
size.
M584: Assigns stepper driver numbers to axes, and defines axes as linear or
rotational.
M585: Probe Tool
M585: Allows the current tool's offset to be updated by driving it into a given
endstop, on machines with at least one tool probe.
M586: Enables/disables network protocols (HTTP, HTTPS, FTP, Telnet, SSH) and
configures parameters.
M587: Adds WiFi network SSID and password to the remembered networks list.
Optionally sets IP address, gateway, netmask, DNS server and country code.
M588: Removes the specified network SSID from the remembered networks list.
M589: Configures the Duet to allow WiFi devices to connect directly, as an access
point. Settings for SSID, password, IP address and optionally the WiFi channel.
M591: Configures filament sensing for the specified extruder. The sensor may be a
simple filament presence detector, a device that measures movement of filament,
or both.
M592: Nonlinear extrusion is a feature that compensates for the increased back
pressure from the hot end as extrusion speed increases.
M594: Height following mode allows the Z position of the tool to be controlled by
a PID controller using feedback from a sensor. See also M951.
M595: Allows the movement queue parameters to be adjusted so that the queue
can be lengthened if necessary, or kept short if a long movement queue is not
needed and there are other demands on RAM.
M600: Behaves like M226 except that if macro file filament-change.g exists in /sys
on the SD card, it is run in preference to pause.g.
M665: Set the delta calibration variables, including diagonal rod length, delta
radius, printing radius, homed nozzle height and tower postion correction.
M669: Sets kinematic type (cartesian, CoreXY, CoreXZ, Delta, SCARA, Hangprinter,
polar etc) and any extra kinematic parameters.
M670: Sets the port switching time advance for the specified pins.
M673: Aligns a plane that is mounted on a rotary axis. To make use of this code it is
required to take two probe points via G30 P first.
M674: Determines the Z center point of a stash that is mounted on a rotary axis.
This code is yet to be implemented.
M675: Finds the center of a cavity that can be measured using the configured axis
endstop.
M701: Load filament
M702: Unloads the previously loaded filament from the current tool.
M703: After assigning a filament to a tool, this command may be used to run
/filaments/<filament name>/config.g to set parameters like temperatures,
extrusion factor, retract distance.
M851: Implemented for backwards compatibility with other firmware. It sets the Z
probe trigger in the same way as G31 Z-nn (note the sign reversal).
M905: Updates the machine's local date and time or reports them if no parameters
are specified.
M906: Sets the peak currents to send to the stepper motors for each axis.
M911: When the supply voltage falls below the auto save threshold while a print
from SD card is in progress, all heaters will be turned off, printing will be stopped
immediately (probably in the middle of a move), the position saved, and the
specified command string executed.
M912: Adjusts the temperature reading offset of the MCU's on-chip temperature
sensor.
M915: Sets the stall detection parameters and optionally the low-load current
reduction parameters for TMC2660, TMC2130 or similar driver chips.
M916: If the last print was not completed and resume information has been saved
(either because the print was paused or because of a power failure), then the
heater temperatures, tool selection, head position, mix ratio, mesh bed
compensation height map etc. are restored from the saved values and printing is
resumed.
M917: Sets the percentage of the current set by M906 that is to be used when the
motor is stationary but not idle, or moving very slowly.
M929: When event logging is enabled, important events such as power up,
start/finish printing and (if possible) power down will be logged to the SD card.
M950: Used to create heaters, fans, spindles and GPIO ports, and to configure
parameters.
M951: Height following mode allows the Z position of the tool to be controlled by
a PID controller using feedback from a sensor. See also M594.
M952: Set CAN-FD expansion board address and/or normal data rate
M952: Expansion boards without address selection switches use a default address.
This command can change the address, and the default data rate.
M953: Allows the bandwidth of the CAN bus to be optimised, by increasing the
data rate during transmission of CAN-FD data packets by means of the BRS (bit
rate switch) feature.
M957: Raises an event internally, based on the given parameters, as if the event
had actually occurred, and executes any related handler macro for that event.
M997: Triggers a firmware update if the necessary files are present on the SD card.
Can update firmware on Duet mainboards, Duet 3 CAN-connected expansion
boards, WiFi modules and PanelDue.
M998: Request resend of line
M999: Restart
M999: Restarts the firmware using a software reset. Can also reboot attached SBC.
T: Select Tool
Parameters
R1: Select the tool that was active when the print was last paused (firmware 1.20
and later)
Pnnn: Bitmap of all the macros to be run (dc42 build 1.19 or later and ch fork
1.17b or later)
Tool number
Example
T0 ; select tool 0
T1 P0 ; select tool 1 but don't run any tool change macro files
T-1 P0 ; deselect all tools but don't run any tool change macro files
T R1 ; select the tool that was active last time the print was paused
If Tn is used to select tool n but that tool is already active, the command does
nothing. Otherwise, the sequence followed is:
Note: Prior to RRF 3.3, when changing tools, tool change macro files are not run
unless all axes have been homed. In RRF 3.3 and later, tool change macro files are
now run regardless of whether axes have been homed or not. You can use
conditional GCode to choose which commands are executed if axes have been
homed/not homed.
1. If another tool is already selected, run macro tfree#.g where # is the number of
that tool.
2. If another tool is already selected, deselect it and set its heaters to their standby
temperatures (as defined by the R parameter in the most recent G10/M568
command for that tool)
4. Set the new tool to its operating temperatures specified by the S parameter in
the most recent G10/M568 command for that tool
5. Run macro tpost#.g where # is the number of the new tool. Typically this file
would contain at least a M116 command to wait for its temperatures to
stabilise.
Selecting a non-existent tool (49, say) just does Steps 1-2 above1. That is to say it
leaves the previous tool in its standby state. You can, of course, use the G10/M568
command beforehand to set that standby temperature to anything you like.
After a reset tools will not start heating until they are selected. You can either put
them all at their standby temperature by selecting them in turn, or leave them off
so they only come on if/when you first use them. The M0, M1 and M112
commands turn them all off. You can, of course, turn them all off with the M1
command, then turn some back on again. Don't forget also to turn on the heated
bed (if any) if you use that trick.
Tool numbering starts at 0 by default however M563 allows the user to specify tool
numbers, so with them you can have tools 17, 29 and 48 if you want. Negative
numbers are not allowed. The highest Tool number that can be defined from RRF3
onwards is 49
Starting from RRF 3.3beta2 both selecting as well as deselecting with a configured
spindle will stop the spindle assigned to these tools. This is in accordance to NIST
GCode standard that says "after a tool change is complete the spindle is stopped".
Notes
1
Selecting a non-existent tool also removes any X/Y/Z offset applied for the old
tool.
2
Under special circumstances, the execution of those macro files may not be
desired. RepRapFirmware 1.19 or later supports an optional P parameter to specify
which macros shall be run. If it is absent then all of the macros above will be run,
else you can pass a bitmap of all the macros to be executed. The bitmap of this
value consists of tfree=1, tpre=2 and tpost=4.
3
You may wish to include a move to a parking position 'within the tfreeN.g gcode
macro in order to allow the new extruder to reach temperature while not in contact
with the print.
4
Tool offsets are applied whenever there is a current tool. So they are applied in
tfree.g (for the outgoing tool) and in tpost.g (for the incoming tool), but not in
tpre.g (because no tool is current at that point).
For more information and background, along with the master list of all RepRap G-
Codes check the http://reprap.org/wiki/G-code.
For the technically minded, G-Code line endings are Unix Line Endings (\n), but will
accept Windows Line Endings (\r\n), so you should not need to worry about
converting between the two, but it is best practice to use Unix Line Endings where
possible.
to the host computer are terminated by a newline and look like this:
xx [line number to resend] [T:93.2 B:22.9] [C: X:9.2 Y:125.4 Z:3.7 E:1902.5]
[Some debugging or other information may be here]
ok
rs
!!
!! means that a hardware fault has been detected. The RepRap machine will
and the bed respectively, and are only sent in response to M105. If such
temperatures don't exist (for example for an extruder that works at room
temperature and doesn't have a sensor) then a value below absolute zero (-273oC)
is returned.
C: means that coordinates follow. Those are the X: Y: etc values. These are only
The RepRap machine may also send lines that look like this:
// action:command
is allowed to be sent from the firmware, the command can currently be pause,
resume or disconnect which will execute those commands on the host.
As this is also a comment other hosts will just ignore these commands.
ok
start
once to the host before sending anything else. This should not be replaced or
augmented
by version numbers and the like. M115 (see above) requests those.
All this means that every line sent by RepRap to the host computer except the start
line has a two-character prefix (one of ok, rs, !! or //). The machine should never
send a line without such a prefix.
Exceptions:
M20 S2
M36
M408
Slicers will optionally add G-Code scripts to the beginning and end of their output
file to perform specified actions before and/or after a print such as z-probing the
build-area, heating/cooling the bed and hotend, performing ooze free "nozzle
wipe" startup routine, switching system power on/off, and even "ejecting" parts. For
general information and examples (not specific to RepRapFirmware) there is more
info on
the https://reprap.org/wiki/Start_GCode_rout... and https://reprap.org/wiki/End_GC
ode_routin... pages.