Adding custom M Codes to Marlin doesn't work for Marlin 2.0

How would one go about adding custom G codes or M Codes to Marlin 2.0? The Marlin_main.cpp file does not exist.

In general for Marlin 2.0, things are organized better, but split into more files.


The code in 2.0.x is similar to the old branch 1.1.x, G-code is parsed in gcode.cpp, specifically in process_parsed_command:

void GcodeSuite::process_parsed_command(const bool no_ok/*=false*/)

In the case statement the codes read from the G-code files are parsed (interpreted) and the appropriate method is called (e.g. G28() calls void GcodeSuite::G28())

If you want to create your own codes, it could be an idea to start there. Also think of using a different letter and/or codes in the 10,000 range so that it will not collide with new implemented G-codes.

  1. Choose a code in the >10,000 in case new codes are added. But in this example I will choose 13
  2. Navigate to 'src' folder of Marlin
  3. Edit the file gcode.cpp around line 223 to have a new unused number. For example, this will create a new G code function for the label G13.
  // Handle a known G, M, or T
  switch (parser.command_letter) {
    case 'G': switch (parser.codenum) {
      case 13: G13(); break;
      case 0: case 1: G0_G1(  
  1. On line 375 of gcode.h add: static void G13(); to declare it.

  2. In my case i was reading values from an analog system. So I went to src/temperatures and copied M105.cpp to be G13.cpp. Then inside the file I replaced GcodeSuite::M105 to be GcodeSuite::G13. I am using this to take in the weight of something using a [scale][1] but for now I just want to test functionality so here is my test function:

void GcodeSuite::G13() {

  SERIAL_ECHOLNPGM("here is where weights are broadcast");


And again this is the only part I changed in my new copy of M105.cpp (a new file named G13.cpp). There is still more stuff in the file than just these few lines.

  1. Upload to board

  2. When going to octoprint and typing in G13 I get:

Send: G13
Recv: okhere is where weights are broadcast

A bit more work can be done to make it look nice, but this was the hard part. [1]: https://www.instructables.com/id/Arduino-Bathroom-Scale-With-50-Kg-Load-Cells-and-H/


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.