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 227KB

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