<p>In the file <code>Marlin_main.cpp</code> on line 7131 there is a switch case:</p>

<p>(To turn on line numbers go to <code>File&gt;Preferences</code> and click Display line numbers.)</p>

<pre><code>case 'M': switch (codenum) {
  #if ENABLED(ULTIPANEL)
    case 0: // M0 - Unconditional stop - Wait for user button press on LCD
    case 1: // M1 - Conditional stop - Wait for user button press on LCD
      gcode_M0_M1();
      break;
  #endif // ULTIPANEL

  case 17:
    gcode_M17();
    break;
  etc.....
</code></pre>

<p>Adding another case with an unused number such as 5 and then the code you want followed by a break should do the trick. Ex:</p>

<pre><code>case 5:
   doABunchofCoolStuff();
   myservo.write(thebestposition);
   break;
</code></pre>

<p>-AC</p>

CC BY-SA 3.0
2017-02-14T05:17:14.520Z
2017-02-14T05:17:14.520Z
Airfield20
<p>If I wanted to add my own custom M Codes in Marlin - in which source code file would I do that? </p>

CC BY-SA 4.0
2020-05-19T17:24:29.493Z
This answer is relevant for Marlin 1.x, but not for Marlin 2.x
K Mmmm
<marlin>
Adding custom M Codes to Marlin
Mtl Dev
# Adding custom M Codes to Marlin

(Asked by: username_0 on 2017-02-13)

If I wanted to add my own custom M Codes in Marlin - in which source code file would I do that?

**Tags:** marlin
> **Comments:**
> **username_1**: This answer is relevant for Marlin 1.x, but not for Marlin 2.x  

---

## 1 answers

### Answer by username_2 on 2017-02-14. Score: 4 | Accepted answer

In the file Marlin_main.cpp on line 7131 there is a switch case:
(To turn on line numbers go to File>Preferences and click Display line numbers.)
case 'M': switch (codenum) {
  #if ENABLED(ULTIPANEL)
    case 0: // M0 - Unconditional stop - Wait for user button press on LCD
    case 1: // M1 - Conditional stop - Wait for user button press on LCD
      gcode_M0_M1();
      break;
  #endif // ULTIPANEL

  case 17:
    gcode_M17();
    break;
  etc.....

Adding another case with an unused number such as 5 and then the code you want followed by a break should do the trick. Ex:
case 5:
   doABunchofCoolStuff();
   myservo.write(thebestposition);
   break;

-AC


---

