chiark / gitweb /
delete obsolete and wrong code
[marlin.git] / Marlin / Marlin.pde
1 /*
2     Reprap firmware based on Sprinter and grbl.
3  Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
4  
5  This program is free software: you can redistribute it and/or modify
6  it under the terms of the GNU General Public License as published by
7  the Free Software Foundation, either version 3 of the License, or
8  (at your option) any later version.
9  
10  This program is distributed in the hope that it will be useful,
11  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  GNU General Public License for more details.
14  
15  You should have received a copy of the GNU General Public License
16  along with this program.  If not, see <http://www.gnu.org/licenses/>.
17  */
18
19 /*
20  This firmware is a mashup between Sprinter and grbl.
21   (https://github.com/kliment/Sprinter)
22   (https://github.com/simen/grbl/tree)
23  
24  It has preliminary support for Matthew Roberts advance algorithm 
25     http://reprap.org/pipermail/reprap-dev/2011-May/003323.html
26  */
27
28 #include "Marlin.h"
29
30 #include "ultralcd.h"
31 #include "planner.h"
32 #include "stepper.h"
33 #include "temperature.h"
34 #include "motion_control.h"
35 #include "cardreader.h"
36 #include "watchdog.h"
37 #include "EEPROMwrite.h"
38 #include "language.h"
39 #include "pins_arduino.h"
40
41 #define VERSION_STRING  "1.0.0 RC2"
42
43 // look here for descriptions of gcodes: http://linuxcnc.org/handbook/gcode/g-code.html
44 // http://objects.reprap.org/wiki/Mendel_User_Manual:_RepRapGCodes
45
46 //Implemented Codes
47 //-------------------
48 // G0  -> G1
49 // G1  - Coordinated Movement X Y Z E
50 // G2  - CW ARC
51 // G3  - CCW ARC
52 // G4  - Dwell S<seconds> or P<milliseconds>
53 // G28 - Home all Axis
54 // G90 - Use Absolute Coordinates
55 // G91 - Use Relative Coordinates
56 // G92 - Set current position to cordinates given
57
58 //RepRap M Codes
59 // M104 - Set extruder target temp
60 // M105 - Read current temp
61 // M106 - Fan on
62 // M107 - Fan off
63 // M109 - Wait for extruder current temp to reach target temp.
64 // M114 - Display current position
65
66 //Custom M Codes
67 // M17  - Enable/Power all stepper motors
68 // M18  - Disable all stepper motors; same as M84
69 // M20  - List SD card
70 // M21  - Init SD card
71 // M22  - Release SD card
72 // M23  - Select SD file (M23 filename.g)
73 // M24  - Start/resume SD print
74 // M25  - Pause SD print
75 // M26  - Set SD position in bytes (M26 S12345)
76 // M27  - Report SD print status
77 // M28  - Start SD write (M28 filename.g)
78 // M29  - Stop SD write
79 // M30  - Delete file from SD (M30 filename.g)
80 // M31  - Output time since last M109 or SD card start to serial
81 // M42  - Change pin status via gcode
82 // M80  - Turn on Power Supply
83 // M81  - Turn off Power Supply
84 // M82  - Set E codes absolute (default)
85 // M83  - Set E codes relative while in Absolute Coordinates (G90) mode
86 // M84  - Disable steppers until next move, 
87 //        or use S<seconds> to specify an inactivity timeout, after which the steppers will be disabled.  S0 to disable the timeout.
88 // M85  - Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
89 // M92  - Set axis_steps_per_unit - same syntax as G92
90 // M114 - Output current position to serial port 
91 // M115 - Capabilities string
92 // M117 - display message
93 // M119 - Output Endstop status to serial port
94 // M140 - Set bed target temp
95 // M190 - Wait for bed current temp to reach target temp.
96 // M200 - Set filament diameter
97 // M201 - Set max acceleration in units/s^2 for print moves (M201 X1000 Y1000)
98 // M202 - Set max acceleration in units/s^2 for travel moves (M202 X1000 Y1000) Unused in Marlin!!
99 // M203 - Set maximum feedrate that your machine can sustain (M203 X200 Y200 Z300 E10000) in mm/sec
100 // M204 - Set default acceleration: S normal moves T filament only moves (M204 S3000 T7000) im mm/sec^2  also sets minimum segment time in ms (B20000) to prevent buffer underruns and M20 minimum feedrate
101 // M205 -  advanced settings:  minimum travel speed S=while printing T=travel only,  B=minimum segment time X= maximum xy jerk, Z=maximum Z jerk, E=maximum E jerk
102 // M206 - set additional homeing offset
103 // M220 S<factor in percent>- set speed factor override percentage
104 // M221 S<factor in percent>- set extrude factor override percentage
105 // M240 - Trigger a camera to take a photograph
106 // M301 - Set PID parameters P I and D
107 // M302 - Allow cold extrudes
108 // M303 - PID relay autotune S<temperature> sets the target temperature. (default target temperature = 150C)
109 // M400 - Finish all moves
110 // M500 - stores paramters in EEPROM
111 // M501 - reads parameters from EEPROM (if you need reset them after you changed them temporarily).  
112 // M502 - reverts to the default "factory settings".  You still need to store them in EEPROM afterwards if you want to.
113 // M503 - print the current settings (from memory not from eeprom)
114 // M999 - Restart after being stopped by error
115
116 //Stepper Movement Variables
117
118 //===========================================================================
119 //=============================imported variables============================
120 //===========================================================================
121
122
123 //===========================================================================
124 //=============================public variables=============================
125 //===========================================================================
126 #ifdef SDSUPPORT
127 CardReader card;
128 #endif
129 float homing_feedrate[] = HOMING_FEEDRATE;
130 bool axis_relative_modes[] = AXIS_RELATIVE_MODES;
131 volatile int feedmultiply=100; //100->1 200->2
132 int saved_feedmultiply;
133 volatile bool feedmultiplychanged=false;
134 volatile int extrudemultiply=100; //100->1 200->2
135 float current_position[NUM_AXIS] = { 0.0, 0.0, 0.0, 0.0 };
136 float add_homeing[3]={0,0,0};
137 uint8_t active_extruder = 0;
138 unsigned char FanSpeed=0;
139
140
141 //===========================================================================
142 //=============================private variables=============================
143 //===========================================================================
144 const char axis_codes[NUM_AXIS] = {'X', 'Y', 'Z', 'E'};
145 static float destination[NUM_AXIS] = {  0.0, 0.0, 0.0, 0.0};
146 static float offset[3] = {0.0, 0.0, 0.0};
147 static bool home_all_axis = true;
148 static float feedrate = 1500.0, next_feedrate, saved_feedrate;
149 static long gcode_N, gcode_LastN, Stopped_gcode_LastN = 0;
150
151 static bool relative_mode = false;  //Determines Absolute or Relative Coordinates
152 static bool relative_mode_e = false;  //Determines Absolute or Relative E Codes while in Absolute Coordinates mode. E is always relative in Relative Coordinates mode.
153
154 static char cmdbuffer[BUFSIZE][MAX_CMD_SIZE];
155 static bool fromsd[BUFSIZE];
156 static int bufindr = 0;
157 static int bufindw = 0;
158 static int buflen = 0;
159 //static int i = 0;
160 static char serial_char;
161 static int serial_count = 0;
162 static boolean comment_mode = false;
163 static char *strchr_pointer; // just a pointer to find chars in the cmd string like X, Y, Z, E, etc
164
165 const int sensitive_pins[] = SENSITIVE_PINS; // Sensitive pin list for M42
166
167 //static float tt = 0;
168 //static float bt = 0;
169
170 //Inactivity shutdown variables
171 static unsigned long previous_millis_cmd = 0;
172 static unsigned long max_inactive_time = 0;
173 static unsigned long stepper_inactive_time = DEFAULT_STEPPER_DEACTIVE_TIME*1000l;
174
175 static unsigned long starttime=0;
176 static unsigned long stoptime=0;
177
178 static uint8_t tmp_extruder;
179
180 bool Stopped=false;
181
182 //===========================================================================
183 //=============================ROUTINES=============================
184 //===========================================================================
185
186 void get_arc_coordinates();
187
188 extern "C"{
189   extern unsigned int __bss_end;
190   extern unsigned int __heap_start;
191   extern void *__brkval;
192
193   int freeMemory() {
194     int free_memory;
195
196     if((int)__brkval == 0)
197       free_memory = ((int)&free_memory) - ((int)&__bss_end);
198     else
199       free_memory = ((int)&free_memory) - ((int)__brkval);
200
201     return free_memory;
202   }
203 }
204
205 //adds an command to the main command buffer
206 //thats really done in a non-safe way.
207 //needs overworking someday
208 void enquecommand(const char *cmd)
209 {
210   if(buflen < BUFSIZE)
211   {
212     //this is dangerous if a mixing of serial and this happsens
213     strcpy(&(cmdbuffer[bufindw][0]),cmd);
214     SERIAL_ECHO_START;
215     SERIAL_ECHOPGM("enqueing \"");
216     SERIAL_ECHO(cmdbuffer[bufindw]);
217     SERIAL_ECHOLNPGM("\"");
218     bufindw= (bufindw + 1)%BUFSIZE;
219     buflen += 1;
220   }
221 }
222
223 void setup_photpin()
224 {
225   #ifdef PHOTOGRAPH_PIN
226     #if (PHOTOGRAPH_PIN > -1)
227     SET_OUTPUT(PHOTOGRAPH_PIN);
228     WRITE(PHOTOGRAPH_PIN, LOW);
229     #endif
230   #endif 
231 }
232
233 void setup_powerhold()
234 {
235  #ifdef SUICIDE_PIN
236    #if (SUICIDE_PIN> -1)
237       SET_OUTPUT(SUICIDE_PIN);
238       WRITE(SUICIDE_PIN, HIGH);
239    #endif
240  #endif
241 }
242
243 void suicide()
244 {
245  #ifdef SUICIDE_PIN
246     #if (SUICIDE_PIN> -1) 
247       SET_OUTPUT(SUICIDE_PIN);
248       WRITE(SUICIDE_PIN, LOW);
249     #endif
250   #endif
251 }
252
253 void setup()
254
255   setup_powerhold();
256   MYSERIAL.begin(BAUDRATE);
257   SERIAL_PROTOCOLLNPGM("start");
258   SERIAL_ECHO_START;
259
260   // Check startup - does nothing if bootloader sets MCUSR to 0
261   byte mcu = MCUSR;
262   if(mcu & 1) SERIAL_ECHOLNPGM(MSG_POWERUP);
263   if(mcu & 2) SERIAL_ECHOLNPGM(MSG_EXTERNAL_RESET);
264   if(mcu & 4) SERIAL_ECHOLNPGM(MSG_BROWNOUT_RESET);
265   if(mcu & 8) SERIAL_ECHOLNPGM(MSG_WATCHDOG_RESET);
266   if(mcu & 32) SERIAL_ECHOLNPGM(MSG_SOFTWARE_RESET);
267   MCUSR=0;
268
269   SERIAL_ECHOPGM(MSG_MARLIN);
270   SERIAL_ECHOLNPGM(VERSION_STRING);
271   #ifdef STRING_VERSION_CONFIG_H
272     #ifdef STRING_CONFIG_H_AUTHOR
273       SERIAL_ECHO_START;
274       SERIAL_ECHOPGM(MSG_CONFIGURATION_VER);
275       SERIAL_ECHOPGM(STRING_VERSION_CONFIG_H);
276       SERIAL_ECHOPGM(MSG_AUTHOR);
277       SERIAL_ECHOLNPGM(STRING_CONFIG_H_AUTHOR);
278     #endif
279   #endif
280   SERIAL_ECHO_START;
281   SERIAL_ECHOPGM(MSG_FREE_MEMORY);
282   SERIAL_ECHO(freeMemory());
283   SERIAL_ECHOPGM(MSG_PLANNER_BUFFER_BYTES);
284   SERIAL_ECHOLN((int)sizeof(block_t)*BLOCK_BUFFER_SIZE);
285   for(int8_t i = 0; i < BUFSIZE; i++)
286   {
287     fromsd[i] = false;
288   }
289   
290   EEPROM_RetrieveSettings(); // loads data from EEPROM if available
291
292   for(int8_t i=0; i < NUM_AXIS; i++)
293   {
294     axis_steps_per_sqr_second[i] = max_acceleration_units_per_sq_second[i] * axis_steps_per_unit[i];
295   }
296
297
298   tp_init();    // Initialize temperature loop 
299   plan_init();  // Initialize planner;
300   st_init();    // Initialize stepper;
301   wd_init();
302   setup_photpin();
303 }
304
305
306 void loop()
307 {
308   if(buflen < (BUFSIZE-1))
309     get_command();
310   #ifdef SDSUPPORT
311   card.checkautostart(false);
312   #endif
313   if(buflen)
314   {
315     #ifdef SDSUPPORT
316       if(card.saving)
317       {
318         if(strstr(cmdbuffer[bufindr],"M29") == NULL)
319         {
320           card.write_command(cmdbuffer[bufindr]);
321           SERIAL_PROTOCOLLNPGM(MSG_OK);
322         }
323         else
324         {
325           card.closefile();
326           SERIAL_PROTOCOLLNPGM(MSG_FILE_SAVED);
327         }
328       }
329       else
330       {
331         process_commands();
332       }
333     #else
334       process_commands();
335     #endif //SDSUPPORT
336     buflen = (buflen-1);
337     bufindr = (bufindr + 1)%BUFSIZE;
338   }
339   //check heater every n milliseconds
340   manage_heater();
341   manage_inactivity(1);
342   checkHitEndstops();
343   LCD_STATUS;
344 }
345
346 void get_command() 
347
348   while( MYSERIAL.available() > 0  && buflen < BUFSIZE) {
349     serial_char = MYSERIAL.read();
350     if(serial_char == '\n' || 
351        serial_char == '\r' || 
352        (serial_char == ':' && comment_mode == false) || 
353        serial_count >= (MAX_CMD_SIZE - 1) ) 
354     {
355       if(!serial_count) { //if empty line
356         comment_mode = false; //for new command
357         return;
358       }
359       cmdbuffer[bufindw][serial_count] = 0; //terminate string
360       if(!comment_mode){
361         comment_mode = false; //for new command
362         fromsd[bufindw] = false;
363         if(strstr(cmdbuffer[bufindw], "N") != NULL)
364         {
365           strchr_pointer = strchr(cmdbuffer[bufindw], 'N');
366           gcode_N = (strtol(&cmdbuffer[bufindw][strchr_pointer - cmdbuffer[bufindw] + 1], NULL, 10));
367           if(gcode_N != gcode_LastN+1 && (strstr(cmdbuffer[bufindw], "M110") == NULL) ) {
368             SERIAL_ERROR_START;
369             SERIAL_ERRORPGM(MSG_ERR_LINE_NO);
370             SERIAL_ERRORLN(gcode_LastN);
371             //Serial.println(gcode_N);
372             FlushSerialRequestResend();
373             serial_count = 0;
374             return;
375           }
376
377           if(strstr(cmdbuffer[bufindw], "*") != NULL)
378           {
379             byte checksum = 0;
380             byte count = 0;
381             while(cmdbuffer[bufindw][count] != '*') checksum = checksum^cmdbuffer[bufindw][count++];
382             strchr_pointer = strchr(cmdbuffer[bufindw], '*');
383
384             if( (int)(strtod(&cmdbuffer[bufindw][strchr_pointer - cmdbuffer[bufindw] + 1], NULL)) != checksum) {
385               SERIAL_ERROR_START;
386               SERIAL_ERRORPGM(MSG_ERR_CHECKSUM_MISMATCH);
387               SERIAL_ERRORLN(gcode_LastN);
388               FlushSerialRequestResend();
389               serial_count = 0;
390               return;
391             }
392             //if no errors, continue parsing
393           }
394           else 
395           {
396             SERIAL_ERROR_START;
397             SERIAL_ERRORPGM(MSG_ERR_NO_CHECKSUM);
398             SERIAL_ERRORLN(gcode_LastN);
399             FlushSerialRequestResend();
400             serial_count = 0;
401             return;
402           }
403
404           gcode_LastN = gcode_N;
405           //if no errors, continue parsing
406         }
407         else  // if we don't receive 'N' but still see '*'
408         {
409           if((strstr(cmdbuffer[bufindw], "*") != NULL))
410           {
411             SERIAL_ERROR_START;
412             SERIAL_ERRORPGM(MSG_ERR_NO_LINENUMBER_WITH_CHECKSUM);
413             SERIAL_ERRORLN(gcode_LastN);
414             serial_count = 0;
415             return;
416           }
417         }
418         if((strstr(cmdbuffer[bufindw], "G") != NULL)){
419           strchr_pointer = strchr(cmdbuffer[bufindw], 'G');
420           switch((int)((strtod(&cmdbuffer[bufindw][strchr_pointer - cmdbuffer[bufindw] + 1], NULL)))){
421           case 0:
422           case 1:
423           case 2:
424           case 3:
425             if(Stopped == false) { // If printer is stopped by an error the G[0-3] codes are ignored.
426               #ifdef SDSUPPORT
427               if(card.saving)
428                 break;
429               #endif //SDSUPPORT
430               SERIAL_PROTOCOLLNPGM(MSG_OK); 
431             }
432             else {
433               SERIAL_ERRORLNPGM(MSG_ERR_STOPPED);
434               LCD_MESSAGEPGM(MSG_STOPPED);
435             }
436             break;
437           default:
438             break;
439           }
440
441         }
442         bufindw = (bufindw + 1)%BUFSIZE;
443         buflen += 1;
444       }
445       serial_count = 0; //clear buffer
446     }
447     else
448     {
449       if(serial_char == ';') comment_mode = true;
450       if(!comment_mode) cmdbuffer[bufindw][serial_count++] = serial_char;
451     }
452   }
453   #ifdef SDSUPPORT
454   if(!card.sdprinting || serial_count!=0){
455     return;
456   }
457   while( !card.eof()  && buflen < BUFSIZE) {
458     int16_t n=card.get();
459     serial_char = (char)n;
460     if(serial_char == '\n' || 
461        serial_char == '\r' || 
462        (serial_char == ':' && comment_mode == false) || 
463        serial_count >= (MAX_CMD_SIZE - 1)||n==-1) 
464     {
465       if(card.eof()){
466         SERIAL_PROTOCOLLNPGM(MSG_FILE_PRINTED);
467         stoptime=millis();
468         char time[30];
469         unsigned long t=(stoptime-starttime)/1000;
470         int sec,min;
471         min=t/60;
472         sec=t%60;
473         sprintf(time,"%i min, %i sec",min,sec);
474         SERIAL_ECHO_START;
475         SERIAL_ECHOLN(time);
476         LCD_MESSAGE(time);
477         card.printingHasFinished();
478         card.checkautostart(true);
479         
480       }
481       if(!serial_count)
482       {
483         comment_mode = false; //for new command
484         return; //if empty line
485       }
486       cmdbuffer[bufindw][serial_count] = 0; //terminate string
487 //      if(!comment_mode){
488         fromsd[bufindw] = true;
489         buflen += 1;
490         bufindw = (bufindw + 1)%BUFSIZE;
491 //      }     
492       comment_mode = false; //for new command
493       serial_count = 0; //clear buffer
494     }
495     else
496     {
497       if(serial_char == ';') comment_mode = true;
498       if(!comment_mode) cmdbuffer[bufindw][serial_count++] = serial_char;
499     }
500   }
501   
502   #endif //SDSUPPORT
503
504 }
505
506
507 float code_value() 
508
509   return (strtod(&cmdbuffer[bufindr][strchr_pointer - cmdbuffer[bufindr] + 1], NULL)); 
510 }
511
512 long code_value_long() 
513
514   return (strtol(&cmdbuffer[bufindr][strchr_pointer - cmdbuffer[bufindr] + 1], NULL, 10)); 
515 }
516
517 bool code_seen(char code_string[]) //Return True if the string was found
518
519   return (strstr(cmdbuffer[bufindr], code_string) != NULL); 
520 }  
521
522 bool code_seen(char code)
523 {
524   strchr_pointer = strchr(cmdbuffer[bufindr], code);
525   return (strchr_pointer != NULL);  //Return True if a character was found
526 }
527
528 #define HOMEAXIS(LETTER) \
529   if ((LETTER##_MIN_PIN > -1 && LETTER##_HOME_DIR==-1) || (LETTER##_MAX_PIN > -1 && LETTER##_HOME_DIR==1))\
530     { \
531     current_position[LETTER##_AXIS] = 0; \
532     plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]); \
533     destination[LETTER##_AXIS] = 1.5 * LETTER##_MAX_LENGTH * LETTER##_HOME_DIR; \
534     feedrate = homing_feedrate[LETTER##_AXIS]; \
535     plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder); \
536     st_synchronize();\
537     \
538     current_position[LETTER##_AXIS] = 0;\
539     plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);\
540     destination[LETTER##_AXIS] = -LETTER##_HOME_RETRACT_MM * LETTER##_HOME_DIR;\
541     plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder); \
542     st_synchronize();\
543     \
544     destination[LETTER##_AXIS] = 2*LETTER##_HOME_RETRACT_MM * LETTER##_HOME_DIR;\
545     feedrate = homing_feedrate[LETTER##_AXIS]/2 ;  \
546     plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder); \
547     st_synchronize();\
548     \
549     current_position[LETTER##_AXIS] = (LETTER##_HOME_DIR == -1) ? LETTER##_HOME_POS : LETTER##_MAX_LENGTH;\
550     destination[LETTER##_AXIS] = current_position[LETTER##_AXIS];\
551     feedrate = 0.0;\
552     endstops_hit_on_purpose();\
553   }
554
555 void process_commands()
556 {
557   unsigned long codenum; //throw away variable
558   char *starpos = NULL;
559
560   if(code_seen('G'))
561   {
562     switch((int)code_value())
563     {
564     case 0: // G0 -> G1
565     case 1: // G1
566       if(Stopped == false) {
567         get_coordinates(); // For X Y Z E F
568         prepare_move();
569         //ClearToSend();
570         return;
571       }
572       //break;
573     case 2: // G2  - CW ARC
574       if(Stopped == false) {
575         get_arc_coordinates();
576         prepare_arc_move(true);
577         return;
578       }
579     case 3: // G3  - CCW ARC
580       if(Stopped == false) {
581         get_arc_coordinates();
582         prepare_arc_move(false);
583         return;
584       }
585     case 4: // G4 dwell
586       LCD_MESSAGEPGM(MSG_DWELL);
587       codenum = 0;
588       if(code_seen('P')) codenum = code_value(); // milliseconds to wait
589       if(code_seen('S')) codenum = code_value() * 1000; // seconds to wait
590       
591       st_synchronize();
592       codenum += millis();  // keep track of when we started waiting
593       previous_millis_cmd = millis();
594       while(millis()  < codenum ){
595         manage_heater();
596         manage_inactivity(1);
597       }
598       break;
599     case 28: //G28 Home all Axis one at a time
600       saved_feedrate = feedrate;
601       saved_feedmultiply = feedmultiply;
602       feedmultiply = 100;
603       previous_millis_cmd = millis();
604       
605       enable_endstops(true);
606       
607       for(int8_t i=0; i < NUM_AXIS; i++) {
608         destination[i] = current_position[i];
609       }
610       feedrate = 0.0;
611       home_all_axis = !((code_seen(axis_codes[0])) || (code_seen(axis_codes[1])) || (code_seen(axis_codes[2])));
612       #ifdef QUICK_HOME
613       if((home_all_axis)||( code_seen(axis_codes[X_AXIS]) && code_seen(axis_codes[Y_AXIS])) )  //first diagonal move
614       {
615         current_position[X_AXIS] = 0;current_position[Y_AXIS] = 0;  
616
617         plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]); 
618         destination[X_AXIS] = 1.5 * X_MAX_LENGTH * X_HOME_DIR;destination[Y_AXIS] = 1.5 * Y_MAX_LENGTH * Y_HOME_DIR;  
619         feedrate = homing_feedrate[X_AXIS]; 
620         if(homing_feedrate[Y_AXIS]<feedrate)
621           feedrate =homing_feedrate[Y_AXIS]; 
622         plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
623         st_synchronize();
624     
625         current_position[X_AXIS] = (X_HOME_DIR == -1) ? X_HOME_POS : X_MAX_LENGTH;
626         current_position[Y_AXIS] = (Y_HOME_DIR == -1) ? Y_HOME_POS : Y_MAX_LENGTH;
627         plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
628         destination[X_AXIS] = current_position[X_AXIS];
629         destination[Y_AXIS] = current_position[Y_AXIS];
630         plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
631         feedrate = 0.0;
632         st_synchronize();
633         endstops_hit_on_purpose();
634       }
635       #endif
636       
637       if((home_all_axis) || (code_seen(axis_codes[X_AXIS]))) 
638       {
639         HOMEAXIS(X);
640       }
641
642       if((home_all_axis) || (code_seen(axis_codes[Y_AXIS]))) {
643        HOMEAXIS(Y);
644       }
645       
646       if((home_all_axis) || (code_seen(axis_codes[Z_AXIS]))) {
647         HOMEAXIS(Z);
648       }
649       
650       if(code_seen(axis_codes[X_AXIS])) 
651       {
652         if(code_value_long() != 0) {
653           current_position[X_AXIS]=code_value()+add_homeing[0];
654         }
655       }
656
657       if(code_seen(axis_codes[Y_AXIS])) {
658         if(code_value_long() != 0) {
659           current_position[Y_AXIS]=code_value()+add_homeing[1];
660         }
661       }
662
663       if(code_seen(axis_codes[Z_AXIS])) {
664         if(code_value_long() != 0) {
665           current_position[Z_AXIS]=code_value()+add_homeing[2];
666         }
667       }
668       plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
669       
670       #ifdef ENDSTOPS_ONLY_FOR_HOMING
671         enable_endstops(false);
672       #endif
673       
674       feedrate = saved_feedrate;
675       feedmultiply = saved_feedmultiply;
676       previous_millis_cmd = millis();
677       endstops_hit_on_purpose();
678       break;
679     case 90: // G90
680       relative_mode = false;
681       break;
682     case 91: // G91
683       relative_mode = true;
684       break;
685     case 92: // G92
686       if(!code_seen(axis_codes[E_AXIS]))
687         st_synchronize();
688       for(int8_t i=0; i < NUM_AXIS; i++) {
689         if(code_seen(axis_codes[i])) { 
690            if(i == E_AXIS) {
691              current_position[i] = code_value();  
692              plan_set_e_position(current_position[E_AXIS]);
693            }
694            else {
695              current_position[i] = code_value()+add_homeing[i];  
696              plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
697            }
698         }
699       }
700       break;
701     }
702   }
703
704   else if(code_seen('M'))
705   {
706     switch( (int)code_value() ) 
707     {
708     case 17:
709         LCD_MESSAGEPGM(MSG_NO_MOVE);
710         enable_x(); 
711         enable_y(); 
712         enable_z(); 
713         enable_e0(); 
714         enable_e1(); 
715         enable_e2(); 
716       break;
717
718 #ifdef SDSUPPORT
719     case 20: // M20 - list SD card
720       SERIAL_PROTOCOLLNPGM(MSG_BEGIN_FILE_LIST);
721       card.ls();
722       SERIAL_PROTOCOLLNPGM(MSG_END_FILE_LIST);
723       break;
724     case 21: // M21 - init SD card
725       
726       card.initsd();
727       
728       break;
729     case 22: //M22 - release SD card
730       card.release();
731
732       break;
733     case 23: //M23 - Select file
734       starpos = (strchr(strchr_pointer + 4,'*'));
735       if(starpos!=NULL)
736         *(starpos-1)='\0';
737       card.openFile(strchr_pointer + 4,true);
738       break;
739     case 24: //M24 - Start SD print
740       card.startFileprint();
741       starttime=millis();
742       break;
743     case 25: //M25 - Pause SD print
744       card.pauseSDPrint();
745       break;
746     case 26: //M26 - Set SD index
747       if(card.cardOK && code_seen('S')) {
748         card.setIndex(code_value_long());
749       }
750       break;
751     case 27: //M27 - Get SD status
752       card.getStatus();
753       break;
754     case 28: //M28 - Start SD write
755       starpos = (strchr(strchr_pointer + 4,'*'));
756       if(starpos != NULL){
757         char* npos = strchr(cmdbuffer[bufindr], 'N');
758         strchr_pointer = strchr(npos,' ') + 1;
759         *(starpos-1) = '\0';
760       }
761       card.openFile(strchr_pointer+4,false);
762       break;
763     case 29: //M29 - Stop SD write
764       //processed in write to file routine above
765       //card,saving = false;
766       break;
767     case 30: //M30 <filename> Delete File 
768         if (card.cardOK){
769                 card.closefile();
770                 starpos = (strchr(strchr_pointer + 4,'*'));
771                 if(starpos != NULL){
772                 char* npos = strchr(cmdbuffer[bufindr], 'N');
773                 strchr_pointer = strchr(npos,' ') + 1;
774                 *(starpos-1) = '\0';
775          }
776          card.removeFile(strchr_pointer + 4);
777         }
778         break;
779         
780 #endif //SDSUPPORT
781
782     case 31: //M31 take time since the start of the SD print or an M109 command
783       {
784       stoptime=millis();
785       char time[30];
786       unsigned long t=(stoptime-starttime)/1000;
787       int sec,min;
788       min=t/60;
789       sec=t%60;
790       sprintf(time,"%i min, %i sec",min,sec);
791       SERIAL_ECHO_START;
792       SERIAL_ECHOLN(time);
793       LCD_MESSAGE(time);
794       autotempShutdown();
795       }
796       break;
797     case 42: //M42 -Change pin status via gcode
798       if (code_seen('S'))
799       {
800         int pin_status = code_value();
801         if (code_seen('P') && pin_status >= 0 && pin_status <= 255)
802         {
803           int pin_number = code_value();
804           for(int8_t i = 0; i < (int8_t)sizeof(sensitive_pins); i++)
805           {
806             if (sensitive_pins[i] == pin_number)
807             {
808               pin_number = -1;
809               break;
810             }
811           }
812           
813           if (pin_number > -1)
814           {              
815             pinMode(pin_number, OUTPUT);
816             digitalWrite(pin_number, pin_status);
817             analogWrite(pin_number, pin_status);
818           }
819         }
820       }
821      break;
822     case 104: // M104
823       tmp_extruder = active_extruder;
824       if(code_seen('T')) {
825         tmp_extruder = code_value();
826         if(tmp_extruder >= EXTRUDERS) {
827           SERIAL_ECHO_START;
828           SERIAL_ECHO(MSG_M104_INVALID_EXTRUDER);
829           SERIAL_ECHOLN(tmp_extruder);
830           break;
831         }
832       }
833       if (code_seen('S')) setTargetHotend(code_value(), tmp_extruder);
834       setWatch();
835       break;
836     case 140: // M140 set bed temp
837       if (code_seen('S')) setTargetBed(code_value());
838       break;
839     case 105 : // M105
840       tmp_extruder = active_extruder;
841       if(code_seen('T')) {
842         tmp_extruder = code_value();
843         if(tmp_extruder >= EXTRUDERS) {
844           SERIAL_ECHO_START;
845           SERIAL_ECHO(MSG_M105_INVALID_EXTRUDER);
846           SERIAL_ECHOLN(tmp_extruder);
847           break;
848         }
849       }
850       #if (TEMP_0_PIN > -1)
851         SERIAL_PROTOCOLPGM("ok T:");
852         SERIAL_PROTOCOL_F(degHotend(tmp_extruder),1); 
853         SERIAL_PROTOCOLPGM(" /");
854         SERIAL_PROTOCOL_F(degTargetHotend(tmp_extruder),1); 
855         #if TEMP_BED_PIN > -1
856           SERIAL_PROTOCOLPGM(" B:");  
857           SERIAL_PROTOCOL_F(degBed(),1);
858           SERIAL_PROTOCOLPGM(" /");
859           SERIAL_PROTOCOL_F(degTargetBed(),1);
860         #endif //TEMP_BED_PIN
861       #else
862         SERIAL_ERROR_START;
863         SERIAL_ERRORLNPGM(MSG_ERR_NO_THERMISTORS);
864       #endif
865       #ifdef PIDTEMP
866         SERIAL_PROTOCOLPGM(" @:");
867         SERIAL_PROTOCOL(getHeaterPower(tmp_extruder));  
868       #endif
869         SERIAL_PROTOCOLLN("");
870       return;
871       break;
872     case 109: 
873     {// M109 - Wait for extruder heater to reach target.
874       tmp_extruder = active_extruder;
875       if(code_seen('T')) {
876         tmp_extruder = code_value();
877         if(tmp_extruder >= EXTRUDERS) {
878           SERIAL_ECHO_START;
879           SERIAL_ECHO(MSG_M109_INVALID_EXTRUDER);
880           SERIAL_ECHOLN(tmp_extruder);
881           break;
882         }
883       }
884       LCD_MESSAGEPGM(MSG_HEATING);   
885       #ifdef AUTOTEMP
886         autotemp_enabled=false;
887       #endif
888       if (code_seen('S')) setTargetHotend(code_value(), tmp_extruder);
889       #ifdef AUTOTEMP
890         if (code_seen('S')) autotemp_min=code_value();
891         if (code_seen('B')) autotemp_max=code_value();
892         if (code_seen('F')) 
893         {
894           autotemp_factor=code_value();
895           autotemp_enabled=true;
896         }
897       #endif
898       
899       setWatch();
900       codenum = millis(); 
901
902       /* See if we are heating up or cooling down */
903       bool target_direction = isHeatingHotend(tmp_extruder); // true if heating, false if cooling
904
905       #ifdef TEMP_RESIDENCY_TIME
906         long residencyStart;
907         residencyStart = -1;
908         /* continue to loop until we have reached the target temp   
909           _and_ until TEMP_RESIDENCY_TIME hasn't passed since we reached it */
910         while((residencyStart == -1) ||
911               (residencyStart >= 0 && (((unsigned int) (millis() - residencyStart)) < (TEMP_RESIDENCY_TIME * 1000UL))) ) {
912       #else
913         while ( target_direction ? (isHeatingHotend(tmp_extruder)) : (isCoolingHotend(tmp_extruder)&&(CooldownNoWait==false)) ) {
914       #endif //TEMP_RESIDENCY_TIME
915           if( (millis() - codenum) > 1000UL )
916           { //Print Temp Reading and remaining time every 1 second while heating up/cooling down
917             SERIAL_PROTOCOLPGM("T:");
918             SERIAL_PROTOCOL_F(degHotend(tmp_extruder),1); 
919             SERIAL_PROTOCOLPGM(" E:");
920             SERIAL_PROTOCOL((int)tmp_extruder); 
921             #ifdef TEMP_RESIDENCY_TIME
922               SERIAL_PROTOCOLPGM(" W:");
923               if(residencyStart > -1)
924               {
925                  codenum = ((TEMP_RESIDENCY_TIME * 1000UL) - (millis() - residencyStart)) / 1000UL;
926                  SERIAL_PROTOCOLLN( codenum );
927               }
928               else 
929               {
930                  SERIAL_PROTOCOLLN( "?" );
931               }
932             #else
933               SERIAL_PROTOCOLLN("");
934             #endif
935             codenum = millis();
936           }
937           manage_heater();
938           manage_inactivity(1);
939           LCD_STATUS;
940         #ifdef TEMP_RESIDENCY_TIME
941             /* start/restart the TEMP_RESIDENCY_TIME timer whenever we reach target temp for the first time
942               or when current temp falls outside the hysteresis after target temp was reached */
943           if ((residencyStart == -1 &&  target_direction && (degHotend(tmp_extruder) >= (degTargetHotend(tmp_extruder)-TEMP_WINDOW))) ||
944               (residencyStart == -1 && !target_direction && (degHotend(tmp_extruder) <= (degTargetHotend(tmp_extruder)+TEMP_WINDOW))) ||
945               (residencyStart > -1 && labs(degHotend(tmp_extruder) - degTargetHotend(tmp_extruder)) > TEMP_HYSTERESIS) ) 
946           {
947             residencyStart = millis();
948           }
949         #endif //TEMP_RESIDENCY_TIME
950         }
951         LCD_MESSAGEPGM(MSG_HEATING_COMPLETE);
952         starttime=millis();
953         previous_millis_cmd = millis();
954       }
955       break;
956     case 190: // M190 - Wait for bed heater to reach target.
957     #if TEMP_BED_PIN > -1
958         LCD_MESSAGEPGM(MSG_BED_HEATING);
959         if (code_seen('S')) setTargetBed(code_value());
960         codenum = millis(); 
961         while(isHeatingBed()) 
962         {
963           if(( millis() - codenum) > 1000 ) //Print Temp Reading every 1 second while heating up.
964           {
965             float tt=degHotend(active_extruder);
966             SERIAL_PROTOCOLPGM("T:");
967             SERIAL_PROTOCOL(tt);
968             SERIAL_PROTOCOLPGM(" E:");
969             SERIAL_PROTOCOL((int)active_extruder); 
970             SERIAL_PROTOCOLPGM(" B:");
971             SERIAL_PROTOCOL_F(degBed(),1); 
972             SERIAL_PROTOCOLLN(""); 
973             codenum = millis(); 
974           }
975           manage_heater();
976           manage_inactivity(1);
977           LCD_STATUS;
978         }
979         LCD_MESSAGEPGM(MSG_BED_DONE);
980         previous_millis_cmd = millis();
981     #endif
982         break;
983
984     #if FAN_PIN > -1
985       case 106: //M106 Fan On
986         if (code_seen('S')){
987            FanSpeed=constrain(code_value(),0,255);
988         }
989         else {
990           FanSpeed=255;                 
991         }
992         break;
993       case 107: //M107 Fan Off
994         FanSpeed = 0;
995         break;
996     #endif //FAN_PIN
997
998     #if (PS_ON_PIN > -1)
999       case 80: // M80 - ATX Power On
1000         SET_OUTPUT(PS_ON_PIN); //GND
1001         WRITE(PS_ON_PIN, LOW);
1002         break;
1003       #endif
1004       
1005       case 81: // M81 - ATX Power Off
1006       
1007       #if defined SUICIDE_PIN && SUICIDE_PIN > -1
1008         st_synchronize();
1009         suicide();
1010       #elif (PS_ON_PIN > -1)
1011         SET_INPUT(PS_ON_PIN); //Floating
1012       #endif
1013                 break;
1014         
1015     case 82:
1016       axis_relative_modes[3] = false;
1017       break;
1018     case 83:
1019       axis_relative_modes[3] = true;
1020       break;
1021     case 18: //compatibility
1022     case 84: // M84
1023       if(code_seen('S')){ 
1024         stepper_inactive_time = code_value() * 1000; 
1025       }
1026       else
1027       { 
1028         bool all_axis = !((code_seen(axis_codes[0])) || (code_seen(axis_codes[1])) || (code_seen(axis_codes[2]))|| (code_seen(axis_codes[3])));
1029         if(all_axis)
1030         {
1031           st_synchronize();
1032           disable_e0();
1033           disable_e1();
1034           disable_e2();
1035           finishAndDisableSteppers();
1036         }
1037         else
1038         {
1039           st_synchronize();
1040           if(code_seen('X')) disable_x();
1041           if(code_seen('Y')) disable_y();
1042           if(code_seen('Z')) disable_z();
1043           #if ((E0_ENABLE_PIN != X_ENABLE_PIN) && (E1_ENABLE_PIN != Y_ENABLE_PIN)) // Only enable on boards that have seperate ENABLE_PINS
1044             if(code_seen('E')) {
1045               disable_e0();
1046               disable_e1();
1047               disable_e2();
1048             }
1049           #endif 
1050           LCD_MESSAGEPGM(MSG_PART_RELEASE);
1051         }
1052       }
1053       break;
1054     case 85: // M85
1055       code_seen('S');
1056       max_inactive_time = code_value() * 1000; 
1057       break;
1058     case 92: // M92
1059       for(int8_t i=0; i < NUM_AXIS; i++) 
1060       {
1061         if(code_seen(axis_codes[i])) 
1062           
1063           if(i == 3) { // E
1064             float value = code_value();
1065             if(value < 20.0) {
1066               float factor = axis_steps_per_unit[i] / value; // increase e constants if M92 E14 is given for netfab.
1067               max_e_jerk *= factor;
1068               max_feedrate[i] *= factor;
1069               axis_steps_per_sqr_second[i] *= factor;
1070             }
1071             axis_steps_per_unit[i] = value;
1072           }
1073           else {
1074             axis_steps_per_unit[i] = code_value();
1075           }
1076       }
1077       break;
1078     case 115: // M115
1079       SerialprintPGM(MSG_M115_REPORT);
1080       break;
1081     case 117: // M117 display message
1082       LCD_MESSAGE(cmdbuffer[bufindr]+5);
1083       break;
1084     case 114: // M114
1085       SERIAL_PROTOCOLPGM("X:");
1086       SERIAL_PROTOCOL(current_position[X_AXIS]);
1087       SERIAL_PROTOCOLPGM("Y:");
1088       SERIAL_PROTOCOL(current_position[Y_AXIS]);
1089       SERIAL_PROTOCOLPGM("Z:");
1090       SERIAL_PROTOCOL(current_position[Z_AXIS]);
1091       SERIAL_PROTOCOLPGM("E:");      
1092       SERIAL_PROTOCOL(current_position[E_AXIS]);
1093       
1094       SERIAL_PROTOCOLPGM(MSG_COUNT_X);
1095       SERIAL_PROTOCOL(float(st_get_position(X_AXIS))/axis_steps_per_unit[X_AXIS]);
1096       SERIAL_PROTOCOLPGM("Y:");
1097       SERIAL_PROTOCOL(float(st_get_position(Y_AXIS))/axis_steps_per_unit[Y_AXIS]);
1098       SERIAL_PROTOCOLPGM("Z:");
1099       SERIAL_PROTOCOL(float(st_get_position(Z_AXIS))/axis_steps_per_unit[Z_AXIS]);
1100       
1101       SERIAL_PROTOCOLLN("");
1102       break;
1103     case 120: // M120
1104       enable_endstops(false) ;
1105       break;
1106     case 121: // M121
1107       enable_endstops(true) ;
1108       break;
1109     case 119: // M119
1110       #if (X_MIN_PIN > -1)
1111         SERIAL_PROTOCOLPGM(MSG_X_MIN);
1112         SERIAL_PROTOCOL(((READ(X_MIN_PIN)^X_ENDSTOPS_INVERTING)?"H ":"L "));
1113       #endif
1114       #if (X_MAX_PIN > -1)
1115         SERIAL_PROTOCOLPGM(MSG_X_MAX);
1116         SERIAL_PROTOCOL(((READ(X_MAX_PIN)^X_ENDSTOPS_INVERTING)?"H ":"L "));
1117       #endif
1118       #if (Y_MIN_PIN > -1)
1119         SERIAL_PROTOCOLPGM(MSG_Y_MIN);
1120         SERIAL_PROTOCOL(((READ(Y_MIN_PIN)^Y_ENDSTOPS_INVERTING)?"H ":"L "));
1121       #endif
1122       #if (Y_MAX_PIN > -1)
1123         SERIAL_PROTOCOLPGM(MSG_Y_MAX);
1124         SERIAL_PROTOCOL(((READ(Y_MAX_PIN)^Y_ENDSTOPS_INVERTING)?"H ":"L "));
1125       #endif
1126       #if (Z_MIN_PIN > -1)
1127         SERIAL_PROTOCOLPGM(MSG_Z_MIN);
1128         SERIAL_PROTOCOL(((READ(Z_MIN_PIN)^Z_ENDSTOPS_INVERTING)?"H ":"L "));
1129       #endif
1130       #if (Z_MAX_PIN > -1)
1131         SERIAL_PROTOCOLPGM(MSG_Z_MAX);
1132         SERIAL_PROTOCOL(((READ(Z_MAX_PIN)^Z_ENDSTOPS_INVERTING)?"H ":"L "));
1133       #endif
1134       SERIAL_PROTOCOLLN("");
1135       break;
1136       //TODO: update for all axis, use for loop
1137     case 201: // M201
1138       for(int8_t i=0; i < NUM_AXIS; i++) 
1139       {
1140         if(code_seen(axis_codes[i]))
1141         {
1142           max_acceleration_units_per_sq_second[i] = code_value();
1143           axis_steps_per_sqr_second[i] = code_value() * axis_steps_per_unit[i];
1144         }
1145       }
1146       break;
1147     #if 0 // Not used for Sprinter/grbl gen6
1148     case 202: // M202
1149       for(int8_t i=0; i < NUM_AXIS; i++) {
1150         if(code_seen(axis_codes[i])) axis_travel_steps_per_sqr_second[i] = code_value() * axis_steps_per_unit[i];
1151       }
1152       break;
1153     #endif
1154     case 203: // M203 max feedrate mm/sec
1155       for(int8_t i=0; i < NUM_AXIS; i++) {
1156         if(code_seen(axis_codes[i])) max_feedrate[i] = code_value();
1157       }
1158       break;
1159     case 204: // M204 acclereration S normal moves T filmanent only moves
1160       {
1161         if(code_seen('S')) acceleration = code_value() ;
1162         if(code_seen('T')) retract_acceleration = code_value() ;
1163       }
1164       break;
1165     case 205: //M205 advanced settings:  minimum travel speed S=while printing T=travel only,  B=minimum segment time X= maximum xy jerk, Z=maximum Z jerk
1166     {
1167       if(code_seen('S')) minimumfeedrate = code_value();
1168       if(code_seen('T')) mintravelfeedrate = code_value();
1169       if(code_seen('B')) minsegmenttime = code_value() ;
1170       if(code_seen('X')) max_xy_jerk = code_value() ;
1171       if(code_seen('Z')) max_z_jerk = code_value() ;
1172       if(code_seen('E')) max_e_jerk = code_value() ;
1173     }
1174     break;
1175     case 206: // M206 additional homeing offset
1176       for(int8_t i=0; i < 3; i++) 
1177       {
1178         if(code_seen(axis_codes[i])) add_homeing[i] = code_value();
1179       }
1180       break;
1181     case 220: // M220 S<factor in percent>- set speed factor override percentage
1182     {
1183       if(code_seen('S')) 
1184       {
1185         feedmultiply = code_value() ;
1186         feedmultiplychanged=true;
1187       }
1188     }
1189     break;
1190     case 221: // M221 S<factor in percent>- set extrude factor override percentage
1191     {
1192       if(code_seen('S')) 
1193       {
1194         extrudemultiply = code_value() ;
1195       }
1196     }
1197     break;
1198
1199     #ifdef PIDTEMP
1200     case 301: // M301
1201       {
1202         if(code_seen('P')) Kp = code_value();
1203         if(code_seen('I')) Ki = code_value()*PID_dT;
1204         if(code_seen('D')) Kd = code_value()/PID_dT;
1205         #ifdef PID_ADD_EXTRUSION_RATE
1206         if(code_seen('C')) Kc = code_value();
1207         #endif
1208         updatePID();
1209         SERIAL_PROTOCOL(MSG_OK);
1210                 SERIAL_PROTOCOL(" p:");
1211         SERIAL_PROTOCOL(Kp);
1212         SERIAL_PROTOCOL(" i:");
1213         SERIAL_PROTOCOL(Ki/PID_dT);
1214         SERIAL_PROTOCOL(" d:");
1215         SERIAL_PROTOCOL(Kd*PID_dT);
1216         #ifdef PID_ADD_EXTRUSION_RATE
1217         SERIAL_PROTOCOL(" c:");
1218         SERIAL_PROTOCOL(Kc*PID_dT);
1219         #endif
1220         SERIAL_PROTOCOLLN("");
1221       }
1222       break;
1223     #endif //PIDTEMP
1224     case 240: // M240  Triggers a camera by emulating a Canon RC-1 : http://www.doc-diy.net/photo/rc-1_hacked/
1225      {
1226       #ifdef PHOTOGRAPH_PIN
1227         #if (PHOTOGRAPH_PIN > -1)
1228         const uint8_t NUM_PULSES=16;
1229         const float PULSE_LENGTH=0.01524;
1230         for(int i=0; i < NUM_PULSES; i++) {
1231           WRITE(PHOTOGRAPH_PIN, HIGH);
1232           _delay_ms(PULSE_LENGTH);
1233           WRITE(PHOTOGRAPH_PIN, LOW);
1234           _delay_ms(PULSE_LENGTH);
1235         }
1236         delay(7.33);
1237         for(int i=0; i < NUM_PULSES; i++) {
1238           WRITE(PHOTOGRAPH_PIN, HIGH);
1239           _delay_ms(PULSE_LENGTH);
1240           WRITE(PHOTOGRAPH_PIN, LOW);
1241           _delay_ms(PULSE_LENGTH);
1242         }
1243         #endif
1244       #endif
1245      }
1246     break;
1247       
1248     case 302: // allow cold extrudes
1249     {
1250       allow_cold_extrudes(true);
1251     }
1252     break;
1253     case 303: // M303 PID autotune
1254     {
1255       float temp = 150.0;
1256       if (code_seen('S')) temp=code_value();
1257       PID_autotune(temp);
1258     }
1259     break;
1260     case 400: // finish all moves
1261     {
1262       st_synchronize();
1263     }
1264     break;
1265     case 500: // Store settings in EEPROM
1266     {
1267         EEPROM_StoreSettings();
1268     }
1269     break;
1270     case 501: // Read settings from EEPROM
1271     {
1272       EEPROM_RetrieveSettings();
1273     }
1274     break;
1275     case 502: // Revert to default settings
1276     {
1277       EEPROM_RetrieveSettings(true);
1278     }
1279     break;
1280     case 503: // print settings currently in memory
1281     {
1282       EEPROM_printSettings();
1283     }
1284     break;
1285     case 999: // Restart after being stopped
1286       Stopped = false;
1287       gcode_LastN = Stopped_gcode_LastN;
1288       FlushSerialRequestResend();
1289     break;
1290     }
1291   }
1292
1293   else if(code_seen('T')) 
1294   {
1295     tmp_extruder = code_value();
1296     if(tmp_extruder >= EXTRUDERS) {
1297       SERIAL_ECHO_START;
1298       SERIAL_ECHO("T");
1299       SERIAL_ECHO(tmp_extruder);
1300       SERIAL_ECHOLN(MSG_INVALID_EXTRUDER);
1301     }
1302     else {
1303       active_extruder = tmp_extruder;
1304       SERIAL_ECHO_START;
1305       SERIAL_ECHO(MSG_ACTIVE_EXTRUDER);
1306       SERIAL_PROTOCOLLN((int)active_extruder);
1307     }
1308   }
1309
1310   else
1311   {
1312     SERIAL_ECHO_START;
1313     SERIAL_ECHOPGM(MSG_UNKNOWN_COMMAND);
1314     SERIAL_ECHO(cmdbuffer[bufindr]);
1315     SERIAL_ECHOLNPGM("\"");
1316   }
1317
1318   ClearToSend();
1319 }
1320
1321 void FlushSerialRequestResend()
1322 {
1323   //char cmdbuffer[bufindr][100]="Resend:";
1324   MYSERIAL.flush();
1325   SERIAL_PROTOCOLPGM(MSG_RESEND);
1326   SERIAL_PROTOCOLLN(gcode_LastN + 1);
1327   ClearToSend();
1328 }
1329
1330 void ClearToSend()
1331 {
1332   previous_millis_cmd = millis();
1333   #ifdef SDSUPPORT
1334   if(fromsd[bufindr])
1335     return;
1336   #endif //SDSUPPORT
1337   SERIAL_PROTOCOLLNPGM(MSG_OK); 
1338 }
1339
1340 void get_coordinates()
1341 {
1342   for(int8_t i=0; i < NUM_AXIS; i++) {
1343     if(code_seen(axis_codes[i])) destination[i] = (float)code_value() + (axis_relative_modes[i] || relative_mode)*current_position[i];
1344     else destination[i] = current_position[i]; //Are these else lines really needed?
1345   }
1346   if(code_seen('F')) {
1347     next_feedrate = code_value();
1348     if(next_feedrate > 0.0) feedrate = next_feedrate;
1349   }
1350 }
1351
1352 void get_arc_coordinates()
1353 {
1354    get_coordinates();
1355    if(code_seen('I')) {
1356      offset[0] = code_value();
1357    } 
1358    else {
1359      offset[0] = 0.0;
1360    }
1361    if(code_seen('J')) {
1362      offset[1] = code_value();
1363    }
1364    else {
1365      offset[1] = 0.0;
1366    }
1367 }
1368
1369 void prepare_move()
1370 {
1371   if (min_software_endstops) {
1372     if (destination[X_AXIS] < X_HOME_POS) destination[X_AXIS] = X_HOME_POS;
1373     if (destination[Y_AXIS] < Y_HOME_POS) destination[Y_AXIS] = Y_HOME_POS;
1374     if (destination[Z_AXIS] < Z_HOME_POS) destination[Z_AXIS] = Z_HOME_POS;
1375   }
1376
1377   if (max_software_endstops) {
1378     if (destination[X_AXIS] > X_MAX_LENGTH) destination[X_AXIS] = X_MAX_LENGTH;
1379     if (destination[Y_AXIS] > Y_MAX_LENGTH) destination[Y_AXIS] = Y_MAX_LENGTH;
1380     if (destination[Z_AXIS] > Z_MAX_LENGTH) destination[Z_AXIS] = Z_MAX_LENGTH;
1381   }
1382   previous_millis_cmd = millis();  
1383   plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate*feedmultiply/60/100.0, active_extruder);
1384   for(int8_t i=0; i < NUM_AXIS; i++) {
1385     current_position[i] = destination[i];
1386   }
1387 }
1388
1389 void prepare_arc_move(char isclockwise) {
1390   float r = hypot(offset[X_AXIS], offset[Y_AXIS]); // Compute arc radius for mc_arc
1391
1392   // Trace the arc
1393   mc_arc(current_position, destination, offset, X_AXIS, Y_AXIS, Z_AXIS, feedrate*feedmultiply/60/100.0, r, isclockwise, active_extruder);
1394   
1395   // As far as the parser is concerned, the position is now == target. In reality the
1396   // motion control system might still be processing the action and the real tool position
1397   // in any intermediate location.
1398   for(int8_t i=0; i < NUM_AXIS; i++) {
1399     current_position[i] = destination[i];
1400   }
1401   previous_millis_cmd = millis();
1402 }
1403
1404 #ifdef CONTROLLERFAN_PIN
1405 unsigned long lastMotor = 0; //Save the time for when a motor was turned on last
1406 unsigned long lastMotorCheck = 0;
1407
1408 void controllerFan()
1409 {
1410   if ((millis() - lastMotorCheck) >= 2500) //Not a time critical function, so we only check every 2500ms
1411   {
1412     lastMotorCheck = millis();
1413     
1414     if(!READ(X_ENABLE_PIN) || !READ(Y_ENABLE_PIN) || !READ(Z_ENABLE_PIN)
1415     #if EXTRUDERS > 2
1416        || !READ(E2_ENABLE_PIN)
1417     #endif
1418     #if EXTRUDER > 1
1419        || !READ(E2_ENABLE_PIN)
1420     #endif
1421        || !READ(E0_ENABLE_PIN)) //If any of the drivers are enabled...    
1422     {
1423       lastMotor = millis(); //... set time to NOW so the fan will turn on
1424     }
1425     
1426     if ((millis() - lastMotor) >= (CONTROLLERFAN_SEC*1000UL) || lastMotor == 0) //If the last time any driver was enabled, is longer since than CONTROLLERSEC...   
1427     {
1428       WRITE(CONTROLLERFAN_PIN, LOW); //... turn the fan off
1429     }
1430     else
1431     {
1432       WRITE(CONTROLLERFAN_PIN, HIGH); //... turn the fan on
1433     }
1434   }
1435 }
1436 #endif
1437
1438 void manage_inactivity(byte debug) 
1439
1440   if( (millis() - previous_millis_cmd) >  max_inactive_time ) 
1441     if(max_inactive_time) 
1442       kill(); 
1443   if(stepper_inactive_time)  {
1444     if( (millis() - previous_millis_cmd) >  stepper_inactive_time ) 
1445     {
1446       if(blocks_queued() == false) {
1447         disable_x();
1448         disable_y();
1449         disable_z();
1450         disable_e0();
1451         disable_e1();
1452         disable_e2();
1453       }
1454     }
1455   }
1456   #ifdef CONTROLLERFAN_PIN
1457     controllerFan(); //Check if fan should be turned on to cool stepper drivers down
1458   #endif
1459   #ifdef EXTRUDER_RUNOUT_PREVENT
1460     if( (millis() - previous_millis_cmd) >  EXTRUDER_RUNOUT_SECONDS*1000 ) 
1461     if(degHotend(active_extruder)>EXTRUDER_RUNOUT_MINTEMP)
1462     {
1463      bool oldstatus=READ(E0_ENABLE_PIN);
1464      enable_e0();
1465      float oldepos=current_position[E_AXIS];
1466      float oldedes=destination[E_AXIS];
1467      plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], 
1468                       current_position[E_AXIS]+EXTRUDER_RUNOUT_EXTRUDE*EXTRUDER_RUNOUT_ESTEPS/axis_steps_per_unit[E_AXIS], 
1469                       EXTRUDER_RUNOUT_SPEED/60.*EXTRUDER_RUNOUT_ESTEPS/axis_steps_per_unit[E_AXIS], active_extruder);
1470      current_position[E_AXIS]=oldepos;
1471      destination[E_AXIS]=oldedes;
1472      plan_set_e_position(oldepos);
1473      previous_millis_cmd=millis();
1474      st_synchronize();
1475      WRITE(E0_ENABLE_PIN,oldstatus);
1476     }
1477   #endif
1478   check_axes_activity();
1479 }
1480
1481 void kill()
1482 {
1483   cli(); // Stop interrupts
1484   disable_heater();
1485
1486   disable_x();
1487   disable_y();
1488   disable_z();
1489   disable_e0();
1490   disable_e1();
1491   disable_e2();
1492   
1493   if(PS_ON_PIN > -1) pinMode(PS_ON_PIN,INPUT);
1494   SERIAL_ERROR_START;
1495   SERIAL_ERRORLNPGM(MSG_ERR_KILLED);
1496   LCD_MESSAGEPGM(MSG_KILLED);
1497   suicide();
1498   while(1); // Wait for reset
1499 }
1500
1501 void Stop()
1502 {
1503   disable_heater();
1504   if(Stopped == false) {
1505     Stopped = true;
1506     Stopped_gcode_LastN = gcode_LastN; // Save last g_code for restart
1507     SERIAL_ERROR_START;
1508     SERIAL_ERRORLNPGM(MSG_ERR_STOPPED);
1509     LCD_MESSAGEPGM(MSG_STOPPED);
1510   }
1511 }
1512
1513 bool IsStopped() { return Stopped; };
1514
1515 #ifdef FAST_PWM_FAN
1516 void setPwmFrequency(uint8_t pin, int val)
1517 {
1518   val &= 0x07;
1519   switch(digitalPinToTimer(pin))
1520   {
1521  
1522     #if defined(TCCR0A)
1523     case TIMER0A:
1524     case TIMER0B:
1525          TCCR0B &= ~(CS00 | CS01 | CS02);
1526          TCCR0B |= val;
1527          break;
1528     #endif
1529
1530     #if defined(TCCR1A)
1531     case TIMER1A:
1532     case TIMER1B:
1533          TCCR1B &= ~(CS10 | CS11 | CS12);
1534          TCCR1B |= val;
1535          break;
1536     #endif
1537
1538     #if defined(TCCR2)
1539     case TIMER2:
1540     case TIMER2:
1541          TCCR2 &= ~(CS10 | CS11 | CS12);
1542          TCCR2 |= val;
1543          break;
1544     #endif
1545
1546     #if defined(TCCR2A)
1547     case TIMER2A:
1548     case TIMER2B:
1549          TCCR2B &= ~(CS20 | CS21 | CS22);
1550          TCCR2B |= val;
1551          break;
1552     #endif
1553
1554     #if defined(TCCR3A)
1555     case TIMER3A:
1556     case TIMER3B:
1557     case TIMER3C:
1558          TCCR3B &= ~(CS30 | CS31 | CS32);
1559          TCCR3B |= val;
1560          break;
1561     #endif
1562
1563     #if defined(TCCR4A) 
1564     case TIMER4A:
1565     case TIMER4B:
1566     case TIMER4C:
1567          TCCR4B &= ~(CS40 | CS41 | CS42);
1568          TCCR4B |= val;
1569          break;
1570    #endif
1571
1572     #if defined(TCCR5A) 
1573     case TIMER5A:
1574     case TIMER5B:
1575     case TIMER5C:
1576          TCCR5B &= ~(CS50 | CS51 | CS52);
1577          TCCR5B |= val;
1578          break;
1579    #endif
1580
1581   }
1582 }
1583 #endif
1584
1585