Marlin_main.cpp 386 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535
  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 "AutoDeplete.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. int8_t lcd_change_fil_state = 0;
  153. unsigned long pause_time = 0;
  154. unsigned long start_pause_print = _millis();
  155. unsigned long t_fan_rising_edge = _millis();
  156. LongTimer safetyTimer;
  157. static LongTimer crashDetTimer;
  158. //unsigned long load_filament_time;
  159. bool mesh_bed_leveling_flag = false;
  160. unsigned long total_filament_used;
  161. HeatingStatus heating_status;
  162. uint8_t heating_status_counter;
  163. bool loading_flag = false;
  164. #define XY_NO_RESTORE_FLAG (mesh_bed_leveling_flag || homing_flag)
  165. bool fan_state[2];
  166. int fan_edge_counter[2];
  167. int fan_speed[2];
  168. float extruder_multiplier[EXTRUDERS] = {1.0
  169. #if EXTRUDERS > 1
  170. , 1.0
  171. #if EXTRUDERS > 2
  172. , 1.0
  173. #endif
  174. #endif
  175. };
  176. float current_position[NUM_AXIS] = { 0.0, 0.0, 0.0, 0.0 };
  177. //shortcuts for more readable code
  178. #define _x current_position[X_AXIS]
  179. #define _y current_position[Y_AXIS]
  180. #define _z current_position[Z_AXIS]
  181. #define _e current_position[E_AXIS]
  182. float min_pos[3] = { X_MIN_POS, Y_MIN_POS, Z_MIN_POS };
  183. float max_pos[3] = { X_MAX_POS, Y_MAX_POS, Z_MAX_POS };
  184. bool axis_known_position[3] = {false, false, false};
  185. // Extruder offset
  186. #if EXTRUDERS > 1
  187. #define NUM_EXTRUDER_OFFSETS 2 // only in XY plane
  188. float extruder_offset[NUM_EXTRUDER_OFFSETS][EXTRUDERS] = {
  189. #if defined(EXTRUDER_OFFSET_X) && defined(EXTRUDER_OFFSET_Y)
  190. EXTRUDER_OFFSET_X, EXTRUDER_OFFSET_Y
  191. #endif
  192. };
  193. #endif
  194. uint8_t active_extruder = 0;
  195. int fanSpeed=0;
  196. uint8_t newFanSpeed = 0;
  197. #ifdef FWRETRACT
  198. bool retracted[EXTRUDERS]={false
  199. #if EXTRUDERS > 1
  200. , false
  201. #if EXTRUDERS > 2
  202. , false
  203. #endif
  204. #endif
  205. };
  206. bool retracted_swap[EXTRUDERS]={false
  207. #if EXTRUDERS > 1
  208. , false
  209. #if EXTRUDERS > 2
  210. , false
  211. #endif
  212. #endif
  213. };
  214. float retract_length_swap = RETRACT_LENGTH_SWAP;
  215. float retract_recover_length_swap = RETRACT_RECOVER_LENGTH_SWAP;
  216. #endif
  217. #ifdef PS_DEFAULT_OFF
  218. bool powersupply = false;
  219. #else
  220. bool powersupply = true;
  221. #endif
  222. bool cancel_heatup = false;
  223. int8_t busy_state = NOT_BUSY;
  224. static long prev_busy_signal_ms = -1;
  225. uint8_t host_keepalive_interval = HOST_KEEPALIVE_INTERVAL;
  226. const char errormagic[] PROGMEM = "Error:";
  227. const char echomagic[] PROGMEM = "echo:";
  228. const char G28W0[] PROGMEM = "G28 W0";
  229. // Define some coordinates outside the clamp limits (making them invalid past the parsing stage) so
  230. // that they can be used later for various logical checks
  231. #define X_COORD_INVALID (X_MIN_POS-1)
  232. #define SAVED_START_POSITION_UNSET X_COORD_INVALID
  233. float saved_start_position[NUM_AXIS] = {SAVED_START_POSITION_UNSET, 0, 0, 0};
  234. uint16_t saved_segment_idx = 0;
  235. // storing estimated time to end of print counted by slicer
  236. uint8_t print_percent_done_normal = PRINT_PERCENT_DONE_INIT;
  237. uint8_t print_percent_done_silent = PRINT_PERCENT_DONE_INIT;
  238. uint16_t print_time_remaining_normal = PRINT_TIME_REMAINING_INIT; //estimated remaining print time in minutes
  239. uint16_t print_time_remaining_silent = PRINT_TIME_REMAINING_INIT; //estimated remaining print time in minutes
  240. uint16_t print_time_to_change_normal = PRINT_TIME_REMAINING_INIT; //estimated remaining time to next change in minutes
  241. uint16_t print_time_to_change_silent = PRINT_TIME_REMAINING_INIT; //estimated remaining time to next change in minutes
  242. uint32_t IP_address = 0;
  243. //===========================================================================
  244. //=============================Private Variables=============================
  245. //===========================================================================
  246. #define MSG_BED_LEVELING_FAILED_TIMEOUT 30
  247. const char axis_codes[NUM_AXIS] = {'X', 'Y', 'Z', 'E'};
  248. float destination[NUM_AXIS] = { 0.0, 0.0, 0.0, 0.0};
  249. // For tracing an arc
  250. static float offset[3] = {0.0, 0.0, 0.0};
  251. // Current feedrate
  252. float feedrate = 1500.0;
  253. // Feedrate for the next move
  254. static float next_feedrate;
  255. // Original feedrate saved during homing moves
  256. static float saved_feedrate;
  257. const int8_t sensitive_pins[] PROGMEM = SENSITIVE_PINS; // Sensitive pin list for M42
  258. //static float tt = 0;
  259. //static float bt = 0;
  260. //Inactivity shutdown variables
  261. static LongTimer previous_millis_cmd;
  262. unsigned long max_inactive_time = 0;
  263. static unsigned long stepper_inactive_time = DEFAULT_STEPPER_DEACTIVE_TIME*1000l;
  264. static unsigned long safetytimer_inactive_time = DEFAULT_SAFETYTIMER_TIME_MINS*60*1000ul;
  265. unsigned long starttime=0;
  266. unsigned long stoptime=0;
  267. ShortTimer usb_timer;
  268. bool Stopped=false;
  269. #if NUM_SERVOS > 0
  270. Servo servos[NUM_SERVOS];
  271. #endif
  272. bool target_direction;
  273. //Insert variables if CHDK is defined
  274. #ifdef CHDK
  275. unsigned long chdkHigh = 0;
  276. bool chdkActive = false;
  277. #endif
  278. //! @name RAM save/restore printing
  279. //! @{
  280. bool saved_printing = false; //!< Print is paused and saved in RAM
  281. static uint32_t saved_sdpos = 0; //!< SD card position, or line number in case of USB printing
  282. uint8_t saved_printing_type = PRINTING_TYPE_SD;
  283. static float saved_pos[4] = { X_COORD_INVALID, 0, 0, 0 };
  284. static uint16_t saved_feedrate2 = 0; //!< Default feedrate (truncated from float)
  285. static int saved_feedmultiply2 = 0;
  286. static uint8_t saved_active_extruder = 0;
  287. float saved_extruder_temperature = 0.0; //!< Active extruder temperature
  288. float saved_bed_temperature = 0.0; //!< Bed temperature
  289. static bool saved_extruder_relative_mode = false;
  290. int saved_fan_speed = 0; //!< Print fan speed
  291. //! @}
  292. static int saved_feedmultiply_mm = 100;
  293. class AutoReportFeatures {
  294. union {
  295. struct {
  296. uint8_t temp : 1; //Temperature flag
  297. uint8_t fans : 1; //Fans flag
  298. uint8_t pos: 1; //Position flag
  299. uint8_t ar4 : 1; //Unused
  300. uint8_t ar5 : 1; //Unused
  301. uint8_t ar6 : 1; //Unused
  302. uint8_t ar7 : 1; //Unused
  303. } __attribute__((packed)) bits;
  304. uint8_t byte;
  305. } arFunctionsActive;
  306. uint8_t auto_report_period;
  307. public:
  308. LongTimer auto_report_timer;
  309. AutoReportFeatures():auto_report_period(0){
  310. #if defined(AUTO_REPORT)
  311. arFunctionsActive.byte = 0xff;
  312. #else
  313. arFunctionsActive.byte = 0;
  314. #endif //AUTO_REPORT
  315. }
  316. inline bool Temp()const { return arFunctionsActive.bits.temp != 0; }
  317. inline void SetTemp(uint8_t v){ arFunctionsActive.bits.temp = v; }
  318. inline bool Fans()const { return arFunctionsActive.bits.fans != 0; }
  319. inline void SetFans(uint8_t v){ arFunctionsActive.bits.fans = v; }
  320. inline bool Pos()const { return arFunctionsActive.bits.pos != 0; }
  321. inline void SetPos(uint8_t v){ arFunctionsActive.bits.pos = v; }
  322. inline void SetMask(uint8_t mask){ arFunctionsActive.byte = mask; }
  323. /// sets the autoreporting timer's period
  324. /// setting it to zero stops the timer
  325. void SetPeriod(uint8_t p){
  326. auto_report_period = p;
  327. if (auto_report_period != 0){
  328. auto_report_timer.start();
  329. } else{
  330. auto_report_timer.stop();
  331. }
  332. }
  333. inline void TimerStart() { auto_report_timer.start(); }
  334. inline bool TimerRunning()const { return auto_report_timer.running(); }
  335. inline bool TimerExpired() { return auto_report_timer.expired(auto_report_period * 1000ul); }
  336. };
  337. AutoReportFeatures autoReportFeatures;
  338. //===========================================================================
  339. //=============================Routines======================================
  340. //===========================================================================
  341. static bool setTargetedHotend(int code, uint8_t &extruder);
  342. static void print_time_remaining_init();
  343. static void wait_for_heater(long codenum, uint8_t extruder);
  344. static void gcode_G28(bool home_x_axis, bool home_y_axis, bool home_z_axis);
  345. static void gcode_M105(uint8_t extruder);
  346. #ifndef PINDA_THERMISTOR
  347. static void temp_compensation_start();
  348. static void temp_compensation_apply();
  349. #endif
  350. #ifdef PRUSA_SN_SUPPORT
  351. static uint8_t get_PRUSA_SN(char* SN);
  352. #endif //PRUSA_SN_SUPPORT
  353. uint16_t gcode_in_progress = 0;
  354. uint16_t mcode_in_progress = 0;
  355. void serial_echopair_P(const char *s_P, float v)
  356. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  357. void serial_echopair_P(const char *s_P, double v)
  358. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  359. void serial_echopair_P(const char *s_P, unsigned long v)
  360. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  361. void serialprintPGM(const char *str) {
  362. while(uint8_t ch = pgm_read_byte(str)) {
  363. MYSERIAL.write((char)ch);
  364. ++str;
  365. }
  366. }
  367. void serialprintlnPGM(const char *str) {
  368. serialprintPGM(str);
  369. MYSERIAL.println();
  370. }
  371. #ifdef SDSUPPORT
  372. #include "SdFatUtil.h"
  373. int freeMemory() { return SdFatUtil::FreeRam(); }
  374. #else
  375. extern "C" {
  376. extern unsigned int __bss_end;
  377. extern unsigned int __heap_start;
  378. extern void *__brkval;
  379. int freeMemory() {
  380. int free_memory;
  381. if ((int)__brkval == 0)
  382. free_memory = ((int)&free_memory) - ((int)&__bss_end);
  383. else
  384. free_memory = ((int)&free_memory) - ((int)__brkval);
  385. return free_memory;
  386. }
  387. }
  388. #endif //!SDSUPPORT
  389. void setup_killpin()
  390. {
  391. #if defined(KILL_PIN) && KILL_PIN > -1
  392. SET_INPUT(KILL_PIN);
  393. WRITE(KILL_PIN,HIGH);
  394. #endif
  395. }
  396. // Set home pin
  397. void setup_homepin(void)
  398. {
  399. #if defined(HOME_PIN) && HOME_PIN > -1
  400. SET_INPUT(HOME_PIN);
  401. WRITE(HOME_PIN,HIGH);
  402. #endif
  403. }
  404. void setup_photpin()
  405. {
  406. #if defined(PHOTOGRAPH_PIN) && PHOTOGRAPH_PIN > -1
  407. SET_OUTPUT(PHOTOGRAPH_PIN);
  408. WRITE(PHOTOGRAPH_PIN, LOW);
  409. #endif
  410. }
  411. void setup_powerhold()
  412. {
  413. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  414. SET_OUTPUT(SUICIDE_PIN);
  415. WRITE(SUICIDE_PIN, HIGH);
  416. #endif
  417. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  418. SET_OUTPUT(PS_ON_PIN);
  419. #if defined(PS_DEFAULT_OFF)
  420. WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  421. #else
  422. WRITE(PS_ON_PIN, PS_ON_AWAKE);
  423. #endif
  424. #endif
  425. }
  426. void suicide()
  427. {
  428. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  429. SET_OUTPUT(SUICIDE_PIN);
  430. WRITE(SUICIDE_PIN, LOW);
  431. #endif
  432. }
  433. void servo_init()
  434. {
  435. #if (NUM_SERVOS >= 1) && defined(SERVO0_PIN) && (SERVO0_PIN > -1)
  436. servos[0].attach(SERVO0_PIN);
  437. #endif
  438. #if (NUM_SERVOS >= 2) && defined(SERVO1_PIN) && (SERVO1_PIN > -1)
  439. servos[1].attach(SERVO1_PIN);
  440. #endif
  441. #if (NUM_SERVOS >= 3) && defined(SERVO2_PIN) && (SERVO2_PIN > -1)
  442. servos[2].attach(SERVO2_PIN);
  443. #endif
  444. #if (NUM_SERVOS >= 4) && defined(SERVO3_PIN) && (SERVO3_PIN > -1)
  445. servos[3].attach(SERVO3_PIN);
  446. #endif
  447. #if (NUM_SERVOS >= 5)
  448. #error "TODO: enter initalisation code for more servos"
  449. #endif
  450. }
  451. bool __attribute__((noinline)) printer_active() {
  452. return IS_SD_PRINTING
  453. || usb_timer.running()
  454. || isPrintPaused
  455. || (custom_message_type == CustomMsg::TempCal)
  456. || saved_printing
  457. || (lcd_commands_type == LcdCommands::Layer1Cal)
  458. || mmu_print_saved
  459. || homing_flag
  460. || mesh_bed_leveling_flag;
  461. }
  462. bool fans_check_enabled = true;
  463. #ifdef TMC2130
  464. void crashdet_stop_and_save_print()
  465. {
  466. stop_and_save_print_to_ram(10, -default_retraction); //XY - no change, Z 10mm up, E -1mm retract
  467. }
  468. void crashdet_restore_print_and_continue()
  469. {
  470. restore_print_from_ram_and_continue(default_retraction); //XYZ = orig, E +1mm unretract
  471. // babystep_apply();
  472. }
  473. void crashdet_fmt_error(char* buf, uint8_t mask)
  474. {
  475. if(mask & X_AXIS_MASK) *buf++ = axis_codes[X_AXIS];
  476. if(mask & Y_AXIS_MASK) *buf++ = axis_codes[Y_AXIS];
  477. *buf++ = ' ';
  478. strcpy_P(buf, _T(MSG_CRASH_DETECTED));
  479. }
  480. void crashdet_detected(uint8_t mask)
  481. {
  482. st_synchronize();
  483. static uint8_t crashDet_counter = 0;
  484. static uint8_t crashDet_axes = 0;
  485. bool automatic_recovery_after_crash = true;
  486. char msg[LCD_WIDTH+1] = "";
  487. if (crashDetTimer.expired(CRASHDET_TIMER * 1000ul)) {
  488. crashDet_counter = 0;
  489. }
  490. if(++crashDet_counter >= CRASHDET_COUNTER_MAX) {
  491. automatic_recovery_after_crash = false;
  492. }
  493. crashDetTimer.start();
  494. crashDet_axes |= mask;
  495. lcd_update_enable(true);
  496. lcd_clear();
  497. lcd_update(2);
  498. if (mask & X_AXIS_MASK)
  499. {
  500. eeprom_update_byte((uint8_t*)EEPROM_CRASH_COUNT_X, eeprom_read_byte((uint8_t*)EEPROM_CRASH_COUNT_X) + 1);
  501. eeprom_update_word((uint16_t*)EEPROM_CRASH_COUNT_X_TOT, eeprom_read_word((uint16_t*)EEPROM_CRASH_COUNT_X_TOT) + 1);
  502. }
  503. if (mask & Y_AXIS_MASK)
  504. {
  505. eeprom_update_byte((uint8_t*)EEPROM_CRASH_COUNT_Y, eeprom_read_byte((uint8_t*)EEPROM_CRASH_COUNT_Y) + 1);
  506. eeprom_update_word((uint16_t*)EEPROM_CRASH_COUNT_Y_TOT, eeprom_read_word((uint16_t*)EEPROM_CRASH_COUNT_Y_TOT) + 1);
  507. }
  508. lcd_update_enable(true);
  509. lcd_update(2);
  510. // prepare the status message with the _current_ axes status
  511. crashdet_fmt_error(msg, mask);
  512. lcd_setstatus(msg);
  513. gcode_G28(true, true, false); //home X and Y
  514. if (automatic_recovery_after_crash) {
  515. enquecommand_P(PSTR("CRASH_RECOVER"));
  516. }else{
  517. setTargetHotend(0, active_extruder);
  518. // notify the user of *all* the axes previously affected, not just the last one
  519. lcd_update_enable(false);
  520. lcd_clear();
  521. crashdet_fmt_error(msg, crashDet_axes);
  522. crashDet_axes = 0;
  523. lcd_print(msg);
  524. // ask whether to resume printing
  525. lcd_set_cursor(0, 1);
  526. lcd_puts_P(_T(MSG_RESUME_PRINT));
  527. lcd_putc('?');
  528. bool yesno = lcd_show_yes_no_and_wait(false);
  529. lcd_update_enable(true);
  530. if (yesno)
  531. {
  532. enquecommand_P(PSTR("CRASH_RECOVER"));
  533. }
  534. else
  535. {
  536. enquecommand_P(PSTR("CRASH_CANCEL"));
  537. }
  538. }
  539. }
  540. void crashdet_recover()
  541. {
  542. crashdet_restore_print_and_continue();
  543. if (lcd_crash_detect_enabled()) tmc2130_sg_stop_on_crash = true;
  544. }
  545. void crashdet_cancel()
  546. {
  547. saved_printing = false;
  548. tmc2130_sg_stop_on_crash = true;
  549. if (saved_printing_type == PRINTING_TYPE_SD) {
  550. lcd_print_stop();
  551. }else if(saved_printing_type == PRINTING_TYPE_USB){
  552. SERIAL_ECHOLNRPGM(MSG_OCTOPRINT_CANCEL); //for Octoprint: works the same as clicking "Abort" button in Octoprint GUI
  553. cmdqueue_reset();
  554. }
  555. }
  556. #endif //TMC2130
  557. void failstats_reset_print()
  558. {
  559. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_X, 0);
  560. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_Y, 0);
  561. eeprom_update_byte((uint8_t *)EEPROM_FERROR_COUNT, 0);
  562. eeprom_update_byte((uint8_t *)EEPROM_POWER_COUNT, 0);
  563. eeprom_update_byte((uint8_t *)EEPROM_MMU_FAIL, 0);
  564. eeprom_update_byte((uint8_t *)EEPROM_MMU_LOAD_FAIL, 0);
  565. }
  566. void softReset()
  567. {
  568. cli();
  569. wdt_enable(WDTO_15MS);
  570. while(1);
  571. }
  572. #ifdef MESH_BED_LEVELING
  573. enum MeshLevelingState { MeshReport, MeshStart, MeshNext, MeshSet };
  574. #endif
  575. static void factory_reset_stats(){
  576. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, 0);
  577. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, 0);
  578. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_X, 0);
  579. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_Y, 0);
  580. eeprom_update_byte((uint8_t *)EEPROM_FERROR_COUNT, 0);
  581. eeprom_update_byte((uint8_t *)EEPROM_POWER_COUNT, 0);
  582. eeprom_update_word((uint16_t *)EEPROM_CRASH_COUNT_X_TOT, 0);
  583. eeprom_update_word((uint16_t *)EEPROM_CRASH_COUNT_Y_TOT, 0);
  584. eeprom_update_word((uint16_t *)EEPROM_FERROR_COUNT_TOT, 0);
  585. eeprom_update_word((uint16_t *)EEPROM_POWER_COUNT_TOT, 0);
  586. eeprom_update_word((uint16_t *)EEPROM_MMU_FAIL_TOT, 0);
  587. eeprom_update_word((uint16_t *)EEPROM_MMU_LOAD_FAIL_TOT, 0);
  588. eeprom_update_byte((uint8_t *)EEPROM_MMU_FAIL, 0);
  589. eeprom_update_byte((uint8_t *)EEPROM_MMU_LOAD_FAIL, 0);
  590. }
  591. // Factory reset function
  592. // This function is used to erase parts or whole EEPROM memory which is used for storing calibration and and so on.
  593. // Level input parameter sets depth of reset
  594. static void factory_reset(char level)
  595. {
  596. lcd_clear();
  597. Sound_MakeCustom(100,0,false);
  598. switch (level) {
  599. case 0: // Level 0: Language reset
  600. lang_reset();
  601. break;
  602. case 1: //Level 1: Reset statistics
  603. factory_reset_stats();
  604. lcd_menu_statistics();
  605. break;
  606. case 2: // Level 2: Prepare for shipping
  607. factory_reset_stats();
  608. // FALLTHRU
  609. case 3: // Level 3: Preparation after being serviced
  610. // Force language selection at the next boot up.
  611. lang_reset();
  612. // Force the "Follow calibration flow" message at the next boot up.
  613. calibration_status_store(CALIBRATION_STATUS_Z_CALIBRATION);
  614. eeprom_write_byte((uint8_t*)EEPROM_WIZARD_ACTIVE, 2); //run wizard
  615. farm_disable();
  616. #ifdef FILAMENT_SENSOR
  617. fsensor.setEnabled(true);
  618. fsensor.setAutoLoadEnabled(true, true);
  619. fsensor.setRunoutEnabled(true, true);
  620. #if (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  621. fsensor.setJamDetectionEnabled(true, true);
  622. #endif //(FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  623. #endif //FILAMENT_SENSOR
  624. break;
  625. case 4:
  626. menu_progressbar_init(EEPROM_TOP, PSTR("ERASING all data"));
  627. // Erase EEPROM
  628. for (uint16_t i = 0; i < EEPROM_TOP; i++) {
  629. eeprom_update_byte((uint8_t*)i, 0xFF);
  630. menu_progressbar_update(i);
  631. }
  632. menu_progressbar_finish();
  633. softReset();
  634. break;
  635. default:
  636. break;
  637. }
  638. }
  639. extern "C" {
  640. FILE _uartout; //= {0}; Global variable is always zero initialized. No need to explicitly state this.
  641. }
  642. int uart_putchar(char c, FILE *)
  643. {
  644. MYSERIAL.write(c);
  645. return 0;
  646. }
  647. void lcd_splash()
  648. {
  649. lcd_clear(); // clears display and homes screen
  650. lcd_puts_P(PSTR("\n Original Prusa i3\n Prusa Research"));
  651. }
  652. void factory_reset()
  653. {
  654. KEEPALIVE_STATE(PAUSED_FOR_USER);
  655. if (!READ(BTN_ENC))
  656. {
  657. _delay_ms(1000);
  658. if (!READ(BTN_ENC))
  659. {
  660. lcd_clear();
  661. lcd_puts_P(PSTR("Factory RESET"));
  662. SET_OUTPUT(BEEPER);
  663. if(eSoundMode!=e_SOUND_MODE_SILENT)
  664. WRITE(BEEPER, HIGH);
  665. while (!READ(BTN_ENC));
  666. WRITE(BEEPER, LOW);
  667. _delay_ms(2000);
  668. char level = reset_menu();
  669. factory_reset(level);
  670. switch (level) {
  671. case 0:
  672. case 1:
  673. case 2:
  674. case 3:
  675. case 4: _delay_ms(0); break;
  676. }
  677. }
  678. }
  679. KEEPALIVE_STATE(IN_HANDLER);
  680. }
  681. void show_fw_version_warnings() {
  682. if (FW_DEV_VERSION == FW_VERSION_GOLD || FW_DEV_VERSION == FW_VERSION_RC) return;
  683. switch (FW_DEV_VERSION) {
  684. case(FW_VERSION_ALPHA): lcd_show_fullscreen_message_and_wait_P(_i("You are using firmware alpha version. This is development version. Using this version is not recommended and may cause printer damage.")); break;////MSG_FW_VERSION_ALPHA c=20 r=8
  685. case(FW_VERSION_BETA): lcd_show_fullscreen_message_and_wait_P(_i("You are using firmware beta version. This is development version. Using this version is not recommended and may cause printer damage.")); break;////MSG_FW_VERSION_BETA c=20 r=8
  686. case(FW_VERSION_DEVEL):
  687. case(FW_VERSION_DEBUG):
  688. lcd_update_enable(false);
  689. lcd_clear();
  690. #if FW_DEV_VERSION == FW_VERSION_DEVEL
  691. lcd_puts_at_P(0, 0, PSTR("Development build !!"));
  692. #else
  693. lcd_puts_at_P(0, 0, PSTR("Debbugging build !!!"));
  694. #endif
  695. lcd_puts_at_P(0, 1, PSTR("May destroy printer!"));
  696. lcd_puts_at_P(0, 2, PSTR("ver ")); lcd_puts_P(PSTR(FW_VERSION_FULL));
  697. lcd_puts_at_P(0, 3, PSTR(FW_REPOSITORY));
  698. lcd_wait_for_click();
  699. break;
  700. // 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
  701. }
  702. lcd_update_enable(true);
  703. }
  704. #if defined(FILAMENT_SENSOR) && defined(FSENSOR_PROBING)
  705. //! @brief try to check if firmware is on right type of printer
  706. static void check_if_fw_is_on_right_printer() {
  707. if (fsensor.probeOtherType()) {
  708. lcd_show_fullscreen_message_and_wait_P(_i(PRINTER_NAME " firmware detected on " PRINTER_NAME_ALTERNATE " printer"));////c=20 r=4
  709. }
  710. }
  711. #endif //defined(FILAMENT_SENSOR) && defined(FSENSOR_PROBING)
  712. uint8_t check_printer_version()
  713. {
  714. uint8_t version_changed = 0;
  715. uint16_t printer_type = eeprom_read_word((uint16_t*)EEPROM_PRINTER_TYPE);
  716. uint16_t motherboard = eeprom_read_word((uint16_t*)EEPROM_BOARD_TYPE);
  717. if (printer_type != PRINTER_TYPE) {
  718. if (printer_type == 0xffff) eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  719. else version_changed |= 0b10;
  720. }
  721. if (motherboard != MOTHERBOARD) {
  722. if(motherboard == 0xffff) eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  723. else version_changed |= 0b01;
  724. }
  725. return version_changed;
  726. }
  727. #ifdef BOOTAPP
  728. #include "bootapp.h" //bootloader support
  729. #endif //BOOTAPP
  730. #if (LANG_MODE != 0) //secondary language support
  731. #ifdef XFLASH
  732. // language update from external flash
  733. #define LANGBOOT_BLOCKSIZE 0x1000u
  734. #define LANGBOOT_RAMBUFFER 0x0800
  735. void update_sec_lang_from_external_flash()
  736. {
  737. if ((boot_app_magic == BOOT_APP_MAGIC) && (boot_app_flags & BOOT_APP_FLG_USER0))
  738. {
  739. uint8_t lang = boot_reserved >> 3;
  740. uint8_t state = boot_reserved & 0x07;
  741. lang_table_header_t header;
  742. uint32_t src_addr;
  743. if (lang_get_header(lang, &header, &src_addr))
  744. {
  745. lcd_puts_at_P(1,3,PSTR("Language update."));
  746. for (uint8_t i = 0; i < state; i++) fputc('.', lcdout);
  747. _delay(100);
  748. boot_reserved = (boot_reserved & 0xF8) | ((state + 1) & 0x07);
  749. if ((state * LANGBOOT_BLOCKSIZE) < header.size)
  750. {
  751. cli();
  752. uint16_t size = header.size - state * LANGBOOT_BLOCKSIZE;
  753. if (size > LANGBOOT_BLOCKSIZE) size = LANGBOOT_BLOCKSIZE;
  754. xflash_rd_data(src_addr + state * LANGBOOT_BLOCKSIZE, (uint8_t*)LANGBOOT_RAMBUFFER, size);
  755. if (state == 0)
  756. {
  757. //TODO - check header integrity
  758. }
  759. bootapp_ram2flash(LANGBOOT_RAMBUFFER, _SEC_LANG_TABLE + state * LANGBOOT_BLOCKSIZE, size);
  760. }
  761. else
  762. {
  763. //TODO - check sec lang data integrity
  764. eeprom_update_byte((unsigned char *)EEPROM_LANG, LANG_ID_SEC);
  765. }
  766. }
  767. }
  768. boot_app_flags &= ~BOOT_APP_FLG_USER0;
  769. }
  770. #ifdef DEBUG_XFLASH
  771. uint8_t lang_xflash_enum_codes(uint16_t* codes)
  772. {
  773. lang_table_header_t header;
  774. uint8_t count = 0;
  775. uint32_t addr = 0x00000;
  776. while (1)
  777. {
  778. printf_P(_n("LANGTABLE%d:"), count);
  779. xflash_rd_data(addr, (uint8_t*)&header, sizeof(lang_table_header_t));
  780. if (header.magic != LANG_MAGIC)
  781. {
  782. puts_P(_n("NG!"));
  783. break;
  784. }
  785. puts_P(_n("OK"));
  786. printf_P(_n(" _lt_magic = 0x%08lx %S\n"), header.magic, (header.magic==LANG_MAGIC)?_n("OK"):_n("NA"));
  787. printf_P(_n(" _lt_size = 0x%04x (%d)\n"), header.size, header.size);
  788. printf_P(_n(" _lt_count = 0x%04x (%d)\n"), header.count, header.count);
  789. printf_P(_n(" _lt_chsum = 0x%04x\n"), header.checksum);
  790. printf_P(_n(" _lt_code = 0x%04x (%c%c)\n"), header.code, header.code >> 8, header.code & 0xff);
  791. printf_P(_n(" _lt_sign = 0x%08lx\n"), header.signature);
  792. addr += header.size;
  793. codes[count] = header.code;
  794. count ++;
  795. }
  796. return count;
  797. }
  798. void list_sec_lang_from_external_flash()
  799. {
  800. uint16_t codes[8];
  801. uint8_t count = lang_xflash_enum_codes(codes);
  802. printf_P(_n("XFlash lang count = %hhd\n"), count);
  803. }
  804. #endif //DEBUG_XFLASH
  805. #endif //XFLASH
  806. #endif //(LANG_MODE != 0)
  807. static void fw_crash_init()
  808. {
  809. #ifdef XFLASH_DUMP
  810. dump_crash_reason crash_reason;
  811. if(xfdump_check_state(&crash_reason))
  812. {
  813. // always signal to the host that a dump is available for retrieval
  814. puts_P(_N("// action:dump_available"));
  815. #ifdef EMERGENCY_DUMP
  816. if(crash_reason != dump_crash_reason::manual &&
  817. eeprom_read_byte((uint8_t*)EEPROM_FW_CRASH_FLAG) != 0xFF)
  818. {
  819. lcd_show_fullscreen_message_and_wait_P(
  820. _n("FW crash detected! "
  821. "You can continue printing. "
  822. "Debug data available for analysis. "
  823. "Contact support to submit details."));
  824. }
  825. #endif
  826. }
  827. #else //XFLASH_DUMP
  828. dump_crash_reason crash_reason = (dump_crash_reason)eeprom_read_byte((uint8_t*)EEPROM_FW_CRASH_FLAG);
  829. if(crash_reason != dump_crash_reason::manual && (uint8_t)crash_reason != 0xFF)
  830. {
  831. lcd_beeper_quick_feedback();
  832. lcd_clear();
  833. lcd_puts_P(_n("FIRMWARE CRASH!\nCrash reason:\n"));
  834. switch(crash_reason)
  835. {
  836. case dump_crash_reason::stack_error:
  837. lcd_puts_P(_n("Static memory has\nbeen overwritten"));
  838. break;
  839. case dump_crash_reason::watchdog:
  840. lcd_puts_P(_n("Watchdog timeout"));
  841. break;
  842. case dump_crash_reason::bad_isr:
  843. lcd_puts_P(_n("Bad interrupt"));
  844. break;
  845. default:
  846. lcd_print((uint8_t)crash_reason);
  847. break;
  848. }
  849. lcd_wait_for_click();
  850. }
  851. #endif //XFLASH_DUMP
  852. // prevent crash prompts to reappear once acknowledged
  853. eeprom_update_byte((uint8_t*)EEPROM_FW_CRASH_FLAG, 0xFF);
  854. }
  855. static void xflash_err_msg()
  856. {
  857. puts_P(_n("XFLASH not responding."));
  858. lcd_show_fullscreen_message_and_wait_P(_n("External SPI flash\nXFLASH is not res-\nponding. Language\nswitch unavailable."));
  859. }
  860. // "Setup" function is called by the Arduino framework on startup.
  861. // Before startup, the Timers-functions (PWM)/Analog RW and HardwareSerial provided by the Arduino-code
  862. // are initialized by the main() routine provided by the Arduino framework.
  863. void setup()
  864. {
  865. timer2_init(); // enables functional millis
  866. MMU2::mmu2.Start();
  867. ultralcd_init();
  868. spi_init();
  869. lcd_splash();
  870. Sound_Init(); // also guarantee "SET_OUTPUT(BEEPER)"
  871. selectedSerialPort = eeprom_read_byte((uint8_t *)EEPROM_SECOND_SERIAL_ACTIVE);
  872. if (selectedSerialPort == 0xFF) selectedSerialPort = 0;
  873. eeprom_update_byte((uint8_t *)EEPROM_SECOND_SERIAL_ACTIVE, selectedSerialPort);
  874. MYSERIAL.begin(BAUDRATE);
  875. fdev_setup_stream(uartout, uart_putchar, NULL, _FDEV_SETUP_WRITE); //setup uart out stream
  876. stdout = uartout;
  877. #ifdef XFLASH
  878. bool xflash_success = xflash_init();
  879. uint8_t optiboot_status = 1;
  880. if (xflash_success)
  881. {
  882. optiboot_status = optiboot_xflash_enter();
  883. #if (LANG_MODE != 0) //secondary language support
  884. update_sec_lang_from_external_flash();
  885. #endif //(LANG_MODE != 0)
  886. }
  887. #else
  888. const bool xflash_success = true;
  889. #endif //XFLASH
  890. setup_killpin();
  891. setup_powerhold();
  892. farm_mode_init();
  893. #ifdef TMC2130
  894. if( FarmOrUserECool() ){
  895. //increased extruder current (PFW363)
  896. tmc2130_current_h[E_AXIS] = TMC2130_CURRENTS_FARM;
  897. tmc2130_current_r[E_AXIS] = TMC2130_CURRENTS_FARM;
  898. }
  899. #endif //TMC2130
  900. #ifdef PRUSA_SN_SUPPORT
  901. //Check for valid SN in EEPROM. Try to retrieve it in case it's invalid.
  902. //SN is valid only if it is NULL terminated and starts with "CZPX".
  903. {
  904. char SN[20];
  905. eeprom_read_block(SN, (uint8_t*)EEPROM_PRUSA_SN, 20);
  906. if (SN[19] || strncmp_P(SN, PSTR("CZPX"), 4))
  907. {
  908. if (!get_PRUSA_SN(SN))
  909. {
  910. eeprom_update_block(SN, (uint8_t*)EEPROM_PRUSA_SN, 20);
  911. puts_P(PSTR("SN updated"));
  912. }
  913. else
  914. puts_P(PSTR("SN update failed"));
  915. }
  916. }
  917. #endif //PRUSA_SN_SUPPORT
  918. #ifndef XFLASH
  919. SERIAL_PROTOCOLLNPGM("start");
  920. #else
  921. if ((optiboot_status != 0) || (selectedSerialPort != 0))
  922. SERIAL_PROTOCOLLNPGM("start");
  923. #endif
  924. SERIAL_ECHO_START;
  925. puts_P(PSTR(" " FW_VERSION_FULL));
  926. //SERIAL_ECHOPAIR("Active sheet before:", static_cast<unsigned long int>(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet))));
  927. #ifdef DEBUG_SEC_LANG
  928. lang_table_header_t header;
  929. uint32_t src_addr = 0x00000;
  930. if (lang_get_header(1, &header, &src_addr))
  931. {
  932. printf_P(
  933. _n(
  934. " _src_addr = 0x%08lx\n"
  935. " _lt_magic = 0x%08lx %S\n"
  936. " _lt_size = 0x%04x (%d)\n"
  937. " _lt_count = 0x%04x (%d)\n"
  938. " _lt_chsum = 0x%04x\n"
  939. " _lt_code = 0x%04x (%c%c)\n"
  940. " _lt_resv1 = 0x%08lx\n"
  941. ),
  942. src_addr,
  943. header.magic, (header.magic==LANG_MAGIC)?_n("OK"):_n("NA"),
  944. header.size, header.size,
  945. header.count, header.count,
  946. header.checksum,
  947. header.code, header.code >> 8, header.code & 0xff,
  948. header.signature
  949. );
  950. #if 0
  951. xflash_rd_data(0x25ba, (uint8_t*)&block_buffer, 1024);
  952. for (uint16_t i = 0; i < 1024; i++)
  953. {
  954. if ((i % 16) == 0) printf_P(_n("%04x:"), 0x25ba+i);
  955. printf_P(_n(" %02x"), ((uint8_t*)&block_buffer)[i]);
  956. if ((i % 16) == 15) putchar('\n');
  957. }
  958. #endif
  959. uint16_t sum = 0;
  960. for (uint16_t i = 0; i < header.size; i++)
  961. sum += (uint16_t)pgm_read_byte((uint8_t*)(_SEC_LANG_TABLE + i)) << ((i & 1)?0:8);
  962. printf_P(_n("_SEC_LANG_TABLE checksum = %04x\n"), sum);
  963. sum -= header.checksum; //subtract checksum
  964. printf_P(_n("_SEC_LANG_TABLE checksum = %04x\n"), sum);
  965. sum = (sum >> 8) | ((sum & 0xff) << 8); //swap bytes
  966. if (sum == header.checksum)
  967. puts_P(_n("Checksum OK"));
  968. else
  969. puts_P(_n("Checksum NG"));
  970. }
  971. else
  972. puts_P(_n("lang_get_header failed!"));
  973. #if 0
  974. for (uint16_t i = 0; i < 1024*10; i++)
  975. {
  976. if ((i % 16) == 0) printf_P(_n("%04x:"), _SEC_LANG_TABLE+i);
  977. printf_P(_n(" %02x"), pgm_read_byte((uint8_t*)(_SEC_LANG_TABLE+i)));
  978. if ((i % 16) == 15) putchar('\n');
  979. }
  980. #endif
  981. #if 0
  982. SERIAL_ECHOLN("Reading eeprom from 0 to 100: start");
  983. for (int i = 0; i < 4096; ++i) {
  984. int b = eeprom_read_byte((unsigned char*)i);
  985. if (b != 255) {
  986. SERIAL_ECHO(i);
  987. SERIAL_ECHO(":");
  988. SERIAL_ECHO(b);
  989. SERIAL_ECHOLN("");
  990. }
  991. }
  992. SERIAL_ECHOLN("Reading eeprom from 0 to 100: done");
  993. #endif
  994. #endif //DEBUG_SEC_LANG
  995. // Check startup - does nothing if bootloader sets MCUSR to 0
  996. byte mcu = MCUSR;
  997. /* if (mcu & 1) SERIAL_ECHOLNRPGM(MSG_POWERUP);
  998. if (mcu & 2) SERIAL_ECHOLNRPGM(MSG_EXTERNAL_RESET);
  999. if (mcu & 4) SERIAL_ECHOLNRPGM(MSG_BROWNOUT_RESET);
  1000. if (mcu & 8) SERIAL_ECHOLNRPGM(MSG_WATCHDOG_RESET);
  1001. if (mcu & 32) SERIAL_ECHOLNRPGM(MSG_SOFTWARE_RESET);*/
  1002. if (mcu & 1) puts_P(MSG_POWERUP);
  1003. if (mcu & 2) puts_P(MSG_EXTERNAL_RESET);
  1004. if (mcu & 4) puts_P(MSG_BROWNOUT_RESET);
  1005. if (mcu & 8) puts_P(MSG_WATCHDOG_RESET);
  1006. if (mcu & 32) puts_P(MSG_SOFTWARE_RESET);
  1007. MCUSR = 0;
  1008. //SERIAL_ECHORPGM(MSG_MARLIN);
  1009. //SERIAL_ECHOLNRPGM(VERSION_STRING);
  1010. #ifdef STRING_VERSION_CONFIG_H
  1011. #ifdef STRING_CONFIG_H_AUTHOR
  1012. SERIAL_ECHO_START;
  1013. SERIAL_ECHORPGM(_n(" Last Updated: "));////MSG_CONFIGURATION_VER
  1014. SERIAL_ECHOPGM(STRING_VERSION_CONFIG_H);
  1015. SERIAL_ECHORPGM(_n(" | Author: "));////MSG_AUTHOR
  1016. SERIAL_ECHOLNPGM(STRING_CONFIG_H_AUTHOR);
  1017. SERIAL_ECHOPGM("Compiled: ");
  1018. SERIAL_ECHOLNPGM(__DATE__);
  1019. #endif
  1020. #endif
  1021. SERIAL_ECHO_START;
  1022. SERIAL_ECHORPGM(_n(" Free Memory: "));////MSG_FREE_MEMORY
  1023. SERIAL_ECHO(freeMemory());
  1024. SERIAL_ECHORPGM(_n(" PlannerBufferBytes: "));////MSG_PLANNER_BUFFER_BYTES
  1025. SERIAL_ECHOLN((int)sizeof(block_t)*BLOCK_BUFFER_SIZE);
  1026. //lcd_update_enable(false); // why do we need this?? - andre
  1027. // loads data from EEPROM if available else uses defaults (and resets step acceleration rate)
  1028. bool previous_settings_retrieved = false;
  1029. uint8_t hw_changed = check_printer_version();
  1030. 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
  1031. previous_settings_retrieved = Config_RetrieveSettings();
  1032. }
  1033. else { //printer version was changed so use default settings
  1034. Config_ResetDefault();
  1035. }
  1036. // writes a magic number at the end of static variables to monitor against incorrect overwriting
  1037. // of static memory by stack (this needs to be done before soft_pwm_init, since the check is
  1038. // performed inside the soft_pwm_isr)
  1039. SdFatUtil::set_stack_guard();
  1040. // Initialize pwm/temperature loops
  1041. soft_pwm_init();
  1042. temp_mgr_init();
  1043. #ifdef EXTRUDER_ALTFAN_DETECT
  1044. SERIAL_ECHORPGM(_n("Extruder fan type: "));
  1045. if (extruder_altfan_detect())
  1046. SERIAL_ECHOLNRPGM(PSTR("ALTFAN"));
  1047. else
  1048. SERIAL_ECHOLNRPGM(PSTR("NOCTUA"));
  1049. #endif //EXTRUDER_ALTFAN_DETECT
  1050. plan_init(); // Initialize planner;
  1051. factory_reset();
  1052. if (eeprom_read_dword((uint32_t*)(EEPROM_TOP - 4)) == 0x0ffffffff &&
  1053. eeprom_read_dword((uint32_t*)(EEPROM_TOP - 8)) == 0x0ffffffff)
  1054. {
  1055. // Maiden startup. The firmware has been loaded and first started on a virgin RAMBo board,
  1056. // where all the EEPROM entries are set to 0x0ff.
  1057. // Once a firmware boots up, it forces at least a language selection, which changes
  1058. // EEPROM_LANG to number lower than 0x0ff.
  1059. // 1) Set a high power mode.
  1060. eeprom_update_byte((uint8_t*)EEPROM_SILENT, SILENT_MODE_OFF);
  1061. #ifdef TMC2130
  1062. tmc2130_mode = TMC2130_MODE_NORMAL;
  1063. #endif //TMC2130
  1064. eeprom_write_byte((uint8_t*)EEPROM_WIZARD_ACTIVE, 1); //run wizard
  1065. }
  1066. lcd_encoder_diff=0;
  1067. #ifdef TMC2130
  1068. uint8_t silentMode = eeprom_read_byte((uint8_t*)EEPROM_SILENT);
  1069. if (silentMode == 0xff) silentMode = 0;
  1070. tmc2130_mode = TMC2130_MODE_NORMAL;
  1071. if (lcd_crash_detect_enabled() && !farm_mode)
  1072. {
  1073. lcd_crash_detect_enable();
  1074. puts_P(_N("CrashDetect ENABLED!"));
  1075. }
  1076. else
  1077. {
  1078. lcd_crash_detect_disable();
  1079. puts_P(_N("CrashDetect DISABLED"));
  1080. }
  1081. #ifdef TMC2130_LINEARITY_CORRECTION
  1082. #ifdef TMC2130_LINEARITY_CORRECTION_XYZ
  1083. tmc2130_wave_fac[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_X_FAC);
  1084. tmc2130_wave_fac[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_Y_FAC);
  1085. tmc2130_wave_fac[Z_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_Z_FAC);
  1086. #endif //TMC2130_LINEARITY_CORRECTION_XYZ
  1087. tmc2130_wave_fac[E_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_E_FAC);
  1088. if (tmc2130_wave_fac[X_AXIS] == 0xff) tmc2130_wave_fac[X_AXIS] = 0;
  1089. if (tmc2130_wave_fac[Y_AXIS] == 0xff) tmc2130_wave_fac[Y_AXIS] = 0;
  1090. if (tmc2130_wave_fac[Z_AXIS] == 0xff) tmc2130_wave_fac[Z_AXIS] = 0;
  1091. if (tmc2130_wave_fac[E_AXIS] == 0xff) tmc2130_wave_fac[E_AXIS] = 0;
  1092. #endif //TMC2130_LINEARITY_CORRECTION
  1093. #ifdef TMC2130_VARIABLE_RESOLUTION
  1094. tmc2130_mres[X_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[X_AXIS]);
  1095. tmc2130_mres[Y_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[Y_AXIS]);
  1096. tmc2130_mres[Z_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[Z_AXIS]);
  1097. tmc2130_mres[E_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[E_AXIS]);
  1098. #else //TMC2130_VARIABLE_RESOLUTION
  1099. tmc2130_mres[X_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_XY);
  1100. tmc2130_mres[Y_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_XY);
  1101. tmc2130_mres[Z_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_Z);
  1102. tmc2130_mres[E_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_E);
  1103. #endif //TMC2130_VARIABLE_RESOLUTION
  1104. #endif //TMC2130
  1105. st_init(); // Initialize stepper, this enables interrupts!
  1106. #ifdef TMC2130
  1107. tmc2130_mode = silentMode?TMC2130_MODE_SILENT:TMC2130_MODE_NORMAL;
  1108. update_mode_profile();
  1109. tmc2130_init(TMCInitParams(false, FarmOrUserECool() ));
  1110. #endif //TMC2130
  1111. #ifdef PSU_Delta
  1112. init_force_z(); // ! important for correct Z-axis initialization
  1113. #endif // PSU_Delta
  1114. setup_photpin();
  1115. #if 0
  1116. servo_init();
  1117. #endif
  1118. // Reset the machine correction matrix.
  1119. // It does not make sense to load the correction matrix until the machine is homed.
  1120. world2machine_reset();
  1121. // Initialize current_position accounting for software endstops to
  1122. // avoid unexpected initial shifts on the first move
  1123. clamp_to_software_endstops(current_position);
  1124. plan_set_position_curposXYZE();
  1125. // Show the xflash error message now that serial, lcd and encoder are available
  1126. if (!xflash_success)
  1127. xflash_err_msg();
  1128. #ifdef FILAMENT_SENSOR
  1129. fsensor.init();
  1130. #endif //FILAMENT_SENSOR
  1131. #if defined(CONTROLLERFAN_PIN) && (CONTROLLERFAN_PIN > -1)
  1132. SET_OUTPUT(CONTROLLERFAN_PIN); //Set pin used for driver cooling fan
  1133. #endif
  1134. setup_homepin();
  1135. #if defined(Z_AXIS_ALWAYS_ON)
  1136. enable_z();
  1137. #endif
  1138. // The farm monitoring SW may accidentally expect
  1139. // 2 messages of "printer started" to consider a printer working.
  1140. prusa_statistics(8);
  1141. // Enable Toshiba FlashAir SD card / WiFi enahanced card.
  1142. card.ToshibaFlashAir_enable(eeprom_read_byte((unsigned char*)EEPROM_TOSHIBA_FLASH_AIR_COMPATIBLITY) == 1);
  1143. // Force SD card update. Otherwise the SD card update is done from loop() on card.checkautostart(false),
  1144. // but this times out if a blocking dialog is shown in setup().
  1145. card.initsd();
  1146. #ifdef DEBUG_SD_SPEED_TEST
  1147. if (card.cardOK)
  1148. {
  1149. uint8_t* buff = (uint8_t*)block_buffer;
  1150. uint32_t block = 0;
  1151. uint32_t sumr = 0;
  1152. uint32_t sumw = 0;
  1153. for (int i = 0; i < 1024; i++)
  1154. {
  1155. uint32_t u = _micros();
  1156. bool res = card.card.readBlock(i, buff);
  1157. u = _micros() - u;
  1158. if (res)
  1159. {
  1160. printf_P(PSTR("readBlock %4d 512 bytes %lu us\n"), i, u);
  1161. sumr += u;
  1162. u = _micros();
  1163. res = card.card.writeBlock(i, buff);
  1164. u = _micros() - u;
  1165. if (res)
  1166. {
  1167. printf_P(PSTR("writeBlock %4d 512 bytes %lu us\n"), i, u);
  1168. sumw += u;
  1169. }
  1170. else
  1171. {
  1172. printf_P(PSTR("writeBlock %4d error\n"), i);
  1173. break;
  1174. }
  1175. }
  1176. else
  1177. {
  1178. printf_P(PSTR("readBlock %4d error\n"), i);
  1179. break;
  1180. }
  1181. }
  1182. uint32_t avg_rspeed = (1024 * 1000000) / (sumr / 512);
  1183. uint32_t avg_wspeed = (1024 * 1000000) / (sumw / 512);
  1184. printf_P(PSTR("avg read speed %lu bytes/s\n"), avg_rspeed);
  1185. printf_P(PSTR("avg write speed %lu bytes/s\n"), avg_wspeed);
  1186. }
  1187. else
  1188. printf_P(PSTR("Card NG!\n"));
  1189. #endif //DEBUG_SD_SPEED_TEST
  1190. eeprom_init();
  1191. // In the future, somewhere here would one compare the current firmware version against the firmware version stored in the EEPROM.
  1192. // If they differ, an update procedure may need to be performed. At the end of this block, the current firmware version
  1193. // is being written into the EEPROM, so the update procedure will be triggered only once.
  1194. #if (LANG_MODE != 0) //secondary language support
  1195. #ifdef DEBUG_XFLASH
  1196. XFLASH_SPI_ENTER();
  1197. uint8_t uid[8]; // 64bit unique id
  1198. xflash_rd_uid(uid);
  1199. puts_P(_n("XFLASH UID="));
  1200. for (uint8_t i = 0; i < 8; i ++)
  1201. printf_P(PSTR("%02x"), uid[i]);
  1202. putchar('\n');
  1203. list_sec_lang_from_external_flash();
  1204. #endif //DEBUG_XFLASH
  1205. // lang_reset();
  1206. if (!lang_select(eeprom_read_byte((uint8_t*)EEPROM_LANG)))
  1207. lcd_language();
  1208. #ifdef DEBUG_SEC_LANG
  1209. uint16_t sec_lang_code = lang_get_code(1);
  1210. uint16_t ui = _SEC_LANG_TABLE; //table pointer
  1211. 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);
  1212. lang_print_sec_lang(uartout);
  1213. #endif //DEBUG_SEC_LANG
  1214. #endif //(LANG_MODE != 0)
  1215. if (eeprom_read_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE) == 255) {
  1216. eeprom_write_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE, 0);
  1217. }
  1218. if (eeprom_read_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA) == 255) {
  1219. //eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0);
  1220. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  1221. int16_t z_shift = 0;
  1222. for (uint8_t i = 0; i < 5; i++) {
  1223. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  1224. }
  1225. eeprom_write_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE, 0);
  1226. }
  1227. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO) == 255) {
  1228. eeprom_write_byte((uint8_t*)EEPROM_UVLO, 0);
  1229. }
  1230. if (eeprom_read_byte((uint8_t*)EEPROM_SD_SORT) == 255) {
  1231. eeprom_write_byte((uint8_t*)EEPROM_SD_SORT, 0);
  1232. }
  1233. //mbl_mode_init();
  1234. mbl_settings_init();
  1235. SilentModeMenu_MMU = eeprom_read_byte((uint8_t*)EEPROM_MMU_STEALTH);
  1236. if (SilentModeMenu_MMU == 255) {
  1237. SilentModeMenu_MMU = 1;
  1238. eeprom_write_byte((uint8_t*)EEPROM_MMU_STEALTH, SilentModeMenu_MMU);
  1239. }
  1240. #if !defined(DEBUG_DISABLE_FANCHECK) && defined(FANCHECK) && defined(TACH_1) && TACH_1 >-1
  1241. setup_fan_interrupt();
  1242. #endif //DEBUG_DISABLE_FANCHECK
  1243. #ifndef DEBUG_DISABLE_STARTMSGS
  1244. KEEPALIVE_STATE(PAUSED_FOR_USER);
  1245. if (!farm_mode) {
  1246. #if defined(FILAMENT_SENSOR) && defined(FSENSOR_PROBING)
  1247. check_if_fw_is_on_right_printer();
  1248. #endif //defined(FILAMENT_SENSOR) && defined(FSENSOR_PROBING)
  1249. show_fw_version_warnings();
  1250. }
  1251. switch (hw_changed) {
  1252. //if motherboard or printer type was changed inform user as it can indicate flashing wrong firmware version
  1253. //if user confirms with knob, new hw version (printer and/or motherboard) is written to eeprom and message will be not shown next time
  1254. case(0b01):
  1255. lcd_show_fullscreen_message_and_wait_P(_i("Warning: motherboard type changed.")); ////MSG_CHANGED_MOTHERBOARD c=20 r=4
  1256. eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  1257. break;
  1258. case(0b10):
  1259. lcd_show_fullscreen_message_and_wait_P(_i("Warning: printer type changed.")); ////MSG_CHANGED_PRINTER c=20 r=4
  1260. eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  1261. break;
  1262. case(0b11):
  1263. lcd_show_fullscreen_message_and_wait_P(_i("Warning: both printer type and motherboard type changed.")); ////MSG_CHANGED_BOTH c=20 r=4
  1264. eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  1265. eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  1266. break;
  1267. default: break; //no change, show no message
  1268. }
  1269. if (!previous_settings_retrieved) {
  1270. 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
  1271. Config_StoreSettings();
  1272. }
  1273. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) >= 1) {
  1274. lcd_wizard(WizState::Run);
  1275. }
  1276. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) == 0) { //dont show calibration status messages if wizard is currently active
  1277. if (calibration_status() == CALIBRATION_STATUS_ASSEMBLED ||
  1278. calibration_status() == CALIBRATION_STATUS_UNKNOWN ||
  1279. calibration_status() == CALIBRATION_STATUS_XYZ_CALIBRATION) {
  1280. // Reset the babystepping values, so the printer will not move the Z axis up when the babystepping is enabled.
  1281. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  1282. // Show the message.
  1283. lcd_show_fullscreen_message_and_wait_P(_T(MSG_FOLLOW_CALIBRATION_FLOW));
  1284. }
  1285. else if (calibration_status() == CALIBRATION_STATUS_LIVE_ADJUST) {
  1286. // Show the message.
  1287. lcd_show_fullscreen_message_and_wait_P(_T(MSG_BABYSTEP_Z_NOT_SET));
  1288. lcd_update_enable(true);
  1289. }
  1290. else if (calibration_status() == CALIBRATION_STATUS_CALIBRATED && eeprom_read_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE) && calibration_status_pinda() == false) {
  1291. //lcd_show_fullscreen_message_and_wait_P(_i("Temperature calibration has not been run yet"));////MSG_PINDA_NOT_CALIBRATED c=20 r=4
  1292. lcd_update_enable(true);
  1293. }
  1294. else if (calibration_status() == CALIBRATION_STATUS_Z_CALIBRATION) {
  1295. // Show the message.
  1296. lcd_show_fullscreen_message_and_wait_P(_T(MSG_FOLLOW_Z_CALIBRATION_FLOW));
  1297. }
  1298. }
  1299. #if !defined (DEBUG_DISABLE_FORCE_SELFTEST) && defined (TMC2130)
  1300. if (force_selftest_if_fw_version() && calibration_status() < CALIBRATION_STATUS_ASSEMBLED) {
  1301. lcd_show_fullscreen_message_and_wait_P(_i("Selftest will be run to calibrate accurate sensorless rehoming."));////MSG_FORCE_SELFTEST c=20 r=8
  1302. update_current_firmware_version_to_eeprom();
  1303. lcd_selftest();
  1304. }
  1305. #endif //TMC2130 && !DEBUG_DISABLE_FORCE_SELFTEST
  1306. KEEPALIVE_STATE(IN_PROCESS);
  1307. #endif //DEBUG_DISABLE_STARTMSGS
  1308. lcd_update_enable(true);
  1309. lcd_clear();
  1310. lcd_update(2);
  1311. // Store the currently running firmware into an eeprom,
  1312. // so the next time the firmware gets updated, it will know from which version it has been updated.
  1313. update_current_firmware_version_to_eeprom();
  1314. #ifdef TMC2130
  1315. tmc2130_home_origin[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_X_ORIGIN);
  1316. tmc2130_home_bsteps[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_X_BSTEPS);
  1317. tmc2130_home_fsteps[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_X_FSTEPS);
  1318. if (tmc2130_home_origin[X_AXIS] == 0xff) tmc2130_home_origin[X_AXIS] = 0;
  1319. if (tmc2130_home_bsteps[X_AXIS] == 0xff) tmc2130_home_bsteps[X_AXIS] = 48;
  1320. if (tmc2130_home_fsteps[X_AXIS] == 0xff) tmc2130_home_fsteps[X_AXIS] = 48;
  1321. tmc2130_home_origin[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_ORIGIN);
  1322. tmc2130_home_bsteps[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_BSTEPS);
  1323. tmc2130_home_fsteps[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_FSTEPS);
  1324. if (tmc2130_home_origin[Y_AXIS] == 0xff) tmc2130_home_origin[Y_AXIS] = 0;
  1325. if (tmc2130_home_bsteps[Y_AXIS] == 0xff) tmc2130_home_bsteps[Y_AXIS] = 48;
  1326. if (tmc2130_home_fsteps[Y_AXIS] == 0xff) tmc2130_home_fsteps[Y_AXIS] = 48;
  1327. tmc2130_home_enabled = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_ENABLED);
  1328. if (tmc2130_home_enabled == 0xff) tmc2130_home_enabled = 0;
  1329. #endif //TMC2130
  1330. // report crash failures
  1331. fw_crash_init();
  1332. #ifdef UVLO_SUPPORT
  1333. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO) != 0) { //previous print was terminated by UVLO
  1334. /*
  1335. if (lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_RECOVER_PRINT), false)) recover_print();
  1336. else {
  1337. eeprom_update_byte((uint8_t*)EEPROM_UVLO, 0);
  1338. lcd_update_enable(true);
  1339. lcd_update(2);
  1340. lcd_setstatuspgm(MSG_WELCOME);
  1341. }
  1342. */
  1343. manage_heater(); // Update temperatures
  1344. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1345. 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));
  1346. #endif
  1347. if ( degBed() > ( (float)eeprom_read_byte((uint8_t*)EEPROM_UVLO_TARGET_BED) - AUTOMATIC_UVLO_BED_TEMP_OFFSET) ){
  1348. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1349. puts_P(_N("Automatic recovery!"));
  1350. #endif
  1351. recover_print(1);
  1352. }
  1353. else{
  1354. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1355. puts_P(_N("Normal recovery!"));
  1356. #endif
  1357. if ( lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_RECOVER_PRINT), false) ) recover_print(0);
  1358. else {
  1359. eeprom_update_byte((uint8_t*)EEPROM_UVLO, 0);
  1360. lcd_update_enable(true);
  1361. lcd_update(2);
  1362. lcd_setstatuspgm(MSG_WELCOME);
  1363. }
  1364. }
  1365. }
  1366. // Only arm the uvlo interrupt _after_ a recovering print has been initialized and
  1367. // the entire state machine initialized.
  1368. setup_uvlo_interrupt();
  1369. #endif //UVLO_SUPPORT
  1370. fCheckModeInit();
  1371. fSetMmuMode(MMU2::mmu2.Enabled());
  1372. KEEPALIVE_STATE(NOT_BUSY);
  1373. #ifdef WATCHDOG
  1374. wdt_enable(WDTO_4S);
  1375. #ifdef EMERGENCY_HANDLERS
  1376. WDTCSR |= (1 << WDIE);
  1377. #endif //EMERGENCY_HANDLERS
  1378. #endif //WATCHDOG
  1379. }
  1380. static inline void crash_and_burn(dump_crash_reason reason)
  1381. {
  1382. WRITE(BEEPER, HIGH);
  1383. eeprom_update_byte((uint8_t*)EEPROM_FW_CRASH_FLAG, (uint8_t)reason);
  1384. #ifdef EMERGENCY_DUMP
  1385. xfdump_full_dump_and_reset(reason);
  1386. #elif defined(EMERGENCY_SERIAL_DUMP)
  1387. if(emergency_serial_dump)
  1388. serial_dump_and_reset(reason);
  1389. #endif
  1390. softReset();
  1391. }
  1392. #ifdef EMERGENCY_HANDLERS
  1393. #ifdef WATCHDOG
  1394. ISR(WDT_vect)
  1395. {
  1396. crash_and_burn(dump_crash_reason::watchdog);
  1397. }
  1398. #endif
  1399. ISR(BADISR_vect)
  1400. {
  1401. crash_and_burn(dump_crash_reason::bad_isr);
  1402. }
  1403. #endif //EMERGENCY_HANDLERS
  1404. void stack_error() {
  1405. crash_and_burn(dump_crash_reason::stack_error);
  1406. }
  1407. /**
  1408. * Output autoreport values according to features requested in M155
  1409. */
  1410. #if defined(AUTO_REPORT)
  1411. void host_autoreport()
  1412. {
  1413. if (autoReportFeatures.TimerExpired())
  1414. {
  1415. if(autoReportFeatures.Temp()){
  1416. gcode_M105(active_extruder);
  1417. }
  1418. if(autoReportFeatures.Pos()){
  1419. gcode_M114();
  1420. }
  1421. #if defined(AUTO_REPORT) && (defined(FANCHECK) && (((defined(TACH_0) && (TACH_0 >-1)) || (defined(TACH_1) && (TACH_1 > -1)))))
  1422. if(autoReportFeatures.Fans()){
  1423. gcode_M123();
  1424. }
  1425. #endif //AUTO_REPORT and (FANCHECK and TACH_0 or TACH_1)
  1426. autoReportFeatures.TimerStart();
  1427. }
  1428. }
  1429. #endif //AUTO_REPORT
  1430. /**
  1431. * Output a "busy" message at regular intervals
  1432. * while the machine is not accepting commands.
  1433. */
  1434. void host_keepalive() {
  1435. #ifndef HOST_KEEPALIVE_FEATURE
  1436. return;
  1437. #endif //HOST_KEEPALIVE_FEATURE
  1438. if (farm_mode) return;
  1439. long ms = _millis();
  1440. if (host_keepalive_interval && busy_state != NOT_BUSY) {
  1441. if ((ms - prev_busy_signal_ms) < (long)(1000L * host_keepalive_interval)) return;
  1442. switch (busy_state) {
  1443. case IN_HANDLER:
  1444. case IN_PROCESS:
  1445. SERIAL_ECHO_START;
  1446. SERIAL_ECHOLNPGM("busy: processing");
  1447. break;
  1448. case PAUSED_FOR_USER:
  1449. SERIAL_ECHO_START;
  1450. SERIAL_ECHOLNPGM("busy: paused for user");
  1451. break;
  1452. case PAUSED_FOR_INPUT:
  1453. SERIAL_ECHO_START;
  1454. SERIAL_ECHOLNPGM("busy: paused for input");
  1455. break;
  1456. default:
  1457. break;
  1458. }
  1459. }
  1460. prev_busy_signal_ms = ms;
  1461. }
  1462. // The loop() function is called in an endless loop by the Arduino framework from the default main() routine.
  1463. // Before loop(), the setup() function is called by the main() routine.
  1464. void loop()
  1465. {
  1466. // Reset a previously aborted command, we can now start processing motion again
  1467. planner_aborted = false;
  1468. if(Stopped) {
  1469. // Currently Stopped (possibly due to an error) and not accepting new serial commands.
  1470. // Signal to the host that we're currently busy waiting for supervision.
  1471. KEEPALIVE_STATE(PAUSED_FOR_USER);
  1472. } else {
  1473. // Printer is available for processing, reset state
  1474. KEEPALIVE_STATE(NOT_BUSY);
  1475. }
  1476. if (isPrintPaused && saved_printing_type == PRINTING_TYPE_USB) { //keep believing that usb is being printed. Prevents accessing dangerous menus while pausing.
  1477. usb_timer.start();
  1478. }
  1479. else if (usb_timer.expired(10000)) { //just need to check if it expired. Nothing else is needed to be done.
  1480. ;
  1481. }
  1482. #ifdef PRUSA_M28
  1483. if (prusa_sd_card_upload)
  1484. {
  1485. //we read byte-by byte
  1486. serial_read_stream();
  1487. }
  1488. else
  1489. #endif
  1490. {
  1491. get_command();
  1492. #ifdef SDSUPPORT
  1493. card.checkautostart(false);
  1494. #endif
  1495. if(buflen)
  1496. {
  1497. cmdbuffer_front_already_processed = false;
  1498. #ifdef SDSUPPORT
  1499. if(card.saving)
  1500. {
  1501. // Saving a G-code file onto an SD-card is in progress.
  1502. // Saving starts with M28, saving until M29 is seen.
  1503. if(strstr_P(CMDBUFFER_CURRENT_STRING, PSTR("M29")) == NULL) {
  1504. card.write_command(CMDBUFFER_CURRENT_STRING);
  1505. if(card.logging)
  1506. process_commands();
  1507. else
  1508. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  1509. } else {
  1510. card.closefile();
  1511. SERIAL_PROTOCOLLNRPGM(MSG_FILE_SAVED);
  1512. }
  1513. } else {
  1514. process_commands();
  1515. }
  1516. #else
  1517. process_commands();
  1518. #endif //SDSUPPORT
  1519. if (! cmdbuffer_front_already_processed && buflen)
  1520. {
  1521. // ptr points to the start of the block currently being processed.
  1522. // The first character in the block is the block type.
  1523. char *ptr = cmdbuffer + bufindr;
  1524. if (*ptr == CMDBUFFER_CURRENT_TYPE_SDCARD) {
  1525. // To support power panic, move the lenght of the command on the SD card to a planner buffer.
  1526. union {
  1527. struct {
  1528. char lo;
  1529. char hi;
  1530. } lohi;
  1531. uint16_t value;
  1532. } sdlen;
  1533. sdlen.value = 0;
  1534. {
  1535. // This block locks the interrupts globally for 3.25 us,
  1536. // which corresponds to a maximum repeat frequency of 307.69 kHz.
  1537. // This blocking is safe in the context of a 10kHz stepper driver interrupt
  1538. // or a 115200 Bd serial line receive interrupt, which will not trigger faster than 12kHz.
  1539. cli();
  1540. // Reset the command to something, which will be ignored by the power panic routine,
  1541. // so this buffer length will not be counted twice.
  1542. *ptr ++ = CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED;
  1543. // Extract the current buffer length.
  1544. sdlen.lohi.lo = *ptr ++;
  1545. sdlen.lohi.hi = *ptr;
  1546. // and pass it to the planner queue.
  1547. planner_add_sd_length(sdlen.value);
  1548. sei();
  1549. }
  1550. }
  1551. else if((*ptr == CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR) && !IS_SD_PRINTING){
  1552. cli();
  1553. *ptr ++ = CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED;
  1554. // and one for each command to previous block in the planner queue.
  1555. planner_add_sd_length(1);
  1556. sei();
  1557. }
  1558. // Now it is safe to release the already processed command block. If interrupted by the power panic now,
  1559. // this block's SD card length will not be counted twice as its command type has been replaced
  1560. // by CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED.
  1561. cmdqueue_pop_front();
  1562. }
  1563. host_keepalive();
  1564. }
  1565. }
  1566. //check heater every n milliseconds
  1567. manage_heater();
  1568. manage_inactivity(isPrintPaused);
  1569. checkHitEndstops();
  1570. lcd_update(0);
  1571. #ifdef TMC2130
  1572. tmc2130_check_overtemp();
  1573. if (tmc2130_sg_crash)
  1574. {
  1575. uint8_t crash = tmc2130_sg_crash;
  1576. tmc2130_sg_crash = 0;
  1577. // crashdet_stop_and_save_print();
  1578. switch (crash)
  1579. {
  1580. case 1: enquecommand_P((PSTR("CRASH_DETECTEDX"))); break;
  1581. case 2: enquecommand_P((PSTR("CRASH_DETECTEDY"))); break;
  1582. case 3: enquecommand_P((PSTR("CRASH_DETECTEDXY"))); break;
  1583. }
  1584. }
  1585. #endif //TMC2130
  1586. MMU2::mmu2.mmu_loop();
  1587. }
  1588. #define DEFINE_PGM_READ_ANY(type, reader) \
  1589. static inline type pgm_read_any(const type *p) \
  1590. { return pgm_read_##reader##_near(p); }
  1591. DEFINE_PGM_READ_ANY(float, float);
  1592. DEFINE_PGM_READ_ANY(signed char, byte);
  1593. #define XYZ_CONSTS_FROM_CONFIG(type, array, CONFIG) \
  1594. static const PROGMEM type array##_P[3] = \
  1595. { X_##CONFIG, Y_##CONFIG, Z_##CONFIG }; \
  1596. static inline type array(uint8_t axis) \
  1597. { return pgm_read_any(&array##_P[axis]); } \
  1598. type array##_ext(uint8_t axis) \
  1599. { return pgm_read_any(&array##_P[axis]); }
  1600. XYZ_CONSTS_FROM_CONFIG(float, base_min_pos, MIN_POS);
  1601. XYZ_CONSTS_FROM_CONFIG(float, base_max_pos, MAX_POS);
  1602. XYZ_CONSTS_FROM_CONFIG(float, base_home_pos, HOME_POS);
  1603. XYZ_CONSTS_FROM_CONFIG(float, max_length, MAX_LENGTH);
  1604. XYZ_CONSTS_FROM_CONFIG(float, home_retract_mm, HOME_RETRACT_MM);
  1605. XYZ_CONSTS_FROM_CONFIG(signed char, home_dir, HOME_DIR);
  1606. static void axis_is_at_home(uint8_t axis) {
  1607. current_position[axis] = base_home_pos(axis) + cs.add_homing[axis];
  1608. min_pos[axis] = base_min_pos(axis) + cs.add_homing[axis];
  1609. max_pos[axis] = base_max_pos(axis) + cs.add_homing[axis];
  1610. }
  1611. //! @return original feedmultiply
  1612. static int setup_for_endstop_move(bool enable_endstops_now = true) {
  1613. saved_feedrate = feedrate;
  1614. int l_feedmultiply = feedmultiply;
  1615. feedmultiply = 100;
  1616. previous_millis_cmd.start();
  1617. enable_endstops(enable_endstops_now);
  1618. return l_feedmultiply;
  1619. }
  1620. //! @param original_feedmultiply feedmultiply to restore
  1621. static void clean_up_after_endstop_move(int original_feedmultiply) {
  1622. #ifdef ENDSTOPS_ONLY_FOR_HOMING
  1623. enable_endstops(false);
  1624. #endif
  1625. feedrate = saved_feedrate;
  1626. feedmultiply = original_feedmultiply;
  1627. previous_millis_cmd.start();
  1628. }
  1629. #ifdef ENABLE_AUTO_BED_LEVELING
  1630. #ifdef AUTO_BED_LEVELING_GRID
  1631. static void set_bed_level_equation_lsq(double *plane_equation_coefficients)
  1632. {
  1633. vector_3 planeNormal = vector_3(-plane_equation_coefficients[0], -plane_equation_coefficients[1], 1);
  1634. planeNormal.debug("planeNormal");
  1635. plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1636. //bedLevel.debug("bedLevel");
  1637. //plan_bed_level_matrix.debug("bed level before");
  1638. //vector_3 uncorrected_position = plan_get_position_mm();
  1639. //uncorrected_position.debug("position before");
  1640. vector_3 corrected_position = plan_get_position();
  1641. // corrected_position.debug("position after");
  1642. current_position[X_AXIS] = corrected_position.x;
  1643. current_position[Y_AXIS] = corrected_position.y;
  1644. current_position[Z_AXIS] = corrected_position.z;
  1645. // put the bed at 0 so we don't go below it.
  1646. current_position[Z_AXIS] = cs.zprobe_zoffset; // in the lsq we reach here after raising the extruder due to the loop structure
  1647. plan_set_position_curposXYZE();
  1648. }
  1649. #else // not AUTO_BED_LEVELING_GRID
  1650. static void set_bed_level_equation_3pts(float z_at_pt_1, float z_at_pt_2, float z_at_pt_3) {
  1651. plan_bed_level_matrix.set_to_identity();
  1652. vector_3 pt1 = vector_3(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, z_at_pt_1);
  1653. vector_3 pt2 = vector_3(ABL_PROBE_PT_2_X, ABL_PROBE_PT_2_Y, z_at_pt_2);
  1654. vector_3 pt3 = vector_3(ABL_PROBE_PT_3_X, ABL_PROBE_PT_3_Y, z_at_pt_3);
  1655. vector_3 from_2_to_1 = (pt1 - pt2).get_normal();
  1656. vector_3 from_2_to_3 = (pt3 - pt2).get_normal();
  1657. vector_3 planeNormal = vector_3::cross(from_2_to_1, from_2_to_3).get_normal();
  1658. planeNormal = vector_3(planeNormal.x, planeNormal.y, abs(planeNormal.z));
  1659. plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1660. vector_3 corrected_position = plan_get_position();
  1661. current_position[X_AXIS] = corrected_position.x;
  1662. current_position[Y_AXIS] = corrected_position.y;
  1663. current_position[Z_AXIS] = corrected_position.z;
  1664. // put the bed at 0 so we don't go below it.
  1665. current_position[Z_AXIS] = cs.zprobe_zoffset;
  1666. plan_set_position_curposXYZE();
  1667. }
  1668. #endif // AUTO_BED_LEVELING_GRID
  1669. static void run_z_probe() {
  1670. plan_bed_level_matrix.set_to_identity();
  1671. feedrate = homing_feedrate[Z_AXIS];
  1672. // move down until you find the bed
  1673. float zPosition = -10;
  1674. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1675. st_synchronize();
  1676. // we have to let the planner know where we are right now as it is not where we said to go.
  1677. zPosition = st_get_position_mm(Z_AXIS);
  1678. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS]);
  1679. // move up the retract distance
  1680. zPosition += home_retract_mm(Z_AXIS);
  1681. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1682. st_synchronize();
  1683. // move back down slowly to find bed
  1684. feedrate = homing_feedrate[Z_AXIS]/4;
  1685. zPosition -= home_retract_mm(Z_AXIS) * 2;
  1686. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1687. st_synchronize();
  1688. current_position[Z_AXIS] = st_get_position_mm(Z_AXIS);
  1689. // make sure the planner knows where we are as it may be a bit different than we last said to move to
  1690. plan_set_position_curposXYZE();
  1691. }
  1692. static void do_blocking_move_to(float x, float y, float z) {
  1693. float oldFeedRate = feedrate;
  1694. feedrate = homing_feedrate[Z_AXIS];
  1695. current_position[Z_AXIS] = z;
  1696. plan_buffer_line_curposXYZE(feedrate/60, active_extruder);
  1697. st_synchronize();
  1698. feedrate = XY_TRAVEL_SPEED;
  1699. current_position[X_AXIS] = x;
  1700. current_position[Y_AXIS] = y;
  1701. plan_buffer_line_curposXYZE(feedrate/60, active_extruder);
  1702. st_synchronize();
  1703. feedrate = oldFeedRate;
  1704. }
  1705. static void do_blocking_move_relative(float offset_x, float offset_y, float offset_z) {
  1706. do_blocking_move_to(current_position[X_AXIS] + offset_x, current_position[Y_AXIS] + offset_y, current_position[Z_AXIS] + offset_z);
  1707. }
  1708. /// Probe bed height at position (x,y), returns the measured z value
  1709. static float probe_pt(float x, float y, float z_before) {
  1710. // move to right place
  1711. do_blocking_move_to(current_position[X_AXIS], current_position[Y_AXIS], z_before);
  1712. do_blocking_move_to(x - X_PROBE_OFFSET_FROM_EXTRUDER, y - Y_PROBE_OFFSET_FROM_EXTRUDER, current_position[Z_AXIS]);
  1713. run_z_probe();
  1714. float measured_z = current_position[Z_AXIS];
  1715. SERIAL_PROTOCOLRPGM(_T(MSG_BED));
  1716. SERIAL_PROTOCOLPGM(" x: ");
  1717. SERIAL_PROTOCOL(x);
  1718. SERIAL_PROTOCOLPGM(" y: ");
  1719. SERIAL_PROTOCOL(y);
  1720. SERIAL_PROTOCOLPGM(" z: ");
  1721. SERIAL_PROTOCOL(measured_z);
  1722. SERIAL_PROTOCOLPGM("\n");
  1723. return measured_z;
  1724. }
  1725. #endif // #ifdef ENABLE_AUTO_BED_LEVELING
  1726. #ifdef LIN_ADVANCE
  1727. /**
  1728. * M900: Set and/or Get advance K factor
  1729. *
  1730. * K<factor> Set advance K factor
  1731. */
  1732. inline void gcode_M900() {
  1733. float newK = code_seen('K') ? code_value_float() : -2;
  1734. #ifdef LA_NOCOMPAT
  1735. if (newK >= 0 && newK < LA_K_MAX)
  1736. extruder_advance_K = newK;
  1737. else
  1738. SERIAL_ECHOLNPGM("K out of allowed range!");
  1739. #else
  1740. if (newK == 0)
  1741. {
  1742. extruder_advance_K = 0;
  1743. la10c_reset();
  1744. }
  1745. else
  1746. {
  1747. newK = la10c_value(newK);
  1748. if (newK < 0)
  1749. SERIAL_ECHOLNPGM("K out of allowed range!");
  1750. else
  1751. extruder_advance_K = newK;
  1752. }
  1753. #endif
  1754. SERIAL_ECHO_START;
  1755. SERIAL_ECHOPGM("Advance K=");
  1756. SERIAL_ECHOLN(extruder_advance_K);
  1757. }
  1758. #endif // LIN_ADVANCE
  1759. bool check_commands() {
  1760. bool end_command_found = false;
  1761. while (buflen)
  1762. {
  1763. if ((code_seen_P(PSTR("M84"))) || (code_seen_P(PSTR("M 84")))) end_command_found = true;
  1764. if (!cmdbuffer_front_already_processed)
  1765. cmdqueue_pop_front();
  1766. cmdbuffer_front_already_processed = false;
  1767. }
  1768. return end_command_found;
  1769. }
  1770. // raise_z_above: slowly raise Z to the requested height
  1771. //
  1772. // contrarily to a simple move, this function will carefully plan a move
  1773. // when the current Z position is unknown. In such cases, stallguard is
  1774. // enabled and will prevent prolonged pushing against the Z tops
  1775. void raise_z_above(float target, bool plan)
  1776. {
  1777. if (current_position[Z_AXIS] >= target)
  1778. return;
  1779. // Z needs raising
  1780. current_position[Z_AXIS] = target;
  1781. clamp_to_software_endstops(current_position);
  1782. #if defined(Z_MIN_PIN) && (Z_MIN_PIN > -1) && !defined(DEBUG_DISABLE_ZMINLIMIT)
  1783. bool z_min_endstop = (READ(Z_MIN_PIN) != Z_MIN_ENDSTOP_INVERTING);
  1784. #else
  1785. bool z_min_endstop = false;
  1786. #endif
  1787. if (axis_known_position[Z_AXIS] || z_min_endstop)
  1788. {
  1789. // current position is known or very low, it's safe to raise Z
  1790. if(plan) plan_buffer_line_curposXYZE(max_feedrate[Z_AXIS]);
  1791. return;
  1792. }
  1793. // ensure Z is powered in normal mode to overcome initial load
  1794. enable_z();
  1795. st_synchronize();
  1796. // rely on crashguard to limit damage
  1797. bool z_endstop_enabled = enable_z_endstop(true);
  1798. #ifdef TMC2130
  1799. tmc2130_home_enter(Z_AXIS_MASK);
  1800. #endif //TMC2130
  1801. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 60);
  1802. st_synchronize();
  1803. #ifdef TMC2130
  1804. if (endstop_z_hit_on_purpose())
  1805. {
  1806. // not necessarily exact, but will avoid further vertical moves
  1807. current_position[Z_AXIS] = max_pos[Z_AXIS];
  1808. plan_set_position_curposXYZE();
  1809. }
  1810. tmc2130_home_exit();
  1811. #endif //TMC2130
  1812. enable_z_endstop(z_endstop_enabled);
  1813. }
  1814. #ifdef TMC2130
  1815. bool calibrate_z_auto()
  1816. {
  1817. //lcd_display_message_fullscreen_P(_T(MSG_CALIBRATE_Z_AUTO));
  1818. lcd_clear();
  1819. lcd_puts_at_P(0, 1, _T(MSG_CALIBRATE_Z_AUTO));
  1820. bool endstops_enabled = enable_endstops(true);
  1821. int axis_up_dir = -home_dir(Z_AXIS);
  1822. tmc2130_home_enter(Z_AXIS_MASK);
  1823. current_position[Z_AXIS] = 0;
  1824. plan_set_position_curposXYZE();
  1825. set_destination_to_current();
  1826. destination[Z_AXIS] += (1.1 * max_length(Z_AXIS) * axis_up_dir);
  1827. feedrate = homing_feedrate[Z_AXIS];
  1828. plan_buffer_line_destinationXYZE(feedrate / 60);
  1829. st_synchronize();
  1830. // current_position[axis] = 0;
  1831. // plan_set_position_curposXYZE();
  1832. tmc2130_home_exit();
  1833. enable_endstops(false);
  1834. current_position[Z_AXIS] = 0;
  1835. plan_set_position_curposXYZE();
  1836. set_destination_to_current();
  1837. destination[Z_AXIS] += 10 * axis_up_dir; //10mm up
  1838. feedrate = homing_feedrate[Z_AXIS] / 2;
  1839. plan_buffer_line_destinationXYZE(feedrate / 60);
  1840. st_synchronize();
  1841. enable_endstops(endstops_enabled);
  1842. if (PRINTER_TYPE == PRINTER_MK3) {
  1843. current_position[Z_AXIS] = Z_MAX_POS + 2.0;
  1844. }
  1845. else {
  1846. current_position[Z_AXIS] = Z_MAX_POS + 9.0;
  1847. }
  1848. plan_set_position_curposXYZE();
  1849. return true;
  1850. }
  1851. #endif //TMC2130
  1852. #ifdef TMC2130
  1853. static void check_Z_crash(void)
  1854. {
  1855. if (!READ(Z_TMC2130_DIAG)) { //Z crash
  1856. FORCE_HIGH_POWER_END;
  1857. current_position[Z_AXIS] = 0;
  1858. plan_set_position_curposXYZE();
  1859. current_position[Z_AXIS] += MESH_HOME_Z_SEARCH;
  1860. plan_buffer_line_curposXYZE(max_feedrate[Z_AXIS]);
  1861. st_synchronize();
  1862. kill(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  1863. }
  1864. }
  1865. #endif //TMC2130
  1866. #ifdef TMC2130
  1867. void homeaxis(uint8_t axis, uint8_t cnt, uint8_t* pstep)
  1868. #else
  1869. void homeaxis(uint8_t axis, uint8_t cnt)
  1870. #endif //TMC2130
  1871. {
  1872. bool endstops_enabled = enable_endstops(true); //RP: endstops should be allways enabled durring homing
  1873. #define HOMEAXIS_DO(LETTER) \
  1874. ((LETTER##_MIN_PIN > -1 && LETTER##_HOME_DIR==-1) || (LETTER##_MAX_PIN > -1 && LETTER##_HOME_DIR==1))
  1875. if ((axis==X_AXIS)?HOMEAXIS_DO(X):(axis==Y_AXIS)?HOMEAXIS_DO(Y):0)
  1876. {
  1877. int axis_home_dir = home_dir(axis);
  1878. feedrate = homing_feedrate[axis];
  1879. #ifdef TMC2130
  1880. tmc2130_home_enter(X_AXIS_MASK << axis);
  1881. #endif //TMC2130
  1882. // Move away a bit, so that the print head does not touch the end position,
  1883. // and the following movement to endstop has a chance to achieve the required velocity
  1884. // for the stall guard to work.
  1885. current_position[axis] = 0;
  1886. plan_set_position_curposXYZE();
  1887. set_destination_to_current();
  1888. // destination[axis] = 11.f;
  1889. destination[axis] = -3.f * axis_home_dir;
  1890. plan_buffer_line_destinationXYZE(feedrate/60);
  1891. st_synchronize();
  1892. // Move away from the possible collision with opposite endstop with the collision detection disabled.
  1893. endstops_hit_on_purpose();
  1894. enable_endstops(false);
  1895. current_position[axis] = 0;
  1896. plan_set_position_curposXYZE();
  1897. destination[axis] = 1. * axis_home_dir;
  1898. plan_buffer_line_destinationXYZE(feedrate/60);
  1899. st_synchronize();
  1900. // Now continue to move up to the left end stop with the collision detection enabled.
  1901. enable_endstops(true);
  1902. destination[axis] = 1.1 * axis_home_dir * max_length(axis);
  1903. plan_buffer_line_destinationXYZE(feedrate/60);
  1904. st_synchronize();
  1905. for (uint8_t i = 0; i < cnt; i++)
  1906. {
  1907. // Move away from the collision to a known distance from the left end stop with the collision detection disabled.
  1908. endstops_hit_on_purpose();
  1909. enable_endstops(false);
  1910. current_position[axis] = 0;
  1911. plan_set_position_curposXYZE();
  1912. destination[axis] = -10.f * axis_home_dir;
  1913. plan_buffer_line_destinationXYZE(feedrate/60);
  1914. st_synchronize();
  1915. endstops_hit_on_purpose();
  1916. // Now move left up to the collision, this time with a repeatable velocity.
  1917. enable_endstops(true);
  1918. destination[axis] = 11.f * axis_home_dir;
  1919. #ifdef TMC2130
  1920. feedrate = homing_feedrate[axis];
  1921. #else //TMC2130
  1922. feedrate = homing_feedrate[axis] / 2;
  1923. #endif //TMC2130
  1924. plan_buffer_line_destinationXYZE(feedrate/60);
  1925. st_synchronize();
  1926. #ifdef TMC2130
  1927. uint16_t mscnt = tmc2130_rd_MSCNT(axis);
  1928. if (pstep) pstep[i] = mscnt >> 4;
  1929. printf_P(PSTR("%3d step=%2d mscnt=%4d\n"), i, mscnt >> 4, mscnt);
  1930. #endif //TMC2130
  1931. }
  1932. endstops_hit_on_purpose();
  1933. enable_endstops(false);
  1934. #ifdef TMC2130
  1935. uint8_t orig = tmc2130_home_origin[axis];
  1936. uint8_t back = tmc2130_home_bsteps[axis];
  1937. if (tmc2130_home_enabled && (orig <= 63))
  1938. {
  1939. tmc2130_goto_step(axis, orig, 2, 1000, tmc2130_get_res(axis));
  1940. if (back > 0)
  1941. tmc2130_do_steps(axis, back, -axis_home_dir, 1000);
  1942. }
  1943. else
  1944. tmc2130_do_steps(axis, 8, -axis_home_dir, 1000);
  1945. tmc2130_home_exit();
  1946. #endif //TMC2130
  1947. axis_is_at_home(axis);
  1948. axis_known_position[axis] = true;
  1949. // Move from minimum
  1950. #ifdef TMC2130
  1951. float dist = - axis_home_dir * 0.01f * tmc2130_home_fsteps[axis];
  1952. #else //TMC2130
  1953. float dist = - axis_home_dir * 0.01f * 64;
  1954. #endif //TMC2130
  1955. current_position[axis] -= dist;
  1956. plan_set_position_curposXYZE();
  1957. current_position[axis] += dist;
  1958. destination[axis] = current_position[axis];
  1959. plan_buffer_line_destinationXYZE(0.5f*feedrate/60);
  1960. st_synchronize();
  1961. feedrate = 0.0;
  1962. }
  1963. else if ((axis==Z_AXIS)?HOMEAXIS_DO(Z):0)
  1964. {
  1965. #ifdef TMC2130
  1966. FORCE_HIGH_POWER_START;
  1967. #endif
  1968. int axis_home_dir = home_dir(axis);
  1969. current_position[axis] = 0;
  1970. plan_set_position_curposXYZE();
  1971. destination[axis] = 1.5 * max_length(axis) * axis_home_dir;
  1972. feedrate = homing_feedrate[axis];
  1973. plan_buffer_line_destinationXYZE(feedrate/60);
  1974. st_synchronize();
  1975. #ifdef TMC2130
  1976. check_Z_crash();
  1977. #endif //TMC2130
  1978. current_position[axis] = 0;
  1979. plan_set_position_curposXYZE();
  1980. destination[axis] = -home_retract_mm(axis) * axis_home_dir;
  1981. plan_buffer_line_destinationXYZE(feedrate/60);
  1982. st_synchronize();
  1983. destination[axis] = 2*home_retract_mm(axis) * axis_home_dir;
  1984. feedrate = homing_feedrate[axis]/2 ;
  1985. plan_buffer_line_destinationXYZE(feedrate/60);
  1986. st_synchronize();
  1987. #ifdef TMC2130
  1988. check_Z_crash();
  1989. #endif //TMC2130
  1990. axis_is_at_home(axis);
  1991. destination[axis] = current_position[axis];
  1992. feedrate = 0.0;
  1993. endstops_hit_on_purpose();
  1994. axis_known_position[axis] = true;
  1995. #ifdef TMC2130
  1996. FORCE_HIGH_POWER_END;
  1997. #endif
  1998. }
  1999. enable_endstops(endstops_enabled);
  2000. }
  2001. /**/
  2002. void home_xy()
  2003. {
  2004. set_destination_to_current();
  2005. homeaxis(X_AXIS);
  2006. homeaxis(Y_AXIS);
  2007. plan_set_position_curposXYZE();
  2008. endstops_hit_on_purpose();
  2009. }
  2010. void refresh_cmd_timeout(void)
  2011. {
  2012. previous_millis_cmd.start();
  2013. }
  2014. #ifdef FWRETRACT
  2015. void retract(bool retracting, bool swapretract = false) {
  2016. // Perform FW retraction, just if needed, but behave as if the move has never took place in
  2017. // order to keep E/Z coordinates unchanged. This is done by manipulating the internal planner
  2018. // position, which requires a sync
  2019. if(retracting && !retracted[active_extruder]) {
  2020. st_synchronize();
  2021. set_destination_to_current();
  2022. current_position[E_AXIS]+=(swapretract?retract_length_swap:cs.retract_length)*float(extrudemultiply)*0.01f;
  2023. plan_set_e_position(current_position[E_AXIS]);
  2024. float oldFeedrate = feedrate;
  2025. feedrate=cs.retract_feedrate*60;
  2026. retracted[active_extruder]=true;
  2027. prepare_move();
  2028. if(cs.retract_zlift) {
  2029. st_synchronize();
  2030. current_position[Z_AXIS]-=cs.retract_zlift;
  2031. plan_set_position_curposXYZE();
  2032. prepare_move();
  2033. }
  2034. feedrate = oldFeedrate;
  2035. } else if(!retracting && retracted[active_extruder]) {
  2036. st_synchronize();
  2037. set_destination_to_current();
  2038. float oldFeedrate = feedrate;
  2039. feedrate=cs.retract_recover_feedrate*60;
  2040. if(cs.retract_zlift) {
  2041. current_position[Z_AXIS]+=cs.retract_zlift;
  2042. plan_set_position_curposXYZE();
  2043. prepare_move();
  2044. st_synchronize();
  2045. }
  2046. current_position[E_AXIS]-=(swapretract?(retract_length_swap+retract_recover_length_swap):(cs.retract_length+cs.retract_recover_length))*float(extrudemultiply)*0.01f;
  2047. plan_set_e_position(current_position[E_AXIS]);
  2048. retracted[active_extruder]=false;
  2049. prepare_move();
  2050. feedrate = oldFeedrate;
  2051. }
  2052. } //retract
  2053. #endif //FWRETRACT
  2054. #ifdef TMC2130
  2055. void force_high_power_mode(bool start_high_power_section) {
  2056. #ifdef PSU_Delta
  2057. if (start_high_power_section == true) enable_force_z();
  2058. #endif //PSU_Delta
  2059. uint8_t silent;
  2060. silent = eeprom_read_byte((uint8_t*)EEPROM_SILENT);
  2061. if (silent == 1) {
  2062. //we are in silent mode, set to normal mode to enable crash detection
  2063. // Wait for the planner queue to drain and for the stepper timer routine to reach an idle state.
  2064. st_synchronize();
  2065. cli();
  2066. tmc2130_mode = (start_high_power_section == true) ? TMC2130_MODE_NORMAL : TMC2130_MODE_SILENT;
  2067. update_mode_profile();
  2068. tmc2130_init(TMCInitParams(FarmOrUserECool()));
  2069. // We may have missed a stepper timer interrupt due to the time spent in the tmc2130_init() routine.
  2070. // Be safe than sorry, reset the stepper timer before re-enabling interrupts.
  2071. st_reset_timer();
  2072. sei();
  2073. }
  2074. }
  2075. #endif //TMC2130
  2076. void gcode_M105(uint8_t extruder)
  2077. {
  2078. #if defined(TEMP_0_PIN) && TEMP_0_PIN > -1
  2079. SERIAL_PROTOCOLPGM("T:");
  2080. SERIAL_PROTOCOL_F(degHotend(extruder),1);
  2081. SERIAL_PROTOCOLPGM(" /");
  2082. SERIAL_PROTOCOL_F(degTargetHotend(extruder),1);
  2083. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  2084. SERIAL_PROTOCOLPGM(" B:");
  2085. SERIAL_PROTOCOL_F(degBed(),1);
  2086. SERIAL_PROTOCOLPGM(" /");
  2087. SERIAL_PROTOCOL_F(degTargetBed(),1);
  2088. #endif //TEMP_BED_PIN
  2089. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  2090. SERIAL_PROTOCOLPGM(" T");
  2091. SERIAL_PROTOCOL(cur_extruder);
  2092. SERIAL_PROTOCOL(':');
  2093. SERIAL_PROTOCOL_F(degHotend(cur_extruder),1);
  2094. SERIAL_PROTOCOLPGM(" /");
  2095. SERIAL_PROTOCOL_F(degTargetHotend(cur_extruder),1);
  2096. }
  2097. #else
  2098. SERIAL_ERROR_START;
  2099. SERIAL_ERRORLNRPGM(_n("No thermistors - no temperature"));////MSG_ERR_NO_THERMISTORS
  2100. #endif
  2101. SERIAL_PROTOCOLPGM(" @:");
  2102. #ifdef EXTRUDER_WATTS
  2103. SERIAL_PROTOCOL((EXTRUDER_WATTS * getHeaterPower(tmp_extruder))/127);
  2104. SERIAL_PROTOCOLPGM("W");
  2105. #else
  2106. SERIAL_PROTOCOL(getHeaterPower(extruder));
  2107. #endif
  2108. SERIAL_PROTOCOLPGM(" B@:");
  2109. #ifdef BED_WATTS
  2110. SERIAL_PROTOCOL((BED_WATTS * getHeaterPower(-1))/127);
  2111. SERIAL_PROTOCOLPGM("W");
  2112. #else
  2113. SERIAL_PROTOCOL(getHeaterPower(-1));
  2114. #endif
  2115. #ifdef PINDA_THERMISTOR
  2116. SERIAL_PROTOCOLPGM(" P:");
  2117. SERIAL_PROTOCOL_F(current_temperature_pinda,1);
  2118. #endif //PINDA_THERMISTOR
  2119. #ifdef AMBIENT_THERMISTOR
  2120. SERIAL_PROTOCOLPGM(" A:");
  2121. SERIAL_PROTOCOL_F(current_temperature_ambient,1);
  2122. #endif //AMBIENT_THERMISTOR
  2123. #ifdef SHOW_TEMP_ADC_VALUES
  2124. {
  2125. float raw = 0.0;
  2126. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  2127. SERIAL_PROTOCOLPGM(" ADC B:");
  2128. SERIAL_PROTOCOL_F(degBed(),1);
  2129. SERIAL_PROTOCOLPGM("C->");
  2130. raw = rawBedTemp();
  2131. SERIAL_PROTOCOL_F(raw/OVERSAMPLENR,5);
  2132. SERIAL_PROTOCOLPGM(" Rb->");
  2133. SERIAL_PROTOCOL_F(100 * (1 + (PtA * (raw/OVERSAMPLENR)) + (PtB * sq((raw/OVERSAMPLENR)))), 5);
  2134. SERIAL_PROTOCOLPGM(" Rxb->");
  2135. SERIAL_PROTOCOL_F(raw, 5);
  2136. #endif
  2137. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  2138. SERIAL_PROTOCOLPGM(" T");
  2139. SERIAL_PROTOCOL(cur_extruder);
  2140. SERIAL_PROTOCOLPGM(":");
  2141. SERIAL_PROTOCOL_F(degHotend(cur_extruder),1);
  2142. SERIAL_PROTOCOLPGM("C->");
  2143. raw = rawHotendTemp(cur_extruder);
  2144. SERIAL_PROTOCOL_F(raw/OVERSAMPLENR,5);
  2145. SERIAL_PROTOCOLPGM(" Rt");
  2146. SERIAL_PROTOCOL(cur_extruder);
  2147. SERIAL_PROTOCOLPGM("->");
  2148. SERIAL_PROTOCOL_F(100 * (1 + (PtA * (raw/OVERSAMPLENR)) + (PtB * sq((raw/OVERSAMPLENR)))), 5);
  2149. SERIAL_PROTOCOLPGM(" Rx");
  2150. SERIAL_PROTOCOL(cur_extruder);
  2151. SERIAL_PROTOCOLPGM("->");
  2152. SERIAL_PROTOCOL_F(raw, 5);
  2153. }
  2154. }
  2155. #endif
  2156. SERIAL_PROTOCOLLN();
  2157. }
  2158. #ifdef TMC2130
  2159. 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)
  2160. #else
  2161. 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)
  2162. #endif //TMC2130
  2163. {
  2164. // Flag for the display update routine and to disable the print cancelation during homing.
  2165. st_synchronize();
  2166. homing_flag = true;
  2167. #if 0
  2168. SERIAL_ECHOPGM("G28, initial "); print_world_coordinates();
  2169. SERIAL_ECHOPGM("G28, initial "); print_physical_coordinates();
  2170. #endif
  2171. // Which axes should be homed?
  2172. bool home_x = home_x_axis;
  2173. bool home_y = home_y_axis;
  2174. bool home_z = home_z_axis;
  2175. // Either all X,Y,Z codes are present, or none of them.
  2176. bool home_all_axes = home_x == home_y && home_x == home_z;
  2177. if (home_all_axes)
  2178. // No X/Y/Z code provided means to home all axes.
  2179. home_x = home_y = home_z = true;
  2180. //if we are homing all axes, first move z higher to protect heatbed/steel sheet
  2181. if (home_all_axes) {
  2182. raise_z_above(MESH_HOME_Z_SEARCH);
  2183. st_synchronize();
  2184. }
  2185. #ifdef ENABLE_AUTO_BED_LEVELING
  2186. plan_bed_level_matrix.set_to_identity(); //Reset the plane ("erase" all leveling data)
  2187. #endif //ENABLE_AUTO_BED_LEVELING
  2188. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  2189. // the planner will not perform any adjustments in the XY plane.
  2190. // Wait for the motors to stop and update the current position with the absolute values.
  2191. world2machine_revert_to_uncorrected();
  2192. // For mesh bed leveling deactivate the matrix temporarily.
  2193. // It is necessary to disable the bed leveling for the X and Y homing moves, so that the move is performed
  2194. // in a single axis only.
  2195. // In case of re-homing the X or Y axes only, the mesh bed leveling is restored after G28.
  2196. #ifdef MESH_BED_LEVELING
  2197. uint8_t mbl_was_active = mbl.active;
  2198. mbl.active = 0;
  2199. current_position[Z_AXIS] = st_get_position_mm(Z_AXIS);
  2200. #endif
  2201. // Reset baby stepping to zero, if the babystepping has already been loaded before.
  2202. if (home_z)
  2203. babystep_undo();
  2204. int l_feedmultiply = setup_for_endstop_move();
  2205. set_destination_to_current();
  2206. feedrate = 0.0;
  2207. #if Z_HOME_DIR > 0 // If homing away from BED do Z first
  2208. if(home_z)
  2209. homeaxis(Z_AXIS);
  2210. #endif
  2211. #ifdef QUICK_HOME
  2212. // In the quick mode, if both x and y are to be homed, a diagonal move will be performed initially.
  2213. if(home_x && home_y) //first diagonal move
  2214. {
  2215. current_position[X_AXIS] = 0;current_position[Y_AXIS] = 0;
  2216. uint8_t x_axis_home_dir = home_dir(X_AXIS);
  2217. plan_set_position_curposXYZE();
  2218. 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);
  2219. feedrate = homing_feedrate[X_AXIS];
  2220. if(homing_feedrate[Y_AXIS]<feedrate)
  2221. feedrate = homing_feedrate[Y_AXIS];
  2222. if (max_length(X_AXIS) > max_length(Y_AXIS)) {
  2223. feedrate *= sqrt(pow(max_length(Y_AXIS) / max_length(X_AXIS), 2) + 1);
  2224. } else {
  2225. feedrate *= sqrt(pow(max_length(X_AXIS) / max_length(Y_AXIS), 2) + 1);
  2226. }
  2227. plan_buffer_line_destinationXYZE(feedrate/60);
  2228. st_synchronize();
  2229. axis_is_at_home(X_AXIS);
  2230. axis_is_at_home(Y_AXIS);
  2231. plan_set_position_curposXYZE();
  2232. destination[X_AXIS] = current_position[X_AXIS];
  2233. destination[Y_AXIS] = current_position[Y_AXIS];
  2234. plan_buffer_line_destinationXYZE(feedrate/60);
  2235. feedrate = 0.0;
  2236. st_synchronize();
  2237. endstops_hit_on_purpose();
  2238. current_position[X_AXIS] = destination[X_AXIS];
  2239. current_position[Y_AXIS] = destination[Y_AXIS];
  2240. current_position[Z_AXIS] = destination[Z_AXIS];
  2241. }
  2242. #endif /* QUICK_HOME */
  2243. #ifdef TMC2130
  2244. if(home_x)
  2245. {
  2246. if (!calib)
  2247. homeaxis(X_AXIS);
  2248. else
  2249. tmc2130_home_calibrate(X_AXIS);
  2250. }
  2251. if(home_y)
  2252. {
  2253. if (!calib)
  2254. homeaxis(Y_AXIS);
  2255. else
  2256. tmc2130_home_calibrate(Y_AXIS);
  2257. }
  2258. #else //TMC2130
  2259. if(home_x) homeaxis(X_AXIS);
  2260. if(home_y) homeaxis(Y_AXIS);
  2261. #endif //TMC2130
  2262. if(home_x_axis && home_x_value != 0)
  2263. current_position[X_AXIS]=home_x_value+cs.add_homing[X_AXIS];
  2264. if(home_y_axis && home_y_value != 0)
  2265. current_position[Y_AXIS]=home_y_value+cs.add_homing[Y_AXIS];
  2266. #if Z_HOME_DIR < 0 // If homing towards BED do Z last
  2267. #ifndef Z_SAFE_HOMING
  2268. if(home_z) {
  2269. #if defined (Z_RAISE_BEFORE_HOMING) && (Z_RAISE_BEFORE_HOMING > 0)
  2270. raise_z_above(Z_RAISE_BEFORE_HOMING);
  2271. st_synchronize();
  2272. #endif // defined (Z_RAISE_BEFORE_HOMING) && (Z_RAISE_BEFORE_HOMING > 0)
  2273. #ifdef MESH_BED_LEVELING // If Mesh bed leveling, move X&Y to safe position for home
  2274. raise_z_above(MESH_HOME_Z_SEARCH);
  2275. st_synchronize();
  2276. if (!axis_known_position[X_AXIS]) homeaxis(X_AXIS);
  2277. if (!axis_known_position[Y_AXIS]) homeaxis(Y_AXIS);
  2278. // 1st mesh bed leveling measurement point, corrected.
  2279. world2machine_initialize();
  2280. world2machine(pgm_read_float(bed_ref_points_4), pgm_read_float(bed_ref_points_4+1), destination[X_AXIS], destination[Y_AXIS]);
  2281. world2machine_reset();
  2282. if (destination[Y_AXIS] < Y_MIN_POS)
  2283. destination[Y_AXIS] = Y_MIN_POS;
  2284. feedrate = homing_feedrate[X_AXIS] / 20;
  2285. enable_endstops(false);
  2286. #ifdef DEBUG_BUILD
  2287. SERIAL_ECHOLNPGM("plan_set_position()");
  2288. MYSERIAL.println(current_position[X_AXIS]);MYSERIAL.println(current_position[Y_AXIS]);
  2289. MYSERIAL.println(current_position[Z_AXIS]);MYSERIAL.println(current_position[E_AXIS]);
  2290. #endif
  2291. plan_set_position_curposXYZE();
  2292. #ifdef DEBUG_BUILD
  2293. SERIAL_ECHOLNPGM("plan_buffer_line()");
  2294. MYSERIAL.println(destination[X_AXIS]);MYSERIAL.println(destination[Y_AXIS]);
  2295. MYSERIAL.println(destination[Z_AXIS]);MYSERIAL.println(destination[E_AXIS]);
  2296. MYSERIAL.println(feedrate);MYSERIAL.println(active_extruder);
  2297. #endif
  2298. plan_buffer_line_destinationXYZE(feedrate);
  2299. st_synchronize();
  2300. current_position[X_AXIS] = destination[X_AXIS];
  2301. current_position[Y_AXIS] = destination[Y_AXIS];
  2302. enable_endstops(true);
  2303. endstops_hit_on_purpose();
  2304. homeaxis(Z_AXIS);
  2305. #else // MESH_BED_LEVELING
  2306. homeaxis(Z_AXIS);
  2307. #endif // MESH_BED_LEVELING
  2308. }
  2309. #else // defined(Z_SAFE_HOMING): Z Safe mode activated.
  2310. if(home_all_axes) {
  2311. destination[X_AXIS] = round(Z_SAFE_HOMING_X_POINT - X_PROBE_OFFSET_FROM_EXTRUDER);
  2312. destination[Y_AXIS] = round(Z_SAFE_HOMING_Y_POINT - Y_PROBE_OFFSET_FROM_EXTRUDER);
  2313. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  2314. feedrate = XY_TRAVEL_SPEED/60;
  2315. current_position[Z_AXIS] = 0;
  2316. plan_set_position_curposXYZE();
  2317. plan_buffer_line_destinationXYZE(feedrate);
  2318. st_synchronize();
  2319. current_position[X_AXIS] = destination[X_AXIS];
  2320. current_position[Y_AXIS] = destination[Y_AXIS];
  2321. homeaxis(Z_AXIS);
  2322. }
  2323. // Let's see if X and Y are homed and probe is inside bed area.
  2324. if(home_z) {
  2325. if ( (axis_known_position[X_AXIS]) && (axis_known_position[Y_AXIS]) \
  2326. && (current_position[X_AXIS]+X_PROBE_OFFSET_FROM_EXTRUDER >= X_MIN_POS) \
  2327. && (current_position[X_AXIS]+X_PROBE_OFFSET_FROM_EXTRUDER <= X_MAX_POS) \
  2328. && (current_position[Y_AXIS]+Y_PROBE_OFFSET_FROM_EXTRUDER >= Y_MIN_POS) \
  2329. && (current_position[Y_AXIS]+Y_PROBE_OFFSET_FROM_EXTRUDER <= Y_MAX_POS)) {
  2330. current_position[Z_AXIS] = 0;
  2331. plan_set_position_curposXYZE();
  2332. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  2333. feedrate = max_feedrate[Z_AXIS];
  2334. plan_buffer_line_destinationXYZE(feedrate);
  2335. st_synchronize();
  2336. homeaxis(Z_AXIS);
  2337. } else if (!((axis_known_position[X_AXIS]) && (axis_known_position[Y_AXIS]))) {
  2338. LCD_MESSAGERPGM(MSG_POSITION_UNKNOWN);
  2339. SERIAL_ECHO_START;
  2340. SERIAL_ECHOLNRPGM(MSG_POSITION_UNKNOWN);
  2341. } else {
  2342. LCD_MESSAGERPGM(MSG_ZPROBE_OUT);
  2343. SERIAL_ECHO_START;
  2344. SERIAL_ECHOLNRPGM(MSG_ZPROBE_OUT);
  2345. }
  2346. }
  2347. #endif // Z_SAFE_HOMING
  2348. #endif // Z_HOME_DIR < 0
  2349. if(home_z_axis && home_z_value != 0)
  2350. current_position[Z_AXIS]=home_z_value+cs.add_homing[Z_AXIS];
  2351. #ifdef ENABLE_AUTO_BED_LEVELING
  2352. if(home_z)
  2353. current_position[Z_AXIS] += cs.zprobe_zoffset; //Add Z_Probe offset (the distance is negative)
  2354. #endif
  2355. // Set the planner and stepper routine positions.
  2356. // At this point the mesh bed leveling and world2machine corrections are disabled and current_position
  2357. // contains the machine coordinates.
  2358. plan_set_position_curposXYZE();
  2359. clean_up_after_endstop_move(l_feedmultiply);
  2360. endstops_hit_on_purpose();
  2361. #ifndef MESH_BED_LEVELING
  2362. //-// Oct 2019 :: this part of code is (from) now probably un-compilable
  2363. // If MESH_BED_LEVELING is not active, then it is the original Prusa i3.
  2364. // Offer the user to load the baby step value, which has been adjusted at the previous print session.
  2365. if(card.sdprinting && eeprom_read_word((uint16_t *)EEPROM_BABYSTEP_Z))
  2366. lcd_adjust_z();
  2367. #endif
  2368. // Load the machine correction matrix
  2369. world2machine_initialize();
  2370. // and correct the current_position XY axes to match the transformed coordinate system.
  2371. world2machine_update_current();
  2372. #ifdef MESH_BED_LEVELING
  2373. if (home_x_axis || home_y_axis || without_mbl || home_z_axis)
  2374. {
  2375. if (! home_z && mbl_was_active) {
  2376. // Re-enable the mesh bed leveling if only the X and Y axes were re-homed.
  2377. mbl.active = true;
  2378. // and re-adjust the current logical Z axis with the bed leveling offset applicable at the current XY position.
  2379. current_position[Z_AXIS] -= mbl.get_z(st_get_position_mm(X_AXIS), st_get_position_mm(Y_AXIS));
  2380. }
  2381. }
  2382. #endif
  2383. prusa_statistics(20);
  2384. st_synchronize();
  2385. homing_flag = false;
  2386. #if 0
  2387. SERIAL_ECHOPGM("G28, final "); print_world_coordinates();
  2388. SERIAL_ECHOPGM("G28, final "); print_physical_coordinates();
  2389. SERIAL_ECHOPGM("G28, final "); print_mesh_bed_leveling_table();
  2390. #endif
  2391. }
  2392. static void gcode_G28(bool home_x_axis, bool home_y_axis, bool home_z_axis)
  2393. {
  2394. #ifdef TMC2130
  2395. gcode_G28(home_x_axis, 0, home_y_axis, 0, home_z_axis, 0, false, true);
  2396. #else
  2397. gcode_G28(home_x_axis, 0, home_y_axis, 0, home_z_axis, 0, true);
  2398. #endif //TMC2130
  2399. }
  2400. // G80 - Automatic mesh bed leveling
  2401. static void gcode_G80()
  2402. {
  2403. st_synchronize();
  2404. if (planner_aborted)
  2405. return;
  2406. mesh_bed_leveling_flag = true;
  2407. #ifndef PINDA_THERMISTOR
  2408. static bool run = false; // thermistor-less PINDA temperature compensation is running
  2409. #endif // ndef PINDA_THERMISTOR
  2410. #ifdef SUPPORT_VERBOSITY
  2411. int8_t verbosity_level = 0;
  2412. if (code_seen('V')) {
  2413. // Just 'V' without a number counts as V1.
  2414. char c = strchr_pointer[1];
  2415. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  2416. }
  2417. #endif //SUPPORT_VERBOSITY
  2418. // Firstly check if we know where we are
  2419. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  2420. // We don't know where we are! HOME!
  2421. // Push the commands to the front of the message queue in the reverse order!
  2422. // There shall be always enough space reserved for these commands.
  2423. repeatcommand_front(); // repeat G80 with all its parameters
  2424. enquecommand_front_P(G28W0);
  2425. return;
  2426. }
  2427. uint8_t nMeasPoints = MESH_MEAS_NUM_X_POINTS;
  2428. if (code_seen('N')) {
  2429. nMeasPoints = code_value_uint8();
  2430. if (nMeasPoints != 7) {
  2431. nMeasPoints = 3;
  2432. }
  2433. }
  2434. else {
  2435. nMeasPoints = eeprom_read_byte((uint8_t*)EEPROM_MBL_POINTS_NR);
  2436. }
  2437. uint8_t nProbeRetry = 3;
  2438. if (code_seen('R')) {
  2439. nProbeRetry = code_value_uint8();
  2440. if (nProbeRetry > 10) {
  2441. nProbeRetry = 10;
  2442. }
  2443. }
  2444. else {
  2445. nProbeRetry = eeprom_read_byte((uint8_t*)EEPROM_MBL_PROBE_NR);
  2446. }
  2447. bool magnet_elimination = (eeprom_read_byte((uint8_t*)EEPROM_MBL_MAGNET_ELIMINATION) > 0);
  2448. #ifndef PINDA_THERMISTOR
  2449. if (run == false && eeprom_read_byte((uint8_t *)EEPROM_TEMP_CAL_ACTIVE) && calibration_status_pinda() == true && target_temperature_bed >= 50)
  2450. {
  2451. temp_compensation_start();
  2452. run = true;
  2453. repeatcommand_front(); // repeat G80 with all its parameters
  2454. enquecommand_front_P(G28W0);
  2455. break;
  2456. }
  2457. run = false;
  2458. #endif //PINDA_THERMISTOR
  2459. // Save custom message state, set a new custom message state to display: Calibrating point 9.
  2460. CustomMsg custom_message_type_old = custom_message_type;
  2461. uint8_t custom_message_state_old = custom_message_state;
  2462. custom_message_type = CustomMsg::MeshBedLeveling;
  2463. custom_message_state = (nMeasPoints * nMeasPoints) + 10;
  2464. lcd_update(1);
  2465. mbl.reset(); //reset mesh bed leveling
  2466. // Reset baby stepping to zero, if the babystepping has already been loaded before.
  2467. babystep_undo();
  2468. // Cycle through all points and probe them
  2469. // First move up. During this first movement, the babystepping will be reverted.
  2470. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2471. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 60);
  2472. // The move to the first calibration point.
  2473. current_position[X_AXIS] = BED_X0;
  2474. current_position[Y_AXIS] = BED_Y0;
  2475. #ifdef SUPPORT_VERBOSITY
  2476. if (verbosity_level >= 1)
  2477. {
  2478. bool clamped = world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  2479. clamped ? SERIAL_PROTOCOLPGM("First calibration point clamped.\n") : SERIAL_PROTOCOLPGM("No clamping for first calibration point.\n");
  2480. }
  2481. #else //SUPPORT_VERBOSITY
  2482. world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  2483. #endif //SUPPORT_VERBOSITY
  2484. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  2485. plan_buffer_line_curposXYZE(XY_AXIS_FEEDRATE);
  2486. // Wait until the move is finished.
  2487. st_synchronize();
  2488. if (planner_aborted)
  2489. {
  2490. custom_message_type = custom_message_type_old;
  2491. custom_message_state = custom_message_state_old;
  2492. return;
  2493. }
  2494. uint8_t mesh_point = 0; //index number of calibration point
  2495. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  2496. 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)
  2497. #ifdef SUPPORT_VERBOSITY
  2498. if (verbosity_level >= 1) {
  2499. has_z ? SERIAL_PROTOCOLPGM("Z jitter data from Z cal. valid.\n") : SERIAL_PROTOCOLPGM("Z jitter data from Z cal. not valid.\n");
  2500. }
  2501. #endif // SUPPORT_VERBOSITY
  2502. int l_feedmultiply = setup_for_endstop_move(false); //save feedrate and feedmultiply, sets feedmultiply to 100
  2503. while (mesh_point != nMeasPoints * nMeasPoints) {
  2504. // Get coords of a measuring point.
  2505. uint8_t ix = mesh_point % nMeasPoints; // from 0 to MESH_NUM_X_POINTS - 1
  2506. uint8_t iy = mesh_point / nMeasPoints;
  2507. /*if (!mbl_point_measurement_valid(ix, iy, nMeasPoints, true)) {
  2508. printf_P(PSTR("Skipping point [%d;%d] \n"), ix, iy);
  2509. custom_message_state--;
  2510. mesh_point++;
  2511. continue; //skip
  2512. }*/
  2513. if (iy & 1) ix = (nMeasPoints - 1) - ix; // Zig zag
  2514. if (nMeasPoints == 7) //if we have 7x7 mesh, compare with Z-calibration for points which are in 3x3 mesh
  2515. {
  2516. has_z = ((ix % 3 == 0) && (iy % 3 == 0)) && is_bed_z_jitter_data_valid();
  2517. }
  2518. float z0 = 0.f;
  2519. if (has_z && (mesh_point > 0)) {
  2520. uint16_t z_offset_u = 0;
  2521. if (nMeasPoints == 7) {
  2522. z_offset_u = eeprom_read_word((uint16_t*)(EEPROM_BED_CALIBRATION_Z_JITTER + 2 * ((ix/3) + iy - 1)));
  2523. }
  2524. else {
  2525. z_offset_u = eeprom_read_word((uint16_t*)(EEPROM_BED_CALIBRATION_Z_JITTER + 2 * (ix + iy * 3 - 1)));
  2526. }
  2527. z0 = mbl.z_values[0][0] + *reinterpret_cast<int16_t*>(&z_offset_u) * 0.01;
  2528. #ifdef SUPPORT_VERBOSITY
  2529. if (verbosity_level >= 1) {
  2530. printf_P(PSTR("Bed leveling, point: %d, calibration Z stored in eeprom: %d, calibration z: %f \n"), mesh_point, z_offset_u, z0);
  2531. }
  2532. #endif // SUPPORT_VERBOSITY
  2533. }
  2534. // Move Z up to MESH_HOME_Z_SEARCH.
  2535. if((ix == 0) && (iy == 0)) current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2536. else current_position[Z_AXIS] += 2.f / nMeasPoints; //use relative movement from Z coordinate where PINDa triggered on previous point. This makes calibration faster.
  2537. float init_z_bckp = current_position[Z_AXIS];
  2538. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  2539. st_synchronize();
  2540. // Move to XY position of the sensor point.
  2541. current_position[X_AXIS] = BED_X(ix, nMeasPoints);
  2542. current_position[Y_AXIS] = BED_Y(iy, nMeasPoints);
  2543. //printf_P(PSTR("[%f;%f]\n"), current_position[X_AXIS], current_position[Y_AXIS]);
  2544. #ifdef SUPPORT_VERBOSITY
  2545. if (verbosity_level >= 1) {
  2546. bool clamped = world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  2547. SERIAL_PROTOCOL(mesh_point);
  2548. clamped ? SERIAL_PROTOCOLPGM(": xy clamped.\n") : SERIAL_PROTOCOLPGM(": no xy clamping\n");
  2549. }
  2550. #else //SUPPORT_VERBOSITY
  2551. world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  2552. #endif // SUPPORT_VERBOSITY
  2553. //printf_P(PSTR("after clamping: [%f;%f]\n"), current_position[X_AXIS], current_position[Y_AXIS]);
  2554. plan_buffer_line_curposXYZE(XY_AXIS_FEEDRATE);
  2555. st_synchronize();
  2556. if (planner_aborted)
  2557. {
  2558. custom_message_type = custom_message_type_old;
  2559. custom_message_state = custom_message_state_old;
  2560. return;
  2561. }
  2562. // Go down until endstop is hit
  2563. const float Z_CALIBRATION_THRESHOLD = 1.f;
  2564. 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
  2565. printf_P(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  2566. break;
  2567. }
  2568. 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.
  2569. //printf_P(PSTR("Another attempt! Current Z position: %f\n"), current_position[Z_AXIS]);
  2570. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2571. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  2572. st_synchronize();
  2573. 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
  2574. printf_P(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  2575. break;
  2576. }
  2577. if (MESH_HOME_Z_SEARCH - current_position[Z_AXIS] < 0.1f) {
  2578. puts_P(PSTR("Bed leveling failed. Sensor disconnected or cable broken."));
  2579. break;
  2580. }
  2581. }
  2582. 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
  2583. puts_P(PSTR("Bed leveling failed. Sensor triggered too high."));
  2584. break;
  2585. }
  2586. #ifdef SUPPORT_VERBOSITY
  2587. if (verbosity_level >= 10) {
  2588. SERIAL_ECHOPGM("X: ");
  2589. MYSERIAL.print(current_position[X_AXIS], 5);
  2590. SERIAL_ECHOLNPGM("");
  2591. SERIAL_ECHOPGM("Y: ");
  2592. MYSERIAL.print(current_position[Y_AXIS], 5);
  2593. SERIAL_PROTOCOLPGM("\n");
  2594. }
  2595. #endif // SUPPORT_VERBOSITY
  2596. float offset_z = 0;
  2597. #ifdef PINDA_THERMISTOR
  2598. offset_z = temp_compensation_pinda_thermistor_offset(current_temperature_pinda);
  2599. #endif //PINDA_THERMISTOR
  2600. // #ifdef SUPPORT_VERBOSITY
  2601. /* if (verbosity_level >= 1)
  2602. {
  2603. SERIAL_ECHOPGM("mesh bed leveling: ");
  2604. MYSERIAL.print(current_position[Z_AXIS], 5);
  2605. SERIAL_ECHOPGM(" offset: ");
  2606. MYSERIAL.print(offset_z, 5);
  2607. SERIAL_ECHOLNPGM("");
  2608. }*/
  2609. // #endif // SUPPORT_VERBOSITY
  2610. mbl.set_z(ix, iy, current_position[Z_AXIS] - offset_z); //store measured z values z_values[iy][ix] = z - offset_z;
  2611. custom_message_state--;
  2612. mesh_point++;
  2613. lcd_update(1);
  2614. }
  2615. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2616. #ifdef SUPPORT_VERBOSITY
  2617. if (verbosity_level >= 20) {
  2618. SERIAL_ECHOLNPGM("Mesh bed leveling while loop finished.");
  2619. SERIAL_ECHOLNPGM("MESH_HOME_Z_SEARCH: ");
  2620. MYSERIAL.print(current_position[Z_AXIS], 5);
  2621. }
  2622. #endif // SUPPORT_VERBOSITY
  2623. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  2624. st_synchronize();
  2625. if (mesh_point != nMeasPoints * nMeasPoints) {
  2626. Sound_MakeSound(e_SOUND_TYPE_StandardAlert);
  2627. bool bState;
  2628. do { // repeat until Z-leveling o.k.
  2629. lcd_display_message_fullscreen_P(_i("Some problem encountered, Z-leveling enforced ...")); ////MSG_ZLEVELING_ENFORCED c=20 r=4
  2630. #ifdef TMC2130
  2631. lcd_wait_for_click_delay(MSG_BED_LEVELING_FAILED_TIMEOUT);
  2632. calibrate_z_auto(); // Z-leveling (X-assembly stay up!!!)
  2633. #else // TMC2130
  2634. lcd_wait_for_click_delay(0); // ~ no timeout
  2635. lcd_calibrate_z_end_stop_manual(true); // Z-leveling (X-assembly stay up!!!)
  2636. #endif // TMC2130
  2637. // ~ Z-homing (can not be used "G28", because X & Y-homing would have been done before (Z-homing))
  2638. bState=enable_z_endstop(false);
  2639. current_position[Z_AXIS] -= 1;
  2640. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2641. st_synchronize();
  2642. enable_z_endstop(true);
  2643. #ifdef TMC2130
  2644. tmc2130_home_enter(Z_AXIS_MASK);
  2645. #endif // TMC2130
  2646. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2647. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2648. st_synchronize();
  2649. #ifdef TMC2130
  2650. tmc2130_home_exit();
  2651. #endif // TMC2130
  2652. enable_z_endstop(bState);
  2653. } while (st_get_position_mm(Z_AXIS) > MESH_HOME_Z_SEARCH); // i.e. Z-leveling not o.k.
  2654. // plan_set_z_position(MESH_HOME_Z_SEARCH); // is not necessary ('do-while' loop always ends at the expected Z-position)
  2655. custom_message_type = custom_message_type_old;
  2656. custom_message_state = custom_message_state_old;
  2657. lcd_update_enable(true); // display / status-line recovery
  2658. gcode_G28(true, true, true); // X & Y & Z-homing (must be after individual Z-homing (problem with spool-holder)!)
  2659. repeatcommand_front(); // re-run (i.e. of "G80")
  2660. return;
  2661. }
  2662. clean_up_after_endstop_move(l_feedmultiply);
  2663. // SERIAL_ECHOLNPGM("clean up finished ");
  2664. #ifndef PINDA_THERMISTOR
  2665. if(eeprom_read_byte((uint8_t *)EEPROM_TEMP_CAL_ACTIVE) && calibration_status_pinda() == true) temp_compensation_apply(); //apply PINDA temperature compensation
  2666. #endif
  2667. babystep_apply(); // Apply Z height correction aka baby stepping before mesh bed leveing gets activated.
  2668. // SERIAL_ECHOLNPGM("babystep applied");
  2669. bool eeprom_bed_correction_valid = eeprom_read_byte((unsigned char*)EEPROM_BED_CORRECTION_VALID) == 1;
  2670. #ifdef SUPPORT_VERBOSITY
  2671. if (verbosity_level >= 1) {
  2672. eeprom_bed_correction_valid ? SERIAL_PROTOCOLPGM("Bed correction data valid\n") : SERIAL_PROTOCOLPGM("Bed correction data not valid\n");
  2673. }
  2674. #endif // SUPPORT_VERBOSITY
  2675. for (uint8_t i = 0; i < 4; ++i) {
  2676. unsigned char codes[4] = { 'L', 'R', 'F', 'B' };
  2677. long correction = 0;
  2678. if (code_seen(codes[i]))
  2679. correction = code_value_long();
  2680. else if (eeprom_bed_correction_valid) {
  2681. unsigned char *addr = (i < 2) ?
  2682. ((i == 0) ? (unsigned char*)EEPROM_BED_CORRECTION_LEFT : (unsigned char*)EEPROM_BED_CORRECTION_RIGHT) :
  2683. ((i == 2) ? (unsigned char*)EEPROM_BED_CORRECTION_FRONT : (unsigned char*)EEPROM_BED_CORRECTION_REAR);
  2684. correction = eeprom_read_int8(addr);
  2685. }
  2686. if (correction == 0)
  2687. continue;
  2688. if (labs(correction) > BED_ADJUSTMENT_UM_MAX) {
  2689. SERIAL_ERROR_START;
  2690. SERIAL_ECHOPGM("Excessive bed leveling correction: ");
  2691. SERIAL_ECHO(correction);
  2692. SERIAL_ECHOLNPGM(" microns");
  2693. }
  2694. else {
  2695. float offset = float(correction) * 0.001f;
  2696. switch (i) {
  2697. case 0:
  2698. for (uint8_t row = 0; row < nMeasPoints; ++row) {
  2699. for (uint8_t col = 0; col < nMeasPoints - 1; ++col) {
  2700. mbl.z_values[row][col] += offset * (nMeasPoints - 1 - col) / (nMeasPoints - 1);
  2701. }
  2702. }
  2703. break;
  2704. case 1:
  2705. for (uint8_t row = 0; row < nMeasPoints; ++row) {
  2706. for (uint8_t col = 1; col < nMeasPoints; ++col) {
  2707. mbl.z_values[row][col] += offset * col / (nMeasPoints - 1);
  2708. }
  2709. }
  2710. break;
  2711. case 2:
  2712. for (uint8_t col = 0; col < nMeasPoints; ++col) {
  2713. for (uint8_t row = 0; row < nMeasPoints; ++row) {
  2714. mbl.z_values[row][col] += offset * (nMeasPoints - 1 - row) / (nMeasPoints - 1);
  2715. }
  2716. }
  2717. break;
  2718. case 3:
  2719. for (uint8_t col = 0; col < nMeasPoints; ++col) {
  2720. for (uint8_t row = 1; row < nMeasPoints; ++row) {
  2721. mbl.z_values[row][col] += offset * row / (nMeasPoints - 1);
  2722. }
  2723. }
  2724. break;
  2725. }
  2726. }
  2727. }
  2728. // SERIAL_ECHOLNPGM("Bed leveling correction finished");
  2729. if (nMeasPoints == 3) {
  2730. 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)
  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. if (nMeasPoints == 7 && magnet_elimination) {
  2749. mbl_interpolation(nMeasPoints);
  2750. }
  2751. /*
  2752. SERIAL_PROTOCOLPGM("Num X,Y: ");
  2753. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  2754. SERIAL_PROTOCOLPGM(",");
  2755. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  2756. SERIAL_PROTOCOLPGM("\nZ search height: ");
  2757. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  2758. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  2759. for (int y = MESH_NUM_Y_POINTS-1; y >= 0; y--) {
  2760. for (int x = 0; x < MESH_NUM_X_POINTS; x++) {
  2761. SERIAL_PROTOCOLPGM(" ");
  2762. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  2763. }
  2764. SERIAL_PROTOCOLPGM("\n");
  2765. }
  2766. */
  2767. // SERIAL_ECHOLNPGM("Upsample finished");
  2768. mbl.active = 1; //activate mesh bed leveling
  2769. // SERIAL_ECHOLNPGM("Mesh bed leveling activated");
  2770. go_home_with_z_lift();
  2771. // SERIAL_ECHOLNPGM("Go home finished");
  2772. //unretract (after PINDA preheat retraction)
  2773. if (((int)degHotend(active_extruder) > extrude_min_temp) && eeprom_read_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE) && calibration_status_pinda() && (target_temperature_bed >= 50)) {
  2774. current_position[E_AXIS] += default_retraction;
  2775. plan_buffer_line_curposXYZE(400);
  2776. }
  2777. KEEPALIVE_STATE(NOT_BUSY);
  2778. // Restore custom message state
  2779. lcd_setstatuspgm(MSG_WELCOME);
  2780. custom_message_type = custom_message_type_old;
  2781. custom_message_state = custom_message_state_old;
  2782. lcd_update(2);
  2783. st_synchronize();
  2784. mesh_bed_leveling_flag = false;
  2785. }
  2786. void adjust_bed_reset()
  2787. {
  2788. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_VALID, 1);
  2789. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_LEFT, 0);
  2790. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_RIGHT, 0);
  2791. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_FRONT, 0);
  2792. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_REAR, 0);
  2793. }
  2794. //! @brief Calibrate XYZ
  2795. //! @param onlyZ if true, calibrate only Z axis
  2796. //! @param verbosity_level
  2797. //! @retval true Succeeded
  2798. //! @retval false Failed
  2799. bool gcode_M45(bool onlyZ, int8_t verbosity_level)
  2800. {
  2801. bool final_result = false;
  2802. #ifdef TMC2130
  2803. FORCE_HIGH_POWER_START;
  2804. #endif // TMC2130
  2805. FORCE_BL_ON_START;
  2806. // Only Z calibration?
  2807. if (!onlyZ)
  2808. {
  2809. setTargetBed(0);
  2810. setAllTargetHotends(0);
  2811. adjust_bed_reset(); //reset bed level correction
  2812. }
  2813. // Disable the default update procedure of the display. We will do a modal dialog.
  2814. lcd_update_enable(false);
  2815. // Let the planner use the uncorrected coordinates.
  2816. mbl.reset();
  2817. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  2818. // the planner will not perform any adjustments in the XY plane.
  2819. // Wait for the motors to stop and update the current position with the absolute values.
  2820. world2machine_revert_to_uncorrected();
  2821. // Reset the baby step value applied without moving the axes.
  2822. babystep_reset();
  2823. // Mark all axes as in a need for homing.
  2824. memset(axis_known_position, 0, sizeof(axis_known_position));
  2825. // Home in the XY plane.
  2826. //set_destination_to_current();
  2827. int l_feedmultiply = setup_for_endstop_move();
  2828. lcd_display_message_fullscreen_P(_T(MSG_AUTO_HOME));
  2829. raise_z_above(MESH_HOME_Z_SEARCH);
  2830. st_synchronize();
  2831. home_xy();
  2832. enable_endstops(false);
  2833. current_position[X_AXIS] += 5;
  2834. current_position[Y_AXIS] += 5;
  2835. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2836. st_synchronize();
  2837. // Let the user move the Z axes up to the end stoppers.
  2838. #ifdef TMC2130
  2839. if (calibrate_z_auto())
  2840. {
  2841. #else //TMC2130
  2842. if (lcd_calibrate_z_end_stop_manual(onlyZ))
  2843. {
  2844. #endif //TMC2130
  2845. lcd_show_fullscreen_message_and_wait_P(_T(MSG_CONFIRM_NOZZLE_CLEAN));
  2846. if(onlyZ){
  2847. lcd_display_message_fullscreen_P(_T(MSG_MEASURE_BED_REFERENCE_HEIGHT_LINE1));
  2848. lcd_puts_at_P(0,3,_n("1/9"));
  2849. }else{
  2850. //lcd_show_fullscreen_message_and_wait_P(_T(MSG_PAPER));
  2851. lcd_display_message_fullscreen_P(_T(MSG_FIND_BED_OFFSET_AND_SKEW_LINE1));
  2852. lcd_puts_at_P(0,3,_n("1/4"));
  2853. }
  2854. refresh_cmd_timeout();
  2855. #ifndef STEEL_SHEET
  2856. if (((degHotend(0) > MAX_HOTEND_TEMP_CALIBRATION) || (degBed() > MAX_BED_TEMP_CALIBRATION)) && (!onlyZ))
  2857. {
  2858. lcd_wait_for_cool_down();
  2859. }
  2860. #endif //STEEL_SHEET
  2861. if(!onlyZ)
  2862. {
  2863. KEEPALIVE_STATE(PAUSED_FOR_USER);
  2864. #ifdef STEEL_SHEET
  2865. bool result = lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_STEEL_SHEET_CHECK), false, false);
  2866. if(result) lcd_show_fullscreen_message_and_wait_P(_T(MSG_REMOVE_STEEL_SHEET));
  2867. #endif //STEEL_SHEET
  2868. lcd_show_fullscreen_message_and_wait_P(_T(MSG_PAPER));
  2869. KEEPALIVE_STATE(IN_HANDLER);
  2870. lcd_display_message_fullscreen_P(_T(MSG_FIND_BED_OFFSET_AND_SKEW_LINE1));
  2871. lcd_puts_at_P(0,3,_n("1/4"));
  2872. }
  2873. bool endstops_enabled = enable_endstops(false);
  2874. current_position[Z_AXIS] -= 1; //move 1mm down with disabled endstop
  2875. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2876. st_synchronize();
  2877. // Move the print head close to the bed.
  2878. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2879. enable_endstops(true);
  2880. #ifdef TMC2130
  2881. tmc2130_home_enter(Z_AXIS_MASK);
  2882. #endif //TMC2130
  2883. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2884. st_synchronize();
  2885. #ifdef TMC2130
  2886. tmc2130_home_exit();
  2887. #endif //TMC2130
  2888. enable_endstops(endstops_enabled);
  2889. if ((st_get_position_mm(Z_AXIS) <= (MESH_HOME_Z_SEARCH + HOME_Z_SEARCH_THRESHOLD)) &&
  2890. (st_get_position_mm(Z_AXIS) >= (MESH_HOME_Z_SEARCH - HOME_Z_SEARCH_THRESHOLD)))
  2891. {
  2892. if (onlyZ)
  2893. {
  2894. clean_up_after_endstop_move(l_feedmultiply);
  2895. // Z only calibration.
  2896. // Load the machine correction matrix
  2897. world2machine_initialize();
  2898. // and correct the current_position to match the transformed coordinate system.
  2899. world2machine_update_current();
  2900. //FIXME
  2901. bool result = sample_mesh_and_store_reference();
  2902. if (result)
  2903. {
  2904. if (calibration_status() == CALIBRATION_STATUS_Z_CALIBRATION)
  2905. {
  2906. // Shipped, the nozzle height has been set already. The user can start printing now.
  2907. calibration_status_store(CALIBRATION_STATUS_CALIBRATED);
  2908. }
  2909. final_result = true;
  2910. // babystep_apply();
  2911. }
  2912. }
  2913. else
  2914. {
  2915. // Reset the baby step value and the baby step applied flag.
  2916. calibration_status_store(CALIBRATION_STATUS_XYZ_CALIBRATION);
  2917. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  2918. // Complete XYZ calibration.
  2919. uint8_t point_too_far_mask = 0;
  2920. BedSkewOffsetDetectionResultType result = find_bed_offset_and_skew(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. //#ifndef NEW_XYZCAL
  2927. if (result >= 0)
  2928. {
  2929. #ifdef HEATBED_V2
  2930. sample_z();
  2931. #else //HEATBED_V2
  2932. point_too_far_mask = 0;
  2933. // Second half: The fine adjustment.
  2934. // Let the planner use the uncorrected coordinates.
  2935. mbl.reset();
  2936. world2machine_reset();
  2937. // Home in the XY plane.
  2938. int l_feedmultiply = setup_for_endstop_move();
  2939. home_xy();
  2940. result = improve_bed_offset_and_skew(1, verbosity_level, point_too_far_mask);
  2941. clean_up_after_endstop_move(l_feedmultiply);
  2942. // Print head up.
  2943. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2944. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2945. st_synchronize();
  2946. // if (result >= 0) babystep_apply();
  2947. #endif //HEATBED_V2
  2948. }
  2949. //#endif //NEW_XYZCAL
  2950. lcd_update_enable(true);
  2951. lcd_update(2);
  2952. lcd_bed_calibration_show_result(result, point_too_far_mask);
  2953. if (result >= 0)
  2954. {
  2955. // Calibration valid, the machine should be able to print. Advise the user to run the V2Calibration.gcode.
  2956. calibration_status_store(CALIBRATION_STATUS_LIVE_ADJUST);
  2957. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) != 1) lcd_show_fullscreen_message_and_wait_P(_T(MSG_BABYSTEP_Z_NOT_SET));
  2958. final_result = true;
  2959. }
  2960. }
  2961. #ifdef TMC2130
  2962. tmc2130_home_exit();
  2963. #endif
  2964. }
  2965. else
  2966. {
  2967. lcd_show_fullscreen_message_and_wait_P(PSTR("Calibration failed! Check the axes and run again."));
  2968. final_result = false;
  2969. }
  2970. }
  2971. else
  2972. {
  2973. // Timeouted.
  2974. }
  2975. lcd_update_enable(true);
  2976. #ifdef TMC2130
  2977. FORCE_HIGH_POWER_END;
  2978. #endif // TMC2130
  2979. FORCE_BL_ON_END;
  2980. return final_result;
  2981. }
  2982. void gcode_M114()
  2983. {
  2984. SERIAL_PROTOCOLPGM("X:");
  2985. SERIAL_PROTOCOL(current_position[X_AXIS]);
  2986. SERIAL_PROTOCOLPGM(" Y:");
  2987. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  2988. SERIAL_PROTOCOLPGM(" Z:");
  2989. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  2990. SERIAL_PROTOCOLPGM(" E:");
  2991. SERIAL_PROTOCOL(current_position[E_AXIS]);
  2992. SERIAL_PROTOCOLRPGM(_n(" Count X: "));////MSG_COUNT_X
  2993. SERIAL_PROTOCOL(float(st_get_position(X_AXIS)) / cs.axis_steps_per_unit[X_AXIS]);
  2994. SERIAL_PROTOCOLPGM(" Y:");
  2995. SERIAL_PROTOCOL(float(st_get_position(Y_AXIS)) / cs.axis_steps_per_unit[Y_AXIS]);
  2996. SERIAL_PROTOCOLPGM(" Z:");
  2997. SERIAL_PROTOCOL(float(st_get_position(Z_AXIS)) / cs.axis_steps_per_unit[Z_AXIS]);
  2998. SERIAL_PROTOCOLPGM(" E:");
  2999. SERIAL_PROTOCOLLN(float(st_get_position(E_AXIS)) / cs.axis_steps_per_unit[E_AXIS]);
  3000. }
  3001. #if (defined(FANCHECK) && (((defined(TACH_0) && (TACH_0 >-1)) || (defined(TACH_1) && (TACH_1 > -1)))))
  3002. void gcode_M123()
  3003. {
  3004. 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);
  3005. }
  3006. #endif //FANCHECK and TACH_0 or TACH_1
  3007. //! extracted code to compute z_shift for M600 in case of filament change operation
  3008. //! requested from fsensors.
  3009. //! The function ensures, that the printhead lifts to at least 25mm above the heat bed
  3010. //! unlike the previous implementation, which was adding 25mm even when the head was
  3011. //! printing at e.g. 24mm height.
  3012. //! A safety margin of FILAMENTCHANGE_ZADD is added in all cases to avoid touching
  3013. //! the printout.
  3014. //! This function is templated to enable fast change of computation data type.
  3015. //! @return new z_shift value
  3016. template<typename T>
  3017. static T gcode_M600_filament_change_z_shift()
  3018. {
  3019. #ifdef FILAMENTCHANGE_ZADD
  3020. static_assert(Z_MAX_POS < (255 - FILAMENTCHANGE_ZADD), "Z-range too high, change the T type from uint8_t to uint16_t");
  3021. // avoid floating point arithmetics when not necessary - results in shorter code
  3022. T z_shift = T(FILAMENTCHANGE_ZADD); // always move above printout
  3023. T ztmp = T( current_position[Z_AXIS] );
  3024. if((ztmp + z_shift) < T(MIN_Z_FOR_SWAP)){
  3025. z_shift = T(MIN_Z_FOR_SWAP) - ztmp; // make sure to be at least 25mm above the heat bed
  3026. }
  3027. return z_shift;
  3028. #else
  3029. return T(0);
  3030. #endif
  3031. }
  3032. static void mmu_M600_wait_and_beep() {
  3033. // Beep and wait for user to remove old filament and prepare new filament for load
  3034. KEEPALIVE_STATE(PAUSED_FOR_USER);
  3035. int counterBeep = 0;
  3036. 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
  3037. bool bFirst = true;
  3038. while (!lcd_clicked()) {
  3039. manage_heater();
  3040. manage_inactivity(true);
  3041. #if BEEPER > 0
  3042. if (counterBeep == 500) {
  3043. counterBeep = 0;
  3044. }
  3045. SET_OUTPUT(BEEPER);
  3046. if (counterBeep == 0) {
  3047. if ((eSoundMode == e_SOUND_MODE_BLIND) || (eSoundMode == e_SOUND_MODE_LOUD) || ((eSoundMode == e_SOUND_MODE_ONCE) && bFirst)) {
  3048. bFirst = false;
  3049. WRITE(BEEPER, HIGH);
  3050. }
  3051. }
  3052. if (counterBeep == 20) {
  3053. WRITE(BEEPER, LOW);
  3054. }
  3055. counterBeep++;
  3056. #endif // BEEPER > 0
  3057. delay_keep_alive(4);
  3058. }
  3059. WRITE(BEEPER, LOW);
  3060. }
  3061. /// @brief load filament for mmu v2
  3062. /// @par nozzle_temp nozzle temperature to load filament
  3063. void mmu_M600_load_filament(bool automatic, float nozzle_temp) {
  3064. uint8_t tmp_extruder = MMU2::mmu2.get_current_tool();
  3065. if (automatic) {
  3066. tmp_extruder = ad_getAlternative(tmp_extruder);
  3067. }
  3068. lcd_update_enable(false);
  3069. lcd_clear();
  3070. lcd_puts_at_P(0, 1, _T(MSG_LOADING_FILAMENT));
  3071. lcd_print(' ');
  3072. lcd_print(tmp_extruder + 1);
  3073. // printf_P(PSTR("T code: %d \n"), tmp_extruder);
  3074. // mmu_printf_P(PSTR("T%d\n"), tmp_extruder);
  3075. setTargetHotend(nozzle_temp, active_extruder);
  3076. MMU2::mmu2.load_filament_to_nozzle(tmp_extruder);
  3077. load_filament_final_feed(); // @@TODO verify
  3078. st_synchronize();
  3079. }
  3080. static void gcode_M600(bool automatic, float x_position, float y_position, float z_shift, float e_shift, float /*e_shift_late*/) {
  3081. st_synchronize();
  3082. float lastpos[4];
  3083. prusa_statistics(22);
  3084. //First backup current position and settings
  3085. int feedmultiplyBckp = feedmultiply;
  3086. float HotendTempBckp = degTargetHotend(active_extruder);
  3087. int fanSpeedBckp = fanSpeed;
  3088. lastpos[X_AXIS] = current_position[X_AXIS];
  3089. lastpos[Y_AXIS] = current_position[Y_AXIS];
  3090. lastpos[Z_AXIS] = current_position[Z_AXIS];
  3091. lastpos[E_AXIS] = current_position[E_AXIS];
  3092. // Retract E
  3093. current_position[E_AXIS] += e_shift;
  3094. plan_buffer_line_curposXYZE(FILAMENTCHANGE_RFEED);
  3095. st_synchronize();
  3096. // Lift Z
  3097. current_position[Z_AXIS] += z_shift;
  3098. clamp_to_software_endstops(current_position);
  3099. plan_buffer_line_curposXYZE(FILAMENTCHANGE_ZFEED);
  3100. st_synchronize();
  3101. // Move XY to side
  3102. current_position[X_AXIS] = x_position;
  3103. current_position[Y_AXIS] = y_position;
  3104. plan_buffer_line_curposXYZE(FILAMENTCHANGE_XYFEED);
  3105. st_synchronize();
  3106. // Beep, manage nozzle heater and wait for user to start unload filament
  3107. if (!MMU2::mmu2.Enabled())
  3108. M600_wait_for_user(HotendTempBckp);
  3109. lcd_change_fil_state = 0;
  3110. // Unload filament
  3111. if (MMU2::mmu2.Enabled())
  3112. MMU2::mmu2.unload(); // unload just current filament for multimaterial printers (used also in M702)
  3113. else
  3114. unload_filament(true); // unload filament for single material (used also in M702)
  3115. st_synchronize(); // finish moves
  3116. #ifdef FILAMENT_SENSOR
  3117. fsensor.setRunoutEnabled(false); //suppress filament runouts while loading filament.
  3118. fsensor.setAutoLoadEnabled(false); //suppress filament autoloads while loading filament.
  3119. #if (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  3120. fsensor.setJamDetectionEnabled(false); //suppress filament jam detection while loading filament.
  3121. #endif //(FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  3122. #endif
  3123. if (!MMU2::mmu2.Enabled()) {
  3124. KEEPALIVE_STATE(PAUSED_FOR_USER);
  3125. lcd_change_fil_state =
  3126. lcd_show_fullscreen_message_yes_no_and_wait_P(_i("Was filament unload successful?"), false, true); ////MSG_UNLOAD_SUCCESSFUL c=20 r=2
  3127. if (lcd_change_fil_state == 0) {
  3128. lcd_clear();
  3129. lcd_puts_at_P(0, 2, _T(MSG_PLEASE_WAIT));
  3130. current_position[X_AXIS] -= 100;
  3131. plan_buffer_line_curposXYZE(FILAMENTCHANGE_XYFEED);
  3132. st_synchronize();
  3133. lcd_show_fullscreen_message_and_wait_P(_i("Please open idler and remove filament manually."));////MSG_CHECK_IDLER c=20 r=5
  3134. }
  3135. }
  3136. if (MMU2::mmu2.Enabled()) {
  3137. if (!automatic) {
  3138. if (saved_printing){
  3139. // if M600 was invoked by filament senzor (FINDA) eject filament so user can easily remove it
  3140. MMU2::mmu2.eject_filament(MMU2::mmu2.get_current_tool(), false);
  3141. }
  3142. mmu_M600_wait_and_beep();
  3143. if (saved_printing) {
  3144. lcd_clear();
  3145. lcd_puts_at_P(0, 2, _T(MSG_PLEASE_WAIT));
  3146. //@@TODO mmu_command(MmuCmd::R0);
  3147. // manage_response(false, false);
  3148. }
  3149. }
  3150. mmu_M600_load_filament(automatic, HotendTempBckp);
  3151. } else
  3152. M600_load_filament();
  3153. if (!automatic)
  3154. M600_check_state(HotendTempBckp);
  3155. lcd_update_enable(true);
  3156. // Not let's go back to print
  3157. fanSpeed = fanSpeedBckp;
  3158. // Feed a little of filament to stabilize pressure
  3159. if (!automatic) {
  3160. current_position[E_AXIS] += FILAMENTCHANGE_RECFEED;
  3161. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EXFEED);
  3162. }
  3163. // Move XY back
  3164. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], FILAMENTCHANGE_XYFEED, active_extruder);
  3165. st_synchronize();
  3166. // Move Z back
  3167. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], lastpos[Z_AXIS], current_position[E_AXIS], FILAMENTCHANGE_ZFEED, active_extruder);
  3168. st_synchronize();
  3169. // Set E position to original
  3170. plan_set_e_position(lastpos[E_AXIS]);
  3171. memcpy(current_position, lastpos, sizeof(lastpos));
  3172. set_destination_to_current();
  3173. // Recover feed rate
  3174. feedmultiply = feedmultiplyBckp;
  3175. char cmd[9];
  3176. sprintf_P(cmd, PSTR("M220 S%i"), feedmultiplyBckp);
  3177. enquecommand(cmd);
  3178. #ifdef FILAMENT_SENSOR
  3179. fsensor.settings_init();
  3180. #endif
  3181. lcd_setstatuspgm(MSG_WELCOME);
  3182. custom_message_type = CustomMsg::Status;
  3183. }
  3184. void gcode_M701(uint8_t mmuSlotIndex){
  3185. printf_P(PSTR("gcode_M701 begin\n"));
  3186. #ifdef FILAMENT_SENSOR
  3187. fsensor.setRunoutEnabled(false); // suppress filament runouts while loading filament.
  3188. fsensor.setAutoLoadEnabled(false); // suppress filament autoloads while loading filament.
  3189. #if (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  3190. fsensor.setJamDetectionEnabled(false); // suppress filament jam detection while loading filament.
  3191. #endif //(FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  3192. #endif
  3193. prusa_statistics(22);
  3194. }
  3195. if (MMU2::mmu2.Enabled() && mmuSlotIndex < MMU_FILAMENT_COUNT) {
  3196. MMU2::mmu2.load_filament(mmuSlotIndex); // loads current extruder
  3197. // mmu_extruder = mmuSlotIndex; // @@TODO shall load filament set current tool to some specific index? We don't do that anymore.
  3198. } else {
  3199. enable_z();
  3200. custom_message_type = CustomMsg::FilamentLoading;
  3201. const int feed_mm_before_raising = 30;
  3202. static_assert(feed_mm_before_raising <= FILAMENTCHANGE_FIRSTFEED);
  3203. lcd_setstatuspgm(_T(MSG_LOADING_FILAMENT));
  3204. current_position[E_AXIS] += FILAMENTCHANGE_FIRSTFEED - feed_mm_before_raising;
  3205. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EFEED_FIRST); //fast sequence
  3206. st_synchronize();
  3207. raise_z_above(MIN_Z_FOR_LOAD, false);
  3208. current_position[E_AXIS] += feed_mm_before_raising;
  3209. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EFEED_FIRST); //fast sequence
  3210. load_filament_final_feed(); // slow sequence
  3211. st_synchronize();
  3212. Sound_MakeCustom(50, 500, false);
  3213. if (!farm_mode && loading_flag) {
  3214. lcd_load_filament_color_check();
  3215. }
  3216. lcd_update_enable(true);
  3217. lcd_update(2);
  3218. lcd_setstatuspgm(MSG_WELCOME);
  3219. disable_z();
  3220. loading_flag = false;
  3221. custom_message_type = CustomMsg::Status;
  3222. }
  3223. eFilamentAction = FilamentAction::None;
  3224. #ifdef FILAMENT_SENSOR
  3225. fsensor.settings_init(); // restore filament runout state.
  3226. #endif
  3227. }
  3228. /**
  3229. * @brief Get serial number from 32U2 processor
  3230. *
  3231. * Typical format of S/N is:CZPX0917X003XC13518
  3232. *
  3233. * Send command ;S to serial port 0 to retrieve serial number stored in 32U2 processor,
  3234. * reply is stored in *SN.
  3235. * Operation takes typically 23 ms. If no valid SN can be retrieved within the 250ms window, the function aborts
  3236. * and returns a general failure flag.
  3237. * The command will fail if the 32U2 processor is unpowered via USB since it is isolated from the rest of the electronics.
  3238. * In that case the value that is stored in the EEPROM should be used instead.
  3239. *
  3240. * @return 0 on success
  3241. * @return 1 on general failure
  3242. */
  3243. #ifdef PRUSA_SN_SUPPORT
  3244. static uint8_t get_PRUSA_SN(char* SN)
  3245. {
  3246. uint8_t selectedSerialPort_bak = selectedSerialPort;
  3247. uint8_t rxIndex;
  3248. bool SN_valid = false;
  3249. ShortTimer timeout;
  3250. selectedSerialPort = 0;
  3251. timeout.start();
  3252. while (!SN_valid)
  3253. {
  3254. rxIndex = 0;
  3255. _delay(50);
  3256. MYSERIAL.flush(); //clear RX buffer
  3257. SERIAL_ECHOLNRPGM(PSTR(";S"));
  3258. while (rxIndex < 19)
  3259. {
  3260. if (timeout.expired(250u))
  3261. goto exit;
  3262. if (MYSERIAL.available() > 0)
  3263. {
  3264. SN[rxIndex] = MYSERIAL.read();
  3265. rxIndex++;
  3266. }
  3267. }
  3268. SN[rxIndex] = 0;
  3269. // printf_P(PSTR("SN:%s\n"), SN);
  3270. SN_valid = (strncmp_P(SN, PSTR("CZPX"), 4) == 0);
  3271. }
  3272. exit:
  3273. selectedSerialPort = selectedSerialPort_bak;
  3274. return !SN_valid;
  3275. }
  3276. #endif //PRUSA_SN_SUPPORT
  3277. //! Detection of faulty RAMBo 1.1b boards equipped with bigger capacitors
  3278. //! at the TACH_1 pin, which causes bad detection of print fan speed.
  3279. //! Warning: This function is not to be used by ordinary users, it is here only for automated testing purposes,
  3280. //! it may even interfere with other functions of the printer! You have been warned!
  3281. //! The test idea is to measure the time necessary to charge the capacitor.
  3282. //! So the algorithm is as follows:
  3283. //! 1. Set TACH_1 pin to INPUT mode and LOW
  3284. //! 2. Wait a few ms
  3285. //! 3. disable interrupts and measure the time until the TACH_1 pin reaches HIGH
  3286. //! Repeat 1.-3. several times
  3287. //! Good RAMBo's times are in the range of approx. 260-320 us
  3288. //! Bad RAMBo's times are approx. 260-1200 us
  3289. //! So basically we are interested in maximum time, the minima are mostly the same.
  3290. //! May be that's why the bad RAMBo's still produce some fan RPM reading, but not corresponding to reality
  3291. static void gcode_PRUSA_BadRAMBoFanTest(){
  3292. //printf_P(PSTR("Enter fan pin test\n"));
  3293. #if !defined(DEBUG_DISABLE_FANCHECK) && defined(FANCHECK) && defined(TACH_1) && TACH_1 >-1
  3294. fan_measuring = false; // prevent EXTINT7 breaking into the measurement
  3295. unsigned long tach1max = 0;
  3296. uint8_t tach1cntr = 0;
  3297. for( /* nothing */; tach1cntr < 100; ++tach1cntr){
  3298. //printf_P(PSTR("TACH_1: %d\n"), tach1cntr);
  3299. SET_OUTPUT(TACH_1);
  3300. WRITE(TACH_1, LOW);
  3301. _delay(20); // the delay may be lower
  3302. unsigned long tachMeasure = _micros();
  3303. cli();
  3304. SET_INPUT(TACH_1);
  3305. // just wait brutally in an endless cycle until we reach HIGH
  3306. // if this becomes a problem it may be improved to non-endless cycle
  3307. while( READ(TACH_1) == 0 ) ;
  3308. sei();
  3309. tachMeasure = _micros() - tachMeasure;
  3310. if( tach1max < tachMeasure )
  3311. tach1max = tachMeasure;
  3312. //printf_P(PSTR("TACH_1: %d: capacitor check time=%lu us\n"), (int)tach1cntr, tachMeasure);
  3313. }
  3314. //printf_P(PSTR("TACH_1: max=%lu us\n"), tach1max);
  3315. SERIAL_PROTOCOLPGM("RAMBo FAN ");
  3316. if( tach1max > 500 ){
  3317. // bad RAMBo
  3318. SERIAL_PROTOCOLLNPGM("BAD");
  3319. } else {
  3320. SERIAL_PROTOCOLLNPGM("OK");
  3321. }
  3322. // cleanup after the test function
  3323. SET_INPUT(TACH_1);
  3324. WRITE(TACH_1, HIGH);
  3325. #endif
  3326. }
  3327. // G92 - Set current position to coordinates given
  3328. static void gcode_G92()
  3329. {
  3330. bool codes[NUM_AXIS];
  3331. float values[NUM_AXIS];
  3332. // Check which axes need to be set
  3333. for(uint8_t i = 0; i < NUM_AXIS; ++i)
  3334. {
  3335. codes[i] = code_seen(axis_codes[i]);
  3336. if(codes[i])
  3337. values[i] = code_value();
  3338. }
  3339. if((codes[E_AXIS] && values[E_AXIS] == 0) &&
  3340. (!codes[X_AXIS] && !codes[Y_AXIS] && !codes[Z_AXIS]))
  3341. {
  3342. // As a special optimization, when _just_ clearing the E position
  3343. // we schedule a flag asynchronously along with the next block to
  3344. // reset the starting E position instead of stopping the planner
  3345. current_position[E_AXIS] = 0;
  3346. plan_reset_next_e();
  3347. }
  3348. else
  3349. {
  3350. // In any other case we're forced to synchronize
  3351. st_synchronize();
  3352. for(uint8_t i = 0; i < 3; ++i)
  3353. {
  3354. if(codes[i])
  3355. current_position[i] = values[i] + cs.add_homing[i];
  3356. }
  3357. if(codes[E_AXIS])
  3358. current_position[E_AXIS] = values[E_AXIS];
  3359. // Set all at once
  3360. plan_set_position_curposXYZE();
  3361. }
  3362. }
  3363. #ifdef EXTENDED_CAPABILITIES_REPORT
  3364. static void cap_line(const char* name, bool ena = false) {
  3365. printf_P(PSTR("Cap:%S:%c\n"), name, (char)ena + '0');
  3366. }
  3367. static void extended_capabilities_report()
  3368. {
  3369. // AUTOREPORT_TEMP (M155)
  3370. cap_line(PSTR("AUTOREPORT_TEMP"), ENABLED(AUTO_REPORT));
  3371. #if (defined(FANCHECK) && (((defined(TACH_0) && (TACH_0 >-1)) || (defined(TACH_1) && (TACH_1 > -1)))))
  3372. // AUTOREPORT_FANS (M123)
  3373. cap_line(PSTR("AUTOREPORT_FANS"), ENABLED(AUTO_REPORT));
  3374. #endif //FANCHECK and TACH_0 or TACH_1
  3375. // AUTOREPORT_POSITION (M114)
  3376. cap_line(PSTR("AUTOREPORT_POSITION"), ENABLED(AUTO_REPORT));
  3377. // EXTENDED_M20 (support for L and T parameters)
  3378. cap_line(PSTR("EXTENDED_M20"), 1);
  3379. cap_line(PSTR("PRUSA_MMU2"), 1); //this will soon change to ENABLED(PRUSA_MMU2_SUPPORT)
  3380. }
  3381. #endif //EXTENDED_CAPABILITIES_REPORT
  3382. #ifdef BACKLASH_X
  3383. extern uint8_t st_backlash_x;
  3384. #endif //BACKLASH_X
  3385. #ifdef BACKLASH_Y
  3386. extern uint8_t st_backlash_y;
  3387. #endif //BACKLASH_Y
  3388. //! \ingroup marlin_main
  3389. //! @brief Parse and process commands
  3390. //!
  3391. //! look here for descriptions of G-codes: https://reprap.org/wiki/G-code
  3392. //!
  3393. //!
  3394. //! Implemented Codes
  3395. //! -------------------
  3396. //!
  3397. //! * _This list is not updated. Current documentation is maintained inside the process_cmd function._
  3398. //!
  3399. //!@n PRUSA CODES
  3400. //!@n P F - Returns FW versions
  3401. //!@n P R - Returns revision of printer
  3402. //!
  3403. //!@n G0 -> G1
  3404. //!@n G1 - Coordinated Movement X Y Z E
  3405. //!@n G2 - CW ARC
  3406. //!@n G3 - CCW ARC
  3407. //!@n G4 - Dwell S<seconds> or P<milliseconds>
  3408. //!@n G10 - retract filament according to settings of M207
  3409. //!@n G11 - retract recover filament according to settings of M208
  3410. //!@n G28 - Home all Axes
  3411. //!@n G29 - Detailed Z-Probe, probes the bed at 3 or more points. Will fail if you haven't homed yet.
  3412. //!@n G30 - Single Z Probe, probes bed at current XY location.
  3413. //!@n G31 - Dock sled (Z_PROBE_SLED only)
  3414. //!@n G32 - Undock sled (Z_PROBE_SLED only)
  3415. //!@n G80 - Automatic mesh bed leveling
  3416. //!@n G81 - Print bed profile
  3417. //!@n G90 - Use Absolute Coordinates
  3418. //!@n G91 - Use Relative Coordinates
  3419. //!@n G92 - Set current position to coordinates given
  3420. //!
  3421. //!@n M Codes
  3422. //!@n M0 - Unconditional stop - Wait for user to press a button on the LCD
  3423. //!@n M1 - Same as M0
  3424. //!@n M17 - Enable/Power all stepper motors
  3425. //!@n M18 - Disable all stepper motors; same as M84
  3426. //!@n M20 - List SD card
  3427. //!@n M21 - Init SD card
  3428. //!@n M22 - Release SD card
  3429. //!@n M23 - Select SD file (M23 filename.g)
  3430. //!@n M24 - Start/resume SD print
  3431. //!@n M25 - Pause SD print
  3432. //!@n M26 - Set SD position in bytes (M26 S12345)
  3433. //!@n M27 - Report SD print status
  3434. //!@n M28 - Start SD write (M28 filename.g)
  3435. //!@n M29 - Stop SD write
  3436. //!@n M30 - Delete file from SD (M30 filename.g)
  3437. //!@n M31 - Output time since last M109 or SD card start to serial
  3438. //!@n M32 - Select file and start SD print (Can be used _while_ printing from SD card files):
  3439. //! syntax "M32 /path/filename#", or "M32 S<startpos bytes> !filename#"
  3440. //! Call gcode file : "M32 P !filename#" and return to caller file after finishing (similar to #include).
  3441. //! The '#' is necessary when calling from within sd files, as it stops buffer prereading
  3442. //!@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.
  3443. //!@n M73 - Show percent done and print time remaining
  3444. //!@n M80 - Turn on Power Supply
  3445. //!@n M81 - Turn off Power Supply
  3446. //!@n M82 - Set E codes absolute (default)
  3447. //!@n M83 - Set E codes relative while in Absolute Coordinates (G90) mode
  3448. //!@n M84 - Disable steppers until next move,
  3449. //! or use S<seconds> to specify an inactivity timeout, after which the steppers will be disabled. S0 to disable the timeout.
  3450. //!@n M85 - Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
  3451. //!@n M86 - Set safety timer expiration time with parameter S<seconds>; M86 S0 will disable safety timer
  3452. //!@n M92 - Set axis_steps_per_unit - same syntax as G92
  3453. //!@n M104 - Set extruder target temp
  3454. //!@n M105 - Read current temp
  3455. //!@n M106 - Fan on
  3456. //!@n M107 - Fan off
  3457. //!@n M109 - Sxxx Wait for extruder current temp to reach target temp. Waits only when heating
  3458. //! Rxxx Wait for extruder current temp to reach target temp. Waits when heating and cooling
  3459. //! IF AUTOTEMP is enabled, S<mintemp> B<maxtemp> F<factor>. Exit autotemp by any M109 without F
  3460. //!@n M112 - Emergency stop
  3461. //!@n M113 - Get or set the timeout interval for Host Keepalive "busy" messages
  3462. //!@n M114 - Output current position to serial port
  3463. //!@n M115 - Capabilities string
  3464. //!@n M117 - display message
  3465. //!@n M119 - Output Endstop status to serial port
  3466. //!@n M123 - Tachometer value
  3467. //!@n M126 - Solenoid Air Valve Open (BariCUDA support by jmil)
  3468. //!@n M127 - Solenoid Air Valve Closed (BariCUDA vent to atmospheric pressure by jmil)
  3469. //!@n M128 - EtoP Open (BariCUDA EtoP = electricity to air pressure transducer by jmil)
  3470. //!@n M129 - EtoP Closed (BariCUDA EtoP = electricity to air pressure transducer by jmil)
  3471. //!@n M140 - Set bed target temp
  3472. //!@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.
  3473. //!@n M155 - Automatically send temperatures, fan speeds, position
  3474. //!@n M190 - Sxxx Wait for bed current temp to reach target temp. Waits only when heating
  3475. //! Rxxx Wait for bed current temp to reach target temp. Waits when heating and cooling
  3476. //!@n M200 D<millimeters>- set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).
  3477. //!@n M201 - Set max acceleration in units/s^2 for print moves (M201 X1000 Y1000)
  3478. //!@n M202 - Set max acceleration in units/s^2 for travel moves (M202 X1000 Y1000) Unused in Marlin!!
  3479. //!@n M203 - Set maximum feedrate that your machine can sustain (M203 X200 Y200 Z300 E10000) in mm/sec
  3480. //!@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
  3481. //!@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
  3482. //!@n M206 - set additional homing offset
  3483. //!@n M207 - set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop], stays in mm regardless of M200 setting
  3484. //!@n M208 - set recover=unretract length S[positive mm surplus to the M207 S*] F[feedrate mm/sec]
  3485. //!@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.
  3486. //!@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>
  3487. //!@n M218 - set hotend offset (in mm): T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  3488. //!@n M220 S<factor in percent>- set speed factor override percentage
  3489. //!@n M221 S<factor in percent>- set extrude factor override percentage
  3490. //!@n M226 P<pin number> S<pin state>- Wait until the specified pin reaches the state required
  3491. //!@n M240 - Trigger a camera to take a photograph
  3492. //!@n M250 - Set LCD contrast C<contrast value> (value 0..63)
  3493. //!@n M280 - set servo position absolute. P: servo index, S: angle or microseconds
  3494. //!@n M300 - Play beep sound S<frequency Hz> P<duration ms>
  3495. //!@n M301 - Set PID parameters P I and D
  3496. //!@n M302 - Allow cold extrudes, or set the minimum extrude S<temperature>.
  3497. //!@n M303 - PID relay autotune S<temperature> sets the target temperature. (default target temperature = 150C)
  3498. //!@n M304 - Set bed PID parameters P I and D
  3499. //!@n M310 - Temperature model settings
  3500. //!@n M400 - Finish all moves
  3501. //!@n M401 - Lower z-probe if present
  3502. //!@n M402 - Raise z-probe if present
  3503. //!@n M404 - N<dia in mm> Enter the nominal filament width (3mm, 1.75mm ) or will display nominal filament width without parameters
  3504. //!@n M405 - Turn on Filament Sensor extrusion control. Optional D<delay in cm> to set delay in centimeters between sensor and extruder
  3505. //!@n M406 - Turn off Filament Sensor extrusion control
  3506. //!@n M407 - Displays measured filament diameter
  3507. //!@n M500 - stores parameters in EEPROM
  3508. //!@n M501 - reads parameters from EEPROM (if you need reset them after you changed them temporarily).
  3509. //!@n M502 - reverts to the default "factory settings". You still need to store them in EEPROM afterwards if you want to.
  3510. //!@n M503 - print the current settings (from memory not from EEPROM)
  3511. //!@n M509 - force language selection on next restart
  3512. //!@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)
  3513. //!@n M552 - Set IP address
  3514. //!@n M600 - Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  3515. //!@n M605 - Set dual x-carriage movement mode: S<mode> [ X<duplication x-offset> R<duplication temp offset> ]
  3516. //!@n M860 - Wait for PINDA thermistor to reach target temperature.
  3517. //!@n M861 - Set / Read PINDA temperature compensation offsets
  3518. //!@n M900 - Set LIN_ADVANCE options, if enabled. See Configuration_adv.h for details.
  3519. //!@n M907 - Set digital trimpot motor current using axis codes.
  3520. //!@n M908 - Control digital trimpot directly.
  3521. //!@n M350 - Set microstepping mode.
  3522. //!@n M351 - Toggle MS1 MS2 pins directly.
  3523. //!
  3524. //!@n M928 - Start SD logging (M928 filename.g) - ended by M29
  3525. //!@n M999 - Restart after being stopped by error
  3526. //! <br><br>
  3527. /** @defgroup marlin_main Marlin main */
  3528. /** \ingroup GCodes */
  3529. //! _This is a list of currently implemented G Codes in Prusa firmware (dynamically generated from doxygen)._
  3530. /**
  3531. They are shown in order of appearance in the code.
  3532. There are reasons why some G Codes aren't in numerical order.
  3533. */
  3534. void process_commands()
  3535. {
  3536. if (!buflen) return; //empty command
  3537. #ifdef CMDBUFFER_DEBUG
  3538. SERIAL_ECHOPGM("Processing a GCODE command: ");
  3539. SERIAL_ECHO(cmdbuffer+bufindr+CMDHDRSIZE);
  3540. SERIAL_ECHOLNPGM("");
  3541. SERIAL_ECHOPGM("In cmdqueue: ");
  3542. SERIAL_ECHO(buflen);
  3543. SERIAL_ECHOLNPGM("");
  3544. #endif /* CMDBUFFER_DEBUG */
  3545. unsigned long codenum; //throw away variable
  3546. char *starpos = NULL;
  3547. #ifdef ENABLE_AUTO_BED_LEVELING
  3548. float x_tmp, y_tmp, z_tmp, real_z;
  3549. #endif
  3550. // PRUSA GCODES
  3551. KEEPALIVE_STATE(IN_HANDLER);
  3552. /*!
  3553. ---------------------------------------------------------------------------------
  3554. ### M117 - Display Message <a href="https://reprap.org/wiki/G-code#M117:_Display_Message">M117: Display Message</a>
  3555. This causes the given message to be shown in the status line on an attached LCD.
  3556. It is processed early as to allow printing messages that contain G, M, N or T.
  3557. ---------------------------------------------------------------------------------
  3558. ### Special internal commands
  3559. These are used by internal functions to process certain actions in the right order. Some of these are also usable by the user.
  3560. They are processed early as the commands are complex (strings).
  3561. These are only available on the MK3(S) as these require TMC2130 drivers:
  3562. - CRASH DETECTED
  3563. - CRASH RECOVER
  3564. - CRASH_CANCEL
  3565. - TMC_SET_WAVE
  3566. - TMC_SET_STEP
  3567. - TMC_SET_CHOP
  3568. */
  3569. if (code_seen_P(PSTR("M117"))) //moved to highest priority place to be able to to print strings which includes "G", "PRUSA" and "^"
  3570. {
  3571. starpos = (strchr(strchr_pointer + 5, '*'));
  3572. if (starpos != NULL)
  3573. *(starpos) = '\0';
  3574. lcd_setstatus(strchr_pointer + 5);
  3575. custom_message_type = CustomMsg::M117;
  3576. }
  3577. /*!
  3578. ### M0, M1 - Stop the printer <a href="https://reprap.org/wiki/G-code#M0:_Stop_or_Unconditional_stop">M0: Stop or Unconditional stop</a>
  3579. #### Usage
  3580. M0 [P<ms<] [S<sec>] [string]
  3581. M1 [P<ms>] [S<sec>] [string]
  3582. #### Parameters
  3583. - `P<ms>` - Expire time, in milliseconds
  3584. - `S<sec>` - Expire time, in seconds
  3585. - `string` - Must for M1 and optional for M0 message to display on the LCD
  3586. */
  3587. 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
  3588. const char *src = strchr_pointer + 2;
  3589. codenum = 0;
  3590. bool hasP = false, hasS = false;
  3591. if (code_seen('P')) {
  3592. codenum = code_value_long(); // milliseconds to wait
  3593. hasP = codenum > 0;
  3594. }
  3595. if (code_seen('S')) {
  3596. codenum = code_value_long() * 1000; // seconds to wait
  3597. hasS = codenum > 0;
  3598. }
  3599. starpos = strchr(src, '*');
  3600. if (starpos != NULL) *(starpos) = '\0';
  3601. while (*src == ' ') ++src;
  3602. custom_message_type = CustomMsg::M0Wait;
  3603. if (!hasP && !hasS && *src != '\0') {
  3604. lcd_setstatus(src);
  3605. } else {
  3606. // farmers want to abuse a bug from the previous firmware releases
  3607. // - they need to see the filename on the status screen instead of "Wait for user..."
  3608. // So we won't update the message in farm mode...
  3609. if( ! farm_mode){
  3610. LCD_MESSAGERPGM(_i("Wait for user..."));////MSG_USERWAIT c=20
  3611. } else {
  3612. custom_message_type = CustomMsg::Status; // let the lcd display the name of the printed G-code file in farm mode
  3613. }
  3614. }
  3615. lcd_ignore_click(); //call lcd_ignore_click also for else ???
  3616. st_synchronize();
  3617. previous_millis_cmd.start();
  3618. if (codenum > 0 ) {
  3619. codenum += _millis(); // keep track of when we started waiting
  3620. KEEPALIVE_STATE(PAUSED_FOR_USER);
  3621. while(_millis() < codenum && !lcd_clicked()) {
  3622. manage_heater();
  3623. manage_inactivity(true);
  3624. lcd_update(0);
  3625. }
  3626. KEEPALIVE_STATE(IN_HANDLER);
  3627. lcd_ignore_click(false);
  3628. } else {
  3629. marlin_wait_for_click();
  3630. }
  3631. if (IS_SD_PRINTING)
  3632. custom_message_type = CustomMsg::Status;
  3633. else
  3634. LCD_MESSAGERPGM(MSG_WELCOME);
  3635. }
  3636. #ifdef TMC2130
  3637. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("CRASH_"), 6) == 0)
  3638. {
  3639. // ### CRASH_DETECTED - TMC2130
  3640. // ---------------------------------
  3641. if(code_seen_P(PSTR("CRASH_DETECTED")))
  3642. {
  3643. uint8_t mask = 0;
  3644. if (code_seen('X')) mask |= X_AXIS_MASK;
  3645. if (code_seen('Y')) mask |= Y_AXIS_MASK;
  3646. crashdet_detected(mask);
  3647. }
  3648. // ### CRASH_RECOVER - TMC2130
  3649. // ----------------------------------
  3650. else if(code_seen_P(PSTR("CRASH_RECOVER")))
  3651. crashdet_recover();
  3652. // ### CRASH_CANCEL - TMC2130
  3653. // ----------------------------------
  3654. else if(code_seen_P(PSTR("CRASH_CANCEL")))
  3655. crashdet_cancel();
  3656. }
  3657. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("TMC_"), 4) == 0)
  3658. {
  3659. // ### TMC_SET_WAVE_
  3660. // --------------------
  3661. if (strncmp_P(CMDBUFFER_CURRENT_STRING + 4, PSTR("SET_WAVE_"), 9) == 0)
  3662. {
  3663. uint8_t axis = *(CMDBUFFER_CURRENT_STRING + 13);
  3664. axis = (axis == 'E')?3:(axis - 'X');
  3665. if (axis < 4)
  3666. {
  3667. uint8_t fac = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 14, NULL, 10);
  3668. tmc2130_set_wave(axis, 247, fac);
  3669. }
  3670. }
  3671. // ### TMC_SET_STEP_
  3672. // ------------------
  3673. else if (strncmp_P(CMDBUFFER_CURRENT_STRING + 4, PSTR("SET_STEP_"), 9) == 0)
  3674. {
  3675. uint8_t axis = *(CMDBUFFER_CURRENT_STRING + 13);
  3676. axis = (axis == 'E')?3:(axis - 'X');
  3677. if (axis < 4)
  3678. {
  3679. uint8_t step = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 14, NULL, 10);
  3680. uint16_t res = tmc2130_get_res(axis);
  3681. tmc2130_goto_step(axis, step & (4*res - 1), 2, 1000, res);
  3682. }
  3683. }
  3684. // ### TMC_SET_CHOP_
  3685. // -------------------
  3686. else if (strncmp_P(CMDBUFFER_CURRENT_STRING + 4, PSTR("SET_CHOP_"), 9) == 0)
  3687. {
  3688. uint8_t axis = *(CMDBUFFER_CURRENT_STRING + 13);
  3689. axis = (axis == 'E')?3:(axis - 'X');
  3690. if (axis < 4)
  3691. {
  3692. uint8_t chop0 = tmc2130_chopper_config[axis].toff;
  3693. uint8_t chop1 = tmc2130_chopper_config[axis].hstr;
  3694. uint8_t chop2 = tmc2130_chopper_config[axis].hend;
  3695. uint8_t chop3 = tmc2130_chopper_config[axis].tbl;
  3696. char* str_end = 0;
  3697. if (CMDBUFFER_CURRENT_STRING[14])
  3698. {
  3699. chop0 = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 14, &str_end, 10) & 15;
  3700. if (str_end && *str_end)
  3701. {
  3702. chop1 = (uint8_t)strtol(str_end, &str_end, 10) & 7;
  3703. if (str_end && *str_end)
  3704. {
  3705. chop2 = (uint8_t)strtol(str_end, &str_end, 10) & 15;
  3706. if (str_end && *str_end)
  3707. chop3 = (uint8_t)strtol(str_end, &str_end, 10) & 3;
  3708. }
  3709. }
  3710. }
  3711. tmc2130_chopper_config[axis].toff = chop0;
  3712. tmc2130_chopper_config[axis].hstr = chop1 & 7;
  3713. tmc2130_chopper_config[axis].hend = chop2 & 15;
  3714. tmc2130_chopper_config[axis].tbl = chop3 & 3;
  3715. tmc2130_setup_chopper(axis, tmc2130_mres[axis], tmc2130_current_h[axis], tmc2130_current_r[axis]);
  3716. //printf_P(_N("TMC_SET_CHOP_%c %d %d %d %d\n"), "xyze"[axis], chop0, chop1, chop2, chop3);
  3717. }
  3718. }
  3719. }
  3720. #ifdef BACKLASH_X
  3721. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("BACKLASH_X"), 10) == 0)
  3722. {
  3723. uint8_t bl = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 10, NULL, 10);
  3724. st_backlash_x = bl;
  3725. printf_P(_N("st_backlash_x = %d\n"), st_backlash_x);
  3726. }
  3727. #endif //BACKLASH_X
  3728. #ifdef BACKLASH_Y
  3729. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("BACKLASH_Y"), 10) == 0)
  3730. {
  3731. uint8_t bl = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 10, NULL, 10);
  3732. st_backlash_y = bl;
  3733. printf_P(_N("st_backlash_y = %d\n"), st_backlash_y);
  3734. }
  3735. #endif //BACKLASH_Y
  3736. #endif //TMC2130
  3737. else if(code_seen_P(PSTR("PRUSA"))){
  3738. /*!
  3739. ---------------------------------------------------------------------------------
  3740. ### PRUSA - Internal command set <a href="https://reprap.org/wiki/G-code#G98:_Activate_farm_mode">G98: Activate farm mode - Notes</a>
  3741. Set of internal PRUSA commands
  3742. #### Usage
  3743. PRUSA [ PRN | FAN | thx | uvlo | MMURES | RESET | fv | M28 | SN | Fir | Rev | Lang | Lz | FR ]
  3744. #### Parameters
  3745. - `PRN` - Prints revision of the printer
  3746. - `FAN` - Prints fan details
  3747. - `thx`
  3748. - `uvlo`
  3749. - `MMURES` - Reset MMU
  3750. - `RESET` - (Careful!)
  3751. - `fv` - ?
  3752. - `M28`
  3753. - `SN`
  3754. - `Fir` - Prints firmware version
  3755. - `Rev`- Prints filament size, elelectronics, nozzle type
  3756. - `Lang` - Reset the language
  3757. - `Lz`
  3758. - `FR` - Full factory reset
  3759. - `nozzle set <diameter>` - set nozzle diameter (farm mode only), e.g. `PRUSA nozzle set 0.4`
  3760. - `nozzle D<diameter>` - check the nozzle diameter (farm mode only), works like M862.1 P, e.g. `PRUSA nozzle D0.4`
  3761. - `nozzle` - prints nozzle diameter (farm mode only), works like M862.1 P, e.g. `PRUSA nozzle`
  3762. */
  3763. if (farm_prusa_code_seen()) {}
  3764. else if(code_seen_P(PSTR("FANPINTST"))) {
  3765. gcode_PRUSA_BadRAMBoFanTest();
  3766. }
  3767. else if (code_seen_P(PSTR("FAN"))) { // PRUSA FAN
  3768. printf_P(_N("E0:%d RPM\nPRN0:%d RPM\n"), 60*fan_speed[0], 60*fan_speed[1]);
  3769. }
  3770. else if (code_seen_P(PSTR("uvlo"))) { // PRUSA uvlo
  3771. eeprom_update_byte((uint8_t*)EEPROM_UVLO,0);
  3772. enquecommand_P(PSTR("M24"));
  3773. }
  3774. else if (code_seen_P(PSTR("MMURES"))) // PRUSA MMURES
  3775. {
  3776. MMU2::mmu2.Reset(MMU2::MMU2::Software);
  3777. }
  3778. else if (code_seen_P(PSTR("RESET"))) { // PRUSA RESET
  3779. #ifdef WATCHDOG
  3780. #if defined(XFLASH) && defined(BOOTAPP)
  3781. boot_app_magic = BOOT_APP_MAGIC;
  3782. boot_app_flags = BOOT_APP_FLG_RUN;
  3783. #endif //defined(XFLASH) && defined(BOOTAPP)
  3784. softReset();
  3785. #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.
  3786. asm volatile("jmp 0x3E000");
  3787. #endif
  3788. }
  3789. #ifdef PRUSA_SN_SUPPORT
  3790. else if (code_seen_P(PSTR("SN"))) { // PRUSA SN
  3791. char SN[20];
  3792. eeprom_read_block(SN, (uint8_t*)EEPROM_PRUSA_SN, 20);
  3793. if (SN[19])
  3794. puts_P(PSTR("SN invalid"));
  3795. else
  3796. puts(SN);
  3797. }
  3798. #endif //PRUSA_SN_SUPPORT
  3799. else if(code_seen_P(PSTR("Fir"))){ // PRUSA Fir
  3800. SERIAL_PROTOCOLLN(FW_VERSION_FULL);
  3801. } else if(code_seen_P(PSTR("Rev"))){ // PRUSA Rev
  3802. SERIAL_PROTOCOLLN(FILAMENT_SIZE "-" ELECTRONICS "-" NOZZLE_TYPE );
  3803. } else if(code_seen_P(PSTR("Lang"))) { // PRUSA Lang
  3804. lang_reset();
  3805. } else if(code_seen_P(PSTR("Lz"))) { // PRUSA Lz
  3806. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  3807. } else if(code_seen_P(PSTR("FR"))) { // PRUSA FR
  3808. // Factory full reset
  3809. factory_reset(0);
  3810. } else if(code_seen_P(PSTR("MBL"))) { // PRUSA MBL
  3811. // Change the MBL status without changing the logical Z position.
  3812. if(code_seen('V')) {
  3813. bool value = code_value_short();
  3814. st_synchronize();
  3815. if(value != mbl.active) {
  3816. mbl.active = value;
  3817. // Use plan_set_z_position to reset the physical values
  3818. plan_set_z_position(current_position[Z_AXIS]);
  3819. }
  3820. }
  3821. //-//
  3822. /*
  3823. } else if(code_seen("rrr")) {
  3824. MYSERIAL.println("=== checking ===");
  3825. MYSERIAL.println(eeprom_read_byte((uint8_t*)EEPROM_CHECK_MODE),DEC);
  3826. MYSERIAL.println(eeprom_read_byte((uint8_t*)EEPROM_NOZZLE_DIAMETER),DEC);
  3827. MYSERIAL.println(eeprom_read_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM),DEC);
  3828. MYSERIAL.println(farm_mode,DEC);
  3829. MYSERIAL.println(eCheckMode,DEC);
  3830. } else if(code_seen("www")) {
  3831. MYSERIAL.println("=== @ FF ===");
  3832. eeprom_update_byte((uint8_t*)EEPROM_CHECK_MODE,0xFF);
  3833. eeprom_update_byte((uint8_t*)EEPROM_NOZZLE_DIAMETER,0xFF);
  3834. eeprom_update_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM,0xFFFF);
  3835. */
  3836. } else if (code_seen_P(PSTR("nozzle"))) { // PRUSA nozzle
  3837. uint16_t nDiameter;
  3838. if(code_seen('D'))
  3839. {
  3840. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  3841. nozzle_diameter_check(nDiameter);
  3842. }
  3843. else if(code_seen_P(PSTR("set")) && farm_mode)
  3844. {
  3845. strchr_pointer++; // skip 1st char (~ 's')
  3846. strchr_pointer++; // skip 2nd char (~ 'e')
  3847. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  3848. eeprom_update_byte((uint8_t*)EEPROM_NOZZLE_DIAMETER,(uint8_t)ClNozzleDiameter::_Diameter_Undef); // for correct synchronization after farm-mode exiting
  3849. eeprom_update_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM,nDiameter);
  3850. }
  3851. else SERIAL_PROTOCOLLN((float)eeprom_read_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM)/1000.0);
  3852. //-// !!! SupportMenu
  3853. /*
  3854. // musi byt PRED "PRUSA model"
  3855. } else if (code_seen("smodel")) { //! PRUSA smodel
  3856. size_t nOffset;
  3857. // ! -> "l"
  3858. strchr_pointer+=5*sizeof(*strchr_pointer); // skip 1st - 5th char (~ 'smode')
  3859. nOffset=strspn(strchr_pointer+1," \t\n\r\v\f");
  3860. if(*(strchr_pointer+1+nOffset))
  3861. printer_smodel_check(strchr_pointer);
  3862. else SERIAL_PROTOCOLLN(PRINTER_NAME);
  3863. } else if (code_seen("model")) { //! PRUSA model
  3864. uint16_t nPrinterModel;
  3865. strchr_pointer+=4*sizeof(*strchr_pointer); // skip 1st - 4th char (~ 'mode')
  3866. nPrinterModel=(uint16_t)code_value_long();
  3867. if(nPrinterModel!=0)
  3868. printer_model_check(nPrinterModel);
  3869. else SERIAL_PROTOCOLLN(PRINTER_TYPE);
  3870. } else if (code_seen("version")) { //! PRUSA version
  3871. strchr_pointer+=7*sizeof(*strchr_pointer); // skip 1st - 7th char (~ 'version')
  3872. while(*strchr_pointer==' ') // skip leading spaces
  3873. strchr_pointer++;
  3874. if(*strchr_pointer!=0)
  3875. fw_version_check(strchr_pointer);
  3876. else SERIAL_PROTOCOLLN(FW_VERSION);
  3877. } else if (code_seen("gcode")) { //! PRUSA gcode
  3878. uint16_t nGcodeLevel;
  3879. strchr_pointer+=4*sizeof(*strchr_pointer); // skip 1st - 4th char (~ 'gcod')
  3880. nGcodeLevel=(uint16_t)code_value_long();
  3881. if(nGcodeLevel!=0)
  3882. gcode_level_check(nGcodeLevel);
  3883. else SERIAL_PROTOCOLLN(GCODE_LEVEL);
  3884. */
  3885. }
  3886. //else if (code_seen('Cal')) {
  3887. // lcd_calibration();
  3888. // }
  3889. }
  3890. // This prevents reading files with "^" in their names.
  3891. // Since it is unclear, if there is some usage of this construct,
  3892. // it will be deprecated in 3.9 alpha a possibly completely removed in the future:
  3893. // else if (code_seen('^')) {
  3894. // // nothing, this is a version line
  3895. // }
  3896. else if(code_seen('G'))
  3897. {
  3898. gcode_in_progress = code_value_short();
  3899. // printf_P(_N("BEGIN G-CODE=%u\n"), gcode_in_progress);
  3900. switch (gcode_in_progress)
  3901. {
  3902. /*!
  3903. ---------------------------------------------------------------------------------
  3904. # G Codes
  3905. ### G0, G1 - Coordinated movement X Y Z E <a href="https://reprap.org/wiki/G-code#G0_.26_G1:_Move">G0 & G1: Move</a>
  3906. In Prusa Firmware G0 and G1 are the same.
  3907. #### Usage
  3908. G0 [ X | Y | Z | E | F | S ]
  3909. G1 [ X | Y | Z | E | F | S ]
  3910. #### Parameters
  3911. - `X` - The position to move to on the X axis
  3912. - `Y` - The position to move to on the Y axis
  3913. - `Z` - The position to move to on the Z axis
  3914. - `E` - The amount to extrude between the starting point and ending point
  3915. - `F` - The feedrate per minute of the move between the starting point and ending point (if supplied)
  3916. */
  3917. case 0: // G0 -> G1
  3918. case 1: // G1
  3919. {
  3920. uint16_t start_segment_idx = restore_interrupted_gcode();
  3921. get_coordinates(); // For X Y Z E F
  3922. if (total_filament_used > ((current_position[E_AXIS] - destination[E_AXIS]) * 100)) { //protection against total_filament_used overflow
  3923. total_filament_used = total_filament_used + ((destination[E_AXIS] - current_position[E_AXIS]) * 100);
  3924. }
  3925. #ifdef FWRETRACT
  3926. if(cs.autoretract_enabled) {
  3927. if( !(code_seen('X') || code_seen('Y') || code_seen('Z')) && code_seen('E')) {
  3928. float echange=destination[E_AXIS]-current_position[E_AXIS];
  3929. if((echange<-MIN_RETRACT && !retracted[active_extruder]) || (echange>MIN_RETRACT && retracted[active_extruder])) { //move appears to be an attempt to retract or recover
  3930. st_synchronize();
  3931. current_position[E_AXIS] = destination[E_AXIS]; //hide the slicer-generated retract/recover from calculations
  3932. plan_set_e_position(current_position[E_AXIS]); //AND from the planner
  3933. retract(!retracted[active_extruder]);
  3934. return;
  3935. }
  3936. }
  3937. }
  3938. #endif //FWRETRACT
  3939. prepare_move(start_segment_idx);
  3940. //ClearToSend();
  3941. }
  3942. break;
  3943. /*!
  3944. ### 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>
  3945. These commands don't propperly work with MBL enabled. The compensation only happens at the end of the move, so avoid long arcs.
  3946. #### Usage
  3947. G2 [ X | Y | I | E | F ] (Clockwise Arc)
  3948. G3 [ X | Y | I | E | F ] (Counter-Clockwise Arc)
  3949. #### Parameters
  3950. - `X` - The position to move to on the X axis
  3951. - `Y` - The position to move to on the Y axis
  3952. - 'Z' - The position to move to on the Z axis
  3953. - `I` - The point in X space from the current X position to maintain a constant distance from
  3954. - `J` - The point in Y space from the current Y position to maintain a constant distance from
  3955. - `E` - The amount to extrude between the starting point and ending point
  3956. - `F` - The feedrate per minute of the move between the starting point and ending point (if supplied)
  3957. */
  3958. case 2:
  3959. case 3:
  3960. {
  3961. uint16_t start_segment_idx = restore_interrupted_gcode();
  3962. #ifdef SF_ARC_FIX
  3963. bool relative_mode_backup = relative_mode;
  3964. relative_mode = true;
  3965. #endif
  3966. get_coordinates(); // For X Y Z E F
  3967. #ifdef SF_ARC_FIX
  3968. relative_mode=relative_mode_backup;
  3969. #endif
  3970. offset[0] = code_seen('I') ? code_value() : 0.f;
  3971. offset[1] = code_seen('J') ? code_value() : 0.f;
  3972. prepare_arc_move((gcode_in_progress == 2), start_segment_idx);
  3973. } break;
  3974. /*!
  3975. ### G4 - Dwell <a href="https://reprap.org/wiki/G-code#G4:_Dwell">G4: Dwell</a>
  3976. Pause the machine for a period of time.
  3977. #### Usage
  3978. G4 [ P | S ]
  3979. #### Parameters
  3980. - `P` - Time to wait, in milliseconds
  3981. - `S` - Time to wait, in seconds
  3982. */
  3983. case 4:
  3984. codenum = 0;
  3985. if(code_seen('P')) codenum = code_value(); // milliseconds to wait
  3986. if(code_seen('S')) codenum = code_value() * 1000; // seconds to wait
  3987. if(codenum != 0)
  3988. {
  3989. if(custom_message_type != CustomMsg::M117)
  3990. {
  3991. LCD_MESSAGERPGM(_n("Sleep..."));////MSG_DWELL
  3992. }
  3993. }
  3994. st_synchronize();
  3995. codenum += _millis(); // keep track of when we started waiting
  3996. previous_millis_cmd.start();
  3997. while(_millis() < codenum) {
  3998. manage_heater();
  3999. manage_inactivity();
  4000. lcd_update(0);
  4001. }
  4002. break;
  4003. #ifdef FWRETRACT
  4004. /*!
  4005. ### G10 - Retract <a href="https://reprap.org/wiki/G-code#G10:_Retract">G10: Retract</a>
  4006. Retracts filament according to settings of `M207`
  4007. */
  4008. case 10:
  4009. #if EXTRUDERS > 1
  4010. retracted_swap[active_extruder]=(code_seen('S') && code_value_long() == 1); // checks for swap retract argument
  4011. retract(true,retracted_swap[active_extruder]);
  4012. #else
  4013. retract(true);
  4014. #endif
  4015. break;
  4016. /*!
  4017. ### G11 - Retract recover <a href="https://reprap.org/wiki/G-code#G11:_Unretract">G11: Unretract</a>
  4018. Unretracts/recovers filament according to settings of `M208`
  4019. */
  4020. case 11:
  4021. #if EXTRUDERS > 1
  4022. retract(false,retracted_swap[active_extruder]);
  4023. #else
  4024. retract(false);
  4025. #endif
  4026. break;
  4027. #endif //FWRETRACT
  4028. /*!
  4029. ### G21 - Sets Units to Millimters <a href="https://reprap.org/wiki/G-code#G21:_Set_Units_to_Millimeters">G21: Set Units to Millimeters</a>
  4030. Units are in millimeters. Prusa doesn't support inches.
  4031. */
  4032. case 21:
  4033. break; //Doing nothing. This is just to prevent serial UNKOWN warnings.
  4034. /*!
  4035. ### 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>
  4036. 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).
  4037. #### Usage
  4038. G28 [ X | Y | Z | W | C ]
  4039. #### Parameters
  4040. - `X` - Flag to go back to the X axis origin
  4041. - `Y` - Flag to go back to the Y axis origin
  4042. - `Z` - Flag to go back to the Z axis origin
  4043. - `W` - Suppress mesh bed leveling if `X`, `Y` or `Z` are not provided
  4044. - `C` - Calibrate X and Y origin (home) - Only on MK3/s
  4045. */
  4046. case 28:
  4047. {
  4048. long home_x_value = 0;
  4049. long home_y_value = 0;
  4050. long home_z_value = 0;
  4051. // Which axes should be homed?
  4052. bool home_x = code_seen(axis_codes[X_AXIS]);
  4053. if (home_x) home_x_value = code_value_long();
  4054. bool home_y = code_seen(axis_codes[Y_AXIS]);
  4055. if (home_y) home_y_value = code_value_long();
  4056. bool home_z = code_seen(axis_codes[Z_AXIS]);
  4057. if (home_z) home_z_value = code_value_long();
  4058. bool without_mbl = code_seen('W');
  4059. // calibrate?
  4060. #ifdef TMC2130
  4061. bool calib = code_seen('C');
  4062. gcode_G28(home_x, home_x_value, home_y, home_y_value, home_z, home_z_value, calib, without_mbl);
  4063. #else
  4064. gcode_G28(home_x, home_x_value, home_y, home_y_value, home_z, home_z_value, without_mbl);
  4065. #endif //TMC2130
  4066. if ((home_x || home_y || without_mbl || home_z) == false) {
  4067. gcode_G80();
  4068. }
  4069. break;
  4070. }
  4071. #ifdef ENABLE_AUTO_BED_LEVELING
  4072. /*!
  4073. ### G29 - Detailed Z-Probe <a href="https://reprap.org/wiki/G-code#G29:_Detailed_Z-Probe">G29: Detailed Z-Probe</a>
  4074. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4075. See `G81`
  4076. */
  4077. case 29:
  4078. {
  4079. #if Z_MIN_PIN == -1
  4080. #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."
  4081. #endif
  4082. // Prevent user from running a G29 without first homing in X and Y
  4083. if (! (axis_known_position[X_AXIS] && axis_known_position[Y_AXIS]) )
  4084. {
  4085. LCD_MESSAGERPGM(MSG_POSITION_UNKNOWN);
  4086. SERIAL_ECHO_START;
  4087. SERIAL_ECHOLNRPGM(MSG_POSITION_UNKNOWN);
  4088. break; // abort G29, since we don't know where we are
  4089. }
  4090. st_synchronize();
  4091. // make sure the bed_level_rotation_matrix is identity or the planner will get it incorectly
  4092. //vector_3 corrected_position = plan_get_position_mm();
  4093. //corrected_position.debug("position before G29");
  4094. plan_bed_level_matrix.set_to_identity();
  4095. vector_3 uncorrected_position = plan_get_position();
  4096. //uncorrected_position.debug("position durring G29");
  4097. current_position[X_AXIS] = uncorrected_position.x;
  4098. current_position[Y_AXIS] = uncorrected_position.y;
  4099. current_position[Z_AXIS] = uncorrected_position.z;
  4100. plan_set_position_curposXYZE();
  4101. int l_feedmultiply = setup_for_endstop_move();
  4102. feedrate = homing_feedrate[Z_AXIS];
  4103. #ifdef AUTO_BED_LEVELING_GRID
  4104. // probe at the points of a lattice grid
  4105. int xGridSpacing = (RIGHT_PROBE_BED_POSITION - LEFT_PROBE_BED_POSITION) / (AUTO_BED_LEVELING_GRID_POINTS-1);
  4106. int yGridSpacing = (BACK_PROBE_BED_POSITION - FRONT_PROBE_BED_POSITION) / (AUTO_BED_LEVELING_GRID_POINTS-1);
  4107. // solve the plane equation ax + by + d = z
  4108. // A is the matrix with rows [x y 1] for all the probed points
  4109. // B is the vector of the Z positions
  4110. // 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
  4111. // so Vx = -a Vy = -b Vz = 1 (we want the vector facing towards positive Z
  4112. // "A" matrix of the linear system of equations
  4113. double eqnAMatrix[AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS*3];
  4114. // "B" vector of Z points
  4115. double eqnBVector[AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS];
  4116. int probePointCounter = 0;
  4117. bool zig = true;
  4118. for (int yProbe=FRONT_PROBE_BED_POSITION; yProbe <= BACK_PROBE_BED_POSITION; yProbe += yGridSpacing)
  4119. {
  4120. int xProbe, xInc;
  4121. if (zig)
  4122. {
  4123. xProbe = LEFT_PROBE_BED_POSITION;
  4124. //xEnd = RIGHT_PROBE_BED_POSITION;
  4125. xInc = xGridSpacing;
  4126. zig = false;
  4127. } else // zag
  4128. {
  4129. xProbe = RIGHT_PROBE_BED_POSITION;
  4130. //xEnd = LEFT_PROBE_BED_POSITION;
  4131. xInc = -xGridSpacing;
  4132. zig = true;
  4133. }
  4134. for (int xCount=0; xCount < AUTO_BED_LEVELING_GRID_POINTS; xCount++)
  4135. {
  4136. float z_before;
  4137. if (probePointCounter == 0)
  4138. {
  4139. // raise before probing
  4140. z_before = Z_RAISE_BEFORE_PROBING;
  4141. } else
  4142. {
  4143. // raise extruder
  4144. z_before = current_position[Z_AXIS] + Z_RAISE_BETWEEN_PROBINGS;
  4145. }
  4146. float measured_z = probe_pt(xProbe, yProbe, z_before);
  4147. eqnBVector[probePointCounter] = measured_z;
  4148. eqnAMatrix[probePointCounter + 0*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = xProbe;
  4149. eqnAMatrix[probePointCounter + 1*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = yProbe;
  4150. eqnAMatrix[probePointCounter + 2*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = 1;
  4151. probePointCounter++;
  4152. xProbe += xInc;
  4153. }
  4154. }
  4155. clean_up_after_endstop_move(l_feedmultiply);
  4156. // solve lsq problem
  4157. double *plane_equation_coefficients = qr_solve(AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS, 3, eqnAMatrix, eqnBVector);
  4158. SERIAL_PROTOCOLPGM("Eqn coefficients: a: ");
  4159. SERIAL_PROTOCOL(plane_equation_coefficients[0]);
  4160. SERIAL_PROTOCOLPGM(" b: ");
  4161. SERIAL_PROTOCOL(plane_equation_coefficients[1]);
  4162. SERIAL_PROTOCOLPGM(" d: ");
  4163. SERIAL_PROTOCOLLN(plane_equation_coefficients[2]);
  4164. set_bed_level_equation_lsq(plane_equation_coefficients);
  4165. free(plane_equation_coefficients);
  4166. #else // AUTO_BED_LEVELING_GRID not defined
  4167. // Probe at 3 arbitrary points
  4168. // probe 1
  4169. float z_at_pt_1 = probe_pt(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, Z_RAISE_BEFORE_PROBING);
  4170. // probe 2
  4171. 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);
  4172. // probe 3
  4173. 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);
  4174. clean_up_after_endstop_move(l_feedmultiply);
  4175. set_bed_level_equation_3pts(z_at_pt_1, z_at_pt_2, z_at_pt_3);
  4176. #endif // AUTO_BED_LEVELING_GRID
  4177. st_synchronize();
  4178. // The following code correct the Z height difference from z-probe position and hotend tip position.
  4179. // The Z height on homing is measured by Z-Probe, but the probe is quite far from the hotend.
  4180. // When the bed is uneven, this height must be corrected.
  4181. 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)
  4182. x_tmp = current_position[X_AXIS] + X_PROBE_OFFSET_FROM_EXTRUDER;
  4183. y_tmp = current_position[Y_AXIS] + Y_PROBE_OFFSET_FROM_EXTRUDER;
  4184. z_tmp = current_position[Z_AXIS];
  4185. apply_rotation_xyz(plan_bed_level_matrix, x_tmp, y_tmp, z_tmp); //Apply the correction sending the probe offset
  4186. current_position[Z_AXIS] = z_tmp - real_z + current_position[Z_AXIS]; //The difference is added to current position and sent to planner.
  4187. plan_set_position_curposXYZE();
  4188. }
  4189. break;
  4190. #ifndef Z_PROBE_SLED
  4191. /*!
  4192. ### G30 - Single Z Probe <a href="https://reprap.org/wiki/G-code#G30:_Single_Z-Probe">G30: Single Z-Probe</a>
  4193. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4194. */
  4195. case 30:
  4196. {
  4197. st_synchronize();
  4198. // TODO: make sure the bed_level_rotation_matrix is identity or the planner will get set incorectly
  4199. int l_feedmultiply = setup_for_endstop_move();
  4200. feedrate = homing_feedrate[Z_AXIS];
  4201. run_z_probe();
  4202. SERIAL_PROTOCOLPGM(_T(MSG_BED));
  4203. SERIAL_PROTOCOLPGM(" X: ");
  4204. SERIAL_PROTOCOL(current_position[X_AXIS]);
  4205. SERIAL_PROTOCOLPGM(" Y: ");
  4206. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  4207. SERIAL_PROTOCOLPGM(" Z: ");
  4208. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  4209. SERIAL_PROTOCOLPGM("\n");
  4210. clean_up_after_endstop_move(l_feedmultiply);
  4211. }
  4212. break;
  4213. #else
  4214. /*!
  4215. ### G31 - Dock the sled <a href="https://reprap.org/wiki/G-code#G31:_Dock_Z_Probe_sled">G31: Dock Z Probe sled</a>
  4216. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4217. */
  4218. case 31:
  4219. dock_sled(true);
  4220. break;
  4221. /*!
  4222. ### G32 - Undock the sled <a href="https://reprap.org/wiki/G-code#G32:_Undock_Z_Probe_sled">G32: Undock Z Probe sled</a>
  4223. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4224. */
  4225. case 32:
  4226. dock_sled(false);
  4227. break;
  4228. #endif // Z_PROBE_SLED
  4229. #endif // ENABLE_AUTO_BED_LEVELING
  4230. #ifdef MESH_BED_LEVELING
  4231. /*!
  4232. ### G30 - Single Z Probe <a href="https://reprap.org/wiki/G-code#G30:_Single_Z-Probe">G30: Single Z-Probe</a>
  4233. Sensor must be over the bed.
  4234. The maximum travel distance before an error is triggered is 10mm.
  4235. */
  4236. case 30:
  4237. {
  4238. st_synchronize();
  4239. homing_flag = true;
  4240. // TODO: make sure the bed_level_rotation_matrix is identity or the planner will get set incorectly
  4241. int l_feedmultiply = setup_for_endstop_move();
  4242. feedrate = homing_feedrate[Z_AXIS];
  4243. find_bed_induction_sensor_point_z(-10.f, 3);
  4244. printf_P(_N("%S X: %.5f Y: %.5f Z: %.5f\n"), _T(MSG_BED), _x, _y, _z);
  4245. clean_up_after_endstop_move(l_feedmultiply);
  4246. homing_flag = false;
  4247. }
  4248. break;
  4249. /*!
  4250. ### G75 - Print temperature interpolation <a href="https://reprap.org/wiki/G-code#G75:_Print_temperature_interpolation">G75: Print temperature interpolation</a>
  4251. Show/print PINDA temperature interpolating.
  4252. */
  4253. case 75:
  4254. {
  4255. for (uint8_t i = 40; i <= 110; i++)
  4256. printf_P(_N("%d %.2f"), i, temp_comp_interpolation(i));
  4257. }
  4258. break;
  4259. /*!
  4260. ### G76 - PINDA probe temperature calibration <a href="https://reprap.org/wiki/G-code#G76:_PINDA_probe_temperature_calibration">G76: PINDA probe temperature calibration</a>
  4261. This G-code is used to calibrate the temperature drift of the PINDA (inductive Sensor).
  4262. The PINDAv2 sensor has a built-in thermistor which has the advantage that the calibration can be done once for all materials.
  4263. The Original i3 Prusa MK2/s uses PINDAv1 and this calibration improves the temperature drift, but not as good as the PINDAv2.
  4264. superPINDA sensor has internal temperature compensation and no thermistor output. There is no point of doing temperature calibration in such case.
  4265. If PINDA_THERMISTOR and SUPERPINDA_SUPPORT is defined during compilation, calibration is skipped with serial message "No PINDA thermistor".
  4266. This can be caused also if PINDA thermistor connection is broken or PINDA temperature is lower than PINDA_MINTEMP.
  4267. #### Example
  4268. ```
  4269. G76
  4270. echo PINDA probe calibration start
  4271. echo start temperature: 35.0°
  4272. echo ...
  4273. echo PINDA temperature -- Z shift (mm): 0.---
  4274. ```
  4275. */
  4276. case 76:
  4277. {
  4278. #ifdef PINDA_THERMISTOR
  4279. if (!has_temperature_compensation())
  4280. {
  4281. SERIAL_ECHOLNPGM("No PINDA thermistor");
  4282. break;
  4283. }
  4284. if (calibration_status() >= CALIBRATION_STATUS_XYZ_CALIBRATION) {
  4285. //we need to know accurate position of first calibration point
  4286. //if xyz calibration was not performed yet, interrupt temperature calibration and inform user that xyz cal. is needed
  4287. lcd_show_fullscreen_message_and_wait_P(_i("Please run XYZ calibration first.")); ////MSG_RUN_XYZ c=20 r=4
  4288. break;
  4289. }
  4290. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS]))
  4291. {
  4292. // We don't know where we are! HOME!
  4293. // Push the commands to the front of the message queue in the reverse order!
  4294. // There shall be always enough space reserved for these commands.
  4295. repeatcommand_front(); // repeat G76 with all its parameters
  4296. enquecommand_front_P(G28W0);
  4297. break;
  4298. }
  4299. 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
  4300. bool result = lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_STEEL_SHEET_CHECK), false, false);
  4301. if (result)
  4302. {
  4303. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4304. plan_buffer_line_curposXYZE(3000 / 60);
  4305. current_position[Z_AXIS] = 50;
  4306. current_position[Y_AXIS] = 180;
  4307. plan_buffer_line_curposXYZE(3000 / 60);
  4308. st_synchronize();
  4309. lcd_show_fullscreen_message_and_wait_P(_T(MSG_REMOVE_STEEL_SHEET));
  4310. current_position[Y_AXIS] = pgm_read_float(bed_ref_points_4 + 1);
  4311. current_position[X_AXIS] = pgm_read_float(bed_ref_points_4);
  4312. plan_buffer_line_curposXYZE(3000 / 60);
  4313. st_synchronize();
  4314. gcode_G28(false, false, true);
  4315. }
  4316. if ((current_temperature_pinda > 35) && (farm_mode == false)) {
  4317. //waiting for PIDNA probe to cool down in case that we are not in farm mode
  4318. current_position[Z_AXIS] = 100;
  4319. plan_buffer_line_curposXYZE(3000 / 60);
  4320. if (lcd_wait_for_pinda(35) == false) { //waiting for PINDA probe to cool, if this takes more then time expected, temp. cal. fails
  4321. lcd_temp_cal_show_result(false);
  4322. break;
  4323. }
  4324. }
  4325. st_synchronize();
  4326. homing_flag = true; // keep homing on to avoid babystepping while the LCD is enabled
  4327. lcd_update_enable(true);
  4328. SERIAL_ECHOLNPGM("PINDA probe calibration start");
  4329. float zero_z;
  4330. int z_shift = 0; //unit: steps
  4331. float start_temp = 5 * (int)(current_temperature_pinda / 5);
  4332. if (start_temp < 35) start_temp = 35;
  4333. if (start_temp < current_temperature_pinda) start_temp += 5;
  4334. printf_P(_N("start temperature: %.1f\n"), start_temp);
  4335. // setTargetHotend(200, 0);
  4336. setTargetBed(70 + (start_temp - 30));
  4337. custom_message_type = CustomMsg::TempCal;
  4338. custom_message_state = 1;
  4339. lcd_setstatuspgm(_T(MSG_PINDA_CALIBRATION));
  4340. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4341. plan_buffer_line_curposXYZE(3000 / 60);
  4342. current_position[X_AXIS] = PINDA_PREHEAT_X;
  4343. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  4344. plan_buffer_line_curposXYZE(3000 / 60);
  4345. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  4346. plan_buffer_line_curposXYZE(3000 / 60);
  4347. st_synchronize();
  4348. while (current_temperature_pinda < start_temp)
  4349. {
  4350. delay_keep_alive(1000);
  4351. serialecho_temperatures();
  4352. }
  4353. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0); //invalidate temp. calibration in case that in will be aborted during the calibration process
  4354. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4355. plan_buffer_line_curposXYZE(3000 / 60);
  4356. current_position[X_AXIS] = pgm_read_float(bed_ref_points_4);
  4357. current_position[Y_AXIS] = pgm_read_float(bed_ref_points_4 + 1);
  4358. plan_buffer_line_curposXYZE(3000 / 60);
  4359. st_synchronize();
  4360. bool find_z_result = find_bed_induction_sensor_point_z(-1.f);
  4361. if (find_z_result == false) {
  4362. lcd_temp_cal_show_result(find_z_result);
  4363. homing_flag = false;
  4364. break;
  4365. }
  4366. zero_z = current_position[Z_AXIS];
  4367. printf_P(_N("\nZERO: %.3f\n"), current_position[Z_AXIS]);
  4368. int i = -1; for (; i < 5; i++)
  4369. {
  4370. float temp = (40 + i * 5);
  4371. printf_P(_N("\nStep: %d/6 (skipped)\nPINDA temperature: %d Z shift (mm):0\n"), i + 2, (40 + i*5));
  4372. if (i >= 0) {
  4373. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  4374. }
  4375. if (start_temp <= temp) break;
  4376. }
  4377. for (i++; i < 5; i++)
  4378. {
  4379. float temp = (40 + i * 5);
  4380. printf_P(_N("\nStep: %d/6\n"), i + 2);
  4381. custom_message_state = i + 2;
  4382. setTargetBed(50 + 10 * (temp - 30) / 5);
  4383. // setTargetHotend(255, 0);
  4384. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4385. plan_buffer_line_curposXYZE(3000 / 60);
  4386. current_position[X_AXIS] = PINDA_PREHEAT_X;
  4387. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  4388. plan_buffer_line_curposXYZE(3000 / 60);
  4389. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  4390. plan_buffer_line_curposXYZE(3000 / 60);
  4391. st_synchronize();
  4392. while (current_temperature_pinda < temp)
  4393. {
  4394. delay_keep_alive(1000);
  4395. serialecho_temperatures();
  4396. }
  4397. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4398. plan_buffer_line_curposXYZE(3000 / 60);
  4399. current_position[X_AXIS] = pgm_read_float(bed_ref_points_4);
  4400. current_position[Y_AXIS] = pgm_read_float(bed_ref_points_4 + 1);
  4401. plan_buffer_line_curposXYZE(3000 / 60);
  4402. st_synchronize();
  4403. find_z_result = find_bed_induction_sensor_point_z(-1.f);
  4404. if (find_z_result == false) {
  4405. lcd_temp_cal_show_result(find_z_result);
  4406. break;
  4407. }
  4408. z_shift = (int)((current_position[Z_AXIS] - zero_z)*cs.axis_steps_per_unit[Z_AXIS]);
  4409. printf_P(_N("\nPINDA temperature: %.1f Z shift (mm): %.3f"), current_temperature_pinda, current_position[Z_AXIS] - zero_z);
  4410. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  4411. }
  4412. lcd_temp_cal_show_result(true);
  4413. homing_flag = false;
  4414. #else //PINDA_THERMISTOR
  4415. setTargetBed(PINDA_MIN_T);
  4416. float zero_z;
  4417. int z_shift = 0; //unit: steps
  4418. int t_c; // temperature
  4419. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  4420. // We don't know where we are! HOME!
  4421. // Push the commands to the front of the message queue in the reverse order!
  4422. // There shall be always enough space reserved for these commands.
  4423. repeatcommand_front(); // repeat G76 with all its parameters
  4424. enquecommand_front_P(G28W0);
  4425. break;
  4426. }
  4427. puts_P(_N("PINDA probe calibration start"));
  4428. custom_message_type = CustomMsg::TempCal;
  4429. custom_message_state = 1;
  4430. lcd_setstatuspgm(_T(MSG_PINDA_CALIBRATION));
  4431. current_position[X_AXIS] = PINDA_PREHEAT_X;
  4432. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  4433. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  4434. plan_buffer_line_curposXYZE(3000 / 60);
  4435. st_synchronize();
  4436. while (fabs(degBed() - PINDA_MIN_T) > 1) {
  4437. delay_keep_alive(1000);
  4438. serialecho_temperatures();
  4439. }
  4440. //enquecommand_P(PSTR("M190 S50"));
  4441. for (int i = 0; i < PINDA_HEAT_T; i++) {
  4442. delay_keep_alive(1000);
  4443. serialecho_temperatures();
  4444. }
  4445. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0); //invalidate temp. calibration in case that in will be aborted during the calibration process
  4446. current_position[Z_AXIS] = 5;
  4447. plan_buffer_line_curposXYZE(3000 / 60);
  4448. current_position[X_AXIS] = BED_X0;
  4449. current_position[Y_AXIS] = BED_Y0;
  4450. plan_buffer_line_curposXYZE(3000 / 60);
  4451. st_synchronize();
  4452. find_bed_induction_sensor_point_z(-1.f);
  4453. zero_z = current_position[Z_AXIS];
  4454. printf_P(_N("\nZERO: %.3f\n"), current_position[Z_AXIS]);
  4455. for (int i = 0; i<5; i++) {
  4456. printf_P(_N("\nStep: %d/6\n"), i + 2);
  4457. custom_message_state = i + 2;
  4458. t_c = 60 + i * 10;
  4459. setTargetBed(t_c);
  4460. current_position[X_AXIS] = PINDA_PREHEAT_X;
  4461. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  4462. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  4463. plan_buffer_line_curposXYZE(3000 / 60);
  4464. st_synchronize();
  4465. while (degBed() < t_c) {
  4466. delay_keep_alive(1000);
  4467. serialecho_temperatures();
  4468. }
  4469. for (int i = 0; i < PINDA_HEAT_T; i++) {
  4470. delay_keep_alive(1000);
  4471. serialecho_temperatures();
  4472. }
  4473. current_position[Z_AXIS] = 5;
  4474. plan_buffer_line_curposXYZE(3000 / 60);
  4475. current_position[X_AXIS] = BED_X0;
  4476. current_position[Y_AXIS] = BED_Y0;
  4477. plan_buffer_line_curposXYZE(3000 / 60);
  4478. st_synchronize();
  4479. find_bed_induction_sensor_point_z(-1.f);
  4480. z_shift = (int)((current_position[Z_AXIS] - zero_z)*cs.axis_steps_per_unit[Z_AXIS]);
  4481. printf_P(_N("\nTemperature: %d Z shift (mm): %.3f\n"), t_c, current_position[Z_AXIS] - zero_z);
  4482. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  4483. }
  4484. custom_message_type = CustomMsg::Status;
  4485. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  4486. puts_P(_N("Temperature calibration done."));
  4487. disable_x();
  4488. disable_y();
  4489. disable_z();
  4490. disable_e0();
  4491. disable_e1();
  4492. disable_e2();
  4493. setTargetBed(0); //set bed target temperature back to 0
  4494. lcd_show_fullscreen_message_and_wait_P(_T(MSG_PINDA_CALIBRATION_DONE));
  4495. eeprom_update_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE, 1);
  4496. lcd_update_enable(true);
  4497. lcd_update(2);
  4498. #endif //PINDA_THERMISTOR
  4499. }
  4500. break;
  4501. /*!
  4502. ### G80 - Mesh-based Z probe <a href="https://reprap.org/wiki/G-code#G80:_Mesh-based_Z_probe">G80: Mesh-based Z probe</a>
  4503. Default 3x3 grid can be changed on MK2.5/s and MK3/s to 7x7 grid.
  4504. #### Usage
  4505. G80 [ N | R | V | L | R | F | B ]
  4506. #### Parameters
  4507. - `N` - Number of mesh points on x axis. Default is 3. Valid values are 3 and 7.
  4508. - `R` - Probe retries. Default 3 max. 10
  4509. - `V` - Verbosity level 1=low, 10=mid, 20=high. It only can be used if the firmware has been compiled with SUPPORT_VERBOSITY active.
  4510. Using the following parameters enables additional "manual" bed leveling correction. Valid values are -100 microns to 100 microns.
  4511. #### Additional Parameters
  4512. - `L` - Left Bed Level correct value in um.
  4513. - `R` - Right Bed Level correct value in um.
  4514. - `F` - Front Bed Level correct value in um.
  4515. - `B` - Back Bed Level correct value in um.
  4516. */
  4517. /*
  4518. * Probes a grid and produces a mesh to compensate for variable bed height
  4519. * The S0 report the points as below
  4520. * +----> X-axis
  4521. * |
  4522. * |
  4523. * v Y-axis
  4524. */
  4525. case 80: {
  4526. gcode_G80();
  4527. }
  4528. break;
  4529. /*!
  4530. ### G81 - Mesh bed leveling status <a href="https://reprap.org/wiki/G-code#G81:_Mesh_bed_leveling_status">G81: Mesh bed leveling status</a>
  4531. Prints mesh bed leveling status and bed profile if activated.
  4532. */
  4533. case 81:
  4534. if (mbl.active) {
  4535. SERIAL_PROTOCOLPGM("Num X,Y: ");
  4536. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  4537. SERIAL_PROTOCOL(',');
  4538. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  4539. SERIAL_PROTOCOLPGM("\nZ search height: ");
  4540. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  4541. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  4542. for (uint8_t y = MESH_NUM_Y_POINTS; y-- > 0;) {
  4543. for (uint8_t x = 0; x < MESH_NUM_X_POINTS; x++) {
  4544. SERIAL_PROTOCOLPGM(" ");
  4545. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  4546. }
  4547. SERIAL_PROTOCOLLN();
  4548. }
  4549. }
  4550. else
  4551. SERIAL_PROTOCOLLNPGM("Mesh bed leveling not active.");
  4552. break;
  4553. #if 0
  4554. /*!
  4555. ### 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>
  4556. WARNING! USE WITH CAUTION! If you'll try to probe where is no leveling pad, nasty things can happen!
  4557. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4558. */
  4559. case 82:
  4560. SERIAL_PROTOCOLLNPGM("Finding bed ");
  4561. int l_feedmultiply = setup_for_endstop_move();
  4562. find_bed_induction_sensor_point_z();
  4563. clean_up_after_endstop_move(l_feedmultiply);
  4564. SERIAL_PROTOCOLPGM("Bed found at: ");
  4565. SERIAL_PROTOCOL_F(current_position[Z_AXIS], 5);
  4566. SERIAL_PROTOCOLPGM("\n");
  4567. break;
  4568. /*!
  4569. ### 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>
  4570. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4571. */
  4572. case 83:
  4573. {
  4574. int babystepz = code_seen('S') ? code_value() : 0;
  4575. int BabyPosition = code_seen('P') ? code_value() : 0;
  4576. if (babystepz != 0) {
  4577. //FIXME Vojtech: What shall be the index of the axis Z: 3 or 4?
  4578. // Is the axis indexed starting with zero or one?
  4579. if (BabyPosition > 4) {
  4580. SERIAL_PROTOCOLLNPGM("Index out of bounds");
  4581. }else{
  4582. // Save it to the eeprom
  4583. babystepLoadZ = babystepz;
  4584. eeprom_update_word((uint16_t*)EEPROM_BABYSTEP_Z0 + BabyPosition, babystepLoadZ);
  4585. // adjust the Z
  4586. babystepsTodoZadd(babystepLoadZ);
  4587. }
  4588. }
  4589. }
  4590. break;
  4591. /*!
  4592. ### 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>
  4593. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4594. */
  4595. case 84:
  4596. babystepsTodoZsubtract(babystepLoadZ);
  4597. // babystepLoadZ = 0;
  4598. break;
  4599. /*!
  4600. ### G85: Pick best babystep - Not active <a href="https://reprap.org/wiki/G-code#G85:_Pick_best_babystep">G85: Pick best babystep</a>
  4601. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4602. */
  4603. case 85:
  4604. lcd_pick_babystep();
  4605. break;
  4606. #endif
  4607. /*!
  4608. ### 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>
  4609. This G-code will be performed at the start of a calibration script.
  4610. (Prusa3D specific)
  4611. */
  4612. case 86:
  4613. calibration_status_store(CALIBRATION_STATUS_LIVE_ADJUST);
  4614. break;
  4615. /*!
  4616. ### 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>
  4617. This G-code will be performed at the end of a calibration script.
  4618. (Prusa3D specific)
  4619. */
  4620. case 87:
  4621. calibration_status_store(CALIBRATION_STATUS_CALIBRATED);
  4622. break;
  4623. /*!
  4624. ### G88 - Reserved <a href="https://reprap.org/wiki/G-code#G88:_Reserved">G88: Reserved</a>
  4625. Currently has no effect.
  4626. */
  4627. // Prusa3D specific: Don't know what it is for, it is in V2Calibration.gcode
  4628. case 88:
  4629. break;
  4630. #endif // ENABLE_MESH_BED_LEVELING
  4631. /*!
  4632. ### G90 - Switch off relative mode <a href="https://reprap.org/wiki/G-code#G90:_Set_to_Absolute_Positioning">G90: Set to Absolute Positioning</a>
  4633. All coordinates from now on are absolute relative to the origin of the machine. E axis is left intact.
  4634. */
  4635. case 90: {
  4636. axis_relative_modes &= ~(X_AXIS_MASK | Y_AXIS_MASK | Z_AXIS_MASK);
  4637. }
  4638. break;
  4639. /*!
  4640. ### G91 - Switch on relative mode <a href="https://reprap.org/wiki/G-code#G91:_Set_to_Relative_Positioning">G91: Set to Relative Positioning</a>
  4641. All coordinates from now on are relative to the last position. E axis is left intact.
  4642. */
  4643. case 91: {
  4644. axis_relative_modes |= X_AXIS_MASK | Y_AXIS_MASK | Z_AXIS_MASK;
  4645. }
  4646. break;
  4647. /*!
  4648. ### G92 - Set position <a href="https://reprap.org/wiki/G-code#G92:_Set_Position">G92: Set Position</a>
  4649. It is used for setting the current position of each axis. The parameters are always absolute to the origin.
  4650. If a parameter is omitted, that axis will not be affected.
  4651. 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`).
  4652. A G92 without coordinates will reset all axes to zero on some firmware. This is not the case for Prusa-Firmware!
  4653. #### Usage
  4654. G92 [ X | Y | Z | E ]
  4655. #### Parameters
  4656. - `X` - new X axis position
  4657. - `Y` - new Y axis position
  4658. - `Z` - new Z axis position
  4659. - `E` - new extruder position
  4660. */
  4661. case 92: {
  4662. gcode_G92();
  4663. }
  4664. break;
  4665. #ifdef PRUSA_FARM
  4666. /*!
  4667. ### G98 - Activate farm mode <a href="https://reprap.org/wiki/G-code#G98:_Activate_farm_mode">G98: Activate farm mode</a>
  4668. Enable Prusa-specific Farm functions and g-code.
  4669. See Internal Prusa commands.
  4670. */
  4671. case 98:
  4672. farm_gcode_g98();
  4673. break;
  4674. /*! ### G99 - Deactivate farm mode <a href="https://reprap.org/wiki/G-code#G99:_Deactivate_farm_mode">G99: Deactivate farm mode</a>
  4675. Disables Prusa-specific Farm functions and g-code.
  4676. */
  4677. case 99:
  4678. farm_gcode_g99();
  4679. break;
  4680. #endif //PRUSA_FARM
  4681. default:
  4682. printf_P(MSG_UNKNOWN_CODE, 'G', cmdbuffer + bufindr + CMDHDRSIZE);
  4683. }
  4684. // printf_P(_N("END G-CODE=%u\n"), gcode_in_progress);
  4685. gcode_in_progress = 0;
  4686. } // end if(code_seen('G'))
  4687. /*!
  4688. ### End of G-Codes
  4689. */
  4690. /*!
  4691. ---------------------------------------------------------------------------------
  4692. # M Commands
  4693. */
  4694. else if(code_seen('M'))
  4695. {
  4696. int index;
  4697. for (index = 1; *(strchr_pointer + index) == ' ' || *(strchr_pointer + index) == '\t'; index++);
  4698. /*for (++strchr_pointer; *strchr_pointer == ' ' || *strchr_pointer == '\t'; ++strchr_pointer);*/
  4699. if (*(strchr_pointer+index) < '0' || *(strchr_pointer+index) > '9') {
  4700. printf_P(PSTR("Invalid M code: %s\n"), cmdbuffer + bufindr + CMDHDRSIZE);
  4701. } else
  4702. {
  4703. mcode_in_progress = code_value_short();
  4704. // printf_P(_N("BEGIN M-CODE=%u\n"), mcode_in_progress);
  4705. switch(mcode_in_progress)
  4706. {
  4707. /*!
  4708. ### 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>
  4709. */
  4710. case 17:
  4711. LCD_MESSAGERPGM(_i("No move."));////MSG_NO_MOVE c=20
  4712. enable_x();
  4713. enable_y();
  4714. enable_z();
  4715. enable_e0();
  4716. enable_e1();
  4717. enable_e2();
  4718. break;
  4719. #ifdef SDSUPPORT
  4720. /*!
  4721. ### M20 - SD Card file list <a href="https://reprap.org/wiki/G-code#M20:_List_SD_card">M20: List SD card</a>
  4722. #### Usage
  4723. M20 [ L | T ]
  4724. #### Parameters
  4725. - `T` - Report timestamps as well. The value is one uint32_t encoded as hex. Requires host software parsing (Cap:EXTENDED_M20).
  4726. - `L` - Reports long filenames instead of just short filenames. Requires host software parsing (Cap:EXTENDED_M20).
  4727. */
  4728. case 20:
  4729. KEEPALIVE_STATE(NOT_BUSY); // do not send busy messages during listing. Inhibits the output of manage_heater()
  4730. SERIAL_PROTOCOLLNRPGM(_N("Begin file list"));////MSG_BEGIN_FILE_LIST
  4731. card.ls(CardReader::ls_param(code_seen('L'), code_seen('T')));
  4732. SERIAL_PROTOCOLLNRPGM(_N("End file list"));////MSG_END_FILE_LIST
  4733. break;
  4734. /*!
  4735. ### M21 - Init SD card <a href="https://reprap.org/wiki/G-code#M21:_Initialize_SD_card">M21: Initialize SD card</a>
  4736. */
  4737. case 21:
  4738. card.initsd();
  4739. break;
  4740. /*!
  4741. ### M22 - Release SD card <a href="https://reprap.org/wiki/G-code#M22:_Release_SD_card">M22: Release SD card</a>
  4742. */
  4743. case 22:
  4744. card.release();
  4745. break;
  4746. /*!
  4747. ### M23 - Select file <a href="https://reprap.org/wiki/G-code#M23:_Select_SD_file">M23: Select SD file</a>
  4748. #### Usage
  4749. M23 [filename]
  4750. */
  4751. case 23:
  4752. starpos = (strchr(strchr_pointer + 4,'*'));
  4753. if(starpos!=NULL)
  4754. *(starpos)='\0';
  4755. card.openFileReadFilteredGcode(strchr_pointer + 4, true);
  4756. break;
  4757. /*!
  4758. ### M24 - Start SD print <a href="https://reprap.org/wiki/G-code#M24:_Start.2Fresume_SD_print">M24: Start/resume SD print</a>
  4759. */
  4760. case 24:
  4761. if (isPrintPaused)
  4762. lcd_resume_print();
  4763. else
  4764. {
  4765. if (!card.get_sdpos())
  4766. {
  4767. // A new print has started from scratch, reset stats
  4768. failstats_reset_print();
  4769. sdpos_atomic = 0;
  4770. #ifndef LA_NOCOMPAT
  4771. la10c_reset();
  4772. #endif
  4773. }
  4774. card.startFileprint();
  4775. starttime=_millis();
  4776. }
  4777. break;
  4778. /*!
  4779. ### M26 - Set SD index <a href="https://reprap.org/wiki/G-code#M26:_Set_SD_position">M26: Set SD position</a>
  4780. Set position in SD card file to index in bytes.
  4781. This command is expected to be called after M23 and before M24.
  4782. Otherwise effect of this command is undefined.
  4783. #### Usage
  4784. M26 [ S ]
  4785. #### Parameters
  4786. - `S` - Index in bytes
  4787. */
  4788. case 26:
  4789. if(card.cardOK && code_seen('S')) {
  4790. long index = code_value_long();
  4791. card.setIndex(index);
  4792. // We don't disable interrupt during update of sdpos_atomic
  4793. // as we expect, that SD card print is not active in this moment
  4794. sdpos_atomic = index;
  4795. }
  4796. break;
  4797. /*!
  4798. ### M27 - Get SD status <a href="https://reprap.org/wiki/G-code#M27:_Report_SD_print_status">M27: Report SD print status</a>
  4799. #### Usage
  4800. M27 [ P ]
  4801. #### Parameters
  4802. - `P` - Show full SFN path instead of LFN only.
  4803. */
  4804. case 27:
  4805. card.getStatus(code_seen('P'));
  4806. break;
  4807. /*!
  4808. ### 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>
  4809. */
  4810. case 28:
  4811. starpos = (strchr(strchr_pointer + 4,'*'));
  4812. if(starpos != NULL){
  4813. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  4814. strchr_pointer = strchr(npos,' ') + 1;
  4815. *(starpos) = '\0';
  4816. }
  4817. card.openFileWrite(strchr_pointer+4);
  4818. break;
  4819. /*! ### 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>
  4820. 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.
  4821. */
  4822. case 29:
  4823. //processed in write to file routine above
  4824. //card,saving = false;
  4825. break;
  4826. /*!
  4827. ### 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>
  4828. #### Usage
  4829. M30 [filename]
  4830. */
  4831. case 30:
  4832. if (card.cardOK){
  4833. card.closefile();
  4834. starpos = (strchr(strchr_pointer + 4,'*'));
  4835. if(starpos != NULL){
  4836. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  4837. strchr_pointer = strchr(npos,' ') + 1;
  4838. *(starpos) = '\0';
  4839. }
  4840. card.removeFile(strchr_pointer + 4);
  4841. }
  4842. break;
  4843. /*!
  4844. ### 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>
  4845. @todo What are the parameters P and S for in M32?
  4846. */
  4847. case 32:
  4848. {
  4849. if(card.sdprinting) {
  4850. st_synchronize();
  4851. }
  4852. starpos = (strchr(strchr_pointer + 4,'*'));
  4853. const char* namestartpos = (strchr(strchr_pointer + 4,'!')); //find ! to indicate filename string start.
  4854. if(namestartpos==NULL)
  4855. {
  4856. namestartpos=strchr_pointer + 4; //default name position, 4 letters after the M
  4857. }
  4858. else
  4859. namestartpos++; //to skip the '!'
  4860. if(starpos!=NULL)
  4861. *(starpos)='\0';
  4862. bool call_procedure=(code_seen('P'));
  4863. if(strchr_pointer>namestartpos)
  4864. call_procedure=false; //false alert, 'P' found within filename
  4865. if( card.cardOK )
  4866. {
  4867. card.openFileReadFilteredGcode(namestartpos,!call_procedure);
  4868. if(code_seen('S'))
  4869. if(strchr_pointer<namestartpos) //only if "S" is occuring _before_ the filename
  4870. card.setIndex(code_value_long());
  4871. card.startFileprint();
  4872. if(!call_procedure)
  4873. {
  4874. if(!card.get_sdpos())
  4875. {
  4876. // A new print has started from scratch, reset stats
  4877. failstats_reset_print();
  4878. sdpos_atomic = 0;
  4879. #ifndef LA_NOCOMPAT
  4880. la10c_reset();
  4881. #endif
  4882. }
  4883. starttime=_millis(); // procedure calls count as normal print time.
  4884. }
  4885. }
  4886. } break;
  4887. /*!
  4888. ### M928 - Start SD logging <a href="https://reprap.org/wiki/G-code#M928:_Start_SD_logging">M928: Start SD logging</a>
  4889. #### Usage
  4890. M928 [filename]
  4891. */
  4892. case 928:
  4893. starpos = (strchr(strchr_pointer + 5,'*'));
  4894. if(starpos != NULL){
  4895. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  4896. strchr_pointer = strchr(npos,' ') + 1;
  4897. *(starpos) = '\0';
  4898. }
  4899. card.openLogFile(strchr_pointer+5);
  4900. break;
  4901. #endif //SDSUPPORT
  4902. /*!
  4903. ### 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>
  4904. */
  4905. case 31: //M31 take time since the start of the SD print or an M109 command
  4906. {
  4907. stoptime=_millis();
  4908. char time[30];
  4909. unsigned long t=(stoptime-starttime)/1000;
  4910. int sec,min;
  4911. min=t/60;
  4912. sec=t%60;
  4913. sprintf_P(time, PSTR("%i min, %i sec"), min, sec);
  4914. SERIAL_ECHO_START;
  4915. SERIAL_ECHOLN(time);
  4916. lcd_setstatus(time);
  4917. autotempShutdown();
  4918. }
  4919. break;
  4920. /*!
  4921. ### M42 - Set pin state <a href="https://reprap.org/wiki/G-code#M42:_Switch_I.2FO_pin">M42: Switch I/O pin</a>
  4922. #### Usage
  4923. M42 [ P | S ]
  4924. #### Parameters
  4925. - `P` - Pin number.
  4926. - `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.
  4927. */
  4928. case 42:
  4929. if (code_seen('S'))
  4930. {
  4931. uint8_t pin_status = code_value_uint8();
  4932. int8_t pin_number = LED_PIN;
  4933. if (code_seen('P'))
  4934. pin_number = code_value_uint8();
  4935. for(int8_t i = 0; i < (int8_t)(sizeof(sensitive_pins)/sizeof(sensitive_pins[0])); i++)
  4936. {
  4937. if ((int8_t)pgm_read_byte(&sensitive_pins[i]) == pin_number)
  4938. {
  4939. pin_number = -1;
  4940. break;
  4941. }
  4942. }
  4943. #if defined(FAN_PIN) && FAN_PIN > -1
  4944. if (pin_number == FAN_PIN)
  4945. fanSpeed = pin_status;
  4946. #endif
  4947. if (pin_number > -1)
  4948. {
  4949. pinMode(pin_number, OUTPUT);
  4950. digitalWrite(pin_number, pin_status);
  4951. analogWrite(pin_number, pin_status);
  4952. }
  4953. }
  4954. break;
  4955. /*!
  4956. ### 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>
  4957. */
  4958. case 44: // M44: Prusa3D: Reset the bed skew and offset calibration.
  4959. // Reset the baby step value and the baby step applied flag.
  4960. calibration_status_store(CALIBRATION_STATUS_ASSEMBLED);
  4961. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  4962. // Reset the skew and offset in both RAM and EEPROM.
  4963. reset_bed_offset_and_skew();
  4964. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  4965. // the planner will not perform any adjustments in the XY plane.
  4966. // Wait for the motors to stop and update the current position with the absolute values.
  4967. world2machine_revert_to_uncorrected();
  4968. break;
  4969. /*!
  4970. ### 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>
  4971. #### Usage
  4972. M45 [ V ]
  4973. #### Parameters
  4974. - `V` - Verbosity level 1, 10 and 20 (low, mid, high). Only when SUPPORT_VERBOSITY is defined. Optional.
  4975. - `Z` - If it is provided, only Z calibration will run. Otherwise full calibration is executed.
  4976. */
  4977. case 45: // M45: Prusa3D: bed skew and offset with manual Z up
  4978. {
  4979. int8_t verbosity_level = 0;
  4980. bool only_Z = code_seen('Z');
  4981. #ifdef SUPPORT_VERBOSITY
  4982. if (code_seen('V'))
  4983. {
  4984. // Just 'V' without a number counts as V1.
  4985. char c = strchr_pointer[1];
  4986. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  4987. }
  4988. #endif //SUPPORT_VERBOSITY
  4989. gcode_M45(only_Z, verbosity_level);
  4990. }
  4991. break;
  4992. /*!
  4993. ### 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>
  4994. */
  4995. case 46:
  4996. {
  4997. // M46: Prusa3D: Show the assigned IP address.
  4998. if (card.ToshibaFlashAir_isEnabled()) {
  4999. uint8_t ip[4];
  5000. if (card.ToshibaFlashAir_GetIP(ip)) {
  5001. // SERIAL_PROTOCOLPGM("Toshiba FlashAir current IP: ");
  5002. SERIAL_PROTOCOL(uint8_t(ip[0]));
  5003. SERIAL_PROTOCOL('.');
  5004. SERIAL_PROTOCOL(uint8_t(ip[1]));
  5005. SERIAL_PROTOCOL('.');
  5006. SERIAL_PROTOCOL(uint8_t(ip[2]));
  5007. SERIAL_PROTOCOL('.');
  5008. SERIAL_PROTOCOLLN(uint8_t(ip[3]));
  5009. } else {
  5010. SERIAL_PROTOCOLPGM("?Toshiba FlashAir GetIP failed\n");
  5011. }
  5012. } else {
  5013. SERIAL_PROTOCOLLNPGM("n/a");
  5014. }
  5015. break;
  5016. }
  5017. /*!
  5018. ### 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>
  5019. */
  5020. case 47:
  5021. KEEPALIVE_STATE(PAUSED_FOR_USER);
  5022. lcd_diag_show_end_stops();
  5023. KEEPALIVE_STATE(IN_HANDLER);
  5024. break;
  5025. #if 0
  5026. case 48: // M48: scan the bed induction sensor points, print the sensor trigger coordinates to the serial line for visualization on the PC.
  5027. {
  5028. // Disable the default update procedure of the display. We will do a modal dialog.
  5029. lcd_update_enable(false);
  5030. // Let the planner use the uncorrected coordinates.
  5031. mbl.reset();
  5032. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  5033. // the planner will not perform any adjustments in the XY plane.
  5034. // Wait for the motors to stop and update the current position with the absolute values.
  5035. world2machine_revert_to_uncorrected();
  5036. // Move the print head close to the bed.
  5037. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  5038. 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);
  5039. st_synchronize();
  5040. // Home in the XY plane.
  5041. set_destination_to_current();
  5042. int l_feedmultiply = setup_for_endstop_move();
  5043. home_xy();
  5044. int8_t verbosity_level = 0;
  5045. if (code_seen('V')) {
  5046. // Just 'V' without a number counts as V1.
  5047. char c = strchr_pointer[1];
  5048. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  5049. }
  5050. bool success = scan_bed_induction_points(verbosity_level);
  5051. clean_up_after_endstop_move(l_feedmultiply);
  5052. // Print head up.
  5053. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  5054. 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);
  5055. st_synchronize();
  5056. lcd_update_enable(true);
  5057. break;
  5058. }
  5059. #endif
  5060. #ifdef ENABLE_AUTO_BED_LEVELING
  5061. #ifdef Z_PROBE_REPEATABILITY_TEST
  5062. /*!
  5063. ### 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>
  5064. 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.
  5065. 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.
  5066. @todo Why would you check for both uppercase and lowercase? Seems wasteful.
  5067. #### Usage
  5068. M48 [ n | X | Y | V | L ]
  5069. #### Parameters
  5070. - `n` - Number of samples. Valid values 4-50
  5071. - `X` - X position for samples
  5072. - `Y` - Y position for samples
  5073. - `V` - Verbose level. Valid values 1-4
  5074. - `L` - Legs of movementprior to doing probe. Valid values 1-15
  5075. */
  5076. case 48: // M48 Z-Probe repeatability
  5077. {
  5078. #if Z_MIN_PIN == -1
  5079. #error "You must have a Z_MIN endstop in order to enable calculation of Z-Probe repeatability."
  5080. #endif
  5081. double sum=0.0;
  5082. double mean=0.0;
  5083. double sigma=0.0;
  5084. double sample_set[50];
  5085. int verbose_level=1, n=0, j, n_samples = 10, n_legs=0;
  5086. double X_current, Y_current, Z_current;
  5087. double X_probe_location, Y_probe_location, Z_start_location, ext_position;
  5088. if (code_seen('V') || code_seen('v')) {
  5089. verbose_level = code_value();
  5090. if (verbose_level<0 || verbose_level>4 ) {
  5091. SERIAL_PROTOCOLPGM("?Verbose Level not plausable.\n");
  5092. goto Sigma_Exit;
  5093. }
  5094. }
  5095. if (verbose_level > 0) {
  5096. SERIAL_PROTOCOLPGM("M48 Z-Probe Repeatability test. Version 2.00\n");
  5097. SERIAL_PROTOCOLPGM("Full support at: http://3dprintboard.com/forum.php\n");
  5098. }
  5099. if (code_seen('n')) {
  5100. n_samples = code_value();
  5101. if (n_samples<4 || n_samples>50 ) {
  5102. SERIAL_PROTOCOLPGM("?Specified sample size not plausable.\n");
  5103. goto Sigma_Exit;
  5104. }
  5105. }
  5106. X_current = X_probe_location = st_get_position_mm(X_AXIS);
  5107. Y_current = Y_probe_location = st_get_position_mm(Y_AXIS);
  5108. Z_current = st_get_position_mm(Z_AXIS);
  5109. Z_start_location = st_get_position_mm(Z_AXIS) + Z_RAISE_BEFORE_PROBING;
  5110. ext_position = st_get_position_mm(E_AXIS);
  5111. if (code_seen('X') || code_seen('x') ) {
  5112. X_probe_location = code_value() - X_PROBE_OFFSET_FROM_EXTRUDER;
  5113. if (X_probe_location<X_MIN_POS || X_probe_location>X_MAX_POS ) {
  5114. SERIAL_PROTOCOLPGM("?Specified X position out of range.\n");
  5115. goto Sigma_Exit;
  5116. }
  5117. }
  5118. if (code_seen('Y') || code_seen('y') ) {
  5119. Y_probe_location = code_value() - Y_PROBE_OFFSET_FROM_EXTRUDER;
  5120. if (Y_probe_location<Y_MIN_POS || Y_probe_location>Y_MAX_POS ) {
  5121. SERIAL_PROTOCOLPGM("?Specified Y position out of range.\n");
  5122. goto Sigma_Exit;
  5123. }
  5124. }
  5125. if (code_seen('L') || code_seen('l') ) {
  5126. n_legs = code_value();
  5127. if ( n_legs==1 )
  5128. n_legs = 2;
  5129. if ( n_legs<0 || n_legs>15 ) {
  5130. SERIAL_PROTOCOLPGM("?Specified number of legs in movement not plausable.\n");
  5131. goto Sigma_Exit;
  5132. }
  5133. }
  5134. //
  5135. // Do all the preliminary setup work. First raise the probe.
  5136. //
  5137. st_synchronize();
  5138. plan_bed_level_matrix.set_to_identity();
  5139. plan_buffer_line( X_current, Y_current, Z_start_location,
  5140. ext_position,
  5141. homing_feedrate[Z_AXIS]/60,
  5142. active_extruder);
  5143. st_synchronize();
  5144. //
  5145. // Now get everything to the specified probe point So we can safely do a probe to
  5146. // get us close to the bed. If the Z-Axis is far from the bed, we don't want to
  5147. // use that as a starting point for each probe.
  5148. //
  5149. if (verbose_level > 2)
  5150. SERIAL_PROTOCOL("Positioning probe for the test.\n");
  5151. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  5152. ext_position,
  5153. homing_feedrate[X_AXIS]/60,
  5154. active_extruder);
  5155. st_synchronize();
  5156. current_position[X_AXIS] = X_current = st_get_position_mm(X_AXIS);
  5157. current_position[Y_AXIS] = Y_current = st_get_position_mm(Y_AXIS);
  5158. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  5159. current_position[E_AXIS] = ext_position = st_get_position_mm(E_AXIS);
  5160. //
  5161. // OK, do the inital probe to get us close to the bed.
  5162. // Then retrace the right amount and use that in subsequent probes
  5163. //
  5164. int l_feedmultiply = setup_for_endstop_move();
  5165. run_z_probe();
  5166. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  5167. Z_start_location = st_get_position_mm(Z_AXIS) + Z_RAISE_BEFORE_PROBING;
  5168. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  5169. ext_position,
  5170. homing_feedrate[X_AXIS]/60,
  5171. active_extruder);
  5172. st_synchronize();
  5173. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  5174. for( n=0; n<n_samples; n++) {
  5175. do_blocking_move_to( X_probe_location, Y_probe_location, Z_start_location); // Make sure we are at the probe location
  5176. if ( n_legs) {
  5177. double radius=0.0, theta=0.0, x_sweep, y_sweep;
  5178. int rotational_direction, l;
  5179. rotational_direction = (unsigned long) _millis() & 0x0001; // clockwise or counter clockwise
  5180. radius = (unsigned long) _millis() % (long) (X_MAX_LENGTH/4); // limit how far out to go
  5181. theta = (float) ((unsigned long) _millis() % (long) 360) / (360./(2*3.1415926)); // turn into radians
  5182. //SERIAL_ECHOPAIR("starting radius: ",radius);
  5183. //SERIAL_ECHOPAIR(" theta: ",theta);
  5184. //SERIAL_ECHOPAIR(" direction: ",rotational_direction);
  5185. //SERIAL_PROTOCOLLNPGM("");
  5186. for( l=0; l<n_legs-1; l++) {
  5187. if (rotational_direction==1)
  5188. theta += (float) ((unsigned long) _millis() % (long) 20) / (360.0/(2*3.1415926)); // turn into radians
  5189. else
  5190. theta -= (float) ((unsigned long) _millis() % (long) 20) / (360.0/(2*3.1415926)); // turn into radians
  5191. radius += (float) ( ((long) ((unsigned long) _millis() % (long) 10)) - 5);
  5192. if ( radius<0.0 )
  5193. radius = -radius;
  5194. X_current = X_probe_location + cos(theta) * radius;
  5195. Y_current = Y_probe_location + sin(theta) * radius;
  5196. if ( X_current<X_MIN_POS) // Make sure our X & Y are sane
  5197. X_current = X_MIN_POS;
  5198. if ( X_current>X_MAX_POS)
  5199. X_current = X_MAX_POS;
  5200. if ( Y_current<Y_MIN_POS) // Make sure our X & Y are sane
  5201. Y_current = Y_MIN_POS;
  5202. if ( Y_current>Y_MAX_POS)
  5203. Y_current = Y_MAX_POS;
  5204. if (verbose_level>3 ) {
  5205. SERIAL_ECHOPAIR("x: ", X_current);
  5206. SERIAL_ECHOPAIR("y: ", Y_current);
  5207. SERIAL_PROTOCOLLNPGM("");
  5208. }
  5209. do_blocking_move_to( X_current, Y_current, Z_current );
  5210. }
  5211. do_blocking_move_to( X_probe_location, Y_probe_location, Z_start_location); // Go back to the probe location
  5212. }
  5213. int l_feedmultiply = setup_for_endstop_move();
  5214. run_z_probe();
  5215. sample_set[n] = current_position[Z_AXIS];
  5216. //
  5217. // Get the current mean for the data points we have so far
  5218. //
  5219. sum=0.0;
  5220. for( j=0; j<=n; j++) {
  5221. sum = sum + sample_set[j];
  5222. }
  5223. mean = sum / (double (n+1));
  5224. //
  5225. // Now, use that mean to calculate the standard deviation for the
  5226. // data points we have so far
  5227. //
  5228. sum=0.0;
  5229. for( j=0; j<=n; j++) {
  5230. sum = sum + (sample_set[j]-mean) * (sample_set[j]-mean);
  5231. }
  5232. sigma = sqrt( sum / (double (n+1)) );
  5233. if (verbose_level > 1) {
  5234. SERIAL_PROTOCOL(n+1);
  5235. SERIAL_PROTOCOL(" of ");
  5236. SERIAL_PROTOCOL(n_samples);
  5237. SERIAL_PROTOCOLPGM(" z: ");
  5238. SERIAL_PROTOCOL_F(current_position[Z_AXIS], 6);
  5239. }
  5240. if (verbose_level > 2) {
  5241. SERIAL_PROTOCOL(" mean: ");
  5242. SERIAL_PROTOCOL_F(mean,6);
  5243. SERIAL_PROTOCOL(" sigma: ");
  5244. SERIAL_PROTOCOL_F(sigma,6);
  5245. }
  5246. if (verbose_level > 0)
  5247. SERIAL_PROTOCOLPGM("\n");
  5248. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  5249. current_position[E_AXIS], homing_feedrate[Z_AXIS]/60, active_extruder);
  5250. st_synchronize();
  5251. }
  5252. _delay(1000);
  5253. clean_up_after_endstop_move(l_feedmultiply);
  5254. // enable_endstops(true);
  5255. if (verbose_level > 0) {
  5256. SERIAL_PROTOCOLPGM("Mean: ");
  5257. SERIAL_PROTOCOL_F(mean, 6);
  5258. SERIAL_PROTOCOLPGM("\n");
  5259. }
  5260. SERIAL_PROTOCOLPGM("Standard Deviation: ");
  5261. SERIAL_PROTOCOL_F(sigma, 6);
  5262. SERIAL_PROTOCOLPGM("\n\n");
  5263. Sigma_Exit:
  5264. break;
  5265. }
  5266. #endif // Z_PROBE_REPEATABILITY_TEST
  5267. #endif // ENABLE_AUTO_BED_LEVELING
  5268. /*!
  5269. ### M73 - Set/get print progress <a href="https://reprap.org/wiki/G-code#M73:_Set.2FGet_build_percentage">M73: Set/Get build percentage</a>
  5270. #### Usage
  5271. M73 [ P | R | Q | S | C | D ]
  5272. #### Parameters
  5273. - `P` - Percent in normal mode
  5274. - `R` - Time remaining in normal mode
  5275. - `Q` - Percent in silent mode
  5276. - `S` - Time in silent mode
  5277. - `C` - Time to change/pause/user interaction in normal mode
  5278. - `D` - Time to change/pause/user interaction in silent mode
  5279. */
  5280. case 73: //M73 show percent done, time remaining and time to change/pause
  5281. {
  5282. if(code_seen('P')) print_percent_done_normal = code_value_uint8();
  5283. if(code_seen('R')) print_time_remaining_normal = code_value();
  5284. if(code_seen('Q')) print_percent_done_silent = code_value_uint8();
  5285. if(code_seen('S')) print_time_remaining_silent = code_value();
  5286. if(code_seen('C')){
  5287. float print_time_to_change_normal_f = code_value_float();
  5288. print_time_to_change_normal = ( print_time_to_change_normal_f <= 0 ) ? PRINT_TIME_REMAINING_INIT : print_time_to_change_normal_f;
  5289. }
  5290. if(code_seen('D')){
  5291. float print_time_to_change_silent_f = code_value_float();
  5292. print_time_to_change_silent = ( print_time_to_change_silent_f <= 0 ) ? PRINT_TIME_REMAINING_INIT : print_time_to_change_silent_f;
  5293. }
  5294. {
  5295. const char* _msg_mode_done_remain = _N("%S MODE: Percent done: %hhd; print time remaining in mins: %d; Change in mins: %d\n");
  5296. printf_P(_msg_mode_done_remain, _N("NORMAL"), int8_t(print_percent_done_normal), print_time_remaining_normal, print_time_to_change_normal);
  5297. printf_P(_msg_mode_done_remain, _N("SILENT"), int8_t(print_percent_done_silent), print_time_remaining_silent, print_time_to_change_silent);
  5298. }
  5299. break;
  5300. }
  5301. /*!
  5302. ### M104 - Set hotend temperature <a href="https://reprap.org/wiki/G-code#M104:_Set_Extruder_Temperature">M104: Set Extruder Temperature</a>
  5303. #### Usage
  5304. M104 [ S ]
  5305. #### Parameters
  5306. - `S` - Target temperature
  5307. */
  5308. case 104: // M104
  5309. {
  5310. uint8_t extruder;
  5311. if(setTargetedHotend(104,extruder)){
  5312. break;
  5313. }
  5314. if (code_seen('S'))
  5315. {
  5316. setTargetHotendSafe(code_value(), extruder);
  5317. }
  5318. break;
  5319. }
  5320. /*!
  5321. ### M112 - Emergency stop <a href="https://reprap.org/wiki/G-code#M112:_Full_.28Emergency.29_Stop">M112: Full (Emergency) Stop</a>
  5322. It is processed much earlier as to bypass the cmdqueue.
  5323. */
  5324. case 112:
  5325. kill(MSG_M112_KILL, 3);
  5326. break;
  5327. /*!
  5328. ### M140 - Set bed temperature <a href="https://reprap.org/wiki/G-code#M140:_Set_Bed_Temperature_.28Fast.29">M140: Set Bed Temperature (Fast)</a>
  5329. #### Usage
  5330. M140 [ S ]
  5331. #### Parameters
  5332. - `S` - Target temperature
  5333. */
  5334. case 140:
  5335. if (code_seen('S')) setTargetBed(code_value());
  5336. break;
  5337. /*!
  5338. ### M105 - Report temperatures <a href="https://reprap.org/wiki/G-code#M105:_Get_Extruder_Temperature">M105: Get Extruder Temperature</a>
  5339. Prints temperatures:
  5340. - `T:` - Hotend (actual / target)
  5341. - `B:` - Bed (actual / target)
  5342. - `Tx:` - x Tool (actual / target)
  5343. - `@:` - Hotend power
  5344. - `B@:` - Bed power
  5345. - `P:` - PINDAv2 actual (only MK2.5/s and MK3/s)
  5346. - `A:` - Ambient actual (only MK3/s)
  5347. _Example:_
  5348. 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
  5349. */
  5350. case 105:
  5351. {
  5352. uint8_t extruder;
  5353. if(setTargetedHotend(105, extruder)){
  5354. break;
  5355. }
  5356. SERIAL_PROTOCOLPGM("ok ");
  5357. gcode_M105(extruder);
  5358. cmdqueue_pop_front(); //prevent an ok after the command since this command uses an ok at the beginning.
  5359. cmdbuffer_front_already_processed = true;
  5360. break;
  5361. }
  5362. #if defined(AUTO_REPORT)
  5363. /*!
  5364. ### M155 - Automatically send status <a href="https://reprap.org/wiki/G-code#M155:_Automatically_send_temperatures">M155: Automatically send temperatures</a>
  5365. #### Usage
  5366. M155 [ S ] [ C ]
  5367. #### Parameters
  5368. - `S` - Set autoreporting interval in seconds. 0 to disable. Maximum: 255
  5369. - `C` - Activate auto-report function (bit mask). Default is temperature.
  5370. bit 0 = Auto-report temperatures
  5371. bit 1 = Auto-report fans
  5372. bit 2 = Auto-report position
  5373. bit 3 = free
  5374. bit 4 = free
  5375. bit 5 = free
  5376. bit 6 = free
  5377. bit 7 = free
  5378. */
  5379. case 155:
  5380. {
  5381. if (code_seen('S')){
  5382. autoReportFeatures.SetPeriod( code_value_uint8() );
  5383. }
  5384. if (code_seen('C')){
  5385. autoReportFeatures.SetMask(code_value_uint8());
  5386. } else{
  5387. autoReportFeatures.SetMask(1); //Backwards compability to host systems like Octoprint to send only temp if paramerter `C`isn't used.
  5388. }
  5389. }
  5390. break;
  5391. #endif //AUTO_REPORT
  5392. /*!
  5393. ### 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>
  5394. #### Usage
  5395. M104 [ B | R | S ]
  5396. #### Parameters (not mandatory)
  5397. - `S` - Set extruder temperature
  5398. - `R` - Set extruder temperature
  5399. - `B` - Set max. extruder temperature, while `S` is min. temperature. Not active in default, only if AUTOTEMP is defined in source code.
  5400. Parameters S and R are treated identically.
  5401. Command always waits for both cool down and heat up.
  5402. If no parameters are supplied waits for previously set extruder temperature.
  5403. */
  5404. case 109:
  5405. {
  5406. uint8_t extruder;
  5407. if(setTargetedHotend(109, extruder)){
  5408. break;
  5409. }
  5410. LCD_MESSAGERPGM(_T(MSG_HEATING));
  5411. heating_status = HeatingStatus::EXTRUDER_HEATING;
  5412. prusa_statistics(1);
  5413. #ifdef AUTOTEMP
  5414. autotemp_enabled=false;
  5415. #endif
  5416. if (code_seen('S')) {
  5417. setTargetHotendSafe(code_value(), extruder);
  5418. } else if (code_seen('R')) {
  5419. setTargetHotendSafe(code_value(), extruder);
  5420. }
  5421. #ifdef AUTOTEMP
  5422. if (code_seen('S')) autotemp_min=code_value();
  5423. if (code_seen('B')) autotemp_max=code_value();
  5424. if (code_seen('F'))
  5425. {
  5426. autotemp_factor=code_value();
  5427. autotemp_enabled=true;
  5428. }
  5429. #endif
  5430. codenum = _millis();
  5431. /* See if we are heating up or cooling down */
  5432. target_direction = isHeatingHotend(extruder); // true if heating, false if cooling
  5433. cancel_heatup = false;
  5434. wait_for_heater(codenum, extruder); //loops until target temperature is reached
  5435. LCD_MESSAGERPGM(_T(MSG_HEATING_COMPLETE));
  5436. heating_status = HeatingStatus::EXTRUDER_HEATING_COMPLETE;
  5437. prusa_statistics(2);
  5438. //starttime=_millis();
  5439. previous_millis_cmd.start();
  5440. }
  5441. break;
  5442. /*!
  5443. ### 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>
  5444. #### Usage
  5445. M190 [ R | S ]
  5446. #### Parameters (not mandatory)
  5447. - `S` - Set extruder temperature and wait for heating
  5448. - `R` - Set extruder temperature and wait for heating or cooling
  5449. If no parameter is supplied, waits for heating or cooling to previously set temperature.
  5450. */
  5451. case 190:
  5452. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  5453. {
  5454. bool CooldownNoWait = false;
  5455. LCD_MESSAGERPGM(_T(MSG_BED_HEATING));
  5456. heating_status = HeatingStatus::BED_HEATING;
  5457. prusa_statistics(1);
  5458. if (code_seen('S'))
  5459. {
  5460. setTargetBed(code_value());
  5461. CooldownNoWait = true;
  5462. }
  5463. else if (code_seen('R'))
  5464. {
  5465. setTargetBed(code_value());
  5466. }
  5467. codenum = _millis();
  5468. cancel_heatup = false;
  5469. target_direction = isHeatingBed(); // true if heating, false if cooling
  5470. while ( (!cancel_heatup) && (target_direction ? (isHeatingBed()) : (isCoolingBed()&&(CooldownNoWait==false))) )
  5471. {
  5472. if(( _millis() - codenum) > 1000 ) //Print Temp Reading every 1 second while heating up.
  5473. {
  5474. if (!farm_mode) {
  5475. float tt = degHotend(active_extruder);
  5476. SERIAL_PROTOCOLPGM("T:");
  5477. SERIAL_PROTOCOL(tt);
  5478. SERIAL_PROTOCOLPGM(" E:");
  5479. SERIAL_PROTOCOL((int)active_extruder);
  5480. SERIAL_PROTOCOLPGM(" B:");
  5481. SERIAL_PROTOCOL_F(degBed(), 1);
  5482. SERIAL_PROTOCOLLN();
  5483. }
  5484. codenum = _millis();
  5485. }
  5486. manage_heater();
  5487. manage_inactivity();
  5488. lcd_update(0);
  5489. }
  5490. LCD_MESSAGERPGM(_T(MSG_BED_DONE));
  5491. heating_status = HeatingStatus::BED_HEATING_COMPLETE;
  5492. previous_millis_cmd.start();
  5493. }
  5494. #endif
  5495. break;
  5496. #if defined(FAN_PIN) && FAN_PIN > -1
  5497. /*!
  5498. ### M106 - Set fan speed <a href="https://reprap.org/wiki/G-code#M106:_Fan_On">M106: Fan On</a>
  5499. #### Usage
  5500. M106 [ S ]
  5501. #### Parameters
  5502. - `S` - Specifies the duty cycle of the print fan. Allowed values are 0-255. If it's omitted, a value of 255 is used.
  5503. */
  5504. case 106: // M106 Sxxx Fan On S<speed> 0 .. 255
  5505. if (code_seen('S')){
  5506. fanSpeed = code_value_uint8();
  5507. }
  5508. else {
  5509. fanSpeed = 255;
  5510. }
  5511. break;
  5512. /*!
  5513. ### M107 - Fan off <a href="https://reprap.org/wiki/G-code#M107:_Fan_Off">M107: Fan Off</a>
  5514. */
  5515. case 107:
  5516. fanSpeed = 0;
  5517. break;
  5518. #endif //FAN_PIN
  5519. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  5520. /*!
  5521. ### M80 - Turn on the Power Supply <a href="https://reprap.org/wiki/G-code#M80:_ATX_Power_On">M80: ATX Power On</a>
  5522. Only works if the firmware is compiled with PS_ON_PIN defined.
  5523. */
  5524. case 80:
  5525. SET_OUTPUT(PS_ON_PIN); //GND
  5526. WRITE(PS_ON_PIN, PS_ON_AWAKE);
  5527. // If you have a switch on suicide pin, this is useful
  5528. // if you want to start another print with suicide feature after
  5529. // a print without suicide...
  5530. #if defined SUICIDE_PIN && SUICIDE_PIN > -1
  5531. SET_OUTPUT(SUICIDE_PIN);
  5532. WRITE(SUICIDE_PIN, HIGH);
  5533. #endif
  5534. powersupply = true;
  5535. LCD_MESSAGERPGM(MSG_WELCOME);
  5536. lcd_update(0);
  5537. break;
  5538. /*!
  5539. ### M81 - Turn off Power Supply <a href="https://reprap.org/wiki/G-code#M81:_ATX_Power_Off">M81: ATX Power Off</a>
  5540. Only works if the firmware is compiled with PS_ON_PIN defined.
  5541. */
  5542. case 81:
  5543. disable_heater();
  5544. st_synchronize();
  5545. disable_e0();
  5546. disable_e1();
  5547. disable_e2();
  5548. finishAndDisableSteppers();
  5549. fanSpeed = 0;
  5550. _delay(1000); // Wait a little before to switch off
  5551. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  5552. st_synchronize();
  5553. suicide();
  5554. #elif defined(PS_ON_PIN) && PS_ON_PIN > -1
  5555. SET_OUTPUT(PS_ON_PIN);
  5556. WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  5557. #endif
  5558. powersupply = false;
  5559. LCD_MESSAGERPGM(CAT4(CUSTOM_MENDEL_NAME,PSTR(" "),MSG_OFF,PSTR(".")));
  5560. lcd_update(0);
  5561. break;
  5562. #endif
  5563. /*!
  5564. ### 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>
  5565. Makes the extruder interpret extrusion as absolute positions.
  5566. */
  5567. case 82:
  5568. axis_relative_modes &= ~E_AXIS_MASK;
  5569. break;
  5570. /*!
  5571. ### 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>
  5572. Makes the extruder interpret extrusion values as relative positions.
  5573. */
  5574. case 83:
  5575. axis_relative_modes |= E_AXIS_MASK;
  5576. break;
  5577. /*!
  5578. ### M84 - Disable steppers <a href="https://reprap.org/wiki/G-code#M84:_Stop_idle_hold">M84: Stop idle hold</a>
  5579. This command can be used to set the stepper inactivity timeout (`S`) or to disable steppers (`X`,`Y`,`Z`,`E`)
  5580. This command can be used without any additional parameters. In that case all steppers are disabled.
  5581. 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.
  5582. M84 [ S | X | Y | Z | E ]
  5583. - `S` - Seconds
  5584. - `X` - X axis
  5585. - `Y` - Y axis
  5586. - `Z` - Z axis
  5587. - `E` - Extruder
  5588. ### M18 - Disable steppers <a href="https://reprap.org/wiki/G-code#M18:_Disable_all_stepper_motors">M18: Disable all stepper motors</a>
  5589. Equal to M84 (compatibility)
  5590. */
  5591. case 18: //compatibility
  5592. case 84: // M84
  5593. if(code_seen('S')){
  5594. stepper_inactive_time = code_value() * 1000;
  5595. }
  5596. else
  5597. {
  5598. 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])));
  5599. if(all_axis)
  5600. {
  5601. st_synchronize();
  5602. disable_e0();
  5603. disable_e1();
  5604. disable_e2();
  5605. finishAndDisableSteppers();
  5606. }
  5607. else
  5608. {
  5609. st_synchronize();
  5610. if (code_seen('X')) disable_x();
  5611. if (code_seen('Y')) disable_y();
  5612. if (code_seen('Z')) disable_z();
  5613. #if ((E0_ENABLE_PIN != X_ENABLE_PIN) && (E1_ENABLE_PIN != Y_ENABLE_PIN)) // Only enable on boards that have seperate ENABLE_PINS
  5614. if (code_seen('E')) {
  5615. disable_e0();
  5616. disable_e1();
  5617. disable_e2();
  5618. }
  5619. #endif
  5620. }
  5621. }
  5622. break;
  5623. /*!
  5624. ### M85 - Set max inactive time <a href="https://reprap.org/wiki/G-code#M85:_Set_Inactivity_Shutdown_Timer">M85: Set Inactivity Shutdown Timer</a>
  5625. #### Usage
  5626. M85 [ S ]
  5627. #### Parameters
  5628. - `S` - specifies the time in seconds. If a value of 0 is specified, the timer is disabled.
  5629. */
  5630. case 85: // M85
  5631. if(code_seen('S')) {
  5632. max_inactive_time = code_value() * 1000;
  5633. }
  5634. break;
  5635. #ifdef SAFETYTIMER
  5636. /*!
  5637. ### 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>
  5638. When safety timer expires, heatbed and nozzle target temperatures are set to zero.
  5639. #### Usage
  5640. M86 [ S ]
  5641. #### Parameters
  5642. - `S` - specifies the time in seconds. If a value of 0 is specified, the timer is disabled.
  5643. */
  5644. case 86:
  5645. if (code_seen('S')) {
  5646. safetytimer_inactive_time = code_value() * 1000;
  5647. safetyTimer.start();
  5648. }
  5649. break;
  5650. #endif
  5651. /*!
  5652. ### 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>
  5653. 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)
  5654. #### Usage
  5655. M92 [ X | Y | Z | E ]
  5656. #### Parameters
  5657. - `X` - Steps per unit for the X drive
  5658. - `Y` - Steps per unit for the Y drive
  5659. - `Z` - Steps per unit for the Z drive
  5660. - `E` - Steps per unit for the extruder drive
  5661. */
  5662. case 92:
  5663. for(int8_t i=0; i < NUM_AXIS; i++)
  5664. {
  5665. if(code_seen(axis_codes[i]))
  5666. {
  5667. if(i == E_AXIS) { // E
  5668. float value = code_value();
  5669. if(value < 20.0) {
  5670. float factor = cs.axis_steps_per_unit[i] / value; // increase e constants if M92 E14 is given for netfab.
  5671. cs.max_jerk[E_AXIS] *= factor;
  5672. max_feedrate[i] *= factor;
  5673. axis_steps_per_sqr_second[i] *= factor;
  5674. }
  5675. cs.axis_steps_per_unit[i] = value;
  5676. #if defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  5677. fsensor.init();
  5678. #endif //defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  5679. }
  5680. else {
  5681. cs.axis_steps_per_unit[i] = code_value();
  5682. }
  5683. }
  5684. }
  5685. reset_acceleration_rates();
  5686. break;
  5687. /*!
  5688. ### M110 - Set Line number <a href="https://reprap.org/wiki/G-code#M110:_Set_Current_Line_Number">M110: Set Current Line Number</a>
  5689. Sets the line number in G-code
  5690. #### Usage
  5691. M110 [ N ]
  5692. #### Parameters
  5693. - `N` - Line number
  5694. */
  5695. case 110:
  5696. if (code_seen('N'))
  5697. gcode_LastN = code_value_long();
  5698. break;
  5699. /*!
  5700. ### M113 - Get or set host keep-alive interval <a href="https://reprap.org/wiki/G-code#M113:_Host_Keepalive">M113: Host Keepalive</a>
  5701. 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).
  5702. #### Usage
  5703. M113 [ S ]
  5704. #### Parameters
  5705. - `S` - Seconds. Default is 2 seconds between "busy" messages
  5706. */
  5707. case 113:
  5708. if (code_seen('S')) {
  5709. host_keepalive_interval = code_value_uint8();
  5710. // NOMORE(host_keepalive_interval, 60);
  5711. }
  5712. else {
  5713. SERIAL_ECHO_START;
  5714. SERIAL_ECHOPAIR("M113 S", (unsigned long)host_keepalive_interval);
  5715. SERIAL_PROTOCOLLN();
  5716. }
  5717. break;
  5718. /*!
  5719. ### M115 - Firmware info <a href="https://reprap.org/wiki/G-code#M115:_Get_Firmware_Version_and_Capabilities">M115: Get Firmware Version and Capabilities</a>
  5720. Print the firmware info and capabilities
  5721. Without any arguments, prints Prusa firmware version number, machine type, extruder count and UUID.
  5722. `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.
  5723. _Examples:_
  5724. `M115` results:
  5725. `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`
  5726. `M115 V` results:
  5727. `3.8.1`
  5728. `M115 U3.8.2-RC1` results on LCD display for 30s or user interaction:
  5729. `New firmware version available: 3.8.2-RC1 Please upgrade.`
  5730. #### Usage
  5731. M115 [ V | U ]
  5732. #### Parameters
  5733. - V - Report current installed firmware version
  5734. - U - Firmware version provided by G-code to be compared to current one.
  5735. */
  5736. case 115: // M115
  5737. if (code_seen('V')) {
  5738. // Report the Prusa version number.
  5739. SERIAL_PROTOCOLLNRPGM(FW_VERSION_STR_P());
  5740. } else if (code_seen('U')) {
  5741. // Check the firmware version provided. If the firmware version provided by the U code is higher than the currently running firmware,
  5742. // pause the print for 30s and ask the user to upgrade the firmware.
  5743. show_upgrade_dialog_if_version_newer(++ strchr_pointer);
  5744. } else {
  5745. SERIAL_ECHOPGM("FIRMWARE_NAME:Prusa-Firmware ");
  5746. SERIAL_ECHORPGM(FW_VERSION_STR_P());
  5747. SERIAL_ECHOPGM(" based on Marlin FIRMWARE_URL:https://github.com/prusa3d/Prusa-Firmware PROTOCOL_VERSION:");
  5748. SERIAL_ECHOPGM(PROTOCOL_VERSION);
  5749. SERIAL_ECHOPGM(" MACHINE_TYPE:");
  5750. SERIAL_ECHOPGM(CUSTOM_MENDEL_NAME);
  5751. SERIAL_ECHOPGM(" EXTRUDER_COUNT:");
  5752. SERIAL_ECHOPGM(STRINGIFY(EXTRUDERS));
  5753. SERIAL_ECHOPGM(" UUID:");
  5754. SERIAL_ECHOLNPGM(MACHINE_UUID);
  5755. #ifdef EXTENDED_CAPABILITIES_REPORT
  5756. extended_capabilities_report();
  5757. #endif //EXTENDED_CAPABILITIES_REPORT
  5758. }
  5759. break;
  5760. /*!
  5761. ### M114 - Get current position <a href="https://reprap.org/wiki/G-code#M114:_Get_Current_Position">M114: Get Current Position</a>
  5762. */
  5763. case 114:
  5764. gcode_M114();
  5765. break;
  5766. /*
  5767. M117 moved up to get the high priority
  5768. case 117: // M117 display message
  5769. starpos = (strchr(strchr_pointer + 5,'*'));
  5770. if(starpos!=NULL)
  5771. *(starpos)='\0';
  5772. lcd_setstatus(strchr_pointer + 5);
  5773. break;*/
  5774. #ifdef M120_M121_ENABLED
  5775. /*!
  5776. ### M120 - Enable endstops <a href="https://reprap.org/wiki/G-code#M120:_Enable_endstop_detection">M120: Enable endstop detection</a>
  5777. */
  5778. case 120:
  5779. enable_endstops(true) ;
  5780. break;
  5781. /*!
  5782. ### M121 - Disable endstops <a href="https://reprap.org/wiki/G-code#M121:_Disable_endstop_detection">M121: Disable endstop detection</a>
  5783. */
  5784. case 121:
  5785. enable_endstops(false) ;
  5786. break;
  5787. #endif //M120_M121_ENABLED
  5788. /*!
  5789. ### M119 - Get endstop states <a href="https://reprap.org/wiki/G-code#M119:_Get_Endstop_Status">M119: Get Endstop Status</a>
  5790. 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.
  5791. */
  5792. case 119:
  5793. SERIAL_PROTOCOLRPGM(_N("Reporting endstop status"));////MSG_M119_REPORT
  5794. SERIAL_PROTOCOLLN();
  5795. #if defined(X_MIN_PIN) && X_MIN_PIN > -1
  5796. SERIAL_PROTOCOLRPGM(_n("x_min: "));////MSG_X_MIN
  5797. if(READ(X_MIN_PIN)^X_MIN_ENDSTOP_INVERTING){
  5798. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5799. }else{
  5800. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5801. }
  5802. SERIAL_PROTOCOLLN();
  5803. #endif
  5804. #if defined(X_MAX_PIN) && X_MAX_PIN > -1
  5805. SERIAL_PROTOCOLRPGM(_n("x_max: "));////MSG_X_MAX
  5806. if(READ(X_MAX_PIN)^X_MAX_ENDSTOP_INVERTING){
  5807. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5808. }else{
  5809. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5810. }
  5811. SERIAL_PROTOCOLLN();
  5812. #endif
  5813. #if defined(Y_MIN_PIN) && Y_MIN_PIN > -1
  5814. SERIAL_PROTOCOLRPGM(_n("y_min: "));////MSG_Y_MIN
  5815. if(READ(Y_MIN_PIN)^Y_MIN_ENDSTOP_INVERTING){
  5816. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5817. }else{
  5818. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5819. }
  5820. SERIAL_PROTOCOLLN();
  5821. #endif
  5822. #if defined(Y_MAX_PIN) && Y_MAX_PIN > -1
  5823. SERIAL_PROTOCOLRPGM(_n("y_max: "));////MSG_Y_MAX
  5824. if(READ(Y_MAX_PIN)^Y_MAX_ENDSTOP_INVERTING){
  5825. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5826. }else{
  5827. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5828. }
  5829. SERIAL_PROTOCOLLN();
  5830. #endif
  5831. #if defined(Z_MIN_PIN) && Z_MIN_PIN > -1
  5832. SERIAL_PROTOCOLRPGM(MSG_Z_MIN);
  5833. if(READ(Z_MIN_PIN)^Z_MIN_ENDSTOP_INVERTING){
  5834. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5835. }else{
  5836. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5837. }
  5838. SERIAL_PROTOCOLLN();
  5839. #endif
  5840. #if defined(Z_MAX_PIN) && Z_MAX_PIN > -1
  5841. SERIAL_PROTOCOLRPGM(MSG_Z_MAX);
  5842. if(READ(Z_MAX_PIN)^Z_MAX_ENDSTOP_INVERTING){
  5843. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5844. }else{
  5845. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5846. }
  5847. SERIAL_PROTOCOLLN();
  5848. #endif
  5849. break;
  5850. //!@todo update for all axes, use for loop
  5851. #if (defined(FANCHECK) && (((defined(TACH_0) && (TACH_0 >-1)) || (defined(TACH_1) && (TACH_1 > -1)))))
  5852. /*!
  5853. ### M123 - Tachometer value <a href="https://www.reprap.org/wiki/G-code#M123:_Tachometer_value_.28RepRap_.26_Prusa.29">M123: Tachometer value</a>
  5854. This command is used to report fan speeds and fan pwm values.
  5855. #### Usage
  5856. M123
  5857. - E0: - Hotend fan speed in RPM
  5858. - PRN1: - Part cooling fans speed in RPM
  5859. - E0@: - Hotend fan PWM value
  5860. - PRN1@: -Part cooling fan PWM value
  5861. _Example:_
  5862. E0:3240 RPM PRN1:4560 RPM E0@:255 PRN1@:255
  5863. */
  5864. case 123:
  5865. gcode_M123();
  5866. break;
  5867. #endif //FANCHECK and TACH_0 and TACH_1
  5868. #ifdef BLINKM
  5869. /*!
  5870. ### M150 - Set RGB(W) Color <a href="https://reprap.org/wiki/G-code#M150:_Set_LED_color">M150: Set LED color</a>
  5871. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code by defining BLINKM and its dependencies.
  5872. #### Usage
  5873. M150 [ R | U | B ]
  5874. #### Parameters
  5875. - `R` - Red color value
  5876. - `U` - Green color value. It is NOT `G`!
  5877. - `B` - Blue color value
  5878. */
  5879. case 150:
  5880. {
  5881. byte red;
  5882. byte grn;
  5883. byte blu;
  5884. if(code_seen('R')) red = code_value();
  5885. if(code_seen('U')) grn = code_value();
  5886. if(code_seen('B')) blu = code_value();
  5887. SendColors(red,grn,blu);
  5888. }
  5889. break;
  5890. #endif //BLINKM
  5891. /*!
  5892. ### M200 - Set filament diameter <a href="https://reprap.org/wiki/G-code#M200:_Set_filament_diameter">M200: Set filament diameter</a>
  5893. #### Usage
  5894. M200 [ D | T ]
  5895. #### Parameters
  5896. - `D` - Diameter in mm
  5897. - `T` - Number of extruder (MMUs)
  5898. */
  5899. case 200: // M200 D<millimeters> set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).
  5900. {
  5901. uint8_t extruder = active_extruder;
  5902. if(code_seen('T')) {
  5903. extruder = code_value_uint8();
  5904. if(extruder >= EXTRUDERS) {
  5905. SERIAL_ECHO_START;
  5906. SERIAL_ECHO(_n("M200 Invalid extruder "));////MSG_M200_INVALID_EXTRUDER
  5907. break;
  5908. }
  5909. }
  5910. if(code_seen('D')) {
  5911. float diameter = code_value();
  5912. if (diameter == 0.0) {
  5913. // setting any extruder filament size disables volumetric on the assumption that
  5914. // slicers either generate in extruder values as cubic mm or as as filament feeds
  5915. // for all extruders
  5916. cs.volumetric_enabled = false;
  5917. } else {
  5918. cs.filament_size[extruder] = code_value();
  5919. // make sure all extruders have some sane value for the filament size
  5920. cs.filament_size[0] = (cs.filament_size[0] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[0]);
  5921. #if EXTRUDERS > 1
  5922. cs.filament_size[1] = (cs.filament_size[1] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[1]);
  5923. #if EXTRUDERS > 2
  5924. cs.filament_size[2] = (cs.filament_size[2] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[2]);
  5925. #endif
  5926. #endif
  5927. cs.volumetric_enabled = true;
  5928. }
  5929. } else {
  5930. //reserved for setting filament diameter via UFID or filament measuring device
  5931. break;
  5932. }
  5933. calculate_extruder_multipliers();
  5934. }
  5935. break;
  5936. /*!
  5937. ### M201 - Set Print Max Acceleration <a href="https://reprap.org/wiki/G-code#M201:_Set_max_acceleration">M201: Set max printing acceleration</a>
  5938. For each axis individually.
  5939. ##### Usage
  5940. M201 [ X | Y | Z | E ]
  5941. ##### Parameters
  5942. - `X` - Acceleration for X axis in units/s^2
  5943. - `Y` - Acceleration for Y axis in units/s^2
  5944. - `Z` - Acceleration for Z axis in units/s^2
  5945. - `E` - Acceleration for the active or specified extruder in units/s^2
  5946. */
  5947. case 201:
  5948. for (int8_t i = 0; i < NUM_AXIS; i++)
  5949. {
  5950. if (code_seen(axis_codes[i]))
  5951. {
  5952. unsigned long val = code_value();
  5953. #ifdef TMC2130
  5954. unsigned long val_silent = val;
  5955. if ((i == X_AXIS) || (i == Y_AXIS))
  5956. {
  5957. if (val > NORMAL_MAX_ACCEL_XY)
  5958. val = NORMAL_MAX_ACCEL_XY;
  5959. if (val_silent > SILENT_MAX_ACCEL_XY)
  5960. val_silent = SILENT_MAX_ACCEL_XY;
  5961. }
  5962. cs.max_acceleration_units_per_sq_second_normal[i] = val;
  5963. cs.max_acceleration_units_per_sq_second_silent[i] = val_silent;
  5964. #else //TMC2130
  5965. max_acceleration_units_per_sq_second[i] = val;
  5966. #endif //TMC2130
  5967. }
  5968. }
  5969. // 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)
  5970. reset_acceleration_rates();
  5971. break;
  5972. #if 0 // Not used for Sprinter/grbl gen6
  5973. case 202: // M202
  5974. for(int8_t i=0; i < NUM_AXIS; i++) {
  5975. if(code_seen(axis_codes[i])) axis_travel_steps_per_sqr_second[i] = code_value() * cs.axis_steps_per_unit[i];
  5976. }
  5977. break;
  5978. #endif
  5979. /*!
  5980. ### M203 - Set Max Feedrate <a href="https://reprap.org/wiki/G-code#M203:_Set_maximum_feedrate">M203: Set maximum feedrate</a>
  5981. For each axis individually.
  5982. ##### Usage
  5983. M203 [ X | Y | Z | E ]
  5984. ##### Parameters
  5985. - `X` - Maximum feedrate for X axis
  5986. - `Y` - Maximum feedrate for Y axis
  5987. - `Z` - Maximum feedrate for Z axis
  5988. - `E` - Maximum feedrate for extruder drives
  5989. */
  5990. case 203: // M203 max feedrate mm/sec
  5991. for (uint8_t i = 0; i < NUM_AXIS; i++)
  5992. {
  5993. if (code_seen(axis_codes[i]))
  5994. {
  5995. float val = code_value();
  5996. #ifdef TMC2130
  5997. float val_silent = val;
  5998. if ((i == X_AXIS) || (i == Y_AXIS))
  5999. {
  6000. if (val > NORMAL_MAX_FEEDRATE_XY)
  6001. val = NORMAL_MAX_FEEDRATE_XY;
  6002. if (val_silent > SILENT_MAX_FEEDRATE_XY)
  6003. val_silent = SILENT_MAX_FEEDRATE_XY;
  6004. }
  6005. cs.max_feedrate_normal[i] = val;
  6006. cs.max_feedrate_silent[i] = val_silent;
  6007. #else //TMC2130
  6008. max_feedrate[i] = val;
  6009. #endif //TMC2130
  6010. }
  6011. }
  6012. break;
  6013. /*!
  6014. ### M204 - Acceleration settings <a href="https://reprap.org/wiki/G-code#M204:_Set_default_acceleration">M204: Set default acceleration</a>
  6015. #### Old format:
  6016. ##### Usage
  6017. M204 [ S | T ]
  6018. ##### Parameters
  6019. - `S` - normal moves
  6020. - `T` - filmanent only moves
  6021. #### New format:
  6022. ##### Usage
  6023. M204 [ P | R | T ]
  6024. ##### Parameters
  6025. - `P` - printing moves
  6026. - `R` - filmanent only moves
  6027. - `T` - travel moves (as of now T is ignored)
  6028. */
  6029. case 204:
  6030. {
  6031. if(code_seen('S')) {
  6032. // Legacy acceleration format. This format is used by the legacy Marlin, MK2 or MK3 firmware,
  6033. // and it is also generated by Slic3r to control acceleration per extrusion type
  6034. // (there is a separate acceleration settings in Slicer for perimeter, first layer etc).
  6035. cs.acceleration = cs.travel_acceleration = code_value();
  6036. // Interpret the T value as retract acceleration in the old Marlin format.
  6037. if(code_seen('T'))
  6038. cs.retract_acceleration = code_value();
  6039. } else {
  6040. // New acceleration format, compatible with the upstream Marlin.
  6041. if(code_seen('P'))
  6042. cs.acceleration = code_value();
  6043. if(code_seen('R'))
  6044. cs.retract_acceleration = code_value();
  6045. if(code_seen('T'))
  6046. cs.travel_acceleration = code_value();
  6047. }
  6048. }
  6049. break;
  6050. /*!
  6051. ### M205 - Set advanced settings <a href="https://reprap.org/wiki/G-code#M205:_Advanced_settings">M205: Advanced settings</a>
  6052. Set some advanced settings related to movement.
  6053. #### Usage
  6054. M205 [ S | T | B | X | Y | Z | E ]
  6055. #### Parameters
  6056. - `S` - Minimum feedrate for print moves (unit/s)
  6057. - `T` - Minimum feedrate for travel moves (units/s)
  6058. - `B` - Minimum segment time (us)
  6059. - `X` - Maximum X jerk (units/s)
  6060. - `Y` - Maximum Y jerk (units/s)
  6061. - `Z` - Maximum Z jerk (units/s)
  6062. - `E` - Maximum E jerk (units/s)
  6063. */
  6064. case 205:
  6065. {
  6066. if(code_seen('S')) cs.minimumfeedrate = code_value();
  6067. if(code_seen('T')) cs.mintravelfeedrate = code_value();
  6068. if(code_seen('B')) cs.minsegmenttime = code_value() ;
  6069. if(code_seen('X')) cs.max_jerk[X_AXIS] = cs.max_jerk[Y_AXIS] = code_value();
  6070. if(code_seen('Y')) cs.max_jerk[Y_AXIS] = code_value();
  6071. if(code_seen('Z')) cs.max_jerk[Z_AXIS] = code_value();
  6072. if(code_seen('E'))
  6073. {
  6074. float e = code_value();
  6075. #ifndef LA_NOCOMPAT
  6076. e = la10c_jerk(e);
  6077. #endif
  6078. cs.max_jerk[E_AXIS] = e;
  6079. }
  6080. }
  6081. break;
  6082. /*!
  6083. ### M206 - Set additional homing offsets <a href="https://reprap.org/wiki/G-code#M206:_Offset_axes">M206: Offset axes</a>
  6084. #### Usage
  6085. M206 [ X | Y | Z ]
  6086. #### Parameters
  6087. - `X` - X axis offset
  6088. - `Y` - Y axis offset
  6089. - `Z` - Z axis offset
  6090. */
  6091. case 206:
  6092. for(uint8_t i=0; i < 3; i++)
  6093. {
  6094. if(code_seen(axis_codes[i])) cs.add_homing[i] = code_value();
  6095. }
  6096. break;
  6097. #ifdef FWRETRACT
  6098. /*!
  6099. ### M207 - Set firmware retraction <a href="https://reprap.org/wiki/G-code#M207:_Set_retract_length">M207: Set retract length</a>
  6100. #### Usage
  6101. M207 [ S | F | Z ]
  6102. #### Parameters
  6103. - `S` - positive length to retract, in mm
  6104. - `F` - retraction feedrate, in mm/min
  6105. - `Z` - additional zlift/hop
  6106. */
  6107. case 207: //M207 - set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop]
  6108. {
  6109. if(code_seen('S'))
  6110. {
  6111. cs.retract_length = code_value() ;
  6112. }
  6113. if(code_seen('F'))
  6114. {
  6115. cs.retract_feedrate = code_value()/60 ;
  6116. }
  6117. if(code_seen('Z'))
  6118. {
  6119. cs.retract_zlift = code_value() ;
  6120. }
  6121. }break;
  6122. /*!
  6123. ### M208 - Set retract recover length <a href="https://reprap.org/wiki/G-code#M208:_Set_unretract_length">M208: Set unretract length</a>
  6124. #### Usage
  6125. M208 [ S | F ]
  6126. #### Parameters
  6127. - `S` - positive length surplus to the M207 Snnn, in mm
  6128. - `F` - feedrate, in mm/sec
  6129. */
  6130. case 208: // M208 - set retract recover length S[positive mm surplus to the M207 S*] F[feedrate mm/min]
  6131. {
  6132. if(code_seen('S'))
  6133. {
  6134. cs.retract_recover_length = code_value() ;
  6135. }
  6136. if(code_seen('F'))
  6137. {
  6138. cs.retract_recover_feedrate = code_value()/60 ;
  6139. }
  6140. }break;
  6141. /*!
  6142. ### M209 - Enable/disable automatict retract <a href="https://reprap.org/wiki/G-code#M209:_Enable_automatic_retract">M209: Enable automatic retract</a>
  6143. 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.
  6144. #### Usage
  6145. M209 [ S ]
  6146. #### Parameters
  6147. - `S` - 1=true or 0=false
  6148. */
  6149. 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.
  6150. {
  6151. if(code_seen('S'))
  6152. {
  6153. switch(code_value_uint8())
  6154. {
  6155. case 0:
  6156. {
  6157. cs.autoretract_enabled=false;
  6158. retracted[0]=false;
  6159. #if EXTRUDERS > 1
  6160. retracted[1]=false;
  6161. #endif
  6162. #if EXTRUDERS > 2
  6163. retracted[2]=false;
  6164. #endif
  6165. }break;
  6166. case 1:
  6167. {
  6168. cs.autoretract_enabled=true;
  6169. retracted[0]=false;
  6170. #if EXTRUDERS > 1
  6171. retracted[1]=false;
  6172. #endif
  6173. #if EXTRUDERS > 2
  6174. retracted[2]=false;
  6175. #endif
  6176. }break;
  6177. default:
  6178. SERIAL_ECHO_START;
  6179. SERIAL_ECHORPGM(MSG_UNKNOWN_COMMAND);
  6180. SERIAL_ECHO(CMDBUFFER_CURRENT_STRING);
  6181. SERIAL_ECHOLNPGM("\"(1)");
  6182. }
  6183. }
  6184. }break;
  6185. #endif // FWRETRACT
  6186. /*!
  6187. ### M214 - Set Arc configuration values (Use M500 to store in eeprom)
  6188. #### Usage
  6189. M214 [P] [S] [N] [R] [F]
  6190. #### Parameters
  6191. - `P` - A float representing the max and default millimeters per arc segment. Must be greater than 0.
  6192. - `S` - A float representing the minimum allowable millimeters per arc segment. Set to 0 to disable
  6193. - `N` - An int representing the number of arcs to draw before correcting the small angle approximation. Set to 0 to disable.
  6194. - `R` - An int representing the minimum number of segments per arcs of any radius,
  6195. except when the results in segment lengths greater than or less than the minimum
  6196. and maximum segment length. Set to 0 to disable.
  6197. - 'F' - An int representing the number of segments per second, unless this results in segment lengths
  6198. greater than or less than the minimum and maximum segment length. Set to 0 to disable.
  6199. */
  6200. 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>
  6201. {
  6202. // Extract all possible parameters if they appear
  6203. float p = code_seen('P') ? code_value_float() : cs.mm_per_arc_segment;
  6204. float s = code_seen('S') ? code_value_float() : cs.min_mm_per_arc_segment;
  6205. unsigned char n = code_seen('N') ? code_value() : cs.n_arc_correction;
  6206. unsigned short r = code_seen('R') ? code_value() : cs.min_arc_segments;
  6207. unsigned short f = code_seen('F') ? code_value() : cs.arc_segments_per_sec;
  6208. // 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
  6209. if (p <=0 || s < 0 || p < s)
  6210. {
  6211. // Should we display some error here?
  6212. break;
  6213. }
  6214. cs.mm_per_arc_segment = p;
  6215. cs.min_mm_per_arc_segment = s;
  6216. cs.n_arc_correction = n;
  6217. cs.min_arc_segments = r;
  6218. cs.arc_segments_per_sec = f;
  6219. }break;
  6220. #if EXTRUDERS > 1
  6221. /*!
  6222. ### M218 - Set hotend offset <a href="https://reprap.org/wiki/G-code#M218:_Set_Hotend_Offset">M218: Set Hotend Offset</a>
  6223. 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.
  6224. #### Usage
  6225. M218 [ X | Y ]
  6226. #### Parameters
  6227. - `X` - X offset
  6228. - `Y` - Y offset
  6229. */
  6230. case 218: // M218 - set hotend offset (in mm), T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  6231. {
  6232. uint8_t extruder;
  6233. if(setTargetedHotend(218, extruder)){
  6234. break;
  6235. }
  6236. if(code_seen('X'))
  6237. {
  6238. extruder_offset[X_AXIS][extruder] = code_value();
  6239. }
  6240. if(code_seen('Y'))
  6241. {
  6242. extruder_offset[Y_AXIS][extruder] = code_value();
  6243. }
  6244. SERIAL_ECHO_START;
  6245. SERIAL_ECHORPGM(MSG_HOTEND_OFFSET);
  6246. for(extruder = 0; extruder < EXTRUDERS; extruder++)
  6247. {
  6248. SERIAL_ECHO(" ");
  6249. SERIAL_ECHO(extruder_offset[X_AXIS][extruder]);
  6250. SERIAL_ECHO(",");
  6251. SERIAL_ECHO(extruder_offset[Y_AXIS][extruder]);
  6252. }
  6253. SERIAL_ECHOLN("");
  6254. }break;
  6255. #endif
  6256. /*!
  6257. ### 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>
  6258. #### Usage
  6259. M220 [ B | S | R ]
  6260. #### Parameters
  6261. - `B` - Backup current speed factor
  6262. - `S` - Speed factor override percentage (0..100 or higher)
  6263. - `R` - Restore previous speed factor
  6264. */
  6265. case 220: // M220 S<factor in percent>- set speed factor override percentage
  6266. {
  6267. bool codesWereSeen = false;
  6268. if (code_seen('B')) //backup current speed factor
  6269. {
  6270. saved_feedmultiply_mm = feedmultiply;
  6271. codesWereSeen = true;
  6272. }
  6273. if (code_seen('S'))
  6274. {
  6275. feedmultiply = code_value_short();
  6276. codesWereSeen = true;
  6277. }
  6278. if (code_seen('R')) //restore previous feedmultiply
  6279. {
  6280. feedmultiply = saved_feedmultiply_mm;
  6281. codesWereSeen = true;
  6282. }
  6283. if (!codesWereSeen)
  6284. {
  6285. printf_P(PSTR("%i%%\n"), feedmultiply);
  6286. }
  6287. }
  6288. break;
  6289. /*!
  6290. ### 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>
  6291. #### Usage
  6292. M221 [ S | T ]
  6293. #### Parameters
  6294. - `S` - Extrude factor override percentage (0..100 or higher), default 100%
  6295. - `T` - Extruder drive number (Prusa Firmware only), default 0 if not set.
  6296. */
  6297. case 221: // M221 S<factor in percent>- set extrude factor override percentage
  6298. {
  6299. if (code_seen('S'))
  6300. {
  6301. int tmp_code = code_value_short();
  6302. if (code_seen('T'))
  6303. {
  6304. uint8_t extruder;
  6305. if (setTargetedHotend(221, extruder))
  6306. break;
  6307. extruder_multiply[extruder] = tmp_code;
  6308. }
  6309. else
  6310. {
  6311. extrudemultiply = tmp_code ;
  6312. }
  6313. }
  6314. else
  6315. {
  6316. printf_P(PSTR("%i%%\n"), extrudemultiply);
  6317. }
  6318. calculate_extruder_multipliers();
  6319. }
  6320. break;
  6321. /*!
  6322. ### M226 - Wait for Pin state <a href="https://reprap.org/wiki/G-code#M226:_Wait_for_pin_state">M226: Wait for pin state</a>
  6323. Wait until the specified pin reaches the state required
  6324. #### Usage
  6325. M226 [ P | S ]
  6326. #### Parameters
  6327. - `P` - pin number
  6328. - `S` - pin state
  6329. */
  6330. case 226: // M226 P<pin number> S<pin state>- Wait until the specified pin reaches the state required
  6331. {
  6332. if(code_seen('P')){
  6333. int pin_number = code_value_short(); // pin number
  6334. int pin_state = -1; // required pin state - default is inverted
  6335. if(code_seen('S')) pin_state = code_value_short(); // required pin state
  6336. if(pin_state >= -1 && pin_state <= 1){
  6337. for(int8_t i = 0; i < (int8_t)(sizeof(sensitive_pins)/sizeof(sensitive_pins[0])); i++)
  6338. {
  6339. if (((int8_t)pgm_read_byte(&sensitive_pins[i]) == pin_number))
  6340. {
  6341. pin_number = -1;
  6342. break;
  6343. }
  6344. }
  6345. if (pin_number > -1)
  6346. {
  6347. int target = LOW;
  6348. st_synchronize();
  6349. pinMode(pin_number, INPUT);
  6350. switch(pin_state){
  6351. case 1:
  6352. target = HIGH;
  6353. break;
  6354. case 0:
  6355. target = LOW;
  6356. break;
  6357. case -1:
  6358. target = !digitalRead(pin_number);
  6359. break;
  6360. }
  6361. while(digitalRead(pin_number) != target){
  6362. manage_heater();
  6363. manage_inactivity();
  6364. lcd_update(0);
  6365. }
  6366. }
  6367. }
  6368. }
  6369. }
  6370. break;
  6371. #if NUM_SERVOS > 0
  6372. /*!
  6373. ### M280 - Set/Get servo position <a href="https://reprap.org/wiki/G-code#M280:_Set_servo_position">M280: Set servo position</a>
  6374. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  6375. #### Usage
  6376. M280 [ P | S ]
  6377. #### Parameters
  6378. - `P` - Servo index (id)
  6379. - `S` - Target position
  6380. */
  6381. case 280: // M280 - set servo position absolute. P: servo index, S: angle or microseconds
  6382. {
  6383. int servo_index = -1;
  6384. int servo_position = 0;
  6385. if (code_seen('P'))
  6386. servo_index = code_value();
  6387. if (code_seen('S')) {
  6388. servo_position = code_value();
  6389. if ((servo_index >= 0) && (servo_index < NUM_SERVOS)) {
  6390. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  6391. servos[servo_index].attach(0);
  6392. #endif
  6393. servos[servo_index].write(servo_position);
  6394. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  6395. _delay(PROBE_SERVO_DEACTIVATION_DELAY);
  6396. servos[servo_index].detach();
  6397. #endif
  6398. }
  6399. else {
  6400. SERIAL_ECHO_START;
  6401. SERIAL_ECHO("Servo ");
  6402. SERIAL_ECHO(servo_index);
  6403. SERIAL_ECHOLN(" out of range");
  6404. }
  6405. }
  6406. else if (servo_index >= 0) {
  6407. SERIAL_PROTOCOL(MSG_OK);
  6408. SERIAL_PROTOCOL(" Servo ");
  6409. SERIAL_PROTOCOL(servo_index);
  6410. SERIAL_PROTOCOL(": ");
  6411. SERIAL_PROTOCOLLN(servos[servo_index].read());
  6412. }
  6413. }
  6414. break;
  6415. #endif // NUM_SERVOS > 0
  6416. #if (LARGE_FLASH == true && ( BEEPER > 0 || defined(ULTRALCD) || defined(LCD_USE_I2C_BUZZER)))
  6417. /*!
  6418. ### M300 - Play tone <a href="https://reprap.org/wiki/G-code#M300:_Play_beep_sound">M300: Play beep sound</a>
  6419. In Prusa Firmware the defaults are `100Hz` and `1000ms`, so that `M300` without parameters will beep for a second.
  6420. #### Usage
  6421. M300 [ S | P ]
  6422. #### Parameters
  6423. - `S` - frequency in Hz. Not all firmware versions support this parameter
  6424. - `P` - duration in milliseconds
  6425. */
  6426. case 300: // M300
  6427. {
  6428. uint16_t beepS = code_seen('S') ? code_value() : 0;
  6429. uint16_t beepP = code_seen('P') ? code_value() : 1000;
  6430. #if BEEPER > 0
  6431. if (beepP > 0)
  6432. Sound_MakeCustom(beepP,beepS,false);
  6433. #endif
  6434. }
  6435. break;
  6436. #endif // M300
  6437. #ifdef PIDTEMP
  6438. /*!
  6439. ### M301 - Set hotend PID <a href="https://reprap.org/wiki/G-code#M301:_Set_PID_parameters">M301: Set PID parameters</a>
  6440. Sets Proportional (P), Integral (I) and Derivative (D) values for hot end.
  6441. See also <a href="https://reprap.org/wiki/PID_Tuning">PID Tuning.</a>
  6442. #### Usage
  6443. M301 [ P | I | D ]
  6444. #### Parameters
  6445. - `P` - proportional (Kp)
  6446. - `I` - integral (Ki)
  6447. - `D` - derivative (Kd)
  6448. */
  6449. case 301:
  6450. {
  6451. if(code_seen('P')) cs.Kp = code_value();
  6452. if(code_seen('I')) cs.Ki = scalePID_i(code_value());
  6453. if(code_seen('D')) cs.Kd = scalePID_d(code_value());
  6454. updatePID();
  6455. SERIAL_PROTOCOLRPGM(MSG_OK);
  6456. SERIAL_PROTOCOLPGM(" p:");
  6457. SERIAL_PROTOCOL(cs.Kp);
  6458. SERIAL_PROTOCOLPGM(" i:");
  6459. SERIAL_PROTOCOL(unscalePID_i(cs.Ki));
  6460. SERIAL_PROTOCOLPGM(" d:");
  6461. SERIAL_PROTOCOL(unscalePID_d(cs.Kd));
  6462. SERIAL_PROTOCOLLN();
  6463. }
  6464. break;
  6465. #endif //PIDTEMP
  6466. #ifdef PIDTEMPBED
  6467. /*!
  6468. ### M304 - Set bed PID <a href="https://reprap.org/wiki/G-code#M304:_Set_PID_parameters_-_Bed">M304: Set PID parameters - Bed</a>
  6469. Sets Proportional (P), Integral (I) and Derivative (D) values for bed.
  6470. See also <a href="https://reprap.org/wiki/PID_Tuning">PID Tuning.</a>
  6471. #### Usage
  6472. M304 [ P | I | D ]
  6473. #### Parameters
  6474. - `P` - proportional (Kp)
  6475. - `I` - integral (Ki)
  6476. - `D` - derivative (Kd)
  6477. */
  6478. case 304:
  6479. {
  6480. if(code_seen('P')) cs.bedKp = code_value();
  6481. if(code_seen('I')) cs.bedKi = scalePID_i(code_value());
  6482. if(code_seen('D')) cs.bedKd = scalePID_d(code_value());
  6483. updatePID();
  6484. SERIAL_PROTOCOLRPGM(MSG_OK);
  6485. SERIAL_PROTOCOLPGM(" p:");
  6486. SERIAL_PROTOCOL(cs.bedKp);
  6487. SERIAL_PROTOCOLPGM(" i:");
  6488. SERIAL_PROTOCOL(unscalePID_i(cs.bedKi));
  6489. SERIAL_PROTOCOLPGM(" d:");
  6490. SERIAL_PROTOCOLLN(unscalePID_d(cs.bedKd));
  6491. }
  6492. break;
  6493. #endif //PIDTEMP
  6494. /*!
  6495. ### M240 - Trigger camera <a href="https://reprap.org/wiki/G-code#M240:_Trigger_camera">M240: Trigger camera</a>
  6496. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  6497. You need to (re)define and assign `CHDK` or `PHOTOGRAPH_PIN` the correct pin number to be able to use the feature.
  6498. */
  6499. case 240: // M240 Triggers a camera by emulating a Canon RC-1 : http://www.doc-diy.net/photo/rc-1_hacked/
  6500. {
  6501. #ifdef CHDK
  6502. SET_OUTPUT(CHDK);
  6503. WRITE(CHDK, HIGH);
  6504. chdkHigh = _millis();
  6505. chdkActive = true;
  6506. #else
  6507. #if defined(PHOTOGRAPH_PIN) && PHOTOGRAPH_PIN > -1
  6508. const uint8_t NUM_PULSES=16;
  6509. const float PULSE_LENGTH=0.01524;
  6510. for(int i=0; i < NUM_PULSES; i++) {
  6511. WRITE(PHOTOGRAPH_PIN, HIGH);
  6512. _delay_ms(PULSE_LENGTH);
  6513. WRITE(PHOTOGRAPH_PIN, LOW);
  6514. _delay_ms(PULSE_LENGTH);
  6515. }
  6516. _delay(7.33);
  6517. for(int i=0; i < NUM_PULSES; i++) {
  6518. WRITE(PHOTOGRAPH_PIN, HIGH);
  6519. _delay_ms(PULSE_LENGTH);
  6520. WRITE(PHOTOGRAPH_PIN, LOW);
  6521. _delay_ms(PULSE_LENGTH);
  6522. }
  6523. #endif
  6524. #endif //chdk end if
  6525. }
  6526. break;
  6527. #ifdef PREVENT_DANGEROUS_EXTRUDE
  6528. /*!
  6529. ### 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>
  6530. 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.
  6531. #### Usage
  6532. M302 [ S ]
  6533. #### Parameters
  6534. - `S` - Cold extrude minimum temperature
  6535. */
  6536. case 302:
  6537. {
  6538. int temp = 0;
  6539. if (code_seen('S')) temp=code_value_short();
  6540. set_extrude_min_temp(temp);
  6541. }
  6542. break;
  6543. #endif
  6544. /*!
  6545. ### M303 - PID autotune <a href="https://reprap.org/wiki/G-code#M303:_Run_PID_tuning">M303: Run PID tuning</a>
  6546. 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.
  6547. #### Usage
  6548. M303 [ E | S | C ]
  6549. #### Parameters
  6550. - `E` - Extruder, default `E0`. Use `E-1` to calibrate the bed PID
  6551. - `S` - Target temperature, default `210°C` for hotend, 70 for bed
  6552. - `C` - Cycles, default `5`
  6553. */
  6554. case 303:
  6555. {
  6556. float temp = 150.0;
  6557. int e = 0;
  6558. int c = 5;
  6559. if (code_seen('E')) e = code_value_short();
  6560. if (e < 0)
  6561. temp = 70;
  6562. if (code_seen('S')) temp = code_value();
  6563. if (code_seen('C')) c = code_value_short();
  6564. PID_autotune(temp, e, c);
  6565. }
  6566. break;
  6567. #ifdef TEMP_MODEL
  6568. /*!
  6569. ### M310 - Temperature model settings <a href="https://reprap.org/wiki/G-code#M310:_Temperature_model_settings">M310: Temperature model settings</a>
  6570. #### Usage
  6571. M310 ; report values
  6572. M310 [ A ] [ F ] ; autotune
  6573. M310 [ S ] ; set 0=disable 1=enable
  6574. M310 [ I ] [ R ] ; set resistance at index
  6575. M310 [ P | C ] ; set power, capacitance
  6576. M310 [ B | E | W ] ; set beeper, warning and error threshold
  6577. M310 [ T ] ; set ambient temperature correction
  6578. #### Parameters
  6579. - `I` - resistance index position (0-15)
  6580. - `R` - resistance value at index (K/W; requires `I`)
  6581. - `P` - power (W)
  6582. - `C` - capacitance (J/K)
  6583. - `S` - set 0=disable 1=enable
  6584. - `B` - beep and warn when reaching warning threshold 0=disable 1=enable (default: 1)
  6585. - `E` - error threshold (K/s; default in variant)
  6586. - `W` - warning threshold (K/s; default in variant)
  6587. - `T` - ambient temperature correction (K; default in variant)
  6588. - `A` - autotune C+R values
  6589. - `F` - force model self-test state (0=off 1=on) during autotune using current values
  6590. */
  6591. case 310:
  6592. {
  6593. // parse all parameters
  6594. float P = NAN, C = NAN, R = NAN, E = NAN, W = NAN, T = NAN;
  6595. int8_t I = -1, S = -1, B = -1, A = -1, F = -1;
  6596. if(code_seen('C')) C = code_value();
  6597. if(code_seen('P')) P = code_value();
  6598. if(code_seen('I')) I = code_value_short();
  6599. if(code_seen('R')) R = code_value();
  6600. if(code_seen('S')) S = code_value_short();
  6601. if(code_seen('B')) B = code_value_short();
  6602. if(code_seen('E')) E = code_value();
  6603. if(code_seen('W')) W = code_value();
  6604. if(code_seen('T')) T = code_value();
  6605. if(code_seen('A')) A = code_value_short();
  6606. if(code_seen('F')) F = code_value_short();
  6607. // report values if nothing has been requested
  6608. if(isnan(C) && isnan(P) && isnan(R) && isnan(E) && isnan(W) && isnan(T) && I < 0 && S < 0 && B < 0 && A < 0) {
  6609. temp_model_report_settings();
  6610. break;
  6611. }
  6612. // update all parameters
  6613. if(B >= 0) temp_model_set_warn_beep(B);
  6614. if(!isnan(C) || !isnan(P) || !isnan(T) || !isnan(W) || !isnan(E)) temp_model_set_params(C, P, T, W, E);
  6615. if(I >= 0 && !isnan(R)) temp_model_set_resistance(I, R);
  6616. // enable the model last, if requested
  6617. if(S >= 0) temp_model_set_enabled(S);
  6618. // run autotune
  6619. if(A >= 0) temp_model_autotune(A, F > 0);
  6620. }
  6621. break;
  6622. #endif
  6623. /*!
  6624. ### 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>
  6625. Finishes all current moves and and thus clears the buffer.
  6626. Equivalent to `G4` with no parameters.
  6627. */
  6628. case 400:
  6629. {
  6630. st_synchronize();
  6631. }
  6632. break;
  6633. /*!
  6634. ### 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>
  6635. Currently three different materials are needed (default, flex and PVA).
  6636. And storing this information for different load/unload profiles etc. in the future firmware does not have to wait for "ok" from MMU.
  6637. #### Usage
  6638. M403 [ E | F ]
  6639. #### Parameters
  6640. - `E` - Extruder number. 0-indexed.
  6641. - `F` - Filament type
  6642. */
  6643. case 403:
  6644. {
  6645. // currently three different materials are needed (default, flex and PVA)
  6646. // add storing this information for different load/unload profiles etc. in the future
  6647. if (MMU2::mmu2.Enabled())
  6648. {
  6649. uint8_t extruder = 255;
  6650. uint8_t filament = FILAMENT_UNDEFINED;
  6651. if(code_seen('E')) extruder = code_value_uint8();
  6652. if(code_seen('F')) filament = code_value_uint8();
  6653. MMU2::mmu2.set_filament_type(extruder, filament);
  6654. }
  6655. }
  6656. break;
  6657. /*!
  6658. ### 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>
  6659. Save current parameters to EEPROM.
  6660. */
  6661. case 500:
  6662. {
  6663. Config_StoreSettings();
  6664. }
  6665. break;
  6666. /*!
  6667. ### M501 - Read settings from EEPROM <a href="https://reprap.org/wiki/G-code#M501:_Read_parameters_from_EEPROM">M501: Read parameters from EEPROM</a>
  6668. Set the active parameters to those stored in the EEPROM. This is useful to revert parameters after experimenting with them.
  6669. */
  6670. case 501:
  6671. {
  6672. Config_RetrieveSettings();
  6673. }
  6674. break;
  6675. /*!
  6676. ### M502 - Revert all settings to factory default <a href="https://reprap.org/wiki/G-code#M502:_Restore_Default_Settings">M502: Restore Default Settings</a>
  6677. 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.
  6678. */
  6679. case 502:
  6680. {
  6681. Config_ResetDefault();
  6682. }
  6683. break;
  6684. /*!
  6685. ### M503 - Repport all settings currently in memory <a href="https://reprap.org/wiki/G-code#M503:_Report_Current_Settings">M503: Report Current Settings</a>
  6686. 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.
  6687. */
  6688. case 503:
  6689. {
  6690. Config_PrintSettings();
  6691. }
  6692. break;
  6693. /*!
  6694. ### M509 - Force language selection <a href="https://reprap.org/wiki/G-code#M509:_Force_language_selection">M509: Force language selection</a>
  6695. Resets the language to English.
  6696. Only on Original Prusa i3 MK2.5/s and MK3/s with multiple languages.
  6697. */
  6698. case 509:
  6699. {
  6700. lang_reset();
  6701. SERIAL_ECHO_START;
  6702. SERIAL_PROTOCOLPGM(("LANG SEL FORCED"));
  6703. }
  6704. break;
  6705. #ifdef ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED
  6706. /*!
  6707. ### 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>
  6708. 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`.
  6709. #### Usage
  6710. M540 [ S ]
  6711. #### Parameters
  6712. - `S` - disabled=0, enabled=1
  6713. */
  6714. case 540:
  6715. {
  6716. if(code_seen('S')) abort_on_endstop_hit = code_value() > 0;
  6717. }
  6718. break;
  6719. #endif
  6720. #ifdef ENABLE_AUTO_BED_LEVELING
  6721. /*!
  6722. ### M851 - Set Z-Probe Offset <a href="https://reprap.org/wiki/G-code#M851:_Set_Z-Probe_Offset">M851: Set Z-Probe Offset"</a>
  6723. 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.
  6724. 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.)
  6725. #### Usage
  6726. M851 [ Z ]
  6727. #### Parameters
  6728. - `Z` - Z offset probe to nozzle.
  6729. */
  6730. #ifdef CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  6731. case CUSTOM_M_CODE_SET_Z_PROBE_OFFSET:
  6732. {
  6733. float value;
  6734. if (code_seen('Z'))
  6735. {
  6736. value = code_value();
  6737. if ((Z_PROBE_OFFSET_RANGE_MIN <= value) && (value <= Z_PROBE_OFFSET_RANGE_MAX))
  6738. {
  6739. cs.zprobe_zoffset = -value; // compare w/ line 278 of ConfigurationStore.cpp
  6740. SERIAL_ECHO_START;
  6741. SERIAL_ECHOLNRPGM(CAT4(MSG_ZPROBE_ZOFFSET, " ", MSG_OK,PSTR("")));
  6742. SERIAL_PROTOCOLLN();
  6743. }
  6744. else
  6745. {
  6746. SERIAL_ECHO_START;
  6747. SERIAL_ECHORPGM(MSG_ZPROBE_ZOFFSET);
  6748. SERIAL_ECHORPGM(MSG_Z_MIN);
  6749. SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MIN);
  6750. SERIAL_ECHORPGM(MSG_Z_MAX);
  6751. SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MAX);
  6752. SERIAL_PROTOCOLLN();
  6753. }
  6754. }
  6755. else
  6756. {
  6757. SERIAL_ECHO_START;
  6758. SERIAL_ECHOLNRPGM(CAT2(MSG_ZPROBE_ZOFFSET, PSTR(" : ")));
  6759. SERIAL_ECHO(-cs.zprobe_zoffset);
  6760. SERIAL_PROTOCOLLN();
  6761. }
  6762. break;
  6763. }
  6764. #endif // CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  6765. #endif // ENABLE_AUTO_BED_LEVELING
  6766. /*!
  6767. ### 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>
  6768. Sets the printer IP address that is shown in the support menu. Designed to be used with the help of host software.
  6769. If P is not specified nothing happens.
  6770. 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.
  6771. #### Usage
  6772. M552 [ P<IP_address> ]
  6773. #### Parameters
  6774. - `P` - The IP address in xxx.xxx.xxx.xxx format. Eg: P192.168.1.14
  6775. */
  6776. case 552:
  6777. {
  6778. if (code_seen('P'))
  6779. {
  6780. uint8_t valCnt = 0;
  6781. IP_address = 0;
  6782. do
  6783. {
  6784. *strchr_pointer = '*';
  6785. ((uint8_t*)&IP_address)[valCnt] = code_value_short();
  6786. valCnt++;
  6787. } while ((valCnt < 4) && code_seen('.'));
  6788. if (valCnt != 4)
  6789. IP_address = 0;
  6790. }
  6791. } break;
  6792. #ifdef FILAMENTCHANGEENABLE
  6793. /*!
  6794. ### M600 - Initiate Filament change procedure <a href="https://reprap.org/wiki/G-code#M600:_Filament_change_pause">M600: Filament change pause</a>
  6795. Initiates Filament change, it is also used during Filament Runout Sensor process.
  6796. If the `M600` is triggered under 25mm it will do a Z-lift of 25mm to prevent a filament blob.
  6797. #### Usage
  6798. M600 [ X | Y | Z | E | L | AUTO ]
  6799. - `X` - X position, default 211
  6800. - `Y` - Y position, default 0
  6801. - `Z` - relative lift Z, default 2.
  6802. - `E` - initial retract, default -2
  6803. - `L` - later retract distance for removal, default -80
  6804. - `AUTO` - Automatically (only with MMU)
  6805. */
  6806. case 600: //Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  6807. {
  6808. st_synchronize();
  6809. float x_position = current_position[X_AXIS];
  6810. float y_position = current_position[Y_AXIS];
  6811. float z_shift = 0; // is it necessary to be a float?
  6812. float e_shift_init = 0;
  6813. float e_shift_late = 0;
  6814. bool automatic = false;
  6815. //Retract extruder
  6816. if(code_seen('E'))
  6817. {
  6818. e_shift_init = code_value();
  6819. }
  6820. else
  6821. {
  6822. #ifdef FILAMENTCHANGE_FIRSTRETRACT
  6823. e_shift_init = FILAMENTCHANGE_FIRSTRETRACT ;
  6824. #endif
  6825. }
  6826. //currently don't work as we are using the same unload sequence as in M702, needs re-work
  6827. if (code_seen('L'))
  6828. {
  6829. e_shift_late = code_value();
  6830. }
  6831. else
  6832. {
  6833. #ifdef FILAMENTCHANGE_FINALRETRACT
  6834. e_shift_late = FILAMENTCHANGE_FINALRETRACT;
  6835. #endif
  6836. }
  6837. //Lift Z
  6838. if(code_seen('Z'))
  6839. {
  6840. z_shift = code_value();
  6841. }
  6842. else
  6843. {
  6844. z_shift = gcode_M600_filament_change_z_shift<uint8_t>();
  6845. }
  6846. //Move XY to side
  6847. if(code_seen('X'))
  6848. {
  6849. x_position = code_value();
  6850. }
  6851. else
  6852. {
  6853. #ifdef FILAMENTCHANGE_XPOS
  6854. x_position = FILAMENTCHANGE_XPOS;
  6855. #endif
  6856. }
  6857. if(code_seen('Y'))
  6858. {
  6859. y_position = code_value();
  6860. }
  6861. else
  6862. {
  6863. #ifdef FILAMENTCHANGE_YPOS
  6864. y_position = FILAMENTCHANGE_YPOS ;
  6865. #endif
  6866. }
  6867. if (MMU2::mmu2.Enabled() && code_seen_P(PSTR("AUTO")))
  6868. automatic = true;
  6869. gcode_M600(automatic, x_position, y_position, z_shift, e_shift_init, e_shift_late);
  6870. }
  6871. break;
  6872. #endif //FILAMENTCHANGEENABLE
  6873. /*!
  6874. ### M601 - Pause print <a href="https://reprap.org/wiki/G-code#M601:_Pause_print">M601: Pause print</a>
  6875. */
  6876. /*!
  6877. ### M125 - Pause print (TODO: not implemented)
  6878. */
  6879. /*!
  6880. ### M25 - Pause SD print <a href="https://reprap.org/wiki/G-code#M25:_Pause_SD_print">M25: Pause SD print</a>
  6881. */
  6882. case 25:
  6883. case 601:
  6884. {
  6885. if (!isPrintPaused) {
  6886. st_synchronize();
  6887. ClearToSend(); //send OK even before the command finishes executing because we want to make sure it is not skipped because of cmdqueue_pop_front();
  6888. cmdqueue_pop_front(); //trick because we want skip this command (M601) after restore
  6889. lcd_pause_print();
  6890. }
  6891. }
  6892. break;
  6893. /*!
  6894. ### M602 - Resume print <a href="https://reprap.org/wiki/G-code#M602:_Resume_print">M602: Resume print</a>
  6895. */
  6896. case 602:
  6897. {
  6898. if (isPrintPaused) lcd_resume_print();
  6899. }
  6900. break;
  6901. /*!
  6902. ### M603 - Stop print <a href="https://reprap.org/wiki/G-code#M603:_Stop_print">M603: Stop print</a>
  6903. */
  6904. case 603: {
  6905. lcd_print_stop();
  6906. }
  6907. break;
  6908. #ifdef PINDA_THERMISTOR
  6909. /*!
  6910. ### 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>
  6911. Wait for PINDA thermistor to reach target temperature
  6912. #### Usage
  6913. M860 [ S ]
  6914. #### Parameters
  6915. - `S` - Target temperature
  6916. */
  6917. case 860:
  6918. {
  6919. int set_target_pinda = 0;
  6920. if (code_seen('S')) {
  6921. set_target_pinda = code_value_short();
  6922. }
  6923. else {
  6924. break;
  6925. }
  6926. LCD_MESSAGERPGM(_T(MSG_PLEASE_WAIT));
  6927. SERIAL_PROTOCOLPGM("Wait for PINDA target temperature:");
  6928. SERIAL_PROTOCOLLN(set_target_pinda);
  6929. codenum = _millis();
  6930. cancel_heatup = false;
  6931. bool is_pinda_cooling = false;
  6932. if ((degTargetBed() == 0) && (degTargetHotend(0) == 0)) {
  6933. is_pinda_cooling = true;
  6934. }
  6935. while ( ((!is_pinda_cooling) && (!cancel_heatup) && (current_temperature_pinda < set_target_pinda)) || (is_pinda_cooling && (current_temperature_pinda > set_target_pinda)) ) {
  6936. if ((_millis() - codenum) > 1000) //Print Temp Reading every 1 second while waiting.
  6937. {
  6938. SERIAL_PROTOCOLPGM("P:");
  6939. SERIAL_PROTOCOL_F(current_temperature_pinda, 1);
  6940. SERIAL_PROTOCOL('/');
  6941. SERIAL_PROTOCOLLN(set_target_pinda);
  6942. codenum = _millis();
  6943. }
  6944. manage_heater();
  6945. manage_inactivity();
  6946. lcd_update(0);
  6947. }
  6948. LCD_MESSAGERPGM(MSG_OK);
  6949. break;
  6950. }
  6951. /*!
  6952. ### 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>
  6953. Set compensation ustep value `S` for compensation table index `I`.
  6954. #### Usage
  6955. M861 [ ? | ! | Z | S | I ]
  6956. #### Parameters
  6957. - `?` - Print current EEPROM offset values
  6958. - `!` - Set factory default values
  6959. - `Z` - Set all values to 0 (effectively disabling PINDA temperature compensation)
  6960. - `S` - Microsteps
  6961. - `I` - Table index
  6962. */
  6963. case 861: {
  6964. const char * const _header = PSTR("index, temp, ustep, um");
  6965. if (code_seen('?')) { // ? - Print out current EEPROM offset values
  6966. int16_t usteps = 0;
  6967. SERIAL_PROTOCOLPGM("PINDA cal status: ");
  6968. SERIAL_PROTOCOLLN(calibration_status_pinda());
  6969. SERIAL_PROTOCOLLNRPGM(_header);
  6970. for (uint8_t i = 0; i < 6; i++)
  6971. {
  6972. if(i > 0) {
  6973. usteps = eeprom_read_word((uint16_t*) EEPROM_PROBE_TEMP_SHIFT + (i - 1));
  6974. }
  6975. float mm = ((float)usteps) / cs.axis_steps_per_unit[Z_AXIS];
  6976. i == 0 ? SERIAL_PROTOCOLPGM("n/a") : SERIAL_PROTOCOL(i - 1);
  6977. SERIAL_PROTOCOLPGM(", ");
  6978. SERIAL_PROTOCOL(35 + (i * 5));
  6979. SERIAL_PROTOCOLPGM(", ");
  6980. SERIAL_PROTOCOL(usteps);
  6981. SERIAL_PROTOCOLPGM(", ");
  6982. SERIAL_PROTOCOLLN(mm * 1000);
  6983. }
  6984. }
  6985. else if (code_seen('!')) { // ! - Set factory default values
  6986. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  6987. int16_t z_shift = 8; //40C - 20um - 8usteps
  6988. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT, z_shift);
  6989. z_shift = 24; //45C - 60um - 24usteps
  6990. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + 1, z_shift);
  6991. z_shift = 48; //50C - 120um - 48usteps
  6992. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + 2, z_shift);
  6993. z_shift = 80; //55C - 200um - 80usteps
  6994. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + 3, z_shift);
  6995. z_shift = 120; //60C - 300um - 120usteps
  6996. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + 4, z_shift);
  6997. SERIAL_PROTOCOLLNPGM("factory restored");
  6998. }
  6999. else if (code_seen('Z')) { // Z - Set all values to 0 (effectively disabling PINDA temperature compensation)
  7000. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  7001. int16_t z_shift = 0;
  7002. for (uint8_t i = 0; i < 5; i++) {
  7003. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  7004. }
  7005. SERIAL_PROTOCOLLNPGM("zerorized");
  7006. }
  7007. else if (code_seen('S')) { // Sxxx Iyyy - Set compensation ustep value S for compensation table index I
  7008. int16_t usteps = code_value_short();
  7009. if (code_seen('I')) {
  7010. uint8_t index = code_value_uint8();
  7011. if (index < 5) {
  7012. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + index, usteps);
  7013. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  7014. SERIAL_PROTOCOLLNRPGM(_header);
  7015. for (uint8_t i = 0; i < 6; i++)
  7016. {
  7017. usteps = 0;
  7018. if (i > 0) {
  7019. usteps = eeprom_read_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + (i - 1));
  7020. }
  7021. float mm = ((float)usteps) / cs.axis_steps_per_unit[Z_AXIS];
  7022. i == 0 ? SERIAL_PROTOCOLPGM("n/a") : SERIAL_PROTOCOL(i - 1);
  7023. SERIAL_PROTOCOLPGM(", ");
  7024. SERIAL_PROTOCOL(35 + (i * 5));
  7025. SERIAL_PROTOCOLPGM(", ");
  7026. SERIAL_PROTOCOL(usteps);
  7027. SERIAL_PROTOCOLPGM(", ");
  7028. SERIAL_PROTOCOLLN(mm * 1000);
  7029. }
  7030. }
  7031. }
  7032. }
  7033. else {
  7034. SERIAL_PROTOCOLLNPGM("no valid command");
  7035. }
  7036. } break;
  7037. #endif //PINDA_THERMISTOR
  7038. /*!
  7039. ### M862 - Print checking <a href="https://reprap.org/wiki/G-code#M862:_Print_checking">M862: Print checking</a>
  7040. Checks the parameters of the printer and gcode and performs compatibility check
  7041. - M862.1 { P<nozzle_diameter> | Q } 0.25/0.40/0.60
  7042. - M862.2 { P<model_code> | Q }
  7043. - M862.3 { P"<model_name>" | Q }
  7044. - M862.4 { P<fw_version> | Q }
  7045. - M862.5 { P<gcode_level> | Q }
  7046. When run with P<> argument, the check is performed against the input value.
  7047. When run with Q argument, the current value is shown.
  7048. M862.3 accepts text identifiers of printer types too.
  7049. The syntax of M862.3 is (note the quotes around the type):
  7050. M862.3 P "MK3S"
  7051. Accepted printer type identifiers and their numeric counterparts:
  7052. - MK1 (100)
  7053. - MK2 (200)
  7054. - MK2MM (201)
  7055. - MK2S (202)
  7056. - MK2SMM (203)
  7057. - MK2.5 (250)
  7058. - MK2.5MMU2 (20250)
  7059. - MK2.5S (252)
  7060. - MK2.5SMMU2S (20252)
  7061. - MK3 (300)
  7062. - MK3MMU2 (20300)
  7063. - MK3S (302)
  7064. - MK3SMMU2S (20302)
  7065. */
  7066. case 862: // M862: print checking
  7067. float nDummy;
  7068. uint8_t nCommand;
  7069. nCommand=(uint8_t)(modff(code_value_float(),&nDummy)*10.0+0.5);
  7070. switch((ClPrintChecking)nCommand)
  7071. {
  7072. case ClPrintChecking::_Nozzle: // ~ .1
  7073. uint16_t nDiameter;
  7074. if(code_seen('P'))
  7075. {
  7076. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  7077. nozzle_diameter_check(nDiameter);
  7078. }
  7079. else if(code_seen('Q'))
  7080. SERIAL_PROTOCOLLN((float)eeprom_read_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM)/1000.0);
  7081. break;
  7082. case ClPrintChecking::_Model: // ~ .2
  7083. if(code_seen('P'))
  7084. {
  7085. uint16_t nPrinterModel;
  7086. nPrinterModel=(uint16_t)code_value_long();
  7087. printer_model_check(nPrinterModel);
  7088. }
  7089. else if(code_seen('Q'))
  7090. SERIAL_PROTOCOLLN(nPrinterType);
  7091. break;
  7092. case ClPrintChecking::_Smodel: // ~ .3
  7093. if(code_seen('P'))
  7094. printer_smodel_check(strchr_pointer);
  7095. else if(code_seen('Q'))
  7096. SERIAL_PROTOCOLLNRPGM(sPrinterName);
  7097. break;
  7098. case ClPrintChecking::_Version: // ~ .4
  7099. if(code_seen('P'))
  7100. fw_version_check(++strchr_pointer);
  7101. else if(code_seen('Q'))
  7102. SERIAL_PROTOCOLLNRPGM(FW_VERSION_STR_P());
  7103. break;
  7104. case ClPrintChecking::_Gcode: // ~ .5
  7105. if(code_seen('P'))
  7106. {
  7107. uint16_t nGcodeLevel;
  7108. nGcodeLevel=(uint16_t)code_value_long();
  7109. gcode_level_check(nGcodeLevel);
  7110. }
  7111. else if(code_seen('Q'))
  7112. SERIAL_PROTOCOLLN(GCODE_LEVEL);
  7113. break;
  7114. }
  7115. break;
  7116. #ifdef LIN_ADVANCE
  7117. /*!
  7118. ### 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>
  7119. 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.
  7120. #### Usage
  7121. M900 [ K | R | W | H | D]
  7122. #### Parameters
  7123. - `K` - Advance K factor
  7124. - `R` - Set ratio directly (overrides WH/D)
  7125. - `W` - Width
  7126. - `H` - Height
  7127. - `D` - Diameter Set ratio from WH/D
  7128. */
  7129. case 900:
  7130. gcode_M900();
  7131. break;
  7132. #endif
  7133. /*!
  7134. ### 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>
  7135. Set digital trimpot motor current using axis codes (X, Y, Z, E, B, S).
  7136. M907 has no effect when the experimental Extruder motor current scaling mode is active (that applies to farm printing as well)
  7137. #### Usage
  7138. M907 [ X | Y | Z | E | B | S ]
  7139. #### Parameters
  7140. - `X` - X motor driver
  7141. - `Y` - Y motor driver
  7142. - `Z` - Z motor driver
  7143. - `E` - Extruder motor driver
  7144. - `B` - Second Extruder motor driver
  7145. - `S` - All motors
  7146. */
  7147. case 907:
  7148. {
  7149. #ifdef TMC2130
  7150. // See tmc2130_cur2val() for translation to 0 .. 63 range
  7151. for (uint_least8_t i = 0; i < NUM_AXIS; i++){
  7152. if(code_seen(axis_codes[i])){
  7153. if( i == E_AXIS && FarmOrUserECool() ){
  7154. SERIAL_ECHORPGM(eMotorCurrentScalingEnabled);
  7155. SERIAL_ECHOLNPGM(", M907 E ignored");
  7156. continue;
  7157. }
  7158. long cur_mA = code_value_long();
  7159. uint8_t val = tmc2130_cur2val(cur_mA);
  7160. tmc2130_set_current_h(i, val);
  7161. tmc2130_set_current_r(i, val);
  7162. //if (i == E_AXIS) printf_P(PSTR("E-axis current=%ldmA\n"), cur_mA);
  7163. }
  7164. }
  7165. #else //TMC2130
  7166. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  7167. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) st_current_set(i,code_value());
  7168. if(code_seen('B')) st_current_set(4,code_value());
  7169. if(code_seen('S')) for(int i=0;i<=4;i++) st_current_set(i,code_value());
  7170. #endif
  7171. #ifdef MOTOR_CURRENT_PWM_XY_PIN
  7172. if(code_seen('X')) st_current_set(0, code_value());
  7173. #endif
  7174. #ifdef MOTOR_CURRENT_PWM_Z_PIN
  7175. if(code_seen('Z')) st_current_set(1, code_value());
  7176. #endif
  7177. #ifdef MOTOR_CURRENT_PWM_E_PIN
  7178. if(code_seen('E')) st_current_set(2, code_value());
  7179. #endif
  7180. #endif //TMC2130
  7181. }
  7182. break;
  7183. /*!
  7184. ### M908 - Control digital trimpot directly <a href="https://reprap.org/wiki/G-code#M908:_Control_digital_trimpot_directly">M908: Control digital trimpot directly</a>
  7185. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code. Not usable on Prusa printers.
  7186. #### Usage
  7187. M908 [ P | S ]
  7188. #### Parameters
  7189. - `P` - channel
  7190. - `S` - current
  7191. */
  7192. case 908:
  7193. {
  7194. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  7195. uint8_t channel,current;
  7196. if(code_seen('P')) channel=code_value();
  7197. if(code_seen('S')) current=code_value();
  7198. digitalPotWrite(channel, current);
  7199. #endif
  7200. }
  7201. break;
  7202. #ifdef TMC2130_SERVICE_CODES_M910_M918
  7203. /*!
  7204. ### M910 - TMC2130 init <a href="https://reprap.org/wiki/G-code#M910:_TMC2130_init">M910: TMC2130 init</a>
  7205. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7206. */
  7207. case 910:
  7208. {
  7209. tmc2130_init(TMCInitParams(false, FarmOrUserECool()));
  7210. }
  7211. break;
  7212. /*!
  7213. ### M911 - Set TMC2130 holding currents <a href="https://reprap.org/wiki/G-code#M911:_Set_TMC2130_holding_currents">M911: Set TMC2130 holding currents</a>
  7214. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7215. #### Usage
  7216. M911 [ X | Y | Z | E ]
  7217. #### Parameters
  7218. - `X` - X stepper driver holding current value
  7219. - `Y` - Y stepper driver holding current value
  7220. - `Z` - Z stepper driver holding current value
  7221. - `E` - Extruder stepper driver holding current value
  7222. */
  7223. case 911:
  7224. {
  7225. if (code_seen('X')) tmc2130_set_current_h(0, code_value());
  7226. if (code_seen('Y')) tmc2130_set_current_h(1, code_value());
  7227. if (code_seen('Z')) tmc2130_set_current_h(2, code_value());
  7228. if (code_seen('E')) tmc2130_set_current_h(3, code_value());
  7229. }
  7230. break;
  7231. /*!
  7232. ### M912 - Set TMC2130 running currents <a href="https://reprap.org/wiki/G-code#M912:_Set_TMC2130_running_currents">M912: Set TMC2130 running currents</a>
  7233. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7234. #### Usage
  7235. M912 [ X | Y | Z | E ]
  7236. #### Parameters
  7237. - `X` - X stepper driver running current value
  7238. - `Y` - Y stepper driver running current value
  7239. - `Z` - Z stepper driver running current value
  7240. - `E` - Extruder stepper driver running current value
  7241. */
  7242. case 912:
  7243. {
  7244. if (code_seen('X')) tmc2130_set_current_r(0, code_value());
  7245. if (code_seen('Y')) tmc2130_set_current_r(1, code_value());
  7246. if (code_seen('Z')) tmc2130_set_current_r(2, code_value());
  7247. if (code_seen('E')) tmc2130_set_current_r(3, code_value());
  7248. }
  7249. break;
  7250. /*!
  7251. ### M913 - Print TMC2130 currents <a href="https://reprap.org/wiki/G-code#M913:_Print_TMC2130_currents">M913: Print TMC2130 currents</a>
  7252. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7253. Shows TMC2130 currents.
  7254. */
  7255. case 913:
  7256. {
  7257. tmc2130_print_currents();
  7258. }
  7259. break;
  7260. /*!
  7261. ### M914 - Set TMC2130 normal mode <a href="https://reprap.org/wiki/G-code#M914:_Set_TMC2130_normal_mode">M914: Set TMC2130 normal mode</a>
  7262. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7263. */
  7264. case 914:
  7265. {
  7266. tmc2130_mode = TMC2130_MODE_NORMAL;
  7267. update_mode_profile();
  7268. tmc2130_init(TMCInitParams(false, FarmOrUserECool()));
  7269. }
  7270. break;
  7271. /*!
  7272. ### M915 - Set TMC2130 silent mode <a href="https://reprap.org/wiki/G-code#M915:_Set_TMC2130_silent_mode">M915: Set TMC2130 silent mode</a>
  7273. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7274. */
  7275. case 915:
  7276. {
  7277. tmc2130_mode = TMC2130_MODE_SILENT;
  7278. update_mode_profile();
  7279. tmc2130_init(TMCInitParams(false, FarmOrUserECool()));
  7280. }
  7281. break;
  7282. /*!
  7283. ### 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>
  7284. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7285. #### Usage
  7286. M916 [ X | Y | Z | E ]
  7287. #### Parameters
  7288. - `X` - X stepper driver stallguard sensitivity threshold value
  7289. - `Y` - Y stepper driver stallguard sensitivity threshold value
  7290. - `Z` - Z stepper driver stallguard sensitivity threshold value
  7291. - `E` - Extruder stepper driver stallguard sensitivity threshold value
  7292. */
  7293. case 916:
  7294. {
  7295. if (code_seen('X')) tmc2130_sg_thr[X_AXIS] = code_value();
  7296. if (code_seen('Y')) tmc2130_sg_thr[Y_AXIS] = code_value();
  7297. if (code_seen('Z')) tmc2130_sg_thr[Z_AXIS] = code_value();
  7298. if (code_seen('E')) tmc2130_sg_thr[E_AXIS] = code_value();
  7299. for (uint8_t a = X_AXIS; a <= E_AXIS; a++)
  7300. printf_P(_N("tmc2130_sg_thr[%c]=%d\n"), "XYZE"[a], tmc2130_sg_thr[a]);
  7301. }
  7302. break;
  7303. /*!
  7304. ### 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>
  7305. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7306. #### Usage
  7307. M917 [ X | Y | Z | E ]
  7308. #### Parameters
  7309. - `X` - X stepper driver PWM amplitude offset value
  7310. - `Y` - Y stepper driver PWM amplitude offset value
  7311. - `Z` - Z stepper driver PWM amplitude offset value
  7312. - `E` - Extruder stepper driver PWM amplitude offset value
  7313. */
  7314. case 917:
  7315. {
  7316. if (code_seen('X')) tmc2130_set_pwm_ampl(0, code_value());
  7317. if (code_seen('Y')) tmc2130_set_pwm_ampl(1, code_value());
  7318. if (code_seen('Z')) tmc2130_set_pwm_ampl(2, code_value());
  7319. if (code_seen('E')) tmc2130_set_pwm_ampl(3, code_value());
  7320. }
  7321. break;
  7322. /*!
  7323. ### 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>
  7324. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7325. #### Usage
  7326. M918 [ X | Y | Z | E ]
  7327. #### Parameters
  7328. - `X` - X stepper driver PWM amplitude gradient value
  7329. - `Y` - Y stepper driver PWM amplitude gradient value
  7330. - `Z` - Z stepper driver PWM amplitude gradient value
  7331. - `E` - Extruder stepper driver PWM amplitude gradient value
  7332. */
  7333. case 918:
  7334. {
  7335. if (code_seen('X')) tmc2130_set_pwm_grad(0, code_value());
  7336. if (code_seen('Y')) tmc2130_set_pwm_grad(1, code_value());
  7337. if (code_seen('Z')) tmc2130_set_pwm_grad(2, code_value());
  7338. if (code_seen('E')) tmc2130_set_pwm_grad(3, code_value());
  7339. }
  7340. break;
  7341. #endif //TMC2130_SERVICE_CODES_M910_M918
  7342. /*!
  7343. ### M350 - Set microstepping mode <a href="https://reprap.org/wiki/G-code#M350:_Set_microstepping_mode">M350: Set microstepping mode</a>
  7344. 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!
  7345. Printers without TMC2130 drivers also have `B` and `S` options. In this case, the steps-per-unit value in not changed!
  7346. #### Usage
  7347. M350 [ X | Y | Z | E | B | S ]
  7348. #### Parameters
  7349. - `X` - X new resolution
  7350. - `Y` - Y new resolution
  7351. - `Z` - Z new resolution
  7352. - `E` - E new resolution
  7353. Only valid for MK2.5(S) or printers without TMC2130 drivers
  7354. - `B` - Second extruder new resolution
  7355. - `S` - All axes new resolution
  7356. */
  7357. case 350:
  7358. {
  7359. #ifdef TMC2130
  7360. for (uint_least8_t i=0; i<NUM_AXIS; i++)
  7361. {
  7362. if(code_seen(axis_codes[i]))
  7363. {
  7364. uint16_t res_new = code_value();
  7365. #ifdef ALLOW_ALL_MRES
  7366. bool res_valid = res_new > 0 && res_new <= 256 && !(res_new & (res_new - 1)); // must be a power of two
  7367. #else
  7368. bool res_valid = (res_new == 8) || (res_new == 16) || (res_new == 32); // resolutions valid for all axis
  7369. res_valid |= (i != E_AXIS) && ((res_new == 1) || (res_new == 2) || (res_new == 4)); // resolutions valid for X Y Z only
  7370. res_valid |= (i == E_AXIS) && ((res_new == 64) || (res_new == 128)); // resolutions valid for E only
  7371. #endif
  7372. if (res_valid)
  7373. {
  7374. st_synchronize();
  7375. uint16_t res = tmc2130_get_res(i);
  7376. tmc2130_set_res(i, res_new);
  7377. cs.axis_ustep_resolution[i] = res_new;
  7378. if (res_new > res)
  7379. {
  7380. uint16_t fac = (res_new / res);
  7381. cs.axis_steps_per_unit[i] *= fac;
  7382. position[i] *= fac;
  7383. }
  7384. else
  7385. {
  7386. uint16_t fac = (res / res_new);
  7387. cs.axis_steps_per_unit[i] /= fac;
  7388. position[i] /= fac;
  7389. }
  7390. #if defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  7391. if (i == E_AXIS)
  7392. fsensor.init();
  7393. #endif //defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  7394. }
  7395. }
  7396. }
  7397. reset_acceleration_rates();
  7398. #else //TMC2130
  7399. #if defined(X_MS1_PIN) && X_MS1_PIN > -1
  7400. if(code_seen('S')) for(int i=0;i<=4;i++) microstep_mode(i,code_value());
  7401. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_mode(i,(uint8_t)code_value());
  7402. if(code_seen('B')) microstep_mode(4,code_value());
  7403. microstep_readings();
  7404. #endif
  7405. #endif //TMC2130
  7406. }
  7407. break;
  7408. /*!
  7409. ### 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>
  7410. Toggle MS1 MS2 pins directly.
  7411. #### Usage
  7412. M351 [B<0|1>] [E<0|1>] S<1|2> [X<0|1>] [Y<0|1>] [Z<0|1>]
  7413. #### Parameters
  7414. - `X` - Update X axis
  7415. - `Y` - Update Y axis
  7416. - `Z` - Update Z axis
  7417. - `E` - Update E axis
  7418. - `S` - which MSx pin to toggle
  7419. - `B` - new pin value
  7420. */
  7421. case 351:
  7422. {
  7423. #if defined(X_MS1_PIN) && X_MS1_PIN > -1
  7424. if(code_seen('S')) switch((int)code_value())
  7425. {
  7426. case 1:
  7427. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_ms(i,code_value(),-1);
  7428. if(code_seen('B')) microstep_ms(4,code_value(),-1);
  7429. break;
  7430. case 2:
  7431. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_ms(i,-1,code_value());
  7432. if(code_seen('B')) microstep_ms(4,-1,code_value());
  7433. break;
  7434. }
  7435. microstep_readings();
  7436. #endif
  7437. }
  7438. break;
  7439. /*!
  7440. ### M701 - Load filament <a href="https://reprap.org/wiki/G-code#M701:_Load_filament">M701: Load filament</a>
  7441. #### Usage
  7442. M701 [ E | T ]
  7443. #### Parameters
  7444. - `E` - ID of filament to load, ranges from 0 to 4
  7445. - `T` - Alias of `E`. Used for compatibility with Marlin
  7446. */
  7447. case 701:
  7448. {
  7449. uint8_t mmuSlotIndex = 0xffU;
  7450. if (MMU2::mmu2.Enabled() && code_seen('E'))
  7451. mmuSlotIndex = code_value_uint8();
  7452. gcode_M701(mmuSlotIndex);
  7453. }
  7454. break;
  7455. /*!
  7456. ### M702 - Unload filament <a href="https://reprap.org/wiki/G-code#M702:_Unload_filament">G32: Undock Z Probe sled</a>
  7457. #### Usage
  7458. M702 [ C ]
  7459. #### Parameters
  7460. - `C` - Unload just current filament
  7461. - without any parameters unload all filaments
  7462. */
  7463. case 702:
  7464. {
  7465. if (code_seen('C')) {
  7466. if(MMU2::mmu2.Enabled()) MMU2::mmu2.unload(); //! if "C" unload current filament; if mmu is not present no action is performed
  7467. }
  7468. else {
  7469. if(MMU2::mmu2.Enabled()) MMU2::mmu2.unload(); //! unload current filament
  7470. else unload_filament();
  7471. }
  7472. }
  7473. break;
  7474. /*!
  7475. #### End of M-Commands
  7476. */
  7477. default:
  7478. printf_P(MSG_UNKNOWN_CODE, 'M', cmdbuffer + bufindr + CMDHDRSIZE);
  7479. }
  7480. // printf_P(_N("END M-CODE=%u\n"), mcode_in_progress);
  7481. mcode_in_progress = 0;
  7482. }
  7483. }
  7484. // end if(code_seen('M')) (end of M codes)
  7485. /*!
  7486. -----------------------------------------------------------------------------------------
  7487. # T Codes
  7488. T<extruder nr.> - select extruder in case of multi extruder printer. select filament in case of MMU_V2.
  7489. #### For MMU_V2:
  7490. T<n> Gcode to extrude at least 38.10 mm at feedrate 19.02 mm/s must follow immediately to load to extruder wheels.
  7491. @n T? Gcode to extrude shouldn't have to follow, load to extruder wheels is done automatically
  7492. @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.
  7493. @n Tc Load to nozzle after filament was prepared by Tc and extruder nozzle is already heated.
  7494. */
  7495. else if(code_seen('T')){
  7496. TCodes(strchr_pointer, code_value());
  7497. } // end if(code_seen('T')) (end of T codes)
  7498. /*!
  7499. #### End of T-Codes
  7500. */
  7501. /**
  7502. *---------------------------------------------------------------------------------
  7503. *# D codes
  7504. */
  7505. else if (code_seen('D')) // D codes (debug)
  7506. {
  7507. switch(code_value_short())
  7508. {
  7509. /*!
  7510. ### D-1 - Endless Loop <a href="https://reprap.org/wiki/G-code#D-1:_Endless_Loop">D-1: Endless Loop</a>
  7511. */
  7512. case -1:
  7513. dcode__1(); break;
  7514. #ifdef DEBUG_DCODES
  7515. /*!
  7516. ### D0 - Reset <a href="https://reprap.org/wiki/G-code#D0:_Reset">D0: Reset</a>
  7517. #### Usage
  7518. D0 [ B ]
  7519. #### Parameters
  7520. - `B` - Bootloader
  7521. */
  7522. case 0:
  7523. dcode_0(); break;
  7524. /*!
  7525. *
  7526. ### D1 - Clear EEPROM and RESET <a href="https://reprap.org/wiki/G-code#D1:_Clear_EEPROM_and_RESET">D1: Clear EEPROM and RESET</a>
  7527. D1
  7528. *
  7529. */
  7530. case 1:
  7531. dcode_1(); break;
  7532. #endif
  7533. #if defined DEBUG_DCODE2 || defined DEBUG_DCODES
  7534. /*!
  7535. ### D2 - Read/Write RAM <a href="https://reprap.org/wiki/G-code#D2:_Read.2FWrite_RAM">D3: Read/Write RAM</a>
  7536. This command can be used without any additional parameters. It will read the entire RAM.
  7537. #### Usage
  7538. D2 [ A | C | X ]
  7539. #### Parameters
  7540. - `A` - Address (x0000-x1fff)
  7541. - `C` - Count (1-8192)
  7542. - `X` - Data
  7543. #### Notes
  7544. - The hex address needs to be lowercase without the 0 before the x
  7545. - Count is decimal
  7546. - The hex data needs to be lowercase
  7547. */
  7548. case 2:
  7549. dcode_2(); break;
  7550. #endif //DEBUG_DCODES
  7551. #if defined DEBUG_DCODE3 || defined DEBUG_DCODES
  7552. /*!
  7553. ### D3 - Read/Write EEPROM <a href="https://reprap.org/wiki/G-code#D3:_Read.2FWrite_EEPROM">D3: Read/Write EEPROM</a>
  7554. This command can be used without any additional parameters. It will read the entire eeprom.
  7555. #### Usage
  7556. D3 [ A | C | X ]
  7557. #### Parameters
  7558. - `A` - Address (x0000-x0fff)
  7559. - `C` - Count (1-4096)
  7560. - `X` - Data (hex)
  7561. #### Notes
  7562. - The hex address needs to be lowercase without the 0 before the x
  7563. - Count is decimal
  7564. - The hex data needs to be lowercase
  7565. */
  7566. case 3:
  7567. dcode_3(); break;
  7568. #endif //DEBUG_DCODE3
  7569. #ifdef DEBUG_DCODES
  7570. /*!
  7571. ### D4 - Read/Write PIN <a href="https://reprap.org/wiki/G-code#D4:_Read.2FWrite_PIN">D4: Read/Write PIN</a>
  7572. To read the digital value of a pin you need only to define the pin number.
  7573. #### Usage
  7574. D4 [ P | F | V ]
  7575. #### Parameters
  7576. - `P` - Pin (0-255)
  7577. - `F` - Function in/out (0/1)
  7578. - `V` - Value (0/1)
  7579. */
  7580. case 4:
  7581. dcode_4(); break;
  7582. #endif //DEBUG_DCODES
  7583. #if defined DEBUG_DCODE5 || defined DEBUG_DCODES
  7584. /*!
  7585. ### D5 - Read/Write FLASH <a href="https://reprap.org/wiki/G-code#D5:_Read.2FWrite_FLASH">D5: Read/Write Flash</a>
  7586. This command can be used without any additional parameters. It will read the 1kb FLASH.
  7587. #### Usage
  7588. D5 [ A | C | X | E ]
  7589. #### Parameters
  7590. - `A` - Address (x00000-x3ffff)
  7591. - `C` - Count (1-8192)
  7592. - `X` - Data (hex)
  7593. - `E` - Erase
  7594. #### Notes
  7595. - The hex address needs to be lowercase without the 0 before the x
  7596. - Count is decimal
  7597. - The hex data needs to be lowercase
  7598. */
  7599. case 5:
  7600. dcode_5(); break;
  7601. #endif //DEBUG_DCODE5
  7602. #if defined DEBUG_DCODE6 || defined DEBUG_DCODES
  7603. /*!
  7604. ### D6 - Read/Write external FLASH <a href="https://reprap.org/wiki/G-code#D6:_Read.2FWrite_external_FLASH">D6: Read/Write external Flash</a>
  7605. Reserved
  7606. */
  7607. case 6:
  7608. dcode_6(); break;
  7609. #endif
  7610. #ifdef DEBUG_DCODES
  7611. /*!
  7612. ### D7 - Read/Write Bootloader <a href="https://reprap.org/wiki/G-code#D7:_Read.2FWrite_Bootloader">D7: Read/Write Bootloader</a>
  7613. Reserved
  7614. */
  7615. case 7:
  7616. dcode_7(); break;
  7617. /*!
  7618. ### D8 - Read/Write PINDA <a href="https://reprap.org/wiki/G-code#D8:_Read.2FWrite_PINDA">D8: Read/Write PINDA</a>
  7619. #### Usage
  7620. D8 [ ? | ! | P | Z ]
  7621. #### Parameters
  7622. - `?` - Read PINDA temperature shift values
  7623. - `!` - Reset PINDA temperature shift values to default
  7624. - `P` - Pinda temperature [C]
  7625. - `Z` - Z Offset [mm]
  7626. */
  7627. case 8:
  7628. dcode_8(); break;
  7629. /*!
  7630. ### D9 - Read ADC <a href="https://reprap.org/wiki/G-code#D9:_Read.2FWrite_ADC">D9: Read ADC</a>
  7631. #### Usage
  7632. D9 [ I | V ]
  7633. #### Parameters
  7634. - `I` - ADC channel index
  7635. - `0` - Heater 0 temperature
  7636. - `1` - Heater 1 temperature
  7637. - `2` - Bed temperature
  7638. - `3` - PINDA temperature
  7639. - `4` - PWR voltage
  7640. - `5` - Ambient temperature
  7641. - `6` - BED voltage
  7642. - `V` Value to be written as simulated
  7643. */
  7644. case 9:
  7645. dcode_9(); break;
  7646. /*!
  7647. ### 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>
  7648. */
  7649. case 10:
  7650. dcode_10(); break;
  7651. /*!
  7652. ### D12 - Time <a href="https://reprap.org/wiki/G-code#D12:_Time">D12: Time</a>
  7653. Writes the current time in the log file.
  7654. */
  7655. #endif //DEBUG_DCODES
  7656. #ifdef XFLASH_DUMP
  7657. /*!
  7658. ### 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>
  7659. Generate a crash dump for later retrival.
  7660. #### Usage
  7661. D20 [E]
  7662. ### Parameters
  7663. - `E` - Perform an emergency crash dump (resets the printer).
  7664. ### Notes
  7665. - A crash dump can be later recovered with D21, or cleared with D22.
  7666. - An emergency crash dump includes register data, but will cause the printer to reset after the dump
  7667. is completed.
  7668. */
  7669. case 20: {
  7670. dcode_20();
  7671. break;
  7672. };
  7673. /*!
  7674. ### 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>
  7675. Output the complete crash dump (if present) to the serial.
  7676. #### Usage
  7677. D21
  7678. ### Notes
  7679. - The starting address can vary between builds, but it's always at the beginning of the data section.
  7680. */
  7681. case 21: {
  7682. dcode_21();
  7683. break;
  7684. };
  7685. /*!
  7686. ### D22 - Clear crash dump state <a href="https://reprap.org/wiki/G-code#D22:_Clear_crash_dump_state">D22: Clear crash dump state</a>
  7687. Clear an existing internal crash dump.
  7688. #### Usage
  7689. D22
  7690. */
  7691. case 22: {
  7692. dcode_22();
  7693. break;
  7694. };
  7695. #endif //XFLASH_DUMP
  7696. #ifdef EMERGENCY_SERIAL_DUMP
  7697. /*!
  7698. ### 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>
  7699. On boards without offline dump support, request online dumps to the serial port on firmware faults.
  7700. When online dumps are enabled, the FW will dump memory on the serial before resetting.
  7701. #### Usage
  7702. D23 [E] [R]
  7703. #### Parameters
  7704. - `E` - Perform an emergency crash dump (resets the printer).
  7705. - `R` - Disable online dumps.
  7706. */
  7707. case 23: {
  7708. dcode_23();
  7709. break;
  7710. };
  7711. #endif
  7712. #ifdef TEMP_MODEL_DEBUG
  7713. /*!
  7714. ## D70 - Enable low-level temperature model logging for offline simulation
  7715. #### Usage
  7716. D70 [ S ]
  7717. #### Parameters
  7718. - `S` - Enable 0-1 (default 0)
  7719. */
  7720. case 70: {
  7721. if(code_seen('S'))
  7722. temp_model_log_enable(code_value_short());
  7723. break;
  7724. }
  7725. #endif
  7726. #ifdef HEATBED_ANALYSIS
  7727. /*!
  7728. ### D80 - Bed check <a href="https://reprap.org/wiki/G-code#D80:_Bed_check">D80: Bed check</a>
  7729. This command will log data to SD card file "mesh.txt".
  7730. #### Usage
  7731. D80 [ E | F | G | H | I | J ]
  7732. #### Parameters
  7733. - `E` - Dimension X (default 40)
  7734. - `F` - Dimention Y (default 40)
  7735. - `G` - Points X (default 40)
  7736. - `H` - Points Y (default 40)
  7737. - `I` - Offset X (default 74)
  7738. - `J` - Offset Y (default 34)
  7739. */
  7740. case 80:
  7741. dcode_80(); break;
  7742. /*!
  7743. ### D81 - Bed analysis <a href="https://reprap.org/wiki/G-code#D81:_Bed_analysis">D80: Bed analysis</a>
  7744. This command will log data to SD card file "wldsd.txt".
  7745. #### Usage
  7746. D81 [ E | F | G | H | I | J ]
  7747. #### Parameters
  7748. - `E` - Dimension X (default 40)
  7749. - `F` - Dimention Y (default 40)
  7750. - `G` - Points X (default 40)
  7751. - `H` - Points Y (default 40)
  7752. - `I` - Offset X (default 74)
  7753. - `J` - Offset Y (default 34)
  7754. */
  7755. case 81:
  7756. dcode_81(); break;
  7757. #endif //HEATBED_ANALYSIS
  7758. #ifdef DEBUG_DCODES
  7759. /*!
  7760. ### 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>
  7761. */
  7762. case 106:
  7763. dcode_106(); break;
  7764. #ifdef TMC2130
  7765. /*!
  7766. ### D2130 - Trinamic stepper controller <a href="https://reprap.org/wiki/G-code#D2130:_Trinamic_stepper_controller">D2130: Trinamic stepper controller</a>
  7767. @todo Please review by owner of the code. RepRap Wiki Gcode needs to be updated after review of owner as well.
  7768. #### Usage
  7769. D2130 [ Axis | Command | Subcommand | Value ]
  7770. #### Parameters
  7771. - Axis
  7772. - `X` - X stepper driver
  7773. - `Y` - Y stepper driver
  7774. - `Z` - Z stepper driver
  7775. - `E` - Extruder stepper driver
  7776. - Commands
  7777. - `0` - Current off
  7778. - `1` - Current on
  7779. - `+` - Single step
  7780. - `-` - Single step oposite direction
  7781. - `NNN` - Value sereval steps
  7782. - `?` - Read register
  7783. - Subcommands for read register
  7784. - `mres` - Micro step resolution. More information in datasheet '5.5.2 CHOPCONF – Chopper Configuration'
  7785. - `step` - Step
  7786. - `mscnt` - Microstep counter. More information in datasheet '5.5 Motor Driver Registers'
  7787. - `mscuract` - Actual microstep current for motor. More information in datasheet '5.5 Motor Driver Registers'
  7788. - `wave` - Microstep linearity compensation curve
  7789. - `!` - Set register
  7790. - Subcommands for set register
  7791. - `mres` - Micro step resolution
  7792. - `step` - Step
  7793. - `wave` - Microstep linearity compensation curve
  7794. - Values for set register
  7795. - `0, 180 --> 250` - Off
  7796. - `0.9 --> 1.25` - Valid values (recommended is 1.1)
  7797. - `@` - Home calibrate axis
  7798. Examples:
  7799. D2130E?wave
  7800. Print extruder microstep linearity compensation curve
  7801. D2130E!wave0
  7802. Disable extruder linearity compensation curve, (sine curve is used)
  7803. D2130E!wave220
  7804. (sin(x))^1.1 extruder microstep compensation curve used
  7805. Notes:
  7806. For more information see https://www.trinamic.com/fileadmin/assets/Products/ICs_Documents/TMC2130_datasheet.pdf
  7807. *
  7808. */
  7809. case 2130:
  7810. dcode_2130(); break;
  7811. #endif //TMC2130
  7812. #if defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  7813. /*!
  7814. ### D9125 - PAT9125 filament sensor <a href="https://reprap.org/wiki/G-code#D9:_Read.2FWrite_ADC">D9125: PAT9125 filament sensor</a>
  7815. #### Usage
  7816. D9125 [ ? | ! | R | X | Y | L ]
  7817. #### Parameters
  7818. - `?` - Print values
  7819. - `!` - Print values
  7820. - `R` - Resolution. Not active in code
  7821. - `X` - X values
  7822. - `Y` - Y values
  7823. - `L` - Activate filament sensor log
  7824. */
  7825. case 9125:
  7826. dcode_9125(); break;
  7827. #endif //defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  7828. #endif //DEBUG_DCODES
  7829. default:
  7830. printf_P(MSG_UNKNOWN_CODE, 'D', cmdbuffer + bufindr + CMDHDRSIZE);
  7831. }
  7832. }
  7833. else
  7834. {
  7835. SERIAL_ECHO_START;
  7836. SERIAL_ECHORPGM(MSG_UNKNOWN_COMMAND);
  7837. SERIAL_ECHO(CMDBUFFER_CURRENT_STRING);
  7838. SERIAL_ECHOLNPGM("\"(2)");
  7839. }
  7840. KEEPALIVE_STATE(NOT_BUSY);
  7841. ClearToSend();
  7842. }
  7843. /*!
  7844. #### End of D-Codes
  7845. */
  7846. /** @defgroup GCodes G-Code List
  7847. */
  7848. // ---------------------------------------------------
  7849. void FlushSerialRequestResend()
  7850. {
  7851. //char cmdbuffer[bufindr][100]="Resend:";
  7852. MYSERIAL.flush();
  7853. printf_P(_N("%S: %ld\n%S\n"), _n("Resend"), gcode_LastN + 1, MSG_OK);
  7854. }
  7855. // Confirm the execution of a command, if sent from a serial line.
  7856. // Execution of a command from a SD card will not be confirmed.
  7857. void ClearToSend()
  7858. {
  7859. previous_millis_cmd.start();
  7860. if (buflen && ((CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB) || (CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR)))
  7861. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  7862. }
  7863. #if MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  7864. void update_currents() {
  7865. float current_high[3] = DEFAULT_PWM_MOTOR_CURRENT_LOUD;
  7866. float current_low[3] = DEFAULT_PWM_MOTOR_CURRENT;
  7867. float tmp_motor[3];
  7868. //SERIAL_ECHOLNPGM("Currents updated: ");
  7869. if (destination[Z_AXIS] < Z_SILENT) {
  7870. //SERIAL_ECHOLNPGM("LOW");
  7871. for (uint8_t i = 0; i < 3; i++) {
  7872. st_current_set(i, current_low[i]);
  7873. /*MYSERIAL.print(int(i));
  7874. SERIAL_ECHOPGM(": ");
  7875. MYSERIAL.println(current_low[i]);*/
  7876. }
  7877. }
  7878. else if (destination[Z_AXIS] > Z_HIGH_POWER) {
  7879. //SERIAL_ECHOLNPGM("HIGH");
  7880. for (uint8_t i = 0; i < 3; i++) {
  7881. st_current_set(i, current_high[i]);
  7882. /*MYSERIAL.print(int(i));
  7883. SERIAL_ECHOPGM(": ");
  7884. MYSERIAL.println(current_high[i]);*/
  7885. }
  7886. }
  7887. else {
  7888. for (uint8_t i = 0; i < 3; i++) {
  7889. float q = current_low[i] - Z_SILENT*((current_high[i] - current_low[i]) / (Z_HIGH_POWER - Z_SILENT));
  7890. tmp_motor[i] = ((current_high[i] - current_low[i]) / (Z_HIGH_POWER - Z_SILENT))*destination[Z_AXIS] + q;
  7891. st_current_set(i, tmp_motor[i]);
  7892. /*MYSERIAL.print(int(i));
  7893. SERIAL_ECHOPGM(": ");
  7894. MYSERIAL.println(tmp_motor[i]);*/
  7895. }
  7896. }
  7897. }
  7898. #endif //MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  7899. void get_coordinates() {
  7900. bool seen[4]={false,false,false,false};
  7901. for(int8_t i=0; i < NUM_AXIS; i++) {
  7902. if(code_seen(axis_codes[i]))
  7903. {
  7904. bool relative = axis_relative_modes & (1 << i);
  7905. destination[i] = code_value();
  7906. if (i == E_AXIS) {
  7907. float emult = extruder_multiplier[active_extruder];
  7908. if (emult != 1.) {
  7909. if (! relative) {
  7910. destination[i] -= current_position[i];
  7911. relative = true;
  7912. }
  7913. destination[i] *= emult;
  7914. }
  7915. }
  7916. if (relative)
  7917. destination[i] += current_position[i];
  7918. seen[i]=true;
  7919. #if MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  7920. if (i == Z_AXIS && SilentModeMenu == SILENT_MODE_AUTO) update_currents();
  7921. #endif //MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  7922. }
  7923. else destination[i] = current_position[i]; //Are these else lines really needed?
  7924. }
  7925. if(code_seen('F')) {
  7926. next_feedrate = code_value();
  7927. if(next_feedrate > 0.0) feedrate = next_feedrate;
  7928. if (!seen[0] && !seen[1] && !seen[2] && seen[3])
  7929. {
  7930. // float e_max_speed =
  7931. // printf_P(PSTR("E MOVE speed %7.3f\n"), feedrate / 60)
  7932. }
  7933. }
  7934. }
  7935. void clamp_to_software_endstops(float target[3])
  7936. {
  7937. #ifdef DEBUG_DISABLE_SWLIMITS
  7938. return;
  7939. #endif //DEBUG_DISABLE_SWLIMITS
  7940. world2machine_clamp(target[0], target[1]);
  7941. // Clamp the Z coordinate.
  7942. if (min_software_endstops) {
  7943. float negative_z_offset = 0;
  7944. #ifdef ENABLE_AUTO_BED_LEVELING
  7945. if (Z_PROBE_OFFSET_FROM_EXTRUDER < 0) negative_z_offset = negative_z_offset + Z_PROBE_OFFSET_FROM_EXTRUDER;
  7946. if (cs.add_homing[Z_AXIS] < 0) negative_z_offset = negative_z_offset + cs.add_homing[Z_AXIS];
  7947. #endif
  7948. if (target[Z_AXIS] < min_pos[Z_AXIS]+negative_z_offset) target[Z_AXIS] = min_pos[Z_AXIS]+negative_z_offset;
  7949. }
  7950. if (max_software_endstops) {
  7951. if (target[Z_AXIS] > max_pos[Z_AXIS]) target[Z_AXIS] = max_pos[Z_AXIS];
  7952. }
  7953. }
  7954. uint16_t restore_interrupted_gcode() {
  7955. // When recovering from a previous print move, restore the originally
  7956. // calculated start position on the first USB/SD command. This accounts
  7957. // properly for relative moves
  7958. if (
  7959. (saved_start_position[0] != SAVED_START_POSITION_UNSET) && (
  7960. (CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_SDCARD) ||
  7961. (CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR)
  7962. )
  7963. ) {
  7964. memcpy(current_position, saved_start_position, sizeof(current_position));
  7965. saved_start_position[0] = SAVED_START_POSITION_UNSET;
  7966. return saved_segment_idx;
  7967. }
  7968. else
  7969. return 1; //begin with the first segment
  7970. }
  7971. #ifdef MESH_BED_LEVELING
  7972. 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) {
  7973. float dx = x - current_position[X_AXIS];
  7974. float dy = y - current_position[Y_AXIS];
  7975. uint16_t n_segments = 0;
  7976. if (mbl.active) {
  7977. float len = fabs(dx) + fabs(dy);
  7978. if (len > 0)
  7979. // Split to 3cm segments or shorter.
  7980. n_segments = uint16_t(ceil(len / 30.f));
  7981. }
  7982. if (n_segments > 1 && start_segment_idx) {
  7983. float dz = z - current_position[Z_AXIS];
  7984. float de = e - current_position[E_AXIS];
  7985. for (uint16_t i = start_segment_idx; i < n_segments; ++ i) {
  7986. float t = float(i) / float(n_segments);
  7987. plan_buffer_line(current_position[X_AXIS] + t * dx,
  7988. current_position[Y_AXIS] + t * dy,
  7989. current_position[Z_AXIS] + t * dz,
  7990. current_position[E_AXIS] + t * de,
  7991. feed_rate, extruder, current_position, i);
  7992. if (planner_aborted)
  7993. return;
  7994. }
  7995. }
  7996. // The rest of the path.
  7997. plan_buffer_line(x, y, z, e, feed_rate, extruder, current_position);
  7998. }
  7999. #endif // MESH_BED_LEVELING
  8000. void prepare_move(uint16_t start_segment_idx)
  8001. {
  8002. clamp_to_software_endstops(destination);
  8003. previous_millis_cmd.start();
  8004. // Do not use feedmultiply for E or Z only moves
  8005. if((current_position[X_AXIS] == destination[X_AXIS]) && (current_position[Y_AXIS] == destination[Y_AXIS])) {
  8006. plan_buffer_line_destinationXYZE(feedrate/60);
  8007. }
  8008. else {
  8009. #ifdef MESH_BED_LEVELING
  8010. 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);
  8011. #else
  8012. plan_buffer_line_destinationXYZE(feedrate*feedmultiply*(1./(60.f*100.f)));
  8013. #endif
  8014. }
  8015. set_current_to_destination();
  8016. }
  8017. void prepare_arc_move(bool isclockwise, uint16_t start_segment_idx) {
  8018. float r = hypot(offset[X_AXIS], offset[Y_AXIS]); // Compute arc radius for mc_arc
  8019. // Trace the arc
  8020. mc_arc(current_position, destination, offset, feedrate * feedmultiply / 60 / 100.0, r, isclockwise, active_extruder, start_segment_idx);
  8021. // As far as the parser is concerned, the position is now == target. In reality the
  8022. // motion control system might still be processing the action and the real tool position
  8023. // in any intermediate location.
  8024. set_current_to_destination();
  8025. previous_millis_cmd.start();
  8026. }
  8027. #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1
  8028. #if defined(FAN_PIN)
  8029. #if CONTROLLERFAN_PIN == FAN_PIN
  8030. #error "You cannot set CONTROLLERFAN_PIN equal to FAN_PIN"
  8031. #endif
  8032. #endif
  8033. unsigned long lastMotor = 0; //Save the time for when a motor was turned on last
  8034. unsigned long lastMotorCheck = 0;
  8035. void controllerFan()
  8036. {
  8037. if ((_millis() - lastMotorCheck) >= 2500) //Not a time critical function, so we only check every 2500ms
  8038. {
  8039. lastMotorCheck = _millis();
  8040. if(!READ(X_ENABLE_PIN) || !READ(Y_ENABLE_PIN) || !READ(Z_ENABLE_PIN) || (soft_pwm_bed > 0)
  8041. #if EXTRUDERS > 2
  8042. || !READ(E2_ENABLE_PIN)
  8043. #endif
  8044. #if EXTRUDER > 1
  8045. #if defined(X2_ENABLE_PIN) && X2_ENABLE_PIN > -1
  8046. || !READ(X2_ENABLE_PIN)
  8047. #endif
  8048. || !READ(E1_ENABLE_PIN)
  8049. #endif
  8050. || !READ(E0_ENABLE_PIN)) //If any of the drivers are enabled...
  8051. {
  8052. lastMotor = _millis(); //... set time to NOW so the fan will turn on
  8053. }
  8054. if ((_millis() - lastMotor) >= (CONTROLLERFAN_SECS*1000UL) || lastMotor == 0) //If the last time any driver was enabled, is longer since than CONTROLLERSEC...
  8055. {
  8056. digitalWrite(CONTROLLERFAN_PIN, 0);
  8057. analogWrite(CONTROLLERFAN_PIN, 0);
  8058. }
  8059. else
  8060. {
  8061. // allows digital or PWM fan output to be used (see M42 handling)
  8062. digitalWrite(CONTROLLERFAN_PIN, CONTROLLERFAN_SPEED);
  8063. analogWrite(CONTROLLERFAN_PIN, CONTROLLERFAN_SPEED);
  8064. }
  8065. }
  8066. }
  8067. #endif
  8068. #ifdef SAFETYTIMER
  8069. /**
  8070. * @brief Turn off heating after safetytimer_inactive_time milliseconds of inactivity
  8071. *
  8072. * Full screen blocking notification message is shown after heater turning off.
  8073. * Paused print is not considered inactivity, as nozzle is cooled anyway and bed cooling would
  8074. * damage print.
  8075. *
  8076. * If safetytimer_inactive_time is zero, feature is disabled (heating is never turned off because of inactivity)
  8077. */
  8078. static void handleSafetyTimer()
  8079. {
  8080. #if (EXTRUDERS > 1)
  8081. #error Implemented only for one extruder.
  8082. #endif //(EXTRUDERS > 1)
  8083. if (printer_active() || (!degTargetBed() && !degTargetHotend(0)) || (!safetytimer_inactive_time))
  8084. {
  8085. safetyTimer.stop();
  8086. }
  8087. else if ((degTargetBed() || degTargetHotend(0)) && (!safetyTimer.running()))
  8088. {
  8089. safetyTimer.start();
  8090. }
  8091. else if (safetyTimer.expired(farm_mode?FARM_DEFAULT_SAFETYTIMER_TIME_ms:safetytimer_inactive_time))
  8092. {
  8093. setTargetBed(0);
  8094. setAllTargetHotends(0);
  8095. lcd_show_fullscreen_message_and_wait_P(_i("Heating disabled by safety timer."));////MSG_BED_HEATING_SAFETY_DISABLED c=20 r=4
  8096. }
  8097. }
  8098. #endif //SAFETYTIMER
  8099. void manage_inactivity(bool ignore_stepper_queue/*=false*/) //default argument set in Marlin.h
  8100. {
  8101. #ifdef FILAMENT_SENSOR
  8102. if (fsensor.update()) {
  8103. lcd_draw_update = 1; //cause lcd update so that fsensor event polling can be done from the lcd draw routine.
  8104. }
  8105. #endif
  8106. #ifdef SAFETYTIMER
  8107. handleSafetyTimer();
  8108. #endif //SAFETYTIMER
  8109. #if defined(KILL_PIN) && KILL_PIN > -1
  8110. static int killCount = 0; // make the inactivity button a bit less responsive
  8111. const int KILL_DELAY = 10000;
  8112. #endif
  8113. if(buflen < (BUFSIZE-1)){
  8114. get_command();
  8115. }
  8116. if(previous_millis_cmd.expired(max_inactive_time))
  8117. if(max_inactive_time)
  8118. kill(_n("Inactivity Shutdown"), 4);
  8119. if(stepper_inactive_time) {
  8120. if(previous_millis_cmd.expired(stepper_inactive_time))
  8121. {
  8122. if(blocks_queued() == false && ignore_stepper_queue == false) {
  8123. disable_x();
  8124. disable_y();
  8125. disable_z();
  8126. disable_e0();
  8127. disable_e1();
  8128. disable_e2();
  8129. }
  8130. }
  8131. }
  8132. #ifdef CHDK //Check if pin should be set to LOW after M240 set it to HIGH
  8133. if (chdkActive && (_millis() - chdkHigh > CHDK_DELAY))
  8134. {
  8135. chdkActive = false;
  8136. WRITE(CHDK, LOW);
  8137. }
  8138. #endif
  8139. #if defined(KILL_PIN) && KILL_PIN > -1
  8140. // Check if the kill button was pressed and wait just in case it was an accidental
  8141. // key kill key press
  8142. // -------------------------------------------------------------------------------
  8143. if( 0 == READ(KILL_PIN) )
  8144. {
  8145. killCount++;
  8146. }
  8147. else if (killCount > 0)
  8148. {
  8149. killCount--;
  8150. }
  8151. // Exceeded threshold and we can confirm that it was not accidental
  8152. // KILL the machine
  8153. // ----------------------------------------------------------------
  8154. if ( killCount >= KILL_DELAY)
  8155. {
  8156. kill(NULL, 5);
  8157. }
  8158. #endif
  8159. #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1
  8160. controllerFan(); //Check if fan should be turned on to cool stepper drivers down
  8161. #endif
  8162. #ifdef EXTRUDER_RUNOUT_PREVENT
  8163. if(previous_millis_cmd.expired(EXTRUDER_RUNOUT_SECONDS*1000))
  8164. if(degHotend(active_extruder)>EXTRUDER_RUNOUT_MINTEMP)
  8165. {
  8166. bool oldstatus=READ(E0_ENABLE_PIN);
  8167. enable_e0();
  8168. float oldepos=current_position[E_AXIS];
  8169. float oldedes=destination[E_AXIS];
  8170. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS],
  8171. destination[E_AXIS]+EXTRUDER_RUNOUT_EXTRUDE*EXTRUDER_RUNOUT_ESTEPS/cs.axis_steps_per_unit[E_AXIS],
  8172. EXTRUDER_RUNOUT_SPEED/60.*EXTRUDER_RUNOUT_ESTEPS/cs.axis_steps_per_unit[E_AXIS], active_extruder);
  8173. current_position[E_AXIS]=oldepos;
  8174. destination[E_AXIS]=oldedes;
  8175. plan_set_e_position(oldepos);
  8176. previous_millis_cmd.start();
  8177. st_synchronize();
  8178. WRITE(E0_ENABLE_PIN,oldstatus);
  8179. }
  8180. #endif
  8181. check_axes_activity();
  8182. MMU2::mmu2.mmu_loop();
  8183. // handle longpress
  8184. if(lcd_longpress_trigger)
  8185. {
  8186. // long press is not possible in modal mode, wait until ready
  8187. if (lcd_longpress_func && lcd_update_enabled)
  8188. {
  8189. lcd_longpress_func();
  8190. lcd_longpress_trigger = 0;
  8191. }
  8192. }
  8193. #if defined(AUTO_REPORT)
  8194. host_autoreport();
  8195. #endif //AUTO_REPORT
  8196. host_keepalive();
  8197. }
  8198. void kill(const char *full_screen_message, unsigned char id)
  8199. {
  8200. printf_P(_N("KILL: %d\n"), id);
  8201. //return;
  8202. cli(); // Stop interrupts
  8203. disable_heater();
  8204. disable_x();
  8205. // SERIAL_ECHOLNPGM("kill - disable Y");
  8206. disable_y();
  8207. poweroff_z();
  8208. disable_e0();
  8209. disable_e1();
  8210. disable_e2();
  8211. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  8212. pinMode(PS_ON_PIN,INPUT);
  8213. #endif
  8214. SERIAL_ERROR_START;
  8215. SERIAL_ERRORLNRPGM(_n("Printer halted. kill() called!"));////MSG_ERR_KILLED
  8216. if (full_screen_message != NULL) {
  8217. SERIAL_ERRORLNRPGM(full_screen_message);
  8218. lcd_display_message_fullscreen_P(full_screen_message);
  8219. } else {
  8220. LCD_ALERTMESSAGERPGM(_n("KILLED. "));////MSG_KILLED
  8221. }
  8222. // FMC small patch to update the LCD before ending
  8223. sei(); // enable interrupts
  8224. for ( int i=5; i--; lcd_update(0))
  8225. {
  8226. _delay(200);
  8227. }
  8228. cli(); // disable interrupts
  8229. suicide();
  8230. while(1)
  8231. {
  8232. #ifdef WATCHDOG
  8233. wdt_reset();
  8234. #endif //WATCHDOG
  8235. /* Intentionally left empty */
  8236. } // Wait for reset
  8237. }
  8238. void UnconditionalStop()
  8239. {
  8240. CRITICAL_SECTION_START;
  8241. // Disable all heaters and unroll the temperature wait loop stack
  8242. disable_heater();
  8243. cancel_heatup = true;
  8244. heating_status = HeatingStatus::NO_HEATING;
  8245. // Clear any saved printing state
  8246. cancel_saved_printing();
  8247. // Abort the planner
  8248. planner_abort_hard();
  8249. // Reset the queue
  8250. cmdqueue_reset();
  8251. cmdqueue_serial_disabled = false;
  8252. // Reset the sd status
  8253. card.sdprinting = false;
  8254. card.closefile();
  8255. st_reset_timer();
  8256. CRITICAL_SECTION_END;
  8257. }
  8258. // Emergency stop used by overtemp functions which allows recovery
  8259. // WARNING: This function is called *continuously* during a thermal failure.
  8260. //
  8261. // This either pauses (for thermal model errors) or stops *without recovery* depending on
  8262. // "allow_pause". If pause is allowed, this forces a printer-initiated instantanenous pause (just
  8263. // like an LCD pause) that bypasses the host pausing functionality. In this state the printer is
  8264. // kept in busy state and *must* be recovered from the LCD.
  8265. void ThermalStop(bool allow_pause)
  8266. {
  8267. if(Stopped == false) {
  8268. Stopped = true;
  8269. if(allow_pause && (IS_SD_PRINTING || usb_timer.running())) {
  8270. if (!isPrintPaused) {
  8271. lcd_setalertstatuspgm(_T(MSG_PAUSED_THERMAL_ERROR), LCD_STATUS_CRITICAL);
  8272. // we cannot make a distinction for the host here, the pause must be instantaneous
  8273. // so we call the lcd_pause_print to save the print state internally. Thermal errors
  8274. // disable heaters and save the original temperatures to saved_*, which will get
  8275. // overwritten by stop_and_save_print_to_ram. For this corner-case, re-instate the
  8276. // original values after the pause handler is called.
  8277. float bed_temp = saved_bed_temperature;
  8278. float ext_temp = saved_extruder_temperature;
  8279. int fan_speed = saved_fan_speed;
  8280. lcd_pause_print();
  8281. saved_bed_temperature = bed_temp;
  8282. saved_extruder_temperature = ext_temp;
  8283. saved_fan_speed = fan_speed;
  8284. }
  8285. } else {
  8286. // We got a hard thermal error and/or there is no print going on. Just stop.
  8287. lcd_print_stop();
  8288. // Also prevent further menu entry
  8289. menu_set_block(MENU_BLOCK_THERMAL_ERROR);
  8290. }
  8291. // Report the status on the serial, switch to a busy state
  8292. SERIAL_ERROR_START;
  8293. SERIAL_ERRORLNRPGM(MSG_ERR_STOPPED);
  8294. // Eventually report the stopped status on the lcd (though this is usually overridden by a
  8295. // higher-priority alert status message)
  8296. LCD_MESSAGERPGM(_T(MSG_STOPPED));
  8297. // Make a warning sound! We cannot use Sound_MakeCustom as this would stop further moves.
  8298. // Turn on the speaker here (if not already), and turn it off when back in the main loop.
  8299. WRITE(BEEPER, HIGH);
  8300. }
  8301. // Return to the status screen to stop any pending menu action which could have been
  8302. // started by the user while stuck in the Stopped state. This also ensures the NEW
  8303. // error is immediately shown.
  8304. if (menu_menu != lcd_status_screen)
  8305. lcd_return_to_status();
  8306. }
  8307. bool IsStopped() { return Stopped; };
  8308. void finishAndDisableSteppers()
  8309. {
  8310. st_synchronize();
  8311. disable_x();
  8312. disable_y();
  8313. disable_z();
  8314. disable_e0();
  8315. disable_e1();
  8316. disable_e2();
  8317. #ifndef LA_NOCOMPAT
  8318. // Steppers are disabled both when a print is stopped and also via M84 (which is additionally
  8319. // checked-for to indicate a complete file), so abuse this function to reset the LA detection
  8320. // state for the next print.
  8321. la10c_reset();
  8322. #endif
  8323. //in the end of print set estimated time to end of print and extruders used during print to default values for next print
  8324. print_time_remaining_init();
  8325. }
  8326. #ifdef FAST_PWM_FAN
  8327. void setPwmFrequency(uint8_t pin, int val)
  8328. {
  8329. val &= 0x07;
  8330. switch(digitalPinToTimer(pin))
  8331. {
  8332. #if defined(TCCR0A)
  8333. case TIMER0A:
  8334. case TIMER0B:
  8335. // TCCR0B &= ~(_BV(CS00) | _BV(CS01) | _BV(CS02));
  8336. // TCCR0B |= val;
  8337. break;
  8338. #endif
  8339. #if defined(TCCR1A)
  8340. case TIMER1A:
  8341. case TIMER1B:
  8342. // TCCR1B &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  8343. // TCCR1B |= val;
  8344. break;
  8345. #endif
  8346. #if defined(TCCR2)
  8347. case TIMER2:
  8348. case TIMER2:
  8349. TCCR2 &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  8350. TCCR2 |= val;
  8351. break;
  8352. #endif
  8353. #if defined(TCCR2A)
  8354. case TIMER2A:
  8355. case TIMER2B:
  8356. TCCR2B &= ~(_BV(CS20) | _BV(CS21) | _BV(CS22));
  8357. TCCR2B |= val;
  8358. break;
  8359. #endif
  8360. #if defined(TCCR3A)
  8361. case TIMER3A:
  8362. case TIMER3B:
  8363. case TIMER3C:
  8364. TCCR3B &= ~(_BV(CS30) | _BV(CS31) | _BV(CS32));
  8365. TCCR3B |= val;
  8366. break;
  8367. #endif
  8368. #if defined(TCCR4A)
  8369. case TIMER4A:
  8370. case TIMER4B:
  8371. case TIMER4C:
  8372. TCCR4B &= ~(_BV(CS40) | _BV(CS41) | _BV(CS42));
  8373. TCCR4B |= val;
  8374. break;
  8375. #endif
  8376. #if defined(TCCR5A)
  8377. case TIMER5A:
  8378. case TIMER5B:
  8379. case TIMER5C:
  8380. TCCR5B &= ~(_BV(CS50) | _BV(CS51) | _BV(CS52));
  8381. TCCR5B |= val;
  8382. break;
  8383. #endif
  8384. }
  8385. }
  8386. #endif //FAST_PWM_FAN
  8387. //! @brief Get and validate extruder number
  8388. //!
  8389. //! If it is not specified, active_extruder is returned in parameter extruder.
  8390. //! @param [in] code M code number
  8391. //! @param [out] extruder
  8392. //! @return error
  8393. //! @retval true Invalid extruder specified in T code
  8394. //! @retval false Valid extruder specified in T code, or not specifiead
  8395. bool setTargetedHotend(int code, uint8_t &extruder)
  8396. {
  8397. extruder = active_extruder;
  8398. if(code_seen('T')) {
  8399. extruder = code_value_uint8();
  8400. if(extruder >= EXTRUDERS) {
  8401. SERIAL_ECHO_START;
  8402. switch(code){
  8403. case 104:
  8404. SERIAL_ECHORPGM(_n("M104 Invalid extruder "));////MSG_M104_INVALID_EXTRUDER
  8405. break;
  8406. case 105:
  8407. SERIAL_ECHORPGM(_n("M105 Invalid extruder "));////MSG_M105_INVALID_EXTRUDER
  8408. break;
  8409. case 109:
  8410. SERIAL_ECHORPGM(_n("M109 Invalid extruder "));////MSG_M109_INVALID_EXTRUDER
  8411. break;
  8412. case 218:
  8413. SERIAL_ECHORPGM(_n("M218 Invalid extruder "));////MSG_M218_INVALID_EXTRUDER
  8414. break;
  8415. case 221:
  8416. SERIAL_ECHORPGM(_n("M221 Invalid extruder "));////MSG_M221_INVALID_EXTRUDER
  8417. break;
  8418. }
  8419. SERIAL_PROTOCOLLN((int)extruder);
  8420. return true;
  8421. }
  8422. }
  8423. return false;
  8424. }
  8425. void save_statistics(unsigned long _total_filament_used, unsigned long _total_print_time) //_total_filament_used unit: mm/100; print time in s
  8426. {
  8427. if (eeprom_read_byte((uint8_t *)EEPROM_TOTALTIME) == 255 && eeprom_read_byte((uint8_t *)EEPROM_TOTALTIME + 1) == 255 && eeprom_read_byte((uint8_t *)EEPROM_TOTALTIME + 2) == 255 && eeprom_read_byte((uint8_t *)EEPROM_TOTALTIME + 3) == 255)
  8428. {
  8429. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, 0);
  8430. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, 0);
  8431. }
  8432. unsigned long _previous_filament = eeprom_read_dword((uint32_t *)EEPROM_FILAMENTUSED); //_previous_filament unit: cm
  8433. unsigned long _previous_time = eeprom_read_dword((uint32_t *)EEPROM_TOTALTIME); //_previous_time unit: min
  8434. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, _previous_time + (_total_print_time/60)); //EEPROM_TOTALTIME unit: min
  8435. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, _previous_filament + (_total_filament_used / 1000));
  8436. total_filament_used = 0;
  8437. }
  8438. float calculate_extruder_multiplier(float diameter) {
  8439. float out = 1.f;
  8440. if (cs.volumetric_enabled && diameter > 0.f) {
  8441. float area = M_PI * diameter * diameter * 0.25;
  8442. out = 1.f / area;
  8443. }
  8444. if (extrudemultiply != 100)
  8445. out *= float(extrudemultiply) * 0.01f;
  8446. return out;
  8447. }
  8448. void calculate_extruder_multipliers() {
  8449. extruder_multiplier[0] = calculate_extruder_multiplier(cs.filament_size[0]);
  8450. #if EXTRUDERS > 1
  8451. extruder_multiplier[1] = calculate_extruder_multiplier(cs.filament_size[1]);
  8452. #if EXTRUDERS > 2
  8453. extruder_multiplier[2] = calculate_extruder_multiplier(cs.filament_size[2]);
  8454. #endif
  8455. #endif
  8456. }
  8457. void delay_keep_alive(unsigned int ms)
  8458. {
  8459. for (;;) {
  8460. manage_heater();
  8461. // Manage inactivity, but don't disable steppers on timeout.
  8462. manage_inactivity(true);
  8463. lcd_update(0);
  8464. if (ms == 0)
  8465. break;
  8466. else if (ms >= 50) {
  8467. _delay(50);
  8468. ms -= 50;
  8469. } else {
  8470. _delay(ms);
  8471. ms = 0;
  8472. }
  8473. }
  8474. }
  8475. static void wait_for_heater(long codenum, uint8_t extruder) {
  8476. if (!degTargetHotend(extruder))
  8477. return;
  8478. #ifdef TEMP_RESIDENCY_TIME
  8479. long residencyStart;
  8480. residencyStart = -1;
  8481. /* continue to loop until we have reached the target temp
  8482. _and_ until TEMP_RESIDENCY_TIME hasn't passed since we reached it */
  8483. cancel_heatup = false;
  8484. while ((!cancel_heatup) && ((residencyStart == -1) ||
  8485. (residencyStart >= 0 && (((unsigned int)(_millis() - residencyStart)) < (TEMP_RESIDENCY_TIME * 1000UL))))) {
  8486. #else
  8487. while (target_direction ? (isHeatingHotend(tmp_extruder)) : (isCoolingHotend(tmp_extruder) && (CooldownNoWait == false))) {
  8488. #endif //TEMP_RESIDENCY_TIME
  8489. if ((_millis() - codenum) > 1000UL)
  8490. { //Print Temp Reading and remaining time every 1 second while heating up/cooling down
  8491. if (!farm_mode) {
  8492. SERIAL_PROTOCOLPGM("T:");
  8493. SERIAL_PROTOCOL_F(degHotend(extruder), 1);
  8494. SERIAL_PROTOCOLPGM(" E:");
  8495. SERIAL_PROTOCOL((int)extruder);
  8496. #ifdef TEMP_RESIDENCY_TIME
  8497. SERIAL_PROTOCOLPGM(" W:");
  8498. if (residencyStart > -1)
  8499. {
  8500. codenum = ((TEMP_RESIDENCY_TIME * 1000UL) - (_millis() - residencyStart)) / 1000UL;
  8501. SERIAL_PROTOCOLLN(codenum);
  8502. }
  8503. else
  8504. {
  8505. SERIAL_PROTOCOLLN('?');
  8506. }
  8507. }
  8508. #else
  8509. SERIAL_PROTOCOLLN();
  8510. #endif
  8511. codenum = _millis();
  8512. }
  8513. manage_heater();
  8514. manage_inactivity(true); //do not disable steppers
  8515. lcd_update(0);
  8516. #ifdef TEMP_RESIDENCY_TIME
  8517. /* start/restart the TEMP_RESIDENCY_TIME timer whenever we reach target temp for the first time
  8518. or when current temp falls outside the hysteresis after target temp was reached */
  8519. if ((residencyStart == -1 && target_direction && (degHotend(extruder) >= (degTargetHotend(extruder) - TEMP_WINDOW))) ||
  8520. (residencyStart == -1 && !target_direction && (degHotend(extruder) <= (degTargetHotend(extruder) + TEMP_WINDOW))) ||
  8521. (residencyStart > -1 && labs(degHotend(extruder) - degTargetHotend(extruder)) > TEMP_HYSTERESIS))
  8522. {
  8523. residencyStart = _millis();
  8524. }
  8525. #endif //TEMP_RESIDENCY_TIME
  8526. }
  8527. }
  8528. void check_babystep()
  8529. {
  8530. int babystep_z = eeprom_read_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->
  8531. s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)));
  8532. if ((babystep_z < Z_BABYSTEP_MIN) || (babystep_z > Z_BABYSTEP_MAX)) {
  8533. babystep_z = 0; //if babystep value is out of min max range, set it to 0
  8534. SERIAL_ECHOLNPGM("Z live adjust out of range. Setting to 0");
  8535. eeprom_write_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->
  8536. s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),
  8537. babystep_z);
  8538. lcd_show_fullscreen_message_and_wait_P(PSTR("Z live adjust out of range. Setting to 0. Click to continue."));
  8539. lcd_update_enable(true);
  8540. }
  8541. }
  8542. #ifdef HEATBED_ANALYSIS
  8543. void d_setup()
  8544. {
  8545. pinMode(D_DATACLOCK, INPUT_PULLUP);
  8546. pinMode(D_DATA, INPUT_PULLUP);
  8547. pinMode(D_REQUIRE, OUTPUT);
  8548. digitalWrite(D_REQUIRE, HIGH);
  8549. }
  8550. float d_ReadData()
  8551. {
  8552. int digit[13];
  8553. String mergeOutput;
  8554. float output;
  8555. digitalWrite(D_REQUIRE, HIGH);
  8556. for (int i = 0; i<13; i++)
  8557. {
  8558. for (int j = 0; j < 4; j++)
  8559. {
  8560. while (digitalRead(D_DATACLOCK) == LOW) {}
  8561. while (digitalRead(D_DATACLOCK) == HIGH) {}
  8562. bitWrite(digit[i], j, digitalRead(D_DATA));
  8563. }
  8564. }
  8565. digitalWrite(D_REQUIRE, LOW);
  8566. mergeOutput = "";
  8567. output = 0;
  8568. for (int r = 5; r <= 10; r++) //Merge digits
  8569. {
  8570. mergeOutput += digit[r];
  8571. }
  8572. output = mergeOutput.toFloat();
  8573. if (digit[4] == 8) //Handle sign
  8574. {
  8575. output *= -1;
  8576. }
  8577. for (int i = digit[11]; i > 0; i--) //Handle floating point
  8578. {
  8579. output /= 10;
  8580. }
  8581. return output;
  8582. }
  8583. void bed_check(float x_dimension, float y_dimension, int x_points_num, int y_points_num, float shift_x, float shift_y) {
  8584. int t1 = 0;
  8585. int t_delay = 0;
  8586. int digit[13];
  8587. int m;
  8588. char str[3];
  8589. //String mergeOutput;
  8590. char mergeOutput[15];
  8591. float output;
  8592. int mesh_point = 0; //index number of calibration point
  8593. 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
  8594. float bed_zero_ref_y = (-0.6f + Y_PROBE_OFFSET_FROM_EXTRUDER);
  8595. float mesh_home_z_search = 4;
  8596. float measure_z_height = 0.2f;
  8597. float row[x_points_num];
  8598. int ix = 0;
  8599. int iy = 0;
  8600. const char* filename_wldsd = "mesh.txt";
  8601. char data_wldsd[x_points_num * 7 + 1]; //6 chars(" -A.BCD")for each measurement + null
  8602. char numb_wldsd[8]; // (" -A.BCD" + null)
  8603. #ifdef MICROMETER_LOGGING
  8604. d_setup();
  8605. #endif //MICROMETER_LOGGING
  8606. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  8607. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  8608. unsigned int custom_message_type_old = custom_message_type;
  8609. unsigned int custom_message_state_old = custom_message_state;
  8610. custom_message_type = CustomMsg::MeshBedLeveling;
  8611. custom_message_state = (x_points_num * y_points_num) + 10;
  8612. lcd_update(1);
  8613. //mbl.reset();
  8614. babystep_undo();
  8615. card.openFile(filename_wldsd, false);
  8616. /*destination[Z_AXIS] = mesh_home_z_search;
  8617. //plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  8618. plan_buffer_line_destinationXYZE(Z_LIFT_FEEDRATE);
  8619. for(int8_t i=0; i < NUM_AXIS; i++) {
  8620. current_position[i] = destination[i];
  8621. }
  8622. st_synchronize();
  8623. */
  8624. destination[Z_AXIS] = measure_z_height;
  8625. plan_buffer_line_destinationXYZE(Z_LIFT_FEEDRATE);
  8626. for(int8_t i=0; i < NUM_AXIS; i++) {
  8627. current_position[i] = destination[i];
  8628. }
  8629. st_synchronize();
  8630. /*int l_feedmultiply = */setup_for_endstop_move(false);
  8631. SERIAL_PROTOCOLPGM("Num X,Y: ");
  8632. SERIAL_PROTOCOL(x_points_num);
  8633. SERIAL_PROTOCOLPGM(",");
  8634. SERIAL_PROTOCOL(y_points_num);
  8635. SERIAL_PROTOCOLPGM("\nZ search height: ");
  8636. SERIAL_PROTOCOL(mesh_home_z_search);
  8637. SERIAL_PROTOCOLPGM("\nDimension X,Y: ");
  8638. SERIAL_PROTOCOL(x_dimension);
  8639. SERIAL_PROTOCOLPGM(",");
  8640. SERIAL_PROTOCOL(y_dimension);
  8641. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  8642. while (mesh_point != x_points_num * y_points_num) {
  8643. ix = mesh_point % x_points_num; // from 0 to MESH_NUM_X_POINTS - 1
  8644. iy = mesh_point / x_points_num;
  8645. if (iy & 1) ix = (x_points_num - 1) - ix; // Zig zag
  8646. float z0 = 0.f;
  8647. /*destination[Z_AXIS] = mesh_home_z_search;
  8648. //plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  8649. plan_buffer_line_destinationXYZE(Z_LIFT_FEEDRATE);
  8650. for(int8_t i=0; i < NUM_AXIS; i++) {
  8651. current_position[i] = destination[i];
  8652. }
  8653. st_synchronize();*/
  8654. //current_position[X_AXIS] = 13.f + ix * (x_dimension / (x_points_num - 1)) - bed_zero_ref_x + shift_x;
  8655. //current_position[Y_AXIS] = 6.4f + iy * (y_dimension / (y_points_num - 1)) - bed_zero_ref_y + shift_y;
  8656. destination[X_AXIS] = ix * (x_dimension / (x_points_num - 1)) + shift_x;
  8657. destination[Y_AXIS] = iy * (y_dimension / (y_points_num - 1)) + shift_y;
  8658. mesh_plan_buffer_line_destinationXYZE(XY_AXIS_FEEDRATE/6);
  8659. set_current_to_destination();
  8660. st_synchronize();
  8661. // printf_P(PSTR("X = %f; Y= %f \n"), current_position[X_AXIS], current_position[Y_AXIS]);
  8662. delay_keep_alive(1000);
  8663. #ifdef MICROMETER_LOGGING
  8664. //memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8665. //dtostrf(d_ReadData(), 8, 5, numb_wldsd);
  8666. //strcat(data_wldsd, numb_wldsd);
  8667. //MYSERIAL.println(data_wldsd);
  8668. //delay(1000);
  8669. //delay(3000);
  8670. //t1 = millis();
  8671. //while (digitalRead(D_DATACLOCK) == LOW) {}
  8672. //while (digitalRead(D_DATACLOCK) == HIGH) {}
  8673. memset(digit, 0, sizeof(digit));
  8674. //cli();
  8675. digitalWrite(D_REQUIRE, LOW);
  8676. for (int i = 0; i<13; i++)
  8677. {
  8678. //t1 = millis();
  8679. for (int j = 0; j < 4; j++)
  8680. {
  8681. while (digitalRead(D_DATACLOCK) == LOW) {}
  8682. while (digitalRead(D_DATACLOCK) == HIGH) {}
  8683. //printf_P(PSTR("Done %d\n"), j);
  8684. bitWrite(digit[i], j, digitalRead(D_DATA));
  8685. }
  8686. //t_delay = (millis() - t1);
  8687. //SERIAL_PROTOCOLPGM(" ");
  8688. //SERIAL_PROTOCOL_F(t_delay, 5);
  8689. //SERIAL_PROTOCOLPGM(" ");
  8690. }
  8691. //sei();
  8692. digitalWrite(D_REQUIRE, HIGH);
  8693. mergeOutput[0] = '\0';
  8694. output = 0;
  8695. for (int r = 5; r <= 10; r++) //Merge digits
  8696. {
  8697. sprintf(str, "%d", digit[r]);
  8698. strcat(mergeOutput, str);
  8699. }
  8700. output = atof(mergeOutput);
  8701. if (digit[4] == 8) //Handle sign
  8702. {
  8703. output *= -1;
  8704. }
  8705. for (int i = digit[11]; i > 0; i--) //Handle floating point
  8706. {
  8707. output *= 0.1;
  8708. }
  8709. //output = d_ReadData();
  8710. //row[ix] = current_position[Z_AXIS];
  8711. //row[ix] = d_ReadData();
  8712. row[ix] = output;
  8713. if (iy % 2 == 1 ? ix == 0 : ix == x_points_num - 1) {
  8714. memset(data_wldsd, 0, sizeof(data_wldsd));
  8715. for (int i = 0; i < x_points_num; i++) {
  8716. SERIAL_PROTOCOLPGM(" ");
  8717. SERIAL_PROTOCOL_F(row[i], 5);
  8718. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8719. dtostrf(row[i], 7, 3, numb_wldsd);
  8720. strcat(data_wldsd, numb_wldsd);
  8721. }
  8722. card.write_command(data_wldsd);
  8723. SERIAL_PROTOCOLPGM("\n");
  8724. }
  8725. custom_message_state--;
  8726. mesh_point++;
  8727. lcd_update(1);
  8728. }
  8729. #endif //MICROMETER_LOGGING
  8730. card.closefile();
  8731. //clean_up_after_endstop_move(l_feedmultiply);
  8732. }
  8733. void bed_analysis(float x_dimension, float y_dimension, int x_points_num, int y_points_num, float shift_x, float shift_y) {
  8734. int t1 = 0;
  8735. int t_delay = 0;
  8736. int digit[13];
  8737. int m;
  8738. char str[3];
  8739. //String mergeOutput;
  8740. char mergeOutput[15];
  8741. float output;
  8742. int mesh_point = 0; //index number of calibration point
  8743. 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
  8744. float bed_zero_ref_y = (-0.6f + Y_PROBE_OFFSET_FROM_EXTRUDER);
  8745. float mesh_home_z_search = 4;
  8746. float row[x_points_num];
  8747. int ix = 0;
  8748. int iy = 0;
  8749. const char* filename_wldsd = "wldsd.txt";
  8750. char data_wldsd[70];
  8751. char numb_wldsd[10];
  8752. d_setup();
  8753. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  8754. // We don't know where we are! HOME!
  8755. // Push the commands to the front of the message queue in the reverse order!
  8756. // There shall be always enough space reserved for these commands.
  8757. repeatcommand_front(); // repeat G80 with all its parameters
  8758. enquecommand_front_P(G28W0);
  8759. enquecommand_front_P((PSTR("G1 Z5")));
  8760. return;
  8761. }
  8762. unsigned int custom_message_type_old = custom_message_type;
  8763. unsigned int custom_message_state_old = custom_message_state;
  8764. custom_message_type = CustomMsg::MeshBedLeveling;
  8765. custom_message_state = (x_points_num * y_points_num) + 10;
  8766. lcd_update(1);
  8767. mbl.reset();
  8768. babystep_undo();
  8769. card.openFile(filename_wldsd, false);
  8770. current_position[Z_AXIS] = mesh_home_z_search;
  8771. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 60, active_extruder);
  8772. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  8773. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  8774. int l_feedmultiply = setup_for_endstop_move(false);
  8775. SERIAL_PROTOCOLPGM("Num X,Y: ");
  8776. SERIAL_PROTOCOL(x_points_num);
  8777. SERIAL_PROTOCOLPGM(",");
  8778. SERIAL_PROTOCOL(y_points_num);
  8779. SERIAL_PROTOCOLPGM("\nZ search height: ");
  8780. SERIAL_PROTOCOL(mesh_home_z_search);
  8781. SERIAL_PROTOCOLPGM("\nDimension X,Y: ");
  8782. SERIAL_PROTOCOL(x_dimension);
  8783. SERIAL_PROTOCOLPGM(",");
  8784. SERIAL_PROTOCOL(y_dimension);
  8785. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  8786. while (mesh_point != x_points_num * y_points_num) {
  8787. ix = mesh_point % x_points_num; // from 0 to MESH_NUM_X_POINTS - 1
  8788. iy = mesh_point / x_points_num;
  8789. if (iy & 1) ix = (x_points_num - 1) - ix; // Zig zag
  8790. float z0 = 0.f;
  8791. current_position[Z_AXIS] = mesh_home_z_search;
  8792. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE, active_extruder);
  8793. st_synchronize();
  8794. current_position[X_AXIS] = 13.f + ix * (x_dimension / (x_points_num - 1)) - bed_zero_ref_x + shift_x;
  8795. current_position[Y_AXIS] = 6.4f + iy * (y_dimension / (y_points_num - 1)) - bed_zero_ref_y + shift_y;
  8796. plan_buffer_line_curposXYZE(XY_AXIS_FEEDRATE, active_extruder);
  8797. st_synchronize();
  8798. 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
  8799. break;
  8800. card.closefile();
  8801. }
  8802. //memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8803. //dtostrf(d_ReadData(), 8, 5, numb_wldsd);
  8804. //strcat(data_wldsd, numb_wldsd);
  8805. //MYSERIAL.println(data_wldsd);
  8806. //_delay(1000);
  8807. //_delay(3000);
  8808. //t1 = _millis();
  8809. //while (digitalRead(D_DATACLOCK) == LOW) {}
  8810. //while (digitalRead(D_DATACLOCK) == HIGH) {}
  8811. memset(digit, 0, sizeof(digit));
  8812. //cli();
  8813. digitalWrite(D_REQUIRE, LOW);
  8814. for (int i = 0; i<13; i++)
  8815. {
  8816. //t1 = _millis();
  8817. for (int j = 0; j < 4; j++)
  8818. {
  8819. while (digitalRead(D_DATACLOCK) == LOW) {}
  8820. while (digitalRead(D_DATACLOCK) == HIGH) {}
  8821. bitWrite(digit[i], j, digitalRead(D_DATA));
  8822. }
  8823. //t_delay = (_millis() - t1);
  8824. //SERIAL_PROTOCOLPGM(" ");
  8825. //SERIAL_PROTOCOL_F(t_delay, 5);
  8826. //SERIAL_PROTOCOLPGM(" ");
  8827. }
  8828. //sei();
  8829. digitalWrite(D_REQUIRE, HIGH);
  8830. mergeOutput[0] = '\0';
  8831. output = 0;
  8832. for (int r = 5; r <= 10; r++) //Merge digits
  8833. {
  8834. sprintf(str, "%d", digit[r]);
  8835. strcat(mergeOutput, str);
  8836. }
  8837. output = atof(mergeOutput);
  8838. if (digit[4] == 8) //Handle sign
  8839. {
  8840. output *= -1;
  8841. }
  8842. for (int i = digit[11]; i > 0; i--) //Handle floating point
  8843. {
  8844. output *= 0.1;
  8845. }
  8846. //output = d_ReadData();
  8847. //row[ix] = current_position[Z_AXIS];
  8848. memset(data_wldsd, 0, sizeof(data_wldsd));
  8849. for (int i = 0; i <3; i++) {
  8850. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8851. dtostrf(current_position[i], 8, 5, numb_wldsd);
  8852. strcat(data_wldsd, numb_wldsd);
  8853. strcat(data_wldsd, ";");
  8854. }
  8855. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8856. dtostrf(output, 8, 5, numb_wldsd);
  8857. strcat(data_wldsd, numb_wldsd);
  8858. //strcat(data_wldsd, ";");
  8859. card.write_command(data_wldsd);
  8860. //row[ix] = d_ReadData();
  8861. row[ix] = output; // current_position[Z_AXIS];
  8862. if (iy % 2 == 1 ? ix == 0 : ix == x_points_num - 1) {
  8863. for (int i = 0; i < x_points_num; i++) {
  8864. SERIAL_PROTOCOLPGM(" ");
  8865. SERIAL_PROTOCOL_F(row[i], 5);
  8866. }
  8867. SERIAL_PROTOCOLPGM("\n");
  8868. }
  8869. custom_message_state--;
  8870. mesh_point++;
  8871. lcd_update(1);
  8872. }
  8873. card.closefile();
  8874. clean_up_after_endstop_move(l_feedmultiply);
  8875. }
  8876. #endif //HEATBED_ANALYSIS
  8877. #ifndef PINDA_THERMISTOR
  8878. static void temp_compensation_start() {
  8879. custom_message_type = CustomMsg::TempCompPreheat;
  8880. custom_message_state = PINDA_HEAT_T + 1;
  8881. lcd_update(2);
  8882. if ((int)degHotend(active_extruder) > extrude_min_temp) {
  8883. current_position[E_AXIS] -= default_retraction;
  8884. }
  8885. plan_buffer_line_curposXYZE(400, active_extruder);
  8886. current_position[X_AXIS] = PINDA_PREHEAT_X;
  8887. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  8888. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  8889. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  8890. st_synchronize();
  8891. while (fabs(degBed() - target_temperature_bed) > 1) delay_keep_alive(1000);
  8892. for (int i = 0; i < PINDA_HEAT_T; i++) {
  8893. delay_keep_alive(1000);
  8894. custom_message_state = PINDA_HEAT_T - i;
  8895. if (custom_message_state == 99 || custom_message_state == 9) lcd_update(2); //force whole display redraw if number of digits changed
  8896. else lcd_update(1);
  8897. }
  8898. custom_message_type = CustomMsg::Status;
  8899. custom_message_state = 0;
  8900. }
  8901. static void temp_compensation_apply() {
  8902. int i_add;
  8903. int z_shift = 0;
  8904. float z_shift_mm;
  8905. if (calibration_status() == CALIBRATION_STATUS_CALIBRATED) {
  8906. if (target_temperature_bed % 10 == 0 && target_temperature_bed >= 60 && target_temperature_bed <= 100) {
  8907. i_add = (target_temperature_bed - 60) / 10;
  8908. z_shift = eeprom_read_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i_add);
  8909. z_shift_mm = z_shift / cs.axis_steps_per_unit[Z_AXIS];
  8910. }else {
  8911. //interpolation
  8912. z_shift_mm = temp_comp_interpolation(target_temperature_bed) / cs.axis_steps_per_unit[Z_AXIS];
  8913. }
  8914. printf_P(_N("\nZ shift applied:%.3f\n"), z_shift_mm);
  8915. 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);
  8916. st_synchronize();
  8917. plan_set_z_position(current_position[Z_AXIS]);
  8918. }
  8919. else {
  8920. //we have no temp compensation data
  8921. }
  8922. }
  8923. #endif //ndef PINDA_THERMISTOR
  8924. float temp_comp_interpolation(float inp_temperature) {
  8925. //cubic spline interpolation
  8926. int n, i, j;
  8927. float h[10], a, b, c, d, sum, s[10] = { 0 }, x[10], F[10], f[10], m[10][10] = { 0 }, temp;
  8928. int shift[10];
  8929. int temp_C[10];
  8930. n = 6; //number of measured points
  8931. shift[0] = 0;
  8932. for (i = 0; i < n; i++) {
  8933. if (i > 0) {
  8934. //read shift in steps from EEPROM
  8935. shift[i] = eeprom_read_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + (i - 1));
  8936. }
  8937. temp_C[i] = 50 + i * 10; //temperature in C
  8938. #ifdef PINDA_THERMISTOR
  8939. constexpr int start_compensating_temp = 35;
  8940. temp_C[i] = start_compensating_temp + i * 5; //temperature in degrees C
  8941. #ifdef SUPERPINDA_SUPPORT
  8942. static_assert(start_compensating_temp >= PINDA_MINTEMP, "Temperature compensation start point is lower than PINDA_MINTEMP.");
  8943. #endif //SUPERPINDA_SUPPORT
  8944. #else
  8945. temp_C[i] = 50 + i * 10; //temperature in C
  8946. #endif
  8947. x[i] = (float)temp_C[i];
  8948. f[i] = (float)shift[i];
  8949. }
  8950. if (inp_temperature < x[0]) return 0;
  8951. for (i = n - 1; i>0; i--) {
  8952. F[i] = (f[i] - f[i - 1]) / (x[i] - x[i - 1]);
  8953. h[i - 1] = x[i] - x[i - 1];
  8954. }
  8955. //*********** formation of h, s , f matrix **************
  8956. for (i = 1; i<n - 1; i++) {
  8957. m[i][i] = 2 * (h[i - 1] + h[i]);
  8958. if (i != 1) {
  8959. m[i][i - 1] = h[i - 1];
  8960. m[i - 1][i] = h[i - 1];
  8961. }
  8962. m[i][n - 1] = 6 * (F[i + 1] - F[i]);
  8963. }
  8964. //*********** forward elimination **************
  8965. for (i = 1; i<n - 2; i++) {
  8966. temp = (m[i + 1][i] / m[i][i]);
  8967. for (j = 1; j <= n - 1; j++)
  8968. m[i + 1][j] -= temp*m[i][j];
  8969. }
  8970. //*********** backward substitution *********
  8971. for (i = n - 2; i>0; i--) {
  8972. sum = 0;
  8973. for (j = i; j <= n - 2; j++)
  8974. sum += m[i][j] * s[j];
  8975. s[i] = (m[i][n - 1] - sum) / m[i][i];
  8976. }
  8977. for (i = 0; i<n - 1; i++)
  8978. if ((x[i] <= inp_temperature && inp_temperature <= x[i + 1]) || (i == n-2 && inp_temperature > x[i + 1])) {
  8979. a = (s[i + 1] - s[i]) / (6 * h[i]);
  8980. b = s[i] / 2;
  8981. c = (f[i + 1] - f[i]) / h[i] - (2 * h[i] * s[i] + s[i + 1] * h[i]) / 6;
  8982. d = f[i];
  8983. sum = a*pow((inp_temperature - x[i]), 3) + b*pow((inp_temperature - x[i]), 2) + c*(inp_temperature - x[i]) + d;
  8984. }
  8985. return sum;
  8986. }
  8987. #ifdef PINDA_THERMISTOR
  8988. float temp_compensation_pinda_thermistor_offset(float temperature_pinda)
  8989. {
  8990. if (!eeprom_read_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE)) return 0;
  8991. if (!calibration_status_pinda()) return 0;
  8992. return temp_comp_interpolation(temperature_pinda) / cs.axis_steps_per_unit[Z_AXIS];
  8993. }
  8994. #endif //PINDA_THERMISTOR
  8995. void long_pause() //long pause print
  8996. {
  8997. st_synchronize();
  8998. start_pause_print = _millis();
  8999. // Stop heaters
  9000. heating_status = HeatingStatus::NO_HEATING;
  9001. setAllTargetHotends(0);
  9002. // Lift z
  9003. raise_z_above(current_position[Z_AXIS] + Z_PAUSE_LIFT, true);
  9004. // Move XY to side
  9005. if (axis_known_position[X_AXIS] && axis_known_position[Y_AXIS]) {
  9006. current_position[X_AXIS] = X_PAUSE_POS;
  9007. current_position[Y_AXIS] = Y_PAUSE_POS;
  9008. plan_buffer_line_curposXYZE(50);
  9009. }
  9010. // did we come here from a thermal error?
  9011. if(get_temp_error()) {
  9012. // time to stop the error beep
  9013. WRITE(BEEPER, LOW);
  9014. } else {
  9015. // Turn off the print fan
  9016. fanSpeed = 0;
  9017. }
  9018. }
  9019. void serialecho_temperatures() {
  9020. float tt = degHotend(active_extruder);
  9021. SERIAL_PROTOCOLPGM("T:");
  9022. SERIAL_PROTOCOL(tt);
  9023. SERIAL_PROTOCOLPGM(" E:");
  9024. SERIAL_PROTOCOL((int)active_extruder);
  9025. SERIAL_PROTOCOLPGM(" B:");
  9026. SERIAL_PROTOCOL_F(degBed(), 1);
  9027. SERIAL_PROTOCOLLN();
  9028. }
  9029. #ifdef UVLO_SUPPORT
  9030. void uvlo_drain_reset()
  9031. {
  9032. // burn all that residual power
  9033. wdt_enable(WDTO_1S);
  9034. WRITE(BEEPER,HIGH);
  9035. lcd_clear();
  9036. lcd_puts_at_P(0, 1, MSG_POWERPANIC_DETECTED);
  9037. while(1);
  9038. }
  9039. void uvlo_()
  9040. {
  9041. unsigned long time_start = _millis();
  9042. bool sd_print = card.sdprinting;
  9043. // Conserve power as soon as possible.
  9044. #ifdef LCD_BL_PIN
  9045. backlightMode = BACKLIGHT_MODE_DIM;
  9046. backlightLevel_LOW = 0;
  9047. backlight_update();
  9048. #endif //LCD_BL_PIN
  9049. disable_x();
  9050. disable_y();
  9051. #ifdef TMC2130
  9052. tmc2130_set_current_h(Z_AXIS, 20);
  9053. tmc2130_set_current_r(Z_AXIS, 20);
  9054. tmc2130_set_current_h(E_AXIS, 20);
  9055. tmc2130_set_current_r(E_AXIS, 20);
  9056. #endif //TMC2130
  9057. // Stop all heaters
  9058. uint8_t saved_target_temperature_bed = target_temperature_bed;
  9059. uint16_t saved_target_temperature_ext = target_temperature[active_extruder];
  9060. setAllTargetHotends(0);
  9061. setTargetBed(0);
  9062. // Calculate the file position, from which to resume this print.
  9063. long sd_position = sdpos_atomic; //atomic sd position of last command added in queue
  9064. {
  9065. uint16_t sdlen_planner = planner_calc_sd_length(); //length of sd commands in planner
  9066. sd_position -= sdlen_planner;
  9067. uint16_t sdlen_cmdqueue = cmdqueue_calc_sd_length(); //length of sd commands in cmdqueue
  9068. sd_position -= sdlen_cmdqueue;
  9069. if (sd_position < 0) sd_position = 0;
  9070. }
  9071. // save the global state at planning time
  9072. bool pos_invalid = XY_NO_RESTORE_FLAG;
  9073. uint16_t feedrate_bckp;
  9074. if (current_block && !pos_invalid)
  9075. {
  9076. memcpy(saved_start_position, current_block->gcode_start_position, sizeof(saved_start_position));
  9077. feedrate_bckp = current_block->gcode_feedrate;
  9078. saved_segment_idx = current_block->segment_idx;
  9079. }
  9080. else
  9081. {
  9082. saved_start_position[0] = SAVED_START_POSITION_UNSET;
  9083. feedrate_bckp = feedrate;
  9084. saved_segment_idx = 0;
  9085. }
  9086. // From this point on and up to the print recovery, Z should not move during X/Y travels and
  9087. // should be controlled precisely. Reset the MBL status before planner_abort_hard in order to
  9088. // get the physical Z for further manipulation.
  9089. bool mbl_was_active = mbl.active;
  9090. mbl.active = false;
  9091. // After this call, the planner queue is emptied and the current_position is set to a current logical coordinate.
  9092. // The logical coordinate will likely differ from the machine coordinate if the skew calibration and mesh bed leveling
  9093. // are in action.
  9094. planner_abort_hard();
  9095. // Store the print logical Z position, which we need to recover (a slight error here would be
  9096. // recovered on the next Gcode instruction, while a physical location error would not)
  9097. float logical_z = current_position[Z_AXIS];
  9098. if(mbl_was_active) logical_z -= mbl.get_z(st_get_position_mm(X_AXIS), st_get_position_mm(Y_AXIS));
  9099. eeprom_update_float((float*)EEPROM_UVLO_CURRENT_POSITION_Z, logical_z);
  9100. // Store the print E position before we lose track
  9101. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION_E), current_position[E_AXIS]);
  9102. eeprom_update_byte((uint8_t*)EEPROM_UVLO_E_ABS, (axis_relative_modes & E_AXIS_MASK)?0:1);
  9103. // Clean the input command queue, inhibit serial processing using saved_printing
  9104. cmdqueue_reset();
  9105. card.sdprinting = false;
  9106. saved_printing = true;
  9107. // Enable stepper driver interrupt to move Z axis. This should be fine as the planner and
  9108. // command queues are empty, SD card printing is disabled, usb is inhibited.
  9109. planner_aborted = false;
  9110. sei();
  9111. // Retract
  9112. current_position[E_AXIS] -= default_retraction;
  9113. plan_buffer_line_curposXYZE(95);
  9114. st_synchronize();
  9115. disable_e0();
  9116. // Read out the current Z motor microstep counter to move the axis up towards
  9117. // a full step before powering off. NOTE: we need to ensure to schedule more
  9118. // than "dropsegments" steps in order to move (this is always the case here
  9119. // due to UVLO_Z_AXIS_SHIFT being used)
  9120. uint16_t z_res = tmc2130_get_res(Z_AXIS);
  9121. uint16_t z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9122. current_position[Z_AXIS] += float(1024 - z_microsteps)
  9123. / (z_res * cs.axis_steps_per_unit[Z_AXIS])
  9124. + UVLO_Z_AXIS_SHIFT;
  9125. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS]/60);
  9126. st_synchronize();
  9127. poweroff_z();
  9128. // Write the file position.
  9129. eeprom_update_dword((uint32_t*)(EEPROM_FILE_POSITION), sd_position);
  9130. // Store the mesh bed leveling offsets. This is 2*7*7=98 bytes, which takes 98*3.4us=333us in worst case.
  9131. for (uint8_t mesh_point = 0; mesh_point < MESH_NUM_X_POINTS * MESH_NUM_Y_POINTS; ++ mesh_point) {
  9132. uint8_t ix = mesh_point % MESH_NUM_X_POINTS; // from 0 to MESH_NUM_X_POINTS - 1
  9133. uint8_t iy = mesh_point / MESH_NUM_X_POINTS;
  9134. // Scale the z value to 1u resolution.
  9135. int16_t v = mbl_was_active ? int16_t(floor(mbl.z_values[iy][ix] * 1000.f + 0.5f)) : 0;
  9136. eeprom_update_word((uint16_t*)(EEPROM_UVLO_MESH_BED_LEVELING_FULL +2*mesh_point), *reinterpret_cast<uint16_t*>(&v));
  9137. }
  9138. // Write the _final_ Z position and motor microstep counter (unused).
  9139. eeprom_update_float((float*)EEPROM_UVLO_TINY_CURRENT_POSITION_Z, current_position[Z_AXIS]);
  9140. z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9141. eeprom_update_word((uint16_t*)(EEPROM_UVLO_Z_MICROSTEPS), z_microsteps);
  9142. // Store the current position.
  9143. if (pos_invalid)
  9144. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0), X_COORD_INVALID);
  9145. else
  9146. {
  9147. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0), current_position[X_AXIS]);
  9148. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 4), current_position[Y_AXIS]);
  9149. }
  9150. // Store the current feed rate, temperatures, fan speed and extruder multipliers (flow rates)
  9151. eeprom_update_word((uint16_t*)EEPROM_UVLO_FEEDRATE, feedrate_bckp);
  9152. eeprom_update_word((uint16_t*)EEPROM_UVLO_FEEDMULTIPLY, feedmultiply);
  9153. eeprom_update_word((uint16_t*)EEPROM_UVLO_TARGET_HOTEND, saved_target_temperature_ext);
  9154. eeprom_update_byte((uint8_t*)EEPROM_UVLO_TARGET_BED, saved_target_temperature_bed);
  9155. eeprom_update_byte((uint8_t*)EEPROM_UVLO_FAN_SPEED, fanSpeed);
  9156. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_0), extruder_multiplier[0]);
  9157. #if EXTRUDERS > 1
  9158. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_1), extruder_multiplier[1]);
  9159. #if EXTRUDERS > 2
  9160. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_2), extruder_multiplier[2]);
  9161. #endif
  9162. #endif
  9163. eeprom_update_word((uint16_t*)(EEPROM_EXTRUDEMULTIPLY), (uint16_t)extrudemultiply);
  9164. eeprom_update_float((float*)(EEPROM_UVLO_ACCELL), cs.acceleration);
  9165. eeprom_update_float((float*)(EEPROM_UVLO_RETRACT_ACCELL), cs.retract_acceleration);
  9166. eeprom_update_float((float*)(EEPROM_UVLO_TRAVEL_ACCELL), cs.travel_acceleration);
  9167. // Store the saved target
  9168. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+0*4), saved_start_position[X_AXIS]);
  9169. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+1*4), saved_start_position[Y_AXIS]);
  9170. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+2*4), saved_start_position[Z_AXIS]);
  9171. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+3*4), saved_start_position[E_AXIS]);
  9172. eeprom_update_word((uint16_t*)EEPROM_UVLO_SAVED_SEGMENT_IDX, saved_segment_idx);
  9173. #ifdef LIN_ADVANCE
  9174. eeprom_update_float((float*)(EEPROM_UVLO_LA_K), extruder_advance_K);
  9175. #endif
  9176. // Finaly store the "power outage" flag.
  9177. if(sd_print) eeprom_update_byte((uint8_t*)EEPROM_UVLO, 1);
  9178. // Increment power failure counter
  9179. eeprom_update_byte((uint8_t*)EEPROM_POWER_COUNT, eeprom_read_byte((uint8_t*)EEPROM_POWER_COUNT) + 1);
  9180. eeprom_update_word((uint16_t*)EEPROM_POWER_COUNT_TOT, eeprom_read_word((uint16_t*)EEPROM_POWER_COUNT_TOT) + 1);
  9181. printf_P(_N("UVLO - end %d\n"), _millis() - time_start);
  9182. WRITE(BEEPER,HIGH);
  9183. // All is set: with all the juice left, try to move extruder away to detach the nozzle completely from the print
  9184. poweron_z();
  9185. current_position[X_AXIS] = (current_position[X_AXIS] < 0.5f * (X_MIN_POS + X_MAX_POS)) ? X_MIN_POS : X_MAX_POS;
  9186. plan_buffer_line_curposXYZE(500);
  9187. st_synchronize();
  9188. wdt_enable(WDTO_1S);
  9189. while(1);
  9190. }
  9191. void uvlo_tiny()
  9192. {
  9193. unsigned long time_start = _millis();
  9194. // Conserve power as soon as possible.
  9195. disable_x();
  9196. disable_y();
  9197. disable_e0();
  9198. #ifdef TMC2130
  9199. tmc2130_set_current_h(Z_AXIS, 20);
  9200. tmc2130_set_current_r(Z_AXIS, 20);
  9201. #endif //TMC2130
  9202. // Stop all heaters
  9203. setAllTargetHotends(0);
  9204. setTargetBed(0);
  9205. // When power is interrupted on the _first_ recovery an attempt can be made to raise the
  9206. // extruder, causing the Z position to change. Similarly, when recovering, the Z position is
  9207. // lowered. In such cases we cannot just save Z, we need to re-align the steppers to a fullstep.
  9208. // Disable MBL (if not already) to work with physical coordinates.
  9209. mbl.active = false;
  9210. planner_abort_hard();
  9211. // Allow for small roundoffs to be ignored
  9212. 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])
  9213. {
  9214. // Clean the input command queue, inhibit serial processing using saved_printing
  9215. cmdqueue_reset();
  9216. card.sdprinting = false;
  9217. saved_printing = true;
  9218. // Enable stepper driver interrupt to move Z axis. This should be fine as the planner and
  9219. // command queues are empty, SD card printing is disabled, usb is inhibited.
  9220. planner_aborted = false;
  9221. sei();
  9222. // The axis was moved: adjust Z as done on a regular UVLO.
  9223. uint16_t z_res = tmc2130_get_res(Z_AXIS);
  9224. uint16_t z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9225. current_position[Z_AXIS] += float(1024 - z_microsteps)
  9226. / (z_res * cs.axis_steps_per_unit[Z_AXIS])
  9227. + UVLO_TINY_Z_AXIS_SHIFT;
  9228. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS]/60);
  9229. st_synchronize();
  9230. poweroff_z();
  9231. // Update Z position
  9232. eeprom_update_float((float*)(EEPROM_UVLO_TINY_CURRENT_POSITION_Z), current_position[Z_AXIS]);
  9233. // Update the _final_ Z motor microstep counter (unused).
  9234. z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9235. eeprom_update_word((uint16_t*)(EEPROM_UVLO_Z_MICROSTEPS), z_microsteps);
  9236. }
  9237. // Update the the "power outage" flag.
  9238. eeprom_update_byte((uint8_t*)EEPROM_UVLO,2);
  9239. // Increment power failure counter
  9240. eeprom_update_byte((uint8_t*)EEPROM_POWER_COUNT, eeprom_read_byte((uint8_t*)EEPROM_POWER_COUNT) + 1);
  9241. eeprom_update_word((uint16_t*)EEPROM_POWER_COUNT_TOT, eeprom_read_word((uint16_t*)EEPROM_POWER_COUNT_TOT) + 1);
  9242. printf_P(_N("UVLO_TINY - end %d\n"), _millis() - time_start);
  9243. uvlo_drain_reset();
  9244. }
  9245. #endif //UVLO_SUPPORT
  9246. #if (defined(FANCHECK) && defined(TACH_1) && (TACH_1 >-1))
  9247. void setup_fan_interrupt() {
  9248. //INT7
  9249. DDRE &= ~(1 << 7); //input pin
  9250. PORTE &= ~(1 << 7); //no internal pull-up
  9251. //start with sensing rising edge
  9252. EICRB &= ~(1 << 6);
  9253. EICRB |= (1 << 7);
  9254. //enable INT7 interrupt
  9255. EIMSK |= (1 << 7);
  9256. }
  9257. // The fan interrupt is triggered at maximum 325Hz (may be a bit more due to component tollerances),
  9258. // and it takes 4.24 us to process (the interrupt invocation overhead not taken into account).
  9259. ISR(INT7_vect) {
  9260. //measuring speed now works for fanSpeed > 18 (approximately), which is sufficient because MIN_PRINT_FAN_SPEED is higher
  9261. #ifdef FAN_SOFT_PWM
  9262. if (!fan_measuring || (fanSpeedSoftPwm < MIN_PRINT_FAN_SPEED)) return;
  9263. #else //FAN_SOFT_PWM
  9264. if (fanSpeed < MIN_PRINT_FAN_SPEED) return;
  9265. #endif //FAN_SOFT_PWM
  9266. if ((1 << 6) & EICRB) { //interrupt was triggered by rising edge
  9267. t_fan_rising_edge = millis_nc();
  9268. }
  9269. else { //interrupt was triggered by falling edge
  9270. if ((millis_nc() - t_fan_rising_edge) >= FAN_PULSE_WIDTH_LIMIT) {//this pulse was from sensor and not from pwm
  9271. fan_edge_counter[1] += 2; //we are currently counting all edges so lets count two edges for one pulse
  9272. }
  9273. }
  9274. EICRB ^= (1 << 6); //change edge
  9275. }
  9276. #endif
  9277. #ifdef UVLO_SUPPORT
  9278. void setup_uvlo_interrupt() {
  9279. DDRE &= ~(1 << 4); //input pin
  9280. PORTE &= ~(1 << 4); //no internal pull-up
  9281. // sensing falling edge
  9282. EICRB |= (1 << 0);
  9283. EICRB &= ~(1 << 1);
  9284. // enable INT4 interrupt
  9285. EIMSK |= (1 << 4);
  9286. // check if power was lost before we armed the interrupt
  9287. if(!(PINE & (1 << 4)) && eeprom_read_byte((uint8_t*)EEPROM_UVLO))
  9288. {
  9289. SERIAL_ECHOLNPGM("INT4");
  9290. uvlo_drain_reset();
  9291. }
  9292. }
  9293. ISR(INT4_vect) {
  9294. EIMSK &= ~(1 << 4); //disable INT4 interrupt to make sure that this code will be executed just once
  9295. SERIAL_ECHOLNPGM("INT4");
  9296. //fire normal uvlo only in case where EEPROM_UVLO is 0 or if IS_SD_PRINTING is 1.
  9297. if(printer_active() && (!(eeprom_read_byte((uint8_t*)EEPROM_UVLO)))) uvlo_();
  9298. if(eeprom_read_byte((uint8_t*)EEPROM_UVLO)) uvlo_tiny();
  9299. }
  9300. void recover_print(uint8_t automatic) {
  9301. char cmd[30];
  9302. lcd_update_enable(true);
  9303. lcd_update(2);
  9304. lcd_setstatuspgm(_i("Recovering print"));////MSG_RECOVERING_PRINT c=20
  9305. // Recover position, temperatures and extrude_multipliers
  9306. bool mbl_was_active = recover_machine_state_after_power_panic();
  9307. // Lift the print head 25mm, first to avoid collisions with oozed material with the print,
  9308. // and second also so one may remove the excess priming material.
  9309. if(eeprom_read_byte((uint8_t*)EEPROM_UVLO) == 1)
  9310. {
  9311. sprintf_P(cmd, PSTR("G1 Z%.3f F800"), current_position[Z_AXIS] + 25);
  9312. enquecommand(cmd);
  9313. }
  9314. // Home X and Y axes. Homing just X and Y shall not touch the babystep and the world2machine
  9315. // transformation status. G28 will not touch Z when MBL is off.
  9316. enquecommand_P(PSTR("G28 X Y"));
  9317. // Set the target bed and nozzle temperatures and wait.
  9318. sprintf_P(cmd, PSTR("M104 S%d"), target_temperature[active_extruder]);
  9319. enquecommand(cmd);
  9320. sprintf_P(cmd, PSTR("M140 S%d"), target_temperature_bed);
  9321. enquecommand(cmd);
  9322. sprintf_P(cmd, PSTR("M109 S%d"), target_temperature[active_extruder]);
  9323. enquecommand(cmd);
  9324. enquecommand_P(PSTR("M83")); //E axis relative mode
  9325. // If not automatically recoreverd (long power loss)
  9326. if(automatic == 0){
  9327. //Extrude some filament to stabilize the pressure
  9328. enquecommand_P(PSTR("G1 E5 F120"));
  9329. // Retract to be consistent with a short pause
  9330. sprintf_P(cmd, PSTR("G1 E%-0.3f F2700"), default_retraction);
  9331. enquecommand(cmd);
  9332. }
  9333. 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]);
  9334. // Restart the print.
  9335. restore_print_from_eeprom(mbl_was_active);
  9336. printf_P(_N("Current pos Z_AXIS:%.3f\nCurrent pos E_AXIS:%.3f\n"), current_position[Z_AXIS], current_position[E_AXIS]);
  9337. }
  9338. bool recover_machine_state_after_power_panic()
  9339. {
  9340. // 1) Preset some dummy values for the XY axes
  9341. current_position[X_AXIS] = 0;
  9342. current_position[Y_AXIS] = 0;
  9343. // 2) Restore the mesh bed leveling offsets, but not the MBL status.
  9344. // This is 2*7*7=98 bytes, which takes 98*3.4us=333us in worst case.
  9345. bool mbl_was_active = false;
  9346. for (int8_t mesh_point = 0; mesh_point < MESH_NUM_X_POINTS * MESH_NUM_Y_POINTS; ++ mesh_point) {
  9347. uint8_t ix = mesh_point % MESH_NUM_X_POINTS; // from 0 to MESH_NUM_X_POINTS - 1
  9348. uint8_t iy = mesh_point / MESH_NUM_X_POINTS;
  9349. // Scale the z value to 10u resolution.
  9350. int16_t v;
  9351. eeprom_read_block(&v, (void*)(EEPROM_UVLO_MESH_BED_LEVELING_FULL+2*mesh_point), 2);
  9352. if (v != 0)
  9353. mbl_was_active = true;
  9354. mbl.z_values[iy][ix] = float(v) * 0.001f;
  9355. }
  9356. // Recover the physical coordinate of the Z axis at the time of the power panic.
  9357. // The current position after power panic is moved to the next closest 0th full step.
  9358. current_position[Z_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_TINY_CURRENT_POSITION_Z));
  9359. // Recover last E axis position
  9360. current_position[E_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_E));
  9361. // 3) Initialize the logical to physical coordinate system transformation.
  9362. world2machine_initialize();
  9363. // SERIAL_ECHOPGM("recover_machine_state_after_power_panic, initial ");
  9364. // print_mesh_bed_leveling_table();
  9365. // 4) Load the baby stepping value, which is expected to be active at the time of power panic.
  9366. // The baby stepping value is used to reset the physical Z axis when rehoming the Z axis.
  9367. babystep_load();
  9368. // 5) Set the physical positions from the logical positions using the world2machine transformation
  9369. // This is only done to inizialize Z/E axes with physical locations, since X/Y are unknown.
  9370. clamp_to_software_endstops(current_position);
  9371. set_destination_to_current();
  9372. plan_set_position_curposXYZE();
  9373. SERIAL_ECHOPGM("recover_machine_state_after_power_panic, initial ");
  9374. print_world_coordinates();
  9375. // 6) Power up the Z motors, mark their positions as known.
  9376. axis_known_position[Z_AXIS] = true;
  9377. enable_z();
  9378. // 7) Recover the target temperatures.
  9379. target_temperature[active_extruder] = eeprom_read_word((uint16_t*)EEPROM_UVLO_TARGET_HOTEND);
  9380. target_temperature_bed = eeprom_read_byte((uint8_t*)EEPROM_UVLO_TARGET_BED);
  9381. // 8) Recover extruder multipilers
  9382. extruder_multiplier[0] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_0));
  9383. #if EXTRUDERS > 1
  9384. extruder_multiplier[1] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_1));
  9385. #if EXTRUDERS > 2
  9386. extruder_multiplier[2] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_2));
  9387. #endif
  9388. #endif
  9389. extrudemultiply = (int)eeprom_read_word((uint16_t*)(EEPROM_EXTRUDEMULTIPLY));
  9390. // 9) Recover the saved target
  9391. saved_start_position[X_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+0*4));
  9392. saved_start_position[Y_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+1*4));
  9393. saved_start_position[Z_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+2*4));
  9394. saved_start_position[E_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+3*4));
  9395. saved_segment_idx = eeprom_read_word((uint16_t*)EEPROM_UVLO_SAVED_SEGMENT_IDX);
  9396. #ifdef LIN_ADVANCE
  9397. extruder_advance_K = eeprom_read_float((float*)EEPROM_UVLO_LA_K);
  9398. #endif
  9399. return mbl_was_active;
  9400. }
  9401. void restore_print_from_eeprom(bool mbl_was_active) {
  9402. int feedrate_rec;
  9403. int feedmultiply_rec;
  9404. uint8_t fan_speed_rec;
  9405. char cmd[48];
  9406. char filename[FILENAME_LENGTH];
  9407. uint8_t depth = 0;
  9408. char dir_name[9];
  9409. fan_speed_rec = eeprom_read_byte((uint8_t*)EEPROM_UVLO_FAN_SPEED);
  9410. feedrate_rec = eeprom_read_word((uint16_t*)EEPROM_UVLO_FEEDRATE);
  9411. feedmultiply_rec = eeprom_read_word((uint16_t*)EEPROM_UVLO_FEEDMULTIPLY);
  9412. SERIAL_ECHOPGM("Feedrate:");
  9413. MYSERIAL.print(feedrate_rec);
  9414. SERIAL_ECHOPGM(", feedmultiply:");
  9415. MYSERIAL.println(feedmultiply_rec);
  9416. depth = eeprom_read_byte((uint8_t*)EEPROM_DIR_DEPTH);
  9417. MYSERIAL.println(int(depth));
  9418. for (uint8_t i = 0; i < depth; i++) {
  9419. for (uint8_t j = 0; j < 8; j++) {
  9420. dir_name[j] = eeprom_read_byte((uint8_t*)EEPROM_DIRS + j + 8 * i);
  9421. }
  9422. dir_name[8] = '\0';
  9423. MYSERIAL.println(dir_name);
  9424. // strcpy(card.dir_names[i], dir_name);
  9425. card.chdir(dir_name, false);
  9426. }
  9427. for (uint8_t i = 0; i < 8; i++) {
  9428. filename[i] = eeprom_read_byte((uint8_t*)EEPROM_FILENAME + i);
  9429. }
  9430. filename[8] = '\0';
  9431. MYSERIAL.print(filename);
  9432. strcat_P(filename, PSTR(".gco"));
  9433. sprintf_P(cmd, PSTR("M23 %s"), filename);
  9434. enquecommand(cmd);
  9435. uint32_t position = eeprom_read_dword((uint32_t*)(EEPROM_FILE_POSITION));
  9436. SERIAL_ECHOPGM("Position read from eeprom:");
  9437. MYSERIAL.println(position);
  9438. // Move to the XY print position in logical coordinates, where the print has been killed, but
  9439. // without shifting Z along the way. This requires performing the move without mbl.
  9440. float pos_x = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0));
  9441. float pos_y = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 4));
  9442. if (pos_x != X_COORD_INVALID)
  9443. {
  9444. sprintf_P(cmd, PSTR("G1 X%f Y%f F3000"), pos_x, pos_y);
  9445. enquecommand(cmd);
  9446. }
  9447. // Enable MBL and switch to logical positioning
  9448. if (mbl_was_active)
  9449. enquecommand_P(PSTR("PRUSA MBL V1"));
  9450. // Move the Z axis down to the print, in logical coordinates.
  9451. sprintf_P(cmd, PSTR("G1 Z%f"), eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_Z)));
  9452. enquecommand(cmd);
  9453. // Restore acceleration settings
  9454. float acceleration = eeprom_read_float((float*)(EEPROM_UVLO_ACCELL));
  9455. float retract_acceleration = eeprom_read_float((float*)(EEPROM_UVLO_RETRACT_ACCELL));
  9456. float travel_acceleration = eeprom_read_float((float*)(EEPROM_UVLO_TRAVEL_ACCELL));
  9457. sprintf_P(cmd, PSTR("M204 P%f R%f T%f"), acceleration, retract_acceleration, travel_acceleration);
  9458. enquecommand(cmd);
  9459. // Unretract.
  9460. sprintf_P(cmd, PSTR("G1 E%0.3f F2700"), default_retraction);
  9461. enquecommand(cmd);
  9462. // Recover final E axis position and mode
  9463. float pos_e = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_E));
  9464. sprintf_P(cmd, PSTR("G92 E%6.3f"), pos_e);
  9465. enquecommand(cmd);
  9466. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO_E_ABS))
  9467. enquecommand_P(PSTR("M82")); //E axis abslute mode
  9468. // Set the feedrates saved at the power panic.
  9469. sprintf_P(cmd, PSTR("G1 F%d"), feedrate_rec);
  9470. enquecommand(cmd);
  9471. sprintf_P(cmd, PSTR("M220 S%d"), feedmultiply_rec);
  9472. enquecommand(cmd);
  9473. // Set the fan speed saved at the power panic.
  9474. strcpy_P(cmd, PSTR("M106 S"));
  9475. strcat(cmd, itostr3(int(fan_speed_rec)));
  9476. enquecommand(cmd);
  9477. // Set a position in the file.
  9478. sprintf_P(cmd, PSTR("M26 S%lu"), position);
  9479. enquecommand(cmd);
  9480. enquecommand_P(PSTR("G4 S0"));
  9481. enquecommand_P(PSTR("PRUSA uvlo"));
  9482. }
  9483. #endif //UVLO_SUPPORT
  9484. //! @brief Immediately stop print moves
  9485. //!
  9486. //! Immediately stop print moves, save current extruder temperature and position to RAM.
  9487. //! If printing from sd card, position in file is saved.
  9488. //! If printing from USB, line number is saved.
  9489. //!
  9490. //! @param z_move
  9491. //! @param e_move
  9492. void stop_and_save_print_to_ram(float z_move, float e_move)
  9493. {
  9494. if (saved_printing) return;
  9495. #if 0
  9496. unsigned char nplanner_blocks;
  9497. #endif
  9498. unsigned char nlines;
  9499. uint16_t sdlen_planner;
  9500. uint16_t sdlen_cmdqueue;
  9501. cli();
  9502. if (card.sdprinting) {
  9503. #if 0
  9504. nplanner_blocks = number_of_blocks();
  9505. #endif
  9506. saved_sdpos = sdpos_atomic; //atomic sd position of last command added in queue
  9507. sdlen_planner = planner_calc_sd_length(); //length of sd commands in planner
  9508. saved_sdpos -= sdlen_planner;
  9509. sdlen_cmdqueue = cmdqueue_calc_sd_length(); //length of sd commands in cmdqueue
  9510. saved_sdpos -= sdlen_cmdqueue;
  9511. saved_printing_type = PRINTING_TYPE_SD;
  9512. }
  9513. else if (usb_timer.running()) { //reuse saved_sdpos for storing line number
  9514. saved_sdpos = gcode_LastN; //start with line number of command added recently to cmd queue
  9515. //reuse planner_calc_sd_length function for getting number of lines of commands in planner:
  9516. nlines = planner_calc_sd_length(); //number of lines of commands in planner
  9517. saved_sdpos -= nlines;
  9518. saved_sdpos -= buflen; //number of blocks in cmd buffer
  9519. saved_printing_type = PRINTING_TYPE_USB;
  9520. }
  9521. else {
  9522. saved_printing_type = PRINTING_TYPE_NONE;
  9523. //not sd printing nor usb printing
  9524. }
  9525. #if 0
  9526. SERIAL_ECHOPGM("SDPOS_ATOMIC="); MYSERIAL.println(sdpos_atomic, DEC);
  9527. SERIAL_ECHOPGM("SDPOS="); MYSERIAL.println(card.get_sdpos(), DEC);
  9528. SERIAL_ECHOPGM("SDLEN_PLAN="); MYSERIAL.println(sdlen_planner, DEC);
  9529. SERIAL_ECHOPGM("SDLEN_CMDQ="); MYSERIAL.println(sdlen_cmdqueue, DEC);
  9530. SERIAL_ECHOPGM("PLANNERBLOCKS="); MYSERIAL.println(int(nplanner_blocks), DEC);
  9531. SERIAL_ECHOPGM("SDSAVED="); MYSERIAL.println(saved_sdpos, DEC);
  9532. //SERIAL_ECHOPGM("SDFILELEN="); MYSERIAL.println(card.fileSize(), DEC);
  9533. {
  9534. card.setIndex(saved_sdpos);
  9535. SERIAL_ECHOLNPGM("Content of planner buffer: ");
  9536. for (unsigned int idx = 0; idx < sdlen_planner; ++ idx)
  9537. MYSERIAL.print(char(card.get()));
  9538. SERIAL_ECHOLNPGM("Content of command buffer: ");
  9539. for (unsigned int idx = 0; idx < sdlen_cmdqueue; ++ idx)
  9540. MYSERIAL.print(char(card.get()));
  9541. SERIAL_ECHOLNPGM("End of command buffer");
  9542. }
  9543. {
  9544. // Print the content of the planner buffer, line by line:
  9545. card.setIndex(saved_sdpos);
  9546. int8_t iline = 0;
  9547. for (unsigned char idx = block_buffer_tail; idx != block_buffer_head; idx = (idx + 1) & (BLOCK_BUFFER_SIZE - 1), ++ iline) {
  9548. SERIAL_ECHOPGM("Planner line (from file): ");
  9549. MYSERIAL.print(int(iline), DEC);
  9550. SERIAL_ECHOPGM(", length: ");
  9551. MYSERIAL.print(block_buffer[idx].sdlen, DEC);
  9552. SERIAL_ECHOPGM(", steps: (");
  9553. MYSERIAL.print(block_buffer[idx].steps_x, DEC);
  9554. SERIAL_ECHOPGM(",");
  9555. MYSERIAL.print(block_buffer[idx].steps_y, DEC);
  9556. SERIAL_ECHOPGM(",");
  9557. MYSERIAL.print(block_buffer[idx].steps_z, DEC);
  9558. SERIAL_ECHOPGM(",");
  9559. MYSERIAL.print(block_buffer[idx].steps_e, DEC);
  9560. SERIAL_ECHOPGM("), events: ");
  9561. MYSERIAL.println(block_buffer[idx].step_event_count, DEC);
  9562. for (int len = block_buffer[idx].sdlen; len > 0; -- len)
  9563. MYSERIAL.print(char(card.get()));
  9564. }
  9565. }
  9566. {
  9567. // Print the content of the command buffer, line by line:
  9568. int8_t iline = 0;
  9569. union {
  9570. struct {
  9571. char lo;
  9572. char hi;
  9573. } lohi;
  9574. uint16_t value;
  9575. } sdlen_single;
  9576. int _bufindr = bufindr;
  9577. for (int _buflen = buflen; _buflen > 0; ++ iline) {
  9578. if (cmdbuffer[_bufindr] == CMDBUFFER_CURRENT_TYPE_SDCARD) {
  9579. sdlen_single.lohi.lo = cmdbuffer[_bufindr + 1];
  9580. sdlen_single.lohi.hi = cmdbuffer[_bufindr + 2];
  9581. }
  9582. SERIAL_ECHOPGM("Buffer line (from buffer): ");
  9583. MYSERIAL.print(int(iline), DEC);
  9584. SERIAL_ECHOPGM(", type: ");
  9585. MYSERIAL.print(int(cmdbuffer[_bufindr]), DEC);
  9586. SERIAL_ECHOPGM(", len: ");
  9587. MYSERIAL.println(sdlen_single.value, DEC);
  9588. // Print the content of the buffer line.
  9589. MYSERIAL.println(cmdbuffer + _bufindr + CMDHDRSIZE);
  9590. SERIAL_ECHOPGM("Buffer line (from file): ");
  9591. MYSERIAL.println(int(iline), DEC);
  9592. for (; sdlen_single.value > 0; -- sdlen_single.value)
  9593. MYSERIAL.print(char(card.get()));
  9594. if (-- _buflen == 0)
  9595. break;
  9596. // First skip the current command ID and iterate up to the end of the string.
  9597. for (_bufindr += CMDHDRSIZE; cmdbuffer[_bufindr] != 0; ++ _bufindr) ;
  9598. // Second, skip the end of string null character and iterate until a nonzero command ID is found.
  9599. for (++ _bufindr; _bufindr < sizeof(cmdbuffer) && cmdbuffer[_bufindr] == 0; ++ _bufindr) ;
  9600. // If the end of the buffer was empty,
  9601. if (_bufindr == sizeof(cmdbuffer)) {
  9602. // skip to the start and find the nonzero command.
  9603. for (_bufindr = 0; cmdbuffer[_bufindr] == 0; ++ _bufindr) ;
  9604. }
  9605. }
  9606. }
  9607. #endif
  9608. // save the global state at planning time
  9609. bool pos_invalid = XY_NO_RESTORE_FLAG;
  9610. if (current_block && !pos_invalid)
  9611. {
  9612. memcpy(saved_start_position, current_block->gcode_start_position, sizeof(saved_start_position));
  9613. saved_feedrate2 = current_block->gcode_feedrate;
  9614. saved_segment_idx = current_block->segment_idx;
  9615. // 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);
  9616. }
  9617. else
  9618. {
  9619. saved_start_position[0] = SAVED_START_POSITION_UNSET;
  9620. saved_feedrate2 = feedrate;
  9621. saved_segment_idx = 0;
  9622. }
  9623. planner_abort_hard(); //abort printing
  9624. memcpy(saved_pos, current_position, sizeof(saved_pos));
  9625. if (pos_invalid) saved_pos[X_AXIS] = X_COORD_INVALID;
  9626. saved_feedmultiply2 = feedmultiply; //save feedmultiply
  9627. saved_active_extruder = active_extruder; //save active_extruder
  9628. saved_extruder_temperature = degTargetHotend(active_extruder);
  9629. saved_bed_temperature = degTargetBed();
  9630. saved_extruder_relative_mode = axis_relative_modes & E_AXIS_MASK;
  9631. saved_fan_speed = fanSpeed;
  9632. cmdqueue_reset(); //empty cmdqueue
  9633. card.sdprinting = false;
  9634. // card.closefile();
  9635. saved_printing = true;
  9636. // We may have missed a stepper timer interrupt. Be safe than sorry, reset the stepper timer before re-enabling interrupts.
  9637. st_reset_timer();
  9638. sei();
  9639. if ((z_move != 0) || (e_move != 0)) { // extruder or z move
  9640. // Rather than calling plan_buffer_line directly, push the move into the command queue so that
  9641. // the caller can continue processing. This is used during powerpanic to save the state as we
  9642. // move away from the print.
  9643. char buf[48];
  9644. if(e_move)
  9645. {
  9646. // First unretract (relative extrusion)
  9647. if(!saved_extruder_relative_mode){
  9648. enquecommand(PSTR("M83"), true);
  9649. }
  9650. //retract 45mm/s
  9651. // A single sprintf may not be faster, but is definitely 20B shorter
  9652. // than a sequence of commands building the string piece by piece
  9653. // A snprintf would have been a safer call, but since it is not used
  9654. // in the whole program, its implementation would bring more bytes to the total size
  9655. // The behavior of dtostrf 8,3 should be roughly the same as %-0.3
  9656. sprintf_P(buf, PSTR("G1 E%-0.3f F2700"), e_move);
  9657. enquecommand(buf, false);
  9658. }
  9659. if(z_move)
  9660. {
  9661. // Then lift Z axis
  9662. sprintf_P(buf, PSTR("G1 Z%-0.3f F%-0.3f"), saved_pos[Z_AXIS] + z_move, homing_feedrate[Z_AXIS]);
  9663. enquecommand(buf, false);
  9664. }
  9665. // If this call is invoked from the main Arduino loop() function, let the caller know that the command
  9666. // in the command queue is not the original command, but a new one, so it should not be removed from the queue.
  9667. repeatcommand_front();
  9668. }
  9669. }
  9670. //! @brief Restore print from ram
  9671. //!
  9672. //! Restore print saved by stop_and_save_print_to_ram(). Is blocking, restores
  9673. //! print fan speed, waits for extruder temperature restore, then restores
  9674. //! position and continues print moves.
  9675. //!
  9676. //! Internally lcd_update() is called by wait_for_heater().
  9677. //!
  9678. //! @param e_move
  9679. void restore_print_from_ram_and_continue(float e_move)
  9680. {
  9681. if (!saved_printing) return;
  9682. #ifdef FANCHECK
  9683. // Do not allow resume printing if fans are still not ok
  9684. if ((fan_check_error != EFCE_OK) && (fan_check_error != EFCE_FIXED)) return;
  9685. if (fan_check_error == EFCE_FIXED) fan_check_error = EFCE_OK; //reenable serial stream processing if printing from usb
  9686. #endif
  9687. // restore bed temperature (bed can be disabled during a thermal warning)
  9688. if (degBed() != saved_bed_temperature)
  9689. setTargetBed(saved_bed_temperature);
  9690. // restore active_extruder
  9691. active_extruder = saved_active_extruder;
  9692. fanSpeed = saved_fan_speed;
  9693. if (degTargetHotend(saved_active_extruder) != saved_extruder_temperature)
  9694. {
  9695. setTargetHotendSafe(saved_extruder_temperature, saved_active_extruder);
  9696. heating_status = HeatingStatus::EXTRUDER_HEATING;
  9697. wait_for_heater(_millis(), saved_active_extruder);
  9698. heating_status = HeatingStatus::EXTRUDER_HEATING_COMPLETE;
  9699. }
  9700. axis_relative_modes ^= (-saved_extruder_relative_mode ^ axis_relative_modes) & E_AXIS_MASK;
  9701. float e = saved_pos[E_AXIS] - e_move;
  9702. plan_set_e_position(e);
  9703. #ifdef FANCHECK
  9704. fans_check_enabled = false;
  9705. #endif
  9706. // do not restore XY for commands that do not require that
  9707. if (saved_pos[X_AXIS] == X_COORD_INVALID)
  9708. {
  9709. saved_pos[X_AXIS] = current_position[X_AXIS];
  9710. saved_pos[Y_AXIS] = current_position[Y_AXIS];
  9711. }
  9712. //first move print head in XY to the saved position:
  9713. 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);
  9714. //then move Z
  9715. 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);
  9716. //and finaly unretract (35mm/s)
  9717. plan_buffer_line(saved_pos[X_AXIS], saved_pos[Y_AXIS], saved_pos[Z_AXIS], saved_pos[E_AXIS], FILAMENTCHANGE_RFEED, active_extruder);
  9718. st_synchronize();
  9719. #ifdef FANCHECK
  9720. fans_check_enabled = true;
  9721. #endif
  9722. // restore original feedrate/feedmultiply _after_ restoring the extruder position
  9723. feedrate = saved_feedrate2;
  9724. feedmultiply = saved_feedmultiply2;
  9725. memcpy(current_position, saved_pos, sizeof(saved_pos));
  9726. set_destination_to_current();
  9727. if (saved_printing_type == PRINTING_TYPE_SD) { //was sd printing
  9728. card.setIndex(saved_sdpos);
  9729. sdpos_atomic = saved_sdpos;
  9730. card.sdprinting = true;
  9731. }
  9732. else if (saved_printing_type == PRINTING_TYPE_USB) { //was usb printing
  9733. gcode_LastN = saved_sdpos; //saved_sdpos was reused for storing line number when usb printing
  9734. serial_count = 0;
  9735. FlushSerialRequestResend();
  9736. }
  9737. else {
  9738. //not sd printing nor usb printing
  9739. }
  9740. lcd_setstatuspgm(MSG_WELCOME);
  9741. saved_printing_type = PRINTING_TYPE_NONE;
  9742. saved_printing = false;
  9743. planner_aborted = true; // unroll the stack
  9744. }
  9745. // Cancel the state related to a currently saved print
  9746. void cancel_saved_printing()
  9747. {
  9748. eeprom_update_byte((uint8_t*)EEPROM_UVLO, 0);
  9749. saved_start_position[0] = SAVED_START_POSITION_UNSET;
  9750. saved_printing_type = PRINTING_TYPE_NONE;
  9751. saved_printing = false;
  9752. }
  9753. void print_world_coordinates()
  9754. {
  9755. printf_P(_N("world coordinates: (%.3f, %.3f, %.3f)\n"), current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS]);
  9756. }
  9757. void print_physical_coordinates()
  9758. {
  9759. 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));
  9760. }
  9761. void print_mesh_bed_leveling_table()
  9762. {
  9763. SERIAL_ECHOPGM("mesh bed leveling: ");
  9764. for (int8_t y = 0; y < MESH_NUM_Y_POINTS; ++ y)
  9765. for (int8_t x = 0; x < MESH_NUM_Y_POINTS; ++ x) {
  9766. MYSERIAL.print(mbl.z_values[y][x], 3);
  9767. SERIAL_ECHO(' ');
  9768. }
  9769. SERIAL_ECHOLN();
  9770. }
  9771. uint8_t calc_percent_done()
  9772. {
  9773. //in case that we have information from M73 gcode return percentage counted by slicer, else return percentage counted as byte_printed/filesize
  9774. uint8_t percent_done = 0;
  9775. #ifdef TMC2130
  9776. if (SilentModeMenu == SILENT_MODE_OFF && print_percent_done_normal <= 100)
  9777. {
  9778. percent_done = print_percent_done_normal;
  9779. }
  9780. else if (print_percent_done_silent <= 100)
  9781. {
  9782. percent_done = print_percent_done_silent;
  9783. }
  9784. #else
  9785. if (print_percent_done_normal <= 100)
  9786. {
  9787. percent_done = print_percent_done_normal;
  9788. }
  9789. #endif //TMC2130
  9790. else
  9791. {
  9792. percent_done = card.percentDone();
  9793. }
  9794. return percent_done;
  9795. }
  9796. static void print_time_remaining_init()
  9797. {
  9798. print_time_remaining_normal = PRINT_TIME_REMAINING_INIT;
  9799. print_percent_done_normal = PRINT_PERCENT_DONE_INIT;
  9800. print_time_remaining_silent = PRINT_TIME_REMAINING_INIT;
  9801. print_percent_done_silent = PRINT_PERCENT_DONE_INIT;
  9802. print_time_to_change_normal = PRINT_TIME_REMAINING_INIT;
  9803. print_time_to_change_silent = PRINT_TIME_REMAINING_INIT;
  9804. }
  9805. void load_filament_final_feed()
  9806. {
  9807. current_position[E_AXIS]+= FILAMENTCHANGE_FINALFEED;
  9808. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EFEED_FINAL);
  9809. }
  9810. //! @brief Wait for user to check the state
  9811. //! @par nozzle_temp nozzle temperature to load filament
  9812. void M600_check_state(float nozzle_temp)
  9813. {
  9814. lcd_change_fil_state = 0;
  9815. while (lcd_change_fil_state != 1)
  9816. {
  9817. lcd_change_fil_state = 0;
  9818. KEEPALIVE_STATE(PAUSED_FOR_USER);
  9819. lcd_alright();
  9820. KEEPALIVE_STATE(IN_HANDLER);
  9821. switch(lcd_change_fil_state)
  9822. {
  9823. // Filament failed to load so load it again
  9824. case 2:
  9825. if (MMU2::mmu2.Enabled()){
  9826. //@@TODO mmu_M600_load_filament(false, nozzle_temp); //nonautomatic load; change to "wrong filament loaded" option?
  9827. } else {
  9828. M600_load_filament_movements();
  9829. }
  9830. break;
  9831. // Filament loaded properly but color is not clear
  9832. case 3:
  9833. st_synchronize();
  9834. load_filament_final_feed();
  9835. lcd_loading_color();
  9836. st_synchronize();
  9837. break;
  9838. // Everything good
  9839. default:
  9840. lcd_change_success();
  9841. break;
  9842. }
  9843. }
  9844. }
  9845. //! @brief Wait for user action
  9846. //!
  9847. //! Beep, manage nozzle heater and wait for user to start unload filament
  9848. //! If times out, active extruder temperature is set to 0.
  9849. //!
  9850. //! @param HotendTempBckp Temperature to be restored for active extruder, after user resolves MMU problem.
  9851. void M600_wait_for_user(float HotendTempBckp) {
  9852. KEEPALIVE_STATE(PAUSED_FOR_USER);
  9853. int counterBeep = 0;
  9854. unsigned long waiting_start_time = _millis();
  9855. uint8_t wait_for_user_state = 0;
  9856. lcd_display_message_fullscreen_P(_T(MSG_PRESS_TO_UNLOAD));
  9857. bool bFirst=true;
  9858. while (!(wait_for_user_state == 0 && lcd_clicked())){
  9859. manage_heater();
  9860. manage_inactivity(true);
  9861. #if BEEPER > 0
  9862. if (counterBeep == 500) {
  9863. counterBeep = 0;
  9864. }
  9865. SET_OUTPUT(BEEPER);
  9866. if (counterBeep == 0) {
  9867. if((eSoundMode==e_SOUND_MODE_BLIND)|| (eSoundMode==e_SOUND_MODE_LOUD)||((eSoundMode==e_SOUND_MODE_ONCE)&&bFirst))
  9868. {
  9869. bFirst=false;
  9870. WRITE(BEEPER, HIGH);
  9871. }
  9872. }
  9873. if (counterBeep == 20) {
  9874. WRITE(BEEPER, LOW);
  9875. }
  9876. counterBeep++;
  9877. #endif //BEEPER > 0
  9878. switch (wait_for_user_state) {
  9879. case 0: //nozzle is hot, waiting for user to press the knob to unload filament
  9880. delay_keep_alive(4);
  9881. if (_millis() > waiting_start_time + (unsigned long)M600_TIMEOUT * 1000) {
  9882. lcd_display_message_fullscreen_P(_i("Press the knob to preheat nozzle and continue."));////MSG_PRESS_TO_PREHEAT c=20 r=4
  9883. wait_for_user_state = 1;
  9884. setAllTargetHotends(0);
  9885. st_synchronize();
  9886. disable_e0();
  9887. disable_e1();
  9888. disable_e2();
  9889. }
  9890. break;
  9891. case 1: //nozzle target temperature is set to zero, waiting for user to start nozzle preheat
  9892. delay_keep_alive(4);
  9893. if (lcd_clicked()) {
  9894. setTargetHotend(HotendTempBckp, active_extruder);
  9895. lcd_wait_for_heater();
  9896. wait_for_user_state = 2;
  9897. }
  9898. break;
  9899. case 2: //waiting for nozzle to reach target temperature
  9900. if (fabs(degTargetHotend(active_extruder) - degHotend(active_extruder)) < 1) {
  9901. lcd_display_message_fullscreen_P(_T(MSG_PRESS_TO_UNLOAD));
  9902. waiting_start_time = _millis();
  9903. wait_for_user_state = 0;
  9904. }
  9905. else {
  9906. counterBeep = 20; //beeper will be inactive during waiting for nozzle preheat
  9907. lcd_set_cursor(1, 4);
  9908. lcd_printf_P(PSTR("%3d"), (int16_t)degHotend(active_extruder));
  9909. }
  9910. break;
  9911. }
  9912. }
  9913. WRITE(BEEPER, LOW);
  9914. }
  9915. void M600_load_filament_movements()
  9916. {
  9917. current_position[E_AXIS]+= FILAMENTCHANGE_FIRSTFEED;
  9918. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EFEED_FIRST);
  9919. load_filament_final_feed();
  9920. lcd_loading_filament();
  9921. st_synchronize();
  9922. }
  9923. void M600_load_filament() {
  9924. //load filament for single material and MMU
  9925. lcd_wait_interact();
  9926. //load_filament_time = _millis();
  9927. KEEPALIVE_STATE(PAUSED_FOR_USER);
  9928. while(!lcd_clicked())
  9929. {
  9930. manage_heater();
  9931. manage_inactivity(true);
  9932. #ifdef FILAMENT_SENSOR
  9933. if (fsensor.getFilamentLoadEvent()) {
  9934. Sound_MakeCustom(50,1000,false);
  9935. break;
  9936. }
  9937. #endif //FILAMENT_SENSOR
  9938. }
  9939. KEEPALIVE_STATE(IN_HANDLER);
  9940. M600_load_filament_movements();
  9941. Sound_MakeCustom(50,1000,false);
  9942. lcd_update_enable(false);
  9943. }
  9944. //! @brief Wait for click
  9945. //!
  9946. //! Set
  9947. void marlin_wait_for_click()
  9948. {
  9949. int8_t busy_state_backup = busy_state;
  9950. KEEPALIVE_STATE(PAUSED_FOR_USER);
  9951. lcd_consume_click();
  9952. while(!lcd_clicked())
  9953. {
  9954. manage_heater();
  9955. manage_inactivity(true);
  9956. lcd_update(0);
  9957. }
  9958. KEEPALIVE_STATE(busy_state_backup);
  9959. }
  9960. #define FIL_LOAD_LENGTH 60
  9961. #ifdef PSU_Delta
  9962. bool bEnableForce_z;
  9963. void init_force_z()
  9964. {
  9965. WRITE(Z_ENABLE_PIN,Z_ENABLE_ON);
  9966. bEnableForce_z=true; // "true"-value enforce "disable_force_z()" executing
  9967. disable_force_z();
  9968. }
  9969. void check_force_z()
  9970. {
  9971. if(!(bEnableForce_z||eeprom_read_byte((uint8_t*)EEPROM_SILENT)))
  9972. init_force_z(); // causes enforced switching into disable-state
  9973. }
  9974. void disable_force_z()
  9975. {
  9976. if(!bEnableForce_z) return; // motor already disabled (may be ;-p )
  9977. bEnableForce_z=false;
  9978. // switching to silent mode
  9979. #ifdef TMC2130
  9980. tmc2130_mode=TMC2130_MODE_SILENT;
  9981. update_mode_profile();
  9982. tmc2130_init(TMCInitParams(true, FarmOrUserECool()));
  9983. #endif // TMC2130
  9984. }
  9985. void enable_force_z()
  9986. {
  9987. if(bEnableForce_z)
  9988. return; // motor already enabled (may be ;-p )
  9989. bEnableForce_z=true;
  9990. // mode recovering
  9991. #ifdef TMC2130
  9992. tmc2130_mode=eeprom_read_byte((uint8_t*)EEPROM_SILENT)?TMC2130_MODE_SILENT:TMC2130_MODE_NORMAL;
  9993. update_mode_profile();
  9994. tmc2130_init(TMCInitParams(true, FarmOrUserECool()));
  9995. #endif // TMC2130
  9996. WRITE(Z_ENABLE_PIN,Z_ENABLE_ON); // slightly redundant ;-p
  9997. }
  9998. #endif // PSU_Delta