Marlin_main.cpp 391 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733
  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. int fanSpeed=0;
  195. uint8_t newFanSpeed = 0;
  196. #ifdef FWRETRACT
  197. bool retracted[EXTRUDERS]={false
  198. #if EXTRUDERS > 1
  199. , false
  200. #if EXTRUDERS > 2
  201. , false
  202. #endif
  203. #endif
  204. };
  205. bool retracted_swap[EXTRUDERS]={false
  206. #if EXTRUDERS > 1
  207. , false
  208. #if EXTRUDERS > 2
  209. , false
  210. #endif
  211. #endif
  212. };
  213. float retract_length_swap = RETRACT_LENGTH_SWAP;
  214. float retract_recover_length_swap = RETRACT_RECOVER_LENGTH_SWAP;
  215. #endif
  216. #ifdef PS_DEFAULT_OFF
  217. bool powersupply = false;
  218. #else
  219. bool powersupply = true;
  220. #endif
  221. bool cancel_heatup = false;
  222. int8_t busy_state = NOT_BUSY;
  223. static long prev_busy_signal_ms = -1;
  224. uint8_t host_keepalive_interval = HOST_KEEPALIVE_INTERVAL;
  225. const char errormagic[] PROGMEM = "Error:";
  226. const char echomagic[] PROGMEM = "echo:";
  227. const char G28W0[] PROGMEM = "G28 W0";
  228. // Define some coordinates outside the clamp limits (making them invalid past the parsing stage) so
  229. // that they can be used later for various logical checks
  230. #define X_COORD_INVALID (X_MIN_POS-1)
  231. #define SAVED_START_POSITION_UNSET X_COORD_INVALID
  232. float saved_start_position[NUM_AXIS] = {SAVED_START_POSITION_UNSET, 0, 0, 0};
  233. uint16_t saved_segment_idx = 0;
  234. // storing estimated time to end of print counted by slicer
  235. uint8_t print_percent_done_normal = PRINT_PERCENT_DONE_INIT;
  236. uint8_t print_percent_done_silent = PRINT_PERCENT_DONE_INIT;
  237. uint16_t print_time_remaining_normal = PRINT_TIME_REMAINING_INIT; //estimated remaining print time in minutes
  238. uint16_t print_time_remaining_silent = PRINT_TIME_REMAINING_INIT; //estimated remaining print time in minutes
  239. uint16_t print_time_to_change_normal = PRINT_TIME_REMAINING_INIT; //estimated remaining time to next change in minutes
  240. uint16_t print_time_to_change_silent = PRINT_TIME_REMAINING_INIT; //estimated remaining time to next change in minutes
  241. uint32_t IP_address = 0;
  242. //===========================================================================
  243. //=============================Private Variables=============================
  244. //===========================================================================
  245. #define MSG_BED_LEVELING_FAILED_TIMEOUT 30
  246. const char axis_codes[NUM_AXIS] = {'X', 'Y', 'Z', 'E'};
  247. float destination[NUM_AXIS] = { 0.0, 0.0, 0.0, 0.0};
  248. // For tracing an arc
  249. static float offset[3] = {0.0, 0.0, 0.0};
  250. // Current feedrate
  251. float feedrate = 1500.0;
  252. // Feedrate for the next move
  253. static float next_feedrate;
  254. // Original feedrate saved during homing moves
  255. static float saved_feedrate;
  256. const int8_t sensitive_pins[] PROGMEM = SENSITIVE_PINS; // Sensitive pin list for M42
  257. //static float tt = 0;
  258. //static float bt = 0;
  259. //Inactivity shutdown variables
  260. static LongTimer previous_millis_cmd;
  261. unsigned long max_inactive_time = 0;
  262. static unsigned long stepper_inactive_time = DEFAULT_STEPPER_DEACTIVE_TIME*1000l;
  263. static unsigned long safetytimer_inactive_time = DEFAULT_SAFETYTIMER_TIME_MINS*60*1000ul;
  264. unsigned long starttime=0;
  265. unsigned long stoptime=0;
  266. ShortTimer usb_timer;
  267. bool Stopped=false;
  268. #if NUM_SERVOS > 0
  269. Servo servos[NUM_SERVOS];
  270. #endif
  271. bool target_direction;
  272. //Insert variables if CHDK is defined
  273. #ifdef CHDK
  274. unsigned long chdkHigh = 0;
  275. bool chdkActive = false;
  276. #endif
  277. //! @name RAM save/restore printing
  278. //! @{
  279. bool saved_printing = false; //!< Print is paused and saved in RAM
  280. static uint32_t saved_sdpos = 0; //!< SD card position, or line number in case of USB printing
  281. uint8_t saved_printing_type = PRINTING_TYPE_SD;
  282. static float saved_pos[4] = { X_COORD_INVALID, 0, 0, 0 };
  283. static uint16_t saved_feedrate2 = 0; //!< Default feedrate (truncated from float)
  284. static int saved_feedmultiply2 = 0;
  285. float saved_extruder_temperature = 0.0; //!< Active extruder temperature
  286. float saved_bed_temperature = 0.0;
  287. static bool saved_extruder_relative_mode = false;
  288. int saved_fan_speed = 0; //!< Print fan speed
  289. //! @}
  290. static int saved_feedmultiply_mm = 100;
  291. class AutoReportFeatures {
  292. union {
  293. struct {
  294. uint8_t temp : 1; //Temperature flag
  295. uint8_t fans : 1; //Fans flag
  296. uint8_t pos: 1; //Position flag
  297. uint8_t ar4 : 1; //Unused
  298. uint8_t ar5 : 1; //Unused
  299. uint8_t ar6 : 1; //Unused
  300. uint8_t ar7 : 1; //Unused
  301. } __attribute__((packed)) bits;
  302. uint8_t byte;
  303. } arFunctionsActive;
  304. uint8_t auto_report_period;
  305. public:
  306. LongTimer auto_report_timer;
  307. AutoReportFeatures():auto_report_period(0){
  308. #if defined(AUTO_REPORT)
  309. arFunctionsActive.byte = 0xff;
  310. #else
  311. arFunctionsActive.byte = 0;
  312. #endif //AUTO_REPORT
  313. }
  314. inline bool Temp()const { return arFunctionsActive.bits.temp != 0; }
  315. inline void SetTemp(uint8_t v){ arFunctionsActive.bits.temp = v; }
  316. inline bool Fans()const { return arFunctionsActive.bits.fans != 0; }
  317. inline void SetFans(uint8_t v){ arFunctionsActive.bits.fans = v; }
  318. inline bool Pos()const { return arFunctionsActive.bits.pos != 0; }
  319. inline void SetPos(uint8_t v){ arFunctionsActive.bits.pos = v; }
  320. inline void SetMask(uint8_t mask){ arFunctionsActive.byte = mask; }
  321. /// sets the autoreporting timer's period
  322. /// setting it to zero stops the timer
  323. void SetPeriod(uint8_t p){
  324. auto_report_period = p;
  325. if (auto_report_period != 0){
  326. auto_report_timer.start();
  327. } else{
  328. auto_report_timer.stop();
  329. }
  330. }
  331. inline void TimerStart() { auto_report_timer.start(); }
  332. inline bool TimerRunning()const { return auto_report_timer.running(); }
  333. inline bool TimerExpired() { return auto_report_timer.expired(auto_report_period * 1000ul); }
  334. };
  335. AutoReportFeatures autoReportFeatures;
  336. //===========================================================================
  337. //=============================Routines======================================
  338. //===========================================================================
  339. static bool setTargetedHotend(int code, uint8_t &extruder);
  340. static void print_time_remaining_init();
  341. static void wait_for_heater(long codenum, uint8_t extruder);
  342. static void gcode_G28(bool home_x_axis, bool home_y_axis, bool home_z_axis);
  343. static void gcode_M105(uint8_t extruder);
  344. #ifndef PINDA_THERMISTOR
  345. static void temp_compensation_start();
  346. static void temp_compensation_apply();
  347. #endif
  348. #ifdef PRUSA_SN_SUPPORT
  349. static uint8_t get_PRUSA_SN(char* SN);
  350. #endif //PRUSA_SN_SUPPORT
  351. uint16_t gcode_in_progress = 0;
  352. uint16_t mcode_in_progress = 0;
  353. void serial_echopair_P(const char *s_P, float v)
  354. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  355. void serial_echopair_P(const char *s_P, double v)
  356. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  357. void serial_echopair_P(const char *s_P, unsigned long v)
  358. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  359. void serialprintPGM(const char *str) {
  360. while(uint8_t ch = pgm_read_byte(str)) {
  361. MYSERIAL.write((char)ch);
  362. ++str;
  363. }
  364. }
  365. void serialprintlnPGM(const char *str) {
  366. serialprintPGM(str);
  367. MYSERIAL.println();
  368. }
  369. #ifdef SDSUPPORT
  370. #include "SdFatUtil.h"
  371. int freeMemory() { return SdFatUtil::FreeRam(); }
  372. #else
  373. extern "C" {
  374. extern unsigned int __bss_end;
  375. extern unsigned int __heap_start;
  376. extern void *__brkval;
  377. int freeMemory() {
  378. int free_memory;
  379. if ((int)__brkval == 0)
  380. free_memory = ((int)&free_memory) - ((int)&__bss_end);
  381. else
  382. free_memory = ((int)&free_memory) - ((int)__brkval);
  383. return free_memory;
  384. }
  385. }
  386. #endif //!SDSUPPORT
  387. void setup_killpin()
  388. {
  389. #if defined(KILL_PIN) && KILL_PIN > -1
  390. SET_INPUT(KILL_PIN);
  391. WRITE(KILL_PIN,HIGH);
  392. #endif
  393. }
  394. // Set home pin
  395. void setup_homepin(void)
  396. {
  397. #if defined(HOME_PIN) && HOME_PIN > -1
  398. SET_INPUT(HOME_PIN);
  399. WRITE(HOME_PIN,HIGH);
  400. #endif
  401. }
  402. void setup_photpin()
  403. {
  404. #if defined(PHOTOGRAPH_PIN) && PHOTOGRAPH_PIN > -1
  405. SET_OUTPUT(PHOTOGRAPH_PIN);
  406. WRITE(PHOTOGRAPH_PIN, LOW);
  407. #endif
  408. }
  409. void setup_powerhold()
  410. {
  411. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  412. SET_OUTPUT(SUICIDE_PIN);
  413. WRITE(SUICIDE_PIN, HIGH);
  414. #endif
  415. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  416. SET_OUTPUT(PS_ON_PIN);
  417. #if defined(PS_DEFAULT_OFF)
  418. WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  419. #else
  420. WRITE(PS_ON_PIN, PS_ON_AWAKE);
  421. #endif
  422. #endif
  423. }
  424. void suicide()
  425. {
  426. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  427. SET_OUTPUT(SUICIDE_PIN);
  428. WRITE(SUICIDE_PIN, LOW);
  429. #endif
  430. }
  431. void servo_init()
  432. {
  433. #if (NUM_SERVOS >= 1) && defined(SERVO0_PIN) && (SERVO0_PIN > -1)
  434. servos[0].attach(SERVO0_PIN);
  435. #endif
  436. #if (NUM_SERVOS >= 2) && defined(SERVO1_PIN) && (SERVO1_PIN > -1)
  437. servos[1].attach(SERVO1_PIN);
  438. #endif
  439. #if (NUM_SERVOS >= 3) && defined(SERVO2_PIN) && (SERVO2_PIN > -1)
  440. servos[2].attach(SERVO2_PIN);
  441. #endif
  442. #if (NUM_SERVOS >= 4) && defined(SERVO3_PIN) && (SERVO3_PIN > -1)
  443. servos[3].attach(SERVO3_PIN);
  444. #endif
  445. #if (NUM_SERVOS >= 5)
  446. #error "TODO: enter initalisation code for more servos"
  447. #endif
  448. }
  449. bool __attribute__((noinline)) printer_active() {
  450. return IS_SD_PRINTING
  451. || usb_timer.running()
  452. || isPrintPaused
  453. || (custom_message_type == CustomMsg::TempCal)
  454. || saved_printing
  455. || (lcd_commands_type == LcdCommands::Layer1Cal)
  456. || mmu_print_saved
  457. || homing_flag
  458. || mesh_bed_leveling_flag;
  459. }
  460. bool fans_check_enabled = true;
  461. #ifdef TMC2130
  462. void crashdet_stop_and_save_print()
  463. {
  464. stop_and_save_print_to_ram(10, -default_retraction); //XY - no change, Z 10mm up, E -1mm retract
  465. }
  466. void crashdet_restore_print_and_continue()
  467. {
  468. restore_print_from_ram_and_continue(default_retraction); //XYZ = orig, E +1mm unretract
  469. // babystep_apply();
  470. }
  471. void crashdet_fmt_error(char* buf, uint8_t mask)
  472. {
  473. if(mask & X_AXIS_MASK) *buf++ = axis_codes[X_AXIS];
  474. if(mask & Y_AXIS_MASK) *buf++ = axis_codes[Y_AXIS];
  475. *buf++ = ' ';
  476. strcpy_P(buf, _T(MSG_CRASH_DETECTED));
  477. }
  478. void crashdet_detected(uint8_t mask)
  479. {
  480. st_synchronize();
  481. static uint8_t crashDet_counter = 0;
  482. static uint8_t crashDet_axes = 0;
  483. bool automatic_recovery_after_crash = true;
  484. char msg[LCD_WIDTH+1] = "";
  485. if (crashDetTimer.expired(CRASHDET_TIMER * 1000ul)) {
  486. crashDet_counter = 0;
  487. }
  488. if(++crashDet_counter >= CRASHDET_COUNTER_MAX) {
  489. automatic_recovery_after_crash = false;
  490. }
  491. crashDetTimer.start();
  492. crashDet_axes |= mask;
  493. lcd_update_enable(true);
  494. lcd_clear();
  495. lcd_update(2);
  496. if (mask & X_AXIS_MASK)
  497. {
  498. eeprom_update_byte((uint8_t*)EEPROM_CRASH_COUNT_X, eeprom_read_byte((uint8_t*)EEPROM_CRASH_COUNT_X) + 1);
  499. eeprom_update_word((uint16_t*)EEPROM_CRASH_COUNT_X_TOT, eeprom_read_word((uint16_t*)EEPROM_CRASH_COUNT_X_TOT) + 1);
  500. }
  501. if (mask & Y_AXIS_MASK)
  502. {
  503. eeprom_update_byte((uint8_t*)EEPROM_CRASH_COUNT_Y, eeprom_read_byte((uint8_t*)EEPROM_CRASH_COUNT_Y) + 1);
  504. eeprom_update_word((uint16_t*)EEPROM_CRASH_COUNT_Y_TOT, eeprom_read_word((uint16_t*)EEPROM_CRASH_COUNT_Y_TOT) + 1);
  505. }
  506. lcd_update_enable(true);
  507. lcd_update(2);
  508. // prepare the status message with the _current_ axes status
  509. crashdet_fmt_error(msg, mask);
  510. lcd_setstatus(msg);
  511. gcode_G28(true, true, false); //home X and Y
  512. if (automatic_recovery_after_crash) {
  513. enquecommand_P(PSTR("CRASH_RECOVER"));
  514. }else{
  515. setTargetHotend(0, active_extruder);
  516. // notify the user of *all* the axes previously affected, not just the last one
  517. lcd_update_enable(false);
  518. lcd_clear();
  519. crashdet_fmt_error(msg, crashDet_axes);
  520. crashDet_axes = 0;
  521. lcd_print(msg);
  522. // ask whether to resume printing
  523. lcd_set_cursor(0, 1);
  524. lcd_puts_P(_T(MSG_RESUME_PRINT));
  525. lcd_putc('?');
  526. uint8_t yesno = lcd_show_yes_no_and_wait(false);
  527. if (yesno == LCD_LEFT_BUTTON_CHOICE)
  528. {
  529. enquecommand_P(PSTR("CRASH_RECOVER"));
  530. }
  531. else // LCD_MIDDLE_BUTTON_CHOICE
  532. {
  533. enquecommand_P(PSTR("CRASH_CANCEL"));
  534. }
  535. }
  536. }
  537. void crashdet_recover()
  538. {
  539. crashdet_restore_print_and_continue();
  540. if (lcd_crash_detect_enabled()) tmc2130_sg_stop_on_crash = true;
  541. }
  542. void crashdet_cancel()
  543. {
  544. saved_printing = false;
  545. tmc2130_sg_stop_on_crash = true;
  546. if (saved_printing_type == PRINTING_TYPE_SD) {
  547. lcd_print_stop();
  548. }else if(saved_printing_type == PRINTING_TYPE_USB){
  549. SERIAL_ECHOLNRPGM(MSG_OCTOPRINT_CANCEL); //for Octoprint: works the same as clicking "Abort" button in Octoprint GUI
  550. cmdqueue_reset();
  551. }
  552. }
  553. #endif //TMC2130
  554. void failstats_reset_print()
  555. {
  556. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_X, 0);
  557. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_Y, 0);
  558. eeprom_update_byte((uint8_t *)EEPROM_FERROR_COUNT, 0);
  559. eeprom_update_byte((uint8_t *)EEPROM_POWER_COUNT, 0);
  560. eeprom_update_byte((uint8_t *)EEPROM_MMU_FAIL, 0);
  561. eeprom_update_byte((uint8_t *)EEPROM_MMU_LOAD_FAIL, 0);
  562. }
  563. void softReset()
  564. {
  565. cli();
  566. wdt_enable(WDTO_15MS);
  567. while(1);
  568. }
  569. #ifdef MESH_BED_LEVELING
  570. enum MeshLevelingState { MeshReport, MeshStart, MeshNext, MeshSet };
  571. #endif
  572. static void factory_reset_stats(){
  573. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, 0);
  574. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, 0);
  575. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_X, 0);
  576. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_Y, 0);
  577. eeprom_update_byte((uint8_t *)EEPROM_FERROR_COUNT, 0);
  578. eeprom_update_byte((uint8_t *)EEPROM_POWER_COUNT, 0);
  579. eeprom_update_word((uint16_t *)EEPROM_CRASH_COUNT_X_TOT, 0);
  580. eeprom_update_word((uint16_t *)EEPROM_CRASH_COUNT_Y_TOT, 0);
  581. eeprom_update_word((uint16_t *)EEPROM_FERROR_COUNT_TOT, 0);
  582. eeprom_update_word((uint16_t *)EEPROM_POWER_COUNT_TOT, 0);
  583. eeprom_update_word((uint16_t *)EEPROM_MMU_FAIL_TOT, 0);
  584. eeprom_update_word((uint16_t *)EEPROM_MMU_LOAD_FAIL_TOT, 0);
  585. eeprom_update_byte((uint8_t *)EEPROM_MMU_FAIL, 0);
  586. eeprom_update_byte((uint8_t *)EEPROM_MMU_LOAD_FAIL, 0);
  587. }
  588. // Factory reset function
  589. // This function is used to erase parts or whole EEPROM memory which is used for storing calibration and and so on.
  590. // Level input parameter sets depth of reset
  591. static void factory_reset(char level)
  592. {
  593. lcd_clear();
  594. Sound_MakeCustom(100,0,false);
  595. switch (level) {
  596. case 0: // Level 0: Language reset
  597. lang_reset();
  598. break;
  599. case 1: //Level 1: Reset statistics
  600. factory_reset_stats();
  601. lcd_menu_statistics();
  602. break;
  603. case 2: // Level 2: Prepare for shipping
  604. factory_reset_stats();
  605. // FALLTHRU
  606. case 3: // Level 3: Preparation after being serviced
  607. // Force language selection at the next boot up.
  608. lang_reset();
  609. // Force the "Follow calibration flow" message at the next boot up.
  610. calibration_status_store(CALIBRATION_STATUS_Z_CALIBRATION);
  611. eeprom_write_byte((uint8_t*)EEPROM_WIZARD_ACTIVE, 2); //run wizard
  612. farm_disable();
  613. #ifdef FILAMENT_SENSOR
  614. fsensor.setEnabled(true);
  615. fsensor.setAutoLoadEnabled(true, true);
  616. fsensor.setRunoutEnabled(true, true);
  617. #if (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  618. fsensor.setJamDetectionEnabled(true, true);
  619. #endif //(FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  620. #endif //FILAMENT_SENSOR
  621. break;
  622. case 4:
  623. menu_progressbar_init(EEPROM_TOP, PSTR("ERASING all data"));
  624. // Erase EEPROM
  625. for (uint16_t i = 0; i < EEPROM_TOP; i++) {
  626. eeprom_update_byte((uint8_t*)i, 0xFF);
  627. menu_progressbar_update(i);
  628. }
  629. menu_progressbar_finish();
  630. softReset();
  631. break;
  632. default:
  633. break;
  634. }
  635. }
  636. extern "C" {
  637. FILE _uartout; //= {0}; Global variable is always zero initialized. No need to explicitly state this.
  638. }
  639. int uart_putchar(char c, FILE *)
  640. {
  641. MYSERIAL.write(c);
  642. return 0;
  643. }
  644. void lcd_splash()
  645. {
  646. lcd_clear(); // clears display and homes screen
  647. lcd_puts_P(PSTR("\n Original Prusa i3\n Prusa Research"));
  648. }
  649. void factory_reset()
  650. {
  651. KEEPALIVE_STATE(PAUSED_FOR_USER);
  652. if (!READ(BTN_ENC))
  653. {
  654. _delay_ms(1000);
  655. if (!READ(BTN_ENC))
  656. {
  657. lcd_clear();
  658. lcd_puts_P(PSTR("Factory RESET"));
  659. SET_OUTPUT(BEEPER);
  660. if(eSoundMode!=e_SOUND_MODE_SILENT)
  661. WRITE(BEEPER, HIGH);
  662. while (!READ(BTN_ENC));
  663. WRITE(BEEPER, LOW);
  664. _delay_ms(2000);
  665. char level = reset_menu();
  666. factory_reset(level);
  667. switch (level) {
  668. case 0:
  669. case 1:
  670. case 2:
  671. case 3:
  672. case 4: _delay_ms(0); break;
  673. }
  674. }
  675. }
  676. KEEPALIVE_STATE(IN_HANDLER);
  677. }
  678. void show_fw_version_warnings() {
  679. if (FW_DEV_VERSION == FW_VERSION_GOLD || FW_DEV_VERSION == FW_VERSION_RC) return;
  680. switch (FW_DEV_VERSION) {
  681. 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
  682. 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
  683. case(FW_VERSION_DEVEL):
  684. case(FW_VERSION_DEBUG):
  685. lcd_update_enable(false);
  686. lcd_clear();
  687. #if FW_DEV_VERSION == FW_VERSION_DEVEL
  688. lcd_puts_at_P(0, 0, PSTR("Development build !!"));
  689. #else
  690. lcd_puts_at_P(0, 0, PSTR("Debbugging build !!!"));
  691. #endif
  692. lcd_puts_at_P(0, 1, PSTR("May destroy printer!"));
  693. lcd_puts_at_P(0, 2, PSTR("ver ")); lcd_puts_P(PSTR(FW_VERSION_FULL));
  694. lcd_puts_at_P(0, 3, PSTR(FW_REPOSITORY));
  695. lcd_wait_for_click();
  696. break;
  697. // 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
  698. }
  699. lcd_update_enable(true);
  700. }
  701. #if defined(FILAMENT_SENSOR) && defined(FSENSOR_PROBING)
  702. //! @brief try to check if firmware is on right type of printer
  703. static void check_if_fw_is_on_right_printer() {
  704. if (fsensor.probeOtherType()) {
  705. lcd_show_fullscreen_message_and_wait_P(_i(PRINTER_NAME " firmware detected on " PRINTER_NAME_ALTERNATE " printer"));////c=20 r=4
  706. }
  707. }
  708. #endif //defined(FILAMENT_SENSOR) && defined(FSENSOR_PROBING)
  709. uint8_t check_printer_version()
  710. {
  711. uint8_t version_changed = 0;
  712. uint16_t printer_type = eeprom_read_word((uint16_t*)EEPROM_PRINTER_TYPE);
  713. uint16_t motherboard = eeprom_read_word((uint16_t*)EEPROM_BOARD_TYPE);
  714. if (printer_type != PRINTER_TYPE) {
  715. if (printer_type == 0xffff) eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  716. else version_changed |= 0b10;
  717. }
  718. if (motherboard != MOTHERBOARD) {
  719. if(motherboard == 0xffff) eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  720. else version_changed |= 0b01;
  721. }
  722. return version_changed;
  723. }
  724. #ifdef BOOTAPP
  725. #include "bootapp.h" //bootloader support
  726. #endif //BOOTAPP
  727. #if (LANG_MODE != 0) //secondary language support
  728. #ifdef XFLASH
  729. // language update from external flash
  730. #define LANGBOOT_BLOCKSIZE 0x1000u
  731. #define LANGBOOT_RAMBUFFER 0x0800
  732. void update_sec_lang_from_external_flash()
  733. {
  734. if ((boot_app_magic == BOOT_APP_MAGIC) && (boot_app_flags & BOOT_APP_FLG_USER0))
  735. {
  736. uint8_t lang = boot_reserved >> 3;
  737. uint8_t state = boot_reserved & 0x07;
  738. lang_table_header_t header;
  739. uint32_t src_addr;
  740. if (lang_get_header(lang, &header, &src_addr))
  741. {
  742. lcd_puts_at_P(1,3,PSTR("Language update."));
  743. for (uint8_t i = 0; i < state; i++) fputc('.', lcdout);
  744. _delay(100);
  745. boot_reserved = (boot_reserved & 0xF8) | ((state + 1) & 0x07);
  746. if ((state * LANGBOOT_BLOCKSIZE) < header.size)
  747. {
  748. cli();
  749. uint16_t size = header.size - state * LANGBOOT_BLOCKSIZE;
  750. if (size > LANGBOOT_BLOCKSIZE) size = LANGBOOT_BLOCKSIZE;
  751. xflash_rd_data(src_addr + state * LANGBOOT_BLOCKSIZE, (uint8_t*)LANGBOOT_RAMBUFFER, size);
  752. if (state == 0)
  753. {
  754. //TODO - check header integrity
  755. }
  756. bootapp_ram2flash(LANGBOOT_RAMBUFFER, _SEC_LANG_TABLE + state * LANGBOOT_BLOCKSIZE, size);
  757. }
  758. else
  759. {
  760. //TODO - check sec lang data integrity
  761. eeprom_update_byte((unsigned char *)EEPROM_LANG, LANG_ID_SEC);
  762. }
  763. }
  764. }
  765. boot_app_flags &= ~BOOT_APP_FLG_USER0;
  766. }
  767. #ifdef DEBUG_XFLASH
  768. uint8_t lang_xflash_enum_codes(uint16_t* codes)
  769. {
  770. lang_table_header_t header;
  771. uint8_t count = 0;
  772. uint32_t addr = 0x00000;
  773. while (1)
  774. {
  775. printf_P(_n("LANGTABLE%d:"), count);
  776. xflash_rd_data(addr, (uint8_t*)&header, sizeof(lang_table_header_t));
  777. if (header.magic != LANG_MAGIC)
  778. {
  779. puts_P(_n("NG!"));
  780. break;
  781. }
  782. puts_P(_n("OK"));
  783. printf_P(_n(" _lt_magic = 0x%08lx %S\n"), header.magic, (header.magic==LANG_MAGIC)?_n("OK"):_n("NA"));
  784. printf_P(_n(" _lt_size = 0x%04x (%d)\n"), header.size, header.size);
  785. printf_P(_n(" _lt_count = 0x%04x (%d)\n"), header.count, header.count);
  786. printf_P(_n(" _lt_chsum = 0x%04x\n"), header.checksum);
  787. printf_P(_n(" _lt_code = 0x%04x (%c%c)\n"), header.code, header.code >> 8, header.code & 0xff);
  788. printf_P(_n(" _lt_sign = 0x%08lx\n"), header.signature);
  789. addr += header.size;
  790. codes[count] = header.code;
  791. count ++;
  792. }
  793. return count;
  794. }
  795. void list_sec_lang_from_external_flash()
  796. {
  797. uint16_t codes[8];
  798. uint8_t count = lang_xflash_enum_codes(codes);
  799. printf_P(_n("XFlash lang count = %hhd\n"), count);
  800. }
  801. #endif //DEBUG_XFLASH
  802. #endif //XFLASH
  803. #endif //(LANG_MODE != 0)
  804. static void fw_crash_init()
  805. {
  806. #ifdef XFLASH_DUMP
  807. dump_crash_reason crash_reason;
  808. if(xfdump_check_state(&crash_reason))
  809. {
  810. // always signal to the host that a dump is available for retrieval
  811. puts_P(_N("// action:dump_available"));
  812. #ifdef EMERGENCY_DUMP
  813. if(crash_reason != dump_crash_reason::manual &&
  814. eeprom_read_byte((uint8_t*)EEPROM_FW_CRASH_FLAG) != 0xFF)
  815. {
  816. lcd_show_fullscreen_message_and_wait_P(
  817. _n("FW crash detected! "
  818. "You can continue printing. "
  819. "Debug data available for analysis. "
  820. "Contact support to submit details."));
  821. }
  822. #endif
  823. }
  824. #else //XFLASH_DUMP
  825. dump_crash_reason crash_reason = (dump_crash_reason)eeprom_read_byte((uint8_t*)EEPROM_FW_CRASH_FLAG);
  826. if(crash_reason != dump_crash_reason::manual && (uint8_t)crash_reason != 0xFF)
  827. {
  828. lcd_beeper_quick_feedback();
  829. lcd_clear();
  830. lcd_puts_P(_n("FIRMWARE CRASH!\nCrash reason:\n"));
  831. switch(crash_reason)
  832. {
  833. case dump_crash_reason::stack_error:
  834. lcd_puts_P(_n("Static memory has\nbeen overwritten"));
  835. break;
  836. case dump_crash_reason::watchdog:
  837. lcd_puts_P(_n("Watchdog timeout"));
  838. break;
  839. case dump_crash_reason::bad_isr:
  840. lcd_puts_P(_n("Bad interrupt"));
  841. break;
  842. default:
  843. lcd_print((uint8_t)crash_reason);
  844. break;
  845. }
  846. lcd_wait_for_click();
  847. }
  848. #endif //XFLASH_DUMP
  849. // prevent crash prompts to reappear once acknowledged
  850. eeprom_update_byte((uint8_t*)EEPROM_FW_CRASH_FLAG, 0xFF);
  851. }
  852. static void xflash_err_msg()
  853. {
  854. puts_P(_n("XFLASH not responding."));
  855. lcd_show_fullscreen_message_and_wait_P(_n("External SPI flash\nXFLASH is not res-\nponding. Language\nswitch unavailable."));
  856. }
  857. // "Setup" function is called by the Arduino framework on startup.
  858. // Before startup, the Timers-functions (PWM)/Analog RW and HardwareSerial provided by the Arduino-code
  859. // are initialized by the main() routine provided by the Arduino framework.
  860. void setup()
  861. {
  862. timer2_init(); // enables functional millis
  863. ultralcd_init();
  864. spi_init();
  865. lcd_splash();
  866. Sound_Init(); // also guarantee "SET_OUTPUT(BEEPER)"
  867. selectedSerialPort = eeprom_read_byte((uint8_t *)EEPROM_SECOND_SERIAL_ACTIVE);
  868. if (selectedSerialPort == 0xFF) selectedSerialPort = 0;
  869. eeprom_update_byte((uint8_t *)EEPROM_SECOND_SERIAL_ACTIVE, selectedSerialPort);
  870. MYSERIAL.begin(BAUDRATE);
  871. fdev_setup_stream(uartout, uart_putchar, NULL, _FDEV_SETUP_WRITE); //setup uart out stream
  872. stdout = uartout;
  873. #ifdef XFLASH
  874. bool xflash_success = xflash_init();
  875. uint8_t optiboot_status = 1;
  876. if (xflash_success)
  877. {
  878. optiboot_status = optiboot_xflash_enter();
  879. #if (LANG_MODE != 0) //secondary language support
  880. update_sec_lang_from_external_flash();
  881. #endif //(LANG_MODE != 0)
  882. }
  883. #else
  884. const bool xflash_success = true;
  885. #endif //XFLASH
  886. setup_killpin();
  887. setup_powerhold();
  888. farm_mode_init();
  889. #ifdef TMC2130
  890. if( FarmOrUserECool() ){
  891. //increased extruder current (PFW363)
  892. tmc2130_current_h[E_AXIS] = TMC2130_CURRENTS_FARM;
  893. tmc2130_current_r[E_AXIS] = TMC2130_CURRENTS_FARM;
  894. }
  895. #endif //TMC2130
  896. #ifdef PRUSA_SN_SUPPORT
  897. //Check for valid SN in EEPROM. Try to retrieve it in case it's invalid.
  898. //SN is valid only if it is NULL terminated and starts with "CZPX".
  899. {
  900. char SN[20];
  901. eeprom_read_block(SN, (uint8_t*)EEPROM_PRUSA_SN, 20);
  902. if (SN[19] || strncmp_P(SN, PSTR("CZPX"), 4))
  903. {
  904. if (!get_PRUSA_SN(SN))
  905. {
  906. eeprom_update_block(SN, (uint8_t*)EEPROM_PRUSA_SN, 20);
  907. puts_P(PSTR("SN updated"));
  908. }
  909. else
  910. puts_P(PSTR("SN update failed"));
  911. }
  912. }
  913. #endif //PRUSA_SN_SUPPORT
  914. #ifndef XFLASH
  915. SERIAL_PROTOCOLLNPGM("start");
  916. #else
  917. if ((optiboot_status != 0) || (selectedSerialPort != 0))
  918. SERIAL_PROTOCOLLNPGM("start");
  919. #endif
  920. SERIAL_ECHO_START;
  921. puts_P(PSTR(" " FW_VERSION_FULL));
  922. if (eeprom_read_byte((uint8_t *)EEPROM_MMU_ENABLED)) {
  923. MMU2::mmu2.Start();
  924. }
  925. //SERIAL_ECHOPAIR("Active sheet before:", static_cast<unsigned long int>(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet))));
  926. #ifdef DEBUG_SEC_LANG
  927. lang_table_header_t header;
  928. uint32_t src_addr = 0x00000;
  929. if (lang_get_header(1, &header, &src_addr))
  930. {
  931. printf_P(
  932. _n(
  933. " _src_addr = 0x%08lx\n"
  934. " _lt_magic = 0x%08lx %S\n"
  935. " _lt_size = 0x%04x (%d)\n"
  936. " _lt_count = 0x%04x (%d)\n"
  937. " _lt_chsum = 0x%04x\n"
  938. " _lt_code = 0x%04x (%c%c)\n"
  939. " _lt_resv1 = 0x%08lx\n"
  940. ),
  941. src_addr,
  942. header.magic, (header.magic==LANG_MAGIC)?_n("OK"):_n("NA"),
  943. header.size, header.size,
  944. header.count, header.count,
  945. header.checksum,
  946. header.code, header.code >> 8, header.code & 0xff,
  947. header.signature
  948. );
  949. #if 0
  950. xflash_rd_data(0x25ba, (uint8_t*)&block_buffer, 1024);
  951. for (uint16_t i = 0; i < 1024; i++)
  952. {
  953. if ((i % 16) == 0) printf_P(_n("%04x:"), 0x25ba+i);
  954. printf_P(_n(" %02x"), ((uint8_t*)&block_buffer)[i]);
  955. if ((i % 16) == 15) putchar('\n');
  956. }
  957. #endif
  958. uint16_t sum = 0;
  959. for (uint16_t i = 0; i < header.size; i++)
  960. sum += (uint16_t)pgm_read_byte((uint8_t*)(_SEC_LANG_TABLE + i)) << ((i & 1)?0:8);
  961. printf_P(_n("_SEC_LANG_TABLE checksum = %04x\n"), sum);
  962. sum -= header.checksum; //subtract checksum
  963. printf_P(_n("_SEC_LANG_TABLE checksum = %04x\n"), sum);
  964. sum = (sum >> 8) | ((sum & 0xff) << 8); //swap bytes
  965. if (sum == header.checksum)
  966. puts_P(_n("Checksum OK"));
  967. else
  968. puts_P(_n("Checksum NG"));
  969. }
  970. else
  971. puts_P(_n("lang_get_header failed!"));
  972. #if 0
  973. for (uint16_t i = 0; i < 1024*10; i++)
  974. {
  975. if ((i % 16) == 0) printf_P(_n("%04x:"), _SEC_LANG_TABLE+i);
  976. printf_P(_n(" %02x"), pgm_read_byte((uint8_t*)(_SEC_LANG_TABLE+i)));
  977. if ((i % 16) == 15) putchar('\n');
  978. }
  979. #endif
  980. #if 0
  981. SERIAL_ECHOLN("Reading eeprom from 0 to 100: start");
  982. for (int i = 0; i < 4096; ++i) {
  983. int b = eeprom_read_byte((unsigned char*)i);
  984. if (b != 255) {
  985. SERIAL_ECHO(i);
  986. SERIAL_ECHO(":");
  987. SERIAL_ECHO(b);
  988. SERIAL_ECHOLN("");
  989. }
  990. }
  991. SERIAL_ECHOLN("Reading eeprom from 0 to 100: done");
  992. #endif
  993. #endif //DEBUG_SEC_LANG
  994. // Check startup - does nothing if bootloader sets MCUSR to 0
  995. byte mcu = MCUSR;
  996. /* if (mcu & 1) SERIAL_ECHOLNRPGM(MSG_POWERUP);
  997. if (mcu & 2) SERIAL_ECHOLNRPGM(MSG_EXTERNAL_RESET);
  998. if (mcu & 4) SERIAL_ECHOLNRPGM(MSG_BROWNOUT_RESET);
  999. if (mcu & 8) SERIAL_ECHOLNRPGM(MSG_WATCHDOG_RESET);
  1000. if (mcu & 32) SERIAL_ECHOLNRPGM(MSG_SOFTWARE_RESET);*/
  1001. if (mcu & 1) puts_P(MSG_POWERUP);
  1002. if (mcu & 2) puts_P(MSG_EXTERNAL_RESET);
  1003. if (mcu & 4) puts_P(MSG_BROWNOUT_RESET);
  1004. if (mcu & 8) puts_P(MSG_WATCHDOG_RESET);
  1005. if (mcu & 32) puts_P(MSG_SOFTWARE_RESET);
  1006. MCUSR = 0;
  1007. //SERIAL_ECHORPGM(MSG_MARLIN);
  1008. //SERIAL_ECHOLNRPGM(VERSION_STRING);
  1009. #ifdef STRING_VERSION_CONFIG_H
  1010. #ifdef STRING_CONFIG_H_AUTHOR
  1011. SERIAL_ECHO_START;
  1012. SERIAL_ECHORPGM(_n(" Last Updated: "));////MSG_CONFIGURATION_VER
  1013. SERIAL_ECHOPGM(STRING_VERSION_CONFIG_H);
  1014. SERIAL_ECHORPGM(_n(" | Author: "));////MSG_AUTHOR
  1015. SERIAL_ECHOLNPGM(STRING_CONFIG_H_AUTHOR);
  1016. SERIAL_ECHOPGM("Compiled: ");
  1017. SERIAL_ECHOLNPGM(__DATE__);
  1018. #endif
  1019. #endif
  1020. SERIAL_ECHO_START;
  1021. SERIAL_ECHORPGM(_n(" Free Memory: "));////MSG_FREE_MEMORY
  1022. SERIAL_ECHO(freeMemory());
  1023. SERIAL_ECHORPGM(_n(" PlannerBufferBytes: "));////MSG_PLANNER_BUFFER_BYTES
  1024. SERIAL_ECHOLN((int)sizeof(block_t)*BLOCK_BUFFER_SIZE);
  1025. //lcd_update_enable(false); // why do we need this?? - andre
  1026. // loads data from EEPROM if available else uses defaults (and resets step acceleration rate)
  1027. bool previous_settings_retrieved = false;
  1028. uint8_t hw_changed = check_printer_version();
  1029. 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
  1030. previous_settings_retrieved = Config_RetrieveSettings();
  1031. }
  1032. else { //printer version was changed so use default settings
  1033. Config_ResetDefault();
  1034. }
  1035. // writes a magic number at the end of static variables to monitor against incorrect overwriting
  1036. // of static memory by stack (this needs to be done before soft_pwm_init, since the check is
  1037. // performed inside the soft_pwm_isr)
  1038. SdFatUtil::set_stack_guard();
  1039. // Initialize pwm/temperature loops
  1040. soft_pwm_init();
  1041. temp_mgr_init();
  1042. #ifdef EXTRUDER_ALTFAN_DETECT
  1043. SERIAL_ECHORPGM(_n("Extruder fan type: "));
  1044. if (extruder_altfan_detect())
  1045. SERIAL_ECHOLNRPGM(PSTR("ALTFAN"));
  1046. else
  1047. SERIAL_ECHOLNRPGM(PSTR("NOCTUA"));
  1048. #endif //EXTRUDER_ALTFAN_DETECT
  1049. plan_init(); // Initialize planner;
  1050. factory_reset();
  1051. if (eeprom_read_dword((uint32_t*)(EEPROM_TOP - 4)) == 0x0ffffffff &&
  1052. eeprom_read_dword((uint32_t*)(EEPROM_TOP - 8)) == 0x0ffffffff)
  1053. {
  1054. // Maiden startup. The firmware has been loaded and first started on a virgin RAMBo board,
  1055. // where all the EEPROM entries are set to 0x0ff.
  1056. // Once a firmware boots up, it forces at least a language selection, which changes
  1057. // EEPROM_LANG to number lower than 0x0ff.
  1058. // 1) Set a high power mode.
  1059. eeprom_update_byte((uint8_t*)EEPROM_SILENT, SILENT_MODE_OFF);
  1060. #ifdef TMC2130
  1061. tmc2130_mode = TMC2130_MODE_NORMAL;
  1062. #endif //TMC2130
  1063. eeprom_write_byte((uint8_t*)EEPROM_WIZARD_ACTIVE, 1); //run wizard
  1064. }
  1065. lcd_encoder_diff=0;
  1066. #ifdef TMC2130
  1067. uint8_t silentMode = eeprom_read_byte((uint8_t*)EEPROM_SILENT);
  1068. if (silentMode == 0xff) silentMode = 0;
  1069. tmc2130_mode = TMC2130_MODE_NORMAL;
  1070. if (lcd_crash_detect_enabled() && !farm_mode)
  1071. {
  1072. lcd_crash_detect_enable();
  1073. puts_P(_N("CrashDetect ENABLED!"));
  1074. }
  1075. else
  1076. {
  1077. lcd_crash_detect_disable();
  1078. puts_P(_N("CrashDetect DISABLED"));
  1079. }
  1080. #ifdef TMC2130_LINEARITY_CORRECTION
  1081. #ifdef TMC2130_LINEARITY_CORRECTION_XYZ
  1082. tmc2130_wave_fac[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_X_FAC);
  1083. tmc2130_wave_fac[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_Y_FAC);
  1084. tmc2130_wave_fac[Z_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_Z_FAC);
  1085. #endif //TMC2130_LINEARITY_CORRECTION_XYZ
  1086. tmc2130_wave_fac[E_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_E_FAC);
  1087. if (tmc2130_wave_fac[X_AXIS] == 0xff) tmc2130_wave_fac[X_AXIS] = 0;
  1088. if (tmc2130_wave_fac[Y_AXIS] == 0xff) tmc2130_wave_fac[Y_AXIS] = 0;
  1089. if (tmc2130_wave_fac[Z_AXIS] == 0xff) tmc2130_wave_fac[Z_AXIS] = 0;
  1090. if (tmc2130_wave_fac[E_AXIS] == 0xff) tmc2130_wave_fac[E_AXIS] = 0;
  1091. #endif //TMC2130_LINEARITY_CORRECTION
  1092. #ifdef TMC2130_VARIABLE_RESOLUTION
  1093. tmc2130_mres[X_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[X_AXIS]);
  1094. tmc2130_mres[Y_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[Y_AXIS]);
  1095. tmc2130_mres[Z_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[Z_AXIS]);
  1096. tmc2130_mres[E_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[E_AXIS]);
  1097. #else //TMC2130_VARIABLE_RESOLUTION
  1098. tmc2130_mres[X_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_XY);
  1099. tmc2130_mres[Y_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_XY);
  1100. tmc2130_mres[Z_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_Z);
  1101. tmc2130_mres[E_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_E);
  1102. #endif //TMC2130_VARIABLE_RESOLUTION
  1103. #endif //TMC2130
  1104. st_init(); // Initialize stepper, this enables interrupts!
  1105. #ifdef TMC2130
  1106. tmc2130_mode = silentMode?TMC2130_MODE_SILENT:TMC2130_MODE_NORMAL;
  1107. update_mode_profile();
  1108. tmc2130_init(TMCInitParams(false, FarmOrUserECool() ));
  1109. #endif //TMC2130
  1110. #ifdef PSU_Delta
  1111. init_force_z(); // ! important for correct Z-axis initialization
  1112. #endif // PSU_Delta
  1113. setup_photpin();
  1114. #if 0
  1115. servo_init();
  1116. #endif
  1117. // Reset the machine correction matrix.
  1118. // It does not make sense to load the correction matrix until the machine is homed.
  1119. world2machine_reset();
  1120. // Initialize current_position accounting for software endstops to
  1121. // avoid unexpected initial shifts on the first move
  1122. clamp_to_software_endstops(current_position);
  1123. plan_set_position_curposXYZE();
  1124. // Show the xflash error message now that serial, lcd and encoder are available
  1125. if (!xflash_success)
  1126. xflash_err_msg();
  1127. #ifdef FILAMENT_SENSOR
  1128. fsensor.init();
  1129. #endif //FILAMENT_SENSOR
  1130. #if defined(CONTROLLERFAN_PIN) && (CONTROLLERFAN_PIN > -1)
  1131. SET_OUTPUT(CONTROLLERFAN_PIN); //Set pin used for driver cooling fan
  1132. #endif
  1133. setup_homepin();
  1134. #if defined(Z_AXIS_ALWAYS_ON)
  1135. enable_z();
  1136. #endif
  1137. // The farm monitoring SW may accidentally expect
  1138. // 2 messages of "printer started" to consider a printer working.
  1139. prusa_statistics(8);
  1140. // Enable Toshiba FlashAir SD card / WiFi enahanced card.
  1141. card.ToshibaFlashAir_enable(eeprom_read_byte((unsigned char*)EEPROM_TOSHIBA_FLASH_AIR_COMPATIBLITY) == 1);
  1142. // Force SD card update. Otherwise the SD card update is done from loop() on card.checkautostart(false),
  1143. // but this times out if a blocking dialog is shown in setup().
  1144. card.initsd();
  1145. #ifdef DEBUG_SD_SPEED_TEST
  1146. if (card.cardOK)
  1147. {
  1148. uint8_t* buff = (uint8_t*)block_buffer;
  1149. uint32_t block = 0;
  1150. uint32_t sumr = 0;
  1151. uint32_t sumw = 0;
  1152. for (int i = 0; i < 1024; i++)
  1153. {
  1154. uint32_t u = _micros();
  1155. bool res = card.card.readBlock(i, buff);
  1156. u = _micros() - u;
  1157. if (res)
  1158. {
  1159. printf_P(PSTR("readBlock %4d 512 bytes %lu us\n"), i, u);
  1160. sumr += u;
  1161. u = _micros();
  1162. res = card.card.writeBlock(i, buff);
  1163. u = _micros() - u;
  1164. if (res)
  1165. {
  1166. printf_P(PSTR("writeBlock %4d 512 bytes %lu us\n"), i, u);
  1167. sumw += u;
  1168. }
  1169. else
  1170. {
  1171. printf_P(PSTR("writeBlock %4d error\n"), i);
  1172. break;
  1173. }
  1174. }
  1175. else
  1176. {
  1177. printf_P(PSTR("readBlock %4d error\n"), i);
  1178. break;
  1179. }
  1180. }
  1181. uint32_t avg_rspeed = (1024 * 1000000) / (sumr / 512);
  1182. uint32_t avg_wspeed = (1024 * 1000000) / (sumw / 512);
  1183. printf_P(PSTR("avg read speed %lu bytes/s\n"), avg_rspeed);
  1184. printf_P(PSTR("avg write speed %lu bytes/s\n"), avg_wspeed);
  1185. }
  1186. else
  1187. printf_P(PSTR("Card NG!\n"));
  1188. #endif //DEBUG_SD_SPEED_TEST
  1189. eeprom_init();
  1190. // In the future, somewhere here would one compare the current firmware version against the firmware version stored in the EEPROM.
  1191. // If they differ, an update procedure may need to be performed. At the end of this block, the current firmware version
  1192. // is being written into the EEPROM, so the update procedure will be triggered only once.
  1193. #if (LANG_MODE != 0) //secondary language support
  1194. #ifdef DEBUG_XFLASH
  1195. XFLASH_SPI_ENTER();
  1196. uint8_t uid[8]; // 64bit unique id
  1197. xflash_rd_uid(uid);
  1198. puts_P(_n("XFLASH UID="));
  1199. for (uint8_t i = 0; i < 8; i ++)
  1200. printf_P(PSTR("%02x"), uid[i]);
  1201. putchar('\n');
  1202. list_sec_lang_from_external_flash();
  1203. #endif //DEBUG_XFLASH
  1204. // lang_reset();
  1205. if (!lang_select(eeprom_read_byte((uint8_t*)EEPROM_LANG)))
  1206. lcd_language();
  1207. #ifdef DEBUG_SEC_LANG
  1208. uint16_t sec_lang_code = lang_get_code(1);
  1209. uint16_t ui = _SEC_LANG_TABLE; //table pointer
  1210. 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);
  1211. lang_print_sec_lang(uartout);
  1212. #endif //DEBUG_SEC_LANG
  1213. #endif //(LANG_MODE != 0)
  1214. if (eeprom_read_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE) == 255) {
  1215. eeprom_write_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE, 0);
  1216. }
  1217. if (eeprom_read_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA) == 255) {
  1218. //eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0);
  1219. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  1220. int16_t z_shift = 0;
  1221. for (uint8_t i = 0; i < 5; i++) {
  1222. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  1223. }
  1224. eeprom_write_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE, 0);
  1225. }
  1226. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO) == 255) {
  1227. eeprom_write_byte((uint8_t*)EEPROM_UVLO, 0);
  1228. }
  1229. if (eeprom_read_byte((uint8_t*)EEPROM_SD_SORT) == 255) {
  1230. eeprom_write_byte((uint8_t*)EEPROM_SD_SORT, 0);
  1231. }
  1232. //mbl_mode_init();
  1233. mbl_settings_init();
  1234. SilentModeMenu_MMU = eeprom_read_byte((uint8_t*)EEPROM_MMU_STEALTH);
  1235. if (SilentModeMenu_MMU == 255) {
  1236. SilentModeMenu_MMU = 1;
  1237. eeprom_write_byte((uint8_t*)EEPROM_MMU_STEALTH, SilentModeMenu_MMU);
  1238. }
  1239. #if !defined(DEBUG_DISABLE_FANCHECK) && defined(FANCHECK) && defined(TACH_1) && TACH_1 >-1
  1240. setup_fan_interrupt();
  1241. #endif //DEBUG_DISABLE_FANCHECK
  1242. #ifndef DEBUG_DISABLE_STARTMSGS
  1243. KEEPALIVE_STATE(PAUSED_FOR_USER);
  1244. if (!farm_mode) {
  1245. #if defined(FILAMENT_SENSOR) && defined(FSENSOR_PROBING)
  1246. check_if_fw_is_on_right_printer();
  1247. #endif //defined(FILAMENT_SENSOR) && defined(FSENSOR_PROBING)
  1248. show_fw_version_warnings();
  1249. }
  1250. switch (hw_changed) {
  1251. //if motherboard or printer type was changed inform user as it can indicate flashing wrong firmware version
  1252. //if user confirms with knob, new hw version (printer and/or motherboard) is written to eeprom and message will be not shown next time
  1253. case(0b01):
  1254. lcd_show_fullscreen_message_and_wait_P(_i("Warning: motherboard type changed.")); ////MSG_CHANGED_MOTHERBOARD c=20 r=4
  1255. eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  1256. break;
  1257. case(0b10):
  1258. lcd_show_fullscreen_message_and_wait_P(_i("Warning: printer type changed.")); ////MSG_CHANGED_PRINTER c=20 r=4
  1259. eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  1260. break;
  1261. case(0b11):
  1262. lcd_show_fullscreen_message_and_wait_P(_i("Warning: both printer type and motherboard type changed.")); ////MSG_CHANGED_BOTH c=20 r=4
  1263. eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  1264. eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  1265. break;
  1266. default: break; //no change, show no message
  1267. }
  1268. if (!previous_settings_retrieved) {
  1269. 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
  1270. Config_StoreSettings();
  1271. }
  1272. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) >= 1) {
  1273. lcd_wizard(WizState::Run);
  1274. }
  1275. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) == 0) { //dont show calibration status messages if wizard is currently active
  1276. if (calibration_status() == CALIBRATION_STATUS_ASSEMBLED ||
  1277. calibration_status() == CALIBRATION_STATUS_UNKNOWN ||
  1278. calibration_status() == CALIBRATION_STATUS_XYZ_CALIBRATION) {
  1279. // Reset the babystepping values, so the printer will not move the Z axis up when the babystepping is enabled.
  1280. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  1281. // Show the message.
  1282. lcd_show_fullscreen_message_and_wait_P(_T(MSG_FOLLOW_CALIBRATION_FLOW));
  1283. }
  1284. else if (calibration_status() == CALIBRATION_STATUS_LIVE_ADJUST) {
  1285. // Show the message.
  1286. lcd_show_fullscreen_message_and_wait_P(_T(MSG_BABYSTEP_Z_NOT_SET));
  1287. lcd_update_enable(true);
  1288. }
  1289. else if (calibration_status() == CALIBRATION_STATUS_CALIBRATED && eeprom_read_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE) && calibration_status_pinda() == false) {
  1290. //lcd_show_fullscreen_message_and_wait_P(_i("Temperature calibration has not been run yet"));////MSG_PINDA_NOT_CALIBRATED c=20 r=4
  1291. lcd_update_enable(true);
  1292. }
  1293. else if (calibration_status() == CALIBRATION_STATUS_Z_CALIBRATION) {
  1294. // Show the message.
  1295. lcd_show_fullscreen_message_and_wait_P(_T(MSG_FOLLOW_Z_CALIBRATION_FLOW));
  1296. }
  1297. }
  1298. #if !defined (DEBUG_DISABLE_FORCE_SELFTEST) && defined (TMC2130)
  1299. if (force_selftest_if_fw_version() && calibration_status() < CALIBRATION_STATUS_ASSEMBLED) {
  1300. lcd_show_fullscreen_message_and_wait_P(_i("Selftest will be run to calibrate accurate sensorless rehoming."));////MSG_FORCE_SELFTEST c=20 r=8
  1301. update_current_firmware_version_to_eeprom();
  1302. lcd_selftest();
  1303. }
  1304. #endif //TMC2130 && !DEBUG_DISABLE_FORCE_SELFTEST
  1305. KEEPALIVE_STATE(IN_PROCESS);
  1306. #endif //DEBUG_DISABLE_STARTMSGS
  1307. lcd_update_enable(true);
  1308. lcd_clear();
  1309. lcd_update(2);
  1310. // Store the currently running firmware into an eeprom,
  1311. // so the next time the firmware gets updated, it will know from which version it has been updated.
  1312. update_current_firmware_version_to_eeprom();
  1313. #ifdef TMC2130
  1314. tmc2130_home_origin[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_X_ORIGIN);
  1315. tmc2130_home_bsteps[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_X_BSTEPS);
  1316. tmc2130_home_fsteps[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_X_FSTEPS);
  1317. if (tmc2130_home_origin[X_AXIS] == 0xff) tmc2130_home_origin[X_AXIS] = 0;
  1318. if (tmc2130_home_bsteps[X_AXIS] == 0xff) tmc2130_home_bsteps[X_AXIS] = 48;
  1319. if (tmc2130_home_fsteps[X_AXIS] == 0xff) tmc2130_home_fsteps[X_AXIS] = 48;
  1320. tmc2130_home_origin[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_ORIGIN);
  1321. tmc2130_home_bsteps[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_BSTEPS);
  1322. tmc2130_home_fsteps[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_FSTEPS);
  1323. if (tmc2130_home_origin[Y_AXIS] == 0xff) tmc2130_home_origin[Y_AXIS] = 0;
  1324. if (tmc2130_home_bsteps[Y_AXIS] == 0xff) tmc2130_home_bsteps[Y_AXIS] = 48;
  1325. if (tmc2130_home_fsteps[Y_AXIS] == 0xff) tmc2130_home_fsteps[Y_AXIS] = 48;
  1326. tmc2130_home_enabled = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_ENABLED);
  1327. if (tmc2130_home_enabled == 0xff) tmc2130_home_enabled = 0;
  1328. #endif //TMC2130
  1329. // report crash failures
  1330. fw_crash_init();
  1331. #ifdef UVLO_SUPPORT
  1332. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO) != 0) { //previous print was terminated by UVLO
  1333. /*
  1334. if (!lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_RECOVER_PRINT), false)) recover_print();
  1335. else {
  1336. eeprom_update_byte((uint8_t*)EEPROM_UVLO, 0);
  1337. lcd_update_enable(true);
  1338. lcd_update(2);
  1339. lcd_setstatuspgm(MSG_WELCOME);
  1340. }
  1341. */
  1342. manage_heater(); // Update temperatures
  1343. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1344. 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));
  1345. #endif
  1346. if ( degBed() > ( (float)eeprom_read_byte((uint8_t*)EEPROM_UVLO_TARGET_BED) - AUTOMATIC_UVLO_BED_TEMP_OFFSET) ){
  1347. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1348. puts_P(_N("Automatic recovery!"));
  1349. #endif
  1350. recover_print(1);
  1351. }
  1352. else{
  1353. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1354. puts_P(_N("Normal recovery!"));
  1355. #endif
  1356. if ( lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_RECOVER_PRINT), false) == LCD_LEFT_BUTTON_CHOICE) {
  1357. 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. KEEPALIVE_STATE(NOT_BUSY);
  1372. #ifdef WATCHDOG
  1373. wdt_enable(WDTO_4S);
  1374. #ifdef EMERGENCY_HANDLERS
  1375. WDTCSR |= (1 << WDIE);
  1376. #endif //EMERGENCY_HANDLERS
  1377. #endif //WATCHDOG
  1378. }
  1379. static inline void crash_and_burn(dump_crash_reason reason)
  1380. {
  1381. WRITE(BEEPER, HIGH);
  1382. eeprom_update_byte((uint8_t*)EEPROM_FW_CRASH_FLAG, (uint8_t)reason);
  1383. #ifdef EMERGENCY_DUMP
  1384. xfdump_full_dump_and_reset(reason);
  1385. #elif defined(EMERGENCY_SERIAL_DUMP)
  1386. if(emergency_serial_dump)
  1387. serial_dump_and_reset(reason);
  1388. #endif
  1389. softReset();
  1390. }
  1391. #ifdef EMERGENCY_HANDLERS
  1392. #ifdef WATCHDOG
  1393. ISR(WDT_vect)
  1394. {
  1395. crash_and_burn(dump_crash_reason::watchdog);
  1396. }
  1397. #endif
  1398. ISR(BADISR_vect)
  1399. {
  1400. crash_and_burn(dump_crash_reason::bad_isr);
  1401. }
  1402. #endif //EMERGENCY_HANDLERS
  1403. void stack_error() {
  1404. crash_and_burn(dump_crash_reason::stack_error);
  1405. }
  1406. /**
  1407. * Output autoreport values according to features requested in M155
  1408. */
  1409. #if defined(AUTO_REPORT)
  1410. void host_autoreport()
  1411. {
  1412. if (autoReportFeatures.TimerExpired())
  1413. {
  1414. if(autoReportFeatures.Temp()){
  1415. gcode_M105(active_extruder);
  1416. }
  1417. if(autoReportFeatures.Pos()){
  1418. gcode_M114();
  1419. }
  1420. #if defined(AUTO_REPORT) && (defined(FANCHECK) && (((defined(TACH_0) && (TACH_0 >-1)) || (defined(TACH_1) && (TACH_1 > -1)))))
  1421. if(autoReportFeatures.Fans()){
  1422. gcode_M123();
  1423. }
  1424. #endif //AUTO_REPORT and (FANCHECK and TACH_0 or TACH_1)
  1425. autoReportFeatures.TimerStart();
  1426. }
  1427. }
  1428. #endif //AUTO_REPORT
  1429. /**
  1430. * Output a "busy" message at regular intervals
  1431. * while the machine is not accepting commands.
  1432. */
  1433. void host_keepalive() {
  1434. #ifndef HOST_KEEPALIVE_FEATURE
  1435. return;
  1436. #endif //HOST_KEEPALIVE_FEATURE
  1437. if (farm_mode) return;
  1438. long ms = _millis();
  1439. if (host_keepalive_interval && busy_state != NOT_BUSY) {
  1440. if ((ms - prev_busy_signal_ms) < (long)(1000L * host_keepalive_interval)) return;
  1441. switch (busy_state) {
  1442. case IN_HANDLER:
  1443. case IN_PROCESS:
  1444. SERIAL_ECHO_START;
  1445. SERIAL_ECHOLNPGM("busy: processing");
  1446. break;
  1447. case PAUSED_FOR_USER:
  1448. SERIAL_ECHO_START;
  1449. SERIAL_ECHOLNPGM("busy: paused for user");
  1450. break;
  1451. case PAUSED_FOR_INPUT:
  1452. SERIAL_ECHO_START;
  1453. SERIAL_ECHOLNPGM("busy: paused for input");
  1454. break;
  1455. default:
  1456. break;
  1457. }
  1458. }
  1459. prev_busy_signal_ms = ms;
  1460. }
  1461. // The loop() function is called in an endless loop by the Arduino framework from the default main() routine.
  1462. // Before loop(), the setup() function is called by the main() routine.
  1463. void loop()
  1464. {
  1465. // Reset a previously aborted command, we can now start processing motion again
  1466. planner_aborted = false;
  1467. if(Stopped) {
  1468. // Currently Stopped (possibly due to an error) and not accepting new serial commands.
  1469. // Signal to the host that we're currently busy waiting for supervision.
  1470. KEEPALIVE_STATE(PAUSED_FOR_USER);
  1471. } else {
  1472. // Printer is available for processing, reset state
  1473. KEEPALIVE_STATE(NOT_BUSY);
  1474. }
  1475. if (isPrintPaused && saved_printing_type == PRINTING_TYPE_USB) { //keep believing that usb is being printed. Prevents accessing dangerous menus while pausing.
  1476. usb_timer.start();
  1477. }
  1478. else if (usb_timer.expired(10000)) { //just need to check if it expired. Nothing else is needed to be done.
  1479. ;
  1480. }
  1481. #ifdef PRUSA_M28
  1482. if (prusa_sd_card_upload)
  1483. {
  1484. //we read byte-by byte
  1485. serial_read_stream();
  1486. }
  1487. else
  1488. #endif
  1489. {
  1490. get_command();
  1491. #ifdef SDSUPPORT
  1492. card.checkautostart(false);
  1493. #endif
  1494. if(buflen)
  1495. {
  1496. cmdbuffer_front_already_processed = false;
  1497. #ifdef SDSUPPORT
  1498. if(card.saving)
  1499. {
  1500. // Saving a G-code file onto an SD-card is in progress.
  1501. // Saving starts with M28, saving until M29 is seen.
  1502. if(strstr_P(CMDBUFFER_CURRENT_STRING, PSTR("M29")) == NULL) {
  1503. card.write_command(CMDBUFFER_CURRENT_STRING);
  1504. if(card.logging)
  1505. process_commands();
  1506. else
  1507. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  1508. } else {
  1509. card.closefile();
  1510. SERIAL_PROTOCOLLNRPGM(MSG_FILE_SAVED);
  1511. }
  1512. } else {
  1513. process_commands();
  1514. }
  1515. #else
  1516. process_commands();
  1517. #endif //SDSUPPORT
  1518. if (! cmdbuffer_front_already_processed && buflen)
  1519. {
  1520. // ptr points to the start of the block currently being processed.
  1521. // The first character in the block is the block type.
  1522. char *ptr = cmdbuffer + bufindr;
  1523. if (*ptr == CMDBUFFER_CURRENT_TYPE_SDCARD) {
  1524. // To support power panic, move the lenght of the command on the SD card to a planner buffer.
  1525. union {
  1526. struct {
  1527. char lo;
  1528. char hi;
  1529. } lohi;
  1530. uint16_t value;
  1531. } sdlen;
  1532. sdlen.value = 0;
  1533. {
  1534. // This block locks the interrupts globally for 3.25 us,
  1535. // which corresponds to a maximum repeat frequency of 307.69 kHz.
  1536. // This blocking is safe in the context of a 10kHz stepper driver interrupt
  1537. // or a 115200 Bd serial line receive interrupt, which will not trigger faster than 12kHz.
  1538. cli();
  1539. // Reset the command to something, which will be ignored by the power panic routine,
  1540. // so this buffer length will not be counted twice.
  1541. *ptr ++ = CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED;
  1542. // Extract the current buffer length.
  1543. sdlen.lohi.lo = *ptr ++;
  1544. sdlen.lohi.hi = *ptr;
  1545. // and pass it to the planner queue.
  1546. planner_add_sd_length(sdlen.value);
  1547. sei();
  1548. }
  1549. }
  1550. else if((*ptr == CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR) && !IS_SD_PRINTING){
  1551. cli();
  1552. *ptr ++ = CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED;
  1553. // and one for each command to previous block in the planner queue.
  1554. planner_add_sd_length(1);
  1555. sei();
  1556. }
  1557. // Now it is safe to release the already processed command block. If interrupted by the power panic now,
  1558. // this block's SD card length will not be counted twice as its command type has been replaced
  1559. // by CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED.
  1560. cmdqueue_pop_front();
  1561. }
  1562. host_keepalive();
  1563. }
  1564. }
  1565. //check heater every n milliseconds
  1566. manage_heater();
  1567. manage_inactivity(isPrintPaused);
  1568. checkHitEndstops();
  1569. lcd_update(0);
  1570. #ifdef TMC2130
  1571. tmc2130_check_overtemp();
  1572. if (tmc2130_sg_crash)
  1573. {
  1574. uint8_t crash = tmc2130_sg_crash;
  1575. tmc2130_sg_crash = 0;
  1576. // crashdet_stop_and_save_print();
  1577. switch (crash)
  1578. {
  1579. case 1: enquecommand_P((PSTR("CRASH_DETECTEDX"))); break;
  1580. case 2: enquecommand_P((PSTR("CRASH_DETECTEDY"))); break;
  1581. case 3: enquecommand_P((PSTR("CRASH_DETECTEDXY"))); break;
  1582. }
  1583. }
  1584. #endif //TMC2130
  1585. MMU2::mmu2.mmu_loop();
  1586. }
  1587. #define DEFINE_PGM_READ_ANY(type, reader) \
  1588. static inline type pgm_read_any(const type *p) \
  1589. { return pgm_read_##reader##_near(p); }
  1590. DEFINE_PGM_READ_ANY(float, float);
  1591. DEFINE_PGM_READ_ANY(signed char, byte);
  1592. #define XYZ_CONSTS_FROM_CONFIG(type, array, CONFIG) \
  1593. static const PROGMEM type array##_P[3] = \
  1594. { X_##CONFIG, Y_##CONFIG, Z_##CONFIG }; \
  1595. static inline type array(uint8_t axis) \
  1596. { return pgm_read_any(&array##_P[axis]); } \
  1597. type array##_ext(uint8_t axis) \
  1598. { return pgm_read_any(&array##_P[axis]); }
  1599. XYZ_CONSTS_FROM_CONFIG(float, base_min_pos, MIN_POS);
  1600. XYZ_CONSTS_FROM_CONFIG(float, base_max_pos, MAX_POS);
  1601. XYZ_CONSTS_FROM_CONFIG(float, base_home_pos, HOME_POS);
  1602. XYZ_CONSTS_FROM_CONFIG(float, max_length, MAX_LENGTH);
  1603. XYZ_CONSTS_FROM_CONFIG(float, home_retract_mm, HOME_RETRACT_MM);
  1604. XYZ_CONSTS_FROM_CONFIG(signed char, home_dir, HOME_DIR);
  1605. static void axis_is_at_home(uint8_t axis) {
  1606. current_position[axis] = base_home_pos(axis) + cs.add_homing[axis];
  1607. min_pos[axis] = base_min_pos(axis) + cs.add_homing[axis];
  1608. max_pos[axis] = base_max_pos(axis) + cs.add_homing[axis];
  1609. }
  1610. //! @return original feedmultiply
  1611. static int setup_for_endstop_move(bool enable_endstops_now = true) {
  1612. saved_feedrate = feedrate;
  1613. int l_feedmultiply = feedmultiply;
  1614. feedmultiply = 100;
  1615. previous_millis_cmd.start();
  1616. enable_endstops(enable_endstops_now);
  1617. return l_feedmultiply;
  1618. }
  1619. //! @param original_feedmultiply feedmultiply to restore
  1620. static void clean_up_after_endstop_move(int original_feedmultiply) {
  1621. #ifdef ENDSTOPS_ONLY_FOR_HOMING
  1622. enable_endstops(false);
  1623. #endif
  1624. feedrate = saved_feedrate;
  1625. feedmultiply = original_feedmultiply;
  1626. previous_millis_cmd.start();
  1627. }
  1628. #ifdef ENABLE_AUTO_BED_LEVELING
  1629. #ifdef AUTO_BED_LEVELING_GRID
  1630. static void set_bed_level_equation_lsq(double *plane_equation_coefficients)
  1631. {
  1632. vector_3 planeNormal = vector_3(-plane_equation_coefficients[0], -plane_equation_coefficients[1], 1);
  1633. planeNormal.debug("planeNormal");
  1634. plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1635. //bedLevel.debug("bedLevel");
  1636. //plan_bed_level_matrix.debug("bed level before");
  1637. //vector_3 uncorrected_position = plan_get_position_mm();
  1638. //uncorrected_position.debug("position before");
  1639. vector_3 corrected_position = plan_get_position();
  1640. // corrected_position.debug("position after");
  1641. current_position[X_AXIS] = corrected_position.x;
  1642. current_position[Y_AXIS] = corrected_position.y;
  1643. current_position[Z_AXIS] = corrected_position.z;
  1644. // put the bed at 0 so we don't go below it.
  1645. current_position[Z_AXIS] = cs.zprobe_zoffset; // in the lsq we reach here after raising the extruder due to the loop structure
  1646. plan_set_position_curposXYZE();
  1647. }
  1648. #else // not AUTO_BED_LEVELING_GRID
  1649. static void set_bed_level_equation_3pts(float z_at_pt_1, float z_at_pt_2, float z_at_pt_3) {
  1650. plan_bed_level_matrix.set_to_identity();
  1651. vector_3 pt1 = vector_3(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, z_at_pt_1);
  1652. vector_3 pt2 = vector_3(ABL_PROBE_PT_2_X, ABL_PROBE_PT_2_Y, z_at_pt_2);
  1653. vector_3 pt3 = vector_3(ABL_PROBE_PT_3_X, ABL_PROBE_PT_3_Y, z_at_pt_3);
  1654. vector_3 from_2_to_1 = (pt1 - pt2).get_normal();
  1655. vector_3 from_2_to_3 = (pt3 - pt2).get_normal();
  1656. vector_3 planeNormal = vector_3::cross(from_2_to_1, from_2_to_3).get_normal();
  1657. planeNormal = vector_3(planeNormal.x, planeNormal.y, abs(planeNormal.z));
  1658. plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1659. vector_3 corrected_position = plan_get_position();
  1660. current_position[X_AXIS] = corrected_position.x;
  1661. current_position[Y_AXIS] = corrected_position.y;
  1662. current_position[Z_AXIS] = corrected_position.z;
  1663. // put the bed at 0 so we don't go below it.
  1664. current_position[Z_AXIS] = cs.zprobe_zoffset;
  1665. plan_set_position_curposXYZE();
  1666. }
  1667. #endif // AUTO_BED_LEVELING_GRID
  1668. static void run_z_probe() {
  1669. plan_bed_level_matrix.set_to_identity();
  1670. feedrate = homing_feedrate[Z_AXIS];
  1671. // move down until you find the bed
  1672. float zPosition = -10;
  1673. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1674. st_synchronize();
  1675. // we have to let the planner know where we are right now as it is not where we said to go.
  1676. zPosition = st_get_position_mm(Z_AXIS);
  1677. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS]);
  1678. // move up the retract distance
  1679. zPosition += home_retract_mm(Z_AXIS);
  1680. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1681. st_synchronize();
  1682. // move back down slowly to find bed
  1683. feedrate = homing_feedrate[Z_AXIS]/4;
  1684. zPosition -= home_retract_mm(Z_AXIS) * 2;
  1685. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1686. st_synchronize();
  1687. current_position[Z_AXIS] = st_get_position_mm(Z_AXIS);
  1688. // make sure the planner knows where we are as it may be a bit different than we last said to move to
  1689. plan_set_position_curposXYZE();
  1690. }
  1691. static void do_blocking_move_to(float x, float y, float z) {
  1692. float oldFeedRate = feedrate;
  1693. feedrate = homing_feedrate[Z_AXIS];
  1694. current_position[Z_AXIS] = z;
  1695. plan_buffer_line_curposXYZE(feedrate/60, active_extruder);
  1696. st_synchronize();
  1697. feedrate = XY_TRAVEL_SPEED;
  1698. current_position[X_AXIS] = x;
  1699. current_position[Y_AXIS] = y;
  1700. plan_buffer_line_curposXYZE(feedrate/60, active_extruder);
  1701. st_synchronize();
  1702. feedrate = oldFeedRate;
  1703. }
  1704. static void do_blocking_move_relative(float offset_x, float offset_y, float offset_z) {
  1705. do_blocking_move_to(current_position[X_AXIS] + offset_x, current_position[Y_AXIS] + offset_y, current_position[Z_AXIS] + offset_z);
  1706. }
  1707. /// Probe bed height at position (x,y), returns the measured z value
  1708. static float probe_pt(float x, float y, float z_before) {
  1709. // move to right place
  1710. do_blocking_move_to(current_position[X_AXIS], current_position[Y_AXIS], z_before);
  1711. do_blocking_move_to(x - X_PROBE_OFFSET_FROM_EXTRUDER, y - Y_PROBE_OFFSET_FROM_EXTRUDER, current_position[Z_AXIS]);
  1712. run_z_probe();
  1713. float measured_z = current_position[Z_AXIS];
  1714. SERIAL_PROTOCOLRPGM(_T(MSG_BED));
  1715. SERIAL_PROTOCOLPGM(" x: ");
  1716. SERIAL_PROTOCOL(x);
  1717. SERIAL_PROTOCOLPGM(" y: ");
  1718. SERIAL_PROTOCOL(y);
  1719. SERIAL_PROTOCOLPGM(" z: ");
  1720. SERIAL_PROTOCOL(measured_z);
  1721. SERIAL_PROTOCOLPGM("\n");
  1722. return measured_z;
  1723. }
  1724. #endif // #ifdef ENABLE_AUTO_BED_LEVELING
  1725. #ifdef LIN_ADVANCE
  1726. /**
  1727. * M900: Set and/or Get advance K factor
  1728. *
  1729. * K<factor> Set advance K factor
  1730. */
  1731. inline void gcode_M900() {
  1732. float newK = code_seen('K') ? code_value_float() : -2;
  1733. #ifdef LA_NOCOMPAT
  1734. if (newK >= 0 && newK < LA_K_MAX)
  1735. extruder_advance_K = newK;
  1736. else
  1737. SERIAL_ECHOLNPGM("K out of allowed range!");
  1738. #else
  1739. if (newK == 0)
  1740. {
  1741. extruder_advance_K = 0;
  1742. la10c_reset();
  1743. }
  1744. else
  1745. {
  1746. newK = la10c_value(newK);
  1747. if (newK < 0)
  1748. SERIAL_ECHOLNPGM("K out of allowed range!");
  1749. else
  1750. extruder_advance_K = newK;
  1751. }
  1752. #endif
  1753. SERIAL_ECHO_START;
  1754. SERIAL_ECHOPGM("Advance K=");
  1755. SERIAL_ECHOLN(extruder_advance_K);
  1756. }
  1757. #endif // LIN_ADVANCE
  1758. bool check_commands() {
  1759. bool end_command_found = false;
  1760. while (buflen)
  1761. {
  1762. if ((code_seen_P(PSTR("M84"))) || (code_seen_P(PSTR("M 84")))) end_command_found = true;
  1763. if (!cmdbuffer_front_already_processed)
  1764. cmdqueue_pop_front();
  1765. cmdbuffer_front_already_processed = false;
  1766. }
  1767. return end_command_found;
  1768. }
  1769. /// @brief Safely move Z-axis by distance delta (mm)
  1770. /// @param delta travel distance in mm
  1771. /// @returns The actual travel distance in mm. Endstop may limit the requested move.
  1772. float raise_z(float delta)
  1773. {
  1774. float travel_z = current_position[Z_AXIS];
  1775. // Prepare to move Z axis
  1776. current_position[Z_AXIS] += delta;
  1777. #if defined(Z_MIN_PIN) && (Z_MIN_PIN > -1) && !defined(DEBUG_DISABLE_ZMINLIMIT)
  1778. bool z_min_endstop = (READ(Z_MIN_PIN) != Z_MIN_ENDSTOP_INVERTING);
  1779. #else
  1780. bool z_min_endstop = false;
  1781. #endif
  1782. if (axis_known_position[Z_AXIS] || z_min_endstop)
  1783. {
  1784. // current position is known or very low, it's safe to raise Z
  1785. clamp_to_software_endstops(current_position);
  1786. plan_buffer_line_curposXYZE(max_feedrate[Z_AXIS]);
  1787. st_synchronize();
  1788. // Get the final travel distance
  1789. travel_z = current_position[Z_AXIS] - travel_z;
  1790. } else {
  1791. // ensure Z is powered in normal mode to overcome initial load
  1792. enable_z();
  1793. st_synchronize();
  1794. // rely on crashguard to limit damage
  1795. bool z_endstop_enabled = enable_z_endstop(true);
  1796. #ifdef TMC2130
  1797. tmc2130_home_enter(Z_AXIS_MASK);
  1798. #endif //TMC2130
  1799. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 60);
  1800. st_synchronize();
  1801. // Get the final travel distance
  1802. travel_z = st_get_position_mm(Z_AXIS) - travel_z;
  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. return travel_z;
  1815. }
  1816. // raise_z_above: slowly raise Z to the requested height
  1817. //
  1818. // contrarily to a simple move, this function will carefully plan a move
  1819. // when the current Z position is unknown. In such cases, stallguard is
  1820. // enabled and will prevent prolonged pushing against the Z tops
  1821. void raise_z_above(float target)
  1822. {
  1823. if (current_position[Z_AXIS] >= target)
  1824. return;
  1825. // Use absolute value in case the current position is unknown
  1826. raise_z(fabs(current_position[Z_AXIS] - target));
  1827. }
  1828. #ifdef TMC2130
  1829. bool calibrate_z_auto()
  1830. {
  1831. //lcd_display_message_fullscreen_P(_T(MSG_CALIBRATE_Z_AUTO));
  1832. lcd_clear();
  1833. lcd_puts_at_P(0, 1, _T(MSG_CALIBRATE_Z_AUTO));
  1834. bool endstops_enabled = enable_endstops(true);
  1835. int axis_up_dir = -home_dir(Z_AXIS);
  1836. tmc2130_home_enter(Z_AXIS_MASK);
  1837. current_position[Z_AXIS] = 0;
  1838. plan_set_position_curposXYZE();
  1839. set_destination_to_current();
  1840. destination[Z_AXIS] += (1.1 * max_length(Z_AXIS) * axis_up_dir);
  1841. feedrate = homing_feedrate[Z_AXIS];
  1842. plan_buffer_line_destinationXYZE(feedrate / 60);
  1843. st_synchronize();
  1844. // current_position[axis] = 0;
  1845. // plan_set_position_curposXYZE();
  1846. tmc2130_home_exit();
  1847. current_position[Z_AXIS] = 0;
  1848. plan_set_position_curposXYZE();
  1849. set_destination_to_current();
  1850. destination[Z_AXIS] += 10 * axis_up_dir; //10mm up
  1851. feedrate = homing_feedrate[Z_AXIS] / 2;
  1852. plan_buffer_line_destinationXYZE(feedrate / 60);
  1853. st_synchronize();
  1854. enable_endstops(endstops_enabled);
  1855. if (PRINTER_TYPE == PRINTER_MK3) {
  1856. current_position[Z_AXIS] = Z_MAX_POS + 2.0;
  1857. }
  1858. else {
  1859. current_position[Z_AXIS] = Z_MAX_POS + 9.0;
  1860. }
  1861. plan_set_position_curposXYZE();
  1862. return true;
  1863. }
  1864. #endif //TMC2130
  1865. #ifdef TMC2130
  1866. static void check_Z_crash(void)
  1867. {
  1868. if (!READ(Z_TMC2130_DIAG)) { //Z crash
  1869. FORCE_HIGH_POWER_END;
  1870. current_position[Z_AXIS] = 0;
  1871. plan_set_position_curposXYZE();
  1872. current_position[Z_AXIS] += MESH_HOME_Z_SEARCH;
  1873. plan_buffer_line_curposXYZE(max_feedrate[Z_AXIS]);
  1874. st_synchronize();
  1875. kill(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  1876. }
  1877. }
  1878. #endif //TMC2130
  1879. #ifdef TMC2130
  1880. void homeaxis(uint8_t axis, uint8_t cnt, uint8_t* pstep)
  1881. #else
  1882. void homeaxis(uint8_t axis, uint8_t cnt)
  1883. #endif //TMC2130
  1884. {
  1885. bool endstops_enabled = enable_endstops(true); //RP: endstops should be allways enabled durring homing
  1886. #define HOMEAXIS_DO(LETTER) \
  1887. ((LETTER##_MIN_PIN > -1 && LETTER##_HOME_DIR==-1) || (LETTER##_MAX_PIN > -1 && LETTER##_HOME_DIR==1))
  1888. if ((axis==X_AXIS)?HOMEAXIS_DO(X):(axis==Y_AXIS)?HOMEAXIS_DO(Y):0)
  1889. {
  1890. int axis_home_dir = home_dir(axis);
  1891. feedrate = homing_feedrate[axis];
  1892. #ifdef TMC2130
  1893. tmc2130_home_enter(X_AXIS_MASK << axis);
  1894. #endif //TMC2130
  1895. // Move away a bit, so that the print head does not touch the end position,
  1896. // and the following movement to endstop has a chance to achieve the required velocity
  1897. // for the stall guard to work.
  1898. current_position[axis] = 0;
  1899. plan_set_position_curposXYZE();
  1900. set_destination_to_current();
  1901. // destination[axis] = 11.f;
  1902. destination[axis] = -3.f * axis_home_dir;
  1903. plan_buffer_line_destinationXYZE(feedrate/60);
  1904. st_synchronize();
  1905. // Move away from the possible collision with opposite endstop with the collision detection disabled.
  1906. endstops_hit_on_purpose();
  1907. enable_endstops(false);
  1908. current_position[axis] = 0;
  1909. plan_set_position_curposXYZE();
  1910. destination[axis] = 1. * axis_home_dir;
  1911. plan_buffer_line_destinationXYZE(feedrate/60);
  1912. st_synchronize();
  1913. // Now continue to move up to the left end stop with the collision detection enabled.
  1914. enable_endstops(true);
  1915. destination[axis] = 1.1 * axis_home_dir * max_length(axis);
  1916. plan_buffer_line_destinationXYZE(feedrate/60);
  1917. st_synchronize();
  1918. for (uint8_t i = 0; i < cnt; i++)
  1919. {
  1920. // Move away from the collision to a known distance from the left end stop with the collision detection disabled.
  1921. endstops_hit_on_purpose();
  1922. enable_endstops(false);
  1923. current_position[axis] = 0;
  1924. plan_set_position_curposXYZE();
  1925. destination[axis] = -10.f * axis_home_dir;
  1926. plan_buffer_line_destinationXYZE(feedrate/60);
  1927. st_synchronize();
  1928. endstops_hit_on_purpose();
  1929. // Now move left up to the collision, this time with a repeatable velocity.
  1930. enable_endstops(true);
  1931. destination[axis] = 11.f * axis_home_dir;
  1932. #ifdef TMC2130
  1933. feedrate = homing_feedrate[axis];
  1934. #else //TMC2130
  1935. feedrate = homing_feedrate[axis] / 2;
  1936. #endif //TMC2130
  1937. plan_buffer_line_destinationXYZE(feedrate/60);
  1938. st_synchronize();
  1939. #ifdef TMC2130
  1940. uint16_t mscnt = tmc2130_rd_MSCNT(axis);
  1941. if (pstep) pstep[i] = mscnt >> 4;
  1942. printf_P(PSTR("%3d step=%2d mscnt=%4d\n"), i, mscnt >> 4, mscnt);
  1943. #endif //TMC2130
  1944. }
  1945. endstops_hit_on_purpose();
  1946. enable_endstops(false);
  1947. #ifdef TMC2130
  1948. uint8_t orig = tmc2130_home_origin[axis];
  1949. uint8_t back = tmc2130_home_bsteps[axis];
  1950. if (tmc2130_home_enabled && (orig <= 63))
  1951. {
  1952. tmc2130_goto_step(axis, orig, 2, 1000, tmc2130_get_res(axis));
  1953. if (back > 0)
  1954. tmc2130_do_steps(axis, back, -axis_home_dir, 1000);
  1955. }
  1956. else
  1957. tmc2130_do_steps(axis, 8, -axis_home_dir, 1000);
  1958. tmc2130_home_exit();
  1959. #endif //TMC2130
  1960. axis_is_at_home(axis);
  1961. axis_known_position[axis] = true;
  1962. // Move from minimum
  1963. #ifdef TMC2130
  1964. float dist = - axis_home_dir * 0.01f * tmc2130_home_fsteps[axis];
  1965. #else //TMC2130
  1966. float dist = - axis_home_dir * 0.01f * 64;
  1967. #endif //TMC2130
  1968. current_position[axis] -= dist;
  1969. plan_set_position_curposXYZE();
  1970. current_position[axis] += dist;
  1971. destination[axis] = current_position[axis];
  1972. plan_buffer_line_destinationXYZE(0.5f*feedrate/60);
  1973. st_synchronize();
  1974. feedrate = 0.0;
  1975. }
  1976. else if ((axis==Z_AXIS)?HOMEAXIS_DO(Z):0)
  1977. {
  1978. #ifdef TMC2130
  1979. FORCE_HIGH_POWER_START;
  1980. #endif
  1981. int axis_home_dir = home_dir(axis);
  1982. current_position[axis] = 0;
  1983. plan_set_position_curposXYZE();
  1984. destination[axis] = 1.5 * max_length(axis) * axis_home_dir;
  1985. feedrate = homing_feedrate[axis];
  1986. plan_buffer_line_destinationXYZE(feedrate/60);
  1987. st_synchronize();
  1988. #ifdef TMC2130
  1989. check_Z_crash();
  1990. #endif //TMC2130
  1991. current_position[axis] = 0;
  1992. plan_set_position_curposXYZE();
  1993. destination[axis] = -home_retract_mm(axis) * axis_home_dir;
  1994. plan_buffer_line_destinationXYZE(feedrate/60);
  1995. st_synchronize();
  1996. destination[axis] = 2*home_retract_mm(axis) * axis_home_dir;
  1997. feedrate = homing_feedrate[axis]/2 ;
  1998. plan_buffer_line_destinationXYZE(feedrate/60);
  1999. st_synchronize();
  2000. #ifdef TMC2130
  2001. check_Z_crash();
  2002. #endif //TMC2130
  2003. axis_is_at_home(axis);
  2004. destination[axis] = current_position[axis];
  2005. feedrate = 0.0;
  2006. endstops_hit_on_purpose();
  2007. axis_known_position[axis] = true;
  2008. #ifdef TMC2130
  2009. FORCE_HIGH_POWER_END;
  2010. #endif
  2011. }
  2012. enable_endstops(endstops_enabled);
  2013. }
  2014. /**/
  2015. void home_xy()
  2016. {
  2017. set_destination_to_current();
  2018. homeaxis(X_AXIS);
  2019. homeaxis(Y_AXIS);
  2020. plan_set_position_curposXYZE();
  2021. endstops_hit_on_purpose();
  2022. }
  2023. void refresh_cmd_timeout(void)
  2024. {
  2025. previous_millis_cmd.start();
  2026. }
  2027. #ifdef FWRETRACT
  2028. void retract(bool retracting, bool swapretract = false) {
  2029. // Perform FW retraction, just if needed, but behave as if the move has never took place in
  2030. // order to keep E/Z coordinates unchanged. This is done by manipulating the internal planner
  2031. // position, which requires a sync
  2032. if(retracting && !retracted[active_extruder]) {
  2033. st_synchronize();
  2034. set_destination_to_current();
  2035. current_position[E_AXIS]+=(swapretract?retract_length_swap:cs.retract_length)*float(extrudemultiply)*0.01f;
  2036. plan_set_e_position(current_position[E_AXIS]);
  2037. float oldFeedrate = feedrate;
  2038. feedrate=cs.retract_feedrate*60;
  2039. retracted[active_extruder]=true;
  2040. prepare_move();
  2041. if(cs.retract_zlift) {
  2042. st_synchronize();
  2043. current_position[Z_AXIS]-=cs.retract_zlift;
  2044. plan_set_position_curposXYZE();
  2045. prepare_move();
  2046. }
  2047. feedrate = oldFeedrate;
  2048. } else if(!retracting && retracted[active_extruder]) {
  2049. st_synchronize();
  2050. set_destination_to_current();
  2051. float oldFeedrate = feedrate;
  2052. feedrate=cs.retract_recover_feedrate*60;
  2053. if(cs.retract_zlift) {
  2054. current_position[Z_AXIS]+=cs.retract_zlift;
  2055. plan_set_position_curposXYZE();
  2056. prepare_move();
  2057. st_synchronize();
  2058. }
  2059. current_position[E_AXIS]-=(swapretract?(retract_length_swap+retract_recover_length_swap):(cs.retract_length+cs.retract_recover_length))*float(extrudemultiply)*0.01f;
  2060. plan_set_e_position(current_position[E_AXIS]);
  2061. retracted[active_extruder]=false;
  2062. prepare_move();
  2063. feedrate = oldFeedrate;
  2064. }
  2065. } //retract
  2066. #endif //FWRETRACT
  2067. #ifdef TMC2130
  2068. void force_high_power_mode(bool start_high_power_section) {
  2069. #ifdef PSU_Delta
  2070. if (start_high_power_section == true) enable_force_z();
  2071. #endif //PSU_Delta
  2072. uint8_t silent;
  2073. silent = eeprom_read_byte((uint8_t*)EEPROM_SILENT);
  2074. if (silent == 1) {
  2075. //we are in silent mode, set to normal mode to enable crash detection
  2076. // Wait for the planner queue to drain and for the stepper timer routine to reach an idle state.
  2077. st_synchronize();
  2078. cli();
  2079. tmc2130_mode = (start_high_power_section == true) ? TMC2130_MODE_NORMAL : TMC2130_MODE_SILENT;
  2080. update_mode_profile();
  2081. tmc2130_init(TMCInitParams(FarmOrUserECool()));
  2082. // We may have missed a stepper timer interrupt due to the time spent in the tmc2130_init() routine.
  2083. // Be safe than sorry, reset the stepper timer before re-enabling interrupts.
  2084. st_reset_timer();
  2085. sei();
  2086. }
  2087. }
  2088. #endif //TMC2130
  2089. void gcode_M105(uint8_t extruder)
  2090. {
  2091. #if defined(TEMP_0_PIN) && TEMP_0_PIN > -1
  2092. SERIAL_PROTOCOLPGM("T:");
  2093. SERIAL_PROTOCOL_F(degHotend(extruder),1);
  2094. SERIAL_PROTOCOLPGM(" /");
  2095. SERIAL_PROTOCOL_F(degTargetHotend(extruder),1);
  2096. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  2097. SERIAL_PROTOCOLPGM(" B:");
  2098. SERIAL_PROTOCOL_F(degBed(),1);
  2099. SERIAL_PROTOCOLPGM(" /");
  2100. SERIAL_PROTOCOL_F(degTargetBed(),1);
  2101. #endif //TEMP_BED_PIN
  2102. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  2103. SERIAL_PROTOCOLPGM(" T");
  2104. SERIAL_PROTOCOL(cur_extruder);
  2105. SERIAL_PROTOCOL(':');
  2106. SERIAL_PROTOCOL_F(degHotend(cur_extruder),1);
  2107. SERIAL_PROTOCOLPGM(" /");
  2108. SERIAL_PROTOCOL_F(degTargetHotend(cur_extruder),1);
  2109. }
  2110. #else
  2111. SERIAL_ERROR_START;
  2112. SERIAL_ERRORLNRPGM(_n("No thermistors - no temperature"));////MSG_ERR_NO_THERMISTORS
  2113. #endif
  2114. SERIAL_PROTOCOLPGM(" @:");
  2115. #ifdef EXTRUDER_WATTS
  2116. SERIAL_PROTOCOL((EXTRUDER_WATTS * getHeaterPower(tmp_extruder))/127);
  2117. SERIAL_PROTOCOLPGM("W");
  2118. #else
  2119. SERIAL_PROTOCOL(getHeaterPower(extruder));
  2120. #endif
  2121. SERIAL_PROTOCOLPGM(" B@:");
  2122. #ifdef BED_WATTS
  2123. SERIAL_PROTOCOL((BED_WATTS * getHeaterPower(-1))/127);
  2124. SERIAL_PROTOCOLPGM("W");
  2125. #else
  2126. SERIAL_PROTOCOL(getHeaterPower(-1));
  2127. #endif
  2128. #ifdef PINDA_THERMISTOR
  2129. SERIAL_PROTOCOLPGM(" P:");
  2130. SERIAL_PROTOCOL_F(current_temperature_pinda,1);
  2131. #endif //PINDA_THERMISTOR
  2132. #ifdef AMBIENT_THERMISTOR
  2133. SERIAL_PROTOCOLPGM(" A:");
  2134. SERIAL_PROTOCOL_F(current_temperature_ambient,1);
  2135. #endif //AMBIENT_THERMISTOR
  2136. #ifdef SHOW_TEMP_ADC_VALUES
  2137. {
  2138. float raw = 0.0;
  2139. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  2140. SERIAL_PROTOCOLPGM(" ADC B:");
  2141. SERIAL_PROTOCOL_F(degBed(),1);
  2142. SERIAL_PROTOCOLPGM("C->");
  2143. raw = rawBedTemp();
  2144. SERIAL_PROTOCOL_F(raw/OVERSAMPLENR,5);
  2145. SERIAL_PROTOCOLPGM(" Rb->");
  2146. SERIAL_PROTOCOL_F(100 * (1 + (PtA * (raw/OVERSAMPLENR)) + (PtB * sq((raw/OVERSAMPLENR)))), 5);
  2147. SERIAL_PROTOCOLPGM(" Rxb->");
  2148. SERIAL_PROTOCOL_F(raw, 5);
  2149. #endif
  2150. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  2151. SERIAL_PROTOCOLPGM(" T");
  2152. SERIAL_PROTOCOL(cur_extruder);
  2153. SERIAL_PROTOCOLPGM(":");
  2154. SERIAL_PROTOCOL_F(degHotend(cur_extruder),1);
  2155. SERIAL_PROTOCOLPGM("C->");
  2156. raw = rawHotendTemp(cur_extruder);
  2157. SERIAL_PROTOCOL_F(raw/OVERSAMPLENR,5);
  2158. SERIAL_PROTOCOLPGM(" Rt");
  2159. SERIAL_PROTOCOL(cur_extruder);
  2160. SERIAL_PROTOCOLPGM("->");
  2161. SERIAL_PROTOCOL_F(100 * (1 + (PtA * (raw/OVERSAMPLENR)) + (PtB * sq((raw/OVERSAMPLENR)))), 5);
  2162. SERIAL_PROTOCOLPGM(" Rx");
  2163. SERIAL_PROTOCOL(cur_extruder);
  2164. SERIAL_PROTOCOLPGM("->");
  2165. SERIAL_PROTOCOL_F(raw, 5);
  2166. }
  2167. }
  2168. #endif
  2169. SERIAL_PROTOCOLLN();
  2170. }
  2171. #ifdef TMC2130
  2172. 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)
  2173. #else
  2174. 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)
  2175. #endif //TMC2130
  2176. {
  2177. // Flag for the display update routine and to disable the print cancelation during homing.
  2178. st_synchronize();
  2179. homing_flag = true;
  2180. #if 0
  2181. SERIAL_ECHOPGM("G28, initial "); print_world_coordinates();
  2182. SERIAL_ECHOPGM("G28, initial "); print_physical_coordinates();
  2183. #endif
  2184. // Which axes should be homed?
  2185. bool home_x = home_x_axis;
  2186. bool home_y = home_y_axis;
  2187. bool home_z = home_z_axis;
  2188. // Either all X,Y,Z codes are present, or none of them.
  2189. bool home_all_axes = home_x == home_y && home_x == home_z;
  2190. if (home_all_axes)
  2191. // No X/Y/Z code provided means to home all axes.
  2192. home_x = home_y = home_z = true;
  2193. //if we are homing all axes, first move z higher to protect heatbed/steel sheet
  2194. if (home_all_axes) {
  2195. raise_z_above(MESH_HOME_Z_SEARCH);
  2196. }
  2197. #ifdef ENABLE_AUTO_BED_LEVELING
  2198. plan_bed_level_matrix.set_to_identity(); //Reset the plane ("erase" all leveling data)
  2199. #endif //ENABLE_AUTO_BED_LEVELING
  2200. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  2201. // the planner will not perform any adjustments in the XY plane.
  2202. // Wait for the motors to stop and update the current position with the absolute values.
  2203. world2machine_revert_to_uncorrected();
  2204. // For mesh bed leveling deactivate the matrix temporarily.
  2205. // It is necessary to disable the bed leveling for the X and Y homing moves, so that the move is performed
  2206. // in a single axis only.
  2207. // In case of re-homing the X or Y axes only, the mesh bed leveling is restored after G28.
  2208. #ifdef MESH_BED_LEVELING
  2209. uint8_t mbl_was_active = mbl.active;
  2210. mbl.active = 0;
  2211. current_position[Z_AXIS] = st_get_position_mm(Z_AXIS);
  2212. #endif
  2213. // Reset baby stepping to zero, if the babystepping has already been loaded before.
  2214. if (home_z)
  2215. babystep_undo();
  2216. int l_feedmultiply = setup_for_endstop_move();
  2217. set_destination_to_current();
  2218. feedrate = 0.0;
  2219. #if Z_HOME_DIR > 0 // If homing away from BED do Z first
  2220. if(home_z)
  2221. homeaxis(Z_AXIS);
  2222. #endif
  2223. #ifdef QUICK_HOME
  2224. // In the quick mode, if both x and y are to be homed, a diagonal move will be performed initially.
  2225. if(home_x && home_y) //first diagonal move
  2226. {
  2227. current_position[X_AXIS] = 0;current_position[Y_AXIS] = 0;
  2228. uint8_t x_axis_home_dir = home_dir(X_AXIS);
  2229. plan_set_position_curposXYZE();
  2230. 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);
  2231. feedrate = homing_feedrate[X_AXIS];
  2232. if(homing_feedrate[Y_AXIS]<feedrate)
  2233. feedrate = homing_feedrate[Y_AXIS];
  2234. if (max_length(X_AXIS) > max_length(Y_AXIS)) {
  2235. feedrate *= sqrt(pow(max_length(Y_AXIS) / max_length(X_AXIS), 2) + 1);
  2236. } else {
  2237. feedrate *= sqrt(pow(max_length(X_AXIS) / max_length(Y_AXIS), 2) + 1);
  2238. }
  2239. plan_buffer_line_destinationXYZE(feedrate/60);
  2240. st_synchronize();
  2241. axis_is_at_home(X_AXIS);
  2242. axis_is_at_home(Y_AXIS);
  2243. plan_set_position_curposXYZE();
  2244. destination[X_AXIS] = current_position[X_AXIS];
  2245. destination[Y_AXIS] = current_position[Y_AXIS];
  2246. plan_buffer_line_destinationXYZE(feedrate/60);
  2247. feedrate = 0.0;
  2248. st_synchronize();
  2249. endstops_hit_on_purpose();
  2250. current_position[X_AXIS] = destination[X_AXIS];
  2251. current_position[Y_AXIS] = destination[Y_AXIS];
  2252. current_position[Z_AXIS] = destination[Z_AXIS];
  2253. }
  2254. #endif /* QUICK_HOME */
  2255. #ifdef TMC2130
  2256. if(home_x)
  2257. {
  2258. if (!calib)
  2259. homeaxis(X_AXIS);
  2260. else
  2261. tmc2130_home_calibrate(X_AXIS);
  2262. }
  2263. if(home_y)
  2264. {
  2265. if (!calib)
  2266. homeaxis(Y_AXIS);
  2267. else
  2268. tmc2130_home_calibrate(Y_AXIS);
  2269. }
  2270. #else //TMC2130
  2271. if(home_x) homeaxis(X_AXIS);
  2272. if(home_y) homeaxis(Y_AXIS);
  2273. #endif //TMC2130
  2274. if(home_x_axis && home_x_value != 0)
  2275. current_position[X_AXIS]=home_x_value+cs.add_homing[X_AXIS];
  2276. if(home_y_axis && home_y_value != 0)
  2277. current_position[Y_AXIS]=home_y_value+cs.add_homing[Y_AXIS];
  2278. #if Z_HOME_DIR < 0 // If homing towards BED do Z last
  2279. #ifndef Z_SAFE_HOMING
  2280. if(home_z) {
  2281. #if defined (Z_RAISE_BEFORE_HOMING) && (Z_RAISE_BEFORE_HOMING > 0)
  2282. raise_z_above(Z_RAISE_BEFORE_HOMING);
  2283. #endif // defined (Z_RAISE_BEFORE_HOMING) && (Z_RAISE_BEFORE_HOMING > 0)
  2284. #ifdef MESH_BED_LEVELING // If Mesh bed leveling, move X&Y to safe position for home
  2285. raise_z_above(MESH_HOME_Z_SEARCH);
  2286. if (!axis_known_position[X_AXIS]) homeaxis(X_AXIS);
  2287. if (!axis_known_position[Y_AXIS]) homeaxis(Y_AXIS);
  2288. // 1st mesh bed leveling measurement point, corrected.
  2289. world2machine_initialize();
  2290. world2machine(pgm_read_float(bed_ref_points_4), pgm_read_float(bed_ref_points_4+1), destination[X_AXIS], destination[Y_AXIS]);
  2291. world2machine_reset();
  2292. if (destination[Y_AXIS] < Y_MIN_POS)
  2293. destination[Y_AXIS] = Y_MIN_POS;
  2294. feedrate = homing_feedrate[X_AXIS] / 20;
  2295. enable_endstops(false);
  2296. #ifdef DEBUG_BUILD
  2297. SERIAL_ECHOLNPGM("plan_set_position()");
  2298. MYSERIAL.println(current_position[X_AXIS]);MYSERIAL.println(current_position[Y_AXIS]);
  2299. MYSERIAL.println(current_position[Z_AXIS]);MYSERIAL.println(current_position[E_AXIS]);
  2300. #endif
  2301. plan_set_position_curposXYZE();
  2302. #ifdef DEBUG_BUILD
  2303. SERIAL_ECHOLNPGM("plan_buffer_line()");
  2304. MYSERIAL.println(destination[X_AXIS]);MYSERIAL.println(destination[Y_AXIS]);
  2305. MYSERIAL.println(destination[Z_AXIS]);MYSERIAL.println(destination[E_AXIS]);
  2306. MYSERIAL.println(feedrate);MYSERIAL.println(active_extruder);
  2307. #endif
  2308. plan_buffer_line_destinationXYZE(feedrate);
  2309. st_synchronize();
  2310. current_position[X_AXIS] = destination[X_AXIS];
  2311. current_position[Y_AXIS] = destination[Y_AXIS];
  2312. enable_endstops(true);
  2313. endstops_hit_on_purpose();
  2314. homeaxis(Z_AXIS);
  2315. #else // MESH_BED_LEVELING
  2316. homeaxis(Z_AXIS);
  2317. #endif // MESH_BED_LEVELING
  2318. }
  2319. #else // defined(Z_SAFE_HOMING): Z Safe mode activated.
  2320. if(home_all_axes) {
  2321. destination[X_AXIS] = round(Z_SAFE_HOMING_X_POINT - X_PROBE_OFFSET_FROM_EXTRUDER);
  2322. destination[Y_AXIS] = round(Z_SAFE_HOMING_Y_POINT - Y_PROBE_OFFSET_FROM_EXTRUDER);
  2323. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  2324. feedrate = XY_TRAVEL_SPEED/60;
  2325. current_position[Z_AXIS] = 0;
  2326. plan_set_position_curposXYZE();
  2327. plan_buffer_line_destinationXYZE(feedrate);
  2328. st_synchronize();
  2329. current_position[X_AXIS] = destination[X_AXIS];
  2330. current_position[Y_AXIS] = destination[Y_AXIS];
  2331. homeaxis(Z_AXIS);
  2332. }
  2333. // Let's see if X and Y are homed and probe is inside bed area.
  2334. if(home_z) {
  2335. if ( (axis_known_position[X_AXIS]) && (axis_known_position[Y_AXIS]) \
  2336. && (current_position[X_AXIS]+X_PROBE_OFFSET_FROM_EXTRUDER >= X_MIN_POS) \
  2337. && (current_position[X_AXIS]+X_PROBE_OFFSET_FROM_EXTRUDER <= X_MAX_POS) \
  2338. && (current_position[Y_AXIS]+Y_PROBE_OFFSET_FROM_EXTRUDER >= Y_MIN_POS) \
  2339. && (current_position[Y_AXIS]+Y_PROBE_OFFSET_FROM_EXTRUDER <= Y_MAX_POS)) {
  2340. current_position[Z_AXIS] = 0;
  2341. plan_set_position_curposXYZE();
  2342. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  2343. feedrate = max_feedrate[Z_AXIS];
  2344. plan_buffer_line_destinationXYZE(feedrate);
  2345. st_synchronize();
  2346. homeaxis(Z_AXIS);
  2347. } else if (!((axis_known_position[X_AXIS]) && (axis_known_position[Y_AXIS]))) {
  2348. LCD_MESSAGERPGM(MSG_POSITION_UNKNOWN);
  2349. SERIAL_ECHO_START;
  2350. SERIAL_ECHOLNRPGM(MSG_POSITION_UNKNOWN);
  2351. } else {
  2352. LCD_MESSAGERPGM(MSG_ZPROBE_OUT);
  2353. SERIAL_ECHO_START;
  2354. SERIAL_ECHOLNRPGM(MSG_ZPROBE_OUT);
  2355. }
  2356. }
  2357. #endif // Z_SAFE_HOMING
  2358. #endif // Z_HOME_DIR < 0
  2359. if(home_z_axis && home_z_value != 0)
  2360. current_position[Z_AXIS]=home_z_value+cs.add_homing[Z_AXIS];
  2361. #ifdef ENABLE_AUTO_BED_LEVELING
  2362. if(home_z)
  2363. current_position[Z_AXIS] += cs.zprobe_zoffset; //Add Z_Probe offset (the distance is negative)
  2364. #endif
  2365. // Set the planner and stepper routine positions.
  2366. // At this point the mesh bed leveling and world2machine corrections are disabled and current_position
  2367. // contains the machine coordinates.
  2368. plan_set_position_curposXYZE();
  2369. clean_up_after_endstop_move(l_feedmultiply);
  2370. endstops_hit_on_purpose();
  2371. #ifndef MESH_BED_LEVELING
  2372. //-// Oct 2019 :: this part of code is (from) now probably un-compilable
  2373. // If MESH_BED_LEVELING is not active, then it is the original Prusa i3.
  2374. // Offer the user to load the baby step value, which has been adjusted at the previous print session.
  2375. if(card.sdprinting && eeprom_read_word((uint16_t *)EEPROM_BABYSTEP_Z))
  2376. lcd_adjust_z();
  2377. #endif
  2378. // Load the machine correction matrix
  2379. world2machine_initialize();
  2380. // and correct the current_position XY axes to match the transformed coordinate system.
  2381. world2machine_update_current();
  2382. #ifdef MESH_BED_LEVELING
  2383. if (home_x_axis || home_y_axis || without_mbl || home_z_axis)
  2384. {
  2385. if (! home_z && mbl_was_active) {
  2386. // Re-enable the mesh bed leveling if only the X and Y axes were re-homed.
  2387. mbl.active = true;
  2388. // and re-adjust the current logical Z axis with the bed leveling offset applicable at the current XY position.
  2389. current_position[Z_AXIS] -= mbl.get_z(st_get_position_mm(X_AXIS), st_get_position_mm(Y_AXIS));
  2390. }
  2391. }
  2392. #endif
  2393. prusa_statistics(20);
  2394. st_synchronize();
  2395. homing_flag = false;
  2396. #if 0
  2397. SERIAL_ECHOPGM("G28, final "); print_world_coordinates();
  2398. SERIAL_ECHOPGM("G28, final "); print_physical_coordinates();
  2399. SERIAL_ECHOPGM("G28, final "); print_mesh_bed_leveling_table();
  2400. #endif
  2401. }
  2402. static void gcode_G28(bool home_x_axis, bool home_y_axis, bool home_z_axis)
  2403. {
  2404. #ifdef TMC2130
  2405. gcode_G28(home_x_axis, 0, home_y_axis, 0, home_z_axis, 0, false, true);
  2406. #else
  2407. gcode_G28(home_x_axis, 0, home_y_axis, 0, home_z_axis, 0, true);
  2408. #endif //TMC2130
  2409. }
  2410. // G80 - Automatic mesh bed leveling
  2411. static void gcode_G80()
  2412. {
  2413. st_synchronize();
  2414. if (planner_aborted)
  2415. return;
  2416. mesh_bed_leveling_flag = true;
  2417. #ifndef PINDA_THERMISTOR
  2418. static bool run = false; // thermistor-less PINDA temperature compensation is running
  2419. #endif // ndef PINDA_THERMISTOR
  2420. #ifdef SUPPORT_VERBOSITY
  2421. int8_t verbosity_level = 0;
  2422. if (code_seen('V')) {
  2423. // Just 'V' without a number counts as V1.
  2424. char c = strchr_pointer[1];
  2425. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  2426. }
  2427. #endif //SUPPORT_VERBOSITY
  2428. // Firstly check if we know where we are
  2429. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  2430. // We don't know where we are! HOME!
  2431. // Push the commands to the front of the message queue in the reverse order!
  2432. // There shall be always enough space reserved for these commands.
  2433. repeatcommand_front(); // repeat G80 with all its parameters
  2434. enquecommand_front_P(G28W0);
  2435. return;
  2436. }
  2437. uint8_t nMeasPoints = MESH_MEAS_NUM_X_POINTS;
  2438. if (code_seen('N')) {
  2439. nMeasPoints = code_value_uint8();
  2440. if (nMeasPoints != 7) {
  2441. nMeasPoints = 3;
  2442. }
  2443. }
  2444. else {
  2445. nMeasPoints = eeprom_read_byte((uint8_t*)EEPROM_MBL_POINTS_NR);
  2446. }
  2447. uint8_t nProbeRetry = 3;
  2448. if (code_seen('R')) {
  2449. nProbeRetry = code_value_uint8();
  2450. if (nProbeRetry > 10) {
  2451. nProbeRetry = 10;
  2452. }
  2453. }
  2454. else {
  2455. nProbeRetry = eeprom_read_byte((uint8_t*)EEPROM_MBL_PROBE_NR);
  2456. }
  2457. bool magnet_elimination = (eeprom_read_byte((uint8_t*)EEPROM_MBL_MAGNET_ELIMINATION) > 0);
  2458. #ifndef PINDA_THERMISTOR
  2459. if (run == false && eeprom_read_byte((uint8_t *)EEPROM_TEMP_CAL_ACTIVE) && calibration_status_pinda() == true && target_temperature_bed >= 50)
  2460. {
  2461. temp_compensation_start();
  2462. run = true;
  2463. repeatcommand_front(); // repeat G80 with all its parameters
  2464. enquecommand_front_P(G28W0);
  2465. break;
  2466. }
  2467. run = false;
  2468. #endif //PINDA_THERMISTOR
  2469. // Save custom message state, set a new custom message state to display: Calibrating point 9.
  2470. CustomMsg custom_message_type_old = custom_message_type;
  2471. uint8_t custom_message_state_old = custom_message_state;
  2472. custom_message_type = CustomMsg::MeshBedLeveling;
  2473. custom_message_state = (nMeasPoints * nMeasPoints) + 10;
  2474. lcd_update(1);
  2475. mbl.reset(); //reset mesh bed leveling
  2476. // Reset baby stepping to zero, if the babystepping has already been loaded before.
  2477. babystep_undo();
  2478. // Cycle through all points and probe them
  2479. // First move up. During this first movement, the babystepping will be reverted.
  2480. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2481. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 60);
  2482. // The move to the first calibration point.
  2483. current_position[X_AXIS] = BED_X0;
  2484. current_position[Y_AXIS] = BED_Y0;
  2485. #ifdef SUPPORT_VERBOSITY
  2486. if (verbosity_level >= 1)
  2487. {
  2488. bool clamped = world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  2489. clamped ? SERIAL_PROTOCOLPGM("First calibration point clamped.\n") : SERIAL_PROTOCOLPGM("No clamping for first calibration point.\n");
  2490. }
  2491. #else //SUPPORT_VERBOSITY
  2492. world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  2493. #endif //SUPPORT_VERBOSITY
  2494. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  2495. plan_buffer_line_curposXYZE(XY_AXIS_FEEDRATE);
  2496. // Wait until the move is finished.
  2497. st_synchronize();
  2498. if (planner_aborted)
  2499. {
  2500. custom_message_type = custom_message_type_old;
  2501. custom_message_state = custom_message_state_old;
  2502. return;
  2503. }
  2504. uint8_t mesh_point = 0; //index number of calibration point
  2505. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  2506. 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)
  2507. #ifdef SUPPORT_VERBOSITY
  2508. if (verbosity_level >= 1) {
  2509. has_z ? SERIAL_PROTOCOLPGM("Z jitter data from Z cal. valid.\n") : SERIAL_PROTOCOLPGM("Z jitter data from Z cal. not valid.\n");
  2510. }
  2511. #endif // SUPPORT_VERBOSITY
  2512. int l_feedmultiply = setup_for_endstop_move(false); //save feedrate and feedmultiply, sets feedmultiply to 100
  2513. while (mesh_point != nMeasPoints * nMeasPoints) {
  2514. // Get coords of a measuring point.
  2515. uint8_t ix = mesh_point % nMeasPoints; // from 0 to MESH_NUM_X_POINTS - 1
  2516. uint8_t iy = mesh_point / nMeasPoints;
  2517. /*if (!mbl_point_measurement_valid(ix, iy, nMeasPoints, true)) {
  2518. printf_P(PSTR("Skipping point [%d;%d] \n"), ix, iy);
  2519. custom_message_state--;
  2520. mesh_point++;
  2521. continue; //skip
  2522. }*/
  2523. if (iy & 1) ix = (nMeasPoints - 1) - ix; // Zig zag
  2524. if (nMeasPoints == 7) //if we have 7x7 mesh, compare with Z-calibration for points which are in 3x3 mesh
  2525. {
  2526. has_z = ((ix % 3 == 0) && (iy % 3 == 0)) && is_bed_z_jitter_data_valid();
  2527. }
  2528. float z0 = 0.f;
  2529. if (has_z && (mesh_point > 0)) {
  2530. uint16_t z_offset_u = 0;
  2531. if (nMeasPoints == 7) {
  2532. z_offset_u = eeprom_read_word((uint16_t*)(EEPROM_BED_CALIBRATION_Z_JITTER + 2 * ((ix/3) + iy - 1)));
  2533. }
  2534. else {
  2535. z_offset_u = eeprom_read_word((uint16_t*)(EEPROM_BED_CALIBRATION_Z_JITTER + 2 * (ix + iy * 3 - 1)));
  2536. }
  2537. z0 = mbl.z_values[0][0] + *reinterpret_cast<int16_t*>(&z_offset_u) * 0.01;
  2538. #ifdef SUPPORT_VERBOSITY
  2539. if (verbosity_level >= 1) {
  2540. printf_P(PSTR("Bed leveling, point: %d, calibration Z stored in eeprom: %d, calibration z: %f \n"), mesh_point, z_offset_u, z0);
  2541. }
  2542. #endif // SUPPORT_VERBOSITY
  2543. }
  2544. // Move Z up to MESH_HOME_Z_SEARCH.
  2545. if((ix == 0) && (iy == 0)) current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2546. else current_position[Z_AXIS] += 2.f / nMeasPoints; //use relative movement from Z coordinate where PINDa triggered on previous point. This makes calibration faster.
  2547. float init_z_bckp = current_position[Z_AXIS];
  2548. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  2549. st_synchronize();
  2550. // Move to XY position of the sensor point.
  2551. current_position[X_AXIS] = BED_X(ix, nMeasPoints);
  2552. current_position[Y_AXIS] = BED_Y(iy, nMeasPoints);
  2553. //printf_P(PSTR("[%f;%f]\n"), current_position[X_AXIS], current_position[Y_AXIS]);
  2554. #ifdef SUPPORT_VERBOSITY
  2555. if (verbosity_level >= 1) {
  2556. bool clamped = world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  2557. SERIAL_PROTOCOL(mesh_point);
  2558. clamped ? SERIAL_PROTOCOLPGM(": xy clamped.\n") : SERIAL_PROTOCOLPGM(": no xy clamping\n");
  2559. }
  2560. #else //SUPPORT_VERBOSITY
  2561. world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  2562. #endif // SUPPORT_VERBOSITY
  2563. //printf_P(PSTR("after clamping: [%f;%f]\n"), current_position[X_AXIS], current_position[Y_AXIS]);
  2564. plan_buffer_line_curposXYZE(XY_AXIS_FEEDRATE);
  2565. st_synchronize();
  2566. if (planner_aborted)
  2567. {
  2568. custom_message_type = custom_message_type_old;
  2569. custom_message_state = custom_message_state_old;
  2570. return;
  2571. }
  2572. // Go down until endstop is hit
  2573. const float Z_CALIBRATION_THRESHOLD = 1.f;
  2574. 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
  2575. printf_P(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  2576. break;
  2577. }
  2578. 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.
  2579. //printf_P(PSTR("Another attempt! Current Z position: %f\n"), current_position[Z_AXIS]);
  2580. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2581. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  2582. st_synchronize();
  2583. 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
  2584. printf_P(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  2585. break;
  2586. }
  2587. if (MESH_HOME_Z_SEARCH - current_position[Z_AXIS] < 0.1f) {
  2588. puts_P(PSTR("Bed leveling failed. Sensor disconnected or cable broken."));
  2589. break;
  2590. }
  2591. }
  2592. 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
  2593. puts_P(PSTR("Bed leveling failed. Sensor triggered too high."));
  2594. break;
  2595. }
  2596. #ifdef SUPPORT_VERBOSITY
  2597. if (verbosity_level >= 10) {
  2598. SERIAL_ECHOPGM("X: ");
  2599. MYSERIAL.print(current_position[X_AXIS], 5);
  2600. SERIAL_ECHOLNPGM("");
  2601. SERIAL_ECHOPGM("Y: ");
  2602. MYSERIAL.print(current_position[Y_AXIS], 5);
  2603. SERIAL_PROTOCOLPGM("\n");
  2604. }
  2605. #endif // SUPPORT_VERBOSITY
  2606. float offset_z = 0;
  2607. #ifdef PINDA_THERMISTOR
  2608. offset_z = temp_compensation_pinda_thermistor_offset(current_temperature_pinda);
  2609. #endif //PINDA_THERMISTOR
  2610. // #ifdef SUPPORT_VERBOSITY
  2611. /* if (verbosity_level >= 1)
  2612. {
  2613. SERIAL_ECHOPGM("mesh bed leveling: ");
  2614. MYSERIAL.print(current_position[Z_AXIS], 5);
  2615. SERIAL_ECHOPGM(" offset: ");
  2616. MYSERIAL.print(offset_z, 5);
  2617. SERIAL_ECHOLNPGM("");
  2618. }*/
  2619. // #endif // SUPPORT_VERBOSITY
  2620. mbl.set_z(ix, iy, current_position[Z_AXIS] - offset_z); //store measured z values z_values[iy][ix] = z - offset_z;
  2621. custom_message_state--;
  2622. mesh_point++;
  2623. lcd_update(1);
  2624. }
  2625. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2626. #ifdef SUPPORT_VERBOSITY
  2627. if (verbosity_level >= 20) {
  2628. SERIAL_ECHOLNPGM("Mesh bed leveling while loop finished.");
  2629. SERIAL_ECHOLNPGM("MESH_HOME_Z_SEARCH: ");
  2630. MYSERIAL.print(current_position[Z_AXIS], 5);
  2631. }
  2632. #endif // SUPPORT_VERBOSITY
  2633. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  2634. st_synchronize();
  2635. if (mesh_point != nMeasPoints * nMeasPoints) {
  2636. Sound_MakeSound(e_SOUND_TYPE_StandardAlert);
  2637. bool bState;
  2638. do { // repeat until Z-leveling o.k.
  2639. lcd_display_message_fullscreen_P(_i("Some problem encountered, Z-leveling enforced ...")); ////MSG_ZLEVELING_ENFORCED c=20 r=4
  2640. #ifdef TMC2130
  2641. lcd_wait_for_click_delay(MSG_BED_LEVELING_FAILED_TIMEOUT);
  2642. calibrate_z_auto(); // Z-leveling (X-assembly stay up!!!)
  2643. #else // TMC2130
  2644. lcd_wait_for_click_delay(0); // ~ no timeout
  2645. lcd_calibrate_z_end_stop_manual(true); // Z-leveling (X-assembly stay up!!!)
  2646. #endif // TMC2130
  2647. // ~ Z-homing (can not be used "G28", because X & Y-homing would have been done before (Z-homing))
  2648. bState=enable_z_endstop(false);
  2649. raise_z(-1);
  2650. enable_z_endstop(true);
  2651. #ifdef TMC2130
  2652. tmc2130_home_enter(Z_AXIS_MASK);
  2653. #endif // TMC2130
  2654. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2655. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2656. st_synchronize();
  2657. #ifdef TMC2130
  2658. tmc2130_home_exit();
  2659. #endif // TMC2130
  2660. enable_z_endstop(bState);
  2661. } while (st_get_position_mm(Z_AXIS) > MESH_HOME_Z_SEARCH); // i.e. Z-leveling not o.k.
  2662. // plan_set_z_position(MESH_HOME_Z_SEARCH); // is not necessary ('do-while' loop always ends at the expected Z-position)
  2663. custom_message_type = custom_message_type_old;
  2664. custom_message_state = custom_message_state_old;
  2665. lcd_update_enable(true); // display / status-line recovery
  2666. gcode_G28(true, true, true); // X & Y & Z-homing (must be after individual Z-homing (problem with spool-holder)!)
  2667. repeatcommand_front(); // re-run (i.e. of "G80")
  2668. return;
  2669. }
  2670. clean_up_after_endstop_move(l_feedmultiply);
  2671. // SERIAL_ECHOLNPGM("clean up finished ");
  2672. #ifndef PINDA_THERMISTOR
  2673. if(eeprom_read_byte((uint8_t *)EEPROM_TEMP_CAL_ACTIVE) && calibration_status_pinda() == true) temp_compensation_apply(); //apply PINDA temperature compensation
  2674. #endif
  2675. babystep_apply(); // Apply Z height correction aka baby stepping before mesh bed leveing gets activated.
  2676. // SERIAL_ECHOLNPGM("babystep applied");
  2677. bool eeprom_bed_correction_valid = eeprom_read_byte((unsigned char*)EEPROM_BED_CORRECTION_VALID) == 1;
  2678. #ifdef SUPPORT_VERBOSITY
  2679. if (verbosity_level >= 1) {
  2680. eeprom_bed_correction_valid ? SERIAL_PROTOCOLPGM("Bed correction data valid\n") : SERIAL_PROTOCOLPGM("Bed correction data not valid\n");
  2681. }
  2682. #endif // SUPPORT_VERBOSITY
  2683. for (uint8_t i = 0; i < 4; ++i) {
  2684. unsigned char codes[4] = { 'L', 'R', 'F', 'B' };
  2685. long correction = 0;
  2686. if (code_seen(codes[i]))
  2687. correction = code_value_long();
  2688. else if (eeprom_bed_correction_valid) {
  2689. unsigned char *addr = (i < 2) ?
  2690. ((i == 0) ? (unsigned char*)EEPROM_BED_CORRECTION_LEFT : (unsigned char*)EEPROM_BED_CORRECTION_RIGHT) :
  2691. ((i == 2) ? (unsigned char*)EEPROM_BED_CORRECTION_FRONT : (unsigned char*)EEPROM_BED_CORRECTION_REAR);
  2692. correction = eeprom_read_int8(addr);
  2693. }
  2694. if (correction == 0)
  2695. continue;
  2696. if (labs(correction) > BED_ADJUSTMENT_UM_MAX) {
  2697. SERIAL_ERROR_START;
  2698. SERIAL_ECHOPGM("Excessive bed leveling correction: ");
  2699. SERIAL_ECHO(correction);
  2700. SERIAL_ECHOLNPGM(" microns");
  2701. }
  2702. else {
  2703. float offset = float(correction) * 0.001f;
  2704. switch (i) {
  2705. case 0:
  2706. for (uint8_t row = 0; row < nMeasPoints; ++row) {
  2707. for (uint8_t col = 0; col < nMeasPoints - 1; ++col) {
  2708. mbl.z_values[row][col] += offset * (nMeasPoints - 1 - col) / (nMeasPoints - 1);
  2709. }
  2710. }
  2711. break;
  2712. case 1:
  2713. for (uint8_t row = 0; row < nMeasPoints; ++row) {
  2714. for (uint8_t col = 1; col < nMeasPoints; ++col) {
  2715. mbl.z_values[row][col] += offset * col / (nMeasPoints - 1);
  2716. }
  2717. }
  2718. break;
  2719. case 2:
  2720. for (uint8_t col = 0; col < nMeasPoints; ++col) {
  2721. for (uint8_t row = 0; row < nMeasPoints; ++row) {
  2722. mbl.z_values[row][col] += offset * (nMeasPoints - 1 - row) / (nMeasPoints - 1);
  2723. }
  2724. }
  2725. break;
  2726. case 3:
  2727. for (uint8_t col = 0; col < nMeasPoints; ++col) {
  2728. for (uint8_t row = 1; row < nMeasPoints; ++row) {
  2729. mbl.z_values[row][col] += offset * row / (nMeasPoints - 1);
  2730. }
  2731. }
  2732. break;
  2733. }
  2734. }
  2735. }
  2736. // SERIAL_ECHOLNPGM("Bed leveling correction finished");
  2737. if (nMeasPoints == 3) {
  2738. 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)
  2739. }
  2740. /*
  2741. SERIAL_PROTOCOLPGM("Num X,Y: ");
  2742. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  2743. SERIAL_PROTOCOLPGM(",");
  2744. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  2745. SERIAL_PROTOCOLPGM("\nZ search height: ");
  2746. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  2747. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  2748. for (int y = MESH_NUM_Y_POINTS-1; y >= 0; y--) {
  2749. for (int x = 0; x < MESH_NUM_X_POINTS; x++) {
  2750. SERIAL_PROTOCOLPGM(" ");
  2751. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  2752. }
  2753. SERIAL_PROTOCOLPGM("\n");
  2754. }
  2755. */
  2756. if (nMeasPoints == 7 && magnet_elimination) {
  2757. mbl_interpolation(nMeasPoints);
  2758. }
  2759. /*
  2760. SERIAL_PROTOCOLPGM("Num X,Y: ");
  2761. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  2762. SERIAL_PROTOCOLPGM(",");
  2763. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  2764. SERIAL_PROTOCOLPGM("\nZ search height: ");
  2765. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  2766. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  2767. for (int y = MESH_NUM_Y_POINTS-1; y >= 0; y--) {
  2768. for (int x = 0; x < MESH_NUM_X_POINTS; x++) {
  2769. SERIAL_PROTOCOLPGM(" ");
  2770. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  2771. }
  2772. SERIAL_PROTOCOLPGM("\n");
  2773. }
  2774. */
  2775. // SERIAL_ECHOLNPGM("Upsample finished");
  2776. mbl.active = 1; //activate mesh bed leveling
  2777. // SERIAL_ECHOLNPGM("Mesh bed leveling activated");
  2778. go_home_with_z_lift();
  2779. // SERIAL_ECHOLNPGM("Go home finished");
  2780. //unretract (after PINDA preheat retraction)
  2781. if (((int)degHotend(active_extruder) > extrude_min_temp) && eeprom_read_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE) && calibration_status_pinda() && (target_temperature_bed >= 50)) {
  2782. current_position[E_AXIS] += default_retraction;
  2783. plan_buffer_line_curposXYZE(400);
  2784. }
  2785. KEEPALIVE_STATE(NOT_BUSY);
  2786. // Restore custom message state
  2787. lcd_setstatuspgm(MSG_WELCOME);
  2788. custom_message_type = custom_message_type_old;
  2789. custom_message_state = custom_message_state_old;
  2790. lcd_update(2);
  2791. st_synchronize();
  2792. mesh_bed_leveling_flag = false;
  2793. }
  2794. void adjust_bed_reset()
  2795. {
  2796. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_VALID, 1);
  2797. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_LEFT, 0);
  2798. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_RIGHT, 0);
  2799. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_FRONT, 0);
  2800. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_REAR, 0);
  2801. }
  2802. //! @brief Calibrate XYZ
  2803. //! @param onlyZ if true, calibrate only Z axis
  2804. //! @param verbosity_level
  2805. //! @retval true Succeeded
  2806. //! @retval false Failed
  2807. bool gcode_M45(bool onlyZ, int8_t verbosity_level)
  2808. {
  2809. bool final_result = false;
  2810. #ifdef TMC2130
  2811. FORCE_HIGH_POWER_START;
  2812. #endif // TMC2130
  2813. FORCE_BL_ON_START;
  2814. // Only Z calibration?
  2815. if (!onlyZ)
  2816. {
  2817. setTargetBed(0);
  2818. setAllTargetHotends(0);
  2819. adjust_bed_reset(); //reset bed level correction
  2820. }
  2821. // Disable the default update procedure of the display. We will do a modal dialog.
  2822. lcd_update_enable(false);
  2823. // Let the planner use the uncorrected coordinates.
  2824. mbl.reset();
  2825. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  2826. // the planner will not perform any adjustments in the XY plane.
  2827. // Wait for the motors to stop and update the current position with the absolute values.
  2828. world2machine_revert_to_uncorrected();
  2829. // Reset the baby step value applied without moving the axes.
  2830. babystep_reset();
  2831. // Mark all axes as in a need for homing.
  2832. memset(axis_known_position, 0, sizeof(axis_known_position));
  2833. // Home in the XY plane.
  2834. //set_destination_to_current();
  2835. int l_feedmultiply = setup_for_endstop_move();
  2836. lcd_display_message_fullscreen_P(_T(MSG_AUTO_HOME));
  2837. raise_z_above(MESH_HOME_Z_SEARCH);
  2838. home_xy();
  2839. enable_endstops(false);
  2840. current_position[X_AXIS] += 5;
  2841. current_position[Y_AXIS] += 5;
  2842. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2843. st_synchronize();
  2844. // Let the user move the Z axes up to the end stoppers.
  2845. #ifdef TMC2130
  2846. if (calibrate_z_auto())
  2847. {
  2848. #else //TMC2130
  2849. if (lcd_calibrate_z_end_stop_manual(onlyZ))
  2850. {
  2851. #endif //TMC2130
  2852. lcd_show_fullscreen_message_and_wait_P(_T(MSG_CONFIRM_NOZZLE_CLEAN));
  2853. if(onlyZ){
  2854. lcd_display_message_fullscreen_P(_T(MSG_MEASURE_BED_REFERENCE_HEIGHT_LINE1));
  2855. lcd_puts_at_P(0,3,_n("1/9"));
  2856. }else{
  2857. //lcd_show_fullscreen_message_and_wait_P(_T(MSG_PAPER));
  2858. lcd_display_message_fullscreen_P(_T(MSG_FIND_BED_OFFSET_AND_SKEW_LINE1));
  2859. lcd_puts_at_P(0,3,_n("1/4"));
  2860. }
  2861. refresh_cmd_timeout();
  2862. #ifndef STEEL_SHEET
  2863. if (((degHotend(0) > MAX_HOTEND_TEMP_CALIBRATION) || (degBed() > MAX_BED_TEMP_CALIBRATION)) && (!onlyZ))
  2864. {
  2865. lcd_wait_for_cool_down();
  2866. }
  2867. #endif //STEEL_SHEET
  2868. if(!onlyZ)
  2869. {
  2870. KEEPALIVE_STATE(PAUSED_FOR_USER);
  2871. #ifdef STEEL_SHEET
  2872. uint8_t result = lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_STEEL_SHEET_CHECK), false);
  2873. if(result == LCD_LEFT_BUTTON_CHOICE) {
  2874. lcd_show_fullscreen_message_and_wait_P(_T(MSG_REMOVE_STEEL_SHEET));
  2875. }
  2876. #endif //STEEL_SHEET
  2877. lcd_show_fullscreen_message_and_wait_P(_T(MSG_PAPER));
  2878. KEEPALIVE_STATE(IN_HANDLER);
  2879. lcd_display_message_fullscreen_P(_T(MSG_FIND_BED_OFFSET_AND_SKEW_LINE1));
  2880. lcd_puts_at_P(0,3,_n("1/4"));
  2881. }
  2882. bool endstops_enabled = enable_endstops(false);
  2883. raise_z(-1);
  2884. // Move the print head close to the bed.
  2885. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2886. enable_endstops(true);
  2887. #ifdef TMC2130
  2888. tmc2130_home_enter(Z_AXIS_MASK);
  2889. #endif //TMC2130
  2890. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2891. st_synchronize();
  2892. #ifdef TMC2130
  2893. tmc2130_home_exit();
  2894. #endif //TMC2130
  2895. enable_endstops(endstops_enabled);
  2896. if ((st_get_position_mm(Z_AXIS) <= (MESH_HOME_Z_SEARCH + HOME_Z_SEARCH_THRESHOLD)) &&
  2897. (st_get_position_mm(Z_AXIS) >= (MESH_HOME_Z_SEARCH - HOME_Z_SEARCH_THRESHOLD)))
  2898. {
  2899. if (onlyZ)
  2900. {
  2901. clean_up_after_endstop_move(l_feedmultiply);
  2902. // Z only calibration.
  2903. // Load the machine correction matrix
  2904. world2machine_initialize();
  2905. // and correct the current_position to match the transformed coordinate system.
  2906. world2machine_update_current();
  2907. //FIXME
  2908. bool result = sample_mesh_and_store_reference();
  2909. if (result)
  2910. {
  2911. if (calibration_status() == CALIBRATION_STATUS_Z_CALIBRATION)
  2912. {
  2913. // Shipped, the nozzle height has been set already. The user can start printing now.
  2914. calibration_status_store(CALIBRATION_STATUS_CALIBRATED);
  2915. }
  2916. final_result = true;
  2917. // babystep_apply();
  2918. }
  2919. }
  2920. else
  2921. {
  2922. // Reset the baby step value and the baby step applied flag.
  2923. calibration_status_store(CALIBRATION_STATUS_XYZ_CALIBRATION);
  2924. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  2925. // Complete XYZ calibration.
  2926. uint8_t point_too_far_mask = 0;
  2927. BedSkewOffsetDetectionResultType result = find_bed_offset_and_skew(verbosity_level, point_too_far_mask);
  2928. clean_up_after_endstop_move(l_feedmultiply);
  2929. // Print head up.
  2930. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2931. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2932. st_synchronize();
  2933. //#ifndef NEW_XYZCAL
  2934. if (result >= 0)
  2935. {
  2936. #ifdef HEATBED_V2
  2937. sample_z();
  2938. #else //HEATBED_V2
  2939. point_too_far_mask = 0;
  2940. // Second half: The fine adjustment.
  2941. // Let the planner use the uncorrected coordinates.
  2942. mbl.reset();
  2943. world2machine_reset();
  2944. // Home in the XY plane.
  2945. int l_feedmultiply = setup_for_endstop_move();
  2946. home_xy();
  2947. result = improve_bed_offset_and_skew(1, verbosity_level, point_too_far_mask);
  2948. clean_up_after_endstop_move(l_feedmultiply);
  2949. // Print head up.
  2950. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2951. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2952. st_synchronize();
  2953. // if (result >= 0) babystep_apply();
  2954. #endif //HEATBED_V2
  2955. }
  2956. //#endif //NEW_XYZCAL
  2957. lcd_update_enable(true);
  2958. lcd_update(2);
  2959. lcd_bed_calibration_show_result(result, point_too_far_mask);
  2960. if (result >= 0)
  2961. {
  2962. // Calibration valid, the machine should be able to print. Advise the user to run the V2Calibration.gcode.
  2963. calibration_status_store(CALIBRATION_STATUS_LIVE_ADJUST);
  2964. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) != 1) lcd_show_fullscreen_message_and_wait_P(_T(MSG_BABYSTEP_Z_NOT_SET));
  2965. final_result = true;
  2966. }
  2967. }
  2968. #ifdef TMC2130
  2969. tmc2130_home_exit();
  2970. #endif
  2971. }
  2972. else
  2973. {
  2974. lcd_show_fullscreen_message_and_wait_P(PSTR("Calibration failed! Check the axes and run again."));
  2975. final_result = false;
  2976. }
  2977. }
  2978. else
  2979. {
  2980. // Timeouted.
  2981. }
  2982. lcd_update_enable(true);
  2983. #ifdef TMC2130
  2984. FORCE_HIGH_POWER_END;
  2985. #endif // TMC2130
  2986. FORCE_BL_ON_END;
  2987. return final_result;
  2988. }
  2989. void gcode_M114()
  2990. {
  2991. SERIAL_PROTOCOLPGM("X:");
  2992. SERIAL_PROTOCOL(current_position[X_AXIS]);
  2993. SERIAL_PROTOCOLPGM(" Y:");
  2994. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  2995. SERIAL_PROTOCOLPGM(" Z:");
  2996. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  2997. SERIAL_PROTOCOLPGM(" E:");
  2998. SERIAL_PROTOCOL(current_position[E_AXIS]);
  2999. SERIAL_PROTOCOLRPGM(_n(" Count X: "));////MSG_COUNT_X
  3000. SERIAL_PROTOCOL(float(st_get_position(X_AXIS)) / cs.axis_steps_per_unit[X_AXIS]);
  3001. SERIAL_PROTOCOLPGM(" Y:");
  3002. SERIAL_PROTOCOL(float(st_get_position(Y_AXIS)) / cs.axis_steps_per_unit[Y_AXIS]);
  3003. SERIAL_PROTOCOLPGM(" Z:");
  3004. SERIAL_PROTOCOL(float(st_get_position(Z_AXIS)) / cs.axis_steps_per_unit[Z_AXIS]);
  3005. SERIAL_PROTOCOLPGM(" E:");
  3006. SERIAL_PROTOCOLLN(float(st_get_position(E_AXIS)) / cs.axis_steps_per_unit[E_AXIS]);
  3007. }
  3008. #if (defined(FANCHECK) && (((defined(TACH_0) && (TACH_0 >-1)) || (defined(TACH_1) && (TACH_1 > -1)))))
  3009. void gcode_M123()
  3010. {
  3011. 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);
  3012. }
  3013. #endif //FANCHECK and TACH_0 or TACH_1
  3014. static void mmu_M600_wait_and_beep() {
  3015. // Beep and wait for user to remove old filament and prepare new filament for load
  3016. KEEPALIVE_STATE(PAUSED_FOR_USER);
  3017. int counterBeep = 0;
  3018. 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
  3019. bool bFirst = true;
  3020. while (!lcd_clicked()) {
  3021. manage_heater();
  3022. manage_inactivity(true);
  3023. #if BEEPER > 0
  3024. if (counterBeep == 500) {
  3025. counterBeep = 0;
  3026. }
  3027. SET_OUTPUT(BEEPER);
  3028. if (counterBeep == 0) {
  3029. if ((eSoundMode == e_SOUND_MODE_BLIND) || (eSoundMode == e_SOUND_MODE_LOUD) || ((eSoundMode == e_SOUND_MODE_ONCE) && bFirst)) {
  3030. bFirst = false;
  3031. WRITE(BEEPER, HIGH);
  3032. }
  3033. }
  3034. if (counterBeep == 20) {
  3035. WRITE(BEEPER, LOW);
  3036. }
  3037. counterBeep++;
  3038. #endif // BEEPER > 0
  3039. delay_keep_alive(4);
  3040. }
  3041. WRITE(BEEPER, LOW);
  3042. }
  3043. /**
  3044. * @brief Handling of unload when using MMU with M600
  3045. * A fullscreen message showing "Unloading Filament x"
  3046. * should be shown on the LCD and LCD updates should be
  3047. * are disabled in the meantime.
  3048. */
  3049. static void mmu_M600_unload_filament() {
  3050. if (MMU2::mmu2.get_current_tool() == (uint8_t)MMU2::FILAMENT_UNKNOWN) return;
  3051. lcd_update_enable(false);
  3052. lcd_clear();
  3053. lcd_puts_at_P(0, 1, _T(MSG_UNLOADING_FILAMENT));
  3054. lcd_print(' ');
  3055. lcd_print(MMU2::mmu2.get_current_tool() + 1);
  3056. // unload just current filament for multimaterial printers (used also in M702)
  3057. MMU2::mmu2.unload();
  3058. lcd_update_enable(true);
  3059. }
  3060. /// @brief load filament for mmu v2
  3061. /// @par nozzle_temp nozzle temperature to load filament
  3062. static void mmu_M600_load_filament(bool automatic, float nozzle_temp) {
  3063. // TODO: Only ask for the slot if automatic/ SpoolJoin is off
  3064. uint8_t slot = choose_menu_P(_T(MSG_SELECT_EXTRUDER), _T(MSG_EXTRUDER));
  3065. // TODO SpoolJoin
  3066. /*if (automatic) {
  3067. tmp_extruder = ad_getAlternative(tmp_extruder);
  3068. }*/
  3069. lcd_update_enable(false);
  3070. lcd_clear();
  3071. lcd_puts_at_P(0, 1, _T(MSG_LOADING_FILAMENT));
  3072. lcd_print(' ');
  3073. lcd_print(slot + 1);
  3074. setTargetHotend(nozzle_temp, active_extruder);
  3075. MMU2::mmu2.load_filament_to_nozzle(slot);
  3076. load_filament_final_feed(); // @@TODO verify
  3077. st_synchronize();
  3078. }
  3079. static void gcode_M600(bool automatic, float x_position, float y_position, float z_shift, float e_shift, float /*e_shift_late*/) {
  3080. st_synchronize();
  3081. float lastpos[4];
  3082. prusa_statistics(22);
  3083. //First backup current position and settings
  3084. int feedmultiplyBckp = feedmultiply;
  3085. float HotendTempBckp = degTargetHotend(active_extruder);
  3086. int fanSpeedBckp = fanSpeed;
  3087. lastpos[X_AXIS] = current_position[X_AXIS];
  3088. lastpos[Y_AXIS] = current_position[Y_AXIS];
  3089. lastpos[Z_AXIS] = current_position[Z_AXIS];
  3090. lastpos[E_AXIS] = current_position[E_AXIS];
  3091. // Retract E
  3092. current_position[E_AXIS] += e_shift;
  3093. plan_buffer_line_curposXYZE(FILAMENTCHANGE_RFEED);
  3094. st_synchronize();
  3095. // Raise the Z axis
  3096. float delta = raise_z(z_shift);
  3097. // Move XY to side
  3098. current_position[X_AXIS] = x_position;
  3099. current_position[Y_AXIS] = y_position;
  3100. plan_buffer_line_curposXYZE(FILAMENTCHANGE_XYFEED);
  3101. st_synchronize();
  3102. // Beep, manage nozzle heater and wait for user to start unload filament
  3103. if (!MMU2::mmu2.Enabled())
  3104. M600_wait_for_user(HotendTempBckp);
  3105. lcd_change_fil_state = 0;
  3106. // Unload filament
  3107. if (MMU2::mmu2.Enabled())
  3108. mmu_M600_unload_filament();
  3109. else
  3110. unload_filament(FILAMENTCHANGE_FINALRETRACT, true); // unload filament for single material (used also in M702)
  3111. st_synchronize(); // finish moves
  3112. {
  3113. FSensorBlockRunout fsBlockRunout;
  3114. if (!MMU2::mmu2.Enabled()) {
  3115. KEEPALIVE_STATE(PAUSED_FOR_USER);
  3116. lcd_change_fil_state =
  3117. lcd_show_fullscreen_message_yes_no_and_wait_P(_i("Was filament unload successful?"), false, LCD_LEFT_BUTTON_CHOICE); ////MSG_UNLOAD_SUCCESSFUL c=20 r=2
  3118. if (lcd_change_fil_state == LCD_MIDDLE_BUTTON_CHOICE) {
  3119. lcd_clear();
  3120. lcd_puts_at_P(0, 2, _T(MSG_PLEASE_WAIT));
  3121. current_position[X_AXIS] -= 100;
  3122. plan_buffer_line_curposXYZE(FILAMENTCHANGE_XYFEED);
  3123. st_synchronize();
  3124. lcd_show_fullscreen_message_and_wait_P(_i("Please open idler and remove filament manually.")); ////MSG_CHECK_IDLER c=20 r=5
  3125. }
  3126. }
  3127. if (MMU2::mmu2.Enabled()) {
  3128. if (!automatic) {
  3129. if (saved_printing){
  3130. // if M600 was invoked by filament senzor (FINDA) eject filament so user can easily remove it
  3131. MMU2::mmu2.eject_filament(MMU2::mmu2.get_current_tool(), false);
  3132. }
  3133. mmu_M600_wait_and_beep();
  3134. if (saved_printing) {
  3135. lcd_clear();
  3136. lcd_puts_at_P(0, 2, _T(MSG_PLEASE_WAIT));
  3137. //@@TODO mmu_command(MmuCmd::R0);
  3138. // manage_response(false, false);
  3139. }
  3140. }
  3141. mmu_M600_load_filament(automatic, HotendTempBckp);
  3142. } else
  3143. M600_load_filament();
  3144. if (!automatic)
  3145. M600_check_state(HotendTempBckp);
  3146. lcd_update_enable(true);
  3147. // Not let's go back to print
  3148. fanSpeed = fanSpeedBckp;
  3149. // Feed a little of filament to stabilize pressure
  3150. if (!automatic) {
  3151. current_position[E_AXIS] += FILAMENTCHANGE_RECFEED;
  3152. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EXFEED);
  3153. }
  3154. // TODO: Move the Z-axis after XY, not before. Currently this does not work
  3155. // and raise_z seems to have no affect after XY move for unknown reasons.
  3156. // This needs to be looked into.
  3157. // Recover Z axis
  3158. raise_z(-delta);
  3159. // Move XY back
  3160. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], FILAMENTCHANGE_XYFEED, active_extruder);
  3161. st_synchronize();
  3162. // Set E position to original
  3163. plan_set_e_position(lastpos[E_AXIS]);
  3164. memcpy(current_position, lastpos, sizeof(lastpos));
  3165. set_destination_to_current();
  3166. // Recover feed rate
  3167. feedmultiply = feedmultiplyBckp;
  3168. char cmd[9];
  3169. sprintf_P(cmd, PSTR("M220 S%i"), feedmultiplyBckp);
  3170. enquecommand(cmd);
  3171. }
  3172. lcd_setstatuspgm(MSG_WELCOME);
  3173. custom_message_type = CustomMsg::Status;
  3174. }
  3175. void gcode_M701(float fastLoadLength, uint8_t mmuSlotIndex){
  3176. FSensorBlockRunout fsBlockRunout;
  3177. prusa_statistics(22);
  3178. if (MMU2::mmu2.Enabled() && mmuSlotIndex < MMU_FILAMENT_COUNT) {
  3179. MMU2::mmu2.load_filament_to_nozzle(mmuSlotIndex);
  3180. } else {
  3181. custom_message_type = CustomMsg::FilamentLoading;
  3182. lcd_setstatuspgm(_T(MSG_LOADING_FILAMENT));
  3183. current_position[E_AXIS] += fastLoadLength;
  3184. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EFEED_FIRST); //fast sequence
  3185. load_filament_final_feed(); // slow sequence
  3186. st_synchronize();
  3187. Sound_MakeCustom(50, 500, false);
  3188. if (!farm_mode && loading_flag) {
  3189. lcd_load_filament_color_check();
  3190. }
  3191. lcd_update_enable(true);
  3192. lcd_update(2);
  3193. lcd_setstatuspgm(MSG_WELCOME);
  3194. loading_flag = false;
  3195. custom_message_type = CustomMsg::Status;
  3196. }
  3197. eFilamentAction = FilamentAction::None;
  3198. }
  3199. // Common gcode shared by the gcodes. This saves some flash memory
  3200. static void gcodes_M704_M705_M706(uint16_t gcode)
  3201. {
  3202. uint8_t mmuSlotIndex = 0xffU;
  3203. if (MMU2::mmu2.Enabled() && code_seen('P'))
  3204. {
  3205. mmuSlotIndex = code_value_uint8();
  3206. if (mmuSlotIndex < MMU_FILAMENT_COUNT) {
  3207. switch (gcode)
  3208. {
  3209. case 704:
  3210. MMU2::mmu2.load_filament(mmuSlotIndex);
  3211. break;
  3212. case 705:
  3213. MMU2::mmu2.eject_filament(mmuSlotIndex, false);
  3214. break;
  3215. case 706:
  3216. #ifdef MMU_HAS_CUTTER
  3217. if (eeprom_read_byte((uint8_t*)EEPROM_MMU_CUTTER_ENABLED) != 0){
  3218. MMU2::mmu2.cut_filament(mmuSlotIndex);
  3219. }
  3220. #endif // MMU_HAS_CUTTER
  3221. break;
  3222. default:
  3223. break;
  3224. }
  3225. }
  3226. }
  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. uint8_t result = lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_STEEL_SHEET_CHECK), false);
  4301. if (result == LCD_LEFT_BUTTON_CHOICE)
  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. if (MMU2::mmu2.Enabled())
  4777. {
  4778. if (MMU2::mmu2.FindaDetectsFilament() && !fsensor.getFilamentPresent())
  4779. { // Filament only half way into the PTFE. Unload the filament.
  4780. MMU2::mmu2.unload();
  4781. // Tx and Tc gcodes take care of loading the filament to the nozzle.
  4782. }
  4783. }
  4784. }
  4785. break;
  4786. /*!
  4787. ### M26 - Set SD index <a href="https://reprap.org/wiki/G-code#M26:_Set_SD_position">M26: Set SD position</a>
  4788. Set position in SD card file to index in bytes.
  4789. This command is expected to be called after M23 and before M24.
  4790. Otherwise effect of this command is undefined.
  4791. #### Usage
  4792. M26 [ S ]
  4793. #### Parameters
  4794. - `S` - Index in bytes
  4795. */
  4796. case 26:
  4797. if(card.cardOK && code_seen('S')) {
  4798. long index = code_value_long();
  4799. card.setIndex(index);
  4800. // We don't disable interrupt during update of sdpos_atomic
  4801. // as we expect, that SD card print is not active in this moment
  4802. sdpos_atomic = index;
  4803. }
  4804. break;
  4805. /*!
  4806. ### M27 - Get SD status <a href="https://reprap.org/wiki/G-code#M27:_Report_SD_print_status">M27: Report SD print status</a>
  4807. #### Usage
  4808. M27 [ P ]
  4809. #### Parameters
  4810. - `P` - Show full SFN path instead of LFN only.
  4811. */
  4812. case 27:
  4813. card.getStatus(code_seen('P'));
  4814. break;
  4815. /*!
  4816. ### 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>
  4817. */
  4818. case 28:
  4819. starpos = (strchr(strchr_pointer + 4,'*'));
  4820. if(starpos != NULL){
  4821. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  4822. strchr_pointer = strchr(npos,' ') + 1;
  4823. *(starpos) = '\0';
  4824. }
  4825. card.openFileWrite(strchr_pointer+4);
  4826. break;
  4827. /*! ### 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>
  4828. 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.
  4829. */
  4830. case 29:
  4831. //processed in write to file routine above
  4832. //card,saving = false;
  4833. break;
  4834. /*!
  4835. ### 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>
  4836. #### Usage
  4837. M30 [filename]
  4838. */
  4839. case 30:
  4840. if (card.cardOK){
  4841. card.closefile();
  4842. starpos = (strchr(strchr_pointer + 4,'*'));
  4843. if(starpos != NULL){
  4844. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  4845. strchr_pointer = strchr(npos,' ') + 1;
  4846. *(starpos) = '\0';
  4847. }
  4848. card.removeFile(strchr_pointer + 4);
  4849. }
  4850. break;
  4851. /*!
  4852. ### 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>
  4853. @todo What are the parameters P and S for in M32?
  4854. */
  4855. case 32:
  4856. {
  4857. if(card.sdprinting) {
  4858. st_synchronize();
  4859. }
  4860. starpos = (strchr(strchr_pointer + 4,'*'));
  4861. const char* namestartpos = (strchr(strchr_pointer + 4,'!')); //find ! to indicate filename string start.
  4862. if(namestartpos==NULL)
  4863. {
  4864. namestartpos=strchr_pointer + 4; //default name position, 4 letters after the M
  4865. }
  4866. else
  4867. namestartpos++; //to skip the '!'
  4868. if(starpos!=NULL)
  4869. *(starpos)='\0';
  4870. bool call_procedure=(code_seen('P'));
  4871. if(strchr_pointer>namestartpos)
  4872. call_procedure=false; //false alert, 'P' found within filename
  4873. if( card.cardOK )
  4874. {
  4875. card.openFileReadFilteredGcode(namestartpos,!call_procedure);
  4876. if(code_seen('S'))
  4877. if(strchr_pointer<namestartpos) //only if "S" is occuring _before_ the filename
  4878. card.setIndex(code_value_long());
  4879. card.startFileprint();
  4880. if(!call_procedure)
  4881. {
  4882. if(!card.get_sdpos())
  4883. {
  4884. // A new print has started from scratch, reset stats
  4885. failstats_reset_print();
  4886. sdpos_atomic = 0;
  4887. #ifndef LA_NOCOMPAT
  4888. la10c_reset();
  4889. #endif
  4890. }
  4891. starttime=_millis(); // procedure calls count as normal print time.
  4892. }
  4893. }
  4894. } break;
  4895. /*!
  4896. ### M928 - Start SD logging <a href="https://reprap.org/wiki/G-code#M928:_Start_SD_logging">M928: Start SD logging</a>
  4897. #### Usage
  4898. M928 [filename]
  4899. */
  4900. case 928:
  4901. starpos = (strchr(strchr_pointer + 5,'*'));
  4902. if(starpos != NULL){
  4903. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  4904. strchr_pointer = strchr(npos,' ') + 1;
  4905. *(starpos) = '\0';
  4906. }
  4907. card.openLogFile(strchr_pointer+5);
  4908. break;
  4909. #endif //SDSUPPORT
  4910. /*!
  4911. ### 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>
  4912. */
  4913. case 31: //M31 take time since the start of the SD print or an M109 command
  4914. {
  4915. stoptime=_millis();
  4916. char time[30];
  4917. unsigned long t=(stoptime-starttime)/1000;
  4918. int sec,min;
  4919. min=t/60;
  4920. sec=t%60;
  4921. sprintf_P(time, PSTR("%i min, %i sec"), min, sec);
  4922. SERIAL_ECHO_START;
  4923. SERIAL_ECHOLN(time);
  4924. lcd_setstatus(time);
  4925. autotempShutdown();
  4926. }
  4927. break;
  4928. /*!
  4929. ### M42 - Set pin state <a href="https://reprap.org/wiki/G-code#M42:_Switch_I.2FO_pin">M42: Switch I/O pin</a>
  4930. #### Usage
  4931. M42 [ P | S ]
  4932. #### Parameters
  4933. - `P` - Pin number.
  4934. - `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.
  4935. */
  4936. case 42:
  4937. if (code_seen('S'))
  4938. {
  4939. uint8_t pin_status = code_value_uint8();
  4940. int8_t pin_number = LED_PIN;
  4941. if (code_seen('P'))
  4942. pin_number = code_value_uint8();
  4943. for(int8_t i = 0; i < (int8_t)(sizeof(sensitive_pins)/sizeof(sensitive_pins[0])); i++)
  4944. {
  4945. if ((int8_t)pgm_read_byte(&sensitive_pins[i]) == pin_number)
  4946. {
  4947. pin_number = -1;
  4948. break;
  4949. }
  4950. }
  4951. #if defined(FAN_PIN) && FAN_PIN > -1
  4952. if (pin_number == FAN_PIN)
  4953. fanSpeed = pin_status;
  4954. #endif
  4955. if (pin_number > -1)
  4956. {
  4957. pinMode(pin_number, OUTPUT);
  4958. digitalWrite(pin_number, pin_status);
  4959. analogWrite(pin_number, pin_status);
  4960. }
  4961. }
  4962. break;
  4963. /*!
  4964. ### 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>
  4965. */
  4966. case 44: // M44: Prusa3D: Reset the bed skew and offset calibration.
  4967. // Reset the baby step value and the baby step applied flag.
  4968. calibration_status_store(CALIBRATION_STATUS_ASSEMBLED);
  4969. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  4970. // Reset the skew and offset in both RAM and EEPROM.
  4971. reset_bed_offset_and_skew();
  4972. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  4973. // the planner will not perform any adjustments in the XY plane.
  4974. // Wait for the motors to stop and update the current position with the absolute values.
  4975. world2machine_revert_to_uncorrected();
  4976. break;
  4977. /*!
  4978. ### 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>
  4979. #### Usage
  4980. M45 [ V ]
  4981. #### Parameters
  4982. - `V` - Verbosity level 1, 10 and 20 (low, mid, high). Only when SUPPORT_VERBOSITY is defined. Optional.
  4983. - `Z` - If it is provided, only Z calibration will run. Otherwise full calibration is executed.
  4984. */
  4985. case 45: // M45: Prusa3D: bed skew and offset with manual Z up
  4986. {
  4987. int8_t verbosity_level = 0;
  4988. bool only_Z = code_seen('Z');
  4989. #ifdef SUPPORT_VERBOSITY
  4990. if (code_seen('V'))
  4991. {
  4992. // Just 'V' without a number counts as V1.
  4993. char c = strchr_pointer[1];
  4994. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  4995. }
  4996. #endif //SUPPORT_VERBOSITY
  4997. gcode_M45(only_Z, verbosity_level);
  4998. }
  4999. break;
  5000. /*!
  5001. ### 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>
  5002. */
  5003. case 46:
  5004. {
  5005. // M46: Prusa3D: Show the assigned IP address.
  5006. if (card.ToshibaFlashAir_isEnabled()) {
  5007. uint8_t ip[4];
  5008. if (card.ToshibaFlashAir_GetIP(ip)) {
  5009. // SERIAL_PROTOCOLPGM("Toshiba FlashAir current IP: ");
  5010. SERIAL_PROTOCOL(uint8_t(ip[0]));
  5011. SERIAL_PROTOCOL('.');
  5012. SERIAL_PROTOCOL(uint8_t(ip[1]));
  5013. SERIAL_PROTOCOL('.');
  5014. SERIAL_PROTOCOL(uint8_t(ip[2]));
  5015. SERIAL_PROTOCOL('.');
  5016. SERIAL_PROTOCOLLN(uint8_t(ip[3]));
  5017. } else {
  5018. SERIAL_PROTOCOLPGM("?Toshiba FlashAir GetIP failed\n");
  5019. }
  5020. } else {
  5021. SERIAL_PROTOCOLLNPGM("n/a");
  5022. }
  5023. break;
  5024. }
  5025. /*!
  5026. ### 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>
  5027. */
  5028. case 47:
  5029. KEEPALIVE_STATE(PAUSED_FOR_USER);
  5030. lcd_diag_show_end_stops();
  5031. KEEPALIVE_STATE(IN_HANDLER);
  5032. break;
  5033. #if 0
  5034. case 48: // M48: scan the bed induction sensor points, print the sensor trigger coordinates to the serial line for visualization on the PC.
  5035. {
  5036. // Disable the default update procedure of the display. We will do a modal dialog.
  5037. lcd_update_enable(false);
  5038. // Let the planner use the uncorrected coordinates.
  5039. mbl.reset();
  5040. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  5041. // the planner will not perform any adjustments in the XY plane.
  5042. // Wait for the motors to stop and update the current position with the absolute values.
  5043. world2machine_revert_to_uncorrected();
  5044. // Move the print head close to the bed.
  5045. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  5046. 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);
  5047. st_synchronize();
  5048. // Home in the XY plane.
  5049. set_destination_to_current();
  5050. int l_feedmultiply = setup_for_endstop_move();
  5051. home_xy();
  5052. int8_t verbosity_level = 0;
  5053. if (code_seen('V')) {
  5054. // Just 'V' without a number counts as V1.
  5055. char c = strchr_pointer[1];
  5056. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  5057. }
  5058. bool success = scan_bed_induction_points(verbosity_level);
  5059. clean_up_after_endstop_move(l_feedmultiply);
  5060. // Print head up.
  5061. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  5062. 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);
  5063. st_synchronize();
  5064. lcd_update_enable(true);
  5065. break;
  5066. }
  5067. #endif
  5068. #ifdef ENABLE_AUTO_BED_LEVELING
  5069. #ifdef Z_PROBE_REPEATABILITY_TEST
  5070. /*!
  5071. ### 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>
  5072. 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.
  5073. 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.
  5074. @todo Why would you check for both uppercase and lowercase? Seems wasteful.
  5075. #### Usage
  5076. M48 [ n | X | Y | V | L ]
  5077. #### Parameters
  5078. - `n` - Number of samples. Valid values 4-50
  5079. - `X` - X position for samples
  5080. - `Y` - Y position for samples
  5081. - `V` - Verbose level. Valid values 1-4
  5082. - `L` - Legs of movementprior to doing probe. Valid values 1-15
  5083. */
  5084. case 48: // M48 Z-Probe repeatability
  5085. {
  5086. #if Z_MIN_PIN == -1
  5087. #error "You must have a Z_MIN endstop in order to enable calculation of Z-Probe repeatability."
  5088. #endif
  5089. double sum=0.0;
  5090. double mean=0.0;
  5091. double sigma=0.0;
  5092. double sample_set[50];
  5093. int verbose_level=1, n=0, j, n_samples = 10, n_legs=0;
  5094. double X_current, Y_current, Z_current;
  5095. double X_probe_location, Y_probe_location, Z_start_location, ext_position;
  5096. if (code_seen('V') || code_seen('v')) {
  5097. verbose_level = code_value();
  5098. if (verbose_level<0 || verbose_level>4 ) {
  5099. SERIAL_PROTOCOLPGM("?Verbose Level not plausable.\n");
  5100. goto Sigma_Exit;
  5101. }
  5102. }
  5103. if (verbose_level > 0) {
  5104. SERIAL_PROTOCOLPGM("M48 Z-Probe Repeatability test. Version 2.00\n");
  5105. SERIAL_PROTOCOLPGM("Full support at: http://3dprintboard.com/forum.php\n");
  5106. }
  5107. if (code_seen('n')) {
  5108. n_samples = code_value();
  5109. if (n_samples<4 || n_samples>50 ) {
  5110. SERIAL_PROTOCOLPGM("?Specified sample size not plausable.\n");
  5111. goto Sigma_Exit;
  5112. }
  5113. }
  5114. X_current = X_probe_location = st_get_position_mm(X_AXIS);
  5115. Y_current = Y_probe_location = st_get_position_mm(Y_AXIS);
  5116. Z_current = st_get_position_mm(Z_AXIS);
  5117. Z_start_location = st_get_position_mm(Z_AXIS) + Z_RAISE_BEFORE_PROBING;
  5118. ext_position = st_get_position_mm(E_AXIS);
  5119. if (code_seen('X') || code_seen('x') ) {
  5120. X_probe_location = code_value() - X_PROBE_OFFSET_FROM_EXTRUDER;
  5121. if (X_probe_location<X_MIN_POS || X_probe_location>X_MAX_POS ) {
  5122. SERIAL_PROTOCOLPGM("?Specified X position out of range.\n");
  5123. goto Sigma_Exit;
  5124. }
  5125. }
  5126. if (code_seen('Y') || code_seen('y') ) {
  5127. Y_probe_location = code_value() - Y_PROBE_OFFSET_FROM_EXTRUDER;
  5128. if (Y_probe_location<Y_MIN_POS || Y_probe_location>Y_MAX_POS ) {
  5129. SERIAL_PROTOCOLPGM("?Specified Y position out of range.\n");
  5130. goto Sigma_Exit;
  5131. }
  5132. }
  5133. if (code_seen('L') || code_seen('l') ) {
  5134. n_legs = code_value();
  5135. if ( n_legs==1 )
  5136. n_legs = 2;
  5137. if ( n_legs<0 || n_legs>15 ) {
  5138. SERIAL_PROTOCOLPGM("?Specified number of legs in movement not plausable.\n");
  5139. goto Sigma_Exit;
  5140. }
  5141. }
  5142. //
  5143. // Do all the preliminary setup work. First raise the probe.
  5144. //
  5145. st_synchronize();
  5146. plan_bed_level_matrix.set_to_identity();
  5147. plan_buffer_line( X_current, Y_current, Z_start_location,
  5148. ext_position,
  5149. homing_feedrate[Z_AXIS]/60,
  5150. active_extruder);
  5151. st_synchronize();
  5152. //
  5153. // Now get everything to the specified probe point So we can safely do a probe to
  5154. // get us close to the bed. If the Z-Axis is far from the bed, we don't want to
  5155. // use that as a starting point for each probe.
  5156. //
  5157. if (verbose_level > 2)
  5158. SERIAL_PROTOCOL("Positioning probe for the test.\n");
  5159. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  5160. ext_position,
  5161. homing_feedrate[X_AXIS]/60,
  5162. active_extruder);
  5163. st_synchronize();
  5164. current_position[X_AXIS] = X_current = st_get_position_mm(X_AXIS);
  5165. current_position[Y_AXIS] = Y_current = st_get_position_mm(Y_AXIS);
  5166. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  5167. current_position[E_AXIS] = ext_position = st_get_position_mm(E_AXIS);
  5168. //
  5169. // OK, do the inital probe to get us close to the bed.
  5170. // Then retrace the right amount and use that in subsequent probes
  5171. //
  5172. int l_feedmultiply = setup_for_endstop_move();
  5173. run_z_probe();
  5174. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  5175. Z_start_location = st_get_position_mm(Z_AXIS) + Z_RAISE_BEFORE_PROBING;
  5176. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  5177. ext_position,
  5178. homing_feedrate[X_AXIS]/60,
  5179. active_extruder);
  5180. st_synchronize();
  5181. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  5182. for( n=0; n<n_samples; n++) {
  5183. do_blocking_move_to( X_probe_location, Y_probe_location, Z_start_location); // Make sure we are at the probe location
  5184. if ( n_legs) {
  5185. double radius=0.0, theta=0.0, x_sweep, y_sweep;
  5186. int rotational_direction, l;
  5187. rotational_direction = (unsigned long) _millis() & 0x0001; // clockwise or counter clockwise
  5188. radius = (unsigned long) _millis() % (long) (X_MAX_LENGTH/4); // limit how far out to go
  5189. theta = (float) ((unsigned long) _millis() % (long) 360) / (360./(2*3.1415926)); // turn into radians
  5190. //SERIAL_ECHOPAIR("starting radius: ",radius);
  5191. //SERIAL_ECHOPAIR(" theta: ",theta);
  5192. //SERIAL_ECHOPAIR(" direction: ",rotational_direction);
  5193. //SERIAL_PROTOCOLLNPGM("");
  5194. for( l=0; l<n_legs-1; l++) {
  5195. if (rotational_direction==1)
  5196. theta += (float) ((unsigned long) _millis() % (long) 20) / (360.0/(2*3.1415926)); // turn into radians
  5197. else
  5198. theta -= (float) ((unsigned long) _millis() % (long) 20) / (360.0/(2*3.1415926)); // turn into radians
  5199. radius += (float) ( ((long) ((unsigned long) _millis() % (long) 10)) - 5);
  5200. if ( radius<0.0 )
  5201. radius = -radius;
  5202. X_current = X_probe_location + cos(theta) * radius;
  5203. Y_current = Y_probe_location + sin(theta) * radius;
  5204. if ( X_current<X_MIN_POS) // Make sure our X & Y are sane
  5205. X_current = X_MIN_POS;
  5206. if ( X_current>X_MAX_POS)
  5207. X_current = X_MAX_POS;
  5208. if ( Y_current<Y_MIN_POS) // Make sure our X & Y are sane
  5209. Y_current = Y_MIN_POS;
  5210. if ( Y_current>Y_MAX_POS)
  5211. Y_current = Y_MAX_POS;
  5212. if (verbose_level>3 ) {
  5213. SERIAL_ECHOPAIR("x: ", X_current);
  5214. SERIAL_ECHOPAIR("y: ", Y_current);
  5215. SERIAL_PROTOCOLLNPGM("");
  5216. }
  5217. do_blocking_move_to( X_current, Y_current, Z_current );
  5218. }
  5219. do_blocking_move_to( X_probe_location, Y_probe_location, Z_start_location); // Go back to the probe location
  5220. }
  5221. int l_feedmultiply = setup_for_endstop_move();
  5222. run_z_probe();
  5223. sample_set[n] = current_position[Z_AXIS];
  5224. //
  5225. // Get the current mean for the data points we have so far
  5226. //
  5227. sum=0.0;
  5228. for( j=0; j<=n; j++) {
  5229. sum = sum + sample_set[j];
  5230. }
  5231. mean = sum / (double (n+1));
  5232. //
  5233. // Now, use that mean to calculate the standard deviation for the
  5234. // data points we have so far
  5235. //
  5236. sum=0.0;
  5237. for( j=0; j<=n; j++) {
  5238. sum = sum + (sample_set[j]-mean) * (sample_set[j]-mean);
  5239. }
  5240. sigma = sqrt( sum / (double (n+1)) );
  5241. if (verbose_level > 1) {
  5242. SERIAL_PROTOCOL(n+1);
  5243. SERIAL_PROTOCOL(" of ");
  5244. SERIAL_PROTOCOL(n_samples);
  5245. SERIAL_PROTOCOLPGM(" z: ");
  5246. SERIAL_PROTOCOL_F(current_position[Z_AXIS], 6);
  5247. }
  5248. if (verbose_level > 2) {
  5249. SERIAL_PROTOCOL(" mean: ");
  5250. SERIAL_PROTOCOL_F(mean,6);
  5251. SERIAL_PROTOCOL(" sigma: ");
  5252. SERIAL_PROTOCOL_F(sigma,6);
  5253. }
  5254. if (verbose_level > 0)
  5255. SERIAL_PROTOCOLPGM("\n");
  5256. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  5257. current_position[E_AXIS], homing_feedrate[Z_AXIS]/60, active_extruder);
  5258. st_synchronize();
  5259. }
  5260. _delay(1000);
  5261. clean_up_after_endstop_move(l_feedmultiply);
  5262. // enable_endstops(true);
  5263. if (verbose_level > 0) {
  5264. SERIAL_PROTOCOLPGM("Mean: ");
  5265. SERIAL_PROTOCOL_F(mean, 6);
  5266. SERIAL_PROTOCOLPGM("\n");
  5267. }
  5268. SERIAL_PROTOCOLPGM("Standard Deviation: ");
  5269. SERIAL_PROTOCOL_F(sigma, 6);
  5270. SERIAL_PROTOCOLPGM("\n\n");
  5271. Sigma_Exit:
  5272. break;
  5273. }
  5274. #endif // Z_PROBE_REPEATABILITY_TEST
  5275. #endif // ENABLE_AUTO_BED_LEVELING
  5276. /*!
  5277. ### M73 - Set/get print progress <a href="https://reprap.org/wiki/G-code#M73:_Set.2FGet_build_percentage">M73: Set/Get build percentage</a>
  5278. #### Usage
  5279. M73 [ P | R | Q | S | C | D ]
  5280. #### Parameters
  5281. - `P` - Percent in normal mode
  5282. - `R` - Time remaining in normal mode
  5283. - `Q` - Percent in silent mode
  5284. - `S` - Time in silent mode
  5285. - `C` - Time to change/pause/user interaction in normal mode
  5286. - `D` - Time to change/pause/user interaction in silent mode
  5287. */
  5288. case 73: //M73 show percent done, time remaining and time to change/pause
  5289. {
  5290. if(code_seen('P')) print_percent_done_normal = code_value_uint8();
  5291. if(code_seen('R')) print_time_remaining_normal = code_value();
  5292. if(code_seen('Q')) print_percent_done_silent = code_value_uint8();
  5293. if(code_seen('S')) print_time_remaining_silent = code_value();
  5294. if(code_seen('C')){
  5295. float print_time_to_change_normal_f = code_value_float();
  5296. print_time_to_change_normal = ( print_time_to_change_normal_f <= 0 ) ? PRINT_TIME_REMAINING_INIT : print_time_to_change_normal_f;
  5297. }
  5298. if(code_seen('D')){
  5299. float print_time_to_change_silent_f = code_value_float();
  5300. print_time_to_change_silent = ( print_time_to_change_silent_f <= 0 ) ? PRINT_TIME_REMAINING_INIT : print_time_to_change_silent_f;
  5301. }
  5302. {
  5303. const char* _msg_mode_done_remain = _N("%S MODE: Percent done: %hhd; print time remaining in mins: %d; Change in mins: %d\n");
  5304. printf_P(_msg_mode_done_remain, _N("NORMAL"), int8_t(print_percent_done_normal), print_time_remaining_normal, print_time_to_change_normal);
  5305. printf_P(_msg_mode_done_remain, _N("SILENT"), int8_t(print_percent_done_silent), print_time_remaining_silent, print_time_to_change_silent);
  5306. }
  5307. break;
  5308. }
  5309. /*!
  5310. ### M104 - Set hotend temperature <a href="https://reprap.org/wiki/G-code#M104:_Set_Extruder_Temperature">M104: Set Extruder Temperature</a>
  5311. #### Usage
  5312. M104 [ S ]
  5313. #### Parameters
  5314. - `S` - Target temperature
  5315. */
  5316. case 104: // M104
  5317. {
  5318. uint8_t extruder;
  5319. if(setTargetedHotend(104,extruder)){
  5320. break;
  5321. }
  5322. if (code_seen('S'))
  5323. {
  5324. setTargetHotendSafe(code_value(), extruder);
  5325. }
  5326. break;
  5327. }
  5328. /*!
  5329. ### M112 - Emergency stop <a href="https://reprap.org/wiki/G-code#M112:_Full_.28Emergency.29_Stop">M112: Full (Emergency) Stop</a>
  5330. It is processed much earlier as to bypass the cmdqueue.
  5331. */
  5332. case 112:
  5333. kill(MSG_M112_KILL, 3);
  5334. break;
  5335. /*!
  5336. ### M140 - Set bed temperature <a href="https://reprap.org/wiki/G-code#M140:_Set_Bed_Temperature_.28Fast.29">M140: Set Bed Temperature (Fast)</a>
  5337. #### Usage
  5338. M140 [ S ]
  5339. #### Parameters
  5340. - `S` - Target temperature
  5341. */
  5342. case 140:
  5343. if (code_seen('S')) setTargetBed(code_value());
  5344. break;
  5345. /*!
  5346. ### M105 - Report temperatures <a href="https://reprap.org/wiki/G-code#M105:_Get_Extruder_Temperature">M105: Get Extruder Temperature</a>
  5347. Prints temperatures:
  5348. - `T:` - Hotend (actual / target)
  5349. - `B:` - Bed (actual / target)
  5350. - `Tx:` - x Tool (actual / target)
  5351. - `@:` - Hotend power
  5352. - `B@:` - Bed power
  5353. - `P:` - PINDAv2 actual (only MK2.5/s and MK3/s)
  5354. - `A:` - Ambient actual (only MK3/s)
  5355. _Example:_
  5356. 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
  5357. */
  5358. case 105:
  5359. {
  5360. uint8_t extruder;
  5361. if(setTargetedHotend(105, extruder)){
  5362. break;
  5363. }
  5364. SERIAL_PROTOCOLPGM("ok ");
  5365. gcode_M105(extruder);
  5366. cmdqueue_pop_front(); //prevent an ok after the command since this command uses an ok at the beginning.
  5367. cmdbuffer_front_already_processed = true;
  5368. break;
  5369. }
  5370. #if defined(AUTO_REPORT)
  5371. /*!
  5372. ### M155 - Automatically send status <a href="https://reprap.org/wiki/G-code#M155:_Automatically_send_temperatures">M155: Automatically send temperatures</a>
  5373. #### Usage
  5374. M155 [ S ] [ C ]
  5375. #### Parameters
  5376. - `S` - Set autoreporting interval in seconds. 0 to disable. Maximum: 255
  5377. - `C` - Activate auto-report function (bit mask). Default is temperature.
  5378. bit 0 = Auto-report temperatures
  5379. bit 1 = Auto-report fans
  5380. bit 2 = Auto-report position
  5381. bit 3 = free
  5382. bit 4 = free
  5383. bit 5 = free
  5384. bit 6 = free
  5385. bit 7 = free
  5386. */
  5387. case 155:
  5388. {
  5389. if (code_seen('S')){
  5390. autoReportFeatures.SetPeriod( code_value_uint8() );
  5391. }
  5392. if (code_seen('C')){
  5393. autoReportFeatures.SetMask(code_value_uint8());
  5394. } else{
  5395. autoReportFeatures.SetMask(1); //Backwards compability to host systems like Octoprint to send only temp if paramerter `C`isn't used.
  5396. }
  5397. }
  5398. break;
  5399. #endif //AUTO_REPORT
  5400. /*!
  5401. ### 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>
  5402. #### Usage
  5403. M104 [ B | R | S ]
  5404. #### Parameters (not mandatory)
  5405. - `S` - Set extruder temperature
  5406. - `R` - Set extruder temperature
  5407. - `B` - Set max. extruder temperature, while `S` is min. temperature. Not active in default, only if AUTOTEMP is defined in source code.
  5408. Parameters S and R are treated identically.
  5409. Command always waits for both cool down and heat up.
  5410. If no parameters are supplied waits for previously set extruder temperature.
  5411. */
  5412. case 109:
  5413. {
  5414. uint8_t extruder;
  5415. if(setTargetedHotend(109, extruder)){
  5416. break;
  5417. }
  5418. LCD_MESSAGERPGM(_T(MSG_HEATING));
  5419. heating_status = HeatingStatus::EXTRUDER_HEATING;
  5420. prusa_statistics(1);
  5421. #ifdef AUTOTEMP
  5422. autotemp_enabled=false;
  5423. #endif
  5424. if (code_seen('S')) {
  5425. setTargetHotendSafe(code_value(), extruder);
  5426. } else if (code_seen('R')) {
  5427. setTargetHotendSafe(code_value(), extruder);
  5428. }
  5429. #ifdef AUTOTEMP
  5430. if (code_seen('S')) autotemp_min=code_value();
  5431. if (code_seen('B')) autotemp_max=code_value();
  5432. if (code_seen('F'))
  5433. {
  5434. autotemp_factor=code_value();
  5435. autotemp_enabled=true;
  5436. }
  5437. #endif
  5438. codenum = _millis();
  5439. /* See if we are heating up or cooling down */
  5440. target_direction = isHeatingHotend(extruder); // true if heating, false if cooling
  5441. cancel_heatup = false;
  5442. wait_for_heater(codenum, extruder); //loops until target temperature is reached
  5443. LCD_MESSAGERPGM(_T(MSG_HEATING_COMPLETE));
  5444. heating_status = HeatingStatus::EXTRUDER_HEATING_COMPLETE;
  5445. prusa_statistics(2);
  5446. //starttime=_millis();
  5447. previous_millis_cmd.start();
  5448. }
  5449. break;
  5450. /*!
  5451. ### 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>
  5452. #### Usage
  5453. M190 [ R | S ]
  5454. #### Parameters (not mandatory)
  5455. - `S` - Set extruder temperature and wait for heating
  5456. - `R` - Set extruder temperature and wait for heating or cooling
  5457. If no parameter is supplied, waits for heating or cooling to previously set temperature.
  5458. */
  5459. case 190:
  5460. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  5461. {
  5462. bool CooldownNoWait = false;
  5463. LCD_MESSAGERPGM(_T(MSG_BED_HEATING));
  5464. heating_status = HeatingStatus::BED_HEATING;
  5465. prusa_statistics(1);
  5466. if (code_seen('S'))
  5467. {
  5468. setTargetBed(code_value());
  5469. CooldownNoWait = true;
  5470. }
  5471. else if (code_seen('R'))
  5472. {
  5473. setTargetBed(code_value());
  5474. }
  5475. codenum = _millis();
  5476. cancel_heatup = false;
  5477. target_direction = isHeatingBed(); // true if heating, false if cooling
  5478. while ( (!cancel_heatup) && (target_direction ? (isHeatingBed()) : (isCoolingBed()&&(CooldownNoWait==false))) )
  5479. {
  5480. if(( _millis() - codenum) > 1000 ) //Print Temp Reading every 1 second while heating up.
  5481. {
  5482. if (!farm_mode) {
  5483. float tt = degHotend(active_extruder);
  5484. SERIAL_PROTOCOLPGM("T:");
  5485. SERIAL_PROTOCOL(tt);
  5486. SERIAL_PROTOCOLPGM(" E:");
  5487. SERIAL_PROTOCOL((int)active_extruder);
  5488. SERIAL_PROTOCOLPGM(" B:");
  5489. SERIAL_PROTOCOL_F(degBed(), 1);
  5490. SERIAL_PROTOCOLLN();
  5491. }
  5492. codenum = _millis();
  5493. }
  5494. manage_heater();
  5495. manage_inactivity();
  5496. lcd_update(0);
  5497. }
  5498. LCD_MESSAGERPGM(_T(MSG_BED_DONE));
  5499. heating_status = HeatingStatus::BED_HEATING_COMPLETE;
  5500. previous_millis_cmd.start();
  5501. }
  5502. #endif
  5503. break;
  5504. #if defined(FAN_PIN) && FAN_PIN > -1
  5505. /*!
  5506. ### M106 - Set fan speed <a href="https://reprap.org/wiki/G-code#M106:_Fan_On">M106: Fan On</a>
  5507. #### Usage
  5508. M106 [ S ]
  5509. #### Parameters
  5510. - `S` - Specifies the duty cycle of the print fan. Allowed values are 0-255. If it's omitted, a value of 255 is used.
  5511. */
  5512. case 106: // M106 Sxxx Fan On S<speed> 0 .. 255
  5513. if (code_seen('S')){
  5514. fanSpeed = code_value_uint8();
  5515. }
  5516. else {
  5517. fanSpeed = 255;
  5518. }
  5519. break;
  5520. /*!
  5521. ### M107 - Fan off <a href="https://reprap.org/wiki/G-code#M107:_Fan_Off">M107: Fan Off</a>
  5522. */
  5523. case 107:
  5524. fanSpeed = 0;
  5525. break;
  5526. #endif //FAN_PIN
  5527. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  5528. /*!
  5529. ### M80 - Turn on the Power Supply <a href="https://reprap.org/wiki/G-code#M80:_ATX_Power_On">M80: ATX Power On</a>
  5530. Only works if the firmware is compiled with PS_ON_PIN defined.
  5531. */
  5532. case 80:
  5533. SET_OUTPUT(PS_ON_PIN); //GND
  5534. WRITE(PS_ON_PIN, PS_ON_AWAKE);
  5535. // If you have a switch on suicide pin, this is useful
  5536. // if you want to start another print with suicide feature after
  5537. // a print without suicide...
  5538. #if defined SUICIDE_PIN && SUICIDE_PIN > -1
  5539. SET_OUTPUT(SUICIDE_PIN);
  5540. WRITE(SUICIDE_PIN, HIGH);
  5541. #endif
  5542. powersupply = true;
  5543. LCD_MESSAGERPGM(MSG_WELCOME);
  5544. lcd_update(0);
  5545. break;
  5546. /*!
  5547. ### M81 - Turn off Power Supply <a href="https://reprap.org/wiki/G-code#M81:_ATX_Power_Off">M81: ATX Power Off</a>
  5548. Only works if the firmware is compiled with PS_ON_PIN defined.
  5549. */
  5550. case 81:
  5551. disable_heater();
  5552. st_synchronize();
  5553. disable_e0();
  5554. disable_e1();
  5555. disable_e2();
  5556. finishAndDisableSteppers();
  5557. fanSpeed = 0;
  5558. _delay(1000); // Wait a little before to switch off
  5559. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  5560. st_synchronize();
  5561. suicide();
  5562. #elif defined(PS_ON_PIN) && PS_ON_PIN > -1
  5563. SET_OUTPUT(PS_ON_PIN);
  5564. WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  5565. #endif
  5566. powersupply = false;
  5567. LCD_MESSAGERPGM(CAT4(CUSTOM_MENDEL_NAME,PSTR(" "),MSG_OFF,PSTR(".")));
  5568. lcd_update(0);
  5569. break;
  5570. #endif
  5571. /*!
  5572. ### 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>
  5573. Makes the extruder interpret extrusion as absolute positions.
  5574. */
  5575. case 82:
  5576. axis_relative_modes &= ~E_AXIS_MASK;
  5577. break;
  5578. /*!
  5579. ### 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>
  5580. Makes the extruder interpret extrusion values as relative positions.
  5581. */
  5582. case 83:
  5583. axis_relative_modes |= E_AXIS_MASK;
  5584. break;
  5585. /*!
  5586. ### M84 - Disable steppers <a href="https://reprap.org/wiki/G-code#M84:_Stop_idle_hold">M84: Stop idle hold</a>
  5587. This command can be used to set the stepper inactivity timeout (`S`) or to disable steppers (`X`,`Y`,`Z`,`E`)
  5588. This command can be used without any additional parameters. In that case all steppers are disabled.
  5589. 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.
  5590. M84 [ S | X | Y | Z | E ]
  5591. - `S` - Seconds
  5592. - `X` - X axis
  5593. - `Y` - Y axis
  5594. - `Z` - Z axis
  5595. - `E` - Extruder
  5596. ### M18 - Disable steppers <a href="https://reprap.org/wiki/G-code#M18:_Disable_all_stepper_motors">M18: Disable all stepper motors</a>
  5597. Equal to M84 (compatibility)
  5598. */
  5599. case 18: //compatibility
  5600. case 84: // M84
  5601. if(code_seen('S')){
  5602. stepper_inactive_time = code_value() * 1000;
  5603. }
  5604. else
  5605. {
  5606. 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])));
  5607. if(all_axis)
  5608. {
  5609. st_synchronize();
  5610. disable_e0();
  5611. disable_e1();
  5612. disable_e2();
  5613. finishAndDisableSteppers();
  5614. }
  5615. else
  5616. {
  5617. st_synchronize();
  5618. if (code_seen('X')) disable_x();
  5619. if (code_seen('Y')) disable_y();
  5620. if (code_seen('Z')) disable_z();
  5621. #if ((E0_ENABLE_PIN != X_ENABLE_PIN) && (E1_ENABLE_PIN != Y_ENABLE_PIN)) // Only enable on boards that have seperate ENABLE_PINS
  5622. if (code_seen('E')) {
  5623. disable_e0();
  5624. disable_e1();
  5625. disable_e2();
  5626. }
  5627. #endif
  5628. }
  5629. }
  5630. break;
  5631. /*!
  5632. ### M85 - Set max inactive time <a href="https://reprap.org/wiki/G-code#M85:_Set_Inactivity_Shutdown_Timer">M85: Set Inactivity Shutdown Timer</a>
  5633. #### Usage
  5634. M85 [ S ]
  5635. #### Parameters
  5636. - `S` - specifies the time in seconds. If a value of 0 is specified, the timer is disabled.
  5637. */
  5638. case 85: // M85
  5639. if(code_seen('S')) {
  5640. max_inactive_time = code_value() * 1000;
  5641. }
  5642. break;
  5643. #ifdef SAFETYTIMER
  5644. /*!
  5645. ### 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>
  5646. When safety timer expires, heatbed and nozzle target temperatures are set to zero.
  5647. #### Usage
  5648. M86 [ S ]
  5649. #### Parameters
  5650. - `S` - specifies the time in seconds. If a value of 0 is specified, the timer is disabled.
  5651. */
  5652. case 86:
  5653. if (code_seen('S')) {
  5654. safetytimer_inactive_time = code_value() * 1000;
  5655. safetyTimer.start();
  5656. }
  5657. break;
  5658. #endif
  5659. /*!
  5660. ### 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>
  5661. 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)
  5662. #### Usage
  5663. M92 [ X | Y | Z | E ]
  5664. #### Parameters
  5665. - `X` - Steps per unit for the X drive
  5666. - `Y` - Steps per unit for the Y drive
  5667. - `Z` - Steps per unit for the Z drive
  5668. - `E` - Steps per unit for the extruder drive
  5669. */
  5670. case 92:
  5671. for(int8_t i=0; i < NUM_AXIS; i++)
  5672. {
  5673. if(code_seen(axis_codes[i]))
  5674. {
  5675. if(i == E_AXIS) { // E
  5676. float value = code_value();
  5677. if(value < 20.0) {
  5678. float factor = cs.axis_steps_per_unit[i] / value; // increase e constants if M92 E14 is given for netfab.
  5679. cs.max_jerk[E_AXIS] *= factor;
  5680. max_feedrate[i] *= factor;
  5681. axis_steps_per_sqr_second[i] *= factor;
  5682. }
  5683. cs.axis_steps_per_unit[i] = value;
  5684. #if defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  5685. fsensor.init();
  5686. #endif //defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  5687. }
  5688. else {
  5689. cs.axis_steps_per_unit[i] = code_value();
  5690. }
  5691. }
  5692. }
  5693. reset_acceleration_rates();
  5694. break;
  5695. /*!
  5696. ### M110 - Set Line number <a href="https://reprap.org/wiki/G-code#M110:_Set_Current_Line_Number">M110: Set Current Line Number</a>
  5697. Sets the line number in G-code
  5698. #### Usage
  5699. M110 [ N ]
  5700. #### Parameters
  5701. - `N` - Line number
  5702. */
  5703. case 110:
  5704. if (code_seen('N'))
  5705. gcode_LastN = code_value_long();
  5706. break;
  5707. /*!
  5708. ### M113 - Get or set host keep-alive interval <a href="https://reprap.org/wiki/G-code#M113:_Host_Keepalive">M113: Host Keepalive</a>
  5709. 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).
  5710. #### Usage
  5711. M113 [ S ]
  5712. #### Parameters
  5713. - `S` - Seconds. Default is 2 seconds between "busy" messages
  5714. */
  5715. case 113:
  5716. if (code_seen('S')) {
  5717. host_keepalive_interval = code_value_uint8();
  5718. // NOMORE(host_keepalive_interval, 60);
  5719. }
  5720. else {
  5721. SERIAL_ECHO_START;
  5722. SERIAL_ECHOPAIR("M113 S", (unsigned long)host_keepalive_interval);
  5723. SERIAL_PROTOCOLLN();
  5724. }
  5725. break;
  5726. /*!
  5727. ### M115 - Firmware info <a href="https://reprap.org/wiki/G-code#M115:_Get_Firmware_Version_and_Capabilities">M115: Get Firmware Version and Capabilities</a>
  5728. Print the firmware info and capabilities
  5729. Without any arguments, prints Prusa firmware version number, machine type, extruder count and UUID.
  5730. `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.
  5731. _Examples:_
  5732. `M115` results:
  5733. `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`
  5734. `M115 V` results:
  5735. `3.8.1`
  5736. `M115 U3.8.2-RC1` results on LCD display for 30s or user interaction:
  5737. `New firmware version available: 3.8.2-RC1 Please upgrade.`
  5738. #### Usage
  5739. M115 [ V | U ]
  5740. #### Parameters
  5741. - V - Report current installed firmware version
  5742. - U - Firmware version provided by G-code to be compared to current one.
  5743. */
  5744. case 115: // M115
  5745. if (code_seen('V')) {
  5746. // Report the Prusa version number.
  5747. SERIAL_PROTOCOLLNRPGM(FW_VERSION_STR_P());
  5748. } else if (code_seen('U')) {
  5749. // Check the firmware version provided. If the firmware version provided by the U code is higher than the currently running firmware,
  5750. // pause the print for 30s and ask the user to upgrade the firmware.
  5751. show_upgrade_dialog_if_version_newer(++ strchr_pointer);
  5752. } else {
  5753. SERIAL_ECHOPGM("FIRMWARE_NAME:Prusa-Firmware ");
  5754. SERIAL_ECHORPGM(FW_VERSION_STR_P());
  5755. SERIAL_ECHOPGM(" based on Marlin FIRMWARE_URL:https://github.com/prusa3d/Prusa-Firmware PROTOCOL_VERSION:");
  5756. SERIAL_ECHOPGM(PROTOCOL_VERSION);
  5757. SERIAL_ECHOPGM(" MACHINE_TYPE:");
  5758. SERIAL_ECHOPGM(CUSTOM_MENDEL_NAME);
  5759. SERIAL_ECHOPGM(" EXTRUDER_COUNT:");
  5760. SERIAL_ECHOPGM(STRINGIFY(EXTRUDERS));
  5761. SERIAL_ECHOPGM(" UUID:");
  5762. SERIAL_ECHOLNPGM(MACHINE_UUID);
  5763. #ifdef EXTENDED_CAPABILITIES_REPORT
  5764. extended_capabilities_report();
  5765. #endif //EXTENDED_CAPABILITIES_REPORT
  5766. }
  5767. break;
  5768. /*!
  5769. ### M114 - Get current position <a href="https://reprap.org/wiki/G-code#M114:_Get_Current_Position">M114: Get Current Position</a>
  5770. */
  5771. case 114:
  5772. gcode_M114();
  5773. break;
  5774. /*
  5775. M117 moved up to get the high priority
  5776. case 117: // M117 display message
  5777. starpos = (strchr(strchr_pointer + 5,'*'));
  5778. if(starpos!=NULL)
  5779. *(starpos)='\0';
  5780. lcd_setstatus(strchr_pointer + 5);
  5781. break;*/
  5782. #ifdef M120_M121_ENABLED
  5783. /*!
  5784. ### M120 - Enable endstops <a href="https://reprap.org/wiki/G-code#M120:_Enable_endstop_detection">M120: Enable endstop detection</a>
  5785. */
  5786. case 120:
  5787. enable_endstops(true) ;
  5788. break;
  5789. /*!
  5790. ### M121 - Disable endstops <a href="https://reprap.org/wiki/G-code#M121:_Disable_endstop_detection">M121: Disable endstop detection</a>
  5791. */
  5792. case 121:
  5793. enable_endstops(false) ;
  5794. break;
  5795. #endif //M120_M121_ENABLED
  5796. /*!
  5797. ### M119 - Get endstop states <a href="https://reprap.org/wiki/G-code#M119:_Get_Endstop_Status">M119: Get Endstop Status</a>
  5798. 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.
  5799. */
  5800. case 119:
  5801. SERIAL_PROTOCOLRPGM(_N("Reporting endstop status"));////MSG_M119_REPORT
  5802. SERIAL_PROTOCOLLN();
  5803. #if defined(X_MIN_PIN) && X_MIN_PIN > -1
  5804. SERIAL_PROTOCOLRPGM(_n("x_min: "));////MSG_X_MIN
  5805. if(READ(X_MIN_PIN)^X_MIN_ENDSTOP_INVERTING){
  5806. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5807. }else{
  5808. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5809. }
  5810. SERIAL_PROTOCOLLN();
  5811. #endif
  5812. #if defined(X_MAX_PIN) && X_MAX_PIN > -1
  5813. SERIAL_PROTOCOLRPGM(_n("x_max: "));////MSG_X_MAX
  5814. if(READ(X_MAX_PIN)^X_MAX_ENDSTOP_INVERTING){
  5815. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5816. }else{
  5817. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5818. }
  5819. SERIAL_PROTOCOLLN();
  5820. #endif
  5821. #if defined(Y_MIN_PIN) && Y_MIN_PIN > -1
  5822. SERIAL_PROTOCOLRPGM(_n("y_min: "));////MSG_Y_MIN
  5823. if(READ(Y_MIN_PIN)^Y_MIN_ENDSTOP_INVERTING){
  5824. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5825. }else{
  5826. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5827. }
  5828. SERIAL_PROTOCOLLN();
  5829. #endif
  5830. #if defined(Y_MAX_PIN) && Y_MAX_PIN > -1
  5831. SERIAL_PROTOCOLRPGM(_n("y_max: "));////MSG_Y_MAX
  5832. if(READ(Y_MAX_PIN)^Y_MAX_ENDSTOP_INVERTING){
  5833. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5834. }else{
  5835. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5836. }
  5837. SERIAL_PROTOCOLLN();
  5838. #endif
  5839. #if defined(Z_MIN_PIN) && Z_MIN_PIN > -1
  5840. SERIAL_PROTOCOLRPGM(MSG_Z_MIN);
  5841. if(READ(Z_MIN_PIN)^Z_MIN_ENDSTOP_INVERTING){
  5842. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5843. }else{
  5844. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5845. }
  5846. SERIAL_PROTOCOLLN();
  5847. #endif
  5848. #if defined(Z_MAX_PIN) && Z_MAX_PIN > -1
  5849. SERIAL_PROTOCOLRPGM(MSG_Z_MAX);
  5850. if(READ(Z_MAX_PIN)^Z_MAX_ENDSTOP_INVERTING){
  5851. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5852. }else{
  5853. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5854. }
  5855. SERIAL_PROTOCOLLN();
  5856. #endif
  5857. break;
  5858. //!@todo update for all axes, use for loop
  5859. #if (defined(FANCHECK) && (((defined(TACH_0) && (TACH_0 >-1)) || (defined(TACH_1) && (TACH_1 > -1)))))
  5860. /*!
  5861. ### M123 - Tachometer value <a href="https://www.reprap.org/wiki/G-code#M123:_Tachometer_value_.28RepRap_.26_Prusa.29">M123: Tachometer value</a>
  5862. This command is used to report fan speeds and fan pwm values.
  5863. #### Usage
  5864. M123
  5865. - E0: - Hotend fan speed in RPM
  5866. - PRN1: - Part cooling fans speed in RPM
  5867. - E0@: - Hotend fan PWM value
  5868. - PRN1@: -Part cooling fan PWM value
  5869. _Example:_
  5870. E0:3240 RPM PRN1:4560 RPM E0@:255 PRN1@:255
  5871. */
  5872. case 123:
  5873. gcode_M123();
  5874. break;
  5875. #endif //FANCHECK and TACH_0 and TACH_1
  5876. #ifdef BLINKM
  5877. /*!
  5878. ### M150 - Set RGB(W) Color <a href="https://reprap.org/wiki/G-code#M150:_Set_LED_color">M150: Set LED color</a>
  5879. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code by defining BLINKM and its dependencies.
  5880. #### Usage
  5881. M150 [ R | U | B ]
  5882. #### Parameters
  5883. - `R` - Red color value
  5884. - `U` - Green color value. It is NOT `G`!
  5885. - `B` - Blue color value
  5886. */
  5887. case 150:
  5888. {
  5889. byte red;
  5890. byte grn;
  5891. byte blu;
  5892. if(code_seen('R')) red = code_value();
  5893. if(code_seen('U')) grn = code_value();
  5894. if(code_seen('B')) blu = code_value();
  5895. SendColors(red,grn,blu);
  5896. }
  5897. break;
  5898. #endif //BLINKM
  5899. /*!
  5900. ### M200 - Set filament diameter <a href="https://reprap.org/wiki/G-code#M200:_Set_filament_diameter">M200: Set filament diameter</a>
  5901. #### Usage
  5902. M200 [ D | T ]
  5903. #### Parameters
  5904. - `D` - Diameter in mm
  5905. - `T` - Number of extruder (MMUs)
  5906. */
  5907. case 200: // M200 D<millimeters> set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).
  5908. {
  5909. uint8_t extruder = active_extruder;
  5910. if(code_seen('T')) {
  5911. extruder = code_value_uint8();
  5912. if(extruder >= EXTRUDERS) {
  5913. SERIAL_ECHO_START;
  5914. SERIAL_ECHO(_n("M200 Invalid extruder "));////MSG_M200_INVALID_EXTRUDER
  5915. break;
  5916. }
  5917. }
  5918. if(code_seen('D')) {
  5919. float diameter = code_value();
  5920. if (diameter == 0.0) {
  5921. // setting any extruder filament size disables volumetric on the assumption that
  5922. // slicers either generate in extruder values as cubic mm or as as filament feeds
  5923. // for all extruders
  5924. cs.volumetric_enabled = false;
  5925. } else {
  5926. cs.filament_size[extruder] = code_value();
  5927. // make sure all extruders have some sane value for the filament size
  5928. cs.filament_size[0] = (cs.filament_size[0] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[0]);
  5929. #if EXTRUDERS > 1
  5930. cs.filament_size[1] = (cs.filament_size[1] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[1]);
  5931. #if EXTRUDERS > 2
  5932. cs.filament_size[2] = (cs.filament_size[2] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[2]);
  5933. #endif
  5934. #endif
  5935. cs.volumetric_enabled = true;
  5936. }
  5937. } else {
  5938. //reserved for setting filament diameter via UFID or filament measuring device
  5939. break;
  5940. }
  5941. calculate_extruder_multipliers();
  5942. }
  5943. break;
  5944. /*!
  5945. ### M201 - Set Print Max Acceleration <a href="https://reprap.org/wiki/G-code#M201:_Set_max_acceleration">M201: Set max printing acceleration</a>
  5946. For each axis individually.
  5947. ##### Usage
  5948. M201 [ X | Y | Z | E ]
  5949. ##### Parameters
  5950. - `X` - Acceleration for X axis in units/s^2
  5951. - `Y` - Acceleration for Y axis in units/s^2
  5952. - `Z` - Acceleration for Z axis in units/s^2
  5953. - `E` - Acceleration for the active or specified extruder in units/s^2
  5954. */
  5955. case 201:
  5956. for (int8_t i = 0; i < NUM_AXIS; i++)
  5957. {
  5958. if (code_seen(axis_codes[i]))
  5959. {
  5960. unsigned long val = code_value();
  5961. #ifdef TMC2130
  5962. unsigned long val_silent = val;
  5963. if ((i == X_AXIS) || (i == Y_AXIS))
  5964. {
  5965. if (val > NORMAL_MAX_ACCEL_XY)
  5966. val = NORMAL_MAX_ACCEL_XY;
  5967. if (val_silent > SILENT_MAX_ACCEL_XY)
  5968. val_silent = SILENT_MAX_ACCEL_XY;
  5969. }
  5970. cs.max_acceleration_units_per_sq_second_normal[i] = val;
  5971. cs.max_acceleration_units_per_sq_second_silent[i] = val_silent;
  5972. #else //TMC2130
  5973. max_acceleration_units_per_sq_second[i] = val;
  5974. #endif //TMC2130
  5975. }
  5976. }
  5977. // 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)
  5978. reset_acceleration_rates();
  5979. break;
  5980. #if 0 // Not used for Sprinter/grbl gen6
  5981. case 202: // M202
  5982. for(int8_t i=0; i < NUM_AXIS; i++) {
  5983. if(code_seen(axis_codes[i])) axis_travel_steps_per_sqr_second[i] = code_value() * cs.axis_steps_per_unit[i];
  5984. }
  5985. break;
  5986. #endif
  5987. /*!
  5988. ### M203 - Set Max Feedrate <a href="https://reprap.org/wiki/G-code#M203:_Set_maximum_feedrate">M203: Set maximum feedrate</a>
  5989. For each axis individually.
  5990. ##### Usage
  5991. M203 [ X | Y | Z | E ]
  5992. ##### Parameters
  5993. - `X` - Maximum feedrate for X axis
  5994. - `Y` - Maximum feedrate for Y axis
  5995. - `Z` - Maximum feedrate for Z axis
  5996. - `E` - Maximum feedrate for extruder drives
  5997. */
  5998. case 203: // M203 max feedrate mm/sec
  5999. for (uint8_t i = 0; i < NUM_AXIS; i++)
  6000. {
  6001. if (code_seen(axis_codes[i]))
  6002. {
  6003. float val = code_value();
  6004. #ifdef TMC2130
  6005. float val_silent = val;
  6006. if ((i == X_AXIS) || (i == Y_AXIS))
  6007. {
  6008. if (val > NORMAL_MAX_FEEDRATE_XY)
  6009. val = NORMAL_MAX_FEEDRATE_XY;
  6010. if (val_silent > SILENT_MAX_FEEDRATE_XY)
  6011. val_silent = SILENT_MAX_FEEDRATE_XY;
  6012. }
  6013. cs.max_feedrate_normal[i] = val;
  6014. cs.max_feedrate_silent[i] = val_silent;
  6015. #else //TMC2130
  6016. max_feedrate[i] = val;
  6017. #endif //TMC2130
  6018. }
  6019. }
  6020. break;
  6021. /*!
  6022. ### M204 - Acceleration settings <a href="https://reprap.org/wiki/G-code#M204:_Set_default_acceleration">M204: Set default acceleration</a>
  6023. #### Old format:
  6024. ##### Usage
  6025. M204 [ S | T ]
  6026. ##### Parameters
  6027. - `S` - normal moves
  6028. - `T` - filmanent only moves
  6029. #### New format:
  6030. ##### Usage
  6031. M204 [ P | R | T ]
  6032. ##### Parameters
  6033. - `P` - printing moves
  6034. - `R` - filmanent only moves
  6035. - `T` - travel moves (as of now T is ignored)
  6036. */
  6037. case 204:
  6038. {
  6039. if(code_seen('S')) {
  6040. // Legacy acceleration format. This format is used by the legacy Marlin, MK2 or MK3 firmware,
  6041. // and it is also generated by Slic3r to control acceleration per extrusion type
  6042. // (there is a separate acceleration settings in Slicer for perimeter, first layer etc).
  6043. cs.acceleration = cs.travel_acceleration = code_value();
  6044. // Interpret the T value as retract acceleration in the old Marlin format.
  6045. if(code_seen('T'))
  6046. cs.retract_acceleration = code_value();
  6047. } else {
  6048. // New acceleration format, compatible with the upstream Marlin.
  6049. if(code_seen('P'))
  6050. cs.acceleration = code_value();
  6051. if(code_seen('R'))
  6052. cs.retract_acceleration = code_value();
  6053. if(code_seen('T'))
  6054. cs.travel_acceleration = code_value();
  6055. }
  6056. }
  6057. break;
  6058. /*!
  6059. ### M205 - Set advanced settings <a href="https://reprap.org/wiki/G-code#M205:_Advanced_settings">M205: Advanced settings</a>
  6060. Set some advanced settings related to movement.
  6061. #### Usage
  6062. M205 [ S | T | B | X | Y | Z | E ]
  6063. #### Parameters
  6064. - `S` - Minimum feedrate for print moves (unit/s)
  6065. - `T` - Minimum feedrate for travel moves (units/s)
  6066. - `B` - Minimum segment time (us)
  6067. - `X` - Maximum X jerk (units/s)
  6068. - `Y` - Maximum Y jerk (units/s)
  6069. - `Z` - Maximum Z jerk (units/s)
  6070. - `E` - Maximum E jerk (units/s)
  6071. */
  6072. case 205:
  6073. {
  6074. if(code_seen('S')) cs.minimumfeedrate = code_value();
  6075. if(code_seen('T')) cs.mintravelfeedrate = code_value();
  6076. if(code_seen('B')) cs.minsegmenttime = code_value() ;
  6077. if(code_seen('X')) cs.max_jerk[X_AXIS] = cs.max_jerk[Y_AXIS] = code_value();
  6078. if(code_seen('Y')) cs.max_jerk[Y_AXIS] = code_value();
  6079. if(code_seen('Z')) cs.max_jerk[Z_AXIS] = code_value();
  6080. if(code_seen('E'))
  6081. {
  6082. float e = code_value();
  6083. #ifndef LA_NOCOMPAT
  6084. e = la10c_jerk(e);
  6085. #endif
  6086. cs.max_jerk[E_AXIS] = e;
  6087. }
  6088. }
  6089. break;
  6090. /*!
  6091. ### M206 - Set additional homing offsets <a href="https://reprap.org/wiki/G-code#M206:_Offset_axes">M206: Offset axes</a>
  6092. #### Usage
  6093. M206 [ X | Y | Z ]
  6094. #### Parameters
  6095. - `X` - X axis offset
  6096. - `Y` - Y axis offset
  6097. - `Z` - Z axis offset
  6098. */
  6099. case 206:
  6100. for(uint8_t i=0; i < 3; i++)
  6101. {
  6102. if(code_seen(axis_codes[i])) cs.add_homing[i] = code_value();
  6103. }
  6104. break;
  6105. #ifdef FWRETRACT
  6106. /*!
  6107. ### M207 - Set firmware retraction <a href="https://reprap.org/wiki/G-code#M207:_Set_retract_length">M207: Set retract length</a>
  6108. #### Usage
  6109. M207 [ S | F | Z ]
  6110. #### Parameters
  6111. - `S` - positive length to retract, in mm
  6112. - `F` - retraction feedrate, in mm/min
  6113. - `Z` - additional zlift/hop
  6114. */
  6115. case 207: //M207 - set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop]
  6116. {
  6117. if(code_seen('S'))
  6118. {
  6119. cs.retract_length = code_value() ;
  6120. }
  6121. if(code_seen('F'))
  6122. {
  6123. cs.retract_feedrate = code_value()/60 ;
  6124. }
  6125. if(code_seen('Z'))
  6126. {
  6127. cs.retract_zlift = code_value() ;
  6128. }
  6129. }break;
  6130. /*!
  6131. ### M208 - Set retract recover length <a href="https://reprap.org/wiki/G-code#M208:_Set_unretract_length">M208: Set unretract length</a>
  6132. #### Usage
  6133. M208 [ S | F ]
  6134. #### Parameters
  6135. - `S` - positive length surplus to the M207 Snnn, in mm
  6136. - `F` - feedrate, in mm/sec
  6137. */
  6138. case 208: // M208 - set retract recover length S[positive mm surplus to the M207 S*] F[feedrate mm/min]
  6139. {
  6140. if(code_seen('S'))
  6141. {
  6142. cs.retract_recover_length = code_value() ;
  6143. }
  6144. if(code_seen('F'))
  6145. {
  6146. cs.retract_recover_feedrate = code_value()/60 ;
  6147. }
  6148. }break;
  6149. /*!
  6150. ### M209 - Enable/disable automatict retract <a href="https://reprap.org/wiki/G-code#M209:_Enable_automatic_retract">M209: Enable automatic retract</a>
  6151. 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.
  6152. #### Usage
  6153. M209 [ S ]
  6154. #### Parameters
  6155. - `S` - 1=true or 0=false
  6156. */
  6157. 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.
  6158. {
  6159. if(code_seen('S'))
  6160. {
  6161. switch(code_value_uint8())
  6162. {
  6163. case 0:
  6164. {
  6165. cs.autoretract_enabled=false;
  6166. retracted[0]=false;
  6167. #if EXTRUDERS > 1
  6168. retracted[1]=false;
  6169. #endif
  6170. #if EXTRUDERS > 2
  6171. retracted[2]=false;
  6172. #endif
  6173. }break;
  6174. case 1:
  6175. {
  6176. cs.autoretract_enabled=true;
  6177. retracted[0]=false;
  6178. #if EXTRUDERS > 1
  6179. retracted[1]=false;
  6180. #endif
  6181. #if EXTRUDERS > 2
  6182. retracted[2]=false;
  6183. #endif
  6184. }break;
  6185. default:
  6186. SERIAL_ECHO_START;
  6187. SERIAL_ECHORPGM(MSG_UNKNOWN_COMMAND);
  6188. SERIAL_ECHO(CMDBUFFER_CURRENT_STRING);
  6189. SERIAL_ECHOLNPGM("\"(1)");
  6190. }
  6191. }
  6192. }break;
  6193. #endif // FWRETRACT
  6194. /*!
  6195. ### M214 - Set Arc configuration values (Use M500 to store in eeprom)
  6196. #### Usage
  6197. M214 [P] [S] [N] [R] [F]
  6198. #### Parameters
  6199. - `P` - A float representing the max and default millimeters per arc segment. Must be greater than 0.
  6200. - `S` - A float representing the minimum allowable millimeters per arc segment. Set to 0 to disable
  6201. - `N` - An int representing the number of arcs to draw before correcting the small angle approximation. Set to 0 to disable.
  6202. - `R` - An int representing the minimum number of segments per arcs of any radius,
  6203. except when the results in segment lengths greater than or less than the minimum
  6204. and maximum segment length. Set to 0 to disable.
  6205. - 'F' - An int representing the number of segments per second, unless this results in segment lengths
  6206. greater than or less than the minimum and maximum segment length. Set to 0 to disable.
  6207. */
  6208. 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>
  6209. {
  6210. // Extract all possible parameters if they appear
  6211. float p = code_seen('P') ? code_value_float() : cs.mm_per_arc_segment;
  6212. float s = code_seen('S') ? code_value_float() : cs.min_mm_per_arc_segment;
  6213. unsigned char n = code_seen('N') ? code_value() : cs.n_arc_correction;
  6214. unsigned short r = code_seen('R') ? code_value() : cs.min_arc_segments;
  6215. unsigned short f = code_seen('F') ? code_value() : cs.arc_segments_per_sec;
  6216. // 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
  6217. if (p <=0 || s < 0 || p < s)
  6218. {
  6219. // Should we display some error here?
  6220. break;
  6221. }
  6222. cs.mm_per_arc_segment = p;
  6223. cs.min_mm_per_arc_segment = s;
  6224. cs.n_arc_correction = n;
  6225. cs.min_arc_segments = r;
  6226. cs.arc_segments_per_sec = f;
  6227. }break;
  6228. #if EXTRUDERS > 1
  6229. /*!
  6230. ### M218 - Set hotend offset <a href="https://reprap.org/wiki/G-code#M218:_Set_Hotend_Offset">M218: Set Hotend Offset</a>
  6231. 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.
  6232. #### Usage
  6233. M218 [ X | Y ]
  6234. #### Parameters
  6235. - `X` - X offset
  6236. - `Y` - Y offset
  6237. */
  6238. case 218: // M218 - set hotend offset (in mm), T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  6239. {
  6240. uint8_t extruder;
  6241. if(setTargetedHotend(218, extruder)){
  6242. break;
  6243. }
  6244. if(code_seen('X'))
  6245. {
  6246. extruder_offset[X_AXIS][extruder] = code_value();
  6247. }
  6248. if(code_seen('Y'))
  6249. {
  6250. extruder_offset[Y_AXIS][extruder] = code_value();
  6251. }
  6252. SERIAL_ECHO_START;
  6253. SERIAL_ECHORPGM(MSG_HOTEND_OFFSET);
  6254. for(extruder = 0; extruder < EXTRUDERS; extruder++)
  6255. {
  6256. SERIAL_ECHO(" ");
  6257. SERIAL_ECHO(extruder_offset[X_AXIS][extruder]);
  6258. SERIAL_ECHO(",");
  6259. SERIAL_ECHO(extruder_offset[Y_AXIS][extruder]);
  6260. }
  6261. SERIAL_ECHOLN("");
  6262. }break;
  6263. #endif
  6264. /*!
  6265. ### 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>
  6266. #### Usage
  6267. M220 [ B | S | R ]
  6268. #### Parameters
  6269. - `B` - Backup current speed factor
  6270. - `S` - Speed factor override percentage (0..100 or higher)
  6271. - `R` - Restore previous speed factor
  6272. */
  6273. case 220: // M220 S<factor in percent>- set speed factor override percentage
  6274. {
  6275. bool codesWereSeen = false;
  6276. if (code_seen('B')) //backup current speed factor
  6277. {
  6278. saved_feedmultiply_mm = feedmultiply;
  6279. codesWereSeen = true;
  6280. }
  6281. if (code_seen('S'))
  6282. {
  6283. feedmultiply = code_value_short();
  6284. codesWereSeen = true;
  6285. }
  6286. if (code_seen('R')) //restore previous feedmultiply
  6287. {
  6288. feedmultiply = saved_feedmultiply_mm;
  6289. codesWereSeen = true;
  6290. }
  6291. if (!codesWereSeen)
  6292. {
  6293. printf_P(PSTR("%i%%\n"), feedmultiply);
  6294. }
  6295. }
  6296. break;
  6297. /*!
  6298. ### 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>
  6299. #### Usage
  6300. M221 [ S | T ]
  6301. #### Parameters
  6302. - `S` - Extrude factor override percentage (0..100 or higher), default 100%
  6303. - `T` - Extruder drive number (Prusa Firmware only), default 0 if not set.
  6304. */
  6305. case 221: // M221 S<factor in percent>- set extrude factor override percentage
  6306. {
  6307. if (code_seen('S'))
  6308. {
  6309. int tmp_code = code_value_short();
  6310. if (code_seen('T'))
  6311. {
  6312. uint8_t extruder;
  6313. if (setTargetedHotend(221, extruder))
  6314. break;
  6315. extruder_multiply[extruder] = tmp_code;
  6316. }
  6317. else
  6318. {
  6319. extrudemultiply = tmp_code ;
  6320. }
  6321. }
  6322. else
  6323. {
  6324. printf_P(PSTR("%i%%\n"), extrudemultiply);
  6325. }
  6326. calculate_extruder_multipliers();
  6327. }
  6328. break;
  6329. /*!
  6330. ### M226 - Wait for Pin state <a href="https://reprap.org/wiki/G-code#M226:_Wait_for_pin_state">M226: Wait for pin state</a>
  6331. Wait until the specified pin reaches the state required
  6332. #### Usage
  6333. M226 [ P | S ]
  6334. #### Parameters
  6335. - `P` - pin number
  6336. - `S` - pin state
  6337. */
  6338. case 226: // M226 P<pin number> S<pin state>- Wait until the specified pin reaches the state required
  6339. {
  6340. if(code_seen('P')){
  6341. int pin_number = code_value_short(); // pin number
  6342. int pin_state = -1; // required pin state - default is inverted
  6343. if(code_seen('S')) pin_state = code_value_short(); // required pin state
  6344. if(pin_state >= -1 && pin_state <= 1){
  6345. for(int8_t i = 0; i < (int8_t)(sizeof(sensitive_pins)/sizeof(sensitive_pins[0])); i++)
  6346. {
  6347. if (((int8_t)pgm_read_byte(&sensitive_pins[i]) == pin_number))
  6348. {
  6349. pin_number = -1;
  6350. break;
  6351. }
  6352. }
  6353. if (pin_number > -1)
  6354. {
  6355. int target = LOW;
  6356. st_synchronize();
  6357. pinMode(pin_number, INPUT);
  6358. switch(pin_state){
  6359. case 1:
  6360. target = HIGH;
  6361. break;
  6362. case 0:
  6363. target = LOW;
  6364. break;
  6365. case -1:
  6366. target = !digitalRead(pin_number);
  6367. break;
  6368. }
  6369. while(digitalRead(pin_number) != target){
  6370. manage_heater();
  6371. manage_inactivity();
  6372. lcd_update(0);
  6373. }
  6374. }
  6375. }
  6376. }
  6377. }
  6378. break;
  6379. #if NUM_SERVOS > 0
  6380. /*!
  6381. ### M280 - Set/Get servo position <a href="https://reprap.org/wiki/G-code#M280:_Set_servo_position">M280: Set servo position</a>
  6382. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  6383. #### Usage
  6384. M280 [ P | S ]
  6385. #### Parameters
  6386. - `P` - Servo index (id)
  6387. - `S` - Target position
  6388. */
  6389. case 280: // M280 - set servo position absolute. P: servo index, S: angle or microseconds
  6390. {
  6391. int servo_index = -1;
  6392. int servo_position = 0;
  6393. if (code_seen('P'))
  6394. servo_index = code_value();
  6395. if (code_seen('S')) {
  6396. servo_position = code_value();
  6397. if ((servo_index >= 0) && (servo_index < NUM_SERVOS)) {
  6398. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  6399. servos[servo_index].attach(0);
  6400. #endif
  6401. servos[servo_index].write(servo_position);
  6402. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  6403. _delay(PROBE_SERVO_DEACTIVATION_DELAY);
  6404. servos[servo_index].detach();
  6405. #endif
  6406. }
  6407. else {
  6408. SERIAL_ECHO_START;
  6409. SERIAL_ECHO("Servo ");
  6410. SERIAL_ECHO(servo_index);
  6411. SERIAL_ECHOLN(" out of range");
  6412. }
  6413. }
  6414. else if (servo_index >= 0) {
  6415. SERIAL_PROTOCOL(MSG_OK);
  6416. SERIAL_PROTOCOL(" Servo ");
  6417. SERIAL_PROTOCOL(servo_index);
  6418. SERIAL_PROTOCOL(": ");
  6419. SERIAL_PROTOCOLLN(servos[servo_index].read());
  6420. }
  6421. }
  6422. break;
  6423. #endif // NUM_SERVOS > 0
  6424. #if (LARGE_FLASH == true && ( BEEPER > 0 || defined(ULTRALCD) || defined(LCD_USE_I2C_BUZZER)))
  6425. /*!
  6426. ### M300 - Play tone <a href="https://reprap.org/wiki/G-code#M300:_Play_beep_sound">M300: Play beep sound</a>
  6427. In Prusa Firmware the defaults are `100Hz` and `1000ms`, so that `M300` without parameters will beep for a second.
  6428. #### Usage
  6429. M300 [ S | P ]
  6430. #### Parameters
  6431. - `S` - frequency in Hz. Not all firmware versions support this parameter
  6432. - `P` - duration in milliseconds
  6433. */
  6434. case 300: // M300
  6435. {
  6436. uint16_t beepS = code_seen('S') ? code_value() : 0;
  6437. uint16_t beepP = code_seen('P') ? code_value() : 1000;
  6438. #if BEEPER > 0
  6439. if (beepP > 0)
  6440. Sound_MakeCustom(beepP,beepS,false);
  6441. #endif
  6442. }
  6443. break;
  6444. #endif // M300
  6445. #ifdef PIDTEMP
  6446. /*!
  6447. ### M301 - Set hotend PID <a href="https://reprap.org/wiki/G-code#M301:_Set_PID_parameters">M301: Set PID parameters</a>
  6448. Sets Proportional (P), Integral (I) and Derivative (D) values for hot end.
  6449. See also <a href="https://reprap.org/wiki/PID_Tuning">PID Tuning.</a>
  6450. #### Usage
  6451. M301 [ P | I | D ]
  6452. #### Parameters
  6453. - `P` - proportional (Kp)
  6454. - `I` - integral (Ki)
  6455. - `D` - derivative (Kd)
  6456. */
  6457. case 301:
  6458. {
  6459. if(code_seen('P')) cs.Kp = code_value();
  6460. if(code_seen('I')) cs.Ki = scalePID_i(code_value());
  6461. if(code_seen('D')) cs.Kd = scalePID_d(code_value());
  6462. updatePID();
  6463. SERIAL_PROTOCOLRPGM(MSG_OK);
  6464. SERIAL_PROTOCOLPGM(" p:");
  6465. SERIAL_PROTOCOL(cs.Kp);
  6466. SERIAL_PROTOCOLPGM(" i:");
  6467. SERIAL_PROTOCOL(unscalePID_i(cs.Ki));
  6468. SERIAL_PROTOCOLPGM(" d:");
  6469. SERIAL_PROTOCOL(unscalePID_d(cs.Kd));
  6470. SERIAL_PROTOCOLLN();
  6471. }
  6472. break;
  6473. #endif //PIDTEMP
  6474. #ifdef PIDTEMPBED
  6475. /*!
  6476. ### M304 - Set bed PID <a href="https://reprap.org/wiki/G-code#M304:_Set_PID_parameters_-_Bed">M304: Set PID parameters - Bed</a>
  6477. Sets Proportional (P), Integral (I) and Derivative (D) values for bed.
  6478. See also <a href="https://reprap.org/wiki/PID_Tuning">PID Tuning.</a>
  6479. #### Usage
  6480. M304 [ P | I | D ]
  6481. #### Parameters
  6482. - `P` - proportional (Kp)
  6483. - `I` - integral (Ki)
  6484. - `D` - derivative (Kd)
  6485. */
  6486. case 304:
  6487. {
  6488. if(code_seen('P')) cs.bedKp = code_value();
  6489. if(code_seen('I')) cs.bedKi = scalePID_i(code_value());
  6490. if(code_seen('D')) cs.bedKd = scalePID_d(code_value());
  6491. updatePID();
  6492. SERIAL_PROTOCOLRPGM(MSG_OK);
  6493. SERIAL_PROTOCOLPGM(" p:");
  6494. SERIAL_PROTOCOL(cs.bedKp);
  6495. SERIAL_PROTOCOLPGM(" i:");
  6496. SERIAL_PROTOCOL(unscalePID_i(cs.bedKi));
  6497. SERIAL_PROTOCOLPGM(" d:");
  6498. SERIAL_PROTOCOLLN(unscalePID_d(cs.bedKd));
  6499. }
  6500. break;
  6501. #endif //PIDTEMP
  6502. /*!
  6503. ### M240 - Trigger camera <a href="https://reprap.org/wiki/G-code#M240:_Trigger_camera">M240: Trigger camera</a>
  6504. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  6505. You need to (re)define and assign `CHDK` or `PHOTOGRAPH_PIN` the correct pin number to be able to use the feature.
  6506. */
  6507. case 240: // M240 Triggers a camera by emulating a Canon RC-1 : http://www.doc-diy.net/photo/rc-1_hacked/
  6508. {
  6509. #ifdef CHDK
  6510. SET_OUTPUT(CHDK);
  6511. WRITE(CHDK, HIGH);
  6512. chdkHigh = _millis();
  6513. chdkActive = true;
  6514. #else
  6515. #if defined(PHOTOGRAPH_PIN) && PHOTOGRAPH_PIN > -1
  6516. const uint8_t NUM_PULSES=16;
  6517. const float PULSE_LENGTH=0.01524;
  6518. for(int i=0; i < NUM_PULSES; i++) {
  6519. WRITE(PHOTOGRAPH_PIN, HIGH);
  6520. _delay_ms(PULSE_LENGTH);
  6521. WRITE(PHOTOGRAPH_PIN, LOW);
  6522. _delay_ms(PULSE_LENGTH);
  6523. }
  6524. _delay(7.33);
  6525. for(int i=0; i < NUM_PULSES; i++) {
  6526. WRITE(PHOTOGRAPH_PIN, HIGH);
  6527. _delay_ms(PULSE_LENGTH);
  6528. WRITE(PHOTOGRAPH_PIN, LOW);
  6529. _delay_ms(PULSE_LENGTH);
  6530. }
  6531. #endif
  6532. #endif //chdk end if
  6533. }
  6534. break;
  6535. #ifdef PREVENT_DANGEROUS_EXTRUDE
  6536. /*!
  6537. ### 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>
  6538. 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.
  6539. #### Usage
  6540. M302 [ S ]
  6541. #### Parameters
  6542. - `S` - Cold extrude minimum temperature
  6543. */
  6544. case 302:
  6545. {
  6546. int temp = 0;
  6547. if (code_seen('S')) temp=code_value_short();
  6548. set_extrude_min_temp(temp);
  6549. }
  6550. break;
  6551. #endif
  6552. /*!
  6553. ### M303 - PID autotune <a href="https://reprap.org/wiki/G-code#M303:_Run_PID_tuning">M303: Run PID tuning</a>
  6554. 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.
  6555. #### Usage
  6556. M303 [ E | S | C ]
  6557. #### Parameters
  6558. - `E` - Extruder, default `E0`. Use `E-1` to calibrate the bed PID
  6559. - `S` - Target temperature, default `210°C` for hotend, 70 for bed
  6560. - `C` - Cycles, default `5`
  6561. */
  6562. case 303:
  6563. {
  6564. float temp = 150.0;
  6565. int e = 0;
  6566. int c = 5;
  6567. if (code_seen('E')) e = code_value_short();
  6568. if (e < 0)
  6569. temp = 70;
  6570. if (code_seen('S')) temp = code_value();
  6571. if (code_seen('C')) c = code_value_short();
  6572. PID_autotune(temp, e, c);
  6573. }
  6574. break;
  6575. #ifdef TEMP_MODEL
  6576. /*!
  6577. ### M310 - Temperature model settings <a href="https://reprap.org/wiki/G-code#M310:_Temperature_model_settings">M310: Temperature model settings</a>
  6578. #### Usage
  6579. M310 ; report values
  6580. M310 [ A ] [ F ] ; autotune
  6581. M310 [ S ] ; set 0=disable 1=enable
  6582. M310 [ I ] [ R ] ; set resistance at index
  6583. M310 [ P | C ] ; set power, capacitance
  6584. M310 [ B | E | W ] ; set beeper, warning and error threshold
  6585. M310 [ T ] ; set ambient temperature correction
  6586. #### Parameters
  6587. - `I` - resistance index position (0-15)
  6588. - `R` - resistance value at index (K/W; requires `I`)
  6589. - `P` - power (W)
  6590. - `C` - capacitance (J/K)
  6591. - `S` - set 0=disable 1=enable
  6592. - `B` - beep and warn when reaching warning threshold 0=disable 1=enable (default: 1)
  6593. - `E` - error threshold (K/s; default in variant)
  6594. - `W` - warning threshold (K/s; default in variant)
  6595. - `T` - ambient temperature correction (K; default in variant)
  6596. - `A` - autotune C+R values
  6597. - `F` - force model self-test state (0=off 1=on) during autotune using current values
  6598. */
  6599. case 310:
  6600. {
  6601. // parse all parameters
  6602. float P = NAN, C = NAN, R = NAN, E = NAN, W = NAN, T = NAN;
  6603. int8_t I = -1, S = -1, B = -1, A = -1, F = -1;
  6604. if(code_seen('C')) C = code_value();
  6605. if(code_seen('P')) P = code_value();
  6606. if(code_seen('I')) I = code_value_short();
  6607. if(code_seen('R')) R = code_value();
  6608. if(code_seen('S')) S = code_value_short();
  6609. if(code_seen('B')) B = code_value_short();
  6610. if(code_seen('E')) E = code_value();
  6611. if(code_seen('W')) W = code_value();
  6612. if(code_seen('T')) T = code_value();
  6613. if(code_seen('A')) A = code_value_short();
  6614. if(code_seen('F')) F = code_value_short();
  6615. // report values if nothing has been requested
  6616. if(isnan(C) && isnan(P) && isnan(R) && isnan(E) && isnan(W) && isnan(T) && I < 0 && S < 0 && B < 0 && A < 0) {
  6617. temp_model_report_settings();
  6618. break;
  6619. }
  6620. // update all parameters
  6621. if(B >= 0) temp_model_set_warn_beep(B);
  6622. if(!isnan(C) || !isnan(P) || !isnan(T) || !isnan(W) || !isnan(E)) temp_model_set_params(C, P, T, W, E);
  6623. if(I >= 0 && !isnan(R)) temp_model_set_resistance(I, R);
  6624. // enable the model last, if requested
  6625. if(S >= 0) temp_model_set_enabled(S);
  6626. // run autotune
  6627. if(A >= 0) temp_model_autotune(A, F > 0);
  6628. }
  6629. break;
  6630. #endif
  6631. /*!
  6632. ### 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>
  6633. Finishes all current moves and and thus clears the buffer.
  6634. Equivalent to `G4` with no parameters.
  6635. */
  6636. case 400:
  6637. {
  6638. st_synchronize();
  6639. }
  6640. break;
  6641. /*!
  6642. ### 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>
  6643. Currently three different materials are needed (default, flex and PVA).
  6644. And storing this information for different load/unload profiles etc. in the future firmware does not have to wait for "ok" from MMU.
  6645. #### Usage
  6646. M403 [ E | F ]
  6647. #### Parameters
  6648. - `E` - Extruder number. 0-indexed.
  6649. - `F` - Filament type
  6650. */
  6651. case 403:
  6652. {
  6653. // currently three different materials are needed (default, flex and PVA)
  6654. // add storing this information for different load/unload profiles etc. in the future
  6655. if (MMU2::mmu2.Enabled())
  6656. {
  6657. uint8_t extruder = 255;
  6658. uint8_t filament = FILAMENT_UNDEFINED;
  6659. if(code_seen('E')) extruder = code_value_uint8();
  6660. if(code_seen('F')) filament = code_value_uint8();
  6661. MMU2::mmu2.set_filament_type(extruder, filament);
  6662. }
  6663. }
  6664. break;
  6665. /*!
  6666. ### 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>
  6667. Save current parameters to EEPROM.
  6668. */
  6669. case 500:
  6670. {
  6671. Config_StoreSettings();
  6672. }
  6673. break;
  6674. /*!
  6675. ### M501 - Read settings from EEPROM <a href="https://reprap.org/wiki/G-code#M501:_Read_parameters_from_EEPROM">M501: Read parameters from EEPROM</a>
  6676. Set the active parameters to those stored in the EEPROM. This is useful to revert parameters after experimenting with them.
  6677. */
  6678. case 501:
  6679. {
  6680. Config_RetrieveSettings();
  6681. }
  6682. break;
  6683. /*!
  6684. ### M502 - Revert all settings to factory default <a href="https://reprap.org/wiki/G-code#M502:_Restore_Default_Settings">M502: Restore Default Settings</a>
  6685. 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.
  6686. */
  6687. case 502:
  6688. {
  6689. Config_ResetDefault();
  6690. }
  6691. break;
  6692. /*!
  6693. ### M503 - Repport all settings currently in memory <a href="https://reprap.org/wiki/G-code#M503:_Report_Current_Settings">M503: Report Current Settings</a>
  6694. 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.
  6695. */
  6696. case 503:
  6697. {
  6698. Config_PrintSettings();
  6699. }
  6700. break;
  6701. /*!
  6702. ### M509 - Force language selection <a href="https://reprap.org/wiki/G-code#M509:_Force_language_selection">M509: Force language selection</a>
  6703. Resets the language to English.
  6704. Only on Original Prusa i3 MK2.5/s and MK3/s with multiple languages.
  6705. */
  6706. case 509:
  6707. {
  6708. lang_reset();
  6709. SERIAL_ECHO_START;
  6710. SERIAL_PROTOCOLPGM(("LANG SEL FORCED"));
  6711. }
  6712. break;
  6713. #ifdef ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED
  6714. /*!
  6715. ### 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>
  6716. 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`.
  6717. #### Usage
  6718. M540 [ S ]
  6719. #### Parameters
  6720. - `S` - disabled=0, enabled=1
  6721. */
  6722. case 540:
  6723. {
  6724. if(code_seen('S')) abort_on_endstop_hit = code_value() > 0;
  6725. }
  6726. break;
  6727. #endif
  6728. #ifdef ENABLE_AUTO_BED_LEVELING
  6729. /*!
  6730. ### M851 - Set Z-Probe Offset <a href="https://reprap.org/wiki/G-code#M851:_Set_Z-Probe_Offset">M851: Set Z-Probe Offset"</a>
  6731. 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.
  6732. 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.)
  6733. #### Usage
  6734. M851 [ Z ]
  6735. #### Parameters
  6736. - `Z` - Z offset probe to nozzle.
  6737. */
  6738. #ifdef CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  6739. case CUSTOM_M_CODE_SET_Z_PROBE_OFFSET:
  6740. {
  6741. float value;
  6742. if (code_seen('Z'))
  6743. {
  6744. value = code_value();
  6745. if ((Z_PROBE_OFFSET_RANGE_MIN <= value) && (value <= Z_PROBE_OFFSET_RANGE_MAX))
  6746. {
  6747. cs.zprobe_zoffset = -value; // compare w/ line 278 of ConfigurationStore.cpp
  6748. SERIAL_ECHO_START;
  6749. SERIAL_ECHOLNRPGM(CAT4(MSG_ZPROBE_ZOFFSET, " ", MSG_OK,PSTR("")));
  6750. SERIAL_PROTOCOLLN();
  6751. }
  6752. else
  6753. {
  6754. SERIAL_ECHO_START;
  6755. SERIAL_ECHORPGM(MSG_ZPROBE_ZOFFSET);
  6756. SERIAL_ECHORPGM(MSG_Z_MIN);
  6757. SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MIN);
  6758. SERIAL_ECHORPGM(MSG_Z_MAX);
  6759. SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MAX);
  6760. SERIAL_PROTOCOLLN();
  6761. }
  6762. }
  6763. else
  6764. {
  6765. SERIAL_ECHO_START;
  6766. SERIAL_ECHOLNRPGM(CAT2(MSG_ZPROBE_ZOFFSET, PSTR(" : ")));
  6767. SERIAL_ECHO(-cs.zprobe_zoffset);
  6768. SERIAL_PROTOCOLLN();
  6769. }
  6770. break;
  6771. }
  6772. #endif // CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  6773. #endif // ENABLE_AUTO_BED_LEVELING
  6774. /*!
  6775. ### 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>
  6776. Sets the printer IP address that is shown in the support menu. Designed to be used with the help of host software.
  6777. If P is not specified nothing happens.
  6778. 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.
  6779. #### Usage
  6780. M552 [ P<IP_address> ]
  6781. #### Parameters
  6782. - `P` - The IP address in xxx.xxx.xxx.xxx format. Eg: P192.168.1.14
  6783. */
  6784. case 552:
  6785. {
  6786. if (code_seen('P'))
  6787. {
  6788. uint8_t valCnt = 0;
  6789. IP_address = 0;
  6790. do
  6791. {
  6792. *strchr_pointer = '*';
  6793. ((uint8_t*)&IP_address)[valCnt] = code_value_short();
  6794. valCnt++;
  6795. } while ((valCnt < 4) && code_seen('.'));
  6796. if (valCnt != 4)
  6797. IP_address = 0;
  6798. }
  6799. } break;
  6800. #ifdef FILAMENTCHANGEENABLE
  6801. /*!
  6802. ### M600 - Initiate Filament change procedure <a href="https://reprap.org/wiki/G-code#M600:_Filament_change_pause">M600: Filament change pause</a>
  6803. Initiates Filament change, it is also used during Filament Runout Sensor process.
  6804. If the `M600` is triggered under 25mm it will do a Z-lift of 25mm to prevent a filament blob.
  6805. #### Usage
  6806. M600 [ X | Y | Z | E | L | AUTO ]
  6807. - `X` - X position, default 211
  6808. - `Y` - Y position, default 0
  6809. - `Z` - relative lift Z, default MIN_Z_FOR_SWAP.
  6810. - `E` - initial retract, default -2
  6811. - `L` - later retract distance for removal, default -80
  6812. - `AUTO` - Automatically (only with MMU)
  6813. */
  6814. case 600: //Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  6815. {
  6816. st_synchronize();
  6817. float x_position = current_position[X_AXIS];
  6818. float y_position = current_position[Y_AXIS];
  6819. float z_shift = MIN_Z_FOR_SWAP;
  6820. float e_shift_init = 0;
  6821. float e_shift_late = 0;
  6822. bool automatic = false;
  6823. //Retract extruder
  6824. if(code_seen('E'))
  6825. {
  6826. e_shift_init = code_value();
  6827. }
  6828. else
  6829. {
  6830. #ifdef FILAMENTCHANGE_FIRSTRETRACT
  6831. e_shift_init = FILAMENTCHANGE_FIRSTRETRACT ;
  6832. #endif
  6833. }
  6834. //currently don't work as we are using the same unload sequence as in M702, needs re-work
  6835. if (code_seen('L'))
  6836. {
  6837. e_shift_late = code_value();
  6838. }
  6839. else
  6840. {
  6841. #ifdef FILAMENTCHANGE_FINALRETRACT
  6842. e_shift_late = FILAMENTCHANGE_FINALRETRACT;
  6843. #endif
  6844. }
  6845. // Z lift. For safety only allow positive values
  6846. if (code_seen('Z')) z_shift = fabs(code_value());
  6847. //Move XY to side
  6848. if(code_seen('X'))
  6849. {
  6850. x_position = code_value();
  6851. }
  6852. else
  6853. {
  6854. #ifdef FILAMENTCHANGE_XPOS
  6855. x_position = FILAMENTCHANGE_XPOS;
  6856. #endif
  6857. }
  6858. if(code_seen('Y'))
  6859. {
  6860. y_position = code_value();
  6861. }
  6862. else
  6863. {
  6864. #ifdef FILAMENTCHANGE_YPOS
  6865. y_position = FILAMENTCHANGE_YPOS ;
  6866. #endif
  6867. }
  6868. if (MMU2::mmu2.Enabled() && code_seen_P(PSTR("AUTO")))
  6869. automatic = true;
  6870. gcode_M600(automatic, x_position, y_position, z_shift, e_shift_init, e_shift_late);
  6871. }
  6872. break;
  6873. #endif //FILAMENTCHANGEENABLE
  6874. /*!
  6875. ### M601 - Pause print <a href="https://reprap.org/wiki/G-code#M601:_Pause_print">M601: Pause print</a>
  6876. */
  6877. /*!
  6878. ### M125 - Pause print (TODO: not implemented)
  6879. */
  6880. /*!
  6881. ### M25 - Pause SD print <a href="https://reprap.org/wiki/G-code#M25:_Pause_SD_print">M25: Pause SD print</a>
  6882. */
  6883. case 25:
  6884. case 601:
  6885. {
  6886. if (!isPrintPaused) {
  6887. st_synchronize();
  6888. ClearToSend(); //send OK even before the command finishes executing because we want to make sure it is not skipped because of cmdqueue_pop_front();
  6889. cmdqueue_pop_front(); //trick because we want skip this command (M601) after restore
  6890. lcd_pause_print();
  6891. }
  6892. }
  6893. break;
  6894. /*!
  6895. ### M602 - Resume print <a href="https://reprap.org/wiki/G-code#M602:_Resume_print">M602: Resume print</a>
  6896. */
  6897. case 602:
  6898. {
  6899. if (isPrintPaused) lcd_resume_print();
  6900. }
  6901. break;
  6902. /*!
  6903. ### M603 - Stop print <a href="https://reprap.org/wiki/G-code#M603:_Stop_print">M603: Stop print</a>
  6904. */
  6905. case 603: {
  6906. lcd_print_stop();
  6907. }
  6908. break;
  6909. #ifdef PINDA_THERMISTOR
  6910. /*!
  6911. ### 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>
  6912. Wait for PINDA thermistor to reach target temperature
  6913. #### Usage
  6914. M860 [ S ]
  6915. #### Parameters
  6916. - `S` - Target temperature
  6917. */
  6918. case 860:
  6919. {
  6920. int set_target_pinda = 0;
  6921. if (code_seen('S')) {
  6922. set_target_pinda = code_value_short();
  6923. }
  6924. else {
  6925. break;
  6926. }
  6927. LCD_MESSAGERPGM(_T(MSG_PLEASE_WAIT));
  6928. SERIAL_PROTOCOLPGM("Wait for PINDA target temperature:");
  6929. SERIAL_PROTOCOLLN(set_target_pinda);
  6930. codenum = _millis();
  6931. cancel_heatup = false;
  6932. bool is_pinda_cooling = false;
  6933. if ((degTargetBed() == 0) && (degTargetHotend(0) == 0)) {
  6934. is_pinda_cooling = true;
  6935. }
  6936. while ( ((!is_pinda_cooling) && (!cancel_heatup) && (current_temperature_pinda < set_target_pinda)) || (is_pinda_cooling && (current_temperature_pinda > set_target_pinda)) ) {
  6937. if ((_millis() - codenum) > 1000) //Print Temp Reading every 1 second while waiting.
  6938. {
  6939. SERIAL_PROTOCOLPGM("P:");
  6940. SERIAL_PROTOCOL_F(current_temperature_pinda, 1);
  6941. SERIAL_PROTOCOL('/');
  6942. SERIAL_PROTOCOLLN(set_target_pinda);
  6943. codenum = _millis();
  6944. }
  6945. manage_heater();
  6946. manage_inactivity();
  6947. lcd_update(0);
  6948. }
  6949. LCD_MESSAGERPGM(MSG_OK);
  6950. break;
  6951. }
  6952. /*!
  6953. ### 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>
  6954. Set compensation ustep value `S` for compensation table index `I`.
  6955. #### Usage
  6956. M861 [ ? | ! | Z | S | I ]
  6957. #### Parameters
  6958. - `?` - Print current EEPROM offset values
  6959. - `!` - Set factory default values
  6960. - `Z` - Set all values to 0 (effectively disabling PINDA temperature compensation)
  6961. - `S` - Microsteps
  6962. - `I` - Table index
  6963. */
  6964. case 861: {
  6965. const char * const _header = PSTR("index, temp, ustep, um");
  6966. if (code_seen('?')) { // ? - Print out current EEPROM offset values
  6967. int16_t usteps = 0;
  6968. SERIAL_PROTOCOLPGM("PINDA cal status: ");
  6969. SERIAL_PROTOCOLLN(calibration_status_pinda());
  6970. SERIAL_PROTOCOLLNRPGM(_header);
  6971. for (uint8_t i = 0; i < 6; i++)
  6972. {
  6973. if(i > 0) {
  6974. usteps = eeprom_read_word((uint16_t*) EEPROM_PROBE_TEMP_SHIFT + (i - 1));
  6975. }
  6976. float mm = ((float)usteps) / cs.axis_steps_per_unit[Z_AXIS];
  6977. i == 0 ? SERIAL_PROTOCOLPGM("n/a") : SERIAL_PROTOCOL(i - 1);
  6978. SERIAL_PROTOCOLPGM(", ");
  6979. SERIAL_PROTOCOL(35 + (i * 5));
  6980. SERIAL_PROTOCOLPGM(", ");
  6981. SERIAL_PROTOCOL(usteps);
  6982. SERIAL_PROTOCOLPGM(", ");
  6983. SERIAL_PROTOCOLLN(mm * 1000);
  6984. }
  6985. }
  6986. else if (code_seen('!')) { // ! - Set factory default values
  6987. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  6988. int16_t z_shift = 8; //40C - 20um - 8usteps
  6989. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT, z_shift);
  6990. z_shift = 24; //45C - 60um - 24usteps
  6991. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + 1, z_shift);
  6992. z_shift = 48; //50C - 120um - 48usteps
  6993. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + 2, z_shift);
  6994. z_shift = 80; //55C - 200um - 80usteps
  6995. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + 3, z_shift);
  6996. z_shift = 120; //60C - 300um - 120usteps
  6997. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + 4, z_shift);
  6998. SERIAL_PROTOCOLLNPGM("factory restored");
  6999. }
  7000. else if (code_seen('Z')) { // Z - Set all values to 0 (effectively disabling PINDA temperature compensation)
  7001. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  7002. int16_t z_shift = 0;
  7003. for (uint8_t i = 0; i < 5; i++) {
  7004. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  7005. }
  7006. SERIAL_PROTOCOLLNPGM("zerorized");
  7007. }
  7008. else if (code_seen('S')) { // Sxxx Iyyy - Set compensation ustep value S for compensation table index I
  7009. int16_t usteps = code_value_short();
  7010. if (code_seen('I')) {
  7011. uint8_t index = code_value_uint8();
  7012. if (index < 5) {
  7013. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + index, usteps);
  7014. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  7015. SERIAL_PROTOCOLLNRPGM(_header);
  7016. for (uint8_t i = 0; i < 6; i++)
  7017. {
  7018. usteps = 0;
  7019. if (i > 0) {
  7020. usteps = eeprom_read_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + (i - 1));
  7021. }
  7022. float mm = ((float)usteps) / cs.axis_steps_per_unit[Z_AXIS];
  7023. i == 0 ? SERIAL_PROTOCOLPGM("n/a") : SERIAL_PROTOCOL(i - 1);
  7024. SERIAL_PROTOCOLPGM(", ");
  7025. SERIAL_PROTOCOL(35 + (i * 5));
  7026. SERIAL_PROTOCOLPGM(", ");
  7027. SERIAL_PROTOCOL(usteps);
  7028. SERIAL_PROTOCOLPGM(", ");
  7029. SERIAL_PROTOCOLLN(mm * 1000);
  7030. }
  7031. }
  7032. }
  7033. }
  7034. else {
  7035. SERIAL_PROTOCOLLNPGM("no valid command");
  7036. }
  7037. } break;
  7038. #endif //PINDA_THERMISTOR
  7039. /*!
  7040. ### M862 - Print checking <a href="https://reprap.org/wiki/G-code#M862:_Print_checking">M862: Print checking</a>
  7041. Checks the parameters of the printer and gcode and performs compatibility check
  7042. - M862.1 { P<nozzle_diameter> | Q } 0.25/0.40/0.60
  7043. - M862.2 { P<model_code> | Q }
  7044. - M862.3 { P"<model_name>" | Q }
  7045. - M862.4 { P<fw_version> | Q }
  7046. - M862.5 { P<gcode_level> | Q }
  7047. When run with P<> argument, the check is performed against the input value.
  7048. When run with Q argument, the current value is shown.
  7049. M862.3 accepts text identifiers of printer types too.
  7050. The syntax of M862.3 is (note the quotes around the type):
  7051. M862.3 P "MK3S"
  7052. Accepted printer type identifiers and their numeric counterparts:
  7053. - MK1 (100)
  7054. - MK2 (200)
  7055. - MK2MM (201)
  7056. - MK2S (202)
  7057. - MK2SMM (203)
  7058. - MK2.5 (250)
  7059. - MK2.5MMU2 (20250)
  7060. - MK2.5S (252)
  7061. - MK2.5SMMU2S (20252)
  7062. - MK3 (300)
  7063. - MK3MMU2 (20300)
  7064. - MK3S (302)
  7065. - MK3SMMU2S (20302)
  7066. */
  7067. case 862: // M862: print checking
  7068. float nDummy;
  7069. uint8_t nCommand;
  7070. nCommand=(uint8_t)(modff(code_value_float(),&nDummy)*10.0+0.5);
  7071. switch((ClPrintChecking)nCommand)
  7072. {
  7073. case ClPrintChecking::_Nozzle: // ~ .1
  7074. uint16_t nDiameter;
  7075. if(code_seen('P'))
  7076. {
  7077. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  7078. nozzle_diameter_check(nDiameter);
  7079. }
  7080. else if(code_seen('Q'))
  7081. SERIAL_PROTOCOLLN((float)eeprom_read_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM)/1000.0);
  7082. break;
  7083. case ClPrintChecking::_Model: // ~ .2
  7084. if(code_seen('P'))
  7085. {
  7086. uint16_t nPrinterModel;
  7087. nPrinterModel=(uint16_t)code_value_long();
  7088. // based on current state of MMU (active/stopped/connecting) perform a runtime update of the printer type
  7089. fSetMmuMode(MMU2::mmu2.Enabled());
  7090. printer_model_check(nPrinterModel);
  7091. }
  7092. else if(code_seen('Q'))
  7093. SERIAL_PROTOCOLLN(nPrinterType);
  7094. break;
  7095. case ClPrintChecking::_Smodel: // ~ .3
  7096. if(code_seen('P'))
  7097. {
  7098. fSetMmuMode(MMU2::mmu2.Enabled());
  7099. printer_smodel_check(strchr_pointer);
  7100. }
  7101. else if(code_seen('Q'))
  7102. SERIAL_PROTOCOLLNRPGM(sPrinterName);
  7103. break;
  7104. case ClPrintChecking::_Version: // ~ .4
  7105. if(code_seen('P'))
  7106. fw_version_check(++strchr_pointer);
  7107. else if(code_seen('Q'))
  7108. SERIAL_PROTOCOLLNRPGM(FW_VERSION_STR_P());
  7109. break;
  7110. case ClPrintChecking::_Gcode: // ~ .5
  7111. if(code_seen('P'))
  7112. {
  7113. uint16_t nGcodeLevel;
  7114. nGcodeLevel=(uint16_t)code_value_long();
  7115. gcode_level_check(nGcodeLevel);
  7116. }
  7117. else if(code_seen('Q'))
  7118. SERIAL_PROTOCOLLN(GCODE_LEVEL);
  7119. break;
  7120. }
  7121. break;
  7122. #ifdef LIN_ADVANCE
  7123. /*!
  7124. ### 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>
  7125. 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.
  7126. #### Usage
  7127. M900 [ K | R | W | H | D]
  7128. #### Parameters
  7129. - `K` - Advance K factor
  7130. - `R` - Set ratio directly (overrides WH/D)
  7131. - `W` - Width
  7132. - `H` - Height
  7133. - `D` - Diameter Set ratio from WH/D
  7134. */
  7135. case 900:
  7136. gcode_M900();
  7137. break;
  7138. #endif
  7139. /*!
  7140. ### 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>
  7141. Set digital trimpot motor current using axis codes (X, Y, Z, E, B, S).
  7142. M907 has no effect when the experimental Extruder motor current scaling mode is active (that applies to farm printing as well)
  7143. #### Usage
  7144. M907 [ X | Y | Z | E | B | S ]
  7145. #### Parameters
  7146. - `X` - X motor driver
  7147. - `Y` - Y motor driver
  7148. - `Z` - Z motor driver
  7149. - `E` - Extruder motor driver
  7150. - `B` - Second Extruder motor driver
  7151. - `S` - All motors
  7152. */
  7153. case 907:
  7154. {
  7155. #ifdef TMC2130
  7156. // See tmc2130_cur2val() for translation to 0 .. 63 range
  7157. for (uint_least8_t i = 0; i < NUM_AXIS; i++){
  7158. if(code_seen(axis_codes[i])){
  7159. if( i == E_AXIS && FarmOrUserECool() ){
  7160. SERIAL_ECHORPGM(eMotorCurrentScalingEnabled);
  7161. SERIAL_ECHOLNPGM(", M907 E ignored");
  7162. continue;
  7163. }
  7164. long cur_mA = code_value_long();
  7165. uint8_t val = tmc2130_cur2val(cur_mA);
  7166. tmc2130_set_current_h(i, val);
  7167. tmc2130_set_current_r(i, val);
  7168. //if (i == E_AXIS) printf_P(PSTR("E-axis current=%ldmA\n"), cur_mA);
  7169. }
  7170. }
  7171. #else //TMC2130
  7172. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  7173. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) st_current_set(i,code_value());
  7174. if(code_seen('B')) st_current_set(4,code_value());
  7175. if(code_seen('S')) for(int i=0;i<=4;i++) st_current_set(i,code_value());
  7176. #endif
  7177. #ifdef MOTOR_CURRENT_PWM_XY_PIN
  7178. if(code_seen('X')) st_current_set(0, code_value());
  7179. #endif
  7180. #ifdef MOTOR_CURRENT_PWM_Z_PIN
  7181. if(code_seen('Z')) st_current_set(1, code_value());
  7182. #endif
  7183. #ifdef MOTOR_CURRENT_PWM_E_PIN
  7184. if(code_seen('E')) st_current_set(2, code_value());
  7185. #endif
  7186. #endif //TMC2130
  7187. }
  7188. break;
  7189. /*!
  7190. ### M908 - Control digital trimpot directly <a href="https://reprap.org/wiki/G-code#M908:_Control_digital_trimpot_directly">M908: Control digital trimpot directly</a>
  7191. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code. Not usable on Prusa printers.
  7192. #### Usage
  7193. M908 [ P | S ]
  7194. #### Parameters
  7195. - `P` - channel
  7196. - `S` - current
  7197. */
  7198. case 908:
  7199. {
  7200. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  7201. uint8_t channel,current;
  7202. if(code_seen('P')) channel=code_value();
  7203. if(code_seen('S')) current=code_value();
  7204. digitalPotWrite(channel, current);
  7205. #endif
  7206. }
  7207. break;
  7208. #ifdef TMC2130_SERVICE_CODES_M910_M918
  7209. /*!
  7210. ### M910 - TMC2130 init <a href="https://reprap.org/wiki/G-code#M910:_TMC2130_init">M910: TMC2130 init</a>
  7211. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7212. */
  7213. case 910:
  7214. {
  7215. tmc2130_init(TMCInitParams(false, FarmOrUserECool()));
  7216. }
  7217. break;
  7218. /*!
  7219. ### M911 - Set TMC2130 holding currents <a href="https://reprap.org/wiki/G-code#M911:_Set_TMC2130_holding_currents">M911: Set TMC2130 holding currents</a>
  7220. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7221. #### Usage
  7222. M911 [ X | Y | Z | E ]
  7223. #### Parameters
  7224. - `X` - X stepper driver holding current value
  7225. - `Y` - Y stepper driver holding current value
  7226. - `Z` - Z stepper driver holding current value
  7227. - `E` - Extruder stepper driver holding current value
  7228. */
  7229. case 911:
  7230. {
  7231. if (code_seen('X')) tmc2130_set_current_h(0, code_value());
  7232. if (code_seen('Y')) tmc2130_set_current_h(1, code_value());
  7233. if (code_seen('Z')) tmc2130_set_current_h(2, code_value());
  7234. if (code_seen('E')) tmc2130_set_current_h(3, code_value());
  7235. }
  7236. break;
  7237. /*!
  7238. ### M912 - Set TMC2130 running currents <a href="https://reprap.org/wiki/G-code#M912:_Set_TMC2130_running_currents">M912: Set TMC2130 running currents</a>
  7239. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7240. #### Usage
  7241. M912 [ X | Y | Z | E ]
  7242. #### Parameters
  7243. - `X` - X stepper driver running current value
  7244. - `Y` - Y stepper driver running current value
  7245. - `Z` - Z stepper driver running current value
  7246. - `E` - Extruder stepper driver running current value
  7247. */
  7248. case 912:
  7249. {
  7250. if (code_seen('X')) tmc2130_set_current_r(0, code_value());
  7251. if (code_seen('Y')) tmc2130_set_current_r(1, code_value());
  7252. if (code_seen('Z')) tmc2130_set_current_r(2, code_value());
  7253. if (code_seen('E')) tmc2130_set_current_r(3, code_value());
  7254. }
  7255. break;
  7256. /*!
  7257. ### M913 - Print TMC2130 currents <a href="https://reprap.org/wiki/G-code#M913:_Print_TMC2130_currents">M913: Print TMC2130 currents</a>
  7258. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7259. Shows TMC2130 currents.
  7260. */
  7261. case 913:
  7262. {
  7263. tmc2130_print_currents();
  7264. }
  7265. break;
  7266. /*!
  7267. ### M914 - Set TMC2130 normal mode <a href="https://reprap.org/wiki/G-code#M914:_Set_TMC2130_normal_mode">M914: Set TMC2130 normal mode</a>
  7268. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7269. */
  7270. case 914:
  7271. {
  7272. tmc2130_mode = TMC2130_MODE_NORMAL;
  7273. update_mode_profile();
  7274. tmc2130_init(TMCInitParams(false, FarmOrUserECool()));
  7275. }
  7276. break;
  7277. /*!
  7278. ### M915 - Set TMC2130 silent mode <a href="https://reprap.org/wiki/G-code#M915:_Set_TMC2130_silent_mode">M915: Set TMC2130 silent mode</a>
  7279. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7280. */
  7281. case 915:
  7282. {
  7283. tmc2130_mode = TMC2130_MODE_SILENT;
  7284. update_mode_profile();
  7285. tmc2130_init(TMCInitParams(false, FarmOrUserECool()));
  7286. }
  7287. break;
  7288. /*!
  7289. ### 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>
  7290. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7291. #### Usage
  7292. M916 [ X | Y | Z | E ]
  7293. #### Parameters
  7294. - `X` - X stepper driver stallguard sensitivity threshold value
  7295. - `Y` - Y stepper driver stallguard sensitivity threshold value
  7296. - `Z` - Z stepper driver stallguard sensitivity threshold value
  7297. - `E` - Extruder stepper driver stallguard sensitivity threshold value
  7298. */
  7299. case 916:
  7300. {
  7301. if (code_seen('X')) tmc2130_sg_thr[X_AXIS] = code_value();
  7302. if (code_seen('Y')) tmc2130_sg_thr[Y_AXIS] = code_value();
  7303. if (code_seen('Z')) tmc2130_sg_thr[Z_AXIS] = code_value();
  7304. if (code_seen('E')) tmc2130_sg_thr[E_AXIS] = code_value();
  7305. for (uint8_t a = X_AXIS; a <= E_AXIS; a++)
  7306. printf_P(_N("tmc2130_sg_thr[%c]=%d\n"), "XYZE"[a], tmc2130_sg_thr[a]);
  7307. }
  7308. break;
  7309. /*!
  7310. ### 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>
  7311. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7312. #### Usage
  7313. M917 [ X | Y | Z | E ]
  7314. #### Parameters
  7315. - `X` - X stepper driver PWM amplitude offset value
  7316. - `Y` - Y stepper driver PWM amplitude offset value
  7317. - `Z` - Z stepper driver PWM amplitude offset value
  7318. - `E` - Extruder stepper driver PWM amplitude offset value
  7319. */
  7320. case 917:
  7321. {
  7322. if (code_seen('X')) tmc2130_set_pwm_ampl(0, code_value());
  7323. if (code_seen('Y')) tmc2130_set_pwm_ampl(1, code_value());
  7324. if (code_seen('Z')) tmc2130_set_pwm_ampl(2, code_value());
  7325. if (code_seen('E')) tmc2130_set_pwm_ampl(3, code_value());
  7326. }
  7327. break;
  7328. /*!
  7329. ### 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>
  7330. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7331. #### Usage
  7332. M918 [ X | Y | Z | E ]
  7333. #### Parameters
  7334. - `X` - X stepper driver PWM amplitude gradient value
  7335. - `Y` - Y stepper driver PWM amplitude gradient value
  7336. - `Z` - Z stepper driver PWM amplitude gradient value
  7337. - `E` - Extruder stepper driver PWM amplitude gradient value
  7338. */
  7339. case 918:
  7340. {
  7341. if (code_seen('X')) tmc2130_set_pwm_grad(0, code_value());
  7342. if (code_seen('Y')) tmc2130_set_pwm_grad(1, code_value());
  7343. if (code_seen('Z')) tmc2130_set_pwm_grad(2, code_value());
  7344. if (code_seen('E')) tmc2130_set_pwm_grad(3, code_value());
  7345. }
  7346. break;
  7347. #endif //TMC2130_SERVICE_CODES_M910_M918
  7348. /*!
  7349. ### M350 - Set microstepping mode <a href="https://reprap.org/wiki/G-code#M350:_Set_microstepping_mode">M350: Set microstepping mode</a>
  7350. 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!
  7351. Printers without TMC2130 drivers also have `B` and `S` options. In this case, the steps-per-unit value in not changed!
  7352. #### Usage
  7353. M350 [ X | Y | Z | E | B | S ]
  7354. #### Parameters
  7355. - `X` - X new resolution
  7356. - `Y` - Y new resolution
  7357. - `Z` - Z new resolution
  7358. - `E` - E new resolution
  7359. Only valid for MK2.5(S) or printers without TMC2130 drivers
  7360. - `B` - Second extruder new resolution
  7361. - `S` - All axes new resolution
  7362. */
  7363. case 350:
  7364. {
  7365. #ifdef TMC2130
  7366. for (uint_least8_t i=0; i<NUM_AXIS; i++)
  7367. {
  7368. if(code_seen(axis_codes[i]))
  7369. {
  7370. uint16_t res_new = code_value();
  7371. #ifdef ALLOW_ALL_MRES
  7372. bool res_valid = res_new > 0 && res_new <= 256 && !(res_new & (res_new - 1)); // must be a power of two
  7373. #else
  7374. bool res_valid = (res_new == 8) || (res_new == 16) || (res_new == 32); // resolutions valid for all axis
  7375. res_valid |= (i != E_AXIS) && ((res_new == 1) || (res_new == 2) || (res_new == 4)); // resolutions valid for X Y Z only
  7376. res_valid |= (i == E_AXIS) && ((res_new == 64) || (res_new == 128)); // resolutions valid for E only
  7377. #endif
  7378. if (res_valid)
  7379. {
  7380. st_synchronize();
  7381. uint16_t res = tmc2130_get_res(i);
  7382. tmc2130_set_res(i, res_new);
  7383. cs.axis_ustep_resolution[i] = res_new;
  7384. if (res_new > res)
  7385. {
  7386. uint16_t fac = (res_new / res);
  7387. cs.axis_steps_per_unit[i] *= fac;
  7388. position[i] *= fac;
  7389. }
  7390. else
  7391. {
  7392. uint16_t fac = (res / res_new);
  7393. cs.axis_steps_per_unit[i] /= fac;
  7394. position[i] /= fac;
  7395. }
  7396. #if defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  7397. if (i == E_AXIS)
  7398. fsensor.init();
  7399. #endif //defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  7400. }
  7401. }
  7402. }
  7403. reset_acceleration_rates();
  7404. #else //TMC2130
  7405. #if defined(X_MS1_PIN) && X_MS1_PIN > -1
  7406. if(code_seen('S')) for(int i=0;i<=4;i++) microstep_mode(i,code_value());
  7407. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_mode(i,(uint8_t)code_value());
  7408. if(code_seen('B')) microstep_mode(4,code_value());
  7409. microstep_readings();
  7410. #endif
  7411. #endif //TMC2130
  7412. }
  7413. break;
  7414. /*!
  7415. ### 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>
  7416. Toggle MS1 MS2 pins directly.
  7417. #### Usage
  7418. M351 [B<0|1>] [E<0|1>] S<1|2> [X<0|1>] [Y<0|1>] [Z<0|1>]
  7419. #### Parameters
  7420. - `X` - Update X axis
  7421. - `Y` - Update Y axis
  7422. - `Z` - Update Z axis
  7423. - `E` - Update E axis
  7424. - `S` - which MSx pin to toggle
  7425. - `B` - new pin value
  7426. */
  7427. case 351:
  7428. {
  7429. #if defined(X_MS1_PIN) && X_MS1_PIN > -1
  7430. if(code_seen('S')) switch((int)code_value())
  7431. {
  7432. case 1:
  7433. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_ms(i,code_value(),-1);
  7434. if(code_seen('B')) microstep_ms(4,code_value(),-1);
  7435. break;
  7436. case 2:
  7437. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_ms(i,-1,code_value());
  7438. if(code_seen('B')) microstep_ms(4,-1,code_value());
  7439. break;
  7440. }
  7441. microstep_readings();
  7442. #endif
  7443. }
  7444. break;
  7445. /*!
  7446. ### M701 - Load filament to extruder <a href="https://reprap.org/wiki/G-code#M701:_Load_filament">M701: Load filament</a>
  7447. Load filament into the active extruder.
  7448. #### Usage
  7449. M701 [ P | T | L | Z ]
  7450. #### Parameters
  7451. - `P` - n index of MMU slot (zero based, so 0-4 like T0 and T4)
  7452. - `T` - Alias of `P`. Used for compatibility with Marlin
  7453. - `L` - Extrude distance for insertion (positive value)(manual reload)
  7454. - `Z` - Move the Z axis by this distance. Default value MIN_Z_FOR_LOAD
  7455. */
  7456. case 701:
  7457. {
  7458. uint8_t mmuSlotIndex = 0xffU;
  7459. float fastLoadLength = FILAMENTCHANGE_FIRSTFEED; // Only used without MMU
  7460. float z_target = MIN_Z_FOR_LOAD;
  7461. if( MMU2::mmu2.Enabled() )
  7462. {
  7463. if( code_seen('P') || code_seen('T') ) {
  7464. mmuSlotIndex = code_value_uint8();
  7465. }
  7466. }
  7467. if (code_seen('L')) fastLoadLength = code_value();
  7468. // Z lift. For safety only allow positive values
  7469. if (code_seen('Z')) z_target = fabs(code_value());
  7470. // Raise the Z axis
  7471. float delta = raise_z(z_target);
  7472. // Load filament
  7473. gcode_M701(fastLoadLength, mmuSlotIndex);
  7474. // Restore Z axis
  7475. raise_z(-delta);
  7476. }
  7477. break;
  7478. /*!
  7479. ### M702 - Unload filament <a href="https://reprap.org/wiki/G-code#M702:_Unload_filament">G32: Undock Z Probe sled</a>
  7480. #### Usage
  7481. M702 [ U | Z ]
  7482. #### Parameters
  7483. - `U` - Retract distance for removal (manual reload). Default value is 0.
  7484. - `Z` - Move the Z axis by this distance. Default value MIN_Z_FOR_UNLOAD.
  7485. */
  7486. case 702:
  7487. {
  7488. float z_target = MIN_Z_FOR_UNLOAD;
  7489. float unloadLength = FILAMENTCHANGE_FINALRETRACT;
  7490. if (code_seen('U')) unloadLength = code_value();
  7491. // For safety only allow positive values
  7492. if (code_seen('Z')) z_target = fabs(code_value());
  7493. // Raise the Z axis
  7494. float delta = raise_z(z_target);
  7495. // Unload filament
  7496. if (MMU2::mmu2.Enabled()) MMU2::mmu2.unload();
  7497. else unload_filament(unloadLength);
  7498. // Restore Z axis
  7499. raise_z(-delta);
  7500. }
  7501. break;
  7502. /*!
  7503. ### M704 - Load to MMU
  7504. #### Usage
  7505. M704 [ P ]
  7506. #### Parameters
  7507. - `P` - n index of slot (zero based, so 0-4 like T0 and T4)
  7508. */
  7509. case 704:
  7510. {
  7511. gcodes_M704_M705_M706(704);
  7512. }
  7513. break;
  7514. /*!
  7515. ### M705 - Eject filament
  7516. #### Usage
  7517. M705 [ P ]
  7518. #### Parameters
  7519. - `P` - n index of slot (zero based, so 0-4 like T0 and T4)
  7520. */
  7521. case 705:
  7522. {
  7523. gcodes_M704_M705_M706(705);
  7524. }
  7525. break;
  7526. /*!
  7527. ### M706 - Cut filament
  7528. #### Usage
  7529. M706 [ P ]
  7530. #### Parameters
  7531. - `P` - n index of slot (zero based, so 0-4 like T0 and T4)
  7532. */
  7533. case 706:
  7534. {
  7535. gcodes_M704_M705_M706(706);
  7536. }
  7537. break;
  7538. /*!
  7539. ### M707 - Read from MMU register
  7540. #### Usage
  7541. M707 [ A | C ]
  7542. M707 A0x14 C2 - Read two bytes from register 0x14
  7543. #### Parameters
  7544. - `A` - Address of register in hexidecimal. Default value is 0.
  7545. - `C` - Number of bytes to read. Default value is 0.
  7546. */
  7547. case 707:
  7548. {
  7549. uint8_t addr = 0;
  7550. uint8_t nrbytes = 0;
  7551. if ( MMU2::mmu2.Enabled() )
  7552. {
  7553. if( code_seen('A') ) {
  7554. addr = uint8_t(strtol(strchr_pointer+1, NULL, 0));
  7555. }
  7556. if( code_seen('C') ) {
  7557. nrbytes = code_value_uint8();
  7558. }
  7559. MMU2::mmu2.ReadRegister(addr, nrbytes);
  7560. }
  7561. }
  7562. break;
  7563. /*!
  7564. ### M708 - Write to MMU register
  7565. #### Usage
  7566. M708 [ A | X | C ]
  7567. M708 A0x14 X30 C1 - Write to register 0x14 the value 30 which is 1 byte.
  7568. #### Parameters
  7569. - `A` - Address of register in hexidecimal. Default value is 0.
  7570. - `X` - Data to write. Default value is 0.
  7571. - `C` - Number of bytes to write. Default value is 0.
  7572. */
  7573. case 708:
  7574. {
  7575. uint8_t addr = 0;
  7576. uint8_t data = 0;
  7577. uint8_t nrbytes = 0;
  7578. if ( MMU2::mmu2.Enabled() )
  7579. {
  7580. if( code_seen('A') ) {
  7581. addr = uint8_t(strtol(strchr_pointer+1, NULL, 0));
  7582. }
  7583. if( code_seen('X') ) {
  7584. data = code_value_uint8();
  7585. }
  7586. if( code_seen('C') ) {
  7587. nrbytes = code_value_uint8();
  7588. }
  7589. MMU2::mmu2.WriteRegister(addr, data, nrbytes);
  7590. }
  7591. }
  7592. break;
  7593. /*!
  7594. ### M709 - MMU turn on/off/reset
  7595. The MK3S cannot not power off the MMU, for that reason the functionality is not supported.
  7596. #### Usage
  7597. M709 [ X ]
  7598. M709 X0 - issue an X0 command via communication into the MMU (soft reset)
  7599. M709 X1 - toggle the MMU's reset pin (hardware reset)
  7600. #### Parameters
  7601. - `X` - Reset MMU
  7602. */
  7603. case 709:
  7604. {
  7605. if (MMU2::mmu2.Enabled() && code_seen('X'))
  7606. {
  7607. switch (code_value_uint8())
  7608. {
  7609. case 0:
  7610. MMU2::mmu2.Reset(MMU2::MMU2::Software);
  7611. break;
  7612. case 1:
  7613. MMU2::mmu2.Reset(MMU2::MMU2::ResetPin);
  7614. break;
  7615. default:
  7616. break;
  7617. }
  7618. }
  7619. }
  7620. break;
  7621. /*!
  7622. ### M999 - Restart after being stopped <a href="https://reprap.org/wiki/G-code#M999:_Restart_after_being_stopped_by_error">M999: Restart after being stopped by error</a>
  7623. @todo Usually doesn't work. Should be fixed or removed. Most of the time, if `Stopped` it set, the print fails and is unrecoverable.
  7624. */
  7625. case 999:
  7626. Stopped = false;
  7627. lcd_reset_alert_level();
  7628. //@@TODO gcode_LastN = Stopped_gcode_LastN;
  7629. FlushSerialRequestResend();
  7630. break;
  7631. /*!
  7632. #### End of M-Commands
  7633. */
  7634. default:
  7635. printf_P(MSG_UNKNOWN_CODE, 'M', cmdbuffer + bufindr + CMDHDRSIZE);
  7636. }
  7637. // printf_P(_N("END M-CODE=%u\n"), mcode_in_progress);
  7638. mcode_in_progress = 0;
  7639. }
  7640. }
  7641. // end if(code_seen('M')) (end of M codes)
  7642. /*!
  7643. -----------------------------------------------------------------------------------------
  7644. # T Codes
  7645. T<extruder nr.> - select extruder in case of multi extruder printer. select filament in case of MMU_V2.
  7646. #### For MMU_V2:
  7647. T<n> Gcode to extrude at least 38.10 mm at feedrate 19.02 mm/s must follow immediately to load to extruder wheels.
  7648. @n T? Gcode to extrude shouldn't have to follow, load to extruder wheels is done automatically
  7649. @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.
  7650. @n Tc Load to nozzle after filament was prepared by Tc and extruder nozzle is already heated.
  7651. */
  7652. else if(code_seen('T')){
  7653. TCodes(strchr_pointer, code_value());
  7654. } // end if(code_seen('T')) (end of T codes)
  7655. /*!
  7656. #### End of T-Codes
  7657. */
  7658. /**
  7659. *---------------------------------------------------------------------------------
  7660. *# D codes
  7661. */
  7662. else if (code_seen('D')) // D codes (debug)
  7663. {
  7664. switch(code_value_short())
  7665. {
  7666. /*!
  7667. ### D-1 - Endless Loop <a href="https://reprap.org/wiki/G-code#D-1:_Endless_Loop">D-1: Endless Loop</a>
  7668. */
  7669. case -1:
  7670. dcode__1(); break;
  7671. #ifdef DEBUG_DCODES
  7672. /*!
  7673. ### D0 - Reset <a href="https://reprap.org/wiki/G-code#D0:_Reset">D0: Reset</a>
  7674. #### Usage
  7675. D0 [ B ]
  7676. #### Parameters
  7677. - `B` - Bootloader
  7678. */
  7679. case 0:
  7680. dcode_0(); break;
  7681. /*!
  7682. *
  7683. ### D1 - Clear EEPROM and RESET <a href="https://reprap.org/wiki/G-code#D1:_Clear_EEPROM_and_RESET">D1: Clear EEPROM and RESET</a>
  7684. D1
  7685. *
  7686. */
  7687. case 1:
  7688. dcode_1(); break;
  7689. #endif
  7690. #if defined DEBUG_DCODE2 || defined DEBUG_DCODES
  7691. /*!
  7692. ### D2 - Read/Write RAM <a href="https://reprap.org/wiki/G-code#D2:_Read.2FWrite_RAM">D3: Read/Write RAM</a>
  7693. This command can be used without any additional parameters. It will read the entire RAM.
  7694. #### Usage
  7695. D2 [ A | C | X ]
  7696. #### Parameters
  7697. - `A` - Address (x0000-x1fff)
  7698. - `C` - Count (1-8192)
  7699. - `X` - Data
  7700. #### Notes
  7701. - The hex address needs to be lowercase without the 0 before the x
  7702. - Count is decimal
  7703. - The hex data needs to be lowercase
  7704. */
  7705. case 2:
  7706. dcode_2(); break;
  7707. #endif //DEBUG_DCODES
  7708. #if defined DEBUG_DCODE3 || defined DEBUG_DCODES
  7709. /*!
  7710. ### D3 - Read/Write EEPROM <a href="https://reprap.org/wiki/G-code#D3:_Read.2FWrite_EEPROM">D3: Read/Write EEPROM</a>
  7711. This command can be used without any additional parameters. It will read the entire eeprom.
  7712. #### Usage
  7713. D3 [ A | C | X ]
  7714. #### Parameters
  7715. - `A` - Address (x0000-x0fff)
  7716. - `C` - Count (1-4096)
  7717. - `X` - Data (hex)
  7718. #### Notes
  7719. - The hex address needs to be lowercase without the 0 before the x
  7720. - Count is decimal
  7721. - The hex data needs to be lowercase
  7722. */
  7723. case 3:
  7724. dcode_3(); break;
  7725. #endif //DEBUG_DCODE3
  7726. #ifdef DEBUG_DCODES
  7727. /*!
  7728. ### D4 - Read/Write PIN <a href="https://reprap.org/wiki/G-code#D4:_Read.2FWrite_PIN">D4: Read/Write PIN</a>
  7729. To read the digital value of a pin you need only to define the pin number.
  7730. #### Usage
  7731. D4 [ P | F | V ]
  7732. #### Parameters
  7733. - `P` - Pin (0-255)
  7734. - `F` - Function in/out (0/1)
  7735. - `V` - Value (0/1)
  7736. */
  7737. case 4:
  7738. dcode_4(); break;
  7739. #endif //DEBUG_DCODES
  7740. #if defined DEBUG_DCODE5 || defined DEBUG_DCODES
  7741. /*!
  7742. ### D5 - Read/Write FLASH <a href="https://reprap.org/wiki/G-code#D5:_Read.2FWrite_FLASH">D5: Read/Write Flash</a>
  7743. This command can be used without any additional parameters. It will read the 1kb FLASH.
  7744. #### Usage
  7745. D5 [ A | C | X | E ]
  7746. #### Parameters
  7747. - `A` - Address (x00000-x3ffff)
  7748. - `C` - Count (1-8192)
  7749. - `X` - Data (hex)
  7750. - `E` - Erase
  7751. #### Notes
  7752. - The hex address needs to be lowercase without the 0 before the x
  7753. - Count is decimal
  7754. - The hex data needs to be lowercase
  7755. */
  7756. case 5:
  7757. dcode_5(); break;
  7758. #endif //DEBUG_DCODE5
  7759. #if defined DEBUG_DCODE6 || defined DEBUG_DCODES
  7760. /*!
  7761. ### D6 - Read/Write external FLASH <a href="https://reprap.org/wiki/G-code#D6:_Read.2FWrite_external_FLASH">D6: Read/Write external Flash</a>
  7762. Reserved
  7763. */
  7764. case 6:
  7765. dcode_6(); break;
  7766. #endif
  7767. #ifdef DEBUG_DCODES
  7768. /*!
  7769. ### D7 - Read/Write Bootloader <a href="https://reprap.org/wiki/G-code#D7:_Read.2FWrite_Bootloader">D7: Read/Write Bootloader</a>
  7770. Reserved
  7771. */
  7772. case 7:
  7773. dcode_7(); break;
  7774. /*!
  7775. ### D8 - Read/Write PINDA <a href="https://reprap.org/wiki/G-code#D8:_Read.2FWrite_PINDA">D8: Read/Write PINDA</a>
  7776. #### Usage
  7777. D8 [ ? | ! | P | Z ]
  7778. #### Parameters
  7779. - `?` - Read PINDA temperature shift values
  7780. - `!` - Reset PINDA temperature shift values to default
  7781. - `P` - Pinda temperature [C]
  7782. - `Z` - Z Offset [mm]
  7783. */
  7784. case 8:
  7785. dcode_8(); break;
  7786. /*!
  7787. ### D9 - Read ADC <a href="https://reprap.org/wiki/G-code#D9:_Read.2FWrite_ADC">D9: Read ADC</a>
  7788. #### Usage
  7789. D9 [ I | V ]
  7790. #### Parameters
  7791. - `I` - ADC channel index
  7792. - `0` - Heater 0 temperature
  7793. - `1` - Heater 1 temperature
  7794. - `2` - Bed temperature
  7795. - `3` - PINDA temperature
  7796. - `4` - PWR voltage
  7797. - `5` - Ambient temperature
  7798. - `6` - BED voltage
  7799. - `V` Value to be written as simulated
  7800. */
  7801. case 9:
  7802. dcode_9(); break;
  7803. /*!
  7804. ### 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>
  7805. */
  7806. case 10:
  7807. dcode_10(); break;
  7808. /*!
  7809. ### D12 - Time <a href="https://reprap.org/wiki/G-code#D12:_Time">D12: Time</a>
  7810. Writes the current time in the log file.
  7811. */
  7812. #endif //DEBUG_DCODES
  7813. #ifdef XFLASH_DUMP
  7814. /*!
  7815. ### 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>
  7816. Generate a crash dump for later retrival.
  7817. #### Usage
  7818. D20 [E]
  7819. ### Parameters
  7820. - `E` - Perform an emergency crash dump (resets the printer).
  7821. ### Notes
  7822. - A crash dump can be later recovered with D21, or cleared with D22.
  7823. - An emergency crash dump includes register data, but will cause the printer to reset after the dump
  7824. is completed.
  7825. */
  7826. case 20: {
  7827. dcode_20();
  7828. break;
  7829. };
  7830. /*!
  7831. ### 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>
  7832. Output the complete crash dump (if present) to the serial.
  7833. #### Usage
  7834. D21
  7835. ### Notes
  7836. - The starting address can vary between builds, but it's always at the beginning of the data section.
  7837. */
  7838. case 21: {
  7839. dcode_21();
  7840. break;
  7841. };
  7842. /*!
  7843. ### D22 - Clear crash dump state <a href="https://reprap.org/wiki/G-code#D22:_Clear_crash_dump_state">D22: Clear crash dump state</a>
  7844. Clear an existing internal crash dump.
  7845. #### Usage
  7846. D22
  7847. */
  7848. case 22: {
  7849. dcode_22();
  7850. break;
  7851. };
  7852. #endif //XFLASH_DUMP
  7853. #ifdef EMERGENCY_SERIAL_DUMP
  7854. /*!
  7855. ### 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>
  7856. On boards without offline dump support, request online dumps to the serial port on firmware faults.
  7857. When online dumps are enabled, the FW will dump memory on the serial before resetting.
  7858. #### Usage
  7859. D23 [E] [R]
  7860. #### Parameters
  7861. - `E` - Perform an emergency crash dump (resets the printer).
  7862. - `R` - Disable online dumps.
  7863. */
  7864. case 23: {
  7865. dcode_23();
  7866. break;
  7867. };
  7868. #endif
  7869. #ifdef TEMP_MODEL_DEBUG
  7870. /*!
  7871. ## D70 - Enable low-level temperature model logging for offline simulation
  7872. #### Usage
  7873. D70 [ S ]
  7874. #### Parameters
  7875. - `S` - Enable 0-1 (default 0)
  7876. */
  7877. case 70: {
  7878. if(code_seen('S'))
  7879. temp_model_log_enable(code_value_short());
  7880. break;
  7881. }
  7882. #endif
  7883. #ifdef HEATBED_ANALYSIS
  7884. /*!
  7885. ### D80 - Bed check <a href="https://reprap.org/wiki/G-code#D80:_Bed_check">D80: Bed check</a>
  7886. This command will log data to SD card file "mesh.txt".
  7887. #### Usage
  7888. D80 [ E | F | G | H | I | J ]
  7889. #### Parameters
  7890. - `E` - Dimension X (default 40)
  7891. - `F` - Dimention Y (default 40)
  7892. - `G` - Points X (default 40)
  7893. - `H` - Points Y (default 40)
  7894. - `I` - Offset X (default 74)
  7895. - `J` - Offset Y (default 34)
  7896. */
  7897. case 80:
  7898. dcode_80(); break;
  7899. /*!
  7900. ### D81 - Bed analysis <a href="https://reprap.org/wiki/G-code#D81:_Bed_analysis">D80: Bed analysis</a>
  7901. This command will log data to SD card file "wldsd.txt".
  7902. #### Usage
  7903. D81 [ E | F | G | H | I | J ]
  7904. #### Parameters
  7905. - `E` - Dimension X (default 40)
  7906. - `F` - Dimention Y (default 40)
  7907. - `G` - Points X (default 40)
  7908. - `H` - Points Y (default 40)
  7909. - `I` - Offset X (default 74)
  7910. - `J` - Offset Y (default 34)
  7911. */
  7912. case 81:
  7913. dcode_81(); break;
  7914. #endif //HEATBED_ANALYSIS
  7915. #ifdef DEBUG_DCODES
  7916. /*!
  7917. ### 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>
  7918. */
  7919. case 106:
  7920. dcode_106(); break;
  7921. #ifdef TMC2130
  7922. /*!
  7923. ### D2130 - Trinamic stepper controller <a href="https://reprap.org/wiki/G-code#D2130:_Trinamic_stepper_controller">D2130: Trinamic stepper controller</a>
  7924. @todo Please review by owner of the code. RepRap Wiki Gcode needs to be updated after review of owner as well.
  7925. #### Usage
  7926. D2130 [ Axis | Command | Subcommand | Value ]
  7927. #### Parameters
  7928. - Axis
  7929. - `X` - X stepper driver
  7930. - `Y` - Y stepper driver
  7931. - `Z` - Z stepper driver
  7932. - `E` - Extruder stepper driver
  7933. - Commands
  7934. - `0` - Current off
  7935. - `1` - Current on
  7936. - `+` - Single step
  7937. - `-` - Single step oposite direction
  7938. - `NNN` - Value sereval steps
  7939. - `?` - Read register
  7940. - Subcommands for read register
  7941. - `mres` - Micro step resolution. More information in datasheet '5.5.2 CHOPCONF – Chopper Configuration'
  7942. - `step` - Step
  7943. - `mscnt` - Microstep counter. More information in datasheet '5.5 Motor Driver Registers'
  7944. - `mscuract` - Actual microstep current for motor. More information in datasheet '5.5 Motor Driver Registers'
  7945. - `wave` - Microstep linearity compensation curve
  7946. - `!` - Set register
  7947. - Subcommands for set register
  7948. - `mres` - Micro step resolution
  7949. - `step` - Step
  7950. - `wave` - Microstep linearity compensation curve
  7951. - Values for set register
  7952. - `0, 180 --> 250` - Off
  7953. - `0.9 --> 1.25` - Valid values (recommended is 1.1)
  7954. - `@` - Home calibrate axis
  7955. Examples:
  7956. D2130E?wave
  7957. Print extruder microstep linearity compensation curve
  7958. D2130E!wave0
  7959. Disable extruder linearity compensation curve, (sine curve is used)
  7960. D2130E!wave220
  7961. (sin(x))^1.1 extruder microstep compensation curve used
  7962. Notes:
  7963. For more information see https://www.trinamic.com/fileadmin/assets/Products/ICs_Documents/TMC2130_datasheet.pdf
  7964. *
  7965. */
  7966. case 2130:
  7967. dcode_2130(); break;
  7968. #endif //TMC2130
  7969. #if defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  7970. /*!
  7971. ### D9125 - PAT9125 filament sensor <a href="https://reprap.org/wiki/G-code#D9:_Read.2FWrite_ADC">D9125: PAT9125 filament sensor</a>
  7972. #### Usage
  7973. D9125 [ ? | ! | R | X | Y | L ]
  7974. #### Parameters
  7975. - `?` - Print values
  7976. - `!` - Print values
  7977. - `R` - Resolution. Not active in code
  7978. - `X` - X values
  7979. - `Y` - Y values
  7980. - `L` - Activate filament sensor log
  7981. */
  7982. case 9125:
  7983. dcode_9125(); break;
  7984. #endif //defined(FILAMENT_SENSOR) && (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  7985. #endif //DEBUG_DCODES
  7986. default:
  7987. printf_P(MSG_UNKNOWN_CODE, 'D', cmdbuffer + bufindr + CMDHDRSIZE);
  7988. }
  7989. }
  7990. else
  7991. {
  7992. SERIAL_ECHO_START;
  7993. SERIAL_ECHORPGM(MSG_UNKNOWN_COMMAND);
  7994. SERIAL_ECHO(CMDBUFFER_CURRENT_STRING);
  7995. SERIAL_ECHOLNPGM("\"(2)");
  7996. }
  7997. KEEPALIVE_STATE(NOT_BUSY);
  7998. ClearToSend();
  7999. }
  8000. /*!
  8001. #### End of D-Codes
  8002. */
  8003. /** @defgroup GCodes G-Code List
  8004. */
  8005. // ---------------------------------------------------
  8006. void FlushSerialRequestResend()
  8007. {
  8008. //char cmdbuffer[bufindr][100]="Resend:";
  8009. MYSERIAL.flush();
  8010. printf_P(_N("%S: %ld\n%S\n"), _n("Resend"), gcode_LastN + 1, MSG_OK);
  8011. }
  8012. // Confirm the execution of a command, if sent from a serial line.
  8013. // Execution of a command from a SD card will not be confirmed.
  8014. void ClearToSend()
  8015. {
  8016. previous_millis_cmd.start();
  8017. if (buflen && ((CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB) || (CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR)))
  8018. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  8019. }
  8020. #if MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  8021. void update_currents() {
  8022. float current_high[3] = DEFAULT_PWM_MOTOR_CURRENT_LOUD;
  8023. float current_low[3] = DEFAULT_PWM_MOTOR_CURRENT;
  8024. float tmp_motor[3];
  8025. //SERIAL_ECHOLNPGM("Currents updated: ");
  8026. if (destination[Z_AXIS] < Z_SILENT) {
  8027. //SERIAL_ECHOLNPGM("LOW");
  8028. for (uint8_t i = 0; i < 3; i++) {
  8029. st_current_set(i, current_low[i]);
  8030. /*MYSERIAL.print(int(i));
  8031. SERIAL_ECHOPGM(": ");
  8032. MYSERIAL.println(current_low[i]);*/
  8033. }
  8034. }
  8035. else if (destination[Z_AXIS] > Z_HIGH_POWER) {
  8036. //SERIAL_ECHOLNPGM("HIGH");
  8037. for (uint8_t i = 0; i < 3; i++) {
  8038. st_current_set(i, current_high[i]);
  8039. /*MYSERIAL.print(int(i));
  8040. SERIAL_ECHOPGM(": ");
  8041. MYSERIAL.println(current_high[i]);*/
  8042. }
  8043. }
  8044. else {
  8045. for (uint8_t i = 0; i < 3; i++) {
  8046. float q = current_low[i] - Z_SILENT*((current_high[i] - current_low[i]) / (Z_HIGH_POWER - Z_SILENT));
  8047. tmp_motor[i] = ((current_high[i] - current_low[i]) / (Z_HIGH_POWER - Z_SILENT))*destination[Z_AXIS] + q;
  8048. st_current_set(i, tmp_motor[i]);
  8049. /*MYSERIAL.print(int(i));
  8050. SERIAL_ECHOPGM(": ");
  8051. MYSERIAL.println(tmp_motor[i]);*/
  8052. }
  8053. }
  8054. }
  8055. #endif //MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  8056. void get_coordinates() {
  8057. bool seen[4]={false,false,false,false};
  8058. for(int8_t i=0; i < NUM_AXIS; i++) {
  8059. if(code_seen(axis_codes[i]))
  8060. {
  8061. bool relative = axis_relative_modes & (1 << i);
  8062. destination[i] = code_value();
  8063. if (i == E_AXIS) {
  8064. float emult = extruder_multiplier[active_extruder];
  8065. if (emult != 1.) {
  8066. if (! relative) {
  8067. destination[i] -= current_position[i];
  8068. relative = true;
  8069. }
  8070. destination[i] *= emult;
  8071. }
  8072. }
  8073. if (relative)
  8074. destination[i] += current_position[i];
  8075. seen[i]=true;
  8076. #if MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  8077. if (i == Z_AXIS && SilentModeMenu == SILENT_MODE_AUTO) update_currents();
  8078. #endif //MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  8079. }
  8080. else destination[i] = current_position[i]; //Are these else lines really needed?
  8081. }
  8082. if(code_seen('F')) {
  8083. next_feedrate = code_value();
  8084. if(next_feedrate > 0.0) feedrate = next_feedrate;
  8085. if (!seen[0] && !seen[1] && !seen[2] && seen[3])
  8086. {
  8087. // float e_max_speed =
  8088. // printf_P(PSTR("E MOVE speed %7.3f\n"), feedrate / 60)
  8089. }
  8090. }
  8091. }
  8092. void clamp_to_software_endstops(float target[3])
  8093. {
  8094. #ifdef DEBUG_DISABLE_SWLIMITS
  8095. return;
  8096. #endif //DEBUG_DISABLE_SWLIMITS
  8097. world2machine_clamp(target[0], target[1]);
  8098. // Clamp the Z coordinate.
  8099. if (min_software_endstops) {
  8100. float negative_z_offset = 0;
  8101. #ifdef ENABLE_AUTO_BED_LEVELING
  8102. if (Z_PROBE_OFFSET_FROM_EXTRUDER < 0) negative_z_offset = negative_z_offset + Z_PROBE_OFFSET_FROM_EXTRUDER;
  8103. if (cs.add_homing[Z_AXIS] < 0) negative_z_offset = negative_z_offset + cs.add_homing[Z_AXIS];
  8104. #endif
  8105. if (target[Z_AXIS] < min_pos[Z_AXIS]+negative_z_offset) target[Z_AXIS] = min_pos[Z_AXIS]+negative_z_offset;
  8106. }
  8107. if (max_software_endstops) {
  8108. if (target[Z_AXIS] > max_pos[Z_AXIS]) target[Z_AXIS] = max_pos[Z_AXIS];
  8109. }
  8110. }
  8111. uint16_t restore_interrupted_gcode() {
  8112. // When recovering from a previous print move, restore the originally
  8113. // calculated start position on the first USB/SD command. This accounts
  8114. // properly for relative moves
  8115. if (
  8116. (saved_start_position[0] != SAVED_START_POSITION_UNSET) && (
  8117. (CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_SDCARD) ||
  8118. (CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR)
  8119. )
  8120. ) {
  8121. memcpy(current_position, saved_start_position, sizeof(current_position));
  8122. saved_start_position[0] = SAVED_START_POSITION_UNSET;
  8123. return saved_segment_idx;
  8124. }
  8125. else
  8126. return 1; //begin with the first segment
  8127. }
  8128. #ifdef MESH_BED_LEVELING
  8129. 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) {
  8130. float dx = x - current_position[X_AXIS];
  8131. float dy = y - current_position[Y_AXIS];
  8132. uint16_t n_segments = 0;
  8133. if (mbl.active) {
  8134. float len = fabs(dx) + fabs(dy);
  8135. if (len > 0)
  8136. // Split to 3cm segments or shorter.
  8137. n_segments = uint16_t(ceil(len / 30.f));
  8138. }
  8139. if (n_segments > 1 && start_segment_idx) {
  8140. float dz = z - current_position[Z_AXIS];
  8141. float de = e - current_position[E_AXIS];
  8142. for (uint16_t i = start_segment_idx; i < n_segments; ++ i) {
  8143. float t = float(i) / float(n_segments);
  8144. plan_buffer_line(current_position[X_AXIS] + t * dx,
  8145. current_position[Y_AXIS] + t * dy,
  8146. current_position[Z_AXIS] + t * dz,
  8147. current_position[E_AXIS] + t * de,
  8148. feed_rate, extruder, current_position, i);
  8149. if (planner_aborted)
  8150. return;
  8151. }
  8152. }
  8153. // The rest of the path.
  8154. plan_buffer_line(x, y, z, e, feed_rate, extruder, current_position);
  8155. }
  8156. #endif // MESH_BED_LEVELING
  8157. void prepare_move(uint16_t start_segment_idx)
  8158. {
  8159. clamp_to_software_endstops(destination);
  8160. previous_millis_cmd.start();
  8161. // Do not use feedmultiply for E or Z only moves
  8162. if((current_position[X_AXIS] == destination[X_AXIS]) && (current_position[Y_AXIS] == destination[Y_AXIS])) {
  8163. plan_buffer_line_destinationXYZE(feedrate/60);
  8164. }
  8165. else {
  8166. #ifdef MESH_BED_LEVELING
  8167. 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);
  8168. #else
  8169. plan_buffer_line_destinationXYZE(feedrate*feedmultiply*(1./(60.f*100.f)));
  8170. #endif
  8171. }
  8172. set_current_to_destination();
  8173. }
  8174. void prepare_arc_move(bool isclockwise, uint16_t start_segment_idx) {
  8175. float r = hypot(offset[X_AXIS], offset[Y_AXIS]); // Compute arc radius for mc_arc
  8176. // Trace the arc
  8177. mc_arc(current_position, destination, offset, feedrate * feedmultiply / 60 / 100.0, r, isclockwise, active_extruder, start_segment_idx);
  8178. // As far as the parser is concerned, the position is now == target. In reality the
  8179. // motion control system might still be processing the action and the real tool position
  8180. // in any intermediate location.
  8181. set_current_to_destination();
  8182. previous_millis_cmd.start();
  8183. }
  8184. #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1
  8185. #if defined(FAN_PIN)
  8186. #if CONTROLLERFAN_PIN == FAN_PIN
  8187. #error "You cannot set CONTROLLERFAN_PIN equal to FAN_PIN"
  8188. #endif
  8189. #endif
  8190. unsigned long lastMotor = 0; //Save the time for when a motor was turned on last
  8191. unsigned long lastMotorCheck = 0;
  8192. void controllerFan()
  8193. {
  8194. if ((_millis() - lastMotorCheck) >= 2500) //Not a time critical function, so we only check every 2500ms
  8195. {
  8196. lastMotorCheck = _millis();
  8197. if(!READ(X_ENABLE_PIN) || !READ(Y_ENABLE_PIN) || !READ(Z_ENABLE_PIN) || (soft_pwm_bed > 0)
  8198. #if EXTRUDERS > 2
  8199. || !READ(E2_ENABLE_PIN)
  8200. #endif
  8201. #if EXTRUDER > 1
  8202. #if defined(X2_ENABLE_PIN) && X2_ENABLE_PIN > -1
  8203. || !READ(X2_ENABLE_PIN)
  8204. #endif
  8205. || !READ(E1_ENABLE_PIN)
  8206. #endif
  8207. || !READ(E0_ENABLE_PIN)) //If any of the drivers are enabled...
  8208. {
  8209. lastMotor = _millis(); //... set time to NOW so the fan will turn on
  8210. }
  8211. if ((_millis() - lastMotor) >= (CONTROLLERFAN_SECS*1000UL) || lastMotor == 0) //If the last time any driver was enabled, is longer since than CONTROLLERSEC...
  8212. {
  8213. digitalWrite(CONTROLLERFAN_PIN, 0);
  8214. analogWrite(CONTROLLERFAN_PIN, 0);
  8215. }
  8216. else
  8217. {
  8218. // allows digital or PWM fan output to be used (see M42 handling)
  8219. digitalWrite(CONTROLLERFAN_PIN, CONTROLLERFAN_SPEED);
  8220. analogWrite(CONTROLLERFAN_PIN, CONTROLLERFAN_SPEED);
  8221. }
  8222. }
  8223. }
  8224. #endif
  8225. #ifdef SAFETYTIMER
  8226. /**
  8227. * @brief Turn off heating after safetytimer_inactive_time milliseconds of inactivity
  8228. *
  8229. * Full screen blocking notification message is shown after heater turning off.
  8230. * Paused print is not considered inactivity, as nozzle is cooled anyway and bed cooling would
  8231. * damage print.
  8232. *
  8233. * If safetytimer_inactive_time is zero, feature is disabled (heating is never turned off because of inactivity)
  8234. */
  8235. static void handleSafetyTimer()
  8236. {
  8237. #if (EXTRUDERS > 1)
  8238. #error Implemented only for one extruder.
  8239. #endif //(EXTRUDERS > 1)
  8240. if (printer_active() || (!degTargetBed() && !degTargetHotend(0)) || (!safetytimer_inactive_time))
  8241. {
  8242. safetyTimer.stop();
  8243. }
  8244. else if ((degTargetBed() || degTargetHotend(0)) && (!safetyTimer.running()))
  8245. {
  8246. safetyTimer.start();
  8247. }
  8248. else if (safetyTimer.expired(farm_mode?FARM_DEFAULT_SAFETYTIMER_TIME_ms:safetytimer_inactive_time))
  8249. {
  8250. setTargetBed(0);
  8251. setAllTargetHotends(0);
  8252. lcd_show_fullscreen_message_and_wait_P(_i("Heating disabled by safety timer."));////MSG_BED_HEATING_SAFETY_DISABLED c=20 r=4
  8253. }
  8254. }
  8255. #endif //SAFETYTIMER
  8256. void manage_inactivity(bool ignore_stepper_queue/*=false*/) //default argument set in Marlin.h
  8257. {
  8258. #ifdef FILAMENT_SENSOR
  8259. if (fsensor.update()) {
  8260. lcd_draw_update = 1; //cause lcd update so that fsensor event polling can be done from the lcd draw routine.
  8261. }
  8262. #endif
  8263. #ifdef SAFETYTIMER
  8264. handleSafetyTimer();
  8265. #endif //SAFETYTIMER
  8266. #if defined(KILL_PIN) && KILL_PIN > -1
  8267. static int killCount = 0; // make the inactivity button a bit less responsive
  8268. const int KILL_DELAY = 10000;
  8269. #endif
  8270. if(buflen < (BUFSIZE-1)){
  8271. get_command();
  8272. }
  8273. if(previous_millis_cmd.expired(max_inactive_time))
  8274. if(max_inactive_time)
  8275. kill(_n("Inactivity Shutdown"), 4);
  8276. if(stepper_inactive_time) {
  8277. if(previous_millis_cmd.expired(stepper_inactive_time))
  8278. {
  8279. if(blocks_queued() == false && ignore_stepper_queue == false) {
  8280. disable_x();
  8281. disable_y();
  8282. disable_z();
  8283. disable_e0();
  8284. disable_e1();
  8285. disable_e2();
  8286. }
  8287. }
  8288. }
  8289. #ifdef CHDK //Check if pin should be set to LOW after M240 set it to HIGH
  8290. if (chdkActive && (_millis() - chdkHigh > CHDK_DELAY))
  8291. {
  8292. chdkActive = false;
  8293. WRITE(CHDK, LOW);
  8294. }
  8295. #endif
  8296. #if defined(KILL_PIN) && KILL_PIN > -1
  8297. // Check if the kill button was pressed and wait just in case it was an accidental
  8298. // key kill key press
  8299. // -------------------------------------------------------------------------------
  8300. if( 0 == READ(KILL_PIN) )
  8301. {
  8302. killCount++;
  8303. }
  8304. else if (killCount > 0)
  8305. {
  8306. killCount--;
  8307. }
  8308. // Exceeded threshold and we can confirm that it was not accidental
  8309. // KILL the machine
  8310. // ----------------------------------------------------------------
  8311. if ( killCount >= KILL_DELAY)
  8312. {
  8313. kill(NULL, 5);
  8314. }
  8315. #endif
  8316. #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1
  8317. controllerFan(); //Check if fan should be turned on to cool stepper drivers down
  8318. #endif
  8319. #ifdef EXTRUDER_RUNOUT_PREVENT
  8320. if(previous_millis_cmd.expired(EXTRUDER_RUNOUT_SECONDS*1000))
  8321. if(degHotend(active_extruder)>EXTRUDER_RUNOUT_MINTEMP)
  8322. {
  8323. bool oldstatus=READ(E0_ENABLE_PIN);
  8324. enable_e0();
  8325. float oldepos=current_position[E_AXIS];
  8326. float oldedes=destination[E_AXIS];
  8327. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS],
  8328. destination[E_AXIS]+EXTRUDER_RUNOUT_EXTRUDE*EXTRUDER_RUNOUT_ESTEPS/cs.axis_steps_per_unit[E_AXIS],
  8329. EXTRUDER_RUNOUT_SPEED/60.*EXTRUDER_RUNOUT_ESTEPS/cs.axis_steps_per_unit[E_AXIS], active_extruder);
  8330. current_position[E_AXIS]=oldepos;
  8331. destination[E_AXIS]=oldedes;
  8332. plan_set_e_position(oldepos);
  8333. previous_millis_cmd.start();
  8334. st_synchronize();
  8335. WRITE(E0_ENABLE_PIN,oldstatus);
  8336. }
  8337. #endif
  8338. check_axes_activity();
  8339. MMU2::mmu2.mmu_loop();
  8340. // handle longpress
  8341. if(lcd_longpress_trigger)
  8342. {
  8343. // long press is not possible in modal mode, wait until ready
  8344. if (lcd_longpress_func && lcd_update_enabled)
  8345. {
  8346. lcd_longpress_func();
  8347. lcd_longpress_trigger = 0;
  8348. }
  8349. }
  8350. #if defined(AUTO_REPORT)
  8351. host_autoreport();
  8352. #endif //AUTO_REPORT
  8353. host_keepalive();
  8354. }
  8355. void kill(const char *full_screen_message, unsigned char id)
  8356. {
  8357. printf_P(_N("KILL: %d\n"), id);
  8358. //return;
  8359. cli(); // Stop interrupts
  8360. disable_heater();
  8361. disable_x();
  8362. // SERIAL_ECHOLNPGM("kill - disable Y");
  8363. disable_y();
  8364. poweroff_z();
  8365. disable_e0();
  8366. disable_e1();
  8367. disable_e2();
  8368. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  8369. pinMode(PS_ON_PIN,INPUT);
  8370. #endif
  8371. SERIAL_ERROR_START;
  8372. SERIAL_ERRORLNRPGM(_n("Printer halted. kill() called!"));////MSG_ERR_KILLED
  8373. if (full_screen_message != NULL) {
  8374. SERIAL_ERRORLNRPGM(full_screen_message);
  8375. lcd_display_message_fullscreen_P(full_screen_message);
  8376. } else {
  8377. LCD_ALERTMESSAGERPGM(_n("KILLED. "));////MSG_KILLED
  8378. }
  8379. // FMC small patch to update the LCD before ending
  8380. sei(); // enable interrupts
  8381. for ( int i=5; i--; lcd_update(0))
  8382. {
  8383. _delay(200);
  8384. }
  8385. cli(); // disable interrupts
  8386. suicide();
  8387. while(1)
  8388. {
  8389. #ifdef WATCHDOG
  8390. wdt_reset();
  8391. #endif //WATCHDOG
  8392. /* Intentionally left empty */
  8393. } // Wait for reset
  8394. }
  8395. void UnconditionalStop()
  8396. {
  8397. CRITICAL_SECTION_START;
  8398. // Disable all heaters and unroll the temperature wait loop stack
  8399. disable_heater();
  8400. cancel_heatup = true;
  8401. heating_status = HeatingStatus::NO_HEATING;
  8402. // Clear any saved printing state
  8403. cancel_saved_printing();
  8404. // Abort the planner
  8405. planner_abort_hard();
  8406. // Reset the queue
  8407. cmdqueue_reset();
  8408. cmdqueue_serial_disabled = false;
  8409. // Reset the sd status
  8410. card.sdprinting = false;
  8411. card.closefile();
  8412. st_reset_timer();
  8413. CRITICAL_SECTION_END;
  8414. }
  8415. // Emergency stop used by overtemp functions which allows recovery
  8416. // WARNING: This function is called *continuously* during a thermal failure.
  8417. //
  8418. // This either pauses (for thermal model errors) or stops *without recovery* depending on
  8419. // "allow_pause". If pause is allowed, this forces a printer-initiated instantanenous pause (just
  8420. // like an LCD pause) that bypasses the host pausing functionality. In this state the printer is
  8421. // kept in busy state and *must* be recovered from the LCD.
  8422. void ThermalStop(bool allow_pause)
  8423. {
  8424. if(Stopped == false) {
  8425. Stopped = true;
  8426. if(allow_pause && (IS_SD_PRINTING || usb_timer.running())) {
  8427. if (!isPrintPaused) {
  8428. lcd_setalertstatuspgm(_T(MSG_PAUSED_THERMAL_ERROR), LCD_STATUS_CRITICAL);
  8429. // we cannot make a distinction for the host here, the pause must be instantaneous
  8430. // so we call the lcd_pause_print to save the print state internally. Thermal errors
  8431. // disable heaters and save the original temperatures to saved_*, which will get
  8432. // overwritten by stop_and_save_print_to_ram. For this corner-case, re-instate the
  8433. // original values after the pause handler is called.
  8434. float bed_temp = saved_bed_temperature;
  8435. float ext_temp = saved_extruder_temperature;
  8436. int fan_speed = saved_fan_speed;
  8437. lcd_pause_print();
  8438. saved_bed_temperature = bed_temp;
  8439. saved_extruder_temperature = ext_temp;
  8440. saved_fan_speed = fan_speed;
  8441. }
  8442. } else {
  8443. // We got a hard thermal error and/or there is no print going on. Just stop.
  8444. lcd_print_stop();
  8445. // Also prevent further menu entry
  8446. menu_set_block(MENU_BLOCK_THERMAL_ERROR);
  8447. }
  8448. // Report the status on the serial, switch to a busy state
  8449. SERIAL_ERROR_START;
  8450. SERIAL_ERRORLNRPGM(MSG_ERR_STOPPED);
  8451. // Eventually report the stopped status on the lcd (though this is usually overridden by a
  8452. // higher-priority alert status message)
  8453. LCD_MESSAGERPGM(_T(MSG_STOPPED));
  8454. // Make a warning sound! We cannot use Sound_MakeCustom as this would stop further moves.
  8455. // Turn on the speaker here (if not already), and turn it off when back in the main loop.
  8456. WRITE(BEEPER, HIGH);
  8457. }
  8458. // Return to the status screen to stop any pending menu action which could have been
  8459. // started by the user while stuck in the Stopped state. This also ensures the NEW
  8460. // error is immediately shown.
  8461. if (menu_menu != lcd_status_screen)
  8462. lcd_return_to_status();
  8463. }
  8464. bool IsStopped() { return Stopped; };
  8465. void finishAndDisableSteppers()
  8466. {
  8467. st_synchronize();
  8468. disable_x();
  8469. disable_y();
  8470. disable_z();
  8471. disable_e0();
  8472. disable_e1();
  8473. disable_e2();
  8474. #ifndef LA_NOCOMPAT
  8475. // Steppers are disabled both when a print is stopped and also via M84 (which is additionally
  8476. // checked-for to indicate a complete file), so abuse this function to reset the LA detection
  8477. // state for the next print.
  8478. la10c_reset();
  8479. #endif
  8480. //in the end of print set estimated time to end of print and extruders used during print to default values for next print
  8481. print_time_remaining_init();
  8482. }
  8483. #ifdef FAST_PWM_FAN
  8484. void setPwmFrequency(uint8_t pin, int val)
  8485. {
  8486. val &= 0x07;
  8487. switch(digitalPinToTimer(pin))
  8488. {
  8489. #if defined(TCCR0A)
  8490. case TIMER0A:
  8491. case TIMER0B:
  8492. // TCCR0B &= ~(_BV(CS00) | _BV(CS01) | _BV(CS02));
  8493. // TCCR0B |= val;
  8494. break;
  8495. #endif
  8496. #if defined(TCCR1A)
  8497. case TIMER1A:
  8498. case TIMER1B:
  8499. // TCCR1B &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  8500. // TCCR1B |= val;
  8501. break;
  8502. #endif
  8503. #if defined(TCCR2)
  8504. case TIMER2:
  8505. case TIMER2:
  8506. TCCR2 &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  8507. TCCR2 |= val;
  8508. break;
  8509. #endif
  8510. #if defined(TCCR2A)
  8511. case TIMER2A:
  8512. case TIMER2B:
  8513. TCCR2B &= ~(_BV(CS20) | _BV(CS21) | _BV(CS22));
  8514. TCCR2B |= val;
  8515. break;
  8516. #endif
  8517. #if defined(TCCR3A)
  8518. case TIMER3A:
  8519. case TIMER3B:
  8520. case TIMER3C:
  8521. TCCR3B &= ~(_BV(CS30) | _BV(CS31) | _BV(CS32));
  8522. TCCR3B |= val;
  8523. break;
  8524. #endif
  8525. #if defined(TCCR4A)
  8526. case TIMER4A:
  8527. case TIMER4B:
  8528. case TIMER4C:
  8529. TCCR4B &= ~(_BV(CS40) | _BV(CS41) | _BV(CS42));
  8530. TCCR4B |= val;
  8531. break;
  8532. #endif
  8533. #if defined(TCCR5A)
  8534. case TIMER5A:
  8535. case TIMER5B:
  8536. case TIMER5C:
  8537. TCCR5B &= ~(_BV(CS50) | _BV(CS51) | _BV(CS52));
  8538. TCCR5B |= val;
  8539. break;
  8540. #endif
  8541. }
  8542. }
  8543. #endif //FAST_PWM_FAN
  8544. //! @brief Get and validate extruder number
  8545. //!
  8546. //! If it is not specified, active_extruder is returned in parameter extruder.
  8547. //! @param [in] code M code number
  8548. //! @param [out] extruder
  8549. //! @return error
  8550. //! @retval true Invalid extruder specified in T code
  8551. //! @retval false Valid extruder specified in T code, or not specifiead
  8552. bool setTargetedHotend(int code, uint8_t &extruder)
  8553. {
  8554. extruder = active_extruder;
  8555. if(code_seen('T')) {
  8556. extruder = code_value_uint8();
  8557. if(extruder >= EXTRUDERS) {
  8558. SERIAL_ECHO_START;
  8559. switch(code){
  8560. case 104:
  8561. SERIAL_ECHORPGM(_n("M104 Invalid extruder "));////MSG_M104_INVALID_EXTRUDER
  8562. break;
  8563. case 105:
  8564. SERIAL_ECHORPGM(_n("M105 Invalid extruder "));////MSG_M105_INVALID_EXTRUDER
  8565. break;
  8566. case 109:
  8567. SERIAL_ECHORPGM(_n("M109 Invalid extruder "));////MSG_M109_INVALID_EXTRUDER
  8568. break;
  8569. case 218:
  8570. SERIAL_ECHORPGM(_n("M218 Invalid extruder "));////MSG_M218_INVALID_EXTRUDER
  8571. break;
  8572. case 221:
  8573. SERIAL_ECHORPGM(_n("M221 Invalid extruder "));////MSG_M221_INVALID_EXTRUDER
  8574. break;
  8575. }
  8576. SERIAL_PROTOCOLLN((int)extruder);
  8577. return true;
  8578. }
  8579. }
  8580. return false;
  8581. }
  8582. void save_statistics(unsigned long _total_filament_used, unsigned long _total_print_time) //_total_filament_used unit: mm/100; print time in s
  8583. {
  8584. 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)
  8585. {
  8586. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, 0);
  8587. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, 0);
  8588. }
  8589. unsigned long _previous_filament = eeprom_read_dword((uint32_t *)EEPROM_FILAMENTUSED); //_previous_filament unit: cm
  8590. unsigned long _previous_time = eeprom_read_dword((uint32_t *)EEPROM_TOTALTIME); //_previous_time unit: min
  8591. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, _previous_time + (_total_print_time/60)); //EEPROM_TOTALTIME unit: min
  8592. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, _previous_filament + (_total_filament_used / 1000));
  8593. total_filament_used = 0;
  8594. }
  8595. float calculate_extruder_multiplier(float diameter) {
  8596. float out = 1.f;
  8597. if (cs.volumetric_enabled && diameter > 0.f) {
  8598. float area = M_PI * diameter * diameter * 0.25;
  8599. out = 1.f / area;
  8600. }
  8601. if (extrudemultiply != 100)
  8602. out *= float(extrudemultiply) * 0.01f;
  8603. return out;
  8604. }
  8605. void calculate_extruder_multipliers() {
  8606. extruder_multiplier[0] = calculate_extruder_multiplier(cs.filament_size[0]);
  8607. #if EXTRUDERS > 1
  8608. extruder_multiplier[1] = calculate_extruder_multiplier(cs.filament_size[1]);
  8609. #if EXTRUDERS > 2
  8610. extruder_multiplier[2] = calculate_extruder_multiplier(cs.filament_size[2]);
  8611. #endif
  8612. #endif
  8613. }
  8614. void delay_keep_alive(unsigned int ms)
  8615. {
  8616. for (;;) {
  8617. manage_heater();
  8618. // Manage inactivity, but don't disable steppers on timeout.
  8619. manage_inactivity(true);
  8620. lcd_update(0);
  8621. if (ms == 0)
  8622. break;
  8623. else if (ms >= 50) {
  8624. _delay(50);
  8625. ms -= 50;
  8626. } else {
  8627. _delay(ms);
  8628. ms = 0;
  8629. }
  8630. }
  8631. }
  8632. static void wait_for_heater(long codenum, uint8_t extruder) {
  8633. if (!degTargetHotend(extruder))
  8634. return;
  8635. #ifdef TEMP_RESIDENCY_TIME
  8636. long residencyStart;
  8637. residencyStart = -1;
  8638. /* continue to loop until we have reached the target temp
  8639. _and_ until TEMP_RESIDENCY_TIME hasn't passed since we reached it */
  8640. cancel_heatup = false;
  8641. while ((!cancel_heatup) && ((residencyStart == -1) ||
  8642. (residencyStart >= 0 && (((unsigned int)(_millis() - residencyStart)) < (TEMP_RESIDENCY_TIME * 1000UL))))) {
  8643. #else
  8644. while (target_direction ? (isHeatingHotend(tmp_extruder)) : (isCoolingHotend(tmp_extruder) && (CooldownNoWait == false))) {
  8645. #endif //TEMP_RESIDENCY_TIME
  8646. if ((_millis() - codenum) > 1000UL)
  8647. { //Print Temp Reading and remaining time every 1 second while heating up/cooling down
  8648. if (!farm_mode) {
  8649. SERIAL_PROTOCOLPGM("T:");
  8650. SERIAL_PROTOCOL_F(degHotend(extruder), 1);
  8651. SERIAL_PROTOCOLPGM(" E:");
  8652. SERIAL_PROTOCOL((int)extruder);
  8653. #ifdef TEMP_RESIDENCY_TIME
  8654. SERIAL_PROTOCOLPGM(" W:");
  8655. if (residencyStart > -1)
  8656. {
  8657. codenum = ((TEMP_RESIDENCY_TIME * 1000UL) - (_millis() - residencyStart)) / 1000UL;
  8658. SERIAL_PROTOCOLLN(codenum);
  8659. }
  8660. else
  8661. {
  8662. SERIAL_PROTOCOLLN('?');
  8663. }
  8664. }
  8665. #else
  8666. SERIAL_PROTOCOLLN();
  8667. #endif
  8668. codenum = _millis();
  8669. }
  8670. manage_heater();
  8671. manage_inactivity(true); //do not disable steppers
  8672. lcd_update(0);
  8673. #ifdef TEMP_RESIDENCY_TIME
  8674. /* start/restart the TEMP_RESIDENCY_TIME timer whenever we reach target temp for the first time
  8675. or when current temp falls outside the hysteresis after target temp was reached */
  8676. if ((residencyStart == -1 && target_direction && (degHotend(extruder) >= (degTargetHotend(extruder) - TEMP_WINDOW))) ||
  8677. (residencyStart == -1 && !target_direction && (degHotend(extruder) <= (degTargetHotend(extruder) + TEMP_WINDOW))) ||
  8678. (residencyStart > -1 && labs(degHotend(extruder) - degTargetHotend(extruder)) > TEMP_HYSTERESIS))
  8679. {
  8680. residencyStart = _millis();
  8681. }
  8682. #endif //TEMP_RESIDENCY_TIME
  8683. }
  8684. }
  8685. void check_babystep()
  8686. {
  8687. int babystep_z = eeprom_read_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->
  8688. s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)));
  8689. if ((babystep_z < Z_BABYSTEP_MIN) || (babystep_z > Z_BABYSTEP_MAX)) {
  8690. babystep_z = 0; //if babystep value is out of min max range, set it to 0
  8691. SERIAL_ECHOLNPGM("Z live adjust out of range. Setting to 0");
  8692. eeprom_write_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->
  8693. s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),
  8694. babystep_z);
  8695. lcd_show_fullscreen_message_and_wait_P(PSTR("Z live adjust out of range. Setting to 0. Click to continue."));
  8696. lcd_update_enable(true);
  8697. }
  8698. }
  8699. #ifdef HEATBED_ANALYSIS
  8700. void d_setup()
  8701. {
  8702. pinMode(D_DATACLOCK, INPUT_PULLUP);
  8703. pinMode(D_DATA, INPUT_PULLUP);
  8704. pinMode(D_REQUIRE, OUTPUT);
  8705. digitalWrite(D_REQUIRE, HIGH);
  8706. }
  8707. float d_ReadData()
  8708. {
  8709. int digit[13];
  8710. String mergeOutput;
  8711. float output;
  8712. digitalWrite(D_REQUIRE, HIGH);
  8713. for (int i = 0; i<13; i++)
  8714. {
  8715. for (int j = 0; j < 4; j++)
  8716. {
  8717. while (digitalRead(D_DATACLOCK) == LOW) {}
  8718. while (digitalRead(D_DATACLOCK) == HIGH) {}
  8719. bitWrite(digit[i], j, digitalRead(D_DATA));
  8720. }
  8721. }
  8722. digitalWrite(D_REQUIRE, LOW);
  8723. mergeOutput = "";
  8724. output = 0;
  8725. for (int r = 5; r <= 10; r++) //Merge digits
  8726. {
  8727. mergeOutput += digit[r];
  8728. }
  8729. output = mergeOutput.toFloat();
  8730. if (digit[4] == 8) //Handle sign
  8731. {
  8732. output *= -1;
  8733. }
  8734. for (int i = digit[11]; i > 0; i--) //Handle floating point
  8735. {
  8736. output /= 10;
  8737. }
  8738. return output;
  8739. }
  8740. void bed_check(float x_dimension, float y_dimension, int x_points_num, int y_points_num, float shift_x, float shift_y) {
  8741. int t1 = 0;
  8742. int t_delay = 0;
  8743. int digit[13];
  8744. int m;
  8745. char str[3];
  8746. //String mergeOutput;
  8747. char mergeOutput[15];
  8748. float output;
  8749. int mesh_point = 0; //index number of calibration point
  8750. 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
  8751. float bed_zero_ref_y = (-0.6f + Y_PROBE_OFFSET_FROM_EXTRUDER);
  8752. float mesh_home_z_search = 4;
  8753. float measure_z_height = 0.2f;
  8754. float row[x_points_num];
  8755. int ix = 0;
  8756. int iy = 0;
  8757. const char* filename_wldsd = "mesh.txt";
  8758. char data_wldsd[x_points_num * 7 + 1]; //6 chars(" -A.BCD")for each measurement + null
  8759. char numb_wldsd[8]; // (" -A.BCD" + null)
  8760. #ifdef MICROMETER_LOGGING
  8761. d_setup();
  8762. #endif //MICROMETER_LOGGING
  8763. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  8764. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  8765. unsigned int custom_message_type_old = custom_message_type;
  8766. unsigned int custom_message_state_old = custom_message_state;
  8767. custom_message_type = CustomMsg::MeshBedLeveling;
  8768. custom_message_state = (x_points_num * y_points_num) + 10;
  8769. lcd_update(1);
  8770. //mbl.reset();
  8771. babystep_undo();
  8772. card.openFile(filename_wldsd, false);
  8773. /*destination[Z_AXIS] = mesh_home_z_search;
  8774. //plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  8775. plan_buffer_line_destinationXYZE(Z_LIFT_FEEDRATE);
  8776. for(int8_t i=0; i < NUM_AXIS; i++) {
  8777. current_position[i] = destination[i];
  8778. }
  8779. st_synchronize();
  8780. */
  8781. destination[Z_AXIS] = measure_z_height;
  8782. plan_buffer_line_destinationXYZE(Z_LIFT_FEEDRATE);
  8783. for(int8_t i=0; i < NUM_AXIS; i++) {
  8784. current_position[i] = destination[i];
  8785. }
  8786. st_synchronize();
  8787. /*int l_feedmultiply = */setup_for_endstop_move(false);
  8788. SERIAL_PROTOCOLPGM("Num X,Y: ");
  8789. SERIAL_PROTOCOL(x_points_num);
  8790. SERIAL_PROTOCOLPGM(",");
  8791. SERIAL_PROTOCOL(y_points_num);
  8792. SERIAL_PROTOCOLPGM("\nZ search height: ");
  8793. SERIAL_PROTOCOL(mesh_home_z_search);
  8794. SERIAL_PROTOCOLPGM("\nDimension X,Y: ");
  8795. SERIAL_PROTOCOL(x_dimension);
  8796. SERIAL_PROTOCOLPGM(",");
  8797. SERIAL_PROTOCOL(y_dimension);
  8798. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  8799. while (mesh_point != x_points_num * y_points_num) {
  8800. ix = mesh_point % x_points_num; // from 0 to MESH_NUM_X_POINTS - 1
  8801. iy = mesh_point / x_points_num;
  8802. if (iy & 1) ix = (x_points_num - 1) - ix; // Zig zag
  8803. float z0 = 0.f;
  8804. /*destination[Z_AXIS] = mesh_home_z_search;
  8805. //plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  8806. plan_buffer_line_destinationXYZE(Z_LIFT_FEEDRATE);
  8807. for(int8_t i=0; i < NUM_AXIS; i++) {
  8808. current_position[i] = destination[i];
  8809. }
  8810. st_synchronize();*/
  8811. //current_position[X_AXIS] = 13.f + ix * (x_dimension / (x_points_num - 1)) - bed_zero_ref_x + shift_x;
  8812. //current_position[Y_AXIS] = 6.4f + iy * (y_dimension / (y_points_num - 1)) - bed_zero_ref_y + shift_y;
  8813. destination[X_AXIS] = ix * (x_dimension / (x_points_num - 1)) + shift_x;
  8814. destination[Y_AXIS] = iy * (y_dimension / (y_points_num - 1)) + shift_y;
  8815. mesh_plan_buffer_line_destinationXYZE(XY_AXIS_FEEDRATE/6);
  8816. set_current_to_destination();
  8817. st_synchronize();
  8818. // printf_P(PSTR("X = %f; Y= %f \n"), current_position[X_AXIS], current_position[Y_AXIS]);
  8819. delay_keep_alive(1000);
  8820. #ifdef MICROMETER_LOGGING
  8821. //memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8822. //dtostrf(d_ReadData(), 8, 5, numb_wldsd);
  8823. //strcat(data_wldsd, numb_wldsd);
  8824. //MYSERIAL.println(data_wldsd);
  8825. //delay(1000);
  8826. //delay(3000);
  8827. //t1 = millis();
  8828. //while (digitalRead(D_DATACLOCK) == LOW) {}
  8829. //while (digitalRead(D_DATACLOCK) == HIGH) {}
  8830. memset(digit, 0, sizeof(digit));
  8831. //cli();
  8832. digitalWrite(D_REQUIRE, LOW);
  8833. for (int i = 0; i<13; i++)
  8834. {
  8835. //t1 = millis();
  8836. for (int j = 0; j < 4; j++)
  8837. {
  8838. while (digitalRead(D_DATACLOCK) == LOW) {}
  8839. while (digitalRead(D_DATACLOCK) == HIGH) {}
  8840. //printf_P(PSTR("Done %d\n"), j);
  8841. bitWrite(digit[i], j, digitalRead(D_DATA));
  8842. }
  8843. //t_delay = (millis() - t1);
  8844. //SERIAL_PROTOCOLPGM(" ");
  8845. //SERIAL_PROTOCOL_F(t_delay, 5);
  8846. //SERIAL_PROTOCOLPGM(" ");
  8847. }
  8848. //sei();
  8849. digitalWrite(D_REQUIRE, HIGH);
  8850. mergeOutput[0] = '\0';
  8851. output = 0;
  8852. for (int r = 5; r <= 10; r++) //Merge digits
  8853. {
  8854. sprintf(str, "%d", digit[r]);
  8855. strcat(mergeOutput, str);
  8856. }
  8857. output = atof(mergeOutput);
  8858. if (digit[4] == 8) //Handle sign
  8859. {
  8860. output *= -1;
  8861. }
  8862. for (int i = digit[11]; i > 0; i--) //Handle floating point
  8863. {
  8864. output *= 0.1;
  8865. }
  8866. //output = d_ReadData();
  8867. //row[ix] = current_position[Z_AXIS];
  8868. //row[ix] = d_ReadData();
  8869. row[ix] = output;
  8870. if (iy % 2 == 1 ? ix == 0 : ix == x_points_num - 1) {
  8871. memset(data_wldsd, 0, sizeof(data_wldsd));
  8872. for (int i = 0; i < x_points_num; i++) {
  8873. SERIAL_PROTOCOLPGM(" ");
  8874. SERIAL_PROTOCOL_F(row[i], 5);
  8875. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8876. dtostrf(row[i], 7, 3, numb_wldsd);
  8877. strcat(data_wldsd, numb_wldsd);
  8878. }
  8879. card.write_command(data_wldsd);
  8880. SERIAL_PROTOCOLPGM("\n");
  8881. }
  8882. custom_message_state--;
  8883. mesh_point++;
  8884. lcd_update(1);
  8885. }
  8886. #endif //MICROMETER_LOGGING
  8887. card.closefile();
  8888. //clean_up_after_endstop_move(l_feedmultiply);
  8889. }
  8890. void bed_analysis(float x_dimension, float y_dimension, int x_points_num, int y_points_num, float shift_x, float shift_y) {
  8891. int t1 = 0;
  8892. int t_delay = 0;
  8893. int digit[13];
  8894. int m;
  8895. char str[3];
  8896. //String mergeOutput;
  8897. char mergeOutput[15];
  8898. float output;
  8899. int mesh_point = 0; //index number of calibration point
  8900. 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
  8901. float bed_zero_ref_y = (-0.6f + Y_PROBE_OFFSET_FROM_EXTRUDER);
  8902. float mesh_home_z_search = 4;
  8903. float row[x_points_num];
  8904. int ix = 0;
  8905. int iy = 0;
  8906. const char* filename_wldsd = "wldsd.txt";
  8907. char data_wldsd[70];
  8908. char numb_wldsd[10];
  8909. d_setup();
  8910. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  8911. // We don't know where we are! HOME!
  8912. // Push the commands to the front of the message queue in the reverse order!
  8913. // There shall be always enough space reserved for these commands.
  8914. repeatcommand_front(); // repeat G80 with all its parameters
  8915. enquecommand_front_P(G28W0);
  8916. enquecommand_front_P((PSTR("G1 Z5")));
  8917. return;
  8918. }
  8919. unsigned int custom_message_type_old = custom_message_type;
  8920. unsigned int custom_message_state_old = custom_message_state;
  8921. custom_message_type = CustomMsg::MeshBedLeveling;
  8922. custom_message_state = (x_points_num * y_points_num) + 10;
  8923. lcd_update(1);
  8924. mbl.reset();
  8925. babystep_undo();
  8926. card.openFile(filename_wldsd, false);
  8927. current_position[Z_AXIS] = mesh_home_z_search;
  8928. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 60, active_extruder);
  8929. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  8930. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  8931. int l_feedmultiply = setup_for_endstop_move(false);
  8932. SERIAL_PROTOCOLPGM("Num X,Y: ");
  8933. SERIAL_PROTOCOL(x_points_num);
  8934. SERIAL_PROTOCOLPGM(",");
  8935. SERIAL_PROTOCOL(y_points_num);
  8936. SERIAL_PROTOCOLPGM("\nZ search height: ");
  8937. SERIAL_PROTOCOL(mesh_home_z_search);
  8938. SERIAL_PROTOCOLPGM("\nDimension X,Y: ");
  8939. SERIAL_PROTOCOL(x_dimension);
  8940. SERIAL_PROTOCOLPGM(",");
  8941. SERIAL_PROTOCOL(y_dimension);
  8942. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  8943. while (mesh_point != x_points_num * y_points_num) {
  8944. ix = mesh_point % x_points_num; // from 0 to MESH_NUM_X_POINTS - 1
  8945. iy = mesh_point / x_points_num;
  8946. if (iy & 1) ix = (x_points_num - 1) - ix; // Zig zag
  8947. float z0 = 0.f;
  8948. current_position[Z_AXIS] = mesh_home_z_search;
  8949. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE, active_extruder);
  8950. st_synchronize();
  8951. current_position[X_AXIS] = 13.f + ix * (x_dimension / (x_points_num - 1)) - bed_zero_ref_x + shift_x;
  8952. current_position[Y_AXIS] = 6.4f + iy * (y_dimension / (y_points_num - 1)) - bed_zero_ref_y + shift_y;
  8953. plan_buffer_line_curposXYZE(XY_AXIS_FEEDRATE, active_extruder);
  8954. st_synchronize();
  8955. 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
  8956. break;
  8957. card.closefile();
  8958. }
  8959. //memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8960. //dtostrf(d_ReadData(), 8, 5, numb_wldsd);
  8961. //strcat(data_wldsd, numb_wldsd);
  8962. //MYSERIAL.println(data_wldsd);
  8963. //_delay(1000);
  8964. //_delay(3000);
  8965. //t1 = _millis();
  8966. //while (digitalRead(D_DATACLOCK) == LOW) {}
  8967. //while (digitalRead(D_DATACLOCK) == HIGH) {}
  8968. memset(digit, 0, sizeof(digit));
  8969. //cli();
  8970. digitalWrite(D_REQUIRE, LOW);
  8971. for (int i = 0; i<13; i++)
  8972. {
  8973. //t1 = _millis();
  8974. for (int j = 0; j < 4; j++)
  8975. {
  8976. while (digitalRead(D_DATACLOCK) == LOW) {}
  8977. while (digitalRead(D_DATACLOCK) == HIGH) {}
  8978. bitWrite(digit[i], j, digitalRead(D_DATA));
  8979. }
  8980. //t_delay = (_millis() - t1);
  8981. //SERIAL_PROTOCOLPGM(" ");
  8982. //SERIAL_PROTOCOL_F(t_delay, 5);
  8983. //SERIAL_PROTOCOLPGM(" ");
  8984. }
  8985. //sei();
  8986. digitalWrite(D_REQUIRE, HIGH);
  8987. mergeOutput[0] = '\0';
  8988. output = 0;
  8989. for (int r = 5; r <= 10; r++) //Merge digits
  8990. {
  8991. sprintf(str, "%d", digit[r]);
  8992. strcat(mergeOutput, str);
  8993. }
  8994. output = atof(mergeOutput);
  8995. if (digit[4] == 8) //Handle sign
  8996. {
  8997. output *= -1;
  8998. }
  8999. for (int i = digit[11]; i > 0; i--) //Handle floating point
  9000. {
  9001. output *= 0.1;
  9002. }
  9003. //output = d_ReadData();
  9004. //row[ix] = current_position[Z_AXIS];
  9005. memset(data_wldsd, 0, sizeof(data_wldsd));
  9006. for (int i = 0; i <3; i++) {
  9007. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  9008. dtostrf(current_position[i], 8, 5, numb_wldsd);
  9009. strcat(data_wldsd, numb_wldsd);
  9010. strcat(data_wldsd, ";");
  9011. }
  9012. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  9013. dtostrf(output, 8, 5, numb_wldsd);
  9014. strcat(data_wldsd, numb_wldsd);
  9015. //strcat(data_wldsd, ";");
  9016. card.write_command(data_wldsd);
  9017. //row[ix] = d_ReadData();
  9018. row[ix] = output; // current_position[Z_AXIS];
  9019. if (iy % 2 == 1 ? ix == 0 : ix == x_points_num - 1) {
  9020. for (int i = 0; i < x_points_num; i++) {
  9021. SERIAL_PROTOCOLPGM(" ");
  9022. SERIAL_PROTOCOL_F(row[i], 5);
  9023. }
  9024. SERIAL_PROTOCOLPGM("\n");
  9025. }
  9026. custom_message_state--;
  9027. mesh_point++;
  9028. lcd_update(1);
  9029. }
  9030. card.closefile();
  9031. clean_up_after_endstop_move(l_feedmultiply);
  9032. }
  9033. #endif //HEATBED_ANALYSIS
  9034. #ifndef PINDA_THERMISTOR
  9035. static void temp_compensation_start() {
  9036. custom_message_type = CustomMsg::TempCompPreheat;
  9037. custom_message_state = PINDA_HEAT_T + 1;
  9038. lcd_update(2);
  9039. if ((int)degHotend(active_extruder) > extrude_min_temp) {
  9040. current_position[E_AXIS] -= default_retraction;
  9041. }
  9042. plan_buffer_line_curposXYZE(400, active_extruder);
  9043. current_position[X_AXIS] = PINDA_PREHEAT_X;
  9044. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  9045. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  9046. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  9047. st_synchronize();
  9048. while (fabs(degBed() - target_temperature_bed) > 1) delay_keep_alive(1000);
  9049. for (int i = 0; i < PINDA_HEAT_T; i++) {
  9050. delay_keep_alive(1000);
  9051. custom_message_state = PINDA_HEAT_T - i;
  9052. if (custom_message_state == 99 || custom_message_state == 9) lcd_update(2); //force whole display redraw if number of digits changed
  9053. else lcd_update(1);
  9054. }
  9055. custom_message_type = CustomMsg::Status;
  9056. custom_message_state = 0;
  9057. }
  9058. static void temp_compensation_apply() {
  9059. int i_add;
  9060. int z_shift = 0;
  9061. float z_shift_mm;
  9062. if (calibration_status() == CALIBRATION_STATUS_CALIBRATED) {
  9063. if (target_temperature_bed % 10 == 0 && target_temperature_bed >= 60 && target_temperature_bed <= 100) {
  9064. i_add = (target_temperature_bed - 60) / 10;
  9065. z_shift = eeprom_read_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i_add);
  9066. z_shift_mm = z_shift / cs.axis_steps_per_unit[Z_AXIS];
  9067. }else {
  9068. //interpolation
  9069. z_shift_mm = temp_comp_interpolation(target_temperature_bed) / cs.axis_steps_per_unit[Z_AXIS];
  9070. }
  9071. printf_P(_N("\nZ shift applied:%.3f\n"), z_shift_mm);
  9072. 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);
  9073. st_synchronize();
  9074. plan_set_z_position(current_position[Z_AXIS]);
  9075. }
  9076. else {
  9077. //we have no temp compensation data
  9078. }
  9079. }
  9080. #endif //ndef PINDA_THERMISTOR
  9081. float temp_comp_interpolation(float inp_temperature) {
  9082. //cubic spline interpolation
  9083. int n, i, j;
  9084. float h[10], a, b, c, d, sum, s[10] = { 0 }, x[10], F[10], f[10], m[10][10] = { 0 }, temp;
  9085. int shift[10];
  9086. int temp_C[10];
  9087. n = 6; //number of measured points
  9088. shift[0] = 0;
  9089. for (i = 0; i < n; i++) {
  9090. if (i > 0) {
  9091. //read shift in steps from EEPROM
  9092. shift[i] = eeprom_read_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + (i - 1));
  9093. }
  9094. temp_C[i] = 50 + i * 10; //temperature in C
  9095. #ifdef PINDA_THERMISTOR
  9096. constexpr int start_compensating_temp = 35;
  9097. temp_C[i] = start_compensating_temp + i * 5; //temperature in degrees C
  9098. #ifdef SUPERPINDA_SUPPORT
  9099. static_assert(start_compensating_temp >= PINDA_MINTEMP, "Temperature compensation start point is lower than PINDA_MINTEMP.");
  9100. #endif //SUPERPINDA_SUPPORT
  9101. #else
  9102. temp_C[i] = 50 + i * 10; //temperature in C
  9103. #endif
  9104. x[i] = (float)temp_C[i];
  9105. f[i] = (float)shift[i];
  9106. }
  9107. if (inp_temperature < x[0]) return 0;
  9108. for (i = n - 1; i>0; i--) {
  9109. F[i] = (f[i] - f[i - 1]) / (x[i] - x[i - 1]);
  9110. h[i - 1] = x[i] - x[i - 1];
  9111. }
  9112. //*********** formation of h, s , f matrix **************
  9113. for (i = 1; i<n - 1; i++) {
  9114. m[i][i] = 2 * (h[i - 1] + h[i]);
  9115. if (i != 1) {
  9116. m[i][i - 1] = h[i - 1];
  9117. m[i - 1][i] = h[i - 1];
  9118. }
  9119. m[i][n - 1] = 6 * (F[i + 1] - F[i]);
  9120. }
  9121. //*********** forward elimination **************
  9122. for (i = 1; i<n - 2; i++) {
  9123. temp = (m[i + 1][i] / m[i][i]);
  9124. for (j = 1; j <= n - 1; j++)
  9125. m[i + 1][j] -= temp*m[i][j];
  9126. }
  9127. //*********** backward substitution *********
  9128. for (i = n - 2; i>0; i--) {
  9129. sum = 0;
  9130. for (j = i; j <= n - 2; j++)
  9131. sum += m[i][j] * s[j];
  9132. s[i] = (m[i][n - 1] - sum) / m[i][i];
  9133. }
  9134. for (i = 0; i<n - 1; i++)
  9135. if ((x[i] <= inp_temperature && inp_temperature <= x[i + 1]) || (i == n-2 && inp_temperature > x[i + 1])) {
  9136. a = (s[i + 1] - s[i]) / (6 * h[i]);
  9137. b = s[i] / 2;
  9138. c = (f[i + 1] - f[i]) / h[i] - (2 * h[i] * s[i] + s[i + 1] * h[i]) / 6;
  9139. d = f[i];
  9140. sum = a*pow((inp_temperature - x[i]), 3) + b*pow((inp_temperature - x[i]), 2) + c*(inp_temperature - x[i]) + d;
  9141. }
  9142. return sum;
  9143. }
  9144. #ifdef PINDA_THERMISTOR
  9145. float temp_compensation_pinda_thermistor_offset(float temperature_pinda)
  9146. {
  9147. if (!eeprom_read_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE)) return 0;
  9148. if (!calibration_status_pinda()) return 0;
  9149. return temp_comp_interpolation(temperature_pinda) / cs.axis_steps_per_unit[Z_AXIS];
  9150. }
  9151. #endif //PINDA_THERMISTOR
  9152. void long_pause() //long pause print
  9153. {
  9154. st_synchronize();
  9155. start_pause_print = _millis();
  9156. // Stop heaters
  9157. heating_status = HeatingStatus::NO_HEATING;
  9158. setAllTargetHotends(0);
  9159. // Lift z
  9160. raise_z(Z_PAUSE_LIFT);
  9161. // Move XY to side
  9162. if (axis_known_position[X_AXIS] && axis_known_position[Y_AXIS]) {
  9163. current_position[X_AXIS] = X_PAUSE_POS;
  9164. current_position[Y_AXIS] = Y_PAUSE_POS;
  9165. plan_buffer_line_curposXYZE(50);
  9166. }
  9167. // did we come here from a thermal error?
  9168. if(get_temp_error()) {
  9169. // time to stop the error beep
  9170. WRITE(BEEPER, LOW);
  9171. } else {
  9172. // Turn off the print fan
  9173. fanSpeed = 0;
  9174. }
  9175. }
  9176. void serialecho_temperatures() {
  9177. float tt = degHotend(active_extruder);
  9178. SERIAL_PROTOCOLPGM("T:");
  9179. SERIAL_PROTOCOL(tt);
  9180. SERIAL_PROTOCOLPGM(" E:");
  9181. SERIAL_PROTOCOL((int)active_extruder);
  9182. SERIAL_PROTOCOLPGM(" B:");
  9183. SERIAL_PROTOCOL_F(degBed(), 1);
  9184. SERIAL_PROTOCOLLN();
  9185. }
  9186. #ifdef UVLO_SUPPORT
  9187. void uvlo_drain_reset()
  9188. {
  9189. // burn all that residual power
  9190. wdt_enable(WDTO_1S);
  9191. WRITE(BEEPER,HIGH);
  9192. lcd_clear();
  9193. lcd_puts_at_P(0, 1, MSG_POWERPANIC_DETECTED);
  9194. while(1);
  9195. }
  9196. void uvlo_()
  9197. {
  9198. unsigned long time_start = _millis();
  9199. bool sd_print = card.sdprinting;
  9200. // Conserve power as soon as possible.
  9201. #ifdef LCD_BL_PIN
  9202. backlightMode = BACKLIGHT_MODE_DIM;
  9203. backlightLevel_LOW = 0;
  9204. backlight_update();
  9205. #endif //LCD_BL_PIN
  9206. disable_x();
  9207. disable_y();
  9208. #ifdef TMC2130
  9209. tmc2130_set_current_h(Z_AXIS, 20);
  9210. tmc2130_set_current_r(Z_AXIS, 20);
  9211. tmc2130_set_current_h(E_AXIS, 20);
  9212. tmc2130_set_current_r(E_AXIS, 20);
  9213. #endif //TMC2130
  9214. // Stop all heaters
  9215. uint8_t saved_target_temperature_bed = target_temperature_bed;
  9216. uint16_t saved_target_temperature_ext = target_temperature[active_extruder];
  9217. setAllTargetHotends(0);
  9218. setTargetBed(0);
  9219. // Calculate the file position, from which to resume this print.
  9220. long sd_position = sdpos_atomic; //atomic sd position of last command added in queue
  9221. {
  9222. uint16_t sdlen_planner = planner_calc_sd_length(); //length of sd commands in planner
  9223. sd_position -= sdlen_planner;
  9224. uint16_t sdlen_cmdqueue = cmdqueue_calc_sd_length(); //length of sd commands in cmdqueue
  9225. sd_position -= sdlen_cmdqueue;
  9226. if (sd_position < 0) sd_position = 0;
  9227. }
  9228. // save the global state at planning time
  9229. bool pos_invalid = XY_NO_RESTORE_FLAG;
  9230. uint16_t feedrate_bckp;
  9231. if (current_block && !pos_invalid)
  9232. {
  9233. memcpy(saved_start_position, current_block->gcode_start_position, sizeof(saved_start_position));
  9234. feedrate_bckp = current_block->gcode_feedrate;
  9235. saved_segment_idx = current_block->segment_idx;
  9236. }
  9237. else
  9238. {
  9239. saved_start_position[0] = SAVED_START_POSITION_UNSET;
  9240. feedrate_bckp = feedrate;
  9241. saved_segment_idx = 0;
  9242. }
  9243. // From this point on and up to the print recovery, Z should not move during X/Y travels and
  9244. // should be controlled precisely. Reset the MBL status before planner_abort_hard in order to
  9245. // get the physical Z for further manipulation.
  9246. bool mbl_was_active = mbl.active;
  9247. mbl.active = false;
  9248. // After this call, the planner queue is emptied and the current_position is set to a current logical coordinate.
  9249. // The logical coordinate will likely differ from the machine coordinate if the skew calibration and mesh bed leveling
  9250. // are in action.
  9251. planner_abort_hard();
  9252. // Store the print logical Z position, which we need to recover (a slight error here would be
  9253. // recovered on the next Gcode instruction, while a physical location error would not)
  9254. float logical_z = current_position[Z_AXIS];
  9255. if(mbl_was_active) logical_z -= mbl.get_z(st_get_position_mm(X_AXIS), st_get_position_mm(Y_AXIS));
  9256. eeprom_update_float((float*)EEPROM_UVLO_CURRENT_POSITION_Z, logical_z);
  9257. // Store the print E position before we lose track
  9258. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION_E), current_position[E_AXIS]);
  9259. eeprom_update_byte((uint8_t*)EEPROM_UVLO_E_ABS, (axis_relative_modes & E_AXIS_MASK)?0:1);
  9260. // Clean the input command queue, inhibit serial processing using saved_printing
  9261. cmdqueue_reset();
  9262. card.sdprinting = false;
  9263. saved_printing = true;
  9264. // Enable stepper driver interrupt to move Z axis. This should be fine as the planner and
  9265. // command queues are empty, SD card printing is disabled, usb is inhibited.
  9266. planner_aborted = false;
  9267. sei();
  9268. // Retract
  9269. current_position[E_AXIS] -= default_retraction;
  9270. plan_buffer_line_curposXYZE(95);
  9271. st_synchronize();
  9272. disable_e0();
  9273. // Read out the current Z motor microstep counter to move the axis up towards
  9274. // a full step before powering off. NOTE: we need to ensure to schedule more
  9275. // than "dropsegments" steps in order to move (this is always the case here
  9276. // due to UVLO_Z_AXIS_SHIFT being used)
  9277. uint16_t z_res = tmc2130_get_res(Z_AXIS);
  9278. uint16_t z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9279. current_position[Z_AXIS] += float(1024 - z_microsteps)
  9280. / (z_res * cs.axis_steps_per_unit[Z_AXIS])
  9281. + UVLO_Z_AXIS_SHIFT;
  9282. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS]/60);
  9283. st_synchronize();
  9284. poweroff_z();
  9285. // Write the file position.
  9286. eeprom_update_dword((uint32_t*)(EEPROM_FILE_POSITION), sd_position);
  9287. // Store the mesh bed leveling offsets. This is 2*7*7=98 bytes, which takes 98*3.4us=333us in worst case.
  9288. for (uint8_t mesh_point = 0; mesh_point < MESH_NUM_X_POINTS * MESH_NUM_Y_POINTS; ++ mesh_point) {
  9289. uint8_t ix = mesh_point % MESH_NUM_X_POINTS; // from 0 to MESH_NUM_X_POINTS - 1
  9290. uint8_t iy = mesh_point / MESH_NUM_X_POINTS;
  9291. // Scale the z value to 1u resolution.
  9292. int16_t v = mbl_was_active ? int16_t(floor(mbl.z_values[iy][ix] * 1000.f + 0.5f)) : 0;
  9293. eeprom_update_word((uint16_t*)(EEPROM_UVLO_MESH_BED_LEVELING_FULL +2*mesh_point), *reinterpret_cast<uint16_t*>(&v));
  9294. }
  9295. // Write the _final_ Z position and motor microstep counter (unused).
  9296. eeprom_update_float((float*)EEPROM_UVLO_TINY_CURRENT_POSITION_Z, current_position[Z_AXIS]);
  9297. z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9298. eeprom_update_word((uint16_t*)(EEPROM_UVLO_Z_MICROSTEPS), z_microsteps);
  9299. // Store the current position.
  9300. if (pos_invalid)
  9301. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0), X_COORD_INVALID);
  9302. else
  9303. {
  9304. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0), current_position[X_AXIS]);
  9305. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 4), current_position[Y_AXIS]);
  9306. }
  9307. // Store the current feed rate, temperatures, fan speed and extruder multipliers (flow rates)
  9308. eeprom_update_word((uint16_t*)EEPROM_UVLO_FEEDRATE, feedrate_bckp);
  9309. eeprom_update_word((uint16_t*)EEPROM_UVLO_FEEDMULTIPLY, feedmultiply);
  9310. eeprom_update_word((uint16_t*)EEPROM_UVLO_TARGET_HOTEND, saved_target_temperature_ext);
  9311. eeprom_update_byte((uint8_t*)EEPROM_UVLO_TARGET_BED, saved_target_temperature_bed);
  9312. eeprom_update_byte((uint8_t*)EEPROM_UVLO_FAN_SPEED, fanSpeed);
  9313. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_0), extruder_multiplier[0]);
  9314. #if EXTRUDERS > 1
  9315. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_1), extruder_multiplier[1]);
  9316. #if EXTRUDERS > 2
  9317. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_2), extruder_multiplier[2]);
  9318. #endif
  9319. #endif
  9320. eeprom_update_word((uint16_t*)(EEPROM_EXTRUDEMULTIPLY), (uint16_t)extrudemultiply);
  9321. eeprom_update_float((float*)(EEPROM_UVLO_ACCELL), cs.acceleration);
  9322. eeprom_update_float((float*)(EEPROM_UVLO_RETRACT_ACCELL), cs.retract_acceleration);
  9323. eeprom_update_float((float*)(EEPROM_UVLO_TRAVEL_ACCELL), cs.travel_acceleration);
  9324. // Store the saved target
  9325. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+0*4), saved_start_position[X_AXIS]);
  9326. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+1*4), saved_start_position[Y_AXIS]);
  9327. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+2*4), saved_start_position[Z_AXIS]);
  9328. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+3*4), saved_start_position[E_AXIS]);
  9329. eeprom_update_word((uint16_t*)EEPROM_UVLO_SAVED_SEGMENT_IDX, saved_segment_idx);
  9330. #ifdef LIN_ADVANCE
  9331. eeprom_update_float((float*)(EEPROM_UVLO_LA_K), extruder_advance_K);
  9332. #endif
  9333. // Finaly store the "power outage" flag.
  9334. if(sd_print) eeprom_update_byte((uint8_t*)EEPROM_UVLO, 1);
  9335. // Increment power failure counter
  9336. eeprom_update_byte((uint8_t*)EEPROM_POWER_COUNT, eeprom_read_byte((uint8_t*)EEPROM_POWER_COUNT) + 1);
  9337. eeprom_update_word((uint16_t*)EEPROM_POWER_COUNT_TOT, eeprom_read_word((uint16_t*)EEPROM_POWER_COUNT_TOT) + 1);
  9338. printf_P(_N("UVLO - end %d\n"), _millis() - time_start);
  9339. WRITE(BEEPER,HIGH);
  9340. // All is set: with all the juice left, try to move extruder away to detach the nozzle completely from the print
  9341. poweron_z();
  9342. current_position[X_AXIS] = (current_position[X_AXIS] < 0.5f * (X_MIN_POS + X_MAX_POS)) ? X_MIN_POS : X_MAX_POS;
  9343. plan_buffer_line_curposXYZE(500);
  9344. st_synchronize();
  9345. wdt_enable(WDTO_1S);
  9346. while(1);
  9347. }
  9348. void uvlo_tiny()
  9349. {
  9350. unsigned long time_start = _millis();
  9351. // Conserve power as soon as possible.
  9352. disable_x();
  9353. disable_y();
  9354. disable_e0();
  9355. #ifdef TMC2130
  9356. tmc2130_set_current_h(Z_AXIS, 20);
  9357. tmc2130_set_current_r(Z_AXIS, 20);
  9358. #endif //TMC2130
  9359. // Stop all heaters
  9360. setAllTargetHotends(0);
  9361. setTargetBed(0);
  9362. // When power is interrupted on the _first_ recovery an attempt can be made to raise the
  9363. // extruder, causing the Z position to change. Similarly, when recovering, the Z position is
  9364. // lowered. In such cases we cannot just save Z, we need to re-align the steppers to a fullstep.
  9365. // Disable MBL (if not already) to work with physical coordinates.
  9366. mbl.active = false;
  9367. planner_abort_hard();
  9368. // Allow for small roundoffs to be ignored
  9369. 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])
  9370. {
  9371. // Clean the input command queue, inhibit serial processing using saved_printing
  9372. cmdqueue_reset();
  9373. card.sdprinting = false;
  9374. saved_printing = true;
  9375. // Enable stepper driver interrupt to move Z axis. This should be fine as the planner and
  9376. // command queues are empty, SD card printing is disabled, usb is inhibited.
  9377. planner_aborted = false;
  9378. sei();
  9379. // The axis was moved: adjust Z as done on a regular UVLO.
  9380. uint16_t z_res = tmc2130_get_res(Z_AXIS);
  9381. uint16_t z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9382. current_position[Z_AXIS] += float(1024 - z_microsteps)
  9383. / (z_res * cs.axis_steps_per_unit[Z_AXIS])
  9384. + UVLO_TINY_Z_AXIS_SHIFT;
  9385. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS]/60);
  9386. st_synchronize();
  9387. poweroff_z();
  9388. // Update Z position
  9389. eeprom_update_float((float*)(EEPROM_UVLO_TINY_CURRENT_POSITION_Z), current_position[Z_AXIS]);
  9390. // Update the _final_ Z motor microstep counter (unused).
  9391. z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9392. eeprom_update_word((uint16_t*)(EEPROM_UVLO_Z_MICROSTEPS), z_microsteps);
  9393. }
  9394. // Update the the "power outage" flag.
  9395. eeprom_update_byte((uint8_t*)EEPROM_UVLO,2);
  9396. // Increment power failure counter
  9397. eeprom_update_byte((uint8_t*)EEPROM_POWER_COUNT, eeprom_read_byte((uint8_t*)EEPROM_POWER_COUNT) + 1);
  9398. eeprom_update_word((uint16_t*)EEPROM_POWER_COUNT_TOT, eeprom_read_word((uint16_t*)EEPROM_POWER_COUNT_TOT) + 1);
  9399. printf_P(_N("UVLO_TINY - end %d\n"), _millis() - time_start);
  9400. uvlo_drain_reset();
  9401. }
  9402. #endif //UVLO_SUPPORT
  9403. #if (defined(FANCHECK) && defined(TACH_1) && (TACH_1 >-1))
  9404. void setup_fan_interrupt() {
  9405. //INT7
  9406. DDRE &= ~(1 << 7); //input pin
  9407. PORTE &= ~(1 << 7); //no internal pull-up
  9408. //start with sensing rising edge
  9409. EICRB &= ~(1 << 6);
  9410. EICRB |= (1 << 7);
  9411. //enable INT7 interrupt
  9412. EIMSK |= (1 << 7);
  9413. }
  9414. // The fan interrupt is triggered at maximum 325Hz (may be a bit more due to component tollerances),
  9415. // and it takes 4.24 us to process (the interrupt invocation overhead not taken into account).
  9416. ISR(INT7_vect) {
  9417. //measuring speed now works for fanSpeed > 18 (approximately), which is sufficient because MIN_PRINT_FAN_SPEED is higher
  9418. #ifdef FAN_SOFT_PWM
  9419. if (!fan_measuring || (fanSpeedSoftPwm < MIN_PRINT_FAN_SPEED)) return;
  9420. #else //FAN_SOFT_PWM
  9421. if (fanSpeed < MIN_PRINT_FAN_SPEED) return;
  9422. #endif //FAN_SOFT_PWM
  9423. if ((1 << 6) & EICRB) { //interrupt was triggered by rising edge
  9424. t_fan_rising_edge = millis_nc();
  9425. }
  9426. else { //interrupt was triggered by falling edge
  9427. if ((millis_nc() - t_fan_rising_edge) >= FAN_PULSE_WIDTH_LIMIT) {//this pulse was from sensor and not from pwm
  9428. fan_edge_counter[1] += 2; //we are currently counting all edges so lets count two edges for one pulse
  9429. }
  9430. }
  9431. EICRB ^= (1 << 6); //change edge
  9432. }
  9433. #endif
  9434. #ifdef UVLO_SUPPORT
  9435. void setup_uvlo_interrupt() {
  9436. DDRE &= ~(1 << 4); //input pin
  9437. PORTE &= ~(1 << 4); //no internal pull-up
  9438. // sensing falling edge
  9439. EICRB |= (1 << 0);
  9440. EICRB &= ~(1 << 1);
  9441. // enable INT4 interrupt
  9442. EIMSK |= (1 << 4);
  9443. // check if power was lost before we armed the interrupt
  9444. if(!(PINE & (1 << 4)) && eeprom_read_byte((uint8_t*)EEPROM_UVLO))
  9445. {
  9446. SERIAL_ECHOLNPGM("INT4");
  9447. uvlo_drain_reset();
  9448. }
  9449. }
  9450. ISR(INT4_vect) {
  9451. EIMSK &= ~(1 << 4); //disable INT4 interrupt to make sure that this code will be executed just once
  9452. SERIAL_ECHOLNPGM("INT4");
  9453. //fire normal uvlo only in case where EEPROM_UVLO is 0 or if IS_SD_PRINTING is 1.
  9454. if(printer_active() && (!(eeprom_read_byte((uint8_t*)EEPROM_UVLO)))) uvlo_();
  9455. if(eeprom_read_byte((uint8_t*)EEPROM_UVLO)) uvlo_tiny();
  9456. }
  9457. void recover_print(uint8_t automatic) {
  9458. char cmd[30];
  9459. lcd_update_enable(true);
  9460. lcd_update(2);
  9461. lcd_setstatuspgm(_i("Recovering print"));////MSG_RECOVERING_PRINT c=20
  9462. // Recover position, temperatures and extrude_multipliers
  9463. bool mbl_was_active = recover_machine_state_after_power_panic();
  9464. // Lift the print head 25mm, first to avoid collisions with oozed material with the print,
  9465. // and second also so one may remove the excess priming material.
  9466. if(eeprom_read_byte((uint8_t*)EEPROM_UVLO) == 1)
  9467. {
  9468. sprintf_P(cmd, PSTR("G1 Z%.3f F800"), current_position[Z_AXIS] + 25);
  9469. enquecommand(cmd);
  9470. }
  9471. // Home X and Y axes. Homing just X and Y shall not touch the babystep and the world2machine
  9472. // transformation status. G28 will not touch Z when MBL is off.
  9473. enquecommand_P(PSTR("G28 X Y"));
  9474. // Set the target bed and nozzle temperatures and wait.
  9475. sprintf_P(cmd, PSTR("M104 S%d"), target_temperature[active_extruder]);
  9476. enquecommand(cmd);
  9477. sprintf_P(cmd, PSTR("M140 S%d"), target_temperature_bed);
  9478. enquecommand(cmd);
  9479. sprintf_P(cmd, PSTR("M109 S%d"), target_temperature[active_extruder]);
  9480. enquecommand(cmd);
  9481. enquecommand_P(PSTR("M83")); //E axis relative mode
  9482. // If not automatically recoreverd (long power loss)
  9483. if(automatic == 0){
  9484. //Extrude some filament to stabilize the pressure
  9485. enquecommand_P(PSTR("G1 E5 F120"));
  9486. // Retract to be consistent with a short pause
  9487. sprintf_P(cmd, PSTR("G1 E%-0.3f F2700"), default_retraction);
  9488. enquecommand(cmd);
  9489. }
  9490. 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]);
  9491. // Restart the print.
  9492. restore_print_from_eeprom(mbl_was_active);
  9493. printf_P(_N("Current pos Z_AXIS:%.3f\nCurrent pos E_AXIS:%.3f\n"), current_position[Z_AXIS], current_position[E_AXIS]);
  9494. }
  9495. bool recover_machine_state_after_power_panic()
  9496. {
  9497. // 1) Preset some dummy values for the XY axes
  9498. current_position[X_AXIS] = 0;
  9499. current_position[Y_AXIS] = 0;
  9500. // 2) Restore the mesh bed leveling offsets, but not the MBL status.
  9501. // This is 2*7*7=98 bytes, which takes 98*3.4us=333us in worst case.
  9502. bool mbl_was_active = false;
  9503. for (int8_t mesh_point = 0; mesh_point < MESH_NUM_X_POINTS * MESH_NUM_Y_POINTS; ++ mesh_point) {
  9504. uint8_t ix = mesh_point % MESH_NUM_X_POINTS; // from 0 to MESH_NUM_X_POINTS - 1
  9505. uint8_t iy = mesh_point / MESH_NUM_X_POINTS;
  9506. // Scale the z value to 10u resolution.
  9507. int16_t v;
  9508. eeprom_read_block(&v, (void*)(EEPROM_UVLO_MESH_BED_LEVELING_FULL+2*mesh_point), 2);
  9509. if (v != 0)
  9510. mbl_was_active = true;
  9511. mbl.z_values[iy][ix] = float(v) * 0.001f;
  9512. }
  9513. // Recover the physical coordinate of the Z axis at the time of the power panic.
  9514. // The current position after power panic is moved to the next closest 0th full step.
  9515. current_position[Z_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_TINY_CURRENT_POSITION_Z));
  9516. // Recover last E axis position
  9517. current_position[E_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_E));
  9518. // 3) Initialize the logical to physical coordinate system transformation.
  9519. world2machine_initialize();
  9520. // SERIAL_ECHOPGM("recover_machine_state_after_power_panic, initial ");
  9521. // print_mesh_bed_leveling_table();
  9522. // 4) Load the baby stepping value, which is expected to be active at the time of power panic.
  9523. // The baby stepping value is used to reset the physical Z axis when rehoming the Z axis.
  9524. babystep_load();
  9525. // 5) Set the physical positions from the logical positions using the world2machine transformation
  9526. // This is only done to inizialize Z/E axes with physical locations, since X/Y are unknown.
  9527. clamp_to_software_endstops(current_position);
  9528. set_destination_to_current();
  9529. plan_set_position_curposXYZE();
  9530. SERIAL_ECHOPGM("recover_machine_state_after_power_panic, initial ");
  9531. print_world_coordinates();
  9532. // 6) Power up the Z motors, mark their positions as known.
  9533. axis_known_position[Z_AXIS] = true;
  9534. enable_z();
  9535. // 7) Recover the target temperatures.
  9536. target_temperature[active_extruder] = eeprom_read_word((uint16_t*)EEPROM_UVLO_TARGET_HOTEND);
  9537. target_temperature_bed = eeprom_read_byte((uint8_t*)EEPROM_UVLO_TARGET_BED);
  9538. // 8) Recover extruder multipilers
  9539. extruder_multiplier[0] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_0));
  9540. #if EXTRUDERS > 1
  9541. extruder_multiplier[1] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_1));
  9542. #if EXTRUDERS > 2
  9543. extruder_multiplier[2] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_2));
  9544. #endif
  9545. #endif
  9546. extrudemultiply = (int)eeprom_read_word((uint16_t*)(EEPROM_EXTRUDEMULTIPLY));
  9547. // 9) Recover the saved target
  9548. saved_start_position[X_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+0*4));
  9549. saved_start_position[Y_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+1*4));
  9550. saved_start_position[Z_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+2*4));
  9551. saved_start_position[E_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+3*4));
  9552. saved_segment_idx = eeprom_read_word((uint16_t*)EEPROM_UVLO_SAVED_SEGMENT_IDX);
  9553. #ifdef LIN_ADVANCE
  9554. extruder_advance_K = eeprom_read_float((float*)EEPROM_UVLO_LA_K);
  9555. #endif
  9556. return mbl_was_active;
  9557. }
  9558. void restore_print_from_eeprom(bool mbl_was_active) {
  9559. int feedrate_rec;
  9560. int feedmultiply_rec;
  9561. uint8_t fan_speed_rec;
  9562. char cmd[48];
  9563. char filename[FILENAME_LENGTH];
  9564. uint8_t depth = 0;
  9565. char dir_name[9];
  9566. fan_speed_rec = eeprom_read_byte((uint8_t*)EEPROM_UVLO_FAN_SPEED);
  9567. feedrate_rec = eeprom_read_word((uint16_t*)EEPROM_UVLO_FEEDRATE);
  9568. feedmultiply_rec = eeprom_read_word((uint16_t*)EEPROM_UVLO_FEEDMULTIPLY);
  9569. SERIAL_ECHOPGM("Feedrate:");
  9570. MYSERIAL.print(feedrate_rec);
  9571. SERIAL_ECHOPGM(", feedmultiply:");
  9572. MYSERIAL.println(feedmultiply_rec);
  9573. depth = eeprom_read_byte((uint8_t*)EEPROM_DIR_DEPTH);
  9574. MYSERIAL.println(int(depth));
  9575. for (uint8_t i = 0; i < depth; i++) {
  9576. for (uint8_t j = 0; j < 8; j++) {
  9577. dir_name[j] = eeprom_read_byte((uint8_t*)EEPROM_DIRS + j + 8 * i);
  9578. }
  9579. dir_name[8] = '\0';
  9580. MYSERIAL.println(dir_name);
  9581. // strcpy(card.dir_names[i], dir_name);
  9582. card.chdir(dir_name, false);
  9583. }
  9584. for (uint8_t i = 0; i < 8; i++) {
  9585. filename[i] = eeprom_read_byte((uint8_t*)EEPROM_FILENAME + i);
  9586. }
  9587. filename[8] = '\0';
  9588. MYSERIAL.print(filename);
  9589. strcat_P(filename, PSTR(".gco"));
  9590. sprintf_P(cmd, PSTR("M23 %s"), filename);
  9591. enquecommand(cmd);
  9592. uint32_t position = eeprom_read_dword((uint32_t*)(EEPROM_FILE_POSITION));
  9593. SERIAL_ECHOPGM("Position read from eeprom:");
  9594. MYSERIAL.println(position);
  9595. // Move to the XY print position in logical coordinates, where the print has been killed, but
  9596. // without shifting Z along the way. This requires performing the move without mbl.
  9597. float pos_x = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0));
  9598. float pos_y = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 4));
  9599. if (pos_x != X_COORD_INVALID)
  9600. {
  9601. sprintf_P(cmd, PSTR("G1 X%f Y%f F3000"), pos_x, pos_y);
  9602. enquecommand(cmd);
  9603. }
  9604. // Enable MBL and switch to logical positioning
  9605. if (mbl_was_active)
  9606. enquecommand_P(PSTR("PRUSA MBL V1"));
  9607. // Move the Z axis down to the print, in logical coordinates.
  9608. sprintf_P(cmd, PSTR("G1 Z%f"), eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_Z)));
  9609. enquecommand(cmd);
  9610. // Restore acceleration settings
  9611. float acceleration = eeprom_read_float((float*)(EEPROM_UVLO_ACCELL));
  9612. float retract_acceleration = eeprom_read_float((float*)(EEPROM_UVLO_RETRACT_ACCELL));
  9613. float travel_acceleration = eeprom_read_float((float*)(EEPROM_UVLO_TRAVEL_ACCELL));
  9614. sprintf_P(cmd, PSTR("M204 P%f R%f T%f"), acceleration, retract_acceleration, travel_acceleration);
  9615. enquecommand(cmd);
  9616. // Unretract.
  9617. sprintf_P(cmd, PSTR("G1 E%0.3f F2700"), default_retraction);
  9618. enquecommand(cmd);
  9619. // Recover final E axis position and mode
  9620. float pos_e = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_E));
  9621. sprintf_P(cmd, PSTR("G92 E%6.3f"), pos_e);
  9622. enquecommand(cmd);
  9623. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO_E_ABS))
  9624. enquecommand_P(PSTR("M82")); //E axis abslute mode
  9625. // Set the feedrates saved at the power panic.
  9626. sprintf_P(cmd, PSTR("G1 F%d"), feedrate_rec);
  9627. enquecommand(cmd);
  9628. sprintf_P(cmd, PSTR("M220 S%d"), feedmultiply_rec);
  9629. enquecommand(cmd);
  9630. // Set the fan speed saved at the power panic.
  9631. strcpy_P(cmd, PSTR("M106 S"));
  9632. strcat(cmd, itostr3(int(fan_speed_rec)));
  9633. enquecommand(cmd);
  9634. // Set a position in the file.
  9635. sprintf_P(cmd, PSTR("M26 S%lu"), position);
  9636. enquecommand(cmd);
  9637. enquecommand_P(PSTR("G4 S0"));
  9638. enquecommand_P(PSTR("PRUSA uvlo"));
  9639. }
  9640. #endif //UVLO_SUPPORT
  9641. //! @brief Immediately stop print moves
  9642. //!
  9643. //! Immediately stop print moves, save current extruder temperature and position to RAM.
  9644. //! If printing from sd card, position in file is saved.
  9645. //! If printing from USB, line number is saved.
  9646. //!
  9647. //! @param z_move
  9648. //! @param e_move
  9649. void stop_and_save_print_to_ram(float z_move, float e_move)
  9650. {
  9651. if (saved_printing) return;
  9652. #if 0
  9653. unsigned char nplanner_blocks;
  9654. #endif
  9655. unsigned char nlines;
  9656. uint16_t sdlen_planner;
  9657. uint16_t sdlen_cmdqueue;
  9658. cli();
  9659. if (card.sdprinting) {
  9660. #if 0
  9661. nplanner_blocks = number_of_blocks();
  9662. #endif
  9663. saved_sdpos = sdpos_atomic; //atomic sd position of last command added in queue
  9664. sdlen_planner = planner_calc_sd_length(); //length of sd commands in planner
  9665. saved_sdpos -= sdlen_planner;
  9666. sdlen_cmdqueue = cmdqueue_calc_sd_length(); //length of sd commands in cmdqueue
  9667. saved_sdpos -= sdlen_cmdqueue;
  9668. saved_printing_type = PRINTING_TYPE_SD;
  9669. }
  9670. else if (usb_timer.running()) { //reuse saved_sdpos for storing line number
  9671. saved_sdpos = gcode_LastN; //start with line number of command added recently to cmd queue
  9672. //reuse planner_calc_sd_length function for getting number of lines of commands in planner:
  9673. nlines = planner_calc_sd_length(); //number of lines of commands in planner
  9674. saved_sdpos -= nlines;
  9675. saved_sdpos -= buflen; //number of blocks in cmd buffer
  9676. saved_printing_type = PRINTING_TYPE_USB;
  9677. }
  9678. else {
  9679. saved_printing_type = PRINTING_TYPE_NONE;
  9680. //not sd printing nor usb printing
  9681. }
  9682. #if 0
  9683. SERIAL_ECHOPGM("SDPOS_ATOMIC="); MYSERIAL.println(sdpos_atomic, DEC);
  9684. SERIAL_ECHOPGM("SDPOS="); MYSERIAL.println(card.get_sdpos(), DEC);
  9685. SERIAL_ECHOPGM("SDLEN_PLAN="); MYSERIAL.println(sdlen_planner, DEC);
  9686. SERIAL_ECHOPGM("SDLEN_CMDQ="); MYSERIAL.println(sdlen_cmdqueue, DEC);
  9687. SERIAL_ECHOPGM("PLANNERBLOCKS="); MYSERIAL.println(int(nplanner_blocks), DEC);
  9688. SERIAL_ECHOPGM("SDSAVED="); MYSERIAL.println(saved_sdpos, DEC);
  9689. //SERIAL_ECHOPGM("SDFILELEN="); MYSERIAL.println(card.fileSize(), DEC);
  9690. {
  9691. card.setIndex(saved_sdpos);
  9692. SERIAL_ECHOLNPGM("Content of planner buffer: ");
  9693. for (unsigned int idx = 0; idx < sdlen_planner; ++ idx)
  9694. MYSERIAL.print(char(card.get()));
  9695. SERIAL_ECHOLNPGM("Content of command buffer: ");
  9696. for (unsigned int idx = 0; idx < sdlen_cmdqueue; ++ idx)
  9697. MYSERIAL.print(char(card.get()));
  9698. SERIAL_ECHOLNPGM("End of command buffer");
  9699. }
  9700. {
  9701. // Print the content of the planner buffer, line by line:
  9702. card.setIndex(saved_sdpos);
  9703. int8_t iline = 0;
  9704. for (unsigned char idx = block_buffer_tail; idx != block_buffer_head; idx = (idx + 1) & (BLOCK_BUFFER_SIZE - 1), ++ iline) {
  9705. SERIAL_ECHOPGM("Planner line (from file): ");
  9706. MYSERIAL.print(int(iline), DEC);
  9707. SERIAL_ECHOPGM(", length: ");
  9708. MYSERIAL.print(block_buffer[idx].sdlen, DEC);
  9709. SERIAL_ECHOPGM(", steps: (");
  9710. MYSERIAL.print(block_buffer[idx].steps_x, DEC);
  9711. SERIAL_ECHOPGM(",");
  9712. MYSERIAL.print(block_buffer[idx].steps_y, DEC);
  9713. SERIAL_ECHOPGM(",");
  9714. MYSERIAL.print(block_buffer[idx].steps_z, DEC);
  9715. SERIAL_ECHOPGM(",");
  9716. MYSERIAL.print(block_buffer[idx].steps_e, DEC);
  9717. SERIAL_ECHOPGM("), events: ");
  9718. MYSERIAL.println(block_buffer[idx].step_event_count, DEC);
  9719. for (int len = block_buffer[idx].sdlen; len > 0; -- len)
  9720. MYSERIAL.print(char(card.get()));
  9721. }
  9722. }
  9723. {
  9724. // Print the content of the command buffer, line by line:
  9725. int8_t iline = 0;
  9726. union {
  9727. struct {
  9728. char lo;
  9729. char hi;
  9730. } lohi;
  9731. uint16_t value;
  9732. } sdlen_single;
  9733. int _bufindr = bufindr;
  9734. for (int _buflen = buflen; _buflen > 0; ++ iline) {
  9735. if (cmdbuffer[_bufindr] == CMDBUFFER_CURRENT_TYPE_SDCARD) {
  9736. sdlen_single.lohi.lo = cmdbuffer[_bufindr + 1];
  9737. sdlen_single.lohi.hi = cmdbuffer[_bufindr + 2];
  9738. }
  9739. SERIAL_ECHOPGM("Buffer line (from buffer): ");
  9740. MYSERIAL.print(int(iline), DEC);
  9741. SERIAL_ECHOPGM(", type: ");
  9742. MYSERIAL.print(int(cmdbuffer[_bufindr]), DEC);
  9743. SERIAL_ECHOPGM(", len: ");
  9744. MYSERIAL.println(sdlen_single.value, DEC);
  9745. // Print the content of the buffer line.
  9746. MYSERIAL.println(cmdbuffer + _bufindr + CMDHDRSIZE);
  9747. SERIAL_ECHOPGM("Buffer line (from file): ");
  9748. MYSERIAL.println(int(iline), DEC);
  9749. for (; sdlen_single.value > 0; -- sdlen_single.value)
  9750. MYSERIAL.print(char(card.get()));
  9751. if (-- _buflen == 0)
  9752. break;
  9753. // First skip the current command ID and iterate up to the end of the string.
  9754. for (_bufindr += CMDHDRSIZE; cmdbuffer[_bufindr] != 0; ++ _bufindr) ;
  9755. // Second, skip the end of string null character and iterate until a nonzero command ID is found.
  9756. for (++ _bufindr; _bufindr < sizeof(cmdbuffer) && cmdbuffer[_bufindr] == 0; ++ _bufindr) ;
  9757. // If the end of the buffer was empty,
  9758. if (_bufindr == sizeof(cmdbuffer)) {
  9759. // skip to the start and find the nonzero command.
  9760. for (_bufindr = 0; cmdbuffer[_bufindr] == 0; ++ _bufindr) ;
  9761. }
  9762. }
  9763. }
  9764. #endif
  9765. // save the global state at planning time
  9766. bool pos_invalid = XY_NO_RESTORE_FLAG;
  9767. if (current_block && !pos_invalid)
  9768. {
  9769. memcpy(saved_start_position, current_block->gcode_start_position, sizeof(saved_start_position));
  9770. saved_feedrate2 = current_block->gcode_feedrate;
  9771. saved_segment_idx = current_block->segment_idx;
  9772. // 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);
  9773. }
  9774. else
  9775. {
  9776. saved_start_position[0] = SAVED_START_POSITION_UNSET;
  9777. saved_feedrate2 = feedrate;
  9778. saved_segment_idx = 0;
  9779. }
  9780. planner_abort_hard(); //abort printing
  9781. memcpy(saved_pos, current_position, sizeof(saved_pos));
  9782. if (pos_invalid) saved_pos[X_AXIS] = X_COORD_INVALID;
  9783. saved_feedmultiply2 = feedmultiply; //save feedmultiply
  9784. saved_extruder_temperature = degTargetHotend(active_extruder);
  9785. saved_bed_temperature = degTargetBed();
  9786. saved_extruder_relative_mode = axis_relative_modes & E_AXIS_MASK;
  9787. saved_fan_speed = fanSpeed;
  9788. cmdqueue_reset(); //empty cmdqueue
  9789. card.sdprinting = false;
  9790. // card.closefile();
  9791. saved_printing = true;
  9792. // We may have missed a stepper timer interrupt. Be safe than sorry, reset the stepper timer before re-enabling interrupts.
  9793. st_reset_timer();
  9794. sei();
  9795. if ((z_move != 0) || (e_move != 0)) { // extruder or z move
  9796. // Rather than calling plan_buffer_line directly, push the move into the command queue so that
  9797. // the caller can continue processing. This is used during powerpanic to save the state as we
  9798. // move away from the print.
  9799. char buf[48];
  9800. if(e_move)
  9801. {
  9802. // First unretract (relative extrusion)
  9803. if(!saved_extruder_relative_mode){
  9804. enquecommand(PSTR("M83"), true);
  9805. }
  9806. //retract 45mm/s
  9807. // A single sprintf may not be faster, but is definitely 20B shorter
  9808. // than a sequence of commands building the string piece by piece
  9809. // A snprintf would have been a safer call, but since it is not used
  9810. // in the whole program, its implementation would bring more bytes to the total size
  9811. // The behavior of dtostrf 8,3 should be roughly the same as %-0.3
  9812. sprintf_P(buf, PSTR("G1 E%-0.3f F2700"), e_move);
  9813. enquecommand(buf, false);
  9814. }
  9815. if(z_move)
  9816. {
  9817. // Then lift Z axis
  9818. sprintf_P(buf, PSTR("G1 Z%-0.3f F%-0.3f"), saved_pos[Z_AXIS] + z_move, homing_feedrate[Z_AXIS]);
  9819. enquecommand(buf, false);
  9820. }
  9821. // If this call is invoked from the main Arduino loop() function, let the caller know that the command
  9822. // in the command queue is not the original command, but a new one, so it should not be removed from the queue.
  9823. repeatcommand_front();
  9824. }
  9825. }
  9826. void restore_extruder_temperature_from_ram() {
  9827. if (degTargetHotend(active_extruder) != saved_extruder_temperature)
  9828. {
  9829. setTargetHotendSafe(saved_extruder_temperature, active_extruder);
  9830. heating_status = HeatingStatus::EXTRUDER_HEATING;
  9831. wait_for_heater(_millis(), active_extruder);
  9832. heating_status = HeatingStatus::EXTRUDER_HEATING_COMPLETE;
  9833. }
  9834. }
  9835. //! @brief Restore print from ram
  9836. //!
  9837. //! Restore print saved by stop_and_save_print_to_ram(). Is blocking, restores
  9838. //! print fan speed, waits for extruder temperature restore, then restores
  9839. //! position and continues print moves.
  9840. //!
  9841. //! Internally lcd_update() is called by wait_for_heater().
  9842. //!
  9843. //! @param e_move
  9844. void restore_print_from_ram_and_continue(float e_move)
  9845. {
  9846. if (!saved_printing) return;
  9847. #ifdef FANCHECK
  9848. // Do not allow resume printing if fans are still not ok
  9849. if ((fan_check_error != EFCE_OK) && (fan_check_error != EFCE_FIXED)) return;
  9850. if (fan_check_error == EFCE_FIXED) fan_check_error = EFCE_OK; //reenable serial stream processing if printing from usb
  9851. #endif
  9852. // restore bed temperature (bed can be disabled during a thermal warning)
  9853. if (degBed() != saved_bed_temperature)
  9854. setTargetBed(saved_bed_temperature);
  9855. fanSpeed = saved_fan_speed;
  9856. restore_extruder_temperature_from_ram();
  9857. axis_relative_modes ^= (-saved_extruder_relative_mode ^ axis_relative_modes) & E_AXIS_MASK;
  9858. float e = saved_pos[E_AXIS] - e_move;
  9859. plan_set_e_position(e);
  9860. #ifdef FANCHECK
  9861. fans_check_enabled = false;
  9862. #endif
  9863. // do not restore XY for commands that do not require that
  9864. if (saved_pos[X_AXIS] == X_COORD_INVALID)
  9865. {
  9866. saved_pos[X_AXIS] = current_position[X_AXIS];
  9867. saved_pos[Y_AXIS] = current_position[Y_AXIS];
  9868. }
  9869. //first move print head in XY to the saved position:
  9870. 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);
  9871. //then move Z
  9872. 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);
  9873. //and finaly unretract (35mm/s)
  9874. plan_buffer_line(saved_pos[X_AXIS], saved_pos[Y_AXIS], saved_pos[Z_AXIS], saved_pos[E_AXIS], FILAMENTCHANGE_RFEED, active_extruder);
  9875. st_synchronize();
  9876. #ifdef FANCHECK
  9877. fans_check_enabled = true;
  9878. #endif
  9879. // restore original feedrate/feedmultiply _after_ restoring the extruder position
  9880. feedrate = saved_feedrate2;
  9881. feedmultiply = saved_feedmultiply2;
  9882. memcpy(current_position, saved_pos, sizeof(saved_pos));
  9883. set_destination_to_current();
  9884. if (saved_printing_type == PRINTING_TYPE_SD) { //was sd printing
  9885. card.setIndex(saved_sdpos);
  9886. sdpos_atomic = saved_sdpos;
  9887. card.sdprinting = true;
  9888. }
  9889. else if (saved_printing_type == PRINTING_TYPE_USB) { //was usb printing
  9890. gcode_LastN = saved_sdpos; //saved_sdpos was reused for storing line number when usb printing
  9891. serial_count = 0;
  9892. FlushSerialRequestResend();
  9893. }
  9894. else {
  9895. //not sd printing nor usb printing
  9896. }
  9897. lcd_setstatuspgm(MSG_WELCOME);
  9898. saved_printing_type = PRINTING_TYPE_NONE;
  9899. saved_printing = false;
  9900. planner_aborted = true; // unroll the stack
  9901. }
  9902. // Cancel the state related to a currently saved print
  9903. void cancel_saved_printing()
  9904. {
  9905. eeprom_update_byte((uint8_t*)EEPROM_UVLO, 0);
  9906. saved_start_position[0] = SAVED_START_POSITION_UNSET;
  9907. saved_printing_type = PRINTING_TYPE_NONE;
  9908. saved_printing = false;
  9909. }
  9910. void print_world_coordinates()
  9911. {
  9912. printf_P(_N("world coordinates: (%.3f, %.3f, %.3f)\n"), current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS]);
  9913. }
  9914. void print_physical_coordinates()
  9915. {
  9916. 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));
  9917. }
  9918. void print_mesh_bed_leveling_table()
  9919. {
  9920. SERIAL_ECHOPGM("mesh bed leveling: ");
  9921. for (int8_t y = 0; y < MESH_NUM_Y_POINTS; ++ y)
  9922. for (int8_t x = 0; x < MESH_NUM_Y_POINTS; ++ x) {
  9923. MYSERIAL.print(mbl.z_values[y][x], 3);
  9924. SERIAL_ECHO(' ');
  9925. }
  9926. SERIAL_ECHOLN();
  9927. }
  9928. uint8_t calc_percent_done()
  9929. {
  9930. //in case that we have information from M73 gcode return percentage counted by slicer, else return percentage counted as byte_printed/filesize
  9931. uint8_t percent_done = 0;
  9932. #ifdef TMC2130
  9933. if (SilentModeMenu == SILENT_MODE_OFF && print_percent_done_normal <= 100)
  9934. {
  9935. percent_done = print_percent_done_normal;
  9936. }
  9937. else if (print_percent_done_silent <= 100)
  9938. {
  9939. percent_done = print_percent_done_silent;
  9940. }
  9941. #else
  9942. if (print_percent_done_normal <= 100)
  9943. {
  9944. percent_done = print_percent_done_normal;
  9945. }
  9946. #endif //TMC2130
  9947. else
  9948. {
  9949. percent_done = card.percentDone();
  9950. }
  9951. return percent_done;
  9952. }
  9953. static void print_time_remaining_init()
  9954. {
  9955. print_time_remaining_normal = PRINT_TIME_REMAINING_INIT;
  9956. print_percent_done_normal = PRINT_PERCENT_DONE_INIT;
  9957. print_time_remaining_silent = PRINT_TIME_REMAINING_INIT;
  9958. print_percent_done_silent = PRINT_PERCENT_DONE_INIT;
  9959. print_time_to_change_normal = PRINT_TIME_REMAINING_INIT;
  9960. print_time_to_change_silent = PRINT_TIME_REMAINING_INIT;
  9961. }
  9962. void load_filament_final_feed()
  9963. {
  9964. current_position[E_AXIS]+= FILAMENTCHANGE_FINALFEED;
  9965. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EFEED_FINAL);
  9966. }
  9967. //! @brief Wait for user to check the state
  9968. //! @par nozzle_temp nozzle temperature to load filament
  9969. void M600_check_state(float nozzle_temp)
  9970. {
  9971. lcd_change_fil_state = 0;
  9972. while (lcd_change_fil_state != 1)
  9973. {
  9974. lcd_change_fil_state = 0;
  9975. KEEPALIVE_STATE(PAUSED_FOR_USER);
  9976. lcd_alright();
  9977. KEEPALIVE_STATE(IN_HANDLER);
  9978. switch(lcd_change_fil_state)
  9979. {
  9980. // Filament failed to load so load it again
  9981. case 2:
  9982. if (MMU2::mmu2.Enabled()){
  9983. // Unload filament
  9984. mmu_M600_unload_filament();
  9985. // Ask to remove any old filament and load new
  9986. mmu_M600_wait_and_beep();
  9987. // After user clicks knob, MMU will load the filament
  9988. mmu_M600_load_filament(false, nozzle_temp);
  9989. } else {
  9990. M600_load_filament_movements();
  9991. }
  9992. break;
  9993. // Filament loaded properly but color is not clear
  9994. case 3:
  9995. st_synchronize();
  9996. load_filament_final_feed();
  9997. lcd_loading_color();
  9998. st_synchronize();
  9999. break;
  10000. // Everything good
  10001. default:
  10002. lcd_change_success();
  10003. break;
  10004. }
  10005. }
  10006. }
  10007. //! @brief Wait for user action
  10008. //!
  10009. //! Beep, manage nozzle heater and wait for user to start unload filament
  10010. //! If times out, active extruder temperature is set to 0.
  10011. //!
  10012. //! @param HotendTempBckp Temperature to be restored for active extruder, after user resolves MMU problem.
  10013. void M600_wait_for_user(float HotendTempBckp) {
  10014. KEEPALIVE_STATE(PAUSED_FOR_USER);
  10015. int counterBeep = 0;
  10016. unsigned long waiting_start_time = _millis();
  10017. uint8_t wait_for_user_state = 0;
  10018. lcd_display_message_fullscreen_P(_T(MSG_PRESS_TO_UNLOAD));
  10019. bool bFirst=true;
  10020. while (!(wait_for_user_state == 0 && lcd_clicked())){
  10021. manage_heater();
  10022. manage_inactivity(true);
  10023. #if BEEPER > 0
  10024. if (counterBeep == 500) {
  10025. counterBeep = 0;
  10026. }
  10027. SET_OUTPUT(BEEPER);
  10028. if (counterBeep == 0) {
  10029. if((eSoundMode==e_SOUND_MODE_BLIND)|| (eSoundMode==e_SOUND_MODE_LOUD)||((eSoundMode==e_SOUND_MODE_ONCE)&&bFirst))
  10030. {
  10031. bFirst=false;
  10032. WRITE(BEEPER, HIGH);
  10033. }
  10034. }
  10035. if (counterBeep == 20) {
  10036. WRITE(BEEPER, LOW);
  10037. }
  10038. counterBeep++;
  10039. #endif //BEEPER > 0
  10040. switch (wait_for_user_state) {
  10041. case 0: //nozzle is hot, waiting for user to press the knob to unload filament
  10042. delay_keep_alive(4);
  10043. if (_millis() > waiting_start_time + (unsigned long)M600_TIMEOUT * 1000) {
  10044. lcd_display_message_fullscreen_P(_i("Press the knob to preheat nozzle and continue."));////MSG_PRESS_TO_PREHEAT c=20 r=4
  10045. wait_for_user_state = 1;
  10046. setAllTargetHotends(0);
  10047. st_synchronize();
  10048. disable_e0();
  10049. disable_e1();
  10050. disable_e2();
  10051. }
  10052. break;
  10053. case 1: //nozzle target temperature is set to zero, waiting for user to start nozzle preheat
  10054. delay_keep_alive(4);
  10055. if (lcd_clicked()) {
  10056. setTargetHotend(HotendTempBckp, active_extruder);
  10057. lcd_wait_for_heater();
  10058. wait_for_user_state = 2;
  10059. }
  10060. break;
  10061. case 2: //waiting for nozzle to reach target temperature
  10062. if (fabs(degTargetHotend(active_extruder) - degHotend(active_extruder)) < 1) {
  10063. lcd_display_message_fullscreen_P(_T(MSG_PRESS_TO_UNLOAD));
  10064. waiting_start_time = _millis();
  10065. wait_for_user_state = 0;
  10066. }
  10067. else {
  10068. counterBeep = 20; //beeper will be inactive during waiting for nozzle preheat
  10069. lcd_set_cursor(1, 4);
  10070. lcd_printf_P(PSTR("%3d"), (int16_t)degHotend(active_extruder));
  10071. }
  10072. break;
  10073. }
  10074. }
  10075. WRITE(BEEPER, LOW);
  10076. }
  10077. void M600_load_filament_movements()
  10078. {
  10079. current_position[E_AXIS]+= FILAMENTCHANGE_FIRSTFEED;
  10080. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EFEED_FIRST);
  10081. load_filament_final_feed();
  10082. lcd_loading_filament();
  10083. st_synchronize();
  10084. }
  10085. void M600_load_filament() {
  10086. //load filament for single material and MMU
  10087. lcd_wait_interact();
  10088. //load_filament_time = _millis();
  10089. KEEPALIVE_STATE(PAUSED_FOR_USER);
  10090. while(!lcd_clicked())
  10091. {
  10092. manage_heater();
  10093. manage_inactivity(true);
  10094. #ifdef FILAMENT_SENSOR
  10095. if (fsensor.getFilamentLoadEvent()) {
  10096. Sound_MakeCustom(50,1000,false);
  10097. break;
  10098. }
  10099. #endif //FILAMENT_SENSOR
  10100. }
  10101. KEEPALIVE_STATE(IN_HANDLER);
  10102. M600_load_filament_movements();
  10103. Sound_MakeCustom(50,1000,false);
  10104. lcd_update_enable(false);
  10105. }
  10106. //! @brief Wait for click
  10107. //!
  10108. //! Set
  10109. void marlin_wait_for_click()
  10110. {
  10111. int8_t busy_state_backup = busy_state;
  10112. KEEPALIVE_STATE(PAUSED_FOR_USER);
  10113. lcd_consume_click();
  10114. while(!lcd_clicked())
  10115. {
  10116. manage_heater();
  10117. manage_inactivity(true);
  10118. lcd_update(0);
  10119. }
  10120. KEEPALIVE_STATE(busy_state_backup);
  10121. }
  10122. #define FIL_LOAD_LENGTH 60
  10123. #ifdef PSU_Delta
  10124. bool bEnableForce_z;
  10125. void init_force_z()
  10126. {
  10127. WRITE(Z_ENABLE_PIN,Z_ENABLE_ON);
  10128. bEnableForce_z=true; // "true"-value enforce "disable_force_z()" executing
  10129. disable_force_z();
  10130. }
  10131. void check_force_z()
  10132. {
  10133. if(!(bEnableForce_z||eeprom_read_byte((uint8_t*)EEPROM_SILENT)))
  10134. init_force_z(); // causes enforced switching into disable-state
  10135. }
  10136. void disable_force_z()
  10137. {
  10138. if(!bEnableForce_z) return; // motor already disabled (may be ;-p )
  10139. bEnableForce_z=false;
  10140. // switching to silent mode
  10141. #ifdef TMC2130
  10142. tmc2130_mode=TMC2130_MODE_SILENT;
  10143. update_mode_profile();
  10144. tmc2130_init(TMCInitParams(true, FarmOrUserECool()));
  10145. #endif // TMC2130
  10146. }
  10147. void enable_force_z()
  10148. {
  10149. if(bEnableForce_z)
  10150. return; // motor already enabled (may be ;-p )
  10151. bEnableForce_z=true;
  10152. // mode recovering
  10153. #ifdef TMC2130
  10154. tmc2130_mode=eeprom_read_byte((uint8_t*)EEPROM_SILENT)?TMC2130_MODE_SILENT:TMC2130_MODE_NORMAL;
  10155. update_mode_profile();
  10156. tmc2130_init(TMCInitParams(true, FarmOrUserECool()));
  10157. #endif // TMC2130
  10158. WRITE(Z_ENABLE_PIN,Z_ENABLE_ON); // slightly redundant ;-p
  10159. }
  10160. #endif // PSU_Delta