My Marlin configs for Fabrikator Mini and CTC i3 Pro B
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

Marlin_main.cpp 401KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597
  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. * G20 - Set input units to inches
  56. * G21 - Set input units to millimeters
  57. * G26 - Mesh Validation Pattern (Requires UBL_G26_MESH_VALIDATION)
  58. * G27 - Park Nozzle (Requires NOZZLE_PARK_FEATURE)
  59. * G28 - Home one or more axes
  60. * G29 - Detailed Z probe, probes the bed at 3 or more points. Will fail if you haven't homed yet.
  61. * G30 - Single Z probe, probes bed at X Y location (defaults to current XY location)
  62. * G31 - Dock sled (Z_PROBE_SLED only)
  63. * G32 - Undock sled (Z_PROBE_SLED only)
  64. * G33 - Delta Auto-Calibration (Requires DELTA_AUTO_CALIBRATION)
  65. * G38 - Probe target - similar to G28 except it uses the Z_MIN_PROBE for all three axes
  66. * G42 - Coordinated move to a mesh point (Requires AUTO_BED_LEVELING_UBL)
  67. * G90 - Use Absolute Coordinates
  68. * G91 - Use Relative Coordinates
  69. * G92 - Set current position to coordinates given
  70. *
  71. * "M" Codes
  72. *
  73. * M0 - Unconditional stop - Wait for user to press a button on the LCD (Only if ULTRA_LCD is enabled)
  74. * M1 - Same as M0
  75. * M3 - Turn laser/spindle on, set spindle/laser speed/power, set rotation to clockwise
  76. * M4 - Turn laser/spindle on, set spindle/laser speed/power, set rotation to counter-clockwise
  77. * M5 - Turn laser/spindle off
  78. * M17 - Enable/Power all stepper motors
  79. * M18 - Disable all stepper motors; same as M84
  80. * M20 - List SD card. (Requires SDSUPPORT)
  81. * M21 - Init SD card. (Requires SDSUPPORT)
  82. * M22 - Release SD card. (Requires SDSUPPORT)
  83. * M23 - Select SD file: "M23 /path/file.gco". (Requires SDSUPPORT)
  84. * M24 - Start/resume SD print. (Requires SDSUPPORT)
  85. * M25 - Pause SD print. (Requires SDSUPPORT)
  86. * M26 - Set SD position in bytes: "M26 S12345". (Requires SDSUPPORT)
  87. * M27 - Report SD print status. (Requires SDSUPPORT)
  88. * M28 - Start SD write: "M28 /path/file.gco". (Requires SDSUPPORT)
  89. * M29 - Stop SD write. (Requires SDSUPPORT)
  90. * M30 - Delete file from SD: "M30 /path/file.gco"
  91. * M31 - Report time since last M109 or SD card start to serial.
  92. * M32 - Select file and start SD print: "M32 [S<bytepos>] !/path/file.gco#". (Requires SDSUPPORT)
  93. * Use P to run other files as sub-programs: "M32 P !filename#"
  94. * The '#' is necessary when calling from within sd files, as it stops buffer prereading
  95. * M33 - Get the longname version of a path. (Requires LONG_FILENAME_HOST_SUPPORT)
  96. * M34 - Set SD Card sorting options. (Requires SDCARD_SORT_ALPHA)
  97. * M42 - Change pin status via gcode: M42 P<pin> S<value>. LED pin assumed if P is omitted.
  98. * M43 - Display pin status, watch pins for changes, watch endstops & toggle LED, Z servo probe test, toggle pins
  99. * M48 - Measure Z Probe repeatability: M48 P<points> X<pos> Y<pos> V<level> E<engage> L<legs>. (Requires Z_MIN_PROBE_REPEATABILITY_TEST)
  100. * M75 - Start the print job timer.
  101. * M76 - Pause the print job timer.
  102. * M77 - Stop the print job timer.
  103. * M78 - Show statistical information about the print jobs. (Requires PRINTCOUNTER)
  104. * M80 - Turn on Power Supply. (Requires POWER_SUPPLY > 0)
  105. * M81 - Turn off Power Supply. (Requires POWER_SUPPLY > 0)
  106. * M82 - Set E codes absolute (default).
  107. * M83 - Set E codes relative while in Absolute (G90) mode.
  108. * M84 - Disable steppers until next move, or use S<seconds> to specify an idle
  109. * duration after which steppers should turn off. S0 disables the timeout.
  110. * M85 - Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
  111. * M92 - Set planner.axis_steps_per_mm for one or more axes.
  112. * M100 - Watch Free Memory (for debugging) (Requires M100_FREE_MEMORY_WATCHER)
  113. * M104 - Set extruder target temp.
  114. * M105 - Report current temperatures.
  115. * M106 - Fan on.
  116. * M107 - Fan off.
  117. * M108 - Break out of heating loops (M109, M190, M303). With no controller, breaks out of M0/M1. (Requires EMERGENCY_PARSER)
  118. * M109 - Sxxx Wait for extruder current temp to reach target temp. Waits only when heating
  119. * Rxxx Wait for extruder current temp to reach target temp. Waits when heating and cooling
  120. * If AUTOTEMP is enabled, S<mintemp> B<maxtemp> F<factor>. Exit autotemp by any M109 without F
  121. * M110 - Set the current line number. (Used by host printing)
  122. * M111 - Set debug flags: "M111 S<flagbits>". See flag bits defined in enum.h.
  123. * M112 - Emergency stop.
  124. * M113 - Get or set the timeout interval for Host Keepalive "busy" messages. (Requires HOST_KEEPALIVE_FEATURE)
  125. * M114 - Report current position.
  126. * M115 - Report capabilities. (Extended capabilities requires EXTENDED_CAPABILITIES_REPORT)
  127. * M117 - Display a message on the controller screen. (Requires an LCD)
  128. * M119 - Report endstops status.
  129. * M120 - Enable endstops detection.
  130. * M121 - Disable endstops detection.
  131. * M125 - Save current position and move to filament change position. (Requires PARK_HEAD_ON_PAUSE)
  132. * M126 - Solenoid Air Valve Open. (Requires BARICUDA)
  133. * M127 - Solenoid Air Valve Closed. (Requires BARICUDA)
  134. * M128 - EtoP Open. (Requires BARICUDA)
  135. * M129 - EtoP Closed. (Requires BARICUDA)
  136. * M140 - Set bed target temp. S<temp>
  137. * M145 - Set heatup values for materials on the LCD. H<hotend> B<bed> F<fan speed> for S<material> (0=PLA, 1=ABS)
  138. * M149 - Set temperature units. (Requires TEMPERATURE_UNITS_SUPPORT)
  139. * M150 - Set Status LED Color as R<red> U<green> B<blue>. Values 0-255. (Requires BLINKM or RGB_LED)
  140. * M155 - Auto-report temperatures with interval of S<seconds>. (Requires AUTO_REPORT_TEMPERATURES)
  141. * M163 - Set a single proportion for a mixing extruder. (Requires MIXING_EXTRUDER)
  142. * M164 - Save the mix as a virtual extruder. (Requires MIXING_EXTRUDER and MIXING_VIRTUAL_TOOLS)
  143. * M165 - Set the proportions for a mixing extruder. Use parameters ABCDHI to set the mixing factors. (Requires MIXING_EXTRUDER)
  144. * M190 - Sxxx Wait for bed current temp to reach target temp. ** Waits only when heating! **
  145. * Rxxx Wait for bed current temp to reach target temp. ** Waits for heating or cooling. **
  146. * M200 - Set filament diameter, D<diameter>, setting E axis units to cubic. (Use S0 to revert to linear units.)
  147. * M201 - Set max acceleration in units/s^2 for print moves: "M201 X<accel> Y<accel> Z<accel> E<accel>"
  148. * M202 - Set max acceleration in units/s^2 for travel moves: "M202 X<accel> Y<accel> Z<accel> E<accel>" ** UNUSED IN MARLIN! **
  149. * M203 - Set maximum feedrate: "M203 X<fr> Y<fr> Z<fr> E<fr>" in units/sec.
  150. * M204 - Set default acceleration in units/sec^2: P<printing> R<extruder_only> T<travel>
  151. * M205 - Set advanced settings. Current units apply:
  152. S<print> T<travel> minimum speeds
  153. B<minimum segment time>
  154. X<max X jerk>, Y<max Y jerk>, Z<max Z jerk>, E<max E jerk>
  155. * M206 - Set additional homing offset. (Disabled by NO_WORKSPACE_OFFSETS or DELTA)
  156. * M207 - Set Retract Length: S<length>, Feedrate: F<units/min>, and Z lift: Z<distance>. (Requires FWRETRACT)
  157. * M208 - Set Recover (unretract) Additional (!) Length: S<length> and Feedrate: F<units/min>. (Requires FWRETRACT)
  158. * M209 - Turn Automatic Retract Detection on/off: S<0|1> (For slicers that don't support G10/11). (Requires FWRETRACT)
  159. Every normal extrude-only move will be classified as retract depending on the direction.
  160. * M211 - Enable, Disable, and/or Report software endstops: S<0|1> (Requires MIN_SOFTWARE_ENDSTOPS or MAX_SOFTWARE_ENDSTOPS)
  161. * M218 - Set a tool offset: "M218 T<index> X<offset> Y<offset>". (Requires 2 or more extruders)
  162. * M220 - Set Feedrate Percentage: "M220 S<percent>" (i.e., "FR" on the LCD)
  163. * M221 - Set Flow Percentage: "M221 S<percent>"
  164. * M226 - Wait until a pin is in a given state: "M226 P<pin> S<state>"
  165. * M240 - Trigger a camera to take a photograph. (Requires CHDK or PHOTOGRAPH_PIN)
  166. * M250 - Set LCD contrast: "M250 C<contrast>" (0-63). (Requires LCD support)
  167. * M260 - i2c Send Data (Requires EXPERIMENTAL_I2CBUS)
  168. * M261 - i2c Request Data (Requires EXPERIMENTAL_I2CBUS)
  169. * M280 - Set servo position absolute: "M280 P<index> S<angle|µs>". (Requires servos)
  170. * M300 - Play beep sound S<frequency Hz> P<duration ms>
  171. * M301 - Set PID parameters P I and D. (Requires PIDTEMP)
  172. * M302 - Allow cold extrudes, or set the minimum extrude S<temperature>. (Requires PREVENT_COLD_EXTRUSION)
  173. * M303 - PID relay autotune S<temperature> sets the target temperature. Default 150C. (Requires PIDTEMP)
  174. * M304 - Set bed PID parameters P I and D. (Requires PIDTEMPBED)
  175. * M350 - Set microstepping mode. (Requires digital microstepping pins.)
  176. * M351 - Toggle MS1 MS2 pins directly. (Requires digital microstepping pins.)
  177. * M355 - Turn the Case Light on/off and set its brightness. (Requires CASE_LIGHT_PIN)
  178. * M380 - Activate solenoid on active extruder. (Requires EXT_SOLENOID)
  179. * M381 - Disable all solenoids. (Requires EXT_SOLENOID)
  180. * M400 - Finish all moves.
  181. * M401 - Lower Z probe. (Requires a probe)
  182. * M402 - Raise Z probe. (Requires a probe)
  183. * M404 - Display or set the Nominal Filament Width: "W<diameter>". (Requires FILAMENT_WIDTH_SENSOR)
  184. * M405 - Enable Filament Sensor flow control. "M405 D<delay_cm>". (Requires FILAMENT_WIDTH_SENSOR)
  185. * M406 - Disable Filament Sensor flow control. (Requires FILAMENT_WIDTH_SENSOR)
  186. * M407 - Display measured filament diameter in millimeters. (Requires FILAMENT_WIDTH_SENSOR)
  187. * M410 - Quickstop. Abort all planned moves.
  188. * M420 - Enable/Disable Leveling (with current values) S1=enable S0=disable (Requires MESH_BED_LEVELING or ABL)
  189. * 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)
  190. * M428 - Set the home_offset based on the current_position. Nearest edge applies. (Disabled by NO_WORKSPACE_OFFSETS or DELTA)
  191. * M500 - Store parameters in EEPROM. (Requires EEPROM_SETTINGS)
  192. * M501 - Restore parameters from EEPROM. (Requires EEPROM_SETTINGS)
  193. * M502 - Revert to the default "factory settings". ** Does not write them to EEPROM! **
  194. * M503 - Print the current settings (in memory): "M503 S<verbose>". S0 specifies compact output.
  195. * M540 - Enable/disable SD card abort on endstop hit: "M540 S<state>". (Requires ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  196. * M600 - Pause for filament change: "M600 X<pos> Y<pos> Z<raise> E<first_retract> L<later_retract>". (Requires ADVANCED_PAUSE_FEATURE)
  197. * 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)
  198. * M666 - Set delta endstop adjustment. (Requires DELTA)
  199. * M605 - Set dual x-carriage movement mode: "M605 S<mode> [X<x_offset>] [R<temp_offset>]". (Requires DUAL_X_CARRIAGE)
  200. * M851 - Set Z probe's Z offset in current units. (Negative = below the nozzle.)
  201. * M900 - Get and/or Set advance K factor and WH/D ratio. (Requires LIN_ADVANCE)
  202. * 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)
  203. * M907 - Set digital trimpot motor current using axis codes. (Requires a board with digital trimpots)
  204. * M908 - Control digital trimpot directly. (Requires DAC_STEPPER_CURRENT or DIGIPOTSS_PIN)
  205. * M909 - Print digipot/DAC current value. (Requires DAC_STEPPER_CURRENT)
  206. * M910 - Commit digipot/DAC value to external EEPROM via I2C. (Requires DAC_STEPPER_CURRENT)
  207. * M911 - Report stepper driver overtemperature pre-warn condition. (Requires HAVE_TMC2130)
  208. * M912 - Clear stepper driver overtemperature pre-warn condition flag. (Requires HAVE_TMC2130)
  209. * M913 - Set HYBRID_THRESHOLD speed. (Requires HYBRID_THRESHOLD)
  210. * M914 - Set SENSORLESS_HOMING sensitivity. (Requires SENSORLESS_HOMING)
  211. *
  212. * M360 - SCARA calibration: Move to cal-position ThetaA (0 deg calibration)
  213. * M361 - SCARA calibration: Move to cal-position ThetaB (90 deg calibration - steps per degree)
  214. * M362 - SCARA calibration: Move to cal-position PsiA (0 deg calibration)
  215. * M363 - SCARA calibration: Move to cal-position PsiB (90 deg calibration - steps per degree)
  216. * M364 - SCARA calibration: Move to cal-position PSIC (90 deg to Theta calibration position)
  217. *
  218. * ************ Custom codes - This can change to suit future G-code regulations
  219. * M928 - Start SD logging: "M928 filename.gco". Stop with M29. (Requires SDSUPPORT)
  220. * M999 - Restart after being stopped by error
  221. *
  222. * "T" Codes
  223. *
  224. * T0-T3 - Select an extruder (tool) by index: "T<n> F<units/min>"
  225. *
  226. */
  227. #include "Marlin.h"
  228. #include "ultralcd.h"
  229. #include "planner.h"
  230. #include "stepper.h"
  231. #include "endstops.h"
  232. #include "temperature.h"
  233. #include "cardreader.h"
  234. #include "configuration_store.h"
  235. #include "language.h"
  236. #include "pins_arduino.h"
  237. #include "math.h"
  238. #include "nozzle.h"
  239. #include "duration_t.h"
  240. #include "types.h"
  241. #include "gcode.h"
  242. #if HAS_ABL
  243. #include "vector_3.h"
  244. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  245. #include "qr_solve.h"
  246. #endif
  247. #elif ENABLED(MESH_BED_LEVELING)
  248. #include "mesh_bed_leveling.h"
  249. #endif
  250. #if ENABLED(BEZIER_CURVE_SUPPORT)
  251. #include "planner_bezier.h"
  252. #endif
  253. #if HAS_BUZZER && DISABLED(LCD_USE_I2C_BUZZER)
  254. #include "buzzer.h"
  255. #endif
  256. #if ENABLED(USE_WATCHDOG)
  257. #include "watchdog.h"
  258. #endif
  259. #if ENABLED(BLINKM)
  260. #include "blinkm.h"
  261. #include "Wire.h"
  262. #endif
  263. #if HAS_SERVOS
  264. #include "servo.h"
  265. #endif
  266. #if HAS_DIGIPOTSS
  267. #include <SPI.h>
  268. #endif
  269. #if ENABLED(DAC_STEPPER_CURRENT)
  270. #include "stepper_dac.h"
  271. #endif
  272. #if ENABLED(EXPERIMENTAL_I2CBUS)
  273. #include "twibus.h"
  274. #endif
  275. #if ENABLED(ENDSTOP_INTERRUPTS_FEATURE)
  276. #include "endstop_interrupts.h"
  277. #endif
  278. #if ENABLED(M100_FREE_MEMORY_WATCHER)
  279. void gcode_M100();
  280. void M100_dump_routine(const char * const title, const char *start, const char *end);
  281. #endif
  282. #if ENABLED(SDSUPPORT)
  283. CardReader card;
  284. #endif
  285. #if ENABLED(EXPERIMENTAL_I2CBUS)
  286. TWIBus i2c;
  287. #endif
  288. #if ENABLED(G38_PROBE_TARGET)
  289. bool G38_move = false,
  290. G38_endstop_hit = false;
  291. #endif
  292. #if ENABLED(AUTO_BED_LEVELING_UBL)
  293. #include "ubl.h"
  294. unified_bed_leveling ubl;
  295. #define UBL_MESH_VALID !( ( ubl.z_values[0][0] == ubl.z_values[0][1] && ubl.z_values[0][1] == ubl.z_values[0][2] \
  296. && ubl.z_values[1][0] == ubl.z_values[1][1] && ubl.z_values[1][1] == ubl.z_values[1][2] \
  297. && ubl.z_values[2][0] == ubl.z_values[2][1] && ubl.z_values[2][1] == ubl.z_values[2][2] \
  298. && ubl.z_values[0][0] == 0 && ubl.z_values[1][0] == 0 && ubl.z_values[2][0] == 0 ) \
  299. || isnan(ubl.z_values[0][0]))
  300. #endif
  301. bool Running = true;
  302. uint8_t marlin_debug_flags = DEBUG_NONE;
  303. /**
  304. * Cartesian Current Position
  305. * Used to track the logical position as moves are queued.
  306. * Used by 'line_to_current_position' to do a move after changing it.
  307. * Used by 'SYNC_PLAN_POSITION_KINEMATIC' to update 'planner.position'.
  308. */
  309. float current_position[XYZE] = { 0.0 };
  310. /**
  311. * Cartesian Destination
  312. * A temporary position, usually applied to 'current_position'.
  313. * Set with 'gcode_get_destination' or 'set_destination_to_current'.
  314. * 'line_to_destination' sets 'current_position' to 'destination'.
  315. */
  316. float destination[XYZE] = { 0.0 };
  317. /**
  318. * axis_homed
  319. * Flags that each linear axis was homed.
  320. * XYZ on cartesian, ABC on delta, ABZ on SCARA.
  321. *
  322. * axis_known_position
  323. * Flags that the position is known in each linear axis. Set when homed.
  324. * Cleared whenever a stepper powers off, potentially losing its position.
  325. */
  326. bool axis_homed[XYZ] = { false }, axis_known_position[XYZ] = { false };
  327. /**
  328. * GCode line number handling. Hosts may opt to include line numbers when
  329. * sending commands to Marlin, and lines will be checked for sequentiality.
  330. * M110 N<int> sets the current line number.
  331. */
  332. static long gcode_N, gcode_LastN, Stopped_gcode_LastN = 0;
  333. /**
  334. * GCode Command Queue
  335. * A simple ring buffer of BUFSIZE command strings.
  336. *
  337. * Commands are copied into this buffer by the command injectors
  338. * (immediate, serial, sd card) and they are processed sequentially by
  339. * the main loop. The process_next_command function parses the next
  340. * command and hands off execution to individual handler functions.
  341. */
  342. uint8_t commands_in_queue = 0; // Count of commands in the queue
  343. static uint8_t cmd_queue_index_r = 0, // Ring buffer read position
  344. cmd_queue_index_w = 0; // Ring buffer write position
  345. #if ENABLED(M100_FREE_MEMORY_WATCHER)
  346. char command_queue[BUFSIZE][MAX_CMD_SIZE]; // Necessary so M100 Free Memory Dumper can show us the commands and any corruption
  347. #else // This can be collapsed back to the way it was soon.
  348. static char command_queue[BUFSIZE][MAX_CMD_SIZE];
  349. #endif
  350. /**
  351. * Next Injected Command pointer. NULL if no commands are being injected.
  352. * Used by Marlin internally to ensure that commands initiated from within
  353. * are enqueued ahead of any pending serial or sd card commands.
  354. */
  355. static const char *injected_commands_P = NULL;
  356. #if ENABLED(TEMPERATURE_UNITS_SUPPORT)
  357. TempUnit input_temp_units = TEMPUNIT_C;
  358. #endif
  359. /**
  360. * Feed rates are often configured with mm/m
  361. * but the planner and stepper like mm/s units.
  362. */
  363. float constexpr homing_feedrate_mm_s[] = {
  364. #if ENABLED(DELTA)
  365. MMM_TO_MMS(HOMING_FEEDRATE_Z), MMM_TO_MMS(HOMING_FEEDRATE_Z),
  366. #else
  367. MMM_TO_MMS(HOMING_FEEDRATE_XY), MMM_TO_MMS(HOMING_FEEDRATE_XY),
  368. #endif
  369. MMM_TO_MMS(HOMING_FEEDRATE_Z), 0
  370. };
  371. float feedrate_mm_s = MMM_TO_MMS(1500.0);
  372. static float saved_feedrate_mm_s;
  373. int feedrate_percentage = 100, saved_feedrate_percentage,
  374. flow_percentage[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(100);
  375. bool axis_relative_modes[] = AXIS_RELATIVE_MODES,
  376. volumetric_enabled =
  377. #if ENABLED(VOLUMETRIC_DEFAULT_ON)
  378. true
  379. #else
  380. false
  381. #endif
  382. ;
  383. float filament_size[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(DEFAULT_NOMINAL_FILAMENT_DIA),
  384. volumetric_multiplier[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(1.0);
  385. #if HAS_WORKSPACE_OFFSET
  386. #if HAS_POSITION_SHIFT
  387. // The distance that XYZ has been offset by G92. Reset by G28.
  388. float position_shift[XYZ] = { 0 };
  389. #endif
  390. #if HAS_HOME_OFFSET
  391. // This offset is added to the configured home position.
  392. // Set by M206, M428, or menu item. Saved to EEPROM.
  393. float home_offset[XYZ] = { 0 };
  394. #endif
  395. #if HAS_HOME_OFFSET && HAS_POSITION_SHIFT
  396. // The above two are combined to save on computes
  397. float workspace_offset[XYZ] = { 0 };
  398. #endif
  399. #endif
  400. // Software Endstops are based on the configured limits.
  401. #if HAS_SOFTWARE_ENDSTOPS
  402. bool soft_endstops_enabled = true;
  403. #endif
  404. float soft_endstop_min[XYZ] = { X_MIN_POS, Y_MIN_POS, Z_MIN_POS },
  405. soft_endstop_max[XYZ] = { X_MAX_POS, Y_MAX_POS, Z_MAX_POS };
  406. #if FAN_COUNT > 0
  407. int16_t fanSpeeds[FAN_COUNT] = { 0 };
  408. #if ENABLED(PROBING_FANS_OFF)
  409. bool fans_paused = false;
  410. int16_t paused_fanSpeeds[FAN_COUNT] = { 0 };
  411. #endif
  412. #endif
  413. // The active extruder (tool). Set with T<extruder> command.
  414. uint8_t active_extruder = 0;
  415. // Relative Mode. Enable with G91, disable with G90.
  416. static bool relative_mode = false;
  417. // For M109 and M190, this flag may be cleared (by M108) to exit the wait loop
  418. volatile bool wait_for_heatup = true;
  419. // For M0/M1, this flag may be cleared (by M108) to exit the wait-for-user loop
  420. #if HAS_RESUME_CONTINUE
  421. volatile bool wait_for_user = false;
  422. #endif
  423. const char axis_codes[XYZE] = {'X', 'Y', 'Z', 'E'};
  424. // Number of characters read in the current line of serial input
  425. static int serial_count = 0;
  426. // Inactivity shutdown
  427. millis_t previous_cmd_ms = 0;
  428. static millis_t max_inactive_time = 0;
  429. static millis_t stepper_inactive_time = (DEFAULT_STEPPER_DEACTIVE_TIME) * 1000UL;
  430. // Print Job Timer
  431. #if ENABLED(PRINTCOUNTER)
  432. PrintCounter print_job_timer = PrintCounter();
  433. #else
  434. Stopwatch print_job_timer = Stopwatch();
  435. #endif
  436. // Buzzer - I2C on the LCD or a BEEPER_PIN
  437. #if ENABLED(LCD_USE_I2C_BUZZER)
  438. #define BUZZ(d,f) lcd_buzz(d, f)
  439. #elif PIN_EXISTS(BEEPER)
  440. Buzzer buzzer;
  441. #define BUZZ(d,f) buzzer.tone(d, f)
  442. #else
  443. #define BUZZ(d,f) NOOP
  444. #endif
  445. static uint8_t target_extruder;
  446. #if HAS_BED_PROBE
  447. float zprobe_zoffset = Z_PROBE_OFFSET_FROM_EXTRUDER;
  448. #endif
  449. #if HAS_ABL
  450. float xy_probe_feedrate_mm_s = MMM_TO_MMS(XY_PROBE_SPEED);
  451. #define XY_PROBE_FEEDRATE_MM_S xy_probe_feedrate_mm_s
  452. #elif defined(XY_PROBE_SPEED)
  453. #define XY_PROBE_FEEDRATE_MM_S MMM_TO_MMS(XY_PROBE_SPEED)
  454. #else
  455. #define XY_PROBE_FEEDRATE_MM_S PLANNER_XY_FEEDRATE()
  456. #endif
  457. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  458. #if ENABLED(DELTA)
  459. #define ADJUST_DELTA(V) \
  460. if (planner.abl_enabled) { \
  461. const float zadj = bilinear_z_offset(V); \
  462. delta[A_AXIS] += zadj; \
  463. delta[B_AXIS] += zadj; \
  464. delta[C_AXIS] += zadj; \
  465. }
  466. #else
  467. #define ADJUST_DELTA(V) if (planner.abl_enabled) { delta[Z_AXIS] += bilinear_z_offset(V); }
  468. #endif
  469. #elif IS_KINEMATIC
  470. #define ADJUST_DELTA(V) NOOP
  471. #endif
  472. #if ENABLED(Z_DUAL_ENDSTOPS)
  473. float z_endstop_adj =
  474. #ifdef Z_DUAL_ENDSTOPS_ADJUSTMENT
  475. Z_DUAL_ENDSTOPS_ADJUSTMENT
  476. #else
  477. 0
  478. #endif
  479. ;
  480. #endif
  481. // Extruder offsets
  482. #if HOTENDS > 1
  483. float hotend_offset[XYZ][HOTENDS];
  484. #endif
  485. #if HAS_Z_SERVO_ENDSTOP
  486. const int z_servo_angle[2] = Z_SERVO_ANGLES;
  487. #endif
  488. #if ENABLED(BARICUDA)
  489. int baricuda_valve_pressure = 0;
  490. int baricuda_e_to_p_pressure = 0;
  491. #endif
  492. #if ENABLED(FWRETRACT)
  493. bool autoretract_enabled = false;
  494. bool retracted[EXTRUDERS] = { false };
  495. bool retracted_swap[EXTRUDERS] = { false };
  496. float retract_length = RETRACT_LENGTH;
  497. float retract_length_swap = RETRACT_LENGTH_SWAP;
  498. float retract_feedrate_mm_s = RETRACT_FEEDRATE;
  499. float retract_zlift = RETRACT_ZLIFT;
  500. float retract_recover_length = RETRACT_RECOVER_LENGTH;
  501. float retract_recover_length_swap = RETRACT_RECOVER_LENGTH_SWAP;
  502. float retract_recover_feedrate_mm_s = RETRACT_RECOVER_FEEDRATE;
  503. #endif // FWRETRACT
  504. #if HAS_POWER_SWITCH
  505. bool powersupply_on =
  506. #if ENABLED(PS_DEFAULT_OFF)
  507. false
  508. #else
  509. true
  510. #endif
  511. ;
  512. #endif
  513. #if HAS_CASE_LIGHT
  514. bool case_light_on =
  515. #if ENABLED(CASE_LIGHT_DEFAULT_ON)
  516. true
  517. #else
  518. false
  519. #endif
  520. ;
  521. #endif
  522. #if ENABLED(DELTA)
  523. float delta[ABC],
  524. endstop_adj[ABC] = { 0 };
  525. // These values are loaded or reset at boot time when setup() calls
  526. // settings.load(), which calls recalc_delta_settings().
  527. float delta_radius,
  528. delta_tower_angle_trim[2],
  529. delta_tower[ABC][2],
  530. delta_diagonal_rod,
  531. delta_calibration_radius,
  532. delta_diagonal_rod_2_tower[ABC],
  533. delta_segments_per_second,
  534. delta_clip_start_height = Z_MAX_POS;
  535. float delta_safe_distance_from_top();
  536. #endif
  537. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  538. int bilinear_grid_spacing[2], bilinear_start[2];
  539. float bilinear_grid_factor[2],
  540. z_values[GRID_MAX_POINTS_X][GRID_MAX_POINTS_Y];
  541. #endif
  542. #if IS_SCARA
  543. // Float constants for SCARA calculations
  544. const float L1 = SCARA_LINKAGE_1, L2 = SCARA_LINKAGE_2,
  545. L1_2 = sq(float(L1)), L1_2_2 = 2.0 * L1_2,
  546. L2_2 = sq(float(L2));
  547. float delta_segments_per_second = SCARA_SEGMENTS_PER_SECOND,
  548. delta[ABC];
  549. #endif
  550. float cartes[XYZ] = { 0 };
  551. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  552. bool filament_sensor = false; // M405 turns on filament sensor control. M406 turns it off.
  553. float filament_width_nominal = DEFAULT_NOMINAL_FILAMENT_DIA, // Nominal filament width. Change with M404.
  554. filament_width_meas = DEFAULT_MEASURED_FILAMENT_DIA; // Measured filament diameter
  555. int8_t measurement_delay[MAX_MEASUREMENT_DELAY + 1]; // Ring buffer to delayed measurement. Store extruder factor after subtracting 100
  556. int filwidth_delay_index[2] = { 0, -1 }; // Indexes into ring buffer
  557. int meas_delay_cm = MEASUREMENT_DELAY_CM; // Distance delay setting
  558. #endif
  559. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  560. static bool filament_ran_out = false;
  561. #endif
  562. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  563. AdvancedPauseMenuResponse advanced_pause_menu_response;
  564. #endif
  565. #if ENABLED(MIXING_EXTRUDER)
  566. float mixing_factor[MIXING_STEPPERS]; // Reciprocal of mix proportion. 0.0 = off, otherwise >= 1.0.
  567. #if MIXING_VIRTUAL_TOOLS > 1
  568. float mixing_virtual_tool_mix[MIXING_VIRTUAL_TOOLS][MIXING_STEPPERS];
  569. #endif
  570. #endif
  571. static bool send_ok[BUFSIZE];
  572. #if HAS_SERVOS
  573. Servo servo[NUM_SERVOS];
  574. #define MOVE_SERVO(I, P) servo[I].move(P)
  575. #if HAS_Z_SERVO_ENDSTOP
  576. #define DEPLOY_Z_SERVO() MOVE_SERVO(Z_ENDSTOP_SERVO_NR, z_servo_angle[0])
  577. #define STOW_Z_SERVO() MOVE_SERVO(Z_ENDSTOP_SERVO_NR, z_servo_angle[1])
  578. #endif
  579. #endif
  580. #ifdef CHDK
  581. millis_t chdkHigh = 0;
  582. bool chdkActive = false;
  583. #endif
  584. #ifdef AUTOMATIC_CURRENT_CONTROL
  585. bool auto_current_control = 0;
  586. #endif
  587. #if ENABLED(PID_EXTRUSION_SCALING)
  588. int lpq_len = 20;
  589. #endif
  590. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  591. MarlinBusyState busy_state = NOT_BUSY;
  592. static millis_t next_busy_signal_ms = 0;
  593. uint8_t host_keepalive_interval = DEFAULT_KEEPALIVE_INTERVAL;
  594. #else
  595. #define host_keepalive() NOOP
  596. #endif
  597. static inline float pgm_read_any(const float *p) { return pgm_read_float_near(p); }
  598. static inline signed char pgm_read_any(const signed char *p) { return pgm_read_byte_near(p); }
  599. #define XYZ_CONSTS_FROM_CONFIG(type, array, CONFIG) \
  600. static const PROGMEM type array##_P[XYZ] = { X_##CONFIG, Y_##CONFIG, Z_##CONFIG }; \
  601. static inline type array(AxisEnum axis) { return pgm_read_any(&array##_P[axis]); } \
  602. typedef void __void_##CONFIG##__
  603. XYZ_CONSTS_FROM_CONFIG(float, base_min_pos, MIN_POS);
  604. XYZ_CONSTS_FROM_CONFIG(float, base_max_pos, MAX_POS);
  605. XYZ_CONSTS_FROM_CONFIG(float, base_home_pos, HOME_POS);
  606. XYZ_CONSTS_FROM_CONFIG(float, max_length, MAX_LENGTH);
  607. XYZ_CONSTS_FROM_CONFIG(float, home_bump_mm, HOME_BUMP_MM);
  608. XYZ_CONSTS_FROM_CONFIG(signed char, home_dir, HOME_DIR);
  609. /**
  610. * ***************************************************************************
  611. * ******************************** FUNCTIONS ********************************
  612. * ***************************************************************************
  613. */
  614. void stop();
  615. void get_available_commands();
  616. void process_next_command();
  617. void prepare_move_to_destination();
  618. void get_cartesian_from_steppers();
  619. void set_current_from_steppers_for_axis(const AxisEnum axis);
  620. #if ENABLED(ARC_SUPPORT)
  621. void plan_arc(float target[XYZE], float* offset, uint8_t clockwise);
  622. #endif
  623. #if ENABLED(BEZIER_CURVE_SUPPORT)
  624. void plan_cubic_move(const float offset[4]);
  625. #endif
  626. void tool_change(const uint8_t tmp_extruder, const float fr_mm_s=0.0, bool no_move=false);
  627. static void report_current_position();
  628. #if ENABLED(DEBUG_LEVELING_FEATURE)
  629. void print_xyz(const char* prefix, const char* suffix, const float x, const float y, const float z) {
  630. serialprintPGM(prefix);
  631. SERIAL_CHAR('(');
  632. SERIAL_ECHO(x);
  633. SERIAL_ECHOPAIR(", ", y);
  634. SERIAL_ECHOPAIR(", ", z);
  635. SERIAL_CHAR(')');
  636. suffix ? serialprintPGM(suffix) : SERIAL_EOL;
  637. }
  638. void print_xyz(const char* prefix, const char* suffix, const float xyz[]) {
  639. print_xyz(prefix, suffix, xyz[X_AXIS], xyz[Y_AXIS], xyz[Z_AXIS]);
  640. }
  641. #if HAS_ABL
  642. void print_xyz(const char* prefix, const char* suffix, const vector_3 &xyz) {
  643. print_xyz(prefix, suffix, xyz.x, xyz.y, xyz.z);
  644. }
  645. #endif
  646. #define DEBUG_POS(SUFFIX,VAR) do { \
  647. print_xyz(PSTR(" " STRINGIFY(VAR) "="), PSTR(" : " SUFFIX "\n"), VAR); } while(0)
  648. #endif
  649. /**
  650. * sync_plan_position
  651. *
  652. * Set the planner/stepper positions directly from current_position with
  653. * no kinematic translation. Used for homing axes and cartesian/core syncing.
  654. */
  655. inline void sync_plan_position() {
  656. #if ENABLED(DEBUG_LEVELING_FEATURE)
  657. if (DEBUGGING(LEVELING)) DEBUG_POS("sync_plan_position", current_position);
  658. #endif
  659. planner.set_position_mm(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  660. }
  661. inline void sync_plan_position_e() { planner.set_e_position_mm(current_position[E_AXIS]); }
  662. #if IS_KINEMATIC
  663. inline void sync_plan_position_kinematic() {
  664. #if ENABLED(DEBUG_LEVELING_FEATURE)
  665. if (DEBUGGING(LEVELING)) DEBUG_POS("sync_plan_position_kinematic", current_position);
  666. #endif
  667. planner.set_position_mm_kinematic(current_position);
  668. }
  669. #define SYNC_PLAN_POSITION_KINEMATIC() sync_plan_position_kinematic()
  670. #else
  671. #define SYNC_PLAN_POSITION_KINEMATIC() sync_plan_position()
  672. #endif
  673. #if ENABLED(SDSUPPORT)
  674. #include "SdFatUtil.h"
  675. int freeMemory() { return SdFatUtil::FreeRam(); }
  676. #else
  677. extern "C" {
  678. extern char __bss_end;
  679. extern char __heap_start;
  680. extern void* __brkval;
  681. int freeMemory() {
  682. int free_memory;
  683. if ((int)__brkval == 0)
  684. free_memory = ((int)&free_memory) - ((int)&__bss_end);
  685. else
  686. free_memory = ((int)&free_memory) - ((int)__brkval);
  687. return free_memory;
  688. }
  689. }
  690. #endif // !SDSUPPORT
  691. #if ENABLED(DIGIPOT_I2C)
  692. extern void digipot_i2c_set_current(int channel, float current);
  693. extern void digipot_i2c_init();
  694. #endif
  695. /**
  696. * Inject the next "immediate" command, when possible, onto the front of the queue.
  697. * Return true if any immediate commands remain to inject.
  698. */
  699. static bool drain_injected_commands_P() {
  700. if (injected_commands_P != NULL) {
  701. size_t i = 0;
  702. char c, cmd[30];
  703. strncpy_P(cmd, injected_commands_P, sizeof(cmd) - 1);
  704. cmd[sizeof(cmd) - 1] = '\0';
  705. while ((c = cmd[i]) && c != '\n') i++; // find the end of this gcode command
  706. cmd[i] = '\0';
  707. if (enqueue_and_echo_command(cmd)) // success?
  708. injected_commands_P = c ? injected_commands_P + i + 1 : NULL; // next command or done
  709. }
  710. return (injected_commands_P != NULL); // return whether any more remain
  711. }
  712. /**
  713. * Record one or many commands to run from program memory.
  714. * Aborts the current queue, if any.
  715. * Note: drain_injected_commands_P() must be called repeatedly to drain the commands afterwards
  716. */
  717. void enqueue_and_echo_commands_P(const char * const pgcode) {
  718. injected_commands_P = pgcode;
  719. drain_injected_commands_P(); // first command executed asap (when possible)
  720. }
  721. /**
  722. * Clear the Marlin command queue
  723. */
  724. void clear_command_queue() {
  725. cmd_queue_index_r = cmd_queue_index_w;
  726. commands_in_queue = 0;
  727. }
  728. /**
  729. * Once a new command is in the ring buffer, call this to commit it
  730. */
  731. inline void _commit_command(bool say_ok) {
  732. send_ok[cmd_queue_index_w] = say_ok;
  733. if (++cmd_queue_index_w >= BUFSIZE) cmd_queue_index_w = 0;
  734. commands_in_queue++;
  735. }
  736. /**
  737. * Copy a command from RAM into the main command buffer.
  738. * Return true if the command was successfully added.
  739. * Return false for a full buffer, or if the 'command' is a comment.
  740. */
  741. inline bool _enqueuecommand(const char* cmd, bool say_ok=false) {
  742. if (*cmd == ';' || commands_in_queue >= BUFSIZE) return false;
  743. strcpy(command_queue[cmd_queue_index_w], cmd);
  744. _commit_command(say_ok);
  745. return true;
  746. }
  747. /**
  748. * Enqueue with Serial Echo
  749. */
  750. bool enqueue_and_echo_command(const char* cmd, bool say_ok/*=false*/) {
  751. if (_enqueuecommand(cmd, say_ok)) {
  752. SERIAL_ECHO_START;
  753. SERIAL_ECHOPAIR(MSG_ENQUEUEING, cmd);
  754. SERIAL_CHAR('"');
  755. SERIAL_EOL;
  756. return true;
  757. }
  758. return false;
  759. }
  760. void setup_killpin() {
  761. #if HAS_KILL
  762. SET_INPUT_PULLUP(KILL_PIN);
  763. #endif
  764. }
  765. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  766. void setup_filrunoutpin() {
  767. #if ENABLED(ENDSTOPPULLUP_FIL_RUNOUT)
  768. SET_INPUT_PULLUP(FIL_RUNOUT_PIN);
  769. #else
  770. SET_INPUT(FIL_RUNOUT_PIN);
  771. #endif
  772. }
  773. #endif
  774. void setup_homepin(void) {
  775. #if HAS_HOME
  776. SET_INPUT_PULLUP(HOME_PIN);
  777. #endif
  778. }
  779. void setup_powerhold() {
  780. #if HAS_SUICIDE
  781. OUT_WRITE(SUICIDE_PIN, HIGH);
  782. #endif
  783. #if HAS_POWER_SWITCH
  784. #if ENABLED(PS_DEFAULT_OFF)
  785. OUT_WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  786. #else
  787. OUT_WRITE(PS_ON_PIN, PS_ON_AWAKE);
  788. #endif
  789. #endif
  790. }
  791. void suicide() {
  792. #if HAS_SUICIDE
  793. OUT_WRITE(SUICIDE_PIN, LOW);
  794. #endif
  795. }
  796. void servo_init() {
  797. #if NUM_SERVOS >= 1 && HAS_SERVO_0
  798. servo[0].attach(SERVO0_PIN);
  799. servo[0].detach(); // Just set up the pin. We don't have a position yet. Don't move to a random position.
  800. #endif
  801. #if NUM_SERVOS >= 2 && HAS_SERVO_1
  802. servo[1].attach(SERVO1_PIN);
  803. servo[1].detach();
  804. #endif
  805. #if NUM_SERVOS >= 3 && HAS_SERVO_2
  806. servo[2].attach(SERVO2_PIN);
  807. servo[2].detach();
  808. #endif
  809. #if NUM_SERVOS >= 4 && HAS_SERVO_3
  810. servo[3].attach(SERVO3_PIN);
  811. servo[3].detach();
  812. #endif
  813. #if HAS_Z_SERVO_ENDSTOP
  814. /**
  815. * Set position of Z Servo Endstop
  816. *
  817. * The servo might be deployed and positioned too low to stow
  818. * when starting up the machine or rebooting the board.
  819. * There's no way to know where the nozzle is positioned until
  820. * homing has been done - no homing with z-probe without init!
  821. *
  822. */
  823. STOW_Z_SERVO();
  824. #endif
  825. }
  826. /**
  827. * Stepper Reset (RigidBoard, et.al.)
  828. */
  829. #if HAS_STEPPER_RESET
  830. void disableStepperDrivers() {
  831. OUT_WRITE(STEPPER_RESET_PIN, LOW); // drive it down to hold in reset motor driver chips
  832. }
  833. void enableStepperDrivers() { SET_INPUT(STEPPER_RESET_PIN); } // set to input, which allows it to be pulled high by pullups
  834. #endif
  835. #if ENABLED(EXPERIMENTAL_I2CBUS) && I2C_SLAVE_ADDRESS > 0
  836. void i2c_on_receive(int bytes) { // just echo all bytes received to serial
  837. i2c.receive(bytes);
  838. }
  839. void i2c_on_request() { // just send dummy data for now
  840. i2c.reply("Hello World!\n");
  841. }
  842. #endif
  843. #if HAS_COLOR_LEDS
  844. void set_led_color(
  845. const uint8_t r, const uint8_t g, const uint8_t b
  846. #if ENABLED(RGBW_LED)
  847. , const uint8_t w=0
  848. #endif
  849. ) {
  850. #if ENABLED(BLINKM)
  851. // This variant uses i2c to send the RGB components to the device.
  852. SendColors(r, g, b);
  853. #else
  854. // This variant uses 3 separate pins for the RGB components.
  855. // If the pins can do PWM then their intensity will be set.
  856. WRITE(RGB_LED_R_PIN, r ? HIGH : LOW);
  857. WRITE(RGB_LED_G_PIN, g ? HIGH : LOW);
  858. WRITE(RGB_LED_B_PIN, b ? HIGH : LOW);
  859. analogWrite(RGB_LED_R_PIN, r);
  860. analogWrite(RGB_LED_G_PIN, g);
  861. analogWrite(RGB_LED_B_PIN, b);
  862. #if ENABLED(RGBW_LED)
  863. WRITE(RGB_LED_W_PIN, w ? HIGH : LOW);
  864. analogWrite(RGB_LED_W_PIN, w);
  865. #endif
  866. #endif
  867. }
  868. #endif // HAS_COLOR_LEDS
  869. void gcode_line_error(const char* err, bool doFlush = true) {
  870. SERIAL_ERROR_START;
  871. serialprintPGM(err);
  872. SERIAL_ERRORLN(gcode_LastN);
  873. //Serial.println(gcode_N);
  874. if (doFlush) FlushSerialRequestResend();
  875. serial_count = 0;
  876. }
  877. /**
  878. * Get all commands waiting on the serial port and queue them.
  879. * Exit when the buffer is full or when no more characters are
  880. * left on the serial port.
  881. */
  882. inline void get_serial_commands() {
  883. static char serial_line_buffer[MAX_CMD_SIZE];
  884. static bool serial_comment_mode = false;
  885. // If the command buffer is empty for too long,
  886. // send "wait" to indicate Marlin is still waiting.
  887. #if defined(NO_TIMEOUTS) && NO_TIMEOUTS > 0
  888. static millis_t last_command_time = 0;
  889. const millis_t ms = millis();
  890. if (commands_in_queue == 0 && !MYSERIAL.available() && ELAPSED(ms, last_command_time + NO_TIMEOUTS)) {
  891. SERIAL_ECHOLNPGM(MSG_WAIT);
  892. last_command_time = ms;
  893. }
  894. #endif
  895. /**
  896. * Loop while serial characters are incoming and the queue is not full
  897. */
  898. while (commands_in_queue < BUFSIZE && MYSERIAL.available() > 0) {
  899. char serial_char = MYSERIAL.read();
  900. /**
  901. * If the character ends the line
  902. */
  903. if (serial_char == '\n' || serial_char == '\r') {
  904. serial_comment_mode = false; // end of line == end of comment
  905. if (!serial_count) continue; // skip empty lines
  906. serial_line_buffer[serial_count] = 0; // terminate string
  907. serial_count = 0; //reset buffer
  908. char* command = serial_line_buffer;
  909. while (*command == ' ') command++; // skip any leading spaces
  910. char *npos = (*command == 'N') ? command : NULL, // Require the N parameter to start the line
  911. *apos = strchr(command, '*');
  912. if (npos) {
  913. bool M110 = strstr_P(command, PSTR("M110")) != NULL;
  914. if (M110) {
  915. char* n2pos = strchr(command + 4, 'N');
  916. if (n2pos) npos = n2pos;
  917. }
  918. gcode_N = strtol(npos + 1, NULL, 10);
  919. if (gcode_N != gcode_LastN + 1 && !M110) {
  920. gcode_line_error(PSTR(MSG_ERR_LINE_NO));
  921. return;
  922. }
  923. if (apos) {
  924. byte checksum = 0, count = 0;
  925. while (command[count] != '*') checksum ^= command[count++];
  926. if (strtol(apos + 1, NULL, 10) != checksum) {
  927. gcode_line_error(PSTR(MSG_ERR_CHECKSUM_MISMATCH));
  928. return;
  929. }
  930. // if no errors, continue parsing
  931. }
  932. else {
  933. gcode_line_error(PSTR(MSG_ERR_NO_CHECKSUM));
  934. return;
  935. }
  936. gcode_LastN = gcode_N;
  937. // if no errors, continue parsing
  938. }
  939. else if (apos) { // No '*' without 'N'
  940. gcode_line_error(PSTR(MSG_ERR_NO_LINENUMBER_WITH_CHECKSUM), false);
  941. return;
  942. }
  943. // Movement commands alert when stopped
  944. if (IsStopped()) {
  945. char* gpos = strchr(command, 'G');
  946. if (gpos) {
  947. const int codenum = strtol(gpos + 1, NULL, 10);
  948. switch (codenum) {
  949. case 0:
  950. case 1:
  951. case 2:
  952. case 3:
  953. SERIAL_ERRORLNPGM(MSG_ERR_STOPPED);
  954. LCD_MESSAGEPGM(MSG_STOPPED);
  955. break;
  956. }
  957. }
  958. }
  959. #if DISABLED(EMERGENCY_PARSER)
  960. // If command was e-stop process now
  961. if (strcmp(command, "M108") == 0) {
  962. wait_for_heatup = false;
  963. #if ENABLED(ULTIPANEL)
  964. wait_for_user = false;
  965. #endif
  966. }
  967. if (strcmp(command, "M112") == 0) kill(PSTR(MSG_KILLED));
  968. if (strcmp(command, "M410") == 0) { quickstop_stepper(); }
  969. #endif
  970. #if defined(NO_TIMEOUTS) && NO_TIMEOUTS > 0
  971. last_command_time = ms;
  972. #endif
  973. // Add the command to the queue
  974. _enqueuecommand(serial_line_buffer, true);
  975. }
  976. else if (serial_count >= MAX_CMD_SIZE - 1) {
  977. // Keep fetching, but ignore normal characters beyond the max length
  978. // The command will be injected when EOL is reached
  979. }
  980. else if (serial_char == '\\') { // Handle escapes
  981. if (MYSERIAL.available() > 0) {
  982. // if we have one more character, copy it over
  983. serial_char = MYSERIAL.read();
  984. if (!serial_comment_mode) serial_line_buffer[serial_count++] = serial_char;
  985. }
  986. // otherwise do nothing
  987. }
  988. else { // it's not a newline, carriage return or escape char
  989. if (serial_char == ';') serial_comment_mode = true;
  990. if (!serial_comment_mode) serial_line_buffer[serial_count++] = serial_char;
  991. }
  992. } // queue has space, serial has data
  993. }
  994. #if ENABLED(SDSUPPORT)
  995. /**
  996. * Get commands from the SD Card until the command buffer is full
  997. * or until the end of the file is reached. The special character '#'
  998. * can also interrupt buffering.
  999. */
  1000. inline void get_sdcard_commands() {
  1001. static bool stop_buffering = false,
  1002. sd_comment_mode = false;
  1003. if (!card.sdprinting) return;
  1004. /**
  1005. * '#' stops reading from SD to the buffer prematurely, so procedural
  1006. * macro calls are possible. If it occurs, stop_buffering is triggered
  1007. * and the buffer is run dry; this character _can_ occur in serial com
  1008. * due to checksums, however, no checksums are used in SD printing.
  1009. */
  1010. if (commands_in_queue == 0) stop_buffering = false;
  1011. uint16_t sd_count = 0;
  1012. bool card_eof = card.eof();
  1013. while (commands_in_queue < BUFSIZE && !card_eof && !stop_buffering) {
  1014. const int16_t n = card.get();
  1015. char sd_char = (char)n;
  1016. card_eof = card.eof();
  1017. if (card_eof || n == -1
  1018. || sd_char == '\n' || sd_char == '\r'
  1019. || ((sd_char == '#' || sd_char == ':') && !sd_comment_mode)
  1020. ) {
  1021. if (card_eof) {
  1022. SERIAL_PROTOCOLLNPGM(MSG_FILE_PRINTED);
  1023. card.printingHasFinished();
  1024. #if ENABLED(PRINTER_EVENT_LEDS)
  1025. LCD_MESSAGEPGM(MSG_INFO_COMPLETED_PRINTS);
  1026. set_led_color(0, 255, 0); // Green
  1027. #if HAS_RESUME_CONTINUE
  1028. enqueue_and_echo_commands_P(PSTR("M0")); // end of the queue!
  1029. #else
  1030. safe_delay(1000);
  1031. #endif
  1032. set_led_color(0, 0, 0); // OFF
  1033. #endif
  1034. card.checkautostart(true);
  1035. }
  1036. else if (n == -1) {
  1037. SERIAL_ERROR_START;
  1038. SERIAL_ECHOLNPGM(MSG_SD_ERR_READ);
  1039. }
  1040. if (sd_char == '#') stop_buffering = true;
  1041. sd_comment_mode = false; // for new command
  1042. if (!sd_count) continue; // skip empty lines (and comment lines)
  1043. command_queue[cmd_queue_index_w][sd_count] = '\0'; // terminate string
  1044. sd_count = 0; // clear sd line buffer
  1045. _commit_command(false);
  1046. }
  1047. else if (sd_count >= MAX_CMD_SIZE - 1) {
  1048. /**
  1049. * Keep fetching, but ignore normal characters beyond the max length
  1050. * The command will be injected when EOL is reached
  1051. */
  1052. }
  1053. else {
  1054. if (sd_char == ';') sd_comment_mode = true;
  1055. if (!sd_comment_mode) command_queue[cmd_queue_index_w][sd_count++] = sd_char;
  1056. }
  1057. }
  1058. }
  1059. #endif // SDSUPPORT
  1060. /**
  1061. * Add to the circular command queue the next command from:
  1062. * - The command-injection queue (injected_commands_P)
  1063. * - The active serial input (usually USB)
  1064. * - The SD card file being actively printed
  1065. */
  1066. void get_available_commands() {
  1067. // if any immediate commands remain, don't get other commands yet
  1068. if (drain_injected_commands_P()) return;
  1069. get_serial_commands();
  1070. #if ENABLED(SDSUPPORT)
  1071. get_sdcard_commands();
  1072. #endif
  1073. }
  1074. /**
  1075. * Set target_extruder from the T parameter or the active_extruder
  1076. *
  1077. * Returns TRUE if the target is invalid
  1078. */
  1079. bool get_target_extruder_from_command(int code) {
  1080. if (parser.seen('T')) {
  1081. if (parser.value_byte() >= EXTRUDERS) {
  1082. SERIAL_ECHO_START;
  1083. SERIAL_CHAR('M');
  1084. SERIAL_ECHO(code);
  1085. SERIAL_ECHOLNPAIR(" " MSG_INVALID_EXTRUDER " ", parser.value_byte());
  1086. return true;
  1087. }
  1088. target_extruder = parser.value_byte();
  1089. }
  1090. else
  1091. target_extruder = active_extruder;
  1092. return false;
  1093. }
  1094. #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(DUAL_NOZZLE_DUPLICATION_MODE)
  1095. bool extruder_duplication_enabled = false; // Used in Dual X mode 2
  1096. #endif
  1097. #if ENABLED(DUAL_X_CARRIAGE)
  1098. static DualXMode dual_x_carriage_mode = DEFAULT_DUAL_X_CARRIAGE_MODE;
  1099. static float x_home_pos(const int extruder) {
  1100. if (extruder == 0)
  1101. return LOGICAL_X_POSITION(base_home_pos(X_AXIS));
  1102. else
  1103. /**
  1104. * In dual carriage mode the extruder offset provides an override of the
  1105. * second X-carriage position when homed - otherwise X2_HOME_POS is used.
  1106. * This allows soft recalibration of the second extruder home position
  1107. * without firmware reflash (through the M218 command).
  1108. */
  1109. return LOGICAL_X_POSITION(hotend_offset[X_AXIS][1] > 0 ? hotend_offset[X_AXIS][1] : X2_HOME_POS);
  1110. }
  1111. static int x_home_dir(const int extruder) { return extruder ? X2_HOME_DIR : X_HOME_DIR; }
  1112. static float inactive_extruder_x_pos = X2_MAX_POS; // used in mode 0 & 1
  1113. static bool active_extruder_parked = false; // used in mode 1 & 2
  1114. static float raised_parked_position[XYZE]; // used in mode 1
  1115. static millis_t delayed_move_time = 0; // used in mode 1
  1116. static float duplicate_extruder_x_offset = DEFAULT_DUPLICATION_X_OFFSET; // used in mode 2
  1117. static int16_t duplicate_extruder_temp_offset = 0; // used in mode 2
  1118. #endif // DUAL_X_CARRIAGE
  1119. #if HAS_WORKSPACE_OFFSET || ENABLED(DUAL_X_CARRIAGE)
  1120. /**
  1121. * Software endstops can be used to monitor the open end of
  1122. * an axis that has a hardware endstop on the other end. Or
  1123. * they can prevent axes from moving past endstops and grinding.
  1124. *
  1125. * To keep doing their job as the coordinate system changes,
  1126. * the software endstop positions must be refreshed to remain
  1127. * at the same positions relative to the machine.
  1128. */
  1129. void update_software_endstops(const AxisEnum axis) {
  1130. const float offs = 0.0
  1131. #if HAS_HOME_OFFSET
  1132. + home_offset[axis]
  1133. #endif
  1134. #if HAS_POSITION_SHIFT
  1135. + position_shift[axis]
  1136. #endif
  1137. ;
  1138. #if HAS_HOME_OFFSET && HAS_POSITION_SHIFT
  1139. workspace_offset[axis] = offs;
  1140. #endif
  1141. #if ENABLED(DUAL_X_CARRIAGE)
  1142. if (axis == X_AXIS) {
  1143. // In Dual X mode hotend_offset[X] is T1's home position
  1144. float dual_max_x = max(hotend_offset[X_AXIS][1], X2_MAX_POS);
  1145. if (active_extruder != 0) {
  1146. // T1 can move from X2_MIN_POS to X2_MAX_POS or X2 home position (whichever is larger)
  1147. soft_endstop_min[X_AXIS] = X2_MIN_POS + offs;
  1148. soft_endstop_max[X_AXIS] = dual_max_x + offs;
  1149. }
  1150. else if (dual_x_carriage_mode == DXC_DUPLICATION_MODE) {
  1151. // In Duplication Mode, T0 can move as far left as X_MIN_POS
  1152. // but not so far to the right that T1 would move past the end
  1153. soft_endstop_min[X_AXIS] = base_min_pos(X_AXIS) + offs;
  1154. soft_endstop_max[X_AXIS] = min(base_max_pos(X_AXIS), dual_max_x - duplicate_extruder_x_offset) + offs;
  1155. }
  1156. else {
  1157. // In other modes, T0 can move from X_MIN_POS to X_MAX_POS
  1158. soft_endstop_min[axis] = base_min_pos(axis) + offs;
  1159. soft_endstop_max[axis] = base_max_pos(axis) + offs;
  1160. }
  1161. }
  1162. #else
  1163. soft_endstop_min[axis] = base_min_pos(axis) + offs;
  1164. soft_endstop_max[axis] = base_max_pos(axis) + offs;
  1165. #endif
  1166. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1167. if (DEBUGGING(LEVELING)) {
  1168. SERIAL_ECHOPAIR("For ", axis_codes[axis]);
  1169. #if HAS_HOME_OFFSET
  1170. SERIAL_ECHOPAIR(" axis:\n home_offset = ", home_offset[axis]);
  1171. #endif
  1172. #if HAS_POSITION_SHIFT
  1173. SERIAL_ECHOPAIR("\n position_shift = ", position_shift[axis]);
  1174. #endif
  1175. SERIAL_ECHOPAIR("\n soft_endstop_min = ", soft_endstop_min[axis]);
  1176. SERIAL_ECHOLNPAIR("\n soft_endstop_max = ", soft_endstop_max[axis]);
  1177. }
  1178. #endif
  1179. #if ENABLED(DELTA)
  1180. if (axis == Z_AXIS)
  1181. delta_clip_start_height = soft_endstop_max[axis] - delta_safe_distance_from_top();
  1182. #endif
  1183. }
  1184. #endif // HAS_WORKSPACE_OFFSET || DUAL_X_CARRIAGE
  1185. #if HAS_M206_COMMAND
  1186. /**
  1187. * Change the home offset for an axis, update the current
  1188. * position and the software endstops to retain the same
  1189. * relative distance to the new home.
  1190. *
  1191. * Since this changes the current_position, code should
  1192. * call sync_plan_position soon after this.
  1193. */
  1194. static void set_home_offset(const AxisEnum axis, const float v) {
  1195. current_position[axis] += v - home_offset[axis];
  1196. home_offset[axis] = v;
  1197. update_software_endstops(axis);
  1198. }
  1199. #endif // HAS_M206_COMMAND
  1200. /**
  1201. * Set an axis' current position to its home position (after homing).
  1202. *
  1203. * For Core and Cartesian robots this applies one-to-one when an
  1204. * individual axis has been homed.
  1205. *
  1206. * DELTA should wait until all homing is done before setting the XYZ
  1207. * current_position to home, because homing is a single operation.
  1208. * In the case where the axis positions are already known and previously
  1209. * homed, DELTA could home to X or Y individually by moving either one
  1210. * to the center. However, homing Z always homes XY and Z.
  1211. *
  1212. * SCARA should wait until all XY homing is done before setting the XY
  1213. * current_position to home, because neither X nor Y is at home until
  1214. * both are at home. Z can however be homed individually.
  1215. *
  1216. * Callers must sync the planner position after calling this!
  1217. */
  1218. static void set_axis_is_at_home(AxisEnum axis) {
  1219. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1220. if (DEBUGGING(LEVELING)) {
  1221. SERIAL_ECHOPAIR(">>> set_axis_is_at_home(", axis_codes[axis]);
  1222. SERIAL_CHAR(')');
  1223. SERIAL_EOL;
  1224. }
  1225. #endif
  1226. axis_known_position[axis] = axis_homed[axis] = true;
  1227. #if HAS_POSITION_SHIFT
  1228. position_shift[axis] = 0;
  1229. update_software_endstops(axis);
  1230. #endif
  1231. #if ENABLED(DUAL_X_CARRIAGE)
  1232. if (axis == X_AXIS && (active_extruder == 1 || dual_x_carriage_mode == DXC_DUPLICATION_MODE)) {
  1233. current_position[X_AXIS] = x_home_pos(active_extruder);
  1234. return;
  1235. }
  1236. #endif
  1237. #if ENABLED(MORGAN_SCARA)
  1238. /**
  1239. * Morgan SCARA homes XY at the same time
  1240. */
  1241. if (axis == X_AXIS || axis == Y_AXIS) {
  1242. float homeposition[XYZ];
  1243. LOOP_XYZ(i) homeposition[i] = LOGICAL_POSITION(base_home_pos((AxisEnum)i), i);
  1244. // SERIAL_ECHOPAIR("homeposition X:", homeposition[X_AXIS]);
  1245. // SERIAL_ECHOLNPAIR(" Y:", homeposition[Y_AXIS]);
  1246. /**
  1247. * Get Home position SCARA arm angles using inverse kinematics,
  1248. * and calculate homing offset using forward kinematics
  1249. */
  1250. inverse_kinematics(homeposition);
  1251. forward_kinematics_SCARA(delta[A_AXIS], delta[B_AXIS]);
  1252. // SERIAL_ECHOPAIR("Cartesian X:", cartes[X_AXIS]);
  1253. // SERIAL_ECHOLNPAIR(" Y:", cartes[Y_AXIS]);
  1254. current_position[axis] = LOGICAL_POSITION(cartes[axis], axis);
  1255. /**
  1256. * SCARA home positions are based on configuration since the actual
  1257. * limits are determined by the inverse kinematic transform.
  1258. */
  1259. soft_endstop_min[axis] = base_min_pos(axis); // + (cartes[axis] - base_home_pos(axis));
  1260. soft_endstop_max[axis] = base_max_pos(axis); // + (cartes[axis] - base_home_pos(axis));
  1261. }
  1262. else
  1263. #endif
  1264. {
  1265. current_position[axis] = LOGICAL_POSITION(base_home_pos(axis), axis);
  1266. }
  1267. /**
  1268. * Z Probe Z Homing? Account for the probe's Z offset.
  1269. */
  1270. #if HAS_BED_PROBE && Z_HOME_DIR < 0
  1271. if (axis == Z_AXIS) {
  1272. #if HOMING_Z_WITH_PROBE
  1273. current_position[Z_AXIS] -= zprobe_zoffset;
  1274. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1275. if (DEBUGGING(LEVELING)) {
  1276. SERIAL_ECHOLNPGM("*** Z HOMED WITH PROBE (Z_MIN_PROBE_USES_Z_MIN_ENDSTOP_PIN) ***");
  1277. SERIAL_ECHOLNPAIR("> zprobe_zoffset = ", zprobe_zoffset);
  1278. }
  1279. #endif
  1280. #elif ENABLED(DEBUG_LEVELING_FEATURE)
  1281. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("*** Z HOMED TO ENDSTOP (Z_MIN_PROBE_ENDSTOP) ***");
  1282. #endif
  1283. }
  1284. #endif
  1285. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1286. if (DEBUGGING(LEVELING)) {
  1287. #if HAS_HOME_OFFSET
  1288. SERIAL_ECHOPAIR("> home_offset[", axis_codes[axis]);
  1289. SERIAL_ECHOLNPAIR("] = ", home_offset[axis]);
  1290. #endif
  1291. DEBUG_POS("", current_position);
  1292. SERIAL_ECHOPAIR("<<< set_axis_is_at_home(", axis_codes[axis]);
  1293. SERIAL_CHAR(')');
  1294. SERIAL_EOL;
  1295. }
  1296. #endif
  1297. }
  1298. /**
  1299. * Some planner shorthand inline functions
  1300. */
  1301. inline float get_homing_bump_feedrate(AxisEnum axis) {
  1302. int constexpr homing_bump_divisor[] = HOMING_BUMP_DIVISOR;
  1303. int hbd = homing_bump_divisor[axis];
  1304. if (hbd < 1) {
  1305. hbd = 10;
  1306. SERIAL_ECHO_START;
  1307. SERIAL_ECHOLNPGM("Warning: Homing Bump Divisor < 1");
  1308. }
  1309. return homing_feedrate_mm_s[axis] / hbd;
  1310. }
  1311. //
  1312. // line_to_current_position
  1313. // Move the planner to the current position from wherever it last moved
  1314. // (or from wherever it has been told it is located).
  1315. //
  1316. inline void line_to_current_position() {
  1317. planner.buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], feedrate_mm_s, active_extruder);
  1318. }
  1319. //
  1320. // line_to_destination
  1321. // Move the planner, not necessarily synced with current_position
  1322. //
  1323. inline void line_to_destination(float fr_mm_s) {
  1324. planner.buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], fr_mm_s, active_extruder);
  1325. }
  1326. inline void line_to_destination() { line_to_destination(feedrate_mm_s); }
  1327. inline void set_current_to_destination() { COPY(current_position, destination); }
  1328. inline void set_destination_to_current() { COPY(destination, current_position); }
  1329. #if IS_KINEMATIC
  1330. /**
  1331. * Calculate delta, start a line, and set current_position to destination
  1332. */
  1333. void prepare_uninterpolated_move_to_destination(const float fr_mm_s=0.0) {
  1334. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1335. if (DEBUGGING(LEVELING)) DEBUG_POS("prepare_uninterpolated_move_to_destination", destination);
  1336. #endif
  1337. if ( current_position[X_AXIS] == destination[X_AXIS]
  1338. && current_position[Y_AXIS] == destination[Y_AXIS]
  1339. && current_position[Z_AXIS] == destination[Z_AXIS]
  1340. && current_position[E_AXIS] == destination[E_AXIS]
  1341. ) return;
  1342. refresh_cmd_timeout();
  1343. planner.buffer_line_kinematic(destination, MMS_SCALED(fr_mm_s ? fr_mm_s : feedrate_mm_s), active_extruder);
  1344. set_current_to_destination();
  1345. }
  1346. #endif // IS_KINEMATIC
  1347. /**
  1348. * Plan a move to (X, Y, Z) and set the current_position
  1349. * The final current_position may not be the one that was requested
  1350. */
  1351. void do_blocking_move_to(const float &x, const float &y, const float &z, const float &fr_mm_s /*=0.0*/) {
  1352. const float old_feedrate_mm_s = feedrate_mm_s;
  1353. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1354. if (DEBUGGING(LEVELING)) print_xyz(PSTR(">>> do_blocking_move_to"), NULL, x, y, z);
  1355. #endif
  1356. #if ENABLED(DELTA)
  1357. if (!position_is_reachable_xy(x, y)) return;
  1358. feedrate_mm_s = fr_mm_s ? fr_mm_s : XY_PROBE_FEEDRATE_MM_S;
  1359. set_destination_to_current(); // sync destination at the start
  1360. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1361. if (DEBUGGING(LEVELING)) DEBUG_POS("set_destination_to_current", destination);
  1362. #endif
  1363. // when in the danger zone
  1364. if (current_position[Z_AXIS] > delta_clip_start_height) {
  1365. if (z > delta_clip_start_height) { // staying in the danger zone
  1366. destination[X_AXIS] = x; // move directly (uninterpolated)
  1367. destination[Y_AXIS] = y;
  1368. destination[Z_AXIS] = z;
  1369. prepare_uninterpolated_move_to_destination(); // set_current_to_destination
  1370. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1371. if (DEBUGGING(LEVELING)) DEBUG_POS("danger zone move", current_position);
  1372. #endif
  1373. return;
  1374. }
  1375. else {
  1376. destination[Z_AXIS] = delta_clip_start_height;
  1377. prepare_uninterpolated_move_to_destination(); // set_current_to_destination
  1378. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1379. if (DEBUGGING(LEVELING)) DEBUG_POS("zone border move", current_position);
  1380. #endif
  1381. }
  1382. }
  1383. if (z > current_position[Z_AXIS]) { // raising?
  1384. destination[Z_AXIS] = z;
  1385. prepare_uninterpolated_move_to_destination(); // set_current_to_destination
  1386. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1387. if (DEBUGGING(LEVELING)) DEBUG_POS("z raise move", current_position);
  1388. #endif
  1389. }
  1390. destination[X_AXIS] = x;
  1391. destination[Y_AXIS] = y;
  1392. prepare_move_to_destination(); // set_current_to_destination
  1393. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1394. if (DEBUGGING(LEVELING)) DEBUG_POS("xy move", current_position);
  1395. #endif
  1396. if (z < current_position[Z_AXIS]) { // lowering?
  1397. destination[Z_AXIS] = z;
  1398. prepare_uninterpolated_move_to_destination(); // set_current_to_destination
  1399. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1400. if (DEBUGGING(LEVELING)) DEBUG_POS("z lower move", current_position);
  1401. #endif
  1402. }
  1403. #elif IS_SCARA
  1404. if (!position_is_reachable_xy(x, y)) return;
  1405. set_destination_to_current();
  1406. // If Z needs to raise, do it before moving XY
  1407. if (destination[Z_AXIS] < z) {
  1408. destination[Z_AXIS] = z;
  1409. prepare_uninterpolated_move_to_destination(fr_mm_s ? fr_mm_s : homing_feedrate_mm_s[Z_AXIS]);
  1410. }
  1411. destination[X_AXIS] = x;
  1412. destination[Y_AXIS] = y;
  1413. prepare_uninterpolated_move_to_destination(fr_mm_s ? fr_mm_s : XY_PROBE_FEEDRATE_MM_S);
  1414. // If Z needs to lower, do it after moving XY
  1415. if (destination[Z_AXIS] > z) {
  1416. destination[Z_AXIS] = z;
  1417. prepare_uninterpolated_move_to_destination(fr_mm_s ? fr_mm_s : homing_feedrate_mm_s[Z_AXIS]);
  1418. }
  1419. #else
  1420. // If Z needs to raise, do it before moving XY
  1421. if (current_position[Z_AXIS] < z) {
  1422. feedrate_mm_s = fr_mm_s ? fr_mm_s : homing_feedrate_mm_s[Z_AXIS];
  1423. current_position[Z_AXIS] = z;
  1424. line_to_current_position();
  1425. }
  1426. feedrate_mm_s = fr_mm_s ? fr_mm_s : XY_PROBE_FEEDRATE_MM_S;
  1427. current_position[X_AXIS] = x;
  1428. current_position[Y_AXIS] = y;
  1429. line_to_current_position();
  1430. // If Z needs to lower, do it after moving XY
  1431. if (current_position[Z_AXIS] > z) {
  1432. feedrate_mm_s = fr_mm_s ? fr_mm_s : homing_feedrate_mm_s[Z_AXIS];
  1433. current_position[Z_AXIS] = z;
  1434. line_to_current_position();
  1435. }
  1436. #endif
  1437. stepper.synchronize();
  1438. feedrate_mm_s = old_feedrate_mm_s;
  1439. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1440. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< do_blocking_move_to");
  1441. #endif
  1442. }
  1443. void do_blocking_move_to_x(const float &x, const float &fr_mm_s/*=0.0*/) {
  1444. do_blocking_move_to(x, current_position[Y_AXIS], current_position[Z_AXIS], fr_mm_s);
  1445. }
  1446. void do_blocking_move_to_z(const float &z, const float &fr_mm_s/*=0.0*/) {
  1447. do_blocking_move_to(current_position[X_AXIS], current_position[Y_AXIS], z, fr_mm_s);
  1448. }
  1449. void do_blocking_move_to_xy(const float &x, const float &y, const float &fr_mm_s/*=0.0*/) {
  1450. do_blocking_move_to(x, y, current_position[Z_AXIS], fr_mm_s);
  1451. }
  1452. //
  1453. // Prepare to do endstop or probe moves
  1454. // with custom feedrates.
  1455. //
  1456. // - Save current feedrates
  1457. // - Reset the rate multiplier
  1458. // - Reset the command timeout
  1459. // - Enable the endstops (for endstop moves)
  1460. //
  1461. static void setup_for_endstop_or_probe_move() {
  1462. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1463. if (DEBUGGING(LEVELING)) DEBUG_POS("setup_for_endstop_or_probe_move", current_position);
  1464. #endif
  1465. saved_feedrate_mm_s = feedrate_mm_s;
  1466. saved_feedrate_percentage = feedrate_percentage;
  1467. feedrate_percentage = 100;
  1468. refresh_cmd_timeout();
  1469. }
  1470. static void clean_up_after_endstop_or_probe_move() {
  1471. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1472. if (DEBUGGING(LEVELING)) DEBUG_POS("clean_up_after_endstop_or_probe_move", current_position);
  1473. #endif
  1474. feedrate_mm_s = saved_feedrate_mm_s;
  1475. feedrate_percentage = saved_feedrate_percentage;
  1476. refresh_cmd_timeout();
  1477. }
  1478. #if HAS_BED_PROBE
  1479. /**
  1480. * Raise Z to a minimum height to make room for a probe to move
  1481. */
  1482. inline void do_probe_raise(float z_raise) {
  1483. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1484. if (DEBUGGING(LEVELING)) {
  1485. SERIAL_ECHOPAIR("do_probe_raise(", z_raise);
  1486. SERIAL_CHAR(')');
  1487. SERIAL_EOL;
  1488. }
  1489. #endif
  1490. float z_dest = LOGICAL_Z_POSITION(z_raise);
  1491. if (zprobe_zoffset < 0) z_dest -= zprobe_zoffset;
  1492. #if ENABLED(DELTA)
  1493. z_dest -= home_offset[Z_AXIS];
  1494. #endif
  1495. if (z_dest > current_position[Z_AXIS])
  1496. do_blocking_move_to_z(z_dest);
  1497. }
  1498. #endif // HAS_BED_PROBE
  1499. #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)
  1500. bool axis_unhomed_error(const bool x/*=true*/, const bool y/*=true*/, const bool z/*=true*/) {
  1501. #if ENABLED(HOME_AFTER_DEACTIVATE)
  1502. const bool xx = x && !axis_known_position[X_AXIS],
  1503. yy = y && !axis_known_position[Y_AXIS],
  1504. zz = z && !axis_known_position[Z_AXIS];
  1505. #else
  1506. const bool xx = x && !axis_homed[X_AXIS],
  1507. yy = y && !axis_homed[Y_AXIS],
  1508. zz = z && !axis_homed[Z_AXIS];
  1509. #endif
  1510. if (xx || yy || zz) {
  1511. SERIAL_ECHO_START;
  1512. SERIAL_ECHOPGM(MSG_HOME " ");
  1513. if (xx) SERIAL_ECHOPGM(MSG_X);
  1514. if (yy) SERIAL_ECHOPGM(MSG_Y);
  1515. if (zz) SERIAL_ECHOPGM(MSG_Z);
  1516. SERIAL_ECHOLNPGM(" " MSG_FIRST);
  1517. #if ENABLED(ULTRA_LCD)
  1518. lcd_status_printf_P(0, PSTR(MSG_HOME " %s%s%s " MSG_FIRST), xx ? MSG_X : "", yy ? MSG_Y : "", zz ? MSG_Z : "");
  1519. #endif
  1520. return true;
  1521. }
  1522. return false;
  1523. }
  1524. #endif
  1525. #if ENABLED(Z_PROBE_SLED)
  1526. #ifndef SLED_DOCKING_OFFSET
  1527. #define SLED_DOCKING_OFFSET 0
  1528. #endif
  1529. /**
  1530. * Method to dock/undock a sled designed by Charles Bell.
  1531. *
  1532. * stow[in] If false, move to MAX_X and engage the solenoid
  1533. * If true, move to MAX_X and release the solenoid
  1534. */
  1535. static void dock_sled(bool stow) {
  1536. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1537. if (DEBUGGING(LEVELING)) {
  1538. SERIAL_ECHOPAIR("dock_sled(", stow);
  1539. SERIAL_CHAR(')');
  1540. SERIAL_EOL;
  1541. }
  1542. #endif
  1543. // Dock sled a bit closer to ensure proper capturing
  1544. do_blocking_move_to_x(X_MAX_POS + SLED_DOCKING_OFFSET - ((stow) ? 1 : 0));
  1545. #if HAS_SOLENOID_1 && DISABLED(EXT_SOLENOID)
  1546. WRITE(SOL1_PIN, !stow); // switch solenoid
  1547. #endif
  1548. }
  1549. #elif ENABLED(Z_PROBE_ALLEN_KEY)
  1550. void run_deploy_moves_script() {
  1551. #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)
  1552. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_X
  1553. #define Z_PROBE_ALLEN_KEY_DEPLOY_1_X current_position[X_AXIS]
  1554. #endif
  1555. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_Y
  1556. #define Z_PROBE_ALLEN_KEY_DEPLOY_1_Y current_position[Y_AXIS]
  1557. #endif
  1558. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_Z
  1559. #define Z_PROBE_ALLEN_KEY_DEPLOY_1_Z current_position[Z_AXIS]
  1560. #endif
  1561. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_FEEDRATE
  1562. #define Z_PROBE_ALLEN_KEY_DEPLOY_1_FEEDRATE 0.0
  1563. #endif
  1564. do_blocking_move_to(Z_PROBE_ALLEN_KEY_DEPLOY_1_X, Z_PROBE_ALLEN_KEY_DEPLOY_1_Y, Z_PROBE_ALLEN_KEY_DEPLOY_1_Z, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_1_FEEDRATE));
  1565. #endif
  1566. #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)
  1567. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_X
  1568. #define Z_PROBE_ALLEN_KEY_DEPLOY_2_X current_position[X_AXIS]
  1569. #endif
  1570. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_Y
  1571. #define Z_PROBE_ALLEN_KEY_DEPLOY_2_Y current_position[Y_AXIS]
  1572. #endif
  1573. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_Z
  1574. #define Z_PROBE_ALLEN_KEY_DEPLOY_2_Z current_position[Z_AXIS]
  1575. #endif
  1576. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE
  1577. #define Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE 0.0
  1578. #endif
  1579. do_blocking_move_to(Z_PROBE_ALLEN_KEY_DEPLOY_2_X, Z_PROBE_ALLEN_KEY_DEPLOY_2_Y, Z_PROBE_ALLEN_KEY_DEPLOY_2_Z, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE));
  1580. #endif
  1581. #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)
  1582. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_X
  1583. #define Z_PROBE_ALLEN_KEY_DEPLOY_3_X current_position[X_AXIS]
  1584. #endif
  1585. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_Y
  1586. #define Z_PROBE_ALLEN_KEY_DEPLOY_3_Y current_position[Y_AXIS]
  1587. #endif
  1588. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_Z
  1589. #define Z_PROBE_ALLEN_KEY_DEPLOY_3_Z current_position[Z_AXIS]
  1590. #endif
  1591. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE
  1592. #define Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE 0.0
  1593. #endif
  1594. do_blocking_move_to(Z_PROBE_ALLEN_KEY_DEPLOY_3_X, Z_PROBE_ALLEN_KEY_DEPLOY_3_Y, Z_PROBE_ALLEN_KEY_DEPLOY_3_Z, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE));
  1595. #endif
  1596. #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)
  1597. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_X
  1598. #define Z_PROBE_ALLEN_KEY_DEPLOY_4_X current_position[X_AXIS]
  1599. #endif
  1600. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_Y
  1601. #define Z_PROBE_ALLEN_KEY_DEPLOY_4_Y current_position[Y_AXIS]
  1602. #endif
  1603. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_Z
  1604. #define Z_PROBE_ALLEN_KEY_DEPLOY_4_Z current_position[Z_AXIS]
  1605. #endif
  1606. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_FEEDRATE
  1607. #define Z_PROBE_ALLEN_KEY_DEPLOY_4_FEEDRATE 0.0
  1608. #endif
  1609. do_blocking_move_to(Z_PROBE_ALLEN_KEY_DEPLOY_4_X, Z_PROBE_ALLEN_KEY_DEPLOY_4_Y, Z_PROBE_ALLEN_KEY_DEPLOY_4_Z, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_4_FEEDRATE));
  1610. #endif
  1611. #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)
  1612. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_X
  1613. #define Z_PROBE_ALLEN_KEY_DEPLOY_5_X current_position[X_AXIS]
  1614. #endif
  1615. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_Y
  1616. #define Z_PROBE_ALLEN_KEY_DEPLOY_5_Y current_position[Y_AXIS]
  1617. #endif
  1618. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_Z
  1619. #define Z_PROBE_ALLEN_KEY_DEPLOY_5_Z current_position[Z_AXIS]
  1620. #endif
  1621. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_FEEDRATE
  1622. #define Z_PROBE_ALLEN_KEY_DEPLOY_5_FEEDRATE 0.0
  1623. #endif
  1624. do_blocking_move_to(Z_PROBE_ALLEN_KEY_DEPLOY_5_X, Z_PROBE_ALLEN_KEY_DEPLOY_5_Y, Z_PROBE_ALLEN_KEY_DEPLOY_5_Z, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_5_FEEDRATE));
  1625. #endif
  1626. }
  1627. void run_stow_moves_script() {
  1628. #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)
  1629. #ifndef Z_PROBE_ALLEN_KEY_STOW_1_X
  1630. #define Z_PROBE_ALLEN_KEY_STOW_1_X current_position[X_AXIS]
  1631. #endif
  1632. #ifndef Z_PROBE_ALLEN_KEY_STOW_1_Y
  1633. #define Z_PROBE_ALLEN_KEY_STOW_1_Y current_position[Y_AXIS]
  1634. #endif
  1635. #ifndef Z_PROBE_ALLEN_KEY_STOW_1_Z
  1636. #define Z_PROBE_ALLEN_KEY_STOW_1_Z current_position[Z_AXIS]
  1637. #endif
  1638. #ifndef Z_PROBE_ALLEN_KEY_STOW_1_FEEDRATE
  1639. #define Z_PROBE_ALLEN_KEY_STOW_1_FEEDRATE 0.0
  1640. #endif
  1641. do_blocking_move_to(Z_PROBE_ALLEN_KEY_STOW_1_X, Z_PROBE_ALLEN_KEY_STOW_1_Y, Z_PROBE_ALLEN_KEY_STOW_1_Z, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_1_FEEDRATE));
  1642. #endif
  1643. #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)
  1644. #ifndef Z_PROBE_ALLEN_KEY_STOW_2_X
  1645. #define Z_PROBE_ALLEN_KEY_STOW_2_X current_position[X_AXIS]
  1646. #endif
  1647. #ifndef Z_PROBE_ALLEN_KEY_STOW_2_Y
  1648. #define Z_PROBE_ALLEN_KEY_STOW_2_Y current_position[Y_AXIS]
  1649. #endif
  1650. #ifndef Z_PROBE_ALLEN_KEY_STOW_2_Z
  1651. #define Z_PROBE_ALLEN_KEY_STOW_2_Z current_position[Z_AXIS]
  1652. #endif
  1653. #ifndef Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE
  1654. #define Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE 0.0
  1655. #endif
  1656. do_blocking_move_to(Z_PROBE_ALLEN_KEY_STOW_2_X, Z_PROBE_ALLEN_KEY_STOW_2_Y, Z_PROBE_ALLEN_KEY_STOW_2_Z, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE));
  1657. #endif
  1658. #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)
  1659. #ifndef Z_PROBE_ALLEN_KEY_STOW_3_X
  1660. #define Z_PROBE_ALLEN_KEY_STOW_3_X current_position[X_AXIS]
  1661. #endif
  1662. #ifndef Z_PROBE_ALLEN_KEY_STOW_3_Y
  1663. #define Z_PROBE_ALLEN_KEY_STOW_3_Y current_position[Y_AXIS]
  1664. #endif
  1665. #ifndef Z_PROBE_ALLEN_KEY_STOW_3_Z
  1666. #define Z_PROBE_ALLEN_KEY_STOW_3_Z current_position[Z_AXIS]
  1667. #endif
  1668. #ifndef Z_PROBE_ALLEN_KEY_STOW_3_FEEDRATE
  1669. #define Z_PROBE_ALLEN_KEY_STOW_3_FEEDRATE 0.0
  1670. #endif
  1671. do_blocking_move_to(Z_PROBE_ALLEN_KEY_STOW_3_X, Z_PROBE_ALLEN_KEY_STOW_3_Y, Z_PROBE_ALLEN_KEY_STOW_3_Z, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_3_FEEDRATE));
  1672. #endif
  1673. #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)
  1674. #ifndef Z_PROBE_ALLEN_KEY_STOW_4_X
  1675. #define Z_PROBE_ALLEN_KEY_STOW_4_X current_position[X_AXIS]
  1676. #endif
  1677. #ifndef Z_PROBE_ALLEN_KEY_STOW_4_Y
  1678. #define Z_PROBE_ALLEN_KEY_STOW_4_Y current_position[Y_AXIS]
  1679. #endif
  1680. #ifndef Z_PROBE_ALLEN_KEY_STOW_4_Z
  1681. #define Z_PROBE_ALLEN_KEY_STOW_4_Z current_position[Z_AXIS]
  1682. #endif
  1683. #ifndef Z_PROBE_ALLEN_KEY_STOW_4_FEEDRATE
  1684. #define Z_PROBE_ALLEN_KEY_STOW_4_FEEDRATE 0.0
  1685. #endif
  1686. do_blocking_move_to(Z_PROBE_ALLEN_KEY_STOW_4_X, Z_PROBE_ALLEN_KEY_STOW_4_Y, Z_PROBE_ALLEN_KEY_STOW_4_Z, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_4_FEEDRATE));
  1687. #endif
  1688. #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)
  1689. #ifndef Z_PROBE_ALLEN_KEY_STOW_5_X
  1690. #define Z_PROBE_ALLEN_KEY_STOW_5_X current_position[X_AXIS]
  1691. #endif
  1692. #ifndef Z_PROBE_ALLEN_KEY_STOW_5_Y
  1693. #define Z_PROBE_ALLEN_KEY_STOW_5_Y current_position[Y_AXIS]
  1694. #endif
  1695. #ifndef Z_PROBE_ALLEN_KEY_STOW_5_Z
  1696. #define Z_PROBE_ALLEN_KEY_STOW_5_Z current_position[Z_AXIS]
  1697. #endif
  1698. #ifndef Z_PROBE_ALLEN_KEY_STOW_5_FEEDRATE
  1699. #define Z_PROBE_ALLEN_KEY_STOW_5_FEEDRATE 0.0
  1700. #endif
  1701. do_blocking_move_to(Z_PROBE_ALLEN_KEY_STOW_5_X, Z_PROBE_ALLEN_KEY_STOW_5_Y, Z_PROBE_ALLEN_KEY_STOW_5_Z, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_5_FEEDRATE));
  1702. #endif
  1703. }
  1704. #endif
  1705. #if ENABLED(PROBING_FANS_OFF)
  1706. void fans_pause(const bool p) {
  1707. if (p != fans_paused) {
  1708. fans_paused = p;
  1709. if (p)
  1710. for (uint8_t x = 0; x < FAN_COUNT; x++) {
  1711. paused_fanSpeeds[x] = fanSpeeds[x];
  1712. fanSpeeds[x] = 0;
  1713. }
  1714. else
  1715. for (uint8_t x = 0; x < FAN_COUNT; x++)
  1716. fanSpeeds[x] = paused_fanSpeeds[x];
  1717. }
  1718. }
  1719. #endif // PROBING_FANS_OFF
  1720. #if HAS_BED_PROBE
  1721. // TRIGGERED_WHEN_STOWED_TEST can easily be extended to servo probes, ... if needed.
  1722. #if ENABLED(PROBE_IS_TRIGGERED_WHEN_STOWED_TEST)
  1723. #if ENABLED(Z_MIN_PROBE_ENDSTOP)
  1724. #define _TRIGGERED_WHEN_STOWED_TEST (READ(Z_MIN_PROBE_PIN) != Z_MIN_PROBE_ENDSTOP_INVERTING)
  1725. #else
  1726. #define _TRIGGERED_WHEN_STOWED_TEST (READ(Z_MIN_PIN) != Z_MIN_ENDSTOP_INVERTING)
  1727. #endif
  1728. #endif
  1729. #if QUIET_PROBING
  1730. void probing_pause(const bool p) {
  1731. #if ENABLED(PROBING_HEATERS_OFF)
  1732. thermalManager.pause(p);
  1733. #endif
  1734. #if ENABLED(PROBING_FANS_OFF)
  1735. fans_pause(p);
  1736. #endif
  1737. if (p) safe_delay(25);
  1738. }
  1739. #endif // QUIET_PROBING
  1740. #if ENABLED(BLTOUCH)
  1741. void bltouch_command(int angle) {
  1742. servo[Z_ENDSTOP_SERVO_NR].move(angle); // Give the BL-Touch the command and wait
  1743. safe_delay(BLTOUCH_DELAY);
  1744. }
  1745. void set_bltouch_deployed(const bool deploy) {
  1746. if (deploy && TEST_BLTOUCH()) { // If BL-Touch says it's triggered
  1747. bltouch_command(BLTOUCH_RESET); // try to reset it.
  1748. bltouch_command(BLTOUCH_DEPLOY); // Also needs to deploy and stow to
  1749. bltouch_command(BLTOUCH_STOW); // clear the triggered condition.
  1750. safe_delay(1500); // Wait for internal self-test to complete.
  1751. // (Measured completion time was 0.65 seconds
  1752. // after reset, deploy, and stow sequence)
  1753. if (TEST_BLTOUCH()) { // If it still claims to be triggered...
  1754. SERIAL_ERROR_START;
  1755. SERIAL_ERRORLNPGM(MSG_STOP_BLTOUCH);
  1756. stop(); // punt!
  1757. }
  1758. }
  1759. bltouch_command(deploy ? BLTOUCH_DEPLOY : BLTOUCH_STOW);
  1760. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1761. if (DEBUGGING(LEVELING)) {
  1762. SERIAL_ECHOPAIR("set_bltouch_deployed(", deploy);
  1763. SERIAL_CHAR(')');
  1764. SERIAL_EOL;
  1765. }
  1766. #endif
  1767. }
  1768. #endif // BLTOUCH
  1769. // returns false for ok and true for failure
  1770. bool set_probe_deployed(bool deploy) {
  1771. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1772. if (DEBUGGING(LEVELING)) {
  1773. DEBUG_POS("set_probe_deployed", current_position);
  1774. SERIAL_ECHOLNPAIR("deploy: ", deploy);
  1775. }
  1776. #endif
  1777. if (endstops.z_probe_enabled == deploy) return false;
  1778. // Make room for probe
  1779. do_probe_raise(_Z_CLEARANCE_DEPLOY_PROBE);
  1780. // When deploying make sure BLTOUCH is not already triggered
  1781. #if ENABLED(BLTOUCH)
  1782. if (deploy && TEST_BLTOUCH()) { // If BL-Touch says it's triggered
  1783. bltouch_command(BLTOUCH_RESET); // try to reset it.
  1784. bltouch_command(BLTOUCH_DEPLOY); // Also needs to deploy and stow to
  1785. bltouch_command(BLTOUCH_STOW); // clear the triggered condition.
  1786. safe_delay(1500); // wait for internal self test to complete
  1787. // measured completion time was 0.65 seconds
  1788. // after reset, deploy & stow sequence
  1789. if (TEST_BLTOUCH()) { // If it still claims to be triggered...
  1790. SERIAL_ERROR_START;
  1791. SERIAL_ERRORLNPGM(MSG_STOP_BLTOUCH);
  1792. stop(); // punt!
  1793. return true;
  1794. }
  1795. }
  1796. #elif ENABLED(Z_PROBE_SLED) || ENABLED(Z_PROBE_ALLEN_KEY)
  1797. #if ENABLED(Z_PROBE_SLED)
  1798. #define _AUE_ARGS true, false, false
  1799. #else
  1800. #define _AUE_ARGS
  1801. #endif
  1802. if (axis_unhomed_error(_AUE_ARGS)) {
  1803. SERIAL_ERROR_START;
  1804. SERIAL_ERRORLNPGM(MSG_STOP_UNHOMED);
  1805. stop();
  1806. return true;
  1807. }
  1808. #endif
  1809. const float oldXpos = current_position[X_AXIS],
  1810. oldYpos = current_position[Y_AXIS];
  1811. #ifdef _TRIGGERED_WHEN_STOWED_TEST
  1812. // If endstop is already false, the Z probe is deployed
  1813. if (_TRIGGERED_WHEN_STOWED_TEST == deploy) { // closed after the probe specific actions.
  1814. // Would a goto be less ugly?
  1815. //while (!_TRIGGERED_WHEN_STOWED_TEST) idle(); // would offer the opportunity
  1816. // for a triggered when stowed manual probe.
  1817. if (!deploy) endstops.enable_z_probe(false); // Switch off triggered when stowed probes early
  1818. // otherwise an Allen-Key probe can't be stowed.
  1819. #endif
  1820. #if ENABLED(SOLENOID_PROBE)
  1821. #if HAS_SOLENOID_1
  1822. WRITE(SOL1_PIN, deploy);
  1823. #endif
  1824. #elif ENABLED(Z_PROBE_SLED)
  1825. dock_sled(!deploy);
  1826. #elif HAS_Z_SERVO_ENDSTOP && DISABLED(BLTOUCH)
  1827. servo[Z_ENDSTOP_SERVO_NR].move(z_servo_angle[deploy ? 0 : 1]);
  1828. #elif ENABLED(Z_PROBE_ALLEN_KEY)
  1829. deploy ? run_deploy_moves_script() : run_stow_moves_script();
  1830. #endif
  1831. #ifdef _TRIGGERED_WHEN_STOWED_TEST
  1832. } // _TRIGGERED_WHEN_STOWED_TEST == deploy
  1833. if (_TRIGGERED_WHEN_STOWED_TEST == deploy) { // State hasn't changed?
  1834. if (IsRunning()) {
  1835. SERIAL_ERROR_START;
  1836. SERIAL_ERRORLNPGM("Z-Probe failed");
  1837. LCD_ALERTMESSAGEPGM("Err: ZPROBE");
  1838. }
  1839. stop();
  1840. return true;
  1841. } // _TRIGGERED_WHEN_STOWED_TEST == deploy
  1842. #endif
  1843. do_blocking_move_to(oldXpos, oldYpos, current_position[Z_AXIS]); // return to position before deploy
  1844. endstops.enable_z_probe(deploy);
  1845. return false;
  1846. }
  1847. static void do_probe_move(float z, float fr_mm_m) {
  1848. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1849. if (DEBUGGING(LEVELING)) DEBUG_POS(">>> do_probe_move", current_position);
  1850. #endif
  1851. // Deploy BLTouch at the start of any probe
  1852. #if ENABLED(BLTOUCH)
  1853. set_bltouch_deployed(true);
  1854. #endif
  1855. #if QUIET_PROBING
  1856. probing_pause(true);
  1857. #endif
  1858. // Move down until probe triggered
  1859. do_blocking_move_to_z(LOGICAL_Z_POSITION(z), MMM_TO_MMS(fr_mm_m));
  1860. #if QUIET_PROBING
  1861. probing_pause(false);
  1862. #endif
  1863. // Retract BLTouch immediately after a probe
  1864. #if ENABLED(BLTOUCH)
  1865. set_bltouch_deployed(false);
  1866. #endif
  1867. // Clear endstop flags
  1868. endstops.hit_on_purpose();
  1869. // Get Z where the steppers were interrupted
  1870. set_current_from_steppers_for_axis(Z_AXIS);
  1871. // Tell the planner where we actually are
  1872. SYNC_PLAN_POSITION_KINEMATIC();
  1873. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1874. if (DEBUGGING(LEVELING)) DEBUG_POS("<<< do_probe_move", current_position);
  1875. #endif
  1876. }
  1877. // Do a single Z probe and return with current_position[Z_AXIS]
  1878. // at the height where the probe triggered.
  1879. static float run_z_probe() {
  1880. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1881. if (DEBUGGING(LEVELING)) DEBUG_POS(">>> run_z_probe", current_position);
  1882. #endif
  1883. // Prevent stepper_inactive_time from running out and EXTRUDER_RUNOUT_PREVENT from extruding
  1884. refresh_cmd_timeout();
  1885. #if ENABLED(PROBE_DOUBLE_TOUCH)
  1886. // Do a first probe at the fast speed
  1887. do_probe_move(-(Z_MAX_LENGTH) - 10, Z_PROBE_SPEED_FAST);
  1888. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1889. float first_probe_z = current_position[Z_AXIS];
  1890. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR("1st Probe Z:", first_probe_z);
  1891. #endif
  1892. // move up by the bump distance
  1893. do_blocking_move_to_z(current_position[Z_AXIS] + home_bump_mm(Z_AXIS), MMM_TO_MMS(Z_PROBE_SPEED_FAST));
  1894. #else
  1895. // If the nozzle is above the travel height then
  1896. // move down quickly before doing the slow probe
  1897. float z = LOGICAL_Z_POSITION(Z_CLEARANCE_BETWEEN_PROBES);
  1898. if (zprobe_zoffset < 0) z -= zprobe_zoffset;
  1899. #if ENABLED(DELTA)
  1900. z -= home_offset[Z_AXIS];
  1901. #endif
  1902. if (z < current_position[Z_AXIS])
  1903. do_blocking_move_to_z(z, MMM_TO_MMS(Z_PROBE_SPEED_FAST));
  1904. #endif
  1905. // move down slowly to find bed
  1906. do_probe_move(-(Z_MAX_LENGTH) - 10, Z_PROBE_SPEED_SLOW);
  1907. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1908. if (DEBUGGING(LEVELING)) DEBUG_POS("<<< run_z_probe", current_position);
  1909. #endif
  1910. // Debug: compare probe heights
  1911. #if ENABLED(PROBE_DOUBLE_TOUCH) && ENABLED(DEBUG_LEVELING_FEATURE)
  1912. if (DEBUGGING(LEVELING)) {
  1913. SERIAL_ECHOPAIR("2nd Probe Z:", current_position[Z_AXIS]);
  1914. SERIAL_ECHOLNPAIR(" Discrepancy:", first_probe_z - current_position[Z_AXIS]);
  1915. }
  1916. #endif
  1917. return current_position[Z_AXIS] + zprobe_zoffset;
  1918. }
  1919. /**
  1920. * - Move to the given XY
  1921. * - Deploy the probe, if not already deployed
  1922. * - Probe the bed, get the Z position
  1923. * - Depending on the 'stow' flag
  1924. * - Stow the probe, or
  1925. * - Raise to the BETWEEN height
  1926. * - Return the probed Z position
  1927. */
  1928. float probe_pt(const float &x, const float &y, const bool stow/*=true*/, const int verbose_level/*=1*/) {
  1929. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1930. if (DEBUGGING(LEVELING)) {
  1931. SERIAL_ECHOPAIR(">>> probe_pt(", x);
  1932. SERIAL_ECHOPAIR(", ", y);
  1933. SERIAL_ECHOPAIR(", ", stow ? "" : "no ");
  1934. SERIAL_ECHOLNPGM("stow)");
  1935. DEBUG_POS("", current_position);
  1936. }
  1937. #endif
  1938. if (!position_is_reachable_by_probe_xy(x, y)) return NAN;
  1939. const float old_feedrate_mm_s = feedrate_mm_s;
  1940. #if ENABLED(DELTA)
  1941. if (current_position[Z_AXIS] > delta_clip_start_height)
  1942. do_blocking_move_to_z(delta_clip_start_height);
  1943. #endif
  1944. // Ensure a minimum height before moving the probe
  1945. do_probe_raise(Z_CLEARANCE_BETWEEN_PROBES);
  1946. feedrate_mm_s = XY_PROBE_FEEDRATE_MM_S;
  1947. // Move the probe to the given XY
  1948. do_blocking_move_to_xy(x - (X_PROBE_OFFSET_FROM_EXTRUDER), y - (Y_PROBE_OFFSET_FROM_EXTRUDER));
  1949. if (DEPLOY_PROBE()) return NAN;
  1950. const float measured_z = run_z_probe();
  1951. if (!stow)
  1952. do_probe_raise(Z_CLEARANCE_BETWEEN_PROBES);
  1953. else
  1954. if (STOW_PROBE()) return NAN;
  1955. if (verbose_level > 2) {
  1956. SERIAL_PROTOCOLPGM("Bed X: ");
  1957. SERIAL_PROTOCOL_F(x, 3);
  1958. SERIAL_PROTOCOLPGM(" Y: ");
  1959. SERIAL_PROTOCOL_F(y, 3);
  1960. SERIAL_PROTOCOLPGM(" Z: ");
  1961. SERIAL_PROTOCOL_F(measured_z, 3);
  1962. SERIAL_EOL;
  1963. }
  1964. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1965. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< probe_pt");
  1966. #endif
  1967. feedrate_mm_s = old_feedrate_mm_s;
  1968. return measured_z;
  1969. }
  1970. #endif // HAS_BED_PROBE
  1971. #if HAS_LEVELING
  1972. bool leveling_is_valid() {
  1973. return
  1974. #if ENABLED(MESH_BED_LEVELING)
  1975. mbl.has_mesh()
  1976. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  1977. !!bilinear_grid_spacing[X_AXIS]
  1978. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  1979. true
  1980. #else // 3POINT, LINEAR
  1981. true
  1982. #endif
  1983. ;
  1984. }
  1985. bool leveling_is_active() {
  1986. return
  1987. #if ENABLED(MESH_BED_LEVELING)
  1988. mbl.active()
  1989. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  1990. ubl.state.active
  1991. #else
  1992. planner.abl_enabled
  1993. #endif
  1994. ;
  1995. }
  1996. /**
  1997. * Turn bed leveling on or off, fixing the current
  1998. * position as-needed.
  1999. *
  2000. * Disable: Current position = physical position
  2001. * Enable: Current position = "unleveled" physical position
  2002. */
  2003. void set_bed_leveling_enabled(const bool enable/*=true*/) {
  2004. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  2005. const bool can_change = (!enable || leveling_is_valid());
  2006. #else
  2007. constexpr bool can_change = true;
  2008. #endif
  2009. if (can_change && enable != leveling_is_active()) {
  2010. #if ENABLED(MESH_BED_LEVELING)
  2011. if (!enable)
  2012. planner.apply_leveling(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS]);
  2013. const bool enabling = enable && leveling_is_valid();
  2014. mbl.set_active(enabling);
  2015. if (enabling) planner.unapply_leveling(current_position);
  2016. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  2017. #if PLANNER_LEVELING
  2018. if (!enable) // leveling from on to off
  2019. planner.apply_leveling(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS]);
  2020. else
  2021. planner.unapply_leveling(current_position);
  2022. #endif
  2023. ubl.state.active = enable;
  2024. #else // ABL
  2025. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  2026. // Force bilinear_z_offset to re-calculate next time
  2027. const float reset[XYZ] = { -9999.999, -9999.999, 0 };
  2028. (void)bilinear_z_offset(reset);
  2029. #endif
  2030. planner.abl_enabled = enable;
  2031. if (!enable)
  2032. set_current_from_steppers_for_axis(
  2033. #if ABL_PLANAR
  2034. ALL_AXES
  2035. #else
  2036. Z_AXIS
  2037. #endif
  2038. );
  2039. else
  2040. planner.unapply_leveling(current_position);
  2041. #endif
  2042. }
  2043. }
  2044. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  2045. void set_z_fade_height(const float zfh) {
  2046. planner.z_fade_height = zfh;
  2047. planner.inverse_z_fade_height = RECIPROCAL(zfh);
  2048. if (leveling_is_active())
  2049. set_current_from_steppers_for_axis(
  2050. #if ABL_PLANAR
  2051. ALL_AXES
  2052. #else
  2053. Z_AXIS
  2054. #endif
  2055. );
  2056. }
  2057. #endif // LEVELING_FADE_HEIGHT
  2058. /**
  2059. * Reset calibration results to zero.
  2060. */
  2061. void reset_bed_level() {
  2062. set_bed_leveling_enabled(false);
  2063. #if ENABLED(MESH_BED_LEVELING)
  2064. if (leveling_is_valid()) {
  2065. mbl.reset();
  2066. mbl.set_has_mesh(false);
  2067. }
  2068. #else
  2069. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2070. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("reset_bed_level");
  2071. #endif
  2072. #if ABL_PLANAR
  2073. planner.bed_level_matrix.set_to_identity();
  2074. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  2075. bilinear_start[X_AXIS] = bilinear_start[Y_AXIS] =
  2076. bilinear_grid_spacing[X_AXIS] = bilinear_grid_spacing[Y_AXIS] = 0;
  2077. for (uint8_t x = 0; x < GRID_MAX_POINTS_X; x++)
  2078. for (uint8_t y = 0; y < GRID_MAX_POINTS_Y; y++)
  2079. z_values[x][y] = NAN;
  2080. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  2081. ubl.reset();
  2082. #endif
  2083. #endif
  2084. }
  2085. #endif // HAS_LEVELING
  2086. #if ENABLED(AUTO_BED_LEVELING_BILINEAR) || ENABLED(MESH_BED_LEVELING)
  2087. /**
  2088. * Enable to produce output in JSON format suitable
  2089. * for SCAD or JavaScript mesh visualizers.
  2090. *
  2091. * Visualize meshes in OpenSCAD using the included script.
  2092. *
  2093. * buildroot/shared/scripts/MarlinMesh.scad
  2094. */
  2095. //#define SCAD_MESH_OUTPUT
  2096. /**
  2097. * Print calibration results for plotting or manual frame adjustment.
  2098. */
  2099. 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)) {
  2100. #ifndef SCAD_MESH_OUTPUT
  2101. for (uint8_t x = 0; x < sx; x++) {
  2102. for (uint8_t i = 0; i < precision + 2 + (x < 10 ? 1 : 0); i++)
  2103. SERIAL_PROTOCOLCHAR(' ');
  2104. SERIAL_PROTOCOL((int)x);
  2105. }
  2106. SERIAL_EOL;
  2107. #endif
  2108. #ifdef SCAD_MESH_OUTPUT
  2109. SERIAL_PROTOCOLLNPGM("measured_z = ["); // open 2D array
  2110. #endif
  2111. for (uint8_t y = 0; y < sy; y++) {
  2112. #ifdef SCAD_MESH_OUTPUT
  2113. SERIAL_PROTOCOLPGM(" ["); // open sub-array
  2114. #else
  2115. if (y < 10) SERIAL_PROTOCOLCHAR(' ');
  2116. SERIAL_PROTOCOL((int)y);
  2117. #endif
  2118. for (uint8_t x = 0; x < sx; x++) {
  2119. SERIAL_PROTOCOLCHAR(' ');
  2120. const float offset = fn(x, y);
  2121. if (!isnan(offset)) {
  2122. if (offset >= 0) SERIAL_PROTOCOLCHAR('+');
  2123. SERIAL_PROTOCOL_F(offset, precision);
  2124. }
  2125. else {
  2126. #ifdef SCAD_MESH_OUTPUT
  2127. for (uint8_t i = 3; i < precision + 3; i++)
  2128. SERIAL_PROTOCOLCHAR(' ');
  2129. SERIAL_PROTOCOLPGM("NAN");
  2130. #else
  2131. for (uint8_t i = 0; i < precision + 3; i++)
  2132. SERIAL_PROTOCOLCHAR(i ? '=' : ' ');
  2133. #endif
  2134. }
  2135. #ifdef SCAD_MESH_OUTPUT
  2136. if (x < sx - 1) SERIAL_PROTOCOLCHAR(',');
  2137. #endif
  2138. }
  2139. #ifdef SCAD_MESH_OUTPUT
  2140. SERIAL_PROTOCOLCHAR(' ');
  2141. SERIAL_PROTOCOLCHAR(']'); // close sub-array
  2142. if (y < sy - 1) SERIAL_PROTOCOLCHAR(',');
  2143. #endif
  2144. SERIAL_EOL;
  2145. }
  2146. #ifdef SCAD_MESH_OUTPUT
  2147. SERIAL_PROTOCOLPGM("];"); // close 2D array
  2148. #endif
  2149. SERIAL_EOL;
  2150. }
  2151. #endif
  2152. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  2153. /**
  2154. * Extrapolate a single point from its neighbors
  2155. */
  2156. static void extrapolate_one_point(const uint8_t x, const uint8_t y, const int8_t xdir, const int8_t ydir) {
  2157. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2158. if (DEBUGGING(LEVELING)) {
  2159. SERIAL_ECHOPGM("Extrapolate [");
  2160. if (x < 10) SERIAL_CHAR(' ');
  2161. SERIAL_ECHO((int)x);
  2162. SERIAL_CHAR(xdir ? (xdir > 0 ? '+' : '-') : ' ');
  2163. SERIAL_CHAR(' ');
  2164. if (y < 10) SERIAL_CHAR(' ');
  2165. SERIAL_ECHO((int)y);
  2166. SERIAL_CHAR(ydir ? (ydir > 0 ? '+' : '-') : ' ');
  2167. SERIAL_CHAR(']');
  2168. }
  2169. #endif
  2170. if (!isnan(z_values[x][y])) {
  2171. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2172. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM(" (done)");
  2173. #endif
  2174. return; // Don't overwrite good values.
  2175. }
  2176. SERIAL_EOL;
  2177. // Get X neighbors, Y neighbors, and XY neighbors
  2178. const uint8_t x1 = x + xdir, y1 = y + ydir, x2 = x1 + xdir, y2 = y1 + ydir;
  2179. float a1 = z_values[x1][y ], a2 = z_values[x2][y ],
  2180. b1 = z_values[x ][y1], b2 = z_values[x ][y2],
  2181. c1 = z_values[x1][y1], c2 = z_values[x2][y2];
  2182. // Treat far unprobed points as zero, near as equal to far
  2183. if (isnan(a2)) a2 = 0.0; if (isnan(a1)) a1 = a2;
  2184. if (isnan(b2)) b2 = 0.0; if (isnan(b1)) b1 = b2;
  2185. if (isnan(c2)) c2 = 0.0; if (isnan(c1)) c1 = c2;
  2186. const float a = 2 * a1 - a2, b = 2 * b1 - b2, c = 2 * c1 - c2;
  2187. // Take the average instead of the median
  2188. z_values[x][y] = (a + b + c) / 3.0;
  2189. // Median is robust (ignores outliers).
  2190. // z_values[x][y] = (a < b) ? ((b < c) ? b : (c < a) ? a : c)
  2191. // : ((c < b) ? b : (a < c) ? a : c);
  2192. }
  2193. //Enable this if your SCARA uses 180° of total area
  2194. //#define EXTRAPOLATE_FROM_EDGE
  2195. #if ENABLED(EXTRAPOLATE_FROM_EDGE)
  2196. #if GRID_MAX_POINTS_X < GRID_MAX_POINTS_Y
  2197. #define HALF_IN_X
  2198. #elif GRID_MAX_POINTS_Y < GRID_MAX_POINTS_X
  2199. #define HALF_IN_Y
  2200. #endif
  2201. #endif
  2202. /**
  2203. * Fill in the unprobed points (corners of circular print surface)
  2204. * using linear extrapolation, away from the center.
  2205. */
  2206. static void extrapolate_unprobed_bed_level() {
  2207. #ifdef HALF_IN_X
  2208. constexpr uint8_t ctrx2 = 0, xlen = GRID_MAX_POINTS_X - 1;
  2209. #else
  2210. constexpr uint8_t ctrx1 = (GRID_MAX_POINTS_X - 1) / 2, // left-of-center
  2211. ctrx2 = (GRID_MAX_POINTS_X) / 2, // right-of-center
  2212. xlen = ctrx1;
  2213. #endif
  2214. #ifdef HALF_IN_Y
  2215. constexpr uint8_t ctry2 = 0, ylen = GRID_MAX_POINTS_Y - 1;
  2216. #else
  2217. constexpr uint8_t ctry1 = (GRID_MAX_POINTS_Y - 1) / 2, // top-of-center
  2218. ctry2 = (GRID_MAX_POINTS_Y) / 2, // bottom-of-center
  2219. ylen = ctry1;
  2220. #endif
  2221. for (uint8_t xo = 0; xo <= xlen; xo++)
  2222. for (uint8_t yo = 0; yo <= ylen; yo++) {
  2223. uint8_t x2 = ctrx2 + xo, y2 = ctry2 + yo;
  2224. #ifndef HALF_IN_X
  2225. const uint8_t x1 = ctrx1 - xo;
  2226. #endif
  2227. #ifndef HALF_IN_Y
  2228. const uint8_t y1 = ctry1 - yo;
  2229. #ifndef HALF_IN_X
  2230. extrapolate_one_point(x1, y1, +1, +1); // left-below + +
  2231. #endif
  2232. extrapolate_one_point(x2, y1, -1, +1); // right-below - +
  2233. #endif
  2234. #ifndef HALF_IN_X
  2235. extrapolate_one_point(x1, y2, +1, -1); // left-above + -
  2236. #endif
  2237. extrapolate_one_point(x2, y2, -1, -1); // right-above - -
  2238. }
  2239. }
  2240. static void print_bilinear_leveling_grid() {
  2241. SERIAL_ECHOLNPGM("Bilinear Leveling Grid:");
  2242. print_2d_array(GRID_MAX_POINTS_X, GRID_MAX_POINTS_Y, 3,
  2243. [](const uint8_t ix, const uint8_t iy) { return z_values[ix][iy]; }
  2244. );
  2245. }
  2246. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  2247. #define ABL_GRID_POINTS_VIRT_X (GRID_MAX_POINTS_X - 1) * (BILINEAR_SUBDIVISIONS) + 1
  2248. #define ABL_GRID_POINTS_VIRT_Y (GRID_MAX_POINTS_Y - 1) * (BILINEAR_SUBDIVISIONS) + 1
  2249. #define ABL_TEMP_POINTS_X (GRID_MAX_POINTS_X + 2)
  2250. #define ABL_TEMP_POINTS_Y (GRID_MAX_POINTS_Y + 2)
  2251. float z_values_virt[ABL_GRID_POINTS_VIRT_X][ABL_GRID_POINTS_VIRT_Y];
  2252. int bilinear_grid_spacing_virt[2] = { 0 };
  2253. float bilinear_grid_factor_virt[2] = { 0 };
  2254. static void bed_level_virt_print() {
  2255. SERIAL_ECHOLNPGM("Subdivided with CATMULL ROM Leveling Grid:");
  2256. print_2d_array(ABL_GRID_POINTS_VIRT_X, ABL_GRID_POINTS_VIRT_Y, 5,
  2257. [](const uint8_t ix, const uint8_t iy) { return z_values_virt[ix][iy]; }
  2258. );
  2259. }
  2260. #define LINEAR_EXTRAPOLATION(E, I) ((E) * 2 - (I))
  2261. float bed_level_virt_coord(const uint8_t x, const uint8_t y) {
  2262. uint8_t ep = 0, ip = 1;
  2263. if (!x || x == ABL_TEMP_POINTS_X - 1) {
  2264. if (x) {
  2265. ep = GRID_MAX_POINTS_X - 1;
  2266. ip = GRID_MAX_POINTS_X - 2;
  2267. }
  2268. if (WITHIN(y, 1, ABL_TEMP_POINTS_Y - 2))
  2269. return LINEAR_EXTRAPOLATION(
  2270. z_values[ep][y - 1],
  2271. z_values[ip][y - 1]
  2272. );
  2273. else
  2274. return LINEAR_EXTRAPOLATION(
  2275. bed_level_virt_coord(ep + 1, y),
  2276. bed_level_virt_coord(ip + 1, y)
  2277. );
  2278. }
  2279. if (!y || y == ABL_TEMP_POINTS_Y - 1) {
  2280. if (y) {
  2281. ep = GRID_MAX_POINTS_Y - 1;
  2282. ip = GRID_MAX_POINTS_Y - 2;
  2283. }
  2284. if (WITHIN(x, 1, ABL_TEMP_POINTS_X - 2))
  2285. return LINEAR_EXTRAPOLATION(
  2286. z_values[x - 1][ep],
  2287. z_values[x - 1][ip]
  2288. );
  2289. else
  2290. return LINEAR_EXTRAPOLATION(
  2291. bed_level_virt_coord(x, ep + 1),
  2292. bed_level_virt_coord(x, ip + 1)
  2293. );
  2294. }
  2295. return z_values[x - 1][y - 1];
  2296. }
  2297. static float bed_level_virt_cmr(const float p[4], const uint8_t i, const float t) {
  2298. return (
  2299. p[i-1] * -t * sq(1 - t)
  2300. + p[i] * (2 - 5 * sq(t) + 3 * t * sq(t))
  2301. + p[i+1] * t * (1 + 4 * t - 3 * sq(t))
  2302. - p[i+2] * sq(t) * (1 - t)
  2303. ) * 0.5;
  2304. }
  2305. static float bed_level_virt_2cmr(const uint8_t x, const uint8_t y, const float &tx, const float &ty) {
  2306. float row[4], column[4];
  2307. for (uint8_t i = 0; i < 4; i++) {
  2308. for (uint8_t j = 0; j < 4; j++) {
  2309. column[j] = bed_level_virt_coord(i + x - 1, j + y - 1);
  2310. }
  2311. row[i] = bed_level_virt_cmr(column, 1, ty);
  2312. }
  2313. return bed_level_virt_cmr(row, 1, tx);
  2314. }
  2315. void bed_level_virt_interpolate() {
  2316. bilinear_grid_spacing_virt[X_AXIS] = bilinear_grid_spacing[X_AXIS] / (BILINEAR_SUBDIVISIONS);
  2317. bilinear_grid_spacing_virt[Y_AXIS] = bilinear_grid_spacing[Y_AXIS] / (BILINEAR_SUBDIVISIONS);
  2318. bilinear_grid_factor_virt[X_AXIS] = RECIPROCAL(bilinear_grid_spacing_virt[X_AXIS]);
  2319. bilinear_grid_factor_virt[Y_AXIS] = RECIPROCAL(bilinear_grid_spacing_virt[Y_AXIS]);
  2320. for (uint8_t y = 0; y < GRID_MAX_POINTS_Y; y++)
  2321. for (uint8_t x = 0; x < GRID_MAX_POINTS_X; x++)
  2322. for (uint8_t ty = 0; ty < BILINEAR_SUBDIVISIONS; ty++)
  2323. for (uint8_t tx = 0; tx < BILINEAR_SUBDIVISIONS; tx++) {
  2324. if ((ty && y == GRID_MAX_POINTS_Y - 1) || (tx && x == GRID_MAX_POINTS_X - 1))
  2325. continue;
  2326. z_values_virt[x * (BILINEAR_SUBDIVISIONS) + tx][y * (BILINEAR_SUBDIVISIONS) + ty] =
  2327. bed_level_virt_2cmr(
  2328. x + 1,
  2329. y + 1,
  2330. (float)tx / (BILINEAR_SUBDIVISIONS),
  2331. (float)ty / (BILINEAR_SUBDIVISIONS)
  2332. );
  2333. }
  2334. }
  2335. #endif // ABL_BILINEAR_SUBDIVISION
  2336. // Refresh after other values have been updated
  2337. void refresh_bed_level() {
  2338. bilinear_grid_factor[X_AXIS] = RECIPROCAL(bilinear_grid_spacing[X_AXIS]);
  2339. bilinear_grid_factor[Y_AXIS] = RECIPROCAL(bilinear_grid_spacing[Y_AXIS]);
  2340. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  2341. bed_level_virt_interpolate();
  2342. #endif
  2343. }
  2344. #endif // AUTO_BED_LEVELING_BILINEAR
  2345. /**
  2346. * Home an individual linear axis
  2347. */
  2348. static void do_homing_move(const AxisEnum axis, float distance, float fr_mm_s=0.0) {
  2349. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2350. if (DEBUGGING(LEVELING)) {
  2351. SERIAL_ECHOPAIR(">>> do_homing_move(", axis_codes[axis]);
  2352. SERIAL_ECHOPAIR(", ", distance);
  2353. SERIAL_ECHOPAIR(", ", fr_mm_s);
  2354. SERIAL_CHAR(')');
  2355. SERIAL_EOL;
  2356. }
  2357. #endif
  2358. #if HOMING_Z_WITH_PROBE && ENABLED(BLTOUCH)
  2359. const bool deploy_bltouch = (axis == Z_AXIS && distance < 0);
  2360. if (deploy_bltouch) set_bltouch_deployed(true);
  2361. #endif
  2362. #if QUIET_PROBING
  2363. if (axis == Z_AXIS) probing_pause(true);
  2364. #endif
  2365. // Tell the planner we're at Z=0
  2366. current_position[axis] = 0;
  2367. #if IS_SCARA
  2368. SYNC_PLAN_POSITION_KINEMATIC();
  2369. current_position[axis] = distance;
  2370. inverse_kinematics(current_position);
  2371. planner.buffer_line(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], current_position[E_AXIS], fr_mm_s ? fr_mm_s : homing_feedrate_mm_s[axis], active_extruder);
  2372. #else
  2373. sync_plan_position();
  2374. current_position[axis] = distance;
  2375. 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_mm_s[axis], active_extruder);
  2376. #endif
  2377. stepper.synchronize();
  2378. #if QUIET_PROBING
  2379. if (axis == Z_AXIS) probing_pause(false);
  2380. #endif
  2381. #if HOMING_Z_WITH_PROBE && ENABLED(BLTOUCH)
  2382. if (deploy_bltouch) set_bltouch_deployed(false);
  2383. #endif
  2384. endstops.hit_on_purpose();
  2385. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2386. if (DEBUGGING(LEVELING)) {
  2387. SERIAL_ECHOPAIR("<<< do_homing_move(", axis_codes[axis]);
  2388. SERIAL_CHAR(')');
  2389. SERIAL_EOL;
  2390. }
  2391. #endif
  2392. }
  2393. /**
  2394. * TMC2130 specific sensorless homing using stallGuard2.
  2395. * stallGuard2 only works when in spreadCycle mode.
  2396. * spreadCycle and stealthChop are mutually exclusive.
  2397. */
  2398. #if ENABLED(SENSORLESS_HOMING)
  2399. void tmc2130_sensorless_homing(TMC2130Stepper &st, bool enable=true) {
  2400. #if ENABLED(STEALTHCHOP)
  2401. if (enable) {
  2402. st.coolstep_min_speed(1024UL * 1024UL - 1UL);
  2403. st.stealthChop(0);
  2404. }
  2405. else {
  2406. st.coolstep_min_speed(0);
  2407. st.stealthChop(1);
  2408. }
  2409. #endif
  2410. st.diag1_stall(enable ? 1 : 0);
  2411. }
  2412. #endif
  2413. /**
  2414. * Home an individual "raw axis" to its endstop.
  2415. * This applies to XYZ on Cartesian and Core robots, and
  2416. * to the individual ABC steppers on DELTA and SCARA.
  2417. *
  2418. * At the end of the procedure the axis is marked as
  2419. * homed and the current position of that axis is updated.
  2420. * Kinematic robots should wait till all axes are homed
  2421. * before updating the current position.
  2422. */
  2423. #define HOMEAXIS(LETTER) homeaxis(LETTER##_AXIS)
  2424. static void homeaxis(const AxisEnum axis) {
  2425. #if IS_SCARA
  2426. // Only Z homing (with probe) is permitted
  2427. if (axis != Z_AXIS) { BUZZ(100, 880); return; }
  2428. #else
  2429. #define CAN_HOME(A) \
  2430. (axis == A##_AXIS && ((A##_MIN_PIN > -1 && A##_HOME_DIR < 0) || (A##_MAX_PIN > -1 && A##_HOME_DIR > 0)))
  2431. if (!CAN_HOME(X) && !CAN_HOME(Y) && !CAN_HOME(Z)) return;
  2432. #endif
  2433. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2434. if (DEBUGGING(LEVELING)) {
  2435. SERIAL_ECHOPAIR(">>> homeaxis(", axis_codes[axis]);
  2436. SERIAL_CHAR(')');
  2437. SERIAL_EOL;
  2438. }
  2439. #endif
  2440. const int axis_home_dir =
  2441. #if ENABLED(DUAL_X_CARRIAGE)
  2442. (axis == X_AXIS) ? x_home_dir(active_extruder) :
  2443. #endif
  2444. home_dir(axis);
  2445. // Homing Z towards the bed? Deploy the Z probe or endstop.
  2446. #if HOMING_Z_WITH_PROBE
  2447. if (axis == Z_AXIS && DEPLOY_PROBE()) return;
  2448. #endif
  2449. // Set a flag for Z motor locking
  2450. #if ENABLED(Z_DUAL_ENDSTOPS)
  2451. if (axis == Z_AXIS) stepper.set_homing_flag(true);
  2452. #endif
  2453. // Disable stealthChop if used. Enable diag1 pin on driver.
  2454. #if ENABLED(SENSORLESS_HOMING)
  2455. #if ENABLED(X_IS_TMC2130)
  2456. if (axis == X_AXIS) tmc2130_sensorless_homing(stepperX);
  2457. #endif
  2458. #if ENABLED(Y_IS_TMC2130)
  2459. if (axis == Y_AXIS) tmc2130_sensorless_homing(stepperY);
  2460. #endif
  2461. #endif
  2462. // Fast move towards endstop until triggered
  2463. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2464. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Home 1 Fast:");
  2465. #endif
  2466. do_homing_move(axis, 1.5 * max_length(axis) * axis_home_dir);
  2467. // When homing Z with probe respect probe clearance
  2468. const float bump = axis_home_dir * (
  2469. #if HOMING_Z_WITH_PROBE
  2470. (axis == Z_AXIS) ? max(Z_CLEARANCE_BETWEEN_PROBES, home_bump_mm(Z_AXIS)) :
  2471. #endif
  2472. home_bump_mm(axis)
  2473. );
  2474. // If a second homing move is configured...
  2475. if (bump) {
  2476. // Move away from the endstop by the axis HOME_BUMP_MM
  2477. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2478. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Move Away:");
  2479. #endif
  2480. do_homing_move(axis, -bump);
  2481. // Slow move towards endstop until triggered
  2482. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2483. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Home 2 Slow:");
  2484. #endif
  2485. do_homing_move(axis, 2 * bump, get_homing_bump_feedrate(axis));
  2486. }
  2487. #if ENABLED(Z_DUAL_ENDSTOPS)
  2488. if (axis == Z_AXIS) {
  2489. float adj = fabs(z_endstop_adj);
  2490. bool lockZ1;
  2491. if (axis_home_dir > 0) {
  2492. adj = -adj;
  2493. lockZ1 = (z_endstop_adj > 0);
  2494. }
  2495. else
  2496. lockZ1 = (z_endstop_adj < 0);
  2497. if (lockZ1) stepper.set_z_lock(true); else stepper.set_z2_lock(true);
  2498. // Move to the adjusted endstop height
  2499. do_homing_move(axis, adj);
  2500. if (lockZ1) stepper.set_z_lock(false); else stepper.set_z2_lock(false);
  2501. stepper.set_homing_flag(false);
  2502. } // Z_AXIS
  2503. #endif
  2504. #if IS_SCARA
  2505. set_axis_is_at_home(axis);
  2506. SYNC_PLAN_POSITION_KINEMATIC();
  2507. #elif ENABLED(DELTA)
  2508. // Delta has already moved all three towers up in G28
  2509. // so here it re-homes each tower in turn.
  2510. // Delta homing treats the axes as normal linear axes.
  2511. // retrace by the amount specified in endstop_adj + additional 0.1mm in order to have minimum steps
  2512. if (endstop_adj[axis] * Z_HOME_DIR <= 0) {
  2513. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2514. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("endstop_adj:");
  2515. #endif
  2516. do_homing_move(axis, endstop_adj[axis] - 0.1);
  2517. }
  2518. #else
  2519. // For cartesian/core machines,
  2520. // set the axis to its home position
  2521. set_axis_is_at_home(axis);
  2522. sync_plan_position();
  2523. destination[axis] = current_position[axis];
  2524. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2525. if (DEBUGGING(LEVELING)) DEBUG_POS("> AFTER set_axis_is_at_home", current_position);
  2526. #endif
  2527. #endif
  2528. // Re-enable stealthChop if used. Disable diag1 pin on driver.
  2529. #if ENABLED(SENSORLESS_HOMING)
  2530. #if ENABLED(X_IS_TMC2130)
  2531. if (axis == X_AXIS) tmc2130_sensorless_homing(stepperX, false);
  2532. #endif
  2533. #if ENABLED(Y_IS_TMC2130)
  2534. if (axis == Y_AXIS) tmc2130_sensorless_homing(stepperY, false);
  2535. #endif
  2536. #endif
  2537. // Put away the Z probe
  2538. #if HOMING_Z_WITH_PROBE
  2539. if (axis == Z_AXIS && STOW_PROBE()) return;
  2540. #endif
  2541. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2542. if (DEBUGGING(LEVELING)) {
  2543. SERIAL_ECHOPAIR("<<< homeaxis(", axis_codes[axis]);
  2544. SERIAL_CHAR(')');
  2545. SERIAL_EOL;
  2546. }
  2547. #endif
  2548. } // homeaxis()
  2549. #if ENABLED(FWRETRACT)
  2550. void retract(const bool retracting, const bool swapping = false) {
  2551. static float hop_height;
  2552. if (retracting == retracted[active_extruder]) return;
  2553. const float old_feedrate_mm_s = feedrate_mm_s;
  2554. set_destination_to_current();
  2555. if (retracting) {
  2556. feedrate_mm_s = retract_feedrate_mm_s;
  2557. current_position[E_AXIS] += (swapping ? retract_length_swap : retract_length) / volumetric_multiplier[active_extruder];
  2558. sync_plan_position_e();
  2559. prepare_move_to_destination();
  2560. if (retract_zlift > 0.01) {
  2561. hop_height = current_position[Z_AXIS];
  2562. // Pretend current position is lower
  2563. current_position[Z_AXIS] -= retract_zlift;
  2564. SYNC_PLAN_POSITION_KINEMATIC();
  2565. // Raise up to the old current_position
  2566. prepare_move_to_destination();
  2567. }
  2568. }
  2569. else {
  2570. // If the height hasn't been lowered, undo the Z hop
  2571. if (retract_zlift > 0.01 && hop_height <= current_position[Z_AXIS]) {
  2572. // Pretend current position is higher. Z will lower on the next move
  2573. current_position[Z_AXIS] += retract_zlift;
  2574. SYNC_PLAN_POSITION_KINEMATIC();
  2575. // Lower Z
  2576. prepare_move_to_destination();
  2577. }
  2578. feedrate_mm_s = retract_recover_feedrate_mm_s;
  2579. const float move_e = swapping ? retract_length_swap + retract_recover_length_swap : retract_length + retract_recover_length;
  2580. current_position[E_AXIS] -= move_e / volumetric_multiplier[active_extruder];
  2581. sync_plan_position_e();
  2582. // Recover E
  2583. prepare_move_to_destination();
  2584. }
  2585. feedrate_mm_s = old_feedrate_mm_s;
  2586. retracted[active_extruder] = retracting;
  2587. } // retract()
  2588. #endif // FWRETRACT
  2589. #if ENABLED(MIXING_EXTRUDER)
  2590. void normalize_mix() {
  2591. float mix_total = 0.0;
  2592. for (uint8_t i = 0; i < MIXING_STEPPERS; i++) mix_total += RECIPROCAL(mixing_factor[i]);
  2593. // Scale all values if they don't add up to ~1.0
  2594. if (!NEAR(mix_total, 1.0)) {
  2595. SERIAL_PROTOCOLLNPGM("Warning: Mix factors must add up to 1.0. Scaling.");
  2596. for (uint8_t i = 0; i < MIXING_STEPPERS; i++) mixing_factor[i] *= mix_total;
  2597. }
  2598. }
  2599. #if ENABLED(DIRECT_MIXING_IN_G1)
  2600. // Get mixing parameters from the GCode
  2601. // The total "must" be 1.0 (but it will be normalized)
  2602. // If no mix factors are given, the old mix is preserved
  2603. void gcode_get_mix() {
  2604. const char* mixing_codes = "ABCDHI";
  2605. byte mix_bits = 0;
  2606. for (uint8_t i = 0; i < MIXING_STEPPERS; i++) {
  2607. if (parser.seen(mixing_codes[i])) {
  2608. SBI(mix_bits, i);
  2609. float v = parser.value_float();
  2610. NOLESS(v, 0.0);
  2611. mixing_factor[i] = RECIPROCAL(v);
  2612. }
  2613. }
  2614. // If any mixing factors were included, clear the rest
  2615. // If none were included, preserve the last mix
  2616. if (mix_bits) {
  2617. for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
  2618. if (!TEST(mix_bits, i)) mixing_factor[i] = 0.0;
  2619. normalize_mix();
  2620. }
  2621. }
  2622. #endif
  2623. #endif
  2624. /**
  2625. * ***************************************************************************
  2626. * ***************************** G-CODE HANDLING *****************************
  2627. * ***************************************************************************
  2628. */
  2629. /**
  2630. * Set XYZE destination and feedrate from the current GCode command
  2631. *
  2632. * - Set destination from included axis codes
  2633. * - Set to current for missing axis codes
  2634. * - Set the feedrate, if included
  2635. */
  2636. void gcode_get_destination() {
  2637. LOOP_XYZE(i) {
  2638. if (parser.seen(axis_codes[i]))
  2639. destination[i] = parser.value_axis_units((AxisEnum)i) + (axis_relative_modes[i] || relative_mode ? current_position[i] : 0);
  2640. else
  2641. destination[i] = current_position[i];
  2642. }
  2643. if (parser.seen('F') && parser.value_linear_units() > 0.0)
  2644. feedrate_mm_s = MMM_TO_MMS(parser.value_feedrate());
  2645. #if ENABLED(PRINTCOUNTER)
  2646. if (!DEBUGGING(DRYRUN))
  2647. print_job_timer.incFilamentUsed(destination[E_AXIS] - current_position[E_AXIS]);
  2648. #endif
  2649. // Get ABCDHI mixing factors
  2650. #if ENABLED(MIXING_EXTRUDER) && ENABLED(DIRECT_MIXING_IN_G1)
  2651. gcode_get_mix();
  2652. #endif
  2653. }
  2654. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  2655. /**
  2656. * Output a "busy" message at regular intervals
  2657. * while the machine is not accepting commands.
  2658. */
  2659. void host_keepalive() {
  2660. const millis_t ms = millis();
  2661. if (host_keepalive_interval && busy_state != NOT_BUSY) {
  2662. if (PENDING(ms, next_busy_signal_ms)) return;
  2663. switch (busy_state) {
  2664. case IN_HANDLER:
  2665. case IN_PROCESS:
  2666. SERIAL_ECHO_START;
  2667. SERIAL_ECHOLNPGM(MSG_BUSY_PROCESSING);
  2668. break;
  2669. case PAUSED_FOR_USER:
  2670. SERIAL_ECHO_START;
  2671. SERIAL_ECHOLNPGM(MSG_BUSY_PAUSED_FOR_USER);
  2672. break;
  2673. case PAUSED_FOR_INPUT:
  2674. SERIAL_ECHO_START;
  2675. SERIAL_ECHOLNPGM(MSG_BUSY_PAUSED_FOR_INPUT);
  2676. break;
  2677. default:
  2678. break;
  2679. }
  2680. }
  2681. next_busy_signal_ms = ms + host_keepalive_interval * 1000UL;
  2682. }
  2683. #endif // HOST_KEEPALIVE_FEATURE
  2684. /**************************************************
  2685. ***************** GCode Handlers *****************
  2686. **************************************************/
  2687. /**
  2688. * G0, G1: Coordinated movement of X Y Z E axes
  2689. */
  2690. inline void gcode_G0_G1(
  2691. #if IS_SCARA
  2692. bool fast_move=false
  2693. #endif
  2694. ) {
  2695. if (IsRunning()) {
  2696. gcode_get_destination(); // For X Y Z E F
  2697. #if ENABLED(FWRETRACT)
  2698. if (autoretract_enabled && !(parser.seen('X') || parser.seen('Y') || parser.seen('Z')) && parser.seen('E')) {
  2699. const float echange = destination[E_AXIS] - current_position[E_AXIS];
  2700. // Is this move an attempt to retract or recover?
  2701. if ((echange < -MIN_RETRACT && !retracted[active_extruder]) || (echange > MIN_RETRACT && retracted[active_extruder])) {
  2702. current_position[E_AXIS] = destination[E_AXIS]; // hide the slicer-generated retract/recover from calculations
  2703. sync_plan_position_e(); // AND from the planner
  2704. retract(!retracted[active_extruder]);
  2705. return;
  2706. }
  2707. }
  2708. #endif // FWRETRACT
  2709. #if IS_SCARA
  2710. fast_move ? prepare_uninterpolated_move_to_destination() : prepare_move_to_destination();
  2711. #else
  2712. prepare_move_to_destination();
  2713. #endif
  2714. }
  2715. }
  2716. /**
  2717. * G2: Clockwise Arc
  2718. * G3: Counterclockwise Arc
  2719. *
  2720. * This command has two forms: IJ-form and R-form.
  2721. *
  2722. * - I specifies an X offset. J specifies a Y offset.
  2723. * At least one of the IJ parameters is required.
  2724. * X and Y can be omitted to do a complete circle.
  2725. * The given XY is not error-checked. The arc ends
  2726. * based on the angle of the destination.
  2727. * Mixing I or J with R will throw an error.
  2728. *
  2729. * - R specifies the radius. X or Y is required.
  2730. * Omitting both X and Y will throw an error.
  2731. * X or Y must differ from the current XY.
  2732. * Mixing R with I or J will throw an error.
  2733. *
  2734. * Examples:
  2735. *
  2736. * G2 I10 ; CW circle centered at X+10
  2737. * G3 X20 Y12 R14 ; CCW circle with r=14 ending at X20 Y12
  2738. */
  2739. #if ENABLED(ARC_SUPPORT)
  2740. inline void gcode_G2_G3(bool clockwise) {
  2741. if (IsRunning()) {
  2742. #if ENABLED(SF_ARC_FIX)
  2743. const bool relative_mode_backup = relative_mode;
  2744. relative_mode = true;
  2745. #endif
  2746. gcode_get_destination();
  2747. #if ENABLED(SF_ARC_FIX)
  2748. relative_mode = relative_mode_backup;
  2749. #endif
  2750. float arc_offset[2] = { 0.0, 0.0 };
  2751. if (parser.seen('R')) {
  2752. const float r = parser.value_linear_units(),
  2753. x1 = current_position[X_AXIS], y1 = current_position[Y_AXIS],
  2754. x2 = destination[X_AXIS], y2 = destination[Y_AXIS];
  2755. if (r && (x2 != x1 || y2 != y1)) {
  2756. const float e = clockwise ^ (r < 0) ? -1 : 1, // clockwise -1/1, counterclockwise 1/-1
  2757. dx = x2 - x1, dy = y2 - y1, // X and Y differences
  2758. d = HYPOT(dx, dy), // Linear distance between the points
  2759. h = sqrt(sq(r) - sq(d * 0.5)), // Distance to the arc pivot-point
  2760. mx = (x1 + x2) * 0.5, my = (y1 + y2) * 0.5, // Point between the two points
  2761. sx = -dy / d, sy = dx / d, // Slope of the perpendicular bisector
  2762. cx = mx + e * h * sx, cy = my + e * h * sy; // Pivot-point of the arc
  2763. arc_offset[X_AXIS] = cx - x1;
  2764. arc_offset[Y_AXIS] = cy - y1;
  2765. }
  2766. }
  2767. else {
  2768. if (parser.seen('I')) arc_offset[X_AXIS] = parser.value_linear_units();
  2769. if (parser.seen('J')) arc_offset[Y_AXIS] = parser.value_linear_units();
  2770. }
  2771. if (arc_offset[0] || arc_offset[1]) {
  2772. // Send an arc to the planner
  2773. plan_arc(destination, arc_offset, clockwise);
  2774. refresh_cmd_timeout();
  2775. }
  2776. else {
  2777. // Bad arguments
  2778. SERIAL_ERROR_START;
  2779. SERIAL_ERRORLNPGM(MSG_ERR_ARC_ARGS);
  2780. }
  2781. }
  2782. }
  2783. #endif
  2784. /**
  2785. * G4: Dwell S<seconds> or P<milliseconds>
  2786. */
  2787. inline void gcode_G4() {
  2788. millis_t dwell_ms = 0;
  2789. if (parser.seen('P')) dwell_ms = parser.value_millis(); // milliseconds to wait
  2790. if (parser.seen('S')) dwell_ms = parser.value_millis_from_seconds(); // seconds to wait
  2791. stepper.synchronize();
  2792. refresh_cmd_timeout();
  2793. dwell_ms += previous_cmd_ms; // keep track of when we started waiting
  2794. if (!lcd_hasstatus()) LCD_MESSAGEPGM(MSG_DWELL);
  2795. while (PENDING(millis(), dwell_ms)) idle();
  2796. }
  2797. #if ENABLED(BEZIER_CURVE_SUPPORT)
  2798. /**
  2799. * Parameters interpreted according to:
  2800. * http://linuxcnc.org/docs/2.6/html/gcode/gcode.html#sec:G5-Cubic-Spline
  2801. * However I, J omission is not supported at this point; all
  2802. * parameters can be omitted and default to zero.
  2803. */
  2804. /**
  2805. * G5: Cubic B-spline
  2806. */
  2807. inline void gcode_G5() {
  2808. if (IsRunning()) {
  2809. gcode_get_destination();
  2810. const float offset[] = {
  2811. parser.seen('I') ? parser.value_linear_units() : 0.0,
  2812. parser.seen('J') ? parser.value_linear_units() : 0.0,
  2813. parser.seen('P') ? parser.value_linear_units() : 0.0,
  2814. parser.seen('Q') ? parser.value_linear_units() : 0.0
  2815. };
  2816. plan_cubic_move(offset);
  2817. }
  2818. }
  2819. #endif // BEZIER_CURVE_SUPPORT
  2820. #if ENABLED(FWRETRACT)
  2821. /**
  2822. * G10 - Retract filament according to settings of M207
  2823. * G11 - Recover filament according to settings of M208
  2824. */
  2825. inline void gcode_G10_G11(bool doRetract=false) {
  2826. #if EXTRUDERS > 1
  2827. if (doRetract) {
  2828. retracted_swap[active_extruder] = (parser.seen('S') && parser.value_bool()); // checks for swap retract argument
  2829. }
  2830. #endif
  2831. retract(doRetract
  2832. #if EXTRUDERS > 1
  2833. , retracted_swap[active_extruder]
  2834. #endif
  2835. );
  2836. }
  2837. #endif // FWRETRACT
  2838. #if ENABLED(NOZZLE_CLEAN_FEATURE)
  2839. /**
  2840. * G12: Clean the nozzle
  2841. */
  2842. inline void gcode_G12() {
  2843. // Don't allow nozzle cleaning without homing first
  2844. if (axis_unhomed_error()) return;
  2845. const uint8_t pattern = parser.seen('P') ? parser.value_ushort() : 0,
  2846. strokes = parser.seen('S') ? parser.value_ushort() : NOZZLE_CLEAN_STROKES,
  2847. objects = parser.seen('T') ? parser.value_ushort() : NOZZLE_CLEAN_TRIANGLES;
  2848. const float radius = parser.seen('R') ? parser.value_float() : NOZZLE_CLEAN_CIRCLE_RADIUS;
  2849. Nozzle::clean(pattern, strokes, radius, objects);
  2850. }
  2851. #endif
  2852. #if ENABLED(INCH_MODE_SUPPORT)
  2853. /**
  2854. * G20: Set input mode to inches
  2855. */
  2856. inline void gcode_G20() { parser.set_input_linear_units(LINEARUNIT_INCH); }
  2857. /**
  2858. * G21: Set input mode to millimeters
  2859. */
  2860. inline void gcode_G21() { parser.set_input_linear_units(LINEARUNIT_MM); }
  2861. #endif
  2862. #if ENABLED(NOZZLE_PARK_FEATURE)
  2863. /**
  2864. * G27: Park the nozzle
  2865. */
  2866. inline void gcode_G27() {
  2867. // Don't allow nozzle parking without homing first
  2868. if (axis_unhomed_error()) return;
  2869. Nozzle::park(parser.seen('P') ? parser.value_ushort() : 0);
  2870. }
  2871. #endif // NOZZLE_PARK_FEATURE
  2872. #if ENABLED(QUICK_HOME)
  2873. static void quick_home_xy() {
  2874. // Pretend the current position is 0,0
  2875. current_position[X_AXIS] = current_position[Y_AXIS] = 0.0;
  2876. sync_plan_position();
  2877. const int x_axis_home_dir =
  2878. #if ENABLED(DUAL_X_CARRIAGE)
  2879. x_home_dir(active_extruder)
  2880. #else
  2881. home_dir(X_AXIS)
  2882. #endif
  2883. ;
  2884. const float mlx = max_length(X_AXIS),
  2885. mly = max_length(Y_AXIS),
  2886. mlratio = mlx > mly ? mly / mlx : mlx / mly,
  2887. fr_mm_s = min(homing_feedrate_mm_s[X_AXIS], homing_feedrate_mm_s[Y_AXIS]) * sqrt(sq(mlratio) + 1.0);
  2888. do_blocking_move_to_xy(1.5 * mlx * x_axis_home_dir, 1.5 * mly * home_dir(Y_AXIS), fr_mm_s);
  2889. endstops.hit_on_purpose(); // clear endstop hit flags
  2890. current_position[X_AXIS] = current_position[Y_AXIS] = 0.0;
  2891. }
  2892. #endif // QUICK_HOME
  2893. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2894. void log_machine_info() {
  2895. SERIAL_ECHOPGM("Machine Type: ");
  2896. #if ENABLED(DELTA)
  2897. SERIAL_ECHOLNPGM("Delta");
  2898. #elif IS_SCARA
  2899. SERIAL_ECHOLNPGM("SCARA");
  2900. #elif IS_CORE
  2901. SERIAL_ECHOLNPGM("Core");
  2902. #else
  2903. SERIAL_ECHOLNPGM("Cartesian");
  2904. #endif
  2905. SERIAL_ECHOPGM("Probe: ");
  2906. #if ENABLED(PROBE_MANUALLY)
  2907. SERIAL_ECHOLNPGM("PROBE_MANUALLY");
  2908. #elif ENABLED(FIX_MOUNTED_PROBE)
  2909. SERIAL_ECHOLNPGM("FIX_MOUNTED_PROBE");
  2910. #elif ENABLED(BLTOUCH)
  2911. SERIAL_ECHOLNPGM("BLTOUCH");
  2912. #elif HAS_Z_SERVO_ENDSTOP
  2913. SERIAL_ECHOLNPGM("SERVO PROBE");
  2914. #elif ENABLED(Z_PROBE_SLED)
  2915. SERIAL_ECHOLNPGM("Z_PROBE_SLED");
  2916. #elif ENABLED(Z_PROBE_ALLEN_KEY)
  2917. SERIAL_ECHOLNPGM("Z_PROBE_ALLEN_KEY");
  2918. #else
  2919. SERIAL_ECHOLNPGM("NONE");
  2920. #endif
  2921. #if HAS_BED_PROBE
  2922. SERIAL_ECHOPAIR("Probe Offset X:", X_PROBE_OFFSET_FROM_EXTRUDER);
  2923. SERIAL_ECHOPAIR(" Y:", Y_PROBE_OFFSET_FROM_EXTRUDER);
  2924. SERIAL_ECHOPAIR(" Z:", zprobe_zoffset);
  2925. #if (X_PROBE_OFFSET_FROM_EXTRUDER > 0)
  2926. SERIAL_ECHOPGM(" (Right");
  2927. #elif (X_PROBE_OFFSET_FROM_EXTRUDER < 0)
  2928. SERIAL_ECHOPGM(" (Left");
  2929. #elif (Y_PROBE_OFFSET_FROM_EXTRUDER != 0)
  2930. SERIAL_ECHOPGM(" (Middle");
  2931. #else
  2932. SERIAL_ECHOPGM(" (Aligned With");
  2933. #endif
  2934. #if (Y_PROBE_OFFSET_FROM_EXTRUDER > 0)
  2935. SERIAL_ECHOPGM("-Back");
  2936. #elif (Y_PROBE_OFFSET_FROM_EXTRUDER < 0)
  2937. SERIAL_ECHOPGM("-Front");
  2938. #elif (X_PROBE_OFFSET_FROM_EXTRUDER != 0)
  2939. SERIAL_ECHOPGM("-Center");
  2940. #endif
  2941. if (zprobe_zoffset < 0)
  2942. SERIAL_ECHOPGM(" & Below");
  2943. else if (zprobe_zoffset > 0)
  2944. SERIAL_ECHOPGM(" & Above");
  2945. else
  2946. SERIAL_ECHOPGM(" & Same Z as");
  2947. SERIAL_ECHOLNPGM(" Nozzle)");
  2948. #endif
  2949. #if HAS_ABL
  2950. SERIAL_ECHOPGM("Auto Bed Leveling: ");
  2951. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  2952. SERIAL_ECHOPGM("LINEAR");
  2953. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  2954. SERIAL_ECHOPGM("BILINEAR");
  2955. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  2956. SERIAL_ECHOPGM("3POINT");
  2957. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  2958. SERIAL_ECHOPGM("UBL");
  2959. #endif
  2960. if (leveling_is_active()) {
  2961. SERIAL_ECHOLNPGM(" (enabled)");
  2962. #if ABL_PLANAR
  2963. float diff[XYZ] = {
  2964. stepper.get_axis_position_mm(X_AXIS) - current_position[X_AXIS],
  2965. stepper.get_axis_position_mm(Y_AXIS) - current_position[Y_AXIS],
  2966. stepper.get_axis_position_mm(Z_AXIS) - current_position[Z_AXIS]
  2967. };
  2968. SERIAL_ECHOPGM("ABL Adjustment X");
  2969. if (diff[X_AXIS] > 0) SERIAL_CHAR('+');
  2970. SERIAL_ECHO(diff[X_AXIS]);
  2971. SERIAL_ECHOPGM(" Y");
  2972. if (diff[Y_AXIS] > 0) SERIAL_CHAR('+');
  2973. SERIAL_ECHO(diff[Y_AXIS]);
  2974. SERIAL_ECHOPGM(" Z");
  2975. if (diff[Z_AXIS] > 0) SERIAL_CHAR('+');
  2976. SERIAL_ECHO(diff[Z_AXIS]);
  2977. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  2978. SERIAL_ECHOPAIR("UBL Adjustment Z", stepper.get_axis_position_mm(Z_AXIS) - current_position[Z_AXIS]);
  2979. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  2980. SERIAL_ECHOPAIR("ABL Adjustment Z", bilinear_z_offset(current_position));
  2981. #endif
  2982. }
  2983. else
  2984. SERIAL_ECHOLNPGM(" (disabled)");
  2985. SERIAL_EOL;
  2986. #elif ENABLED(MESH_BED_LEVELING)
  2987. SERIAL_ECHOPGM("Mesh Bed Leveling");
  2988. if (leveling_is_active()) {
  2989. float lz = current_position[Z_AXIS];
  2990. planner.apply_leveling(current_position[X_AXIS], current_position[Y_AXIS], lz);
  2991. SERIAL_ECHOLNPGM(" (enabled)");
  2992. SERIAL_ECHOPAIR("MBL Adjustment Z", lz);
  2993. }
  2994. else
  2995. SERIAL_ECHOPGM(" (disabled)");
  2996. SERIAL_EOL;
  2997. #endif // MESH_BED_LEVELING
  2998. }
  2999. #endif // DEBUG_LEVELING_FEATURE
  3000. #if ENABLED(DELTA)
  3001. /**
  3002. * A delta can only safely home all axes at the same time
  3003. * This is like quick_home_xy() but for 3 towers.
  3004. */
  3005. inline void home_delta() {
  3006. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3007. if (DEBUGGING(LEVELING)) DEBUG_POS(">>> home_delta", current_position);
  3008. #endif
  3009. // Init the current position of all carriages to 0,0,0
  3010. ZERO(current_position);
  3011. sync_plan_position();
  3012. // Move all carriages together linearly until an endstop is hit.
  3013. current_position[X_AXIS] = current_position[Y_AXIS] = current_position[Z_AXIS] = (Z_MAX_LENGTH + 10);
  3014. feedrate_mm_s = homing_feedrate_mm_s[X_AXIS];
  3015. line_to_current_position();
  3016. stepper.synchronize();
  3017. endstops.hit_on_purpose(); // clear endstop hit flags
  3018. // At least one carriage has reached the top.
  3019. // Now re-home each carriage separately.
  3020. HOMEAXIS(A);
  3021. HOMEAXIS(B);
  3022. HOMEAXIS(C);
  3023. // Set all carriages to their home positions
  3024. // Do this here all at once for Delta, because
  3025. // XYZ isn't ABC. Applying this per-tower would
  3026. // give the impression that they are the same.
  3027. LOOP_XYZ(i) set_axis_is_at_home((AxisEnum)i);
  3028. SYNC_PLAN_POSITION_KINEMATIC();
  3029. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3030. if (DEBUGGING(LEVELING)) DEBUG_POS("<<< home_delta", current_position);
  3031. #endif
  3032. }
  3033. #endif // DELTA
  3034. #if ENABLED(Z_SAFE_HOMING)
  3035. inline void home_z_safely() {
  3036. // Disallow Z homing if X or Y are unknown
  3037. if (!axis_known_position[X_AXIS] || !axis_known_position[Y_AXIS]) {
  3038. LCD_MESSAGEPGM(MSG_ERR_Z_HOMING);
  3039. SERIAL_ECHO_START;
  3040. SERIAL_ECHOLNPGM(MSG_ERR_Z_HOMING);
  3041. return;
  3042. }
  3043. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3044. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Z_SAFE_HOMING >>>");
  3045. #endif
  3046. SYNC_PLAN_POSITION_KINEMATIC();
  3047. /**
  3048. * Move the Z probe (or just the nozzle) to the safe homing point
  3049. */
  3050. destination[X_AXIS] = LOGICAL_X_POSITION(Z_SAFE_HOMING_X_POINT);
  3051. destination[Y_AXIS] = LOGICAL_Y_POSITION(Z_SAFE_HOMING_Y_POINT);
  3052. destination[Z_AXIS] = current_position[Z_AXIS]; // Z is already at the right height
  3053. #if HOMING_Z_WITH_PROBE
  3054. destination[X_AXIS] -= X_PROBE_OFFSET_FROM_EXTRUDER;
  3055. destination[Y_AXIS] -= Y_PROBE_OFFSET_FROM_EXTRUDER;
  3056. #endif
  3057. if (position_is_reachable_xy(destination[X_AXIS], destination[Y_AXIS])) {
  3058. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3059. if (DEBUGGING(LEVELING)) DEBUG_POS("Z_SAFE_HOMING", destination);
  3060. #endif
  3061. // This causes the carriage on Dual X to unpark
  3062. #if ENABLED(DUAL_X_CARRIAGE)
  3063. active_extruder_parked = false;
  3064. #endif
  3065. do_blocking_move_to_xy(destination[X_AXIS], destination[Y_AXIS]);
  3066. HOMEAXIS(Z);
  3067. }
  3068. else {
  3069. LCD_MESSAGEPGM(MSG_ZPROBE_OUT);
  3070. SERIAL_ECHO_START;
  3071. SERIAL_ECHOLNPGM(MSG_ZPROBE_OUT);
  3072. }
  3073. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3074. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< Z_SAFE_HOMING");
  3075. #endif
  3076. }
  3077. #endif // Z_SAFE_HOMING
  3078. #if ENABLED(PROBE_MANUALLY)
  3079. bool g29_in_progress = false;
  3080. #else
  3081. constexpr bool g29_in_progress = false;
  3082. #endif
  3083. /**
  3084. * G28: Home all axes according to settings
  3085. *
  3086. * Parameters
  3087. *
  3088. * None Home to all axes with no parameters.
  3089. * With QUICK_HOME enabled XY will home together, then Z.
  3090. *
  3091. * Cartesian parameters
  3092. *
  3093. * X Home to the X endstop
  3094. * Y Home to the Y endstop
  3095. * Z Home to the Z endstop
  3096. *
  3097. */
  3098. inline void gcode_G28(const bool always_home_all) {
  3099. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3100. if (DEBUGGING(LEVELING)) {
  3101. SERIAL_ECHOLNPGM(">>> gcode_G28");
  3102. log_machine_info();
  3103. }
  3104. #endif
  3105. // Wait for planner moves to finish!
  3106. stepper.synchronize();
  3107. // Cancel the active G29 session
  3108. #if ENABLED(PROBE_MANUALLY)
  3109. g29_in_progress = false;
  3110. #endif
  3111. // Disable the leveling matrix before homing
  3112. #if HAS_LEVELING
  3113. #if ENABLED(AUTO_BED_LEVELING_UBL)
  3114. const bool ubl_state_at_entry = leveling_is_active();
  3115. #endif
  3116. set_bed_leveling_enabled(false);
  3117. #endif
  3118. // Always home with tool 0 active
  3119. #if HOTENDS > 1
  3120. const uint8_t old_tool_index = active_extruder;
  3121. tool_change(0, 0, true);
  3122. #endif
  3123. #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(DUAL_NOZZLE_DUPLICATION_MODE)
  3124. extruder_duplication_enabled = false;
  3125. #endif
  3126. setup_for_endstop_or_probe_move();
  3127. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3128. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("> endstops.enable(true)");
  3129. #endif
  3130. endstops.enable(true); // Enable endstops for next homing move
  3131. #if ENABLED(DELTA)
  3132. home_delta();
  3133. #else // NOT DELTA
  3134. const bool homeX = always_home_all || parser.seen('X'),
  3135. homeY = always_home_all || parser.seen('Y'),
  3136. homeZ = always_home_all || parser.seen('Z'),
  3137. home_all = (!homeX && !homeY && !homeZ) || (homeX && homeY && homeZ);
  3138. set_destination_to_current();
  3139. #if Z_HOME_DIR > 0 // If homing away from BED do Z first
  3140. if (home_all || homeZ) {
  3141. HOMEAXIS(Z);
  3142. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3143. if (DEBUGGING(LEVELING)) DEBUG_POS("> HOMEAXIS(Z)", current_position);
  3144. #endif
  3145. }
  3146. #else
  3147. if (home_all || homeX || homeY) {
  3148. // Raise Z before homing any other axes and z is not already high enough (never lower z)
  3149. destination[Z_AXIS] = LOGICAL_Z_POSITION(Z_HOMING_HEIGHT);
  3150. if (destination[Z_AXIS] > current_position[Z_AXIS]) {
  3151. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3152. if (DEBUGGING(LEVELING))
  3153. SERIAL_ECHOLNPAIR("Raise Z (before homing) to ", destination[Z_AXIS]);
  3154. #endif
  3155. do_blocking_move_to_z(destination[Z_AXIS]);
  3156. }
  3157. }
  3158. #endif
  3159. #if ENABLED(QUICK_HOME)
  3160. if (home_all || (homeX && homeY)) quick_home_xy();
  3161. #endif
  3162. #if ENABLED(HOME_Y_BEFORE_X)
  3163. // Home Y
  3164. if (home_all || homeY) {
  3165. HOMEAXIS(Y);
  3166. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3167. if (DEBUGGING(LEVELING)) DEBUG_POS("> homeY", current_position);
  3168. #endif
  3169. }
  3170. #endif
  3171. // Home X
  3172. if (home_all || homeX) {
  3173. #if ENABLED(DUAL_X_CARRIAGE)
  3174. // Always home the 2nd (right) extruder first
  3175. active_extruder = 1;
  3176. HOMEAXIS(X);
  3177. // Remember this extruder's position for later tool change
  3178. inactive_extruder_x_pos = RAW_X_POSITION(current_position[X_AXIS]);
  3179. // Home the 1st (left) extruder
  3180. active_extruder = 0;
  3181. HOMEAXIS(X);
  3182. // Consider the active extruder to be parked
  3183. COPY(raised_parked_position, current_position);
  3184. delayed_move_time = 0;
  3185. active_extruder_parked = true;
  3186. #else
  3187. HOMEAXIS(X);
  3188. #endif
  3189. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3190. if (DEBUGGING(LEVELING)) DEBUG_POS("> homeX", current_position);
  3191. #endif
  3192. }
  3193. #if DISABLED(HOME_Y_BEFORE_X)
  3194. // Home Y
  3195. if (home_all || homeY) {
  3196. HOMEAXIS(Y);
  3197. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3198. if (DEBUGGING(LEVELING)) DEBUG_POS("> homeY", current_position);
  3199. #endif
  3200. }
  3201. #endif
  3202. // Home Z last if homing towards the bed
  3203. #if Z_HOME_DIR < 0
  3204. if (home_all || homeZ) {
  3205. #if ENABLED(Z_SAFE_HOMING)
  3206. home_z_safely();
  3207. #else
  3208. HOMEAXIS(Z);
  3209. #endif
  3210. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3211. if (DEBUGGING(LEVELING)) DEBUG_POS("> (home_all || homeZ) > final", current_position);
  3212. #endif
  3213. } // home_all || homeZ
  3214. #endif // Z_HOME_DIR < 0
  3215. SYNC_PLAN_POSITION_KINEMATIC();
  3216. #endif // !DELTA (gcode_G28)
  3217. endstops.not_homing();
  3218. #if ENABLED(DELTA) && ENABLED(DELTA_HOME_TO_SAFE_ZONE)
  3219. // move to a height where we can use the full xy-area
  3220. do_blocking_move_to_z(delta_clip_start_height);
  3221. #endif
  3222. #if ENABLED(AUTO_BED_LEVELING_UBL)
  3223. set_bed_leveling_enabled(ubl_state_at_entry);
  3224. #endif
  3225. clean_up_after_endstop_or_probe_move();
  3226. // Restore the active tool after homing
  3227. #if HOTENDS > 1
  3228. tool_change(old_tool_index, 0, true);
  3229. #endif
  3230. lcd_refresh();
  3231. report_current_position();
  3232. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3233. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< gcode_G28");
  3234. #endif
  3235. } // G28
  3236. void home_all_axes() { gcode_G28(true); }
  3237. #if HAS_PROBING_PROCEDURE
  3238. void out_of_range_error(const char* p_edge) {
  3239. SERIAL_PROTOCOLPGM("?Probe ");
  3240. serialprintPGM(p_edge);
  3241. SERIAL_PROTOCOLLNPGM(" position out of range.");
  3242. }
  3243. #endif
  3244. #if ENABLED(MESH_BED_LEVELING) || ENABLED(PROBE_MANUALLY)
  3245. #if ENABLED(PROBE_MANUALLY) && ENABLED(LCD_BED_LEVELING)
  3246. extern bool lcd_wait_for_move;
  3247. #endif
  3248. inline void _manual_goto_xy(const float &x, const float &y) {
  3249. const float old_feedrate_mm_s = feedrate_mm_s;
  3250. #if MANUAL_PROBE_HEIGHT > 0
  3251. feedrate_mm_s = homing_feedrate_mm_s[Z_AXIS];
  3252. current_position[Z_AXIS] = LOGICAL_Z_POSITION(Z_MIN_POS) + MANUAL_PROBE_HEIGHT;
  3253. line_to_current_position();
  3254. #endif
  3255. feedrate_mm_s = MMM_TO_MMS(XY_PROBE_SPEED);
  3256. current_position[X_AXIS] = LOGICAL_X_POSITION(x);
  3257. current_position[Y_AXIS] = LOGICAL_Y_POSITION(y);
  3258. line_to_current_position();
  3259. #if MANUAL_PROBE_HEIGHT > 0
  3260. feedrate_mm_s = homing_feedrate_mm_s[Z_AXIS];
  3261. current_position[Z_AXIS] = LOGICAL_Z_POSITION(Z_MIN_POS); // just slightly over the bed
  3262. line_to_current_position();
  3263. #endif
  3264. feedrate_mm_s = old_feedrate_mm_s;
  3265. stepper.synchronize();
  3266. #if ENABLED(PROBE_MANUALLY) && ENABLED(LCD_BED_LEVELING)
  3267. lcd_wait_for_move = false;
  3268. #endif
  3269. }
  3270. #endif
  3271. #if ENABLED(MESH_BED_LEVELING)
  3272. // Save 130 bytes with non-duplication of PSTR
  3273. void echo_not_entered() { SERIAL_PROTOCOLLNPGM(" not entered."); }
  3274. void mbl_mesh_report() {
  3275. SERIAL_PROTOCOLLNPGM("Num X,Y: " STRINGIFY(GRID_MAX_POINTS_X) "," STRINGIFY(GRID_MAX_POINTS_Y));
  3276. SERIAL_PROTOCOLPGM("Z offset: "); SERIAL_PROTOCOL_F(mbl.z_offset, 5);
  3277. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  3278. print_2d_array(GRID_MAX_POINTS_X, GRID_MAX_POINTS_Y, 5,
  3279. [](const uint8_t ix, const uint8_t iy) { return mbl.z_values[ix][iy]; }
  3280. );
  3281. }
  3282. void mesh_probing_done() {
  3283. mbl.set_has_mesh(true);
  3284. home_all_axes();
  3285. set_bed_leveling_enabled(true);
  3286. #if ENABLED(MESH_G28_REST_ORIGIN)
  3287. current_position[Z_AXIS] = LOGICAL_Z_POSITION(Z_MIN_POS);
  3288. set_destination_to_current();
  3289. line_to_destination(homing_feedrate_mm_s[Z_AXIS]);
  3290. stepper.synchronize();
  3291. #endif
  3292. }
  3293. /**
  3294. * G29: Mesh-based Z probe, probes a grid and produces a
  3295. * mesh to compensate for variable bed height
  3296. *
  3297. * Parameters With MESH_BED_LEVELING:
  3298. *
  3299. * S0 Produce a mesh report
  3300. * S1 Start probing mesh points
  3301. * S2 Probe the next mesh point
  3302. * S3 Xn Yn Zn.nn Manually modify a single point
  3303. * S4 Zn.nn Set z offset. Positive away from bed, negative closer to bed.
  3304. * S5 Reset and disable mesh
  3305. *
  3306. * The S0 report the points as below
  3307. *
  3308. * +----> X-axis 1-n
  3309. * |
  3310. * |
  3311. * v Y-axis 1-n
  3312. *
  3313. */
  3314. inline void gcode_G29() {
  3315. static int mbl_probe_index = -1;
  3316. #if HAS_SOFTWARE_ENDSTOPS
  3317. static bool enable_soft_endstops;
  3318. #endif
  3319. const MeshLevelingState state = parser.seen('S') ? (MeshLevelingState)parser.value_byte() : MeshReport;
  3320. if (!WITHIN(state, 0, 5)) {
  3321. SERIAL_PROTOCOLLNPGM("S out of range (0-5).");
  3322. return;
  3323. }
  3324. int8_t px, py;
  3325. switch (state) {
  3326. case MeshReport:
  3327. if (leveling_is_valid()) {
  3328. SERIAL_PROTOCOLLNPAIR("State: ", leveling_is_active() ? MSG_ON : MSG_OFF);
  3329. mbl_mesh_report();
  3330. }
  3331. else
  3332. SERIAL_PROTOCOLLNPGM("Mesh bed leveling has no data.");
  3333. break;
  3334. case MeshStart:
  3335. mbl.reset();
  3336. mbl_probe_index = 0;
  3337. enqueue_and_echo_commands_P(PSTR("G28\nG29 S2"));
  3338. break;
  3339. case MeshNext:
  3340. if (mbl_probe_index < 0) {
  3341. SERIAL_PROTOCOLLNPGM("Start mesh probing with \"G29 S1\" first.");
  3342. return;
  3343. }
  3344. // For each G29 S2...
  3345. if (mbl_probe_index == 0) {
  3346. #if HAS_SOFTWARE_ENDSTOPS
  3347. // For the initial G29 S2 save software endstop state
  3348. enable_soft_endstops = soft_endstops_enabled;
  3349. #endif
  3350. }
  3351. else {
  3352. // For G29 S2 after adjusting Z.
  3353. mbl.set_zigzag_z(mbl_probe_index - 1, current_position[Z_AXIS]);
  3354. #if HAS_SOFTWARE_ENDSTOPS
  3355. soft_endstops_enabled = enable_soft_endstops;
  3356. #endif
  3357. }
  3358. // If there's another point to sample, move there with optional lift.
  3359. if (mbl_probe_index < GRID_MAX_POINTS) {
  3360. mbl.zigzag(mbl_probe_index, px, py);
  3361. _manual_goto_xy(mbl.index_to_xpos[px], mbl.index_to_ypos[py]);
  3362. #if HAS_SOFTWARE_ENDSTOPS
  3363. // Disable software endstops to allow manual adjustment
  3364. // If G29 is not completed, they will not be re-enabled
  3365. soft_endstops_enabled = false;
  3366. #endif
  3367. mbl_probe_index++;
  3368. }
  3369. else {
  3370. // One last "return to the bed" (as originally coded) at completion
  3371. current_position[Z_AXIS] = LOGICAL_Z_POSITION(Z_MIN_POS) + MANUAL_PROBE_HEIGHT;
  3372. line_to_current_position();
  3373. stepper.synchronize();
  3374. // After recording the last point, activate home and activate
  3375. mbl_probe_index = -1;
  3376. SERIAL_PROTOCOLLNPGM("Mesh probing done.");
  3377. BUZZ(100, 659);
  3378. BUZZ(100, 698);
  3379. mesh_probing_done();
  3380. }
  3381. break;
  3382. case MeshSet:
  3383. if (parser.seen('X')) {
  3384. px = parser.value_int() - 1;
  3385. if (!WITHIN(px, 0, GRID_MAX_POINTS_X - 1)) {
  3386. SERIAL_PROTOCOLLNPGM("X out of range (1-" STRINGIFY(GRID_MAX_POINTS_X) ").");
  3387. return;
  3388. }
  3389. }
  3390. else {
  3391. SERIAL_CHAR('X'); echo_not_entered();
  3392. return;
  3393. }
  3394. if (parser.seen('Y')) {
  3395. py = parser.value_int() - 1;
  3396. if (!WITHIN(py, 0, GRID_MAX_POINTS_Y - 1)) {
  3397. SERIAL_PROTOCOLLNPGM("Y out of range (1-" STRINGIFY(GRID_MAX_POINTS_Y) ").");
  3398. return;
  3399. }
  3400. }
  3401. else {
  3402. SERIAL_CHAR('Y'); echo_not_entered();
  3403. return;
  3404. }
  3405. if (parser.seen('Z')) {
  3406. mbl.z_values[px][py] = parser.value_linear_units();
  3407. }
  3408. else {
  3409. SERIAL_CHAR('Z'); echo_not_entered();
  3410. return;
  3411. }
  3412. break;
  3413. case MeshSetZOffset:
  3414. if (parser.seen('Z')) {
  3415. mbl.z_offset = parser.value_linear_units();
  3416. }
  3417. else {
  3418. SERIAL_CHAR('Z'); echo_not_entered();
  3419. return;
  3420. }
  3421. break;
  3422. case MeshReset:
  3423. reset_bed_level();
  3424. break;
  3425. } // switch(state)
  3426. report_current_position();
  3427. }
  3428. #elif HAS_ABL && DISABLED(AUTO_BED_LEVELING_UBL)
  3429. #if ABL_GRID
  3430. #if ENABLED(PROBE_Y_FIRST)
  3431. #define PR_OUTER_VAR xCount
  3432. #define PR_OUTER_END abl_grid_points_x
  3433. #define PR_INNER_VAR yCount
  3434. #define PR_INNER_END abl_grid_points_y
  3435. #else
  3436. #define PR_OUTER_VAR yCount
  3437. #define PR_OUTER_END abl_grid_points_y
  3438. #define PR_INNER_VAR xCount
  3439. #define PR_INNER_END abl_grid_points_x
  3440. #endif
  3441. #endif
  3442. /**
  3443. * G29: Detailed Z probe, probes the bed at 3 or more points.
  3444. * Will fail if the printer has not been homed with G28.
  3445. *
  3446. * Enhanced G29 Auto Bed Leveling Probe Routine
  3447. *
  3448. * D Dry-Run mode. Just evaluate the bed Topology - Don't apply
  3449. * or alter the bed level data. Useful to check the topology
  3450. * after a first run of G29.
  3451. *
  3452. * J Jettison current bed leveling data
  3453. *
  3454. * V Set the verbose level (0-4). Example: "G29 V3"
  3455. *
  3456. * Parameters With LINEAR leveling only:
  3457. *
  3458. * P Set the size of the grid that will be probed (P x P points).
  3459. * Example: "G29 P4"
  3460. *
  3461. * X Set the X size of the grid that will be probed (X x Y points).
  3462. * Example: "G29 X7 Y5"
  3463. *
  3464. * Y Set the Y size of the grid that will be probed (X x Y points).
  3465. *
  3466. * T Generate a Bed Topology Report. Example: "G29 P5 T" for a detailed report.
  3467. * This is useful for manual bed leveling and finding flaws in the bed (to
  3468. * assist with part placement).
  3469. * Not supported by non-linear delta printer bed leveling.
  3470. *
  3471. * Parameters With LINEAR and BILINEAR leveling only:
  3472. *
  3473. * S Set the XY travel speed between probe points (in units/min)
  3474. *
  3475. * F Set the Front limit of the probing grid
  3476. * B Set the Back limit of the probing grid
  3477. * L Set the Left limit of the probing grid
  3478. * R Set the Right limit of the probing grid
  3479. *
  3480. * Parameters with DEBUG_LEVELING_FEATURE only:
  3481. *
  3482. * C Make a totally fake grid with no actual probing.
  3483. * For use in testing when no probing is possible.
  3484. *
  3485. * Parameters with BILINEAR leveling only:
  3486. *
  3487. * Z Supply an additional Z probe offset
  3488. *
  3489. * Extra parameters with PROBE_MANUALLY:
  3490. *
  3491. * To do manual probing simply repeat G29 until the procedure is complete.
  3492. * The first G29 accepts parameters. 'G29 Q' for status, 'G29 A' to abort.
  3493. *
  3494. * Q Query leveling and G29 state
  3495. *
  3496. * A Abort current leveling procedure
  3497. *
  3498. * W Write a mesh point. (Ignored during leveling.)
  3499. * X Required X for mesh point
  3500. * Y Required Y for mesh point
  3501. * Z Required Z for mesh point
  3502. *
  3503. * Without PROBE_MANUALLY:
  3504. *
  3505. * E By default G29 will engage the Z probe, test the bed, then disengage.
  3506. * Include "E" to engage/disengage the Z probe for each sample.
  3507. * There's no extra effect if you have a fixed Z probe.
  3508. *
  3509. */
  3510. inline void gcode_G29() {
  3511. // G29 Q is also available if debugging
  3512. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3513. const bool query = parser.seen('Q');
  3514. const uint8_t old_debug_flags = marlin_debug_flags;
  3515. if (query) marlin_debug_flags |= DEBUG_LEVELING;
  3516. if (DEBUGGING(LEVELING)) {
  3517. DEBUG_POS(">>> gcode_G29", current_position);
  3518. log_machine_info();
  3519. }
  3520. marlin_debug_flags = old_debug_flags;
  3521. #if DISABLED(PROBE_MANUALLY)
  3522. if (query) return;
  3523. #endif
  3524. #endif
  3525. #if ENABLED(DEBUG_LEVELING_FEATURE) && DISABLED(PROBE_MANUALLY)
  3526. const bool faux = parser.seen('C') && parser.value_bool();
  3527. #else
  3528. bool constexpr faux = false;
  3529. #endif
  3530. // Don't allow auto-leveling without homing first
  3531. if (axis_unhomed_error()) return;
  3532. // Define local vars 'static' for manual probing, 'auto' otherwise
  3533. #if ENABLED(PROBE_MANUALLY)
  3534. #define ABL_VAR static
  3535. #else
  3536. #define ABL_VAR
  3537. #endif
  3538. ABL_VAR int verbose_level;
  3539. ABL_VAR float xProbe, yProbe, measured_z;
  3540. ABL_VAR bool dryrun, abl_should_enable;
  3541. #if ENABLED(PROBE_MANUALLY) || ENABLED(AUTO_BED_LEVELING_LINEAR)
  3542. ABL_VAR int abl_probe_index;
  3543. #endif
  3544. #if HAS_SOFTWARE_ENDSTOPS && ENABLED(PROBE_MANUALLY)
  3545. ABL_VAR bool enable_soft_endstops = true;
  3546. #endif
  3547. #if ABL_GRID
  3548. #if ENABLED(PROBE_MANUALLY)
  3549. ABL_VAR uint8_t PR_OUTER_VAR;
  3550. ABL_VAR int8_t PR_INNER_VAR;
  3551. #endif
  3552. ABL_VAR int left_probe_bed_position, right_probe_bed_position, front_probe_bed_position, back_probe_bed_position;
  3553. ABL_VAR float xGridSpacing, yGridSpacing;
  3554. #if ABL_PLANAR
  3555. ABL_VAR uint8_t abl_grid_points_x = GRID_MAX_POINTS_X,
  3556. abl_grid_points_y = GRID_MAX_POINTS_Y;
  3557. ABL_VAR bool do_topography_map;
  3558. #else // 3-point
  3559. uint8_t constexpr abl_grid_points_x = GRID_MAX_POINTS_X,
  3560. abl_grid_points_y = GRID_MAX_POINTS_Y;
  3561. #endif
  3562. #if ENABLED(AUTO_BED_LEVELING_LINEAR) || ENABLED(PROBE_MANUALLY)
  3563. #if ABL_PLANAR
  3564. ABL_VAR int abl2;
  3565. #else // 3-point
  3566. int constexpr abl2 = GRID_MAX_POINTS;
  3567. #endif
  3568. #endif
  3569. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3570. ABL_VAR float zoffset;
  3571. #elif ENABLED(AUTO_BED_LEVELING_LINEAR)
  3572. ABL_VAR int indexIntoAB[GRID_MAX_POINTS_X][GRID_MAX_POINTS_Y];
  3573. ABL_VAR float eqnAMatrix[GRID_MAX_POINTS * 3], // "A" matrix of the linear system of equations
  3574. eqnBVector[GRID_MAX_POINTS], // "B" vector of Z points
  3575. mean;
  3576. #endif
  3577. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  3578. // Probe at 3 arbitrary points
  3579. ABL_VAR vector_3 points[3] = {
  3580. vector_3(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, 0),
  3581. vector_3(ABL_PROBE_PT_2_X, ABL_PROBE_PT_2_Y, 0),
  3582. vector_3(ABL_PROBE_PT_3_X, ABL_PROBE_PT_3_Y, 0)
  3583. };
  3584. #endif // AUTO_BED_LEVELING_3POINT
  3585. /**
  3586. * On the initial G29 fetch command parameters.
  3587. */
  3588. if (!g29_in_progress) {
  3589. #if ENABLED(PROBE_MANUALLY) || ENABLED(AUTO_BED_LEVELING_LINEAR)
  3590. abl_probe_index = -1;
  3591. #endif
  3592. abl_should_enable = leveling_is_active();
  3593. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3594. if (parser.seen('W')) {
  3595. if (!leveling_is_valid()) {
  3596. SERIAL_ERROR_START;
  3597. SERIAL_ERRORLNPGM("No bilinear grid");
  3598. return;
  3599. }
  3600. const float z = parser.seen('Z') && parser.has_value() ? parser.value_float() : 99999;
  3601. if (!WITHIN(z, -10, 10)) {
  3602. SERIAL_ERROR_START;
  3603. SERIAL_ERRORLNPGM("Bad Z value");
  3604. return;
  3605. }
  3606. const float x = parser.seen('X') && parser.has_value() ? parser.value_float() : 99999,
  3607. y = parser.seen('Y') && parser.has_value() ? parser.value_float() : 99999;
  3608. int8_t i = parser.seen('I') && parser.has_value() ? parser.value_byte() : -1,
  3609. j = parser.seen('J') && parser.has_value() ? parser.value_byte() : -1;
  3610. if (x < 99998 && y < 99998) {
  3611. // Get nearest i / j from x / y
  3612. i = (x - LOGICAL_X_POSITION(bilinear_start[X_AXIS]) + 0.5 * xGridSpacing) / xGridSpacing;
  3613. j = (y - LOGICAL_Y_POSITION(bilinear_start[Y_AXIS]) + 0.5 * yGridSpacing) / yGridSpacing;
  3614. i = constrain(i, 0, GRID_MAX_POINTS_X - 1);
  3615. j = constrain(j, 0, GRID_MAX_POINTS_Y - 1);
  3616. }
  3617. if (WITHIN(i, 0, GRID_MAX_POINTS_X - 1) && WITHIN(j, 0, GRID_MAX_POINTS_Y)) {
  3618. set_bed_leveling_enabled(false);
  3619. z_values[i][j] = z;
  3620. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  3621. bed_level_virt_interpolate();
  3622. #endif
  3623. set_bed_leveling_enabled(abl_should_enable);
  3624. }
  3625. return;
  3626. } // parser.seen('W')
  3627. #endif
  3628. #if HAS_LEVELING
  3629. // Jettison bed leveling data
  3630. if (parser.seen('J')) {
  3631. reset_bed_level();
  3632. return;
  3633. }
  3634. #endif
  3635. verbose_level = parser.seen('V') && parser.has_value() ? parser.value_int() : 0;
  3636. if (!WITHIN(verbose_level, 0, 4)) {
  3637. SERIAL_PROTOCOLLNPGM("?(V)erbose level is implausible (0-4).");
  3638. return;
  3639. }
  3640. dryrun = parser.seen('D') && parser.value_bool();
  3641. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  3642. do_topography_map = verbose_level > 2 || parser.seen('T');
  3643. // X and Y specify points in each direction, overriding the default
  3644. // These values may be saved with the completed mesh
  3645. abl_grid_points_x = parser.seen('X') ? parser.value_int() : GRID_MAX_POINTS_X;
  3646. abl_grid_points_y = parser.seen('Y') ? parser.value_int() : GRID_MAX_POINTS_Y;
  3647. if (parser.seen('P')) abl_grid_points_x = abl_grid_points_y = parser.value_int();
  3648. if (abl_grid_points_x < 2 || abl_grid_points_y < 2) {
  3649. SERIAL_PROTOCOLLNPGM("?Number of probe points is implausible (2 minimum).");
  3650. return;
  3651. }
  3652. abl2 = abl_grid_points_x * abl_grid_points_y;
  3653. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3654. zoffset = parser.seen('Z') ? parser.value_linear_units() : 0;
  3655. #endif
  3656. #if ABL_GRID
  3657. xy_probe_feedrate_mm_s = MMM_TO_MMS(parser.seen('S') ? parser.value_linear_units() : XY_PROBE_SPEED);
  3658. left_probe_bed_position = parser.seen('L') ? (int)parser.value_linear_units() : LOGICAL_X_POSITION(LEFT_PROBE_BED_POSITION);
  3659. right_probe_bed_position = parser.seen('R') ? (int)parser.value_linear_units() : LOGICAL_X_POSITION(RIGHT_PROBE_BED_POSITION);
  3660. front_probe_bed_position = parser.seen('F') ? (int)parser.value_linear_units() : LOGICAL_Y_POSITION(FRONT_PROBE_BED_POSITION);
  3661. back_probe_bed_position = parser.seen('B') ? (int)parser.value_linear_units() : LOGICAL_Y_POSITION(BACK_PROBE_BED_POSITION);
  3662. const bool left_out_l = left_probe_bed_position < LOGICAL_X_POSITION(MIN_PROBE_X),
  3663. left_out = left_out_l || left_probe_bed_position > right_probe_bed_position - (MIN_PROBE_EDGE),
  3664. right_out_r = right_probe_bed_position > LOGICAL_X_POSITION(MAX_PROBE_X),
  3665. right_out = right_out_r || right_probe_bed_position < left_probe_bed_position + MIN_PROBE_EDGE,
  3666. front_out_f = front_probe_bed_position < LOGICAL_Y_POSITION(MIN_PROBE_Y),
  3667. front_out = front_out_f || front_probe_bed_position > back_probe_bed_position - (MIN_PROBE_EDGE),
  3668. back_out_b = back_probe_bed_position > LOGICAL_Y_POSITION(MAX_PROBE_Y),
  3669. back_out = back_out_b || back_probe_bed_position < front_probe_bed_position + MIN_PROBE_EDGE;
  3670. if (left_out || right_out || front_out || back_out) {
  3671. if (left_out) {
  3672. out_of_range_error(PSTR("(L)eft"));
  3673. left_probe_bed_position = left_out_l ? LOGICAL_X_POSITION(MIN_PROBE_X) : right_probe_bed_position - (MIN_PROBE_EDGE);
  3674. }
  3675. if (right_out) {
  3676. out_of_range_error(PSTR("(R)ight"));
  3677. right_probe_bed_position = right_out_r ? LOGICAL_Y_POSITION(MAX_PROBE_X) : left_probe_bed_position + MIN_PROBE_EDGE;
  3678. }
  3679. if (front_out) {
  3680. out_of_range_error(PSTR("(F)ront"));
  3681. front_probe_bed_position = front_out_f ? LOGICAL_Y_POSITION(MIN_PROBE_Y) : back_probe_bed_position - (MIN_PROBE_EDGE);
  3682. }
  3683. if (back_out) {
  3684. out_of_range_error(PSTR("(B)ack"));
  3685. back_probe_bed_position = back_out_b ? LOGICAL_Y_POSITION(MAX_PROBE_Y) : front_probe_bed_position + MIN_PROBE_EDGE;
  3686. }
  3687. return;
  3688. }
  3689. // probe at the points of a lattice grid
  3690. xGridSpacing = (right_probe_bed_position - left_probe_bed_position) / (abl_grid_points_x - 1);
  3691. yGridSpacing = (back_probe_bed_position - front_probe_bed_position) / (abl_grid_points_y - 1);
  3692. #endif // ABL_GRID
  3693. if (verbose_level > 0) {
  3694. SERIAL_PROTOCOLLNPGM("G29 Auto Bed Leveling");
  3695. if (dryrun) SERIAL_PROTOCOLLNPGM("Running in DRY-RUN mode");
  3696. }
  3697. stepper.synchronize();
  3698. // Disable auto bed leveling during G29
  3699. planner.abl_enabled = false;
  3700. if (!dryrun) {
  3701. // Re-orient the current position without leveling
  3702. // based on where the steppers are positioned.
  3703. set_current_from_steppers_for_axis(ALL_AXES);
  3704. // Sync the planner to where the steppers stopped
  3705. SYNC_PLAN_POSITION_KINEMATIC();
  3706. }
  3707. if (!faux) setup_for_endstop_or_probe_move();
  3708. //xProbe = yProbe = measured_z = 0;
  3709. #if HAS_BED_PROBE
  3710. // Deploy the probe. Probe will raise if needed.
  3711. if (DEPLOY_PROBE()) {
  3712. planner.abl_enabled = abl_should_enable;
  3713. return;
  3714. }
  3715. #endif
  3716. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3717. if ( xGridSpacing != bilinear_grid_spacing[X_AXIS]
  3718. || yGridSpacing != bilinear_grid_spacing[Y_AXIS]
  3719. || left_probe_bed_position != LOGICAL_X_POSITION(bilinear_start[X_AXIS])
  3720. || front_probe_bed_position != LOGICAL_Y_POSITION(bilinear_start[Y_AXIS])
  3721. ) {
  3722. if (dryrun) {
  3723. // Before reset bed level, re-enable to correct the position
  3724. planner.abl_enabled = abl_should_enable;
  3725. }
  3726. // Reset grid to 0.0 or "not probed". (Also disables ABL)
  3727. reset_bed_level();
  3728. // Initialize a grid with the given dimensions
  3729. bilinear_grid_spacing[X_AXIS] = xGridSpacing;
  3730. bilinear_grid_spacing[Y_AXIS] = yGridSpacing;
  3731. bilinear_start[X_AXIS] = RAW_X_POSITION(left_probe_bed_position);
  3732. bilinear_start[Y_AXIS] = RAW_Y_POSITION(front_probe_bed_position);
  3733. // Can't re-enable (on error) until the new grid is written
  3734. abl_should_enable = false;
  3735. }
  3736. #elif ENABLED(AUTO_BED_LEVELING_LINEAR)
  3737. mean = 0.0;
  3738. #endif // AUTO_BED_LEVELING_LINEAR
  3739. #if ENABLED(AUTO_BED_LEVELING_3POINT)
  3740. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3741. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("> 3-point Leveling");
  3742. #endif
  3743. // Probe at 3 arbitrary points
  3744. points[0].z = points[1].z = points[2].z = 0;
  3745. #endif // AUTO_BED_LEVELING_3POINT
  3746. } // !g29_in_progress
  3747. #if ENABLED(PROBE_MANUALLY)
  3748. const bool seenA = parser.seen('A'), seenQ = parser.seen('Q');
  3749. // For manual probing, get the next index to probe now.
  3750. // On the first probe this will be incremented to 0.
  3751. if (!seenA && !seenQ) {
  3752. ++abl_probe_index;
  3753. g29_in_progress = true;
  3754. }
  3755. // Abort current G29 procedure, go back to ABLStart
  3756. if (seenA && g29_in_progress) {
  3757. SERIAL_PROTOCOLLNPGM("Manual G29 aborted");
  3758. #if HAS_SOFTWARE_ENDSTOPS
  3759. soft_endstops_enabled = enable_soft_endstops;
  3760. #endif
  3761. planner.abl_enabled = abl_should_enable;
  3762. g29_in_progress = false;
  3763. #if ENABLED(LCD_BED_LEVELING)
  3764. lcd_wait_for_move = false;
  3765. #endif
  3766. }
  3767. // Query G29 status
  3768. if (verbose_level || seenQ) {
  3769. SERIAL_PROTOCOLPGM("Manual G29 ");
  3770. if (g29_in_progress) {
  3771. SERIAL_PROTOCOLPAIR("point ", abl_probe_index + 1);
  3772. SERIAL_PROTOCOLLNPAIR(" of ", abl2);
  3773. }
  3774. else
  3775. SERIAL_PROTOCOLLNPGM("idle");
  3776. }
  3777. if (seenA || seenQ) return;
  3778. if (abl_probe_index == 0) {
  3779. // For the initial G29 save software endstop state
  3780. #if HAS_SOFTWARE_ENDSTOPS
  3781. enable_soft_endstops = soft_endstops_enabled;
  3782. #endif
  3783. }
  3784. else {
  3785. // For G29 after adjusting Z.
  3786. // Save the previous Z before going to the next point
  3787. measured_z = current_position[Z_AXIS];
  3788. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  3789. mean += measured_z;
  3790. eqnBVector[abl_probe_index] = measured_z;
  3791. eqnAMatrix[abl_probe_index + 0 * abl2] = xProbe;
  3792. eqnAMatrix[abl_probe_index + 1 * abl2] = yProbe;
  3793. eqnAMatrix[abl_probe_index + 2 * abl2] = 1;
  3794. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3795. z_values[xCount][yCount] = measured_z + zoffset;
  3796. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  3797. points[i].z = measured_z;
  3798. #endif
  3799. }
  3800. //
  3801. // If there's another point to sample, move there with optional lift.
  3802. //
  3803. #if ABL_GRID
  3804. // Skip any unreachable points
  3805. while (abl_probe_index < abl2) {
  3806. // Set xCount, yCount based on abl_probe_index, with zig-zag
  3807. PR_OUTER_VAR = abl_probe_index / PR_INNER_END;
  3808. PR_INNER_VAR = abl_probe_index - (PR_OUTER_VAR * PR_INNER_END);
  3809. // Probe in reverse order for every other row/column
  3810. bool zig = (PR_OUTER_VAR & 1); // != ((PR_OUTER_END) & 1);
  3811. if (zig) PR_INNER_VAR = (PR_INNER_END - 1) - PR_INNER_VAR;
  3812. const float xBase = xCount * xGridSpacing + left_probe_bed_position,
  3813. yBase = yCount * yGridSpacing + front_probe_bed_position;
  3814. xProbe = floor(xBase + (xBase < 0 ? 0 : 0.5));
  3815. yProbe = floor(yBase + (yBase < 0 ? 0 : 0.5));
  3816. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  3817. indexIntoAB[xCount][yCount] = abl_probe_index;
  3818. #endif
  3819. // Keep looping till a reachable point is found
  3820. if (position_is_reachable_xy(xProbe, yProbe)) break;
  3821. ++abl_probe_index;
  3822. }
  3823. // Is there a next point to move to?
  3824. if (abl_probe_index < abl2) {
  3825. _manual_goto_xy(xProbe, yProbe); // Can be used here too!
  3826. #if HAS_SOFTWARE_ENDSTOPS
  3827. // Disable software endstops to allow manual adjustment
  3828. // If G29 is not completed, they will not be re-enabled
  3829. soft_endstops_enabled = false;
  3830. #endif
  3831. return;
  3832. }
  3833. else {
  3834. // Leveling done! Fall through to G29 finishing code below
  3835. SERIAL_PROTOCOLLNPGM("Grid probing done.");
  3836. // Re-enable software endstops, if needed
  3837. #if HAS_SOFTWARE_ENDSTOPS
  3838. soft_endstops_enabled = enable_soft_endstops;
  3839. #endif
  3840. }
  3841. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  3842. // Probe at 3 arbitrary points
  3843. if (abl_probe_index < 3) {
  3844. xProbe = LOGICAL_X_POSITION(points[abl_probe_index].x);
  3845. yProbe = LOGICAL_Y_POSITION(points[abl_probe_index].y);
  3846. #if HAS_SOFTWARE_ENDSTOPS
  3847. // Disable software endstops to allow manual adjustment
  3848. // If G29 is not completed, they will not be re-enabled
  3849. soft_endstops_enabled = false;
  3850. #endif
  3851. return;
  3852. }
  3853. else {
  3854. SERIAL_PROTOCOLLNPGM("3-point probing done.");
  3855. // Re-enable software endstops, if needed
  3856. #if HAS_SOFTWARE_ENDSTOPS
  3857. soft_endstops_enabled = enable_soft_endstops;
  3858. #endif
  3859. if (!dryrun) {
  3860. vector_3 planeNormal = vector_3::cross(points[0] - points[1], points[2] - points[1]).get_normal();
  3861. if (planeNormal.z < 0) {
  3862. planeNormal.x *= -1;
  3863. planeNormal.y *= -1;
  3864. planeNormal.z *= -1;
  3865. }
  3866. planner.bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  3867. // Can't re-enable (on error) until the new grid is written
  3868. abl_should_enable = false;
  3869. }
  3870. }
  3871. #endif // AUTO_BED_LEVELING_3POINT
  3872. #else // !PROBE_MANUALLY
  3873. const bool stow_probe_after_each = parser.seen('E');
  3874. #if ABL_GRID
  3875. bool zig = PR_OUTER_END & 1; // Always end at RIGHT and BACK_PROBE_BED_POSITION
  3876. // Outer loop is Y with PROBE_Y_FIRST disabled
  3877. for (uint8_t PR_OUTER_VAR = 0; PR_OUTER_VAR < PR_OUTER_END; PR_OUTER_VAR++) {
  3878. int8_t inStart, inStop, inInc;
  3879. if (zig) { // away from origin
  3880. inStart = 0;
  3881. inStop = PR_INNER_END;
  3882. inInc = 1;
  3883. }
  3884. else { // towards origin
  3885. inStart = PR_INNER_END - 1;
  3886. inStop = -1;
  3887. inInc = -1;
  3888. }
  3889. zig ^= true; // zag
  3890. // Inner loop is Y with PROBE_Y_FIRST enabled
  3891. for (int8_t PR_INNER_VAR = inStart; PR_INNER_VAR != inStop; PR_INNER_VAR += inInc) {
  3892. float xBase = left_probe_bed_position + xGridSpacing * xCount,
  3893. yBase = front_probe_bed_position + yGridSpacing * yCount;
  3894. xProbe = floor(xBase + (xBase < 0 ? 0 : 0.5));
  3895. yProbe = floor(yBase + (yBase < 0 ? 0 : 0.5));
  3896. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  3897. indexIntoAB[xCount][yCount] = ++abl_probe_index; // 0...
  3898. #endif
  3899. #if IS_KINEMATIC
  3900. // Avoid probing outside the round or hexagonal area
  3901. if (!position_is_reachable_by_probe_xy(xProbe, yProbe)) continue;
  3902. #endif
  3903. measured_z = faux ? 0.001 * random(-100, 101) : probe_pt(xProbe, yProbe, stow_probe_after_each, verbose_level);
  3904. if (isnan(measured_z)) {
  3905. planner.abl_enabled = abl_should_enable;
  3906. return;
  3907. }
  3908. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  3909. mean += measured_z;
  3910. eqnBVector[abl_probe_index] = measured_z;
  3911. eqnAMatrix[abl_probe_index + 0 * abl2] = xProbe;
  3912. eqnAMatrix[abl_probe_index + 1 * abl2] = yProbe;
  3913. eqnAMatrix[abl_probe_index + 2 * abl2] = 1;
  3914. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3915. z_values[xCount][yCount] = measured_z + zoffset;
  3916. #endif
  3917. abl_should_enable = false;
  3918. idle();
  3919. } // inner
  3920. } // outer
  3921. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  3922. // Probe at 3 arbitrary points
  3923. for (uint8_t i = 0; i < 3; ++i) {
  3924. // Retain the last probe position
  3925. xProbe = LOGICAL_X_POSITION(points[i].x);
  3926. yProbe = LOGICAL_Y_POSITION(points[i].y);
  3927. measured_z = faux ? 0.001 * random(-100, 101) : probe_pt(xProbe, yProbe, stow_probe_after_each, verbose_level);
  3928. if (isnan(measured_z)) {
  3929. planner.abl_enabled = abl_should_enable;
  3930. return;
  3931. }
  3932. points[i].z = measured_z;
  3933. }
  3934. if (!dryrun) {
  3935. vector_3 planeNormal = vector_3::cross(points[0] - points[1], points[2] - points[1]).get_normal();
  3936. if (planeNormal.z < 0) {
  3937. planeNormal.x *= -1;
  3938. planeNormal.y *= -1;
  3939. planeNormal.z *= -1;
  3940. }
  3941. planner.bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  3942. // Can't re-enable (on error) until the new grid is written
  3943. abl_should_enable = false;
  3944. }
  3945. #endif // AUTO_BED_LEVELING_3POINT
  3946. // Raise to _Z_CLEARANCE_DEPLOY_PROBE. Stow the probe.
  3947. if (STOW_PROBE()) {
  3948. planner.abl_enabled = abl_should_enable;
  3949. return;
  3950. }
  3951. #endif // !PROBE_MANUALLY
  3952. //
  3953. // G29 Finishing Code
  3954. //
  3955. // Unless this is a dry run, auto bed leveling will
  3956. // definitely be enabled after this point.
  3957. //
  3958. // If code above wants to continue leveling, it should
  3959. // return or loop before this point.
  3960. //
  3961. // Restore state after probing
  3962. if (!faux) clean_up_after_endstop_or_probe_move();
  3963. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3964. if (DEBUGGING(LEVELING)) DEBUG_POS("> probing complete", current_position);
  3965. #endif
  3966. #if ENABLED(PROBE_MANUALLY)
  3967. g29_in_progress = false;
  3968. #if ENABLED(LCD_BED_LEVELING)
  3969. lcd_wait_for_move = false;
  3970. #endif
  3971. #endif
  3972. // Calculate leveling, print reports, correct the position
  3973. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3974. if (!dryrun) extrapolate_unprobed_bed_level();
  3975. print_bilinear_leveling_grid();
  3976. refresh_bed_level();
  3977. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  3978. bed_level_virt_print();
  3979. #endif
  3980. #elif ENABLED(AUTO_BED_LEVELING_LINEAR)
  3981. // For LINEAR leveling calculate matrix, print reports, correct the position
  3982. /**
  3983. * solve the plane equation ax + by + d = z
  3984. * A is the matrix with rows [x y 1] for all the probed points
  3985. * B is the vector of the Z positions
  3986. * the normal vector to the plane is formed by the coefficients of the
  3987. * plane equation in the standard form, which is Vx*x+Vy*y+Vz*z+d = 0
  3988. * so Vx = -a Vy = -b Vz = 1 (we want the vector facing towards positive Z
  3989. */
  3990. float plane_equation_coefficients[3];
  3991. qr_solve(plane_equation_coefficients, abl2, 3, eqnAMatrix, eqnBVector);
  3992. mean /= abl2;
  3993. if (verbose_level) {
  3994. SERIAL_PROTOCOLPGM("Eqn coefficients: a: ");
  3995. SERIAL_PROTOCOL_F(plane_equation_coefficients[0], 8);
  3996. SERIAL_PROTOCOLPGM(" b: ");
  3997. SERIAL_PROTOCOL_F(plane_equation_coefficients[1], 8);
  3998. SERIAL_PROTOCOLPGM(" d: ");
  3999. SERIAL_PROTOCOL_F(plane_equation_coefficients[2], 8);
  4000. SERIAL_EOL;
  4001. if (verbose_level > 2) {
  4002. SERIAL_PROTOCOLPGM("Mean of sampled points: ");
  4003. SERIAL_PROTOCOL_F(mean, 8);
  4004. SERIAL_EOL;
  4005. }
  4006. }
  4007. // Create the matrix but don't correct the position yet
  4008. if (!dryrun) {
  4009. planner.bed_level_matrix = matrix_3x3::create_look_at(
  4010. vector_3(-plane_equation_coefficients[0], -plane_equation_coefficients[1], 1)
  4011. );
  4012. }
  4013. // Show the Topography map if enabled
  4014. if (do_topography_map) {
  4015. SERIAL_PROTOCOLLNPGM("\nBed Height Topography:\n"
  4016. " +--- BACK --+\n"
  4017. " | |\n"
  4018. " L | (+) | R\n"
  4019. " E | | I\n"
  4020. " F | (-) N (+) | G\n"
  4021. " T | | H\n"
  4022. " | (-) | T\n"
  4023. " | |\n"
  4024. " O-- FRONT --+\n"
  4025. " (0,0)");
  4026. float min_diff = 999;
  4027. for (int8_t yy = abl_grid_points_y - 1; yy >= 0; yy--) {
  4028. for (uint8_t xx = 0; xx < abl_grid_points_x; xx++) {
  4029. int ind = indexIntoAB[xx][yy];
  4030. float diff = eqnBVector[ind] - mean,
  4031. x_tmp = eqnAMatrix[ind + 0 * abl2],
  4032. y_tmp = eqnAMatrix[ind + 1 * abl2],
  4033. z_tmp = 0;
  4034. apply_rotation_xyz(planner.bed_level_matrix, x_tmp, y_tmp, z_tmp);
  4035. NOMORE(min_diff, eqnBVector[ind] - z_tmp);
  4036. if (diff >= 0.0)
  4037. SERIAL_PROTOCOLPGM(" +"); // Include + for column alignment
  4038. else
  4039. SERIAL_PROTOCOLCHAR(' ');
  4040. SERIAL_PROTOCOL_F(diff, 5);
  4041. } // xx
  4042. SERIAL_EOL;
  4043. } // yy
  4044. SERIAL_EOL;
  4045. if (verbose_level > 3) {
  4046. SERIAL_PROTOCOLLNPGM("\nCorrected Bed Height vs. Bed Topology:");
  4047. for (int8_t yy = abl_grid_points_y - 1; yy >= 0; yy--) {
  4048. for (uint8_t xx = 0; xx < abl_grid_points_x; xx++) {
  4049. int ind = indexIntoAB[xx][yy];
  4050. float x_tmp = eqnAMatrix[ind + 0 * abl2],
  4051. y_tmp = eqnAMatrix[ind + 1 * abl2],
  4052. z_tmp = 0;
  4053. apply_rotation_xyz(planner.bed_level_matrix, x_tmp, y_tmp, z_tmp);
  4054. float diff = eqnBVector[ind] - z_tmp - min_diff;
  4055. if (diff >= 0.0)
  4056. SERIAL_PROTOCOLPGM(" +");
  4057. // Include + for column alignment
  4058. else
  4059. SERIAL_PROTOCOLCHAR(' ');
  4060. SERIAL_PROTOCOL_F(diff, 5);
  4061. } // xx
  4062. SERIAL_EOL;
  4063. } // yy
  4064. SERIAL_EOL;
  4065. }
  4066. } //do_topography_map
  4067. #endif // AUTO_BED_LEVELING_LINEAR
  4068. #if ABL_PLANAR
  4069. // For LINEAR and 3POINT leveling correct the current position
  4070. if (verbose_level > 0)
  4071. planner.bed_level_matrix.debug(PSTR("\n\nBed Level Correction Matrix:"));
  4072. if (!dryrun) {
  4073. //
  4074. // Correct the current XYZ position based on the tilted plane.
  4075. //
  4076. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4077. if (DEBUGGING(LEVELING)) DEBUG_POS("G29 uncorrected XYZ", current_position);
  4078. #endif
  4079. float converted[XYZ];
  4080. COPY(converted, current_position);
  4081. planner.abl_enabled = true;
  4082. planner.unapply_leveling(converted); // use conversion machinery
  4083. planner.abl_enabled = false;
  4084. // Use the last measured distance to the bed, if possible
  4085. if ( NEAR(current_position[X_AXIS], xProbe - (X_PROBE_OFFSET_FROM_EXTRUDER))
  4086. && NEAR(current_position[Y_AXIS], yProbe - (Y_PROBE_OFFSET_FROM_EXTRUDER))
  4087. ) {
  4088. float simple_z = current_position[Z_AXIS] - measured_z;
  4089. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4090. if (DEBUGGING(LEVELING)) {
  4091. SERIAL_ECHOPAIR("Z from Probe:", simple_z);
  4092. SERIAL_ECHOPAIR(" Matrix:", converted[Z_AXIS]);
  4093. SERIAL_ECHOLNPAIR(" Discrepancy:", simple_z - converted[Z_AXIS]);
  4094. }
  4095. #endif
  4096. converted[Z_AXIS] = simple_z;
  4097. }
  4098. // The rotated XY and corrected Z are now current_position
  4099. COPY(current_position, converted);
  4100. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4101. if (DEBUGGING(LEVELING)) DEBUG_POS("G29 corrected XYZ", current_position);
  4102. #endif
  4103. }
  4104. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  4105. if (!dryrun) {
  4106. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4107. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR("G29 uncorrected Z:", current_position[Z_AXIS]);
  4108. #endif
  4109. // Unapply the offset because it is going to be immediately applied
  4110. // and cause compensation movement in Z
  4111. current_position[Z_AXIS] -= bilinear_z_offset(current_position);
  4112. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4113. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR(" corrected Z:", current_position[Z_AXIS]);
  4114. #endif
  4115. }
  4116. #endif // ABL_PLANAR
  4117. #ifdef Z_PROBE_END_SCRIPT
  4118. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4119. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR("Z Probe End Script: ", Z_PROBE_END_SCRIPT);
  4120. #endif
  4121. enqueue_and_echo_commands_P(PSTR(Z_PROBE_END_SCRIPT));
  4122. stepper.synchronize();
  4123. #endif
  4124. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4125. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< gcode_G29");
  4126. #endif
  4127. report_current_position();
  4128. KEEPALIVE_STATE(IN_HANDLER);
  4129. // Auto Bed Leveling is complete! Enable if possible.
  4130. planner.abl_enabled = dryrun ? abl_should_enable : true;
  4131. if (planner.abl_enabled)
  4132. SYNC_PLAN_POSITION_KINEMATIC();
  4133. }
  4134. #endif // HAS_ABL && !AUTO_BED_LEVELING_UBL
  4135. #if HAS_BED_PROBE
  4136. /**
  4137. * G30: Do a single Z probe at the current XY
  4138. *
  4139. * Parameters:
  4140. *
  4141. * X Probe X position (default current X)
  4142. * Y Probe Y position (default current Y)
  4143. * S0 Leave the probe deployed
  4144. */
  4145. inline void gcode_G30() {
  4146. const float xpos = parser.seen('X') ? parser.value_linear_units() : current_position[X_AXIS] + X_PROBE_OFFSET_FROM_EXTRUDER,
  4147. ypos = parser.seen('Y') ? parser.value_linear_units() : current_position[Y_AXIS] + Y_PROBE_OFFSET_FROM_EXTRUDER;
  4148. if (!position_is_reachable_by_probe_xy(xpos, ypos)) return;
  4149. // Disable leveling so the planner won't mess with us
  4150. #if HAS_LEVELING
  4151. set_bed_leveling_enabled(false);
  4152. #endif
  4153. setup_for_endstop_or_probe_move();
  4154. const float measured_z = probe_pt(xpos, ypos, !parser.seen('S') || parser.value_bool(), 1);
  4155. if (!isnan(measured_z)) {
  4156. SERIAL_PROTOCOLPAIR("Bed X: ", FIXFLOAT(xpos));
  4157. SERIAL_PROTOCOLPAIR(" Y: ", FIXFLOAT(ypos));
  4158. SERIAL_PROTOCOLLNPAIR(" Z: ", FIXFLOAT(measured_z));
  4159. }
  4160. clean_up_after_endstop_or_probe_move();
  4161. report_current_position();
  4162. }
  4163. #if ENABLED(Z_PROBE_SLED)
  4164. /**
  4165. * G31: Deploy the Z probe
  4166. */
  4167. inline void gcode_G31() { DEPLOY_PROBE(); }
  4168. /**
  4169. * G32: Stow the Z probe
  4170. */
  4171. inline void gcode_G32() { STOW_PROBE(); }
  4172. #endif // Z_PROBE_SLED
  4173. #if ENABLED(DELTA_AUTO_CALIBRATION)
  4174. /**
  4175. * G33 - Delta '1-4-7-point' Auto-Calibration
  4176. * Calibrate height, endstops, delta radius, and tower angles.
  4177. *
  4178. * Parameters:
  4179. *
  4180. * Pn Number of probe points:
  4181. *
  4182. * P1 Probe center and set height only.
  4183. * P2 Probe center and towers. Set height, endstops, and delta radius.
  4184. * P3 Probe all positions: center, towers and opposite towers. Set all.
  4185. * P4-P7 Probe all positions at different locations and average them.
  4186. *
  4187. * T Don't calibrate tower angle corrections
  4188. *
  4189. * Cn.nn Calibration precision; when omitted calibrates to maximum precision
  4190. *
  4191. * Vn Verbose level:
  4192. *
  4193. * V0 Dry-run mode. Report settings and probe results. No calibration.
  4194. * V1 Report settings
  4195. * V2 Report settings and probe results
  4196. */
  4197. inline void gcode_G33() {
  4198. const int8_t probe_points = parser.seen('P') ? parser.value_int() : DELTA_CALIBRATION_DEFAULT_POINTS;
  4199. if (!WITHIN(probe_points, 1, 7)) {
  4200. SERIAL_PROTOCOLLNPGM("?(P)oints is implausible (1 to 7).");
  4201. return;
  4202. }
  4203. const int8_t verbose_level = parser.seen('V') ? parser.value_byte() : 1;
  4204. if (!WITHIN(verbose_level, 0, 2)) {
  4205. SERIAL_PROTOCOLLNPGM("?(V)erbose level is implausible (0-2).");
  4206. return;
  4207. }
  4208. const float calibration_precision = parser.seen('C') ? parser.value_float() : 0.0;
  4209. if (calibration_precision < 0) {
  4210. SERIAL_PROTOCOLLNPGM("?(C)alibration precision is implausible (>0).");
  4211. return;
  4212. }
  4213. const bool towers_set = !parser.seen('T'),
  4214. _1p_calibration = probe_points == 1,
  4215. _4p_calibration = probe_points == 2,
  4216. _4p_towers_points = _4p_calibration && towers_set,
  4217. _4p_opposite_points = _4p_calibration && !towers_set,
  4218. _7p_calibration = probe_points >= 3,
  4219. _7p_half_circle = probe_points == 3,
  4220. _7p_double_circle = probe_points == 5,
  4221. _7p_triple_circle = probe_points == 6,
  4222. _7p_quadruple_circle = probe_points == 7,
  4223. _7p_multi_circle = _7p_double_circle || _7p_triple_circle || _7p_quadruple_circle,
  4224. _7p_intermed_points = _7p_calibration && !_7p_half_circle;
  4225. if (!_1p_calibration) { // test if the outer radius is reachable
  4226. const float circles = (_7p_quadruple_circle ? 1.5 :
  4227. _7p_triple_circle ? 1.0 :
  4228. _7p_double_circle ? 0.5 : 0),
  4229. radius = (1 + circles * 0.1) * delta_calibration_radius;
  4230. for (uint8_t axis = 1; axis < 13; ++axis) {
  4231. if (!position_is_reachable_by_probe_xy(cos(RADIANS(180 + 30 * axis)) * radius, sin(RADIANS(180 + 30 * axis)) * radius)) {
  4232. SERIAL_PROTOCOLLNPGM("?(M665 B)ed radius is implausible.");
  4233. return;
  4234. }
  4235. }
  4236. }
  4237. SERIAL_PROTOCOLLNPGM("G33 Auto Calibrate");
  4238. stepper.synchronize();
  4239. #if HAS_LEVELING
  4240. reset_bed_level(); // After calibration bed-level data is no longer valid
  4241. #endif
  4242. #if HOTENDS > 1
  4243. const uint8_t old_tool_index = active_extruder;
  4244. tool_change(0, 0, true);
  4245. #endif
  4246. setup_for_endstop_or_probe_move();
  4247. endstops.enable(true);
  4248. home_delta();
  4249. endstops.not_homing();
  4250. const static char save_message[] PROGMEM = "Save with M500 and/or copy to Configuration.h";
  4251. float test_precision,
  4252. zero_std_dev = (verbose_level ? 999.0 : 0.0), // 0.0 in dry-run mode : forced end
  4253. zero_std_dev_old = zero_std_dev,
  4254. e_old[XYZ] = {
  4255. endstop_adj[A_AXIS],
  4256. endstop_adj[B_AXIS],
  4257. endstop_adj[C_AXIS]
  4258. },
  4259. dr_old = delta_radius,
  4260. zh_old = home_offset[Z_AXIS],
  4261. alpha_old = delta_tower_angle_trim[A_AXIS],
  4262. beta_old = delta_tower_angle_trim[B_AXIS];
  4263. // print settings
  4264. SERIAL_PROTOCOLPGM("Checking... AC");
  4265. if (verbose_level == 0) SERIAL_PROTOCOLPGM(" (DRY-RUN)");
  4266. SERIAL_EOL;
  4267. LCD_MESSAGEPGM("Checking... AC"); // TODO: Make translatable string
  4268. SERIAL_PROTOCOLPAIR(".Height:", DELTA_HEIGHT + home_offset[Z_AXIS]);
  4269. if (!_1p_calibration) {
  4270. SERIAL_PROTOCOLPGM(" Ex:");
  4271. if (endstop_adj[A_AXIS] >= 0) SERIAL_CHAR('+');
  4272. SERIAL_PROTOCOL_F(endstop_adj[A_AXIS], 2);
  4273. SERIAL_PROTOCOLPGM(" Ey:");
  4274. if (endstop_adj[B_AXIS] >= 0) SERIAL_CHAR('+');
  4275. SERIAL_PROTOCOL_F(endstop_adj[B_AXIS], 2);
  4276. SERIAL_PROTOCOLPGM(" Ez:");
  4277. if (endstop_adj[C_AXIS] >= 0) SERIAL_CHAR('+');
  4278. SERIAL_PROTOCOL_F(endstop_adj[C_AXIS], 2);
  4279. SERIAL_PROTOCOLPAIR(" Radius:", delta_radius);
  4280. }
  4281. SERIAL_EOL;
  4282. if (_7p_calibration && towers_set) {
  4283. SERIAL_PROTOCOLPGM(".Tower angle : Tx:");
  4284. if (delta_tower_angle_trim[A_AXIS] >= 0) SERIAL_CHAR('+');
  4285. SERIAL_PROTOCOL_F(delta_tower_angle_trim[A_AXIS], 2);
  4286. SERIAL_PROTOCOLPGM(" Ty:");
  4287. if (delta_tower_angle_trim[B_AXIS] >= 0) SERIAL_CHAR('+');
  4288. SERIAL_PROTOCOL_F(delta_tower_angle_trim[B_AXIS], 2);
  4289. SERIAL_PROTOCOLPGM(" Tz:+0.00");
  4290. SERIAL_EOL;
  4291. }
  4292. #if ENABLED(Z_PROBE_SLED)
  4293. DEPLOY_PROBE();
  4294. #endif
  4295. int8_t iterations = 0;
  4296. home_offset[Z_AXIS] -= probe_pt(0.0, 0.0 , true, 1); // 1st probe to set height
  4297. do_probe_raise(Z_CLEARANCE_BETWEEN_PROBES);
  4298. do {
  4299. float z_at_pt[13] = { 0.0 }, S1 = 0.0, S2 = 0.0;
  4300. int16_t N = 0;
  4301. test_precision = zero_std_dev_old != 999.0 ? (zero_std_dev + zero_std_dev_old) / 2 : zero_std_dev;
  4302. iterations++;
  4303. // Probe the points
  4304. if (!_7p_half_circle && !_7p_triple_circle) { // probe the center
  4305. z_at_pt[0] += probe_pt(0.0, 0.0 , true, 1);
  4306. }
  4307. if (_7p_calibration) { // probe extra center points
  4308. for (int8_t axis = _7p_multi_circle ? 11 : 9; axis > 0; axis -= _7p_multi_circle ? 2 : 4) {
  4309. const float a = RADIANS(180 + 30 * axis), r = delta_calibration_radius * 0.1;
  4310. z_at_pt[0] += probe_pt(cos(a) * r, sin(a) * r, true, 1); // TODO: Needs error handling
  4311. }
  4312. z_at_pt[0] /= float(_7p_double_circle ? 7 : probe_points);
  4313. }
  4314. if (!_1p_calibration) { // probe the radius
  4315. bool zig_zag = true;
  4316. const uint8_t start = _4p_opposite_points ? 3 : 1,
  4317. step = _4p_calibration ? 4 : _7p_half_circle ? 2 : 1;
  4318. for (uint8_t axis = start; axis < 13; axis += step) {
  4319. const float offset_circles = _7p_quadruple_circle ? (zig_zag ? 1.5 : 1.0) :
  4320. _7p_triple_circle ? (zig_zag ? 1.0 : 0.5) :
  4321. _7p_double_circle ? (zig_zag ? 0.5 : 0.0) : 0;
  4322. for (float circles = -offset_circles ; circles <= offset_circles; circles++) {
  4323. const float a = RADIANS(180 + 30 * axis),
  4324. r = delta_calibration_radius * (1 + circles * (zig_zag ? 0.1 : -0.1));
  4325. z_at_pt[axis] += probe_pt(cos(a) * r, sin(a) * r, true, 1); // TODO: Needs error handling
  4326. }
  4327. zig_zag = !zig_zag;
  4328. z_at_pt[axis] /= (2 * offset_circles + 1);
  4329. }
  4330. }
  4331. if (_7p_intermed_points) // average intermediates to tower and opposites
  4332. for (uint8_t axis = 1; axis <= 11; axis += 2)
  4333. z_at_pt[axis] = (z_at_pt[axis] + (z_at_pt[axis + 1] + z_at_pt[(axis + 10) % 12 + 1]) / 2.0) / 2.0;
  4334. S1 += z_at_pt[0];
  4335. S2 += sq(z_at_pt[0]);
  4336. N++;
  4337. if (!_1p_calibration) // std dev from zero plane
  4338. for (uint8_t axis = (_4p_opposite_points ? 3 : 1); axis < 13; axis += (_4p_calibration ? 4 : 2)) {
  4339. S1 += z_at_pt[axis];
  4340. S2 += sq(z_at_pt[axis]);
  4341. N++;
  4342. }
  4343. zero_std_dev_old = zero_std_dev;
  4344. zero_std_dev = round(sqrt(S2 / N) * 1000.0) / 1000.0 + 0.00001;
  4345. if (iterations == 1) home_offset[Z_AXIS] = zh_old; // reset height after 1st probe change
  4346. // Solve matrices
  4347. if (zero_std_dev < test_precision && zero_std_dev > calibration_precision) {
  4348. COPY(e_old, endstop_adj);
  4349. dr_old = delta_radius;
  4350. zh_old = home_offset[Z_AXIS];
  4351. alpha_old = delta_tower_angle_trim[A_AXIS];
  4352. beta_old = delta_tower_angle_trim[B_AXIS];
  4353. float e_delta[XYZ] = { 0.0 }, r_delta = 0.0, t_alpha = 0.0, t_beta = 0.0;
  4354. const float r_diff = delta_radius - delta_calibration_radius,
  4355. h_factor = 1.00 + r_diff * 0.001, //1.02 for r_diff = 20mm
  4356. r_factor = -(1.75 + 0.005 * r_diff + 0.001 * sq(r_diff)), //2.25 for r_diff = 20mm
  4357. a_factor = 100.0 / delta_calibration_radius; //1.25 for cal_rd = 80mm
  4358. #define ZP(N,I) ((N) * z_at_pt[I])
  4359. #define Z1000(I) ZP(1.00, I)
  4360. #define Z1050(I) ZP(h_factor, I)
  4361. #define Z0700(I) ZP(h_factor * 2.0 / 3.00, I)
  4362. #define Z0350(I) ZP(h_factor / 3.00, I)
  4363. #define Z0175(I) ZP(h_factor / 6.00, I)
  4364. #define Z2250(I) ZP(r_factor, I)
  4365. #define Z0750(I) ZP(r_factor / 3.00, I)
  4366. #define Z0375(I) ZP(r_factor / 6.00, I)
  4367. #define Z0444(I) ZP(a_factor * 4.0 / 9.0, I)
  4368. #define Z0888(I) ZP(a_factor * 8.0 / 9.0, I)
  4369. switch (probe_points) {
  4370. case 1:
  4371. test_precision = 0.00;
  4372. LOOP_XYZ(i) e_delta[i] = Z1000(0);
  4373. break;
  4374. case 2:
  4375. if (towers_set) {
  4376. e_delta[X_AXIS] = Z1050(0) + Z0700(1) - Z0350(5) - Z0350(9);
  4377. e_delta[Y_AXIS] = Z1050(0) - Z0350(1) + Z0700(5) - Z0350(9);
  4378. e_delta[Z_AXIS] = Z1050(0) - Z0350(1) - Z0350(5) + Z0700(9);
  4379. r_delta = Z2250(0) - Z0750(1) - Z0750(5) - Z0750(9);
  4380. }
  4381. else {
  4382. e_delta[X_AXIS] = Z1050(0) - Z0700(7) + Z0350(11) + Z0350(3);
  4383. e_delta[Y_AXIS] = Z1050(0) + Z0350(7) - Z0700(11) + Z0350(3);
  4384. e_delta[Z_AXIS] = Z1050(0) + Z0350(7) + Z0350(11) - Z0700(3);
  4385. r_delta = Z2250(0) - Z0750(7) - Z0750(11) - Z0750(3);
  4386. }
  4387. break;
  4388. default:
  4389. e_delta[X_AXIS] = Z1050(0) + Z0350(1) - Z0175(5) - Z0175(9) - Z0350(7) + Z0175(11) + Z0175(3);
  4390. e_delta[Y_AXIS] = Z1050(0) - Z0175(1) + Z0350(5) - Z0175(9) + Z0175(7) - Z0350(11) + Z0175(3);
  4391. e_delta[Z_AXIS] = Z1050(0) - Z0175(1) - Z0175(5) + Z0350(9) + Z0175(7) + Z0175(11) - Z0350(3);
  4392. r_delta = Z2250(0) - Z0375(1) - Z0375(5) - Z0375(9) - Z0375(7) - Z0375(11) - Z0375(3);
  4393. if (towers_set) {
  4394. t_alpha = Z0444(1) - Z0888(5) + Z0444(9) + Z0444(7) - Z0888(11) + Z0444(3);
  4395. t_beta = Z0888(1) - Z0444(5) - Z0444(9) + Z0888(7) - Z0444(11) - Z0444(3);
  4396. }
  4397. break;
  4398. }
  4399. LOOP_XYZ(axis) endstop_adj[axis] += e_delta[axis];
  4400. delta_radius += r_delta;
  4401. delta_tower_angle_trim[A_AXIS] += t_alpha;
  4402. delta_tower_angle_trim[B_AXIS] += t_beta;
  4403. // adjust delta_height and endstops by the max amount
  4404. const float z_temp = MAX3(endstop_adj[A_AXIS], endstop_adj[B_AXIS], endstop_adj[C_AXIS]);
  4405. home_offset[Z_AXIS] -= z_temp;
  4406. LOOP_XYZ(i) endstop_adj[i] -= z_temp;
  4407. recalc_delta_settings(delta_radius, delta_diagonal_rod);
  4408. }
  4409. else if(zero_std_dev >= test_precision) { // step one back
  4410. COPY(endstop_adj, e_old);
  4411. delta_radius = dr_old;
  4412. home_offset[Z_AXIS] = zh_old;
  4413. delta_tower_angle_trim[A_AXIS] = alpha_old;
  4414. delta_tower_angle_trim[B_AXIS] = beta_old;
  4415. recalc_delta_settings(delta_radius, delta_diagonal_rod);
  4416. }
  4417. // print report
  4418. if (verbose_level != 1) {
  4419. SERIAL_PROTOCOLPGM(". c:");
  4420. if (z_at_pt[0] > 0) SERIAL_CHAR('+');
  4421. SERIAL_PROTOCOL_F(z_at_pt[0], 2);
  4422. if (_4p_towers_points || _7p_calibration) {
  4423. SERIAL_PROTOCOLPGM(" x:");
  4424. if (z_at_pt[1] >= 0) SERIAL_CHAR('+');
  4425. SERIAL_PROTOCOL_F(z_at_pt[1], 2);
  4426. SERIAL_PROTOCOLPGM(" y:");
  4427. if (z_at_pt[5] >= 0) SERIAL_CHAR('+');
  4428. SERIAL_PROTOCOL_F(z_at_pt[5], 2);
  4429. SERIAL_PROTOCOLPGM(" z:");
  4430. if (z_at_pt[9] >= 0) SERIAL_CHAR('+');
  4431. SERIAL_PROTOCOL_F(z_at_pt[9], 2);
  4432. }
  4433. if (!_4p_opposite_points) SERIAL_EOL;
  4434. if ((_4p_opposite_points) || _7p_calibration) {
  4435. if (_7p_calibration) {
  4436. SERIAL_CHAR('.');
  4437. SERIAL_PROTOCOL_SP(13);
  4438. }
  4439. SERIAL_PROTOCOLPGM(" yz:");
  4440. if (z_at_pt[7] >= 0) SERIAL_CHAR('+');
  4441. SERIAL_PROTOCOL_F(z_at_pt[7], 2);
  4442. SERIAL_PROTOCOLPGM(" zx:");
  4443. if (z_at_pt[11] >= 0) SERIAL_CHAR('+');
  4444. SERIAL_PROTOCOL_F(z_at_pt[11], 2);
  4445. SERIAL_PROTOCOLPGM(" xy:");
  4446. if (z_at_pt[3] >= 0) SERIAL_CHAR('+');
  4447. SERIAL_PROTOCOL_F(z_at_pt[3], 2);
  4448. SERIAL_EOL;
  4449. }
  4450. }
  4451. if (test_precision != 0.0) { // !forced end
  4452. if (zero_std_dev >= test_precision || zero_std_dev <= calibration_precision) { // end iterations
  4453. SERIAL_PROTOCOLPGM("Calibration OK");
  4454. SERIAL_PROTOCOL_SP(36);
  4455. if (zero_std_dev >= test_precision)
  4456. SERIAL_PROTOCOLPGM("rolling back.");
  4457. else {
  4458. SERIAL_PROTOCOLPGM("std dev:");
  4459. SERIAL_PROTOCOL_F(zero_std_dev, 3);
  4460. }
  4461. SERIAL_EOL;
  4462. LCD_MESSAGEPGM("Calibration OK"); // TODO: Make translatable string
  4463. }
  4464. else { // !end iterations
  4465. char mess[15] = "No convergence";
  4466. if (iterations < 31)
  4467. sprintf_P(mess, PSTR("Iteration : %02i"), (int)iterations);
  4468. SERIAL_PROTOCOL(mess);
  4469. SERIAL_PROTOCOL_SP(36);
  4470. SERIAL_PROTOCOLPGM("std dev:");
  4471. SERIAL_PROTOCOL_F(zero_std_dev, 3);
  4472. SERIAL_EOL;
  4473. lcd_setstatus(mess);
  4474. }
  4475. SERIAL_PROTOCOLPAIR(".Height:", DELTA_HEIGHT + home_offset[Z_AXIS]);
  4476. if (!_1p_calibration) {
  4477. SERIAL_PROTOCOLPGM(" Ex:");
  4478. if (endstop_adj[A_AXIS] >= 0) SERIAL_CHAR('+');
  4479. SERIAL_PROTOCOL_F(endstop_adj[A_AXIS], 2);
  4480. SERIAL_PROTOCOLPGM(" Ey:");
  4481. if (endstop_adj[B_AXIS] >= 0) SERIAL_CHAR('+');
  4482. SERIAL_PROTOCOL_F(endstop_adj[B_AXIS], 2);
  4483. SERIAL_PROTOCOLPGM(" Ez:");
  4484. if (endstop_adj[C_AXIS] >= 0) SERIAL_CHAR('+');
  4485. SERIAL_PROTOCOL_F(endstop_adj[C_AXIS], 2);
  4486. SERIAL_PROTOCOLPAIR(" Radius:", delta_radius);
  4487. }
  4488. SERIAL_EOL;
  4489. if (_7p_calibration && towers_set) {
  4490. SERIAL_PROTOCOLPGM(".Tower angle : Tx:");
  4491. if (delta_tower_angle_trim[A_AXIS] >= 0) SERIAL_CHAR('+');
  4492. SERIAL_PROTOCOL_F(delta_tower_angle_trim[A_AXIS], 2);
  4493. SERIAL_PROTOCOLPGM(" Ty:");
  4494. if (delta_tower_angle_trim[B_AXIS] >= 0) SERIAL_CHAR('+');
  4495. SERIAL_PROTOCOL_F(delta_tower_angle_trim[B_AXIS], 2);
  4496. SERIAL_PROTOCOLPGM(" Tz:+0.00");
  4497. SERIAL_EOL;
  4498. }
  4499. if (zero_std_dev >= test_precision || zero_std_dev <= calibration_precision)
  4500. serialprintPGM(save_message);
  4501. SERIAL_EOL;
  4502. }
  4503. else { // forced end
  4504. if (verbose_level == 0) {
  4505. SERIAL_PROTOCOLPGM("End DRY-RUN");
  4506. SERIAL_PROTOCOL_SP(39);
  4507. SERIAL_PROTOCOLPGM("std dev:");
  4508. SERIAL_PROTOCOL_F(zero_std_dev, 3);
  4509. SERIAL_EOL;
  4510. }
  4511. else {
  4512. SERIAL_PROTOCOLLNPGM("Calibration OK");
  4513. LCD_MESSAGEPGM("Calibration OK"); // TODO: Make translatable string
  4514. SERIAL_PROTOCOLPAIR(".Height:", DELTA_HEIGHT + home_offset[Z_AXIS]);
  4515. SERIAL_EOL;
  4516. serialprintPGM(save_message);
  4517. SERIAL_EOL;
  4518. }
  4519. }
  4520. endstops.enable(true);
  4521. home_delta();
  4522. endstops.not_homing();
  4523. }
  4524. while (zero_std_dev < test_precision && zero_std_dev > calibration_precision && iterations < 31);
  4525. #if ENABLED(DELTA_HOME_TO_SAFE_ZONE)
  4526. do_blocking_move_to_z(delta_clip_start_height);
  4527. #endif
  4528. clean_up_after_endstop_or_probe_move();
  4529. #if HOTENDS > 1
  4530. tool_change(old_tool_index, 0, true);
  4531. #endif
  4532. #if ENABLED(Z_PROBE_SLED)
  4533. RETRACT_PROBE();
  4534. #endif
  4535. }
  4536. #endif // DELTA_AUTO_CALIBRATION
  4537. #endif // HAS_BED_PROBE
  4538. #if ENABLED(G38_PROBE_TARGET)
  4539. static bool G38_run_probe() {
  4540. bool G38_pass_fail = false;
  4541. // Get direction of move and retract
  4542. float retract_mm[XYZ];
  4543. LOOP_XYZ(i) {
  4544. float dist = destination[i] - current_position[i];
  4545. retract_mm[i] = fabs(dist) < G38_MINIMUM_MOVE ? 0 : home_bump_mm((AxisEnum)i) * (dist > 0 ? -1 : 1);
  4546. }
  4547. stepper.synchronize(); // wait until the machine is idle
  4548. // Move until destination reached or target hit
  4549. endstops.enable(true);
  4550. G38_move = true;
  4551. G38_endstop_hit = false;
  4552. prepare_move_to_destination();
  4553. stepper.synchronize();
  4554. G38_move = false;
  4555. endstops.hit_on_purpose();
  4556. set_current_from_steppers_for_axis(ALL_AXES);
  4557. SYNC_PLAN_POSITION_KINEMATIC();
  4558. if (G38_endstop_hit) {
  4559. G38_pass_fail = true;
  4560. #if ENABLED(PROBE_DOUBLE_TOUCH)
  4561. // Move away by the retract distance
  4562. set_destination_to_current();
  4563. LOOP_XYZ(i) destination[i] += retract_mm[i];
  4564. endstops.enable(false);
  4565. prepare_move_to_destination();
  4566. stepper.synchronize();
  4567. feedrate_mm_s /= 4;
  4568. // Bump the target more slowly
  4569. LOOP_XYZ(i) destination[i] -= retract_mm[i] * 2;
  4570. endstops.enable(true);
  4571. G38_move = true;
  4572. prepare_move_to_destination();
  4573. stepper.synchronize();
  4574. G38_move = false;
  4575. set_current_from_steppers_for_axis(ALL_AXES);
  4576. SYNC_PLAN_POSITION_KINEMATIC();
  4577. #endif
  4578. }
  4579. endstops.hit_on_purpose();
  4580. endstops.not_homing();
  4581. return G38_pass_fail;
  4582. }
  4583. /**
  4584. * G38.2 - probe toward workpiece, stop on contact, signal error if failure
  4585. * G38.3 - probe toward workpiece, stop on contact
  4586. *
  4587. * Like G28 except uses Z min probe for all axes
  4588. */
  4589. inline void gcode_G38(bool is_38_2) {
  4590. // Get X Y Z E F
  4591. gcode_get_destination();
  4592. setup_for_endstop_or_probe_move();
  4593. // If any axis has enough movement, do the move
  4594. LOOP_XYZ(i)
  4595. if (fabs(destination[i] - current_position[i]) >= G38_MINIMUM_MOVE) {
  4596. if (!parser.seen('F')) feedrate_mm_s = homing_feedrate_mm_s[i];
  4597. // If G38.2 fails throw an error
  4598. if (!G38_run_probe() && is_38_2) {
  4599. SERIAL_ERROR_START;
  4600. SERIAL_ERRORLNPGM("Failed to reach target");
  4601. }
  4602. break;
  4603. }
  4604. clean_up_after_endstop_or_probe_move();
  4605. }
  4606. #endif // G38_PROBE_TARGET
  4607. #if ENABLED(AUTO_BED_LEVELING_BILINEAR) || ENABLED(AUTO_BED_LEVELING_UBL) || ENABLED(MESH_BED_LEVELING)
  4608. /**
  4609. * G42: Move X & Y axes to mesh coordinates (I & J)
  4610. */
  4611. inline void gcode_G42() {
  4612. if (IsRunning()) {
  4613. const bool hasI = parser.seen('I');
  4614. const int8_t ix = parser.has_value() ? parser.value_int() : 0;
  4615. const bool hasJ = parser.seen('J');
  4616. const int8_t iy = parser.has_value() ? parser.value_int() : 0;
  4617. if ((hasI && !WITHIN(ix, 0, GRID_MAX_POINTS_X - 1)) || (hasJ && !WITHIN(iy, 0, GRID_MAX_POINTS_Y - 1))) {
  4618. SERIAL_ECHOLNPGM(MSG_ERR_MESH_XY);
  4619. return;
  4620. }
  4621. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  4622. #define _GET_MESH_X(I) bilinear_start[X_AXIS] + I * bilinear_grid_spacing[X_AXIS]
  4623. #define _GET_MESH_Y(J) bilinear_start[Y_AXIS] + J * bilinear_grid_spacing[Y_AXIS]
  4624. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  4625. #define _GET_MESH_X(I) ubl.mesh_index_to_xpos(I)
  4626. #define _GET_MESH_Y(J) ubl.mesh_index_to_ypos(J)
  4627. #elif ENABLED(MESH_BED_LEVELING)
  4628. #define _GET_MESH_X(I) mbl.index_to_xpos[I]
  4629. #define _GET_MESH_Y(J) mbl.index_to_ypos[J]
  4630. #endif
  4631. set_destination_to_current();
  4632. if (hasI) destination[X_AXIS] = LOGICAL_X_POSITION(_GET_MESH_X(ix));
  4633. if (hasJ) destination[Y_AXIS] = LOGICAL_Y_POSITION(_GET_MESH_Y(iy));
  4634. if (parser.seen('P') && parser.value_bool()) {
  4635. if (hasI) destination[X_AXIS] -= X_PROBE_OFFSET_FROM_EXTRUDER;
  4636. if (hasJ) destination[Y_AXIS] -= Y_PROBE_OFFSET_FROM_EXTRUDER;
  4637. }
  4638. if (parser.seen('F') && parser.value_linear_units() > 0.0)
  4639. feedrate_mm_s = MMM_TO_MMS(parser.value_linear_units());
  4640. // SCARA kinematic has "safe" XY raw moves
  4641. #if IS_SCARA
  4642. prepare_uninterpolated_move_to_destination();
  4643. #else
  4644. prepare_move_to_destination();
  4645. #endif
  4646. }
  4647. }
  4648. #endif // AUTO_BED_LEVELING_UBL
  4649. /**
  4650. * G92: Set current position to given X Y Z E
  4651. */
  4652. inline void gcode_G92() {
  4653. bool didXYZ = false,
  4654. didE = parser.seen('E');
  4655. if (!didE) stepper.synchronize();
  4656. LOOP_XYZE(i) {
  4657. if (parser.seen(axis_codes[i])) {
  4658. #if IS_SCARA
  4659. current_position[i] = parser.value_axis_units((AxisEnum)i);
  4660. if (i != E_AXIS) didXYZ = true;
  4661. #else
  4662. #if HAS_POSITION_SHIFT
  4663. const float p = current_position[i];
  4664. #endif
  4665. float v = parser.value_axis_units((AxisEnum)i);
  4666. current_position[i] = v;
  4667. if (i != E_AXIS) {
  4668. didXYZ = true;
  4669. #if HAS_POSITION_SHIFT
  4670. position_shift[i] += v - p; // Offset the coordinate space
  4671. update_software_endstops((AxisEnum)i);
  4672. #endif
  4673. }
  4674. #endif
  4675. }
  4676. }
  4677. if (didXYZ)
  4678. SYNC_PLAN_POSITION_KINEMATIC();
  4679. else if (didE)
  4680. sync_plan_position_e();
  4681. report_current_position();
  4682. }
  4683. #if HAS_RESUME_CONTINUE
  4684. /**
  4685. * M0: Unconditional stop - Wait for user button press on LCD
  4686. * M1: Conditional stop - Wait for user button press on LCD
  4687. */
  4688. inline void gcode_M0_M1() {
  4689. const char * const args = parser.string_arg;
  4690. millis_t ms = 0;
  4691. bool hasP = false, hasS = false;
  4692. if (parser.seen('P')) {
  4693. ms = parser.value_millis(); // milliseconds to wait
  4694. hasP = ms > 0;
  4695. }
  4696. if (parser.seen('S')) {
  4697. ms = parser.value_millis_from_seconds(); // seconds to wait
  4698. hasS = ms > 0;
  4699. }
  4700. #if ENABLED(ULTIPANEL)
  4701. if (!hasP && !hasS && args && *args)
  4702. lcd_setstatus(args, true);
  4703. else {
  4704. LCD_MESSAGEPGM(MSG_USERWAIT);
  4705. #if ENABLED(LCD_PROGRESS_BAR) && PROGRESS_MSG_EXPIRE > 0
  4706. dontExpireStatus();
  4707. #endif
  4708. }
  4709. #else
  4710. if (!hasP && !hasS && args && *args) {
  4711. SERIAL_ECHO_START;
  4712. SERIAL_ECHOLN(args);
  4713. }
  4714. #endif
  4715. KEEPALIVE_STATE(PAUSED_FOR_USER);
  4716. wait_for_user = true;
  4717. stepper.synchronize();
  4718. refresh_cmd_timeout();
  4719. if (ms > 0) {
  4720. ms += previous_cmd_ms; // wait until this time for a click
  4721. while (PENDING(millis(), ms) && wait_for_user) idle();
  4722. }
  4723. else {
  4724. #if ENABLED(ULTIPANEL)
  4725. if (lcd_detected()) {
  4726. while (wait_for_user) idle();
  4727. IS_SD_PRINTING ? LCD_MESSAGEPGM(MSG_RESUMING) : LCD_MESSAGEPGM(WELCOME_MSG);
  4728. }
  4729. #else
  4730. while (wait_for_user) idle();
  4731. #endif
  4732. }
  4733. wait_for_user = false;
  4734. KEEPALIVE_STATE(IN_HANDLER);
  4735. }
  4736. #endif // HAS_RESUME_CONTINUE
  4737. #if ENABLED(SPINDLE_LASER_ENABLE)
  4738. /**
  4739. * M3: Spindle Clockwise
  4740. * M4: Spindle Counter-clockwise
  4741. *
  4742. * S0 turns off spindle.
  4743. *
  4744. * If no speed PWM output is defined then M3/M4 just turns it on.
  4745. *
  4746. * At least 12.8KHz (50Hz * 256) is needed for spindle PWM.
  4747. * Hardware PWM is required. ISRs are too slow.
  4748. *
  4749. * NOTE: WGM for timers 3, 4, and 5 must be either Mode 1 or Mode 5.
  4750. * No other settings give a PWM signal that goes from 0 to 5 volts.
  4751. *
  4752. * The system automatically sets WGM to Mode 1, so no special
  4753. * initialization is needed.
  4754. *
  4755. * WGM bits for timer 2 are automatically set by the system to
  4756. * Mode 1. This produces an acceptable 0 to 5 volt signal.
  4757. * No special initialization is needed.
  4758. *
  4759. * NOTE: A minimum PWM frequency of 50 Hz is needed. All prescaler
  4760. * factors for timers 2, 3, 4, and 5 are acceptable.
  4761. *
  4762. * SPINDLE_LASER_ENABLE_PIN needs an external pullup or it may power on
  4763. * the spindle/laser during power-up or when connecting to the host
  4764. * (usually goes through a reset which sets all I/O pins to tri-state)
  4765. *
  4766. * PWM duty cycle goes from 0 (off) to 255 (always on).
  4767. */
  4768. // Wait for spindle to come up to speed
  4769. inline void delay_for_power_up() {
  4770. refresh_cmd_timeout();
  4771. while (PENDING(millis(), SPINDLE_LASER_POWERUP_DELAY + previous_cmd_ms)) idle();
  4772. }
  4773. // Wait for spindle to stop turning
  4774. inline void delay_for_power_down() {
  4775. refresh_cmd_timeout();
  4776. while (PENDING(millis(), SPINDLE_LASER_POWERDOWN_DELAY + previous_cmd_ms + 1)) idle();
  4777. }
  4778. /**
  4779. * ocr_val_mode() is used for debugging and to get the points needed to compute the RPM vs ocr_val line
  4780. *
  4781. * it accepts inputs of 0-255
  4782. */
  4783. inline void ocr_val_mode() {
  4784. uint8_t spindle_laser_power = parser.value_byte();
  4785. WRITE(SPINDLE_LASER_ENABLE_PIN, SPINDLE_LASER_ENABLE_INVERT); // turn spindle on (active low)
  4786. if (SPINDLE_LASER_PWM_INVERT) spindle_laser_power = 255 - spindle_laser_power;
  4787. analogWrite(SPINDLE_LASER_PWM_PIN, spindle_laser_power);
  4788. }
  4789. inline void gcode_M3_M4(bool is_M3) {
  4790. stepper.synchronize(); // wait until previous movement commands (G0/G0/G2/G3) have completed before playing with the spindle
  4791. #if SPINDLE_DIR_CHANGE
  4792. const bool rotation_dir = (is_M3 && !SPINDLE_INVERT_DIR || !is_M3 && SPINDLE_INVERT_DIR) ? HIGH : LOW;
  4793. if (SPINDLE_STOP_ON_DIR_CHANGE \
  4794. && READ(SPINDLE_LASER_ENABLE_PIN) == SPINDLE_LASER_ENABLE_INVERT \
  4795. && READ(SPINDLE_DIR_PIN) != rotation_dir
  4796. ) {
  4797. WRITE(SPINDLE_LASER_ENABLE_PIN, !SPINDLE_LASER_ENABLE_INVERT); // turn spindle off
  4798. delay_for_power_down();
  4799. }
  4800. digitalWrite(SPINDLE_DIR_PIN, rotation_dir);
  4801. #endif
  4802. /**
  4803. * Our final value for ocr_val is an unsigned 8 bit value between 0 and 255 which usually means uint8_t.
  4804. * Went to uint16_t because some of the uint8_t calculations would sometimes give 1000 0000 rather than 1111 1111.
  4805. * Then needed to AND the uint16_t result with 0x00FF to make sure we only wrote the byte of interest.
  4806. */
  4807. #if ENABLED(SPINDLE_LASER_PWM)
  4808. if (parser.seen('O')) ocr_val_mode();
  4809. else {
  4810. const float spindle_laser_power = parser.seen('S') ? parser.value_float() : 0;
  4811. if (spindle_laser_power == 0) {
  4812. WRITE(SPINDLE_LASER_ENABLE_PIN, !SPINDLE_LASER_ENABLE_INVERT); // turn spindle off (active low)
  4813. delay_for_power_down();
  4814. }
  4815. else {
  4816. int16_t ocr_val = (spindle_laser_power - (SPEED_POWER_INTERCEPT)) * (1.0 / (SPEED_POWER_SLOPE)); // convert RPM to PWM duty cycle
  4817. NOMORE(ocr_val, 255); // limit to max the Atmel PWM will support
  4818. if (spindle_laser_power <= SPEED_POWER_MIN)
  4819. ocr_val = (SPEED_POWER_MIN - (SPEED_POWER_INTERCEPT)) * (1.0 / (SPEED_POWER_SLOPE)); // minimum setting
  4820. if (spindle_laser_power >= SPEED_POWER_MAX)
  4821. ocr_val = (SPEED_POWER_MAX - (SPEED_POWER_INTERCEPT)) * (1.0 / (SPEED_POWER_SLOPE)); // limit to max RPM
  4822. if (SPINDLE_LASER_PWM_INVERT) ocr_val = 255 - ocr_val;
  4823. WRITE(SPINDLE_LASER_ENABLE_PIN, SPINDLE_LASER_ENABLE_INVERT); // turn spindle on (active low)
  4824. analogWrite(SPINDLE_LASER_PWM_PIN, ocr_val & 0xFF); // only write low byte
  4825. delay_for_power_up();
  4826. }
  4827. }
  4828. #else
  4829. WRITE(SPINDLE_LASER_ENABLE_PIN, SPINDLE_LASER_ENABLE_INVERT); // turn spindle on (active low) if spindle speed option not enabled
  4830. delay_for_power_up();
  4831. #endif
  4832. }
  4833. /**
  4834. * M5 turn off spindle
  4835. */
  4836. inline void gcode_M5() {
  4837. stepper.synchronize();
  4838. WRITE(SPINDLE_LASER_ENABLE_PIN, !SPINDLE_LASER_ENABLE_INVERT);
  4839. delay_for_power_down();
  4840. }
  4841. #endif // SPINDLE_LASER_ENABLE
  4842. /**
  4843. * M17: Enable power on all stepper motors
  4844. */
  4845. inline void gcode_M17() {
  4846. LCD_MESSAGEPGM(MSG_NO_MOVE);
  4847. enable_all_steppers();
  4848. }
  4849. #if IS_KINEMATIC
  4850. #define RUNPLAN(RATE_MM_S) planner.buffer_line_kinematic(destination, RATE_MM_S, active_extruder)
  4851. #else
  4852. #define RUNPLAN(RATE_MM_S) line_to_destination(RATE_MM_S)
  4853. #endif
  4854. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  4855. static float resume_position[XYZE];
  4856. static bool move_away_flag = false;
  4857. #if ENABLED(SDSUPPORT)
  4858. static bool sd_print_paused = false;
  4859. #endif
  4860. static void filament_change_beep(const int8_t max_beep_count, const bool init=false) {
  4861. static millis_t next_buzz = 0;
  4862. static int8_t runout_beep = 0;
  4863. if (init) next_buzz = runout_beep = 0;
  4864. const millis_t ms = millis();
  4865. if (ELAPSED(ms, next_buzz)) {
  4866. if (max_beep_count < 0 || runout_beep < max_beep_count + 5) { // Only beep as long as we're supposed to
  4867. next_buzz = ms + ((max_beep_count < 0 || runout_beep < max_beep_count) ? 2500 : 400);
  4868. BUZZ(300, 2000);
  4869. runout_beep++;
  4870. }
  4871. }
  4872. }
  4873. static bool pause_print(const float &retract, const float &z_lift, const float &x_pos, const float &y_pos,
  4874. const float &unload_length = 0 , int8_t max_beep_count = 0, bool show_lcd = false
  4875. ) {
  4876. if (move_away_flag) return false; // already paused
  4877. if (!DEBUGGING(DRYRUN) && thermalManager.tooColdToExtrude(active_extruder) && unload_length > 0) {
  4878. SERIAL_ERROR_START;
  4879. SERIAL_ERRORLNPGM(MSG_TOO_COLD_FOR_M600);
  4880. return false;
  4881. }
  4882. // Indicate that the printer is paused
  4883. move_away_flag = true;
  4884. // Pause the print job and timer
  4885. #if ENABLED(SDSUPPORT)
  4886. if (card.sdprinting) {
  4887. card.pauseSDPrint();
  4888. sd_print_paused = true;
  4889. }
  4890. #endif
  4891. print_job_timer.pause();
  4892. // Show initial message and wait for synchronize steppers
  4893. if (show_lcd) {
  4894. #if ENABLED(ULTIPANEL)
  4895. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_INIT);
  4896. #endif
  4897. }
  4898. stepper.synchronize();
  4899. // Save current position
  4900. COPY(resume_position, current_position);
  4901. set_destination_to_current();
  4902. // Initial retract before move to filament change position
  4903. destination[E_AXIS] += retract;
  4904. RUNPLAN(PAUSE_PARK_RETRACT_FEEDRATE);
  4905. // Lift Z axis
  4906. if (z_lift > 0) {
  4907. destination[Z_AXIS] += z_lift;
  4908. NOMORE(destination[Z_AXIS], Z_MAX_POS);
  4909. RUNPLAN(PAUSE_PARK_Z_FEEDRATE);
  4910. }
  4911. // Move XY axes to filament exchange position
  4912. destination[X_AXIS] = x_pos;
  4913. destination[Y_AXIS] = y_pos;
  4914. clamp_to_software_endstops(destination);
  4915. RUNPLAN(PAUSE_PARK_XY_FEEDRATE);
  4916. stepper.synchronize();
  4917. if (unload_length != 0) {
  4918. if (show_lcd) {
  4919. #if ENABLED(ULTIPANEL)
  4920. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_UNLOAD);
  4921. idle();
  4922. #endif
  4923. }
  4924. // Unload filament
  4925. destination[E_AXIS] += unload_length;
  4926. RUNPLAN(FILAMENT_CHANGE_UNLOAD_FEEDRATE);
  4927. stepper.synchronize();
  4928. if (show_lcd) {
  4929. #if ENABLED(ULTIPANEL)
  4930. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_INSERT);
  4931. #endif
  4932. }
  4933. #if HAS_BUZZER
  4934. filament_change_beep(max_beep_count, true);
  4935. #endif
  4936. idle();
  4937. }
  4938. // Disable extruders steppers for manual filament changing
  4939. disable_e_steppers();
  4940. safe_delay(100);
  4941. // Start the heater idle timers
  4942. const millis_t nozzle_timeout = (millis_t)(PAUSE_PARK_NOZZLE_TIMEOUT) * 1000UL;
  4943. HOTEND_LOOP()
  4944. thermalManager.start_heater_idle_timer(e, nozzle_timeout);
  4945. return true;
  4946. }
  4947. static void wait_for_filament_reload(int8_t max_beep_count = 0) {
  4948. bool nozzle_timed_out = false;
  4949. // Wait for filament insert by user and press button
  4950. KEEPALIVE_STATE(PAUSED_FOR_USER);
  4951. wait_for_user = true; // LCD click or M108 will clear this
  4952. while (wait_for_user) {
  4953. #if HAS_BUZZER
  4954. filament_change_beep(max_beep_count);
  4955. #endif
  4956. if (!nozzle_timed_out)
  4957. HOTEND_LOOP()
  4958. nozzle_timed_out |= thermalManager.is_heater_idle(e);
  4959. #if ENABLED(ULTIPANEL)
  4960. if (nozzle_timed_out)
  4961. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_CLICK_TO_HEAT_NOZZLE);
  4962. #endif
  4963. idle(true);
  4964. }
  4965. KEEPALIVE_STATE(IN_HANDLER);
  4966. }
  4967. static void resume_print(const float &load_length = 0, const float &initial_extrude_length = 0, int8_t max_beep_count = 0) {
  4968. bool nozzle_timed_out = false;
  4969. if (!move_away_flag) return;
  4970. // Re-enable the heaters if they timed out
  4971. HOTEND_LOOP() {
  4972. nozzle_timed_out |= thermalManager.is_heater_idle(e);
  4973. thermalManager.reset_heater_idle_timer(e);
  4974. }
  4975. #if ENABLED(ULTIPANEL)
  4976. // Show "wait for heating"
  4977. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_WAIT_FOR_NOZZLES_TO_HEAT);
  4978. #endif
  4979. wait_for_heatup = true;
  4980. while (wait_for_heatup) {
  4981. idle();
  4982. wait_for_heatup = false;
  4983. HOTEND_LOOP() {
  4984. if (abs(thermalManager.degHotend(e) - thermalManager.degTargetHotend(e)) > 3) {
  4985. wait_for_heatup = true;
  4986. break;
  4987. }
  4988. }
  4989. }
  4990. #if HAS_BUZZER
  4991. filament_change_beep(max_beep_count, true);
  4992. #endif
  4993. if (load_length != 0) {
  4994. #if ENABLED(ULTIPANEL)
  4995. // Show "insert filament"
  4996. if (nozzle_timed_out)
  4997. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_INSERT);
  4998. #endif
  4999. KEEPALIVE_STATE(PAUSED_FOR_USER);
  5000. wait_for_user = true; // LCD click or M108 will clear this
  5001. while (wait_for_user && nozzle_timed_out) {
  5002. #if HAS_BUZZER
  5003. filament_change_beep(max_beep_count);
  5004. #endif
  5005. idle(true);
  5006. }
  5007. KEEPALIVE_STATE(IN_HANDLER);
  5008. #if ENABLED(ULTIPANEL)
  5009. // Show "load" message
  5010. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_LOAD);
  5011. #endif
  5012. // Load filament
  5013. destination[E_AXIS] += load_length;
  5014. RUNPLAN(FILAMENT_CHANGE_LOAD_FEEDRATE);
  5015. stepper.synchronize();
  5016. }
  5017. #if ENABLED(ULTIPANEL) && defined(ADVANCED_PAUSE_EXTRUDE_LENGTH) && ADVANCED_PAUSE_EXTRUDE_LENGTH > 0
  5018. float extrude_length = initial_extrude_length;
  5019. do {
  5020. if (extrude_length > 0) {
  5021. // "Wait for filament extrude"
  5022. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_EXTRUDE);
  5023. // Extrude filament to get into hotend
  5024. destination[E_AXIS] += extrude_length;
  5025. RUNPLAN(ADVANCED_PAUSE_EXTRUDE_FEEDRATE);
  5026. stepper.synchronize();
  5027. }
  5028. // Show "Extrude More" / "Resume" menu and wait for reply
  5029. KEEPALIVE_STATE(PAUSED_FOR_USER);
  5030. wait_for_user = false;
  5031. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_OPTION);
  5032. while (advanced_pause_menu_response == ADVANCED_PAUSE_RESPONSE_WAIT_FOR) idle(true);
  5033. KEEPALIVE_STATE(IN_HANDLER);
  5034. extrude_length = ADVANCED_PAUSE_EXTRUDE_LENGTH;
  5035. // Keep looping if "Extrude More" was selected
  5036. } while (advanced_pause_menu_response == ADVANCED_PAUSE_RESPONSE_EXTRUDE_MORE);
  5037. #endif
  5038. #if ENABLED(ULTIPANEL)
  5039. // "Wait for print to resume"
  5040. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_RESUME);
  5041. #endif
  5042. // Set extruder to saved position
  5043. destination[E_AXIS] = current_position[E_AXIS] = resume_position[E_AXIS];
  5044. planner.set_e_position_mm(current_position[E_AXIS]);
  5045. #if IS_KINEMATIC
  5046. // Move XYZ to starting position
  5047. planner.buffer_line_kinematic(lastpos, PAUSE_PARK_XY_FEEDRATE, active_extruder);
  5048. #else
  5049. // Move XY to starting position, then Z
  5050. destination[X_AXIS] = resume_position[X_AXIS];
  5051. destination[Y_AXIS] = resume_position[Y_AXIS];
  5052. RUNPLAN(PAUSE_PARK_XY_FEEDRATE);
  5053. destination[Z_AXIS] = resume_position[Z_AXIS];
  5054. RUNPLAN(PAUSE_PARK_Z_FEEDRATE);
  5055. #endif
  5056. stepper.synchronize();
  5057. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  5058. filament_ran_out = false;
  5059. #endif
  5060. set_current_to_destination();
  5061. #if ENABLED(ULTIPANEL)
  5062. // Show status screen
  5063. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_STATUS);
  5064. #endif
  5065. #if ENABLED(SDSUPPORT)
  5066. if (sd_print_paused) {
  5067. card.startFileprint();
  5068. sd_print_paused = false;
  5069. }
  5070. #endif
  5071. move_away_flag = false;
  5072. }
  5073. #endif // ADVANCED_PAUSE_FEATURE
  5074. #if ENABLED(SDSUPPORT)
  5075. /**
  5076. * M20: List SD card to serial output
  5077. */
  5078. inline void gcode_M20() {
  5079. SERIAL_PROTOCOLLNPGM(MSG_BEGIN_FILE_LIST);
  5080. card.ls();
  5081. SERIAL_PROTOCOLLNPGM(MSG_END_FILE_LIST);
  5082. }
  5083. /**
  5084. * M21: Init SD Card
  5085. */
  5086. inline void gcode_M21() { card.initsd(); }
  5087. /**
  5088. * M22: Release SD Card
  5089. */
  5090. inline void gcode_M22() { card.release(); }
  5091. /**
  5092. * M23: Open a file
  5093. */
  5094. inline void gcode_M23() { card.openFile(parser.string_arg, true); }
  5095. /**
  5096. * M24: Start or Resume SD Print
  5097. */
  5098. inline void gcode_M24() {
  5099. #if ENABLED(PARK_HEAD_ON_PAUSE)
  5100. resume_print();
  5101. #endif
  5102. card.startFileprint();
  5103. print_job_timer.start();
  5104. }
  5105. /**
  5106. * M25: Pause SD Print
  5107. */
  5108. inline void gcode_M25() {
  5109. card.pauseSDPrint();
  5110. print_job_timer.pause();
  5111. #if ENABLED(PARK_HEAD_ON_PAUSE)
  5112. enqueue_and_echo_commands_P(PSTR("M125")); // Must be enqueued with pauseSDPrint set to be last in the buffer
  5113. #endif
  5114. }
  5115. /**
  5116. * M26: Set SD Card file index
  5117. */
  5118. inline void gcode_M26() {
  5119. if (card.cardOK && parser.seen('S'))
  5120. card.setIndex(parser.value_long());
  5121. }
  5122. /**
  5123. * M27: Get SD Card status
  5124. */
  5125. inline void gcode_M27() { card.getStatus(); }
  5126. /**
  5127. * M28: Start SD Write
  5128. */
  5129. inline void gcode_M28() { card.openFile(parser.string_arg, false); }
  5130. /**
  5131. * M29: Stop SD Write
  5132. * Processed in write to file routine above
  5133. */
  5134. inline void gcode_M29() {
  5135. // card.saving = false;
  5136. }
  5137. /**
  5138. * M30 <filename>: Delete SD Card file
  5139. */
  5140. inline void gcode_M30() {
  5141. if (card.cardOK) {
  5142. card.closefile();
  5143. card.removeFile(parser.string_arg);
  5144. }
  5145. }
  5146. #endif // SDSUPPORT
  5147. /**
  5148. * M31: Get the time since the start of SD Print (or last M109)
  5149. */
  5150. inline void gcode_M31() {
  5151. char buffer[21];
  5152. duration_t elapsed = print_job_timer.duration();
  5153. elapsed.toString(buffer);
  5154. lcd_setstatus(buffer);
  5155. SERIAL_ECHO_START;
  5156. SERIAL_ECHOLNPAIR("Print time: ", buffer);
  5157. }
  5158. #if ENABLED(SDSUPPORT)
  5159. /**
  5160. * M32: Select file and start SD Print
  5161. */
  5162. inline void gcode_M32() {
  5163. if (card.sdprinting)
  5164. stepper.synchronize();
  5165. char* namestartpos = parser.string_arg;
  5166. bool call_procedure = parser.seen('P');
  5167. if (card.cardOK) {
  5168. card.openFile(namestartpos, true, call_procedure);
  5169. if (parser.seen('S'))
  5170. card.setIndex(parser.value_long());
  5171. card.startFileprint();
  5172. // Procedure calls count as normal print time.
  5173. if (!call_procedure) print_job_timer.start();
  5174. }
  5175. }
  5176. #if ENABLED(LONG_FILENAME_HOST_SUPPORT)
  5177. /**
  5178. * M33: Get the long full path of a file or folder
  5179. *
  5180. * Parameters:
  5181. * <dospath> Case-insensitive DOS-style path to a file or folder
  5182. *
  5183. * Example:
  5184. * M33 miscel~1/armchair/armcha~1.gco
  5185. *
  5186. * Output:
  5187. * /Miscellaneous/Armchair/Armchair.gcode
  5188. */
  5189. inline void gcode_M33() {
  5190. card.printLongPath(parser.string_arg);
  5191. }
  5192. #endif
  5193. #if ENABLED(SDCARD_SORT_ALPHA) && ENABLED(SDSORT_GCODE)
  5194. /**
  5195. * M34: Set SD Card Sorting Options
  5196. */
  5197. inline void gcode_M34() {
  5198. if (parser.seen('S')) card.setSortOn(parser.value_bool());
  5199. if (parser.seen('F')) {
  5200. int v = parser.value_long();
  5201. card.setSortFolders(v < 0 ? -1 : v > 0 ? 1 : 0);
  5202. }
  5203. //if (parser.seen('R')) card.setSortReverse(parser.value_bool());
  5204. }
  5205. #endif // SDCARD_SORT_ALPHA && SDSORT_GCODE
  5206. /**
  5207. * M928: Start SD Write
  5208. */
  5209. inline void gcode_M928() {
  5210. card.openLogFile(parser.string_arg);
  5211. }
  5212. #endif // SDSUPPORT
  5213. /**
  5214. * Sensitive pin test for M42, M226
  5215. */
  5216. static bool pin_is_protected(uint8_t pin) {
  5217. static const int sensitive_pins[] = SENSITIVE_PINS;
  5218. for (uint8_t i = 0; i < COUNT(sensitive_pins); i++)
  5219. if (sensitive_pins[i] == pin) return true;
  5220. return false;
  5221. }
  5222. /**
  5223. * M42: Change pin status via GCode
  5224. *
  5225. * P<pin> Pin number (LED if omitted)
  5226. * S<byte> Pin status from 0 - 255
  5227. */
  5228. inline void gcode_M42() {
  5229. if (!parser.seen('S')) return;
  5230. int pin_status = parser.value_int();
  5231. if (!WITHIN(pin_status, 0, 255)) return;
  5232. int pin_number = parser.seen('P') ? parser.value_int() : LED_PIN;
  5233. if (pin_number < 0) return;
  5234. if (pin_is_protected(pin_number)) {
  5235. SERIAL_ERROR_START;
  5236. SERIAL_ERRORLNPGM(MSG_ERR_PROTECTED_PIN);
  5237. return;
  5238. }
  5239. pinMode(pin_number, OUTPUT);
  5240. digitalWrite(pin_number, pin_status);
  5241. analogWrite(pin_number, pin_status);
  5242. #if FAN_COUNT > 0
  5243. switch (pin_number) {
  5244. #if HAS_FAN0
  5245. case FAN_PIN: fanSpeeds[0] = pin_status; break;
  5246. #endif
  5247. #if HAS_FAN1
  5248. case FAN1_PIN: fanSpeeds[1] = pin_status; break;
  5249. #endif
  5250. #if HAS_FAN2
  5251. case FAN2_PIN: fanSpeeds[2] = pin_status; break;
  5252. #endif
  5253. }
  5254. #endif
  5255. }
  5256. #if ENABLED(PINS_DEBUGGING)
  5257. #include "pinsDebug.h"
  5258. inline void toggle_pins() {
  5259. const bool I_flag = parser.seen('I') && parser.value_bool();
  5260. const int repeat = parser.seen('R') ? parser.value_int() : 1,
  5261. start = parser.seen('S') ? parser.value_int() : 0,
  5262. end = parser.seen('E') ? parser.value_int() : NUM_DIGITAL_PINS - 1,
  5263. wait = parser.seen('W') ? parser.value_int() : 500;
  5264. for (uint8_t pin = start; pin <= end; pin++) {
  5265. if (!I_flag && pin_is_protected(pin)) {
  5266. SERIAL_ECHOPAIR("Sensitive Pin: ", pin);
  5267. SERIAL_ECHOLNPGM(" untouched.");
  5268. }
  5269. else {
  5270. SERIAL_ECHOPAIR("Pulsing Pin: ", pin);
  5271. pinMode(pin, OUTPUT);
  5272. for (int16_t j = 0; j < repeat; j++) {
  5273. digitalWrite(pin, 0);
  5274. safe_delay(wait);
  5275. digitalWrite(pin, 1);
  5276. safe_delay(wait);
  5277. digitalWrite(pin, 0);
  5278. safe_delay(wait);
  5279. }
  5280. }
  5281. SERIAL_CHAR('\n');
  5282. }
  5283. SERIAL_ECHOLNPGM("Done.");
  5284. } // toggle_pins
  5285. inline void servo_probe_test() {
  5286. #if !(NUM_SERVOS > 0 && HAS_SERVO_0)
  5287. SERIAL_ERROR_START;
  5288. SERIAL_ERRORLNPGM("SERVO not setup");
  5289. #elif !HAS_Z_SERVO_ENDSTOP
  5290. SERIAL_ERROR_START;
  5291. SERIAL_ERRORLNPGM("Z_ENDSTOP_SERVO_NR not setup");
  5292. #else
  5293. const uint8_t probe_index = parser.seen('P') ? parser.value_byte() : Z_ENDSTOP_SERVO_NR;
  5294. SERIAL_PROTOCOLLNPGM("Servo probe test");
  5295. SERIAL_PROTOCOLLNPAIR(". using index: ", probe_index);
  5296. SERIAL_PROTOCOLLNPAIR(". deploy angle: ", z_servo_angle[0]);
  5297. SERIAL_PROTOCOLLNPAIR(". stow angle: ", z_servo_angle[1]);
  5298. bool probe_inverting;
  5299. #if ENABLED(Z_MIN_PROBE_USES_Z_MIN_ENDSTOP_PIN)
  5300. #define PROBE_TEST_PIN Z_MIN_PIN
  5301. SERIAL_PROTOCOLLNPAIR(". probe uses Z_MIN pin: ", PROBE_TEST_PIN);
  5302. SERIAL_PROTOCOLLNPGM(". uses Z_MIN_ENDSTOP_INVERTING (ignores Z_MIN_PROBE_ENDSTOP_INVERTING)");
  5303. SERIAL_PROTOCOLPGM(". Z_MIN_ENDSTOP_INVERTING: ");
  5304. #if Z_MIN_ENDSTOP_INVERTING
  5305. SERIAL_PROTOCOLLNPGM("true");
  5306. #else
  5307. SERIAL_PROTOCOLLNPGM("false");
  5308. #endif
  5309. probe_inverting = Z_MIN_ENDSTOP_INVERTING;
  5310. #elif ENABLED(Z_MIN_PROBE_ENDSTOP)
  5311. #define PROBE_TEST_PIN Z_MIN_PROBE_PIN
  5312. SERIAL_PROTOCOLLNPAIR(". probe uses Z_MIN_PROBE_PIN: ", PROBE_TEST_PIN);
  5313. SERIAL_PROTOCOLLNPGM(". uses Z_MIN_PROBE_ENDSTOP_INVERTING (ignores Z_MIN_ENDSTOP_INVERTING)");
  5314. SERIAL_PROTOCOLPGM(". Z_MIN_PROBE_ENDSTOP_INVERTING: ");
  5315. #if Z_MIN_PROBE_ENDSTOP_INVERTING
  5316. SERIAL_PROTOCOLLNPGM("true");
  5317. #else
  5318. SERIAL_PROTOCOLLNPGM("false");
  5319. #endif
  5320. probe_inverting = Z_MIN_PROBE_ENDSTOP_INVERTING;
  5321. #endif
  5322. SERIAL_PROTOCOLLNPGM(". deploy & stow 4 times");
  5323. pinMode(PROBE_TEST_PIN, INPUT_PULLUP);
  5324. bool deploy_state;
  5325. bool stow_state;
  5326. for (uint8_t i = 0; i < 4; i++) {
  5327. servo[probe_index].move(z_servo_angle[0]); //deploy
  5328. safe_delay(500);
  5329. deploy_state = digitalRead(PROBE_TEST_PIN);
  5330. servo[probe_index].move(z_servo_angle[1]); //stow
  5331. safe_delay(500);
  5332. stow_state = digitalRead(PROBE_TEST_PIN);
  5333. }
  5334. if (probe_inverting != deploy_state) SERIAL_PROTOCOLLNPGM("WARNING - INVERTING setting probably backwards");
  5335. refresh_cmd_timeout();
  5336. if (deploy_state != stow_state) {
  5337. SERIAL_PROTOCOLLNPGM("BLTouch clone detected");
  5338. if (deploy_state) {
  5339. SERIAL_PROTOCOLLNPGM(". DEPLOYED state: HIGH (logic 1)");
  5340. SERIAL_PROTOCOLLNPGM(". STOWED (triggered) state: LOW (logic 0)");
  5341. }
  5342. else {
  5343. SERIAL_PROTOCOLLNPGM(". DEPLOYED state: LOW (logic 0)");
  5344. SERIAL_PROTOCOLLNPGM(". STOWED (triggered) state: HIGH (logic 1)");
  5345. }
  5346. #if ENABLED(BLTOUCH)
  5347. SERIAL_PROTOCOLLNPGM("ERROR: BLTOUCH enabled - set this device up as a Z Servo Probe with inverting as true.");
  5348. #endif
  5349. }
  5350. else { // measure active signal length
  5351. servo[probe_index].move(z_servo_angle[0]); // deploy
  5352. safe_delay(500);
  5353. SERIAL_PROTOCOLLNPGM("please trigger probe");
  5354. uint16_t probe_counter = 0;
  5355. // Allow 30 seconds max for operator to trigger probe
  5356. for (uint16_t j = 0; j < 500 * 30 && probe_counter == 0 ; j++) {
  5357. safe_delay(2);
  5358. if (0 == j % (500 * 1)) // keep cmd_timeout happy
  5359. refresh_cmd_timeout();
  5360. if (deploy_state != digitalRead(PROBE_TEST_PIN)) { // probe triggered
  5361. for (probe_counter = 1; probe_counter < 50 && deploy_state != digitalRead(PROBE_TEST_PIN); ++probe_counter)
  5362. safe_delay(2);
  5363. if (probe_counter == 50)
  5364. SERIAL_PROTOCOLLNPGM("Z Servo Probe detected"); // >= 100mS active time
  5365. else if (probe_counter >= 2)
  5366. SERIAL_PROTOCOLLNPAIR("BLTouch compatible probe detected - pulse width (+/- 4mS): ", probe_counter * 2); // allow 4 - 100mS pulse
  5367. else
  5368. SERIAL_PROTOCOLLNPGM("noise detected - please re-run test"); // less than 2mS pulse
  5369. servo[probe_index].move(z_servo_angle[1]); //stow
  5370. } // pulse detected
  5371. } // for loop waiting for trigger
  5372. if (probe_counter == 0) SERIAL_PROTOCOLLNPGM("trigger not detected");
  5373. } // measure active signal length
  5374. #endif
  5375. } // servo_probe_test
  5376. /**
  5377. * M43: Pin debug - report pin state, watch pins, toggle pins and servo probe test/report
  5378. *
  5379. * M43 - report name and state of pin(s)
  5380. * P<pin> Pin to read or watch. If omitted, reads all pins.
  5381. * I Flag to ignore Marlin's pin protection.
  5382. *
  5383. * M43 W - Watch pins -reporting changes- until reset, click, or M108.
  5384. * P<pin> Pin to read or watch. If omitted, read/watch all pins.
  5385. * I Flag to ignore Marlin's pin protection.
  5386. *
  5387. * M43 E<bool> - Enable / disable background endstop monitoring
  5388. * - Machine continues to operate
  5389. * - Reports changes to endstops
  5390. * - Toggles LED when an endstop changes
  5391. * - Can not reliably catch the 5mS pulse from BLTouch type probes
  5392. *
  5393. * M43 T - Toggle pin(s) and report which pin is being toggled
  5394. * S<pin> - Start Pin number. If not given, will default to 0
  5395. * L<pin> - End Pin number. If not given, will default to last pin defined for this board
  5396. * I - Flag to ignore Marlin's pin protection. Use with caution!!!!
  5397. * R - Repeat pulses on each pin this number of times before continueing to next pin
  5398. * W - Wait time (in miliseconds) between pulses. If not given will default to 500
  5399. *
  5400. * M43 S - Servo probe test
  5401. * P<index> - Probe index (optional - defaults to 0
  5402. */
  5403. inline void gcode_M43() {
  5404. if (parser.seen('T')) { // must be first ot else it's "S" and "E" parameters will execute endstop or servo test
  5405. toggle_pins();
  5406. return;
  5407. }
  5408. // Enable or disable endstop monitoring
  5409. if (parser.seen('E')) {
  5410. endstop_monitor_flag = parser.value_bool();
  5411. SERIAL_PROTOCOLPGM("endstop monitor ");
  5412. SERIAL_PROTOCOL(endstop_monitor_flag ? "en" : "dis");
  5413. SERIAL_PROTOCOLLNPGM("abled");
  5414. return;
  5415. }
  5416. if (parser.seen('S')) {
  5417. servo_probe_test();
  5418. return;
  5419. }
  5420. // Get the range of pins to test or watch
  5421. const uint8_t first_pin = parser.seen('P') ? parser.value_byte() : 0,
  5422. last_pin = parser.seen('P') ? first_pin : NUM_DIGITAL_PINS - 1;
  5423. if (first_pin > last_pin) return;
  5424. const bool ignore_protection = parser.seen('I') && parser.value_bool();
  5425. // Watch until click, M108, or reset
  5426. if (parser.seen('W') && parser.value_bool()) {
  5427. SERIAL_PROTOCOLLNPGM("Watching pins");
  5428. byte pin_state[last_pin - first_pin + 1];
  5429. for (int8_t pin = first_pin; pin <= last_pin; pin++) {
  5430. if (pin_is_protected(pin) && !ignore_protection) continue;
  5431. pinMode(pin, INPUT_PULLUP);
  5432. /*
  5433. if (IS_ANALOG(pin))
  5434. pin_state[pin - first_pin] = analogRead(pin - analogInputToDigitalPin(0)); // int16_t pin_state[...]
  5435. else
  5436. //*/
  5437. pin_state[pin - first_pin] = digitalRead(pin);
  5438. }
  5439. #if HAS_RESUME_CONTINUE
  5440. wait_for_user = true;
  5441. KEEPALIVE_STATE(PAUSED_FOR_USER);
  5442. #endif
  5443. for (;;) {
  5444. for (int8_t pin = first_pin; pin <= last_pin; pin++) {
  5445. if (pin_is_protected(pin)) continue;
  5446. const byte val =
  5447. /*
  5448. IS_ANALOG(pin)
  5449. ? analogRead(pin - analogInputToDigitalPin(0)) : // int16_t val
  5450. :
  5451. //*/
  5452. digitalRead(pin);
  5453. if (val != pin_state[pin - first_pin]) {
  5454. report_pin_state(pin);
  5455. pin_state[pin - first_pin] = val;
  5456. }
  5457. }
  5458. #if HAS_RESUME_CONTINUE
  5459. if (!wait_for_user) {
  5460. KEEPALIVE_STATE(IN_HANDLER);
  5461. break;
  5462. }
  5463. #endif
  5464. safe_delay(500);
  5465. }
  5466. return;
  5467. }
  5468. // Report current state of selected pin(s)
  5469. for (uint8_t pin = first_pin; pin <= last_pin; pin++)
  5470. report_pin_state_extended(pin, ignore_protection);
  5471. }
  5472. #endif // PINS_DEBUGGING
  5473. #if ENABLED(Z_MIN_PROBE_REPEATABILITY_TEST)
  5474. /**
  5475. * M48: Z probe repeatability measurement function.
  5476. *
  5477. * Usage:
  5478. * M48 <P#> <X#> <Y#> <V#> <E> <L#>
  5479. * P = Number of sampled points (4-50, default 10)
  5480. * X = Sample X position
  5481. * Y = Sample Y position
  5482. * V = Verbose level (0-4, default=1)
  5483. * E = Engage Z probe for each reading
  5484. * L = Number of legs of movement before probe
  5485. * S = Schizoid (Or Star if you prefer)
  5486. *
  5487. * This function assumes the bed has been homed. Specifically, that a G28 command
  5488. * as been issued prior to invoking the M48 Z probe repeatability measurement function.
  5489. * Any information generated by a prior G29 Bed leveling command will be lost and need to be
  5490. * regenerated.
  5491. */
  5492. inline void gcode_M48() {
  5493. if (axis_unhomed_error()) return;
  5494. const int8_t verbose_level = parser.seen('V') ? parser.value_byte() : 1;
  5495. if (!WITHIN(verbose_level, 0, 4)) {
  5496. SERIAL_PROTOCOLLNPGM("?(V)erbose level is implausible (0-4).");
  5497. return;
  5498. }
  5499. if (verbose_level > 0)
  5500. SERIAL_PROTOCOLLNPGM("M48 Z-Probe Repeatability Test");
  5501. int8_t n_samples = parser.seen('P') ? parser.value_byte() : 10;
  5502. if (!WITHIN(n_samples, 4, 50)) {
  5503. SERIAL_PROTOCOLLNPGM("?Sample size not plausible (4-50).");
  5504. return;
  5505. }
  5506. const bool stow_probe_after_each = parser.seen('E');
  5507. float X_current = current_position[X_AXIS],
  5508. Y_current = current_position[Y_AXIS];
  5509. const float X_probe_location = parser.seen('X') ? parser.value_linear_units() : X_current + X_PROBE_OFFSET_FROM_EXTRUDER,
  5510. Y_probe_location = parser.seen('Y') ? parser.value_linear_units() : Y_current + Y_PROBE_OFFSET_FROM_EXTRUDER;
  5511. #if DISABLED(DELTA)
  5512. if (!WITHIN(X_probe_location, LOGICAL_X_POSITION(MIN_PROBE_X), LOGICAL_X_POSITION(MAX_PROBE_X))) {
  5513. out_of_range_error(PSTR("X"));
  5514. return;
  5515. }
  5516. if (!WITHIN(Y_probe_location, LOGICAL_Y_POSITION(MIN_PROBE_Y), LOGICAL_Y_POSITION(MAX_PROBE_Y))) {
  5517. out_of_range_error(PSTR("Y"));
  5518. return;
  5519. }
  5520. #else
  5521. if (!position_is_reachable_by_probe_xy(X_probe_location, Y_probe_location)) {
  5522. SERIAL_PROTOCOLLNPGM("? (X,Y) location outside of probeable radius.");
  5523. return;
  5524. }
  5525. #endif
  5526. bool seen_L = parser.seen('L');
  5527. uint8_t n_legs = seen_L ? parser.value_byte() : 0;
  5528. if (n_legs > 15) {
  5529. SERIAL_PROTOCOLLNPGM("?Number of legs in movement not plausible (0-15).");
  5530. return;
  5531. }
  5532. if (n_legs == 1) n_legs = 2;
  5533. bool schizoid_flag = parser.seen('S');
  5534. if (schizoid_flag && !seen_L) n_legs = 7;
  5535. /**
  5536. * Now get everything to the specified probe point So we can safely do a
  5537. * probe to get us close to the bed. If the Z-Axis is far from the bed,
  5538. * we don't want to use that as a starting point for each probe.
  5539. */
  5540. if (verbose_level > 2)
  5541. SERIAL_PROTOCOLLNPGM("Positioning the probe...");
  5542. // Disable bed level correction in M48 because we want the raw data when we probe
  5543. #if HAS_LEVELING
  5544. const bool was_enabled = leveling_is_active();
  5545. set_bed_leveling_enabled(false);
  5546. #endif
  5547. setup_for_endstop_or_probe_move();
  5548. // Move to the first point, deploy, and probe
  5549. const float t = probe_pt(X_probe_location, Y_probe_location, stow_probe_after_each, verbose_level);
  5550. if (isnan(t)) return;
  5551. randomSeed(millis());
  5552. double mean = 0.0, sigma = 0.0, min = 99999.9, max = -99999.9, sample_set[n_samples];
  5553. for (uint8_t n = 0; n < n_samples; n++) {
  5554. if (n_legs) {
  5555. int dir = (random(0, 10) > 5.0) ? -1 : 1; // clockwise or counter clockwise
  5556. float angle = random(0.0, 360.0),
  5557. radius = random(
  5558. #if ENABLED(DELTA)
  5559. DELTA_PROBEABLE_RADIUS / 8, DELTA_PROBEABLE_RADIUS / 3
  5560. #else
  5561. 5, X_MAX_LENGTH / 8
  5562. #endif
  5563. );
  5564. if (verbose_level > 3) {
  5565. SERIAL_ECHOPAIR("Starting radius: ", radius);
  5566. SERIAL_ECHOPAIR(" angle: ", angle);
  5567. SERIAL_ECHOPGM(" Direction: ");
  5568. if (dir > 0) SERIAL_ECHOPGM("Counter-");
  5569. SERIAL_ECHOLNPGM("Clockwise");
  5570. }
  5571. for (uint8_t l = 0; l < n_legs - 1; l++) {
  5572. double delta_angle;
  5573. if (schizoid_flag)
  5574. // The points of a 5 point star are 72 degrees apart. We need to
  5575. // skip a point and go to the next one on the star.
  5576. delta_angle = dir * 2.0 * 72.0;
  5577. else
  5578. // If we do this line, we are just trying to move further
  5579. // around the circle.
  5580. delta_angle = dir * (float) random(25, 45);
  5581. angle += delta_angle;
  5582. while (angle > 360.0) // We probably do not need to keep the angle between 0 and 2*PI, but the
  5583. angle -= 360.0; // Arduino documentation says the trig functions should not be given values
  5584. while (angle < 0.0) // outside of this range. It looks like they behave correctly with
  5585. angle += 360.0; // numbers outside of the range, but just to be safe we clamp them.
  5586. X_current = X_probe_location - (X_PROBE_OFFSET_FROM_EXTRUDER) + cos(RADIANS(angle)) * radius;
  5587. Y_current = Y_probe_location - (Y_PROBE_OFFSET_FROM_EXTRUDER) + sin(RADIANS(angle)) * radius;
  5588. #if DISABLED(DELTA)
  5589. X_current = constrain(X_current, X_MIN_POS, X_MAX_POS);
  5590. Y_current = constrain(Y_current, Y_MIN_POS, Y_MAX_POS);
  5591. #else
  5592. // If we have gone out too far, we can do a simple fix and scale the numbers
  5593. // back in closer to the origin.
  5594. while (!position_is_reachable_by_probe_xy(X_current, Y_current)) {
  5595. X_current *= 0.8;
  5596. Y_current *= 0.8;
  5597. if (verbose_level > 3) {
  5598. SERIAL_ECHOPAIR("Pulling point towards center:", X_current);
  5599. SERIAL_ECHOLNPAIR(", ", Y_current);
  5600. }
  5601. }
  5602. #endif
  5603. if (verbose_level > 3) {
  5604. SERIAL_PROTOCOLPGM("Going to:");
  5605. SERIAL_ECHOPAIR(" X", X_current);
  5606. SERIAL_ECHOPAIR(" Y", Y_current);
  5607. SERIAL_ECHOLNPAIR(" Z", current_position[Z_AXIS]);
  5608. }
  5609. do_blocking_move_to_xy(X_current, Y_current);
  5610. } // n_legs loop
  5611. } // n_legs
  5612. // Probe a single point
  5613. sample_set[n] = probe_pt(X_probe_location, Y_probe_location, stow_probe_after_each, 0);
  5614. /**
  5615. * Get the current mean for the data points we have so far
  5616. */
  5617. double sum = 0.0;
  5618. for (uint8_t j = 0; j <= n; j++) sum += sample_set[j];
  5619. mean = sum / (n + 1);
  5620. NOMORE(min, sample_set[n]);
  5621. NOLESS(max, sample_set[n]);
  5622. /**
  5623. * Now, use that mean to calculate the standard deviation for the
  5624. * data points we have so far
  5625. */
  5626. sum = 0.0;
  5627. for (uint8_t j = 0; j <= n; j++)
  5628. sum += sq(sample_set[j] - mean);
  5629. sigma = sqrt(sum / (n + 1));
  5630. if (verbose_level > 0) {
  5631. if (verbose_level > 1) {
  5632. SERIAL_PROTOCOL(n + 1);
  5633. SERIAL_PROTOCOLPGM(" of ");
  5634. SERIAL_PROTOCOL((int)n_samples);
  5635. SERIAL_PROTOCOLPGM(": z: ");
  5636. SERIAL_PROTOCOL_F(sample_set[n], 3);
  5637. if (verbose_level > 2) {
  5638. SERIAL_PROTOCOLPGM(" mean: ");
  5639. SERIAL_PROTOCOL_F(mean, 4);
  5640. SERIAL_PROTOCOLPGM(" sigma: ");
  5641. SERIAL_PROTOCOL_F(sigma, 6);
  5642. SERIAL_PROTOCOLPGM(" min: ");
  5643. SERIAL_PROTOCOL_F(min, 3);
  5644. SERIAL_PROTOCOLPGM(" max: ");
  5645. SERIAL_PROTOCOL_F(max, 3);
  5646. SERIAL_PROTOCOLPGM(" range: ");
  5647. SERIAL_PROTOCOL_F(max-min, 3);
  5648. }
  5649. SERIAL_EOL;
  5650. }
  5651. }
  5652. } // End of probe loop
  5653. if (STOW_PROBE()) return;
  5654. SERIAL_PROTOCOLPGM("Finished!");
  5655. SERIAL_EOL;
  5656. if (verbose_level > 0) {
  5657. SERIAL_PROTOCOLPGM("Mean: ");
  5658. SERIAL_PROTOCOL_F(mean, 6);
  5659. SERIAL_PROTOCOLPGM(" Min: ");
  5660. SERIAL_PROTOCOL_F(min, 3);
  5661. SERIAL_PROTOCOLPGM(" Max: ");
  5662. SERIAL_PROTOCOL_F(max, 3);
  5663. SERIAL_PROTOCOLPGM(" Range: ");
  5664. SERIAL_PROTOCOL_F(max-min, 3);
  5665. SERIAL_EOL;
  5666. }
  5667. SERIAL_PROTOCOLPGM("Standard Deviation: ");
  5668. SERIAL_PROTOCOL_F(sigma, 6);
  5669. SERIAL_EOL;
  5670. SERIAL_EOL;
  5671. clean_up_after_endstop_or_probe_move();
  5672. // Re-enable bed level correction if it had been on
  5673. #if HAS_LEVELING
  5674. set_bed_leveling_enabled(was_enabled);
  5675. #endif
  5676. report_current_position();
  5677. }
  5678. #endif // Z_MIN_PROBE_REPEATABILITY_TEST
  5679. #if ENABLED(AUTO_BED_LEVELING_UBL) && ENABLED(UBL_G26_MESH_VALIDATION)
  5680. inline void gcode_M49() {
  5681. ubl.g26_debug_flag ^= true;
  5682. SERIAL_PROTOCOLPGM("UBL Debug Flag turned ");
  5683. serialprintPGM(ubl.g26_debug_flag ? PSTR("on.") : PSTR("off."));
  5684. }
  5685. #endif // AUTO_BED_LEVELING_UBL && UBL_G26_MESH_VALIDATION
  5686. /**
  5687. * M75: Start print timer
  5688. */
  5689. inline void gcode_M75() { print_job_timer.start(); }
  5690. /**
  5691. * M76: Pause print timer
  5692. */
  5693. inline void gcode_M76() { print_job_timer.pause(); }
  5694. /**
  5695. * M77: Stop print timer
  5696. */
  5697. inline void gcode_M77() { print_job_timer.stop(); }
  5698. #if ENABLED(PRINTCOUNTER)
  5699. /**
  5700. * M78: Show print statistics
  5701. */
  5702. inline void gcode_M78() {
  5703. // "M78 S78" will reset the statistics
  5704. if (parser.seen('S') && parser.value_int() == 78)
  5705. print_job_timer.initStats();
  5706. else
  5707. print_job_timer.showStats();
  5708. }
  5709. #endif
  5710. /**
  5711. * M104: Set hot end temperature
  5712. */
  5713. inline void gcode_M104() {
  5714. if (get_target_extruder_from_command(104)) return;
  5715. if (DEBUGGING(DRYRUN)) return;
  5716. #if ENABLED(SINGLENOZZLE)
  5717. if (target_extruder != active_extruder) return;
  5718. #endif
  5719. if (parser.seen('S')) {
  5720. const int16_t temp = parser.value_celsius();
  5721. thermalManager.setTargetHotend(temp, target_extruder);
  5722. #if ENABLED(DUAL_X_CARRIAGE)
  5723. if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && target_extruder == 0)
  5724. thermalManager.setTargetHotend(temp ? temp + duplicate_extruder_temp_offset : 0, 1);
  5725. #endif
  5726. #if ENABLED(PRINTJOB_TIMER_AUTOSTART)
  5727. /**
  5728. * Stop the timer at the end of print. Start is managed by 'heat and wait' M109.
  5729. * We use half EXTRUDE_MINTEMP here to allow nozzles to be put into hot
  5730. * standby mode, for instance in a dual extruder setup, without affecting
  5731. * the running print timer.
  5732. */
  5733. if (parser.value_celsius() <= (EXTRUDE_MINTEMP) / 2) {
  5734. print_job_timer.stop();
  5735. LCD_MESSAGEPGM(WELCOME_MSG);
  5736. }
  5737. #endif
  5738. if (parser.value_celsius() > thermalManager.degHotend(target_extruder))
  5739. lcd_status_printf_P(0, PSTR("E%i %s"), target_extruder + 1, MSG_HEATING);
  5740. }
  5741. #if ENABLED(AUTOTEMP)
  5742. planner.autotemp_M104_M109();
  5743. #endif
  5744. }
  5745. #if HAS_TEMP_HOTEND || HAS_TEMP_BED
  5746. void print_heaterstates() {
  5747. #if HAS_TEMP_HOTEND
  5748. SERIAL_PROTOCOLPGM(" T:");
  5749. SERIAL_PROTOCOL(thermalManager.degHotend(target_extruder));
  5750. SERIAL_PROTOCOLPGM(" /");
  5751. SERIAL_PROTOCOL(thermalManager.degTargetHotend(target_extruder));
  5752. #if ENABLED(SHOW_TEMP_ADC_VALUES)
  5753. SERIAL_PROTOCOLPAIR(" (", thermalManager.rawHotendTemp(target_extruder) / OVERSAMPLENR);
  5754. SERIAL_PROTOCOLCHAR(')');
  5755. #endif
  5756. #endif
  5757. #if HAS_TEMP_BED
  5758. SERIAL_PROTOCOLPGM(" B:");
  5759. SERIAL_PROTOCOL(thermalManager.degBed());
  5760. SERIAL_PROTOCOLPGM(" /");
  5761. SERIAL_PROTOCOL(thermalManager.degTargetBed());
  5762. #if ENABLED(SHOW_TEMP_ADC_VALUES)
  5763. SERIAL_PROTOCOLPAIR(" (", thermalManager.rawBedTemp() / OVERSAMPLENR);
  5764. SERIAL_PROTOCOLCHAR(')');
  5765. #endif
  5766. #endif
  5767. #if HOTENDS > 1
  5768. HOTEND_LOOP() {
  5769. SERIAL_PROTOCOLPAIR(" T", e);
  5770. SERIAL_PROTOCOLCHAR(':');
  5771. SERIAL_PROTOCOL(thermalManager.degHotend(e));
  5772. SERIAL_PROTOCOLPGM(" /");
  5773. SERIAL_PROTOCOL(thermalManager.degTargetHotend(e));
  5774. #if ENABLED(SHOW_TEMP_ADC_VALUES)
  5775. SERIAL_PROTOCOLPAIR(" (", thermalManager.rawHotendTemp(e) / OVERSAMPLENR);
  5776. SERIAL_PROTOCOLCHAR(')');
  5777. #endif
  5778. }
  5779. #endif
  5780. SERIAL_PROTOCOLPGM(" @:");
  5781. SERIAL_PROTOCOL(thermalManager.getHeaterPower(target_extruder));
  5782. #if HAS_TEMP_BED
  5783. SERIAL_PROTOCOLPGM(" B@:");
  5784. SERIAL_PROTOCOL(thermalManager.getHeaterPower(-1));
  5785. #endif
  5786. #if HOTENDS > 1
  5787. HOTEND_LOOP() {
  5788. SERIAL_PROTOCOLPAIR(" @", e);
  5789. SERIAL_PROTOCOLCHAR(':');
  5790. SERIAL_PROTOCOL(thermalManager.getHeaterPower(e));
  5791. }
  5792. #endif
  5793. }
  5794. #endif
  5795. /**
  5796. * M105: Read hot end and bed temperature
  5797. */
  5798. inline void gcode_M105() {
  5799. if (get_target_extruder_from_command(105)) return;
  5800. #if HAS_TEMP_HOTEND || HAS_TEMP_BED
  5801. SERIAL_PROTOCOLPGM(MSG_OK);
  5802. print_heaterstates();
  5803. #else // !HAS_TEMP_HOTEND && !HAS_TEMP_BED
  5804. SERIAL_ERROR_START;
  5805. SERIAL_ERRORLNPGM(MSG_ERR_NO_THERMISTORS);
  5806. #endif
  5807. SERIAL_EOL;
  5808. }
  5809. #if ENABLED(AUTO_REPORT_TEMPERATURES) && (HAS_TEMP_HOTEND || HAS_TEMP_BED)
  5810. static uint8_t auto_report_temp_interval;
  5811. static millis_t next_temp_report_ms;
  5812. /**
  5813. * M155: Set temperature auto-report interval. M155 S<seconds>
  5814. */
  5815. inline void gcode_M155() {
  5816. if (parser.seen('S')) {
  5817. auto_report_temp_interval = parser.value_byte();
  5818. NOMORE(auto_report_temp_interval, 60);
  5819. next_temp_report_ms = millis() + 1000UL * auto_report_temp_interval;
  5820. }
  5821. }
  5822. inline void auto_report_temperatures() {
  5823. if (auto_report_temp_interval && ELAPSED(millis(), next_temp_report_ms)) {
  5824. next_temp_report_ms = millis() + 1000UL * auto_report_temp_interval;
  5825. print_heaterstates();
  5826. SERIAL_EOL;
  5827. }
  5828. }
  5829. #endif // AUTO_REPORT_TEMPERATURES
  5830. #if FAN_COUNT > 0
  5831. /**
  5832. * M106: Set Fan Speed
  5833. *
  5834. * S<int> Speed between 0-255
  5835. * P<index> Fan index, if more than one fan
  5836. */
  5837. inline void gcode_M106() {
  5838. uint16_t s = parser.seen('S') ? parser.value_ushort() : 255,
  5839. p = parser.seen('P') ? parser.value_ushort() : 0;
  5840. NOMORE(s, 255);
  5841. if (p < FAN_COUNT) fanSpeeds[p] = s;
  5842. }
  5843. /**
  5844. * M107: Fan Off
  5845. */
  5846. inline void gcode_M107() {
  5847. uint16_t p = parser.seen('P') ? parser.value_ushort() : 0;
  5848. if (p < FAN_COUNT) fanSpeeds[p] = 0;
  5849. }
  5850. #endif // FAN_COUNT > 0
  5851. #if DISABLED(EMERGENCY_PARSER)
  5852. /**
  5853. * M108: Stop the waiting for heaters in M109, M190, M303. Does not affect the target temperature.
  5854. */
  5855. inline void gcode_M108() { wait_for_heatup = false; }
  5856. /**
  5857. * M112: Emergency Stop
  5858. */
  5859. inline void gcode_M112() { kill(PSTR(MSG_KILLED)); }
  5860. /**
  5861. * M410: Quickstop - Abort all planned moves
  5862. *
  5863. * This will stop the carriages mid-move, so most likely they
  5864. * will be out of sync with the stepper position after this.
  5865. */
  5866. inline void gcode_M410() { quickstop_stepper(); }
  5867. #endif
  5868. /**
  5869. * M109: Sxxx Wait for extruder(s) to reach temperature. Waits only when heating.
  5870. * Rxxx Wait for extruder(s) to reach temperature. Waits when heating and cooling.
  5871. */
  5872. #ifndef MIN_COOLING_SLOPE_DEG
  5873. #define MIN_COOLING_SLOPE_DEG 1.50
  5874. #endif
  5875. #ifndef MIN_COOLING_SLOPE_TIME
  5876. #define MIN_COOLING_SLOPE_TIME 60
  5877. #endif
  5878. inline void gcode_M109() {
  5879. if (get_target_extruder_from_command(109)) return;
  5880. if (DEBUGGING(DRYRUN)) return;
  5881. #if ENABLED(SINGLENOZZLE)
  5882. if (target_extruder != active_extruder) return;
  5883. #endif
  5884. const bool no_wait_for_cooling = parser.seen('S');
  5885. if (no_wait_for_cooling || parser.seen('R')) {
  5886. const int16_t temp = parser.value_celsius();
  5887. thermalManager.setTargetHotend(temp, target_extruder);
  5888. #if ENABLED(DUAL_X_CARRIAGE)
  5889. if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && target_extruder == 0)
  5890. thermalManager.setTargetHotend(temp ? temp + duplicate_extruder_temp_offset : 0, 1);
  5891. #endif
  5892. #if ENABLED(PRINTJOB_TIMER_AUTOSTART)
  5893. /**
  5894. * Use half EXTRUDE_MINTEMP to allow nozzles to be put into hot
  5895. * standby mode, (e.g., in a dual extruder setup) without affecting
  5896. * the running print timer.
  5897. */
  5898. if (parser.value_celsius() <= (EXTRUDE_MINTEMP) / 2) {
  5899. print_job_timer.stop();
  5900. LCD_MESSAGEPGM(WELCOME_MSG);
  5901. }
  5902. else
  5903. print_job_timer.start();
  5904. #endif
  5905. if (thermalManager.isHeatingHotend(target_extruder)) lcd_status_printf_P(0, PSTR("E%i %s"), target_extruder + 1, MSG_HEATING);
  5906. }
  5907. else return;
  5908. #if ENABLED(AUTOTEMP)
  5909. planner.autotemp_M104_M109();
  5910. #endif
  5911. #if TEMP_RESIDENCY_TIME > 0
  5912. millis_t residency_start_ms = 0;
  5913. // Loop until the temperature has stabilized
  5914. #define TEMP_CONDITIONS (!residency_start_ms || PENDING(now, residency_start_ms + (TEMP_RESIDENCY_TIME) * 1000UL))
  5915. #else
  5916. // Loop until the temperature is very close target
  5917. #define TEMP_CONDITIONS (wants_to_cool ? thermalManager.isCoolingHotend(target_extruder) : thermalManager.isHeatingHotend(target_extruder))
  5918. #endif
  5919. float target_temp = -1.0, old_temp = 9999.0;
  5920. bool wants_to_cool = false;
  5921. wait_for_heatup = true;
  5922. millis_t now, next_temp_ms = 0, next_cool_check_ms = 0;
  5923. KEEPALIVE_STATE(NOT_BUSY);
  5924. #if ENABLED(PRINTER_EVENT_LEDS)
  5925. const float start_temp = thermalManager.degHotend(target_extruder);
  5926. uint8_t old_blue = 0;
  5927. #endif
  5928. do {
  5929. // Target temperature might be changed during the loop
  5930. if (target_temp != thermalManager.degTargetHotend(target_extruder)) {
  5931. wants_to_cool = thermalManager.isCoolingHotend(target_extruder);
  5932. target_temp = thermalManager.degTargetHotend(target_extruder);
  5933. // Exit if S<lower>, continue if S<higher>, R<lower>, or R<higher>
  5934. if (no_wait_for_cooling && wants_to_cool) break;
  5935. }
  5936. now = millis();
  5937. if (ELAPSED(now, next_temp_ms)) { //Print temp & remaining time every 1s while waiting
  5938. next_temp_ms = now + 1000UL;
  5939. print_heaterstates();
  5940. #if TEMP_RESIDENCY_TIME > 0
  5941. SERIAL_PROTOCOLPGM(" W:");
  5942. if (residency_start_ms) {
  5943. long rem = (((TEMP_RESIDENCY_TIME) * 1000UL) - (now - residency_start_ms)) / 1000UL;
  5944. SERIAL_PROTOCOLLN(rem);
  5945. }
  5946. else {
  5947. SERIAL_PROTOCOLLNPGM("?");
  5948. }
  5949. #else
  5950. SERIAL_EOL;
  5951. #endif
  5952. }
  5953. idle();
  5954. refresh_cmd_timeout(); // to prevent stepper_inactive_time from running out
  5955. const float temp = thermalManager.degHotend(target_extruder);
  5956. #if ENABLED(PRINTER_EVENT_LEDS)
  5957. // Gradually change LED strip from violet to red as nozzle heats up
  5958. if (!wants_to_cool) {
  5959. const uint8_t blue = map(constrain(temp, start_temp, target_temp), start_temp, target_temp, 255, 0);
  5960. if (blue != old_blue) set_led_color(255, 0, (old_blue = blue));
  5961. }
  5962. #endif
  5963. #if TEMP_RESIDENCY_TIME > 0
  5964. const float temp_diff = fabs(target_temp - temp);
  5965. if (!residency_start_ms) {
  5966. // Start the TEMP_RESIDENCY_TIME timer when we reach target temp for the first time.
  5967. if (temp_diff < TEMP_WINDOW) residency_start_ms = now;
  5968. }
  5969. else if (temp_diff > TEMP_HYSTERESIS) {
  5970. // Restart the timer whenever the temperature falls outside the hysteresis.
  5971. residency_start_ms = now;
  5972. }
  5973. #endif
  5974. // Prevent a wait-forever situation if R is misused i.e. M109 R0
  5975. if (wants_to_cool) {
  5976. // break after MIN_COOLING_SLOPE_TIME seconds
  5977. // if the temperature did not drop at least MIN_COOLING_SLOPE_DEG
  5978. if (!next_cool_check_ms || ELAPSED(now, next_cool_check_ms)) {
  5979. if (old_temp - temp < MIN_COOLING_SLOPE_DEG) break;
  5980. next_cool_check_ms = now + 1000UL * MIN_COOLING_SLOPE_TIME;
  5981. old_temp = temp;
  5982. }
  5983. }
  5984. } while (wait_for_heatup && TEMP_CONDITIONS);
  5985. if (wait_for_heatup) {
  5986. LCD_MESSAGEPGM(MSG_HEATING_COMPLETE);
  5987. #if ENABLED(PRINTER_EVENT_LEDS)
  5988. #if ENABLED(RGBW_LED)
  5989. set_led_color(0, 0, 0, 255); // Turn on the WHITE LED
  5990. #else
  5991. set_led_color(255, 255, 255); // Set LEDs All On
  5992. #endif
  5993. #endif
  5994. }
  5995. KEEPALIVE_STATE(IN_HANDLER);
  5996. }
  5997. #if HAS_TEMP_BED
  5998. #ifndef MIN_COOLING_SLOPE_DEG_BED
  5999. #define MIN_COOLING_SLOPE_DEG_BED 1.50
  6000. #endif
  6001. #ifndef MIN_COOLING_SLOPE_TIME_BED
  6002. #define MIN_COOLING_SLOPE_TIME_BED 60
  6003. #endif
  6004. /**
  6005. * M190: Sxxx Wait for bed current temp to reach target temp. Waits only when heating
  6006. * Rxxx Wait for bed current temp to reach target temp. Waits when heating and cooling
  6007. */
  6008. inline void gcode_M190() {
  6009. if (DEBUGGING(DRYRUN)) return;
  6010. LCD_MESSAGEPGM(MSG_BED_HEATING);
  6011. const bool no_wait_for_cooling = parser.seen('S');
  6012. if (no_wait_for_cooling || parser.seen('R')) {
  6013. thermalManager.setTargetBed(parser.value_celsius());
  6014. #if ENABLED(PRINTJOB_TIMER_AUTOSTART)
  6015. if (parser.value_celsius() > BED_MINTEMP)
  6016. print_job_timer.start();
  6017. #endif
  6018. }
  6019. else return;
  6020. #if TEMP_BED_RESIDENCY_TIME > 0
  6021. millis_t residency_start_ms = 0;
  6022. // Loop until the temperature has stabilized
  6023. #define TEMP_BED_CONDITIONS (!residency_start_ms || PENDING(now, residency_start_ms + (TEMP_BED_RESIDENCY_TIME) * 1000UL))
  6024. #else
  6025. // Loop until the temperature is very close target
  6026. #define TEMP_BED_CONDITIONS (wants_to_cool ? thermalManager.isCoolingBed() : thermalManager.isHeatingBed())
  6027. #endif
  6028. float target_temp = -1.0, old_temp = 9999.0;
  6029. bool wants_to_cool = false;
  6030. wait_for_heatup = true;
  6031. millis_t now, next_temp_ms = 0, next_cool_check_ms = 0;
  6032. KEEPALIVE_STATE(NOT_BUSY);
  6033. target_extruder = active_extruder; // for print_heaterstates
  6034. #if ENABLED(PRINTER_EVENT_LEDS)
  6035. const float start_temp = thermalManager.degBed();
  6036. uint8_t old_red = 255;
  6037. #endif
  6038. do {
  6039. // Target temperature might be changed during the loop
  6040. if (target_temp != thermalManager.degTargetBed()) {
  6041. wants_to_cool = thermalManager.isCoolingBed();
  6042. target_temp = thermalManager.degTargetBed();
  6043. // Exit if S<lower>, continue if S<higher>, R<lower>, or R<higher>
  6044. if (no_wait_for_cooling && wants_to_cool) break;
  6045. }
  6046. now = millis();
  6047. if (ELAPSED(now, next_temp_ms)) { //Print Temp Reading every 1 second while heating up.
  6048. next_temp_ms = now + 1000UL;
  6049. print_heaterstates();
  6050. #if TEMP_BED_RESIDENCY_TIME > 0
  6051. SERIAL_PROTOCOLPGM(" W:");
  6052. if (residency_start_ms) {
  6053. long rem = (((TEMP_BED_RESIDENCY_TIME) * 1000UL) - (now - residency_start_ms)) / 1000UL;
  6054. SERIAL_PROTOCOLLN(rem);
  6055. }
  6056. else {
  6057. SERIAL_PROTOCOLLNPGM("?");
  6058. }
  6059. #else
  6060. SERIAL_EOL;
  6061. #endif
  6062. }
  6063. idle();
  6064. refresh_cmd_timeout(); // to prevent stepper_inactive_time from running out
  6065. const float temp = thermalManager.degBed();
  6066. #if ENABLED(PRINTER_EVENT_LEDS)
  6067. // Gradually change LED strip from blue to violet as bed heats up
  6068. if (!wants_to_cool) {
  6069. const uint8_t red = map(constrain(temp, start_temp, target_temp), start_temp, target_temp, 0, 255);
  6070. if (red != old_red) set_led_color((old_red = red), 0, 255);
  6071. }
  6072. #endif
  6073. #if TEMP_BED_RESIDENCY_TIME > 0
  6074. const float temp_diff = fabs(target_temp - temp);
  6075. if (!residency_start_ms) {
  6076. // Start the TEMP_BED_RESIDENCY_TIME timer when we reach target temp for the first time.
  6077. if (temp_diff < TEMP_BED_WINDOW) residency_start_ms = now;
  6078. }
  6079. else if (temp_diff > TEMP_BED_HYSTERESIS) {
  6080. // Restart the timer whenever the temperature falls outside the hysteresis.
  6081. residency_start_ms = now;
  6082. }
  6083. #endif // TEMP_BED_RESIDENCY_TIME > 0
  6084. // Prevent a wait-forever situation if R is misused i.e. M190 R0
  6085. if (wants_to_cool) {
  6086. // Break after MIN_COOLING_SLOPE_TIME_BED seconds
  6087. // if the temperature did not drop at least MIN_COOLING_SLOPE_DEG_BED
  6088. if (!next_cool_check_ms || ELAPSED(now, next_cool_check_ms)) {
  6089. if (old_temp - temp < MIN_COOLING_SLOPE_DEG_BED) break;
  6090. next_cool_check_ms = now + 1000UL * MIN_COOLING_SLOPE_TIME_BED;
  6091. old_temp = temp;
  6092. }
  6093. }
  6094. } while (wait_for_heatup && TEMP_BED_CONDITIONS);
  6095. if (wait_for_heatup) LCD_MESSAGEPGM(MSG_BED_DONE);
  6096. KEEPALIVE_STATE(IN_HANDLER);
  6097. }
  6098. #endif // HAS_TEMP_BED
  6099. /**
  6100. * M110: Set Current Line Number
  6101. */
  6102. inline void gcode_M110() {
  6103. if (parser.seen('N')) gcode_LastN = parser.value_long();
  6104. }
  6105. /**
  6106. * M111: Set the debug level
  6107. */
  6108. inline void gcode_M111() {
  6109. marlin_debug_flags = parser.seen('S') ? parser.value_byte() : (uint8_t)DEBUG_NONE;
  6110. const static char str_debug_1[] PROGMEM = MSG_DEBUG_ECHO;
  6111. const static char str_debug_2[] PROGMEM = MSG_DEBUG_INFO;
  6112. const static char str_debug_4[] PROGMEM = MSG_DEBUG_ERRORS;
  6113. const static char str_debug_8[] PROGMEM = MSG_DEBUG_DRYRUN;
  6114. const static char str_debug_16[] PROGMEM = MSG_DEBUG_COMMUNICATION;
  6115. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6116. const static char str_debug_32[] PROGMEM = MSG_DEBUG_LEVELING;
  6117. #endif
  6118. const static char* const debug_strings[] PROGMEM = {
  6119. str_debug_1, str_debug_2, str_debug_4, str_debug_8, str_debug_16
  6120. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6121. , str_debug_32
  6122. #endif
  6123. };
  6124. SERIAL_ECHO_START;
  6125. SERIAL_ECHOPGM(MSG_DEBUG_PREFIX);
  6126. if (marlin_debug_flags) {
  6127. uint8_t comma = 0;
  6128. for (uint8_t i = 0; i < COUNT(debug_strings); i++) {
  6129. if (TEST(marlin_debug_flags, i)) {
  6130. if (comma++) SERIAL_CHAR(',');
  6131. serialprintPGM((char*)pgm_read_word(&debug_strings[i]));
  6132. }
  6133. }
  6134. }
  6135. else {
  6136. SERIAL_ECHOPGM(MSG_DEBUG_OFF);
  6137. }
  6138. SERIAL_EOL;
  6139. }
  6140. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  6141. /**
  6142. * M113: Get or set Host Keepalive interval (0 to disable)
  6143. *
  6144. * S<seconds> Optional. Set the keepalive interval.
  6145. */
  6146. inline void gcode_M113() {
  6147. if (parser.seen('S')) {
  6148. host_keepalive_interval = parser.value_byte();
  6149. NOMORE(host_keepalive_interval, 60);
  6150. }
  6151. else {
  6152. SERIAL_ECHO_START;
  6153. SERIAL_ECHOLNPAIR("M113 S", (unsigned long)host_keepalive_interval);
  6154. }
  6155. }
  6156. #endif
  6157. #if ENABLED(BARICUDA)
  6158. #if HAS_HEATER_1
  6159. /**
  6160. * M126: Heater 1 valve open
  6161. */
  6162. inline void gcode_M126() { baricuda_valve_pressure = parser.seen('S') ? parser.value_byte() : 255; }
  6163. /**
  6164. * M127: Heater 1 valve close
  6165. */
  6166. inline void gcode_M127() { baricuda_valve_pressure = 0; }
  6167. #endif
  6168. #if HAS_HEATER_2
  6169. /**
  6170. * M128: Heater 2 valve open
  6171. */
  6172. inline void gcode_M128() { baricuda_e_to_p_pressure = parser.seen('S') ? parser.value_byte() : 255; }
  6173. /**
  6174. * M129: Heater 2 valve close
  6175. */
  6176. inline void gcode_M129() { baricuda_e_to_p_pressure = 0; }
  6177. #endif
  6178. #endif // BARICUDA
  6179. /**
  6180. * M140: Set bed temperature
  6181. */
  6182. inline void gcode_M140() {
  6183. if (DEBUGGING(DRYRUN)) return;
  6184. if (parser.seen('S')) thermalManager.setTargetBed(parser.value_celsius());
  6185. }
  6186. #if ENABLED(ULTIPANEL)
  6187. /**
  6188. * M145: Set the heatup state for a material in the LCD menu
  6189. *
  6190. * S<material> (0=PLA, 1=ABS)
  6191. * H<hotend temp>
  6192. * B<bed temp>
  6193. * F<fan speed>
  6194. */
  6195. inline void gcode_M145() {
  6196. uint8_t material = parser.seen('S') ? (uint8_t)parser.value_int() : 0;
  6197. if (material >= COUNT(lcd_preheat_hotend_temp)) {
  6198. SERIAL_ERROR_START;
  6199. SERIAL_ERRORLNPGM(MSG_ERR_MATERIAL_INDEX);
  6200. }
  6201. else {
  6202. int v;
  6203. if (parser.seen('H')) {
  6204. v = parser.value_int();
  6205. lcd_preheat_hotend_temp[material] = constrain(v, EXTRUDE_MINTEMP, HEATER_0_MAXTEMP - 15);
  6206. }
  6207. if (parser.seen('F')) {
  6208. v = parser.value_int();
  6209. lcd_preheat_fan_speed[material] = constrain(v, 0, 255);
  6210. }
  6211. #if TEMP_SENSOR_BED != 0
  6212. if (parser.seen('B')) {
  6213. v = parser.value_int();
  6214. lcd_preheat_bed_temp[material] = constrain(v, BED_MINTEMP, BED_MAXTEMP - 15);
  6215. }
  6216. #endif
  6217. }
  6218. }
  6219. #endif // ULTIPANEL
  6220. #if ENABLED(TEMPERATURE_UNITS_SUPPORT)
  6221. /**
  6222. * M149: Set temperature units
  6223. */
  6224. inline void gcode_M149() {
  6225. if (parser.seen('C')) parser.set_input_temp_units(TEMPUNIT_C);
  6226. else if (parser.seen('K')) parser.set_input_temp_units(TEMPUNIT_K);
  6227. else if (parser.seen('F')) parser.set_input_temp_units(TEMPUNIT_F);
  6228. }
  6229. #endif
  6230. #if HAS_POWER_SWITCH
  6231. /**
  6232. * M80 : Turn on the Power Supply
  6233. * M80 S : Report the current state and exit
  6234. */
  6235. inline void gcode_M80() {
  6236. // S: Report the current power supply state and exit
  6237. if (parser.seen('S')) {
  6238. serialprintPGM(powersupply_on ? PSTR("PS:1\n") : PSTR("PS:0\n"));
  6239. return;
  6240. }
  6241. OUT_WRITE(PS_ON_PIN, PS_ON_AWAKE); // GND
  6242. /**
  6243. * If you have a switch on suicide pin, this is useful
  6244. * if you want to start another print with suicide feature after
  6245. * a print without suicide...
  6246. */
  6247. #if HAS_SUICIDE
  6248. OUT_WRITE(SUICIDE_PIN, HIGH);
  6249. #endif
  6250. #if ENABLED(HAVE_TMC2130)
  6251. delay(100);
  6252. tmc2130_init(); // Settings only stick when the driver has power
  6253. #endif
  6254. powersupply_on = true;
  6255. #if ENABLED(ULTIPANEL)
  6256. LCD_MESSAGEPGM(WELCOME_MSG);
  6257. #endif
  6258. }
  6259. #endif // HAS_POWER_SWITCH
  6260. /**
  6261. * M81: Turn off Power, including Power Supply, if there is one.
  6262. *
  6263. * This code should ALWAYS be available for EMERGENCY SHUTDOWN!
  6264. */
  6265. inline void gcode_M81() {
  6266. thermalManager.disable_all_heaters();
  6267. stepper.finish_and_disable();
  6268. #if FAN_COUNT > 0
  6269. for (uint8_t i = 0; i < FAN_COUNT; i++) fanSpeeds[i] = 0;
  6270. #if ENABLED(PROBING_FANS_OFF)
  6271. fans_paused = false;
  6272. ZERO(paused_fanSpeeds);
  6273. #endif
  6274. #endif
  6275. safe_delay(1000); // Wait 1 second before switching off
  6276. #if HAS_SUICIDE
  6277. stepper.synchronize();
  6278. suicide();
  6279. #elif HAS_POWER_SWITCH
  6280. OUT_WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  6281. powersupply_on = false;
  6282. #endif
  6283. #if ENABLED(ULTIPANEL)
  6284. LCD_MESSAGEPGM(MACHINE_NAME " " MSG_OFF ".");
  6285. #endif
  6286. }
  6287. /**
  6288. * M82: Set E codes absolute (default)
  6289. */
  6290. inline void gcode_M82() { axis_relative_modes[E_AXIS] = false; }
  6291. /**
  6292. * M83: Set E codes relative while in Absolute Coordinates (G90) mode
  6293. */
  6294. inline void gcode_M83() { axis_relative_modes[E_AXIS] = true; }
  6295. /**
  6296. * M18, M84: Disable stepper motors
  6297. */
  6298. inline void gcode_M18_M84() {
  6299. if (parser.seen('S')) {
  6300. stepper_inactive_time = parser.value_millis_from_seconds();
  6301. }
  6302. else {
  6303. bool all_axis = !((parser.seen('X')) || (parser.seen('Y')) || (parser.seen('Z')) || (parser.seen('E')));
  6304. if (all_axis) {
  6305. stepper.finish_and_disable();
  6306. }
  6307. else {
  6308. stepper.synchronize();
  6309. if (parser.seen('X')) disable_X();
  6310. if (parser.seen('Y')) disable_Y();
  6311. if (parser.seen('Z')) disable_Z();
  6312. #if ((E0_ENABLE_PIN != X_ENABLE_PIN) && (E1_ENABLE_PIN != Y_ENABLE_PIN)) // Only enable on boards that have seperate ENABLE_PINS
  6313. if (parser.seen('E')) disable_e_steppers();
  6314. #endif
  6315. }
  6316. }
  6317. }
  6318. /**
  6319. * M85: Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
  6320. */
  6321. inline void gcode_M85() {
  6322. if (parser.seen('S')) max_inactive_time = parser.value_millis_from_seconds();
  6323. }
  6324. /**
  6325. * Multi-stepper support for M92, M201, M203
  6326. */
  6327. #if ENABLED(DISTINCT_E_FACTORS)
  6328. #define GET_TARGET_EXTRUDER(CMD) if (get_target_extruder_from_command(CMD)) return
  6329. #define TARGET_EXTRUDER target_extruder
  6330. #else
  6331. #define GET_TARGET_EXTRUDER(CMD) NOOP
  6332. #define TARGET_EXTRUDER 0
  6333. #endif
  6334. /**
  6335. * M92: Set axis steps-per-unit for one or more axes, X, Y, Z, and E.
  6336. * (Follows the same syntax as G92)
  6337. *
  6338. * With multiple extruders use T to specify which one.
  6339. */
  6340. inline void gcode_M92() {
  6341. GET_TARGET_EXTRUDER(92);
  6342. LOOP_XYZE(i) {
  6343. if (parser.seen(axis_codes[i])) {
  6344. if (i == E_AXIS) {
  6345. const float value = parser.value_per_axis_unit((AxisEnum)(E_AXIS + TARGET_EXTRUDER));
  6346. if (value < 20.0) {
  6347. float factor = planner.axis_steps_per_mm[E_AXIS + TARGET_EXTRUDER] / value; // increase e constants if M92 E14 is given for netfab.
  6348. planner.max_jerk[E_AXIS] *= factor;
  6349. planner.max_feedrate_mm_s[E_AXIS + TARGET_EXTRUDER] *= factor;
  6350. planner.max_acceleration_steps_per_s2[E_AXIS + TARGET_EXTRUDER] *= factor;
  6351. }
  6352. planner.axis_steps_per_mm[E_AXIS + TARGET_EXTRUDER] = value;
  6353. }
  6354. else {
  6355. planner.axis_steps_per_mm[i] = parser.value_per_axis_unit((AxisEnum)i);
  6356. }
  6357. }
  6358. }
  6359. planner.refresh_positioning();
  6360. }
  6361. /**
  6362. * Output the current position to serial
  6363. */
  6364. static void report_current_position() {
  6365. SERIAL_PROTOCOLPGM("X:");
  6366. SERIAL_PROTOCOL(current_position[X_AXIS]);
  6367. SERIAL_PROTOCOLPGM(" Y:");
  6368. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  6369. SERIAL_PROTOCOLPGM(" Z:");
  6370. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  6371. SERIAL_PROTOCOLPGM(" E:");
  6372. SERIAL_PROTOCOL(current_position[E_AXIS]);
  6373. stepper.report_positions();
  6374. #if IS_SCARA
  6375. SERIAL_PROTOCOLPAIR("SCARA Theta:", stepper.get_axis_position_degrees(A_AXIS));
  6376. SERIAL_PROTOCOLLNPAIR(" Psi+Theta:", stepper.get_axis_position_degrees(B_AXIS));
  6377. SERIAL_EOL;
  6378. #endif
  6379. }
  6380. /**
  6381. * M114: Output current position to serial port
  6382. */
  6383. inline void gcode_M114() { stepper.synchronize(); report_current_position(); }
  6384. /**
  6385. * M115: Capabilities string
  6386. */
  6387. inline void gcode_M115() {
  6388. SERIAL_PROTOCOLLNPGM(MSG_M115_REPORT);
  6389. #if ENABLED(EXTENDED_CAPABILITIES_REPORT)
  6390. // EEPROM (M500, M501)
  6391. #if ENABLED(EEPROM_SETTINGS)
  6392. SERIAL_PROTOCOLLNPGM("Cap:EEPROM:1");
  6393. #else
  6394. SERIAL_PROTOCOLLNPGM("Cap:EEPROM:0");
  6395. #endif
  6396. // AUTOREPORT_TEMP (M155)
  6397. #if ENABLED(AUTO_REPORT_TEMPERATURES)
  6398. SERIAL_PROTOCOLLNPGM("Cap:AUTOREPORT_TEMP:1");
  6399. #else
  6400. SERIAL_PROTOCOLLNPGM("Cap:AUTOREPORT_TEMP:0");
  6401. #endif
  6402. // PROGRESS (M530 S L, M531 <file>, M532 X L)
  6403. SERIAL_PROTOCOLLNPGM("Cap:PROGRESS:0");
  6404. // AUTOLEVEL (G29)
  6405. #if HAS_ABL
  6406. SERIAL_PROTOCOLLNPGM("Cap:AUTOLEVEL:1");
  6407. #else
  6408. SERIAL_PROTOCOLLNPGM("Cap:AUTOLEVEL:0");
  6409. #endif
  6410. // Z_PROBE (G30)
  6411. #if HAS_BED_PROBE
  6412. SERIAL_PROTOCOLLNPGM("Cap:Z_PROBE:1");
  6413. #else
  6414. SERIAL_PROTOCOLLNPGM("Cap:Z_PROBE:0");
  6415. #endif
  6416. // MESH_REPORT (M420 V)
  6417. #if HAS_LEVELING
  6418. SERIAL_PROTOCOLLNPGM("Cap:LEVELING_DATA:1");
  6419. #else
  6420. SERIAL_PROTOCOLLNPGM("Cap:LEVELING_DATA:0");
  6421. #endif
  6422. // SOFTWARE_POWER (G30)
  6423. #if HAS_POWER_SWITCH
  6424. SERIAL_PROTOCOLLNPGM("Cap:SOFTWARE_POWER:1");
  6425. #else
  6426. SERIAL_PROTOCOLLNPGM("Cap:SOFTWARE_POWER:0");
  6427. #endif
  6428. // TOGGLE_LIGHTS (M355)
  6429. #if HAS_CASE_LIGHT
  6430. SERIAL_PROTOCOLLNPGM("Cap:TOGGLE_LIGHTS:1");
  6431. #else
  6432. SERIAL_PROTOCOLLNPGM("Cap:TOGGLE_LIGHTS:0");
  6433. #endif
  6434. // EMERGENCY_PARSER (M108, M112, M410)
  6435. #if ENABLED(EMERGENCY_PARSER)
  6436. SERIAL_PROTOCOLLNPGM("Cap:EMERGENCY_PARSER:1");
  6437. #else
  6438. SERIAL_PROTOCOLLNPGM("Cap:EMERGENCY_PARSER:0");
  6439. #endif
  6440. #endif // EXTENDED_CAPABILITIES_REPORT
  6441. }
  6442. /**
  6443. * M117: Set LCD Status Message
  6444. */
  6445. inline void gcode_M117() {
  6446. lcd_setstatus(parser.string_arg);
  6447. }
  6448. /**
  6449. * M119: Output endstop states to serial output
  6450. */
  6451. inline void gcode_M119() { endstops.M119(); }
  6452. /**
  6453. * M120: Enable endstops and set non-homing endstop state to "enabled"
  6454. */
  6455. inline void gcode_M120() { endstops.enable_globally(true); }
  6456. /**
  6457. * M121: Disable endstops and set non-homing endstop state to "disabled"
  6458. */
  6459. inline void gcode_M121() { endstops.enable_globally(false); }
  6460. #if ENABLED(PARK_HEAD_ON_PAUSE)
  6461. /**
  6462. * M125: Store current position and move to filament change position.
  6463. * Called on pause (by M25) to prevent material leaking onto the
  6464. * object. On resume (M24) the head will be moved back and the
  6465. * print will resume.
  6466. *
  6467. * If Marlin is compiled without SD Card support, M125 can be
  6468. * used directly to pause the print and move to park position,
  6469. * resuming with a button click or M108.
  6470. *
  6471. * L = override retract length
  6472. * X = override X
  6473. * Y = override Y
  6474. * Z = override Z raise
  6475. */
  6476. inline void gcode_M125() {
  6477. // Initial retract before move to filament change position
  6478. const float retract = parser.seen('L') ? parser.value_axis_units(E_AXIS) : 0
  6479. #if defined(PAUSE_PARK_RETRACT_LENGTH) && PAUSE_PARK_RETRACT_LENGTH > 0
  6480. - (PAUSE_PARK_RETRACT_LENGTH)
  6481. #endif
  6482. ;
  6483. // Lift Z axis
  6484. const float z_lift = parser.seen('Z') ? parser.value_linear_units() :
  6485. #if defined(PAUSE_PARK_Z_ADD) && PAUSE_PARK_Z_ADD > 0
  6486. PAUSE_PARK_Z_ADD
  6487. #else
  6488. 0
  6489. #endif
  6490. ;
  6491. // Move XY axes to filament change position or given position
  6492. const float x_pos = parser.seen('X') ? parser.value_linear_units() : 0
  6493. #ifdef PAUSE_PARK_X_POS
  6494. + PAUSE_PARK_X_POS
  6495. #endif
  6496. ;
  6497. const float y_pos = parser.seen('Y') ? parser.value_linear_units() : 0
  6498. #ifdef PAUSE_PARK_Y_POS
  6499. + PAUSE_PARK_Y_POS
  6500. #endif
  6501. ;
  6502. #if HOTENDS > 1 && DISABLED(DUAL_X_CARRIAGE)
  6503. if (active_extruder > 0) {
  6504. if (!parser.seen('X')) x_pos += hotend_offset[X_AXIS][active_extruder];
  6505. if (!parser.seen('Y')) y_pos += hotend_offset[Y_AXIS][active_extruder];
  6506. }
  6507. #endif
  6508. const bool job_running = print_job_timer.isRunning();
  6509. if (pause_print(retract, z_lift, x_pos, y_pos)) {
  6510. #if DISABLED(SDSUPPORT)
  6511. // Wait for lcd click or M108
  6512. wait_for_filament_reload();
  6513. // Return to print position and continue
  6514. resume_print();
  6515. if (job_running) print_job_timer.start();
  6516. #endif
  6517. }
  6518. }
  6519. #endif // PARK_HEAD_ON_PAUSE
  6520. #if HAS_COLOR_LEDS
  6521. /**
  6522. * M150: Set Status LED Color - Use R-U-B-W for R-G-B-W
  6523. *
  6524. * Always sets all 3 or 4 components. If a component is left out, set to 0.
  6525. *
  6526. * Examples:
  6527. *
  6528. * M150 R255 ; Turn LED red
  6529. * M150 R255 U127 ; Turn LED orange (PWM only)
  6530. * M150 ; Turn LED off
  6531. * M150 R U B ; Turn LED white
  6532. * M150 W ; Turn LED white using a white LED
  6533. *
  6534. */
  6535. inline void gcode_M150() {
  6536. set_led_color(
  6537. parser.seen('R') ? (parser.has_value() ? parser.value_byte() : 255) : 0,
  6538. parser.seen('U') ? (parser.has_value() ? parser.value_byte() : 255) : 0,
  6539. parser.seen('B') ? (parser.has_value() ? parser.value_byte() : 255) : 0
  6540. #if ENABLED(RGBW_LED)
  6541. , parser.seen('W') ? (parser.has_value() ? parser.value_byte() : 255) : 0
  6542. #endif
  6543. );
  6544. }
  6545. #endif // BLINKM || RGB_LED
  6546. /**
  6547. * M200: Set filament diameter and set E axis units to cubic units
  6548. *
  6549. * T<extruder> - Optional extruder number. Current extruder if omitted.
  6550. * D<linear> - Diameter of the filament. Use "D0" to switch back to linear units on the E axis.
  6551. */
  6552. inline void gcode_M200() {
  6553. if (get_target_extruder_from_command(200)) return;
  6554. if (parser.seen('D')) {
  6555. // setting any extruder filament size disables volumetric on the assumption that
  6556. // slicers either generate in extruder values as cubic mm or as as filament feeds
  6557. // for all extruders
  6558. volumetric_enabled = (parser.value_linear_units() != 0.0);
  6559. if (volumetric_enabled) {
  6560. filament_size[target_extruder] = parser.value_linear_units();
  6561. // make sure all extruders have some sane value for the filament size
  6562. for (uint8_t i = 0; i < COUNT(filament_size); i++)
  6563. if (! filament_size[i]) filament_size[i] = DEFAULT_NOMINAL_FILAMENT_DIA;
  6564. }
  6565. }
  6566. calculate_volumetric_multipliers();
  6567. }
  6568. /**
  6569. * M201: Set max acceleration in units/s^2 for print moves (M201 X1000 Y1000)
  6570. *
  6571. * With multiple extruders use T to specify which one.
  6572. */
  6573. inline void gcode_M201() {
  6574. GET_TARGET_EXTRUDER(201);
  6575. LOOP_XYZE(i) {
  6576. if (parser.seen(axis_codes[i])) {
  6577. const uint8_t a = i + (i == E_AXIS ? TARGET_EXTRUDER : 0);
  6578. planner.max_acceleration_mm_per_s2[a] = parser.value_axis_units((AxisEnum)a);
  6579. }
  6580. }
  6581. // 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)
  6582. planner.reset_acceleration_rates();
  6583. }
  6584. #if 0 // Not used for Sprinter/grbl gen6
  6585. inline void gcode_M202() {
  6586. LOOP_XYZE(i) {
  6587. 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];
  6588. }
  6589. }
  6590. #endif
  6591. /**
  6592. * M203: Set maximum feedrate that your machine can sustain (M203 X200 Y200 Z300 E10000) in units/sec
  6593. *
  6594. * With multiple extruders use T to specify which one.
  6595. */
  6596. inline void gcode_M203() {
  6597. GET_TARGET_EXTRUDER(203);
  6598. LOOP_XYZE(i)
  6599. if (parser.seen(axis_codes[i])) {
  6600. const uint8_t a = i + (i == E_AXIS ? TARGET_EXTRUDER : 0);
  6601. planner.max_feedrate_mm_s[a] = parser.value_axis_units((AxisEnum)a);
  6602. }
  6603. }
  6604. /**
  6605. * M204: Set Accelerations in units/sec^2 (M204 P1200 R3000 T3000)
  6606. *
  6607. * P = Printing moves
  6608. * R = Retract only (no X, Y, Z) moves
  6609. * T = Travel (non printing) moves
  6610. *
  6611. * Also sets minimum segment time in ms (B20000) to prevent buffer under-runs and M20 minimum feedrate
  6612. */
  6613. inline void gcode_M204() {
  6614. if (parser.seen('S')) { // Kept for legacy compatibility. Should NOT BE USED for new developments.
  6615. planner.travel_acceleration = planner.acceleration = parser.value_linear_units();
  6616. SERIAL_ECHOLNPAIR("Setting Print and Travel Acceleration: ", planner.acceleration);
  6617. }
  6618. if (parser.seen('P')) {
  6619. planner.acceleration = parser.value_linear_units();
  6620. SERIAL_ECHOLNPAIR("Setting Print Acceleration: ", planner.acceleration);
  6621. }
  6622. if (parser.seen('R')) {
  6623. planner.retract_acceleration = parser.value_linear_units();
  6624. SERIAL_ECHOLNPAIR("Setting Retract Acceleration: ", planner.retract_acceleration);
  6625. }
  6626. if (parser.seen('T')) {
  6627. planner.travel_acceleration = parser.value_linear_units();
  6628. SERIAL_ECHOLNPAIR("Setting Travel Acceleration: ", planner.travel_acceleration);
  6629. }
  6630. }
  6631. /**
  6632. * M205: Set Advanced Settings
  6633. *
  6634. * S = Min Feed Rate (units/s)
  6635. * T = Min Travel Feed Rate (units/s)
  6636. * B = Min Segment Time (µs)
  6637. * X = Max X Jerk (units/sec^2)
  6638. * Y = Max Y Jerk (units/sec^2)
  6639. * Z = Max Z Jerk (units/sec^2)
  6640. * E = Max E Jerk (units/sec^2)
  6641. */
  6642. inline void gcode_M205() {
  6643. if (parser.seen('S')) planner.min_feedrate_mm_s = parser.value_linear_units();
  6644. if (parser.seen('T')) planner.min_travel_feedrate_mm_s = parser.value_linear_units();
  6645. if (parser.seen('B')) planner.min_segment_time = parser.value_millis();
  6646. if (parser.seen('X')) planner.max_jerk[X_AXIS] = parser.value_linear_units();
  6647. if (parser.seen('Y')) planner.max_jerk[Y_AXIS] = parser.value_linear_units();
  6648. if (parser.seen('Z')) planner.max_jerk[Z_AXIS] = parser.value_linear_units();
  6649. if (parser.seen('E')) planner.max_jerk[E_AXIS] = parser.value_linear_units();
  6650. }
  6651. #if HAS_M206_COMMAND
  6652. /**
  6653. * M206: Set Additional Homing Offset (X Y Z). SCARA aliases T=X, P=Y
  6654. *
  6655. * *** @thinkyhead: I recommend deprecating M206 for SCARA in favor of M665.
  6656. * *** M206 for SCARA will remain enabled in 1.1.x for compatibility.
  6657. * *** In the next 1.2 release, it will simply be disabled by default.
  6658. */
  6659. inline void gcode_M206() {
  6660. LOOP_XYZ(i)
  6661. if (parser.seen(axis_codes[i]))
  6662. set_home_offset((AxisEnum)i, parser.value_linear_units());
  6663. #if ENABLED(MORGAN_SCARA)
  6664. if (parser.seen('T')) set_home_offset(A_AXIS, parser.value_linear_units()); // Theta
  6665. if (parser.seen('P')) set_home_offset(B_AXIS, parser.value_linear_units()); // Psi
  6666. #endif
  6667. SYNC_PLAN_POSITION_KINEMATIC();
  6668. report_current_position();
  6669. }
  6670. #endif // HAS_M206_COMMAND
  6671. #if ENABLED(DELTA)
  6672. /**
  6673. * M665: Set delta configurations
  6674. *
  6675. * H = delta height
  6676. * L = diagonal rod
  6677. * R = delta radius
  6678. * S = segments per second
  6679. * B = delta calibration radius
  6680. * X = Alpha (Tower 1) angle trim
  6681. * Y = Beta (Tower 2) angle trim
  6682. * Z = Rotate A and B by this angle
  6683. */
  6684. inline void gcode_M665() {
  6685. if (parser.seen('H')) {
  6686. home_offset[Z_AXIS] = parser.value_linear_units() - DELTA_HEIGHT;
  6687. current_position[Z_AXIS] += parser.value_linear_units() - DELTA_HEIGHT - home_offset[Z_AXIS];
  6688. update_software_endstops(Z_AXIS);
  6689. }
  6690. if (parser.seen('L')) delta_diagonal_rod = parser.value_linear_units();
  6691. if (parser.seen('R')) delta_radius = parser.value_linear_units();
  6692. if (parser.seen('S')) delta_segments_per_second = parser.value_float();
  6693. if (parser.seen('B')) delta_calibration_radius = parser.value_float();
  6694. if (parser.seen('X')) delta_tower_angle_trim[A_AXIS] = parser.value_float();
  6695. if (parser.seen('Y')) delta_tower_angle_trim[B_AXIS] = parser.value_float();
  6696. if (parser.seen('Z')) { // rotate all 3 axis for Z = 0
  6697. delta_tower_angle_trim[A_AXIS] -= parser.value_float();
  6698. delta_tower_angle_trim[B_AXIS] -= parser.value_float();
  6699. }
  6700. recalc_delta_settings(delta_radius, delta_diagonal_rod);
  6701. }
  6702. /**
  6703. * M666: Set delta endstop adjustment
  6704. */
  6705. inline void gcode_M666() {
  6706. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6707. if (DEBUGGING(LEVELING)) {
  6708. SERIAL_ECHOLNPGM(">>> gcode_M666");
  6709. }
  6710. #endif
  6711. LOOP_XYZ(i) {
  6712. if (parser.seen(axis_codes[i])) {
  6713. endstop_adj[i] = parser.value_linear_units();
  6714. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6715. if (DEBUGGING(LEVELING)) {
  6716. SERIAL_ECHOPAIR("endstop_adj[", axis_codes[i]);
  6717. SERIAL_ECHOLNPAIR("] = ", endstop_adj[i]);
  6718. }
  6719. #endif
  6720. }
  6721. }
  6722. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6723. if (DEBUGGING(LEVELING)) {
  6724. SERIAL_ECHOLNPGM("<<< gcode_M666");
  6725. }
  6726. #endif
  6727. // normalize endstops so all are <=0; set the residue to delta height
  6728. const float z_temp = MAX3(endstop_adj[A_AXIS], endstop_adj[B_AXIS], endstop_adj[C_AXIS]);
  6729. home_offset[Z_AXIS] -= z_temp;
  6730. LOOP_XYZ(i) endstop_adj[i] -= z_temp;
  6731. }
  6732. #elif IS_SCARA
  6733. /**
  6734. * M665: Set SCARA settings
  6735. *
  6736. * Parameters:
  6737. *
  6738. * S[segments-per-second] - Segments-per-second
  6739. * P[theta-psi-offset] - Theta-Psi offset, added to the shoulder (A/X) angle
  6740. * T[theta-offset] - Theta offset, added to the elbow (B/Y) angle
  6741. *
  6742. * A, P, and X are all aliases for the shoulder angle
  6743. * B, T, and Y are all aliases for the elbow angle
  6744. */
  6745. inline void gcode_M665() {
  6746. if (parser.seen('S')) delta_segments_per_second = parser.value_float();
  6747. const bool hasA = parser.seen('A'), hasP = parser.seen('P'), hasX = parser.seen('X');
  6748. const uint8_t sumAPX = hasA + hasP + hasX;
  6749. if (sumAPX == 1)
  6750. home_offset[A_AXIS] = parser.value_float();
  6751. else if (sumAPX > 1) {
  6752. SERIAL_ERROR_START;
  6753. SERIAL_ERRORLNPGM("Only one of A, P, or X is allowed.");
  6754. return;
  6755. }
  6756. const bool hasB = parser.seen('B'), hasT = parser.seen('T'), hasY = parser.seen('Y');
  6757. const uint8_t sumBTY = hasB + hasT + hasY;
  6758. if (sumBTY == 1)
  6759. home_offset[B_AXIS] = parser.value_float();
  6760. else if (sumBTY > 1) {
  6761. SERIAL_ERROR_START;
  6762. SERIAL_ERRORLNPGM("Only one of B, T, or Y is allowed.");
  6763. return;
  6764. }
  6765. }
  6766. #elif ENABLED(Z_DUAL_ENDSTOPS) // !DELTA && ENABLED(Z_DUAL_ENDSTOPS)
  6767. /**
  6768. * M666: For Z Dual Endstop setup, set z axis offset to the z2 axis.
  6769. */
  6770. inline void gcode_M666() {
  6771. if (parser.seen('Z')) z_endstop_adj = parser.value_linear_units();
  6772. SERIAL_ECHOLNPAIR("Z Endstop Adjustment set to (mm):", z_endstop_adj);
  6773. }
  6774. #endif // !DELTA && Z_DUAL_ENDSTOPS
  6775. #if ENABLED(FWRETRACT)
  6776. /**
  6777. * M207: Set firmware retraction values
  6778. *
  6779. * S[+units] retract_length
  6780. * W[+units] retract_length_swap (multi-extruder)
  6781. * F[units/min] retract_feedrate_mm_s
  6782. * Z[units] retract_zlift
  6783. */
  6784. inline void gcode_M207() {
  6785. if (parser.seen('S')) retract_length = parser.value_axis_units(E_AXIS);
  6786. if (parser.seen('F')) retract_feedrate_mm_s = MMM_TO_MMS(parser.value_axis_units(E_AXIS));
  6787. if (parser.seen('Z')) retract_zlift = parser.value_linear_units();
  6788. #if EXTRUDERS > 1
  6789. if (parser.seen('W')) retract_length_swap = parser.value_axis_units(E_AXIS);
  6790. #endif
  6791. }
  6792. /**
  6793. * M208: Set firmware un-retraction values
  6794. *
  6795. * S[+units] retract_recover_length (in addition to M207 S*)
  6796. * W[+units] retract_recover_length_swap (multi-extruder)
  6797. * F[units/min] retract_recover_feedrate_mm_s
  6798. */
  6799. inline void gcode_M208() {
  6800. if (parser.seen('S')) retract_recover_length = parser.value_axis_units(E_AXIS);
  6801. if (parser.seen('F')) retract_recover_feedrate_mm_s = MMM_TO_MMS(parser.value_axis_units(E_AXIS));
  6802. #if EXTRUDERS > 1
  6803. if (parser.seen('W')) retract_recover_length_swap = parser.value_axis_units(E_AXIS);
  6804. #endif
  6805. }
  6806. /**
  6807. * M209: Enable automatic retract (M209 S1)
  6808. * For slicers that don't support G10/11, reversed extrude-only
  6809. * moves will be classified as retraction.
  6810. */
  6811. inline void gcode_M209() {
  6812. if (parser.seen('S')) {
  6813. autoretract_enabled = parser.value_bool();
  6814. for (int i = 0; i < EXTRUDERS; i++) retracted[i] = false;
  6815. }
  6816. }
  6817. #endif // FWRETRACT
  6818. /**
  6819. * M211: Enable, Disable, and/or Report software endstops
  6820. *
  6821. * Usage: M211 S1 to enable, M211 S0 to disable, M211 alone for report
  6822. */
  6823. inline void gcode_M211() {
  6824. SERIAL_ECHO_START;
  6825. #if HAS_SOFTWARE_ENDSTOPS
  6826. if (parser.seen('S')) soft_endstops_enabled = parser.value_bool();
  6827. SERIAL_ECHOPGM(MSG_SOFT_ENDSTOPS);
  6828. serialprintPGM(soft_endstops_enabled ? PSTR(MSG_ON) : PSTR(MSG_OFF));
  6829. #else
  6830. SERIAL_ECHOPGM(MSG_SOFT_ENDSTOPS);
  6831. SERIAL_ECHOPGM(MSG_OFF);
  6832. #endif
  6833. SERIAL_ECHOPGM(MSG_SOFT_MIN);
  6834. SERIAL_ECHOPAIR( MSG_X, soft_endstop_min[X_AXIS]);
  6835. SERIAL_ECHOPAIR(" " MSG_Y, soft_endstop_min[Y_AXIS]);
  6836. SERIAL_ECHOPAIR(" " MSG_Z, soft_endstop_min[Z_AXIS]);
  6837. SERIAL_ECHOPGM(MSG_SOFT_MAX);
  6838. SERIAL_ECHOPAIR( MSG_X, soft_endstop_max[X_AXIS]);
  6839. SERIAL_ECHOPAIR(" " MSG_Y, soft_endstop_max[Y_AXIS]);
  6840. SERIAL_ECHOLNPAIR(" " MSG_Z, soft_endstop_max[Z_AXIS]);
  6841. }
  6842. #if HOTENDS > 1
  6843. /**
  6844. * M218 - set hotend offset (in linear units)
  6845. *
  6846. * T<tool>
  6847. * X<xoffset>
  6848. * Y<yoffset>
  6849. * Z<zoffset> - Available with DUAL_X_CARRIAGE and SWITCHING_NOZZLE
  6850. */
  6851. inline void gcode_M218() {
  6852. if (get_target_extruder_from_command(218) || target_extruder == 0) return;
  6853. if (parser.seen('X')) hotend_offset[X_AXIS][target_extruder] = parser.value_linear_units();
  6854. if (parser.seen('Y')) hotend_offset[Y_AXIS][target_extruder] = parser.value_linear_units();
  6855. #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(SWITCHING_NOZZLE)
  6856. if (parser.seen('Z')) hotend_offset[Z_AXIS][target_extruder] = parser.value_linear_units();
  6857. #endif
  6858. SERIAL_ECHO_START;
  6859. SERIAL_ECHOPGM(MSG_HOTEND_OFFSET);
  6860. HOTEND_LOOP() {
  6861. SERIAL_CHAR(' ');
  6862. SERIAL_ECHO(hotend_offset[X_AXIS][e]);
  6863. SERIAL_CHAR(',');
  6864. SERIAL_ECHO(hotend_offset[Y_AXIS][e]);
  6865. #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(SWITCHING_NOZZLE)
  6866. SERIAL_CHAR(',');
  6867. SERIAL_ECHO(hotend_offset[Z_AXIS][e]);
  6868. #endif
  6869. }
  6870. SERIAL_EOL;
  6871. }
  6872. #endif // HOTENDS > 1
  6873. /**
  6874. * M220: Set speed percentage factor, aka "Feed Rate" (M220 S95)
  6875. */
  6876. inline void gcode_M220() {
  6877. if (parser.seen('S')) feedrate_percentage = parser.value_int();
  6878. }
  6879. /**
  6880. * M221: Set extrusion percentage (M221 T0 S95)
  6881. */
  6882. inline void gcode_M221() {
  6883. if (get_target_extruder_from_command(221)) return;
  6884. if (parser.seen('S'))
  6885. flow_percentage[target_extruder] = parser.value_int();
  6886. }
  6887. /**
  6888. * M226: Wait until the specified pin reaches the state required (M226 P<pin> S<state>)
  6889. */
  6890. inline void gcode_M226() {
  6891. if (parser.seen('P')) {
  6892. int pin_number = parser.value_int(),
  6893. pin_state = parser.seen('S') ? parser.value_int() : -1; // required pin state - default is inverted
  6894. if (pin_state >= -1 && pin_state <= 1 && pin_number > -1 && !pin_is_protected(pin_number)) {
  6895. int target = LOW;
  6896. stepper.synchronize();
  6897. pinMode(pin_number, INPUT);
  6898. switch (pin_state) {
  6899. case 1:
  6900. target = HIGH;
  6901. break;
  6902. case 0:
  6903. target = LOW;
  6904. break;
  6905. case -1:
  6906. target = !digitalRead(pin_number);
  6907. break;
  6908. }
  6909. while (digitalRead(pin_number) != target) idle();
  6910. } // pin_state -1 0 1 && pin_number > -1
  6911. } // parser.seen('P')
  6912. }
  6913. #if ENABLED(EXPERIMENTAL_I2CBUS)
  6914. /**
  6915. * M260: Send data to a I2C slave device
  6916. *
  6917. * This is a PoC, the formating and arguments for the GCODE will
  6918. * change to be more compatible, the current proposal is:
  6919. *
  6920. * M260 A<slave device address base 10> ; Sets the I2C slave address the data will be sent to
  6921. *
  6922. * M260 B<byte-1 value in base 10>
  6923. * M260 B<byte-2 value in base 10>
  6924. * M260 B<byte-3 value in base 10>
  6925. *
  6926. * M260 S1 ; Send the buffered data and reset the buffer
  6927. * M260 R1 ; Reset the buffer without sending data
  6928. *
  6929. */
  6930. inline void gcode_M260() {
  6931. // Set the target address
  6932. if (parser.seen('A')) i2c.address(parser.value_byte());
  6933. // Add a new byte to the buffer
  6934. if (parser.seen('B')) i2c.addbyte(parser.value_byte());
  6935. // Flush the buffer to the bus
  6936. if (parser.seen('S')) i2c.send();
  6937. // Reset and rewind the buffer
  6938. else if (parser.seen('R')) i2c.reset();
  6939. }
  6940. /**
  6941. * M261: Request X bytes from I2C slave device
  6942. *
  6943. * Usage: M261 A<slave device address base 10> B<number of bytes>
  6944. */
  6945. inline void gcode_M261() {
  6946. if (parser.seen('A')) i2c.address(parser.value_byte());
  6947. uint8_t bytes = parser.seen('B') ? parser.value_byte() : 1;
  6948. if (i2c.addr && bytes && bytes <= TWIBUS_BUFFER_SIZE) {
  6949. i2c.relay(bytes);
  6950. }
  6951. else {
  6952. SERIAL_ERROR_START;
  6953. SERIAL_ERRORLN("Bad i2c request");
  6954. }
  6955. }
  6956. #endif // EXPERIMENTAL_I2CBUS
  6957. #if HAS_SERVOS
  6958. /**
  6959. * M280: Get or set servo position. P<index> [S<angle>]
  6960. */
  6961. inline void gcode_M280() {
  6962. if (!parser.seen('P')) return;
  6963. int servo_index = parser.value_int();
  6964. if (WITHIN(servo_index, 0, NUM_SERVOS - 1)) {
  6965. if (parser.seen('S'))
  6966. MOVE_SERVO(servo_index, parser.value_int());
  6967. else {
  6968. SERIAL_ECHO_START;
  6969. SERIAL_ECHOPAIR(" Servo ", servo_index);
  6970. SERIAL_ECHOLNPAIR(": ", servo[servo_index].read());
  6971. }
  6972. }
  6973. else {
  6974. SERIAL_ERROR_START;
  6975. SERIAL_ECHOPAIR("Servo ", servo_index);
  6976. SERIAL_ECHOLNPGM(" out of range");
  6977. }
  6978. }
  6979. #endif // HAS_SERVOS
  6980. #if HAS_BUZZER
  6981. /**
  6982. * M300: Play beep sound S<frequency Hz> P<duration ms>
  6983. */
  6984. inline void gcode_M300() {
  6985. uint16_t const frequency = parser.seen('S') ? parser.value_ushort() : 260;
  6986. uint16_t duration = parser.seen('P') ? parser.value_ushort() : 1000;
  6987. // Limits the tone duration to 0-5 seconds.
  6988. NOMORE(duration, 5000);
  6989. BUZZ(duration, frequency);
  6990. }
  6991. #endif // HAS_BUZZER
  6992. #if ENABLED(PIDTEMP)
  6993. /**
  6994. * M301: Set PID parameters P I D (and optionally C, L)
  6995. *
  6996. * P[float] Kp term
  6997. * I[float] Ki term (unscaled)
  6998. * D[float] Kd term (unscaled)
  6999. *
  7000. * With PID_EXTRUSION_SCALING:
  7001. *
  7002. * C[float] Kc term
  7003. * L[float] LPQ length
  7004. */
  7005. inline void gcode_M301() {
  7006. // multi-extruder PID patch: M301 updates or prints a single extruder's PID values
  7007. // default behaviour (omitting E parameter) is to update for extruder 0 only
  7008. int e = parser.seen('E') ? parser.value_int() : 0; // extruder being updated
  7009. if (e < HOTENDS) { // catch bad input value
  7010. if (parser.seen('P')) PID_PARAM(Kp, e) = parser.value_float();
  7011. if (parser.seen('I')) PID_PARAM(Ki, e) = scalePID_i(parser.value_float());
  7012. if (parser.seen('D')) PID_PARAM(Kd, e) = scalePID_d(parser.value_float());
  7013. #if ENABLED(PID_EXTRUSION_SCALING)
  7014. if (parser.seen('C')) PID_PARAM(Kc, e) = parser.value_float();
  7015. if (parser.seen('L')) lpq_len = parser.value_float();
  7016. NOMORE(lpq_len, LPQ_MAX_LEN);
  7017. #endif
  7018. thermalManager.updatePID();
  7019. SERIAL_ECHO_START;
  7020. #if ENABLED(PID_PARAMS_PER_HOTEND)
  7021. SERIAL_ECHOPAIR(" e:", e); // specify extruder in serial output
  7022. #endif // PID_PARAMS_PER_HOTEND
  7023. SERIAL_ECHOPAIR(" p:", PID_PARAM(Kp, e));
  7024. SERIAL_ECHOPAIR(" i:", unscalePID_i(PID_PARAM(Ki, e)));
  7025. SERIAL_ECHOPAIR(" d:", unscalePID_d(PID_PARAM(Kd, e)));
  7026. #if ENABLED(PID_EXTRUSION_SCALING)
  7027. //Kc does not have scaling applied above, or in resetting defaults
  7028. SERIAL_ECHOPAIR(" c:", PID_PARAM(Kc, e));
  7029. #endif
  7030. SERIAL_EOL;
  7031. }
  7032. else {
  7033. SERIAL_ERROR_START;
  7034. SERIAL_ERRORLN(MSG_INVALID_EXTRUDER);
  7035. }
  7036. }
  7037. #endif // PIDTEMP
  7038. #if ENABLED(PIDTEMPBED)
  7039. inline void gcode_M304() {
  7040. if (parser.seen('P')) thermalManager.bedKp = parser.value_float();
  7041. if (parser.seen('I')) thermalManager.bedKi = scalePID_i(parser.value_float());
  7042. if (parser.seen('D')) thermalManager.bedKd = scalePID_d(parser.value_float());
  7043. thermalManager.updatePID();
  7044. SERIAL_ECHO_START;
  7045. SERIAL_ECHOPAIR(" p:", thermalManager.bedKp);
  7046. SERIAL_ECHOPAIR(" i:", unscalePID_i(thermalManager.bedKi));
  7047. SERIAL_ECHOLNPAIR(" d:", unscalePID_d(thermalManager.bedKd));
  7048. }
  7049. #endif // PIDTEMPBED
  7050. #if defined(CHDK) || HAS_PHOTOGRAPH
  7051. /**
  7052. * M240: Trigger a camera by emulating a Canon RC-1
  7053. * See http://www.doc-diy.net/photo/rc-1_hacked/
  7054. */
  7055. inline void gcode_M240() {
  7056. #ifdef CHDK
  7057. OUT_WRITE(CHDK, HIGH);
  7058. chdkHigh = millis();
  7059. chdkActive = true;
  7060. #elif HAS_PHOTOGRAPH
  7061. const uint8_t NUM_PULSES = 16;
  7062. const float PULSE_LENGTH = 0.01524;
  7063. for (int i = 0; i < NUM_PULSES; i++) {
  7064. WRITE(PHOTOGRAPH_PIN, HIGH);
  7065. _delay_ms(PULSE_LENGTH);
  7066. WRITE(PHOTOGRAPH_PIN, LOW);
  7067. _delay_ms(PULSE_LENGTH);
  7068. }
  7069. delay(7.33);
  7070. for (int i = 0; i < NUM_PULSES; i++) {
  7071. WRITE(PHOTOGRAPH_PIN, HIGH);
  7072. _delay_ms(PULSE_LENGTH);
  7073. WRITE(PHOTOGRAPH_PIN, LOW);
  7074. _delay_ms(PULSE_LENGTH);
  7075. }
  7076. #endif // !CHDK && HAS_PHOTOGRAPH
  7077. }
  7078. #endif // CHDK || PHOTOGRAPH_PIN
  7079. #if HAS_LCD_CONTRAST
  7080. /**
  7081. * M250: Read and optionally set the LCD contrast
  7082. */
  7083. inline void gcode_M250() {
  7084. if (parser.seen('C')) set_lcd_contrast(parser.value_int());
  7085. SERIAL_PROTOCOLPGM("lcd contrast value: ");
  7086. SERIAL_PROTOCOL(lcd_contrast);
  7087. SERIAL_EOL;
  7088. }
  7089. #endif // HAS_LCD_CONTRAST
  7090. #if ENABLED(PREVENT_COLD_EXTRUSION)
  7091. /**
  7092. * M302: Allow cold extrudes, or set the minimum extrude temperature
  7093. *
  7094. * S<temperature> sets the minimum extrude temperature
  7095. * P<bool> enables (1) or disables (0) cold extrusion
  7096. *
  7097. * Examples:
  7098. *
  7099. * M302 ; report current cold extrusion state
  7100. * M302 P0 ; enable cold extrusion checking
  7101. * M302 P1 ; disables cold extrusion checking
  7102. * M302 S0 ; always allow extrusion (disables checking)
  7103. * M302 S170 ; only allow extrusion above 170
  7104. * M302 S170 P1 ; set min extrude temp to 170 but leave disabled
  7105. */
  7106. inline void gcode_M302() {
  7107. bool seen_S = parser.seen('S');
  7108. if (seen_S) {
  7109. thermalManager.extrude_min_temp = parser.value_celsius();
  7110. thermalManager.allow_cold_extrude = (thermalManager.extrude_min_temp == 0);
  7111. }
  7112. if (parser.seen('P'))
  7113. thermalManager.allow_cold_extrude = (thermalManager.extrude_min_temp == 0) || parser.value_bool();
  7114. else if (!seen_S) {
  7115. // Report current state
  7116. SERIAL_ECHO_START;
  7117. SERIAL_ECHOPAIR("Cold extrudes are ", (thermalManager.allow_cold_extrude ? "en" : "dis"));
  7118. SERIAL_ECHOPAIR("abled (min temp ", thermalManager.extrude_min_temp);
  7119. SERIAL_ECHOLNPGM("C)");
  7120. }
  7121. }
  7122. #endif // PREVENT_COLD_EXTRUSION
  7123. /**
  7124. * M303: PID relay autotune
  7125. *
  7126. * S<temperature> sets the target temperature. (default 150C)
  7127. * E<extruder> (-1 for the bed) (default 0)
  7128. * C<cycles>
  7129. * U<bool> with a non-zero value will apply the result to current settings
  7130. */
  7131. inline void gcode_M303() {
  7132. #if HAS_PID_HEATING
  7133. const int e = parser.seen('E') ? parser.value_int() : 0,
  7134. c = parser.seen('C') ? parser.value_int() : 5;
  7135. const bool u = parser.seen('U') && parser.value_bool();
  7136. int16_t temp = parser.seen('S') ? parser.value_celsius() : (e < 0 ? 70 : 150);
  7137. if (WITHIN(e, 0, HOTENDS - 1))
  7138. target_extruder = e;
  7139. KEEPALIVE_STATE(NOT_BUSY); // don't send "busy: processing" messages during autotune output
  7140. thermalManager.PID_autotune(temp, e, c, u);
  7141. KEEPALIVE_STATE(IN_HANDLER);
  7142. #else
  7143. SERIAL_ERROR_START;
  7144. SERIAL_ERRORLNPGM(MSG_ERR_M303_DISABLED);
  7145. #endif
  7146. }
  7147. #if ENABLED(MORGAN_SCARA)
  7148. bool SCARA_move_to_cal(uint8_t delta_a, uint8_t delta_b) {
  7149. if (IsRunning()) {
  7150. forward_kinematics_SCARA(delta_a, delta_b);
  7151. destination[X_AXIS] = LOGICAL_X_POSITION(cartes[X_AXIS]);
  7152. destination[Y_AXIS] = LOGICAL_Y_POSITION(cartes[Y_AXIS]);
  7153. destination[Z_AXIS] = current_position[Z_AXIS];
  7154. prepare_move_to_destination();
  7155. return true;
  7156. }
  7157. return false;
  7158. }
  7159. /**
  7160. * M360: SCARA calibration: Move to cal-position ThetaA (0 deg calibration)
  7161. */
  7162. inline bool gcode_M360() {
  7163. SERIAL_ECHOLNPGM(" Cal: Theta 0");
  7164. return SCARA_move_to_cal(0, 120);
  7165. }
  7166. /**
  7167. * M361: SCARA calibration: Move to cal-position ThetaB (90 deg calibration - steps per degree)
  7168. */
  7169. inline bool gcode_M361() {
  7170. SERIAL_ECHOLNPGM(" Cal: Theta 90");
  7171. return SCARA_move_to_cal(90, 130);
  7172. }
  7173. /**
  7174. * M362: SCARA calibration: Move to cal-position PsiA (0 deg calibration)
  7175. */
  7176. inline bool gcode_M362() {
  7177. SERIAL_ECHOLNPGM(" Cal: Psi 0");
  7178. return SCARA_move_to_cal(60, 180);
  7179. }
  7180. /**
  7181. * M363: SCARA calibration: Move to cal-position PsiB (90 deg calibration - steps per degree)
  7182. */
  7183. inline bool gcode_M363() {
  7184. SERIAL_ECHOLNPGM(" Cal: Psi 90");
  7185. return SCARA_move_to_cal(50, 90);
  7186. }
  7187. /**
  7188. * M364: SCARA calibration: Move to cal-position PsiC (90 deg to Theta calibration position)
  7189. */
  7190. inline bool gcode_M364() {
  7191. SERIAL_ECHOLNPGM(" Cal: Theta-Psi 90");
  7192. return SCARA_move_to_cal(45, 135);
  7193. }
  7194. #endif // SCARA
  7195. #if ENABLED(EXT_SOLENOID)
  7196. void enable_solenoid(const uint8_t num) {
  7197. switch (num) {
  7198. case 0:
  7199. OUT_WRITE(SOL0_PIN, HIGH);
  7200. break;
  7201. #if HAS_SOLENOID_1 && EXTRUDERS > 1
  7202. case 1:
  7203. OUT_WRITE(SOL1_PIN, HIGH);
  7204. break;
  7205. #endif
  7206. #if HAS_SOLENOID_2 && EXTRUDERS > 2
  7207. case 2:
  7208. OUT_WRITE(SOL2_PIN, HIGH);
  7209. break;
  7210. #endif
  7211. #if HAS_SOLENOID_3 && EXTRUDERS > 3
  7212. case 3:
  7213. OUT_WRITE(SOL3_PIN, HIGH);
  7214. break;
  7215. #endif
  7216. #if HAS_SOLENOID_4 && EXTRUDERS > 4
  7217. case 4:
  7218. OUT_WRITE(SOL4_PIN, HIGH);
  7219. break;
  7220. #endif
  7221. default:
  7222. SERIAL_ECHO_START;
  7223. SERIAL_ECHOLNPGM(MSG_INVALID_SOLENOID);
  7224. break;
  7225. }
  7226. }
  7227. void enable_solenoid_on_active_extruder() { enable_solenoid(active_extruder); }
  7228. void disable_all_solenoids() {
  7229. OUT_WRITE(SOL0_PIN, LOW);
  7230. #if HAS_SOLENOID_1 && EXTRUDERS > 1
  7231. OUT_WRITE(SOL1_PIN, LOW);
  7232. #endif
  7233. #if HAS_SOLENOID_2 && EXTRUDERS > 2
  7234. OUT_WRITE(SOL2_PIN, LOW);
  7235. #endif
  7236. #if HAS_SOLENOID_3 && EXTRUDERS > 3
  7237. OUT_WRITE(SOL3_PIN, LOW);
  7238. #endif
  7239. #if HAS_SOLENOID_4 && EXTRUDERS > 4
  7240. OUT_WRITE(SOL4_PIN, LOW);
  7241. #endif
  7242. }
  7243. /**
  7244. * M380: Enable solenoid on the active extruder
  7245. */
  7246. inline void gcode_M380() { enable_solenoid_on_active_extruder(); }
  7247. /**
  7248. * M381: Disable all solenoids
  7249. */
  7250. inline void gcode_M381() { disable_all_solenoids(); }
  7251. #endif // EXT_SOLENOID
  7252. /**
  7253. * M400: Finish all moves
  7254. */
  7255. inline void gcode_M400() { stepper.synchronize(); }
  7256. #if HAS_BED_PROBE
  7257. /**
  7258. * M401: Engage Z Servo endstop if available
  7259. */
  7260. inline void gcode_M401() { DEPLOY_PROBE(); }
  7261. /**
  7262. * M402: Retract Z Servo endstop if enabled
  7263. */
  7264. inline void gcode_M402() { STOW_PROBE(); }
  7265. #endif // HAS_BED_PROBE
  7266. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  7267. /**
  7268. * M404: Display or set (in current units) the nominal filament width (3mm, 1.75mm ) W<3.0>
  7269. */
  7270. inline void gcode_M404() {
  7271. if (parser.seen('W')) {
  7272. filament_width_nominal = parser.value_linear_units();
  7273. }
  7274. else {
  7275. SERIAL_PROTOCOLPGM("Filament dia (nominal mm):");
  7276. SERIAL_PROTOCOLLN(filament_width_nominal);
  7277. }
  7278. }
  7279. /**
  7280. * M405: Turn on filament sensor for control
  7281. */
  7282. inline void gcode_M405() {
  7283. // This is technically a linear measurement, but since it's quantized to centimeters and is a different unit than
  7284. // everything else, it uses parser.value_int() instead of parser.value_linear_units().
  7285. if (parser.seen('D')) meas_delay_cm = parser.value_int();
  7286. NOMORE(meas_delay_cm, MAX_MEASUREMENT_DELAY);
  7287. if (filwidth_delay_index[1] == -1) { // Initialize the ring buffer if not done since startup
  7288. const int temp_ratio = thermalManager.widthFil_to_size_ratio() - 100; // -100 to scale within a signed byte
  7289. for (uint8_t i = 0; i < COUNT(measurement_delay); ++i)
  7290. measurement_delay[i] = temp_ratio;
  7291. filwidth_delay_index[0] = filwidth_delay_index[1] = 0;
  7292. }
  7293. filament_sensor = true;
  7294. //SERIAL_PROTOCOLPGM("Filament dia (measured mm):");
  7295. //SERIAL_PROTOCOL(filament_width_meas);
  7296. //SERIAL_PROTOCOLPGM("Extrusion ratio(%):");
  7297. //SERIAL_PROTOCOL(flow_percentage[active_extruder]);
  7298. }
  7299. /**
  7300. * M406: Turn off filament sensor for control
  7301. */
  7302. inline void gcode_M406() { filament_sensor = false; }
  7303. /**
  7304. * M407: Get measured filament diameter on serial output
  7305. */
  7306. inline void gcode_M407() {
  7307. SERIAL_PROTOCOLPGM("Filament dia (measured mm):");
  7308. SERIAL_PROTOCOLLN(filament_width_meas);
  7309. }
  7310. #endif // FILAMENT_WIDTH_SENSOR
  7311. void quickstop_stepper() {
  7312. stepper.quick_stop();
  7313. stepper.synchronize();
  7314. set_current_from_steppers_for_axis(ALL_AXES);
  7315. SYNC_PLAN_POSITION_KINEMATIC();
  7316. }
  7317. #if HAS_LEVELING
  7318. /**
  7319. * M420: Enable/Disable Bed Leveling and/or set the Z fade height.
  7320. *
  7321. * S[bool] Turns leveling on or off
  7322. * Z[height] Sets the Z fade height (0 or none to disable)
  7323. * V[bool] Verbose - Print the leveling grid
  7324. *
  7325. * With AUTO_BED_LEVELING_UBL only:
  7326. *
  7327. * L[index] Load UBL mesh from index (0 is default)
  7328. */
  7329. inline void gcode_M420() {
  7330. #if ENABLED(AUTO_BED_LEVELING_UBL)
  7331. // L to load a mesh from the EEPROM
  7332. if (parser.seen('L')) {
  7333. const int8_t storage_slot = parser.has_value() ? parser.value_int() : ubl.state.storage_slot;
  7334. const int16_t a = settings.calc_num_meshes();
  7335. if (!a) {
  7336. SERIAL_PROTOCOLLNPGM("?EEPROM storage not available.");
  7337. return;
  7338. }
  7339. if (!WITHIN(storage_slot, 0, a - 1)) {
  7340. SERIAL_PROTOCOLLNPGM("?Invalid storage slot.");
  7341. SERIAL_PROTOCOLLNPAIR("?Use 0 to ", a - 1);
  7342. return;
  7343. }
  7344. settings.load_mesh(storage_slot);
  7345. ubl.state.storage_slot = storage_slot;
  7346. }
  7347. #endif // AUTO_BED_LEVELING_UBL
  7348. // V to print the matrix or mesh
  7349. if (parser.seen('V')) {
  7350. #if ABL_PLANAR
  7351. planner.bed_level_matrix.debug(PSTR("Bed Level Correction Matrix:"));
  7352. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  7353. if (leveling_is_valid()) {
  7354. print_bilinear_leveling_grid();
  7355. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  7356. bed_level_virt_print();
  7357. #endif
  7358. }
  7359. #elif ENABLED(MESH_BED_LEVELING)
  7360. if (leveling_is_valid()) {
  7361. SERIAL_ECHOLNPGM("Mesh Bed Level data:");
  7362. mbl_mesh_report();
  7363. }
  7364. #endif
  7365. }
  7366. #if ENABLED(AUTO_BED_LEVELING_UBL)
  7367. // L to load a mesh from the EEPROM
  7368. if (parser.seen('L') || parser.seen('V')) {
  7369. ubl.display_map(0); // Currently only supports one map type
  7370. SERIAL_ECHOLNPAIR("UBL_MESH_VALID = ", UBL_MESH_VALID);
  7371. SERIAL_ECHOLNPAIR("ubl.state.storage_slot = ", ubl.state.storage_slot);
  7372. }
  7373. #endif
  7374. bool to_enable = false;
  7375. if (parser.seen('S')) {
  7376. to_enable = parser.value_bool();
  7377. set_bed_leveling_enabled(to_enable);
  7378. }
  7379. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  7380. if (parser.seen('Z')) set_z_fade_height(parser.value_linear_units());
  7381. #endif
  7382. const bool new_status = leveling_is_active();
  7383. if (to_enable && !new_status) {
  7384. SERIAL_ERROR_START;
  7385. SERIAL_ERRORLNPGM(MSG_ERR_M420_FAILED);
  7386. }
  7387. SERIAL_ECHO_START;
  7388. SERIAL_ECHOLNPAIR("Bed Leveling ", new_status ? MSG_ON : MSG_OFF);
  7389. }
  7390. #endif
  7391. #if ENABLED(MESH_BED_LEVELING)
  7392. /**
  7393. * M421: Set a single Mesh Bed Leveling Z coordinate
  7394. *
  7395. * Usage:
  7396. * M421 X<linear> Y<linear> Z<linear>
  7397. * M421 X<linear> Y<linear> Q<offset>
  7398. * M421 I<xindex> J<yindex> Z<linear>
  7399. * M421 I<xindex> J<yindex> Q<offset>
  7400. */
  7401. inline void gcode_M421() {
  7402. const bool hasX = parser.seen('X'), hasI = parser.seen('I');
  7403. const int8_t ix = hasI ? parser.value_int() : hasX ? mbl.probe_index_x(RAW_X_POSITION(parser.value_linear_units())) : -1;
  7404. const bool hasY = parser.seen('Y'), hasJ = parser.seen('J');
  7405. const int8_t iy = hasJ ? parser.value_int() : hasY ? mbl.probe_index_y(RAW_Y_POSITION(parser.value_linear_units())) : -1;
  7406. const bool hasZ = parser.seen('Z'), hasQ = !hasZ && parser.seen('Q');
  7407. if (int(hasI && hasJ) + int(hasX && hasY) != 1 || !(hasZ || hasQ)) {
  7408. SERIAL_ERROR_START;
  7409. SERIAL_ERRORLNPGM(MSG_ERR_M421_PARAMETERS);
  7410. }
  7411. else if (ix < 0 || iy < 0) {
  7412. SERIAL_ERROR_START;
  7413. SERIAL_ERRORLNPGM(MSG_ERR_MESH_XY);
  7414. }
  7415. else
  7416. mbl.set_z(ix, iy, parser.value_linear_units() + (hasQ ? mbl.z_values[ix][iy] : 0));
  7417. }
  7418. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  7419. /**
  7420. * M421: Set a single Mesh Bed Leveling Z coordinate
  7421. *
  7422. * Usage:
  7423. * M421 I<xindex> J<yindex> Z<linear>
  7424. * M421 I<xindex> J<yindex> Q<offset>
  7425. */
  7426. inline void gcode_M421() {
  7427. const bool hasI = parser.seen('I');
  7428. const int8_t ix = hasI ? parser.value_int() : -1;
  7429. const bool hasJ = parser.seen('J');
  7430. const int8_t iy = hasJ ? parser.value_int() : -1;
  7431. const bool hasZ = parser.seen('Z'), hasQ = !hasZ && parser.seen('Q');
  7432. if (!hasI || !hasJ || !(hasZ || hasQ)) {
  7433. SERIAL_ERROR_START;
  7434. SERIAL_ERRORLNPGM(MSG_ERR_M421_PARAMETERS);
  7435. }
  7436. else if (!WITHIN(ix, 0, GRID_MAX_POINTS_X - 1) || !WITHIN(iy, 0, GRID_MAX_POINTS_Y - 1)) {
  7437. SERIAL_ERROR_START;
  7438. SERIAL_ERRORLNPGM(MSG_ERR_MESH_XY);
  7439. }
  7440. else {
  7441. z_values[ix][iy] = parser.value_linear_units() + (hasQ ? z_values[ix][iy] : 0);
  7442. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  7443. bed_level_virt_interpolate();
  7444. #endif
  7445. }
  7446. }
  7447. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  7448. /**
  7449. * M421: Set a single Mesh Bed Leveling Z coordinate
  7450. *
  7451. * Usage:
  7452. * M421 I<xindex> J<yindex> Z<linear>
  7453. * M421 I<xindex> J<yindex> Q<offset>
  7454. * M421 C Z<linear>
  7455. * M421 C Q<offset>
  7456. */
  7457. inline void gcode_M421() {
  7458. const bool hasC = parser.seen('C'), hasI = parser.seen('I');
  7459. int8_t ix = hasI ? parser.value_int() : -1;
  7460. const bool hasJ = parser.seen('J');
  7461. int8_t iy = hasJ ? parser.value_int() : -1;
  7462. const bool hasZ = parser.seen('Z'), hasQ = !hasZ && parser.seen('Q');
  7463. if (hasC) {
  7464. 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);
  7465. ix = location.x_index;
  7466. iy = location.y_index;
  7467. }
  7468. if (int(hasC) + int(hasI && hasJ) != 1 || !(hasZ || hasQ)) {
  7469. SERIAL_ERROR_START;
  7470. SERIAL_ERRORLNPGM(MSG_ERR_M421_PARAMETERS);
  7471. }
  7472. else if (!WITHIN(ix, 0, GRID_MAX_POINTS_X - 1) || !WITHIN(iy, 0, GRID_MAX_POINTS_Y - 1)) {
  7473. SERIAL_ERROR_START;
  7474. SERIAL_ERRORLNPGM(MSG_ERR_MESH_XY);
  7475. }
  7476. else
  7477. ubl.z_values[ix][iy] = parser.value_linear_units() + (hasQ ? ubl.z_values[ix][iy] : 0);
  7478. }
  7479. #endif // AUTO_BED_LEVELING_UBL
  7480. #if HAS_M206_COMMAND
  7481. /**
  7482. * M428: Set home_offset based on the distance between the
  7483. * current_position and the nearest "reference point."
  7484. * If an axis is past center its endstop position
  7485. * is the reference-point. Otherwise it uses 0. This allows
  7486. * the Z offset to be set near the bed when using a max endstop.
  7487. *
  7488. * M428 can't be used more than 2cm away from 0 or an endstop.
  7489. *
  7490. * Use M206 to set these values directly.
  7491. */
  7492. inline void gcode_M428() {
  7493. bool err = false;
  7494. LOOP_XYZ(i) {
  7495. if (axis_homed[i]) {
  7496. const float base = (current_position[i] > (soft_endstop_min[i] + soft_endstop_max[i]) * 0.5) ? base_home_pos((AxisEnum)i) : 0,
  7497. diff = base - RAW_POSITION(current_position[i], i);
  7498. if (WITHIN(diff, -20, 20)) {
  7499. set_home_offset((AxisEnum)i, diff);
  7500. }
  7501. else {
  7502. SERIAL_ERROR_START;
  7503. SERIAL_ERRORLNPGM(MSG_ERR_M428_TOO_FAR);
  7504. LCD_ALERTMESSAGEPGM("Err: Too far!");
  7505. BUZZ(200, 40);
  7506. err = true;
  7507. break;
  7508. }
  7509. }
  7510. }
  7511. if (!err) {
  7512. SYNC_PLAN_POSITION_KINEMATIC();
  7513. report_current_position();
  7514. LCD_MESSAGEPGM(MSG_HOME_OFFSETS_APPLIED);
  7515. BUZZ(100, 659);
  7516. BUZZ(100, 698);
  7517. }
  7518. }
  7519. #endif // HAS_M206_COMMAND
  7520. /**
  7521. * M500: Store settings in EEPROM
  7522. */
  7523. inline void gcode_M500() {
  7524. (void)settings.save();
  7525. }
  7526. /**
  7527. * M501: Read settings from EEPROM
  7528. */
  7529. inline void gcode_M501() {
  7530. (void)settings.load();
  7531. }
  7532. /**
  7533. * M502: Revert to default settings
  7534. */
  7535. inline void gcode_M502() {
  7536. (void)settings.reset();
  7537. }
  7538. /**
  7539. * M503: print settings currently in memory
  7540. */
  7541. inline void gcode_M503() {
  7542. (void)settings.report(parser.seen('S') && !parser.value_bool());
  7543. }
  7544. #if ENABLED(ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  7545. /**
  7546. * M540: Set whether SD card print should abort on endstop hit (M540 S<0|1>)
  7547. */
  7548. inline void gcode_M540() {
  7549. if (parser.seen('S')) stepper.abort_on_endstop_hit = parser.value_bool();
  7550. }
  7551. #endif // ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED
  7552. #if HAS_BED_PROBE
  7553. void refresh_zprobe_zoffset(const bool no_babystep/*=false*/) {
  7554. static float last_zoffset = NAN;
  7555. if (!isnan(last_zoffset)) {
  7556. #if ENABLED(AUTO_BED_LEVELING_BILINEAR) || ENABLED(BABYSTEP_ZPROBE_OFFSET) || ENABLED(DELTA)
  7557. const float diff = zprobe_zoffset - last_zoffset;
  7558. #endif
  7559. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  7560. // Correct bilinear grid for new probe offset
  7561. if (diff) {
  7562. for (uint8_t x = 0; x < GRID_MAX_POINTS_X; x++)
  7563. for (uint8_t y = 0; y < GRID_MAX_POINTS_Y; y++)
  7564. z_values[x][y] -= diff;
  7565. }
  7566. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  7567. bed_level_virt_interpolate();
  7568. #endif
  7569. #endif
  7570. #if ENABLED(BABYSTEP_ZPROBE_OFFSET)
  7571. if (!no_babystep && leveling_is_active())
  7572. thermalManager.babystep_axis(Z_AXIS, -lround(diff * planner.axis_steps_per_mm[Z_AXIS]));
  7573. #else
  7574. UNUSED(no_babystep);
  7575. #endif
  7576. #if ENABLED(DELTA) // correct the delta_height
  7577. home_offset[Z_AXIS] -= diff;
  7578. #endif
  7579. }
  7580. last_zoffset = zprobe_zoffset;
  7581. }
  7582. inline void gcode_M851() {
  7583. SERIAL_ECHO_START;
  7584. SERIAL_ECHOPGM(MSG_ZPROBE_ZOFFSET " ");
  7585. if (parser.seen('Z')) {
  7586. const float value = parser.value_linear_units();
  7587. if (WITHIN(value, Z_PROBE_OFFSET_RANGE_MIN, Z_PROBE_OFFSET_RANGE_MAX)) {
  7588. zprobe_zoffset = value;
  7589. refresh_zprobe_zoffset();
  7590. SERIAL_ECHO(zprobe_zoffset);
  7591. }
  7592. else
  7593. SERIAL_ECHOPGM(MSG_Z_MIN " " STRINGIFY(Z_PROBE_OFFSET_RANGE_MIN) " " MSG_Z_MAX " " STRINGIFY(Z_PROBE_OFFSET_RANGE_MAX));
  7594. }
  7595. else
  7596. SERIAL_ECHOPAIR(": ", zprobe_zoffset);
  7597. SERIAL_EOL;
  7598. }
  7599. #endif // HAS_BED_PROBE
  7600. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  7601. /**
  7602. * M600: Pause for filament change
  7603. *
  7604. * E[distance] - Retract the filament this far (negative value)
  7605. * Z[distance] - Move the Z axis by this distance
  7606. * X[position] - Move to this X position, with Y
  7607. * Y[position] - Move to this Y position, with X
  7608. * U[distance] - Retract distance for removal (negative value) (manual reload)
  7609. * L[distance] - Extrude distance for insertion (positive value) (manual reload)
  7610. * B[count] - Number of times to beep, -1 for indefinite (if equipped with a buzzer)
  7611. *
  7612. * Default values are used for omitted arguments.
  7613. *
  7614. */
  7615. inline void gcode_M600() {
  7616. // Initial retract before move to filament change position
  7617. const float retract = parser.seen('E') ? parser.value_axis_units(E_AXIS) : 0
  7618. #if defined(PAUSE_PARK_RETRACT_LENGTH) && PAUSE_PARK_RETRACT_LENGTH > 0
  7619. - (PAUSE_PARK_RETRACT_LENGTH)
  7620. #endif
  7621. ;
  7622. // Lift Z axis
  7623. const float z_lift = parser.seen('Z') ? parser.value_linear_units() :
  7624. #if defined(PAUSE_PARK_Z_ADD) && PAUSE_PARK_Z_ADD > 0
  7625. PAUSE_PARK_Z_ADD
  7626. #else
  7627. 0
  7628. #endif
  7629. ;
  7630. // Move XY axes to filament exchange position
  7631. const float x_pos = parser.seen('X') ? parser.value_linear_units() : 0
  7632. #ifdef PAUSE_PARK_X_POS
  7633. + PAUSE_PARK_X_POS
  7634. #endif
  7635. ;
  7636. const float y_pos = parser.seen('Y') ? parser.value_linear_units() : 0
  7637. #ifdef PAUSE_PARK_Y_POS
  7638. + PAUSE_PARK_Y_POS
  7639. #endif
  7640. ;
  7641. // Unload filament
  7642. const float unload_length = parser.seen('U') ? parser.value_axis_units(E_AXIS) : 0
  7643. #if defined(FILAMENT_CHANGE_UNLOAD_LENGTH) && FILAMENT_CHANGE_UNLOAD_LENGTH > 0
  7644. - (FILAMENT_CHANGE_UNLOAD_LENGTH)
  7645. #endif
  7646. ;
  7647. // Load filament
  7648. const float load_length = parser.seen('L') ? parser.value_axis_units(E_AXIS) : 0
  7649. #ifdef FILAMENT_CHANGE_LOAD_LENGTH
  7650. + FILAMENT_CHANGE_LOAD_LENGTH
  7651. #endif
  7652. ;
  7653. const int beep_count = parser.seen('B') ? parser.value_int() :
  7654. #ifdef FILAMENT_CHANGE_NUMBER_OF_ALERT_BEEPS
  7655. FILAMENT_CHANGE_NUMBER_OF_ALERT_BEEPS
  7656. #else
  7657. -1
  7658. #endif
  7659. ;
  7660. const bool job_running = print_job_timer.isRunning();
  7661. if (pause_print(retract, z_lift, x_pos, y_pos, unload_length, beep_count, true)) {
  7662. wait_for_filament_reload(beep_count);
  7663. resume_print(load_length, ADVANCED_PAUSE_EXTRUDE_LENGTH, beep_count);
  7664. }
  7665. // Resume the print job timer if it was running
  7666. if (job_running) print_job_timer.start();
  7667. }
  7668. #endif // ADVANCED_PAUSE_FEATURE
  7669. #if ENABLED(DUAL_X_CARRIAGE)
  7670. /**
  7671. * M605: Set dual x-carriage movement mode
  7672. *
  7673. * M605 S0: Full control mode. The slicer has full control over x-carriage movement
  7674. * M605 S1: Auto-park mode. The inactive head will auto park/unpark without slicer involvement
  7675. * M605 S2 [Xnnn] [Rmmm]: Duplication mode. The second extruder will duplicate the first with nnn
  7676. * units x-offset and an optional differential hotend temperature of
  7677. * mmm degrees. E.g., with "M605 S2 X100 R2" the second extruder will duplicate
  7678. * the first with a spacing of 100mm in the x direction and 2 degrees hotter.
  7679. *
  7680. * Note: the X axis should be homed after changing dual x-carriage mode.
  7681. */
  7682. inline void gcode_M605() {
  7683. stepper.synchronize();
  7684. if (parser.seen('S')) dual_x_carriage_mode = (DualXMode)parser.value_byte();
  7685. switch (dual_x_carriage_mode) {
  7686. case DXC_FULL_CONTROL_MODE:
  7687. case DXC_AUTO_PARK_MODE:
  7688. break;
  7689. case DXC_DUPLICATION_MODE:
  7690. if (parser.seen('X')) duplicate_extruder_x_offset = max(parser.value_linear_units(), X2_MIN_POS - x_home_pos(0));
  7691. if (parser.seen('R')) duplicate_extruder_temp_offset = parser.value_celsius_diff();
  7692. SERIAL_ECHO_START;
  7693. SERIAL_ECHOPGM(MSG_HOTEND_OFFSET);
  7694. SERIAL_CHAR(' ');
  7695. SERIAL_ECHO(hotend_offset[X_AXIS][0]);
  7696. SERIAL_CHAR(',');
  7697. SERIAL_ECHO(hotend_offset[Y_AXIS][0]);
  7698. SERIAL_CHAR(' ');
  7699. SERIAL_ECHO(duplicate_extruder_x_offset);
  7700. SERIAL_CHAR(',');
  7701. SERIAL_ECHOLN(hotend_offset[Y_AXIS][1]);
  7702. break;
  7703. default:
  7704. dual_x_carriage_mode = DEFAULT_DUAL_X_CARRIAGE_MODE;
  7705. break;
  7706. }
  7707. active_extruder_parked = false;
  7708. extruder_duplication_enabled = false;
  7709. delayed_move_time = 0;
  7710. }
  7711. #elif ENABLED(DUAL_NOZZLE_DUPLICATION_MODE)
  7712. inline void gcode_M605() {
  7713. stepper.synchronize();
  7714. extruder_duplication_enabled = parser.seen('S') && parser.value_int() == (int)DXC_DUPLICATION_MODE;
  7715. SERIAL_ECHO_START;
  7716. SERIAL_ECHOLNPAIR(MSG_DUPLICATION_MODE, extruder_duplication_enabled ? MSG_ON : MSG_OFF);
  7717. }
  7718. #endif // DUAL_NOZZLE_DUPLICATION_MODE
  7719. #if ENABLED(LIN_ADVANCE)
  7720. /**
  7721. * M900: Set and/or Get advance K factor and WH/D ratio
  7722. *
  7723. * K<factor> Set advance K factor
  7724. * R<ratio> Set ratio directly (overrides WH/D)
  7725. * W<width> H<height> D<diam> Set ratio from WH/D
  7726. */
  7727. inline void gcode_M900() {
  7728. stepper.synchronize();
  7729. const float newK = parser.seen('K') ? parser.value_float() : -1;
  7730. if (newK >= 0) planner.extruder_advance_k = newK;
  7731. float newR = parser.seen('R') ? parser.value_float() : -1;
  7732. if (newR < 0) {
  7733. const float newD = parser.seen('D') ? parser.value_float() : -1,
  7734. newW = parser.seen('W') ? parser.value_float() : -1,
  7735. newH = parser.seen('H') ? parser.value_float() : -1;
  7736. if (newD >= 0 && newW >= 0 && newH >= 0)
  7737. newR = newD ? (newW * newH) / (sq(newD * 0.5) * M_PI) : 0;
  7738. }
  7739. if (newR >= 0) planner.advance_ed_ratio = newR;
  7740. SERIAL_ECHO_START;
  7741. SERIAL_ECHOPAIR("Advance K=", planner.extruder_advance_k);
  7742. SERIAL_ECHOPGM(" E/D=");
  7743. const float ratio = planner.advance_ed_ratio;
  7744. if (ratio) SERIAL_ECHO(ratio); else SERIAL_ECHOPGM("Auto");
  7745. SERIAL_EOL;
  7746. }
  7747. #endif // LIN_ADVANCE
  7748. #if ENABLED(HAVE_TMC2130)
  7749. static void tmc2130_get_current(TMC2130Stepper &st, const char name) {
  7750. SERIAL_CHAR(name);
  7751. SERIAL_ECHOPGM(" axis driver current: ");
  7752. SERIAL_ECHOLN(st.getCurrent());
  7753. }
  7754. static void tmc2130_set_current(TMC2130Stepper &st, const char name, const int mA) {
  7755. st.setCurrent(mA, R_SENSE, HOLD_MULTIPLIER);
  7756. tmc2130_get_current(st, name);
  7757. }
  7758. static void tmc2130_report_otpw(TMC2130Stepper &st, const char name) {
  7759. SERIAL_CHAR(name);
  7760. SERIAL_ECHOPGM(" axis temperature prewarn triggered: ");
  7761. serialprintPGM(st.getOTPW() ? PSTR("true") : PSTR("false"));
  7762. SERIAL_EOL;
  7763. }
  7764. static void tmc2130_clear_otpw(TMC2130Stepper &st, const char name) {
  7765. st.clear_otpw();
  7766. SERIAL_CHAR(name);
  7767. SERIAL_ECHOLNPGM(" prewarn flag cleared");
  7768. }
  7769. static void tmc2130_get_pwmthrs(TMC2130Stepper &st, const char name, const uint16_t spmm) {
  7770. SERIAL_CHAR(name);
  7771. SERIAL_ECHOPGM(" stealthChop max speed set to ");
  7772. SERIAL_ECHOLN(12650000UL * st.microsteps() / (256 * st.stealth_max_speed() * spmm));
  7773. }
  7774. static void tmc2130_set_pwmthrs(TMC2130Stepper &st, const char name, const int32_t thrs, const uint32_t spmm) {
  7775. st.stealth_max_speed(12650000UL * st.microsteps() / (256 * thrs * spmm));
  7776. tmc2130_get_pwmthrs(st, name, spmm);
  7777. }
  7778. static void tmc2130_get_sgt(TMC2130Stepper &st, const char name) {
  7779. SERIAL_CHAR(name);
  7780. SERIAL_ECHOPGM(" driver homing sensitivity set to ");
  7781. SERIAL_ECHOLN(st.sgt());
  7782. }
  7783. static void tmc2130_set_sgt(TMC2130Stepper &st, const char name, const int8_t sgt_val) {
  7784. st.sgt(sgt_val);
  7785. tmc2130_get_sgt(st, name);
  7786. }
  7787. /**
  7788. * M906: Set motor current in milliamps using axis codes X, Y, Z, E
  7789. * Report driver currents when no axis specified
  7790. *
  7791. * S1: Enable automatic current control
  7792. * S0: Disable
  7793. */
  7794. inline void gcode_M906() {
  7795. uint16_t values[XYZE];
  7796. LOOP_XYZE(i)
  7797. values[i] = parser.seen(axis_codes[i]) ? parser.value_int() : 0;
  7798. #if ENABLED(X_IS_TMC2130)
  7799. if (values[X_AXIS]) tmc2130_set_current(stepperX, 'X', values[X_AXIS]);
  7800. else tmc2130_get_current(stepperX, 'X');
  7801. #endif
  7802. #if ENABLED(Y_IS_TMC2130)
  7803. if (values[Y_AXIS]) tmc2130_set_current(stepperY, 'Y', values[Y_AXIS]);
  7804. else tmc2130_get_current(stepperY, 'Y');
  7805. #endif
  7806. #if ENABLED(Z_IS_TMC2130)
  7807. if (values[Z_AXIS]) tmc2130_set_current(stepperZ, 'Z', values[Z_AXIS]);
  7808. else tmc2130_get_current(stepperZ, 'Z');
  7809. #endif
  7810. #if ENABLED(E0_IS_TMC2130)
  7811. if (values[E_AXIS]) tmc2130_set_current(stepperE0, 'E', values[E_AXIS]);
  7812. else tmc2130_get_current(stepperE0, 'E');
  7813. #endif
  7814. #if ENABLED(AUTOMATIC_CURRENT_CONTROL)
  7815. if (parser.seen('S')) auto_current_control = parser.value_bool();
  7816. #endif
  7817. }
  7818. /**
  7819. * M911: Report TMC2130 stepper driver overtemperature pre-warn flag
  7820. * The flag is held by the library and persist until manually cleared by M912
  7821. */
  7822. inline void gcode_M911() {
  7823. const bool reportX = parser.seen('X'), reportY = parser.seen('Y'), reportZ = parser.seen('Z'), reportE = parser.seen('E'),
  7824. reportAll = (!reportX && !reportY && !reportZ && !reportE) || (reportX && reportY && reportZ && reportE);
  7825. #if ENABLED(X_IS_TMC2130)
  7826. if (reportX || reportAll) tmc2130_report_otpw(stepperX, 'X');
  7827. #endif
  7828. #if ENABLED(Y_IS_TMC2130)
  7829. if (reportY || reportAll) tmc2130_report_otpw(stepperY, 'Y');
  7830. #endif
  7831. #if ENABLED(Z_IS_TMC2130)
  7832. if (reportZ || reportAll) tmc2130_report_otpw(stepperZ, 'Z');
  7833. #endif
  7834. #if ENABLED(E0_IS_TMC2130)
  7835. if (reportE || reportAll) tmc2130_report_otpw(stepperE0, 'E');
  7836. #endif
  7837. }
  7838. /**
  7839. * M912: Clear TMC2130 stepper driver overtemperature pre-warn flag held by the library
  7840. */
  7841. inline void gcode_M912() {
  7842. const bool clearX = parser.seen('X'), clearY = parser.seen('Y'), clearZ = parser.seen('Z'), clearE = parser.seen('E'),
  7843. clearAll = (!clearX && !clearY && !clearZ && !clearE) || (clearX && clearY && clearZ && clearE);
  7844. #if ENABLED(X_IS_TMC2130)
  7845. if (clearX || clearAll) tmc2130_clear_otpw(stepperX, 'X');
  7846. #endif
  7847. #if ENABLED(Y_IS_TMC2130)
  7848. if (clearY || clearAll) tmc2130_clear_otpw(stepperY, 'Y');
  7849. #endif
  7850. #if ENABLED(Z_IS_TMC2130)
  7851. if (clearZ || clearAll) tmc2130_clear_otpw(stepperZ, 'Z');
  7852. #endif
  7853. #if ENABLED(E0_IS_TMC2130)
  7854. if (clearE || clearAll) tmc2130_clear_otpw(stepperE0, 'E');
  7855. #endif
  7856. }
  7857. /**
  7858. * M913: Set HYBRID_THRESHOLD speed.
  7859. */
  7860. #if ENABLED(HYBRID_THRESHOLD)
  7861. inline void gcode_M913() {
  7862. uint16_t values[XYZE];
  7863. LOOP_XYZE(i)
  7864. values[i] = parser.seen(axis_codes[i]) ? parser.value_int() : 0;
  7865. #if ENABLED(X_IS_TMC2130)
  7866. if (values[X_AXIS]) tmc2130_set_pwmthrs(stepperX, 'X', values[X_AXIS], planner.axis_steps_per_mm[X_AXIS]);
  7867. else tmc2130_get_pwmthrs(stepperX, 'X', planner.axis_steps_per_mm[X_AXIS]);
  7868. #endif
  7869. #if ENABLED(Y_IS_TMC2130)
  7870. if (values[Y_AXIS]) tmc2130_set_pwmthrs(stepperY, 'Y', values[Y_AXIS], planner.axis_steps_per_mm[Y_AXIS]);
  7871. else tmc2130_get_pwmthrs(stepperY, 'Y', planner.axis_steps_per_mm[Y_AXIS]);
  7872. #endif
  7873. #if ENABLED(Z_IS_TMC2130)
  7874. if (values[Z_AXIS]) tmc2130_set_pwmthrs(stepperZ, 'Z', values[Z_AXIS], planner.axis_steps_per_mm[Z_AXIS]);
  7875. else tmc2130_get_pwmthrs(stepperZ, 'Z', planner.axis_steps_per_mm[Z_AXIS]);
  7876. #endif
  7877. #if ENABLED(E0_IS_TMC2130)
  7878. if (values[E_AXIS]) tmc2130_set_pwmthrs(stepperE0, 'E', values[E_AXIS], planner.axis_steps_per_mm[E_AXIS]);
  7879. else tmc2130_get_pwmthrs(stepperE0, 'E', planner.axis_steps_per_mm[E_AXIS]);
  7880. #endif
  7881. }
  7882. #endif // HYBRID_THRESHOLD
  7883. /**
  7884. * M914: Set SENSORLESS_HOMING sensitivity.
  7885. */
  7886. #if ENABLED(SENSORLESS_HOMING)
  7887. inline void gcode_M914() {
  7888. #if ENABLED(X_IS_TMC2130)
  7889. if (parser.seen(axis_codes[X_AXIS])) tmc2130_set_sgt(stepperX, 'X', parser.value_int());
  7890. else tmc2130_get_sgt(stepperX, 'X');
  7891. #endif
  7892. #if ENABLED(Y_IS_TMC2130)
  7893. if (parser.seen(axis_codes[Y_AXIS])) tmc2130_set_sgt(stepperY, 'Y', parser.value_int());
  7894. else tmc2130_get_sgt(stepperY, 'Y');
  7895. #endif
  7896. }
  7897. #endif // SENSORLESS_HOMING
  7898. #endif // HAVE_TMC2130
  7899. /**
  7900. * M907: Set digital trimpot motor current using axis codes X, Y, Z, E, B, S
  7901. */
  7902. inline void gcode_M907() {
  7903. #if HAS_DIGIPOTSS
  7904. LOOP_XYZE(i) if (parser.seen(axis_codes[i])) stepper.digipot_current(i, parser.value_int());
  7905. if (parser.seen('B')) stepper.digipot_current(4, parser.value_int());
  7906. if (parser.seen('S')) for (uint8_t i = 0; i <= 4; i++) stepper.digipot_current(i, parser.value_int());
  7907. #elif HAS_MOTOR_CURRENT_PWM
  7908. #if PIN_EXISTS(MOTOR_CURRENT_PWM_XY)
  7909. if (parser.seen('X')) stepper.digipot_current(0, parser.value_int());
  7910. #endif
  7911. #if PIN_EXISTS(MOTOR_CURRENT_PWM_Z)
  7912. if (parser.seen('Z')) stepper.digipot_current(1, parser.value_int());
  7913. #endif
  7914. #if PIN_EXISTS(MOTOR_CURRENT_PWM_E)
  7915. if (parser.seen('E')) stepper.digipot_current(2, parser.value_int());
  7916. #endif
  7917. #endif
  7918. #if ENABLED(DIGIPOT_I2C)
  7919. // this one uses actual amps in floating point
  7920. LOOP_XYZE(i) if (parser.seen(axis_codes[i])) digipot_i2c_set_current(i, parser.value_float());
  7921. // for each additional extruder (named B,C,D,E..., channels 4,5,6,7...)
  7922. 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());
  7923. #endif
  7924. #if ENABLED(DAC_STEPPER_CURRENT)
  7925. if (parser.seen('S')) {
  7926. const float dac_percent = parser.value_float();
  7927. for (uint8_t i = 0; i <= 4; i++) dac_current_percent(i, dac_percent);
  7928. }
  7929. LOOP_XYZE(i) if (parser.seen(axis_codes[i])) dac_current_percent(i, parser.value_float());
  7930. #endif
  7931. }
  7932. #if HAS_DIGIPOTSS || ENABLED(DAC_STEPPER_CURRENT)
  7933. /**
  7934. * M908: Control digital trimpot directly (M908 P<pin> S<current>)
  7935. */
  7936. inline void gcode_M908() {
  7937. #if HAS_DIGIPOTSS
  7938. stepper.digitalPotWrite(
  7939. parser.seen('P') ? parser.value_int() : 0,
  7940. parser.seen('S') ? parser.value_int() : 0
  7941. );
  7942. #endif
  7943. #ifdef DAC_STEPPER_CURRENT
  7944. dac_current_raw(
  7945. parser.seen('P') ? parser.value_byte() : -1,
  7946. parser.seen('S') ? parser.value_ushort() : 0
  7947. );
  7948. #endif
  7949. }
  7950. #if ENABLED(DAC_STEPPER_CURRENT) // As with Printrbot RevF
  7951. inline void gcode_M909() { dac_print_values(); }
  7952. inline void gcode_M910() { dac_commit_eeprom(); }
  7953. #endif
  7954. #endif // HAS_DIGIPOTSS || DAC_STEPPER_CURRENT
  7955. #if HAS_MICROSTEPS
  7956. // M350 Set microstepping mode. Warning: Steps per unit remains unchanged. S code sets stepping mode for all drivers.
  7957. inline void gcode_M350() {
  7958. if (parser.seen('S')) for (int i = 0; i <= 4; i++) stepper.microstep_mode(i, parser.value_byte());
  7959. LOOP_XYZE(i) if (parser.seen(axis_codes[i])) stepper.microstep_mode(i, parser.value_byte());
  7960. if (parser.seen('B')) stepper.microstep_mode(4, parser.value_byte());
  7961. stepper.microstep_readings();
  7962. }
  7963. /**
  7964. * M351: Toggle MS1 MS2 pins directly with axis codes X Y Z E B
  7965. * S# determines MS1 or MS2, X# sets the pin high/low.
  7966. */
  7967. inline void gcode_M351() {
  7968. if (parser.seen('S')) switch (parser.value_byte()) {
  7969. case 1:
  7970. LOOP_XYZE(i) if (parser.seen(axis_codes[i])) stepper.microstep_ms(i, parser.value_byte(), -1);
  7971. if (parser.seen('B')) stepper.microstep_ms(4, parser.value_byte(), -1);
  7972. break;
  7973. case 2:
  7974. LOOP_XYZE(i) if (parser.seen(axis_codes[i])) stepper.microstep_ms(i, -1, parser.value_byte());
  7975. if (parser.seen('B')) stepper.microstep_ms(4, -1, parser.value_byte());
  7976. break;
  7977. }
  7978. stepper.microstep_readings();
  7979. }
  7980. #endif // HAS_MICROSTEPS
  7981. #if HAS_CASE_LIGHT
  7982. uint8_t case_light_brightness = 255;
  7983. void update_case_light() {
  7984. WRITE(CASE_LIGHT_PIN, case_light_on != INVERT_CASE_LIGHT ? HIGH : LOW);
  7985. analogWrite(CASE_LIGHT_PIN, case_light_on != INVERT_CASE_LIGHT ? case_light_brightness : 0);
  7986. }
  7987. #endif // HAS_CASE_LIGHT
  7988. /**
  7989. * M355: Turn case lights on/off and set brightness
  7990. *
  7991. * S<bool> Turn case light on or off
  7992. * P<byte> Set case light brightness (PWM pin required)
  7993. */
  7994. inline void gcode_M355() {
  7995. #if HAS_CASE_LIGHT
  7996. if (parser.seen('P')) case_light_brightness = parser.value_byte();
  7997. if (parser.seen('S')) case_light_on = parser.value_bool();
  7998. update_case_light();
  7999. SERIAL_ECHO_START;
  8000. SERIAL_ECHOPGM("Case lights ");
  8001. case_light_on ? SERIAL_ECHOLNPGM("on") : SERIAL_ECHOLNPGM("off");
  8002. #else
  8003. SERIAL_ERROR_START;
  8004. SERIAL_ERRORLNPGM(MSG_ERR_M355_NONE);
  8005. #endif // HAS_CASE_LIGHT
  8006. }
  8007. #if ENABLED(MIXING_EXTRUDER)
  8008. /**
  8009. * M163: Set a single mix factor for a mixing extruder
  8010. * This is called "weight" by some systems.
  8011. *
  8012. * S[index] The channel index to set
  8013. * P[float] The mix value
  8014. *
  8015. */
  8016. inline void gcode_M163() {
  8017. const int mix_index = parser.seen('S') ? parser.value_int() : 0;
  8018. if (mix_index < MIXING_STEPPERS) {
  8019. float mix_value = parser.seen('P') ? parser.value_float() : 0.0;
  8020. NOLESS(mix_value, 0.0);
  8021. mixing_factor[mix_index] = RECIPROCAL(mix_value);
  8022. }
  8023. }
  8024. #if MIXING_VIRTUAL_TOOLS > 1
  8025. /**
  8026. * M164: Store the current mix factors as a virtual tool.
  8027. *
  8028. * S[index] The virtual tool to store
  8029. *
  8030. */
  8031. inline void gcode_M164() {
  8032. const int tool_index = parser.seen('S') ? parser.value_int() : 0;
  8033. if (tool_index < MIXING_VIRTUAL_TOOLS) {
  8034. normalize_mix();
  8035. for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
  8036. mixing_virtual_tool_mix[tool_index][i] = mixing_factor[i];
  8037. }
  8038. }
  8039. #endif
  8040. #if ENABLED(DIRECT_MIXING_IN_G1)
  8041. /**
  8042. * M165: Set multiple mix factors for a mixing extruder.
  8043. * Factors that are left out will be set to 0.
  8044. * All factors together must add up to 1.0.
  8045. *
  8046. * A[factor] Mix factor for extruder stepper 1
  8047. * B[factor] Mix factor for extruder stepper 2
  8048. * C[factor] Mix factor for extruder stepper 3
  8049. * D[factor] Mix factor for extruder stepper 4
  8050. * H[factor] Mix factor for extruder stepper 5
  8051. * I[factor] Mix factor for extruder stepper 6
  8052. *
  8053. */
  8054. inline void gcode_M165() { gcode_get_mix(); }
  8055. #endif
  8056. #endif // MIXING_EXTRUDER
  8057. /**
  8058. * M999: Restart after being stopped
  8059. *
  8060. * Default behaviour is to flush the serial buffer and request
  8061. * a resend to the host starting on the last N line received.
  8062. *
  8063. * Sending "M999 S1" will resume printing without flushing the
  8064. * existing command buffer.
  8065. *
  8066. */
  8067. inline void gcode_M999() {
  8068. Running = true;
  8069. lcd_reset_alert_level();
  8070. if (parser.seen('S') && parser.value_bool()) return;
  8071. // gcode_LastN = Stopped_gcode_LastN;
  8072. FlushSerialRequestResend();
  8073. }
  8074. #if ENABLED(SWITCHING_EXTRUDER)
  8075. inline void move_extruder_servo(uint8_t e) {
  8076. const int angles[2] = SWITCHING_EXTRUDER_SERVO_ANGLES;
  8077. MOVE_SERVO(SWITCHING_EXTRUDER_SERVO_NR, angles[e]);
  8078. safe_delay(500);
  8079. }
  8080. #endif
  8081. #if ENABLED(SWITCHING_NOZZLE)
  8082. inline void move_nozzle_servo(uint8_t e) {
  8083. const int angles[2] = SWITCHING_NOZZLE_SERVO_ANGLES;
  8084. MOVE_SERVO(SWITCHING_NOZZLE_SERVO_NR, angles[e]);
  8085. safe_delay(500);
  8086. }
  8087. #endif
  8088. inline void invalid_extruder_error(const uint8_t &e) {
  8089. SERIAL_ECHO_START;
  8090. SERIAL_CHAR('T');
  8091. SERIAL_ECHO_F(e, DEC);
  8092. SERIAL_ECHOLN(MSG_INVALID_EXTRUDER);
  8093. }
  8094. /**
  8095. * Perform a tool-change, which may result in moving the
  8096. * previous tool out of the way and the new tool into place.
  8097. */
  8098. void tool_change(const uint8_t tmp_extruder, const float fr_mm_s/*=0.0*/, bool no_move/*=false*/) {
  8099. #if ENABLED(MIXING_EXTRUDER) && MIXING_VIRTUAL_TOOLS > 1
  8100. if (tmp_extruder >= MIXING_VIRTUAL_TOOLS)
  8101. return invalid_extruder_error(tmp_extruder);
  8102. // T0-Tnnn: Switch virtual tool by changing the mix
  8103. for (uint8_t j = 0; j < MIXING_STEPPERS; j++)
  8104. mixing_factor[j] = mixing_virtual_tool_mix[tmp_extruder][j];
  8105. #else // !MIXING_EXTRUDER || MIXING_VIRTUAL_TOOLS <= 1
  8106. #if HOTENDS > 1
  8107. if (tmp_extruder >= EXTRUDERS)
  8108. return invalid_extruder_error(tmp_extruder);
  8109. const float old_feedrate_mm_s = fr_mm_s > 0.0 ? fr_mm_s : feedrate_mm_s;
  8110. feedrate_mm_s = fr_mm_s > 0.0 ? fr_mm_s : XY_PROBE_FEEDRATE_MM_S;
  8111. if (tmp_extruder != active_extruder) {
  8112. if (!no_move && axis_unhomed_error()) {
  8113. SERIAL_ECHOLNPGM("No move on toolchange");
  8114. no_move = true;
  8115. }
  8116. // Save current position to destination, for use later
  8117. set_destination_to_current();
  8118. #if ENABLED(DUAL_X_CARRIAGE)
  8119. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8120. if (DEBUGGING(LEVELING)) {
  8121. SERIAL_ECHOPGM("Dual X Carriage Mode ");
  8122. switch (dual_x_carriage_mode) {
  8123. case DXC_FULL_CONTROL_MODE: SERIAL_ECHOLNPGM("DXC_FULL_CONTROL_MODE"); break;
  8124. case DXC_AUTO_PARK_MODE: SERIAL_ECHOLNPGM("DXC_AUTO_PARK_MODE"); break;
  8125. case DXC_DUPLICATION_MODE: SERIAL_ECHOLNPGM("DXC_DUPLICATION_MODE"); break;
  8126. }
  8127. }
  8128. #endif
  8129. const float xhome = x_home_pos(active_extruder);
  8130. if (dual_x_carriage_mode == DXC_AUTO_PARK_MODE
  8131. && IsRunning()
  8132. && (delayed_move_time || current_position[X_AXIS] != xhome)
  8133. ) {
  8134. float raised_z = current_position[Z_AXIS] + TOOLCHANGE_PARK_ZLIFT;
  8135. #if ENABLED(MAX_SOFTWARE_ENDSTOPS)
  8136. NOMORE(raised_z, soft_endstop_max[Z_AXIS]);
  8137. #endif
  8138. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8139. if (DEBUGGING(LEVELING)) {
  8140. SERIAL_ECHOLNPAIR("Raise to ", raised_z);
  8141. SERIAL_ECHOLNPAIR("MoveX to ", xhome);
  8142. SERIAL_ECHOLNPAIR("Lower to ", current_position[Z_AXIS]);
  8143. }
  8144. #endif
  8145. // Park old head: 1) raise 2) move to park position 3) lower
  8146. for (uint8_t i = 0; i < 3; i++)
  8147. planner.buffer_line(
  8148. i == 0 ? current_position[X_AXIS] : xhome,
  8149. current_position[Y_AXIS],
  8150. i == 2 ? current_position[Z_AXIS] : raised_z,
  8151. current_position[E_AXIS],
  8152. planner.max_feedrate_mm_s[i == 1 ? X_AXIS : Z_AXIS],
  8153. active_extruder
  8154. );
  8155. stepper.synchronize();
  8156. }
  8157. // Apply Y & Z extruder offset (X offset is used as home pos with Dual X)
  8158. current_position[Y_AXIS] -= hotend_offset[Y_AXIS][active_extruder] - hotend_offset[Y_AXIS][tmp_extruder];
  8159. current_position[Z_AXIS] -= hotend_offset[Z_AXIS][active_extruder] - hotend_offset[Z_AXIS][tmp_extruder];
  8160. // Activate the new extruder
  8161. active_extruder = tmp_extruder;
  8162. // This function resets the max/min values - the current position may be overwritten below.
  8163. set_axis_is_at_home(X_AXIS);
  8164. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8165. if (DEBUGGING(LEVELING)) DEBUG_POS("New Extruder", current_position);
  8166. #endif
  8167. // Only when auto-parking are carriages safe to move
  8168. if (dual_x_carriage_mode != DXC_AUTO_PARK_MODE) no_move = true;
  8169. switch (dual_x_carriage_mode) {
  8170. case DXC_FULL_CONTROL_MODE:
  8171. // New current position is the position of the activated extruder
  8172. current_position[X_AXIS] = LOGICAL_X_POSITION(inactive_extruder_x_pos);
  8173. // Save the inactive extruder's position (from the old current_position)
  8174. inactive_extruder_x_pos = RAW_X_POSITION(destination[X_AXIS]);
  8175. break;
  8176. case DXC_AUTO_PARK_MODE:
  8177. // record raised toolhead position for use by unpark
  8178. COPY(raised_parked_position, current_position);
  8179. raised_parked_position[Z_AXIS] += TOOLCHANGE_UNPARK_ZLIFT;
  8180. #if ENABLED(MAX_SOFTWARE_ENDSTOPS)
  8181. NOMORE(raised_parked_position[Z_AXIS], soft_endstop_max[Z_AXIS]);
  8182. #endif
  8183. active_extruder_parked = true;
  8184. delayed_move_time = 0;
  8185. break;
  8186. case DXC_DUPLICATION_MODE:
  8187. // If the new extruder is the left one, set it "parked"
  8188. // This triggers the second extruder to move into the duplication position
  8189. active_extruder_parked = (active_extruder == 0);
  8190. if (active_extruder_parked)
  8191. current_position[X_AXIS] = LOGICAL_X_POSITION(inactive_extruder_x_pos);
  8192. else
  8193. current_position[X_AXIS] = destination[X_AXIS] + duplicate_extruder_x_offset;
  8194. inactive_extruder_x_pos = RAW_X_POSITION(destination[X_AXIS]);
  8195. extruder_duplication_enabled = false;
  8196. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8197. if (DEBUGGING(LEVELING)) {
  8198. SERIAL_ECHOLNPAIR("Set inactive_extruder_x_pos=", inactive_extruder_x_pos);
  8199. SERIAL_ECHOLNPGM("Clear extruder_duplication_enabled");
  8200. }
  8201. #endif
  8202. break;
  8203. }
  8204. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8205. if (DEBUGGING(LEVELING)) {
  8206. SERIAL_ECHOLNPAIR("Active extruder parked: ", active_extruder_parked ? "yes" : "no");
  8207. DEBUG_POS("New extruder (parked)", current_position);
  8208. }
  8209. #endif
  8210. // No extra case for HAS_ABL in DUAL_X_CARRIAGE. Does that mean they don't work together?
  8211. #else // !DUAL_X_CARRIAGE
  8212. #if ENABLED(SWITCHING_NOZZLE)
  8213. // <0 if the new nozzle is higher, >0 if lower. A bigger raise when lower.
  8214. const float z_diff = hotend_offset[Z_AXIS][active_extruder] - hotend_offset[Z_AXIS][tmp_extruder],
  8215. z_raise = 0.3 + (z_diff > 0.0 ? z_diff : 0.0);
  8216. // Always raise by some amount (destination copied from current_position earlier)
  8217. current_position[Z_AXIS] += z_raise;
  8218. planner.buffer_line_kinematic(current_position, planner.max_feedrate_mm_s[Z_AXIS], active_extruder);
  8219. stepper.synchronize();
  8220. move_nozzle_servo(active_extruder);
  8221. #endif
  8222. #if ENABLED(SWITCHING_EXTRUDER)
  8223. #if !(ENABLED(SWITCHING_NOZZLE) && (SWITCHING_EXTRUDER_SERVO_NR == SWITCHING_NOZZLE_SERVO_NR))
  8224. stepper.synchronize();
  8225. move_extruder_servo(active_extruder);
  8226. #endif
  8227. #endif
  8228. /**
  8229. * Set current_position to the position of the new nozzle.
  8230. * Offsets are based on linear distance, so we need to get
  8231. * the resulting position in coordinate space.
  8232. *
  8233. * - With grid or 3-point leveling, offset XYZ by a tilted vector
  8234. * - With mesh leveling, update Z for the new position
  8235. * - Otherwise, just use the raw linear distance
  8236. *
  8237. * Software endstops are altered here too. Consider a case where:
  8238. * E0 at X=0 ... E1 at X=10
  8239. * When we switch to E1 now X=10, but E1 can't move left.
  8240. * To express this we apply the change in XY to the software endstops.
  8241. * E1 can move farther right than E0, so the right limit is extended.
  8242. *
  8243. * Note that we don't adjust the Z software endstops. Why not?
  8244. * Consider a case where Z=0 (here) and switching to E1 makes Z=1
  8245. * because the bed is 1mm lower at the new position. As long as
  8246. * the first nozzle is out of the way, the carriage should be
  8247. * allowed to move 1mm lower. This technically "breaks" the
  8248. * Z software endstop. But this is technically correct (and
  8249. * there is no viable alternative).
  8250. */
  8251. #if ABL_PLANAR
  8252. // Offset extruder, make sure to apply the bed level rotation matrix
  8253. vector_3 tmp_offset_vec = vector_3(hotend_offset[X_AXIS][tmp_extruder],
  8254. hotend_offset[Y_AXIS][tmp_extruder],
  8255. 0),
  8256. act_offset_vec = vector_3(hotend_offset[X_AXIS][active_extruder],
  8257. hotend_offset[Y_AXIS][active_extruder],
  8258. 0),
  8259. offset_vec = tmp_offset_vec - act_offset_vec;
  8260. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8261. if (DEBUGGING(LEVELING)) {
  8262. tmp_offset_vec.debug(PSTR("tmp_offset_vec"));
  8263. act_offset_vec.debug(PSTR("act_offset_vec"));
  8264. offset_vec.debug(PSTR("offset_vec (BEFORE)"));
  8265. }
  8266. #endif
  8267. offset_vec.apply_rotation(planner.bed_level_matrix.transpose(planner.bed_level_matrix));
  8268. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8269. if (DEBUGGING(LEVELING)) offset_vec.debug(PSTR("offset_vec (AFTER)"));
  8270. #endif
  8271. // Adjustments to the current position
  8272. const float xydiff[2] = { offset_vec.x, offset_vec.y };
  8273. current_position[Z_AXIS] += offset_vec.z;
  8274. #else // !ABL_PLANAR
  8275. const float xydiff[2] = {
  8276. hotend_offset[X_AXIS][tmp_extruder] - hotend_offset[X_AXIS][active_extruder],
  8277. hotend_offset[Y_AXIS][tmp_extruder] - hotend_offset[Y_AXIS][active_extruder]
  8278. };
  8279. #if ENABLED(MESH_BED_LEVELING)
  8280. if (leveling_is_active()) {
  8281. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8282. if (DEBUGGING(LEVELING)) SERIAL_ECHOPAIR("Z before MBL: ", current_position[Z_AXIS]);
  8283. #endif
  8284. float x2 = current_position[X_AXIS] + xydiff[X_AXIS],
  8285. y2 = current_position[Y_AXIS] + xydiff[Y_AXIS],
  8286. z1 = current_position[Z_AXIS], z2 = z1;
  8287. planner.apply_leveling(current_position[X_AXIS], current_position[Y_AXIS], z1);
  8288. planner.apply_leveling(x2, y2, z2);
  8289. current_position[Z_AXIS] += z2 - z1;
  8290. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8291. if (DEBUGGING(LEVELING))
  8292. SERIAL_ECHOLNPAIR(" after: ", current_position[Z_AXIS]);
  8293. #endif
  8294. }
  8295. #endif // MESH_BED_LEVELING
  8296. #endif // !HAS_ABL
  8297. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8298. if (DEBUGGING(LEVELING)) {
  8299. SERIAL_ECHOPAIR("Offset Tool XY by { ", xydiff[X_AXIS]);
  8300. SERIAL_ECHOPAIR(", ", xydiff[Y_AXIS]);
  8301. SERIAL_ECHOLNPGM(" }");
  8302. }
  8303. #endif
  8304. // The newly-selected extruder XY is actually at...
  8305. current_position[X_AXIS] += xydiff[X_AXIS];
  8306. current_position[Y_AXIS] += xydiff[Y_AXIS];
  8307. #if HAS_WORKSPACE_OFFSET || ENABLED(DUAL_X_CARRIAGE)
  8308. for (uint8_t i = X_AXIS; i <= Y_AXIS; i++) {
  8309. #if HAS_POSITION_SHIFT
  8310. position_shift[i] += xydiff[i];
  8311. #endif
  8312. update_software_endstops((AxisEnum)i);
  8313. }
  8314. #endif
  8315. // Set the new active extruder
  8316. active_extruder = tmp_extruder;
  8317. #endif // !DUAL_X_CARRIAGE
  8318. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8319. if (DEBUGGING(LEVELING)) DEBUG_POS("Sync After Toolchange", current_position);
  8320. #endif
  8321. // Tell the planner the new "current position"
  8322. SYNC_PLAN_POSITION_KINEMATIC();
  8323. // Move to the "old position" (move the extruder into place)
  8324. if (!no_move && IsRunning()) {
  8325. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8326. if (DEBUGGING(LEVELING)) DEBUG_POS("Move back", destination);
  8327. #endif
  8328. prepare_move_to_destination();
  8329. }
  8330. #if ENABLED(SWITCHING_NOZZLE)
  8331. // Move back down, if needed. (Including when the new tool is higher.)
  8332. if (z_raise != z_diff) {
  8333. destination[Z_AXIS] += z_diff;
  8334. feedrate_mm_s = planner.max_feedrate_mm_s[Z_AXIS];
  8335. prepare_move_to_destination();
  8336. }
  8337. #endif
  8338. } // (tmp_extruder != active_extruder)
  8339. stepper.synchronize();
  8340. #if ENABLED(EXT_SOLENOID)
  8341. disable_all_solenoids();
  8342. enable_solenoid_on_active_extruder();
  8343. #endif // EXT_SOLENOID
  8344. feedrate_mm_s = old_feedrate_mm_s;
  8345. #else // HOTENDS <= 1
  8346. // Set the new active extruder
  8347. active_extruder = tmp_extruder;
  8348. UNUSED(fr_mm_s);
  8349. UNUSED(no_move);
  8350. #if ENABLED(SWITCHING_EXTRUDER)
  8351. stepper.synchronize();
  8352. move_extruder_servo(active_extruder);
  8353. #endif
  8354. #endif // HOTENDS <= 1
  8355. SERIAL_ECHO_START;
  8356. SERIAL_ECHOLNPAIR(MSG_ACTIVE_EXTRUDER, (int)active_extruder);
  8357. #endif // !MIXING_EXTRUDER || MIXING_VIRTUAL_TOOLS <= 1
  8358. }
  8359. /**
  8360. * T0-T3: Switch tool, usually switching extruders
  8361. *
  8362. * F[units/min] Set the movement feedrate
  8363. * S1 Don't move the tool in XY after change
  8364. */
  8365. inline void gcode_T(uint8_t tmp_extruder) {
  8366. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8367. if (DEBUGGING(LEVELING)) {
  8368. SERIAL_ECHOPAIR(">>> gcode_T(", tmp_extruder);
  8369. SERIAL_CHAR(')');
  8370. SERIAL_EOL;
  8371. DEBUG_POS("BEFORE", current_position);
  8372. }
  8373. #endif
  8374. #if HOTENDS == 1 || (ENABLED(MIXING_EXTRUDER) && MIXING_VIRTUAL_TOOLS > 1)
  8375. tool_change(tmp_extruder);
  8376. #elif HOTENDS > 1
  8377. tool_change(
  8378. tmp_extruder,
  8379. parser.seen('F') ? MMM_TO_MMS(parser.value_linear_units()) : 0.0,
  8380. (tmp_extruder == active_extruder) || (parser.seen('S') && parser.value_bool())
  8381. );
  8382. #endif
  8383. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8384. if (DEBUGGING(LEVELING)) {
  8385. DEBUG_POS("AFTER", current_position);
  8386. SERIAL_ECHOLNPGM("<<< gcode_T");
  8387. }
  8388. #endif
  8389. }
  8390. /**
  8391. * Process a single command and dispatch it to its handler
  8392. * This is called from the main loop()
  8393. */
  8394. void process_next_command() {
  8395. char * const current_command = command_queue[cmd_queue_index_r];
  8396. if (DEBUGGING(ECHO)) {
  8397. SERIAL_ECHO_START;
  8398. SERIAL_ECHOLN(current_command);
  8399. #if ENABLED(M100_FREE_MEMORY_WATCHER)
  8400. SERIAL_ECHOPAIR("slot:", cmd_queue_index_r);
  8401. M100_dump_routine(" Command Queue:", (const char*)command_queue, (const char*)(command_queue + sizeof(command_queue)));
  8402. #endif
  8403. }
  8404. KEEPALIVE_STATE(IN_HANDLER);
  8405. // Parse the next command in the queue
  8406. parser.parse(current_command);
  8407. // Handle a known G, M, or T
  8408. switch (parser.command_letter) {
  8409. case 'G': switch (parser.codenum) {
  8410. // G0, G1
  8411. case 0:
  8412. case 1:
  8413. #if IS_SCARA
  8414. gcode_G0_G1(parser.codenum == 0);
  8415. #else
  8416. gcode_G0_G1();
  8417. #endif
  8418. break;
  8419. // G2, G3
  8420. #if ENABLED(ARC_SUPPORT) && DISABLED(SCARA)
  8421. case 2: // G2 - CW ARC
  8422. case 3: // G3 - CCW ARC
  8423. gcode_G2_G3(parser.codenum == 2);
  8424. break;
  8425. #endif
  8426. // G4 Dwell
  8427. case 4:
  8428. gcode_G4();
  8429. break;
  8430. #if ENABLED(BEZIER_CURVE_SUPPORT)
  8431. // G5
  8432. case 5: // G5 - Cubic B_spline
  8433. gcode_G5();
  8434. break;
  8435. #endif // BEZIER_CURVE_SUPPORT
  8436. #if ENABLED(FWRETRACT)
  8437. case 10: // G10: retract
  8438. case 11: // G11: retract_recover
  8439. gcode_G10_G11(parser.codenum == 10);
  8440. break;
  8441. #endif // FWRETRACT
  8442. #if ENABLED(NOZZLE_CLEAN_FEATURE)
  8443. case 12:
  8444. gcode_G12(); // G12: Nozzle Clean
  8445. break;
  8446. #endif // NOZZLE_CLEAN_FEATURE
  8447. #if ENABLED(INCH_MODE_SUPPORT)
  8448. case 20: //G20: Inch Mode
  8449. gcode_G20();
  8450. break;
  8451. case 21: //G21: MM Mode
  8452. gcode_G21();
  8453. break;
  8454. #endif // INCH_MODE_SUPPORT
  8455. #if ENABLED(AUTO_BED_LEVELING_UBL) && ENABLED(UBL_G26_MESH_VALIDATION)
  8456. case 26: // G26: Mesh Validation Pattern generation
  8457. gcode_G26();
  8458. break;
  8459. #endif // AUTO_BED_LEVELING_UBL
  8460. #if ENABLED(NOZZLE_PARK_FEATURE)
  8461. case 27: // G27: Nozzle Park
  8462. gcode_G27();
  8463. break;
  8464. #endif // NOZZLE_PARK_FEATURE
  8465. case 28: // G28: Home all axes, one at a time
  8466. gcode_G28(false);
  8467. break;
  8468. #if HAS_LEVELING
  8469. case 29: // G29 Detailed Z probe, probes the bed at 3 or more points,
  8470. // or provides access to the UBL System if enabled.
  8471. gcode_G29();
  8472. break;
  8473. #endif // HAS_LEVELING
  8474. #if HAS_BED_PROBE
  8475. case 30: // G30 Single Z probe
  8476. gcode_G30();
  8477. break;
  8478. #if ENABLED(Z_PROBE_SLED)
  8479. case 31: // G31: dock the sled
  8480. gcode_G31();
  8481. break;
  8482. case 32: // G32: undock the sled
  8483. gcode_G32();
  8484. break;
  8485. #endif // Z_PROBE_SLED
  8486. #if ENABLED(DELTA_AUTO_CALIBRATION)
  8487. case 33: // G33: Delta Auto-Calibration
  8488. gcode_G33();
  8489. break;
  8490. #endif // DELTA_AUTO_CALIBRATION
  8491. #endif // HAS_BED_PROBE
  8492. #if ENABLED(G38_PROBE_TARGET)
  8493. case 38: // G38.2 & G38.3
  8494. if (subcode == 2 || subcode == 3)
  8495. gcode_G38(subcode == 2);
  8496. break;
  8497. #endif
  8498. case 90: // G90
  8499. relative_mode = false;
  8500. break;
  8501. case 91: // G91
  8502. relative_mode = true;
  8503. break;
  8504. case 92: // G92
  8505. gcode_G92();
  8506. break;
  8507. #if ENABLED(AUTO_BED_LEVELING_BILINEAR) || ENABLED(AUTO_BED_LEVELING_UBL) || ENABLED(MESH_BED_LEVELING)
  8508. case 42:
  8509. gcode_G42();
  8510. break;
  8511. #endif
  8512. #if ENABLED(DEBUG_GCODE_PARSER)
  8513. case 800:
  8514. parser.debug(); // GCode Parser Test for G
  8515. break;
  8516. #endif
  8517. }
  8518. break;
  8519. case 'M': switch (parser.codenum) {
  8520. #if HAS_RESUME_CONTINUE
  8521. case 0: // M0: Unconditional stop - Wait for user button press on LCD
  8522. case 1: // M1: Conditional stop - Wait for user button press on LCD
  8523. gcode_M0_M1();
  8524. break;
  8525. #endif // ULTIPANEL
  8526. #if ENABLED(SPINDLE_LASER_ENABLE)
  8527. case 3:
  8528. gcode_M3_M4(true); // M3: turn spindle/laser on, set laser/spindle power/speed, set rotation direction CW
  8529. break; // synchronizes with movement commands
  8530. case 4:
  8531. gcode_M3_M4(false); // M4: turn spindle/laser on, set laser/spindle power/speed, set rotation direction CCW
  8532. break; // synchronizes with movement commands
  8533. case 5:
  8534. gcode_M5(); // M5 - turn spindle/laser off
  8535. break; // synchronizes with movement commands
  8536. #endif
  8537. case 17: // M17: Enable all stepper motors
  8538. gcode_M17();
  8539. break;
  8540. #if ENABLED(SDSUPPORT)
  8541. case 20: // M20: list SD card
  8542. gcode_M20(); break;
  8543. case 21: // M21: init SD card
  8544. gcode_M21(); break;
  8545. case 22: // M22: release SD card
  8546. gcode_M22(); break;
  8547. case 23: // M23: Select file
  8548. gcode_M23(); break;
  8549. case 24: // M24: Start SD print
  8550. gcode_M24(); break;
  8551. case 25: // M25: Pause SD print
  8552. gcode_M25(); break;
  8553. case 26: // M26: Set SD index
  8554. gcode_M26(); break;
  8555. case 27: // M27: Get SD status
  8556. gcode_M27(); break;
  8557. case 28: // M28: Start SD write
  8558. gcode_M28(); break;
  8559. case 29: // M29: Stop SD write
  8560. gcode_M29(); break;
  8561. case 30: // M30 <filename> Delete File
  8562. gcode_M30(); break;
  8563. case 32: // M32: Select file and start SD print
  8564. gcode_M32(); break;
  8565. #if ENABLED(LONG_FILENAME_HOST_SUPPORT)
  8566. case 33: // M33: Get the long full path to a file or folder
  8567. gcode_M33(); break;
  8568. #endif
  8569. #if ENABLED(SDCARD_SORT_ALPHA) && ENABLED(SDSORT_GCODE)
  8570. case 34: //M34 - Set SD card sorting options
  8571. gcode_M34(); break;
  8572. #endif // SDCARD_SORT_ALPHA && SDSORT_GCODE
  8573. case 928: // M928: Start SD write
  8574. gcode_M928(); break;
  8575. #endif // SDSUPPORT
  8576. case 31: // M31: Report time since the start of SD print or last M109
  8577. gcode_M31(); break;
  8578. case 42: // M42: Change pin state
  8579. gcode_M42(); break;
  8580. #if ENABLED(PINS_DEBUGGING)
  8581. case 43: // M43: Read pin state
  8582. gcode_M43(); break;
  8583. #endif
  8584. #if ENABLED(Z_MIN_PROBE_REPEATABILITY_TEST)
  8585. case 48: // M48: Z probe repeatability test
  8586. gcode_M48();
  8587. break;
  8588. #endif // Z_MIN_PROBE_REPEATABILITY_TEST
  8589. #if ENABLED(AUTO_BED_LEVELING_UBL) && ENABLED(UBL_G26_MESH_VALIDATION)
  8590. case 49: // M49: Turn on or off G26 debug flag for verbose output
  8591. gcode_M49();
  8592. break;
  8593. #endif // AUTO_BED_LEVELING_UBL && UBL_G26_MESH_VALIDATION
  8594. case 75: // M75: Start print timer
  8595. gcode_M75(); break;
  8596. case 76: // M76: Pause print timer
  8597. gcode_M76(); break;
  8598. case 77: // M77: Stop print timer
  8599. gcode_M77(); break;
  8600. #if ENABLED(PRINTCOUNTER)
  8601. case 78: // M78: Show print statistics
  8602. gcode_M78(); break;
  8603. #endif
  8604. #if ENABLED(M100_FREE_MEMORY_WATCHER)
  8605. case 100: // M100: Free Memory Report
  8606. gcode_M100();
  8607. break;
  8608. #endif
  8609. case 104: // M104: Set hot end temperature
  8610. gcode_M104();
  8611. break;
  8612. case 110: // M110: Set Current Line Number
  8613. gcode_M110();
  8614. break;
  8615. case 111: // M111: Set debug level
  8616. gcode_M111();
  8617. break;
  8618. #if DISABLED(EMERGENCY_PARSER)
  8619. case 108: // M108: Cancel Waiting
  8620. gcode_M108();
  8621. break;
  8622. case 112: // M112: Emergency Stop
  8623. gcode_M112();
  8624. break;
  8625. case 410: // M410 quickstop - Abort all the planned moves.
  8626. gcode_M410();
  8627. break;
  8628. #endif
  8629. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  8630. case 113: // M113: Set Host Keepalive interval
  8631. gcode_M113();
  8632. break;
  8633. #endif
  8634. case 140: // M140: Set bed temperature
  8635. gcode_M140();
  8636. break;
  8637. case 105: // M105: Report current temperature
  8638. gcode_M105();
  8639. KEEPALIVE_STATE(NOT_BUSY);
  8640. return; // "ok" already printed
  8641. #if ENABLED(AUTO_REPORT_TEMPERATURES) && (HAS_TEMP_HOTEND || HAS_TEMP_BED)
  8642. case 155: // M155: Set temperature auto-report interval
  8643. gcode_M155();
  8644. break;
  8645. #endif
  8646. case 109: // M109: Wait for hotend temperature to reach target
  8647. gcode_M109();
  8648. break;
  8649. #if HAS_TEMP_BED
  8650. case 190: // M190: Wait for bed temperature to reach target
  8651. gcode_M190();
  8652. break;
  8653. #endif // HAS_TEMP_BED
  8654. #if FAN_COUNT > 0
  8655. case 106: // M106: Fan On
  8656. gcode_M106();
  8657. break;
  8658. case 107: // M107: Fan Off
  8659. gcode_M107();
  8660. break;
  8661. #endif // FAN_COUNT > 0
  8662. #if ENABLED(PARK_HEAD_ON_PAUSE)
  8663. case 125: // M125: Store current position and move to filament change position
  8664. gcode_M125(); break;
  8665. #endif
  8666. #if ENABLED(BARICUDA)
  8667. // PWM for HEATER_1_PIN
  8668. #if HAS_HEATER_1
  8669. case 126: // M126: valve open
  8670. gcode_M126();
  8671. break;
  8672. case 127: // M127: valve closed
  8673. gcode_M127();
  8674. break;
  8675. #endif // HAS_HEATER_1
  8676. // PWM for HEATER_2_PIN
  8677. #if HAS_HEATER_2
  8678. case 128: // M128: valve open
  8679. gcode_M128();
  8680. break;
  8681. case 129: // M129: valve closed
  8682. gcode_M129();
  8683. break;
  8684. #endif // HAS_HEATER_2
  8685. #endif // BARICUDA
  8686. #if HAS_POWER_SWITCH
  8687. case 80: // M80: Turn on Power Supply
  8688. gcode_M80();
  8689. break;
  8690. #endif // HAS_POWER_SWITCH
  8691. case 81: // M81: Turn off Power, including Power Supply, if possible
  8692. gcode_M81();
  8693. break;
  8694. case 82: // M82: Set E axis normal mode (same as other axes)
  8695. gcode_M82();
  8696. break;
  8697. case 83: // M83: Set E axis relative mode
  8698. gcode_M83();
  8699. break;
  8700. case 18: // M18 => M84
  8701. case 84: // M84: Disable all steppers or set timeout
  8702. gcode_M18_M84();
  8703. break;
  8704. case 85: // M85: Set inactivity stepper shutdown timeout
  8705. gcode_M85();
  8706. break;
  8707. case 92: // M92: Set the steps-per-unit for one or more axes
  8708. gcode_M92();
  8709. break;
  8710. case 114: // M114: Report current position
  8711. gcode_M114();
  8712. break;
  8713. case 115: // M115: Report capabilities
  8714. gcode_M115();
  8715. break;
  8716. case 117: // M117: Set LCD message text, if possible
  8717. gcode_M117();
  8718. break;
  8719. case 119: // M119: Report endstop states
  8720. gcode_M119();
  8721. break;
  8722. case 120: // M120: Enable endstops
  8723. gcode_M120();
  8724. break;
  8725. case 121: // M121: Disable endstops
  8726. gcode_M121();
  8727. break;
  8728. #if ENABLED(ULTIPANEL)
  8729. case 145: // M145: Set material heatup parameters
  8730. gcode_M145();
  8731. break;
  8732. #endif
  8733. #if ENABLED(TEMPERATURE_UNITS_SUPPORT)
  8734. case 149: // M149: Set temperature units
  8735. gcode_M149();
  8736. break;
  8737. #endif
  8738. #if HAS_COLOR_LEDS
  8739. case 150: // M150: Set Status LED Color
  8740. gcode_M150();
  8741. break;
  8742. #endif // BLINKM
  8743. #if ENABLED(MIXING_EXTRUDER)
  8744. case 163: // M163: Set a component weight for mixing extruder
  8745. gcode_M163();
  8746. break;
  8747. #if MIXING_VIRTUAL_TOOLS > 1
  8748. case 164: // M164: Save current mix as a virtual extruder
  8749. gcode_M164();
  8750. break;
  8751. #endif
  8752. #if ENABLED(DIRECT_MIXING_IN_G1)
  8753. case 165: // M165: Set multiple mix weights
  8754. gcode_M165();
  8755. break;
  8756. #endif
  8757. #endif
  8758. case 200: // M200: Set filament diameter, E to cubic units
  8759. gcode_M200();
  8760. break;
  8761. case 201: // M201: Set max acceleration for print moves (units/s^2)
  8762. gcode_M201();
  8763. break;
  8764. #if 0 // Not used for Sprinter/grbl gen6
  8765. case 202: // M202
  8766. gcode_M202();
  8767. break;
  8768. #endif
  8769. case 203: // M203: Set max feedrate (units/sec)
  8770. gcode_M203();
  8771. break;
  8772. case 204: // M204: Set acceleration
  8773. gcode_M204();
  8774. break;
  8775. case 205: //M205: Set advanced settings
  8776. gcode_M205();
  8777. break;
  8778. #if HAS_M206_COMMAND
  8779. case 206: // M206: Set home offsets
  8780. gcode_M206();
  8781. break;
  8782. #endif
  8783. #if ENABLED(DELTA)
  8784. case 665: // M665: Set delta configurations
  8785. gcode_M665();
  8786. break;
  8787. #endif
  8788. #if ENABLED(DELTA) || ENABLED(Z_DUAL_ENDSTOPS)
  8789. case 666: // M666: Set delta or dual endstop adjustment
  8790. gcode_M666();
  8791. break;
  8792. #endif
  8793. #if ENABLED(FWRETRACT)
  8794. case 207: // M207: Set Retract Length, Feedrate, and Z lift
  8795. gcode_M207();
  8796. break;
  8797. case 208: // M208: Set Recover (unretract) Additional Length and Feedrate
  8798. gcode_M208();
  8799. break;
  8800. case 209: // M209: Turn Automatic Retract Detection on/off
  8801. gcode_M209();
  8802. break;
  8803. #endif // FWRETRACT
  8804. case 211: // M211: Enable, Disable, and/or Report software endstops
  8805. gcode_M211();
  8806. break;
  8807. #if HOTENDS > 1
  8808. case 218: // M218: Set a tool offset
  8809. gcode_M218();
  8810. break;
  8811. #endif
  8812. case 220: // M220: Set Feedrate Percentage: S<percent> ("FR" on your LCD)
  8813. gcode_M220();
  8814. break;
  8815. case 221: // M221: Set Flow Percentage
  8816. gcode_M221();
  8817. break;
  8818. case 226: // M226: Wait until a pin reaches a state
  8819. gcode_M226();
  8820. break;
  8821. #if HAS_SERVOS
  8822. case 280: // M280: Set servo position absolute
  8823. gcode_M280();
  8824. break;
  8825. #endif // HAS_SERVOS
  8826. #if HAS_BUZZER
  8827. case 300: // M300: Play beep tone
  8828. gcode_M300();
  8829. break;
  8830. #endif // HAS_BUZZER
  8831. #if ENABLED(PIDTEMP)
  8832. case 301: // M301: Set hotend PID parameters
  8833. gcode_M301();
  8834. break;
  8835. #endif // PIDTEMP
  8836. #if ENABLED(PIDTEMPBED)
  8837. case 304: // M304: Set bed PID parameters
  8838. gcode_M304();
  8839. break;
  8840. #endif // PIDTEMPBED
  8841. #if defined(CHDK) || HAS_PHOTOGRAPH
  8842. case 240: // M240: Trigger a camera by emulating a Canon RC-1 : http://www.doc-diy.net/photo/rc-1_hacked/
  8843. gcode_M240();
  8844. break;
  8845. #endif // CHDK || PHOTOGRAPH_PIN
  8846. #if HAS_LCD_CONTRAST
  8847. case 250: // M250: Set LCD contrast
  8848. gcode_M250();
  8849. break;
  8850. #endif // HAS_LCD_CONTRAST
  8851. #if ENABLED(EXPERIMENTAL_I2CBUS)
  8852. case 260: // M260: Send data to an i2c slave
  8853. gcode_M260();
  8854. break;
  8855. case 261: // M261: Request data from an i2c slave
  8856. gcode_M261();
  8857. break;
  8858. #endif // EXPERIMENTAL_I2CBUS
  8859. #if ENABLED(PREVENT_COLD_EXTRUSION)
  8860. case 302: // M302: Allow cold extrudes (set the minimum extrude temperature)
  8861. gcode_M302();
  8862. break;
  8863. #endif // PREVENT_COLD_EXTRUSION
  8864. case 303: // M303: PID autotune
  8865. gcode_M303();
  8866. break;
  8867. #if ENABLED(MORGAN_SCARA)
  8868. case 360: // M360: SCARA Theta pos1
  8869. if (gcode_M360()) return;
  8870. break;
  8871. case 361: // M361: SCARA Theta pos2
  8872. if (gcode_M361()) return;
  8873. break;
  8874. case 362: // M362: SCARA Psi pos1
  8875. if (gcode_M362()) return;
  8876. break;
  8877. case 363: // M363: SCARA Psi pos2
  8878. if (gcode_M363()) return;
  8879. break;
  8880. case 364: // M364: SCARA Psi pos3 (90 deg to Theta)
  8881. if (gcode_M364()) return;
  8882. break;
  8883. #endif // SCARA
  8884. case 400: // M400: Finish all moves
  8885. gcode_M400();
  8886. break;
  8887. #if HAS_BED_PROBE
  8888. case 401: // M401: Deploy probe
  8889. gcode_M401();
  8890. break;
  8891. case 402: // M402: Stow probe
  8892. gcode_M402();
  8893. break;
  8894. #endif // HAS_BED_PROBE
  8895. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  8896. case 404: // M404: Enter the nominal filament width (3mm, 1.75mm ) N<3.0> or display nominal filament width
  8897. gcode_M404();
  8898. break;
  8899. case 405: // M405: Turn on filament sensor for control
  8900. gcode_M405();
  8901. break;
  8902. case 406: // M406: Turn off filament sensor for control
  8903. gcode_M406();
  8904. break;
  8905. case 407: // M407: Display measured filament diameter
  8906. gcode_M407();
  8907. break;
  8908. #endif // FILAMENT_WIDTH_SENSOR
  8909. #if HAS_LEVELING
  8910. case 420: // M420: Enable/Disable Bed Leveling
  8911. gcode_M420();
  8912. break;
  8913. #endif
  8914. #if ENABLED(MESH_BED_LEVELING) || ENABLED(AUTO_BED_LEVELING_UBL) || ENABLED(AUTO_BED_LEVELING_BILINEAR)
  8915. case 421: // M421: Set a Mesh Bed Leveling Z coordinate
  8916. gcode_M421();
  8917. break;
  8918. #endif
  8919. #if HAS_M206_COMMAND
  8920. case 428: // M428: Apply current_position to home_offset
  8921. gcode_M428();
  8922. break;
  8923. #endif
  8924. case 500: // M500: Store settings in EEPROM
  8925. gcode_M500();
  8926. break;
  8927. case 501: // M501: Read settings from EEPROM
  8928. gcode_M501();
  8929. break;
  8930. case 502: // M502: Revert to default settings
  8931. gcode_M502();
  8932. break;
  8933. case 503: // M503: print settings currently in memory
  8934. gcode_M503();
  8935. break;
  8936. #if ENABLED(ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  8937. case 540: // M540: Set abort on endstop hit for SD printing
  8938. gcode_M540();
  8939. break;
  8940. #endif
  8941. #if HAS_BED_PROBE
  8942. case 851: // M851: Set Z Probe Z Offset
  8943. gcode_M851();
  8944. break;
  8945. #endif // HAS_BED_PROBE
  8946. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  8947. case 600: // M600: Pause for filament change
  8948. gcode_M600();
  8949. break;
  8950. #endif // ADVANCED_PAUSE_FEATURE
  8951. #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(DUAL_NOZZLE_DUPLICATION_MODE)
  8952. case 605: // M605: Set Dual X Carriage movement mode
  8953. gcode_M605();
  8954. break;
  8955. #endif // DUAL_X_CARRIAGE
  8956. #if ENABLED(LIN_ADVANCE)
  8957. case 900: // M900: Set advance K factor.
  8958. gcode_M900();
  8959. break;
  8960. #endif
  8961. #if ENABLED(HAVE_TMC2130)
  8962. case 906: // M906: Set motor current in milliamps using axis codes X, Y, Z, E
  8963. gcode_M906();
  8964. break;
  8965. #endif
  8966. case 907: // M907: Set digital trimpot motor current using axis codes.
  8967. gcode_M907();
  8968. break;
  8969. #if HAS_DIGIPOTSS || ENABLED(DAC_STEPPER_CURRENT)
  8970. case 908: // M908: Control digital trimpot directly.
  8971. gcode_M908();
  8972. break;
  8973. #if ENABLED(DAC_STEPPER_CURRENT) // As with Printrbot RevF
  8974. case 909: // M909: Print digipot/DAC current value
  8975. gcode_M909();
  8976. break;
  8977. case 910: // M910: Commit digipot/DAC value to external EEPROM
  8978. gcode_M910();
  8979. break;
  8980. #endif
  8981. #endif // HAS_DIGIPOTSS || DAC_STEPPER_CURRENT
  8982. #if ENABLED(HAVE_TMC2130)
  8983. case 911: // M911: Report TMC2130 prewarn triggered flags
  8984. gcode_M911();
  8985. break;
  8986. case 912: // M911: Clear TMC2130 prewarn triggered flags
  8987. gcode_M912();
  8988. break;
  8989. #if ENABLED(HYBRID_THRESHOLD)
  8990. case 913: // M913: Set HYBRID_THRESHOLD speed.
  8991. gcode_M913();
  8992. break;
  8993. #endif
  8994. #if ENABLED(SENSORLESS_HOMING)
  8995. case 914: // M914: Set SENSORLESS_HOMING sensitivity.
  8996. gcode_M914();
  8997. break;
  8998. #endif
  8999. #endif
  9000. #if HAS_MICROSTEPS
  9001. case 350: // M350: Set microstepping mode. Warning: Steps per unit remains unchanged. S code sets stepping mode for all drivers.
  9002. gcode_M350();
  9003. break;
  9004. case 351: // M351: Toggle MS1 MS2 pins directly, S# determines MS1 or MS2, X# sets the pin high/low.
  9005. gcode_M351();
  9006. break;
  9007. #endif // HAS_MICROSTEPS
  9008. case 355: // M355 Turn case lights on/off
  9009. gcode_M355();
  9010. break;
  9011. #if ENABLED(DEBUG_GCODE_PARSER)
  9012. case 800:
  9013. parser.debug(); // GCode Parser Test for M
  9014. break;
  9015. #endif
  9016. case 999: // M999: Restart after being Stopped
  9017. gcode_M999();
  9018. break;
  9019. }
  9020. break;
  9021. case 'T':
  9022. gcode_T(parser.codenum);
  9023. break;
  9024. default: parser.unknown_command_error();
  9025. }
  9026. KEEPALIVE_STATE(NOT_BUSY);
  9027. ok_to_send();
  9028. }
  9029. /**
  9030. * Send a "Resend: nnn" message to the host to
  9031. * indicate that a command needs to be re-sent.
  9032. */
  9033. void FlushSerialRequestResend() {
  9034. //char command_queue[cmd_queue_index_r][100]="Resend:";
  9035. MYSERIAL.flush();
  9036. SERIAL_PROTOCOLPGM(MSG_RESEND);
  9037. SERIAL_PROTOCOLLN(gcode_LastN + 1);
  9038. ok_to_send();
  9039. }
  9040. /**
  9041. * Send an "ok" message to the host, indicating
  9042. * that a command was successfully processed.
  9043. *
  9044. * If ADVANCED_OK is enabled also include:
  9045. * N<int> Line number of the command, if any
  9046. * P<int> Planner space remaining
  9047. * B<int> Block queue space remaining
  9048. */
  9049. void ok_to_send() {
  9050. refresh_cmd_timeout();
  9051. if (!send_ok[cmd_queue_index_r]) return;
  9052. SERIAL_PROTOCOLPGM(MSG_OK);
  9053. #if ENABLED(ADVANCED_OK)
  9054. char* p = command_queue[cmd_queue_index_r];
  9055. if (*p == 'N') {
  9056. SERIAL_PROTOCOL(' ');
  9057. SERIAL_ECHO(*p++);
  9058. while (NUMERIC_SIGNED(*p))
  9059. SERIAL_ECHO(*p++);
  9060. }
  9061. SERIAL_PROTOCOLPGM(" P"); SERIAL_PROTOCOL(int(BLOCK_BUFFER_SIZE - planner.movesplanned() - 1));
  9062. SERIAL_PROTOCOLPGM(" B"); SERIAL_PROTOCOL(BUFSIZE - commands_in_queue);
  9063. #endif
  9064. SERIAL_EOL;
  9065. }
  9066. #if HAS_SOFTWARE_ENDSTOPS
  9067. /**
  9068. * Constrain the given coordinates to the software endstops.
  9069. */
  9070. void clamp_to_software_endstops(float target[XYZ]) {
  9071. if (!soft_endstops_enabled) return;
  9072. #if ENABLED(MIN_SOFTWARE_ENDSTOPS)
  9073. NOLESS(target[X_AXIS], soft_endstop_min[X_AXIS]);
  9074. NOLESS(target[Y_AXIS], soft_endstop_min[Y_AXIS]);
  9075. NOLESS(target[Z_AXIS], soft_endstop_min[Z_AXIS]);
  9076. #endif
  9077. #if ENABLED(MAX_SOFTWARE_ENDSTOPS)
  9078. NOMORE(target[X_AXIS], soft_endstop_max[X_AXIS]);
  9079. NOMORE(target[Y_AXIS], soft_endstop_max[Y_AXIS]);
  9080. NOMORE(target[Z_AXIS], soft_endstop_max[Z_AXIS]);
  9081. #endif
  9082. }
  9083. #endif
  9084. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  9085. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  9086. #define ABL_BG_SPACING(A) bilinear_grid_spacing_virt[A]
  9087. #define ABL_BG_FACTOR(A) bilinear_grid_factor_virt[A]
  9088. #define ABL_BG_POINTS_X ABL_GRID_POINTS_VIRT_X
  9089. #define ABL_BG_POINTS_Y ABL_GRID_POINTS_VIRT_Y
  9090. #define ABL_BG_GRID(X,Y) z_values_virt[X][Y]
  9091. #else
  9092. #define ABL_BG_SPACING(A) bilinear_grid_spacing[A]
  9093. #define ABL_BG_FACTOR(A) bilinear_grid_factor[A]
  9094. #define ABL_BG_POINTS_X GRID_MAX_POINTS_X
  9095. #define ABL_BG_POINTS_Y GRID_MAX_POINTS_Y
  9096. #define ABL_BG_GRID(X,Y) z_values[X][Y]
  9097. #endif
  9098. // Get the Z adjustment for non-linear bed leveling
  9099. float bilinear_z_offset(const float logical[XYZ]) {
  9100. static float z1, d2, z3, d4, L, D, ratio_x, ratio_y,
  9101. last_x = -999.999, last_y = -999.999;
  9102. // Whole units for the grid line indices. Constrained within bounds.
  9103. static int8_t gridx, gridy, nextx, nexty,
  9104. last_gridx = -99, last_gridy = -99;
  9105. // XY relative to the probed area
  9106. const float x = RAW_X_POSITION(logical[X_AXIS]) - bilinear_start[X_AXIS],
  9107. y = RAW_Y_POSITION(logical[Y_AXIS]) - bilinear_start[Y_AXIS];
  9108. #if ENABLED(EXTRAPOLATE_BEYOND_GRID)
  9109. // Keep using the last grid box
  9110. #define FAR_EDGE_OR_BOX 2
  9111. #else
  9112. // Just use the grid far edge
  9113. #define FAR_EDGE_OR_BOX 1
  9114. #endif
  9115. if (last_x != x) {
  9116. last_x = x;
  9117. ratio_x = x * ABL_BG_FACTOR(X_AXIS);
  9118. const float gx = constrain(floor(ratio_x), 0, ABL_BG_POINTS_X - FAR_EDGE_OR_BOX);
  9119. ratio_x -= gx; // Subtract whole to get the ratio within the grid box
  9120. #if DISABLED(EXTRAPOLATE_BEYOND_GRID)
  9121. // Beyond the grid maintain height at grid edges
  9122. NOLESS(ratio_x, 0); // Never < 0.0. (> 1.0 is ok when nextx==gridx.)
  9123. #endif
  9124. gridx = gx;
  9125. nextx = min(gridx + 1, ABL_BG_POINTS_X - 1);
  9126. }
  9127. if (last_y != y || last_gridx != gridx) {
  9128. if (last_y != y) {
  9129. last_y = y;
  9130. ratio_y = y * ABL_BG_FACTOR(Y_AXIS);
  9131. const float gy = constrain(floor(ratio_y), 0, ABL_BG_POINTS_Y - FAR_EDGE_OR_BOX);
  9132. ratio_y -= gy;
  9133. #if DISABLED(EXTRAPOLATE_BEYOND_GRID)
  9134. // Beyond the grid maintain height at grid edges
  9135. NOLESS(ratio_y, 0); // Never < 0.0. (> 1.0 is ok when nexty==gridy.)
  9136. #endif
  9137. gridy = gy;
  9138. nexty = min(gridy + 1, ABL_BG_POINTS_Y - 1);
  9139. }
  9140. if (last_gridx != gridx || last_gridy != gridy) {
  9141. last_gridx = gridx;
  9142. last_gridy = gridy;
  9143. // Z at the box corners
  9144. z1 = ABL_BG_GRID(gridx, gridy); // left-front
  9145. d2 = ABL_BG_GRID(gridx, nexty) - z1; // left-back (delta)
  9146. z3 = ABL_BG_GRID(nextx, gridy); // right-front
  9147. d4 = ABL_BG_GRID(nextx, nexty) - z3; // right-back (delta)
  9148. }
  9149. // Bilinear interpolate. Needed since y or gridx has changed.
  9150. L = z1 + d2 * ratio_y; // Linear interp. LF -> LB
  9151. const float R = z3 + d4 * ratio_y; // Linear interp. RF -> RB
  9152. D = R - L;
  9153. }
  9154. const float offset = L + ratio_x * D; // the offset almost always changes
  9155. /*
  9156. static float last_offset = 0;
  9157. if (fabs(last_offset - offset) > 0.2) {
  9158. SERIAL_ECHOPGM("Sudden Shift at ");
  9159. SERIAL_ECHOPAIR("x=", x);
  9160. SERIAL_ECHOPAIR(" / ", bilinear_grid_spacing[X_AXIS]);
  9161. SERIAL_ECHOLNPAIR(" -> gridx=", gridx);
  9162. SERIAL_ECHOPAIR(" y=", y);
  9163. SERIAL_ECHOPAIR(" / ", bilinear_grid_spacing[Y_AXIS]);
  9164. SERIAL_ECHOLNPAIR(" -> gridy=", gridy);
  9165. SERIAL_ECHOPAIR(" ratio_x=", ratio_x);
  9166. SERIAL_ECHOLNPAIR(" ratio_y=", ratio_y);
  9167. SERIAL_ECHOPAIR(" z1=", z1);
  9168. SERIAL_ECHOPAIR(" z2=", z2);
  9169. SERIAL_ECHOPAIR(" z3=", z3);
  9170. SERIAL_ECHOLNPAIR(" z4=", z4);
  9171. SERIAL_ECHOPAIR(" L=", L);
  9172. SERIAL_ECHOPAIR(" R=", R);
  9173. SERIAL_ECHOLNPAIR(" offset=", offset);
  9174. }
  9175. last_offset = offset;
  9176. //*/
  9177. return offset;
  9178. }
  9179. #endif // AUTO_BED_LEVELING_BILINEAR
  9180. #if ENABLED(DELTA)
  9181. /**
  9182. * Recalculate factors used for delta kinematics whenever
  9183. * settings have been changed (e.g., by M665).
  9184. */
  9185. void recalc_delta_settings(float radius, float diagonal_rod) {
  9186. const float trt[ABC] = DELTA_RADIUS_TRIM_TOWER,
  9187. drt[ABC] = DELTA_DIAGONAL_ROD_TRIM_TOWER;
  9188. delta_tower[A_AXIS][X_AXIS] = cos(RADIANS(210 + delta_tower_angle_trim[A_AXIS])) * (radius + trt[A_AXIS]); // front left tower
  9189. delta_tower[A_AXIS][Y_AXIS] = sin(RADIANS(210 + delta_tower_angle_trim[A_AXIS])) * (radius + trt[A_AXIS]);
  9190. delta_tower[B_AXIS][X_AXIS] = cos(RADIANS(330 + delta_tower_angle_trim[B_AXIS])) * (radius + trt[B_AXIS]); // front right tower
  9191. delta_tower[B_AXIS][Y_AXIS] = sin(RADIANS(330 + delta_tower_angle_trim[B_AXIS])) * (radius + trt[B_AXIS]);
  9192. delta_tower[C_AXIS][X_AXIS] = 0.0; // back middle tower
  9193. delta_tower[C_AXIS][Y_AXIS] = (radius + trt[C_AXIS]);
  9194. delta_diagonal_rod_2_tower[A_AXIS] = sq(diagonal_rod + drt[A_AXIS]);
  9195. delta_diagonal_rod_2_tower[B_AXIS] = sq(diagonal_rod + drt[B_AXIS]);
  9196. delta_diagonal_rod_2_tower[C_AXIS] = sq(diagonal_rod + drt[C_AXIS]);
  9197. }
  9198. #if ENABLED(DELTA_FAST_SQRT)
  9199. /**
  9200. * Fast inverse sqrt from Quake III Arena
  9201. * See: https://en.wikipedia.org/wiki/Fast_inverse_square_root
  9202. */
  9203. float Q_rsqrt(float number) {
  9204. long i;
  9205. float x2, y;
  9206. const float threehalfs = 1.5f;
  9207. x2 = number * 0.5f;
  9208. y = number;
  9209. i = * ( long * ) &y; // evil floating point bit level hacking
  9210. i = 0x5F3759DF - ( i >> 1 ); // what the f***?
  9211. y = * ( float * ) &i;
  9212. y = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration
  9213. // y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed
  9214. return y;
  9215. }
  9216. #define _SQRT(n) (1.0f / Q_rsqrt(n))
  9217. #else
  9218. #define _SQRT(n) sqrt(n)
  9219. #endif
  9220. /**
  9221. * Delta Inverse Kinematics
  9222. *
  9223. * Calculate the tower positions for a given logical
  9224. * position, storing the result in the delta[] array.
  9225. *
  9226. * This is an expensive calculation, requiring 3 square
  9227. * roots per segmented linear move, and strains the limits
  9228. * of a Mega2560 with a Graphical Display.
  9229. *
  9230. * Suggested optimizations include:
  9231. *
  9232. * - Disable the home_offset (M206) and/or position_shift (G92)
  9233. * features to remove up to 12 float additions.
  9234. *
  9235. * - Use a fast-inverse-sqrt function and add the reciprocal.
  9236. * (see above)
  9237. */
  9238. // Macro to obtain the Z position of an individual tower
  9239. #define DELTA_Z(T) raw[Z_AXIS] + _SQRT( \
  9240. delta_diagonal_rod_2_tower[T] - HYPOT2( \
  9241. delta_tower[T][X_AXIS] - raw[X_AXIS], \
  9242. delta_tower[T][Y_AXIS] - raw[Y_AXIS] \
  9243. ) \
  9244. )
  9245. #define DELTA_RAW_IK() do { \
  9246. delta[A_AXIS] = DELTA_Z(A_AXIS); \
  9247. delta[B_AXIS] = DELTA_Z(B_AXIS); \
  9248. delta[C_AXIS] = DELTA_Z(C_AXIS); \
  9249. } while(0)
  9250. #define DELTA_LOGICAL_IK() do { \
  9251. const float raw[XYZ] = { \
  9252. RAW_X_POSITION(logical[X_AXIS]), \
  9253. RAW_Y_POSITION(logical[Y_AXIS]), \
  9254. RAW_Z_POSITION(logical[Z_AXIS]) \
  9255. }; \
  9256. DELTA_RAW_IK(); \
  9257. } while(0)
  9258. #define DELTA_DEBUG() do { \
  9259. SERIAL_ECHOPAIR("cartesian X:", raw[X_AXIS]); \
  9260. SERIAL_ECHOPAIR(" Y:", raw[Y_AXIS]); \
  9261. SERIAL_ECHOLNPAIR(" Z:", raw[Z_AXIS]); \
  9262. SERIAL_ECHOPAIR("delta A:", delta[A_AXIS]); \
  9263. SERIAL_ECHOPAIR(" B:", delta[B_AXIS]); \
  9264. SERIAL_ECHOLNPAIR(" C:", delta[C_AXIS]); \
  9265. } while(0)
  9266. void inverse_kinematics(const float logical[XYZ]) {
  9267. DELTA_LOGICAL_IK();
  9268. // DELTA_DEBUG();
  9269. }
  9270. /**
  9271. * Calculate the highest Z position where the
  9272. * effector has the full range of XY motion.
  9273. */
  9274. float delta_safe_distance_from_top() {
  9275. float cartesian[XYZ] = {
  9276. LOGICAL_X_POSITION(0),
  9277. LOGICAL_Y_POSITION(0),
  9278. LOGICAL_Z_POSITION(0)
  9279. };
  9280. inverse_kinematics(cartesian);
  9281. float distance = delta[A_AXIS];
  9282. cartesian[Y_AXIS] = LOGICAL_Y_POSITION(DELTA_PRINTABLE_RADIUS);
  9283. inverse_kinematics(cartesian);
  9284. return abs(distance - delta[A_AXIS]);
  9285. }
  9286. /**
  9287. * Delta Forward Kinematics
  9288. *
  9289. * See the Wikipedia article "Trilateration"
  9290. * https://en.wikipedia.org/wiki/Trilateration
  9291. *
  9292. * Establish a new coordinate system in the plane of the
  9293. * three carriage points. This system has its origin at
  9294. * tower1, with tower2 on the X axis. Tower3 is in the X-Y
  9295. * plane with a Z component of zero.
  9296. * We will define unit vectors in this coordinate system
  9297. * in our original coordinate system. Then when we calculate
  9298. * the Xnew, Ynew and Znew values, we can translate back into
  9299. * the original system by moving along those unit vectors
  9300. * by the corresponding values.
  9301. *
  9302. * Variable names matched to Marlin, c-version, and avoid the
  9303. * use of any vector library.
  9304. *
  9305. * by Andreas Hardtung 2016-06-07
  9306. * based on a Java function from "Delta Robot Kinematics V3"
  9307. * by Steve Graves
  9308. *
  9309. * The result is stored in the cartes[] array.
  9310. */
  9311. void forward_kinematics_DELTA(float z1, float z2, float z3) {
  9312. // Create a vector in old coordinates along x axis of new coordinate
  9313. 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 };
  9314. // Get the Magnitude of vector.
  9315. float d = sqrt( sq(p12[0]) + sq(p12[1]) + sq(p12[2]) );
  9316. // Create unit vector by dividing by magnitude.
  9317. float ex[3] = { p12[0] / d, p12[1] / d, p12[2] / d };
  9318. // Get the vector from the origin of the new system to the third point.
  9319. 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 };
  9320. // Use the dot product to find the component of this vector on the X axis.
  9321. float i = ex[0] * p13[0] + ex[1] * p13[1] + ex[2] * p13[2];
  9322. // Create a vector along the x axis that represents the x component of p13.
  9323. float iex[3] = { ex[0] * i, ex[1] * i, ex[2] * i };
  9324. // Subtract the X component from the original vector leaving only Y. We use the
  9325. // variable that will be the unit vector after we scale it.
  9326. float ey[3] = { p13[0] - iex[0], p13[1] - iex[1], p13[2] - iex[2] };
  9327. // The magnitude of Y component
  9328. float j = sqrt( sq(ey[0]) + sq(ey[1]) + sq(ey[2]) );
  9329. // Convert to a unit vector
  9330. ey[0] /= j; ey[1] /= j; ey[2] /= j;
  9331. // The cross product of the unit x and y is the unit z
  9332. // float[] ez = vectorCrossProd(ex, ey);
  9333. float ez[3] = {
  9334. ex[1] * ey[2] - ex[2] * ey[1],
  9335. ex[2] * ey[0] - ex[0] * ey[2],
  9336. ex[0] * ey[1] - ex[1] * ey[0]
  9337. };
  9338. // We now have the d, i and j values defined in Wikipedia.
  9339. // Plug them into the equations defined in Wikipedia for Xnew, Ynew and Znew
  9340. float Xnew = (delta_diagonal_rod_2_tower[A_AXIS] - delta_diagonal_rod_2_tower[B_AXIS] + sq(d)) / (d * 2),
  9341. Ynew = ((delta_diagonal_rod_2_tower[A_AXIS] - delta_diagonal_rod_2_tower[C_AXIS] + HYPOT2(i, j)) / 2 - i * Xnew) / j,
  9342. Znew = sqrt(delta_diagonal_rod_2_tower[A_AXIS] - HYPOT2(Xnew, Ynew));
  9343. // Start from the origin of the old coordinates and add vectors in the
  9344. // old coords that represent the Xnew, Ynew and Znew to find the point
  9345. // in the old system.
  9346. cartes[X_AXIS] = delta_tower[A_AXIS][X_AXIS] + ex[0] * Xnew + ey[0] * Ynew - ez[0] * Znew;
  9347. cartes[Y_AXIS] = delta_tower[A_AXIS][Y_AXIS] + ex[1] * Xnew + ey[1] * Ynew - ez[1] * Znew;
  9348. cartes[Z_AXIS] = z1 + ex[2] * Xnew + ey[2] * Ynew - ez[2] * Znew;
  9349. }
  9350. void forward_kinematics_DELTA(float point[ABC]) {
  9351. forward_kinematics_DELTA(point[A_AXIS], point[B_AXIS], point[C_AXIS]);
  9352. }
  9353. #endif // DELTA
  9354. /**
  9355. * Get the stepper positions in the cartes[] array.
  9356. * Forward kinematics are applied for DELTA and SCARA.
  9357. *
  9358. * The result is in the current coordinate space with
  9359. * leveling applied. The coordinates need to be run through
  9360. * unapply_leveling to obtain the "ideal" coordinates
  9361. * suitable for current_position, etc.
  9362. */
  9363. void get_cartesian_from_steppers() {
  9364. #if ENABLED(DELTA)
  9365. forward_kinematics_DELTA(
  9366. stepper.get_axis_position_mm(A_AXIS),
  9367. stepper.get_axis_position_mm(B_AXIS),
  9368. stepper.get_axis_position_mm(C_AXIS)
  9369. );
  9370. cartes[X_AXIS] += LOGICAL_X_POSITION(0);
  9371. cartes[Y_AXIS] += LOGICAL_Y_POSITION(0);
  9372. cartes[Z_AXIS] += LOGICAL_Z_POSITION(0);
  9373. #elif IS_SCARA
  9374. forward_kinematics_SCARA(
  9375. stepper.get_axis_position_degrees(A_AXIS),
  9376. stepper.get_axis_position_degrees(B_AXIS)
  9377. );
  9378. cartes[X_AXIS] += LOGICAL_X_POSITION(0);
  9379. cartes[Y_AXIS] += LOGICAL_Y_POSITION(0);
  9380. cartes[Z_AXIS] = stepper.get_axis_position_mm(Z_AXIS);
  9381. #else
  9382. cartes[X_AXIS] = stepper.get_axis_position_mm(X_AXIS);
  9383. cartes[Y_AXIS] = stepper.get_axis_position_mm(Y_AXIS);
  9384. cartes[Z_AXIS] = stepper.get_axis_position_mm(Z_AXIS);
  9385. #endif
  9386. }
  9387. /**
  9388. * Set the current_position for an axis based on
  9389. * the stepper positions, removing any leveling that
  9390. * may have been applied.
  9391. */
  9392. void set_current_from_steppers_for_axis(const AxisEnum axis) {
  9393. get_cartesian_from_steppers();
  9394. #if PLANNER_LEVELING
  9395. planner.unapply_leveling(cartes);
  9396. #endif
  9397. if (axis == ALL_AXES)
  9398. COPY(current_position, cartes);
  9399. else
  9400. current_position[axis] = cartes[axis];
  9401. }
  9402. #if ENABLED(MESH_BED_LEVELING)
  9403. /**
  9404. * Prepare a mesh-leveled linear move in a Cartesian setup,
  9405. * splitting the move where it crosses mesh borders.
  9406. */
  9407. void mesh_line_to_destination(float fr_mm_s, uint8_t x_splits = 0xFF, uint8_t y_splits = 0xFF) {
  9408. int cx1 = mbl.cell_index_x(RAW_CURRENT_POSITION(X)),
  9409. cy1 = mbl.cell_index_y(RAW_CURRENT_POSITION(Y)),
  9410. cx2 = mbl.cell_index_x(RAW_X_POSITION(destination[X_AXIS])),
  9411. cy2 = mbl.cell_index_y(RAW_Y_POSITION(destination[Y_AXIS]));
  9412. NOMORE(cx1, GRID_MAX_POINTS_X - 2);
  9413. NOMORE(cy1, GRID_MAX_POINTS_Y - 2);
  9414. NOMORE(cx2, GRID_MAX_POINTS_X - 2);
  9415. NOMORE(cy2, GRID_MAX_POINTS_Y - 2);
  9416. if (cx1 == cx2 && cy1 == cy2) {
  9417. // Start and end on same mesh square
  9418. line_to_destination(fr_mm_s);
  9419. set_current_to_destination();
  9420. return;
  9421. }
  9422. #define MBL_SEGMENT_END(A) (current_position[A ##_AXIS] + (destination[A ##_AXIS] - current_position[A ##_AXIS]) * normalized_dist)
  9423. float normalized_dist, end[XYZE];
  9424. // Split at the left/front border of the right/top square
  9425. const int8_t gcx = max(cx1, cx2), gcy = max(cy1, cy2);
  9426. if (cx2 != cx1 && TEST(x_splits, gcx)) {
  9427. COPY(end, destination);
  9428. destination[X_AXIS] = LOGICAL_X_POSITION(mbl.index_to_xpos[gcx]);
  9429. normalized_dist = (destination[X_AXIS] - current_position[X_AXIS]) / (end[X_AXIS] - current_position[X_AXIS]);
  9430. destination[Y_AXIS] = MBL_SEGMENT_END(Y);
  9431. CBI(x_splits, gcx);
  9432. }
  9433. else if (cy2 != cy1 && TEST(y_splits, gcy)) {
  9434. COPY(end, destination);
  9435. destination[Y_AXIS] = LOGICAL_Y_POSITION(mbl.index_to_ypos[gcy]);
  9436. normalized_dist = (destination[Y_AXIS] - current_position[Y_AXIS]) / (end[Y_AXIS] - current_position[Y_AXIS]);
  9437. destination[X_AXIS] = MBL_SEGMENT_END(X);
  9438. CBI(y_splits, gcy);
  9439. }
  9440. else {
  9441. // Already split on a border
  9442. line_to_destination(fr_mm_s);
  9443. set_current_to_destination();
  9444. return;
  9445. }
  9446. destination[Z_AXIS] = MBL_SEGMENT_END(Z);
  9447. destination[E_AXIS] = MBL_SEGMENT_END(E);
  9448. // Do the split and look for more borders
  9449. mesh_line_to_destination(fr_mm_s, x_splits, y_splits);
  9450. // Restore destination from stack
  9451. COPY(destination, end);
  9452. mesh_line_to_destination(fr_mm_s, x_splits, y_splits);
  9453. }
  9454. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR) && !IS_KINEMATIC
  9455. #define CELL_INDEX(A,V) ((RAW_##A##_POSITION(V) - bilinear_start[A##_AXIS]) * ABL_BG_FACTOR(A##_AXIS))
  9456. /**
  9457. * Prepare a bilinear-leveled linear move on Cartesian,
  9458. * splitting the move where it crosses grid borders.
  9459. */
  9460. void bilinear_line_to_destination(float fr_mm_s, uint16_t x_splits = 0xFFFF, uint16_t y_splits = 0xFFFF) {
  9461. int cx1 = CELL_INDEX(X, current_position[X_AXIS]),
  9462. cy1 = CELL_INDEX(Y, current_position[Y_AXIS]),
  9463. cx2 = CELL_INDEX(X, destination[X_AXIS]),
  9464. cy2 = CELL_INDEX(Y, destination[Y_AXIS]);
  9465. cx1 = constrain(cx1, 0, ABL_BG_POINTS_X - 2);
  9466. cy1 = constrain(cy1, 0, ABL_BG_POINTS_Y - 2);
  9467. cx2 = constrain(cx2, 0, ABL_BG_POINTS_X - 2);
  9468. cy2 = constrain(cy2, 0, ABL_BG_POINTS_Y - 2);
  9469. if (cx1 == cx2 && cy1 == cy2) {
  9470. // Start and end on same mesh square
  9471. line_to_destination(fr_mm_s);
  9472. set_current_to_destination();
  9473. return;
  9474. }
  9475. #define LINE_SEGMENT_END(A) (current_position[A ##_AXIS] + (destination[A ##_AXIS] - current_position[A ##_AXIS]) * normalized_dist)
  9476. float normalized_dist, end[XYZE];
  9477. // Split at the left/front border of the right/top square
  9478. const int8_t gcx = max(cx1, cx2), gcy = max(cy1, cy2);
  9479. if (cx2 != cx1 && TEST(x_splits, gcx)) {
  9480. COPY(end, destination);
  9481. destination[X_AXIS] = LOGICAL_X_POSITION(bilinear_start[X_AXIS] + ABL_BG_SPACING(X_AXIS) * gcx);
  9482. normalized_dist = (destination[X_AXIS] - current_position[X_AXIS]) / (end[X_AXIS] - current_position[X_AXIS]);
  9483. destination[Y_AXIS] = LINE_SEGMENT_END(Y);
  9484. CBI(x_splits, gcx);
  9485. }
  9486. else if (cy2 != cy1 && TEST(y_splits, gcy)) {
  9487. COPY(end, destination);
  9488. destination[Y_AXIS] = LOGICAL_Y_POSITION(bilinear_start[Y_AXIS] + ABL_BG_SPACING(Y_AXIS) * gcy);
  9489. normalized_dist = (destination[Y_AXIS] - current_position[Y_AXIS]) / (end[Y_AXIS] - current_position[Y_AXIS]);
  9490. destination[X_AXIS] = LINE_SEGMENT_END(X);
  9491. CBI(y_splits, gcy);
  9492. }
  9493. else {
  9494. // Already split on a border
  9495. line_to_destination(fr_mm_s);
  9496. set_current_to_destination();
  9497. return;
  9498. }
  9499. destination[Z_AXIS] = LINE_SEGMENT_END(Z);
  9500. destination[E_AXIS] = LINE_SEGMENT_END(E);
  9501. // Do the split and look for more borders
  9502. bilinear_line_to_destination(fr_mm_s, x_splits, y_splits);
  9503. // Restore destination from stack
  9504. COPY(destination, end);
  9505. bilinear_line_to_destination(fr_mm_s, x_splits, y_splits);
  9506. }
  9507. #endif // AUTO_BED_LEVELING_BILINEAR
  9508. #if IS_KINEMATIC && !UBL_DELTA
  9509. /**
  9510. * Prepare a linear move in a DELTA or SCARA setup.
  9511. *
  9512. * This calls planner.buffer_line several times, adding
  9513. * small incremental moves for DELTA or SCARA.
  9514. */
  9515. inline bool prepare_kinematic_move_to(float ltarget[XYZE]) {
  9516. // Get the top feedrate of the move in the XY plane
  9517. const float _feedrate_mm_s = MMS_SCALED(feedrate_mm_s);
  9518. // If the move is only in Z/E don't split up the move
  9519. if (ltarget[X_AXIS] == current_position[X_AXIS] && ltarget[Y_AXIS] == current_position[Y_AXIS]) {
  9520. planner.buffer_line_kinematic(ltarget, _feedrate_mm_s, active_extruder);
  9521. return false;
  9522. }
  9523. // Fail if attempting move outside printable radius
  9524. if (!position_is_reachable_xy(ltarget[X_AXIS], ltarget[Y_AXIS])) return true;
  9525. // Get the cartesian distances moved in XYZE
  9526. const float difference[XYZE] = {
  9527. ltarget[X_AXIS] - current_position[X_AXIS],
  9528. ltarget[Y_AXIS] - current_position[Y_AXIS],
  9529. ltarget[Z_AXIS] - current_position[Z_AXIS],
  9530. ltarget[E_AXIS] - current_position[E_AXIS]
  9531. };
  9532. // Get the linear distance in XYZ
  9533. float cartesian_mm = sqrt(sq(difference[X_AXIS]) + sq(difference[Y_AXIS]) + sq(difference[Z_AXIS]));
  9534. // If the move is very short, check the E move distance
  9535. if (UNEAR_ZERO(cartesian_mm)) cartesian_mm = abs(difference[E_AXIS]);
  9536. // No E move either? Game over.
  9537. if (UNEAR_ZERO(cartesian_mm)) return true;
  9538. // Minimum number of seconds to move the given distance
  9539. const float seconds = cartesian_mm / _feedrate_mm_s;
  9540. // The number of segments-per-second times the duration
  9541. // gives the number of segments
  9542. uint16_t segments = delta_segments_per_second * seconds;
  9543. // For SCARA minimum segment size is 0.25mm
  9544. #if IS_SCARA
  9545. NOMORE(segments, cartesian_mm * 4);
  9546. #endif
  9547. // At least one segment is required
  9548. NOLESS(segments, 1);
  9549. // The approximate length of each segment
  9550. const float inv_segments = 1.0 / float(segments),
  9551. segment_distance[XYZE] = {
  9552. difference[X_AXIS] * inv_segments,
  9553. difference[Y_AXIS] * inv_segments,
  9554. difference[Z_AXIS] * inv_segments,
  9555. difference[E_AXIS] * inv_segments
  9556. };
  9557. // SERIAL_ECHOPAIR("mm=", cartesian_mm);
  9558. // SERIAL_ECHOPAIR(" seconds=", seconds);
  9559. // SERIAL_ECHOLNPAIR(" segments=", segments);
  9560. #if IS_SCARA && ENABLED(SCARA_FEEDRATE_SCALING)
  9561. // SCARA needs to scale the feed rate from mm/s to degrees/s
  9562. const float inv_segment_length = min(10.0, float(segments) / cartesian_mm), // 1/mm/segs
  9563. feed_factor = inv_segment_length * _feedrate_mm_s;
  9564. float oldA = stepper.get_axis_position_degrees(A_AXIS),
  9565. oldB = stepper.get_axis_position_degrees(B_AXIS);
  9566. #endif
  9567. // Get the logical current position as starting point
  9568. float logical[XYZE];
  9569. COPY(logical, current_position);
  9570. // Drop one segment so the last move is to the exact target.
  9571. // If there's only 1 segment, loops will be skipped entirely.
  9572. --segments;
  9573. // Calculate and execute the segments
  9574. for (uint16_t s = segments + 1; --s;) {
  9575. LOOP_XYZE(i) logical[i] += segment_distance[i];
  9576. #if ENABLED(DELTA)
  9577. DELTA_LOGICAL_IK(); // Delta can inline its kinematics
  9578. #else
  9579. inverse_kinematics(logical);
  9580. #endif
  9581. ADJUST_DELTA(logical); // Adjust Z if bed leveling is enabled
  9582. #if IS_SCARA && ENABLED(SCARA_FEEDRATE_SCALING)
  9583. // For SCARA scale the feed rate from mm/s to degrees/s
  9584. // Use ratio between the length of the move and the larger angle change
  9585. const float adiff = abs(delta[A_AXIS] - oldA),
  9586. bdiff = abs(delta[B_AXIS] - oldB);
  9587. planner.buffer_line(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], logical[E_AXIS], max(adiff, bdiff) * feed_factor, active_extruder);
  9588. oldA = delta[A_AXIS];
  9589. oldB = delta[B_AXIS];
  9590. #else
  9591. planner.buffer_line(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], logical[E_AXIS], _feedrate_mm_s, active_extruder);
  9592. #endif
  9593. }
  9594. // Since segment_distance is only approximate,
  9595. // the final move must be to the exact destination.
  9596. #if IS_SCARA && ENABLED(SCARA_FEEDRATE_SCALING)
  9597. // For SCARA scale the feed rate from mm/s to degrees/s
  9598. // With segments > 1 length is 1 segment, otherwise total length
  9599. inverse_kinematics(ltarget);
  9600. ADJUST_DELTA(ltarget);
  9601. const float adiff = abs(delta[A_AXIS] - oldA),
  9602. bdiff = abs(delta[B_AXIS] - oldB);
  9603. planner.buffer_line(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], logical[E_AXIS], max(adiff, bdiff) * feed_factor, active_extruder);
  9604. #else
  9605. planner.buffer_line_kinematic(ltarget, _feedrate_mm_s, active_extruder);
  9606. #endif
  9607. return false;
  9608. }
  9609. #else // !IS_KINEMATIC || UBL_DELTA
  9610. /**
  9611. * Prepare a linear move in a Cartesian setup.
  9612. * If Mesh Bed Leveling is enabled, perform a mesh move.
  9613. *
  9614. * Returns true if the caller didn't update current_position.
  9615. */
  9616. inline bool prepare_move_to_destination_cartesian() {
  9617. #if ENABLED(AUTO_BED_LEVELING_UBL)
  9618. const float fr_scaled = MMS_SCALED(feedrate_mm_s);
  9619. if (ubl.state.active) { // direct use of ubl.state.active for speed
  9620. ubl.line_to_destination_cartesian(fr_scaled, active_extruder);
  9621. return true;
  9622. }
  9623. else
  9624. line_to_destination(fr_scaled);
  9625. #else
  9626. // Do not use feedrate_percentage for E or Z only moves
  9627. if (current_position[X_AXIS] == destination[X_AXIS] && current_position[Y_AXIS] == destination[Y_AXIS])
  9628. line_to_destination();
  9629. else {
  9630. const float fr_scaled = MMS_SCALED(feedrate_mm_s);
  9631. #if ENABLED(MESH_BED_LEVELING)
  9632. if (mbl.active()) { // direct used of mbl.active() for speed
  9633. mesh_line_to_destination(fr_scaled);
  9634. return true;
  9635. }
  9636. else
  9637. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  9638. if (planner.abl_enabled) { // direct use of abl_enabled for speed
  9639. bilinear_line_to_destination(fr_scaled);
  9640. return true;
  9641. }
  9642. else
  9643. #endif
  9644. line_to_destination(fr_scaled);
  9645. }
  9646. #endif
  9647. return false;
  9648. }
  9649. #endif // !IS_KINEMATIC || UBL_DELTA
  9650. #if ENABLED(DUAL_X_CARRIAGE)
  9651. /**
  9652. * Prepare a linear move in a dual X axis setup
  9653. */
  9654. inline bool prepare_move_to_destination_dualx() {
  9655. if (active_extruder_parked) {
  9656. switch (dual_x_carriage_mode) {
  9657. case DXC_FULL_CONTROL_MODE:
  9658. break;
  9659. case DXC_AUTO_PARK_MODE:
  9660. if (current_position[E_AXIS] == destination[E_AXIS]) {
  9661. // This is a travel move (with no extrusion)
  9662. // Skip it, but keep track of the current position
  9663. // (so it can be used as the start of the next non-travel move)
  9664. if (delayed_move_time != 0xFFFFFFFFUL) {
  9665. set_current_to_destination();
  9666. NOLESS(raised_parked_position[Z_AXIS], destination[Z_AXIS]);
  9667. delayed_move_time = millis();
  9668. return true;
  9669. }
  9670. }
  9671. // unpark extruder: 1) raise, 2) move into starting XY position, 3) lower
  9672. for (uint8_t i = 0; i < 3; i++)
  9673. planner.buffer_line(
  9674. i == 0 ? raised_parked_position[X_AXIS] : current_position[X_AXIS],
  9675. i == 0 ? raised_parked_position[Y_AXIS] : current_position[Y_AXIS],
  9676. i == 2 ? current_position[Z_AXIS] : raised_parked_position[Z_AXIS],
  9677. current_position[E_AXIS],
  9678. i == 1 ? PLANNER_XY_FEEDRATE() : planner.max_feedrate_mm_s[Z_AXIS],
  9679. active_extruder
  9680. );
  9681. delayed_move_time = 0;
  9682. active_extruder_parked = false;
  9683. #if ENABLED(DEBUG_LEVELING_FEATURE)
  9684. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Clear active_extruder_parked");
  9685. #endif
  9686. break;
  9687. case DXC_DUPLICATION_MODE:
  9688. if (active_extruder == 0) {
  9689. #if ENABLED(DEBUG_LEVELING_FEATURE)
  9690. if (DEBUGGING(LEVELING)) {
  9691. SERIAL_ECHOPAIR("Set planner X", LOGICAL_X_POSITION(inactive_extruder_x_pos));
  9692. SERIAL_ECHOLNPAIR(" ... Line to X", current_position[X_AXIS] + duplicate_extruder_x_offset);
  9693. }
  9694. #endif
  9695. // move duplicate extruder into correct duplication position.
  9696. planner.set_position_mm(
  9697. LOGICAL_X_POSITION(inactive_extruder_x_pos),
  9698. current_position[Y_AXIS],
  9699. current_position[Z_AXIS],
  9700. current_position[E_AXIS]
  9701. );
  9702. planner.buffer_line(
  9703. current_position[X_AXIS] + duplicate_extruder_x_offset,
  9704. current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS],
  9705. planner.max_feedrate_mm_s[X_AXIS], 1
  9706. );
  9707. SYNC_PLAN_POSITION_KINEMATIC();
  9708. stepper.synchronize();
  9709. extruder_duplication_enabled = true;
  9710. active_extruder_parked = false;
  9711. #if ENABLED(DEBUG_LEVELING_FEATURE)
  9712. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Set extruder_duplication_enabled\nClear active_extruder_parked");
  9713. #endif
  9714. }
  9715. else {
  9716. #if ENABLED(DEBUG_LEVELING_FEATURE)
  9717. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Active extruder not 0");
  9718. #endif
  9719. }
  9720. break;
  9721. }
  9722. }
  9723. return false;
  9724. }
  9725. #endif // DUAL_X_CARRIAGE
  9726. /**
  9727. * Prepare a single move and get ready for the next one
  9728. *
  9729. * This may result in several calls to planner.buffer_line to
  9730. * do smaller moves for DELTA, SCARA, mesh moves, etc.
  9731. */
  9732. void prepare_move_to_destination() {
  9733. clamp_to_software_endstops(destination);
  9734. refresh_cmd_timeout();
  9735. #if ENABLED(PREVENT_COLD_EXTRUSION)
  9736. if (!DEBUGGING(DRYRUN)) {
  9737. if (destination[E_AXIS] != current_position[E_AXIS]) {
  9738. if (thermalManager.tooColdToExtrude(active_extruder)) {
  9739. current_position[E_AXIS] = destination[E_AXIS]; // Behave as if the move really took place, but ignore E part
  9740. SERIAL_ECHO_START;
  9741. SERIAL_ECHOLNPGM(MSG_ERR_COLD_EXTRUDE_STOP);
  9742. }
  9743. #if ENABLED(PREVENT_LENGTHY_EXTRUDE)
  9744. if (labs(destination[E_AXIS] - current_position[E_AXIS]) > EXTRUDE_MAXLENGTH) {
  9745. current_position[E_AXIS] = destination[E_AXIS]; // Behave as if the move really took place, but ignore E part
  9746. SERIAL_ECHO_START;
  9747. SERIAL_ECHOLNPGM(MSG_ERR_LONG_EXTRUDE_STOP);
  9748. }
  9749. #endif
  9750. }
  9751. }
  9752. #endif
  9753. if (
  9754. #if IS_KINEMATIC
  9755. #if UBL_DELTA
  9756. ubl.prepare_linear_move_to(destination, feedrate_mm_s)
  9757. #else
  9758. prepare_kinematic_move_to(destination)
  9759. #endif
  9760. #elif ENABLED(DUAL_X_CARRIAGE)
  9761. prepare_move_to_destination_dualx()
  9762. #elif UBL_DELTA // will work for CARTESIAN too (smaller segments follow mesh more closely)
  9763. ubl.prepare_linear_move_to(destination, feedrate_mm_s)
  9764. #else
  9765. prepare_move_to_destination_cartesian()
  9766. #endif
  9767. ) return;
  9768. set_current_to_destination();
  9769. }
  9770. #if ENABLED(ARC_SUPPORT)
  9771. /**
  9772. * Plan an arc in 2 dimensions
  9773. *
  9774. * The arc is approximated by generating many small linear segments.
  9775. * The length of each segment is configured in MM_PER_ARC_SEGMENT (Default 1mm)
  9776. * Arcs should only be made relatively large (over 5mm), as larger arcs with
  9777. * larger segments will tend to be more efficient. Your slicer should have
  9778. * options for G2/G3 arc generation. In future these options may be GCode tunable.
  9779. */
  9780. void plan_arc(
  9781. float logical[XYZE], // Destination position
  9782. float *offset, // Center of rotation relative to current_position
  9783. uint8_t clockwise // Clockwise?
  9784. ) {
  9785. float r_X = -offset[X_AXIS], // Radius vector from center to current location
  9786. r_Y = -offset[Y_AXIS];
  9787. const float radius = HYPOT(r_X, r_Y),
  9788. center_X = current_position[X_AXIS] - r_X,
  9789. center_Y = current_position[Y_AXIS] - r_Y,
  9790. rt_X = logical[X_AXIS] - center_X,
  9791. rt_Y = logical[Y_AXIS] - center_Y,
  9792. linear_travel = logical[Z_AXIS] - current_position[Z_AXIS],
  9793. extruder_travel = logical[E_AXIS] - current_position[E_AXIS];
  9794. // CCW angle of rotation between position and target from the circle center. Only one atan2() trig computation required.
  9795. float angular_travel = atan2(r_X * rt_Y - r_Y * rt_X, r_X * rt_X + r_Y * rt_Y);
  9796. if (angular_travel < 0) angular_travel += RADIANS(360);
  9797. if (clockwise) angular_travel -= RADIANS(360);
  9798. // Make a circle if the angular rotation is 0
  9799. if (angular_travel == 0 && current_position[X_AXIS] == logical[X_AXIS] && current_position[Y_AXIS] == logical[Y_AXIS])
  9800. angular_travel += RADIANS(360);
  9801. const float mm_of_travel = HYPOT(angular_travel * radius, fabs(linear_travel));
  9802. if (mm_of_travel < 0.001) return;
  9803. uint16_t segments = floor(mm_of_travel / (MM_PER_ARC_SEGMENT));
  9804. if (segments == 0) segments = 1;
  9805. /**
  9806. * Vector rotation by transformation matrix: r is the original vector, r_T is the rotated vector,
  9807. * and phi is the angle of rotation. Based on the solution approach by Jens Geisler.
  9808. * r_T = [cos(phi) -sin(phi);
  9809. * sin(phi) cos(phi)] * r ;
  9810. *
  9811. * For arc generation, the center of the circle is the axis of rotation and the radius vector is
  9812. * defined from the circle center to the initial position. Each line segment is formed by successive
  9813. * vector rotations. This requires only two cos() and sin() computations to form the rotation
  9814. * matrix for the duration of the entire arc. Error may accumulate from numerical round-off, since
  9815. * all double numbers are single precision on the Arduino. (True double precision will not have
  9816. * round off issues for CNC applications.) Single precision error can accumulate to be greater than
  9817. * tool precision in some cases. Therefore, arc path correction is implemented.
  9818. *
  9819. * Small angle approximation may be used to reduce computation overhead further. This approximation
  9820. * holds for everything, but very small circles and large MM_PER_ARC_SEGMENT values. In other words,
  9821. * theta_per_segment would need to be greater than 0.1 rad and N_ARC_CORRECTION would need to be large
  9822. * to cause an appreciable drift error. N_ARC_CORRECTION~=25 is more than small enough to correct for
  9823. * numerical drift error. N_ARC_CORRECTION may be on the order a hundred(s) before error becomes an
  9824. * issue for CNC machines with the single precision Arduino calculations.
  9825. *
  9826. * This approximation also allows plan_arc to immediately insert a line segment into the planner
  9827. * without the initial overhead of computing cos() or sin(). By the time the arc needs to be applied
  9828. * a correction, the planner should have caught up to the lag caused by the initial plan_arc overhead.
  9829. * This is important when there are successive arc motions.
  9830. */
  9831. // Vector rotation matrix values
  9832. float arc_target[XYZE];
  9833. const float theta_per_segment = angular_travel / segments,
  9834. linear_per_segment = linear_travel / segments,
  9835. extruder_per_segment = extruder_travel / segments,
  9836. sin_T = theta_per_segment,
  9837. cos_T = 1 - 0.5 * sq(theta_per_segment); // Small angle approximation
  9838. // Initialize the linear axis
  9839. arc_target[Z_AXIS] = current_position[Z_AXIS];
  9840. // Initialize the extruder axis
  9841. arc_target[E_AXIS] = current_position[E_AXIS];
  9842. const float fr_mm_s = MMS_SCALED(feedrate_mm_s);
  9843. millis_t next_idle_ms = millis() + 200UL;
  9844. int8_t count = 0;
  9845. for (uint16_t i = 1; i < segments; i++) { // Iterate (segments-1) times
  9846. thermalManager.manage_heater();
  9847. if (ELAPSED(millis(), next_idle_ms)) {
  9848. next_idle_ms = millis() + 200UL;
  9849. idle();
  9850. }
  9851. if (++count < N_ARC_CORRECTION) {
  9852. // Apply vector rotation matrix to previous r_X / 1
  9853. const float r_new_Y = r_X * sin_T + r_Y * cos_T;
  9854. r_X = r_X * cos_T - r_Y * sin_T;
  9855. r_Y = r_new_Y;
  9856. }
  9857. else {
  9858. // Arc correction to radius vector. Computed only every N_ARC_CORRECTION increments.
  9859. // Compute exact location by applying transformation matrix from initial radius vector(=-offset).
  9860. // To reduce stuttering, the sin and cos could be computed at different times.
  9861. // For now, compute both at the same time.
  9862. const float cos_Ti = cos(i * theta_per_segment),
  9863. sin_Ti = sin(i * theta_per_segment);
  9864. r_X = -offset[X_AXIS] * cos_Ti + offset[Y_AXIS] * sin_Ti;
  9865. r_Y = -offset[X_AXIS] * sin_Ti - offset[Y_AXIS] * cos_Ti;
  9866. count = 0;
  9867. }
  9868. // Update arc_target location
  9869. arc_target[X_AXIS] = center_X + r_X;
  9870. arc_target[Y_AXIS] = center_Y + r_Y;
  9871. arc_target[Z_AXIS] += linear_per_segment;
  9872. arc_target[E_AXIS] += extruder_per_segment;
  9873. clamp_to_software_endstops(arc_target);
  9874. planner.buffer_line_kinematic(arc_target, fr_mm_s, active_extruder);
  9875. }
  9876. // Ensure last segment arrives at target location.
  9877. planner.buffer_line_kinematic(logical, fr_mm_s, active_extruder);
  9878. // As far as the parser is concerned, the position is now == target. In reality the
  9879. // motion control system might still be processing the action and the real tool position
  9880. // in any intermediate location.
  9881. set_current_to_destination();
  9882. }
  9883. #endif
  9884. #if ENABLED(BEZIER_CURVE_SUPPORT)
  9885. void plan_cubic_move(const float offset[4]) {
  9886. cubic_b_spline(current_position, destination, offset, MMS_SCALED(feedrate_mm_s), active_extruder);
  9887. // As far as the parser is concerned, the position is now == destination. In reality the
  9888. // motion control system might still be processing the action and the real tool position
  9889. // in any intermediate location.
  9890. set_current_to_destination();
  9891. }
  9892. #endif // BEZIER_CURVE_SUPPORT
  9893. #if ENABLED(USE_CONTROLLER_FAN)
  9894. void controllerFan() {
  9895. static millis_t lastMotorOn = 0, // Last time a motor was turned on
  9896. nextMotorCheck = 0; // Last time the state was checked
  9897. const millis_t ms = millis();
  9898. if (ELAPSED(ms, nextMotorCheck)) {
  9899. nextMotorCheck = ms + 2500UL; // Not a time critical function, so only check every 2.5s
  9900. 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
  9901. || E0_ENABLE_READ == E_ENABLE_ON // If any of the drivers are enabled...
  9902. #if E_STEPPERS > 1
  9903. || E1_ENABLE_READ == E_ENABLE_ON
  9904. #if HAS_X2_ENABLE
  9905. || X2_ENABLE_READ == X_ENABLE_ON
  9906. #endif
  9907. #if E_STEPPERS > 2
  9908. || E2_ENABLE_READ == E_ENABLE_ON
  9909. #if E_STEPPERS > 3
  9910. || E3_ENABLE_READ == E_ENABLE_ON
  9911. #if E_STEPPERS > 4
  9912. || E4_ENABLE_READ == E_ENABLE_ON
  9913. #endif // E_STEPPERS > 4
  9914. #endif // E_STEPPERS > 3
  9915. #endif // E_STEPPERS > 2
  9916. #endif // E_STEPPERS > 1
  9917. ) {
  9918. lastMotorOn = ms; //... set time to NOW so the fan will turn on
  9919. }
  9920. // Fan off if no steppers have been enabled for CONTROLLERFAN_SECS seconds
  9921. uint8_t speed = (!lastMotorOn || ELAPSED(ms, lastMotorOn + (CONTROLLERFAN_SECS) * 1000UL)) ? 0 : CONTROLLERFAN_SPEED;
  9922. // allows digital or PWM fan output to be used (see M42 handling)
  9923. WRITE(CONTROLLER_FAN_PIN, speed);
  9924. analogWrite(CONTROLLER_FAN_PIN, speed);
  9925. }
  9926. }
  9927. #endif // USE_CONTROLLER_FAN
  9928. #if ENABLED(MORGAN_SCARA)
  9929. /**
  9930. * Morgan SCARA Forward Kinematics. Results in cartes[].
  9931. * Maths and first version by QHARLEY.
  9932. * Integrated into Marlin and slightly restructured by Joachim Cerny.
  9933. */
  9934. void forward_kinematics_SCARA(const float &a, const float &b) {
  9935. float a_sin = sin(RADIANS(a)) * L1,
  9936. a_cos = cos(RADIANS(a)) * L1,
  9937. b_sin = sin(RADIANS(b)) * L2,
  9938. b_cos = cos(RADIANS(b)) * L2;
  9939. cartes[X_AXIS] = a_cos + b_cos + SCARA_OFFSET_X; //theta
  9940. cartes[Y_AXIS] = a_sin + b_sin + SCARA_OFFSET_Y; //theta+phi
  9941. /*
  9942. SERIAL_ECHOPAIR("SCARA FK Angle a=", a);
  9943. SERIAL_ECHOPAIR(" b=", b);
  9944. SERIAL_ECHOPAIR(" a_sin=", a_sin);
  9945. SERIAL_ECHOPAIR(" a_cos=", a_cos);
  9946. SERIAL_ECHOPAIR(" b_sin=", b_sin);
  9947. SERIAL_ECHOLNPAIR(" b_cos=", b_cos);
  9948. SERIAL_ECHOPAIR(" cartes[X_AXIS]=", cartes[X_AXIS]);
  9949. SERIAL_ECHOLNPAIR(" cartes[Y_AXIS]=", cartes[Y_AXIS]);
  9950. //*/
  9951. }
  9952. /**
  9953. * Morgan SCARA Inverse Kinematics. Results in delta[].
  9954. *
  9955. * See http://forums.reprap.org/read.php?185,283327
  9956. *
  9957. * Maths and first version by QHARLEY.
  9958. * Integrated into Marlin and slightly restructured by Joachim Cerny.
  9959. */
  9960. void inverse_kinematics(const float logical[XYZ]) {
  9961. static float C2, S2, SK1, SK2, THETA, PSI;
  9962. float sx = RAW_X_POSITION(logical[X_AXIS]) - SCARA_OFFSET_X, // Translate SCARA to standard X Y
  9963. sy = RAW_Y_POSITION(logical[Y_AXIS]) - SCARA_OFFSET_Y; // With scaling factor.
  9964. if (L1 == L2)
  9965. C2 = HYPOT2(sx, sy) / L1_2_2 - 1;
  9966. else
  9967. C2 = (HYPOT2(sx, sy) - (L1_2 + L2_2)) / (2.0 * L1 * L2);
  9968. S2 = sqrt(sq(C2) - 1);
  9969. // Unrotated Arm1 plus rotated Arm2 gives the distance from Center to End
  9970. SK1 = L1 + L2 * C2;
  9971. // Rotated Arm2 gives the distance from Arm1 to Arm2
  9972. SK2 = L2 * S2;
  9973. // Angle of Arm1 is the difference between Center-to-End angle and the Center-to-Elbow
  9974. THETA = atan2(SK1, SK2) - atan2(sx, sy);
  9975. // Angle of Arm2
  9976. PSI = atan2(S2, C2);
  9977. delta[A_AXIS] = DEGREES(THETA); // theta is support arm angle
  9978. delta[B_AXIS] = DEGREES(THETA + PSI); // equal to sub arm angle (inverted motor)
  9979. delta[C_AXIS] = logical[Z_AXIS];
  9980. /*
  9981. DEBUG_POS("SCARA IK", logical);
  9982. DEBUG_POS("SCARA IK", delta);
  9983. SERIAL_ECHOPAIR(" SCARA (x,y) ", sx);
  9984. SERIAL_ECHOPAIR(",", sy);
  9985. SERIAL_ECHOPAIR(" C2=", C2);
  9986. SERIAL_ECHOPAIR(" S2=", S2);
  9987. SERIAL_ECHOPAIR(" Theta=", THETA);
  9988. SERIAL_ECHOLNPAIR(" Phi=", PHI);
  9989. //*/
  9990. }
  9991. #endif // MORGAN_SCARA
  9992. #if ENABLED(TEMP_STAT_LEDS)
  9993. static bool red_led = false;
  9994. static millis_t next_status_led_update_ms = 0;
  9995. void handle_status_leds(void) {
  9996. if (ELAPSED(millis(), next_status_led_update_ms)) {
  9997. next_status_led_update_ms += 500; // Update every 0.5s
  9998. float max_temp = 0.0;
  9999. #if HAS_TEMP_BED
  10000. max_temp = MAX3(max_temp, thermalManager.degTargetBed(), thermalManager.degBed());
  10001. #endif
  10002. HOTEND_LOOP()
  10003. max_temp = MAX3(max_temp, thermalManager.degHotend(e), thermalManager.degTargetHotend(e));
  10004. bool new_led = (max_temp > 55.0) ? true : (max_temp < 54.0) ? false : red_led;
  10005. if (new_led != red_led) {
  10006. red_led = new_led;
  10007. #if PIN_EXISTS(STAT_LED_RED)
  10008. WRITE(STAT_LED_RED_PIN, new_led ? HIGH : LOW);
  10009. #if PIN_EXISTS(STAT_LED_BLUE)
  10010. WRITE(STAT_LED_BLUE_PIN, new_led ? LOW : HIGH);
  10011. #endif
  10012. #else
  10013. WRITE(STAT_LED_BLUE_PIN, new_led ? HIGH : LOW);
  10014. #endif
  10015. }
  10016. }
  10017. }
  10018. #endif
  10019. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  10020. void handle_filament_runout() {
  10021. if (!filament_ran_out) {
  10022. filament_ran_out = true;
  10023. enqueue_and_echo_commands_P(PSTR(FILAMENT_RUNOUT_SCRIPT));
  10024. stepper.synchronize();
  10025. }
  10026. }
  10027. #endif // FILAMENT_RUNOUT_SENSOR
  10028. #if ENABLED(FAST_PWM_FAN)
  10029. void setPwmFrequency(uint8_t pin, int val) {
  10030. val &= 0x07;
  10031. switch (digitalPinToTimer(pin)) {
  10032. #ifdef TCCR0A
  10033. case TIMER0A:
  10034. case TIMER0B:
  10035. //_SET_CS(0, val);
  10036. break;
  10037. #endif
  10038. #ifdef TCCR1A
  10039. case TIMER1A:
  10040. case TIMER1B:
  10041. //_SET_CS(1, val);
  10042. break;
  10043. #endif
  10044. #ifdef TCCR2
  10045. case TIMER2:
  10046. case TIMER2:
  10047. _SET_CS(2, val);
  10048. break;
  10049. #endif
  10050. #ifdef TCCR2A
  10051. case TIMER2A:
  10052. case TIMER2B:
  10053. _SET_CS(2, val);
  10054. break;
  10055. #endif
  10056. #ifdef TCCR3A
  10057. case TIMER3A:
  10058. case TIMER3B:
  10059. case TIMER3C:
  10060. _SET_CS(3, val);
  10061. break;
  10062. #endif
  10063. #ifdef TCCR4A
  10064. case TIMER4A:
  10065. case TIMER4B:
  10066. case TIMER4C:
  10067. _SET_CS(4, val);
  10068. break;
  10069. #endif
  10070. #ifdef TCCR5A
  10071. case TIMER5A:
  10072. case TIMER5B:
  10073. case TIMER5C:
  10074. _SET_CS(5, val);
  10075. break;
  10076. #endif
  10077. }
  10078. }
  10079. #endif // FAST_PWM_FAN
  10080. float calculate_volumetric_multiplier(float diameter) {
  10081. if (!volumetric_enabled || diameter == 0) return 1.0;
  10082. return 1.0 / (M_PI * sq(diameter * 0.5));
  10083. }
  10084. void calculate_volumetric_multipliers() {
  10085. for (uint8_t i = 0; i < COUNT(filament_size); i++)
  10086. volumetric_multiplier[i] = calculate_volumetric_multiplier(filament_size[i]);
  10087. }
  10088. void enable_all_steppers() {
  10089. enable_X();
  10090. enable_Y();
  10091. enable_Z();
  10092. enable_E0();
  10093. enable_E1();
  10094. enable_E2();
  10095. enable_E3();
  10096. enable_E4();
  10097. }
  10098. void disable_e_steppers() {
  10099. disable_E0();
  10100. disable_E1();
  10101. disable_E2();
  10102. disable_E3();
  10103. disable_E4();
  10104. }
  10105. void disable_all_steppers() {
  10106. disable_X();
  10107. disable_Y();
  10108. disable_Z();
  10109. disable_e_steppers();
  10110. }
  10111. #if ENABLED(HAVE_TMC2130)
  10112. void automatic_current_control(TMC2130Stepper &st, String axisID) {
  10113. // Check otpw even if we don't use automatic control. Allows for flag inspection.
  10114. const bool is_otpw = st.checkOT();
  10115. // Report if a warning was triggered
  10116. static bool previous_otpw = false;
  10117. if (is_otpw && !previous_otpw) {
  10118. char timestamp[10];
  10119. duration_t elapsed = print_job_timer.duration();
  10120. const bool has_days = (elapsed.value > 60*60*24L);
  10121. (void)elapsed.toDigital(timestamp, has_days);
  10122. SERIAL_ECHO(timestamp);
  10123. SERIAL_ECHO(": ");
  10124. SERIAL_ECHO(axisID);
  10125. SERIAL_ECHOLNPGM(" driver overtemperature warning!");
  10126. }
  10127. previous_otpw = is_otpw;
  10128. #if CURRENT_STEP > 0 && ENABLED(AUTOMATIC_CURRENT_CONTROL)
  10129. // Return if user has not enabled current control start with M906 S1.
  10130. if (!auto_current_control) return;
  10131. /**
  10132. * Decrease current if is_otpw is true.
  10133. * Bail out if driver is disabled.
  10134. * Increase current if OTPW has not been triggered yet.
  10135. */
  10136. uint16_t current = st.getCurrent();
  10137. if (is_otpw) {
  10138. st.setCurrent(current - CURRENT_STEP, R_SENSE, HOLD_MULTIPLIER);
  10139. #if ENABLED(REPORT_CURRENT_CHANGE)
  10140. SERIAL_ECHO(axisID);
  10141. SERIAL_ECHOPAIR(" current decreased to ", st.getCurrent());
  10142. #endif
  10143. }
  10144. else if (!st.isEnabled())
  10145. return;
  10146. else if (!is_otpw && !st.getOTPW()) {
  10147. current += CURRENT_STEP;
  10148. if (current <= AUTO_ADJUST_MAX) {
  10149. st.setCurrent(current, R_SENSE, HOLD_MULTIPLIER);
  10150. #if ENABLED(REPORT_CURRENT_CHANGE)
  10151. SERIAL_ECHO(axisID);
  10152. SERIAL_ECHOPAIR(" current increased to ", st.getCurrent());
  10153. #endif
  10154. }
  10155. }
  10156. SERIAL_EOL;
  10157. #endif
  10158. }
  10159. void checkOverTemp() {
  10160. static millis_t next_cOT = 0;
  10161. if (ELAPSED(millis(), next_cOT)) {
  10162. next_cOT = millis() + 5000;
  10163. #if ENABLED(X_IS_TMC2130)
  10164. automatic_current_control(stepperX, "X");
  10165. #endif
  10166. #if ENABLED(Y_IS_TMC2130)
  10167. automatic_current_control(stepperY, "Y");
  10168. #endif
  10169. #if ENABLED(Z_IS_TMC2130)
  10170. automatic_current_control(stepperZ, "Z");
  10171. #endif
  10172. #if ENABLED(X2_IS_TMC2130)
  10173. automatic_current_control(stepperX2, "X2");
  10174. #endif
  10175. #if ENABLED(Y2_IS_TMC2130)
  10176. automatic_current_control(stepperY2, "Y2");
  10177. #endif
  10178. #if ENABLED(Z2_IS_TMC2130)
  10179. automatic_current_control(stepperZ2, "Z2");
  10180. #endif
  10181. #if ENABLED(E0_IS_TMC2130)
  10182. automatic_current_control(stepperE0, "E0");
  10183. #endif
  10184. #if ENABLED(E1_IS_TMC2130)
  10185. automatic_current_control(stepperE1, "E1");
  10186. #endif
  10187. #if ENABLED(E2_IS_TMC2130)
  10188. automatic_current_control(stepperE2, "E2");
  10189. #endif
  10190. #if ENABLED(E3_IS_TMC2130)
  10191. automatic_current_control(stepperE3, "E3");
  10192. #endif
  10193. #if ENABLED(E4_IS_TMC2130)
  10194. automatic_current_control(stepperE4, "E4");
  10195. #endif
  10196. #if ENABLED(E4_IS_TMC2130)
  10197. automatic_current_control(stepperE4);
  10198. #endif
  10199. }
  10200. }
  10201. #endif // HAVE_TMC2130
  10202. /**
  10203. * Manage several activities:
  10204. * - Check for Filament Runout
  10205. * - Keep the command buffer full
  10206. * - Check for maximum inactive time between commands
  10207. * - Check for maximum inactive time between stepper commands
  10208. * - Check if pin CHDK needs to go LOW
  10209. * - Check for KILL button held down
  10210. * - Check for HOME button held down
  10211. * - Check if cooling fan needs to be switched on
  10212. * - Check if an idle but hot extruder needs filament extruded (EXTRUDER_RUNOUT_PREVENT)
  10213. */
  10214. void manage_inactivity(bool ignore_stepper_queue/*=false*/) {
  10215. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  10216. if ((IS_SD_PRINTING || print_job_timer.isRunning()) && (READ(FIL_RUNOUT_PIN) == FIL_RUNOUT_INVERTING))
  10217. handle_filament_runout();
  10218. #endif
  10219. if (commands_in_queue < BUFSIZE) get_available_commands();
  10220. const millis_t ms = millis();
  10221. if (max_inactive_time && ELAPSED(ms, previous_cmd_ms + max_inactive_time)) {
  10222. SERIAL_ERROR_START;
  10223. SERIAL_ECHOLNPAIR(MSG_KILL_INACTIVE_TIME, parser.command_ptr);
  10224. kill(PSTR(MSG_KILLED));
  10225. }
  10226. // Prevent steppers timing-out in the middle of M600
  10227. #if ENABLED(ADVANCED_PAUSE_FEATURE) && ENABLED(PAUSE_PARK_NO_STEPPER_TIMEOUT)
  10228. #define MOVE_AWAY_TEST !move_away_flag
  10229. #else
  10230. #define MOVE_AWAY_TEST true
  10231. #endif
  10232. if (MOVE_AWAY_TEST && stepper_inactive_time && ELAPSED(ms, previous_cmd_ms + stepper_inactive_time)
  10233. && !ignore_stepper_queue && !planner.blocks_queued()) {
  10234. #if ENABLED(DISABLE_INACTIVE_X)
  10235. disable_X();
  10236. #endif
  10237. #if ENABLED(DISABLE_INACTIVE_Y)
  10238. disable_Y();
  10239. #endif
  10240. #if ENABLED(DISABLE_INACTIVE_Z)
  10241. disable_Z();
  10242. #endif
  10243. #if ENABLED(DISABLE_INACTIVE_E)
  10244. disable_e_steppers();
  10245. #endif
  10246. }
  10247. #ifdef CHDK // Check if pin should be set to LOW after M240 set it to HIGH
  10248. if (chdkActive && ELAPSED(ms, chdkHigh + CHDK_DELAY)) {
  10249. chdkActive = false;
  10250. WRITE(CHDK, LOW);
  10251. }
  10252. #endif
  10253. #if HAS_KILL
  10254. // Check if the kill button was pressed and wait just in case it was an accidental
  10255. // key kill key press
  10256. // -------------------------------------------------------------------------------
  10257. static int killCount = 0; // make the inactivity button a bit less responsive
  10258. const int KILL_DELAY = 750;
  10259. if (!READ(KILL_PIN))
  10260. killCount++;
  10261. else if (killCount > 0)
  10262. killCount--;
  10263. // Exceeded threshold and we can confirm that it was not accidental
  10264. // KILL the machine
  10265. // ----------------------------------------------------------------
  10266. if (killCount >= KILL_DELAY) {
  10267. SERIAL_ERROR_START;
  10268. SERIAL_ERRORLNPGM(MSG_KILL_BUTTON);
  10269. kill(PSTR(MSG_KILLED));
  10270. }
  10271. #endif
  10272. #if HAS_HOME
  10273. // Check to see if we have to home, use poor man's debouncer
  10274. // ---------------------------------------------------------
  10275. static int homeDebounceCount = 0; // poor man's debouncing count
  10276. const int HOME_DEBOUNCE_DELAY = 2500;
  10277. if (!IS_SD_PRINTING && !READ(HOME_PIN)) {
  10278. if (!homeDebounceCount) {
  10279. enqueue_and_echo_commands_P(PSTR("G28"));
  10280. LCD_MESSAGEPGM(MSG_AUTO_HOME);
  10281. }
  10282. if (homeDebounceCount < HOME_DEBOUNCE_DELAY)
  10283. homeDebounceCount++;
  10284. else
  10285. homeDebounceCount = 0;
  10286. }
  10287. #endif
  10288. #if ENABLED(USE_CONTROLLER_FAN)
  10289. controllerFan(); // Check if fan should be turned on to cool stepper drivers down
  10290. #endif
  10291. #if ENABLED(EXTRUDER_RUNOUT_PREVENT)
  10292. if (ELAPSED(ms, previous_cmd_ms + (EXTRUDER_RUNOUT_SECONDS) * 1000UL)
  10293. && thermalManager.degHotend(active_extruder) > EXTRUDER_RUNOUT_MINTEMP) {
  10294. bool oldstatus;
  10295. #if ENABLED(SWITCHING_EXTRUDER)
  10296. oldstatus = E0_ENABLE_READ;
  10297. enable_E0();
  10298. #else // !SWITCHING_EXTRUDER
  10299. switch (active_extruder) {
  10300. case 0: oldstatus = E0_ENABLE_READ; enable_E0(); break;
  10301. #if E_STEPPERS > 1
  10302. case 1: oldstatus = E1_ENABLE_READ; enable_E1(); break;
  10303. #if E_STEPPERS > 2
  10304. case 2: oldstatus = E2_ENABLE_READ; enable_E2(); break;
  10305. #if E_STEPPERS > 3
  10306. case 3: oldstatus = E3_ENABLE_READ; enable_E3(); break;
  10307. #if E_STEPPERS > 4
  10308. case 4: oldstatus = E4_ENABLE_READ; enable_E4(); break;
  10309. #endif // E_STEPPERS > 4
  10310. #endif // E_STEPPERS > 3
  10311. #endif // E_STEPPERS > 2
  10312. #endif // E_STEPPERS > 1
  10313. }
  10314. #endif // !SWITCHING_EXTRUDER
  10315. previous_cmd_ms = ms; // refresh_cmd_timeout()
  10316. const float olde = current_position[E_AXIS];
  10317. current_position[E_AXIS] += EXTRUDER_RUNOUT_EXTRUDE;
  10318. planner.buffer_line_kinematic(current_position, MMM_TO_MMS(EXTRUDER_RUNOUT_SPEED), active_extruder);
  10319. current_position[E_AXIS] = olde;
  10320. planner.set_e_position_mm(olde);
  10321. stepper.synchronize();
  10322. #if ENABLED(SWITCHING_EXTRUDER)
  10323. E0_ENABLE_WRITE(oldstatus);
  10324. #else
  10325. switch (active_extruder) {
  10326. case 0: E0_ENABLE_WRITE(oldstatus); break;
  10327. #if E_STEPPERS > 1
  10328. case 1: E1_ENABLE_WRITE(oldstatus); break;
  10329. #if E_STEPPERS > 2
  10330. case 2: E2_ENABLE_WRITE(oldstatus); break;
  10331. #if E_STEPPERS > 3
  10332. case 3: E3_ENABLE_WRITE(oldstatus); break;
  10333. #if E_STEPPERS > 4
  10334. case 4: E4_ENABLE_WRITE(oldstatus); break;
  10335. #endif // E_STEPPERS > 4
  10336. #endif // E_STEPPERS > 3
  10337. #endif // E_STEPPERS > 2
  10338. #endif // E_STEPPERS > 1
  10339. }
  10340. #endif // !SWITCHING_EXTRUDER
  10341. }
  10342. #endif // EXTRUDER_RUNOUT_PREVENT
  10343. #if ENABLED(DUAL_X_CARRIAGE)
  10344. // handle delayed move timeout
  10345. if (delayed_move_time && ELAPSED(ms, delayed_move_time + 1000UL) && IsRunning()) {
  10346. // travel moves have been received so enact them
  10347. delayed_move_time = 0xFFFFFFFFUL; // force moves to be done
  10348. set_destination_to_current();
  10349. prepare_move_to_destination();
  10350. }
  10351. #endif
  10352. #if ENABLED(TEMP_STAT_LEDS)
  10353. handle_status_leds();
  10354. #endif
  10355. #if ENABLED(HAVE_TMC2130)
  10356. checkOverTemp();
  10357. #endif
  10358. planner.check_axes_activity();
  10359. }
  10360. /**
  10361. * Standard idle routine keeps the machine alive
  10362. */
  10363. void idle(
  10364. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  10365. bool no_stepper_sleep/*=false*/
  10366. #endif
  10367. ) {
  10368. lcd_update();
  10369. host_keepalive();
  10370. #if ENABLED(AUTO_REPORT_TEMPERATURES) && (HAS_TEMP_HOTEND || HAS_TEMP_BED)
  10371. auto_report_temperatures();
  10372. #endif
  10373. manage_inactivity(
  10374. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  10375. no_stepper_sleep
  10376. #endif
  10377. );
  10378. thermalManager.manage_heater();
  10379. #if ENABLED(PRINTCOUNTER)
  10380. print_job_timer.tick();
  10381. #endif
  10382. #if HAS_BUZZER && DISABLED(LCD_USE_I2C_BUZZER)
  10383. buzzer.tick();
  10384. #endif
  10385. }
  10386. /**
  10387. * Kill all activity and lock the machine.
  10388. * After this the machine will need to be reset.
  10389. */
  10390. void kill(const char* lcd_msg) {
  10391. SERIAL_ERROR_START;
  10392. SERIAL_ERRORLNPGM(MSG_ERR_KILLED);
  10393. thermalManager.disable_all_heaters();
  10394. disable_all_steppers();
  10395. #if ENABLED(ULTRA_LCD)
  10396. kill_screen(lcd_msg);
  10397. #else
  10398. UNUSED(lcd_msg);
  10399. #endif
  10400. _delay_ms(600); // Wait a short time (allows messages to get out before shutting down.
  10401. cli(); // Stop interrupts
  10402. _delay_ms(250); //Wait to ensure all interrupts routines stopped
  10403. thermalManager.disable_all_heaters(); //turn off heaters again
  10404. #if HAS_POWER_SWITCH
  10405. SET_INPUT(PS_ON_PIN);
  10406. #endif
  10407. suicide();
  10408. while (1) {
  10409. #if ENABLED(USE_WATCHDOG)
  10410. watchdog_reset();
  10411. #endif
  10412. } // Wait for reset
  10413. }
  10414. /**
  10415. * Turn off heaters and stop the print in progress
  10416. * After a stop the machine may be resumed with M999
  10417. */
  10418. void stop() {
  10419. thermalManager.disable_all_heaters(); // 'unpause' taken care of in here
  10420. #if ENABLED(PROBING_FANS_OFF)
  10421. if (fans_paused) fans_pause(false); // put things back the way they were
  10422. #endif
  10423. if (IsRunning()) {
  10424. Stopped_gcode_LastN = gcode_LastN; // Save last g_code for restart
  10425. SERIAL_ERROR_START;
  10426. SERIAL_ERRORLNPGM(MSG_ERR_STOPPED);
  10427. LCD_MESSAGEPGM(MSG_STOPPED);
  10428. safe_delay(350); // allow enough time for messages to get out before stopping
  10429. Running = false;
  10430. }
  10431. }
  10432. /**
  10433. * Marlin entry-point: Set up before the program loop
  10434. * - Set up the kill pin, filament runout, power hold
  10435. * - Start the serial port
  10436. * - Print startup messages and diagnostics
  10437. * - Get EEPROM or default settings
  10438. * - Initialize managers for:
  10439. * • temperature
  10440. * • planner
  10441. * • watchdog
  10442. * • stepper
  10443. * • photo pin
  10444. * • servos
  10445. * • LCD controller
  10446. * • Digipot I2C
  10447. * • Z probe sled
  10448. * • status LEDs
  10449. */
  10450. void setup() {
  10451. #ifdef DISABLE_JTAG
  10452. // Disable JTAG on AT90USB chips to free up pins for IO
  10453. MCUCR = 0x80;
  10454. MCUCR = 0x80;
  10455. #endif
  10456. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  10457. setup_filrunoutpin();
  10458. #endif
  10459. setup_killpin();
  10460. setup_powerhold();
  10461. #if HAS_STEPPER_RESET
  10462. disableStepperDrivers();
  10463. #endif
  10464. MYSERIAL.begin(BAUDRATE);
  10465. SERIAL_PROTOCOLLNPGM("start");
  10466. SERIAL_ECHO_START;
  10467. // Check startup - does nothing if bootloader sets MCUSR to 0
  10468. byte mcu = MCUSR;
  10469. if (mcu & 1) SERIAL_ECHOLNPGM(MSG_POWERUP);
  10470. if (mcu & 2) SERIAL_ECHOLNPGM(MSG_EXTERNAL_RESET);
  10471. if (mcu & 4) SERIAL_ECHOLNPGM(MSG_BROWNOUT_RESET);
  10472. if (mcu & 8) SERIAL_ECHOLNPGM(MSG_WATCHDOG_RESET);
  10473. if (mcu & 32) SERIAL_ECHOLNPGM(MSG_SOFTWARE_RESET);
  10474. MCUSR = 0;
  10475. SERIAL_ECHOPGM(MSG_MARLIN);
  10476. SERIAL_CHAR(' ');
  10477. SERIAL_ECHOLNPGM(SHORT_BUILD_VERSION);
  10478. SERIAL_EOL;
  10479. #if defined(STRING_DISTRIBUTION_DATE) && defined(STRING_CONFIG_H_AUTHOR)
  10480. SERIAL_ECHO_START;
  10481. SERIAL_ECHOPGM(MSG_CONFIGURATION_VER);
  10482. SERIAL_ECHOPGM(STRING_DISTRIBUTION_DATE);
  10483. SERIAL_ECHOLNPGM(MSG_AUTHOR STRING_CONFIG_H_AUTHOR);
  10484. SERIAL_ECHOLNPGM("Compiled: " __DATE__);
  10485. #endif
  10486. SERIAL_ECHO_START;
  10487. SERIAL_ECHOPAIR(MSG_FREE_MEMORY, freeMemory());
  10488. SERIAL_ECHOLNPAIR(MSG_PLANNER_BUFFER_BYTES, (int)sizeof(block_t)*BLOCK_BUFFER_SIZE);
  10489. // Send "ok" after commands by default
  10490. for (int8_t i = 0; i < BUFSIZE; i++) send_ok[i] = true;
  10491. // Load data from EEPROM if available (or use defaults)
  10492. // This also updates variables in the planner, elsewhere
  10493. (void)settings.load();
  10494. #if HAS_M206_COMMAND
  10495. // Initialize current position based on home_offset
  10496. COPY(current_position, home_offset);
  10497. #else
  10498. ZERO(current_position);
  10499. #endif
  10500. // Vital to init stepper/planner equivalent for current_position
  10501. SYNC_PLAN_POSITION_KINEMATIC();
  10502. thermalManager.init(); // Initialize temperature loop
  10503. #if ENABLED(USE_WATCHDOG)
  10504. watchdog_init();
  10505. #endif
  10506. stepper.init(); // Initialize stepper, this enables interrupts!
  10507. servo_init();
  10508. #if HAS_PHOTOGRAPH
  10509. OUT_WRITE(PHOTOGRAPH_PIN, LOW);
  10510. #endif
  10511. #if HAS_CASE_LIGHT
  10512. update_case_light();
  10513. #endif
  10514. #if ENABLED(SPINDLE_LASER_ENABLE)
  10515. OUT_WRITE(SPINDLE_LASER_ENABLE_PIN, !SPINDLE_LASER_ENABLE_INVERT); // init spindle to off
  10516. #if SPINDLE_DIR_CHANGE
  10517. OUT_WRITE(SPINDLE_DIR_PIN, SPINDLE_INVERT_DIR ? 255 : 0); // init rotation to clockwise (M3)
  10518. #endif
  10519. #if ENABLED(SPINDLE_LASER_PWM)
  10520. SET_OUTPUT(SPINDLE_LASER_PWM_PIN);
  10521. analogWrite(SPINDLE_LASER_PWM_PIN, SPINDLE_LASER_PWM_INVERT ? 255 : 0); // set to lowest speed
  10522. #endif
  10523. #endif
  10524. #if HAS_BED_PROBE
  10525. endstops.enable_z_probe(false);
  10526. #endif
  10527. #if ENABLED(USE_CONTROLLER_FAN)
  10528. SET_OUTPUT(CONTROLLER_FAN_PIN); //Set pin used for driver cooling fan
  10529. #endif
  10530. #if HAS_STEPPER_RESET
  10531. enableStepperDrivers();
  10532. #endif
  10533. #if ENABLED(DIGIPOT_I2C)
  10534. digipot_i2c_init();
  10535. #endif
  10536. #if ENABLED(DAC_STEPPER_CURRENT)
  10537. dac_init();
  10538. #endif
  10539. #if (ENABLED(Z_PROBE_SLED) || ENABLED(SOLENOID_PROBE)) && HAS_SOLENOID_1
  10540. OUT_WRITE(SOL1_PIN, LOW); // turn it off
  10541. #endif
  10542. setup_homepin();
  10543. #if PIN_EXISTS(STAT_LED_RED)
  10544. OUT_WRITE(STAT_LED_RED_PIN, LOW); // turn it off
  10545. #endif
  10546. #if PIN_EXISTS(STAT_LED_BLUE)
  10547. OUT_WRITE(STAT_LED_BLUE_PIN, LOW); // turn it off
  10548. #endif
  10549. #if ENABLED(RGB_LED) || ENABLED(RGBW_LED)
  10550. SET_OUTPUT(RGB_LED_R_PIN);
  10551. SET_OUTPUT(RGB_LED_G_PIN);
  10552. SET_OUTPUT(RGB_LED_B_PIN);
  10553. #if ENABLED(RGBW_LED)
  10554. SET_OUTPUT(RGB_LED_W_PIN);
  10555. #endif
  10556. #endif
  10557. lcd_init();
  10558. #if ENABLED(SHOW_BOOTSCREEN)
  10559. #if ENABLED(DOGLCD)
  10560. safe_delay(BOOTSCREEN_TIMEOUT);
  10561. #elif ENABLED(ULTRA_LCD)
  10562. bootscreen();
  10563. #if DISABLED(SDSUPPORT)
  10564. lcd_init();
  10565. #endif
  10566. #endif
  10567. #endif
  10568. #if ENABLED(MIXING_EXTRUDER) && MIXING_VIRTUAL_TOOLS > 1
  10569. // Initialize mixing to 100% color 1
  10570. for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
  10571. mixing_factor[i] = (i == 0) ? 1.0 : 0.0;
  10572. for (uint8_t t = 0; t < MIXING_VIRTUAL_TOOLS; t++)
  10573. for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
  10574. mixing_virtual_tool_mix[t][i] = mixing_factor[i];
  10575. #endif
  10576. #if ENABLED(BLTOUCH)
  10577. // Make sure any BLTouch error condition is cleared
  10578. bltouch_command(BLTOUCH_RESET);
  10579. set_bltouch_deployed(true);
  10580. set_bltouch_deployed(false);
  10581. #endif
  10582. #if ENABLED(EXPERIMENTAL_I2CBUS) && I2C_SLAVE_ADDRESS > 0
  10583. i2c.onReceive(i2c_on_receive);
  10584. i2c.onRequest(i2c_on_request);
  10585. #endif
  10586. #if ENABLED(ENDSTOP_INTERRUPTS_FEATURE)
  10587. setup_endstop_interrupts();
  10588. #endif
  10589. }
  10590. /**
  10591. * The main Marlin program loop
  10592. *
  10593. * - Save or log commands to SD
  10594. * - Process available commands (if not saving)
  10595. * - Call heater manager
  10596. * - Call inactivity manager
  10597. * - Call endstop manager
  10598. * - Call LCD update
  10599. */
  10600. void loop() {
  10601. if (commands_in_queue < BUFSIZE) get_available_commands();
  10602. #if ENABLED(SDSUPPORT)
  10603. card.checkautostart(false);
  10604. #endif
  10605. if (commands_in_queue) {
  10606. #if ENABLED(SDSUPPORT)
  10607. if (card.saving) {
  10608. char* command = command_queue[cmd_queue_index_r];
  10609. if (strstr_P(command, PSTR("M29"))) {
  10610. // M29 closes the file
  10611. card.closefile();
  10612. SERIAL_PROTOCOLLNPGM(MSG_FILE_SAVED);
  10613. ok_to_send();
  10614. }
  10615. else {
  10616. // Write the string from the read buffer to SD
  10617. card.write_command(command);
  10618. if (card.logging)
  10619. process_next_command(); // The card is saving because it's logging
  10620. else
  10621. ok_to_send();
  10622. }
  10623. }
  10624. else
  10625. process_next_command();
  10626. #else
  10627. process_next_command();
  10628. #endif // SDSUPPORT
  10629. // The queue may be reset by a command handler or by code invoked by idle() within a handler
  10630. if (commands_in_queue) {
  10631. --commands_in_queue;
  10632. if (++cmd_queue_index_r >= BUFSIZE) cmd_queue_index_r = 0;
  10633. }
  10634. }
  10635. endstops.report_state();
  10636. idle();
  10637. }