Marlin_main.cpp 175 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124
  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 AUTO_BED_LEVELING_GRID
  27. #include "qr_solve.h"
  28. #endif
  29. #endif // ENABLE_AUTO_BED_LEVELING
  30. #ifdef MESH_BED_LEVELING
  31. #include "mesh_bed_leveling.h"
  32. #include "mesh_bed_calibration.h"
  33. #endif
  34. #include "ultralcd.h"
  35. #include "Configuration_prusa.h"
  36. #include "planner.h"
  37. #include "stepper.h"
  38. #include "temperature.h"
  39. #include "motion_control.h"
  40. #include "cardreader.h"
  41. #include "watchdog.h"
  42. #include "ConfigurationStore.h"
  43. #include "language.h"
  44. #include "pins_arduino.h"
  45. #include "math.h"
  46. #ifdef BLINKM
  47. #include "BlinkM.h"
  48. #include "Wire.h"
  49. #endif
  50. #ifdef ULTRALCD
  51. #include "ultralcd.h"
  52. #endif
  53. #if NUM_SERVOS > 0
  54. #include "Servo.h"
  55. #endif
  56. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  57. #include <SPI.h>
  58. #endif
  59. #define VERSION_STRING "1.0.2"
  60. #include "ultralcd.h"
  61. // Macros for bit masks
  62. #define BIT(b) (1<<(b))
  63. #define TEST(n,b) (((n)&BIT(b))!=0)
  64. #define SET_BIT(n,b,value) (n) ^= ((-value)^(n)) & (BIT(b))
  65. // look here for descriptions of G-codes: http://linuxcnc.org/handbook/gcode/g-code.html
  66. // http://objects.reprap.org/wiki/Mendel_User_Manual:_RepRapGCodes
  67. //Implemented Codes
  68. //-------------------
  69. // PRUSA CODES
  70. // P F - Returns FW versions
  71. // P R - Returns revision of printer
  72. // G0 -> G1
  73. // G1 - Coordinated Movement X Y Z E
  74. // G2 - CW ARC
  75. // G3 - CCW ARC
  76. // G4 - Dwell S<seconds> or P<milliseconds>
  77. // G10 - retract filament according to settings of M207
  78. // G11 - retract recover filament according to settings of M208
  79. // G28 - Home all Axis
  80. // G29 - Detailed Z-Probe, probes the bed at 3 or more points. Will fail if you haven't homed yet.
  81. // G30 - Single Z Probe, probes bed at current XY location.
  82. // G31 - Dock sled (Z_PROBE_SLED only)
  83. // G32 - Undock sled (Z_PROBE_SLED only)
  84. // G80 - Automatic mesh bed leveling
  85. // G81 - Print bed profile
  86. // G90 - Use Absolute Coordinates
  87. // G91 - Use Relative Coordinates
  88. // G92 - Set current position to coordinates given
  89. // M Codes
  90. // M0 - Unconditional stop - Wait for user to press a button on the LCD (Only if ULTRA_LCD is enabled)
  91. // M1 - Same as M0
  92. // M17 - Enable/Power all stepper motors
  93. // M18 - Disable all stepper motors; same as M84
  94. // M20 - List SD card
  95. // M21 - Init SD card
  96. // M22 - Release SD card
  97. // M23 - Select SD file (M23 filename.g)
  98. // M24 - Start/resume SD print
  99. // M25 - Pause SD print
  100. // M26 - Set SD position in bytes (M26 S12345)
  101. // M27 - Report SD print status
  102. // M28 - Start SD write (M28 filename.g)
  103. // M29 - Stop SD write
  104. // M30 - Delete file from SD (M30 filename.g)
  105. // M31 - Output time since last M109 or SD card start to serial
  106. // M32 - Select file and start SD print (Can be used _while_ printing from SD card files):
  107. // syntax "M32 /path/filename#", or "M32 S<startpos bytes> !filename#"
  108. // Call gcode file : "M32 P !filename#" and return to caller file after finishing (similar to #include).
  109. // The '#' is necessary when calling from within sd files, as it stops buffer prereading
  110. // 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.
  111. // M80 - Turn on Power Supply
  112. // M81 - Turn off Power Supply
  113. // M82 - Set E codes absolute (default)
  114. // M83 - Set E codes relative while in Absolute Coordinates (G90) mode
  115. // M84 - Disable steppers until next move,
  116. // or use S<seconds> to specify an inactivity timeout, after which the steppers will be disabled. S0 to disable the timeout.
  117. // M85 - Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
  118. // M92 - Set axis_steps_per_unit - same syntax as G92
  119. // M104 - Set extruder target temp
  120. // M105 - Read current temp
  121. // M106 - Fan on
  122. // M107 - Fan off
  123. // M109 - Sxxx Wait for extruder current temp to reach target temp. Waits only when heating
  124. // Rxxx Wait for extruder current temp to reach target temp. Waits when heating and cooling
  125. // IF AUTOTEMP is enabled, S<mintemp> B<maxtemp> F<factor>. Exit autotemp by any M109 without F
  126. // M112 - Emergency stop
  127. // M114 - Output current position to serial port
  128. // M115 - Capabilities string
  129. // M117 - display message
  130. // M119 - Output Endstop status to serial port
  131. // M126 - Solenoid Air Valve Open (BariCUDA support by jmil)
  132. // M127 - Solenoid Air Valve Closed (BariCUDA vent to atmospheric pressure by jmil)
  133. // M128 - EtoP Open (BariCUDA EtoP = electricity to air pressure transducer by jmil)
  134. // M129 - EtoP Closed (BariCUDA EtoP = electricity to air pressure transducer by jmil)
  135. // M140 - Set bed target temp
  136. // M150 - Set BlinkM Color Output R: Red<0-255> U(!): Green<0-255> B: Blue<0-255> over i2c, G for green does not work.
  137. // M190 - Sxxx Wait for bed current temp to reach target temp. Waits only when heating
  138. // Rxxx Wait for bed current temp to reach target temp. Waits when heating and cooling
  139. // M200 D<millimeters>- set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).
  140. // M201 - Set max acceleration in units/s^2 for print moves (M201 X1000 Y1000)
  141. // M202 - Set max acceleration in units/s^2 for travel moves (M202 X1000 Y1000) Unused in Marlin!!
  142. // M203 - Set maximum feedrate that your machine can sustain (M203 X200 Y200 Z300 E10000) in mm/sec
  143. // M204 - Set default acceleration: S normal moves T filament only moves (M204 S3000 T7000) in mm/sec^2 also sets minimum segment time in ms (B20000) to prevent buffer under-runs and M20 minimum feedrate
  144. // 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
  145. // M206 - set additional homing offset
  146. // M207 - set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop], stays in mm regardless of M200 setting
  147. // M208 - set recover=unretract length S[positive mm surplus to the M207 S*] F[feedrate mm/sec]
  148. // 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.
  149. // M218 - set hotend offset (in mm): T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  150. // M220 S<factor in percent>- set speed factor override percentage
  151. // M221 S<factor in percent>- set extrude factor override percentage
  152. // M226 P<pin number> S<pin state>- Wait until the specified pin reaches the state required
  153. // M240 - Trigger a camera to take a photograph
  154. // M250 - Set LCD contrast C<contrast value> (value 0..63)
  155. // M280 - set servo position absolute. P: servo index, S: angle or microseconds
  156. // M300 - Play beep sound S<frequency Hz> P<duration ms>
  157. // M301 - Set PID parameters P I and D
  158. // M302 - Allow cold extrudes, or set the minimum extrude S<temperature>.
  159. // M303 - PID relay autotune S<temperature> sets the target temperature. (default target temperature = 150C)
  160. // M304 - Set bed PID parameters P I and D
  161. // M400 - Finish all moves
  162. // M401 - Lower z-probe if present
  163. // M402 - Raise z-probe if present
  164. // M404 - N<dia in mm> Enter the nominal filament width (3mm, 1.75mm ) or will display nominal filament width without parameters
  165. // M405 - Turn on Filament Sensor extrusion control. Optional D<delay in cm> to set delay in centimeters between sensor and extruder
  166. // M406 - Turn off Filament Sensor extrusion control
  167. // M407 - Displays measured filament diameter
  168. // M500 - stores parameters in EEPROM
  169. // M501 - reads parameters from EEPROM (if you need reset them after you changed them temporarily).
  170. // M502 - reverts to the default "factory settings". You still need to store them in EEPROM afterwards if you want to.
  171. // M503 - print the current settings (from memory not from EEPROM)
  172. // M509 - force language selection on next restart
  173. // M540 - Use S[0|1] to enable or disable the stop SD card print on endstop hit (requires ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  174. // M600 - Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  175. // M605 - Set dual x-carriage movement mode: S<mode> [ X<duplication x-offset> R<duplication temp offset> ]
  176. // M907 - Set digital trimpot motor current using axis codes.
  177. // M908 - Control digital trimpot directly.
  178. // M350 - Set microstepping mode.
  179. // M351 - Toggle MS1 MS2 pins directly.
  180. // M928 - Start SD logging (M928 filename.g) - ended by M29
  181. // M999 - Restart after being stopped by error
  182. //Stepper Movement Variables
  183. //===========================================================================
  184. //=============================imported variables============================
  185. //===========================================================================
  186. //===========================================================================
  187. //=============================public variables=============================
  188. //===========================================================================
  189. #ifdef SDSUPPORT
  190. CardReader card;
  191. #endif
  192. union Data
  193. {
  194. byte b[2];
  195. int value;
  196. };
  197. int babystepLoad[3];
  198. float homing_feedrate[] = HOMING_FEEDRATE;
  199. // Currently only the extruder axis may be switched to a relative mode.
  200. // Other axes are always absolute or relative based on the common relative_mode flag.
  201. bool axis_relative_modes[] = AXIS_RELATIVE_MODES;
  202. int feedmultiply=100; //100->1 200->2
  203. int saved_feedmultiply;
  204. int extrudemultiply=100; //100->1 200->2
  205. int extruder_multiply[EXTRUDERS] = {100
  206. #if EXTRUDERS > 1
  207. , 100
  208. #if EXTRUDERS > 2
  209. , 100
  210. #endif
  211. #endif
  212. };
  213. bool is_usb_printing = false;
  214. bool _doMeshL = false;
  215. unsigned int usb_printing_counter;
  216. int lcd_change_fil_state = 0;
  217. int feedmultiplyBckp = 100;
  218. unsigned char lang_selected = 0;
  219. unsigned long total_filament_used;
  220. unsigned int heating_status;
  221. unsigned int heating_status_counter;
  222. bool custom_message;
  223. unsigned int custom_message_type;
  224. unsigned int custom_message_state;
  225. bool volumetric_enabled = false;
  226. float filament_size[EXTRUDERS] = { DEFAULT_NOMINAL_FILAMENT_DIA
  227. #if EXTRUDERS > 1
  228. , DEFAULT_NOMINAL_FILAMENT_DIA
  229. #if EXTRUDERS > 2
  230. , DEFAULT_NOMINAL_FILAMENT_DIA
  231. #endif
  232. #endif
  233. };
  234. float volumetric_multiplier[EXTRUDERS] = {1.0
  235. #if EXTRUDERS > 1
  236. , 1.0
  237. #if EXTRUDERS > 2
  238. , 1.0
  239. #endif
  240. #endif
  241. };
  242. float current_position[NUM_AXIS] = { 0.0, 0.0, 0.0, 0.0 };
  243. float add_homing[3]={0,0,0};
  244. float min_pos[3] = { X_MIN_POS, Y_MIN_POS, Z_MIN_POS };
  245. float max_pos[3] = { X_MAX_POS, Y_MAX_POS, Z_MAX_POS };
  246. bool axis_known_position[3] = {false, false, false};
  247. float zprobe_zoffset;
  248. // Extruder offset
  249. #if EXTRUDERS > 1
  250. #ifndef DUAL_X_CARRIAGE
  251. #define NUM_EXTRUDER_OFFSETS 2 // only in XY plane
  252. #else
  253. #define NUM_EXTRUDER_OFFSETS 3 // supports offsets in XYZ plane
  254. #endif
  255. float extruder_offset[NUM_EXTRUDER_OFFSETS][EXTRUDERS] = {
  256. #if defined(EXTRUDER_OFFSET_X) && defined(EXTRUDER_OFFSET_Y)
  257. EXTRUDER_OFFSET_X, EXTRUDER_OFFSET_Y
  258. #endif
  259. };
  260. #endif
  261. uint8_t active_extruder = 0;
  262. int fanSpeed=0;
  263. #ifdef FWRETRACT
  264. bool autoretract_enabled=false;
  265. bool retracted[EXTRUDERS]={false
  266. #if EXTRUDERS > 1
  267. , false
  268. #if EXTRUDERS > 2
  269. , false
  270. #endif
  271. #endif
  272. };
  273. bool retracted_swap[EXTRUDERS]={false
  274. #if EXTRUDERS > 1
  275. , false
  276. #if EXTRUDERS > 2
  277. , false
  278. #endif
  279. #endif
  280. };
  281. float retract_length = RETRACT_LENGTH;
  282. float retract_length_swap = RETRACT_LENGTH_SWAP;
  283. float retract_feedrate = RETRACT_FEEDRATE;
  284. float retract_zlift = RETRACT_ZLIFT;
  285. float retract_recover_length = RETRACT_RECOVER_LENGTH;
  286. float retract_recover_length_swap = RETRACT_RECOVER_LENGTH_SWAP;
  287. float retract_recover_feedrate = RETRACT_RECOVER_FEEDRATE;
  288. #endif
  289. #ifdef ULTIPANEL
  290. #ifdef PS_DEFAULT_OFF
  291. bool powersupply = false;
  292. #else
  293. bool powersupply = true;
  294. #endif
  295. #endif
  296. bool cancel_heatup = false ;
  297. #ifdef FILAMENT_SENSOR
  298. //Variables for Filament Sensor input
  299. float filament_width_nominal=DEFAULT_NOMINAL_FILAMENT_DIA; //Set nominal filament width, can be changed with M404
  300. bool filament_sensor=false; //M405 turns on filament_sensor control, M406 turns it off
  301. float filament_width_meas=DEFAULT_MEASURED_FILAMENT_DIA; //Stores the measured filament diameter
  302. signed char measurement_delay[MAX_MEASUREMENT_DELAY+1]; //ring buffer to delay measurement store extruder factor after subtracting 100
  303. int delay_index1=0; //index into ring buffer
  304. int delay_index2=-1; //index into ring buffer - set to -1 on startup to indicate ring buffer needs to be initialized
  305. float delay_dist=0; //delay distance counter
  306. int meas_delay_cm = MEASUREMENT_DELAY_CM; //distance delay setting
  307. #endif
  308. const char errormagic[] PROGMEM = "Error:";
  309. const char echomagic[] PROGMEM = "echo:";
  310. //===========================================================================
  311. //=============================Private Variables=============================
  312. //===========================================================================
  313. const char axis_codes[NUM_AXIS] = {'X', 'Y', 'Z', 'E'};
  314. float destination[NUM_AXIS] = { 0.0, 0.0, 0.0, 0.0};
  315. static float delta[3] = {0.0, 0.0, 0.0};
  316. // For tracing an arc
  317. static float offset[3] = {0.0, 0.0, 0.0};
  318. static bool home_all_axis = true;
  319. static float feedrate = 1500.0, next_feedrate, saved_feedrate;
  320. static long gcode_N, gcode_LastN, Stopped_gcode_LastN = 0;
  321. // Determines Absolute or Relative Coordinates.
  322. // Also there is bool axis_relative_modes[] per axis flag.
  323. static bool relative_mode = false;
  324. // String circular buffer. Commands may be pushed to the buffer from both sides:
  325. // Chained commands will be pushed to the front, interactive (from LCD menu)
  326. // and printing commands (from serial line or from SD card) are pushed to the tail.
  327. // First character of each entry indicates the type of the entry:
  328. #define CMDBUFFER_CURRENT_TYPE_UNKNOWN 0
  329. // Command in cmdbuffer was sent over USB.
  330. #define CMDBUFFER_CURRENT_TYPE_USB 1
  331. // Command in cmdbuffer was read from SDCARD.
  332. #define CMDBUFFER_CURRENT_TYPE_SDCARD 2
  333. // Command in cmdbuffer was generated by the UI.
  334. #define CMDBUFFER_CURRENT_TYPE_UI 3
  335. // Command in cmdbuffer was generated by another G-code.
  336. #define CMDBUFFER_CURRENT_TYPE_CHAINED 4
  337. // How much space to reserve for the chained commands
  338. // of type CMDBUFFER_CURRENT_TYPE_CHAINED,
  339. // which are pushed to the front of the queue?
  340. // Maximum 5 commands of max length 20 + null terminator.
  341. #define CMDBUFFER_RESERVE_FRONT (5*21)
  342. // Reserve BUFSIZE lines of length MAX_CMD_SIZE plus CMDBUFFER_RESERVE_FRONT.
  343. static char cmdbuffer[BUFSIZE * (MAX_CMD_SIZE + 1) + CMDBUFFER_RESERVE_FRONT];
  344. // Head of the circular buffer, where to read.
  345. static int bufindr = 0;
  346. // Tail of the buffer, where to write.
  347. static int bufindw = 0;
  348. // Number of lines in cmdbuffer.
  349. static int buflen = 0;
  350. // Flag for processing the current command inside the main Arduino loop().
  351. // If a new command was pushed to the front of a command buffer while
  352. // processing another command, this replaces the command on the top.
  353. // Therefore don't remove the command from the queue in the loop() function.
  354. static bool cmdbuffer_front_already_processed = false;
  355. // Type of a command, which is to be executed right now.
  356. #define CMDBUFFER_CURRENT_TYPE (cmdbuffer[bufindr])
  357. // String of a command, which is to be executed right now.
  358. #define CMDBUFFER_CURRENT_STRING (cmdbuffer+bufindr+1)
  359. // Enable debugging of the command buffer.
  360. // Debugging information will be sent to serial line.
  361. // #define CMDBUFFER_DEBUG
  362. static int serial_count = 0;
  363. static boolean comment_mode = false;
  364. static char *strchr_pointer; // just a pointer to find chars in the command string like X, Y, Z, E, etc
  365. const int sensitive_pins[] = SENSITIVE_PINS; // Sensitive pin list for M42
  366. //static float tt = 0;
  367. //static float bt = 0;
  368. //Inactivity shutdown variables
  369. static unsigned long previous_millis_cmd = 0;
  370. static unsigned long max_inactive_time = 0;
  371. static unsigned long stepper_inactive_time = DEFAULT_STEPPER_DEACTIVE_TIME*1000l;
  372. unsigned long starttime=0;
  373. unsigned long stoptime=0;
  374. unsigned long _usb_timer = 0;
  375. static uint8_t tmp_extruder;
  376. bool Stopped=false;
  377. #if NUM_SERVOS > 0
  378. Servo servos[NUM_SERVOS];
  379. #endif
  380. bool CooldownNoWait = true;
  381. bool target_direction;
  382. //Insert variables if CHDK is defined
  383. #ifdef CHDK
  384. unsigned long chdkHigh = 0;
  385. boolean chdkActive = false;
  386. #endif
  387. //===========================================================================
  388. //=============================Routines======================================
  389. //===========================================================================
  390. void get_arc_coordinates();
  391. bool setTargetedHotend(int code);
  392. void serial_echopair_P(const char *s_P, float v)
  393. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  394. void serial_echopair_P(const char *s_P, double v)
  395. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  396. void serial_echopair_P(const char *s_P, unsigned long v)
  397. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  398. #ifdef SDSUPPORT
  399. #include "SdFatUtil.h"
  400. int freeMemory() { return SdFatUtil::FreeRam(); }
  401. #else
  402. extern "C" {
  403. extern unsigned int __bss_end;
  404. extern unsigned int __heap_start;
  405. extern void *__brkval;
  406. int freeMemory() {
  407. int free_memory;
  408. if ((int)__brkval == 0)
  409. free_memory = ((int)&free_memory) - ((int)&__bss_end);
  410. else
  411. free_memory = ((int)&free_memory) - ((int)__brkval);
  412. return free_memory;
  413. }
  414. }
  415. #endif //!SDSUPPORT
  416. // Pop the currently processed command from the queue.
  417. // It is expected, that there is at least one command in the queue.
  418. void cmdqueue_pop_front()
  419. {
  420. if (buflen > 0) {
  421. #ifdef CMDBUFFER_DEBUG
  422. SERIAL_ECHOPGM("Dequeing ");
  423. SERIAL_ECHO(cmdbuffer+bufindr+1);
  424. SERIAL_ECHOLNPGM("");
  425. SERIAL_ECHOPGM("Old indices: buflen ");
  426. SERIAL_ECHO(buflen);
  427. SERIAL_ECHOPGM(", bufindr ");
  428. SERIAL_ECHO(bufindr);
  429. SERIAL_ECHOPGM(", bufindw ");
  430. SERIAL_ECHO(bufindw);
  431. SERIAL_ECHOPGM(", serial_count ");
  432. SERIAL_ECHO(serial_count);
  433. SERIAL_ECHOPGM(", bufsize ");
  434. SERIAL_ECHO(sizeof(cmdbuffer));
  435. SERIAL_ECHOLNPGM("");
  436. #endif /* CMDBUFFER_DEBUG */
  437. if (-- buflen == 0) {
  438. // Empty buffer.
  439. if (serial_count == 0)
  440. // No serial communication is pending. Reset both pointers to zero.
  441. bufindw = 0;
  442. bufindr = bufindw;
  443. } else {
  444. // There is at least one ready line in the buffer.
  445. // First skip the current command ID and iterate up to the end of the string.
  446. for (++ bufindr; cmdbuffer[bufindr] != 0; ++ bufindr) ;
  447. // Second, skip the end of string null character and iterate until a nonzero command ID is found.
  448. for (++ bufindr; bufindr < sizeof(cmdbuffer) && cmdbuffer[bufindr] == 0; ++ bufindr) ;
  449. // If the end of the buffer was empty,
  450. if (bufindr == sizeof(cmdbuffer)) {
  451. // skip to the start and find the nonzero command.
  452. for (bufindr = 0; cmdbuffer[bufindr] == 0; ++ bufindr) ;
  453. }
  454. #ifdef CMDBUFFER_DEBUG
  455. SERIAL_ECHOPGM("New indices: buflen ");
  456. SERIAL_ECHO(buflen);
  457. SERIAL_ECHOPGM(", bufindr ");
  458. SERIAL_ECHO(bufindr);
  459. SERIAL_ECHOPGM(", bufindw ");
  460. SERIAL_ECHO(bufindw);
  461. SERIAL_ECHOPGM(", serial_count ");
  462. SERIAL_ECHO(serial_count);
  463. SERIAL_ECHOPGM(" new command on the top: ");
  464. SERIAL_ECHO(cmdbuffer+bufindr+1);
  465. SERIAL_ECHOLNPGM("");
  466. #endif /* CMDBUFFER_DEBUG */
  467. }
  468. }
  469. }
  470. // How long a string could be pushed to the front of the command queue?
  471. // If yes, adjust bufindr to the new position, where the new command could be enqued.
  472. // len_asked does not contain the zero terminator size.
  473. bool cmdqueue_could_enqueue_front(int len_asked)
  474. {
  475. // MAX_CMD_SIZE has to accommodate the zero terminator.
  476. if (len_asked >= MAX_CMD_SIZE)
  477. return false;
  478. // Remove the currently processed command from the queue.
  479. if (! cmdbuffer_front_already_processed) {
  480. cmdqueue_pop_front();
  481. cmdbuffer_front_already_processed = true;
  482. }
  483. if (bufindr == bufindw && buflen > 0)
  484. // Full buffer.
  485. return false;
  486. // Adjust the end of the write buffer based on whether a partial line is in the receive buffer.
  487. int endw = (serial_count > 0) ? (bufindw + MAX_CMD_SIZE + 1) : bufindw;
  488. if (bufindw < bufindr) {
  489. int bufindr_new = bufindr - len_asked - 2;
  490. // Simple case. There is a contiguous space between the write buffer and the read buffer.
  491. if (endw <= bufindr_new) {
  492. bufindr = bufindr_new;
  493. return true;
  494. }
  495. } else {
  496. // Otherwise the free space is split between the start and end.
  497. if (len_asked + 2 <= bufindr) {
  498. // Could fit at the start.
  499. bufindr -= len_asked + 2;
  500. return true;
  501. }
  502. int bufindr_new = sizeof(cmdbuffer) - len_asked - 2;
  503. if (endw <= bufindr_new) {
  504. memset(cmdbuffer, 0, bufindr);
  505. bufindr = bufindr_new;
  506. return true;
  507. }
  508. }
  509. return false;
  510. }
  511. // Could one enqueue a command of lenthg len_asked into the buffer,
  512. // while leaving CMDBUFFER_RESERVE_FRONT at the start?
  513. // If yes, adjust bufindw to the new position, where the new command could be enqued.
  514. // len_asked does not contain the zero terminator size.
  515. bool cmdqueue_could_enqueue_back(int len_asked)
  516. {
  517. // MAX_CMD_SIZE has to accommodate the zero terminator.
  518. if (len_asked >= MAX_CMD_SIZE)
  519. return false;
  520. if (bufindr == bufindw && buflen > 0)
  521. // Full buffer.
  522. return false;
  523. if (serial_count > 0) {
  524. // If there is some data stored starting at bufindw, len_asked is certainly smaller than
  525. // the allocated data buffer. Try to reserve a new buffer and to move the already received
  526. // serial data.
  527. // How much memory to reserve for the commands pushed to the front?
  528. // End of the queue, when pushing to the end.
  529. int endw = bufindw + len_asked + 2;
  530. if (bufindw < bufindr)
  531. // Simple case. There is a contiguous space between the write buffer and the read buffer.
  532. return endw + CMDBUFFER_RESERVE_FRONT <= bufindr;
  533. // Otherwise the free space is split between the start and end.
  534. if (// Could one fit to the end, including the reserve?
  535. endw + CMDBUFFER_RESERVE_FRONT <= sizeof(cmdbuffer) ||
  536. // Could one fit to the end, and the reserve to the start?
  537. (endw <= sizeof(cmdbuffer) && CMDBUFFER_RESERVE_FRONT <= bufindr))
  538. return true;
  539. // Could one fit both to the start?
  540. if (len_asked + 2 + CMDBUFFER_RESERVE_FRONT <= bufindr) {
  541. // Mark the rest of the buffer as used.
  542. memset(cmdbuffer+bufindw, 0, sizeof(cmdbuffer)-bufindw);
  543. // and point to the start.
  544. bufindw = 0;
  545. return true;
  546. }
  547. } else {
  548. // How much memory to reserve for the commands pushed to the front?
  549. // End of the queue, when pushing to the end.
  550. int endw = bufindw + len_asked + 2;
  551. if (bufindw < bufindr)
  552. // Simple case. There is a contiguous space between the write buffer and the read buffer.
  553. return endw + CMDBUFFER_RESERVE_FRONT <= bufindr;
  554. // Otherwise the free space is split between the start and end.
  555. if (// Could one fit to the end, including the reserve?
  556. endw + CMDBUFFER_RESERVE_FRONT <= sizeof(cmdbuffer) ||
  557. // Could one fit to the end, and the reserve to the start?
  558. (endw <= sizeof(cmdbuffer) && CMDBUFFER_RESERVE_FRONT <= bufindr))
  559. return true;
  560. // Could one fit both to the start?
  561. if (len_asked + 2 + CMDBUFFER_RESERVE_FRONT <= bufindr) {
  562. // Mark the rest of the buffer as used.
  563. memset(cmdbuffer+bufindw, 0, sizeof(cmdbuffer)-bufindw);
  564. // and point to the start.
  565. bufindw = 0;
  566. return true;
  567. }
  568. }
  569. return false;
  570. }
  571. #ifdef CMDBUFFER_DEBUG
  572. static void cmdqueue_dump_to_serial_single_line(int nr, const char *p)
  573. {
  574. SERIAL_ECHOPGM("Entry nr: ");
  575. SERIAL_ECHO(nr);
  576. SERIAL_ECHOPGM(", type: ");
  577. SERIAL_ECHO(int(*p));
  578. SERIAL_ECHOPGM(", cmd: ");
  579. SERIAL_ECHO(p+1);
  580. SERIAL_ECHOLNPGM("");
  581. }
  582. static void cmdqueue_dump_to_serial()
  583. {
  584. if (buflen == 0) {
  585. SERIAL_ECHOLNPGM("The command buffer is empty.");
  586. } else {
  587. SERIAL_ECHOPGM("Content of the buffer: entries ");
  588. SERIAL_ECHO(buflen);
  589. SERIAL_ECHOPGM(", indr ");
  590. SERIAL_ECHO(bufindr);
  591. SERIAL_ECHOPGM(", indw ");
  592. SERIAL_ECHO(bufindw);
  593. SERIAL_ECHOLNPGM("");
  594. int nr = 0;
  595. if (bufindr < bufindw) {
  596. for (const char *p = cmdbuffer + bufindr; p < cmdbuffer + bufindw; ++ nr) {
  597. cmdqueue_dump_to_serial_single_line(nr, p);
  598. // Skip the command.
  599. for (++p; *p != 0; ++ p);
  600. // Skip the gaps.
  601. for (++p; p < cmdbuffer + bufindw && *p == 0; ++ p);
  602. }
  603. } else {
  604. for (const char *p = cmdbuffer + bufindr; p < cmdbuffer + sizeof(cmdbuffer); ++ nr) {
  605. cmdqueue_dump_to_serial_single_line(nr, p);
  606. // Skip the command.
  607. for (++p; *p != 0; ++ p);
  608. // Skip the gaps.
  609. for (++p; p < cmdbuffer + sizeof(cmdbuffer) && *p == 0; ++ p);
  610. }
  611. for (const char *p = cmdbuffer; p < cmdbuffer + bufindw; ++ nr) {
  612. cmdqueue_dump_to_serial_single_line(nr, p);
  613. // Skip the command.
  614. for (++p; *p != 0; ++ p);
  615. // Skip the gaps.
  616. for (++p; p < cmdbuffer + bufindw && *p == 0; ++ p);
  617. }
  618. }
  619. SERIAL_ECHOLNPGM("End of the buffer.");
  620. }
  621. }
  622. #endif /* CMDBUFFER_DEBUG */
  623. //adds an command to the main command buffer
  624. //thats really done in a non-safe way.
  625. //needs overworking someday
  626. // Currently the maximum length of a command piped through this function is around 20 characters
  627. void enquecommand(const char *cmd, bool from_progmem)
  628. {
  629. int len = from_progmem ? strlen_P(cmd) : strlen(cmd);
  630. // Does cmd fit the queue while leaving sufficient space at the front for the chained commands?
  631. // If it fits, it may move bufindw, so it points to a contiguous buffer, which fits cmd.
  632. if (cmdqueue_could_enqueue_back(len)) {
  633. // This is dangerous if a mixing of serial and this happens
  634. // This may easily be tested: If serial_count > 0, we have a problem.
  635. cmdbuffer[bufindw] = CMDBUFFER_CURRENT_TYPE_UI;
  636. if (from_progmem)
  637. strcpy_P(cmdbuffer + bufindw + 1, cmd);
  638. else
  639. strcpy(cmdbuffer + bufindw + 1, cmd);
  640. SERIAL_ECHO_START;
  641. SERIAL_ECHORPGM(MSG_Enqueing);
  642. SERIAL_ECHO(cmdbuffer + bufindw + 1);
  643. SERIAL_ECHOLNPGM("\"");
  644. bufindw += len + 2;
  645. if (bufindw == sizeof(cmdbuffer))
  646. bufindw = 0;
  647. ++ buflen;
  648. #ifdef CMDBUFFER_DEBUG
  649. cmdqueue_dump_to_serial();
  650. #endif /* CMDBUFFER_DEBUG */
  651. } else {
  652. SERIAL_ECHO_START;
  653. SERIAL_ECHORPGM(MSG_Enqueing);
  654. if (from_progmem)
  655. SERIAL_PROTOCOLRPGM(cmd);
  656. else
  657. SERIAL_ECHO(cmd);
  658. SERIAL_ECHOLNPGM("\" failed: Buffer full!");
  659. #ifdef CMDBUFFER_DEBUG
  660. cmdqueue_dump_to_serial();
  661. #endif /* CMDBUFFER_DEBUG */
  662. }
  663. }
  664. void enquecommand_front(const char *cmd, bool from_progmem)
  665. {
  666. int len = from_progmem ? strlen_P(cmd) : strlen(cmd);
  667. // Does cmd fit the queue? This call shall move bufindr, so the command may be copied.
  668. if (cmdqueue_could_enqueue_front(len)) {
  669. cmdbuffer[bufindr] = CMDBUFFER_CURRENT_TYPE_UI;
  670. if (from_progmem)
  671. strcpy_P(cmdbuffer + bufindr + 1, cmd);
  672. else
  673. strcpy(cmdbuffer + bufindr + 1, cmd);
  674. ++ buflen;
  675. SERIAL_ECHO_START;
  676. SERIAL_ECHOPGM("Enqueing to the front: \"");
  677. SERIAL_ECHO(cmdbuffer + bufindr + 1);
  678. SERIAL_ECHOLNPGM("\"");
  679. #ifdef CMDBUFFER_DEBUG
  680. cmdqueue_dump_to_serial();
  681. #endif /* CMDBUFFER_DEBUG */
  682. } else {
  683. SERIAL_ECHO_START;
  684. SERIAL_ECHOPGM("Enqueing to the front: \"");
  685. if (from_progmem)
  686. SERIAL_PROTOCOLRPGM(cmd);
  687. else
  688. SERIAL_ECHO(cmd);
  689. SERIAL_ECHOLNPGM("\" failed: Buffer full!");
  690. #ifdef CMDBUFFER_DEBUG
  691. cmdqueue_dump_to_serial();
  692. #endif /* CMDBUFFER_DEBUG */
  693. }
  694. }
  695. // Mark the command at the top of the command queue as new.
  696. // Therefore it will not be removed from the queue.
  697. void repeatcommand_front()
  698. {
  699. cmdbuffer_front_already_processed = true;
  700. }
  701. void setup_killpin()
  702. {
  703. #if defined(KILL_PIN) && KILL_PIN > -1
  704. SET_INPUT(KILL_PIN);
  705. WRITE(KILL_PIN,HIGH);
  706. #endif
  707. }
  708. // Set home pin
  709. void setup_homepin(void)
  710. {
  711. #if defined(HOME_PIN) && HOME_PIN > -1
  712. SET_INPUT(HOME_PIN);
  713. WRITE(HOME_PIN,HIGH);
  714. #endif
  715. }
  716. void setup_photpin()
  717. {
  718. #if defined(PHOTOGRAPH_PIN) && PHOTOGRAPH_PIN > -1
  719. SET_OUTPUT(PHOTOGRAPH_PIN);
  720. WRITE(PHOTOGRAPH_PIN, LOW);
  721. #endif
  722. }
  723. void setup_powerhold()
  724. {
  725. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  726. SET_OUTPUT(SUICIDE_PIN);
  727. WRITE(SUICIDE_PIN, HIGH);
  728. #endif
  729. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  730. SET_OUTPUT(PS_ON_PIN);
  731. #if defined(PS_DEFAULT_OFF)
  732. WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  733. #else
  734. WRITE(PS_ON_PIN, PS_ON_AWAKE);
  735. #endif
  736. #endif
  737. }
  738. void suicide()
  739. {
  740. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  741. SET_OUTPUT(SUICIDE_PIN);
  742. WRITE(SUICIDE_PIN, LOW);
  743. #endif
  744. }
  745. void servo_init()
  746. {
  747. #if (NUM_SERVOS >= 1) && defined(SERVO0_PIN) && (SERVO0_PIN > -1)
  748. servos[0].attach(SERVO0_PIN);
  749. #endif
  750. #if (NUM_SERVOS >= 2) && defined(SERVO1_PIN) && (SERVO1_PIN > -1)
  751. servos[1].attach(SERVO1_PIN);
  752. #endif
  753. #if (NUM_SERVOS >= 3) && defined(SERVO2_PIN) && (SERVO2_PIN > -1)
  754. servos[2].attach(SERVO2_PIN);
  755. #endif
  756. #if (NUM_SERVOS >= 4) && defined(SERVO3_PIN) && (SERVO3_PIN > -1)
  757. servos[3].attach(SERVO3_PIN);
  758. #endif
  759. #if (NUM_SERVOS >= 5)
  760. #error "TODO: enter initalisation code for more servos"
  761. #endif
  762. }
  763. static void lcd_language_menu();
  764. #ifdef MESH_BED_LEVELING
  765. enum MeshLevelingState { MeshReport, MeshStart, MeshNext, MeshSet };
  766. #endif
  767. // "Setup" function is called by the Arduino framework on startup.
  768. // Before startup, the Timers-functions (PWM)/Analog RW and HardwareSerial provided by the Arduino-code
  769. // are initialized by the main() routine provided by the Arduino framework.
  770. void setup()
  771. {
  772. setup_killpin();
  773. setup_powerhold();
  774. MYSERIAL.begin(BAUDRATE);
  775. SERIAL_PROTOCOLLNPGM("start");
  776. SERIAL_ECHO_START;
  777. #if 0
  778. SERIAL_ECHOLN("Reading eeprom from 0 to 100: start");
  779. for (int i = 0; i < 4096; ++ i) {
  780. int b = eeprom_read_byte((unsigned char*)i);
  781. if (b != 255) {
  782. SERIAL_ECHO(i);
  783. SERIAL_ECHO(":");
  784. SERIAL_ECHO(b);
  785. SERIAL_ECHOLN("");
  786. }
  787. }
  788. SERIAL_ECHOLN("Reading eeprom from 0 to 100: done");
  789. #endif
  790. // Check startup - does nothing if bootloader sets MCUSR to 0
  791. byte mcu = MCUSR;
  792. if(mcu & 1) SERIAL_ECHOLNRPGM(MSG_POWERUP);
  793. if(mcu & 2) SERIAL_ECHOLNRPGM(MSG_EXTERNAL_RESET);
  794. if(mcu & 4) SERIAL_ECHOLNRPGM(MSG_BROWNOUT_RESET);
  795. if(mcu & 8) SERIAL_ECHOLNRPGM(MSG_WATCHDOG_RESET);
  796. if(mcu & 32) SERIAL_ECHOLNRPGM(MSG_SOFTWARE_RESET);
  797. MCUSR=0;
  798. //SERIAL_ECHORPGM(MSG_MARLIN);
  799. //SERIAL_ECHOLNRPGM(VERSION_STRING);
  800. #ifdef STRING_VERSION_CONFIG_H
  801. #ifdef STRING_CONFIG_H_AUTHOR
  802. SERIAL_ECHO_START;
  803. SERIAL_ECHORPGM(MSG_CONFIGURATION_VER);
  804. SERIAL_ECHOPGM(STRING_VERSION_CONFIG_H);
  805. SERIAL_ECHORPGM(MSG_AUTHOR);
  806. SERIAL_ECHOLNPGM(STRING_CONFIG_H_AUTHOR);
  807. SERIAL_ECHOPGM("Compiled: ");
  808. SERIAL_ECHOLNPGM(__DATE__);
  809. #endif
  810. #endif
  811. SERIAL_ECHO_START;
  812. SERIAL_ECHORPGM(MSG_FREE_MEMORY);
  813. SERIAL_ECHO(freeMemory());
  814. SERIAL_ECHORPGM(MSG_PLANNER_BUFFER_BYTES);
  815. SERIAL_ECHOLN((int)sizeof(block_t)*BLOCK_BUFFER_SIZE);
  816. // loads data from EEPROM if available else uses defaults (and resets step acceleration rate)
  817. Config_RetrieveSettings();
  818. tp_init(); // Initialize temperature loop
  819. plan_init(); // Initialize planner;
  820. watchdog_init();
  821. st_init(); // Initialize stepper, this enables interrupts!
  822. setup_photpin();
  823. servo_init();
  824. // Reset the machine correction matrix.
  825. // It does not make sense to load the correction matrix until the machine is homed.
  826. world2machine_reset();
  827. lcd_init();
  828. if(!READ(BTN_ENC) ){
  829. _delay_ms(1000);
  830. if(!READ(BTN_ENC) ){
  831. SET_OUTPUT(BEEPER);
  832. WRITE(BEEPER,HIGH);
  833. lcd_force_language_selection();
  834. while(!READ(BTN_ENC));
  835. WRITE(BEEPER,LOW);
  836. }
  837. }else{
  838. _delay_ms(1000); // wait 1sec to display the splash screen
  839. }
  840. #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1
  841. SET_OUTPUT(CONTROLLERFAN_PIN); //Set pin used for driver cooling fan
  842. #endif
  843. #ifdef DIGIPOT_I2C
  844. digipot_i2c_init();
  845. #endif
  846. setup_homepin();
  847. #if defined(Z_AXIS_ALWAYS_ON)
  848. enable_z();
  849. #endif
  850. }
  851. // The loop() function is called in an endless loop by the Arduino framework from the default main() routine.
  852. // Before loop(), the setup() function is called by the main() routine.
  853. void loop()
  854. {
  855. if (usb_printing_counter > 0 && millis()-_usb_timer > 1000)
  856. {
  857. is_usb_printing = true;
  858. usb_printing_counter--;
  859. _usb_timer = millis();
  860. }
  861. if (usb_printing_counter == 0)
  862. {
  863. is_usb_printing = false;
  864. }
  865. get_command();
  866. #ifdef SDSUPPORT
  867. card.checkautostart(false);
  868. #endif
  869. if(buflen)
  870. {
  871. #ifdef SDSUPPORT
  872. if(card.saving)
  873. {
  874. // Saving a G-code file onto an SD-card is in progress.
  875. // Saving starts with M28, saving until M29 is seen.
  876. if(strstr_P(CMDBUFFER_CURRENT_STRING, PSTR("M29")) == NULL) {
  877. card.write_command(CMDBUFFER_CURRENT_STRING);
  878. if(card.logging)
  879. process_commands();
  880. else
  881. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  882. } else {
  883. card.closefile();
  884. SERIAL_PROTOCOLLNRPGM(MSG_FILE_SAVED);
  885. }
  886. } else {
  887. process_commands();
  888. }
  889. #else
  890. process_commands();
  891. #endif //SDSUPPORT
  892. if (! cmdbuffer_front_already_processed)
  893. cmdqueue_pop_front();
  894. cmdbuffer_front_already_processed = false;
  895. }
  896. //check heater every n milliseconds
  897. manage_heater();
  898. manage_inactivity();
  899. checkHitEndstops();
  900. lcd_update();
  901. }
  902. void get_command()
  903. {
  904. // Test and reserve space for the new command string.
  905. if (! cmdqueue_could_enqueue_back(MAX_CMD_SIZE-1))
  906. return;
  907. while (MYSERIAL.available() > 0) {
  908. char serial_char = MYSERIAL.read();
  909. if(serial_char == '\n' ||
  910. serial_char == '\r' ||
  911. (serial_char == ':' && comment_mode == false) ||
  912. serial_count >= (MAX_CMD_SIZE - 1) )
  913. {
  914. if(!serial_count) { //if empty line
  915. comment_mode = false; //for new command
  916. return;
  917. }
  918. cmdbuffer[bufindw+serial_count+1] = 0; //terminate string
  919. if(!comment_mode){
  920. comment_mode = false; //for new command
  921. if ((strchr_pointer = strchr(cmdbuffer+bufindw+1, 'N')) != NULL)
  922. {
  923. // Line number met. When sending a G-code over a serial line, each line may be stamped with its index,
  924. // and Marlin tests, whether the successive lines are stamped with an increasing line number ID.
  925. gcode_N = (strtol(strchr_pointer+1, NULL, 10));
  926. if(gcode_N != gcode_LastN+1 && (strstr_P(cmdbuffer+bufindw+1, PSTR("M110")) == NULL) ) {
  927. // M110 - set current line number.
  928. // Line numbers not sent in succession.
  929. SERIAL_ERROR_START;
  930. SERIAL_ERRORRPGM(MSG_ERR_LINE_NO);
  931. SERIAL_ERRORLN(gcode_LastN);
  932. //Serial.println(gcode_N);
  933. FlushSerialRequestResend();
  934. serial_count = 0;
  935. return;
  936. }
  937. if((strchr_pointer = strchr(cmdbuffer+bufindw+1, '*')) != NULL)
  938. {
  939. byte checksum = 0;
  940. char *p = cmdbuffer+bufindw+1;
  941. while (p != strchr_pointer)
  942. checksum = checksum^(*p++);
  943. if (int(strtol(strchr_pointer+1, NULL, 10)) != int(checksum)) {
  944. SERIAL_ERROR_START;
  945. SERIAL_ERRORRPGM(MSG_ERR_CHECKSUM_MISMATCH);
  946. SERIAL_ERRORLN(gcode_LastN);
  947. FlushSerialRequestResend();
  948. serial_count = 0;
  949. return;
  950. }
  951. // If no errors, remove the checksum and continue parsing.
  952. *strchr_pointer = 0;
  953. }
  954. else
  955. {
  956. SERIAL_ERROR_START;
  957. SERIAL_ERRORRPGM(MSG_ERR_NO_CHECKSUM);
  958. SERIAL_ERRORLN(gcode_LastN);
  959. FlushSerialRequestResend();
  960. serial_count = 0;
  961. return;
  962. }
  963. gcode_LastN = gcode_N;
  964. //if no errors, continue parsing
  965. } // end of 'N' command
  966. else // if we don't receive 'N' but still see '*'
  967. {
  968. if((strchr(cmdbuffer+bufindw+1, '*') != NULL))
  969. {
  970. SERIAL_ERROR_START;
  971. SERIAL_ERRORRPGM(MSG_ERR_NO_LINENUMBER_WITH_CHECKSUM);
  972. SERIAL_ERRORLN(gcode_LastN);
  973. serial_count = 0;
  974. return;
  975. }
  976. } // end of '*' command
  977. if ((strchr_pointer = strchr(cmdbuffer+bufindw+1, 'G')) != NULL) {
  978. if (! IS_SD_PRINTING) {
  979. usb_printing_counter = 10;
  980. is_usb_printing = true;
  981. }
  982. if (Stopped == true) {
  983. int gcode = strtol(strchr_pointer+1, NULL, 10);
  984. if (gcode >= 0 && gcode <= 3) {
  985. SERIAL_ERRORLNRPGM(MSG_ERR_STOPPED);
  986. LCD_MESSAGERPGM(MSG_STOPPED);
  987. }
  988. }
  989. } // end of 'G' command
  990. //If command was e-stop process now
  991. if(strcmp(cmdbuffer+bufindw+1, "M112") == 0)
  992. kill();
  993. // Store the current line into buffer, move to the next line.
  994. cmdbuffer[bufindw] = CMDBUFFER_CURRENT_TYPE_USB;
  995. #ifdef CMDBUFFER_DEBUG
  996. SERIAL_ECHO_START;
  997. SERIAL_ECHOPGM("Storing a command line to buffer: ");
  998. SERIAL_ECHO(cmdbuffer+bufindw+1);
  999. SERIAL_ECHOLNPGM("");
  1000. #endif /* CMDBUFFER_DEBUG */
  1001. bufindw += strlen(cmdbuffer+bufindw+1) + 2;
  1002. if (bufindw == sizeof(cmdbuffer))
  1003. bufindw = 0;
  1004. ++ buflen;
  1005. #ifdef CMDBUFFER_DEBUG
  1006. SERIAL_ECHOPGM("Number of commands in the buffer: ");
  1007. SERIAL_ECHO(buflen);
  1008. SERIAL_ECHOLNPGM("");
  1009. #endif /* CMDBUFFER_DEBUG */
  1010. } // end of 'not comment mode'
  1011. serial_count = 0; //clear buffer
  1012. // Don't call cmdqueue_could_enqueue_back if there are no characters waiting
  1013. // in the queue, as this function will reserve the memory.
  1014. if (MYSERIAL.available() == 0 || ! cmdqueue_could_enqueue_back(MAX_CMD_SIZE-1))
  1015. return;
  1016. } // end of "end of line" processing
  1017. else {
  1018. // Not an "end of line" symbol. Store the new character into a buffer.
  1019. if(serial_char == ';') comment_mode = true;
  1020. if(!comment_mode) cmdbuffer[bufindw+1+serial_count++] = serial_char;
  1021. }
  1022. } // end of serial line processing loop
  1023. #ifdef SDSUPPORT
  1024. if(!card.sdprinting || serial_count!=0){
  1025. // If there is a half filled buffer from serial line, wait until return before
  1026. // continuing with the serial line.
  1027. return;
  1028. }
  1029. //'#' stops reading from SD to the buffer prematurely, so procedural macro calls are possible
  1030. // if it occurs, stop_buffering is triggered and the buffer is ran dry.
  1031. // this character _can_ occur in serial com, due to checksums. however, no checksums are used in SD printing
  1032. static bool stop_buffering=false;
  1033. if(buflen==0) stop_buffering=false;
  1034. // Reads whole lines from the SD card. Never leaves a half-filled line in the cmdbuffer.
  1035. while( !card.eof() && !stop_buffering) {
  1036. int16_t n=card.get();
  1037. char serial_char = (char)n;
  1038. if(serial_char == '\n' ||
  1039. serial_char == '\r' ||
  1040. (serial_char == '#' && comment_mode == false) ||
  1041. (serial_char == ':' && comment_mode == false) ||
  1042. serial_count >= (MAX_CMD_SIZE - 1)||n==-1)
  1043. {
  1044. if(card.eof()){
  1045. SERIAL_PROTOCOLLNRPGM(MSG_FILE_PRINTED);
  1046. stoptime=millis();
  1047. char time[30];
  1048. unsigned long t=(stoptime-starttime)/1000;
  1049. int hours, minutes;
  1050. minutes=(t/60)%60;
  1051. hours=t/60/60;
  1052. save_statistics(total_filament_used, t);
  1053. sprintf_P(time, PSTR("%i hours %i minutes"),hours, minutes);
  1054. SERIAL_ECHO_START;
  1055. SERIAL_ECHOLN(time);
  1056. lcd_setstatus(time);
  1057. card.printingHasFinished();
  1058. card.checkautostart(true);
  1059. }
  1060. if(serial_char=='#')
  1061. stop_buffering=true;
  1062. if(!serial_count)
  1063. {
  1064. comment_mode = false; //for new command
  1065. return; //if empty line
  1066. }
  1067. cmdbuffer[bufindw+serial_count+1] = 0; //terminate string
  1068. cmdbuffer[bufindw] = CMDBUFFER_CURRENT_TYPE_SDCARD;
  1069. ++ buflen;
  1070. bufindw += strlen(cmdbuffer+bufindw+1) + 2;
  1071. if (bufindw == sizeof(cmdbuffer))
  1072. bufindw = 0;
  1073. comment_mode = false; //for new command
  1074. serial_count = 0; //clear buffer
  1075. // The following line will reserve buffer space if available.
  1076. if (! cmdqueue_could_enqueue_back(MAX_CMD_SIZE-1))
  1077. return;
  1078. }
  1079. else
  1080. {
  1081. if(serial_char == ';') comment_mode = true;
  1082. if(!comment_mode) cmdbuffer[bufindw+1+serial_count++] = serial_char;
  1083. }
  1084. }
  1085. #endif //SDSUPPORT
  1086. }
  1087. // Return True if a character was found
  1088. static inline bool code_seen(char code) { return (strchr_pointer = strchr(CMDBUFFER_CURRENT_STRING, code)) != NULL; }
  1089. static inline float code_value() { return strtod(strchr_pointer+1, NULL); }
  1090. static inline long code_value_long() { return strtol(strchr_pointer+1, NULL, 10); }
  1091. static inline int16_t code_value_short() { return int16_t(strtol(strchr_pointer+1, NULL, 10)); };
  1092. #define DEFINE_PGM_READ_ANY(type, reader) \
  1093. static inline type pgm_read_any(const type *p) \
  1094. { return pgm_read_##reader##_near(p); }
  1095. DEFINE_PGM_READ_ANY(float, float);
  1096. DEFINE_PGM_READ_ANY(signed char, byte);
  1097. #define XYZ_CONSTS_FROM_CONFIG(type, array, CONFIG) \
  1098. static const PROGMEM type array##_P[3] = \
  1099. { X_##CONFIG, Y_##CONFIG, Z_##CONFIG }; \
  1100. static inline type array(int axis) \
  1101. { return pgm_read_any(&array##_P[axis]); } \
  1102. type array##_ext(int axis) \
  1103. { return pgm_read_any(&array##_P[axis]); }
  1104. XYZ_CONSTS_FROM_CONFIG(float, base_min_pos, MIN_POS);
  1105. XYZ_CONSTS_FROM_CONFIG(float, base_max_pos, MAX_POS);
  1106. XYZ_CONSTS_FROM_CONFIG(float, base_home_pos, HOME_POS);
  1107. XYZ_CONSTS_FROM_CONFIG(float, max_length, MAX_LENGTH);
  1108. XYZ_CONSTS_FROM_CONFIG(float, home_retract_mm, HOME_RETRACT_MM);
  1109. XYZ_CONSTS_FROM_CONFIG(signed char, home_dir, HOME_DIR);
  1110. #ifdef DUAL_X_CARRIAGE
  1111. #if EXTRUDERS == 1 || defined(COREXY) \
  1112. || !defined(X2_ENABLE_PIN) || !defined(X2_STEP_PIN) || !defined(X2_DIR_PIN) \
  1113. || !defined(X2_HOME_POS) || !defined(X2_MIN_POS) || !defined(X2_MAX_POS) \
  1114. || !defined(X_MAX_PIN) || X_MAX_PIN < 0
  1115. #error "Missing or invalid definitions for DUAL_X_CARRIAGE mode."
  1116. #endif
  1117. #if X_HOME_DIR != -1 || X2_HOME_DIR != 1
  1118. #error "Please use canonical x-carriage assignment" // the x-carriages are defined by their homing directions
  1119. #endif
  1120. #define DXC_FULL_CONTROL_MODE 0
  1121. #define DXC_AUTO_PARK_MODE 1
  1122. #define DXC_DUPLICATION_MODE 2
  1123. static int dual_x_carriage_mode = DEFAULT_DUAL_X_CARRIAGE_MODE;
  1124. static float x_home_pos(int extruder) {
  1125. if (extruder == 0)
  1126. return base_home_pos(X_AXIS) + add_homing[X_AXIS];
  1127. else
  1128. // In dual carriage mode the extruder offset provides an override of the
  1129. // second X-carriage offset when homed - otherwise X2_HOME_POS is used.
  1130. // This allow soft recalibration of the second extruder offset position without firmware reflash
  1131. // (through the M218 command).
  1132. return (extruder_offset[X_AXIS][1] > 0) ? extruder_offset[X_AXIS][1] : X2_HOME_POS;
  1133. }
  1134. static int x_home_dir(int extruder) {
  1135. return (extruder == 0) ? X_HOME_DIR : X2_HOME_DIR;
  1136. }
  1137. static float inactive_extruder_x_pos = X2_MAX_POS; // used in mode 0 & 1
  1138. static bool active_extruder_parked = false; // used in mode 1 & 2
  1139. static float raised_parked_position[NUM_AXIS]; // used in mode 1
  1140. static unsigned long delayed_move_time = 0; // used in mode 1
  1141. static float duplicate_extruder_x_offset = DEFAULT_DUPLICATION_X_OFFSET; // used in mode 2
  1142. static float duplicate_extruder_temp_offset = 0; // used in mode 2
  1143. bool extruder_duplication_enabled = false; // used in mode 2
  1144. #endif //DUAL_X_CARRIAGE
  1145. static void axis_is_at_home(int axis) {
  1146. #ifdef DUAL_X_CARRIAGE
  1147. if (axis == X_AXIS) {
  1148. if (active_extruder != 0) {
  1149. current_position[X_AXIS] = x_home_pos(active_extruder);
  1150. min_pos[X_AXIS] = X2_MIN_POS;
  1151. max_pos[X_AXIS] = max(extruder_offset[X_AXIS][1], X2_MAX_POS);
  1152. return;
  1153. }
  1154. else if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && active_extruder == 0) {
  1155. current_position[X_AXIS] = base_home_pos(X_AXIS) + add_homing[X_AXIS];
  1156. min_pos[X_AXIS] = base_min_pos(X_AXIS) + add_homing[X_AXIS];
  1157. max_pos[X_AXIS] = min(base_max_pos(X_AXIS) + add_homing[X_AXIS],
  1158. max(extruder_offset[X_AXIS][1], X2_MAX_POS) - duplicate_extruder_x_offset);
  1159. return;
  1160. }
  1161. }
  1162. #endif
  1163. current_position[axis] = base_home_pos(axis) + add_homing[axis];
  1164. min_pos[axis] = base_min_pos(axis) + add_homing[axis];
  1165. max_pos[axis] = base_max_pos(axis) + add_homing[axis];
  1166. }
  1167. inline void set_current_to_destination() { memcpy(current_position, destination, sizeof(current_position)); }
  1168. inline void set_destination_to_current() { memcpy(destination, current_position, sizeof(destination)); }
  1169. static void setup_for_endstop_move() {
  1170. saved_feedrate = feedrate;
  1171. saved_feedmultiply = feedmultiply;
  1172. feedmultiply = 100;
  1173. previous_millis_cmd = millis();
  1174. enable_endstops(true);
  1175. }
  1176. static void clean_up_after_endstop_move() {
  1177. #ifdef ENDSTOPS_ONLY_FOR_HOMING
  1178. enable_endstops(false);
  1179. #endif
  1180. feedrate = saved_feedrate;
  1181. feedmultiply = saved_feedmultiply;
  1182. previous_millis_cmd = millis();
  1183. }
  1184. #ifdef ENABLE_AUTO_BED_LEVELING
  1185. #ifdef AUTO_BED_LEVELING_GRID
  1186. static void set_bed_level_equation_lsq(double *plane_equation_coefficients)
  1187. {
  1188. vector_3 planeNormal = vector_3(-plane_equation_coefficients[0], -plane_equation_coefficients[1], 1);
  1189. planeNormal.debug("planeNormal");
  1190. plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1191. //bedLevel.debug("bedLevel");
  1192. //plan_bed_level_matrix.debug("bed level before");
  1193. //vector_3 uncorrected_position = plan_get_position_mm();
  1194. //uncorrected_position.debug("position before");
  1195. vector_3 corrected_position = plan_get_position();
  1196. // corrected_position.debug("position after");
  1197. current_position[X_AXIS] = corrected_position.x;
  1198. current_position[Y_AXIS] = corrected_position.y;
  1199. current_position[Z_AXIS] = corrected_position.z;
  1200. // put the bed at 0 so we don't go below it.
  1201. current_position[Z_AXIS] = zprobe_zoffset; // in the lsq we reach here after raising the extruder due to the loop structure
  1202. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1203. }
  1204. #else // not AUTO_BED_LEVELING_GRID
  1205. static void set_bed_level_equation_3pts(float z_at_pt_1, float z_at_pt_2, float z_at_pt_3) {
  1206. plan_bed_level_matrix.set_to_identity();
  1207. vector_3 pt1 = vector_3(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, z_at_pt_1);
  1208. vector_3 pt2 = vector_3(ABL_PROBE_PT_2_X, ABL_PROBE_PT_2_Y, z_at_pt_2);
  1209. vector_3 pt3 = vector_3(ABL_PROBE_PT_3_X, ABL_PROBE_PT_3_Y, z_at_pt_3);
  1210. vector_3 from_2_to_1 = (pt1 - pt2).get_normal();
  1211. vector_3 from_2_to_3 = (pt3 - pt2).get_normal();
  1212. vector_3 planeNormal = vector_3::cross(from_2_to_1, from_2_to_3).get_normal();
  1213. planeNormal = vector_3(planeNormal.x, planeNormal.y, abs(planeNormal.z));
  1214. plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1215. vector_3 corrected_position = plan_get_position();
  1216. current_position[X_AXIS] = corrected_position.x;
  1217. current_position[Y_AXIS] = corrected_position.y;
  1218. current_position[Z_AXIS] = corrected_position.z;
  1219. // put the bed at 0 so we don't go below it.
  1220. current_position[Z_AXIS] = zprobe_zoffset;
  1221. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1222. }
  1223. #endif // AUTO_BED_LEVELING_GRID
  1224. static void run_z_probe() {
  1225. plan_bed_level_matrix.set_to_identity();
  1226. feedrate = homing_feedrate[Z_AXIS];
  1227. // move down until you find the bed
  1228. float zPosition = -10;
  1229. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1230. st_synchronize();
  1231. // we have to let the planner know where we are right now as it is not where we said to go.
  1232. zPosition = st_get_position_mm(Z_AXIS);
  1233. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS]);
  1234. // move up the retract distance
  1235. zPosition += home_retract_mm(Z_AXIS);
  1236. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1237. st_synchronize();
  1238. // move back down slowly to find bed
  1239. feedrate = homing_feedrate[Z_AXIS]/4;
  1240. zPosition -= home_retract_mm(Z_AXIS) * 2;
  1241. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1242. st_synchronize();
  1243. current_position[Z_AXIS] = st_get_position_mm(Z_AXIS);
  1244. // make sure the planner knows where we are as it may be a bit different than we last said to move to
  1245. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1246. }
  1247. static void do_blocking_move_to(float x, float y, float z) {
  1248. float oldFeedRate = feedrate;
  1249. feedrate = homing_feedrate[Z_AXIS];
  1250. current_position[Z_AXIS] = z;
  1251. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], feedrate/60, active_extruder);
  1252. st_synchronize();
  1253. feedrate = XY_TRAVEL_SPEED;
  1254. current_position[X_AXIS] = x;
  1255. current_position[Y_AXIS] = y;
  1256. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], feedrate/60, active_extruder);
  1257. st_synchronize();
  1258. feedrate = oldFeedRate;
  1259. }
  1260. static void do_blocking_move_relative(float offset_x, float offset_y, float offset_z) {
  1261. do_blocking_move_to(current_position[X_AXIS] + offset_x, current_position[Y_AXIS] + offset_y, current_position[Z_AXIS] + offset_z);
  1262. }
  1263. /// Probe bed height at position (x,y), returns the measured z value
  1264. static float probe_pt(float x, float y, float z_before) {
  1265. // move to right place
  1266. do_blocking_move_to(current_position[X_AXIS], current_position[Y_AXIS], z_before);
  1267. do_blocking_move_to(x - X_PROBE_OFFSET_FROM_EXTRUDER, y - Y_PROBE_OFFSET_FROM_EXTRUDER, current_position[Z_AXIS]);
  1268. run_z_probe();
  1269. float measured_z = current_position[Z_AXIS];
  1270. SERIAL_PROTOCOLRPGM(MSG_BED);
  1271. SERIAL_PROTOCOLPGM(" x: ");
  1272. SERIAL_PROTOCOL(x);
  1273. SERIAL_PROTOCOLPGM(" y: ");
  1274. SERIAL_PROTOCOL(y);
  1275. SERIAL_PROTOCOLPGM(" z: ");
  1276. SERIAL_PROTOCOL(measured_z);
  1277. SERIAL_PROTOCOLPGM("\n");
  1278. return measured_z;
  1279. }
  1280. #endif // #ifdef ENABLE_AUTO_BED_LEVELING
  1281. static void homeaxis(int axis) {
  1282. #define HOMEAXIS_DO(LETTER) \
  1283. ((LETTER##_MIN_PIN > -1 && LETTER##_HOME_DIR==-1) || (LETTER##_MAX_PIN > -1 && LETTER##_HOME_DIR==1))
  1284. if (axis==X_AXIS ? HOMEAXIS_DO(X) :
  1285. axis==Y_AXIS ? HOMEAXIS_DO(Y) :
  1286. axis==Z_AXIS ? HOMEAXIS_DO(Z) :
  1287. 0) {
  1288. int axis_home_dir = home_dir(axis);
  1289. #ifdef DUAL_X_CARRIAGE
  1290. if (axis == X_AXIS)
  1291. axis_home_dir = x_home_dir(active_extruder);
  1292. #endif
  1293. current_position[axis] = 0;
  1294. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1295. destination[axis] = 1.5 * max_length(axis) * axis_home_dir;
  1296. feedrate = homing_feedrate[axis];
  1297. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1298. st_synchronize();
  1299. current_position[axis] = 0;
  1300. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1301. destination[axis] = -home_retract_mm(axis) * axis_home_dir;
  1302. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1303. st_synchronize();
  1304. destination[axis] = 2*home_retract_mm(axis) * axis_home_dir;
  1305. feedrate = homing_feedrate[axis]/2 ;
  1306. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1307. st_synchronize();
  1308. axis_is_at_home(axis);
  1309. destination[axis] = current_position[axis];
  1310. feedrate = 0.0;
  1311. endstops_hit_on_purpose();
  1312. axis_known_position[axis] = true;
  1313. }
  1314. }
  1315. void home_xy()
  1316. {
  1317. set_destination_to_current();
  1318. homeaxis(X_AXIS);
  1319. homeaxis(Y_AXIS);
  1320. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1321. endstops_hit_on_purpose();
  1322. }
  1323. void refresh_cmd_timeout(void)
  1324. {
  1325. previous_millis_cmd = millis();
  1326. }
  1327. #ifdef FWRETRACT
  1328. void retract(bool retracting, bool swapretract = false) {
  1329. if(retracting && !retracted[active_extruder]) {
  1330. destination[X_AXIS]=current_position[X_AXIS];
  1331. destination[Y_AXIS]=current_position[Y_AXIS];
  1332. destination[Z_AXIS]=current_position[Z_AXIS];
  1333. destination[E_AXIS]=current_position[E_AXIS];
  1334. if (swapretract) {
  1335. current_position[E_AXIS]+=retract_length_swap/volumetric_multiplier[active_extruder];
  1336. } else {
  1337. current_position[E_AXIS]+=retract_length/volumetric_multiplier[active_extruder];
  1338. }
  1339. plan_set_e_position(current_position[E_AXIS]);
  1340. float oldFeedrate = feedrate;
  1341. feedrate=retract_feedrate*60;
  1342. retracted[active_extruder]=true;
  1343. prepare_move();
  1344. current_position[Z_AXIS]-=retract_zlift;
  1345. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1346. prepare_move();
  1347. feedrate = oldFeedrate;
  1348. } else if(!retracting && retracted[active_extruder]) {
  1349. destination[X_AXIS]=current_position[X_AXIS];
  1350. destination[Y_AXIS]=current_position[Y_AXIS];
  1351. destination[Z_AXIS]=current_position[Z_AXIS];
  1352. destination[E_AXIS]=current_position[E_AXIS];
  1353. current_position[Z_AXIS]+=retract_zlift;
  1354. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1355. //prepare_move();
  1356. if (swapretract) {
  1357. current_position[E_AXIS]-=(retract_length_swap+retract_recover_length_swap)/volumetric_multiplier[active_extruder];
  1358. } else {
  1359. current_position[E_AXIS]-=(retract_length+retract_recover_length)/volumetric_multiplier[active_extruder];
  1360. }
  1361. plan_set_e_position(current_position[E_AXIS]);
  1362. float oldFeedrate = feedrate;
  1363. feedrate=retract_recover_feedrate*60;
  1364. retracted[active_extruder]=false;
  1365. prepare_move();
  1366. feedrate = oldFeedrate;
  1367. }
  1368. } //retract
  1369. #endif //FWRETRACT
  1370. void process_commands()
  1371. {
  1372. #ifdef FILAMENT_RUNOUT_SUPPORT
  1373. SET_INPUT(FR_SENS);
  1374. #endif
  1375. #ifdef CMDBUFFER_DEBUG
  1376. SERIAL_ECHOPGM("Processing a GCODE command: ");
  1377. SERIAL_ECHO(cmdbuffer+bufindr+1);
  1378. SERIAL_ECHOLNPGM("");
  1379. SERIAL_ECHOPGM("In cmdqueue: ");
  1380. SERIAL_ECHO(buflen);
  1381. SERIAL_ECHOLNPGM("");
  1382. #endif /* CMDBUFFER_DEBUG */
  1383. unsigned long codenum; //throw away variable
  1384. char *starpos = NULL;
  1385. #ifdef ENABLE_AUTO_BED_LEVELING
  1386. float x_tmp, y_tmp, z_tmp, real_z;
  1387. #endif
  1388. // PRUSA GCODES
  1389. /*
  1390. if(code_seen('PRUSA')){
  1391. if(code_seen('Fir')){
  1392. SERIAL_PROTOCOLLN(FW_version);
  1393. } else if(code_seen('Rev')){
  1394. SERIAL_PROTOCOLLN(FILAMENT_SIZE "-" ELECTRONICS "-" NOZZLE_TYPE );
  1395. } else if(code_seen('Lang')) {
  1396. lcd_force_language_selection();
  1397. } else if(code_seen('Lz')) {
  1398. EEPROM_save_B(EEPROM_BABYSTEP_Z,0);
  1399. }
  1400. //else if (code_seen('Cal')) {
  1401. // lcd_calibration();
  1402. // }
  1403. }
  1404. else
  1405. */
  1406. if(code_seen('G'))
  1407. {
  1408. switch((int)code_value())
  1409. {
  1410. case 0: // G0 -> G1
  1411. case 1: // G1
  1412. if(Stopped == false) {
  1413. #ifdef FILAMENT_RUNOUT_SUPPORT
  1414. if(READ(FR_SENS)){
  1415. feedmultiplyBckp=feedmultiply;
  1416. float target[4];
  1417. float lastpos[4];
  1418. target[X_AXIS]=current_position[X_AXIS];
  1419. target[Y_AXIS]=current_position[Y_AXIS];
  1420. target[Z_AXIS]=current_position[Z_AXIS];
  1421. target[E_AXIS]=current_position[E_AXIS];
  1422. lastpos[X_AXIS]=current_position[X_AXIS];
  1423. lastpos[Y_AXIS]=current_position[Y_AXIS];
  1424. lastpos[Z_AXIS]=current_position[Z_AXIS];
  1425. lastpos[E_AXIS]=current_position[E_AXIS];
  1426. //retract by E
  1427. target[E_AXIS]+= FILAMENTCHANGE_FIRSTRETRACT ;
  1428. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 400, active_extruder);
  1429. target[Z_AXIS]+= FILAMENTCHANGE_ZADD ;
  1430. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 300, active_extruder);
  1431. target[X_AXIS]= FILAMENTCHANGE_XPOS ;
  1432. target[Y_AXIS]= FILAMENTCHANGE_YPOS ;
  1433. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 70, active_extruder);
  1434. target[E_AXIS]+= FILAMENTCHANGE_FINALRETRACT ;
  1435. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 20, active_extruder);
  1436. //finish moves
  1437. st_synchronize();
  1438. //disable extruder steppers so filament can be removed
  1439. disable_e0();
  1440. disable_e1();
  1441. disable_e2();
  1442. delay(100);
  1443. //LCD_ALERTMESSAGEPGM(MSG_FILAMENTCHANGE);
  1444. uint8_t cnt=0;
  1445. int counterBeep = 0;
  1446. lcd_wait_interact();
  1447. while(!lcd_clicked()){
  1448. cnt++;
  1449. manage_heater();
  1450. manage_inactivity(true);
  1451. //lcd_update();
  1452. if(cnt==0)
  1453. {
  1454. #if BEEPER > 0
  1455. if (counterBeep== 500){
  1456. counterBeep = 0;
  1457. }
  1458. SET_OUTPUT(BEEPER);
  1459. if (counterBeep== 0){
  1460. WRITE(BEEPER,HIGH);
  1461. }
  1462. if (counterBeep== 20){
  1463. WRITE(BEEPER,LOW);
  1464. }
  1465. counterBeep++;
  1466. #else
  1467. #if !defined(LCD_FEEDBACK_FREQUENCY_HZ) || !defined(LCD_FEEDBACK_FREQUENCY_DURATION_MS)
  1468. lcd_buzz(1000/6,100);
  1469. #else
  1470. lcd_buzz(LCD_FEEDBACK_FREQUENCY_DURATION_MS,LCD_FEEDBACK_FREQUENCY_HZ);
  1471. #endif
  1472. #endif
  1473. }
  1474. }
  1475. WRITE(BEEPER,LOW);
  1476. target[E_AXIS]+= FILAMENTCHANGE_FIRSTFEED ;
  1477. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 20, active_extruder);
  1478. target[E_AXIS]+= FILAMENTCHANGE_FINALFEED ;
  1479. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 2, active_extruder);
  1480. lcd_change_fil_state = 0;
  1481. lcd_loading_filament();
  1482. while ((lcd_change_fil_state == 0)||(lcd_change_fil_state != 1)){
  1483. lcd_change_fil_state = 0;
  1484. lcd_alright();
  1485. switch(lcd_change_fil_state){
  1486. case 2:
  1487. target[E_AXIS]+= FILAMENTCHANGE_FIRSTFEED ;
  1488. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 20, active_extruder);
  1489. target[E_AXIS]+= FILAMENTCHANGE_FINALFEED ;
  1490. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 2, active_extruder);
  1491. lcd_loading_filament();
  1492. break;
  1493. case 3:
  1494. target[E_AXIS]+= FILAMENTCHANGE_FINALFEED ;
  1495. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 2, active_extruder);
  1496. lcd_loading_color();
  1497. break;
  1498. default:
  1499. lcd_change_success();
  1500. break;
  1501. }
  1502. }
  1503. target[E_AXIS]+= 5;
  1504. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 2, active_extruder);
  1505. target[E_AXIS]+= FILAMENTCHANGE_FIRSTRETRACT;
  1506. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 400, active_extruder);
  1507. //current_position[E_AXIS]=target[E_AXIS]; //the long retract of L is compensated by manual filament feeding
  1508. //plan_set_e_position(current_position[E_AXIS]);
  1509. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 70, active_extruder); //should do nothing
  1510. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], target[Z_AXIS], target[E_AXIS], 70, active_extruder); //move xy back
  1511. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], lastpos[Z_AXIS], target[E_AXIS], 200, active_extruder); //move z back
  1512. target[E_AXIS]= target[E_AXIS] - FILAMENTCHANGE_FIRSTRETRACT;
  1513. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], lastpos[Z_AXIS], target[E_AXIS], 5, active_extruder); //final untretract
  1514. plan_set_e_position(lastpos[E_AXIS]);
  1515. feedmultiply=feedmultiplyBckp;
  1516. char cmd[9];
  1517. sprintf_P(cmd, PSTR("M220 S%i"), feedmultiplyBckp);
  1518. enquecommand(cmd);
  1519. }
  1520. #endif
  1521. get_coordinates(); // For X Y Z E F
  1522. total_filament_used = total_filament_used + ((destination[E_AXIS] - current_position[E_AXIS])*100);
  1523. #ifdef FWRETRACT
  1524. if(autoretract_enabled)
  1525. if( !(code_seen('X') || code_seen('Y') || code_seen('Z')) && code_seen('E')) {
  1526. float echange=destination[E_AXIS]-current_position[E_AXIS];
  1527. if((echange<-MIN_RETRACT && !retracted) || (echange>MIN_RETRACT && retracted)) { //move appears to be an attempt to retract or recover
  1528. current_position[E_AXIS] = destination[E_AXIS]; //hide the slicer-generated retract/recover from calculations
  1529. plan_set_e_position(current_position[E_AXIS]); //AND from the planner
  1530. retract(!retracted);
  1531. return;
  1532. }
  1533. }
  1534. #endif //FWRETRACT
  1535. prepare_move();
  1536. //ClearToSend();
  1537. }
  1538. break;
  1539. case 2: // G2 - CW ARC
  1540. if(Stopped == false) {
  1541. get_arc_coordinates();
  1542. prepare_arc_move(true);
  1543. }
  1544. break;
  1545. case 3: // G3 - CCW ARC
  1546. if(Stopped == false) {
  1547. get_arc_coordinates();
  1548. prepare_arc_move(false);
  1549. }
  1550. break;
  1551. case 4: // G4 dwell
  1552. LCD_MESSAGERPGM(MSG_DWELL);
  1553. codenum = 0;
  1554. if(code_seen('P')) codenum = code_value(); // milliseconds to wait
  1555. if(code_seen('S')) codenum = code_value() * 1000; // seconds to wait
  1556. st_synchronize();
  1557. codenum += millis(); // keep track of when we started waiting
  1558. previous_millis_cmd = millis();
  1559. while(millis() < codenum) {
  1560. manage_heater();
  1561. manage_inactivity();
  1562. lcd_update();
  1563. }
  1564. break;
  1565. #ifdef FWRETRACT
  1566. case 10: // G10 retract
  1567. #if EXTRUDERS > 1
  1568. retracted_swap[active_extruder]=(code_seen('S') && code_value_long() == 1); // checks for swap retract argument
  1569. retract(true,retracted_swap[active_extruder]);
  1570. #else
  1571. retract(true);
  1572. #endif
  1573. break;
  1574. case 11: // G11 retract_recover
  1575. #if EXTRUDERS > 1
  1576. retract(false,retracted_swap[active_extruder]);
  1577. #else
  1578. retract(false);
  1579. #endif
  1580. break;
  1581. #endif //FWRETRACT
  1582. case 28: //G28 Home all Axis one at a time
  1583. #ifdef ENABLE_AUTO_BED_LEVELING
  1584. plan_bed_level_matrix.set_to_identity(); //Reset the plane ("erase" all leveling data)
  1585. #endif //ENABLE_AUTO_BED_LEVELING
  1586. _doMeshL = false;
  1587. // For mesh bed leveling deactivate the matrix temporarily
  1588. #ifdef MESH_BED_LEVELING
  1589. mbl.active = 0;
  1590. #endif
  1591. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  1592. // the planner will not perform any adjustments in the XY plane.
  1593. world2machine_reset();
  1594. saved_feedrate = feedrate;
  1595. saved_feedmultiply = feedmultiply;
  1596. feedmultiply = 100;
  1597. previous_millis_cmd = millis();
  1598. enable_endstops(true);
  1599. for(int8_t i=0; i < NUM_AXIS; i++) {
  1600. destination[i] = current_position[i];
  1601. }
  1602. feedrate = 0.0;
  1603. home_all_axis = !((code_seen(axis_codes[X_AXIS])) || (code_seen(axis_codes[Y_AXIS])) || (code_seen(axis_codes[Z_AXIS])));
  1604. #if Z_HOME_DIR > 0 // If homing away from BED do Z first
  1605. if((home_all_axis) || (code_seen(axis_codes[Z_AXIS]))) {
  1606. homeaxis(Z_AXIS);
  1607. }
  1608. #endif
  1609. #ifdef QUICK_HOME
  1610. // In the quick mode, if both x and y are to be homed, a diagonal move will be performed initially.
  1611. if((home_all_axis)||( code_seen(axis_codes[X_AXIS]) && code_seen(axis_codes[Y_AXIS])) ) //first diagonal move
  1612. {
  1613. current_position[X_AXIS] = 0;current_position[Y_AXIS] = 0;
  1614. #ifndef DUAL_X_CARRIAGE
  1615. int x_axis_home_dir = home_dir(X_AXIS);
  1616. #else
  1617. int x_axis_home_dir = x_home_dir(active_extruder);
  1618. extruder_duplication_enabled = false;
  1619. #endif
  1620. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1621. 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);
  1622. feedrate = homing_feedrate[X_AXIS];
  1623. if(homing_feedrate[Y_AXIS]<feedrate)
  1624. feedrate = homing_feedrate[Y_AXIS];
  1625. if (max_length(X_AXIS) > max_length(Y_AXIS)) {
  1626. feedrate *= sqrt(pow(max_length(Y_AXIS) / max_length(X_AXIS), 2) + 1);
  1627. } else {
  1628. feedrate *= sqrt(pow(max_length(X_AXIS) / max_length(Y_AXIS), 2) + 1);
  1629. }
  1630. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1631. st_synchronize();
  1632. axis_is_at_home(X_AXIS);
  1633. axis_is_at_home(Y_AXIS);
  1634. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1635. destination[X_AXIS] = current_position[X_AXIS];
  1636. destination[Y_AXIS] = current_position[Y_AXIS];
  1637. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1638. feedrate = 0.0;
  1639. st_synchronize();
  1640. endstops_hit_on_purpose();
  1641. current_position[X_AXIS] = destination[X_AXIS];
  1642. current_position[Y_AXIS] = destination[Y_AXIS];
  1643. current_position[Z_AXIS] = destination[Z_AXIS];
  1644. }
  1645. #endif /* QUICK_HOME */
  1646. if (home_all_axis)
  1647. {
  1648. _doMeshL = true;
  1649. }
  1650. if((home_all_axis) || (code_seen(axis_codes[X_AXIS])))
  1651. {
  1652. #ifdef DUAL_X_CARRIAGE
  1653. int tmp_extruder = active_extruder;
  1654. extruder_duplication_enabled = false;
  1655. active_extruder = !active_extruder;
  1656. homeaxis(X_AXIS);
  1657. inactive_extruder_x_pos = current_position[X_AXIS];
  1658. active_extruder = tmp_extruder;
  1659. homeaxis(X_AXIS);
  1660. // reset state used by the different modes
  1661. memcpy(raised_parked_position, current_position, sizeof(raised_parked_position));
  1662. delayed_move_time = 0;
  1663. active_extruder_parked = true;
  1664. #else
  1665. homeaxis(X_AXIS);
  1666. #endif
  1667. }
  1668. if((home_all_axis) || (code_seen(axis_codes[Y_AXIS]))) {
  1669. homeaxis(Y_AXIS);
  1670. }
  1671. if(code_seen(axis_codes[X_AXIS]))
  1672. {
  1673. if(code_value_long() != 0) {
  1674. current_position[X_AXIS]=code_value()+add_homing[X_AXIS];
  1675. }
  1676. }
  1677. if(code_seen(axis_codes[Y_AXIS])) {
  1678. if(code_value_long() != 0) {
  1679. current_position[Y_AXIS]=code_value()+add_homing[Y_AXIS];
  1680. }
  1681. }
  1682. #if Z_HOME_DIR < 0 // If homing towards BED do Z last
  1683. #ifndef Z_SAFE_HOMING
  1684. if((home_all_axis) || (code_seen(axis_codes[Z_AXIS]))) {
  1685. #if defined (Z_RAISE_BEFORE_HOMING) && (Z_RAISE_BEFORE_HOMING > 0)
  1686. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  1687. feedrate = max_feedrate[Z_AXIS];
  1688. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate, active_extruder);
  1689. st_synchronize();
  1690. #endif // defined (Z_RAISE_BEFORE_HOMING) && (Z_RAISE_BEFORE_HOMING > 0)
  1691. #ifdef MESH_BED_LEVELING // If Mesh bed leveling, moxve X&Y to safe position for home
  1692. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] ))
  1693. {
  1694. homeaxis(X_AXIS);
  1695. homeaxis(Y_AXIS);
  1696. }
  1697. // 1st mesh bed leveling measurement point, corrected.
  1698. world2machine_initialize();
  1699. destination[X_AXIS] = world2machine_rotation_and_skew[0][0] * pgm_read_float(bed_ref_points) + world2machine_rotation_and_skew[0][1] * pgm_read_float(bed_ref_points+1) + world2machine_shift[0];
  1700. destination[Y_AXIS] = world2machine_rotation_and_skew[1][0] * pgm_read_float(bed_ref_points) + world2machine_rotation_and_skew[1][1] * pgm_read_float(bed_ref_points+1) + world2machine_shift[1];
  1701. world2machine_reset();
  1702. destination[Z_AXIS] = MESH_HOME_Z_SEARCH; // Set destination away from bed
  1703. feedrate = homing_feedrate[Z_AXIS]/10;
  1704. current_position[Z_AXIS] = 0;
  1705. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1706. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate, active_extruder);
  1707. st_synchronize();
  1708. current_position[X_AXIS] = destination[X_AXIS];
  1709. current_position[Y_AXIS] = destination[Y_AXIS];
  1710. homeaxis(Z_AXIS);
  1711. _doMeshL = true;
  1712. #else // MESH_BED_LEVELING
  1713. homeaxis(Z_AXIS);
  1714. #endif // MESH_BED_LEVELING
  1715. }
  1716. #else // defined(Z_SAFE_HOMING): Z Safe mode activated.
  1717. if(home_all_axis) {
  1718. destination[X_AXIS] = round(Z_SAFE_HOMING_X_POINT - X_PROBE_OFFSET_FROM_EXTRUDER);
  1719. destination[Y_AXIS] = round(Z_SAFE_HOMING_Y_POINT - Y_PROBE_OFFSET_FROM_EXTRUDER);
  1720. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  1721. feedrate = XY_TRAVEL_SPEED/60;
  1722. current_position[Z_AXIS] = 0;
  1723. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1724. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate, active_extruder);
  1725. st_synchronize();
  1726. current_position[X_AXIS] = destination[X_AXIS];
  1727. current_position[Y_AXIS] = destination[Y_AXIS];
  1728. homeaxis(Z_AXIS);
  1729. }
  1730. // Let's see if X and Y are homed and probe is inside bed area.
  1731. if(code_seen(axis_codes[Z_AXIS])) {
  1732. if ( (axis_known_position[X_AXIS]) && (axis_known_position[Y_AXIS]) \
  1733. && (current_position[X_AXIS]+X_PROBE_OFFSET_FROM_EXTRUDER >= X_MIN_POS) \
  1734. && (current_position[X_AXIS]+X_PROBE_OFFSET_FROM_EXTRUDER <= X_MAX_POS) \
  1735. && (current_position[Y_AXIS]+Y_PROBE_OFFSET_FROM_EXTRUDER >= Y_MIN_POS) \
  1736. && (current_position[Y_AXIS]+Y_PROBE_OFFSET_FROM_EXTRUDER <= Y_MAX_POS)) {
  1737. current_position[Z_AXIS] = 0;
  1738. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1739. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  1740. feedrate = max_feedrate[Z_AXIS];
  1741. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate, active_extruder);
  1742. st_synchronize();
  1743. homeaxis(Z_AXIS);
  1744. } else if (!((axis_known_position[X_AXIS]) && (axis_known_position[Y_AXIS]))) {
  1745. LCD_MESSAGERPGM(MSG_POSITION_UNKNOWN);
  1746. SERIAL_ECHO_START;
  1747. SERIAL_ECHOLNRPGM(MSG_POSITION_UNKNOWN);
  1748. } else {
  1749. LCD_MESSAGERPGM(MSG_ZPROBE_OUT);
  1750. SERIAL_ECHO_START;
  1751. SERIAL_ECHOLNRPGM(MSG_ZPROBE_OUT);
  1752. }
  1753. }
  1754. #endif // Z_SAFE_HOMING
  1755. #endif // Z_HOME_DIR < 0
  1756. if(code_seen(axis_codes[Z_AXIS])) {
  1757. if(code_value_long() != 0) {
  1758. current_position[Z_AXIS]=code_value()+add_homing[Z_AXIS];
  1759. }
  1760. }
  1761. #ifdef ENABLE_AUTO_BED_LEVELING
  1762. if((home_all_axis) || (code_seen(axis_codes[Z_AXIS]))) {
  1763. current_position[Z_AXIS] += zprobe_zoffset; //Add Z_Probe offset (the distance is negative)
  1764. }
  1765. #endif
  1766. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1767. #ifdef ENDSTOPS_ONLY_FOR_HOMING
  1768. enable_endstops(false);
  1769. #endif
  1770. feedrate = saved_feedrate;
  1771. feedmultiply = saved_feedmultiply;
  1772. previous_millis_cmd = millis();
  1773. endstops_hit_on_purpose();
  1774. #ifndef MESH_BED_LEVELING
  1775. if(card.sdprinting) {
  1776. EEPROM_read_B(EEPROM_BABYSTEP_Z,&babystepLoad[2]);
  1777. if(babystepLoad[2] != 0){
  1778. lcd_adjust_z();
  1779. }
  1780. }
  1781. #endif
  1782. // Load the machine correction matrix
  1783. world2machine_initialize();
  1784. // and correct the current_position to match the transformed coordinate system.
  1785. world2machine_update_current();
  1786. #ifdef MESH_BED_LEVELING
  1787. if (code_seen('W'))
  1788. {
  1789. _doMeshL = false;
  1790. SERIAL_ECHOLN("G80 disabled");
  1791. }
  1792. if ( _doMeshL)
  1793. {
  1794. st_synchronize();
  1795. // Push the commands to the front of the message queue in the reverse order!
  1796. // There shall be always enough space reserved for these commands.
  1797. enquecommand_front_P((PSTR("G80")));
  1798. }
  1799. #endif
  1800. break;
  1801. #ifdef ENABLE_AUTO_BED_LEVELING
  1802. case 29: // G29 Detailed Z-Probe, probes the bed at 3 or more points.
  1803. {
  1804. #if Z_MIN_PIN == -1
  1805. #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."
  1806. #endif
  1807. // Prevent user from running a G29 without first homing in X and Y
  1808. if (! (axis_known_position[X_AXIS] && axis_known_position[Y_AXIS]) )
  1809. {
  1810. LCD_MESSAGERPGM(MSG_POSITION_UNKNOWN);
  1811. SERIAL_ECHO_START;
  1812. SERIAL_ECHOLNRPGM(MSG_POSITION_UNKNOWN);
  1813. break; // abort G29, since we don't know where we are
  1814. }
  1815. st_synchronize();
  1816. // make sure the bed_level_rotation_matrix is identity or the planner will get it incorectly
  1817. //vector_3 corrected_position = plan_get_position_mm();
  1818. //corrected_position.debug("position before G29");
  1819. plan_bed_level_matrix.set_to_identity();
  1820. vector_3 uncorrected_position = plan_get_position();
  1821. //uncorrected_position.debug("position durring G29");
  1822. current_position[X_AXIS] = uncorrected_position.x;
  1823. current_position[Y_AXIS] = uncorrected_position.y;
  1824. current_position[Z_AXIS] = uncorrected_position.z;
  1825. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1826. setup_for_endstop_move();
  1827. feedrate = homing_feedrate[Z_AXIS];
  1828. #ifdef AUTO_BED_LEVELING_GRID
  1829. // probe at the points of a lattice grid
  1830. int xGridSpacing = (RIGHT_PROBE_BED_POSITION - LEFT_PROBE_BED_POSITION) / (AUTO_BED_LEVELING_GRID_POINTS-1);
  1831. int yGridSpacing = (BACK_PROBE_BED_POSITION - FRONT_PROBE_BED_POSITION) / (AUTO_BED_LEVELING_GRID_POINTS-1);
  1832. // solve the plane equation ax + by + d = z
  1833. // A is the matrix with rows [x y 1] for all the probed points
  1834. // B is the vector of the Z positions
  1835. // 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
  1836. // so Vx = -a Vy = -b Vz = 1 (we want the vector facing towards positive Z
  1837. // "A" matrix of the linear system of equations
  1838. double eqnAMatrix[AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS*3];
  1839. // "B" vector of Z points
  1840. double eqnBVector[AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS];
  1841. int probePointCounter = 0;
  1842. bool zig = true;
  1843. for (int yProbe=FRONT_PROBE_BED_POSITION; yProbe <= BACK_PROBE_BED_POSITION; yProbe += yGridSpacing)
  1844. {
  1845. int xProbe, xInc;
  1846. if (zig)
  1847. {
  1848. xProbe = LEFT_PROBE_BED_POSITION;
  1849. //xEnd = RIGHT_PROBE_BED_POSITION;
  1850. xInc = xGridSpacing;
  1851. zig = false;
  1852. } else // zag
  1853. {
  1854. xProbe = RIGHT_PROBE_BED_POSITION;
  1855. //xEnd = LEFT_PROBE_BED_POSITION;
  1856. xInc = -xGridSpacing;
  1857. zig = true;
  1858. }
  1859. for (int xCount=0; xCount < AUTO_BED_LEVELING_GRID_POINTS; xCount++)
  1860. {
  1861. float z_before;
  1862. if (probePointCounter == 0)
  1863. {
  1864. // raise before probing
  1865. z_before = Z_RAISE_BEFORE_PROBING;
  1866. } else
  1867. {
  1868. // raise extruder
  1869. z_before = current_position[Z_AXIS] + Z_RAISE_BETWEEN_PROBINGS;
  1870. }
  1871. float measured_z = probe_pt(xProbe, yProbe, z_before);
  1872. eqnBVector[probePointCounter] = measured_z;
  1873. eqnAMatrix[probePointCounter + 0*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = xProbe;
  1874. eqnAMatrix[probePointCounter + 1*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = yProbe;
  1875. eqnAMatrix[probePointCounter + 2*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = 1;
  1876. probePointCounter++;
  1877. xProbe += xInc;
  1878. }
  1879. }
  1880. clean_up_after_endstop_move();
  1881. // solve lsq problem
  1882. double *plane_equation_coefficients = qr_solve(AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS, 3, eqnAMatrix, eqnBVector);
  1883. SERIAL_PROTOCOLPGM("Eqn coefficients: a: ");
  1884. SERIAL_PROTOCOL(plane_equation_coefficients[0]);
  1885. SERIAL_PROTOCOLPGM(" b: ");
  1886. SERIAL_PROTOCOL(plane_equation_coefficients[1]);
  1887. SERIAL_PROTOCOLPGM(" d: ");
  1888. SERIAL_PROTOCOLLN(plane_equation_coefficients[2]);
  1889. set_bed_level_equation_lsq(plane_equation_coefficients);
  1890. free(plane_equation_coefficients);
  1891. #else // AUTO_BED_LEVELING_GRID not defined
  1892. // Probe at 3 arbitrary points
  1893. // probe 1
  1894. float z_at_pt_1 = probe_pt(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, Z_RAISE_BEFORE_PROBING);
  1895. // probe 2
  1896. float z_at_pt_2 = probe_pt(ABL_PROBE_PT_2_X, ABL_PROBE_PT_2_Y, current_position[Z_AXIS] + Z_RAISE_BETWEEN_PROBINGS);
  1897. // probe 3
  1898. float z_at_pt_3 = probe_pt(ABL_PROBE_PT_3_X, ABL_PROBE_PT_3_Y, current_position[Z_AXIS] + Z_RAISE_BETWEEN_PROBINGS);
  1899. clean_up_after_endstop_move();
  1900. set_bed_level_equation_3pts(z_at_pt_1, z_at_pt_2, z_at_pt_3);
  1901. #endif // AUTO_BED_LEVELING_GRID
  1902. st_synchronize();
  1903. // The following code correct the Z height difference from z-probe position and hotend tip position.
  1904. // The Z height on homing is measured by Z-Probe, but the probe is quite far from the hotend.
  1905. // When the bed is uneven, this height must be corrected.
  1906. 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)
  1907. x_tmp = current_position[X_AXIS] + X_PROBE_OFFSET_FROM_EXTRUDER;
  1908. y_tmp = current_position[Y_AXIS] + Y_PROBE_OFFSET_FROM_EXTRUDER;
  1909. z_tmp = current_position[Z_AXIS];
  1910. apply_rotation_xyz(plan_bed_level_matrix, x_tmp, y_tmp, z_tmp); //Apply the correction sending the probe offset
  1911. current_position[Z_AXIS] = z_tmp - real_z + current_position[Z_AXIS]; //The difference is added to current position and sent to planner.
  1912. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1913. }
  1914. break;
  1915. #ifndef Z_PROBE_SLED
  1916. case 30: // G30 Single Z Probe
  1917. {
  1918. st_synchronize();
  1919. // TODO: make sure the bed_level_rotation_matrix is identity or the planner will get set incorectly
  1920. setup_for_endstop_move();
  1921. feedrate = homing_feedrate[Z_AXIS];
  1922. run_z_probe();
  1923. SERIAL_PROTOCOLPGM(MSG_BED);
  1924. SERIAL_PROTOCOLPGM(" X: ");
  1925. SERIAL_PROTOCOL(current_position[X_AXIS]);
  1926. SERIAL_PROTOCOLPGM(" Y: ");
  1927. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  1928. SERIAL_PROTOCOLPGM(" Z: ");
  1929. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  1930. SERIAL_PROTOCOLPGM("\n");
  1931. clean_up_after_endstop_move();
  1932. }
  1933. break;
  1934. #else
  1935. case 31: // dock the sled
  1936. dock_sled(true);
  1937. break;
  1938. case 32: // undock the sled
  1939. dock_sled(false);
  1940. break;
  1941. #endif // Z_PROBE_SLED
  1942. #endif // ENABLE_AUTO_BED_LEVELING
  1943. #ifdef MESH_BED_LEVELING
  1944. /**
  1945. * G80: Mesh-based Z probe, probes a grid and produces a
  1946. * mesh to compensate for variable bed height
  1947. *
  1948. * The S0 report the points as below
  1949. *
  1950. * +----> X-axis
  1951. * |
  1952. * |
  1953. * v Y-axis
  1954. *
  1955. */
  1956. case 80:
  1957. {
  1958. if (!IS_SD_PRINTING)
  1959. {
  1960. custom_message = true;
  1961. custom_message_type = 1;
  1962. custom_message_state = (MESH_MEAS_NUM_X_POINTS * MESH_MEAS_NUM_Y_POINTS) + 10;
  1963. }
  1964. // Firstly check if we know where we are
  1965. if ( !( axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS] ) ){
  1966. // We don't know where we are! HOME!
  1967. // Push the commands to the front of the message queue in the reverse order!
  1968. // There shall be always enough space reserved for these commands.
  1969. repeatcommand_front(); // repeat G80 with all its parameters
  1970. enquecommand_front_P((PSTR("G28 W0")));
  1971. break;
  1972. }
  1973. mbl.reset();
  1974. // Cycle through all points and probe them
  1975. // First move up.
  1976. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  1977. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], homing_feedrate[Z_AXIS]/60, active_extruder);
  1978. // The move to the first calibration point.
  1979. current_position[X_AXIS] = pgm_read_float(bed_ref_points);
  1980. current_position[Y_AXIS] = pgm_read_float(bed_ref_points+1);
  1981. // mbl.get_meas_xy(0, 0, current_position[X_AXIS], current_position[Y_AXIS], false);
  1982. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], homing_feedrate[X_AXIS]/30, active_extruder);
  1983. // Wait until the move is finished.
  1984. st_synchronize();
  1985. int mesh_point = 0;
  1986. int ix = 0;
  1987. int iy = 0;
  1988. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS]/20;
  1989. int Z_PROBE_FEEDRATE = homing_feedrate[Z_AXIS]/60;
  1990. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS]/40;
  1991. setup_for_endstop_move();
  1992. while (mesh_point != MESH_MEAS_NUM_X_POINTS * MESH_MEAS_NUM_Y_POINTS) {
  1993. // Move Z to proper distance
  1994. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  1995. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], Z_LIFT_FEEDRATE, active_extruder);
  1996. st_synchronize();
  1997. // Get cords of measuring point
  1998. ix = mesh_point % MESH_MEAS_NUM_X_POINTS;
  1999. iy = mesh_point / MESH_MEAS_NUM_X_POINTS;
  2000. if (iy & 1) ix = (MESH_MEAS_NUM_X_POINTS - 1) - ix; // Zig zag
  2001. current_position[X_AXIS] = pgm_read_float(bed_ref_points+2*mesh_point);
  2002. current_position[Y_AXIS] = pgm_read_float(bed_ref_points+2*mesh_point+1);
  2003. // mbl.get_meas_xy(ix, iy, current_position[X_AXIS], current_position[Y_AXIS], false);
  2004. enable_endstops(false);
  2005. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], XY_AXIS_FEEDRATE, active_extruder);
  2006. st_synchronize();
  2007. // Go down until endstop is hit
  2008. find_bed_induction_sensor_point_z();
  2009. mbl.set_z(ix, iy, current_position[Z_AXIS]);
  2010. if (!IS_SD_PRINTING)
  2011. {
  2012. custom_message_state--;
  2013. }
  2014. mesh_point++;
  2015. }
  2016. clean_up_after_endstop_move();
  2017. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2018. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS],current_position[Z_AXIS] , current_position[E_AXIS], Z_LIFT_FEEDRATE, active_extruder);
  2019. mbl.upsample_3x3();
  2020. mbl.active = 1;
  2021. current_position[X_AXIS] = X_MIN_POS+0.2;
  2022. current_position[Y_AXIS] = Y_MIN_POS+0.2;
  2023. current_position[Z_AXIS] = Z_MIN_POS;
  2024. plan_buffer_line(current_position[X_AXIS], current_position[X_AXIS], current_position[Z_AXIS], current_position[E_AXIS], XY_AXIS_FEEDRATE, active_extruder);
  2025. st_synchronize();
  2026. if(card.sdprinting || is_usb_printing )
  2027. {
  2028. if(eeprom_read_byte((unsigned char*)EEPROM_BABYSTEP_Z_SET) == 0x01)
  2029. {
  2030. EEPROM_read_B(EEPROM_BABYSTEP_Z,&babystepLoad[2]);
  2031. babystepsTodo[Z_AXIS] = babystepLoad[2];
  2032. }
  2033. }
  2034. }
  2035. break;
  2036. /**
  2037. * G81: Print mesh bed leveling status and bed profile if activated
  2038. */
  2039. case 81:
  2040. if (mbl.active) {
  2041. SERIAL_PROTOCOLPGM("Num X,Y: ");
  2042. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  2043. SERIAL_PROTOCOLPGM(",");
  2044. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  2045. SERIAL_PROTOCOLPGM("\nZ search height: ");
  2046. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  2047. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  2048. for (int y = MESH_NUM_Y_POINTS-1; y >= 0; y--) {
  2049. for (int x = 0; x < MESH_NUM_X_POINTS; x++) {
  2050. SERIAL_PROTOCOLPGM(" ");
  2051. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  2052. }
  2053. SERIAL_PROTOCOLPGM("\n");
  2054. }
  2055. }
  2056. else
  2057. SERIAL_PROTOCOLLNPGM("Mesh bed leveling not active.");
  2058. break;
  2059. /**
  2060. * G82: Single Z probe at current location
  2061. *
  2062. * WARNING! USE WITH CAUTION! If you'll try to probe where is no leveling pad, nasty things can happen!
  2063. *
  2064. */
  2065. case 82:
  2066. SERIAL_PROTOCOLLNPGM("Finding bed ");
  2067. setup_for_endstop_move();
  2068. find_bed_induction_sensor_point_z();
  2069. clean_up_after_endstop_move();
  2070. SERIAL_PROTOCOLPGM("Bed found at: ");
  2071. SERIAL_PROTOCOL_F(current_position[Z_AXIS], 5);
  2072. SERIAL_PROTOCOLPGM("\n");
  2073. break;
  2074. /**
  2075. * G83: Babystep in Z and store to EEPROM
  2076. */
  2077. case 83:
  2078. {
  2079. int babystepz = code_seen('S') ? code_value() : 0;
  2080. int BabyPosition = code_seen('P') ? code_value() : 0;
  2081. if (babystepz != 0) {
  2082. if (BabyPosition > 4) {
  2083. SERIAL_PROTOCOLLNPGM("Index out of bounds");
  2084. }else{
  2085. // Save it to the eeprom
  2086. babystepLoad[2] = babystepz;
  2087. EEPROM_save_B(EEPROM_BABYSTEP_Z0+(BabyPosition*2),&babystepLoad[2]);
  2088. // adjist the Z
  2089. babystepsTodo[Z_AXIS] = babystepLoad[2];
  2090. }
  2091. }
  2092. }
  2093. break;
  2094. /**
  2095. * G84: UNDO Babystep Z (move Z axis back)
  2096. */
  2097. case 84:
  2098. babystepsTodo[Z_AXIS] = -babystepLoad[2];
  2099. break;
  2100. /**
  2101. * G85: Pick best babystep
  2102. */
  2103. case 85:
  2104. lcd_pick_babystep();
  2105. break;
  2106. /**
  2107. * G86: Disable babystep correction after home
  2108. */
  2109. case 86:
  2110. eeprom_write_byte((unsigned char*)EEPROM_BABYSTEP_Z_SET, 0xFF);
  2111. break;
  2112. /**
  2113. * G87: Enable babystep correction after home
  2114. */
  2115. case 87:
  2116. eeprom_write_byte((unsigned char*)EEPROM_BABYSTEP_Z_SET, 0x01);
  2117. break;
  2118. case 88:
  2119. break;
  2120. #endif // ENABLE_MESH_BED_LEVELING
  2121. case 90: // G90
  2122. relative_mode = false;
  2123. break;
  2124. case 91: // G91
  2125. relative_mode = true;
  2126. break;
  2127. case 92: // G92
  2128. if(!code_seen(axis_codes[E_AXIS]))
  2129. st_synchronize();
  2130. for(int8_t i=0; i < NUM_AXIS; i++) {
  2131. if(code_seen(axis_codes[i])) {
  2132. if(i == E_AXIS) {
  2133. current_position[i] = code_value();
  2134. plan_set_e_position(current_position[E_AXIS]);
  2135. }
  2136. else {
  2137. current_position[i] = code_value()+add_homing[i];
  2138. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  2139. }
  2140. }
  2141. }
  2142. break;
  2143. }
  2144. } // end if(code_seen('G'))
  2145. else if(code_seen('M'))
  2146. {
  2147. switch( (int)code_value() )
  2148. {
  2149. #ifdef ULTIPANEL
  2150. case 0: // M0 - Unconditional stop - Wait for user button press on LCD
  2151. case 1: // M1 - Conditional stop - Wait for user button press on LCD
  2152. {
  2153. char *src = strchr_pointer + 2;
  2154. codenum = 0;
  2155. bool hasP = false, hasS = false;
  2156. if (code_seen('P')) {
  2157. codenum = code_value(); // milliseconds to wait
  2158. hasP = codenum > 0;
  2159. }
  2160. if (code_seen('S')) {
  2161. codenum = code_value() * 1000; // seconds to wait
  2162. hasS = codenum > 0;
  2163. }
  2164. starpos = strchr(src, '*');
  2165. if (starpos != NULL) *(starpos) = '\0';
  2166. while (*src == ' ') ++src;
  2167. if (!hasP && !hasS && *src != '\0') {
  2168. lcd_setstatus(src);
  2169. } else {
  2170. LCD_MESSAGERPGM(MSG_USERWAIT);
  2171. }
  2172. lcd_ignore_click();
  2173. st_synchronize();
  2174. previous_millis_cmd = millis();
  2175. if (codenum > 0){
  2176. codenum += millis(); // keep track of when we started waiting
  2177. while(millis() < codenum && !lcd_clicked()){
  2178. manage_heater();
  2179. manage_inactivity();
  2180. lcd_update();
  2181. }
  2182. lcd_ignore_click(false);
  2183. }else{
  2184. if (!lcd_detected())
  2185. break;
  2186. while(!lcd_clicked()){
  2187. manage_heater();
  2188. manage_inactivity();
  2189. lcd_update();
  2190. }
  2191. }
  2192. if (IS_SD_PRINTING)
  2193. LCD_MESSAGERPGM(MSG_RESUMING);
  2194. else
  2195. LCD_MESSAGERPGM(WELCOME_MSG);
  2196. }
  2197. break;
  2198. #endif
  2199. case 17:
  2200. LCD_MESSAGERPGM(MSG_NO_MOVE);
  2201. enable_x();
  2202. enable_y();
  2203. enable_z();
  2204. enable_e0();
  2205. enable_e1();
  2206. enable_e2();
  2207. break;
  2208. #ifdef SDSUPPORT
  2209. case 20: // M20 - list SD card
  2210. SERIAL_PROTOCOLLNRPGM(MSG_BEGIN_FILE_LIST);
  2211. card.ls();
  2212. SERIAL_PROTOCOLLNRPGM(MSG_END_FILE_LIST);
  2213. break;
  2214. case 21: // M21 - init SD card
  2215. card.initsd();
  2216. break;
  2217. case 22: //M22 - release SD card
  2218. card.release();
  2219. break;
  2220. case 23: //M23 - Select file
  2221. starpos = (strchr(strchr_pointer + 4,'*'));
  2222. if(starpos!=NULL)
  2223. *(starpos)='\0';
  2224. card.openFile(strchr_pointer + 4,true);
  2225. break;
  2226. case 24: //M24 - Start SD print
  2227. card.startFileprint();
  2228. starttime=millis();
  2229. break;
  2230. case 25: //M25 - Pause SD print
  2231. card.pauseSDPrint();
  2232. break;
  2233. case 26: //M26 - Set SD index
  2234. if(card.cardOK && code_seen('S')) {
  2235. card.setIndex(code_value_long());
  2236. }
  2237. break;
  2238. case 27: //M27 - Get SD status
  2239. card.getStatus();
  2240. break;
  2241. case 28: //M28 - Start SD write
  2242. starpos = (strchr(strchr_pointer + 4,'*'));
  2243. if(starpos != NULL){
  2244. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  2245. strchr_pointer = strchr(npos,' ') + 1;
  2246. *(starpos) = '\0';
  2247. }
  2248. card.openFile(strchr_pointer+4,false);
  2249. break;
  2250. case 29: //M29 - Stop SD write
  2251. //processed in write to file routine above
  2252. //card,saving = false;
  2253. break;
  2254. case 30: //M30 <filename> Delete File
  2255. if (card.cardOK){
  2256. card.closefile();
  2257. starpos = (strchr(strchr_pointer + 4,'*'));
  2258. if(starpos != NULL){
  2259. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  2260. strchr_pointer = strchr(npos,' ') + 1;
  2261. *(starpos) = '\0';
  2262. }
  2263. card.removeFile(strchr_pointer + 4);
  2264. }
  2265. break;
  2266. case 32: //M32 - Select file and start SD print
  2267. {
  2268. if(card.sdprinting) {
  2269. st_synchronize();
  2270. }
  2271. starpos = (strchr(strchr_pointer + 4,'*'));
  2272. char* namestartpos = (strchr(strchr_pointer + 4,'!')); //find ! to indicate filename string start.
  2273. if(namestartpos==NULL)
  2274. {
  2275. namestartpos=strchr_pointer + 4; //default name position, 4 letters after the M
  2276. }
  2277. else
  2278. namestartpos++; //to skip the '!'
  2279. if(starpos!=NULL)
  2280. *(starpos)='\0';
  2281. bool call_procedure=(code_seen('P'));
  2282. if(strchr_pointer>namestartpos)
  2283. call_procedure=false; //false alert, 'P' found within filename
  2284. if( card.cardOK )
  2285. {
  2286. card.openFile(namestartpos,true,!call_procedure);
  2287. if(code_seen('S'))
  2288. if(strchr_pointer<namestartpos) //only if "S" is occuring _before_ the filename
  2289. card.setIndex(code_value_long());
  2290. card.startFileprint();
  2291. if(!call_procedure)
  2292. starttime=millis(); //procedure calls count as normal print time.
  2293. }
  2294. } break;
  2295. case 928: //M928 - Start SD write
  2296. starpos = (strchr(strchr_pointer + 5,'*'));
  2297. if(starpos != NULL){
  2298. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  2299. strchr_pointer = strchr(npos,' ') + 1;
  2300. *(starpos) = '\0';
  2301. }
  2302. card.openLogFile(strchr_pointer+5);
  2303. break;
  2304. #endif //SDSUPPORT
  2305. case 31: //M31 take time since the start of the SD print or an M109 command
  2306. {
  2307. stoptime=millis();
  2308. char time[30];
  2309. unsigned long t=(stoptime-starttime)/1000;
  2310. int sec,min;
  2311. min=t/60;
  2312. sec=t%60;
  2313. sprintf_P(time, PSTR("%i min, %i sec"), min, sec);
  2314. SERIAL_ECHO_START;
  2315. SERIAL_ECHOLN(time);
  2316. lcd_setstatus(time);
  2317. autotempShutdown();
  2318. }
  2319. break;
  2320. case 42: //M42 -Change pin status via gcode
  2321. if (code_seen('S'))
  2322. {
  2323. int pin_status = code_value();
  2324. int pin_number = LED_PIN;
  2325. if (code_seen('P') && pin_status >= 0 && pin_status <= 255)
  2326. pin_number = code_value();
  2327. for(int8_t i = 0; i < (int8_t)(sizeof(sensitive_pins)/sizeof(int)); i++)
  2328. {
  2329. if (sensitive_pins[i] == pin_number)
  2330. {
  2331. pin_number = -1;
  2332. break;
  2333. }
  2334. }
  2335. #if defined(FAN_PIN) && FAN_PIN > -1
  2336. if (pin_number == FAN_PIN)
  2337. fanSpeed = pin_status;
  2338. #endif
  2339. if (pin_number > -1)
  2340. {
  2341. pinMode(pin_number, OUTPUT);
  2342. digitalWrite(pin_number, pin_status);
  2343. analogWrite(pin_number, pin_status);
  2344. }
  2345. }
  2346. break;
  2347. case 44: // M45: Reset the bed skew and offset calibration.
  2348. // Reset the skew and offset in both RAM and EEPROM.
  2349. reset_bed_offset_and_skew();
  2350. world2machine_reset();
  2351. // Wait for the motors to stop and update the current position with the absolute values.
  2352. st_synchronize();
  2353. current_position[X_AXIS] = st_get_position_mm(X_AXIS);
  2354. current_position[Y_AXIS] = st_get_position_mm(Y_AXIS);
  2355. break;
  2356. case 45: // M46: bed skew and offset with manual Z up
  2357. {
  2358. // Disable the default update procedure of the display. We will do a modal dialog.
  2359. lcd_update_enable(false);
  2360. // Let the planner use the uncorrected coordinates.
  2361. mbl.reset();
  2362. world2machine_reset();
  2363. // Let the user move the Z axes up to the end stoppers.
  2364. if (lcd_calibrate_z_end_stop_manual()) {
  2365. // Move the print head close to the bed.
  2366. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2367. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS],current_position[Z_AXIS] , current_position[E_AXIS], homing_feedrate[Z_AXIS]/40, active_extruder);
  2368. st_synchronize();
  2369. // Home in the XY plane.
  2370. set_destination_to_current();
  2371. setup_for_endstop_move();
  2372. home_xy();
  2373. int8_t verbosity_level = 0;
  2374. if (code_seen('V')) {
  2375. // Just 'V' without a number counts as V1.
  2376. char c = strchr_pointer[1];
  2377. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  2378. }
  2379. bool success = find_bed_offset_and_skew(verbosity_level);
  2380. clean_up_after_endstop_move();
  2381. // Print head up.
  2382. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2383. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS],current_position[Z_AXIS] , current_position[E_AXIS], homing_feedrate[Z_AXIS]/40, active_extruder);
  2384. st_synchronize();
  2385. // Second half: The fine adjustment.
  2386. // Let the planner use the uncorrected coordinates.
  2387. mbl.reset();
  2388. world2machine_reset();
  2389. // Home in the XY plane.
  2390. setup_for_endstop_move();
  2391. home_xy();
  2392. success = improve_bed_offset_and_skew(1, verbosity_level);
  2393. clean_up_after_endstop_move();
  2394. // Print head up.
  2395. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2396. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS],current_position[Z_AXIS] , current_position[E_AXIS], homing_feedrate[Z_AXIS]/40, active_extruder);
  2397. st_synchronize();
  2398. if (success) {
  2399. // Mesh bed leveling.
  2400. // Push the commands to the front of the message queue in the reverse order!
  2401. // There shall be always enough space reserved for these commands.
  2402. enquecommand_front_P((PSTR("G80")));
  2403. }
  2404. lcd_update_enable(true);
  2405. lcd_implementation_clear();
  2406. // lcd_return_to_status();
  2407. lcd_update();
  2408. }
  2409. break;
  2410. }
  2411. case 47:
  2412. lcd_diag_show_end_stops();
  2413. break;
  2414. // M48 Z-Probe repeatability measurement function.
  2415. //
  2416. // Usage: M48 <n #_samples> <X X_position_for_samples> <Y Y_position_for_samples> <V Verbose_Level> <L legs_of_movement_prior_to_doing_probe>
  2417. //
  2418. // This function assumes the bed has been homed. Specificaly, that a G28 command
  2419. // as been issued prior to invoking the M48 Z-Probe repeatability measurement function.
  2420. // Any information generated by a prior G29 Bed leveling command will be lost and need to be
  2421. // regenerated.
  2422. //
  2423. // The number of samples will default to 10 if not specified. You can use upper or lower case
  2424. // letters for any of the options EXCEPT n. n must be in lower case because Marlin uses a capital
  2425. // N for its communication protocol and will get horribly confused if you send it a capital N.
  2426. //
  2427. #ifdef ENABLE_AUTO_BED_LEVELING
  2428. #ifdef Z_PROBE_REPEATABILITY_TEST
  2429. case 48: // M48 Z-Probe repeatability
  2430. {
  2431. #if Z_MIN_PIN == -1
  2432. #error "You must have a Z_MIN endstop in order to enable calculation of Z-Probe repeatability."
  2433. #endif
  2434. double sum=0.0;
  2435. double mean=0.0;
  2436. double sigma=0.0;
  2437. double sample_set[50];
  2438. int verbose_level=1, n=0, j, n_samples = 10, n_legs=0;
  2439. double X_current, Y_current, Z_current;
  2440. double X_probe_location, Y_probe_location, Z_start_location, ext_position;
  2441. if (code_seen('V') || code_seen('v')) {
  2442. verbose_level = code_value();
  2443. if (verbose_level<0 || verbose_level>4 ) {
  2444. SERIAL_PROTOCOLPGM("?Verbose Level not plausable.\n");
  2445. goto Sigma_Exit;
  2446. }
  2447. }
  2448. if (verbose_level > 0) {
  2449. SERIAL_PROTOCOLPGM("M48 Z-Probe Repeatability test. Version 2.00\n");
  2450. SERIAL_PROTOCOLPGM("Full support at: http://3dprintboard.com/forum.php\n");
  2451. }
  2452. if (code_seen('n')) {
  2453. n_samples = code_value();
  2454. if (n_samples<4 || n_samples>50 ) {
  2455. SERIAL_PROTOCOLPGM("?Specified sample size not plausable.\n");
  2456. goto Sigma_Exit;
  2457. }
  2458. }
  2459. X_current = X_probe_location = st_get_position_mm(X_AXIS);
  2460. Y_current = Y_probe_location = st_get_position_mm(Y_AXIS);
  2461. Z_current = st_get_position_mm(Z_AXIS);
  2462. Z_start_location = st_get_position_mm(Z_AXIS) + Z_RAISE_BEFORE_PROBING;
  2463. ext_position = st_get_position_mm(E_AXIS);
  2464. if (code_seen('X') || code_seen('x') ) {
  2465. X_probe_location = code_value() - X_PROBE_OFFSET_FROM_EXTRUDER;
  2466. if (X_probe_location<X_MIN_POS || X_probe_location>X_MAX_POS ) {
  2467. SERIAL_PROTOCOLPGM("?Specified X position out of range.\n");
  2468. goto Sigma_Exit;
  2469. }
  2470. }
  2471. if (code_seen('Y') || code_seen('y') ) {
  2472. Y_probe_location = code_value() - Y_PROBE_OFFSET_FROM_EXTRUDER;
  2473. if (Y_probe_location<Y_MIN_POS || Y_probe_location>Y_MAX_POS ) {
  2474. SERIAL_PROTOCOLPGM("?Specified Y position out of range.\n");
  2475. goto Sigma_Exit;
  2476. }
  2477. }
  2478. if (code_seen('L') || code_seen('l') ) {
  2479. n_legs = code_value();
  2480. if ( n_legs==1 )
  2481. n_legs = 2;
  2482. if ( n_legs<0 || n_legs>15 ) {
  2483. SERIAL_PROTOCOLPGM("?Specified number of legs in movement not plausable.\n");
  2484. goto Sigma_Exit;
  2485. }
  2486. }
  2487. //
  2488. // Do all the preliminary setup work. First raise the probe.
  2489. //
  2490. st_synchronize();
  2491. plan_bed_level_matrix.set_to_identity();
  2492. plan_buffer_line( X_current, Y_current, Z_start_location,
  2493. ext_position,
  2494. homing_feedrate[Z_AXIS]/60,
  2495. active_extruder);
  2496. st_synchronize();
  2497. //
  2498. // Now get everything to the specified probe point So we can safely do a probe to
  2499. // get us close to the bed. If the Z-Axis is far from the bed, we don't want to
  2500. // use that as a starting point for each probe.
  2501. //
  2502. if (verbose_level > 2)
  2503. SERIAL_PROTOCOL("Positioning probe for the test.\n");
  2504. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  2505. ext_position,
  2506. homing_feedrate[X_AXIS]/60,
  2507. active_extruder);
  2508. st_synchronize();
  2509. current_position[X_AXIS] = X_current = st_get_position_mm(X_AXIS);
  2510. current_position[Y_AXIS] = Y_current = st_get_position_mm(Y_AXIS);
  2511. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  2512. current_position[E_AXIS] = ext_position = st_get_position_mm(E_AXIS);
  2513. //
  2514. // OK, do the inital probe to get us close to the bed.
  2515. // Then retrace the right amount and use that in subsequent probes
  2516. //
  2517. setup_for_endstop_move();
  2518. run_z_probe();
  2519. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  2520. Z_start_location = st_get_position_mm(Z_AXIS) + Z_RAISE_BEFORE_PROBING;
  2521. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  2522. ext_position,
  2523. homing_feedrate[X_AXIS]/60,
  2524. active_extruder);
  2525. st_synchronize();
  2526. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  2527. for( n=0; n<n_samples; n++) {
  2528. do_blocking_move_to( X_probe_location, Y_probe_location, Z_start_location); // Make sure we are at the probe location
  2529. if ( n_legs) {
  2530. double radius=0.0, theta=0.0, x_sweep, y_sweep;
  2531. int rotational_direction, l;
  2532. rotational_direction = (unsigned long) millis() & 0x0001; // clockwise or counter clockwise
  2533. radius = (unsigned long) millis() % (long) (X_MAX_LENGTH/4); // limit how far out to go
  2534. theta = (float) ((unsigned long) millis() % (long) 360) / (360./(2*3.1415926)); // turn into radians
  2535. //SERIAL_ECHOPAIR("starting radius: ",radius);
  2536. //SERIAL_ECHOPAIR(" theta: ",theta);
  2537. //SERIAL_ECHOPAIR(" direction: ",rotational_direction);
  2538. //SERIAL_PROTOCOLLNPGM("");
  2539. for( l=0; l<n_legs-1; l++) {
  2540. if (rotational_direction==1)
  2541. theta += (float) ((unsigned long) millis() % (long) 20) / (360.0/(2*3.1415926)); // turn into radians
  2542. else
  2543. theta -= (float) ((unsigned long) millis() % (long) 20) / (360.0/(2*3.1415926)); // turn into radians
  2544. radius += (float) ( ((long) ((unsigned long) millis() % (long) 10)) - 5);
  2545. if ( radius<0.0 )
  2546. radius = -radius;
  2547. X_current = X_probe_location + cos(theta) * radius;
  2548. Y_current = Y_probe_location + sin(theta) * radius;
  2549. if ( X_current<X_MIN_POS) // Make sure our X & Y are sane
  2550. X_current = X_MIN_POS;
  2551. if ( X_current>X_MAX_POS)
  2552. X_current = X_MAX_POS;
  2553. if ( Y_current<Y_MIN_POS) // Make sure our X & Y are sane
  2554. Y_current = Y_MIN_POS;
  2555. if ( Y_current>Y_MAX_POS)
  2556. Y_current = Y_MAX_POS;
  2557. if (verbose_level>3 ) {
  2558. SERIAL_ECHOPAIR("x: ", X_current);
  2559. SERIAL_ECHOPAIR("y: ", Y_current);
  2560. SERIAL_PROTOCOLLNPGM("");
  2561. }
  2562. do_blocking_move_to( X_current, Y_current, Z_current );
  2563. }
  2564. do_blocking_move_to( X_probe_location, Y_probe_location, Z_start_location); // Go back to the probe location
  2565. }
  2566. setup_for_endstop_move();
  2567. run_z_probe();
  2568. sample_set[n] = current_position[Z_AXIS];
  2569. //
  2570. // Get the current mean for the data points we have so far
  2571. //
  2572. sum=0.0;
  2573. for( j=0; j<=n; j++) {
  2574. sum = sum + sample_set[j];
  2575. }
  2576. mean = sum / (double (n+1));
  2577. //
  2578. // Now, use that mean to calculate the standard deviation for the
  2579. // data points we have so far
  2580. //
  2581. sum=0.0;
  2582. for( j=0; j<=n; j++) {
  2583. sum = sum + (sample_set[j]-mean) * (sample_set[j]-mean);
  2584. }
  2585. sigma = sqrt( sum / (double (n+1)) );
  2586. if (verbose_level > 1) {
  2587. SERIAL_PROTOCOL(n+1);
  2588. SERIAL_PROTOCOL(" of ");
  2589. SERIAL_PROTOCOL(n_samples);
  2590. SERIAL_PROTOCOLPGM(" z: ");
  2591. SERIAL_PROTOCOL_F(current_position[Z_AXIS], 6);
  2592. }
  2593. if (verbose_level > 2) {
  2594. SERIAL_PROTOCOL(" mean: ");
  2595. SERIAL_PROTOCOL_F(mean,6);
  2596. SERIAL_PROTOCOL(" sigma: ");
  2597. SERIAL_PROTOCOL_F(sigma,6);
  2598. }
  2599. if (verbose_level > 0)
  2600. SERIAL_PROTOCOLPGM("\n");
  2601. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  2602. current_position[E_AXIS], homing_feedrate[Z_AXIS]/60, active_extruder);
  2603. st_synchronize();
  2604. }
  2605. delay(1000);
  2606. clean_up_after_endstop_move();
  2607. // enable_endstops(true);
  2608. if (verbose_level > 0) {
  2609. SERIAL_PROTOCOLPGM("Mean: ");
  2610. SERIAL_PROTOCOL_F(mean, 6);
  2611. SERIAL_PROTOCOLPGM("\n");
  2612. }
  2613. SERIAL_PROTOCOLPGM("Standard Deviation: ");
  2614. SERIAL_PROTOCOL_F(sigma, 6);
  2615. SERIAL_PROTOCOLPGM("\n\n");
  2616. Sigma_Exit:
  2617. break;
  2618. }
  2619. #endif // Z_PROBE_REPEATABILITY_TEST
  2620. #endif // ENABLE_AUTO_BED_LEVELING
  2621. case 104: // M104
  2622. if(setTargetedHotend(104)){
  2623. break;
  2624. }
  2625. if (code_seen('S')) setTargetHotend(code_value(), tmp_extruder);
  2626. #ifdef DUAL_X_CARRIAGE
  2627. if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && tmp_extruder == 0)
  2628. setTargetHotend1(code_value() == 0.0 ? 0.0 : code_value() + duplicate_extruder_temp_offset);
  2629. #endif
  2630. setWatch();
  2631. break;
  2632. case 112: // M112 -Emergency Stop
  2633. kill();
  2634. break;
  2635. case 140: // M140 set bed temp
  2636. if (code_seen('S')) setTargetBed(code_value());
  2637. break;
  2638. case 105 : // M105
  2639. if(setTargetedHotend(105)){
  2640. break;
  2641. }
  2642. #if defined(TEMP_0_PIN) && TEMP_0_PIN > -1
  2643. SERIAL_PROTOCOLPGM("ok T:");
  2644. SERIAL_PROTOCOL_F(degHotend(tmp_extruder),1);
  2645. SERIAL_PROTOCOLPGM(" /");
  2646. SERIAL_PROTOCOL_F(degTargetHotend(tmp_extruder),1);
  2647. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  2648. SERIAL_PROTOCOLPGM(" B:");
  2649. SERIAL_PROTOCOL_F(degBed(),1);
  2650. SERIAL_PROTOCOLPGM(" /");
  2651. SERIAL_PROTOCOL_F(degTargetBed(),1);
  2652. #endif //TEMP_BED_PIN
  2653. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  2654. SERIAL_PROTOCOLPGM(" T");
  2655. SERIAL_PROTOCOL(cur_extruder);
  2656. SERIAL_PROTOCOLPGM(":");
  2657. SERIAL_PROTOCOL_F(degHotend(cur_extruder),1);
  2658. SERIAL_PROTOCOLPGM(" /");
  2659. SERIAL_PROTOCOL_F(degTargetHotend(cur_extruder),1);
  2660. }
  2661. #else
  2662. SERIAL_ERROR_START;
  2663. SERIAL_ERRORLNRPGM(MSG_ERR_NO_THERMISTORS);
  2664. #endif
  2665. SERIAL_PROTOCOLPGM(" @:");
  2666. #ifdef EXTRUDER_WATTS
  2667. SERIAL_PROTOCOL((EXTRUDER_WATTS * getHeaterPower(tmp_extruder))/127);
  2668. SERIAL_PROTOCOLPGM("W");
  2669. #else
  2670. SERIAL_PROTOCOL(getHeaterPower(tmp_extruder));
  2671. #endif
  2672. SERIAL_PROTOCOLPGM(" B@:");
  2673. #ifdef BED_WATTS
  2674. SERIAL_PROTOCOL((BED_WATTS * getHeaterPower(-1))/127);
  2675. SERIAL_PROTOCOLPGM("W");
  2676. #else
  2677. SERIAL_PROTOCOL(getHeaterPower(-1));
  2678. #endif
  2679. #ifdef SHOW_TEMP_ADC_VALUES
  2680. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  2681. SERIAL_PROTOCOLPGM(" ADC B:");
  2682. SERIAL_PROTOCOL_F(degBed(),1);
  2683. SERIAL_PROTOCOLPGM("C->");
  2684. SERIAL_PROTOCOL_F(rawBedTemp()/OVERSAMPLENR,0);
  2685. #endif
  2686. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  2687. SERIAL_PROTOCOLPGM(" T");
  2688. SERIAL_PROTOCOL(cur_extruder);
  2689. SERIAL_PROTOCOLPGM(":");
  2690. SERIAL_PROTOCOL_F(degHotend(cur_extruder),1);
  2691. SERIAL_PROTOCOLPGM("C->");
  2692. SERIAL_PROTOCOL_F(rawHotendTemp(cur_extruder)/OVERSAMPLENR,0);
  2693. }
  2694. #endif
  2695. SERIAL_PROTOCOLLN("");
  2696. return;
  2697. break;
  2698. case 109:
  2699. {// M109 - Wait for extruder heater to reach target.
  2700. if(setTargetedHotend(109)){
  2701. break;
  2702. }
  2703. LCD_MESSAGERPGM(MSG_HEATING);
  2704. heating_status = 1;
  2705. #ifdef AUTOTEMP
  2706. autotemp_enabled=false;
  2707. #endif
  2708. if (code_seen('S')) {
  2709. setTargetHotend(code_value(), tmp_extruder);
  2710. #ifdef DUAL_X_CARRIAGE
  2711. if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && tmp_extruder == 0)
  2712. setTargetHotend1(code_value() == 0.0 ? 0.0 : code_value() + duplicate_extruder_temp_offset);
  2713. #endif
  2714. CooldownNoWait = true;
  2715. } else if (code_seen('R')) {
  2716. setTargetHotend(code_value(), tmp_extruder);
  2717. #ifdef DUAL_X_CARRIAGE
  2718. if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && tmp_extruder == 0)
  2719. setTargetHotend1(code_value() == 0.0 ? 0.0 : code_value() + duplicate_extruder_temp_offset);
  2720. #endif
  2721. CooldownNoWait = false;
  2722. }
  2723. #ifdef AUTOTEMP
  2724. if (code_seen('S')) autotemp_min=code_value();
  2725. if (code_seen('B')) autotemp_max=code_value();
  2726. if (code_seen('F'))
  2727. {
  2728. autotemp_factor=code_value();
  2729. autotemp_enabled=true;
  2730. }
  2731. #endif
  2732. setWatch();
  2733. codenum = millis();
  2734. /* See if we are heating up or cooling down */
  2735. target_direction = isHeatingHotend(tmp_extruder); // true if heating, false if cooling
  2736. cancel_heatup = false;
  2737. #ifdef TEMP_RESIDENCY_TIME
  2738. long residencyStart;
  2739. residencyStart = -1;
  2740. /* continue to loop until we have reached the target temp
  2741. _and_ until TEMP_RESIDENCY_TIME hasn't passed since we reached it */
  2742. while((!cancel_heatup)&&((residencyStart == -1) ||
  2743. (residencyStart >= 0 && (((unsigned int) (millis() - residencyStart)) < (TEMP_RESIDENCY_TIME * 1000UL)))) ) {
  2744. #else
  2745. while ( target_direction ? (isHeatingHotend(tmp_extruder)) : (isCoolingHotend(tmp_extruder)&&(CooldownNoWait==false)) ) {
  2746. #endif //TEMP_RESIDENCY_TIME
  2747. if( (millis() - codenum) > 1000UL )
  2748. { //Print Temp Reading and remaining time every 1 second while heating up/cooling down
  2749. SERIAL_PROTOCOLPGM("T:");
  2750. SERIAL_PROTOCOL_F(degHotend(tmp_extruder),1);
  2751. SERIAL_PROTOCOLPGM(" E:");
  2752. SERIAL_PROTOCOL((int)tmp_extruder);
  2753. #ifdef TEMP_RESIDENCY_TIME
  2754. SERIAL_PROTOCOLPGM(" W:");
  2755. if(residencyStart > -1)
  2756. {
  2757. codenum = ((TEMP_RESIDENCY_TIME * 1000UL) - (millis() - residencyStart)) / 1000UL;
  2758. SERIAL_PROTOCOLLN( codenum );
  2759. }
  2760. else
  2761. {
  2762. SERIAL_PROTOCOLLN( "?" );
  2763. }
  2764. #else
  2765. SERIAL_PROTOCOLLN("");
  2766. #endif
  2767. codenum = millis();
  2768. }
  2769. manage_heater();
  2770. manage_inactivity();
  2771. lcd_update();
  2772. #ifdef TEMP_RESIDENCY_TIME
  2773. /* start/restart the TEMP_RESIDENCY_TIME timer whenever we reach target temp for the first time
  2774. or when current temp falls outside the hysteresis after target temp was reached */
  2775. if ((residencyStart == -1 && target_direction && (degHotend(tmp_extruder) >= (degTargetHotend(tmp_extruder)-TEMP_WINDOW))) ||
  2776. (residencyStart == -1 && !target_direction && (degHotend(tmp_extruder) <= (degTargetHotend(tmp_extruder)+TEMP_WINDOW))) ||
  2777. (residencyStart > -1 && labs(degHotend(tmp_extruder) - degTargetHotend(tmp_extruder)) > TEMP_HYSTERESIS) )
  2778. {
  2779. residencyStart = millis();
  2780. }
  2781. #endif //TEMP_RESIDENCY_TIME
  2782. }
  2783. LCD_MESSAGERPGM(MSG_HEATING_COMPLETE);
  2784. heating_status = 2;
  2785. starttime=millis();
  2786. previous_millis_cmd = millis();
  2787. }
  2788. break;
  2789. case 190: // M190 - Wait for bed heater to reach target.
  2790. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  2791. LCD_MESSAGERPGM(MSG_BED_HEATING);
  2792. heating_status = 3;
  2793. if (code_seen('S'))
  2794. {
  2795. setTargetBed(code_value());
  2796. CooldownNoWait = true;
  2797. }
  2798. else if (code_seen('R'))
  2799. {
  2800. setTargetBed(code_value());
  2801. CooldownNoWait = false;
  2802. }
  2803. codenum = millis();
  2804. cancel_heatup = false;
  2805. target_direction = isHeatingBed(); // true if heating, false if cooling
  2806. while ( (target_direction)&&(!cancel_heatup) ? (isHeatingBed()) : (isCoolingBed()&&(CooldownNoWait==false)) )
  2807. {
  2808. if(( millis() - codenum) > 1000 ) //Print Temp Reading every 1 second while heating up.
  2809. {
  2810. float tt=degHotend(active_extruder);
  2811. SERIAL_PROTOCOLPGM("T:");
  2812. SERIAL_PROTOCOL(tt);
  2813. SERIAL_PROTOCOLPGM(" E:");
  2814. SERIAL_PROTOCOL((int)active_extruder);
  2815. SERIAL_PROTOCOLPGM(" B:");
  2816. SERIAL_PROTOCOL_F(degBed(),1);
  2817. SERIAL_PROTOCOLLN("");
  2818. codenum = millis();
  2819. }
  2820. manage_heater();
  2821. manage_inactivity();
  2822. lcd_update();
  2823. }
  2824. LCD_MESSAGERPGM(MSG_BED_DONE);
  2825. heating_status = 4;
  2826. previous_millis_cmd = millis();
  2827. #endif
  2828. break;
  2829. #if defined(FAN_PIN) && FAN_PIN > -1
  2830. case 106: //M106 Fan On
  2831. if (code_seen('S')){
  2832. fanSpeed=constrain(code_value(),0,255);
  2833. }
  2834. else {
  2835. fanSpeed=255;
  2836. }
  2837. break;
  2838. case 107: //M107 Fan Off
  2839. fanSpeed = 0;
  2840. break;
  2841. #endif //FAN_PIN
  2842. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  2843. case 80: // M80 - Turn on Power Supply
  2844. SET_OUTPUT(PS_ON_PIN); //GND
  2845. WRITE(PS_ON_PIN, PS_ON_AWAKE);
  2846. // If you have a switch on suicide pin, this is useful
  2847. // if you want to start another print with suicide feature after
  2848. // a print without suicide...
  2849. #if defined SUICIDE_PIN && SUICIDE_PIN > -1
  2850. SET_OUTPUT(SUICIDE_PIN);
  2851. WRITE(SUICIDE_PIN, HIGH);
  2852. #endif
  2853. #ifdef ULTIPANEL
  2854. powersupply = true;
  2855. LCD_MESSAGERPGM(WELCOME_MSG);
  2856. lcd_update();
  2857. #endif
  2858. break;
  2859. #endif
  2860. case 81: // M81 - Turn off Power Supply
  2861. disable_heater();
  2862. st_synchronize();
  2863. disable_e0();
  2864. disable_e1();
  2865. disable_e2();
  2866. finishAndDisableSteppers();
  2867. fanSpeed = 0;
  2868. delay(1000); // Wait a little before to switch off
  2869. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  2870. st_synchronize();
  2871. suicide();
  2872. #elif defined(PS_ON_PIN) && PS_ON_PIN > -1
  2873. SET_OUTPUT(PS_ON_PIN);
  2874. WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  2875. #endif
  2876. #ifdef ULTIPANEL
  2877. powersupply = false;
  2878. LCD_MESSAGERPGM(CAT4(CUSTOM_MENDEL_NAME,PSTR(" "),MSG_OFF,PSTR("."))); //!!
  2879. /*
  2880. MACHNAME = "Prusa i3"
  2881. MSGOFF = "Vypnuto"
  2882. "Prusai3"" ""vypnuto""."
  2883. "Prusa i3"" "MSG_ALL[lang_selected][50]"."
  2884. */
  2885. lcd_update();
  2886. #endif
  2887. break;
  2888. case 82:
  2889. axis_relative_modes[3] = false;
  2890. break;
  2891. case 83:
  2892. axis_relative_modes[3] = true;
  2893. break;
  2894. case 18: //compatibility
  2895. case 84: // M84
  2896. if(code_seen('S')){
  2897. stepper_inactive_time = code_value() * 1000;
  2898. }
  2899. else
  2900. {
  2901. bool all_axis = !((code_seen(axis_codes[X_AXIS])) || (code_seen(axis_codes[Y_AXIS])) || (code_seen(axis_codes[Z_AXIS]))|| (code_seen(axis_codes[E_AXIS])));
  2902. if(all_axis)
  2903. {
  2904. st_synchronize();
  2905. disable_e0();
  2906. disable_e1();
  2907. disable_e2();
  2908. finishAndDisableSteppers();
  2909. }
  2910. else
  2911. {
  2912. st_synchronize();
  2913. if(code_seen('X')) disable_x();
  2914. if(code_seen('Y')) disable_y();
  2915. if(code_seen('Z')) disable_z();
  2916. #if ((E0_ENABLE_PIN != X_ENABLE_PIN) && (E1_ENABLE_PIN != Y_ENABLE_PIN)) // Only enable on boards that have seperate ENABLE_PINS
  2917. if(code_seen('E')) {
  2918. disable_e0();
  2919. disable_e1();
  2920. disable_e2();
  2921. }
  2922. #endif
  2923. }
  2924. }
  2925. break;
  2926. case 85: // M85
  2927. if(code_seen('S')) {
  2928. max_inactive_time = code_value() * 1000;
  2929. }
  2930. break;
  2931. case 92: // M92
  2932. for(int8_t i=0; i < NUM_AXIS; i++)
  2933. {
  2934. if(code_seen(axis_codes[i]))
  2935. {
  2936. if(i == 3) { // E
  2937. float value = code_value();
  2938. if(value < 20.0) {
  2939. float factor = axis_steps_per_unit[i] / value; // increase e constants if M92 E14 is given for netfab.
  2940. max_e_jerk *= factor;
  2941. max_feedrate[i] *= factor;
  2942. axis_steps_per_sqr_second[i] *= factor;
  2943. }
  2944. axis_steps_per_unit[i] = value;
  2945. }
  2946. else {
  2947. axis_steps_per_unit[i] = code_value();
  2948. }
  2949. }
  2950. }
  2951. break;
  2952. case 115: // M115
  2953. SERIAL_PROTOCOLRPGM(MSG_M115_REPORT);
  2954. break;
  2955. case 117: // M117 display message
  2956. starpos = (strchr(strchr_pointer + 5,'*'));
  2957. if(starpos!=NULL)
  2958. *(starpos)='\0';
  2959. lcd_setstatus(strchr_pointer + 5);
  2960. break;
  2961. case 114: // M114
  2962. SERIAL_PROTOCOLPGM("X:");
  2963. SERIAL_PROTOCOL(current_position[X_AXIS]);
  2964. SERIAL_PROTOCOLPGM(" Y:");
  2965. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  2966. SERIAL_PROTOCOLPGM(" Z:");
  2967. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  2968. SERIAL_PROTOCOLPGM(" E:");
  2969. SERIAL_PROTOCOL(current_position[E_AXIS]);
  2970. SERIAL_PROTOCOLRPGM(MSG_COUNT_X);
  2971. SERIAL_PROTOCOL(float(st_get_position(X_AXIS))/axis_steps_per_unit[X_AXIS]);
  2972. SERIAL_PROTOCOLPGM(" Y:");
  2973. SERIAL_PROTOCOL(float(st_get_position(Y_AXIS))/axis_steps_per_unit[Y_AXIS]);
  2974. SERIAL_PROTOCOLPGM(" Z:");
  2975. SERIAL_PROTOCOL(float(st_get_position(Z_AXIS))/axis_steps_per_unit[Z_AXIS]);
  2976. SERIAL_PROTOCOLLN("");
  2977. break;
  2978. case 120: // M120
  2979. enable_endstops(false) ;
  2980. break;
  2981. case 121: // M121
  2982. enable_endstops(true) ;
  2983. break;
  2984. case 119: // M119
  2985. SERIAL_PROTOCOLRPGM(MSG_M119_REPORT);
  2986. SERIAL_PROTOCOLLN("");
  2987. #if defined(X_MIN_PIN) && X_MIN_PIN > -1
  2988. SERIAL_PROTOCOLRPGM(MSG_X_MIN);
  2989. if(READ(X_MIN_PIN)^X_MIN_ENDSTOP_INVERTING){
  2990. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  2991. }else{
  2992. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  2993. }
  2994. SERIAL_PROTOCOLLN("");
  2995. #endif
  2996. #if defined(X_MAX_PIN) && X_MAX_PIN > -1
  2997. SERIAL_PROTOCOLRPGM(MSG_X_MAX);
  2998. if(READ(X_MAX_PIN)^X_MAX_ENDSTOP_INVERTING){
  2999. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  3000. }else{
  3001. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  3002. }
  3003. SERIAL_PROTOCOLLN("");
  3004. #endif
  3005. #if defined(Y_MIN_PIN) && Y_MIN_PIN > -1
  3006. SERIAL_PROTOCOLRPGM(MSG_Y_MIN);
  3007. if(READ(Y_MIN_PIN)^Y_MIN_ENDSTOP_INVERTING){
  3008. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  3009. }else{
  3010. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  3011. }
  3012. SERIAL_PROTOCOLLN("");
  3013. #endif
  3014. #if defined(Y_MAX_PIN) && Y_MAX_PIN > -1
  3015. SERIAL_PROTOCOLRPGM(MSG_Y_MAX);
  3016. if(READ(Y_MAX_PIN)^Y_MAX_ENDSTOP_INVERTING){
  3017. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  3018. }else{
  3019. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  3020. }
  3021. SERIAL_PROTOCOLLN("");
  3022. #endif
  3023. #if defined(Z_MIN_PIN) && Z_MIN_PIN > -1
  3024. SERIAL_PROTOCOLRPGM(MSG_Z_MIN);
  3025. if(READ(Z_MIN_PIN)^Z_MIN_ENDSTOP_INVERTING){
  3026. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  3027. }else{
  3028. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  3029. }
  3030. SERIAL_PROTOCOLLN("");
  3031. #endif
  3032. #if defined(Z_MAX_PIN) && Z_MAX_PIN > -1
  3033. SERIAL_PROTOCOLRPGM(MSG_Z_MAX);
  3034. if(READ(Z_MAX_PIN)^Z_MAX_ENDSTOP_INVERTING){
  3035. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  3036. }else{
  3037. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  3038. }
  3039. SERIAL_PROTOCOLLN("");
  3040. #endif
  3041. break;
  3042. //TODO: update for all axis, use for loop
  3043. #ifdef BLINKM
  3044. case 150: // M150
  3045. {
  3046. byte red;
  3047. byte grn;
  3048. byte blu;
  3049. if(code_seen('R')) red = code_value();
  3050. if(code_seen('U')) grn = code_value();
  3051. if(code_seen('B')) blu = code_value();
  3052. SendColors(red,grn,blu);
  3053. }
  3054. break;
  3055. #endif //BLINKM
  3056. case 200: // M200 D<millimeters> set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).
  3057. {
  3058. tmp_extruder = active_extruder;
  3059. if(code_seen('T')) {
  3060. tmp_extruder = code_value();
  3061. if(tmp_extruder >= EXTRUDERS) {
  3062. SERIAL_ECHO_START;
  3063. SERIAL_ECHO(MSG_M200_INVALID_EXTRUDER);
  3064. break;
  3065. }
  3066. }
  3067. float area = .0;
  3068. if(code_seen('D')) {
  3069. float diameter = (float)code_value();
  3070. if (diameter == 0.0) {
  3071. // setting any extruder filament size disables volumetric on the assumption that
  3072. // slicers either generate in extruder values as cubic mm or as as filament feeds
  3073. // for all extruders
  3074. volumetric_enabled = false;
  3075. } else {
  3076. filament_size[tmp_extruder] = (float)code_value();
  3077. // make sure all extruders have some sane value for the filament size
  3078. filament_size[0] = (filament_size[0] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : filament_size[0]);
  3079. #if EXTRUDERS > 1
  3080. filament_size[1] = (filament_size[1] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : filament_size[1]);
  3081. #if EXTRUDERS > 2
  3082. filament_size[2] = (filament_size[2] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : filament_size[2]);
  3083. #endif
  3084. #endif
  3085. volumetric_enabled = true;
  3086. }
  3087. } else {
  3088. //reserved for setting filament diameter via UFID or filament measuring device
  3089. break;
  3090. }
  3091. calculate_volumetric_multipliers();
  3092. }
  3093. break;
  3094. case 201: // M201
  3095. for(int8_t i=0; i < NUM_AXIS; i++)
  3096. {
  3097. if(code_seen(axis_codes[i]))
  3098. {
  3099. max_acceleration_units_per_sq_second[i] = code_value();
  3100. }
  3101. }
  3102. // 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)
  3103. reset_acceleration_rates();
  3104. break;
  3105. #if 0 // Not used for Sprinter/grbl gen6
  3106. case 202: // M202
  3107. for(int8_t i=0; i < NUM_AXIS; i++) {
  3108. if(code_seen(axis_codes[i])) axis_travel_steps_per_sqr_second[i] = code_value() * axis_steps_per_unit[i];
  3109. }
  3110. break;
  3111. #endif
  3112. case 203: // M203 max feedrate mm/sec
  3113. for(int8_t i=0; i < NUM_AXIS; i++) {
  3114. if(code_seen(axis_codes[i])) max_feedrate[i] = code_value();
  3115. }
  3116. break;
  3117. case 204: // M204 acclereration S normal moves T filmanent only moves
  3118. {
  3119. if(code_seen('S')) acceleration = code_value() ;
  3120. if(code_seen('T')) retract_acceleration = code_value() ;
  3121. }
  3122. break;
  3123. 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
  3124. {
  3125. if(code_seen('S')) minimumfeedrate = code_value();
  3126. if(code_seen('T')) mintravelfeedrate = code_value();
  3127. if(code_seen('B')) minsegmenttime = code_value() ;
  3128. if(code_seen('X')) max_xy_jerk = code_value() ;
  3129. if(code_seen('Z')) max_z_jerk = code_value() ;
  3130. if(code_seen('E')) max_e_jerk = code_value() ;
  3131. }
  3132. break;
  3133. case 206: // M206 additional homing offset
  3134. for(int8_t i=0; i < 3; i++)
  3135. {
  3136. if(code_seen(axis_codes[i])) add_homing[i] = code_value();
  3137. }
  3138. break;
  3139. #ifdef FWRETRACT
  3140. case 207: //M207 - set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop]
  3141. {
  3142. if(code_seen('S'))
  3143. {
  3144. retract_length = code_value() ;
  3145. }
  3146. if(code_seen('F'))
  3147. {
  3148. retract_feedrate = code_value()/60 ;
  3149. }
  3150. if(code_seen('Z'))
  3151. {
  3152. retract_zlift = code_value() ;
  3153. }
  3154. }break;
  3155. case 208: // M208 - set retract recover length S[positive mm surplus to the M207 S*] F[feedrate mm/min]
  3156. {
  3157. if(code_seen('S'))
  3158. {
  3159. retract_recover_length = code_value() ;
  3160. }
  3161. if(code_seen('F'))
  3162. {
  3163. retract_recover_feedrate = code_value()/60 ;
  3164. }
  3165. }break;
  3166. 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.
  3167. {
  3168. if(code_seen('S'))
  3169. {
  3170. int t= code_value() ;
  3171. switch(t)
  3172. {
  3173. case 0:
  3174. {
  3175. autoretract_enabled=false;
  3176. retracted[0]=false;
  3177. #if EXTRUDERS > 1
  3178. retracted[1]=false;
  3179. #endif
  3180. #if EXTRUDERS > 2
  3181. retracted[2]=false;
  3182. #endif
  3183. }break;
  3184. case 1:
  3185. {
  3186. autoretract_enabled=true;
  3187. retracted[0]=false;
  3188. #if EXTRUDERS > 1
  3189. retracted[1]=false;
  3190. #endif
  3191. #if EXTRUDERS > 2
  3192. retracted[2]=false;
  3193. #endif
  3194. }break;
  3195. default:
  3196. SERIAL_ECHO_START;
  3197. SERIAL_ECHORPGM(MSG_UNKNOWN_COMMAND);
  3198. SERIAL_ECHO(CMDBUFFER_CURRENT_STRING);
  3199. SERIAL_ECHOLNPGM("\"");
  3200. }
  3201. }
  3202. }break;
  3203. #endif // FWRETRACT
  3204. #if EXTRUDERS > 1
  3205. case 218: // M218 - set hotend offset (in mm), T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  3206. {
  3207. if(setTargetedHotend(218)){
  3208. break;
  3209. }
  3210. if(code_seen('X'))
  3211. {
  3212. extruder_offset[X_AXIS][tmp_extruder] = code_value();
  3213. }
  3214. if(code_seen('Y'))
  3215. {
  3216. extruder_offset[Y_AXIS][tmp_extruder] = code_value();
  3217. }
  3218. #ifdef DUAL_X_CARRIAGE
  3219. if(code_seen('Z'))
  3220. {
  3221. extruder_offset[Z_AXIS][tmp_extruder] = code_value();
  3222. }
  3223. #endif
  3224. SERIAL_ECHO_START;
  3225. SERIAL_ECHORPGM(MSG_HOTEND_OFFSET);
  3226. for(tmp_extruder = 0; tmp_extruder < EXTRUDERS; tmp_extruder++)
  3227. {
  3228. SERIAL_ECHO(" ");
  3229. SERIAL_ECHO(extruder_offset[X_AXIS][tmp_extruder]);
  3230. SERIAL_ECHO(",");
  3231. SERIAL_ECHO(extruder_offset[Y_AXIS][tmp_extruder]);
  3232. #ifdef DUAL_X_CARRIAGE
  3233. SERIAL_ECHO(",");
  3234. SERIAL_ECHO(extruder_offset[Z_AXIS][tmp_extruder]);
  3235. #endif
  3236. }
  3237. SERIAL_ECHOLN("");
  3238. }break;
  3239. #endif
  3240. case 220: // M220 S<factor in percent>- set speed factor override percentage
  3241. {
  3242. if(code_seen('S'))
  3243. {
  3244. feedmultiply = code_value() ;
  3245. }
  3246. }
  3247. break;
  3248. case 221: // M221 S<factor in percent>- set extrude factor override percentage
  3249. {
  3250. if(code_seen('S'))
  3251. {
  3252. int tmp_code = code_value();
  3253. if (code_seen('T'))
  3254. {
  3255. if(setTargetedHotend(221)){
  3256. break;
  3257. }
  3258. extruder_multiply[tmp_extruder] = tmp_code;
  3259. }
  3260. else
  3261. {
  3262. extrudemultiply = tmp_code ;
  3263. }
  3264. }
  3265. }
  3266. break;
  3267. case 226: // M226 P<pin number> S<pin state>- Wait until the specified pin reaches the state required
  3268. {
  3269. if(code_seen('P')){
  3270. int pin_number = code_value(); // pin number
  3271. int pin_state = -1; // required pin state - default is inverted
  3272. if(code_seen('S')) pin_state = code_value(); // required pin state
  3273. if(pin_state >= -1 && pin_state <= 1){
  3274. for(int8_t i = 0; i < (int8_t)(sizeof(sensitive_pins)/sizeof(int)); i++)
  3275. {
  3276. if (sensitive_pins[i] == pin_number)
  3277. {
  3278. pin_number = -1;
  3279. break;
  3280. }
  3281. }
  3282. if (pin_number > -1)
  3283. {
  3284. int target = LOW;
  3285. st_synchronize();
  3286. pinMode(pin_number, INPUT);
  3287. switch(pin_state){
  3288. case 1:
  3289. target = HIGH;
  3290. break;
  3291. case 0:
  3292. target = LOW;
  3293. break;
  3294. case -1:
  3295. target = !digitalRead(pin_number);
  3296. break;
  3297. }
  3298. while(digitalRead(pin_number) != target){
  3299. manage_heater();
  3300. manage_inactivity();
  3301. lcd_update();
  3302. }
  3303. }
  3304. }
  3305. }
  3306. }
  3307. break;
  3308. #if NUM_SERVOS > 0
  3309. case 280: // M280 - set servo position absolute. P: servo index, S: angle or microseconds
  3310. {
  3311. int servo_index = -1;
  3312. int servo_position = 0;
  3313. if (code_seen('P'))
  3314. servo_index = code_value();
  3315. if (code_seen('S')) {
  3316. servo_position = code_value();
  3317. if ((servo_index >= 0) && (servo_index < NUM_SERVOS)) {
  3318. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  3319. servos[servo_index].attach(0);
  3320. #endif
  3321. servos[servo_index].write(servo_position);
  3322. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  3323. delay(PROBE_SERVO_DEACTIVATION_DELAY);
  3324. servos[servo_index].detach();
  3325. #endif
  3326. }
  3327. else {
  3328. SERIAL_ECHO_START;
  3329. SERIAL_ECHO("Servo ");
  3330. SERIAL_ECHO(servo_index);
  3331. SERIAL_ECHOLN(" out of range");
  3332. }
  3333. }
  3334. else if (servo_index >= 0) {
  3335. SERIAL_PROTOCOL(MSG_OK);
  3336. SERIAL_PROTOCOL(" Servo ");
  3337. SERIAL_PROTOCOL(servo_index);
  3338. SERIAL_PROTOCOL(": ");
  3339. SERIAL_PROTOCOL(servos[servo_index].read());
  3340. SERIAL_PROTOCOLLN("");
  3341. }
  3342. }
  3343. break;
  3344. #endif // NUM_SERVOS > 0
  3345. #if (LARGE_FLASH == true && ( BEEPER > 0 || defined(ULTRALCD) || defined(LCD_USE_I2C_BUZZER)))
  3346. case 300: // M300
  3347. {
  3348. int beepS = code_seen('S') ? code_value() : 110;
  3349. int beepP = code_seen('P') ? code_value() : 1000;
  3350. if (beepS > 0)
  3351. {
  3352. #if BEEPER > 0
  3353. tone(BEEPER, beepS);
  3354. delay(beepP);
  3355. noTone(BEEPER);
  3356. #elif defined(ULTRALCD)
  3357. lcd_buzz(beepS, beepP);
  3358. #elif defined(LCD_USE_I2C_BUZZER)
  3359. lcd_buzz(beepP, beepS);
  3360. #endif
  3361. }
  3362. else
  3363. {
  3364. delay(beepP);
  3365. }
  3366. }
  3367. break;
  3368. #endif // M300
  3369. #ifdef PIDTEMP
  3370. case 301: // M301
  3371. {
  3372. if(code_seen('P')) Kp = code_value();
  3373. if(code_seen('I')) Ki = scalePID_i(code_value());
  3374. if(code_seen('D')) Kd = scalePID_d(code_value());
  3375. #ifdef PID_ADD_EXTRUSION_RATE
  3376. if(code_seen('C')) Kc = code_value();
  3377. #endif
  3378. updatePID();
  3379. SERIAL_PROTOCOL(MSG_OK);
  3380. SERIAL_PROTOCOL(" p:");
  3381. SERIAL_PROTOCOL(Kp);
  3382. SERIAL_PROTOCOL(" i:");
  3383. SERIAL_PROTOCOL(unscalePID_i(Ki));
  3384. SERIAL_PROTOCOL(" d:");
  3385. SERIAL_PROTOCOL(unscalePID_d(Kd));
  3386. #ifdef PID_ADD_EXTRUSION_RATE
  3387. SERIAL_PROTOCOL(" c:");
  3388. //Kc does not have scaling applied above, or in resetting defaults
  3389. SERIAL_PROTOCOL(Kc);
  3390. #endif
  3391. SERIAL_PROTOCOLLN("");
  3392. }
  3393. break;
  3394. #endif //PIDTEMP
  3395. #ifdef PIDTEMPBED
  3396. case 304: // M304
  3397. {
  3398. if(code_seen('P')) bedKp = code_value();
  3399. if(code_seen('I')) bedKi = scalePID_i(code_value());
  3400. if(code_seen('D')) bedKd = scalePID_d(code_value());
  3401. updatePID();
  3402. SERIAL_PROTOCOL(MSG_OK);
  3403. SERIAL_PROTOCOL(" p:");
  3404. SERIAL_PROTOCOL(bedKp);
  3405. SERIAL_PROTOCOL(" i:");
  3406. SERIAL_PROTOCOL(unscalePID_i(bedKi));
  3407. SERIAL_PROTOCOL(" d:");
  3408. SERIAL_PROTOCOL(unscalePID_d(bedKd));
  3409. SERIAL_PROTOCOLLN("");
  3410. }
  3411. break;
  3412. #endif //PIDTEMP
  3413. case 240: // M240 Triggers a camera by emulating a Canon RC-1 : http://www.doc-diy.net/photo/rc-1_hacked/
  3414. {
  3415. #ifdef CHDK
  3416. SET_OUTPUT(CHDK);
  3417. WRITE(CHDK, HIGH);
  3418. chdkHigh = millis();
  3419. chdkActive = true;
  3420. #else
  3421. #if defined(PHOTOGRAPH_PIN) && PHOTOGRAPH_PIN > -1
  3422. const uint8_t NUM_PULSES=16;
  3423. const float PULSE_LENGTH=0.01524;
  3424. for(int i=0; i < NUM_PULSES; i++) {
  3425. WRITE(PHOTOGRAPH_PIN, HIGH);
  3426. _delay_ms(PULSE_LENGTH);
  3427. WRITE(PHOTOGRAPH_PIN, LOW);
  3428. _delay_ms(PULSE_LENGTH);
  3429. }
  3430. delay(7.33);
  3431. for(int i=0; i < NUM_PULSES; i++) {
  3432. WRITE(PHOTOGRAPH_PIN, HIGH);
  3433. _delay_ms(PULSE_LENGTH);
  3434. WRITE(PHOTOGRAPH_PIN, LOW);
  3435. _delay_ms(PULSE_LENGTH);
  3436. }
  3437. #endif
  3438. #endif //chdk end if
  3439. }
  3440. break;
  3441. #ifdef DOGLCD
  3442. case 250: // M250 Set LCD contrast value: C<value> (value 0..63)
  3443. {
  3444. if (code_seen('C')) {
  3445. lcd_setcontrast( ((int)code_value())&63 );
  3446. }
  3447. SERIAL_PROTOCOLPGM("lcd contrast value: ");
  3448. SERIAL_PROTOCOL(lcd_contrast);
  3449. SERIAL_PROTOCOLLN("");
  3450. }
  3451. break;
  3452. #endif
  3453. #ifdef PREVENT_DANGEROUS_EXTRUDE
  3454. case 302: // allow cold extrudes, or set the minimum extrude temperature
  3455. {
  3456. float temp = .0;
  3457. if (code_seen('S')) temp=code_value();
  3458. set_extrude_min_temp(temp);
  3459. }
  3460. break;
  3461. #endif
  3462. case 303: // M303 PID autotune
  3463. {
  3464. float temp = 150.0;
  3465. int e=0;
  3466. int c=5;
  3467. if (code_seen('E')) e=code_value();
  3468. if (e<0)
  3469. temp=70;
  3470. if (code_seen('S')) temp=code_value();
  3471. if (code_seen('C')) c=code_value();
  3472. PID_autotune(temp, e, c);
  3473. }
  3474. break;
  3475. case 400: // M400 finish all moves
  3476. {
  3477. st_synchronize();
  3478. }
  3479. break;
  3480. #ifdef FILAMENT_SENSOR
  3481. case 404: //M404 Enter the nominal filament width (3mm, 1.75mm ) N<3.0> or display nominal filament width
  3482. {
  3483. #if (FILWIDTH_PIN > -1)
  3484. if(code_seen('N')) filament_width_nominal=code_value();
  3485. else{
  3486. SERIAL_PROTOCOLPGM("Filament dia (nominal mm):");
  3487. SERIAL_PROTOCOLLN(filament_width_nominal);
  3488. }
  3489. #endif
  3490. }
  3491. break;
  3492. case 405: //M405 Turn on filament sensor for control
  3493. {
  3494. if(code_seen('D')) meas_delay_cm=code_value();
  3495. if(meas_delay_cm> MAX_MEASUREMENT_DELAY)
  3496. meas_delay_cm = MAX_MEASUREMENT_DELAY;
  3497. if(delay_index2 == -1) //initialize the ring buffer if it has not been done since startup
  3498. {
  3499. int temp_ratio = widthFil_to_size_ratio();
  3500. for (delay_index1=0; delay_index1<(MAX_MEASUREMENT_DELAY+1); ++delay_index1 ){
  3501. measurement_delay[delay_index1]=temp_ratio-100; //subtract 100 to scale within a signed byte
  3502. }
  3503. delay_index1=0;
  3504. delay_index2=0;
  3505. }
  3506. filament_sensor = true ;
  3507. //SERIAL_PROTOCOLPGM("Filament dia (measured mm):");
  3508. //SERIAL_PROTOCOL(filament_width_meas);
  3509. //SERIAL_PROTOCOLPGM("Extrusion ratio(%):");
  3510. //SERIAL_PROTOCOL(extrudemultiply);
  3511. }
  3512. break;
  3513. case 406: //M406 Turn off filament sensor for control
  3514. {
  3515. filament_sensor = false ;
  3516. }
  3517. break;
  3518. case 407: //M407 Display measured filament diameter
  3519. {
  3520. SERIAL_PROTOCOLPGM("Filament dia (measured mm):");
  3521. SERIAL_PROTOCOLLN(filament_width_meas);
  3522. }
  3523. break;
  3524. #endif
  3525. case 500: // M500 Store settings in EEPROM
  3526. {
  3527. Config_StoreSettings();
  3528. }
  3529. break;
  3530. case 501: // M501 Read settings from EEPROM
  3531. {
  3532. Config_RetrieveSettings();
  3533. }
  3534. break;
  3535. case 502: // M502 Revert to default settings
  3536. {
  3537. Config_ResetDefault();
  3538. }
  3539. break;
  3540. case 503: // M503 print settings currently in memory
  3541. {
  3542. Config_PrintSettings();
  3543. }
  3544. break;
  3545. case 509: //M509 Force language selection
  3546. {
  3547. lcd_force_language_selection();
  3548. SERIAL_ECHO_START;
  3549. SERIAL_PROTOCOLPGM(("LANG SEL FORCED"));
  3550. }
  3551. break;
  3552. #ifdef ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED
  3553. case 540:
  3554. {
  3555. if(code_seen('S')) abort_on_endstop_hit = code_value() > 0;
  3556. }
  3557. break;
  3558. #endif
  3559. #ifdef CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  3560. case CUSTOM_M_CODE_SET_Z_PROBE_OFFSET:
  3561. {
  3562. float value;
  3563. if (code_seen('Z'))
  3564. {
  3565. value = code_value();
  3566. if ((Z_PROBE_OFFSET_RANGE_MIN <= value) && (value <= Z_PROBE_OFFSET_RANGE_MAX))
  3567. {
  3568. zprobe_zoffset = -value; // compare w/ line 278 of ConfigurationStore.cpp
  3569. SERIAL_ECHO_START;
  3570. SERIAL_ECHOLNRPGM(CAT4(MSG_ZPROBE_ZOFFSET, " ", MSG_OK,PSTR("")));
  3571. SERIAL_PROTOCOLLN("");
  3572. }
  3573. else
  3574. {
  3575. SERIAL_ECHO_START;
  3576. SERIAL_ECHORPGM(MSG_ZPROBE_ZOFFSET);
  3577. SERIAL_ECHORPGM(MSG_Z_MIN);
  3578. SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MIN);
  3579. SERIAL_ECHORPGM(MSG_Z_MAX);
  3580. SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MAX);
  3581. SERIAL_PROTOCOLLN("");
  3582. }
  3583. }
  3584. else
  3585. {
  3586. SERIAL_ECHO_START;
  3587. SERIAL_ECHOLNRPGM(CAT2(MSG_ZPROBE_ZOFFSET, PSTR(" : ")));
  3588. SERIAL_ECHO(-zprobe_zoffset);
  3589. SERIAL_PROTOCOLLN("");
  3590. }
  3591. break;
  3592. }
  3593. #endif // CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  3594. #ifdef FILAMENTCHANGEENABLE
  3595. case 600: //Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  3596. {
  3597. st_synchronize();
  3598. feedmultiplyBckp=feedmultiply;
  3599. int8_t TooLowZ = 0;
  3600. float target[4];
  3601. float lastpos[4];
  3602. target[X_AXIS]=current_position[X_AXIS];
  3603. target[Y_AXIS]=current_position[Y_AXIS];
  3604. target[Z_AXIS]=current_position[Z_AXIS];
  3605. target[E_AXIS]=current_position[E_AXIS];
  3606. lastpos[X_AXIS]=current_position[X_AXIS];
  3607. lastpos[Y_AXIS]=current_position[Y_AXIS];
  3608. lastpos[Z_AXIS]=current_position[Z_AXIS];
  3609. lastpos[E_AXIS]=current_position[E_AXIS];
  3610. //Restract extruder
  3611. if(code_seen('E'))
  3612. {
  3613. target[E_AXIS]+= code_value();
  3614. }
  3615. else
  3616. {
  3617. #ifdef FILAMENTCHANGE_FIRSTRETRACT
  3618. target[E_AXIS]+= FILAMENTCHANGE_FIRSTRETRACT ;
  3619. #endif
  3620. }
  3621. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], FILAMENTCHANGE_RFEED, active_extruder);
  3622. //Lift Z
  3623. if(code_seen('Z'))
  3624. {
  3625. target[Z_AXIS]+= code_value();
  3626. }
  3627. else
  3628. {
  3629. #ifdef FILAMENTCHANGE_ZADD
  3630. target[Z_AXIS]+= FILAMENTCHANGE_ZADD ;
  3631. if(target[Z_AXIS] < 10){
  3632. target[Z_AXIS]+= 10 ;
  3633. TooLowZ = 1;
  3634. }else{
  3635. TooLowZ = 0;
  3636. }
  3637. #endif
  3638. }
  3639. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], FILAMENTCHANGE_ZFEED, active_extruder);
  3640. //Move XY to side
  3641. if(code_seen('X'))
  3642. {
  3643. target[X_AXIS]+= code_value();
  3644. }
  3645. else
  3646. {
  3647. #ifdef FILAMENTCHANGE_XPOS
  3648. target[X_AXIS]= FILAMENTCHANGE_XPOS ;
  3649. #endif
  3650. }
  3651. if(code_seen('Y'))
  3652. {
  3653. target[Y_AXIS]= code_value();
  3654. }
  3655. else
  3656. {
  3657. #ifdef FILAMENTCHANGE_YPOS
  3658. target[Y_AXIS]= FILAMENTCHANGE_YPOS ;
  3659. #endif
  3660. }
  3661. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], FILAMENTCHANGE_XYFEED, active_extruder);
  3662. // Unload filament
  3663. if(code_seen('L'))
  3664. {
  3665. target[E_AXIS]+= code_value();
  3666. }
  3667. else
  3668. {
  3669. #ifdef FILAMENTCHANGE_FINALRETRACT
  3670. target[E_AXIS]+= FILAMENTCHANGE_FINALRETRACT ;
  3671. #endif
  3672. }
  3673. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], FILAMENTCHANGE_RFEED, active_extruder);
  3674. //finish moves
  3675. st_synchronize();
  3676. //disable extruder steppers so filament can be removed
  3677. disable_e0();
  3678. disable_e1();
  3679. disable_e2();
  3680. delay(100);
  3681. //Wait for user to insert filament
  3682. uint8_t cnt=0;
  3683. int counterBeep = 0;
  3684. lcd_wait_interact();
  3685. while(!lcd_clicked()){
  3686. cnt++;
  3687. manage_heater();
  3688. manage_inactivity(true);
  3689. if(cnt==0)
  3690. {
  3691. #if BEEPER > 0
  3692. if (counterBeep== 500){
  3693. counterBeep = 0;
  3694. }
  3695. SET_OUTPUT(BEEPER);
  3696. if (counterBeep== 0){
  3697. WRITE(BEEPER,HIGH);
  3698. }
  3699. if (counterBeep== 20){
  3700. WRITE(BEEPER,LOW);
  3701. }
  3702. counterBeep++;
  3703. #else
  3704. #if !defined(LCD_FEEDBACK_FREQUENCY_HZ) || !defined(LCD_FEEDBACK_FREQUENCY_DURATION_MS)
  3705. lcd_buzz(1000/6,100);
  3706. #else
  3707. lcd_buzz(LCD_FEEDBACK_FREQUENCY_DURATION_MS,LCD_FEEDBACK_FREQUENCY_HZ);
  3708. #endif
  3709. #endif
  3710. }
  3711. }
  3712. //Filament inserted
  3713. WRITE(BEEPER,LOW);
  3714. //Feed the filament to the end of nozzle quickly
  3715. target[E_AXIS]+= FILAMENTCHANGE_FIRSTFEED ;
  3716. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], FILAMENTCHANGE_EFEED, active_extruder);
  3717. //Extrude some filament
  3718. target[E_AXIS]+= FILAMENTCHANGE_FINALFEED ;
  3719. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], FILAMENTCHANGE_EXFEED, active_extruder);
  3720. //Wait for user to check the state
  3721. lcd_change_fil_state = 0;
  3722. lcd_loading_filament();
  3723. while ((lcd_change_fil_state == 0)||(lcd_change_fil_state != 1)){
  3724. lcd_change_fil_state = 0;
  3725. lcd_alright();
  3726. switch(lcd_change_fil_state){
  3727. // Filament failed to load so load it again
  3728. case 2:
  3729. target[E_AXIS]+= FILAMENTCHANGE_FIRSTFEED ;
  3730. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], FILAMENTCHANGE_EFEED, active_extruder);
  3731. target[E_AXIS]+= FILAMENTCHANGE_FINALFEED ;
  3732. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], FILAMENTCHANGE_EXFEED, active_extruder);
  3733. lcd_loading_filament();
  3734. break;
  3735. // Filament loaded properly but color is not clear
  3736. case 3:
  3737. target[E_AXIS]+= FILAMENTCHANGE_FINALFEED ;
  3738. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 2, active_extruder);
  3739. lcd_loading_color();
  3740. break;
  3741. // Everything good
  3742. default:
  3743. lcd_change_success();
  3744. break;
  3745. }
  3746. }
  3747. //Not let's go back to print
  3748. //Feed a little of filament to stabilize pressure
  3749. target[E_AXIS]+= FILAMENTCHANGE_RECFEED;
  3750. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], FILAMENTCHANGE_EXFEED, active_extruder);
  3751. //Retract
  3752. target[E_AXIS]+= FILAMENTCHANGE_FIRSTRETRACT;
  3753. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], FILAMENTCHANGE_RFEED, active_extruder);
  3754. //plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 70, active_extruder); //should do nothing
  3755. //Move XY back
  3756. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], target[Z_AXIS], target[E_AXIS], FILAMENTCHANGE_XYFEED, active_extruder);
  3757. //Move Z back
  3758. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], lastpos[Z_AXIS], target[E_AXIS], FILAMENTCHANGE_ZFEED, active_extruder);
  3759. target[E_AXIS]= target[E_AXIS] - FILAMENTCHANGE_FIRSTRETRACT;
  3760. //Unretract
  3761. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], lastpos[Z_AXIS], target[E_AXIS], FILAMENTCHANGE_RFEED, active_extruder);
  3762. //Set E position to original
  3763. plan_set_e_position(lastpos[E_AXIS]);
  3764. //Recover feed rate
  3765. feedmultiply=feedmultiplyBckp;
  3766. char cmd[9];
  3767. sprintf_P(cmd, PSTR("M220 S%i"), feedmultiplyBckp);
  3768. enquecommand(cmd);
  3769. }
  3770. break;
  3771. #endif //FILAMENTCHANGEENABLE
  3772. #ifdef DUAL_X_CARRIAGE
  3773. case 605: // Set dual x-carriage movement mode:
  3774. // M605 S0: Full control mode. The slicer has full control over x-carriage movement
  3775. // M605 S1: Auto-park mode. The inactive head will auto park/unpark without slicer involvement
  3776. // M605 S2 [Xnnn] [Rmmm]: Duplication mode. The second extruder will duplicate the first with nnn
  3777. // millimeters x-offset and an optional differential hotend temperature of
  3778. // mmm degrees. E.g., with "M605 S2 X100 R2" the second extruder will duplicate
  3779. // the first with a spacing of 100mm in the x direction and 2 degrees hotter.
  3780. //
  3781. // Note: the X axis should be homed after changing dual x-carriage mode.
  3782. {
  3783. st_synchronize();
  3784. if (code_seen('S'))
  3785. dual_x_carriage_mode = code_value();
  3786. if (dual_x_carriage_mode == DXC_DUPLICATION_MODE)
  3787. {
  3788. if (code_seen('X'))
  3789. duplicate_extruder_x_offset = max(code_value(),X2_MIN_POS - x_home_pos(0));
  3790. if (code_seen('R'))
  3791. duplicate_extruder_temp_offset = code_value();
  3792. SERIAL_ECHO_START;
  3793. SERIAL_ECHORPGM(MSG_HOTEND_OFFSET);
  3794. SERIAL_ECHO(" ");
  3795. SERIAL_ECHO(extruder_offset[X_AXIS][0]);
  3796. SERIAL_ECHO(",");
  3797. SERIAL_ECHO(extruder_offset[Y_AXIS][0]);
  3798. SERIAL_ECHO(" ");
  3799. SERIAL_ECHO(duplicate_extruder_x_offset);
  3800. SERIAL_ECHO(",");
  3801. SERIAL_ECHOLN(extruder_offset[Y_AXIS][1]);
  3802. }
  3803. else if (dual_x_carriage_mode != DXC_FULL_CONTROL_MODE && dual_x_carriage_mode != DXC_AUTO_PARK_MODE)
  3804. {
  3805. dual_x_carriage_mode = DEFAULT_DUAL_X_CARRIAGE_MODE;
  3806. }
  3807. active_extruder_parked = false;
  3808. extruder_duplication_enabled = false;
  3809. delayed_move_time = 0;
  3810. }
  3811. break;
  3812. #endif //DUAL_X_CARRIAGE
  3813. case 907: // M907 Set digital trimpot motor current using axis codes.
  3814. {
  3815. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  3816. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) digipot_current(i,code_value());
  3817. if(code_seen('B')) digipot_current(4,code_value());
  3818. if(code_seen('S')) for(int i=0;i<=4;i++) digipot_current(i,code_value());
  3819. #endif
  3820. #ifdef MOTOR_CURRENT_PWM_XY_PIN
  3821. if(code_seen('X')) digipot_current(0, code_value());
  3822. #endif
  3823. #ifdef MOTOR_CURRENT_PWM_Z_PIN
  3824. if(code_seen('Z')) digipot_current(1, code_value());
  3825. #endif
  3826. #ifdef MOTOR_CURRENT_PWM_E_PIN
  3827. if(code_seen('E')) digipot_current(2, code_value());
  3828. #endif
  3829. #ifdef DIGIPOT_I2C
  3830. // this one uses actual amps in floating point
  3831. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) digipot_i2c_set_current(i, code_value());
  3832. // for each additional extruder (named B,C,D,E..., channels 4,5,6,7...)
  3833. 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());
  3834. #endif
  3835. }
  3836. break;
  3837. case 908: // M908 Control digital trimpot directly.
  3838. {
  3839. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  3840. uint8_t channel,current;
  3841. if(code_seen('P')) channel=code_value();
  3842. if(code_seen('S')) current=code_value();
  3843. digitalPotWrite(channel, current);
  3844. #endif
  3845. }
  3846. break;
  3847. case 350: // M350 Set microstepping mode. Warning: Steps per unit remains unchanged. S code sets stepping mode for all drivers.
  3848. {
  3849. #if defined(X_MS1_PIN) && X_MS1_PIN > -1
  3850. if(code_seen('S')) for(int i=0;i<=4;i++) microstep_mode(i,code_value());
  3851. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_mode(i,(uint8_t)code_value());
  3852. if(code_seen('B')) microstep_mode(4,code_value());
  3853. microstep_readings();
  3854. #endif
  3855. }
  3856. break;
  3857. case 351: // M351 Toggle MS1 MS2 pins directly, S# determines MS1 or MS2, X# sets the pin high/low.
  3858. {
  3859. #if defined(X_MS1_PIN) && X_MS1_PIN > -1
  3860. if(code_seen('S')) switch((int)code_value())
  3861. {
  3862. case 1:
  3863. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_ms(i,code_value(),-1);
  3864. if(code_seen('B')) microstep_ms(4,code_value(),-1);
  3865. break;
  3866. case 2:
  3867. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_ms(i,-1,code_value());
  3868. if(code_seen('B')) microstep_ms(4,-1,code_value());
  3869. break;
  3870. }
  3871. microstep_readings();
  3872. #endif
  3873. }
  3874. break;
  3875. case 999: // M999: Restart after being stopped
  3876. Stopped = false;
  3877. lcd_reset_alert_level();
  3878. gcode_LastN = Stopped_gcode_LastN;
  3879. FlushSerialRequestResend();
  3880. break;
  3881. }
  3882. } // end if(code_seen('M')) (end of M codes)
  3883. else if(code_seen('T'))
  3884. {
  3885. tmp_extruder = code_value();
  3886. if(tmp_extruder >= EXTRUDERS) {
  3887. SERIAL_ECHO_START;
  3888. SERIAL_ECHO("T");
  3889. SERIAL_ECHO(tmp_extruder);
  3890. SERIAL_ECHOLN(MSG_INVALID_EXTRUDER);
  3891. }
  3892. else {
  3893. boolean make_move = false;
  3894. if(code_seen('F')) {
  3895. make_move = true;
  3896. next_feedrate = code_value();
  3897. if(next_feedrate > 0.0) {
  3898. feedrate = next_feedrate;
  3899. }
  3900. }
  3901. #if EXTRUDERS > 1
  3902. if(tmp_extruder != active_extruder) {
  3903. // Save current position to return to after applying extruder offset
  3904. memcpy(destination, current_position, sizeof(destination));
  3905. #ifdef DUAL_X_CARRIAGE
  3906. if (dual_x_carriage_mode == DXC_AUTO_PARK_MODE && Stopped == false &&
  3907. (delayed_move_time != 0 || current_position[X_AXIS] != x_home_pos(active_extruder)))
  3908. {
  3909. // Park old head: 1) raise 2) move to park position 3) lower
  3910. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS] + TOOLCHANGE_PARK_ZLIFT,
  3911. current_position[E_AXIS], max_feedrate[Z_AXIS], active_extruder);
  3912. plan_buffer_line(x_home_pos(active_extruder), current_position[Y_AXIS], current_position[Z_AXIS] + TOOLCHANGE_PARK_ZLIFT,
  3913. current_position[E_AXIS], max_feedrate[X_AXIS], active_extruder);
  3914. plan_buffer_line(x_home_pos(active_extruder), current_position[Y_AXIS], current_position[Z_AXIS],
  3915. current_position[E_AXIS], max_feedrate[Z_AXIS], active_extruder);
  3916. st_synchronize();
  3917. }
  3918. // apply Y & Z extruder offset (x offset is already used in determining home pos)
  3919. current_position[Y_AXIS] = current_position[Y_AXIS] -
  3920. extruder_offset[Y_AXIS][active_extruder] +
  3921. extruder_offset[Y_AXIS][tmp_extruder];
  3922. current_position[Z_AXIS] = current_position[Z_AXIS] -
  3923. extruder_offset[Z_AXIS][active_extruder] +
  3924. extruder_offset[Z_AXIS][tmp_extruder];
  3925. active_extruder = tmp_extruder;
  3926. // This function resets the max/min values - the current position may be overwritten below.
  3927. axis_is_at_home(X_AXIS);
  3928. if (dual_x_carriage_mode == DXC_FULL_CONTROL_MODE)
  3929. {
  3930. current_position[X_AXIS] = inactive_extruder_x_pos;
  3931. inactive_extruder_x_pos = destination[X_AXIS];
  3932. }
  3933. else if (dual_x_carriage_mode == DXC_DUPLICATION_MODE)
  3934. {
  3935. active_extruder_parked = (active_extruder == 0); // this triggers the second extruder to move into the duplication position
  3936. if (active_extruder == 0 || active_extruder_parked)
  3937. current_position[X_AXIS] = inactive_extruder_x_pos;
  3938. else
  3939. current_position[X_AXIS] = destination[X_AXIS] + duplicate_extruder_x_offset;
  3940. inactive_extruder_x_pos = destination[X_AXIS];
  3941. extruder_duplication_enabled = false;
  3942. }
  3943. else
  3944. {
  3945. // record raised toolhead position for use by unpark
  3946. memcpy(raised_parked_position, current_position, sizeof(raised_parked_position));
  3947. raised_parked_position[Z_AXIS] += TOOLCHANGE_UNPARK_ZLIFT;
  3948. active_extruder_parked = true;
  3949. delayed_move_time = 0;
  3950. }
  3951. #else
  3952. // Offset extruder (only by XY)
  3953. int i;
  3954. for(i = 0; i < 2; i++) {
  3955. current_position[i] = current_position[i] -
  3956. extruder_offset[i][active_extruder] +
  3957. extruder_offset[i][tmp_extruder];
  3958. }
  3959. // Set the new active extruder and position
  3960. active_extruder = tmp_extruder;
  3961. #endif //else DUAL_X_CARRIAGE
  3962. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  3963. // Move to the old position if 'F' was in the parameters
  3964. if(make_move && Stopped == false) {
  3965. prepare_move();
  3966. }
  3967. }
  3968. #endif
  3969. SERIAL_ECHO_START;
  3970. SERIAL_ECHO(MSG_ACTIVE_EXTRUDER);
  3971. SERIAL_PROTOCOLLN((int)active_extruder);
  3972. }
  3973. } // end if(code_seen('T')) (end of T codes)
  3974. else
  3975. {
  3976. SERIAL_ECHO_START;
  3977. SERIAL_ECHORPGM(MSG_UNKNOWN_COMMAND);
  3978. SERIAL_ECHO(CMDBUFFER_CURRENT_STRING);
  3979. SERIAL_ECHOLNPGM("\"");
  3980. }
  3981. ClearToSend();
  3982. }
  3983. void FlushSerialRequestResend()
  3984. {
  3985. //char cmdbuffer[bufindr][100]="Resend:";
  3986. MYSERIAL.flush();
  3987. SERIAL_PROTOCOLRPGM(MSG_RESEND);
  3988. SERIAL_PROTOCOLLN(gcode_LastN + 1);
  3989. ClearToSend();
  3990. }
  3991. // Confirm the execution of a command, if sent from a serial line.
  3992. // Execution of a command from a SD card will not be confirmed.
  3993. void ClearToSend()
  3994. {
  3995. previous_millis_cmd = millis();
  3996. if (CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB)
  3997. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  3998. }
  3999. void get_coordinates()
  4000. {
  4001. bool seen[4]={false,false,false,false};
  4002. for(int8_t i=0; i < NUM_AXIS; i++) {
  4003. if(code_seen(axis_codes[i]))
  4004. {
  4005. destination[i] = (float)code_value() + (axis_relative_modes[i] || relative_mode)*current_position[i];
  4006. seen[i]=true;
  4007. }
  4008. else destination[i] = current_position[i]; //Are these else lines really needed?
  4009. }
  4010. if(code_seen('F')) {
  4011. next_feedrate = code_value();
  4012. if(next_feedrate > 0.0) feedrate = next_feedrate;
  4013. }
  4014. }
  4015. void get_arc_coordinates()
  4016. {
  4017. #ifdef SF_ARC_FIX
  4018. bool relative_mode_backup = relative_mode;
  4019. relative_mode = true;
  4020. #endif
  4021. get_coordinates();
  4022. #ifdef SF_ARC_FIX
  4023. relative_mode=relative_mode_backup;
  4024. #endif
  4025. if(code_seen('I')) {
  4026. offset[0] = code_value();
  4027. }
  4028. else {
  4029. offset[0] = 0.0;
  4030. }
  4031. if(code_seen('J')) {
  4032. offset[1] = code_value();
  4033. }
  4034. else {
  4035. offset[1] = 0.0;
  4036. }
  4037. }
  4038. void clamp_to_software_endstops(float target[3])
  4039. {
  4040. if (min_software_endstops) {
  4041. if (target[X_AXIS] < min_pos[X_AXIS]) target[X_AXIS] = min_pos[X_AXIS];
  4042. if (target[Y_AXIS] < min_pos[Y_AXIS]) target[Y_AXIS] = min_pos[Y_AXIS];
  4043. float negative_z_offset = 0;
  4044. #ifdef ENABLE_AUTO_BED_LEVELING
  4045. if (Z_PROBE_OFFSET_FROM_EXTRUDER < 0) negative_z_offset = negative_z_offset + Z_PROBE_OFFSET_FROM_EXTRUDER;
  4046. if (add_homing[Z_AXIS] < 0) negative_z_offset = negative_z_offset + add_homing[Z_AXIS];
  4047. #endif
  4048. if (target[Z_AXIS] < min_pos[Z_AXIS]+negative_z_offset) target[Z_AXIS] = min_pos[Z_AXIS]+negative_z_offset;
  4049. }
  4050. if (max_software_endstops) {
  4051. if (target[X_AXIS] > max_pos[X_AXIS]) target[X_AXIS] = max_pos[X_AXIS];
  4052. if (target[Y_AXIS] > max_pos[Y_AXIS]) target[Y_AXIS] = max_pos[Y_AXIS];
  4053. if (target[Z_AXIS] > max_pos[Z_AXIS]) target[Z_AXIS] = max_pos[Z_AXIS];
  4054. }
  4055. }
  4056. #ifdef MESH_BED_LEVELING
  4057. void mesh_plan_buffer_line(const float &x, const float &y, const float &z, const float &e, const float &feed_rate, const uint8_t extruder) {
  4058. float dx = x - current_position[X_AXIS];
  4059. float dy = y - current_position[Y_AXIS];
  4060. float dz = z - current_position[Z_AXIS];
  4061. int n_segments = 0;
  4062. if (mbl.active) {
  4063. float len = abs(dx) + abs(dy) + abs(dz);
  4064. if (len > 0)
  4065. n_segments = int(floor(len / 30.f));
  4066. }
  4067. if (n_segments > 1) {
  4068. float de = e - current_position[E_AXIS];
  4069. for (int i = 1; i < n_segments; ++ i) {
  4070. float t = float(i) / float(n_segments);
  4071. plan_buffer_line(
  4072. current_position[X_AXIS] + t * dx,
  4073. current_position[Y_AXIS] + t * dy,
  4074. current_position[Z_AXIS] + t * dz,
  4075. current_position[E_AXIS] + t * de,
  4076. feed_rate, extruder);
  4077. }
  4078. }
  4079. // The rest of the path.
  4080. plan_buffer_line(x, y, z, e, feed_rate, extruder);
  4081. set_current_to_destination();
  4082. }
  4083. #endif // MESH_BED_LEVELING
  4084. void prepare_move()
  4085. {
  4086. clamp_to_software_endstops(destination);
  4087. previous_millis_cmd = millis();
  4088. #ifdef DUAL_X_CARRIAGE
  4089. if (active_extruder_parked)
  4090. {
  4091. if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && active_extruder == 0)
  4092. {
  4093. // move duplicate extruder into correct duplication position.
  4094. plan_set_position(inactive_extruder_x_pos, current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  4095. plan_buffer_line(current_position[X_AXIS] + duplicate_extruder_x_offset, current_position[Y_AXIS], current_position[Z_AXIS],
  4096. current_position[E_AXIS], max_feedrate[X_AXIS], 1);
  4097. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  4098. st_synchronize();
  4099. extruder_duplication_enabled = true;
  4100. active_extruder_parked = false;
  4101. }
  4102. else if (dual_x_carriage_mode == DXC_AUTO_PARK_MODE) // handle unparking of head
  4103. {
  4104. if (current_position[E_AXIS] == destination[E_AXIS])
  4105. {
  4106. // this is a travel move - skit it but keep track of current position (so that it can later
  4107. // be used as start of first non-travel move)
  4108. if (delayed_move_time != 0xFFFFFFFFUL)
  4109. {
  4110. memcpy(current_position, destination, sizeof(current_position));
  4111. if (destination[Z_AXIS] > raised_parked_position[Z_AXIS])
  4112. raised_parked_position[Z_AXIS] = destination[Z_AXIS];
  4113. delayed_move_time = millis();
  4114. return;
  4115. }
  4116. }
  4117. delayed_move_time = 0;
  4118. // unpark extruder: 1) raise, 2) move into starting XY position, 3) lower
  4119. 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);
  4120. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], raised_parked_position[Z_AXIS],
  4121. current_position[E_AXIS], min(max_feedrate[X_AXIS],max_feedrate[Y_AXIS]), active_extruder);
  4122. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS],
  4123. current_position[E_AXIS], max_feedrate[Z_AXIS], active_extruder);
  4124. active_extruder_parked = false;
  4125. }
  4126. }
  4127. #endif //DUAL_X_CARRIAGE
  4128. // Do not use feedmultiply for E or Z only moves
  4129. if( (current_position[X_AXIS] == destination [X_AXIS]) && (current_position[Y_AXIS] == destination [Y_AXIS])) {
  4130. #ifdef MESH_BED_LEVELING
  4131. mesh_plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  4132. #else
  4133. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  4134. #endif
  4135. }
  4136. else {
  4137. #ifdef MESH_BED_LEVELING
  4138. mesh_plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate*feedmultiply/60/100.0, active_extruder);
  4139. #else
  4140. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate*feedmultiply/60/100.0, active_extruder);
  4141. #endif
  4142. }
  4143. for(int8_t i=0; i < NUM_AXIS; i++) {
  4144. current_position[i] = destination[i];
  4145. }
  4146. }
  4147. void prepare_arc_move(char isclockwise) {
  4148. float r = hypot(offset[X_AXIS], offset[Y_AXIS]); // Compute arc radius for mc_arc
  4149. // Trace the arc
  4150. mc_arc(current_position, destination, offset, X_AXIS, Y_AXIS, Z_AXIS, feedrate*feedmultiply/60/100.0, r, isclockwise, active_extruder);
  4151. // As far as the parser is concerned, the position is now == target. In reality the
  4152. // motion control system might still be processing the action and the real tool position
  4153. // in any intermediate location.
  4154. for(int8_t i=0; i < NUM_AXIS; i++) {
  4155. current_position[i] = destination[i];
  4156. }
  4157. previous_millis_cmd = millis();
  4158. }
  4159. #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1
  4160. #if defined(FAN_PIN)
  4161. #if CONTROLLERFAN_PIN == FAN_PIN
  4162. #error "You cannot set CONTROLLERFAN_PIN equal to FAN_PIN"
  4163. #endif
  4164. #endif
  4165. unsigned long lastMotor = 0; //Save the time for when a motor was turned on last
  4166. unsigned long lastMotorCheck = 0;
  4167. void controllerFan()
  4168. {
  4169. if ((millis() - lastMotorCheck) >= 2500) //Not a time critical function, so we only check every 2500ms
  4170. {
  4171. lastMotorCheck = millis();
  4172. if(!READ(X_ENABLE_PIN) || !READ(Y_ENABLE_PIN) || !READ(Z_ENABLE_PIN) || (soft_pwm_bed > 0)
  4173. #if EXTRUDERS > 2
  4174. || !READ(E2_ENABLE_PIN)
  4175. #endif
  4176. #if EXTRUDER > 1
  4177. #if defined(X2_ENABLE_PIN) && X2_ENABLE_PIN > -1
  4178. || !READ(X2_ENABLE_PIN)
  4179. #endif
  4180. || !READ(E1_ENABLE_PIN)
  4181. #endif
  4182. || !READ(E0_ENABLE_PIN)) //If any of the drivers are enabled...
  4183. {
  4184. lastMotor = millis(); //... set time to NOW so the fan will turn on
  4185. }
  4186. if ((millis() - lastMotor) >= (CONTROLLERFAN_SECS*1000UL) || lastMotor == 0) //If the last time any driver was enabled, is longer since than CONTROLLERSEC...
  4187. {
  4188. digitalWrite(CONTROLLERFAN_PIN, 0);
  4189. analogWrite(CONTROLLERFAN_PIN, 0);
  4190. }
  4191. else
  4192. {
  4193. // allows digital or PWM fan output to be used (see M42 handling)
  4194. digitalWrite(CONTROLLERFAN_PIN, CONTROLLERFAN_SPEED);
  4195. analogWrite(CONTROLLERFAN_PIN, CONTROLLERFAN_SPEED);
  4196. }
  4197. }
  4198. }
  4199. #endif
  4200. #ifdef TEMP_STAT_LEDS
  4201. static bool blue_led = false;
  4202. static bool red_led = false;
  4203. static uint32_t stat_update = 0;
  4204. void handle_status_leds(void) {
  4205. float max_temp = 0.0;
  4206. if(millis() > stat_update) {
  4207. stat_update += 500; // Update every 0.5s
  4208. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  4209. max_temp = max(max_temp, degHotend(cur_extruder));
  4210. max_temp = max(max_temp, degTargetHotend(cur_extruder));
  4211. }
  4212. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  4213. max_temp = max(max_temp, degTargetBed());
  4214. max_temp = max(max_temp, degBed());
  4215. #endif
  4216. if((max_temp > 55.0) && (red_led == false)) {
  4217. digitalWrite(STAT_LED_RED, 1);
  4218. digitalWrite(STAT_LED_BLUE, 0);
  4219. red_led = true;
  4220. blue_led = false;
  4221. }
  4222. if((max_temp < 54.0) && (blue_led == false)) {
  4223. digitalWrite(STAT_LED_RED, 0);
  4224. digitalWrite(STAT_LED_BLUE, 1);
  4225. red_led = false;
  4226. blue_led = true;
  4227. }
  4228. }
  4229. }
  4230. #endif
  4231. void manage_inactivity(bool ignore_stepper_queue/*=false*/) //default argument set in Marlin.h
  4232. {
  4233. #if defined(KILL_PIN) && KILL_PIN > -1
  4234. static int killCount = 0; // make the inactivity button a bit less responsive
  4235. const int KILL_DELAY = 10000;
  4236. #endif
  4237. if(buflen < (BUFSIZE-1))
  4238. get_command();
  4239. if( (millis() - previous_millis_cmd) > max_inactive_time )
  4240. if(max_inactive_time)
  4241. kill();
  4242. if(stepper_inactive_time) {
  4243. if( (millis() - previous_millis_cmd) > stepper_inactive_time )
  4244. {
  4245. if(blocks_queued() == false && ignore_stepper_queue == false) {
  4246. disable_x();
  4247. disable_y();
  4248. disable_z();
  4249. disable_e0();
  4250. disable_e1();
  4251. disable_e2();
  4252. }
  4253. }
  4254. }
  4255. #ifdef CHDK //Check if pin should be set to LOW after M240 set it to HIGH
  4256. if (chdkActive && (millis() - chdkHigh > CHDK_DELAY))
  4257. {
  4258. chdkActive = false;
  4259. WRITE(CHDK, LOW);
  4260. }
  4261. #endif
  4262. #if defined(KILL_PIN) && KILL_PIN > -1
  4263. // Check if the kill button was pressed and wait just in case it was an accidental
  4264. // key kill key press
  4265. // -------------------------------------------------------------------------------
  4266. if( 0 == READ(KILL_PIN) )
  4267. {
  4268. killCount++;
  4269. }
  4270. else if (killCount > 0)
  4271. {
  4272. killCount--;
  4273. }
  4274. // Exceeded threshold and we can confirm that it was not accidental
  4275. // KILL the machine
  4276. // ----------------------------------------------------------------
  4277. if ( killCount >= KILL_DELAY)
  4278. {
  4279. kill();
  4280. }
  4281. #endif
  4282. #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1
  4283. controllerFan(); //Check if fan should be turned on to cool stepper drivers down
  4284. #endif
  4285. #ifdef EXTRUDER_RUNOUT_PREVENT
  4286. if( (millis() - previous_millis_cmd) > EXTRUDER_RUNOUT_SECONDS*1000 )
  4287. if(degHotend(active_extruder)>EXTRUDER_RUNOUT_MINTEMP)
  4288. {
  4289. bool oldstatus=READ(E0_ENABLE_PIN);
  4290. enable_e0();
  4291. float oldepos=current_position[E_AXIS];
  4292. float oldedes=destination[E_AXIS];
  4293. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS],
  4294. destination[E_AXIS]+EXTRUDER_RUNOUT_EXTRUDE*EXTRUDER_RUNOUT_ESTEPS/axis_steps_per_unit[E_AXIS],
  4295. EXTRUDER_RUNOUT_SPEED/60.*EXTRUDER_RUNOUT_ESTEPS/axis_steps_per_unit[E_AXIS], active_extruder);
  4296. current_position[E_AXIS]=oldepos;
  4297. destination[E_AXIS]=oldedes;
  4298. plan_set_e_position(oldepos);
  4299. previous_millis_cmd=millis();
  4300. st_synchronize();
  4301. WRITE(E0_ENABLE_PIN,oldstatus);
  4302. }
  4303. #endif
  4304. #if defined(DUAL_X_CARRIAGE)
  4305. // handle delayed move timeout
  4306. if (delayed_move_time != 0 && (millis() - delayed_move_time) > 1000 && Stopped == false)
  4307. {
  4308. // travel moves have been received so enact them
  4309. delayed_move_time = 0xFFFFFFFFUL; // force moves to be done
  4310. memcpy(destination,current_position,sizeof(destination));
  4311. prepare_move();
  4312. }
  4313. #endif
  4314. #ifdef TEMP_STAT_LEDS
  4315. handle_status_leds();
  4316. #endif
  4317. check_axes_activity();
  4318. }
  4319. void kill()
  4320. {
  4321. cli(); // Stop interrupts
  4322. disable_heater();
  4323. disable_x();
  4324. disable_y();
  4325. disable_z();
  4326. disable_e0();
  4327. disable_e1();
  4328. disable_e2();
  4329. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  4330. pinMode(PS_ON_PIN,INPUT);
  4331. #endif
  4332. SERIAL_ERROR_START;
  4333. SERIAL_ERRORLNRPGM(MSG_ERR_KILLED);
  4334. LCD_ALERTMESSAGERPGM(MSG_KILLED);
  4335. // FMC small patch to update the LCD before ending
  4336. sei(); // enable interrupts
  4337. for ( int i=5; i--; lcd_update())
  4338. {
  4339. delay(200);
  4340. }
  4341. cli(); // disable interrupts
  4342. suicide();
  4343. while(1) { /* Intentionally left empty */ } // Wait for reset
  4344. }
  4345. void Stop()
  4346. {
  4347. disable_heater();
  4348. if(Stopped == false) {
  4349. Stopped = true;
  4350. Stopped_gcode_LastN = gcode_LastN; // Save last g_code for restart
  4351. SERIAL_ERROR_START;
  4352. SERIAL_ERRORLNRPGM(MSG_ERR_STOPPED);
  4353. LCD_MESSAGERPGM(MSG_STOPPED);
  4354. }
  4355. }
  4356. bool IsStopped() { return Stopped; };
  4357. #ifdef FAST_PWM_FAN
  4358. void setPwmFrequency(uint8_t pin, int val)
  4359. {
  4360. val &= 0x07;
  4361. switch(digitalPinToTimer(pin))
  4362. {
  4363. #if defined(TCCR0A)
  4364. case TIMER0A:
  4365. case TIMER0B:
  4366. // TCCR0B &= ~(_BV(CS00) | _BV(CS01) | _BV(CS02));
  4367. // TCCR0B |= val;
  4368. break;
  4369. #endif
  4370. #if defined(TCCR1A)
  4371. case TIMER1A:
  4372. case TIMER1B:
  4373. // TCCR1B &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  4374. // TCCR1B |= val;
  4375. break;
  4376. #endif
  4377. #if defined(TCCR2)
  4378. case TIMER2:
  4379. case TIMER2:
  4380. TCCR2 &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  4381. TCCR2 |= val;
  4382. break;
  4383. #endif
  4384. #if defined(TCCR2A)
  4385. case TIMER2A:
  4386. case TIMER2B:
  4387. TCCR2B &= ~(_BV(CS20) | _BV(CS21) | _BV(CS22));
  4388. TCCR2B |= val;
  4389. break;
  4390. #endif
  4391. #if defined(TCCR3A)
  4392. case TIMER3A:
  4393. case TIMER3B:
  4394. case TIMER3C:
  4395. TCCR3B &= ~(_BV(CS30) | _BV(CS31) | _BV(CS32));
  4396. TCCR3B |= val;
  4397. break;
  4398. #endif
  4399. #if defined(TCCR4A)
  4400. case TIMER4A:
  4401. case TIMER4B:
  4402. case TIMER4C:
  4403. TCCR4B &= ~(_BV(CS40) | _BV(CS41) | _BV(CS42));
  4404. TCCR4B |= val;
  4405. break;
  4406. #endif
  4407. #if defined(TCCR5A)
  4408. case TIMER5A:
  4409. case TIMER5B:
  4410. case TIMER5C:
  4411. TCCR5B &= ~(_BV(CS50) | _BV(CS51) | _BV(CS52));
  4412. TCCR5B |= val;
  4413. break;
  4414. #endif
  4415. }
  4416. }
  4417. #endif //FAST_PWM_FAN
  4418. bool setTargetedHotend(int code){
  4419. tmp_extruder = active_extruder;
  4420. if(code_seen('T')) {
  4421. tmp_extruder = code_value();
  4422. if(tmp_extruder >= EXTRUDERS) {
  4423. SERIAL_ECHO_START;
  4424. switch(code){
  4425. case 104:
  4426. SERIAL_ECHO(MSG_M104_INVALID_EXTRUDER);
  4427. break;
  4428. case 105:
  4429. SERIAL_ECHO(MSG_M105_INVALID_EXTRUDER);
  4430. break;
  4431. case 109:
  4432. SERIAL_ECHO(MSG_M109_INVALID_EXTRUDER);
  4433. break;
  4434. case 218:
  4435. SERIAL_ECHO(MSG_M218_INVALID_EXTRUDER);
  4436. break;
  4437. case 221:
  4438. SERIAL_ECHO(MSG_M221_INVALID_EXTRUDER);
  4439. break;
  4440. }
  4441. SERIAL_ECHOLN(tmp_extruder);
  4442. return true;
  4443. }
  4444. }
  4445. return false;
  4446. }
  4447. void save_statistics(unsigned long _total_filament_used, unsigned long _total_print_time)
  4448. {
  4449. if (eeprom_read_byte((uint8_t *)EEPROM_TOTALTIME) == 255 && eeprom_read_byte((uint8_t *)EEPROM_TOTALTIME + 1) == 255 && eeprom_read_byte((uint8_t *)EEPROM_TOTALTIME + 2) == 255 && eeprom_read_byte((uint8_t *)EEPROM_TOTALTIME + 3) == 255)
  4450. {
  4451. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, 0);
  4452. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, 0);
  4453. }
  4454. unsigned long _previous_filament = eeprom_read_dword((uint32_t *)EEPROM_FILAMENTUSED);
  4455. unsigned long _previous_time = eeprom_read_dword((uint32_t *)EEPROM_TOTALTIME);
  4456. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, _previous_time + (_total_print_time/60));
  4457. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, _previous_filament + (_total_filament_used / 1000));
  4458. total_filament_used = 0;
  4459. }
  4460. float calculate_volumetric_multiplier(float diameter) {
  4461. float area = .0;
  4462. float radius = .0;
  4463. radius = diameter * .5;
  4464. if (! volumetric_enabled || radius == 0) {
  4465. area = 1;
  4466. }
  4467. else {
  4468. area = M_PI * pow(radius, 2);
  4469. }
  4470. return 1.0 / area;
  4471. }
  4472. void calculate_volumetric_multipliers() {
  4473. volumetric_multiplier[0] = calculate_volumetric_multiplier(filament_size[0]);
  4474. #if EXTRUDERS > 1
  4475. volumetric_multiplier[1] = calculate_volumetric_multiplier(filament_size[1]);
  4476. #if EXTRUDERS > 2
  4477. volumetric_multiplier[2] = calculate_volumetric_multiplier(filament_size[2]);
  4478. #endif
  4479. #endif
  4480. }
  4481. void delay_keep_alive(int ms)
  4482. {
  4483. for (;;) {
  4484. manage_heater();
  4485. manage_inactivity();
  4486. lcd_update();
  4487. if (ms == 0)
  4488. break;
  4489. else if (ms >= 50) {
  4490. delay(50);
  4491. ms -= 50;
  4492. } else {
  4493. delay(ms);
  4494. ms = 0;
  4495. }
  4496. }
  4497. }