My Marlin configs for Fabrikator Mini and CTC i3 Pro B
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Marlin_main.cpp 418KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179
  1. /**
  2. * Marlin 3D Printer Firmware
  3. * Copyright (C) 2016, 2017 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
  4. *
  5. * Based on Sprinter and grbl.
  6. * Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
  7. *
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation, either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. *
  21. */
  22. /**
  23. * About Marlin
  24. *
  25. * This firmware is a mashup between Sprinter and grbl.
  26. * - https://github.com/kliment/Sprinter
  27. * - https://github.com/simen/grbl/tree
  28. */
  29. /**
  30. * -----------------
  31. * G-Codes in Marlin
  32. * -----------------
  33. *
  34. * Helpful G-code references:
  35. * - http://linuxcnc.org/handbook/gcode/g-code.html
  36. * - http://objects.reprap.org/wiki/Mendel_User_Manual:_RepRapGCodes
  37. *
  38. * Help to document Marlin's G-codes online:
  39. * - http://reprap.org/wiki/G-code
  40. * - https://github.com/MarlinFirmware/MarlinDocumentation
  41. *
  42. * -----------------
  43. *
  44. * "G" Codes
  45. *
  46. * G0 -> G1
  47. * G1 - Coordinated Movement X Y Z E
  48. * G2 - CW ARC
  49. * G3 - CCW ARC
  50. * G4 - Dwell S<seconds> or P<milliseconds>
  51. * G5 - Cubic B-spline with XYZE destination and IJPQ offsets
  52. * G10 - Retract filament according to settings of M207
  53. * G11 - Retract recover filament according to settings of M208
  54. * G12 - Clean tool
  55. * G17 - Select Plane XY (Requires CNC_WORKSPACE_PLANES)
  56. * G18 - Select Plane ZX (Requires CNC_WORKSPACE_PLANES)
  57. * G19 - Select Plane YZ (Requires CNC_WORKSPACE_PLANES)
  58. * G20 - Set input units to inches
  59. * G21 - Set input units to millimeters
  60. * G26 - Mesh Validation Pattern (Requires UBL_G26_MESH_VALIDATION)
  61. * G27 - Park Nozzle (Requires NOZZLE_PARK_FEATURE)
  62. * G28 - Home one or more axes
  63. * G29 - Detailed Z probe, probes the bed at 3 or more points. Will fail if you haven't homed yet.
  64. * G30 - Single Z probe, probes bed at X Y location (defaults to current XY location)
  65. * G31 - Dock sled (Z_PROBE_SLED only)
  66. * G32 - Undock sled (Z_PROBE_SLED only)
  67. * G33 - Delta Auto-Calibration (Requires DELTA_AUTO_CALIBRATION)
  68. * G38 - Probe target - similar to G28 except it uses the Z_MIN_PROBE for all three axes
  69. * G42 - Coordinated move to a mesh point (Requires AUTO_BED_LEVELING_UBL)
  70. * G90 - Use Absolute Coordinates
  71. * G91 - Use Relative Coordinates
  72. * G92 - Set current position to coordinates given
  73. *
  74. * "M" Codes
  75. *
  76. * M0 - Unconditional stop - Wait for user to press a button on the LCD (Only if ULTRA_LCD is enabled)
  77. * M1 -> M0
  78. * M3 - Turn laser/spindle on, set spindle/laser speed/power, set rotation to clockwise
  79. * M4 - Turn laser/spindle on, set spindle/laser speed/power, set rotation to counter-clockwise
  80. * M5 - Turn laser/spindle off
  81. * M17 - Enable/Power all stepper motors
  82. * M18 - Disable all stepper motors; same as M84
  83. * M20 - List SD card. (Requires SDSUPPORT)
  84. * M21 - Init SD card. (Requires SDSUPPORT)
  85. * M22 - Release SD card. (Requires SDSUPPORT)
  86. * M23 - Select SD file: "M23 /path/file.gco". (Requires SDSUPPORT)
  87. * M24 - Start/resume SD print. (Requires SDSUPPORT)
  88. * M25 - Pause SD print. (Requires SDSUPPORT)
  89. * M26 - Set SD position in bytes: "M26 S12345". (Requires SDSUPPORT)
  90. * M27 - Report SD print status. (Requires SDSUPPORT)
  91. * M28 - Start SD write: "M28 /path/file.gco". (Requires SDSUPPORT)
  92. * M29 - Stop SD write. (Requires SDSUPPORT)
  93. * M30 - Delete file from SD: "M30 /path/file.gco"
  94. * M31 - Report time since last M109 or SD card start to serial.
  95. * M32 - Select file and start SD print: "M32 [S<bytepos>] !/path/file.gco#". (Requires SDSUPPORT)
  96. * Use P to run other files as sub-programs: "M32 P !filename#"
  97. * The '#' is necessary when calling from within sd files, as it stops buffer prereading
  98. * M33 - Get the longname version of a path. (Requires LONG_FILENAME_HOST_SUPPORT)
  99. * M34 - Set SD Card sorting options. (Requires SDCARD_SORT_ALPHA)
  100. * M42 - Change pin status via gcode: M42 P<pin> S<value>. LED pin assumed if P is omitted.
  101. * M43 - Display pin status, watch pins for changes, watch endstops & toggle LED, Z servo probe test, toggle pins
  102. * M48 - Measure Z Probe repeatability: M48 P<points> X<pos> Y<pos> V<level> E<engage> L<legs>. (Requires Z_MIN_PROBE_REPEATABILITY_TEST)
  103. * M75 - Start the print job timer.
  104. * M76 - Pause the print job timer.
  105. * M77 - Stop the print job timer.
  106. * M78 - Show statistical information about the print jobs. (Requires PRINTCOUNTER)
  107. * M80 - Turn on Power Supply. (Requires POWER_SUPPLY > 0)
  108. * M81 - Turn off Power Supply. (Requires POWER_SUPPLY > 0)
  109. * M82 - Set E codes absolute (default).
  110. * M83 - Set E codes relative while in Absolute (G90) mode.
  111. * M84 - Disable steppers until next move, or use S<seconds> to specify an idle
  112. * duration after which steppers should turn off. S0 disables the timeout.
  113. * M85 - Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
  114. * M92 - Set planner.axis_steps_per_mm for one or more axes.
  115. * M100 - Watch Free Memory (for debugging) (Requires M100_FREE_MEMORY_WATCHER)
  116. * M104 - Set extruder target temp.
  117. * M105 - Report current temperatures.
  118. * M106 - Fan on.
  119. * M107 - Fan off.
  120. * M108 - Break out of heating loops (M109, M190, M303). With no controller, breaks out of M0/M1. (Requires EMERGENCY_PARSER)
  121. * M109 - Sxxx Wait for extruder current temp to reach target temp. Waits only when heating
  122. * Rxxx Wait for extruder current temp to reach target temp. Waits when heating and cooling
  123. * If AUTOTEMP is enabled, S<mintemp> B<maxtemp> F<factor>. Exit autotemp by any M109 without F
  124. * M110 - Set the current line number. (Used by host printing)
  125. * M111 - Set debug flags: "M111 S<flagbits>". See flag bits defined in enum.h.
  126. * M112 - Emergency stop.
  127. * M113 - Get or set the timeout interval for Host Keepalive "busy" messages. (Requires HOST_KEEPALIVE_FEATURE)
  128. * M114 - Report current position.
  129. * M115 - Report capabilities. (Extended capabilities requires EXTENDED_CAPABILITIES_REPORT)
  130. * M117 - Display a message on the controller screen. (Requires an LCD)
  131. * M118 - Display a message in the host console.
  132. * M119 - Report endstops status.
  133. * M120 - Enable endstops detection.
  134. * M121 - Disable endstops detection.
  135. * M125 - Save current position and move to filament change position. (Requires PARK_HEAD_ON_PAUSE)
  136. * M126 - Solenoid Air Valve Open. (Requires BARICUDA)
  137. * M127 - Solenoid Air Valve Closed. (Requires BARICUDA)
  138. * M128 - EtoP Open. (Requires BARICUDA)
  139. * M129 - EtoP Closed. (Requires BARICUDA)
  140. * M140 - Set bed target temp. S<temp>
  141. * M145 - Set heatup values for materials on the LCD. H<hotend> B<bed> F<fan speed> for S<material> (0=PLA, 1=ABS)
  142. * M149 - Set temperature units. (Requires TEMPERATURE_UNITS_SUPPORT)
  143. * M150 - Set Status LED Color as R<red> U<green> B<blue>. Values 0-255. (Requires BLINKM, RGB_LED, RGBW_LED, or PCA9632)
  144. * M155 - Auto-report temperatures with interval of S<seconds>. (Requires AUTO_REPORT_TEMPERATURES)
  145. * M163 - Set a single proportion for a mixing extruder. (Requires MIXING_EXTRUDER)
  146. * M164 - Save the mix as a virtual extruder. (Requires MIXING_EXTRUDER and MIXING_VIRTUAL_TOOLS)
  147. * M165 - Set the proportions for a mixing extruder. Use parameters ABCDHI to set the mixing factors. (Requires MIXING_EXTRUDER)
  148. * M190 - Sxxx Wait for bed current temp to reach target temp. ** Waits only when heating! **
  149. * Rxxx Wait for bed current temp to reach target temp. ** Waits for heating or cooling. **
  150. * M200 - Set filament diameter, D<diameter>, setting E axis units to cubic. (Use S0 to revert to linear units.)
  151. * M201 - Set max acceleration in units/s^2 for print moves: "M201 X<accel> Y<accel> Z<accel> E<accel>"
  152. * M202 - Set max acceleration in units/s^2 for travel moves: "M202 X<accel> Y<accel> Z<accel> E<accel>" ** UNUSED IN MARLIN! **
  153. * M203 - Set maximum feedrate: "M203 X<fr> Y<fr> Z<fr> E<fr>" in units/sec.
  154. * M204 - Set default acceleration in units/sec^2: P<printing> R<extruder_only> T<travel>
  155. * M205 - Set advanced settings. Current units apply:
  156. S<print> T<travel> minimum speeds
  157. B<minimum segment time>
  158. X<max X jerk>, Y<max Y jerk>, Z<max Z jerk>, E<max E jerk>
  159. * M206 - Set additional homing offset. (Disabled by NO_WORKSPACE_OFFSETS or DELTA)
  160. * M207 - Set Retract Length: S<length>, Feedrate: F<units/min>, and Z lift: Z<distance>. (Requires FWRETRACT)
  161. * M208 - Set Recover (unretract) Additional (!) Length: S<length> and Feedrate: F<units/min>. (Requires FWRETRACT)
  162. * M209 - Turn Automatic Retract Detection on/off: S<0|1> (For slicers that don't support G10/11). (Requires FWRETRACT)
  163. Every normal extrude-only move will be classified as retract depending on the direction.
  164. * M211 - Enable, Disable, and/or Report software endstops: S<0|1> (Requires MIN_SOFTWARE_ENDSTOPS or MAX_SOFTWARE_ENDSTOPS)
  165. * M218 - Set a tool offset: "M218 T<index> X<offset> Y<offset>". (Requires 2 or more extruders)
  166. * M220 - Set Feedrate Percentage: "M220 S<percent>" (i.e., "FR" on the LCD)
  167. * M221 - Set Flow Percentage: "M221 S<percent>"
  168. * M226 - Wait until a pin is in a given state: "M226 P<pin> S<state>"
  169. * M240 - Trigger a camera to take a photograph. (Requires CHDK or PHOTOGRAPH_PIN)
  170. * M250 - Set LCD contrast: "M250 C<contrast>" (0-63). (Requires LCD support)
  171. * M260 - i2c Send Data (Requires EXPERIMENTAL_I2CBUS)
  172. * M261 - i2c Request Data (Requires EXPERIMENTAL_I2CBUS)
  173. * M280 - Set servo position absolute: "M280 P<index> S<angle|µs>". (Requires servos)
  174. * M300 - Play beep sound S<frequency Hz> P<duration ms>
  175. * M301 - Set PID parameters P I and D. (Requires PIDTEMP)
  176. * M302 - Allow cold extrudes, or set the minimum extrude S<temperature>. (Requires PREVENT_COLD_EXTRUSION)
  177. * M303 - PID relay autotune S<temperature> sets the target temperature. Default 150C. (Requires PIDTEMP)
  178. * M304 - Set bed PID parameters P I and D. (Requires PIDTEMPBED)
  179. * M350 - Set microstepping mode. (Requires digital microstepping pins.)
  180. * M351 - Toggle MS1 MS2 pins directly. (Requires digital microstepping pins.)
  181. * M355 - Set Case Light on/off and set brightness. (Requires CASE_LIGHT_PIN)
  182. * M380 - Activate solenoid on active extruder. (Requires EXT_SOLENOID)
  183. * M381 - Disable all solenoids. (Requires EXT_SOLENOID)
  184. * M400 - Finish all moves.
  185. * M401 - Lower Z probe. (Requires a probe)
  186. * M402 - Raise Z probe. (Requires a probe)
  187. * M404 - Display or set the Nominal Filament Width: "W<diameter>". (Requires FILAMENT_WIDTH_SENSOR)
  188. * M405 - Enable Filament Sensor flow control. "M405 D<delay_cm>". (Requires FILAMENT_WIDTH_SENSOR)
  189. * M406 - Disable Filament Sensor flow control. (Requires FILAMENT_WIDTH_SENSOR)
  190. * M407 - Display measured filament diameter in millimeters. (Requires FILAMENT_WIDTH_SENSOR)
  191. * M410 - Quickstop. Abort all planned moves.
  192. * M420 - Enable/Disable Leveling (with current values) S1=enable S0=disable (Requires MESH_BED_LEVELING or ABL)
  193. * M421 - Set a single Z coordinate in the Mesh Leveling grid. X<units> Y<units> Z<units> (Requires MESH_BED_LEVELING or AUTO_BED_LEVELING_UBL)
  194. * M428 - Set the home_offset based on the current_position. Nearest edge applies. (Disabled by NO_WORKSPACE_OFFSETS or DELTA)
  195. * M500 - Store parameters in EEPROM. (Requires EEPROM_SETTINGS)
  196. * M501 - Restore parameters from EEPROM. (Requires EEPROM_SETTINGS)
  197. * M502 - Revert to the default "factory settings". ** Does not write them to EEPROM! **
  198. * M503 - Print the current settings (in memory): "M503 S<verbose>". S0 specifies compact output.
  199. * M540 - Enable/disable SD card abort on endstop hit: "M540 S<state>". (Requires ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  200. * M600 - Pause for filament change: "M600 X<pos> Y<pos> Z<raise> E<first_retract> L<later_retract>". (Requires ADVANCED_PAUSE_FEATURE)
  201. * M665 - Set delta configurations: "M665 L<diagonal rod> R<delta radius> S<segments/s> A<rod A trim mm> B<rod B trim mm> C<rod C trim mm> I<tower A trim angle> J<tower B trim angle> K<tower C trim angle>" (Requires DELTA)
  202. * M666 - Set delta endstop adjustment. (Requires DELTA)
  203. * M605 - Set dual x-carriage movement mode: "M605 S<mode> [X<x_offset>] [R<temp_offset>]". (Requires DUAL_X_CARRIAGE)
  204. * M851 - Set Z probe's Z offset in current units. (Negative = below the nozzle.)
  205. * M860 - Report the position of position encoder modules.
  206. * M861 - Report the status of position encoder modules.
  207. * M862 - Perform an axis continuity test for position encoder modules.
  208. * M863 - Perform steps-per-mm calibration for position encoder modules.
  209. * M864 - Change position encoder module I2C address.
  210. * M865 - Check position encoder module firmware version.
  211. * M866 - Report or reset position encoder module error count.
  212. * M867 - Enable/disable or toggle error correction for position encoder modules.
  213. * M868 - Report or set position encoder module error correction threshold.
  214. * M869 - Report position encoder module error.
  215. * M900 - Get and/or Set advance K factor and WH/D ratio. (Requires LIN_ADVANCE)
  216. * M906 - Set or get motor current in milliamps using axis codes X, Y, Z, E. Report values if no axis codes given. (Requires HAVE_TMC2130)
  217. * M907 - Set digital trimpot motor current using axis codes. (Requires a board with digital trimpots)
  218. * M908 - Control digital trimpot directly. (Requires DAC_STEPPER_CURRENT or DIGIPOTSS_PIN)
  219. * M909 - Print digipot/DAC current value. (Requires DAC_STEPPER_CURRENT)
  220. * M910 - Commit digipot/DAC value to external EEPROM via I2C. (Requires DAC_STEPPER_CURRENT)
  221. * M911 - Report stepper driver overtemperature pre-warn condition. (Requires HAVE_TMC2130)
  222. * M912 - Clear stepper driver overtemperature pre-warn condition flag. (Requires HAVE_TMC2130)
  223. * M913 - Set HYBRID_THRESHOLD speed. (Requires HYBRID_THRESHOLD)
  224. * M914 - Set SENSORLESS_HOMING sensitivity. (Requires SENSORLESS_HOMING)
  225. *
  226. * M360 - SCARA calibration: Move to cal-position ThetaA (0 deg calibration)
  227. * M361 - SCARA calibration: Move to cal-position ThetaB (90 deg calibration - steps per degree)
  228. * M362 - SCARA calibration: Move to cal-position PsiA (0 deg calibration)
  229. * M363 - SCARA calibration: Move to cal-position PsiB (90 deg calibration - steps per degree)
  230. * M364 - SCARA calibration: Move to cal-position PSIC (90 deg to Theta calibration position)
  231. *
  232. * ************ Custom codes - This can change to suit future G-code regulations
  233. * M928 - Start SD logging: "M928 filename.gco". Stop with M29. (Requires SDSUPPORT)
  234. * M999 - Restart after being stopped by error
  235. *
  236. * "T" Codes
  237. *
  238. * T0-T3 - Select an extruder (tool) by index: "T<n> F<units/min>"
  239. *
  240. */
  241. #include "Marlin.h"
  242. #include "ultralcd.h"
  243. #include "planner.h"
  244. #include "stepper.h"
  245. #include "endstops.h"
  246. #include "temperature.h"
  247. #include "cardreader.h"
  248. #include "configuration_store.h"
  249. #include "language.h"
  250. #include "pins_arduino.h"
  251. #include "math.h"
  252. #include "nozzle.h"
  253. #include "duration_t.h"
  254. #include "types.h"
  255. #include "gcode.h"
  256. #if HAS_ABL
  257. #include "vector_3.h"
  258. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  259. #include "qr_solve.h"
  260. #endif
  261. #elif ENABLED(MESH_BED_LEVELING)
  262. #include "mesh_bed_leveling.h"
  263. #endif
  264. #if ENABLED(BEZIER_CURVE_SUPPORT)
  265. #include "planner_bezier.h"
  266. #endif
  267. #if HAS_BUZZER && DISABLED(LCD_USE_I2C_BUZZER)
  268. #include "buzzer.h"
  269. #endif
  270. #if ENABLED(USE_WATCHDOG)
  271. #include "watchdog.h"
  272. #endif
  273. #if ENABLED(BLINKM)
  274. #include "blinkm.h"
  275. #include "Wire.h"
  276. #endif
  277. #if ENABLED(PCA9632)
  278. #include "pca9632.h"
  279. #endif
  280. #if HAS_SERVOS
  281. #include "servo.h"
  282. #endif
  283. #if HAS_DIGIPOTSS
  284. #include <SPI.h>
  285. #endif
  286. #if ENABLED(DAC_STEPPER_CURRENT)
  287. #include "stepper_dac.h"
  288. #endif
  289. #if ENABLED(EXPERIMENTAL_I2CBUS)
  290. #include "twibus.h"
  291. #endif
  292. #if ENABLED(I2C_POSITION_ENCODERS)
  293. #include "I2CPositionEncoder.h"
  294. #endif
  295. #if ENABLED(ENDSTOP_INTERRUPTS_FEATURE)
  296. #include "endstop_interrupts.h"
  297. #endif
  298. #if ENABLED(M100_FREE_MEMORY_WATCHER)
  299. void gcode_M100();
  300. void M100_dump_routine(const char * const title, const char *start, const char *end);
  301. #endif
  302. #if ENABLED(SDSUPPORT)
  303. CardReader card;
  304. #endif
  305. #if ENABLED(EXPERIMENTAL_I2CBUS)
  306. TWIBus i2c;
  307. #endif
  308. #if ENABLED(G38_PROBE_TARGET)
  309. bool G38_move = false,
  310. G38_endstop_hit = false;
  311. #endif
  312. #if ENABLED(AUTO_BED_LEVELING_UBL)
  313. #include "ubl.h"
  314. extern bool defer_return_to_status;
  315. unified_bed_leveling ubl;
  316. #define UBL_MESH_VALID !( ( ubl.z_values[0][0] == ubl.z_values[0][1] && ubl.z_values[0][1] == ubl.z_values[0][2] \
  317. && ubl.z_values[1][0] == ubl.z_values[1][1] && ubl.z_values[1][1] == ubl.z_values[1][2] \
  318. && ubl.z_values[2][0] == ubl.z_values[2][1] && ubl.z_values[2][1] == ubl.z_values[2][2] \
  319. && ubl.z_values[0][0] == 0 && ubl.z_values[1][0] == 0 && ubl.z_values[2][0] == 0 ) \
  320. || isnan(ubl.z_values[0][0]))
  321. #endif
  322. bool Running = true;
  323. uint8_t marlin_debug_flags = DEBUG_NONE;
  324. /**
  325. * Cartesian Current Position
  326. * Used to track the logical position as moves are queued.
  327. * Used by 'line_to_current_position' to do a move after changing it.
  328. * Used by 'SYNC_PLAN_POSITION_KINEMATIC' to update 'planner.position'.
  329. */
  330. float current_position[XYZE] = { 0.0 };
  331. /**
  332. * Cartesian Destination
  333. * A temporary position, usually applied to 'current_position'.
  334. * Set with 'gcode_get_destination' or 'set_destination_to_current'.
  335. * 'line_to_destination' sets 'current_position' to 'destination'.
  336. */
  337. float destination[XYZE] = { 0.0 };
  338. /**
  339. * axis_homed
  340. * Flags that each linear axis was homed.
  341. * XYZ on cartesian, ABC on delta, ABZ on SCARA.
  342. *
  343. * axis_known_position
  344. * Flags that the position is known in each linear axis. Set when homed.
  345. * Cleared whenever a stepper powers off, potentially losing its position.
  346. */
  347. bool axis_homed[XYZ] = { false }, axis_known_position[XYZ] = { false };
  348. /**
  349. * GCode line number handling. Hosts may opt to include line numbers when
  350. * sending commands to Marlin, and lines will be checked for sequentiality.
  351. * M110 N<int> sets the current line number.
  352. */
  353. static long gcode_N, gcode_LastN, Stopped_gcode_LastN = 0;
  354. /**
  355. * GCode Command Queue
  356. * A simple ring buffer of BUFSIZE command strings.
  357. *
  358. * Commands are copied into this buffer by the command injectors
  359. * (immediate, serial, sd card) and they are processed sequentially by
  360. * the main loop. The process_next_command function parses the next
  361. * command and hands off execution to individual handler functions.
  362. */
  363. uint8_t commands_in_queue = 0; // Count of commands in the queue
  364. static uint8_t cmd_queue_index_r = 0, // Ring buffer read position
  365. cmd_queue_index_w = 0; // Ring buffer write position
  366. #if ENABLED(M100_FREE_MEMORY_WATCHER)
  367. char command_queue[BUFSIZE][MAX_CMD_SIZE]; // Necessary so M100 Free Memory Dumper can show us the commands and any corruption
  368. #else // This can be collapsed back to the way it was soon.
  369. static char command_queue[BUFSIZE][MAX_CMD_SIZE];
  370. #endif
  371. /**
  372. * Next Injected Command pointer. NULL if no commands are being injected.
  373. * Used by Marlin internally to ensure that commands initiated from within
  374. * are enqueued ahead of any pending serial or sd card commands.
  375. */
  376. static const char *injected_commands_P = NULL;
  377. #if ENABLED(TEMPERATURE_UNITS_SUPPORT)
  378. TempUnit input_temp_units = TEMPUNIT_C;
  379. #endif
  380. /**
  381. * Feed rates are often configured with mm/m
  382. * but the planner and stepper like mm/s units.
  383. */
  384. static const float homing_feedrate_mm_s[] PROGMEM = {
  385. #if ENABLED(DELTA)
  386. MMM_TO_MMS(HOMING_FEEDRATE_Z), MMM_TO_MMS(HOMING_FEEDRATE_Z),
  387. #else
  388. MMM_TO_MMS(HOMING_FEEDRATE_XY), MMM_TO_MMS(HOMING_FEEDRATE_XY),
  389. #endif
  390. MMM_TO_MMS(HOMING_FEEDRATE_Z), 0
  391. };
  392. FORCE_INLINE float homing_feedrate(const AxisEnum a) { return pgm_read_float(&homing_feedrate_mm_s[a]); }
  393. float feedrate_mm_s = MMM_TO_MMS(1500.0);
  394. static float saved_feedrate_mm_s;
  395. int16_t feedrate_percentage = 100, saved_feedrate_percentage,
  396. flow_percentage[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(100);
  397. bool axis_relative_modes[] = AXIS_RELATIVE_MODES,
  398. volumetric_enabled =
  399. #if ENABLED(VOLUMETRIC_DEFAULT_ON)
  400. true
  401. #else
  402. false
  403. #endif
  404. ;
  405. float filament_size[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(DEFAULT_NOMINAL_FILAMENT_DIA),
  406. volumetric_multiplier[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(1.0);
  407. #if HAS_WORKSPACE_OFFSET
  408. #if HAS_POSITION_SHIFT
  409. // The distance that XYZ has been offset by G92. Reset by G28.
  410. float position_shift[XYZ] = { 0 };
  411. #endif
  412. #if HAS_HOME_OFFSET
  413. // This offset is added to the configured home position.
  414. // Set by M206, M428, or menu item. Saved to EEPROM.
  415. float home_offset[XYZ] = { 0 };
  416. #endif
  417. #if HAS_HOME_OFFSET && HAS_POSITION_SHIFT
  418. // The above two are combined to save on computes
  419. float workspace_offset[XYZ] = { 0 };
  420. #endif
  421. #endif
  422. // Software Endstops are based on the configured limits.
  423. #if HAS_SOFTWARE_ENDSTOPS
  424. bool soft_endstops_enabled = true;
  425. #endif
  426. float soft_endstop_min[XYZ] = { X_MIN_POS, Y_MIN_POS, Z_MIN_POS },
  427. soft_endstop_max[XYZ] = { X_MAX_POS, Y_MAX_POS, Z_MAX_POS };
  428. #if FAN_COUNT > 0
  429. int16_t fanSpeeds[FAN_COUNT] = { 0 };
  430. #if ENABLED(PROBING_FANS_OFF)
  431. bool fans_paused = false;
  432. int16_t paused_fanSpeeds[FAN_COUNT] = { 0 };
  433. #endif
  434. #endif
  435. // The active extruder (tool). Set with T<extruder> command.
  436. uint8_t active_extruder = 0;
  437. // Relative Mode. Enable with G91, disable with G90.
  438. static bool relative_mode = false;
  439. // For M109 and M190, this flag may be cleared (by M108) to exit the wait loop
  440. volatile bool wait_for_heatup = true;
  441. // For M0/M1, this flag may be cleared (by M108) to exit the wait-for-user loop
  442. #if HAS_RESUME_CONTINUE
  443. volatile bool wait_for_user = false;
  444. #endif
  445. const char axis_codes[XYZE] = { 'X', 'Y', 'Z', 'E' };
  446. // Number of characters read in the current line of serial input
  447. static int serial_count = 0;
  448. // Inactivity shutdown
  449. millis_t previous_cmd_ms = 0;
  450. static millis_t max_inactive_time = 0;
  451. static millis_t stepper_inactive_time = (DEFAULT_STEPPER_DEACTIVE_TIME) * 1000UL;
  452. // Print Job Timer
  453. #if ENABLED(PRINTCOUNTER)
  454. PrintCounter print_job_timer = PrintCounter();
  455. #else
  456. Stopwatch print_job_timer = Stopwatch();
  457. #endif
  458. // Buzzer - I2C on the LCD or a BEEPER_PIN
  459. #if ENABLED(LCD_USE_I2C_BUZZER)
  460. #define BUZZ(d,f) lcd_buzz(d, f)
  461. #elif PIN_EXISTS(BEEPER)
  462. Buzzer buzzer;
  463. #define BUZZ(d,f) buzzer.tone(d, f)
  464. #else
  465. #define BUZZ(d,f) NOOP
  466. #endif
  467. static uint8_t target_extruder;
  468. #if HAS_BED_PROBE
  469. float zprobe_zoffset = Z_PROBE_OFFSET_FROM_EXTRUDER;
  470. #endif
  471. #if HAS_ABL
  472. float xy_probe_feedrate_mm_s = MMM_TO_MMS(XY_PROBE_SPEED);
  473. #define XY_PROBE_FEEDRATE_MM_S xy_probe_feedrate_mm_s
  474. #elif defined(XY_PROBE_SPEED)
  475. #define XY_PROBE_FEEDRATE_MM_S MMM_TO_MMS(XY_PROBE_SPEED)
  476. #else
  477. #define XY_PROBE_FEEDRATE_MM_S PLANNER_XY_FEEDRATE()
  478. #endif
  479. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  480. #if ENABLED(DELTA)
  481. #define ADJUST_DELTA(V) \
  482. if (planner.abl_enabled) { \
  483. const float zadj = bilinear_z_offset(V); \
  484. delta[A_AXIS] += zadj; \
  485. delta[B_AXIS] += zadj; \
  486. delta[C_AXIS] += zadj; \
  487. }
  488. #else
  489. #define ADJUST_DELTA(V) if (planner.abl_enabled) { delta[Z_AXIS] += bilinear_z_offset(V); }
  490. #endif
  491. #elif IS_KINEMATIC
  492. #define ADJUST_DELTA(V) NOOP
  493. #endif
  494. #if ENABLED(Z_DUAL_ENDSTOPS)
  495. float z_endstop_adj =
  496. #ifdef Z_DUAL_ENDSTOPS_ADJUSTMENT
  497. Z_DUAL_ENDSTOPS_ADJUSTMENT
  498. #else
  499. 0
  500. #endif
  501. ;
  502. #endif
  503. // Extruder offsets
  504. #if HOTENDS > 1
  505. float hotend_offset[XYZ][HOTENDS];
  506. #endif
  507. #if HAS_Z_SERVO_ENDSTOP
  508. const int z_servo_angle[2] = Z_SERVO_ANGLES;
  509. #endif
  510. #if ENABLED(BARICUDA)
  511. int baricuda_valve_pressure = 0;
  512. int baricuda_e_to_p_pressure = 0;
  513. #endif
  514. #if ENABLED(FWRETRACT)
  515. bool autoretract_enabled = false;
  516. bool retracted[EXTRUDERS] = { false };
  517. bool retracted_swap[EXTRUDERS] = { false };
  518. float retract_length = RETRACT_LENGTH;
  519. float retract_length_swap = RETRACT_LENGTH_SWAP;
  520. float retract_feedrate_mm_s = RETRACT_FEEDRATE;
  521. float retract_zlift = RETRACT_ZLIFT;
  522. float retract_recover_length = RETRACT_RECOVER_LENGTH;
  523. float retract_recover_length_swap = RETRACT_RECOVER_LENGTH_SWAP;
  524. float retract_recover_feedrate_mm_s = RETRACT_RECOVER_FEEDRATE;
  525. #endif // FWRETRACT
  526. #if HAS_POWER_SWITCH
  527. bool powersupply_on =
  528. #if ENABLED(PS_DEFAULT_OFF)
  529. false
  530. #else
  531. true
  532. #endif
  533. ;
  534. #endif
  535. #if ENABLED(DELTA)
  536. float delta[ABC],
  537. endstop_adj[ABC] = { 0 };
  538. // These values are loaded or reset at boot time when setup() calls
  539. // settings.load(), which calls recalc_delta_settings().
  540. float delta_radius,
  541. delta_tower_angle_trim[2],
  542. delta_tower[ABC][2],
  543. delta_diagonal_rod,
  544. delta_calibration_radius,
  545. delta_diagonal_rod_2_tower[ABC],
  546. delta_segments_per_second,
  547. delta_clip_start_height = Z_MAX_POS;
  548. float delta_safe_distance_from_top();
  549. #endif
  550. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  551. int bilinear_grid_spacing[2], bilinear_start[2];
  552. float bilinear_grid_factor[2],
  553. z_values[GRID_MAX_POINTS_X][GRID_MAX_POINTS_Y];
  554. #endif
  555. #if IS_SCARA
  556. // Float constants for SCARA calculations
  557. const float L1 = SCARA_LINKAGE_1, L2 = SCARA_LINKAGE_2,
  558. L1_2 = sq(float(L1)), L1_2_2 = 2.0 * L1_2,
  559. L2_2 = sq(float(L2));
  560. float delta_segments_per_second = SCARA_SEGMENTS_PER_SECOND,
  561. delta[ABC];
  562. #endif
  563. float cartes[XYZ] = { 0 };
  564. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  565. bool filament_sensor = false; // M405 turns on filament sensor control. M406 turns it off.
  566. float filament_width_nominal = DEFAULT_NOMINAL_FILAMENT_DIA, // Nominal filament width. Change with M404.
  567. filament_width_meas = DEFAULT_MEASURED_FILAMENT_DIA; // Measured filament diameter
  568. uint8_t meas_delay_cm = MEASUREMENT_DELAY_CM, // Distance delay setting
  569. measurement_delay[MAX_MEASUREMENT_DELAY + 1]; // Ring buffer to delayed measurement. Store extruder factor after subtracting 100
  570. int8_t filwidth_delay_index[2] = { 0, -1 }; // Indexes into ring buffer
  571. #endif
  572. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  573. static bool filament_ran_out = false;
  574. #endif
  575. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  576. AdvancedPauseMenuResponse advanced_pause_menu_response;
  577. #endif
  578. #if ENABLED(MIXING_EXTRUDER)
  579. float mixing_factor[MIXING_STEPPERS]; // Reciprocal of mix proportion. 0.0 = off, otherwise >= 1.0.
  580. #if MIXING_VIRTUAL_TOOLS > 1
  581. float mixing_virtual_tool_mix[MIXING_VIRTUAL_TOOLS][MIXING_STEPPERS];
  582. #endif
  583. #endif
  584. static bool send_ok[BUFSIZE];
  585. #if HAS_SERVOS
  586. Servo servo[NUM_SERVOS];
  587. #define MOVE_SERVO(I, P) servo[I].move(P)
  588. #if HAS_Z_SERVO_ENDSTOP
  589. #define DEPLOY_Z_SERVO() MOVE_SERVO(Z_ENDSTOP_SERVO_NR, z_servo_angle[0])
  590. #define STOW_Z_SERVO() MOVE_SERVO(Z_ENDSTOP_SERVO_NR, z_servo_angle[1])
  591. #endif
  592. #endif
  593. #ifdef CHDK
  594. millis_t chdkHigh = 0;
  595. bool chdkActive = false;
  596. #endif
  597. #ifdef AUTOMATIC_CURRENT_CONTROL
  598. bool auto_current_control = 0;
  599. #endif
  600. #if ENABLED(PID_EXTRUSION_SCALING)
  601. int lpq_len = 20;
  602. #endif
  603. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  604. MarlinBusyState busy_state = NOT_BUSY;
  605. static millis_t next_busy_signal_ms = 0;
  606. uint8_t host_keepalive_interval = DEFAULT_KEEPALIVE_INTERVAL;
  607. #else
  608. #define host_keepalive() NOOP
  609. #endif
  610. #if ENABLED(I2C_POSITION_ENCODERS)
  611. I2CPositionEncodersMgr I2CPEM;
  612. uint8_t blockBufferIndexRef = 0;
  613. millis_t lastUpdateMillis;
  614. #endif
  615. #if ENABLED(CNC_WORKSPACE_PLANES)
  616. static WorkspacePlane workspace_plane = PLANE_XY;
  617. #endif
  618. FORCE_INLINE float pgm_read_any(const float *p) { return pgm_read_float_near(p); }
  619. FORCE_INLINE signed char pgm_read_any(const signed char *p) { return pgm_read_byte_near(p); }
  620. #define XYZ_CONSTS_FROM_CONFIG(type, array, CONFIG) \
  621. static const PROGMEM type array##_P[XYZ] = { X_##CONFIG, Y_##CONFIG, Z_##CONFIG }; \
  622. static inline type array(AxisEnum axis) { return pgm_read_any(&array##_P[axis]); } \
  623. typedef void __void_##CONFIG##__
  624. XYZ_CONSTS_FROM_CONFIG(float, base_min_pos, MIN_POS);
  625. XYZ_CONSTS_FROM_CONFIG(float, base_max_pos, MAX_POS);
  626. XYZ_CONSTS_FROM_CONFIG(float, base_home_pos, HOME_POS);
  627. XYZ_CONSTS_FROM_CONFIG(float, max_length, MAX_LENGTH);
  628. XYZ_CONSTS_FROM_CONFIG(float, home_bump_mm, HOME_BUMP_MM);
  629. XYZ_CONSTS_FROM_CONFIG(signed char, home_dir, HOME_DIR);
  630. /**
  631. * ***************************************************************************
  632. * ******************************** FUNCTIONS ********************************
  633. * ***************************************************************************
  634. */
  635. void stop();
  636. void get_available_commands();
  637. void process_next_command();
  638. void prepare_move_to_destination();
  639. void get_cartesian_from_steppers();
  640. void set_current_from_steppers_for_axis(const AxisEnum axis);
  641. #if ENABLED(ARC_SUPPORT)
  642. void plan_arc(float target[XYZE], float* offset, uint8_t clockwise);
  643. #endif
  644. #if ENABLED(BEZIER_CURVE_SUPPORT)
  645. void plan_cubic_move(const float offset[4]);
  646. #endif
  647. void tool_change(const uint8_t tmp_extruder, const float fr_mm_s=0.0, bool no_move=false);
  648. void report_current_position();
  649. void report_current_position_detail();
  650. #if ENABLED(DEBUG_LEVELING_FEATURE)
  651. void print_xyz(const char* prefix, const char* suffix, const float x, const float y, const float z) {
  652. serialprintPGM(prefix);
  653. SERIAL_CHAR('(');
  654. SERIAL_ECHO(x);
  655. SERIAL_ECHOPAIR(", ", y);
  656. SERIAL_ECHOPAIR(", ", z);
  657. SERIAL_CHAR(')');
  658. if (suffix) serialprintPGM(suffix); else SERIAL_EOL();
  659. }
  660. void print_xyz(const char* prefix, const char* suffix, const float xyz[]) {
  661. print_xyz(prefix, suffix, xyz[X_AXIS], xyz[Y_AXIS], xyz[Z_AXIS]);
  662. }
  663. #if HAS_ABL
  664. void print_xyz(const char* prefix, const char* suffix, const vector_3 &xyz) {
  665. print_xyz(prefix, suffix, xyz.x, xyz.y, xyz.z);
  666. }
  667. #endif
  668. #define DEBUG_POS(SUFFIX,VAR) do { \
  669. print_xyz(PSTR(" " STRINGIFY(VAR) "="), PSTR(" : " SUFFIX "\n"), VAR); }while(0)
  670. #endif
  671. /**
  672. * sync_plan_position
  673. *
  674. * Set the planner/stepper positions directly from current_position with
  675. * no kinematic translation. Used for homing axes and cartesian/core syncing.
  676. */
  677. void sync_plan_position() {
  678. #if ENABLED(DEBUG_LEVELING_FEATURE)
  679. if (DEBUGGING(LEVELING)) DEBUG_POS("sync_plan_position", current_position);
  680. #endif
  681. planner.set_position_mm(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  682. }
  683. inline void sync_plan_position_e() { planner.set_e_position_mm(current_position[E_AXIS]); }
  684. #if IS_KINEMATIC
  685. inline void sync_plan_position_kinematic() {
  686. #if ENABLED(DEBUG_LEVELING_FEATURE)
  687. if (DEBUGGING(LEVELING)) DEBUG_POS("sync_plan_position_kinematic", current_position);
  688. #endif
  689. planner.set_position_mm_kinematic(current_position);
  690. }
  691. #define SYNC_PLAN_POSITION_KINEMATIC() sync_plan_position_kinematic()
  692. #else
  693. #define SYNC_PLAN_POSITION_KINEMATIC() sync_plan_position()
  694. #endif
  695. #if ENABLED(SDSUPPORT)
  696. #include "SdFatUtil.h"
  697. int freeMemory() { return SdFatUtil::FreeRam(); }
  698. #else
  699. extern "C" {
  700. extern char __bss_end;
  701. extern char __heap_start;
  702. extern void* __brkval;
  703. int freeMemory() {
  704. int free_memory;
  705. if ((int)__brkval == 0)
  706. free_memory = ((int)&free_memory) - ((int)&__bss_end);
  707. else
  708. free_memory = ((int)&free_memory) - ((int)__brkval);
  709. return free_memory;
  710. }
  711. }
  712. #endif // !SDSUPPORT
  713. #if ENABLED(DIGIPOT_I2C)
  714. extern void digipot_i2c_set_current(uint8_t channel, float current);
  715. extern void digipot_i2c_init();
  716. #endif
  717. /**
  718. * Inject the next "immediate" command, when possible, onto the front of the queue.
  719. * Return true if any immediate commands remain to inject.
  720. */
  721. static bool drain_injected_commands_P() {
  722. if (injected_commands_P != NULL) {
  723. size_t i = 0;
  724. char c, cmd[30];
  725. strncpy_P(cmd, injected_commands_P, sizeof(cmd) - 1);
  726. cmd[sizeof(cmd) - 1] = '\0';
  727. while ((c = cmd[i]) && c != '\n') i++; // find the end of this gcode command
  728. cmd[i] = '\0';
  729. if (enqueue_and_echo_command(cmd)) // success?
  730. injected_commands_P = c ? injected_commands_P + i + 1 : NULL; // next command or done
  731. }
  732. return (injected_commands_P != NULL); // return whether any more remain
  733. }
  734. /**
  735. * Record one or many commands to run from program memory.
  736. * Aborts the current queue, if any.
  737. * Note: drain_injected_commands_P() must be called repeatedly to drain the commands afterwards
  738. */
  739. void enqueue_and_echo_commands_P(const char * const pgcode) {
  740. injected_commands_P = pgcode;
  741. drain_injected_commands_P(); // first command executed asap (when possible)
  742. }
  743. /**
  744. * Clear the Marlin command queue
  745. */
  746. void clear_command_queue() {
  747. cmd_queue_index_r = cmd_queue_index_w;
  748. commands_in_queue = 0;
  749. }
  750. /**
  751. * Once a new command is in the ring buffer, call this to commit it
  752. */
  753. inline void _commit_command(bool say_ok) {
  754. send_ok[cmd_queue_index_w] = say_ok;
  755. if (++cmd_queue_index_w >= BUFSIZE) cmd_queue_index_w = 0;
  756. commands_in_queue++;
  757. }
  758. /**
  759. * Copy a command from RAM into the main command buffer.
  760. * Return true if the command was successfully added.
  761. * Return false for a full buffer, or if the 'command' is a comment.
  762. */
  763. inline bool _enqueuecommand(const char* cmd, bool say_ok=false) {
  764. if (*cmd == ';' || commands_in_queue >= BUFSIZE) return false;
  765. strcpy(command_queue[cmd_queue_index_w], cmd);
  766. _commit_command(say_ok);
  767. return true;
  768. }
  769. /**
  770. * Enqueue with Serial Echo
  771. */
  772. bool enqueue_and_echo_command(const char* cmd, bool say_ok/*=false*/) {
  773. if (_enqueuecommand(cmd, say_ok)) {
  774. SERIAL_ECHO_START();
  775. SERIAL_ECHOPAIR(MSG_ENQUEUEING, cmd);
  776. SERIAL_CHAR('"');
  777. SERIAL_EOL();
  778. return true;
  779. }
  780. return false;
  781. }
  782. void setup_killpin() {
  783. #if HAS_KILL
  784. SET_INPUT_PULLUP(KILL_PIN);
  785. #endif
  786. }
  787. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  788. void setup_filrunoutpin() {
  789. #if ENABLED(ENDSTOPPULLUP_FIL_RUNOUT)
  790. SET_INPUT_PULLUP(FIL_RUNOUT_PIN);
  791. #else
  792. SET_INPUT(FIL_RUNOUT_PIN);
  793. #endif
  794. }
  795. #endif
  796. void setup_powerhold() {
  797. #if HAS_SUICIDE
  798. OUT_WRITE(SUICIDE_PIN, HIGH);
  799. #endif
  800. #if HAS_POWER_SWITCH
  801. #if ENABLED(PS_DEFAULT_OFF)
  802. OUT_WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  803. #else
  804. OUT_WRITE(PS_ON_PIN, PS_ON_AWAKE);
  805. #endif
  806. #endif
  807. }
  808. void suicide() {
  809. #if HAS_SUICIDE
  810. OUT_WRITE(SUICIDE_PIN, LOW);
  811. #endif
  812. }
  813. void servo_init() {
  814. #if NUM_SERVOS >= 1 && HAS_SERVO_0
  815. servo[0].attach(SERVO0_PIN);
  816. servo[0].detach(); // Just set up the pin. We don't have a position yet. Don't move to a random position.
  817. #endif
  818. #if NUM_SERVOS >= 2 && HAS_SERVO_1
  819. servo[1].attach(SERVO1_PIN);
  820. servo[1].detach();
  821. #endif
  822. #if NUM_SERVOS >= 3 && HAS_SERVO_2
  823. servo[2].attach(SERVO2_PIN);
  824. servo[2].detach();
  825. #endif
  826. #if NUM_SERVOS >= 4 && HAS_SERVO_3
  827. servo[3].attach(SERVO3_PIN);
  828. servo[3].detach();
  829. #endif
  830. #if HAS_Z_SERVO_ENDSTOP
  831. /**
  832. * Set position of Z Servo Endstop
  833. *
  834. * The servo might be deployed and positioned too low to stow
  835. * when starting up the machine or rebooting the board.
  836. * There's no way to know where the nozzle is positioned until
  837. * homing has been done - no homing with z-probe without init!
  838. *
  839. */
  840. STOW_Z_SERVO();
  841. #endif
  842. }
  843. /**
  844. * Stepper Reset (RigidBoard, et.al.)
  845. */
  846. #if HAS_STEPPER_RESET
  847. void disableStepperDrivers() {
  848. OUT_WRITE(STEPPER_RESET_PIN, LOW); // drive it down to hold in reset motor driver chips
  849. }
  850. void enableStepperDrivers() { SET_INPUT(STEPPER_RESET_PIN); } // set to input, which allows it to be pulled high by pullups
  851. #endif
  852. #if ENABLED(EXPERIMENTAL_I2CBUS) && I2C_SLAVE_ADDRESS > 0
  853. void i2c_on_receive(int bytes) { // just echo all bytes received to serial
  854. i2c.receive(bytes);
  855. }
  856. void i2c_on_request() { // just send dummy data for now
  857. i2c.reply("Hello World!\n");
  858. }
  859. #endif
  860. #if HAS_COLOR_LEDS
  861. void set_led_color(
  862. const uint8_t r, const uint8_t g, const uint8_t b
  863. #if ENABLED(RGBW_LED)
  864. , const uint8_t w=0
  865. #endif
  866. ) {
  867. #if ENABLED(BLINKM)
  868. // This variant uses i2c to send the RGB components to the device.
  869. SendColors(r, g, b);
  870. #endif
  871. #if ENABLED(RGB_LED) || ENABLED(RGBW_LED)
  872. // This variant uses 3 separate pins for the RGB components.
  873. // If the pins can do PWM then their intensity will be set.
  874. WRITE(RGB_LED_R_PIN, r ? HIGH : LOW);
  875. WRITE(RGB_LED_G_PIN, g ? HIGH : LOW);
  876. WRITE(RGB_LED_B_PIN, b ? HIGH : LOW);
  877. analogWrite(RGB_LED_R_PIN, r);
  878. analogWrite(RGB_LED_G_PIN, g);
  879. analogWrite(RGB_LED_B_PIN, b);
  880. #if ENABLED(RGBW_LED)
  881. WRITE(RGB_LED_W_PIN, w ? HIGH : LOW);
  882. analogWrite(RGB_LED_W_PIN, w);
  883. #endif
  884. #endif
  885. #if ENABLED(PCA9632)
  886. // Update I2C LED driver
  887. PCA9632_SetColor(r, g, b);
  888. #endif
  889. }
  890. #endif // HAS_COLOR_LEDS
  891. void gcode_line_error(const char* err, bool doFlush = true) {
  892. SERIAL_ERROR_START();
  893. serialprintPGM(err);
  894. SERIAL_ERRORLN(gcode_LastN);
  895. //Serial.println(gcode_N);
  896. if (doFlush) FlushSerialRequestResend();
  897. serial_count = 0;
  898. }
  899. /**
  900. * Get all commands waiting on the serial port and queue them.
  901. * Exit when the buffer is full or when no more characters are
  902. * left on the serial port.
  903. */
  904. inline void get_serial_commands() {
  905. static char serial_line_buffer[MAX_CMD_SIZE];
  906. static bool serial_comment_mode = false;
  907. // If the command buffer is empty for too long,
  908. // send "wait" to indicate Marlin is still waiting.
  909. #if defined(NO_TIMEOUTS) && NO_TIMEOUTS > 0
  910. static millis_t last_command_time = 0;
  911. const millis_t ms = millis();
  912. if (commands_in_queue == 0 && !MYSERIAL.available() && ELAPSED(ms, last_command_time + NO_TIMEOUTS)) {
  913. SERIAL_ECHOLNPGM(MSG_WAIT);
  914. last_command_time = ms;
  915. }
  916. #endif
  917. /**
  918. * Loop while serial characters are incoming and the queue is not full
  919. */
  920. while (commands_in_queue < BUFSIZE && MYSERIAL.available() > 0) {
  921. char serial_char = MYSERIAL.read();
  922. /**
  923. * If the character ends the line
  924. */
  925. if (serial_char == '\n' || serial_char == '\r') {
  926. serial_comment_mode = false; // end of line == end of comment
  927. if (!serial_count) continue; // skip empty lines
  928. serial_line_buffer[serial_count] = 0; // terminate string
  929. serial_count = 0; //reset buffer
  930. char* command = serial_line_buffer;
  931. while (*command == ' ') command++; // skip any leading spaces
  932. char *npos = (*command == 'N') ? command : NULL, // Require the N parameter to start the line
  933. *apos = strchr(command, '*');
  934. if (npos) {
  935. bool M110 = strstr_P(command, PSTR("M110")) != NULL;
  936. if (M110) {
  937. char* n2pos = strchr(command + 4, 'N');
  938. if (n2pos) npos = n2pos;
  939. }
  940. gcode_N = strtol(npos + 1, NULL, 10);
  941. if (gcode_N != gcode_LastN + 1 && !M110) {
  942. gcode_line_error(PSTR(MSG_ERR_LINE_NO));
  943. return;
  944. }
  945. if (apos) {
  946. byte checksum = 0, count = 0;
  947. while (command[count] != '*') checksum ^= command[count++];
  948. if (strtol(apos + 1, NULL, 10) != checksum) {
  949. gcode_line_error(PSTR(MSG_ERR_CHECKSUM_MISMATCH));
  950. return;
  951. }
  952. // if no errors, continue parsing
  953. }
  954. else {
  955. gcode_line_error(PSTR(MSG_ERR_NO_CHECKSUM));
  956. return;
  957. }
  958. gcode_LastN = gcode_N;
  959. // if no errors, continue parsing
  960. }
  961. else if (apos) { // No '*' without 'N'
  962. gcode_line_error(PSTR(MSG_ERR_NO_LINENUMBER_WITH_CHECKSUM), false);
  963. return;
  964. }
  965. // Movement commands alert when stopped
  966. if (IsStopped()) {
  967. char* gpos = strchr(command, 'G');
  968. if (gpos) {
  969. const int codenum = strtol(gpos + 1, NULL, 10);
  970. switch (codenum) {
  971. case 0:
  972. case 1:
  973. case 2:
  974. case 3:
  975. SERIAL_ERRORLNPGM(MSG_ERR_STOPPED);
  976. LCD_MESSAGEPGM(MSG_STOPPED);
  977. break;
  978. }
  979. }
  980. }
  981. #if DISABLED(EMERGENCY_PARSER)
  982. // If command was e-stop process now
  983. if (strcmp(command, "M108") == 0) {
  984. wait_for_heatup = false;
  985. #if ENABLED(ULTIPANEL)
  986. wait_for_user = false;
  987. #endif
  988. }
  989. if (strcmp(command, "M112") == 0) kill(PSTR(MSG_KILLED));
  990. if (strcmp(command, "M410") == 0) { quickstop_stepper(); }
  991. #endif
  992. #if defined(NO_TIMEOUTS) && NO_TIMEOUTS > 0
  993. last_command_time = ms;
  994. #endif
  995. // Add the command to the queue
  996. _enqueuecommand(serial_line_buffer, true);
  997. }
  998. else if (serial_count >= MAX_CMD_SIZE - 1) {
  999. // Keep fetching, but ignore normal characters beyond the max length
  1000. // The command will be injected when EOL is reached
  1001. }
  1002. else if (serial_char == '\\') { // Handle escapes
  1003. if (MYSERIAL.available() > 0) {
  1004. // if we have one more character, copy it over
  1005. serial_char = MYSERIAL.read();
  1006. if (!serial_comment_mode) serial_line_buffer[serial_count++] = serial_char;
  1007. }
  1008. // otherwise do nothing
  1009. }
  1010. else { // it's not a newline, carriage return or escape char
  1011. if (serial_char == ';') serial_comment_mode = true;
  1012. if (!serial_comment_mode) serial_line_buffer[serial_count++] = serial_char;
  1013. }
  1014. } // queue has space, serial has data
  1015. }
  1016. #if ENABLED(SDSUPPORT)
  1017. /**
  1018. * Get commands from the SD Card until the command buffer is full
  1019. * or until the end of the file is reached. The special character '#'
  1020. * can also interrupt buffering.
  1021. */
  1022. inline void get_sdcard_commands() {
  1023. static bool stop_buffering = false,
  1024. sd_comment_mode = false;
  1025. if (!card.sdprinting) return;
  1026. /**
  1027. * '#' stops reading from SD to the buffer prematurely, so procedural
  1028. * macro calls are possible. If it occurs, stop_buffering is triggered
  1029. * and the buffer is run dry; this character _can_ occur in serial com
  1030. * due to checksums, however, no checksums are used in SD printing.
  1031. */
  1032. if (commands_in_queue == 0) stop_buffering = false;
  1033. uint16_t sd_count = 0;
  1034. bool card_eof = card.eof();
  1035. while (commands_in_queue < BUFSIZE && !card_eof && !stop_buffering) {
  1036. const int16_t n = card.get();
  1037. char sd_char = (char)n;
  1038. card_eof = card.eof();
  1039. if (card_eof || n == -1
  1040. || sd_char == '\n' || sd_char == '\r'
  1041. || ((sd_char == '#' || sd_char == ':') && !sd_comment_mode)
  1042. ) {
  1043. if (card_eof) {
  1044. SERIAL_PROTOCOLLNPGM(MSG_FILE_PRINTED);
  1045. card.printingHasFinished();
  1046. #if ENABLED(PRINTER_EVENT_LEDS)
  1047. LCD_MESSAGEPGM(MSG_INFO_COMPLETED_PRINTS);
  1048. set_led_color(0, 255, 0); // Green
  1049. #if HAS_RESUME_CONTINUE
  1050. enqueue_and_echo_commands_P(PSTR("M0")); // end of the queue!
  1051. #else
  1052. safe_delay(1000);
  1053. #endif
  1054. set_led_color(0, 0, 0); // OFF
  1055. #endif
  1056. card.checkautostart(true);
  1057. }
  1058. else if (n == -1) {
  1059. SERIAL_ERROR_START();
  1060. SERIAL_ECHOLNPGM(MSG_SD_ERR_READ);
  1061. }
  1062. if (sd_char == '#') stop_buffering = true;
  1063. sd_comment_mode = false; // for new command
  1064. if (!sd_count) continue; // skip empty lines (and comment lines)
  1065. command_queue[cmd_queue_index_w][sd_count] = '\0'; // terminate string
  1066. sd_count = 0; // clear sd line buffer
  1067. _commit_command(false);
  1068. }
  1069. else if (sd_count >= MAX_CMD_SIZE - 1) {
  1070. /**
  1071. * Keep fetching, but ignore normal characters beyond the max length
  1072. * The command will be injected when EOL is reached
  1073. */
  1074. }
  1075. else {
  1076. if (sd_char == ';') sd_comment_mode = true;
  1077. if (!sd_comment_mode) command_queue[cmd_queue_index_w][sd_count++] = sd_char;
  1078. }
  1079. }
  1080. }
  1081. #endif // SDSUPPORT
  1082. /**
  1083. * Add to the circular command queue the next command from:
  1084. * - The command-injection queue (injected_commands_P)
  1085. * - The active serial input (usually USB)
  1086. * - The SD card file being actively printed
  1087. */
  1088. void get_available_commands() {
  1089. // if any immediate commands remain, don't get other commands yet
  1090. if (drain_injected_commands_P()) return;
  1091. get_serial_commands();
  1092. #if ENABLED(SDSUPPORT)
  1093. get_sdcard_commands();
  1094. #endif
  1095. }
  1096. /**
  1097. * Set target_extruder from the T parameter or the active_extruder
  1098. *
  1099. * Returns TRUE if the target is invalid
  1100. */
  1101. bool get_target_extruder_from_command(const uint16_t code) {
  1102. if (parser.seenval('T')) {
  1103. const int8_t e = parser.value_byte();
  1104. if (e >= EXTRUDERS) {
  1105. SERIAL_ECHO_START();
  1106. SERIAL_CHAR('M');
  1107. SERIAL_ECHO(code);
  1108. SERIAL_ECHOLNPAIR(" " MSG_INVALID_EXTRUDER " ", e);
  1109. return true;
  1110. }
  1111. target_extruder = e;
  1112. }
  1113. else
  1114. target_extruder = active_extruder;
  1115. return false;
  1116. }
  1117. #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(DUAL_NOZZLE_DUPLICATION_MODE)
  1118. bool extruder_duplication_enabled = false; // Used in Dual X mode 2
  1119. #endif
  1120. #if ENABLED(DUAL_X_CARRIAGE)
  1121. static DualXMode dual_x_carriage_mode = DEFAULT_DUAL_X_CARRIAGE_MODE;
  1122. static float x_home_pos(const int extruder) {
  1123. if (extruder == 0)
  1124. return LOGICAL_X_POSITION(base_home_pos(X_AXIS));
  1125. else
  1126. /**
  1127. * In dual carriage mode the extruder offset provides an override of the
  1128. * second X-carriage position when homed - otherwise X2_HOME_POS is used.
  1129. * This allows soft recalibration of the second extruder home position
  1130. * without firmware reflash (through the M218 command).
  1131. */
  1132. return LOGICAL_X_POSITION(hotend_offset[X_AXIS][1] > 0 ? hotend_offset[X_AXIS][1] : X2_HOME_POS);
  1133. }
  1134. static int x_home_dir(const int extruder) { return extruder ? X2_HOME_DIR : X_HOME_DIR; }
  1135. static float inactive_extruder_x_pos = X2_MAX_POS; // used in mode 0 & 1
  1136. static bool active_extruder_parked = false; // used in mode 1 & 2
  1137. static float raised_parked_position[XYZE]; // used in mode 1
  1138. static millis_t delayed_move_time = 0; // used in mode 1
  1139. static float duplicate_extruder_x_offset = DEFAULT_DUPLICATION_X_OFFSET; // used in mode 2
  1140. static int16_t duplicate_extruder_temp_offset = 0; // used in mode 2
  1141. #endif // DUAL_X_CARRIAGE
  1142. #if HAS_WORKSPACE_OFFSET || ENABLED(DUAL_X_CARRIAGE)
  1143. /**
  1144. * Software endstops can be used to monitor the open end of
  1145. * an axis that has a hardware endstop on the other end. Or
  1146. * they can prevent axes from moving past endstops and grinding.
  1147. *
  1148. * To keep doing their job as the coordinate system changes,
  1149. * the software endstop positions must be refreshed to remain
  1150. * at the same positions relative to the machine.
  1151. */
  1152. void update_software_endstops(const AxisEnum axis) {
  1153. const float offs = 0.0
  1154. #if HAS_HOME_OFFSET
  1155. + home_offset[axis]
  1156. #endif
  1157. #if HAS_POSITION_SHIFT
  1158. + position_shift[axis]
  1159. #endif
  1160. ;
  1161. #if HAS_HOME_OFFSET && HAS_POSITION_SHIFT
  1162. workspace_offset[axis] = offs;
  1163. #endif
  1164. #if ENABLED(DUAL_X_CARRIAGE)
  1165. if (axis == X_AXIS) {
  1166. // In Dual X mode hotend_offset[X] is T1's home position
  1167. float dual_max_x = max(hotend_offset[X_AXIS][1], X2_MAX_POS);
  1168. if (active_extruder != 0) {
  1169. // T1 can move from X2_MIN_POS to X2_MAX_POS or X2 home position (whichever is larger)
  1170. soft_endstop_min[X_AXIS] = X2_MIN_POS + offs;
  1171. soft_endstop_max[X_AXIS] = dual_max_x + offs;
  1172. }
  1173. else if (dual_x_carriage_mode == DXC_DUPLICATION_MODE) {
  1174. // In Duplication Mode, T0 can move as far left as X_MIN_POS
  1175. // but not so far to the right that T1 would move past the end
  1176. soft_endstop_min[X_AXIS] = base_min_pos(X_AXIS) + offs;
  1177. soft_endstop_max[X_AXIS] = min(base_max_pos(X_AXIS), dual_max_x - duplicate_extruder_x_offset) + offs;
  1178. }
  1179. else {
  1180. // In other modes, T0 can move from X_MIN_POS to X_MAX_POS
  1181. soft_endstop_min[axis] = base_min_pos(axis) + offs;
  1182. soft_endstop_max[axis] = base_max_pos(axis) + offs;
  1183. }
  1184. }
  1185. #else
  1186. soft_endstop_min[axis] = base_min_pos(axis) + offs;
  1187. soft_endstop_max[axis] = base_max_pos(axis) + offs;
  1188. #endif
  1189. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1190. if (DEBUGGING(LEVELING)) {
  1191. SERIAL_ECHOPAIR("For ", axis_codes[axis]);
  1192. #if HAS_HOME_OFFSET
  1193. SERIAL_ECHOPAIR(" axis:\n home_offset = ", home_offset[axis]);
  1194. #endif
  1195. #if HAS_POSITION_SHIFT
  1196. SERIAL_ECHOPAIR("\n position_shift = ", position_shift[axis]);
  1197. #endif
  1198. SERIAL_ECHOPAIR("\n soft_endstop_min = ", soft_endstop_min[axis]);
  1199. SERIAL_ECHOLNPAIR("\n soft_endstop_max = ", soft_endstop_max[axis]);
  1200. }
  1201. #endif
  1202. #if ENABLED(DELTA)
  1203. if (axis == Z_AXIS)
  1204. delta_clip_start_height = soft_endstop_max[axis] - delta_safe_distance_from_top();
  1205. #endif
  1206. }
  1207. #endif // HAS_WORKSPACE_OFFSET || DUAL_X_CARRIAGE
  1208. #if HAS_M206_COMMAND
  1209. /**
  1210. * Change the home offset for an axis, update the current
  1211. * position and the software endstops to retain the same
  1212. * relative distance to the new home.
  1213. *
  1214. * Since this changes the current_position, code should
  1215. * call sync_plan_position soon after this.
  1216. */
  1217. static void set_home_offset(const AxisEnum axis, const float v) {
  1218. current_position[axis] += v - home_offset[axis];
  1219. home_offset[axis] = v;
  1220. update_software_endstops(axis);
  1221. }
  1222. #endif // HAS_M206_COMMAND
  1223. /**
  1224. * Set an axis' current position to its home position (after homing).
  1225. *
  1226. * For Core and Cartesian robots this applies one-to-one when an
  1227. * individual axis has been homed.
  1228. *
  1229. * DELTA should wait until all homing is done before setting the XYZ
  1230. * current_position to home, because homing is a single operation.
  1231. * In the case where the axis positions are already known and previously
  1232. * homed, DELTA could home to X or Y individually by moving either one
  1233. * to the center. However, homing Z always homes XY and Z.
  1234. *
  1235. * SCARA should wait until all XY homing is done before setting the XY
  1236. * current_position to home, because neither X nor Y is at home until
  1237. * both are at home. Z can however be homed individually.
  1238. *
  1239. * Callers must sync the planner position after calling this!
  1240. */
  1241. static void set_axis_is_at_home(const AxisEnum axis) {
  1242. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1243. if (DEBUGGING(LEVELING)) {
  1244. SERIAL_ECHOPAIR(">>> set_axis_is_at_home(", axis_codes[axis]);
  1245. SERIAL_CHAR(')');
  1246. SERIAL_EOL();
  1247. }
  1248. #endif
  1249. axis_known_position[axis] = axis_homed[axis] = true;
  1250. #if HAS_POSITION_SHIFT
  1251. position_shift[axis] = 0;
  1252. update_software_endstops(axis);
  1253. #endif
  1254. #if ENABLED(DUAL_X_CARRIAGE)
  1255. if (axis == X_AXIS && (active_extruder == 1 || dual_x_carriage_mode == DXC_DUPLICATION_MODE)) {
  1256. current_position[X_AXIS] = x_home_pos(active_extruder);
  1257. return;
  1258. }
  1259. #endif
  1260. #if ENABLED(MORGAN_SCARA)
  1261. /**
  1262. * Morgan SCARA homes XY at the same time
  1263. */
  1264. if (axis == X_AXIS || axis == Y_AXIS) {
  1265. float homeposition[XYZ];
  1266. LOOP_XYZ(i) homeposition[i] = LOGICAL_POSITION(base_home_pos((AxisEnum)i), i);
  1267. // SERIAL_ECHOPAIR("homeposition X:", homeposition[X_AXIS]);
  1268. // SERIAL_ECHOLNPAIR(" Y:", homeposition[Y_AXIS]);
  1269. /**
  1270. * Get Home position SCARA arm angles using inverse kinematics,
  1271. * and calculate homing offset using forward kinematics
  1272. */
  1273. inverse_kinematics(homeposition);
  1274. forward_kinematics_SCARA(delta[A_AXIS], delta[B_AXIS]);
  1275. // SERIAL_ECHOPAIR("Cartesian X:", cartes[X_AXIS]);
  1276. // SERIAL_ECHOLNPAIR(" Y:", cartes[Y_AXIS]);
  1277. current_position[axis] = LOGICAL_POSITION(cartes[axis], axis);
  1278. /**
  1279. * SCARA home positions are based on configuration since the actual
  1280. * limits are determined by the inverse kinematic transform.
  1281. */
  1282. soft_endstop_min[axis] = base_min_pos(axis); // + (cartes[axis] - base_home_pos(axis));
  1283. soft_endstop_max[axis] = base_max_pos(axis); // + (cartes[axis] - base_home_pos(axis));
  1284. }
  1285. else
  1286. #endif
  1287. {
  1288. current_position[axis] = LOGICAL_POSITION(base_home_pos(axis), axis);
  1289. }
  1290. /**
  1291. * Z Probe Z Homing? Account for the probe's Z offset.
  1292. */
  1293. #if HAS_BED_PROBE && Z_HOME_DIR < 0
  1294. if (axis == Z_AXIS) {
  1295. #if HOMING_Z_WITH_PROBE
  1296. current_position[Z_AXIS] -= zprobe_zoffset;
  1297. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1298. if (DEBUGGING(LEVELING)) {
  1299. SERIAL_ECHOLNPGM("*** Z HOMED WITH PROBE (Z_MIN_PROBE_USES_Z_MIN_ENDSTOP_PIN) ***");
  1300. SERIAL_ECHOLNPAIR("> zprobe_zoffset = ", zprobe_zoffset);
  1301. }
  1302. #endif
  1303. #elif ENABLED(DEBUG_LEVELING_FEATURE)
  1304. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("*** Z HOMED TO ENDSTOP (Z_MIN_PROBE_ENDSTOP) ***");
  1305. #endif
  1306. }
  1307. #endif
  1308. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1309. if (DEBUGGING(LEVELING)) {
  1310. #if HAS_HOME_OFFSET
  1311. SERIAL_ECHOPAIR("> home_offset[", axis_codes[axis]);
  1312. SERIAL_ECHOLNPAIR("] = ", home_offset[axis]);
  1313. #endif
  1314. DEBUG_POS("", current_position);
  1315. SERIAL_ECHOPAIR("<<< set_axis_is_at_home(", axis_codes[axis]);
  1316. SERIAL_CHAR(')');
  1317. SERIAL_EOL();
  1318. }
  1319. #endif
  1320. #if ENABLED(I2C_POSITION_ENCODERS)
  1321. I2CPEM.homed(axis);
  1322. #endif
  1323. }
  1324. /**
  1325. * Some planner shorthand inline functions
  1326. */
  1327. inline float get_homing_bump_feedrate(const AxisEnum axis) {
  1328. static const uint8_t homing_bump_divisor[] PROGMEM = HOMING_BUMP_DIVISOR;
  1329. uint8_t hbd = pgm_read_byte(&homing_bump_divisor[axis]);
  1330. if (hbd < 1) {
  1331. hbd = 10;
  1332. SERIAL_ECHO_START();
  1333. SERIAL_ECHOLNPGM("Warning: Homing Bump Divisor < 1");
  1334. }
  1335. return homing_feedrate(axis) / hbd;
  1336. }
  1337. /**
  1338. * Move the planner to the current position from wherever it last moved
  1339. * (or from wherever it has been told it is located).
  1340. */
  1341. inline void line_to_current_position() {
  1342. planner.buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], feedrate_mm_s, active_extruder);
  1343. }
  1344. /**
  1345. * Move the planner to the position stored in the destination array, which is
  1346. * used by G0/G1/G2/G3/G5 and many other functions to set a destination.
  1347. */
  1348. inline void line_to_destination(const float fr_mm_s) {
  1349. planner.buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], fr_mm_s, active_extruder);
  1350. }
  1351. inline void line_to_destination() { line_to_destination(feedrate_mm_s); }
  1352. inline void set_current_to_destination() { COPY(current_position, destination); }
  1353. inline void set_destination_to_current() { COPY(destination, current_position); }
  1354. #if IS_KINEMATIC
  1355. /**
  1356. * Calculate delta, start a line, and set current_position to destination
  1357. */
  1358. void prepare_uninterpolated_move_to_destination(const float fr_mm_s=0.0) {
  1359. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1360. if (DEBUGGING(LEVELING)) DEBUG_POS("prepare_uninterpolated_move_to_destination", destination);
  1361. #endif
  1362. refresh_cmd_timeout();
  1363. #if UBL_DELTA
  1364. // ubl segmented line will do z-only moves in single segment
  1365. ubl.prepare_segmented_line_to(destination, MMS_SCALED(fr_mm_s ? fr_mm_s : feedrate_mm_s));
  1366. #else
  1367. if ( current_position[X_AXIS] == destination[X_AXIS]
  1368. && current_position[Y_AXIS] == destination[Y_AXIS]
  1369. && current_position[Z_AXIS] == destination[Z_AXIS]
  1370. && current_position[E_AXIS] == destination[E_AXIS]
  1371. ) return;
  1372. planner.buffer_line_kinematic(destination, MMS_SCALED(fr_mm_s ? fr_mm_s : feedrate_mm_s), active_extruder);
  1373. #endif
  1374. set_current_to_destination();
  1375. }
  1376. #endif // IS_KINEMATIC
  1377. /**
  1378. * Plan a move to (X, Y, Z) and set the current_position
  1379. * The final current_position may not be the one that was requested
  1380. */
  1381. void do_blocking_move_to(const float &lx, const float &ly, const float &lz, const float &fr_mm_s/*=0.0*/) {
  1382. const float old_feedrate_mm_s = feedrate_mm_s;
  1383. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1384. if (DEBUGGING(LEVELING)) print_xyz(PSTR(">>> do_blocking_move_to"), NULL, lx, ly, lz);
  1385. #endif
  1386. #if ENABLED(DELTA)
  1387. if (!position_is_reachable_xy(lx, ly)) return;
  1388. feedrate_mm_s = fr_mm_s ? fr_mm_s : XY_PROBE_FEEDRATE_MM_S;
  1389. set_destination_to_current(); // sync destination at the start
  1390. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1391. if (DEBUGGING(LEVELING)) DEBUG_POS("set_destination_to_current", destination);
  1392. #endif
  1393. // when in the danger zone
  1394. if (current_position[Z_AXIS] > delta_clip_start_height) {
  1395. if (lz > delta_clip_start_height) { // staying in the danger zone
  1396. destination[X_AXIS] = lx; // move directly (uninterpolated)
  1397. destination[Y_AXIS] = ly;
  1398. destination[Z_AXIS] = lz;
  1399. prepare_uninterpolated_move_to_destination(); // set_current_to_destination
  1400. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1401. if (DEBUGGING(LEVELING)) DEBUG_POS("danger zone move", current_position);
  1402. #endif
  1403. return;
  1404. }
  1405. else {
  1406. destination[Z_AXIS] = delta_clip_start_height;
  1407. prepare_uninterpolated_move_to_destination(); // set_current_to_destination
  1408. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1409. if (DEBUGGING(LEVELING)) DEBUG_POS("zone border move", current_position);
  1410. #endif
  1411. }
  1412. }
  1413. if (lz > current_position[Z_AXIS]) { // raising?
  1414. destination[Z_AXIS] = lz;
  1415. prepare_uninterpolated_move_to_destination(); // set_current_to_destination
  1416. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1417. if (DEBUGGING(LEVELING)) DEBUG_POS("z raise move", current_position);
  1418. #endif
  1419. }
  1420. destination[X_AXIS] = lx;
  1421. destination[Y_AXIS] = ly;
  1422. prepare_move_to_destination(); // set_current_to_destination
  1423. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1424. if (DEBUGGING(LEVELING)) DEBUG_POS("xy move", current_position);
  1425. #endif
  1426. if (lz < current_position[Z_AXIS]) { // lowering?
  1427. destination[Z_AXIS] = lz;
  1428. prepare_uninterpolated_move_to_destination(); // set_current_to_destination
  1429. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1430. if (DEBUGGING(LEVELING)) DEBUG_POS("z lower move", current_position);
  1431. #endif
  1432. }
  1433. #elif IS_SCARA
  1434. if (!position_is_reachable_xy(lx, ly)) return;
  1435. set_destination_to_current();
  1436. // If Z needs to raise, do it before moving XY
  1437. if (destination[Z_AXIS] < lz) {
  1438. destination[Z_AXIS] = lz;
  1439. prepare_uninterpolated_move_to_destination(fr_mm_s ? fr_mm_s : homing_feedrate(Z_AXIS));
  1440. }
  1441. destination[X_AXIS] = lx;
  1442. destination[Y_AXIS] = ly;
  1443. prepare_uninterpolated_move_to_destination(fr_mm_s ? fr_mm_s : XY_PROBE_FEEDRATE_MM_S);
  1444. // If Z needs to lower, do it after moving XY
  1445. if (destination[Z_AXIS] > lz) {
  1446. destination[Z_AXIS] = lz;
  1447. prepare_uninterpolated_move_to_destination(fr_mm_s ? fr_mm_s : homing_feedrate(Z_AXIS));
  1448. }
  1449. #else
  1450. // If Z needs to raise, do it before moving XY
  1451. if (current_position[Z_AXIS] < lz) {
  1452. feedrate_mm_s = fr_mm_s ? fr_mm_s : homing_feedrate(Z_AXIS);
  1453. current_position[Z_AXIS] = lz;
  1454. line_to_current_position();
  1455. }
  1456. feedrate_mm_s = fr_mm_s ? fr_mm_s : XY_PROBE_FEEDRATE_MM_S;
  1457. current_position[X_AXIS] = lx;
  1458. current_position[Y_AXIS] = ly;
  1459. line_to_current_position();
  1460. // If Z needs to lower, do it after moving XY
  1461. if (current_position[Z_AXIS] > lz) {
  1462. feedrate_mm_s = fr_mm_s ? fr_mm_s : homing_feedrate(Z_AXIS);
  1463. current_position[Z_AXIS] = lz;
  1464. line_to_current_position();
  1465. }
  1466. #endif
  1467. stepper.synchronize();
  1468. feedrate_mm_s = old_feedrate_mm_s;
  1469. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1470. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< do_blocking_move_to");
  1471. #endif
  1472. }
  1473. void do_blocking_move_to_x(const float &lx, const float &fr_mm_s/*=0.0*/) {
  1474. do_blocking_move_to(lx, current_position[Y_AXIS], current_position[Z_AXIS], fr_mm_s);
  1475. }
  1476. void do_blocking_move_to_z(const float &lz, const float &fr_mm_s/*=0.0*/) {
  1477. do_blocking_move_to(current_position[X_AXIS], current_position[Y_AXIS], lz, fr_mm_s);
  1478. }
  1479. void do_blocking_move_to_xy(const float &lx, const float &ly, const float &fr_mm_s/*=0.0*/) {
  1480. do_blocking_move_to(lx, ly, current_position[Z_AXIS], fr_mm_s);
  1481. }
  1482. //
  1483. // Prepare to do endstop or probe moves
  1484. // with custom feedrates.
  1485. //
  1486. // - Save current feedrates
  1487. // - Reset the rate multiplier
  1488. // - Reset the command timeout
  1489. // - Enable the endstops (for endstop moves)
  1490. //
  1491. static void setup_for_endstop_or_probe_move() {
  1492. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1493. if (DEBUGGING(LEVELING)) DEBUG_POS("setup_for_endstop_or_probe_move", current_position);
  1494. #endif
  1495. saved_feedrate_mm_s = feedrate_mm_s;
  1496. saved_feedrate_percentage = feedrate_percentage;
  1497. feedrate_percentage = 100;
  1498. refresh_cmd_timeout();
  1499. }
  1500. static void clean_up_after_endstop_or_probe_move() {
  1501. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1502. if (DEBUGGING(LEVELING)) DEBUG_POS("clean_up_after_endstop_or_probe_move", current_position);
  1503. #endif
  1504. feedrate_mm_s = saved_feedrate_mm_s;
  1505. feedrate_percentage = saved_feedrate_percentage;
  1506. refresh_cmd_timeout();
  1507. }
  1508. #if HAS_BED_PROBE
  1509. /**
  1510. * Raise Z to a minimum height to make room for a probe to move
  1511. */
  1512. inline void do_probe_raise(const float z_raise) {
  1513. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1514. if (DEBUGGING(LEVELING)) {
  1515. SERIAL_ECHOPAIR("do_probe_raise(", z_raise);
  1516. SERIAL_CHAR(')');
  1517. SERIAL_EOL();
  1518. }
  1519. #endif
  1520. float z_dest = LOGICAL_Z_POSITION(z_raise);
  1521. if (zprobe_zoffset < 0) z_dest -= zprobe_zoffset;
  1522. #if ENABLED(DELTA)
  1523. z_dest -= home_offset[Z_AXIS]; // Account for delta height adjustment
  1524. #endif
  1525. if (z_dest > current_position[Z_AXIS])
  1526. do_blocking_move_to_z(z_dest);
  1527. }
  1528. #endif // HAS_BED_PROBE
  1529. #if HAS_PROBING_PROCEDURE || HOTENDS > 1 || ENABLED(Z_PROBE_ALLEN_KEY) || ENABLED(Z_PROBE_SLED) || ENABLED(NOZZLE_CLEAN_FEATURE) || ENABLED(NOZZLE_PARK_FEATURE) || ENABLED(DELTA_AUTO_CALIBRATION)
  1530. bool axis_unhomed_error(const bool x/*=true*/, const bool y/*=true*/, const bool z/*=true*/) {
  1531. #if ENABLED(HOME_AFTER_DEACTIVATE)
  1532. const bool xx = x && !axis_known_position[X_AXIS],
  1533. yy = y && !axis_known_position[Y_AXIS],
  1534. zz = z && !axis_known_position[Z_AXIS];
  1535. #else
  1536. const bool xx = x && !axis_homed[X_AXIS],
  1537. yy = y && !axis_homed[Y_AXIS],
  1538. zz = z && !axis_homed[Z_AXIS];
  1539. #endif
  1540. if (xx || yy || zz) {
  1541. SERIAL_ECHO_START();
  1542. SERIAL_ECHOPGM(MSG_HOME " ");
  1543. if (xx) SERIAL_ECHOPGM(MSG_X);
  1544. if (yy) SERIAL_ECHOPGM(MSG_Y);
  1545. if (zz) SERIAL_ECHOPGM(MSG_Z);
  1546. SERIAL_ECHOLNPGM(" " MSG_FIRST);
  1547. #if ENABLED(ULTRA_LCD)
  1548. lcd_status_printf_P(0, PSTR(MSG_HOME " %s%s%s " MSG_FIRST), xx ? MSG_X : "", yy ? MSG_Y : "", zz ? MSG_Z : "");
  1549. #endif
  1550. return true;
  1551. }
  1552. return false;
  1553. }
  1554. #endif
  1555. #if ENABLED(Z_PROBE_SLED)
  1556. #ifndef SLED_DOCKING_OFFSET
  1557. #define SLED_DOCKING_OFFSET 0
  1558. #endif
  1559. /**
  1560. * Method to dock/undock a sled designed by Charles Bell.
  1561. *
  1562. * stow[in] If false, move to MAX_X and engage the solenoid
  1563. * If true, move to MAX_X and release the solenoid
  1564. */
  1565. static void dock_sled(bool stow) {
  1566. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1567. if (DEBUGGING(LEVELING)) {
  1568. SERIAL_ECHOPAIR("dock_sled(", stow);
  1569. SERIAL_CHAR(')');
  1570. SERIAL_EOL();
  1571. }
  1572. #endif
  1573. // Dock sled a bit closer to ensure proper capturing
  1574. do_blocking_move_to_x(X_MAX_POS + SLED_DOCKING_OFFSET - ((stow) ? 1 : 0));
  1575. #if HAS_SOLENOID_1 && DISABLED(EXT_SOLENOID)
  1576. WRITE(SOL1_PIN, !stow); // switch solenoid
  1577. #endif
  1578. }
  1579. #elif ENABLED(Z_PROBE_ALLEN_KEY)
  1580. FORCE_INLINE void do_blocking_move_to(const float logical[XYZ], const float &fr_mm_s) {
  1581. do_blocking_move_to(logical[X_AXIS], logical[Y_AXIS], logical[Z_AXIS], fr_mm_s);
  1582. }
  1583. void run_deploy_moves_script() {
  1584. #if defined(Z_PROBE_ALLEN_KEY_DEPLOY_1_X) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_1_Y) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_1_Z)
  1585. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_X
  1586. #define Z_PROBE_ALLEN_KEY_DEPLOY_1_X current_position[X_AXIS]
  1587. #endif
  1588. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_Y
  1589. #define Z_PROBE_ALLEN_KEY_DEPLOY_1_Y current_position[Y_AXIS]
  1590. #endif
  1591. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_Z
  1592. #define Z_PROBE_ALLEN_KEY_DEPLOY_1_Z current_position[Z_AXIS]
  1593. #endif
  1594. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_FEEDRATE
  1595. #define Z_PROBE_ALLEN_KEY_DEPLOY_1_FEEDRATE 0.0
  1596. #endif
  1597. const float deploy_1[] = { Z_PROBE_ALLEN_KEY_DEPLOY_1_X, Z_PROBE_ALLEN_KEY_DEPLOY_1_Y, Z_PROBE_ALLEN_KEY_DEPLOY_1_Z };
  1598. do_blocking_move_to(deploy_1, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_1_FEEDRATE));
  1599. #endif
  1600. #if defined(Z_PROBE_ALLEN_KEY_DEPLOY_2_X) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_2_Y) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_2_Z)
  1601. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_X
  1602. #define Z_PROBE_ALLEN_KEY_DEPLOY_2_X current_position[X_AXIS]
  1603. #endif
  1604. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_Y
  1605. #define Z_PROBE_ALLEN_KEY_DEPLOY_2_Y current_position[Y_AXIS]
  1606. #endif
  1607. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_Z
  1608. #define Z_PROBE_ALLEN_KEY_DEPLOY_2_Z current_position[Z_AXIS]
  1609. #endif
  1610. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE
  1611. #define Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE 0.0
  1612. #endif
  1613. const float deploy_2[] = { Z_PROBE_ALLEN_KEY_DEPLOY_2_X, Z_PROBE_ALLEN_KEY_DEPLOY_2_Y, Z_PROBE_ALLEN_KEY_DEPLOY_2_Z };
  1614. do_blocking_move_to(deploy_2, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE));
  1615. #endif
  1616. #if defined(Z_PROBE_ALLEN_KEY_DEPLOY_3_X) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_3_Y) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_3_Z)
  1617. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_X
  1618. #define Z_PROBE_ALLEN_KEY_DEPLOY_3_X current_position[X_AXIS]
  1619. #endif
  1620. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_Y
  1621. #define Z_PROBE_ALLEN_KEY_DEPLOY_3_Y current_position[Y_AXIS]
  1622. #endif
  1623. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_Z
  1624. #define Z_PROBE_ALLEN_KEY_DEPLOY_3_Z current_position[Z_AXIS]
  1625. #endif
  1626. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE
  1627. #define Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE 0.0
  1628. #endif
  1629. const float deploy_3[] = { Z_PROBE_ALLEN_KEY_DEPLOY_3_X, Z_PROBE_ALLEN_KEY_DEPLOY_3_Y, Z_PROBE_ALLEN_KEY_DEPLOY_3_Z };
  1630. do_blocking_move_to(deploy_3, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE));
  1631. #endif
  1632. #if defined(Z_PROBE_ALLEN_KEY_DEPLOY_4_X) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_4_Y) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_4_Z)
  1633. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_X
  1634. #define Z_PROBE_ALLEN_KEY_DEPLOY_4_X current_position[X_AXIS]
  1635. #endif
  1636. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_Y
  1637. #define Z_PROBE_ALLEN_KEY_DEPLOY_4_Y current_position[Y_AXIS]
  1638. #endif
  1639. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_Z
  1640. #define Z_PROBE_ALLEN_KEY_DEPLOY_4_Z current_position[Z_AXIS]
  1641. #endif
  1642. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_FEEDRATE
  1643. #define Z_PROBE_ALLEN_KEY_DEPLOY_4_FEEDRATE 0.0
  1644. #endif
  1645. const float deploy_4[] = { Z_PROBE_ALLEN_KEY_DEPLOY_4_X, Z_PROBE_ALLEN_KEY_DEPLOY_4_Y, Z_PROBE_ALLEN_KEY_DEPLOY_4_Z };
  1646. do_blocking_move_to(deploy_4, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_4_FEEDRATE));
  1647. #endif
  1648. #if defined(Z_PROBE_ALLEN_KEY_DEPLOY_5_X) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_5_Y) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_5_Z)
  1649. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_X
  1650. #define Z_PROBE_ALLEN_KEY_DEPLOY_5_X current_position[X_AXIS]
  1651. #endif
  1652. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_Y
  1653. #define Z_PROBE_ALLEN_KEY_DEPLOY_5_Y current_position[Y_AXIS]
  1654. #endif
  1655. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_Z
  1656. #define Z_PROBE_ALLEN_KEY_DEPLOY_5_Z current_position[Z_AXIS]
  1657. #endif
  1658. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_FEEDRATE
  1659. #define Z_PROBE_ALLEN_KEY_DEPLOY_5_FEEDRATE 0.0
  1660. #endif
  1661. const float deploy_5[] = { Z_PROBE_ALLEN_KEY_DEPLOY_5_X, Z_PROBE_ALLEN_KEY_DEPLOY_5_Y, Z_PROBE_ALLEN_KEY_DEPLOY_5_Z };
  1662. do_blocking_move_to(deploy_5, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_5_FEEDRATE));
  1663. #endif
  1664. }
  1665. void run_stow_moves_script() {
  1666. #if defined(Z_PROBE_ALLEN_KEY_STOW_1_X) || defined(Z_PROBE_ALLEN_KEY_STOW_1_Y) || defined(Z_PROBE_ALLEN_KEY_STOW_1_Z)
  1667. #ifndef Z_PROBE_ALLEN_KEY_STOW_1_X
  1668. #define Z_PROBE_ALLEN_KEY_STOW_1_X current_position[X_AXIS]
  1669. #endif
  1670. #ifndef Z_PROBE_ALLEN_KEY_STOW_1_Y
  1671. #define Z_PROBE_ALLEN_KEY_STOW_1_Y current_position[Y_AXIS]
  1672. #endif
  1673. #ifndef Z_PROBE_ALLEN_KEY_STOW_1_Z
  1674. #define Z_PROBE_ALLEN_KEY_STOW_1_Z current_position[Z_AXIS]
  1675. #endif
  1676. #ifndef Z_PROBE_ALLEN_KEY_STOW_1_FEEDRATE
  1677. #define Z_PROBE_ALLEN_KEY_STOW_1_FEEDRATE 0.0
  1678. #endif
  1679. const float stow_1[] = { Z_PROBE_ALLEN_KEY_STOW_1_X, Z_PROBE_ALLEN_KEY_STOW_1_Y, Z_PROBE_ALLEN_KEY_STOW_1_Z };
  1680. do_blocking_move_to(stow_1, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_1_FEEDRATE));
  1681. #endif
  1682. #if defined(Z_PROBE_ALLEN_KEY_STOW_2_X) || defined(Z_PROBE_ALLEN_KEY_STOW_2_Y) || defined(Z_PROBE_ALLEN_KEY_STOW_2_Z)
  1683. #ifndef Z_PROBE_ALLEN_KEY_STOW_2_X
  1684. #define Z_PROBE_ALLEN_KEY_STOW_2_X current_position[X_AXIS]
  1685. #endif
  1686. #ifndef Z_PROBE_ALLEN_KEY_STOW_2_Y
  1687. #define Z_PROBE_ALLEN_KEY_STOW_2_Y current_position[Y_AXIS]
  1688. #endif
  1689. #ifndef Z_PROBE_ALLEN_KEY_STOW_2_Z
  1690. #define Z_PROBE_ALLEN_KEY_STOW_2_Z current_position[Z_AXIS]
  1691. #endif
  1692. #ifndef Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE
  1693. #define Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE 0.0
  1694. #endif
  1695. const float stow_2[] = { Z_PROBE_ALLEN_KEY_STOW_2_X, Z_PROBE_ALLEN_KEY_STOW_2_Y, Z_PROBE_ALLEN_KEY_STOW_2_Z };
  1696. do_blocking_move_to(stow_2, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE));
  1697. #endif
  1698. #if defined(Z_PROBE_ALLEN_KEY_STOW_3_X) || defined(Z_PROBE_ALLEN_KEY_STOW_3_Y) || defined(Z_PROBE_ALLEN_KEY_STOW_3_Z)
  1699. #ifndef Z_PROBE_ALLEN_KEY_STOW_3_X
  1700. #define Z_PROBE_ALLEN_KEY_STOW_3_X current_position[X_AXIS]
  1701. #endif
  1702. #ifndef Z_PROBE_ALLEN_KEY_STOW_3_Y
  1703. #define Z_PROBE_ALLEN_KEY_STOW_3_Y current_position[Y_AXIS]
  1704. #endif
  1705. #ifndef Z_PROBE_ALLEN_KEY_STOW_3_Z
  1706. #define Z_PROBE_ALLEN_KEY_STOW_3_Z current_position[Z_AXIS]
  1707. #endif
  1708. #ifndef Z_PROBE_ALLEN_KEY_STOW_3_FEEDRATE
  1709. #define Z_PROBE_ALLEN_KEY_STOW_3_FEEDRATE 0.0
  1710. #endif
  1711. const float stow_3[] = { Z_PROBE_ALLEN_KEY_STOW_3_X, Z_PROBE_ALLEN_KEY_STOW_3_Y, Z_PROBE_ALLEN_KEY_STOW_3_Z };
  1712. do_blocking_move_to(stow_3, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_3_FEEDRATE));
  1713. #endif
  1714. #if defined(Z_PROBE_ALLEN_KEY_STOW_4_X) || defined(Z_PROBE_ALLEN_KEY_STOW_4_Y) || defined(Z_PROBE_ALLEN_KEY_STOW_4_Z)
  1715. #ifndef Z_PROBE_ALLEN_KEY_STOW_4_X
  1716. #define Z_PROBE_ALLEN_KEY_STOW_4_X current_position[X_AXIS]
  1717. #endif
  1718. #ifndef Z_PROBE_ALLEN_KEY_STOW_4_Y
  1719. #define Z_PROBE_ALLEN_KEY_STOW_4_Y current_position[Y_AXIS]
  1720. #endif
  1721. #ifndef Z_PROBE_ALLEN_KEY_STOW_4_Z
  1722. #define Z_PROBE_ALLEN_KEY_STOW_4_Z current_position[Z_AXIS]
  1723. #endif
  1724. #ifndef Z_PROBE_ALLEN_KEY_STOW_4_FEEDRATE
  1725. #define Z_PROBE_ALLEN_KEY_STOW_4_FEEDRATE 0.0
  1726. #endif
  1727. const float stow_4[] = { Z_PROBE_ALLEN_KEY_STOW_4_X, Z_PROBE_ALLEN_KEY_STOW_4_Y, Z_PROBE_ALLEN_KEY_STOW_4_Z };
  1728. do_blocking_move_to(stow_4, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_4_FEEDRATE));
  1729. #endif
  1730. #if defined(Z_PROBE_ALLEN_KEY_STOW_5_X) || defined(Z_PROBE_ALLEN_KEY_STOW_5_Y) || defined(Z_PROBE_ALLEN_KEY_STOW_5_Z)
  1731. #ifndef Z_PROBE_ALLEN_KEY_STOW_5_X
  1732. #define Z_PROBE_ALLEN_KEY_STOW_5_X current_position[X_AXIS]
  1733. #endif
  1734. #ifndef Z_PROBE_ALLEN_KEY_STOW_5_Y
  1735. #define Z_PROBE_ALLEN_KEY_STOW_5_Y current_position[Y_AXIS]
  1736. #endif
  1737. #ifndef Z_PROBE_ALLEN_KEY_STOW_5_Z
  1738. #define Z_PROBE_ALLEN_KEY_STOW_5_Z current_position[Z_AXIS]
  1739. #endif
  1740. #ifndef Z_PROBE_ALLEN_KEY_STOW_5_FEEDRATE
  1741. #define Z_PROBE_ALLEN_KEY_STOW_5_FEEDRATE 0.0
  1742. #endif
  1743. const float stow_5[] = { Z_PROBE_ALLEN_KEY_STOW_5_X, Z_PROBE_ALLEN_KEY_STOW_5_Y, Z_PROBE_ALLEN_KEY_STOW_5_Z };
  1744. do_blocking_move_to(stow_5, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_5_FEEDRATE));
  1745. #endif
  1746. }
  1747. #endif
  1748. #if ENABLED(PROBING_FANS_OFF)
  1749. void fans_pause(const bool p) {
  1750. if (p != fans_paused) {
  1751. fans_paused = p;
  1752. if (p)
  1753. for (uint8_t x = 0; x < FAN_COUNT; x++) {
  1754. paused_fanSpeeds[x] = fanSpeeds[x];
  1755. fanSpeeds[x] = 0;
  1756. }
  1757. else
  1758. for (uint8_t x = 0; x < FAN_COUNT; x++)
  1759. fanSpeeds[x] = paused_fanSpeeds[x];
  1760. }
  1761. }
  1762. #endif // PROBING_FANS_OFF
  1763. #if HAS_BED_PROBE
  1764. // TRIGGERED_WHEN_STOWED_TEST can easily be extended to servo probes, ... if needed.
  1765. #if ENABLED(PROBE_IS_TRIGGERED_WHEN_STOWED_TEST)
  1766. #if ENABLED(Z_MIN_PROBE_ENDSTOP)
  1767. #define _TRIGGERED_WHEN_STOWED_TEST (READ(Z_MIN_PROBE_PIN) != Z_MIN_PROBE_ENDSTOP_INVERTING)
  1768. #else
  1769. #define _TRIGGERED_WHEN_STOWED_TEST (READ(Z_MIN_PIN) != Z_MIN_ENDSTOP_INVERTING)
  1770. #endif
  1771. #endif
  1772. #if QUIET_PROBING
  1773. void probing_pause(const bool p) {
  1774. #if ENABLED(PROBING_HEATERS_OFF)
  1775. thermalManager.pause(p);
  1776. #endif
  1777. #if ENABLED(PROBING_FANS_OFF)
  1778. fans_pause(p);
  1779. #endif
  1780. if (p) safe_delay(25);
  1781. }
  1782. #endif // QUIET_PROBING
  1783. #if ENABLED(BLTOUCH)
  1784. void bltouch_command(int angle) {
  1785. servo[Z_ENDSTOP_SERVO_NR].move(angle); // Give the BL-Touch the command and wait
  1786. safe_delay(BLTOUCH_DELAY);
  1787. }
  1788. void set_bltouch_deployed(const bool deploy) {
  1789. if (deploy && TEST_BLTOUCH()) { // If BL-Touch says it's triggered
  1790. bltouch_command(BLTOUCH_RESET); // try to reset it.
  1791. bltouch_command(BLTOUCH_DEPLOY); // Also needs to deploy and stow to
  1792. bltouch_command(BLTOUCH_STOW); // clear the triggered condition.
  1793. safe_delay(1500); // Wait for internal self-test to complete.
  1794. // (Measured completion time was 0.65 seconds
  1795. // after reset, deploy, and stow sequence)
  1796. if (TEST_BLTOUCH()) { // If it still claims to be triggered...
  1797. SERIAL_ERROR_START();
  1798. SERIAL_ERRORLNPGM(MSG_STOP_BLTOUCH);
  1799. stop(); // punt!
  1800. }
  1801. }
  1802. bltouch_command(deploy ? BLTOUCH_DEPLOY : BLTOUCH_STOW);
  1803. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1804. if (DEBUGGING(LEVELING)) {
  1805. SERIAL_ECHOPAIR("set_bltouch_deployed(", deploy);
  1806. SERIAL_CHAR(')');
  1807. SERIAL_EOL();
  1808. }
  1809. #endif
  1810. }
  1811. #endif // BLTOUCH
  1812. // returns false for ok and true for failure
  1813. bool set_probe_deployed(bool deploy) {
  1814. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1815. if (DEBUGGING(LEVELING)) {
  1816. DEBUG_POS("set_probe_deployed", current_position);
  1817. SERIAL_ECHOLNPAIR("deploy: ", deploy);
  1818. }
  1819. #endif
  1820. if (endstops.z_probe_enabled == deploy) return false;
  1821. // Make room for probe
  1822. do_probe_raise(_Z_CLEARANCE_DEPLOY_PROBE);
  1823. // When deploying make sure BLTOUCH is not already triggered
  1824. #if ENABLED(BLTOUCH)
  1825. if (deploy && TEST_BLTOUCH()) { // If BL-Touch says it's triggered
  1826. bltouch_command(BLTOUCH_RESET); // try to reset it.
  1827. bltouch_command(BLTOUCH_DEPLOY); // Also needs to deploy and stow to
  1828. bltouch_command(BLTOUCH_STOW); // clear the triggered condition.
  1829. safe_delay(1500); // wait for internal self test to complete
  1830. // measured completion time was 0.65 seconds
  1831. // after reset, deploy & stow sequence
  1832. if (TEST_BLTOUCH()) { // If it still claims to be triggered...
  1833. SERIAL_ERROR_START();
  1834. SERIAL_ERRORLNPGM(MSG_STOP_BLTOUCH);
  1835. stop(); // punt!
  1836. return true;
  1837. }
  1838. }
  1839. #elif ENABLED(Z_PROBE_SLED) || ENABLED(Z_PROBE_ALLEN_KEY)
  1840. #if ENABLED(Z_PROBE_SLED)
  1841. #define _AUE_ARGS true, false, false
  1842. #else
  1843. #define _AUE_ARGS
  1844. #endif
  1845. if (axis_unhomed_error(_AUE_ARGS)) {
  1846. SERIAL_ERROR_START();
  1847. SERIAL_ERRORLNPGM(MSG_STOP_UNHOMED);
  1848. stop();
  1849. return true;
  1850. }
  1851. #endif
  1852. const float oldXpos = current_position[X_AXIS],
  1853. oldYpos = current_position[Y_AXIS];
  1854. #ifdef _TRIGGERED_WHEN_STOWED_TEST
  1855. // If endstop is already false, the Z probe is deployed
  1856. if (_TRIGGERED_WHEN_STOWED_TEST == deploy) { // closed after the probe specific actions.
  1857. // Would a goto be less ugly?
  1858. //while (!_TRIGGERED_WHEN_STOWED_TEST) idle(); // would offer the opportunity
  1859. // for a triggered when stowed manual probe.
  1860. if (!deploy) endstops.enable_z_probe(false); // Switch off triggered when stowed probes early
  1861. // otherwise an Allen-Key probe can't be stowed.
  1862. #endif
  1863. #if ENABLED(SOLENOID_PROBE)
  1864. #if HAS_SOLENOID_1
  1865. WRITE(SOL1_PIN, deploy);
  1866. #endif
  1867. #elif ENABLED(Z_PROBE_SLED)
  1868. dock_sled(!deploy);
  1869. #elif HAS_Z_SERVO_ENDSTOP && DISABLED(BLTOUCH)
  1870. servo[Z_ENDSTOP_SERVO_NR].move(z_servo_angle[deploy ? 0 : 1]);
  1871. #elif ENABLED(Z_PROBE_ALLEN_KEY)
  1872. deploy ? run_deploy_moves_script() : run_stow_moves_script();
  1873. #endif
  1874. #ifdef _TRIGGERED_WHEN_STOWED_TEST
  1875. } // _TRIGGERED_WHEN_STOWED_TEST == deploy
  1876. if (_TRIGGERED_WHEN_STOWED_TEST == deploy) { // State hasn't changed?
  1877. if (IsRunning()) {
  1878. SERIAL_ERROR_START();
  1879. SERIAL_ERRORLNPGM("Z-Probe failed");
  1880. LCD_ALERTMESSAGEPGM("Err: ZPROBE");
  1881. }
  1882. stop();
  1883. return true;
  1884. } // _TRIGGERED_WHEN_STOWED_TEST == deploy
  1885. #endif
  1886. do_blocking_move_to(oldXpos, oldYpos, current_position[Z_AXIS]); // return to position before deploy
  1887. endstops.enable_z_probe(deploy);
  1888. return false;
  1889. }
  1890. static void do_probe_move(float z, float fr_mm_m) {
  1891. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1892. if (DEBUGGING(LEVELING)) DEBUG_POS(">>> do_probe_move", current_position);
  1893. #endif
  1894. // Deploy BLTouch at the start of any probe
  1895. #if ENABLED(BLTOUCH)
  1896. set_bltouch_deployed(true);
  1897. #endif
  1898. #if QUIET_PROBING
  1899. probing_pause(true);
  1900. #endif
  1901. // Move down until probe triggered
  1902. do_blocking_move_to_z(LOGICAL_Z_POSITION(z), MMM_TO_MMS(fr_mm_m));
  1903. #if QUIET_PROBING
  1904. probing_pause(false);
  1905. #endif
  1906. // Retract BLTouch immediately after a probe
  1907. #if ENABLED(BLTOUCH)
  1908. set_bltouch_deployed(false);
  1909. #endif
  1910. // Clear endstop flags
  1911. endstops.hit_on_purpose();
  1912. // Get Z where the steppers were interrupted
  1913. set_current_from_steppers_for_axis(Z_AXIS);
  1914. // Tell the planner where we actually are
  1915. SYNC_PLAN_POSITION_KINEMATIC();
  1916. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1917. if (DEBUGGING(LEVELING)) DEBUG_POS("<<< do_probe_move", current_position);
  1918. #endif
  1919. }
  1920. // Do a single Z probe and return with current_position[Z_AXIS]
  1921. // at the height where the probe triggered.
  1922. static float run_z_probe() {
  1923. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1924. if (DEBUGGING(LEVELING)) DEBUG_POS(">>> run_z_probe", current_position);
  1925. #endif
  1926. // Prevent stepper_inactive_time from running out and EXTRUDER_RUNOUT_PREVENT from extruding
  1927. refresh_cmd_timeout();
  1928. #if ENABLED(PROBE_DOUBLE_TOUCH)
  1929. // Do a first probe at the fast speed
  1930. do_probe_move(-(Z_MAX_LENGTH) - 10, Z_PROBE_SPEED_FAST);
  1931. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1932. float first_probe_z = current_position[Z_AXIS];
  1933. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR("1st Probe Z:", first_probe_z);
  1934. #endif
  1935. // move up by the bump distance
  1936. do_blocking_move_to_z(current_position[Z_AXIS] + home_bump_mm(Z_AXIS), MMM_TO_MMS(Z_PROBE_SPEED_FAST));
  1937. #else
  1938. // If the nozzle is above the travel height then
  1939. // move down quickly before doing the slow probe
  1940. float z = LOGICAL_Z_POSITION(Z_CLEARANCE_BETWEEN_PROBES);
  1941. if (zprobe_zoffset < 0) z -= zprobe_zoffset;
  1942. #if ENABLED(DELTA)
  1943. z -= home_offset[Z_AXIS]; // Account for delta height adjustment
  1944. #endif
  1945. if (z < current_position[Z_AXIS])
  1946. do_blocking_move_to_z(z, MMM_TO_MMS(Z_PROBE_SPEED_FAST));
  1947. #endif
  1948. // move down slowly to find bed
  1949. do_probe_move(-(Z_MAX_LENGTH) - 10, Z_PROBE_SPEED_SLOW);
  1950. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1951. if (DEBUGGING(LEVELING)) DEBUG_POS("<<< run_z_probe", current_position);
  1952. #endif
  1953. // Debug: compare probe heights
  1954. #if ENABLED(PROBE_DOUBLE_TOUCH) && ENABLED(DEBUG_LEVELING_FEATURE)
  1955. if (DEBUGGING(LEVELING)) {
  1956. SERIAL_ECHOPAIR("2nd Probe Z:", current_position[Z_AXIS]);
  1957. SERIAL_ECHOLNPAIR(" Discrepancy:", first_probe_z - current_position[Z_AXIS]);
  1958. }
  1959. #endif
  1960. return RAW_CURRENT_POSITION(Z) + zprobe_zoffset
  1961. #if ENABLED(DELTA)
  1962. + home_offset[Z_AXIS] // Account for delta height adjustment
  1963. #endif
  1964. ;
  1965. }
  1966. /**
  1967. * - Move to the given XY
  1968. * - Deploy the probe, if not already deployed
  1969. * - Probe the bed, get the Z position
  1970. * - Depending on the 'stow' flag
  1971. * - Stow the probe, or
  1972. * - Raise to the BETWEEN height
  1973. * - Return the probed Z position
  1974. */
  1975. float probe_pt(const float &lx, const float &ly, const bool stow, const uint8_t verbose_level, const bool printable=true) {
  1976. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1977. if (DEBUGGING(LEVELING)) {
  1978. SERIAL_ECHOPAIR(">>> probe_pt(", lx);
  1979. SERIAL_ECHOPAIR(", ", ly);
  1980. SERIAL_ECHOPAIR(", ", stow ? "" : "no ");
  1981. SERIAL_ECHOLNPGM("stow)");
  1982. DEBUG_POS("", current_position);
  1983. }
  1984. #endif
  1985. const float nx = lx - (X_PROBE_OFFSET_FROM_EXTRUDER), ny = ly - (Y_PROBE_OFFSET_FROM_EXTRUDER);
  1986. if (printable)
  1987. if (!position_is_reachable_by_probe_xy(lx, ly)) return NAN;
  1988. else
  1989. if (!position_is_reachable_xy(nx, ny)) return NAN;
  1990. const float old_feedrate_mm_s = feedrate_mm_s;
  1991. #if ENABLED(DELTA)
  1992. if (current_position[Z_AXIS] > delta_clip_start_height)
  1993. do_blocking_move_to_z(delta_clip_start_height);
  1994. #endif
  1995. // Ensure a minimum height before moving the probe
  1996. do_probe_raise(Z_CLEARANCE_BETWEEN_PROBES);
  1997. feedrate_mm_s = XY_PROBE_FEEDRATE_MM_S;
  1998. // Move the probe to the given XY
  1999. do_blocking_move_to_xy(nx, ny);
  2000. if (DEPLOY_PROBE()) return NAN;
  2001. const float measured_z = run_z_probe();
  2002. if (!stow)
  2003. do_probe_raise(Z_CLEARANCE_BETWEEN_PROBES);
  2004. else
  2005. if (STOW_PROBE()) return NAN;
  2006. if (verbose_level > 2) {
  2007. SERIAL_PROTOCOLPGM("Bed X: ");
  2008. SERIAL_PROTOCOL_F(lx, 3);
  2009. SERIAL_PROTOCOLPGM(" Y: ");
  2010. SERIAL_PROTOCOL_F(ly, 3);
  2011. SERIAL_PROTOCOLPGM(" Z: ");
  2012. SERIAL_PROTOCOL_F(measured_z, 3);
  2013. SERIAL_EOL();
  2014. }
  2015. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2016. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< probe_pt");
  2017. #endif
  2018. feedrate_mm_s = old_feedrate_mm_s;
  2019. return measured_z;
  2020. }
  2021. #endif // HAS_BED_PROBE
  2022. #if HAS_LEVELING
  2023. bool leveling_is_valid() {
  2024. return
  2025. #if ENABLED(MESH_BED_LEVELING)
  2026. mbl.has_mesh()
  2027. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  2028. !!bilinear_grid_spacing[X_AXIS]
  2029. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  2030. true
  2031. #else // 3POINT, LINEAR
  2032. true
  2033. #endif
  2034. ;
  2035. }
  2036. bool leveling_is_active() {
  2037. return
  2038. #if ENABLED(MESH_BED_LEVELING)
  2039. mbl.active()
  2040. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  2041. ubl.state.active
  2042. #else
  2043. planner.abl_enabled
  2044. #endif
  2045. ;
  2046. }
  2047. /**
  2048. * Turn bed leveling on or off, fixing the current
  2049. * position as-needed.
  2050. *
  2051. * Disable: Current position = physical position
  2052. * Enable: Current position = "unleveled" physical position
  2053. */
  2054. void set_bed_leveling_enabled(const bool enable/*=true*/) {
  2055. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  2056. const bool can_change = (!enable || leveling_is_valid());
  2057. #else
  2058. constexpr bool can_change = true;
  2059. #endif
  2060. if (can_change && enable != leveling_is_active()) {
  2061. #if ENABLED(MESH_BED_LEVELING)
  2062. if (!enable)
  2063. planner.apply_leveling(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS]);
  2064. const bool enabling = enable && leveling_is_valid();
  2065. mbl.set_active(enabling);
  2066. if (enabling) planner.unapply_leveling(current_position);
  2067. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  2068. #if PLANNER_LEVELING
  2069. if (ubl.state.active) { // leveling from on to off
  2070. // change unleveled current_position to physical current_position without moving steppers.
  2071. planner.apply_leveling(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS]);
  2072. ubl.state.active = false; // disable only AFTER calling apply_leveling
  2073. }
  2074. else { // leveling from off to on
  2075. ubl.state.active = true; // enable BEFORE calling unapply_leveling, otherwise ignored
  2076. // change physical current_position to unleveled current_position without moving steppers.
  2077. planner.unapply_leveling(current_position);
  2078. }
  2079. #else
  2080. ubl.state.active = enable; // just flip the bit, current_position will be wrong until next move.
  2081. #endif
  2082. #else // ABL
  2083. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  2084. // Force bilinear_z_offset to re-calculate next time
  2085. const float reset[XYZ] = { -9999.999, -9999.999, 0 };
  2086. (void)bilinear_z_offset(reset);
  2087. #endif
  2088. // Enable or disable leveling compensation in the planner
  2089. planner.abl_enabled = enable;
  2090. if (!enable)
  2091. // When disabling just get the current position from the steppers.
  2092. // This will yield the smallest error when first converted back to steps.
  2093. set_current_from_steppers_for_axis(
  2094. #if ABL_PLANAR
  2095. ALL_AXES
  2096. #else
  2097. Z_AXIS
  2098. #endif
  2099. );
  2100. else
  2101. // When enabling, remove compensation from the current position,
  2102. // so compensation will give the right stepper counts.
  2103. planner.unapply_leveling(current_position);
  2104. #endif // ABL
  2105. }
  2106. }
  2107. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  2108. void set_z_fade_height(const float zfh) {
  2109. const bool level_active = leveling_is_active();
  2110. #if ENABLED(AUTO_BED_LEVELING_UBL)
  2111. if (level_active)
  2112. set_bed_leveling_enabled(false); // turn off before changing fade height for proper apply/unapply leveling to maintain current_position
  2113. planner.z_fade_height = zfh;
  2114. planner.inverse_z_fade_height = RECIPROCAL(zfh);
  2115. if (level_active)
  2116. set_bed_leveling_enabled(true); // turn back on after changing fade height
  2117. #else
  2118. planner.z_fade_height = zfh;
  2119. planner.inverse_z_fade_height = RECIPROCAL(zfh);
  2120. if (level_active) {
  2121. set_current_from_steppers_for_axis(
  2122. #if ABL_PLANAR
  2123. ALL_AXES
  2124. #else
  2125. Z_AXIS
  2126. #endif
  2127. );
  2128. }
  2129. #endif
  2130. }
  2131. #endif // LEVELING_FADE_HEIGHT
  2132. /**
  2133. * Reset calibration results to zero.
  2134. */
  2135. void reset_bed_level() {
  2136. set_bed_leveling_enabled(false);
  2137. #if ENABLED(MESH_BED_LEVELING)
  2138. if (leveling_is_valid()) {
  2139. mbl.reset();
  2140. mbl.set_has_mesh(false);
  2141. }
  2142. #else
  2143. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2144. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("reset_bed_level");
  2145. #endif
  2146. #if ABL_PLANAR
  2147. planner.bed_level_matrix.set_to_identity();
  2148. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  2149. bilinear_start[X_AXIS] = bilinear_start[Y_AXIS] =
  2150. bilinear_grid_spacing[X_AXIS] = bilinear_grid_spacing[Y_AXIS] = 0;
  2151. for (uint8_t x = 0; x < GRID_MAX_POINTS_X; x++)
  2152. for (uint8_t y = 0; y < GRID_MAX_POINTS_Y; y++)
  2153. z_values[x][y] = NAN;
  2154. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  2155. ubl.reset();
  2156. #endif
  2157. #endif
  2158. }
  2159. #endif // HAS_LEVELING
  2160. #if ENABLED(AUTO_BED_LEVELING_BILINEAR) || ENABLED(MESH_BED_LEVELING)
  2161. /**
  2162. * Enable to produce output in JSON format suitable
  2163. * for SCAD or JavaScript mesh visualizers.
  2164. *
  2165. * Visualize meshes in OpenSCAD using the included script.
  2166. *
  2167. * buildroot/shared/scripts/MarlinMesh.scad
  2168. */
  2169. //#define SCAD_MESH_OUTPUT
  2170. /**
  2171. * Print calibration results for plotting or manual frame adjustment.
  2172. */
  2173. static void print_2d_array(const uint8_t sx, const uint8_t sy, const uint8_t precision, float (*fn)(const uint8_t, const uint8_t)) {
  2174. #ifndef SCAD_MESH_OUTPUT
  2175. for (uint8_t x = 0; x < sx; x++) {
  2176. for (uint8_t i = 0; i < precision + 2 + (x < 10 ? 1 : 0); i++)
  2177. SERIAL_PROTOCOLCHAR(' ');
  2178. SERIAL_PROTOCOL((int)x);
  2179. }
  2180. SERIAL_EOL();
  2181. #endif
  2182. #ifdef SCAD_MESH_OUTPUT
  2183. SERIAL_PROTOCOLLNPGM("measured_z = ["); // open 2D array
  2184. #endif
  2185. for (uint8_t y = 0; y < sy; y++) {
  2186. #ifdef SCAD_MESH_OUTPUT
  2187. SERIAL_PROTOCOLPGM(" ["); // open sub-array
  2188. #else
  2189. if (y < 10) SERIAL_PROTOCOLCHAR(' ');
  2190. SERIAL_PROTOCOL((int)y);
  2191. #endif
  2192. for (uint8_t x = 0; x < sx; x++) {
  2193. SERIAL_PROTOCOLCHAR(' ');
  2194. const float offset = fn(x, y);
  2195. if (!isnan(offset)) {
  2196. if (offset >= 0) SERIAL_PROTOCOLCHAR('+');
  2197. SERIAL_PROTOCOL_F(offset, precision);
  2198. }
  2199. else {
  2200. #ifdef SCAD_MESH_OUTPUT
  2201. for (uint8_t i = 3; i < precision + 3; i++)
  2202. SERIAL_PROTOCOLCHAR(' ');
  2203. SERIAL_PROTOCOLPGM("NAN");
  2204. #else
  2205. for (uint8_t i = 0; i < precision + 3; i++)
  2206. SERIAL_PROTOCOLCHAR(i ? '=' : ' ');
  2207. #endif
  2208. }
  2209. #ifdef SCAD_MESH_OUTPUT
  2210. if (x < sx - 1) SERIAL_PROTOCOLCHAR(',');
  2211. #endif
  2212. }
  2213. #ifdef SCAD_MESH_OUTPUT
  2214. SERIAL_PROTOCOLCHAR(' ');
  2215. SERIAL_PROTOCOLCHAR(']'); // close sub-array
  2216. if (y < sy - 1) SERIAL_PROTOCOLCHAR(',');
  2217. #endif
  2218. SERIAL_EOL();
  2219. }
  2220. #ifdef SCAD_MESH_OUTPUT
  2221. SERIAL_PROTOCOLPGM("];"); // close 2D array
  2222. #endif
  2223. SERIAL_EOL();
  2224. }
  2225. #endif
  2226. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  2227. /**
  2228. * Extrapolate a single point from its neighbors
  2229. */
  2230. static void extrapolate_one_point(const uint8_t x, const uint8_t y, const int8_t xdir, const int8_t ydir) {
  2231. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2232. if (DEBUGGING(LEVELING)) {
  2233. SERIAL_ECHOPGM("Extrapolate [");
  2234. if (x < 10) SERIAL_CHAR(' ');
  2235. SERIAL_ECHO((int)x);
  2236. SERIAL_CHAR(xdir ? (xdir > 0 ? '+' : '-') : ' ');
  2237. SERIAL_CHAR(' ');
  2238. if (y < 10) SERIAL_CHAR(' ');
  2239. SERIAL_ECHO((int)y);
  2240. SERIAL_CHAR(ydir ? (ydir > 0 ? '+' : '-') : ' ');
  2241. SERIAL_CHAR(']');
  2242. }
  2243. #endif
  2244. if (!isnan(z_values[x][y])) {
  2245. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2246. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM(" (done)");
  2247. #endif
  2248. return; // Don't overwrite good values.
  2249. }
  2250. SERIAL_EOL();
  2251. // Get X neighbors, Y neighbors, and XY neighbors
  2252. const uint8_t x1 = x + xdir, y1 = y + ydir, x2 = x1 + xdir, y2 = y1 + ydir;
  2253. float a1 = z_values[x1][y ], a2 = z_values[x2][y ],
  2254. b1 = z_values[x ][y1], b2 = z_values[x ][y2],
  2255. c1 = z_values[x1][y1], c2 = z_values[x2][y2];
  2256. // Treat far unprobed points as zero, near as equal to far
  2257. if (isnan(a2)) a2 = 0.0; if (isnan(a1)) a1 = a2;
  2258. if (isnan(b2)) b2 = 0.0; if (isnan(b1)) b1 = b2;
  2259. if (isnan(c2)) c2 = 0.0; if (isnan(c1)) c1 = c2;
  2260. const float a = 2 * a1 - a2, b = 2 * b1 - b2, c = 2 * c1 - c2;
  2261. // Take the average instead of the median
  2262. z_values[x][y] = (a + b + c) / 3.0;
  2263. // Median is robust (ignores outliers).
  2264. // z_values[x][y] = (a < b) ? ((b < c) ? b : (c < a) ? a : c)
  2265. // : ((c < b) ? b : (a < c) ? a : c);
  2266. }
  2267. //Enable this if your SCARA uses 180° of total area
  2268. //#define EXTRAPOLATE_FROM_EDGE
  2269. #if ENABLED(EXTRAPOLATE_FROM_EDGE)
  2270. #if GRID_MAX_POINTS_X < GRID_MAX_POINTS_Y
  2271. #define HALF_IN_X
  2272. #elif GRID_MAX_POINTS_Y < GRID_MAX_POINTS_X
  2273. #define HALF_IN_Y
  2274. #endif
  2275. #endif
  2276. /**
  2277. * Fill in the unprobed points (corners of circular print surface)
  2278. * using linear extrapolation, away from the center.
  2279. */
  2280. static void extrapolate_unprobed_bed_level() {
  2281. #ifdef HALF_IN_X
  2282. constexpr uint8_t ctrx2 = 0, xlen = GRID_MAX_POINTS_X - 1;
  2283. #else
  2284. constexpr uint8_t ctrx1 = (GRID_MAX_POINTS_X - 1) / 2, // left-of-center
  2285. ctrx2 = (GRID_MAX_POINTS_X) / 2, // right-of-center
  2286. xlen = ctrx1;
  2287. #endif
  2288. #ifdef HALF_IN_Y
  2289. constexpr uint8_t ctry2 = 0, ylen = GRID_MAX_POINTS_Y - 1;
  2290. #else
  2291. constexpr uint8_t ctry1 = (GRID_MAX_POINTS_Y - 1) / 2, // top-of-center
  2292. ctry2 = (GRID_MAX_POINTS_Y) / 2, // bottom-of-center
  2293. ylen = ctry1;
  2294. #endif
  2295. for (uint8_t xo = 0; xo <= xlen; xo++)
  2296. for (uint8_t yo = 0; yo <= ylen; yo++) {
  2297. uint8_t x2 = ctrx2 + xo, y2 = ctry2 + yo;
  2298. #ifndef HALF_IN_X
  2299. const uint8_t x1 = ctrx1 - xo;
  2300. #endif
  2301. #ifndef HALF_IN_Y
  2302. const uint8_t y1 = ctry1 - yo;
  2303. #ifndef HALF_IN_X
  2304. extrapolate_one_point(x1, y1, +1, +1); // left-below + +
  2305. #endif
  2306. extrapolate_one_point(x2, y1, -1, +1); // right-below - +
  2307. #endif
  2308. #ifndef HALF_IN_X
  2309. extrapolate_one_point(x1, y2, +1, -1); // left-above + -
  2310. #endif
  2311. extrapolate_one_point(x2, y2, -1, -1); // right-above - -
  2312. }
  2313. }
  2314. static void print_bilinear_leveling_grid() {
  2315. SERIAL_ECHOLNPGM("Bilinear Leveling Grid:");
  2316. print_2d_array(GRID_MAX_POINTS_X, GRID_MAX_POINTS_Y, 3,
  2317. [](const uint8_t ix, const uint8_t iy) { return z_values[ix][iy]; }
  2318. );
  2319. }
  2320. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  2321. #define ABL_GRID_POINTS_VIRT_X (GRID_MAX_POINTS_X - 1) * (BILINEAR_SUBDIVISIONS) + 1
  2322. #define ABL_GRID_POINTS_VIRT_Y (GRID_MAX_POINTS_Y - 1) * (BILINEAR_SUBDIVISIONS) + 1
  2323. #define ABL_TEMP_POINTS_X (GRID_MAX_POINTS_X + 2)
  2324. #define ABL_TEMP_POINTS_Y (GRID_MAX_POINTS_Y + 2)
  2325. float z_values_virt[ABL_GRID_POINTS_VIRT_X][ABL_GRID_POINTS_VIRT_Y];
  2326. int bilinear_grid_spacing_virt[2] = { 0 };
  2327. float bilinear_grid_factor_virt[2] = { 0 };
  2328. static void bed_level_virt_print() {
  2329. SERIAL_ECHOLNPGM("Subdivided with CATMULL ROM Leveling Grid:");
  2330. print_2d_array(ABL_GRID_POINTS_VIRT_X, ABL_GRID_POINTS_VIRT_Y, 5,
  2331. [](const uint8_t ix, const uint8_t iy) { return z_values_virt[ix][iy]; }
  2332. );
  2333. }
  2334. #define LINEAR_EXTRAPOLATION(E, I) ((E) * 2 - (I))
  2335. float bed_level_virt_coord(const uint8_t x, const uint8_t y) {
  2336. uint8_t ep = 0, ip = 1;
  2337. if (!x || x == ABL_TEMP_POINTS_X - 1) {
  2338. if (x) {
  2339. ep = GRID_MAX_POINTS_X - 1;
  2340. ip = GRID_MAX_POINTS_X - 2;
  2341. }
  2342. if (WITHIN(y, 1, ABL_TEMP_POINTS_Y - 2))
  2343. return LINEAR_EXTRAPOLATION(
  2344. z_values[ep][y - 1],
  2345. z_values[ip][y - 1]
  2346. );
  2347. else
  2348. return LINEAR_EXTRAPOLATION(
  2349. bed_level_virt_coord(ep + 1, y),
  2350. bed_level_virt_coord(ip + 1, y)
  2351. );
  2352. }
  2353. if (!y || y == ABL_TEMP_POINTS_Y - 1) {
  2354. if (y) {
  2355. ep = GRID_MAX_POINTS_Y - 1;
  2356. ip = GRID_MAX_POINTS_Y - 2;
  2357. }
  2358. if (WITHIN(x, 1, ABL_TEMP_POINTS_X - 2))
  2359. return LINEAR_EXTRAPOLATION(
  2360. z_values[x - 1][ep],
  2361. z_values[x - 1][ip]
  2362. );
  2363. else
  2364. return LINEAR_EXTRAPOLATION(
  2365. bed_level_virt_coord(x, ep + 1),
  2366. bed_level_virt_coord(x, ip + 1)
  2367. );
  2368. }
  2369. return z_values[x - 1][y - 1];
  2370. }
  2371. static float bed_level_virt_cmr(const float p[4], const uint8_t i, const float t) {
  2372. return (
  2373. p[i-1] * -t * sq(1 - t)
  2374. + p[i] * (2 - 5 * sq(t) + 3 * t * sq(t))
  2375. + p[i+1] * t * (1 + 4 * t - 3 * sq(t))
  2376. - p[i+2] * sq(t) * (1 - t)
  2377. ) * 0.5;
  2378. }
  2379. static float bed_level_virt_2cmr(const uint8_t x, const uint8_t y, const float &tx, const float &ty) {
  2380. float row[4], column[4];
  2381. for (uint8_t i = 0; i < 4; i++) {
  2382. for (uint8_t j = 0; j < 4; j++) {
  2383. column[j] = bed_level_virt_coord(i + x - 1, j + y - 1);
  2384. }
  2385. row[i] = bed_level_virt_cmr(column, 1, ty);
  2386. }
  2387. return bed_level_virt_cmr(row, 1, tx);
  2388. }
  2389. void bed_level_virt_interpolate() {
  2390. bilinear_grid_spacing_virt[X_AXIS] = bilinear_grid_spacing[X_AXIS] / (BILINEAR_SUBDIVISIONS);
  2391. bilinear_grid_spacing_virt[Y_AXIS] = bilinear_grid_spacing[Y_AXIS] / (BILINEAR_SUBDIVISIONS);
  2392. bilinear_grid_factor_virt[X_AXIS] = RECIPROCAL(bilinear_grid_spacing_virt[X_AXIS]);
  2393. bilinear_grid_factor_virt[Y_AXIS] = RECIPROCAL(bilinear_grid_spacing_virt[Y_AXIS]);
  2394. for (uint8_t y = 0; y < GRID_MAX_POINTS_Y; y++)
  2395. for (uint8_t x = 0; x < GRID_MAX_POINTS_X; x++)
  2396. for (uint8_t ty = 0; ty < BILINEAR_SUBDIVISIONS; ty++)
  2397. for (uint8_t tx = 0; tx < BILINEAR_SUBDIVISIONS; tx++) {
  2398. if ((ty && y == GRID_MAX_POINTS_Y - 1) || (tx && x == GRID_MAX_POINTS_X - 1))
  2399. continue;
  2400. z_values_virt[x * (BILINEAR_SUBDIVISIONS) + tx][y * (BILINEAR_SUBDIVISIONS) + ty] =
  2401. bed_level_virt_2cmr(
  2402. x + 1,
  2403. y + 1,
  2404. (float)tx / (BILINEAR_SUBDIVISIONS),
  2405. (float)ty / (BILINEAR_SUBDIVISIONS)
  2406. );
  2407. }
  2408. }
  2409. #endif // ABL_BILINEAR_SUBDIVISION
  2410. // Refresh after other values have been updated
  2411. void refresh_bed_level() {
  2412. bilinear_grid_factor[X_AXIS] = RECIPROCAL(bilinear_grid_spacing[X_AXIS]);
  2413. bilinear_grid_factor[Y_AXIS] = RECIPROCAL(bilinear_grid_spacing[Y_AXIS]);
  2414. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  2415. bed_level_virt_interpolate();
  2416. #endif
  2417. }
  2418. #endif // AUTO_BED_LEVELING_BILINEAR
  2419. /**
  2420. * Home an individual linear axis
  2421. */
  2422. static void do_homing_move(const AxisEnum axis, const float distance, const float fr_mm_s=0.0) {
  2423. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2424. if (DEBUGGING(LEVELING)) {
  2425. SERIAL_ECHOPAIR(">>> do_homing_move(", axis_codes[axis]);
  2426. SERIAL_ECHOPAIR(", ", distance);
  2427. SERIAL_ECHOPAIR(", ", fr_mm_s);
  2428. SERIAL_CHAR(')');
  2429. SERIAL_EOL();
  2430. }
  2431. #endif
  2432. #if HOMING_Z_WITH_PROBE && ENABLED(BLTOUCH)
  2433. const bool deploy_bltouch = (axis == Z_AXIS && distance < 0);
  2434. if (deploy_bltouch) set_bltouch_deployed(true);
  2435. #endif
  2436. #if QUIET_PROBING
  2437. if (axis == Z_AXIS) probing_pause(true);
  2438. #endif
  2439. // Tell the planner we're at Z=0
  2440. current_position[axis] = 0;
  2441. #if IS_SCARA
  2442. SYNC_PLAN_POSITION_KINEMATIC();
  2443. current_position[axis] = distance;
  2444. inverse_kinematics(current_position);
  2445. planner.buffer_line(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], current_position[E_AXIS], fr_mm_s ? fr_mm_s : homing_feedrate(axis), active_extruder);
  2446. #else
  2447. sync_plan_position();
  2448. current_position[axis] = distance;
  2449. planner.buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], fr_mm_s ? fr_mm_s : homing_feedrate(axis), active_extruder);
  2450. #endif
  2451. stepper.synchronize();
  2452. #if QUIET_PROBING
  2453. if (axis == Z_AXIS) probing_pause(false);
  2454. #endif
  2455. #if HOMING_Z_WITH_PROBE && ENABLED(BLTOUCH)
  2456. if (deploy_bltouch) set_bltouch_deployed(false);
  2457. #endif
  2458. endstops.hit_on_purpose();
  2459. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2460. if (DEBUGGING(LEVELING)) {
  2461. SERIAL_ECHOPAIR("<<< do_homing_move(", axis_codes[axis]);
  2462. SERIAL_CHAR(')');
  2463. SERIAL_EOL();
  2464. }
  2465. #endif
  2466. }
  2467. /**
  2468. * TMC2130 specific sensorless homing using stallGuard2.
  2469. * stallGuard2 only works when in spreadCycle mode.
  2470. * spreadCycle and stealthChop are mutually exclusive.
  2471. */
  2472. #if ENABLED(SENSORLESS_HOMING)
  2473. void tmc2130_sensorless_homing(TMC2130Stepper &st, bool enable=true) {
  2474. #if ENABLED(STEALTHCHOP)
  2475. if (enable) {
  2476. st.coolstep_min_speed(1024UL * 1024UL - 1UL);
  2477. st.stealthChop(0);
  2478. }
  2479. else {
  2480. st.coolstep_min_speed(0);
  2481. st.stealthChop(1);
  2482. }
  2483. #endif
  2484. st.diag1_stall(enable ? 1 : 0);
  2485. }
  2486. #endif
  2487. /**
  2488. * Home an individual "raw axis" to its endstop.
  2489. * This applies to XYZ on Cartesian and Core robots, and
  2490. * to the individual ABC steppers on DELTA and SCARA.
  2491. *
  2492. * At the end of the procedure the axis is marked as
  2493. * homed and the current position of that axis is updated.
  2494. * Kinematic robots should wait till all axes are homed
  2495. * before updating the current position.
  2496. */
  2497. #define HOMEAXIS(LETTER) homeaxis(LETTER##_AXIS)
  2498. static void homeaxis(const AxisEnum axis) {
  2499. #if IS_SCARA
  2500. // Only Z homing (with probe) is permitted
  2501. if (axis != Z_AXIS) { BUZZ(100, 880); return; }
  2502. #else
  2503. #define CAN_HOME(A) \
  2504. (axis == A##_AXIS && ((A##_MIN_PIN > -1 && A##_HOME_DIR < 0) || (A##_MAX_PIN > -1 && A##_HOME_DIR > 0)))
  2505. if (!CAN_HOME(X) && !CAN_HOME(Y) && !CAN_HOME(Z)) return;
  2506. #endif
  2507. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2508. if (DEBUGGING(LEVELING)) {
  2509. SERIAL_ECHOPAIR(">>> homeaxis(", axis_codes[axis]);
  2510. SERIAL_CHAR(')');
  2511. SERIAL_EOL();
  2512. }
  2513. #endif
  2514. const int axis_home_dir =
  2515. #if ENABLED(DUAL_X_CARRIAGE)
  2516. (axis == X_AXIS) ? x_home_dir(active_extruder) :
  2517. #endif
  2518. home_dir(axis);
  2519. // Homing Z towards the bed? Deploy the Z probe or endstop.
  2520. #if HOMING_Z_WITH_PROBE
  2521. if (axis == Z_AXIS && DEPLOY_PROBE()) return;
  2522. #endif
  2523. // Set a flag for Z motor locking
  2524. #if ENABLED(Z_DUAL_ENDSTOPS)
  2525. if (axis == Z_AXIS) stepper.set_homing_flag(true);
  2526. #endif
  2527. // Disable stealthChop if used. Enable diag1 pin on driver.
  2528. #if ENABLED(SENSORLESS_HOMING)
  2529. #if ENABLED(X_IS_TMC2130)
  2530. if (axis == X_AXIS) tmc2130_sensorless_homing(stepperX);
  2531. #endif
  2532. #if ENABLED(Y_IS_TMC2130)
  2533. if (axis == Y_AXIS) tmc2130_sensorless_homing(stepperY);
  2534. #endif
  2535. #endif
  2536. // Fast move towards endstop until triggered
  2537. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2538. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Home 1 Fast:");
  2539. #endif
  2540. do_homing_move(axis, 1.5 * max_length(axis) * axis_home_dir);
  2541. // When homing Z with probe respect probe clearance
  2542. const float bump = axis_home_dir * (
  2543. #if HOMING_Z_WITH_PROBE
  2544. (axis == Z_AXIS) ? max(Z_CLEARANCE_BETWEEN_PROBES, home_bump_mm(Z_AXIS)) :
  2545. #endif
  2546. home_bump_mm(axis)
  2547. );
  2548. // If a second homing move is configured...
  2549. if (bump) {
  2550. // Move away from the endstop by the axis HOME_BUMP_MM
  2551. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2552. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Move Away:");
  2553. #endif
  2554. do_homing_move(axis, -bump);
  2555. // Slow move towards endstop until triggered
  2556. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2557. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Home 2 Slow:");
  2558. #endif
  2559. do_homing_move(axis, 2 * bump, get_homing_bump_feedrate(axis));
  2560. }
  2561. #if ENABLED(Z_DUAL_ENDSTOPS)
  2562. if (axis == Z_AXIS) {
  2563. float adj = FABS(z_endstop_adj);
  2564. bool lockZ1;
  2565. if (axis_home_dir > 0) {
  2566. adj = -adj;
  2567. lockZ1 = (z_endstop_adj > 0);
  2568. }
  2569. else
  2570. lockZ1 = (z_endstop_adj < 0);
  2571. if (lockZ1) stepper.set_z_lock(true); else stepper.set_z2_lock(true);
  2572. // Move to the adjusted endstop height
  2573. do_homing_move(axis, adj);
  2574. if (lockZ1) stepper.set_z_lock(false); else stepper.set_z2_lock(false);
  2575. stepper.set_homing_flag(false);
  2576. } // Z_AXIS
  2577. #endif
  2578. #if IS_SCARA
  2579. set_axis_is_at_home(axis);
  2580. SYNC_PLAN_POSITION_KINEMATIC();
  2581. #elif ENABLED(DELTA)
  2582. // Delta has already moved all three towers up in G28
  2583. // so here it re-homes each tower in turn.
  2584. // Delta homing treats the axes as normal linear axes.
  2585. // retrace by the amount specified in endstop_adj + additional 0.1mm in order to have minimum steps
  2586. if (endstop_adj[axis] * Z_HOME_DIR <= 0) {
  2587. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2588. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("endstop_adj:");
  2589. #endif
  2590. do_homing_move(axis, endstop_adj[axis] - 0.1);
  2591. }
  2592. #else
  2593. // For cartesian/core machines,
  2594. // set the axis to its home position
  2595. set_axis_is_at_home(axis);
  2596. sync_plan_position();
  2597. destination[axis] = current_position[axis];
  2598. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2599. if (DEBUGGING(LEVELING)) DEBUG_POS("> AFTER set_axis_is_at_home", current_position);
  2600. #endif
  2601. #endif
  2602. // Re-enable stealthChop if used. Disable diag1 pin on driver.
  2603. #if ENABLED(SENSORLESS_HOMING)
  2604. #if ENABLED(X_IS_TMC2130)
  2605. if (axis == X_AXIS) tmc2130_sensorless_homing(stepperX, false);
  2606. #endif
  2607. #if ENABLED(Y_IS_TMC2130)
  2608. if (axis == Y_AXIS) tmc2130_sensorless_homing(stepperY, false);
  2609. #endif
  2610. #endif
  2611. // Put away the Z probe
  2612. #if HOMING_Z_WITH_PROBE
  2613. if (axis == Z_AXIS && STOW_PROBE()) return;
  2614. #endif
  2615. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2616. if (DEBUGGING(LEVELING)) {
  2617. SERIAL_ECHOPAIR("<<< homeaxis(", axis_codes[axis]);
  2618. SERIAL_CHAR(')');
  2619. SERIAL_EOL();
  2620. }
  2621. #endif
  2622. } // homeaxis()
  2623. #if ENABLED(FWRETRACT)
  2624. void retract(const bool retracting, const bool swapping = false) {
  2625. static float hop_height;
  2626. if (retracting == retracted[active_extruder]) return;
  2627. const float old_feedrate_mm_s = feedrate_mm_s;
  2628. set_destination_to_current();
  2629. if (retracting) {
  2630. feedrate_mm_s = retract_feedrate_mm_s;
  2631. current_position[E_AXIS] += (swapping ? retract_length_swap : retract_length) / volumetric_multiplier[active_extruder];
  2632. sync_plan_position_e();
  2633. prepare_move_to_destination();
  2634. if (retract_zlift > 0.01) {
  2635. hop_height = current_position[Z_AXIS];
  2636. // Pretend current position is lower
  2637. current_position[Z_AXIS] -= retract_zlift;
  2638. SYNC_PLAN_POSITION_KINEMATIC();
  2639. // Raise up to the old current_position
  2640. prepare_move_to_destination();
  2641. }
  2642. }
  2643. else {
  2644. // If the height hasn't been lowered, undo the Z hop
  2645. if (retract_zlift > 0.01 && hop_height <= current_position[Z_AXIS]) {
  2646. // Pretend current position is higher. Z will lower on the next move
  2647. current_position[Z_AXIS] += retract_zlift;
  2648. SYNC_PLAN_POSITION_KINEMATIC();
  2649. // Lower Z
  2650. prepare_move_to_destination();
  2651. }
  2652. feedrate_mm_s = retract_recover_feedrate_mm_s;
  2653. const float move_e = swapping ? retract_length_swap + retract_recover_length_swap : retract_length + retract_recover_length;
  2654. current_position[E_AXIS] -= move_e / volumetric_multiplier[active_extruder];
  2655. sync_plan_position_e();
  2656. // Recover E
  2657. prepare_move_to_destination();
  2658. }
  2659. feedrate_mm_s = old_feedrate_mm_s;
  2660. retracted[active_extruder] = retracting;
  2661. } // retract()
  2662. #endif // FWRETRACT
  2663. #if ENABLED(MIXING_EXTRUDER)
  2664. void normalize_mix() {
  2665. float mix_total = 0.0;
  2666. for (uint8_t i = 0; i < MIXING_STEPPERS; i++) mix_total += RECIPROCAL(mixing_factor[i]);
  2667. // Scale all values if they don't add up to ~1.0
  2668. if (!NEAR(mix_total, 1.0)) {
  2669. SERIAL_PROTOCOLLNPGM("Warning: Mix factors must add up to 1.0. Scaling.");
  2670. for (uint8_t i = 0; i < MIXING_STEPPERS; i++) mixing_factor[i] *= mix_total;
  2671. }
  2672. }
  2673. #if ENABLED(DIRECT_MIXING_IN_G1)
  2674. // Get mixing parameters from the GCode
  2675. // The total "must" be 1.0 (but it will be normalized)
  2676. // If no mix factors are given, the old mix is preserved
  2677. void gcode_get_mix() {
  2678. const char* mixing_codes = "ABCDHI";
  2679. byte mix_bits = 0;
  2680. for (uint8_t i = 0; i < MIXING_STEPPERS; i++) {
  2681. if (parser.seenval(mixing_codes[i])) {
  2682. SBI(mix_bits, i);
  2683. float v = parser.value_float();
  2684. NOLESS(v, 0.0);
  2685. mixing_factor[i] = RECIPROCAL(v);
  2686. }
  2687. }
  2688. // If any mixing factors were included, clear the rest
  2689. // If none were included, preserve the last mix
  2690. if (mix_bits) {
  2691. for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
  2692. if (!TEST(mix_bits, i)) mixing_factor[i] = 0.0;
  2693. normalize_mix();
  2694. }
  2695. }
  2696. #endif
  2697. #endif
  2698. /**
  2699. * ***************************************************************************
  2700. * ***************************** G-CODE HANDLING *****************************
  2701. * ***************************************************************************
  2702. */
  2703. /**
  2704. * Set XYZE destination and feedrate from the current GCode command
  2705. *
  2706. * - Set destination from included axis codes
  2707. * - Set to current for missing axis codes
  2708. * - Set the feedrate, if included
  2709. */
  2710. void gcode_get_destination() {
  2711. LOOP_XYZE(i) {
  2712. if (parser.seen(axis_codes[i]))
  2713. destination[i] = parser.value_axis_units((AxisEnum)i) + (axis_relative_modes[i] || relative_mode ? current_position[i] : 0);
  2714. else
  2715. destination[i] = current_position[i];
  2716. }
  2717. if (parser.linearval('F') > 0.0)
  2718. feedrate_mm_s = MMM_TO_MMS(parser.value_feedrate());
  2719. #if ENABLED(PRINTCOUNTER)
  2720. if (!DEBUGGING(DRYRUN))
  2721. print_job_timer.incFilamentUsed(destination[E_AXIS] - current_position[E_AXIS]);
  2722. #endif
  2723. // Get ABCDHI mixing factors
  2724. #if ENABLED(MIXING_EXTRUDER) && ENABLED(DIRECT_MIXING_IN_G1)
  2725. gcode_get_mix();
  2726. #endif
  2727. }
  2728. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  2729. /**
  2730. * Output a "busy" message at regular intervals
  2731. * while the machine is not accepting commands.
  2732. */
  2733. void host_keepalive() {
  2734. const millis_t ms = millis();
  2735. if (host_keepalive_interval && busy_state != NOT_BUSY) {
  2736. if (PENDING(ms, next_busy_signal_ms)) return;
  2737. switch (busy_state) {
  2738. case IN_HANDLER:
  2739. case IN_PROCESS:
  2740. SERIAL_ECHO_START();
  2741. SERIAL_ECHOLNPGM(MSG_BUSY_PROCESSING);
  2742. break;
  2743. case PAUSED_FOR_USER:
  2744. SERIAL_ECHO_START();
  2745. SERIAL_ECHOLNPGM(MSG_BUSY_PAUSED_FOR_USER);
  2746. break;
  2747. case PAUSED_FOR_INPUT:
  2748. SERIAL_ECHO_START();
  2749. SERIAL_ECHOLNPGM(MSG_BUSY_PAUSED_FOR_INPUT);
  2750. break;
  2751. default:
  2752. break;
  2753. }
  2754. }
  2755. next_busy_signal_ms = ms + host_keepalive_interval * 1000UL;
  2756. }
  2757. #endif // HOST_KEEPALIVE_FEATURE
  2758. /**************************************************
  2759. ***************** GCode Handlers *****************
  2760. **************************************************/
  2761. /**
  2762. * G0, G1: Coordinated movement of X Y Z E axes
  2763. */
  2764. inline void gcode_G0_G1(
  2765. #if IS_SCARA
  2766. bool fast_move=false
  2767. #endif
  2768. ) {
  2769. if (IsRunning()) {
  2770. gcode_get_destination(); // For X Y Z E F
  2771. #if ENABLED(FWRETRACT)
  2772. if (autoretract_enabled && !(parser.seen('X') || parser.seen('Y') || parser.seen('Z')) && parser.seen('E')) {
  2773. const float echange = destination[E_AXIS] - current_position[E_AXIS];
  2774. // Is this move an attempt to retract or recover?
  2775. if ((echange < -MIN_RETRACT && !retracted[active_extruder]) || (echange > MIN_RETRACT && retracted[active_extruder])) {
  2776. current_position[E_AXIS] = destination[E_AXIS]; // hide the slicer-generated retract/recover from calculations
  2777. sync_plan_position_e(); // AND from the planner
  2778. retract(!retracted[active_extruder]);
  2779. return;
  2780. }
  2781. }
  2782. #endif // FWRETRACT
  2783. #if IS_SCARA
  2784. fast_move ? prepare_uninterpolated_move_to_destination() : prepare_move_to_destination();
  2785. #else
  2786. prepare_move_to_destination();
  2787. #endif
  2788. }
  2789. }
  2790. /**
  2791. * G2: Clockwise Arc
  2792. * G3: Counterclockwise Arc
  2793. *
  2794. * This command has two forms: IJ-form and R-form.
  2795. *
  2796. * - I specifies an X offset. J specifies a Y offset.
  2797. * At least one of the IJ parameters is required.
  2798. * X and Y can be omitted to do a complete circle.
  2799. * The given XY is not error-checked. The arc ends
  2800. * based on the angle of the destination.
  2801. * Mixing I or J with R will throw an error.
  2802. *
  2803. * - R specifies the radius. X or Y is required.
  2804. * Omitting both X and Y will throw an error.
  2805. * X or Y must differ from the current XY.
  2806. * Mixing R with I or J will throw an error.
  2807. *
  2808. * - P specifies the number of full circles to do
  2809. * before the specified arc move.
  2810. *
  2811. * Examples:
  2812. *
  2813. * G2 I10 ; CW circle centered at X+10
  2814. * G3 X20 Y12 R14 ; CCW circle with r=14 ending at X20 Y12
  2815. */
  2816. #if ENABLED(ARC_SUPPORT)
  2817. inline void gcode_G2_G3(bool clockwise) {
  2818. if (IsRunning()) {
  2819. #if ENABLED(SF_ARC_FIX)
  2820. const bool relative_mode_backup = relative_mode;
  2821. relative_mode = true;
  2822. #endif
  2823. gcode_get_destination();
  2824. #if ENABLED(SF_ARC_FIX)
  2825. relative_mode = relative_mode_backup;
  2826. #endif
  2827. float arc_offset[2] = { 0.0, 0.0 };
  2828. if (parser.seenval('R')) {
  2829. const float r = parser.value_linear_units(),
  2830. p1 = current_position[X_AXIS], q1 = current_position[Y_AXIS],
  2831. p2 = destination[X_AXIS], q2 = destination[Y_AXIS];
  2832. if (r && (p2 != p1 || q2 != q1)) {
  2833. const float e = clockwise ^ (r < 0) ? -1 : 1, // clockwise -1/1, counterclockwise 1/-1
  2834. dx = p2 - p1, dy = q2 - q1, // X and Y differences
  2835. d = HYPOT(dx, dy), // Linear distance between the points
  2836. h = SQRT(sq(r) - sq(d * 0.5)), // Distance to the arc pivot-point
  2837. mx = (p1 + p2) * 0.5, my = (q1 + q2) * 0.5, // Point between the two points
  2838. sx = -dy / d, sy = dx / d, // Slope of the perpendicular bisector
  2839. cx = mx + e * h * sx, cy = my + e * h * sy; // Pivot-point of the arc
  2840. arc_offset[0] = cx - p1;
  2841. arc_offset[1] = cy - q1;
  2842. }
  2843. }
  2844. else {
  2845. if (parser.seenval('I')) arc_offset[0] = parser.value_linear_units();
  2846. if (parser.seenval('J')) arc_offset[1] = parser.value_linear_units();
  2847. }
  2848. if (arc_offset[0] || arc_offset[1]) {
  2849. #if ENABLED(ARC_P_CIRCLES)
  2850. // P indicates number of circles to do
  2851. int8_t circles_to_do = parser.byteval('P');
  2852. if (!WITHIN(circles_to_do, 0, 100)) {
  2853. SERIAL_ERROR_START();
  2854. SERIAL_ERRORLNPGM(MSG_ERR_ARC_ARGS);
  2855. }
  2856. while (circles_to_do--)
  2857. plan_arc(current_position, arc_offset, clockwise);
  2858. #endif
  2859. // Send the arc to the planner
  2860. plan_arc(destination, arc_offset, clockwise);
  2861. refresh_cmd_timeout();
  2862. }
  2863. else {
  2864. // Bad arguments
  2865. SERIAL_ERROR_START();
  2866. SERIAL_ERRORLNPGM(MSG_ERR_ARC_ARGS);
  2867. }
  2868. }
  2869. }
  2870. #endif // ARC_SUPPORT
  2871. /**
  2872. * G4: Dwell S<seconds> or P<milliseconds>
  2873. */
  2874. inline void gcode_G4() {
  2875. millis_t dwell_ms = 0;
  2876. if (parser.seenval('P')) dwell_ms = parser.value_millis(); // milliseconds to wait
  2877. if (parser.seenval('S')) dwell_ms = parser.value_millis_from_seconds(); // seconds to wait
  2878. stepper.synchronize();
  2879. refresh_cmd_timeout();
  2880. dwell_ms += previous_cmd_ms; // keep track of when we started waiting
  2881. if (!lcd_hasstatus()) LCD_MESSAGEPGM(MSG_DWELL);
  2882. while (PENDING(millis(), dwell_ms)) idle();
  2883. }
  2884. #if ENABLED(BEZIER_CURVE_SUPPORT)
  2885. /**
  2886. * Parameters interpreted according to:
  2887. * http://linuxcnc.org/docs/2.6/html/gcode/gcode.html#sec:G5-Cubic-Spline
  2888. * However I, J omission is not supported at this point; all
  2889. * parameters can be omitted and default to zero.
  2890. */
  2891. /**
  2892. * G5: Cubic B-spline
  2893. */
  2894. inline void gcode_G5() {
  2895. if (IsRunning()) {
  2896. gcode_get_destination();
  2897. const float offset[] = {
  2898. parser.linearval('I'),
  2899. parser.linearval('J'),
  2900. parser.linearval('P'),
  2901. parser.linearval('Q')
  2902. };
  2903. plan_cubic_move(offset);
  2904. }
  2905. }
  2906. #endif // BEZIER_CURVE_SUPPORT
  2907. #if ENABLED(FWRETRACT)
  2908. /**
  2909. * G10 - Retract filament according to settings of M207
  2910. * G11 - Recover filament according to settings of M208
  2911. */
  2912. inline void gcode_G10_G11(bool doRetract=false) {
  2913. #if EXTRUDERS > 1
  2914. if (doRetract)
  2915. retracted_swap[active_extruder] = parser.boolval('S'); // checks for swap retract argument
  2916. #endif
  2917. retract(doRetract
  2918. #if EXTRUDERS > 1
  2919. , retracted_swap[active_extruder]
  2920. #endif
  2921. );
  2922. }
  2923. #endif // FWRETRACT
  2924. #if ENABLED(NOZZLE_CLEAN_FEATURE)
  2925. /**
  2926. * G12: Clean the nozzle
  2927. */
  2928. inline void gcode_G12() {
  2929. // Don't allow nozzle cleaning without homing first
  2930. if (axis_unhomed_error()) return;
  2931. const uint8_t pattern = parser.ushortval('P', 0),
  2932. strokes = parser.ushortval('S', NOZZLE_CLEAN_STROKES),
  2933. objects = parser.ushortval('T', NOZZLE_CLEAN_TRIANGLES);
  2934. const float radius = parser.floatval('R', NOZZLE_CLEAN_CIRCLE_RADIUS);
  2935. Nozzle::clean(pattern, strokes, radius, objects);
  2936. }
  2937. #endif
  2938. #if ENABLED(CNC_WORKSPACE_PLANES)
  2939. void report_workspace_plane() {
  2940. SERIAL_ECHO_START();
  2941. SERIAL_ECHOPGM("Workspace Plane ");
  2942. serialprintPGM(workspace_plane == PLANE_YZ ? PSTR("YZ\n") : workspace_plane == PLANE_ZX ? PSTR("ZX\n") : PSTR("XY\n"));
  2943. }
  2944. /**
  2945. * G17: Select Plane XY
  2946. * G18: Select Plane ZX
  2947. * G19: Select Plane YZ
  2948. */
  2949. inline void gcode_G17() { workspace_plane = PLANE_XY; }
  2950. inline void gcode_G18() { workspace_plane = PLANE_ZX; }
  2951. inline void gcode_G19() { workspace_plane = PLANE_YZ; }
  2952. #endif // CNC_WORKSPACE_PLANES
  2953. #if ENABLED(INCH_MODE_SUPPORT)
  2954. /**
  2955. * G20: Set input mode to inches
  2956. */
  2957. inline void gcode_G20() { parser.set_input_linear_units(LINEARUNIT_INCH); }
  2958. /**
  2959. * G21: Set input mode to millimeters
  2960. */
  2961. inline void gcode_G21() { parser.set_input_linear_units(LINEARUNIT_MM); }
  2962. #endif
  2963. #if ENABLED(NOZZLE_PARK_FEATURE)
  2964. /**
  2965. * G27: Park the nozzle
  2966. */
  2967. inline void gcode_G27() {
  2968. // Don't allow nozzle parking without homing first
  2969. if (axis_unhomed_error()) return;
  2970. Nozzle::park(parser.ushortval('P'));
  2971. }
  2972. #endif // NOZZLE_PARK_FEATURE
  2973. #if ENABLED(QUICK_HOME)
  2974. static void quick_home_xy() {
  2975. // Pretend the current position is 0,0
  2976. current_position[X_AXIS] = current_position[Y_AXIS] = 0.0;
  2977. sync_plan_position();
  2978. const int x_axis_home_dir =
  2979. #if ENABLED(DUAL_X_CARRIAGE)
  2980. x_home_dir(active_extruder)
  2981. #else
  2982. home_dir(X_AXIS)
  2983. #endif
  2984. ;
  2985. const float mlx = max_length(X_AXIS),
  2986. mly = max_length(Y_AXIS),
  2987. mlratio = mlx > mly ? mly / mlx : mlx / mly,
  2988. fr_mm_s = min(homing_feedrate(X_AXIS), homing_feedrate(Y_AXIS)) * SQRT(sq(mlratio) + 1.0);
  2989. do_blocking_move_to_xy(1.5 * mlx * x_axis_home_dir, 1.5 * mly * home_dir(Y_AXIS), fr_mm_s);
  2990. endstops.hit_on_purpose(); // clear endstop hit flags
  2991. current_position[X_AXIS] = current_position[Y_AXIS] = 0.0;
  2992. }
  2993. #endif // QUICK_HOME
  2994. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2995. void log_machine_info() {
  2996. SERIAL_ECHOPGM("Machine Type: ");
  2997. #if ENABLED(DELTA)
  2998. SERIAL_ECHOLNPGM("Delta");
  2999. #elif IS_SCARA
  3000. SERIAL_ECHOLNPGM("SCARA");
  3001. #elif IS_CORE
  3002. SERIAL_ECHOLNPGM("Core");
  3003. #else
  3004. SERIAL_ECHOLNPGM("Cartesian");
  3005. #endif
  3006. SERIAL_ECHOPGM("Probe: ");
  3007. #if ENABLED(PROBE_MANUALLY)
  3008. SERIAL_ECHOLNPGM("PROBE_MANUALLY");
  3009. #elif ENABLED(FIX_MOUNTED_PROBE)
  3010. SERIAL_ECHOLNPGM("FIX_MOUNTED_PROBE");
  3011. #elif ENABLED(BLTOUCH)
  3012. SERIAL_ECHOLNPGM("BLTOUCH");
  3013. #elif HAS_Z_SERVO_ENDSTOP
  3014. SERIAL_ECHOLNPGM("SERVO PROBE");
  3015. #elif ENABLED(Z_PROBE_SLED)
  3016. SERIAL_ECHOLNPGM("Z_PROBE_SLED");
  3017. #elif ENABLED(Z_PROBE_ALLEN_KEY)
  3018. SERIAL_ECHOLNPGM("Z_PROBE_ALLEN_KEY");
  3019. #else
  3020. SERIAL_ECHOLNPGM("NONE");
  3021. #endif
  3022. #if HAS_BED_PROBE
  3023. SERIAL_ECHOPAIR("Probe Offset X:", X_PROBE_OFFSET_FROM_EXTRUDER);
  3024. SERIAL_ECHOPAIR(" Y:", Y_PROBE_OFFSET_FROM_EXTRUDER);
  3025. SERIAL_ECHOPAIR(" Z:", zprobe_zoffset);
  3026. #if X_PROBE_OFFSET_FROM_EXTRUDER > 0
  3027. SERIAL_ECHOPGM(" (Right");
  3028. #elif X_PROBE_OFFSET_FROM_EXTRUDER < 0
  3029. SERIAL_ECHOPGM(" (Left");
  3030. #elif Y_PROBE_OFFSET_FROM_EXTRUDER != 0
  3031. SERIAL_ECHOPGM(" (Middle");
  3032. #else
  3033. SERIAL_ECHOPGM(" (Aligned With");
  3034. #endif
  3035. #if Y_PROBE_OFFSET_FROM_EXTRUDER > 0
  3036. SERIAL_ECHOPGM("-Back");
  3037. #elif Y_PROBE_OFFSET_FROM_EXTRUDER < 0
  3038. SERIAL_ECHOPGM("-Front");
  3039. #elif X_PROBE_OFFSET_FROM_EXTRUDER != 0
  3040. SERIAL_ECHOPGM("-Center");
  3041. #endif
  3042. if (zprobe_zoffset < 0)
  3043. SERIAL_ECHOPGM(" & Below");
  3044. else if (zprobe_zoffset > 0)
  3045. SERIAL_ECHOPGM(" & Above");
  3046. else
  3047. SERIAL_ECHOPGM(" & Same Z as");
  3048. SERIAL_ECHOLNPGM(" Nozzle)");
  3049. #endif
  3050. #if HAS_ABL
  3051. SERIAL_ECHOPGM("Auto Bed Leveling: ");
  3052. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  3053. SERIAL_ECHOPGM("LINEAR");
  3054. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3055. SERIAL_ECHOPGM("BILINEAR");
  3056. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  3057. SERIAL_ECHOPGM("3POINT");
  3058. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  3059. SERIAL_ECHOPGM("UBL");
  3060. #endif
  3061. if (leveling_is_active()) {
  3062. SERIAL_ECHOLNPGM(" (enabled)");
  3063. #if ABL_PLANAR
  3064. const float diff[XYZ] = {
  3065. stepper.get_axis_position_mm(X_AXIS) - current_position[X_AXIS],
  3066. stepper.get_axis_position_mm(Y_AXIS) - current_position[Y_AXIS],
  3067. stepper.get_axis_position_mm(Z_AXIS) - current_position[Z_AXIS]
  3068. };
  3069. SERIAL_ECHOPGM("ABL Adjustment X");
  3070. if (diff[X_AXIS] > 0) SERIAL_CHAR('+');
  3071. SERIAL_ECHO(diff[X_AXIS]);
  3072. SERIAL_ECHOPGM(" Y");
  3073. if (diff[Y_AXIS] > 0) SERIAL_CHAR('+');
  3074. SERIAL_ECHO(diff[Y_AXIS]);
  3075. SERIAL_ECHOPGM(" Z");
  3076. if (diff[Z_AXIS] > 0) SERIAL_CHAR('+');
  3077. SERIAL_ECHO(diff[Z_AXIS]);
  3078. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  3079. SERIAL_ECHOPAIR("UBL Adjustment Z", stepper.get_axis_position_mm(Z_AXIS) - current_position[Z_AXIS]);
  3080. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3081. SERIAL_ECHOPAIR("ABL Adjustment Z", bilinear_z_offset(current_position));
  3082. #endif
  3083. }
  3084. else
  3085. SERIAL_ECHOLNPGM(" (disabled)");
  3086. SERIAL_EOL();
  3087. #elif ENABLED(MESH_BED_LEVELING)
  3088. SERIAL_ECHOPGM("Mesh Bed Leveling");
  3089. if (leveling_is_active()) {
  3090. float lz = current_position[Z_AXIS];
  3091. planner.apply_leveling(current_position[X_AXIS], current_position[Y_AXIS], lz);
  3092. SERIAL_ECHOLNPGM(" (enabled)");
  3093. SERIAL_ECHOPAIR("MBL Adjustment Z", lz);
  3094. }
  3095. else
  3096. SERIAL_ECHOPGM(" (disabled)");
  3097. SERIAL_EOL();
  3098. #endif // MESH_BED_LEVELING
  3099. }
  3100. #endif // DEBUG_LEVELING_FEATURE
  3101. #if ENABLED(DELTA)
  3102. /**
  3103. * A delta can only safely home all axes at the same time
  3104. * This is like quick_home_xy() but for 3 towers.
  3105. */
  3106. inline void home_delta() {
  3107. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3108. if (DEBUGGING(LEVELING)) DEBUG_POS(">>> home_delta", current_position);
  3109. #endif
  3110. // Init the current position of all carriages to 0,0,0
  3111. ZERO(current_position);
  3112. sync_plan_position();
  3113. // Move all carriages together linearly until an endstop is hit.
  3114. current_position[X_AXIS] = current_position[Y_AXIS] = current_position[Z_AXIS] = (Z_MAX_LENGTH + 10);
  3115. feedrate_mm_s = homing_feedrate(X_AXIS);
  3116. line_to_current_position();
  3117. stepper.synchronize();
  3118. endstops.hit_on_purpose(); // clear endstop hit flags
  3119. // At least one carriage has reached the top.
  3120. // Now re-home each carriage separately.
  3121. HOMEAXIS(A);
  3122. HOMEAXIS(B);
  3123. HOMEAXIS(C);
  3124. // Set all carriages to their home positions
  3125. // Do this here all at once for Delta, because
  3126. // XYZ isn't ABC. Applying this per-tower would
  3127. // give the impression that they are the same.
  3128. LOOP_XYZ(i) set_axis_is_at_home((AxisEnum)i);
  3129. SYNC_PLAN_POSITION_KINEMATIC();
  3130. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3131. if (DEBUGGING(LEVELING)) DEBUG_POS("<<< home_delta", current_position);
  3132. #endif
  3133. }
  3134. #endif // DELTA
  3135. #if ENABLED(Z_SAFE_HOMING)
  3136. inline void home_z_safely() {
  3137. // Disallow Z homing if X or Y are unknown
  3138. if (!axis_known_position[X_AXIS] || !axis_known_position[Y_AXIS]) {
  3139. LCD_MESSAGEPGM(MSG_ERR_Z_HOMING);
  3140. SERIAL_ECHO_START();
  3141. SERIAL_ECHOLNPGM(MSG_ERR_Z_HOMING);
  3142. return;
  3143. }
  3144. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3145. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Z_SAFE_HOMING >>>");
  3146. #endif
  3147. SYNC_PLAN_POSITION_KINEMATIC();
  3148. /**
  3149. * Move the Z probe (or just the nozzle) to the safe homing point
  3150. */
  3151. destination[X_AXIS] = LOGICAL_X_POSITION(Z_SAFE_HOMING_X_POINT);
  3152. destination[Y_AXIS] = LOGICAL_Y_POSITION(Z_SAFE_HOMING_Y_POINT);
  3153. destination[Z_AXIS] = current_position[Z_AXIS]; // Z is already at the right height
  3154. #if HOMING_Z_WITH_PROBE
  3155. destination[X_AXIS] -= X_PROBE_OFFSET_FROM_EXTRUDER;
  3156. destination[Y_AXIS] -= Y_PROBE_OFFSET_FROM_EXTRUDER;
  3157. #endif
  3158. if (position_is_reachable_xy(destination[X_AXIS], destination[Y_AXIS])) {
  3159. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3160. if (DEBUGGING(LEVELING)) DEBUG_POS("Z_SAFE_HOMING", destination);
  3161. #endif
  3162. // This causes the carriage on Dual X to unpark
  3163. #if ENABLED(DUAL_X_CARRIAGE)
  3164. active_extruder_parked = false;
  3165. #endif
  3166. do_blocking_move_to_xy(destination[X_AXIS], destination[Y_AXIS]);
  3167. HOMEAXIS(Z);
  3168. }
  3169. else {
  3170. LCD_MESSAGEPGM(MSG_ZPROBE_OUT);
  3171. SERIAL_ECHO_START();
  3172. SERIAL_ECHOLNPGM(MSG_ZPROBE_OUT);
  3173. }
  3174. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3175. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< Z_SAFE_HOMING");
  3176. #endif
  3177. }
  3178. #endif // Z_SAFE_HOMING
  3179. #if ENABLED(PROBE_MANUALLY)
  3180. bool g29_in_progress = false;
  3181. #else
  3182. constexpr bool g29_in_progress = false;
  3183. #endif
  3184. /**
  3185. * G28: Home all axes according to settings
  3186. *
  3187. * Parameters
  3188. *
  3189. * None Home to all axes with no parameters.
  3190. * With QUICK_HOME enabled XY will home together, then Z.
  3191. *
  3192. * Cartesian parameters
  3193. *
  3194. * X Home to the X endstop
  3195. * Y Home to the Y endstop
  3196. * Z Home to the Z endstop
  3197. *
  3198. */
  3199. inline void gcode_G28(const bool always_home_all) {
  3200. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3201. if (DEBUGGING(LEVELING)) {
  3202. SERIAL_ECHOLNPGM(">>> gcode_G28");
  3203. log_machine_info();
  3204. }
  3205. #endif
  3206. // Wait for planner moves to finish!
  3207. stepper.synchronize();
  3208. // Cancel the active G29 session
  3209. #if ENABLED(PROBE_MANUALLY)
  3210. g29_in_progress = false;
  3211. #endif
  3212. // Disable the leveling matrix before homing
  3213. #if HAS_LEVELING
  3214. #if ENABLED(AUTO_BED_LEVELING_UBL)
  3215. const bool ubl_state_at_entry = leveling_is_active();
  3216. #endif
  3217. set_bed_leveling_enabled(false);
  3218. #endif
  3219. #if ENABLED(CNC_WORKSPACE_PLANES)
  3220. workspace_plane = PLANE_XY;
  3221. #endif
  3222. // Always home with tool 0 active
  3223. #if HOTENDS > 1
  3224. const uint8_t old_tool_index = active_extruder;
  3225. tool_change(0, 0, true);
  3226. #endif
  3227. #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(DUAL_NOZZLE_DUPLICATION_MODE)
  3228. extruder_duplication_enabled = false;
  3229. #endif
  3230. setup_for_endstop_or_probe_move();
  3231. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3232. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("> endstops.enable(true)");
  3233. #endif
  3234. endstops.enable(true); // Enable endstops for next homing move
  3235. #if ENABLED(DELTA)
  3236. home_delta();
  3237. UNUSED(always_home_all);
  3238. #else // NOT DELTA
  3239. const bool homeX = always_home_all || parser.seen('X'),
  3240. homeY = always_home_all || parser.seen('Y'),
  3241. homeZ = always_home_all || parser.seen('Z'),
  3242. home_all = (!homeX && !homeY && !homeZ) || (homeX && homeY && homeZ);
  3243. set_destination_to_current();
  3244. #if Z_HOME_DIR > 0 // If homing away from BED do Z first
  3245. if (home_all || homeZ) {
  3246. HOMEAXIS(Z);
  3247. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3248. if (DEBUGGING(LEVELING)) DEBUG_POS("> HOMEAXIS(Z)", current_position);
  3249. #endif
  3250. }
  3251. #else
  3252. if (home_all || homeX || homeY) {
  3253. // Raise Z before homing any other axes and z is not already high enough (never lower z)
  3254. destination[Z_AXIS] = LOGICAL_Z_POSITION(Z_HOMING_HEIGHT);
  3255. if (destination[Z_AXIS] > current_position[Z_AXIS]) {
  3256. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3257. if (DEBUGGING(LEVELING))
  3258. SERIAL_ECHOLNPAIR("Raise Z (before homing) to ", destination[Z_AXIS]);
  3259. #endif
  3260. do_blocking_move_to_z(destination[Z_AXIS]);
  3261. }
  3262. }
  3263. #endif
  3264. #if ENABLED(QUICK_HOME)
  3265. if (home_all || (homeX && homeY)) quick_home_xy();
  3266. #endif
  3267. #if ENABLED(HOME_Y_BEFORE_X)
  3268. // Home Y
  3269. if (home_all || homeY) {
  3270. HOMEAXIS(Y);
  3271. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3272. if (DEBUGGING(LEVELING)) DEBUG_POS("> homeY", current_position);
  3273. #endif
  3274. }
  3275. #endif
  3276. // Home X
  3277. if (home_all || homeX) {
  3278. #if ENABLED(DUAL_X_CARRIAGE)
  3279. // Always home the 2nd (right) extruder first
  3280. active_extruder = 1;
  3281. HOMEAXIS(X);
  3282. // Remember this extruder's position for later tool change
  3283. inactive_extruder_x_pos = RAW_X_POSITION(current_position[X_AXIS]);
  3284. // Home the 1st (left) extruder
  3285. active_extruder = 0;
  3286. HOMEAXIS(X);
  3287. // Consider the active extruder to be parked
  3288. COPY(raised_parked_position, current_position);
  3289. delayed_move_time = 0;
  3290. active_extruder_parked = true;
  3291. #else
  3292. HOMEAXIS(X);
  3293. #endif
  3294. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3295. if (DEBUGGING(LEVELING)) DEBUG_POS("> homeX", current_position);
  3296. #endif
  3297. }
  3298. #if DISABLED(HOME_Y_BEFORE_X)
  3299. // Home Y
  3300. if (home_all || homeY) {
  3301. HOMEAXIS(Y);
  3302. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3303. if (DEBUGGING(LEVELING)) DEBUG_POS("> homeY", current_position);
  3304. #endif
  3305. }
  3306. #endif
  3307. // Home Z last if homing towards the bed
  3308. #if Z_HOME_DIR < 0
  3309. if (home_all || homeZ) {
  3310. #if ENABLED(Z_SAFE_HOMING)
  3311. home_z_safely();
  3312. #else
  3313. HOMEAXIS(Z);
  3314. #endif
  3315. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3316. if (DEBUGGING(LEVELING)) DEBUG_POS("> (home_all || homeZ) > final", current_position);
  3317. #endif
  3318. } // home_all || homeZ
  3319. #endif // Z_HOME_DIR < 0
  3320. SYNC_PLAN_POSITION_KINEMATIC();
  3321. #endif // !DELTA (gcode_G28)
  3322. endstops.not_homing();
  3323. #if ENABLED(DELTA) && ENABLED(DELTA_HOME_TO_SAFE_ZONE)
  3324. // move to a height where we can use the full xy-area
  3325. do_blocking_move_to_z(delta_clip_start_height);
  3326. #endif
  3327. #if ENABLED(AUTO_BED_LEVELING_UBL)
  3328. set_bed_leveling_enabled(ubl_state_at_entry);
  3329. #endif
  3330. clean_up_after_endstop_or_probe_move();
  3331. // Restore the active tool after homing
  3332. #if HOTENDS > 1
  3333. tool_change(old_tool_index, 0, true);
  3334. #endif
  3335. lcd_refresh();
  3336. report_current_position();
  3337. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3338. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< gcode_G28");
  3339. #endif
  3340. } // G28
  3341. void home_all_axes() { gcode_G28(true); }
  3342. #if HAS_PROBING_PROCEDURE
  3343. void out_of_range_error(const char* p_edge) {
  3344. SERIAL_PROTOCOLPGM("?Probe ");
  3345. serialprintPGM(p_edge);
  3346. SERIAL_PROTOCOLLNPGM(" position out of range.");
  3347. }
  3348. #endif
  3349. #if ENABLED(MESH_BED_LEVELING) || ENABLED(PROBE_MANUALLY)
  3350. #if ENABLED(PROBE_MANUALLY) && ENABLED(LCD_BED_LEVELING)
  3351. extern bool lcd_wait_for_move;
  3352. #endif
  3353. inline void _manual_goto_xy(const float &x, const float &y) {
  3354. const float old_feedrate_mm_s = feedrate_mm_s;
  3355. #if MANUAL_PROBE_HEIGHT > 0
  3356. feedrate_mm_s = homing_feedrate(Z_AXIS);
  3357. current_position[Z_AXIS] = LOGICAL_Z_POSITION(Z_MIN_POS) + MANUAL_PROBE_HEIGHT;
  3358. line_to_current_position();
  3359. #endif
  3360. feedrate_mm_s = MMM_TO_MMS(XY_PROBE_SPEED);
  3361. current_position[X_AXIS] = LOGICAL_X_POSITION(x);
  3362. current_position[Y_AXIS] = LOGICAL_Y_POSITION(y);
  3363. line_to_current_position();
  3364. #if MANUAL_PROBE_HEIGHT > 0
  3365. feedrate_mm_s = homing_feedrate(Z_AXIS);
  3366. current_position[Z_AXIS] = LOGICAL_Z_POSITION(Z_MIN_POS); // just slightly over the bed
  3367. line_to_current_position();
  3368. #endif
  3369. feedrate_mm_s = old_feedrate_mm_s;
  3370. stepper.synchronize();
  3371. #if ENABLED(PROBE_MANUALLY) && ENABLED(LCD_BED_LEVELING)
  3372. lcd_wait_for_move = false;
  3373. #endif
  3374. }
  3375. #endif
  3376. #if ENABLED(MESH_BED_LEVELING)
  3377. // Save 130 bytes with non-duplication of PSTR
  3378. void echo_not_entered() { SERIAL_PROTOCOLLNPGM(" not entered."); }
  3379. void mbl_mesh_report() {
  3380. SERIAL_PROTOCOLLNPGM("Num X,Y: " STRINGIFY(GRID_MAX_POINTS_X) "," STRINGIFY(GRID_MAX_POINTS_Y));
  3381. SERIAL_PROTOCOLPGM("Z offset: "); SERIAL_PROTOCOL_F(mbl.z_offset, 5);
  3382. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  3383. print_2d_array(GRID_MAX_POINTS_X, GRID_MAX_POINTS_Y, 5,
  3384. [](const uint8_t ix, const uint8_t iy) { return mbl.z_values[ix][iy]; }
  3385. );
  3386. }
  3387. void mesh_probing_done() {
  3388. mbl.set_has_mesh(true);
  3389. home_all_axes();
  3390. set_bed_leveling_enabled(true);
  3391. #if ENABLED(MESH_G28_REST_ORIGIN)
  3392. current_position[Z_AXIS] = LOGICAL_Z_POSITION(Z_MIN_POS);
  3393. set_destination_to_current();
  3394. line_to_destination(homing_feedrate(Z_AXIS));
  3395. stepper.synchronize();
  3396. #endif
  3397. }
  3398. /**
  3399. * G29: Mesh-based Z probe, probes a grid and produces a
  3400. * mesh to compensate for variable bed height
  3401. *
  3402. * Parameters With MESH_BED_LEVELING:
  3403. *
  3404. * S0 Produce a mesh report
  3405. * S1 Start probing mesh points
  3406. * S2 Probe the next mesh point
  3407. * S3 Xn Yn Zn.nn Manually modify a single point
  3408. * S4 Zn.nn Set z offset. Positive away from bed, negative closer to bed.
  3409. * S5 Reset and disable mesh
  3410. *
  3411. * The S0 report the points as below
  3412. *
  3413. * +----> X-axis 1-n
  3414. * |
  3415. * |
  3416. * v Y-axis 1-n
  3417. *
  3418. */
  3419. inline void gcode_G29() {
  3420. static int mbl_probe_index = -1;
  3421. #if HAS_SOFTWARE_ENDSTOPS
  3422. static bool enable_soft_endstops;
  3423. #endif
  3424. const MeshLevelingState state = (MeshLevelingState)parser.byteval('S', (int8_t)MeshReport);
  3425. if (!WITHIN(state, 0, 5)) {
  3426. SERIAL_PROTOCOLLNPGM("S out of range (0-5).");
  3427. return;
  3428. }
  3429. int8_t px, py;
  3430. switch (state) {
  3431. case MeshReport:
  3432. if (leveling_is_valid()) {
  3433. SERIAL_PROTOCOLLNPAIR("State: ", leveling_is_active() ? MSG_ON : MSG_OFF);
  3434. mbl_mesh_report();
  3435. }
  3436. else
  3437. SERIAL_PROTOCOLLNPGM("Mesh bed leveling has no data.");
  3438. break;
  3439. case MeshStart:
  3440. mbl.reset();
  3441. mbl_probe_index = 0;
  3442. enqueue_and_echo_commands_P(PSTR("G28\nG29 S2"));
  3443. break;
  3444. case MeshNext:
  3445. if (mbl_probe_index < 0) {
  3446. SERIAL_PROTOCOLLNPGM("Start mesh probing with \"G29 S1\" first.");
  3447. return;
  3448. }
  3449. // For each G29 S2...
  3450. if (mbl_probe_index == 0) {
  3451. #if HAS_SOFTWARE_ENDSTOPS
  3452. // For the initial G29 S2 save software endstop state
  3453. enable_soft_endstops = soft_endstops_enabled;
  3454. #endif
  3455. }
  3456. else {
  3457. // For G29 S2 after adjusting Z.
  3458. mbl.set_zigzag_z(mbl_probe_index - 1, current_position[Z_AXIS]);
  3459. #if HAS_SOFTWARE_ENDSTOPS
  3460. soft_endstops_enabled = enable_soft_endstops;
  3461. #endif
  3462. }
  3463. // If there's another point to sample, move there with optional lift.
  3464. if (mbl_probe_index < GRID_MAX_POINTS) {
  3465. mbl.zigzag(mbl_probe_index, px, py);
  3466. _manual_goto_xy(mbl.index_to_xpos[px], mbl.index_to_ypos[py]);
  3467. #if HAS_SOFTWARE_ENDSTOPS
  3468. // Disable software endstops to allow manual adjustment
  3469. // If G29 is not completed, they will not be re-enabled
  3470. soft_endstops_enabled = false;
  3471. #endif
  3472. mbl_probe_index++;
  3473. }
  3474. else {
  3475. // One last "return to the bed" (as originally coded) at completion
  3476. current_position[Z_AXIS] = LOGICAL_Z_POSITION(Z_MIN_POS) + MANUAL_PROBE_HEIGHT;
  3477. line_to_current_position();
  3478. stepper.synchronize();
  3479. // After recording the last point, activate home and activate
  3480. mbl_probe_index = -1;
  3481. SERIAL_PROTOCOLLNPGM("Mesh probing done.");
  3482. BUZZ(100, 659);
  3483. BUZZ(100, 698);
  3484. mesh_probing_done();
  3485. }
  3486. break;
  3487. case MeshSet:
  3488. if (parser.seenval('X')) {
  3489. px = parser.value_int() - 1;
  3490. if (!WITHIN(px, 0, GRID_MAX_POINTS_X - 1)) {
  3491. SERIAL_PROTOCOLLNPGM("X out of range (1-" STRINGIFY(GRID_MAX_POINTS_X) ").");
  3492. return;
  3493. }
  3494. }
  3495. else {
  3496. SERIAL_CHAR('X'); echo_not_entered();
  3497. return;
  3498. }
  3499. if (parser.seenval('Y')) {
  3500. py = parser.value_int() - 1;
  3501. if (!WITHIN(py, 0, GRID_MAX_POINTS_Y - 1)) {
  3502. SERIAL_PROTOCOLLNPGM("Y out of range (1-" STRINGIFY(GRID_MAX_POINTS_Y) ").");
  3503. return;
  3504. }
  3505. }
  3506. else {
  3507. SERIAL_CHAR('Y'); echo_not_entered();
  3508. return;
  3509. }
  3510. if (parser.seenval('Z')) {
  3511. mbl.z_values[px][py] = parser.value_linear_units();
  3512. }
  3513. else {
  3514. SERIAL_CHAR('Z'); echo_not_entered();
  3515. return;
  3516. }
  3517. break;
  3518. case MeshSetZOffset:
  3519. if (parser.seenval('Z')) {
  3520. mbl.z_offset = parser.value_linear_units();
  3521. }
  3522. else {
  3523. SERIAL_CHAR('Z'); echo_not_entered();
  3524. return;
  3525. }
  3526. break;
  3527. case MeshReset:
  3528. reset_bed_level();
  3529. break;
  3530. } // switch(state)
  3531. report_current_position();
  3532. }
  3533. #elif HAS_ABL && DISABLED(AUTO_BED_LEVELING_UBL)
  3534. #if ABL_GRID
  3535. #if ENABLED(PROBE_Y_FIRST)
  3536. #define PR_OUTER_VAR xCount
  3537. #define PR_OUTER_END abl_grid_points_x
  3538. #define PR_INNER_VAR yCount
  3539. #define PR_INNER_END abl_grid_points_y
  3540. #else
  3541. #define PR_OUTER_VAR yCount
  3542. #define PR_OUTER_END abl_grid_points_y
  3543. #define PR_INNER_VAR xCount
  3544. #define PR_INNER_END abl_grid_points_x
  3545. #endif
  3546. #endif
  3547. /**
  3548. * G29: Detailed Z probe, probes the bed at 3 or more points.
  3549. * Will fail if the printer has not been homed with G28.
  3550. *
  3551. * Enhanced G29 Auto Bed Leveling Probe Routine
  3552. *
  3553. * D Dry-Run mode. Just evaluate the bed Topology - Don't apply
  3554. * or alter the bed level data. Useful to check the topology
  3555. * after a first run of G29.
  3556. *
  3557. * J Jettison current bed leveling data
  3558. *
  3559. * V Set the verbose level (0-4). Example: "G29 V3"
  3560. *
  3561. * Parameters With LINEAR leveling only:
  3562. *
  3563. * P Set the size of the grid that will be probed (P x P points).
  3564. * Example: "G29 P4"
  3565. *
  3566. * X Set the X size of the grid that will be probed (X x Y points).
  3567. * Example: "G29 X7 Y5"
  3568. *
  3569. * Y Set the Y size of the grid that will be probed (X x Y points).
  3570. *
  3571. * T Generate a Bed Topology Report. Example: "G29 P5 T" for a detailed report.
  3572. * This is useful for manual bed leveling and finding flaws in the bed (to
  3573. * assist with part placement).
  3574. * Not supported by non-linear delta printer bed leveling.
  3575. *
  3576. * Parameters With LINEAR and BILINEAR leveling only:
  3577. *
  3578. * S Set the XY travel speed between probe points (in units/min)
  3579. *
  3580. * F Set the Front limit of the probing grid
  3581. * B Set the Back limit of the probing grid
  3582. * L Set the Left limit of the probing grid
  3583. * R Set the Right limit of the probing grid
  3584. *
  3585. * Parameters with DEBUG_LEVELING_FEATURE only:
  3586. *
  3587. * C Make a totally fake grid with no actual probing.
  3588. * For use in testing when no probing is possible.
  3589. *
  3590. * Parameters with BILINEAR leveling only:
  3591. *
  3592. * Z Supply an additional Z probe offset
  3593. *
  3594. * Extra parameters with PROBE_MANUALLY:
  3595. *
  3596. * To do manual probing simply repeat G29 until the procedure is complete.
  3597. * The first G29 accepts parameters. 'G29 Q' for status, 'G29 A' to abort.
  3598. *
  3599. * Q Query leveling and G29 state
  3600. *
  3601. * A Abort current leveling procedure
  3602. *
  3603. * Extra parameters with BILINEAR only:
  3604. *
  3605. * W Write a mesh point. (If G29 is idle.)
  3606. * I X index for mesh point
  3607. * J Y index for mesh point
  3608. * X X for mesh point, overrides I
  3609. * Y Y for mesh point, overrides J
  3610. * Z Z for mesh point. Otherwise, raw current Z.
  3611. *
  3612. * Without PROBE_MANUALLY:
  3613. *
  3614. * E By default G29 will engage the Z probe, test the bed, then disengage.
  3615. * Include "E" to engage/disengage the Z probe for each sample.
  3616. * There's no extra effect if you have a fixed Z probe.
  3617. *
  3618. */
  3619. inline void gcode_G29() {
  3620. // G29 Q is also available if debugging
  3621. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3622. const bool query = parser.seen('Q');
  3623. const uint8_t old_debug_flags = marlin_debug_flags;
  3624. if (query) marlin_debug_flags |= DEBUG_LEVELING;
  3625. if (DEBUGGING(LEVELING)) {
  3626. DEBUG_POS(">>> gcode_G29", current_position);
  3627. log_machine_info();
  3628. }
  3629. marlin_debug_flags = old_debug_flags;
  3630. #if DISABLED(PROBE_MANUALLY)
  3631. if (query) return;
  3632. #endif
  3633. #endif
  3634. #if ENABLED(PROBE_MANUALLY)
  3635. const bool seenA = parser.seen('A'), seenQ = parser.seen('Q'), no_action = seenA || seenQ;
  3636. #endif
  3637. #if ENABLED(DEBUG_LEVELING_FEATURE) && DISABLED(PROBE_MANUALLY)
  3638. const bool faux = parser.boolval('C');
  3639. #elif ENABLED(PROBE_MANUALLY)
  3640. const bool faux = no_action;
  3641. #else
  3642. bool constexpr faux = false;
  3643. #endif
  3644. // Don't allow auto-leveling without homing first
  3645. if (axis_unhomed_error()) return;
  3646. // Define local vars 'static' for manual probing, 'auto' otherwise
  3647. #if ENABLED(PROBE_MANUALLY)
  3648. #define ABL_VAR static
  3649. #else
  3650. #define ABL_VAR
  3651. #endif
  3652. ABL_VAR int verbose_level;
  3653. ABL_VAR float xProbe, yProbe, measured_z;
  3654. ABL_VAR bool dryrun, abl_should_enable;
  3655. #if ENABLED(PROBE_MANUALLY) || ENABLED(AUTO_BED_LEVELING_LINEAR)
  3656. ABL_VAR int abl_probe_index;
  3657. #endif
  3658. #if HAS_SOFTWARE_ENDSTOPS && ENABLED(PROBE_MANUALLY)
  3659. ABL_VAR bool enable_soft_endstops = true;
  3660. #endif
  3661. #if ABL_GRID
  3662. #if ENABLED(PROBE_MANUALLY)
  3663. ABL_VAR uint8_t PR_OUTER_VAR;
  3664. ABL_VAR int8_t PR_INNER_VAR;
  3665. #endif
  3666. ABL_VAR int left_probe_bed_position, right_probe_bed_position, front_probe_bed_position, back_probe_bed_position;
  3667. ABL_VAR float xGridSpacing, yGridSpacing;
  3668. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  3669. ABL_VAR uint8_t abl_grid_points_x = GRID_MAX_POINTS_X,
  3670. abl_grid_points_y = GRID_MAX_POINTS_Y;
  3671. ABL_VAR bool do_topography_map;
  3672. #else // Bilinear
  3673. uint8_t constexpr abl_grid_points_x = GRID_MAX_POINTS_X,
  3674. abl_grid_points_y = GRID_MAX_POINTS_Y;
  3675. #endif
  3676. #if ENABLED(AUTO_BED_LEVELING_LINEAR) || ENABLED(PROBE_MANUALLY)
  3677. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  3678. ABL_VAR int abl2;
  3679. #else // Bilinear
  3680. int constexpr abl2 = GRID_MAX_POINTS;
  3681. #endif
  3682. #endif
  3683. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3684. ABL_VAR float zoffset;
  3685. #elif ENABLED(AUTO_BED_LEVELING_LINEAR)
  3686. ABL_VAR int indexIntoAB[GRID_MAX_POINTS_X][GRID_MAX_POINTS_Y];
  3687. ABL_VAR float eqnAMatrix[GRID_MAX_POINTS * 3], // "A" matrix of the linear system of equations
  3688. eqnBVector[GRID_MAX_POINTS], // "B" vector of Z points
  3689. mean;
  3690. #endif
  3691. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  3692. int constexpr abl2 = 3;
  3693. // Probe at 3 arbitrary points
  3694. ABL_VAR vector_3 points[3] = {
  3695. vector_3(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, 0),
  3696. vector_3(ABL_PROBE_PT_2_X, ABL_PROBE_PT_2_Y, 0),
  3697. vector_3(ABL_PROBE_PT_3_X, ABL_PROBE_PT_3_Y, 0)
  3698. };
  3699. #endif // AUTO_BED_LEVELING_3POINT
  3700. /**
  3701. * On the initial G29 fetch command parameters.
  3702. */
  3703. if (!g29_in_progress) {
  3704. #if ENABLED(PROBE_MANUALLY) || ENABLED(AUTO_BED_LEVELING_LINEAR)
  3705. abl_probe_index = -1;
  3706. #endif
  3707. abl_should_enable = leveling_is_active();
  3708. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3709. if (parser.seen('W')) {
  3710. if (!leveling_is_valid()) {
  3711. SERIAL_ERROR_START();
  3712. SERIAL_ERRORLNPGM("No bilinear grid");
  3713. return;
  3714. }
  3715. const float z = parser.floatval('Z', RAW_CURRENT_POSITION(Z));
  3716. if (!WITHIN(z, -10, 10)) {
  3717. SERIAL_ERROR_START();
  3718. SERIAL_ERRORLNPGM("Bad Z value");
  3719. return;
  3720. }
  3721. const float x = parser.floatval('X', NAN),
  3722. y = parser.floatval('Y', NAN);
  3723. int8_t i = parser.byteval('I', -1),
  3724. j = parser.byteval('J', -1);
  3725. if (!isnan(x) && !isnan(y)) {
  3726. // Get nearest i / j from x / y
  3727. i = (x - LOGICAL_X_POSITION(bilinear_start[X_AXIS]) + 0.5 * xGridSpacing) / xGridSpacing;
  3728. j = (y - LOGICAL_Y_POSITION(bilinear_start[Y_AXIS]) + 0.5 * yGridSpacing) / yGridSpacing;
  3729. i = constrain(i, 0, GRID_MAX_POINTS_X - 1);
  3730. j = constrain(j, 0, GRID_MAX_POINTS_Y - 1);
  3731. }
  3732. if (WITHIN(i, 0, GRID_MAX_POINTS_X - 1) && WITHIN(j, 0, GRID_MAX_POINTS_Y)) {
  3733. set_bed_leveling_enabled(false);
  3734. z_values[i][j] = z;
  3735. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  3736. bed_level_virt_interpolate();
  3737. #endif
  3738. set_bed_leveling_enabled(abl_should_enable);
  3739. }
  3740. return;
  3741. } // parser.seen('W')
  3742. #endif
  3743. #if HAS_LEVELING
  3744. // Jettison bed leveling data
  3745. if (parser.seen('J')) {
  3746. reset_bed_level();
  3747. return;
  3748. }
  3749. #endif
  3750. verbose_level = parser.intval('V');
  3751. if (!WITHIN(verbose_level, 0, 4)) {
  3752. SERIAL_PROTOCOLLNPGM("?(V)erbose level is implausible (0-4).");
  3753. return;
  3754. }
  3755. dryrun = parser.boolval('D')
  3756. #if ENABLED(PROBE_MANUALLY)
  3757. || no_action
  3758. #endif
  3759. ;
  3760. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  3761. do_topography_map = verbose_level > 2 || parser.boolval('T');
  3762. // X and Y specify points in each direction, overriding the default
  3763. // These values may be saved with the completed mesh
  3764. abl_grid_points_x = parser.intval('X', GRID_MAX_POINTS_X);
  3765. abl_grid_points_y = parser.intval('Y', GRID_MAX_POINTS_Y);
  3766. if (parser.seenval('P')) abl_grid_points_x = abl_grid_points_y = parser.value_int();
  3767. if (abl_grid_points_x < 2 || abl_grid_points_y < 2) {
  3768. SERIAL_PROTOCOLLNPGM("?Number of probe points is implausible (2 minimum).");
  3769. return;
  3770. }
  3771. abl2 = abl_grid_points_x * abl_grid_points_y;
  3772. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3773. zoffset = parser.linearval('Z');
  3774. #endif
  3775. #if ABL_GRID
  3776. xy_probe_feedrate_mm_s = MMM_TO_MMS(parser.linearval('S', XY_PROBE_SPEED));
  3777. left_probe_bed_position = (int)parser.linearval('L', LOGICAL_X_POSITION(LEFT_PROBE_BED_POSITION));
  3778. right_probe_bed_position = (int)parser.linearval('R', LOGICAL_X_POSITION(RIGHT_PROBE_BED_POSITION));
  3779. front_probe_bed_position = (int)parser.linearval('F', LOGICAL_Y_POSITION(FRONT_PROBE_BED_POSITION));
  3780. back_probe_bed_position = (int)parser.linearval('B', LOGICAL_Y_POSITION(BACK_PROBE_BED_POSITION));
  3781. const bool left_out_l = left_probe_bed_position < LOGICAL_X_POSITION(MIN_PROBE_X),
  3782. left_out = left_out_l || left_probe_bed_position > right_probe_bed_position - (MIN_PROBE_EDGE),
  3783. right_out_r = right_probe_bed_position > LOGICAL_X_POSITION(MAX_PROBE_X),
  3784. right_out = right_out_r || right_probe_bed_position < left_probe_bed_position + MIN_PROBE_EDGE,
  3785. front_out_f = front_probe_bed_position < LOGICAL_Y_POSITION(MIN_PROBE_Y),
  3786. front_out = front_out_f || front_probe_bed_position > back_probe_bed_position - (MIN_PROBE_EDGE),
  3787. back_out_b = back_probe_bed_position > LOGICAL_Y_POSITION(MAX_PROBE_Y),
  3788. back_out = back_out_b || back_probe_bed_position < front_probe_bed_position + MIN_PROBE_EDGE;
  3789. if (left_out || right_out || front_out || back_out) {
  3790. if (left_out) {
  3791. out_of_range_error(PSTR("(L)eft"));
  3792. left_probe_bed_position = left_out_l ? LOGICAL_X_POSITION(MIN_PROBE_X) : right_probe_bed_position - (MIN_PROBE_EDGE);
  3793. }
  3794. if (right_out) {
  3795. out_of_range_error(PSTR("(R)ight"));
  3796. right_probe_bed_position = right_out_r ? LOGICAL_Y_POSITION(MAX_PROBE_X) : left_probe_bed_position + MIN_PROBE_EDGE;
  3797. }
  3798. if (front_out) {
  3799. out_of_range_error(PSTR("(F)ront"));
  3800. front_probe_bed_position = front_out_f ? LOGICAL_Y_POSITION(MIN_PROBE_Y) : back_probe_bed_position - (MIN_PROBE_EDGE);
  3801. }
  3802. if (back_out) {
  3803. out_of_range_error(PSTR("(B)ack"));
  3804. back_probe_bed_position = back_out_b ? LOGICAL_Y_POSITION(MAX_PROBE_Y) : front_probe_bed_position + MIN_PROBE_EDGE;
  3805. }
  3806. return;
  3807. }
  3808. // probe at the points of a lattice grid
  3809. xGridSpacing = (right_probe_bed_position - left_probe_bed_position) / (abl_grid_points_x - 1);
  3810. yGridSpacing = (back_probe_bed_position - front_probe_bed_position) / (abl_grid_points_y - 1);
  3811. #endif // ABL_GRID
  3812. if (verbose_level > 0) {
  3813. SERIAL_PROTOCOLLNPGM("G29 Auto Bed Leveling");
  3814. if (dryrun) SERIAL_PROTOCOLLNPGM("Running in DRY-RUN mode");
  3815. }
  3816. stepper.synchronize();
  3817. // Disable auto bed leveling during G29
  3818. planner.abl_enabled = false;
  3819. if (!dryrun) {
  3820. // Re-orient the current position without leveling
  3821. // based on where the steppers are positioned.
  3822. set_current_from_steppers_for_axis(ALL_AXES);
  3823. // Sync the planner to where the steppers stopped
  3824. SYNC_PLAN_POSITION_KINEMATIC();
  3825. }
  3826. if (!faux) setup_for_endstop_or_probe_move();
  3827. //xProbe = yProbe = measured_z = 0;
  3828. #if HAS_BED_PROBE
  3829. // Deploy the probe. Probe will raise if needed.
  3830. if (DEPLOY_PROBE()) {
  3831. planner.abl_enabled = abl_should_enable;
  3832. return;
  3833. }
  3834. #endif
  3835. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3836. if ( xGridSpacing != bilinear_grid_spacing[X_AXIS]
  3837. || yGridSpacing != bilinear_grid_spacing[Y_AXIS]
  3838. || left_probe_bed_position != LOGICAL_X_POSITION(bilinear_start[X_AXIS])
  3839. || front_probe_bed_position != LOGICAL_Y_POSITION(bilinear_start[Y_AXIS])
  3840. ) {
  3841. if (dryrun) {
  3842. // Before reset bed level, re-enable to correct the position
  3843. planner.abl_enabled = abl_should_enable;
  3844. }
  3845. // Reset grid to 0.0 or "not probed". (Also disables ABL)
  3846. reset_bed_level();
  3847. // Initialize a grid with the given dimensions
  3848. bilinear_grid_spacing[X_AXIS] = xGridSpacing;
  3849. bilinear_grid_spacing[Y_AXIS] = yGridSpacing;
  3850. bilinear_start[X_AXIS] = RAW_X_POSITION(left_probe_bed_position);
  3851. bilinear_start[Y_AXIS] = RAW_Y_POSITION(front_probe_bed_position);
  3852. // Can't re-enable (on error) until the new grid is written
  3853. abl_should_enable = false;
  3854. }
  3855. #elif ENABLED(AUTO_BED_LEVELING_LINEAR)
  3856. mean = 0.0;
  3857. #endif // AUTO_BED_LEVELING_LINEAR
  3858. #if ENABLED(AUTO_BED_LEVELING_3POINT)
  3859. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3860. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("> 3-point Leveling");
  3861. #endif
  3862. // Probe at 3 arbitrary points
  3863. points[0].z = points[1].z = points[2].z = 0;
  3864. #endif // AUTO_BED_LEVELING_3POINT
  3865. } // !g29_in_progress
  3866. #if ENABLED(PROBE_MANUALLY)
  3867. // For manual probing, get the next index to probe now.
  3868. // On the first probe this will be incremented to 0.
  3869. if (!no_action) {
  3870. ++abl_probe_index;
  3871. g29_in_progress = true;
  3872. }
  3873. // Abort current G29 procedure, go back to idle state
  3874. if (seenA && g29_in_progress) {
  3875. SERIAL_PROTOCOLLNPGM("Manual G29 aborted");
  3876. #if HAS_SOFTWARE_ENDSTOPS
  3877. soft_endstops_enabled = enable_soft_endstops;
  3878. #endif
  3879. planner.abl_enabled = abl_should_enable;
  3880. g29_in_progress = false;
  3881. #if ENABLED(LCD_BED_LEVELING)
  3882. lcd_wait_for_move = false;
  3883. #endif
  3884. }
  3885. // Query G29 status
  3886. if (verbose_level || seenQ) {
  3887. SERIAL_PROTOCOLPGM("Manual G29 ");
  3888. if (g29_in_progress) {
  3889. SERIAL_PROTOCOLPAIR("point ", min(abl_probe_index + 1, abl2));
  3890. SERIAL_PROTOCOLLNPAIR(" of ", abl2);
  3891. }
  3892. else
  3893. SERIAL_PROTOCOLLNPGM("idle");
  3894. }
  3895. if (no_action) return;
  3896. if (abl_probe_index == 0) {
  3897. // For the initial G29 save software endstop state
  3898. #if HAS_SOFTWARE_ENDSTOPS
  3899. enable_soft_endstops = soft_endstops_enabled;
  3900. #endif
  3901. }
  3902. else {
  3903. // For G29 after adjusting Z.
  3904. // Save the previous Z before going to the next point
  3905. measured_z = current_position[Z_AXIS];
  3906. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  3907. mean += measured_z;
  3908. eqnBVector[abl_probe_index] = measured_z;
  3909. eqnAMatrix[abl_probe_index + 0 * abl2] = xProbe;
  3910. eqnAMatrix[abl_probe_index + 1 * abl2] = yProbe;
  3911. eqnAMatrix[abl_probe_index + 2 * abl2] = 1;
  3912. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3913. z_values[xCount][yCount] = measured_z + zoffset;
  3914. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3915. if (DEBUGGING(LEVELING)) {
  3916. SERIAL_PROTOCOLPAIR("Save X", xCount);
  3917. SERIAL_PROTOCOLPAIR(" Y", yCount);
  3918. SERIAL_PROTOCOLLNPAIR(" Z", measured_z + zoffset);
  3919. }
  3920. #endif
  3921. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  3922. points[abl_probe_index].z = measured_z;
  3923. #endif
  3924. }
  3925. //
  3926. // If there's another point to sample, move there with optional lift.
  3927. //
  3928. #if ABL_GRID
  3929. // Skip any unreachable points
  3930. while (abl_probe_index < abl2) {
  3931. // Set xCount, yCount based on abl_probe_index, with zig-zag
  3932. PR_OUTER_VAR = abl_probe_index / PR_INNER_END;
  3933. PR_INNER_VAR = abl_probe_index - (PR_OUTER_VAR * PR_INNER_END);
  3934. // Probe in reverse order for every other row/column
  3935. bool zig = (PR_OUTER_VAR & 1); // != ((PR_OUTER_END) & 1);
  3936. if (zig) PR_INNER_VAR = (PR_INNER_END - 1) - PR_INNER_VAR;
  3937. const float xBase = xCount * xGridSpacing + left_probe_bed_position,
  3938. yBase = yCount * yGridSpacing + front_probe_bed_position;
  3939. xProbe = FLOOR(xBase + (xBase < 0 ? 0 : 0.5));
  3940. yProbe = FLOOR(yBase + (yBase < 0 ? 0 : 0.5));
  3941. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  3942. indexIntoAB[xCount][yCount] = abl_probe_index;
  3943. #endif
  3944. // Keep looping till a reachable point is found
  3945. if (position_is_reachable_xy(xProbe, yProbe)) break;
  3946. ++abl_probe_index;
  3947. }
  3948. // Is there a next point to move to?
  3949. if (abl_probe_index < abl2) {
  3950. _manual_goto_xy(xProbe, yProbe); // Can be used here too!
  3951. #if HAS_SOFTWARE_ENDSTOPS
  3952. // Disable software endstops to allow manual adjustment
  3953. // If G29 is not completed, they will not be re-enabled
  3954. soft_endstops_enabled = false;
  3955. #endif
  3956. return;
  3957. }
  3958. else {
  3959. // Leveling done! Fall through to G29 finishing code below
  3960. SERIAL_PROTOCOLLNPGM("Grid probing done.");
  3961. // Re-enable software endstops, if needed
  3962. #if HAS_SOFTWARE_ENDSTOPS
  3963. soft_endstops_enabled = enable_soft_endstops;
  3964. #endif
  3965. }
  3966. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  3967. // Probe at 3 arbitrary points
  3968. if (abl_probe_index < 3) {
  3969. xProbe = LOGICAL_X_POSITION(points[abl_probe_index].x);
  3970. yProbe = LOGICAL_Y_POSITION(points[abl_probe_index].y);
  3971. #if HAS_SOFTWARE_ENDSTOPS
  3972. // Disable software endstops to allow manual adjustment
  3973. // If G29 is not completed, they will not be re-enabled
  3974. soft_endstops_enabled = false;
  3975. #endif
  3976. return;
  3977. }
  3978. else {
  3979. SERIAL_PROTOCOLLNPGM("3-point probing done.");
  3980. // Re-enable software endstops, if needed
  3981. #if HAS_SOFTWARE_ENDSTOPS
  3982. soft_endstops_enabled = enable_soft_endstops;
  3983. #endif
  3984. if (!dryrun) {
  3985. vector_3 planeNormal = vector_3::cross(points[0] - points[1], points[2] - points[1]).get_normal();
  3986. if (planeNormal.z < 0) {
  3987. planeNormal.x *= -1;
  3988. planeNormal.y *= -1;
  3989. planeNormal.z *= -1;
  3990. }
  3991. planner.bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  3992. // Can't re-enable (on error) until the new grid is written
  3993. abl_should_enable = false;
  3994. }
  3995. }
  3996. #endif // AUTO_BED_LEVELING_3POINT
  3997. #else // !PROBE_MANUALLY
  3998. const bool stow_probe_after_each = parser.boolval('E');
  3999. #if ABL_GRID
  4000. bool zig = PR_OUTER_END & 1; // Always end at RIGHT and BACK_PROBE_BED_POSITION
  4001. // Outer loop is Y with PROBE_Y_FIRST disabled
  4002. for (uint8_t PR_OUTER_VAR = 0; PR_OUTER_VAR < PR_OUTER_END; PR_OUTER_VAR++) {
  4003. int8_t inStart, inStop, inInc;
  4004. if (zig) { // away from origin
  4005. inStart = 0;
  4006. inStop = PR_INNER_END;
  4007. inInc = 1;
  4008. }
  4009. else { // towards origin
  4010. inStart = PR_INNER_END - 1;
  4011. inStop = -1;
  4012. inInc = -1;
  4013. }
  4014. zig ^= true; // zag
  4015. // Inner loop is Y with PROBE_Y_FIRST enabled
  4016. for (int8_t PR_INNER_VAR = inStart; PR_INNER_VAR != inStop; PR_INNER_VAR += inInc) {
  4017. float xBase = left_probe_bed_position + xGridSpacing * xCount,
  4018. yBase = front_probe_bed_position + yGridSpacing * yCount;
  4019. xProbe = FLOOR(xBase + (xBase < 0 ? 0 : 0.5));
  4020. yProbe = FLOOR(yBase + (yBase < 0 ? 0 : 0.5));
  4021. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  4022. indexIntoAB[xCount][yCount] = ++abl_probe_index; // 0...
  4023. #endif
  4024. #if IS_KINEMATIC
  4025. // Avoid probing outside the round or hexagonal area
  4026. if (!position_is_reachable_by_probe_xy(xProbe, yProbe)) continue;
  4027. #endif
  4028. measured_z = faux ? 0.001 * random(-100, 101) : probe_pt(xProbe, yProbe, stow_probe_after_each, verbose_level);
  4029. if (isnan(measured_z)) {
  4030. planner.abl_enabled = abl_should_enable;
  4031. return;
  4032. }
  4033. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  4034. mean += measured_z;
  4035. eqnBVector[abl_probe_index] = measured_z;
  4036. eqnAMatrix[abl_probe_index + 0 * abl2] = xProbe;
  4037. eqnAMatrix[abl_probe_index + 1 * abl2] = yProbe;
  4038. eqnAMatrix[abl_probe_index + 2 * abl2] = 1;
  4039. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  4040. z_values[xCount][yCount] = measured_z + zoffset;
  4041. #endif
  4042. abl_should_enable = false;
  4043. idle();
  4044. } // inner
  4045. } // outer
  4046. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  4047. // Probe at 3 arbitrary points
  4048. for (uint8_t i = 0; i < 3; ++i) {
  4049. // Retain the last probe position
  4050. xProbe = LOGICAL_X_POSITION(points[i].x);
  4051. yProbe = LOGICAL_Y_POSITION(points[i].y);
  4052. measured_z = faux ? 0.001 * random(-100, 101) : probe_pt(xProbe, yProbe, stow_probe_after_each, verbose_level);
  4053. if (isnan(measured_z)) {
  4054. planner.abl_enabled = abl_should_enable;
  4055. return;
  4056. }
  4057. points[i].z = measured_z;
  4058. }
  4059. if (!dryrun) {
  4060. vector_3 planeNormal = vector_3::cross(points[0] - points[1], points[2] - points[1]).get_normal();
  4061. if (planeNormal.z < 0) {
  4062. planeNormal.x *= -1;
  4063. planeNormal.y *= -1;
  4064. planeNormal.z *= -1;
  4065. }
  4066. planner.bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  4067. // Can't re-enable (on error) until the new grid is written
  4068. abl_should_enable = false;
  4069. }
  4070. #endif // AUTO_BED_LEVELING_3POINT
  4071. // Raise to _Z_CLEARANCE_DEPLOY_PROBE. Stow the probe.
  4072. if (STOW_PROBE()) {
  4073. planner.abl_enabled = abl_should_enable;
  4074. return;
  4075. }
  4076. #endif // !PROBE_MANUALLY
  4077. //
  4078. // G29 Finishing Code
  4079. //
  4080. // Unless this is a dry run, auto bed leveling will
  4081. // definitely be enabled after this point.
  4082. //
  4083. // If code above wants to continue leveling, it should
  4084. // return or loop before this point.
  4085. //
  4086. // Restore state after probing
  4087. if (!faux) clean_up_after_endstop_or_probe_move();
  4088. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4089. if (DEBUGGING(LEVELING)) DEBUG_POS("> probing complete", current_position);
  4090. #endif
  4091. #if ENABLED(PROBE_MANUALLY)
  4092. g29_in_progress = false;
  4093. #if ENABLED(LCD_BED_LEVELING)
  4094. lcd_wait_for_move = false;
  4095. #endif
  4096. #endif
  4097. // Calculate leveling, print reports, correct the position
  4098. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  4099. if (!dryrun) extrapolate_unprobed_bed_level();
  4100. print_bilinear_leveling_grid();
  4101. refresh_bed_level();
  4102. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  4103. bed_level_virt_print();
  4104. #endif
  4105. #elif ENABLED(AUTO_BED_LEVELING_LINEAR)
  4106. // For LINEAR leveling calculate matrix, print reports, correct the position
  4107. /**
  4108. * solve the plane equation ax + by + d = z
  4109. * A is the matrix with rows [x y 1] for all the probed points
  4110. * B is the vector of the Z positions
  4111. * the normal vector to the plane is formed by the coefficients of the
  4112. * plane equation in the standard form, which is Vx*x+Vy*y+Vz*z+d = 0
  4113. * so Vx = -a Vy = -b Vz = 1 (we want the vector facing towards positive Z
  4114. */
  4115. float plane_equation_coefficients[3];
  4116. qr_solve(plane_equation_coefficients, abl2, 3, eqnAMatrix, eqnBVector);
  4117. mean /= abl2;
  4118. if (verbose_level) {
  4119. SERIAL_PROTOCOLPGM("Eqn coefficients: a: ");
  4120. SERIAL_PROTOCOL_F(plane_equation_coefficients[0], 8);
  4121. SERIAL_PROTOCOLPGM(" b: ");
  4122. SERIAL_PROTOCOL_F(plane_equation_coefficients[1], 8);
  4123. SERIAL_PROTOCOLPGM(" d: ");
  4124. SERIAL_PROTOCOL_F(plane_equation_coefficients[2], 8);
  4125. SERIAL_EOL();
  4126. if (verbose_level > 2) {
  4127. SERIAL_PROTOCOLPGM("Mean of sampled points: ");
  4128. SERIAL_PROTOCOL_F(mean, 8);
  4129. SERIAL_EOL();
  4130. }
  4131. }
  4132. // Create the matrix but don't correct the position yet
  4133. if (!dryrun) {
  4134. planner.bed_level_matrix = matrix_3x3::create_look_at(
  4135. vector_3(-plane_equation_coefficients[0], -plane_equation_coefficients[1], 1)
  4136. );
  4137. }
  4138. // Show the Topography map if enabled
  4139. if (do_topography_map) {
  4140. SERIAL_PROTOCOLLNPGM("\nBed Height Topography:\n"
  4141. " +--- BACK --+\n"
  4142. " | |\n"
  4143. " L | (+) | R\n"
  4144. " E | | I\n"
  4145. " F | (-) N (+) | G\n"
  4146. " T | | H\n"
  4147. " | (-) | T\n"
  4148. " | |\n"
  4149. " O-- FRONT --+\n"
  4150. " (0,0)");
  4151. float min_diff = 999;
  4152. for (int8_t yy = abl_grid_points_y - 1; yy >= 0; yy--) {
  4153. for (uint8_t xx = 0; xx < abl_grid_points_x; xx++) {
  4154. int ind = indexIntoAB[xx][yy];
  4155. float diff = eqnBVector[ind] - mean,
  4156. x_tmp = eqnAMatrix[ind + 0 * abl2],
  4157. y_tmp = eqnAMatrix[ind + 1 * abl2],
  4158. z_tmp = 0;
  4159. apply_rotation_xyz(planner.bed_level_matrix, x_tmp, y_tmp, z_tmp);
  4160. NOMORE(min_diff, eqnBVector[ind] - z_tmp);
  4161. if (diff >= 0.0)
  4162. SERIAL_PROTOCOLPGM(" +"); // Include + for column alignment
  4163. else
  4164. SERIAL_PROTOCOLCHAR(' ');
  4165. SERIAL_PROTOCOL_F(diff, 5);
  4166. } // xx
  4167. SERIAL_EOL();
  4168. } // yy
  4169. SERIAL_EOL();
  4170. if (verbose_level > 3) {
  4171. SERIAL_PROTOCOLLNPGM("\nCorrected Bed Height vs. Bed Topology:");
  4172. for (int8_t yy = abl_grid_points_y - 1; yy >= 0; yy--) {
  4173. for (uint8_t xx = 0; xx < abl_grid_points_x; xx++) {
  4174. int ind = indexIntoAB[xx][yy];
  4175. float x_tmp = eqnAMatrix[ind + 0 * abl2],
  4176. y_tmp = eqnAMatrix[ind + 1 * abl2],
  4177. z_tmp = 0;
  4178. apply_rotation_xyz(planner.bed_level_matrix, x_tmp, y_tmp, z_tmp);
  4179. float diff = eqnBVector[ind] - z_tmp - min_diff;
  4180. if (diff >= 0.0)
  4181. SERIAL_PROTOCOLPGM(" +");
  4182. // Include + for column alignment
  4183. else
  4184. SERIAL_PROTOCOLCHAR(' ');
  4185. SERIAL_PROTOCOL_F(diff, 5);
  4186. } // xx
  4187. SERIAL_EOL();
  4188. } // yy
  4189. SERIAL_EOL();
  4190. }
  4191. } //do_topography_map
  4192. #endif // AUTO_BED_LEVELING_LINEAR
  4193. #if ABL_PLANAR
  4194. // For LINEAR and 3POINT leveling correct the current position
  4195. if (verbose_level > 0)
  4196. planner.bed_level_matrix.debug(PSTR("\n\nBed Level Correction Matrix:"));
  4197. if (!dryrun) {
  4198. //
  4199. // Correct the current XYZ position based on the tilted plane.
  4200. //
  4201. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4202. if (DEBUGGING(LEVELING)) DEBUG_POS("G29 uncorrected XYZ", current_position);
  4203. #endif
  4204. float converted[XYZ];
  4205. COPY(converted, current_position);
  4206. planner.abl_enabled = true;
  4207. planner.unapply_leveling(converted); // use conversion machinery
  4208. planner.abl_enabled = false;
  4209. // Use the last measured distance to the bed, if possible
  4210. if ( NEAR(current_position[X_AXIS], xProbe - (X_PROBE_OFFSET_FROM_EXTRUDER))
  4211. && NEAR(current_position[Y_AXIS], yProbe - (Y_PROBE_OFFSET_FROM_EXTRUDER))
  4212. ) {
  4213. const float simple_z = current_position[Z_AXIS] - measured_z;
  4214. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4215. if (DEBUGGING(LEVELING)) {
  4216. SERIAL_ECHOPAIR("Z from Probe:", simple_z);
  4217. SERIAL_ECHOPAIR(" Matrix:", converted[Z_AXIS]);
  4218. SERIAL_ECHOLNPAIR(" Discrepancy:", simple_z - converted[Z_AXIS]);
  4219. }
  4220. #endif
  4221. converted[Z_AXIS] = simple_z;
  4222. }
  4223. // The rotated XY and corrected Z are now current_position
  4224. COPY(current_position, converted);
  4225. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4226. if (DEBUGGING(LEVELING)) DEBUG_POS("G29 corrected XYZ", current_position);
  4227. #endif
  4228. }
  4229. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  4230. if (!dryrun) {
  4231. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4232. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR("G29 uncorrected Z:", current_position[Z_AXIS]);
  4233. #endif
  4234. // Unapply the offset because it is going to be immediately applied
  4235. // and cause compensation movement in Z
  4236. current_position[Z_AXIS] -= bilinear_z_offset(current_position);
  4237. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4238. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR(" corrected Z:", current_position[Z_AXIS]);
  4239. #endif
  4240. }
  4241. #endif // ABL_PLANAR
  4242. #ifdef Z_PROBE_END_SCRIPT
  4243. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4244. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR("Z Probe End Script: ", Z_PROBE_END_SCRIPT);
  4245. #endif
  4246. enqueue_and_echo_commands_P(PSTR(Z_PROBE_END_SCRIPT));
  4247. stepper.synchronize();
  4248. #endif
  4249. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4250. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< gcode_G29");
  4251. #endif
  4252. report_current_position();
  4253. KEEPALIVE_STATE(IN_HANDLER);
  4254. // Auto Bed Leveling is complete! Enable if possible.
  4255. planner.abl_enabled = dryrun ? abl_should_enable : true;
  4256. if (planner.abl_enabled)
  4257. SYNC_PLAN_POSITION_KINEMATIC();
  4258. }
  4259. #endif // HAS_ABL && !AUTO_BED_LEVELING_UBL
  4260. #if HAS_BED_PROBE
  4261. /**
  4262. * G30: Do a single Z probe at the current XY
  4263. *
  4264. * Parameters:
  4265. *
  4266. * X Probe X position (default current X)
  4267. * Y Probe Y position (default current Y)
  4268. * S0 Leave the probe deployed
  4269. */
  4270. inline void gcode_G30() {
  4271. const float xpos = parser.linearval('X', current_position[X_AXIS] + X_PROBE_OFFSET_FROM_EXTRUDER),
  4272. ypos = parser.linearval('Y', current_position[Y_AXIS] + Y_PROBE_OFFSET_FROM_EXTRUDER);
  4273. if (!position_is_reachable_by_probe_xy(xpos, ypos)) return;
  4274. // Disable leveling so the planner won't mess with us
  4275. #if HAS_LEVELING
  4276. set_bed_leveling_enabled(false);
  4277. #endif
  4278. setup_for_endstop_or_probe_move();
  4279. const float measured_z = probe_pt(xpos, ypos, parser.boolval('S', true), 1);
  4280. if (!isnan(measured_z)) {
  4281. SERIAL_PROTOCOLPAIR("Bed X: ", FIXFLOAT(xpos));
  4282. SERIAL_PROTOCOLPAIR(" Y: ", FIXFLOAT(ypos));
  4283. SERIAL_PROTOCOLLNPAIR(" Z: ", FIXFLOAT(measured_z));
  4284. }
  4285. clean_up_after_endstop_or_probe_move();
  4286. report_current_position();
  4287. }
  4288. #if ENABLED(Z_PROBE_SLED)
  4289. /**
  4290. * G31: Deploy the Z probe
  4291. */
  4292. inline void gcode_G31() { DEPLOY_PROBE(); }
  4293. /**
  4294. * G32: Stow the Z probe
  4295. */
  4296. inline void gcode_G32() { STOW_PROBE(); }
  4297. #endif // Z_PROBE_SLED
  4298. #endif // HAS_BED_PROBE
  4299. #if PROBE_SELECTED
  4300. #if ENABLED(DELTA_AUTO_CALIBRATION)
  4301. /**
  4302. * G33 - Delta '1-4-7-point' Auto-Calibration
  4303. * Calibrate height, endstops, delta radius, and tower angles.
  4304. *
  4305. * Parameters:
  4306. *
  4307. * Pn Number of probe points:
  4308. *
  4309. * P1 Probe center and set height only.
  4310. * P2 Probe center and towers. Set height, endstops, and delta radius.
  4311. * P3 Probe all positions: center, towers and opposite towers. Set all.
  4312. * P4-P7 Probe all positions at different locations and average them.
  4313. *
  4314. * T0 Don't calibrate tower angle corrections
  4315. *
  4316. * Cn.nn Calibration precision; when omitted calibrates to maximum precision
  4317. *
  4318. * Fn Force to run at least n iterations and takes the best result
  4319. *
  4320. * Vn Verbose level:
  4321. *
  4322. * V0 Dry-run mode. Report settings and probe results. No calibration.
  4323. * V1 Report settings
  4324. * V2 Report settings and probe results
  4325. *
  4326. * E Engage the probe for each point
  4327. */
  4328. void print_signed_float(const char * const prefix, const float &f) {
  4329. SERIAL_PROTOCOLPGM(" ");
  4330. serialprintPGM(prefix);
  4331. SERIAL_PROTOCOLCHAR(':');
  4332. if (f >= 0) SERIAL_CHAR('+');
  4333. SERIAL_PROTOCOL_F(f, 2);
  4334. }
  4335. inline void gcode_G33() {
  4336. const int8_t probe_points = parser.intval('P', DELTA_CALIBRATION_DEFAULT_POINTS);
  4337. if (!WITHIN(probe_points, 1, 7)) {
  4338. SERIAL_PROTOCOLLNPGM("?(P)oints is implausible (1 to 7).");
  4339. return;
  4340. }
  4341. const int8_t verbose_level = parser.byteval('V', 1);
  4342. if (!WITHIN(verbose_level, 0, 2)) {
  4343. SERIAL_PROTOCOLLNPGM("?(V)erbose level is implausible (0-2).");
  4344. return;
  4345. }
  4346. const float calibration_precision = parser.floatval('C');
  4347. if (calibration_precision < 0) {
  4348. SERIAL_PROTOCOLLNPGM("?(C)alibration precision is implausible (>0).");
  4349. return;
  4350. }
  4351. const int8_t force_iterations = parser.intval('F', 0);
  4352. if (!WITHIN(force_iterations, 0, 30)) {
  4353. SERIAL_PROTOCOLLNPGM("?(F)orce iteration is implausible (0-30).");
  4354. return;
  4355. }
  4356. const bool towers_set = parser.boolval('T', true),
  4357. stow_after_each = parser.boolval('E'),
  4358. _1p_calibration = probe_points == 1,
  4359. _4p_calibration = probe_points == 2,
  4360. _4p_towers_points = _4p_calibration && towers_set,
  4361. _4p_opposite_points = _4p_calibration && !towers_set,
  4362. _7p_calibration = probe_points >= 3,
  4363. _7p_half_circle = probe_points == 3,
  4364. _7p_double_circle = probe_points == 5,
  4365. _7p_triple_circle = probe_points == 6,
  4366. _7p_quadruple_circle = probe_points == 7,
  4367. _7p_multi_circle = _7p_double_circle || _7p_triple_circle || _7p_quadruple_circle,
  4368. _7p_intermed_points = _7p_calibration && !_7p_half_circle;
  4369. const static char save_message[] PROGMEM = "Save with M500 and/or copy to Configuration.h";
  4370. const float dx = (X_PROBE_OFFSET_FROM_EXTRUDER),
  4371. dy = (Y_PROBE_OFFSET_FROM_EXTRUDER);
  4372. int8_t iterations = 0;
  4373. float test_precision,
  4374. zero_std_dev = (verbose_level ? 999.0 : 0.0), // 0.0 in dry-run mode : forced end
  4375. zero_std_dev_old = zero_std_dev,
  4376. zero_std_dev_min = zero_std_dev,
  4377. e_old[XYZ] = {
  4378. endstop_adj[A_AXIS],
  4379. endstop_adj[B_AXIS],
  4380. endstop_adj[C_AXIS]
  4381. },
  4382. dr_old = delta_radius,
  4383. zh_old = home_offset[Z_AXIS],
  4384. alpha_old = delta_tower_angle_trim[A_AXIS],
  4385. beta_old = delta_tower_angle_trim[B_AXIS];
  4386. if (!_1p_calibration) { // test if the outer radius is reachable
  4387. const float circles = (_7p_quadruple_circle ? 1.5 :
  4388. _7p_triple_circle ? 1.0 :
  4389. _7p_double_circle ? 0.5 : 0),
  4390. r = (1 + circles * 0.1) * delta_calibration_radius;
  4391. for (uint8_t axis = 1; axis < 13; ++axis) {
  4392. const float a = RADIANS(180 + 30 * axis);
  4393. if (!position_is_reachable_xy(cos(a) * r, sin(a) * r)) {
  4394. SERIAL_PROTOCOLLNPGM("?(M665 B)ed radius is implausible.");
  4395. return;
  4396. }
  4397. }
  4398. }
  4399. SERIAL_PROTOCOLLNPGM("G33 Auto Calibrate");
  4400. stepper.synchronize();
  4401. #if HAS_LEVELING
  4402. reset_bed_level(); // After calibration bed-level data is no longer valid
  4403. #endif
  4404. #if HOTENDS > 1
  4405. const uint8_t old_tool_index = active_extruder;
  4406. tool_change(0, 0, true);
  4407. #endif
  4408. setup_for_endstop_or_probe_move();
  4409. DEPLOY_PROBE();
  4410. endstops.enable(true);
  4411. home_delta();
  4412. endstops.not_homing();
  4413. // print settings
  4414. SERIAL_PROTOCOLPGM("Checking... AC");
  4415. if (verbose_level == 0) SERIAL_PROTOCOLPGM(" (DRY-RUN)");
  4416. SERIAL_EOL();
  4417. LCD_MESSAGEPGM("Checking... AC"); // TODO: Make translatable string
  4418. SERIAL_PROTOCOLPAIR(".Height:", DELTA_HEIGHT + home_offset[Z_AXIS]);
  4419. if (!_1p_calibration) {
  4420. print_signed_float(PSTR(" Ex"), endstop_adj[A_AXIS]);
  4421. print_signed_float(PSTR("Ey"), endstop_adj[B_AXIS]);
  4422. print_signed_float(PSTR("Ez"), endstop_adj[C_AXIS]);
  4423. SERIAL_PROTOCOLPAIR(" Radius:", delta_radius);
  4424. }
  4425. SERIAL_EOL();
  4426. if (_7p_calibration && towers_set) {
  4427. SERIAL_PROTOCOLPGM(".Tower angle : ");
  4428. print_signed_float(PSTR("Tx"), delta_tower_angle_trim[A_AXIS]);
  4429. print_signed_float(PSTR("Ty"), delta_tower_angle_trim[B_AXIS]);
  4430. SERIAL_PROTOCOLPGM(" Tz:+0.00");
  4431. SERIAL_EOL();
  4432. }
  4433. #if DISABLED(PROBE_MANUALLY)
  4434. home_offset[Z_AXIS] -= probe_pt(dx, dy, stow_after_each, 1, false); // 1st probe to set height
  4435. #endif
  4436. do {
  4437. float z_at_pt[13] = { 0.0 };
  4438. test_precision = zero_std_dev_old != 999.0 ? (zero_std_dev + zero_std_dev_old) / 2 : zero_std_dev;
  4439. iterations++;
  4440. // Probe the points
  4441. if (!_7p_half_circle && !_7p_triple_circle) { // probe the center
  4442. #if ENABLED(PROBE_MANUALLY)
  4443. z_at_pt[0] += lcd_probe_pt(0, 0);
  4444. #else
  4445. z_at_pt[0] += probe_pt(dx, dy, stow_after_each, 1, false);
  4446. #endif
  4447. }
  4448. if (_7p_calibration) { // probe extra center points
  4449. for (int8_t axis = _7p_multi_circle ? 11 : 9; axis > 0; axis -= _7p_multi_circle ? 2 : 4) {
  4450. const float a = RADIANS(180 + 30 * axis), r = delta_calibration_radius * 0.1;
  4451. #if ENABLED(PROBE_MANUALLY)
  4452. z_at_pt[0] += lcd_probe_pt(cos(a) * r, sin(a) * r);
  4453. #else
  4454. z_at_pt[0] += probe_pt(cos(a) * r + dx, sin(a) * r + dy, stow_after_each, 1, false);
  4455. #endif
  4456. }
  4457. z_at_pt[0] /= float(_7p_double_circle ? 7 : probe_points);
  4458. }
  4459. if (!_1p_calibration) { // probe the radius
  4460. bool zig_zag = true;
  4461. const uint8_t start = _4p_opposite_points ? 3 : 1,
  4462. step = _4p_calibration ? 4 : _7p_half_circle ? 2 : 1;
  4463. for (uint8_t axis = start; axis < 13; axis += step) {
  4464. const float zigadd = (zig_zag ? 0.5 : 0.0),
  4465. offset_circles = _7p_quadruple_circle ? zigadd + 1.0 :
  4466. _7p_triple_circle ? zigadd + 0.5 :
  4467. _7p_double_circle ? zigadd : 0;
  4468. for (float circles = -offset_circles ; circles <= offset_circles; circles++) {
  4469. const float a = RADIANS(180 + 30 * axis),
  4470. r = delta_calibration_radius * (1 + circles * (zig_zag ? 0.1 : -0.1));
  4471. #if ENABLED(PROBE_MANUALLY)
  4472. z_at_pt[axis] += lcd_probe_pt(cos(a) * r, sin(a) * r);
  4473. #else
  4474. z_at_pt[axis] += probe_pt(cos(a) * r + dx, sin(a) * r + dy, stow_after_each, 1, false);
  4475. #endif
  4476. }
  4477. zig_zag = !zig_zag;
  4478. z_at_pt[axis] /= (2 * offset_circles + 1);
  4479. }
  4480. }
  4481. if (_7p_intermed_points) // average intermediates to tower and opposites
  4482. for (uint8_t axis = 1; axis < 13; axis += 2)
  4483. z_at_pt[axis] = (z_at_pt[axis] + (z_at_pt[axis + 1] + z_at_pt[(axis + 10) % 12 + 1]) / 2.0) / 2.0;
  4484. float S1 = z_at_pt[0],
  4485. S2 = sq(z_at_pt[0]);
  4486. int16_t N = 1;
  4487. if (!_1p_calibration) // std dev from zero plane
  4488. for (uint8_t axis = (_4p_opposite_points ? 3 : 1); axis < 13; axis += (_4p_calibration ? 4 : 2)) {
  4489. S1 += z_at_pt[axis];
  4490. S2 += sq(z_at_pt[axis]);
  4491. N++;
  4492. }
  4493. zero_std_dev_old = zero_std_dev;
  4494. NOMORE(zero_std_dev_min, zero_std_dev);
  4495. zero_std_dev = round(sqrt(S2 / N) * 1000.0) / 1000.0 + 0.00001;
  4496. // Solve matrices
  4497. if ((zero_std_dev < test_precision && zero_std_dev > calibration_precision) || iterations <= force_iterations) {
  4498. if (zero_std_dev < zero_std_dev_min) {
  4499. COPY(e_old, endstop_adj);
  4500. dr_old = delta_radius;
  4501. zh_old = home_offset[Z_AXIS];
  4502. alpha_old = delta_tower_angle_trim[A_AXIS];
  4503. beta_old = delta_tower_angle_trim[B_AXIS];
  4504. }
  4505. float e_delta[XYZ] = { 0.0 }, r_delta = 0.0, t_alpha = 0.0, t_beta = 0.0;
  4506. const float r_diff = delta_radius - delta_calibration_radius,
  4507. h_factor = 1.00 + r_diff * 0.001, //1.02 for r_diff = 20mm
  4508. r_factor = -(1.75 + 0.005 * r_diff + 0.001 * sq(r_diff)), //2.25 for r_diff = 20mm
  4509. a_factor = 100.0 / delta_calibration_radius; //1.25 for cal_rd = 80mm
  4510. #define ZP(N,I) ((N) * z_at_pt[I])
  4511. #define Z1000(I) ZP(1.00, I)
  4512. #define Z1050(I) ZP(h_factor, I)
  4513. #define Z0700(I) ZP(h_factor * 2.0 / 3.00, I)
  4514. #define Z0350(I) ZP(h_factor / 3.00, I)
  4515. #define Z0175(I) ZP(h_factor / 6.00, I)
  4516. #define Z2250(I) ZP(r_factor, I)
  4517. #define Z0750(I) ZP(r_factor / 3.00, I)
  4518. #define Z0375(I) ZP(r_factor / 6.00, I)
  4519. #define Z0444(I) ZP(a_factor * 4.0 / 9.0, I)
  4520. #define Z0888(I) ZP(a_factor * 8.0 / 9.0, I)
  4521. #if ENABLED(PROBE_MANUALLY)
  4522. test_precision = 0.00; // forced end
  4523. #endif
  4524. switch (probe_points) {
  4525. case 1:
  4526. test_precision = 0.00; // forced end
  4527. LOOP_XYZ(i) e_delta[i] = Z1000(0);
  4528. break;
  4529. case 2:
  4530. if (towers_set) {
  4531. e_delta[X_AXIS] = Z1050(0) + Z0700(1) - Z0350(5) - Z0350(9);
  4532. e_delta[Y_AXIS] = Z1050(0) - Z0350(1) + Z0700(5) - Z0350(9);
  4533. e_delta[Z_AXIS] = Z1050(0) - Z0350(1) - Z0350(5) + Z0700(9);
  4534. r_delta = Z2250(0) - Z0750(1) - Z0750(5) - Z0750(9);
  4535. }
  4536. else {
  4537. e_delta[X_AXIS] = Z1050(0) - Z0700(7) + Z0350(11) + Z0350(3);
  4538. e_delta[Y_AXIS] = Z1050(0) + Z0350(7) - Z0700(11) + Z0350(3);
  4539. e_delta[Z_AXIS] = Z1050(0) + Z0350(7) + Z0350(11) - Z0700(3);
  4540. r_delta = Z2250(0) - Z0750(7) - Z0750(11) - Z0750(3);
  4541. }
  4542. break;
  4543. default:
  4544. e_delta[X_AXIS] = Z1050(0) + Z0350(1) - Z0175(5) - Z0175(9) - Z0350(7) + Z0175(11) + Z0175(3);
  4545. e_delta[Y_AXIS] = Z1050(0) - Z0175(1) + Z0350(5) - Z0175(9) + Z0175(7) - Z0350(11) + Z0175(3);
  4546. e_delta[Z_AXIS] = Z1050(0) - Z0175(1) - Z0175(5) + Z0350(9) + Z0175(7) + Z0175(11) - Z0350(3);
  4547. r_delta = Z2250(0) - Z0375(1) - Z0375(5) - Z0375(9) - Z0375(7) - Z0375(11) - Z0375(3);
  4548. if (towers_set) {
  4549. t_alpha = Z0444(1) - Z0888(5) + Z0444(9) + Z0444(7) - Z0888(11) + Z0444(3);
  4550. t_beta = Z0888(1) - Z0444(5) - Z0444(9) + Z0888(7) - Z0444(11) - Z0444(3);
  4551. }
  4552. break;
  4553. }
  4554. LOOP_XYZ(axis) endstop_adj[axis] += e_delta[axis];
  4555. delta_radius += r_delta;
  4556. delta_tower_angle_trim[A_AXIS] += t_alpha;
  4557. delta_tower_angle_trim[B_AXIS] += t_beta;
  4558. // adjust delta_height and endstops by the max amount
  4559. const float z_temp = MAX3(endstop_adj[A_AXIS], endstop_adj[B_AXIS], endstop_adj[C_AXIS]);
  4560. home_offset[Z_AXIS] -= z_temp;
  4561. LOOP_XYZ(i) endstop_adj[i] -= z_temp;
  4562. recalc_delta_settings(delta_radius, delta_diagonal_rod);
  4563. }
  4564. else if (zero_std_dev >= test_precision) { // step one back
  4565. COPY(endstop_adj, e_old);
  4566. delta_radius = dr_old;
  4567. home_offset[Z_AXIS] = zh_old;
  4568. delta_tower_angle_trim[A_AXIS] = alpha_old;
  4569. delta_tower_angle_trim[B_AXIS] = beta_old;
  4570. recalc_delta_settings(delta_radius, delta_diagonal_rod);
  4571. }
  4572. // print report
  4573. if (verbose_level != 1) {
  4574. SERIAL_PROTOCOLPGM(". ");
  4575. print_signed_float(PSTR("c"), z_at_pt[0]);
  4576. if (_4p_towers_points || _7p_calibration) {
  4577. print_signed_float(PSTR(" x"), z_at_pt[1]);
  4578. print_signed_float(PSTR(" y"), z_at_pt[5]);
  4579. print_signed_float(PSTR(" z"), z_at_pt[9]);
  4580. }
  4581. if (!_4p_opposite_points) SERIAL_EOL();
  4582. if ((_4p_opposite_points) || _7p_calibration) {
  4583. if (_7p_calibration) {
  4584. SERIAL_CHAR('.');
  4585. SERIAL_PROTOCOL_SP(13);
  4586. }
  4587. print_signed_float(PSTR(" yz"), z_at_pt[7]);
  4588. print_signed_float(PSTR("zx"), z_at_pt[11]);
  4589. print_signed_float(PSTR("xy"), z_at_pt[3]);
  4590. SERIAL_EOL();
  4591. }
  4592. }
  4593. if (verbose_level != 0) { // !dry run
  4594. if ((zero_std_dev >= test_precision || zero_std_dev <= calibration_precision) && iterations > force_iterations) { // end iterations
  4595. SERIAL_PROTOCOLPGM("Calibration OK");
  4596. SERIAL_PROTOCOL_SP(36);
  4597. #if DISABLED(PROBE_MANUALLY)
  4598. if (zero_std_dev >= test_precision && !_1p_calibration)
  4599. SERIAL_PROTOCOLPGM("rolling back.");
  4600. else
  4601. #endif
  4602. {
  4603. SERIAL_PROTOCOLPGM("std dev:");
  4604. SERIAL_PROTOCOL_F(zero_std_dev, 3);
  4605. }
  4606. SERIAL_EOL();
  4607. LCD_MESSAGEPGM("Calibration OK"); // TODO: Make translatable string
  4608. }
  4609. else { // !end iterations
  4610. char mess[15] = "No convergence";
  4611. if (iterations < 31)
  4612. sprintf_P(mess, PSTR("Iteration : %02i"), (int)iterations);
  4613. SERIAL_PROTOCOL(mess);
  4614. SERIAL_PROTOCOL_SP(36);
  4615. SERIAL_PROTOCOLPGM("std dev:");
  4616. SERIAL_PROTOCOL_F(zero_std_dev, 3);
  4617. SERIAL_EOL();
  4618. lcd_setstatus(mess);
  4619. }
  4620. SERIAL_PROTOCOLPAIR(".Height:", DELTA_HEIGHT + home_offset[Z_AXIS]);
  4621. if (!_1p_calibration) {
  4622. print_signed_float(PSTR(" Ex"), endstop_adj[A_AXIS]);
  4623. print_signed_float(PSTR("Ey"), endstop_adj[B_AXIS]);
  4624. print_signed_float(PSTR("Ez"), endstop_adj[C_AXIS]);
  4625. SERIAL_PROTOCOLPAIR(" Radius:", delta_radius);
  4626. }
  4627. SERIAL_EOL();
  4628. if (_7p_calibration && towers_set) {
  4629. SERIAL_PROTOCOLPGM(".Tower angle : ");
  4630. print_signed_float(PSTR("Tx"), delta_tower_angle_trim[A_AXIS]);
  4631. print_signed_float(PSTR("Ty"), delta_tower_angle_trim[B_AXIS]);
  4632. SERIAL_PROTOCOLPGM(" Tz:+0.00");
  4633. SERIAL_EOL();
  4634. }
  4635. if ((zero_std_dev >= test_precision || zero_std_dev <= calibration_precision) && iterations > force_iterations)
  4636. serialprintPGM(save_message);
  4637. SERIAL_EOL();
  4638. }
  4639. else { // dry run
  4640. SERIAL_PROTOCOLPGM("End DRY-RUN");
  4641. SERIAL_PROTOCOL_SP(39);
  4642. SERIAL_PROTOCOLPGM("std dev:");
  4643. SERIAL_PROTOCOL_F(zero_std_dev, 3);
  4644. SERIAL_EOL();
  4645. }
  4646. endstops.enable(true);
  4647. home_delta();
  4648. endstops.not_homing();
  4649. }
  4650. while ((zero_std_dev < test_precision && zero_std_dev > calibration_precision && iterations < 31) || iterations <= force_iterations);
  4651. #if ENABLED(DELTA_HOME_TO_SAFE_ZONE)
  4652. do_blocking_move_to_z(delta_clip_start_height);
  4653. #endif
  4654. STOW_PROBE();
  4655. clean_up_after_endstop_or_probe_move();
  4656. #if HOTENDS > 1
  4657. tool_change(old_tool_index, 0, true);
  4658. #endif
  4659. }
  4660. #endif // DELTA_AUTO_CALIBRATION
  4661. #endif // PROBE_SELECTED
  4662. #if ENABLED(G38_PROBE_TARGET)
  4663. static bool G38_run_probe() {
  4664. bool G38_pass_fail = false;
  4665. // Get direction of move and retract
  4666. float retract_mm[XYZ];
  4667. LOOP_XYZ(i) {
  4668. float dist = destination[i] - current_position[i];
  4669. retract_mm[i] = FABS(dist) < G38_MINIMUM_MOVE ? 0 : home_bump_mm((AxisEnum)i) * (dist > 0 ? -1 : 1);
  4670. }
  4671. stepper.synchronize(); // wait until the machine is idle
  4672. // Move until destination reached or target hit
  4673. endstops.enable(true);
  4674. G38_move = true;
  4675. G38_endstop_hit = false;
  4676. prepare_move_to_destination();
  4677. stepper.synchronize();
  4678. G38_move = false;
  4679. endstops.hit_on_purpose();
  4680. set_current_from_steppers_for_axis(ALL_AXES);
  4681. SYNC_PLAN_POSITION_KINEMATIC();
  4682. if (G38_endstop_hit) {
  4683. G38_pass_fail = true;
  4684. #if ENABLED(PROBE_DOUBLE_TOUCH)
  4685. // Move away by the retract distance
  4686. set_destination_to_current();
  4687. LOOP_XYZ(i) destination[i] += retract_mm[i];
  4688. endstops.enable(false);
  4689. prepare_move_to_destination();
  4690. stepper.synchronize();
  4691. feedrate_mm_s /= 4;
  4692. // Bump the target more slowly
  4693. LOOP_XYZ(i) destination[i] -= retract_mm[i] * 2;
  4694. endstops.enable(true);
  4695. G38_move = true;
  4696. prepare_move_to_destination();
  4697. stepper.synchronize();
  4698. G38_move = false;
  4699. set_current_from_steppers_for_axis(ALL_AXES);
  4700. SYNC_PLAN_POSITION_KINEMATIC();
  4701. #endif
  4702. }
  4703. endstops.hit_on_purpose();
  4704. endstops.not_homing();
  4705. return G38_pass_fail;
  4706. }
  4707. /**
  4708. * G38.2 - probe toward workpiece, stop on contact, signal error if failure
  4709. * G38.3 - probe toward workpiece, stop on contact
  4710. *
  4711. * Like G28 except uses Z min probe for all axes
  4712. */
  4713. inline void gcode_G38(bool is_38_2) {
  4714. // Get X Y Z E F
  4715. gcode_get_destination();
  4716. setup_for_endstop_or_probe_move();
  4717. // If any axis has enough movement, do the move
  4718. LOOP_XYZ(i)
  4719. if (FABS(destination[i] - current_position[i]) >= G38_MINIMUM_MOVE) {
  4720. if (!parser.seenval('F')) feedrate_mm_s = homing_feedrate(i);
  4721. // If G38.2 fails throw an error
  4722. if (!G38_run_probe() && is_38_2) {
  4723. SERIAL_ERROR_START();
  4724. SERIAL_ERRORLNPGM("Failed to reach target");
  4725. }
  4726. break;
  4727. }
  4728. clean_up_after_endstop_or_probe_move();
  4729. }
  4730. #endif // G38_PROBE_TARGET
  4731. #if ENABLED(AUTO_BED_LEVELING_BILINEAR) || ENABLED(AUTO_BED_LEVELING_UBL) || ENABLED(MESH_BED_LEVELING)
  4732. /**
  4733. * G42: Move X & Y axes to mesh coordinates (I & J)
  4734. */
  4735. inline void gcode_G42() {
  4736. if (IsRunning()) {
  4737. const bool hasI = parser.seenval('I');
  4738. const int8_t ix = hasI ? parser.value_int() : 0;
  4739. const bool hasJ = parser.seenval('J');
  4740. const int8_t iy = hasJ ? parser.value_int() : 0;
  4741. if ((hasI && !WITHIN(ix, 0, GRID_MAX_POINTS_X - 1)) || (hasJ && !WITHIN(iy, 0, GRID_MAX_POINTS_Y - 1))) {
  4742. SERIAL_ECHOLNPGM(MSG_ERR_MESH_XY);
  4743. return;
  4744. }
  4745. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  4746. #define _GET_MESH_X(I) bilinear_start[X_AXIS] + I * bilinear_grid_spacing[X_AXIS]
  4747. #define _GET_MESH_Y(J) bilinear_start[Y_AXIS] + J * bilinear_grid_spacing[Y_AXIS]
  4748. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  4749. #define _GET_MESH_X(I) ubl.mesh_index_to_xpos(I)
  4750. #define _GET_MESH_Y(J) ubl.mesh_index_to_ypos(J)
  4751. #elif ENABLED(MESH_BED_LEVELING)
  4752. #define _GET_MESH_X(I) mbl.index_to_xpos[I]
  4753. #define _GET_MESH_Y(J) mbl.index_to_ypos[J]
  4754. #endif
  4755. set_destination_to_current();
  4756. if (hasI) destination[X_AXIS] = LOGICAL_X_POSITION(_GET_MESH_X(ix));
  4757. if (hasJ) destination[Y_AXIS] = LOGICAL_Y_POSITION(_GET_MESH_Y(iy));
  4758. if (parser.boolval('P')) {
  4759. if (hasI) destination[X_AXIS] -= X_PROBE_OFFSET_FROM_EXTRUDER;
  4760. if (hasJ) destination[Y_AXIS] -= Y_PROBE_OFFSET_FROM_EXTRUDER;
  4761. }
  4762. const float fval = parser.linearval('F');
  4763. if (fval > 0.0) feedrate_mm_s = MMM_TO_MMS(fval);
  4764. // SCARA kinematic has "safe" XY raw moves
  4765. #if IS_SCARA
  4766. prepare_uninterpolated_move_to_destination();
  4767. #else
  4768. prepare_move_to_destination();
  4769. #endif
  4770. }
  4771. }
  4772. #endif // AUTO_BED_LEVELING_UBL
  4773. /**
  4774. * G92: Set current position to given X Y Z E
  4775. */
  4776. inline void gcode_G92() {
  4777. bool didXYZ = false,
  4778. didE = parser.seenval('E');
  4779. if (!didE) stepper.synchronize();
  4780. LOOP_XYZE(i) {
  4781. if (parser.seenval(axis_codes[i])) {
  4782. #if IS_SCARA
  4783. current_position[i] = parser.value_axis_units((AxisEnum)i);
  4784. if (i != E_AXIS) didXYZ = true;
  4785. #else
  4786. #if HAS_POSITION_SHIFT
  4787. const float p = current_position[i];
  4788. #endif
  4789. const float v = parser.value_axis_units((AxisEnum)i);
  4790. current_position[i] = v;
  4791. if (i != E_AXIS) {
  4792. didXYZ = true;
  4793. #if HAS_POSITION_SHIFT
  4794. position_shift[i] += v - p; // Offset the coordinate space
  4795. update_software_endstops((AxisEnum)i);
  4796. #if ENABLED(I2C_POSITION_ENCODERS)
  4797. I2CPEM.encoders[I2CPEM.idx_from_axis((AxisEnum)i)].set_axis_offset(position_shift[i]);
  4798. #endif
  4799. #endif
  4800. }
  4801. #endif
  4802. }
  4803. }
  4804. if (didXYZ)
  4805. SYNC_PLAN_POSITION_KINEMATIC();
  4806. else if (didE)
  4807. sync_plan_position_e();
  4808. report_current_position();
  4809. }
  4810. #if HAS_RESUME_CONTINUE
  4811. /**
  4812. * M0: Unconditional stop - Wait for user button press on LCD
  4813. * M1: Conditional stop - Wait for user button press on LCD
  4814. */
  4815. inline void gcode_M0_M1() {
  4816. const char * const args = parser.string_arg;
  4817. millis_t ms = 0;
  4818. bool hasP = false, hasS = false;
  4819. if (parser.seenval('P')) {
  4820. ms = parser.value_millis(); // milliseconds to wait
  4821. hasP = ms > 0;
  4822. }
  4823. if (parser.seenval('S')) {
  4824. ms = parser.value_millis_from_seconds(); // seconds to wait
  4825. hasS = ms > 0;
  4826. }
  4827. #if ENABLED(ULTIPANEL)
  4828. if (!hasP && !hasS && args && *args)
  4829. lcd_setstatus(args, true);
  4830. else {
  4831. LCD_MESSAGEPGM(MSG_USERWAIT);
  4832. #if ENABLED(LCD_PROGRESS_BAR) && PROGRESS_MSG_EXPIRE > 0
  4833. dontExpireStatus();
  4834. #endif
  4835. }
  4836. #else
  4837. if (!hasP && !hasS && args && *args) {
  4838. SERIAL_ECHO_START();
  4839. SERIAL_ECHOLN(args);
  4840. }
  4841. #endif
  4842. KEEPALIVE_STATE(PAUSED_FOR_USER);
  4843. wait_for_user = true;
  4844. stepper.synchronize();
  4845. refresh_cmd_timeout();
  4846. if (ms > 0) {
  4847. ms += previous_cmd_ms; // wait until this time for a click
  4848. while (PENDING(millis(), ms) && wait_for_user) idle();
  4849. }
  4850. else {
  4851. #if ENABLED(ULTIPANEL)
  4852. if (lcd_detected()) {
  4853. while (wait_for_user) idle();
  4854. IS_SD_PRINTING ? LCD_MESSAGEPGM(MSG_RESUMING) : LCD_MESSAGEPGM(WELCOME_MSG);
  4855. }
  4856. #else
  4857. while (wait_for_user) idle();
  4858. #endif
  4859. }
  4860. wait_for_user = false;
  4861. KEEPALIVE_STATE(IN_HANDLER);
  4862. }
  4863. #endif // HAS_RESUME_CONTINUE
  4864. #if ENABLED(SPINDLE_LASER_ENABLE)
  4865. /**
  4866. * M3: Spindle Clockwise
  4867. * M4: Spindle Counter-clockwise
  4868. *
  4869. * S0 turns off spindle.
  4870. *
  4871. * If no speed PWM output is defined then M3/M4 just turns it on.
  4872. *
  4873. * At least 12.8KHz (50Hz * 256) is needed for spindle PWM.
  4874. * Hardware PWM is required. ISRs are too slow.
  4875. *
  4876. * NOTE: WGM for timers 3, 4, and 5 must be either Mode 1 or Mode 5.
  4877. * No other settings give a PWM signal that goes from 0 to 5 volts.
  4878. *
  4879. * The system automatically sets WGM to Mode 1, so no special
  4880. * initialization is needed.
  4881. *
  4882. * WGM bits for timer 2 are automatically set by the system to
  4883. * Mode 1. This produces an acceptable 0 to 5 volt signal.
  4884. * No special initialization is needed.
  4885. *
  4886. * NOTE: A minimum PWM frequency of 50 Hz is needed. All prescaler
  4887. * factors for timers 2, 3, 4, and 5 are acceptable.
  4888. *
  4889. * SPINDLE_LASER_ENABLE_PIN needs an external pullup or it may power on
  4890. * the spindle/laser during power-up or when connecting to the host
  4891. * (usually goes through a reset which sets all I/O pins to tri-state)
  4892. *
  4893. * PWM duty cycle goes from 0 (off) to 255 (always on).
  4894. */
  4895. // Wait for spindle to come up to speed
  4896. inline void delay_for_power_up() {
  4897. refresh_cmd_timeout();
  4898. while (PENDING(millis(), SPINDLE_LASER_POWERUP_DELAY + previous_cmd_ms)) idle();
  4899. }
  4900. // Wait for spindle to stop turning
  4901. inline void delay_for_power_down() {
  4902. refresh_cmd_timeout();
  4903. while (PENDING(millis(), SPINDLE_LASER_POWERDOWN_DELAY + previous_cmd_ms + 1)) idle();
  4904. }
  4905. /**
  4906. * ocr_val_mode() is used for debugging and to get the points needed to compute the RPM vs ocr_val line
  4907. *
  4908. * it accepts inputs of 0-255
  4909. */
  4910. inline void ocr_val_mode() {
  4911. uint8_t spindle_laser_power = parser.value_byte();
  4912. WRITE(SPINDLE_LASER_ENABLE_PIN, SPINDLE_LASER_ENABLE_INVERT); // turn spindle on (active low)
  4913. if (SPINDLE_LASER_PWM_INVERT) spindle_laser_power = 255 - spindle_laser_power;
  4914. analogWrite(SPINDLE_LASER_PWM_PIN, spindle_laser_power);
  4915. }
  4916. inline void gcode_M3_M4(bool is_M3) {
  4917. stepper.synchronize(); // wait until previous movement commands (G0/G0/G2/G3) have completed before playing with the spindle
  4918. #if SPINDLE_DIR_CHANGE
  4919. const bool rotation_dir = (is_M3 && !SPINDLE_INVERT_DIR || !is_M3 && SPINDLE_INVERT_DIR) ? HIGH : LOW;
  4920. if (SPINDLE_STOP_ON_DIR_CHANGE \
  4921. && READ(SPINDLE_LASER_ENABLE_PIN) == SPINDLE_LASER_ENABLE_INVERT \
  4922. && READ(SPINDLE_DIR_PIN) != rotation_dir
  4923. ) {
  4924. WRITE(SPINDLE_LASER_ENABLE_PIN, !SPINDLE_LASER_ENABLE_INVERT); // turn spindle off
  4925. delay_for_power_down();
  4926. }
  4927. digitalWrite(SPINDLE_DIR_PIN, rotation_dir);
  4928. #endif
  4929. /**
  4930. * Our final value for ocr_val is an unsigned 8 bit value between 0 and 255 which usually means uint8_t.
  4931. * Went to uint16_t because some of the uint8_t calculations would sometimes give 1000 0000 rather than 1111 1111.
  4932. * Then needed to AND the uint16_t result with 0x00FF to make sure we only wrote the byte of interest.
  4933. */
  4934. #if ENABLED(SPINDLE_LASER_PWM)
  4935. if (parser.seen('O')) ocr_val_mode();
  4936. else {
  4937. const float spindle_laser_power = parser.floatval('S');
  4938. if (spindle_laser_power == 0) {
  4939. WRITE(SPINDLE_LASER_ENABLE_PIN, !SPINDLE_LASER_ENABLE_INVERT); // turn spindle off (active low)
  4940. delay_for_power_down();
  4941. }
  4942. else {
  4943. int16_t ocr_val = (spindle_laser_power - (SPEED_POWER_INTERCEPT)) * (1.0 / (SPEED_POWER_SLOPE)); // convert RPM to PWM duty cycle
  4944. NOMORE(ocr_val, 255); // limit to max the Atmel PWM will support
  4945. if (spindle_laser_power <= SPEED_POWER_MIN)
  4946. ocr_val = (SPEED_POWER_MIN - (SPEED_POWER_INTERCEPT)) * (1.0 / (SPEED_POWER_SLOPE)); // minimum setting
  4947. if (spindle_laser_power >= SPEED_POWER_MAX)
  4948. ocr_val = (SPEED_POWER_MAX - (SPEED_POWER_INTERCEPT)) * (1.0 / (SPEED_POWER_SLOPE)); // limit to max RPM
  4949. if (SPINDLE_LASER_PWM_INVERT) ocr_val = 255 - ocr_val;
  4950. WRITE(SPINDLE_LASER_ENABLE_PIN, SPINDLE_LASER_ENABLE_INVERT); // turn spindle on (active low)
  4951. analogWrite(SPINDLE_LASER_PWM_PIN, ocr_val & 0xFF); // only write low byte
  4952. delay_for_power_up();
  4953. }
  4954. }
  4955. #else
  4956. WRITE(SPINDLE_LASER_ENABLE_PIN, SPINDLE_LASER_ENABLE_INVERT); // turn spindle on (active low) if spindle speed option not enabled
  4957. delay_for_power_up();
  4958. #endif
  4959. }
  4960. /**
  4961. * M5 turn off spindle
  4962. */
  4963. inline void gcode_M5() {
  4964. stepper.synchronize();
  4965. WRITE(SPINDLE_LASER_ENABLE_PIN, !SPINDLE_LASER_ENABLE_INVERT);
  4966. delay_for_power_down();
  4967. }
  4968. #endif // SPINDLE_LASER_ENABLE
  4969. /**
  4970. * M17: Enable power on all stepper motors
  4971. */
  4972. inline void gcode_M17() {
  4973. LCD_MESSAGEPGM(MSG_NO_MOVE);
  4974. enable_all_steppers();
  4975. }
  4976. #if IS_KINEMATIC
  4977. #define RUNPLAN(RATE_MM_S) planner.buffer_line_kinematic(destination, RATE_MM_S, active_extruder)
  4978. #else
  4979. #define RUNPLAN(RATE_MM_S) line_to_destination(RATE_MM_S)
  4980. #endif
  4981. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  4982. static float resume_position[XYZE];
  4983. static bool move_away_flag = false;
  4984. #if ENABLED(SDSUPPORT)
  4985. static bool sd_print_paused = false;
  4986. #endif
  4987. static void filament_change_beep(const int8_t max_beep_count, const bool init=false) {
  4988. static millis_t next_buzz = 0;
  4989. static int8_t runout_beep = 0;
  4990. if (init) next_buzz = runout_beep = 0;
  4991. const millis_t ms = millis();
  4992. if (ELAPSED(ms, next_buzz)) {
  4993. if (max_beep_count < 0 || runout_beep < max_beep_count + 5) { // Only beep as long as we're supposed to
  4994. next_buzz = ms + ((max_beep_count < 0 || runout_beep < max_beep_count) ? 2500 : 400);
  4995. BUZZ(300, 2000);
  4996. runout_beep++;
  4997. }
  4998. }
  4999. }
  5000. static void ensure_safe_temperature() {
  5001. bool heaters_heating = true;
  5002. wait_for_heatup = true; // M108 will clear this
  5003. while (wait_for_heatup && heaters_heating) {
  5004. idle();
  5005. heaters_heating = false;
  5006. HOTEND_LOOP() {
  5007. if (thermalManager.degTargetHotend(e) && abs(thermalManager.degHotend(e) - thermalManager.degTargetHotend(e)) > TEMP_HYSTERESIS) {
  5008. heaters_heating = true;
  5009. #if ENABLED(ULTIPANEL)
  5010. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_WAIT_FOR_NOZZLES_TO_HEAT);
  5011. #endif
  5012. break;
  5013. }
  5014. }
  5015. }
  5016. }
  5017. static bool pause_print(const float &retract, const float &z_lift, const float &x_pos, const float &y_pos,
  5018. const float &unload_length = 0 , const int8_t max_beep_count = 0, const bool show_lcd = false
  5019. ) {
  5020. if (move_away_flag) return false; // already paused
  5021. if (!DEBUGGING(DRYRUN) && (unload_length != 0 || retract != 0)) {
  5022. #if ENABLED(PREVENT_COLD_EXTRUSION)
  5023. if (!thermalManager.allow_cold_extrude &&
  5024. thermalManager.degTargetHotend(active_extruder) < thermalManager.extrude_min_temp) {
  5025. SERIAL_ERROR_START();
  5026. SERIAL_ERRORLNPGM(MSG_TOO_COLD_FOR_M600);
  5027. return false;
  5028. }
  5029. #endif
  5030. ensure_safe_temperature(); // wait for extruder to heat up before unloading
  5031. }
  5032. // Indicate that the printer is paused
  5033. move_away_flag = true;
  5034. // Pause the print job and timer
  5035. #if ENABLED(SDSUPPORT)
  5036. if (card.sdprinting) {
  5037. card.pauseSDPrint();
  5038. sd_print_paused = true;
  5039. }
  5040. #endif
  5041. print_job_timer.pause();
  5042. // Show initial message and wait for synchronize steppers
  5043. if (show_lcd) {
  5044. #if ENABLED(ULTIPANEL)
  5045. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_INIT);
  5046. #endif
  5047. }
  5048. stepper.synchronize();
  5049. // Save current position
  5050. COPY(resume_position, current_position);
  5051. set_destination_to_current();
  5052. if (retract) {
  5053. // Initial retract before move to filament change position
  5054. destination[E_AXIS] += retract;
  5055. RUNPLAN(PAUSE_PARK_RETRACT_FEEDRATE);
  5056. }
  5057. // Lift Z axis
  5058. if (z_lift > 0) {
  5059. destination[Z_AXIS] += z_lift;
  5060. NOMORE(destination[Z_AXIS], Z_MAX_POS);
  5061. RUNPLAN(PAUSE_PARK_Z_FEEDRATE);
  5062. }
  5063. // Move XY axes to filament exchange position
  5064. destination[X_AXIS] = x_pos;
  5065. destination[Y_AXIS] = y_pos;
  5066. clamp_to_software_endstops(destination);
  5067. RUNPLAN(PAUSE_PARK_XY_FEEDRATE);
  5068. stepper.synchronize();
  5069. if (unload_length != 0) {
  5070. if (show_lcd) {
  5071. #if ENABLED(ULTIPANEL)
  5072. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_UNLOAD);
  5073. idle();
  5074. #endif
  5075. }
  5076. // Unload filament
  5077. destination[E_AXIS] += unload_length;
  5078. RUNPLAN(FILAMENT_CHANGE_UNLOAD_FEEDRATE);
  5079. stepper.synchronize();
  5080. }
  5081. if (show_lcd) {
  5082. #if ENABLED(ULTIPANEL)
  5083. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_INSERT);
  5084. #endif
  5085. }
  5086. #if HAS_BUZZER
  5087. filament_change_beep(max_beep_count, true);
  5088. #endif
  5089. idle();
  5090. // Disable extruders steppers for manual filament changing (only on boards that have separate ENABLE_PINS)
  5091. #if E0_ENABLE_PIN != X_ENABLE_PIN && E1_ENABLE_PIN != Y_ENABLE_PIN
  5092. disable_e_steppers();
  5093. safe_delay(100);
  5094. #endif
  5095. // Start the heater idle timers
  5096. const millis_t nozzle_timeout = (millis_t)(PAUSE_PARK_NOZZLE_TIMEOUT) * 1000UL;
  5097. HOTEND_LOOP()
  5098. thermalManager.start_heater_idle_timer(e, nozzle_timeout);
  5099. return true;
  5100. }
  5101. static void wait_for_filament_reload(const int8_t max_beep_count = 0) {
  5102. bool nozzle_timed_out = false;
  5103. // Wait for filament insert by user and press button
  5104. KEEPALIVE_STATE(PAUSED_FOR_USER);
  5105. wait_for_user = true; // LCD click or M108 will clear this
  5106. while (wait_for_user) {
  5107. #if HAS_BUZZER
  5108. filament_change_beep(max_beep_count);
  5109. #endif
  5110. // If the nozzle has timed out, wait for the user to press the button to re-heat the nozzle, then
  5111. // re-heat the nozzle, re-show the insert screen, restart the idle timers, and start over
  5112. if (!nozzle_timed_out)
  5113. HOTEND_LOOP()
  5114. nozzle_timed_out |= thermalManager.is_heater_idle(e);
  5115. if (nozzle_timed_out) {
  5116. #if ENABLED(ULTIPANEL)
  5117. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_CLICK_TO_HEAT_NOZZLE);
  5118. #endif
  5119. // Wait for LCD click or M108
  5120. while (wait_for_user) idle(true);
  5121. // Re-enable the heaters if they timed out
  5122. HOTEND_LOOP() thermalManager.reset_heater_idle_timer(e);
  5123. // Wait for the heaters to reach the target temperatures
  5124. ensure_safe_temperature();
  5125. #if ENABLED(ULTIPANEL)
  5126. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_INSERT);
  5127. #endif
  5128. // Start the heater idle timers
  5129. const millis_t nozzle_timeout = (millis_t)(PAUSE_PARK_NOZZLE_TIMEOUT) * 1000UL;
  5130. HOTEND_LOOP()
  5131. thermalManager.start_heater_idle_timer(e, nozzle_timeout);
  5132. wait_for_user = true; /* Wait for user to load filament */
  5133. nozzle_timed_out = false;
  5134. #if HAS_BUZZER
  5135. filament_change_beep(max_beep_count, true);
  5136. #endif
  5137. }
  5138. idle(true);
  5139. }
  5140. KEEPALIVE_STATE(IN_HANDLER);
  5141. }
  5142. static void resume_print(const float &load_length = 0, const float &initial_extrude_length = 0, const int8_t max_beep_count = 0) {
  5143. bool nozzle_timed_out = false;
  5144. if (!move_away_flag) return;
  5145. // Re-enable the heaters if they timed out
  5146. HOTEND_LOOP() {
  5147. nozzle_timed_out |= thermalManager.is_heater_idle(e);
  5148. thermalManager.reset_heater_idle_timer(e);
  5149. }
  5150. if (nozzle_timed_out) ensure_safe_temperature();
  5151. #if HAS_BUZZER
  5152. filament_change_beep(max_beep_count, true);
  5153. #endif
  5154. if (load_length != 0) {
  5155. #if ENABLED(ULTIPANEL)
  5156. // Show "insert filament"
  5157. if (nozzle_timed_out)
  5158. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_INSERT);
  5159. #endif
  5160. KEEPALIVE_STATE(PAUSED_FOR_USER);
  5161. wait_for_user = true; // LCD click or M108 will clear this
  5162. while (wait_for_user && nozzle_timed_out) {
  5163. #if HAS_BUZZER
  5164. filament_change_beep(max_beep_count);
  5165. #endif
  5166. idle(true);
  5167. }
  5168. KEEPALIVE_STATE(IN_HANDLER);
  5169. #if ENABLED(ULTIPANEL)
  5170. // Show "load" message
  5171. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_LOAD);
  5172. #endif
  5173. // Load filament
  5174. destination[E_AXIS] += load_length;
  5175. RUNPLAN(FILAMENT_CHANGE_LOAD_FEEDRATE);
  5176. stepper.synchronize();
  5177. }
  5178. #if ENABLED(ULTIPANEL) && ADVANCED_PAUSE_EXTRUDE_LENGTH > 0
  5179. float extrude_length = initial_extrude_length;
  5180. do {
  5181. if (extrude_length > 0) {
  5182. // "Wait for filament extrude"
  5183. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_EXTRUDE);
  5184. // Extrude filament to get into hotend
  5185. destination[E_AXIS] += extrude_length;
  5186. RUNPLAN(ADVANCED_PAUSE_EXTRUDE_FEEDRATE);
  5187. stepper.synchronize();
  5188. }
  5189. // Show "Extrude More" / "Resume" menu and wait for reply
  5190. KEEPALIVE_STATE(PAUSED_FOR_USER);
  5191. wait_for_user = false;
  5192. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_OPTION);
  5193. while (advanced_pause_menu_response == ADVANCED_PAUSE_RESPONSE_WAIT_FOR) idle(true);
  5194. KEEPALIVE_STATE(IN_HANDLER);
  5195. extrude_length = ADVANCED_PAUSE_EXTRUDE_LENGTH;
  5196. // Keep looping if "Extrude More" was selected
  5197. } while (advanced_pause_menu_response == ADVANCED_PAUSE_RESPONSE_EXTRUDE_MORE);
  5198. #endif
  5199. #if ENABLED(ULTIPANEL)
  5200. // "Wait for print to resume"
  5201. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_RESUME);
  5202. #endif
  5203. // Set extruder to saved position
  5204. destination[E_AXIS] = current_position[E_AXIS] = resume_position[E_AXIS];
  5205. planner.set_e_position_mm(current_position[E_AXIS]);
  5206. #if IS_KINEMATIC
  5207. // Move XYZ to starting position
  5208. planner.buffer_line_kinematic(resume_position, PAUSE_PARK_XY_FEEDRATE, active_extruder);
  5209. #else
  5210. // Move XY to starting position, then Z
  5211. destination[X_AXIS] = resume_position[X_AXIS];
  5212. destination[Y_AXIS] = resume_position[Y_AXIS];
  5213. RUNPLAN(PAUSE_PARK_XY_FEEDRATE);
  5214. destination[Z_AXIS] = resume_position[Z_AXIS];
  5215. RUNPLAN(PAUSE_PARK_Z_FEEDRATE);
  5216. #endif
  5217. stepper.synchronize();
  5218. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  5219. filament_ran_out = false;
  5220. #endif
  5221. #if ENABLED(ULTIPANEL)
  5222. // Show status screen
  5223. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_STATUS);
  5224. #endif
  5225. #if ENABLED(SDSUPPORT)
  5226. if (sd_print_paused) {
  5227. card.startFileprint();
  5228. sd_print_paused = false;
  5229. }
  5230. #endif
  5231. move_away_flag = false;
  5232. }
  5233. #endif // ADVANCED_PAUSE_FEATURE
  5234. #if ENABLED(SDSUPPORT)
  5235. /**
  5236. * M20: List SD card to serial output
  5237. */
  5238. inline void gcode_M20() {
  5239. SERIAL_PROTOCOLLNPGM(MSG_BEGIN_FILE_LIST);
  5240. card.ls();
  5241. SERIAL_PROTOCOLLNPGM(MSG_END_FILE_LIST);
  5242. }
  5243. /**
  5244. * M21: Init SD Card
  5245. */
  5246. inline void gcode_M21() { card.initsd(); }
  5247. /**
  5248. * M22: Release SD Card
  5249. */
  5250. inline void gcode_M22() { card.release(); }
  5251. /**
  5252. * M23: Open a file
  5253. */
  5254. inline void gcode_M23() { card.openFile(parser.string_arg, true); }
  5255. /**
  5256. * M24: Start or Resume SD Print
  5257. */
  5258. inline void gcode_M24() {
  5259. #if ENABLED(PARK_HEAD_ON_PAUSE)
  5260. resume_print();
  5261. #endif
  5262. card.startFileprint();
  5263. print_job_timer.start();
  5264. }
  5265. /**
  5266. * M25: Pause SD Print
  5267. */
  5268. inline void gcode_M25() {
  5269. card.pauseSDPrint();
  5270. print_job_timer.pause();
  5271. #if ENABLED(PARK_HEAD_ON_PAUSE)
  5272. enqueue_and_echo_commands_P(PSTR("M125")); // Must be enqueued with pauseSDPrint set to be last in the buffer
  5273. #endif
  5274. }
  5275. /**
  5276. * M26: Set SD Card file index
  5277. */
  5278. inline void gcode_M26() {
  5279. if (card.cardOK && parser.seenval('S'))
  5280. card.setIndex(parser.value_long());
  5281. }
  5282. /**
  5283. * M27: Get SD Card status
  5284. */
  5285. inline void gcode_M27() { card.getStatus(); }
  5286. /**
  5287. * M28: Start SD Write
  5288. */
  5289. inline void gcode_M28() { card.openFile(parser.string_arg, false); }
  5290. /**
  5291. * M29: Stop SD Write
  5292. * Processed in write to file routine above
  5293. */
  5294. inline void gcode_M29() {
  5295. // card.saving = false;
  5296. }
  5297. /**
  5298. * M30 <filename>: Delete SD Card file
  5299. */
  5300. inline void gcode_M30() {
  5301. if (card.cardOK) {
  5302. card.closefile();
  5303. card.removeFile(parser.string_arg);
  5304. }
  5305. }
  5306. #endif // SDSUPPORT
  5307. /**
  5308. * M31: Get the time since the start of SD Print (or last M109)
  5309. */
  5310. inline void gcode_M31() {
  5311. char buffer[21];
  5312. duration_t elapsed = print_job_timer.duration();
  5313. elapsed.toString(buffer);
  5314. lcd_setstatus(buffer);
  5315. SERIAL_ECHO_START();
  5316. SERIAL_ECHOLNPAIR("Print time: ", buffer);
  5317. }
  5318. #if ENABLED(SDSUPPORT)
  5319. /**
  5320. * M32: Select file and start SD Print
  5321. */
  5322. inline void gcode_M32() {
  5323. if (card.sdprinting)
  5324. stepper.synchronize();
  5325. char* namestartpos = parser.string_arg;
  5326. const bool call_procedure = parser.boolval('P');
  5327. if (card.cardOK) {
  5328. card.openFile(namestartpos, true, call_procedure);
  5329. if (parser.seenval('S'))
  5330. card.setIndex(parser.value_long());
  5331. card.startFileprint();
  5332. // Procedure calls count as normal print time.
  5333. if (!call_procedure) print_job_timer.start();
  5334. }
  5335. }
  5336. #if ENABLED(LONG_FILENAME_HOST_SUPPORT)
  5337. /**
  5338. * M33: Get the long full path of a file or folder
  5339. *
  5340. * Parameters:
  5341. * <dospath> Case-insensitive DOS-style path to a file or folder
  5342. *
  5343. * Example:
  5344. * M33 miscel~1/armchair/armcha~1.gco
  5345. *
  5346. * Output:
  5347. * /Miscellaneous/Armchair/Armchair.gcode
  5348. */
  5349. inline void gcode_M33() {
  5350. card.printLongPath(parser.string_arg);
  5351. }
  5352. #endif
  5353. #if ENABLED(SDCARD_SORT_ALPHA) && ENABLED(SDSORT_GCODE)
  5354. /**
  5355. * M34: Set SD Card Sorting Options
  5356. */
  5357. inline void gcode_M34() {
  5358. if (parser.seen('S')) card.setSortOn(parser.value_bool());
  5359. if (parser.seenval('F')) {
  5360. const int v = parser.value_long();
  5361. card.setSortFolders(v < 0 ? -1 : v > 0 ? 1 : 0);
  5362. }
  5363. //if (parser.seen('R')) card.setSortReverse(parser.value_bool());
  5364. }
  5365. #endif // SDCARD_SORT_ALPHA && SDSORT_GCODE
  5366. /**
  5367. * M928: Start SD Write
  5368. */
  5369. inline void gcode_M928() {
  5370. card.openLogFile(parser.string_arg);
  5371. }
  5372. #endif // SDSUPPORT
  5373. /**
  5374. * Sensitive pin test for M42, M226
  5375. */
  5376. static bool pin_is_protected(const int8_t pin) {
  5377. static const int8_t sensitive_pins[] PROGMEM = SENSITIVE_PINS;
  5378. for (uint8_t i = 0; i < COUNT(sensitive_pins); i++)
  5379. if (pin == (int8_t)pgm_read_byte(&sensitive_pins[i])) return true;
  5380. return false;
  5381. }
  5382. /**
  5383. * M42: Change pin status via GCode
  5384. *
  5385. * P<pin> Pin number (LED if omitted)
  5386. * S<byte> Pin status from 0 - 255
  5387. */
  5388. inline void gcode_M42() {
  5389. if (!parser.seenval('S')) return;
  5390. const byte pin_status = parser.value_byte();
  5391. const int pin_number = parser.intval('P', LED_PIN);
  5392. if (pin_number < 0) return;
  5393. if (pin_is_protected(pin_number)) {
  5394. SERIAL_ERROR_START();
  5395. SERIAL_ERRORLNPGM(MSG_ERR_PROTECTED_PIN);
  5396. return;
  5397. }
  5398. pinMode(pin_number, OUTPUT);
  5399. digitalWrite(pin_number, pin_status);
  5400. analogWrite(pin_number, pin_status);
  5401. #if FAN_COUNT > 0
  5402. switch (pin_number) {
  5403. #if HAS_FAN0
  5404. case FAN_PIN: fanSpeeds[0] = pin_status; break;
  5405. #endif
  5406. #if HAS_FAN1
  5407. case FAN1_PIN: fanSpeeds[1] = pin_status; break;
  5408. #endif
  5409. #if HAS_FAN2
  5410. case FAN2_PIN: fanSpeeds[2] = pin_status; break;
  5411. #endif
  5412. }
  5413. #endif
  5414. }
  5415. #if ENABLED(PINS_DEBUGGING)
  5416. #include "pinsDebug.h"
  5417. inline void toggle_pins() {
  5418. const bool I_flag = parser.boolval('I');
  5419. const int repeat = parser.intval('R', 1),
  5420. start = parser.intval('S'),
  5421. end = parser.intval('E', NUM_DIGITAL_PINS - 1),
  5422. wait = parser.intval('W', 500);
  5423. for (uint8_t pin = start; pin <= end; pin++) {
  5424. //report_pin_state_extended(pin, I_flag, false);
  5425. if (!I_flag && pin_is_protected(pin)) {
  5426. report_pin_state_extended(pin, I_flag, true, "Untouched ");
  5427. SERIAL_EOL();
  5428. }
  5429. else {
  5430. report_pin_state_extended(pin, I_flag, true, "Pulsing ");
  5431. #if AVR_AT90USB1286_FAMILY // Teensy IDEs don't know about these pins so must use FASTIO
  5432. if (pin == 46) {
  5433. SET_OUTPUT(46);
  5434. for (int16_t j = 0; j < repeat; j++) {
  5435. WRITE(46, 0); safe_delay(wait);
  5436. WRITE(46, 1); safe_delay(wait);
  5437. WRITE(46, 0); safe_delay(wait);
  5438. }
  5439. }
  5440. else if (pin == 47) {
  5441. SET_OUTPUT(47);
  5442. for (int16_t j = 0; j < repeat; j++) {
  5443. WRITE(47, 0); safe_delay(wait);
  5444. WRITE(47, 1); safe_delay(wait);
  5445. WRITE(47, 0); safe_delay(wait);
  5446. }
  5447. }
  5448. else
  5449. #endif
  5450. {
  5451. pinMode(pin, OUTPUT);
  5452. for (int16_t j = 0; j < repeat; j++) {
  5453. digitalWrite(pin, 0); safe_delay(wait);
  5454. digitalWrite(pin, 1); safe_delay(wait);
  5455. digitalWrite(pin, 0); safe_delay(wait);
  5456. }
  5457. }
  5458. }
  5459. SERIAL_EOL();
  5460. }
  5461. SERIAL_ECHOLNPGM("Done.");
  5462. } // toggle_pins
  5463. inline void servo_probe_test() {
  5464. #if !(NUM_SERVOS > 0 && HAS_SERVO_0)
  5465. SERIAL_ERROR_START();
  5466. SERIAL_ERRORLNPGM("SERVO not setup");
  5467. #elif !HAS_Z_SERVO_ENDSTOP
  5468. SERIAL_ERROR_START();
  5469. SERIAL_ERRORLNPGM("Z_ENDSTOP_SERVO_NR not setup");
  5470. #else
  5471. const uint8_t probe_index = parser.byteval('P', Z_ENDSTOP_SERVO_NR);
  5472. SERIAL_PROTOCOLLNPGM("Servo probe test");
  5473. SERIAL_PROTOCOLLNPAIR(". using index: ", probe_index);
  5474. SERIAL_PROTOCOLLNPAIR(". deploy angle: ", z_servo_angle[0]);
  5475. SERIAL_PROTOCOLLNPAIR(". stow angle: ", z_servo_angle[1]);
  5476. bool probe_inverting;
  5477. #if ENABLED(Z_MIN_PROBE_USES_Z_MIN_ENDSTOP_PIN)
  5478. #define PROBE_TEST_PIN Z_MIN_PIN
  5479. SERIAL_PROTOCOLLNPAIR(". probe uses Z_MIN pin: ", PROBE_TEST_PIN);
  5480. SERIAL_PROTOCOLLNPGM(". uses Z_MIN_ENDSTOP_INVERTING (ignores Z_MIN_PROBE_ENDSTOP_INVERTING)");
  5481. SERIAL_PROTOCOLPGM(". Z_MIN_ENDSTOP_INVERTING: ");
  5482. #if Z_MIN_ENDSTOP_INVERTING
  5483. SERIAL_PROTOCOLLNPGM("true");
  5484. #else
  5485. SERIAL_PROTOCOLLNPGM("false");
  5486. #endif
  5487. probe_inverting = Z_MIN_ENDSTOP_INVERTING;
  5488. #elif ENABLED(Z_MIN_PROBE_ENDSTOP)
  5489. #define PROBE_TEST_PIN Z_MIN_PROBE_PIN
  5490. SERIAL_PROTOCOLLNPAIR(". probe uses Z_MIN_PROBE_PIN: ", PROBE_TEST_PIN);
  5491. SERIAL_PROTOCOLLNPGM(". uses Z_MIN_PROBE_ENDSTOP_INVERTING (ignores Z_MIN_ENDSTOP_INVERTING)");
  5492. SERIAL_PROTOCOLPGM(". Z_MIN_PROBE_ENDSTOP_INVERTING: ");
  5493. #if Z_MIN_PROBE_ENDSTOP_INVERTING
  5494. SERIAL_PROTOCOLLNPGM("true");
  5495. #else
  5496. SERIAL_PROTOCOLLNPGM("false");
  5497. #endif
  5498. probe_inverting = Z_MIN_PROBE_ENDSTOP_INVERTING;
  5499. #endif
  5500. SERIAL_PROTOCOLLNPGM(". deploy & stow 4 times");
  5501. SET_INPUT_PULLUP(PROBE_TEST_PIN);
  5502. bool deploy_state, stow_state;
  5503. for (uint8_t i = 0; i < 4; i++) {
  5504. servo[probe_index].move(z_servo_angle[0]); //deploy
  5505. safe_delay(500);
  5506. deploy_state = digitalRead(PROBE_TEST_PIN);
  5507. servo[probe_index].move(z_servo_angle[1]); //stow
  5508. safe_delay(500);
  5509. stow_state = digitalRead(PROBE_TEST_PIN);
  5510. }
  5511. if (probe_inverting != deploy_state) SERIAL_PROTOCOLLNPGM("WARNING - INVERTING setting probably backwards");
  5512. refresh_cmd_timeout();
  5513. if (deploy_state != stow_state) {
  5514. SERIAL_PROTOCOLLNPGM("BLTouch clone detected");
  5515. if (deploy_state) {
  5516. SERIAL_PROTOCOLLNPGM(". DEPLOYED state: HIGH (logic 1)");
  5517. SERIAL_PROTOCOLLNPGM(". STOWED (triggered) state: LOW (logic 0)");
  5518. }
  5519. else {
  5520. SERIAL_PROTOCOLLNPGM(". DEPLOYED state: LOW (logic 0)");
  5521. SERIAL_PROTOCOLLNPGM(". STOWED (triggered) state: HIGH (logic 1)");
  5522. }
  5523. #if ENABLED(BLTOUCH)
  5524. SERIAL_PROTOCOLLNPGM("ERROR: BLTOUCH enabled - set this device up as a Z Servo Probe with inverting as true.");
  5525. #endif
  5526. }
  5527. else { // measure active signal length
  5528. servo[probe_index].move(z_servo_angle[0]); // deploy
  5529. safe_delay(500);
  5530. SERIAL_PROTOCOLLNPGM("please trigger probe");
  5531. uint16_t probe_counter = 0;
  5532. // Allow 30 seconds max for operator to trigger probe
  5533. for (uint16_t j = 0; j < 500 * 30 && probe_counter == 0 ; j++) {
  5534. safe_delay(2);
  5535. if (0 == j % (500 * 1)) // keep cmd_timeout happy
  5536. refresh_cmd_timeout();
  5537. if (deploy_state != digitalRead(PROBE_TEST_PIN)) { // probe triggered
  5538. for (probe_counter = 1; probe_counter < 50 && deploy_state != digitalRead(PROBE_TEST_PIN); ++probe_counter)
  5539. safe_delay(2);
  5540. if (probe_counter == 50)
  5541. SERIAL_PROTOCOLLNPGM("Z Servo Probe detected"); // >= 100mS active time
  5542. else if (probe_counter >= 2)
  5543. SERIAL_PROTOCOLLNPAIR("BLTouch compatible probe detected - pulse width (+/- 4mS): ", probe_counter * 2); // allow 4 - 100mS pulse
  5544. else
  5545. SERIAL_PROTOCOLLNPGM("noise detected - please re-run test"); // less than 2mS pulse
  5546. servo[probe_index].move(z_servo_angle[1]); //stow
  5547. } // pulse detected
  5548. } // for loop waiting for trigger
  5549. if (probe_counter == 0) SERIAL_PROTOCOLLNPGM("trigger not detected");
  5550. } // measure active signal length
  5551. #endif
  5552. } // servo_probe_test
  5553. /**
  5554. * M43: Pin debug - report pin state, watch pins, toggle pins and servo probe test/report
  5555. *
  5556. * M43 - report name and state of pin(s)
  5557. * P<pin> Pin to read or watch. If omitted, reads all pins.
  5558. * I Flag to ignore Marlin's pin protection.
  5559. *
  5560. * M43 W - Watch pins -reporting changes- until reset, click, or M108.
  5561. * P<pin> Pin to read or watch. If omitted, read/watch all pins.
  5562. * I Flag to ignore Marlin's pin protection.
  5563. *
  5564. * M43 E<bool> - Enable / disable background endstop monitoring
  5565. * - Machine continues to operate
  5566. * - Reports changes to endstops
  5567. * - Toggles LED_PIN when an endstop changes
  5568. * - Can not reliably catch the 5mS pulse from BLTouch type probes
  5569. *
  5570. * M43 T - Toggle pin(s) and report which pin is being toggled
  5571. * S<pin> - Start Pin number. If not given, will default to 0
  5572. * L<pin> - End Pin number. If not given, will default to last pin defined for this board
  5573. * I<bool> - Flag to ignore Marlin's pin protection. Use with caution!!!!
  5574. * R - Repeat pulses on each pin this number of times before continueing to next pin
  5575. * W - Wait time (in miliseconds) between pulses. If not given will default to 500
  5576. *
  5577. * M43 S - Servo probe test
  5578. * P<index> - Probe index (optional - defaults to 0
  5579. */
  5580. inline void gcode_M43() {
  5581. if (parser.seen('T')) { // must be first or else its "S" and "E" parameters will execute endstop or servo test
  5582. toggle_pins();
  5583. return;
  5584. }
  5585. // Enable or disable endstop monitoring
  5586. if (parser.seen('E')) {
  5587. endstop_monitor_flag = parser.value_bool();
  5588. SERIAL_PROTOCOLPGM("endstop monitor ");
  5589. SERIAL_PROTOCOL(endstop_monitor_flag ? "en" : "dis");
  5590. SERIAL_PROTOCOLLNPGM("abled");
  5591. return;
  5592. }
  5593. if (parser.seen('S')) {
  5594. servo_probe_test();
  5595. return;
  5596. }
  5597. // Get the range of pins to test or watch
  5598. const uint8_t first_pin = parser.byteval('P'),
  5599. last_pin = parser.seenval('P') ? first_pin : NUM_DIGITAL_PINS - 1;
  5600. if (first_pin > last_pin) return;
  5601. const bool ignore_protection = parser.boolval('I');
  5602. // Watch until click, M108, or reset
  5603. if (parser.boolval('W')) {
  5604. SERIAL_PROTOCOLLNPGM("Watching pins");
  5605. byte pin_state[last_pin - first_pin + 1];
  5606. for (int8_t pin = first_pin; pin <= last_pin; pin++) {
  5607. if (pin_is_protected(pin) && !ignore_protection) continue;
  5608. pinMode(pin, INPUT_PULLUP);
  5609. delay(1);
  5610. /*
  5611. if (IS_ANALOG(pin))
  5612. pin_state[pin - first_pin] = analogRead(pin - analogInputToDigitalPin(0)); // int16_t pin_state[...]
  5613. else
  5614. //*/
  5615. pin_state[pin - first_pin] = digitalRead(pin);
  5616. }
  5617. #if HAS_RESUME_CONTINUE
  5618. wait_for_user = true;
  5619. KEEPALIVE_STATE(PAUSED_FOR_USER);
  5620. #endif
  5621. for (;;) {
  5622. for (int8_t pin = first_pin; pin <= last_pin; pin++) {
  5623. if (pin_is_protected(pin) && !ignore_protection) continue;
  5624. const byte val =
  5625. /*
  5626. IS_ANALOG(pin)
  5627. ? analogRead(pin - analogInputToDigitalPin(0)) : // int16_t val
  5628. :
  5629. //*/
  5630. digitalRead(pin);
  5631. if (val != pin_state[pin - first_pin]) {
  5632. report_pin_state_extended(pin, ignore_protection, false);
  5633. pin_state[pin - first_pin] = val;
  5634. }
  5635. }
  5636. #if HAS_RESUME_CONTINUE
  5637. if (!wait_for_user) {
  5638. KEEPALIVE_STATE(IN_HANDLER);
  5639. break;
  5640. }
  5641. #endif
  5642. safe_delay(200);
  5643. }
  5644. return;
  5645. }
  5646. // Report current state of selected pin(s)
  5647. for (uint8_t pin = first_pin; pin <= last_pin; pin++)
  5648. report_pin_state_extended(pin, ignore_protection, true);
  5649. }
  5650. #endif // PINS_DEBUGGING
  5651. #if ENABLED(Z_MIN_PROBE_REPEATABILITY_TEST)
  5652. /**
  5653. * M48: Z probe repeatability measurement function.
  5654. *
  5655. * Usage:
  5656. * M48 <P#> <X#> <Y#> <V#> <E> <L#>
  5657. * P = Number of sampled points (4-50, default 10)
  5658. * X = Sample X position
  5659. * Y = Sample Y position
  5660. * V = Verbose level (0-4, default=1)
  5661. * E = Engage Z probe for each reading
  5662. * L = Number of legs of movement before probe
  5663. * S = Schizoid (Or Star if you prefer)
  5664. *
  5665. * This function assumes the bed has been homed. Specifically, that a G28 command
  5666. * as been issued prior to invoking the M48 Z probe repeatability measurement function.
  5667. * Any information generated by a prior G29 Bed leveling command will be lost and need to be
  5668. * regenerated.
  5669. */
  5670. inline void gcode_M48() {
  5671. if (axis_unhomed_error()) return;
  5672. const int8_t verbose_level = parser.byteval('V', 1);
  5673. if (!WITHIN(verbose_level, 0, 4)) {
  5674. SERIAL_PROTOCOLLNPGM("?(V)erbose level is implausible (0-4).");
  5675. return;
  5676. }
  5677. if (verbose_level > 0)
  5678. SERIAL_PROTOCOLLNPGM("M48 Z-Probe Repeatability Test");
  5679. const int8_t n_samples = parser.byteval('P', 10);
  5680. if (!WITHIN(n_samples, 4, 50)) {
  5681. SERIAL_PROTOCOLLNPGM("?Sample size not plausible (4-50).");
  5682. return;
  5683. }
  5684. const bool stow_probe_after_each = parser.boolval('E');
  5685. float X_current = current_position[X_AXIS],
  5686. Y_current = current_position[Y_AXIS];
  5687. const float X_probe_location = parser.linearval('X', X_current + X_PROBE_OFFSET_FROM_EXTRUDER),
  5688. Y_probe_location = parser.linearval('Y', Y_current + Y_PROBE_OFFSET_FROM_EXTRUDER);
  5689. #if DISABLED(DELTA)
  5690. if (!WITHIN(X_probe_location, LOGICAL_X_POSITION(MIN_PROBE_X), LOGICAL_X_POSITION(MAX_PROBE_X))) {
  5691. out_of_range_error(PSTR("X"));
  5692. return;
  5693. }
  5694. if (!WITHIN(Y_probe_location, LOGICAL_Y_POSITION(MIN_PROBE_Y), LOGICAL_Y_POSITION(MAX_PROBE_Y))) {
  5695. out_of_range_error(PSTR("Y"));
  5696. return;
  5697. }
  5698. #else
  5699. if (!position_is_reachable_by_probe_xy(X_probe_location, Y_probe_location)) {
  5700. SERIAL_PROTOCOLLNPGM("? (X,Y) location outside of probeable radius.");
  5701. return;
  5702. }
  5703. #endif
  5704. bool seen_L = parser.seen('L');
  5705. uint8_t n_legs = seen_L ? parser.value_byte() : 0;
  5706. if (n_legs > 15) {
  5707. SERIAL_PROTOCOLLNPGM("?Number of legs in movement not plausible (0-15).");
  5708. return;
  5709. }
  5710. if (n_legs == 1) n_legs = 2;
  5711. const bool schizoid_flag = parser.boolval('S');
  5712. if (schizoid_flag && !seen_L) n_legs = 7;
  5713. /**
  5714. * Now get everything to the specified probe point So we can safely do a
  5715. * probe to get us close to the bed. If the Z-Axis is far from the bed,
  5716. * we don't want to use that as a starting point for each probe.
  5717. */
  5718. if (verbose_level > 2)
  5719. SERIAL_PROTOCOLLNPGM("Positioning the probe...");
  5720. // Disable bed level correction in M48 because we want the raw data when we probe
  5721. #if HAS_LEVELING
  5722. const bool was_enabled = leveling_is_active();
  5723. set_bed_leveling_enabled(false);
  5724. #endif
  5725. setup_for_endstop_or_probe_move();
  5726. // Move to the first point, deploy, and probe
  5727. const float t = probe_pt(X_probe_location, Y_probe_location, stow_probe_after_each, verbose_level);
  5728. if (isnan(t)) return;
  5729. randomSeed(millis());
  5730. double mean = 0.0, sigma = 0.0, min = 99999.9, max = -99999.9, sample_set[n_samples];
  5731. for (uint8_t n = 0; n < n_samples; n++) {
  5732. if (n_legs) {
  5733. int dir = (random(0, 10) > 5.0) ? -1 : 1; // clockwise or counter clockwise
  5734. float angle = random(0.0, 360.0),
  5735. radius = random(
  5736. #if ENABLED(DELTA)
  5737. DELTA_PROBEABLE_RADIUS / 8, DELTA_PROBEABLE_RADIUS / 3
  5738. #else
  5739. 5, X_MAX_LENGTH / 8
  5740. #endif
  5741. );
  5742. if (verbose_level > 3) {
  5743. SERIAL_ECHOPAIR("Starting radius: ", radius);
  5744. SERIAL_ECHOPAIR(" angle: ", angle);
  5745. SERIAL_ECHOPGM(" Direction: ");
  5746. if (dir > 0) SERIAL_ECHOPGM("Counter-");
  5747. SERIAL_ECHOLNPGM("Clockwise");
  5748. }
  5749. for (uint8_t l = 0; l < n_legs - 1; l++) {
  5750. double delta_angle;
  5751. if (schizoid_flag)
  5752. // The points of a 5 point star are 72 degrees apart. We need to
  5753. // skip a point and go to the next one on the star.
  5754. delta_angle = dir * 2.0 * 72.0;
  5755. else
  5756. // If we do this line, we are just trying to move further
  5757. // around the circle.
  5758. delta_angle = dir * (float) random(25, 45);
  5759. angle += delta_angle;
  5760. while (angle > 360.0) // We probably do not need to keep the angle between 0 and 2*PI, but the
  5761. angle -= 360.0; // Arduino documentation says the trig functions should not be given values
  5762. while (angle < 0.0) // outside of this range. It looks like they behave correctly with
  5763. angle += 360.0; // numbers outside of the range, but just to be safe we clamp them.
  5764. X_current = X_probe_location - (X_PROBE_OFFSET_FROM_EXTRUDER) + cos(RADIANS(angle)) * radius;
  5765. Y_current = Y_probe_location - (Y_PROBE_OFFSET_FROM_EXTRUDER) + sin(RADIANS(angle)) * radius;
  5766. #if DISABLED(DELTA)
  5767. X_current = constrain(X_current, X_MIN_POS, X_MAX_POS);
  5768. Y_current = constrain(Y_current, Y_MIN_POS, Y_MAX_POS);
  5769. #else
  5770. // If we have gone out too far, we can do a simple fix and scale the numbers
  5771. // back in closer to the origin.
  5772. while (!position_is_reachable_by_probe_xy(X_current, Y_current)) {
  5773. X_current *= 0.8;
  5774. Y_current *= 0.8;
  5775. if (verbose_level > 3) {
  5776. SERIAL_ECHOPAIR("Pulling point towards center:", X_current);
  5777. SERIAL_ECHOLNPAIR(", ", Y_current);
  5778. }
  5779. }
  5780. #endif
  5781. if (verbose_level > 3) {
  5782. SERIAL_PROTOCOLPGM("Going to:");
  5783. SERIAL_ECHOPAIR(" X", X_current);
  5784. SERIAL_ECHOPAIR(" Y", Y_current);
  5785. SERIAL_ECHOLNPAIR(" Z", current_position[Z_AXIS]);
  5786. }
  5787. do_blocking_move_to_xy(X_current, Y_current);
  5788. } // n_legs loop
  5789. } // n_legs
  5790. // Probe a single point
  5791. sample_set[n] = probe_pt(X_probe_location, Y_probe_location, stow_probe_after_each, 0);
  5792. /**
  5793. * Get the current mean for the data points we have so far
  5794. */
  5795. double sum = 0.0;
  5796. for (uint8_t j = 0; j <= n; j++) sum += sample_set[j];
  5797. mean = sum / (n + 1);
  5798. NOMORE(min, sample_set[n]);
  5799. NOLESS(max, sample_set[n]);
  5800. /**
  5801. * Now, use that mean to calculate the standard deviation for the
  5802. * data points we have so far
  5803. */
  5804. sum = 0.0;
  5805. for (uint8_t j = 0; j <= n; j++)
  5806. sum += sq(sample_set[j] - mean);
  5807. sigma = SQRT(sum / (n + 1));
  5808. if (verbose_level > 0) {
  5809. if (verbose_level > 1) {
  5810. SERIAL_PROTOCOL(n + 1);
  5811. SERIAL_PROTOCOLPGM(" of ");
  5812. SERIAL_PROTOCOL((int)n_samples);
  5813. SERIAL_PROTOCOLPGM(": z: ");
  5814. SERIAL_PROTOCOL_F(sample_set[n], 3);
  5815. if (verbose_level > 2) {
  5816. SERIAL_PROTOCOLPGM(" mean: ");
  5817. SERIAL_PROTOCOL_F(mean, 4);
  5818. SERIAL_PROTOCOLPGM(" sigma: ");
  5819. SERIAL_PROTOCOL_F(sigma, 6);
  5820. SERIAL_PROTOCOLPGM(" min: ");
  5821. SERIAL_PROTOCOL_F(min, 3);
  5822. SERIAL_PROTOCOLPGM(" max: ");
  5823. SERIAL_PROTOCOL_F(max, 3);
  5824. SERIAL_PROTOCOLPGM(" range: ");
  5825. SERIAL_PROTOCOL_F(max-min, 3);
  5826. }
  5827. SERIAL_EOL();
  5828. }
  5829. }
  5830. } // End of probe loop
  5831. if (STOW_PROBE()) return;
  5832. SERIAL_PROTOCOLPGM("Finished!");
  5833. SERIAL_EOL();
  5834. if (verbose_level > 0) {
  5835. SERIAL_PROTOCOLPGM("Mean: ");
  5836. SERIAL_PROTOCOL_F(mean, 6);
  5837. SERIAL_PROTOCOLPGM(" Min: ");
  5838. SERIAL_PROTOCOL_F(min, 3);
  5839. SERIAL_PROTOCOLPGM(" Max: ");
  5840. SERIAL_PROTOCOL_F(max, 3);
  5841. SERIAL_PROTOCOLPGM(" Range: ");
  5842. SERIAL_PROTOCOL_F(max-min, 3);
  5843. SERIAL_EOL();
  5844. }
  5845. SERIAL_PROTOCOLPGM("Standard Deviation: ");
  5846. SERIAL_PROTOCOL_F(sigma, 6);
  5847. SERIAL_EOL();
  5848. SERIAL_EOL();
  5849. clean_up_after_endstop_or_probe_move();
  5850. // Re-enable bed level correction if it had been on
  5851. #if HAS_LEVELING
  5852. set_bed_leveling_enabled(was_enabled);
  5853. #endif
  5854. report_current_position();
  5855. }
  5856. #endif // Z_MIN_PROBE_REPEATABILITY_TEST
  5857. #if ENABLED(AUTO_BED_LEVELING_UBL) && ENABLED(UBL_G26_MESH_VALIDATION)
  5858. inline void gcode_M49() {
  5859. ubl.g26_debug_flag ^= true;
  5860. SERIAL_PROTOCOLPGM("UBL Debug Flag turned ");
  5861. serialprintPGM(ubl.g26_debug_flag ? PSTR("on.") : PSTR("off."));
  5862. }
  5863. #endif // AUTO_BED_LEVELING_UBL && UBL_G26_MESH_VALIDATION
  5864. /**
  5865. * M75: Start print timer
  5866. */
  5867. inline void gcode_M75() { print_job_timer.start(); }
  5868. /**
  5869. * M76: Pause print timer
  5870. */
  5871. inline void gcode_M76() { print_job_timer.pause(); }
  5872. /**
  5873. * M77: Stop print timer
  5874. */
  5875. inline void gcode_M77() { print_job_timer.stop(); }
  5876. #if ENABLED(PRINTCOUNTER)
  5877. /**
  5878. * M78: Show print statistics
  5879. */
  5880. inline void gcode_M78() {
  5881. // "M78 S78" will reset the statistics
  5882. if (parser.intval('S') == 78)
  5883. print_job_timer.initStats();
  5884. else
  5885. print_job_timer.showStats();
  5886. }
  5887. #endif
  5888. /**
  5889. * M104: Set hot end temperature
  5890. */
  5891. inline void gcode_M104() {
  5892. if (get_target_extruder_from_command(104)) return;
  5893. if (DEBUGGING(DRYRUN)) return;
  5894. #if ENABLED(SINGLENOZZLE)
  5895. if (target_extruder != active_extruder) return;
  5896. #endif
  5897. if (parser.seenval('S')) {
  5898. const int16_t temp = parser.value_celsius();
  5899. thermalManager.setTargetHotend(temp, target_extruder);
  5900. #if ENABLED(DUAL_X_CARRIAGE)
  5901. if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && target_extruder == 0)
  5902. thermalManager.setTargetHotend(temp ? temp + duplicate_extruder_temp_offset : 0, 1);
  5903. #endif
  5904. #if ENABLED(PRINTJOB_TIMER_AUTOSTART)
  5905. /**
  5906. * Stop the timer at the end of print. Start is managed by 'heat and wait' M109.
  5907. * We use half EXTRUDE_MINTEMP here to allow nozzles to be put into hot
  5908. * standby mode, for instance in a dual extruder setup, without affecting
  5909. * the running print timer.
  5910. */
  5911. if (parser.value_celsius() <= (EXTRUDE_MINTEMP) / 2) {
  5912. print_job_timer.stop();
  5913. LCD_MESSAGEPGM(WELCOME_MSG);
  5914. }
  5915. #endif
  5916. if (parser.value_celsius() > thermalManager.degHotend(target_extruder))
  5917. lcd_status_printf_P(0, PSTR("E%i %s"), target_extruder + 1, MSG_HEATING);
  5918. }
  5919. #if ENABLED(AUTOTEMP)
  5920. planner.autotemp_M104_M109();
  5921. #endif
  5922. }
  5923. #if HAS_TEMP_HOTEND || HAS_TEMP_BED
  5924. void print_heater_state(const float &c, const float &t,
  5925. #if ENABLED(SHOW_TEMP_ADC_VALUES)
  5926. const float r,
  5927. #endif
  5928. const int8_t e=-2
  5929. ) {
  5930. SERIAL_PROTOCOLCHAR(' ');
  5931. SERIAL_PROTOCOLCHAR(
  5932. #if HAS_TEMP_BED && HAS_TEMP_HOTEND
  5933. e == -1 ? 'B' : 'T'
  5934. #elif HAS_TEMP_HOTEND
  5935. 'T'
  5936. #else
  5937. 'B'
  5938. #endif
  5939. );
  5940. #if HOTENDS > 1
  5941. if (e >= 0) SERIAL_PROTOCOLCHAR('0' + e);
  5942. #endif
  5943. SERIAL_PROTOCOLCHAR(':');
  5944. SERIAL_PROTOCOL(c);
  5945. SERIAL_PROTOCOLPAIR(" /" , t);
  5946. #if ENABLED(SHOW_TEMP_ADC_VALUES)
  5947. SERIAL_PROTOCOLPAIR(" (", r / OVERSAMPLENR);
  5948. SERIAL_PROTOCOLCHAR(')');
  5949. #endif
  5950. }
  5951. void print_heaterstates() {
  5952. #if HAS_TEMP_HOTEND
  5953. print_heater_state(thermalManager.degHotend(target_extruder), thermalManager.degTargetHotend(target_extruder)
  5954. #if ENABLED(SHOW_TEMP_ADC_VALUES)
  5955. , thermalManager.rawHotendTemp(target_extruder)
  5956. #endif
  5957. );
  5958. #endif
  5959. #if HAS_TEMP_BED
  5960. print_heater_state(thermalManager.degBed(), thermalManager.degTargetBed(),
  5961. #if ENABLED(SHOW_TEMP_ADC_VALUES)
  5962. thermalManager.rawBedTemp(),
  5963. #endif
  5964. -1 // BED
  5965. );
  5966. #endif
  5967. #if HOTENDS > 1
  5968. HOTEND_LOOP() print_heater_state(thermalManager.degHotend(e), thermalManager.degTargetHotend(e),
  5969. #if ENABLED(SHOW_TEMP_ADC_VALUES)
  5970. thermalManager.rawHotendTemp(e),
  5971. #endif
  5972. e
  5973. );
  5974. #endif
  5975. SERIAL_PROTOCOLPGM(" @:");
  5976. SERIAL_PROTOCOL(thermalManager.getHeaterPower(target_extruder));
  5977. #if HAS_TEMP_BED
  5978. SERIAL_PROTOCOLPGM(" B@:");
  5979. SERIAL_PROTOCOL(thermalManager.getHeaterPower(-1));
  5980. #endif
  5981. #if HOTENDS > 1
  5982. HOTEND_LOOP() {
  5983. SERIAL_PROTOCOLPAIR(" @", e);
  5984. SERIAL_PROTOCOLCHAR(':');
  5985. SERIAL_PROTOCOL(thermalManager.getHeaterPower(e));
  5986. }
  5987. #endif
  5988. }
  5989. #endif
  5990. /**
  5991. * M105: Read hot end and bed temperature
  5992. */
  5993. inline void gcode_M105() {
  5994. if (get_target_extruder_from_command(105)) return;
  5995. #if HAS_TEMP_HOTEND || HAS_TEMP_BED
  5996. SERIAL_PROTOCOLPGM(MSG_OK);
  5997. print_heaterstates();
  5998. #else // !HAS_TEMP_HOTEND && !HAS_TEMP_BED
  5999. SERIAL_ERROR_START();
  6000. SERIAL_ERRORLNPGM(MSG_ERR_NO_THERMISTORS);
  6001. #endif
  6002. SERIAL_EOL();
  6003. }
  6004. #if ENABLED(AUTO_REPORT_TEMPERATURES) && (HAS_TEMP_HOTEND || HAS_TEMP_BED)
  6005. static uint8_t auto_report_temp_interval;
  6006. static millis_t next_temp_report_ms;
  6007. /**
  6008. * M155: Set temperature auto-report interval. M155 S<seconds>
  6009. */
  6010. inline void gcode_M155() {
  6011. if (parser.seenval('S')) {
  6012. auto_report_temp_interval = parser.value_byte();
  6013. NOMORE(auto_report_temp_interval, 60);
  6014. next_temp_report_ms = millis() + 1000UL * auto_report_temp_interval;
  6015. }
  6016. }
  6017. inline void auto_report_temperatures() {
  6018. if (auto_report_temp_interval && ELAPSED(millis(), next_temp_report_ms)) {
  6019. next_temp_report_ms = millis() + 1000UL * auto_report_temp_interval;
  6020. print_heaterstates();
  6021. SERIAL_EOL();
  6022. }
  6023. }
  6024. #endif // AUTO_REPORT_TEMPERATURES
  6025. #if FAN_COUNT > 0
  6026. /**
  6027. * M106: Set Fan Speed
  6028. *
  6029. * S<int> Speed between 0-255
  6030. * P<index> Fan index, if more than one fan
  6031. */
  6032. inline void gcode_M106() {
  6033. uint16_t s = parser.ushortval('S', 255);
  6034. NOMORE(s, 255);
  6035. const uint8_t p = parser.byteval('P', 0);
  6036. if (p < FAN_COUNT) fanSpeeds[p] = s;
  6037. }
  6038. /**
  6039. * M107: Fan Off
  6040. */
  6041. inline void gcode_M107() {
  6042. const uint16_t p = parser.ushortval('P');
  6043. if (p < FAN_COUNT) fanSpeeds[p] = 0;
  6044. }
  6045. #endif // FAN_COUNT > 0
  6046. #if DISABLED(EMERGENCY_PARSER)
  6047. /**
  6048. * M108: Stop the waiting for heaters in M109, M190, M303. Does not affect the target temperature.
  6049. */
  6050. inline void gcode_M108() { wait_for_heatup = false; }
  6051. /**
  6052. * M112: Emergency Stop
  6053. */
  6054. inline void gcode_M112() { kill(PSTR(MSG_KILLED)); }
  6055. /**
  6056. * M410: Quickstop - Abort all planned moves
  6057. *
  6058. * This will stop the carriages mid-move, so most likely they
  6059. * will be out of sync with the stepper position after this.
  6060. */
  6061. inline void gcode_M410() { quickstop_stepper(); }
  6062. #endif
  6063. /**
  6064. * M109: Sxxx Wait for extruder(s) to reach temperature. Waits only when heating.
  6065. * Rxxx Wait for extruder(s) to reach temperature. Waits when heating and cooling.
  6066. */
  6067. #ifndef MIN_COOLING_SLOPE_DEG
  6068. #define MIN_COOLING_SLOPE_DEG 1.50
  6069. #endif
  6070. #ifndef MIN_COOLING_SLOPE_TIME
  6071. #define MIN_COOLING_SLOPE_TIME 60
  6072. #endif
  6073. inline void gcode_M109() {
  6074. if (get_target_extruder_from_command(109)) return;
  6075. if (DEBUGGING(DRYRUN)) return;
  6076. #if ENABLED(SINGLENOZZLE)
  6077. if (target_extruder != active_extruder) return;
  6078. #endif
  6079. const bool no_wait_for_cooling = parser.seenval('S');
  6080. if (no_wait_for_cooling || parser.seenval('R')) {
  6081. const int16_t temp = parser.value_celsius();
  6082. thermalManager.setTargetHotend(temp, target_extruder);
  6083. #if ENABLED(DUAL_X_CARRIAGE)
  6084. if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && target_extruder == 0)
  6085. thermalManager.setTargetHotend(temp ? temp + duplicate_extruder_temp_offset : 0, 1);
  6086. #endif
  6087. #if ENABLED(PRINTJOB_TIMER_AUTOSTART)
  6088. /**
  6089. * Use half EXTRUDE_MINTEMP to allow nozzles to be put into hot
  6090. * standby mode, (e.g., in a dual extruder setup) without affecting
  6091. * the running print timer.
  6092. */
  6093. if (parser.value_celsius() <= (EXTRUDE_MINTEMP) / 2) {
  6094. print_job_timer.stop();
  6095. LCD_MESSAGEPGM(WELCOME_MSG);
  6096. }
  6097. else
  6098. print_job_timer.start();
  6099. #endif
  6100. if (thermalManager.isHeatingHotend(target_extruder)) lcd_status_printf_P(0, PSTR("E%i %s"), target_extruder + 1, MSG_HEATING);
  6101. }
  6102. else return;
  6103. #if ENABLED(AUTOTEMP)
  6104. planner.autotemp_M104_M109();
  6105. #endif
  6106. #if TEMP_RESIDENCY_TIME > 0
  6107. millis_t residency_start_ms = 0;
  6108. // Loop until the temperature has stabilized
  6109. #define TEMP_CONDITIONS (!residency_start_ms || PENDING(now, residency_start_ms + (TEMP_RESIDENCY_TIME) * 1000UL))
  6110. #else
  6111. // Loop until the temperature is very close target
  6112. #define TEMP_CONDITIONS (wants_to_cool ? thermalManager.isCoolingHotend(target_extruder) : thermalManager.isHeatingHotend(target_extruder))
  6113. #endif
  6114. float target_temp = -1.0, old_temp = 9999.0;
  6115. bool wants_to_cool = false;
  6116. wait_for_heatup = true;
  6117. millis_t now, next_temp_ms = 0, next_cool_check_ms = 0;
  6118. KEEPALIVE_STATE(NOT_BUSY);
  6119. #if ENABLED(PRINTER_EVENT_LEDS)
  6120. const float start_temp = thermalManager.degHotend(target_extruder);
  6121. uint8_t old_blue = 0;
  6122. #endif
  6123. do {
  6124. // Target temperature might be changed during the loop
  6125. if (target_temp != thermalManager.degTargetHotend(target_extruder)) {
  6126. wants_to_cool = thermalManager.isCoolingHotend(target_extruder);
  6127. target_temp = thermalManager.degTargetHotend(target_extruder);
  6128. // Exit if S<lower>, continue if S<higher>, R<lower>, or R<higher>
  6129. if (no_wait_for_cooling && wants_to_cool) break;
  6130. }
  6131. now = millis();
  6132. if (ELAPSED(now, next_temp_ms)) { //Print temp & remaining time every 1s while waiting
  6133. next_temp_ms = now + 1000UL;
  6134. print_heaterstates();
  6135. #if TEMP_RESIDENCY_TIME > 0
  6136. SERIAL_PROTOCOLPGM(" W:");
  6137. if (residency_start_ms)
  6138. SERIAL_PROTOCOL(long((((TEMP_RESIDENCY_TIME) * 1000UL) - (now - residency_start_ms)) / 1000UL));
  6139. else
  6140. SERIAL_PROTOCOLCHAR('?');
  6141. #endif
  6142. SERIAL_EOL();
  6143. }
  6144. idle();
  6145. refresh_cmd_timeout(); // to prevent stepper_inactive_time from running out
  6146. const float temp = thermalManager.degHotend(target_extruder);
  6147. #if ENABLED(PRINTER_EVENT_LEDS)
  6148. // Gradually change LED strip from violet to red as nozzle heats up
  6149. if (!wants_to_cool) {
  6150. const uint8_t blue = map(constrain(temp, start_temp, target_temp), start_temp, target_temp, 255, 0);
  6151. if (blue != old_blue) set_led_color(255, 0, (old_blue = blue));
  6152. }
  6153. #endif
  6154. #if TEMP_RESIDENCY_TIME > 0
  6155. const float temp_diff = FABS(target_temp - temp);
  6156. if (!residency_start_ms) {
  6157. // Start the TEMP_RESIDENCY_TIME timer when we reach target temp for the first time.
  6158. if (temp_diff < TEMP_WINDOW) residency_start_ms = now;
  6159. }
  6160. else if (temp_diff > TEMP_HYSTERESIS) {
  6161. // Restart the timer whenever the temperature falls outside the hysteresis.
  6162. residency_start_ms = now;
  6163. }
  6164. #endif
  6165. // Prevent a wait-forever situation if R is misused i.e. M109 R0
  6166. if (wants_to_cool) {
  6167. // break after MIN_COOLING_SLOPE_TIME seconds
  6168. // if the temperature did not drop at least MIN_COOLING_SLOPE_DEG
  6169. if (!next_cool_check_ms || ELAPSED(now, next_cool_check_ms)) {
  6170. if (old_temp - temp < MIN_COOLING_SLOPE_DEG) break;
  6171. next_cool_check_ms = now + 1000UL * MIN_COOLING_SLOPE_TIME;
  6172. old_temp = temp;
  6173. }
  6174. }
  6175. } while (wait_for_heatup && TEMP_CONDITIONS);
  6176. if (wait_for_heatup) {
  6177. LCD_MESSAGEPGM(MSG_HEATING_COMPLETE);
  6178. #if ENABLED(PRINTER_EVENT_LEDS)
  6179. #if ENABLED(RGBW_LED)
  6180. set_led_color(0, 0, 0, 255); // Turn on the WHITE LED
  6181. #else
  6182. set_led_color(255, 255, 255); // Set LEDs All On
  6183. #endif
  6184. #endif
  6185. }
  6186. KEEPALIVE_STATE(IN_HANDLER);
  6187. }
  6188. #if HAS_TEMP_BED
  6189. #ifndef MIN_COOLING_SLOPE_DEG_BED
  6190. #define MIN_COOLING_SLOPE_DEG_BED 1.50
  6191. #endif
  6192. #ifndef MIN_COOLING_SLOPE_TIME_BED
  6193. #define MIN_COOLING_SLOPE_TIME_BED 60
  6194. #endif
  6195. /**
  6196. * M190: Sxxx Wait for bed current temp to reach target temp. Waits only when heating
  6197. * Rxxx Wait for bed current temp to reach target temp. Waits when heating and cooling
  6198. */
  6199. inline void gcode_M190() {
  6200. if (DEBUGGING(DRYRUN)) return;
  6201. LCD_MESSAGEPGM(MSG_BED_HEATING);
  6202. const bool no_wait_for_cooling = parser.seenval('S');
  6203. if (no_wait_for_cooling || parser.seenval('R')) {
  6204. thermalManager.setTargetBed(parser.value_celsius());
  6205. #if ENABLED(PRINTJOB_TIMER_AUTOSTART)
  6206. if (parser.value_celsius() > BED_MINTEMP)
  6207. print_job_timer.start();
  6208. #endif
  6209. }
  6210. else return;
  6211. #if TEMP_BED_RESIDENCY_TIME > 0
  6212. millis_t residency_start_ms = 0;
  6213. // Loop until the temperature has stabilized
  6214. #define TEMP_BED_CONDITIONS (!residency_start_ms || PENDING(now, residency_start_ms + (TEMP_BED_RESIDENCY_TIME) * 1000UL))
  6215. #else
  6216. // Loop until the temperature is very close target
  6217. #define TEMP_BED_CONDITIONS (wants_to_cool ? thermalManager.isCoolingBed() : thermalManager.isHeatingBed())
  6218. #endif
  6219. float target_temp = -1.0, old_temp = 9999.0;
  6220. bool wants_to_cool = false;
  6221. wait_for_heatup = true;
  6222. millis_t now, next_temp_ms = 0, next_cool_check_ms = 0;
  6223. KEEPALIVE_STATE(NOT_BUSY);
  6224. target_extruder = active_extruder; // for print_heaterstates
  6225. #if ENABLED(PRINTER_EVENT_LEDS)
  6226. const float start_temp = thermalManager.degBed();
  6227. uint8_t old_red = 255;
  6228. #endif
  6229. do {
  6230. // Target temperature might be changed during the loop
  6231. if (target_temp != thermalManager.degTargetBed()) {
  6232. wants_to_cool = thermalManager.isCoolingBed();
  6233. target_temp = thermalManager.degTargetBed();
  6234. // Exit if S<lower>, continue if S<higher>, R<lower>, or R<higher>
  6235. if (no_wait_for_cooling && wants_to_cool) break;
  6236. }
  6237. now = millis();
  6238. if (ELAPSED(now, next_temp_ms)) { //Print Temp Reading every 1 second while heating up.
  6239. next_temp_ms = now + 1000UL;
  6240. print_heaterstates();
  6241. #if TEMP_BED_RESIDENCY_TIME > 0
  6242. SERIAL_PROTOCOLPGM(" W:");
  6243. if (residency_start_ms)
  6244. SERIAL_PROTOCOL(long((((TEMP_BED_RESIDENCY_TIME) * 1000UL) - (now - residency_start_ms)) / 1000UL));
  6245. else
  6246. SERIAL_PROTOCOLCHAR('?');
  6247. #endif
  6248. SERIAL_EOL();
  6249. }
  6250. idle();
  6251. refresh_cmd_timeout(); // to prevent stepper_inactive_time from running out
  6252. const float temp = thermalManager.degBed();
  6253. #if ENABLED(PRINTER_EVENT_LEDS)
  6254. // Gradually change LED strip from blue to violet as bed heats up
  6255. if (!wants_to_cool) {
  6256. const uint8_t red = map(constrain(temp, start_temp, target_temp), start_temp, target_temp, 0, 255);
  6257. if (red != old_red) set_led_color((old_red = red), 0, 255);
  6258. }
  6259. #endif
  6260. #if TEMP_BED_RESIDENCY_TIME > 0
  6261. const float temp_diff = FABS(target_temp - temp);
  6262. if (!residency_start_ms) {
  6263. // Start the TEMP_BED_RESIDENCY_TIME timer when we reach target temp for the first time.
  6264. if (temp_diff < TEMP_BED_WINDOW) residency_start_ms = now;
  6265. }
  6266. else if (temp_diff > TEMP_BED_HYSTERESIS) {
  6267. // Restart the timer whenever the temperature falls outside the hysteresis.
  6268. residency_start_ms = now;
  6269. }
  6270. #endif // TEMP_BED_RESIDENCY_TIME > 0
  6271. // Prevent a wait-forever situation if R is misused i.e. M190 R0
  6272. if (wants_to_cool) {
  6273. // Break after MIN_COOLING_SLOPE_TIME_BED seconds
  6274. // if the temperature did not drop at least MIN_COOLING_SLOPE_DEG_BED
  6275. if (!next_cool_check_ms || ELAPSED(now, next_cool_check_ms)) {
  6276. if (old_temp - temp < MIN_COOLING_SLOPE_DEG_BED) break;
  6277. next_cool_check_ms = now + 1000UL * MIN_COOLING_SLOPE_TIME_BED;
  6278. old_temp = temp;
  6279. }
  6280. }
  6281. } while (wait_for_heatup && TEMP_BED_CONDITIONS);
  6282. if (wait_for_heatup) LCD_MESSAGEPGM(MSG_BED_DONE);
  6283. KEEPALIVE_STATE(IN_HANDLER);
  6284. }
  6285. #endif // HAS_TEMP_BED
  6286. /**
  6287. * M110: Set Current Line Number
  6288. */
  6289. inline void gcode_M110() {
  6290. if (parser.seenval('N')) gcode_LastN = parser.value_long();
  6291. }
  6292. /**
  6293. * M111: Set the debug level
  6294. */
  6295. inline void gcode_M111() {
  6296. marlin_debug_flags = parser.byteval('S', (uint8_t)DEBUG_NONE);
  6297. const static char str_debug_1[] PROGMEM = MSG_DEBUG_ECHO;
  6298. const static char str_debug_2[] PROGMEM = MSG_DEBUG_INFO;
  6299. const static char str_debug_4[] PROGMEM = MSG_DEBUG_ERRORS;
  6300. const static char str_debug_8[] PROGMEM = MSG_DEBUG_DRYRUN;
  6301. const static char str_debug_16[] PROGMEM = MSG_DEBUG_COMMUNICATION;
  6302. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6303. const static char str_debug_32[] PROGMEM = MSG_DEBUG_LEVELING;
  6304. #endif
  6305. const static char* const debug_strings[] PROGMEM = {
  6306. str_debug_1, str_debug_2, str_debug_4, str_debug_8, str_debug_16
  6307. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6308. , str_debug_32
  6309. #endif
  6310. };
  6311. SERIAL_ECHO_START();
  6312. SERIAL_ECHOPGM(MSG_DEBUG_PREFIX);
  6313. if (marlin_debug_flags) {
  6314. uint8_t comma = 0;
  6315. for (uint8_t i = 0; i < COUNT(debug_strings); i++) {
  6316. if (TEST(marlin_debug_flags, i)) {
  6317. if (comma++) SERIAL_CHAR(',');
  6318. serialprintPGM((char*)pgm_read_word(&debug_strings[i]));
  6319. }
  6320. }
  6321. }
  6322. else {
  6323. SERIAL_ECHOPGM(MSG_DEBUG_OFF);
  6324. }
  6325. SERIAL_EOL();
  6326. }
  6327. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  6328. /**
  6329. * M113: Get or set Host Keepalive interval (0 to disable)
  6330. *
  6331. * S<seconds> Optional. Set the keepalive interval.
  6332. */
  6333. inline void gcode_M113() {
  6334. if (parser.seenval('S')) {
  6335. host_keepalive_interval = parser.value_byte();
  6336. NOMORE(host_keepalive_interval, 60);
  6337. }
  6338. else {
  6339. SERIAL_ECHO_START();
  6340. SERIAL_ECHOLNPAIR("M113 S", (unsigned long)host_keepalive_interval);
  6341. }
  6342. }
  6343. #endif
  6344. #if ENABLED(BARICUDA)
  6345. #if HAS_HEATER_1
  6346. /**
  6347. * M126: Heater 1 valve open
  6348. */
  6349. inline void gcode_M126() { baricuda_valve_pressure = parser.byteval('S', 255); }
  6350. /**
  6351. * M127: Heater 1 valve close
  6352. */
  6353. inline void gcode_M127() { baricuda_valve_pressure = 0; }
  6354. #endif
  6355. #if HAS_HEATER_2
  6356. /**
  6357. * M128: Heater 2 valve open
  6358. */
  6359. inline void gcode_M128() { baricuda_e_to_p_pressure = parser.byteval('S', 255); }
  6360. /**
  6361. * M129: Heater 2 valve close
  6362. */
  6363. inline void gcode_M129() { baricuda_e_to_p_pressure = 0; }
  6364. #endif
  6365. #endif // BARICUDA
  6366. /**
  6367. * M140: Set bed temperature
  6368. */
  6369. inline void gcode_M140() {
  6370. if (DEBUGGING(DRYRUN)) return;
  6371. if (parser.seenval('S')) thermalManager.setTargetBed(parser.value_celsius());
  6372. }
  6373. #if ENABLED(ULTIPANEL)
  6374. /**
  6375. * M145: Set the heatup state for a material in the LCD menu
  6376. *
  6377. * S<material> (0=PLA, 1=ABS)
  6378. * H<hotend temp>
  6379. * B<bed temp>
  6380. * F<fan speed>
  6381. */
  6382. inline void gcode_M145() {
  6383. const uint8_t material = (uint8_t)parser.intval('S');
  6384. if (material >= COUNT(lcd_preheat_hotend_temp)) {
  6385. SERIAL_ERROR_START();
  6386. SERIAL_ERRORLNPGM(MSG_ERR_MATERIAL_INDEX);
  6387. }
  6388. else {
  6389. int v;
  6390. if (parser.seenval('H')) {
  6391. v = parser.value_int();
  6392. lcd_preheat_hotend_temp[material] = constrain(v, EXTRUDE_MINTEMP, HEATER_0_MAXTEMP - 15);
  6393. }
  6394. if (parser.seenval('F')) {
  6395. v = parser.value_int();
  6396. lcd_preheat_fan_speed[material] = constrain(v, 0, 255);
  6397. }
  6398. #if TEMP_SENSOR_BED != 0
  6399. if (parser.seenval('B')) {
  6400. v = parser.value_int();
  6401. lcd_preheat_bed_temp[material] = constrain(v, BED_MINTEMP, BED_MAXTEMP - 15);
  6402. }
  6403. #endif
  6404. }
  6405. }
  6406. #endif // ULTIPANEL
  6407. #if ENABLED(TEMPERATURE_UNITS_SUPPORT)
  6408. /**
  6409. * M149: Set temperature units
  6410. */
  6411. inline void gcode_M149() {
  6412. if (parser.seenval('C')) parser.set_input_temp_units(TEMPUNIT_C);
  6413. else if (parser.seenval('K')) parser.set_input_temp_units(TEMPUNIT_K);
  6414. else if (parser.seenval('F')) parser.set_input_temp_units(TEMPUNIT_F);
  6415. }
  6416. #endif
  6417. #if HAS_POWER_SWITCH
  6418. /**
  6419. * M80 : Turn on the Power Supply
  6420. * M80 S : Report the current state and exit
  6421. */
  6422. inline void gcode_M80() {
  6423. // S: Report the current power supply state and exit
  6424. if (parser.seen('S')) {
  6425. serialprintPGM(powersupply_on ? PSTR("PS:1\n") : PSTR("PS:0\n"));
  6426. return;
  6427. }
  6428. OUT_WRITE(PS_ON_PIN, PS_ON_AWAKE); // GND
  6429. /**
  6430. * If you have a switch on suicide pin, this is useful
  6431. * if you want to start another print with suicide feature after
  6432. * a print without suicide...
  6433. */
  6434. #if HAS_SUICIDE
  6435. OUT_WRITE(SUICIDE_PIN, HIGH);
  6436. #endif
  6437. #if ENABLED(HAVE_TMC2130)
  6438. delay(100);
  6439. tmc2130_init(); // Settings only stick when the driver has power
  6440. #endif
  6441. powersupply_on = true;
  6442. #if ENABLED(ULTIPANEL)
  6443. LCD_MESSAGEPGM(WELCOME_MSG);
  6444. #endif
  6445. }
  6446. #endif // HAS_POWER_SWITCH
  6447. /**
  6448. * M81: Turn off Power, including Power Supply, if there is one.
  6449. *
  6450. * This code should ALWAYS be available for EMERGENCY SHUTDOWN!
  6451. */
  6452. inline void gcode_M81() {
  6453. thermalManager.disable_all_heaters();
  6454. stepper.finish_and_disable();
  6455. #if FAN_COUNT > 0
  6456. for (uint8_t i = 0; i < FAN_COUNT; i++) fanSpeeds[i] = 0;
  6457. #if ENABLED(PROBING_FANS_OFF)
  6458. fans_paused = false;
  6459. ZERO(paused_fanSpeeds);
  6460. #endif
  6461. #endif
  6462. safe_delay(1000); // Wait 1 second before switching off
  6463. #if HAS_SUICIDE
  6464. stepper.synchronize();
  6465. suicide();
  6466. #elif HAS_POWER_SWITCH
  6467. OUT_WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  6468. powersupply_on = false;
  6469. #endif
  6470. #if ENABLED(ULTIPANEL)
  6471. LCD_MESSAGEPGM(MACHINE_NAME " " MSG_OFF ".");
  6472. #endif
  6473. }
  6474. /**
  6475. * M82: Set E codes absolute (default)
  6476. */
  6477. inline void gcode_M82() { axis_relative_modes[E_AXIS] = false; }
  6478. /**
  6479. * M83: Set E codes relative while in Absolute Coordinates (G90) mode
  6480. */
  6481. inline void gcode_M83() { axis_relative_modes[E_AXIS] = true; }
  6482. /**
  6483. * M18, M84: Disable stepper motors
  6484. */
  6485. inline void gcode_M18_M84() {
  6486. if (parser.seenval('S')) {
  6487. stepper_inactive_time = parser.value_millis_from_seconds();
  6488. }
  6489. else {
  6490. bool all_axis = !((parser.seen('X')) || (parser.seen('Y')) || (parser.seen('Z')) || (parser.seen('E')));
  6491. if (all_axis) {
  6492. stepper.finish_and_disable();
  6493. }
  6494. else {
  6495. stepper.synchronize();
  6496. if (parser.seen('X')) disable_X();
  6497. if (parser.seen('Y')) disable_Y();
  6498. if (parser.seen('Z')) disable_Z();
  6499. #if E0_ENABLE_PIN != X_ENABLE_PIN && E1_ENABLE_PIN != Y_ENABLE_PIN // Only enable on boards that have separate ENABLE_PINS
  6500. if (parser.seen('E')) disable_e_steppers();
  6501. #endif
  6502. }
  6503. #if ENABLED(AUTO_BED_LEVELING_UBL) && ENABLED(ULTRA_LCD) // Only needed with an LCD
  6504. ubl_lcd_map_control = defer_return_to_status = false;
  6505. #endif
  6506. }
  6507. }
  6508. /**
  6509. * M85: Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
  6510. */
  6511. inline void gcode_M85() {
  6512. if (parser.seen('S')) max_inactive_time = parser.value_millis_from_seconds();
  6513. }
  6514. /**
  6515. * Multi-stepper support for M92, M201, M203
  6516. */
  6517. #if ENABLED(DISTINCT_E_FACTORS)
  6518. #define GET_TARGET_EXTRUDER(CMD) if (get_target_extruder_from_command(CMD)) return
  6519. #define TARGET_EXTRUDER target_extruder
  6520. #else
  6521. #define GET_TARGET_EXTRUDER(CMD) NOOP
  6522. #define TARGET_EXTRUDER 0
  6523. #endif
  6524. /**
  6525. * M92: Set axis steps-per-unit for one or more axes, X, Y, Z, and E.
  6526. * (Follows the same syntax as G92)
  6527. *
  6528. * With multiple extruders use T to specify which one.
  6529. */
  6530. inline void gcode_M92() {
  6531. GET_TARGET_EXTRUDER(92);
  6532. LOOP_XYZE(i) {
  6533. if (parser.seen(axis_codes[i])) {
  6534. if (i == E_AXIS) {
  6535. const float value = parser.value_per_axis_unit((AxisEnum)(E_AXIS + TARGET_EXTRUDER));
  6536. if (value < 20.0) {
  6537. float factor = planner.axis_steps_per_mm[E_AXIS + TARGET_EXTRUDER] / value; // increase e constants if M92 E14 is given for netfab.
  6538. planner.max_jerk[E_AXIS] *= factor;
  6539. planner.max_feedrate_mm_s[E_AXIS + TARGET_EXTRUDER] *= factor;
  6540. planner.max_acceleration_steps_per_s2[E_AXIS + TARGET_EXTRUDER] *= factor;
  6541. }
  6542. planner.axis_steps_per_mm[E_AXIS + TARGET_EXTRUDER] = value;
  6543. }
  6544. else {
  6545. planner.axis_steps_per_mm[i] = parser.value_per_axis_unit((AxisEnum)i);
  6546. }
  6547. }
  6548. }
  6549. planner.refresh_positioning();
  6550. }
  6551. /**
  6552. * Output the current position to serial
  6553. */
  6554. void report_current_position() {
  6555. SERIAL_PROTOCOLPGM("X:");
  6556. SERIAL_PROTOCOL(current_position[X_AXIS]);
  6557. SERIAL_PROTOCOLPGM(" Y:");
  6558. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  6559. SERIAL_PROTOCOLPGM(" Z:");
  6560. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  6561. SERIAL_PROTOCOLPGM(" E:");
  6562. SERIAL_PROTOCOL(current_position[E_AXIS]);
  6563. stepper.report_positions();
  6564. #if IS_SCARA
  6565. SERIAL_PROTOCOLPAIR("SCARA Theta:", stepper.get_axis_position_degrees(A_AXIS));
  6566. SERIAL_PROTOCOLLNPAIR(" Psi+Theta:", stepper.get_axis_position_degrees(B_AXIS));
  6567. SERIAL_EOL();
  6568. #endif
  6569. }
  6570. #ifdef M114_DETAIL
  6571. void report_xyze(const float pos[XYZE], const uint8_t n = 4, const uint8_t precision = 3) {
  6572. char str[12];
  6573. for (uint8_t i = 0; i < n; i++) {
  6574. SERIAL_CHAR(' ');
  6575. SERIAL_CHAR(axis_codes[i]);
  6576. SERIAL_CHAR(':');
  6577. SERIAL_PROTOCOL(dtostrf(pos[i], 8, precision, str));
  6578. }
  6579. SERIAL_EOL();
  6580. }
  6581. inline void report_xyz(const float pos[XYZ]) { report_xyze(pos, 3); }
  6582. void report_current_position_detail() {
  6583. stepper.synchronize();
  6584. SERIAL_PROTOCOLPGM("\nLogical:");
  6585. report_xyze(current_position);
  6586. SERIAL_PROTOCOLPGM("Raw: ");
  6587. const float raw[XYZ] = { RAW_X_POSITION(current_position[X_AXIS]), RAW_Y_POSITION(current_position[Y_AXIS]), RAW_Z_POSITION(current_position[Z_AXIS]) };
  6588. report_xyz(raw);
  6589. SERIAL_PROTOCOLPGM("Leveled:");
  6590. float leveled[XYZ] = { current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS] };
  6591. planner.apply_leveling(leveled);
  6592. report_xyz(leveled);
  6593. SERIAL_PROTOCOLPGM("UnLevel:");
  6594. float unleveled[XYZ] = { leveled[X_AXIS], leveled[Y_AXIS], leveled[Z_AXIS] };
  6595. planner.unapply_leveling(unleveled);
  6596. report_xyz(unleveled);
  6597. #if IS_KINEMATIC
  6598. #if IS_SCARA
  6599. SERIAL_PROTOCOLPGM("ScaraK: ");
  6600. #else
  6601. SERIAL_PROTOCOLPGM("DeltaK: ");
  6602. #endif
  6603. inverse_kinematics(leveled); // writes delta[]
  6604. report_xyz(delta);
  6605. #endif
  6606. SERIAL_PROTOCOLPGM("Stepper:");
  6607. const float step_count[XYZE] = { stepper.position(X_AXIS), stepper.position(Y_AXIS), stepper.position(Z_AXIS), stepper.position(E_AXIS) };
  6608. report_xyze(step_count, 4, 0);
  6609. #if IS_SCARA
  6610. const float deg[XYZ] = {
  6611. stepper.get_axis_position_degrees(A_AXIS),
  6612. stepper.get_axis_position_degrees(B_AXIS)
  6613. };
  6614. SERIAL_PROTOCOLPGM("Degrees:");
  6615. report_xyze(deg, 2);
  6616. #endif
  6617. SERIAL_PROTOCOLPGM("FromStp:");
  6618. get_cartesian_from_steppers(); // writes cartes[XYZ] (with forward kinematics)
  6619. const float from_steppers[XYZE] = { cartes[X_AXIS], cartes[Y_AXIS], cartes[Z_AXIS], stepper.get_axis_position_mm(E_AXIS) };
  6620. report_xyze(from_steppers);
  6621. const float diff[XYZE] = {
  6622. from_steppers[X_AXIS] - leveled[X_AXIS],
  6623. from_steppers[Y_AXIS] - leveled[Y_AXIS],
  6624. from_steppers[Z_AXIS] - leveled[Z_AXIS],
  6625. from_steppers[E_AXIS] - current_position[E_AXIS]
  6626. };
  6627. SERIAL_PROTOCOLPGM("Differ: ");
  6628. report_xyze(diff);
  6629. }
  6630. #endif // M114_DETAIL
  6631. /**
  6632. * M114: Report current position to host
  6633. */
  6634. inline void gcode_M114() {
  6635. #ifdef M114_DETAIL
  6636. if (parser.seen('D')) {
  6637. report_current_position_detail();
  6638. return;
  6639. }
  6640. #endif
  6641. stepper.synchronize();
  6642. report_current_position();
  6643. }
  6644. /**
  6645. * M115: Capabilities string
  6646. */
  6647. inline void gcode_M115() {
  6648. SERIAL_PROTOCOLLNPGM(MSG_M115_REPORT);
  6649. #if ENABLED(EXTENDED_CAPABILITIES_REPORT)
  6650. // EEPROM (M500, M501)
  6651. #if ENABLED(EEPROM_SETTINGS)
  6652. SERIAL_PROTOCOLLNPGM("Cap:EEPROM:1");
  6653. #else
  6654. SERIAL_PROTOCOLLNPGM("Cap:EEPROM:0");
  6655. #endif
  6656. // AUTOREPORT_TEMP (M155)
  6657. #if ENABLED(AUTO_REPORT_TEMPERATURES)
  6658. SERIAL_PROTOCOLLNPGM("Cap:AUTOREPORT_TEMP:1");
  6659. #else
  6660. SERIAL_PROTOCOLLNPGM("Cap:AUTOREPORT_TEMP:0");
  6661. #endif
  6662. // PROGRESS (M530 S L, M531 <file>, M532 X L)
  6663. SERIAL_PROTOCOLLNPGM("Cap:PROGRESS:0");
  6664. // Print Job timer M75, M76, M77
  6665. SERIAL_PROTOCOLLNPGM("Cap:PRINT_JOB:1");
  6666. // AUTOLEVEL (G29)
  6667. #if HAS_ABL
  6668. SERIAL_PROTOCOLLNPGM("Cap:AUTOLEVEL:1");
  6669. #else
  6670. SERIAL_PROTOCOLLNPGM("Cap:AUTOLEVEL:0");
  6671. #endif
  6672. // Z_PROBE (G30)
  6673. #if HAS_BED_PROBE
  6674. SERIAL_PROTOCOLLNPGM("Cap:Z_PROBE:1");
  6675. #else
  6676. SERIAL_PROTOCOLLNPGM("Cap:Z_PROBE:0");
  6677. #endif
  6678. // MESH_REPORT (M420 V)
  6679. #if HAS_LEVELING
  6680. SERIAL_PROTOCOLLNPGM("Cap:LEVELING_DATA:1");
  6681. #else
  6682. SERIAL_PROTOCOLLNPGM("Cap:LEVELING_DATA:0");
  6683. #endif
  6684. // SOFTWARE_POWER (M80, M81)
  6685. #if HAS_POWER_SWITCH
  6686. SERIAL_PROTOCOLLNPGM("Cap:SOFTWARE_POWER:1");
  6687. #else
  6688. SERIAL_PROTOCOLLNPGM("Cap:SOFTWARE_POWER:0");
  6689. #endif
  6690. // CASE LIGHTS (M355)
  6691. #if HAS_CASE_LIGHT
  6692. SERIAL_PROTOCOLLNPGM("Cap:TOGGLE_LIGHTS:1");
  6693. if (USEABLE_HARDWARE_PWM(CASE_LIGHT_PIN)) {
  6694. SERIAL_PROTOCOLLNPGM("Cap:CASE_LIGHT_BRIGHTNESS:1");
  6695. }
  6696. else
  6697. SERIAL_PROTOCOLLNPGM("Cap:CASE_LIGHT_BRIGHTNESS:0");
  6698. #else
  6699. SERIAL_PROTOCOLLNPGM("Cap:TOGGLE_LIGHTS:0");
  6700. SERIAL_PROTOCOLLNPGM("Cap:CASE_LIGHT_BRIGHTNESS:0");
  6701. #endif
  6702. // EMERGENCY_PARSER (M108, M112, M410)
  6703. #if ENABLED(EMERGENCY_PARSER)
  6704. SERIAL_PROTOCOLLNPGM("Cap:EMERGENCY_PARSER:1");
  6705. #else
  6706. SERIAL_PROTOCOLLNPGM("Cap:EMERGENCY_PARSER:0");
  6707. #endif
  6708. #endif // EXTENDED_CAPABILITIES_REPORT
  6709. }
  6710. /**
  6711. * M117: Set LCD Status Message
  6712. */
  6713. inline void gcode_M117() { lcd_setstatus(parser.string_arg); }
  6714. /**
  6715. * M118: Display a message in the host console.
  6716. *
  6717. * A Append '// ' for an action command, as in OctoPrint
  6718. * E Have the host 'echo:' the text
  6719. */
  6720. inline void gcode_M118() {
  6721. if (parser.boolval('E')) SERIAL_ECHO_START();
  6722. if (parser.boolval('A')) SERIAL_ECHOPGM("// ");
  6723. SERIAL_ECHOLN(parser.string_arg);
  6724. }
  6725. /**
  6726. * M119: Output endstop states to serial output
  6727. */
  6728. inline void gcode_M119() { endstops.M119(); }
  6729. /**
  6730. * M120: Enable endstops and set non-homing endstop state to "enabled"
  6731. */
  6732. inline void gcode_M120() { endstops.enable_globally(true); }
  6733. /**
  6734. * M121: Disable endstops and set non-homing endstop state to "disabled"
  6735. */
  6736. inline void gcode_M121() { endstops.enable_globally(false); }
  6737. #if ENABLED(PARK_HEAD_ON_PAUSE)
  6738. /**
  6739. * M125: Store current position and move to filament change position.
  6740. * Called on pause (by M25) to prevent material leaking onto the
  6741. * object. On resume (M24) the head will be moved back and the
  6742. * print will resume.
  6743. *
  6744. * If Marlin is compiled without SD Card support, M125 can be
  6745. * used directly to pause the print and move to park position,
  6746. * resuming with a button click or M108.
  6747. *
  6748. * L = override retract length
  6749. * X = override X
  6750. * Y = override Y
  6751. * Z = override Z raise
  6752. */
  6753. inline void gcode_M125() {
  6754. // Initial retract before move to filament change position
  6755. const float retract = parser.seen('L') ? parser.value_axis_units(E_AXIS) : 0
  6756. #if defined(PAUSE_PARK_RETRACT_LENGTH) && PAUSE_PARK_RETRACT_LENGTH > 0
  6757. - (PAUSE_PARK_RETRACT_LENGTH)
  6758. #endif
  6759. ;
  6760. // Lift Z axis
  6761. const float z_lift = parser.linearval('Z')
  6762. #if PAUSE_PARK_Z_ADD > 0
  6763. + PAUSE_PARK_Z_ADD
  6764. #endif
  6765. ;
  6766. // Move XY axes to filament change position or given position
  6767. const float x_pos = parser.linearval('X')
  6768. #ifdef PAUSE_PARK_X_POS
  6769. + PAUSE_PARK_X_POS
  6770. #endif
  6771. #if HOTENDS > 1 && DISABLED(DUAL_X_CARRIAGE)
  6772. + (active_extruder ? hotend_offset[X_AXIS][active_extruder] : 0)
  6773. #endif
  6774. ;
  6775. const float y_pos = parser.linearval('Y')
  6776. #ifdef PAUSE_PARK_Y_POS
  6777. + PAUSE_PARK_Y_POS
  6778. #endif
  6779. #if HOTENDS > 1 && DISABLED(DUAL_X_CARRIAGE)
  6780. + (active_extruder ? hotend_offset[Y_AXIS][active_extruder] : 0)
  6781. #endif
  6782. ;
  6783. const bool job_running = print_job_timer.isRunning();
  6784. if (pause_print(retract, z_lift, x_pos, y_pos)) {
  6785. #if DISABLED(SDSUPPORT)
  6786. // Wait for lcd click or M108
  6787. wait_for_filament_reload();
  6788. // Return to print position and continue
  6789. resume_print();
  6790. if (job_running) print_job_timer.start();
  6791. #endif
  6792. }
  6793. }
  6794. #endif // PARK_HEAD_ON_PAUSE
  6795. #if HAS_COLOR_LEDS
  6796. /**
  6797. * M150: Set Status LED Color - Use R-U-B-W for R-G-B-W
  6798. *
  6799. * Always sets all 3 or 4 components. If a component is left out, set to 0.
  6800. *
  6801. * Examples:
  6802. *
  6803. * M150 R255 ; Turn LED red
  6804. * M150 R255 U127 ; Turn LED orange (PWM only)
  6805. * M150 ; Turn LED off
  6806. * M150 R U B ; Turn LED white
  6807. * M150 W ; Turn LED white using a white LED
  6808. *
  6809. */
  6810. inline void gcode_M150() {
  6811. set_led_color(
  6812. parser.seen('R') ? (parser.has_value() ? parser.value_byte() : 255) : 0,
  6813. parser.seen('U') ? (parser.has_value() ? parser.value_byte() : 255) : 0,
  6814. parser.seen('B') ? (parser.has_value() ? parser.value_byte() : 255) : 0
  6815. #if ENABLED(RGBW_LED)
  6816. , parser.seen('W') ? (parser.has_value() ? parser.value_byte() : 255) : 0
  6817. #endif
  6818. );
  6819. }
  6820. #endif // HAS_COLOR_LEDS
  6821. /**
  6822. * M200: Set filament diameter and set E axis units to cubic units
  6823. *
  6824. * T<extruder> - Optional extruder number. Current extruder if omitted.
  6825. * D<linear> - Diameter of the filament. Use "D0" to switch back to linear units on the E axis.
  6826. */
  6827. inline void gcode_M200() {
  6828. if (get_target_extruder_from_command(200)) return;
  6829. if (parser.seen('D')) {
  6830. // setting any extruder filament size disables volumetric on the assumption that
  6831. // slicers either generate in extruder values as cubic mm or as as filament feeds
  6832. // for all extruders
  6833. volumetric_enabled = (parser.value_linear_units() != 0.0);
  6834. if (volumetric_enabled) {
  6835. filament_size[target_extruder] = parser.value_linear_units();
  6836. // make sure all extruders have some sane value for the filament size
  6837. for (uint8_t i = 0; i < COUNT(filament_size); i++)
  6838. if (! filament_size[i]) filament_size[i] = DEFAULT_NOMINAL_FILAMENT_DIA;
  6839. }
  6840. }
  6841. calculate_volumetric_multipliers();
  6842. }
  6843. /**
  6844. * M201: Set max acceleration in units/s^2 for print moves (M201 X1000 Y1000)
  6845. *
  6846. * With multiple extruders use T to specify which one.
  6847. */
  6848. inline void gcode_M201() {
  6849. GET_TARGET_EXTRUDER(201);
  6850. LOOP_XYZE(i) {
  6851. if (parser.seen(axis_codes[i])) {
  6852. const uint8_t a = i + (i == E_AXIS ? TARGET_EXTRUDER : 0);
  6853. planner.max_acceleration_mm_per_s2[a] = parser.value_axis_units((AxisEnum)a);
  6854. }
  6855. }
  6856. // 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)
  6857. planner.reset_acceleration_rates();
  6858. }
  6859. #if 0 // Not used for Sprinter/grbl gen6
  6860. inline void gcode_M202() {
  6861. LOOP_XYZE(i) {
  6862. if (parser.seen(axis_codes[i])) axis_travel_steps_per_sqr_second[i] = parser.value_axis_units((AxisEnum)i) * planner.axis_steps_per_mm[i];
  6863. }
  6864. }
  6865. #endif
  6866. /**
  6867. * M203: Set maximum feedrate that your machine can sustain (M203 X200 Y200 Z300 E10000) in units/sec
  6868. *
  6869. * With multiple extruders use T to specify which one.
  6870. */
  6871. inline void gcode_M203() {
  6872. GET_TARGET_EXTRUDER(203);
  6873. LOOP_XYZE(i)
  6874. if (parser.seen(axis_codes[i])) {
  6875. const uint8_t a = i + (i == E_AXIS ? TARGET_EXTRUDER : 0);
  6876. planner.max_feedrate_mm_s[a] = parser.value_axis_units((AxisEnum)a);
  6877. }
  6878. }
  6879. /**
  6880. * M204: Set Accelerations in units/sec^2 (M204 P1200 R3000 T3000)
  6881. *
  6882. * P = Printing moves
  6883. * R = Retract only (no X, Y, Z) moves
  6884. * T = Travel (non printing) moves
  6885. *
  6886. * Also sets minimum segment time in ms (B20000) to prevent buffer under-runs and M20 minimum feedrate
  6887. */
  6888. inline void gcode_M204() {
  6889. if (parser.seen('S')) { // Kept for legacy compatibility. Should NOT BE USED for new developments.
  6890. planner.travel_acceleration = planner.acceleration = parser.value_linear_units();
  6891. SERIAL_ECHOLNPAIR("Setting Print and Travel Acceleration: ", planner.acceleration);
  6892. }
  6893. if (parser.seen('P')) {
  6894. planner.acceleration = parser.value_linear_units();
  6895. SERIAL_ECHOLNPAIR("Setting Print Acceleration: ", planner.acceleration);
  6896. }
  6897. if (parser.seen('R')) {
  6898. planner.retract_acceleration = parser.value_linear_units();
  6899. SERIAL_ECHOLNPAIR("Setting Retract Acceleration: ", planner.retract_acceleration);
  6900. }
  6901. if (parser.seen('T')) {
  6902. planner.travel_acceleration = parser.value_linear_units();
  6903. SERIAL_ECHOLNPAIR("Setting Travel Acceleration: ", planner.travel_acceleration);
  6904. }
  6905. }
  6906. /**
  6907. * M205: Set Advanced Settings
  6908. *
  6909. * S = Min Feed Rate (units/s)
  6910. * T = Min Travel Feed Rate (units/s)
  6911. * B = Min Segment Time (µs)
  6912. * X = Max X Jerk (units/sec^2)
  6913. * Y = Max Y Jerk (units/sec^2)
  6914. * Z = Max Z Jerk (units/sec^2)
  6915. * E = Max E Jerk (units/sec^2)
  6916. */
  6917. inline void gcode_M205() {
  6918. if (parser.seen('S')) planner.min_feedrate_mm_s = parser.value_linear_units();
  6919. if (parser.seen('T')) planner.min_travel_feedrate_mm_s = parser.value_linear_units();
  6920. if (parser.seen('B')) planner.min_segment_time = parser.value_millis();
  6921. if (parser.seen('X')) planner.max_jerk[X_AXIS] = parser.value_linear_units();
  6922. if (parser.seen('Y')) planner.max_jerk[Y_AXIS] = parser.value_linear_units();
  6923. if (parser.seen('Z')) planner.max_jerk[Z_AXIS] = parser.value_linear_units();
  6924. if (parser.seen('E')) planner.max_jerk[E_AXIS] = parser.value_linear_units();
  6925. }
  6926. #if HAS_M206_COMMAND
  6927. /**
  6928. * M206: Set Additional Homing Offset (X Y Z). SCARA aliases T=X, P=Y
  6929. *
  6930. * *** @thinkyhead: I recommend deprecating M206 for SCARA in favor of M665.
  6931. * *** M206 for SCARA will remain enabled in 1.1.x for compatibility.
  6932. * *** In the next 1.2 release, it will simply be disabled by default.
  6933. */
  6934. inline void gcode_M206() {
  6935. LOOP_XYZ(i)
  6936. if (parser.seen(axis_codes[i]))
  6937. set_home_offset((AxisEnum)i, parser.value_linear_units());
  6938. #if ENABLED(MORGAN_SCARA)
  6939. if (parser.seen('T')) set_home_offset(A_AXIS, parser.value_linear_units()); // Theta
  6940. if (parser.seen('P')) set_home_offset(B_AXIS, parser.value_linear_units()); // Psi
  6941. #endif
  6942. SYNC_PLAN_POSITION_KINEMATIC();
  6943. report_current_position();
  6944. }
  6945. #endif // HAS_M206_COMMAND
  6946. #if ENABLED(DELTA)
  6947. /**
  6948. * M665: Set delta configurations
  6949. *
  6950. * H = delta height
  6951. * L = diagonal rod
  6952. * R = delta radius
  6953. * S = segments per second
  6954. * B = delta calibration radius
  6955. * X = Alpha (Tower 1) angle trim
  6956. * Y = Beta (Tower 2) angle trim
  6957. * Z = Rotate A and B by this angle
  6958. */
  6959. inline void gcode_M665() {
  6960. if (parser.seen('H')) {
  6961. home_offset[Z_AXIS] = parser.value_linear_units() - DELTA_HEIGHT;
  6962. update_software_endstops(Z_AXIS);
  6963. }
  6964. if (parser.seen('L')) delta_diagonal_rod = parser.value_linear_units();
  6965. if (parser.seen('R')) delta_radius = parser.value_linear_units();
  6966. if (parser.seen('S')) delta_segments_per_second = parser.value_float();
  6967. if (parser.seen('B')) delta_calibration_radius = parser.value_float();
  6968. if (parser.seen('X')) delta_tower_angle_trim[A_AXIS] = parser.value_float();
  6969. if (parser.seen('Y')) delta_tower_angle_trim[B_AXIS] = parser.value_float();
  6970. if (parser.seen('Z')) { // rotate all 3 axis for Z = 0
  6971. delta_tower_angle_trim[A_AXIS] -= parser.value_float();
  6972. delta_tower_angle_trim[B_AXIS] -= parser.value_float();
  6973. }
  6974. recalc_delta_settings(delta_radius, delta_diagonal_rod);
  6975. }
  6976. /**
  6977. * M666: Set delta endstop adjustment
  6978. */
  6979. inline void gcode_M666() {
  6980. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6981. if (DEBUGGING(LEVELING)) {
  6982. SERIAL_ECHOLNPGM(">>> gcode_M666");
  6983. }
  6984. #endif
  6985. LOOP_XYZ(i) {
  6986. if (parser.seen(axis_codes[i])) {
  6987. endstop_adj[i] = parser.value_linear_units();
  6988. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6989. if (DEBUGGING(LEVELING)) {
  6990. SERIAL_ECHOPAIR("endstop_adj[", axis_codes[i]);
  6991. SERIAL_ECHOLNPAIR("] = ", endstop_adj[i]);
  6992. }
  6993. #endif
  6994. }
  6995. }
  6996. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6997. if (DEBUGGING(LEVELING)) {
  6998. SERIAL_ECHOLNPGM("<<< gcode_M666");
  6999. }
  7000. #endif
  7001. // normalize endstops so all are <=0; set the residue to delta height
  7002. const float z_temp = MAX3(endstop_adj[A_AXIS], endstop_adj[B_AXIS], endstop_adj[C_AXIS]);
  7003. home_offset[Z_AXIS] -= z_temp;
  7004. LOOP_XYZ(i) endstop_adj[i] -= z_temp;
  7005. }
  7006. #elif IS_SCARA
  7007. /**
  7008. * M665: Set SCARA settings
  7009. *
  7010. * Parameters:
  7011. *
  7012. * S[segments-per-second] - Segments-per-second
  7013. * P[theta-psi-offset] - Theta-Psi offset, added to the shoulder (A/X) angle
  7014. * T[theta-offset] - Theta offset, added to the elbow (B/Y) angle
  7015. *
  7016. * A, P, and X are all aliases for the shoulder angle
  7017. * B, T, and Y are all aliases for the elbow angle
  7018. */
  7019. inline void gcode_M665() {
  7020. if (parser.seen('S')) delta_segments_per_second = parser.value_float();
  7021. const bool hasA = parser.seen('A'), hasP = parser.seen('P'), hasX = parser.seen('X');
  7022. const uint8_t sumAPX = hasA + hasP + hasX;
  7023. if (sumAPX == 1)
  7024. home_offset[A_AXIS] = parser.value_float();
  7025. else if (sumAPX > 1) {
  7026. SERIAL_ERROR_START();
  7027. SERIAL_ERRORLNPGM("Only one of A, P, or X is allowed.");
  7028. return;
  7029. }
  7030. const bool hasB = parser.seen('B'), hasT = parser.seen('T'), hasY = parser.seen('Y');
  7031. const uint8_t sumBTY = hasB + hasT + hasY;
  7032. if (sumBTY == 1)
  7033. home_offset[B_AXIS] = parser.value_float();
  7034. else if (sumBTY > 1) {
  7035. SERIAL_ERROR_START();
  7036. SERIAL_ERRORLNPGM("Only one of B, T, or Y is allowed.");
  7037. return;
  7038. }
  7039. }
  7040. #elif ENABLED(Z_DUAL_ENDSTOPS) // !DELTA && ENABLED(Z_DUAL_ENDSTOPS)
  7041. /**
  7042. * M666: For Z Dual Endstop setup, set z axis offset to the z2 axis.
  7043. */
  7044. inline void gcode_M666() {
  7045. if (parser.seen('Z')) z_endstop_adj = parser.value_linear_units();
  7046. SERIAL_ECHOLNPAIR("Z Endstop Adjustment set to (mm):", z_endstop_adj);
  7047. }
  7048. #endif // !DELTA && Z_DUAL_ENDSTOPS
  7049. #if ENABLED(FWRETRACT)
  7050. /**
  7051. * M207: Set firmware retraction values
  7052. *
  7053. * S[+units] retract_length
  7054. * W[+units] retract_length_swap (multi-extruder)
  7055. * F[units/min] retract_feedrate_mm_s
  7056. * Z[units] retract_zlift
  7057. */
  7058. inline void gcode_M207() {
  7059. if (parser.seen('S')) retract_length = parser.value_axis_units(E_AXIS);
  7060. if (parser.seen('F')) retract_feedrate_mm_s = MMM_TO_MMS(parser.value_axis_units(E_AXIS));
  7061. if (parser.seen('Z')) retract_zlift = parser.value_linear_units();
  7062. #if EXTRUDERS > 1
  7063. if (parser.seen('W')) retract_length_swap = parser.value_axis_units(E_AXIS);
  7064. #endif
  7065. }
  7066. /**
  7067. * M208: Set firmware un-retraction values
  7068. *
  7069. * S[+units] retract_recover_length (in addition to M207 S*)
  7070. * W[+units] retract_recover_length_swap (multi-extruder)
  7071. * F[units/min] retract_recover_feedrate_mm_s
  7072. */
  7073. inline void gcode_M208() {
  7074. if (parser.seen('S')) retract_recover_length = parser.value_axis_units(E_AXIS);
  7075. if (parser.seen('F')) retract_recover_feedrate_mm_s = MMM_TO_MMS(parser.value_axis_units(E_AXIS));
  7076. #if EXTRUDERS > 1
  7077. if (parser.seen('W')) retract_recover_length_swap = parser.value_axis_units(E_AXIS);
  7078. #endif
  7079. }
  7080. /**
  7081. * M209: Enable automatic retract (M209 S1)
  7082. * For slicers that don't support G10/11, reversed extrude-only
  7083. * moves will be classified as retraction.
  7084. */
  7085. inline void gcode_M209() {
  7086. if (parser.seen('S')) {
  7087. autoretract_enabled = parser.value_bool();
  7088. for (int i = 0; i < EXTRUDERS; i++) retracted[i] = false;
  7089. }
  7090. }
  7091. #endif // FWRETRACT
  7092. /**
  7093. * M211: Enable, Disable, and/or Report software endstops
  7094. *
  7095. * Usage: M211 S1 to enable, M211 S0 to disable, M211 alone for report
  7096. */
  7097. inline void gcode_M211() {
  7098. SERIAL_ECHO_START();
  7099. #if HAS_SOFTWARE_ENDSTOPS
  7100. if (parser.seen('S')) soft_endstops_enabled = parser.value_bool();
  7101. SERIAL_ECHOPGM(MSG_SOFT_ENDSTOPS);
  7102. serialprintPGM(soft_endstops_enabled ? PSTR(MSG_ON) : PSTR(MSG_OFF));
  7103. #else
  7104. SERIAL_ECHOPGM(MSG_SOFT_ENDSTOPS);
  7105. SERIAL_ECHOPGM(MSG_OFF);
  7106. #endif
  7107. SERIAL_ECHOPGM(MSG_SOFT_MIN);
  7108. SERIAL_ECHOPAIR( MSG_X, soft_endstop_min[X_AXIS]);
  7109. SERIAL_ECHOPAIR(" " MSG_Y, soft_endstop_min[Y_AXIS]);
  7110. SERIAL_ECHOPAIR(" " MSG_Z, soft_endstop_min[Z_AXIS]);
  7111. SERIAL_ECHOPGM(MSG_SOFT_MAX);
  7112. SERIAL_ECHOPAIR( MSG_X, soft_endstop_max[X_AXIS]);
  7113. SERIAL_ECHOPAIR(" " MSG_Y, soft_endstop_max[Y_AXIS]);
  7114. SERIAL_ECHOLNPAIR(" " MSG_Z, soft_endstop_max[Z_AXIS]);
  7115. }
  7116. #if HOTENDS > 1
  7117. /**
  7118. * M218 - set hotend offset (in linear units)
  7119. *
  7120. * T<tool>
  7121. * X<xoffset>
  7122. * Y<yoffset>
  7123. * Z<zoffset> - Available with DUAL_X_CARRIAGE and SWITCHING_NOZZLE
  7124. */
  7125. inline void gcode_M218() {
  7126. if (get_target_extruder_from_command(218) || target_extruder == 0) return;
  7127. if (parser.seenval('X')) hotend_offset[X_AXIS][target_extruder] = parser.value_linear_units();
  7128. if (parser.seenval('Y')) hotend_offset[Y_AXIS][target_extruder] = parser.value_linear_units();
  7129. #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(SWITCHING_NOZZLE)
  7130. if (parser.seenval('Z')) hotend_offset[Z_AXIS][target_extruder] = parser.value_linear_units();
  7131. #endif
  7132. SERIAL_ECHO_START();
  7133. SERIAL_ECHOPGM(MSG_HOTEND_OFFSET);
  7134. HOTEND_LOOP() {
  7135. SERIAL_CHAR(' ');
  7136. SERIAL_ECHO(hotend_offset[X_AXIS][e]);
  7137. SERIAL_CHAR(',');
  7138. SERIAL_ECHO(hotend_offset[Y_AXIS][e]);
  7139. #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(SWITCHING_NOZZLE)
  7140. SERIAL_CHAR(',');
  7141. SERIAL_ECHO(hotend_offset[Z_AXIS][e]);
  7142. #endif
  7143. }
  7144. SERIAL_EOL();
  7145. }
  7146. #endif // HOTENDS > 1
  7147. /**
  7148. * M220: Set speed percentage factor, aka "Feed Rate" (M220 S95)
  7149. */
  7150. inline void gcode_M220() {
  7151. if (parser.seenval('S')) feedrate_percentage = parser.value_int();
  7152. }
  7153. /**
  7154. * M221: Set extrusion percentage (M221 T0 S95)
  7155. */
  7156. inline void gcode_M221() {
  7157. if (get_target_extruder_from_command(221)) return;
  7158. if (parser.seenval('S'))
  7159. flow_percentage[target_extruder] = parser.value_int();
  7160. }
  7161. /**
  7162. * M226: Wait until the specified pin reaches the state required (M226 P<pin> S<state>)
  7163. */
  7164. inline void gcode_M226() {
  7165. if (parser.seen('P')) {
  7166. const int pin_number = parser.value_int(),
  7167. pin_state = parser.intval('S', -1); // required pin state - default is inverted
  7168. if (WITHIN(pin_state, -1, 1) && pin_number > -1 && !pin_is_protected(pin_number)) {
  7169. int target = LOW;
  7170. stepper.synchronize();
  7171. pinMode(pin_number, INPUT);
  7172. switch (pin_state) {
  7173. case 1:
  7174. target = HIGH;
  7175. break;
  7176. case 0:
  7177. target = LOW;
  7178. break;
  7179. case -1:
  7180. target = !digitalRead(pin_number);
  7181. break;
  7182. }
  7183. while (digitalRead(pin_number) != target) idle();
  7184. } // pin_state -1 0 1 && pin_number > -1
  7185. } // parser.seen('P')
  7186. }
  7187. #if ENABLED(EXPERIMENTAL_I2CBUS)
  7188. /**
  7189. * M260: Send data to a I2C slave device
  7190. *
  7191. * This is a PoC, the formating and arguments for the GCODE will
  7192. * change to be more compatible, the current proposal is:
  7193. *
  7194. * M260 A<slave device address base 10> ; Sets the I2C slave address the data will be sent to
  7195. *
  7196. * M260 B<byte-1 value in base 10>
  7197. * M260 B<byte-2 value in base 10>
  7198. * M260 B<byte-3 value in base 10>
  7199. *
  7200. * M260 S1 ; Send the buffered data and reset the buffer
  7201. * M260 R1 ; Reset the buffer without sending data
  7202. *
  7203. */
  7204. inline void gcode_M260() {
  7205. // Set the target address
  7206. if (parser.seen('A')) i2c.address(parser.value_byte());
  7207. // Add a new byte to the buffer
  7208. if (parser.seen('B')) i2c.addbyte(parser.value_byte());
  7209. // Flush the buffer to the bus
  7210. if (parser.seen('S')) i2c.send();
  7211. // Reset and rewind the buffer
  7212. else if (parser.seen('R')) i2c.reset();
  7213. }
  7214. /**
  7215. * M261: Request X bytes from I2C slave device
  7216. *
  7217. * Usage: M261 A<slave device address base 10> B<number of bytes>
  7218. */
  7219. inline void gcode_M261() {
  7220. if (parser.seen('A')) i2c.address(parser.value_byte());
  7221. uint8_t bytes = parser.byteval('B', 1);
  7222. if (i2c.addr && bytes && bytes <= TWIBUS_BUFFER_SIZE) {
  7223. i2c.relay(bytes);
  7224. }
  7225. else {
  7226. SERIAL_ERROR_START();
  7227. SERIAL_ERRORLN("Bad i2c request");
  7228. }
  7229. }
  7230. #endif // EXPERIMENTAL_I2CBUS
  7231. #if HAS_SERVOS
  7232. /**
  7233. * M280: Get or set servo position. P<index> [S<angle>]
  7234. */
  7235. inline void gcode_M280() {
  7236. if (!parser.seen('P')) return;
  7237. const int servo_index = parser.value_int();
  7238. if (WITHIN(servo_index, 0, NUM_SERVOS - 1)) {
  7239. if (parser.seen('S'))
  7240. MOVE_SERVO(servo_index, parser.value_int());
  7241. else {
  7242. SERIAL_ECHO_START();
  7243. SERIAL_ECHOPAIR(" Servo ", servo_index);
  7244. SERIAL_ECHOLNPAIR(": ", servo[servo_index].read());
  7245. }
  7246. }
  7247. else {
  7248. SERIAL_ERROR_START();
  7249. SERIAL_ECHOPAIR("Servo ", servo_index);
  7250. SERIAL_ECHOLNPGM(" out of range");
  7251. }
  7252. }
  7253. #endif // HAS_SERVOS
  7254. #if HAS_BUZZER
  7255. /**
  7256. * M300: Play beep sound S<frequency Hz> P<duration ms>
  7257. */
  7258. inline void gcode_M300() {
  7259. uint16_t const frequency = parser.ushortval('S', 260);
  7260. uint16_t duration = parser.ushortval('P', 1000);
  7261. // Limits the tone duration to 0-5 seconds.
  7262. NOMORE(duration, 5000);
  7263. BUZZ(duration, frequency);
  7264. }
  7265. #endif // HAS_BUZZER
  7266. #if ENABLED(PIDTEMP)
  7267. /**
  7268. * M301: Set PID parameters P I D (and optionally C, L)
  7269. *
  7270. * P[float] Kp term
  7271. * I[float] Ki term (unscaled)
  7272. * D[float] Kd term (unscaled)
  7273. *
  7274. * With PID_EXTRUSION_SCALING:
  7275. *
  7276. * C[float] Kc term
  7277. * L[float] LPQ length
  7278. */
  7279. inline void gcode_M301() {
  7280. // multi-extruder PID patch: M301 updates or prints a single extruder's PID values
  7281. // default behaviour (omitting E parameter) is to update for extruder 0 only
  7282. const uint8_t e = parser.byteval('E'); // extruder being updated
  7283. if (e < HOTENDS) { // catch bad input value
  7284. if (parser.seen('P')) PID_PARAM(Kp, e) = parser.value_float();
  7285. if (parser.seen('I')) PID_PARAM(Ki, e) = scalePID_i(parser.value_float());
  7286. if (parser.seen('D')) PID_PARAM(Kd, e) = scalePID_d(parser.value_float());
  7287. #if ENABLED(PID_EXTRUSION_SCALING)
  7288. if (parser.seen('C')) PID_PARAM(Kc, e) = parser.value_float();
  7289. if (parser.seen('L')) lpq_len = parser.value_float();
  7290. NOMORE(lpq_len, LPQ_MAX_LEN);
  7291. #endif
  7292. thermalManager.updatePID();
  7293. SERIAL_ECHO_START();
  7294. #if ENABLED(PID_PARAMS_PER_HOTEND)
  7295. SERIAL_ECHOPAIR(" e:", e); // specify extruder in serial output
  7296. #endif // PID_PARAMS_PER_HOTEND
  7297. SERIAL_ECHOPAIR(" p:", PID_PARAM(Kp, e));
  7298. SERIAL_ECHOPAIR(" i:", unscalePID_i(PID_PARAM(Ki, e)));
  7299. SERIAL_ECHOPAIR(" d:", unscalePID_d(PID_PARAM(Kd, e)));
  7300. #if ENABLED(PID_EXTRUSION_SCALING)
  7301. //Kc does not have scaling applied above, or in resetting defaults
  7302. SERIAL_ECHOPAIR(" c:", PID_PARAM(Kc, e));
  7303. #endif
  7304. SERIAL_EOL();
  7305. }
  7306. else {
  7307. SERIAL_ERROR_START();
  7308. SERIAL_ERRORLN(MSG_INVALID_EXTRUDER);
  7309. }
  7310. }
  7311. #endif // PIDTEMP
  7312. #if ENABLED(PIDTEMPBED)
  7313. inline void gcode_M304() {
  7314. if (parser.seen('P')) thermalManager.bedKp = parser.value_float();
  7315. if (parser.seen('I')) thermalManager.bedKi = scalePID_i(parser.value_float());
  7316. if (parser.seen('D')) thermalManager.bedKd = scalePID_d(parser.value_float());
  7317. thermalManager.updatePID();
  7318. SERIAL_ECHO_START();
  7319. SERIAL_ECHOPAIR(" p:", thermalManager.bedKp);
  7320. SERIAL_ECHOPAIR(" i:", unscalePID_i(thermalManager.bedKi));
  7321. SERIAL_ECHOLNPAIR(" d:", unscalePID_d(thermalManager.bedKd));
  7322. }
  7323. #endif // PIDTEMPBED
  7324. #if defined(CHDK) || HAS_PHOTOGRAPH
  7325. /**
  7326. * M240: Trigger a camera by emulating a Canon RC-1
  7327. * See http://www.doc-diy.net/photo/rc-1_hacked/
  7328. */
  7329. inline void gcode_M240() {
  7330. #ifdef CHDK
  7331. OUT_WRITE(CHDK, HIGH);
  7332. chdkHigh = millis();
  7333. chdkActive = true;
  7334. #elif HAS_PHOTOGRAPH
  7335. const uint8_t NUM_PULSES = 16;
  7336. const float PULSE_LENGTH = 0.01524;
  7337. for (int i = 0; i < NUM_PULSES; i++) {
  7338. WRITE(PHOTOGRAPH_PIN, HIGH);
  7339. _delay_ms(PULSE_LENGTH);
  7340. WRITE(PHOTOGRAPH_PIN, LOW);
  7341. _delay_ms(PULSE_LENGTH);
  7342. }
  7343. delay(7.33);
  7344. for (int i = 0; i < NUM_PULSES; i++) {
  7345. WRITE(PHOTOGRAPH_PIN, HIGH);
  7346. _delay_ms(PULSE_LENGTH);
  7347. WRITE(PHOTOGRAPH_PIN, LOW);
  7348. _delay_ms(PULSE_LENGTH);
  7349. }
  7350. #endif // !CHDK && HAS_PHOTOGRAPH
  7351. }
  7352. #endif // CHDK || PHOTOGRAPH_PIN
  7353. #if HAS_LCD_CONTRAST
  7354. /**
  7355. * M250: Read and optionally set the LCD contrast
  7356. */
  7357. inline void gcode_M250() {
  7358. if (parser.seen('C')) set_lcd_contrast(parser.value_int());
  7359. SERIAL_PROTOCOLPGM("lcd contrast value: ");
  7360. SERIAL_PROTOCOL(lcd_contrast);
  7361. SERIAL_EOL();
  7362. }
  7363. #endif // HAS_LCD_CONTRAST
  7364. #if ENABLED(PREVENT_COLD_EXTRUSION)
  7365. /**
  7366. * M302: Allow cold extrudes, or set the minimum extrude temperature
  7367. *
  7368. * S<temperature> sets the minimum extrude temperature
  7369. * P<bool> enables (1) or disables (0) cold extrusion
  7370. *
  7371. * Examples:
  7372. *
  7373. * M302 ; report current cold extrusion state
  7374. * M302 P0 ; enable cold extrusion checking
  7375. * M302 P1 ; disables cold extrusion checking
  7376. * M302 S0 ; always allow extrusion (disables checking)
  7377. * M302 S170 ; only allow extrusion above 170
  7378. * M302 S170 P1 ; set min extrude temp to 170 but leave disabled
  7379. */
  7380. inline void gcode_M302() {
  7381. const bool seen_S = parser.seen('S');
  7382. if (seen_S) {
  7383. thermalManager.extrude_min_temp = parser.value_celsius();
  7384. thermalManager.allow_cold_extrude = (thermalManager.extrude_min_temp == 0);
  7385. }
  7386. if (parser.seen('P'))
  7387. thermalManager.allow_cold_extrude = (thermalManager.extrude_min_temp == 0) || parser.value_bool();
  7388. else if (!seen_S) {
  7389. // Report current state
  7390. SERIAL_ECHO_START();
  7391. SERIAL_ECHOPAIR("Cold extrudes are ", (thermalManager.allow_cold_extrude ? "en" : "dis"));
  7392. SERIAL_ECHOPAIR("abled (min temp ", thermalManager.extrude_min_temp);
  7393. SERIAL_ECHOLNPGM("C)");
  7394. }
  7395. }
  7396. #endif // PREVENT_COLD_EXTRUSION
  7397. /**
  7398. * M303: PID relay autotune
  7399. *
  7400. * S<temperature> sets the target temperature. (default 150C)
  7401. * E<extruder> (-1 for the bed) (default 0)
  7402. * C<cycles>
  7403. * U<bool> with a non-zero value will apply the result to current settings
  7404. */
  7405. inline void gcode_M303() {
  7406. #if HAS_PID_HEATING
  7407. const int e = parser.intval('E'), c = parser.intval('C', 5);
  7408. const bool u = parser.boolval('U');
  7409. int16_t temp = parser.celsiusval('S', e < 0 ? 70 : 150);
  7410. if (WITHIN(e, 0, HOTENDS - 1))
  7411. target_extruder = e;
  7412. KEEPALIVE_STATE(NOT_BUSY); // don't send "busy: processing" messages during autotune output
  7413. thermalManager.PID_autotune(temp, e, c, u);
  7414. KEEPALIVE_STATE(IN_HANDLER);
  7415. #else
  7416. SERIAL_ERROR_START();
  7417. SERIAL_ERRORLNPGM(MSG_ERR_M303_DISABLED);
  7418. #endif
  7419. }
  7420. #if ENABLED(MORGAN_SCARA)
  7421. bool SCARA_move_to_cal(uint8_t delta_a, uint8_t delta_b) {
  7422. if (IsRunning()) {
  7423. forward_kinematics_SCARA(delta_a, delta_b);
  7424. destination[X_AXIS] = LOGICAL_X_POSITION(cartes[X_AXIS]);
  7425. destination[Y_AXIS] = LOGICAL_Y_POSITION(cartes[Y_AXIS]);
  7426. destination[Z_AXIS] = current_position[Z_AXIS];
  7427. prepare_move_to_destination();
  7428. return true;
  7429. }
  7430. return false;
  7431. }
  7432. /**
  7433. * M360: SCARA calibration: Move to cal-position ThetaA (0 deg calibration)
  7434. */
  7435. inline bool gcode_M360() {
  7436. SERIAL_ECHOLNPGM(" Cal: Theta 0");
  7437. return SCARA_move_to_cal(0, 120);
  7438. }
  7439. /**
  7440. * M361: SCARA calibration: Move to cal-position ThetaB (90 deg calibration - steps per degree)
  7441. */
  7442. inline bool gcode_M361() {
  7443. SERIAL_ECHOLNPGM(" Cal: Theta 90");
  7444. return SCARA_move_to_cal(90, 130);
  7445. }
  7446. /**
  7447. * M362: SCARA calibration: Move to cal-position PsiA (0 deg calibration)
  7448. */
  7449. inline bool gcode_M362() {
  7450. SERIAL_ECHOLNPGM(" Cal: Psi 0");
  7451. return SCARA_move_to_cal(60, 180);
  7452. }
  7453. /**
  7454. * M363: SCARA calibration: Move to cal-position PsiB (90 deg calibration - steps per degree)
  7455. */
  7456. inline bool gcode_M363() {
  7457. SERIAL_ECHOLNPGM(" Cal: Psi 90");
  7458. return SCARA_move_to_cal(50, 90);
  7459. }
  7460. /**
  7461. * M364: SCARA calibration: Move to cal-position PsiC (90 deg to Theta calibration position)
  7462. */
  7463. inline bool gcode_M364() {
  7464. SERIAL_ECHOLNPGM(" Cal: Theta-Psi 90");
  7465. return SCARA_move_to_cal(45, 135);
  7466. }
  7467. #endif // SCARA
  7468. #if ENABLED(EXT_SOLENOID)
  7469. void enable_solenoid(const uint8_t num) {
  7470. switch (num) {
  7471. case 0:
  7472. OUT_WRITE(SOL0_PIN, HIGH);
  7473. break;
  7474. #if HAS_SOLENOID_1 && EXTRUDERS > 1
  7475. case 1:
  7476. OUT_WRITE(SOL1_PIN, HIGH);
  7477. break;
  7478. #endif
  7479. #if HAS_SOLENOID_2 && EXTRUDERS > 2
  7480. case 2:
  7481. OUT_WRITE(SOL2_PIN, HIGH);
  7482. break;
  7483. #endif
  7484. #if HAS_SOLENOID_3 && EXTRUDERS > 3
  7485. case 3:
  7486. OUT_WRITE(SOL3_PIN, HIGH);
  7487. break;
  7488. #endif
  7489. #if HAS_SOLENOID_4 && EXTRUDERS > 4
  7490. case 4:
  7491. OUT_WRITE(SOL4_PIN, HIGH);
  7492. break;
  7493. #endif
  7494. default:
  7495. SERIAL_ECHO_START();
  7496. SERIAL_ECHOLNPGM(MSG_INVALID_SOLENOID);
  7497. break;
  7498. }
  7499. }
  7500. void enable_solenoid_on_active_extruder() { enable_solenoid(active_extruder); }
  7501. void disable_all_solenoids() {
  7502. OUT_WRITE(SOL0_PIN, LOW);
  7503. #if HAS_SOLENOID_1 && EXTRUDERS > 1
  7504. OUT_WRITE(SOL1_PIN, LOW);
  7505. #endif
  7506. #if HAS_SOLENOID_2 && EXTRUDERS > 2
  7507. OUT_WRITE(SOL2_PIN, LOW);
  7508. #endif
  7509. #if HAS_SOLENOID_3 && EXTRUDERS > 3
  7510. OUT_WRITE(SOL3_PIN, LOW);
  7511. #endif
  7512. #if HAS_SOLENOID_4 && EXTRUDERS > 4
  7513. OUT_WRITE(SOL4_PIN, LOW);
  7514. #endif
  7515. }
  7516. /**
  7517. * M380: Enable solenoid on the active extruder
  7518. */
  7519. inline void gcode_M380() { enable_solenoid_on_active_extruder(); }
  7520. /**
  7521. * M381: Disable all solenoids
  7522. */
  7523. inline void gcode_M381() { disable_all_solenoids(); }
  7524. #endif // EXT_SOLENOID
  7525. /**
  7526. * M400: Finish all moves
  7527. */
  7528. inline void gcode_M400() { stepper.synchronize(); }
  7529. #if HAS_BED_PROBE
  7530. /**
  7531. * M401: Engage Z Servo endstop if available
  7532. */
  7533. inline void gcode_M401() { DEPLOY_PROBE(); }
  7534. /**
  7535. * M402: Retract Z Servo endstop if enabled
  7536. */
  7537. inline void gcode_M402() { STOW_PROBE(); }
  7538. #endif // HAS_BED_PROBE
  7539. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  7540. /**
  7541. * M404: Display or set (in current units) the nominal filament width (3mm, 1.75mm ) W<3.0>
  7542. */
  7543. inline void gcode_M404() {
  7544. if (parser.seen('W')) {
  7545. filament_width_nominal = parser.value_linear_units();
  7546. }
  7547. else {
  7548. SERIAL_PROTOCOLPGM("Filament dia (nominal mm):");
  7549. SERIAL_PROTOCOLLN(filament_width_nominal);
  7550. }
  7551. }
  7552. /**
  7553. * M405: Turn on filament sensor for control
  7554. */
  7555. inline void gcode_M405() {
  7556. // This is technically a linear measurement, but since it's quantized to centimeters and is a different
  7557. // unit than everything else, it uses parser.value_byte() instead of parser.value_linear_units().
  7558. if (parser.seen('D')) {
  7559. meas_delay_cm = parser.value_byte();
  7560. NOMORE(meas_delay_cm, MAX_MEASUREMENT_DELAY);
  7561. }
  7562. if (filwidth_delay_index[1] == -1) { // Initialize the ring buffer if not done since startup
  7563. const uint8_t temp_ratio = thermalManager.widthFil_to_size_ratio() - 100; // -100 to scale within a signed byte
  7564. for (uint8_t i = 0; i < COUNT(measurement_delay); ++i)
  7565. measurement_delay[i] = temp_ratio;
  7566. filwidth_delay_index[0] = filwidth_delay_index[1] = 0;
  7567. }
  7568. filament_sensor = true;
  7569. //SERIAL_PROTOCOLPGM("Filament dia (measured mm):");
  7570. //SERIAL_PROTOCOL(filament_width_meas);
  7571. //SERIAL_PROTOCOLPGM("Extrusion ratio(%):");
  7572. //SERIAL_PROTOCOL(flow_percentage[active_extruder]);
  7573. }
  7574. /**
  7575. * M406: Turn off filament sensor for control
  7576. */
  7577. inline void gcode_M406() { filament_sensor = false; }
  7578. /**
  7579. * M407: Get measured filament diameter on serial output
  7580. */
  7581. inline void gcode_M407() {
  7582. SERIAL_PROTOCOLPGM("Filament dia (measured mm):");
  7583. SERIAL_PROTOCOLLN(filament_width_meas);
  7584. }
  7585. #endif // FILAMENT_WIDTH_SENSOR
  7586. void quickstop_stepper() {
  7587. stepper.quick_stop();
  7588. stepper.synchronize();
  7589. set_current_from_steppers_for_axis(ALL_AXES);
  7590. SYNC_PLAN_POSITION_KINEMATIC();
  7591. }
  7592. #if HAS_LEVELING
  7593. /**
  7594. * M420: Enable/Disable Bed Leveling and/or set the Z fade height.
  7595. *
  7596. * S[bool] Turns leveling on or off
  7597. * Z[height] Sets the Z fade height (0 or none to disable)
  7598. * V[bool] Verbose - Print the leveling grid
  7599. *
  7600. * With AUTO_BED_LEVELING_UBL only:
  7601. *
  7602. * L[index] Load UBL mesh from index (0 is default)
  7603. */
  7604. inline void gcode_M420() {
  7605. #if ENABLED(AUTO_BED_LEVELING_UBL)
  7606. // L to load a mesh from the EEPROM
  7607. if (parser.seen('L')) {
  7608. #if ENABLED(EEPROM_SETTINGS)
  7609. const int8_t storage_slot = parser.has_value() ? parser.value_int() : ubl.state.storage_slot;
  7610. const int16_t a = settings.calc_num_meshes();
  7611. if (!a) {
  7612. SERIAL_PROTOCOLLNPGM("?EEPROM storage not available.");
  7613. return;
  7614. }
  7615. if (!WITHIN(storage_slot, 0, a - 1)) {
  7616. SERIAL_PROTOCOLLNPGM("?Invalid storage slot.");
  7617. SERIAL_PROTOCOLLNPAIR("?Use 0 to ", a - 1);
  7618. return;
  7619. }
  7620. settings.load_mesh(storage_slot);
  7621. ubl.state.storage_slot = storage_slot;
  7622. #else
  7623. SERIAL_PROTOCOLLNPGM("?EEPROM storage not available.");
  7624. return;
  7625. #endif
  7626. }
  7627. // L to load a mesh from the EEPROM
  7628. if (parser.seen('L') || parser.seen('V')) {
  7629. ubl.display_map(0); // Currently only supports one map type
  7630. SERIAL_ECHOLNPAIR("UBL_MESH_VALID = ", UBL_MESH_VALID);
  7631. SERIAL_ECHOLNPAIR("ubl.state.storage_slot = ", ubl.state.storage_slot);
  7632. }
  7633. #endif // AUTO_BED_LEVELING_UBL
  7634. // V to print the matrix or mesh
  7635. if (parser.seen('V')) {
  7636. #if ABL_PLANAR
  7637. planner.bed_level_matrix.debug(PSTR("Bed Level Correction Matrix:"));
  7638. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  7639. if (leveling_is_valid()) {
  7640. print_bilinear_leveling_grid();
  7641. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  7642. bed_level_virt_print();
  7643. #endif
  7644. }
  7645. #elif ENABLED(MESH_BED_LEVELING)
  7646. if (leveling_is_valid()) {
  7647. SERIAL_ECHOLNPGM("Mesh Bed Level data:");
  7648. mbl_mesh_report();
  7649. }
  7650. #endif
  7651. }
  7652. const bool to_enable = parser.boolval('S');
  7653. if (parser.seen('S'))
  7654. set_bed_leveling_enabled(to_enable);
  7655. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  7656. if (parser.seen('Z')) set_z_fade_height(parser.value_linear_units());
  7657. #endif
  7658. const bool new_status = leveling_is_active();
  7659. if (to_enable && !new_status) {
  7660. SERIAL_ERROR_START();
  7661. SERIAL_ERRORLNPGM(MSG_ERR_M420_FAILED);
  7662. }
  7663. SERIAL_ECHO_START();
  7664. SERIAL_ECHOLNPAIR("Bed Leveling ", new_status ? MSG_ON : MSG_OFF);
  7665. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  7666. SERIAL_ECHO_START();
  7667. SERIAL_ECHOPGM("Fade Height ");
  7668. if (planner.z_fade_height > 0.0)
  7669. SERIAL_ECHOLN(planner.z_fade_height);
  7670. else
  7671. SERIAL_ECHOLNPGM(MSG_OFF);
  7672. #endif
  7673. }
  7674. #endif
  7675. #if ENABLED(MESH_BED_LEVELING)
  7676. /**
  7677. * M421: Set a single Mesh Bed Leveling Z coordinate
  7678. *
  7679. * Usage:
  7680. * M421 X<linear> Y<linear> Z<linear>
  7681. * M421 X<linear> Y<linear> Q<offset>
  7682. * M421 I<xindex> J<yindex> Z<linear>
  7683. * M421 I<xindex> J<yindex> Q<offset>
  7684. */
  7685. inline void gcode_M421() {
  7686. const bool hasX = parser.seen('X'), hasI = parser.seen('I');
  7687. const int8_t ix = hasI ? parser.value_int() : hasX ? mbl.probe_index_x(RAW_X_POSITION(parser.value_linear_units())) : -1;
  7688. const bool hasY = parser.seen('Y'), hasJ = parser.seen('J');
  7689. const int8_t iy = hasJ ? parser.value_int() : hasY ? mbl.probe_index_y(RAW_Y_POSITION(parser.value_linear_units())) : -1;
  7690. const bool hasZ = parser.seen('Z'), hasQ = !hasZ && parser.seen('Q');
  7691. if (int(hasI && hasJ) + int(hasX && hasY) != 1 || !(hasZ || hasQ)) {
  7692. SERIAL_ERROR_START();
  7693. SERIAL_ERRORLNPGM(MSG_ERR_M421_PARAMETERS);
  7694. }
  7695. else if (ix < 0 || iy < 0) {
  7696. SERIAL_ERROR_START();
  7697. SERIAL_ERRORLNPGM(MSG_ERR_MESH_XY);
  7698. }
  7699. else
  7700. mbl.set_z(ix, iy, parser.value_linear_units() + (hasQ ? mbl.z_values[ix][iy] : 0));
  7701. }
  7702. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  7703. /**
  7704. * M421: Set a single Mesh Bed Leveling Z coordinate
  7705. *
  7706. * Usage:
  7707. * M421 I<xindex> J<yindex> Z<linear>
  7708. * M421 I<xindex> J<yindex> Q<offset>
  7709. */
  7710. inline void gcode_M421() {
  7711. int8_t ix = parser.intval('I', -1), iy = parser.intval('J', -1);
  7712. const bool hasI = ix >= 0,
  7713. hasJ = iy >= 0,
  7714. hasZ = parser.seen('Z'),
  7715. hasQ = !hasZ && parser.seen('Q');
  7716. if (!hasI || !hasJ || !(hasZ || hasQ)) {
  7717. SERIAL_ERROR_START();
  7718. SERIAL_ERRORLNPGM(MSG_ERR_M421_PARAMETERS);
  7719. }
  7720. else if (!WITHIN(ix, 0, GRID_MAX_POINTS_X - 1) || !WITHIN(iy, 0, GRID_MAX_POINTS_Y - 1)) {
  7721. SERIAL_ERROR_START();
  7722. SERIAL_ERRORLNPGM(MSG_ERR_MESH_XY);
  7723. }
  7724. else {
  7725. z_values[ix][iy] = parser.value_linear_units() + (hasQ ? z_values[ix][iy] : 0);
  7726. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  7727. bed_level_virt_interpolate();
  7728. #endif
  7729. }
  7730. }
  7731. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  7732. /**
  7733. * M421: Set a single Mesh Bed Leveling Z coordinate
  7734. *
  7735. * Usage:
  7736. * M421 I<xindex> J<yindex> Z<linear>
  7737. * M421 I<xindex> J<yindex> Q<offset>
  7738. * M421 C Z<linear>
  7739. * M421 C Q<offset>
  7740. */
  7741. inline void gcode_M421() {
  7742. int8_t ix = parser.intval('I', -1), iy = parser.intval('J', -1);
  7743. const bool hasI = ix >= 0,
  7744. hasJ = iy >= 0,
  7745. hasC = parser.seen('C'),
  7746. hasZ = parser.seen('Z'),
  7747. hasQ = !hasZ && parser.seen('Q');
  7748. if (hasC) {
  7749. const mesh_index_pair location = ubl.find_closest_mesh_point_of_type(REAL, current_position[X_AXIS], current_position[Y_AXIS], USE_NOZZLE_AS_REFERENCE, NULL, false);
  7750. ix = location.x_index;
  7751. iy = location.y_index;
  7752. }
  7753. if (int(hasC) + int(hasI && hasJ) != 1 || !(hasZ || hasQ)) {
  7754. SERIAL_ERROR_START();
  7755. SERIAL_ERRORLNPGM(MSG_ERR_M421_PARAMETERS);
  7756. }
  7757. else if (!WITHIN(ix, 0, GRID_MAX_POINTS_X - 1) || !WITHIN(iy, 0, GRID_MAX_POINTS_Y - 1)) {
  7758. SERIAL_ERROR_START();
  7759. SERIAL_ERRORLNPGM(MSG_ERR_MESH_XY);
  7760. }
  7761. else
  7762. ubl.z_values[ix][iy] = parser.value_linear_units() + (hasQ ? ubl.z_values[ix][iy] : 0);
  7763. }
  7764. #endif // AUTO_BED_LEVELING_UBL
  7765. #if HAS_M206_COMMAND
  7766. /**
  7767. * M428: Set home_offset based on the distance between the
  7768. * current_position and the nearest "reference point."
  7769. * If an axis is past center its endstop position
  7770. * is the reference-point. Otherwise it uses 0. This allows
  7771. * the Z offset to be set near the bed when using a max endstop.
  7772. *
  7773. * M428 can't be used more than 2cm away from 0 or an endstop.
  7774. *
  7775. * Use M206 to set these values directly.
  7776. */
  7777. inline void gcode_M428() {
  7778. bool err = false;
  7779. LOOP_XYZ(i) {
  7780. if (axis_homed[i]) {
  7781. const float base = (current_position[i] > (soft_endstop_min[i] + soft_endstop_max[i]) * 0.5) ? base_home_pos((AxisEnum)i) : 0,
  7782. diff = base - RAW_POSITION(current_position[i], i);
  7783. if (WITHIN(diff, -20, 20)) {
  7784. set_home_offset((AxisEnum)i, diff);
  7785. }
  7786. else {
  7787. SERIAL_ERROR_START();
  7788. SERIAL_ERRORLNPGM(MSG_ERR_M428_TOO_FAR);
  7789. LCD_ALERTMESSAGEPGM("Err: Too far!");
  7790. BUZZ(200, 40);
  7791. err = true;
  7792. break;
  7793. }
  7794. }
  7795. }
  7796. if (!err) {
  7797. SYNC_PLAN_POSITION_KINEMATIC();
  7798. report_current_position();
  7799. LCD_MESSAGEPGM(MSG_HOME_OFFSETS_APPLIED);
  7800. BUZZ(100, 659);
  7801. BUZZ(100, 698);
  7802. }
  7803. }
  7804. #endif // HAS_M206_COMMAND
  7805. /**
  7806. * M500: Store settings in EEPROM
  7807. */
  7808. inline void gcode_M500() {
  7809. (void)settings.save();
  7810. }
  7811. /**
  7812. * M501: Read settings from EEPROM
  7813. */
  7814. inline void gcode_M501() {
  7815. (void)settings.load();
  7816. }
  7817. /**
  7818. * M502: Revert to default settings
  7819. */
  7820. inline void gcode_M502() {
  7821. (void)settings.reset();
  7822. }
  7823. #if DISABLED(DISABLE_M503)
  7824. /**
  7825. * M503: print settings currently in memory
  7826. */
  7827. inline void gcode_M503() {
  7828. (void)settings.report(!parser.boolval('S', true));
  7829. }
  7830. #endif
  7831. #if ENABLED(ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  7832. /**
  7833. * M540: Set whether SD card print should abort on endstop hit (M540 S<0|1>)
  7834. */
  7835. inline void gcode_M540() {
  7836. if (parser.seen('S')) stepper.abort_on_endstop_hit = parser.value_bool();
  7837. }
  7838. #endif // ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED
  7839. #if HAS_BED_PROBE
  7840. void refresh_zprobe_zoffset(const bool no_babystep/*=false*/) {
  7841. static float last_zoffset = NAN;
  7842. if (!isnan(last_zoffset)) {
  7843. #if ENABLED(AUTO_BED_LEVELING_BILINEAR) || ENABLED(BABYSTEP_ZPROBE_OFFSET) || ENABLED(DELTA)
  7844. const float diff = zprobe_zoffset - last_zoffset;
  7845. #endif
  7846. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  7847. // Correct bilinear grid for new probe offset
  7848. if (diff) {
  7849. for (uint8_t x = 0; x < GRID_MAX_POINTS_X; x++)
  7850. for (uint8_t y = 0; y < GRID_MAX_POINTS_Y; y++)
  7851. z_values[x][y] -= diff;
  7852. }
  7853. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  7854. bed_level_virt_interpolate();
  7855. #endif
  7856. #endif
  7857. #if ENABLED(BABYSTEP_ZPROBE_OFFSET)
  7858. if (!no_babystep && leveling_is_active())
  7859. thermalManager.babystep_axis(Z_AXIS, -LROUND(diff * planner.axis_steps_per_mm[Z_AXIS]));
  7860. #else
  7861. UNUSED(no_babystep);
  7862. #endif
  7863. #if ENABLED(DELTA) // correct the delta_height
  7864. home_offset[Z_AXIS] -= diff;
  7865. #endif
  7866. }
  7867. last_zoffset = zprobe_zoffset;
  7868. }
  7869. inline void gcode_M851() {
  7870. SERIAL_ECHO_START();
  7871. SERIAL_ECHOPGM(MSG_ZPROBE_ZOFFSET " ");
  7872. if (parser.seen('Z')) {
  7873. const float value = parser.value_linear_units();
  7874. if (WITHIN(value, Z_PROBE_OFFSET_RANGE_MIN, Z_PROBE_OFFSET_RANGE_MAX)) {
  7875. zprobe_zoffset = value;
  7876. refresh_zprobe_zoffset();
  7877. SERIAL_ECHO(zprobe_zoffset);
  7878. }
  7879. else
  7880. SERIAL_ECHOPGM(MSG_Z_MIN " " STRINGIFY(Z_PROBE_OFFSET_RANGE_MIN) " " MSG_Z_MAX " " STRINGIFY(Z_PROBE_OFFSET_RANGE_MAX));
  7881. }
  7882. else
  7883. SERIAL_ECHOPAIR(": ", zprobe_zoffset);
  7884. SERIAL_EOL();
  7885. }
  7886. #endif // HAS_BED_PROBE
  7887. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  7888. /**
  7889. * M600: Pause for filament change
  7890. *
  7891. * E[distance] - Retract the filament this far (negative value)
  7892. * Z[distance] - Move the Z axis by this distance
  7893. * X[position] - Move to this X position, with Y
  7894. * Y[position] - Move to this Y position, with X
  7895. * U[distance] - Retract distance for removal (negative value) (manual reload)
  7896. * L[distance] - Extrude distance for insertion (positive value) (manual reload)
  7897. * B[count] - Number of times to beep, -1 for indefinite (if equipped with a buzzer)
  7898. *
  7899. * Default values are used for omitted arguments.
  7900. *
  7901. */
  7902. inline void gcode_M600() {
  7903. #if ENABLED(HOME_BEFORE_FILAMENT_CHANGE)
  7904. // Don't allow filament change without homing first
  7905. if (axis_unhomed_error()) home_all_axes();
  7906. #endif
  7907. // Initial retract before move to filament change position
  7908. const float retract = parser.seen('E') ? parser.value_axis_units(E_AXIS) : 0
  7909. #if defined(PAUSE_PARK_RETRACT_LENGTH) && PAUSE_PARK_RETRACT_LENGTH > 0
  7910. - (PAUSE_PARK_RETRACT_LENGTH)
  7911. #endif
  7912. ;
  7913. // Lift Z axis
  7914. const float z_lift = parser.linearval('Z', 0
  7915. #if defined(PAUSE_PARK_Z_ADD) && PAUSE_PARK_Z_ADD > 0
  7916. + PAUSE_PARK_Z_ADD
  7917. #endif
  7918. );
  7919. // Move XY axes to filament exchange position
  7920. const float x_pos = parser.linearval('X', 0
  7921. #ifdef PAUSE_PARK_X_POS
  7922. + PAUSE_PARK_X_POS
  7923. #endif
  7924. );
  7925. const float y_pos = parser.linearval('Y', 0
  7926. #ifdef PAUSE_PARK_Y_POS
  7927. + PAUSE_PARK_Y_POS
  7928. #endif
  7929. );
  7930. // Unload filament
  7931. const float unload_length = parser.seen('U') ? parser.value_axis_units(E_AXIS) : 0
  7932. #if defined(FILAMENT_CHANGE_UNLOAD_LENGTH) && FILAMENT_CHANGE_UNLOAD_LENGTH > 0
  7933. - (FILAMENT_CHANGE_UNLOAD_LENGTH)
  7934. #endif
  7935. ;
  7936. // Load filament
  7937. const float load_length = parser.seen('L') ? parser.value_axis_units(E_AXIS) : 0
  7938. #ifdef FILAMENT_CHANGE_LOAD_LENGTH
  7939. + FILAMENT_CHANGE_LOAD_LENGTH
  7940. #endif
  7941. ;
  7942. const int beep_count = parser.intval('B',
  7943. #ifdef FILAMENT_CHANGE_NUMBER_OF_ALERT_BEEPS
  7944. FILAMENT_CHANGE_NUMBER_OF_ALERT_BEEPS
  7945. #else
  7946. -1
  7947. #endif
  7948. );
  7949. const bool job_running = print_job_timer.isRunning();
  7950. if (pause_print(retract, z_lift, x_pos, y_pos, unload_length, beep_count, true)) {
  7951. wait_for_filament_reload(beep_count);
  7952. resume_print(load_length, ADVANCED_PAUSE_EXTRUDE_LENGTH, beep_count);
  7953. }
  7954. // Resume the print job timer if it was running
  7955. if (job_running) print_job_timer.start();
  7956. }
  7957. #endif // ADVANCED_PAUSE_FEATURE
  7958. #if ENABLED(MK2_MULTIPLEXER)
  7959. inline void select_multiplexed_stepper(const uint8_t e) {
  7960. stepper.synchronize();
  7961. disable_e_steppers();
  7962. WRITE(E_MUX0_PIN, TEST(e, 0) ? HIGH : LOW);
  7963. WRITE(E_MUX1_PIN, TEST(e, 1) ? HIGH : LOW);
  7964. WRITE(E_MUX2_PIN, TEST(e, 2) ? HIGH : LOW);
  7965. safe_delay(100);
  7966. }
  7967. /**
  7968. * M702: Unload all extruders
  7969. */
  7970. inline void gcode_M702() {
  7971. for (uint8_t s = 0; s < E_STEPPERS; s++) {
  7972. select_multiplexed_stepper(e);
  7973. // TODO: standard unload filament function
  7974. // MK2 firmware behavior:
  7975. // - Make sure temperature is high enough
  7976. // - Raise Z to at least 15 to make room
  7977. // - Extrude 1cm of filament in 1 second
  7978. // - Under 230C quickly purge ~12mm, over 230C purge ~10mm
  7979. // - Change E max feedrate to 80, eject the filament from the tube. Sync.
  7980. // - Restore E max feedrate to 50
  7981. }
  7982. // Go back to the last active extruder
  7983. select_multiplexed_stepper(active_extruder);
  7984. disable_e_steppers();
  7985. }
  7986. #endif // MK2_MULTIPLEXER
  7987. #if ENABLED(DUAL_X_CARRIAGE)
  7988. /**
  7989. * M605: Set dual x-carriage movement mode
  7990. *
  7991. * M605 S0: Full control mode. The slicer has full control over x-carriage movement
  7992. * M605 S1: Auto-park mode. The inactive head will auto park/unpark without slicer involvement
  7993. * M605 S2 [Xnnn] [Rmmm]: Duplication mode. The second extruder will duplicate the first with nnn
  7994. * units x-offset and an optional differential hotend temperature of
  7995. * mmm degrees. E.g., with "M605 S2 X100 R2" the second extruder will duplicate
  7996. * the first with a spacing of 100mm in the x direction and 2 degrees hotter.
  7997. *
  7998. * Note: the X axis should be homed after changing dual x-carriage mode.
  7999. */
  8000. inline void gcode_M605() {
  8001. stepper.synchronize();
  8002. if (parser.seen('S')) dual_x_carriage_mode = (DualXMode)parser.value_byte();
  8003. switch (dual_x_carriage_mode) {
  8004. case DXC_FULL_CONTROL_MODE:
  8005. case DXC_AUTO_PARK_MODE:
  8006. break;
  8007. case DXC_DUPLICATION_MODE:
  8008. if (parser.seen('X')) duplicate_extruder_x_offset = max(parser.value_linear_units(), X2_MIN_POS - x_home_pos(0));
  8009. if (parser.seen('R')) duplicate_extruder_temp_offset = parser.value_celsius_diff();
  8010. SERIAL_ECHO_START();
  8011. SERIAL_ECHOPGM(MSG_HOTEND_OFFSET);
  8012. SERIAL_CHAR(' ');
  8013. SERIAL_ECHO(hotend_offset[X_AXIS][0]);
  8014. SERIAL_CHAR(',');
  8015. SERIAL_ECHO(hotend_offset[Y_AXIS][0]);
  8016. SERIAL_CHAR(' ');
  8017. SERIAL_ECHO(duplicate_extruder_x_offset);
  8018. SERIAL_CHAR(',');
  8019. SERIAL_ECHOLN(hotend_offset[Y_AXIS][1]);
  8020. break;
  8021. default:
  8022. dual_x_carriage_mode = DEFAULT_DUAL_X_CARRIAGE_MODE;
  8023. break;
  8024. }
  8025. active_extruder_parked = false;
  8026. extruder_duplication_enabled = false;
  8027. delayed_move_time = 0;
  8028. }
  8029. #elif ENABLED(DUAL_NOZZLE_DUPLICATION_MODE)
  8030. inline void gcode_M605() {
  8031. stepper.synchronize();
  8032. extruder_duplication_enabled = parser.intval('S') == (int)DXC_DUPLICATION_MODE;
  8033. SERIAL_ECHO_START();
  8034. SERIAL_ECHOLNPAIR(MSG_DUPLICATION_MODE, extruder_duplication_enabled ? MSG_ON : MSG_OFF);
  8035. }
  8036. #endif // DUAL_NOZZLE_DUPLICATION_MODE
  8037. #if ENABLED(LIN_ADVANCE)
  8038. /**
  8039. * M900: Set and/or Get advance K factor and WH/D ratio
  8040. *
  8041. * K<factor> Set advance K factor
  8042. * R<ratio> Set ratio directly (overrides WH/D)
  8043. * W<width> H<height> D<diam> Set ratio from WH/D
  8044. */
  8045. inline void gcode_M900() {
  8046. stepper.synchronize();
  8047. const float newK = parser.floatval('K', -1);
  8048. if (newK >= 0) planner.extruder_advance_k = newK;
  8049. float newR = parser.floatval('R', -1);
  8050. if (newR < 0) {
  8051. const float newD = parser.floatval('D', -1),
  8052. newW = parser.floatval('W', -1),
  8053. newH = parser.floatval('H', -1);
  8054. if (newD >= 0 && newW >= 0 && newH >= 0)
  8055. newR = newD ? (newW * newH) / (sq(newD * 0.5) * M_PI) : 0;
  8056. }
  8057. if (newR >= 0) planner.advance_ed_ratio = newR;
  8058. SERIAL_ECHO_START();
  8059. SERIAL_ECHOPAIR("Advance K=", planner.extruder_advance_k);
  8060. SERIAL_ECHOPGM(" E/D=");
  8061. const float ratio = planner.advance_ed_ratio;
  8062. if (ratio) SERIAL_ECHO(ratio); else SERIAL_ECHOPGM("Auto");
  8063. SERIAL_EOL();
  8064. }
  8065. #endif // LIN_ADVANCE
  8066. #if ENABLED(HAVE_TMC2130)
  8067. static void tmc2130_get_current(TMC2130Stepper &st, const char name) {
  8068. SERIAL_CHAR(name);
  8069. SERIAL_ECHOPGM(" axis driver current: ");
  8070. SERIAL_ECHOLN(st.getCurrent());
  8071. }
  8072. static void tmc2130_set_current(TMC2130Stepper &st, const char name, const int mA) {
  8073. st.setCurrent(mA, R_SENSE, HOLD_MULTIPLIER);
  8074. tmc2130_get_current(st, name);
  8075. }
  8076. static void tmc2130_report_otpw(TMC2130Stepper &st, const char name) {
  8077. SERIAL_CHAR(name);
  8078. SERIAL_ECHOPGM(" axis temperature prewarn triggered: ");
  8079. serialprintPGM(st.getOTPW() ? PSTR("true") : PSTR("false"));
  8080. SERIAL_EOL();
  8081. }
  8082. static void tmc2130_clear_otpw(TMC2130Stepper &st, const char name) {
  8083. st.clear_otpw();
  8084. SERIAL_CHAR(name);
  8085. SERIAL_ECHOLNPGM(" prewarn flag cleared");
  8086. }
  8087. static void tmc2130_get_pwmthrs(TMC2130Stepper &st, const char name, const uint16_t spmm) {
  8088. SERIAL_CHAR(name);
  8089. SERIAL_ECHOPGM(" stealthChop max speed set to ");
  8090. SERIAL_ECHOLN(12650000UL * st.microsteps() / (256 * st.stealth_max_speed() * spmm));
  8091. }
  8092. static void tmc2130_set_pwmthrs(TMC2130Stepper &st, const char name, const int32_t thrs, const uint32_t spmm) {
  8093. st.stealth_max_speed(12650000UL * st.microsteps() / (256 * thrs * spmm));
  8094. tmc2130_get_pwmthrs(st, name, spmm);
  8095. }
  8096. static void tmc2130_get_sgt(TMC2130Stepper &st, const char name) {
  8097. SERIAL_CHAR(name);
  8098. SERIAL_ECHOPGM(" driver homing sensitivity set to ");
  8099. SERIAL_ECHOLN(st.sgt());
  8100. }
  8101. static void tmc2130_set_sgt(TMC2130Stepper &st, const char name, const int8_t sgt_val) {
  8102. st.sgt(sgt_val);
  8103. tmc2130_get_sgt(st, name);
  8104. }
  8105. /**
  8106. * M906: Set motor current in milliamps using axis codes X, Y, Z, E
  8107. * Report driver currents when no axis specified
  8108. *
  8109. * S1: Enable automatic current control
  8110. * S0: Disable
  8111. */
  8112. inline void gcode_M906() {
  8113. uint16_t values[XYZE];
  8114. LOOP_XYZE(i)
  8115. values[i] = parser.intval(axis_codes[i]);
  8116. #if ENABLED(X_IS_TMC2130)
  8117. if (values[X_AXIS]) tmc2130_set_current(stepperX, 'X', values[X_AXIS]);
  8118. else tmc2130_get_current(stepperX, 'X');
  8119. #endif
  8120. #if ENABLED(Y_IS_TMC2130)
  8121. if (values[Y_AXIS]) tmc2130_set_current(stepperY, 'Y', values[Y_AXIS]);
  8122. else tmc2130_get_current(stepperY, 'Y');
  8123. #endif
  8124. #if ENABLED(Z_IS_TMC2130)
  8125. if (values[Z_AXIS]) tmc2130_set_current(stepperZ, 'Z', values[Z_AXIS]);
  8126. else tmc2130_get_current(stepperZ, 'Z');
  8127. #endif
  8128. #if ENABLED(E0_IS_TMC2130)
  8129. if (values[E_AXIS]) tmc2130_set_current(stepperE0, 'E', values[E_AXIS]);
  8130. else tmc2130_get_current(stepperE0, 'E');
  8131. #endif
  8132. #if ENABLED(AUTOMATIC_CURRENT_CONTROL)
  8133. if (parser.seen('S')) auto_current_control = parser.value_bool();
  8134. #endif
  8135. }
  8136. /**
  8137. * M911: Report TMC2130 stepper driver overtemperature pre-warn flag
  8138. * The flag is held by the library and persist until manually cleared by M912
  8139. */
  8140. inline void gcode_M911() {
  8141. const bool reportX = parser.seen('X'), reportY = parser.seen('Y'), reportZ = parser.seen('Z'), reportE = parser.seen('E'),
  8142. reportAll = (!reportX && !reportY && !reportZ && !reportE) || (reportX && reportY && reportZ && reportE);
  8143. #if ENABLED(X_IS_TMC2130)
  8144. if (reportX || reportAll) tmc2130_report_otpw(stepperX, 'X');
  8145. #endif
  8146. #if ENABLED(Y_IS_TMC2130)
  8147. if (reportY || reportAll) tmc2130_report_otpw(stepperY, 'Y');
  8148. #endif
  8149. #if ENABLED(Z_IS_TMC2130)
  8150. if (reportZ || reportAll) tmc2130_report_otpw(stepperZ, 'Z');
  8151. #endif
  8152. #if ENABLED(E0_IS_TMC2130)
  8153. if (reportE || reportAll) tmc2130_report_otpw(stepperE0, 'E');
  8154. #endif
  8155. }
  8156. /**
  8157. * M912: Clear TMC2130 stepper driver overtemperature pre-warn flag held by the library
  8158. */
  8159. inline void gcode_M912() {
  8160. const bool clearX = parser.seen('X'), clearY = parser.seen('Y'), clearZ = parser.seen('Z'), clearE = parser.seen('E'),
  8161. clearAll = (!clearX && !clearY && !clearZ && !clearE) || (clearX && clearY && clearZ && clearE);
  8162. #if ENABLED(X_IS_TMC2130)
  8163. if (clearX || clearAll) tmc2130_clear_otpw(stepperX, 'X');
  8164. #endif
  8165. #if ENABLED(Y_IS_TMC2130)
  8166. if (clearY || clearAll) tmc2130_clear_otpw(stepperY, 'Y');
  8167. #endif
  8168. #if ENABLED(Z_IS_TMC2130)
  8169. if (clearZ || clearAll) tmc2130_clear_otpw(stepperZ, 'Z');
  8170. #endif
  8171. #if ENABLED(E0_IS_TMC2130)
  8172. if (clearE || clearAll) tmc2130_clear_otpw(stepperE0, 'E');
  8173. #endif
  8174. }
  8175. /**
  8176. * M913: Set HYBRID_THRESHOLD speed.
  8177. */
  8178. #if ENABLED(HYBRID_THRESHOLD)
  8179. inline void gcode_M913() {
  8180. uint16_t values[XYZE];
  8181. LOOP_XYZE(i)
  8182. values[i] = parser.intval(axis_codes[i]);
  8183. #if ENABLED(X_IS_TMC2130)
  8184. if (values[X_AXIS]) tmc2130_set_pwmthrs(stepperX, 'X', values[X_AXIS], planner.axis_steps_per_mm[X_AXIS]);
  8185. else tmc2130_get_pwmthrs(stepperX, 'X', planner.axis_steps_per_mm[X_AXIS]);
  8186. #endif
  8187. #if ENABLED(Y_IS_TMC2130)
  8188. if (values[Y_AXIS]) tmc2130_set_pwmthrs(stepperY, 'Y', values[Y_AXIS], planner.axis_steps_per_mm[Y_AXIS]);
  8189. else tmc2130_get_pwmthrs(stepperY, 'Y', planner.axis_steps_per_mm[Y_AXIS]);
  8190. #endif
  8191. #if ENABLED(Z_IS_TMC2130)
  8192. if (values[Z_AXIS]) tmc2130_set_pwmthrs(stepperZ, 'Z', values[Z_AXIS], planner.axis_steps_per_mm[Z_AXIS]);
  8193. else tmc2130_get_pwmthrs(stepperZ, 'Z', planner.axis_steps_per_mm[Z_AXIS]);
  8194. #endif
  8195. #if ENABLED(E0_IS_TMC2130)
  8196. if (values[E_AXIS]) tmc2130_set_pwmthrs(stepperE0, 'E', values[E_AXIS], planner.axis_steps_per_mm[E_AXIS]);
  8197. else tmc2130_get_pwmthrs(stepperE0, 'E', planner.axis_steps_per_mm[E_AXIS]);
  8198. #endif
  8199. }
  8200. #endif // HYBRID_THRESHOLD
  8201. /**
  8202. * M914: Set SENSORLESS_HOMING sensitivity.
  8203. */
  8204. #if ENABLED(SENSORLESS_HOMING)
  8205. inline void gcode_M914() {
  8206. #if ENABLED(X_IS_TMC2130)
  8207. if (parser.seen(axis_codes[X_AXIS])) tmc2130_set_sgt(stepperX, 'X', parser.value_int());
  8208. else tmc2130_get_sgt(stepperX, 'X');
  8209. #endif
  8210. #if ENABLED(Y_IS_TMC2130)
  8211. if (parser.seen(axis_codes[Y_AXIS])) tmc2130_set_sgt(stepperY, 'Y', parser.value_int());
  8212. else tmc2130_get_sgt(stepperY, 'Y');
  8213. #endif
  8214. }
  8215. #endif // SENSORLESS_HOMING
  8216. #endif // HAVE_TMC2130
  8217. /**
  8218. * M907: Set digital trimpot motor current using axis codes X, Y, Z, E, B, S
  8219. */
  8220. inline void gcode_M907() {
  8221. #if HAS_DIGIPOTSS
  8222. LOOP_XYZE(i) if (parser.seen(axis_codes[i])) stepper.digipot_current(i, parser.value_int());
  8223. if (parser.seen('B')) stepper.digipot_current(4, parser.value_int());
  8224. if (parser.seen('S')) for (uint8_t i = 0; i <= 4; i++) stepper.digipot_current(i, parser.value_int());
  8225. #elif HAS_MOTOR_CURRENT_PWM
  8226. #if PIN_EXISTS(MOTOR_CURRENT_PWM_XY)
  8227. if (parser.seen('X')) stepper.digipot_current(0, parser.value_int());
  8228. #endif
  8229. #if PIN_EXISTS(MOTOR_CURRENT_PWM_Z)
  8230. if (parser.seen('Z')) stepper.digipot_current(1, parser.value_int());
  8231. #endif
  8232. #if PIN_EXISTS(MOTOR_CURRENT_PWM_E)
  8233. if (parser.seen('E')) stepper.digipot_current(2, parser.value_int());
  8234. #endif
  8235. #endif
  8236. #if ENABLED(DIGIPOT_I2C)
  8237. // this one uses actual amps in floating point
  8238. LOOP_XYZE(i) if (parser.seen(axis_codes[i])) digipot_i2c_set_current(i, parser.value_float());
  8239. // for each additional extruder (named B,C,D,E..., channels 4,5,6,7...)
  8240. for (uint8_t i = NUM_AXIS; i < DIGIPOT_I2C_NUM_CHANNELS; i++) if (parser.seen('B' + i - (NUM_AXIS))) digipot_i2c_set_current(i, parser.value_float());
  8241. #endif
  8242. #if ENABLED(DAC_STEPPER_CURRENT)
  8243. if (parser.seen('S')) {
  8244. const float dac_percent = parser.value_float();
  8245. for (uint8_t i = 0; i <= 4; i++) dac_current_percent(i, dac_percent);
  8246. }
  8247. LOOP_XYZE(i) if (parser.seen(axis_codes[i])) dac_current_percent(i, parser.value_float());
  8248. #endif
  8249. }
  8250. #if HAS_DIGIPOTSS || ENABLED(DAC_STEPPER_CURRENT)
  8251. /**
  8252. * M908: Control digital trimpot directly (M908 P<pin> S<current>)
  8253. */
  8254. inline void gcode_M908() {
  8255. #if HAS_DIGIPOTSS
  8256. stepper.digitalPotWrite(
  8257. parser.intval('P'),
  8258. parser.intval('S')
  8259. );
  8260. #endif
  8261. #ifdef DAC_STEPPER_CURRENT
  8262. dac_current_raw(
  8263. parser.byteval('P', -1),
  8264. parser.ushortval('S', 0)
  8265. );
  8266. #endif
  8267. }
  8268. #if ENABLED(DAC_STEPPER_CURRENT) // As with Printrbot RevF
  8269. inline void gcode_M909() { dac_print_values(); }
  8270. inline void gcode_M910() { dac_commit_eeprom(); }
  8271. #endif
  8272. #endif // HAS_DIGIPOTSS || DAC_STEPPER_CURRENT
  8273. #if HAS_MICROSTEPS
  8274. // M350 Set microstepping mode. Warning: Steps per unit remains unchanged. S code sets stepping mode for all drivers.
  8275. inline void gcode_M350() {
  8276. if (parser.seen('S')) for (int i = 0; i <= 4; i++) stepper.microstep_mode(i, parser.value_byte());
  8277. LOOP_XYZE(i) if (parser.seen(axis_codes[i])) stepper.microstep_mode(i, parser.value_byte());
  8278. if (parser.seen('B')) stepper.microstep_mode(4, parser.value_byte());
  8279. stepper.microstep_readings();
  8280. }
  8281. /**
  8282. * M351: Toggle MS1 MS2 pins directly with axis codes X Y Z E B
  8283. * S# determines MS1 or MS2, X# sets the pin high/low.
  8284. */
  8285. inline void gcode_M351() {
  8286. if (parser.seenval('S')) switch (parser.value_byte()) {
  8287. case 1:
  8288. LOOP_XYZE(i) if (parser.seenval(axis_codes[i])) stepper.microstep_ms(i, parser.value_byte(), -1);
  8289. if (parser.seenval('B')) stepper.microstep_ms(4, parser.value_byte(), -1);
  8290. break;
  8291. case 2:
  8292. LOOP_XYZE(i) if (parser.seenval(axis_codes[i])) stepper.microstep_ms(i, -1, parser.value_byte());
  8293. if (parser.seenval('B')) stepper.microstep_ms(4, -1, parser.value_byte());
  8294. break;
  8295. }
  8296. stepper.microstep_readings();
  8297. }
  8298. #endif // HAS_MICROSTEPS
  8299. #if HAS_CASE_LIGHT
  8300. #ifndef INVERT_CASE_LIGHT
  8301. #define INVERT_CASE_LIGHT false
  8302. #endif
  8303. int case_light_brightness; // LCD routine wants INT
  8304. bool case_light_on;
  8305. void update_case_light() {
  8306. pinMode(CASE_LIGHT_PIN, OUTPUT); // digitalWrite doesn't set the port mode
  8307. uint8_t case_light_bright = (uint8_t)case_light_brightness;
  8308. if (case_light_on) {
  8309. if (USEABLE_HARDWARE_PWM(CASE_LIGHT_PIN)) {
  8310. analogWrite(CASE_LIGHT_PIN, INVERT_CASE_LIGHT ? 255 - case_light_brightness : case_light_brightness );
  8311. }
  8312. else digitalWrite(CASE_LIGHT_PIN, INVERT_CASE_LIGHT ? LOW : HIGH );
  8313. }
  8314. else digitalWrite(CASE_LIGHT_PIN, INVERT_CASE_LIGHT ? HIGH : LOW);
  8315. }
  8316. #endif // HAS_CASE_LIGHT
  8317. /**
  8318. * M355: Turn case light on/off and set brightness
  8319. *
  8320. * P<byte> Set case light brightness (PWM pin required - ignored otherwise)
  8321. *
  8322. * S<bool> Set case light on/off
  8323. *
  8324. * When S turns on the light on a PWM pin then the current brightness level is used/restored
  8325. *
  8326. * M355 P200 S0 turns off the light & sets the brightness level
  8327. * M355 S1 turns on the light with a brightness of 200 (assuming a PWM pin)
  8328. */
  8329. inline void gcode_M355() {
  8330. #if HAS_CASE_LIGHT
  8331. uint8_t args = 0;
  8332. if (parser.seenval('P')) ++args, case_light_brightness = parser.value_byte();
  8333. if (parser.seenval('S')) ++args, case_light_on = parser.value_bool();
  8334. if (args) update_case_light();
  8335. // always report case light status
  8336. SERIAL_ECHO_START();
  8337. if (!case_light_on) {
  8338. SERIAL_ECHOLN("Case light: off");
  8339. }
  8340. else {
  8341. if (!USEABLE_HARDWARE_PWM(CASE_LIGHT_PIN)) SERIAL_ECHOLN("Case light: on");
  8342. else SERIAL_ECHOLNPAIR("Case light: ", case_light_brightness);
  8343. }
  8344. #else
  8345. SERIAL_ERROR_START();
  8346. SERIAL_ERRORLNPGM(MSG_ERR_M355_NONE);
  8347. #endif // HAS_CASE_LIGHT
  8348. }
  8349. #if ENABLED(MIXING_EXTRUDER)
  8350. /**
  8351. * M163: Set a single mix factor for a mixing extruder
  8352. * This is called "weight" by some systems.
  8353. *
  8354. * S[index] The channel index to set
  8355. * P[float] The mix value
  8356. *
  8357. */
  8358. inline void gcode_M163() {
  8359. const int mix_index = parser.intval('S');
  8360. if (mix_index < MIXING_STEPPERS) {
  8361. float mix_value = parser.floatval('P');
  8362. NOLESS(mix_value, 0.0);
  8363. mixing_factor[mix_index] = RECIPROCAL(mix_value);
  8364. }
  8365. }
  8366. #if MIXING_VIRTUAL_TOOLS > 1
  8367. /**
  8368. * M164: Store the current mix factors as a virtual tool.
  8369. *
  8370. * S[index] The virtual tool to store
  8371. *
  8372. */
  8373. inline void gcode_M164() {
  8374. const int tool_index = parser.intval('S');
  8375. if (tool_index < MIXING_VIRTUAL_TOOLS) {
  8376. normalize_mix();
  8377. for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
  8378. mixing_virtual_tool_mix[tool_index][i] = mixing_factor[i];
  8379. }
  8380. }
  8381. #endif
  8382. #if ENABLED(DIRECT_MIXING_IN_G1)
  8383. /**
  8384. * M165: Set multiple mix factors for a mixing extruder.
  8385. * Factors that are left out will be set to 0.
  8386. * All factors together must add up to 1.0.
  8387. *
  8388. * A[factor] Mix factor for extruder stepper 1
  8389. * B[factor] Mix factor for extruder stepper 2
  8390. * C[factor] Mix factor for extruder stepper 3
  8391. * D[factor] Mix factor for extruder stepper 4
  8392. * H[factor] Mix factor for extruder stepper 5
  8393. * I[factor] Mix factor for extruder stepper 6
  8394. *
  8395. */
  8396. inline void gcode_M165() { gcode_get_mix(); }
  8397. #endif
  8398. #endif // MIXING_EXTRUDER
  8399. /**
  8400. * M999: Restart after being stopped
  8401. *
  8402. * Default behaviour is to flush the serial buffer and request
  8403. * a resend to the host starting on the last N line received.
  8404. *
  8405. * Sending "M999 S1" will resume printing without flushing the
  8406. * existing command buffer.
  8407. *
  8408. */
  8409. inline void gcode_M999() {
  8410. Running = true;
  8411. lcd_reset_alert_level();
  8412. if (parser.boolval('S')) return;
  8413. // gcode_LastN = Stopped_gcode_LastN;
  8414. FlushSerialRequestResend();
  8415. }
  8416. #if ENABLED(SWITCHING_EXTRUDER)
  8417. #if EXTRUDERS > 3
  8418. #define REQ_ANGLES 4
  8419. #define _SERVO_NR (e < 2 ? SWITCHING_EXTRUDER_SERVO_NR : SWITCHING_EXTRUDER_E23_SERVO_NR)
  8420. #else
  8421. #define REQ_ANGLES 2
  8422. #define _SERVO_NR SWITCHING_EXTRUDER_SERVO_NR
  8423. #endif
  8424. inline void move_extruder_servo(const uint8_t e) {
  8425. constexpr int16_t angles[] = SWITCHING_EXTRUDER_SERVO_ANGLES;
  8426. static_assert(COUNT(angles) == REQ_ANGLES, "SWITCHING_EXTRUDER_SERVO_ANGLES needs " STRINGIFY(REQ_ANGLES) " angles.");
  8427. stepper.synchronize();
  8428. #if EXTRUDERS & 1
  8429. if (e < EXTRUDERS - 1)
  8430. #endif
  8431. {
  8432. MOVE_SERVO(_SERVO_NR, angles[e]);
  8433. safe_delay(500);
  8434. }
  8435. }
  8436. #endif // SWITCHING_EXTRUDER
  8437. #if ENABLED(SWITCHING_NOZZLE)
  8438. inline void move_nozzle_servo(const uint8_t e) {
  8439. const int16_t angles[2] = SWITCHING_NOZZLE_SERVO_ANGLES;
  8440. stepper.synchronize();
  8441. MOVE_SERVO(SWITCHING_NOZZLE_SERVO_NR, angles[e]);
  8442. safe_delay(500);
  8443. }
  8444. #endif
  8445. inline void invalid_extruder_error(const uint8_t e) {
  8446. SERIAL_ECHO_START();
  8447. SERIAL_CHAR('T');
  8448. SERIAL_ECHO_F(e, DEC);
  8449. SERIAL_CHAR(' ');
  8450. SERIAL_ECHOLN(MSG_INVALID_EXTRUDER);
  8451. }
  8452. /**
  8453. * Perform a tool-change, which may result in moving the
  8454. * previous tool out of the way and the new tool into place.
  8455. */
  8456. void tool_change(const uint8_t tmp_extruder, const float fr_mm_s/*=0.0*/, bool no_move/*=false*/) {
  8457. #if ENABLED(MIXING_EXTRUDER) && MIXING_VIRTUAL_TOOLS > 1
  8458. if (tmp_extruder >= MIXING_VIRTUAL_TOOLS)
  8459. return invalid_extruder_error(tmp_extruder);
  8460. // T0-Tnnn: Switch virtual tool by changing the mix
  8461. for (uint8_t j = 0; j < MIXING_STEPPERS; j++)
  8462. mixing_factor[j] = mixing_virtual_tool_mix[tmp_extruder][j];
  8463. #else // !MIXING_EXTRUDER || MIXING_VIRTUAL_TOOLS <= 1
  8464. if (tmp_extruder >= EXTRUDERS)
  8465. return invalid_extruder_error(tmp_extruder);
  8466. #if HOTENDS > 1
  8467. const float old_feedrate_mm_s = fr_mm_s > 0.0 ? fr_mm_s : feedrate_mm_s;
  8468. feedrate_mm_s = fr_mm_s > 0.0 ? fr_mm_s : XY_PROBE_FEEDRATE_MM_S;
  8469. if (tmp_extruder != active_extruder) {
  8470. if (!no_move && axis_unhomed_error()) {
  8471. SERIAL_ECHOLNPGM("No move on toolchange");
  8472. no_move = true;
  8473. }
  8474. // Save current position to destination, for use later
  8475. set_destination_to_current();
  8476. #if ENABLED(DUAL_X_CARRIAGE)
  8477. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8478. if (DEBUGGING(LEVELING)) {
  8479. SERIAL_ECHOPGM("Dual X Carriage Mode ");
  8480. switch (dual_x_carriage_mode) {
  8481. case DXC_FULL_CONTROL_MODE: SERIAL_ECHOLNPGM("DXC_FULL_CONTROL_MODE"); break;
  8482. case DXC_AUTO_PARK_MODE: SERIAL_ECHOLNPGM("DXC_AUTO_PARK_MODE"); break;
  8483. case DXC_DUPLICATION_MODE: SERIAL_ECHOLNPGM("DXC_DUPLICATION_MODE"); break;
  8484. }
  8485. }
  8486. #endif
  8487. const float xhome = x_home_pos(active_extruder);
  8488. if (dual_x_carriage_mode == DXC_AUTO_PARK_MODE
  8489. && IsRunning()
  8490. && (delayed_move_time || current_position[X_AXIS] != xhome)
  8491. ) {
  8492. float raised_z = current_position[Z_AXIS] + TOOLCHANGE_PARK_ZLIFT;
  8493. #if ENABLED(MAX_SOFTWARE_ENDSTOPS)
  8494. NOMORE(raised_z, soft_endstop_max[Z_AXIS]);
  8495. #endif
  8496. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8497. if (DEBUGGING(LEVELING)) {
  8498. SERIAL_ECHOLNPAIR("Raise to ", raised_z);
  8499. SERIAL_ECHOLNPAIR("MoveX to ", xhome);
  8500. SERIAL_ECHOLNPAIR("Lower to ", current_position[Z_AXIS]);
  8501. }
  8502. #endif
  8503. // Park old head: 1) raise 2) move to park position 3) lower
  8504. for (uint8_t i = 0; i < 3; i++)
  8505. planner.buffer_line(
  8506. i == 0 ? current_position[X_AXIS] : xhome,
  8507. current_position[Y_AXIS],
  8508. i == 2 ? current_position[Z_AXIS] : raised_z,
  8509. current_position[E_AXIS],
  8510. planner.max_feedrate_mm_s[i == 1 ? X_AXIS : Z_AXIS],
  8511. active_extruder
  8512. );
  8513. stepper.synchronize();
  8514. }
  8515. // Apply Y & Z extruder offset (X offset is used as home pos with Dual X)
  8516. current_position[Y_AXIS] -= hotend_offset[Y_AXIS][active_extruder] - hotend_offset[Y_AXIS][tmp_extruder];
  8517. current_position[Z_AXIS] -= hotend_offset[Z_AXIS][active_extruder] - hotend_offset[Z_AXIS][tmp_extruder];
  8518. // Activate the new extruder
  8519. active_extruder = tmp_extruder;
  8520. // This function resets the max/min values - the current position may be overwritten below.
  8521. set_axis_is_at_home(X_AXIS);
  8522. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8523. if (DEBUGGING(LEVELING)) DEBUG_POS("New Extruder", current_position);
  8524. #endif
  8525. // Only when auto-parking are carriages safe to move
  8526. if (dual_x_carriage_mode != DXC_AUTO_PARK_MODE) no_move = true;
  8527. switch (dual_x_carriage_mode) {
  8528. case DXC_FULL_CONTROL_MODE:
  8529. // New current position is the position of the activated extruder
  8530. current_position[X_AXIS] = LOGICAL_X_POSITION(inactive_extruder_x_pos);
  8531. // Save the inactive extruder's position (from the old current_position)
  8532. inactive_extruder_x_pos = RAW_X_POSITION(destination[X_AXIS]);
  8533. break;
  8534. case DXC_AUTO_PARK_MODE:
  8535. // record raised toolhead position for use by unpark
  8536. COPY(raised_parked_position, current_position);
  8537. raised_parked_position[Z_AXIS] += TOOLCHANGE_UNPARK_ZLIFT;
  8538. #if ENABLED(MAX_SOFTWARE_ENDSTOPS)
  8539. NOMORE(raised_parked_position[Z_AXIS], soft_endstop_max[Z_AXIS]);
  8540. #endif
  8541. active_extruder_parked = true;
  8542. delayed_move_time = 0;
  8543. break;
  8544. case DXC_DUPLICATION_MODE:
  8545. // If the new extruder is the left one, set it "parked"
  8546. // This triggers the second extruder to move into the duplication position
  8547. active_extruder_parked = (active_extruder == 0);
  8548. if (active_extruder_parked)
  8549. current_position[X_AXIS] = LOGICAL_X_POSITION(inactive_extruder_x_pos);
  8550. else
  8551. current_position[X_AXIS] = destination[X_AXIS] + duplicate_extruder_x_offset;
  8552. inactive_extruder_x_pos = RAW_X_POSITION(destination[X_AXIS]);
  8553. extruder_duplication_enabled = false;
  8554. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8555. if (DEBUGGING(LEVELING)) {
  8556. SERIAL_ECHOLNPAIR("Set inactive_extruder_x_pos=", inactive_extruder_x_pos);
  8557. SERIAL_ECHOLNPGM("Clear extruder_duplication_enabled");
  8558. }
  8559. #endif
  8560. break;
  8561. }
  8562. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8563. if (DEBUGGING(LEVELING)) {
  8564. SERIAL_ECHOLNPAIR("Active extruder parked: ", active_extruder_parked ? "yes" : "no");
  8565. DEBUG_POS("New extruder (parked)", current_position);
  8566. }
  8567. #endif
  8568. // No extra case for HAS_ABL in DUAL_X_CARRIAGE. Does that mean they don't work together?
  8569. #else // !DUAL_X_CARRIAGE
  8570. #if ENABLED(SWITCHING_NOZZLE)
  8571. #define DONT_SWITCH (SWITCHING_EXTRUDER_SERVO_NR == SWITCHING_NOZZLE_SERVO_NR)
  8572. // <0 if the new nozzle is higher, >0 if lower. A bigger raise when lower.
  8573. const float z_diff = hotend_offset[Z_AXIS][active_extruder] - hotend_offset[Z_AXIS][tmp_extruder],
  8574. z_raise = 0.3 + (z_diff > 0.0 ? z_diff : 0.0);
  8575. // Always raise by some amount (destination copied from current_position earlier)
  8576. current_position[Z_AXIS] += z_raise;
  8577. planner.buffer_line_kinematic(current_position, planner.max_feedrate_mm_s[Z_AXIS], active_extruder);
  8578. move_nozzle_servo(tmp_extruder);
  8579. #endif
  8580. /**
  8581. * Set current_position to the position of the new nozzle.
  8582. * Offsets are based on linear distance, so we need to get
  8583. * the resulting position in coordinate space.
  8584. *
  8585. * - With grid or 3-point leveling, offset XYZ by a tilted vector
  8586. * - With mesh leveling, update Z for the new position
  8587. * - Otherwise, just use the raw linear distance
  8588. *
  8589. * Software endstops are altered here too. Consider a case where:
  8590. * E0 at X=0 ... E1 at X=10
  8591. * When we switch to E1 now X=10, but E1 can't move left.
  8592. * To express this we apply the change in XY to the software endstops.
  8593. * E1 can move farther right than E0, so the right limit is extended.
  8594. *
  8595. * Note that we don't adjust the Z software endstops. Why not?
  8596. * Consider a case where Z=0 (here) and switching to E1 makes Z=1
  8597. * because the bed is 1mm lower at the new position. As long as
  8598. * the first nozzle is out of the way, the carriage should be
  8599. * allowed to move 1mm lower. This technically "breaks" the
  8600. * Z software endstop. But this is technically correct (and
  8601. * there is no viable alternative).
  8602. */
  8603. #if ABL_PLANAR
  8604. // Offset extruder, make sure to apply the bed level rotation matrix
  8605. vector_3 tmp_offset_vec = vector_3(hotend_offset[X_AXIS][tmp_extruder],
  8606. hotend_offset[Y_AXIS][tmp_extruder],
  8607. 0),
  8608. act_offset_vec = vector_3(hotend_offset[X_AXIS][active_extruder],
  8609. hotend_offset[Y_AXIS][active_extruder],
  8610. 0),
  8611. offset_vec = tmp_offset_vec - act_offset_vec;
  8612. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8613. if (DEBUGGING(LEVELING)) {
  8614. tmp_offset_vec.debug(PSTR("tmp_offset_vec"));
  8615. act_offset_vec.debug(PSTR("act_offset_vec"));
  8616. offset_vec.debug(PSTR("offset_vec (BEFORE)"));
  8617. }
  8618. #endif
  8619. offset_vec.apply_rotation(planner.bed_level_matrix.transpose(planner.bed_level_matrix));
  8620. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8621. if (DEBUGGING(LEVELING)) offset_vec.debug(PSTR("offset_vec (AFTER)"));
  8622. #endif
  8623. // Adjustments to the current position
  8624. const float xydiff[2] = { offset_vec.x, offset_vec.y };
  8625. current_position[Z_AXIS] += offset_vec.z;
  8626. #else // !ABL_PLANAR
  8627. const float xydiff[2] = {
  8628. hotend_offset[X_AXIS][tmp_extruder] - hotend_offset[X_AXIS][active_extruder],
  8629. hotend_offset[Y_AXIS][tmp_extruder] - hotend_offset[Y_AXIS][active_extruder]
  8630. };
  8631. #if ENABLED(MESH_BED_LEVELING)
  8632. if (leveling_is_active()) {
  8633. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8634. if (DEBUGGING(LEVELING)) SERIAL_ECHOPAIR("Z before MBL: ", current_position[Z_AXIS]);
  8635. #endif
  8636. float x2 = current_position[X_AXIS] + xydiff[X_AXIS],
  8637. y2 = current_position[Y_AXIS] + xydiff[Y_AXIS],
  8638. z1 = current_position[Z_AXIS], z2 = z1;
  8639. planner.apply_leveling(current_position[X_AXIS], current_position[Y_AXIS], z1);
  8640. planner.apply_leveling(x2, y2, z2);
  8641. current_position[Z_AXIS] += z2 - z1;
  8642. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8643. if (DEBUGGING(LEVELING))
  8644. SERIAL_ECHOLNPAIR(" after: ", current_position[Z_AXIS]);
  8645. #endif
  8646. }
  8647. #endif // MESH_BED_LEVELING
  8648. #endif // !HAS_ABL
  8649. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8650. if (DEBUGGING(LEVELING)) {
  8651. SERIAL_ECHOPAIR("Offset Tool XY by { ", xydiff[X_AXIS]);
  8652. SERIAL_ECHOPAIR(", ", xydiff[Y_AXIS]);
  8653. SERIAL_ECHOLNPGM(" }");
  8654. }
  8655. #endif
  8656. // The newly-selected extruder XY is actually at...
  8657. current_position[X_AXIS] += xydiff[X_AXIS];
  8658. current_position[Y_AXIS] += xydiff[Y_AXIS];
  8659. #if HAS_WORKSPACE_OFFSET || ENABLED(DUAL_X_CARRIAGE)
  8660. for (uint8_t i = X_AXIS; i <= Y_AXIS; i++) {
  8661. #if HAS_POSITION_SHIFT
  8662. position_shift[i] += xydiff[i];
  8663. #endif
  8664. update_software_endstops((AxisEnum)i);
  8665. }
  8666. #endif
  8667. // Set the new active extruder
  8668. active_extruder = tmp_extruder;
  8669. #endif // !DUAL_X_CARRIAGE
  8670. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8671. if (DEBUGGING(LEVELING)) DEBUG_POS("Sync After Toolchange", current_position);
  8672. #endif
  8673. // Tell the planner the new "current position"
  8674. SYNC_PLAN_POSITION_KINEMATIC();
  8675. // Move to the "old position" (move the extruder into place)
  8676. if (!no_move && IsRunning()) {
  8677. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8678. if (DEBUGGING(LEVELING)) DEBUG_POS("Move back", destination);
  8679. #endif
  8680. prepare_move_to_destination();
  8681. }
  8682. #if ENABLED(SWITCHING_NOZZLE)
  8683. // Move back down, if needed. (Including when the new tool is higher.)
  8684. if (z_raise != z_diff) {
  8685. destination[Z_AXIS] += z_diff;
  8686. feedrate_mm_s = planner.max_feedrate_mm_s[Z_AXIS];
  8687. prepare_move_to_destination();
  8688. }
  8689. #endif
  8690. } // (tmp_extruder != active_extruder)
  8691. stepper.synchronize();
  8692. #if ENABLED(EXT_SOLENOID)
  8693. disable_all_solenoids();
  8694. enable_solenoid_on_active_extruder();
  8695. #endif // EXT_SOLENOID
  8696. feedrate_mm_s = old_feedrate_mm_s;
  8697. #else // HOTENDS <= 1
  8698. UNUSED(fr_mm_s);
  8699. UNUSED(no_move);
  8700. #if ENABLED(SWITCHING_EXTRUDER) && !DONT_SWITCH
  8701. stepper.synchronize();
  8702. move_extruder_servo(tmp_extruder);
  8703. #elif ENABLED(MK2_MULTIPLEXER)
  8704. if (tmp_extruder >= E_STEPPERS)
  8705. return invalid_extruder_error(tmp_extruder);
  8706. select_multiplexed_stepper(tmp_extruder);
  8707. #endif
  8708. #endif // HOTENDS <= 1
  8709. active_extruder = tmp_extruder;
  8710. SERIAL_ECHO_START();
  8711. SERIAL_ECHOLNPAIR(MSG_ACTIVE_EXTRUDER, (int)active_extruder);
  8712. #endif // !MIXING_EXTRUDER || MIXING_VIRTUAL_TOOLS <= 1
  8713. }
  8714. /**
  8715. * T0-T3: Switch tool, usually switching extruders
  8716. *
  8717. * F[units/min] Set the movement feedrate
  8718. * S1 Don't move the tool in XY after change
  8719. */
  8720. inline void gcode_T(uint8_t tmp_extruder) {
  8721. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8722. if (DEBUGGING(LEVELING)) {
  8723. SERIAL_ECHOPAIR(">>> gcode_T(", tmp_extruder);
  8724. SERIAL_CHAR(')');
  8725. SERIAL_EOL();
  8726. DEBUG_POS("BEFORE", current_position);
  8727. }
  8728. #endif
  8729. #if HOTENDS == 1 || (ENABLED(MIXING_EXTRUDER) && MIXING_VIRTUAL_TOOLS > 1)
  8730. tool_change(tmp_extruder);
  8731. #elif HOTENDS > 1
  8732. tool_change(
  8733. tmp_extruder,
  8734. MMM_TO_MMS(parser.linearval('F')),
  8735. (tmp_extruder == active_extruder) || parser.boolval('S')
  8736. );
  8737. #endif
  8738. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8739. if (DEBUGGING(LEVELING)) {
  8740. DEBUG_POS("AFTER", current_position);
  8741. SERIAL_ECHOLNPGM("<<< gcode_T");
  8742. }
  8743. #endif
  8744. }
  8745. /**
  8746. * Process a single command and dispatch it to its handler
  8747. * This is called from the main loop()
  8748. */
  8749. void process_next_command() {
  8750. char * const current_command = command_queue[cmd_queue_index_r];
  8751. if (DEBUGGING(ECHO)) {
  8752. SERIAL_ECHO_START();
  8753. SERIAL_ECHOLN(current_command);
  8754. #if ENABLED(M100_FREE_MEMORY_WATCHER)
  8755. SERIAL_ECHOPAIR("slot:", cmd_queue_index_r);
  8756. M100_dump_routine(" Command Queue:", (const char*)command_queue, (const char*)(command_queue + sizeof(command_queue)));
  8757. #endif
  8758. }
  8759. KEEPALIVE_STATE(IN_HANDLER);
  8760. // Parse the next command in the queue
  8761. parser.parse(current_command);
  8762. // Handle a known G, M, or T
  8763. switch (parser.command_letter) {
  8764. case 'G': switch (parser.codenum) {
  8765. // G0, G1
  8766. case 0:
  8767. case 1:
  8768. #if IS_SCARA
  8769. gcode_G0_G1(parser.codenum == 0);
  8770. #else
  8771. gcode_G0_G1();
  8772. #endif
  8773. break;
  8774. // G2, G3
  8775. #if ENABLED(ARC_SUPPORT) && DISABLED(SCARA)
  8776. case 2: // G2 - CW ARC
  8777. case 3: // G3 - CCW ARC
  8778. gcode_G2_G3(parser.codenum == 2);
  8779. break;
  8780. #endif
  8781. // G4 Dwell
  8782. case 4:
  8783. gcode_G4();
  8784. break;
  8785. #if ENABLED(BEZIER_CURVE_SUPPORT)
  8786. // G5
  8787. case 5: // G5 - Cubic B_spline
  8788. gcode_G5();
  8789. break;
  8790. #endif // BEZIER_CURVE_SUPPORT
  8791. #if ENABLED(FWRETRACT)
  8792. case 10: // G10: retract
  8793. case 11: // G11: retract_recover
  8794. gcode_G10_G11(parser.codenum == 10);
  8795. break;
  8796. #endif // FWRETRACT
  8797. #if ENABLED(NOZZLE_CLEAN_FEATURE)
  8798. case 12:
  8799. gcode_G12(); // G12: Nozzle Clean
  8800. break;
  8801. #endif // NOZZLE_CLEAN_FEATURE
  8802. #if ENABLED(CNC_WORKSPACE_PLANES)
  8803. case 17: // G17: Select Plane XY
  8804. gcode_G17();
  8805. break;
  8806. case 18: // G18: Select Plane ZX
  8807. gcode_G18();
  8808. break;
  8809. case 19: // G19: Select Plane YZ
  8810. gcode_G19();
  8811. break;
  8812. #endif // CNC_WORKSPACE_PLANES
  8813. #if ENABLED(INCH_MODE_SUPPORT)
  8814. case 20: //G20: Inch Mode
  8815. gcode_G20();
  8816. break;
  8817. case 21: //G21: MM Mode
  8818. gcode_G21();
  8819. break;
  8820. #endif // INCH_MODE_SUPPORT
  8821. #if ENABLED(AUTO_BED_LEVELING_UBL) && ENABLED(UBL_G26_MESH_VALIDATION)
  8822. case 26: // G26: Mesh Validation Pattern generation
  8823. gcode_G26();
  8824. break;
  8825. #endif // AUTO_BED_LEVELING_UBL
  8826. #if ENABLED(NOZZLE_PARK_FEATURE)
  8827. case 27: // G27: Nozzle Park
  8828. gcode_G27();
  8829. break;
  8830. #endif // NOZZLE_PARK_FEATURE
  8831. case 28: // G28: Home all axes, one at a time
  8832. gcode_G28(false);
  8833. break;
  8834. #if HAS_LEVELING
  8835. case 29: // G29 Detailed Z probe, probes the bed at 3 or more points,
  8836. // or provides access to the UBL System if enabled.
  8837. gcode_G29();
  8838. break;
  8839. #endif // HAS_LEVELING
  8840. #if HAS_BED_PROBE
  8841. case 30: // G30 Single Z probe
  8842. gcode_G30();
  8843. break;
  8844. #if ENABLED(Z_PROBE_SLED)
  8845. case 31: // G31: dock the sled
  8846. gcode_G31();
  8847. break;
  8848. case 32: // G32: undock the sled
  8849. gcode_G32();
  8850. break;
  8851. #endif // Z_PROBE_SLED
  8852. #endif // HAS_BED_PROBE
  8853. #if PROBE_SELECTED
  8854. #if ENABLED(DELTA_AUTO_CALIBRATION)
  8855. case 33: // G33: Delta Auto-Calibration
  8856. gcode_G33();
  8857. break;
  8858. #endif // DELTA_AUTO_CALIBRATION
  8859. #endif // PROBE_SELECTED
  8860. #if ENABLED(G38_PROBE_TARGET)
  8861. case 38: // G38.2 & G38.3
  8862. if (subcode == 2 || subcode == 3)
  8863. gcode_G38(subcode == 2);
  8864. break;
  8865. #endif
  8866. case 90: // G90
  8867. relative_mode = false;
  8868. break;
  8869. case 91: // G91
  8870. relative_mode = true;
  8871. break;
  8872. case 92: // G92
  8873. gcode_G92();
  8874. break;
  8875. #if ENABLED(AUTO_BED_LEVELING_BILINEAR) || ENABLED(AUTO_BED_LEVELING_UBL) || ENABLED(MESH_BED_LEVELING)
  8876. case 42:
  8877. gcode_G42();
  8878. break;
  8879. #endif
  8880. #if ENABLED(DEBUG_GCODE_PARSER)
  8881. case 800:
  8882. parser.debug(); // GCode Parser Test for G
  8883. break;
  8884. #endif
  8885. }
  8886. break;
  8887. case 'M': switch (parser.codenum) {
  8888. #if HAS_RESUME_CONTINUE
  8889. case 0: // M0: Unconditional stop - Wait for user button press on LCD
  8890. case 1: // M1: Conditional stop - Wait for user button press on LCD
  8891. gcode_M0_M1();
  8892. break;
  8893. #endif // ULTIPANEL
  8894. #if ENABLED(SPINDLE_LASER_ENABLE)
  8895. case 3:
  8896. gcode_M3_M4(true); // M3: turn spindle/laser on, set laser/spindle power/speed, set rotation direction CW
  8897. break; // synchronizes with movement commands
  8898. case 4:
  8899. gcode_M3_M4(false); // M4: turn spindle/laser on, set laser/spindle power/speed, set rotation direction CCW
  8900. break; // synchronizes with movement commands
  8901. case 5:
  8902. gcode_M5(); // M5 - turn spindle/laser off
  8903. break; // synchronizes with movement commands
  8904. #endif
  8905. case 17: // M17: Enable all stepper motors
  8906. gcode_M17();
  8907. break;
  8908. #if ENABLED(SDSUPPORT)
  8909. case 20: // M20: list SD card
  8910. gcode_M20(); break;
  8911. case 21: // M21: init SD card
  8912. gcode_M21(); break;
  8913. case 22: // M22: release SD card
  8914. gcode_M22(); break;
  8915. case 23: // M23: Select file
  8916. gcode_M23(); break;
  8917. case 24: // M24: Start SD print
  8918. gcode_M24(); break;
  8919. case 25: // M25: Pause SD print
  8920. gcode_M25(); break;
  8921. case 26: // M26: Set SD index
  8922. gcode_M26(); break;
  8923. case 27: // M27: Get SD status
  8924. gcode_M27(); break;
  8925. case 28: // M28: Start SD write
  8926. gcode_M28(); break;
  8927. case 29: // M29: Stop SD write
  8928. gcode_M29(); break;
  8929. case 30: // M30 <filename> Delete File
  8930. gcode_M30(); break;
  8931. case 32: // M32: Select file and start SD print
  8932. gcode_M32(); break;
  8933. #if ENABLED(LONG_FILENAME_HOST_SUPPORT)
  8934. case 33: // M33: Get the long full path to a file or folder
  8935. gcode_M33(); break;
  8936. #endif
  8937. #if ENABLED(SDCARD_SORT_ALPHA) && ENABLED(SDSORT_GCODE)
  8938. case 34: //M34 - Set SD card sorting options
  8939. gcode_M34(); break;
  8940. #endif // SDCARD_SORT_ALPHA && SDSORT_GCODE
  8941. case 928: // M928: Start SD write
  8942. gcode_M928(); break;
  8943. #endif // SDSUPPORT
  8944. case 31: // M31: Report time since the start of SD print or last M109
  8945. gcode_M31(); break;
  8946. case 42: // M42: Change pin state
  8947. gcode_M42(); break;
  8948. #if ENABLED(PINS_DEBUGGING)
  8949. case 43: // M43: Read pin state
  8950. gcode_M43(); break;
  8951. #endif
  8952. #if ENABLED(Z_MIN_PROBE_REPEATABILITY_TEST)
  8953. case 48: // M48: Z probe repeatability test
  8954. gcode_M48();
  8955. break;
  8956. #endif // Z_MIN_PROBE_REPEATABILITY_TEST
  8957. #if ENABLED(AUTO_BED_LEVELING_UBL) && ENABLED(UBL_G26_MESH_VALIDATION)
  8958. case 49: // M49: Turn on or off G26 debug flag for verbose output
  8959. gcode_M49();
  8960. break;
  8961. #endif // AUTO_BED_LEVELING_UBL && UBL_G26_MESH_VALIDATION
  8962. case 75: // M75: Start print timer
  8963. gcode_M75(); break;
  8964. case 76: // M76: Pause print timer
  8965. gcode_M76(); break;
  8966. case 77: // M77: Stop print timer
  8967. gcode_M77(); break;
  8968. #if ENABLED(PRINTCOUNTER)
  8969. case 78: // M78: Show print statistics
  8970. gcode_M78(); break;
  8971. #endif
  8972. #if ENABLED(M100_FREE_MEMORY_WATCHER)
  8973. case 100: // M100: Free Memory Report
  8974. gcode_M100();
  8975. break;
  8976. #endif
  8977. case 104: // M104: Set hot end temperature
  8978. gcode_M104();
  8979. break;
  8980. case 110: // M110: Set Current Line Number
  8981. gcode_M110();
  8982. break;
  8983. case 111: // M111: Set debug level
  8984. gcode_M111();
  8985. break;
  8986. #if DISABLED(EMERGENCY_PARSER)
  8987. case 108: // M108: Cancel Waiting
  8988. gcode_M108();
  8989. break;
  8990. case 112: // M112: Emergency Stop
  8991. gcode_M112();
  8992. break;
  8993. case 410: // M410 quickstop - Abort all the planned moves.
  8994. gcode_M410();
  8995. break;
  8996. #endif
  8997. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  8998. case 113: // M113: Set Host Keepalive interval
  8999. gcode_M113();
  9000. break;
  9001. #endif
  9002. case 140: // M140: Set bed temperature
  9003. gcode_M140();
  9004. break;
  9005. case 105: // M105: Report current temperature
  9006. gcode_M105();
  9007. KEEPALIVE_STATE(NOT_BUSY);
  9008. return; // "ok" already printed
  9009. #if ENABLED(AUTO_REPORT_TEMPERATURES) && (HAS_TEMP_HOTEND || HAS_TEMP_BED)
  9010. case 155: // M155: Set temperature auto-report interval
  9011. gcode_M155();
  9012. break;
  9013. #endif
  9014. case 109: // M109: Wait for hotend temperature to reach target
  9015. gcode_M109();
  9016. break;
  9017. #if HAS_TEMP_BED
  9018. case 190: // M190: Wait for bed temperature to reach target
  9019. gcode_M190();
  9020. break;
  9021. #endif // HAS_TEMP_BED
  9022. #if FAN_COUNT > 0
  9023. case 106: // M106: Fan On
  9024. gcode_M106();
  9025. break;
  9026. case 107: // M107: Fan Off
  9027. gcode_M107();
  9028. break;
  9029. #endif // FAN_COUNT > 0
  9030. #if ENABLED(PARK_HEAD_ON_PAUSE)
  9031. case 125: // M125: Store current position and move to filament change position
  9032. gcode_M125(); break;
  9033. #endif
  9034. #if ENABLED(BARICUDA)
  9035. // PWM for HEATER_1_PIN
  9036. #if HAS_HEATER_1
  9037. case 126: // M126: valve open
  9038. gcode_M126();
  9039. break;
  9040. case 127: // M127: valve closed
  9041. gcode_M127();
  9042. break;
  9043. #endif // HAS_HEATER_1
  9044. // PWM for HEATER_2_PIN
  9045. #if HAS_HEATER_2
  9046. case 128: // M128: valve open
  9047. gcode_M128();
  9048. break;
  9049. case 129: // M129: valve closed
  9050. gcode_M129();
  9051. break;
  9052. #endif // HAS_HEATER_2
  9053. #endif // BARICUDA
  9054. #if HAS_POWER_SWITCH
  9055. case 80: // M80: Turn on Power Supply
  9056. gcode_M80();
  9057. break;
  9058. #endif // HAS_POWER_SWITCH
  9059. case 81: // M81: Turn off Power, including Power Supply, if possible
  9060. gcode_M81();
  9061. break;
  9062. case 82: // M82: Set E axis normal mode (same as other axes)
  9063. gcode_M82();
  9064. break;
  9065. case 83: // M83: Set E axis relative mode
  9066. gcode_M83();
  9067. break;
  9068. case 18: // M18 => M84
  9069. case 84: // M84: Disable all steppers or set timeout
  9070. gcode_M18_M84();
  9071. break;
  9072. case 85: // M85: Set inactivity stepper shutdown timeout
  9073. gcode_M85();
  9074. break;
  9075. case 92: // M92: Set the steps-per-unit for one or more axes
  9076. gcode_M92();
  9077. break;
  9078. case 114: // M114: Report current position
  9079. gcode_M114();
  9080. break;
  9081. case 115: // M115: Report capabilities
  9082. gcode_M115();
  9083. break;
  9084. case 117: // M117: Set LCD message text, if possible
  9085. gcode_M117();
  9086. break;
  9087. case 118: // M118: Display a message in the host console
  9088. gcode_M118();
  9089. break;
  9090. case 119: // M119: Report endstop states
  9091. gcode_M119();
  9092. break;
  9093. case 120: // M120: Enable endstops
  9094. gcode_M120();
  9095. break;
  9096. case 121: // M121: Disable endstops
  9097. gcode_M121();
  9098. break;
  9099. #if ENABLED(ULTIPANEL)
  9100. case 145: // M145: Set material heatup parameters
  9101. gcode_M145();
  9102. break;
  9103. #endif
  9104. #if ENABLED(TEMPERATURE_UNITS_SUPPORT)
  9105. case 149: // M149: Set temperature units
  9106. gcode_M149();
  9107. break;
  9108. #endif
  9109. #if HAS_COLOR_LEDS
  9110. case 150: // M150: Set Status LED Color
  9111. gcode_M150();
  9112. break;
  9113. #endif // HAS_COLOR_LEDS
  9114. #if ENABLED(MIXING_EXTRUDER)
  9115. case 163: // M163: Set a component weight for mixing extruder
  9116. gcode_M163();
  9117. break;
  9118. #if MIXING_VIRTUAL_TOOLS > 1
  9119. case 164: // M164: Save current mix as a virtual extruder
  9120. gcode_M164();
  9121. break;
  9122. #endif
  9123. #if ENABLED(DIRECT_MIXING_IN_G1)
  9124. case 165: // M165: Set multiple mix weights
  9125. gcode_M165();
  9126. break;
  9127. #endif
  9128. #endif
  9129. case 200: // M200: Set filament diameter, E to cubic units
  9130. gcode_M200();
  9131. break;
  9132. case 201: // M201: Set max acceleration for print moves (units/s^2)
  9133. gcode_M201();
  9134. break;
  9135. #if 0 // Not used for Sprinter/grbl gen6
  9136. case 202: // M202
  9137. gcode_M202();
  9138. break;
  9139. #endif
  9140. case 203: // M203: Set max feedrate (units/sec)
  9141. gcode_M203();
  9142. break;
  9143. case 204: // M204: Set acceleration
  9144. gcode_M204();
  9145. break;
  9146. case 205: //M205: Set advanced settings
  9147. gcode_M205();
  9148. break;
  9149. #if HAS_M206_COMMAND
  9150. case 206: // M206: Set home offsets
  9151. gcode_M206();
  9152. break;
  9153. #endif
  9154. #if ENABLED(DELTA)
  9155. case 665: // M665: Set delta configurations
  9156. gcode_M665();
  9157. break;
  9158. #endif
  9159. #if ENABLED(DELTA) || ENABLED(Z_DUAL_ENDSTOPS)
  9160. case 666: // M666: Set delta or dual endstop adjustment
  9161. gcode_M666();
  9162. break;
  9163. #endif
  9164. #if ENABLED(FWRETRACT)
  9165. case 207: // M207: Set Retract Length, Feedrate, and Z lift
  9166. gcode_M207();
  9167. break;
  9168. case 208: // M208: Set Recover (unretract) Additional Length and Feedrate
  9169. gcode_M208();
  9170. break;
  9171. case 209: // M209: Turn Automatic Retract Detection on/off
  9172. gcode_M209();
  9173. break;
  9174. #endif // FWRETRACT
  9175. case 211: // M211: Enable, Disable, and/or Report software endstops
  9176. gcode_M211();
  9177. break;
  9178. #if HOTENDS > 1
  9179. case 218: // M218: Set a tool offset
  9180. gcode_M218();
  9181. break;
  9182. #endif
  9183. case 220: // M220: Set Feedrate Percentage: S<percent> ("FR" on your LCD)
  9184. gcode_M220();
  9185. break;
  9186. case 221: // M221: Set Flow Percentage
  9187. gcode_M221();
  9188. break;
  9189. case 226: // M226: Wait until a pin reaches a state
  9190. gcode_M226();
  9191. break;
  9192. #if HAS_SERVOS
  9193. case 280: // M280: Set servo position absolute
  9194. gcode_M280();
  9195. break;
  9196. #endif // HAS_SERVOS
  9197. #if HAS_BUZZER
  9198. case 300: // M300: Play beep tone
  9199. gcode_M300();
  9200. break;
  9201. #endif // HAS_BUZZER
  9202. #if ENABLED(PIDTEMP)
  9203. case 301: // M301: Set hotend PID parameters
  9204. gcode_M301();
  9205. break;
  9206. #endif // PIDTEMP
  9207. #if ENABLED(PIDTEMPBED)
  9208. case 304: // M304: Set bed PID parameters
  9209. gcode_M304();
  9210. break;
  9211. #endif // PIDTEMPBED
  9212. #if defined(CHDK) || HAS_PHOTOGRAPH
  9213. case 240: // M240: Trigger a camera by emulating a Canon RC-1 : http://www.doc-diy.net/photo/rc-1_hacked/
  9214. gcode_M240();
  9215. break;
  9216. #endif // CHDK || PHOTOGRAPH_PIN
  9217. #if HAS_LCD_CONTRAST
  9218. case 250: // M250: Set LCD contrast
  9219. gcode_M250();
  9220. break;
  9221. #endif // HAS_LCD_CONTRAST
  9222. #if ENABLED(EXPERIMENTAL_I2CBUS)
  9223. case 260: // M260: Send data to an i2c slave
  9224. gcode_M260();
  9225. break;
  9226. case 261: // M261: Request data from an i2c slave
  9227. gcode_M261();
  9228. break;
  9229. #endif // EXPERIMENTAL_I2CBUS
  9230. #if ENABLED(PREVENT_COLD_EXTRUSION)
  9231. case 302: // M302: Allow cold extrudes (set the minimum extrude temperature)
  9232. gcode_M302();
  9233. break;
  9234. #endif // PREVENT_COLD_EXTRUSION
  9235. case 303: // M303: PID autotune
  9236. gcode_M303();
  9237. break;
  9238. #if ENABLED(MORGAN_SCARA)
  9239. case 360: // M360: SCARA Theta pos1
  9240. if (gcode_M360()) return;
  9241. break;
  9242. case 361: // M361: SCARA Theta pos2
  9243. if (gcode_M361()) return;
  9244. break;
  9245. case 362: // M362: SCARA Psi pos1
  9246. if (gcode_M362()) return;
  9247. break;
  9248. case 363: // M363: SCARA Psi pos2
  9249. if (gcode_M363()) return;
  9250. break;
  9251. case 364: // M364: SCARA Psi pos3 (90 deg to Theta)
  9252. if (gcode_M364()) return;
  9253. break;
  9254. #endif // SCARA
  9255. case 400: // M400: Finish all moves
  9256. gcode_M400();
  9257. break;
  9258. #if HAS_BED_PROBE
  9259. case 401: // M401: Deploy probe
  9260. gcode_M401();
  9261. break;
  9262. case 402: // M402: Stow probe
  9263. gcode_M402();
  9264. break;
  9265. #endif // HAS_BED_PROBE
  9266. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  9267. case 404: // M404: Enter the nominal filament width (3mm, 1.75mm ) N<3.0> or display nominal filament width
  9268. gcode_M404();
  9269. break;
  9270. case 405: // M405: Turn on filament sensor for control
  9271. gcode_M405();
  9272. break;
  9273. case 406: // M406: Turn off filament sensor for control
  9274. gcode_M406();
  9275. break;
  9276. case 407: // M407: Display measured filament diameter
  9277. gcode_M407();
  9278. break;
  9279. #endif // FILAMENT_WIDTH_SENSOR
  9280. #if HAS_LEVELING
  9281. case 420: // M420: Enable/Disable Bed Leveling
  9282. gcode_M420();
  9283. break;
  9284. #endif
  9285. #if ENABLED(MESH_BED_LEVELING) || ENABLED(AUTO_BED_LEVELING_UBL) || ENABLED(AUTO_BED_LEVELING_BILINEAR)
  9286. case 421: // M421: Set a Mesh Bed Leveling Z coordinate
  9287. gcode_M421();
  9288. break;
  9289. #endif
  9290. #if HAS_M206_COMMAND
  9291. case 428: // M428: Apply current_position to home_offset
  9292. gcode_M428();
  9293. break;
  9294. #endif
  9295. case 500: // M500: Store settings in EEPROM
  9296. gcode_M500();
  9297. break;
  9298. case 501: // M501: Read settings from EEPROM
  9299. gcode_M501();
  9300. break;
  9301. case 502: // M502: Revert to default settings
  9302. gcode_M502();
  9303. break;
  9304. #if DISABLED(DISABLE_M503)
  9305. case 503: // M503: print settings currently in memory
  9306. gcode_M503();
  9307. break;
  9308. #endif
  9309. #if ENABLED(ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  9310. case 540: // M540: Set abort on endstop hit for SD printing
  9311. gcode_M540();
  9312. break;
  9313. #endif
  9314. #if HAS_BED_PROBE
  9315. case 851: // M851: Set Z Probe Z Offset
  9316. gcode_M851();
  9317. break;
  9318. #endif // HAS_BED_PROBE
  9319. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  9320. case 600: // M600: Pause for filament change
  9321. gcode_M600();
  9322. break;
  9323. #endif // ADVANCED_PAUSE_FEATURE
  9324. #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(DUAL_NOZZLE_DUPLICATION_MODE)
  9325. case 605: // M605: Set Dual X Carriage movement mode
  9326. gcode_M605();
  9327. break;
  9328. #endif // DUAL_X_CARRIAGE
  9329. #if ENABLED(MK2_MULTIPLEXER)
  9330. case 702: // M702: Unload all extruders
  9331. gcode_M702();
  9332. break;
  9333. #endif
  9334. #if ENABLED(LIN_ADVANCE)
  9335. case 900: // M900: Set advance K factor.
  9336. gcode_M900();
  9337. break;
  9338. #endif
  9339. #if ENABLED(HAVE_TMC2130)
  9340. case 906: // M906: Set motor current in milliamps using axis codes X, Y, Z, E
  9341. gcode_M906();
  9342. break;
  9343. #endif
  9344. case 907: // M907: Set digital trimpot motor current using axis codes.
  9345. gcode_M907();
  9346. break;
  9347. #if HAS_DIGIPOTSS || ENABLED(DAC_STEPPER_CURRENT)
  9348. case 908: // M908: Control digital trimpot directly.
  9349. gcode_M908();
  9350. break;
  9351. #if ENABLED(DAC_STEPPER_CURRENT) // As with Printrbot RevF
  9352. case 909: // M909: Print digipot/DAC current value
  9353. gcode_M909();
  9354. break;
  9355. case 910: // M910: Commit digipot/DAC value to external EEPROM
  9356. gcode_M910();
  9357. break;
  9358. #endif
  9359. #endif // HAS_DIGIPOTSS || DAC_STEPPER_CURRENT
  9360. #if ENABLED(HAVE_TMC2130)
  9361. case 911: // M911: Report TMC2130 prewarn triggered flags
  9362. gcode_M911();
  9363. break;
  9364. case 912: // M911: Clear TMC2130 prewarn triggered flags
  9365. gcode_M912();
  9366. break;
  9367. #if ENABLED(HYBRID_THRESHOLD)
  9368. case 913: // M913: Set HYBRID_THRESHOLD speed.
  9369. gcode_M913();
  9370. break;
  9371. #endif
  9372. #if ENABLED(SENSORLESS_HOMING)
  9373. case 914: // M914: Set SENSORLESS_HOMING sensitivity.
  9374. gcode_M914();
  9375. break;
  9376. #endif
  9377. #endif
  9378. #if HAS_MICROSTEPS
  9379. case 350: // M350: Set microstepping mode. Warning: Steps per unit remains unchanged. S code sets stepping mode for all drivers.
  9380. gcode_M350();
  9381. break;
  9382. case 351: // M351: Toggle MS1 MS2 pins directly, S# determines MS1 or MS2, X# sets the pin high/low.
  9383. gcode_M351();
  9384. break;
  9385. #endif // HAS_MICROSTEPS
  9386. case 355: // M355 set case light brightness
  9387. gcode_M355();
  9388. break;
  9389. #if ENABLED(DEBUG_GCODE_PARSER)
  9390. case 800:
  9391. parser.debug(); // GCode Parser Test for M
  9392. break;
  9393. #endif
  9394. #if ENABLED(I2C_POSITION_ENCODERS)
  9395. case 860: // M860 Report encoder module position
  9396. gcode_M860();
  9397. break;
  9398. case 861: // M861 Report encoder module status
  9399. gcode_M861();
  9400. break;
  9401. case 862: // M862 Perform axis test
  9402. gcode_M862();
  9403. break;
  9404. case 863: // M863 Calibrate steps/mm
  9405. gcode_M863();
  9406. break;
  9407. case 864: // M864 Change module address
  9408. gcode_M864();
  9409. break;
  9410. case 865: // M865 Check module firmware version
  9411. gcode_M865();
  9412. break;
  9413. case 866: // M866 Report axis error count
  9414. gcode_M866();
  9415. break;
  9416. case 867: // M867 Toggle error correction
  9417. gcode_M867();
  9418. break;
  9419. case 868: // M868 Set error correction threshold
  9420. gcode_M868();
  9421. break;
  9422. case 869: // M869 Report axis error
  9423. gcode_M869();
  9424. break;
  9425. #endif // I2C_POSITION_ENCODERS
  9426. case 999: // M999: Restart after being Stopped
  9427. gcode_M999();
  9428. break;
  9429. }
  9430. break;
  9431. case 'T':
  9432. gcode_T(parser.codenum);
  9433. break;
  9434. default: parser.unknown_command_error();
  9435. }
  9436. KEEPALIVE_STATE(NOT_BUSY);
  9437. ok_to_send();
  9438. }
  9439. /**
  9440. * Send a "Resend: nnn" message to the host to
  9441. * indicate that a command needs to be re-sent.
  9442. */
  9443. void FlushSerialRequestResend() {
  9444. //char command_queue[cmd_queue_index_r][100]="Resend:";
  9445. MYSERIAL.flush();
  9446. SERIAL_PROTOCOLPGM(MSG_RESEND);
  9447. SERIAL_PROTOCOLLN(gcode_LastN + 1);
  9448. ok_to_send();
  9449. }
  9450. /**
  9451. * Send an "ok" message to the host, indicating
  9452. * that a command was successfully processed.
  9453. *
  9454. * If ADVANCED_OK is enabled also include:
  9455. * N<int> Line number of the command, if any
  9456. * P<int> Planner space remaining
  9457. * B<int> Block queue space remaining
  9458. */
  9459. void ok_to_send() {
  9460. refresh_cmd_timeout();
  9461. if (!send_ok[cmd_queue_index_r]) return;
  9462. SERIAL_PROTOCOLPGM(MSG_OK);
  9463. #if ENABLED(ADVANCED_OK)
  9464. char* p = command_queue[cmd_queue_index_r];
  9465. if (*p == 'N') {
  9466. SERIAL_PROTOCOL(' ');
  9467. SERIAL_ECHO(*p++);
  9468. while (NUMERIC_SIGNED(*p))
  9469. SERIAL_ECHO(*p++);
  9470. }
  9471. SERIAL_PROTOCOLPGM(" P"); SERIAL_PROTOCOL(int(BLOCK_BUFFER_SIZE - planner.movesplanned() - 1));
  9472. SERIAL_PROTOCOLPGM(" B"); SERIAL_PROTOCOL(BUFSIZE - commands_in_queue);
  9473. #endif
  9474. SERIAL_EOL();
  9475. }
  9476. #if HAS_SOFTWARE_ENDSTOPS
  9477. /**
  9478. * Constrain the given coordinates to the software endstops.
  9479. */
  9480. // NOTE: This makes no sense for delta beds other than Z-axis.
  9481. // For delta the X/Y would need to be clamped at
  9482. // DELTA_PRINTABLE_RADIUS from center of bed, but delta
  9483. // now enforces is_position_reachable for X/Y regardless
  9484. // of HAS_SOFTWARE_ENDSTOPS, so that enforcement would be
  9485. // redundant here. Probably should #ifdef out the X/Y
  9486. // axis clamps here for delta and just leave the Z clamp.
  9487. void clamp_to_software_endstops(float target[XYZ]) {
  9488. if (!soft_endstops_enabled) return;
  9489. #if ENABLED(MIN_SOFTWARE_ENDSTOPS)
  9490. NOLESS(target[X_AXIS], soft_endstop_min[X_AXIS]);
  9491. NOLESS(target[Y_AXIS], soft_endstop_min[Y_AXIS]);
  9492. NOLESS(target[Z_AXIS], soft_endstop_min[Z_AXIS]);
  9493. #endif
  9494. #if ENABLED(MAX_SOFTWARE_ENDSTOPS)
  9495. NOMORE(target[X_AXIS], soft_endstop_max[X_AXIS]);
  9496. NOMORE(target[Y_AXIS], soft_endstop_max[Y_AXIS]);
  9497. NOMORE(target[Z_AXIS], soft_endstop_max[Z_AXIS]);
  9498. #endif
  9499. }
  9500. #endif
  9501. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  9502. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  9503. #define ABL_BG_SPACING(A) bilinear_grid_spacing_virt[A]
  9504. #define ABL_BG_FACTOR(A) bilinear_grid_factor_virt[A]
  9505. #define ABL_BG_POINTS_X ABL_GRID_POINTS_VIRT_X
  9506. #define ABL_BG_POINTS_Y ABL_GRID_POINTS_VIRT_Y
  9507. #define ABL_BG_GRID(X,Y) z_values_virt[X][Y]
  9508. #else
  9509. #define ABL_BG_SPACING(A) bilinear_grid_spacing[A]
  9510. #define ABL_BG_FACTOR(A) bilinear_grid_factor[A]
  9511. #define ABL_BG_POINTS_X GRID_MAX_POINTS_X
  9512. #define ABL_BG_POINTS_Y GRID_MAX_POINTS_Y
  9513. #define ABL_BG_GRID(X,Y) z_values[X][Y]
  9514. #endif
  9515. // Get the Z adjustment for non-linear bed leveling
  9516. float bilinear_z_offset(const float logical[XYZ]) {
  9517. static float z1, d2, z3, d4, L, D, ratio_x, ratio_y,
  9518. last_x = -999.999, last_y = -999.999;
  9519. // Whole units for the grid line indices. Constrained within bounds.
  9520. static int8_t gridx, gridy, nextx, nexty,
  9521. last_gridx = -99, last_gridy = -99;
  9522. // XY relative to the probed area
  9523. const float x = RAW_X_POSITION(logical[X_AXIS]) - bilinear_start[X_AXIS],
  9524. y = RAW_Y_POSITION(logical[Y_AXIS]) - bilinear_start[Y_AXIS];
  9525. #if ENABLED(EXTRAPOLATE_BEYOND_GRID)
  9526. // Keep using the last grid box
  9527. #define FAR_EDGE_OR_BOX 2
  9528. #else
  9529. // Just use the grid far edge
  9530. #define FAR_EDGE_OR_BOX 1
  9531. #endif
  9532. if (last_x != x) {
  9533. last_x = x;
  9534. ratio_x = x * ABL_BG_FACTOR(X_AXIS);
  9535. const float gx = constrain(FLOOR(ratio_x), 0, ABL_BG_POINTS_X - FAR_EDGE_OR_BOX);
  9536. ratio_x -= gx; // Subtract whole to get the ratio within the grid box
  9537. #if DISABLED(EXTRAPOLATE_BEYOND_GRID)
  9538. // Beyond the grid maintain height at grid edges
  9539. NOLESS(ratio_x, 0); // Never < 0.0. (> 1.0 is ok when nextx==gridx.)
  9540. #endif
  9541. gridx = gx;
  9542. nextx = min(gridx + 1, ABL_BG_POINTS_X - 1);
  9543. }
  9544. if (last_y != y || last_gridx != gridx) {
  9545. if (last_y != y) {
  9546. last_y = y;
  9547. ratio_y = y * ABL_BG_FACTOR(Y_AXIS);
  9548. const float gy = constrain(FLOOR(ratio_y), 0, ABL_BG_POINTS_Y - FAR_EDGE_OR_BOX);
  9549. ratio_y -= gy;
  9550. #if DISABLED(EXTRAPOLATE_BEYOND_GRID)
  9551. // Beyond the grid maintain height at grid edges
  9552. NOLESS(ratio_y, 0); // Never < 0.0. (> 1.0 is ok when nexty==gridy.)
  9553. #endif
  9554. gridy = gy;
  9555. nexty = min(gridy + 1, ABL_BG_POINTS_Y - 1);
  9556. }
  9557. if (last_gridx != gridx || last_gridy != gridy) {
  9558. last_gridx = gridx;
  9559. last_gridy = gridy;
  9560. // Z at the box corners
  9561. z1 = ABL_BG_GRID(gridx, gridy); // left-front
  9562. d2 = ABL_BG_GRID(gridx, nexty) - z1; // left-back (delta)
  9563. z3 = ABL_BG_GRID(nextx, gridy); // right-front
  9564. d4 = ABL_BG_GRID(nextx, nexty) - z3; // right-back (delta)
  9565. }
  9566. // Bilinear interpolate. Needed since y or gridx has changed.
  9567. L = z1 + d2 * ratio_y; // Linear interp. LF -> LB
  9568. const float R = z3 + d4 * ratio_y; // Linear interp. RF -> RB
  9569. D = R - L;
  9570. }
  9571. const float offset = L + ratio_x * D; // the offset almost always changes
  9572. /*
  9573. static float last_offset = 0;
  9574. if (FABS(last_offset - offset) > 0.2) {
  9575. SERIAL_ECHOPGM("Sudden Shift at ");
  9576. SERIAL_ECHOPAIR("x=", x);
  9577. SERIAL_ECHOPAIR(" / ", bilinear_grid_spacing[X_AXIS]);
  9578. SERIAL_ECHOLNPAIR(" -> gridx=", gridx);
  9579. SERIAL_ECHOPAIR(" y=", y);
  9580. SERIAL_ECHOPAIR(" / ", bilinear_grid_spacing[Y_AXIS]);
  9581. SERIAL_ECHOLNPAIR(" -> gridy=", gridy);
  9582. SERIAL_ECHOPAIR(" ratio_x=", ratio_x);
  9583. SERIAL_ECHOLNPAIR(" ratio_y=", ratio_y);
  9584. SERIAL_ECHOPAIR(" z1=", z1);
  9585. SERIAL_ECHOPAIR(" z2=", z2);
  9586. SERIAL_ECHOPAIR(" z3=", z3);
  9587. SERIAL_ECHOLNPAIR(" z4=", z4);
  9588. SERIAL_ECHOPAIR(" L=", L);
  9589. SERIAL_ECHOPAIR(" R=", R);
  9590. SERIAL_ECHOLNPAIR(" offset=", offset);
  9591. }
  9592. last_offset = offset;
  9593. //*/
  9594. return offset;
  9595. }
  9596. #endif // AUTO_BED_LEVELING_BILINEAR
  9597. #if ENABLED(DELTA)
  9598. /**
  9599. * Recalculate factors used for delta kinematics whenever
  9600. * settings have been changed (e.g., by M665).
  9601. */
  9602. void recalc_delta_settings(float radius, float diagonal_rod) {
  9603. const float trt[ABC] = DELTA_RADIUS_TRIM_TOWER,
  9604. drt[ABC] = DELTA_DIAGONAL_ROD_TRIM_TOWER;
  9605. delta_tower[A_AXIS][X_AXIS] = cos(RADIANS(210 + delta_tower_angle_trim[A_AXIS])) * (radius + trt[A_AXIS]); // front left tower
  9606. delta_tower[A_AXIS][Y_AXIS] = sin(RADIANS(210 + delta_tower_angle_trim[A_AXIS])) * (radius + trt[A_AXIS]);
  9607. delta_tower[B_AXIS][X_AXIS] = cos(RADIANS(330 + delta_tower_angle_trim[B_AXIS])) * (radius + trt[B_AXIS]); // front right tower
  9608. delta_tower[B_AXIS][Y_AXIS] = sin(RADIANS(330 + delta_tower_angle_trim[B_AXIS])) * (radius + trt[B_AXIS]);
  9609. delta_tower[C_AXIS][X_AXIS] = 0.0; // back middle tower
  9610. delta_tower[C_AXIS][Y_AXIS] = (radius + trt[C_AXIS]);
  9611. delta_diagonal_rod_2_tower[A_AXIS] = sq(diagonal_rod + drt[A_AXIS]);
  9612. delta_diagonal_rod_2_tower[B_AXIS] = sq(diagonal_rod + drt[B_AXIS]);
  9613. delta_diagonal_rod_2_tower[C_AXIS] = sq(diagonal_rod + drt[C_AXIS]);
  9614. }
  9615. #if ENABLED(DELTA_FAST_SQRT)
  9616. /**
  9617. * Fast inverse sqrt from Quake III Arena
  9618. * See: https://en.wikipedia.org/wiki/Fast_inverse_square_root
  9619. */
  9620. float Q_rsqrt(float number) {
  9621. long i;
  9622. float x2, y;
  9623. const float threehalfs = 1.5f;
  9624. x2 = number * 0.5f;
  9625. y = number;
  9626. i = * ( long * ) &y; // evil floating point bit level hacking
  9627. i = 0x5F3759DF - ( i >> 1 ); // what the f***?
  9628. y = * ( float * ) &i;
  9629. y = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration
  9630. // y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed
  9631. return y;
  9632. }
  9633. #define _SQRT(n) (1.0f / Q_rsqrt(n))
  9634. #else
  9635. #define _SQRT(n) SQRT(n)
  9636. #endif
  9637. /**
  9638. * Delta Inverse Kinematics
  9639. *
  9640. * Calculate the tower positions for a given logical
  9641. * position, storing the result in the delta[] array.
  9642. *
  9643. * This is an expensive calculation, requiring 3 square
  9644. * roots per segmented linear move, and strains the limits
  9645. * of a Mega2560 with a Graphical Display.
  9646. *
  9647. * Suggested optimizations include:
  9648. *
  9649. * - Disable the home_offset (M206) and/or position_shift (G92)
  9650. * features to remove up to 12 float additions.
  9651. *
  9652. * - Use a fast-inverse-sqrt function and add the reciprocal.
  9653. * (see above)
  9654. */
  9655. // Macro to obtain the Z position of an individual tower
  9656. #define DELTA_Z(T) raw[Z_AXIS] + _SQRT( \
  9657. delta_diagonal_rod_2_tower[T] - HYPOT2( \
  9658. delta_tower[T][X_AXIS] - raw[X_AXIS], \
  9659. delta_tower[T][Y_AXIS] - raw[Y_AXIS] \
  9660. ) \
  9661. )
  9662. #define DELTA_RAW_IK() do { \
  9663. delta[A_AXIS] = DELTA_Z(A_AXIS); \
  9664. delta[B_AXIS] = DELTA_Z(B_AXIS); \
  9665. delta[C_AXIS] = DELTA_Z(C_AXIS); \
  9666. }while(0)
  9667. #define DELTA_LOGICAL_IK() do { \
  9668. const float raw[XYZ] = { \
  9669. RAW_X_POSITION(logical[X_AXIS]), \
  9670. RAW_Y_POSITION(logical[Y_AXIS]), \
  9671. RAW_Z_POSITION(logical[Z_AXIS]) \
  9672. }; \
  9673. DELTA_RAW_IK(); \
  9674. }while(0)
  9675. #define DELTA_DEBUG() do { \
  9676. SERIAL_ECHOPAIR("cartesian X:", raw[X_AXIS]); \
  9677. SERIAL_ECHOPAIR(" Y:", raw[Y_AXIS]); \
  9678. SERIAL_ECHOLNPAIR(" Z:", raw[Z_AXIS]); \
  9679. SERIAL_ECHOPAIR("delta A:", delta[A_AXIS]); \
  9680. SERIAL_ECHOPAIR(" B:", delta[B_AXIS]); \
  9681. SERIAL_ECHOLNPAIR(" C:", delta[C_AXIS]); \
  9682. }while(0)
  9683. void inverse_kinematics(const float logical[XYZ]) {
  9684. DELTA_LOGICAL_IK();
  9685. // DELTA_DEBUG();
  9686. }
  9687. /**
  9688. * Calculate the highest Z position where the
  9689. * effector has the full range of XY motion.
  9690. */
  9691. float delta_safe_distance_from_top() {
  9692. float cartesian[XYZ] = {
  9693. LOGICAL_X_POSITION(0),
  9694. LOGICAL_Y_POSITION(0),
  9695. LOGICAL_Z_POSITION(0)
  9696. };
  9697. inverse_kinematics(cartesian);
  9698. float distance = delta[A_AXIS];
  9699. cartesian[Y_AXIS] = LOGICAL_Y_POSITION(DELTA_PRINTABLE_RADIUS);
  9700. inverse_kinematics(cartesian);
  9701. return FABS(distance - delta[A_AXIS]);
  9702. }
  9703. /**
  9704. * Delta Forward Kinematics
  9705. *
  9706. * See the Wikipedia article "Trilateration"
  9707. * https://en.wikipedia.org/wiki/Trilateration
  9708. *
  9709. * Establish a new coordinate system in the plane of the
  9710. * three carriage points. This system has its origin at
  9711. * tower1, with tower2 on the X axis. Tower3 is in the X-Y
  9712. * plane with a Z component of zero.
  9713. * We will define unit vectors in this coordinate system
  9714. * in our original coordinate system. Then when we calculate
  9715. * the Xnew, Ynew and Znew values, we can translate back into
  9716. * the original system by moving along those unit vectors
  9717. * by the corresponding values.
  9718. *
  9719. * Variable names matched to Marlin, c-version, and avoid the
  9720. * use of any vector library.
  9721. *
  9722. * by Andreas Hardtung 2016-06-07
  9723. * based on a Java function from "Delta Robot Kinematics V3"
  9724. * by Steve Graves
  9725. *
  9726. * The result is stored in the cartes[] array.
  9727. */
  9728. void forward_kinematics_DELTA(float z1, float z2, float z3) {
  9729. // Create a vector in old coordinates along x axis of new coordinate
  9730. float p12[3] = { delta_tower[B_AXIS][X_AXIS] - delta_tower[A_AXIS][X_AXIS], delta_tower[B_AXIS][Y_AXIS] - delta_tower[A_AXIS][Y_AXIS], z2 - z1 };
  9731. // Get the Magnitude of vector.
  9732. float d = SQRT( sq(p12[0]) + sq(p12[1]) + sq(p12[2]) );
  9733. // Create unit vector by dividing by magnitude.
  9734. float ex[3] = { p12[0] / d, p12[1] / d, p12[2] / d };
  9735. // Get the vector from the origin of the new system to the third point.
  9736. float p13[3] = { delta_tower[C_AXIS][X_AXIS] - delta_tower[A_AXIS][X_AXIS], delta_tower[C_AXIS][Y_AXIS] - delta_tower[A_AXIS][Y_AXIS], z3 - z1 };
  9737. // Use the dot product to find the component of this vector on the X axis.
  9738. float i = ex[0] * p13[0] + ex[1] * p13[1] + ex[2] * p13[2];
  9739. // Create a vector along the x axis that represents the x component of p13.
  9740. float iex[3] = { ex[0] * i, ex[1] * i, ex[2] * i };
  9741. // Subtract the X component from the original vector leaving only Y. We use the
  9742. // variable that will be the unit vector after we scale it.
  9743. float ey[3] = { p13[0] - iex[0], p13[1] - iex[1], p13[2] - iex[2] };
  9744. // The magnitude of Y component
  9745. float j = SQRT( sq(ey[0]) + sq(ey[1]) + sq(ey[2]) );
  9746. // Convert to a unit vector
  9747. ey[0] /= j; ey[1] /= j; ey[2] /= j;
  9748. // The cross product of the unit x and y is the unit z
  9749. // float[] ez = vectorCrossProd(ex, ey);
  9750. float ez[3] = {
  9751. ex[1] * ey[2] - ex[2] * ey[1],
  9752. ex[2] * ey[0] - ex[0] * ey[2],
  9753. ex[0] * ey[1] - ex[1] * ey[0]
  9754. };
  9755. // We now have the d, i and j values defined in Wikipedia.
  9756. // Plug them into the equations defined in Wikipedia for Xnew, Ynew and Znew
  9757. float Xnew = (delta_diagonal_rod_2_tower[A_AXIS] - delta_diagonal_rod_2_tower[B_AXIS] + sq(d)) / (d * 2),
  9758. Ynew = ((delta_diagonal_rod_2_tower[A_AXIS] - delta_diagonal_rod_2_tower[C_AXIS] + HYPOT2(i, j)) / 2 - i * Xnew) / j,
  9759. Znew = SQRT(delta_diagonal_rod_2_tower[A_AXIS] - HYPOT2(Xnew, Ynew));
  9760. // Start from the origin of the old coordinates and add vectors in the
  9761. // old coords that represent the Xnew, Ynew and Znew to find the point
  9762. // in the old system.
  9763. cartes[X_AXIS] = delta_tower[A_AXIS][X_AXIS] + ex[0] * Xnew + ey[0] * Ynew - ez[0] * Znew;
  9764. cartes[Y_AXIS] = delta_tower[A_AXIS][Y_AXIS] + ex[1] * Xnew + ey[1] * Ynew - ez[1] * Znew;
  9765. cartes[Z_AXIS] = z1 + ex[2] * Xnew + ey[2] * Ynew - ez[2] * Znew;
  9766. }
  9767. void forward_kinematics_DELTA(float point[ABC]) {
  9768. forward_kinematics_DELTA(point[A_AXIS], point[B_AXIS], point[C_AXIS]);
  9769. }
  9770. #endif // DELTA
  9771. /**
  9772. * Get the stepper positions in the cartes[] array.
  9773. * Forward kinematics are applied for DELTA and SCARA.
  9774. *
  9775. * The result is in the current coordinate space with
  9776. * leveling applied. The coordinates need to be run through
  9777. * unapply_leveling to obtain the "ideal" coordinates
  9778. * suitable for current_position, etc.
  9779. */
  9780. void get_cartesian_from_steppers() {
  9781. #if ENABLED(DELTA)
  9782. forward_kinematics_DELTA(
  9783. stepper.get_axis_position_mm(A_AXIS),
  9784. stepper.get_axis_position_mm(B_AXIS),
  9785. stepper.get_axis_position_mm(C_AXIS)
  9786. );
  9787. cartes[X_AXIS] += LOGICAL_X_POSITION(0);
  9788. cartes[Y_AXIS] += LOGICAL_Y_POSITION(0);
  9789. cartes[Z_AXIS] += LOGICAL_Z_POSITION(0);
  9790. #elif IS_SCARA
  9791. forward_kinematics_SCARA(
  9792. stepper.get_axis_position_degrees(A_AXIS),
  9793. stepper.get_axis_position_degrees(B_AXIS)
  9794. );
  9795. cartes[X_AXIS] += LOGICAL_X_POSITION(0);
  9796. cartes[Y_AXIS] += LOGICAL_Y_POSITION(0);
  9797. cartes[Z_AXIS] = stepper.get_axis_position_mm(Z_AXIS);
  9798. #else
  9799. cartes[X_AXIS] = stepper.get_axis_position_mm(X_AXIS);
  9800. cartes[Y_AXIS] = stepper.get_axis_position_mm(Y_AXIS);
  9801. cartes[Z_AXIS] = stepper.get_axis_position_mm(Z_AXIS);
  9802. #endif
  9803. }
  9804. /**
  9805. * Set the current_position for an axis based on
  9806. * the stepper positions, removing any leveling that
  9807. * may have been applied.
  9808. */
  9809. void set_current_from_steppers_for_axis(const AxisEnum axis) {
  9810. get_cartesian_from_steppers();
  9811. #if PLANNER_LEVELING
  9812. planner.unapply_leveling(cartes);
  9813. #endif
  9814. if (axis == ALL_AXES)
  9815. COPY(current_position, cartes);
  9816. else
  9817. current_position[axis] = cartes[axis];
  9818. }
  9819. #if ENABLED(MESH_BED_LEVELING)
  9820. /**
  9821. * Prepare a mesh-leveled linear move in a Cartesian setup,
  9822. * splitting the move where it crosses mesh borders.
  9823. */
  9824. void mesh_line_to_destination(float fr_mm_s, uint8_t x_splits = 0xFF, uint8_t y_splits = 0xFF) {
  9825. int cx1 = mbl.cell_index_x(RAW_CURRENT_POSITION(X)),
  9826. cy1 = mbl.cell_index_y(RAW_CURRENT_POSITION(Y)),
  9827. cx2 = mbl.cell_index_x(RAW_X_POSITION(destination[X_AXIS])),
  9828. cy2 = mbl.cell_index_y(RAW_Y_POSITION(destination[Y_AXIS]));
  9829. NOMORE(cx1, GRID_MAX_POINTS_X - 2);
  9830. NOMORE(cy1, GRID_MAX_POINTS_Y - 2);
  9831. NOMORE(cx2, GRID_MAX_POINTS_X - 2);
  9832. NOMORE(cy2, GRID_MAX_POINTS_Y - 2);
  9833. if (cx1 == cx2 && cy1 == cy2) {
  9834. // Start and end on same mesh square
  9835. line_to_destination(fr_mm_s);
  9836. set_current_to_destination();
  9837. return;
  9838. }
  9839. #define MBL_SEGMENT_END(A) (current_position[A ##_AXIS] + (destination[A ##_AXIS] - current_position[A ##_AXIS]) * normalized_dist)
  9840. float normalized_dist, end[XYZE];
  9841. // Split at the left/front border of the right/top square
  9842. const int8_t gcx = max(cx1, cx2), gcy = max(cy1, cy2);
  9843. if (cx2 != cx1 && TEST(x_splits, gcx)) {
  9844. COPY(end, destination);
  9845. destination[X_AXIS] = LOGICAL_X_POSITION(mbl.index_to_xpos[gcx]);
  9846. normalized_dist = (destination[X_AXIS] - current_position[X_AXIS]) / (end[X_AXIS] - current_position[X_AXIS]);
  9847. destination[Y_AXIS] = MBL_SEGMENT_END(Y);
  9848. CBI(x_splits, gcx);
  9849. }
  9850. else if (cy2 != cy1 && TEST(y_splits, gcy)) {
  9851. COPY(end, destination);
  9852. destination[Y_AXIS] = LOGICAL_Y_POSITION(mbl.index_to_ypos[gcy]);
  9853. normalized_dist = (destination[Y_AXIS] - current_position[Y_AXIS]) / (end[Y_AXIS] - current_position[Y_AXIS]);
  9854. destination[X_AXIS] = MBL_SEGMENT_END(X);
  9855. CBI(y_splits, gcy);
  9856. }
  9857. else {
  9858. // Already split on a border
  9859. line_to_destination(fr_mm_s);
  9860. set_current_to_destination();
  9861. return;
  9862. }
  9863. destination[Z_AXIS] = MBL_SEGMENT_END(Z);
  9864. destination[E_AXIS] = MBL_SEGMENT_END(E);
  9865. // Do the split and look for more borders
  9866. mesh_line_to_destination(fr_mm_s, x_splits, y_splits);
  9867. // Restore destination from stack
  9868. COPY(destination, end);
  9869. mesh_line_to_destination(fr_mm_s, x_splits, y_splits);
  9870. }
  9871. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR) && !IS_KINEMATIC
  9872. #define CELL_INDEX(A,V) ((RAW_##A##_POSITION(V) - bilinear_start[A##_AXIS]) * ABL_BG_FACTOR(A##_AXIS))
  9873. /**
  9874. * Prepare a bilinear-leveled linear move on Cartesian,
  9875. * splitting the move where it crosses grid borders.
  9876. */
  9877. void bilinear_line_to_destination(float fr_mm_s, uint16_t x_splits = 0xFFFF, uint16_t y_splits = 0xFFFF) {
  9878. int cx1 = CELL_INDEX(X, current_position[X_AXIS]),
  9879. cy1 = CELL_INDEX(Y, current_position[Y_AXIS]),
  9880. cx2 = CELL_INDEX(X, destination[X_AXIS]),
  9881. cy2 = CELL_INDEX(Y, destination[Y_AXIS]);
  9882. cx1 = constrain(cx1, 0, ABL_BG_POINTS_X - 2);
  9883. cy1 = constrain(cy1, 0, ABL_BG_POINTS_Y - 2);
  9884. cx2 = constrain(cx2, 0, ABL_BG_POINTS_X - 2);
  9885. cy2 = constrain(cy2, 0, ABL_BG_POINTS_Y - 2);
  9886. if (cx1 == cx2 && cy1 == cy2) {
  9887. // Start and end on same mesh square
  9888. line_to_destination(fr_mm_s);
  9889. set_current_to_destination();
  9890. return;
  9891. }
  9892. #define LINE_SEGMENT_END(A) (current_position[A ##_AXIS] + (destination[A ##_AXIS] - current_position[A ##_AXIS]) * normalized_dist)
  9893. float normalized_dist, end[XYZE];
  9894. // Split at the left/front border of the right/top square
  9895. const int8_t gcx = max(cx1, cx2), gcy = max(cy1, cy2);
  9896. if (cx2 != cx1 && TEST(x_splits, gcx)) {
  9897. COPY(end, destination);
  9898. destination[X_AXIS] = LOGICAL_X_POSITION(bilinear_start[X_AXIS] + ABL_BG_SPACING(X_AXIS) * gcx);
  9899. normalized_dist = (destination[X_AXIS] - current_position[X_AXIS]) / (end[X_AXIS] - current_position[X_AXIS]);
  9900. destination[Y_AXIS] = LINE_SEGMENT_END(Y);
  9901. CBI(x_splits, gcx);
  9902. }
  9903. else if (cy2 != cy1 && TEST(y_splits, gcy)) {
  9904. COPY(end, destination);
  9905. destination[Y_AXIS] = LOGICAL_Y_POSITION(bilinear_start[Y_AXIS] + ABL_BG_SPACING(Y_AXIS) * gcy);
  9906. normalized_dist = (destination[Y_AXIS] - current_position[Y_AXIS]) / (end[Y_AXIS] - current_position[Y_AXIS]);
  9907. destination[X_AXIS] = LINE_SEGMENT_END(X);
  9908. CBI(y_splits, gcy);
  9909. }
  9910. else {
  9911. // Already split on a border
  9912. line_to_destination(fr_mm_s);
  9913. set_current_to_destination();
  9914. return;
  9915. }
  9916. destination[Z_AXIS] = LINE_SEGMENT_END(Z);
  9917. destination[E_AXIS] = LINE_SEGMENT_END(E);
  9918. // Do the split and look for more borders
  9919. bilinear_line_to_destination(fr_mm_s, x_splits, y_splits);
  9920. // Restore destination from stack
  9921. COPY(destination, end);
  9922. bilinear_line_to_destination(fr_mm_s, x_splits, y_splits);
  9923. }
  9924. #endif // AUTO_BED_LEVELING_BILINEAR
  9925. #if IS_KINEMATIC && !UBL_DELTA
  9926. /**
  9927. * Prepare a linear move in a DELTA or SCARA setup.
  9928. *
  9929. * This calls planner.buffer_line several times, adding
  9930. * small incremental moves for DELTA or SCARA.
  9931. */
  9932. inline bool prepare_kinematic_move_to(float ltarget[XYZE]) {
  9933. // Get the top feedrate of the move in the XY plane
  9934. const float _feedrate_mm_s = MMS_SCALED(feedrate_mm_s);
  9935. // If the move is only in Z/E don't split up the move
  9936. if (ltarget[X_AXIS] == current_position[X_AXIS] && ltarget[Y_AXIS] == current_position[Y_AXIS]) {
  9937. planner.buffer_line_kinematic(ltarget, _feedrate_mm_s, active_extruder);
  9938. return false;
  9939. }
  9940. // Fail if attempting move outside printable radius
  9941. if (!position_is_reachable_xy(ltarget[X_AXIS], ltarget[Y_AXIS])) return true;
  9942. // Get the cartesian distances moved in XYZE
  9943. const float difference[XYZE] = {
  9944. ltarget[X_AXIS] - current_position[X_AXIS],
  9945. ltarget[Y_AXIS] - current_position[Y_AXIS],
  9946. ltarget[Z_AXIS] - current_position[Z_AXIS],
  9947. ltarget[E_AXIS] - current_position[E_AXIS]
  9948. };
  9949. // Get the linear distance in XYZ
  9950. float cartesian_mm = SQRT(sq(difference[X_AXIS]) + sq(difference[Y_AXIS]) + sq(difference[Z_AXIS]));
  9951. // If the move is very short, check the E move distance
  9952. if (UNEAR_ZERO(cartesian_mm)) cartesian_mm = FABS(difference[E_AXIS]);
  9953. // No E move either? Game over.
  9954. if (UNEAR_ZERO(cartesian_mm)) return true;
  9955. // Minimum number of seconds to move the given distance
  9956. const float seconds = cartesian_mm / _feedrate_mm_s;
  9957. // The number of segments-per-second times the duration
  9958. // gives the number of segments
  9959. uint16_t segments = delta_segments_per_second * seconds;
  9960. // For SCARA minimum segment size is 0.25mm
  9961. #if IS_SCARA
  9962. NOMORE(segments, cartesian_mm * 4);
  9963. #endif
  9964. // At least one segment is required
  9965. NOLESS(segments, 1);
  9966. // The approximate length of each segment
  9967. const float inv_segments = 1.0 / float(segments),
  9968. segment_distance[XYZE] = {
  9969. difference[X_AXIS] * inv_segments,
  9970. difference[Y_AXIS] * inv_segments,
  9971. difference[Z_AXIS] * inv_segments,
  9972. difference[E_AXIS] * inv_segments
  9973. };
  9974. // SERIAL_ECHOPAIR("mm=", cartesian_mm);
  9975. // SERIAL_ECHOPAIR(" seconds=", seconds);
  9976. // SERIAL_ECHOLNPAIR(" segments=", segments);
  9977. #if IS_SCARA && ENABLED(SCARA_FEEDRATE_SCALING)
  9978. // SCARA needs to scale the feed rate from mm/s to degrees/s
  9979. const float inv_segment_length = min(10.0, float(segments) / cartesian_mm), // 1/mm/segs
  9980. feed_factor = inv_segment_length * _feedrate_mm_s;
  9981. float oldA = stepper.get_axis_position_degrees(A_AXIS),
  9982. oldB = stepper.get_axis_position_degrees(B_AXIS);
  9983. #endif
  9984. // Get the logical current position as starting point
  9985. float logical[XYZE];
  9986. COPY(logical, current_position);
  9987. // Drop one segment so the last move is to the exact target.
  9988. // If there's only 1 segment, loops will be skipped entirely.
  9989. --segments;
  9990. // Calculate and execute the segments
  9991. for (uint16_t s = segments + 1; --s;) {
  9992. LOOP_XYZE(i) logical[i] += segment_distance[i];
  9993. #if ENABLED(DELTA)
  9994. DELTA_LOGICAL_IK(); // Delta can inline its kinematics
  9995. #else
  9996. inverse_kinematics(logical);
  9997. #endif
  9998. ADJUST_DELTA(logical); // Adjust Z if bed leveling is enabled
  9999. #if IS_SCARA && ENABLED(SCARA_FEEDRATE_SCALING)
  10000. // For SCARA scale the feed rate from mm/s to degrees/s
  10001. // Use ratio between the length of the move and the larger angle change
  10002. const float adiff = abs(delta[A_AXIS] - oldA),
  10003. bdiff = abs(delta[B_AXIS] - oldB);
  10004. planner.buffer_line(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], logical[E_AXIS], max(adiff, bdiff) * feed_factor, active_extruder);
  10005. oldA = delta[A_AXIS];
  10006. oldB = delta[B_AXIS];
  10007. #else
  10008. planner.buffer_line(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], logical[E_AXIS], _feedrate_mm_s, active_extruder);
  10009. #endif
  10010. }
  10011. // Since segment_distance is only approximate,
  10012. // the final move must be to the exact destination.
  10013. #if IS_SCARA && ENABLED(SCARA_FEEDRATE_SCALING)
  10014. // For SCARA scale the feed rate from mm/s to degrees/s
  10015. // With segments > 1 length is 1 segment, otherwise total length
  10016. inverse_kinematics(ltarget);
  10017. ADJUST_DELTA(ltarget);
  10018. const float adiff = abs(delta[A_AXIS] - oldA),
  10019. bdiff = abs(delta[B_AXIS] - oldB);
  10020. planner.buffer_line(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], logical[E_AXIS], max(adiff, bdiff) * feed_factor, active_extruder);
  10021. #else
  10022. planner.buffer_line_kinematic(ltarget, _feedrate_mm_s, active_extruder);
  10023. #endif
  10024. return false;
  10025. }
  10026. #else // !IS_KINEMATIC || UBL_DELTA
  10027. /**
  10028. * Prepare a linear move in a Cartesian setup.
  10029. * If Mesh Bed Leveling is enabled, perform a mesh move.
  10030. *
  10031. * Returns true if the caller didn't update current_position.
  10032. */
  10033. inline bool prepare_move_to_destination_cartesian() {
  10034. #if ENABLED(AUTO_BED_LEVELING_UBL)
  10035. const float fr_scaled = MMS_SCALED(feedrate_mm_s);
  10036. if (ubl.state.active) { // direct use of ubl.state.active for speed
  10037. ubl.line_to_destination_cartesian(fr_scaled, active_extruder);
  10038. return true;
  10039. }
  10040. else
  10041. line_to_destination(fr_scaled);
  10042. #else
  10043. // Do not use feedrate_percentage for E or Z only moves
  10044. if (current_position[X_AXIS] == destination[X_AXIS] && current_position[Y_AXIS] == destination[Y_AXIS])
  10045. line_to_destination();
  10046. else {
  10047. const float fr_scaled = MMS_SCALED(feedrate_mm_s);
  10048. #if ENABLED(MESH_BED_LEVELING)
  10049. if (mbl.active()) { // direct used of mbl.active() for speed
  10050. mesh_line_to_destination(fr_scaled);
  10051. return true;
  10052. }
  10053. else
  10054. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  10055. if (planner.abl_enabled) { // direct use of abl_enabled for speed
  10056. bilinear_line_to_destination(fr_scaled);
  10057. return true;
  10058. }
  10059. else
  10060. #endif
  10061. line_to_destination(fr_scaled);
  10062. }
  10063. #endif
  10064. return false;
  10065. }
  10066. #endif // !IS_KINEMATIC || UBL_DELTA
  10067. #if ENABLED(DUAL_X_CARRIAGE)
  10068. /**
  10069. * Prepare a linear move in a dual X axis setup
  10070. */
  10071. inline bool prepare_move_to_destination_dualx() {
  10072. if (active_extruder_parked) {
  10073. switch (dual_x_carriage_mode) {
  10074. case DXC_FULL_CONTROL_MODE:
  10075. break;
  10076. case DXC_AUTO_PARK_MODE:
  10077. if (current_position[E_AXIS] == destination[E_AXIS]) {
  10078. // This is a travel move (with no extrusion)
  10079. // Skip it, but keep track of the current position
  10080. // (so it can be used as the start of the next non-travel move)
  10081. if (delayed_move_time != 0xFFFFFFFFUL) {
  10082. set_current_to_destination();
  10083. NOLESS(raised_parked_position[Z_AXIS], destination[Z_AXIS]);
  10084. delayed_move_time = millis();
  10085. return true;
  10086. }
  10087. }
  10088. // unpark extruder: 1) raise, 2) move into starting XY position, 3) lower
  10089. for (uint8_t i = 0; i < 3; i++)
  10090. planner.buffer_line(
  10091. i == 0 ? raised_parked_position[X_AXIS] : current_position[X_AXIS],
  10092. i == 0 ? raised_parked_position[Y_AXIS] : current_position[Y_AXIS],
  10093. i == 2 ? current_position[Z_AXIS] : raised_parked_position[Z_AXIS],
  10094. current_position[E_AXIS],
  10095. i == 1 ? PLANNER_XY_FEEDRATE() : planner.max_feedrate_mm_s[Z_AXIS],
  10096. active_extruder
  10097. );
  10098. delayed_move_time = 0;
  10099. active_extruder_parked = false;
  10100. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10101. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Clear active_extruder_parked");
  10102. #endif
  10103. break;
  10104. case DXC_DUPLICATION_MODE:
  10105. if (active_extruder == 0) {
  10106. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10107. if (DEBUGGING(LEVELING)) {
  10108. SERIAL_ECHOPAIR("Set planner X", LOGICAL_X_POSITION(inactive_extruder_x_pos));
  10109. SERIAL_ECHOLNPAIR(" ... Line to X", current_position[X_AXIS] + duplicate_extruder_x_offset);
  10110. }
  10111. #endif
  10112. // move duplicate extruder into correct duplication position.
  10113. planner.set_position_mm(
  10114. LOGICAL_X_POSITION(inactive_extruder_x_pos),
  10115. current_position[Y_AXIS],
  10116. current_position[Z_AXIS],
  10117. current_position[E_AXIS]
  10118. );
  10119. planner.buffer_line(
  10120. current_position[X_AXIS] + duplicate_extruder_x_offset,
  10121. current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS],
  10122. planner.max_feedrate_mm_s[X_AXIS], 1
  10123. );
  10124. SYNC_PLAN_POSITION_KINEMATIC();
  10125. stepper.synchronize();
  10126. extruder_duplication_enabled = true;
  10127. active_extruder_parked = false;
  10128. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10129. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Set extruder_duplication_enabled\nClear active_extruder_parked");
  10130. #endif
  10131. }
  10132. else {
  10133. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10134. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Active extruder not 0");
  10135. #endif
  10136. }
  10137. break;
  10138. }
  10139. }
  10140. return false;
  10141. }
  10142. #endif // DUAL_X_CARRIAGE
  10143. /**
  10144. * Prepare a single move and get ready for the next one
  10145. *
  10146. * This may result in several calls to planner.buffer_line to
  10147. * do smaller moves for DELTA, SCARA, mesh moves, etc.
  10148. */
  10149. void prepare_move_to_destination() {
  10150. clamp_to_software_endstops(destination);
  10151. refresh_cmd_timeout();
  10152. #if ENABLED(PREVENT_COLD_EXTRUSION)
  10153. if (!DEBUGGING(DRYRUN)) {
  10154. if (destination[E_AXIS] != current_position[E_AXIS]) {
  10155. if (thermalManager.tooColdToExtrude(active_extruder)) {
  10156. current_position[E_AXIS] = destination[E_AXIS]; // Behave as if the move really took place, but ignore E part
  10157. SERIAL_ECHO_START();
  10158. SERIAL_ECHOLNPGM(MSG_ERR_COLD_EXTRUDE_STOP);
  10159. }
  10160. #if ENABLED(PREVENT_LENGTHY_EXTRUDE)
  10161. if (destination[E_AXIS] - current_position[E_AXIS] > EXTRUDE_MAXLENGTH) {
  10162. current_position[E_AXIS] = destination[E_AXIS]; // Behave as if the move really took place, but ignore E part
  10163. SERIAL_ECHO_START();
  10164. SERIAL_ECHOLNPGM(MSG_ERR_LONG_EXTRUDE_STOP);
  10165. }
  10166. #endif
  10167. }
  10168. }
  10169. #endif
  10170. if (
  10171. #if UBL_DELTA // Also works for CARTESIAN (smaller segments follow mesh more closely)
  10172. ubl.prepare_segmented_line_to(destination, feedrate_mm_s)
  10173. #elif IS_KINEMATIC
  10174. prepare_kinematic_move_to(destination)
  10175. #elif ENABLED(DUAL_X_CARRIAGE)
  10176. prepare_move_to_destination_dualx()
  10177. #else
  10178. prepare_move_to_destination_cartesian()
  10179. #endif
  10180. ) return;
  10181. set_current_to_destination();
  10182. }
  10183. #if ENABLED(ARC_SUPPORT)
  10184. #if N_ARC_CORRECTION < 1
  10185. #undef N_ARC_CORRECTION
  10186. #define N_ARC_CORRECTION 1
  10187. #endif
  10188. /**
  10189. * Plan an arc in 2 dimensions
  10190. *
  10191. * The arc is approximated by generating many small linear segments.
  10192. * The length of each segment is configured in MM_PER_ARC_SEGMENT (Default 1mm)
  10193. * Arcs should only be made relatively large (over 5mm), as larger arcs with
  10194. * larger segments will tend to be more efficient. Your slicer should have
  10195. * options for G2/G3 arc generation. In future these options may be GCode tunable.
  10196. */
  10197. void plan_arc(
  10198. float logical[XYZE], // Destination position
  10199. float *offset, // Center of rotation relative to current_position
  10200. uint8_t clockwise // Clockwise?
  10201. ) {
  10202. #if ENABLED(CNC_WORKSPACE_PLANES)
  10203. AxisEnum p_axis, q_axis, l_axis;
  10204. switch (workspace_plane) {
  10205. case PLANE_XY: p_axis = X_AXIS; q_axis = Y_AXIS; l_axis = Z_AXIS; break;
  10206. case PLANE_ZX: p_axis = Z_AXIS; q_axis = X_AXIS; l_axis = Y_AXIS; break;
  10207. case PLANE_YZ: p_axis = Y_AXIS; q_axis = Z_AXIS; l_axis = X_AXIS; break;
  10208. }
  10209. #else
  10210. constexpr AxisEnum p_axis = X_AXIS, q_axis = Y_AXIS, l_axis = Z_AXIS;
  10211. #endif
  10212. // Radius vector from center to current location
  10213. float r_P = -offset[0], r_Q = -offset[1];
  10214. const float radius = HYPOT(r_P, r_Q),
  10215. center_P = current_position[p_axis] - r_P,
  10216. center_Q = current_position[q_axis] - r_Q,
  10217. rt_X = logical[p_axis] - center_P,
  10218. rt_Y = logical[q_axis] - center_Q,
  10219. linear_travel = logical[l_axis] - current_position[l_axis],
  10220. extruder_travel = logical[E_AXIS] - current_position[E_AXIS];
  10221. // CCW angle of rotation between position and target from the circle center. Only one atan2() trig computation required.
  10222. float angular_travel = ATAN2(r_P * rt_Y - r_Q * rt_X, r_P * rt_X + r_Q * rt_Y);
  10223. if (angular_travel < 0) angular_travel += RADIANS(360);
  10224. if (clockwise) angular_travel -= RADIANS(360);
  10225. // Make a circle if the angular rotation is 0 and the target is current position
  10226. if (angular_travel == 0 && current_position[p_axis] == logical[p_axis] && current_position[q_axis] == logical[q_axis])
  10227. angular_travel = RADIANS(360);
  10228. const float mm_of_travel = HYPOT(angular_travel * radius, FABS(linear_travel));
  10229. if (mm_of_travel < 0.001) return;
  10230. uint16_t segments = FLOOR(mm_of_travel / (MM_PER_ARC_SEGMENT));
  10231. if (segments == 0) segments = 1;
  10232. /**
  10233. * Vector rotation by transformation matrix: r is the original vector, r_T is the rotated vector,
  10234. * and phi is the angle of rotation. Based on the solution approach by Jens Geisler.
  10235. * r_T = [cos(phi) -sin(phi);
  10236. * sin(phi) cos(phi)] * r ;
  10237. *
  10238. * For arc generation, the center of the circle is the axis of rotation and the radius vector is
  10239. * defined from the circle center to the initial position. Each line segment is formed by successive
  10240. * vector rotations. This requires only two cos() and sin() computations to form the rotation
  10241. * matrix for the duration of the entire arc. Error may accumulate from numerical round-off, since
  10242. * all double numbers are single precision on the Arduino. (True double precision will not have
  10243. * round off issues for CNC applications.) Single precision error can accumulate to be greater than
  10244. * tool precision in some cases. Therefore, arc path correction is implemented.
  10245. *
  10246. * Small angle approximation may be used to reduce computation overhead further. This approximation
  10247. * holds for everything, but very small circles and large MM_PER_ARC_SEGMENT values. In other words,
  10248. * theta_per_segment would need to be greater than 0.1 rad and N_ARC_CORRECTION would need to be large
  10249. * to cause an appreciable drift error. N_ARC_CORRECTION~=25 is more than small enough to correct for
  10250. * numerical drift error. N_ARC_CORRECTION may be on the order a hundred(s) before error becomes an
  10251. * issue for CNC machines with the single precision Arduino calculations.
  10252. *
  10253. * This approximation also allows plan_arc to immediately insert a line segment into the planner
  10254. * without the initial overhead of computing cos() or sin(). By the time the arc needs to be applied
  10255. * a correction, the planner should have caught up to the lag caused by the initial plan_arc overhead.
  10256. * This is important when there are successive arc motions.
  10257. */
  10258. // Vector rotation matrix values
  10259. float arc_target[XYZE];
  10260. const float theta_per_segment = angular_travel / segments,
  10261. linear_per_segment = linear_travel / segments,
  10262. extruder_per_segment = extruder_travel / segments,
  10263. sin_T = theta_per_segment,
  10264. cos_T = 1 - 0.5 * sq(theta_per_segment); // Small angle approximation
  10265. // Initialize the linear axis
  10266. arc_target[l_axis] = current_position[l_axis];
  10267. // Initialize the extruder axis
  10268. arc_target[E_AXIS] = current_position[E_AXIS];
  10269. const float fr_mm_s = MMS_SCALED(feedrate_mm_s);
  10270. millis_t next_idle_ms = millis() + 200UL;
  10271. #if N_ARC_CORRECTION > 1
  10272. int8_t count = N_ARC_CORRECTION;
  10273. #endif
  10274. for (uint16_t i = 1; i < segments; i++) { // Iterate (segments-1) times
  10275. thermalManager.manage_heater();
  10276. if (ELAPSED(millis(), next_idle_ms)) {
  10277. next_idle_ms = millis() + 200UL;
  10278. idle();
  10279. }
  10280. #if N_ARC_CORRECTION > 1
  10281. if (--count) {
  10282. // Apply vector rotation matrix to previous r_P / 1
  10283. const float r_new_Y = r_P * sin_T + r_Q * cos_T;
  10284. r_P = r_P * cos_T - r_Q * sin_T;
  10285. r_Q = r_new_Y;
  10286. }
  10287. else
  10288. #endif
  10289. {
  10290. #if N_ARC_CORRECTION > 1
  10291. count = N_ARC_CORRECTION;
  10292. #endif
  10293. // Arc correction to radius vector. Computed only every N_ARC_CORRECTION increments.
  10294. // Compute exact location by applying transformation matrix from initial radius vector(=-offset).
  10295. // To reduce stuttering, the sin and cos could be computed at different times.
  10296. // For now, compute both at the same time.
  10297. const float cos_Ti = cos(i * theta_per_segment), sin_Ti = sin(i * theta_per_segment);
  10298. r_P = -offset[0] * cos_Ti + offset[1] * sin_Ti;
  10299. r_Q = -offset[0] * sin_Ti - offset[1] * cos_Ti;
  10300. }
  10301. // Update arc_target location
  10302. arc_target[p_axis] = center_P + r_P;
  10303. arc_target[q_axis] = center_Q + r_Q;
  10304. arc_target[l_axis] += linear_per_segment;
  10305. arc_target[E_AXIS] += extruder_per_segment;
  10306. clamp_to_software_endstops(arc_target);
  10307. planner.buffer_line_kinematic(arc_target, fr_mm_s, active_extruder);
  10308. }
  10309. // Ensure last segment arrives at target location.
  10310. planner.buffer_line_kinematic(logical, fr_mm_s, active_extruder);
  10311. // As far as the parser is concerned, the position is now == target. In reality the
  10312. // motion control system might still be processing the action and the real tool position
  10313. // in any intermediate location.
  10314. set_current_to_destination();
  10315. }
  10316. #endif
  10317. #if ENABLED(BEZIER_CURVE_SUPPORT)
  10318. void plan_cubic_move(const float offset[4]) {
  10319. cubic_b_spline(current_position, destination, offset, MMS_SCALED(feedrate_mm_s), active_extruder);
  10320. // As far as the parser is concerned, the position is now == destination. In reality the
  10321. // motion control system might still be processing the action and the real tool position
  10322. // in any intermediate location.
  10323. set_current_to_destination();
  10324. }
  10325. #endif // BEZIER_CURVE_SUPPORT
  10326. #if ENABLED(USE_CONTROLLER_FAN)
  10327. void controllerFan() {
  10328. static millis_t lastMotorOn = 0, // Last time a motor was turned on
  10329. nextMotorCheck = 0; // Last time the state was checked
  10330. const millis_t ms = millis();
  10331. if (ELAPSED(ms, nextMotorCheck)) {
  10332. nextMotorCheck = ms + 2500UL; // Not a time critical function, so only check every 2.5s
  10333. if (X_ENABLE_READ == X_ENABLE_ON || Y_ENABLE_READ == Y_ENABLE_ON || Z_ENABLE_READ == Z_ENABLE_ON || thermalManager.soft_pwm_amount_bed > 0
  10334. || E0_ENABLE_READ == E_ENABLE_ON // If any of the drivers are enabled...
  10335. #if E_STEPPERS > 1
  10336. || E1_ENABLE_READ == E_ENABLE_ON
  10337. #if HAS_X2_ENABLE
  10338. || X2_ENABLE_READ == X_ENABLE_ON
  10339. #endif
  10340. #if E_STEPPERS > 2
  10341. || E2_ENABLE_READ == E_ENABLE_ON
  10342. #if E_STEPPERS > 3
  10343. || E3_ENABLE_READ == E_ENABLE_ON
  10344. #if E_STEPPERS > 4
  10345. || E4_ENABLE_READ == E_ENABLE_ON
  10346. #endif // E_STEPPERS > 4
  10347. #endif // E_STEPPERS > 3
  10348. #endif // E_STEPPERS > 2
  10349. #endif // E_STEPPERS > 1
  10350. ) {
  10351. lastMotorOn = ms; //... set time to NOW so the fan will turn on
  10352. }
  10353. // Fan off if no steppers have been enabled for CONTROLLERFAN_SECS seconds
  10354. uint8_t speed = (!lastMotorOn || ELAPSED(ms, lastMotorOn + (CONTROLLERFAN_SECS) * 1000UL)) ? 0 : CONTROLLERFAN_SPEED;
  10355. // allows digital or PWM fan output to be used (see M42 handling)
  10356. WRITE(CONTROLLER_FAN_PIN, speed);
  10357. analogWrite(CONTROLLER_FAN_PIN, speed);
  10358. }
  10359. }
  10360. #endif // USE_CONTROLLER_FAN
  10361. #if ENABLED(MORGAN_SCARA)
  10362. /**
  10363. * Morgan SCARA Forward Kinematics. Results in cartes[].
  10364. * Maths and first version by QHARLEY.
  10365. * Integrated into Marlin and slightly restructured by Joachim Cerny.
  10366. */
  10367. void forward_kinematics_SCARA(const float &a, const float &b) {
  10368. float a_sin = sin(RADIANS(a)) * L1,
  10369. a_cos = cos(RADIANS(a)) * L1,
  10370. b_sin = sin(RADIANS(b)) * L2,
  10371. b_cos = cos(RADIANS(b)) * L2;
  10372. cartes[X_AXIS] = a_cos + b_cos + SCARA_OFFSET_X; //theta
  10373. cartes[Y_AXIS] = a_sin + b_sin + SCARA_OFFSET_Y; //theta+phi
  10374. /*
  10375. SERIAL_ECHOPAIR("SCARA FK Angle a=", a);
  10376. SERIAL_ECHOPAIR(" b=", b);
  10377. SERIAL_ECHOPAIR(" a_sin=", a_sin);
  10378. SERIAL_ECHOPAIR(" a_cos=", a_cos);
  10379. SERIAL_ECHOPAIR(" b_sin=", b_sin);
  10380. SERIAL_ECHOLNPAIR(" b_cos=", b_cos);
  10381. SERIAL_ECHOPAIR(" cartes[X_AXIS]=", cartes[X_AXIS]);
  10382. SERIAL_ECHOLNPAIR(" cartes[Y_AXIS]=", cartes[Y_AXIS]);
  10383. //*/
  10384. }
  10385. /**
  10386. * Morgan SCARA Inverse Kinematics. Results in delta[].
  10387. *
  10388. * See http://forums.reprap.org/read.php?185,283327
  10389. *
  10390. * Maths and first version by QHARLEY.
  10391. * Integrated into Marlin and slightly restructured by Joachim Cerny.
  10392. */
  10393. void inverse_kinematics(const float logical[XYZ]) {
  10394. static float C2, S2, SK1, SK2, THETA, PSI;
  10395. float sx = RAW_X_POSITION(logical[X_AXIS]) - SCARA_OFFSET_X, // Translate SCARA to standard X Y
  10396. sy = RAW_Y_POSITION(logical[Y_AXIS]) - SCARA_OFFSET_Y; // With scaling factor.
  10397. if (L1 == L2)
  10398. C2 = HYPOT2(sx, sy) / L1_2_2 - 1;
  10399. else
  10400. C2 = (HYPOT2(sx, sy) - (L1_2 + L2_2)) / (2.0 * L1 * L2);
  10401. S2 = SQRT(1 - sq(C2));
  10402. // Unrotated Arm1 plus rotated Arm2 gives the distance from Center to End
  10403. SK1 = L1 + L2 * C2;
  10404. // Rotated Arm2 gives the distance from Arm1 to Arm2
  10405. SK2 = L2 * S2;
  10406. // Angle of Arm1 is the difference between Center-to-End angle and the Center-to-Elbow
  10407. THETA = ATAN2(SK1, SK2) - ATAN2(sx, sy);
  10408. // Angle of Arm2
  10409. PSI = ATAN2(S2, C2);
  10410. delta[A_AXIS] = DEGREES(THETA); // theta is support arm angle
  10411. delta[B_AXIS] = DEGREES(THETA + PSI); // equal to sub arm angle (inverted motor)
  10412. delta[C_AXIS] = logical[Z_AXIS];
  10413. /*
  10414. DEBUG_POS("SCARA IK", logical);
  10415. DEBUG_POS("SCARA IK", delta);
  10416. SERIAL_ECHOPAIR(" SCARA (x,y) ", sx);
  10417. SERIAL_ECHOPAIR(",", sy);
  10418. SERIAL_ECHOPAIR(" C2=", C2);
  10419. SERIAL_ECHOPAIR(" S2=", S2);
  10420. SERIAL_ECHOPAIR(" Theta=", THETA);
  10421. SERIAL_ECHOLNPAIR(" Phi=", PHI);
  10422. //*/
  10423. }
  10424. #endif // MORGAN_SCARA
  10425. #if ENABLED(TEMP_STAT_LEDS)
  10426. static bool red_led = false;
  10427. static millis_t next_status_led_update_ms = 0;
  10428. void handle_status_leds(void) {
  10429. if (ELAPSED(millis(), next_status_led_update_ms)) {
  10430. next_status_led_update_ms += 500; // Update every 0.5s
  10431. float max_temp = 0.0;
  10432. #if HAS_TEMP_BED
  10433. max_temp = MAX3(max_temp, thermalManager.degTargetBed(), thermalManager.degBed());
  10434. #endif
  10435. HOTEND_LOOP()
  10436. max_temp = MAX3(max_temp, thermalManager.degHotend(e), thermalManager.degTargetHotend(e));
  10437. const bool new_led = (max_temp > 55.0) ? true : (max_temp < 54.0) ? false : red_led;
  10438. if (new_led != red_led) {
  10439. red_led = new_led;
  10440. #if PIN_EXISTS(STAT_LED_RED)
  10441. WRITE(STAT_LED_RED_PIN, new_led ? HIGH : LOW);
  10442. #if PIN_EXISTS(STAT_LED_BLUE)
  10443. WRITE(STAT_LED_BLUE_PIN, new_led ? LOW : HIGH);
  10444. #endif
  10445. #else
  10446. WRITE(STAT_LED_BLUE_PIN, new_led ? HIGH : LOW);
  10447. #endif
  10448. }
  10449. }
  10450. }
  10451. #endif
  10452. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  10453. void handle_filament_runout() {
  10454. if (!filament_ran_out) {
  10455. filament_ran_out = true;
  10456. enqueue_and_echo_commands_P(PSTR(FILAMENT_RUNOUT_SCRIPT));
  10457. stepper.synchronize();
  10458. }
  10459. }
  10460. #endif // FILAMENT_RUNOUT_SENSOR
  10461. #if ENABLED(FAST_PWM_FAN)
  10462. void setPwmFrequency(uint8_t pin, int val) {
  10463. val &= 0x07;
  10464. switch (digitalPinToTimer(pin)) {
  10465. #ifdef TCCR0A
  10466. #if !AVR_AT90USB1286_FAMILY
  10467. case TIMER0A:
  10468. #endif
  10469. case TIMER0B:
  10470. //_SET_CS(0, val);
  10471. break;
  10472. #endif
  10473. #ifdef TCCR1A
  10474. case TIMER1A:
  10475. case TIMER1B:
  10476. //_SET_CS(1, val);
  10477. break;
  10478. #endif
  10479. #ifdef TCCR2
  10480. case TIMER2:
  10481. case TIMER2:
  10482. _SET_CS(2, val);
  10483. break;
  10484. #endif
  10485. #ifdef TCCR2A
  10486. case TIMER2A:
  10487. case TIMER2B:
  10488. _SET_CS(2, val);
  10489. break;
  10490. #endif
  10491. #ifdef TCCR3A
  10492. case TIMER3A:
  10493. case TIMER3B:
  10494. case TIMER3C:
  10495. _SET_CS(3, val);
  10496. break;
  10497. #endif
  10498. #ifdef TCCR4A
  10499. case TIMER4A:
  10500. case TIMER4B:
  10501. case TIMER4C:
  10502. _SET_CS(4, val);
  10503. break;
  10504. #endif
  10505. #ifdef TCCR5A
  10506. case TIMER5A:
  10507. case TIMER5B:
  10508. case TIMER5C:
  10509. _SET_CS(5, val);
  10510. break;
  10511. #endif
  10512. }
  10513. }
  10514. #endif // FAST_PWM_FAN
  10515. float calculate_volumetric_multiplier(float diameter) {
  10516. if (!volumetric_enabled || diameter == 0) return 1.0;
  10517. return 1.0 / (M_PI * sq(diameter * 0.5));
  10518. }
  10519. void calculate_volumetric_multipliers() {
  10520. for (uint8_t i = 0; i < COUNT(filament_size); i++)
  10521. volumetric_multiplier[i] = calculate_volumetric_multiplier(filament_size[i]);
  10522. }
  10523. void enable_all_steppers() {
  10524. enable_X();
  10525. enable_Y();
  10526. enable_Z();
  10527. enable_E0();
  10528. enable_E1();
  10529. enable_E2();
  10530. enable_E3();
  10531. enable_E4();
  10532. }
  10533. void disable_e_steppers() {
  10534. disable_E0();
  10535. disable_E1();
  10536. disable_E2();
  10537. disable_E3();
  10538. disable_E4();
  10539. }
  10540. void disable_all_steppers() {
  10541. disable_X();
  10542. disable_Y();
  10543. disable_Z();
  10544. disable_e_steppers();
  10545. }
  10546. #if ENABLED(HAVE_TMC2130)
  10547. void automatic_current_control(TMC2130Stepper &st, String axisID) {
  10548. // Check otpw even if we don't use automatic control. Allows for flag inspection.
  10549. const bool is_otpw = st.checkOT();
  10550. // Report if a warning was triggered
  10551. static bool previous_otpw = false;
  10552. if (is_otpw && !previous_otpw) {
  10553. char timestamp[10];
  10554. duration_t elapsed = print_job_timer.duration();
  10555. const bool has_days = (elapsed.value > 60*60*24L);
  10556. (void)elapsed.toDigital(timestamp, has_days);
  10557. SERIAL_ECHO(timestamp);
  10558. SERIAL_ECHOPGM(": ");
  10559. SERIAL_ECHO(axisID);
  10560. SERIAL_ECHOLNPGM(" driver overtemperature warning!");
  10561. }
  10562. previous_otpw = is_otpw;
  10563. #if CURRENT_STEP > 0 && ENABLED(AUTOMATIC_CURRENT_CONTROL)
  10564. // Return if user has not enabled current control start with M906 S1.
  10565. if (!auto_current_control) return;
  10566. /**
  10567. * Decrease current if is_otpw is true.
  10568. * Bail out if driver is disabled.
  10569. * Increase current if OTPW has not been triggered yet.
  10570. */
  10571. uint16_t current = st.getCurrent();
  10572. if (is_otpw) {
  10573. st.setCurrent(current - CURRENT_STEP, R_SENSE, HOLD_MULTIPLIER);
  10574. #if ENABLED(REPORT_CURRENT_CHANGE)
  10575. SERIAL_ECHO(axisID);
  10576. SERIAL_ECHOPAIR(" current decreased to ", st.getCurrent());
  10577. #endif
  10578. }
  10579. else if (!st.isEnabled())
  10580. return;
  10581. else if (!is_otpw && !st.getOTPW()) {
  10582. current += CURRENT_STEP;
  10583. if (current <= AUTO_ADJUST_MAX) {
  10584. st.setCurrent(current, R_SENSE, HOLD_MULTIPLIER);
  10585. #if ENABLED(REPORT_CURRENT_CHANGE)
  10586. SERIAL_ECHO(axisID);
  10587. SERIAL_ECHOPAIR(" current increased to ", st.getCurrent());
  10588. #endif
  10589. }
  10590. }
  10591. SERIAL_EOL();
  10592. #endif
  10593. }
  10594. void checkOverTemp() {
  10595. static millis_t next_cOT = 0;
  10596. if (ELAPSED(millis(), next_cOT)) {
  10597. next_cOT = millis() + 5000;
  10598. #if ENABLED(X_IS_TMC2130)
  10599. automatic_current_control(stepperX, "X");
  10600. #endif
  10601. #if ENABLED(Y_IS_TMC2130)
  10602. automatic_current_control(stepperY, "Y");
  10603. #endif
  10604. #if ENABLED(Z_IS_TMC2130)
  10605. automatic_current_control(stepperZ, "Z");
  10606. #endif
  10607. #if ENABLED(X2_IS_TMC2130)
  10608. automatic_current_control(stepperX2, "X2");
  10609. #endif
  10610. #if ENABLED(Y2_IS_TMC2130)
  10611. automatic_current_control(stepperY2, "Y2");
  10612. #endif
  10613. #if ENABLED(Z2_IS_TMC2130)
  10614. automatic_current_control(stepperZ2, "Z2");
  10615. #endif
  10616. #if ENABLED(E0_IS_TMC2130)
  10617. automatic_current_control(stepperE0, "E0");
  10618. #endif
  10619. #if ENABLED(E1_IS_TMC2130)
  10620. automatic_current_control(stepperE1, "E1");
  10621. #endif
  10622. #if ENABLED(E2_IS_TMC2130)
  10623. automatic_current_control(stepperE2, "E2");
  10624. #endif
  10625. #if ENABLED(E3_IS_TMC2130)
  10626. automatic_current_control(stepperE3, "E3");
  10627. #endif
  10628. #if ENABLED(E4_IS_TMC2130)
  10629. automatic_current_control(stepperE4, "E4");
  10630. #endif
  10631. #if ENABLED(E4_IS_TMC2130)
  10632. automatic_current_control(stepperE4);
  10633. #endif
  10634. }
  10635. }
  10636. #endif // HAVE_TMC2130
  10637. /**
  10638. * Manage several activities:
  10639. * - Check for Filament Runout
  10640. * - Keep the command buffer full
  10641. * - Check for maximum inactive time between commands
  10642. * - Check for maximum inactive time between stepper commands
  10643. * - Check if pin CHDK needs to go LOW
  10644. * - Check for KILL button held down
  10645. * - Check for HOME button held down
  10646. * - Check if cooling fan needs to be switched on
  10647. * - Check if an idle but hot extruder needs filament extruded (EXTRUDER_RUNOUT_PREVENT)
  10648. */
  10649. void manage_inactivity(bool ignore_stepper_queue/*=false*/) {
  10650. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  10651. if ((IS_SD_PRINTING || print_job_timer.isRunning()) && (READ(FIL_RUNOUT_PIN) == FIL_RUNOUT_INVERTING))
  10652. handle_filament_runout();
  10653. #endif
  10654. if (commands_in_queue < BUFSIZE) get_available_commands();
  10655. const millis_t ms = millis();
  10656. if (max_inactive_time && ELAPSED(ms, previous_cmd_ms + max_inactive_time)) {
  10657. SERIAL_ERROR_START();
  10658. SERIAL_ECHOLNPAIR(MSG_KILL_INACTIVE_TIME, parser.command_ptr);
  10659. kill(PSTR(MSG_KILLED));
  10660. }
  10661. // Prevent steppers timing-out in the middle of M600
  10662. #if ENABLED(ADVANCED_PAUSE_FEATURE) && ENABLED(PAUSE_PARK_NO_STEPPER_TIMEOUT)
  10663. #define MOVE_AWAY_TEST !move_away_flag
  10664. #else
  10665. #define MOVE_AWAY_TEST true
  10666. #endif
  10667. if (MOVE_AWAY_TEST && stepper_inactive_time && ELAPSED(ms, previous_cmd_ms + stepper_inactive_time)
  10668. && !ignore_stepper_queue && !planner.blocks_queued()) {
  10669. #if ENABLED(DISABLE_INACTIVE_X)
  10670. disable_X();
  10671. #endif
  10672. #if ENABLED(DISABLE_INACTIVE_Y)
  10673. disable_Y();
  10674. #endif
  10675. #if ENABLED(DISABLE_INACTIVE_Z)
  10676. disable_Z();
  10677. #endif
  10678. #if ENABLED(DISABLE_INACTIVE_E)
  10679. disable_e_steppers();
  10680. #endif
  10681. #if ENABLED(AUTO_BED_LEVELING_UBL) && ENABLED(ULTRA_LCD) // Only needed with an LCD
  10682. ubl_lcd_map_control = defer_return_to_status = false;
  10683. #endif
  10684. }
  10685. #ifdef CHDK // Check if pin should be set to LOW after M240 set it to HIGH
  10686. if (chdkActive && ELAPSED(ms, chdkHigh + CHDK_DELAY)) {
  10687. chdkActive = false;
  10688. WRITE(CHDK, LOW);
  10689. }
  10690. #endif
  10691. #if HAS_KILL
  10692. // Check if the kill button was pressed and wait just in case it was an accidental
  10693. // key kill key press
  10694. // -------------------------------------------------------------------------------
  10695. static int killCount = 0; // make the inactivity button a bit less responsive
  10696. const int KILL_DELAY = 750;
  10697. if (!READ(KILL_PIN))
  10698. killCount++;
  10699. else if (killCount > 0)
  10700. killCount--;
  10701. // Exceeded threshold and we can confirm that it was not accidental
  10702. // KILL the machine
  10703. // ----------------------------------------------------------------
  10704. if (killCount >= KILL_DELAY) {
  10705. SERIAL_ERROR_START();
  10706. SERIAL_ERRORLNPGM(MSG_KILL_BUTTON);
  10707. kill(PSTR(MSG_KILLED));
  10708. }
  10709. #endif
  10710. #if HAS_HOME
  10711. // Check to see if we have to home, use poor man's debouncer
  10712. // ---------------------------------------------------------
  10713. static int homeDebounceCount = 0; // poor man's debouncing count
  10714. const int HOME_DEBOUNCE_DELAY = 2500;
  10715. if (!IS_SD_PRINTING && !READ(HOME_PIN)) {
  10716. if (!homeDebounceCount) {
  10717. enqueue_and_echo_commands_P(PSTR("G28"));
  10718. LCD_MESSAGEPGM(MSG_AUTO_HOME);
  10719. }
  10720. if (homeDebounceCount < HOME_DEBOUNCE_DELAY)
  10721. homeDebounceCount++;
  10722. else
  10723. homeDebounceCount = 0;
  10724. }
  10725. #endif
  10726. #if ENABLED(USE_CONTROLLER_FAN)
  10727. controllerFan(); // Check if fan should be turned on to cool stepper drivers down
  10728. #endif
  10729. #if ENABLED(EXTRUDER_RUNOUT_PREVENT)
  10730. if (ELAPSED(ms, previous_cmd_ms + (EXTRUDER_RUNOUT_SECONDS) * 1000UL)
  10731. && thermalManager.degHotend(active_extruder) > EXTRUDER_RUNOUT_MINTEMP) {
  10732. bool oldstatus;
  10733. #if ENABLED(SWITCHING_EXTRUDER)
  10734. oldstatus = E0_ENABLE_READ;
  10735. enable_E0();
  10736. #else // !SWITCHING_EXTRUDER
  10737. switch (active_extruder) {
  10738. case 0: oldstatus = E0_ENABLE_READ; enable_E0(); break;
  10739. #if E_STEPPERS > 1
  10740. case 1: oldstatus = E1_ENABLE_READ; enable_E1(); break;
  10741. #if E_STEPPERS > 2
  10742. case 2: oldstatus = E2_ENABLE_READ; enable_E2(); break;
  10743. #if E_STEPPERS > 3
  10744. case 3: oldstatus = E3_ENABLE_READ; enable_E3(); break;
  10745. #if E_STEPPERS > 4
  10746. case 4: oldstatus = E4_ENABLE_READ; enable_E4(); break;
  10747. #endif // E_STEPPERS > 4
  10748. #endif // E_STEPPERS > 3
  10749. #endif // E_STEPPERS > 2
  10750. #endif // E_STEPPERS > 1
  10751. }
  10752. #endif // !SWITCHING_EXTRUDER
  10753. previous_cmd_ms = ms; // refresh_cmd_timeout()
  10754. const float olde = current_position[E_AXIS];
  10755. current_position[E_AXIS] += EXTRUDER_RUNOUT_EXTRUDE;
  10756. planner.buffer_line_kinematic(current_position, MMM_TO_MMS(EXTRUDER_RUNOUT_SPEED), active_extruder);
  10757. current_position[E_AXIS] = olde;
  10758. planner.set_e_position_mm(olde);
  10759. stepper.synchronize();
  10760. #if ENABLED(SWITCHING_EXTRUDER)
  10761. E0_ENABLE_WRITE(oldstatus);
  10762. #else
  10763. switch (active_extruder) {
  10764. case 0: E0_ENABLE_WRITE(oldstatus); break;
  10765. #if E_STEPPERS > 1
  10766. case 1: E1_ENABLE_WRITE(oldstatus); break;
  10767. #if E_STEPPERS > 2
  10768. case 2: E2_ENABLE_WRITE(oldstatus); break;
  10769. #if E_STEPPERS > 3
  10770. case 3: E3_ENABLE_WRITE(oldstatus); break;
  10771. #if E_STEPPERS > 4
  10772. case 4: E4_ENABLE_WRITE(oldstatus); break;
  10773. #endif // E_STEPPERS > 4
  10774. #endif // E_STEPPERS > 3
  10775. #endif // E_STEPPERS > 2
  10776. #endif // E_STEPPERS > 1
  10777. }
  10778. #endif // !SWITCHING_EXTRUDER
  10779. }
  10780. #endif // EXTRUDER_RUNOUT_PREVENT
  10781. #if ENABLED(DUAL_X_CARRIAGE)
  10782. // handle delayed move timeout
  10783. if (delayed_move_time && ELAPSED(ms, delayed_move_time + 1000UL) && IsRunning()) {
  10784. // travel moves have been received so enact them
  10785. delayed_move_time = 0xFFFFFFFFUL; // force moves to be done
  10786. set_destination_to_current();
  10787. prepare_move_to_destination();
  10788. }
  10789. #endif
  10790. #if ENABLED(TEMP_STAT_LEDS)
  10791. handle_status_leds();
  10792. #endif
  10793. #if ENABLED(HAVE_TMC2130)
  10794. checkOverTemp();
  10795. #endif
  10796. planner.check_axes_activity();
  10797. }
  10798. /**
  10799. * Standard idle routine keeps the machine alive
  10800. */
  10801. void idle(
  10802. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  10803. bool no_stepper_sleep/*=false*/
  10804. #endif
  10805. ) {
  10806. lcd_update();
  10807. host_keepalive();
  10808. #if ENABLED(AUTO_REPORT_TEMPERATURES) && (HAS_TEMP_HOTEND || HAS_TEMP_BED)
  10809. auto_report_temperatures();
  10810. #endif
  10811. manage_inactivity(
  10812. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  10813. no_stepper_sleep
  10814. #endif
  10815. );
  10816. thermalManager.manage_heater();
  10817. #if ENABLED(PRINTCOUNTER)
  10818. print_job_timer.tick();
  10819. #endif
  10820. #if HAS_BUZZER && DISABLED(LCD_USE_I2C_BUZZER)
  10821. buzzer.tick();
  10822. #endif
  10823. #if ENABLED(I2C_POSITION_ENCODERS)
  10824. if (planner.blocks_queued() &&
  10825. ( (blockBufferIndexRef != planner.block_buffer_head) ||
  10826. ((lastUpdateMillis + I2CPE_MIN_UPD_TIME_MS) < millis())) ) {
  10827. blockBufferIndexRef = planner.block_buffer_head;
  10828. I2CPEM.update();
  10829. lastUpdateMillis = millis();
  10830. }
  10831. #endif
  10832. }
  10833. /**
  10834. * Kill all activity and lock the machine.
  10835. * After this the machine will need to be reset.
  10836. */
  10837. void kill(const char* lcd_msg) {
  10838. SERIAL_ERROR_START();
  10839. SERIAL_ERRORLNPGM(MSG_ERR_KILLED);
  10840. thermalManager.disable_all_heaters();
  10841. disable_all_steppers();
  10842. #if ENABLED(ULTRA_LCD)
  10843. kill_screen(lcd_msg);
  10844. #else
  10845. UNUSED(lcd_msg);
  10846. #endif
  10847. _delay_ms(600); // Wait a short time (allows messages to get out before shutting down.
  10848. cli(); // Stop interrupts
  10849. _delay_ms(250); //Wait to ensure all interrupts routines stopped
  10850. thermalManager.disable_all_heaters(); //turn off heaters again
  10851. #if defined(ACTION_ON_KILL)
  10852. SERIAL_ECHOLNPGM("//action:" ACTION_ON_KILL);
  10853. #endif
  10854. #if HAS_POWER_SWITCH
  10855. SET_INPUT(PS_ON_PIN);
  10856. #endif
  10857. suicide();
  10858. while (1) {
  10859. #if ENABLED(USE_WATCHDOG)
  10860. watchdog_reset();
  10861. #endif
  10862. } // Wait for reset
  10863. }
  10864. /**
  10865. * Turn off heaters and stop the print in progress
  10866. * After a stop the machine may be resumed with M999
  10867. */
  10868. void stop() {
  10869. thermalManager.disable_all_heaters(); // 'unpause' taken care of in here
  10870. #if ENABLED(PROBING_FANS_OFF)
  10871. if (fans_paused) fans_pause(false); // put things back the way they were
  10872. #endif
  10873. if (IsRunning()) {
  10874. Stopped_gcode_LastN = gcode_LastN; // Save last g_code for restart
  10875. SERIAL_ERROR_START();
  10876. SERIAL_ERRORLNPGM(MSG_ERR_STOPPED);
  10877. LCD_MESSAGEPGM(MSG_STOPPED);
  10878. safe_delay(350); // allow enough time for messages to get out before stopping
  10879. Running = false;
  10880. }
  10881. }
  10882. /**
  10883. * Marlin entry-point: Set up before the program loop
  10884. * - Set up the kill pin, filament runout, power hold
  10885. * - Start the serial port
  10886. * - Print startup messages and diagnostics
  10887. * - Get EEPROM or default settings
  10888. * - Initialize managers for:
  10889. * • temperature
  10890. * • planner
  10891. * • watchdog
  10892. * • stepper
  10893. * • photo pin
  10894. * • servos
  10895. * • LCD controller
  10896. * • Digipot I2C
  10897. * • Z probe sled
  10898. * • status LEDs
  10899. */
  10900. void setup() {
  10901. #ifdef DISABLE_JTAG
  10902. // Disable JTAG on AT90USB chips to free up pins for IO
  10903. MCUCR = 0x80;
  10904. MCUCR = 0x80;
  10905. #endif
  10906. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  10907. setup_filrunoutpin();
  10908. #endif
  10909. setup_killpin();
  10910. setup_powerhold();
  10911. #if HAS_STEPPER_RESET
  10912. disableStepperDrivers();
  10913. #endif
  10914. MYSERIAL.begin(BAUDRATE);
  10915. SERIAL_PROTOCOLLNPGM("start");
  10916. SERIAL_ECHO_START();
  10917. // Check startup - does nothing if bootloader sets MCUSR to 0
  10918. byte mcu = MCUSR;
  10919. if (mcu & 1) SERIAL_ECHOLNPGM(MSG_POWERUP);
  10920. if (mcu & 2) SERIAL_ECHOLNPGM(MSG_EXTERNAL_RESET);
  10921. if (mcu & 4) SERIAL_ECHOLNPGM(MSG_BROWNOUT_RESET);
  10922. if (mcu & 8) SERIAL_ECHOLNPGM(MSG_WATCHDOG_RESET);
  10923. if (mcu & 32) SERIAL_ECHOLNPGM(MSG_SOFTWARE_RESET);
  10924. MCUSR = 0;
  10925. SERIAL_ECHOPGM(MSG_MARLIN);
  10926. SERIAL_CHAR(' ');
  10927. SERIAL_ECHOLNPGM(SHORT_BUILD_VERSION);
  10928. SERIAL_EOL();
  10929. #if defined(STRING_DISTRIBUTION_DATE) && defined(STRING_CONFIG_H_AUTHOR)
  10930. SERIAL_ECHO_START();
  10931. SERIAL_ECHOPGM(MSG_CONFIGURATION_VER);
  10932. SERIAL_ECHOPGM(STRING_DISTRIBUTION_DATE);
  10933. SERIAL_ECHOLNPGM(MSG_AUTHOR STRING_CONFIG_H_AUTHOR);
  10934. SERIAL_ECHOLNPGM("Compiled: " __DATE__);
  10935. #endif
  10936. SERIAL_ECHO_START();
  10937. SERIAL_ECHOPAIR(MSG_FREE_MEMORY, freeMemory());
  10938. SERIAL_ECHOLNPAIR(MSG_PLANNER_BUFFER_BYTES, (int)sizeof(block_t)*BLOCK_BUFFER_SIZE);
  10939. // Send "ok" after commands by default
  10940. for (int8_t i = 0; i < BUFSIZE; i++) send_ok[i] = true;
  10941. // Load data from EEPROM if available (or use defaults)
  10942. // This also updates variables in the planner, elsewhere
  10943. (void)settings.load();
  10944. #if HAS_M206_COMMAND
  10945. // Initialize current position based on home_offset
  10946. COPY(current_position, home_offset);
  10947. #else
  10948. ZERO(current_position);
  10949. #endif
  10950. // Vital to init stepper/planner equivalent for current_position
  10951. SYNC_PLAN_POSITION_KINEMATIC();
  10952. thermalManager.init(); // Initialize temperature loop
  10953. #if ENABLED(USE_WATCHDOG)
  10954. watchdog_init();
  10955. #endif
  10956. stepper.init(); // Initialize stepper, this enables interrupts!
  10957. servo_init();
  10958. #if HAS_PHOTOGRAPH
  10959. OUT_WRITE(PHOTOGRAPH_PIN, LOW);
  10960. #endif
  10961. #if HAS_CASE_LIGHT
  10962. case_light_on = CASE_LIGHT_DEFAULT_ON;
  10963. case_light_brightness = CASE_LIGHT_DEFAULT_BRIGHTNESS;
  10964. update_case_light();
  10965. #endif
  10966. #if ENABLED(SPINDLE_LASER_ENABLE)
  10967. OUT_WRITE(SPINDLE_LASER_ENABLE_PIN, !SPINDLE_LASER_ENABLE_INVERT); // init spindle to off
  10968. #if SPINDLE_DIR_CHANGE
  10969. OUT_WRITE(SPINDLE_DIR_PIN, SPINDLE_INVERT_DIR ? 255 : 0); // init rotation to clockwise (M3)
  10970. #endif
  10971. #if ENABLED(SPINDLE_LASER_PWM)
  10972. SET_OUTPUT(SPINDLE_LASER_PWM_PIN);
  10973. analogWrite(SPINDLE_LASER_PWM_PIN, SPINDLE_LASER_PWM_INVERT ? 255 : 0); // set to lowest speed
  10974. #endif
  10975. #endif
  10976. #if HAS_BED_PROBE
  10977. endstops.enable_z_probe(false);
  10978. #endif
  10979. #if ENABLED(USE_CONTROLLER_FAN)
  10980. SET_OUTPUT(CONTROLLER_FAN_PIN); //Set pin used for driver cooling fan
  10981. #endif
  10982. #if HAS_STEPPER_RESET
  10983. enableStepperDrivers();
  10984. #endif
  10985. #if ENABLED(DIGIPOT_I2C)
  10986. digipot_i2c_init();
  10987. #endif
  10988. #if ENABLED(DAC_STEPPER_CURRENT)
  10989. dac_init();
  10990. #endif
  10991. #if (ENABLED(Z_PROBE_SLED) || ENABLED(SOLENOID_PROBE)) && HAS_SOLENOID_1
  10992. OUT_WRITE(SOL1_PIN, LOW); // turn it off
  10993. #endif
  10994. #if HAS_HOME
  10995. SET_INPUT_PULLUP(HOME_PIN);
  10996. #endif
  10997. #if PIN_EXISTS(STAT_LED_RED)
  10998. OUT_WRITE(STAT_LED_RED_PIN, LOW); // turn it off
  10999. #endif
  11000. #if PIN_EXISTS(STAT_LED_BLUE)
  11001. OUT_WRITE(STAT_LED_BLUE_PIN, LOW); // turn it off
  11002. #endif
  11003. #if ENABLED(RGB_LED) || ENABLED(RGBW_LED)
  11004. SET_OUTPUT(RGB_LED_R_PIN);
  11005. SET_OUTPUT(RGB_LED_G_PIN);
  11006. SET_OUTPUT(RGB_LED_B_PIN);
  11007. #if ENABLED(RGBW_LED)
  11008. SET_OUTPUT(RGB_LED_W_PIN);
  11009. #endif
  11010. #endif
  11011. #if ENABLED(MK2_MULTIPLEXER)
  11012. SET_OUTPUT(E_MUX0_PIN);
  11013. SET_OUTPUT(E_MUX1_PIN);
  11014. SET_OUTPUT(E_MUX2_PIN);
  11015. #endif
  11016. lcd_init();
  11017. #ifndef CUSTOM_BOOTSCREEN_TIMEOUT
  11018. #define CUSTOM_BOOTSCREEN_TIMEOUT 2500
  11019. #endif
  11020. #if ENABLED(SHOW_BOOTSCREEN)
  11021. #if ENABLED(DOGLCD) // On DOGM the first bootscreen is already drawn
  11022. #if ENABLED(SHOW_CUSTOM_BOOTSCREEN)
  11023. safe_delay(CUSTOM_BOOTSCREEN_TIMEOUT); // Custom boot screen pause
  11024. lcd_bootscreen(); // Show Marlin boot screen
  11025. #endif
  11026. safe_delay(BOOTSCREEN_TIMEOUT); // Pause
  11027. #elif ENABLED(ULTRA_LCD)
  11028. lcd_bootscreen();
  11029. #if DISABLED(SDSUPPORT)
  11030. lcd_init();
  11031. #endif
  11032. #endif
  11033. #endif
  11034. #if ENABLED(MIXING_EXTRUDER) && MIXING_VIRTUAL_TOOLS > 1
  11035. // Initialize mixing to 100% color 1
  11036. for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
  11037. mixing_factor[i] = (i == 0) ? 1.0 : 0.0;
  11038. for (uint8_t t = 0; t < MIXING_VIRTUAL_TOOLS; t++)
  11039. for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
  11040. mixing_virtual_tool_mix[t][i] = mixing_factor[i];
  11041. #endif
  11042. #if ENABLED(BLTOUCH)
  11043. // Make sure any BLTouch error condition is cleared
  11044. bltouch_command(BLTOUCH_RESET);
  11045. set_bltouch_deployed(true);
  11046. set_bltouch_deployed(false);
  11047. #endif
  11048. #if ENABLED(I2C_POSITION_ENCODERS)
  11049. I2CPEM.init();
  11050. #endif
  11051. #if ENABLED(EXPERIMENTAL_I2CBUS) && I2C_SLAVE_ADDRESS > 0
  11052. i2c.onReceive(i2c_on_receive);
  11053. i2c.onRequest(i2c_on_request);
  11054. #endif
  11055. #if ENABLED(ENDSTOP_INTERRUPTS_FEATURE)
  11056. setup_endstop_interrupts();
  11057. #endif
  11058. #if ENABLED(SWITCHING_EXTRUDER)
  11059. move_extruder_servo(0); // Initialize extruder servo
  11060. #endif
  11061. #if ENABLED(SWITCHING_NOZZLE)
  11062. move_nozzle_servo(0); // Initialize nozzle servo
  11063. #endif
  11064. }
  11065. /**
  11066. * The main Marlin program loop
  11067. *
  11068. * - Save or log commands to SD
  11069. * - Process available commands (if not saving)
  11070. * - Call heater manager
  11071. * - Call inactivity manager
  11072. * - Call endstop manager
  11073. * - Call LCD update
  11074. */
  11075. void loop() {
  11076. if (commands_in_queue < BUFSIZE) get_available_commands();
  11077. #if ENABLED(SDSUPPORT)
  11078. card.checkautostart(false);
  11079. #endif
  11080. if (commands_in_queue) {
  11081. #if ENABLED(SDSUPPORT)
  11082. if (card.saving) {
  11083. char* command = command_queue[cmd_queue_index_r];
  11084. if (strstr_P(command, PSTR("M29"))) {
  11085. // M29 closes the file
  11086. card.closefile();
  11087. SERIAL_PROTOCOLLNPGM(MSG_FILE_SAVED);
  11088. ok_to_send();
  11089. }
  11090. else {
  11091. // Write the string from the read buffer to SD
  11092. card.write_command(command);
  11093. if (card.logging)
  11094. process_next_command(); // The card is saving because it's logging
  11095. else
  11096. ok_to_send();
  11097. }
  11098. }
  11099. else
  11100. process_next_command();
  11101. #else
  11102. process_next_command();
  11103. #endif // SDSUPPORT
  11104. // The queue may be reset by a command handler or by code invoked by idle() within a handler
  11105. if (commands_in_queue) {
  11106. --commands_in_queue;
  11107. if (++cmd_queue_index_r >= BUFSIZE) cmd_queue_index_r = 0;
  11108. }
  11109. }
  11110. endstops.report_state();
  11111. idle();
  11112. }