My Marlin configs for Fabrikator Mini and CTC i3 Pro B
Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

Marlin_main.cpp 232KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374
  1. /**
  2. * Marlin Firmware
  3. *
  4. * Based on Sprinter and grbl.
  5. * Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
  6. *
  7. * This program is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. *
  20. * About Marlin
  21. *
  22. * This firmware is a mashup between Sprinter and grbl.
  23. * - https://github.com/kliment/Sprinter
  24. * - https://github.com/simen/grbl/tree
  25. *
  26. * It has preliminary support for Matthew Roberts advance algorithm
  27. * - http://reprap.org/pipermail/reprap-dev/2011-May/003323.html
  28. */
  29. #include "Marlin.h"
  30. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  31. #include "vector_3.h"
  32. #if ENABLED(AUTO_BED_LEVELING_GRID)
  33. #include "qr_solve.h"
  34. #endif
  35. #endif // AUTO_BED_LEVELING_FEATURE
  36. #if ENABLED(MESH_BED_LEVELING)
  37. #include "mesh_bed_leveling.h"
  38. #endif
  39. #include "ultralcd.h"
  40. #include "planner.h"
  41. #include "stepper.h"
  42. #include "temperature.h"
  43. #include "cardreader.h"
  44. #include "configuration_store.h"
  45. #include "language.h"
  46. #include "pins_arduino.h"
  47. #include "math.h"
  48. #include "buzzer.h"
  49. #if ENABLED(USE_WATCHDOG)
  50. #include "watchdog.h"
  51. #endif
  52. #if ENABLED(BLINKM)
  53. #include "blinkm.h"
  54. #include "Wire.h"
  55. #endif
  56. #if HAS_SERVOS
  57. #include "servo.h"
  58. #endif
  59. #if HAS_DIGIPOTSS
  60. #include <SPI.h>
  61. #endif
  62. /**
  63. * Look here for descriptions of G-codes:
  64. * - http://linuxcnc.org/handbook/gcode/g-code.html
  65. * - http://objects.reprap.org/wiki/Mendel_User_Manual:_RepRapGCodes
  66. *
  67. * Help us document these G-codes online:
  68. * - https://github.com/MarlinFirmware/Marlin/wiki/G-Code-in-Marlin
  69. * - http://reprap.org/wiki/G-code
  70. *
  71. * -----------------
  72. * Implemented Codes
  73. * -----------------
  74. *
  75. * "G" Codes
  76. *
  77. * G0 -> G1
  78. * G1 - Coordinated Movement X Y Z E
  79. * G2 - CW ARC
  80. * G3 - CCW ARC
  81. * G4 - Dwell S<seconds> or P<milliseconds>
  82. * G10 - retract filament according to settings of M207
  83. * G11 - retract recover filament according to settings of M208
  84. * G28 - Home one or more axes
  85. * G29 - Detailed Z probe, probes the bed at 3 or more points. Will fail if you haven't homed yet.
  86. * G30 - Single Z probe, probes bed at current XY location.
  87. * G31 - Dock sled (Z_PROBE_SLED only)
  88. * G32 - Undock sled (Z_PROBE_SLED only)
  89. * G90 - Use Absolute Coordinates
  90. * G91 - Use Relative Coordinates
  91. * G92 - Set current position to coordinates given
  92. *
  93. * "M" Codes
  94. *
  95. * M0 - Unconditional stop - Wait for user to press a button on the LCD (Only if ULTRA_LCD is enabled)
  96. * M1 - Same as M0
  97. * M17 - Enable/Power all stepper motors
  98. * M18 - Disable all stepper motors; same as M84
  99. * M20 - List SD card
  100. * M21 - Init SD card
  101. * M22 - Release SD card
  102. * M23 - Select SD file (M23 filename.g)
  103. * M24 - Start/resume SD print
  104. * M25 - Pause SD print
  105. * M26 - Set SD position in bytes (M26 S12345)
  106. * M27 - Report SD print status
  107. * M28 - Start SD write (M28 filename.g)
  108. * M29 - Stop SD write
  109. * M30 - Delete file from SD (M30 filename.g)
  110. * M31 - Output time since last M109 or SD card start to serial
  111. * M32 - Select file and start SD print (Can be used _while_ printing from SD card files):
  112. * syntax "M32 /path/filename#", or "M32 S<startpos bytes> !filename#"
  113. * Call gcode file : "M32 P !filename#" and return to caller file after finishing (similar to #include).
  114. * The '#' is necessary when calling from within sd files, as it stops buffer prereading
  115. * M33 - Get the longname version of a path
  116. * M42 - Change pin status via gcode Use M42 Px Sy to set pin x to value y, when omitting Px the onboard led will be used.
  117. * M48 - Measure Z_Probe repeatability. M48 [P # of points] [X position] [Y position] [V_erboseness #] [E_ngage Probe] [L # of legs of travel]
  118. * M80 - Turn on Power Supply
  119. * M81 - Turn off Power Supply
  120. * M82 - Set E codes absolute (default)
  121. * M83 - Set E codes relative while in Absolute Coordinates (G90) mode
  122. * M84 - Disable steppers until next move,
  123. * or use S<seconds> to specify an inactivity timeout, after which the steppers will be disabled. S0 to disable the timeout.
  124. * M85 - Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
  125. * M92 - Set axis_steps_per_unit - same syntax as G92
  126. * M104 - Set extruder target temp
  127. * M105 - Read current temp
  128. * M106 - Fan on
  129. * M107 - Fan off
  130. * M109 - Sxxx Wait for extruder current temp to reach target temp. Waits only when heating
  131. * Rxxx Wait for extruder current temp to reach target temp. Waits when heating and cooling
  132. * IF AUTOTEMP is enabled, S<mintemp> B<maxtemp> F<factor>. Exit autotemp by any M109 without F
  133. * M110 - Set the current line number
  134. * M111 - Set debug flags with S<mask>. See flag bits defined in Marlin.h.
  135. * M112 - Emergency stop
  136. * M114 - Output current position to serial port
  137. * M115 - Capabilities string
  138. * M117 - Display a message on the controller screen
  139. * M119 - Output Endstop status to serial port
  140. * M120 - Enable endstop detection
  141. * M121 - Disable endstop detection
  142. * M126 - Solenoid Air Valve Open (BariCUDA support by jmil)
  143. * M127 - Solenoid Air Valve Closed (BariCUDA vent to atmospheric pressure by jmil)
  144. * M128 - EtoP Open (BariCUDA EtoP = electricity to air pressure transducer by jmil)
  145. * M129 - EtoP Closed (BariCUDA EtoP = electricity to air pressure transducer by jmil)
  146. * M140 - Set bed target temp
  147. * M145 - Set the heatup state H<hotend> B<bed> F<fan speed> for S<material> (0=PLA, 1=ABS)
  148. * M150 - Set BlinkM Color Output R: Red<0-255> U(!): Green<0-255> B: Blue<0-255> over i2c, G for green does not work.
  149. * M190 - Sxxx Wait for bed current temp to reach target temp. Waits only when heating
  150. * Rxxx Wait for bed current temp to reach target temp. Waits when heating and cooling
  151. * M200 - set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).:D<millimeters>-
  152. * M201 - Set max acceleration in units/s^2 for print moves (M201 X1000 Y1000)
  153. * M202 - Set max acceleration in units/s^2 for travel moves (M202 X1000 Y1000) Unused in Marlin!!
  154. * M203 - Set maximum feedrate that your machine can sustain (M203 X200 Y200 Z300 E10000) in mm/sec
  155. * M204 - Set default acceleration: P for Printing moves, R for Retract only (no X, Y, Z) moves and T for Travel (non printing) moves (ex. M204 P800 T3000 R9000) in mm/sec^2
  156. * M205 - advanced settings: minimum travel speed S=while printing T=travel only, B=minimum segment time X= maximum xy jerk, Z=maximum Z jerk, E=maximum E jerk
  157. * M206 - Set additional homing offset
  158. * M207 - Set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop], stays in mm regardless of M200 setting
  159. * M208 - Set recover=unretract length S[positive mm surplus to the M207 S*] F[feedrate mm/min]
  160. * M209 - S<1=true/0=false> enable automatic retract detect if the slicer did not support G10/11: every normal extrude-only move will be classified as retract depending on the direction.
  161. * M218 - Set hotend offset (in mm): T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  162. * M220 - Set speed factor override percentage: S<factor in percent>
  163. * M221 - Set extrude factor override percentage: S<factor in percent>
  164. * M226 - Wait until the specified pin reaches the state required: P<pin number> S<pin state>
  165. * M240 - Trigger a camera to take a photograph
  166. * M250 - Set LCD contrast C<contrast value> (value 0..63)
  167. * M280 - Set servo position absolute. P: servo index, S: angle or microseconds
  168. * M300 - Play beep sound S<frequency Hz> P<duration ms>
  169. * M301 - Set PID parameters P I and D
  170. * M302 - Allow cold extrudes, or set the minimum extrude S<temperature>.
  171. * M303 - PID relay autotune S<temperature> sets the target temperature. (default target temperature = 150C)
  172. * M304 - Set bed PID parameters P I and D
  173. * M380 - Activate solenoid on active extruder
  174. * M381 - Disable all solenoids
  175. * M400 - Finish all moves
  176. * M401 - Lower Z probe if present
  177. * M402 - Raise Z probe if present
  178. * M404 - N<dia in mm> Enter the nominal filament width (3mm, 1.75mm ) or will display nominal filament width without parameters
  179. * M405 - Turn on Filament Sensor extrusion control. Optional D<delay in cm> to set delay in centimeters between sensor and extruder
  180. * M406 - Turn off Filament Sensor extrusion control
  181. * M407 - Display measured filament diameter
  182. * M410 - Quickstop. Abort all the planned moves
  183. * M420 - Enable/Disable Mesh Leveling (with current values) S1=enable S0=disable
  184. * M421 - Set a single Z coordinate in the Mesh Leveling grid. X<mm> Y<mm> Z<mm>
  185. * M428 - Set the home_offset logically based on the current_position
  186. * M500 - Store parameters in EEPROM
  187. * M501 - Read parameters from EEPROM (if you need reset them after you changed them temporarily).
  188. * M502 - Revert to the default "factory settings". You still need to store them in EEPROM afterwards if you want to.
  189. * M503 - Print the current settings (from memory not from EEPROM). Use S0 to leave off headings.
  190. * M540 - Use S[0|1] to enable or disable the stop SD card print on endstop hit (requires ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  191. * M600 - Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  192. * M665 - Set delta configurations: L<diagonal rod> R<delta radius> S<segments/s>
  193. * M666 - Set delta endstop adjustment
  194. * M605 - Set dual x-carriage movement mode: S<mode> [ X<duplication x-offset> R<duplication temp offset> ]
  195. * M907 - Set digital trimpot motor current using axis codes.
  196. * M908 - Control digital trimpot directly.
  197. * M350 - Set microstepping mode.
  198. * M351 - Toggle MS1 MS2 pins directly.
  199. *
  200. * ************ SCARA Specific - This can change to suit future G-code regulations
  201. * M360 - SCARA calibration: Move to cal-position ThetaA (0 deg calibration)
  202. * M361 - SCARA calibration: Move to cal-position ThetaB (90 deg calibration - steps per degree)
  203. * M362 - SCARA calibration: Move to cal-position PsiA (0 deg calibration)
  204. * M363 - SCARA calibration: Move to cal-position PsiB (90 deg calibration - steps per degree)
  205. * M364 - SCARA calibration: Move to cal-position PSIC (90 deg to Theta calibration position)
  206. * M365 - SCARA calibration: Scaling factor, X, Y, Z axis
  207. * ************* SCARA End ***************
  208. *
  209. * ************ Custom codes - This can change to suit future G-code regulations
  210. * M100 - Watch Free Memory (For Debugging Only)
  211. * M851 - Set Z probe's Z offset (mm above extruder -- The value will always be negative)
  212. * M928 - Start SD logging (M928 filename.g) - ended by M29
  213. * M999 - Restart after being stopped by error
  214. *
  215. * "T" Codes
  216. *
  217. * T0-T3 - Select a tool by index (usually an extruder) [ F<mm/min> ]
  218. *
  219. */
  220. #if ENABLED(M100_FREE_MEMORY_WATCHER)
  221. void gcode_M100();
  222. #endif
  223. #if ENABLED(SDSUPPORT)
  224. CardReader card;
  225. #endif
  226. bool Running = true;
  227. uint8_t marlin_debug_flags = DEBUG_INFO | DEBUG_ERRORS;
  228. static float feedrate = 1500.0, saved_feedrate;
  229. float current_position[NUM_AXIS] = { 0.0 };
  230. static float destination[NUM_AXIS] = { 0.0 };
  231. bool axis_known_position[3] = { false };
  232. bool axis_homed[3] = { false };
  233. static long gcode_N, gcode_LastN, Stopped_gcode_LastN = 0;
  234. static char* current_command, *current_command_args;
  235. static int cmd_queue_index_r = 0;
  236. static int cmd_queue_index_w = 0;
  237. static int commands_in_queue = 0;
  238. static char command_queue[BUFSIZE][MAX_CMD_SIZE];
  239. const float homing_feedrate[] = HOMING_FEEDRATE;
  240. bool axis_relative_modes[] = AXIS_RELATIVE_MODES;
  241. int feedrate_multiplier = 100; //100->1 200->2
  242. int saved_feedrate_multiplier;
  243. int extruder_multiplier[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(100);
  244. bool volumetric_enabled = false;
  245. float filament_size[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(DEFAULT_NOMINAL_FILAMENT_DIA);
  246. float volumetric_multiplier[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(1.0);
  247. float home_offset[3] = { 0 };
  248. float min_pos[3] = { X_MIN_POS, Y_MIN_POS, Z_MIN_POS };
  249. float max_pos[3] = { X_MAX_POS, Y_MAX_POS, Z_MAX_POS };
  250. uint8_t active_extruder = 0;
  251. int fanSpeed = 0;
  252. bool cancel_heatup = false;
  253. const char errormagic[] PROGMEM = "Error:";
  254. const char echomagic[] PROGMEM = "echo:";
  255. const char axis_codes[NUM_AXIS] = {'X', 'Y', 'Z', 'E'};
  256. static bool relative_mode = false; //Determines Absolute or Relative Coordinates
  257. static int serial_count = 0;
  258. static char* seen_pointer; ///< A pointer to find chars in the command string (X, Y, Z, E, etc.)
  259. const char* queued_commands_P = NULL; /* pointer to the current line in the active sequence of commands, or NULL when none */
  260. const int sensitive_pins[] = SENSITIVE_PINS; ///< Sensitive pin list for M42
  261. // Inactivity shutdown
  262. millis_t previous_cmd_ms = 0;
  263. static millis_t max_inactive_time = 0;
  264. static millis_t stepper_inactive_time = (DEFAULT_STEPPER_DEACTIVE_TIME) * 1000L;
  265. millis_t print_job_start_ms = 0; ///< Print job start time
  266. millis_t print_job_stop_ms = 0; ///< Print job stop time
  267. static uint8_t target_extruder;
  268. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  269. int xy_travel_speed = XY_TRAVEL_SPEED;
  270. float zprobe_zoffset = Z_PROBE_OFFSET_FROM_EXTRUDER;
  271. #endif
  272. #if ENABLED(Z_DUAL_ENDSTOPS) && DISABLED(DELTA)
  273. float z_endstop_adj = 0;
  274. #endif
  275. // Extruder offsets
  276. #if EXTRUDERS > 1
  277. #ifndef EXTRUDER_OFFSET_X
  278. #define EXTRUDER_OFFSET_X { 0 }
  279. #endif
  280. #ifndef EXTRUDER_OFFSET_Y
  281. #define EXTRUDER_OFFSET_Y { 0 }
  282. #endif
  283. float extruder_offset[][EXTRUDERS] = {
  284. EXTRUDER_OFFSET_X,
  285. EXTRUDER_OFFSET_Y
  286. #if ENABLED(DUAL_X_CARRIAGE)
  287. , { 0 } // supports offsets in XYZ plane
  288. #endif
  289. };
  290. #endif
  291. #if HAS_SERVO_ENDSTOPS
  292. const int servo_endstop_id[] = SERVO_ENDSTOP_IDS;
  293. const int servo_endstop_angle[][2] = SERVO_ENDSTOP_ANGLES;
  294. #endif
  295. #if ENABLED(BARICUDA)
  296. int ValvePressure = 0;
  297. int EtoPPressure = 0;
  298. #endif
  299. #if ENABLED(FWRETRACT)
  300. bool autoretract_enabled = false;
  301. bool retracted[EXTRUDERS] = { false };
  302. bool retracted_swap[EXTRUDERS] = { false };
  303. float retract_length = RETRACT_LENGTH;
  304. float retract_length_swap = RETRACT_LENGTH_SWAP;
  305. float retract_feedrate = RETRACT_FEEDRATE;
  306. float retract_zlift = RETRACT_ZLIFT;
  307. float retract_recover_length = RETRACT_RECOVER_LENGTH;
  308. float retract_recover_length_swap = RETRACT_RECOVER_LENGTH_SWAP;
  309. float retract_recover_feedrate = RETRACT_RECOVER_FEEDRATE;
  310. #endif // FWRETRACT
  311. #if ENABLED(ULTIPANEL) && HAS_POWER_SWITCH
  312. bool powersupply =
  313. #if ENABLED(PS_DEFAULT_OFF)
  314. false
  315. #else
  316. true
  317. #endif
  318. ;
  319. #endif
  320. #if ENABLED(DELTA)
  321. #define TOWER_1 X_AXIS
  322. #define TOWER_2 Y_AXIS
  323. #define TOWER_3 Z_AXIS
  324. float delta[3] = { 0 };
  325. #define SIN_60 0.8660254037844386
  326. #define COS_60 0.5
  327. float endstop_adj[3] = { 0 };
  328. // these are the default values, can be overriden with M665
  329. float delta_radius = DELTA_RADIUS;
  330. float delta_tower1_x = -SIN_60 * (delta_radius + DELTA_RADIUS_TRIM_TOWER_1); // front left tower
  331. float delta_tower1_y = -COS_60 * (delta_radius + DELTA_RADIUS_TRIM_TOWER_1);
  332. float delta_tower2_x = SIN_60 * (delta_radius + DELTA_RADIUS_TRIM_TOWER_2); // front right tower
  333. float delta_tower2_y = -COS_60 * (delta_radius + DELTA_RADIUS_TRIM_TOWER_2);
  334. float delta_tower3_x = 0; // back middle tower
  335. float delta_tower3_y = (delta_radius + DELTA_RADIUS_TRIM_TOWER_3);
  336. float delta_diagonal_rod = DELTA_DIAGONAL_ROD;
  337. float delta_diagonal_rod_trim_tower_1 = DELTA_DIAGONAL_ROD_TRIM_TOWER_1;
  338. float delta_diagonal_rod_trim_tower_2 = DELTA_DIAGONAL_ROD_TRIM_TOWER_2;
  339. float delta_diagonal_rod_trim_tower_3 = DELTA_DIAGONAL_ROD_TRIM_TOWER_3;
  340. float delta_diagonal_rod_2_tower_1 = sq(delta_diagonal_rod + delta_diagonal_rod_trim_tower_1);
  341. float delta_diagonal_rod_2_tower_2 = sq(delta_diagonal_rod + delta_diagonal_rod_trim_tower_2);
  342. float delta_diagonal_rod_2_tower_3 = sq(delta_diagonal_rod + delta_diagonal_rod_trim_tower_3);
  343. //float delta_diagonal_rod_2 = sq(delta_diagonal_rod);
  344. float delta_segments_per_second = DELTA_SEGMENTS_PER_SECOND;
  345. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  346. int delta_grid_spacing[2] = { 0, 0 };
  347. float bed_level[AUTO_BED_LEVELING_GRID_POINTS][AUTO_BED_LEVELING_GRID_POINTS];
  348. #endif
  349. #else
  350. static bool home_all_axis = true;
  351. #endif
  352. #if ENABLED(SCARA)
  353. float delta_segments_per_second = SCARA_SEGMENTS_PER_SECOND;
  354. static float delta[3] = { 0 };
  355. float axis_scaling[3] = { 1, 1, 1 }; // Build size scaling, default to 1
  356. #endif
  357. #if ENABLED(FILAMENT_SENSOR)
  358. //Variables for Filament Sensor input
  359. float filament_width_nominal = DEFAULT_NOMINAL_FILAMENT_DIA; //Set nominal filament width, can be changed with M404
  360. bool filament_sensor = false; //M405 turns on filament_sensor control, M406 turns it off
  361. float filament_width_meas = DEFAULT_MEASURED_FILAMENT_DIA; //Stores the measured filament diameter
  362. signed char measurement_delay[MAX_MEASUREMENT_DELAY + 1]; //ring buffer to delay measurement store extruder factor after subtracting 100
  363. int delay_index1 = 0; //index into ring buffer
  364. int delay_index2 = -1; //index into ring buffer - set to -1 on startup to indicate ring buffer needs to be initialized
  365. float delay_dist = 0; //delay distance counter
  366. int meas_delay_cm = MEASUREMENT_DELAY_CM; //distance delay setting
  367. #endif
  368. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  369. static bool filrunoutEnqueued = false;
  370. #endif
  371. static bool send_ok[BUFSIZE];
  372. #if HAS_SERVOS
  373. Servo servo[NUM_SERVOS];
  374. #endif
  375. #ifdef CHDK
  376. unsigned long chdkHigh = 0;
  377. boolean chdkActive = false;
  378. #endif
  379. #if ENABLED(PID_ADD_EXTRUSION_RATE)
  380. int lpq_len = 20;
  381. #endif
  382. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  383. // States for managing Marlin and host communication
  384. // Marlin sends messages if blocked or busy
  385. enum MarlinBusyState {
  386. NOT_BUSY, // Not in a handler
  387. IN_HANDLER, // Processing a GCode
  388. IN_PROCESS, // Known to be blocking command input (as in G29)
  389. PAUSED_FOR_USER, // Blocking pending any input
  390. PAUSED_FOR_INPUT // Blocking pending text input (concept)
  391. };
  392. static MarlinBusyState busy_state = NOT_BUSY;
  393. static millis_t next_busy_signal_ms = -1;
  394. #define KEEPALIVE_STATE(n) do{ busy_state = n; }while(0)
  395. #else
  396. #define host_keepalive() ;
  397. #define KEEPALIVE_STATE(n) ;
  398. #endif // HOST_KEEPALIVE_FEATURE
  399. //===========================================================================
  400. //================================ Functions ================================
  401. //===========================================================================
  402. void process_next_command();
  403. void plan_arc(float target[NUM_AXIS], float* offset, uint8_t clockwise);
  404. bool setTargetedHotend(int code);
  405. void serial_echopair_P(const char* s_P, int v) { serialprintPGM(s_P); SERIAL_ECHO(v); }
  406. void serial_echopair_P(const char* s_P, long v) { serialprintPGM(s_P); SERIAL_ECHO(v); }
  407. void serial_echopair_P(const char* s_P, float v) { serialprintPGM(s_P); SERIAL_ECHO(v); }
  408. void serial_echopair_P(const char* s_P, double v) { serialprintPGM(s_P); SERIAL_ECHO(v); }
  409. void serial_echopair_P(const char* s_P, unsigned long v) { serialprintPGM(s_P); SERIAL_ECHO(v); }
  410. #if ENABLED(PREVENT_DANGEROUS_EXTRUDE)
  411. float extrude_min_temp = EXTRUDE_MINTEMP;
  412. #endif
  413. #if ENABLED(SDSUPPORT)
  414. #include "SdFatUtil.h"
  415. int freeMemory() { return SdFatUtil::FreeRam(); }
  416. #else
  417. extern "C" {
  418. extern unsigned int __bss_end;
  419. extern unsigned int __heap_start;
  420. extern void* __brkval;
  421. int freeMemory() {
  422. int free_memory;
  423. if ((int)__brkval == 0)
  424. free_memory = ((int)&free_memory) - ((int)&__bss_end);
  425. else
  426. free_memory = ((int)&free_memory) - ((int)__brkval);
  427. return free_memory;
  428. }
  429. }
  430. #endif //!SDSUPPORT
  431. /**
  432. * Inject the next "immediate" command, when possible.
  433. * Return true if any immediate commands remain to inject.
  434. */
  435. static bool drain_queued_commands_P() {
  436. if (queued_commands_P != NULL) {
  437. // Get the next gcode to run
  438. size_t i = 0;
  439. char c;
  440. while ((c = queued_commands_P[i++]) && c != '\n') { };
  441. if (i > 1) {
  442. char cmd[i];
  443. strncpy_P(cmd, queued_commands_P, i - 1);
  444. cmd[i - 1] = '\0';
  445. if (enqueue_and_echo_command(cmd)) { // buffer was not full (else we will retry later)
  446. if (c)
  447. queued_commands_P += i; // move to next command
  448. else
  449. queued_commands_P = NULL; // no more commands in the sequence
  450. }
  451. }
  452. }
  453. return (queued_commands_P != NULL); // any more left to add?
  454. }
  455. /**
  456. * Record one or many commands to run from program memory.
  457. * Aborts the current queue, if any.
  458. * Note: drain_queued_commands_P() must be called repeatedly to drain the commands afterwards
  459. */
  460. void enqueue_and_echo_commands_P(const char* pgcode) {
  461. queued_commands_P = pgcode;
  462. drain_queued_commands_P(); // first command executed asap (when possible)
  463. }
  464. /**
  465. * Once a new command is in the ring buffer, call this to commit it
  466. */
  467. inline void _commit_command(bool say_ok) {
  468. send_ok[cmd_queue_index_w] = say_ok;
  469. cmd_queue_index_w = (cmd_queue_index_w + 1) % BUFSIZE;
  470. commands_in_queue++;
  471. }
  472. /**
  473. * Copy a command directly into the main command buffer, from RAM.
  474. * Returns true if successfully adds the command
  475. */
  476. inline bool _enqueuecommand(const char* cmd, bool say_ok=false) {
  477. if (*cmd == ';' || commands_in_queue >= BUFSIZE) return false;
  478. strcpy(command_queue[cmd_queue_index_w], cmd);
  479. _commit_command(say_ok);
  480. return true;
  481. }
  482. /**
  483. * Enqueue with Serial Echo
  484. */
  485. bool enqueue_and_echo_command(const char* cmd, bool say_ok/*=false*/) {
  486. if (_enqueuecommand(cmd, say_ok)) {
  487. SERIAL_ECHO_START;
  488. SERIAL_ECHOPGM(MSG_Enqueueing);
  489. SERIAL_ECHO(cmd);
  490. SERIAL_ECHOLNPGM("\"");
  491. return true;
  492. }
  493. return false;
  494. }
  495. void setup_killpin() {
  496. #if HAS_KILL
  497. SET_INPUT(KILL_PIN);
  498. WRITE(KILL_PIN, HIGH);
  499. #endif
  500. }
  501. void setup_filrunoutpin() {
  502. #if HAS_FILRUNOUT
  503. pinMode(FILRUNOUT_PIN, INPUT);
  504. #if ENABLED(ENDSTOPPULLUP_FIL_RUNOUT)
  505. WRITE(FILRUNOUT_PIN, HIGH);
  506. #endif
  507. #endif
  508. }
  509. // Set home pin
  510. void setup_homepin(void) {
  511. #if HAS_HOME
  512. SET_INPUT(HOME_PIN);
  513. WRITE(HOME_PIN, HIGH);
  514. #endif
  515. }
  516. void setup_photpin() {
  517. #if HAS_PHOTOGRAPH
  518. OUT_WRITE(PHOTOGRAPH_PIN, LOW);
  519. #endif
  520. }
  521. void setup_powerhold() {
  522. #if HAS_SUICIDE
  523. OUT_WRITE(SUICIDE_PIN, HIGH);
  524. #endif
  525. #if HAS_POWER_SWITCH
  526. #if ENABLED(PS_DEFAULT_OFF)
  527. OUT_WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  528. #else
  529. OUT_WRITE(PS_ON_PIN, PS_ON_AWAKE);
  530. #endif
  531. #endif
  532. }
  533. void suicide() {
  534. #if HAS_SUICIDE
  535. OUT_WRITE(SUICIDE_PIN, LOW);
  536. #endif
  537. }
  538. void servo_init() {
  539. #if NUM_SERVOS >= 1 && HAS_SERVO_0
  540. servo[0].attach(SERVO0_PIN);
  541. servo[0].detach(); // Just set up the pin. We don't have a position yet. Don't move to a random position.
  542. #endif
  543. #if NUM_SERVOS >= 2 && HAS_SERVO_1
  544. servo[1].attach(SERVO1_PIN);
  545. servo[1].detach();
  546. #endif
  547. #if NUM_SERVOS >= 3 && HAS_SERVO_2
  548. servo[2].attach(SERVO2_PIN);
  549. servo[2].detach();
  550. #endif
  551. #if NUM_SERVOS >= 4 && HAS_SERVO_3
  552. servo[3].attach(SERVO3_PIN);
  553. servo[3].detach();
  554. #endif
  555. // Set position of Servo Endstops that are defined
  556. #if HAS_SERVO_ENDSTOPS
  557. for (int i = 0; i < 3; i++)
  558. if (servo_endstop_id[i] >= 0)
  559. servo[servo_endstop_id[i]].move(servo_endstop_angle[i][1]);
  560. #endif
  561. }
  562. /**
  563. * Stepper Reset (RigidBoard, et.al.)
  564. */
  565. #if HAS_STEPPER_RESET
  566. void disableStepperDrivers() {
  567. pinMode(STEPPER_RESET_PIN, OUTPUT);
  568. digitalWrite(STEPPER_RESET_PIN, LOW); // drive it down to hold in reset motor driver chips
  569. }
  570. void enableStepperDrivers() { pinMode(STEPPER_RESET_PIN, INPUT); } // set to input, which allows it to be pulled high by pullups
  571. #endif
  572. /**
  573. * Marlin entry-point: Set up before the program loop
  574. * - Set up the kill pin, filament runout, power hold
  575. * - Start the serial port
  576. * - Print startup messages and diagnostics
  577. * - Get EEPROM or default settings
  578. * - Initialize managers for:
  579. * • temperature
  580. * • planner
  581. * • watchdog
  582. * • stepper
  583. * • photo pin
  584. * • servos
  585. * • LCD controller
  586. * • Digipot I2C
  587. * • Z probe sled
  588. * • status LEDs
  589. */
  590. void setup() {
  591. #ifdef DISABLE_JTAG
  592. // Disable JTAG on AT90USB chips to free up pins for IO
  593. MCUCR = 0x80;
  594. MCUCR = 0x80;
  595. #endif
  596. setup_killpin();
  597. setup_filrunoutpin();
  598. setup_powerhold();
  599. #if HAS_STEPPER_RESET
  600. disableStepperDrivers();
  601. #endif
  602. MYSERIAL.begin(BAUDRATE);
  603. SERIAL_PROTOCOLLNPGM("start");
  604. SERIAL_ECHO_START;
  605. // Check startup - does nothing if bootloader sets MCUSR to 0
  606. byte mcu = MCUSR;
  607. if (mcu & 1) SERIAL_ECHOLNPGM(MSG_POWERUP);
  608. if (mcu & 2) SERIAL_ECHOLNPGM(MSG_EXTERNAL_RESET);
  609. if (mcu & 4) SERIAL_ECHOLNPGM(MSG_BROWNOUT_RESET);
  610. if (mcu & 8) SERIAL_ECHOLNPGM(MSG_WATCHDOG_RESET);
  611. if (mcu & 32) SERIAL_ECHOLNPGM(MSG_SOFTWARE_RESET);
  612. MCUSR = 0;
  613. SERIAL_ECHOPGM(MSG_MARLIN);
  614. SERIAL_ECHOLNPGM(" " SHORT_BUILD_VERSION);
  615. #ifdef STRING_DISTRIBUTION_DATE
  616. #ifdef STRING_CONFIG_H_AUTHOR
  617. SERIAL_ECHO_START;
  618. SERIAL_ECHOPGM(MSG_CONFIGURATION_VER);
  619. SERIAL_ECHOPGM(STRING_DISTRIBUTION_DATE);
  620. SERIAL_ECHOPGM(MSG_AUTHOR);
  621. SERIAL_ECHOLNPGM(STRING_CONFIG_H_AUTHOR);
  622. SERIAL_ECHOPGM("Compiled: ");
  623. SERIAL_ECHOLNPGM(__DATE__);
  624. #endif // STRING_CONFIG_H_AUTHOR
  625. #endif // STRING_DISTRIBUTION_DATE
  626. SERIAL_ECHO_START;
  627. SERIAL_ECHOPGM(MSG_FREE_MEMORY);
  628. SERIAL_ECHO(freeMemory());
  629. SERIAL_ECHOPGM(MSG_PLANNER_BUFFER_BYTES);
  630. SERIAL_ECHOLN((int)sizeof(block_t)*BLOCK_BUFFER_SIZE);
  631. // Send "ok" after commands by default
  632. for (int8_t i = 0; i < BUFSIZE; i++) send_ok[i] = true;
  633. // loads data from EEPROM if available else uses defaults (and resets step acceleration rate)
  634. Config_RetrieveSettings();
  635. lcd_init();
  636. tp_init(); // Initialize temperature loop
  637. plan_init(); // Initialize planner;
  638. #if ENABLED(USE_WATCHDOG)
  639. watchdog_init();
  640. #endif
  641. st_init(); // Initialize stepper, this enables interrupts!
  642. setup_photpin();
  643. servo_init();
  644. #if HAS_CONTROLLERFAN
  645. SET_OUTPUT(CONTROLLERFAN_PIN); //Set pin used for driver cooling fan
  646. #endif
  647. #if HAS_STEPPER_RESET
  648. enableStepperDrivers();
  649. #endif
  650. #if ENABLED(DIGIPOT_I2C)
  651. digipot_i2c_init();
  652. #endif
  653. #if ENABLED(Z_PROBE_SLED)
  654. pinMode(SLED_PIN, OUTPUT);
  655. digitalWrite(SLED_PIN, LOW); // turn it off
  656. #endif // Z_PROBE_SLED
  657. setup_homepin();
  658. #ifdef STAT_LED_RED
  659. pinMode(STAT_LED_RED, OUTPUT);
  660. digitalWrite(STAT_LED_RED, LOW); // turn it off
  661. #endif
  662. #ifdef STAT_LED_BLUE
  663. pinMode(STAT_LED_BLUE, OUTPUT);
  664. digitalWrite(STAT_LED_BLUE, LOW); // turn it off
  665. #endif
  666. }
  667. /**
  668. * The main Marlin program loop
  669. *
  670. * - Save or log commands to SD
  671. * - Process available commands (if not saving)
  672. * - Call heater manager
  673. * - Call inactivity manager
  674. * - Call endstop manager
  675. * - Call LCD update
  676. */
  677. void loop() {
  678. if (commands_in_queue < BUFSIZE) get_command();
  679. #if ENABLED(SDSUPPORT)
  680. card.checkautostart(false);
  681. #endif
  682. if (commands_in_queue) {
  683. #if ENABLED(SDSUPPORT)
  684. if (card.saving) {
  685. char* command = command_queue[cmd_queue_index_r];
  686. if (strstr_P(command, PSTR("M29"))) {
  687. // M29 closes the file
  688. card.closefile();
  689. SERIAL_PROTOCOLLNPGM(MSG_FILE_SAVED);
  690. ok_to_send();
  691. }
  692. else {
  693. // Write the string from the read buffer to SD
  694. card.write_command(command);
  695. if (card.logging)
  696. process_next_command(); // The card is saving because it's logging
  697. else
  698. ok_to_send();
  699. }
  700. }
  701. else
  702. process_next_command();
  703. #else
  704. process_next_command();
  705. #endif // SDSUPPORT
  706. commands_in_queue--;
  707. cmd_queue_index_r = (cmd_queue_index_r + 1) % BUFSIZE;
  708. }
  709. checkHitEndstops();
  710. idle();
  711. }
  712. void gcode_line_error(const char* err, bool doFlush = true) {
  713. SERIAL_ERROR_START;
  714. serialprintPGM(err);
  715. SERIAL_ERRORLN(gcode_LastN);
  716. //Serial.println(gcode_N);
  717. if (doFlush) FlushSerialRequestResend();
  718. serial_count = 0;
  719. }
  720. /**
  721. * Add to the circular command queue the next command from:
  722. * - The command-injection queue (queued_commands_P)
  723. * - The active serial input (usually USB)
  724. * - The SD card file being actively printed
  725. */
  726. void get_command() {
  727. static char serial_line_buffer[MAX_CMD_SIZE];
  728. static boolean serial_comment_mode = false;
  729. if (drain_queued_commands_P()) return; // priority is given to non-serial commands
  730. #if defined(NO_TIMEOUTS) && NO_TIMEOUTS > 0
  731. static millis_t last_command_time = 0;
  732. millis_t ms = millis();
  733. if (!MYSERIAL.available() && commands_in_queue == 0 && ms - last_command_time > NO_TIMEOUTS) {
  734. SERIAL_ECHOLNPGM(MSG_WAIT);
  735. last_command_time = ms;
  736. }
  737. #endif
  738. //
  739. // Loop while serial characters are incoming and the queue is not full
  740. //
  741. while (commands_in_queue < BUFSIZE && MYSERIAL.available() > 0) {
  742. char serial_char = MYSERIAL.read();
  743. //
  744. // If the character ends the line
  745. //
  746. if (serial_char == '\n' || serial_char == '\r') {
  747. serial_comment_mode = false; // end of line == end of comment
  748. if (!serial_count) return; // empty lines just exit
  749. serial_line_buffer[serial_count] = 0; // terminate string
  750. serial_count = 0; //reset buffer
  751. char* command = serial_line_buffer;
  752. while (*command == ' ') command++; // skip any leading spaces
  753. char* npos = (*command == 'N') ? command : NULL; // Require the N parameter to start the line
  754. char* apos = strchr(command, '*');
  755. if (npos) {
  756. boolean M110 = strstr_P(command, PSTR("M110")) != NULL;
  757. if (M110) {
  758. char* n2pos = strchr(command + 4, 'N');
  759. if (n2pos) npos = n2pos;
  760. }
  761. gcode_N = strtol(npos + 1, NULL, 10);
  762. if (gcode_N != gcode_LastN + 1 && !M110) {
  763. gcode_line_error(PSTR(MSG_ERR_LINE_NO));
  764. return;
  765. }
  766. if (apos) {
  767. byte checksum = 0, count = 0;
  768. while (command[count] != '*') checksum ^= command[count++];
  769. if (strtol(apos + 1, NULL, 10) != checksum) {
  770. gcode_line_error(PSTR(MSG_ERR_CHECKSUM_MISMATCH));
  771. return;
  772. }
  773. // if no errors, continue parsing
  774. }
  775. else {
  776. gcode_line_error(PSTR(MSG_ERR_NO_CHECKSUM));
  777. return;
  778. }
  779. gcode_LastN = gcode_N;
  780. // if no errors, continue parsing
  781. }
  782. else if (apos) { // No '*' without 'N'
  783. gcode_line_error(PSTR(MSG_ERR_NO_LINENUMBER_WITH_CHECKSUM), false);
  784. return;
  785. }
  786. // Movement commands alert when stopped
  787. if (IsStopped()) {
  788. char* gpos = strchr(command, 'G');
  789. if (gpos) {
  790. int codenum = strtol(gpos + 1, NULL, 10);
  791. switch (codenum) {
  792. case 0:
  793. case 1:
  794. case 2:
  795. case 3:
  796. SERIAL_ERRORLNPGM(MSG_ERR_STOPPED);
  797. LCD_MESSAGEPGM(MSG_STOPPED);
  798. break;
  799. }
  800. }
  801. }
  802. // If command was e-stop process now
  803. if (strcmp(command, "M112") == 0) kill(PSTR(MSG_KILLED));
  804. #if defined(NO_TIMEOUTS) && NO_TIMEOUTS > 0
  805. last_command_time = ms;
  806. #endif
  807. // Add the command to the queue
  808. _enqueuecommand(serial_line_buffer, true);
  809. }
  810. else if (serial_count >= MAX_CMD_SIZE - 1) {
  811. // Keep fetching, but ignore normal characters beyond the max length
  812. // The command will be injected when EOL is reached
  813. }
  814. else if (serial_char == '\\') { // Handle escapes
  815. if (MYSERIAL.available() > 0) {
  816. // if we have one more character, copy it over
  817. serial_char = MYSERIAL.read();
  818. serial_line_buffer[serial_count++] = serial_char;
  819. }
  820. // otherwise do nothing
  821. }
  822. else { // it's not a newline, carriage return or escape char
  823. if (serial_char == ';') serial_comment_mode = true;
  824. if (!serial_comment_mode) serial_line_buffer[serial_count++] = serial_char;
  825. }
  826. } // queue has space, serial has data
  827. #if ENABLED(SDSUPPORT)
  828. static bool stop_buffering = false,
  829. sd_comment_mode = false;
  830. if (!card.sdprinting) return;
  831. // '#' stops reading from SD to the buffer prematurely, so procedural macro calls are possible
  832. // if it occurs, stop_buffering is triggered and the buffer is run dry.
  833. // this character _can_ occur in serial com, due to checksums. however, no checksums are used in SD printing
  834. if (commands_in_queue == 0) stop_buffering = false;
  835. uint16_t sd_count = 0;
  836. bool card_eof = card.eof();
  837. while (commands_in_queue < BUFSIZE && !card_eof && !stop_buffering) {
  838. int16_t n = card.get();
  839. char sd_char = (char)n;
  840. card_eof = card.eof();
  841. if (card_eof || n == -1
  842. || sd_char == '\n' || sd_char == '\r'
  843. || ((sd_char == '#' || sd_char == ':') && !sd_comment_mode)
  844. ) {
  845. if (card_eof) {
  846. SERIAL_PROTOCOLLNPGM(MSG_FILE_PRINTED);
  847. print_job_stop_ms = millis();
  848. char time[30];
  849. millis_t t = (print_job_stop_ms - print_job_start_ms) / 1000;
  850. int hours = t / 60 / 60, minutes = (t / 60) % 60;
  851. sprintf_P(time, PSTR("%i " MSG_END_HOUR " %i " MSG_END_MINUTE), hours, minutes);
  852. SERIAL_ECHO_START;
  853. SERIAL_ECHOLN(time);
  854. lcd_setstatus(time, true);
  855. card.printingHasFinished();
  856. card.checkautostart(true);
  857. }
  858. if (sd_char == '#') stop_buffering = true;
  859. sd_comment_mode = false; //for new command
  860. if (!sd_count) continue; //skip empty lines
  861. command_queue[cmd_queue_index_w][sd_count] = '\0'; //terminate string
  862. sd_count = 0; //clear buffer
  863. _commit_command(false);
  864. }
  865. else if (sd_count >= MAX_CMD_SIZE - 1) {
  866. // Keep fetching, but ignore normal characters beyond the max length
  867. // The command will be injected when EOL is reached
  868. }
  869. else {
  870. if (sd_char == ';') sd_comment_mode = true;
  871. if (!sd_comment_mode) command_queue[cmd_queue_index_w][sd_count++] = sd_char;
  872. }
  873. }
  874. #endif // SDSUPPORT
  875. }
  876. bool code_has_value() {
  877. int i = 1;
  878. char c = seen_pointer[i];
  879. while (c == ' ') c = seen_pointer[++i];
  880. if (c == '-' || c == '+') c = seen_pointer[++i];
  881. if (c == '.') c = seen_pointer[++i];
  882. return (c >= '0' && c <= '9');
  883. }
  884. float code_value() {
  885. float ret;
  886. char* e = strchr(seen_pointer, 'E');
  887. if (e) {
  888. *e = 0;
  889. ret = strtod(seen_pointer + 1, NULL);
  890. *e = 'E';
  891. }
  892. else
  893. ret = strtod(seen_pointer + 1, NULL);
  894. return ret;
  895. }
  896. long code_value_long() { return strtol(seen_pointer + 1, NULL, 10); }
  897. int16_t code_value_short() { return (int16_t)strtol(seen_pointer + 1, NULL, 10); }
  898. bool code_seen(char code) {
  899. seen_pointer = strchr(current_command_args, code);
  900. return (seen_pointer != NULL); // Return TRUE if the code-letter was found
  901. }
  902. #define DEFINE_PGM_READ_ANY(type, reader) \
  903. static inline type pgm_read_any(const type *p) \
  904. { return pgm_read_##reader##_near(p); }
  905. DEFINE_PGM_READ_ANY(float, float);
  906. DEFINE_PGM_READ_ANY(signed char, byte);
  907. #define XYZ_CONSTS_FROM_CONFIG(type, array, CONFIG) \
  908. static const PROGMEM type array##_P[3] = \
  909. { X_##CONFIG, Y_##CONFIG, Z_##CONFIG }; \
  910. static inline type array(int axis) \
  911. { return pgm_read_any(&array##_P[axis]); }
  912. XYZ_CONSTS_FROM_CONFIG(float, base_min_pos, MIN_POS);
  913. XYZ_CONSTS_FROM_CONFIG(float, base_max_pos, MAX_POS);
  914. XYZ_CONSTS_FROM_CONFIG(float, base_home_pos, HOME_POS);
  915. XYZ_CONSTS_FROM_CONFIG(float, max_length, MAX_LENGTH);
  916. XYZ_CONSTS_FROM_CONFIG(float, home_bump_mm, HOME_BUMP_MM);
  917. XYZ_CONSTS_FROM_CONFIG(signed char, home_dir, HOME_DIR);
  918. #if ENABLED(DUAL_X_CARRIAGE)
  919. #define DXC_FULL_CONTROL_MODE 0
  920. #define DXC_AUTO_PARK_MODE 1
  921. #define DXC_DUPLICATION_MODE 2
  922. static int dual_x_carriage_mode = DEFAULT_DUAL_X_CARRIAGE_MODE;
  923. static float x_home_pos(int extruder) {
  924. if (extruder == 0)
  925. return base_home_pos(X_AXIS) + home_offset[X_AXIS];
  926. else
  927. // In dual carriage mode the extruder offset provides an override of the
  928. // second X-carriage offset when homed - otherwise X2_HOME_POS is used.
  929. // This allow soft recalibration of the second extruder offset position without firmware reflash
  930. // (through the M218 command).
  931. return (extruder_offset[X_AXIS][1] > 0) ? extruder_offset[X_AXIS][1] : X2_HOME_POS;
  932. }
  933. static int x_home_dir(int extruder) {
  934. return (extruder == 0) ? X_HOME_DIR : X2_HOME_DIR;
  935. }
  936. static float inactive_extruder_x_pos = X2_MAX_POS; // used in mode 0 & 1
  937. static bool active_extruder_parked = false; // used in mode 1 & 2
  938. static float raised_parked_position[NUM_AXIS]; // used in mode 1
  939. static millis_t delayed_move_time = 0; // used in mode 1
  940. static float duplicate_extruder_x_offset = DEFAULT_DUPLICATION_X_OFFSET; // used in mode 2
  941. static float duplicate_extruder_temp_offset = 0; // used in mode 2
  942. bool extruder_duplication_enabled = false; // used in mode 2
  943. #endif //DUAL_X_CARRIAGE
  944. #if ENABLED(DEBUG_LEVELING_FEATURE)
  945. void print_xyz(const char* prefix, const float x, const float y, const float z) {
  946. SERIAL_ECHO(prefix);
  947. SERIAL_ECHOPAIR(": (", x);
  948. SERIAL_ECHOPAIR(", ", y);
  949. SERIAL_ECHOPAIR(", ", z);
  950. SERIAL_ECHOLNPGM(")");
  951. }
  952. void print_xyz(const char* prefix, const float xyz[]) {
  953. print_xyz(prefix, xyz[X_AXIS], xyz[Y_AXIS], xyz[Z_AXIS]);
  954. }
  955. #endif
  956. static void set_axis_is_at_home(AxisEnum axis) {
  957. #if ENABLED(DUAL_X_CARRIAGE)
  958. if (axis == X_AXIS) {
  959. if (active_extruder != 0) {
  960. current_position[X_AXIS] = x_home_pos(active_extruder);
  961. min_pos[X_AXIS] = X2_MIN_POS;
  962. max_pos[X_AXIS] = max(extruder_offset[X_AXIS][1], X2_MAX_POS);
  963. return;
  964. }
  965. else if (dual_x_carriage_mode == DXC_DUPLICATION_MODE) {
  966. float xoff = home_offset[X_AXIS];
  967. current_position[X_AXIS] = base_home_pos(X_AXIS) + xoff;
  968. min_pos[X_AXIS] = base_min_pos(X_AXIS) + xoff;
  969. max_pos[X_AXIS] = min(base_max_pos(X_AXIS) + xoff, max(extruder_offset[X_AXIS][1], X2_MAX_POS) - duplicate_extruder_x_offset);
  970. return;
  971. }
  972. }
  973. #endif
  974. #if ENABLED(SCARA)
  975. if (axis == X_AXIS || axis == Y_AXIS) {
  976. float homeposition[3];
  977. for (int i = 0; i < 3; i++) homeposition[i] = base_home_pos(i);
  978. // SERIAL_ECHOPGM("homeposition[x]= "); SERIAL_ECHO(homeposition[0]);
  979. // SERIAL_ECHOPGM("homeposition[y]= "); SERIAL_ECHOLN(homeposition[1]);
  980. // Works out real Homeposition angles using inverse kinematics,
  981. // and calculates homing offset using forward kinematics
  982. calculate_delta(homeposition);
  983. // SERIAL_ECHOPGM("base Theta= "); SERIAL_ECHO(delta[X_AXIS]);
  984. // SERIAL_ECHOPGM(" base Psi+Theta="); SERIAL_ECHOLN(delta[Y_AXIS]);
  985. for (int i = 0; i < 2; i++) delta[i] -= home_offset[i];
  986. // SERIAL_ECHOPGM("addhome X="); SERIAL_ECHO(home_offset[X_AXIS]);
  987. // SERIAL_ECHOPGM(" addhome Y="); SERIAL_ECHO(home_offset[Y_AXIS]);
  988. // SERIAL_ECHOPGM(" addhome Theta="); SERIAL_ECHO(delta[X_AXIS]);
  989. // SERIAL_ECHOPGM(" addhome Psi+Theta="); SERIAL_ECHOLN(delta[Y_AXIS]);
  990. calculate_SCARA_forward_Transform(delta);
  991. // SERIAL_ECHOPGM("Delta X="); SERIAL_ECHO(delta[X_AXIS]);
  992. // SERIAL_ECHOPGM(" Delta Y="); SERIAL_ECHOLN(delta[Y_AXIS]);
  993. current_position[axis] = delta[axis];
  994. // SCARA home positions are based on configuration since the actual limits are determined by the
  995. // inverse kinematic transform.
  996. min_pos[axis] = base_min_pos(axis); // + (delta[axis] - base_home_pos(axis));
  997. max_pos[axis] = base_max_pos(axis); // + (delta[axis] - base_home_pos(axis));
  998. }
  999. else
  1000. #endif
  1001. {
  1002. current_position[axis] = base_home_pos(axis) + home_offset[axis];
  1003. min_pos[axis] = base_min_pos(axis) + home_offset[axis];
  1004. max_pos[axis] = base_max_pos(axis) + home_offset[axis];
  1005. #if ENABLED(AUTO_BED_LEVELING_FEATURE) && Z_HOME_DIR < 0
  1006. if (axis == Z_AXIS) current_position[Z_AXIS] -= zprobe_zoffset;
  1007. #endif
  1008. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1009. if (marlin_debug_flags & DEBUG_LEVELING) {
  1010. SERIAL_ECHOPAIR("set_axis_is_at_home ", (unsigned long)axis);
  1011. SERIAL_ECHOPAIR(" > (home_offset[axis]==", home_offset[axis]);
  1012. print_xyz(") > current_position", current_position);
  1013. }
  1014. #endif
  1015. }
  1016. }
  1017. /**
  1018. * Some planner shorthand inline functions
  1019. */
  1020. inline void set_homing_bump_feedrate(AxisEnum axis) {
  1021. const int homing_bump_divisor[] = HOMING_BUMP_DIVISOR;
  1022. int hbd = homing_bump_divisor[axis];
  1023. if (hbd < 1) {
  1024. hbd = 10;
  1025. SERIAL_ECHO_START;
  1026. SERIAL_ECHOLNPGM("Warning: Homing Bump Divisor < 1");
  1027. }
  1028. feedrate = homing_feedrate[axis] / hbd;
  1029. }
  1030. inline void line_to_current_position() {
  1031. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], feedrate / 60, active_extruder);
  1032. }
  1033. inline void line_to_z(float zPosition) {
  1034. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate / 60, active_extruder);
  1035. }
  1036. inline void line_to_destination(float mm_m) {
  1037. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], mm_m / 60, active_extruder);
  1038. }
  1039. inline void line_to_destination() {
  1040. line_to_destination(feedrate);
  1041. }
  1042. inline void sync_plan_position() {
  1043. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1044. }
  1045. #if ENABLED(DELTA) || ENABLED(SCARA)
  1046. inline void sync_plan_position_delta() {
  1047. calculate_delta(current_position);
  1048. plan_set_position(delta[X_AXIS], delta[Y_AXIS], delta[Z_AXIS], current_position[E_AXIS]);
  1049. }
  1050. #endif
  1051. inline void set_current_to_destination() { memcpy(current_position, destination, sizeof(current_position)); }
  1052. inline void set_destination_to_current() { memcpy(destination, current_position, sizeof(destination)); }
  1053. static void setup_for_endstop_move() {
  1054. saved_feedrate = feedrate;
  1055. saved_feedrate_multiplier = feedrate_multiplier;
  1056. feedrate_multiplier = 100;
  1057. refresh_cmd_timeout();
  1058. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1059. if (marlin_debug_flags & DEBUG_LEVELING) {
  1060. SERIAL_ECHOLNPGM("setup_for_endstop_move > enable_endstops(true)");
  1061. }
  1062. #endif
  1063. enable_endstops(true);
  1064. }
  1065. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  1066. #if ENABLED(DELTA)
  1067. /**
  1068. * Calculate delta, start a line, and set current_position to destination
  1069. */
  1070. void prepare_move_raw() {
  1071. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1072. if (marlin_debug_flags & DEBUG_LEVELING) {
  1073. print_xyz("prepare_move_raw > destination", destination);
  1074. }
  1075. #endif
  1076. refresh_cmd_timeout();
  1077. calculate_delta(destination);
  1078. plan_buffer_line(delta[X_AXIS], delta[Y_AXIS], delta[Z_AXIS], destination[E_AXIS], (feedrate / 60) * (feedrate_multiplier / 100.0), active_extruder);
  1079. set_current_to_destination();
  1080. }
  1081. #endif
  1082. #if ENABLED(AUTO_BED_LEVELING_GRID)
  1083. #if DISABLED(DELTA)
  1084. static void set_bed_level_equation_lsq(double* plane_equation_coefficients) {
  1085. vector_3 planeNormal = vector_3(-plane_equation_coefficients[0], -plane_equation_coefficients[1], 1);
  1086. planeNormal.debug("planeNormal");
  1087. plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1088. //bedLevel.debug("bedLevel");
  1089. //plan_bed_level_matrix.debug("bed level before");
  1090. //vector_3 uncorrected_position = plan_get_position_mm();
  1091. //uncorrected_position.debug("position before");
  1092. vector_3 corrected_position = plan_get_position();
  1093. //corrected_position.debug("position after");
  1094. current_position[X_AXIS] = corrected_position.x;
  1095. current_position[Y_AXIS] = corrected_position.y;
  1096. current_position[Z_AXIS] = corrected_position.z;
  1097. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1098. if (marlin_debug_flags & DEBUG_LEVELING) {
  1099. print_xyz("set_bed_level_equation_lsq > current_position", current_position);
  1100. }
  1101. #endif
  1102. sync_plan_position();
  1103. }
  1104. #endif // !DELTA
  1105. #else // !AUTO_BED_LEVELING_GRID
  1106. static void set_bed_level_equation_3pts(float z_at_pt_1, float z_at_pt_2, float z_at_pt_3) {
  1107. plan_bed_level_matrix.set_to_identity();
  1108. vector_3 pt1 = vector_3(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, z_at_pt_1);
  1109. vector_3 pt2 = vector_3(ABL_PROBE_PT_2_X, ABL_PROBE_PT_2_Y, z_at_pt_2);
  1110. vector_3 pt3 = vector_3(ABL_PROBE_PT_3_X, ABL_PROBE_PT_3_Y, z_at_pt_3);
  1111. vector_3 planeNormal = vector_3::cross(pt1 - pt2, pt3 - pt2).get_normal();
  1112. if (planeNormal.z < 0) {
  1113. planeNormal.x = -planeNormal.x;
  1114. planeNormal.y = -planeNormal.y;
  1115. planeNormal.z = -planeNormal.z;
  1116. }
  1117. plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1118. vector_3 corrected_position = plan_get_position();
  1119. current_position[X_AXIS] = corrected_position.x;
  1120. current_position[Y_AXIS] = corrected_position.y;
  1121. current_position[Z_AXIS] = corrected_position.z;
  1122. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1123. if (marlin_debug_flags & DEBUG_LEVELING) {
  1124. print_xyz("set_bed_level_equation_3pts > current_position", current_position);
  1125. }
  1126. #endif
  1127. sync_plan_position();
  1128. }
  1129. #endif // !AUTO_BED_LEVELING_GRID
  1130. static void run_z_probe() {
  1131. refresh_cmd_timeout(); // to prevent stepper_inactive_time from running out and EXTRUDER_RUNOUT_PREVENT from extruding
  1132. #if ENABLED(DELTA)
  1133. float start_z = current_position[Z_AXIS];
  1134. long start_steps = st_get_position(Z_AXIS);
  1135. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1136. if (marlin_debug_flags & DEBUG_LEVELING) {
  1137. SERIAL_ECHOLNPGM("run_z_probe (DELTA) 1");
  1138. }
  1139. #endif
  1140. // move down slowly until you find the bed
  1141. feedrate = homing_feedrate[Z_AXIS] / 4;
  1142. destination[Z_AXIS] = -10;
  1143. prepare_move_raw(); // this will also set_current_to_destination
  1144. st_synchronize();
  1145. endstops_hit_on_purpose(); // clear endstop hit flags
  1146. // we have to let the planner know where we are right now as it is not where we said to go.
  1147. long stop_steps = st_get_position(Z_AXIS);
  1148. float mm = start_z - float(start_steps - stop_steps) / axis_steps_per_unit[Z_AXIS];
  1149. current_position[Z_AXIS] = mm;
  1150. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1151. if (marlin_debug_flags & DEBUG_LEVELING) {
  1152. print_xyz("run_z_probe (DELTA) 2 > current_position", current_position);
  1153. }
  1154. #endif
  1155. sync_plan_position_delta();
  1156. #else // !DELTA
  1157. plan_bed_level_matrix.set_to_identity();
  1158. feedrate = homing_feedrate[Z_AXIS];
  1159. // Move down until the Z probe (or endstop?) is triggered
  1160. float zPosition = -(Z_MAX_LENGTH + 10);
  1161. line_to_z(zPosition);
  1162. st_synchronize();
  1163. // Tell the planner where we ended up - Get this from the stepper handler
  1164. zPosition = st_get_axis_position_mm(Z_AXIS);
  1165. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS]);
  1166. // move up the retract distance
  1167. zPosition += home_bump_mm(Z_AXIS);
  1168. line_to_z(zPosition);
  1169. st_synchronize();
  1170. endstops_hit_on_purpose(); // clear endstop hit flags
  1171. // move back down slowly to find bed
  1172. set_homing_bump_feedrate(Z_AXIS);
  1173. zPosition -= home_bump_mm(Z_AXIS) * 2;
  1174. line_to_z(zPosition);
  1175. st_synchronize();
  1176. endstops_hit_on_purpose(); // clear endstop hit flags
  1177. // Get the current stepper position after bumping an endstop
  1178. current_position[Z_AXIS] = st_get_axis_position_mm(Z_AXIS);
  1179. sync_plan_position();
  1180. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1181. if (marlin_debug_flags & DEBUG_LEVELING) {
  1182. print_xyz("run_z_probe > current_position", current_position);
  1183. }
  1184. #endif
  1185. #endif // !DELTA
  1186. }
  1187. /**
  1188. * Plan a move to (X, Y, Z) and set the current_position
  1189. * The final current_position may not be the one that was requested
  1190. */
  1191. static void do_blocking_move_to(float x, float y, float z) {
  1192. float oldFeedRate = feedrate;
  1193. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1194. if (marlin_debug_flags & DEBUG_LEVELING) {
  1195. print_xyz("do_blocking_move_to", x, y, z);
  1196. }
  1197. #endif
  1198. #if ENABLED(DELTA)
  1199. feedrate = XY_TRAVEL_SPEED;
  1200. destination[X_AXIS] = x;
  1201. destination[Y_AXIS] = y;
  1202. destination[Z_AXIS] = z;
  1203. prepare_move_raw(); // this will also set_current_to_destination
  1204. st_synchronize();
  1205. #else
  1206. feedrate = homing_feedrate[Z_AXIS];
  1207. current_position[Z_AXIS] = z;
  1208. line_to_current_position();
  1209. st_synchronize();
  1210. feedrate = xy_travel_speed;
  1211. current_position[X_AXIS] = x;
  1212. current_position[Y_AXIS] = y;
  1213. line_to_current_position();
  1214. st_synchronize();
  1215. #endif
  1216. feedrate = oldFeedRate;
  1217. }
  1218. inline void do_blocking_move_to_xy(float x, float y) { do_blocking_move_to(x, y, current_position[Z_AXIS]); }
  1219. inline void do_blocking_move_to_x(float x) { do_blocking_move_to(x, current_position[Y_AXIS], current_position[Z_AXIS]); }
  1220. inline void do_blocking_move_to_z(float z) { do_blocking_move_to(current_position[X_AXIS], current_position[Y_AXIS], z); }
  1221. inline void raise_z_after_probing() { do_blocking_move_to_z(current_position[Z_AXIS] + Z_RAISE_AFTER_PROBING); }
  1222. static void clean_up_after_endstop_move() {
  1223. #if ENABLED(ENDSTOPS_ONLY_FOR_HOMING)
  1224. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1225. if (marlin_debug_flags & DEBUG_LEVELING) {
  1226. SERIAL_ECHOLNPGM("clean_up_after_endstop_move > ENDSTOPS_ONLY_FOR_HOMING > enable_endstops(false)");
  1227. }
  1228. #endif
  1229. enable_endstops(false);
  1230. #endif
  1231. feedrate = saved_feedrate;
  1232. feedrate_multiplier = saved_feedrate_multiplier;
  1233. refresh_cmd_timeout();
  1234. }
  1235. static void deploy_z_probe() {
  1236. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1237. if (marlin_debug_flags & DEBUG_LEVELING) {
  1238. print_xyz("deploy_z_probe > current_position", current_position);
  1239. }
  1240. #endif
  1241. #if HAS_SERVO_ENDSTOPS
  1242. // Engage Z Servo endstop if enabled
  1243. if (servo_endstop_id[Z_AXIS] >= 0) servo[servo_endstop_id[Z_AXIS]].move(servo_endstop_angle[Z_AXIS][0]);
  1244. #elif ENABLED(Z_PROBE_ALLEN_KEY)
  1245. feedrate = Z_PROBE_ALLEN_KEY_DEPLOY_1_FEEDRATE;
  1246. // If endstop is already false, the Z probe is deployed
  1247. #if ENABLED(Z_MIN_PROBE_ENDSTOP)
  1248. bool z_probe_endstop = (READ(Z_MIN_PROBE_PIN) != Z_MIN_PROBE_ENDSTOP_INVERTING);
  1249. if (z_probe_endstop)
  1250. #else
  1251. bool z_min_endstop = (READ(Z_MIN_PIN) != Z_MIN_ENDSTOP_INVERTING);
  1252. if (z_min_endstop)
  1253. #endif
  1254. {
  1255. // Move to the start position to initiate deployment
  1256. destination[X_AXIS] = Z_PROBE_ALLEN_KEY_DEPLOY_1_X;
  1257. destination[Y_AXIS] = Z_PROBE_ALLEN_KEY_DEPLOY_1_Y;
  1258. destination[Z_AXIS] = Z_PROBE_ALLEN_KEY_DEPLOY_1_Z;
  1259. prepare_move_raw(); // this will also set_current_to_destination
  1260. // Move to engage deployment
  1261. if (Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE != Z_PROBE_ALLEN_KEY_DEPLOY_1_FEEDRATE)
  1262. feedrate = Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE;
  1263. if (Z_PROBE_ALLEN_KEY_DEPLOY_2_X != Z_PROBE_ALLEN_KEY_DEPLOY_1_X)
  1264. destination[X_AXIS] = Z_PROBE_ALLEN_KEY_DEPLOY_2_X;
  1265. if (Z_PROBE_ALLEN_KEY_DEPLOY_2_Y != Z_PROBE_ALLEN_KEY_DEPLOY_1_Y)
  1266. destination[Y_AXIS] = Z_PROBE_ALLEN_KEY_DEPLOY_2_Y;
  1267. if (Z_PROBE_ALLEN_KEY_DEPLOY_2_Z != Z_PROBE_ALLEN_KEY_DEPLOY_1_Z)
  1268. destination[Z_AXIS] = Z_PROBE_ALLEN_KEY_DEPLOY_2_Z;
  1269. prepare_move_raw();
  1270. #ifdef Z_PROBE_ALLEN_KEY_DEPLOY_3_X
  1271. if (Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE != Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE)
  1272. feedrate = Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE;
  1273. // Move to trigger deployment
  1274. if (Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE != Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE)
  1275. feedrate = Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE;
  1276. if (Z_PROBE_ALLEN_KEY_DEPLOY_3_X != Z_PROBE_ALLEN_KEY_DEPLOY_2_X)
  1277. destination[X_AXIS] = Z_PROBE_ALLEN_KEY_DEPLOY_3_X;
  1278. if (Z_PROBE_ALLEN_KEY_DEPLOY_3_Y != Z_PROBE_ALLEN_KEY_DEPLOY_2_Y)
  1279. destination[Y_AXIS] = Z_PROBE_ALLEN_KEY_DEPLOY_3_Y;
  1280. if (Z_PROBE_ALLEN_KEY_DEPLOY_3_Z != Z_PROBE_ALLEN_KEY_DEPLOY_2_Z)
  1281. destination[Z_AXIS] = Z_PROBE_ALLEN_KEY_DEPLOY_3_Z;
  1282. prepare_move_raw();
  1283. #endif
  1284. }
  1285. // Partially Home X,Y for safety
  1286. destination[X_AXIS] = destination[X_AXIS] * 0.75;
  1287. destination[Y_AXIS] = destination[Y_AXIS] * 0.75;
  1288. prepare_move_raw(); // this will also set_current_to_destination
  1289. st_synchronize();
  1290. #if ENABLED(Z_MIN_PROBE_ENDSTOP)
  1291. z_probe_endstop = (READ(Z_MIN_PROBE_PIN) != Z_MIN_PROBE_ENDSTOP_INVERTING);
  1292. if (z_probe_endstop)
  1293. #else
  1294. z_min_endstop = (READ(Z_MIN_PIN) != Z_MIN_ENDSTOP_INVERTING);
  1295. if (z_min_endstop)
  1296. #endif
  1297. {
  1298. if (IsRunning()) {
  1299. SERIAL_ERROR_START;
  1300. SERIAL_ERRORLNPGM("Z-Probe failed to engage!");
  1301. LCD_ALERTMESSAGEPGM("Err: ZPROBE");
  1302. }
  1303. Stop();
  1304. }
  1305. #endif // Z_PROBE_ALLEN_KEY
  1306. }
  1307. static void stow_z_probe(bool doRaise = true) {
  1308. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1309. if (marlin_debug_flags & DEBUG_LEVELING) {
  1310. print_xyz("stow_z_probe > current_position", current_position);
  1311. }
  1312. #endif
  1313. #if HAS_SERVO_ENDSTOPS
  1314. // Retract Z Servo endstop if enabled
  1315. if (servo_endstop_id[Z_AXIS] >= 0) {
  1316. #if Z_RAISE_AFTER_PROBING > 0
  1317. if (doRaise) {
  1318. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1319. if (marlin_debug_flags & DEBUG_LEVELING) {
  1320. SERIAL_ECHOPAIR("Raise Z (after) by ", (float)Z_RAISE_AFTER_PROBING);
  1321. SERIAL_EOL;
  1322. SERIAL_ECHO("> SERVO_ENDSTOPS > raise_z_after_probing()");
  1323. SERIAL_EOL;
  1324. }
  1325. #endif
  1326. raise_z_after_probing(); // this also updates current_position
  1327. st_synchronize();
  1328. }
  1329. #endif
  1330. // Change the Z servo angle
  1331. servo[servo_endstop_id[Z_AXIS]].move(servo_endstop_angle[Z_AXIS][1]);
  1332. }
  1333. #elif ENABLED(Z_PROBE_ALLEN_KEY)
  1334. // Move up for safety
  1335. feedrate = Z_PROBE_ALLEN_KEY_STOW_1_FEEDRATE;
  1336. #if Z_RAISE_AFTER_PROBING > 0
  1337. destination[Z_AXIS] = current_position[Z_AXIS] + Z_RAISE_AFTER_PROBING;
  1338. prepare_move_raw(); // this will also set_current_to_destination
  1339. #endif
  1340. // Move to the start position to initiate retraction
  1341. destination[X_AXIS] = Z_PROBE_ALLEN_KEY_STOW_1_X;
  1342. destination[Y_AXIS] = Z_PROBE_ALLEN_KEY_STOW_1_Y;
  1343. destination[Z_AXIS] = Z_PROBE_ALLEN_KEY_STOW_1_Z;
  1344. prepare_move_raw();
  1345. // Move the nozzle down to push the Z probe into retracted position
  1346. if (Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE != Z_PROBE_ALLEN_KEY_STOW_1_FEEDRATE)
  1347. feedrate = Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE;
  1348. if (Z_PROBE_ALLEN_KEY_STOW_2_X != Z_PROBE_ALLEN_KEY_STOW_1_X)
  1349. destination[X_AXIS] = Z_PROBE_ALLEN_KEY_STOW_2_X;
  1350. if (Z_PROBE_ALLEN_KEY_STOW_2_Y != Z_PROBE_ALLEN_KEY_STOW_1_Y)
  1351. destination[Y_AXIS] = Z_PROBE_ALLEN_KEY_STOW_2_Y;
  1352. destination[Z_AXIS] = Z_PROBE_ALLEN_KEY_STOW_2_Z;
  1353. prepare_move_raw();
  1354. // Move up for safety
  1355. if (Z_PROBE_ALLEN_KEY_STOW_3_FEEDRATE != Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE)
  1356. feedrate = Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE;
  1357. if (Z_PROBE_ALLEN_KEY_STOW_3_X != Z_PROBE_ALLEN_KEY_STOW_2_X)
  1358. destination[X_AXIS] = Z_PROBE_ALLEN_KEY_STOW_3_X;
  1359. if (Z_PROBE_ALLEN_KEY_STOW_3_Y != Z_PROBE_ALLEN_KEY_STOW_2_Y)
  1360. destination[Y_AXIS] = Z_PROBE_ALLEN_KEY_STOW_3_Y;
  1361. destination[Z_AXIS] = Z_PROBE_ALLEN_KEY_STOW_3_Z;
  1362. prepare_move_raw();
  1363. // Home XY for safety
  1364. feedrate = homing_feedrate[X_AXIS] / 2;
  1365. destination[X_AXIS] = 0;
  1366. destination[Y_AXIS] = 0;
  1367. prepare_move_raw(); // this will also set_current_to_destination
  1368. st_synchronize();
  1369. #if ENABLED(Z_MIN_PROBE_ENDSTOP)
  1370. bool z_probe_endstop = (READ(Z_MIN_PROBE_PIN) != Z_MIN_PROBE_ENDSTOP_INVERTING);
  1371. if (!z_probe_endstop)
  1372. #else
  1373. bool z_min_endstop = (READ(Z_MIN_PIN) != Z_MIN_ENDSTOP_INVERTING);
  1374. if (!z_min_endstop)
  1375. #endif
  1376. {
  1377. if (IsRunning()) {
  1378. SERIAL_ERROR_START;
  1379. SERIAL_ERRORLNPGM("Z-Probe failed to retract!");
  1380. LCD_ALERTMESSAGEPGM("Err: ZPROBE");
  1381. }
  1382. Stop();
  1383. }
  1384. #endif // Z_PROBE_ALLEN_KEY
  1385. }
  1386. enum ProbeAction {
  1387. ProbeStay = 0,
  1388. ProbeDeploy = _BV(0),
  1389. ProbeStow = _BV(1),
  1390. ProbeDeployAndStow = (ProbeDeploy | ProbeStow)
  1391. };
  1392. // Probe bed height at position (x,y), returns the measured z value
  1393. static float probe_pt(float x, float y, float z_before, ProbeAction probe_action = ProbeDeployAndStow, int verbose_level = 1) {
  1394. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1395. if (marlin_debug_flags & DEBUG_LEVELING) {
  1396. SERIAL_ECHOLNPGM("probe_pt >>>");
  1397. SERIAL_ECHOPAIR("> ProbeAction:", (unsigned long)probe_action);
  1398. SERIAL_EOL;
  1399. print_xyz("> current_position", current_position);
  1400. }
  1401. #endif
  1402. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1403. if (marlin_debug_flags & DEBUG_LEVELING) {
  1404. SERIAL_ECHOPAIR("Z Raise to z_before ", z_before);
  1405. SERIAL_EOL;
  1406. SERIAL_ECHOPAIR("> do_blocking_move_to_z ", z_before);
  1407. SERIAL_EOL;
  1408. }
  1409. #endif
  1410. // Move Z up to the z_before height, then move the Z probe to the given XY
  1411. do_blocking_move_to_z(z_before); // this also updates current_position
  1412. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1413. if (marlin_debug_flags & DEBUG_LEVELING) {
  1414. SERIAL_ECHOPAIR("> do_blocking_move_to_xy ", x - (X_PROBE_OFFSET_FROM_EXTRUDER));
  1415. SERIAL_ECHOPAIR(", ", y - (Y_PROBE_OFFSET_FROM_EXTRUDER));
  1416. SERIAL_EOL;
  1417. }
  1418. #endif
  1419. do_blocking_move_to_xy(x - (X_PROBE_OFFSET_FROM_EXTRUDER), y - (Y_PROBE_OFFSET_FROM_EXTRUDER)); // this also updates current_position
  1420. #if DISABLED(Z_PROBE_SLED) && DISABLED(Z_PROBE_ALLEN_KEY)
  1421. if (probe_action & ProbeDeploy) {
  1422. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1423. if (marlin_debug_flags & DEBUG_LEVELING) {
  1424. SERIAL_ECHOLNPGM("> ProbeDeploy");
  1425. }
  1426. #endif
  1427. deploy_z_probe();
  1428. }
  1429. #endif
  1430. run_z_probe();
  1431. float measured_z = current_position[Z_AXIS];
  1432. #if DISABLED(Z_PROBE_SLED) && DISABLED(Z_PROBE_ALLEN_KEY)
  1433. if (probe_action & ProbeStow) {
  1434. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1435. if (marlin_debug_flags & DEBUG_LEVELING) {
  1436. SERIAL_ECHOLNPGM("> ProbeStow (stow_z_probe will do Z Raise)");
  1437. }
  1438. #endif
  1439. stow_z_probe();
  1440. }
  1441. #endif
  1442. if (verbose_level > 2) {
  1443. SERIAL_PROTOCOLPGM("Bed X: ");
  1444. SERIAL_PROTOCOL_F(x, 3);
  1445. SERIAL_PROTOCOLPGM(" Y: ");
  1446. SERIAL_PROTOCOL_F(y, 3);
  1447. SERIAL_PROTOCOLPGM(" Z: ");
  1448. SERIAL_PROTOCOL_F(measured_z, 3);
  1449. SERIAL_EOL;
  1450. }
  1451. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1452. if (marlin_debug_flags & DEBUG_LEVELING) {
  1453. SERIAL_ECHOLNPGM("<<< probe_pt");
  1454. }
  1455. #endif
  1456. return measured_z;
  1457. }
  1458. #if ENABLED(DELTA)
  1459. /**
  1460. * All DELTA leveling in the Marlin uses NONLINEAR_BED_LEVELING
  1461. */
  1462. static void extrapolate_one_point(int x, int y, int xdir, int ydir) {
  1463. if (bed_level[x][y] != 0.0) {
  1464. return; // Don't overwrite good values.
  1465. }
  1466. float a = 2 * bed_level[x + xdir][y] - bed_level[x + xdir * 2][y]; // Left to right.
  1467. float b = 2 * bed_level[x][y + ydir] - bed_level[x][y + ydir * 2]; // Front to back.
  1468. float c = 2 * bed_level[x + xdir][y + ydir] - bed_level[x + xdir * 2][y + ydir * 2]; // Diagonal.
  1469. float median = c; // Median is robust (ignores outliers).
  1470. if (a < b) {
  1471. if (b < c) median = b;
  1472. if (c < a) median = a;
  1473. }
  1474. else { // b <= a
  1475. if (c < b) median = b;
  1476. if (a < c) median = a;
  1477. }
  1478. bed_level[x][y] = median;
  1479. }
  1480. // Fill in the unprobed points (corners of circular print surface)
  1481. // using linear extrapolation, away from the center.
  1482. static void extrapolate_unprobed_bed_level() {
  1483. int half = (AUTO_BED_LEVELING_GRID_POINTS - 1) / 2;
  1484. for (int y = 0; y <= half; y++) {
  1485. for (int x = 0; x <= half; x++) {
  1486. if (x + y < 3) continue;
  1487. extrapolate_one_point(half - x, half - y, x > 1 ? +1 : 0, y > 1 ? +1 : 0);
  1488. extrapolate_one_point(half + x, half - y, x > 1 ? -1 : 0, y > 1 ? +1 : 0);
  1489. extrapolate_one_point(half - x, half + y, x > 1 ? +1 : 0, y > 1 ? -1 : 0);
  1490. extrapolate_one_point(half + x, half + y, x > 1 ? -1 : 0, y > 1 ? -1 : 0);
  1491. }
  1492. }
  1493. }
  1494. // Print calibration results for plotting or manual frame adjustment.
  1495. static void print_bed_level() {
  1496. for (int y = 0; y < AUTO_BED_LEVELING_GRID_POINTS; y++) {
  1497. for (int x = 0; x < AUTO_BED_LEVELING_GRID_POINTS; x++) {
  1498. SERIAL_PROTOCOL_F(bed_level[x][y], 2);
  1499. SERIAL_PROTOCOLCHAR(' ');
  1500. }
  1501. SERIAL_EOL;
  1502. }
  1503. }
  1504. // Reset calibration results to zero.
  1505. void reset_bed_level() {
  1506. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1507. if (marlin_debug_flags & DEBUG_LEVELING) {
  1508. SERIAL_ECHOLNPGM("reset_bed_level");
  1509. }
  1510. #endif
  1511. for (int y = 0; y < AUTO_BED_LEVELING_GRID_POINTS; y++) {
  1512. for (int x = 0; x < AUTO_BED_LEVELING_GRID_POINTS; x++) {
  1513. bed_level[x][y] = 0.0;
  1514. }
  1515. }
  1516. }
  1517. #endif // DELTA
  1518. #if HAS_SERVO_ENDSTOPS && DISABLED(Z_PROBE_SLED)
  1519. void raise_z_for_servo() {
  1520. float zpos = current_position[Z_AXIS], z_dest = Z_RAISE_BEFORE_PROBING;
  1521. // The zprobe_zoffset is negative any switch below the nozzle, so
  1522. // multiply by Z_HOME_DIR (-1) to move enough away from bed for the probe
  1523. z_dest += axis_known_position[Z_AXIS] ? zprobe_zoffset * Z_HOME_DIR : zpos;
  1524. if (zpos < z_dest) do_blocking_move_to_z(z_dest); // also updates current_position
  1525. }
  1526. #endif
  1527. #endif // AUTO_BED_LEVELING_FEATURE
  1528. #if ENABLED(Z_PROBE_SLED)
  1529. #ifndef SLED_DOCKING_OFFSET
  1530. #define SLED_DOCKING_OFFSET 0
  1531. #endif
  1532. /**
  1533. * Method to dock/undock a sled designed by Charles Bell.
  1534. *
  1535. * dock[in] If true, move to MAX_X and engage the electromagnet
  1536. * offset[in] The additional distance to move to adjust docking location
  1537. */
  1538. static void dock_sled(bool dock, int offset = 0) {
  1539. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1540. if (marlin_debug_flags & DEBUG_LEVELING) {
  1541. SERIAL_ECHOPAIR("dock_sled", dock);
  1542. SERIAL_EOL;
  1543. }
  1544. #endif
  1545. if (!axis_known_position[X_AXIS] || !axis_known_position[Y_AXIS]) {
  1546. LCD_MESSAGEPGM(MSG_POSITION_UNKNOWN);
  1547. SERIAL_ECHO_START;
  1548. SERIAL_ECHOLNPGM(MSG_POSITION_UNKNOWN);
  1549. return;
  1550. }
  1551. float oldXpos = current_position[X_AXIS]; // save x position
  1552. if (dock) {
  1553. #if Z_RAISE_AFTER_PROBING > 0
  1554. raise_z_after_probing(); // raise Z
  1555. #endif
  1556. do_blocking_move_to_x(X_MAX_POS + SLED_DOCKING_OFFSET + offset - 1); // Dock sled a bit closer to ensure proper capturing
  1557. digitalWrite(SLED_PIN, LOW); // turn off magnet
  1558. }
  1559. else {
  1560. float z_loc = current_position[Z_AXIS];
  1561. if (z_loc < Z_RAISE_BEFORE_PROBING + 5) z_loc = Z_RAISE_BEFORE_PROBING;
  1562. do_blocking_move_to(X_MAX_POS + SLED_DOCKING_OFFSET + offset, current_position[Y_AXIS], z_loc); // this also updates current_position
  1563. digitalWrite(SLED_PIN, HIGH); // turn on magnet
  1564. }
  1565. do_blocking_move_to_x(oldXpos); // return to position before docking
  1566. }
  1567. #endif // Z_PROBE_SLED
  1568. /**
  1569. * Home an individual axis
  1570. */
  1571. #define HOMEAXIS(LETTER) homeaxis(LETTER##_AXIS)
  1572. static void homeaxis(AxisEnum axis) {
  1573. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1574. if (marlin_debug_flags & DEBUG_LEVELING) {
  1575. SERIAL_ECHOPAIR(">>> homeaxis(", (unsigned long)axis);
  1576. SERIAL_CHAR(')');
  1577. SERIAL_EOL;
  1578. }
  1579. #endif
  1580. #define HOMEAXIS_DO(LETTER) \
  1581. ((LETTER##_MIN_PIN > -1 && LETTER##_HOME_DIR==-1) || (LETTER##_MAX_PIN > -1 && LETTER##_HOME_DIR==1))
  1582. if (axis == X_AXIS ? HOMEAXIS_DO(X) : axis == Y_AXIS ? HOMEAXIS_DO(Y) : axis == Z_AXIS ? HOMEAXIS_DO(Z) : 0) {
  1583. int axis_home_dir =
  1584. #if ENABLED(DUAL_X_CARRIAGE)
  1585. (axis == X_AXIS) ? x_home_dir(active_extruder) :
  1586. #endif
  1587. home_dir(axis);
  1588. // Set the axis position as setup for the move
  1589. current_position[axis] = 0;
  1590. sync_plan_position();
  1591. #if ENABLED(Z_PROBE_SLED)
  1592. // Get Probe
  1593. if (axis == Z_AXIS) {
  1594. if (axis_home_dir < 0) dock_sled(false);
  1595. }
  1596. #endif
  1597. #if SERVO_LEVELING && DISABLED(Z_PROBE_SLED)
  1598. // Deploy a Z probe if there is one, and homing towards the bed
  1599. if (axis == Z_AXIS) {
  1600. if (axis_home_dir < 0) deploy_z_probe();
  1601. }
  1602. #endif
  1603. #if HAS_SERVO_ENDSTOPS
  1604. // Engage Servo endstop if enabled
  1605. if (axis != Z_AXIS && servo_endstop_id[axis] >= 0)
  1606. servo[servo_endstop_id[axis]].move(servo_endstop_angle[axis][0]);
  1607. #endif
  1608. // Set a flag for Z motor locking
  1609. #if ENABLED(Z_DUAL_ENDSTOPS)
  1610. if (axis == Z_AXIS) In_Homing_Process(true);
  1611. #endif
  1612. // Move towards the endstop until an endstop is triggered
  1613. destination[axis] = 1.5 * max_length(axis) * axis_home_dir;
  1614. feedrate = homing_feedrate[axis];
  1615. line_to_destination();
  1616. st_synchronize();
  1617. // Set the axis position as setup for the move
  1618. current_position[axis] = 0;
  1619. sync_plan_position();
  1620. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1621. if (marlin_debug_flags & DEBUG_LEVELING) {
  1622. SERIAL_ECHOLNPGM("> enable_endstops(false)");
  1623. }
  1624. #endif
  1625. enable_endstops(false); // Disable endstops while moving away
  1626. // Move away from the endstop by the axis HOME_BUMP_MM
  1627. destination[axis] = -home_bump_mm(axis) * axis_home_dir;
  1628. line_to_destination();
  1629. st_synchronize();
  1630. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1631. if (marlin_debug_flags & DEBUG_LEVELING) {
  1632. SERIAL_ECHOLNPGM("> enable_endstops(true)");
  1633. }
  1634. #endif
  1635. enable_endstops(true); // Enable endstops for next homing move
  1636. // Slow down the feedrate for the next move
  1637. set_homing_bump_feedrate(axis);
  1638. // Move slowly towards the endstop until triggered
  1639. destination[axis] = 2 * home_bump_mm(axis) * axis_home_dir;
  1640. line_to_destination();
  1641. st_synchronize();
  1642. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1643. if (marlin_debug_flags & DEBUG_LEVELING) {
  1644. print_xyz("> TRIGGER ENDSTOP > current_position", current_position);
  1645. }
  1646. #endif
  1647. #if ENABLED(Z_DUAL_ENDSTOPS)
  1648. if (axis == Z_AXIS) {
  1649. float adj = fabs(z_endstop_adj);
  1650. bool lockZ1;
  1651. if (axis_home_dir > 0) {
  1652. adj = -adj;
  1653. lockZ1 = (z_endstop_adj > 0);
  1654. }
  1655. else
  1656. lockZ1 = (z_endstop_adj < 0);
  1657. if (lockZ1) Lock_z_motor(true); else Lock_z2_motor(true);
  1658. sync_plan_position();
  1659. // Move to the adjusted endstop height
  1660. feedrate = homing_feedrate[axis];
  1661. destination[Z_AXIS] = adj;
  1662. line_to_destination();
  1663. st_synchronize();
  1664. if (lockZ1) Lock_z_motor(false); else Lock_z2_motor(false);
  1665. In_Homing_Process(false);
  1666. } // Z_AXIS
  1667. #endif
  1668. #if ENABLED(DELTA)
  1669. // retrace by the amount specified in endstop_adj
  1670. if (endstop_adj[axis] * axis_home_dir < 0) {
  1671. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1672. if (marlin_debug_flags & DEBUG_LEVELING) {
  1673. SERIAL_ECHOLNPGM("> enable_endstops(false)");
  1674. }
  1675. #endif
  1676. enable_endstops(false); // Disable endstops while moving away
  1677. sync_plan_position();
  1678. destination[axis] = endstop_adj[axis];
  1679. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1680. if (marlin_debug_flags & DEBUG_LEVELING) {
  1681. SERIAL_ECHOPAIR("> endstop_adj = ", endstop_adj[axis]);
  1682. print_xyz(" > destination", destination);
  1683. }
  1684. #endif
  1685. line_to_destination();
  1686. st_synchronize();
  1687. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1688. if (marlin_debug_flags & DEBUG_LEVELING) {
  1689. SERIAL_ECHOLNPGM("> enable_endstops(true)");
  1690. }
  1691. #endif
  1692. enable_endstops(true); // Enable endstops for next homing move
  1693. }
  1694. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1695. else {
  1696. if (marlin_debug_flags & DEBUG_LEVELING) {
  1697. SERIAL_ECHOPAIR("> endstop_adj * axis_home_dir = ", endstop_adj[axis] * axis_home_dir);
  1698. SERIAL_EOL;
  1699. }
  1700. }
  1701. #endif
  1702. #endif
  1703. // Set the axis position to its home position (plus home offsets)
  1704. set_axis_is_at_home(axis);
  1705. sync_plan_position();
  1706. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1707. if (marlin_debug_flags & DEBUG_LEVELING) {
  1708. print_xyz("> AFTER set_axis_is_at_home > current_position", current_position);
  1709. }
  1710. #endif
  1711. destination[axis] = current_position[axis];
  1712. feedrate = 0.0;
  1713. endstops_hit_on_purpose(); // clear endstop hit flags
  1714. axis_known_position[axis] = true;
  1715. axis_homed[axis] = true;
  1716. #if ENABLED(Z_PROBE_SLED)
  1717. // bring Z probe back
  1718. if (axis == Z_AXIS) {
  1719. if (axis_home_dir < 0) dock_sled(true);
  1720. }
  1721. #endif
  1722. #if SERVO_LEVELING && DISABLED(Z_PROBE_SLED)
  1723. // Deploy a Z probe if there is one, and homing towards the bed
  1724. if (axis == Z_AXIS) {
  1725. if (axis_home_dir < 0) {
  1726. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1727. if (marlin_debug_flags & DEBUG_LEVELING) {
  1728. SERIAL_ECHOLNPGM("> SERVO_LEVELING > stow_z_probe");
  1729. }
  1730. #endif
  1731. stow_z_probe();
  1732. }
  1733. }
  1734. else
  1735. #endif
  1736. {
  1737. #if HAS_SERVO_ENDSTOPS
  1738. // Retract Servo endstop if enabled
  1739. if (servo_endstop_id[axis] >= 0) {
  1740. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1741. if (marlin_debug_flags & DEBUG_LEVELING) {
  1742. SERIAL_ECHOLNPGM("> SERVO_ENDSTOPS > Stow with servo.move()");
  1743. }
  1744. #endif
  1745. servo[servo_endstop_id[axis]].move(servo_endstop_angle[axis][1]);
  1746. }
  1747. #endif
  1748. }
  1749. }
  1750. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1751. if (marlin_debug_flags & DEBUG_LEVELING) {
  1752. SERIAL_ECHOPAIR("<<< homeaxis(", (unsigned long)axis);
  1753. SERIAL_CHAR(')');
  1754. SERIAL_EOL;
  1755. }
  1756. #endif
  1757. }
  1758. #if ENABLED(FWRETRACT)
  1759. void retract(bool retracting, bool swapping = false) {
  1760. if (retracting == retracted[active_extruder]) return;
  1761. float oldFeedrate = feedrate;
  1762. set_destination_to_current();
  1763. if (retracting) {
  1764. feedrate = retract_feedrate * 60;
  1765. current_position[E_AXIS] += (swapping ? retract_length_swap : retract_length) / volumetric_multiplier[active_extruder];
  1766. plan_set_e_position(current_position[E_AXIS]);
  1767. prepare_move();
  1768. if (retract_zlift > 0.01) {
  1769. current_position[Z_AXIS] -= retract_zlift;
  1770. #if ENABLED(DELTA)
  1771. sync_plan_position_delta();
  1772. #else
  1773. sync_plan_position();
  1774. #endif
  1775. prepare_move();
  1776. }
  1777. }
  1778. else {
  1779. if (retract_zlift > 0.01) {
  1780. current_position[Z_AXIS] += retract_zlift;
  1781. #if ENABLED(DELTA)
  1782. sync_plan_position_delta();
  1783. #else
  1784. sync_plan_position();
  1785. #endif
  1786. //prepare_move();
  1787. }
  1788. feedrate = retract_recover_feedrate * 60;
  1789. float move_e = swapping ? retract_length_swap + retract_recover_length_swap : retract_length + retract_recover_length;
  1790. current_position[E_AXIS] -= move_e / volumetric_multiplier[active_extruder];
  1791. plan_set_e_position(current_position[E_AXIS]);
  1792. prepare_move();
  1793. }
  1794. feedrate = oldFeedrate;
  1795. retracted[active_extruder] = retracting;
  1796. } // retract()
  1797. #endif // FWRETRACT
  1798. /**
  1799. *
  1800. * G-Code Handler functions
  1801. *
  1802. */
  1803. /**
  1804. * Set XYZE destination and feedrate from the current GCode command
  1805. *
  1806. * - Set destination from included axis codes
  1807. * - Set to current for missing axis codes
  1808. * - Set the feedrate, if included
  1809. */
  1810. void gcode_get_destination() {
  1811. for (int i = 0; i < NUM_AXIS; i++) {
  1812. if (code_seen(axis_codes[i]))
  1813. destination[i] = code_value() + (axis_relative_modes[i] || relative_mode ? current_position[i] : 0);
  1814. else
  1815. destination[i] = current_position[i];
  1816. }
  1817. if (code_seen('F')) {
  1818. float next_feedrate = code_value();
  1819. if (next_feedrate > 0.0) feedrate = next_feedrate;
  1820. }
  1821. }
  1822. void unknown_command_error() {
  1823. SERIAL_ECHO_START;
  1824. SERIAL_ECHOPGM(MSG_UNKNOWN_COMMAND);
  1825. SERIAL_ECHO(current_command);
  1826. SERIAL_ECHOPGM("\"\n");
  1827. }
  1828. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  1829. void host_keepalive() {
  1830. millis_t ms = millis();
  1831. if (busy_state != NOT_BUSY) {
  1832. if (ms < next_busy_signal_ms) return;
  1833. switch (busy_state) {
  1834. case NOT_BUSY:
  1835. break;
  1836. case IN_HANDLER:
  1837. case IN_PROCESS:
  1838. SERIAL_ECHO_START;
  1839. SERIAL_ECHOLNPGM(MSG_BUSY_PROCESSING);
  1840. break;
  1841. case PAUSED_FOR_USER:
  1842. SERIAL_ECHO_START;
  1843. SERIAL_ECHOLNPGM(MSG_BUSY_PAUSED_FOR_USER);
  1844. break;
  1845. case PAUSED_FOR_INPUT:
  1846. SERIAL_ECHO_START;
  1847. SERIAL_ECHOLNPGM(MSG_BUSY_PAUSED_FOR_INPUT);
  1848. break;
  1849. }
  1850. }
  1851. next_busy_signal_ms = ms + 2000UL;
  1852. }
  1853. #endif //HOST_KEEPALIVE_FEATURE
  1854. /**
  1855. * G0, G1: Coordinated movement of X Y Z E axes
  1856. */
  1857. inline void gcode_G0_G1() {
  1858. if (IsRunning()) {
  1859. gcode_get_destination(); // For X Y Z E F
  1860. #if ENABLED(FWRETRACT)
  1861. if (autoretract_enabled && !(code_seen('X') || code_seen('Y') || code_seen('Z')) && code_seen('E')) {
  1862. float echange = destination[E_AXIS] - current_position[E_AXIS];
  1863. // Is this move an attempt to retract or recover?
  1864. if ((echange < -MIN_RETRACT && !retracted[active_extruder]) || (echange > MIN_RETRACT && retracted[active_extruder])) {
  1865. current_position[E_AXIS] = destination[E_AXIS]; // hide the slicer-generated retract/recover from calculations
  1866. plan_set_e_position(current_position[E_AXIS]); // AND from the planner
  1867. retract(!retracted[active_extruder]);
  1868. return;
  1869. }
  1870. }
  1871. #endif //FWRETRACT
  1872. prepare_move();
  1873. }
  1874. }
  1875. /**
  1876. * G2: Clockwise Arc
  1877. * G3: Counterclockwise Arc
  1878. */
  1879. inline void gcode_G2_G3(bool clockwise) {
  1880. if (IsRunning()) {
  1881. #if ENABLED(SF_ARC_FIX)
  1882. bool relative_mode_backup = relative_mode;
  1883. relative_mode = true;
  1884. #endif
  1885. gcode_get_destination();
  1886. #if ENABLED(SF_ARC_FIX)
  1887. relative_mode = relative_mode_backup;
  1888. #endif
  1889. // Center of arc as offset from current_position
  1890. float arc_offset[2] = {
  1891. code_seen('I') ? code_value() : 0,
  1892. code_seen('J') ? code_value() : 0
  1893. };
  1894. // Send an arc to the planner
  1895. plan_arc(destination, arc_offset, clockwise);
  1896. refresh_cmd_timeout();
  1897. }
  1898. }
  1899. /**
  1900. * G4: Dwell S<seconds> or P<milliseconds>
  1901. */
  1902. inline void gcode_G4() {
  1903. millis_t codenum = 0;
  1904. if (code_seen('P')) codenum = code_value_long(); // milliseconds to wait
  1905. if (code_seen('S')) codenum = code_value() * 1000; // seconds to wait
  1906. st_synchronize();
  1907. refresh_cmd_timeout();
  1908. codenum += previous_cmd_ms; // keep track of when we started waiting
  1909. if (!lcd_hasstatus()) LCD_MESSAGEPGM(MSG_DWELL);
  1910. while (millis() < codenum) idle();
  1911. }
  1912. #if ENABLED(FWRETRACT)
  1913. /**
  1914. * G10 - Retract filament according to settings of M207
  1915. * G11 - Recover filament according to settings of M208
  1916. */
  1917. inline void gcode_G10_G11(bool doRetract=false) {
  1918. #if EXTRUDERS > 1
  1919. if (doRetract) {
  1920. retracted_swap[active_extruder] = (code_seen('S') && code_value_short() == 1); // checks for swap retract argument
  1921. }
  1922. #endif
  1923. retract(doRetract
  1924. #if EXTRUDERS > 1
  1925. , retracted_swap[active_extruder]
  1926. #endif
  1927. );
  1928. }
  1929. #endif //FWRETRACT
  1930. /**
  1931. * G28: Home all axes according to settings
  1932. *
  1933. * Parameters
  1934. *
  1935. * None Home to all axes with no parameters.
  1936. * With QUICK_HOME enabled XY will home together, then Z.
  1937. *
  1938. * Cartesian parameters
  1939. *
  1940. * X Home to the X endstop
  1941. * Y Home to the Y endstop
  1942. * Z Home to the Z endstop
  1943. *
  1944. */
  1945. inline void gcode_G28() {
  1946. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1947. if (marlin_debug_flags & DEBUG_LEVELING) {
  1948. SERIAL_ECHOLNPGM("gcode_G28 >>>");
  1949. }
  1950. #endif
  1951. // Wait for planner moves to finish!
  1952. st_synchronize();
  1953. // For auto bed leveling, clear the level matrix
  1954. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  1955. plan_bed_level_matrix.set_to_identity();
  1956. #if ENABLED(DELTA)
  1957. reset_bed_level();
  1958. #endif
  1959. #endif
  1960. // For manual bed leveling deactivate the matrix temporarily
  1961. #if ENABLED(MESH_BED_LEVELING)
  1962. uint8_t mbl_was_active = mbl.active;
  1963. mbl.active = 0;
  1964. #endif
  1965. setup_for_endstop_move();
  1966. set_destination_to_current(); // Directly after a reset this is all 0. Later we get a hint if we have to raise z or not.
  1967. feedrate = 0.0;
  1968. #if ENABLED(DELTA)
  1969. // A delta can only safely home all axis at the same time
  1970. // all axis have to home at the same time
  1971. // Pretend the current position is 0,0,0
  1972. for (int i = X_AXIS; i <= Z_AXIS; i++) current_position[i] = 0;
  1973. sync_plan_position();
  1974. // Move all carriages up together until the first endstop is hit.
  1975. for (int i = X_AXIS; i <= Z_AXIS; i++) destination[i] = 3 * (Z_MAX_LENGTH);
  1976. feedrate = 1.732 * homing_feedrate[X_AXIS];
  1977. line_to_destination();
  1978. st_synchronize();
  1979. endstops_hit_on_purpose(); // clear endstop hit flags
  1980. // Destination reached
  1981. for (int i = X_AXIS; i <= Z_AXIS; i++) current_position[i] = destination[i];
  1982. // take care of back off and rehome now we are all at the top
  1983. HOMEAXIS(X);
  1984. HOMEAXIS(Y);
  1985. HOMEAXIS(Z);
  1986. sync_plan_position_delta();
  1987. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1988. if (marlin_debug_flags & DEBUG_LEVELING) {
  1989. print_xyz("(DELTA) > current_position", current_position);
  1990. }
  1991. #endif
  1992. #else // NOT DELTA
  1993. bool homeX = code_seen(axis_codes[X_AXIS]),
  1994. homeY = code_seen(axis_codes[Y_AXIS]),
  1995. homeZ = code_seen(axis_codes[Z_AXIS]);
  1996. home_all_axis = (!homeX && !homeY && !homeZ) || (homeX && homeY && homeZ);
  1997. #if Z_HOME_DIR > 0 // If homing away from BED do Z first
  1998. if (home_all_axis || homeZ) {
  1999. HOMEAXIS(Z);
  2000. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2001. if (marlin_debug_flags & DEBUG_LEVELING) {
  2002. print_xyz("> HOMEAXIS(Z) > current_position", current_position);
  2003. }
  2004. #endif
  2005. }
  2006. #elif defined(MIN_Z_HEIGHT_FOR_HOMING) && MIN_Z_HEIGHT_FOR_HOMING > 0
  2007. // Raise Z before homing any other axes and z is not already high enough (never lower z)
  2008. if (current_position[Z_AXIS] <= MIN_Z_HEIGHT_FOR_HOMING) {
  2009. destination[Z_AXIS] = MIN_Z_HEIGHT_FOR_HOMING;
  2010. feedrate = max_feedrate[Z_AXIS] * 60; // feedrate (mm/m) = max_feedrate (mm/s)
  2011. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2012. if (marlin_debug_flags & DEBUG_LEVELING) {
  2013. SERIAL_ECHOPAIR("Raise Z (before homing) to ", (float)(MIN_Z_HEIGHT_FOR_HOMING));
  2014. SERIAL_EOL;
  2015. print_xyz("> (home_all_axis || homeZ) > current_position", current_position);
  2016. print_xyz("> (home_all_axis || homeZ) > destination", destination);
  2017. }
  2018. #endif
  2019. line_to_destination();
  2020. st_synchronize();
  2021. // Update the current Z position even if it currently not real from Z-home
  2022. // otherwise each call to line_to_destination() will want to move Z-axis
  2023. // by MIN_Z_HEIGHT_FOR_HOMING.
  2024. current_position[Z_AXIS] = destination[Z_AXIS];
  2025. }
  2026. #endif
  2027. #if ENABLED(QUICK_HOME)
  2028. if (home_all_axis || (homeX && homeY)) { // First diagonal move
  2029. current_position[X_AXIS] = current_position[Y_AXIS] = 0;
  2030. #if ENABLED(DUAL_X_CARRIAGE)
  2031. int x_axis_home_dir = x_home_dir(active_extruder);
  2032. extruder_duplication_enabled = false;
  2033. #else
  2034. int x_axis_home_dir = home_dir(X_AXIS);
  2035. #endif
  2036. sync_plan_position();
  2037. float mlx = max_length(X_AXIS), mly = max_length(Y_AXIS),
  2038. mlratio = mlx > mly ? mly / mlx : mlx / mly;
  2039. destination[X_AXIS] = 1.5 * mlx * x_axis_home_dir;
  2040. destination[Y_AXIS] = 1.5 * mly * home_dir(Y_AXIS);
  2041. feedrate = min(homing_feedrate[X_AXIS], homing_feedrate[Y_AXIS]) * sqrt(mlratio * mlratio + 1);
  2042. line_to_destination();
  2043. st_synchronize();
  2044. set_axis_is_at_home(X_AXIS);
  2045. set_axis_is_at_home(Y_AXIS);
  2046. sync_plan_position();
  2047. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2048. if (marlin_debug_flags & DEBUG_LEVELING) {
  2049. print_xyz("> QUICK_HOME > current_position 1", current_position);
  2050. }
  2051. #endif
  2052. destination[X_AXIS] = current_position[X_AXIS];
  2053. destination[Y_AXIS] = current_position[Y_AXIS];
  2054. line_to_destination();
  2055. feedrate = 0.0;
  2056. st_synchronize();
  2057. endstops_hit_on_purpose(); // clear endstop hit flags
  2058. current_position[X_AXIS] = destination[X_AXIS];
  2059. current_position[Y_AXIS] = destination[Y_AXIS];
  2060. #if DISABLED(SCARA)
  2061. current_position[Z_AXIS] = destination[Z_AXIS];
  2062. #endif
  2063. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2064. if (marlin_debug_flags & DEBUG_LEVELING) {
  2065. print_xyz("> QUICK_HOME > current_position 2", current_position);
  2066. }
  2067. #endif
  2068. }
  2069. #endif // QUICK_HOME
  2070. #if ENABLED(HOME_Y_BEFORE_X)
  2071. // Home Y
  2072. if (home_all_axis || homeY) HOMEAXIS(Y);
  2073. #endif
  2074. // Home X
  2075. if (home_all_axis || homeX) {
  2076. #if ENABLED(DUAL_X_CARRIAGE)
  2077. int tmp_extruder = active_extruder;
  2078. extruder_duplication_enabled = false;
  2079. active_extruder = !active_extruder;
  2080. HOMEAXIS(X);
  2081. inactive_extruder_x_pos = current_position[X_AXIS];
  2082. active_extruder = tmp_extruder;
  2083. HOMEAXIS(X);
  2084. // reset state used by the different modes
  2085. memcpy(raised_parked_position, current_position, sizeof(raised_parked_position));
  2086. delayed_move_time = 0;
  2087. active_extruder_parked = true;
  2088. #else
  2089. HOMEAXIS(X);
  2090. #endif
  2091. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2092. if (marlin_debug_flags & DEBUG_LEVELING) {
  2093. print_xyz("> homeX", current_position);
  2094. }
  2095. #endif
  2096. }
  2097. #if DISABLED(HOME_Y_BEFORE_X)
  2098. // Home Y
  2099. if (home_all_axis || homeY) {
  2100. HOMEAXIS(Y);
  2101. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2102. if (marlin_debug_flags & DEBUG_LEVELING) {
  2103. print_xyz("> homeY", current_position);
  2104. }
  2105. #endif
  2106. }
  2107. #endif
  2108. // Home Z last if homing towards the bed
  2109. #if Z_HOME_DIR < 0
  2110. if (home_all_axis || homeZ) {
  2111. #if ENABLED(Z_SAFE_HOMING)
  2112. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2113. if (marlin_debug_flags & DEBUG_LEVELING) {
  2114. SERIAL_ECHOLNPGM("> Z_SAFE_HOMING >>>");
  2115. }
  2116. #endif
  2117. if (home_all_axis) {
  2118. // At this point we already have Z at MIN_Z_HEIGHT_FOR_HOMING height
  2119. // No need to move Z any more as this height should already be safe
  2120. // enough to reach Z_SAFE_HOMING XY positions.
  2121. // Just make sure the planner is in sync.
  2122. sync_plan_position();
  2123. //
  2124. // Set the Z probe (or just the nozzle) destination to the safe homing point
  2125. //
  2126. destination[X_AXIS] = round(Z_SAFE_HOMING_X_POINT - (X_PROBE_OFFSET_FROM_EXTRUDER));
  2127. destination[Y_AXIS] = round(Z_SAFE_HOMING_Y_POINT - (Y_PROBE_OFFSET_FROM_EXTRUDER));
  2128. destination[Z_AXIS] = current_position[Z_AXIS]; //z is already at the right height
  2129. feedrate = XY_TRAVEL_SPEED;
  2130. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2131. if (marlin_debug_flags & DEBUG_LEVELING) {
  2132. print_xyz("> Z_SAFE_HOMING > home_all_axis > current_position", current_position);
  2133. print_xyz("> Z_SAFE_HOMING > home_all_axis > destination", destination);
  2134. }
  2135. #endif
  2136. // Move in the XY plane
  2137. line_to_destination();
  2138. st_synchronize();
  2139. // Update the current positions for XY, Z is still at least at
  2140. // MIN_Z_HEIGHT_FOR_HOMING height, no changes there.
  2141. current_position[X_AXIS] = destination[X_AXIS];
  2142. current_position[Y_AXIS] = destination[Y_AXIS];
  2143. // Home the Z axis
  2144. HOMEAXIS(Z);
  2145. }
  2146. else if (homeZ) { // Don't need to Home Z twice
  2147. // Let's see if X and Y are homed
  2148. if (axis_known_position[X_AXIS] && axis_known_position[Y_AXIS]) {
  2149. // Make sure the Z probe is within the physical limits
  2150. // NOTE: This doesn't necessarily ensure the Z probe is also within the bed!
  2151. float cpx = current_position[X_AXIS], cpy = current_position[Y_AXIS];
  2152. if ( cpx >= X_MIN_POS - (X_PROBE_OFFSET_FROM_EXTRUDER)
  2153. && cpx <= X_MAX_POS - (X_PROBE_OFFSET_FROM_EXTRUDER)
  2154. && cpy >= Y_MIN_POS - (Y_PROBE_OFFSET_FROM_EXTRUDER)
  2155. && cpy <= Y_MAX_POS - (Y_PROBE_OFFSET_FROM_EXTRUDER)) {
  2156. // Home the Z axis
  2157. HOMEAXIS(Z);
  2158. }
  2159. else {
  2160. LCD_MESSAGEPGM(MSG_ZPROBE_OUT);
  2161. SERIAL_ECHO_START;
  2162. SERIAL_ECHOLNPGM(MSG_ZPROBE_OUT);
  2163. }
  2164. }
  2165. else {
  2166. LCD_MESSAGEPGM(MSG_POSITION_UNKNOWN);
  2167. SERIAL_ECHO_START;
  2168. SERIAL_ECHOLNPGM(MSG_POSITION_UNKNOWN);
  2169. }
  2170. } // !home_all_axes && homeZ
  2171. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2172. if (marlin_debug_flags & DEBUG_LEVELING) {
  2173. SERIAL_ECHOLNPGM("<<< Z_SAFE_HOMING");
  2174. }
  2175. #endif
  2176. #else // !Z_SAFE_HOMING
  2177. HOMEAXIS(Z);
  2178. #endif // !Z_SAFE_HOMING
  2179. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2180. if (marlin_debug_flags & DEBUG_LEVELING) {
  2181. print_xyz("> (home_all_axis || homeZ) > final", current_position);
  2182. }
  2183. #endif
  2184. } // home_all_axis || homeZ
  2185. #endif // Z_HOME_DIR < 0
  2186. sync_plan_position();
  2187. #endif // else DELTA
  2188. #if ENABLED(SCARA)
  2189. sync_plan_position_delta();
  2190. #endif
  2191. #if ENABLED(ENDSTOPS_ONLY_FOR_HOMING)
  2192. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2193. if (marlin_debug_flags & DEBUG_LEVELING) {
  2194. SERIAL_ECHOLNPGM("ENDSTOPS_ONLY_FOR_HOMING enable_endstops(false)");
  2195. }
  2196. #endif
  2197. enable_endstops(false);
  2198. #endif
  2199. // For manual leveling move back to 0,0
  2200. #if ENABLED(MESH_BED_LEVELING)
  2201. if (mbl_was_active) {
  2202. current_position[X_AXIS] = mbl.get_x(0);
  2203. current_position[Y_AXIS] = mbl.get_y(0);
  2204. set_destination_to_current();
  2205. feedrate = homing_feedrate[X_AXIS];
  2206. line_to_destination();
  2207. st_synchronize();
  2208. current_position[Z_AXIS] = MESH_HOME_SEARCH_Z;
  2209. sync_plan_position();
  2210. mbl.active = 1;
  2211. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2212. if (marlin_debug_flags & DEBUG_LEVELING) {
  2213. print_xyz("mbl_was_active > current_position", current_position);
  2214. }
  2215. #endif
  2216. }
  2217. #endif
  2218. feedrate = saved_feedrate;
  2219. feedrate_multiplier = saved_feedrate_multiplier;
  2220. refresh_cmd_timeout();
  2221. endstops_hit_on_purpose(); // clear endstop hit flags
  2222. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2223. if (marlin_debug_flags & DEBUG_LEVELING) {
  2224. SERIAL_ECHOLNPGM("<<< gcode_G28");
  2225. }
  2226. #endif
  2227. }
  2228. #if ENABLED(MESH_BED_LEVELING)
  2229. enum MeshLevelingState { MeshReport, MeshStart, MeshNext, MeshSet };
  2230. /**
  2231. * G29: Mesh-based Z probe, probes a grid and produces a
  2232. * mesh to compensate for variable bed height
  2233. *
  2234. * Parameters With MESH_BED_LEVELING:
  2235. *
  2236. * S0 Produce a mesh report
  2237. * S1 Start probing mesh points
  2238. * S2 Probe the next mesh point
  2239. * S3 Xn Yn Zn.nn Manually modify a single point
  2240. *
  2241. * The S0 report the points as below
  2242. *
  2243. * +----> X-axis
  2244. * |
  2245. * |
  2246. * v Y-axis
  2247. *
  2248. */
  2249. inline void gcode_G29() {
  2250. static int probe_point = -1;
  2251. MeshLevelingState state = code_seen('S') ? (MeshLevelingState)code_value_short() : MeshReport;
  2252. if (state < 0 || state > 3) {
  2253. SERIAL_PROTOCOLLNPGM("S out of range (0-3).");
  2254. return;
  2255. }
  2256. int ix, iy;
  2257. float z;
  2258. switch (state) {
  2259. case MeshReport:
  2260. if (mbl.active) {
  2261. SERIAL_PROTOCOLPGM("Num X,Y: ");
  2262. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  2263. SERIAL_PROTOCOLCHAR(',');
  2264. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  2265. SERIAL_PROTOCOLPGM("\nZ search height: ");
  2266. SERIAL_PROTOCOL(MESH_HOME_SEARCH_Z);
  2267. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  2268. for (int y = 0; y < MESH_NUM_Y_POINTS; y++) {
  2269. for (int x = 0; x < MESH_NUM_X_POINTS; x++) {
  2270. SERIAL_PROTOCOLPGM(" ");
  2271. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  2272. }
  2273. SERIAL_EOL;
  2274. }
  2275. }
  2276. else
  2277. SERIAL_PROTOCOLLNPGM("Mesh bed leveling not active.");
  2278. break;
  2279. case MeshStart:
  2280. mbl.reset();
  2281. probe_point = 0;
  2282. enqueue_and_echo_commands_P(PSTR("G28\nG29 S2"));
  2283. break;
  2284. case MeshNext:
  2285. if (probe_point < 0) {
  2286. SERIAL_PROTOCOLLNPGM("Start mesh probing with \"G29 S1\" first.");
  2287. return;
  2288. }
  2289. if (probe_point == 0) {
  2290. // Set Z to a positive value before recording the first Z.
  2291. current_position[Z_AXIS] = MESH_HOME_SEARCH_Z;
  2292. sync_plan_position();
  2293. }
  2294. else {
  2295. // For others, save the Z of the previous point, then raise Z again.
  2296. ix = (probe_point - 1) % (MESH_NUM_X_POINTS);
  2297. iy = (probe_point - 1) / (MESH_NUM_X_POINTS);
  2298. if (iy & 1) ix = (MESH_NUM_X_POINTS - 1) - ix; // zig-zag
  2299. mbl.set_z(ix, iy, current_position[Z_AXIS]);
  2300. current_position[Z_AXIS] = MESH_HOME_SEARCH_Z;
  2301. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], homing_feedrate[X_AXIS] / 60, active_extruder);
  2302. st_synchronize();
  2303. }
  2304. // Is there another point to sample? Move there.
  2305. if (probe_point < (MESH_NUM_X_POINTS) * (MESH_NUM_Y_POINTS)) {
  2306. ix = probe_point % (MESH_NUM_X_POINTS);
  2307. iy = probe_point / (MESH_NUM_X_POINTS);
  2308. if (iy & 1) ix = (MESH_NUM_X_POINTS - 1) - ix; // zig-zag
  2309. current_position[X_AXIS] = mbl.get_x(ix);
  2310. current_position[Y_AXIS] = mbl.get_y(iy);
  2311. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], homing_feedrate[X_AXIS] / 60, active_extruder);
  2312. st_synchronize();
  2313. probe_point++;
  2314. }
  2315. else {
  2316. // After recording the last point, activate the mbl and home
  2317. SERIAL_PROTOCOLLNPGM("Mesh probing done.");
  2318. probe_point = -1;
  2319. mbl.active = 1;
  2320. enqueue_and_echo_commands_P(PSTR("G28"));
  2321. }
  2322. break;
  2323. case MeshSet:
  2324. if (code_seen('X')) {
  2325. ix = code_value_long() - 1;
  2326. if (ix < 0 || ix >= MESH_NUM_X_POINTS) {
  2327. SERIAL_PROTOCOLPGM("X out of range (1-" STRINGIFY(MESH_NUM_X_POINTS) ").\n");
  2328. return;
  2329. }
  2330. }
  2331. else {
  2332. SERIAL_PROTOCOLPGM("X not entered.\n");
  2333. return;
  2334. }
  2335. if (code_seen('Y')) {
  2336. iy = code_value_long() - 1;
  2337. if (iy < 0 || iy >= MESH_NUM_Y_POINTS) {
  2338. SERIAL_PROTOCOLPGM("Y out of range (1-" STRINGIFY(MESH_NUM_Y_POINTS) ").\n");
  2339. return;
  2340. }
  2341. }
  2342. else {
  2343. SERIAL_PROTOCOLPGM("Y not entered.\n");
  2344. return;
  2345. }
  2346. if (code_seen('Z')) {
  2347. z = code_value();
  2348. }
  2349. else {
  2350. SERIAL_PROTOCOLPGM("Z not entered.\n");
  2351. return;
  2352. }
  2353. mbl.z_values[iy][ix] = z;
  2354. } // switch(state)
  2355. }
  2356. #elif ENABLED(AUTO_BED_LEVELING_FEATURE)
  2357. void out_of_range_error(const char* p_edge) {
  2358. SERIAL_PROTOCOLPGM("?Probe ");
  2359. serialprintPGM(p_edge);
  2360. SERIAL_PROTOCOLLNPGM(" position out of range.");
  2361. }
  2362. /**
  2363. * G29: Detailed Z probe, probes the bed at 3 or more points.
  2364. * Will fail if the printer has not been homed with G28.
  2365. *
  2366. * Enhanced G29 Auto Bed Leveling Probe Routine
  2367. *
  2368. * Parameters With AUTO_BED_LEVELING_GRID:
  2369. *
  2370. * P Set the size of the grid that will be probed (P x P points).
  2371. * Not supported by non-linear delta printer bed leveling.
  2372. * Example: "G29 P4"
  2373. *
  2374. * S Set the XY travel speed between probe points (in mm/min)
  2375. *
  2376. * D Dry-Run mode. Just evaluate the bed Topology - Don't apply
  2377. * or clean the rotation Matrix. Useful to check the topology
  2378. * after a first run of G29.
  2379. *
  2380. * V Set the verbose level (0-4). Example: "G29 V3"
  2381. *
  2382. * T Generate a Bed Topology Report. Example: "G29 P5 T" for a detailed report.
  2383. * This is useful for manual bed leveling and finding flaws in the bed (to
  2384. * assist with part placement).
  2385. * Not supported by non-linear delta printer bed leveling.
  2386. *
  2387. * F Set the Front limit of the probing grid
  2388. * B Set the Back limit of the probing grid
  2389. * L Set the Left limit of the probing grid
  2390. * R Set the Right limit of the probing grid
  2391. *
  2392. * Global Parameters:
  2393. *
  2394. * E/e By default G29 will engage the Z probe, test the bed, then disengage.
  2395. * Include "E" to engage/disengage the Z probe for each sample.
  2396. * There's no extra effect if you have a fixed Z probe.
  2397. * Usage: "G29 E" or "G29 e"
  2398. *
  2399. */
  2400. inline void gcode_G29() {
  2401. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2402. if (marlin_debug_flags & DEBUG_LEVELING) {
  2403. SERIAL_ECHOLNPGM("gcode_G29 >>>");
  2404. }
  2405. #endif
  2406. // Don't allow auto-leveling without homing first
  2407. if (!axis_known_position[X_AXIS] || !axis_known_position[Y_AXIS]) {
  2408. LCD_MESSAGEPGM(MSG_POSITION_UNKNOWN);
  2409. SERIAL_ECHO_START;
  2410. SERIAL_ECHOLNPGM(MSG_POSITION_UNKNOWN);
  2411. return;
  2412. }
  2413. int verbose_level = code_seen('V') ? code_value_short() : 1;
  2414. if (verbose_level < 0 || verbose_level > 4) {
  2415. SERIAL_ECHOLNPGM("?(V)erbose Level is implausible (0-4).");
  2416. return;
  2417. }
  2418. bool dryrun = code_seen('D'),
  2419. deploy_probe_for_each_reading = code_seen('E');
  2420. #if ENABLED(AUTO_BED_LEVELING_GRID)
  2421. #if DISABLED(DELTA)
  2422. bool do_topography_map = verbose_level > 2 || code_seen('T');
  2423. #endif
  2424. if (verbose_level > 0) {
  2425. SERIAL_PROTOCOLPGM("G29 Auto Bed Leveling\n");
  2426. if (dryrun) SERIAL_ECHOLNPGM("Running in DRY-RUN mode");
  2427. }
  2428. int auto_bed_leveling_grid_points = AUTO_BED_LEVELING_GRID_POINTS;
  2429. #if DISABLED(DELTA)
  2430. if (code_seen('P')) auto_bed_leveling_grid_points = code_value_short();
  2431. if (auto_bed_leveling_grid_points < 2) {
  2432. SERIAL_PROTOCOLPGM("?Number of probed (P)oints is implausible (2 minimum).\n");
  2433. return;
  2434. }
  2435. #endif
  2436. xy_travel_speed = code_seen('S') ? code_value_short() : XY_TRAVEL_SPEED;
  2437. int left_probe_bed_position = code_seen('L') ? code_value_short() : LEFT_PROBE_BED_POSITION,
  2438. right_probe_bed_position = code_seen('R') ? code_value_short() : RIGHT_PROBE_BED_POSITION,
  2439. front_probe_bed_position = code_seen('F') ? code_value_short() : FRONT_PROBE_BED_POSITION,
  2440. back_probe_bed_position = code_seen('B') ? code_value_short() : BACK_PROBE_BED_POSITION;
  2441. bool left_out_l = left_probe_bed_position < MIN_PROBE_X,
  2442. left_out = left_out_l || left_probe_bed_position > right_probe_bed_position - (MIN_PROBE_EDGE),
  2443. right_out_r = right_probe_bed_position > MAX_PROBE_X,
  2444. right_out = right_out_r || right_probe_bed_position < left_probe_bed_position + MIN_PROBE_EDGE,
  2445. front_out_f = front_probe_bed_position < MIN_PROBE_Y,
  2446. front_out = front_out_f || front_probe_bed_position > back_probe_bed_position - (MIN_PROBE_EDGE),
  2447. back_out_b = back_probe_bed_position > MAX_PROBE_Y,
  2448. back_out = back_out_b || back_probe_bed_position < front_probe_bed_position + MIN_PROBE_EDGE;
  2449. if (left_out || right_out || front_out || back_out) {
  2450. if (left_out) {
  2451. out_of_range_error(PSTR("(L)eft"));
  2452. left_probe_bed_position = left_out_l ? MIN_PROBE_X : right_probe_bed_position - (MIN_PROBE_EDGE);
  2453. }
  2454. if (right_out) {
  2455. out_of_range_error(PSTR("(R)ight"));
  2456. right_probe_bed_position = right_out_r ? MAX_PROBE_X : left_probe_bed_position + MIN_PROBE_EDGE;
  2457. }
  2458. if (front_out) {
  2459. out_of_range_error(PSTR("(F)ront"));
  2460. front_probe_bed_position = front_out_f ? MIN_PROBE_Y : back_probe_bed_position - (MIN_PROBE_EDGE);
  2461. }
  2462. if (back_out) {
  2463. out_of_range_error(PSTR("(B)ack"));
  2464. back_probe_bed_position = back_out_b ? MAX_PROBE_Y : front_probe_bed_position + MIN_PROBE_EDGE;
  2465. }
  2466. return;
  2467. }
  2468. #endif // AUTO_BED_LEVELING_GRID
  2469. #if ENABLED(Z_PROBE_SLED)
  2470. dock_sled(false); // engage (un-dock) the Z probe
  2471. #elif ENABLED(Z_PROBE_ALLEN_KEY) //|| SERVO_LEVELING
  2472. deploy_z_probe();
  2473. #endif
  2474. st_synchronize();
  2475. if (!dryrun) {
  2476. // make sure the bed_level_rotation_matrix is identity or the planner will get it wrong
  2477. plan_bed_level_matrix.set_to_identity();
  2478. #if ENABLED(DELTA)
  2479. reset_bed_level();
  2480. #else //!DELTA
  2481. //vector_3 corrected_position = plan_get_position_mm();
  2482. //corrected_position.debug("position before G29");
  2483. vector_3 uncorrected_position = plan_get_position();
  2484. //uncorrected_position.debug("position during G29");
  2485. current_position[X_AXIS] = uncorrected_position.x;
  2486. current_position[Y_AXIS] = uncorrected_position.y;
  2487. current_position[Z_AXIS] = uncorrected_position.z;
  2488. sync_plan_position();
  2489. #endif // !DELTA
  2490. }
  2491. setup_for_endstop_move();
  2492. feedrate = homing_feedrate[Z_AXIS];
  2493. #if ENABLED(AUTO_BED_LEVELING_GRID)
  2494. // probe at the points of a lattice grid
  2495. const int xGridSpacing = (right_probe_bed_position - left_probe_bed_position) / (auto_bed_leveling_grid_points - 1),
  2496. yGridSpacing = (back_probe_bed_position - front_probe_bed_position) / (auto_bed_leveling_grid_points - 1);
  2497. #if ENABLED(DELTA)
  2498. delta_grid_spacing[0] = xGridSpacing;
  2499. delta_grid_spacing[1] = yGridSpacing;
  2500. float z_offset = zprobe_zoffset;
  2501. if (code_seen(axis_codes[Z_AXIS])) z_offset += code_value();
  2502. #else // !DELTA
  2503. // solve the plane equation ax + by + d = z
  2504. // A is the matrix with rows [x y 1] for all the probed points
  2505. // B is the vector of the Z positions
  2506. // the normal vector to the plane is formed by the coefficients of the plane equation in the standard form, which is Vx*x+Vy*y+Vz*z+d = 0
  2507. // so Vx = -a Vy = -b Vz = 1 (we want the vector facing towards positive Z
  2508. int abl2 = auto_bed_leveling_grid_points * auto_bed_leveling_grid_points;
  2509. double eqnAMatrix[abl2 * 3], // "A" matrix of the linear system of equations
  2510. eqnBVector[abl2], // "B" vector of Z points
  2511. mean = 0.0;
  2512. int8_t indexIntoAB[auto_bed_leveling_grid_points][auto_bed_leveling_grid_points];
  2513. #endif // !DELTA
  2514. int probePointCounter = 0;
  2515. bool zig = (auto_bed_leveling_grid_points & 1) ? true : false; //always end at [RIGHT_PROBE_BED_POSITION, BACK_PROBE_BED_POSITION]
  2516. for (int yCount = 0; yCount < auto_bed_leveling_grid_points; yCount++) {
  2517. double yProbe = front_probe_bed_position + yGridSpacing * yCount;
  2518. int xStart, xStop, xInc;
  2519. if (zig) {
  2520. xStart = 0;
  2521. xStop = auto_bed_leveling_grid_points;
  2522. xInc = 1;
  2523. }
  2524. else {
  2525. xStart = auto_bed_leveling_grid_points - 1;
  2526. xStop = -1;
  2527. xInc = -1;
  2528. }
  2529. zig = !zig;
  2530. for (int xCount = xStart; xCount != xStop; xCount += xInc) {
  2531. double xProbe = left_probe_bed_position + xGridSpacing * xCount;
  2532. // raise extruder
  2533. float measured_z,
  2534. z_before = probePointCounter ? Z_RAISE_BETWEEN_PROBINGS + current_position[Z_AXIS] : Z_RAISE_BEFORE_PROBING;
  2535. if (probePointCounter) {
  2536. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2537. if (marlin_debug_flags & DEBUG_LEVELING) {
  2538. SERIAL_ECHOPAIR("z_before = (between) ", (float)(Z_RAISE_BETWEEN_PROBINGS + current_position[Z_AXIS]));
  2539. SERIAL_EOL;
  2540. }
  2541. #endif
  2542. }
  2543. else {
  2544. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2545. if (marlin_debug_flags & DEBUG_LEVELING) {
  2546. SERIAL_ECHOPAIR("z_before = (before) ", (float)Z_RAISE_BEFORE_PROBING);
  2547. SERIAL_EOL;
  2548. }
  2549. #endif
  2550. }
  2551. #if ENABLED(DELTA)
  2552. // Avoid probing the corners (outside the round or hexagon print surface) on a delta printer.
  2553. float distance_from_center = sqrt(xProbe * xProbe + yProbe * yProbe);
  2554. if (distance_from_center > DELTA_PROBABLE_RADIUS) continue;
  2555. #endif //DELTA
  2556. ProbeAction act;
  2557. if (deploy_probe_for_each_reading) // G29 E - Stow between probes
  2558. act = ProbeDeployAndStow;
  2559. else if (yCount == 0 && xCount == xStart)
  2560. act = ProbeDeploy;
  2561. else if (yCount == auto_bed_leveling_grid_points - 1 && xCount == xStop - xInc)
  2562. act = ProbeStow;
  2563. else
  2564. act = ProbeStay;
  2565. measured_z = probe_pt(xProbe, yProbe, z_before, act, verbose_level);
  2566. #if DISABLED(DELTA)
  2567. mean += measured_z;
  2568. eqnBVector[probePointCounter] = measured_z;
  2569. eqnAMatrix[probePointCounter + 0 * abl2] = xProbe;
  2570. eqnAMatrix[probePointCounter + 1 * abl2] = yProbe;
  2571. eqnAMatrix[probePointCounter + 2 * abl2] = 1;
  2572. indexIntoAB[xCount][yCount] = probePointCounter;
  2573. #else
  2574. bed_level[xCount][yCount] = measured_z + z_offset;
  2575. #endif
  2576. probePointCounter++;
  2577. idle();
  2578. } //xProbe
  2579. } //yProbe
  2580. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2581. if (marlin_debug_flags & DEBUG_LEVELING) {
  2582. print_xyz("> probing complete > current_position", current_position);
  2583. }
  2584. #endif
  2585. clean_up_after_endstop_move();
  2586. #if ENABLED(DELTA)
  2587. if (!dryrun) extrapolate_unprobed_bed_level();
  2588. print_bed_level();
  2589. #else // !DELTA
  2590. // solve lsq problem
  2591. double plane_equation_coefficients[3];
  2592. qr_solve(plane_equation_coefficients, abl2, 3, eqnAMatrix, eqnBVector);
  2593. mean /= abl2;
  2594. if (verbose_level) {
  2595. SERIAL_PROTOCOLPGM("Eqn coefficients: a: ");
  2596. SERIAL_PROTOCOL_F(plane_equation_coefficients[0], 8);
  2597. SERIAL_PROTOCOLPGM(" b: ");
  2598. SERIAL_PROTOCOL_F(plane_equation_coefficients[1], 8);
  2599. SERIAL_PROTOCOLPGM(" d: ");
  2600. SERIAL_PROTOCOL_F(plane_equation_coefficients[2], 8);
  2601. SERIAL_EOL;
  2602. if (verbose_level > 2) {
  2603. SERIAL_PROTOCOLPGM("Mean of sampled points: ");
  2604. SERIAL_PROTOCOL_F(mean, 8);
  2605. SERIAL_EOL;
  2606. }
  2607. }
  2608. if (!dryrun) set_bed_level_equation_lsq(plane_equation_coefficients);
  2609. // Show the Topography map if enabled
  2610. if (do_topography_map) {
  2611. SERIAL_PROTOCOLPGM(" \nBed Height Topography: \n");
  2612. SERIAL_PROTOCOLPGM(" +--- BACK --+\n");
  2613. SERIAL_PROTOCOLPGM(" | |\n");
  2614. SERIAL_PROTOCOLPGM(" L | (+) | R\n");
  2615. SERIAL_PROTOCOLPGM(" E | | I\n");
  2616. SERIAL_PROTOCOLPGM(" F | (-) N (+) | G\n");
  2617. SERIAL_PROTOCOLPGM(" T | | H\n");
  2618. SERIAL_PROTOCOLPGM(" | (-) | T\n");
  2619. SERIAL_PROTOCOLPGM(" | |\n");
  2620. SERIAL_PROTOCOLPGM(" O-- FRONT --+\n");
  2621. SERIAL_PROTOCOLPGM(" (0,0)\n");
  2622. float min_diff = 999;
  2623. for (int yy = auto_bed_leveling_grid_points - 1; yy >= 0; yy--) {
  2624. for (int xx = 0; xx < auto_bed_leveling_grid_points; xx++) {
  2625. int ind = indexIntoAB[xx][yy];
  2626. float diff = eqnBVector[ind] - mean;
  2627. float x_tmp = eqnAMatrix[ind + 0 * abl2],
  2628. y_tmp = eqnAMatrix[ind + 1 * abl2],
  2629. z_tmp = 0;
  2630. apply_rotation_xyz(plan_bed_level_matrix, x_tmp, y_tmp, z_tmp);
  2631. NOMORE(min_diff, eqnBVector[ind] - z_tmp);
  2632. if (diff >= 0.0)
  2633. SERIAL_PROTOCOLPGM(" +"); // Include + for column alignment
  2634. else
  2635. SERIAL_PROTOCOLCHAR(' ');
  2636. SERIAL_PROTOCOL_F(diff, 5);
  2637. } // xx
  2638. SERIAL_EOL;
  2639. } // yy
  2640. SERIAL_EOL;
  2641. if (verbose_level > 3) {
  2642. SERIAL_PROTOCOLPGM(" \nCorrected Bed Height vs. Bed Topology: \n");
  2643. for (int yy = auto_bed_leveling_grid_points - 1; yy >= 0; yy--) {
  2644. for (int xx = 0; xx < auto_bed_leveling_grid_points; xx++) {
  2645. int ind = indexIntoAB[xx][yy];
  2646. float x_tmp = eqnAMatrix[ind + 0 * abl2],
  2647. y_tmp = eqnAMatrix[ind + 1 * abl2],
  2648. z_tmp = 0;
  2649. apply_rotation_xyz(plan_bed_level_matrix, x_tmp, y_tmp, z_tmp);
  2650. float diff = eqnBVector[ind] - z_tmp - min_diff;
  2651. if (diff >= 0.0)
  2652. SERIAL_PROTOCOLPGM(" +");
  2653. // Include + for column alignment
  2654. else
  2655. SERIAL_PROTOCOLCHAR(' ');
  2656. SERIAL_PROTOCOL_F(diff, 5);
  2657. } // xx
  2658. SERIAL_EOL;
  2659. } // yy
  2660. SERIAL_EOL;
  2661. }
  2662. } //do_topography_map
  2663. #endif //!DELTA
  2664. #else // !AUTO_BED_LEVELING_GRID
  2665. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2666. if (marlin_debug_flags & DEBUG_LEVELING) {
  2667. SERIAL_ECHOLNPGM("> 3-point Leveling");
  2668. }
  2669. #endif
  2670. // Actions for each probe
  2671. ProbeAction p1, p2, p3;
  2672. if (deploy_probe_for_each_reading)
  2673. p1 = p2 = p3 = ProbeDeployAndStow;
  2674. else
  2675. p1 = ProbeDeploy, p2 = ProbeStay, p3 = ProbeStow;
  2676. // Probe at 3 arbitrary points
  2677. float z_at_pt_1 = probe_pt(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, Z_RAISE_BEFORE_PROBING, p1, verbose_level),
  2678. z_at_pt_2 = probe_pt(ABL_PROBE_PT_2_X, ABL_PROBE_PT_2_Y, current_position[Z_AXIS] + Z_RAISE_BETWEEN_PROBINGS, p2, verbose_level),
  2679. z_at_pt_3 = probe_pt(ABL_PROBE_PT_3_X, ABL_PROBE_PT_3_Y, current_position[Z_AXIS] + Z_RAISE_BETWEEN_PROBINGS, p3, verbose_level);
  2680. clean_up_after_endstop_move();
  2681. if (!dryrun) set_bed_level_equation_3pts(z_at_pt_1, z_at_pt_2, z_at_pt_3);
  2682. #endif // !AUTO_BED_LEVELING_GRID
  2683. #if ENABLED(DELTA)
  2684. // Allen Key Probe for Delta
  2685. #if ENABLED(Z_PROBE_ALLEN_KEY)
  2686. stow_z_probe();
  2687. #elif Z_RAISE_AFTER_PROBING > 0
  2688. raise_z_after_probing();
  2689. #endif
  2690. #else // !DELTA
  2691. if (verbose_level > 0)
  2692. plan_bed_level_matrix.debug(" \n\nBed Level Correction Matrix:");
  2693. if (!dryrun) {
  2694. // Correct the Z height difference from Z probe position and nozzle tip position.
  2695. // The Z height on homing is measured by Z probe, but the Z probe is quite far from the nozzle.
  2696. // When the bed is uneven, this height must be corrected.
  2697. float x_tmp = current_position[X_AXIS] + X_PROBE_OFFSET_FROM_EXTRUDER,
  2698. y_tmp = current_position[Y_AXIS] + Y_PROBE_OFFSET_FROM_EXTRUDER,
  2699. z_tmp = current_position[Z_AXIS],
  2700. real_z = st_get_axis_position_mm(Z_AXIS); //get the real Z (since plan_get_position is now correcting the plane)
  2701. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2702. if (marlin_debug_flags & DEBUG_LEVELING) {
  2703. SERIAL_ECHOPAIR("> BEFORE apply_rotation_xyz > z_tmp = ", z_tmp);
  2704. SERIAL_EOL;
  2705. SERIAL_ECHOPAIR("> BEFORE apply_rotation_xyz > real_z = ", real_z);
  2706. SERIAL_EOL;
  2707. }
  2708. #endif
  2709. apply_rotation_xyz(plan_bed_level_matrix, x_tmp, y_tmp, z_tmp); // Apply the correction sending the Z probe offset
  2710. // Get the current Z position and send it to the planner.
  2711. //
  2712. // >> (z_tmp - real_z) : The rotated current Z minus the uncorrected Z (most recent plan_set_position/sync_plan_position)
  2713. //
  2714. // >> zprobe_zoffset : Z distance from nozzle to Z probe (set by default, M851, EEPROM, or Menu)
  2715. //
  2716. // >> Z_RAISE_AFTER_PROBING : The distance the Z probe will have lifted after the last probe
  2717. //
  2718. // >> Should home_offset[Z_AXIS] be included?
  2719. //
  2720. // Discussion: home_offset[Z_AXIS] was applied in G28 to set the starting Z.
  2721. // If Z is not tweaked in G29 -and- the Z probe in G29 is not actually "homing" Z...
  2722. // then perhaps it should not be included here. The purpose of home_offset[] is to
  2723. // adjust for inaccurate endstops, not for reasonably accurate probes. If it were
  2724. // added here, it could be seen as a compensating factor for the Z probe.
  2725. //
  2726. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2727. if (marlin_debug_flags & DEBUG_LEVELING) {
  2728. SERIAL_ECHOPAIR("> AFTER apply_rotation_xyz > z_tmp = ", z_tmp);
  2729. SERIAL_EOL;
  2730. }
  2731. #endif
  2732. current_position[Z_AXIS] = -zprobe_zoffset + (z_tmp - real_z)
  2733. #if HAS_SERVO_ENDSTOPS || ENABLED(Z_PROBE_ALLEN_KEY) || ENABLED(Z_PROBE_SLED)
  2734. + Z_RAISE_AFTER_PROBING
  2735. #endif
  2736. ;
  2737. // current_position[Z_AXIS] += home_offset[Z_AXIS]; // The Z probe determines Z=0, not "Z home"
  2738. sync_plan_position();
  2739. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2740. if (marlin_debug_flags & DEBUG_LEVELING) {
  2741. print_xyz("> corrected Z in G29", current_position);
  2742. }
  2743. #endif
  2744. }
  2745. // Sled assembly for Cartesian bots
  2746. #if ENABLED(Z_PROBE_SLED)
  2747. dock_sled(true); // dock the sled
  2748. #elif Z_RAISE_AFTER_PROBING > 0
  2749. // Raise Z axis for non-delta and non servo based probes
  2750. #if !defined(HAS_SERVO_ENDSTOPS) && DISABLED(Z_PROBE_ALLEN_KEY) && DISABLED(Z_PROBE_SLED)
  2751. raise_z_after_probing();
  2752. #endif
  2753. #endif
  2754. #endif // !DELTA
  2755. #ifdef Z_PROBE_END_SCRIPT
  2756. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2757. if (marlin_debug_flags & DEBUG_LEVELING) {
  2758. SERIAL_ECHO("Z Probe End Script: ");
  2759. SERIAL_ECHOLNPGM(Z_PROBE_END_SCRIPT);
  2760. }
  2761. #endif
  2762. enqueue_and_echo_commands_P(PSTR(Z_PROBE_END_SCRIPT));
  2763. st_synchronize();
  2764. #endif
  2765. KEEPALIVE_STATE(IN_HANDLER);
  2766. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2767. if (marlin_debug_flags & DEBUG_LEVELING) {
  2768. SERIAL_ECHOLNPGM("<<< gcode_G29");
  2769. }
  2770. #endif
  2771. }
  2772. #if DISABLED(Z_PROBE_SLED)
  2773. /**
  2774. * G30: Do a single Z probe at the current XY
  2775. */
  2776. inline void gcode_G30() {
  2777. #if HAS_SERVO_ENDSTOPS
  2778. raise_z_for_servo();
  2779. #endif
  2780. deploy_z_probe(); // Engage Z Servo endstop if available
  2781. st_synchronize();
  2782. // TODO: clear the leveling matrix or the planner will be set incorrectly
  2783. setup_for_endstop_move();
  2784. feedrate = homing_feedrate[Z_AXIS];
  2785. run_z_probe();
  2786. SERIAL_PROTOCOLPGM("Bed X: ");
  2787. SERIAL_PROTOCOL(current_position[X_AXIS] + 0.0001);
  2788. SERIAL_PROTOCOLPGM(" Y: ");
  2789. SERIAL_PROTOCOL(current_position[Y_AXIS] + 0.0001);
  2790. SERIAL_PROTOCOLPGM(" Z: ");
  2791. SERIAL_PROTOCOL(current_position[Z_AXIS] + 0.0001);
  2792. SERIAL_EOL;
  2793. clean_up_after_endstop_move();
  2794. #if HAS_SERVO_ENDSTOPS
  2795. raise_z_for_servo();
  2796. #endif
  2797. stow_z_probe(false); // Retract Z Servo endstop if available
  2798. }
  2799. #endif //!Z_PROBE_SLED
  2800. #endif //AUTO_BED_LEVELING_FEATURE
  2801. /**
  2802. * G92: Set current position to given X Y Z E
  2803. */
  2804. inline void gcode_G92() {
  2805. if (!code_seen(axis_codes[E_AXIS]))
  2806. st_synchronize();
  2807. bool didXYZ = false;
  2808. for (int i = 0; i < NUM_AXIS; i++) {
  2809. if (code_seen(axis_codes[i])) {
  2810. float v = current_position[i] = code_value();
  2811. if (i == E_AXIS)
  2812. plan_set_e_position(v);
  2813. else
  2814. didXYZ = true;
  2815. }
  2816. }
  2817. if (didXYZ) {
  2818. #if ENABLED(DELTA) || ENABLED(SCARA)
  2819. sync_plan_position_delta();
  2820. #else
  2821. sync_plan_position();
  2822. #endif
  2823. }
  2824. }
  2825. #if ENABLED(ULTIPANEL)
  2826. /**
  2827. * M0: // M0 - Unconditional stop - Wait for user button press on LCD
  2828. * M1: // M1 - Conditional stop - Wait for user button press on LCD
  2829. */
  2830. inline void gcode_M0_M1() {
  2831. char* args = current_command_args;
  2832. millis_t codenum = 0;
  2833. bool hasP = false, hasS = false;
  2834. if (code_seen('P')) {
  2835. codenum = code_value_short(); // milliseconds to wait
  2836. hasP = codenum > 0;
  2837. }
  2838. if (code_seen('S')) {
  2839. codenum = code_value() * 1000; // seconds to wait
  2840. hasS = codenum > 0;
  2841. }
  2842. if (!hasP && !hasS && *args != '\0')
  2843. lcd_setstatus(args, true);
  2844. else {
  2845. LCD_MESSAGEPGM(MSG_USERWAIT);
  2846. #if ENABLED(LCD_PROGRESS_BAR) && PROGRESS_MSG_EXPIRE > 0
  2847. dontExpireStatus();
  2848. #endif
  2849. }
  2850. lcd_ignore_click();
  2851. st_synchronize();
  2852. refresh_cmd_timeout();
  2853. if (codenum > 0) {
  2854. codenum += previous_cmd_ms; // wait until this time for a click
  2855. KEEPALIVE_STATE(PAUSED_FOR_USER);
  2856. while (millis() < codenum && !lcd_clicked()) idle();
  2857. KEEPALIVE_STATE(IN_HANDLER);
  2858. lcd_ignore_click(false);
  2859. }
  2860. else {
  2861. if (!lcd_detected()) return;
  2862. KEEPALIVE_STATE(PAUSED_FOR_USER);
  2863. while (!lcd_clicked()) idle();
  2864. KEEPALIVE_STATE(IN_HANDLER);
  2865. }
  2866. if (IS_SD_PRINTING)
  2867. LCD_MESSAGEPGM(MSG_RESUMING);
  2868. else
  2869. LCD_MESSAGEPGM(WELCOME_MSG);
  2870. }
  2871. #endif // ULTIPANEL
  2872. /**
  2873. * M17: Enable power on all stepper motors
  2874. */
  2875. inline void gcode_M17() {
  2876. LCD_MESSAGEPGM(MSG_NO_MOVE);
  2877. enable_all_steppers();
  2878. }
  2879. #if ENABLED(SDSUPPORT)
  2880. /**
  2881. * M20: List SD card to serial output
  2882. */
  2883. inline void gcode_M20() {
  2884. SERIAL_PROTOCOLLNPGM(MSG_BEGIN_FILE_LIST);
  2885. card.ls();
  2886. SERIAL_PROTOCOLLNPGM(MSG_END_FILE_LIST);
  2887. }
  2888. /**
  2889. * M21: Init SD Card
  2890. */
  2891. inline void gcode_M21() {
  2892. card.initsd();
  2893. }
  2894. /**
  2895. * M22: Release SD Card
  2896. */
  2897. inline void gcode_M22() {
  2898. card.release();
  2899. }
  2900. /**
  2901. * M23: Open a file
  2902. */
  2903. inline void gcode_M23() {
  2904. card.openFile(current_command_args, true);
  2905. }
  2906. /**
  2907. * M24: Start SD Print
  2908. */
  2909. inline void gcode_M24() {
  2910. card.startFileprint();
  2911. print_job_start_ms = millis();
  2912. }
  2913. /**
  2914. * M25: Pause SD Print
  2915. */
  2916. inline void gcode_M25() {
  2917. card.pauseSDPrint();
  2918. }
  2919. /**
  2920. * M26: Set SD Card file index
  2921. */
  2922. inline void gcode_M26() {
  2923. if (card.cardOK && code_seen('S'))
  2924. card.setIndex(code_value_short());
  2925. }
  2926. /**
  2927. * M27: Get SD Card status
  2928. */
  2929. inline void gcode_M27() {
  2930. card.getStatus();
  2931. }
  2932. /**
  2933. * M28: Start SD Write
  2934. */
  2935. inline void gcode_M28() {
  2936. card.openFile(current_command_args, false);
  2937. }
  2938. /**
  2939. * M29: Stop SD Write
  2940. * Processed in write to file routine above
  2941. */
  2942. inline void gcode_M29() {
  2943. // card.saving = false;
  2944. }
  2945. /**
  2946. * M30 <filename>: Delete SD Card file
  2947. */
  2948. inline void gcode_M30() {
  2949. if (card.cardOK) {
  2950. card.closefile();
  2951. card.removeFile(current_command_args);
  2952. }
  2953. }
  2954. #endif //SDSUPPORT
  2955. /**
  2956. * M31: Get the time since the start of SD Print (or last M109)
  2957. */
  2958. inline void gcode_M31() {
  2959. print_job_stop_ms = millis();
  2960. millis_t t = (print_job_stop_ms - print_job_start_ms) / 1000;
  2961. int min = t / 60, sec = t % 60;
  2962. char time[30];
  2963. sprintf_P(time, PSTR("%i min, %i sec"), min, sec);
  2964. SERIAL_ECHO_START;
  2965. SERIAL_ECHOLN(time);
  2966. lcd_setstatus(time);
  2967. autotempShutdown();
  2968. }
  2969. #if ENABLED(SDSUPPORT)
  2970. /**
  2971. * M32: Select file and start SD Print
  2972. */
  2973. inline void gcode_M32() {
  2974. if (card.sdprinting)
  2975. st_synchronize();
  2976. char* namestartpos = strchr(current_command_args, '!'); // Find ! to indicate filename string start.
  2977. if (!namestartpos)
  2978. namestartpos = current_command_args; // Default name position, 4 letters after the M
  2979. else
  2980. namestartpos++; //to skip the '!'
  2981. bool call_procedure = code_seen('P') && (seen_pointer < namestartpos);
  2982. if (card.cardOK) {
  2983. card.openFile(namestartpos, true, !call_procedure);
  2984. if (code_seen('S') && seen_pointer < namestartpos) // "S" (must occur _before_ the filename!)
  2985. card.setIndex(code_value_short());
  2986. card.startFileprint();
  2987. if (!call_procedure)
  2988. print_job_start_ms = millis(); //procedure calls count as normal print time.
  2989. }
  2990. }
  2991. #if ENABLED(LONG_FILENAME_HOST_SUPPORT)
  2992. /**
  2993. * M33: Get the long full path of a file or folder
  2994. *
  2995. * Parameters:
  2996. * <dospath> Case-insensitive DOS-style path to a file or folder
  2997. *
  2998. * Example:
  2999. * M33 miscel~1/armchair/armcha~1.gco
  3000. *
  3001. * Output:
  3002. * /Miscellaneous/Armchair/Armchair.gcode
  3003. */
  3004. inline void gcode_M33() {
  3005. card.printLongPath(current_command_args);
  3006. }
  3007. #endif
  3008. /**
  3009. * M928: Start SD Write
  3010. */
  3011. inline void gcode_M928() {
  3012. card.openLogFile(current_command_args);
  3013. }
  3014. #endif // SDSUPPORT
  3015. /**
  3016. * M42: Change pin status via GCode
  3017. */
  3018. inline void gcode_M42() {
  3019. if (code_seen('S')) {
  3020. int pin_status = code_value_short(),
  3021. pin_number = LED_PIN;
  3022. if (code_seen('P') && pin_status >= 0 && pin_status <= 255)
  3023. pin_number = code_value_short();
  3024. for (uint8_t i = 0; i < COUNT(sensitive_pins); i++) {
  3025. if (sensitive_pins[i] == pin_number) {
  3026. pin_number = -1;
  3027. break;
  3028. }
  3029. }
  3030. #if HAS_FAN
  3031. if (pin_number == FAN_PIN) fanSpeed = pin_status;
  3032. #endif
  3033. if (pin_number > -1) {
  3034. pinMode(pin_number, OUTPUT);
  3035. digitalWrite(pin_number, pin_status);
  3036. analogWrite(pin_number, pin_status);
  3037. }
  3038. } // code_seen('S')
  3039. }
  3040. #if ENABLED(AUTO_BED_LEVELING_FEATURE) && ENABLED(Z_MIN_PROBE_REPEATABILITY_TEST)
  3041. // This is redundant since the SanityCheck.h already checks for a valid Z_MIN_PROBE_PIN, but here for clarity.
  3042. #if ENABLED(Z_MIN_PROBE_ENDSTOP)
  3043. #if !HAS_Z_PROBE
  3044. #error You must define Z_MIN_PROBE_PIN to enable Z probe repeatability calculation.
  3045. #endif
  3046. #elif !HAS_Z_MIN
  3047. #error You must define Z_MIN_PIN to enable Z probe repeatability calculation.
  3048. #endif
  3049. /**
  3050. * M48: Z probe repeatability measurement function.
  3051. *
  3052. * Usage:
  3053. * M48 <P#> <X#> <Y#> <V#> <E> <L#>
  3054. * P = Number of sampled points (4-50, default 10)
  3055. * X = Sample X position
  3056. * Y = Sample Y position
  3057. * V = Verbose level (0-4, default=1)
  3058. * E = Engage Z probe for each reading
  3059. * L = Number of legs of movement before probe
  3060. *
  3061. * This function assumes the bed has been homed. Specifically, that a G28 command
  3062. * as been issued prior to invoking the M48 Z probe repeatability measurement function.
  3063. * Any information generated by a prior G29 Bed leveling command will be lost and need to be
  3064. * regenerated.
  3065. */
  3066. inline void gcode_M48() {
  3067. double sum = 0.0, mean = 0.0, sigma = 0.0, sample_set[50];
  3068. uint8_t verbose_level = 1, n_samples = 10, n_legs = 0;
  3069. if (code_seen('V')) {
  3070. verbose_level = code_value_short();
  3071. if (verbose_level < 0 || verbose_level > 4) {
  3072. SERIAL_PROTOCOLPGM("?Verbose Level not plausible (0-4).\n");
  3073. return;
  3074. }
  3075. }
  3076. if (verbose_level > 0)
  3077. SERIAL_PROTOCOLPGM("M48 Z-Probe Repeatability test\n");
  3078. if (code_seen('P')) {
  3079. n_samples = code_value_short();
  3080. if (n_samples < 4 || n_samples > 50) {
  3081. SERIAL_PROTOCOLPGM("?Sample size not plausible (4-50).\n");
  3082. return;
  3083. }
  3084. }
  3085. double X_current = st_get_axis_position_mm(X_AXIS),
  3086. Y_current = st_get_axis_position_mm(Y_AXIS),
  3087. Z_current = st_get_axis_position_mm(Z_AXIS),
  3088. E_current = st_get_axis_position_mm(E_AXIS),
  3089. X_probe_location = X_current, Y_probe_location = Y_current,
  3090. Z_start_location = Z_current + Z_RAISE_BEFORE_PROBING;
  3091. bool deploy_probe_for_each_reading = code_seen('E');
  3092. if (code_seen('X')) {
  3093. X_probe_location = code_value() - (X_PROBE_OFFSET_FROM_EXTRUDER);
  3094. if (X_probe_location < X_MIN_POS || X_probe_location > X_MAX_POS) {
  3095. out_of_range_error(PSTR("X"));
  3096. return;
  3097. }
  3098. }
  3099. if (code_seen('Y')) {
  3100. Y_probe_location = code_value() - Y_PROBE_OFFSET_FROM_EXTRUDER;
  3101. if (Y_probe_location < Y_MIN_POS || Y_probe_location > Y_MAX_POS) {
  3102. out_of_range_error(PSTR("Y"));
  3103. return;
  3104. }
  3105. }
  3106. if (code_seen('L')) {
  3107. n_legs = code_value_short();
  3108. if (n_legs == 1) n_legs = 2;
  3109. if (n_legs < 0 || n_legs > 15) {
  3110. SERIAL_PROTOCOLPGM("?Number of legs in movement not plausible (0-15).\n");
  3111. return;
  3112. }
  3113. }
  3114. //
  3115. // Do all the preliminary setup work. First raise the Z probe.
  3116. //
  3117. st_synchronize();
  3118. plan_bed_level_matrix.set_to_identity();
  3119. plan_buffer_line(X_current, Y_current, Z_start_location, E_current, homing_feedrate[Z_AXIS] / 60, active_extruder);
  3120. st_synchronize();
  3121. //
  3122. // Now get everything to the specified probe point So we can safely do a probe to
  3123. // get us close to the bed. If the Z-Axis is far from the bed, we don't want to
  3124. // use that as a starting point for each probe.
  3125. //
  3126. if (verbose_level > 2)
  3127. SERIAL_PROTOCOLPGM("Positioning the probe...\n");
  3128. plan_buffer_line(X_probe_location, Y_probe_location, Z_start_location,
  3129. E_current,
  3130. homing_feedrate[X_AXIS] / 60,
  3131. active_extruder);
  3132. st_synchronize();
  3133. current_position[X_AXIS] = X_current = st_get_axis_position_mm(X_AXIS);
  3134. current_position[Y_AXIS] = Y_current = st_get_axis_position_mm(Y_AXIS);
  3135. current_position[Z_AXIS] = Z_current = st_get_axis_position_mm(Z_AXIS);
  3136. current_position[E_AXIS] = E_current = st_get_axis_position_mm(E_AXIS);
  3137. //
  3138. // OK, do the initial probe to get us close to the bed.
  3139. // Then retrace the right amount and use that in subsequent probes
  3140. //
  3141. deploy_z_probe();
  3142. setup_for_endstop_move();
  3143. run_z_probe();
  3144. Z_current = current_position[Z_AXIS] = st_get_axis_position_mm(Z_AXIS);
  3145. Z_start_location = Z_current + Z_RAISE_BEFORE_PROBING;
  3146. plan_buffer_line(X_probe_location, Y_probe_location, Z_start_location,
  3147. E_current,
  3148. homing_feedrate[X_AXIS] / 60,
  3149. active_extruder);
  3150. st_synchronize();
  3151. Z_current = current_position[Z_AXIS] = st_get_axis_position_mm(Z_AXIS);
  3152. if (deploy_probe_for_each_reading) stow_z_probe();
  3153. for (uint8_t n = 0; n < n_samples; n++) {
  3154. // Make sure we are at the probe location
  3155. do_blocking_move_to(X_probe_location, Y_probe_location, Z_start_location); // this also updates current_position
  3156. if (n_legs) {
  3157. millis_t ms = millis();
  3158. double radius = ms % ((X_MAX_LENGTH) / 4), // limit how far out to go
  3159. theta = RADIANS(ms % 360L);
  3160. float dir = (ms & 0x0001) ? 1 : -1; // clockwise or counter clockwise
  3161. //SERIAL_ECHOPAIR("starting radius: ",radius);
  3162. //SERIAL_ECHOPAIR(" theta: ",theta);
  3163. //SERIAL_ECHOPAIR(" direction: ",dir);
  3164. //SERIAL_EOL;
  3165. for (uint8_t l = 0; l < n_legs - 1; l++) {
  3166. ms = millis();
  3167. theta += RADIANS(dir * (ms % 20L));
  3168. radius += (ms % 10L) - 5L;
  3169. if (radius < 0.0) radius = -radius;
  3170. X_current = X_probe_location + cos(theta) * radius;
  3171. X_current = constrain(X_current, X_MIN_POS, X_MAX_POS);
  3172. Y_current = Y_probe_location + sin(theta) * radius;
  3173. Y_current = constrain(Y_current, Y_MIN_POS, Y_MAX_POS);
  3174. if (verbose_level > 3) {
  3175. SERIAL_ECHOPAIR("x: ", X_current);
  3176. SERIAL_ECHOPAIR("y: ", Y_current);
  3177. SERIAL_EOL;
  3178. }
  3179. do_blocking_move_to(X_current, Y_current, Z_current); // this also updates current_position
  3180. } // n_legs loop
  3181. // Go back to the probe location
  3182. do_blocking_move_to(X_probe_location, Y_probe_location, Z_start_location); // this also updates current_position
  3183. } // n_legs
  3184. if (deploy_probe_for_each_reading) {
  3185. deploy_z_probe();
  3186. delay(1000);
  3187. }
  3188. setup_for_endstop_move();
  3189. run_z_probe();
  3190. sample_set[n] = current_position[Z_AXIS];
  3191. //
  3192. // Get the current mean for the data points we have so far
  3193. //
  3194. sum = 0.0;
  3195. for (uint8_t j = 0; j <= n; j++) sum += sample_set[j];
  3196. mean = sum / (n + 1);
  3197. //
  3198. // Now, use that mean to calculate the standard deviation for the
  3199. // data points we have so far
  3200. //
  3201. sum = 0.0;
  3202. for (uint8_t j = 0; j <= n; j++) {
  3203. float ss = sample_set[j] - mean;
  3204. sum += ss * ss;
  3205. }
  3206. sigma = sqrt(sum / (n + 1));
  3207. if (verbose_level > 1) {
  3208. SERIAL_PROTOCOL(n + 1);
  3209. SERIAL_PROTOCOLPGM(" of ");
  3210. SERIAL_PROTOCOL((int)n_samples);
  3211. SERIAL_PROTOCOLPGM(" z: ");
  3212. SERIAL_PROTOCOL_F(current_position[Z_AXIS], 6);
  3213. if (verbose_level > 2) {
  3214. SERIAL_PROTOCOLPGM(" mean: ");
  3215. SERIAL_PROTOCOL_F(mean, 6);
  3216. SERIAL_PROTOCOLPGM(" sigma: ");
  3217. SERIAL_PROTOCOL_F(sigma, 6);
  3218. }
  3219. }
  3220. if (verbose_level > 0) SERIAL_EOL;
  3221. plan_buffer_line(X_probe_location, Y_probe_location, Z_start_location, current_position[E_AXIS], homing_feedrate[Z_AXIS] / 60, active_extruder);
  3222. st_synchronize();
  3223. // Stow between
  3224. if (deploy_probe_for_each_reading) {
  3225. stow_z_probe();
  3226. delay(1000);
  3227. }
  3228. }
  3229. // Stow after
  3230. if (!deploy_probe_for_each_reading) {
  3231. stow_z_probe();
  3232. delay(1000);
  3233. }
  3234. clean_up_after_endstop_move();
  3235. if (verbose_level > 0) {
  3236. SERIAL_PROTOCOLPGM("Mean: ");
  3237. SERIAL_PROTOCOL_F(mean, 6);
  3238. SERIAL_EOL;
  3239. }
  3240. SERIAL_PROTOCOLPGM("Standard Deviation: ");
  3241. SERIAL_PROTOCOL_F(sigma, 6);
  3242. SERIAL_EOL; SERIAL_EOL;
  3243. }
  3244. #endif // AUTO_BED_LEVELING_FEATURE && Z_MIN_PROBE_REPEATABILITY_TEST
  3245. /**
  3246. * M104: Set hot end temperature
  3247. */
  3248. inline void gcode_M104() {
  3249. if (setTargetedHotend(104)) return;
  3250. if (marlin_debug_flags & DEBUG_DRYRUN) return;
  3251. if (code_seen('S')) {
  3252. float temp = code_value();
  3253. setTargetHotend(temp, target_extruder);
  3254. #if ENABLED(DUAL_X_CARRIAGE)
  3255. if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && target_extruder == 0)
  3256. setTargetHotend1(temp == 0.0 ? 0.0 : temp + duplicate_extruder_temp_offset);
  3257. #endif
  3258. }
  3259. }
  3260. #if HAS_TEMP_0 || HAS_TEMP_BED || ENABLED(HEATER_0_USES_MAX6675)
  3261. void print_heaterstates() {
  3262. #if HAS_TEMP_0 || ENABLED(HEATER_0_USES_MAX6675)
  3263. SERIAL_PROTOCOLPGM(" T:");
  3264. SERIAL_PROTOCOL_F(degHotend(target_extruder), 1);
  3265. SERIAL_PROTOCOLPGM(" /");
  3266. SERIAL_PROTOCOL_F(degTargetHotend(target_extruder), 1);
  3267. #endif
  3268. #if HAS_TEMP_BED
  3269. SERIAL_PROTOCOLPGM(" B:");
  3270. SERIAL_PROTOCOL_F(degBed(), 1);
  3271. SERIAL_PROTOCOLPGM(" /");
  3272. SERIAL_PROTOCOL_F(degTargetBed(), 1);
  3273. #endif
  3274. #if EXTRUDERS > 1
  3275. for (int8_t e = 0; e < EXTRUDERS; ++e) {
  3276. SERIAL_PROTOCOLPGM(" T");
  3277. SERIAL_PROTOCOL(e);
  3278. SERIAL_PROTOCOLCHAR(':');
  3279. SERIAL_PROTOCOL_F(degHotend(e), 1);
  3280. SERIAL_PROTOCOLPGM(" /");
  3281. SERIAL_PROTOCOL_F(degTargetHotend(e), 1);
  3282. }
  3283. #endif
  3284. #if HAS_TEMP_BED
  3285. SERIAL_PROTOCOLPGM(" B@:");
  3286. #ifdef BED_WATTS
  3287. SERIAL_PROTOCOL(((BED_WATTS) * getHeaterPower(-1)) / 127);
  3288. SERIAL_PROTOCOLCHAR('W');
  3289. #else
  3290. SERIAL_PROTOCOL(getHeaterPower(-1));
  3291. #endif
  3292. #endif
  3293. SERIAL_PROTOCOLPGM(" @:");
  3294. #ifdef EXTRUDER_WATTS
  3295. SERIAL_PROTOCOL(((EXTRUDER_WATTS) * getHeaterPower(target_extruder)) / 127);
  3296. SERIAL_PROTOCOLCHAR('W');
  3297. #else
  3298. SERIAL_PROTOCOL(getHeaterPower(target_extruder));
  3299. #endif
  3300. #if EXTRUDERS > 1
  3301. for (int8_t e = 0; e < EXTRUDERS; ++e) {
  3302. SERIAL_PROTOCOLPGM(" @");
  3303. SERIAL_PROTOCOL(e);
  3304. SERIAL_PROTOCOLCHAR(':');
  3305. #ifdef EXTRUDER_WATTS
  3306. SERIAL_PROTOCOL(((EXTRUDER_WATTS) * getHeaterPower(e)) / 127);
  3307. SERIAL_PROTOCOLCHAR('W');
  3308. #else
  3309. SERIAL_PROTOCOL(getHeaterPower(e));
  3310. #endif
  3311. }
  3312. #endif
  3313. #if ENABLED(SHOW_TEMP_ADC_VALUES)
  3314. #if HAS_TEMP_BED
  3315. SERIAL_PROTOCOLPGM(" ADC B:");
  3316. SERIAL_PROTOCOL_F(degBed(), 1);
  3317. SERIAL_PROTOCOLPGM("C->");
  3318. SERIAL_PROTOCOL_F(rawBedTemp() / OVERSAMPLENR, 0);
  3319. #endif
  3320. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  3321. SERIAL_PROTOCOLPGM(" T");
  3322. SERIAL_PROTOCOL(cur_extruder);
  3323. SERIAL_PROTOCOLCHAR(':');
  3324. SERIAL_PROTOCOL_F(degHotend(cur_extruder), 1);
  3325. SERIAL_PROTOCOLPGM("C->");
  3326. SERIAL_PROTOCOL_F(rawHotendTemp(cur_extruder) / OVERSAMPLENR, 0);
  3327. }
  3328. #endif
  3329. }
  3330. #endif
  3331. /**
  3332. * M105: Read hot end and bed temperature
  3333. */
  3334. inline void gcode_M105() {
  3335. if (setTargetedHotend(105)) return;
  3336. #if HAS_TEMP_0 || HAS_TEMP_BED || ENABLED(HEATER_0_USES_MAX6675)
  3337. SERIAL_PROTOCOLPGM(MSG_OK);
  3338. print_heaterstates();
  3339. #else // !HAS_TEMP_0 && !HAS_TEMP_BED
  3340. SERIAL_ERROR_START;
  3341. SERIAL_ERRORLNPGM(MSG_ERR_NO_THERMISTORS);
  3342. #endif
  3343. SERIAL_EOL;
  3344. }
  3345. #if HAS_FAN
  3346. /**
  3347. * M106: Set Fan Speed
  3348. */
  3349. inline void gcode_M106() { fanSpeed = code_seen('S') ? constrain(code_value_short(), 0, 255) : 255; }
  3350. /**
  3351. * M107: Fan Off
  3352. */
  3353. inline void gcode_M107() { fanSpeed = 0; }
  3354. #endif // HAS_FAN
  3355. /**
  3356. * M109: Sxxx Wait for extruder(s) to reach temperature. Waits only when heating.
  3357. * Rxxx Wait for extruder(s) to reach temperature. Waits when heating and cooling.
  3358. */
  3359. inline void gcode_M109() {
  3360. bool no_wait_for_cooling = true;
  3361. if (setTargetedHotend(109)) return;
  3362. if (marlin_debug_flags & DEBUG_DRYRUN) return;
  3363. LCD_MESSAGEPGM(MSG_HEATING);
  3364. no_wait_for_cooling = code_seen('S');
  3365. if (no_wait_for_cooling || code_seen('R')) {
  3366. float temp = code_value();
  3367. setTargetHotend(temp, target_extruder);
  3368. #if ENABLED(DUAL_X_CARRIAGE)
  3369. if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && target_extruder == 0)
  3370. setTargetHotend1(temp == 0.0 ? 0.0 : temp + duplicate_extruder_temp_offset);
  3371. #endif
  3372. }
  3373. #if ENABLED(AUTOTEMP)
  3374. autotemp_enabled = code_seen('F');
  3375. if (autotemp_enabled) autotemp_factor = code_value();
  3376. if (code_seen('S')) autotemp_min = code_value();
  3377. if (code_seen('B')) autotemp_max = code_value();
  3378. #endif
  3379. // Exit if the temperature is above target and not waiting for cooling
  3380. if (no_wait_for_cooling && !isHeatingHotend(target_extruder)) return;
  3381. // Prevents a wait-forever situation if R is misused i.e. M109 R0
  3382. // Try to calculate a ballpark safe margin by halving EXTRUDE_MINTEMP
  3383. if (degTargetHotend(target_extruder) < (EXTRUDE_MINTEMP/2)) return;
  3384. #ifdef TEMP_RESIDENCY_TIME
  3385. long residency_start_ms = -1;
  3386. // Loop until the temperature has stabilized
  3387. #define TEMP_CONDITIONS (residency_start_ms < 0 || now < residency_start_ms + (TEMP_RESIDENCY_TIME) * 1000UL)
  3388. #else
  3389. // Loop until the temperature is very close target
  3390. #define TEMP_CONDITIONS (fabs(degHotend(target_extruder) - degTargetHotend(target_extruder)) < 0.75f)
  3391. #endif //TEMP_RESIDENCY_TIME
  3392. cancel_heatup = false;
  3393. millis_t now = millis(), next_temp_ms = now + 1000UL;
  3394. while (!cancel_heatup && TEMP_CONDITIONS) {
  3395. now = millis();
  3396. if (now > next_temp_ms) { //Print temp & remaining time every 1s while waiting
  3397. next_temp_ms = now + 1000UL;
  3398. #if HAS_TEMP_0 || HAS_TEMP_BED || ENABLED(HEATER_0_USES_MAX6675)
  3399. print_heaterstates();
  3400. #endif
  3401. #ifdef TEMP_RESIDENCY_TIME
  3402. SERIAL_PROTOCOLPGM(" W:");
  3403. if (residency_start_ms >= 0) {
  3404. long rem = (((TEMP_RESIDENCY_TIME) * 1000UL) - (now - residency_start_ms)) / 1000UL;
  3405. SERIAL_PROTOCOLLN(rem);
  3406. }
  3407. else {
  3408. SERIAL_PROTOCOLLNPGM("?");
  3409. }
  3410. #else
  3411. SERIAL_EOL;
  3412. #endif
  3413. }
  3414. idle();
  3415. refresh_cmd_timeout(); // to prevent stepper_inactive_time from running out
  3416. #ifdef TEMP_RESIDENCY_TIME
  3417. // Start the TEMP_RESIDENCY_TIME timer when we reach target temp for the first time.
  3418. // Restart the timer whenever the temperature falls outside the hysteresis.
  3419. if (labs(degHotend(target_extruder) - degTargetHotend(target_extruder)) > ((residency_start_ms < 0) ? TEMP_WINDOW : TEMP_HYSTERESIS))
  3420. residency_start_ms = millis();
  3421. #endif //TEMP_RESIDENCY_TIME
  3422. } // while(!cancel_heatup && TEMP_CONDITIONS)
  3423. LCD_MESSAGEPGM(MSG_HEATING_COMPLETE);
  3424. print_job_start_ms = previous_cmd_ms;
  3425. }
  3426. #if HAS_TEMP_BED
  3427. /**
  3428. * M190: Sxxx Wait for bed current temp to reach target temp. Waits only when heating
  3429. * Rxxx Wait for bed current temp to reach target temp. Waits when heating and cooling
  3430. */
  3431. inline void gcode_M190() {
  3432. if (marlin_debug_flags & DEBUG_DRYRUN) return;
  3433. LCD_MESSAGEPGM(MSG_BED_HEATING);
  3434. bool no_wait_for_cooling = code_seen('S');
  3435. if (no_wait_for_cooling || code_seen('R'))
  3436. setTargetBed(code_value());
  3437. // Exit if the temperature is above target and not waiting for cooling
  3438. if (no_wait_for_cooling && !isHeatingBed()) return;
  3439. cancel_heatup = false;
  3440. millis_t now = millis(), next_temp_ms = now + 1000UL;
  3441. while (!cancel_heatup && degTargetBed() != degBed()) {
  3442. millis_t now = millis();
  3443. if (now > next_temp_ms) { //Print Temp Reading every 1 second while heating up.
  3444. next_temp_ms = now + 1000UL;
  3445. print_heaterstates();
  3446. SERIAL_EOL;
  3447. }
  3448. idle();
  3449. refresh_cmd_timeout(); // to prevent stepper_inactive_time from running out
  3450. }
  3451. LCD_MESSAGEPGM(MSG_BED_DONE);
  3452. }
  3453. #endif // HAS_TEMP_BED
  3454. /**
  3455. * M110: Set Current Line Number
  3456. */
  3457. inline void gcode_M110() {
  3458. if (code_seen('N')) gcode_N = code_value_long();
  3459. }
  3460. /**
  3461. * M111: Set the debug level
  3462. */
  3463. inline void gcode_M111() {
  3464. marlin_debug_flags = code_seen('S') ? code_value_short() : DEBUG_INFO | DEBUG_COMMUNICATION;
  3465. if (marlin_debug_flags & DEBUG_ECHO) {
  3466. SERIAL_ECHO_START;
  3467. SERIAL_ECHOLNPGM(MSG_DEBUG_ECHO);
  3468. }
  3469. // FOR MOMENT NOT ACTIVE
  3470. //if (marlin_debug_flags & DEBUG_INFO) SERIAL_ECHOLNPGM(MSG_DEBUG_INFO);
  3471. //if (marlin_debug_flags & DEBUG_ERRORS) SERIAL_ECHOLNPGM(MSG_DEBUG_ERRORS);
  3472. if (marlin_debug_flags & DEBUG_DRYRUN) {
  3473. SERIAL_ECHO_START;
  3474. SERIAL_ECHOLNPGM(MSG_DEBUG_DRYRUN);
  3475. disable_all_heaters();
  3476. }
  3477. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3478. if (marlin_debug_flags & DEBUG_LEVELING) {
  3479. SERIAL_ECHO_START;
  3480. SERIAL_ECHOLNPGM(MSG_DEBUG_LEVELING);
  3481. }
  3482. #endif
  3483. }
  3484. /**
  3485. * M112: Emergency Stop
  3486. */
  3487. inline void gcode_M112() { kill(PSTR(MSG_KILLED)); }
  3488. #if ENABLED(BARICUDA)
  3489. #if HAS_HEATER_1
  3490. /**
  3491. * M126: Heater 1 valve open
  3492. */
  3493. inline void gcode_M126() { ValvePressure = code_seen('S') ? constrain(code_value(), 0, 255) : 255; }
  3494. /**
  3495. * M127: Heater 1 valve close
  3496. */
  3497. inline void gcode_M127() { ValvePressure = 0; }
  3498. #endif
  3499. #if HAS_HEATER_2
  3500. /**
  3501. * M128: Heater 2 valve open
  3502. */
  3503. inline void gcode_M128() { EtoPPressure = code_seen('S') ? constrain(code_value(), 0, 255) : 255; }
  3504. /**
  3505. * M129: Heater 2 valve close
  3506. */
  3507. inline void gcode_M129() { EtoPPressure = 0; }
  3508. #endif
  3509. #endif //BARICUDA
  3510. /**
  3511. * M140: Set bed temperature
  3512. */
  3513. inline void gcode_M140() {
  3514. if (marlin_debug_flags & DEBUG_DRYRUN) return;
  3515. if (code_seen('S')) setTargetBed(code_value());
  3516. }
  3517. #if ENABLED(ULTIPANEL)
  3518. /**
  3519. * M145: Set the heatup state for a material in the LCD menu
  3520. * S<material> (0=PLA, 1=ABS)
  3521. * H<hotend temp>
  3522. * B<bed temp>
  3523. * F<fan speed>
  3524. */
  3525. inline void gcode_M145() {
  3526. int8_t material = code_seen('S') ? code_value_short() : 0;
  3527. if (material < 0 || material > 1) {
  3528. SERIAL_ERROR_START;
  3529. SERIAL_ERRORLNPGM(MSG_ERR_MATERIAL_INDEX);
  3530. }
  3531. else {
  3532. int v;
  3533. switch (material) {
  3534. case 0:
  3535. if (code_seen('H')) {
  3536. v = code_value_short();
  3537. plaPreheatHotendTemp = constrain(v, EXTRUDE_MINTEMP, HEATER_0_MAXTEMP - 15);
  3538. }
  3539. if (code_seen('F')) {
  3540. v = code_value_short();
  3541. plaPreheatFanSpeed = constrain(v, 0, 255);
  3542. }
  3543. #if TEMP_SENSOR_BED != 0
  3544. if (code_seen('B')) {
  3545. v = code_value_short();
  3546. plaPreheatHPBTemp = constrain(v, BED_MINTEMP, BED_MAXTEMP - 15);
  3547. }
  3548. #endif
  3549. break;
  3550. case 1:
  3551. if (code_seen('H')) {
  3552. v = code_value_short();
  3553. absPreheatHotendTemp = constrain(v, EXTRUDE_MINTEMP, HEATER_0_MAXTEMP - 15);
  3554. }
  3555. if (code_seen('F')) {
  3556. v = code_value_short();
  3557. absPreheatFanSpeed = constrain(v, 0, 255);
  3558. }
  3559. #if TEMP_SENSOR_BED != 0
  3560. if (code_seen('B')) {
  3561. v = code_value_short();
  3562. absPreheatHPBTemp = constrain(v, BED_MINTEMP, BED_MAXTEMP - 15);
  3563. }
  3564. #endif
  3565. break;
  3566. }
  3567. }
  3568. }
  3569. #endif
  3570. #if HAS_POWER_SWITCH
  3571. /**
  3572. * M80: Turn on Power Supply
  3573. */
  3574. inline void gcode_M80() {
  3575. OUT_WRITE(PS_ON_PIN, PS_ON_AWAKE); //GND
  3576. // If you have a switch on suicide pin, this is useful
  3577. // if you want to start another print with suicide feature after
  3578. // a print without suicide...
  3579. #if HAS_SUICIDE
  3580. OUT_WRITE(SUICIDE_PIN, HIGH);
  3581. #endif
  3582. #if ENABLED(ULTIPANEL)
  3583. powersupply = true;
  3584. LCD_MESSAGEPGM(WELCOME_MSG);
  3585. lcd_update();
  3586. #endif
  3587. }
  3588. #endif // HAS_POWER_SWITCH
  3589. /**
  3590. * M81: Turn off Power, including Power Supply, if there is one.
  3591. *
  3592. * This code should ALWAYS be available for EMERGENCY SHUTDOWN!
  3593. */
  3594. inline void gcode_M81() {
  3595. disable_all_heaters();
  3596. finishAndDisableSteppers();
  3597. fanSpeed = 0;
  3598. delay(1000); // Wait 1 second before switching off
  3599. #if HAS_SUICIDE
  3600. st_synchronize();
  3601. suicide();
  3602. #elif HAS_POWER_SWITCH
  3603. OUT_WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  3604. #endif
  3605. #if ENABLED(ULTIPANEL)
  3606. #if HAS_POWER_SWITCH
  3607. powersupply = false;
  3608. #endif
  3609. LCD_MESSAGEPGM(MACHINE_NAME " " MSG_OFF ".");
  3610. lcd_update();
  3611. #endif
  3612. }
  3613. /**
  3614. * M82: Set E codes absolute (default)
  3615. */
  3616. inline void gcode_M82() { axis_relative_modes[E_AXIS] = false; }
  3617. /**
  3618. * M83: Set E codes relative while in Absolute Coordinates (G90) mode
  3619. */
  3620. inline void gcode_M83() { axis_relative_modes[E_AXIS] = true; }
  3621. /**
  3622. * M18, M84: Disable all stepper motors
  3623. */
  3624. inline void gcode_M18_M84() {
  3625. if (code_seen('S')) {
  3626. stepper_inactive_time = code_value() * 1000;
  3627. }
  3628. else {
  3629. bool all_axis = !((code_seen(axis_codes[X_AXIS])) || (code_seen(axis_codes[Y_AXIS])) || (code_seen(axis_codes[Z_AXIS])) || (code_seen(axis_codes[E_AXIS])));
  3630. if (all_axis) {
  3631. finishAndDisableSteppers();
  3632. }
  3633. else {
  3634. st_synchronize();
  3635. if (code_seen('X')) disable_x();
  3636. if (code_seen('Y')) disable_y();
  3637. if (code_seen('Z')) disable_z();
  3638. #if ((E0_ENABLE_PIN != X_ENABLE_PIN) && (E1_ENABLE_PIN != Y_ENABLE_PIN)) // Only enable on boards that have seperate ENABLE_PINS
  3639. if (code_seen('E')) {
  3640. disable_e0();
  3641. disable_e1();
  3642. disable_e2();
  3643. disable_e3();
  3644. }
  3645. #endif
  3646. }
  3647. }
  3648. }
  3649. /**
  3650. * M85: Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
  3651. */
  3652. inline void gcode_M85() {
  3653. if (code_seen('S')) max_inactive_time = code_value() * 1000;
  3654. }
  3655. /**
  3656. * M92: Set axis steps-per-unit for one or more axes, X, Y, Z, and E.
  3657. * (Follows the same syntax as G92)
  3658. */
  3659. inline void gcode_M92() {
  3660. for (int8_t i = 0; i < NUM_AXIS; i++) {
  3661. if (code_seen(axis_codes[i])) {
  3662. if (i == E_AXIS) {
  3663. float value = code_value();
  3664. if (value < 20.0) {
  3665. float factor = axis_steps_per_unit[i] / value; // increase e constants if M92 E14 is given for netfab.
  3666. max_e_jerk *= factor;
  3667. max_feedrate[i] *= factor;
  3668. axis_steps_per_sqr_second[i] *= factor;
  3669. }
  3670. axis_steps_per_unit[i] = value;
  3671. }
  3672. else {
  3673. axis_steps_per_unit[i] = code_value();
  3674. }
  3675. }
  3676. }
  3677. }
  3678. /**
  3679. * M114: Output current position to serial port
  3680. */
  3681. inline void gcode_M114() {
  3682. SERIAL_PROTOCOLPGM("X:");
  3683. SERIAL_PROTOCOL(current_position[X_AXIS]);
  3684. SERIAL_PROTOCOLPGM(" Y:");
  3685. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  3686. SERIAL_PROTOCOLPGM(" Z:");
  3687. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  3688. SERIAL_PROTOCOLPGM(" E:");
  3689. SERIAL_PROTOCOL(current_position[E_AXIS]);
  3690. CRITICAL_SECTION_START;
  3691. extern volatile long count_position[NUM_AXIS];
  3692. long xpos = count_position[X_AXIS],
  3693. ypos = count_position[Y_AXIS],
  3694. zpos = count_position[Z_AXIS];
  3695. CRITICAL_SECTION_END;
  3696. #if ENABLED(COREXY) || ENABLED(COREXZ)
  3697. SERIAL_PROTOCOLPGM(MSG_COUNT_A);
  3698. #else
  3699. SERIAL_PROTOCOLPGM(MSG_COUNT_X);
  3700. #endif
  3701. SERIAL_PROTOCOL(xpos);
  3702. #if ENABLED(COREXY)
  3703. SERIAL_PROTOCOLPGM(" B:");
  3704. #else
  3705. SERIAL_PROTOCOLPGM(" Y:");
  3706. #endif
  3707. SERIAL_PROTOCOL(ypos);
  3708. #if ENABLED(COREXZ)
  3709. SERIAL_PROTOCOLPGM(" C:");
  3710. #else
  3711. SERIAL_PROTOCOLPGM(" Z:");
  3712. #endif
  3713. SERIAL_PROTOCOL(zpos);
  3714. SERIAL_EOL;
  3715. #if ENABLED(SCARA)
  3716. SERIAL_PROTOCOLPGM("SCARA Theta:");
  3717. SERIAL_PROTOCOL(delta[X_AXIS]);
  3718. SERIAL_PROTOCOLPGM(" Psi+Theta:");
  3719. SERIAL_PROTOCOL(delta[Y_AXIS]);
  3720. SERIAL_EOL;
  3721. SERIAL_PROTOCOLPGM("SCARA Cal - Theta:");
  3722. SERIAL_PROTOCOL(delta[X_AXIS] + home_offset[X_AXIS]);
  3723. SERIAL_PROTOCOLPGM(" Psi+Theta (90):");
  3724. SERIAL_PROTOCOL(delta[Y_AXIS] - delta[X_AXIS] - 90 + home_offset[Y_AXIS]);
  3725. SERIAL_EOL;
  3726. SERIAL_PROTOCOLPGM("SCARA step Cal - Theta:");
  3727. SERIAL_PROTOCOL(delta[X_AXIS] / 90 * axis_steps_per_unit[X_AXIS]);
  3728. SERIAL_PROTOCOLPGM(" Psi+Theta:");
  3729. SERIAL_PROTOCOL((delta[Y_AXIS] - delta[X_AXIS]) / 90 * axis_steps_per_unit[Y_AXIS]);
  3730. SERIAL_EOL; SERIAL_EOL;
  3731. #endif
  3732. }
  3733. /**
  3734. * M115: Capabilities string
  3735. */
  3736. inline void gcode_M115() {
  3737. SERIAL_PROTOCOLPGM(MSG_M115_REPORT);
  3738. }
  3739. /**
  3740. * M117: Set LCD Status Message
  3741. */
  3742. inline void gcode_M117() {
  3743. lcd_setstatus(current_command_args);
  3744. }
  3745. /**
  3746. * M119: Output endstop states to serial output
  3747. */
  3748. inline void gcode_M119() {
  3749. SERIAL_PROTOCOLLN(MSG_M119_REPORT);
  3750. #if HAS_X_MIN
  3751. SERIAL_PROTOCOLPGM(MSG_X_MIN);
  3752. SERIAL_PROTOCOLLN(((READ(X_MIN_PIN)^X_MIN_ENDSTOP_INVERTING) ? MSG_ENDSTOP_HIT : MSG_ENDSTOP_OPEN));
  3753. #endif
  3754. #if HAS_X_MAX
  3755. SERIAL_PROTOCOLPGM(MSG_X_MAX);
  3756. SERIAL_PROTOCOLLN(((READ(X_MAX_PIN)^X_MAX_ENDSTOP_INVERTING) ? MSG_ENDSTOP_HIT : MSG_ENDSTOP_OPEN));
  3757. #endif
  3758. #if HAS_Y_MIN
  3759. SERIAL_PROTOCOLPGM(MSG_Y_MIN);
  3760. SERIAL_PROTOCOLLN(((READ(Y_MIN_PIN)^Y_MIN_ENDSTOP_INVERTING) ? MSG_ENDSTOP_HIT : MSG_ENDSTOP_OPEN));
  3761. #endif
  3762. #if HAS_Y_MAX
  3763. SERIAL_PROTOCOLPGM(MSG_Y_MAX);
  3764. SERIAL_PROTOCOLLN(((READ(Y_MAX_PIN)^Y_MAX_ENDSTOP_INVERTING) ? MSG_ENDSTOP_HIT : MSG_ENDSTOP_OPEN));
  3765. #endif
  3766. #if HAS_Z_MIN
  3767. SERIAL_PROTOCOLPGM(MSG_Z_MIN);
  3768. SERIAL_PROTOCOLLN(((READ(Z_MIN_PIN)^Z_MIN_ENDSTOP_INVERTING) ? MSG_ENDSTOP_HIT : MSG_ENDSTOP_OPEN));
  3769. #endif
  3770. #if HAS_Z_MAX
  3771. SERIAL_PROTOCOLPGM(MSG_Z_MAX);
  3772. SERIAL_PROTOCOLLN(((READ(Z_MAX_PIN)^Z_MAX_ENDSTOP_INVERTING) ? MSG_ENDSTOP_HIT : MSG_ENDSTOP_OPEN));
  3773. #endif
  3774. #if HAS_Z2_MAX
  3775. SERIAL_PROTOCOLPGM(MSG_Z2_MAX);
  3776. SERIAL_PROTOCOLLN(((READ(Z2_MAX_PIN)^Z2_MAX_ENDSTOP_INVERTING) ? MSG_ENDSTOP_HIT : MSG_ENDSTOP_OPEN));
  3777. #endif
  3778. #if HAS_Z_PROBE
  3779. SERIAL_PROTOCOLPGM(MSG_Z_PROBE);
  3780. SERIAL_PROTOCOLLN(((READ(Z_MIN_PROBE_PIN)^Z_MIN_PROBE_ENDSTOP_INVERTING) ? MSG_ENDSTOP_HIT : MSG_ENDSTOP_OPEN));
  3781. #endif
  3782. }
  3783. /**
  3784. * M120: Enable endstops
  3785. */
  3786. inline void gcode_M120() { enable_endstops(true); }
  3787. /**
  3788. * M121: Disable endstops
  3789. */
  3790. inline void gcode_M121() { enable_endstops(false); }
  3791. #if ENABLED(BLINKM)
  3792. /**
  3793. * M150: Set Status LED Color - Use R-U-B for R-G-B
  3794. */
  3795. inline void gcode_M150() {
  3796. SendColors(
  3797. code_seen('R') ? (byte)code_value_short() : 0,
  3798. code_seen('U') ? (byte)code_value_short() : 0,
  3799. code_seen('B') ? (byte)code_value_short() : 0
  3800. );
  3801. }
  3802. #endif // BLINKM
  3803. /**
  3804. * M200: Set filament diameter and set E axis units to cubic millimeters
  3805. *
  3806. * T<extruder> - Optional extruder number. Current extruder if omitted.
  3807. * D<mm> - Diameter of the filament. Use "D0" to set units back to millimeters.
  3808. */
  3809. inline void gcode_M200() {
  3810. if (setTargetedHotend(200)) return;
  3811. if (code_seen('D')) {
  3812. float diameter = code_value();
  3813. // setting any extruder filament size disables volumetric on the assumption that
  3814. // slicers either generate in extruder values as cubic mm or as as filament feeds
  3815. // for all extruders
  3816. volumetric_enabled = (diameter != 0.0);
  3817. if (volumetric_enabled) {
  3818. filament_size[target_extruder] = diameter;
  3819. // make sure all extruders have some sane value for the filament size
  3820. for (int i = 0; i < EXTRUDERS; i++)
  3821. if (! filament_size[i]) filament_size[i] = DEFAULT_NOMINAL_FILAMENT_DIA;
  3822. }
  3823. }
  3824. else {
  3825. //reserved for setting filament diameter via UFID or filament measuring device
  3826. return;
  3827. }
  3828. calculate_volumetric_multipliers();
  3829. }
  3830. /**
  3831. * M201: Set max acceleration in units/s^2 for print moves (M201 X1000 Y1000)
  3832. */
  3833. inline void gcode_M201() {
  3834. for (int8_t i = 0; i < NUM_AXIS; i++) {
  3835. if (code_seen(axis_codes[i])) {
  3836. max_acceleration_units_per_sq_second[i] = code_value();
  3837. }
  3838. }
  3839. // 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)
  3840. reset_acceleration_rates();
  3841. }
  3842. #if 0 // Not used for Sprinter/grbl gen6
  3843. inline void gcode_M202() {
  3844. for (int8_t i = 0; i < NUM_AXIS; i++) {
  3845. if (code_seen(axis_codes[i])) axis_travel_steps_per_sqr_second[i] = code_value() * axis_steps_per_unit[i];
  3846. }
  3847. }
  3848. #endif
  3849. /**
  3850. * M203: Set maximum feedrate that your machine can sustain (M203 X200 Y200 Z300 E10000) in mm/sec
  3851. */
  3852. inline void gcode_M203() {
  3853. for (int8_t i = 0; i < NUM_AXIS; i++) {
  3854. if (code_seen(axis_codes[i])) {
  3855. max_feedrate[i] = code_value();
  3856. }
  3857. }
  3858. }
  3859. /**
  3860. * M204: Set Accelerations in mm/sec^2 (M204 P1200 R3000 T3000)
  3861. *
  3862. * P = Printing moves
  3863. * R = Retract only (no X, Y, Z) moves
  3864. * T = Travel (non printing) moves
  3865. *
  3866. * Also sets minimum segment time in ms (B20000) to prevent buffer under-runs and M20 minimum feedrate
  3867. */
  3868. inline void gcode_M204() {
  3869. if (code_seen('S')) { // Kept for legacy compatibility. Should NOT BE USED for new developments.
  3870. travel_acceleration = acceleration = code_value();
  3871. SERIAL_ECHOPAIR("Setting Print and Travel Acceleration: ", acceleration);
  3872. SERIAL_EOL;
  3873. }
  3874. if (code_seen('P')) {
  3875. acceleration = code_value();
  3876. SERIAL_ECHOPAIR("Setting Print Acceleration: ", acceleration);
  3877. SERIAL_EOL;
  3878. }
  3879. if (code_seen('R')) {
  3880. retract_acceleration = code_value();
  3881. SERIAL_ECHOPAIR("Setting Retract Acceleration: ", retract_acceleration);
  3882. SERIAL_EOL;
  3883. }
  3884. if (code_seen('T')) {
  3885. travel_acceleration = code_value();
  3886. SERIAL_ECHOPAIR("Setting Travel Acceleration: ", travel_acceleration);
  3887. SERIAL_EOL;
  3888. }
  3889. }
  3890. /**
  3891. * M205: Set Advanced Settings
  3892. *
  3893. * S = Min Feed Rate (mm/s)
  3894. * T = Min Travel Feed Rate (mm/s)
  3895. * B = Min Segment Time (µs)
  3896. * X = Max XY Jerk (mm/s/s)
  3897. * Z = Max Z Jerk (mm/s/s)
  3898. * E = Max E Jerk (mm/s/s)
  3899. */
  3900. inline void gcode_M205() {
  3901. if (code_seen('S')) minimumfeedrate = code_value();
  3902. if (code_seen('T')) mintravelfeedrate = code_value();
  3903. if (code_seen('B')) minsegmenttime = code_value();
  3904. if (code_seen('X')) max_xy_jerk = code_value();
  3905. if (code_seen('Z')) max_z_jerk = code_value();
  3906. if (code_seen('E')) max_e_jerk = code_value();
  3907. }
  3908. /**
  3909. * M206: Set Additional Homing Offset (X Y Z). SCARA aliases T=X, P=Y
  3910. */
  3911. inline void gcode_M206() {
  3912. for (int8_t i = X_AXIS; i <= Z_AXIS; i++) {
  3913. if (code_seen(axis_codes[i])) {
  3914. home_offset[i] = code_value();
  3915. }
  3916. }
  3917. #if ENABLED(SCARA)
  3918. if (code_seen('T')) home_offset[X_AXIS] = code_value(); // Theta
  3919. if (code_seen('P')) home_offset[Y_AXIS] = code_value(); // Psi
  3920. #endif
  3921. }
  3922. #if ENABLED(DELTA)
  3923. /**
  3924. * M665: Set delta configurations
  3925. *
  3926. * L = diagonal rod
  3927. * R = delta radius
  3928. * S = segments per second
  3929. * A = Alpha (Tower 1) diagonal rod trim
  3930. * B = Beta (Tower 2) diagonal rod trim
  3931. * C = Gamma (Tower 3) diagonal rod trim
  3932. */
  3933. inline void gcode_M665() {
  3934. if (code_seen('L')) delta_diagonal_rod = code_value();
  3935. if (code_seen('R')) delta_radius = code_value();
  3936. if (code_seen('S')) delta_segments_per_second = code_value();
  3937. if (code_seen('A')) delta_diagonal_rod_trim_tower_1 = code_value();
  3938. if (code_seen('B')) delta_diagonal_rod_trim_tower_2 = code_value();
  3939. if (code_seen('C')) delta_diagonal_rod_trim_tower_3 = code_value();
  3940. recalc_delta_settings(delta_radius, delta_diagonal_rod);
  3941. }
  3942. /**
  3943. * M666: Set delta endstop adjustment
  3944. */
  3945. inline void gcode_M666() {
  3946. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3947. if (marlin_debug_flags & DEBUG_LEVELING) {
  3948. SERIAL_ECHOLNPGM(">>> gcode_M666");
  3949. }
  3950. #endif
  3951. for (int8_t i = X_AXIS; i <= Z_AXIS; i++) {
  3952. if (code_seen(axis_codes[i])) {
  3953. endstop_adj[i] = code_value();
  3954. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3955. if (marlin_debug_flags & DEBUG_LEVELING) {
  3956. SERIAL_ECHOPGM("endstop_adj[");
  3957. SERIAL_ECHO(axis_codes[i]);
  3958. SERIAL_ECHOPAIR("] = ", endstop_adj[i]);
  3959. SERIAL_EOL;
  3960. }
  3961. #endif
  3962. }
  3963. }
  3964. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3965. if (marlin_debug_flags & DEBUG_LEVELING) {
  3966. SERIAL_ECHOLNPGM("<<< gcode_M666");
  3967. }
  3968. #endif
  3969. }
  3970. #elif ENABLED(Z_DUAL_ENDSTOPS) // !DELTA && ENABLED(Z_DUAL_ENDSTOPS)
  3971. /**
  3972. * M666: For Z Dual Endstop setup, set z axis offset to the z2 axis.
  3973. */
  3974. inline void gcode_M666() {
  3975. if (code_seen('Z')) z_endstop_adj = code_value();
  3976. SERIAL_ECHOPAIR("Z Endstop Adjustment set to (mm):", z_endstop_adj);
  3977. SERIAL_EOL;
  3978. }
  3979. #endif // !DELTA && Z_DUAL_ENDSTOPS
  3980. #if ENABLED(FWRETRACT)
  3981. /**
  3982. * M207: Set firmware retraction values
  3983. *
  3984. * S[+mm] retract_length
  3985. * W[+mm] retract_length_swap (multi-extruder)
  3986. * F[mm/min] retract_feedrate
  3987. * Z[mm] retract_zlift
  3988. */
  3989. inline void gcode_M207() {
  3990. if (code_seen('S')) retract_length = code_value();
  3991. if (code_seen('F')) retract_feedrate = code_value() / 60;
  3992. if (code_seen('Z')) retract_zlift = code_value();
  3993. #if EXTRUDERS > 1
  3994. if (code_seen('W')) retract_length_swap = code_value();
  3995. #endif
  3996. }
  3997. /**
  3998. * M208: Set firmware un-retraction values
  3999. *
  4000. * S[+mm] retract_recover_length (in addition to M207 S*)
  4001. * W[+mm] retract_recover_length_swap (multi-extruder)
  4002. * F[mm/min] retract_recover_feedrate
  4003. */
  4004. inline void gcode_M208() {
  4005. if (code_seen('S')) retract_recover_length = code_value();
  4006. if (code_seen('F')) retract_recover_feedrate = code_value() / 60;
  4007. #if EXTRUDERS > 1
  4008. if (code_seen('W')) retract_recover_length_swap = code_value();
  4009. #endif
  4010. }
  4011. /**
  4012. * M209: Enable automatic retract (M209 S1)
  4013. * detect if the slicer did not support G10/11: every normal extrude-only move will be classified as retract depending on the direction.
  4014. */
  4015. inline void gcode_M209() {
  4016. if (code_seen('S')) {
  4017. int t = code_value_short();
  4018. switch (t) {
  4019. case 0:
  4020. autoretract_enabled = false;
  4021. break;
  4022. case 1:
  4023. autoretract_enabled = true;
  4024. break;
  4025. default:
  4026. unknown_command_error();
  4027. return;
  4028. }
  4029. for (int i = 0; i < EXTRUDERS; i++) retracted[i] = false;
  4030. }
  4031. }
  4032. #endif // FWRETRACT
  4033. #if EXTRUDERS > 1
  4034. /**
  4035. * M218 - set hotend offset (in mm), T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  4036. */
  4037. inline void gcode_M218() {
  4038. if (setTargetedHotend(218)) return;
  4039. if (code_seen('X')) extruder_offset[X_AXIS][target_extruder] = code_value();
  4040. if (code_seen('Y')) extruder_offset[Y_AXIS][target_extruder] = code_value();
  4041. #if ENABLED(DUAL_X_CARRIAGE)
  4042. if (code_seen('Z')) extruder_offset[Z_AXIS][target_extruder] = code_value();
  4043. #endif
  4044. SERIAL_ECHO_START;
  4045. SERIAL_ECHOPGM(MSG_HOTEND_OFFSET);
  4046. for (int e = 0; e < EXTRUDERS; e++) {
  4047. SERIAL_CHAR(' ');
  4048. SERIAL_ECHO(extruder_offset[X_AXIS][e]);
  4049. SERIAL_CHAR(',');
  4050. SERIAL_ECHO(extruder_offset[Y_AXIS][e]);
  4051. #if ENABLED(DUAL_X_CARRIAGE)
  4052. SERIAL_CHAR(',');
  4053. SERIAL_ECHO(extruder_offset[Z_AXIS][e]);
  4054. #endif
  4055. }
  4056. SERIAL_EOL;
  4057. }
  4058. #endif // EXTRUDERS > 1
  4059. /**
  4060. * M220: Set speed percentage factor, aka "Feed Rate" (M220 S95)
  4061. */
  4062. inline void gcode_M220() {
  4063. if (code_seen('S')) feedrate_multiplier = code_value();
  4064. }
  4065. /**
  4066. * M221: Set extrusion percentage (M221 T0 S95)
  4067. */
  4068. inline void gcode_M221() {
  4069. if (code_seen('S')) {
  4070. int sval = code_value();
  4071. if (setTargetedHotend(221)) return;
  4072. extruder_multiplier[target_extruder] = sval;
  4073. }
  4074. }
  4075. /**
  4076. * M226: Wait until the specified pin reaches the state required (M226 P<pin> S<state>)
  4077. */
  4078. inline void gcode_M226() {
  4079. if (code_seen('P')) {
  4080. int pin_number = code_value();
  4081. int pin_state = code_seen('S') ? code_value() : -1; // required pin state - default is inverted
  4082. if (pin_state >= -1 && pin_state <= 1) {
  4083. for (uint8_t i = 0; i < COUNT(sensitive_pins); i++) {
  4084. if (sensitive_pins[i] == pin_number) {
  4085. pin_number = -1;
  4086. break;
  4087. }
  4088. }
  4089. if (pin_number > -1) {
  4090. int target = LOW;
  4091. st_synchronize();
  4092. pinMode(pin_number, INPUT);
  4093. switch (pin_state) {
  4094. case 1:
  4095. target = HIGH;
  4096. break;
  4097. case 0:
  4098. target = LOW;
  4099. break;
  4100. case -1:
  4101. target = !digitalRead(pin_number);
  4102. break;
  4103. }
  4104. while (digitalRead(pin_number) != target) idle();
  4105. } // pin_number > -1
  4106. } // pin_state -1 0 1
  4107. } // code_seen('P')
  4108. }
  4109. #if HAS_SERVOS
  4110. /**
  4111. * M280: Get or set servo position. P<index> S<angle>
  4112. */
  4113. inline void gcode_M280() {
  4114. int servo_index = code_seen('P') ? code_value_short() : -1;
  4115. int servo_position = 0;
  4116. if (code_seen('S')) {
  4117. servo_position = code_value_short();
  4118. if (servo_index >= 0 && servo_index < NUM_SERVOS)
  4119. servo[servo_index].move(servo_position);
  4120. else {
  4121. SERIAL_ERROR_START;
  4122. SERIAL_ERROR("Servo ");
  4123. SERIAL_ERROR(servo_index);
  4124. SERIAL_ERRORLN(" out of range");
  4125. }
  4126. }
  4127. else if (servo_index >= 0) {
  4128. SERIAL_ECHO_START;
  4129. SERIAL_ECHO(" Servo ");
  4130. SERIAL_ECHO(servo_index);
  4131. SERIAL_ECHO(": ");
  4132. SERIAL_ECHOLN(servo[servo_index].read());
  4133. }
  4134. }
  4135. #endif // HAS_SERVOS
  4136. #if HAS_BUZZER
  4137. /**
  4138. * M300: Play beep sound S<frequency Hz> P<duration ms>
  4139. */
  4140. inline void gcode_M300() {
  4141. uint16_t beepS = code_seen('S') ? code_value_short() : 110;
  4142. uint32_t beepP = code_seen('P') ? code_value_long() : 1000;
  4143. if (beepP > 5000) beepP = 5000; // limit to 5 seconds
  4144. buzz(beepP, beepS);
  4145. }
  4146. #endif // HAS_BUZZER
  4147. #if ENABLED(PIDTEMP)
  4148. /**
  4149. * M301: Set PID parameters P I D (and optionally C, L)
  4150. *
  4151. * P[float] Kp term
  4152. * I[float] Ki term (unscaled)
  4153. * D[float] Kd term (unscaled)
  4154. *
  4155. * With PID_ADD_EXTRUSION_RATE:
  4156. *
  4157. * C[float] Kc term
  4158. * L[float] LPQ length
  4159. */
  4160. inline void gcode_M301() {
  4161. // multi-extruder PID patch: M301 updates or prints a single extruder's PID values
  4162. // default behaviour (omitting E parameter) is to update for extruder 0 only
  4163. int e = code_seen('E') ? code_value() : 0; // extruder being updated
  4164. if (e < EXTRUDERS) { // catch bad input value
  4165. if (code_seen('P')) PID_PARAM(Kp, e) = code_value();
  4166. if (code_seen('I')) PID_PARAM(Ki, e) = scalePID_i(code_value());
  4167. if (code_seen('D')) PID_PARAM(Kd, e) = scalePID_d(code_value());
  4168. #if ENABLED(PID_ADD_EXTRUSION_RATE)
  4169. if (code_seen('C')) PID_PARAM(Kc, e) = code_value();
  4170. if (code_seen('L')) lpq_len = code_value();
  4171. NOMORE(lpq_len, LPQ_MAX_LEN);
  4172. #endif
  4173. updatePID();
  4174. SERIAL_ECHO_START;
  4175. #if ENABLED(PID_PARAMS_PER_EXTRUDER)
  4176. SERIAL_ECHO(" e:"); // specify extruder in serial output
  4177. SERIAL_ECHO(e);
  4178. #endif // PID_PARAMS_PER_EXTRUDER
  4179. SERIAL_ECHO(" p:");
  4180. SERIAL_ECHO(PID_PARAM(Kp, e));
  4181. SERIAL_ECHO(" i:");
  4182. SERIAL_ECHO(unscalePID_i(PID_PARAM(Ki, e)));
  4183. SERIAL_ECHO(" d:");
  4184. SERIAL_ECHO(unscalePID_d(PID_PARAM(Kd, e)));
  4185. #if ENABLED(PID_ADD_EXTRUSION_RATE)
  4186. SERIAL_ECHO(" c:");
  4187. //Kc does not have scaling applied above, or in resetting defaults
  4188. SERIAL_ECHO(PID_PARAM(Kc, e));
  4189. #endif
  4190. SERIAL_EOL;
  4191. }
  4192. else {
  4193. SERIAL_ERROR_START;
  4194. SERIAL_ERRORLN(MSG_INVALID_EXTRUDER);
  4195. }
  4196. }
  4197. #endif // PIDTEMP
  4198. #if ENABLED(PIDTEMPBED)
  4199. inline void gcode_M304() {
  4200. if (code_seen('P')) bedKp = code_value();
  4201. if (code_seen('I')) bedKi = scalePID_i(code_value());
  4202. if (code_seen('D')) bedKd = scalePID_d(code_value());
  4203. updatePID();
  4204. SERIAL_ECHO_START;
  4205. SERIAL_ECHO(" p:");
  4206. SERIAL_ECHO(bedKp);
  4207. SERIAL_ECHO(" i:");
  4208. SERIAL_ECHO(unscalePID_i(bedKi));
  4209. SERIAL_ECHO(" d:");
  4210. SERIAL_ECHOLN(unscalePID_d(bedKd));
  4211. }
  4212. #endif // PIDTEMPBED
  4213. #if defined(CHDK) || HAS_PHOTOGRAPH
  4214. /**
  4215. * M240: Trigger a camera by emulating a Canon RC-1
  4216. * See http://www.doc-diy.net/photo/rc-1_hacked/
  4217. */
  4218. inline void gcode_M240() {
  4219. #ifdef CHDK
  4220. OUT_WRITE(CHDK, HIGH);
  4221. chdkHigh = millis();
  4222. chdkActive = true;
  4223. #elif HAS_PHOTOGRAPH
  4224. const uint8_t NUM_PULSES = 16;
  4225. const float PULSE_LENGTH = 0.01524;
  4226. for (int i = 0; i < NUM_PULSES; i++) {
  4227. WRITE(PHOTOGRAPH_PIN, HIGH);
  4228. _delay_ms(PULSE_LENGTH);
  4229. WRITE(PHOTOGRAPH_PIN, LOW);
  4230. _delay_ms(PULSE_LENGTH);
  4231. }
  4232. delay(7.33);
  4233. for (int i = 0; i < NUM_PULSES; i++) {
  4234. WRITE(PHOTOGRAPH_PIN, HIGH);
  4235. _delay_ms(PULSE_LENGTH);
  4236. WRITE(PHOTOGRAPH_PIN, LOW);
  4237. _delay_ms(PULSE_LENGTH);
  4238. }
  4239. #endif // !CHDK && HAS_PHOTOGRAPH
  4240. }
  4241. #endif // CHDK || PHOTOGRAPH_PIN
  4242. #if ENABLED(HAS_LCD_CONTRAST)
  4243. /**
  4244. * M250: Read and optionally set the LCD contrast
  4245. */
  4246. inline void gcode_M250() {
  4247. if (code_seen('C')) lcd_setcontrast(code_value_short() & 0x3F);
  4248. SERIAL_PROTOCOLPGM("lcd contrast value: ");
  4249. SERIAL_PROTOCOL(lcd_contrast);
  4250. SERIAL_EOL;
  4251. }
  4252. #endif // HAS_LCD_CONTRAST
  4253. #if ENABLED(PREVENT_DANGEROUS_EXTRUDE)
  4254. void set_extrude_min_temp(float temp) { extrude_min_temp = temp; }
  4255. /**
  4256. * M302: Allow cold extrudes, or set the minimum extrude S<temperature>.
  4257. */
  4258. inline void gcode_M302() {
  4259. set_extrude_min_temp(code_seen('S') ? code_value() : 0);
  4260. }
  4261. #endif // PREVENT_DANGEROUS_EXTRUDE
  4262. /**
  4263. * M303: PID relay autotune
  4264. * S<temperature> sets the target temperature. (default target temperature = 150C)
  4265. * E<extruder> (-1 for the bed)
  4266. * C<cycles>
  4267. */
  4268. inline void gcode_M303() {
  4269. int e = code_seen('E') ? code_value_short() : 0;
  4270. int c = code_seen('C') ? code_value_short() : 5;
  4271. float temp = code_seen('S') ? code_value() : (e < 0 ? 70.0 : 150.0);
  4272. if (e >=0 && e < EXTRUDERS)
  4273. target_extruder = e;
  4274. KEEPALIVE_STATE(NOT_BUSY);
  4275. PID_autotune(temp, e, c);
  4276. }
  4277. #if ENABLED(SCARA)
  4278. bool SCARA_move_to_cal(uint8_t delta_x, uint8_t delta_y) {
  4279. //SoftEndsEnabled = false; // Ignore soft endstops during calibration
  4280. //SERIAL_ECHOLN(" Soft endstops disabled ");
  4281. if (IsRunning()) {
  4282. //gcode_get_destination(); // For X Y Z E F
  4283. delta[X_AXIS] = delta_x;
  4284. delta[Y_AXIS] = delta_y;
  4285. calculate_SCARA_forward_Transform(delta);
  4286. destination[X_AXIS] = delta[X_AXIS] / axis_scaling[X_AXIS];
  4287. destination[Y_AXIS] = delta[Y_AXIS] / axis_scaling[Y_AXIS];
  4288. prepare_move();
  4289. //ok_to_send();
  4290. return true;
  4291. }
  4292. return false;
  4293. }
  4294. /**
  4295. * M360: SCARA calibration: Move to cal-position ThetaA (0 deg calibration)
  4296. */
  4297. inline bool gcode_M360() {
  4298. SERIAL_ECHOLN(" Cal: Theta 0 ");
  4299. return SCARA_move_to_cal(0, 120);
  4300. }
  4301. /**
  4302. * M361: SCARA calibration: Move to cal-position ThetaB (90 deg calibration - steps per degree)
  4303. */
  4304. inline bool gcode_M361() {
  4305. SERIAL_ECHOLN(" Cal: Theta 90 ");
  4306. return SCARA_move_to_cal(90, 130);
  4307. }
  4308. /**
  4309. * M362: SCARA calibration: Move to cal-position PsiA (0 deg calibration)
  4310. */
  4311. inline bool gcode_M362() {
  4312. SERIAL_ECHOLN(" Cal: Psi 0 ");
  4313. return SCARA_move_to_cal(60, 180);
  4314. }
  4315. /**
  4316. * M363: SCARA calibration: Move to cal-position PsiB (90 deg calibration - steps per degree)
  4317. */
  4318. inline bool gcode_M363() {
  4319. SERIAL_ECHOLN(" Cal: Psi 90 ");
  4320. return SCARA_move_to_cal(50, 90);
  4321. }
  4322. /**
  4323. * M364: SCARA calibration: Move to cal-position PSIC (90 deg to Theta calibration position)
  4324. */
  4325. inline bool gcode_M364() {
  4326. SERIAL_ECHOLN(" Cal: Theta-Psi 90 ");
  4327. return SCARA_move_to_cal(45, 135);
  4328. }
  4329. /**
  4330. * M365: SCARA calibration: Scaling factor, X, Y, Z axis
  4331. */
  4332. inline void gcode_M365() {
  4333. for (int8_t i = X_AXIS; i <= Z_AXIS; i++) {
  4334. if (code_seen(axis_codes[i])) {
  4335. axis_scaling[i] = code_value();
  4336. }
  4337. }
  4338. }
  4339. #endif // SCARA
  4340. #if ENABLED(EXT_SOLENOID)
  4341. void enable_solenoid(uint8_t num) {
  4342. switch (num) {
  4343. case 0:
  4344. OUT_WRITE(SOL0_PIN, HIGH);
  4345. break;
  4346. #if HAS_SOLENOID_1
  4347. case 1:
  4348. OUT_WRITE(SOL1_PIN, HIGH);
  4349. break;
  4350. #endif
  4351. #if HAS_SOLENOID_2
  4352. case 2:
  4353. OUT_WRITE(SOL2_PIN, HIGH);
  4354. break;
  4355. #endif
  4356. #if HAS_SOLENOID_3
  4357. case 3:
  4358. OUT_WRITE(SOL3_PIN, HIGH);
  4359. break;
  4360. #endif
  4361. default:
  4362. SERIAL_ECHO_START;
  4363. SERIAL_ECHOLNPGM(MSG_INVALID_SOLENOID);
  4364. break;
  4365. }
  4366. }
  4367. void enable_solenoid_on_active_extruder() { enable_solenoid(active_extruder); }
  4368. void disable_all_solenoids() {
  4369. OUT_WRITE(SOL0_PIN, LOW);
  4370. OUT_WRITE(SOL1_PIN, LOW);
  4371. OUT_WRITE(SOL2_PIN, LOW);
  4372. OUT_WRITE(SOL3_PIN, LOW);
  4373. }
  4374. /**
  4375. * M380: Enable solenoid on the active extruder
  4376. */
  4377. inline void gcode_M380() { enable_solenoid_on_active_extruder(); }
  4378. /**
  4379. * M381: Disable all solenoids
  4380. */
  4381. inline void gcode_M381() { disable_all_solenoids(); }
  4382. #endif // EXT_SOLENOID
  4383. /**
  4384. * M400: Finish all moves
  4385. */
  4386. inline void gcode_M400() { st_synchronize(); }
  4387. #if ENABLED(AUTO_BED_LEVELING_FEATURE) && DISABLED(Z_PROBE_SLED) && (HAS_SERVO_ENDSTOPS || ENABLED(Z_PROBE_ALLEN_KEY))
  4388. /**
  4389. * M401: Engage Z Servo endstop if available
  4390. */
  4391. inline void gcode_M401() {
  4392. #if HAS_SERVO_ENDSTOPS
  4393. raise_z_for_servo();
  4394. #endif
  4395. deploy_z_probe();
  4396. }
  4397. /**
  4398. * M402: Retract Z Servo endstop if enabled
  4399. */
  4400. inline void gcode_M402() {
  4401. #if HAS_SERVO_ENDSTOPS
  4402. raise_z_for_servo();
  4403. #endif
  4404. stow_z_probe(false);
  4405. }
  4406. #endif // AUTO_BED_LEVELING_FEATURE && (HAS_SERVO_ENDSTOPS || Z_PROBE_ALLEN_KEY) && !Z_PROBE_SLED
  4407. #if ENABLED(FILAMENT_SENSOR)
  4408. /**
  4409. * M404: Display or set the nominal filament width (3mm, 1.75mm ) W<3.0>
  4410. */
  4411. inline void gcode_M404() {
  4412. #if HAS_FILWIDTH
  4413. if (code_seen('W')) {
  4414. filament_width_nominal = code_value();
  4415. }
  4416. else {
  4417. SERIAL_PROTOCOLPGM("Filament dia (nominal mm):");
  4418. SERIAL_PROTOCOLLN(filament_width_nominal);
  4419. }
  4420. #endif
  4421. }
  4422. /**
  4423. * M405: Turn on filament sensor for control
  4424. */
  4425. inline void gcode_M405() {
  4426. if (code_seen('D')) meas_delay_cm = code_value();
  4427. NOMORE(meas_delay_cm, MAX_MEASUREMENT_DELAY);
  4428. if (delay_index2 == -1) { //initialize the ring buffer if it has not been done since startup
  4429. int temp_ratio = widthFil_to_size_ratio();
  4430. for (delay_index1 = 0; delay_index1 < MAX_MEASUREMENT_DELAY + 1; ++delay_index1)
  4431. measurement_delay[delay_index1] = temp_ratio - 100; //subtract 100 to scale within a signed byte
  4432. delay_index1 = delay_index2 = 0;
  4433. }
  4434. filament_sensor = true;
  4435. //SERIAL_PROTOCOLPGM("Filament dia (measured mm):");
  4436. //SERIAL_PROTOCOL(filament_width_meas);
  4437. //SERIAL_PROTOCOLPGM("Extrusion ratio(%):");
  4438. //SERIAL_PROTOCOL(extruder_multiplier[active_extruder]);
  4439. }
  4440. /**
  4441. * M406: Turn off filament sensor for control
  4442. */
  4443. inline void gcode_M406() { filament_sensor = false; }
  4444. /**
  4445. * M407: Get measured filament diameter on serial output
  4446. */
  4447. inline void gcode_M407() {
  4448. SERIAL_PROTOCOLPGM("Filament dia (measured mm):");
  4449. SERIAL_PROTOCOLLN(filament_width_meas);
  4450. }
  4451. #endif // FILAMENT_SENSOR
  4452. /**
  4453. * M410: Quickstop - Abort all planned moves
  4454. *
  4455. * This will stop the carriages mid-move, so most likely they
  4456. * will be out of sync with the stepper position after this.
  4457. */
  4458. inline void gcode_M410() { quickStop(); }
  4459. #if ENABLED(MESH_BED_LEVELING)
  4460. /**
  4461. * M420: Enable/Disable Mesh Bed Leveling
  4462. */
  4463. inline void gcode_M420() { if (code_seen('S') && code_has_value()) mbl.active = !!code_value_short(); }
  4464. /**
  4465. * M421: Set a single Mesh Bed Leveling Z coordinate
  4466. */
  4467. inline void gcode_M421() {
  4468. float x, y, z;
  4469. bool err = false, hasX, hasY, hasZ;
  4470. if ((hasX = code_seen('X'))) x = code_value();
  4471. if ((hasY = code_seen('Y'))) y = code_value();
  4472. if ((hasZ = code_seen('Z'))) z = code_value();
  4473. if (!hasX || !hasY || !hasZ) {
  4474. SERIAL_ERROR_START;
  4475. SERIAL_ERRORLNPGM(MSG_ERR_M421_REQUIRES_XYZ);
  4476. err = true;
  4477. }
  4478. if (x >= MESH_NUM_X_POINTS || y >= MESH_NUM_Y_POINTS) {
  4479. SERIAL_ERROR_START;
  4480. SERIAL_ERRORLNPGM(MSG_ERR_MESH_INDEX_OOB);
  4481. err = true;
  4482. }
  4483. if (!err) mbl.set_z(mbl.select_x_index(x), mbl.select_y_index(y), z);
  4484. }
  4485. #endif
  4486. /**
  4487. * M428: Set home_offset based on the distance between the
  4488. * current_position and the nearest "reference point."
  4489. * If an axis is past center its endstop position
  4490. * is the reference-point. Otherwise it uses 0. This allows
  4491. * the Z offset to be set near the bed when using a max endstop.
  4492. *
  4493. * M428 can't be used more than 2cm away from 0 or an endstop.
  4494. *
  4495. * Use M206 to set these values directly.
  4496. */
  4497. inline void gcode_M428() {
  4498. bool err = false;
  4499. float new_offs[3], new_pos[3];
  4500. memcpy(new_pos, current_position, sizeof(new_pos));
  4501. memcpy(new_offs, home_offset, sizeof(new_offs));
  4502. for (int8_t i = X_AXIS; i <= Z_AXIS; i++) {
  4503. if (axis_known_position[i]) {
  4504. float base = (new_pos[i] > (min_pos[i] + max_pos[i]) / 2) ? base_home_pos(i) : 0,
  4505. diff = new_pos[i] - base;
  4506. if (diff > -20 && diff < 20) {
  4507. new_offs[i] -= diff;
  4508. new_pos[i] = base;
  4509. }
  4510. else {
  4511. SERIAL_ERROR_START;
  4512. SERIAL_ERRORLNPGM(MSG_ERR_M428_TOO_FAR);
  4513. LCD_ALERTMESSAGEPGM("Err: Too far!");
  4514. #if HAS_BUZZER
  4515. enqueue_and_echo_commands_P(PSTR("M300 S40 P200"));
  4516. #endif
  4517. err = true;
  4518. break;
  4519. }
  4520. }
  4521. }
  4522. if (!err) {
  4523. memcpy(current_position, new_pos, sizeof(new_pos));
  4524. memcpy(home_offset, new_offs, sizeof(new_offs));
  4525. sync_plan_position();
  4526. LCD_ALERTMESSAGEPGM("Offset applied.");
  4527. #if HAS_BUZZER
  4528. enqueue_and_echo_commands_P(PSTR("M300 S659 P200\nM300 S698 P200"));
  4529. #endif
  4530. }
  4531. }
  4532. /**
  4533. * M500: Store settings in EEPROM
  4534. */
  4535. inline void gcode_M500() {
  4536. Config_StoreSettings();
  4537. }
  4538. /**
  4539. * M501: Read settings from EEPROM
  4540. */
  4541. inline void gcode_M501() {
  4542. Config_RetrieveSettings();
  4543. }
  4544. /**
  4545. * M502: Revert to default settings
  4546. */
  4547. inline void gcode_M502() {
  4548. Config_ResetDefault();
  4549. }
  4550. /**
  4551. * M503: print settings currently in memory
  4552. */
  4553. inline void gcode_M503() {
  4554. Config_PrintSettings(code_seen('S') && code_value() == 0);
  4555. }
  4556. #if ENABLED(ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  4557. /**
  4558. * M540: Set whether SD card print should abort on endstop hit (M540 S<0|1>)
  4559. */
  4560. inline void gcode_M540() {
  4561. if (code_seen('S')) abort_on_endstop_hit = (code_value() > 0);
  4562. }
  4563. #endif // ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED
  4564. #ifdef CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  4565. inline void gcode_SET_Z_PROBE_OFFSET() {
  4566. SERIAL_ECHO_START;
  4567. SERIAL_ECHOPGM(MSG_ZPROBE_ZOFFSET);
  4568. SERIAL_CHAR(' ');
  4569. if (code_seen('Z')) {
  4570. float value = code_value();
  4571. if (Z_PROBE_OFFSET_RANGE_MIN <= value && value <= Z_PROBE_OFFSET_RANGE_MAX) {
  4572. zprobe_zoffset = value;
  4573. SERIAL_ECHO(zprobe_zoffset);
  4574. }
  4575. else {
  4576. SERIAL_ECHOPGM(MSG_Z_MIN);
  4577. SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MIN);
  4578. SERIAL_ECHOPGM(MSG_Z_MAX);
  4579. SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MAX);
  4580. }
  4581. }
  4582. else {
  4583. SERIAL_ECHOPAIR(": ", zprobe_zoffset);
  4584. }
  4585. SERIAL_EOL;
  4586. }
  4587. #endif // CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  4588. #if ENABLED(FILAMENTCHANGEENABLE)
  4589. /**
  4590. * M600: Pause for filament change
  4591. *
  4592. * E[distance] - Retract the filament this far (negative value)
  4593. * Z[distance] - Move the Z axis by this distance
  4594. * X[position] - Move to this X position, with Y
  4595. * Y[position] - Move to this Y position, with X
  4596. * L[distance] - Retract distance for removal (manual reload)
  4597. *
  4598. * Default values are used for omitted arguments.
  4599. *
  4600. */
  4601. inline void gcode_M600() {
  4602. if (degHotend(active_extruder) < extrude_min_temp) {
  4603. SERIAL_ERROR_START;
  4604. SERIAL_ERRORLNPGM(MSG_TOO_COLD_FOR_M600);
  4605. return;
  4606. }
  4607. float lastpos[NUM_AXIS], fr60 = feedrate / 60;
  4608. for (int i = 0; i < NUM_AXIS; i++)
  4609. lastpos[i] = destination[i] = current_position[i];
  4610. #if ENABLED(DELTA)
  4611. #define RUNPLAN calculate_delta(destination); \
  4612. plan_buffer_line(delta[X_AXIS], delta[Y_AXIS], delta[Z_AXIS], destination[E_AXIS], fr60, active_extruder);
  4613. #else
  4614. #define RUNPLAN line_to_destination();
  4615. #endif
  4616. //retract by E
  4617. if (code_seen('E')) destination[E_AXIS] += code_value();
  4618. #ifdef FILAMENTCHANGE_FIRSTRETRACT
  4619. else destination[E_AXIS] += FILAMENTCHANGE_FIRSTRETRACT;
  4620. #endif
  4621. RUNPLAN;
  4622. //lift Z
  4623. if (code_seen('Z')) destination[Z_AXIS] += code_value();
  4624. #ifdef FILAMENTCHANGE_ZADD
  4625. else destination[Z_AXIS] += FILAMENTCHANGE_ZADD;
  4626. #endif
  4627. RUNPLAN;
  4628. //move xy
  4629. if (code_seen('X')) destination[X_AXIS] = code_value();
  4630. #ifdef FILAMENTCHANGE_XPOS
  4631. else destination[X_AXIS] = FILAMENTCHANGE_XPOS;
  4632. #endif
  4633. if (code_seen('Y')) destination[Y_AXIS] = code_value();
  4634. #ifdef FILAMENTCHANGE_YPOS
  4635. else destination[Y_AXIS] = FILAMENTCHANGE_YPOS;
  4636. #endif
  4637. RUNPLAN;
  4638. if (code_seen('L')) destination[E_AXIS] += code_value();
  4639. #ifdef FILAMENTCHANGE_FINALRETRACT
  4640. else destination[E_AXIS] += FILAMENTCHANGE_FINALRETRACT;
  4641. #endif
  4642. RUNPLAN;
  4643. //finish moves
  4644. st_synchronize();
  4645. //disable extruder steppers so filament can be removed
  4646. disable_e0();
  4647. disable_e1();
  4648. disable_e2();
  4649. disable_e3();
  4650. delay(100);
  4651. LCD_ALERTMESSAGEPGM(MSG_FILAMENTCHANGE);
  4652. millis_t next_tick = 0;
  4653. KEEPALIVE_STATE(WAIT_FOR_USER);
  4654. while (!lcd_clicked()) {
  4655. #if DISABLED(AUTO_FILAMENT_CHANGE)
  4656. millis_t ms = millis();
  4657. if (ms >= next_tick) {
  4658. lcd_quick_feedback();
  4659. next_tick = ms + 2500; // feedback every 2.5s while waiting
  4660. }
  4661. idle(true);
  4662. #else
  4663. current_position[E_AXIS] += AUTO_FILAMENT_CHANGE_LENGTH;
  4664. destination[E_AXIS] = current_position[E_AXIS];
  4665. line_to_destination(AUTO_FILAMENT_CHANGE_FEEDRATE);
  4666. st_synchronize();
  4667. #endif
  4668. } // while(!lcd_clicked)
  4669. KEEPALIVE_STATE(IN_HANDLER);
  4670. lcd_quick_feedback(); // click sound feedback
  4671. #if ENABLED(AUTO_FILAMENT_CHANGE)
  4672. current_position[E_AXIS] = 0;
  4673. st_synchronize();
  4674. #endif
  4675. //return to normal
  4676. if (code_seen('L')) destination[E_AXIS] -= code_value();
  4677. #ifdef FILAMENTCHANGE_FINALRETRACT
  4678. else destination[E_AXIS] -= FILAMENTCHANGE_FINALRETRACT;
  4679. #endif
  4680. current_position[E_AXIS] = destination[E_AXIS]; //the long retract of L is compensated by manual filament feeding
  4681. plan_set_e_position(current_position[E_AXIS]);
  4682. RUNPLAN; //should do nothing
  4683. lcd_reset_alert_level();
  4684. #if ENABLED(DELTA)
  4685. // Move XYZ to starting position, then E
  4686. calculate_delta(lastpos);
  4687. plan_buffer_line(delta[X_AXIS], delta[Y_AXIS], delta[Z_AXIS], destination[E_AXIS], fr60, active_extruder);
  4688. plan_buffer_line(delta[X_AXIS], delta[Y_AXIS], delta[Z_AXIS], lastpos[E_AXIS], fr60, active_extruder);
  4689. #else
  4690. // Move XY to starting position, then Z, then E
  4691. destination[X_AXIS] = lastpos[X_AXIS];
  4692. destination[Y_AXIS] = lastpos[Y_AXIS];
  4693. line_to_destination();
  4694. destination[Z_AXIS] = lastpos[Z_AXIS];
  4695. line_to_destination();
  4696. destination[E_AXIS] = lastpos[E_AXIS];
  4697. line_to_destination();
  4698. #endif
  4699. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  4700. filrunoutEnqueued = false;
  4701. #endif
  4702. }
  4703. #endif // FILAMENTCHANGEENABLE
  4704. #if ENABLED(DUAL_X_CARRIAGE)
  4705. /**
  4706. * M605: Set dual x-carriage movement mode
  4707. *
  4708. * M605 S0: Full control mode. The slicer has full control over x-carriage movement
  4709. * M605 S1: Auto-park mode. The inactive head will auto park/unpark without slicer involvement
  4710. * M605 S2 [Xnnn] [Rmmm]: Duplication mode. The second extruder will duplicate the first with nnn
  4711. * millimeters x-offset and an optional differential hotend temperature of
  4712. * mmm degrees. E.g., with "M605 S2 X100 R2" the second extruder will duplicate
  4713. * the first with a spacing of 100mm in the x direction and 2 degrees hotter.
  4714. *
  4715. * Note: the X axis should be homed after changing dual x-carriage mode.
  4716. */
  4717. inline void gcode_M605() {
  4718. st_synchronize();
  4719. if (code_seen('S')) dual_x_carriage_mode = code_value();
  4720. switch (dual_x_carriage_mode) {
  4721. case DXC_DUPLICATION_MODE:
  4722. if (code_seen('X')) duplicate_extruder_x_offset = max(code_value(), X2_MIN_POS - x_home_pos(0));
  4723. if (code_seen('R')) duplicate_extruder_temp_offset = code_value();
  4724. SERIAL_ECHO_START;
  4725. SERIAL_ECHOPGM(MSG_HOTEND_OFFSET);
  4726. SERIAL_CHAR(' ');
  4727. SERIAL_ECHO(extruder_offset[X_AXIS][0]);
  4728. SERIAL_CHAR(',');
  4729. SERIAL_ECHO(extruder_offset[Y_AXIS][0]);
  4730. SERIAL_CHAR(' ');
  4731. SERIAL_ECHO(duplicate_extruder_x_offset);
  4732. SERIAL_CHAR(',');
  4733. SERIAL_ECHOLN(extruder_offset[Y_AXIS][1]);
  4734. break;
  4735. case DXC_FULL_CONTROL_MODE:
  4736. case DXC_AUTO_PARK_MODE:
  4737. break;
  4738. default:
  4739. dual_x_carriage_mode = DEFAULT_DUAL_X_CARRIAGE_MODE;
  4740. break;
  4741. }
  4742. active_extruder_parked = false;
  4743. extruder_duplication_enabled = false;
  4744. delayed_move_time = 0;
  4745. }
  4746. #endif // DUAL_X_CARRIAGE
  4747. /**
  4748. * M907: Set digital trimpot motor current using axis codes X, Y, Z, E, B, S
  4749. */
  4750. inline void gcode_M907() {
  4751. #if HAS_DIGIPOTSS
  4752. for (int i = 0; i < NUM_AXIS; i++)
  4753. if (code_seen(axis_codes[i])) digipot_current(i, code_value());
  4754. if (code_seen('B')) digipot_current(4, code_value());
  4755. if (code_seen('S')) for (int i = 0; i <= 4; i++) digipot_current(i, code_value());
  4756. #endif
  4757. #ifdef MOTOR_CURRENT_PWM_XY_PIN
  4758. if (code_seen('X')) digipot_current(0, code_value());
  4759. #endif
  4760. #ifdef MOTOR_CURRENT_PWM_Z_PIN
  4761. if (code_seen('Z')) digipot_current(1, code_value());
  4762. #endif
  4763. #ifdef MOTOR_CURRENT_PWM_E_PIN
  4764. if (code_seen('E')) digipot_current(2, code_value());
  4765. #endif
  4766. #if ENABLED(DIGIPOT_I2C)
  4767. // this one uses actual amps in floating point
  4768. for (int i = 0; i < NUM_AXIS; i++) if (code_seen(axis_codes[i])) digipot_i2c_set_current(i, code_value());
  4769. // for each additional extruder (named B,C,D,E..., channels 4,5,6,7...)
  4770. for (int i = NUM_AXIS; i < DIGIPOT_I2C_NUM_CHANNELS; i++) if (code_seen('B' + i - (NUM_AXIS))) digipot_i2c_set_current(i, code_value());
  4771. #endif
  4772. }
  4773. #if HAS_DIGIPOTSS
  4774. /**
  4775. * M908: Control digital trimpot directly (M908 P<pin> S<current>)
  4776. */
  4777. inline void gcode_M908() {
  4778. digitalPotWrite(
  4779. code_seen('P') ? code_value() : 0,
  4780. code_seen('S') ? code_value() : 0
  4781. );
  4782. }
  4783. #endif // HAS_DIGIPOTSS
  4784. #if HAS_MICROSTEPS
  4785. // M350 Set microstepping mode. Warning: Steps per unit remains unchanged. S code sets stepping mode for all drivers.
  4786. inline void gcode_M350() {
  4787. if (code_seen('S')) for (int i = 0; i <= 4; i++) microstep_mode(i, code_value());
  4788. for (int i = 0; i < NUM_AXIS; i++) if (code_seen(axis_codes[i])) microstep_mode(i, (uint8_t)code_value());
  4789. if (code_seen('B')) microstep_mode(4, code_value());
  4790. microstep_readings();
  4791. }
  4792. /**
  4793. * M351: Toggle MS1 MS2 pins directly with axis codes X Y Z E B
  4794. * S# determines MS1 or MS2, X# sets the pin high/low.
  4795. */
  4796. inline void gcode_M351() {
  4797. if (code_seen('S')) switch (code_value_short()) {
  4798. case 1:
  4799. for (int i = 0; i < NUM_AXIS; i++) if (code_seen(axis_codes[i])) microstep_ms(i, code_value(), -1);
  4800. if (code_seen('B')) microstep_ms(4, code_value(), -1);
  4801. break;
  4802. case 2:
  4803. for (int i = 0; i < NUM_AXIS; i++) if (code_seen(axis_codes[i])) microstep_ms(i, -1, code_value());
  4804. if (code_seen('B')) microstep_ms(4, -1, code_value());
  4805. break;
  4806. }
  4807. microstep_readings();
  4808. }
  4809. #endif // HAS_MICROSTEPS
  4810. /**
  4811. * M999: Restart after being stopped
  4812. */
  4813. inline void gcode_M999() {
  4814. Running = true;
  4815. lcd_reset_alert_level();
  4816. // gcode_LastN = Stopped_gcode_LastN;
  4817. FlushSerialRequestResend();
  4818. }
  4819. /**
  4820. * T0-T3: Switch tool, usually switching extruders
  4821. *
  4822. * F[mm/min] Set the movement feedrate
  4823. */
  4824. inline void gcode_T(uint8_t tmp_extruder) {
  4825. if (tmp_extruder >= EXTRUDERS) {
  4826. SERIAL_ECHO_START;
  4827. SERIAL_CHAR('T');
  4828. SERIAL_PROTOCOL_F(tmp_extruder, DEC);
  4829. SERIAL_ECHOLN(MSG_INVALID_EXTRUDER);
  4830. }
  4831. else {
  4832. target_extruder = tmp_extruder;
  4833. #if EXTRUDERS > 1
  4834. bool make_move = false;
  4835. #endif
  4836. if (code_seen('F')) {
  4837. #if EXTRUDERS > 1
  4838. make_move = true;
  4839. #endif
  4840. float next_feedrate = code_value();
  4841. if (next_feedrate > 0.0) feedrate = next_feedrate;
  4842. }
  4843. #if EXTRUDERS > 1
  4844. if (tmp_extruder != active_extruder) {
  4845. // Save current position to return to after applying extruder offset
  4846. set_destination_to_current();
  4847. #if ENABLED(DUAL_X_CARRIAGE)
  4848. if (dual_x_carriage_mode == DXC_AUTO_PARK_MODE && IsRunning() &&
  4849. (delayed_move_time != 0 || current_position[X_AXIS] != x_home_pos(active_extruder))) {
  4850. // Park old head: 1) raise 2) move to park position 3) lower
  4851. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS] + TOOLCHANGE_PARK_ZLIFT,
  4852. current_position[E_AXIS], max_feedrate[Z_AXIS], active_extruder);
  4853. plan_buffer_line(x_home_pos(active_extruder), current_position[Y_AXIS], current_position[Z_AXIS] + TOOLCHANGE_PARK_ZLIFT,
  4854. current_position[E_AXIS], max_feedrate[X_AXIS], active_extruder);
  4855. plan_buffer_line(x_home_pos(active_extruder), current_position[Y_AXIS], current_position[Z_AXIS],
  4856. current_position[E_AXIS], max_feedrate[Z_AXIS], active_extruder);
  4857. st_synchronize();
  4858. }
  4859. // apply Y & Z extruder offset (x offset is already used in determining home pos)
  4860. current_position[Y_AXIS] -= extruder_offset[Y_AXIS][active_extruder] - extruder_offset[Y_AXIS][tmp_extruder];
  4861. current_position[Z_AXIS] -= extruder_offset[Z_AXIS][active_extruder] - extruder_offset[Z_AXIS][tmp_extruder];
  4862. active_extruder = tmp_extruder;
  4863. // This function resets the max/min values - the current position may be overwritten below.
  4864. set_axis_is_at_home(X_AXIS);
  4865. if (dual_x_carriage_mode == DXC_FULL_CONTROL_MODE) {
  4866. current_position[X_AXIS] = inactive_extruder_x_pos;
  4867. inactive_extruder_x_pos = destination[X_AXIS];
  4868. }
  4869. else if (dual_x_carriage_mode == DXC_DUPLICATION_MODE) {
  4870. active_extruder_parked = (active_extruder == 0); // this triggers the second extruder to move into the duplication position
  4871. if (active_extruder == 0 || active_extruder_parked)
  4872. current_position[X_AXIS] = inactive_extruder_x_pos;
  4873. else
  4874. current_position[X_AXIS] = destination[X_AXIS] + duplicate_extruder_x_offset;
  4875. inactive_extruder_x_pos = destination[X_AXIS];
  4876. extruder_duplication_enabled = false;
  4877. }
  4878. else {
  4879. // record raised toolhead position for use by unpark
  4880. memcpy(raised_parked_position, current_position, sizeof(raised_parked_position));
  4881. raised_parked_position[Z_AXIS] += TOOLCHANGE_UNPARK_ZLIFT;
  4882. active_extruder_parked = true;
  4883. delayed_move_time = 0;
  4884. }
  4885. #else // !DUAL_X_CARRIAGE
  4886. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  4887. // Offset extruder, make sure to apply the bed level rotation matrix
  4888. vector_3 tmp_offset_vec = vector_3(extruder_offset[X_AXIS][tmp_extruder],
  4889. extruder_offset[Y_AXIS][tmp_extruder],
  4890. extruder_offset[Z_AXIS][tmp_extruder]),
  4891. act_offset_vec = vector_3(extruder_offset[X_AXIS][active_extruder],
  4892. extruder_offset[Y_AXIS][active_extruder],
  4893. extruder_offset[Z_AXIS][active_extruder]),
  4894. offset_vec = tmp_offset_vec - act_offset_vec;
  4895. offset_vec.apply_rotation(plan_bed_level_matrix.transpose(plan_bed_level_matrix));
  4896. current_position[X_AXIS] += offset_vec.x;
  4897. current_position[Y_AXIS] += offset_vec.y;
  4898. current_position[Z_AXIS] += offset_vec.z;
  4899. #else // !AUTO_BED_LEVELING_FEATURE
  4900. // Offset extruder (only by XY)
  4901. for (int i=X_AXIS; i<=Y_AXIS; i++)
  4902. current_position[i] += extruder_offset[i][tmp_extruder] - extruder_offset[i][active_extruder];
  4903. #endif // !AUTO_BED_LEVELING_FEATURE
  4904. // Set the new active extruder and position
  4905. active_extruder = tmp_extruder;
  4906. #endif // !DUAL_X_CARRIAGE
  4907. #if ENABLED(DELTA)
  4908. sync_plan_position_delta();
  4909. #else
  4910. sync_plan_position();
  4911. #endif
  4912. // Move to the old position if 'F' was in the parameters
  4913. if (make_move && IsRunning()) prepare_move();
  4914. }
  4915. #if ENABLED(EXT_SOLENOID)
  4916. st_synchronize();
  4917. disable_all_solenoids();
  4918. enable_solenoid_on_active_extruder();
  4919. #endif // EXT_SOLENOID
  4920. #endif // EXTRUDERS > 1
  4921. SERIAL_ECHO_START;
  4922. SERIAL_ECHO(MSG_ACTIVE_EXTRUDER);
  4923. SERIAL_PROTOCOLLN((int)active_extruder);
  4924. }
  4925. }
  4926. /**
  4927. * Process a single command and dispatch it to its handler
  4928. * This is called from the main loop()
  4929. */
  4930. void process_next_command() {
  4931. current_command = command_queue[cmd_queue_index_r];
  4932. if ((marlin_debug_flags & DEBUG_ECHO)) {
  4933. SERIAL_ECHO_START;
  4934. SERIAL_ECHOLN(current_command);
  4935. }
  4936. // Sanitize the current command:
  4937. // - Skip leading spaces
  4938. // - Bypass N[-0-9][0-9]*[ ]*
  4939. // - Overwrite * with nul to mark the end
  4940. while (*current_command == ' ') ++current_command;
  4941. if (*current_command == 'N' && ((current_command[1] >= '0' && current_command[1] <= '9') || current_command[1] == '-')) {
  4942. current_command += 2; // skip N[-0-9]
  4943. while (*current_command >= '0' && *current_command <= '9') ++current_command; // skip [0-9]*
  4944. while (*current_command == ' ') ++current_command; // skip [ ]*
  4945. }
  4946. char* starpos = strchr(current_command, '*'); // * should always be the last parameter
  4947. if (starpos) while (*starpos == ' ' || *starpos == '*') *starpos-- = '\0'; // nullify '*' and ' '
  4948. // Get the command code, which must be G, M, or T
  4949. char command_code = *current_command;
  4950. // Skip the letter-code and spaces to get the numeric part
  4951. current_command_args = current_command + 1;
  4952. while (*current_command_args == ' ') ++current_command_args;
  4953. // The code must have a numeric value
  4954. bool code_is_good = (*current_command_args >= '0' && *current_command_args <= '9');
  4955. int codenum; // define ahead of goto
  4956. // Bail early if there's no code
  4957. if (!code_is_good) goto ExitUnknownCommand;
  4958. // Args pointer optimizes code_seen, especially those taking XYZEF
  4959. // This wastes a little cpu on commands that expect no arguments.
  4960. while (*current_command_args == ' ' || (*current_command_args >= '0' && *current_command_args <= '9')) ++current_command_args;
  4961. // Interpret the code int
  4962. seen_pointer = current_command;
  4963. codenum = code_value_short();
  4964. KEEPALIVE_STATE(IN_HANDLER);
  4965. // Handle a known G, M, or T
  4966. switch (command_code) {
  4967. case 'G': switch (codenum) {
  4968. // G0, G1
  4969. case 0:
  4970. case 1:
  4971. gcode_G0_G1();
  4972. break;
  4973. // G2, G3
  4974. #if DISABLED(SCARA)
  4975. case 2: // G2 - CW ARC
  4976. case 3: // G3 - CCW ARC
  4977. gcode_G2_G3(codenum == 2);
  4978. break;
  4979. #endif
  4980. // G4 Dwell
  4981. case 4:
  4982. gcode_G4();
  4983. break;
  4984. #if ENABLED(FWRETRACT)
  4985. case 10: // G10: retract
  4986. case 11: // G11: retract_recover
  4987. gcode_G10_G11(codenum == 10);
  4988. break;
  4989. #endif //FWRETRACT
  4990. case 28: // G28: Home all axes, one at a time
  4991. gcode_G28();
  4992. break;
  4993. #if ENABLED(AUTO_BED_LEVELING_FEATURE) || ENABLED(MESH_BED_LEVELING)
  4994. case 29: // G29 Detailed Z probe, probes the bed at 3 or more points.
  4995. gcode_G29();
  4996. break;
  4997. #endif
  4998. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  4999. #if DISABLED(Z_PROBE_SLED)
  5000. case 30: // G30 Single Z probe
  5001. gcode_G30();
  5002. break;
  5003. #else // Z_PROBE_SLED
  5004. case 31: // G31: dock the sled
  5005. case 32: // G32: undock the sled
  5006. dock_sled(codenum == 31);
  5007. break;
  5008. #endif // Z_PROBE_SLED
  5009. #endif // AUTO_BED_LEVELING_FEATURE
  5010. case 90: // G90
  5011. relative_mode = false;
  5012. break;
  5013. case 91: // G91
  5014. relative_mode = true;
  5015. break;
  5016. case 92: // G92
  5017. gcode_G92();
  5018. break;
  5019. }
  5020. break;
  5021. case 'M': switch (codenum) {
  5022. #if ENABLED(ULTIPANEL)
  5023. case 0: // M0 - Unconditional stop - Wait for user button press on LCD
  5024. case 1: // M1 - Conditional stop - Wait for user button press on LCD
  5025. gcode_M0_M1();
  5026. break;
  5027. #endif // ULTIPANEL
  5028. case 17:
  5029. gcode_M17();
  5030. break;
  5031. #if ENABLED(SDSUPPORT)
  5032. case 20: // M20 - list SD card
  5033. gcode_M20(); break;
  5034. case 21: // M21 - init SD card
  5035. gcode_M21(); break;
  5036. case 22: //M22 - release SD card
  5037. gcode_M22(); break;
  5038. case 23: //M23 - Select file
  5039. gcode_M23(); break;
  5040. case 24: //M24 - Start SD print
  5041. gcode_M24(); break;
  5042. case 25: //M25 - Pause SD print
  5043. gcode_M25(); break;
  5044. case 26: //M26 - Set SD index
  5045. gcode_M26(); break;
  5046. case 27: //M27 - Get SD status
  5047. gcode_M27(); break;
  5048. case 28: //M28 - Start SD write
  5049. gcode_M28(); break;
  5050. case 29: //M29 - Stop SD write
  5051. gcode_M29(); break;
  5052. case 30: //M30 <filename> Delete File
  5053. gcode_M30(); break;
  5054. case 32: //M32 - Select file and start SD print
  5055. gcode_M32(); break;
  5056. #if ENABLED(LONG_FILENAME_HOST_SUPPORT)
  5057. case 33: //M33 - Get the long full path to a file or folder
  5058. gcode_M33(); break;
  5059. #endif // LONG_FILENAME_HOST_SUPPORT
  5060. case 928: //M928 - Start SD write
  5061. gcode_M928(); break;
  5062. #endif //SDSUPPORT
  5063. case 31: //M31 take time since the start of the SD print or an M109 command
  5064. gcode_M31();
  5065. break;
  5066. case 42: //M42 -Change pin status via gcode
  5067. gcode_M42();
  5068. break;
  5069. #if ENABLED(AUTO_BED_LEVELING_FEATURE) && ENABLED(Z_MIN_PROBE_REPEATABILITY_TEST)
  5070. case 48: // M48 Z probe repeatability
  5071. gcode_M48();
  5072. break;
  5073. #endif // AUTO_BED_LEVELING_FEATURE && Z_MIN_PROBE_REPEATABILITY_TEST
  5074. #if ENABLED(M100_FREE_MEMORY_WATCHER)
  5075. case 100:
  5076. gcode_M100();
  5077. break;
  5078. #endif
  5079. case 104: // M104
  5080. gcode_M104();
  5081. break;
  5082. case 110: // M110: Set Current Line Number
  5083. gcode_M110();
  5084. break;
  5085. case 111: // M111: Set debug level
  5086. gcode_M111();
  5087. break;
  5088. case 112: // M112: Emergency Stop
  5089. gcode_M112();
  5090. break;
  5091. case 140: // M140: Set bed temp
  5092. gcode_M140();
  5093. break;
  5094. case 105: // M105: Read current temperature
  5095. gcode_M105();
  5096. return; // "ok" already printed
  5097. case 109: // M109: Wait for temperature
  5098. gcode_M109();
  5099. break;
  5100. #if HAS_TEMP_BED
  5101. case 190: // M190: Wait for bed heater to reach target
  5102. gcode_M190();
  5103. break;
  5104. #endif // HAS_TEMP_BED
  5105. #if HAS_FAN
  5106. case 106: // M106: Fan On
  5107. gcode_M106();
  5108. break;
  5109. case 107: // M107: Fan Off
  5110. gcode_M107();
  5111. break;
  5112. #endif // HAS_FAN
  5113. #if ENABLED(BARICUDA)
  5114. // PWM for HEATER_1_PIN
  5115. #if HAS_HEATER_1
  5116. case 126: // M126: valve open
  5117. gcode_M126();
  5118. break;
  5119. case 127: // M127: valve closed
  5120. gcode_M127();
  5121. break;
  5122. #endif // HAS_HEATER_1
  5123. // PWM for HEATER_2_PIN
  5124. #if HAS_HEATER_2
  5125. case 128: // M128: valve open
  5126. gcode_M128();
  5127. break;
  5128. case 129: // M129: valve closed
  5129. gcode_M129();
  5130. break;
  5131. #endif // HAS_HEATER_2
  5132. #endif // BARICUDA
  5133. #if HAS_POWER_SWITCH
  5134. case 80: // M80: Turn on Power Supply
  5135. gcode_M80();
  5136. break;
  5137. #endif // HAS_POWER_SWITCH
  5138. case 81: // M81: Turn off Power, including Power Supply, if possible
  5139. gcode_M81();
  5140. break;
  5141. case 82:
  5142. gcode_M82();
  5143. break;
  5144. case 83:
  5145. gcode_M83();
  5146. break;
  5147. case 18: // (for compatibility)
  5148. case 84: // M84
  5149. gcode_M18_M84();
  5150. break;
  5151. case 85: // M85
  5152. gcode_M85();
  5153. break;
  5154. case 92: // M92: Set the steps-per-unit for one or more axes
  5155. gcode_M92();
  5156. break;
  5157. case 115: // M115: Report capabilities
  5158. gcode_M115();
  5159. break;
  5160. case 117: // M117: Set LCD message text, if possible
  5161. gcode_M117();
  5162. break;
  5163. case 114: // M114: Report current position
  5164. gcode_M114();
  5165. break;
  5166. case 120: // M120: Enable endstops
  5167. gcode_M120();
  5168. break;
  5169. case 121: // M121: Disable endstops
  5170. gcode_M121();
  5171. break;
  5172. case 119: // M119: Report endstop states
  5173. gcode_M119();
  5174. break;
  5175. #if ENABLED(ULTIPANEL)
  5176. case 145: // M145: Set material heatup parameters
  5177. gcode_M145();
  5178. break;
  5179. #endif
  5180. #if ENABLED(BLINKM)
  5181. case 150: // M150
  5182. gcode_M150();
  5183. break;
  5184. #endif //BLINKM
  5185. case 200: // M200 D<millimeters> set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).
  5186. gcode_M200();
  5187. break;
  5188. case 201: // M201
  5189. gcode_M201();
  5190. break;
  5191. #if 0 // Not used for Sprinter/grbl gen6
  5192. case 202: // M202
  5193. gcode_M202();
  5194. break;
  5195. #endif
  5196. case 203: // M203 max feedrate mm/sec
  5197. gcode_M203();
  5198. break;
  5199. case 204: // M204 acclereration S normal moves T filmanent only moves
  5200. gcode_M204();
  5201. break;
  5202. case 205: //M205 advanced settings: minimum travel speed S=while printing T=travel only, B=minimum segment time X= maximum xy jerk, Z=maximum Z jerk
  5203. gcode_M205();
  5204. break;
  5205. case 206: // M206 additional homing offset
  5206. gcode_M206();
  5207. break;
  5208. #if ENABLED(DELTA)
  5209. case 665: // M665 set delta configurations L<diagonal_rod> R<delta_radius> S<segments_per_sec>
  5210. gcode_M665();
  5211. break;
  5212. #endif
  5213. #if ENABLED(DELTA) || ENABLED(Z_DUAL_ENDSTOPS)
  5214. case 666: // M666 set delta / dual endstop adjustment
  5215. gcode_M666();
  5216. break;
  5217. #endif
  5218. #if ENABLED(FWRETRACT)
  5219. case 207: //M207 - set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop]
  5220. gcode_M207();
  5221. break;
  5222. case 208: // M208 - set retract recover length S[positive mm surplus to the M207 S*] F[feedrate mm/min]
  5223. gcode_M208();
  5224. break;
  5225. case 209: // M209 - S<1=true/0=false> enable automatic retract detect if the slicer did not support G10/11: every normal extrude-only move will be classified as retract depending on the direction.
  5226. gcode_M209();
  5227. break;
  5228. #endif // FWRETRACT
  5229. #if EXTRUDERS > 1
  5230. case 218: // M218 - set hotend offset (in mm), T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  5231. gcode_M218();
  5232. break;
  5233. #endif
  5234. case 220: // M220 S<factor in percent>- set speed factor override percentage
  5235. gcode_M220();
  5236. break;
  5237. case 221: // M221 S<factor in percent>- set extrude factor override percentage
  5238. gcode_M221();
  5239. break;
  5240. case 226: // M226 P<pin number> S<pin state>- Wait until the specified pin reaches the state required
  5241. gcode_M226();
  5242. break;
  5243. #if HAS_SERVOS
  5244. case 280: // M280 - set servo position absolute. P: servo index, S: angle or microseconds
  5245. gcode_M280();
  5246. break;
  5247. #endif // HAS_SERVOS
  5248. #if HAS_BUZZER
  5249. case 300: // M300 - Play beep tone
  5250. gcode_M300();
  5251. break;
  5252. #endif // HAS_BUZZER
  5253. #if ENABLED(PIDTEMP)
  5254. case 301: // M301
  5255. gcode_M301();
  5256. break;
  5257. #endif // PIDTEMP
  5258. #if ENABLED(PIDTEMPBED)
  5259. case 304: // M304
  5260. gcode_M304();
  5261. break;
  5262. #endif // PIDTEMPBED
  5263. #if defined(CHDK) || HAS_PHOTOGRAPH
  5264. case 240: // M240 Triggers a camera by emulating a Canon RC-1 : http://www.doc-diy.net/photo/rc-1_hacked/
  5265. gcode_M240();
  5266. break;
  5267. #endif // CHDK || PHOTOGRAPH_PIN
  5268. #if ENABLED(HAS_LCD_CONTRAST)
  5269. case 250: // M250 Set LCD contrast value: C<value> (value 0..63)
  5270. gcode_M250();
  5271. break;
  5272. #endif // HAS_LCD_CONTRAST
  5273. #if ENABLED(PREVENT_DANGEROUS_EXTRUDE)
  5274. case 302: // allow cold extrudes, or set the minimum extrude temperature
  5275. gcode_M302();
  5276. break;
  5277. #endif // PREVENT_DANGEROUS_EXTRUDE
  5278. case 303: // M303 PID autotune
  5279. gcode_M303();
  5280. break;
  5281. #if ENABLED(SCARA)
  5282. case 360: // M360 SCARA Theta pos1
  5283. if (gcode_M360()) return;
  5284. break;
  5285. case 361: // M361 SCARA Theta pos2
  5286. if (gcode_M361()) return;
  5287. break;
  5288. case 362: // M362 SCARA Psi pos1
  5289. if (gcode_M362()) return;
  5290. break;
  5291. case 363: // M363 SCARA Psi pos2
  5292. if (gcode_M363()) return;
  5293. break;
  5294. case 364: // M364 SCARA Psi pos3 (90 deg to Theta)
  5295. if (gcode_M364()) return;
  5296. break;
  5297. case 365: // M365 Set SCARA scaling for X Y Z
  5298. gcode_M365();
  5299. break;
  5300. #endif // SCARA
  5301. case 400: // M400 finish all moves
  5302. gcode_M400();
  5303. break;
  5304. #if ENABLED(AUTO_BED_LEVELING_FEATURE) && (HAS_SERVO_ENDSTOPS || ENABLED(Z_PROBE_ALLEN_KEY)) && DISABLED(Z_PROBE_SLED)
  5305. case 401:
  5306. gcode_M401();
  5307. break;
  5308. case 402:
  5309. gcode_M402();
  5310. break;
  5311. #endif // AUTO_BED_LEVELING_FEATURE && (HAS_SERVO_ENDSTOPS || Z_PROBE_ALLEN_KEY) && !Z_PROBE_SLED
  5312. #if ENABLED(FILAMENT_SENSOR)
  5313. case 404: //M404 Enter the nominal filament width (3mm, 1.75mm ) N<3.0> or display nominal filament width
  5314. gcode_M404();
  5315. break;
  5316. case 405: //M405 Turn on filament sensor for control
  5317. gcode_M405();
  5318. break;
  5319. case 406: //M406 Turn off filament sensor for control
  5320. gcode_M406();
  5321. break;
  5322. case 407: //M407 Display measured filament diameter
  5323. gcode_M407();
  5324. break;
  5325. #endif // FILAMENT_SENSOR
  5326. case 410: // M410 quickstop - Abort all the planned moves.
  5327. gcode_M410();
  5328. break;
  5329. #if ENABLED(MESH_BED_LEVELING)
  5330. case 420: // M420 Enable/Disable Mesh Bed Leveling
  5331. gcode_M420();
  5332. break;
  5333. case 421: // M421 Set a Mesh Bed Leveling Z coordinate
  5334. gcode_M421();
  5335. break;
  5336. #endif
  5337. case 428: // M428 Apply current_position to home_offset
  5338. gcode_M428();
  5339. break;
  5340. case 500: // M500 Store settings in EEPROM
  5341. gcode_M500();
  5342. break;
  5343. case 501: // M501 Read settings from EEPROM
  5344. gcode_M501();
  5345. break;
  5346. case 502: // M502 Revert to default settings
  5347. gcode_M502();
  5348. break;
  5349. case 503: // M503 print settings currently in memory
  5350. gcode_M503();
  5351. break;
  5352. #if ENABLED(ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  5353. case 540:
  5354. gcode_M540();
  5355. break;
  5356. #endif
  5357. #ifdef CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  5358. case CUSTOM_M_CODE_SET_Z_PROBE_OFFSET:
  5359. gcode_SET_Z_PROBE_OFFSET();
  5360. break;
  5361. #endif // CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  5362. #if ENABLED(FILAMENTCHANGEENABLE)
  5363. case 600: //Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  5364. gcode_M600();
  5365. break;
  5366. #endif // FILAMENTCHANGEENABLE
  5367. #if ENABLED(DUAL_X_CARRIAGE)
  5368. case 605:
  5369. gcode_M605();
  5370. break;
  5371. #endif // DUAL_X_CARRIAGE
  5372. case 907: // M907 Set digital trimpot motor current using axis codes.
  5373. gcode_M907();
  5374. break;
  5375. #if HAS_DIGIPOTSS
  5376. case 908: // M908 Control digital trimpot directly.
  5377. gcode_M908();
  5378. break;
  5379. #endif // HAS_DIGIPOTSS
  5380. #if HAS_MICROSTEPS
  5381. case 350: // M350 Set microstepping mode. Warning: Steps per unit remains unchanged. S code sets stepping mode for all drivers.
  5382. gcode_M350();
  5383. break;
  5384. case 351: // M351 Toggle MS1 MS2 pins directly, S# determines MS1 or MS2, X# sets the pin high/low.
  5385. gcode_M351();
  5386. break;
  5387. #endif // HAS_MICROSTEPS
  5388. case 999: // M999: Restart after being Stopped
  5389. gcode_M999();
  5390. break;
  5391. }
  5392. break;
  5393. case 'T':
  5394. gcode_T(codenum);
  5395. break;
  5396. default: code_is_good = false;
  5397. }
  5398. KEEPALIVE_STATE(NOT_BUSY);
  5399. ExitUnknownCommand:
  5400. // Still unknown command? Throw an error
  5401. if (!code_is_good) unknown_command_error();
  5402. ok_to_send();
  5403. }
  5404. void FlushSerialRequestResend() {
  5405. //char command_queue[cmd_queue_index_r][100]="Resend:";
  5406. MYSERIAL.flush();
  5407. SERIAL_PROTOCOLPGM(MSG_RESEND);
  5408. SERIAL_PROTOCOLLN(gcode_LastN + 1);
  5409. ok_to_send();
  5410. }
  5411. void ok_to_send() {
  5412. refresh_cmd_timeout();
  5413. if (!send_ok[cmd_queue_index_r]) return;
  5414. SERIAL_PROTOCOLPGM(MSG_OK);
  5415. #if ENABLED(ADVANCED_OK)
  5416. char* p = command_queue[cmd_queue_index_r];
  5417. if (*p == 'N') {
  5418. SERIAL_PROTOCOL(' ');
  5419. SERIAL_ECHO(*p++);
  5420. while ((*p >= '0' && *p <= '9') || *p == '-')
  5421. SERIAL_ECHO(*p++);
  5422. }
  5423. SERIAL_PROTOCOLPGM(" P"); SERIAL_PROTOCOL(int(BLOCK_BUFFER_SIZE - movesplanned() - 1));
  5424. SERIAL_PROTOCOLPGM(" B"); SERIAL_PROTOCOL(BUFSIZE - commands_in_queue);
  5425. #endif
  5426. SERIAL_EOL;
  5427. }
  5428. void clamp_to_software_endstops(float target[3]) {
  5429. if (min_software_endstops) {
  5430. NOLESS(target[X_AXIS], min_pos[X_AXIS]);
  5431. NOLESS(target[Y_AXIS], min_pos[Y_AXIS]);
  5432. float negative_z_offset = 0;
  5433. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  5434. if (zprobe_zoffset < 0) negative_z_offset += zprobe_zoffset;
  5435. if (home_offset[Z_AXIS] < 0) {
  5436. #if ENABLED(DEBUG_LEVELING_FEATURE)
  5437. if (marlin_debug_flags & DEBUG_LEVELING) {
  5438. SERIAL_ECHOPAIR("> clamp_to_software_endstops > Add home_offset[Z_AXIS]:", home_offset[Z_AXIS]);
  5439. SERIAL_EOL;
  5440. }
  5441. #endif
  5442. negative_z_offset += home_offset[Z_AXIS];
  5443. }
  5444. #endif
  5445. NOLESS(target[Z_AXIS], min_pos[Z_AXIS] + negative_z_offset);
  5446. }
  5447. if (max_software_endstops) {
  5448. NOMORE(target[X_AXIS], max_pos[X_AXIS]);
  5449. NOMORE(target[Y_AXIS], max_pos[Y_AXIS]);
  5450. NOMORE(target[Z_AXIS], max_pos[Z_AXIS]);
  5451. }
  5452. }
  5453. #if ENABLED(DELTA)
  5454. void recalc_delta_settings(float radius, float diagonal_rod) {
  5455. delta_tower1_x = -SIN_60 * (radius + DELTA_RADIUS_TRIM_TOWER_1); // front left tower
  5456. delta_tower1_y = -COS_60 * (radius + DELTA_RADIUS_TRIM_TOWER_1);
  5457. delta_tower2_x = SIN_60 * (radius + DELTA_RADIUS_TRIM_TOWER_2); // front right tower
  5458. delta_tower2_y = -COS_60 * (radius + DELTA_RADIUS_TRIM_TOWER_2);
  5459. delta_tower3_x = 0.0; // back middle tower
  5460. delta_tower3_y = (radius + DELTA_RADIUS_TRIM_TOWER_3);
  5461. delta_diagonal_rod_2_tower_1 = sq(diagonal_rod + delta_diagonal_rod_trim_tower_1);
  5462. delta_diagonal_rod_2_tower_2 = sq(diagonal_rod + delta_diagonal_rod_trim_tower_2);
  5463. delta_diagonal_rod_2_tower_3 = sq(diagonal_rod + delta_diagonal_rod_trim_tower_3);
  5464. }
  5465. void calculate_delta(float cartesian[3]) {
  5466. delta[TOWER_1] = sqrt(delta_diagonal_rod_2_tower_1
  5467. - sq(delta_tower1_x - cartesian[X_AXIS])
  5468. - sq(delta_tower1_y - cartesian[Y_AXIS])
  5469. ) + cartesian[Z_AXIS];
  5470. delta[TOWER_2] = sqrt(delta_diagonal_rod_2_tower_2
  5471. - sq(delta_tower2_x - cartesian[X_AXIS])
  5472. - sq(delta_tower2_y - cartesian[Y_AXIS])
  5473. ) + cartesian[Z_AXIS];
  5474. delta[TOWER_3] = sqrt(delta_diagonal_rod_2_tower_3
  5475. - sq(delta_tower3_x - cartesian[X_AXIS])
  5476. - sq(delta_tower3_y - cartesian[Y_AXIS])
  5477. ) + cartesian[Z_AXIS];
  5478. /*
  5479. SERIAL_ECHOPGM("cartesian x="); SERIAL_ECHO(cartesian[X_AXIS]);
  5480. SERIAL_ECHOPGM(" y="); SERIAL_ECHO(cartesian[Y_AXIS]);
  5481. SERIAL_ECHOPGM(" z="); SERIAL_ECHOLN(cartesian[Z_AXIS]);
  5482. SERIAL_ECHOPGM("delta a="); SERIAL_ECHO(delta[TOWER_1]);
  5483. SERIAL_ECHOPGM(" b="); SERIAL_ECHO(delta[TOWER_2]);
  5484. SERIAL_ECHOPGM(" c="); SERIAL_ECHOLN(delta[TOWER_3]);
  5485. */
  5486. }
  5487. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  5488. // Adjust print surface height by linear interpolation over the bed_level array.
  5489. void adjust_delta(float cartesian[3]) {
  5490. if (delta_grid_spacing[0] == 0 || delta_grid_spacing[1] == 0) return; // G29 not done!
  5491. int half = (AUTO_BED_LEVELING_GRID_POINTS - 1) / 2;
  5492. float h1 = 0.001 - half, h2 = half - 0.001,
  5493. grid_x = max(h1, min(h2, cartesian[X_AXIS] / delta_grid_spacing[0])),
  5494. grid_y = max(h1, min(h2, cartesian[Y_AXIS] / delta_grid_spacing[1]));
  5495. int floor_x = floor(grid_x), floor_y = floor(grid_y);
  5496. float ratio_x = grid_x - floor_x, ratio_y = grid_y - floor_y,
  5497. z1 = bed_level[floor_x + half][floor_y + half],
  5498. z2 = bed_level[floor_x + half][floor_y + half + 1],
  5499. z3 = bed_level[floor_x + half + 1][floor_y + half],
  5500. z4 = bed_level[floor_x + half + 1][floor_y + half + 1],
  5501. left = (1 - ratio_y) * z1 + ratio_y * z2,
  5502. right = (1 - ratio_y) * z3 + ratio_y * z4,
  5503. offset = (1 - ratio_x) * left + ratio_x * right;
  5504. delta[X_AXIS] += offset;
  5505. delta[Y_AXIS] += offset;
  5506. delta[Z_AXIS] += offset;
  5507. /*
  5508. SERIAL_ECHOPGM("grid_x="); SERIAL_ECHO(grid_x);
  5509. SERIAL_ECHOPGM(" grid_y="); SERIAL_ECHO(grid_y);
  5510. SERIAL_ECHOPGM(" floor_x="); SERIAL_ECHO(floor_x);
  5511. SERIAL_ECHOPGM(" floor_y="); SERIAL_ECHO(floor_y);
  5512. SERIAL_ECHOPGM(" ratio_x="); SERIAL_ECHO(ratio_x);
  5513. SERIAL_ECHOPGM(" ratio_y="); SERIAL_ECHO(ratio_y);
  5514. SERIAL_ECHOPGM(" z1="); SERIAL_ECHO(z1);
  5515. SERIAL_ECHOPGM(" z2="); SERIAL_ECHO(z2);
  5516. SERIAL_ECHOPGM(" z3="); SERIAL_ECHO(z3);
  5517. SERIAL_ECHOPGM(" z4="); SERIAL_ECHO(z4);
  5518. SERIAL_ECHOPGM(" left="); SERIAL_ECHO(left);
  5519. SERIAL_ECHOPGM(" right="); SERIAL_ECHO(right);
  5520. SERIAL_ECHOPGM(" offset="); SERIAL_ECHOLN(offset);
  5521. */
  5522. }
  5523. #endif // AUTO_BED_LEVELING_FEATURE
  5524. #endif // DELTA
  5525. #if ENABLED(MESH_BED_LEVELING)
  5526. // This function is used to split lines on mesh borders so each segment is only part of one mesh area
  5527. void mesh_plan_buffer_line(float x, float y, float z, const float e, float feed_rate, const uint8_t& extruder, uint8_t x_splits = 0xff, uint8_t y_splits = 0xff) {
  5528. if (!mbl.active) {
  5529. plan_buffer_line(x, y, z, e, feed_rate, extruder);
  5530. set_current_to_destination();
  5531. return;
  5532. }
  5533. int pix = mbl.select_x_index(current_position[X_AXIS]);
  5534. int piy = mbl.select_y_index(current_position[Y_AXIS]);
  5535. int ix = mbl.select_x_index(x);
  5536. int iy = mbl.select_y_index(y);
  5537. pix = min(pix, MESH_NUM_X_POINTS - 2);
  5538. piy = min(piy, MESH_NUM_Y_POINTS - 2);
  5539. ix = min(ix, MESH_NUM_X_POINTS - 2);
  5540. iy = min(iy, MESH_NUM_Y_POINTS - 2);
  5541. if (pix == ix && piy == iy) {
  5542. // Start and end on same mesh square
  5543. plan_buffer_line(x, y, z, e, feed_rate, extruder);
  5544. set_current_to_destination();
  5545. return;
  5546. }
  5547. float nx, ny, nz, ne, normalized_dist;
  5548. if (ix > pix && TEST(x_splits, ix)) {
  5549. nx = mbl.get_x(ix);
  5550. normalized_dist = (nx - current_position[X_AXIS]) / (x - current_position[X_AXIS]);
  5551. ny = current_position[Y_AXIS] + (y - current_position[Y_AXIS]) * normalized_dist;
  5552. nz = current_position[Z_AXIS] + (z - current_position[Z_AXIS]) * normalized_dist;
  5553. ne = current_position[E_AXIS] + (e - current_position[E_AXIS]) * normalized_dist;
  5554. CBI(x_splits, ix);
  5555. }
  5556. else if (ix < pix && TEST(x_splits, pix)) {
  5557. nx = mbl.get_x(pix);
  5558. normalized_dist = (nx - current_position[X_AXIS]) / (x - current_position[X_AXIS]);
  5559. ny = current_position[Y_AXIS] + (y - current_position[Y_AXIS]) * normalized_dist;
  5560. nz = current_position[Z_AXIS] + (z - current_position[Z_AXIS]) * normalized_dist;
  5561. ne = current_position[E_AXIS] + (e - current_position[E_AXIS]) * normalized_dist;
  5562. CBI(x_splits, pix);
  5563. }
  5564. else if (iy > piy && TEST(y_splits, iy)) {
  5565. ny = mbl.get_y(iy);
  5566. normalized_dist = (ny - current_position[Y_AXIS]) / (y - current_position[Y_AXIS]);
  5567. nx = current_position[X_AXIS] + (x - current_position[X_AXIS]) * normalized_dist;
  5568. nz = current_position[Z_AXIS] + (z - current_position[Z_AXIS]) * normalized_dist;
  5569. ne = current_position[E_AXIS] + (e - current_position[E_AXIS]) * normalized_dist;
  5570. CBI(y_splits, iy);
  5571. }
  5572. else if (iy < piy && TEST(y_splits, piy)) {
  5573. ny = mbl.get_y(piy);
  5574. normalized_dist = (ny - current_position[Y_AXIS]) / (y - current_position[Y_AXIS]);
  5575. nx = current_position[X_AXIS] + (x - current_position[X_AXIS]) * normalized_dist;
  5576. nz = current_position[Z_AXIS] + (z - current_position[Z_AXIS]) * normalized_dist;
  5577. ne = current_position[E_AXIS] + (e - current_position[E_AXIS]) * normalized_dist;
  5578. CBI(y_splits, piy);
  5579. }
  5580. else {
  5581. // Already split on a border
  5582. plan_buffer_line(x, y, z, e, feed_rate, extruder);
  5583. set_current_to_destination();
  5584. return;
  5585. }
  5586. // Do the split and look for more borders
  5587. destination[X_AXIS] = nx;
  5588. destination[Y_AXIS] = ny;
  5589. destination[Z_AXIS] = nz;
  5590. destination[E_AXIS] = ne;
  5591. mesh_plan_buffer_line(nx, ny, nz, ne, feed_rate, extruder, x_splits, y_splits);
  5592. destination[X_AXIS] = x;
  5593. destination[Y_AXIS] = y;
  5594. destination[Z_AXIS] = z;
  5595. destination[E_AXIS] = e;
  5596. mesh_plan_buffer_line(x, y, z, e, feed_rate, extruder, x_splits, y_splits);
  5597. }
  5598. #endif // MESH_BED_LEVELING
  5599. #if ENABLED(PREVENT_DANGEROUS_EXTRUDE)
  5600. inline void prevent_dangerous_extrude(float& curr_e, float& dest_e) {
  5601. if (marlin_debug_flags & DEBUG_DRYRUN) return;
  5602. float de = dest_e - curr_e;
  5603. if (de) {
  5604. if (degHotend(active_extruder) < extrude_min_temp) {
  5605. curr_e = dest_e; // Behave as if the move really took place, but ignore E part
  5606. SERIAL_ECHO_START;
  5607. SERIAL_ECHOLNPGM(MSG_ERR_COLD_EXTRUDE_STOP);
  5608. }
  5609. #if ENABLED(PREVENT_LENGTHY_EXTRUDE)
  5610. if (labs(de) > EXTRUDE_MAXLENGTH) {
  5611. curr_e = dest_e; // Behave as if the move really took place, but ignore E part
  5612. SERIAL_ECHO_START;
  5613. SERIAL_ECHOLNPGM(MSG_ERR_LONG_EXTRUDE_STOP);
  5614. }
  5615. #endif
  5616. }
  5617. }
  5618. #endif // PREVENT_DANGEROUS_EXTRUDE
  5619. #if ENABLED(DELTA) || ENABLED(SCARA)
  5620. inline bool prepare_move_delta(float target[NUM_AXIS]) {
  5621. float difference[NUM_AXIS];
  5622. for (int8_t i = 0; i < NUM_AXIS; i++) difference[i] = target[i] - current_position[i];
  5623. float cartesian_mm = sqrt(sq(difference[X_AXIS]) + sq(difference[Y_AXIS]) + sq(difference[Z_AXIS]));
  5624. if (cartesian_mm < 0.000001) cartesian_mm = abs(difference[E_AXIS]);
  5625. if (cartesian_mm < 0.000001) return false;
  5626. float seconds = 6000 * cartesian_mm / feedrate / feedrate_multiplier;
  5627. int steps = max(1, int(delta_segments_per_second * seconds));
  5628. // SERIAL_ECHOPGM("mm="); SERIAL_ECHO(cartesian_mm);
  5629. // SERIAL_ECHOPGM(" seconds="); SERIAL_ECHO(seconds);
  5630. // SERIAL_ECHOPGM(" steps="); SERIAL_ECHOLN(steps);
  5631. for (int s = 1; s <= steps; s++) {
  5632. float fraction = float(s) / float(steps);
  5633. for (int8_t i = 0; i < NUM_AXIS; i++)
  5634. target[i] = current_position[i] + difference[i] * fraction;
  5635. calculate_delta(target);
  5636. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  5637. adjust_delta(target);
  5638. #endif
  5639. //SERIAL_ECHOPGM("target[X_AXIS]="); SERIAL_ECHOLN(target[X_AXIS]);
  5640. //SERIAL_ECHOPGM("target[Y_AXIS]="); SERIAL_ECHOLN(target[Y_AXIS]);
  5641. //SERIAL_ECHOPGM("target[Z_AXIS]="); SERIAL_ECHOLN(target[Z_AXIS]);
  5642. //SERIAL_ECHOPGM("delta[X_AXIS]="); SERIAL_ECHOLN(delta[X_AXIS]);
  5643. //SERIAL_ECHOPGM("delta[Y_AXIS]="); SERIAL_ECHOLN(delta[Y_AXIS]);
  5644. //SERIAL_ECHOPGM("delta[Z_AXIS]="); SERIAL_ECHOLN(delta[Z_AXIS]);
  5645. plan_buffer_line(delta[X_AXIS], delta[Y_AXIS], delta[Z_AXIS], target[E_AXIS], feedrate / 60 * feedrate_multiplier / 100.0, active_extruder);
  5646. }
  5647. return true;
  5648. }
  5649. #endif // DELTA || SCARA
  5650. #if ENABLED(SCARA)
  5651. inline bool prepare_move_scara(float target[NUM_AXIS]) { return prepare_move_delta(target); }
  5652. #endif
  5653. #if ENABLED(DUAL_X_CARRIAGE)
  5654. inline bool prepare_move_dual_x_carriage() {
  5655. if (active_extruder_parked) {
  5656. if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && active_extruder == 0) {
  5657. // move duplicate extruder into correct duplication position.
  5658. plan_set_position(inactive_extruder_x_pos, current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  5659. plan_buffer_line(current_position[X_AXIS] + duplicate_extruder_x_offset,
  5660. current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], max_feedrate[X_AXIS], 1);
  5661. sync_plan_position();
  5662. st_synchronize();
  5663. extruder_duplication_enabled = true;
  5664. active_extruder_parked = false;
  5665. }
  5666. else if (dual_x_carriage_mode == DXC_AUTO_PARK_MODE) { // handle unparking of head
  5667. if (current_position[E_AXIS] == destination[E_AXIS]) {
  5668. // This is a travel move (with no extrusion)
  5669. // Skip it, but keep track of the current position
  5670. // (so it can be used as the start of the next non-travel move)
  5671. if (delayed_move_time != 0xFFFFFFFFUL) {
  5672. set_current_to_destination();
  5673. NOLESS(raised_parked_position[Z_AXIS], destination[Z_AXIS]);
  5674. delayed_move_time = millis();
  5675. return false;
  5676. }
  5677. }
  5678. delayed_move_time = 0;
  5679. // unpark extruder: 1) raise, 2) move into starting XY position, 3) lower
  5680. plan_buffer_line(raised_parked_position[X_AXIS], raised_parked_position[Y_AXIS], raised_parked_position[Z_AXIS], current_position[E_AXIS], max_feedrate[Z_AXIS], active_extruder);
  5681. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], raised_parked_position[Z_AXIS], current_position[E_AXIS], min(max_feedrate[X_AXIS], max_feedrate[Y_AXIS]), active_extruder);
  5682. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], max_feedrate[Z_AXIS], active_extruder);
  5683. active_extruder_parked = false;
  5684. }
  5685. }
  5686. return true;
  5687. }
  5688. #endif // DUAL_X_CARRIAGE
  5689. #if DISABLED(DELTA) && DISABLED(SCARA)
  5690. inline bool prepare_move_cartesian() {
  5691. // Do not use feedrate_multiplier for E or Z only moves
  5692. if (current_position[X_AXIS] == destination[X_AXIS] && current_position[Y_AXIS] == destination[Y_AXIS]) {
  5693. line_to_destination();
  5694. }
  5695. else {
  5696. #if ENABLED(MESH_BED_LEVELING)
  5697. mesh_plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], (feedrate / 60) * (feedrate_multiplier / 100.0), active_extruder);
  5698. return false;
  5699. #else
  5700. line_to_destination(feedrate * feedrate_multiplier / 100.0);
  5701. #endif
  5702. }
  5703. return true;
  5704. }
  5705. #endif // !DELTA && !SCARA
  5706. /**
  5707. * Prepare a single move and get ready for the next one
  5708. *
  5709. * (This may call plan_buffer_line several times to put
  5710. * smaller moves into the planner for DELTA or SCARA.)
  5711. */
  5712. void prepare_move() {
  5713. clamp_to_software_endstops(destination);
  5714. refresh_cmd_timeout();
  5715. #if ENABLED(PREVENT_DANGEROUS_EXTRUDE)
  5716. prevent_dangerous_extrude(current_position[E_AXIS], destination[E_AXIS]);
  5717. #endif
  5718. #if ENABLED(SCARA)
  5719. if (!prepare_move_scara(destination)) return;
  5720. #elif ENABLED(DELTA)
  5721. if (!prepare_move_delta(destination)) return;
  5722. #endif
  5723. #if ENABLED(DUAL_X_CARRIAGE)
  5724. if (!prepare_move_dual_x_carriage()) return;
  5725. #endif
  5726. #if DISABLED(DELTA) && DISABLED(SCARA)
  5727. if (!prepare_move_cartesian()) return;
  5728. #endif
  5729. set_current_to_destination();
  5730. }
  5731. /**
  5732. * Plan an arc in 2 dimensions
  5733. *
  5734. * The arc is approximated by generating many small linear segments.
  5735. * The length of each segment is configured in MM_PER_ARC_SEGMENT (Default 1mm)
  5736. * Arcs should only be made relatively large (over 5mm), as larger arcs with
  5737. * larger segments will tend to be more efficient. Your slicer should have
  5738. * options for G2/G3 arc generation. In future these options may be GCode tunable.
  5739. */
  5740. void plan_arc(
  5741. float target[NUM_AXIS], // Destination position
  5742. float* offset, // Center of rotation relative to current_position
  5743. uint8_t clockwise // Clockwise?
  5744. ) {
  5745. float radius = hypot(offset[X_AXIS], offset[Y_AXIS]),
  5746. center_axis0 = current_position[X_AXIS] + offset[X_AXIS],
  5747. center_axis1 = current_position[Y_AXIS] + offset[Y_AXIS],
  5748. linear_travel = target[Z_AXIS] - current_position[Z_AXIS],
  5749. extruder_travel = target[E_AXIS] - current_position[E_AXIS],
  5750. r_axis0 = -offset[X_AXIS], // Radius vector from center to current location
  5751. r_axis1 = -offset[Y_AXIS],
  5752. rt_axis0 = target[X_AXIS] - center_axis0,
  5753. rt_axis1 = target[Y_AXIS] - center_axis1;
  5754. // CCW angle of rotation between position and target from the circle center. Only one atan2() trig computation required.
  5755. float angular_travel = atan2(r_axis0 * rt_axis1 - r_axis1 * rt_axis0, r_axis0 * rt_axis0 + r_axis1 * rt_axis1);
  5756. if (angular_travel < 0) angular_travel += RADIANS(360);
  5757. if (clockwise) angular_travel -= RADIANS(360);
  5758. // Make a circle if the angular rotation is 0
  5759. if (current_position[X_AXIS] == target[X_AXIS] && current_position[Y_AXIS] == target[Y_AXIS] && angular_travel == 0)
  5760. angular_travel += RADIANS(360);
  5761. float mm_of_travel = hypot(angular_travel * radius, fabs(linear_travel));
  5762. if (mm_of_travel < 0.001) return;
  5763. uint16_t segments = floor(mm_of_travel / (MM_PER_ARC_SEGMENT));
  5764. if (segments == 0) segments = 1;
  5765. float theta_per_segment = angular_travel / segments;
  5766. float linear_per_segment = linear_travel / segments;
  5767. float extruder_per_segment = extruder_travel / segments;
  5768. /* Vector rotation by transformation matrix: r is the original vector, r_T is the rotated vector,
  5769. and phi is the angle of rotation. Based on the solution approach by Jens Geisler.
  5770. r_T = [cos(phi) -sin(phi);
  5771. sin(phi) cos(phi] * r ;
  5772. For arc generation, the center of the circle is the axis of rotation and the radius vector is
  5773. defined from the circle center to the initial position. Each line segment is formed by successive
  5774. vector rotations. This requires only two cos() and sin() computations to form the rotation
  5775. matrix for the duration of the entire arc. Error may accumulate from numerical round-off, since
  5776. all double numbers are single precision on the Arduino. (True double precision will not have
  5777. round off issues for CNC applications.) Single precision error can accumulate to be greater than
  5778. tool precision in some cases. Therefore, arc path correction is implemented.
  5779. Small angle approximation may be used to reduce computation overhead further. This approximation
  5780. holds for everything, but very small circles and large MM_PER_ARC_SEGMENT values. In other words,
  5781. theta_per_segment would need to be greater than 0.1 rad and N_ARC_CORRECTION would need to be large
  5782. to cause an appreciable drift error. N_ARC_CORRECTION~=25 is more than small enough to correct for
  5783. numerical drift error. N_ARC_CORRECTION may be on the order a hundred(s) before error becomes an
  5784. issue for CNC machines with the single precision Arduino calculations.
  5785. This approximation also allows plan_arc to immediately insert a line segment into the planner
  5786. without the initial overhead of computing cos() or sin(). By the time the arc needs to be applied
  5787. a correction, the planner should have caught up to the lag caused by the initial plan_arc overhead.
  5788. This is important when there are successive arc motions.
  5789. */
  5790. // Vector rotation matrix values
  5791. float cos_T = 1 - 0.5 * theta_per_segment * theta_per_segment; // Small angle approximation
  5792. float sin_T = theta_per_segment;
  5793. float arc_target[NUM_AXIS];
  5794. float sin_Ti;
  5795. float cos_Ti;
  5796. float r_axisi;
  5797. uint16_t i;
  5798. int8_t count = 0;
  5799. // Initialize the linear axis
  5800. arc_target[Z_AXIS] = current_position[Z_AXIS];
  5801. // Initialize the extruder axis
  5802. arc_target[E_AXIS] = current_position[E_AXIS];
  5803. float feed_rate = feedrate * feedrate_multiplier / 60 / 100.0;
  5804. for (i = 1; i < segments; i++) { // Increment (segments-1)
  5805. if (count < N_ARC_CORRECTION) {
  5806. // Apply vector rotation matrix to previous r_axis0 / 1
  5807. r_axisi = r_axis0 * sin_T + r_axis1 * cos_T;
  5808. r_axis0 = r_axis0 * cos_T - r_axis1 * sin_T;
  5809. r_axis1 = r_axisi;
  5810. count++;
  5811. }
  5812. else {
  5813. // Arc correction to radius vector. Computed only every N_ARC_CORRECTION increments.
  5814. // Compute exact location by applying transformation matrix from initial radius vector(=-offset).
  5815. cos_Ti = cos(i * theta_per_segment);
  5816. sin_Ti = sin(i * theta_per_segment);
  5817. r_axis0 = -offset[X_AXIS] * cos_Ti + offset[Y_AXIS] * sin_Ti;
  5818. r_axis1 = -offset[X_AXIS] * sin_Ti - offset[Y_AXIS] * cos_Ti;
  5819. count = 0;
  5820. }
  5821. // Update arc_target location
  5822. arc_target[X_AXIS] = center_axis0 + r_axis0;
  5823. arc_target[Y_AXIS] = center_axis1 + r_axis1;
  5824. arc_target[Z_AXIS] += linear_per_segment;
  5825. arc_target[E_AXIS] += extruder_per_segment;
  5826. clamp_to_software_endstops(arc_target);
  5827. #if ENABLED(DELTA) || ENABLED(SCARA)
  5828. calculate_delta(arc_target);
  5829. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  5830. adjust_delta(arc_target);
  5831. #endif
  5832. plan_buffer_line(delta[X_AXIS], delta[Y_AXIS], delta[Z_AXIS], arc_target[E_AXIS], feed_rate, active_extruder);
  5833. #else
  5834. plan_buffer_line(arc_target[X_AXIS], arc_target[Y_AXIS], arc_target[Z_AXIS], arc_target[E_AXIS], feed_rate, active_extruder);
  5835. #endif
  5836. }
  5837. // Ensure last segment arrives at target location.
  5838. #if ENABLED(DELTA) || ENABLED(SCARA)
  5839. calculate_delta(target);
  5840. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  5841. adjust_delta(target);
  5842. #endif
  5843. plan_buffer_line(delta[X_AXIS], delta[Y_AXIS], delta[Z_AXIS], target[E_AXIS], feed_rate, active_extruder);
  5844. #else
  5845. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], feed_rate, active_extruder);
  5846. #endif
  5847. // As far as the parser is concerned, the position is now == target. In reality the
  5848. // motion control system might still be processing the action and the real tool position
  5849. // in any intermediate location.
  5850. set_current_to_destination();
  5851. }
  5852. #if HAS_CONTROLLERFAN
  5853. void controllerFan() {
  5854. static millis_t lastMotor = 0; // Last time a motor was turned on
  5855. static millis_t lastMotorCheck = 0; // Last time the state was checked
  5856. millis_t ms = millis();
  5857. if (ms >= lastMotorCheck + 2500) { // Not a time critical function, so we only check every 2500ms
  5858. lastMotorCheck = ms;
  5859. if (X_ENABLE_READ == X_ENABLE_ON || Y_ENABLE_READ == Y_ENABLE_ON || Z_ENABLE_READ == Z_ENABLE_ON || soft_pwm_bed > 0
  5860. || E0_ENABLE_READ == E_ENABLE_ON // If any of the drivers are enabled...
  5861. #if EXTRUDERS > 1
  5862. || E1_ENABLE_READ == E_ENABLE_ON
  5863. #if HAS_X2_ENABLE
  5864. || X2_ENABLE_READ == X_ENABLE_ON
  5865. #endif
  5866. #if EXTRUDERS > 2
  5867. || E2_ENABLE_READ == E_ENABLE_ON
  5868. #if EXTRUDERS > 3
  5869. || E3_ENABLE_READ == E_ENABLE_ON
  5870. #endif
  5871. #endif
  5872. #endif
  5873. ) {
  5874. lastMotor = ms; //... set time to NOW so the fan will turn on
  5875. }
  5876. uint8_t speed = (lastMotor == 0 || ms >= lastMotor + ((CONTROLLERFAN_SECS) * 1000UL)) ? 0 : CONTROLLERFAN_SPEED;
  5877. // allows digital or PWM fan output to be used (see M42 handling)
  5878. digitalWrite(CONTROLLERFAN_PIN, speed);
  5879. analogWrite(CONTROLLERFAN_PIN, speed);
  5880. }
  5881. }
  5882. #endif // HAS_CONTROLLERFAN
  5883. #if ENABLED(SCARA)
  5884. void calculate_SCARA_forward_Transform(float f_scara[3]) {
  5885. // Perform forward kinematics, and place results in delta[3]
  5886. // The maths and first version has been done by QHARLEY . Integrated into masterbranch 06/2014 and slightly restructured by Joachim Cerny in June 2014
  5887. float x_sin, x_cos, y_sin, y_cos;
  5888. //SERIAL_ECHOPGM("f_delta x="); SERIAL_ECHO(f_scara[X_AXIS]);
  5889. //SERIAL_ECHOPGM(" y="); SERIAL_ECHO(f_scara[Y_AXIS]);
  5890. x_sin = sin(f_scara[X_AXIS] / SCARA_RAD2DEG) * Linkage_1;
  5891. x_cos = cos(f_scara[X_AXIS] / SCARA_RAD2DEG) * Linkage_1;
  5892. y_sin = sin(f_scara[Y_AXIS] / SCARA_RAD2DEG) * Linkage_2;
  5893. y_cos = cos(f_scara[Y_AXIS] / SCARA_RAD2DEG) * Linkage_2;
  5894. //SERIAL_ECHOPGM(" x_sin="); SERIAL_ECHO(x_sin);
  5895. //SERIAL_ECHOPGM(" x_cos="); SERIAL_ECHO(x_cos);
  5896. //SERIAL_ECHOPGM(" y_sin="); SERIAL_ECHO(y_sin);
  5897. //SERIAL_ECHOPGM(" y_cos="); SERIAL_ECHOLN(y_cos);
  5898. delta[X_AXIS] = x_cos + y_cos + SCARA_offset_x; //theta
  5899. delta[Y_AXIS] = x_sin + y_sin + SCARA_offset_y; //theta+phi
  5900. //SERIAL_ECHOPGM(" delta[X_AXIS]="); SERIAL_ECHO(delta[X_AXIS]);
  5901. //SERIAL_ECHOPGM(" delta[Y_AXIS]="); SERIAL_ECHOLN(delta[Y_AXIS]);
  5902. }
  5903. void calculate_delta(float cartesian[3]) {
  5904. //reverse kinematics.
  5905. // Perform reversed kinematics, and place results in delta[3]
  5906. // The maths and first version has been done by QHARLEY . Integrated into masterbranch 06/2014 and slightly restructured by Joachim Cerny in June 2014
  5907. float SCARA_pos[2];
  5908. static float SCARA_C2, SCARA_S2, SCARA_K1, SCARA_K2, SCARA_theta, SCARA_psi;
  5909. SCARA_pos[X_AXIS] = cartesian[X_AXIS] * axis_scaling[X_AXIS] - SCARA_offset_x; //Translate SCARA to standard X Y
  5910. SCARA_pos[Y_AXIS] = cartesian[Y_AXIS] * axis_scaling[Y_AXIS] - SCARA_offset_y; // With scaling factor.
  5911. #if (Linkage_1 == Linkage_2)
  5912. SCARA_C2 = ((sq(SCARA_pos[X_AXIS]) + sq(SCARA_pos[Y_AXIS])) / (2 * (float)L1_2)) - 1;
  5913. #else
  5914. SCARA_C2 = (sq(SCARA_pos[X_AXIS]) + sq(SCARA_pos[Y_AXIS]) - (float)L1_2 - (float)L2_2) / 45000;
  5915. #endif
  5916. SCARA_S2 = sqrt(1 - sq(SCARA_C2));
  5917. SCARA_K1 = Linkage_1 + Linkage_2 * SCARA_C2;
  5918. SCARA_K2 = Linkage_2 * SCARA_S2;
  5919. SCARA_theta = (atan2(SCARA_pos[X_AXIS], SCARA_pos[Y_AXIS]) - atan2(SCARA_K1, SCARA_K2)) * -1;
  5920. SCARA_psi = atan2(SCARA_S2, SCARA_C2);
  5921. delta[X_AXIS] = SCARA_theta * SCARA_RAD2DEG; // Multiply by 180/Pi - theta is support arm angle
  5922. delta[Y_AXIS] = (SCARA_theta + SCARA_psi) * SCARA_RAD2DEG; // - equal to sub arm angle (inverted motor)
  5923. delta[Z_AXIS] = cartesian[Z_AXIS];
  5924. /*
  5925. SERIAL_ECHOPGM("cartesian x="); SERIAL_ECHO(cartesian[X_AXIS]);
  5926. SERIAL_ECHOPGM(" y="); SERIAL_ECHO(cartesian[Y_AXIS]);
  5927. SERIAL_ECHOPGM(" z="); SERIAL_ECHOLN(cartesian[Z_AXIS]);
  5928. SERIAL_ECHOPGM("scara x="); SERIAL_ECHO(SCARA_pos[X_AXIS]);
  5929. SERIAL_ECHOPGM(" y="); SERIAL_ECHOLN(SCARA_pos[Y_AXIS]);
  5930. SERIAL_ECHOPGM("delta x="); SERIAL_ECHO(delta[X_AXIS]);
  5931. SERIAL_ECHOPGM(" y="); SERIAL_ECHO(delta[Y_AXIS]);
  5932. SERIAL_ECHOPGM(" z="); SERIAL_ECHOLN(delta[Z_AXIS]);
  5933. SERIAL_ECHOPGM("C2="); SERIAL_ECHO(SCARA_C2);
  5934. SERIAL_ECHOPGM(" S2="); SERIAL_ECHO(SCARA_S2);
  5935. SERIAL_ECHOPGM(" Theta="); SERIAL_ECHO(SCARA_theta);
  5936. SERIAL_ECHOPGM(" Psi="); SERIAL_ECHOLN(SCARA_psi);
  5937. SERIAL_EOL;
  5938. */
  5939. }
  5940. #endif // SCARA
  5941. #if ENABLED(TEMP_STAT_LEDS)
  5942. static bool red_led = false;
  5943. static millis_t next_status_led_update_ms = 0;
  5944. void handle_status_leds(void) {
  5945. float max_temp = 0.0;
  5946. if (millis() > next_status_led_update_ms) {
  5947. next_status_led_update_ms += 500; // Update every 0.5s
  5948. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder)
  5949. max_temp = max(max(max_temp, degHotend(cur_extruder)), degTargetHotend(cur_extruder));
  5950. #if HAS_TEMP_BED
  5951. max_temp = max(max(max_temp, degTargetBed()), degBed());
  5952. #endif
  5953. bool new_led = (max_temp > 55.0) ? true : (max_temp < 54.0) ? false : red_led;
  5954. if (new_led != red_led) {
  5955. red_led = new_led;
  5956. digitalWrite(STAT_LED_RED, new_led ? HIGH : LOW);
  5957. digitalWrite(STAT_LED_BLUE, new_led ? LOW : HIGH);
  5958. }
  5959. }
  5960. }
  5961. #endif
  5962. void enable_all_steppers() {
  5963. enable_x();
  5964. enable_y();
  5965. enable_z();
  5966. enable_e0();
  5967. enable_e1();
  5968. enable_e2();
  5969. enable_e3();
  5970. }
  5971. void disable_all_steppers() {
  5972. disable_x();
  5973. disable_y();
  5974. disable_z();
  5975. disable_e0();
  5976. disable_e1();
  5977. disable_e2();
  5978. disable_e3();
  5979. }
  5980. /**
  5981. * Standard idle routine keeps the machine alive
  5982. */
  5983. void idle(
  5984. #if ENABLED(FILAMENTCHANGEENABLE)
  5985. bool no_stepper_sleep/*=false*/
  5986. #endif
  5987. ) {
  5988. manage_heater();
  5989. manage_inactivity(
  5990. #if ENABLED(FILAMENTCHANGEENABLE)
  5991. no_stepper_sleep
  5992. #endif
  5993. );
  5994. host_keepalive();
  5995. lcd_update();
  5996. }
  5997. /**
  5998. * Manage several activities:
  5999. * - Check for Filament Runout
  6000. * - Keep the command buffer full
  6001. * - Check for maximum inactive time between commands
  6002. * - Check for maximum inactive time between stepper commands
  6003. * - Check if pin CHDK needs to go LOW
  6004. * - Check for KILL button held down
  6005. * - Check for HOME button held down
  6006. * - Check if cooling fan needs to be switched on
  6007. * - Check if an idle but hot extruder needs filament extruded (EXTRUDER_RUNOUT_PREVENT)
  6008. */
  6009. void manage_inactivity(bool ignore_stepper_queue/*=false*/) {
  6010. #if HAS_FILRUNOUT
  6011. if (IS_SD_PRINTING && !(READ(FILRUNOUT_PIN) ^ FIL_RUNOUT_INVERTING))
  6012. filrunout();
  6013. #endif
  6014. if (commands_in_queue < BUFSIZE) get_command();
  6015. millis_t ms = millis();
  6016. if (max_inactive_time && ms > previous_cmd_ms + max_inactive_time) kill(PSTR(MSG_KILLED));
  6017. if (stepper_inactive_time && ms > previous_cmd_ms + stepper_inactive_time
  6018. && !ignore_stepper_queue && !blocks_queued()) {
  6019. #if ENABLED(DISABLE_INACTIVE_X)
  6020. disable_x();
  6021. #endif
  6022. #if ENABLED(DISABLE_INACTIVE_Y)
  6023. disable_y();
  6024. #endif
  6025. #if ENABLED(DISABLE_INACTIVE_Z)
  6026. disable_z();
  6027. #endif
  6028. #if ENABLED(DISABLE_INACTIVE_E)
  6029. disable_e0();
  6030. disable_e1();
  6031. disable_e2();
  6032. disable_e3();
  6033. #endif
  6034. }
  6035. #ifdef CHDK // Check if pin should be set to LOW after M240 set it to HIGH
  6036. if (chdkActive && ms > chdkHigh + CHDK_DELAY) {
  6037. chdkActive = false;
  6038. WRITE(CHDK, LOW);
  6039. }
  6040. #endif
  6041. #if HAS_KILL
  6042. // Check if the kill button was pressed and wait just in case it was an accidental
  6043. // key kill key press
  6044. // -------------------------------------------------------------------------------
  6045. static int killCount = 0; // make the inactivity button a bit less responsive
  6046. const int KILL_DELAY = 750;
  6047. if (!READ(KILL_PIN))
  6048. killCount++;
  6049. else if (killCount > 0)
  6050. killCount--;
  6051. // Exceeded threshold and we can confirm that it was not accidental
  6052. // KILL the machine
  6053. // ----------------------------------------------------------------
  6054. if (killCount >= KILL_DELAY) kill(PSTR(MSG_KILLED));
  6055. #endif
  6056. #if HAS_HOME
  6057. // Check to see if we have to home, use poor man's debouncer
  6058. // ---------------------------------------------------------
  6059. static int homeDebounceCount = 0; // poor man's debouncing count
  6060. const int HOME_DEBOUNCE_DELAY = 2500;
  6061. if (!READ(HOME_PIN)) {
  6062. if (!homeDebounceCount) {
  6063. enqueue_and_echo_commands_P(PSTR("G28"));
  6064. LCD_MESSAGEPGM(MSG_AUTO_HOME);
  6065. }
  6066. if (homeDebounceCount < HOME_DEBOUNCE_DELAY)
  6067. homeDebounceCount++;
  6068. else
  6069. homeDebounceCount = 0;
  6070. }
  6071. #endif
  6072. #if HAS_CONTROLLERFAN
  6073. controllerFan(); // Check if fan should be turned on to cool stepper drivers down
  6074. #endif
  6075. #if ENABLED(EXTRUDER_RUNOUT_PREVENT)
  6076. if (ms > previous_cmd_ms + (EXTRUDER_RUNOUT_SECONDS) * 1000)
  6077. if (degHotend(active_extruder) > EXTRUDER_RUNOUT_MINTEMP) {
  6078. bool oldstatus;
  6079. switch (active_extruder) {
  6080. case 0:
  6081. oldstatus = E0_ENABLE_READ;
  6082. enable_e0();
  6083. break;
  6084. #if EXTRUDERS > 1
  6085. case 1:
  6086. oldstatus = E1_ENABLE_READ;
  6087. enable_e1();
  6088. break;
  6089. #if EXTRUDERS > 2
  6090. case 2:
  6091. oldstatus = E2_ENABLE_READ;
  6092. enable_e2();
  6093. break;
  6094. #if EXTRUDERS > 3
  6095. case 3:
  6096. oldstatus = E3_ENABLE_READ;
  6097. enable_e3();
  6098. break;
  6099. #endif
  6100. #endif
  6101. #endif
  6102. }
  6103. float oldepos = current_position[E_AXIS], oldedes = destination[E_AXIS];
  6104. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS],
  6105. destination[E_AXIS] + (EXTRUDER_RUNOUT_EXTRUDE) * (EXTRUDER_RUNOUT_ESTEPS) / axis_steps_per_unit[E_AXIS],
  6106. (EXTRUDER_RUNOUT_SPEED) / 60. * (EXTRUDER_RUNOUT_ESTEPS) / axis_steps_per_unit[E_AXIS], active_extruder);
  6107. current_position[E_AXIS] = oldepos;
  6108. destination[E_AXIS] = oldedes;
  6109. plan_set_e_position(oldepos);
  6110. previous_cmd_ms = ms; // refresh_cmd_timeout()
  6111. st_synchronize();
  6112. switch (active_extruder) {
  6113. case 0:
  6114. E0_ENABLE_WRITE(oldstatus);
  6115. break;
  6116. #if EXTRUDERS > 1
  6117. case 1:
  6118. E1_ENABLE_WRITE(oldstatus);
  6119. break;
  6120. #if EXTRUDERS > 2
  6121. case 2:
  6122. E2_ENABLE_WRITE(oldstatus);
  6123. break;
  6124. #if EXTRUDERS > 3
  6125. case 3:
  6126. E3_ENABLE_WRITE(oldstatus);
  6127. break;
  6128. #endif
  6129. #endif
  6130. #endif
  6131. }
  6132. }
  6133. #endif
  6134. #if ENABLED(DUAL_X_CARRIAGE)
  6135. // handle delayed move timeout
  6136. if (delayed_move_time && ms > delayed_move_time + 1000 && IsRunning()) {
  6137. // travel moves have been received so enact them
  6138. delayed_move_time = 0xFFFFFFFFUL; // force moves to be done
  6139. set_destination_to_current();
  6140. prepare_move();
  6141. }
  6142. #endif
  6143. #if ENABLED(TEMP_STAT_LEDS)
  6144. handle_status_leds();
  6145. #endif
  6146. check_axes_activity();
  6147. }
  6148. void kill(const char* lcd_msg) {
  6149. #if ENABLED(ULTRA_LCD)
  6150. lcd_setalertstatuspgm(lcd_msg);
  6151. #else
  6152. UNUSED(lcd_msg);
  6153. #endif
  6154. cli(); // Stop interrupts
  6155. disable_all_heaters();
  6156. disable_all_steppers();
  6157. #if HAS_POWER_SWITCH
  6158. pinMode(PS_ON_PIN, INPUT);
  6159. #endif
  6160. SERIAL_ERROR_START;
  6161. SERIAL_ERRORLNPGM(MSG_ERR_KILLED);
  6162. // FMC small patch to update the LCD before ending
  6163. sei(); // enable interrupts
  6164. for (int i = 5; i--; lcd_update()) delay(200); // Wait a short time
  6165. cli(); // disable interrupts
  6166. suicide();
  6167. while (1) {
  6168. #if ENABLED(USE_WATCHDOG)
  6169. watchdog_reset();
  6170. #endif
  6171. } // Wait for reset
  6172. }
  6173. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  6174. void filrunout() {
  6175. if (!filrunoutEnqueued) {
  6176. filrunoutEnqueued = true;
  6177. enqueue_and_echo_commands_P(PSTR(FILAMENT_RUNOUT_SCRIPT));
  6178. st_synchronize();
  6179. }
  6180. }
  6181. #endif // FILAMENT_RUNOUT_SENSOR
  6182. #if ENABLED(FAST_PWM_FAN)
  6183. void setPwmFrequency(uint8_t pin, int val) {
  6184. val &= 0x07;
  6185. switch (digitalPinToTimer(pin)) {
  6186. #if defined(TCCR0A)
  6187. case TIMER0A:
  6188. case TIMER0B:
  6189. // TCCR0B &= ~(_BV(CS00) | _BV(CS01) | _BV(CS02));
  6190. // TCCR0B |= val;
  6191. break;
  6192. #endif
  6193. #if defined(TCCR1A)
  6194. case TIMER1A:
  6195. case TIMER1B:
  6196. // TCCR1B &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  6197. // TCCR1B |= val;
  6198. break;
  6199. #endif
  6200. #if defined(TCCR2)
  6201. case TIMER2:
  6202. case TIMER2:
  6203. TCCR2 &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  6204. TCCR2 |= val;
  6205. break;
  6206. #endif
  6207. #if defined(TCCR2A)
  6208. case TIMER2A:
  6209. case TIMER2B:
  6210. TCCR2B &= ~(_BV(CS20) | _BV(CS21) | _BV(CS22));
  6211. TCCR2B |= val;
  6212. break;
  6213. #endif
  6214. #if defined(TCCR3A)
  6215. case TIMER3A:
  6216. case TIMER3B:
  6217. case TIMER3C:
  6218. TCCR3B &= ~(_BV(CS30) | _BV(CS31) | _BV(CS32));
  6219. TCCR3B |= val;
  6220. break;
  6221. #endif
  6222. #if defined(TCCR4A)
  6223. case TIMER4A:
  6224. case TIMER4B:
  6225. case TIMER4C:
  6226. TCCR4B &= ~(_BV(CS40) | _BV(CS41) | _BV(CS42));
  6227. TCCR4B |= val;
  6228. break;
  6229. #endif
  6230. #if defined(TCCR5A)
  6231. case TIMER5A:
  6232. case TIMER5B:
  6233. case TIMER5C:
  6234. TCCR5B &= ~(_BV(CS50) | _BV(CS51) | _BV(CS52));
  6235. TCCR5B |= val;
  6236. break;
  6237. #endif
  6238. }
  6239. }
  6240. #endif // FAST_PWM_FAN
  6241. void Stop() {
  6242. disable_all_heaters();
  6243. if (IsRunning()) {
  6244. Running = false;
  6245. Stopped_gcode_LastN = gcode_LastN; // Save last g_code for restart
  6246. SERIAL_ERROR_START;
  6247. SERIAL_ERRORLNPGM(MSG_ERR_STOPPED);
  6248. LCD_MESSAGEPGM(MSG_STOPPED);
  6249. }
  6250. }
  6251. /**
  6252. * Set target_extruder from the T parameter or the active_extruder
  6253. *
  6254. * Returns TRUE if the target is invalid
  6255. */
  6256. bool setTargetedHotend(int code) {
  6257. target_extruder = active_extruder;
  6258. if (code_seen('T')) {
  6259. target_extruder = code_value_short();
  6260. if (target_extruder >= EXTRUDERS) {
  6261. SERIAL_ECHO_START;
  6262. SERIAL_CHAR('M');
  6263. SERIAL_ECHO(code);
  6264. SERIAL_ECHOPGM(" " MSG_INVALID_EXTRUDER " ");
  6265. SERIAL_ECHOLN(target_extruder);
  6266. return true;
  6267. }
  6268. }
  6269. return false;
  6270. }
  6271. float calculate_volumetric_multiplier(float diameter) {
  6272. if (!volumetric_enabled || diameter == 0) return 1.0;
  6273. float d2 = diameter * 0.5;
  6274. return 1.0 / (M_PI * d2 * d2);
  6275. }
  6276. void calculate_volumetric_multipliers() {
  6277. for (int i = 0; i < EXTRUDERS; i++)
  6278. volumetric_multiplier[i] = calculate_volumetric_multiplier(filament_size[i]);
  6279. }