Marlin_main.cpp 130 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806
  1. /* -*- c++ -*- */
  2. /*
  3. Reprap firmware based on Sprinter and grbl.
  4. Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
  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. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with this program. If not, see <http://www.gnu.org/licenses/>.
  15. */
  16. /*
  17. This firmware is a mashup between Sprinter and grbl.
  18. (https://github.com/kliment/Sprinter)
  19. (https://github.com/simen/grbl/tree)
  20. It has preliminary support for Matthew Roberts advance algorithm
  21. http://reprap.org/pipermail/reprap-dev/2011-May/003323.html
  22. */
  23. #include "Marlin.h"
  24. #ifdef ENABLE_AUTO_BED_LEVELING
  25. #include "vector_3.h"
  26. #ifdef ACCURATE_BED_LEVELING
  27. #include "qr_solve.h"
  28. #endif
  29. #endif // ENABLE_AUTO_BED_LEVELING
  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 "ConfigurationStore.h"
  38. #include "language.h"
  39. #include "pins_arduino.h"
  40. #include "math.h"
  41. #ifdef BLINKM
  42. #include "BlinkM.h"
  43. #include "Wire.h"
  44. #endif
  45. #if NUM_SERVOS > 0
  46. #include "Servo.h"
  47. #endif
  48. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  49. #include <SPI.h>
  50. #endif
  51. #define VERSION_STRING "1.0.0"
  52. // look here for descriptions of gcodes: http://linuxcnc.org/handbook/gcode/g-code.html
  53. // http://objects.reprap.org/wiki/Mendel_User_Manual:_RepRapGCodes
  54. //Implemented Codes
  55. //-------------------
  56. // G0 -> G1
  57. // G1 - Coordinated Movement X Y Z E
  58. // G2 - CW ARC
  59. // G3 - CCW ARC
  60. // G4 - Dwell S<seconds> or P<milliseconds>
  61. // G10 - retract filament according to settings of M207
  62. // G11 - retract recover filament according to settings of M208
  63. // G28 - Home all Axis
  64. // G29 - Detailed Z-Probe, probes the bed at 3 points. You must de at the home position for this to work correctly.
  65. // G30 - Single Z Probe, probes bed at current XY location.
  66. // G90 - Use Absolute Coordinates
  67. // G91 - Use Relative Coordinates
  68. // G92 - Set current position to cordinates given
  69. // M Codes
  70. // M0 - Unconditional stop - Wait for user to press a button on the LCD (Only if ULTRA_LCD is enabled)
  71. // M1 - Same as M0
  72. // M17 - Enable/Power all stepper motors
  73. // M18 - Disable all stepper motors; same as M84
  74. // M20 - List SD card
  75. // M21 - Init SD card
  76. // M22 - Release SD card
  77. // M23 - Select SD file (M23 filename.g)
  78. // M24 - Start/resume SD print
  79. // M25 - Pause SD print
  80. // M26 - Set SD position in bytes (M26 S12345)
  81. // M27 - Report SD print status
  82. // M28 - Start SD write (M28 filename.g)
  83. // M29 - Stop SD write
  84. // M30 - Delete file from SD (M30 filename.g)
  85. // M31 - Output time since last M109 or SD card start to serial
  86. // M32 - Select file and start SD print (Can be used _while_ printing from SD card files):
  87. // syntax "M32 /path/filename#", or "M32 S<startpos bytes> !filename#"
  88. // Call gcode file : "M32 P !filename#" and return to caller file after finishing (simiarl to #include).
  89. // The '#' is necessary when calling from within sd files, as it stops buffer prereading
  90. // M42 - Change pin status via gcode Use M42 Px Sy to set pin x to value y, when omitting Px the onboard led will be used.
  91. // M80 - Turn on Power Supply
  92. // M81 - Turn off Power Supply
  93. // M82 - Set E codes absolute (default)
  94. // M83 - Set E codes relative while in Absolute Coordinates (G90) mode
  95. // M84 - Disable steppers until next move,
  96. // or use S<seconds> to specify an inactivity timeout, after which the steppers will be disabled. S0 to disable the timeout.
  97. // M85 - Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
  98. // M92 - Set axis_steps_per_unit - same syntax as G92
  99. // M104 - Set extruder target temp
  100. // M105 - Read current temp
  101. // M106 - Fan on
  102. // M107 - Fan off
  103. // M109 - Sxxx Wait for extruder current temp to reach target temp. Waits only when heating
  104. // Rxxx Wait for extruder current temp to reach target temp. Waits when heating and cooling
  105. // M114 - Output current position to serial port
  106. // M115 - Capabilities string
  107. // M117 - display message
  108. // M119 - Output Endstop status to serial port
  109. // M126 - Solenoid Air Valve Open (BariCUDA support by jmil)
  110. // M127 - Solenoid Air Valve Closed (BariCUDA vent to atmospheric pressure by jmil)
  111. // M128 - EtoP Open (BariCUDA EtoP = electricity to air pressure transducer by jmil)
  112. // M129 - EtoP Closed (BariCUDA EtoP = electricity to air pressure transducer by jmil)
  113. // M140 - Set bed target temp
  114. // M150 - Set BlinkM Colour Output R: Red<0-255> U(!): Green<0-255> B: Blue<0-255> over i2c, G for green does not work.
  115. // M190 - Sxxx Wait for bed current temp to reach target temp. Waits only when heating
  116. // Rxxx Wait for bed current temp to reach target temp. Waits when heating and cooling
  117. // M200 D<millimeters>- set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).
  118. // M201 - Set max acceleration in units/s^2 for print moves (M201 X1000 Y1000)
  119. // M202 - Set max acceleration in units/s^2 for travel moves (M202 X1000 Y1000) Unused in Marlin!!
  120. // M203 - Set maximum feedrate that your machine can sustain (M203 X200 Y200 Z300 E10000) in mm/sec
  121. // 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
  122. // 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
  123. // M206 - set additional homeing offset
  124. // M207 - set retract length S[positive mm] F[feedrate mm/sec] Z[additional zlift/hop]
  125. // M208 - set recover=unretract length S[positive mm surplus to the M207 S*] F[feedrate mm/sec]
  126. // M209 - S<1=true/0=false> enable automatic retract detect if the slicer did not support G10/11: every normal extrude-only move will be classified as retract depending on the direction.
  127. // M218 - set hotend offset (in mm): T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  128. // M220 S<factor in percent>- set speed factor override percentage
  129. // M221 S<factor in percent>- set extrude factor override percentage
  130. // M226 P<pin number> S<pin state>- Wait until the specified pin reaches the state required
  131. // M240 - Trigger a camera to take a photograph
  132. // M250 - Set LCD contrast C<contrast value> (value 0..63)
  133. // M280 - set servo position absolute. P: servo index, S: angle or microseconds
  134. // M300 - Play beepsound S<frequency Hz> P<duration ms>
  135. // M301 - Set PID parameters P I and D
  136. // M302 - Allow cold extrudes, or set the minimum extrude S<temperature>.
  137. // M303 - PID relay autotune S<temperature> sets the target temperature. (default target temperature = 150C)
  138. // M304 - Set bed PID parameters P I and D
  139. // M400 - Finish all moves
  140. // M401 - Lower z-probe if present
  141. // M402 - Raise z-probe if present
  142. // M500 - stores paramters in EEPROM
  143. // M501 - reads parameters from EEPROM (if you need reset them after you changed them temporarily).
  144. // M502 - reverts to the default "factory settings". You still need to store them in EEPROM afterwards if you want to.
  145. // M503 - print the current settings (from memory not from eeprom)
  146. // M540 - Use S[0|1] to enable or disable the stop SD card print on endstop hit (requires ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  147. // M600 - Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  148. // M666 - set delta endstop adjustemnt
  149. // M605 - Set dual x-carriage movement mode: S<mode> [ X<duplication x-offset> R<duplication temp offset> ]
  150. // M907 - Set digital trimpot motor current using axis codes.
  151. // M908 - Control digital trimpot directly.
  152. // M350 - Set microstepping mode.
  153. // M351 - Toggle MS1 MS2 pins directly.
  154. // M928 - Start SD logging (M928 filename.g) - ended by M29
  155. // M999 - Restart after being stopped by error
  156. //Stepper Movement Variables
  157. //===========================================================================
  158. //=============================imported variables============================
  159. //===========================================================================
  160. //===========================================================================
  161. //=============================public variables=============================
  162. //===========================================================================
  163. #ifdef SDSUPPORT
  164. CardReader card;
  165. #endif
  166. float homing_feedrate[] = HOMING_FEEDRATE;
  167. bool axis_relative_modes[] = AXIS_RELATIVE_MODES;
  168. int feedmultiply=100; //100->1 200->2
  169. int saved_feedmultiply;
  170. int extrudemultiply=100; //100->1 200->2
  171. float volumetric_multiplier[EXTRUDERS] = {1.0
  172. #if EXTRUDERS > 1
  173. , 1.0
  174. #if EXTRUDERS > 2
  175. , 1.0
  176. #endif
  177. #endif
  178. };
  179. float current_position[NUM_AXIS] = { 0.0, 0.0, 0.0, 0.0 };
  180. float add_homeing[3]={0,0,0};
  181. #ifdef DELTA
  182. float endstop_adj[3]={0,0,0};
  183. #endif
  184. float min_pos[3] = { X_MIN_POS, Y_MIN_POS, Z_MIN_POS };
  185. float max_pos[3] = { X_MAX_POS, Y_MAX_POS, Z_MAX_POS };
  186. bool axis_known_position[3] = {false, false, false};
  187. float zprobe_zoffset;
  188. // Extruder offset
  189. #if EXTRUDERS > 1
  190. #ifndef DUAL_X_CARRIAGE
  191. #define NUM_EXTRUDER_OFFSETS 2 // only in XY plane
  192. #else
  193. #define NUM_EXTRUDER_OFFSETS 3 // supports offsets in XYZ plane
  194. #endif
  195. float extruder_offset[NUM_EXTRUDER_OFFSETS][EXTRUDERS] = {
  196. #if defined(EXTRUDER_OFFSET_X) && defined(EXTRUDER_OFFSET_Y)
  197. EXTRUDER_OFFSET_X, EXTRUDER_OFFSET_Y
  198. #endif
  199. };
  200. #endif
  201. uint8_t active_extruder = 0;
  202. int fanSpeed=0;
  203. #ifdef SERVO_ENDSTOPS
  204. int servo_endstops[] = SERVO_ENDSTOPS;
  205. int servo_endstop_angles[] = SERVO_ENDSTOP_ANGLES;
  206. #endif
  207. #ifdef BARICUDA
  208. int ValvePressure=0;
  209. int EtoPPressure=0;
  210. #endif
  211. #ifdef FWRETRACT
  212. bool autoretract_enabled=true;
  213. bool retracted=false;
  214. float retract_length=3, retract_feedrate=17*60, retract_zlift=0.8;
  215. float retract_recover_length=0, retract_recover_feedrate=8*60;
  216. #endif
  217. #ifdef ULTIPANEL
  218. #ifdef PS_DEFAULT_OFF
  219. bool powersupply = false;
  220. #else
  221. bool powersupply = true;
  222. #endif
  223. #endif
  224. #ifdef DELTA
  225. float delta[3] = {0.0, 0.0, 0.0};
  226. #endif
  227. //===========================================================================
  228. //=============================private variables=============================
  229. //===========================================================================
  230. const char axis_codes[NUM_AXIS] = {'X', 'Y', 'Z', 'E'};
  231. static float destination[NUM_AXIS] = { 0.0, 0.0, 0.0, 0.0};
  232. static float offset[3] = {0.0, 0.0, 0.0};
  233. static bool home_all_axis = true;
  234. static float feedrate = 1500.0, next_feedrate, saved_feedrate;
  235. static long gcode_N, gcode_LastN, Stopped_gcode_LastN = 0;
  236. static bool relative_mode = false; //Determines Absolute or Relative Coordinates
  237. static char cmdbuffer[BUFSIZE][MAX_CMD_SIZE];
  238. static bool fromsd[BUFSIZE];
  239. static int bufindr = 0;
  240. static int bufindw = 0;
  241. static int buflen = 0;
  242. //static int i = 0;
  243. static char serial_char;
  244. static int serial_count = 0;
  245. static boolean comment_mode = false;
  246. static char *strchr_pointer; // just a pointer to find chars in the cmd string like X, Y, Z, E, etc
  247. const int sensitive_pins[] = SENSITIVE_PINS; // Sensitive pin list for M42
  248. //static float tt = 0;
  249. //static float bt = 0;
  250. //Inactivity shutdown variables
  251. static unsigned long previous_millis_cmd = 0;
  252. static unsigned long max_inactive_time = 0;
  253. static unsigned long stepper_inactive_time = DEFAULT_STEPPER_DEACTIVE_TIME*1000l;
  254. unsigned long starttime=0;
  255. unsigned long stoptime=0;
  256. static uint8_t tmp_extruder;
  257. const char* queued_commands_P = NULL; /* pointer to the current line in the active sequence of commands, or NULL when none */
  258. bool Stopped=false;
  259. #if NUM_SERVOS > 0
  260. Servo servos[NUM_SERVOS];
  261. #endif
  262. bool CooldownNoWait = true;
  263. bool target_direction;
  264. #if defined(SDSUPPORT) && defined(POWEROFF_SAVE_SD_FILE)
  265. #define SAVE_INFO_INTERVAL (1000 * 10)
  266. #define APPEND_CMD_COUNT 5
  267. //#define SAVE_EACH_CMD_MODE
  268. struct power_off_info_t power_off_info;
  269. static char power_off_commands[BUFSIZE + APPEND_CMD_COUNT][MAX_CMD_SIZE];
  270. int power_off_commands_count = 0;
  271. int power_off_type_yes = 0;
  272. static int power_off_commands_index = 0;
  273. #endif
  274. //===========================================================================
  275. //=============================ROUTINES=============================
  276. //===========================================================================
  277. void get_arc_coordinates();
  278. bool setTargetedHotend(int code);
  279. void serial_echopair_P(const char *s_P, float v)
  280. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  281. void serial_echopair_P(const char *s_P, double v)
  282. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  283. void serial_echopair_P(const char *s_P, unsigned long v)
  284. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  285. extern "C"{
  286. extern unsigned int __bss_end;
  287. extern unsigned int __heap_start;
  288. extern void *__brkval;
  289. int freeMemory() {
  290. int free_memory;
  291. if((int)__brkval == 0)
  292. free_memory = ((int)&free_memory) - ((int)&__bss_end);
  293. else
  294. free_memory = ((int)&free_memory) - ((int)__brkval);
  295. return free_memory;
  296. }
  297. }
  298. //adds an command to the main command buffer
  299. //thats really done in a non-safe way.
  300. //needs overworking someday
  301. // void enquecommand(const char *cmd)
  302. // {
  303. // if(buflen < BUFSIZE)
  304. // {
  305. // //this is dangerous if a mixing of serial and this happsens
  306. // strcpy(&(cmdbuffer[bufindw][0]),cmd);
  307. // SERIAL_ECHO_START;
  308. // SERIAL_ECHOPGM("enqueing \"");
  309. // SERIAL_ECHO(cmdbuffer[bufindw]);
  310. // SERIAL_ECHOLNPGM("\"");
  311. // bufindw= (bufindw + 1)%BUFSIZE;
  312. // buflen += 1;
  313. // }
  314. // }
  315. // void enquecommand_P(const char *cmd)
  316. // {
  317. // if(buflen < BUFSIZE)
  318. // {
  319. // //this is dangerous if a mixing of serial and this happsens
  320. // strcpy_P(&(cmdbuffer[bufindw][0]),cmd);
  321. // SERIAL_ECHO_START;
  322. // SERIAL_ECHOPGM("enqueing \"");
  323. // SERIAL_ECHO(cmdbuffer[bufindw]);
  324. // SERIAL_ECHOLNPGM("\"");
  325. // bufindw= (bufindw + 1)%BUFSIZE;
  326. // buflen += 1;
  327. // }
  328. // }
  329. /**
  330. * Inject the next command from the command queue, when possible
  331. * Return false only if no command was pending
  332. */
  333. static bool drain_queued_commands_P()
  334. {
  335. if (!queued_commands_P) return false;
  336. // Get the next 30 chars from the sequence of gcodes to run
  337. char cmd[30];
  338. strncpy_P(cmd, queued_commands_P, sizeof(cmd) - 1);
  339. cmd[sizeof(cmd) - 1] = '\0';
  340. // Look for the end of line, or the end of sequence
  341. size_t i = 0;
  342. char c;
  343. while ((c = cmd[i]) && c != '\n') i++; // find the end of this gcode command
  344. cmd[i] = '\0';
  345. if (enqueuecommand(cmd)) { // buffer was not full (else we will retry later)
  346. if (c)
  347. queued_commands_P += i + 1; // move to next command
  348. else
  349. queued_commands_P = NULL; // will have no more commands in the sequence
  350. }
  351. return true;
  352. }
  353. /**
  354. * Record one or many commands to run from program memory.
  355. * Aborts the current queue, if any.
  356. * Note: drain_queued_commands_P() must be called repeatedly to drain the commands afterwards
  357. */
  358. void enqueuecommands_P(const char* pgcode)
  359. {
  360. queued_commands_P = pgcode;
  361. drain_queued_commands_P(); // first command executed asap (when possible)
  362. }
  363. /**
  364. * Copy a command directly into the main command buffer, from RAM.
  365. *
  366. * This is done in a non-safe way and needs a rework someday.
  367. * Returns false if it doesn't add any command
  368. */
  369. bool enqueuecommand(const char* cmd)
  370. {
  371. if (*cmd == ';' || buflen >= BUFSIZE) return false;
  372. // This is dangerous if a mixing of serial and this happens
  373. char* command = cmdbuffer[bufindw];
  374. strcpy(command, cmd);
  375. SERIAL_ECHO_START;
  376. SERIAL_ECHOPGM("enqueing \"");
  377. SERIAL_ECHO(command);
  378. SERIAL_ECHOLNPGM("\"");
  379. bufindw = (bufindw + 1) % BUFSIZE;
  380. buflen++;
  381. return true;
  382. }
  383. void setup_killpin()
  384. {
  385. #if defined(KILL_PIN) && KILL_PIN > -1
  386. pinMode(KILL_PIN,INPUT);
  387. WRITE(KILL_PIN,HIGH);
  388. #endif
  389. }
  390. void setup_photpin()
  391. {
  392. #if defined(PHOTOGRAPH_PIN) && PHOTOGRAPH_PIN > -1
  393. SET_OUTPUT(PHOTOGRAPH_PIN);
  394. WRITE(PHOTOGRAPH_PIN, LOW);
  395. #endif
  396. }
  397. void setup_powerhold()
  398. {
  399. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  400. SET_OUTPUT(SUICIDE_PIN);
  401. WRITE(SUICIDE_PIN, HIGH);
  402. #endif
  403. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  404. SET_OUTPUT(PS_ON_PIN);
  405. #if defined(PS_DEFAULT_OFF)
  406. WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  407. #else
  408. WRITE(PS_ON_PIN, PS_ON_AWAKE);
  409. #endif
  410. #endif
  411. }
  412. void suicide()
  413. {
  414. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  415. SET_OUTPUT(SUICIDE_PIN);
  416. WRITE(SUICIDE_PIN, LOW);
  417. #endif
  418. }
  419. void servo_init()
  420. {
  421. #if (NUM_SERVOS >= 1) && defined(SERVO0_PIN) && (SERVO0_PIN > -1)
  422. servos[0].attach(SERVO0_PIN);
  423. #endif
  424. #if (NUM_SERVOS >= 2) && defined(SERVO1_PIN) && (SERVO1_PIN > -1)
  425. servos[1].attach(SERVO1_PIN);
  426. #endif
  427. #if (NUM_SERVOS >= 3) && defined(SERVO2_PIN) && (SERVO2_PIN > -1)
  428. servos[2].attach(SERVO2_PIN);
  429. #endif
  430. #if (NUM_SERVOS >= 4) && defined(SERVO3_PIN) && (SERVO3_PIN > -1)
  431. servos[3].attach(SERVO3_PIN);
  432. #endif
  433. #if (NUM_SERVOS >= 5)
  434. #error "TODO: enter initalisation code for more servos"
  435. #endif
  436. // Set position of Servo Endstops that are defined
  437. #ifdef SERVO_ENDSTOPS
  438. for(int8_t i = 0; i < 3; i++)
  439. {
  440. if(servo_endstops[i] > -1) {
  441. servos[servo_endstops[i]].write(servo_endstop_angles[i * 2 + 1]);
  442. }
  443. }
  444. #endif
  445. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  446. delay(PROBE_SERVO_DEACTIVATION_DELAY);
  447. servos[servo_endstops[Z_AXIS]].detach();
  448. #endif
  449. }
  450. #if defined(SDSUPPORT) && defined(POWEROFF_SAVE_SD_FILE)
  451. void init_power_off_info () {
  452. int i = 0;
  453. memset(&power_off_info, 0, sizeof(power_off_info));
  454. memset(power_off_commands, 0, sizeof(power_off_commands));
  455. if (!card.cardOK){
  456. card.initsd();
  457. }
  458. if (card.cardOK) {
  459. SERIAL_PROTOCOLLN("Init power off infomation.");
  460. SERIAL_PROTOCOLLN("size: ");
  461. SERIAL_PROTOCOLLN(sizeof(power_off_info));
  462. strncpy_P(power_off_info.power_off_filename, PSTR("bin"), sizeof(power_off_info.power_off_filename) - 1);
  463. if (card.existPowerOffFile(power_off_info.power_off_filename)) {
  464. card.openPowerOffFile(power_off_info.power_off_filename, O_READ);
  465. card.getPowerOffInfo(&power_off_info, sizeof(power_off_info));
  466. card.closePowerOffFile();
  467. // card.removePowerOffFile();
  468. SERIAL_PROTOCOLLN("init valid: ");
  469. SERIAL_PROTOCOLLN((unsigned long)power_off_info.valid_head);
  470. SERIAL_PROTOCOLLN((unsigned long)power_off_info.valid_foot);
  471. if ((power_off_info.valid_head != 0) && (power_off_info.valid_head == power_off_info.valid_foot)) {
  472. enable_z();
  473. /* --------------------------------------------------------------------- */
  474. SERIAL_PROTOCOLLN("current_position(X,Y,Z,E,F,T1..T4,B): ");
  475. for (i = 0; i < NUM_AXIS; i++) {
  476. //current_position[i] = power_off_info.current_position[i];
  477. SERIAL_PROTOCOLLN(power_off_info.current_position[i]);
  478. }
  479. //feedrate = power_off_info.feedrate;
  480. SERIAL_PROTOCOLLN(power_off_info.feedrate);
  481. for (i = 0; i < 4; i++) {
  482. //target_temperature[i] = power_off_info.target_temperature[i];
  483. SERIAL_PROTOCOLLN(power_off_info.target_temperature[i]);
  484. }
  485. SERIAL_PROTOCOLLN(power_off_info.target_temperature_bed);
  486. /* --------------------------------------------------------------------- */
  487. SERIAL_PROTOCOLLN("cmd_queue(R,W,C,Q): ");
  488. //cmd_queue_index_r = power_off_info.cmd_queue_index_r;
  489. SERIAL_PROTOCOLLN(power_off_info.cmd_queue_index_r);
  490. //cmd_queue_index_w = power_off_info.cmd_queue_index_w;
  491. SERIAL_PROTOCOLLN(power_off_info.cmd_queue_index_w);
  492. //commands_in_queue = power_off_info.commands_in_queue;
  493. SERIAL_PROTOCOLLN(power_off_info.commands_in_queue);
  494. //memcpy(command_queue, power_off_info.command_queue, sizeof(command_queue));
  495. for (i = 0; i < BUFSIZE; i++) {
  496. SERIAL_PROTOCOLLN(power_off_info.command_queue[i]);
  497. }
  498. char str_X[16];
  499. char str_Y[16];
  500. char str_Z[16];
  501. char str_E[16];
  502. char str_Z_up[16];
  503. memset(str_Z, 0, sizeof(str_X));
  504. memset(str_Z, 0, sizeof(str_Y));
  505. memset(str_Z, 0, sizeof(str_Z));
  506. memset(str_E, 0, sizeof(str_E));
  507. memset(str_Z_up, 0, sizeof(str_Z_up));
  508. dtostrf(power_off_info.current_position[0], 1, 3, str_X);
  509. dtostrf(power_off_info.current_position[1], 1, 3, str_Y);
  510. dtostrf(power_off_info.current_position[2], 1, 3, str_Z);
  511. dtostrf(power_off_info.current_position[2] + 5, 1, 3, str_Z_up);
  512. #if defined(SAVE_EACH_CMD_MODE)
  513. dtostrf(power_off_info.current_position[3] - 5, 1, 3, str_E);
  514. #else
  515. dtostrf(power_off_info.current_position[3], 1, 3, str_E);
  516. #endif
  517. //sprintf_P(power_off_commands[0], PSTR("G0 Z%s"), tmp);
  518. sprintf_P(power_off_commands[0], PSTR("G92 Z%s E%s"), str_Z, str_E);
  519. sprintf_P(power_off_commands[1], PSTR("G0 Z%s"), str_Z_up);
  520. sprintf_P(power_off_commands[2], PSTR("G28 X0 Y0"));
  521. sprintf_P(power_off_commands[3], PSTR("G0 Z%s"), str_Z);
  522. sprintf_P(power_off_commands[4], PSTR("M117 Printing..."));
  523. power_off_commands_count = APPEND_CMD_COUNT;
  524. i = APPEND_CMD_COUNT;
  525. while (power_off_info.commands_in_queue > 0) {
  526. strcpy(power_off_commands[i++], power_off_info.command_queue[power_off_info.cmd_queue_index_r]);
  527. power_off_commands_count++;
  528. power_off_info.commands_in_queue--;
  529. power_off_info.cmd_queue_index_r = (power_off_info.cmd_queue_index_r + 1) % BUFSIZE;
  530. }
  531. for (i = 0; i < power_off_commands_count; i++) {
  532. SERIAL_PROTOCOLLN(power_off_commands[i]);
  533. }
  534. /* --------------------------------------------------------------------- */
  535. SERIAL_PROTOCOLLN("sd file(start_time,file_name,sd_pos): ");
  536. SERIAL_PROTOCOLLN(power_off_info.print_job_start_ms);
  537. SERIAL_PROTOCOLLN(power_off_info.sd_filename);
  538. SERIAL_PROTOCOLLN(power_off_info.sdpos);
  539. starttime = power_off_info.print_job_start_ms;
  540. card.openFile(power_off_info.sd_filename, true);
  541. card.setIndex(power_off_info.sdpos);
  542. /* --------------------------------------------------------------------- */
  543. }
  544. else {
  545. if ((power_off_info.valid_head != 0) && (power_off_info.valid_head != power_off_info.valid_foot)) {
  546. enqueuecommands_P(PSTR("M117 INVALID DATA."));
  547. }
  548. memset(&power_off_info, 0, sizeof(power_off_info));
  549. strncpy_P(power_off_info.power_off_filename, PSTR("bin"), sizeof(power_off_info.power_off_filename) - 1);
  550. }
  551. }
  552. }
  553. }
  554. bool drain_power_off_commands () {
  555. if (power_off_commands_count > 0) {
  556. if(enqueuecommand(power_off_commands[power_off_commands_index])) {
  557. power_off_commands_index++;
  558. power_off_commands_count--;
  559. }
  560. return true;
  561. }
  562. else {
  563. return false;
  564. }
  565. }
  566. void save_power_off_info () {
  567. int i = 0;
  568. //static millis_t pre_time = millis();
  569. //static millis_t cur_time = millis();
  570. if (card.cardOK && card.sdprinting) {
  571. //cur_time = millis();
  572. if (
  573. #ifdef SAVE_EACH_CMD_MODE
  574. (true)
  575. #else
  576. ((current_position[2] > 0) && (power_off_info.saved_z != current_position[2]))
  577. #endif
  578. //|| ((cur_time - pre_time) > SAVE_INFO_INTERVAL)
  579. ) {
  580. //pre_time = cur_time;
  581. //SERIAL_PROTOCOLLN("Z : ");
  582. //SERIAL_PROTOCOLLN(current_position[2]);
  583. //SERIAL_PROTOCOLLN(power_off_info.saved_z);
  584. power_off_info.valid_head = random(1,256);
  585. power_off_info.valid_foot = power_off_info.valid_head;
  586. //SERIAL_PROTOCOLLN("save valid: ");
  587. //SERIAL_PROTOCOLLN((unsigned long)power_off_info.valid_head);
  588. //SERIAL_PROTOCOLLN((unsigned long)power_off_info.valid_foot);
  589. /* --------------------------------------------------------------------- */
  590. //SERIAL_PROTOCOLLN("current_position(X,Y,Z,SZ,E,F,T1..T4,B): ");
  591. for (i = 0; i < NUM_AXIS; i++) {
  592. power_off_info.current_position[i] = current_position[i];
  593. //SERIAL_PROTOCOLLN(current_position[i]);
  594. }
  595. power_off_info.saved_z = current_position[2];
  596. //SERIAL_PROTOCOLLN(power_off_info.saved_z);
  597. power_off_info.feedrate = feedrate;
  598. //SERIAL_PROTOCOLLN(power_off_info.feedrate);
  599. for (i = 0; i < 4; i++) {
  600. power_off_info.target_temperature[i] = target_temperature[i];
  601. //SERIAL_PROTOCOLLN(target_temperature[i]);
  602. }
  603. power_off_info.target_temperature_bed = target_temperature_bed;
  604. //SERIAL_PROTOCOLLN(power_off_info.target_temperature_bed);
  605. /* --------------------------------------------------------------------- */
  606. //SERIAL_PROTOCOLLN("cmd_queue(R,W,C,Q): ");
  607. power_off_info.cmd_queue_index_r = bufindr;
  608. //SERIAL_PROTOCOLLN(power_off_info.cmd_queue_index_r);
  609. power_off_info.cmd_queue_index_w = bufindw;
  610. //SERIAL_PROTOCOLLN(power_off_info.cmd_queue_index_w);
  611. power_off_info.commands_in_queue = buflen;
  612. //SERIAL_PROTOCOLLN(power_off_info.commands_in_queue);
  613. memcpy(power_off_info.command_queue, cmdbuffer, sizeof(power_off_info.command_queue));
  614. //for (i = 0; i < BUFSIZE; i++) {
  615. // SERIAL_PROTOCOLLN(power_off_info.command_queue[i]);
  616. //}
  617. /* --------------------------------------------------------------------- */
  618. //SERIAL_PROTOCOLLN("sd file(start_time,file_name,sd_pos): ");
  619. power_off_info.print_job_start_ms = starttime;
  620. //SERIAL_PROTOCOLLN(power_off_info.print_job_start_ms);
  621. //strcpy(power_off_info.sd_filename,
  622. card.getAbsFilename(power_off_info.sd_filename);
  623. //SERIAL_PROTOCOLLN(power_off_info.sd_filename);
  624. power_off_info.sdpos = card.getIndex();
  625. //SERIAL_PROTOCOLLN(power_off_info.sdpos);
  626. /* --------------------------------------------------------------------- */
  627. card.openPowerOffFile(power_off_info.power_off_filename, O_CREAT | O_WRITE | O_TRUNC | O_SYNC);
  628. if (card.savePowerOffInfo(&power_off_info, sizeof(power_off_info)) == -1){
  629. SERIAL_PROTOCOLLN("Write power off file failed.");
  630. }
  631. }
  632. }
  633. }
  634. #endif
  635. void setup()
  636. {
  637. // pinMode(CHECK_MATWEIAL, INPUT);
  638. // digitalWrite(CHECK_MATWEIAL, HIGH);
  639. setup_killpin();
  640. setup_powerhold();
  641. MYSERIAL.begin(BAUDRATE);
  642. SERIAL_PROTOCOLLNPGM("start");
  643. SERIAL_ECHO_START;
  644. // Check startup - does nothing if bootloader sets MCUSR to 0
  645. byte mcu = MCUSR;
  646. if(mcu & 1) SERIAL_ECHOLNPGM(MSG_POWERUP);
  647. if(mcu & 2) SERIAL_ECHOLNPGM(MSG_EXTERNAL_RESET);
  648. if(mcu & 4) SERIAL_ECHOLNPGM(MSG_BROWNOUT_RESET);
  649. if(mcu & 8) SERIAL_ECHOLNPGM(MSG_WATCHDOG_RESET);
  650. if(mcu & 32) SERIAL_ECHOLNPGM(MSG_SOFTWARE_RESET);
  651. MCUSR=0;
  652. SERIAL_ECHOPGM(MSG_MARLIN);
  653. SERIAL_ECHOLNPGM(VERSION_STRING);
  654. #ifdef STRING_VERSION_CONFIG_H
  655. #ifdef STRING_CONFIG_H_AUTHOR
  656. SERIAL_ECHO_START;
  657. SERIAL_ECHOPGM(MSG_CONFIGURATION_VER);
  658. SERIAL_ECHOPGM(STRING_VERSION_CONFIG_H);
  659. SERIAL_ECHOPGM(MSG_AUTHOR);
  660. SERIAL_ECHOLNPGM(STRING_CONFIG_H_AUTHOR);
  661. SERIAL_ECHOPGM("Compiled: ");
  662. SERIAL_ECHOLNPGM(__DATE__);
  663. #endif
  664. #endif
  665. SERIAL_ECHO_START;
  666. SERIAL_ECHOPGM(MSG_FREE_MEMORY);
  667. SERIAL_ECHO(freeMemory());
  668. SERIAL_ECHOPGM(MSG_PLANNER_BUFFER_BYTES);
  669. SERIAL_ECHOLN((int)sizeof(block_t)*BLOCK_BUFFER_SIZE);
  670. for(int8_t i = 0; i < BUFSIZE; i++)
  671. {
  672. fromsd[i] = false;
  673. }
  674. // loads data from EEPROM if available else uses defaults (and resets step acceleration rate)
  675. Config_RetrieveSettings();
  676. tp_init(); // Initialize temperature loop
  677. plan_init(); // Initialize planner;
  678. watchdog_init();
  679. st_init(); // Initialize stepper, this enables interrupts!
  680. setup_photpin();
  681. servo_init();
  682. lcd_init();
  683. _delay_ms(1000); // wait 1sec to display the splash screen
  684. #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1
  685. SET_OUTPUT(CONTROLLERFAN_PIN); //Set pin used for driver cooling fan
  686. #endif
  687. #ifdef DIGIPOT_I2C
  688. digipot_i2c_init();
  689. #endif
  690. #if defined(SDSUPPORT) && defined(POWEROFF_SAVE_SD_FILE)
  691. init_power_off_info();
  692. #endif
  693. }
  694. void loop()
  695. {
  696. if(buflen < (BUFSIZE-1))
  697. get_command();
  698. #ifdef SDSUPPORT
  699. card.checkautostart(false);
  700. #endif
  701. if(buflen)
  702. {
  703. #ifdef SDSUPPORT
  704. if(card.saving)
  705. {
  706. if(strstr_P(cmdbuffer[bufindr], PSTR("M29")) == NULL)
  707. {
  708. card.write_command(cmdbuffer[bufindr]);
  709. if(card.logging)
  710. {
  711. process_commands();
  712. }
  713. else
  714. {
  715. SERIAL_PROTOCOLLNPGM(MSG_OK);
  716. }
  717. }
  718. else
  719. {
  720. card.closefile();
  721. SERIAL_PROTOCOLLNPGM(MSG_FILE_SAVED);
  722. }
  723. }
  724. else
  725. {
  726. process_commands();
  727. #if defined(SDSUPPORT) && defined(POWEROFF_SAVE_SD_FILE)
  728. save_power_off_info();
  729. #endif
  730. }
  731. #else
  732. process_commands();
  733. #endif //SDSUPPORT
  734. buflen = (buflen-1);
  735. bufindr = (bufindr + 1)%BUFSIZE;
  736. }
  737. //check heater every n milliseconds
  738. manage_heater();
  739. manage_inactivity();
  740. checkHitEndstops();
  741. lcd_update();
  742. }
  743. void get_command()
  744. {
  745. if (drain_queued_commands_P()) return; // priority is given to non-serial commands
  746. while( MYSERIAL.available() > 0 && buflen < BUFSIZE) {
  747. serial_char = MYSERIAL.read();
  748. if(serial_char == '\n' ||
  749. serial_char == '\r' ||
  750. (serial_char == ':' && comment_mode == false) ||
  751. serial_count >= (MAX_CMD_SIZE - 1) )
  752. {
  753. if(!serial_count) { //if empty line
  754. comment_mode = false; //for new command
  755. return;
  756. }
  757. cmdbuffer[bufindw][serial_count] = 0; //terminate string
  758. if(!comment_mode){
  759. comment_mode = false; //for new command
  760. fromsd[bufindw] = false;
  761. if(strchr(cmdbuffer[bufindw], 'N') != NULL)
  762. {
  763. strchr_pointer = strchr(cmdbuffer[bufindw], 'N');
  764. gcode_N = (strtol(&cmdbuffer[bufindw][strchr_pointer - cmdbuffer[bufindw] + 1], NULL, 10));
  765. if(gcode_N != gcode_LastN+1 && (strstr_P(cmdbuffer[bufindw], PSTR("M110")) == NULL) ) {
  766. SERIAL_ERROR_START;
  767. SERIAL_ERRORPGM(MSG_ERR_LINE_NO);
  768. SERIAL_ERRORLN(gcode_LastN);
  769. //Serial.println(gcode_N);
  770. FlushSerialRequestResend();
  771. serial_count = 0;
  772. return;
  773. }
  774. if(strchr(cmdbuffer[bufindw], '*') != NULL)
  775. {
  776. byte checksum = 0;
  777. byte count = 0;
  778. while(cmdbuffer[bufindw][count] != '*') checksum = checksum^cmdbuffer[bufindw][count++];
  779. strchr_pointer = strchr(cmdbuffer[bufindw], '*');
  780. if( (int)(strtod(&cmdbuffer[bufindw][strchr_pointer - cmdbuffer[bufindw] + 1], NULL)) != checksum) {
  781. SERIAL_ERROR_START;
  782. SERIAL_ERRORPGM(MSG_ERR_CHECKSUM_MISMATCH);
  783. SERIAL_ERRORLN(gcode_LastN);
  784. FlushSerialRequestResend();
  785. serial_count = 0;
  786. return;
  787. }
  788. //if no errors, continue parsing
  789. }
  790. else
  791. {
  792. SERIAL_ERROR_START;
  793. SERIAL_ERRORPGM(MSG_ERR_NO_CHECKSUM);
  794. SERIAL_ERRORLN(gcode_LastN);
  795. FlushSerialRequestResend();
  796. serial_count = 0;
  797. return;
  798. }
  799. gcode_LastN = gcode_N;
  800. //if no errors, continue parsing
  801. }
  802. else // if we don't receive 'N' but still see '*'
  803. {
  804. if((strchr(cmdbuffer[bufindw], '*') != NULL))
  805. {
  806. SERIAL_ERROR_START;
  807. SERIAL_ERRORPGM(MSG_ERR_NO_LINENUMBER_WITH_CHECKSUM);
  808. SERIAL_ERRORLN(gcode_LastN);
  809. serial_count = 0;
  810. return;
  811. }
  812. }
  813. if((strchr(cmdbuffer[bufindw], 'G') != NULL)){
  814. strchr_pointer = strchr(cmdbuffer[bufindw], 'G');
  815. switch((int)((strtod(&cmdbuffer[bufindw][strchr_pointer - cmdbuffer[bufindw] + 1], NULL)))){
  816. case 0:
  817. case 1:
  818. case 2:
  819. case 3:
  820. if(Stopped == false) { // If printer is stopped by an error the G[0-3] codes are ignored.
  821. #ifdef SDSUPPORT
  822. if(card.saving)
  823. break;
  824. #endif //SDSUPPORT
  825. SERIAL_PROTOCOLLNPGM(MSG_OK);
  826. }
  827. else {
  828. SERIAL_ERRORLNPGM(MSG_ERR_STOPPED);
  829. LCD_MESSAGEPGM(MSG_STOPPED);
  830. }
  831. break;
  832. default:
  833. break;
  834. }
  835. }
  836. bufindw = (bufindw + 1)%BUFSIZE;
  837. buflen += 1;
  838. }
  839. serial_count = 0; //clear buffer
  840. }
  841. else
  842. {
  843. if(serial_char == ';') comment_mode = true;
  844. if(!comment_mode) cmdbuffer[bufindw][serial_count++] = serial_char;
  845. }
  846. }
  847. #ifdef SDSUPPORT
  848. if(!card.sdprinting || serial_count!=0){
  849. return;
  850. }
  851. #if defined(SDSUPPORT) && defined(POWEROFF_SAVE_SD_FILE)
  852. if (drain_power_off_commands()) return;
  853. #endif
  854. //'#' stops reading from sd to the buffer prematurely, so procedural macro calls are possible
  855. // if it occures, stop_buffering is triggered and the buffer is ran dry.
  856. // this character _can_ occure in serial com, due to checksums. however, no checksums are used in sd printing
  857. static bool stop_buffering=false;
  858. if(buflen==0) stop_buffering=false;
  859. while( !card.eof() && buflen < BUFSIZE && !stop_buffering) {
  860. int16_t n=card.get();
  861. serial_char = (char)n;
  862. if(serial_char == '\n' ||
  863. serial_char == '\r' ||
  864. (serial_char == '#' && comment_mode == false) ||
  865. (serial_char == ':' && comment_mode == false) ||
  866. serial_count >= (MAX_CMD_SIZE - 1)||n==-1)
  867. {
  868. if(card.eof()){
  869. SERIAL_PROTOCOLLNPGM(MSG_FILE_PRINTED);
  870. stoptime=millis();
  871. char time[30];
  872. unsigned long t=(stoptime-starttime)/1000;
  873. int hours, minutes;
  874. minutes=(t/60)%60;
  875. hours=t/60/60;
  876. sprintf_P(time, PSTR("%i hours %i minutes"),hours, minutes);
  877. SERIAL_ECHO_START;
  878. SERIAL_ECHOLN(time);
  879. lcd_setstatus(time);
  880. card.printingHasFinished();
  881. card.checkautostart(true);
  882. }
  883. if(serial_char=='#')
  884. stop_buffering=true;
  885. if(!serial_count)
  886. {
  887. comment_mode = false; //for new command
  888. return; //if empty line
  889. }
  890. cmdbuffer[bufindw][serial_count] = 0; //terminate string
  891. // if(!comment_mode){
  892. fromsd[bufindw] = true;
  893. buflen += 1;
  894. bufindw = (bufindw + 1)%BUFSIZE;
  895. // }
  896. comment_mode = false; //for new command
  897. serial_count = 0; //clear buffer
  898. }
  899. else
  900. {
  901. if(serial_char == ';') comment_mode = true;
  902. if(!comment_mode) cmdbuffer[bufindw][serial_count++] = serial_char;
  903. }
  904. }
  905. #endif //SDSUPPORT
  906. }
  907. float code_value()
  908. {
  909. return (strtod(&cmdbuffer[bufindr][strchr_pointer - cmdbuffer[bufindr] + 1], NULL));
  910. }
  911. long code_value_long()
  912. {
  913. return (strtol(&cmdbuffer[bufindr][strchr_pointer - cmdbuffer[bufindr] + 1], NULL, 10));
  914. }
  915. bool code_seen(char code)
  916. {
  917. strchr_pointer = strchr(cmdbuffer[bufindr], code);
  918. return (strchr_pointer != NULL); //Return True if a character was found
  919. }
  920. #define DEFINE_PGM_READ_ANY(type, reader) \
  921. static inline type pgm_read_any(const type *p) \
  922. { return pgm_read_##reader##_near(p); }
  923. DEFINE_PGM_READ_ANY(float, float);
  924. DEFINE_PGM_READ_ANY(signed char, byte);
  925. #define XYZ_CONSTS_FROM_CONFIG(type, array, CONFIG) \
  926. static const PROGMEM type array##_P[3] = \
  927. { X_##CONFIG, Y_##CONFIG, Z_##CONFIG }; \
  928. static inline type array(int axis) \
  929. { return pgm_read_any(&array##_P[axis]); }
  930. XYZ_CONSTS_FROM_CONFIG(float, base_min_pos, MIN_POS);
  931. XYZ_CONSTS_FROM_CONFIG(float, base_max_pos, MAX_POS);
  932. XYZ_CONSTS_FROM_CONFIG(float, base_home_pos, HOME_POS);
  933. XYZ_CONSTS_FROM_CONFIG(float, max_length, MAX_LENGTH);
  934. XYZ_CONSTS_FROM_CONFIG(float, home_retract_mm, HOME_RETRACT_MM);
  935. XYZ_CONSTS_FROM_CONFIG(signed char, home_dir, HOME_DIR);
  936. #ifdef DUAL_X_CARRIAGE
  937. #if EXTRUDERS == 1 || defined(COREXY) \
  938. || !defined(X2_ENABLE_PIN) || !defined(X2_STEP_PIN) || !defined(X2_DIR_PIN) \
  939. || !defined(X2_HOME_POS) || !defined(X2_MIN_POS) || !defined(X2_MAX_POS) \
  940. || !defined(X_MAX_PIN) || X_MAX_PIN < 0
  941. #error "Missing or invalid definitions for DUAL_X_CARRIAGE mode."
  942. #endif
  943. #if X_HOME_DIR != -1 || X2_HOME_DIR != 1
  944. #error "Please use canonical x-carriage assignment" // the x-carriages are defined by their homing directions
  945. #endif
  946. #define DXC_FULL_CONTROL_MODE 0
  947. #define DXC_AUTO_PARK_MODE 1
  948. #define DXC_DUPLICATION_MODE 2
  949. static int dual_x_carriage_mode = DEFAULT_DUAL_X_CARRIAGE_MODE;
  950. static float x_home_pos(int extruder) {
  951. if (extruder == 0)
  952. return base_home_pos(X_AXIS) + add_homeing[X_AXIS];
  953. else
  954. // In dual carriage mode the extruder offset provides an override of the
  955. // second X-carriage offset when homed - otherwise X2_HOME_POS is used.
  956. // This allow soft recalibration of the second extruder offset position without firmware reflash
  957. // (through the M218 command).
  958. return (extruder_offset[X_AXIS][1] > 0) ? extruder_offset[X_AXIS][1] : X2_HOME_POS;
  959. }
  960. static int x_home_dir(int extruder) {
  961. return (extruder == 0) ? X_HOME_DIR : X2_HOME_DIR;
  962. }
  963. static float inactive_extruder_x_pos = X2_MAX_POS; // used in mode 0 & 1
  964. static bool active_extruder_parked = false; // used in mode 1 & 2
  965. static float raised_parked_position[NUM_AXIS]; // used in mode 1
  966. static unsigned long delayed_move_time = 0; // used in mode 1
  967. static float duplicate_extruder_x_offset = DEFAULT_DUPLICATION_X_OFFSET; // used in mode 2
  968. static float duplicate_extruder_temp_offset = 0; // used in mode 2
  969. bool extruder_duplication_enabled = false; // used in mode 2
  970. #endif //DUAL_X_CARRIAGE
  971. static void axis_is_at_home(int axis) {
  972. #ifdef DUAL_X_CARRIAGE
  973. if (axis == X_AXIS) {
  974. if (active_extruder != 0) {
  975. current_position[X_AXIS] = x_home_pos(active_extruder);
  976. min_pos[X_AXIS] = X2_MIN_POS;
  977. max_pos[X_AXIS] = max(extruder_offset[X_AXIS][1], X2_MAX_POS);
  978. return;
  979. }
  980. else if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && active_extruder == 0) {
  981. current_position[X_AXIS] = base_home_pos(X_AXIS) + add_homeing[X_AXIS];
  982. min_pos[X_AXIS] = base_min_pos(X_AXIS) + add_homeing[X_AXIS];
  983. max_pos[X_AXIS] = min(base_max_pos(X_AXIS) + add_homeing[X_AXIS],
  984. max(extruder_offset[X_AXIS][1], X2_MAX_POS) - duplicate_extruder_x_offset);
  985. return;
  986. }
  987. }
  988. #endif
  989. current_position[axis] = base_home_pos(axis) + add_homeing[axis];
  990. min_pos[axis] = base_min_pos(axis) + add_homeing[axis];
  991. max_pos[axis] = base_max_pos(axis) + add_homeing[axis];
  992. }
  993. #ifdef ENABLE_AUTO_BED_LEVELING
  994. #ifdef ACCURATE_BED_LEVELING
  995. static void set_bed_level_equation_lsq(double *plane_equation_coefficients)
  996. {
  997. vector_3 planeNormal = vector_3(-plane_equation_coefficients[0], -plane_equation_coefficients[1], 1);
  998. planeNormal.debug("planeNormal");
  999. plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1000. //bedLevel.debug("bedLevel");
  1001. //plan_bed_level_matrix.debug("bed level before");
  1002. //vector_3 uncorrected_position = plan_get_position_mm();
  1003. //uncorrected_position.debug("position before");
  1004. vector_3 corrected_position = plan_get_position();
  1005. // corrected_position.debug("position after");
  1006. current_position[X_AXIS] = corrected_position.x;
  1007. current_position[Y_AXIS] = corrected_position.y;
  1008. current_position[Z_AXIS] = corrected_position.z;
  1009. // but the bed at 0 so we don't go below it.
  1010. current_position[Z_AXIS] = zprobe_zoffset; // in the lsq we reach here after raising the extruder due to the loop structure
  1011. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1012. }
  1013. #else
  1014. static void set_bed_level_equation(float z_at_xLeft_yFront, float z_at_xRight_yFront, float z_at_xLeft_yBack) {
  1015. plan_bed_level_matrix.set_to_identity();
  1016. vector_3 xLeftyFront = vector_3(LEFT_PROBE_BED_POSITION, FRONT_PROBE_BED_POSITION, z_at_xLeft_yFront);
  1017. vector_3 xLeftyBack = vector_3(LEFT_PROBE_BED_POSITION, BACK_PROBE_BED_POSITION, z_at_xLeft_yBack);
  1018. vector_3 xRightyFront = vector_3(RIGHT_PROBE_BED_POSITION, FRONT_PROBE_BED_POSITION, z_at_xRight_yFront);
  1019. vector_3 xPositive = (xRightyFront - xLeftyFront).get_normal();
  1020. vector_3 yPositive = (xLeftyBack - xLeftyFront).get_normal();
  1021. vector_3 planeNormal = vector_3::cross(xPositive, yPositive).get_normal();
  1022. //planeNormal.debug("planeNormal");
  1023. //yPositive.debug("yPositive");
  1024. plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1025. //bedLevel.debug("bedLevel");
  1026. //plan_bed_level_matrix.debug("bed level before");
  1027. //vector_3 uncorrected_position = plan_get_position_mm();
  1028. //uncorrected_position.debug("position before");
  1029. // and set our bed level equation to do the right thing
  1030. //plan_bed_level_matrix.debug("bed level after");
  1031. vector_3 corrected_position = plan_get_position();
  1032. //corrected_position.debug("position after");
  1033. current_position[X_AXIS] = corrected_position.x;
  1034. current_position[Y_AXIS] = corrected_position.y;
  1035. current_position[Z_AXIS] = corrected_position.z;
  1036. // but the bed at 0 so we don't go below it.
  1037. current_position[Z_AXIS] = zprobe_zoffset;
  1038. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1039. }
  1040. #endif // ACCURATE_BED_LEVELING
  1041. static void run_z_probe() {
  1042. plan_bed_level_matrix.set_to_identity();
  1043. feedrate = homing_feedrate[Z_AXIS];
  1044. // move down until you find the bed
  1045. float zPosition = -10;
  1046. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1047. st_synchronize();
  1048. // we have to let the planner know where we are right now as it is not where we said to go.
  1049. zPosition = st_get_position_mm(Z_AXIS);
  1050. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS]);
  1051. // move up the retract distance
  1052. zPosition += home_retract_mm(Z_AXIS);
  1053. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1054. st_synchronize();
  1055. // move back down slowly to find bed
  1056. feedrate = homing_feedrate[Z_AXIS]/4;
  1057. zPosition -= home_retract_mm(Z_AXIS) * 2;
  1058. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1059. st_synchronize();
  1060. current_position[Z_AXIS] = st_get_position_mm(Z_AXIS);
  1061. // make sure the planner knows where we are as it may be a bit different than we last said to move to
  1062. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1063. }
  1064. static void do_blocking_move_to(float x, float y, float z) {
  1065. float oldFeedRate = feedrate;
  1066. feedrate = XY_TRAVEL_SPEED;
  1067. current_position[X_AXIS] = x;
  1068. current_position[Y_AXIS] = y;
  1069. current_position[Z_AXIS] = z;
  1070. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], feedrate/60, active_extruder);
  1071. st_synchronize();
  1072. feedrate = oldFeedRate;
  1073. }
  1074. static void do_blocking_move_relative(float offset_x, float offset_y, float offset_z) {
  1075. do_blocking_move_to(current_position[X_AXIS] + offset_x, current_position[Y_AXIS] + offset_y, current_position[Z_AXIS] + offset_z);
  1076. }
  1077. static void setup_for_endstop_move() {
  1078. saved_feedrate = feedrate;
  1079. saved_feedmultiply = feedmultiply;
  1080. feedmultiply = 100;
  1081. previous_millis_cmd = millis();
  1082. enable_endstops(true);
  1083. }
  1084. static void clean_up_after_endstop_move() {
  1085. #ifdef ENDSTOPS_ONLY_FOR_HOMING
  1086. enable_endstops(false);
  1087. #endif
  1088. feedrate = saved_feedrate;
  1089. feedmultiply = saved_feedmultiply;
  1090. previous_millis_cmd = millis();
  1091. }
  1092. static void engage_z_probe() {
  1093. // Engage Z Servo endstop if enabled
  1094. #ifdef SERVO_ENDSTOPS
  1095. if (servo_endstops[Z_AXIS] > -1) {
  1096. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  1097. servos[servo_endstops[Z_AXIS]].attach(0);
  1098. #endif
  1099. servos[servo_endstops[Z_AXIS]].write(servo_endstop_angles[Z_AXIS * 2]);
  1100. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  1101. delay(PROBE_SERVO_DEACTIVATION_DELAY);
  1102. servos[servo_endstops[Z_AXIS]].detach();
  1103. #endif
  1104. }
  1105. #endif
  1106. }
  1107. static void retract_z_probe() {
  1108. // Retract Z Servo endstop if enabled
  1109. #ifdef SERVO_ENDSTOPS
  1110. if (servo_endstops[Z_AXIS] > -1) {
  1111. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  1112. servos[servo_endstops[Z_AXIS]].attach(0);
  1113. #endif
  1114. servos[servo_endstops[Z_AXIS]].write(servo_endstop_angles[Z_AXIS * 2 + 1]);
  1115. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  1116. delay(PROBE_SERVO_DEACTIVATION_DELAY);
  1117. servos[servo_endstops[Z_AXIS]].detach();
  1118. #endif
  1119. }
  1120. #endif
  1121. }
  1122. #endif // #ifdef ENABLE_AUTO_BED_LEVELING
  1123. static void homeaxis(int axis) {
  1124. #define HOMEAXIS_DO(LETTER) \
  1125. ((LETTER##_MIN_PIN > -1 && LETTER##_HOME_DIR==-1) || (LETTER##_MAX_PIN > -1 && LETTER##_HOME_DIR==1))
  1126. if (axis==X_AXIS ? HOMEAXIS_DO(X) :
  1127. axis==Y_AXIS ? HOMEAXIS_DO(Y) :
  1128. axis==Z_AXIS ? HOMEAXIS_DO(Z) :
  1129. 0) {
  1130. int axis_home_dir = home_dir(axis);
  1131. #ifdef DUAL_X_CARRIAGE
  1132. if (axis == X_AXIS)
  1133. axis_home_dir = x_home_dir(active_extruder);
  1134. #endif
  1135. current_position[axis] = 0;
  1136. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1137. // Engage Servo endstop if enabled
  1138. #ifdef SERVO_ENDSTOPS
  1139. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  1140. if (axis==Z_AXIS) {
  1141. engage_z_probe();
  1142. }
  1143. else
  1144. #endif
  1145. if (servo_endstops[axis] > -1) {
  1146. servos[servo_endstops[axis]].write(servo_endstop_angles[axis * 2]);
  1147. }
  1148. #endif
  1149. destination[axis] = 1.5 * max_length(axis) * axis_home_dir;
  1150. feedrate = homing_feedrate[axis];
  1151. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1152. st_synchronize();
  1153. current_position[axis] = 0;
  1154. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1155. destination[axis] = -home_retract_mm(axis) * axis_home_dir;
  1156. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1157. st_synchronize();
  1158. destination[axis] = 2*home_retract_mm(axis) * axis_home_dir;
  1159. #ifdef DELTA
  1160. feedrate = homing_feedrate[axis]/10;
  1161. #else
  1162. feedrate = homing_feedrate[axis]/2 ;
  1163. #endif
  1164. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1165. st_synchronize();
  1166. #ifdef DELTA
  1167. // retrace by the amount specified in endstop_adj
  1168. if (endstop_adj[axis] * axis_home_dir < 0) {
  1169. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1170. destination[axis] = endstop_adj[axis];
  1171. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1172. st_synchronize();
  1173. }
  1174. #endif
  1175. axis_is_at_home(axis);
  1176. destination[axis] = current_position[axis];
  1177. feedrate = 0.0;
  1178. endstops_hit_on_purpose();
  1179. axis_known_position[axis] = true;
  1180. // Retract Servo endstop if enabled
  1181. #ifdef SERVO_ENDSTOPS
  1182. if (servo_endstops[axis] > -1) {
  1183. servos[servo_endstops[axis]].write(servo_endstop_angles[axis * 2 + 1]);
  1184. }
  1185. #endif
  1186. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  1187. if (axis==Z_AXIS) retract_z_probe();
  1188. #endif
  1189. }
  1190. }
  1191. #define HOMEAXIS(LETTER) homeaxis(LETTER##_AXIS)
  1192. void process_commands()
  1193. {
  1194. unsigned long codenum; //throw away variable
  1195. char *starpos = NULL;
  1196. #ifdef ENABLE_AUTO_BED_LEVELING
  1197. float x_tmp, y_tmp, z_tmp, real_z;
  1198. #endif
  1199. if(code_seen('G'))
  1200. {
  1201. switch((int)code_value())
  1202. {
  1203. case 0: // G0 -> G1
  1204. case 1: // G1
  1205. if(Stopped == false) {
  1206. get_coordinates(); // For X Y Z E F
  1207. prepare_move();
  1208. //ClearToSend();
  1209. return;
  1210. }
  1211. //break;
  1212. case 2: // G2 - CW ARC
  1213. if(Stopped == false) {
  1214. get_arc_coordinates();
  1215. prepare_arc_move(true);
  1216. return;
  1217. }
  1218. case 3: // G3 - CCW ARC
  1219. if(Stopped == false) {
  1220. get_arc_coordinates();
  1221. prepare_arc_move(false);
  1222. return;
  1223. }
  1224. case 4: // G4 dwell
  1225. LCD_MESSAGEPGM(MSG_DWELL);
  1226. codenum = 0;
  1227. if(code_seen('P')) codenum = code_value(); // milliseconds to wait
  1228. if(code_seen('S')) codenum = code_value() * 1000; // seconds to wait
  1229. st_synchronize();
  1230. codenum += millis(); // keep track of when we started waiting
  1231. previous_millis_cmd = millis();
  1232. while(millis() < codenum ){
  1233. manage_heater();
  1234. manage_inactivity();
  1235. lcd_update();
  1236. }
  1237. break;
  1238. #ifdef FWRETRACT
  1239. case 10: // G10 retract
  1240. if(!retracted)
  1241. {
  1242. destination[X_AXIS]=current_position[X_AXIS];
  1243. destination[Y_AXIS]=current_position[Y_AXIS];
  1244. destination[Z_AXIS]=current_position[Z_AXIS];
  1245. current_position[Z_AXIS]+=-retract_zlift;
  1246. destination[E_AXIS]=current_position[E_AXIS]-retract_length;
  1247. feedrate=retract_feedrate;
  1248. retracted=true;
  1249. prepare_move();
  1250. }
  1251. break;
  1252. case 11: // G11 retract_recover
  1253. if(retracted)
  1254. {
  1255. destination[X_AXIS]=current_position[X_AXIS];
  1256. destination[Y_AXIS]=current_position[Y_AXIS];
  1257. destination[Z_AXIS]=current_position[Z_AXIS];
  1258. current_position[Z_AXIS]+=retract_zlift;
  1259. destination[E_AXIS]=current_position[E_AXIS]+retract_length+retract_recover_length;
  1260. feedrate=retract_recover_feedrate;
  1261. retracted=false;
  1262. prepare_move();
  1263. }
  1264. break;
  1265. #endif //FWRETRACT
  1266. case 28: //G28 Home all Axis one at a time
  1267. #ifdef ENABLE_AUTO_BED_LEVELING
  1268. plan_bed_level_matrix.set_to_identity(); //Reset the plane ("erase" all leveling data)
  1269. #endif //ENABLE_AUTO_BED_LEVELING
  1270. saved_feedrate = feedrate;
  1271. saved_feedmultiply = feedmultiply;
  1272. feedmultiply = 100;
  1273. previous_millis_cmd = millis();
  1274. enable_endstops(true);
  1275. for(int8_t i=0; i < NUM_AXIS; i++) {
  1276. destination[i] = current_position[i];
  1277. }
  1278. feedrate = 0.0;
  1279. #ifdef DELTA
  1280. // A delta can only safely home all axis at the same time
  1281. // all axis have to home at the same time
  1282. // Move all carriages up together until the first endstop is hit.
  1283. current_position[X_AXIS] = 0;
  1284. current_position[Y_AXIS] = 0;
  1285. current_position[Z_AXIS] = 0;
  1286. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1287. destination[X_AXIS] = 3 * Z_MAX_LENGTH;
  1288. destination[Y_AXIS] = 3 * Z_MAX_LENGTH;
  1289. destination[Z_AXIS] = 3 * Z_MAX_LENGTH;
  1290. feedrate = 1.732 * homing_feedrate[X_AXIS];
  1291. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1292. st_synchronize();
  1293. endstops_hit_on_purpose();
  1294. current_position[X_AXIS] = destination[X_AXIS];
  1295. current_position[Y_AXIS] = destination[Y_AXIS];
  1296. current_position[Z_AXIS] = destination[Z_AXIS];
  1297. // take care of back off and rehome now we are all at the top
  1298. HOMEAXIS(X);
  1299. HOMEAXIS(Y);
  1300. HOMEAXIS(Z);
  1301. calculate_delta(current_position);
  1302. plan_set_position(delta[X_AXIS], delta[Y_AXIS], delta[Z_AXIS], current_position[E_AXIS]);
  1303. #else // NOT DELTA
  1304. home_all_axis = !((code_seen(axis_codes[0])) || (code_seen(axis_codes[1])) || (code_seen(axis_codes[2])));
  1305. #if Z_HOME_DIR > 0 // If homing away from BED do Z first
  1306. if((home_all_axis) || (code_seen(axis_codes[Z_AXIS]))) {
  1307. HOMEAXIS(Z);
  1308. }
  1309. #endif
  1310. #ifdef QUICK_HOME
  1311. if((home_all_axis)||( code_seen(axis_codes[X_AXIS]) && code_seen(axis_codes[Y_AXIS])) ) //first diagonal move
  1312. {
  1313. current_position[X_AXIS] = 0;current_position[Y_AXIS] = 0;
  1314. #ifndef DUAL_X_CARRIAGE
  1315. int x_axis_home_dir = home_dir(X_AXIS);
  1316. #else
  1317. int x_axis_home_dir = x_home_dir(active_extruder);
  1318. extruder_duplication_enabled = false;
  1319. #endif
  1320. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1321. destination[X_AXIS] = 1.5 * max_length(X_AXIS) * x_axis_home_dir;destination[Y_AXIS] = 1.5 * max_length(Y_AXIS) * home_dir(Y_AXIS);
  1322. feedrate = homing_feedrate[X_AXIS];
  1323. if(homing_feedrate[Y_AXIS]<feedrate)
  1324. feedrate =homing_feedrate[Y_AXIS];
  1325. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1326. st_synchronize();
  1327. axis_is_at_home(X_AXIS);
  1328. axis_is_at_home(Y_AXIS);
  1329. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1330. destination[X_AXIS] = current_position[X_AXIS];
  1331. destination[Y_AXIS] = current_position[Y_AXIS];
  1332. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1333. feedrate = 0.0;
  1334. st_synchronize();
  1335. endstops_hit_on_purpose();
  1336. current_position[X_AXIS] = destination[X_AXIS];
  1337. current_position[Y_AXIS] = destination[Y_AXIS];
  1338. current_position[Z_AXIS] = destination[Z_AXIS];
  1339. }
  1340. #endif
  1341. if((home_all_axis) || (code_seen(axis_codes[X_AXIS])))
  1342. {
  1343. #ifdef DUAL_X_CARRIAGE
  1344. int tmp_extruder = active_extruder;
  1345. extruder_duplication_enabled = false;
  1346. active_extruder = !active_extruder;
  1347. HOMEAXIS(X);
  1348. inactive_extruder_x_pos = current_position[X_AXIS];
  1349. active_extruder = tmp_extruder;
  1350. HOMEAXIS(X);
  1351. // reset state used by the different modes
  1352. memcpy(raised_parked_position, current_position, sizeof(raised_parked_position));
  1353. delayed_move_time = 0;
  1354. active_extruder_parked = true;
  1355. #else
  1356. HOMEAXIS(X);
  1357. #endif
  1358. }
  1359. if((home_all_axis) || (code_seen(axis_codes[Y_AXIS]))) {
  1360. HOMEAXIS(Y);
  1361. }
  1362. if(code_seen(axis_codes[X_AXIS]))
  1363. {
  1364. if(code_value_long() != 0) {
  1365. current_position[X_AXIS]=code_value()+add_homeing[0];
  1366. }
  1367. }
  1368. if(code_seen(axis_codes[Y_AXIS])) {
  1369. if(code_value_long() != 0) {
  1370. current_position[Y_AXIS]=code_value()+add_homeing[1];
  1371. }
  1372. }
  1373. #if Z_HOME_DIR < 0 // If homing towards BED do Z last
  1374. #ifndef Z_SAFE_HOMING
  1375. if((home_all_axis) || (code_seen(axis_codes[Z_AXIS]))) {
  1376. #if defined (Z_RAISE_BEFORE_HOMING) && (Z_RAISE_BEFORE_HOMING > 0)
  1377. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  1378. feedrate = max_feedrate[Z_AXIS];
  1379. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate, active_extruder);
  1380. st_synchronize();
  1381. #endif
  1382. HOMEAXIS(Z);
  1383. }
  1384. #else // Z Safe mode activated.
  1385. if(home_all_axis) {
  1386. destination[X_AXIS] = round(Z_SAFE_HOMING_X_POINT - X_PROBE_OFFSET_FROM_EXTRUDER);
  1387. destination[Y_AXIS] = round(Z_SAFE_HOMING_Y_POINT - Y_PROBE_OFFSET_FROM_EXTRUDER);
  1388. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  1389. feedrate = XY_TRAVEL_SPEED;
  1390. current_position[Z_AXIS] = 0;
  1391. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1392. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate, active_extruder);
  1393. st_synchronize();
  1394. current_position[X_AXIS] = destination[X_AXIS];
  1395. current_position[Y_AXIS] = destination[Y_AXIS];
  1396. HOMEAXIS(Z);
  1397. }
  1398. // Let's see if X and Y are homed and probe is inside bed area.
  1399. if(code_seen(axis_codes[Z_AXIS])) {
  1400. if ( (axis_known_position[X_AXIS]) && (axis_known_position[Y_AXIS]) \
  1401. && (current_position[X_AXIS]+X_PROBE_OFFSET_FROM_EXTRUDER >= X_MIN_POS) \
  1402. && (current_position[X_AXIS]+X_PROBE_OFFSET_FROM_EXTRUDER <= X_MAX_POS) \
  1403. && (current_position[Y_AXIS]+Y_PROBE_OFFSET_FROM_EXTRUDER >= Y_MIN_POS) \
  1404. && (current_position[Y_AXIS]+Y_PROBE_OFFSET_FROM_EXTRUDER <= Y_MAX_POS)) {
  1405. current_position[Z_AXIS] = 0;
  1406. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1407. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  1408. feedrate = max_feedrate[Z_AXIS];
  1409. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate, active_extruder);
  1410. st_synchronize();
  1411. HOMEAXIS(Z);
  1412. } else if (!((axis_known_position[X_AXIS]) && (axis_known_position[Y_AXIS]))) {
  1413. LCD_MESSAGEPGM(MSG_POSITION_UNKNOWN);
  1414. SERIAL_ECHO_START;
  1415. SERIAL_ECHOLNPGM(MSG_POSITION_UNKNOWN);
  1416. } else {
  1417. LCD_MESSAGEPGM(MSG_ZPROBE_OUT);
  1418. SERIAL_ECHO_START;
  1419. SERIAL_ECHOLNPGM(MSG_ZPROBE_OUT);
  1420. }
  1421. }
  1422. #endif
  1423. #endif
  1424. if(code_seen(axis_codes[Z_AXIS])) {
  1425. if(code_value_long() != 0) {
  1426. current_position[Z_AXIS]=code_value()+add_homeing[2];
  1427. }
  1428. }
  1429. #ifdef ENABLE_AUTO_BED_LEVELING
  1430. if((home_all_axis) || (code_seen(axis_codes[Z_AXIS]))) {
  1431. current_position[Z_AXIS] += zprobe_zoffset; //Add Z_Probe offset (the distance is negative)
  1432. }
  1433. #endif
  1434. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1435. #endif // else DELTA
  1436. #ifdef ENDSTOPS_ONLY_FOR_HOMING
  1437. enable_endstops(false);
  1438. #endif
  1439. feedrate = saved_feedrate;
  1440. feedmultiply = saved_feedmultiply;
  1441. previous_millis_cmd = millis();
  1442. endstops_hit_on_purpose();
  1443. break;
  1444. #ifdef ENABLE_AUTO_BED_LEVELING
  1445. case 29: // G29 Detailed Z-Probe, probes the bed at 3 points.
  1446. {
  1447. #if Z_MIN_PIN == -1
  1448. #error "You must have a Z_MIN endstop in order to enable Auto Bed Leveling feature!!! Z_MIN_PIN must point to a valid hardware pin."
  1449. #endif
  1450. st_synchronize();
  1451. // make sure the bed_level_rotation_matrix is identity or the planner will get it incorectly
  1452. //vector_3 corrected_position = plan_get_position_mm();
  1453. //corrected_position.debug("position before G29");
  1454. plan_bed_level_matrix.set_to_identity();
  1455. vector_3 uncorrected_position = plan_get_position();
  1456. //uncorrected_position.debug("position durring G29");
  1457. current_position[X_AXIS] = uncorrected_position.x;
  1458. current_position[Y_AXIS] = uncorrected_position.y;
  1459. current_position[Z_AXIS] = uncorrected_position.z;
  1460. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1461. setup_for_endstop_move();
  1462. feedrate = homing_feedrate[Z_AXIS];
  1463. #ifdef ACCURATE_BED_LEVELING
  1464. int xGridSpacing = (RIGHT_PROBE_BED_POSITION - LEFT_PROBE_BED_POSITION) / (ACCURATE_BED_LEVELING_POINTS-1);
  1465. int yGridSpacing = (BACK_PROBE_BED_POSITION - FRONT_PROBE_BED_POSITION) / (ACCURATE_BED_LEVELING_POINTS-1);
  1466. // solve the plane equation ax + by + d = z
  1467. // A is the matrix with rows [x y 1] for all the probed points
  1468. // B is the vector of the Z positions
  1469. // the normal vector to the plane is formed by the coefficients of the plane equation in the standard form, which is Vx*x+Vy*y+Vz*z+d = 0
  1470. // so Vx = -a Vy = -b Vz = 1 (we want the vector facing towards positive Z
  1471. // "A" matrix of the linear system of equations
  1472. double eqnAMatrix[ACCURATE_BED_LEVELING_POINTS*ACCURATE_BED_LEVELING_POINTS*3];
  1473. // "B" vector of Z points
  1474. double eqnBVector[ACCURATE_BED_LEVELING_POINTS*ACCURATE_BED_LEVELING_POINTS];
  1475. int probePointCounter = 0;
  1476. bool zig = true;
  1477. for (int yProbe=FRONT_PROBE_BED_POSITION; yProbe <= BACK_PROBE_BED_POSITION; yProbe += yGridSpacing)
  1478. {
  1479. int xProbe, xInc;
  1480. if (zig)
  1481. {
  1482. xProbe = LEFT_PROBE_BED_POSITION;
  1483. //xEnd = RIGHT_PROBE_BED_POSITION;
  1484. xInc = xGridSpacing;
  1485. zig = false;
  1486. } else // zag
  1487. {
  1488. xProbe = RIGHT_PROBE_BED_POSITION;
  1489. //xEnd = LEFT_PROBE_BED_POSITION;
  1490. xInc = -xGridSpacing;
  1491. zig = true;
  1492. }
  1493. for (int xCount=0; xCount < ACCURATE_BED_LEVELING_POINTS; xCount++)
  1494. {
  1495. if (probePointCounter == 0)
  1496. {
  1497. // raise before probing
  1498. do_blocking_move_to(current_position[X_AXIS], current_position[Y_AXIS], Z_RAISE_BEFORE_PROBING);
  1499. } else
  1500. {
  1501. // raise extruder
  1502. do_blocking_move_to(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS] + Z_RAISE_BETWEEN_PROBINGS);
  1503. }
  1504. do_blocking_move_to(xProbe - X_PROBE_OFFSET_FROM_EXTRUDER, yProbe - Y_PROBE_OFFSET_FROM_EXTRUDER, current_position[Z_AXIS]);
  1505. engage_z_probe(); // Engage Z Servo endstop if available
  1506. run_z_probe();
  1507. eqnBVector[probePointCounter] = current_position[Z_AXIS];
  1508. retract_z_probe();
  1509. SERIAL_PROTOCOLPGM("Bed x: ");
  1510. SERIAL_PROTOCOL(xProbe);
  1511. SERIAL_PROTOCOLPGM(" y: ");
  1512. SERIAL_PROTOCOL(yProbe);
  1513. SERIAL_PROTOCOLPGM(" z: ");
  1514. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  1515. SERIAL_PROTOCOLPGM("\n");
  1516. eqnAMatrix[probePointCounter + 0*ACCURATE_BED_LEVELING_POINTS*ACCURATE_BED_LEVELING_POINTS] = xProbe;
  1517. eqnAMatrix[probePointCounter + 1*ACCURATE_BED_LEVELING_POINTS*ACCURATE_BED_LEVELING_POINTS] = yProbe;
  1518. eqnAMatrix[probePointCounter + 2*ACCURATE_BED_LEVELING_POINTS*ACCURATE_BED_LEVELING_POINTS] = 1;
  1519. probePointCounter++;
  1520. xProbe += xInc;
  1521. }
  1522. }
  1523. clean_up_after_endstop_move();
  1524. // solve lsq problem
  1525. double *plane_equation_coefficients = qr_solve(ACCURATE_BED_LEVELING_POINTS*ACCURATE_BED_LEVELING_POINTS, 3, eqnAMatrix, eqnBVector);
  1526. SERIAL_PROTOCOLPGM("Eqn coefficients: a: ");
  1527. SERIAL_PROTOCOL(plane_equation_coefficients[0]);
  1528. SERIAL_PROTOCOLPGM(" b: ");
  1529. SERIAL_PROTOCOL(plane_equation_coefficients[1]);
  1530. SERIAL_PROTOCOLPGM(" d: ");
  1531. SERIAL_PROTOCOLLN(plane_equation_coefficients[2]);
  1532. set_bed_level_equation_lsq(plane_equation_coefficients);
  1533. free(plane_equation_coefficients);
  1534. #else // ACCURATE_BED_LEVELING not defined
  1535. // prob 1
  1536. do_blocking_move_to(current_position[X_AXIS], current_position[Y_AXIS], Z_RAISE_BEFORE_PROBING);
  1537. do_blocking_move_to(LEFT_PROBE_BED_POSITION - X_PROBE_OFFSET_FROM_EXTRUDER, BACK_PROBE_BED_POSITION - Y_PROBE_OFFSET_FROM_EXTRUDER, current_position[Z_AXIS]);
  1538. engage_z_probe(); // Engage Z Servo endstop if available
  1539. run_z_probe();
  1540. float z_at_xLeft_yBack = current_position[Z_AXIS];
  1541. retract_z_probe();
  1542. SERIAL_PROTOCOLPGM("Bed x: ");
  1543. SERIAL_PROTOCOL(LEFT_PROBE_BED_POSITION);
  1544. SERIAL_PROTOCOLPGM(" y: ");
  1545. SERIAL_PROTOCOL(BACK_PROBE_BED_POSITION);
  1546. SERIAL_PROTOCOLPGM(" z: ");
  1547. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  1548. SERIAL_PROTOCOLPGM("\n");
  1549. // prob 2
  1550. do_blocking_move_to(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS] + Z_RAISE_BETWEEN_PROBINGS);
  1551. do_blocking_move_to(LEFT_PROBE_BED_POSITION - X_PROBE_OFFSET_FROM_EXTRUDER, FRONT_PROBE_BED_POSITION - Y_PROBE_OFFSET_FROM_EXTRUDER, current_position[Z_AXIS]);
  1552. engage_z_probe(); // Engage Z Servo endstop if available
  1553. run_z_probe();
  1554. float z_at_xLeft_yFront = current_position[Z_AXIS];
  1555. retract_z_probe();
  1556. SERIAL_PROTOCOLPGM("Bed x: ");
  1557. SERIAL_PROTOCOL(LEFT_PROBE_BED_POSITION);
  1558. SERIAL_PROTOCOLPGM(" y: ");
  1559. SERIAL_PROTOCOL(FRONT_PROBE_BED_POSITION);
  1560. SERIAL_PROTOCOLPGM(" z: ");
  1561. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  1562. SERIAL_PROTOCOLPGM("\n");
  1563. // prob 3
  1564. do_blocking_move_to(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS] + Z_RAISE_BETWEEN_PROBINGS);
  1565. // the current position will be updated by the blocking move so the head will not lower on this next call.
  1566. do_blocking_move_to(RIGHT_PROBE_BED_POSITION - X_PROBE_OFFSET_FROM_EXTRUDER, FRONT_PROBE_BED_POSITION - Y_PROBE_OFFSET_FROM_EXTRUDER, current_position[Z_AXIS]);
  1567. engage_z_probe(); // Engage Z Servo endstop if available
  1568. run_z_probe();
  1569. float z_at_xRight_yFront = current_position[Z_AXIS];
  1570. retract_z_probe(); // Retract Z Servo endstop if available
  1571. SERIAL_PROTOCOLPGM("Bed x: ");
  1572. SERIAL_PROTOCOL(RIGHT_PROBE_BED_POSITION);
  1573. SERIAL_PROTOCOLPGM(" y: ");
  1574. SERIAL_PROTOCOL(FRONT_PROBE_BED_POSITION);
  1575. SERIAL_PROTOCOLPGM(" z: ");
  1576. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  1577. SERIAL_PROTOCOLPGM("\n");
  1578. clean_up_after_endstop_move();
  1579. set_bed_level_equation(z_at_xLeft_yFront, z_at_xRight_yFront, z_at_xLeft_yBack);
  1580. #endif // ACCURATE_BED_LEVELING
  1581. st_synchronize();
  1582. // The following code correct the Z height difference from z-probe position and hotend tip position.
  1583. // The Z height on homing is measured by Z-Probe, but the probe is quite far from the hotend.
  1584. // When the bed is uneven, this height must be corrected.
  1585. real_z = float(st_get_position(Z_AXIS))/axis_steps_per_unit[Z_AXIS]; //get the real Z (since the auto bed leveling is already correcting the plane)
  1586. x_tmp = current_position[X_AXIS] + X_PROBE_OFFSET_FROM_EXTRUDER;
  1587. y_tmp = current_position[Y_AXIS] + Y_PROBE_OFFSET_FROM_EXTRUDER;
  1588. z_tmp = current_position[Z_AXIS];
  1589. apply_rotation_xyz(plan_bed_level_matrix, x_tmp, y_tmp, z_tmp); //Apply the correction sending the probe offset
  1590. current_position[Z_AXIS] = z_tmp - real_z + current_position[Z_AXIS]; //The difference is added to current position and sent to planner.
  1591. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1592. }
  1593. break;
  1594. case 30: // G30 Single Z Probe
  1595. {
  1596. engage_z_probe(); // Engage Z Servo endstop if available
  1597. st_synchronize();
  1598. // TODO: make sure the bed_level_rotation_matrix is identity or the planner will get set incorectly
  1599. setup_for_endstop_move();
  1600. feedrate = homing_feedrate[Z_AXIS];
  1601. run_z_probe();
  1602. SERIAL_PROTOCOLPGM("Bed Position X: ");
  1603. SERIAL_PROTOCOL(current_position[X_AXIS]);
  1604. SERIAL_PROTOCOLPGM(" Y: ");
  1605. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  1606. SERIAL_PROTOCOLPGM(" Z: ");
  1607. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  1608. SERIAL_PROTOCOLPGM("\n");
  1609. clean_up_after_endstop_move();
  1610. retract_z_probe(); // Retract Z Servo endstop if available
  1611. }
  1612. break;
  1613. #endif // ENABLE_AUTO_BED_LEVELING
  1614. case 90: // G90
  1615. relative_mode = false;
  1616. break;
  1617. case 91: // G91
  1618. relative_mode = true;
  1619. break;
  1620. case 92: // G92
  1621. if(!code_seen(axis_codes[E_AXIS]))
  1622. st_synchronize();
  1623. for(int8_t i=0; i < NUM_AXIS; i++)
  1624. {
  1625. if(code_seen(axis_codes[i]))
  1626. {
  1627. if(i == E_AXIS) {
  1628. current_position[i] = code_value();
  1629. plan_set_e_position(current_position[E_AXIS]);
  1630. }
  1631. else
  1632. {
  1633. if (i == Z_AXIS)
  1634. {
  1635. axis_known_position[Z_AXIS] = true;
  1636. }
  1637. current_position[i] = code_value()+add_homeing[i];
  1638. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1639. }
  1640. }
  1641. }
  1642. break;
  1643. }
  1644. }
  1645. else if(code_seen('M'))
  1646. {
  1647. switch( (int)code_value() )
  1648. {
  1649. #ifdef ULTIPANEL
  1650. case 0: // M0 - Unconditional stop - Wait for user button press on LCD
  1651. case 1: // M1 - Conditional stop - Wait for user button press on LCD
  1652. {
  1653. LCD_MESSAGEPGM(MSG_USERWAIT);
  1654. codenum = 0;
  1655. if(code_seen('P')) codenum = code_value(); // milliseconds to wait
  1656. if(code_seen('S')) codenum = code_value() * 1000; // seconds to wait
  1657. st_synchronize();
  1658. previous_millis_cmd = millis();
  1659. if (codenum > 0){
  1660. codenum += millis(); // keep track of when we started waiting
  1661. while(millis() < codenum && !lcd_clicked()){
  1662. manage_heater();
  1663. manage_inactivity();
  1664. lcd_update();
  1665. }
  1666. }else{
  1667. while(!lcd_clicked()){
  1668. manage_heater();
  1669. manage_inactivity();
  1670. lcd_update();
  1671. }
  1672. }
  1673. LCD_MESSAGEPGM(MSG_RESUMING);
  1674. }
  1675. break;
  1676. #endif
  1677. case 17:
  1678. LCD_MESSAGEPGM(MSG_NO_MOVE);
  1679. enable_x();
  1680. enable_y();
  1681. enable_z();
  1682. enable_e0();
  1683. enable_e1();
  1684. enable_e2();
  1685. break;
  1686. #ifdef SDSUPPORT
  1687. case 20: // M20 - list SD card
  1688. SERIAL_PROTOCOLLNPGM(MSG_BEGIN_FILE_LIST);
  1689. card.ls();
  1690. SERIAL_PROTOCOLLNPGM(MSG_END_FILE_LIST);
  1691. break;
  1692. case 21: // M21 - init SD card
  1693. card.initsd();
  1694. #if defined(SDSUPPORT) && defined(POWEROFF_SAVE_SD_FILE)
  1695. init_power_off_info();
  1696. #endif
  1697. break;
  1698. case 22: //M22 - release SD card
  1699. card.release();
  1700. break;
  1701. case 23: //M23 - Select file
  1702. starpos = (strchr(strchr_pointer + 4,'*'));
  1703. if(starpos!=NULL)
  1704. *(starpos-1)='\0';
  1705. card.openFile(strchr_pointer + 4,true);
  1706. break;
  1707. case 24: //M24 - Start SD print
  1708. #ifdef SDSUPPORT
  1709. #ifdef POWEROFF_SAVE_SD_FILE
  1710. card.removePowerOffFile();
  1711. #endif
  1712. #endif
  1713. card.startFileprint();
  1714. starttime=millis();
  1715. break;
  1716. case 25: //M25 - Pause SD print
  1717. card.pauseSDPrint();
  1718. break;
  1719. case 26: //M26 - Set SD index
  1720. if(card.cardOK && code_seen('S')) {
  1721. card.setIndex(code_value_long());
  1722. }
  1723. break;
  1724. case 27: //M27 - Get SD status
  1725. card.getStatus();
  1726. break;
  1727. case 28: //M28 - Start SD write
  1728. starpos = (strchr(strchr_pointer + 4,'*'));
  1729. if(starpos != NULL){
  1730. char* npos = strchr(cmdbuffer[bufindr], 'N');
  1731. strchr_pointer = strchr(npos,' ') + 1;
  1732. *(starpos-1) = '\0';
  1733. }
  1734. card.openFile(strchr_pointer+4,false);
  1735. break;
  1736. case 29: //M29 - Stop SD write
  1737. //processed in write to file routine above
  1738. //card,saving = false;
  1739. break;
  1740. case 30: //M30 <filename> Delete File
  1741. if (card.cardOK){
  1742. card.closefile();
  1743. starpos = (strchr(strchr_pointer + 4,'*'));
  1744. if(starpos != NULL){
  1745. char* npos = strchr(cmdbuffer[bufindr], 'N');
  1746. strchr_pointer = strchr(npos,' ') + 1;
  1747. *(starpos-1) = '\0';
  1748. }
  1749. card.removeFile(strchr_pointer + 4);
  1750. }
  1751. break;
  1752. case 32: //M32 - Select file and start SD print
  1753. {
  1754. if(card.sdprinting) {
  1755. st_synchronize();
  1756. }
  1757. starpos = (strchr(strchr_pointer + 4,'*'));
  1758. char* namestartpos = (strchr(strchr_pointer + 4,'!')); //find ! to indicate filename string start.
  1759. if(namestartpos==NULL)
  1760. {
  1761. namestartpos=strchr_pointer + 4; //default name position, 4 letters after the M
  1762. }
  1763. else
  1764. namestartpos++; //to skip the '!'
  1765. if(starpos!=NULL)
  1766. *(starpos-1)='\0';
  1767. bool call_procedure=(code_seen('P'));
  1768. if(strchr_pointer>namestartpos)
  1769. call_procedure=false; //false alert, 'P' found within filename
  1770. if( card.cardOK )
  1771. {
  1772. card.openFile(namestartpos,true,!call_procedure);
  1773. if(code_seen('S'))
  1774. if(strchr_pointer<namestartpos) //only if "S" is occuring _before_ the filename
  1775. card.setIndex(code_value_long());
  1776. card.startFileprint();
  1777. if(!call_procedure)
  1778. starttime=millis(); //procedure calls count as normal print time.
  1779. }
  1780. } break;
  1781. case 928: //M928 - Start SD write
  1782. starpos = (strchr(strchr_pointer + 5,'*'));
  1783. if(starpos != NULL){
  1784. char* npos = strchr(cmdbuffer[bufindr], 'N');
  1785. strchr_pointer = strchr(npos,' ') + 1;
  1786. *(starpos-1) = '\0';
  1787. }
  1788. card.openLogFile(strchr_pointer+5);
  1789. break;
  1790. #endif //SDSUPPORT
  1791. case 31: //M31 take time since the start of the SD print or an M109 command
  1792. {
  1793. stoptime=millis();
  1794. char time[30];
  1795. unsigned long t=(stoptime-starttime)/1000;
  1796. int sec,min;
  1797. min=t/60;
  1798. sec=t%60;
  1799. sprintf_P(time, PSTR("%i min, %i sec"), min, sec);
  1800. SERIAL_ECHO_START;
  1801. SERIAL_ECHOLN(time);
  1802. lcd_setstatus(time);
  1803. autotempShutdown();
  1804. }
  1805. break;
  1806. case 42: //M42 -Change pin status via gcode
  1807. if (code_seen('S'))
  1808. {
  1809. int pin_status = code_value();
  1810. int pin_number = LED_PIN;
  1811. if (code_seen('P') && pin_status >= 0 && pin_status <= 255)
  1812. pin_number = code_value();
  1813. for(int8_t i = 0; i < (int8_t)sizeof(sensitive_pins); i++)
  1814. {
  1815. if (sensitive_pins[i] == pin_number)
  1816. {
  1817. pin_number = -1;
  1818. break;
  1819. }
  1820. }
  1821. #if defined(FAN_PIN) && FAN_PIN > -1
  1822. if (pin_number == FAN_PIN)
  1823. fanSpeed = pin_status;
  1824. #endif
  1825. if (pin_number > -1)
  1826. {
  1827. pinMode(pin_number, OUTPUT);
  1828. digitalWrite(pin_number, pin_status);
  1829. analogWrite(pin_number, pin_status);
  1830. }
  1831. }
  1832. break;
  1833. case 104: // M104
  1834. if(setTargetedHotend(104)){
  1835. break;
  1836. }
  1837. if (code_seen('S')) setTargetHotend(code_value(), tmp_extruder);
  1838. #ifdef DUAL_X_CARRIAGE
  1839. if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && tmp_extruder == 0)
  1840. setTargetHotend1(code_value() == 0.0 ? 0.0 : code_value() + duplicate_extruder_temp_offset);
  1841. #endif
  1842. setWatch();
  1843. break;
  1844. case 140: // M140 set bed temp
  1845. if (code_seen('S')) setTargetBed(code_value());
  1846. break;
  1847. case 105 : // M105
  1848. if(setTargetedHotend(105)){
  1849. break;
  1850. }
  1851. #if defined(TEMP_0_PIN) && TEMP_0_PIN > -1
  1852. SERIAL_PROTOCOLPGM("ok T:");
  1853. SERIAL_PROTOCOL_F(degHotend(tmp_extruder),1);
  1854. SERIAL_PROTOCOLPGM(" /");
  1855. SERIAL_PROTOCOL_F(degTargetHotend(tmp_extruder),1);
  1856. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  1857. SERIAL_PROTOCOLPGM(" B:");
  1858. SERIAL_PROTOCOL_F(degBed(),1);
  1859. SERIAL_PROTOCOLPGM(" /");
  1860. SERIAL_PROTOCOL_F(degTargetBed(),1);
  1861. #endif //TEMP_BED_PIN
  1862. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  1863. SERIAL_PROTOCOLPGM(" T");
  1864. SERIAL_PROTOCOL(cur_extruder);
  1865. SERIAL_PROTOCOLPGM(":");
  1866. SERIAL_PROTOCOL_F(degHotend(cur_extruder),1);
  1867. SERIAL_PROTOCOLPGM(" /");
  1868. SERIAL_PROTOCOL_F(degTargetHotend(cur_extruder),1);
  1869. }
  1870. #else
  1871. SERIAL_ERROR_START;
  1872. SERIAL_ERRORLNPGM(MSG_ERR_NO_THERMISTORS);
  1873. #endif
  1874. SERIAL_PROTOCOLPGM(" @:");
  1875. #ifdef EXTRUDER_WATTS
  1876. SERIAL_PROTOCOL((EXTRUDER_WATTS * getHeaterPower(tmp_extruder))/127);
  1877. SERIAL_PROTOCOLPGM("W");
  1878. #else
  1879. SERIAL_PROTOCOL(getHeaterPower(tmp_extruder));
  1880. #endif
  1881. SERIAL_PROTOCOLPGM(" B@:");
  1882. #ifdef BED_WATTS
  1883. SERIAL_PROTOCOL((BED_WATTS * getHeaterPower(-1))/127);
  1884. SERIAL_PROTOCOLPGM("W");
  1885. #else
  1886. SERIAL_PROTOCOL(getHeaterPower(-1));
  1887. #endif
  1888. #ifdef SHOW_TEMP_ADC_VALUES
  1889. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  1890. SERIAL_PROTOCOLPGM(" ADC B:");
  1891. SERIAL_PROTOCOL_F(degBed(),1);
  1892. SERIAL_PROTOCOLPGM("C->");
  1893. SERIAL_PROTOCOL_F(rawBedTemp()/OVERSAMPLENR,0);
  1894. #endif
  1895. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  1896. SERIAL_PROTOCOLPGM(" T");
  1897. SERIAL_PROTOCOL(cur_extruder);
  1898. SERIAL_PROTOCOLPGM(":");
  1899. SERIAL_PROTOCOL_F(degHotend(cur_extruder),1);
  1900. SERIAL_PROTOCOLPGM("C->");
  1901. SERIAL_PROTOCOL_F(rawHotendTemp(cur_extruder)/OVERSAMPLENR,0);
  1902. }
  1903. #endif
  1904. SERIAL_PROTOCOLLN("");
  1905. return;
  1906. break;
  1907. case 109:
  1908. {// M109 - Wait for extruder heater to reach target.
  1909. if(setTargetedHotend(109)){
  1910. break;
  1911. }
  1912. LCD_MESSAGEPGM(MSG_HEATING);
  1913. #ifdef AUTOTEMP
  1914. autotemp_enabled=false;
  1915. #endif
  1916. if (code_seen('S')) {
  1917. setTargetHotend(code_value(), tmp_extruder);
  1918. #ifdef DUAL_X_CARRIAGE
  1919. if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && tmp_extruder == 0)
  1920. setTargetHotend1(code_value() == 0.0 ? 0.0 : code_value() + duplicate_extruder_temp_offset);
  1921. #endif
  1922. CooldownNoWait = true;
  1923. } else if (code_seen('R')) {
  1924. setTargetHotend(code_value(), tmp_extruder);
  1925. #ifdef DUAL_X_CARRIAGE
  1926. if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && tmp_extruder == 0)
  1927. setTargetHotend1(code_value() == 0.0 ? 0.0 : code_value() + duplicate_extruder_temp_offset);
  1928. #endif
  1929. CooldownNoWait = false;
  1930. }
  1931. #ifdef AUTOTEMP
  1932. if (code_seen('S')) autotemp_min=code_value();
  1933. if (code_seen('B')) autotemp_max=code_value();
  1934. if (code_seen('F'))
  1935. {
  1936. autotemp_factor=code_value();
  1937. autotemp_enabled=true;
  1938. }
  1939. #endif
  1940. setWatch();
  1941. codenum = millis();
  1942. /* See if we are heating up or cooling down */
  1943. target_direction = isHeatingHotend(tmp_extruder); // true if heating, false if cooling
  1944. #ifdef TEMP_RESIDENCY_TIME
  1945. long residencyStart;
  1946. residencyStart = -1;
  1947. /* continue to loop until we have reached the target temp
  1948. _and_ until TEMP_RESIDENCY_TIME hasn't passed since we reached it */
  1949. while((residencyStart == -1) ||
  1950. (residencyStart >= 0 && (((unsigned int) (millis() - residencyStart)) < (TEMP_RESIDENCY_TIME * 1000UL))) ) {
  1951. #else
  1952. while ( target_direction ? (isHeatingHotend(tmp_extruder)) : (isCoolingHotend(tmp_extruder)&&(CooldownNoWait==false)) ) {
  1953. #endif //TEMP_RESIDENCY_TIME
  1954. if( (millis() - codenum) > 1000UL )
  1955. { //Print Temp Reading and remaining time every 1 second while heating up/cooling down
  1956. SERIAL_PROTOCOLPGM("T:");
  1957. SERIAL_PROTOCOL_F(degHotend(tmp_extruder),1);
  1958. SERIAL_PROTOCOLPGM(" E:");
  1959. SERIAL_PROTOCOL((int)tmp_extruder);
  1960. #ifdef TEMP_RESIDENCY_TIME
  1961. SERIAL_PROTOCOLPGM(" W:");
  1962. if(residencyStart > -1)
  1963. {
  1964. codenum = ((TEMP_RESIDENCY_TIME * 1000UL) - (millis() - residencyStart)) / 1000UL;
  1965. SERIAL_PROTOCOLLN( codenum );
  1966. }
  1967. else
  1968. {
  1969. SERIAL_PROTOCOLLN( "?" );
  1970. }
  1971. #else
  1972. SERIAL_PROTOCOLLN("");
  1973. #endif
  1974. codenum = millis();
  1975. }
  1976. manage_heater();
  1977. manage_inactivity();
  1978. lcd_update();
  1979. #ifdef TEMP_RESIDENCY_TIME
  1980. /* start/restart the TEMP_RESIDENCY_TIME timer whenever we reach target temp for the first time
  1981. or when current temp falls outside the hysteresis after target temp was reached */
  1982. if ((residencyStart == -1 && target_direction && (degHotend(tmp_extruder) >= (degTargetHotend(tmp_extruder)-TEMP_WINDOW))) ||
  1983. (residencyStart == -1 && !target_direction && (degHotend(tmp_extruder) <= (degTargetHotend(tmp_extruder)+TEMP_WINDOW))) ||
  1984. (residencyStart > -1 && labs(degHotend(tmp_extruder) - degTargetHotend(tmp_extruder)) > TEMP_HYSTERESIS) )
  1985. {
  1986. residencyStart = millis();
  1987. }
  1988. #endif //TEMP_RESIDENCY_TIME
  1989. }
  1990. LCD_MESSAGEPGM(MSG_HEATING_COMPLETE);
  1991. starttime=millis();
  1992. previous_millis_cmd = millis();
  1993. }
  1994. break;
  1995. case 190: // M190 - Wait for bed heater to reach target.
  1996. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  1997. LCD_MESSAGEPGM(MSG_BED_HEATING);
  1998. if (code_seen('S')) {
  1999. setTargetBed(code_value());
  2000. CooldownNoWait = true;
  2001. } else if (code_seen('R')) {
  2002. setTargetBed(code_value());
  2003. CooldownNoWait = false;
  2004. }
  2005. codenum = millis();
  2006. target_direction = isHeatingBed(); // true if heating, false if cooling
  2007. while ( target_direction ? (isHeatingBed()) : (isCoolingBed()&&(CooldownNoWait==false)) )
  2008. {
  2009. if(( millis() - codenum) > 1000 ) //Print Temp Reading every 1 second while heating up.
  2010. {
  2011. float tt=degHotend(active_extruder);
  2012. SERIAL_PROTOCOLPGM("T:");
  2013. SERIAL_PROTOCOL(tt);
  2014. SERIAL_PROTOCOLPGM(" E:");
  2015. SERIAL_PROTOCOL((int)active_extruder);
  2016. SERIAL_PROTOCOLPGM(" B:");
  2017. SERIAL_PROTOCOL_F(degBed(),1);
  2018. SERIAL_PROTOCOLLN("");
  2019. codenum = millis();
  2020. }
  2021. manage_heater();
  2022. manage_inactivity();
  2023. lcd_update();
  2024. }
  2025. LCD_MESSAGEPGM(MSG_BED_DONE);
  2026. previous_millis_cmd = millis();
  2027. #endif
  2028. break;
  2029. #if defined(FAN_PIN) && FAN_PIN > -1
  2030. case 106: //M106 Fan On
  2031. if (code_seen('S')){
  2032. fanSpeed=constrain(code_value(),0,255);
  2033. }
  2034. else {
  2035. fanSpeed=255;
  2036. }
  2037. break;
  2038. case 107: //M107 Fan Off
  2039. fanSpeed = 0;
  2040. break;
  2041. #endif //FAN_PIN
  2042. #ifdef BARICUDA
  2043. // PWM for HEATER_1_PIN
  2044. #if defined(HEATER_1_PIN) && HEATER_1_PIN > -1
  2045. case 126: //M126 valve open
  2046. if (code_seen('S')){
  2047. ValvePressure=constrain(code_value(),0,255);
  2048. }
  2049. else {
  2050. ValvePressure=255;
  2051. }
  2052. break;
  2053. case 127: //M127 valve closed
  2054. ValvePressure = 0;
  2055. break;
  2056. #endif //HEATER_1_PIN
  2057. // PWM for HEATER_2_PIN
  2058. #if defined(HEATER_2_PIN) && HEATER_2_PIN > -1
  2059. case 128: //M128 valve open
  2060. if (code_seen('S')){
  2061. EtoPPressure=constrain(code_value(),0,255);
  2062. }
  2063. else {
  2064. EtoPPressure=255;
  2065. }
  2066. break;
  2067. case 129: //M129 valve closed
  2068. EtoPPressure = 0;
  2069. break;
  2070. #endif //HEATER_2_PIN
  2071. #endif
  2072. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  2073. case 80: // M80 - Turn on Power Supply
  2074. SET_OUTPUT(PS_ON_PIN); //GND
  2075. WRITE(PS_ON_PIN, PS_ON_AWAKE);
  2076. // If you have a switch on suicide pin, this is useful
  2077. // if you want to start another print with suicide feature after
  2078. // a print without suicide...
  2079. #if defined SUICIDE_PIN && SUICIDE_PIN > -1
  2080. SET_OUTPUT(SUICIDE_PIN);
  2081. WRITE(SUICIDE_PIN, HIGH);
  2082. #endif
  2083. #ifdef ULTIPANEL
  2084. powersupply = true;
  2085. LCD_MESSAGEPGM(WELCOME_MSG);
  2086. lcd_update();
  2087. #endif
  2088. break;
  2089. #endif
  2090. case 81: // M81 - Turn off Power Supply
  2091. disable_heater();
  2092. st_synchronize();
  2093. disable_e0();
  2094. disable_e1();
  2095. disable_e2();
  2096. finishAndDisableSteppers();
  2097. fanSpeed = 0;
  2098. delay(1000); // Wait a little before to switch off
  2099. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  2100. st_synchronize();
  2101. suicide();
  2102. #elif defined(PS_ON_PIN) && PS_ON_PIN > -1
  2103. SET_OUTPUT(PS_ON_PIN);
  2104. WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  2105. #endif
  2106. #ifdef ULTIPANEL
  2107. powersupply = false;
  2108. LCD_MESSAGEPGM(MACHINE_NAME" "MSG_OFF".");
  2109. lcd_update();
  2110. #endif
  2111. break;
  2112. case 82:
  2113. axis_relative_modes[3] = false;
  2114. break;
  2115. case 83:
  2116. axis_relative_modes[3] = true;
  2117. break;
  2118. case 18: //compatibility
  2119. case 84: // M84
  2120. if(code_seen('S')){
  2121. stepper_inactive_time = code_value() * 1000;
  2122. }
  2123. else
  2124. {
  2125. bool all_axis = !((code_seen(axis_codes[0])) || (code_seen(axis_codes[1])) || (code_seen(axis_codes[2]))|| (code_seen(axis_codes[3])));
  2126. if(all_axis)
  2127. {
  2128. st_synchronize();
  2129. disable_e0();
  2130. disable_e1();
  2131. disable_e2();
  2132. finishAndDisableSteppers();
  2133. }
  2134. else
  2135. {
  2136. st_synchronize();
  2137. if(code_seen('X')) disable_x();
  2138. if(code_seen('Y')) disable_y();
  2139. if(code_seen('Z')) disable_z();
  2140. #if ((E0_ENABLE_PIN != X_ENABLE_PIN) && (E1_ENABLE_PIN != Y_ENABLE_PIN)) // Only enable on boards that have seperate ENABLE_PINS
  2141. if(code_seen('E')) {
  2142. disable_e0();
  2143. disable_e1();
  2144. disable_e2();
  2145. }
  2146. #endif
  2147. }
  2148. }
  2149. break;
  2150. case 85: // M85
  2151. code_seen('S');
  2152. max_inactive_time = code_value() * 1000;
  2153. break;
  2154. case 92: // M92
  2155. for(int8_t i=0; i < NUM_AXIS; i++)
  2156. {
  2157. if(code_seen(axis_codes[i]))
  2158. {
  2159. if(i == 3) { // E
  2160. float value = code_value();
  2161. if(value < 20.0) {
  2162. float factor = axis_steps_per_unit[i] / value; // increase e constants if M92 E14 is given for netfab.
  2163. max_e_jerk *= factor;
  2164. max_feedrate[i] *= factor;
  2165. axis_steps_per_sqr_second[i] *= factor;
  2166. }
  2167. axis_steps_per_unit[i] = value;
  2168. }
  2169. else {
  2170. axis_steps_per_unit[i] = code_value();
  2171. }
  2172. }
  2173. }
  2174. break;
  2175. case 115: // M115
  2176. SERIAL_PROTOCOLPGM(MSG_M115_REPORT);
  2177. break;
  2178. case 117: // M117 display message
  2179. starpos = (strchr(strchr_pointer + 5,'*'));
  2180. if(starpos!=NULL)
  2181. *(starpos-1)='\0';
  2182. lcd_setstatus(strchr_pointer + 5);
  2183. break;
  2184. case 114: // M114
  2185. SERIAL_PROTOCOLPGM("X:");
  2186. SERIAL_PROTOCOL(current_position[X_AXIS]);
  2187. SERIAL_PROTOCOLPGM("Y:");
  2188. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  2189. SERIAL_PROTOCOLPGM("Z:");
  2190. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  2191. SERIAL_PROTOCOLPGM("E:");
  2192. SERIAL_PROTOCOL(current_position[E_AXIS]);
  2193. SERIAL_PROTOCOLPGM(MSG_COUNT_X);
  2194. SERIAL_PROTOCOL(float(st_get_position(X_AXIS))/axis_steps_per_unit[X_AXIS]);
  2195. SERIAL_PROTOCOLPGM("Y:");
  2196. SERIAL_PROTOCOL(float(st_get_position(Y_AXIS))/axis_steps_per_unit[Y_AXIS]);
  2197. SERIAL_PROTOCOLPGM("Z:");
  2198. SERIAL_PROTOCOL(float(st_get_position(Z_AXIS))/axis_steps_per_unit[Z_AXIS]);
  2199. SERIAL_PROTOCOLLN("");
  2200. break;
  2201. case 120: // M120
  2202. enable_endstops(false) ;
  2203. break;
  2204. case 121: // M121
  2205. enable_endstops(true) ;
  2206. break;
  2207. case 119: // M119
  2208. SERIAL_PROTOCOLLN(MSG_M119_REPORT);
  2209. #if defined(X_MIN_PIN) && X_MIN_PIN > -1
  2210. SERIAL_PROTOCOLPGM(MSG_X_MIN);
  2211. SERIAL_PROTOCOLLN(((READ(X_MIN_PIN)^X_MIN_ENDSTOP_INVERTING)?MSG_ENDSTOP_HIT:MSG_ENDSTOP_OPEN));
  2212. #endif
  2213. #if defined(X_MAX_PIN) && X_MAX_PIN > -1
  2214. SERIAL_PROTOCOLPGM(MSG_X_MAX);
  2215. SERIAL_PROTOCOLLN(((READ(X_MAX_PIN)^X_MAX_ENDSTOP_INVERTING)?MSG_ENDSTOP_HIT:MSG_ENDSTOP_OPEN));
  2216. #endif
  2217. #if defined(Y_MIN_PIN) && Y_MIN_PIN > -1
  2218. SERIAL_PROTOCOLPGM(MSG_Y_MIN);
  2219. SERIAL_PROTOCOLLN(((READ(Y_MIN_PIN)^Y_MIN_ENDSTOP_INVERTING)?MSG_ENDSTOP_HIT:MSG_ENDSTOP_OPEN));
  2220. #endif
  2221. #if defined(Y_MAX_PIN) && Y_MAX_PIN > -1
  2222. SERIAL_PROTOCOLPGM(MSG_Y_MAX);
  2223. SERIAL_PROTOCOLLN(((READ(Y_MAX_PIN)^Y_MAX_ENDSTOP_INVERTING)?MSG_ENDSTOP_HIT:MSG_ENDSTOP_OPEN));
  2224. #endif
  2225. #if defined(Z_MIN_PIN) && Z_MIN_PIN > -1
  2226. SERIAL_PROTOCOLPGM(MSG_Z_MIN);
  2227. SERIAL_PROTOCOLLN(((READ(Z_MIN_PIN)^Z_MIN_ENDSTOP_INVERTING)?MSG_ENDSTOP_HIT:MSG_ENDSTOP_OPEN));
  2228. #endif
  2229. #if defined(Z_MAX_PIN) && Z_MAX_PIN > -1
  2230. SERIAL_PROTOCOLPGM(MSG_Z_MAX);
  2231. SERIAL_PROTOCOLLN(((READ(Z_MAX_PIN)^Z_MAX_ENDSTOP_INVERTING)?MSG_ENDSTOP_HIT:MSG_ENDSTOP_OPEN));
  2232. #endif
  2233. break;
  2234. //TODO: update for all axis, use for loop
  2235. #ifdef BLINKM
  2236. case 150: // M150
  2237. {
  2238. byte red;
  2239. byte grn;
  2240. byte blu;
  2241. if(code_seen('R')) red = code_value();
  2242. if(code_seen('U')) grn = code_value();
  2243. if(code_seen('B')) blu = code_value();
  2244. SendColors(red,grn,blu);
  2245. }
  2246. break;
  2247. #endif //BLINKM
  2248. case 200: // M200 D<millimeters> set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).
  2249. {
  2250. float area = .0;
  2251. float radius = .0;
  2252. if(code_seen('D')) {
  2253. radius = (float)code_value() * .5;
  2254. if(radius == 0) {
  2255. area = 1;
  2256. } else {
  2257. area = M_PI * pow(radius, 2);
  2258. }
  2259. } else {
  2260. //reserved for setting filament diameter via UFID or filament measuring device
  2261. break;
  2262. }
  2263. tmp_extruder = active_extruder;
  2264. if(code_seen('T')) {
  2265. tmp_extruder = code_value();
  2266. if(tmp_extruder >= EXTRUDERS) {
  2267. SERIAL_ECHO_START;
  2268. SERIAL_ECHO(MSG_M200_INVALID_EXTRUDER);
  2269. }
  2270. SERIAL_ECHOLN(tmp_extruder);
  2271. break;
  2272. }
  2273. volumetric_multiplier[tmp_extruder] = 1 / area;
  2274. }
  2275. break;
  2276. case 201: // M201
  2277. for(int8_t i=0; i < NUM_AXIS; i++)
  2278. {
  2279. if(code_seen(axis_codes[i]))
  2280. {
  2281. max_acceleration_units_per_sq_second[i] = code_value();
  2282. }
  2283. }
  2284. // steps per sq second need to be updated to agree with the units per sq second (as they are what is used in the planner)
  2285. reset_acceleration_rates();
  2286. break;
  2287. #if 0 // Not used for Sprinter/grbl gen6
  2288. case 202: // M202
  2289. for(int8_t i=0; i < NUM_AXIS; i++) {
  2290. if(code_seen(axis_codes[i])) axis_travel_steps_per_sqr_second[i] = code_value() * axis_steps_per_unit[i];
  2291. }
  2292. break;
  2293. #endif
  2294. case 203: // M203 max feedrate mm/sec
  2295. for(int8_t i=0; i < NUM_AXIS; i++) {
  2296. if(code_seen(axis_codes[i])) max_feedrate[i] = code_value();
  2297. }
  2298. break;
  2299. case 204: // M204 acclereration S normal moves T filmanent only moves
  2300. {
  2301. if(code_seen('S')) acceleration = code_value() ;
  2302. if(code_seen('T')) retract_acceleration = code_value() ;
  2303. }
  2304. break;
  2305. 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
  2306. {
  2307. if(code_seen('S')) minimumfeedrate = code_value();
  2308. if(code_seen('T')) mintravelfeedrate = code_value();
  2309. if(code_seen('B')) minsegmenttime = code_value() ;
  2310. if(code_seen('X')) max_xy_jerk = code_value() ;
  2311. if(code_seen('Z')) max_z_jerk = code_value() ;
  2312. if(code_seen('E')) max_e_jerk = code_value() ;
  2313. }
  2314. break;
  2315. case 206: // M206 additional homeing offset
  2316. for(int8_t i=0; i < 3; i++)
  2317. {
  2318. if(code_seen(axis_codes[i])) add_homeing[i] = code_value();
  2319. }
  2320. break;
  2321. #ifdef DELTA
  2322. case 666: // M666 set delta endstop adjustemnt
  2323. for(int8_t i=0; i < 3; i++)
  2324. {
  2325. if(code_seen(axis_codes[i])) endstop_adj[i] = code_value();
  2326. }
  2327. break;
  2328. #endif
  2329. #ifdef FWRETRACT
  2330. case 207: //M207 - set retract length S[positive mm] F[feedrate mm/sec] Z[additional zlift/hop]
  2331. {
  2332. if(code_seen('S'))
  2333. {
  2334. retract_length = code_value() ;
  2335. }
  2336. if(code_seen('F'))
  2337. {
  2338. retract_feedrate = code_value() ;
  2339. }
  2340. if(code_seen('Z'))
  2341. {
  2342. retract_zlift = code_value() ;
  2343. }
  2344. }break;
  2345. case 208: // M208 - set retract recover length S[positive mm surplus to the M207 S*] F[feedrate mm/sec]
  2346. {
  2347. if(code_seen('S'))
  2348. {
  2349. retract_recover_length = code_value() ;
  2350. }
  2351. if(code_seen('F'))
  2352. {
  2353. retract_recover_feedrate = code_value() ;
  2354. }
  2355. }break;
  2356. case 209: // M209 - S<1=true/0=false> enable automatic retract detect if the slicer did not support G10/11: every normal extrude-only move will be classified as retract depending on the direction.
  2357. {
  2358. if(code_seen('S'))
  2359. {
  2360. int t= code_value() ;
  2361. switch(t)
  2362. {
  2363. case 0: autoretract_enabled=false;retracted=false;break;
  2364. case 1: autoretract_enabled=true;retracted=false;break;
  2365. default:
  2366. SERIAL_ECHO_START;
  2367. SERIAL_ECHOPGM(MSG_UNKNOWN_COMMAND);
  2368. SERIAL_ECHO(cmdbuffer[bufindr]);
  2369. SERIAL_ECHOLNPGM("\"");
  2370. }
  2371. }
  2372. }break;
  2373. #endif // FWRETRACT
  2374. #if EXTRUDERS > 1
  2375. case 218: // M218 - set hotend offset (in mm), T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  2376. {
  2377. if(setTargetedHotend(218)){
  2378. break;
  2379. }
  2380. if(code_seen('X'))
  2381. {
  2382. extruder_offset[X_AXIS][tmp_extruder] = code_value();
  2383. }
  2384. if(code_seen('Y'))
  2385. {
  2386. extruder_offset[Y_AXIS][tmp_extruder] = code_value();
  2387. }
  2388. #ifdef DUAL_X_CARRIAGE
  2389. if(code_seen('Z'))
  2390. {
  2391. extruder_offset[Z_AXIS][tmp_extruder] = code_value();
  2392. }
  2393. #endif
  2394. SERIAL_ECHO_START;
  2395. SERIAL_ECHOPGM(MSG_HOTEND_OFFSET);
  2396. for(tmp_extruder = 0; tmp_extruder < EXTRUDERS; tmp_extruder++)
  2397. {
  2398. SERIAL_ECHO(" ");
  2399. SERIAL_ECHO(extruder_offset[X_AXIS][tmp_extruder]);
  2400. SERIAL_ECHO(",");
  2401. SERIAL_ECHO(extruder_offset[Y_AXIS][tmp_extruder]);
  2402. #ifdef DUAL_X_CARRIAGE
  2403. SERIAL_ECHO(",");
  2404. SERIAL_ECHO(extruder_offset[Z_AXIS][tmp_extruder]);
  2405. #endif
  2406. }
  2407. SERIAL_ECHOLN("");
  2408. }break;
  2409. #endif
  2410. case 220: // M220 S<factor in percent>- set speed factor override percentage
  2411. {
  2412. if(code_seen('S'))
  2413. {
  2414. feedmultiply = code_value() ;
  2415. }
  2416. }
  2417. break;
  2418. case 221: // M221 S<factor in percent>- set extrude factor override percentage
  2419. {
  2420. if(code_seen('S'))
  2421. {
  2422. extrudemultiply = code_value() ;
  2423. }
  2424. }
  2425. break;
  2426. case 226: // M226 P<pin number> S<pin state>- Wait until the specified pin reaches the state required
  2427. {
  2428. if(code_seen('P')){
  2429. int pin_number = code_value(); // pin number
  2430. int pin_state = -1; // required pin state - default is inverted
  2431. if(code_seen('S')) pin_state = code_value(); // required pin state
  2432. if(pin_state >= -1 && pin_state <= 1){
  2433. for(int8_t i = 0; i < (int8_t)sizeof(sensitive_pins); i++)
  2434. {
  2435. if (sensitive_pins[i] == pin_number)
  2436. {
  2437. pin_number = -1;
  2438. break;
  2439. }
  2440. }
  2441. if (pin_number > -1)
  2442. {
  2443. st_synchronize();
  2444. pinMode(pin_number, INPUT);
  2445. int target;
  2446. switch(pin_state){
  2447. case 1:
  2448. target = HIGH;
  2449. break;
  2450. case 0:
  2451. target = LOW;
  2452. break;
  2453. case -1:
  2454. target = !digitalRead(pin_number);
  2455. break;
  2456. }
  2457. while(digitalRead(pin_number) != target){
  2458. manage_heater();
  2459. manage_inactivity();
  2460. lcd_update();
  2461. }
  2462. }
  2463. }
  2464. }
  2465. }
  2466. break;
  2467. #if NUM_SERVOS > 0
  2468. case 280: // M280 - set servo position absolute. P: servo index, S: angle or microseconds
  2469. {
  2470. int servo_index = -1;
  2471. int servo_position = 0;
  2472. if (code_seen('P'))
  2473. servo_index = code_value();
  2474. if (code_seen('S')) {
  2475. servo_position = code_value();
  2476. if ((servo_index >= 0) && (servo_index < NUM_SERVOS)) {
  2477. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  2478. servos[servo_index].attach(0);
  2479. #endif
  2480. servos[servo_index].write(servo_position);
  2481. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  2482. delay(PROBE_SERVO_DEACTIVATION_DELAY);
  2483. servos[servo_index].detach();
  2484. #endif
  2485. }
  2486. else {
  2487. SERIAL_ECHO_START;
  2488. SERIAL_ECHO("Servo ");
  2489. SERIAL_ECHO(servo_index);
  2490. SERIAL_ECHOLN(" out of range");
  2491. }
  2492. }
  2493. else if (servo_index >= 0) {
  2494. SERIAL_PROTOCOL(MSG_OK);
  2495. SERIAL_PROTOCOL(" Servo ");
  2496. SERIAL_PROTOCOL(servo_index);
  2497. SERIAL_PROTOCOL(": ");
  2498. SERIAL_PROTOCOL(servos[servo_index].read());
  2499. SERIAL_PROTOCOLLN("");
  2500. }
  2501. }
  2502. break;
  2503. #endif // NUM_SERVOS > 0
  2504. #if (LARGE_FLASH == true && ( BEEPER > 0 || defined(ULTRALCD) || defined(LCD_USE_I2C_BUZZER)))
  2505. case 300: // M300
  2506. {
  2507. int beepS = code_seen('S') ? code_value() : 110;
  2508. int beepP = code_seen('P') ? code_value() : 1000;
  2509. if (beepS > 0)
  2510. {
  2511. #if BEEPER > 0
  2512. tone(BEEPER, beepS);
  2513. delay(beepP);
  2514. noTone(BEEPER);
  2515. #elif defined(ULTRALCD)
  2516. lcd_buzz(beepS, beepP);
  2517. #elif defined(LCD_USE_I2C_BUZZER)
  2518. lcd_buzz(beepP, beepS);
  2519. #endif
  2520. }
  2521. else
  2522. {
  2523. delay(beepP);
  2524. }
  2525. }
  2526. break;
  2527. #endif // M300
  2528. #ifdef PIDTEMP
  2529. case 301: // M301
  2530. {
  2531. if(code_seen('P')) Kp = code_value();
  2532. if(code_seen('I')) Ki = scalePID_i(code_value());
  2533. if(code_seen('D')) Kd = scalePID_d(code_value());
  2534. #ifdef PID_ADD_EXTRUSION_RATE
  2535. if(code_seen('C')) Kc = code_value();
  2536. #endif
  2537. updatePID();
  2538. SERIAL_PROTOCOL(MSG_OK);
  2539. SERIAL_PROTOCOL(" p:");
  2540. SERIAL_PROTOCOL(Kp);
  2541. SERIAL_PROTOCOL(" i:");
  2542. SERIAL_PROTOCOL(unscalePID_i(Ki));
  2543. SERIAL_PROTOCOL(" d:");
  2544. SERIAL_PROTOCOL(unscalePID_d(Kd));
  2545. #ifdef PID_ADD_EXTRUSION_RATE
  2546. SERIAL_PROTOCOL(" c:");
  2547. //Kc does not have scaling applied above, or in resetting defaults
  2548. SERIAL_PROTOCOL(Kc);
  2549. #endif
  2550. SERIAL_PROTOCOLLN("");
  2551. }
  2552. break;
  2553. #endif //PIDTEMP
  2554. #ifdef PIDTEMPBED
  2555. case 304: // M304
  2556. {
  2557. if(code_seen('P')) bedKp = code_value();
  2558. if(code_seen('I')) bedKi = scalePID_i(code_value());
  2559. if(code_seen('D')) bedKd = scalePID_d(code_value());
  2560. updatePID();
  2561. SERIAL_PROTOCOL(MSG_OK);
  2562. SERIAL_PROTOCOL(" p:");
  2563. SERIAL_PROTOCOL(bedKp);
  2564. SERIAL_PROTOCOL(" i:");
  2565. SERIAL_PROTOCOL(unscalePID_i(bedKi));
  2566. SERIAL_PROTOCOL(" d:");
  2567. SERIAL_PROTOCOL(unscalePID_d(bedKd));
  2568. SERIAL_PROTOCOLLN("");
  2569. }
  2570. break;
  2571. #endif //PIDTEMP
  2572. case 240: // M240 Triggers a camera by emulating a Canon RC-1 : http://www.doc-diy.net/photo/rc-1_hacked/
  2573. {
  2574. #if defined(PHOTOGRAPH_PIN) && PHOTOGRAPH_PIN > -1
  2575. const uint8_t NUM_PULSES=16;
  2576. const float PULSE_LENGTH=0.01524;
  2577. for(int i=0; i < NUM_PULSES; i++) {
  2578. WRITE(PHOTOGRAPH_PIN, HIGH);
  2579. _delay_ms(PULSE_LENGTH);
  2580. WRITE(PHOTOGRAPH_PIN, LOW);
  2581. _delay_ms(PULSE_LENGTH);
  2582. }
  2583. delay(7.33);
  2584. for(int i=0; i < NUM_PULSES; i++) {
  2585. WRITE(PHOTOGRAPH_PIN, HIGH);
  2586. _delay_ms(PULSE_LENGTH);
  2587. WRITE(PHOTOGRAPH_PIN, LOW);
  2588. _delay_ms(PULSE_LENGTH);
  2589. }
  2590. #endif
  2591. }
  2592. break;
  2593. #ifdef DOGLCD
  2594. #if !defined(MINIPANEL)
  2595. case 250: // M250 Set LCD contrast value: C<value> (value 0..63)
  2596. {
  2597. if (code_seen('C')) {
  2598. lcd_setcontrast( ((int)code_value())&63 );
  2599. }
  2600. SERIAL_PROTOCOLPGM("lcd contrast value: ");
  2601. SERIAL_PROTOCOL(lcd_contrast);
  2602. SERIAL_PROTOCOLLN("");
  2603. }
  2604. break;
  2605. #endif
  2606. #endif
  2607. #ifdef PREVENT_DANGEROUS_EXTRUDE
  2608. case 302: // allow cold extrudes, or set the minimum extrude temperature
  2609. {
  2610. float temp = .0;
  2611. if (code_seen('S')) temp=code_value();
  2612. set_extrude_min_temp(temp);
  2613. }
  2614. break;
  2615. #endif
  2616. case 303: // M303 PID autotune
  2617. {
  2618. float temp = 150.0;
  2619. int e=0;
  2620. int c=5;
  2621. if (code_seen('E')) e=code_value();
  2622. if (e<0)
  2623. temp=70;
  2624. if (code_seen('S')) temp=code_value();
  2625. if (code_seen('C')) c=code_value();
  2626. PID_autotune(temp, e, c);
  2627. }
  2628. break;
  2629. case 400: // M400 finish all moves
  2630. {
  2631. st_synchronize();
  2632. }
  2633. break;
  2634. #if defined(ENABLE_AUTO_BED_LEVELING) && defined(SERVO_ENDSTOPS)
  2635. case 401:
  2636. {
  2637. engage_z_probe(); // Engage Z Servo endstop if available
  2638. }
  2639. break;
  2640. case 402:
  2641. {
  2642. retract_z_probe(); // Retract Z Servo endstop if enabled
  2643. }
  2644. break;
  2645. #endif
  2646. case 500: // M500 Store settings in EEPROM
  2647. {
  2648. Config_StoreSettings();
  2649. }
  2650. break;
  2651. case 501: // M501 Read settings from EEPROM
  2652. {
  2653. Config_RetrieveSettings();
  2654. }
  2655. break;
  2656. case 502: // M502 Revert to default settings
  2657. {
  2658. Config_ResetDefault();
  2659. }
  2660. break;
  2661. case 503: // M503 print settings currently in memory
  2662. {
  2663. Config_PrintSettings();
  2664. }
  2665. break;
  2666. #ifdef ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED
  2667. case 540:
  2668. {
  2669. if(code_seen('S')) abort_on_endstop_hit = code_value() > 0;
  2670. }
  2671. break;
  2672. #endif
  2673. #ifdef FILAMENTCHANGEENABLE
  2674. case 600: //Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  2675. {
  2676. float target[4];
  2677. float lastpos[4];
  2678. target[X_AXIS]=current_position[X_AXIS];
  2679. target[Y_AXIS]=current_position[Y_AXIS];
  2680. target[Z_AXIS]=current_position[Z_AXIS];
  2681. target[E_AXIS]=current_position[E_AXIS];
  2682. lastpos[X_AXIS]=current_position[X_AXIS];
  2683. lastpos[Y_AXIS]=current_position[Y_AXIS];
  2684. lastpos[Z_AXIS]=current_position[Z_AXIS];
  2685. lastpos[E_AXIS]=current_position[E_AXIS];
  2686. //retract by E
  2687. if(code_seen('E'))
  2688. {
  2689. target[E_AXIS]+= code_value();
  2690. }
  2691. else
  2692. {
  2693. #ifdef FILAMENTCHANGE_FIRSTRETRACT
  2694. target[E_AXIS]+= FILAMENTCHANGE_FIRSTRETRACT ;
  2695. #endif
  2696. }
  2697. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], feedrate/60, active_extruder);
  2698. //lift Z
  2699. if(code_seen('Z'))
  2700. {
  2701. target[Z_AXIS]+= code_value();
  2702. }
  2703. else
  2704. {
  2705. #ifdef FILAMENTCHANGE_ZADD
  2706. target[Z_AXIS]+= FILAMENTCHANGE_ZADD ;
  2707. #endif
  2708. }
  2709. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], feedrate/60, active_extruder);
  2710. //move xy
  2711. if(code_seen('X'))
  2712. {
  2713. target[X_AXIS]+= code_value();
  2714. }
  2715. else
  2716. {
  2717. #ifdef FILAMENTCHANGE_XPOS
  2718. target[X_AXIS]= FILAMENTCHANGE_XPOS ;
  2719. #endif
  2720. }
  2721. if(code_seen('Y'))
  2722. {
  2723. target[Y_AXIS]= code_value();
  2724. }
  2725. else
  2726. {
  2727. #ifdef FILAMENTCHANGE_YPOS
  2728. target[Y_AXIS]= FILAMENTCHANGE_YPOS ;
  2729. #endif
  2730. }
  2731. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], feedrate/60, active_extruder);
  2732. if(code_seen('L'))
  2733. {
  2734. target[E_AXIS]+= code_value();
  2735. }
  2736. else
  2737. {
  2738. #ifdef FILAMENTCHANGE_FINALRETRACT
  2739. target[E_AXIS]+= FILAMENTCHANGE_FINALRETRACT ;
  2740. #endif
  2741. }
  2742. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], feedrate/60, active_extruder);
  2743. //finish moves
  2744. st_synchronize();
  2745. //disable extruder steppers so filament can be removed
  2746. disable_e0();
  2747. disable_e1();
  2748. disable_e2();
  2749. delay(100);
  2750. LCD_ALERTMESSAGEPGM(MSG_FILAMENTCHANGE);
  2751. uint8_t cnt=0;
  2752. while(!lcd_clicked()){
  2753. cnt++;
  2754. manage_heater();
  2755. manage_inactivity();
  2756. lcd_update();
  2757. if(cnt==0)
  2758. {
  2759. #if BEEPER > 0
  2760. SET_OUTPUT(BEEPER);
  2761. WRITE(BEEPER,HIGH);
  2762. delay(3);
  2763. WRITE(BEEPER,LOW);
  2764. delay(3);
  2765. #else
  2766. #if !defined(LCD_FEEDBACK_FREQUENCY_HZ) || !defined(LCD_FEEDBACK_FREQUENCY_DURATION_MS)
  2767. lcd_buzz(1000/6,100);
  2768. #else
  2769. lcd_buzz(LCD_FEEDBACK_FREQUENCY_DURATION_MS,LCD_FEEDBACK_FREQUENCY_HZ);
  2770. #endif
  2771. #endif
  2772. }
  2773. }
  2774. //return to normal
  2775. if(code_seen('L'))
  2776. {
  2777. target[E_AXIS]+= -code_value();
  2778. }
  2779. else
  2780. {
  2781. #ifdef FILAMENTCHANGE_FINALRETRACT
  2782. target[E_AXIS]+=(-1)*FILAMENTCHANGE_FINALRETRACT ;
  2783. #endif
  2784. }
  2785. current_position[E_AXIS]=target[E_AXIS]; //the long retract of L is compensated by manual filament feeding
  2786. plan_set_e_position(current_position[E_AXIS]);
  2787. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], feedrate/60, active_extruder); //should do nothing
  2788. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], target[Z_AXIS], target[E_AXIS], feedrate/60, active_extruder); //move xy back
  2789. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], lastpos[Z_AXIS], target[E_AXIS], feedrate/60, active_extruder); //move z back
  2790. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], lastpos[Z_AXIS], lastpos[E_AXIS], feedrate/60, active_extruder); //final untretract
  2791. }
  2792. break;
  2793. #endif //FILAMENTCHANGEENABLE
  2794. #ifdef DUAL_X_CARRIAGE
  2795. case 605: // Set dual x-carriage movement mode:
  2796. // M605 S0: Full control mode. The slicer has full control over x-carriage movement
  2797. // M605 S1: Auto-park mode. The inactive head will auto park/unpark without slicer involvement
  2798. // M605 S2 [Xnnn] [Rmmm]: Duplication mode. The second extruder will duplicate the first with nnn
  2799. // millimeters x-offset and an optional differential hotend temperature of
  2800. // mmm degrees. E.g., with "M605 S2 X100 R2" the second extruder will duplicate
  2801. // the first with a spacing of 100mm in the x direction and 2 degrees hotter.
  2802. //
  2803. // Note: the X axis should be homed after changing dual x-carriage mode.
  2804. {
  2805. st_synchronize();
  2806. if (code_seen('S'))
  2807. dual_x_carriage_mode = code_value();
  2808. if (dual_x_carriage_mode == DXC_DUPLICATION_MODE)
  2809. {
  2810. if (code_seen('X'))
  2811. duplicate_extruder_x_offset = max(code_value(),X2_MIN_POS - x_home_pos(0));
  2812. if (code_seen('R'))
  2813. duplicate_extruder_temp_offset = code_value();
  2814. SERIAL_ECHO_START;
  2815. SERIAL_ECHOPGM(MSG_HOTEND_OFFSET);
  2816. SERIAL_ECHO(" ");
  2817. SERIAL_ECHO(extruder_offset[X_AXIS][0]);
  2818. SERIAL_ECHO(",");
  2819. SERIAL_ECHO(extruder_offset[Y_AXIS][0]);
  2820. SERIAL_ECHO(" ");
  2821. SERIAL_ECHO(duplicate_extruder_x_offset);
  2822. SERIAL_ECHO(",");
  2823. SERIAL_ECHOLN(extruder_offset[Y_AXIS][1]);
  2824. }
  2825. else if (dual_x_carriage_mode != DXC_FULL_CONTROL_MODE && dual_x_carriage_mode != DXC_AUTO_PARK_MODE)
  2826. {
  2827. dual_x_carriage_mode = DEFAULT_DUAL_X_CARRIAGE_MODE;
  2828. }
  2829. active_extruder_parked = false;
  2830. extruder_duplication_enabled = false;
  2831. delayed_move_time = 0;
  2832. }
  2833. break;
  2834. #endif //DUAL_X_CARRIAGE
  2835. case 907: // M907 Set digital trimpot motor current using axis codes.
  2836. {
  2837. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  2838. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) digipot_current(i,code_value());
  2839. if(code_seen('B')) digipot_current(4,code_value());
  2840. if(code_seen('S')) for(int i=0;i<=4;i++) digipot_current(i,code_value());
  2841. #endif
  2842. #ifdef MOTOR_CURRENT_PWM_XY_PIN
  2843. if(code_seen('X')) digipot_current(0, code_value());
  2844. #endif
  2845. #ifdef MOTOR_CURRENT_PWM_Z_PIN
  2846. if(code_seen('Z')) digipot_current(1, code_value());
  2847. #endif
  2848. #ifdef MOTOR_CURRENT_PWM_E_PIN
  2849. if(code_seen('E')) digipot_current(2, code_value());
  2850. #endif
  2851. #ifdef DIGIPOT_I2C
  2852. // this one uses actual amps in floating point
  2853. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) digipot_i2c_set_current(i, code_value());
  2854. // for each additional extruder (named B,C,D,E..., channels 4,5,6,7...)
  2855. for(int i=NUM_AXIS;i<DIGIPOT_I2C_NUM_CHANNELS;i++) if(code_seen('B'+i-NUM_AXIS)) digipot_i2c_set_current(i, code_value());
  2856. #endif
  2857. }
  2858. break;
  2859. case 908: // M908 Control digital trimpot directly.
  2860. {
  2861. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  2862. uint8_t channel,current;
  2863. if(code_seen('P')) channel=code_value();
  2864. if(code_seen('S')) current=code_value();
  2865. digitalPotWrite(channel, current);
  2866. #endif
  2867. }
  2868. break;
  2869. case 350: // M350 Set microstepping mode. Warning: Steps per unit remains unchanged. S code sets stepping mode for all drivers.
  2870. {
  2871. #if defined(X_MS1_PIN) && X_MS1_PIN > -1
  2872. if(code_seen('S')) for(int i=0;i<=4;i++) microstep_mode(i,code_value());
  2873. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_mode(i,(uint8_t)code_value());
  2874. if(code_seen('B')) microstep_mode(4,code_value());
  2875. microstep_readings();
  2876. #endif
  2877. }
  2878. break;
  2879. case 351: // M351 Toggle MS1 MS2 pins directly, S# determines MS1 or MS2, X# sets the pin high/low.
  2880. {
  2881. #if defined(X_MS1_PIN) && X_MS1_PIN > -1
  2882. if(code_seen('S')) switch((int)code_value())
  2883. {
  2884. case 1:
  2885. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_ms(i,code_value(),-1);
  2886. if(code_seen('B')) microstep_ms(4,code_value(),-1);
  2887. break;
  2888. case 2:
  2889. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_ms(i,-1,code_value());
  2890. if(code_seen('B')) microstep_ms(4,-1,code_value());
  2891. break;
  2892. }
  2893. microstep_readings();
  2894. #endif
  2895. }
  2896. break;
  2897. case 999: // M999: Restart after being stopped
  2898. Stopped = false;
  2899. lcd_reset_alert_level();
  2900. gcode_LastN = Stopped_gcode_LastN;
  2901. FlushSerialRequestResend();
  2902. break;
  2903. }
  2904. }
  2905. else if(code_seen('T'))
  2906. {
  2907. tmp_extruder = code_value();
  2908. if(tmp_extruder >= EXTRUDERS) {
  2909. SERIAL_ECHO_START;
  2910. SERIAL_ECHO("T");
  2911. SERIAL_ECHO(tmp_extruder);
  2912. SERIAL_ECHOLN(MSG_INVALID_EXTRUDER);
  2913. }
  2914. else {
  2915. boolean make_move = false;
  2916. if(code_seen('F')) {
  2917. make_move = true;
  2918. next_feedrate = code_value();
  2919. if(next_feedrate > 0.0) {
  2920. feedrate = next_feedrate;
  2921. }
  2922. }
  2923. #if EXTRUDERS > 1
  2924. if(tmp_extruder != active_extruder) {
  2925. // Save current position to return to after applying extruder offset
  2926. memcpy(destination, current_position, sizeof(destination));
  2927. #ifdef DUAL_X_CARRIAGE
  2928. if (dual_x_carriage_mode == DXC_AUTO_PARK_MODE && Stopped == false &&
  2929. (delayed_move_time != 0 || current_position[X_AXIS] != x_home_pos(active_extruder)))
  2930. {
  2931. // Park old head: 1) raise 2) move to park position 3) lower
  2932. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS] + TOOLCHANGE_PARK_ZLIFT,
  2933. current_position[E_AXIS], max_feedrate[Z_AXIS], active_extruder);
  2934. plan_buffer_line(x_home_pos(active_extruder), current_position[Y_AXIS], current_position[Z_AXIS] + TOOLCHANGE_PARK_ZLIFT,
  2935. current_position[E_AXIS], max_feedrate[X_AXIS], active_extruder);
  2936. plan_buffer_line(x_home_pos(active_extruder), current_position[Y_AXIS], current_position[Z_AXIS],
  2937. current_position[E_AXIS], max_feedrate[Z_AXIS], active_extruder);
  2938. st_synchronize();
  2939. }
  2940. // apply Y & Z extruder offset (x offset is already used in determining home pos)
  2941. current_position[Y_AXIS] = current_position[Y_AXIS] -
  2942. extruder_offset[Y_AXIS][active_extruder] +
  2943. extruder_offset[Y_AXIS][tmp_extruder];
  2944. current_position[Z_AXIS] = current_position[Z_AXIS] -
  2945. extruder_offset[Z_AXIS][active_extruder] +
  2946. extruder_offset[Z_AXIS][tmp_extruder];
  2947. active_extruder = tmp_extruder;
  2948. // This function resets the max/min values - the current position may be overwritten below.
  2949. axis_is_at_home(X_AXIS);
  2950. if (dual_x_carriage_mode == DXC_FULL_CONTROL_MODE)
  2951. {
  2952. current_position[X_AXIS] = inactive_extruder_x_pos;
  2953. inactive_extruder_x_pos = destination[X_AXIS];
  2954. }
  2955. else if (dual_x_carriage_mode == DXC_DUPLICATION_MODE)
  2956. {
  2957. active_extruder_parked = (active_extruder == 0); // this triggers the second extruder to move into the duplication position
  2958. if (active_extruder == 0 || active_extruder_parked)
  2959. current_position[X_AXIS] = inactive_extruder_x_pos;
  2960. else
  2961. current_position[X_AXIS] = destination[X_AXIS] + duplicate_extruder_x_offset;
  2962. inactive_extruder_x_pos = destination[X_AXIS];
  2963. extruder_duplication_enabled = false;
  2964. }
  2965. else
  2966. {
  2967. // record raised toolhead position for use by unpark
  2968. memcpy(raised_parked_position, current_position, sizeof(raised_parked_position));
  2969. raised_parked_position[Z_AXIS] += TOOLCHANGE_UNPARK_ZLIFT;
  2970. active_extruder_parked = true;
  2971. delayed_move_time = 0;
  2972. }
  2973. #else
  2974. // Offset extruder (only by XY)
  2975. int i;
  2976. for(i = 0; i < 2; i++) {
  2977. current_position[i] = current_position[i] -
  2978. extruder_offset[i][active_extruder] +
  2979. extruder_offset[i][tmp_extruder];
  2980. }
  2981. // Set the new active extruder and position
  2982. active_extruder = tmp_extruder;
  2983. #endif //else DUAL_X_CARRIAGE
  2984. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  2985. // Move to the old position if 'F' was in the parameters
  2986. if(make_move && Stopped == false) {
  2987. prepare_move();
  2988. }
  2989. }
  2990. #endif
  2991. SERIAL_ECHO_START;
  2992. SERIAL_ECHO(MSG_ACTIVE_EXTRUDER);
  2993. SERIAL_PROTOCOLLN((int)active_extruder);
  2994. }
  2995. }
  2996. else
  2997. {
  2998. SERIAL_ECHO_START;
  2999. SERIAL_ECHOPGM(MSG_UNKNOWN_COMMAND);
  3000. SERIAL_ECHO(cmdbuffer[bufindr]);
  3001. SERIAL_ECHOLNPGM("\"");
  3002. }
  3003. ClearToSend();
  3004. }
  3005. void FlushSerialRequestResend()
  3006. {
  3007. //char cmdbuffer[bufindr][100]="Resend:";
  3008. MYSERIAL.flush();
  3009. SERIAL_PROTOCOLPGM(MSG_RESEND);
  3010. SERIAL_PROTOCOLLN(gcode_LastN + 1);
  3011. ClearToSend();
  3012. }
  3013. void ClearToSend()
  3014. {
  3015. previous_millis_cmd = millis();
  3016. #ifdef SDSUPPORT
  3017. if(fromsd[bufindr])
  3018. return;
  3019. #endif //SDSUPPORT
  3020. SERIAL_PROTOCOLLNPGM(MSG_OK);
  3021. }
  3022. void get_coordinates()
  3023. {
  3024. bool seen[4]={false,false,false,false};
  3025. for(int8_t i=0; i < NUM_AXIS; i++) {
  3026. if(code_seen(axis_codes[i]))
  3027. {
  3028. destination[i] = (float)code_value() + (axis_relative_modes[i] || relative_mode)*current_position[i];
  3029. seen[i]=true;
  3030. }
  3031. else destination[i] = current_position[i]; //Are these else lines really needed?
  3032. }
  3033. if(code_seen('F')) {
  3034. next_feedrate = code_value();
  3035. if(next_feedrate > 0.0) feedrate = next_feedrate;
  3036. }
  3037. #ifdef FWRETRACT
  3038. if(autoretract_enabled)
  3039. if( !(seen[X_AXIS] || seen[Y_AXIS] || seen[Z_AXIS]) && seen[E_AXIS])
  3040. {
  3041. float echange=destination[E_AXIS]-current_position[E_AXIS];
  3042. if(echange<-MIN_RETRACT) //retract
  3043. {
  3044. if(!retracted)
  3045. {
  3046. destination[Z_AXIS]+=retract_zlift; //not sure why chaninging current_position negatively does not work.
  3047. //if slicer retracted by echange=-1mm and you want to retract 3mm, corrrectede=-2mm additionally
  3048. float correctede=-echange-retract_length;
  3049. //to generate the additional steps, not the destination is changed, but inversely the current position
  3050. current_position[E_AXIS]+=-correctede;
  3051. feedrate=retract_feedrate;
  3052. retracted=true;
  3053. }
  3054. }
  3055. else
  3056. if(echange>MIN_RETRACT) //retract_recover
  3057. {
  3058. if(retracted)
  3059. {
  3060. //current_position[Z_AXIS]+=-retract_zlift;
  3061. //if slicer retracted_recovered by echange=+1mm and you want to retract_recover 3mm, corrrectede=2mm additionally
  3062. float correctede=-echange+1*retract_length+retract_recover_length; //total unretract=retract_length+retract_recover_length[surplus]
  3063. current_position[E_AXIS]+=correctede; //to generate the additional steps, not the destination is changed, but inversely the current position
  3064. feedrate=retract_recover_feedrate;
  3065. retracted=false;
  3066. }
  3067. }
  3068. }
  3069. #endif //FWRETRACT
  3070. }
  3071. void get_arc_coordinates()
  3072. {
  3073. #ifdef SF_ARC_FIX
  3074. bool relative_mode_backup = relative_mode;
  3075. relative_mode = true;
  3076. #endif
  3077. get_coordinates();
  3078. #ifdef SF_ARC_FIX
  3079. relative_mode=relative_mode_backup;
  3080. #endif
  3081. if(code_seen('I')) {
  3082. offset[0] = code_value();
  3083. }
  3084. else {
  3085. offset[0] = 0.0;
  3086. }
  3087. if(code_seen('J')) {
  3088. offset[1] = code_value();
  3089. }
  3090. else {
  3091. offset[1] = 0.0;
  3092. }
  3093. }
  3094. void clamp_to_software_endstops(float target[3])
  3095. {
  3096. if (min_software_endstops) {
  3097. if (target[X_AXIS] < min_pos[X_AXIS]) target[X_AXIS] = min_pos[X_AXIS];
  3098. if (target[Y_AXIS] < min_pos[Y_AXIS]) target[Y_AXIS] = min_pos[Y_AXIS];
  3099. if (target[Z_AXIS] < min_pos[Z_AXIS]) target[Z_AXIS] = min_pos[Z_AXIS];
  3100. }
  3101. if (max_software_endstops) {
  3102. if (target[X_AXIS] > max_pos[X_AXIS]) target[X_AXIS] = max_pos[X_AXIS];
  3103. if (target[Y_AXIS] > max_pos[Y_AXIS]) target[Y_AXIS] = max_pos[Y_AXIS];
  3104. if (target[Z_AXIS] > max_pos[Z_AXIS]) target[Z_AXIS] = max_pos[Z_AXIS];
  3105. }
  3106. }
  3107. #ifdef DELTA
  3108. void calculate_delta(float cartesian[3])
  3109. {
  3110. delta[X_AXIS] = sqrt(DELTA_DIAGONAL_ROD_2
  3111. - sq(DELTA_TOWER1_X-cartesian[X_AXIS])
  3112. - sq(DELTA_TOWER1_Y-cartesian[Y_AXIS])
  3113. ) + cartesian[Z_AXIS];
  3114. delta[Y_AXIS] = sqrt(DELTA_DIAGONAL_ROD_2
  3115. - sq(DELTA_TOWER2_X-cartesian[X_AXIS])
  3116. - sq(DELTA_TOWER2_Y-cartesian[Y_AXIS])
  3117. ) + cartesian[Z_AXIS];
  3118. delta[Z_AXIS] = sqrt(DELTA_DIAGONAL_ROD_2
  3119. - sq(DELTA_TOWER3_X-cartesian[X_AXIS])
  3120. - sq(DELTA_TOWER3_Y-cartesian[Y_AXIS])
  3121. ) + cartesian[Z_AXIS];
  3122. /*
  3123. SERIAL_ECHOPGM("cartesian x="); SERIAL_ECHO(cartesian[X_AXIS]);
  3124. SERIAL_ECHOPGM(" y="); SERIAL_ECHO(cartesian[Y_AXIS]);
  3125. SERIAL_ECHOPGM(" z="); SERIAL_ECHOLN(cartesian[Z_AXIS]);
  3126. SERIAL_ECHOPGM("delta x="); SERIAL_ECHO(delta[X_AXIS]);
  3127. SERIAL_ECHOPGM(" y="); SERIAL_ECHO(delta[Y_AXIS]);
  3128. SERIAL_ECHOPGM(" z="); SERIAL_ECHOLN(delta[Z_AXIS]);
  3129. */
  3130. }
  3131. #endif
  3132. void prepare_move()
  3133. {
  3134. clamp_to_software_endstops(destination);
  3135. previous_millis_cmd = millis();
  3136. #ifdef DELTA
  3137. float difference[NUM_AXIS];
  3138. for (int8_t i=0; i < NUM_AXIS; i++) {
  3139. difference[i] = destination[i] - current_position[i];
  3140. }
  3141. float cartesian_mm = sqrt(sq(difference[X_AXIS]) +
  3142. sq(difference[Y_AXIS]) +
  3143. sq(difference[Z_AXIS]));
  3144. if (cartesian_mm < 0.000001) { cartesian_mm = abs(difference[E_AXIS]); }
  3145. if (cartesian_mm < 0.000001) { return; }
  3146. float seconds = 6000 * cartesian_mm / feedrate / feedmultiply;
  3147. int steps = max(1, int(DELTA_SEGMENTS_PER_SECOND * seconds));
  3148. // SERIAL_ECHOPGM("mm="); SERIAL_ECHO(cartesian_mm);
  3149. // SERIAL_ECHOPGM(" seconds="); SERIAL_ECHO(seconds);
  3150. // SERIAL_ECHOPGM(" steps="); SERIAL_ECHOLN(steps);
  3151. for (int s = 1; s <= steps; s++) {
  3152. float fraction = float(s) / float(steps);
  3153. for(int8_t i=0; i < NUM_AXIS; i++) {
  3154. destination[i] = current_position[i] + difference[i] * fraction;
  3155. }
  3156. calculate_delta(destination);
  3157. plan_buffer_line(delta[X_AXIS], delta[Y_AXIS], delta[Z_AXIS],
  3158. destination[E_AXIS], feedrate*feedmultiply/60/100.0,
  3159. active_extruder);
  3160. }
  3161. #else
  3162. #ifdef DUAL_X_CARRIAGE
  3163. if (active_extruder_parked)
  3164. {
  3165. if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && active_extruder == 0)
  3166. {
  3167. // move duplicate extruder into correct duplication position.
  3168. plan_set_position(inactive_extruder_x_pos, current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  3169. plan_buffer_line(current_position[X_AXIS] + duplicate_extruder_x_offset, current_position[Y_AXIS], current_position[Z_AXIS],
  3170. current_position[E_AXIS], max_feedrate[X_AXIS], 1);
  3171. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  3172. st_synchronize();
  3173. extruder_duplication_enabled = true;
  3174. active_extruder_parked = false;
  3175. }
  3176. else if (dual_x_carriage_mode == DXC_AUTO_PARK_MODE) // handle unparking of head
  3177. {
  3178. if (current_position[E_AXIS] == destination[E_AXIS])
  3179. {
  3180. // this is a travel move - skit it but keep track of current position (so that it can later
  3181. // be used as start of first non-travel move)
  3182. if (delayed_move_time != 0xFFFFFFFFUL)
  3183. {
  3184. memcpy(current_position, destination, sizeof(current_position));
  3185. if (destination[Z_AXIS] > raised_parked_position[Z_AXIS])
  3186. raised_parked_position[Z_AXIS] = destination[Z_AXIS];
  3187. delayed_move_time = millis();
  3188. return;
  3189. }
  3190. }
  3191. delayed_move_time = 0;
  3192. // unpark extruder: 1) raise, 2) move into starting XY position, 3) lower
  3193. plan_buffer_line(raised_parked_position[X_AXIS], raised_parked_position[Y_AXIS], raised_parked_position[Z_AXIS], current_position[E_AXIS], max_feedrate[Z_AXIS], active_extruder);
  3194. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], raised_parked_position[Z_AXIS],
  3195. current_position[E_AXIS], min(max_feedrate[X_AXIS],max_feedrate[Y_AXIS]), active_extruder);
  3196. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS],
  3197. current_position[E_AXIS], max_feedrate[Z_AXIS], active_extruder);
  3198. active_extruder_parked = false;
  3199. }
  3200. }
  3201. #endif //DUAL_X_CARRIAGE
  3202. // Do not use feedmultiply for E or Z only moves
  3203. if( (current_position[X_AXIS] == destination [X_AXIS]) && (current_position[Y_AXIS] == destination [Y_AXIS])) {
  3204. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  3205. }
  3206. else {
  3207. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate*feedmultiply/60/100.0, active_extruder);
  3208. }
  3209. #endif //else DELTA
  3210. for(int8_t i=0; i < NUM_AXIS; i++) {
  3211. current_position[i] = destination[i];
  3212. }
  3213. }
  3214. void prepare_arc_move(char isclockwise) {
  3215. float r = hypot(offset[X_AXIS], offset[Y_AXIS]); // Compute arc radius for mc_arc
  3216. // Trace the arc
  3217. mc_arc(current_position, destination, offset, X_AXIS, Y_AXIS, Z_AXIS, feedrate*feedmultiply/60/100.0, r, isclockwise, active_extruder);
  3218. // As far as the parser is concerned, the position is now == target. In reality the
  3219. // motion control system might still be processing the action and the real tool position
  3220. // in any intermediate location.
  3221. for(int8_t i=0; i < NUM_AXIS; i++) {
  3222. current_position[i] = destination[i];
  3223. }
  3224. previous_millis_cmd = millis();
  3225. }
  3226. #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1
  3227. #if defined(FAN_PIN)
  3228. #if CONTROLLERFAN_PIN == FAN_PIN
  3229. #error "You cannot set CONTROLLERFAN_PIN equal to FAN_PIN"
  3230. #endif
  3231. #endif
  3232. unsigned long lastMotor = 0; //Save the time for when a motor was turned on last
  3233. unsigned long lastMotorCheck = 0;
  3234. void controllerFan()
  3235. {
  3236. if ((millis() - lastMotorCheck) >= 2500) //Not a time critical function, so we only check every 2500ms
  3237. {
  3238. lastMotorCheck = millis();
  3239. if(!READ(X_ENABLE_PIN) || !READ(Y_ENABLE_PIN) || !READ(Z_ENABLE_PIN) || (soft_pwm_bed > 0)
  3240. #if EXTRUDERS > 2
  3241. || !READ(E2_ENABLE_PIN)
  3242. #endif
  3243. #if EXTRUDER > 1
  3244. #if defined(X2_ENABLE_PIN) && X2_ENABLE_PIN > -1
  3245. || !READ(X2_ENABLE_PIN)
  3246. #endif
  3247. || !READ(E1_ENABLE_PIN)
  3248. #endif
  3249. || !READ(E0_ENABLE_PIN)) //If any of the drivers are enabled...
  3250. {
  3251. lastMotor = millis(); //... set time to NOW so the fan will turn on
  3252. }
  3253. if ((millis() - lastMotor) >= (CONTROLLERFAN_SECS*1000UL) || lastMotor == 0) //If the last time any driver was enabled, is longer since than CONTROLLERSEC...
  3254. {
  3255. digitalWrite(CONTROLLERFAN_PIN, 0);
  3256. analogWrite(CONTROLLERFAN_PIN, 0);
  3257. }
  3258. else
  3259. {
  3260. // allows digital or PWM fan output to be used (see M42 handling)
  3261. digitalWrite(CONTROLLERFAN_PIN, CONTROLLERFAN_SPEED);
  3262. analogWrite(CONTROLLERFAN_PIN, CONTROLLERFAN_SPEED);
  3263. }
  3264. }
  3265. }
  3266. #endif
  3267. #ifdef TEMP_STAT_LEDS
  3268. static bool blue_led = false;
  3269. static bool red_led = false;
  3270. static uint32_t stat_update = 0;
  3271. void handle_status_leds(void) {
  3272. float max_temp = 0.0;
  3273. if(millis() > stat_update) {
  3274. stat_update += 500; // Update every 0.5s
  3275. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  3276. max_temp = max(max_temp, degHotend(cur_extruder));
  3277. max_temp = max(max_temp, degTargetHotend(cur_extruder));
  3278. }
  3279. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  3280. max_temp = max(max_temp, degTargetBed());
  3281. max_temp = max(max_temp, degBed());
  3282. #endif
  3283. if((max_temp > 55.0) && (red_led == false)) {
  3284. digitalWrite(STAT_LED_RED, 1);
  3285. digitalWrite(STAT_LED_BLUE, 0);
  3286. red_led = true;
  3287. blue_led = false;
  3288. }
  3289. if((max_temp < 54.0) && (blue_led == false)) {
  3290. digitalWrite(STAT_LED_RED, 0);
  3291. digitalWrite(STAT_LED_BLUE, 1);
  3292. red_led = false;
  3293. blue_led = true;
  3294. }
  3295. }
  3296. }
  3297. #endif
  3298. void manage_inactivity()
  3299. {
  3300. if( (millis() - previous_millis_cmd) > max_inactive_time )
  3301. if(max_inactive_time)
  3302. kill();
  3303. if(stepper_inactive_time) {
  3304. if( (millis() - previous_millis_cmd) > stepper_inactive_time )
  3305. {
  3306. if(blocks_queued() == false) {
  3307. disable_x();
  3308. disable_y();
  3309. disable_z();
  3310. disable_e0();
  3311. disable_e1();
  3312. disable_e2();
  3313. }
  3314. }
  3315. }
  3316. #if defined(KILL_PIN) && KILL_PIN > -1
  3317. if( 0 == READ(KILL_PIN) )
  3318. kill();
  3319. #endif
  3320. #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1
  3321. controllerFan(); //Check if fan should be turned on to cool stepper drivers down
  3322. #endif
  3323. #ifdef EXTRUDER_RUNOUT_PREVENT
  3324. if( (millis() - previous_millis_cmd) > EXTRUDER_RUNOUT_SECONDS*1000 )
  3325. if(degHotend(active_extruder)>EXTRUDER_RUNOUT_MINTEMP)
  3326. {
  3327. bool oldstatus=READ(E0_ENABLE_PIN);
  3328. enable_e0();
  3329. float oldepos=current_position[E_AXIS];
  3330. float oldedes=destination[E_AXIS];
  3331. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS],
  3332. destination[E_AXIS]+EXTRUDER_RUNOUT_EXTRUDE*EXTRUDER_RUNOUT_ESTEPS/axis_steps_per_unit[E_AXIS],
  3333. EXTRUDER_RUNOUT_SPEED/60.*EXTRUDER_RUNOUT_ESTEPS/axis_steps_per_unit[E_AXIS], active_extruder);
  3334. current_position[E_AXIS]=oldepos;
  3335. destination[E_AXIS]=oldedes;
  3336. plan_set_e_position(oldepos);
  3337. previous_millis_cmd=millis();
  3338. st_synchronize();
  3339. WRITE(E0_ENABLE_PIN,oldstatus);
  3340. }
  3341. #endif
  3342. #if defined(DUAL_X_CARRIAGE)
  3343. // handle delayed move timeout
  3344. if (delayed_move_time != 0 && (millis() - delayed_move_time) > 1000 && Stopped == false)
  3345. {
  3346. // travel moves have been received so enact them
  3347. delayed_move_time = 0xFFFFFFFFUL; // force moves to be done
  3348. memcpy(destination,current_position,sizeof(destination));
  3349. prepare_move();
  3350. }
  3351. #endif
  3352. #ifdef TEMP_STAT_LEDS
  3353. handle_status_leds();
  3354. #endif
  3355. check_axes_activity();
  3356. }
  3357. void kill()
  3358. {
  3359. cli(); // Stop interrupts
  3360. disable_heater();
  3361. disable_x();
  3362. disable_y();
  3363. disable_z();
  3364. disable_e0();
  3365. disable_e1();
  3366. disable_e2();
  3367. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  3368. pinMode(PS_ON_PIN,INPUT);
  3369. #endif
  3370. SERIAL_ERROR_START;
  3371. SERIAL_ERRORLNPGM(MSG_ERR_KILLED);
  3372. LCD_ALERTMESSAGEPGM(MSG_KILLED);
  3373. suicide();
  3374. while(1) { /* Intentionally left empty */ } // Wait for reset
  3375. }
  3376. void Stop()
  3377. {
  3378. disable_heater();
  3379. if(Stopped == false) {
  3380. Stopped = true;
  3381. Stopped_gcode_LastN = gcode_LastN; // Save last g_code for restart
  3382. SERIAL_ERROR_START;
  3383. SERIAL_ERRORLNPGM(MSG_ERR_STOPPED);
  3384. LCD_MESSAGEPGM(MSG_STOPPED);
  3385. }
  3386. }
  3387. bool IsStopped() { return Stopped; };
  3388. #ifdef FAST_PWM_FAN
  3389. void setPwmFrequency(uint8_t pin, int val)
  3390. {
  3391. val &= 0x07;
  3392. switch(digitalPinToTimer(pin))
  3393. {
  3394. #if defined(TCCR0A)
  3395. case TIMER0A:
  3396. case TIMER0B:
  3397. // TCCR0B &= ~(_BV(CS00) | _BV(CS01) | _BV(CS02));
  3398. // TCCR0B |= val;
  3399. break;
  3400. #endif
  3401. #if defined(TCCR1A)
  3402. case TIMER1A:
  3403. case TIMER1B:
  3404. // TCCR1B &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  3405. // TCCR1B |= val;
  3406. break;
  3407. #endif
  3408. #if defined(TCCR2)
  3409. case TIMER2:
  3410. case TIMER2:
  3411. TCCR2 &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  3412. TCCR2 |= val;
  3413. break;
  3414. #endif
  3415. #if defined(TCCR2A)
  3416. case TIMER2A:
  3417. case TIMER2B:
  3418. TCCR2B &= ~(_BV(CS20) | _BV(CS21) | _BV(CS22));
  3419. TCCR2B |= val;
  3420. break;
  3421. #endif
  3422. #if defined(TCCR3A)
  3423. case TIMER3A:
  3424. case TIMER3B:
  3425. case TIMER3C:
  3426. TCCR3B &= ~(_BV(CS30) | _BV(CS31) | _BV(CS32));
  3427. TCCR3B |= val;
  3428. break;
  3429. #endif
  3430. #if defined(TCCR4A)
  3431. case TIMER4A:
  3432. case TIMER4B:
  3433. case TIMER4C:
  3434. TCCR4B &= ~(_BV(CS40) | _BV(CS41) | _BV(CS42));
  3435. TCCR4B |= val;
  3436. break;
  3437. #endif
  3438. #if defined(TCCR5A)
  3439. case TIMER5A:
  3440. case TIMER5B:
  3441. case TIMER5C:
  3442. TCCR5B &= ~(_BV(CS50) | _BV(CS51) | _BV(CS52));
  3443. TCCR5B |= val;
  3444. break;
  3445. #endif
  3446. }
  3447. }
  3448. #endif //FAST_PWM_FAN
  3449. bool setTargetedHotend(int code){
  3450. tmp_extruder = active_extruder;
  3451. if(code_seen('T')) {
  3452. tmp_extruder = code_value();
  3453. if(tmp_extruder >= EXTRUDERS) {
  3454. SERIAL_ECHO_START;
  3455. switch(code){
  3456. case 104:
  3457. SERIAL_ECHO(MSG_M104_INVALID_EXTRUDER);
  3458. break;
  3459. case 105:
  3460. SERIAL_ECHO(MSG_M105_INVALID_EXTRUDER);
  3461. break;
  3462. case 109:
  3463. SERIAL_ECHO(MSG_M109_INVALID_EXTRUDER);
  3464. break;
  3465. case 218:
  3466. SERIAL_ECHO(MSG_M218_INVALID_EXTRUDER);
  3467. break;
  3468. }
  3469. SERIAL_ECHOLN(tmp_extruder);
  3470. return true;
  3471. }
  3472. }
  3473. return false;
  3474. }