Marlin_main.cpp 386 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622
  1. /* -*- c++ -*- */
  2. /**
  3. * @file
  4. */
  5. /**
  6. * @mainpage Reprap 3D printer firmware based on Sprinter and grbl.
  7. *
  8. * @section intro_sec Introduction
  9. *
  10. * This firmware is a mashup between Sprinter and grbl.
  11. * https://github.com/kliment/Sprinter
  12. * https://github.com/simen/grbl/tree
  13. *
  14. * It has preliminary support for Matthew Roberts advance algorithm
  15. * http://reprap.org/pipermail/reprap-dev/2011-May/003323.html
  16. *
  17. * Prusa Research s.r.o. https://www.prusa3d.cz
  18. *
  19. * @section copyright_sec Copyright
  20. *
  21. * Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
  22. *
  23. * This program is free software: you can redistribute it and/or modify
  24. * it under the terms of the GNU General Public License as published by
  25. * the Free Software Foundation, either version 3 of the License, or
  26. * (at your option) any later version.
  27. *
  28. * This program is distributed in the hope that it will be useful,
  29. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  30. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  31. * GNU General Public License for more details.
  32. *
  33. * You should have received a copy of the GNU General Public License
  34. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  35. *
  36. * @section notes_sec Notes
  37. *
  38. * * Do not create static objects in global functions.
  39. * Otherwise constructor guard against concurrent calls is generated costing
  40. * about 8B RAM and 14B flash.
  41. *
  42. *
  43. */
  44. //-//
  45. #include "Configuration.h"
  46. #include "Marlin.h"
  47. #include "config.h"
  48. #include "macros.h"
  49. #ifdef ENABLE_AUTO_BED_LEVELING
  50. #include "vector_3.h"
  51. #ifdef AUTO_BED_LEVELING_GRID
  52. #include "qr_solve.h"
  53. #endif
  54. #endif // ENABLE_AUTO_BED_LEVELING
  55. #ifdef MESH_BED_LEVELING
  56. #include "mesh_bed_leveling.h"
  57. #include "mesh_bed_calibration.h"
  58. #endif
  59. #include "printers.h"
  60. #include "menu.h"
  61. #include "ultralcd.h"
  62. #include "conv2str.h"
  63. #include "backlight.h"
  64. #include "planner.h"
  65. #include "stepper.h"
  66. #include "temperature.h"
  67. #include "fancheck.h"
  68. #include "motion_control.h"
  69. #include "cardreader.h"
  70. #include "ConfigurationStore.h"
  71. #include "language.h"
  72. #include "pins_arduino.h"
  73. #include "math.h"
  74. #include "util.h"
  75. #include "Timer.h"
  76. #include "Prusa_farm.h"
  77. #include <avr/wdt.h>
  78. #include <avr/pgmspace.h>
  79. #include "Tcodes.h"
  80. #include "Dcodes.h"
  81. #include "SpoolJoin.h"
  82. #ifndef LA_NOCOMPAT
  83. #include "la10compat.h"
  84. #endif
  85. #include "spi.h"
  86. #include "Filament_sensor.h"
  87. #ifdef TMC2130
  88. #include "tmc2130.h"
  89. #endif //TMC2130
  90. #ifdef XFLASH
  91. #include "xflash.h"
  92. #include "optiboot_xflash.h"
  93. #endif //XFLASH
  94. #include "xflash_dump.h"
  95. #ifdef BLINKM
  96. #include "BlinkM.h"
  97. #include "Wire.h"
  98. #endif
  99. #ifdef ULTRALCD
  100. #include "ultralcd.h"
  101. #endif
  102. #if NUM_SERVOS > 0
  103. #include "Servo.h"
  104. #endif
  105. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  106. #include <SPI.h>
  107. #endif
  108. #include "mmu2.h"
  109. #define VERSION_STRING "1.0.2"
  110. #include "ultralcd.h"
  111. #include "sound.h"
  112. #include "cmdqueue.h"
  113. //Macro for print fan speed
  114. #define FAN_PULSE_WIDTH_LIMIT ((fanSpeed > 100) ? 3 : 4) //time in ms
  115. //filament types
  116. #define FILAMENT_DEFAULT 0
  117. #define FILAMENT_FLEX 1
  118. #define FILAMENT_PVA 2
  119. #define FILAMENT_UNDEFINED 255
  120. //Stepper Movement Variables
  121. //===========================================================================
  122. //=============================imported variables============================
  123. //===========================================================================
  124. //===========================================================================
  125. //=============================public variables=============================
  126. //===========================================================================
  127. #ifdef SDSUPPORT
  128. CardReader card;
  129. #endif
  130. uint8_t mbl_z_probe_nr = 3; //numer of Z measurements for each point in mesh bed leveling calibration
  131. //used for PINDA temp calibration and pause print
  132. #define DEFAULT_RETRACTION 1
  133. #define DEFAULT_RETRACTION_MM 4 //MM
  134. float default_retraction = DEFAULT_RETRACTION;
  135. float homing_feedrate[] = HOMING_FEEDRATE;
  136. //Although this flag and many others like this could be represented with a struct/bitfield for each axis (more readable and efficient code), the implementation
  137. //would not be standard across all platforms. That being said, the code will continue to use bitmasks for independent axis.
  138. //Moreover, according to C/C++ standard, the ordering of bits is platform/compiler dependent and the compiler is allowed to align the bits arbitrarily,
  139. //thus bit operations like shifting and masking may stop working and will be very hard to fix.
  140. uint8_t axis_relative_modes = 0;
  141. int feedmultiply=100; //100->1 200->2
  142. int extrudemultiply=100; //100->1 200->2
  143. int extruder_multiply[EXTRUDERS] = {100
  144. #if EXTRUDERS > 1
  145. , 100
  146. #if EXTRUDERS > 2
  147. , 100
  148. #endif
  149. #endif
  150. };
  151. bool homing_flag = false;
  152. unsigned long pause_time = 0;
  153. unsigned long start_pause_print = _millis();
  154. unsigned long t_fan_rising_edge = _millis();
  155. LongTimer safetyTimer;
  156. static LongTimer crashDetTimer;
  157. //unsigned long load_filament_time;
  158. bool mesh_bed_leveling_flag = false;
  159. unsigned long total_filament_used;
  160. HeatingStatus heating_status;
  161. uint8_t heating_status_counter;
  162. bool loading_flag = false;
  163. #define XY_NO_RESTORE_FLAG (mesh_bed_leveling_flag || homing_flag)
  164. bool fan_state[2];
  165. int fan_edge_counter[2];
  166. int fan_speed[2];
  167. float extruder_multiplier[EXTRUDERS] = {1.0
  168. #if EXTRUDERS > 1
  169. , 1.0
  170. #if EXTRUDERS > 2
  171. , 1.0
  172. #endif
  173. #endif
  174. };
  175. float current_position[NUM_AXIS] = { 0.0, 0.0, 0.0, 0.0 };
  176. //shortcuts for more readable code
  177. #define _x current_position[X_AXIS]
  178. #define _y current_position[Y_AXIS]
  179. #define _z current_position[Z_AXIS]
  180. #define _e current_position[E_AXIS]
  181. float min_pos[3] = { X_MIN_POS, Y_MIN_POS, Z_MIN_POS };
  182. float max_pos[3] = { X_MAX_POS, Y_MAX_POS, Z_MAX_POS };
  183. bool axis_known_position[3] = {false, false, false};
  184. // Extruder offset
  185. #if EXTRUDERS > 1
  186. #define NUM_EXTRUDER_OFFSETS 2 // only in XY plane
  187. float extruder_offset[NUM_EXTRUDER_OFFSETS][EXTRUDERS] = {
  188. #if defined(EXTRUDER_OFFSET_X) && defined(EXTRUDER_OFFSET_Y)
  189. EXTRUDER_OFFSET_X, EXTRUDER_OFFSET_Y
  190. #endif
  191. };
  192. #endif
  193. int fanSpeed=0;
  194. uint8_t newFanSpeed = 0;
  195. #ifdef FWRETRACT
  196. bool retracted[EXTRUDERS]={false
  197. #if EXTRUDERS > 1
  198. , false
  199. #if EXTRUDERS > 2
  200. , false
  201. #endif
  202. #endif
  203. };
  204. bool retracted_swap[EXTRUDERS]={false
  205. #if EXTRUDERS > 1
  206. , false
  207. #if EXTRUDERS > 2
  208. , false
  209. #endif
  210. #endif
  211. };
  212. float retract_length_swap = RETRACT_LENGTH_SWAP;
  213. float retract_recover_length_swap = RETRACT_RECOVER_LENGTH_SWAP;
  214. #endif
  215. #ifdef PS_DEFAULT_OFF
  216. bool powersupply = false;
  217. #else
  218. bool powersupply = true;
  219. #endif
  220. bool cancel_heatup = false;
  221. int8_t busy_state = NOT_BUSY;
  222. static long prev_busy_signal_ms = -1;
  223. uint8_t host_keepalive_interval = HOST_KEEPALIVE_INTERVAL;
  224. const char errormagic[] PROGMEM = "Error:";
  225. const char echomagic[] PROGMEM = "echo:";
  226. const char G28W0[] PROGMEM = "G28 W0";
  227. // Define some coordinates outside the clamp limits (making them invalid past the parsing stage) so
  228. // that they can be used later for various logical checks
  229. #define X_COORD_INVALID (X_MIN_POS-1)
  230. #define SAVED_START_POSITION_UNSET X_COORD_INVALID
  231. float saved_start_position[NUM_AXIS] = {SAVED_START_POSITION_UNSET, 0, 0, 0};
  232. uint16_t saved_segment_idx = 0;
  233. // storing estimated time to end of print counted by slicer
  234. uint8_t print_percent_done_normal = PRINT_PERCENT_DONE_INIT;
  235. uint8_t print_percent_done_silent = PRINT_PERCENT_DONE_INIT;
  236. uint16_t print_time_remaining_normal = PRINT_TIME_REMAINING_INIT; //estimated remaining print time in minutes
  237. uint16_t print_time_remaining_silent = PRINT_TIME_REMAINING_INIT; //estimated remaining print time in minutes
  238. uint16_t print_time_to_change_normal = PRINT_TIME_REMAINING_INIT; //estimated remaining time to next change in minutes
  239. uint16_t print_time_to_change_silent = PRINT_TIME_REMAINING_INIT; //estimated remaining time to next change in minutes
  240. uint32_t IP_address = 0;
  241. //===========================================================================
  242. //=============================Private Variables=============================
  243. //===========================================================================
  244. #define MSG_BED_LEVELING_FAILED_TIMEOUT 30
  245. const char axis_codes[NUM_AXIS] = {'X', 'Y', 'Z', 'E'};
  246. float destination[NUM_AXIS] = { 0.0, 0.0, 0.0, 0.0};
  247. // For tracing an arc
  248. static float offset[3] = {0.0, 0.0, 0.0};
  249. // Current feedrate
  250. float feedrate = 1500.0;
  251. // Feedrate for the next move
  252. static float next_feedrate;
  253. // Original feedrate saved during homing moves
  254. static float saved_feedrate;
  255. const int8_t sensitive_pins[] PROGMEM = SENSITIVE_PINS; // Sensitive pin list for M42
  256. //static float tt = 0;
  257. //static float bt = 0;
  258. //Inactivity shutdown variables
  259. static LongTimer previous_millis_cmd;
  260. unsigned long max_inactive_time = 0;
  261. static unsigned long stepper_inactive_time = DEFAULT_STEPPER_DEACTIVE_TIME*1000l;
  262. static unsigned long safetytimer_inactive_time = DEFAULT_SAFETYTIMER_TIME_MINS*60*1000ul;
  263. unsigned long starttime=0;
  264. unsigned long stoptime=0;
  265. ShortTimer usb_timer;
  266. bool Stopped=false;
  267. #if NUM_SERVOS > 0
  268. Servo servos[NUM_SERVOS];
  269. #endif
  270. bool target_direction;
  271. //Insert variables if CHDK is defined
  272. #ifdef CHDK
  273. unsigned long chdkHigh = 0;
  274. bool chdkActive = false;
  275. #endif
  276. //! @name RAM save/restore printing
  277. //! @{
  278. bool saved_printing = false; //!< Print is paused and saved in RAM
  279. static uint32_t saved_sdpos = 0; //!< SD card position, or line number in case of USB printing
  280. uint8_t saved_printing_type = PRINTING_TYPE_SD;
  281. static float saved_pos[4] = { X_COORD_INVALID, 0, 0, 0 };
  282. static uint16_t saved_feedrate2 = 0; //!< Default feedrate (truncated from float)
  283. static int saved_feedmultiply2 = 0;
  284. float saved_extruder_temperature = 0.0; //!< Active extruder temperature
  285. float saved_bed_temperature = 0.0;
  286. static bool saved_extruder_relative_mode = false;
  287. int saved_fan_speed = 0; //!< Print fan speed
  288. //! @}
  289. static int saved_feedmultiply_mm = 100;
  290. class AutoReportFeatures {
  291. union {
  292. struct {
  293. uint8_t temp : 1; //Temperature flag
  294. uint8_t fans : 1; //Fans flag
  295. uint8_t pos: 1; //Position flag
  296. uint8_t ar4 : 1; //Unused
  297. uint8_t ar5 : 1; //Unused
  298. uint8_t ar6 : 1; //Unused
  299. uint8_t ar7 : 1; //Unused
  300. } __attribute__((packed)) bits;
  301. uint8_t byte;
  302. } arFunctionsActive;
  303. uint8_t auto_report_period;
  304. public:
  305. LongTimer auto_report_timer;
  306. AutoReportFeatures():auto_report_period(0){
  307. #if defined(AUTO_REPORT)
  308. arFunctionsActive.byte = 0xff;
  309. #else
  310. arFunctionsActive.byte = 0;
  311. #endif //AUTO_REPORT
  312. }
  313. inline bool Temp()const { return arFunctionsActive.bits.temp != 0; }
  314. inline void SetTemp(uint8_t v){ arFunctionsActive.bits.temp = v; }
  315. inline bool Fans()const { return arFunctionsActive.bits.fans != 0; }
  316. inline void SetFans(uint8_t v){ arFunctionsActive.bits.fans = v; }
  317. inline bool Pos()const { return arFunctionsActive.bits.pos != 0; }
  318. inline void SetPos(uint8_t v){ arFunctionsActive.bits.pos = v; }
  319. inline void SetMask(uint8_t mask){ arFunctionsActive.byte = mask; }
  320. /// sets the autoreporting timer's period
  321. /// setting it to zero stops the timer
  322. void SetPeriod(uint8_t p){
  323. auto_report_period = p;
  324. if (auto_report_period != 0){
  325. auto_report_timer.start();
  326. } else{
  327. auto_report_timer.stop();
  328. }
  329. }
  330. inline void TimerStart() { auto_report_timer.start(); }
  331. inline bool TimerRunning()const { return auto_report_timer.running(); }
  332. inline bool TimerExpired() { return auto_report_timer.expired(auto_report_period * 1000ul); }
  333. };
  334. AutoReportFeatures autoReportFeatures;
  335. //===========================================================================
  336. //=============================Routines======================================
  337. //===========================================================================
  338. static bool setTargetedHotend(int code, uint8_t &extruder);
  339. static void print_time_remaining_init();
  340. static void wait_for_heater(long codenum, uint8_t extruder);
  341. static void gcode_G28(bool home_x_axis, bool home_y_axis, bool home_z_axis);
  342. static void gcode_M105(uint8_t extruder);
  343. #ifndef PINDA_THERMISTOR
  344. static void temp_compensation_start();
  345. static void temp_compensation_apply();
  346. #endif
  347. #ifdef PRUSA_SN_SUPPORT
  348. static uint8_t get_PRUSA_SN(char* SN);
  349. #endif //PRUSA_SN_SUPPORT
  350. uint16_t gcode_in_progress = 0;
  351. uint16_t mcode_in_progress = 0;
  352. void serial_echopair_P(const char *s_P, float v)
  353. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  354. void serial_echopair_P(const char *s_P, double v)
  355. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  356. void serial_echopair_P(const char *s_P, unsigned long v)
  357. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  358. void serialprintPGM(const char *str) {
  359. while(uint8_t ch = pgm_read_byte(str)) {
  360. MYSERIAL.write((char)ch);
  361. ++str;
  362. }
  363. }
  364. void serialprintlnPGM(const char *str) {
  365. serialprintPGM(str);
  366. MYSERIAL.println();
  367. }
  368. #ifdef SDSUPPORT
  369. #include "SdFatUtil.h"
  370. int freeMemory() { return SdFatUtil::FreeRam(); }
  371. #else
  372. extern "C" {
  373. extern unsigned int __bss_end;
  374. extern unsigned int __heap_start;
  375. extern void *__brkval;
  376. int freeMemory() {
  377. int free_memory;
  378. if ((int)__brkval == 0)
  379. free_memory = ((int)&free_memory) - ((int)&__bss_end);
  380. else
  381. free_memory = ((int)&free_memory) - ((int)__brkval);
  382. return free_memory;
  383. }
  384. }
  385. #endif //!SDSUPPORT
  386. void setup_killpin()
  387. {
  388. #if defined(KILL_PIN) && KILL_PIN > -1
  389. SET_INPUT(KILL_PIN);
  390. WRITE(KILL_PIN,HIGH);
  391. #endif
  392. }
  393. // Set home pin
  394. void setup_homepin(void)
  395. {
  396. #if defined(HOME_PIN) && HOME_PIN > -1
  397. SET_INPUT(HOME_PIN);
  398. WRITE(HOME_PIN,HIGH);
  399. #endif
  400. }
  401. void setup_photpin()
  402. {
  403. #if defined(PHOTOGRAPH_PIN) && PHOTOGRAPH_PIN > -1
  404. SET_OUTPUT(PHOTOGRAPH_PIN);
  405. WRITE(PHOTOGRAPH_PIN, LOW);
  406. #endif
  407. }
  408. void setup_powerhold()
  409. {
  410. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  411. SET_OUTPUT(SUICIDE_PIN);
  412. WRITE(SUICIDE_PIN, HIGH);
  413. #endif
  414. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  415. SET_OUTPUT(PS_ON_PIN);
  416. #if defined(PS_DEFAULT_OFF)
  417. WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  418. #else
  419. WRITE(PS_ON_PIN, PS_ON_AWAKE);
  420. #endif
  421. #endif
  422. }
  423. void suicide()
  424. {
  425. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  426. SET_OUTPUT(SUICIDE_PIN);
  427. WRITE(SUICIDE_PIN, LOW);
  428. #endif
  429. }
  430. void servo_init()
  431. {
  432. #if (NUM_SERVOS >= 1) && defined(SERVO0_PIN) && (SERVO0_PIN > -1)
  433. servos[0].attach(SERVO0_PIN);
  434. #endif
  435. #if (NUM_SERVOS >= 2) && defined(SERVO1_PIN) && (SERVO1_PIN > -1)
  436. servos[1].attach(SERVO1_PIN);
  437. #endif
  438. #if (NUM_SERVOS >= 3) && defined(SERVO2_PIN) && (SERVO2_PIN > -1)
  439. servos[2].attach(SERVO2_PIN);
  440. #endif
  441. #if (NUM_SERVOS >= 4) && defined(SERVO3_PIN) && (SERVO3_PIN > -1)
  442. servos[3].attach(SERVO3_PIN);
  443. #endif
  444. #if (NUM_SERVOS >= 5)
  445. #error "TODO: enter initalisation code for more servos"
  446. #endif
  447. }
  448. bool __attribute__((noinline)) printer_active() {
  449. return IS_SD_PRINTING
  450. || usb_timer.running()
  451. || isPrintPaused
  452. || (custom_message_type == CustomMsg::TempCal)
  453. || saved_printing
  454. || (lcd_commands_type == LcdCommands::Layer1Cal)
  455. || MMU2::mmu2.MMU_PRINT_SAVED()
  456. || homing_flag
  457. || mesh_bed_leveling_flag;
  458. }
  459. bool fans_check_enabled = true;
  460. #ifdef TMC2130
  461. void crashdet_stop_and_save_print()
  462. {
  463. stop_and_save_print_to_ram(10, -default_retraction); //XY - no change, Z 10mm up, E -1mm retract
  464. }
  465. void crashdet_restore_print_and_continue()
  466. {
  467. restore_print_from_ram_and_continue(default_retraction); //XYZ = orig, E +1mm unretract
  468. // babystep_apply();
  469. }
  470. void crashdet_fmt_error(char* buf, uint8_t mask)
  471. {
  472. if(mask & X_AXIS_MASK) *buf++ = axis_codes[X_AXIS];
  473. if(mask & Y_AXIS_MASK) *buf++ = axis_codes[Y_AXIS];
  474. *buf++ = ' ';
  475. strcpy_P(buf, _T(MSG_CRASH_DETECTED));
  476. }
  477. void crashdet_detected(uint8_t mask)
  478. {
  479. st_synchronize();
  480. static uint8_t crashDet_counter = 0;
  481. static uint8_t crashDet_axes = 0;
  482. bool automatic_recovery_after_crash = true;
  483. char msg[LCD_WIDTH+1] = "";
  484. if (crashDetTimer.expired(CRASHDET_TIMER * 1000ul)) {
  485. crashDet_counter = 0;
  486. }
  487. if(++crashDet_counter >= CRASHDET_COUNTER_MAX) {
  488. automatic_recovery_after_crash = false;
  489. }
  490. crashDetTimer.start();
  491. crashDet_axes |= mask;
  492. lcd_update_enable(true);
  493. lcd_clear();
  494. lcd_update(2);
  495. if (mask & X_AXIS_MASK)
  496. {
  497. eeprom_increment_byte((uint8_t*)EEPROM_CRASH_COUNT_X);
  498. eeprom_increment_word((uint16_t*)EEPROM_CRASH_COUNT_X_TOT);
  499. }
  500. if (mask & Y_AXIS_MASK)
  501. {
  502. eeprom_increment_byte((uint8_t*)EEPROM_CRASH_COUNT_Y);
  503. eeprom_increment_word((uint16_t*)EEPROM_CRASH_COUNT_Y_TOT);
  504. }
  505. lcd_update_enable(true);
  506. lcd_update(2);
  507. // prepare the status message with the _current_ axes status
  508. crashdet_fmt_error(msg, mask);
  509. lcd_setstatus(msg);
  510. gcode_G28(true, true, false); //home X and Y
  511. if (automatic_recovery_after_crash) {
  512. enquecommand_P(PSTR("CRASH_RECOVER"));
  513. }else{
  514. setTargetHotend(0, active_extruder);
  515. // notify the user of *all* the axes previously affected, not just the last one
  516. lcd_update_enable(false);
  517. lcd_clear();
  518. crashdet_fmt_error(msg, crashDet_axes);
  519. crashDet_axes = 0;
  520. lcd_print(msg);
  521. // ask whether to resume printing
  522. lcd_set_cursor(0, 1);
  523. lcd_puts_P(_T(MSG_RESUME_PRINT));
  524. lcd_putc('?');
  525. uint8_t yesno = lcd_show_yes_no_and_wait(false);
  526. if (yesno == LCD_LEFT_BUTTON_CHOICE)
  527. {
  528. enquecommand_P(PSTR("CRASH_RECOVER"));
  529. }
  530. else // LCD_MIDDLE_BUTTON_CHOICE
  531. {
  532. enquecommand_P(PSTR("CRASH_CANCEL"));
  533. }
  534. }
  535. }
  536. void crashdet_recover()
  537. {
  538. crashdet_restore_print_and_continue();
  539. if (lcd_crash_detect_enabled()) tmc2130_sg_stop_on_crash = true;
  540. }
  541. void crashdet_cancel()
  542. {
  543. saved_printing = false;
  544. tmc2130_sg_stop_on_crash = true;
  545. if (saved_printing_type == PRINTING_TYPE_SD) {
  546. lcd_print_stop();
  547. }else if(saved_printing_type == PRINTING_TYPE_USB){
  548. SERIAL_ECHOLNRPGM(MSG_OCTOPRINT_CANCEL); //for Octoprint: works the same as clicking "Abort" button in Octoprint GUI
  549. cmdqueue_reset();
  550. }
  551. }
  552. #endif //TMC2130
  553. void failstats_reset_print()
  554. {
  555. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_X, 0);
  556. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_Y, 0);
  557. eeprom_update_byte((uint8_t *)EEPROM_FERROR_COUNT, 0);
  558. eeprom_update_byte((uint8_t *)EEPROM_POWER_COUNT, 0);
  559. eeprom_update_byte((uint8_t *)EEPROM_MMU_FAIL, 0);
  560. eeprom_update_byte((uint8_t *)EEPROM_MMU_LOAD_FAIL, 0);
  561. }
  562. void softReset()
  563. {
  564. cli();
  565. wdt_enable(WDTO_15MS);
  566. while(1);
  567. }
  568. #ifdef MESH_BED_LEVELING
  569. enum MeshLevelingState { MeshReport, MeshStart, MeshNext, MeshSet };
  570. #endif
  571. static void factory_reset_stats(){
  572. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, 0);
  573. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, 0);
  574. failstats_reset_print();
  575. eeprom_update_word((uint16_t *)EEPROM_CRASH_COUNT_X_TOT, 0);
  576. eeprom_update_word((uint16_t *)EEPROM_CRASH_COUNT_Y_TOT, 0);
  577. eeprom_update_word((uint16_t *)EEPROM_FERROR_COUNT_TOT, 0);
  578. eeprom_update_word((uint16_t *)EEPROM_POWER_COUNT_TOT, 0);
  579. eeprom_update_word((uint16_t *)EEPROM_MMU_FAIL_TOT, 0);
  580. eeprom_update_word((uint16_t *)EEPROM_MMU_LOAD_FAIL_TOT, 0);
  581. eeprom_update_dword((uint32_t *)EEPROM_TOTAL_TOOLCHANGE_COUNT, 0);
  582. }
  583. // Factory reset function
  584. // This function is used to erase parts or whole EEPROM memory which is used for storing calibration and and so on.
  585. // Level input parameter sets depth of reset
  586. static void factory_reset(char level)
  587. {
  588. lcd_clear();
  589. Sound_MakeCustom(100,0,false);
  590. switch (level) {
  591. case 0: // Level 0: Language reset
  592. lang_reset();
  593. break;
  594. case 1: //Level 1: Reset statistics
  595. factory_reset_stats();
  596. lcd_menu_statistics();
  597. break;
  598. case 2: // Level 2: Prepare for shipping
  599. factory_reset_stats();
  600. // FALLTHRU
  601. case 3: // Level 3: Preparation after being serviced
  602. // Force language selection at the next boot up.
  603. lang_reset();
  604. // Force the "Follow calibration flow" message at the next boot up.
  605. calibration_status_store(CALIBRATION_STATUS_Z_CALIBRATION);
  606. eeprom_write_byte((uint8_t*)EEPROM_WIZARD_ACTIVE, 2); //run wizard
  607. farm_disable();
  608. #ifdef FILAMENT_SENSOR
  609. fsensor.setEnabled(true);
  610. fsensor.setAutoLoadEnabled(true, true);
  611. fsensor.setRunoutEnabled(true, true);
  612. #if (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  613. fsensor.setJamDetectionEnabled(true, true);
  614. #endif //(FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  615. #endif //FILAMENT_SENSOR
  616. break;
  617. case 4:
  618. menu_progressbar_init(EEPROM_TOP, PSTR("ERASING all data"));
  619. // Erase EEPROM
  620. for (uint16_t i = 0; i < EEPROM_TOP; i++) {
  621. eeprom_update_byte((uint8_t*)i, 0xFF);
  622. menu_progressbar_update(i);
  623. }
  624. menu_progressbar_finish();
  625. softReset();
  626. break;
  627. default:
  628. break;
  629. }
  630. }
  631. extern "C" {
  632. FILE _uartout; //= {0}; Global variable is always zero initialized. No need to explicitly state this.
  633. }
  634. int uart_putchar(char c, FILE *)
  635. {
  636. MYSERIAL.write(c);
  637. return 0;
  638. }
  639. void lcd_splash()
  640. {
  641. lcd_clear(); // clears display and homes screen
  642. lcd_printf_P(PSTR("\n Original Prusa i3\n Prusa Research\n%20.20S"), PSTR(FW_VERSION));
  643. }
  644. void factory_reset()
  645. {
  646. KEEPALIVE_STATE(PAUSED_FOR_USER);
  647. if (!READ(BTN_ENC))
  648. {
  649. _delay_ms(1000);
  650. if (!READ(BTN_ENC))
  651. {
  652. lcd_clear();
  653. lcd_puts_P(PSTR("Factory RESET"));
  654. SET_OUTPUT(BEEPER);
  655. if(eSoundMode!=e_SOUND_MODE_SILENT)
  656. WRITE(BEEPER, HIGH);
  657. while (!READ(BTN_ENC));
  658. WRITE(BEEPER, LOW);
  659. _delay_ms(2000);
  660. char level = reset_menu();
  661. factory_reset(level);
  662. switch (level) {
  663. case 0:
  664. case 1:
  665. case 2:
  666. case 3:
  667. case 4: _delay_ms(0); break;
  668. }
  669. }
  670. }
  671. KEEPALIVE_STATE(IN_HANDLER);
  672. }
  673. #if 0
  674. void show_fw_version_warnings() {
  675. if (FW_DEV_VERSION == FW_VERSION_GOLD || FW_DEV_VERSION == FW_VERSION_RC) return;
  676. switch (FW_DEV_VERSION) {
  677. case(FW_VERSION_BETA): lcd_show_fullscreen_message_and_wait_P(MSG_FW_VERSION_BETA); break;
  678. case(FW_VERSION_ALPHA):
  679. case(FW_VERSION_DEVEL):
  680. case(FW_VERSION_DEBUG):
  681. lcd_update_enable(false);
  682. lcd_clear();
  683. #if (FW_DEV_VERSION == FW_VERSION_DEVEL || FW_DEV_VERSION == FW_VERSION_ALPHA)
  684. lcd_puts_at_P(0, 0, PSTR("Development build !!"));
  685. #else
  686. lcd_puts_at_P(0, 0, PSTR("Debbugging build !!!"));
  687. #endif
  688. lcd_puts_at_P(0, 1, PSTR("May destroy printer!"));
  689. lcd_puts_at_P(0, 2, PSTR("FW")); lcd_puts_P(PSTR(FW_VERSION_FULL));
  690. lcd_puts_at_P(0, 3, PSTR("Repo: ")); lcd_puts_P(PSTR(FW_REPOSITORY));
  691. lcd_wait_for_click();
  692. break;
  693. // default: lcd_show_fullscreen_message_and_wait_P(_i("WARNING: This is an unofficial, unsupported build. Use at your own risk!")); break;////MSG_FW_VERSION_UNKNOWN c=20 r=8
  694. }
  695. lcd_update_enable(true);
  696. }
  697. #endif
  698. #if defined(FILAMENT_SENSOR) && defined(FSENSOR_PROBING)
  699. //! @brief try to check if firmware is on right type of printer
  700. static void check_if_fw_is_on_right_printer() {
  701. if (fsensor.probeOtherType()) {
  702. lcd_show_fullscreen_message_and_wait_P(_i(PRINTER_NAME " firmware detected on " PRINTER_NAME_ALTERNATE " printer"));////c=20 r=4
  703. }
  704. }
  705. #endif //defined(FILAMENT_SENSOR) && defined(FSENSOR_PROBING)
  706. uint8_t check_printer_version()
  707. {
  708. uint8_t version_changed = 0;
  709. uint16_t printer_type = eeprom_read_word((uint16_t*)EEPROM_PRINTER_TYPE);
  710. uint16_t motherboard = eeprom_read_word((uint16_t*)EEPROM_BOARD_TYPE);
  711. if (printer_type != PRINTER_TYPE) {
  712. if (printer_type == 0xffff) eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  713. else version_changed |= 0b10;
  714. }
  715. if (motherboard != MOTHERBOARD) {
  716. if(motherboard == 0xffff) eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  717. else version_changed |= 0b01;
  718. }
  719. return version_changed;
  720. }
  721. #ifdef BOOTAPP
  722. #include "bootapp.h" //bootloader support
  723. #endif //BOOTAPP
  724. #if (LANG_MODE != 0) //secondary language support
  725. #ifdef XFLASH
  726. // language update from external flash
  727. #define LANGBOOT_BLOCKSIZE 0x1000u
  728. #define LANGBOOT_RAMBUFFER 0x0800
  729. void update_sec_lang_from_external_flash()
  730. {
  731. if ((boot_app_magic == BOOT_APP_MAGIC) && (boot_app_flags & BOOT_APP_FLG_USER0))
  732. {
  733. uint8_t lang = boot_reserved >> 3;
  734. uint8_t state = boot_reserved & 0x07;
  735. lang_table_header_t header;
  736. uint32_t src_addr;
  737. if (lang_get_header(lang, &header, &src_addr))
  738. {
  739. lcd_puts_at_P(1,3,PSTR("Language update."));
  740. for (uint8_t i = 0; i < state; i++) fputc('.', lcdout);
  741. _delay(100);
  742. boot_reserved = (boot_reserved & 0xF8) | ((state + 1) & 0x07);
  743. if ((state * LANGBOOT_BLOCKSIZE) < header.size)
  744. {
  745. cli();
  746. uint16_t size = header.size - state * LANGBOOT_BLOCKSIZE;
  747. if (size > LANGBOOT_BLOCKSIZE) size = LANGBOOT_BLOCKSIZE;
  748. xflash_rd_data(src_addr + state * LANGBOOT_BLOCKSIZE, (uint8_t*)LANGBOOT_RAMBUFFER, size);
  749. if (state == 0)
  750. {
  751. //TODO - check header integrity
  752. }
  753. bootapp_ram2flash(LANGBOOT_RAMBUFFER, _SEC_LANG_TABLE + state * LANGBOOT_BLOCKSIZE, size);
  754. }
  755. else
  756. {
  757. //TODO - check sec lang data integrity
  758. eeprom_update_byte((unsigned char *)EEPROM_LANG, LANG_ID_SEC);
  759. }
  760. }
  761. }
  762. boot_app_flags &= ~BOOT_APP_FLG_USER0;
  763. }
  764. #ifdef DEBUG_XFLASH
  765. uint8_t lang_xflash_enum_codes(uint16_t* codes)
  766. {
  767. lang_table_header_t header;
  768. uint8_t count = 0;
  769. uint32_t addr = 0x00000;
  770. while (1)
  771. {
  772. printf_P(_n("LANGTABLE%d:"), count);
  773. xflash_rd_data(addr, (uint8_t*)&header, sizeof(lang_table_header_t));
  774. if (header.magic != LANG_MAGIC)
  775. {
  776. puts_P(_n("NG!"));
  777. break;
  778. }
  779. puts_P(_n("OK"));
  780. printf_P(_n(" _lt_magic = 0x%08lx %S\n"), header.magic, (header.magic==LANG_MAGIC)?_n("OK"):_n("NA"));
  781. printf_P(_n(" _lt_size = 0x%04x (%d)\n"), header.size, header.size);
  782. printf_P(_n(" _lt_count = 0x%04x (%d)\n"), header.count, header.count);
  783. printf_P(_n(" _lt_chsum = 0x%04x\n"), header.checksum);
  784. printf_P(_n(" _lt_code = 0x%04x (%c%c)\n"), header.code, header.code >> 8, header.code & 0xff);
  785. printf_P(_n(" _lt_sign = 0x%08lx\n"), header.signature);
  786. addr += header.size;
  787. codes[count] = header.code;
  788. count ++;
  789. }
  790. return count;
  791. }
  792. void list_sec_lang_from_external_flash()
  793. {
  794. uint16_t codes[8];
  795. uint8_t count = lang_xflash_enum_codes(codes);
  796. printf_P(_n("XFlash lang count = %hhd\n"), count);
  797. }
  798. #endif //DEBUG_XFLASH
  799. #endif //XFLASH
  800. #endif //(LANG_MODE != 0)
  801. static void fw_crash_init()
  802. {
  803. #ifdef XFLASH_DUMP
  804. dump_crash_reason crash_reason;
  805. if(xfdump_check_state(&crash_reason))
  806. {
  807. // always signal to the host that a dump is available for retrieval
  808. puts_P(_N("// action:dump_available"));
  809. #ifdef EMERGENCY_DUMP
  810. if(crash_reason != dump_crash_reason::manual &&
  811. eeprom_read_byte((uint8_t*)EEPROM_FW_CRASH_FLAG) != 0xFF)
  812. {
  813. lcd_show_fullscreen_message_and_wait_P(
  814. _n("FW crash detected! "
  815. "You can continue printing. "
  816. "Debug data available for analysis. "
  817. "Contact support to submit details."));
  818. }
  819. #endif
  820. }
  821. #else //XFLASH_DUMP
  822. dump_crash_reason crash_reason = (dump_crash_reason)eeprom_read_byte((uint8_t*)EEPROM_FW_CRASH_FLAG);
  823. if(crash_reason != dump_crash_reason::manual && (uint8_t)crash_reason != 0xFF)
  824. {
  825. lcd_beeper_quick_feedback();
  826. lcd_clear();
  827. lcd_puts_P(_n("FIRMWARE CRASH!\nCrash reason:\n"));
  828. switch(crash_reason)
  829. {
  830. case dump_crash_reason::stack_error:
  831. lcd_puts_P(_n("Static memory has\nbeen overwritten"));
  832. break;
  833. case dump_crash_reason::watchdog:
  834. lcd_puts_P(_n("Watchdog timeout"));
  835. break;
  836. case dump_crash_reason::bad_isr:
  837. lcd_puts_P(_n("Bad interrupt"));
  838. break;
  839. default:
  840. lcd_print((uint8_t)crash_reason);
  841. break;
  842. }
  843. lcd_wait_for_click();
  844. }
  845. #endif //XFLASH_DUMP
  846. // prevent crash prompts to reappear once acknowledged
  847. eeprom_update_byte((uint8_t*)EEPROM_FW_CRASH_FLAG, 0xFF);
  848. }
  849. static void xflash_err_msg()
  850. {
  851. puts_P(_n("XFLASH not responding."));
  852. lcd_show_fullscreen_message_and_wait_P(_n("External SPI flash\nXFLASH is not res-\nponding. Language\nswitch unavailable."));
  853. }
  854. // "Setup" function is called by the Arduino framework on startup.
  855. // Before startup, the Timers-functions (PWM)/Analog RW and HardwareSerial provided by the Arduino-code
  856. // are initialized by the main() routine provided by the Arduino framework.
  857. void setup()
  858. {
  859. timer2_init(); // enables functional millis
  860. ultralcd_init();
  861. spi_init();
  862. lcd_splash();
  863. Sound_Init(); // also guarantee "SET_OUTPUT(BEEPER)"
  864. selectedSerialPort = eeprom_init_default_byte((uint8_t *)EEPROM_SECOND_SERIAL_ACTIVE, 0);
  865. MYSERIAL.begin(BAUDRATE);
  866. fdev_setup_stream(uartout, uart_putchar, NULL, _FDEV_SETUP_WRITE); //setup uart out stream
  867. stdout = uartout;
  868. #ifdef XFLASH
  869. bool xflash_success = xflash_init();
  870. uint8_t optiboot_status = 1;
  871. if (xflash_success)
  872. {
  873. optiboot_status = optiboot_xflash_enter();
  874. #if (LANG_MODE != 0) //secondary language support
  875. update_sec_lang_from_external_flash();
  876. #endif //(LANG_MODE != 0)
  877. }
  878. #else
  879. const bool xflash_success = true;
  880. #endif //XFLASH
  881. setup_killpin();
  882. setup_powerhold();
  883. farm_mode_init();
  884. #ifdef TMC2130
  885. if( FarmOrUserECool() ){
  886. //increased extruder current (PFW363)
  887. tmc2130_current_h[E_AXIS] = TMC2130_CURRENTS_FARM;
  888. tmc2130_current_r[E_AXIS] = TMC2130_CURRENTS_FARM;
  889. }
  890. #endif //TMC2130
  891. #ifdef PRUSA_SN_SUPPORT
  892. //Check for valid SN in EEPROM. Try to retrieve it in case it's invalid.
  893. //SN is valid only if it is NULL terminated and starts with "CZPX".
  894. {
  895. char SN[20];
  896. eeprom_read_block(SN, (uint8_t*)EEPROM_PRUSA_SN, 20);
  897. if (SN[19] || strncmp_P(SN, PSTR("CZPX"), 4))
  898. {
  899. if (!get_PRUSA_SN(SN))
  900. {
  901. eeprom_update_block(SN, (uint8_t*)EEPROM_PRUSA_SN, 20);
  902. puts_P(PSTR("SN updated"));
  903. }
  904. else
  905. puts_P(PSTR("SN update failed"));
  906. }
  907. }
  908. #endif //PRUSA_SN_SUPPORT
  909. #ifndef XFLASH
  910. SERIAL_PROTOCOLLNPGM("start");
  911. #else
  912. if ((optiboot_status != 0) || (selectedSerialPort != 0))
  913. SERIAL_PROTOCOLLNPGM("start");
  914. #endif
  915. SERIAL_ECHO_START;
  916. puts_P(PSTR(" " FW_VERSION_FULL));
  917. if (eeprom_read_byte((uint8_t *)EEPROM_MMU_ENABLED)) {
  918. MMU2::mmu2.Start();
  919. }
  920. SpoolJoin::spooljoin.initSpoolJoinStatus();
  921. //SERIAL_ECHOPAIR("Active sheet before:", static_cast<unsigned long int>(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet))));
  922. #ifdef DEBUG_SEC_LANG
  923. lang_table_header_t header;
  924. uint32_t src_addr = 0x00000;
  925. if (lang_get_header(1, &header, &src_addr))
  926. {
  927. printf_P(
  928. _n(
  929. " _src_addr = 0x%08lx\n"
  930. " _lt_magic = 0x%08lx %S\n"
  931. " _lt_size = 0x%04x (%d)\n"
  932. " _lt_count = 0x%04x (%d)\n"
  933. " _lt_chsum = 0x%04x\n"
  934. " _lt_code = 0x%04x (%c%c)\n"
  935. " _lt_resv1 = 0x%08lx\n"
  936. ),
  937. src_addr,
  938. header.magic, (header.magic==LANG_MAGIC)?_n("OK"):_n("NA"),
  939. header.size, header.size,
  940. header.count, header.count,
  941. header.checksum,
  942. header.code, header.code >> 8, header.code & 0xff,
  943. header.signature
  944. );
  945. #if 0
  946. xflash_rd_data(0x25ba, (uint8_t*)&block_buffer, 1024);
  947. for (uint16_t i = 0; i < 1024; i++)
  948. {
  949. if ((i % 16) == 0) printf_P(_n("%04x:"), 0x25ba+i);
  950. printf_P(_n(" %02x"), ((uint8_t*)&block_buffer)[i]);
  951. if ((i % 16) == 15) putchar('\n');
  952. }
  953. #endif
  954. uint16_t sum = 0;
  955. for (uint16_t i = 0; i < header.size; i++)
  956. sum += (uint16_t)pgm_read_byte((uint8_t*)(_SEC_LANG_TABLE + i)) << ((i & 1)?0:8);
  957. printf_P(_n("_SEC_LANG_TABLE checksum = %04x\n"), sum);
  958. sum -= header.checksum; //subtract checksum
  959. printf_P(_n("_SEC_LANG_TABLE checksum = %04x\n"), sum);
  960. sum = (sum >> 8) | ((sum & 0xff) << 8); //swap bytes
  961. if (sum == header.checksum)
  962. puts_P(_n("Checksum OK"));
  963. else
  964. puts_P(_n("Checksum NG"));
  965. }
  966. else
  967. puts_P(_n("lang_get_header failed!"));
  968. #if 0
  969. for (uint16_t i = 0; i < 1024*10; i++)
  970. {
  971. if ((i % 16) == 0) printf_P(_n("%04x:"), _SEC_LANG_TABLE+i);
  972. printf_P(_n(" %02x"), pgm_read_byte((uint8_t*)(_SEC_LANG_TABLE+i)));
  973. if ((i % 16) == 15) putchar('\n');
  974. }
  975. #endif
  976. #if 0
  977. SERIAL_ECHOLN("Reading eeprom from 0 to 100: start");
  978. for (int i = 0; i < 4096; ++i) {
  979. int b = eeprom_read_byte((unsigned char*)i);
  980. if (b != 255) {
  981. SERIAL_ECHO(i);
  982. SERIAL_ECHO(":");
  983. SERIAL_ECHO(b);
  984. SERIAL_ECHOLN("");
  985. }
  986. }
  987. SERIAL_ECHOLN("Reading eeprom from 0 to 100: done");
  988. #endif
  989. #endif //DEBUG_SEC_LANG
  990. // Check startup - does nothing if bootloader sets MCUSR to 0
  991. byte mcu = MCUSR;
  992. /* if (mcu & 1) SERIAL_ECHOLNRPGM(MSG_POWERUP);
  993. if (mcu & 2) SERIAL_ECHOLNRPGM(MSG_EXTERNAL_RESET);
  994. if (mcu & 4) SERIAL_ECHOLNRPGM(MSG_BROWNOUT_RESET);
  995. if (mcu & 8) SERIAL_ECHOLNRPGM(MSG_WATCHDOG_RESET);
  996. if (mcu & 32) SERIAL_ECHOLNRPGM(MSG_SOFTWARE_RESET);*/
  997. if (mcu & 1) puts_P(MSG_POWERUP);
  998. if (mcu & 2) puts_P(MSG_EXTERNAL_RESET);
  999. if (mcu & 4) puts_P(MSG_BROWNOUT_RESET);
  1000. if (mcu & 8) puts_P(MSG_WATCHDOG_RESET);
  1001. if (mcu & 32) puts_P(MSG_SOFTWARE_RESET);
  1002. MCUSR = 0;
  1003. //SERIAL_ECHORPGM(MSG_MARLIN);
  1004. //SERIAL_ECHOLNRPGM(VERSION_STRING);
  1005. #ifdef STRING_VERSION_CONFIG_H
  1006. #ifdef STRING_CONFIG_H_AUTHOR
  1007. SERIAL_ECHO_START;
  1008. SERIAL_ECHORPGM(_n(" Last Updated: "));////MSG_CONFIGURATION_VER
  1009. SERIAL_ECHOPGM(STRING_VERSION_CONFIG_H);
  1010. SERIAL_ECHORPGM(_n(" | Author: "));////MSG_AUTHOR
  1011. SERIAL_ECHOLNPGM(STRING_CONFIG_H_AUTHOR);
  1012. #endif
  1013. #endif
  1014. SERIAL_ECHO_START;
  1015. SERIAL_ECHORPGM(_n(" Free Memory: "));////MSG_FREE_MEMORY
  1016. SERIAL_ECHO(freeMemory());
  1017. SERIAL_ECHORPGM(_n(" PlannerBufferBytes: "));////MSG_PLANNER_BUFFER_BYTES
  1018. SERIAL_ECHOLN((int)sizeof(block_t)*BLOCK_BUFFER_SIZE);
  1019. //lcd_update_enable(false); // why do we need this?? - andre
  1020. // loads data from EEPROM if available else uses defaults (and resets step acceleration rate)
  1021. bool previous_settings_retrieved = false;
  1022. uint8_t hw_changed = check_printer_version();
  1023. if (!(hw_changed & 0b10)) { //if printer version wasn't changed, check for eeprom version and retrieve settings from eeprom in case that version wasn't changed
  1024. previous_settings_retrieved = Config_RetrieveSettings();
  1025. }
  1026. else { //printer version was changed so use default settings
  1027. Config_ResetDefault();
  1028. }
  1029. // writes a magic number at the end of static variables to monitor against incorrect overwriting
  1030. // of static memory by stack (this needs to be done before soft_pwm_init, since the check is
  1031. // performed inside the soft_pwm_isr)
  1032. SdFatUtil::set_stack_guard();
  1033. // Initialize pwm/temperature loops
  1034. soft_pwm_init();
  1035. temp_mgr_init();
  1036. #ifdef EXTRUDER_ALTFAN_DETECT
  1037. SERIAL_ECHORPGM(_n("Hotend fan type: "));
  1038. if (extruder_altfan_detect())
  1039. SERIAL_ECHOLNRPGM(PSTR("ALTFAN"));
  1040. else
  1041. SERIAL_ECHOLNRPGM(PSTR("NOCTUA"));
  1042. #endif //EXTRUDER_ALTFAN_DETECT
  1043. plan_init(); // Initialize planner;
  1044. factory_reset();
  1045. eeprom_init_default_byte((uint8_t*)EEPROM_SILENT, SILENT_MODE_OFF);
  1046. eeprom_init_default_byte((uint8_t*)EEPROM_WIZARD_ACTIVE, 1); //run wizard if uninitialized
  1047. lcd_encoder_diff=0;
  1048. #ifdef TMC2130
  1049. uint8_t silentMode = eeprom_read_byte((uint8_t*)EEPROM_SILENT);
  1050. if (silentMode == 0xff) silentMode = 0;
  1051. tmc2130_mode = TMC2130_MODE_NORMAL;
  1052. if (lcd_crash_detect_enabled() && !farm_mode)
  1053. {
  1054. lcd_crash_detect_enable();
  1055. puts_P(_N("CrashDetect ENABLED!"));
  1056. }
  1057. else
  1058. {
  1059. lcd_crash_detect_disable();
  1060. puts_P(_N("CrashDetect DISABLED"));
  1061. }
  1062. #ifdef TMC2130_LINEARITY_CORRECTION
  1063. #ifdef TMC2130_LINEARITY_CORRECTION_XYZ
  1064. tmc2130_wave_fac[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_X_FAC);
  1065. tmc2130_wave_fac[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_Y_FAC);
  1066. tmc2130_wave_fac[Z_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_Z_FAC);
  1067. #endif //TMC2130_LINEARITY_CORRECTION_XYZ
  1068. tmc2130_wave_fac[E_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_E_FAC);
  1069. if (tmc2130_wave_fac[X_AXIS] == 0xff) tmc2130_wave_fac[X_AXIS] = 0;
  1070. if (tmc2130_wave_fac[Y_AXIS] == 0xff) tmc2130_wave_fac[Y_AXIS] = 0;
  1071. if (tmc2130_wave_fac[Z_AXIS] == 0xff) tmc2130_wave_fac[Z_AXIS] = 0;
  1072. if (tmc2130_wave_fac[E_AXIS] == 0xff) tmc2130_wave_fac[E_AXIS] = 0;
  1073. #endif //TMC2130_LINEARITY_CORRECTION
  1074. #ifdef TMC2130_VARIABLE_RESOLUTION
  1075. tmc2130_mres[X_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[X_AXIS]);
  1076. tmc2130_mres[Y_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[Y_AXIS]);
  1077. tmc2130_mres[Z_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[Z_AXIS]);
  1078. tmc2130_mres[E_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[E_AXIS]);
  1079. #else //TMC2130_VARIABLE_RESOLUTION
  1080. tmc2130_mres[X_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_XY);
  1081. tmc2130_mres[Y_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_XY);
  1082. tmc2130_mres[Z_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_Z);
  1083. tmc2130_mres[E_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_E);
  1084. #endif //TMC2130_VARIABLE_RESOLUTION
  1085. #endif //TMC2130
  1086. st_init(); // Initialize stepper, this enables interrupts!
  1087. #ifdef TMC2130
  1088. tmc2130_mode = silentMode?TMC2130_MODE_SILENT:TMC2130_MODE_NORMAL;
  1089. update_mode_profile();
  1090. tmc2130_init(TMCInitParams(false, FarmOrUserECool() ));
  1091. #endif //TMC2130
  1092. #ifdef PSU_Delta
  1093. init_force_z(); // ! important for correct Z-axis initialization
  1094. #endif // PSU_Delta
  1095. setup_photpin();
  1096. #if 0
  1097. servo_init();
  1098. #endif
  1099. // Reset the machine correction matrix.
  1100. // It does not make sense to load the correction matrix until the machine is homed.
  1101. world2machine_reset();
  1102. // Initialize current_position accounting for software endstops to
  1103. // avoid unexpected initial shifts on the first move
  1104. clamp_to_software_endstops(current_position);
  1105. plan_set_position_curposXYZE();
  1106. // Show the xflash error message now that serial, lcd and encoder are available
  1107. if (!xflash_success)
  1108. xflash_err_msg();
  1109. #ifdef FILAMENT_SENSOR
  1110. fsensor.init();
  1111. #endif //FILAMENT_SENSOR
  1112. #if defined(CONTROLLERFAN_PIN) && (CONTROLLERFAN_PIN > -1)
  1113. SET_OUTPUT(CONTROLLERFAN_PIN); //Set pin used for driver cooling fan
  1114. #endif
  1115. setup_homepin();
  1116. #if defined(Z_AXIS_ALWAYS_ON)
  1117. enable_z();
  1118. #endif
  1119. // The farm monitoring SW may accidentally expect
  1120. // 2 messages of "printer started" to consider a printer working.
  1121. prusa_statistics(8);
  1122. // Enable Toshiba FlashAir SD card / WiFi enahanced card.
  1123. card.ToshibaFlashAir_enable(eeprom_read_byte((unsigned char*)EEPROM_TOSHIBA_FLASH_AIR_COMPATIBLITY) == 1);
  1124. // Force SD card update. Otherwise the SD card update is done from loop() on card.checkautostart(false),
  1125. // but this times out if a blocking dialog is shown in setup().
  1126. card.initsd();
  1127. #ifdef DEBUG_SD_SPEED_TEST
  1128. if (card.cardOK)
  1129. {
  1130. uint8_t* buff = (uint8_t*)block_buffer;
  1131. uint32_t block = 0;
  1132. uint32_t sumr = 0;
  1133. uint32_t sumw = 0;
  1134. for (int i = 0; i < 1024; i++)
  1135. {
  1136. uint32_t u = _micros();
  1137. bool res = card.card.readBlock(i, buff);
  1138. u = _micros() - u;
  1139. if (res)
  1140. {
  1141. printf_P(PSTR("readBlock %4d 512 bytes %lu us\n"), i, u);
  1142. sumr += u;
  1143. u = _micros();
  1144. res = card.card.writeBlock(i, buff);
  1145. u = _micros() - u;
  1146. if (res)
  1147. {
  1148. printf_P(PSTR("writeBlock %4d 512 bytes %lu us\n"), i, u);
  1149. sumw += u;
  1150. }
  1151. else
  1152. {
  1153. printf_P(PSTR("writeBlock %4d error\n"), i);
  1154. break;
  1155. }
  1156. }
  1157. else
  1158. {
  1159. printf_P(PSTR("readBlock %4d error\n"), i);
  1160. break;
  1161. }
  1162. }
  1163. uint32_t avg_rspeed = (1024 * 1000000) / (sumr / 512);
  1164. uint32_t avg_wspeed = (1024 * 1000000) / (sumw / 512);
  1165. printf_P(PSTR("avg read speed %lu bytes/s\n"), avg_rspeed);
  1166. printf_P(PSTR("avg write speed %lu bytes/s\n"), avg_wspeed);
  1167. }
  1168. else
  1169. printf_P(PSTR("Card NG!\n"));
  1170. #endif //DEBUG_SD_SPEED_TEST
  1171. eeprom_init();
  1172. // In the future, somewhere here would one compare the current firmware version against the firmware version stored in the EEPROM.
  1173. // If they differ, an update procedure may need to be performed. At the end of this block, the current firmware version
  1174. // is being written into the EEPROM, so the update procedure will be triggered only once.
  1175. #if (LANG_MODE != 0) //secondary language support
  1176. #ifdef DEBUG_XFLASH
  1177. XFLASH_SPI_ENTER();
  1178. uint8_t uid[8]; // 64bit unique id
  1179. xflash_rd_uid(uid);
  1180. puts_P(_n("XFLASH UID="));
  1181. for (uint8_t i = 0; i < 8; i ++)
  1182. printf_P(PSTR("%02x"), uid[i]);
  1183. putchar('\n');
  1184. list_sec_lang_from_external_flash();
  1185. #endif //DEBUG_XFLASH
  1186. // lang_reset();
  1187. if (!lang_select(eeprom_read_byte((uint8_t*)EEPROM_LANG)))
  1188. lcd_language();
  1189. #ifdef DEBUG_SEC_LANG
  1190. uint16_t sec_lang_code = lang_get_code(1);
  1191. uint16_t ui = _SEC_LANG_TABLE; //table pointer
  1192. printf_P(_n("lang_selected=%d\nlang_table=0x%04x\nSEC_LANG_CODE=0x%04x (%c%c)\n"), lang_selected, ui, sec_lang_code, sec_lang_code >> 8, sec_lang_code & 0xff);
  1193. lang_print_sec_lang(uartout);
  1194. #endif //DEBUG_SEC_LANG
  1195. #endif //(LANG_MODE != 0)
  1196. eeprom_init_default_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE, 0);
  1197. if (eeprom_read_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA) == 255) {
  1198. //eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0);
  1199. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  1200. int16_t z_shift = 0;
  1201. for (uint8_t i = 0; i < 5; i++) {
  1202. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  1203. }
  1204. eeprom_write_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE, 0);
  1205. }
  1206. eeprom_init_default_byte((uint8_t*)EEPROM_UVLO, 0);
  1207. eeprom_init_default_byte((uint8_t*)EEPROM_SD_SORT, 0);
  1208. //mbl_mode_init();
  1209. mbl_settings_init();
  1210. SilentModeMenu_MMU = eeprom_read_byte((uint8_t*)EEPROM_MMU_STEALTH);
  1211. if (SilentModeMenu_MMU == 255) {
  1212. SilentModeMenu_MMU = 1;
  1213. eeprom_write_byte((uint8_t*)EEPROM_MMU_STEALTH, SilentModeMenu_MMU);
  1214. }
  1215. #if !defined(DEBUG_DISABLE_FANCHECK) && defined(FANCHECK) && defined(TACH_1) && TACH_1 >-1
  1216. setup_fan_interrupt();
  1217. #endif //DEBUG_DISABLE_FANCHECK
  1218. #ifndef DEBUG_DISABLE_STARTMSGS
  1219. KEEPALIVE_STATE(PAUSED_FOR_USER);
  1220. if (!farm_mode) {
  1221. #if defined(FILAMENT_SENSOR) && defined(FSENSOR_PROBING)
  1222. check_if_fw_is_on_right_printer();
  1223. #endif //defined(FILAMENT_SENSOR) && defined(FSENSOR_PROBING)
  1224. #if 0
  1225. show_fw_version_warnings();
  1226. #endif
  1227. }
  1228. switch (hw_changed) {
  1229. //if motherboard or printer type was changed inform user as it can indicate flashing wrong firmware version
  1230. //if user confirms with knob, new hw version (printer and/or motherboard) is written to eeprom and message will be not shown next time
  1231. case(0b01):
  1232. lcd_show_fullscreen_message_and_wait_P(_i("Warning: motherboard type changed.")); ////MSG_CHANGED_MOTHERBOARD c=20 r=4
  1233. eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  1234. break;
  1235. case(0b10):
  1236. lcd_show_fullscreen_message_and_wait_P(_i("Warning: printer type changed.")); ////MSG_CHANGED_PRINTER c=20 r=4
  1237. eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  1238. break;
  1239. case(0b11):
  1240. lcd_show_fullscreen_message_and_wait_P(_i("Warning: both printer type and motherboard type changed.")); ////MSG_CHANGED_BOTH c=20 r=4
  1241. eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  1242. eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  1243. break;
  1244. default: break; //no change, show no message
  1245. }
  1246. if (!previous_settings_retrieved) {
  1247. lcd_show_fullscreen_message_and_wait_P(_i("Old settings found. Default PID, Esteps etc. will be set.")); //if EEPROM version or printer type was changed, inform user that default setting were loaded////MSG_DEFAULT_SETTINGS_LOADED c=20 r=6
  1248. Config_StoreSettings();
  1249. }
  1250. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) >= 1) {
  1251. lcd_wizard(WizState::Run);
  1252. }
  1253. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) == 0) { //dont show calibration status messages if wizard is currently active
  1254. if (calibration_status() == CALIBRATION_STATUS_ASSEMBLED ||
  1255. calibration_status() == CALIBRATION_STATUS_UNKNOWN ||
  1256. calibration_status() == CALIBRATION_STATUS_XYZ_CALIBRATION) {
  1257. // Reset the babystepping values, so the printer will not move the Z axis up when the babystepping is enabled.
  1258. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  1259. // Show the message.
  1260. lcd_show_fullscreen_message_and_wait_P(_T(MSG_FOLLOW_CALIBRATION_FLOW));
  1261. }
  1262. #ifdef TEMP_MODEL
  1263. else if (calibration_status() == CALIBRATION_STATUS_TEMP_MODEL_CALIBRATION) {
  1264. lcd_show_fullscreen_message_and_wait_P(_T(MSG_TM_NOT_CAL));
  1265. lcd_update_enable(true);
  1266. }
  1267. #endif //TEMP_MODEL
  1268. else if (calibration_status() == CALIBRATION_STATUS_LIVE_ADJUST) {
  1269. // Show the message.
  1270. lcd_show_fullscreen_message_and_wait_P(_T(MSG_BABYSTEP_Z_NOT_SET));
  1271. lcd_update_enable(true);
  1272. }
  1273. else if (calibration_status() == CALIBRATION_STATUS_CALIBRATED && eeprom_read_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE) && calibration_status_pinda() == false) {
  1274. //lcd_show_fullscreen_message_and_wait_P(_i("Temperature calibration has not been run yet"));////MSG_PINDA_NOT_CALIBRATED c=20 r=4
  1275. lcd_update_enable(true);
  1276. }
  1277. else if (calibration_status() == CALIBRATION_STATUS_Z_CALIBRATION) {
  1278. // Show the message.
  1279. lcd_show_fullscreen_message_and_wait_P(_T(MSG_FOLLOW_Z_CALIBRATION_FLOW));
  1280. }
  1281. }
  1282. #if !defined (DEBUG_DISABLE_FORCE_SELFTEST) && defined (TMC2130)
  1283. if (force_selftest_if_fw_version() && calibration_status() < CALIBRATION_STATUS_ASSEMBLED) {
  1284. lcd_show_fullscreen_message_and_wait_P(_i("Selftest will be run to calibrate accurate sensorless rehoming."));////MSG_FORCE_SELFTEST c=20 r=8
  1285. update_current_firmware_version_to_eeprom();
  1286. lcd_selftest();
  1287. }
  1288. #endif //TMC2130 && !DEBUG_DISABLE_FORCE_SELFTEST
  1289. KEEPALIVE_STATE(IN_PROCESS);
  1290. #endif //DEBUG_DISABLE_STARTMSGS
  1291. lcd_update_enable(true);
  1292. lcd_clear();
  1293. lcd_update(2);
  1294. // Store the currently running firmware into an eeprom,
  1295. // so the next time the firmware gets updated, it will know from which version it has been updated.
  1296. update_current_firmware_version_to_eeprom();
  1297. #ifdef TMC2130
  1298. tmc2130_home_origin[X_AXIS] = eeprom_init_default_byte((uint8_t*)EEPROM_TMC2130_HOME_X_ORIGIN, 0);
  1299. tmc2130_home_bsteps[X_AXIS] = eeprom_init_default_byte((uint8_t*)EEPROM_TMC2130_HOME_X_BSTEPS, 48);
  1300. tmc2130_home_fsteps[X_AXIS] = eeprom_init_default_byte((uint8_t*)EEPROM_TMC2130_HOME_X_FSTEPS, 48);
  1301. tmc2130_home_origin[Y_AXIS] = eeprom_init_default_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_ORIGIN, 0);
  1302. tmc2130_home_bsteps[Y_AXIS] = eeprom_init_default_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_BSTEPS, 48);
  1303. tmc2130_home_fsteps[Y_AXIS] = eeprom_init_default_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_FSTEPS, 48);
  1304. tmc2130_home_enabled = eeprom_init_default_byte((uint8_t*)EEPROM_TMC2130_HOME_ENABLED, 0);
  1305. #endif //TMC2130
  1306. // report crash failures
  1307. fw_crash_init();
  1308. #ifdef UVLO_SUPPORT
  1309. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO) != 0) { //previous print was terminated by UVLO
  1310. /*
  1311. if (!lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_RECOVER_PRINT), false)) recover_print();
  1312. else {
  1313. eeprom_update_byte((uint8_t*)EEPROM_UVLO, 0);
  1314. lcd_update_enable(true);
  1315. lcd_update(2);
  1316. lcd_setstatuspgm(MSG_WELCOME);
  1317. }
  1318. */
  1319. manage_heater(); // Update temperatures
  1320. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1321. printf_P(_N("Power panic detected!\nCurrent bed temp:%d\nSaved bed temp:%d\n"), (int)degBed(), eeprom_read_byte((uint8_t*)EEPROM_UVLO_TARGET_BED));
  1322. #endif
  1323. if ( degBed() > ( (float)eeprom_read_byte((uint8_t*)EEPROM_UVLO_TARGET_BED) - AUTOMATIC_UVLO_BED_TEMP_OFFSET) ){
  1324. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1325. puts_P(_N("Automatic recovery!"));
  1326. #endif
  1327. recover_print(1);
  1328. }
  1329. else{
  1330. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1331. puts_P(_N("Normal recovery!"));
  1332. #endif
  1333. if ( lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_RECOVER_PRINT), false) == LCD_LEFT_BUTTON_CHOICE) {
  1334. recover_print(0);
  1335. } else {
  1336. eeprom_update_byte((uint8_t*)EEPROM_UVLO, 0);
  1337. lcd_update_enable(true);
  1338. lcd_update(2);
  1339. lcd_setstatuspgm(MSG_WELCOME);
  1340. }
  1341. }
  1342. }
  1343. // Only arm the uvlo interrupt _after_ a recovering print has been initialized and
  1344. // the entire state machine initialized.
  1345. setup_uvlo_interrupt();
  1346. #endif //UVLO_SUPPORT
  1347. fCheckModeInit();
  1348. KEEPALIVE_STATE(NOT_BUSY);
  1349. #ifdef WATCHDOG
  1350. wdt_enable(WDTO_4S);
  1351. #ifdef EMERGENCY_HANDLERS
  1352. WDTCSR |= (1 << WDIE);
  1353. #endif //EMERGENCY_HANDLERS
  1354. #endif //WATCHDOG
  1355. }
  1356. static inline void crash_and_burn(dump_crash_reason reason)
  1357. {
  1358. WRITE(BEEPER, HIGH);
  1359. eeprom_update_byte((uint8_t*)EEPROM_FW_CRASH_FLAG, (uint8_t)reason);
  1360. #ifdef EMERGENCY_DUMP
  1361. xfdump_full_dump_and_reset(reason);
  1362. #elif defined(EMERGENCY_SERIAL_DUMP)
  1363. if(emergency_serial_dump)
  1364. serial_dump_and_reset(reason);
  1365. #endif
  1366. softReset();
  1367. }
  1368. #ifdef EMERGENCY_HANDLERS
  1369. #ifdef WATCHDOG
  1370. ISR(WDT_vect)
  1371. {
  1372. crash_and_burn(dump_crash_reason::watchdog);
  1373. }
  1374. #endif
  1375. ISR(BADISR_vect)
  1376. {
  1377. crash_and_burn(dump_crash_reason::bad_isr);
  1378. }
  1379. #endif //EMERGENCY_HANDLERS
  1380. void stack_error() {
  1381. crash_and_burn(dump_crash_reason::stack_error);
  1382. }
  1383. /**
  1384. * Output autoreport values according to features requested in M155
  1385. */
  1386. #if defined(AUTO_REPORT)
  1387. void host_autoreport()
  1388. {
  1389. if (autoReportFeatures.TimerExpired())
  1390. {
  1391. if(autoReportFeatures.Temp()){
  1392. gcode_M105(active_extruder);
  1393. }
  1394. if(autoReportFeatures.Pos()){
  1395. gcode_M114();
  1396. }
  1397. #if defined(AUTO_REPORT) && (defined(FANCHECK) && (((defined(TACH_0) && (TACH_0 >-1)) || (defined(TACH_1) && (TACH_1 > -1)))))
  1398. if(autoReportFeatures.Fans()){
  1399. gcode_M123();
  1400. }
  1401. #endif //AUTO_REPORT and (FANCHECK and TACH_0 or TACH_1)
  1402. autoReportFeatures.TimerStart();
  1403. }
  1404. }
  1405. #endif //AUTO_REPORT
  1406. /**
  1407. * Output a "busy" message at regular intervals
  1408. * while the machine is not accepting commands.
  1409. */
  1410. void host_keepalive() {
  1411. #ifndef HOST_KEEPALIVE_FEATURE
  1412. return;
  1413. #endif //HOST_KEEPALIVE_FEATURE
  1414. if (farm_mode) return;
  1415. long ms = _millis();
  1416. if (host_keepalive_interval && busy_state != NOT_BUSY) {
  1417. if ((ms - prev_busy_signal_ms) < (long)(1000L * host_keepalive_interval)) return;
  1418. switch (busy_state) {
  1419. case IN_HANDLER:
  1420. case IN_PROCESS:
  1421. SERIAL_ECHO_START;
  1422. SERIAL_ECHOLNPGM("busy: processing");
  1423. break;
  1424. case PAUSED_FOR_USER:
  1425. SERIAL_ECHO_START;
  1426. SERIAL_ECHOLNPGM("busy: paused for user");
  1427. break;
  1428. case PAUSED_FOR_INPUT:
  1429. SERIAL_ECHO_START;
  1430. SERIAL_ECHOLNPGM("busy: paused for input");
  1431. break;
  1432. default:
  1433. break;
  1434. }
  1435. }
  1436. prev_busy_signal_ms = ms;
  1437. }
  1438. // The loop() function is called in an endless loop by the Arduino framework from the default main() routine.
  1439. // Before loop(), the setup() function is called by the main() routine.
  1440. void loop()
  1441. {
  1442. // Reset a previously aborted command, we can now start processing motion again
  1443. planner_aborted = false;
  1444. if(Stopped) {
  1445. // Currently Stopped (possibly due to an error) and not accepting new serial commands.
  1446. // Signal to the host that we're currently busy waiting for supervision.
  1447. KEEPALIVE_STATE(PAUSED_FOR_USER);
  1448. } else {
  1449. // Printer is available for processing, reset state
  1450. KEEPALIVE_STATE(NOT_BUSY);
  1451. }
  1452. if (isPrintPaused && saved_printing_type == PRINTING_TYPE_USB) { //keep believing that usb is being printed. Prevents accessing dangerous menus while pausing.
  1453. usb_timer.start();
  1454. }
  1455. else if (usb_timer.expired(10000)) { //just need to check if it expired. Nothing else is needed to be done.
  1456. ;
  1457. }
  1458. #ifdef PRUSA_M28
  1459. if (prusa_sd_card_upload)
  1460. {
  1461. //we read byte-by byte
  1462. serial_read_stream();
  1463. }
  1464. else
  1465. #endif
  1466. {
  1467. get_command();
  1468. #ifdef SDSUPPORT
  1469. card.checkautostart(false);
  1470. #endif
  1471. if(buflen)
  1472. {
  1473. cmdbuffer_front_already_processed = false;
  1474. #ifdef SDSUPPORT
  1475. if(card.saving)
  1476. {
  1477. // Saving a G-code file onto an SD-card is in progress.
  1478. // Saving starts with M28, saving until M29 is seen.
  1479. if(strstr_P(CMDBUFFER_CURRENT_STRING, PSTR("M29")) == NULL) {
  1480. card.write_command(CMDBUFFER_CURRENT_STRING);
  1481. if(card.logging)
  1482. process_commands();
  1483. else
  1484. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  1485. } else {
  1486. card.closefile();
  1487. SERIAL_PROTOCOLLNRPGM(MSG_FILE_SAVED);
  1488. }
  1489. } else {
  1490. process_commands();
  1491. }
  1492. #else
  1493. process_commands();
  1494. #endif //SDSUPPORT
  1495. if (! cmdbuffer_front_already_processed && buflen)
  1496. {
  1497. // ptr points to the start of the block currently being processed.
  1498. // The first character in the block is the block type.
  1499. char *ptr = cmdbuffer + bufindr;
  1500. if (*ptr == CMDBUFFER_CURRENT_TYPE_SDCARD) {
  1501. // To support power panic, move the length of the command on the SD card to a planner buffer.
  1502. union {
  1503. struct {
  1504. char lo;
  1505. char hi;
  1506. } lohi;
  1507. uint16_t value;
  1508. } sdlen;
  1509. sdlen.value = 0;
  1510. {
  1511. // This block locks the interrupts globally for 3.25 us,
  1512. // which corresponds to a maximum repeat frequency of 307.69 kHz.
  1513. // This blocking is safe in the context of a 10kHz stepper driver interrupt
  1514. // or a 115200 Bd serial line receive interrupt, which will not trigger faster than 12kHz.
  1515. cli();
  1516. // Reset the command to something, which will be ignored by the power panic routine,
  1517. // so this buffer length will not be counted twice.
  1518. *ptr ++ = CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED;
  1519. // Extract the current buffer length.
  1520. sdlen.lohi.lo = *ptr ++;
  1521. sdlen.lohi.hi = *ptr;
  1522. // and pass it to the planner queue.
  1523. planner_add_sd_length(sdlen.value);
  1524. sei();
  1525. }
  1526. }
  1527. else if((*ptr == CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR) && !IS_SD_PRINTING){
  1528. cli();
  1529. *ptr ++ = CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED;
  1530. // and one for each command to previous block in the planner queue.
  1531. planner_add_sd_length(1);
  1532. sei();
  1533. }
  1534. // Now it is safe to release the already processed command block. If interrupted by the power panic now,
  1535. // this block's SD card length will not be counted twice as its command type has been replaced
  1536. // by CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED.
  1537. cmdqueue_pop_front();
  1538. }
  1539. host_keepalive();
  1540. }
  1541. }
  1542. //check heater every n milliseconds
  1543. manage_heater();
  1544. manage_inactivity(isPrintPaused);
  1545. checkHitEndstops();
  1546. lcd_update(0);
  1547. #ifdef TMC2130
  1548. tmc2130_check_overtemp();
  1549. if (tmc2130_sg_crash)
  1550. {
  1551. uint8_t crash = tmc2130_sg_crash;
  1552. tmc2130_sg_crash = 0;
  1553. // crashdet_stop_and_save_print();
  1554. switch (crash)
  1555. {
  1556. case 1: enquecommand_P((PSTR("CRASH_DETECTEDX"))); break;
  1557. case 2: enquecommand_P((PSTR("CRASH_DETECTEDY"))); break;
  1558. case 3: enquecommand_P((PSTR("CRASH_DETECTEDXY"))); break;
  1559. }
  1560. }
  1561. #endif //TMC2130
  1562. MMU2::mmu2.mmu_loop();
  1563. }
  1564. #define DEFINE_PGM_READ_ANY(type, reader) \
  1565. static inline type pgm_read_any(const type *p) \
  1566. { return pgm_read_##reader##_near(p); }
  1567. DEFINE_PGM_READ_ANY(float, float);
  1568. DEFINE_PGM_READ_ANY(signed char, byte);
  1569. #define XYZ_CONSTS_FROM_CONFIG(type, array, CONFIG) \
  1570. static const PROGMEM type array##_P[3] = \
  1571. { X_##CONFIG, Y_##CONFIG, Z_##CONFIG }; \
  1572. static inline type array(uint8_t axis) \
  1573. { return pgm_read_any(&array##_P[axis]); } \
  1574. type array##_ext(uint8_t axis) \
  1575. { return pgm_read_any(&array##_P[axis]); }
  1576. XYZ_CONSTS_FROM_CONFIG(float, base_min_pos, MIN_POS);
  1577. XYZ_CONSTS_FROM_CONFIG(float, base_max_pos, MAX_POS);
  1578. XYZ_CONSTS_FROM_CONFIG(float, base_home_pos, HOME_POS);
  1579. XYZ_CONSTS_FROM_CONFIG(float, max_length, MAX_LENGTH);
  1580. XYZ_CONSTS_FROM_CONFIG(float, home_retract_mm, HOME_RETRACT_MM);
  1581. XYZ_CONSTS_FROM_CONFIG(signed char, home_dir, HOME_DIR);
  1582. static void axis_is_at_home(uint8_t axis) {
  1583. current_position[axis] = base_home_pos(axis) + cs.add_homing[axis];
  1584. min_pos[axis] = base_min_pos(axis) + cs.add_homing[axis];
  1585. max_pos[axis] = base_max_pos(axis) + cs.add_homing[axis];
  1586. }
  1587. //! @return original feedmultiply
  1588. static int setup_for_endstop_move(bool enable_endstops_now = true) {
  1589. saved_feedrate = feedrate;
  1590. int l_feedmultiply = feedmultiply;
  1591. feedmultiply = 100;
  1592. previous_millis_cmd.start();
  1593. enable_endstops(enable_endstops_now);
  1594. return l_feedmultiply;
  1595. }
  1596. //! @param original_feedmultiply feedmultiply to restore
  1597. static void clean_up_after_endstop_move(int original_feedmultiply) {
  1598. #ifdef ENDSTOPS_ONLY_FOR_HOMING
  1599. enable_endstops(false);
  1600. #endif
  1601. feedrate = saved_feedrate;
  1602. feedmultiply = original_feedmultiply;
  1603. previous_millis_cmd.start();
  1604. }
  1605. #ifdef ENABLE_AUTO_BED_LEVELING
  1606. #ifdef AUTO_BED_LEVELING_GRID
  1607. static void set_bed_level_equation_lsq(double *plane_equation_coefficients)
  1608. {
  1609. vector_3 planeNormal = vector_3(-plane_equation_coefficients[0], -plane_equation_coefficients[1], 1);
  1610. planeNormal.debug("planeNormal");
  1611. plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1612. //bedLevel.debug("bedLevel");
  1613. //plan_bed_level_matrix.debug("bed level before");
  1614. //vector_3 uncorrected_position = plan_get_position_mm();
  1615. //uncorrected_position.debug("position before");
  1616. vector_3 corrected_position = plan_get_position();
  1617. // corrected_position.debug("position after");
  1618. current_position[X_AXIS] = corrected_position.x;
  1619. current_position[Y_AXIS] = corrected_position.y;
  1620. current_position[Z_AXIS] = corrected_position.z;
  1621. // put the bed at 0 so we don't go below it.
  1622. current_position[Z_AXIS] = cs.zprobe_zoffset; // in the lsq we reach here after raising the extruder due to the loop structure
  1623. plan_set_position_curposXYZE();
  1624. }
  1625. #else // not AUTO_BED_LEVELING_GRID
  1626. static void set_bed_level_equation_3pts(float z_at_pt_1, float z_at_pt_2, float z_at_pt_3) {
  1627. plan_bed_level_matrix.set_to_identity();
  1628. vector_3 pt1 = vector_3(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, z_at_pt_1);
  1629. vector_3 pt2 = vector_3(ABL_PROBE_PT_2_X, ABL_PROBE_PT_2_Y, z_at_pt_2);
  1630. vector_3 pt3 = vector_3(ABL_PROBE_PT_3_X, ABL_PROBE_PT_3_Y, z_at_pt_3);
  1631. vector_3 from_2_to_1 = (pt1 - pt2).get_normal();
  1632. vector_3 from_2_to_3 = (pt3 - pt2).get_normal();
  1633. vector_3 planeNormal = vector_3::cross(from_2_to_1, from_2_to_3).get_normal();
  1634. planeNormal = vector_3(planeNormal.x, planeNormal.y, abs(planeNormal.z));
  1635. plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1636. vector_3 corrected_position = plan_get_position();
  1637. current_position[X_AXIS] = corrected_position.x;
  1638. current_position[Y_AXIS] = corrected_position.y;
  1639. current_position[Z_AXIS] = corrected_position.z;
  1640. // put the bed at 0 so we don't go below it.
  1641. current_position[Z_AXIS] = cs.zprobe_zoffset;
  1642. plan_set_position_curposXYZE();
  1643. }
  1644. #endif // AUTO_BED_LEVELING_GRID
  1645. static void run_z_probe() {
  1646. plan_bed_level_matrix.set_to_identity();
  1647. feedrate = homing_feedrate[Z_AXIS];
  1648. // move down until you find the bed
  1649. float zPosition = -10;
  1650. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1651. st_synchronize();
  1652. // we have to let the planner know where we are right now as it is not where we said to go.
  1653. zPosition = st_get_position_mm(Z_AXIS);
  1654. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS]);
  1655. // move up the retract distance
  1656. zPosition += home_retract_mm(Z_AXIS);
  1657. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1658. st_synchronize();
  1659. // move back down slowly to find bed
  1660. feedrate = homing_feedrate[Z_AXIS]/4;
  1661. zPosition -= home_retract_mm(Z_AXIS) * 2;
  1662. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1663. st_synchronize();
  1664. current_position[Z_AXIS] = st_get_position_mm(Z_AXIS);
  1665. // make sure the planner knows where we are as it may be a bit different than we last said to move to
  1666. plan_set_position_curposXYZE();
  1667. }
  1668. static void do_blocking_move_to(float x, float y, float z) {
  1669. float oldFeedRate = feedrate;
  1670. feedrate = homing_feedrate[Z_AXIS];
  1671. current_position[Z_AXIS] = z;
  1672. plan_buffer_line_curposXYZE(feedrate/60, active_extruder);
  1673. st_synchronize();
  1674. feedrate = XY_TRAVEL_SPEED;
  1675. current_position[X_AXIS] = x;
  1676. current_position[Y_AXIS] = y;
  1677. plan_buffer_line_curposXYZE(feedrate/60, active_extruder);
  1678. st_synchronize();
  1679. feedrate = oldFeedRate;
  1680. }
  1681. static void do_blocking_move_relative(float offset_x, float offset_y, float offset_z) {
  1682. do_blocking_move_to(current_position[X_AXIS] + offset_x, current_position[Y_AXIS] + offset_y, current_position[Z_AXIS] + offset_z);
  1683. }
  1684. /// Probe bed height at position (x,y), returns the measured z value
  1685. static float probe_pt(float x, float y, float z_before) {
  1686. // move to right place
  1687. do_blocking_move_to(current_position[X_AXIS], current_position[Y_AXIS], z_before);
  1688. do_blocking_move_to(x - X_PROBE_OFFSET_FROM_EXTRUDER, y - Y_PROBE_OFFSET_FROM_EXTRUDER, current_position[Z_AXIS]);
  1689. run_z_probe();
  1690. float measured_z = current_position[Z_AXIS];
  1691. SERIAL_PROTOCOLRPGM(_T(MSG_BED));
  1692. SERIAL_PROTOCOLPGM(" x: ");
  1693. SERIAL_PROTOCOL(x);
  1694. SERIAL_PROTOCOLPGM(" y: ");
  1695. SERIAL_PROTOCOL(y);
  1696. SERIAL_PROTOCOLPGM(" z: ");
  1697. SERIAL_PROTOCOL(measured_z);
  1698. SERIAL_PROTOCOLPGM("\n");
  1699. return measured_z;
  1700. }
  1701. #endif // #ifdef ENABLE_AUTO_BED_LEVELING
  1702. #ifdef LIN_ADVANCE
  1703. /**
  1704. * M900: Set and/or Get advance K factor
  1705. *
  1706. * K<factor> Set advance K factor
  1707. */
  1708. inline void gcode_M900() {
  1709. float newK = code_seen('K') ? code_value_float() : -2;
  1710. #ifdef LA_NOCOMPAT
  1711. if (newK >= 0 && newK < LA_K_MAX)
  1712. extruder_advance_K = newK;
  1713. else
  1714. SERIAL_ECHOLNPGM("K out of allowed range!");
  1715. #else
  1716. if (newK == 0)
  1717. {
  1718. extruder_advance_K = 0;
  1719. la10c_reset();
  1720. }
  1721. else
  1722. {
  1723. newK = la10c_value(newK);
  1724. if (newK < 0)
  1725. SERIAL_ECHOLNPGM("K out of allowed range!");
  1726. else
  1727. extruder_advance_K = newK;
  1728. }
  1729. #endif
  1730. SERIAL_ECHO_START;
  1731. SERIAL_ECHOPGM("Advance K=");
  1732. SERIAL_ECHOLN(extruder_advance_K);
  1733. }
  1734. #endif // LIN_ADVANCE
  1735. bool check_commands() {
  1736. bool end_command_found = false;
  1737. while (buflen)
  1738. {
  1739. if ((code_seen_P(PSTR("M84"))) || (code_seen_P(PSTR("M 84")))) end_command_found = true;
  1740. if (!cmdbuffer_front_already_processed)
  1741. cmdqueue_pop_front();
  1742. cmdbuffer_front_already_processed = false;
  1743. }
  1744. return end_command_found;
  1745. }
  1746. /// @brief Safely move Z-axis by distance delta (mm)
  1747. /// @param delta travel distance in mm
  1748. /// @returns The actual travel distance in mm. Endstop may limit the requested move.
  1749. float raise_z(float delta)
  1750. {
  1751. float travel_z = current_position[Z_AXIS];
  1752. // Prepare to move Z axis
  1753. current_position[Z_AXIS] += delta;
  1754. #if defined(Z_MIN_PIN) && (Z_MIN_PIN > -1) && !defined(DEBUG_DISABLE_ZMINLIMIT)
  1755. bool z_min_endstop = (READ(Z_MIN_PIN) != Z_MIN_ENDSTOP_INVERTING);
  1756. #else
  1757. bool z_min_endstop = false;
  1758. #endif
  1759. if (axis_known_position[Z_AXIS] || z_min_endstop)
  1760. {
  1761. // current position is known or very low, it's safe to raise Z
  1762. clamp_to_software_endstops(current_position);
  1763. plan_buffer_line_curposXYZE(max_feedrate[Z_AXIS]);
  1764. st_synchronize();
  1765. // Get the final travel distance
  1766. travel_z = current_position[Z_AXIS] - travel_z;
  1767. } else {
  1768. // ensure Z is powered in normal mode to overcome initial load
  1769. enable_z();
  1770. st_synchronize();
  1771. // rely on crashguard to limit damage
  1772. bool z_endstop_enabled = enable_z_endstop(true);
  1773. #ifdef TMC2130
  1774. tmc2130_home_enter(Z_AXIS_MASK);
  1775. #endif //TMC2130
  1776. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 60);
  1777. st_synchronize();
  1778. // Get the final travel distance
  1779. travel_z = st_get_position_mm(Z_AXIS) - travel_z;
  1780. #ifdef TMC2130
  1781. if (endstop_z_hit_on_purpose())
  1782. {
  1783. // not necessarily exact, but will avoid further vertical moves
  1784. current_position[Z_AXIS] = max_pos[Z_AXIS];
  1785. plan_set_position_curposXYZE();
  1786. }
  1787. tmc2130_home_exit();
  1788. #endif //TMC2130
  1789. enable_z_endstop(z_endstop_enabled);
  1790. }
  1791. return travel_z;
  1792. }
  1793. // raise_z_above: slowly raise Z to the requested height
  1794. //
  1795. // contrarily to a simple move, this function will carefully plan a move
  1796. // when the current Z position is unknown. In such cases, stallguard is
  1797. // enabled and will prevent prolonged pushing against the Z tops
  1798. void raise_z_above(float target)
  1799. {
  1800. if (current_position[Z_AXIS] >= target)
  1801. return;
  1802. // Use absolute value in case the current position is unknown
  1803. raise_z(fabs(current_position[Z_AXIS] - target));
  1804. }
  1805. #ifdef TMC2130
  1806. bool calibrate_z_auto()
  1807. {
  1808. //lcd_display_message_fullscreen_P(_T(MSG_CALIBRATE_Z_AUTO));
  1809. lcd_clear();
  1810. lcd_puts_at_P(0, 1, _T(MSG_CALIBRATE_Z_AUTO));
  1811. bool endstops_enabled = enable_endstops(true);
  1812. int axis_up_dir = -home_dir(Z_AXIS);
  1813. tmc2130_home_enter(Z_AXIS_MASK);
  1814. current_position[Z_AXIS] = 0;
  1815. plan_set_position_curposXYZE();
  1816. set_destination_to_current();
  1817. destination[Z_AXIS] += (1.1 * max_length(Z_AXIS) * axis_up_dir);
  1818. feedrate = homing_feedrate[Z_AXIS];
  1819. plan_buffer_line_destinationXYZE(feedrate / 60);
  1820. st_synchronize();
  1821. // current_position[axis] = 0;
  1822. // plan_set_position_curposXYZE();
  1823. tmc2130_home_exit();
  1824. enable_endstops(false);
  1825. current_position[Z_AXIS] = 0;
  1826. plan_set_position_curposXYZE();
  1827. set_destination_to_current();
  1828. destination[Z_AXIS] += 10 * axis_up_dir; //10mm up
  1829. feedrate = homing_feedrate[Z_AXIS] / 2;
  1830. plan_buffer_line_destinationXYZE(feedrate / 60);
  1831. st_synchronize();
  1832. enable_endstops(endstops_enabled);
  1833. if (PRINTER_TYPE == PRINTER_MK3) {
  1834. current_position[Z_AXIS] = Z_MAX_POS + 2.0;
  1835. }
  1836. else {
  1837. current_position[Z_AXIS] = Z_MAX_POS + 9.0;
  1838. }
  1839. plan_set_position_curposXYZE();
  1840. return true;
  1841. }
  1842. #endif //TMC2130
  1843. #ifdef TMC2130
  1844. static void check_Z_crash(void)
  1845. {
  1846. if (!READ(Z_TMC2130_DIAG)) { //Z crash
  1847. FORCE_HIGH_POWER_END;
  1848. current_position[Z_AXIS] = 0;
  1849. plan_set_position_curposXYZE();
  1850. current_position[Z_AXIS] += MESH_HOME_Z_SEARCH;
  1851. plan_buffer_line_curposXYZE(max_feedrate[Z_AXIS]);
  1852. st_synchronize();
  1853. kill(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  1854. }
  1855. }
  1856. #endif //TMC2130
  1857. #ifdef TMC2130
  1858. void homeaxis(uint8_t axis, uint8_t cnt, uint8_t* pstep)
  1859. #else
  1860. void homeaxis(uint8_t axis, uint8_t cnt)
  1861. #endif //TMC2130
  1862. {
  1863. bool endstops_enabled = enable_endstops(true); //RP: endstops should be allways enabled durring homing
  1864. #define HOMEAXIS_DO(LETTER) \
  1865. ((LETTER##_MIN_PIN > -1 && LETTER##_HOME_DIR==-1) || (LETTER##_MAX_PIN > -1 && LETTER##_HOME_DIR==1))
  1866. if ((axis==X_AXIS)?HOMEAXIS_DO(X):(axis==Y_AXIS)?HOMEAXIS_DO(Y):0)
  1867. {
  1868. int axis_home_dir = home_dir(axis);
  1869. feedrate = homing_feedrate[axis];
  1870. #ifdef TMC2130
  1871. tmc2130_home_enter(X_AXIS_MASK << axis);
  1872. #endif //TMC2130
  1873. // Move away a bit, so that the print head does not touch the end position,
  1874. // and the following movement to endstop has a chance to achieve the required velocity
  1875. // for the stall guard to work.
  1876. current_position[axis] = 0;
  1877. plan_set_position_curposXYZE();
  1878. set_destination_to_current();
  1879. // destination[axis] = 11.f;
  1880. destination[axis] = -3.f * axis_home_dir;
  1881. plan_buffer_line_destinationXYZE(feedrate/60);
  1882. st_synchronize();
  1883. // Move away from the possible collision with opposite endstop with the collision detection disabled.
  1884. endstops_hit_on_purpose();
  1885. enable_endstops(false);
  1886. current_position[axis] = 0;
  1887. plan_set_position_curposXYZE();
  1888. destination[axis] = 1. * axis_home_dir;
  1889. plan_buffer_line_destinationXYZE(feedrate/60);
  1890. st_synchronize();
  1891. // Now continue to move up to the left end stop with the collision detection enabled.
  1892. enable_endstops(true);
  1893. destination[axis] = 1.1 * axis_home_dir * max_length(axis);
  1894. plan_buffer_line_destinationXYZE(feedrate/60);
  1895. st_synchronize();
  1896. for (uint8_t i = 0; i < cnt; i++)
  1897. {
  1898. // Move away from the collision to a known distance from the left end stop with the collision detection disabled.
  1899. endstops_hit_on_purpose();
  1900. enable_endstops(false);
  1901. current_position[axis] = 0;
  1902. plan_set_position_curposXYZE();
  1903. destination[axis] = -10.f * axis_home_dir;
  1904. plan_buffer_line_destinationXYZE(feedrate/60);
  1905. st_synchronize();
  1906. endstops_hit_on_purpose();
  1907. // Now move left up to the collision, this time with a repeatable velocity.
  1908. enable_endstops(true);
  1909. destination[axis] = 11.f * axis_home_dir;
  1910. #ifdef TMC2130
  1911. feedrate = homing_feedrate[axis];
  1912. #else //TMC2130
  1913. feedrate = homing_feedrate[axis] / 2;
  1914. #endif //TMC2130
  1915. plan_buffer_line_destinationXYZE(feedrate/60);
  1916. st_synchronize();
  1917. #ifdef TMC2130
  1918. uint16_t mscnt = tmc2130_rd_MSCNT(axis);
  1919. if (pstep) pstep[i] = mscnt >> 4;
  1920. printf_P(PSTR("%3d step=%2d mscnt=%4d\n"), i, mscnt >> 4, mscnt);
  1921. #endif //TMC2130
  1922. }
  1923. endstops_hit_on_purpose();
  1924. enable_endstops(false);
  1925. #ifdef TMC2130
  1926. uint8_t orig = tmc2130_home_origin[axis];
  1927. uint8_t back = tmc2130_home_bsteps[axis];
  1928. if (tmc2130_home_enabled && (orig <= 63))
  1929. {
  1930. tmc2130_goto_step(axis, orig, 2, 1000, tmc2130_get_res(axis));
  1931. if (back > 0)
  1932. tmc2130_do_steps(axis, back, -axis_home_dir, 1000);
  1933. }
  1934. else
  1935. tmc2130_do_steps(axis, 8, -axis_home_dir, 1000);
  1936. tmc2130_home_exit();
  1937. #endif //TMC2130
  1938. axis_is_at_home(axis);
  1939. axis_known_position[axis] = true;
  1940. // Move from minimum
  1941. #ifdef TMC2130
  1942. float dist = - axis_home_dir * 0.01f * tmc2130_home_fsteps[axis];
  1943. #else //TMC2130
  1944. float dist = - axis_home_dir * 0.01f * 64;
  1945. #endif //TMC2130
  1946. current_position[axis] -= dist;
  1947. plan_set_position_curposXYZE();
  1948. current_position[axis] += dist;
  1949. destination[axis] = current_position[axis];
  1950. plan_buffer_line_destinationXYZE(0.5f*feedrate/60);
  1951. st_synchronize();
  1952. feedrate = 0.0;
  1953. }
  1954. else if ((axis==Z_AXIS)?HOMEAXIS_DO(Z):0)
  1955. {
  1956. #ifdef TMC2130
  1957. FORCE_HIGH_POWER_START;
  1958. #endif
  1959. int axis_home_dir = home_dir(axis);
  1960. current_position[axis] = 0;
  1961. plan_set_position_curposXYZE();
  1962. destination[axis] = 1.5 * max_length(axis) * axis_home_dir;
  1963. feedrate = homing_feedrate[axis];
  1964. plan_buffer_line_destinationXYZE(feedrate/60);
  1965. st_synchronize();
  1966. #ifdef TMC2130
  1967. check_Z_crash();
  1968. #endif //TMC2130
  1969. current_position[axis] = 0;
  1970. plan_set_position_curposXYZE();
  1971. destination[axis] = -home_retract_mm(axis) * axis_home_dir;
  1972. plan_buffer_line_destinationXYZE(feedrate/60);
  1973. st_synchronize();
  1974. destination[axis] = 2*home_retract_mm(axis) * axis_home_dir;
  1975. feedrate = homing_feedrate[axis]/2 ;
  1976. plan_buffer_line_destinationXYZE(feedrate/60);
  1977. st_synchronize();
  1978. #ifdef TMC2130
  1979. check_Z_crash();
  1980. #endif //TMC2130
  1981. axis_is_at_home(axis);
  1982. destination[axis] = current_position[axis];
  1983. feedrate = 0.0;
  1984. endstops_hit_on_purpose();
  1985. axis_known_position[axis] = true;
  1986. #ifdef TMC2130
  1987. FORCE_HIGH_POWER_END;
  1988. #endif
  1989. }
  1990. enable_endstops(endstops_enabled);
  1991. }
  1992. /**/
  1993. void home_xy()
  1994. {
  1995. set_destination_to_current();
  1996. homeaxis(X_AXIS);
  1997. homeaxis(Y_AXIS);
  1998. plan_set_position_curposXYZE();
  1999. endstops_hit_on_purpose();
  2000. }
  2001. void refresh_cmd_timeout(void)
  2002. {
  2003. previous_millis_cmd.start();
  2004. }
  2005. #ifdef FWRETRACT
  2006. void retract(bool retracting, bool swapretract = false) {
  2007. // Perform FW retraction, just if needed, but behave as if the move has never took place in
  2008. // order to keep E/Z coordinates unchanged. This is done by manipulating the internal planner
  2009. // position, which requires a sync
  2010. if(retracting && !retracted[active_extruder]) {
  2011. st_synchronize();
  2012. set_destination_to_current();
  2013. current_position[E_AXIS]+=(swapretract?retract_length_swap:cs.retract_length)*float(extrudemultiply)*0.01f;
  2014. plan_set_e_position(current_position[E_AXIS]);
  2015. float oldFeedrate = feedrate;
  2016. feedrate=cs.retract_feedrate*60;
  2017. retracted[active_extruder]=true;
  2018. prepare_move();
  2019. if(cs.retract_zlift) {
  2020. st_synchronize();
  2021. current_position[Z_AXIS]-=cs.retract_zlift;
  2022. plan_set_position_curposXYZE();
  2023. prepare_move();
  2024. }
  2025. feedrate = oldFeedrate;
  2026. } else if(!retracting && retracted[active_extruder]) {
  2027. st_synchronize();
  2028. set_destination_to_current();
  2029. float oldFeedrate = feedrate;
  2030. feedrate=cs.retract_recover_feedrate*60;
  2031. if(cs.retract_zlift) {
  2032. current_position[Z_AXIS]+=cs.retract_zlift;
  2033. plan_set_position_curposXYZE();
  2034. prepare_move();
  2035. st_synchronize();
  2036. }
  2037. current_position[E_AXIS]-=(swapretract?(retract_length_swap+retract_recover_length_swap):(cs.retract_length+cs.retract_recover_length))*float(extrudemultiply)*0.01f;
  2038. plan_set_e_position(current_position[E_AXIS]);
  2039. retracted[active_extruder]=false;
  2040. prepare_move();
  2041. feedrate = oldFeedrate;
  2042. }
  2043. } //retract
  2044. #endif //FWRETRACT
  2045. #ifdef TMC2130
  2046. void force_high_power_mode(bool start_high_power_section) {
  2047. #ifdef PSU_Delta
  2048. if (start_high_power_section == true) enable_force_z();
  2049. #endif //PSU_Delta
  2050. uint8_t silent;
  2051. silent = eeprom_read_byte((uint8_t*)EEPROM_SILENT);
  2052. if (silent == 1) {
  2053. //we are in silent mode, set to normal mode to enable crash detection
  2054. // Wait for the planner queue to drain and for the stepper timer routine to reach an idle state.
  2055. st_synchronize();
  2056. cli();
  2057. tmc2130_mode = (start_high_power_section == true) ? TMC2130_MODE_NORMAL : TMC2130_MODE_SILENT;
  2058. update_mode_profile();
  2059. tmc2130_init(TMCInitParams(FarmOrUserECool()));
  2060. // We may have missed a stepper timer interrupt due to the time spent in the tmc2130_init() routine.
  2061. // Be safe than sorry, reset the stepper timer before re-enabling interrupts.
  2062. st_reset_timer();
  2063. sei();
  2064. }
  2065. }
  2066. #endif //TMC2130
  2067. void gcode_M105(uint8_t extruder)
  2068. {
  2069. #if defined(TEMP_0_PIN) && TEMP_0_PIN > -1
  2070. SERIAL_PROTOCOLPGM("T:");
  2071. SERIAL_PROTOCOL_F(degHotend(extruder),1);
  2072. SERIAL_PROTOCOLPGM(" /");
  2073. SERIAL_PROTOCOL_F(degTargetHotend(extruder),1);
  2074. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  2075. SERIAL_PROTOCOLPGM(" B:");
  2076. SERIAL_PROTOCOL_F(degBed(),1);
  2077. SERIAL_PROTOCOLPGM(" /");
  2078. SERIAL_PROTOCOL_F(degTargetBed(),1);
  2079. #endif //TEMP_BED_PIN
  2080. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  2081. SERIAL_PROTOCOLPGM(" T");
  2082. SERIAL_PROTOCOL(cur_extruder);
  2083. SERIAL_PROTOCOL(':');
  2084. SERIAL_PROTOCOL_F(degHotend(cur_extruder),1);
  2085. SERIAL_PROTOCOLPGM(" /");
  2086. SERIAL_PROTOCOL_F(degTargetHotend(cur_extruder),1);
  2087. }
  2088. #else
  2089. SERIAL_ERROR_START;
  2090. SERIAL_ERRORLNRPGM(_n("No thermistors - no temperature"));////MSG_ERR_NO_THERMISTORS
  2091. #endif
  2092. SERIAL_PROTOCOLPGM(" @:");
  2093. #ifdef EXTRUDER_WATTS
  2094. SERIAL_PROTOCOL((EXTRUDER_WATTS * getHeaterPower(tmp_extruder))/127);
  2095. SERIAL_PROTOCOLPGM("W");
  2096. #else
  2097. SERIAL_PROTOCOL(getHeaterPower(extruder));
  2098. #endif
  2099. SERIAL_PROTOCOLPGM(" B@:");
  2100. #ifdef BED_WATTS
  2101. SERIAL_PROTOCOL((BED_WATTS * getHeaterPower(-1))/127);
  2102. SERIAL_PROTOCOLPGM("W");
  2103. #else
  2104. SERIAL_PROTOCOL(getHeaterPower(-1));
  2105. #endif
  2106. #ifdef PINDA_THERMISTOR
  2107. SERIAL_PROTOCOLPGM(" P:");
  2108. SERIAL_PROTOCOL_F(current_temperature_pinda,1);
  2109. #endif //PINDA_THERMISTOR
  2110. #ifdef AMBIENT_THERMISTOR
  2111. SERIAL_PROTOCOLPGM(" A:");
  2112. SERIAL_PROTOCOL_F(current_temperature_ambient,1);
  2113. #endif //AMBIENT_THERMISTOR
  2114. #ifdef SHOW_TEMP_ADC_VALUES
  2115. {
  2116. float raw = 0.0;
  2117. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  2118. SERIAL_PROTOCOLPGM(" ADC B:");
  2119. SERIAL_PROTOCOL_F(degBed(),1);
  2120. SERIAL_PROTOCOLPGM("C->");
  2121. raw = rawBedTemp();
  2122. SERIAL_PROTOCOL_F(raw/OVERSAMPLENR,5);
  2123. SERIAL_PROTOCOLPGM(" Rb->");
  2124. SERIAL_PROTOCOL_F(100 * (1 + (PtA * (raw/OVERSAMPLENR)) + (PtB * sq((raw/OVERSAMPLENR)))), 5);
  2125. SERIAL_PROTOCOLPGM(" Rxb->");
  2126. SERIAL_PROTOCOL_F(raw, 5);
  2127. #endif
  2128. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  2129. SERIAL_PROTOCOLPGM(" T");
  2130. SERIAL_PROTOCOL(cur_extruder);
  2131. SERIAL_PROTOCOLPGM(":");
  2132. SERIAL_PROTOCOL_F(degHotend(cur_extruder),1);
  2133. SERIAL_PROTOCOLPGM("C->");
  2134. raw = rawHotendTemp(cur_extruder);
  2135. SERIAL_PROTOCOL_F(raw/OVERSAMPLENR,5);
  2136. SERIAL_PROTOCOLPGM(" Rt");
  2137. SERIAL_PROTOCOL(cur_extruder);
  2138. SERIAL_PROTOCOLPGM("->");
  2139. SERIAL_PROTOCOL_F(100 * (1 + (PtA * (raw/OVERSAMPLENR)) + (PtB * sq((raw/OVERSAMPLENR)))), 5);
  2140. SERIAL_PROTOCOLPGM(" Rx");
  2141. SERIAL_PROTOCOL(cur_extruder);
  2142. SERIAL_PROTOCOLPGM("->");
  2143. SERIAL_PROTOCOL_F(raw, 5);
  2144. }
  2145. }
  2146. #endif
  2147. SERIAL_PROTOCOLLN();
  2148. }
  2149. #ifdef TMC2130
  2150. static void gcode_G28(bool home_x_axis, long home_x_value, bool home_y_axis, long home_y_value, bool home_z_axis, long home_z_value, bool calib, bool without_mbl)
  2151. #else
  2152. static void gcode_G28(bool home_x_axis, long home_x_value, bool home_y_axis, long home_y_value, bool home_z_axis, long home_z_value, bool without_mbl)
  2153. #endif //TMC2130
  2154. {
  2155. // Flag for the display update routine and to disable the print cancelation during homing.
  2156. st_synchronize();
  2157. homing_flag = true;
  2158. #if 0
  2159. SERIAL_ECHOPGM("G28, initial "); print_world_coordinates();
  2160. SERIAL_ECHOPGM("G28, initial "); print_physical_coordinates();
  2161. #endif
  2162. // Which axes should be homed?
  2163. bool home_x = home_x_axis;
  2164. bool home_y = home_y_axis;
  2165. bool home_z = home_z_axis;
  2166. // Either all X,Y,Z codes are present, or none of them.
  2167. bool home_all_axes = home_x == home_y && home_x == home_z;
  2168. if (home_all_axes)
  2169. // No X/Y/Z code provided means to home all axes.
  2170. home_x = home_y = home_z = true;
  2171. //if we are homing all axes, first move z higher to protect heatbed/steel sheet
  2172. if (home_all_axes) {
  2173. raise_z_above(MESH_HOME_Z_SEARCH);
  2174. }
  2175. #ifdef ENABLE_AUTO_BED_LEVELING
  2176. plan_bed_level_matrix.set_to_identity(); //Reset the plane ("erase" all leveling data)
  2177. #endif //ENABLE_AUTO_BED_LEVELING
  2178. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  2179. // the planner will not perform any adjustments in the XY plane.
  2180. // Wait for the motors to stop and update the current position with the absolute values.
  2181. world2machine_revert_to_uncorrected();
  2182. // For mesh bed leveling deactivate the matrix temporarily.
  2183. // It is necessary to disable the bed leveling for the X and Y homing moves, so that the move is performed
  2184. // in a single axis only.
  2185. // In case of re-homing the X or Y axes only, the mesh bed leveling is restored after G28.
  2186. #ifdef MESH_BED_LEVELING
  2187. uint8_t mbl_was_active = mbl.active;
  2188. mbl.active = 0;
  2189. current_position[Z_AXIS] = st_get_position_mm(Z_AXIS);
  2190. #endif
  2191. // Reset baby stepping to zero, if the babystepping has already been loaded before.
  2192. if (home_z)
  2193. babystep_undo();
  2194. int l_feedmultiply = setup_for_endstop_move();
  2195. set_destination_to_current();
  2196. feedrate = 0.0;
  2197. #if Z_HOME_DIR > 0 // If homing away from BED do Z first
  2198. if(home_z)
  2199. homeaxis(Z_AXIS);
  2200. #endif
  2201. #ifdef QUICK_HOME
  2202. // In the quick mode, if both x and y are to be homed, a diagonal move will be performed initially.
  2203. if(home_x && home_y) //first diagonal move
  2204. {
  2205. current_position[X_AXIS] = 0;current_position[Y_AXIS] = 0;
  2206. uint8_t x_axis_home_dir = home_dir(X_AXIS);
  2207. plan_set_position_curposXYZE();
  2208. destination[X_AXIS] = 1.5 * max_length(X_AXIS) * x_axis_home_dir;destination[Y_AXIS] = 1.5 * max_length(Y_AXIS) * home_dir(Y_AXIS);
  2209. feedrate = homing_feedrate[X_AXIS];
  2210. if(homing_feedrate[Y_AXIS]<feedrate)
  2211. feedrate = homing_feedrate[Y_AXIS];
  2212. if (max_length(X_AXIS) > max_length(Y_AXIS)) {
  2213. feedrate *= sqrt(pow(max_length(Y_AXIS) / max_length(X_AXIS), 2) + 1);
  2214. } else {
  2215. feedrate *= sqrt(pow(max_length(X_AXIS) / max_length(Y_AXIS), 2) + 1);
  2216. }
  2217. plan_buffer_line_destinationXYZE(feedrate/60);
  2218. st_synchronize();
  2219. axis_is_at_home(X_AXIS);
  2220. axis_is_at_home(Y_AXIS);
  2221. plan_set_position_curposXYZE();
  2222. destination[X_AXIS] = current_position[X_AXIS];
  2223. destination[Y_AXIS] = current_position[Y_AXIS];
  2224. plan_buffer_line_destinationXYZE(feedrate/60);
  2225. feedrate = 0.0;
  2226. st_synchronize();
  2227. endstops_hit_on_purpose();
  2228. current_position[X_AXIS] = destination[X_AXIS];
  2229. current_position[Y_AXIS] = destination[Y_AXIS];
  2230. current_position[Z_AXIS] = destination[Z_AXIS];
  2231. }
  2232. #endif /* QUICK_HOME */
  2233. #ifdef TMC2130
  2234. if(home_x)
  2235. {
  2236. if (!calib)
  2237. homeaxis(X_AXIS);
  2238. else
  2239. tmc2130_home_calibrate(X_AXIS);
  2240. }
  2241. if(home_y)
  2242. {
  2243. if (!calib)
  2244. homeaxis(Y_AXIS);
  2245. else
  2246. tmc2130_home_calibrate(Y_AXIS);
  2247. }
  2248. #else //TMC2130
  2249. if(home_x) homeaxis(X_AXIS);
  2250. if(home_y) homeaxis(Y_AXIS);
  2251. #endif //TMC2130
  2252. if(home_x_axis && home_x_value != 0)
  2253. current_position[X_AXIS]=home_x_value+cs.add_homing[X_AXIS];
  2254. if(home_y_axis && home_y_value != 0)
  2255. current_position[Y_AXIS]=home_y_value+cs.add_homing[Y_AXIS];
  2256. #if Z_HOME_DIR < 0 // If homing towards BED do Z last
  2257. #ifndef Z_SAFE_HOMING
  2258. if(home_z) {
  2259. #if defined (Z_RAISE_BEFORE_HOMING) && (Z_RAISE_BEFORE_HOMING > 0)
  2260. raise_z_above(Z_RAISE_BEFORE_HOMING);
  2261. #endif // defined (Z_RAISE_BEFORE_HOMING) && (Z_RAISE_BEFORE_HOMING > 0)
  2262. #ifdef MESH_BED_LEVELING // If Mesh bed leveling, move X&Y to safe position for home
  2263. raise_z_above(MESH_HOME_Z_SEARCH);
  2264. if (!axis_known_position[X_AXIS]) homeaxis(X_AXIS);
  2265. if (!axis_known_position[Y_AXIS]) homeaxis(Y_AXIS);
  2266. // 1st mesh bed leveling measurement point, corrected.
  2267. world2machine_initialize();
  2268. world2machine(pgm_read_float(bed_ref_points_4), pgm_read_float(bed_ref_points_4+1), destination[X_AXIS], destination[Y_AXIS]);
  2269. world2machine_reset();
  2270. if (destination[Y_AXIS] < Y_MIN_POS)
  2271. destination[Y_AXIS] = Y_MIN_POS;
  2272. feedrate = homing_feedrate[X_AXIS] / 20;
  2273. enable_endstops(false);
  2274. #ifdef DEBUG_BUILD
  2275. SERIAL_ECHOLNPGM("plan_set_position()");
  2276. MYSERIAL.println(current_position[X_AXIS]);MYSERIAL.println(current_position[Y_AXIS]);
  2277. MYSERIAL.println(current_position[Z_AXIS]);MYSERIAL.println(current_position[E_AXIS]);
  2278. #endif
  2279. plan_set_position_curposXYZE();
  2280. #ifdef DEBUG_BUILD
  2281. SERIAL_ECHOLNPGM("plan_buffer_line()");
  2282. MYSERIAL.println(destination[X_AXIS]);MYSERIAL.println(destination[Y_AXIS]);
  2283. MYSERIAL.println(destination[Z_AXIS]);MYSERIAL.println(destination[E_AXIS]);
  2284. MYSERIAL.println(feedrate);MYSERIAL.println(active_extruder);
  2285. #endif
  2286. plan_buffer_line_destinationXYZE(feedrate);
  2287. st_synchronize();
  2288. current_position[X_AXIS] = destination[X_AXIS];
  2289. current_position[Y_AXIS] = destination[Y_AXIS];
  2290. enable_endstops(true);
  2291. endstops_hit_on_purpose();
  2292. homeaxis(Z_AXIS);
  2293. #else // MESH_BED_LEVELING
  2294. homeaxis(Z_AXIS);
  2295. #endif // MESH_BED_LEVELING
  2296. }
  2297. #else // defined(Z_SAFE_HOMING): Z Safe mode activated.
  2298. if(home_all_axes) {
  2299. destination[X_AXIS] = round(Z_SAFE_HOMING_X_POINT - X_PROBE_OFFSET_FROM_EXTRUDER);
  2300. destination[Y_AXIS] = round(Z_SAFE_HOMING_Y_POINT - Y_PROBE_OFFSET_FROM_EXTRUDER);
  2301. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  2302. feedrate = XY_TRAVEL_SPEED/60;
  2303. current_position[Z_AXIS] = 0;
  2304. plan_set_position_curposXYZE();
  2305. plan_buffer_line_destinationXYZE(feedrate);
  2306. st_synchronize();
  2307. current_position[X_AXIS] = destination[X_AXIS];
  2308. current_position[Y_AXIS] = destination[Y_AXIS];
  2309. homeaxis(Z_AXIS);
  2310. }
  2311. // Let's see if X and Y are homed and probe is inside bed area.
  2312. if(home_z) {
  2313. if ( (axis_known_position[X_AXIS]) && (axis_known_position[Y_AXIS]) \
  2314. && (current_position[X_AXIS]+X_PROBE_OFFSET_FROM_EXTRUDER >= X_MIN_POS) \
  2315. && (current_position[X_AXIS]+X_PROBE_OFFSET_FROM_EXTRUDER <= X_MAX_POS) \
  2316. && (current_position[Y_AXIS]+Y_PROBE_OFFSET_FROM_EXTRUDER >= Y_MIN_POS) \
  2317. && (current_position[Y_AXIS]+Y_PROBE_OFFSET_FROM_EXTRUDER <= Y_MAX_POS)) {
  2318. current_position[Z_AXIS] = 0;
  2319. plan_set_position_curposXYZE();
  2320. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  2321. feedrate = max_feedrate[Z_AXIS];
  2322. plan_buffer_line_destinationXYZE(feedrate);
  2323. st_synchronize();
  2324. homeaxis(Z_AXIS);
  2325. } else if (!((axis_known_position[X_AXIS]) && (axis_known_position[Y_AXIS]))) {
  2326. LCD_MESSAGERPGM(MSG_POSITION_UNKNOWN);
  2327. SERIAL_ECHO_START;
  2328. SERIAL_ECHOLNRPGM(MSG_POSITION_UNKNOWN);
  2329. } else {
  2330. LCD_MESSAGERPGM(MSG_ZPROBE_OUT);
  2331. SERIAL_ECHO_START;
  2332. SERIAL_ECHOLNRPGM(MSG_ZPROBE_OUT);
  2333. }
  2334. }
  2335. #endif // Z_SAFE_HOMING
  2336. #endif // Z_HOME_DIR < 0
  2337. if(home_z_axis && home_z_value != 0)
  2338. current_position[Z_AXIS]=home_z_value+cs.add_homing[Z_AXIS];
  2339. #ifdef ENABLE_AUTO_BED_LEVELING
  2340. if(home_z)
  2341. current_position[Z_AXIS] += cs.zprobe_zoffset; //Add Z_Probe offset (the distance is negative)
  2342. #endif
  2343. // Set the planner and stepper routine positions.
  2344. // At this point the mesh bed leveling and world2machine corrections are disabled and current_position
  2345. // contains the machine coordinates.
  2346. plan_set_position_curposXYZE();
  2347. clean_up_after_endstop_move(l_feedmultiply);
  2348. endstops_hit_on_purpose();
  2349. // Load the machine correction matrix
  2350. world2machine_initialize();
  2351. // and correct the current_position XY axes to match the transformed coordinate system.
  2352. world2machine_update_current();
  2353. #ifdef MESH_BED_LEVELING
  2354. if (home_x_axis || home_y_axis || without_mbl || home_z_axis)
  2355. {
  2356. if (! home_z && mbl_was_active) {
  2357. // Re-enable the mesh bed leveling if only the X and Y axes were re-homed.
  2358. mbl.active = true;
  2359. // and re-adjust the current logical Z axis with the bed leveling offset applicable at the current XY position.
  2360. current_position[Z_AXIS] -= mbl.get_z(st_get_position_mm(X_AXIS), st_get_position_mm(Y_AXIS));
  2361. }
  2362. }
  2363. #endif
  2364. prusa_statistics(20);
  2365. st_synchronize();
  2366. homing_flag = false;
  2367. #if 0
  2368. SERIAL_ECHOPGM("G28, final "); print_world_coordinates();
  2369. SERIAL_ECHOPGM("G28, final "); print_physical_coordinates();
  2370. SERIAL_ECHOPGM("G28, final "); print_mesh_bed_leveling_table();
  2371. #endif
  2372. }
  2373. static void gcode_G28(bool home_x_axis, bool home_y_axis, bool home_z_axis)
  2374. {
  2375. #ifdef TMC2130
  2376. gcode_G28(home_x_axis, 0, home_y_axis, 0, home_z_axis, 0, false, true);
  2377. #else
  2378. gcode_G28(home_x_axis, 0, home_y_axis, 0, home_z_axis, 0, true);
  2379. #endif //TMC2130
  2380. }
  2381. // G80 - Automatic mesh bed leveling
  2382. static void gcode_G80()
  2383. {
  2384. st_synchronize();
  2385. if (planner_aborted)
  2386. return;
  2387. mesh_bed_leveling_flag = true;
  2388. #ifndef PINDA_THERMISTOR
  2389. static bool run = false; // thermistor-less PINDA temperature compensation is running
  2390. #endif // ndef PINDA_THERMISTOR
  2391. #ifdef SUPPORT_VERBOSITY
  2392. int8_t verbosity_level = 0;
  2393. if (code_seen('V')) {
  2394. // Just 'V' without a number counts as V1.
  2395. char c = strchr_pointer[1];
  2396. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  2397. }
  2398. #endif //SUPPORT_VERBOSITY
  2399. // Firstly check if we know where we are
  2400. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  2401. // We don't know where we are! HOME!
  2402. // Push the commands to the front of the message queue in the reverse order!
  2403. // There shall be always enough space reserved for these commands.
  2404. repeatcommand_front(); // repeat G80 with all its parameters
  2405. enquecommand_front_P(G28W0);
  2406. return;
  2407. }
  2408. uint8_t nMeasPoints = MESH_MEAS_NUM_X_POINTS;
  2409. if (code_seen('N')) {
  2410. nMeasPoints = code_value_uint8();
  2411. if (nMeasPoints != 7) {
  2412. nMeasPoints = 3;
  2413. }
  2414. }
  2415. else {
  2416. nMeasPoints = eeprom_read_byte((uint8_t*)EEPROM_MBL_POINTS_NR);
  2417. }
  2418. uint8_t nProbeRetry = 3;
  2419. if (code_seen('R')) {
  2420. nProbeRetry = code_value_uint8();
  2421. if (nProbeRetry > 10) {
  2422. nProbeRetry = 10;
  2423. }
  2424. }
  2425. else {
  2426. nProbeRetry = eeprom_read_byte((uint8_t*)EEPROM_MBL_PROBE_NR);
  2427. }
  2428. bool magnet_elimination = (eeprom_read_byte((uint8_t*)EEPROM_MBL_MAGNET_ELIMINATION) > 0);
  2429. #ifndef PINDA_THERMISTOR
  2430. if (run == false && eeprom_read_byte((uint8_t *)EEPROM_TEMP_CAL_ACTIVE) && calibration_status_pinda() == true && target_temperature_bed >= 50)
  2431. {
  2432. temp_compensation_start();
  2433. run = true;
  2434. repeatcommand_front(); // repeat G80 with all its parameters
  2435. enquecommand_front_P(G28W0);
  2436. break;
  2437. }
  2438. run = false;
  2439. #endif //PINDA_THERMISTOR
  2440. // Save custom message state, set a new custom message state to display: Calibrating point 9.
  2441. CustomMsg custom_message_type_old = custom_message_type;
  2442. uint8_t custom_message_state_old = custom_message_state;
  2443. custom_message_type = CustomMsg::MeshBedLeveling;
  2444. custom_message_state = (nMeasPoints * nMeasPoints) + 10;
  2445. lcd_update(1);
  2446. mbl.reset(); //reset mesh bed leveling
  2447. // Reset baby stepping to zero, if the babystepping has already been loaded before.
  2448. babystep_undo();
  2449. // Cycle through all points and probe them
  2450. // First move up. During this first movement, the babystepping will be reverted.
  2451. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2452. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 60);
  2453. // The move to the first calibration point.
  2454. current_position[X_AXIS] = BED_X0;
  2455. current_position[Y_AXIS] = BED_Y0;
  2456. #ifdef SUPPORT_VERBOSITY
  2457. if (verbosity_level >= 1)
  2458. {
  2459. bool clamped = world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  2460. clamped ? SERIAL_PROTOCOLPGM("First calibration point clamped.\n") : SERIAL_PROTOCOLPGM("No clamping for first calibration point.\n");
  2461. }
  2462. #else //SUPPORT_VERBOSITY
  2463. world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  2464. #endif //SUPPORT_VERBOSITY
  2465. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  2466. plan_buffer_line_curposXYZE(XY_AXIS_FEEDRATE);
  2467. // Wait until the move is finished.
  2468. st_synchronize();
  2469. if (planner_aborted)
  2470. {
  2471. custom_message_type = custom_message_type_old;
  2472. custom_message_state = custom_message_state_old;
  2473. return;
  2474. }
  2475. uint8_t mesh_point = 0; //index number of calibration point
  2476. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  2477. bool has_z = is_bed_z_jitter_data_valid(); //checks if we have data from Z calibration (offsets of the Z heiths of the 8 calibration points from the first point)
  2478. #ifdef SUPPORT_VERBOSITY
  2479. if (verbosity_level >= 1) {
  2480. has_z ? SERIAL_PROTOCOLPGM("Z jitter data from Z cal. valid.\n") : SERIAL_PROTOCOLPGM("Z jitter data from Z cal. not valid.\n");
  2481. }
  2482. #endif // SUPPORT_VERBOSITY
  2483. int l_feedmultiply = setup_for_endstop_move(false); //save feedrate and feedmultiply, sets feedmultiply to 100
  2484. while (mesh_point != nMeasPoints * nMeasPoints) {
  2485. // Get coords of a measuring point.
  2486. uint8_t ix = mesh_point % nMeasPoints; // from 0 to MESH_NUM_X_POINTS - 1
  2487. uint8_t iy = mesh_point / nMeasPoints;
  2488. /*if (!mbl_point_measurement_valid(ix, iy, nMeasPoints, true)) {
  2489. printf_P(PSTR("Skipping point [%d;%d] \n"), ix, iy);
  2490. custom_message_state--;
  2491. mesh_point++;
  2492. continue; //skip
  2493. }*/
  2494. if (iy & 1) ix = (nMeasPoints - 1) - ix; // Zig zag
  2495. if (nMeasPoints == 7) //if we have 7x7 mesh, compare with Z-calibration for points which are in 3x3 mesh
  2496. {
  2497. has_z = ((ix % 3 == 0) && (iy % 3 == 0)) && is_bed_z_jitter_data_valid();
  2498. }
  2499. float z0 = 0.f;
  2500. if (has_z && (mesh_point > 0)) {
  2501. uint16_t z_offset_u = 0;
  2502. if (nMeasPoints == 7) {
  2503. z_offset_u = eeprom_read_word((uint16_t*)(EEPROM_BED_CALIBRATION_Z_JITTER + 2 * ((ix/3) + iy - 1)));
  2504. }
  2505. else {
  2506. z_offset_u = eeprom_read_word((uint16_t*)(EEPROM_BED_CALIBRATION_Z_JITTER + 2 * (ix + iy * 3 - 1)));
  2507. }
  2508. z0 = mbl.z_values[0][0] + *reinterpret_cast<int16_t*>(&z_offset_u) * 0.01;
  2509. #ifdef SUPPORT_VERBOSITY
  2510. if (verbosity_level >= 1) {
  2511. printf_P(PSTR("Bed leveling, point: %d, calibration Z stored in eeprom: %d, calibration z: %f \n"), mesh_point, z_offset_u, z0);
  2512. }
  2513. #endif // SUPPORT_VERBOSITY
  2514. }
  2515. // Move Z up to MESH_HOME_Z_SEARCH.
  2516. if((ix == 0) && (iy == 0)) current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2517. else current_position[Z_AXIS] += 2.f / nMeasPoints; //use relative movement from Z coordinate where PINDa triggered on previous point. This makes calibration faster.
  2518. float init_z_bckp = current_position[Z_AXIS];
  2519. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  2520. st_synchronize();
  2521. // Move to XY position of the sensor point.
  2522. current_position[X_AXIS] = BED_X(ix, nMeasPoints);
  2523. current_position[Y_AXIS] = BED_Y(iy, nMeasPoints);
  2524. //printf_P(PSTR("[%f;%f]\n"), current_position[X_AXIS], current_position[Y_AXIS]);
  2525. #ifdef SUPPORT_VERBOSITY
  2526. if (verbosity_level >= 1) {
  2527. bool clamped = world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  2528. SERIAL_PROTOCOL(mesh_point);
  2529. clamped ? SERIAL_PROTOCOLPGM(": xy clamped.\n") : SERIAL_PROTOCOLPGM(": no xy clamping\n");
  2530. }
  2531. #else //SUPPORT_VERBOSITY
  2532. world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  2533. #endif // SUPPORT_VERBOSITY
  2534. //printf_P(PSTR("after clamping: [%f;%f]\n"), current_position[X_AXIS], current_position[Y_AXIS]);
  2535. plan_buffer_line_curposXYZE(XY_AXIS_FEEDRATE);
  2536. st_synchronize();
  2537. if (planner_aborted)
  2538. {
  2539. custom_message_type = custom_message_type_old;
  2540. custom_message_state = custom_message_state_old;
  2541. return;
  2542. }
  2543. // Go down until endstop is hit
  2544. const float Z_CALIBRATION_THRESHOLD = 1.f;
  2545. if (!find_bed_induction_sensor_point_z((has_z && mesh_point > 0) ? z0 - Z_CALIBRATION_THRESHOLD : -10.f, nProbeRetry)) { //if we have data from z calibration max allowed difference is 1mm for each point, if we dont have data max difference is 10mm from initial point
  2546. printf_P(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  2547. break;
  2548. }
  2549. if (init_z_bckp - current_position[Z_AXIS] < 0.1f) { //broken cable or initial Z coordinate too low. Go to MESH_HOME_Z_SEARCH and repeat last step (z-probe) again to distinguish between these two cases.
  2550. //printf_P(PSTR("Another attempt! Current Z position: %f\n"), current_position[Z_AXIS]);
  2551. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2552. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  2553. st_synchronize();
  2554. if (!find_bed_induction_sensor_point_z((has_z && mesh_point > 0) ? z0 - Z_CALIBRATION_THRESHOLD : -10.f, nProbeRetry)) { //if we have data from z calibration max allowed difference is 1mm for each point, if we dont have data max difference is 10mm from initial point
  2555. printf_P(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  2556. break;
  2557. }
  2558. if (MESH_HOME_Z_SEARCH - current_position[Z_AXIS] < 0.1f) {
  2559. puts_P(PSTR("Bed leveling failed. Sensor disconnected or cable broken."));
  2560. break;
  2561. }
  2562. }
  2563. if (has_z && fabs(z0 - current_position[Z_AXIS]) > Z_CALIBRATION_THRESHOLD) { //if we have data from z calibration, max. allowed difference is 1mm for each point
  2564. puts_P(PSTR("Bed leveling failed. Sensor triggered too high."));
  2565. break;
  2566. }
  2567. #ifdef SUPPORT_VERBOSITY
  2568. if (verbosity_level >= 10) {
  2569. SERIAL_ECHOPGM("X: ");
  2570. MYSERIAL.print(current_position[X_AXIS], 5);
  2571. SERIAL_ECHOLNPGM("");
  2572. SERIAL_ECHOPGM("Y: ");
  2573. MYSERIAL.print(current_position[Y_AXIS], 5);
  2574. SERIAL_PROTOCOLPGM("\n");
  2575. }
  2576. #endif // SUPPORT_VERBOSITY
  2577. float offset_z = 0;
  2578. #ifdef PINDA_THERMISTOR
  2579. offset_z = temp_compensation_pinda_thermistor_offset(current_temperature_pinda);
  2580. #endif //PINDA_THERMISTOR
  2581. // #ifdef SUPPORT_VERBOSITY
  2582. /* if (verbosity_level >= 1)
  2583. {
  2584. SERIAL_ECHOPGM("mesh bed leveling: ");
  2585. MYSERIAL.print(current_position[Z_AXIS], 5);
  2586. SERIAL_ECHOPGM(" offset: ");
  2587. MYSERIAL.print(offset_z, 5);
  2588. SERIAL_ECHOLNPGM("");
  2589. }*/
  2590. // #endif // SUPPORT_VERBOSITY
  2591. mbl.set_z(ix, iy, current_position[Z_AXIS] - offset_z); //store measured z values z_values[iy][ix] = z - offset_z;
  2592. custom_message_state--;
  2593. mesh_point++;
  2594. lcd_update(1);
  2595. }
  2596. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2597. #ifdef SUPPORT_VERBOSITY
  2598. if (verbosity_level >= 20) {
  2599. SERIAL_ECHOLNPGM("Mesh bed leveling while loop finished.");
  2600. SERIAL_ECHOLNPGM("MESH_HOME_Z_SEARCH: ");
  2601. MYSERIAL.print(current_position[Z_AXIS], 5);
  2602. }
  2603. #endif // SUPPORT_VERBOSITY
  2604. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  2605. st_synchronize();
  2606. if (mesh_point != nMeasPoints * nMeasPoints) {
  2607. Sound_MakeSound(e_SOUND_TYPE_StandardAlert);
  2608. bool bState;
  2609. do { // repeat until Z-leveling o.k.
  2610. lcd_display_message_fullscreen_P(_i("Some problem encountered, Z-leveling enforced ...")); ////MSG_ZLEVELING_ENFORCED c=20 r=4
  2611. #ifdef TMC2130
  2612. lcd_wait_for_click_delay(MSG_BED_LEVELING_FAILED_TIMEOUT);
  2613. calibrate_z_auto(); // Z-leveling (X-assembly stay up!!!)
  2614. #else // TMC2130
  2615. lcd_wait_for_click_delay(0); // ~ no timeout
  2616. lcd_calibrate_z_end_stop_manual(true); // Z-leveling (X-assembly stay up!!!)
  2617. #endif // TMC2130
  2618. // ~ Z-homing (can not be used "G28", because X & Y-homing would have been done before (Z-homing))
  2619. bState=enable_z_endstop(false);
  2620. raise_z(-1);
  2621. enable_z_endstop(true);
  2622. #ifdef TMC2130
  2623. tmc2130_home_enter(Z_AXIS_MASK);
  2624. #endif // TMC2130
  2625. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2626. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2627. st_synchronize();
  2628. #ifdef TMC2130
  2629. tmc2130_home_exit();
  2630. #endif // TMC2130
  2631. enable_z_endstop(bState);
  2632. } while (st_get_position_mm(Z_AXIS) > MESH_HOME_Z_SEARCH); // i.e. Z-leveling not o.k.
  2633. // plan_set_z_position(MESH_HOME_Z_SEARCH); // is not necessary ('do-while' loop always ends at the expected Z-position)
  2634. custom_message_type = custom_message_type_old;
  2635. custom_message_state = custom_message_state_old;
  2636. lcd_update_enable(true); // display / status-line recovery
  2637. gcode_G28(true, true, true); // X & Y & Z-homing (must be after individual Z-homing (problem with spool-holder)!)
  2638. repeatcommand_front(); // re-run (i.e. of "G80")
  2639. return;
  2640. }
  2641. clean_up_after_endstop_move(l_feedmultiply);
  2642. // SERIAL_ECHOLNPGM("clean up finished ");
  2643. #ifndef PINDA_THERMISTOR
  2644. if(eeprom_read_byte((uint8_t *)EEPROM_TEMP_CAL_ACTIVE) && calibration_status_pinda() == true) temp_compensation_apply(); //apply PINDA temperature compensation
  2645. #endif
  2646. babystep_apply(); // Apply Z height correction aka baby stepping before mesh bed leveing gets activated.
  2647. // SERIAL_ECHOLNPGM("babystep applied");
  2648. bool eeprom_bed_correction_valid = eeprom_read_byte((unsigned char*)EEPROM_BED_CORRECTION_VALID) == 1;
  2649. #ifdef SUPPORT_VERBOSITY
  2650. if (verbosity_level >= 1) {
  2651. eeprom_bed_correction_valid ? SERIAL_PROTOCOLPGM("Bed correction data valid\n") : SERIAL_PROTOCOLPGM("Bed correction data not valid\n");
  2652. }
  2653. #endif // SUPPORT_VERBOSITY
  2654. for (uint8_t i = 0; i < 4; ++i) {
  2655. static const char codes[4] PROGMEM = { 'L', 'R', 'F', 'B' };
  2656. static uint8_t *const eep_addresses[4] PROGMEM = {
  2657. (uint8_t*)EEPROM_BED_CORRECTION_LEFT,
  2658. (uint8_t*)EEPROM_BED_CORRECTION_RIGHT,
  2659. (uint8_t*)EEPROM_BED_CORRECTION_FRONT,
  2660. (uint8_t*)EEPROM_BED_CORRECTION_REAR,
  2661. };
  2662. long correction = 0;
  2663. if (code_seen(pgm_read_byte(&codes[i])))
  2664. correction = code_value_long();
  2665. else if (eeprom_bed_correction_valid)
  2666. correction = (int8_t)eeprom_read_byte((uint8_t*)pgm_read_ptr(&eep_addresses[i]));
  2667. if (correction == 0)
  2668. continue;
  2669. if (labs(correction) > BED_ADJUSTMENT_UM_MAX) {
  2670. SERIAL_ERROR_START;
  2671. SERIAL_ECHOPGM("Excessive bed leveling correction: ");
  2672. SERIAL_ECHO(correction);
  2673. SERIAL_ECHOLNPGM(" microns");
  2674. }
  2675. else {
  2676. float offset = float(correction) * 0.001f;
  2677. switch (i) {
  2678. case 0:
  2679. for (uint8_t row = 0; row < nMeasPoints; ++row) {
  2680. for (uint8_t col = 0; col < nMeasPoints - 1; ++col) {
  2681. mbl.z_values[row][col] += offset * (nMeasPoints - 1 - col) / (nMeasPoints - 1);
  2682. }
  2683. }
  2684. break;
  2685. case 1:
  2686. for (uint8_t row = 0; row < nMeasPoints; ++row) {
  2687. for (uint8_t col = 1; col < nMeasPoints; ++col) {
  2688. mbl.z_values[row][col] += offset * col / (nMeasPoints - 1);
  2689. }
  2690. }
  2691. break;
  2692. case 2:
  2693. for (uint8_t col = 0; col < nMeasPoints; ++col) {
  2694. for (uint8_t row = 0; row < nMeasPoints; ++row) {
  2695. mbl.z_values[row][col] += offset * (nMeasPoints - 1 - row) / (nMeasPoints - 1);
  2696. }
  2697. }
  2698. break;
  2699. case 3:
  2700. for (uint8_t col = 0; col < nMeasPoints; ++col) {
  2701. for (uint8_t row = 1; row < nMeasPoints; ++row) {
  2702. mbl.z_values[row][col] += offset * row / (nMeasPoints - 1);
  2703. }
  2704. }
  2705. break;
  2706. }
  2707. }
  2708. }
  2709. // SERIAL_ECHOLNPGM("Bed leveling correction finished");
  2710. if (nMeasPoints == 3) {
  2711. mbl.upsample_3x3(); //interpolation from 3x3 to 7x7 points using largrangian polynomials while using the same array z_values[iy][ix] for storing (just coppying measured data to new destination and interpolating between them)
  2712. }
  2713. /*
  2714. SERIAL_PROTOCOLPGM("Num X,Y: ");
  2715. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  2716. SERIAL_PROTOCOLPGM(",");
  2717. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  2718. SERIAL_PROTOCOLPGM("\nZ search height: ");
  2719. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  2720. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  2721. for (int y = MESH_NUM_Y_POINTS-1; y >= 0; y--) {
  2722. for (int x = 0; x < MESH_NUM_X_POINTS; x++) {
  2723. SERIAL_PROTOCOLPGM(" ");
  2724. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  2725. }
  2726. SERIAL_PROTOCOLPGM("\n");
  2727. }
  2728. */
  2729. if (nMeasPoints == 7 && magnet_elimination) {
  2730. mbl_interpolation(nMeasPoints);
  2731. }
  2732. /*
  2733. SERIAL_PROTOCOLPGM("Num X,Y: ");
  2734. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  2735. SERIAL_PROTOCOLPGM(",");
  2736. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  2737. SERIAL_PROTOCOLPGM("\nZ search height: ");
  2738. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  2739. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  2740. for (int y = MESH_NUM_Y_POINTS-1; y >= 0; y--) {
  2741. for (int x = 0; x < MESH_NUM_X_POINTS; x++) {
  2742. SERIAL_PROTOCOLPGM(" ");
  2743. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  2744. }
  2745. SERIAL_PROTOCOLPGM("\n");
  2746. }
  2747. */
  2748. // SERIAL_ECHOLNPGM("Upsample finished");
  2749. mbl.active = 1; //activate mesh bed leveling
  2750. // SERIAL_ECHOLNPGM("Mesh bed leveling activated");
  2751. go_home_with_z_lift();
  2752. // SERIAL_ECHOLNPGM("Go home finished");
  2753. //unretract (after PINDA preheat retraction)
  2754. if (((int)degHotend(active_extruder) > extrude_min_temp) && eeprom_read_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE) && calibration_status_pinda() && (target_temperature_bed >= 50)) {
  2755. current_position[E_AXIS] += default_retraction;
  2756. plan_buffer_line_curposXYZE(400);
  2757. }
  2758. KEEPALIVE_STATE(NOT_BUSY);
  2759. // Restore custom message state
  2760. lcd_setstatuspgm(MSG_WELCOME);
  2761. custom_message_type = custom_message_type_old;
  2762. custom_message_state = custom_message_state_old;
  2763. lcd_update(2);
  2764. st_synchronize();
  2765. mesh_bed_leveling_flag = false;
  2766. }
  2767. void adjust_bed_reset()
  2768. {
  2769. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_VALID, 1);
  2770. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_LEFT, 0);
  2771. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_RIGHT, 0);
  2772. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_FRONT, 0);
  2773. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_REAR, 0);
  2774. }
  2775. //! @brief Calibrate XYZ
  2776. //! @param onlyZ if true, calibrate only Z axis
  2777. //! @param verbosity_level
  2778. //! @retval true Succeeded
  2779. //! @retval false Failed
  2780. bool gcode_M45(bool onlyZ, int8_t verbosity_level)
  2781. {
  2782. bool final_result = false;
  2783. #ifdef TMC2130
  2784. FORCE_HIGH_POWER_START;
  2785. #endif // TMC2130
  2786. FORCE_BL_ON_START;
  2787. // Only Z calibration?
  2788. if (!onlyZ)
  2789. {
  2790. setTargetBed(0);
  2791. setAllTargetHotends(0);
  2792. adjust_bed_reset(); //reset bed level correction
  2793. }
  2794. // Disable the default update procedure of the display. We will do a modal dialog.
  2795. lcd_update_enable(false);
  2796. // Let the planner use the uncorrected coordinates.
  2797. mbl.reset();
  2798. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  2799. // the planner will not perform any adjustments in the XY plane.
  2800. // Wait for the motors to stop and update the current position with the absolute values.
  2801. world2machine_revert_to_uncorrected();
  2802. // Reset the baby step value applied without moving the axes.
  2803. babystep_reset();
  2804. // Mark all axes as in a need for homing.
  2805. memset(axis_known_position, 0, sizeof(axis_known_position));
  2806. // Home in the XY plane.
  2807. //set_destination_to_current();
  2808. int l_feedmultiply = setup_for_endstop_move();
  2809. lcd_display_message_fullscreen_P(_T(MSG_AUTO_HOME));
  2810. raise_z_above(MESH_HOME_Z_SEARCH);
  2811. home_xy();
  2812. enable_endstops(false);
  2813. current_position[X_AXIS] += 5;
  2814. current_position[Y_AXIS] += 5;
  2815. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2816. st_synchronize();
  2817. // Let the user move the Z axes up to the end stoppers.
  2818. #ifdef TMC2130
  2819. if (calibrate_z_auto())
  2820. {
  2821. #else //TMC2130
  2822. if (lcd_calibrate_z_end_stop_manual(onlyZ))
  2823. {
  2824. #endif //TMC2130
  2825. lcd_show_fullscreen_message_and_wait_P(_T(MSG_CONFIRM_NOZZLE_CLEAN));
  2826. if(onlyZ){
  2827. lcd_display_message_fullscreen_P(_T(MSG_MEASURE_BED_REFERENCE_HEIGHT_LINE1));
  2828. lcd_puts_at_P(0,3,_n("1/9"));
  2829. }else{
  2830. //lcd_show_fullscreen_message_and_wait_P(_T(MSG_PAPER));
  2831. lcd_display_message_fullscreen_P(_T(MSG_FIND_BED_OFFSET_AND_SKEW_LINE1));
  2832. lcd_puts_at_P(0,3,_n("1/4"));
  2833. }
  2834. refresh_cmd_timeout();
  2835. #ifndef STEEL_SHEET
  2836. if (((degHotend(0) > MAX_HOTEND_TEMP_CALIBRATION) || (degBed() > MAX_BED_TEMP_CALIBRATION)) && (!onlyZ))
  2837. {
  2838. lcd_wait_for_cool_down();
  2839. }
  2840. #endif //STEEL_SHEET
  2841. if(!onlyZ)
  2842. {
  2843. KEEPALIVE_STATE(PAUSED_FOR_USER);
  2844. #ifdef STEEL_SHEET
  2845. uint8_t result = lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_STEEL_SHEET_CHECK), false);
  2846. if(result == LCD_LEFT_BUTTON_CHOICE) {
  2847. lcd_show_fullscreen_message_and_wait_P(_T(MSG_REMOVE_STEEL_SHEET));
  2848. }
  2849. #endif //STEEL_SHEET
  2850. lcd_show_fullscreen_message_and_wait_P(_T(MSG_PAPER));
  2851. KEEPALIVE_STATE(IN_HANDLER);
  2852. lcd_display_message_fullscreen_P(_T(MSG_FIND_BED_OFFSET_AND_SKEW_LINE1));
  2853. lcd_puts_at_P(0,3,_n("1/4"));
  2854. }
  2855. bool endstops_enabled = enable_endstops(false);
  2856. raise_z(-1);
  2857. // Move the print head close to the bed.
  2858. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2859. enable_endstops(true);
  2860. #ifdef TMC2130
  2861. tmc2130_home_enter(Z_AXIS_MASK);
  2862. #endif //TMC2130
  2863. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2864. st_synchronize();
  2865. #ifdef TMC2130
  2866. tmc2130_home_exit();
  2867. #endif //TMC2130
  2868. enable_endstops(endstops_enabled);
  2869. if ((st_get_position_mm(Z_AXIS) <= (MESH_HOME_Z_SEARCH + HOME_Z_SEARCH_THRESHOLD)) &&
  2870. (st_get_position_mm(Z_AXIS) >= (MESH_HOME_Z_SEARCH - HOME_Z_SEARCH_THRESHOLD)))
  2871. {
  2872. if (onlyZ)
  2873. {
  2874. clean_up_after_endstop_move(l_feedmultiply);
  2875. // Z only calibration.
  2876. // Load the machine correction matrix
  2877. world2machine_initialize();
  2878. // and correct the current_position to match the transformed coordinate system.
  2879. world2machine_update_current();
  2880. //FIXME
  2881. bool result = sample_mesh_and_store_reference();
  2882. if (result)
  2883. {
  2884. if (calibration_status() == CALIBRATION_STATUS_Z_CALIBRATION)
  2885. {
  2886. // Shipped, the nozzle height has been set already. The user can start printing now.
  2887. calibration_status_store(CALIBRATION_STATUS_CALIBRATED);
  2888. }
  2889. final_result = true;
  2890. // babystep_apply();
  2891. }
  2892. }
  2893. else
  2894. {
  2895. // Reset the baby step value and the baby step applied flag.
  2896. calibration_status_store(CALIBRATION_STATUS_XYZ_CALIBRATION);
  2897. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  2898. // Complete XYZ calibration.
  2899. uint8_t point_too_far_mask = 0;
  2900. BedSkewOffsetDetectionResultType result = find_bed_offset_and_skew(verbosity_level, point_too_far_mask);
  2901. clean_up_after_endstop_move(l_feedmultiply);
  2902. // Print head up.
  2903. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2904. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2905. st_synchronize();
  2906. //#ifndef NEW_XYZCAL
  2907. if (result >= 0)
  2908. {
  2909. #ifdef HEATBED_V2
  2910. sample_z();
  2911. #else //HEATBED_V2
  2912. point_too_far_mask = 0;
  2913. // Second half: The fine adjustment.
  2914. // Let the planner use the uncorrected coordinates.
  2915. mbl.reset();
  2916. world2machine_reset();
  2917. // Home in the XY plane.
  2918. int l_feedmultiply = setup_for_endstop_move();
  2919. home_xy();
  2920. result = improve_bed_offset_and_skew(1, verbosity_level, point_too_far_mask);
  2921. clean_up_after_endstop_move(l_feedmultiply);
  2922. // Print head up.
  2923. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2924. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2925. st_synchronize();
  2926. // if (result >= 0) babystep_apply();
  2927. #endif //HEATBED_V2
  2928. }
  2929. //#endif //NEW_XYZCAL
  2930. lcd_update_enable(true);
  2931. lcd_update(2);
  2932. lcd_bed_calibration_show_result(result, point_too_far_mask);
  2933. if (result >= 0)
  2934. {
  2935. #ifdef TEMP_MODEL
  2936. calibration_status_store(CALIBRATION_STATUS_TEMP_MODEL_CALIBRATION);
  2937. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) != 1) lcd_show_fullscreen_message_and_wait_P(_T(MSG_TM_NOT_CAL));
  2938. #else
  2939. // Calibration valid, the machine should be able to print. Advise the user to run the V2Calibration.gcode.
  2940. calibration_status_store(CALIBRATION_STATUS_LIVE_ADJUST);
  2941. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) != 1) lcd_show_fullscreen_message_and_wait_P(_T(MSG_BABYSTEP_Z_NOT_SET));
  2942. #endif //TEMP_MODEL
  2943. final_result = true;
  2944. }
  2945. }
  2946. #ifdef TMC2130
  2947. tmc2130_home_exit();
  2948. #endif
  2949. }
  2950. else
  2951. {
  2952. lcd_show_fullscreen_message_and_wait_P(PSTR("Calibration failed! Check the axes and run again."));
  2953. final_result = false;
  2954. }
  2955. }
  2956. else
  2957. {
  2958. // Timeouted.
  2959. }
  2960. lcd_update_enable(true);
  2961. #ifdef TMC2130
  2962. FORCE_HIGH_POWER_END;
  2963. #endif // TMC2130
  2964. FORCE_BL_ON_END;
  2965. return final_result;
  2966. }
  2967. void gcode_M114()
  2968. {
  2969. SERIAL_PROTOCOLPGM("X:");
  2970. SERIAL_PROTOCOL(current_position[X_AXIS]);
  2971. SERIAL_PROTOCOLPGM(" Y:");
  2972. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  2973. SERIAL_PROTOCOLPGM(" Z:");
  2974. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  2975. SERIAL_PROTOCOLPGM(" E:");
  2976. SERIAL_PROTOCOL(current_position[E_AXIS]);
  2977. SERIAL_PROTOCOLRPGM(_n(" Count X: "));////MSG_COUNT_X
  2978. SERIAL_PROTOCOL(float(st_get_position(X_AXIS)) / cs.axis_steps_per_unit[X_AXIS]);
  2979. SERIAL_PROTOCOLPGM(" Y:");
  2980. SERIAL_PROTOCOL(float(st_get_position(Y_AXIS)) / cs.axis_steps_per_unit[Y_AXIS]);
  2981. SERIAL_PROTOCOLPGM(" Z:");
  2982. SERIAL_PROTOCOL(float(st_get_position(Z_AXIS)) / cs.axis_steps_per_unit[Z_AXIS]);
  2983. SERIAL_PROTOCOLPGM(" E:");
  2984. SERIAL_PROTOCOLLN(float(st_get_position(E_AXIS)) / cs.axis_steps_per_unit[E_AXIS]);
  2985. }
  2986. #if (defined(FANCHECK) && (((defined(TACH_0) && (TACH_0 >-1)) || (defined(TACH_1) && (TACH_1 > -1)))))
  2987. void gcode_M123()
  2988. {
  2989. printf_P(_N("E0:%d RPM PRN1:%d RPM E0@:%u PRN1@:%d\n"), 60*fan_speed[active_extruder], 60*fan_speed[1], newFanSpeed, fanSpeed);
  2990. }
  2991. #endif //FANCHECK and TACH_0 or TACH_1
  2992. static void mmu_M600_wait_and_beep() {
  2993. // Beep and wait for user to remove old filament and prepare new filament for load
  2994. KEEPALIVE_STATE(PAUSED_FOR_USER);
  2995. int counterBeep = 0;
  2996. lcd_display_message_fullscreen_P(_i("Remove old filament and press the knob to start loading new filament.")); ////MSG_REMOVE_OLD_FILAMENT c=20 r=5
  2997. bool bFirst = true;
  2998. while (!lcd_clicked()) {
  2999. manage_heater();
  3000. manage_inactivity(true);
  3001. #if BEEPER > 0
  3002. if (counterBeep == 500) {
  3003. counterBeep = 0;
  3004. }
  3005. SET_OUTPUT(BEEPER);
  3006. if (counterBeep == 0) {
  3007. if ((eSoundMode == e_SOUND_MODE_BLIND) || (eSoundMode == e_SOUND_MODE_LOUD) || ((eSoundMode == e_SOUND_MODE_ONCE) && bFirst)) {
  3008. bFirst = false;
  3009. WRITE(BEEPER, HIGH);
  3010. }
  3011. }
  3012. if (counterBeep == 20) {
  3013. WRITE(BEEPER, LOW);
  3014. }
  3015. counterBeep++;
  3016. #endif // BEEPER > 0
  3017. delay_keep_alive(4);
  3018. }
  3019. WRITE(BEEPER, LOW);
  3020. }
  3021. /**
  3022. * @brief Handling of unload when using MMU with M600
  3023. * A fullscreen message showing "Unloading Filament x"
  3024. * should be shown on the LCD and LCD updates should be
  3025. * are disabled in the meantime.
  3026. */
  3027. static void mmu_M600_unload_filament() {
  3028. if (MMU2::mmu2.get_current_tool() == (uint8_t)MMU2::FILAMENT_UNKNOWN) return;
  3029. lcd_update_enable(false);
  3030. lcd_clear();
  3031. lcd_puts_at_P(0, 1, _T(MSG_UNLOADING_FILAMENT));
  3032. lcd_print(' ');
  3033. lcd_print(MMU2::mmu2.get_current_tool() + 1);
  3034. // unload just current filament for multimaterial printers (used also in M702)
  3035. MMU2::mmu2.unload();
  3036. lcd_update_enable(true);
  3037. }
  3038. /// @brief load filament for mmu v2
  3039. /// @par nozzle_temp nozzle temperature to load filament
  3040. static void mmu_M600_load_filament(bool automatic, float nozzle_temp) {
  3041. uint8_t slot;
  3042. if (automatic) {
  3043. slot = SpoolJoin::spooljoin.nextSlot();
  3044. } else {
  3045. // Only ask for the slot if automatic/SpoolJoin is off
  3046. slot = choose_menu_P(_T(MSG_SELECT_EXTRUDER), _T(MSG_EXTRUDER));
  3047. }
  3048. setTargetHotend(nozzle_temp, active_extruder);
  3049. MMU2::mmu2.load_filament_to_nozzle(slot);
  3050. load_filament_final_feed(); // @@TODO verify
  3051. st_synchronize();
  3052. }
  3053. static void gcode_M600(bool automatic, float x_position, float y_position, float z_shift, float e_shift, float /*e_shift_late*/) {
  3054. st_synchronize();
  3055. float lastpos[4];
  3056. prusa_statistics(22);
  3057. //First backup current position and settings
  3058. int feedmultiplyBckp = feedmultiply;
  3059. float HotendTempBckp = degTargetHotend(active_extruder);
  3060. int fanSpeedBckp = fanSpeed;
  3061. memcpy(lastpos, current_position, sizeof(lastpos));
  3062. // Turn off the fan
  3063. fanSpeed = 0;
  3064. // Retract E
  3065. current_position[E_AXIS] += e_shift;
  3066. plan_buffer_line_curposXYZE(FILAMENTCHANGE_RFEED);
  3067. st_synchronize();
  3068. // Raise the Z axis
  3069. raise_z(z_shift);
  3070. // Move XY to side
  3071. current_position[X_AXIS] = x_position;
  3072. current_position[Y_AXIS] = y_position;
  3073. plan_buffer_line_curposXYZE(FILAMENTCHANGE_XYFEED);
  3074. st_synchronize();
  3075. // Beep, manage nozzle heater and wait for user to start unload filament
  3076. if (!MMU2::mmu2.Enabled())
  3077. M600_wait_for_user(HotendTempBckp);
  3078. // Unload filament
  3079. if (MMU2::mmu2.Enabled())
  3080. mmu_M600_unload_filament();
  3081. else
  3082. unload_filament(FILAMENTCHANGE_FINALRETRACT, true); // unload filament for single material (used also in M702)
  3083. st_synchronize(); // finish moves
  3084. {
  3085. FSensorBlockRunout fsBlockRunout;
  3086. if (!MMU2::mmu2.Enabled())
  3087. {
  3088. KEEPALIVE_STATE(PAUSED_FOR_USER);
  3089. uint8_t choice =
  3090. lcd_show_fullscreen_message_yes_no_and_wait_P(_i("Was filament unload successful?"), false, LCD_LEFT_BUTTON_CHOICE); ////MSG_UNLOAD_SUCCESSFUL c=20 r=2
  3091. if (choice == LCD_MIDDLE_BUTTON_CHOICE) {
  3092. lcd_clear();
  3093. lcd_puts_at_P(0, 2, _T(MSG_PLEASE_WAIT));
  3094. current_position[X_AXIS] -= 100;
  3095. plan_buffer_line_curposXYZE(FILAMENTCHANGE_XYFEED);
  3096. st_synchronize();
  3097. lcd_show_fullscreen_message_and_wait_P(_i("Please open idler and remove filament manually.")); ////MSG_CHECK_IDLER c=20 r=5
  3098. }
  3099. M600_load_filament();
  3100. }
  3101. else // MMU is enabled
  3102. {
  3103. if (!automatic) {
  3104. if (saved_printing){
  3105. // if M600 was invoked by filament senzor (FINDA) eject filament so user can easily remove it
  3106. MMU2::mmu2.eject_filament(MMU2::mmu2.get_current_tool(), false);
  3107. }
  3108. mmu_M600_wait_and_beep();
  3109. if (saved_printing) {
  3110. lcd_clear();
  3111. lcd_puts_at_P(0, 2, _T(MSG_PLEASE_WAIT));
  3112. //@@TODO mmu_command(MmuCmd::R0);
  3113. // manage_response(false, false);
  3114. }
  3115. }
  3116. mmu_M600_load_filament(automatic, HotendTempBckp);
  3117. }
  3118. if (!automatic)
  3119. M600_check_state(HotendTempBckp);
  3120. lcd_update_enable(true);
  3121. // Not let's go back to print
  3122. fanSpeed = fanSpeedBckp;
  3123. // Feed a little of filament to stabilize pressure
  3124. if (!automatic) {
  3125. current_position[E_AXIS] += FILAMENTCHANGE_RECFEED;
  3126. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EXFEED);
  3127. }
  3128. // Move XY back
  3129. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], FILAMENTCHANGE_XYFEED, active_extruder);
  3130. st_synchronize();
  3131. // Move Z back
  3132. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], lastpos[Z_AXIS], current_position[E_AXIS], FILAMENTCHANGE_ZFEED, active_extruder);
  3133. st_synchronize();
  3134. // Set E position to original
  3135. plan_set_e_position(lastpos[E_AXIS]);
  3136. memcpy(current_position, lastpos, sizeof(lastpos));
  3137. set_destination_to_current();
  3138. // Recover feed rate
  3139. feedmultiply = feedmultiplyBckp;
  3140. char cmd[9];
  3141. sprintf_P(cmd, PSTR("M220 S%i"), feedmultiplyBckp);
  3142. enquecommand(cmd);
  3143. }
  3144. lcd_setstatuspgm(MSG_WELCOME);
  3145. custom_message_type = CustomMsg::Status;
  3146. }
  3147. void gcode_M701(float fastLoadLength, uint8_t mmuSlotIndex){
  3148. FSensorBlockRunout fsBlockRunout;
  3149. prusa_statistics(22);
  3150. if (MMU2::mmu2.Enabled() && mmuSlotIndex < MMU_FILAMENT_COUNT) {
  3151. MMU2::mmu2.load_filament_to_nozzle(mmuSlotIndex);
  3152. } else {
  3153. custom_message_type = CustomMsg::FilamentLoading;
  3154. lcd_setstatuspgm(_T(MSG_LOADING_FILAMENT));
  3155. current_position[E_AXIS] += fastLoadLength;
  3156. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EFEED_FIRST); //fast sequence
  3157. load_filament_final_feed(); // slow sequence
  3158. st_synchronize();
  3159. Sound_MakeCustom(50, 500, false);
  3160. if (!farm_mode && loading_flag) {
  3161. lcd_load_filament_color_check();
  3162. }
  3163. lcd_update_enable(true);
  3164. lcd_update(2);
  3165. lcd_setstatuspgm(MSG_WELCOME);
  3166. loading_flag = false;
  3167. custom_message_type = CustomMsg::Status;
  3168. }
  3169. eFilamentAction = FilamentAction::None;
  3170. }
  3171. // Common gcode shared by the gcodes. This saves some flash memory
  3172. static void gcodes_M704_M705_M706(uint16_t gcode)
  3173. {
  3174. uint8_t mmuSlotIndex = 0xffU;
  3175. if (MMU2::mmu2.Enabled() && code_seen('P'))
  3176. {
  3177. mmuSlotIndex = code_value_uint8();
  3178. if (mmuSlotIndex < MMU_FILAMENT_COUNT) {
  3179. switch (gcode)
  3180. {
  3181. case 704:
  3182. MMU2::mmu2.load_filament(mmuSlotIndex);
  3183. break;
  3184. case 705:
  3185. MMU2::mmu2.eject_filament(mmuSlotIndex, false);
  3186. break;
  3187. case 706:
  3188. #ifdef MMU_HAS_CUTTER
  3189. if (eeprom_read_byte((uint8_t*)EEPROM_MMU_CUTTER_ENABLED) != 0){
  3190. MMU2::mmu2.cut_filament(mmuSlotIndex);
  3191. }
  3192. #endif // MMU_HAS_CUTTER
  3193. break;
  3194. default:
  3195. break;
  3196. }
  3197. }
  3198. }
  3199. }
  3200. /**
  3201. * @brief Get serial number from 32U2 processor
  3202. *
  3203. * Typical format of S/N is:CZPX0917X003XC13518
  3204. *
  3205. * Send command ;S to serial port 0 to retrieve serial number stored in 32U2 processor,
  3206. * reply is stored in *SN.
  3207. * Operation takes typically 23 ms. If no valid SN can be retrieved within the 250ms window, the function aborts
  3208. * and returns a general failure flag.
  3209. * The command will fail if the 32U2 processor is unpowered via USB since it is isolated from the rest of the electronics.
  3210. * In that case the value that is stored in the EEPROM should be used instead.
  3211. *
  3212. * @return 0 on success
  3213. * @return 1 on general failure
  3214. */
  3215. #ifdef PRUSA_SN_SUPPORT
  3216. static uint8_t get_PRUSA_SN(char* SN)
  3217. {
  3218. uint8_t selectedSerialPort_bak = selectedSerialPort;
  3219. uint8_t rxIndex;
  3220. bool SN_valid = false;
  3221. ShortTimer timeout;
  3222. selectedSerialPort = 0;
  3223. timeout.start();
  3224. while (!SN_valid)
  3225. {
  3226. rxIndex = 0;
  3227. _delay(50);
  3228. MYSERIAL.flush(); //clear RX buffer
  3229. SERIAL_ECHOLNRPGM(PSTR(";S"));
  3230. while (rxIndex < 19)
  3231. {
  3232. if (timeout.expired(250u))
  3233. goto exit;
  3234. if (MYSERIAL.available() > 0)
  3235. {
  3236. SN[rxIndex] = MYSERIAL.read();
  3237. rxIndex++;
  3238. }
  3239. }
  3240. SN[rxIndex] = 0;
  3241. // printf_P(PSTR("SN:%s\n"), SN);
  3242. SN_valid = (strncmp_P(SN, PSTR("CZPX"), 4) == 0);
  3243. }
  3244. exit:
  3245. selectedSerialPort = selectedSerialPort_bak;
  3246. return !SN_valid;
  3247. }
  3248. #endif //PRUSA_SN_SUPPORT
  3249. //! Detection of faulty RAMBo 1.1b boards equipped with bigger capacitors
  3250. //! at the TACH_1 pin, which causes bad detection of print fan speed.
  3251. //! Warning: This function is not to be used by ordinary users, it is here only for automated testing purposes,
  3252. //! it may even interfere with other functions of the printer! You have been warned!
  3253. //! The test idea is to measure the time necessary to charge the capacitor.
  3254. //! So the algorithm is as follows:
  3255. //! 1. Set TACH_1 pin to INPUT mode and LOW
  3256. //! 2. Wait a few ms
  3257. //! 3. disable interrupts and measure the time until the TACH_1 pin reaches HIGH
  3258. //! Repeat 1.-3. several times
  3259. //! Good RAMBo's times are in the range of approx. 260-320 us
  3260. //! Bad RAMBo's times are approx. 260-1200 us
  3261. //! So basically we are interested in maximum time, the minima are mostly the same.
  3262. //! May be that's why the bad RAMBo's still produce some fan RPM reading, but not corresponding to reality
  3263. static void gcode_PRUSA_BadRAMBoFanTest(){
  3264. //printf_P(PSTR("Enter fan pin test\n"));
  3265. #if !defined(DEBUG_DISABLE_FANCHECK) && defined(FANCHECK) && defined(TACH_1) && TACH_1 >-1
  3266. fan_measuring = false; // prevent EXTINT7 breaking into the measurement
  3267. unsigned long tach1max = 0;
  3268. uint8_t tach1cntr = 0;
  3269. for( /* nothing */; tach1cntr < 100; ++tach1cntr){
  3270. //printf_P(PSTR("TACH_1: %d\n"), tach1cntr);
  3271. SET_OUTPUT(TACH_1);
  3272. WRITE(TACH_1, LOW);
  3273. _delay(20); // the delay may be lower
  3274. unsigned long tachMeasure = _micros();
  3275. cli();
  3276. SET_INPUT(TACH_1);
  3277. // just wait brutally in an endless cycle until we reach HIGH
  3278. // if this becomes a problem it may be improved to non-endless cycle
  3279. while( READ(TACH_1) == 0 ) ;
  3280. sei();
  3281. tachMeasure = _micros() - tachMeasure;
  3282. if( tach1max < tachMeasure )
  3283. tach1max = tachMeasure;
  3284. //printf_P(PSTR("TACH_1: %d: capacitor check time=%lu us\n"), (int)tach1cntr, tachMeasure);
  3285. }
  3286. //printf_P(PSTR("TACH_1: max=%lu us\n"), tach1max);
  3287. SERIAL_PROTOCOLPGM("RAMBo FAN ");
  3288. if( tach1max > 500 ){
  3289. // bad RAMBo
  3290. SERIAL_PROTOCOLLNPGM("BAD");
  3291. } else {
  3292. SERIAL_PROTOCOLLNPGM("OK");
  3293. }
  3294. // cleanup after the test function
  3295. SET_INPUT(TACH_1);
  3296. WRITE(TACH_1, HIGH);
  3297. #endif
  3298. }
  3299. // G92 - Set current position to coordinates given
  3300. static void gcode_G92()
  3301. {
  3302. bool codes[NUM_AXIS];
  3303. float values[NUM_AXIS];
  3304. // Check which axes need to be set
  3305. for(uint8_t i = 0; i < NUM_AXIS; ++i)
  3306. {
  3307. codes[i] = code_seen(axis_codes[i]);
  3308. if(codes[i])
  3309. values[i] = code_value();
  3310. }
  3311. if((codes[E_AXIS] && values[E_AXIS] == 0) &&
  3312. (!codes[X_AXIS] && !codes[Y_AXIS] && !codes[Z_AXIS]))
  3313. {
  3314. // As a special optimization, when _just_ clearing the E position
  3315. // we schedule a flag asynchronously along with the next block to
  3316. // reset the starting E position instead of stopping the planner
  3317. current_position[E_AXIS] = 0;
  3318. plan_reset_next_e();
  3319. }
  3320. else
  3321. {
  3322. // In any other case we're forced to synchronize
  3323. st_synchronize();
  3324. for(uint8_t i = 0; i < 3; ++i)
  3325. {
  3326. if(codes[i])
  3327. current_position[i] = values[i] + cs.add_homing[i];
  3328. }
  3329. if(codes[E_AXIS])
  3330. current_position[E_AXIS] = values[E_AXIS];
  3331. // Set all at once
  3332. plan_set_position_curposXYZE();
  3333. }
  3334. }
  3335. #ifdef EXTENDED_CAPABILITIES_REPORT
  3336. static void cap_line(const char* name, bool ena = false) {
  3337. printf_P(PSTR("Cap:%S:%c\n"), name, (char)ena + '0');
  3338. }
  3339. static void extended_capabilities_report()
  3340. {
  3341. // AUTOREPORT_TEMP (M155)
  3342. cap_line(PSTR("AUTOREPORT_TEMP"), ENABLED(AUTO_REPORT));
  3343. #if (defined(FANCHECK) && (((defined(TACH_0) && (TACH_0 >-1)) || (defined(TACH_1) && (TACH_1 > -1)))))
  3344. // AUTOREPORT_FANS (M123)
  3345. cap_line(PSTR("AUTOREPORT_FANS"), ENABLED(AUTO_REPORT));
  3346. #endif //FANCHECK and TACH_0 or TACH_1
  3347. // AUTOREPORT_POSITION (M114)
  3348. cap_line(PSTR("AUTOREPORT_POSITION"), ENABLED(AUTO_REPORT));
  3349. // EXTENDED_M20 (support for L and T parameters)
  3350. cap_line(PSTR("EXTENDED_M20"), 1);
  3351. cap_line(PSTR("PRUSA_MMU2"), 1); //this will soon change to ENABLED(PRUSA_MMU2_SUPPORT)
  3352. }
  3353. #endif //EXTENDED_CAPABILITIES_REPORT
  3354. #ifdef BACKLASH_X
  3355. extern uint8_t st_backlash_x;
  3356. #endif //BACKLASH_X
  3357. #ifdef BACKLASH_Y
  3358. extern uint8_t st_backlash_y;
  3359. #endif //BACKLASH_Y
  3360. //! \ingroup marlin_main
  3361. //! @brief Parse and process commands
  3362. //!
  3363. //! look here for descriptions of G-codes: https://reprap.org/wiki/G-code
  3364. //!
  3365. //!
  3366. //! Implemented Codes
  3367. //! -------------------
  3368. //!
  3369. //! * _This list is not updated. Current documentation is maintained inside the process_cmd function._
  3370. //!
  3371. //!@n PRUSA CODES
  3372. //!@n P F - Returns FW versions
  3373. //!@n P R - Returns revision of printer
  3374. //!
  3375. //!@n G0 -> G1
  3376. //!@n G1 - Coordinated Movement X Y Z E
  3377. //!@n G2 - CW ARC
  3378. //!@n G3 - CCW ARC
  3379. //!@n G4 - Dwell S<seconds> or P<milliseconds>
  3380. //!@n G10 - retract filament according to settings of M207
  3381. //!@n G11 - retract recover filament according to settings of M208
  3382. //!@n G28 - Home all Axes
  3383. //!@n G29 - Detailed Z-Probe, probes the bed at 3 or more points. Will fail if you haven't homed yet.
  3384. //!@n G30 - Single Z Probe, probes bed at current XY location.
  3385. //!@n G31 - Dock sled (Z_PROBE_SLED only)
  3386. //!@n G32 - Undock sled (Z_PROBE_SLED only)
  3387. //!@n G80 - Automatic mesh bed leveling
  3388. //!@n G81 - Print bed profile
  3389. //!@n G90 - Use Absolute Coordinates
  3390. //!@n G91 - Use Relative Coordinates
  3391. //!@n G92 - Set current position to coordinates given
  3392. //!
  3393. //!@n M Codes
  3394. //!@n M0 - Unconditional stop - Wait for user to press a button on the LCD
  3395. //!@n M1 - Same as M0
  3396. //!@n M17 - Enable/Power all stepper motors
  3397. //!@n M18 - Disable all stepper motors; same as M84
  3398. //!@n M20 - List SD card
  3399. //!@n M21 - Init SD card
  3400. //!@n M22 - Release SD card
  3401. //!@n M23 - Select SD file (M23 filename.g)
  3402. //!@n M24 - Start/resume SD print
  3403. //!@n M25 - Pause SD print
  3404. //!@n M26 - Set SD position in bytes (M26 S12345)
  3405. //!@n M27 - Report SD print status
  3406. //!@n M28 - Start SD write (M28 filename.g)
  3407. //!@n M29 - Stop SD write
  3408. //!@n M30 - Delete file from SD (M30 filename.g)
  3409. //!@n M31 - Output time since last M109 or SD card start to serial
  3410. //!@n M32 - Select file and start SD print (Can be used _while_ printing from SD card files):
  3411. //! syntax "M32 /path/filename#", or "M32 S<startpos bytes> !filename#"
  3412. //! Call gcode file : "M32 P !filename#" and return to caller file after finishing (similar to #include).
  3413. //! The '#' is necessary when calling from within sd files, as it stops buffer prereading
  3414. //!@n 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.
  3415. //!@n M73 - Show percent done and print time remaining
  3416. //!@n M80 - Turn on Power Supply
  3417. //!@n M81 - Turn off Power Supply
  3418. //!@n M82 - Set E codes absolute (default)
  3419. //!@n M83 - Set E codes relative while in Absolute Coordinates (G90) mode
  3420. //!@n M84 - Disable steppers until next move,
  3421. //! or use S<seconds> to specify an inactivity timeout, after which the steppers will be disabled. S0 to disable the timeout.
  3422. //!@n M85 - Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
  3423. //!@n M86 - Set safety timer expiration time with parameter S<seconds>; M86 S0 will disable safety timer
  3424. //!@n M92 - Set axis_steps_per_unit - same syntax as G92
  3425. //!@n M104 - Set extruder target temp
  3426. //!@n M105 - Read current temp
  3427. //!@n M106 - Fan on
  3428. //!@n M107 - Fan off
  3429. //!@n M109 - Sxxx Wait for extruder current temp to reach target temp. Waits only when heating
  3430. //! Rxxx Wait for extruder current temp to reach target temp. Waits when heating and cooling
  3431. //! IF AUTOTEMP is enabled, S<mintemp> B<maxtemp> F<factor>. Exit autotemp by any M109 without F
  3432. //!@n M112 - Emergency stop
  3433. //!@n M113 - Get or set the timeout interval for Host Keepalive "busy" messages
  3434. //!@n M114 - Output current position to serial port
  3435. //!@n M115 - Capabilities string
  3436. //!@n M117 - display message
  3437. //!@n M119 - Output Endstop status to serial port
  3438. //!@n M123 - Tachometer value
  3439. //!@n M126 - Solenoid Air Valve Open (BariCUDA support by jmil)
  3440. //!@n M127 - Solenoid Air Valve Closed (BariCUDA vent to atmospheric pressure by jmil)
  3441. //!@n M128 - EtoP Open (BariCUDA EtoP = electricity to air pressure transducer by jmil)
  3442. //!@n M129 - EtoP Closed (BariCUDA EtoP = electricity to air pressure transducer by jmil)
  3443. //!@n M140 - Set bed target temp
  3444. //!@n 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.
  3445. //!@n M155 - Automatically send temperatures, fan speeds, position
  3446. //!@n M190 - Sxxx Wait for bed current temp to reach target temp. Waits only when heating
  3447. //! Rxxx Wait for bed current temp to reach target temp. Waits when heating and cooling
  3448. //!@n M200 D<millimeters>- set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).
  3449. //!@n M201 - Set max acceleration in units/s^2 for print moves (M201 X1000 Y1000)
  3450. //!@n M202 - Set max acceleration in units/s^2 for travel moves (M202 X1000 Y1000) Unused in Marlin!!
  3451. //!@n M203 - Set maximum feedrate that your machine can sustain (M203 X200 Y200 Z300 E10000) in mm/sec
  3452. //!@n M204 - Set default acceleration: S normal moves T filament only moves (M204 S3000 T7000) in mm/sec^2 also sets minimum segment time in ms (B20000) to prevent buffer under-runs and M20 minimum feedrate
  3453. //!@n 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
  3454. //!@n M206 - set additional homing offset
  3455. //!@n M207 - set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop], stays in mm regardless of M200 setting
  3456. //!@n M208 - set recover=unretract length S[positive mm surplus to the M207 S*] F[feedrate mm/sec]
  3457. //!@n 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.
  3458. //!@n M214 - Set Arc Parameters (Use M500 to store in eeprom) P<MM_PER_ARC_SEGMENT> S<MIN_MM_PER_ARC_SEGMENT> R<MIN_ARC_SEGMENTS> F<ARC_SEGMENTS_PER_SEC>
  3459. //!@n M218 - set hotend offset (in mm): T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  3460. //!@n M220 S<factor in percent>- set speed factor override percentage
  3461. //!@n M221 S<factor in percent>- set extrude factor override percentage
  3462. //!@n M226 P<pin number> S<pin state>- Wait until the specified pin reaches the state required
  3463. //!@n M240 - Trigger a camera to take a photograph
  3464. //!@n M250 - Set LCD contrast C<contrast value> (value 0..63)
  3465. //!@n M280 - set servo position absolute. P: servo index, S: angle or microseconds
  3466. //!@n M300 - Play beep sound S<frequency Hz> P<duration ms>
  3467. //!@n M301 - Set PID parameters P I and D
  3468. //!@n M302 - Allow cold extrudes, or set the minimum extrude S<temperature>.
  3469. //!@n M303 - PID relay autotune S<temperature> sets the target temperature. (default target temperature = 150C)
  3470. //!@n M304 - Set bed PID parameters P I and D
  3471. //!@n M310 - Temperature model settings
  3472. //!@n M400 - Finish all moves
  3473. //!@n M401 - Lower z-probe if present
  3474. //!@n M402 - Raise z-probe if present
  3475. //!@n M404 - N<dia in mm> Enter the nominal filament width (3mm, 1.75mm ) or will display nominal filament width without parameters
  3476. //!@n M405 - Turn on Filament Sensor extrusion control. Optional D<delay in cm> to set delay in centimeters between sensor and extruder
  3477. //!@n M406 - Turn off Filament Sensor extrusion control
  3478. //!@n M407 - Displays measured filament diameter
  3479. //!@n M500 - stores parameters in EEPROM
  3480. //!@n M501 - reads parameters from EEPROM (if you need reset them after you changed them temporarily).
  3481. //!@n M502 - reverts to the default "factory settings". You still need to store them in EEPROM afterwards if you want to.
  3482. //!@n M503 - print the current settings (from memory not from EEPROM)
  3483. //!@n M509 - force language selection on next restart
  3484. //!@n M540 - Use S[0|1] to enable or disable the stop SD card print on endstop hit (requires ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  3485. //!@n M552 - Set IP address
  3486. //!@n M600 - Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  3487. //!@n M605 - Set dual x-carriage movement mode: S<mode> [ X<duplication x-offset> R<duplication temp offset> ]
  3488. //!@n M860 - Wait for PINDA thermistor to reach target temperature.
  3489. //!@n M861 - Set / Read PINDA temperature compensation offsets
  3490. //!@n M900 - Set LIN_ADVANCE options, if enabled. See Configuration_adv.h for details.
  3491. //!@n M907 - Set digital trimpot motor current using axis codes.
  3492. //!@n M908 - Control digital trimpot directly.
  3493. //!@n M350 - Set microstepping mode.
  3494. //!@n M351 - Toggle MS1 MS2 pins directly.
  3495. //!
  3496. //!@n M928 - Start SD logging (M928 filename.g) - ended by M29
  3497. //!@n M999 - Restart after being stopped by error
  3498. //! <br><br>
  3499. /** @defgroup marlin_main Marlin main */
  3500. /** \ingroup GCodes */
  3501. //! _This is a list of currently implemented G Codes in Prusa firmware (dynamically generated from doxygen)._
  3502. /**
  3503. They are shown in order of appearance in the code.
  3504. There are reasons why some G Codes aren't in numerical order.
  3505. */
  3506. void process_commands()
  3507. {
  3508. if (!buflen) return; //empty command
  3509. #ifdef CMDBUFFER_DEBUG
  3510. SERIAL_ECHOPGM("Processing a GCODE command: ");
  3511. SERIAL_ECHO(cmdbuffer+bufindr+CMDHDRSIZE);
  3512. SERIAL_ECHOLNPGM("");
  3513. SERIAL_ECHOPGM("In cmdqueue: ");
  3514. SERIAL_ECHO(buflen);
  3515. SERIAL_ECHOLNPGM("");
  3516. #endif /* CMDBUFFER_DEBUG */
  3517. unsigned long codenum; //throw away variable
  3518. char *starpos = NULL;
  3519. #ifdef ENABLE_AUTO_BED_LEVELING
  3520. float x_tmp, y_tmp, z_tmp, real_z;
  3521. #endif
  3522. // PRUSA GCODES
  3523. KEEPALIVE_STATE(IN_HANDLER);
  3524. /*!
  3525. ---------------------------------------------------------------------------------
  3526. ### M117 - Display Message <a href="https://reprap.org/wiki/G-code#M117:_Display_Message">M117: Display Message</a>
  3527. This causes the given message to be shown in the status line on an attached LCD.
  3528. It is processed early as to allow printing messages that contain G, M, N or T.
  3529. ---------------------------------------------------------------------------------
  3530. ### Special internal commands
  3531. These are used by internal functions to process certain actions in the right order. Some of these are also usable by the user.
  3532. They are processed early as the commands are complex (strings).
  3533. These are only available on the MK3(S) as these require TMC2130 drivers:
  3534. - CRASH DETECTED
  3535. - CRASH RECOVER
  3536. - CRASH_CANCEL
  3537. - TMC_SET_WAVE
  3538. - TMC_SET_STEP
  3539. - TMC_SET_CHOP
  3540. */
  3541. if (code_seen_P(PSTR("M117"))) //moved to highest priority place to be able to to print strings which includes "G", "PRUSA" and "^"
  3542. {
  3543. starpos = (strchr(strchr_pointer + 5, '*'));
  3544. if (starpos != NULL)
  3545. *(starpos) = '\0';
  3546. lcd_setstatus(strchr_pointer + 5);
  3547. custom_message_type = CustomMsg::M117;
  3548. }
  3549. /*!
  3550. ### M0, M1 - Stop the printer <a href="https://reprap.org/wiki/G-code#M0:_Stop_or_Unconditional_stop">M0: Stop or Unconditional stop</a>
  3551. #### Usage
  3552. M0 [P<ms<] [S<sec>] [string]
  3553. M1 [P<ms>] [S<sec>] [string]
  3554. #### Parameters
  3555. - `P<ms>` - Expire time, in milliseconds
  3556. - `S<sec>` - Expire time, in seconds
  3557. - `string` - Must for M1 and optional for M0 message to display on the LCD
  3558. */
  3559. else if (code_seen_P(PSTR("M0")) || code_seen_P(PSTR("M1 "))) {// M0 and M1 - (Un)conditional stop - Wait for user button press on LCD
  3560. const char *src = strchr_pointer + 2;
  3561. codenum = 0;
  3562. bool hasP = false, hasS = false;
  3563. if (code_seen('P')) {
  3564. codenum = code_value_long(); // milliseconds to wait
  3565. hasP = codenum > 0;
  3566. }
  3567. if (code_seen('S')) {
  3568. codenum = code_value_long() * 1000; // seconds to wait
  3569. hasS = codenum > 0;
  3570. }
  3571. starpos = strchr(src, '*');
  3572. if (starpos != NULL) *(starpos) = '\0';
  3573. while (*src == ' ') ++src;
  3574. custom_message_type = CustomMsg::M0Wait;
  3575. if (!hasP && !hasS && *src != '\0') {
  3576. lcd_setstatus(src);
  3577. } else {
  3578. // farmers want to abuse a bug from the previous firmware releases
  3579. // - they need to see the filename on the status screen instead of "Wait for user..."
  3580. // So we won't update the message in farm mode...
  3581. if( ! farm_mode){
  3582. LCD_MESSAGERPGM(_i("Wait for user..."));////MSG_USERWAIT c=20
  3583. } else {
  3584. custom_message_type = CustomMsg::Status; // let the lcd display the name of the printed G-code file in farm mode
  3585. }
  3586. }
  3587. lcd_ignore_click(); //call lcd_ignore_click also for else ???
  3588. st_synchronize();
  3589. previous_millis_cmd.start();
  3590. if (codenum > 0 ) {
  3591. codenum += _millis(); // keep track of when we started waiting
  3592. KEEPALIVE_STATE(PAUSED_FOR_USER);
  3593. while(_millis() < codenum && !lcd_clicked()) {
  3594. manage_heater();
  3595. manage_inactivity(true);
  3596. lcd_update(0);
  3597. }
  3598. KEEPALIVE_STATE(IN_HANDLER);
  3599. lcd_ignore_click(false);
  3600. } else {
  3601. marlin_wait_for_click();
  3602. }
  3603. if (IS_SD_PRINTING)
  3604. custom_message_type = CustomMsg::Status;
  3605. else
  3606. LCD_MESSAGERPGM(MSG_WELCOME);
  3607. }
  3608. #ifdef TMC2130
  3609. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("CRASH_"), 6) == 0)
  3610. {
  3611. // ### CRASH_DETECTED - TMC2130
  3612. // ---------------------------------
  3613. if(code_seen_P(PSTR("CRASH_DETECTED")))
  3614. {
  3615. uint8_t mask = 0;
  3616. if (code_seen('X')) mask |= X_AXIS_MASK;
  3617. if (code_seen('Y')) mask |= Y_AXIS_MASK;
  3618. crashdet_detected(mask);
  3619. }
  3620. // ### CRASH_RECOVER - TMC2130
  3621. // ----------------------------------
  3622. else if(code_seen_P(PSTR("CRASH_RECOVER")))
  3623. crashdet_recover();
  3624. // ### CRASH_CANCEL - TMC2130
  3625. // ----------------------------------
  3626. else if(code_seen_P(PSTR("CRASH_CANCEL")))
  3627. crashdet_cancel();
  3628. }
  3629. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("TMC_"), 4) == 0)
  3630. {
  3631. // ### TMC_SET_WAVE_
  3632. // --------------------
  3633. if (strncmp_P(CMDBUFFER_CURRENT_STRING + 4, PSTR("SET_WAVE_"), 9) == 0)
  3634. {
  3635. uint8_t axis = *(CMDBUFFER_CURRENT_STRING + 13);
  3636. axis = (axis == 'E')?3:(axis - 'X');
  3637. if (axis < 4)
  3638. {
  3639. uint8_t fac = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 14, NULL, 10);
  3640. tmc2130_set_wave(axis, 247, fac);
  3641. }
  3642. }
  3643. // ### TMC_SET_STEP_
  3644. // ------------------
  3645. else if (strncmp_P(CMDBUFFER_CURRENT_STRING + 4, PSTR("SET_STEP_"), 9) == 0)
  3646. {
  3647. uint8_t axis = *(CMDBUFFER_CURRENT_STRING + 13);
  3648. axis = (axis == 'E')?3:(axis - 'X');
  3649. if (axis < 4)
  3650. {
  3651. uint8_t step = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 14, NULL, 10);
  3652. uint16_t res = tmc2130_get_res(axis);
  3653. tmc2130_goto_step(axis, step & (4*res - 1), 2, 1000, res);
  3654. }
  3655. }
  3656. // ### TMC_SET_CHOP_
  3657. // -------------------
  3658. else if (strncmp_P(CMDBUFFER_CURRENT_STRING + 4, PSTR("SET_CHOP_"), 9) == 0)
  3659. {
  3660. uint8_t axis = *(CMDBUFFER_CURRENT_STRING + 13);
  3661. axis = (axis == 'E')?3:(axis - 'X');
  3662. if (axis < 4)
  3663. {
  3664. uint8_t chop0 = tmc2130_chopper_config[axis].toff;
  3665. uint8_t chop1 = tmc2130_chopper_config[axis].hstr;
  3666. uint8_t chop2 = tmc2130_chopper_config[axis].hend;
  3667. uint8_t chop3 = tmc2130_chopper_config[axis].tbl;
  3668. char* str_end = 0;
  3669. if (CMDBUFFER_CURRENT_STRING[14])
  3670. {
  3671. chop0 = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 14, &str_end, 10) & 15;
  3672. if (str_end && *str_end)
  3673. {
  3674. chop1 = (uint8_t)strtol(str_end, &str_end, 10) & 7;
  3675. if (str_end && *str_end)
  3676. {
  3677. chop2 = (uint8_t)strtol(str_end, &str_end, 10) & 15;
  3678. if (str_end && *str_end)
  3679. chop3 = (uint8_t)strtol(str_end, &str_end, 10) & 3;
  3680. }
  3681. }
  3682. }
  3683. tmc2130_chopper_config[axis].toff = chop0;
  3684. tmc2130_chopper_config[axis].hstr = chop1 & 7;
  3685. tmc2130_chopper_config[axis].hend = chop2 & 15;
  3686. tmc2130_chopper_config[axis].tbl = chop3 & 3;
  3687. tmc2130_setup_chopper(axis, tmc2130_mres[axis], tmc2130_current_h[axis], tmc2130_current_r[axis]);
  3688. //printf_P(_N("TMC_SET_CHOP_%c %d %d %d %d\n"), "xyze"[axis], chop0, chop1, chop2, chop3);
  3689. }
  3690. }
  3691. }
  3692. #ifdef BACKLASH_X
  3693. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("BACKLASH_X"), 10) == 0)
  3694. {
  3695. uint8_t bl = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 10, NULL, 10);
  3696. st_backlash_x = bl;
  3697. printf_P(_N("st_backlash_x = %d\n"), st_backlash_x);
  3698. }
  3699. #endif //BACKLASH_X
  3700. #ifdef BACKLASH_Y
  3701. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("BACKLASH_Y"), 10) == 0)
  3702. {
  3703. uint8_t bl = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 10, NULL, 10);
  3704. st_backlash_y = bl;
  3705. printf_P(_N("st_backlash_y = %d\n"), st_backlash_y);
  3706. }
  3707. #endif //BACKLASH_Y
  3708. #endif //TMC2130
  3709. else if(code_seen_P(PSTR("PRUSA"))){
  3710. /*!
  3711. ---------------------------------------------------------------------------------
  3712. ### PRUSA - Internal command set <a href="https://reprap.org/wiki/G-code#G98:_Activate_farm_mode">G98: Activate farm mode - Notes</a>
  3713. Set of internal PRUSA commands
  3714. #### Usage
  3715. PRUSA [ PRN | FAN | thx | uvlo | MMURES | RESET | fv | M28 | SN | Fir | Rev | Lang | Lz | FR ]
  3716. #### Parameters
  3717. - `PRN` - Prints revision of the printer
  3718. - `FAN` - Prints fan details
  3719. - `thx`
  3720. - `uvlo`
  3721. - `MMURES` - Reset MMU
  3722. - `RESET` - (Careful!)
  3723. - `fv` - ?
  3724. - `M28`
  3725. - `SN`
  3726. - `Fir` - Prints firmware version
  3727. - `Rev`- Prints filament size, elelectronics, nozzle type
  3728. - `Lang` - Reset the language
  3729. - `Lz`
  3730. - `FR` - Full factory reset
  3731. - `nozzle set <diameter>` - set nozzle diameter (farm mode only), e.g. `PRUSA nozzle set 0.4`
  3732. - `nozzle D<diameter>` - check the nozzle diameter (farm mode only), works like M862.1 P, e.g. `PRUSA nozzle D0.4`
  3733. - `nozzle` - prints nozzle diameter (farm mode only), works like M862.1 P, e.g. `PRUSA nozzle`
  3734. */
  3735. if (farm_prusa_code_seen()) {}
  3736. else if(code_seen_P(PSTR("FANPINTST"))) {
  3737. gcode_PRUSA_BadRAMBoFanTest();
  3738. }
  3739. else if (code_seen_P(PSTR("FAN"))) { // PRUSA FAN
  3740. printf_P(_N("E0:%d RPM\nPRN0:%d RPM\n"), 60*fan_speed[0], 60*fan_speed[1]);
  3741. }
  3742. else if (code_seen_P(PSTR("uvlo"))) { // PRUSA uvlo
  3743. eeprom_update_byte((uint8_t*)EEPROM_UVLO,0);
  3744. enquecommand_P(PSTR("M24"));
  3745. }
  3746. else if (code_seen_P(PSTR("MMURES"))) // PRUSA MMURES
  3747. {
  3748. MMU2::mmu2.Reset(MMU2::MMU2::Software);
  3749. }
  3750. else if (code_seen_P(PSTR("RESET"))) { // PRUSA RESET
  3751. #ifdef WATCHDOG
  3752. #if defined(XFLASH) && defined(BOOTAPP)
  3753. boot_app_magic = BOOT_APP_MAGIC;
  3754. boot_app_flags = BOOT_APP_FLG_RUN;
  3755. #endif //defined(XFLASH) && defined(BOOTAPP)
  3756. softReset();
  3757. #elif defined(BOOTAPP) //this is a safety precaution. This is because the new bootloader turns off the heaters, but the old one doesn't. The watchdog should be used most of the time.
  3758. asm volatile("jmp 0x3E000");
  3759. #endif
  3760. }
  3761. #ifdef PRUSA_SN_SUPPORT
  3762. else if (code_seen_P(PSTR("SN"))) { // PRUSA SN
  3763. char SN[20];
  3764. eeprom_read_block(SN, (uint8_t*)EEPROM_PRUSA_SN, 20);
  3765. if (SN[19])
  3766. puts_P(PSTR("SN invalid"));
  3767. else
  3768. puts(SN);
  3769. }
  3770. #endif //PRUSA_SN_SUPPORT
  3771. else if(code_seen_P(PSTR("Fir"))){ // PRUSA Fir
  3772. SERIAL_PROTOCOLLNPGM(FW_VERSION_FULL);
  3773. } else if(code_seen_P(PSTR("Rev"))){ // PRUSA Rev
  3774. SERIAL_PROTOCOLLNPGM(FILAMENT_SIZE "-" ELECTRONICS "-" NOZZLE_TYPE );
  3775. } else if(code_seen_P(PSTR("Lang"))) { // PRUSA Lang
  3776. lang_reset();
  3777. } else if(code_seen_P(PSTR("Lz"))) { // PRUSA Lz
  3778. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  3779. } else if(code_seen_P(PSTR("FR"))) { // PRUSA FR
  3780. // Factory full reset
  3781. factory_reset(0);
  3782. } else if(code_seen_P(PSTR("MBL"))) { // PRUSA MBL
  3783. // Change the MBL status without changing the logical Z position.
  3784. if(code_seen('V')) {
  3785. bool value = code_value_short();
  3786. st_synchronize();
  3787. if(value != mbl.active) {
  3788. mbl.active = value;
  3789. // Use plan_set_z_position to reset the physical values
  3790. plan_set_z_position(current_position[Z_AXIS]);
  3791. }
  3792. }
  3793. } else if (code_seen_P(PSTR("nozzle"))) { // PRUSA nozzle
  3794. uint16_t nDiameter;
  3795. if(code_seen('D'))
  3796. {
  3797. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  3798. nozzle_diameter_check(nDiameter);
  3799. }
  3800. else if(code_seen_P(PSTR("set")) && farm_mode)
  3801. {
  3802. strchr_pointer++; // skip 1st char (~ 's')
  3803. strchr_pointer++; // skip 2nd char (~ 'e')
  3804. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  3805. eeprom_update_byte((uint8_t*)EEPROM_NOZZLE_DIAMETER,(uint8_t)ClNozzleDiameter::_Diameter_Undef); // for correct synchronization after farm-mode exiting
  3806. eeprom_update_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM,nDiameter);
  3807. }
  3808. else SERIAL_PROTOCOLLN((float)eeprom_read_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM)/1000.0);
  3809. }
  3810. }
  3811. else if(code_seen('G'))
  3812. {
  3813. gcode_in_progress = code_value_short();
  3814. // printf_P(_N("BEGIN G-CODE=%u\n"), gcode_in_progress);
  3815. switch (gcode_in_progress)
  3816. {
  3817. /*!
  3818. ---------------------------------------------------------------------------------
  3819. # G Codes
  3820. ### G0, G1 - Coordinated movement X Y Z E <a href="https://reprap.org/wiki/G-code#G0_.26_G1:_Move">G0 & G1: Move</a>
  3821. In Prusa Firmware G0 and G1 are the same.
  3822. #### Usage
  3823. G0 [ X | Y | Z | E | F | S ]
  3824. G1 [ X | Y | Z | E | F | S ]
  3825. #### Parameters
  3826. - `X` - The position to move to on the X axis
  3827. - `Y` - The position to move to on the Y axis
  3828. - `Z` - The position to move to on the Z axis
  3829. - `E` - The amount to extrude between the starting point and ending point
  3830. - `F` - The feedrate per minute of the move between the starting point and ending point (if supplied)
  3831. */
  3832. case 0: // G0 -> G1
  3833. case 1: // G1
  3834. {
  3835. uint16_t start_segment_idx = restore_interrupted_gcode();
  3836. get_coordinates(); // For X Y Z E F
  3837. if (total_filament_used > ((current_position[E_AXIS] - destination[E_AXIS]) * 100)) { //protection against total_filament_used overflow
  3838. total_filament_used = total_filament_used + ((destination[E_AXIS] - current_position[E_AXIS]) * 100);
  3839. }
  3840. #ifdef FWRETRACT
  3841. if(cs.autoretract_enabled) {
  3842. if( !(code_seen('X') || code_seen('Y') || code_seen('Z')) && code_seen('E')) {
  3843. float echange=destination[E_AXIS]-current_position[E_AXIS];
  3844. if((echange<-MIN_RETRACT && !retracted[active_extruder]) || (echange>MIN_RETRACT && retracted[active_extruder])) { //move appears to be an attempt to retract or recover
  3845. st_synchronize();
  3846. current_position[E_AXIS] = destination[E_AXIS]; //hide the slicer-generated retract/recover from calculations
  3847. plan_set_e_position(current_position[E_AXIS]); //AND from the planner
  3848. retract(!retracted[active_extruder]);
  3849. return;
  3850. }
  3851. }
  3852. }
  3853. #endif //FWRETRACT
  3854. prepare_move(start_segment_idx);
  3855. //ClearToSend();
  3856. }
  3857. break;
  3858. /*!
  3859. ### G2, G3 - Controlled Arc Move <a href="https://reprap.org/wiki/G-code#G2_.26_G3:_Controlled_Arc_Move">G2 & G3: Controlled Arc Move</a>
  3860. These commands don't propperly work with MBL enabled. The compensation only happens at the end of the move, so avoid long arcs.
  3861. #### Usage
  3862. G2 [ X | Y | I | E | F ] (Clockwise Arc)
  3863. G3 [ X | Y | I | E | F ] (Counter-Clockwise Arc)
  3864. #### Parameters
  3865. - `X` - The position to move to on the X axis
  3866. - `Y` - The position to move to on the Y axis
  3867. - 'Z' - The position to move to on the Z axis
  3868. - `I` - The point in X space from the current X position to maintain a constant distance from
  3869. - `J` - The point in Y space from the current Y position to maintain a constant distance from
  3870. - `E` - The amount to extrude between the starting point and ending point
  3871. - `F` - The feedrate per minute of the move between the starting point and ending point (if supplied)
  3872. */
  3873. case 2:
  3874. case 3:
  3875. {
  3876. uint16_t start_segment_idx = restore_interrupted_gcode();
  3877. #ifdef SF_ARC_FIX
  3878. bool relative_mode_backup = relative_mode;
  3879. relative_mode = true;
  3880. #endif
  3881. get_coordinates(); // For X Y Z E F
  3882. #ifdef SF_ARC_FIX
  3883. relative_mode=relative_mode_backup;
  3884. #endif
  3885. offset[0] = code_seen('I') ? code_value() : 0.f;
  3886. offset[1] = code_seen('J') ? code_value() : 0.f;
  3887. prepare_arc_move((gcode_in_progress == 2), start_segment_idx);
  3888. } break;
  3889. /*!
  3890. ### G4 - Dwell <a href="https://reprap.org/wiki/G-code#G4:_Dwell">G4: Dwell</a>
  3891. Pause the machine for a period of time.
  3892. #### Usage
  3893. G4 [ P | S ]
  3894. #### Parameters
  3895. - `P` - Time to wait, in milliseconds
  3896. - `S` - Time to wait, in seconds
  3897. */
  3898. case 4:
  3899. codenum = 0;
  3900. if(code_seen('P')) codenum = code_value(); // milliseconds to wait
  3901. if(code_seen('S')) codenum = code_value() * 1000; // seconds to wait
  3902. if(codenum != 0)
  3903. {
  3904. if(custom_message_type != CustomMsg::M117)
  3905. {
  3906. LCD_MESSAGERPGM(_n("Sleep..."));////MSG_DWELL
  3907. }
  3908. }
  3909. st_synchronize();
  3910. codenum += _millis(); // keep track of when we started waiting
  3911. previous_millis_cmd.start();
  3912. while(_millis() < codenum) {
  3913. manage_heater();
  3914. manage_inactivity();
  3915. lcd_update(0);
  3916. }
  3917. break;
  3918. #ifdef FWRETRACT
  3919. /*!
  3920. ### G10 - Retract <a href="https://reprap.org/wiki/G-code#G10:_Retract">G10: Retract</a>
  3921. Retracts filament according to settings of `M207`
  3922. */
  3923. case 10:
  3924. #if EXTRUDERS > 1
  3925. retracted_swap[active_extruder]=(code_seen('S') && code_value_long() == 1); // checks for swap retract argument
  3926. retract(true,retracted_swap[active_extruder]);
  3927. #else
  3928. retract(true);
  3929. #endif
  3930. break;
  3931. /*!
  3932. ### G11 - Retract recover <a href="https://reprap.org/wiki/G-code#G11:_Unretract">G11: Unretract</a>
  3933. Unretracts/recovers filament according to settings of `M208`
  3934. */
  3935. case 11:
  3936. #if EXTRUDERS > 1
  3937. retract(false,retracted_swap[active_extruder]);
  3938. #else
  3939. retract(false);
  3940. #endif
  3941. break;
  3942. #endif //FWRETRACT
  3943. /*!
  3944. ### G21 - Sets Units to Millimters <a href="https://reprap.org/wiki/G-code#G21:_Set_Units_to_Millimeters">G21: Set Units to Millimeters</a>
  3945. Units are in millimeters. Prusa doesn't support inches.
  3946. */
  3947. case 21:
  3948. break; //Doing nothing. This is just to prevent serial UNKOWN warnings.
  3949. /*!
  3950. ### G28 - Home all Axes one at a time <a href="https://reprap.org/wiki/G-code#G28:_Move_to_Origin_.28Home.29">G28: Move to Origin (Home)</a>
  3951. Using `G28` without any parameters will perfom homing of all axes AND mesh bed leveling, while `G28 W` will just home all axes (no mesh bed leveling).
  3952. #### Usage
  3953. G28 [ X | Y | Z | W | C ]
  3954. #### Parameters
  3955. - `X` - Flag to go back to the X axis origin
  3956. - `Y` - Flag to go back to the Y axis origin
  3957. - `Z` - Flag to go back to the Z axis origin
  3958. - `W` - Suppress mesh bed leveling if `X`, `Y` or `Z` are not provided
  3959. - `C` - Calibrate X and Y origin (home) - Only on MK3/s
  3960. */
  3961. case 28:
  3962. {
  3963. long home_x_value = 0;
  3964. long home_y_value = 0;
  3965. long home_z_value = 0;
  3966. // Which axes should be homed?
  3967. bool home_x = code_seen(axis_codes[X_AXIS]);
  3968. if (home_x) home_x_value = code_value_long();
  3969. bool home_y = code_seen(axis_codes[Y_AXIS]);
  3970. if (home_y) home_y_value = code_value_long();
  3971. bool home_z = code_seen(axis_codes[Z_AXIS]);
  3972. if (home_z) home_z_value = code_value_long();
  3973. bool without_mbl = code_seen('W');
  3974. // calibrate?
  3975. #ifdef TMC2130
  3976. bool calib = code_seen('C');
  3977. gcode_G28(home_x, home_x_value, home_y, home_y_value, home_z, home_z_value, calib, without_mbl);
  3978. #else
  3979. gcode_G28(home_x, home_x_value, home_y, home_y_value, home_z, home_z_value, without_mbl);
  3980. #endif //TMC2130
  3981. if ((home_x || home_y || without_mbl || home_z) == false) {
  3982. gcode_G80();
  3983. }
  3984. break;
  3985. }
  3986. #ifdef ENABLE_AUTO_BED_LEVELING
  3987. /*!
  3988. ### G29 - Detailed Z-Probe <a href="https://reprap.org/wiki/G-code#G29:_Detailed_Z-Probe">G29: Detailed Z-Probe</a>
  3989. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  3990. See `G81`
  3991. */
  3992. case 29:
  3993. {
  3994. #if Z_MIN_PIN == -1
  3995. #error "You must have a Z_MIN endstop in order to enable Auto Bed Leveling feature! Z_MIN_PIN must point to a valid hardware pin."
  3996. #endif
  3997. // Prevent user from running a G29 without first homing in X and Y
  3998. if (! (axis_known_position[X_AXIS] && axis_known_position[Y_AXIS]) )
  3999. {
  4000. LCD_MESSAGERPGM(MSG_POSITION_UNKNOWN);
  4001. SERIAL_ECHO_START;
  4002. SERIAL_ECHOLNRPGM(MSG_POSITION_UNKNOWN);
  4003. break; // abort G29, since we don't know where we are
  4004. }
  4005. st_synchronize();
  4006. // make sure the bed_level_rotation_matrix is identity or the planner will get it incorectly
  4007. //vector_3 corrected_position = plan_get_position_mm();
  4008. //corrected_position.debug("position before G29");
  4009. plan_bed_level_matrix.set_to_identity();
  4010. vector_3 uncorrected_position = plan_get_position();
  4011. //uncorrected_position.debug("position durring G29");
  4012. current_position[X_AXIS] = uncorrected_position.x;
  4013. current_position[Y_AXIS] = uncorrected_position.y;
  4014. current_position[Z_AXIS] = uncorrected_position.z;
  4015. plan_set_position_curposXYZE();
  4016. int l_feedmultiply = setup_for_endstop_move();
  4017. feedrate = homing_feedrate[Z_AXIS];
  4018. #ifdef AUTO_BED_LEVELING_GRID
  4019. // probe at the points of a lattice grid
  4020. int xGridSpacing = (RIGHT_PROBE_BED_POSITION - LEFT_PROBE_BED_POSITION) / (AUTO_BED_LEVELING_GRID_POINTS-1);
  4021. int yGridSpacing = (BACK_PROBE_BED_POSITION - FRONT_PROBE_BED_POSITION) / (AUTO_BED_LEVELING_GRID_POINTS-1);
  4022. // solve the plane equation ax + by + d = z
  4023. // A is the matrix with rows [x y 1] for all the probed points
  4024. // B is the vector of the Z positions
  4025. // 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
  4026. // so Vx = -a Vy = -b Vz = 1 (we want the vector facing towards positive Z
  4027. // "A" matrix of the linear system of equations
  4028. double eqnAMatrix[AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS*3];
  4029. // "B" vector of Z points
  4030. double eqnBVector[AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS];
  4031. int probePointCounter = 0;
  4032. bool zig = true;
  4033. for (int yProbe=FRONT_PROBE_BED_POSITION; yProbe <= BACK_PROBE_BED_POSITION; yProbe += yGridSpacing)
  4034. {
  4035. int xProbe, xInc;
  4036. if (zig)
  4037. {
  4038. xProbe = LEFT_PROBE_BED_POSITION;
  4039. //xEnd = RIGHT_PROBE_BED_POSITION;
  4040. xInc = xGridSpacing;
  4041. zig = false;
  4042. } else // zag
  4043. {
  4044. xProbe = RIGHT_PROBE_BED_POSITION;
  4045. //xEnd = LEFT_PROBE_BED_POSITION;
  4046. xInc = -xGridSpacing;
  4047. zig = true;
  4048. }
  4049. for (int xCount=0; xCount < AUTO_BED_LEVELING_GRID_POINTS; xCount++)
  4050. {
  4051. float z_before;
  4052. if (probePointCounter == 0)
  4053. {
  4054. // raise before probing
  4055. z_before = Z_RAISE_BEFORE_PROBING;
  4056. } else
  4057. {
  4058. // raise extruder
  4059. z_before = current_position[Z_AXIS] + Z_RAISE_BETWEEN_PROBINGS;
  4060. }
  4061. float measured_z = probe_pt(xProbe, yProbe, z_before);
  4062. eqnBVector[probePointCounter] = measured_z;
  4063. eqnAMatrix[probePointCounter + 0*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = xProbe;
  4064. eqnAMatrix[probePointCounter + 1*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = yProbe;
  4065. eqnAMatrix[probePointCounter + 2*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = 1;
  4066. probePointCounter++;
  4067. xProbe += xInc;
  4068. }
  4069. }
  4070. clean_up_after_endstop_move(l_feedmultiply);
  4071. // solve lsq problem
  4072. double *plane_equation_coefficients = qr_solve(AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS, 3, eqnAMatrix, eqnBVector);
  4073. SERIAL_PROTOCOLPGM("Eqn coefficients: a: ");
  4074. SERIAL_PROTOCOL(plane_equation_coefficients[0]);
  4075. SERIAL_PROTOCOLPGM(" b: ");
  4076. SERIAL_PROTOCOL(plane_equation_coefficients[1]);
  4077. SERIAL_PROTOCOLPGM(" d: ");
  4078. SERIAL_PROTOCOLLN(plane_equation_coefficients[2]);
  4079. set_bed_level_equation_lsq(plane_equation_coefficients);
  4080. free(plane_equation_coefficients);
  4081. #else // AUTO_BED_LEVELING_GRID not defined
  4082. // Probe at 3 arbitrary points
  4083. // probe 1
  4084. float z_at_pt_1 = probe_pt(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, Z_RAISE_BEFORE_PROBING);
  4085. // probe 2
  4086. float z_at_pt_2 = probe_pt(ABL_PROBE_PT_2_X, ABL_PROBE_PT_2_Y, current_position[Z_AXIS] + Z_RAISE_BETWEEN_PROBINGS);
  4087. // probe 3
  4088. float z_at_pt_3 = probe_pt(ABL_PROBE_PT_3_X, ABL_PROBE_PT_3_Y, current_position[Z_AXIS] + Z_RAISE_BETWEEN_PROBINGS);
  4089. clean_up_after_endstop_move(l_feedmultiply);
  4090. set_bed_level_equation_3pts(z_at_pt_1, z_at_pt_2, z_at_pt_3);
  4091. #endif // AUTO_BED_LEVELING_GRID
  4092. st_synchronize();
  4093. // The following code correct the Z height difference from z-probe position and hotend tip position.
  4094. // The Z height on homing is measured by Z-Probe, but the probe is quite far from the hotend.
  4095. // When the bed is uneven, this height must be corrected.
  4096. real_z = float(st_get_position(Z_AXIS))/cs.axis_steps_per_unit[Z_AXIS]; //get the real Z (since the auto bed leveling is already correcting the plane)
  4097. x_tmp = current_position[X_AXIS] + X_PROBE_OFFSET_FROM_EXTRUDER;
  4098. y_tmp = current_position[Y_AXIS] + Y_PROBE_OFFSET_FROM_EXTRUDER;
  4099. z_tmp = current_position[Z_AXIS];
  4100. apply_rotation_xyz(plan_bed_level_matrix, x_tmp, y_tmp, z_tmp); //Apply the correction sending the probe offset
  4101. current_position[Z_AXIS] = z_tmp - real_z + current_position[Z_AXIS]; //The difference is added to current position and sent to planner.
  4102. plan_set_position_curposXYZE();
  4103. }
  4104. break;
  4105. #ifndef Z_PROBE_SLED
  4106. /*!
  4107. ### G30 - Single Z Probe <a href="https://reprap.org/wiki/G-code#G30:_Single_Z-Probe">G30: Single Z-Probe</a>
  4108. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4109. */
  4110. case 30:
  4111. {
  4112. st_synchronize();
  4113. // TODO: make sure the bed_level_rotation_matrix is identity or the planner will get set incorectly
  4114. int l_feedmultiply = setup_for_endstop_move();
  4115. feedrate = homing_feedrate[Z_AXIS];
  4116. run_z_probe();
  4117. SERIAL_PROTOCOLPGM(_T(MSG_BED));
  4118. SERIAL_PROTOCOLPGM(" X: ");
  4119. SERIAL_PROTOCOL(current_position[X_AXIS]);
  4120. SERIAL_PROTOCOLPGM(" Y: ");
  4121. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  4122. SERIAL_PROTOCOLPGM(" Z: ");
  4123. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  4124. SERIAL_PROTOCOLPGM("\n");
  4125. clean_up_after_endstop_move(l_feedmultiply);
  4126. }
  4127. break;
  4128. #else
  4129. /*!
  4130. ### G31 - Dock the sled <a href="https://reprap.org/wiki/G-code#G31:_Dock_Z_Probe_sled">G31: Dock Z Probe sled</a>
  4131. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4132. */
  4133. case 31:
  4134. dock_sled(true);
  4135. break;
  4136. /*!
  4137. ### G32 - Undock the sled <a href="https://reprap.org/wiki/G-code#G32:_Undock_Z_Probe_sled">G32: Undock Z Probe sled</a>
  4138. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4139. */
  4140. case 32:
  4141. dock_sled(false);
  4142. break;
  4143. #endif // Z_PROBE_SLED
  4144. #endif // ENABLE_AUTO_BED_LEVELING
  4145. #ifdef MESH_BED_LEVELING
  4146. /*!
  4147. ### G30 - Single Z Probe <a href="https://reprap.org/wiki/G-code#G30:_Single_Z-Probe">G30: Single Z-Probe</a>
  4148. Sensor must be over the bed.
  4149. The maximum travel distance before an error is triggered is 10mm.
  4150. */
  4151. case 30:
  4152. {
  4153. st_synchronize();
  4154. homing_flag = true;
  4155. // TODO: make sure the bed_level_rotation_matrix is identity or the planner will get set incorectly
  4156. int l_feedmultiply = setup_for_endstop_move();
  4157. feedrate = homing_feedrate[Z_AXIS];
  4158. find_bed_induction_sensor_point_z(-10.f, 3);
  4159. printf_P(_N("%S X: %.5f Y: %.5f Z: %.5f\n"), _T(MSG_BED), _x, _y, _z);
  4160. clean_up_after_endstop_move(l_feedmultiply);
  4161. homing_flag = false;
  4162. }
  4163. break;
  4164. /*!
  4165. ### G75 - Print temperature interpolation <a href="https://reprap.org/wiki/G-code#G75:_Print_temperature_interpolation">G75: Print temperature interpolation</a>
  4166. Show/print PINDA temperature interpolating.
  4167. */
  4168. case 75:
  4169. {
  4170. for (uint8_t i = 40; i <= 110; i++)
  4171. printf_P(_N("%d %.2f"), i, temp_comp_interpolation(i));
  4172. }
  4173. break;
  4174. /*!
  4175. ### G76 - PINDA probe temperature calibration <a href="https://reprap.org/wiki/G-code#G76:_PINDA_probe_temperature_calibration">G76: PINDA probe temperature calibration</a>
  4176. This G-code is used to calibrate the temperature drift of the PINDA (inductive Sensor).
  4177. The PINDAv2 sensor has a built-in thermistor which has the advantage that the calibration can be done once for all materials.
  4178. The Original i3 Prusa MK2/s uses PINDAv1 and this calibration improves the temperature drift, but not as good as the PINDAv2.
  4179. superPINDA sensor has internal temperature compensation and no thermistor output. There is no point of doing temperature calibration in such case.
  4180. If PINDA_THERMISTOR and SUPERPINDA_SUPPORT is defined during compilation, calibration is skipped with serial message "No PINDA thermistor".
  4181. This can be caused also if PINDA thermistor connection is broken or PINDA temperature is lower than PINDA_MINTEMP.
  4182. #### Example
  4183. ```
  4184. G76
  4185. echo PINDA probe calibration start
  4186. echo start temperature: 35.0°
  4187. echo ...
  4188. echo PINDA temperature -- Z shift (mm): 0.---
  4189. ```
  4190. */
  4191. case 76:
  4192. {
  4193. #ifdef PINDA_THERMISTOR
  4194. if (!has_temperature_compensation())
  4195. {
  4196. SERIAL_ECHOLNPGM("No PINDA thermistor");
  4197. break;
  4198. }
  4199. if (calibration_status() >= CALIBRATION_STATUS_XYZ_CALIBRATION) {
  4200. //we need to know accurate position of first calibration point
  4201. //if xyz calibration was not performed yet, interrupt temperature calibration and inform user that xyz cal. is needed
  4202. lcd_show_fullscreen_message_and_wait_P(_i("Please run XYZ calibration first.")); ////MSG_RUN_XYZ c=20 r=4
  4203. break;
  4204. }
  4205. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS]))
  4206. {
  4207. // We don't know where we are! HOME!
  4208. // Push the commands to the front of the message queue in the reverse order!
  4209. // There shall be always enough space reserved for these commands.
  4210. repeatcommand_front(); // repeat G76 with all its parameters
  4211. enquecommand_front_P(G28W0);
  4212. break;
  4213. }
  4214. lcd_show_fullscreen_message_and_wait_P(_i("Stable ambient temperature 21-26C is needed a rigid stand is required."));////MSG_TEMP_CAL_WARNING c=20 r=4
  4215. uint8_t result = lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_STEEL_SHEET_CHECK), false);
  4216. if (result == LCD_LEFT_BUTTON_CHOICE)
  4217. {
  4218. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4219. plan_buffer_line_curposXYZE(3000 / 60);
  4220. current_position[Z_AXIS] = 50;
  4221. current_position[Y_AXIS] = 180;
  4222. plan_buffer_line_curposXYZE(3000 / 60);
  4223. st_synchronize();
  4224. lcd_show_fullscreen_message_and_wait_P(_T(MSG_REMOVE_STEEL_SHEET));
  4225. current_position[Y_AXIS] = pgm_read_float(bed_ref_points_4 + 1);
  4226. current_position[X_AXIS] = pgm_read_float(bed_ref_points_4);
  4227. plan_buffer_line_curposXYZE(3000 / 60);
  4228. st_synchronize();
  4229. gcode_G28(false, false, true);
  4230. }
  4231. if ((current_temperature_pinda > 35) && (farm_mode == false)) {
  4232. //waiting for PIDNA probe to cool down in case that we are not in farm mode
  4233. current_position[Z_AXIS] = 100;
  4234. plan_buffer_line_curposXYZE(3000 / 60);
  4235. if (lcd_wait_for_pinda(35) == false) { //waiting for PINDA probe to cool, if this takes more then time expected, temp. cal. fails
  4236. lcd_temp_cal_show_result(false);
  4237. break;
  4238. }
  4239. }
  4240. st_synchronize();
  4241. homing_flag = true; // keep homing on to avoid babystepping while the LCD is enabled
  4242. lcd_update_enable(true);
  4243. SERIAL_ECHOLNPGM("PINDA probe calibration start");
  4244. float zero_z;
  4245. int z_shift = 0; //unit: steps
  4246. float start_temp = 5 * (int)(current_temperature_pinda / 5);
  4247. if (start_temp < 35) start_temp = 35;
  4248. if (start_temp < current_temperature_pinda) start_temp += 5;
  4249. printf_P(_N("start temperature: %.1f\n"), start_temp);
  4250. // setTargetHotend(200, 0);
  4251. setTargetBed(70 + (start_temp - 30));
  4252. custom_message_type = CustomMsg::TempCal;
  4253. custom_message_state = 1;
  4254. lcd_setstatuspgm(_T(MSG_PINDA_CALIBRATION));
  4255. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4256. plan_buffer_line_curposXYZE(3000 / 60);
  4257. current_position[X_AXIS] = PINDA_PREHEAT_X;
  4258. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  4259. plan_buffer_line_curposXYZE(3000 / 60);
  4260. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  4261. plan_buffer_line_curposXYZE(3000 / 60);
  4262. st_synchronize();
  4263. while (current_temperature_pinda < start_temp)
  4264. {
  4265. delay_keep_alive(1000);
  4266. serialecho_temperatures();
  4267. }
  4268. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0); //invalidate temp. calibration in case that in will be aborted during the calibration process
  4269. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4270. plan_buffer_line_curposXYZE(3000 / 60);
  4271. current_position[X_AXIS] = pgm_read_float(bed_ref_points_4);
  4272. current_position[Y_AXIS] = pgm_read_float(bed_ref_points_4 + 1);
  4273. plan_buffer_line_curposXYZE(3000 / 60);
  4274. st_synchronize();
  4275. bool find_z_result = find_bed_induction_sensor_point_z(-1.f);
  4276. if (find_z_result == false) {
  4277. lcd_temp_cal_show_result(find_z_result);
  4278. homing_flag = false;
  4279. break;
  4280. }
  4281. zero_z = current_position[Z_AXIS];
  4282. printf_P(_N("\nZERO: %.3f\n"), current_position[Z_AXIS]);
  4283. int i = -1; for (; i < 5; i++)
  4284. {
  4285. float temp = (40 + i * 5);
  4286. printf_P(_N("\nStep: %d/6 (skipped)\nPINDA temperature: %d Z shift (mm):0\n"), i + 2, (40 + i*5));
  4287. if (i >= 0) {
  4288. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  4289. }
  4290. if (start_temp <= temp) break;
  4291. }
  4292. for (i++; i < 5; i++)
  4293. {
  4294. float temp = (40 + i * 5);
  4295. printf_P(_N("\nStep: %d/6\n"), i + 2);
  4296. custom_message_state = i + 2;
  4297. setTargetBed(50 + 10 * (temp - 30) / 5);
  4298. // setTargetHotend(255, 0);
  4299. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4300. plan_buffer_line_curposXYZE(3000 / 60);
  4301. current_position[X_AXIS] = PINDA_PREHEAT_X;
  4302. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  4303. plan_buffer_line_curposXYZE(3000 / 60);
  4304. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  4305. plan_buffer_line_curposXYZE(3000 / 60);
  4306. st_synchronize();
  4307. while (current_temperature_pinda < temp)
  4308. {
  4309. delay_keep_alive(1000);
  4310. serialecho_temperatures();
  4311. }
  4312. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4313. plan_buffer_line_curposXYZE(3000 / 60);
  4314. current_position[X_AXIS] = pgm_read_float(bed_ref_points_4);
  4315. current_position[Y_AXIS] = pgm_read_float(bed_ref_points_4 + 1);
  4316. plan_buffer_line_curposXYZE(3000 / 60);
  4317. st_synchronize();
  4318. find_z_result = find_bed_induction_sensor_point_z(-1.f);
  4319. if (find_z_result == false) {
  4320. lcd_temp_cal_show_result(find_z_result);
  4321. break;
  4322. }
  4323. z_shift = (int)((current_position[Z_AXIS] - zero_z)*cs.axis_steps_per_unit[Z_AXIS]);
  4324. printf_P(_N("\nPINDA temperature: %.1f Z shift (mm): %.3f"), current_temperature_pinda, current_position[Z_AXIS] - zero_z);
  4325. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  4326. }
  4327. lcd_temp_cal_show_result(true);
  4328. homing_flag = false;
  4329. #else //PINDA_THERMISTOR
  4330. setTargetBed(PINDA_MIN_T);
  4331. float zero_z;
  4332. int z_shift = 0; //unit: steps
  4333. int t_c; // temperature
  4334. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  4335. // We don't know where we are! HOME!
  4336. // Push the commands to the front of the message queue in the reverse order!
  4337. // There shall be always enough space reserved for these commands.
  4338. repeatcommand_front(); // repeat G76 with all its parameters
  4339. enquecommand_front_P(G28W0);
  4340. break;
  4341. }
  4342. puts_P(_N("PINDA probe calibration start"));
  4343. custom_message_type = CustomMsg::TempCal;
  4344. custom_message_state = 1;
  4345. lcd_setstatuspgm(_T(MSG_PINDA_CALIBRATION));
  4346. current_position[X_AXIS] = PINDA_PREHEAT_X;
  4347. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  4348. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  4349. plan_buffer_line_curposXYZE(3000 / 60);
  4350. st_synchronize();
  4351. while (fabs(degBed() - PINDA_MIN_T) > 1) {
  4352. delay_keep_alive(1000);
  4353. serialecho_temperatures();
  4354. }
  4355. //enquecommand_P(PSTR("M190 S50"));
  4356. for (int i = 0; i < PINDA_HEAT_T; i++) {
  4357. delay_keep_alive(1000);
  4358. serialecho_temperatures();
  4359. }
  4360. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0); //invalidate temp. calibration in case that in will be aborted during the calibration process
  4361. current_position[Z_AXIS] = 5;
  4362. plan_buffer_line_curposXYZE(3000 / 60);
  4363. current_position[X_AXIS] = BED_X0;
  4364. current_position[Y_AXIS] = BED_Y0;
  4365. plan_buffer_line_curposXYZE(3000 / 60);
  4366. st_synchronize();
  4367. find_bed_induction_sensor_point_z(-1.f);
  4368. zero_z = current_position[Z_AXIS];
  4369. printf_P(_N("\nZERO: %.3f\n"), current_position[Z_AXIS]);
  4370. for (int i = 0; i<5; i++) {
  4371. printf_P(_N("\nStep: %d/6\n"), i + 2);
  4372. custom_message_state = i + 2;
  4373. t_c = 60 + i * 10;
  4374. setTargetBed(t_c);
  4375. current_position[X_AXIS] = PINDA_PREHEAT_X;
  4376. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  4377. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  4378. plan_buffer_line_curposXYZE(3000 / 60);
  4379. st_synchronize();
  4380. while (degBed() < t_c) {
  4381. delay_keep_alive(1000);
  4382. serialecho_temperatures();
  4383. }
  4384. for (int i = 0; i < PINDA_HEAT_T; i++) {
  4385. delay_keep_alive(1000);
  4386. serialecho_temperatures();
  4387. }
  4388. current_position[Z_AXIS] = 5;
  4389. plan_buffer_line_curposXYZE(3000 / 60);
  4390. current_position[X_AXIS] = BED_X0;
  4391. current_position[Y_AXIS] = BED_Y0;
  4392. plan_buffer_line_curposXYZE(3000 / 60);
  4393. st_synchronize();
  4394. find_bed_induction_sensor_point_z(-1.f);
  4395. z_shift = (int)((current_position[Z_AXIS] - zero_z)*cs.axis_steps_per_unit[Z_AXIS]);
  4396. printf_P(_N("\nTemperature: %d Z shift (mm): %.3f\n"), t_c, current_position[Z_AXIS] - zero_z);
  4397. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  4398. }
  4399. custom_message_type = CustomMsg::Status;
  4400. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  4401. puts_P(_N("Temperature calibration done."));
  4402. disable_x();
  4403. disable_y();
  4404. disable_z();
  4405. disable_e0();
  4406. disable_e1();
  4407. disable_e2();
  4408. setTargetBed(0); //set bed target temperature back to 0
  4409. lcd_show_fullscreen_message_and_wait_P(_T(MSG_PINDA_CALIBRATION_DONE));
  4410. eeprom_update_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE, 1);
  4411. lcd_update_enable(true);
  4412. lcd_update(2);
  4413. #endif //PINDA_THERMISTOR
  4414. }
  4415. break;
  4416. /*!
  4417. ### G80 - Mesh-based Z probe <a href="https://reprap.org/wiki/G-code#G80:_Mesh-based_Z_probe">G80: Mesh-based Z probe</a>
  4418. Default 3x3 grid can be changed on MK2.5/s and MK3/s to 7x7 grid.
  4419. #### Usage
  4420. G80 [ N | R | V | L | R | F | B ]
  4421. #### Parameters
  4422. - `N` - Number of mesh points on x axis. Default is 3. Valid values are 3 and 7.
  4423. - `R` - Probe retries. Default 3 max. 10
  4424. - `V` - Verbosity level 1=low, 10=mid, 20=high. It only can be used if the firmware has been compiled with SUPPORT_VERBOSITY active.
  4425. Using the following parameters enables additional "manual" bed leveling correction. Valid values are -100 microns to 100 microns.
  4426. #### Additional Parameters
  4427. - `L` - Left Bed Level correct value in um.
  4428. - `R` - Right Bed Level correct value in um.
  4429. - `F` - Front Bed Level correct value in um.
  4430. - `B` - Back Bed Level correct value in um.
  4431. */
  4432. /*
  4433. * Probes a grid and produces a mesh to compensate for variable bed height
  4434. * The S0 report the points as below
  4435. * +----> X-axis
  4436. * |
  4437. * |
  4438. * v Y-axis
  4439. */
  4440. case 80: {
  4441. gcode_G80();
  4442. }
  4443. break;
  4444. /*!
  4445. ### G81 - Mesh bed leveling status <a href="https://reprap.org/wiki/G-code#G81:_Mesh_bed_leveling_status">G81: Mesh bed leveling status</a>
  4446. Prints mesh bed leveling status and bed profile if activated.
  4447. */
  4448. case 81:
  4449. if (mbl.active) {
  4450. SERIAL_PROTOCOLPGM("Num X,Y: ");
  4451. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  4452. SERIAL_PROTOCOL(',');
  4453. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  4454. SERIAL_PROTOCOLPGM("\nZ search height: ");
  4455. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  4456. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  4457. for (uint8_t y = MESH_NUM_Y_POINTS; y-- > 0;) {
  4458. for (uint8_t x = 0; x < MESH_NUM_X_POINTS; x++) {
  4459. SERIAL_PROTOCOLPGM(" ");
  4460. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  4461. }
  4462. SERIAL_PROTOCOLLN();
  4463. }
  4464. }
  4465. else
  4466. SERIAL_PROTOCOLLNPGM("Mesh bed leveling not active.");
  4467. break;
  4468. #if 0
  4469. /*!
  4470. ### G82: Single Z probe at current location - Not active <a href="https://reprap.org/wiki/G-code#G82:_Single_Z_probe_at_current_location">G82: Single Z probe at current location</a>
  4471. WARNING! USE WITH CAUTION! If you'll try to probe where is no leveling pad, nasty things can happen!
  4472. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4473. */
  4474. case 82:
  4475. SERIAL_PROTOCOLLNPGM("Finding bed ");
  4476. int l_feedmultiply = setup_for_endstop_move();
  4477. find_bed_induction_sensor_point_z();
  4478. clean_up_after_endstop_move(l_feedmultiply);
  4479. SERIAL_PROTOCOLPGM("Bed found at: ");
  4480. SERIAL_PROTOCOL_F(current_position[Z_AXIS], 5);
  4481. SERIAL_PROTOCOLPGM("\n");
  4482. break;
  4483. /*!
  4484. ### G83: Babystep in Z and store to EEPROM - Not active <a href="https://reprap.org/wiki/G-code#G83:_Babystep_in_Z_and_store_to_EEPROM">G83: Babystep in Z and store to EEPROM</a>
  4485. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4486. */
  4487. case 83:
  4488. {
  4489. int babystepz = code_seen('S') ? code_value() : 0;
  4490. int BabyPosition = code_seen('P') ? code_value() : 0;
  4491. if (babystepz != 0) {
  4492. //FIXME Vojtech: What shall be the index of the axis Z: 3 or 4?
  4493. // Is the axis indexed starting with zero or one?
  4494. if (BabyPosition > 4) {
  4495. SERIAL_PROTOCOLLNPGM("Index out of bounds");
  4496. }else{
  4497. // Save it to the eeprom
  4498. babystepLoadZ = babystepz;
  4499. eeprom_update_word((uint16_t*)EEPROM_BABYSTEP_Z0 + BabyPosition, babystepLoadZ);
  4500. // adjust the Z
  4501. babystepsTodoZadd(babystepLoadZ);
  4502. }
  4503. }
  4504. }
  4505. break;
  4506. /*!
  4507. ### G84: UNDO Babystep Z (move Z axis back) - Not active <a href="https://reprap.org/wiki/G-code#G84:_UNDO_Babystep_Z_.28move_Z_axis_back.29">G84: UNDO Babystep Z (move Z axis back)</a>
  4508. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4509. */
  4510. case 84:
  4511. babystepsTodoZsubtract(babystepLoadZ);
  4512. // babystepLoadZ = 0;
  4513. break;
  4514. /*!
  4515. ### G85: Pick best babystep - Not active <a href="https://reprap.org/wiki/G-code#G85:_Pick_best_babystep">G85: Pick best babystep</a>
  4516. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4517. */
  4518. case 85:
  4519. lcd_pick_babystep();
  4520. break;
  4521. #endif
  4522. /*!
  4523. ### G86 - Disable babystep correction after home <a href="https://reprap.org/wiki/G-code#G86:_Disable_babystep_correction_after_home">G86: Disable babystep correction after home</a>
  4524. This G-code will be performed at the start of a calibration script.
  4525. (Prusa3D specific)
  4526. */
  4527. case 86:
  4528. calibration_status_store(CALIBRATION_STATUS_LIVE_ADJUST);
  4529. break;
  4530. /*!
  4531. ### G87 - Enable babystep correction after home <a href="https://reprap.org/wiki/G-code#G87:_Enable_babystep_correction_after_home">G87: Enable babystep correction after home</a>
  4532. This G-code will be performed at the end of a calibration script.
  4533. (Prusa3D specific)
  4534. */
  4535. case 87:
  4536. calibration_status_store(CALIBRATION_STATUS_CALIBRATED);
  4537. break;
  4538. /*!
  4539. ### G88 - Reserved <a href="https://reprap.org/wiki/G-code#G88:_Reserved">G88: Reserved</a>
  4540. Currently has no effect.
  4541. */
  4542. // Prusa3D specific: Don't know what it is for, it is in V2Calibration.gcode
  4543. case 88:
  4544. break;
  4545. #endif // ENABLE_MESH_BED_LEVELING
  4546. /*!
  4547. ### G90 - Switch off relative mode <a href="https://reprap.org/wiki/G-code#G90:_Set_to_Absolute_Positioning">G90: Set to Absolute Positioning</a>
  4548. All coordinates from now on are absolute relative to the origin of the machine. E axis is left intact.
  4549. */
  4550. case 90: {
  4551. axis_relative_modes &= ~(X_AXIS_MASK | Y_AXIS_MASK | Z_AXIS_MASK);
  4552. }
  4553. break;
  4554. /*!
  4555. ### G91 - Switch on relative mode <a href="https://reprap.org/wiki/G-code#G91:_Set_to_Relative_Positioning">G91: Set to Relative Positioning</a>
  4556. All coordinates from now on are relative to the last position. E axis is left intact.
  4557. */
  4558. case 91: {
  4559. axis_relative_modes |= X_AXIS_MASK | Y_AXIS_MASK | Z_AXIS_MASK;
  4560. }
  4561. break;
  4562. /*!
  4563. ### G92 - Set position <a href="https://reprap.org/wiki/G-code#G92:_Set_Position">G92: Set Position</a>
  4564. It is used for setting the current position of each axis. The parameters are always absolute to the origin.
  4565. If a parameter is omitted, that axis will not be affected.
  4566. If `X`, `Y`, or `Z` axis are specified, the move afterwards might stutter because of Mesh Bed Leveling. `E` axis is not affected if the target position is 0 (`G92 E0`).
  4567. A G92 without coordinates will reset all axes to zero on some firmware. This is not the case for Prusa-Firmware!
  4568. #### Usage
  4569. G92 [ X | Y | Z | E ]
  4570. #### Parameters
  4571. - `X` - new X axis position
  4572. - `Y` - new Y axis position
  4573. - `Z` - new Z axis position
  4574. - `E` - new extruder position
  4575. */
  4576. case 92: {
  4577. gcode_G92();
  4578. }
  4579. break;
  4580. #ifdef PRUSA_FARM
  4581. /*!
  4582. ### G98 - Activate farm mode <a href="https://reprap.org/wiki/G-code#G98:_Activate_farm_mode">G98: Activate farm mode</a>
  4583. Enable Prusa-specific Farm functions and g-code.
  4584. See Internal Prusa commands.
  4585. */
  4586. case 98:
  4587. farm_gcode_g98();
  4588. break;
  4589. /*! ### G99 - Deactivate farm mode <a href="https://reprap.org/wiki/G-code#G99:_Deactivate_farm_mode">G99: Deactivate farm mode</a>
  4590. Disables Prusa-specific Farm functions and g-code.
  4591. */
  4592. case 99:
  4593. farm_gcode_g99();
  4594. break;
  4595. #endif //PRUSA_FARM
  4596. default:
  4597. printf_P(MSG_UNKNOWN_CODE, 'G', cmdbuffer + bufindr + CMDHDRSIZE);
  4598. }
  4599. // printf_P(_N("END G-CODE=%u\n"), gcode_in_progress);
  4600. gcode_in_progress = 0;
  4601. } // end if(code_seen('G'))
  4602. /*!
  4603. ### End of G-Codes
  4604. */
  4605. /*!
  4606. ---------------------------------------------------------------------------------
  4607. # M Commands
  4608. */
  4609. else if(code_seen('M'))
  4610. {
  4611. int index;
  4612. for (index = 1; *(strchr_pointer + index) == ' ' || *(strchr_pointer + index) == '\t'; index++);
  4613. /*for (++strchr_pointer; *strchr_pointer == ' ' || *strchr_pointer == '\t'; ++strchr_pointer);*/
  4614. if (*(strchr_pointer+index) < '0' || *(strchr_pointer+index) > '9') {
  4615. printf_P(PSTR("Invalid M code: %s\n"), cmdbuffer + bufindr + CMDHDRSIZE);
  4616. } else
  4617. {
  4618. mcode_in_progress = code_value_short();
  4619. // printf_P(_N("BEGIN M-CODE=%u\n"), mcode_in_progress);
  4620. switch(mcode_in_progress)
  4621. {
  4622. /*!
  4623. ### M17 - Enable all axes <a href="https://reprap.org/wiki/G-code#M17:_Enable.2FPower_all_stepper_motors">M17: Enable/Power all stepper motors</a>
  4624. */
  4625. case 17:
  4626. LCD_MESSAGERPGM(_i("No move."));////MSG_NO_MOVE c=20
  4627. enable_x();
  4628. enable_y();
  4629. enable_z();
  4630. enable_e0();
  4631. enable_e1();
  4632. enable_e2();
  4633. break;
  4634. #ifdef SDSUPPORT
  4635. /*!
  4636. ### M20 - SD Card file list <a href="https://reprap.org/wiki/G-code#M20:_List_SD_card">M20: List SD card</a>
  4637. #### Usage
  4638. M20 [ L | T ]
  4639. #### Parameters
  4640. - `T` - Report timestamps as well. The value is one uint32_t encoded as hex. Requires host software parsing (Cap:EXTENDED_M20).
  4641. - `L` - Reports long filenames instead of just short filenames. Requires host software parsing (Cap:EXTENDED_M20).
  4642. */
  4643. case 20:
  4644. KEEPALIVE_STATE(NOT_BUSY); // do not send busy messages during listing. Inhibits the output of manage_heater()
  4645. SERIAL_PROTOCOLLNRPGM(_N("Begin file list"));////MSG_BEGIN_FILE_LIST
  4646. card.ls(CardReader::ls_param(code_seen('L'), code_seen('T')));
  4647. SERIAL_PROTOCOLLNRPGM(_N("End file list"));////MSG_END_FILE_LIST
  4648. break;
  4649. /*!
  4650. ### M21 - Init SD card <a href="https://reprap.org/wiki/G-code#M21:_Initialize_SD_card">M21: Initialize SD card</a>
  4651. */
  4652. case 21:
  4653. card.initsd();
  4654. break;
  4655. /*!
  4656. ### M22 - Release SD card <a href="https://reprap.org/wiki/G-code#M22:_Release_SD_card">M22: Release SD card</a>
  4657. */
  4658. case 22:
  4659. card.release();
  4660. break;
  4661. /*!
  4662. ### M23 - Select file <a href="https://reprap.org/wiki/G-code#M23:_Select_SD_file">M23: Select SD file</a>
  4663. #### Usage
  4664. M23 [filename]
  4665. */
  4666. case 23:
  4667. starpos = (strchr(strchr_pointer + 4,'*'));
  4668. if(starpos!=NULL)
  4669. *(starpos)='\0';
  4670. card.openFileReadFilteredGcode(strchr_pointer + 4, true);
  4671. break;
  4672. /*!
  4673. ### M24 - Start SD print <a href="https://reprap.org/wiki/G-code#M24:_Start.2Fresume_SD_print">M24: Start/resume SD print</a>
  4674. */
  4675. case 24:
  4676. if (isPrintPaused)
  4677. lcd_resume_print();
  4678. else
  4679. {
  4680. if (!card.get_sdpos())
  4681. {
  4682. // A new print has started from scratch, reset stats
  4683. failstats_reset_print();
  4684. sdpos_atomic = 0;
  4685. #ifndef LA_NOCOMPAT
  4686. la10c_reset();
  4687. #endif
  4688. }
  4689. card.startFileprint();
  4690. starttime=_millis();
  4691. if (MMU2::mmu2.Enabled())
  4692. {
  4693. if (MMU2::mmu2.FindaDetectsFilament() && !fsensor.getFilamentPresent())
  4694. { // Filament only half way into the PTFE. Unload the filament.
  4695. MMU2::mmu2.unload();
  4696. // Tx and Tc gcodes take care of loading the filament to the nozzle.
  4697. }
  4698. }
  4699. }
  4700. break;
  4701. /*!
  4702. ### M26 - Set SD index <a href="https://reprap.org/wiki/G-code#M26:_Set_SD_position">M26: Set SD position</a>
  4703. Set position in SD card file to index in bytes.
  4704. This command is expected to be called after M23 and before M24.
  4705. Otherwise effect of this command is undefined.
  4706. #### Usage
  4707. M26 [ S ]
  4708. #### Parameters
  4709. - `S` - Index in bytes
  4710. */
  4711. case 26:
  4712. if(card.cardOK && code_seen('S')) {
  4713. long index = code_value_long();
  4714. card.setIndex(index);
  4715. // We don't disable interrupt during update of sdpos_atomic
  4716. // as we expect, that SD card print is not active in this moment
  4717. sdpos_atomic = index;
  4718. }
  4719. break;
  4720. /*!
  4721. ### M27 - Get SD status <a href="https://reprap.org/wiki/G-code#M27:_Report_SD_print_status">M27: Report SD print status</a>
  4722. #### Usage
  4723. M27 [ P ]
  4724. #### Parameters
  4725. - `P` - Show full SFN path instead of LFN only.
  4726. */
  4727. case 27:
  4728. card.getStatus(code_seen('P'));
  4729. break;
  4730. /*!
  4731. ### M28 - Start SD write <a href="https://reprap.org/wiki/G-code#M28:_Begin_write_to_SD_card">M28: Begin write to SD card</a>
  4732. */
  4733. case 28:
  4734. starpos = (strchr(strchr_pointer + 4,'*'));
  4735. if(starpos != NULL){
  4736. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  4737. strchr_pointer = strchr(npos,' ') + 1;
  4738. *(starpos) = '\0';
  4739. }
  4740. card.openFileWrite(strchr_pointer+4);
  4741. break;
  4742. /*! ### M29 - Stop SD write <a href="https://reprap.org/wiki/G-code#M29:_Stop_writing_to_SD_card">M29: Stop writing to SD card</a>
  4743. Stops writing to the SD file signaling the end of the uploaded file. It is processed very early and it's not written to the card.
  4744. */
  4745. case 29:
  4746. //processed in write to file routine above
  4747. //card,saving = false;
  4748. break;
  4749. /*!
  4750. ### M30 - Delete file <a href="https://reprap.org/wiki/G-code#M30:_Delete_a_file_on_the_SD_card">M30: Delete a file on the SD card</a>
  4751. #### Usage
  4752. M30 [filename]
  4753. */
  4754. case 30:
  4755. if (card.cardOK){
  4756. card.closefile();
  4757. starpos = (strchr(strchr_pointer + 4,'*'));
  4758. if(starpos != NULL){
  4759. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  4760. strchr_pointer = strchr(npos,' ') + 1;
  4761. *(starpos) = '\0';
  4762. }
  4763. card.removeFile(strchr_pointer + 4);
  4764. }
  4765. break;
  4766. /*!
  4767. ### M32 - Select file and start SD print <a href="https://reprap.org/wiki/G-code#M32:_Select_file_and_start_SD_print">M32: Select file and start SD print</a>
  4768. @todo What are the parameters P and S for in M32?
  4769. */
  4770. case 32:
  4771. {
  4772. if(card.sdprinting) {
  4773. st_synchronize();
  4774. }
  4775. starpos = (strchr(strchr_pointer + 4,'*'));
  4776. const char* namestartpos = (strchr(strchr_pointer + 4,'!')); //find ! to indicate filename string start.
  4777. if(namestartpos==NULL)
  4778. {
  4779. namestartpos=strchr_pointer + 4; //default name position, 4 letters after the M
  4780. }
  4781. else
  4782. namestartpos++; //to skip the '!'
  4783. if(starpos!=NULL)
  4784. *(starpos)='\0';
  4785. bool call_procedure=(code_seen('P'));
  4786. if(strchr_pointer>namestartpos)
  4787. call_procedure=false; //false alert, 'P' found within filename
  4788. if( card.cardOK )
  4789. {
  4790. card.openFileReadFilteredGcode(namestartpos,!call_procedure);
  4791. if(code_seen('S'))
  4792. if(strchr_pointer<namestartpos) //only if "S" is occuring _before_ the filename
  4793. card.setIndex(code_value_long());
  4794. card.startFileprint();
  4795. if(!call_procedure)
  4796. {
  4797. if(!card.get_sdpos())
  4798. {
  4799. // A new print has started from scratch, reset stats
  4800. failstats_reset_print();
  4801. sdpos_atomic = 0;
  4802. #ifndef LA_NOCOMPAT
  4803. la10c_reset();
  4804. #endif
  4805. }
  4806. starttime=_millis(); // procedure calls count as normal print time.
  4807. }
  4808. }
  4809. } break;
  4810. /*!
  4811. ### M928 - Start SD logging <a href="https://reprap.org/wiki/G-code#M928:_Start_SD_logging">M928: Start SD logging</a>
  4812. #### Usage
  4813. M928 [filename]
  4814. */
  4815. case 928:
  4816. starpos = (strchr(strchr_pointer + 5,'*'));
  4817. if(starpos != NULL){
  4818. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  4819. strchr_pointer = strchr(npos,' ') + 1;
  4820. *(starpos) = '\0';
  4821. }
  4822. card.openLogFile(strchr_pointer+5);
  4823. break;
  4824. #endif //SDSUPPORT
  4825. /*!
  4826. ### M31 - Report current print time <a href="https://reprap.org/wiki/G-code#M31:_Output_time_since_last_M109_or_SD_card_start_to_serial">M31: Output time since last M109 or SD card start to serial</a>
  4827. */
  4828. case 31: //M31 take time since the start of the SD print or an M109 command
  4829. {
  4830. stoptime=_millis();
  4831. char time[30];
  4832. unsigned long t=(stoptime-starttime)/1000;
  4833. int sec,min;
  4834. min=t/60;
  4835. sec=t%60;
  4836. sprintf_P(time, PSTR("%i min, %i sec"), min, sec);
  4837. SERIAL_ECHO_START;
  4838. SERIAL_ECHOLN(time);
  4839. lcd_setstatus(time);
  4840. autotempShutdown();
  4841. }
  4842. break;
  4843. /*!
  4844. ### M42 - Set pin state <a href="https://reprap.org/wiki/G-code#M42:_Switch_I.2FO_pin">M42: Switch I/O pin</a>
  4845. #### Usage
  4846. M42 [ P | S ]
  4847. #### Parameters
  4848. - `P` - Pin number.
  4849. - `S` - Pin value. If the pin is analog, values are from 0 to 255. If the pin is digital, values are from 0 to 1.
  4850. */
  4851. case 42:
  4852. if (code_seen('S'))
  4853. {
  4854. uint8_t pin_status = code_value_uint8();
  4855. int8_t pin_number = LED_PIN;
  4856. if (code_seen('P'))
  4857. pin_number = code_value_uint8();
  4858. for(int8_t i = 0; i < (int8_t)(sizeof(sensitive_pins)/sizeof(sensitive_pins[0])); i++)
  4859. {
  4860. if ((int8_t)pgm_read_byte(&sensitive_pins[i]) == pin_number)
  4861. {
  4862. pin_number = -1;
  4863. break;
  4864. }
  4865. }
  4866. #if defined(FAN_PIN) && FAN_PIN > -1
  4867. if (pin_number == FAN_PIN)
  4868. fanSpeed = pin_status;
  4869. #endif
  4870. if (pin_number > -1)
  4871. {
  4872. pinMode(pin_number, OUTPUT);
  4873. digitalWrite(pin_number, pin_status);
  4874. analogWrite(pin_number, pin_status);
  4875. }
  4876. }
  4877. break;
  4878. /*!
  4879. ### M44 - Reset the bed skew and offset calibration <a href="https://reprap.org/wiki/G-code#M44:_Reset_the_bed_skew_and_offset_calibration">M44: Reset the bed skew and offset calibration</a>
  4880. */
  4881. case 44: // M44: Prusa3D: Reset the bed skew and offset calibration.
  4882. // Reset the baby step value and the baby step applied flag.
  4883. calibration_status_store(CALIBRATION_STATUS_ASSEMBLED);
  4884. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  4885. // Reset the skew and offset in both RAM and EEPROM.
  4886. reset_bed_offset_and_skew();
  4887. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  4888. // the planner will not perform any adjustments in the XY plane.
  4889. // Wait for the motors to stop and update the current position with the absolute values.
  4890. world2machine_revert_to_uncorrected();
  4891. break;
  4892. /*!
  4893. ### M45 - Bed skew and offset with manual Z up <a href="https://reprap.org/wiki/G-code#M45:_Bed_skew_and_offset_with_manual_Z_up">M45: Bed skew and offset with manual Z up</a>
  4894. #### Usage
  4895. M45 [ V ]
  4896. #### Parameters
  4897. - `V` - Verbosity level 1, 10 and 20 (low, mid, high). Only when SUPPORT_VERBOSITY is defined. Optional.
  4898. - `Z` - If it is provided, only Z calibration will run. Otherwise full calibration is executed.
  4899. */
  4900. case 45: // M45: Prusa3D: bed skew and offset with manual Z up
  4901. {
  4902. int8_t verbosity_level = 0;
  4903. bool only_Z = code_seen('Z');
  4904. #ifdef SUPPORT_VERBOSITY
  4905. if (code_seen('V'))
  4906. {
  4907. // Just 'V' without a number counts as V1.
  4908. char c = strchr_pointer[1];
  4909. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  4910. }
  4911. #endif //SUPPORT_VERBOSITY
  4912. gcode_M45(only_Z, verbosity_level);
  4913. }
  4914. break;
  4915. /*!
  4916. ### M46 - Show the assigned IP address <a href="https://reprap.org/wiki/G-code#M46:_Show_the_assigned_IP_address">M46: Show the assigned IP address.</a>
  4917. */
  4918. case 46:
  4919. {
  4920. // M46: Prusa3D: Show the assigned IP address.
  4921. if (card.ToshibaFlashAir_isEnabled()) {
  4922. uint8_t ip[4];
  4923. if (card.ToshibaFlashAir_GetIP(ip)) {
  4924. // SERIAL_PROTOCOLPGM("Toshiba FlashAir current IP: ");
  4925. SERIAL_PROTOCOL(uint8_t(ip[0]));
  4926. SERIAL_PROTOCOL('.');
  4927. SERIAL_PROTOCOL(uint8_t(ip[1]));
  4928. SERIAL_PROTOCOL('.');
  4929. SERIAL_PROTOCOL(uint8_t(ip[2]));
  4930. SERIAL_PROTOCOL('.');
  4931. SERIAL_PROTOCOLLN(uint8_t(ip[3]));
  4932. } else {
  4933. SERIAL_PROTOCOLPGM("?Toshiba FlashAir GetIP failed\n");
  4934. }
  4935. } else {
  4936. SERIAL_PROTOCOLLNPGM("n/a");
  4937. }
  4938. break;
  4939. }
  4940. /*!
  4941. ### M47 - Show end stops dialog on the display <a href="https://reprap.org/wiki/G-code#M47:_Show_end_stops_dialog_on_the_display">M47: Show end stops dialog on the display</a>
  4942. */
  4943. case 47:
  4944. KEEPALIVE_STATE(PAUSED_FOR_USER);
  4945. lcd_diag_show_end_stops();
  4946. KEEPALIVE_STATE(IN_HANDLER);
  4947. break;
  4948. #if 0
  4949. case 48: // M48: scan the bed induction sensor points, print the sensor trigger coordinates to the serial line for visualization on the PC.
  4950. {
  4951. // Disable the default update procedure of the display. We will do a modal dialog.
  4952. lcd_update_enable(false);
  4953. // Let the planner use the uncorrected coordinates.
  4954. mbl.reset();
  4955. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  4956. // the planner will not perform any adjustments in the XY plane.
  4957. // Wait for the motors to stop and update the current position with the absolute values.
  4958. world2machine_revert_to_uncorrected();
  4959. // Move the print head close to the bed.
  4960. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4961. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS],current_position[Z_AXIS] , current_position[E_AXIS], homing_feedrate[Z_AXIS]/40, active_extruder);
  4962. st_synchronize();
  4963. // Home in the XY plane.
  4964. set_destination_to_current();
  4965. int l_feedmultiply = setup_for_endstop_move();
  4966. home_xy();
  4967. int8_t verbosity_level = 0;
  4968. if (code_seen('V')) {
  4969. // Just 'V' without a number counts as V1.
  4970. char c = strchr_pointer[1];
  4971. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  4972. }
  4973. bool success = scan_bed_induction_points(verbosity_level);
  4974. clean_up_after_endstop_move(l_feedmultiply);
  4975. // Print head up.
  4976. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4977. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS],current_position[Z_AXIS] , current_position[E_AXIS], homing_feedrate[Z_AXIS]/40, active_extruder);
  4978. st_synchronize();
  4979. lcd_update_enable(true);
  4980. break;
  4981. }
  4982. #endif
  4983. #ifdef ENABLE_AUTO_BED_LEVELING
  4984. #ifdef Z_PROBE_REPEATABILITY_TEST
  4985. /*!
  4986. ### M48 - Z-Probe repeatability measurement function <a href="https://reprap.org/wiki/G-code#M48:_Measure_Z-Probe_repeatability">M48: Measure Z-Probe repeatability</a>
  4987. This function assumes the bed has been homed. Specifically, that a G28 command as been issued prior to invoking the M48 Z-Probe repeatability measurement function. Any information generated by a prior G29 Bed leveling command will be lost and needs to be regenerated.
  4988. The number of samples will default to 10 if not specified. You can use upper or lower case letters for any of the options EXCEPT n. n must be in lower case because Marlin uses a capital N for its communication protocol and will get horribly confused if you send it a capital N.
  4989. @todo Why would you check for both uppercase and lowercase? Seems wasteful.
  4990. #### Usage
  4991. M48 [ n | X | Y | V | L ]
  4992. #### Parameters
  4993. - `n` - Number of samples. Valid values 4-50
  4994. - `X` - X position for samples
  4995. - `Y` - Y position for samples
  4996. - `V` - Verbose level. Valid values 1-4
  4997. - `L` - Legs of movementprior to doing probe. Valid values 1-15
  4998. */
  4999. case 48: // M48 Z-Probe repeatability
  5000. {
  5001. #if Z_MIN_PIN == -1
  5002. #error "You must have a Z_MIN endstop in order to enable calculation of Z-Probe repeatability."
  5003. #endif
  5004. double sum=0.0;
  5005. double mean=0.0;
  5006. double sigma=0.0;
  5007. double sample_set[50];
  5008. int verbose_level=1, n=0, j, n_samples = 10, n_legs=0;
  5009. double X_current, Y_current, Z_current;
  5010. double X_probe_location, Y_probe_location, Z_start_location, ext_position;
  5011. if (code_seen('V') || code_seen('v')) {
  5012. verbose_level = code_value();
  5013. if (verbose_level<0 || verbose_level>4 ) {
  5014. SERIAL_PROTOCOLPGM("?Verbose Level not plausable.\n");
  5015. goto Sigma_Exit;
  5016. }
  5017. }
  5018. if (verbose_level > 0) {
  5019. SERIAL_PROTOCOLPGM("M48 Z-Probe Repeatability test. Version 2.00\n");
  5020. SERIAL_PROTOCOLPGM("Full support at: http://3dprintboard.com/forum.php\n");
  5021. }
  5022. if (code_seen('n')) {
  5023. n_samples = code_value();
  5024. if (n_samples<4 || n_samples>50 ) {
  5025. SERIAL_PROTOCOLPGM("?Specified sample size not plausable.\n");
  5026. goto Sigma_Exit;
  5027. }
  5028. }
  5029. X_current = X_probe_location = st_get_position_mm(X_AXIS);
  5030. Y_current = Y_probe_location = st_get_position_mm(Y_AXIS);
  5031. Z_current = st_get_position_mm(Z_AXIS);
  5032. Z_start_location = st_get_position_mm(Z_AXIS) + Z_RAISE_BEFORE_PROBING;
  5033. ext_position = st_get_position_mm(E_AXIS);
  5034. if (code_seen('X') || code_seen('x') ) {
  5035. X_probe_location = code_value() - X_PROBE_OFFSET_FROM_EXTRUDER;
  5036. if (X_probe_location<X_MIN_POS || X_probe_location>X_MAX_POS ) {
  5037. SERIAL_PROTOCOLPGM("?Specified X position out of range.\n");
  5038. goto Sigma_Exit;
  5039. }
  5040. }
  5041. if (code_seen('Y') || code_seen('y') ) {
  5042. Y_probe_location = code_value() - Y_PROBE_OFFSET_FROM_EXTRUDER;
  5043. if (Y_probe_location<Y_MIN_POS || Y_probe_location>Y_MAX_POS ) {
  5044. SERIAL_PROTOCOLPGM("?Specified Y position out of range.\n");
  5045. goto Sigma_Exit;
  5046. }
  5047. }
  5048. if (code_seen('L') || code_seen('l') ) {
  5049. n_legs = code_value();
  5050. if ( n_legs==1 )
  5051. n_legs = 2;
  5052. if ( n_legs<0 || n_legs>15 ) {
  5053. SERIAL_PROTOCOLPGM("?Specified number of legs in movement not plausable.\n");
  5054. goto Sigma_Exit;
  5055. }
  5056. }
  5057. //
  5058. // Do all the preliminary setup work. First raise the probe.
  5059. //
  5060. st_synchronize();
  5061. plan_bed_level_matrix.set_to_identity();
  5062. plan_buffer_line( X_current, Y_current, Z_start_location,
  5063. ext_position,
  5064. homing_feedrate[Z_AXIS]/60,
  5065. active_extruder);
  5066. st_synchronize();
  5067. //
  5068. // Now get everything to the specified probe point So we can safely do a probe to
  5069. // get us close to the bed. If the Z-Axis is far from the bed, we don't want to
  5070. // use that as a starting point for each probe.
  5071. //
  5072. if (verbose_level > 2)
  5073. SERIAL_PROTOCOL("Positioning probe for the test.\n");
  5074. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  5075. ext_position,
  5076. homing_feedrate[X_AXIS]/60,
  5077. active_extruder);
  5078. st_synchronize();
  5079. current_position[X_AXIS] = X_current = st_get_position_mm(X_AXIS);
  5080. current_position[Y_AXIS] = Y_current = st_get_position_mm(Y_AXIS);
  5081. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  5082. current_position[E_AXIS] = ext_position = st_get_position_mm(E_AXIS);
  5083. //
  5084. // OK, do the inital probe to get us close to the bed.
  5085. // Then retrace the right amount and use that in subsequent probes
  5086. //
  5087. int l_feedmultiply = setup_for_endstop_move();
  5088. run_z_probe();
  5089. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  5090. Z_start_location = st_get_position_mm(Z_AXIS) + Z_RAISE_BEFORE_PROBING;
  5091. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  5092. ext_position,
  5093. homing_feedrate[X_AXIS]/60,
  5094. active_extruder);
  5095. st_synchronize();
  5096. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  5097. for( n=0; n<n_samples; n++) {
  5098. do_blocking_move_to( X_probe_location, Y_probe_location, Z_start_location); // Make sure we are at the probe location
  5099. if ( n_legs) {
  5100. double radius=0.0, theta=0.0, x_sweep, y_sweep;
  5101. int rotational_direction, l;
  5102. rotational_direction = (unsigned long) _millis() & 0x0001; // clockwise or counter clockwise
  5103. radius = (unsigned long) _millis() % (long) (X_MAX_LENGTH/4); // limit how far out to go
  5104. theta = (float) ((unsigned long) _millis() % (long) 360) / (360./(2*3.1415926)); // turn into radians
  5105. //SERIAL_ECHOPAIR("starting radius: ",radius);
  5106. //SERIAL_ECHOPAIR(" theta: ",theta);
  5107. //SERIAL_ECHOPAIR(" direction: ",rotational_direction);
  5108. //SERIAL_PROTOCOLLNPGM("");
  5109. for( l=0; l<n_legs-1; l++) {
  5110. if (rotational_direction==1)
  5111. theta += (float) ((unsigned long) _millis() % (long) 20) / (360.0/(2*3.1415926)); // turn into radians
  5112. else
  5113. theta -= (float) ((unsigned long) _millis() % (long) 20) / (360.0/(2*3.1415926)); // turn into radians
  5114. radius += (float) ( ((long) ((unsigned long) _millis() % (long) 10)) - 5);
  5115. if ( radius<0.0 )
  5116. radius = -radius;
  5117. X_current = X_probe_location + cos(theta) * radius;
  5118. Y_current = Y_probe_location + sin(theta) * radius;
  5119. if ( X_current<X_MIN_POS) // Make sure our X & Y are sane
  5120. X_current = X_MIN_POS;
  5121. if ( X_current>X_MAX_POS)
  5122. X_current = X_MAX_POS;
  5123. if ( Y_current<Y_MIN_POS) // Make sure our X & Y are sane
  5124. Y_current = Y_MIN_POS;
  5125. if ( Y_current>Y_MAX_POS)
  5126. Y_current = Y_MAX_POS;
  5127. if (verbose_level>3 ) {
  5128. SERIAL_ECHOPAIR("x: ", X_current);
  5129. SERIAL_ECHOPAIR("y: ", Y_current);
  5130. SERIAL_PROTOCOLLNPGM("");
  5131. }
  5132. do_blocking_move_to( X_current, Y_current, Z_current );
  5133. }
  5134. do_blocking_move_to( X_probe_location, Y_probe_location, Z_start_location); // Go back to the probe location
  5135. }
  5136. int l_feedmultiply = setup_for_endstop_move();
  5137. run_z_probe();
  5138. sample_set[n] = current_position[Z_AXIS];
  5139. //
  5140. // Get the current mean for the data points we have so far
  5141. //
  5142. sum=0.0;
  5143. for( j=0; j<=n; j++) {
  5144. sum = sum + sample_set[j];
  5145. }
  5146. mean = sum / (double (n+1));
  5147. //
  5148. // Now, use that mean to calculate the standard deviation for the
  5149. // data points we have so far
  5150. //
  5151. sum=0.0;
  5152. for( j=0; j<=n; j++) {
  5153. sum = sum + (sample_set[j]-mean) * (sample_set[j]-mean);
  5154. }
  5155. sigma = sqrt( sum / (double (n+1)) );
  5156. if (verbose_level > 1) {
  5157. SERIAL_PROTOCOL(n+1);
  5158. SERIAL_PROTOCOL(" of ");
  5159. SERIAL_PROTOCOL(n_samples);
  5160. SERIAL_PROTOCOLPGM(" z: ");
  5161. SERIAL_PROTOCOL_F(current_position[Z_AXIS], 6);
  5162. }
  5163. if (verbose_level > 2) {
  5164. SERIAL_PROTOCOL(" mean: ");
  5165. SERIAL_PROTOCOL_F(mean,6);
  5166. SERIAL_PROTOCOL(" sigma: ");
  5167. SERIAL_PROTOCOL_F(sigma,6);
  5168. }
  5169. if (verbose_level > 0)
  5170. SERIAL_PROTOCOLPGM("\n");
  5171. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  5172. current_position[E_AXIS], homing_feedrate[Z_AXIS]/60, active_extruder);
  5173. st_synchronize();
  5174. }
  5175. _delay(1000);
  5176. clean_up_after_endstop_move(l_feedmultiply);
  5177. // enable_endstops(true);
  5178. if (verbose_level > 0) {
  5179. SERIAL_PROTOCOLPGM("Mean: ");
  5180. SERIAL_PROTOCOL_F(mean, 6);
  5181. SERIAL_PROTOCOLPGM("\n");
  5182. }
  5183. SERIAL_PROTOCOLPGM("Standard Deviation: ");
  5184. SERIAL_PROTOCOL_F(sigma, 6);
  5185. SERIAL_PROTOCOLPGM("\n\n");
  5186. Sigma_Exit:
  5187. break;
  5188. }
  5189. #endif // Z_PROBE_REPEATABILITY_TEST
  5190. #endif // ENABLE_AUTO_BED_LEVELING
  5191. /*!
  5192. ### M73 - Set/get print progress <a href="https://reprap.org/wiki/G-code#M73:_Set.2FGet_build_percentage">M73: Set/Get build percentage</a>
  5193. #### Usage
  5194. M73 [ P | R | Q | S | C | D ]
  5195. #### Parameters
  5196. - `P` - Percent in normal mode
  5197. - `R` - Time remaining in normal mode
  5198. - `Q` - Percent in silent mode
  5199. - `S` - Time in silent mode
  5200. - `C` - Time to change/pause/user interaction in normal mode
  5201. - `D` - Time to change/pause/user interaction in silent mode
  5202. */
  5203. case 73: //M73 show percent done, time remaining and time to change/pause
  5204. {
  5205. if(code_seen('P')) print_percent_done_normal = code_value_uint8();
  5206. if(code_seen('R')) print_time_remaining_normal = code_value();
  5207. if(code_seen('Q')) print_percent_done_silent = code_value_uint8();
  5208. if(code_seen('S')) print_time_remaining_silent = code_value();
  5209. if(code_seen('C')){
  5210. float print_time_to_change_normal_f = code_value_float();
  5211. print_time_to_change_normal = ( print_time_to_change_normal_f <= 0 ) ? PRINT_TIME_REMAINING_INIT : print_time_to_change_normal_f;
  5212. }
  5213. if(code_seen('D')){
  5214. float print_time_to_change_silent_f = code_value_float();
  5215. print_time_to_change_silent = ( print_time_to_change_silent_f <= 0 ) ? PRINT_TIME_REMAINING_INIT : print_time_to_change_silent_f;
  5216. }
  5217. {
  5218. const char* _msg_mode_done_remain = _N("%S MODE: Percent done: %hhd; print time remaining in mins: %d; Change in mins: %d\n");
  5219. printf_P(_msg_mode_done_remain, _N("NORMAL"), int8_t(print_percent_done_normal), print_time_remaining_normal, print_time_to_change_normal);
  5220. printf_P(_msg_mode_done_remain, _N("SILENT"), int8_t(print_percent_done_silent), print_time_remaining_silent, print_time_to_change_silent);
  5221. }
  5222. break;
  5223. }
  5224. /*!
  5225. ### M104 - Set hotend temperature <a href="https://reprap.org/wiki/G-code#M104:_Set_Extruder_Temperature">M104: Set Extruder Temperature</a>
  5226. #### Usage
  5227. M104 [ S ]
  5228. #### Parameters
  5229. - `S` - Target temperature
  5230. */
  5231. case 104: // M104
  5232. {
  5233. uint8_t extruder;
  5234. if(setTargetedHotend(104,extruder)){
  5235. break;
  5236. }
  5237. if (code_seen('S'))
  5238. {
  5239. setTargetHotendSafe(code_value(), extruder);
  5240. }
  5241. break;
  5242. }
  5243. /*!
  5244. ### M112 - Emergency stop <a href="https://reprap.org/wiki/G-code#M112:_Full_.28Emergency.29_Stop">M112: Full (Emergency) Stop</a>
  5245. It is processed much earlier as to bypass the cmdqueue.
  5246. */
  5247. case 112:
  5248. kill(MSG_M112_KILL, 3);
  5249. break;
  5250. /*!
  5251. ### M140 - Set bed temperature <a href="https://reprap.org/wiki/G-code#M140:_Set_Bed_Temperature_.28Fast.29">M140: Set Bed Temperature (Fast)</a>
  5252. #### Usage
  5253. M140 [ S ]
  5254. #### Parameters
  5255. - `S` - Target temperature
  5256. */
  5257. case 140:
  5258. if (code_seen('S')) setTargetBed(code_value());
  5259. break;
  5260. /*!
  5261. ### M105 - Report temperatures <a href="https://reprap.org/wiki/G-code#M105:_Get_Extruder_Temperature">M105: Get Extruder Temperature</a>
  5262. Prints temperatures:
  5263. - `T:` - Hotend (actual / target)
  5264. - `B:` - Bed (actual / target)
  5265. - `Tx:` - x Tool (actual / target)
  5266. - `@:` - Hotend power
  5267. - `B@:` - Bed power
  5268. - `P:` - PINDAv2 actual (only MK2.5/s and MK3/s)
  5269. - `A:` - Ambient actual (only MK3/s)
  5270. _Example:_
  5271. ok T:20.2 /0.0 B:19.1 /0.0 T0:20.2 /0.0 @:0 B@:0 P:19.8 A:26.4
  5272. */
  5273. case 105:
  5274. {
  5275. uint8_t extruder;
  5276. if(setTargetedHotend(105, extruder)){
  5277. break;
  5278. }
  5279. SERIAL_PROTOCOLPGM("ok ");
  5280. gcode_M105(extruder);
  5281. cmdqueue_pop_front(); //prevent an ok after the command since this command uses an ok at the beginning.
  5282. cmdbuffer_front_already_processed = true;
  5283. break;
  5284. }
  5285. #if defined(AUTO_REPORT)
  5286. /*!
  5287. ### M155 - Automatically send status <a href="https://reprap.org/wiki/G-code#M155:_Automatically_send_temperatures">M155: Automatically send temperatures</a>
  5288. #### Usage
  5289. M155 [ S ] [ C ]
  5290. #### Parameters
  5291. - `S` - Set autoreporting interval in seconds. 0 to disable. Maximum: 255
  5292. - `C` - Activate auto-report function (bit mask). Default is temperature.
  5293. bit 0 = Auto-report temperatures
  5294. bit 1 = Auto-report fans
  5295. bit 2 = Auto-report position
  5296. bit 3 = free
  5297. bit 4 = free
  5298. bit 5 = free
  5299. bit 6 = free
  5300. bit 7 = free
  5301. */
  5302. case 155:
  5303. {
  5304. if (code_seen('S')){
  5305. autoReportFeatures.SetPeriod( code_value_uint8() );
  5306. }
  5307. if (code_seen('C')){
  5308. autoReportFeatures.SetMask(code_value_uint8());
  5309. } else{
  5310. autoReportFeatures.SetMask(1); //Backwards compability to host systems like Octoprint to send only temp if paramerter `C`isn't used.
  5311. }
  5312. }
  5313. break;
  5314. #endif //AUTO_REPORT
  5315. /*!
  5316. ### M109 - Wait for extruder temperature <a href="https://reprap.org/wiki/G-code#M109:_Set_Extruder_Temperature_and_Wait">M109: Set Extruder Temperature and Wait</a>
  5317. #### Usage
  5318. M104 [ B | R | S ]
  5319. #### Parameters (not mandatory)
  5320. - `S` - Set extruder temperature
  5321. - `R` - Set extruder temperature
  5322. - `B` - Set max. extruder temperature, while `S` is min. temperature. Not active in default, only if AUTOTEMP is defined in source code.
  5323. Parameters S and R are treated identically.
  5324. Command always waits for both cool down and heat up.
  5325. If no parameters are supplied waits for previously set extruder temperature.
  5326. */
  5327. case 109:
  5328. {
  5329. uint8_t extruder;
  5330. if(setTargetedHotend(109, extruder)){
  5331. break;
  5332. }
  5333. LCD_MESSAGERPGM(_T(MSG_HEATING));
  5334. heating_status = HeatingStatus::EXTRUDER_HEATING;
  5335. prusa_statistics(1);
  5336. #ifdef AUTOTEMP
  5337. autotemp_enabled=false;
  5338. #endif
  5339. if (code_seen('S')) {
  5340. setTargetHotendSafe(code_value(), extruder);
  5341. } else if (code_seen('R')) {
  5342. setTargetHotendSafe(code_value(), extruder);
  5343. }
  5344. #ifdef AUTOTEMP
  5345. if (code_seen('S')) autotemp_min=code_value();
  5346. if (code_seen('B')) autotemp_max=code_value();
  5347. if (code_seen('F'))
  5348. {
  5349. autotemp_factor=code_value();
  5350. autotemp_enabled=true;
  5351. }
  5352. #endif
  5353. codenum = _millis();
  5354. /* See if we are heating up or cooling down */
  5355. target_direction = isHeatingHotend(extruder); // true if heating, false if cooling
  5356. cancel_heatup = false;
  5357. wait_for_heater(codenum, extruder); //loops until target temperature is reached
  5358. LCD_MESSAGERPGM(_T(MSG_HEATING_COMPLETE));
  5359. heating_status = HeatingStatus::EXTRUDER_HEATING_COMPLETE;
  5360. prusa_statistics(2);
  5361. //starttime=_millis();
  5362. previous_millis_cmd.start();
  5363. }
  5364. break;
  5365. /*!
  5366. ### M190 - Wait for bed temperature <a href="https://reprap.org/wiki/G-code#M190:_Wait_for_bed_temperature_to_reach_target_temp">M190: Wait for bed temperature to reach target temp</a>
  5367. #### Usage
  5368. M190 [ R | S ]
  5369. #### Parameters (not mandatory)
  5370. - `S` - Set extruder temperature and wait for heating
  5371. - `R` - Set extruder temperature and wait for heating or cooling
  5372. If no parameter is supplied, waits for heating or cooling to previously set temperature.
  5373. */
  5374. case 190:
  5375. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  5376. {
  5377. bool CooldownNoWait = false;
  5378. LCD_MESSAGERPGM(_T(MSG_BED_HEATING));
  5379. heating_status = HeatingStatus::BED_HEATING;
  5380. prusa_statistics(1);
  5381. if (code_seen('S'))
  5382. {
  5383. setTargetBed(code_value());
  5384. CooldownNoWait = true;
  5385. }
  5386. else if (code_seen('R'))
  5387. {
  5388. setTargetBed(code_value());
  5389. }
  5390. codenum = _millis();
  5391. cancel_heatup = false;
  5392. target_direction = isHeatingBed(); // true if heating, false if cooling
  5393. while ( (!cancel_heatup) && (target_direction ? (isHeatingBed()) : (isCoolingBed()&&(CooldownNoWait==false))) )
  5394. {
  5395. if(( _millis() - codenum) > 1000 ) //Print Temp Reading every 1 second while heating up.
  5396. {
  5397. if (!farm_mode) {
  5398. float tt = degHotend(active_extruder);
  5399. SERIAL_PROTOCOLPGM("T:");
  5400. SERIAL_PROTOCOL(tt);
  5401. SERIAL_PROTOCOLPGM(" E:");
  5402. SERIAL_PROTOCOL((int)active_extruder);
  5403. SERIAL_PROTOCOLPGM(" B:");
  5404. SERIAL_PROTOCOL_F(degBed(), 1);
  5405. SERIAL_PROTOCOLLN();
  5406. }
  5407. codenum = _millis();
  5408. }
  5409. manage_heater();
  5410. manage_inactivity();
  5411. lcd_update(0);
  5412. }
  5413. LCD_MESSAGERPGM(_T(MSG_BED_DONE));
  5414. heating_status = HeatingStatus::BED_HEATING_COMPLETE;
  5415. previous_millis_cmd.start();
  5416. }
  5417. #endif
  5418. break;
  5419. #if defined(FAN_PIN) && FAN_PIN > -1
  5420. /*!
  5421. ### M106 - Set fan speed <a href="https://reprap.org/wiki/G-code#M106:_Fan_On">M106: Fan On</a>
  5422. #### Usage
  5423. M106 [ S ]
  5424. #### Parameters
  5425. - `S` - Specifies the duty cycle of the print fan. Allowed values are 0-255. If it's omitted, a value of 255 is used.
  5426. */
  5427. case 106: // M106 Sxxx Fan On S<speed> 0 .. 255
  5428. if (code_seen('S')){
  5429. fanSpeed = code_value_uint8();
  5430. }
  5431. else {
  5432. fanSpeed = 255;
  5433. }
  5434. break;
  5435. /*!
  5436. ### M107 - Fan off <a href="https://reprap.org/wiki/G-code#M107:_Fan_Off">M107: Fan Off</a>
  5437. */
  5438. case 107:
  5439. fanSpeed = 0;
  5440. break;
  5441. #endif //FAN_PIN
  5442. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  5443. /*!
  5444. ### M80 - Turn on the Power Supply <a href="https://reprap.org/wiki/G-code#M80:_ATX_Power_On">M80: ATX Power On</a>
  5445. Only works if the firmware is compiled with PS_ON_PIN defined.
  5446. */
  5447. case 80:
  5448. SET_OUTPUT(PS_ON_PIN); //GND
  5449. WRITE(PS_ON_PIN, PS_ON_AWAKE);
  5450. // If you have a switch on suicide pin, this is useful
  5451. // if you want to start another print with suicide feature after
  5452. // a print without suicide...
  5453. #if defined SUICIDE_PIN && SUICIDE_PIN > -1
  5454. SET_OUTPUT(SUICIDE_PIN);
  5455. WRITE(SUICIDE_PIN, HIGH);
  5456. #endif
  5457. powersupply = true;
  5458. LCD_MESSAGERPGM(MSG_WELCOME);
  5459. lcd_update(0);
  5460. break;
  5461. /*!
  5462. ### M81 - Turn off Power Supply <a href="https://reprap.org/wiki/G-code#M81:_ATX_Power_Off">M81: ATX Power Off</a>
  5463. Only works if the firmware is compiled with PS_ON_PIN defined.
  5464. */
  5465. case 81:
  5466. disable_heater();
  5467. st_synchronize();
  5468. disable_e0();
  5469. disable_e1();
  5470. disable_e2();
  5471. finishAndDisableSteppers();
  5472. fanSpeed = 0;
  5473. _delay(1000); // Wait a little before to switch off
  5474. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  5475. st_synchronize();
  5476. suicide();
  5477. #elif defined(PS_ON_PIN) && PS_ON_PIN > -1
  5478. SET_OUTPUT(PS_ON_PIN);
  5479. WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  5480. #endif
  5481. powersupply = false;
  5482. LCD_MESSAGERPGM(CAT4(CUSTOM_MENDEL_NAME,PSTR(" "),MSG_OFF,PSTR(".")));
  5483. lcd_update(0);
  5484. break;
  5485. #endif
  5486. /*!
  5487. ### M82 - Set E axis to absolute mode <a href="https://reprap.org/wiki/G-code#M82:_Set_extruder_to_absolute_mode">M82: Set extruder to absolute mode</a>
  5488. Makes the extruder interpret extrusion as absolute positions.
  5489. */
  5490. case 82:
  5491. axis_relative_modes &= ~E_AXIS_MASK;
  5492. break;
  5493. /*!
  5494. ### M83 - Set E axis to relative mode <a href="https://reprap.org/wiki/G-code#M83:_Set_extruder_to_relative_mode">M83: Set extruder to relative mode</a>
  5495. Makes the extruder interpret extrusion values as relative positions.
  5496. */
  5497. case 83:
  5498. axis_relative_modes |= E_AXIS_MASK;
  5499. break;
  5500. /*!
  5501. ### M84 - Disable steppers <a href="https://reprap.org/wiki/G-code#M84:_Stop_idle_hold">M84: Stop idle hold</a>
  5502. This command can be used to set the stepper inactivity timeout (`S`) or to disable steppers (`X`,`Y`,`Z`,`E`)
  5503. This command can be used without any additional parameters. In that case all steppers are disabled.
  5504. The file completeness check uses this parameter to detect an incomplete file. It has to be present at the end of a file with no parameters.
  5505. M84 [ S | X | Y | Z | E ]
  5506. - `S` - Seconds
  5507. - `X` - X axis
  5508. - `Y` - Y axis
  5509. - `Z` - Z axis
  5510. - `E` - Extruder
  5511. ### M18 - Disable steppers <a href="https://reprap.org/wiki/G-code#M18:_Disable_all_stepper_motors">M18: Disable all stepper motors</a>
  5512. Equal to M84 (compatibility)
  5513. */
  5514. case 18: //compatibility
  5515. case 84: // M84
  5516. if(code_seen('S')){
  5517. stepper_inactive_time = code_value() * 1000;
  5518. }
  5519. else
  5520. {
  5521. 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])));
  5522. if(all_axis)
  5523. {
  5524. st_synchronize();
  5525. disable_e0();
  5526. disable_e1();
  5527. disable_e2();
  5528. finishAndDisableSteppers();
  5529. }
  5530. else
  5531. {
  5532. st_synchronize();
  5533. if (code_seen('X')) disable_x();
  5534. if (code_seen('Y')) disable_y();
  5535. if (code_seen('Z')) disable_z();
  5536. #if ((E0_ENABLE_PIN != X_ENABLE_PIN) && (E1_ENABLE_PIN != Y_ENABLE_PIN)) // Only enable on boards that have seperate ENABLE_PINS
  5537. if (code_seen('E')) {
  5538. disable_e0();
  5539. disable_e1();
  5540. disable_e2();
  5541. }
  5542. #endif
  5543. }
  5544. }
  5545. break;
  5546. /*!
  5547. ### M85 - Set max inactive time <a href="https://reprap.org/wiki/G-code#M85:_Set_Inactivity_Shutdown_Timer">M85: Set Inactivity Shutdown Timer</a>
  5548. #### Usage
  5549. M85 [ S ]
  5550. #### Parameters
  5551. - `S` - specifies the time in seconds. If a value of 0 is specified, the timer is disabled.
  5552. */
  5553. case 85: // M85
  5554. if(code_seen('S')) {
  5555. max_inactive_time = code_value() * 1000;
  5556. }
  5557. break;
  5558. #ifdef SAFETYTIMER
  5559. /*!
  5560. ### M86 - Set safety timer expiration time <a href="https://reprap.org/wiki/G-code#M86:_Set_Safety_Timer_expiration_time">M86: Set Safety Timer expiration time</a>
  5561. When safety timer expires, heatbed and nozzle target temperatures are set to zero.
  5562. #### Usage
  5563. M86 [ S ]
  5564. #### Parameters
  5565. - `S` - specifies the time in seconds. If a value of 0 is specified, the timer is disabled.
  5566. */
  5567. case 86:
  5568. if (code_seen('S')) {
  5569. safetytimer_inactive_time = code_value() * 1000;
  5570. safetyTimer.start();
  5571. }
  5572. break;
  5573. #endif
  5574. /*!
  5575. ### M92 Set Axis steps-per-unit <a href="https://reprap.org/wiki/G-code#M92:_Set_axis_steps_per_unit">M92: Set axis_steps_per_unit</a>
  5576. Allows programming of steps per unit (usually mm) for motor drives. These values are reset to firmware defaults on power on, unless saved to EEPROM if available (M500 in Marlin)
  5577. #### Usage
  5578. M92 [ X | Y | Z | E ]
  5579. #### Parameters
  5580. - `X` - Steps per unit for the X drive
  5581. - `Y` - Steps per unit for the Y drive
  5582. - `Z` - Steps per unit for the Z drive
  5583. - `E` - Steps per unit for the extruder drive
  5584. */
  5585. case 92:
  5586. for(int8_t i=0; i < NUM_AXIS; i++)
  5587. {
  5588. if(code_seen(axis_codes[i]))
  5589. {
  5590. if(i == E_AXIS) { // E
  5591. float value = code_value();
  5592. if(value < 20.0) {
  5593. float factor = cs.axis_steps_per_unit[i] / value; // increase e constants if M92 E14 is given for netfab.
  5594. cs.max_jerk[E_AXIS] *= factor;
  5595. max_feedrate[i] *= factor;
  5596. axis_steps_per_sqr_second[i] *= factor;
  5597. }
  5598. cs.axis_steps_per_unit[i] = value;
  5599. #if defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  5600. fsensor.init();
  5601. #endif //defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  5602. }
  5603. else {
  5604. cs.axis_steps_per_unit[i] = code_value();
  5605. }
  5606. }
  5607. }
  5608. reset_acceleration_rates();
  5609. break;
  5610. /*!
  5611. ### M110 - Set Line number <a href="https://reprap.org/wiki/G-code#M110:_Set_Current_Line_Number">M110: Set Current Line Number</a>
  5612. Sets the line number in G-code
  5613. #### Usage
  5614. M110 [ N ]
  5615. #### Parameters
  5616. - `N` - Line number
  5617. */
  5618. case 110:
  5619. if (code_seen('N'))
  5620. gcode_LastN = code_value_long();
  5621. break;
  5622. /*!
  5623. ### M113 - Get or set host keep-alive interval <a href="https://reprap.org/wiki/G-code#M113:_Host_Keepalive">M113: Host Keepalive</a>
  5624. During some lengthy processes, such as G29, Marlin may appear to the host to have “gone away.” The “host keepalive” feature will send messages to the host when Marlin is busy or waiting for user response so the host won’t try to reconnect (or disconnect).
  5625. #### Usage
  5626. M113 [ S ]
  5627. #### Parameters
  5628. - `S` - Seconds. Default is 2 seconds between "busy" messages
  5629. */
  5630. case 113:
  5631. if (code_seen('S')) {
  5632. host_keepalive_interval = code_value_uint8();
  5633. // NOMORE(host_keepalive_interval, 60);
  5634. }
  5635. else {
  5636. SERIAL_ECHO_START;
  5637. SERIAL_ECHOPAIR("M113 S", (unsigned long)host_keepalive_interval);
  5638. SERIAL_PROTOCOLLN();
  5639. }
  5640. break;
  5641. /*!
  5642. ### M115 - Firmware info <a href="https://reprap.org/wiki/G-code#M115:_Get_Firmware_Version_and_Capabilities">M115: Get Firmware Version and Capabilities</a>
  5643. Print the firmware info and capabilities
  5644. Without any arguments, prints Prusa firmware version number, machine type, extruder count and UUID.
  5645. `M115 U` Checks the firmware version provided. If the firmware version provided by the U code is higher than the currently running firmware, it will pause the print for 30s and ask the user to upgrade the firmware.
  5646. _Examples:_
  5647. `M115` results:
  5648. `FIRMWARE_NAME:Prusa-Firmware 3.8.1 based on Marlin FIRMWARE_URL:https://github.com/prusa3d/Prusa-Firmware PROTOCOL_VERSION:1.0 MACHINE_TYPE:Prusa i3 MK3S EXTRUDER_COUNT:1 UUID:00000000-0000-0000-0000-000000000000`
  5649. `M115 V` results:
  5650. `3.8.1`
  5651. `M115 U3.8.2-RC1` results on LCD display for 30s or user interaction:
  5652. `New firmware version available: 3.8.2-RC1 Please upgrade.`
  5653. #### Usage
  5654. M115 [ V | U ]
  5655. #### Parameters
  5656. - V - Report current installed firmware version
  5657. - U - Firmware version provided by G-code to be compared to current one.
  5658. */
  5659. case 115: // M115
  5660. if (code_seen('V')) {
  5661. // Report the Prusa version number.
  5662. SERIAL_PROTOCOLLNRPGM(FW_VERSION_STR_P());
  5663. } else if (code_seen('U')) {
  5664. // Check the firmware version provided. If the firmware version provided by the U code is higher than the currently running firmware,
  5665. // pause the print for 30s and ask the user to upgrade the firmware.
  5666. show_upgrade_dialog_if_version_newer(++ strchr_pointer);
  5667. } else {
  5668. SERIAL_ECHOPGM("FIRMWARE_NAME:Prusa-Firmware ");
  5669. SERIAL_ECHORPGM(FW_VERSION_STR_P());
  5670. SERIAL_ECHOPGM(" based on Marlin FIRMWARE_URL:https://github.com/prusa3d/Prusa-Firmware PROTOCOL_VERSION:");
  5671. SERIAL_ECHOPGM(PROTOCOL_VERSION);
  5672. SERIAL_ECHOPGM(" MACHINE_TYPE:");
  5673. SERIAL_ECHOPGM(CUSTOM_MENDEL_NAME);
  5674. SERIAL_ECHOPGM(" EXTRUDER_COUNT:");
  5675. SERIAL_ECHOPGM(STRINGIFY(EXTRUDERS));
  5676. SERIAL_ECHOPGM(" UUID:");
  5677. SERIAL_ECHOLNPGM(MACHINE_UUID);
  5678. #ifdef EXTENDED_CAPABILITIES_REPORT
  5679. extended_capabilities_report();
  5680. #endif //EXTENDED_CAPABILITIES_REPORT
  5681. }
  5682. break;
  5683. /*!
  5684. ### M114 - Get current position <a href="https://reprap.org/wiki/G-code#M114:_Get_Current_Position">M114: Get Current Position</a>
  5685. */
  5686. case 114:
  5687. gcode_M114();
  5688. break;
  5689. /*
  5690. M117 moved up to get the high priority
  5691. case 117: // M117 display message
  5692. starpos = (strchr(strchr_pointer + 5,'*'));
  5693. if(starpos!=NULL)
  5694. *(starpos)='\0';
  5695. lcd_setstatus(strchr_pointer + 5);
  5696. break;*/
  5697. #ifdef M120_M121_ENABLED
  5698. /*!
  5699. ### M120 - Enable endstops <a href="https://reprap.org/wiki/G-code#M120:_Enable_endstop_detection">M120: Enable endstop detection</a>
  5700. */
  5701. case 120:
  5702. enable_endstops(true) ;
  5703. break;
  5704. /*!
  5705. ### M121 - Disable endstops <a href="https://reprap.org/wiki/G-code#M121:_Disable_endstop_detection">M121: Disable endstop detection</a>
  5706. */
  5707. case 121:
  5708. enable_endstops(false) ;
  5709. break;
  5710. #endif //M120_M121_ENABLED
  5711. /*!
  5712. ### M119 - Get endstop states <a href="https://reprap.org/wiki/G-code#M119:_Get_Endstop_Status">M119: Get Endstop Status</a>
  5713. Returns the current state of the configured X, Y, Z endstops. Takes into account any 'inverted endstop' settings, so one can confirm that the machine is interpreting the endstops correctly.
  5714. */
  5715. case 119:
  5716. SERIAL_PROTOCOLRPGM(_N("Reporting endstop status"));////MSG_M119_REPORT
  5717. SERIAL_PROTOCOLLN();
  5718. #if defined(X_MIN_PIN) && X_MIN_PIN > -1
  5719. SERIAL_PROTOCOLRPGM(_n("x_min: "));////MSG_X_MIN
  5720. if(READ(X_MIN_PIN)^X_MIN_ENDSTOP_INVERTING){
  5721. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5722. }else{
  5723. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5724. }
  5725. SERIAL_PROTOCOLLN();
  5726. #endif
  5727. #if defined(X_MAX_PIN) && X_MAX_PIN > -1
  5728. SERIAL_PROTOCOLRPGM(_n("x_max: "));////MSG_X_MAX
  5729. if(READ(X_MAX_PIN)^X_MAX_ENDSTOP_INVERTING){
  5730. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5731. }else{
  5732. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5733. }
  5734. SERIAL_PROTOCOLLN();
  5735. #endif
  5736. #if defined(Y_MIN_PIN) && Y_MIN_PIN > -1
  5737. SERIAL_PROTOCOLRPGM(_n("y_min: "));////MSG_Y_MIN
  5738. if(READ(Y_MIN_PIN)^Y_MIN_ENDSTOP_INVERTING){
  5739. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5740. }else{
  5741. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5742. }
  5743. SERIAL_PROTOCOLLN();
  5744. #endif
  5745. #if defined(Y_MAX_PIN) && Y_MAX_PIN > -1
  5746. SERIAL_PROTOCOLRPGM(_n("y_max: "));////MSG_Y_MAX
  5747. if(READ(Y_MAX_PIN)^Y_MAX_ENDSTOP_INVERTING){
  5748. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5749. }else{
  5750. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5751. }
  5752. SERIAL_PROTOCOLLN();
  5753. #endif
  5754. #if defined(Z_MIN_PIN) && Z_MIN_PIN > -1
  5755. SERIAL_PROTOCOLRPGM(MSG_Z_MIN);
  5756. if(READ(Z_MIN_PIN)^Z_MIN_ENDSTOP_INVERTING){
  5757. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5758. }else{
  5759. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5760. }
  5761. SERIAL_PROTOCOLLN();
  5762. #endif
  5763. #if defined(Z_MAX_PIN) && Z_MAX_PIN > -1
  5764. SERIAL_PROTOCOLRPGM(MSG_Z_MAX);
  5765. if(READ(Z_MAX_PIN)^Z_MAX_ENDSTOP_INVERTING){
  5766. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5767. }else{
  5768. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5769. }
  5770. SERIAL_PROTOCOLLN();
  5771. #endif
  5772. break;
  5773. //!@todo update for all axes, use for loop
  5774. #if (defined(FANCHECK) && (((defined(TACH_0) && (TACH_0 >-1)) || (defined(TACH_1) && (TACH_1 > -1)))))
  5775. /*!
  5776. ### M123 - Tachometer value <a href="https://www.reprap.org/wiki/G-code#M123:_Tachometer_value_.28RepRap_.26_Prusa.29">M123: Tachometer value</a>
  5777. This command is used to report fan speeds and fan pwm values.
  5778. #### Usage
  5779. M123
  5780. - E0: - Hotend fan speed in RPM
  5781. - PRN1: - Part cooling fans speed in RPM
  5782. - E0@: - Hotend fan PWM value
  5783. - PRN1@: -Part cooling fan PWM value
  5784. _Example:_
  5785. E0:3240 RPM PRN1:4560 RPM E0@:255 PRN1@:255
  5786. */
  5787. case 123:
  5788. gcode_M123();
  5789. break;
  5790. #endif //FANCHECK and TACH_0 and TACH_1
  5791. #ifdef BLINKM
  5792. /*!
  5793. ### M150 - Set RGB(W) Color <a href="https://reprap.org/wiki/G-code#M150:_Set_LED_color">M150: Set LED color</a>
  5794. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code by defining BLINKM and its dependencies.
  5795. #### Usage
  5796. M150 [ R | U | B ]
  5797. #### Parameters
  5798. - `R` - Red color value
  5799. - `U` - Green color value. It is NOT `G`!
  5800. - `B` - Blue color value
  5801. */
  5802. case 150:
  5803. {
  5804. byte red;
  5805. byte grn;
  5806. byte blu;
  5807. if(code_seen('R')) red = code_value();
  5808. if(code_seen('U')) grn = code_value();
  5809. if(code_seen('B')) blu = code_value();
  5810. SendColors(red,grn,blu);
  5811. }
  5812. break;
  5813. #endif //BLINKM
  5814. /*!
  5815. ### M200 - Set filament diameter <a href="https://reprap.org/wiki/G-code#M200:_Set_filament_diameter">M200: Set filament diameter</a>
  5816. #### Usage
  5817. M200 [ D | T ]
  5818. #### Parameters
  5819. - `D` - Diameter in mm
  5820. - `T` - Number of extruder (MMUs)
  5821. */
  5822. case 200: // M200 D<millimeters> set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).
  5823. {
  5824. uint8_t extruder = active_extruder;
  5825. if(code_seen('T')) {
  5826. extruder = code_value_uint8();
  5827. if(extruder >= EXTRUDERS) {
  5828. SERIAL_ECHO_START;
  5829. SERIAL_ECHO(_n("M200 Invalid extruder "));////MSG_M200_INVALID_EXTRUDER
  5830. break;
  5831. }
  5832. }
  5833. if(code_seen('D')) {
  5834. float diameter = code_value();
  5835. if (diameter == 0.0) {
  5836. // setting any extruder filament size disables volumetric on the assumption that
  5837. // slicers either generate in extruder values as cubic mm or as as filament feeds
  5838. // for all extruders
  5839. cs.volumetric_enabled = false;
  5840. } else {
  5841. cs.filament_size[extruder] = code_value();
  5842. // make sure all extruders have some sane value for the filament size
  5843. cs.filament_size[0] = (cs.filament_size[0] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[0]);
  5844. #if EXTRUDERS > 1
  5845. cs.filament_size[1] = (cs.filament_size[1] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[1]);
  5846. #if EXTRUDERS > 2
  5847. cs.filament_size[2] = (cs.filament_size[2] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[2]);
  5848. #endif
  5849. #endif
  5850. cs.volumetric_enabled = true;
  5851. }
  5852. } else {
  5853. //reserved for setting filament diameter via UFID or filament measuring device
  5854. break;
  5855. }
  5856. calculate_extruder_multipliers();
  5857. }
  5858. break;
  5859. /*!
  5860. ### M201 - Set Print Max Acceleration <a href="https://reprap.org/wiki/G-code#M201:_Set_max_acceleration">M201: Set max printing acceleration</a>
  5861. For each axis individually.
  5862. ##### Usage
  5863. M201 [ X | Y | Z | E ]
  5864. ##### Parameters
  5865. - `X` - Acceleration for X axis in units/s^2
  5866. - `Y` - Acceleration for Y axis in units/s^2
  5867. - `Z` - Acceleration for Z axis in units/s^2
  5868. - `E` - Acceleration for the active or specified extruder in units/s^2
  5869. */
  5870. case 201:
  5871. for (int8_t i = 0; i < NUM_AXIS; i++)
  5872. {
  5873. if (code_seen(axis_codes[i]))
  5874. {
  5875. unsigned long val = code_value();
  5876. #ifdef TMC2130
  5877. unsigned long val_silent = val;
  5878. if ((i == X_AXIS) || (i == Y_AXIS))
  5879. {
  5880. if (val > NORMAL_MAX_ACCEL_XY)
  5881. val = NORMAL_MAX_ACCEL_XY;
  5882. if (val_silent > SILENT_MAX_ACCEL_XY)
  5883. val_silent = SILENT_MAX_ACCEL_XY;
  5884. }
  5885. cs.max_acceleration_units_per_sq_second_normal[i] = val;
  5886. cs.max_acceleration_units_per_sq_second_silent[i] = val_silent;
  5887. #else //TMC2130
  5888. max_acceleration_units_per_sq_second[i] = val;
  5889. #endif //TMC2130
  5890. }
  5891. }
  5892. // 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)
  5893. reset_acceleration_rates();
  5894. break;
  5895. #if 0 // Not used for Sprinter/grbl gen6
  5896. case 202: // M202
  5897. for(int8_t i=0; i < NUM_AXIS; i++) {
  5898. if(code_seen(axis_codes[i])) axis_travel_steps_per_sqr_second[i] = code_value() * cs.axis_steps_per_unit[i];
  5899. }
  5900. break;
  5901. #endif
  5902. /*!
  5903. ### M203 - Set Max Feedrate <a href="https://reprap.org/wiki/G-code#M203:_Set_maximum_feedrate">M203: Set maximum feedrate</a>
  5904. For each axis individually.
  5905. ##### Usage
  5906. M203 [ X | Y | Z | E ]
  5907. ##### Parameters
  5908. - `X` - Maximum feedrate for X axis
  5909. - `Y` - Maximum feedrate for Y axis
  5910. - `Z` - Maximum feedrate for Z axis
  5911. - `E` - Maximum feedrate for extruder drives
  5912. */
  5913. case 203: // M203 max feedrate mm/sec
  5914. for (uint8_t i = 0; i < NUM_AXIS; i++)
  5915. {
  5916. if (code_seen(axis_codes[i]))
  5917. {
  5918. float val = code_value();
  5919. #ifdef TMC2130
  5920. float val_silent = val;
  5921. if ((i == X_AXIS) || (i == Y_AXIS))
  5922. {
  5923. if (val > NORMAL_MAX_FEEDRATE_XY)
  5924. val = NORMAL_MAX_FEEDRATE_XY;
  5925. if (val_silent > SILENT_MAX_FEEDRATE_XY)
  5926. val_silent = SILENT_MAX_FEEDRATE_XY;
  5927. }
  5928. cs.max_feedrate_normal[i] = val;
  5929. cs.max_feedrate_silent[i] = val_silent;
  5930. #else //TMC2130
  5931. max_feedrate[i] = val;
  5932. #endif //TMC2130
  5933. }
  5934. }
  5935. break;
  5936. /*!
  5937. ### M204 - Acceleration settings <a href="https://reprap.org/wiki/G-code#M204:_Set_default_acceleration">M204: Set default acceleration</a>
  5938. #### Old format:
  5939. ##### Usage
  5940. M204 [ S | T ]
  5941. ##### Parameters
  5942. - `S` - normal moves
  5943. - `T` - filmanent only moves
  5944. #### New format:
  5945. ##### Usage
  5946. M204 [ P | R | T ]
  5947. ##### Parameters
  5948. - `P` - printing moves
  5949. - `R` - filmanent only moves
  5950. - `T` - travel moves (as of now T is ignored)
  5951. */
  5952. case 204:
  5953. {
  5954. if(code_seen('S')) {
  5955. // Legacy acceleration format. This format is used by the legacy Marlin, MK2 or MK3 firmware,
  5956. // and it is also generated by Slic3r to control acceleration per extrusion type
  5957. // (there is a separate acceleration settings in Slicer for perimeter, first layer etc).
  5958. cs.acceleration = cs.travel_acceleration = code_value();
  5959. // Interpret the T value as retract acceleration in the old Marlin format.
  5960. if(code_seen('T'))
  5961. cs.retract_acceleration = code_value();
  5962. } else {
  5963. // New acceleration format, compatible with the upstream Marlin.
  5964. if(code_seen('P'))
  5965. cs.acceleration = code_value();
  5966. if(code_seen('R'))
  5967. cs.retract_acceleration = code_value();
  5968. if(code_seen('T'))
  5969. cs.travel_acceleration = code_value();
  5970. }
  5971. }
  5972. break;
  5973. /*!
  5974. ### M205 - Set advanced settings <a href="https://reprap.org/wiki/G-code#M205:_Advanced_settings">M205: Advanced settings</a>
  5975. Set some advanced settings related to movement.
  5976. #### Usage
  5977. M205 [ S | T | B | X | Y | Z | E ]
  5978. #### Parameters
  5979. - `S` - Minimum feedrate for print moves (unit/s)
  5980. - `T` - Minimum feedrate for travel moves (units/s)
  5981. - `B` - Minimum segment time (us)
  5982. - `X` - Maximum X jerk (units/s)
  5983. - `Y` - Maximum Y jerk (units/s)
  5984. - `Z` - Maximum Z jerk (units/s)
  5985. - `E` - Maximum E jerk (units/s)
  5986. */
  5987. case 205:
  5988. {
  5989. if(code_seen('S')) cs.minimumfeedrate = code_value();
  5990. if(code_seen('T')) cs.mintravelfeedrate = code_value();
  5991. if(code_seen('B')) cs.minsegmenttime = code_value() ;
  5992. if(code_seen('X')) cs.max_jerk[X_AXIS] = cs.max_jerk[Y_AXIS] = code_value();
  5993. if(code_seen('Y')) cs.max_jerk[Y_AXIS] = code_value();
  5994. if(code_seen('Z')) cs.max_jerk[Z_AXIS] = code_value();
  5995. if(code_seen('E'))
  5996. {
  5997. float e = code_value();
  5998. #ifndef LA_NOCOMPAT
  5999. e = la10c_jerk(e);
  6000. #endif
  6001. cs.max_jerk[E_AXIS] = e;
  6002. }
  6003. }
  6004. break;
  6005. /*!
  6006. ### M206 - Set additional homing offsets <a href="https://reprap.org/wiki/G-code#M206:_Offset_axes">M206: Offset axes</a>
  6007. #### Usage
  6008. M206 [ X | Y | Z ]
  6009. #### Parameters
  6010. - `X` - X axis offset
  6011. - `Y` - Y axis offset
  6012. - `Z` - Z axis offset
  6013. */
  6014. case 206:
  6015. for(uint8_t i=0; i < 3; i++)
  6016. {
  6017. if(code_seen(axis_codes[i])) cs.add_homing[i] = code_value();
  6018. }
  6019. break;
  6020. #ifdef FWRETRACT
  6021. /*!
  6022. ### M207 - Set firmware retraction <a href="https://reprap.org/wiki/G-code#M207:_Set_retract_length">M207: Set retract length</a>
  6023. #### Usage
  6024. M207 [ S | F | Z ]
  6025. #### Parameters
  6026. - `S` - positive length to retract, in mm
  6027. - `F` - retraction feedrate, in mm/min
  6028. - `Z` - additional zlift/hop
  6029. */
  6030. case 207: //M207 - set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop]
  6031. {
  6032. if(code_seen('S'))
  6033. {
  6034. cs.retract_length = code_value() ;
  6035. }
  6036. if(code_seen('F'))
  6037. {
  6038. cs.retract_feedrate = code_value()/60 ;
  6039. }
  6040. if(code_seen('Z'))
  6041. {
  6042. cs.retract_zlift = code_value() ;
  6043. }
  6044. }break;
  6045. /*!
  6046. ### M208 - Set retract recover length <a href="https://reprap.org/wiki/G-code#M208:_Set_unretract_length">M208: Set unretract length</a>
  6047. #### Usage
  6048. M208 [ S | F ]
  6049. #### Parameters
  6050. - `S` - positive length surplus to the M207 Snnn, in mm
  6051. - `F` - feedrate, in mm/sec
  6052. */
  6053. case 208: // M208 - set retract recover length S[positive mm surplus to the M207 S*] F[feedrate mm/min]
  6054. {
  6055. if(code_seen('S'))
  6056. {
  6057. cs.retract_recover_length = code_value() ;
  6058. }
  6059. if(code_seen('F'))
  6060. {
  6061. cs.retract_recover_feedrate = code_value()/60 ;
  6062. }
  6063. }break;
  6064. /*!
  6065. ### M209 - Enable/disable automatict retract <a href="https://reprap.org/wiki/G-code#M209:_Enable_automatic_retract">M209: Enable automatic retract</a>
  6066. This boolean value S 1=true or 0=false enables automatic retract detect if the slicer did not support G10/G11: every normal extrude-only move will be classified as retract depending on the direction.
  6067. #### Usage
  6068. M209 [ S ]
  6069. #### Parameters
  6070. - `S` - 1=true or 0=false
  6071. */
  6072. 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.
  6073. {
  6074. if(code_seen('S'))
  6075. {
  6076. switch(code_value_uint8())
  6077. {
  6078. case 0:
  6079. {
  6080. cs.autoretract_enabled=false;
  6081. retracted[0]=false;
  6082. #if EXTRUDERS > 1
  6083. retracted[1]=false;
  6084. #endif
  6085. #if EXTRUDERS > 2
  6086. retracted[2]=false;
  6087. #endif
  6088. }break;
  6089. case 1:
  6090. {
  6091. cs.autoretract_enabled=true;
  6092. retracted[0]=false;
  6093. #if EXTRUDERS > 1
  6094. retracted[1]=false;
  6095. #endif
  6096. #if EXTRUDERS > 2
  6097. retracted[2]=false;
  6098. #endif
  6099. }break;
  6100. default:
  6101. SERIAL_ECHO_START;
  6102. SERIAL_ECHORPGM(MSG_UNKNOWN_COMMAND);
  6103. SERIAL_ECHO(CMDBUFFER_CURRENT_STRING);
  6104. SERIAL_ECHOLNPGM("\"(1)");
  6105. }
  6106. }
  6107. }break;
  6108. #endif // FWRETRACT
  6109. /*!
  6110. ### M214 - Set Arc configuration values (Use M500 to store in eeprom)
  6111. #### Usage
  6112. M214 [P] [S] [N] [R] [F]
  6113. #### Parameters
  6114. - `P` - A float representing the max and default millimeters per arc segment. Must be greater than 0.
  6115. - `S` - A float representing the minimum allowable millimeters per arc segment. Set to 0 to disable
  6116. - `N` - An int representing the number of arcs to draw before correcting the small angle approximation. Set to 0 to disable.
  6117. - `R` - An int representing the minimum number of segments per arcs of any radius,
  6118. except when the results in segment lengths greater than or less than the minimum
  6119. and maximum segment length. Set to 0 to disable.
  6120. - 'F' - An int representing the number of segments per second, unless this results in segment lengths
  6121. greater than or less than the minimum and maximum segment length. Set to 0 to disable.
  6122. */
  6123. case 214: //!@n M214 - Set Arc Parameters (Use M500 to store in eeprom) P<MM_PER_ARC_SEGMENT> S<MIN_MM_PER_ARC_SEGMENT> R<MIN_ARC_SEGMENTS> F<ARC_SEGMENTS_PER_SEC>
  6124. {
  6125. // Extract all possible parameters if they appear
  6126. float p = code_seen('P') ? code_value_float() : cs.mm_per_arc_segment;
  6127. float s = code_seen('S') ? code_value_float() : cs.min_mm_per_arc_segment;
  6128. unsigned char n = code_seen('N') ? code_value() : cs.n_arc_correction;
  6129. unsigned short r = code_seen('R') ? code_value() : cs.min_arc_segments;
  6130. unsigned short f = code_seen('F') ? code_value() : cs.arc_segments_per_sec;
  6131. // Ensure mm_per_arc_segment is greater than 0, and that min_mm_per_arc_segment is sero or greater than or equal to mm_per_arc_segment
  6132. if (p <=0 || s < 0 || p < s)
  6133. {
  6134. // Should we display some error here?
  6135. break;
  6136. }
  6137. cs.mm_per_arc_segment = p;
  6138. cs.min_mm_per_arc_segment = s;
  6139. cs.n_arc_correction = n;
  6140. cs.min_arc_segments = r;
  6141. cs.arc_segments_per_sec = f;
  6142. }break;
  6143. #if EXTRUDERS > 1
  6144. /*!
  6145. ### M218 - Set hotend offset <a href="https://reprap.org/wiki/G-code#M218:_Set_Hotend_Offset">M218: Set Hotend Offset</a>
  6146. In Prusa Firmware this G-code is only active if `EXTRUDERS` is higher then 1 in the source code. On Original i3 Prusa MK2/s MK2.5/s MK3/s it is not active.
  6147. #### Usage
  6148. M218 [ X | Y ]
  6149. #### Parameters
  6150. - `X` - X offset
  6151. - `Y` - Y offset
  6152. */
  6153. case 218: // M218 - set hotend offset (in mm), T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  6154. {
  6155. uint8_t extruder;
  6156. if(setTargetedHotend(218, extruder)){
  6157. break;
  6158. }
  6159. if(code_seen('X'))
  6160. {
  6161. extruder_offset[X_AXIS][extruder] = code_value();
  6162. }
  6163. if(code_seen('Y'))
  6164. {
  6165. extruder_offset[Y_AXIS][extruder] = code_value();
  6166. }
  6167. SERIAL_ECHO_START;
  6168. SERIAL_ECHORPGM(MSG_HOTEND_OFFSET);
  6169. for(extruder = 0; extruder < EXTRUDERS; extruder++)
  6170. {
  6171. SERIAL_ECHO(" ");
  6172. SERIAL_ECHO(extruder_offset[X_AXIS][extruder]);
  6173. SERIAL_ECHO(",");
  6174. SERIAL_ECHO(extruder_offset[Y_AXIS][extruder]);
  6175. }
  6176. SERIAL_ECHOLN("");
  6177. }break;
  6178. #endif
  6179. /*!
  6180. ### M220 Set feedrate percentage <a href="https://reprap.org/wiki/G-code#M220:_Set_speed_factor_override_percentage">M220: Set speed factor override percentage</a>
  6181. #### Usage
  6182. M220 [ B | S | R ]
  6183. #### Parameters
  6184. - `B` - Backup current speed factor
  6185. - `S` - Speed factor override percentage (0..100 or higher)
  6186. - `R` - Restore previous speed factor
  6187. */
  6188. case 220: // M220 S<factor in percent>- set speed factor override percentage
  6189. {
  6190. bool codesWereSeen = false;
  6191. if (code_seen('B')) //backup current speed factor
  6192. {
  6193. saved_feedmultiply_mm = feedmultiply;
  6194. codesWereSeen = true;
  6195. }
  6196. if (code_seen('S'))
  6197. {
  6198. feedmultiply = code_value_short();
  6199. codesWereSeen = true;
  6200. }
  6201. if (code_seen('R')) //restore previous feedmultiply
  6202. {
  6203. feedmultiply = saved_feedmultiply_mm;
  6204. codesWereSeen = true;
  6205. }
  6206. if (!codesWereSeen)
  6207. {
  6208. printf_P(PSTR("%i%%\n"), feedmultiply);
  6209. }
  6210. }
  6211. break;
  6212. /*!
  6213. ### M221 - Set extrude factor override percentage <a href="https://reprap.org/wiki/G-code#M221:_Set_extrude_factor_override_percentage">M221: Set extrude factor override percentage</a>
  6214. #### Usage
  6215. M221 [ S | T ]
  6216. #### Parameters
  6217. - `S` - Extrude factor override percentage (0..100 or higher), default 100%
  6218. - `T` - Extruder drive number (Prusa Firmware only), default 0 if not set.
  6219. */
  6220. case 221: // M221 S<factor in percent>- set extrude factor override percentage
  6221. {
  6222. if (code_seen('S'))
  6223. {
  6224. int tmp_code = code_value_short();
  6225. if (code_seen('T'))
  6226. {
  6227. uint8_t extruder;
  6228. if (setTargetedHotend(221, extruder))
  6229. break;
  6230. extruder_multiply[extruder] = tmp_code;
  6231. }
  6232. else
  6233. {
  6234. extrudemultiply = tmp_code ;
  6235. }
  6236. }
  6237. else
  6238. {
  6239. printf_P(PSTR("%i%%\n"), extrudemultiply);
  6240. }
  6241. calculate_extruder_multipliers();
  6242. }
  6243. break;
  6244. /*!
  6245. ### M226 - Wait for Pin state <a href="https://reprap.org/wiki/G-code#M226:_Wait_for_pin_state">M226: Wait for pin state</a>
  6246. Wait until the specified pin reaches the state required
  6247. #### Usage
  6248. M226 [ P | S ]
  6249. #### Parameters
  6250. - `P` - pin number
  6251. - `S` - pin state
  6252. */
  6253. case 226: // M226 P<pin number> S<pin state>- Wait until the specified pin reaches the state required
  6254. {
  6255. if(code_seen('P')){
  6256. int pin_number = code_value_short(); // pin number
  6257. int pin_state = -1; // required pin state - default is inverted
  6258. if(code_seen('S')) pin_state = code_value_short(); // required pin state
  6259. if(pin_state >= -1 && pin_state <= 1){
  6260. for(int8_t i = 0; i < (int8_t)(sizeof(sensitive_pins)/sizeof(sensitive_pins[0])); i++)
  6261. {
  6262. if (((int8_t)pgm_read_byte(&sensitive_pins[i]) == pin_number))
  6263. {
  6264. pin_number = -1;
  6265. break;
  6266. }
  6267. }
  6268. if (pin_number > -1)
  6269. {
  6270. int target = LOW;
  6271. st_synchronize();
  6272. pinMode(pin_number, INPUT);
  6273. switch(pin_state){
  6274. case 1:
  6275. target = HIGH;
  6276. break;
  6277. case 0:
  6278. target = LOW;
  6279. break;
  6280. case -1:
  6281. target = !digitalRead(pin_number);
  6282. break;
  6283. }
  6284. while(digitalRead(pin_number) != target){
  6285. manage_heater();
  6286. manage_inactivity();
  6287. lcd_update(0);
  6288. }
  6289. }
  6290. }
  6291. }
  6292. }
  6293. break;
  6294. #if NUM_SERVOS > 0
  6295. /*!
  6296. ### M280 - Set/Get servo position <a href="https://reprap.org/wiki/G-code#M280:_Set_servo_position">M280: Set servo position</a>
  6297. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  6298. #### Usage
  6299. M280 [ P | S ]
  6300. #### Parameters
  6301. - `P` - Servo index (id)
  6302. - `S` - Target position
  6303. */
  6304. case 280: // M280 - set servo position absolute. P: servo index, S: angle or microseconds
  6305. {
  6306. int servo_index = -1;
  6307. int servo_position = 0;
  6308. if (code_seen('P'))
  6309. servo_index = code_value();
  6310. if (code_seen('S')) {
  6311. servo_position = code_value();
  6312. if ((servo_index >= 0) && (servo_index < NUM_SERVOS)) {
  6313. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  6314. servos[servo_index].attach(0);
  6315. #endif
  6316. servos[servo_index].write(servo_position);
  6317. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  6318. _delay(PROBE_SERVO_DEACTIVATION_DELAY);
  6319. servos[servo_index].detach();
  6320. #endif
  6321. }
  6322. else {
  6323. SERIAL_ECHO_START;
  6324. SERIAL_ECHO("Servo ");
  6325. SERIAL_ECHO(servo_index);
  6326. SERIAL_ECHOLN(" out of range");
  6327. }
  6328. }
  6329. else if (servo_index >= 0) {
  6330. SERIAL_PROTOCOL(MSG_OK);
  6331. SERIAL_PROTOCOL(" Servo ");
  6332. SERIAL_PROTOCOL(servo_index);
  6333. SERIAL_PROTOCOL(": ");
  6334. SERIAL_PROTOCOLLN(servos[servo_index].read());
  6335. }
  6336. }
  6337. break;
  6338. #endif // NUM_SERVOS > 0
  6339. #if (LARGE_FLASH == true && ( BEEPER > 0 || defined(ULTRALCD) || defined(LCD_USE_I2C_BUZZER)))
  6340. /*!
  6341. ### M300 - Play tone <a href="https://reprap.org/wiki/G-code#M300:_Play_beep_sound">M300: Play beep sound</a>
  6342. In Prusa Firmware the defaults are `100Hz` and `1000ms`, so that `M300` without parameters will beep for a second.
  6343. #### Usage
  6344. M300 [ S | P ]
  6345. #### Parameters
  6346. - `S` - frequency in Hz. Not all firmware versions support this parameter
  6347. - `P` - duration in milliseconds
  6348. */
  6349. case 300: // M300
  6350. {
  6351. uint16_t beepS = code_seen('S') ? code_value() : 0;
  6352. uint16_t beepP = code_seen('P') ? code_value() : 1000;
  6353. #if BEEPER > 0
  6354. if (beepP > 0)
  6355. Sound_MakeCustom(beepP,beepS,false);
  6356. #endif
  6357. }
  6358. break;
  6359. #endif // M300
  6360. #ifdef PIDTEMP
  6361. /*!
  6362. ### M301 - Set hotend PID <a href="https://reprap.org/wiki/G-code#M301:_Set_PID_parameters">M301: Set PID parameters</a>
  6363. Sets Proportional (P), Integral (I) and Derivative (D) values for hot end.
  6364. See also <a href="https://reprap.org/wiki/PID_Tuning">PID Tuning.</a>
  6365. #### Usage
  6366. M301 [ P | I | D ]
  6367. #### Parameters
  6368. - `P` - proportional (Kp)
  6369. - `I` - integral (Ki)
  6370. - `D` - derivative (Kd)
  6371. */
  6372. case 301:
  6373. {
  6374. if(code_seen('P')) cs.Kp = code_value();
  6375. if(code_seen('I')) cs.Ki = scalePID_i(code_value());
  6376. if(code_seen('D')) cs.Kd = scalePID_d(code_value());
  6377. updatePID();
  6378. SERIAL_PROTOCOLRPGM(MSG_OK);
  6379. SERIAL_PROTOCOLPGM(" p:");
  6380. SERIAL_PROTOCOL(cs.Kp);
  6381. SERIAL_PROTOCOLPGM(" i:");
  6382. SERIAL_PROTOCOL(unscalePID_i(cs.Ki));
  6383. SERIAL_PROTOCOLPGM(" d:");
  6384. SERIAL_PROTOCOL(unscalePID_d(cs.Kd));
  6385. SERIAL_PROTOCOLLN();
  6386. }
  6387. break;
  6388. #endif //PIDTEMP
  6389. #ifdef PIDTEMPBED
  6390. /*!
  6391. ### M304 - Set bed PID <a href="https://reprap.org/wiki/G-code#M304:_Set_PID_parameters_-_Bed">M304: Set PID parameters - Bed</a>
  6392. Sets Proportional (P), Integral (I) and Derivative (D) values for bed.
  6393. See also <a href="https://reprap.org/wiki/PID_Tuning">PID Tuning.</a>
  6394. #### Usage
  6395. M304 [ P | I | D ]
  6396. #### Parameters
  6397. - `P` - proportional (Kp)
  6398. - `I` - integral (Ki)
  6399. - `D` - derivative (Kd)
  6400. */
  6401. case 304:
  6402. {
  6403. if(code_seen('P')) cs.bedKp = code_value();
  6404. if(code_seen('I')) cs.bedKi = scalePID_i(code_value());
  6405. if(code_seen('D')) cs.bedKd = scalePID_d(code_value());
  6406. updatePID();
  6407. SERIAL_PROTOCOLRPGM(MSG_OK);
  6408. SERIAL_PROTOCOLPGM(" p:");
  6409. SERIAL_PROTOCOL(cs.bedKp);
  6410. SERIAL_PROTOCOLPGM(" i:");
  6411. SERIAL_PROTOCOL(unscalePID_i(cs.bedKi));
  6412. SERIAL_PROTOCOLPGM(" d:");
  6413. SERIAL_PROTOCOLLN(unscalePID_d(cs.bedKd));
  6414. }
  6415. break;
  6416. #endif //PIDTEMP
  6417. /*!
  6418. ### M240 - Trigger camera <a href="https://reprap.org/wiki/G-code#M240:_Trigger_camera">M240: Trigger camera</a>
  6419. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  6420. You need to (re)define and assign `CHDK` or `PHOTOGRAPH_PIN` the correct pin number to be able to use the feature.
  6421. */
  6422. case 240: // M240 Triggers a camera by emulating a Canon RC-1 : http://www.doc-diy.net/photo/rc-1_hacked/
  6423. {
  6424. #ifdef CHDK
  6425. SET_OUTPUT(CHDK);
  6426. WRITE(CHDK, HIGH);
  6427. chdkHigh = _millis();
  6428. chdkActive = true;
  6429. #else
  6430. #if defined(PHOTOGRAPH_PIN) && PHOTOGRAPH_PIN > -1
  6431. const uint8_t NUM_PULSES=16;
  6432. const float PULSE_LENGTH=0.01524;
  6433. for(int i=0; i < NUM_PULSES; i++) {
  6434. WRITE(PHOTOGRAPH_PIN, HIGH);
  6435. _delay_ms(PULSE_LENGTH);
  6436. WRITE(PHOTOGRAPH_PIN, LOW);
  6437. _delay_ms(PULSE_LENGTH);
  6438. }
  6439. _delay(7.33);
  6440. for(int i=0; i < NUM_PULSES; i++) {
  6441. WRITE(PHOTOGRAPH_PIN, HIGH);
  6442. _delay_ms(PULSE_LENGTH);
  6443. WRITE(PHOTOGRAPH_PIN, LOW);
  6444. _delay_ms(PULSE_LENGTH);
  6445. }
  6446. #endif
  6447. #endif //chdk end if
  6448. }
  6449. break;
  6450. #ifdef PREVENT_DANGEROUS_EXTRUDE
  6451. /*!
  6452. ### M302 - Allow cold extrude, or set minimum extrude temperature <a href="https://reprap.org/wiki/G-code#M302:_Allow_cold_extrudes">M302: Allow cold extrudes</a>
  6453. This tells the printer to allow movement of the extruder motor above a certain temperature, or if disabled, to allow extruder movement when the hotend is below a safe printing temperature.
  6454. #### Usage
  6455. M302 [ S ]
  6456. #### Parameters
  6457. - `S` - Cold extrude minimum temperature
  6458. */
  6459. case 302:
  6460. {
  6461. int temp = 0;
  6462. if (code_seen('S')) temp=code_value_short();
  6463. set_extrude_min_temp(temp);
  6464. }
  6465. break;
  6466. #endif
  6467. /*!
  6468. ### M303 - PID autotune <a href="https://reprap.org/wiki/G-code#M303:_Run_PID_tuning">M303: Run PID tuning</a>
  6469. PID Tuning refers to a control algorithm used in some repraps to tune heating behavior for hot ends and heated beds. This command generates Proportional (Kp), Integral (Ki), and Derivative (Kd) values for the hotend or bed. Send the appropriate code and wait for the output to update the firmware values.
  6470. #### Usage
  6471. M303 [ E | S | C ]
  6472. #### Parameters
  6473. - `E` - Extruder, default `E0`. Use `E-1` to calibrate the bed PID
  6474. - `S` - Target temperature, default `210°C` for hotend, 70 for bed
  6475. - `C` - Cycles, default `5`
  6476. */
  6477. case 303:
  6478. {
  6479. float temp = 150.0;
  6480. int e = 0;
  6481. int c = 5;
  6482. if (code_seen('E')) e = code_value_short();
  6483. if (e < 0)
  6484. temp = 70;
  6485. if (code_seen('S')) temp = code_value();
  6486. if (code_seen('C')) c = code_value_short();
  6487. PID_autotune(temp, e, c);
  6488. }
  6489. break;
  6490. #ifdef TEMP_MODEL
  6491. /*!
  6492. ### M310 - Temperature model settings <a href="https://reprap.org/wiki/G-code#M310:_Temperature_model_settings">M310: Temperature model settings</a>
  6493. #### Usage
  6494. M310 ; report values
  6495. M310 [ A ] [ F ] ; autotune
  6496. M310 [ S ] ; set 0=disable 1=enable
  6497. M310 [ I ] [ R ] ; set resistance at index
  6498. M310 [ P | C ] ; set power, capacitance
  6499. M310 [ B | E | W ] ; set beeper, warning and error threshold
  6500. M310 [ T ] ; set ambient temperature correction
  6501. #### Parameters
  6502. - `I` - resistance index position (0-15)
  6503. - `R` - resistance value at index (K/W; requires `I`)
  6504. - `P` - power (W)
  6505. - `C` - capacitance (J/K)
  6506. - `S` - set 0=disable 1=enable
  6507. - `B` - beep and warn when reaching warning threshold 0=disable 1=enable (default: 1)
  6508. - `E` - error threshold (K/s; default in variant)
  6509. - `W` - warning threshold (K/s; default in variant)
  6510. - `T` - ambient temperature correction (K; default in variant)
  6511. - `A` - autotune C+R values
  6512. - `F` - force model self-test state (0=off 1=on) during autotune using current values
  6513. */
  6514. case 310:
  6515. {
  6516. // parse all parameters
  6517. float P = NAN, C = NAN, R = NAN, E = NAN, W = NAN, T = NAN;
  6518. int8_t I = -1, S = -1, B = -1, A = -1, F = -1;
  6519. if(code_seen('C')) C = code_value();
  6520. if(code_seen('P')) P = code_value();
  6521. if(code_seen('I')) I = code_value_short();
  6522. if(code_seen('R')) R = code_value();
  6523. if(code_seen('S')) S = code_value_short();
  6524. if(code_seen('B')) B = code_value_short();
  6525. if(code_seen('E')) E = code_value();
  6526. if(code_seen('W')) W = code_value();
  6527. if(code_seen('T')) T = code_value();
  6528. if(code_seen('A')) A = code_value_short();
  6529. if(code_seen('F')) F = code_value_short();
  6530. // report values if nothing has been requested
  6531. if(isnan(C) && isnan(P) && isnan(R) && isnan(E) && isnan(W) && isnan(T) && I < 0 && S < 0 && B < 0 && A < 0) {
  6532. temp_model_report_settings();
  6533. break;
  6534. }
  6535. // update all parameters
  6536. if(B >= 0) temp_model_set_warn_beep(B);
  6537. if(!isnan(C) || !isnan(P) || !isnan(T) || !isnan(W) || !isnan(E)) temp_model_set_params(C, P, T, W, E);
  6538. if(I >= 0 && !isnan(R)) temp_model_set_resistance(I, R);
  6539. // enable the model last, if requested
  6540. if(S >= 0) temp_model_set_enabled(S);
  6541. // run autotune
  6542. if(A >= 0) temp_model_autotune(A, F > 0);
  6543. }
  6544. break;
  6545. #endif
  6546. /*!
  6547. ### M400 - Wait for all moves to finish <a href="https://reprap.org/wiki/G-code#M400:_Wait_for_current_moves_to_finish">M400: Wait for current moves to finish</a>
  6548. Finishes all current moves and and thus clears the buffer.
  6549. Equivalent to `G4` with no parameters.
  6550. */
  6551. case 400:
  6552. {
  6553. st_synchronize();
  6554. }
  6555. break;
  6556. /*!
  6557. ### M403 - Set filament type (material) for particular extruder and notify the MMU <a href="https://reprap.org/wiki/G-code#M403:_Set_filament_type_.28material.29_for_particular_extruder_and_notify_the_MMU.">M403 - Set filament type (material) for particular extruder and notify the MMU</a>
  6558. Currently three different materials are needed (default, flex and PVA).
  6559. And storing this information for different load/unload profiles etc. in the future firmware does not have to wait for "ok" from MMU.
  6560. #### Usage
  6561. M403 [ E | F ]
  6562. #### Parameters
  6563. - `E` - Extruder number. 0-indexed.
  6564. - `F` - Filament type
  6565. */
  6566. case 403:
  6567. {
  6568. // currently three different materials are needed (default, flex and PVA)
  6569. // add storing this information for different load/unload profiles etc. in the future
  6570. if (MMU2::mmu2.Enabled())
  6571. {
  6572. uint8_t extruder = 255;
  6573. uint8_t filament = FILAMENT_UNDEFINED;
  6574. if(code_seen('E')) extruder = code_value_uint8();
  6575. if(code_seen('F')) filament = code_value_uint8();
  6576. MMU2::mmu2.set_filament_type(extruder, filament);
  6577. }
  6578. }
  6579. break;
  6580. /*!
  6581. ### M500 - Store settings in EEPROM <a href="https://reprap.org/wiki/G-code#M500:_Store_parameters_in_non-volatile_storage">M500: Store parameters in non-volatile storage</a>
  6582. Save current parameters to EEPROM.
  6583. */
  6584. case 500:
  6585. {
  6586. Config_StoreSettings();
  6587. }
  6588. break;
  6589. /*!
  6590. ### M501 - Read settings from EEPROM <a href="https://reprap.org/wiki/G-code#M501:_Read_parameters_from_EEPROM">M501: Read parameters from EEPROM</a>
  6591. Set the active parameters to those stored in the EEPROM. This is useful to revert parameters after experimenting with them.
  6592. */
  6593. case 501:
  6594. {
  6595. Config_RetrieveSettings();
  6596. }
  6597. break;
  6598. /*!
  6599. ### M502 - Revert all settings to factory default <a href="https://reprap.org/wiki/G-code#M502:_Restore_Default_Settings">M502: Restore Default Settings</a>
  6600. This command resets all tunable parameters to their default values, as set in the firmware's configuration files. This doesn't reset any parameters stored in the EEPROM, so it must be followed by M500 to write the default settings.
  6601. */
  6602. case 502:
  6603. {
  6604. Config_ResetDefault();
  6605. }
  6606. break;
  6607. /*!
  6608. ### M503 - Repport all settings currently in memory <a href="https://reprap.org/wiki/G-code#M503:_Report_Current_Settings">M503: Report Current Settings</a>
  6609. This command asks the firmware to reply with the current print settings as set in memory. Settings will differ from EEPROM contents if changed since the last load / save. The reply output includes the G-Code commands to produce each setting. For example, Steps-Per-Unit values are displayed as an M92 command.
  6610. */
  6611. case 503:
  6612. {
  6613. Config_PrintSettings();
  6614. }
  6615. break;
  6616. /*!
  6617. ### M509 - Force language selection <a href="https://reprap.org/wiki/G-code#M509:_Force_language_selection">M509: Force language selection</a>
  6618. Resets the language to English.
  6619. Only on Original Prusa i3 MK2.5/s and MK3/s with multiple languages.
  6620. */
  6621. case 509:
  6622. {
  6623. lang_reset();
  6624. SERIAL_ECHO_START;
  6625. SERIAL_PROTOCOLPGM(("LANG SEL FORCED"));
  6626. }
  6627. break;
  6628. #ifdef ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED
  6629. /*!
  6630. ### M540 - Abort print on endstop hit (enable/disable) <a href="https://reprap.org/wiki/G-code#M540_in_Marlin:_Enable.2FDisable_.22Stop_SD_Print_on_Endstop_Hit.22">M540 in Marlin: Enable/Disable "Stop SD Print on Endstop Hit"</a>
  6631. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code. You must define `ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED`.
  6632. #### Usage
  6633. M540 [ S ]
  6634. #### Parameters
  6635. - `S` - disabled=0, enabled=1
  6636. */
  6637. case 540:
  6638. {
  6639. if(code_seen('S')) abort_on_endstop_hit = code_value() > 0;
  6640. }
  6641. break;
  6642. #endif
  6643. #ifdef ENABLE_AUTO_BED_LEVELING
  6644. /*!
  6645. ### M851 - Set Z-Probe Offset <a href="https://reprap.org/wiki/G-code#M851:_Set_Z-Probe_Offset">M851: Set Z-Probe Offset"</a>
  6646. Sets the Z-probe Z offset. This offset is used to determine the actual Z position of the nozzle when using a probe to home Z with G28. This value may also be used by G81 (Prusa) / G29 (Marlin) to apply correction to the Z position.
  6647. This value represents the distance from nozzle to the bed surface at the point where the probe is triggered. This value will be negative for typical switch probes, inductive probes, and setups where the nozzle makes a circuit with a raised metal contact. This setting will be greater than zero on machines where the nozzle itself is used as the probe, pressing down on the bed to press a switch. (This is a common setup on delta machines.)
  6648. #### Usage
  6649. M851 [ Z ]
  6650. #### Parameters
  6651. - `Z` - Z offset probe to nozzle.
  6652. */
  6653. #ifdef CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  6654. case CUSTOM_M_CODE_SET_Z_PROBE_OFFSET:
  6655. {
  6656. float value;
  6657. if (code_seen('Z'))
  6658. {
  6659. value = code_value();
  6660. if ((Z_PROBE_OFFSET_RANGE_MIN <= value) && (value <= Z_PROBE_OFFSET_RANGE_MAX))
  6661. {
  6662. cs.zprobe_zoffset = -value; // compare w/ line 278 of ConfigurationStore.cpp
  6663. SERIAL_ECHO_START;
  6664. SERIAL_ECHOLNRPGM(CAT4(MSG_ZPROBE_ZOFFSET, " ", MSG_OK,PSTR("")));
  6665. SERIAL_PROTOCOLLN();
  6666. }
  6667. else
  6668. {
  6669. SERIAL_ECHO_START;
  6670. SERIAL_ECHORPGM(MSG_ZPROBE_ZOFFSET);
  6671. SERIAL_ECHORPGM(MSG_Z_MIN);
  6672. SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MIN);
  6673. SERIAL_ECHORPGM(MSG_Z_MAX);
  6674. SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MAX);
  6675. SERIAL_PROTOCOLLN();
  6676. }
  6677. }
  6678. else
  6679. {
  6680. SERIAL_ECHO_START;
  6681. SERIAL_ECHOLNRPGM(CAT2(MSG_ZPROBE_ZOFFSET, PSTR(" : ")));
  6682. SERIAL_ECHO(-cs.zprobe_zoffset);
  6683. SERIAL_PROTOCOLLN();
  6684. }
  6685. break;
  6686. }
  6687. #endif // CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  6688. #endif // ENABLE_AUTO_BED_LEVELING
  6689. /*!
  6690. ### M552 - Set IP address <a href="https://reprap.org/wiki/G-code#M552:_Set_IP_address.2C_enable.2Fdisable_network_interface">M552: Set IP address, enable/disable network interface"</a>
  6691. Sets the printer IP address that is shown in the support menu. Designed to be used with the help of host software.
  6692. If P is not specified nothing happens.
  6693. If the structure of the IP address is invalid, 0.0.0.0 is assumed and nothing is shown on the screen in the Support menu.
  6694. #### Usage
  6695. M552 [ P<IP_address> ]
  6696. #### Parameters
  6697. - `P` - The IP address in xxx.xxx.xxx.xxx format. Eg: P192.168.1.14
  6698. */
  6699. case 552:
  6700. {
  6701. if (code_seen('P'))
  6702. {
  6703. uint8_t valCnt = 0;
  6704. IP_address = 0;
  6705. do
  6706. {
  6707. *strchr_pointer = '*';
  6708. ((uint8_t*)&IP_address)[valCnt] = code_value_short();
  6709. valCnt++;
  6710. } while ((valCnt < 4) && code_seen('.'));
  6711. if (valCnt != 4)
  6712. IP_address = 0;
  6713. }
  6714. } break;
  6715. #ifdef FILAMENTCHANGEENABLE
  6716. /*!
  6717. ### M600 - Initiate Filament change procedure <a href="https://reprap.org/wiki/G-code#M600:_Filament_change_pause">M600: Filament change pause</a>
  6718. Initiates Filament change, it is also used during Filament Runout Sensor process.
  6719. If the `M600` is triggered under 25mm it will do a Z-lift of 25mm to prevent a filament blob.
  6720. #### Usage
  6721. M600 [ X | Y | Z | E | L | AUTO ]
  6722. - `X` - X position, default 211
  6723. - `Y` - Y position, default 0
  6724. - `Z` - relative lift Z, default MIN_Z_FOR_SWAP.
  6725. - `E` - initial retract, default -2
  6726. - `L` - later retract distance for removal, default -80
  6727. - `AUTO` - Automatically (only with MMU)
  6728. */
  6729. case 600: //Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  6730. {
  6731. st_synchronize();
  6732. float x_position = current_position[X_AXIS];
  6733. float y_position = current_position[Y_AXIS];
  6734. float z_shift = MIN_Z_FOR_SWAP;
  6735. float e_shift_init = 0;
  6736. float e_shift_late = 0;
  6737. bool automatic = false;
  6738. //Retract extruder
  6739. if(code_seen('E'))
  6740. {
  6741. e_shift_init = code_value();
  6742. }
  6743. else
  6744. {
  6745. #ifdef FILAMENTCHANGE_FIRSTRETRACT
  6746. e_shift_init = FILAMENTCHANGE_FIRSTRETRACT ;
  6747. #endif
  6748. }
  6749. //currently don't work as we are using the same unload sequence as in M702, needs re-work
  6750. if (code_seen('L'))
  6751. {
  6752. e_shift_late = code_value();
  6753. }
  6754. else
  6755. {
  6756. #ifdef FILAMENTCHANGE_FINALRETRACT
  6757. e_shift_late = FILAMENTCHANGE_FINALRETRACT;
  6758. #endif
  6759. }
  6760. // Z lift. For safety only allow positive values
  6761. if (code_seen('Z')) z_shift = fabs(code_value());
  6762. //Move XY to side
  6763. if(code_seen('X'))
  6764. {
  6765. x_position = code_value();
  6766. }
  6767. else
  6768. {
  6769. #ifdef FILAMENTCHANGE_XPOS
  6770. x_position = FILAMENTCHANGE_XPOS;
  6771. #endif
  6772. }
  6773. if(code_seen('Y'))
  6774. {
  6775. y_position = code_value();
  6776. }
  6777. else
  6778. {
  6779. #ifdef FILAMENTCHANGE_YPOS
  6780. y_position = FILAMENTCHANGE_YPOS ;
  6781. #endif
  6782. }
  6783. if (MMU2::mmu2.Enabled() && code_seen_P(PSTR("AUTO")))
  6784. automatic = true;
  6785. gcode_M600(automatic, x_position, y_position, z_shift, e_shift_init, e_shift_late);
  6786. }
  6787. break;
  6788. #endif //FILAMENTCHANGEENABLE
  6789. /*!
  6790. ### M601 - Pause print <a href="https://reprap.org/wiki/G-code#M601:_Pause_print">M601: Pause print</a>
  6791. */
  6792. /*!
  6793. ### M125 - Pause print (TODO: not implemented)
  6794. */
  6795. /*!
  6796. ### M25 - Pause SD print <a href="https://reprap.org/wiki/G-code#M25:_Pause_SD_print">M25: Pause SD print</a>
  6797. */
  6798. case 25:
  6799. case 601:
  6800. {
  6801. if (!isPrintPaused) {
  6802. st_synchronize();
  6803. ClearToSend(); //send OK even before the command finishes executing because we want to make sure it is not skipped because of cmdqueue_pop_front();
  6804. cmdqueue_pop_front(); //trick because we want skip this command (M601) after restore
  6805. lcd_pause_print();
  6806. }
  6807. }
  6808. break;
  6809. /*!
  6810. ### M602 - Resume print <a href="https://reprap.org/wiki/G-code#M602:_Resume_print">M602: Resume print</a>
  6811. */
  6812. case 602:
  6813. {
  6814. if (isPrintPaused) lcd_resume_print();
  6815. }
  6816. break;
  6817. /*!
  6818. ### M603 - Stop print <a href="https://reprap.org/wiki/G-code#M603:_Stop_print">M603: Stop print</a>
  6819. */
  6820. case 603: {
  6821. lcd_print_stop();
  6822. }
  6823. break;
  6824. #ifdef PINDA_THERMISTOR
  6825. /*!
  6826. ### M860 - Wait for extruder temperature (PINDA) <a href="https://reprap.org/wiki/G-code#M860_Wait_for_Probe_Temperature">M860 Wait for Probe Temperature</a>
  6827. Wait for PINDA thermistor to reach target temperature
  6828. #### Usage
  6829. M860 [ S ]
  6830. #### Parameters
  6831. - `S` - Target temperature
  6832. */
  6833. case 860:
  6834. {
  6835. int set_target_pinda = 0;
  6836. if (code_seen('S')) {
  6837. set_target_pinda = code_value_short();
  6838. }
  6839. else {
  6840. break;
  6841. }
  6842. LCD_MESSAGERPGM(_T(MSG_PLEASE_WAIT));
  6843. SERIAL_PROTOCOLPGM("Wait for PINDA target temperature:");
  6844. SERIAL_PROTOCOLLN(set_target_pinda);
  6845. codenum = _millis();
  6846. cancel_heatup = false;
  6847. bool is_pinda_cooling = false;
  6848. if ((degTargetBed() == 0) && (degTargetHotend(0) == 0)) {
  6849. is_pinda_cooling = true;
  6850. }
  6851. while ( ((!is_pinda_cooling) && (!cancel_heatup) && (current_temperature_pinda < set_target_pinda)) || (is_pinda_cooling && (current_temperature_pinda > set_target_pinda)) ) {
  6852. if ((_millis() - codenum) > 1000) //Print Temp Reading every 1 second while waiting.
  6853. {
  6854. SERIAL_PROTOCOLPGM("P:");
  6855. SERIAL_PROTOCOL_F(current_temperature_pinda, 1);
  6856. SERIAL_PROTOCOL('/');
  6857. SERIAL_PROTOCOLLN(set_target_pinda);
  6858. codenum = _millis();
  6859. }
  6860. manage_heater();
  6861. manage_inactivity();
  6862. lcd_update(0);
  6863. }
  6864. LCD_MESSAGERPGM(MSG_OK);
  6865. break;
  6866. }
  6867. /*!
  6868. ### M861 - Set/Get PINDA temperature compensation offsets <a href="https://reprap.org/wiki/G-code#M861_Set_Probe_Thermal_Compensation">M861 Set Probe Thermal Compensation</a>
  6869. Set compensation ustep value `S` for compensation table index `I`.
  6870. #### Usage
  6871. M861 [ ? | ! | Z | S | I ]
  6872. #### Parameters
  6873. - `?` - Print current EEPROM offset values
  6874. - `!` - Set factory default values
  6875. - `Z` - Set all values to 0 (effectively disabling PINDA temperature compensation)
  6876. - `S` - Microsteps
  6877. - `I` - Table index
  6878. */
  6879. case 861: {
  6880. const char * const _header = PSTR("index, temp, ustep, um");
  6881. if (code_seen('?')) { // ? - Print out current EEPROM offset values
  6882. int16_t usteps = 0;
  6883. SERIAL_PROTOCOLPGM("PINDA cal status: ");
  6884. SERIAL_PROTOCOLLN(calibration_status_pinda());
  6885. SERIAL_PROTOCOLLNRPGM(_header);
  6886. for (uint8_t i = 0; i < 6; i++)
  6887. {
  6888. if(i > 0) {
  6889. usteps = eeprom_read_word((uint16_t*) EEPROM_PROBE_TEMP_SHIFT + (i - 1));
  6890. }
  6891. float mm = ((float)usteps) / cs.axis_steps_per_unit[Z_AXIS];
  6892. i == 0 ? SERIAL_PROTOCOLPGM("n/a") : SERIAL_PROTOCOL(i - 1);
  6893. SERIAL_PROTOCOLPGM(", ");
  6894. SERIAL_PROTOCOL(35 + (i * 5));
  6895. SERIAL_PROTOCOLPGM(", ");
  6896. SERIAL_PROTOCOL(usteps);
  6897. SERIAL_PROTOCOLPGM(", ");
  6898. SERIAL_PROTOCOLLN(mm * 1000);
  6899. }
  6900. }
  6901. else if (code_seen('!')) { // ! - Set factory default values
  6902. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  6903. int16_t z_shift = 8; //40C - 20um - 8usteps
  6904. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT, z_shift);
  6905. z_shift = 24; //45C - 60um - 24usteps
  6906. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + 1, z_shift);
  6907. z_shift = 48; //50C - 120um - 48usteps
  6908. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + 2, z_shift);
  6909. z_shift = 80; //55C - 200um - 80usteps
  6910. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + 3, z_shift);
  6911. z_shift = 120; //60C - 300um - 120usteps
  6912. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + 4, z_shift);
  6913. SERIAL_PROTOCOLLNPGM("factory restored");
  6914. }
  6915. else if (code_seen('Z')) { // Z - Set all values to 0 (effectively disabling PINDA temperature compensation)
  6916. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  6917. int16_t z_shift = 0;
  6918. for (uint8_t i = 0; i < 5; i++) {
  6919. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  6920. }
  6921. SERIAL_PROTOCOLLNPGM("zerorized");
  6922. }
  6923. else if (code_seen('S')) { // Sxxx Iyyy - Set compensation ustep value S for compensation table index I
  6924. int16_t usteps = code_value_short();
  6925. if (code_seen('I')) {
  6926. uint8_t index = code_value_uint8();
  6927. if (index < 5) {
  6928. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + index, usteps);
  6929. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  6930. SERIAL_PROTOCOLLNRPGM(_header);
  6931. for (uint8_t i = 0; i < 6; i++)
  6932. {
  6933. usteps = 0;
  6934. if (i > 0) {
  6935. usteps = eeprom_read_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + (i - 1));
  6936. }
  6937. float mm = ((float)usteps) / cs.axis_steps_per_unit[Z_AXIS];
  6938. i == 0 ? SERIAL_PROTOCOLPGM("n/a") : SERIAL_PROTOCOL(i - 1);
  6939. SERIAL_PROTOCOLPGM(", ");
  6940. SERIAL_PROTOCOL(35 + (i * 5));
  6941. SERIAL_PROTOCOLPGM(", ");
  6942. SERIAL_PROTOCOL(usteps);
  6943. SERIAL_PROTOCOLPGM(", ");
  6944. SERIAL_PROTOCOLLN(mm * 1000);
  6945. }
  6946. }
  6947. }
  6948. }
  6949. else {
  6950. SERIAL_PROTOCOLLNPGM("no valid command");
  6951. }
  6952. } break;
  6953. #endif //PINDA_THERMISTOR
  6954. /*!
  6955. ### M862 - Print checking <a href="https://reprap.org/wiki/G-code#M862:_Print_checking">M862: Print checking</a>
  6956. Checks the parameters of the printer and gcode and performs compatibility check
  6957. - M862.1 { P<nozzle_diameter> | Q } 0.25/0.40/0.60
  6958. - M862.2 { P<model_code> | Q }
  6959. - M862.3 { P"<model_name>" | Q }
  6960. - M862.4 { P<fw_version> | Q }
  6961. - M862.5 { P<gcode_level> | Q }
  6962. When run with P<> argument, the check is performed against the input value.
  6963. When run with Q argument, the current value is shown.
  6964. M862.3 accepts text identifiers of printer types too.
  6965. The syntax of M862.3 is (note the quotes around the type):
  6966. M862.3 P "MK3S"
  6967. Accepted printer type identifiers and their numeric counterparts:
  6968. - MK1 (100)
  6969. - MK2 (200)
  6970. - MK2MM (201)
  6971. - MK2S (202)
  6972. - MK2SMM (203)
  6973. - MK2.5 (250)
  6974. - MK2.5MMU2 (20250)
  6975. - MK2.5S (252)
  6976. - MK2.5SMMU2S (20252)
  6977. - MK3 (300)
  6978. - MK3MMU2 (20300)
  6979. - MK3S (302)
  6980. - MK3SMMU2S (20302)
  6981. */
  6982. case 862: // M862: print checking
  6983. float nDummy;
  6984. uint8_t nCommand;
  6985. nCommand=(uint8_t)(modff(code_value_float(),&nDummy)*10.0+0.5);
  6986. switch((ClPrintChecking)nCommand)
  6987. {
  6988. case ClPrintChecking::_Nozzle: // ~ .1
  6989. uint16_t nDiameter;
  6990. if(code_seen('P'))
  6991. {
  6992. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  6993. nozzle_diameter_check(nDiameter);
  6994. }
  6995. else if(code_seen('Q'))
  6996. SERIAL_PROTOCOLLN((float)eeprom_read_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM)/1000.0);
  6997. break;
  6998. case ClPrintChecking::_Model: // ~ .2
  6999. if(code_seen('P'))
  7000. {
  7001. uint16_t nPrinterModel;
  7002. nPrinterModel=(uint16_t)code_value_long();
  7003. // based on current state of MMU (active/stopped/connecting) perform a runtime update of the printer type
  7004. fSetMmuMode(MMU2::mmu2.Enabled());
  7005. printer_model_check(nPrinterModel);
  7006. }
  7007. else if(code_seen('Q'))
  7008. SERIAL_PROTOCOLLN(nPrinterType);
  7009. break;
  7010. case ClPrintChecking::_Smodel: // ~ .3
  7011. if(code_seen('P'))
  7012. {
  7013. fSetMmuMode(MMU2::mmu2.Enabled());
  7014. printer_smodel_check(strchr_pointer);
  7015. }
  7016. else if(code_seen('Q'))
  7017. SERIAL_PROTOCOLLNRPGM(sPrinterName);
  7018. break;
  7019. case ClPrintChecking::_Version: // ~ .4
  7020. if(code_seen('P'))
  7021. fw_version_check(++strchr_pointer);
  7022. else if(code_seen('Q'))
  7023. SERIAL_PROTOCOLLNRPGM(FW_VERSION_STR_P());
  7024. break;
  7025. case ClPrintChecking::_Gcode: // ~ .5
  7026. if(code_seen('P'))
  7027. {
  7028. uint16_t nGcodeLevel;
  7029. nGcodeLevel=(uint16_t)code_value_long();
  7030. gcode_level_check(nGcodeLevel);
  7031. }
  7032. else if(code_seen('Q'))
  7033. SERIAL_PROTOCOLLN(GCODE_LEVEL);
  7034. break;
  7035. }
  7036. break;
  7037. #ifdef LIN_ADVANCE
  7038. /*!
  7039. ### M900 - Set Linear advance options <a href="https://reprap.org/wiki/G-code#M900_Set_Linear_Advance_Scaling_Factors">M900 Set Linear Advance Scaling Factors</a>
  7040. Sets the advance extrusion factors for Linear Advance. If any of the R, W, H, or D parameters are set to zero the ratio will be computed dynamically during printing.
  7041. #### Usage
  7042. M900 [ K | R | W | H | D]
  7043. #### Parameters
  7044. - `K` - Advance K factor
  7045. - `R` - Set ratio directly (overrides WH/D)
  7046. - `W` - Width
  7047. - `H` - Height
  7048. - `D` - Diameter Set ratio from WH/D
  7049. */
  7050. case 900:
  7051. gcode_M900();
  7052. break;
  7053. #endif
  7054. /*!
  7055. ### M907 - Set digital trimpot motor current in mA using axis codes <a href="https://reprap.org/wiki/G-code#M907:_Set_digital_trimpot_motor">M907: Set digital trimpot motor</a>
  7056. Set digital trimpot motor current using axis codes (X, Y, Z, E, B, S).
  7057. M907 has no effect when the experimental Extruder motor current scaling mode is active (that applies to farm printing as well)
  7058. #### Usage
  7059. M907 [ X | Y | Z | E | B | S ]
  7060. #### Parameters
  7061. - `X` - X motor driver
  7062. - `Y` - Y motor driver
  7063. - `Z` - Z motor driver
  7064. - `E` - Extruder motor driver
  7065. - `B` - Second Extruder motor driver
  7066. - `S` - All motors
  7067. */
  7068. case 907:
  7069. {
  7070. #ifdef TMC2130
  7071. // See tmc2130_cur2val() for translation to 0 .. 63 range
  7072. for (uint_least8_t i = 0; i < NUM_AXIS; i++){
  7073. if(code_seen(axis_codes[i])){
  7074. if( i == E_AXIS && FarmOrUserECool() ){
  7075. SERIAL_ECHORPGM(eMotorCurrentScalingEnabled);
  7076. SERIAL_ECHOLNPGM(", M907 E ignored");
  7077. continue;
  7078. }
  7079. long cur_mA = code_value_long();
  7080. uint8_t val = tmc2130_cur2val(cur_mA);
  7081. tmc2130_set_current_h(i, val);
  7082. tmc2130_set_current_r(i, val);
  7083. //if (i == E_AXIS) printf_P(PSTR("E-axis current=%ldmA\n"), cur_mA);
  7084. }
  7085. }
  7086. #else //TMC2130
  7087. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  7088. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) st_current_set(i,code_value());
  7089. if(code_seen('B')) st_current_set(4,code_value());
  7090. if(code_seen('S')) for(int i=0;i<=4;i++) st_current_set(i,code_value());
  7091. #endif
  7092. #ifdef MOTOR_CURRENT_PWM_XY_PIN
  7093. if(code_seen('X')) st_current_set(0, code_value());
  7094. #endif
  7095. #ifdef MOTOR_CURRENT_PWM_Z_PIN
  7096. if(code_seen('Z')) st_current_set(1, code_value());
  7097. #endif
  7098. #ifdef MOTOR_CURRENT_PWM_E_PIN
  7099. if(code_seen('E')) st_current_set(2, code_value());
  7100. #endif
  7101. #endif //TMC2130
  7102. }
  7103. break;
  7104. /*!
  7105. ### M908 - Control digital trimpot directly <a href="https://reprap.org/wiki/G-code#M908:_Control_digital_trimpot_directly">M908: Control digital trimpot directly</a>
  7106. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code. Not usable on Prusa printers.
  7107. #### Usage
  7108. M908 [ P | S ]
  7109. #### Parameters
  7110. - `P` - channel
  7111. - `S` - current
  7112. */
  7113. case 908:
  7114. {
  7115. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  7116. uint8_t channel,current;
  7117. if(code_seen('P')) channel=code_value();
  7118. if(code_seen('S')) current=code_value();
  7119. digitalPotWrite(channel, current);
  7120. #endif
  7121. }
  7122. break;
  7123. #ifdef TMC2130_SERVICE_CODES_M910_M918
  7124. /*!
  7125. ### M910 - TMC2130 init <a href="https://reprap.org/wiki/G-code#M910:_TMC2130_init">M910: TMC2130 init</a>
  7126. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7127. */
  7128. case 910:
  7129. {
  7130. tmc2130_init(TMCInitParams(false, FarmOrUserECool()));
  7131. }
  7132. break;
  7133. /*!
  7134. ### M911 - Set TMC2130 holding currents <a href="https://reprap.org/wiki/G-code#M911:_Set_TMC2130_holding_currents">M911: Set TMC2130 holding currents</a>
  7135. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7136. #### Usage
  7137. M911 [ X | Y | Z | E ]
  7138. #### Parameters
  7139. - `X` - X stepper driver holding current value
  7140. - `Y` - Y stepper driver holding current value
  7141. - `Z` - Z stepper driver holding current value
  7142. - `E` - Extruder stepper driver holding current value
  7143. */
  7144. case 911:
  7145. {
  7146. if (code_seen('X')) tmc2130_set_current_h(0, code_value());
  7147. if (code_seen('Y')) tmc2130_set_current_h(1, code_value());
  7148. if (code_seen('Z')) tmc2130_set_current_h(2, code_value());
  7149. if (code_seen('E')) tmc2130_set_current_h(3, code_value());
  7150. }
  7151. break;
  7152. /*!
  7153. ### M912 - Set TMC2130 running currents <a href="https://reprap.org/wiki/G-code#M912:_Set_TMC2130_running_currents">M912: Set TMC2130 running currents</a>
  7154. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7155. #### Usage
  7156. M912 [ X | Y | Z | E ]
  7157. #### Parameters
  7158. - `X` - X stepper driver running current value
  7159. - `Y` - Y stepper driver running current value
  7160. - `Z` - Z stepper driver running current value
  7161. - `E` - Extruder stepper driver running current value
  7162. */
  7163. case 912:
  7164. {
  7165. if (code_seen('X')) tmc2130_set_current_r(0, code_value());
  7166. if (code_seen('Y')) tmc2130_set_current_r(1, code_value());
  7167. if (code_seen('Z')) tmc2130_set_current_r(2, code_value());
  7168. if (code_seen('E')) tmc2130_set_current_r(3, code_value());
  7169. }
  7170. break;
  7171. /*!
  7172. ### M913 - Print TMC2130 currents <a href="https://reprap.org/wiki/G-code#M913:_Print_TMC2130_currents">M913: Print TMC2130 currents</a>
  7173. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7174. Shows TMC2130 currents.
  7175. */
  7176. case 913:
  7177. {
  7178. tmc2130_print_currents();
  7179. }
  7180. break;
  7181. /*!
  7182. ### M914 - Set TMC2130 normal mode <a href="https://reprap.org/wiki/G-code#M914:_Set_TMC2130_normal_mode">M914: Set TMC2130 normal mode</a>
  7183. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7184. */
  7185. case 914:
  7186. {
  7187. tmc2130_mode = TMC2130_MODE_NORMAL;
  7188. update_mode_profile();
  7189. tmc2130_init(TMCInitParams(false, FarmOrUserECool()));
  7190. }
  7191. break;
  7192. /*!
  7193. ### M915 - Set TMC2130 silent mode <a href="https://reprap.org/wiki/G-code#M915:_Set_TMC2130_silent_mode">M915: Set TMC2130 silent mode</a>
  7194. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7195. */
  7196. case 915:
  7197. {
  7198. tmc2130_mode = TMC2130_MODE_SILENT;
  7199. update_mode_profile();
  7200. tmc2130_init(TMCInitParams(false, FarmOrUserECool()));
  7201. }
  7202. break;
  7203. /*!
  7204. ### M916 - Set TMC2130 Stallguard sensitivity threshold <a href="https://reprap.org/wiki/G-code#M916:_Set_TMC2130_Stallguard_sensitivity_threshold">M916: Set TMC2130 Stallguard sensitivity threshold</a>
  7205. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7206. #### Usage
  7207. M916 [ X | Y | Z | E ]
  7208. #### Parameters
  7209. - `X` - X stepper driver stallguard sensitivity threshold value
  7210. - `Y` - Y stepper driver stallguard sensitivity threshold value
  7211. - `Z` - Z stepper driver stallguard sensitivity threshold value
  7212. - `E` - Extruder stepper driver stallguard sensitivity threshold value
  7213. */
  7214. case 916:
  7215. {
  7216. if (code_seen('X')) tmc2130_sg_thr[X_AXIS] = code_value();
  7217. if (code_seen('Y')) tmc2130_sg_thr[Y_AXIS] = code_value();
  7218. if (code_seen('Z')) tmc2130_sg_thr[Z_AXIS] = code_value();
  7219. if (code_seen('E')) tmc2130_sg_thr[E_AXIS] = code_value();
  7220. for (uint8_t a = X_AXIS; a <= E_AXIS; a++)
  7221. printf_P(_N("tmc2130_sg_thr[%c]=%d\n"), "XYZE"[a], tmc2130_sg_thr[a]);
  7222. }
  7223. break;
  7224. /*!
  7225. ### M917 - Set TMC2130 PWM amplitude offset (pwm_ampl) <a href="https://reprap.org/wiki/G-code#M917:_Set_TMC2130_PWM_amplitude_offset_.28pwm_ampl.29">M917: Set TMC2130 PWM amplitude offset (pwm_ampl)</a>
  7226. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7227. #### Usage
  7228. M917 [ X | Y | Z | E ]
  7229. #### Parameters
  7230. - `X` - X stepper driver PWM amplitude offset value
  7231. - `Y` - Y stepper driver PWM amplitude offset value
  7232. - `Z` - Z stepper driver PWM amplitude offset value
  7233. - `E` - Extruder stepper driver PWM amplitude offset value
  7234. */
  7235. case 917:
  7236. {
  7237. if (code_seen('X')) tmc2130_set_pwm_ampl(0, code_value());
  7238. if (code_seen('Y')) tmc2130_set_pwm_ampl(1, code_value());
  7239. if (code_seen('Z')) tmc2130_set_pwm_ampl(2, code_value());
  7240. if (code_seen('E')) tmc2130_set_pwm_ampl(3, code_value());
  7241. }
  7242. break;
  7243. /*!
  7244. ### M918 - Set TMC2130 PWM amplitude gradient (pwm_grad) <a href="https://reprap.org/wiki/G-code#M918:_Set_TMC2130_PWM_amplitude_gradient_.28pwm_grad.29">M918: Set TMC2130 PWM amplitude gradient (pwm_grad)</a>
  7245. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7246. #### Usage
  7247. M918 [ X | Y | Z | E ]
  7248. #### Parameters
  7249. - `X` - X stepper driver PWM amplitude gradient value
  7250. - `Y` - Y stepper driver PWM amplitude gradient value
  7251. - `Z` - Z stepper driver PWM amplitude gradient value
  7252. - `E` - Extruder stepper driver PWM amplitude gradient value
  7253. */
  7254. case 918:
  7255. {
  7256. if (code_seen('X')) tmc2130_set_pwm_grad(0, code_value());
  7257. if (code_seen('Y')) tmc2130_set_pwm_grad(1, code_value());
  7258. if (code_seen('Z')) tmc2130_set_pwm_grad(2, code_value());
  7259. if (code_seen('E')) tmc2130_set_pwm_grad(3, code_value());
  7260. }
  7261. break;
  7262. #endif //TMC2130_SERVICE_CODES_M910_M918
  7263. /*!
  7264. ### M350 - Set microstepping mode <a href="https://reprap.org/wiki/G-code#M350:_Set_microstepping_mode">M350: Set microstepping mode</a>
  7265. Printers with TMC2130 drivers have `X`, `Y`, `Z` and `E` as options. The steps-per-unit value is updated accordingly. Not all resolutions are valid!
  7266. Printers without TMC2130 drivers also have `B` and `S` options. In this case, the steps-per-unit value in not changed!
  7267. #### Usage
  7268. M350 [ X | Y | Z | E | B | S ]
  7269. #### Parameters
  7270. - `X` - X new resolution
  7271. - `Y` - Y new resolution
  7272. - `Z` - Z new resolution
  7273. - `E` - E new resolution
  7274. Only valid for MK2.5(S) or printers without TMC2130 drivers
  7275. - `B` - Second extruder new resolution
  7276. - `S` - All axes new resolution
  7277. */
  7278. case 350:
  7279. {
  7280. #ifdef TMC2130
  7281. for (uint_least8_t i=0; i<NUM_AXIS; i++)
  7282. {
  7283. if(code_seen(axis_codes[i]))
  7284. {
  7285. uint16_t res_new = code_value();
  7286. #ifdef ALLOW_ALL_MRES
  7287. bool res_valid = res_new > 0 && res_new <= 256 && !(res_new & (res_new - 1)); // must be a power of two
  7288. #else
  7289. bool res_valid = (res_new == 8) || (res_new == 16) || (res_new == 32); // resolutions valid for all axis
  7290. res_valid |= (i != E_AXIS) && ((res_new == 1) || (res_new == 2) || (res_new == 4)); // resolutions valid for X Y Z only
  7291. res_valid |= (i == E_AXIS) && ((res_new == 64) || (res_new == 128)); // resolutions valid for E only
  7292. #endif
  7293. if (res_valid)
  7294. {
  7295. st_synchronize();
  7296. uint16_t res = tmc2130_get_res(i);
  7297. tmc2130_set_res(i, res_new);
  7298. cs.axis_ustep_resolution[i] = res_new;
  7299. if (res_new > res)
  7300. {
  7301. uint16_t fac = (res_new / res);
  7302. cs.axis_steps_per_unit[i] *= fac;
  7303. position[i] *= fac;
  7304. }
  7305. else
  7306. {
  7307. uint16_t fac = (res / res_new);
  7308. cs.axis_steps_per_unit[i] /= fac;
  7309. position[i] /= fac;
  7310. }
  7311. #if defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  7312. if (i == E_AXIS)
  7313. fsensor.init();
  7314. #endif //defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  7315. }
  7316. }
  7317. }
  7318. reset_acceleration_rates();
  7319. #else //TMC2130
  7320. #if defined(X_MS1_PIN) && X_MS1_PIN > -1
  7321. if(code_seen('S')) for(int i=0;i<=4;i++) microstep_mode(i,code_value());
  7322. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_mode(i,(uint8_t)code_value());
  7323. if(code_seen('B')) microstep_mode(4,code_value());
  7324. microstep_readings();
  7325. #endif
  7326. #endif //TMC2130
  7327. }
  7328. break;
  7329. /*!
  7330. ### M351 - Toggle Microstep Pins <a href="https://reprap.org/wiki/G-code#M351:_Toggle_MS1_MS2_pins_directly">M351: Toggle MS1 MS2 pins directly</a>
  7331. Toggle MS1 MS2 pins directly.
  7332. #### Usage
  7333. M351 [B<0|1>] [E<0|1>] S<1|2> [X<0|1>] [Y<0|1>] [Z<0|1>]
  7334. #### Parameters
  7335. - `X` - Update X axis
  7336. - `Y` - Update Y axis
  7337. - `Z` - Update Z axis
  7338. - `E` - Update E axis
  7339. - `S` - which MSx pin to toggle
  7340. - `B` - new pin value
  7341. */
  7342. case 351:
  7343. {
  7344. #if defined(X_MS1_PIN) && X_MS1_PIN > -1
  7345. if(code_seen('S')) switch((int)code_value())
  7346. {
  7347. case 1:
  7348. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_ms(i,code_value(),-1);
  7349. if(code_seen('B')) microstep_ms(4,code_value(),-1);
  7350. break;
  7351. case 2:
  7352. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_ms(i,-1,code_value());
  7353. if(code_seen('B')) microstep_ms(4,-1,code_value());
  7354. break;
  7355. }
  7356. microstep_readings();
  7357. #endif
  7358. }
  7359. break;
  7360. /*!
  7361. ### M701 - Load filament to extruder <a href="https://reprap.org/wiki/G-code#M701:_Load_filament">M701: Load filament</a>
  7362. Load filament into the active extruder.
  7363. #### Usage
  7364. M701 [ P | T | L | Z ]
  7365. #### Parameters
  7366. - `P` - n index of MMU slot (zero based, so 0-4 like T0 and T4)
  7367. - `T` - Alias of `P`. Used for compatibility with Marlin
  7368. - `L` - Extrude distance for insertion (positive value)(manual reload)
  7369. - `Z` - Move the Z axis by this distance. Default value MIN_Z_FOR_LOAD
  7370. */
  7371. case 701:
  7372. {
  7373. uint8_t mmuSlotIndex = 0xffU;
  7374. float fastLoadLength = FILAMENTCHANGE_FIRSTFEED; // Only used without MMU
  7375. float z_target = MIN_Z_FOR_LOAD;
  7376. if( MMU2::mmu2.Enabled() )
  7377. {
  7378. if( code_seen('P') || code_seen('T') ) {
  7379. mmuSlotIndex = code_value_uint8();
  7380. }
  7381. }
  7382. if (code_seen('L')) fastLoadLength = code_value();
  7383. // Z lift. For safety only allow positive values
  7384. if (code_seen('Z')) z_target = fabs(code_value());
  7385. // Raise the Z axis
  7386. float delta = raise_z(z_target);
  7387. // Load filament
  7388. gcode_M701(fastLoadLength, mmuSlotIndex);
  7389. // Restore Z axis
  7390. raise_z(-delta);
  7391. }
  7392. break;
  7393. /*!
  7394. ### M702 - Unload filament <a href="https://reprap.org/wiki/G-code#M702:_Unload_filament">G32: Undock Z Probe sled</a>
  7395. #### Usage
  7396. M702 [ U | Z ]
  7397. #### Parameters
  7398. - `U` - Retract distance for removal (manual reload). Default value is 0.
  7399. - `Z` - Move the Z axis by this distance. Default value MIN_Z_FOR_UNLOAD.
  7400. */
  7401. case 702:
  7402. {
  7403. float z_target = MIN_Z_FOR_UNLOAD;
  7404. float unloadLength = FILAMENTCHANGE_FINALRETRACT;
  7405. if (code_seen('U')) unloadLength = code_value();
  7406. // For safety only allow positive values
  7407. if (code_seen('Z')) z_target = fabs(code_value());
  7408. // Raise the Z axis
  7409. float delta = raise_z(z_target);
  7410. // Unload filament
  7411. if (MMU2::mmu2.Enabled()) MMU2::mmu2.unload();
  7412. else unload_filament(unloadLength);
  7413. // Restore Z axis
  7414. raise_z(-delta);
  7415. }
  7416. break;
  7417. /*!
  7418. ### M704 - Load to MMU <a href="https://reprap.org/wiki/G-code#M704:_Load_to_MMU">M704: Load to MMU</a>
  7419. #### Usage
  7420. M704 [ P ]
  7421. #### Parameters
  7422. - `P` - n index of slot (zero based, so 0-4 like T0 and T4)
  7423. */
  7424. case 704:
  7425. {
  7426. gcodes_M704_M705_M706(704);
  7427. }
  7428. break;
  7429. /*!
  7430. ### M705 - Eject filament <a href="https://reprap.org/wiki/G-code#M705:_Eject_filament">M705: Eject filament</a>
  7431. #### Usage
  7432. M705 [ P ]
  7433. #### Parameters
  7434. - `P` - n index of slot (zero based, so 0-4 like T0 and T4)
  7435. */
  7436. case 705:
  7437. {
  7438. gcodes_M704_M705_M706(705);
  7439. }
  7440. break;
  7441. /*!
  7442. ### M706 - Cut filament <a href="https://reprap.org/wiki/G-code#M706:_Cut_filament">M706: Cut filament</a>
  7443. #### Usage
  7444. M706 [ P ]
  7445. #### Parameters
  7446. - `P` - n index of slot (zero based, so 0-4 like T0 and T4)
  7447. */
  7448. case 706:
  7449. {
  7450. gcodes_M704_M705_M706(706);
  7451. }
  7452. break;
  7453. /*!
  7454. ### M707 - Read from MMU register <a href="https://reprap.org/wiki/G-code#M707:_Read_from_MMU_register">M707: Read from MMU register</a>
  7455. #### Usage
  7456. M707 [ A ]
  7457. #### Parameters
  7458. - `A` - Address of register in hexidecimal.
  7459. #### Example
  7460. M707 A0x1b - Read a 8bit integer from register 0x1b and prints the result onto the serial line.
  7461. Does nothing if the A parameter is not present or if MMU is not enabled.
  7462. */
  7463. case 707: {
  7464. if ( MMU2::mmu2.Enabled() ) {
  7465. if( code_seen('A') ) {
  7466. MMU2::mmu2.ReadRegister(uint8_t(strtol(strchr_pointer+1, NULL, 16)));
  7467. }
  7468. }
  7469. } break;
  7470. /*!
  7471. ### M708 - Write to MMU register <a href="https://reprap.org/wiki/G-code#M708:_Write_to_MMU_register">M707: Write to MMU register</a>
  7472. #### Usage
  7473. M708 [ A | X ]
  7474. #### Parameters
  7475. - `A` - Address of register in hexidecimal.
  7476. - `X` - Data to write (16-bit integer). Default value 0.
  7477. #### Example
  7478. M708 A0x1b X05 - Write to register 0x1b the value 05.
  7479. Does nothing if A parameter is missing or if MMU is not enabled.
  7480. */
  7481. case 708: {
  7482. if ( MMU2::mmu2.Enabled() ){
  7483. uint8_t addr = 0;
  7484. if( code_seen('A') ) {
  7485. addr = uint8_t(strtol(strchr_pointer+1, NULL, 16));
  7486. }
  7487. uint16_t data = 0;
  7488. if( code_seen('X') ) {
  7489. data = code_value_short();
  7490. }
  7491. if(addr){
  7492. MMU2::mmu2.WriteRegister(addr, data);
  7493. }
  7494. }
  7495. } break;
  7496. /*!
  7497. ### M709 - MMU reset <a href="https://reprap.org/wiki/G-code#M709:_MMU_reset">M709: MMU reset</a>
  7498. The MK3S cannot not power off the MMU, for that reason the functionality is not supported.
  7499. #### Usage
  7500. M709 [ X ]
  7501. #### Parameters
  7502. - `X` - Reset MMU (0:soft reset | 1:hardware reset)
  7503. #### Example
  7504. M709 X0 - issue an X0 command via communication into the MMU (soft reset)
  7505. M709 X1 - toggle the MMU's reset pin (hardware reset)
  7506. */
  7507. case 709:
  7508. {
  7509. if (MMU2::mmu2.Enabled() && code_seen('X'))
  7510. {
  7511. switch (code_value_uint8())
  7512. {
  7513. case 0:
  7514. MMU2::mmu2.Reset(MMU2::MMU2::Software);
  7515. break;
  7516. case 1:
  7517. MMU2::mmu2.Reset(MMU2::MMU2::ResetPin);
  7518. break;
  7519. default:
  7520. break;
  7521. }
  7522. }
  7523. }
  7524. break;
  7525. /*!
  7526. ### M999 - Restart after being stopped <a href="https://reprap.org/wiki/G-code#M999:_Restart_after_being_stopped_by_error">M999: Restart after being stopped by error</a>
  7527. @todo Usually doesn't work. Should be fixed or removed. Most of the time, if `Stopped` it set, the print fails and is unrecoverable.
  7528. */
  7529. case 999:
  7530. Stopped = false;
  7531. lcd_reset_alert_level();
  7532. //@@TODO gcode_LastN = Stopped_gcode_LastN;
  7533. FlushSerialRequestResend();
  7534. break;
  7535. /*!
  7536. #### End of M-Commands
  7537. */
  7538. default:
  7539. printf_P(MSG_UNKNOWN_CODE, 'M', cmdbuffer + bufindr + CMDHDRSIZE);
  7540. }
  7541. // printf_P(_N("END M-CODE=%u\n"), mcode_in_progress);
  7542. mcode_in_progress = 0;
  7543. }
  7544. }
  7545. // end if(code_seen('M')) (end of M codes)
  7546. /*!
  7547. -----------------------------------------------------------------------------------------
  7548. # T Codes
  7549. T<extruder nr.> - select extruder in case of multi extruder printer. select filament in case of MMU_V2.
  7550. #### For MMU_V2:
  7551. T<n> Gcode to extrude at least 38.10 mm at feedrate 19.02 mm/s must follow immediately to load to extruder wheels.
  7552. @n T? Gcode to extrude shouldn't have to follow, load to extruder wheels is done automatically
  7553. @n Tx Same as T?, except nozzle doesn't have to be preheated. Tc must be placed after extruder nozzle is preheated to finish filament load.
  7554. @n Tc Load to nozzle after filament was prepared by Tc and extruder nozzle is already heated.
  7555. */
  7556. else if(code_seen('T')){
  7557. TCodes(strchr_pointer, code_value_uint8());
  7558. } // end if(code_seen('T')) (end of T codes)
  7559. /*!
  7560. #### End of T-Codes
  7561. */
  7562. /**
  7563. *---------------------------------------------------------------------------------
  7564. *# D codes
  7565. */
  7566. else if (code_seen('D')) // D codes (debug)
  7567. {
  7568. switch(code_value_short())
  7569. {
  7570. /*!
  7571. ### D-1 - Endless Loop <a href="https://reprap.org/wiki/G-code#D-1:_Endless_Loop">D-1: Endless Loop</a>
  7572. */
  7573. case -1:
  7574. dcode__1(); break;
  7575. #ifdef DEBUG_DCODES
  7576. /*!
  7577. ### D0 - Reset <a href="https://reprap.org/wiki/G-code#D0:_Reset">D0: Reset</a>
  7578. #### Usage
  7579. D0 [ B ]
  7580. #### Parameters
  7581. - `B` - Bootloader
  7582. */
  7583. case 0:
  7584. dcode_0(); break;
  7585. /*!
  7586. *
  7587. ### D1 - Clear EEPROM and RESET <a href="https://reprap.org/wiki/G-code#D1:_Clear_EEPROM_and_RESET">D1: Clear EEPROM and RESET</a>
  7588. D1
  7589. *
  7590. */
  7591. case 1:
  7592. dcode_1(); break;
  7593. #endif
  7594. #if defined DEBUG_DCODE2 || defined DEBUG_DCODES
  7595. /*!
  7596. ### D2 - Read/Write RAM <a href="https://reprap.org/wiki/G-code#D2:_Read.2FWrite_RAM">D3: Read/Write RAM</a>
  7597. This command can be used without any additional parameters. It will read the entire RAM.
  7598. #### Usage
  7599. D2 [ A | C | X ]
  7600. #### Parameters
  7601. - `A` - Address (x0000-x1fff)
  7602. - `C` - Count (1-8192)
  7603. - `X` - Data
  7604. #### Notes
  7605. - The hex address needs to be lowercase without the 0 before the x
  7606. - Count is decimal
  7607. - The hex data needs to be lowercase
  7608. */
  7609. case 2:
  7610. dcode_2(); break;
  7611. #endif //DEBUG_DCODES
  7612. #if defined DEBUG_DCODE3 || defined DEBUG_DCODES
  7613. /*!
  7614. ### D3 - Read/Write EEPROM <a href="https://reprap.org/wiki/G-code#D3:_Read.2FWrite_EEPROM">D3: Read/Write EEPROM</a>
  7615. This command can be used without any additional parameters. It will read the entire eeprom.
  7616. #### Usage
  7617. D3 [ A | C | X ]
  7618. #### Parameters
  7619. - `A` - Address (x0000-x0fff)
  7620. - `C` - Count (1-4096)
  7621. - `X` - Data (hex)
  7622. #### Notes
  7623. - The hex address needs to be lowercase without the 0 before the x
  7624. - Count is decimal
  7625. - The hex data needs to be lowercase
  7626. */
  7627. case 3:
  7628. dcode_3(); break;
  7629. #endif //DEBUG_DCODE3
  7630. #ifdef DEBUG_DCODES
  7631. /*!
  7632. ### D4 - Read/Write PIN <a href="https://reprap.org/wiki/G-code#D4:_Read.2FWrite_PIN">D4: Read/Write PIN</a>
  7633. To read the digital value of a pin you need only to define the pin number.
  7634. #### Usage
  7635. D4 [ P | F | V ]
  7636. #### Parameters
  7637. - `P` - Pin (0-255)
  7638. - `F` - Function in/out (0/1)
  7639. - `V` - Value (0/1)
  7640. */
  7641. case 4:
  7642. dcode_4(); break;
  7643. #endif //DEBUG_DCODES
  7644. #if defined DEBUG_DCODE5 || defined DEBUG_DCODES
  7645. /*!
  7646. ### D5 - Read/Write FLASH <a href="https://reprap.org/wiki/G-code#D5:_Read.2FWrite_FLASH">D5: Read/Write Flash</a>
  7647. This command can be used without any additional parameters. It will read the 1kb FLASH.
  7648. #### Usage
  7649. D5 [ A | C | X | E ]
  7650. #### Parameters
  7651. - `A` - Address (x00000-x3ffff)
  7652. - `C` - Count (1-8192)
  7653. - `X` - Data (hex)
  7654. - `E` - Erase
  7655. #### Notes
  7656. - The hex address needs to be lowercase without the 0 before the x
  7657. - Count is decimal
  7658. - The hex data needs to be lowercase
  7659. */
  7660. case 5:
  7661. dcode_5(); break;
  7662. #endif //DEBUG_DCODE5
  7663. #if defined DEBUG_DCODE6 || defined DEBUG_DCODES
  7664. /*!
  7665. ### D6 - Read/Write external FLASH <a href="https://reprap.org/wiki/G-code#D6:_Read.2FWrite_external_FLASH">D6: Read/Write external Flash</a>
  7666. Reserved
  7667. */
  7668. case 6:
  7669. dcode_6(); break;
  7670. #endif
  7671. #ifdef DEBUG_DCODES
  7672. /*!
  7673. ### D7 - Read/Write Bootloader <a href="https://reprap.org/wiki/G-code#D7:_Read.2FWrite_Bootloader">D7: Read/Write Bootloader</a>
  7674. Reserved
  7675. */
  7676. case 7:
  7677. dcode_7(); break;
  7678. /*!
  7679. ### D8 - Read/Write PINDA <a href="https://reprap.org/wiki/G-code#D8:_Read.2FWrite_PINDA">D8: Read/Write PINDA</a>
  7680. #### Usage
  7681. D8 [ ? | ! | P | Z ]
  7682. #### Parameters
  7683. - `?` - Read PINDA temperature shift values
  7684. - `!` - Reset PINDA temperature shift values to default
  7685. - `P` - Pinda temperature [C]
  7686. - `Z` - Z Offset [mm]
  7687. */
  7688. case 8:
  7689. dcode_8(); break;
  7690. /*!
  7691. ### D9 - Read ADC <a href="https://reprap.org/wiki/G-code#D9:_Read.2FWrite_ADC">D9: Read ADC</a>
  7692. #### Usage
  7693. D9 [ I | V ]
  7694. #### Parameters
  7695. - `I` - ADC channel index
  7696. - `0` - Heater 0 temperature
  7697. - `1` - Heater 1 temperature
  7698. - `2` - Bed temperature
  7699. - `3` - PINDA temperature
  7700. - `4` - PWR voltage
  7701. - `5` - Ambient temperature
  7702. - `6` - BED voltage
  7703. - `V` Value to be written as simulated
  7704. */
  7705. case 9:
  7706. dcode_9(); break;
  7707. /*!
  7708. ### D10 - Set XYZ calibration = OK <a href="https://reprap.org/wiki/G-code#D10:_Set_XYZ_calibration_.3D_OK">D10: Set XYZ calibration = OK</a>
  7709. */
  7710. case 10:
  7711. dcode_10(); break;
  7712. /*!
  7713. ### D12 - Time <a href="https://reprap.org/wiki/G-code#D12:_Time">D12: Time</a>
  7714. Writes the current time in the log file.
  7715. */
  7716. #endif //DEBUG_DCODES
  7717. #ifdef XFLASH_DUMP
  7718. /*!
  7719. ### D20 - Generate an offline crash dump <a href="https://reprap.org/wiki/G-code#D20:_Generate_an_offline_crash_dump">D20: Generate an offline crash dump</a>
  7720. Generate a crash dump for later retrival.
  7721. #### Usage
  7722. D20 [E]
  7723. ### Parameters
  7724. - `E` - Perform an emergency crash dump (resets the printer).
  7725. ### Notes
  7726. - A crash dump can be later recovered with D21, or cleared with D22.
  7727. - An emergency crash dump includes register data, but will cause the printer to reset after the dump
  7728. is completed.
  7729. */
  7730. case 20: {
  7731. dcode_20();
  7732. break;
  7733. };
  7734. /*!
  7735. ### D21 - Print crash dump to serial <a href="https://reprap.org/wiki/G-code#D21:_Print_crash_dump_to_serial">D21: Print crash dump to serial</a>
  7736. Output the complete crash dump (if present) to the serial.
  7737. #### Usage
  7738. D21
  7739. ### Notes
  7740. - The starting address can vary between builds, but it's always at the beginning of the data section.
  7741. */
  7742. case 21: {
  7743. dcode_21();
  7744. break;
  7745. };
  7746. /*!
  7747. ### D22 - Clear crash dump state <a href="https://reprap.org/wiki/G-code#D22:_Clear_crash_dump_state">D22: Clear crash dump state</a>
  7748. Clear an existing internal crash dump.
  7749. #### Usage
  7750. D22
  7751. */
  7752. case 22: {
  7753. dcode_22();
  7754. break;
  7755. };
  7756. #endif //XFLASH_DUMP
  7757. #ifdef EMERGENCY_SERIAL_DUMP
  7758. /*!
  7759. ### D23 - Request emergency dump on serial <a href="https://reprap.org/wiki/G-code#D23:_Request_emergency_dump_on_serial">D23: Request emergency dump on serial</a>
  7760. On boards without offline dump support, request online dumps to the serial port on firmware faults.
  7761. When online dumps are enabled, the FW will dump memory on the serial before resetting.
  7762. #### Usage
  7763. D23 [E] [R]
  7764. #### Parameters
  7765. - `E` - Perform an emergency crash dump (resets the printer).
  7766. - `R` - Disable online dumps.
  7767. */
  7768. case 23: {
  7769. dcode_23();
  7770. break;
  7771. };
  7772. #endif
  7773. #ifdef TEMP_MODEL_DEBUG
  7774. /*!
  7775. ## D70 - Enable low-level temperature model logging for offline simulation
  7776. #### Usage
  7777. D70 [ S ]
  7778. #### Parameters
  7779. - `S` - Enable 0-1 (default 0)
  7780. */
  7781. case 70: {
  7782. if(code_seen('S'))
  7783. temp_model_log_enable(code_value_short());
  7784. break;
  7785. }
  7786. #endif
  7787. #ifdef HEATBED_ANALYSIS
  7788. /*!
  7789. ### D80 - Bed check <a href="https://reprap.org/wiki/G-code#D80:_Bed_check">D80: Bed check</a>
  7790. This command will log data to SD card file "mesh.txt".
  7791. #### Usage
  7792. D80 [ E | F | G | H | I | J ]
  7793. #### Parameters
  7794. - `E` - Dimension X (default 40)
  7795. - `F` - Dimention Y (default 40)
  7796. - `G` - Points X (default 40)
  7797. - `H` - Points Y (default 40)
  7798. - `I` - Offset X (default 74)
  7799. - `J` - Offset Y (default 34)
  7800. */
  7801. case 80:
  7802. dcode_80(); break;
  7803. /*!
  7804. ### D81 - Bed analysis <a href="https://reprap.org/wiki/G-code#D81:_Bed_analysis">D80: Bed analysis</a>
  7805. This command will log data to SD card file "wldsd.txt".
  7806. #### Usage
  7807. D81 [ E | F | G | H | I | J ]
  7808. #### Parameters
  7809. - `E` - Dimension X (default 40)
  7810. - `F` - Dimention Y (default 40)
  7811. - `G` - Points X (default 40)
  7812. - `H` - Points Y (default 40)
  7813. - `I` - Offset X (default 74)
  7814. - `J` - Offset Y (default 34)
  7815. */
  7816. case 81:
  7817. dcode_81(); break;
  7818. #endif //HEATBED_ANALYSIS
  7819. #ifdef DEBUG_DCODES
  7820. /*!
  7821. ### D106 - Print measured fan speed for different pwm values <a href="https://reprap.org/wiki/G-code#D106:_Print_measured_fan_speed_for_different_pwm_values">D106: Print measured fan speed for different pwm values</a>
  7822. */
  7823. case 106:
  7824. dcode_106(); break;
  7825. #ifdef TMC2130
  7826. /*!
  7827. ### D2130 - Trinamic stepper controller <a href="https://reprap.org/wiki/G-code#D2130:_Trinamic_stepper_controller">D2130: Trinamic stepper controller</a>
  7828. @todo Please review by owner of the code. RepRap Wiki Gcode needs to be updated after review of owner as well.
  7829. #### Usage
  7830. D2130 [ Axis | Command | Subcommand | Value ]
  7831. #### Parameters
  7832. - Axis
  7833. - `X` - X stepper driver
  7834. - `Y` - Y stepper driver
  7835. - `Z` - Z stepper driver
  7836. - `E` - Extruder stepper driver
  7837. - Commands
  7838. - `0` - Current off
  7839. - `1` - Current on
  7840. - `+` - Single step
  7841. - `-` - Single step oposite direction
  7842. - `NNN` - Value sereval steps
  7843. - `?` - Read register
  7844. - Subcommands for read register
  7845. - `mres` - Micro step resolution. More information in datasheet '5.5.2 CHOPCONF – Chopper Configuration'
  7846. - `step` - Step
  7847. - `mscnt` - Microstep counter. More information in datasheet '5.5 Motor Driver Registers'
  7848. - `mscuract` - Actual microstep current for motor. More information in datasheet '5.5 Motor Driver Registers'
  7849. - `wave` - Microstep linearity compensation curve
  7850. - `!` - Set register
  7851. - Subcommands for set register
  7852. - `mres` - Micro step resolution
  7853. - `step` - Step
  7854. - `wave` - Microstep linearity compensation curve
  7855. - Values for set register
  7856. - `0, 180 --> 250` - Off
  7857. - `0.9 --> 1.25` - Valid values (recommended is 1.1)
  7858. - `@` - Home calibrate axis
  7859. Examples:
  7860. D2130E?wave
  7861. Print extruder microstep linearity compensation curve
  7862. D2130E!wave0
  7863. Disable extruder linearity compensation curve, (sine curve is used)
  7864. D2130E!wave220
  7865. (sin(x))^1.1 extruder microstep compensation curve used
  7866. Notes:
  7867. For more information see https://www.trinamic.com/fileadmin/assets/Products/ICs_Documents/TMC2130_datasheet.pdf
  7868. *
  7869. */
  7870. case 2130:
  7871. dcode_2130(); break;
  7872. #endif //TMC2130
  7873. #if defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  7874. /*!
  7875. ### D9125 - PAT9125 filament sensor <a href="https://reprap.org/wiki/G-code#D9:_Read.2FWrite_ADC">D9125: PAT9125 filament sensor</a>
  7876. #### Usage
  7877. D9125 [ ? | ! | R | X | Y | L ]
  7878. #### Parameters
  7879. - `?` - Print values
  7880. - `!` - Print values
  7881. - `R` - Resolution. Not active in code
  7882. - `X` - X values
  7883. - `Y` - Y values
  7884. - `L` - Activate filament sensor log
  7885. */
  7886. case 9125:
  7887. dcode_9125(); break;
  7888. #endif //defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  7889. #endif //DEBUG_DCODES
  7890. default:
  7891. printf_P(MSG_UNKNOWN_CODE, 'D', cmdbuffer + bufindr + CMDHDRSIZE);
  7892. }
  7893. }
  7894. else
  7895. {
  7896. SERIAL_ECHO_START;
  7897. SERIAL_ECHORPGM(MSG_UNKNOWN_COMMAND);
  7898. SERIAL_ECHO(CMDBUFFER_CURRENT_STRING);
  7899. SERIAL_ECHOLNPGM("\"(2)");
  7900. }
  7901. KEEPALIVE_STATE(NOT_BUSY);
  7902. ClearToSend();
  7903. }
  7904. /*!
  7905. #### End of D-Codes
  7906. */
  7907. /** @defgroup GCodes G-Code List
  7908. */
  7909. // ---------------------------------------------------
  7910. void FlushSerialRequestResend()
  7911. {
  7912. //char cmdbuffer[bufindr][100]="Resend:";
  7913. MYSERIAL.flush();
  7914. printf_P(_N("%S: %ld\n%S\n"), _n("Resend"), gcode_LastN + 1, MSG_OK);
  7915. }
  7916. // Confirm the execution of a command, if sent from a serial line.
  7917. // Execution of a command from a SD card will not be confirmed.
  7918. void ClearToSend()
  7919. {
  7920. previous_millis_cmd.start();
  7921. if (buflen && ((CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB) || (CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR)))
  7922. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  7923. }
  7924. #if MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  7925. void update_currents() {
  7926. float current_high[3] = DEFAULT_PWM_MOTOR_CURRENT_LOUD;
  7927. float current_low[3] = DEFAULT_PWM_MOTOR_CURRENT;
  7928. float tmp_motor[3];
  7929. //SERIAL_ECHOLNPGM("Currents updated: ");
  7930. if (destination[Z_AXIS] < Z_SILENT) {
  7931. //SERIAL_ECHOLNPGM("LOW");
  7932. for (uint8_t i = 0; i < 3; i++) {
  7933. st_current_set(i, current_low[i]);
  7934. /*MYSERIAL.print(int(i));
  7935. SERIAL_ECHOPGM(": ");
  7936. MYSERIAL.println(current_low[i]);*/
  7937. }
  7938. }
  7939. else if (destination[Z_AXIS] > Z_HIGH_POWER) {
  7940. //SERIAL_ECHOLNPGM("HIGH");
  7941. for (uint8_t i = 0; i < 3; i++) {
  7942. st_current_set(i, current_high[i]);
  7943. /*MYSERIAL.print(int(i));
  7944. SERIAL_ECHOPGM(": ");
  7945. MYSERIAL.println(current_high[i]);*/
  7946. }
  7947. }
  7948. else {
  7949. for (uint8_t i = 0; i < 3; i++) {
  7950. float q = current_low[i] - Z_SILENT*((current_high[i] - current_low[i]) / (Z_HIGH_POWER - Z_SILENT));
  7951. tmp_motor[i] = ((current_high[i] - current_low[i]) / (Z_HIGH_POWER - Z_SILENT))*destination[Z_AXIS] + q;
  7952. st_current_set(i, tmp_motor[i]);
  7953. /*MYSERIAL.print(int(i));
  7954. SERIAL_ECHOPGM(": ");
  7955. MYSERIAL.println(tmp_motor[i]);*/
  7956. }
  7957. }
  7958. }
  7959. #endif //MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  7960. void get_coordinates() {
  7961. bool seen[4]={false,false,false,false};
  7962. for(int8_t i=0; i < NUM_AXIS; i++) {
  7963. if(code_seen(axis_codes[i]))
  7964. {
  7965. bool relative = axis_relative_modes & (1 << i);
  7966. destination[i] = code_value();
  7967. if (i == E_AXIS) {
  7968. float emult = extruder_multiplier[active_extruder];
  7969. if (emult != 1.) {
  7970. if (! relative) {
  7971. destination[i] -= current_position[i];
  7972. relative = true;
  7973. }
  7974. destination[i] *= emult;
  7975. }
  7976. }
  7977. if (relative)
  7978. destination[i] += current_position[i];
  7979. seen[i]=true;
  7980. #if MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  7981. if (i == Z_AXIS && SilentModeMenu == SILENT_MODE_AUTO) update_currents();
  7982. #endif //MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  7983. }
  7984. else destination[i] = current_position[i]; //Are these else lines really needed?
  7985. }
  7986. if(code_seen('F')) {
  7987. next_feedrate = code_value();
  7988. if(next_feedrate > 0.0) feedrate = next_feedrate;
  7989. if (!seen[0] && !seen[1] && !seen[2] && seen[3])
  7990. {
  7991. // float e_max_speed =
  7992. // printf_P(PSTR("E MOVE speed %7.3f\n"), feedrate / 60)
  7993. }
  7994. }
  7995. }
  7996. void clamp_to_software_endstops(float target[3])
  7997. {
  7998. #ifdef DEBUG_DISABLE_SWLIMITS
  7999. return;
  8000. #endif //DEBUG_DISABLE_SWLIMITS
  8001. world2machine_clamp(target[0], target[1]);
  8002. // Clamp the Z coordinate.
  8003. if (min_software_endstops) {
  8004. float negative_z_offset = 0;
  8005. #ifdef ENABLE_AUTO_BED_LEVELING
  8006. if (Z_PROBE_OFFSET_FROM_EXTRUDER < 0) negative_z_offset = negative_z_offset + Z_PROBE_OFFSET_FROM_EXTRUDER;
  8007. if (cs.add_homing[Z_AXIS] < 0) negative_z_offset = negative_z_offset + cs.add_homing[Z_AXIS];
  8008. #endif
  8009. if (target[Z_AXIS] < min_pos[Z_AXIS]+negative_z_offset) target[Z_AXIS] = min_pos[Z_AXIS]+negative_z_offset;
  8010. }
  8011. if (max_software_endstops) {
  8012. if (target[Z_AXIS] > max_pos[Z_AXIS]) target[Z_AXIS] = max_pos[Z_AXIS];
  8013. }
  8014. }
  8015. uint16_t restore_interrupted_gcode() {
  8016. // When recovering from a previous print move, restore the originally
  8017. // calculated start position on the first USB/SD command. This accounts
  8018. // properly for relative moves
  8019. if (
  8020. (saved_start_position[0] != SAVED_START_POSITION_UNSET) && (
  8021. (CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_SDCARD) ||
  8022. (CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR)
  8023. )
  8024. ) {
  8025. memcpy(current_position, saved_start_position, sizeof(current_position));
  8026. saved_start_position[0] = SAVED_START_POSITION_UNSET;
  8027. return saved_segment_idx;
  8028. }
  8029. else
  8030. return 1; //begin with the first segment
  8031. }
  8032. #ifdef MESH_BED_LEVELING
  8033. void mesh_plan_buffer_line(const float &x, const float &y, const float &z, const float &e, const float &feed_rate, const uint8_t extruder, uint16_t start_segment_idx = 0) {
  8034. float dx = x - current_position[X_AXIS];
  8035. float dy = y - current_position[Y_AXIS];
  8036. uint16_t n_segments = 0;
  8037. if (mbl.active) {
  8038. float len = fabs(dx) + fabs(dy);
  8039. if (len > 0)
  8040. // Split to 3cm segments or shorter.
  8041. n_segments = uint16_t(ceil(len / 30.f));
  8042. }
  8043. if (n_segments > 1 && start_segment_idx) {
  8044. float dz = z - current_position[Z_AXIS];
  8045. float de = e - current_position[E_AXIS];
  8046. for (uint16_t i = start_segment_idx; i < n_segments; ++ i) {
  8047. float t = float(i) / float(n_segments);
  8048. plan_buffer_line(current_position[X_AXIS] + t * dx,
  8049. current_position[Y_AXIS] + t * dy,
  8050. current_position[Z_AXIS] + t * dz,
  8051. current_position[E_AXIS] + t * de,
  8052. feed_rate, extruder, current_position, i);
  8053. if (planner_aborted)
  8054. return;
  8055. }
  8056. }
  8057. // The rest of the path.
  8058. plan_buffer_line(x, y, z, e, feed_rate, extruder, current_position);
  8059. }
  8060. #endif // MESH_BED_LEVELING
  8061. void prepare_move(uint16_t start_segment_idx)
  8062. {
  8063. clamp_to_software_endstops(destination);
  8064. previous_millis_cmd.start();
  8065. // Do not use feedmultiply for E or Z only moves
  8066. if((current_position[X_AXIS] == destination[X_AXIS]) && (current_position[Y_AXIS] == destination[Y_AXIS])) {
  8067. plan_buffer_line_destinationXYZE(feedrate/60);
  8068. }
  8069. else {
  8070. #ifdef MESH_BED_LEVELING
  8071. mesh_plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate*feedmultiply*(1./(60.f*100.f)), active_extruder, start_segment_idx);
  8072. #else
  8073. plan_buffer_line_destinationXYZE(feedrate*feedmultiply*(1./(60.f*100.f)));
  8074. #endif
  8075. }
  8076. set_current_to_destination();
  8077. }
  8078. void prepare_arc_move(bool isclockwise, uint16_t start_segment_idx) {
  8079. float r = hypot(offset[X_AXIS], offset[Y_AXIS]); // Compute arc radius for mc_arc
  8080. // Trace the arc
  8081. mc_arc(current_position, destination, offset, feedrate * feedmultiply / 60 / 100.0, r, isclockwise, active_extruder, start_segment_idx);
  8082. // As far as the parser is concerned, the position is now == target. In reality the
  8083. // motion control system might still be processing the action and the real tool position
  8084. // in any intermediate location.
  8085. set_current_to_destination();
  8086. previous_millis_cmd.start();
  8087. }
  8088. #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1
  8089. #if defined(FAN_PIN)
  8090. #if CONTROLLERFAN_PIN == FAN_PIN
  8091. #error "You cannot set CONTROLLERFAN_PIN equal to FAN_PIN"
  8092. #endif
  8093. #endif
  8094. unsigned long lastMotor = 0; //Save the time for when a motor was turned on last
  8095. unsigned long lastMotorCheck = 0;
  8096. void controllerFan()
  8097. {
  8098. if ((_millis() - lastMotorCheck) >= 2500) //Not a time critical function, so we only check every 2500ms
  8099. {
  8100. lastMotorCheck = _millis();
  8101. if(!READ(X_ENABLE_PIN) || !READ(Y_ENABLE_PIN) || !READ(Z_ENABLE_PIN) || (soft_pwm_bed > 0)
  8102. #if EXTRUDERS > 2
  8103. || !READ(E2_ENABLE_PIN)
  8104. #endif
  8105. #if EXTRUDER > 1
  8106. #if defined(X2_ENABLE_PIN) && X2_ENABLE_PIN > -1
  8107. || !READ(X2_ENABLE_PIN)
  8108. #endif
  8109. || !READ(E1_ENABLE_PIN)
  8110. #endif
  8111. || !READ(E0_ENABLE_PIN)) //If any of the drivers are enabled...
  8112. {
  8113. lastMotor = _millis(); //... set time to NOW so the fan will turn on
  8114. }
  8115. if ((_millis() - lastMotor) >= (CONTROLLERFAN_SECS*1000UL) || lastMotor == 0) //If the last time any driver was enabled, is longer since than CONTROLLERSEC...
  8116. {
  8117. digitalWrite(CONTROLLERFAN_PIN, 0);
  8118. analogWrite(CONTROLLERFAN_PIN, 0);
  8119. }
  8120. else
  8121. {
  8122. // allows digital or PWM fan output to be used (see M42 handling)
  8123. digitalWrite(CONTROLLERFAN_PIN, CONTROLLERFAN_SPEED);
  8124. analogWrite(CONTROLLERFAN_PIN, CONTROLLERFAN_SPEED);
  8125. }
  8126. }
  8127. }
  8128. #endif
  8129. #ifdef SAFETYTIMER
  8130. /**
  8131. * @brief Turn off heating after safetytimer_inactive_time milliseconds of inactivity
  8132. *
  8133. * Full screen blocking notification message is shown after heater turning off.
  8134. * Paused print is not considered inactivity, as nozzle is cooled anyway and bed cooling would
  8135. * damage print.
  8136. *
  8137. * If safetytimer_inactive_time is zero, feature is disabled (heating is never turned off because of inactivity)
  8138. */
  8139. static void handleSafetyTimer()
  8140. {
  8141. #if (EXTRUDERS > 1)
  8142. #error Implemented only for one extruder.
  8143. #endif //(EXTRUDERS > 1)
  8144. if (printer_active() || (!degTargetBed() && !degTargetHotend(0)) || (!safetytimer_inactive_time))
  8145. {
  8146. safetyTimer.stop();
  8147. }
  8148. else if ((degTargetBed() || degTargetHotend(0)) && (!safetyTimer.running()))
  8149. {
  8150. safetyTimer.start();
  8151. }
  8152. else if (safetyTimer.expired(farm_mode?FARM_DEFAULT_SAFETYTIMER_TIME_ms:safetytimer_inactive_time))
  8153. {
  8154. setTargetBed(0);
  8155. setAllTargetHotends(0);
  8156. lcd_show_fullscreen_message_and_wait_P(_i("Heating disabled by safety timer."));////MSG_BED_HEATING_SAFETY_DISABLED c=20 r=4
  8157. }
  8158. }
  8159. #endif //SAFETYTIMER
  8160. void manage_inactivity(bool ignore_stepper_queue/*=false*/) //default argument set in Marlin.h
  8161. {
  8162. #ifdef FILAMENT_SENSOR
  8163. if (fsensor.update()) {
  8164. lcd_draw_update = 1; //cause lcd update so that fsensor event polling can be done from the lcd draw routine.
  8165. }
  8166. #endif
  8167. #ifdef SAFETYTIMER
  8168. handleSafetyTimer();
  8169. #endif //SAFETYTIMER
  8170. #if defined(KILL_PIN) && KILL_PIN > -1
  8171. static int killCount = 0; // make the inactivity button a bit less responsive
  8172. const int KILL_DELAY = 10000;
  8173. #endif
  8174. if(buflen < (BUFSIZE-1)){
  8175. get_command();
  8176. }
  8177. if(previous_millis_cmd.expired(max_inactive_time))
  8178. if(max_inactive_time)
  8179. kill(_n("Inactivity Shutdown"), 4);
  8180. if(stepper_inactive_time) {
  8181. if(previous_millis_cmd.expired(stepper_inactive_time))
  8182. {
  8183. if(blocks_queued() == false && ignore_stepper_queue == false) {
  8184. disable_x();
  8185. disable_y();
  8186. disable_z();
  8187. disable_e0();
  8188. disable_e1();
  8189. disable_e2();
  8190. }
  8191. }
  8192. }
  8193. #ifdef CHDK //Check if pin should be set to LOW after M240 set it to HIGH
  8194. if (chdkActive && (_millis() - chdkHigh > CHDK_DELAY))
  8195. {
  8196. chdkActive = false;
  8197. WRITE(CHDK, LOW);
  8198. }
  8199. #endif
  8200. #if defined(KILL_PIN) && KILL_PIN > -1
  8201. // Check if the kill button was pressed and wait just in case it was an accidental
  8202. // key kill key press
  8203. // -------------------------------------------------------------------------------
  8204. if( 0 == READ(KILL_PIN) )
  8205. {
  8206. killCount++;
  8207. }
  8208. else if (killCount > 0)
  8209. {
  8210. killCount--;
  8211. }
  8212. // Exceeded threshold and we can confirm that it was not accidental
  8213. // KILL the machine
  8214. // ----------------------------------------------------------------
  8215. if ( killCount >= KILL_DELAY)
  8216. {
  8217. kill(NULL, 5);
  8218. }
  8219. #endif
  8220. #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1
  8221. controllerFan(); //Check if fan should be turned on to cool stepper drivers down
  8222. #endif
  8223. #ifdef EXTRUDER_RUNOUT_PREVENT
  8224. if(previous_millis_cmd.expired(EXTRUDER_RUNOUT_SECONDS*1000))
  8225. if(degHotend(active_extruder)>EXTRUDER_RUNOUT_MINTEMP)
  8226. {
  8227. bool oldstatus=READ(E0_ENABLE_PIN);
  8228. enable_e0();
  8229. float oldepos=current_position[E_AXIS];
  8230. float oldedes=destination[E_AXIS];
  8231. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS],
  8232. destination[E_AXIS]+EXTRUDER_RUNOUT_EXTRUDE*EXTRUDER_RUNOUT_ESTEPS/cs.axis_steps_per_unit[E_AXIS],
  8233. EXTRUDER_RUNOUT_SPEED/60.*EXTRUDER_RUNOUT_ESTEPS/cs.axis_steps_per_unit[E_AXIS], active_extruder);
  8234. current_position[E_AXIS]=oldepos;
  8235. destination[E_AXIS]=oldedes;
  8236. plan_set_e_position(oldepos);
  8237. previous_millis_cmd.start();
  8238. st_synchronize();
  8239. WRITE(E0_ENABLE_PIN,oldstatus);
  8240. }
  8241. #endif
  8242. check_axes_activity();
  8243. MMU2::mmu2.mmu_loop();
  8244. // handle longpress
  8245. if(lcd_longpress_trigger)
  8246. {
  8247. // long press is not possible in modal mode, wait until ready
  8248. if (lcd_longpress_func && lcd_update_enabled)
  8249. {
  8250. lcd_longpress_func();
  8251. lcd_longpress_trigger = 0;
  8252. }
  8253. }
  8254. #if defined(AUTO_REPORT)
  8255. host_autoreport();
  8256. #endif //AUTO_REPORT
  8257. host_keepalive();
  8258. }
  8259. void kill(const char *full_screen_message, unsigned char id)
  8260. {
  8261. printf_P(_N("KILL: %d\n"), id);
  8262. //return;
  8263. cli(); // Stop interrupts
  8264. disable_heater();
  8265. disable_x();
  8266. // SERIAL_ECHOLNPGM("kill - disable Y");
  8267. disable_y();
  8268. poweroff_z();
  8269. disable_e0();
  8270. disable_e1();
  8271. disable_e2();
  8272. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  8273. pinMode(PS_ON_PIN,INPUT);
  8274. #endif
  8275. SERIAL_ERROR_START;
  8276. SERIAL_ERRORLNRPGM(_n("Printer halted. kill() called!"));////MSG_ERR_KILLED
  8277. if (full_screen_message != NULL) {
  8278. SERIAL_ERRORLNRPGM(full_screen_message);
  8279. lcd_display_message_fullscreen_P(full_screen_message);
  8280. } else {
  8281. LCD_ALERTMESSAGERPGM(_n("KILLED. "));////MSG_KILLED
  8282. }
  8283. // FMC small patch to update the LCD before ending
  8284. sei(); // enable interrupts
  8285. for ( int i=5; i--; lcd_update(0))
  8286. {
  8287. _delay(200);
  8288. }
  8289. cli(); // disable interrupts
  8290. suicide();
  8291. while(1)
  8292. {
  8293. #ifdef WATCHDOG
  8294. wdt_reset();
  8295. #endif //WATCHDOG
  8296. /* Intentionally left empty */
  8297. } // Wait for reset
  8298. }
  8299. void UnconditionalStop()
  8300. {
  8301. CRITICAL_SECTION_START;
  8302. // Disable all heaters and unroll the temperature wait loop stack
  8303. disable_heater();
  8304. cancel_heatup = true;
  8305. heating_status = HeatingStatus::NO_HEATING;
  8306. // Clear any saved printing state
  8307. cancel_saved_printing();
  8308. // Abort the planner
  8309. planner_abort_hard();
  8310. // Reset the queue
  8311. cmdqueue_reset();
  8312. cmdqueue_serial_disabled = false;
  8313. // Reset the sd status
  8314. card.sdprinting = false;
  8315. card.closefile();
  8316. st_reset_timer();
  8317. CRITICAL_SECTION_END;
  8318. }
  8319. // Emergency stop used by overtemp functions which allows recovery
  8320. // WARNING: This function is called *continuously* during a thermal failure.
  8321. //
  8322. // This either pauses (for thermal model errors) or stops *without recovery* depending on
  8323. // "allow_pause". If pause is allowed, this forces a printer-initiated instantanenous pause (just
  8324. // like an LCD pause) that bypasses the host pausing functionality. In this state the printer is
  8325. // kept in busy state and *must* be recovered from the LCD.
  8326. void ThermalStop(bool allow_pause)
  8327. {
  8328. if(Stopped == false) {
  8329. Stopped = true;
  8330. if(allow_pause && (IS_SD_PRINTING || usb_timer.running())) {
  8331. if (!isPrintPaused) {
  8332. lcd_setalertstatuspgm(_T(MSG_PAUSED_THERMAL_ERROR), LCD_STATUS_CRITICAL);
  8333. // we cannot make a distinction for the host here, the pause must be instantaneous
  8334. // so we call the lcd_pause_print to save the print state internally. Thermal errors
  8335. // disable heaters and save the original temperatures to saved_*, which will get
  8336. // overwritten by stop_and_save_print_to_ram. For this corner-case, re-instate the
  8337. // original values after the pause handler is called.
  8338. float bed_temp = saved_bed_temperature;
  8339. float ext_temp = saved_extruder_temperature;
  8340. int fan_speed = saved_fan_speed;
  8341. lcd_pause_print();
  8342. saved_bed_temperature = bed_temp;
  8343. saved_extruder_temperature = ext_temp;
  8344. saved_fan_speed = fan_speed;
  8345. }
  8346. } else {
  8347. // We got a hard thermal error and/or there is no print going on. Just stop.
  8348. lcd_print_stop();
  8349. // Also prevent further menu entry
  8350. menu_set_block(MENU_BLOCK_THERMAL_ERROR);
  8351. }
  8352. // Report the status on the serial, switch to a busy state
  8353. SERIAL_ERROR_START;
  8354. SERIAL_ERRORLNRPGM(MSG_ERR_STOPPED);
  8355. // Eventually report the stopped status on the lcd (though this is usually overridden by a
  8356. // higher-priority alert status message)
  8357. LCD_MESSAGERPGM(_T(MSG_STOPPED));
  8358. // Make a warning sound! We cannot use Sound_MakeCustom as this would stop further moves.
  8359. // Turn on the speaker here (if not already), and turn it off when back in the main loop.
  8360. WRITE(BEEPER, HIGH);
  8361. }
  8362. // Return to the status screen to stop any pending menu action which could have been
  8363. // started by the user while stuck in the Stopped state. This also ensures the NEW
  8364. // error is immediately shown.
  8365. if (menu_menu != lcd_status_screen)
  8366. lcd_return_to_status();
  8367. }
  8368. bool IsStopped() { return Stopped; };
  8369. void finishAndDisableSteppers()
  8370. {
  8371. st_synchronize();
  8372. disable_x();
  8373. disable_y();
  8374. disable_z();
  8375. disable_e0();
  8376. disable_e1();
  8377. disable_e2();
  8378. #ifndef LA_NOCOMPAT
  8379. // Steppers are disabled both when a print is stopped and also via M84 (which is additionally
  8380. // checked-for to indicate a complete file), so abuse this function to reset the LA detection
  8381. // state for the next print.
  8382. la10c_reset();
  8383. #endif
  8384. //in the end of print set estimated time to end of print and extruders used during print to default values for next print
  8385. print_time_remaining_init();
  8386. }
  8387. #ifdef FAST_PWM_FAN
  8388. void setPwmFrequency(uint8_t pin, int val)
  8389. {
  8390. val &= 0x07;
  8391. switch(digitalPinToTimer(pin))
  8392. {
  8393. #if defined(TCCR0A)
  8394. case TIMER0A:
  8395. case TIMER0B:
  8396. // TCCR0B &= ~(_BV(CS00) | _BV(CS01) | _BV(CS02));
  8397. // TCCR0B |= val;
  8398. break;
  8399. #endif
  8400. #if defined(TCCR1A)
  8401. case TIMER1A:
  8402. case TIMER1B:
  8403. // TCCR1B &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  8404. // TCCR1B |= val;
  8405. break;
  8406. #endif
  8407. #if defined(TCCR2)
  8408. case TIMER2:
  8409. case TIMER2:
  8410. TCCR2 &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  8411. TCCR2 |= val;
  8412. break;
  8413. #endif
  8414. #if defined(TCCR2A)
  8415. case TIMER2A:
  8416. case TIMER2B:
  8417. TCCR2B &= ~(_BV(CS20) | _BV(CS21) | _BV(CS22));
  8418. TCCR2B |= val;
  8419. break;
  8420. #endif
  8421. #if defined(TCCR3A)
  8422. case TIMER3A:
  8423. case TIMER3B:
  8424. case TIMER3C:
  8425. TCCR3B &= ~(_BV(CS30) | _BV(CS31) | _BV(CS32));
  8426. TCCR3B |= val;
  8427. break;
  8428. #endif
  8429. #if defined(TCCR4A)
  8430. case TIMER4A:
  8431. case TIMER4B:
  8432. case TIMER4C:
  8433. TCCR4B &= ~(_BV(CS40) | _BV(CS41) | _BV(CS42));
  8434. TCCR4B |= val;
  8435. break;
  8436. #endif
  8437. #if defined(TCCR5A)
  8438. case TIMER5A:
  8439. case TIMER5B:
  8440. case TIMER5C:
  8441. TCCR5B &= ~(_BV(CS50) | _BV(CS51) | _BV(CS52));
  8442. TCCR5B |= val;
  8443. break;
  8444. #endif
  8445. }
  8446. }
  8447. #endif //FAST_PWM_FAN
  8448. //! @brief Get and validate extruder number
  8449. //!
  8450. //! If it is not specified, active_extruder is returned in parameter extruder.
  8451. //! @param [in] code M code number
  8452. //! @param [out] extruder
  8453. //! @return error
  8454. //! @retval true Invalid extruder specified in T code
  8455. //! @retval false Valid extruder specified in T code, or not specifiead
  8456. bool setTargetedHotend(int code, uint8_t &extruder)
  8457. {
  8458. extruder = active_extruder;
  8459. if(code_seen('T')) {
  8460. extruder = code_value_uint8();
  8461. if(extruder >= EXTRUDERS) {
  8462. SERIAL_ECHO_START;
  8463. serialprintPGM(PSTR("M"));
  8464. SERIAL_ECHO(code);
  8465. SERIAL_ECHOPGM(" Invalid extruder ");
  8466. SERIAL_PROTOCOLLN((int)extruder);
  8467. return true;
  8468. }
  8469. }
  8470. return false;
  8471. }
  8472. void save_statistics(unsigned long _total_filament_used, unsigned long _total_print_time) { //_total_filament_used unit: mm/100; print time in s
  8473. uint32_t _previous_filament = eeprom_init_default_dword((uint32_t *)EEPROM_FILAMENTUSED, 0); //_previous_filament unit: cm
  8474. uint32_t _previous_time = eeprom_init_default_dword((uint32_t *)EEPROM_TOTALTIME, 0); //_previous_time unit: min
  8475. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, _previous_time + (_total_print_time / 60)); // EEPROM_TOTALTIME unit: min
  8476. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, _previous_filament + (_total_filament_used / 1000));
  8477. total_filament_used = 0;
  8478. if (MMU2::mmu2.Enabled()) {
  8479. eeprom_add_dword((uint32_t *)EEPROM_TOTAL_TOOLCHANGE_COUNT, MMU2::mmu2.ToolChangeCounter());
  8480. // @@TODO why were EEPROM_MMU_FAIL_TOT and EEPROM_MMU_LOAD_FAIL_TOT behaving differently - i.e. updated with every change?
  8481. MMU2::mmu2.ClearToolChangeCounter();
  8482. MMU2::mmu2.ClearTMCFailures(); // not stored into EEPROM
  8483. }
  8484. }
  8485. float calculate_extruder_multiplier(float diameter) {
  8486. float out = 1.f;
  8487. if (cs.volumetric_enabled && diameter > 0.f) {
  8488. float area = M_PI * diameter * diameter * 0.25;
  8489. out = 1.f / area;
  8490. }
  8491. if (extrudemultiply != 100)
  8492. out *= float(extrudemultiply) * 0.01f;
  8493. return out;
  8494. }
  8495. void calculate_extruder_multipliers() {
  8496. extruder_multiplier[0] = calculate_extruder_multiplier(cs.filament_size[0]);
  8497. #if EXTRUDERS > 1
  8498. extruder_multiplier[1] = calculate_extruder_multiplier(cs.filament_size[1]);
  8499. #if EXTRUDERS > 2
  8500. extruder_multiplier[2] = calculate_extruder_multiplier(cs.filament_size[2]);
  8501. #endif
  8502. #endif
  8503. }
  8504. void delay_keep_alive(unsigned int ms)
  8505. {
  8506. for (;;) {
  8507. manage_heater();
  8508. // Manage inactivity, but don't disable steppers on timeout.
  8509. manage_inactivity(true);
  8510. lcd_update(0);
  8511. if (ms == 0)
  8512. break;
  8513. else if (ms >= 50) {
  8514. _delay(50);
  8515. ms -= 50;
  8516. } else {
  8517. _delay(ms);
  8518. ms = 0;
  8519. }
  8520. }
  8521. }
  8522. static void wait_for_heater(long codenum, uint8_t extruder) {
  8523. if (!degTargetHotend(extruder))
  8524. return;
  8525. #ifdef TEMP_RESIDENCY_TIME
  8526. long residencyStart;
  8527. residencyStart = -1;
  8528. /* continue to loop until we have reached the target temp
  8529. _and_ until TEMP_RESIDENCY_TIME hasn't passed since we reached it */
  8530. cancel_heatup = false;
  8531. while ((!cancel_heatup) && ((residencyStart == -1) ||
  8532. (residencyStart >= 0 && (((unsigned int)(_millis() - residencyStart)) < (TEMP_RESIDENCY_TIME * 1000UL))))) {
  8533. #else
  8534. while (target_direction ? (isHeatingHotend(tmp_extruder)) : (isCoolingHotend(tmp_extruder) && (CooldownNoWait == false))) {
  8535. #endif //TEMP_RESIDENCY_TIME
  8536. if ((_millis() - codenum) > 1000UL)
  8537. { //Print Temp Reading and remaining time every 1 second while heating up/cooling down
  8538. if (!farm_mode) {
  8539. SERIAL_PROTOCOLPGM("T:");
  8540. SERIAL_PROTOCOL_F(degHotend(extruder), 1);
  8541. SERIAL_PROTOCOLPGM(" E:");
  8542. SERIAL_PROTOCOL((int)extruder);
  8543. #ifdef TEMP_RESIDENCY_TIME
  8544. SERIAL_PROTOCOLPGM(" W:");
  8545. if (residencyStart > -1)
  8546. {
  8547. codenum = ((TEMP_RESIDENCY_TIME * 1000UL) - (_millis() - residencyStart)) / 1000UL;
  8548. SERIAL_PROTOCOLLN(codenum);
  8549. }
  8550. else
  8551. {
  8552. SERIAL_PROTOCOLLN('?');
  8553. }
  8554. }
  8555. #else
  8556. SERIAL_PROTOCOLLN();
  8557. #endif
  8558. codenum = _millis();
  8559. }
  8560. manage_heater();
  8561. manage_inactivity(true); //do not disable steppers
  8562. lcd_update(0);
  8563. #ifdef TEMP_RESIDENCY_TIME
  8564. /* start/restart the TEMP_RESIDENCY_TIME timer whenever we reach target temp for the first time
  8565. or when current temp falls outside the hysteresis after target temp was reached */
  8566. if ((residencyStart == -1 && target_direction && (degHotend(extruder) >= (degTargetHotend(extruder) - TEMP_WINDOW))) ||
  8567. (residencyStart == -1 && !target_direction && (degHotend(extruder) <= (degTargetHotend(extruder) + TEMP_WINDOW))) ||
  8568. (residencyStart > -1 && labs(degHotend(extruder) - degTargetHotend(extruder)) > TEMP_HYSTERESIS))
  8569. {
  8570. residencyStart = _millis();
  8571. }
  8572. #endif //TEMP_RESIDENCY_TIME
  8573. }
  8574. }
  8575. void check_babystep()
  8576. {
  8577. int babystep_z = eeprom_read_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->
  8578. s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)));
  8579. if ((babystep_z < Z_BABYSTEP_MIN) || (babystep_z > Z_BABYSTEP_MAX)) {
  8580. babystep_z = 0; //if babystep value is out of min max range, set it to 0
  8581. SERIAL_ECHOLNPGM("Z live adjust out of range. Setting to 0");
  8582. eeprom_write_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->
  8583. s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),
  8584. babystep_z);
  8585. lcd_show_fullscreen_message_and_wait_P(PSTR("Z live adjust out of range. Setting to 0. Click to continue."));
  8586. lcd_update_enable(true);
  8587. }
  8588. }
  8589. #ifdef HEATBED_ANALYSIS
  8590. void d_setup()
  8591. {
  8592. pinMode(D_DATACLOCK, INPUT_PULLUP);
  8593. pinMode(D_DATA, INPUT_PULLUP);
  8594. pinMode(D_REQUIRE, OUTPUT);
  8595. digitalWrite(D_REQUIRE, HIGH);
  8596. }
  8597. float d_ReadData()
  8598. {
  8599. int digit[13];
  8600. String mergeOutput;
  8601. float output;
  8602. digitalWrite(D_REQUIRE, HIGH);
  8603. for (int i = 0; i<13; i++)
  8604. {
  8605. for (int j = 0; j < 4; j++)
  8606. {
  8607. while (digitalRead(D_DATACLOCK) == LOW) {}
  8608. while (digitalRead(D_DATACLOCK) == HIGH) {}
  8609. bitWrite(digit[i], j, digitalRead(D_DATA));
  8610. }
  8611. }
  8612. digitalWrite(D_REQUIRE, LOW);
  8613. mergeOutput = "";
  8614. output = 0;
  8615. for (int r = 5; r <= 10; r++) //Merge digits
  8616. {
  8617. mergeOutput += digit[r];
  8618. }
  8619. output = mergeOutput.toFloat();
  8620. if (digit[4] == 8) //Handle sign
  8621. {
  8622. output *= -1;
  8623. }
  8624. for (int i = digit[11]; i > 0; i--) //Handle floating point
  8625. {
  8626. output /= 10;
  8627. }
  8628. return output;
  8629. }
  8630. void bed_check(float x_dimension, float y_dimension, int x_points_num, int y_points_num, float shift_x, float shift_y) {
  8631. int t1 = 0;
  8632. int t_delay = 0;
  8633. int digit[13];
  8634. int m;
  8635. char str[3];
  8636. //String mergeOutput;
  8637. char mergeOutput[15];
  8638. float output;
  8639. int mesh_point = 0; //index number of calibration point
  8640. float bed_zero_ref_x = (-22.f + X_PROBE_OFFSET_FROM_EXTRUDER); //shift between zero point on bed and target and between probe and nozzle
  8641. float bed_zero_ref_y = (-0.6f + Y_PROBE_OFFSET_FROM_EXTRUDER);
  8642. float mesh_home_z_search = 4;
  8643. float measure_z_height = 0.2f;
  8644. float row[x_points_num];
  8645. int ix = 0;
  8646. int iy = 0;
  8647. const char* filename_wldsd = "mesh.txt";
  8648. char data_wldsd[x_points_num * 7 + 1]; //6 chars(" -A.BCD")for each measurement + null
  8649. char numb_wldsd[8]; // (" -A.BCD" + null)
  8650. #ifdef MICROMETER_LOGGING
  8651. d_setup();
  8652. #endif //MICROMETER_LOGGING
  8653. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  8654. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  8655. unsigned int custom_message_type_old = custom_message_type;
  8656. unsigned int custom_message_state_old = custom_message_state;
  8657. custom_message_type = CustomMsg::MeshBedLeveling;
  8658. custom_message_state = (x_points_num * y_points_num) + 10;
  8659. lcd_update(1);
  8660. //mbl.reset();
  8661. babystep_undo();
  8662. card.openFile(filename_wldsd, false);
  8663. /*destination[Z_AXIS] = mesh_home_z_search;
  8664. //plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  8665. plan_buffer_line_destinationXYZE(Z_LIFT_FEEDRATE);
  8666. for(int8_t i=0; i < NUM_AXIS; i++) {
  8667. current_position[i] = destination[i];
  8668. }
  8669. st_synchronize();
  8670. */
  8671. destination[Z_AXIS] = measure_z_height;
  8672. plan_buffer_line_destinationXYZE(Z_LIFT_FEEDRATE);
  8673. for(int8_t i=0; i < NUM_AXIS; i++) {
  8674. current_position[i] = destination[i];
  8675. }
  8676. st_synchronize();
  8677. /*int l_feedmultiply = */setup_for_endstop_move(false);
  8678. SERIAL_PROTOCOLPGM("Num X,Y: ");
  8679. SERIAL_PROTOCOL(x_points_num);
  8680. SERIAL_PROTOCOLPGM(",");
  8681. SERIAL_PROTOCOL(y_points_num);
  8682. SERIAL_PROTOCOLPGM("\nZ search height: ");
  8683. SERIAL_PROTOCOL(mesh_home_z_search);
  8684. SERIAL_PROTOCOLPGM("\nDimension X,Y: ");
  8685. SERIAL_PROTOCOL(x_dimension);
  8686. SERIAL_PROTOCOLPGM(",");
  8687. SERIAL_PROTOCOL(y_dimension);
  8688. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  8689. while (mesh_point != x_points_num * y_points_num) {
  8690. ix = mesh_point % x_points_num; // from 0 to MESH_NUM_X_POINTS - 1
  8691. iy = mesh_point / x_points_num;
  8692. if (iy & 1) ix = (x_points_num - 1) - ix; // Zig zag
  8693. float z0 = 0.f;
  8694. /*destination[Z_AXIS] = mesh_home_z_search;
  8695. //plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  8696. plan_buffer_line_destinationXYZE(Z_LIFT_FEEDRATE);
  8697. for(int8_t i=0; i < NUM_AXIS; i++) {
  8698. current_position[i] = destination[i];
  8699. }
  8700. st_synchronize();*/
  8701. //current_position[X_AXIS] = 13.f + ix * (x_dimension / (x_points_num - 1)) - bed_zero_ref_x + shift_x;
  8702. //current_position[Y_AXIS] = 6.4f + iy * (y_dimension / (y_points_num - 1)) - bed_zero_ref_y + shift_y;
  8703. destination[X_AXIS] = ix * (x_dimension / (x_points_num - 1)) + shift_x;
  8704. destination[Y_AXIS] = iy * (y_dimension / (y_points_num - 1)) + shift_y;
  8705. mesh_plan_buffer_line_destinationXYZE(XY_AXIS_FEEDRATE/6);
  8706. set_current_to_destination();
  8707. st_synchronize();
  8708. // printf_P(PSTR("X = %f; Y= %f \n"), current_position[X_AXIS], current_position[Y_AXIS]);
  8709. delay_keep_alive(1000);
  8710. #ifdef MICROMETER_LOGGING
  8711. //memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8712. //dtostrf(d_ReadData(), 8, 5, numb_wldsd);
  8713. //strcat(data_wldsd, numb_wldsd);
  8714. //MYSERIAL.println(data_wldsd);
  8715. //delay(1000);
  8716. //delay(3000);
  8717. //t1 = millis();
  8718. //while (digitalRead(D_DATACLOCK) == LOW) {}
  8719. //while (digitalRead(D_DATACLOCK) == HIGH) {}
  8720. memset(digit, 0, sizeof(digit));
  8721. //cli();
  8722. digitalWrite(D_REQUIRE, LOW);
  8723. for (int i = 0; i<13; i++)
  8724. {
  8725. //t1 = millis();
  8726. for (int j = 0; j < 4; j++)
  8727. {
  8728. while (digitalRead(D_DATACLOCK) == LOW) {}
  8729. while (digitalRead(D_DATACLOCK) == HIGH) {}
  8730. //printf_P(PSTR("Done %d\n"), j);
  8731. bitWrite(digit[i], j, digitalRead(D_DATA));
  8732. }
  8733. //t_delay = (millis() - t1);
  8734. //SERIAL_PROTOCOLPGM(" ");
  8735. //SERIAL_PROTOCOL_F(t_delay, 5);
  8736. //SERIAL_PROTOCOLPGM(" ");
  8737. }
  8738. //sei();
  8739. digitalWrite(D_REQUIRE, HIGH);
  8740. mergeOutput[0] = '\0';
  8741. output = 0;
  8742. for (int r = 5; r <= 10; r++) //Merge digits
  8743. {
  8744. sprintf(str, "%d", digit[r]);
  8745. strcat(mergeOutput, str);
  8746. }
  8747. output = atof(mergeOutput);
  8748. if (digit[4] == 8) //Handle sign
  8749. {
  8750. output *= -1;
  8751. }
  8752. for (int i = digit[11]; i > 0; i--) //Handle floating point
  8753. {
  8754. output *= 0.1;
  8755. }
  8756. //output = d_ReadData();
  8757. //row[ix] = current_position[Z_AXIS];
  8758. //row[ix] = d_ReadData();
  8759. row[ix] = output;
  8760. if (iy % 2 == 1 ? ix == 0 : ix == x_points_num - 1) {
  8761. memset(data_wldsd, 0, sizeof(data_wldsd));
  8762. for (int i = 0; i < x_points_num; i++) {
  8763. SERIAL_PROTOCOLPGM(" ");
  8764. SERIAL_PROTOCOL_F(row[i], 5);
  8765. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8766. dtostrf(row[i], 7, 3, numb_wldsd);
  8767. strcat(data_wldsd, numb_wldsd);
  8768. }
  8769. card.write_command(data_wldsd);
  8770. SERIAL_PROTOCOLPGM("\n");
  8771. }
  8772. custom_message_state--;
  8773. mesh_point++;
  8774. lcd_update(1);
  8775. }
  8776. #endif //MICROMETER_LOGGING
  8777. card.closefile();
  8778. //clean_up_after_endstop_move(l_feedmultiply);
  8779. }
  8780. void bed_analysis(float x_dimension, float y_dimension, int x_points_num, int y_points_num, float shift_x, float shift_y) {
  8781. int t1 = 0;
  8782. int t_delay = 0;
  8783. int digit[13];
  8784. int m;
  8785. char str[3];
  8786. //String mergeOutput;
  8787. char mergeOutput[15];
  8788. float output;
  8789. int mesh_point = 0; //index number of calibration point
  8790. float bed_zero_ref_x = (-22.f + X_PROBE_OFFSET_FROM_EXTRUDER); //shift between zero point on bed and target and between probe and nozzle
  8791. float bed_zero_ref_y = (-0.6f + Y_PROBE_OFFSET_FROM_EXTRUDER);
  8792. float mesh_home_z_search = 4;
  8793. float row[x_points_num];
  8794. int ix = 0;
  8795. int iy = 0;
  8796. const char* filename_wldsd = "wldsd.txt";
  8797. char data_wldsd[70];
  8798. char numb_wldsd[10];
  8799. d_setup();
  8800. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  8801. // We don't know where we are! HOME!
  8802. // Push the commands to the front of the message queue in the reverse order!
  8803. // There shall be always enough space reserved for these commands.
  8804. repeatcommand_front(); // repeat G80 with all its parameters
  8805. enquecommand_front_P(G28W0);
  8806. enquecommand_front_P((PSTR("G1 Z5")));
  8807. return;
  8808. }
  8809. unsigned int custom_message_type_old = custom_message_type;
  8810. unsigned int custom_message_state_old = custom_message_state;
  8811. custom_message_type = CustomMsg::MeshBedLeveling;
  8812. custom_message_state = (x_points_num * y_points_num) + 10;
  8813. lcd_update(1);
  8814. mbl.reset();
  8815. babystep_undo();
  8816. card.openFile(filename_wldsd, false);
  8817. current_position[Z_AXIS] = mesh_home_z_search;
  8818. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 60, active_extruder);
  8819. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  8820. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  8821. int l_feedmultiply = setup_for_endstop_move(false);
  8822. SERIAL_PROTOCOLPGM("Num X,Y: ");
  8823. SERIAL_PROTOCOL(x_points_num);
  8824. SERIAL_PROTOCOLPGM(",");
  8825. SERIAL_PROTOCOL(y_points_num);
  8826. SERIAL_PROTOCOLPGM("\nZ search height: ");
  8827. SERIAL_PROTOCOL(mesh_home_z_search);
  8828. SERIAL_PROTOCOLPGM("\nDimension X,Y: ");
  8829. SERIAL_PROTOCOL(x_dimension);
  8830. SERIAL_PROTOCOLPGM(",");
  8831. SERIAL_PROTOCOL(y_dimension);
  8832. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  8833. while (mesh_point != x_points_num * y_points_num) {
  8834. ix = mesh_point % x_points_num; // from 0 to MESH_NUM_X_POINTS - 1
  8835. iy = mesh_point / x_points_num;
  8836. if (iy & 1) ix = (x_points_num - 1) - ix; // Zig zag
  8837. float z0 = 0.f;
  8838. current_position[Z_AXIS] = mesh_home_z_search;
  8839. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE, active_extruder);
  8840. st_synchronize();
  8841. current_position[X_AXIS] = 13.f + ix * (x_dimension / (x_points_num - 1)) - bed_zero_ref_x + shift_x;
  8842. current_position[Y_AXIS] = 6.4f + iy * (y_dimension / (y_points_num - 1)) - bed_zero_ref_y + shift_y;
  8843. plan_buffer_line_curposXYZE(XY_AXIS_FEEDRATE, active_extruder);
  8844. st_synchronize();
  8845. if (!find_bed_induction_sensor_point_z(-10.f)) { //if we have data from z calibration max allowed difference is 1mm for each point, if we dont have data max difference is 10mm from initial point
  8846. break;
  8847. card.closefile();
  8848. }
  8849. //memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8850. //dtostrf(d_ReadData(), 8, 5, numb_wldsd);
  8851. //strcat(data_wldsd, numb_wldsd);
  8852. //MYSERIAL.println(data_wldsd);
  8853. //_delay(1000);
  8854. //_delay(3000);
  8855. //t1 = _millis();
  8856. //while (digitalRead(D_DATACLOCK) == LOW) {}
  8857. //while (digitalRead(D_DATACLOCK) == HIGH) {}
  8858. memset(digit, 0, sizeof(digit));
  8859. //cli();
  8860. digitalWrite(D_REQUIRE, LOW);
  8861. for (int i = 0; i<13; i++)
  8862. {
  8863. //t1 = _millis();
  8864. for (int j = 0; j < 4; j++)
  8865. {
  8866. while (digitalRead(D_DATACLOCK) == LOW) {}
  8867. while (digitalRead(D_DATACLOCK) == HIGH) {}
  8868. bitWrite(digit[i], j, digitalRead(D_DATA));
  8869. }
  8870. //t_delay = (_millis() - t1);
  8871. //SERIAL_PROTOCOLPGM(" ");
  8872. //SERIAL_PROTOCOL_F(t_delay, 5);
  8873. //SERIAL_PROTOCOLPGM(" ");
  8874. }
  8875. //sei();
  8876. digitalWrite(D_REQUIRE, HIGH);
  8877. mergeOutput[0] = '\0';
  8878. output = 0;
  8879. for (int r = 5; r <= 10; r++) //Merge digits
  8880. {
  8881. sprintf(str, "%d", digit[r]);
  8882. strcat(mergeOutput, str);
  8883. }
  8884. output = atof(mergeOutput);
  8885. if (digit[4] == 8) //Handle sign
  8886. {
  8887. output *= -1;
  8888. }
  8889. for (int i = digit[11]; i > 0; i--) //Handle floating point
  8890. {
  8891. output *= 0.1;
  8892. }
  8893. //output = d_ReadData();
  8894. //row[ix] = current_position[Z_AXIS];
  8895. memset(data_wldsd, 0, sizeof(data_wldsd));
  8896. for (int i = 0; i <3; i++) {
  8897. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8898. dtostrf(current_position[i], 8, 5, numb_wldsd);
  8899. strcat(data_wldsd, numb_wldsd);
  8900. strcat(data_wldsd, ";");
  8901. }
  8902. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8903. dtostrf(output, 8, 5, numb_wldsd);
  8904. strcat(data_wldsd, numb_wldsd);
  8905. //strcat(data_wldsd, ";");
  8906. card.write_command(data_wldsd);
  8907. //row[ix] = d_ReadData();
  8908. row[ix] = output; // current_position[Z_AXIS];
  8909. if (iy % 2 == 1 ? ix == 0 : ix == x_points_num - 1) {
  8910. for (int i = 0; i < x_points_num; i++) {
  8911. SERIAL_PROTOCOLPGM(" ");
  8912. SERIAL_PROTOCOL_F(row[i], 5);
  8913. }
  8914. SERIAL_PROTOCOLPGM("\n");
  8915. }
  8916. custom_message_state--;
  8917. mesh_point++;
  8918. lcd_update(1);
  8919. }
  8920. card.closefile();
  8921. clean_up_after_endstop_move(l_feedmultiply);
  8922. }
  8923. #endif //HEATBED_ANALYSIS
  8924. #ifndef PINDA_THERMISTOR
  8925. static void temp_compensation_start() {
  8926. custom_message_type = CustomMsg::TempCompPreheat;
  8927. custom_message_state = PINDA_HEAT_T + 1;
  8928. lcd_update(2);
  8929. if ((int)degHotend(active_extruder) > extrude_min_temp) {
  8930. current_position[E_AXIS] -= default_retraction;
  8931. }
  8932. plan_buffer_line_curposXYZE(400, active_extruder);
  8933. current_position[X_AXIS] = PINDA_PREHEAT_X;
  8934. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  8935. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  8936. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  8937. st_synchronize();
  8938. while (fabs(degBed() - target_temperature_bed) > 1) delay_keep_alive(1000);
  8939. for (int i = 0; i < PINDA_HEAT_T; i++) {
  8940. delay_keep_alive(1000);
  8941. custom_message_state = PINDA_HEAT_T - i;
  8942. if (custom_message_state == 99 || custom_message_state == 9) lcd_update(2); //force whole display redraw if number of digits changed
  8943. else lcd_update(1);
  8944. }
  8945. custom_message_type = CustomMsg::Status;
  8946. custom_message_state = 0;
  8947. }
  8948. static void temp_compensation_apply() {
  8949. int i_add;
  8950. int z_shift = 0;
  8951. float z_shift_mm;
  8952. if (calibration_status() == CALIBRATION_STATUS_CALIBRATED) {
  8953. if (target_temperature_bed % 10 == 0 && target_temperature_bed >= 60 && target_temperature_bed <= 100) {
  8954. i_add = (target_temperature_bed - 60) / 10;
  8955. z_shift = eeprom_read_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i_add);
  8956. z_shift_mm = z_shift / cs.axis_steps_per_unit[Z_AXIS];
  8957. }else {
  8958. //interpolation
  8959. z_shift_mm = temp_comp_interpolation(target_temperature_bed) / cs.axis_steps_per_unit[Z_AXIS];
  8960. }
  8961. printf_P(_N("\nZ shift applied:%.3f\n"), z_shift_mm);
  8962. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS] - z_shift_mm, current_position[E_AXIS], homing_feedrate[Z_AXIS] / 40, active_extruder);
  8963. st_synchronize();
  8964. plan_set_z_position(current_position[Z_AXIS]);
  8965. }
  8966. else {
  8967. //we have no temp compensation data
  8968. }
  8969. }
  8970. #endif //ndef PINDA_THERMISTOR
  8971. float temp_comp_interpolation(float inp_temperature) {
  8972. //cubic spline interpolation
  8973. int n, i, j;
  8974. float h[10], a, b, c, d, sum, s[10] = { 0 }, x[10], F[10], f[10], m[10][10] = { 0 }, temp;
  8975. int shift[10];
  8976. int temp_C[10];
  8977. n = 6; //number of measured points
  8978. shift[0] = 0;
  8979. for (i = 0; i < n; i++) {
  8980. if (i > 0) {
  8981. //read shift in steps from EEPROM
  8982. shift[i] = eeprom_read_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + (i - 1));
  8983. }
  8984. temp_C[i] = 50 + i * 10; //temperature in C
  8985. #ifdef PINDA_THERMISTOR
  8986. constexpr int start_compensating_temp = 35;
  8987. temp_C[i] = start_compensating_temp + i * 5; //temperature in degrees C
  8988. #ifdef SUPERPINDA_SUPPORT
  8989. static_assert(start_compensating_temp >= PINDA_MINTEMP, "Temperature compensation start point is lower than PINDA_MINTEMP.");
  8990. #endif //SUPERPINDA_SUPPORT
  8991. #else
  8992. temp_C[i] = 50 + i * 10; //temperature in C
  8993. #endif
  8994. x[i] = (float)temp_C[i];
  8995. f[i] = (float)shift[i];
  8996. }
  8997. if (inp_temperature < x[0]) return 0;
  8998. for (i = n - 1; i>0; i--) {
  8999. F[i] = (f[i] - f[i - 1]) / (x[i] - x[i - 1]);
  9000. h[i - 1] = x[i] - x[i - 1];
  9001. }
  9002. //*********** formation of h, s , f matrix **************
  9003. for (i = 1; i<n - 1; i++) {
  9004. m[i][i] = 2 * (h[i - 1] + h[i]);
  9005. if (i != 1) {
  9006. m[i][i - 1] = h[i - 1];
  9007. m[i - 1][i] = h[i - 1];
  9008. }
  9009. m[i][n - 1] = 6 * (F[i + 1] - F[i]);
  9010. }
  9011. //*********** forward elimination **************
  9012. for (i = 1; i<n - 2; i++) {
  9013. temp = (m[i + 1][i] / m[i][i]);
  9014. for (j = 1; j <= n - 1; j++)
  9015. m[i + 1][j] -= temp*m[i][j];
  9016. }
  9017. //*********** backward substitution *********
  9018. for (i = n - 2; i>0; i--) {
  9019. sum = 0;
  9020. for (j = i; j <= n - 2; j++)
  9021. sum += m[i][j] * s[j];
  9022. s[i] = (m[i][n - 1] - sum) / m[i][i];
  9023. }
  9024. for (i = 0; i<n - 1; i++)
  9025. if ((x[i] <= inp_temperature && inp_temperature <= x[i + 1]) || (i == n-2 && inp_temperature > x[i + 1])) {
  9026. a = (s[i + 1] - s[i]) / (6 * h[i]);
  9027. b = s[i] / 2;
  9028. c = (f[i + 1] - f[i]) / h[i] - (2 * h[i] * s[i] + s[i + 1] * h[i]) / 6;
  9029. d = f[i];
  9030. sum = a*pow((inp_temperature - x[i]), 3) + b*pow((inp_temperature - x[i]), 2) + c*(inp_temperature - x[i]) + d;
  9031. }
  9032. return sum;
  9033. }
  9034. #ifdef PINDA_THERMISTOR
  9035. float temp_compensation_pinda_thermistor_offset(float temperature_pinda)
  9036. {
  9037. if (!eeprom_read_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE)) return 0;
  9038. if (!calibration_status_pinda()) return 0;
  9039. return temp_comp_interpolation(temperature_pinda) / cs.axis_steps_per_unit[Z_AXIS];
  9040. }
  9041. #endif //PINDA_THERMISTOR
  9042. void long_pause() //long pause print
  9043. {
  9044. st_synchronize();
  9045. start_pause_print = _millis();
  9046. // Stop heaters
  9047. heating_status = HeatingStatus::NO_HEATING;
  9048. setAllTargetHotends(0);
  9049. // Lift z
  9050. raise_z(Z_PAUSE_LIFT);
  9051. // Move XY to side
  9052. if (axis_known_position[X_AXIS] && axis_known_position[Y_AXIS]) {
  9053. current_position[X_AXIS] = X_PAUSE_POS;
  9054. current_position[Y_AXIS] = Y_PAUSE_POS;
  9055. plan_buffer_line_curposXYZE(50);
  9056. }
  9057. // did we come here from a thermal error?
  9058. if(get_temp_error()) {
  9059. // time to stop the error beep
  9060. WRITE(BEEPER, LOW);
  9061. } else {
  9062. // Turn off the print fan
  9063. fanSpeed = 0;
  9064. }
  9065. }
  9066. void serialecho_temperatures() {
  9067. float tt = degHotend(active_extruder);
  9068. SERIAL_PROTOCOLPGM("T:");
  9069. SERIAL_PROTOCOL(tt);
  9070. SERIAL_PROTOCOLPGM(" E:");
  9071. SERIAL_PROTOCOL((int)active_extruder);
  9072. SERIAL_PROTOCOLPGM(" B:");
  9073. SERIAL_PROTOCOL_F(degBed(), 1);
  9074. SERIAL_PROTOCOLLN();
  9075. }
  9076. #ifdef UVLO_SUPPORT
  9077. void uvlo_drain_reset()
  9078. {
  9079. // burn all that residual power
  9080. wdt_enable(WDTO_1S);
  9081. WRITE(BEEPER,HIGH);
  9082. lcd_clear();
  9083. lcd_puts_at_P(0, 1, MSG_POWERPANIC_DETECTED);
  9084. while(1);
  9085. }
  9086. void uvlo_()
  9087. {
  9088. unsigned long time_start = _millis();
  9089. bool sd_print = card.sdprinting;
  9090. // Conserve power as soon as possible.
  9091. #ifdef LCD_BL_PIN
  9092. backlightMode = BACKLIGHT_MODE_DIM;
  9093. backlightLevel_LOW = 0;
  9094. backlight_update();
  9095. #endif //LCD_BL_PIN
  9096. disable_x();
  9097. disable_y();
  9098. #ifdef TMC2130
  9099. tmc2130_set_current_h(Z_AXIS, 20);
  9100. tmc2130_set_current_r(Z_AXIS, 20);
  9101. tmc2130_set_current_h(E_AXIS, 20);
  9102. tmc2130_set_current_r(E_AXIS, 20);
  9103. #endif //TMC2130
  9104. // Stop all heaters
  9105. uint8_t saved_target_temperature_bed = target_temperature_bed;
  9106. uint16_t saved_target_temperature_ext = target_temperature[active_extruder];
  9107. setAllTargetHotends(0);
  9108. setTargetBed(0);
  9109. // Calculate the file position, from which to resume this print.
  9110. long sd_position = sdpos_atomic; //atomic sd position of last command added in queue
  9111. {
  9112. uint16_t sdlen_planner = planner_calc_sd_length(); //length of sd commands in planner
  9113. sd_position -= sdlen_planner;
  9114. uint16_t sdlen_cmdqueue = cmdqueue_calc_sd_length(); //length of sd commands in cmdqueue
  9115. sd_position -= sdlen_cmdqueue;
  9116. if (sd_position < 0) sd_position = 0;
  9117. }
  9118. // save the global state at planning time
  9119. bool pos_invalid = XY_NO_RESTORE_FLAG;
  9120. uint16_t feedrate_bckp;
  9121. if (current_block && !pos_invalid)
  9122. {
  9123. memcpy(saved_start_position, current_block->gcode_start_position, sizeof(saved_start_position));
  9124. feedrate_bckp = current_block->gcode_feedrate;
  9125. saved_segment_idx = current_block->segment_idx;
  9126. }
  9127. else
  9128. {
  9129. saved_start_position[0] = SAVED_START_POSITION_UNSET;
  9130. feedrate_bckp = feedrate;
  9131. saved_segment_idx = 0;
  9132. }
  9133. // From this point on and up to the print recovery, Z should not move during X/Y travels and
  9134. // should be controlled precisely. Reset the MBL status before planner_abort_hard in order to
  9135. // get the physical Z for further manipulation.
  9136. bool mbl_was_active = mbl.active;
  9137. mbl.active = false;
  9138. // After this call, the planner queue is emptied and the current_position is set to a current logical coordinate.
  9139. // The logical coordinate will likely differ from the machine coordinate if the skew calibration and mesh bed leveling
  9140. // are in action.
  9141. planner_abort_hard();
  9142. // Store the print logical Z position, which we need to recover (a slight error here would be
  9143. // recovered on the next Gcode instruction, while a physical location error would not)
  9144. float logical_z = current_position[Z_AXIS];
  9145. if(mbl_was_active) logical_z -= mbl.get_z(st_get_position_mm(X_AXIS), st_get_position_mm(Y_AXIS));
  9146. eeprom_update_float((float*)EEPROM_UVLO_CURRENT_POSITION_Z, logical_z);
  9147. // Store the print E position before we lose track
  9148. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION_E), current_position[E_AXIS]);
  9149. eeprom_update_byte((uint8_t*)EEPROM_UVLO_E_ABS, (axis_relative_modes & E_AXIS_MASK)?0:1);
  9150. // Clean the input command queue, inhibit serial processing using saved_printing
  9151. cmdqueue_reset();
  9152. card.sdprinting = false;
  9153. saved_printing = true;
  9154. // Enable stepper driver interrupt to move Z axis. This should be fine as the planner and
  9155. // command queues are empty, SD card printing is disabled, usb is inhibited.
  9156. planner_aborted = false;
  9157. sei();
  9158. // Retract
  9159. current_position[E_AXIS] -= default_retraction;
  9160. plan_buffer_line_curposXYZE(95);
  9161. st_synchronize();
  9162. disable_e0();
  9163. // Read out the current Z motor microstep counter to move the axis up towards
  9164. // a full step before powering off. NOTE: we need to ensure to schedule more
  9165. // than "dropsegments" steps in order to move (this is always the case here
  9166. // due to UVLO_Z_AXIS_SHIFT being used)
  9167. uint16_t z_res = tmc2130_get_res(Z_AXIS);
  9168. uint16_t z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9169. current_position[Z_AXIS] += float(1024 - z_microsteps)
  9170. / (z_res * cs.axis_steps_per_unit[Z_AXIS])
  9171. + UVLO_Z_AXIS_SHIFT;
  9172. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS]/60);
  9173. st_synchronize();
  9174. poweroff_z();
  9175. // Write the file position.
  9176. eeprom_update_dword((uint32_t*)(EEPROM_FILE_POSITION), sd_position);
  9177. // Store the mesh bed leveling offsets. This is 2*7*7=98 bytes, which takes 98*3.4us=333us in worst case.
  9178. for (uint8_t mesh_point = 0; mesh_point < MESH_NUM_X_POINTS * MESH_NUM_Y_POINTS; ++ mesh_point) {
  9179. uint8_t ix = mesh_point % MESH_NUM_X_POINTS; // from 0 to MESH_NUM_X_POINTS - 1
  9180. uint8_t iy = mesh_point / MESH_NUM_X_POINTS;
  9181. // Scale the z value to 1u resolution.
  9182. int16_t v = mbl_was_active ? int16_t(floor(mbl.z_values[iy][ix] * 1000.f + 0.5f)) : 0;
  9183. eeprom_update_word((uint16_t*)(EEPROM_UVLO_MESH_BED_LEVELING_FULL +2*mesh_point), *reinterpret_cast<uint16_t*>(&v));
  9184. }
  9185. // Write the _final_ Z position and motor microstep counter (unused).
  9186. eeprom_update_float((float*)EEPROM_UVLO_TINY_CURRENT_POSITION_Z, current_position[Z_AXIS]);
  9187. z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9188. eeprom_update_word((uint16_t*)(EEPROM_UVLO_Z_MICROSTEPS), z_microsteps);
  9189. // Store the current position.
  9190. if (pos_invalid)
  9191. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0), X_COORD_INVALID);
  9192. else
  9193. {
  9194. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0), current_position[X_AXIS]);
  9195. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 4), current_position[Y_AXIS]);
  9196. }
  9197. // Store the current feed rate, temperatures, fan speed and extruder multipliers (flow rates)
  9198. eeprom_update_word((uint16_t*)EEPROM_UVLO_FEEDRATE, feedrate_bckp);
  9199. eeprom_update_word((uint16_t*)EEPROM_UVLO_FEEDMULTIPLY, feedmultiply);
  9200. eeprom_update_word((uint16_t*)EEPROM_UVLO_TARGET_HOTEND, saved_target_temperature_ext);
  9201. eeprom_update_byte((uint8_t*)EEPROM_UVLO_TARGET_BED, saved_target_temperature_bed);
  9202. eeprom_update_byte((uint8_t*)EEPROM_UVLO_FAN_SPEED, fanSpeed);
  9203. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_0), extruder_multiplier[0]);
  9204. #if EXTRUDERS > 1
  9205. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_1), extruder_multiplier[1]);
  9206. #if EXTRUDERS > 2
  9207. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_2), extruder_multiplier[2]);
  9208. #endif
  9209. #endif
  9210. eeprom_update_word((uint16_t*)(EEPROM_EXTRUDEMULTIPLY), (uint16_t)extrudemultiply);
  9211. eeprom_update_float((float*)(EEPROM_UVLO_ACCELL), cs.acceleration);
  9212. eeprom_update_float((float*)(EEPROM_UVLO_RETRACT_ACCELL), cs.retract_acceleration);
  9213. eeprom_update_float((float*)(EEPROM_UVLO_TRAVEL_ACCELL), cs.travel_acceleration);
  9214. // Store the saved target
  9215. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+0*4), saved_start_position[X_AXIS]);
  9216. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+1*4), saved_start_position[Y_AXIS]);
  9217. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+2*4), saved_start_position[Z_AXIS]);
  9218. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+3*4), saved_start_position[E_AXIS]);
  9219. eeprom_update_word((uint16_t*)EEPROM_UVLO_SAVED_SEGMENT_IDX, saved_segment_idx);
  9220. #ifdef LIN_ADVANCE
  9221. eeprom_update_float((float*)(EEPROM_UVLO_LA_K), extruder_advance_K);
  9222. #endif
  9223. // Finaly store the "power outage" flag.
  9224. if(sd_print) eeprom_update_byte((uint8_t*)EEPROM_UVLO, 1);
  9225. // Increment power failure counter
  9226. eeprom_increment_byte((uint8_t*)EEPROM_POWER_COUNT);
  9227. eeprom_increment_word((uint16_t*)EEPROM_POWER_COUNT_TOT);
  9228. printf_P(_N("UVLO - end %d\n"), _millis() - time_start);
  9229. WRITE(BEEPER,HIGH);
  9230. // All is set: with all the juice left, try to move extruder away to detach the nozzle completely from the print
  9231. poweron_z();
  9232. current_position[X_AXIS] = (current_position[X_AXIS] < 0.5f * (X_MIN_POS + X_MAX_POS)) ? X_MIN_POS : X_MAX_POS;
  9233. plan_buffer_line_curposXYZE(500);
  9234. st_synchronize();
  9235. wdt_enable(WDTO_1S);
  9236. while(1);
  9237. }
  9238. void uvlo_tiny()
  9239. {
  9240. unsigned long time_start = _millis();
  9241. // Conserve power as soon as possible.
  9242. disable_x();
  9243. disable_y();
  9244. disable_e0();
  9245. #ifdef TMC2130
  9246. tmc2130_set_current_h(Z_AXIS, 20);
  9247. tmc2130_set_current_r(Z_AXIS, 20);
  9248. #endif //TMC2130
  9249. // Stop all heaters
  9250. setAllTargetHotends(0);
  9251. setTargetBed(0);
  9252. // When power is interrupted on the _first_ recovery an attempt can be made to raise the
  9253. // extruder, causing the Z position to change. Similarly, when recovering, the Z position is
  9254. // lowered. In such cases we cannot just save Z, we need to re-align the steppers to a fullstep.
  9255. // Disable MBL (if not already) to work with physical coordinates.
  9256. mbl.active = false;
  9257. planner_abort_hard();
  9258. // Allow for small roundoffs to be ignored
  9259. if(fabs(current_position[Z_AXIS] - eeprom_read_float((float*)(EEPROM_UVLO_TINY_CURRENT_POSITION_Z))) >= 1.f/cs.axis_steps_per_unit[Z_AXIS])
  9260. {
  9261. // Clean the input command queue, inhibit serial processing using saved_printing
  9262. cmdqueue_reset();
  9263. card.sdprinting = false;
  9264. saved_printing = true;
  9265. // Enable stepper driver interrupt to move Z axis. This should be fine as the planner and
  9266. // command queues are empty, SD card printing is disabled, usb is inhibited.
  9267. planner_aborted = false;
  9268. sei();
  9269. // The axis was moved: adjust Z as done on a regular UVLO.
  9270. uint16_t z_res = tmc2130_get_res(Z_AXIS);
  9271. uint16_t z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9272. current_position[Z_AXIS] += float(1024 - z_microsteps)
  9273. / (z_res * cs.axis_steps_per_unit[Z_AXIS])
  9274. + UVLO_TINY_Z_AXIS_SHIFT;
  9275. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS]/60);
  9276. st_synchronize();
  9277. poweroff_z();
  9278. // Update Z position
  9279. eeprom_update_float((float*)(EEPROM_UVLO_TINY_CURRENT_POSITION_Z), current_position[Z_AXIS]);
  9280. // Update the _final_ Z motor microstep counter (unused).
  9281. z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9282. eeprom_update_word((uint16_t*)(EEPROM_UVLO_Z_MICROSTEPS), z_microsteps);
  9283. }
  9284. // Update the the "power outage" flag.
  9285. eeprom_update_byte((uint8_t*)EEPROM_UVLO,2);
  9286. // Increment power failure counter
  9287. eeprom_update_byte((uint8_t*)EEPROM_POWER_COUNT, eeprom_read_byte((uint8_t*)EEPROM_POWER_COUNT) + 1);
  9288. eeprom_update_word((uint16_t*)EEPROM_POWER_COUNT_TOT, eeprom_read_word((uint16_t*)EEPROM_POWER_COUNT_TOT) + 1);
  9289. printf_P(_N("UVLO_TINY - end %d\n"), _millis() - time_start);
  9290. uvlo_drain_reset();
  9291. }
  9292. #endif //UVLO_SUPPORT
  9293. #if (defined(FANCHECK) && defined(TACH_1) && (TACH_1 >-1))
  9294. void setup_fan_interrupt() {
  9295. //INT7
  9296. DDRE &= ~(1 << 7); //input pin
  9297. PORTE &= ~(1 << 7); //no internal pull-up
  9298. //start with sensing rising edge
  9299. EICRB &= ~(1 << 6);
  9300. EICRB |= (1 << 7);
  9301. //enable INT7 interrupt
  9302. EIMSK |= (1 << 7);
  9303. }
  9304. // The fan interrupt is triggered at maximum 325Hz (may be a bit more due to component tollerances),
  9305. // and it takes 4.24 us to process (the interrupt invocation overhead not taken into account).
  9306. ISR(INT7_vect) {
  9307. //measuring speed now works for fanSpeed > 18 (approximately), which is sufficient because MIN_PRINT_FAN_SPEED is higher
  9308. #ifdef FAN_SOFT_PWM
  9309. if (!fan_measuring || (fanSpeedSoftPwm < MIN_PRINT_FAN_SPEED)) return;
  9310. #else //FAN_SOFT_PWM
  9311. if (fanSpeed < MIN_PRINT_FAN_SPEED) return;
  9312. #endif //FAN_SOFT_PWM
  9313. if ((1 << 6) & EICRB) { //interrupt was triggered by rising edge
  9314. t_fan_rising_edge = millis_nc();
  9315. }
  9316. else { //interrupt was triggered by falling edge
  9317. if ((millis_nc() - t_fan_rising_edge) >= FAN_PULSE_WIDTH_LIMIT) {//this pulse was from sensor and not from pwm
  9318. fan_edge_counter[1] += 2; //we are currently counting all edges so lets count two edges for one pulse
  9319. }
  9320. }
  9321. EICRB ^= (1 << 6); //change edge
  9322. }
  9323. #endif
  9324. #ifdef UVLO_SUPPORT
  9325. void setup_uvlo_interrupt() {
  9326. DDRE &= ~(1 << 4); //input pin
  9327. PORTE &= ~(1 << 4); //no internal pull-up
  9328. // sensing falling edge
  9329. EICRB |= (1 << 0);
  9330. EICRB &= ~(1 << 1);
  9331. // enable INT4 interrupt
  9332. EIMSK |= (1 << 4);
  9333. // check if power was lost before we armed the interrupt
  9334. if(!(PINE & (1 << 4)) && eeprom_read_byte((uint8_t*)EEPROM_UVLO))
  9335. {
  9336. SERIAL_ECHOLNPGM("INT4");
  9337. uvlo_drain_reset();
  9338. }
  9339. }
  9340. ISR(INT4_vect) {
  9341. EIMSK &= ~(1 << 4); //disable INT4 interrupt to make sure that this code will be executed just once
  9342. SERIAL_ECHOLNPGM("INT4");
  9343. //fire normal uvlo only in case where EEPROM_UVLO is 0 or if IS_SD_PRINTING is 1.
  9344. if(printer_active() && (!(eeprom_read_byte((uint8_t*)EEPROM_UVLO)))) uvlo_();
  9345. if(eeprom_read_byte((uint8_t*)EEPROM_UVLO)) uvlo_tiny();
  9346. }
  9347. void recover_print(uint8_t automatic) {
  9348. char cmd[30];
  9349. lcd_update_enable(true);
  9350. lcd_update(2);
  9351. lcd_setstatuspgm(_i("Recovering print"));////MSG_RECOVERING_PRINT c=20
  9352. // Recover position, temperatures and extrude_multipliers
  9353. bool mbl_was_active = recover_machine_state_after_power_panic();
  9354. // Lift the print head 25mm, first to avoid collisions with oozed material with the print,
  9355. // and second also so one may remove the excess priming material.
  9356. if(eeprom_read_byte((uint8_t*)EEPROM_UVLO) == 1)
  9357. {
  9358. sprintf_P(cmd, PSTR("G1 Z%.3f F800"), current_position[Z_AXIS] + 25);
  9359. enquecommand(cmd);
  9360. }
  9361. // Home X and Y axes. Homing just X and Y shall not touch the babystep and the world2machine
  9362. // transformation status. G28 will not touch Z when MBL is off.
  9363. enquecommand_P(PSTR("G28 X Y"));
  9364. // Set the target bed and nozzle temperatures and wait.
  9365. sprintf_P(cmd, PSTR("M104 S%d"), target_temperature[active_extruder]);
  9366. enquecommand(cmd);
  9367. sprintf_P(cmd, PSTR("M140 S%d"), target_temperature_bed);
  9368. enquecommand(cmd);
  9369. sprintf_P(cmd, PSTR("M109 S%d"), target_temperature[active_extruder]);
  9370. enquecommand(cmd);
  9371. enquecommand_P(PSTR("M83")); //E axis relative mode
  9372. // If not automatically recoreverd (long power loss)
  9373. if(automatic == 0){
  9374. //Extrude some filament to stabilize the pressure
  9375. enquecommand_P(PSTR("G1 E5 F120"));
  9376. // Retract to be consistent with a short pause
  9377. sprintf_P(cmd, PSTR("G1 E%-0.3f F2700"), default_retraction);
  9378. enquecommand(cmd);
  9379. }
  9380. printf_P(_N("After waiting for temp:\nCurrent pos X_AXIS:%.3f\nCurrent pos Y_AXIS:%.3f\n"), current_position[X_AXIS], current_position[Y_AXIS]);
  9381. // Restart the print.
  9382. restore_print_from_eeprom(mbl_was_active);
  9383. printf_P(_N("Current pos Z_AXIS:%.3f\nCurrent pos E_AXIS:%.3f\n"), current_position[Z_AXIS], current_position[E_AXIS]);
  9384. }
  9385. bool recover_machine_state_after_power_panic()
  9386. {
  9387. // 1) Preset some dummy values for the XY axes
  9388. current_position[X_AXIS] = 0;
  9389. current_position[Y_AXIS] = 0;
  9390. // 2) Restore the mesh bed leveling offsets, but not the MBL status.
  9391. // This is 2*7*7=98 bytes, which takes 98*3.4us=333us in worst case.
  9392. bool mbl_was_active = false;
  9393. for (int8_t mesh_point = 0; mesh_point < MESH_NUM_X_POINTS * MESH_NUM_Y_POINTS; ++ mesh_point) {
  9394. uint8_t ix = mesh_point % MESH_NUM_X_POINTS; // from 0 to MESH_NUM_X_POINTS - 1
  9395. uint8_t iy = mesh_point / MESH_NUM_X_POINTS;
  9396. // Scale the z value to 10u resolution.
  9397. int16_t v;
  9398. eeprom_read_block(&v, (void*)(EEPROM_UVLO_MESH_BED_LEVELING_FULL+2*mesh_point), 2);
  9399. if (v != 0)
  9400. mbl_was_active = true;
  9401. mbl.z_values[iy][ix] = float(v) * 0.001f;
  9402. }
  9403. // Recover the physical coordinate of the Z axis at the time of the power panic.
  9404. // The current position after power panic is moved to the next closest 0th full step.
  9405. current_position[Z_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_TINY_CURRENT_POSITION_Z));
  9406. // Recover last E axis position
  9407. current_position[E_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_E));
  9408. // 3) Initialize the logical to physical coordinate system transformation.
  9409. world2machine_initialize();
  9410. // SERIAL_ECHOPGM("recover_machine_state_after_power_panic, initial ");
  9411. // print_mesh_bed_leveling_table();
  9412. // 4) Load the baby stepping value, which is expected to be active at the time of power panic.
  9413. // The baby stepping value is used to reset the physical Z axis when rehoming the Z axis.
  9414. babystep_load();
  9415. // 5) Set the physical positions from the logical positions using the world2machine transformation
  9416. // This is only done to inizialize Z/E axes with physical locations, since X/Y are unknown.
  9417. clamp_to_software_endstops(current_position);
  9418. set_destination_to_current();
  9419. plan_set_position_curposXYZE();
  9420. SERIAL_ECHOPGM("recover_machine_state_after_power_panic, initial ");
  9421. print_world_coordinates();
  9422. // 6) Power up the Z motors, mark their positions as known.
  9423. axis_known_position[Z_AXIS] = true;
  9424. enable_z();
  9425. // 7) Recover the target temperatures.
  9426. target_temperature[active_extruder] = eeprom_read_word((uint16_t*)EEPROM_UVLO_TARGET_HOTEND);
  9427. target_temperature_bed = eeprom_read_byte((uint8_t*)EEPROM_UVLO_TARGET_BED);
  9428. // 8) Recover extruder multipilers
  9429. extruder_multiplier[0] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_0));
  9430. #if EXTRUDERS > 1
  9431. extruder_multiplier[1] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_1));
  9432. #if EXTRUDERS > 2
  9433. extruder_multiplier[2] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_2));
  9434. #endif
  9435. #endif
  9436. extrudemultiply = (int)eeprom_read_word((uint16_t*)(EEPROM_EXTRUDEMULTIPLY));
  9437. // 9) Recover the saved target
  9438. saved_start_position[X_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+0*4));
  9439. saved_start_position[Y_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+1*4));
  9440. saved_start_position[Z_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+2*4));
  9441. saved_start_position[E_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+3*4));
  9442. saved_segment_idx = eeprom_read_word((uint16_t*)EEPROM_UVLO_SAVED_SEGMENT_IDX);
  9443. #ifdef LIN_ADVANCE
  9444. extruder_advance_K = eeprom_read_float((float*)EEPROM_UVLO_LA_K);
  9445. #endif
  9446. return mbl_was_active;
  9447. }
  9448. void restore_print_from_eeprom(bool mbl_was_active) {
  9449. int feedrate_rec;
  9450. int feedmultiply_rec;
  9451. uint8_t fan_speed_rec;
  9452. char cmd[48];
  9453. char filename[FILENAME_LENGTH];
  9454. uint8_t depth = 0;
  9455. char dir_name[9];
  9456. fan_speed_rec = eeprom_read_byte((uint8_t*)EEPROM_UVLO_FAN_SPEED);
  9457. feedrate_rec = eeprom_read_word((uint16_t*)EEPROM_UVLO_FEEDRATE);
  9458. feedmultiply_rec = eeprom_read_word((uint16_t*)EEPROM_UVLO_FEEDMULTIPLY);
  9459. SERIAL_ECHOPGM("Feedrate:");
  9460. MYSERIAL.print(feedrate_rec);
  9461. SERIAL_ECHOPGM(", feedmultiply:");
  9462. MYSERIAL.println(feedmultiply_rec);
  9463. depth = eeprom_read_byte((uint8_t*)EEPROM_DIR_DEPTH);
  9464. MYSERIAL.println(int(depth));
  9465. for (uint8_t i = 0; i < depth; i++) {
  9466. for (uint8_t j = 0; j < 8; j++) {
  9467. dir_name[j] = eeprom_read_byte((uint8_t*)EEPROM_DIRS + j + 8 * i);
  9468. }
  9469. dir_name[8] = '\0';
  9470. MYSERIAL.println(dir_name);
  9471. // strcpy(card.dir_names[i], dir_name);
  9472. card.chdir(dir_name, false);
  9473. }
  9474. for (uint8_t i = 0; i < 8; i++) {
  9475. filename[i] = eeprom_read_byte((uint8_t*)EEPROM_FILENAME + i);
  9476. }
  9477. filename[8] = '\0';
  9478. MYSERIAL.print(filename);
  9479. strcat_P(filename, PSTR(".gco"));
  9480. sprintf_P(cmd, PSTR("M23 %s"), filename);
  9481. enquecommand(cmd);
  9482. uint32_t position = eeprom_read_dword((uint32_t*)(EEPROM_FILE_POSITION));
  9483. SERIAL_ECHOPGM("Position read from eeprom:");
  9484. MYSERIAL.println(position);
  9485. // Move to the XY print position in logical coordinates, where the print has been killed, but
  9486. // without shifting Z along the way. This requires performing the move without mbl.
  9487. float pos_x = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0));
  9488. float pos_y = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 4));
  9489. if (pos_x != X_COORD_INVALID)
  9490. {
  9491. sprintf_P(cmd, PSTR("G1 X%f Y%f F3000"), pos_x, pos_y);
  9492. enquecommand(cmd);
  9493. }
  9494. // Enable MBL and switch to logical positioning
  9495. if (mbl_was_active)
  9496. enquecommand_P(PSTR("PRUSA MBL V1"));
  9497. // Move the Z axis down to the print, in logical coordinates.
  9498. sprintf_P(cmd, PSTR("G1 Z%f"), eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_Z)));
  9499. enquecommand(cmd);
  9500. // Restore acceleration settings
  9501. float acceleration = eeprom_read_float((float*)(EEPROM_UVLO_ACCELL));
  9502. float retract_acceleration = eeprom_read_float((float*)(EEPROM_UVLO_RETRACT_ACCELL));
  9503. float travel_acceleration = eeprom_read_float((float*)(EEPROM_UVLO_TRAVEL_ACCELL));
  9504. sprintf_P(cmd, PSTR("M204 P%f R%f T%f"), acceleration, retract_acceleration, travel_acceleration);
  9505. enquecommand(cmd);
  9506. // Unretract.
  9507. sprintf_P(cmd, PSTR("G1 E%0.3f F2700"), default_retraction);
  9508. enquecommand(cmd);
  9509. // Recover final E axis position and mode
  9510. float pos_e = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_E));
  9511. sprintf_P(cmd, PSTR("G92 E%6.3f"), pos_e);
  9512. enquecommand(cmd);
  9513. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO_E_ABS))
  9514. enquecommand_P(PSTR("M82")); //E axis abslute mode
  9515. // Set the feedrates saved at the power panic.
  9516. sprintf_P(cmd, PSTR("G1 F%d"), feedrate_rec);
  9517. enquecommand(cmd);
  9518. sprintf_P(cmd, PSTR("M220 S%d"), feedmultiply_rec);
  9519. enquecommand(cmd);
  9520. // Set the fan speed saved at the power panic.
  9521. strcpy_P(cmd, PSTR("M106 S"));
  9522. strcat(cmd, itostr3(int(fan_speed_rec)));
  9523. enquecommand(cmd);
  9524. // Set a position in the file.
  9525. sprintf_P(cmd, PSTR("M26 S%lu"), position);
  9526. enquecommand(cmd);
  9527. enquecommand_P(PSTR("G4 S0"));
  9528. enquecommand_P(PSTR("PRUSA uvlo"));
  9529. }
  9530. #endif //UVLO_SUPPORT
  9531. //! @brief Immediately stop print moves
  9532. //!
  9533. //! Immediately stop print moves, save current extruder temperature and position to RAM.
  9534. //! If printing from sd card, position in file is saved.
  9535. //! If printing from USB, line number is saved.
  9536. //!
  9537. //! @param z_move
  9538. //! @param e_move
  9539. void stop_and_save_print_to_ram(float z_move, float e_move)
  9540. {
  9541. if (saved_printing) return;
  9542. #if 0
  9543. unsigned char nplanner_blocks;
  9544. #endif
  9545. unsigned char nlines;
  9546. uint16_t sdlen_planner;
  9547. uint16_t sdlen_cmdqueue;
  9548. cli();
  9549. if (card.sdprinting) {
  9550. #if 0
  9551. nplanner_blocks = number_of_blocks();
  9552. #endif
  9553. saved_sdpos = sdpos_atomic; //atomic sd position of last command added in queue
  9554. sdlen_planner = planner_calc_sd_length(); //length of sd commands in planner
  9555. saved_sdpos -= sdlen_planner;
  9556. sdlen_cmdqueue = cmdqueue_calc_sd_length(); //length of sd commands in cmdqueue
  9557. saved_sdpos -= sdlen_cmdqueue;
  9558. saved_printing_type = PRINTING_TYPE_SD;
  9559. }
  9560. else if (usb_timer.running()) { //reuse saved_sdpos for storing line number
  9561. saved_sdpos = gcode_LastN; //start with line number of command added recently to cmd queue
  9562. //reuse planner_calc_sd_length function for getting number of lines of commands in planner:
  9563. nlines = planner_calc_sd_length(); //number of lines of commands in planner
  9564. saved_sdpos -= nlines;
  9565. saved_sdpos -= buflen; //number of blocks in cmd buffer
  9566. saved_printing_type = PRINTING_TYPE_USB;
  9567. }
  9568. else {
  9569. saved_printing_type = PRINTING_TYPE_NONE;
  9570. //not sd printing nor usb printing
  9571. }
  9572. #if 0
  9573. SERIAL_ECHOPGM("SDPOS_ATOMIC="); MYSERIAL.println(sdpos_atomic, DEC);
  9574. SERIAL_ECHOPGM("SDPOS="); MYSERIAL.println(card.get_sdpos(), DEC);
  9575. SERIAL_ECHOPGM("SDLEN_PLAN="); MYSERIAL.println(sdlen_planner, DEC);
  9576. SERIAL_ECHOPGM("SDLEN_CMDQ="); MYSERIAL.println(sdlen_cmdqueue, DEC);
  9577. SERIAL_ECHOPGM("PLANNERBLOCKS="); MYSERIAL.println(int(nplanner_blocks), DEC);
  9578. SERIAL_ECHOPGM("SDSAVED="); MYSERIAL.println(saved_sdpos, DEC);
  9579. //SERIAL_ECHOPGM("SDFILELEN="); MYSERIAL.println(card.fileSize(), DEC);
  9580. {
  9581. card.setIndex(saved_sdpos);
  9582. SERIAL_ECHOLNPGM("Content of planner buffer: ");
  9583. for (unsigned int idx = 0; idx < sdlen_planner; ++ idx)
  9584. MYSERIAL.print(char(card.get()));
  9585. SERIAL_ECHOLNPGM("Content of command buffer: ");
  9586. for (unsigned int idx = 0; idx < sdlen_cmdqueue; ++ idx)
  9587. MYSERIAL.print(char(card.get()));
  9588. SERIAL_ECHOLNPGM("End of command buffer");
  9589. }
  9590. {
  9591. // Print the content of the planner buffer, line by line:
  9592. card.setIndex(saved_sdpos);
  9593. int8_t iline = 0;
  9594. for (unsigned char idx = block_buffer_tail; idx != block_buffer_head; idx = (idx + 1) & (BLOCK_BUFFER_SIZE - 1), ++ iline) {
  9595. SERIAL_ECHOPGM("Planner line (from file): ");
  9596. MYSERIAL.print(int(iline), DEC);
  9597. SERIAL_ECHOPGM(", length: ");
  9598. MYSERIAL.print(block_buffer[idx].sdlen, DEC);
  9599. SERIAL_ECHOPGM(", steps: (");
  9600. MYSERIAL.print(block_buffer[idx].steps_x, DEC);
  9601. SERIAL_ECHOPGM(",");
  9602. MYSERIAL.print(block_buffer[idx].steps_y, DEC);
  9603. SERIAL_ECHOPGM(",");
  9604. MYSERIAL.print(block_buffer[idx].steps_z, DEC);
  9605. SERIAL_ECHOPGM(",");
  9606. MYSERIAL.print(block_buffer[idx].steps_e, DEC);
  9607. SERIAL_ECHOPGM("), events: ");
  9608. MYSERIAL.println(block_buffer[idx].step_event_count, DEC);
  9609. for (int len = block_buffer[idx].sdlen; len > 0; -- len)
  9610. MYSERIAL.print(char(card.get()));
  9611. }
  9612. }
  9613. {
  9614. // Print the content of the command buffer, line by line:
  9615. int8_t iline = 0;
  9616. union {
  9617. struct {
  9618. char lo;
  9619. char hi;
  9620. } lohi;
  9621. uint16_t value;
  9622. } sdlen_single;
  9623. int _bufindr = bufindr;
  9624. for (int _buflen = buflen; _buflen > 0; ++ iline) {
  9625. if (cmdbuffer[_bufindr] == CMDBUFFER_CURRENT_TYPE_SDCARD) {
  9626. sdlen_single.lohi.lo = cmdbuffer[_bufindr + 1];
  9627. sdlen_single.lohi.hi = cmdbuffer[_bufindr + 2];
  9628. }
  9629. SERIAL_ECHOPGM("Buffer line (from buffer): ");
  9630. MYSERIAL.print(int(iline), DEC);
  9631. SERIAL_ECHOPGM(", type: ");
  9632. MYSERIAL.print(int(cmdbuffer[_bufindr]), DEC);
  9633. SERIAL_ECHOPGM(", len: ");
  9634. MYSERIAL.println(sdlen_single.value, DEC);
  9635. // Print the content of the buffer line.
  9636. MYSERIAL.println(cmdbuffer + _bufindr + CMDHDRSIZE);
  9637. SERIAL_ECHOPGM("Buffer line (from file): ");
  9638. MYSERIAL.println(int(iline), DEC);
  9639. for (; sdlen_single.value > 0; -- sdlen_single.value)
  9640. MYSERIAL.print(char(card.get()));
  9641. if (-- _buflen == 0)
  9642. break;
  9643. // First skip the current command ID and iterate up to the end of the string.
  9644. for (_bufindr += CMDHDRSIZE; cmdbuffer[_bufindr] != 0; ++ _bufindr) ;
  9645. // Second, skip the end of string null character and iterate until a nonzero command ID is found.
  9646. for (++ _bufindr; _bufindr < sizeof(cmdbuffer) && cmdbuffer[_bufindr] == 0; ++ _bufindr) ;
  9647. // If the end of the buffer was empty,
  9648. if (_bufindr == sizeof(cmdbuffer)) {
  9649. // skip to the start and find the nonzero command.
  9650. for (_bufindr = 0; cmdbuffer[_bufindr] == 0; ++ _bufindr) ;
  9651. }
  9652. }
  9653. }
  9654. #endif
  9655. // save the global state at planning time
  9656. bool pos_invalid = XY_NO_RESTORE_FLAG;
  9657. if (current_block && !pos_invalid)
  9658. {
  9659. memcpy(saved_start_position, current_block->gcode_start_position, sizeof(saved_start_position));
  9660. saved_feedrate2 = current_block->gcode_feedrate;
  9661. saved_segment_idx = current_block->segment_idx;
  9662. // printf_P(PSTR("stop_and_save_print_to_ram: %f, %f, %f, %f, %u\n"), saved_start_position[0], saved_start_position[1], saved_start_position[2], saved_start_position[3], saved_segment_idx);
  9663. }
  9664. else
  9665. {
  9666. saved_start_position[0] = SAVED_START_POSITION_UNSET;
  9667. saved_feedrate2 = feedrate;
  9668. saved_segment_idx = 0;
  9669. }
  9670. planner_abort_hard(); //abort printing
  9671. memcpy(saved_pos, current_position, sizeof(saved_pos));
  9672. if (pos_invalid) saved_pos[X_AXIS] = X_COORD_INVALID;
  9673. saved_feedmultiply2 = feedmultiply; //save feedmultiply
  9674. saved_extruder_temperature = degTargetHotend(active_extruder);
  9675. saved_bed_temperature = degTargetBed();
  9676. saved_extruder_relative_mode = axis_relative_modes & E_AXIS_MASK;
  9677. saved_fan_speed = fanSpeed;
  9678. cmdqueue_reset(); //empty cmdqueue
  9679. card.sdprinting = false;
  9680. // card.closefile();
  9681. saved_printing = true;
  9682. // We may have missed a stepper timer interrupt. Be safe than sorry, reset the stepper timer before re-enabling interrupts.
  9683. st_reset_timer();
  9684. sei();
  9685. if ((z_move != 0) || (e_move != 0)) { // extruder or z move
  9686. // Rather than calling plan_buffer_line directly, push the move into the command queue so that
  9687. // the caller can continue processing. This is used during powerpanic to save the state as we
  9688. // move away from the print.
  9689. char buf[48];
  9690. if(e_move)
  9691. {
  9692. // First unretract (relative extrusion)
  9693. if(!saved_extruder_relative_mode){
  9694. enquecommand(PSTR("M83"), true);
  9695. }
  9696. //retract 45mm/s
  9697. // A single sprintf may not be faster, but is definitely 20B shorter
  9698. // than a sequence of commands building the string piece by piece
  9699. // A snprintf would have been a safer call, but since it is not used
  9700. // in the whole program, its implementation would bring more bytes to the total size
  9701. // The behavior of dtostrf 8,3 should be roughly the same as %-0.3
  9702. sprintf_P(buf, PSTR("G1 E%-0.3f F2700"), e_move);
  9703. enquecommand(buf, false);
  9704. }
  9705. if(z_move)
  9706. {
  9707. // Then lift Z axis
  9708. sprintf_P(buf, PSTR("G1 Z%-0.3f F%-0.3f"), saved_pos[Z_AXIS] + z_move, homing_feedrate[Z_AXIS]);
  9709. enquecommand(buf, false);
  9710. }
  9711. // If this call is invoked from the main Arduino loop() function, let the caller know that the command
  9712. // in the command queue is not the original command, but a new one, so it should not be removed from the queue.
  9713. repeatcommand_front();
  9714. }
  9715. }
  9716. void restore_extruder_temperature_from_ram() {
  9717. if (degTargetHotend(active_extruder) != saved_extruder_temperature)
  9718. {
  9719. setTargetHotendSafe(saved_extruder_temperature, active_extruder);
  9720. heating_status = HeatingStatus::EXTRUDER_HEATING;
  9721. wait_for_heater(_millis(), active_extruder);
  9722. heating_status = HeatingStatus::EXTRUDER_HEATING_COMPLETE;
  9723. }
  9724. }
  9725. //! @brief Restore print from ram
  9726. //!
  9727. //! Restore print saved by stop_and_save_print_to_ram(). Is blocking, restores
  9728. //! print fan speed, waits for extruder temperature restore, then restores
  9729. //! position and continues print moves.
  9730. //!
  9731. //! Internally lcd_update() is called by wait_for_heater().
  9732. //!
  9733. //! @param e_move
  9734. void restore_print_from_ram_and_continue(float e_move)
  9735. {
  9736. if (!saved_printing) return;
  9737. #ifdef FANCHECK
  9738. // Do not allow resume printing if fans are still not ok
  9739. if ((fan_check_error != EFCE_OK) && (fan_check_error != EFCE_FIXED)) return;
  9740. if (fan_check_error == EFCE_FIXED) fan_check_error = EFCE_OK; //reenable serial stream processing if printing from usb
  9741. #endif
  9742. // restore bed temperature (bed can be disabled during a thermal warning)
  9743. if (degBed() != saved_bed_temperature)
  9744. setTargetBed(saved_bed_temperature);
  9745. fanSpeed = saved_fan_speed;
  9746. restore_extruder_temperature_from_ram();
  9747. axis_relative_modes ^= (-saved_extruder_relative_mode ^ axis_relative_modes) & E_AXIS_MASK;
  9748. float e = saved_pos[E_AXIS] - e_move;
  9749. plan_set_e_position(e);
  9750. #ifdef FANCHECK
  9751. fans_check_enabled = false;
  9752. #endif
  9753. // do not restore XY for commands that do not require that
  9754. if (saved_pos[X_AXIS] == X_COORD_INVALID)
  9755. {
  9756. saved_pos[X_AXIS] = current_position[X_AXIS];
  9757. saved_pos[Y_AXIS] = current_position[Y_AXIS];
  9758. }
  9759. //first move print head in XY to the saved position:
  9760. plan_buffer_line(saved_pos[X_AXIS], saved_pos[Y_AXIS], current_position[Z_AXIS], saved_pos[E_AXIS] - e_move, homing_feedrate[Z_AXIS]/13, active_extruder);
  9761. //then move Z
  9762. plan_buffer_line(saved_pos[X_AXIS], saved_pos[Y_AXIS], saved_pos[Z_AXIS], saved_pos[E_AXIS] - e_move, homing_feedrate[Z_AXIS]/13, active_extruder);
  9763. //and finaly unretract (35mm/s)
  9764. plan_buffer_line(saved_pos[X_AXIS], saved_pos[Y_AXIS], saved_pos[Z_AXIS], saved_pos[E_AXIS], FILAMENTCHANGE_RFEED, active_extruder);
  9765. st_synchronize();
  9766. #ifdef FANCHECK
  9767. fans_check_enabled = true;
  9768. #endif
  9769. // restore original feedrate/feedmultiply _after_ restoring the extruder position
  9770. feedrate = saved_feedrate2;
  9771. feedmultiply = saved_feedmultiply2;
  9772. memcpy(current_position, saved_pos, sizeof(saved_pos));
  9773. set_destination_to_current();
  9774. if (saved_printing_type == PRINTING_TYPE_SD) { //was sd printing
  9775. card.setIndex(saved_sdpos);
  9776. sdpos_atomic = saved_sdpos;
  9777. card.sdprinting = true;
  9778. }
  9779. else if (saved_printing_type == PRINTING_TYPE_USB) { //was usb printing
  9780. gcode_LastN = saved_sdpos; //saved_sdpos was reused for storing line number when usb printing
  9781. serial_count = 0;
  9782. FlushSerialRequestResend();
  9783. }
  9784. else {
  9785. //not sd printing nor usb printing
  9786. }
  9787. lcd_setstatuspgm(MSG_WELCOME);
  9788. saved_printing_type = PRINTING_TYPE_NONE;
  9789. saved_printing = false;
  9790. planner_aborted = true; // unroll the stack
  9791. }
  9792. // Cancel the state related to a currently saved print
  9793. void cancel_saved_printing()
  9794. {
  9795. eeprom_update_byte((uint8_t*)EEPROM_UVLO, 0);
  9796. saved_start_position[0] = SAVED_START_POSITION_UNSET;
  9797. saved_printing_type = PRINTING_TYPE_NONE;
  9798. saved_printing = false;
  9799. }
  9800. void print_world_coordinates()
  9801. {
  9802. printf_P(_N("world coordinates: (%.3f, %.3f, %.3f)\n"), current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS]);
  9803. }
  9804. void print_physical_coordinates()
  9805. {
  9806. printf_P(_N("physical coordinates: (%.3f, %.3f, %.3f)\n"), st_get_position_mm(X_AXIS), st_get_position_mm(Y_AXIS), st_get_position_mm(Z_AXIS));
  9807. }
  9808. void print_mesh_bed_leveling_table()
  9809. {
  9810. SERIAL_ECHOPGM("mesh bed leveling: ");
  9811. for (int8_t y = 0; y < MESH_NUM_Y_POINTS; ++ y)
  9812. for (int8_t x = 0; x < MESH_NUM_Y_POINTS; ++ x) {
  9813. MYSERIAL.print(mbl.z_values[y][x], 3);
  9814. SERIAL_ECHO(' ');
  9815. }
  9816. SERIAL_ECHOLN();
  9817. }
  9818. uint8_t calc_percent_done()
  9819. {
  9820. //in case that we have information from M73 gcode return percentage counted by slicer, else return percentage counted as byte_printed/filesize
  9821. uint8_t percent_done = 0;
  9822. #ifdef TMC2130
  9823. if (SilentModeMenu == SILENT_MODE_OFF && print_percent_done_normal <= 100)
  9824. {
  9825. percent_done = print_percent_done_normal;
  9826. }
  9827. else if (print_percent_done_silent <= 100)
  9828. {
  9829. percent_done = print_percent_done_silent;
  9830. }
  9831. #else
  9832. if (print_percent_done_normal <= 100)
  9833. {
  9834. percent_done = print_percent_done_normal;
  9835. }
  9836. #endif //TMC2130
  9837. else
  9838. {
  9839. percent_done = card.percentDone();
  9840. }
  9841. return percent_done;
  9842. }
  9843. static void print_time_remaining_init()
  9844. {
  9845. print_time_remaining_normal = PRINT_TIME_REMAINING_INIT;
  9846. print_percent_done_normal = PRINT_PERCENT_DONE_INIT;
  9847. print_time_remaining_silent = PRINT_TIME_REMAINING_INIT;
  9848. print_percent_done_silent = PRINT_PERCENT_DONE_INIT;
  9849. print_time_to_change_normal = PRINT_TIME_REMAINING_INIT;
  9850. print_time_to_change_silent = PRINT_TIME_REMAINING_INIT;
  9851. }
  9852. void load_filament_final_feed()
  9853. {
  9854. current_position[E_AXIS]+= FILAMENTCHANGE_FINALFEED;
  9855. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EFEED_FINAL);
  9856. }
  9857. //! @brief Wait for user to check the state
  9858. //! @par nozzle_temp nozzle temperature to load filament
  9859. void M600_check_state(float nozzle_temp)
  9860. {
  9861. uint8_t lcd_change_filament_state = 0;
  9862. while (lcd_change_filament_state != 1)
  9863. {
  9864. KEEPALIVE_STATE(PAUSED_FOR_USER);
  9865. lcd_change_filament_state = lcd_alright();
  9866. KEEPALIVE_STATE(IN_HANDLER);
  9867. switch(lcd_change_filament_state)
  9868. {
  9869. // Filament failed to load so load it again
  9870. case 2:
  9871. if (MMU2::mmu2.Enabled()){
  9872. // Unload filament
  9873. mmu_M600_unload_filament();
  9874. // Ask to remove any old filament and load new
  9875. mmu_M600_wait_and_beep();
  9876. // After user clicks knob, MMU will load the filament
  9877. mmu_M600_load_filament(false, nozzle_temp);
  9878. } else {
  9879. M600_load_filament_movements();
  9880. }
  9881. break;
  9882. // Filament loaded properly but color is not clear
  9883. case 3:
  9884. st_synchronize();
  9885. load_filament_final_feed();
  9886. lcd_loading_color();
  9887. st_synchronize();
  9888. break;
  9889. // Everything good
  9890. default:
  9891. lcd_change_success();
  9892. break;
  9893. }
  9894. }
  9895. }
  9896. //! @brief Wait for user action
  9897. //!
  9898. //! Beep, manage nozzle heater and wait for user to start unload filament
  9899. //! If times out, active extruder temperature is set to 0.
  9900. //!
  9901. //! @param HotendTempBckp Temperature to be restored for active extruder, after user resolves MMU problem.
  9902. void M600_wait_for_user(float HotendTempBckp) {
  9903. KEEPALIVE_STATE(PAUSED_FOR_USER);
  9904. int counterBeep = 0;
  9905. unsigned long waiting_start_time = _millis();
  9906. uint8_t wait_for_user_state = 0;
  9907. lcd_display_message_fullscreen_P(_T(MSG_PRESS_TO_UNLOAD));
  9908. bool bFirst=true;
  9909. while (!(wait_for_user_state == 0 && lcd_clicked())){
  9910. manage_heater();
  9911. manage_inactivity(true);
  9912. #if BEEPER > 0
  9913. if (counterBeep == 500) {
  9914. counterBeep = 0;
  9915. }
  9916. SET_OUTPUT(BEEPER);
  9917. if (counterBeep == 0) {
  9918. if((eSoundMode==e_SOUND_MODE_BLIND)|| (eSoundMode==e_SOUND_MODE_LOUD)||((eSoundMode==e_SOUND_MODE_ONCE)&&bFirst))
  9919. {
  9920. bFirst=false;
  9921. WRITE(BEEPER, HIGH);
  9922. }
  9923. }
  9924. if (counterBeep == 20) {
  9925. WRITE(BEEPER, LOW);
  9926. }
  9927. counterBeep++;
  9928. #endif //BEEPER > 0
  9929. switch (wait_for_user_state) {
  9930. case 0: //nozzle is hot, waiting for user to press the knob to unload filament
  9931. delay_keep_alive(4);
  9932. if (_millis() > waiting_start_time + (unsigned long)M600_TIMEOUT * 1000) {
  9933. lcd_display_message_fullscreen_P(_i("Press the knob to preheat nozzle and continue."));////MSG_PRESS_TO_PREHEAT c=20 r=4
  9934. wait_for_user_state = 1;
  9935. setAllTargetHotends(0);
  9936. st_synchronize();
  9937. disable_e0();
  9938. disable_e1();
  9939. disable_e2();
  9940. }
  9941. break;
  9942. case 1: //nozzle target temperature is set to zero, waiting for user to start nozzle preheat
  9943. delay_keep_alive(4);
  9944. if (lcd_clicked()) {
  9945. setTargetHotend(HotendTempBckp, active_extruder);
  9946. lcd_wait_for_heater();
  9947. wait_for_user_state = 2;
  9948. }
  9949. break;
  9950. case 2: //waiting for nozzle to reach target temperature
  9951. if (fabs(degTargetHotend(active_extruder) - degHotend(active_extruder)) < 1) {
  9952. lcd_display_message_fullscreen_P(_T(MSG_PRESS_TO_UNLOAD));
  9953. waiting_start_time = _millis();
  9954. wait_for_user_state = 0;
  9955. }
  9956. else {
  9957. counterBeep = 20; //beeper will be inactive during waiting for nozzle preheat
  9958. lcd_set_cursor(1, 4);
  9959. lcd_printf_P(PSTR("%3d"), (int16_t)degHotend(active_extruder));
  9960. }
  9961. break;
  9962. }
  9963. }
  9964. WRITE(BEEPER, LOW);
  9965. }
  9966. void M600_load_filament_movements()
  9967. {
  9968. current_position[E_AXIS]+= FILAMENTCHANGE_FIRSTFEED;
  9969. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EFEED_FIRST);
  9970. load_filament_final_feed();
  9971. lcd_loading_filament();
  9972. st_synchronize();
  9973. }
  9974. void M600_load_filament() {
  9975. //load filament for single material and MMU
  9976. lcd_wait_interact();
  9977. //load_filament_time = _millis();
  9978. KEEPALIVE_STATE(PAUSED_FOR_USER);
  9979. while(!lcd_clicked())
  9980. {
  9981. manage_heater();
  9982. manage_inactivity(true);
  9983. #ifdef FILAMENT_SENSOR
  9984. if (fsensor.getFilamentLoadEvent()) {
  9985. Sound_MakeCustom(50,1000,false);
  9986. break;
  9987. }
  9988. #endif //FILAMENT_SENSOR
  9989. }
  9990. KEEPALIVE_STATE(IN_HANDLER);
  9991. M600_load_filament_movements();
  9992. Sound_MakeCustom(50,1000,false);
  9993. lcd_update_enable(false);
  9994. }
  9995. //! @brief Wait for click
  9996. //!
  9997. //! Set
  9998. void marlin_wait_for_click()
  9999. {
  10000. int8_t busy_state_backup = busy_state;
  10001. KEEPALIVE_STATE(PAUSED_FOR_USER);
  10002. lcd_consume_click();
  10003. while(!lcd_clicked())
  10004. {
  10005. manage_heater();
  10006. manage_inactivity(true);
  10007. lcd_update(0);
  10008. }
  10009. KEEPALIVE_STATE(busy_state_backup);
  10010. }
  10011. #ifdef PSU_Delta
  10012. bool bEnableForce_z;
  10013. void init_force_z()
  10014. {
  10015. WRITE(Z_ENABLE_PIN,Z_ENABLE_ON);
  10016. bEnableForce_z=true; // "true"-value enforce "disable_force_z()" executing
  10017. disable_force_z();
  10018. }
  10019. void check_force_z()
  10020. {
  10021. if(!(bEnableForce_z||eeprom_read_byte((uint8_t*)EEPROM_SILENT)))
  10022. init_force_z(); // causes enforced switching into disable-state
  10023. }
  10024. void disable_force_z()
  10025. {
  10026. if(!bEnableForce_z) return; // motor already disabled (may be ;-p )
  10027. bEnableForce_z=false;
  10028. // switching to silent mode
  10029. #ifdef TMC2130
  10030. tmc2130_mode=TMC2130_MODE_SILENT;
  10031. update_mode_profile();
  10032. tmc2130_init(TMCInitParams(true, FarmOrUserECool()));
  10033. #endif // TMC2130
  10034. }
  10035. void enable_force_z()
  10036. {
  10037. if(bEnableForce_z)
  10038. return; // motor already enabled (may be ;-p )
  10039. bEnableForce_z=true;
  10040. // mode recovering
  10041. #ifdef TMC2130
  10042. tmc2130_mode=eeprom_read_byte((uint8_t*)EEPROM_SILENT)?TMC2130_MODE_SILENT:TMC2130_MODE_NORMAL;
  10043. update_mode_profile();
  10044. tmc2130_init(TMCInitParams(true, FarmOrUserECool()));
  10045. #endif // TMC2130
  10046. WRITE(Z_ENABLE_PIN,Z_ENABLE_ON); // slightly redundant ;-p
  10047. }
  10048. #endif // PSU_Delta