Marlin_main.cpp 389 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634
  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 "Dcodes.h"
  80. #include "AutoDeplete.h"
  81. #ifndef LA_NOCOMPAT
  82. #include "la10compat.h"
  83. #endif
  84. #include "spi.h"
  85. #ifdef FILAMENT_SENSOR
  86. #include "Filament_sensor.h"
  87. #include "fsensor.h"
  88. #ifdef IR_SENSOR
  89. #include "pat9125.h" // for pat9125_probe
  90. #endif
  91. #endif //FILAMENT_SENSOR
  92. #ifdef TMC2130
  93. #include "tmc2130.h"
  94. #endif //TMC2130
  95. #ifdef XFLASH
  96. #include "xflash.h"
  97. #include "optiboot_xflash.h"
  98. #endif //XFLASH
  99. #include "xflash_dump.h"
  100. #ifdef BLINKM
  101. #include "BlinkM.h"
  102. #include "Wire.h"
  103. #endif
  104. #ifdef ULTRALCD
  105. #include "ultralcd.h"
  106. #endif
  107. #if NUM_SERVOS > 0
  108. #include "Servo.h"
  109. #endif
  110. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  111. #include <SPI.h>
  112. #endif
  113. #include "mmu.h"
  114. #define VERSION_STRING "1.0.2"
  115. #include "ultralcd.h"
  116. #include "sound.h"
  117. #include "cmdqueue.h"
  118. //Macro for print fan speed
  119. #define FAN_PULSE_WIDTH_LIMIT ((fanSpeed > 100) ? 3 : 4) //time in ms
  120. //filament types
  121. #define FILAMENT_DEFAULT 0
  122. #define FILAMENT_FLEX 1
  123. #define FILAMENT_PVA 2
  124. #define FILAMENT_UNDEFINED 255
  125. //Stepper Movement Variables
  126. //===========================================================================
  127. //=============================imported variables============================
  128. //===========================================================================
  129. //===========================================================================
  130. //=============================public variables=============================
  131. //===========================================================================
  132. #ifdef SDSUPPORT
  133. CardReader card;
  134. #endif
  135. uint8_t mbl_z_probe_nr = 3; //numer of Z measurements for each point in mesh bed leveling calibration
  136. //used for PINDA temp calibration and pause print
  137. #define DEFAULT_RETRACTION 1
  138. #define DEFAULT_RETRACTION_MM 4 //MM
  139. float default_retraction = DEFAULT_RETRACTION;
  140. float homing_feedrate[] = HOMING_FEEDRATE;
  141. //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
  142. //would not be standard across all platforms. That being said, the code will continue to use bitmasks for independent axis.
  143. //Moreover, according to C/C++ standard, the ordering of bits is platform/compiler dependent and the compiler is allowed to align the bits arbitrarily,
  144. //thus bit operations like shifting and masking may stop working and will be very hard to fix.
  145. uint8_t axis_relative_modes = 0;
  146. int feedmultiply=100; //100->1 200->2
  147. int extrudemultiply=100; //100->1 200->2
  148. int extruder_multiply[EXTRUDERS] = {100
  149. #if EXTRUDERS > 1
  150. , 100
  151. #if EXTRUDERS > 2
  152. , 100
  153. #endif
  154. #endif
  155. };
  156. bool homing_flag = false;
  157. int8_t lcd_change_fil_state = 0;
  158. unsigned long pause_time = 0;
  159. unsigned long start_pause_print = _millis();
  160. unsigned long t_fan_rising_edge = _millis();
  161. LongTimer safetyTimer;
  162. static LongTimer crashDetTimer;
  163. //unsigned long load_filament_time;
  164. bool mesh_bed_leveling_flag = false;
  165. unsigned long total_filament_used;
  166. HeatingStatus heating_status;
  167. uint8_t heating_status_counter;
  168. bool loading_flag = false;
  169. #define XY_NO_RESTORE_FLAG (mesh_bed_leveling_flag || homing_flag)
  170. bool fan_state[2];
  171. int fan_edge_counter[2];
  172. int fan_speed[2];
  173. float extruder_multiplier[EXTRUDERS] = {1.0
  174. #if EXTRUDERS > 1
  175. , 1.0
  176. #if EXTRUDERS > 2
  177. , 1.0
  178. #endif
  179. #endif
  180. };
  181. float current_position[NUM_AXIS] = { 0.0, 0.0, 0.0, 0.0 };
  182. //shortcuts for more readable code
  183. #define _x current_position[X_AXIS]
  184. #define _y current_position[Y_AXIS]
  185. #define _z current_position[Z_AXIS]
  186. #define _e current_position[E_AXIS]
  187. float min_pos[3] = { X_MIN_POS, Y_MIN_POS, Z_MIN_POS };
  188. float max_pos[3] = { X_MAX_POS, Y_MAX_POS, Z_MAX_POS };
  189. bool axis_known_position[3] = {false, false, false};
  190. // Extruder offset
  191. #if EXTRUDERS > 1
  192. #define NUM_EXTRUDER_OFFSETS 2 // only in XY plane
  193. float extruder_offset[NUM_EXTRUDER_OFFSETS][EXTRUDERS] = {
  194. #if defined(EXTRUDER_OFFSET_X) && defined(EXTRUDER_OFFSET_Y)
  195. EXTRUDER_OFFSET_X, EXTRUDER_OFFSET_Y
  196. #endif
  197. };
  198. #endif
  199. uint8_t active_extruder = 0;
  200. int fanSpeed=0;
  201. uint8_t newFanSpeed = 0;
  202. #ifdef FWRETRACT
  203. bool retracted[EXTRUDERS]={false
  204. #if EXTRUDERS > 1
  205. , false
  206. #if EXTRUDERS > 2
  207. , false
  208. #endif
  209. #endif
  210. };
  211. bool retracted_swap[EXTRUDERS]={false
  212. #if EXTRUDERS > 1
  213. , false
  214. #if EXTRUDERS > 2
  215. , false
  216. #endif
  217. #endif
  218. };
  219. float retract_length_swap = RETRACT_LENGTH_SWAP;
  220. float retract_recover_length_swap = RETRACT_RECOVER_LENGTH_SWAP;
  221. #endif
  222. #ifdef PS_DEFAULT_OFF
  223. bool powersupply = false;
  224. #else
  225. bool powersupply = true;
  226. #endif
  227. bool cancel_heatup = false;
  228. int8_t busy_state = NOT_BUSY;
  229. static long prev_busy_signal_ms = -1;
  230. uint8_t host_keepalive_interval = HOST_KEEPALIVE_INTERVAL;
  231. const char errormagic[] PROGMEM = "Error:";
  232. const char echomagic[] PROGMEM = "echo:";
  233. const char G28W0[] PROGMEM = "G28 W0";
  234. // Define some coordinates outside the clamp limits (making them invalid past the parsing stage) so
  235. // that they can be used later for various logical checks
  236. #define X_COORD_INVALID (X_MIN_POS-1)
  237. #define SAVED_START_POSITION_UNSET X_COORD_INVALID
  238. float saved_start_position[NUM_AXIS] = {SAVED_START_POSITION_UNSET, 0, 0, 0};
  239. uint16_t saved_segment_idx = 0;
  240. // save/restore printing in case that mmu was not responding
  241. bool mmu_print_saved = false;
  242. // storing estimated time to end of print counted by slicer
  243. uint8_t print_percent_done_normal = PRINT_PERCENT_DONE_INIT;
  244. uint8_t print_percent_done_silent = PRINT_PERCENT_DONE_INIT;
  245. uint16_t print_time_remaining_normal = PRINT_TIME_REMAINING_INIT; //estimated remaining print time in minutes
  246. uint16_t print_time_remaining_silent = PRINT_TIME_REMAINING_INIT; //estimated remaining print time in minutes
  247. uint16_t print_time_to_change_normal = PRINT_TIME_REMAINING_INIT; //estimated remaining time to next change in minutes
  248. uint16_t print_time_to_change_silent = PRINT_TIME_REMAINING_INIT; //estimated remaining time to next change in minutes
  249. uint32_t IP_address = 0;
  250. //===========================================================================
  251. //=============================Private Variables=============================
  252. //===========================================================================
  253. #define MSG_BED_LEVELING_FAILED_TIMEOUT 30
  254. const char axis_codes[NUM_AXIS] = {'X', 'Y', 'Z', 'E'};
  255. float destination[NUM_AXIS] = { 0.0, 0.0, 0.0, 0.0};
  256. // For tracing an arc
  257. static float offset[3] = {0.0, 0.0, 0.0};
  258. // Current feedrate
  259. float feedrate = 1500.0;
  260. // Feedrate for the next move
  261. static float next_feedrate;
  262. // Original feedrate saved during homing moves
  263. static float saved_feedrate;
  264. const int8_t sensitive_pins[] PROGMEM = SENSITIVE_PINS; // Sensitive pin list for M42
  265. //static float tt = 0;
  266. //static float bt = 0;
  267. //Inactivity shutdown variables
  268. static LongTimer previous_millis_cmd;
  269. unsigned long max_inactive_time = 0;
  270. static unsigned long stepper_inactive_time = DEFAULT_STEPPER_DEACTIVE_TIME*1000l;
  271. static unsigned long safetytimer_inactive_time = DEFAULT_SAFETYTIMER_TIME_MINS*60*1000ul;
  272. unsigned long starttime=0;
  273. unsigned long stoptime=0;
  274. ShortTimer usb_timer;
  275. bool Stopped=false;
  276. #if NUM_SERVOS > 0
  277. Servo servos[NUM_SERVOS];
  278. #endif
  279. bool target_direction;
  280. //Insert variables if CHDK is defined
  281. #ifdef CHDK
  282. unsigned long chdkHigh = 0;
  283. bool chdkActive = false;
  284. #endif
  285. //! @name RAM save/restore printing
  286. //! @{
  287. bool saved_printing = false; //!< Print is paused and saved in RAM
  288. static uint32_t saved_sdpos = 0; //!< SD card position, or line number in case of USB printing
  289. uint8_t saved_printing_type = PRINTING_TYPE_SD;
  290. static float saved_pos[4] = { X_COORD_INVALID, 0, 0, 0 };
  291. static uint16_t saved_feedrate2 = 0; //!< Default feedrate (truncated from float)
  292. static int saved_feedmultiply2 = 0;
  293. static uint8_t saved_active_extruder = 0;
  294. float saved_extruder_temperature = 0.0; //!< Active extruder temperature
  295. float saved_bed_temperature = 0.0; //!< Bed temperature
  296. static bool saved_extruder_relative_mode = false;
  297. int saved_fan_speed = 0; //!< Print fan speed
  298. //! @}
  299. static int saved_feedmultiply_mm = 100;
  300. class AutoReportFeatures {
  301. union {
  302. struct {
  303. uint8_t temp : 1; //Temperature flag
  304. uint8_t fans : 1; //Fans flag
  305. uint8_t pos: 1; //Position flag
  306. uint8_t ar4 : 1; //Unused
  307. uint8_t ar5 : 1; //Unused
  308. uint8_t ar6 : 1; //Unused
  309. uint8_t ar7 : 1; //Unused
  310. } __attribute__((packed)) bits;
  311. uint8_t byte;
  312. } arFunctionsActive;
  313. uint8_t auto_report_period;
  314. public:
  315. LongTimer auto_report_timer;
  316. AutoReportFeatures():auto_report_period(0){
  317. #if defined(AUTO_REPORT)
  318. arFunctionsActive.byte = 0xff;
  319. #else
  320. arFunctionsActive.byte = 0;
  321. #endif //AUTO_REPORT
  322. }
  323. inline bool Temp()const { return arFunctionsActive.bits.temp != 0; }
  324. inline void SetTemp(uint8_t v){ arFunctionsActive.bits.temp = v; }
  325. inline bool Fans()const { return arFunctionsActive.bits.fans != 0; }
  326. inline void SetFans(uint8_t v){ arFunctionsActive.bits.fans = v; }
  327. inline bool Pos()const { return arFunctionsActive.bits.pos != 0; }
  328. inline void SetPos(uint8_t v){ arFunctionsActive.bits.pos = v; }
  329. inline void SetMask(uint8_t mask){ arFunctionsActive.byte = mask; }
  330. /// sets the autoreporting timer's period
  331. /// setting it to zero stops the timer
  332. void SetPeriod(uint8_t p){
  333. auto_report_period = p;
  334. if (auto_report_period != 0){
  335. auto_report_timer.start();
  336. } else{
  337. auto_report_timer.stop();
  338. }
  339. }
  340. inline void TimerStart() { auto_report_timer.start(); }
  341. inline bool TimerRunning()const { return auto_report_timer.running(); }
  342. inline bool TimerExpired() { return auto_report_timer.expired(auto_report_period * 1000ul); }
  343. };
  344. AutoReportFeatures autoReportFeatures;
  345. //===========================================================================
  346. //=============================Routines======================================
  347. //===========================================================================
  348. static bool setTargetedHotend(int code, uint8_t &extruder);
  349. static void print_time_remaining_init();
  350. static void wait_for_heater(long codenum, uint8_t extruder);
  351. static void gcode_G28(bool home_x_axis, bool home_y_axis, bool home_z_axis);
  352. static void gcode_M105(uint8_t extruder);
  353. #ifndef PINDA_THERMISTOR
  354. static void temp_compensation_start();
  355. static void temp_compensation_apply();
  356. #endif
  357. #ifdef PRUSA_SN_SUPPORT
  358. static uint8_t get_PRUSA_SN(char* SN);
  359. #endif //PRUSA_SN_SUPPORT
  360. uint16_t gcode_in_progress = 0;
  361. uint16_t mcode_in_progress = 0;
  362. void serial_echopair_P(const char *s_P, float v)
  363. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  364. void serial_echopair_P(const char *s_P, double v)
  365. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  366. void serial_echopair_P(const char *s_P, unsigned long v)
  367. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  368. void serialprintPGM(const char *str) {
  369. while(uint8_t ch = pgm_read_byte(str)) {
  370. MYSERIAL.write((char)ch);
  371. ++str;
  372. }
  373. }
  374. void serialprintlnPGM(const char *str) {
  375. serialprintPGM(str);
  376. MYSERIAL.println();
  377. }
  378. #ifdef SDSUPPORT
  379. #include "SdFatUtil.h"
  380. int freeMemory() { return SdFatUtil::FreeRam(); }
  381. #else
  382. extern "C" {
  383. extern unsigned int __bss_end;
  384. extern unsigned int __heap_start;
  385. extern void *__brkval;
  386. int freeMemory() {
  387. int free_memory;
  388. if ((int)__brkval == 0)
  389. free_memory = ((int)&free_memory) - ((int)&__bss_end);
  390. else
  391. free_memory = ((int)&free_memory) - ((int)__brkval);
  392. return free_memory;
  393. }
  394. }
  395. #endif //!SDSUPPORT
  396. void setup_killpin()
  397. {
  398. #if defined(KILL_PIN) && KILL_PIN > -1
  399. SET_INPUT(KILL_PIN);
  400. WRITE(KILL_PIN,HIGH);
  401. #endif
  402. }
  403. // Set home pin
  404. void setup_homepin(void)
  405. {
  406. #if defined(HOME_PIN) && HOME_PIN > -1
  407. SET_INPUT(HOME_PIN);
  408. WRITE(HOME_PIN,HIGH);
  409. #endif
  410. }
  411. void setup_photpin()
  412. {
  413. #if defined(PHOTOGRAPH_PIN) && PHOTOGRAPH_PIN > -1
  414. SET_OUTPUT(PHOTOGRAPH_PIN);
  415. WRITE(PHOTOGRAPH_PIN, LOW);
  416. #endif
  417. }
  418. void setup_powerhold()
  419. {
  420. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  421. SET_OUTPUT(SUICIDE_PIN);
  422. WRITE(SUICIDE_PIN, HIGH);
  423. #endif
  424. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  425. SET_OUTPUT(PS_ON_PIN);
  426. #if defined(PS_DEFAULT_OFF)
  427. WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  428. #else
  429. WRITE(PS_ON_PIN, PS_ON_AWAKE);
  430. #endif
  431. #endif
  432. }
  433. void suicide()
  434. {
  435. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  436. SET_OUTPUT(SUICIDE_PIN);
  437. WRITE(SUICIDE_PIN, LOW);
  438. #endif
  439. }
  440. void servo_init()
  441. {
  442. #if (NUM_SERVOS >= 1) && defined(SERVO0_PIN) && (SERVO0_PIN > -1)
  443. servos[0].attach(SERVO0_PIN);
  444. #endif
  445. #if (NUM_SERVOS >= 2) && defined(SERVO1_PIN) && (SERVO1_PIN > -1)
  446. servos[1].attach(SERVO1_PIN);
  447. #endif
  448. #if (NUM_SERVOS >= 3) && defined(SERVO2_PIN) && (SERVO2_PIN > -1)
  449. servos[2].attach(SERVO2_PIN);
  450. #endif
  451. #if (NUM_SERVOS >= 4) && defined(SERVO3_PIN) && (SERVO3_PIN > -1)
  452. servos[3].attach(SERVO3_PIN);
  453. #endif
  454. #if (NUM_SERVOS >= 5)
  455. #error "TODO: enter initalisation code for more servos"
  456. #endif
  457. }
  458. bool __attribute__((noinline)) printer_active() {
  459. return IS_SD_PRINTING
  460. || usb_timer.running()
  461. || isPrintPaused
  462. || (custom_message_type == CustomMsg::TempCal)
  463. || saved_printing
  464. || (lcd_commands_type == LcdCommands::Layer1Cal)
  465. || mmu_print_saved
  466. || homing_flag
  467. || mesh_bed_leveling_flag;
  468. }
  469. bool fans_check_enabled = true;
  470. #ifdef TMC2130
  471. void crashdet_stop_and_save_print()
  472. {
  473. stop_and_save_print_to_ram(10, -default_retraction); //XY - no change, Z 10mm up, E -1mm retract
  474. }
  475. void crashdet_restore_print_and_continue()
  476. {
  477. restore_print_from_ram_and_continue(default_retraction); //XYZ = orig, E +1mm unretract
  478. // babystep_apply();
  479. }
  480. void crashdet_fmt_error(char* buf, uint8_t mask)
  481. {
  482. if(mask & X_AXIS_MASK) *buf++ = axis_codes[X_AXIS];
  483. if(mask & Y_AXIS_MASK) *buf++ = axis_codes[Y_AXIS];
  484. *buf++ = ' ';
  485. strcpy_P(buf, _T(MSG_CRASH_DETECTED));
  486. }
  487. void crashdet_detected(uint8_t mask)
  488. {
  489. st_synchronize();
  490. static uint8_t crashDet_counter = 0;
  491. static uint8_t crashDet_axes = 0;
  492. bool automatic_recovery_after_crash = true;
  493. char msg[LCD_WIDTH+1] = "";
  494. if (crashDetTimer.expired(CRASHDET_TIMER * 1000ul)) {
  495. crashDet_counter = 0;
  496. }
  497. if(++crashDet_counter >= CRASHDET_COUNTER_MAX) {
  498. automatic_recovery_after_crash = false;
  499. }
  500. crashDetTimer.start();
  501. crashDet_axes |= mask;
  502. lcd_update_enable(true);
  503. lcd_clear();
  504. lcd_update(2);
  505. if (mask & X_AXIS_MASK)
  506. {
  507. eeprom_update_byte((uint8_t*)EEPROM_CRASH_COUNT_X, eeprom_read_byte((uint8_t*)EEPROM_CRASH_COUNT_X) + 1);
  508. eeprom_update_word((uint16_t*)EEPROM_CRASH_COUNT_X_TOT, eeprom_read_word((uint16_t*)EEPROM_CRASH_COUNT_X_TOT) + 1);
  509. }
  510. if (mask & Y_AXIS_MASK)
  511. {
  512. eeprom_update_byte((uint8_t*)EEPROM_CRASH_COUNT_Y, eeprom_read_byte((uint8_t*)EEPROM_CRASH_COUNT_Y) + 1);
  513. eeprom_update_word((uint16_t*)EEPROM_CRASH_COUNT_Y_TOT, eeprom_read_word((uint16_t*)EEPROM_CRASH_COUNT_Y_TOT) + 1);
  514. }
  515. lcd_update_enable(true);
  516. lcd_update(2);
  517. // prepare the status message with the _current_ axes status
  518. crashdet_fmt_error(msg, mask);
  519. lcd_setstatus(msg);
  520. gcode_G28(true, true, false); //home X and Y
  521. if (automatic_recovery_after_crash) {
  522. enquecommand_P(PSTR("CRASH_RECOVER"));
  523. }else{
  524. setTargetHotend(0, active_extruder);
  525. // notify the user of *all* the axes previously affected, not just the last one
  526. lcd_update_enable(false);
  527. lcd_clear();
  528. crashdet_fmt_error(msg, crashDet_axes);
  529. crashDet_axes = 0;
  530. lcd_print(msg);
  531. // ask whether to resume printing
  532. lcd_set_cursor(0, 1);
  533. lcd_puts_P(_T(MSG_RESUME_PRINT));
  534. lcd_putc('?');
  535. bool yesno = lcd_show_yes_no_and_wait(false);
  536. lcd_update_enable(true);
  537. if (yesno)
  538. {
  539. enquecommand_P(PSTR("CRASH_RECOVER"));
  540. }
  541. else
  542. {
  543. enquecommand_P(PSTR("CRASH_CANCEL"));
  544. }
  545. }
  546. }
  547. void crashdet_recover()
  548. {
  549. crashdet_restore_print_and_continue();
  550. if (lcd_crash_detect_enabled()) tmc2130_sg_stop_on_crash = true;
  551. }
  552. void crashdet_cancel()
  553. {
  554. saved_printing = false;
  555. tmc2130_sg_stop_on_crash = true;
  556. if (saved_printing_type == PRINTING_TYPE_SD) {
  557. lcd_print_stop();
  558. }else if(saved_printing_type == PRINTING_TYPE_USB){
  559. SERIAL_ECHOLNRPGM(MSG_OCTOPRINT_CANCEL); //for Octoprint: works the same as clicking "Abort" button in Octoprint GUI
  560. cmdqueue_reset();
  561. }
  562. }
  563. #endif //TMC2130
  564. void failstats_reset_print()
  565. {
  566. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_X, 0);
  567. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_Y, 0);
  568. eeprom_update_byte((uint8_t *)EEPROM_FERROR_COUNT, 0);
  569. eeprom_update_byte((uint8_t *)EEPROM_POWER_COUNT, 0);
  570. eeprom_update_byte((uint8_t *)EEPROM_MMU_FAIL, 0);
  571. eeprom_update_byte((uint8_t *)EEPROM_MMU_LOAD_FAIL, 0);
  572. #if defined(FILAMENT_SENSOR) && defined(PAT9125)
  573. fsensor_softfail = 0;
  574. #endif
  575. }
  576. void softReset()
  577. {
  578. cli();
  579. wdt_enable(WDTO_15MS);
  580. while(1);
  581. }
  582. #ifdef MESH_BED_LEVELING
  583. enum MeshLevelingState { MeshReport, MeshStart, MeshNext, MeshSet };
  584. #endif
  585. static void factory_reset_stats(){
  586. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, 0);
  587. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, 0);
  588. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_X, 0);
  589. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_Y, 0);
  590. eeprom_update_byte((uint8_t *)EEPROM_FERROR_COUNT, 0);
  591. eeprom_update_byte((uint8_t *)EEPROM_POWER_COUNT, 0);
  592. eeprom_update_word((uint16_t *)EEPROM_CRASH_COUNT_X_TOT, 0);
  593. eeprom_update_word((uint16_t *)EEPROM_CRASH_COUNT_Y_TOT, 0);
  594. eeprom_update_word((uint16_t *)EEPROM_FERROR_COUNT_TOT, 0);
  595. eeprom_update_word((uint16_t *)EEPROM_POWER_COUNT_TOT, 0);
  596. eeprom_update_word((uint16_t *)EEPROM_MMU_FAIL_TOT, 0);
  597. eeprom_update_word((uint16_t *)EEPROM_MMU_LOAD_FAIL_TOT, 0);
  598. eeprom_update_byte((uint8_t *)EEPROM_MMU_FAIL, 0);
  599. eeprom_update_byte((uint8_t *)EEPROM_MMU_LOAD_FAIL, 0);
  600. }
  601. // Factory reset function
  602. // This function is used to erase parts or whole EEPROM memory which is used for storing calibration and and so on.
  603. // Level input parameter sets depth of reset
  604. static void factory_reset(char level)
  605. {
  606. lcd_clear();
  607. Sound_MakeCustom(100,0,false);
  608. switch (level) {
  609. case 0: // Level 0: Language reset
  610. lang_reset();
  611. break;
  612. case 1: //Level 1: Reset statistics
  613. factory_reset_stats();
  614. lcd_menu_statistics();
  615. break;
  616. case 2: // Level 2: Prepare for shipping
  617. factory_reset_stats();
  618. // FALLTHRU
  619. case 3: // Level 3: Preparation after being serviced
  620. // Force language selection at the next boot up.
  621. lang_reset();
  622. // Force the "Follow calibration flow" message at the next boot up.
  623. calibration_status_store(CALIBRATION_STATUS_Z_CALIBRATION);
  624. eeprom_write_byte((uint8_t*)EEPROM_WIZARD_ACTIVE, 2); //run wizard
  625. farm_disable();
  626. #ifdef FILAMENT_SENSOR
  627. fsensor.setEnabled(true);
  628. fsensor.setAutoLoadEnabled(true, true);
  629. fsensor.setRunoutEnabled(true, true);
  630. #endif //FILAMENT_SENSOR
  631. break;
  632. case 4:
  633. menu_progressbar_init(EEPROM_TOP, PSTR("ERASING all data"));
  634. // Erase EEPROM
  635. for (uint16_t i = 0; i < EEPROM_TOP; i++) {
  636. eeprom_update_byte((uint8_t*)i, 0xFF);
  637. menu_progressbar_update(i);
  638. }
  639. menu_progressbar_finish();
  640. softReset();
  641. break;
  642. default:
  643. break;
  644. }
  645. }
  646. extern "C" {
  647. FILE _uartout; //= {0}; Global variable is always zero initialized. No need to explicitly state this.
  648. }
  649. int uart_putchar(char c, FILE *)
  650. {
  651. MYSERIAL.write(c);
  652. return 0;
  653. }
  654. void lcd_splash()
  655. {
  656. lcd_clear(); // clears display and homes screen
  657. lcd_puts_P(PSTR("\n Original Prusa i3\n Prusa Research"));
  658. }
  659. void factory_reset()
  660. {
  661. KEEPALIVE_STATE(PAUSED_FOR_USER);
  662. if (!READ(BTN_ENC))
  663. {
  664. _delay_ms(1000);
  665. if (!READ(BTN_ENC))
  666. {
  667. lcd_clear();
  668. lcd_puts_P(PSTR("Factory RESET"));
  669. SET_OUTPUT(BEEPER);
  670. if(eSoundMode!=e_SOUND_MODE_SILENT)
  671. WRITE(BEEPER, HIGH);
  672. while (!READ(BTN_ENC));
  673. WRITE(BEEPER, LOW);
  674. _delay_ms(2000);
  675. char level = reset_menu();
  676. factory_reset(level);
  677. switch (level) {
  678. case 0:
  679. case 1:
  680. case 2:
  681. case 3:
  682. case 4: _delay_ms(0); break;
  683. }
  684. }
  685. }
  686. KEEPALIVE_STATE(IN_HANDLER);
  687. }
  688. void show_fw_version_warnings() {
  689. if (FW_DEV_VERSION == FW_VERSION_GOLD || FW_DEV_VERSION == FW_VERSION_RC) return;
  690. switch (FW_DEV_VERSION) {
  691. 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
  692. 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
  693. case(FW_VERSION_DEVEL):
  694. case(FW_VERSION_DEBUG):
  695. lcd_update_enable(false);
  696. lcd_clear();
  697. #if FW_DEV_VERSION == FW_VERSION_DEVEL
  698. lcd_puts_at_P(0, 0, PSTR("Development build !!"));
  699. #else
  700. lcd_puts_at_P(0, 0, PSTR("Debbugging build !!!"));
  701. #endif
  702. lcd_puts_at_P(0, 1, PSTR("May destroy printer!"));
  703. lcd_puts_at_P(0, 2, PSTR("ver ")); lcd_puts_P(PSTR(FW_VERSION_FULL));
  704. lcd_puts_at_P(0, 3, PSTR(FW_REPOSITORY));
  705. lcd_wait_for_click();
  706. break;
  707. // 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
  708. }
  709. lcd_update_enable(true);
  710. }
  711. //! @brief try to check if firmware is on right type of printer
  712. static void check_if_fw_is_on_right_printer(){
  713. #ifdef FILAMENT_SENSOR
  714. if((PRINTER_TYPE == PRINTER_MK3) || (PRINTER_TYPE == PRINTER_MK3S)){
  715. #ifdef IR_SENSOR
  716. if (pat9125_probe()){
  717. lcd_show_fullscreen_message_and_wait_P(_i("MK3S firmware detected on MK3 printer"));}////MSG_MK3S_FIRMWARE_ON_MK3 c=20 r=4
  718. #endif //IR_SENSOR
  719. #ifdef PAT9125
  720. //will return 1 only if IR can detect filament in bondtech extruder so this may fail even when we have IR sensor
  721. const uint8_t ir_detected = fsensor.getFilamentPresent();
  722. if (ir_detected){
  723. lcd_show_fullscreen_message_and_wait_P(_i("MK3 firmware detected on MK3S printer"));}////MSG_MK3_FIRMWARE_ON_MK3S c=20 r=4
  724. #endif //PAT9125
  725. }
  726. #endif //FILAMENT_SENSOR
  727. }
  728. uint8_t check_printer_version()
  729. {
  730. uint8_t version_changed = 0;
  731. uint16_t printer_type = eeprom_read_word((uint16_t*)EEPROM_PRINTER_TYPE);
  732. uint16_t motherboard = eeprom_read_word((uint16_t*)EEPROM_BOARD_TYPE);
  733. if (printer_type != PRINTER_TYPE) {
  734. if (printer_type == 0xffff) eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  735. else version_changed |= 0b10;
  736. }
  737. if (motherboard != MOTHERBOARD) {
  738. if(motherboard == 0xffff) eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  739. else version_changed |= 0b01;
  740. }
  741. return version_changed;
  742. }
  743. #ifdef BOOTAPP
  744. #include "bootapp.h" //bootloader support
  745. #endif //BOOTAPP
  746. #if (LANG_MODE != 0) //secondary language support
  747. #ifdef XFLASH
  748. // language update from external flash
  749. #define LANGBOOT_BLOCKSIZE 0x1000u
  750. #define LANGBOOT_RAMBUFFER 0x0800
  751. void update_sec_lang_from_external_flash()
  752. {
  753. if ((boot_app_magic == BOOT_APP_MAGIC) && (boot_app_flags & BOOT_APP_FLG_USER0))
  754. {
  755. uint8_t lang = boot_reserved >> 3;
  756. uint8_t state = boot_reserved & 0x07;
  757. lang_table_header_t header;
  758. uint32_t src_addr;
  759. if (lang_get_header(lang, &header, &src_addr))
  760. {
  761. lcd_puts_at_P(1,3,PSTR("Language update."));
  762. for (uint8_t i = 0; i < state; i++) fputc('.', lcdout);
  763. _delay(100);
  764. boot_reserved = (boot_reserved & 0xF8) | ((state + 1) & 0x07);
  765. if ((state * LANGBOOT_BLOCKSIZE) < header.size)
  766. {
  767. cli();
  768. uint16_t size = header.size - state * LANGBOOT_BLOCKSIZE;
  769. if (size > LANGBOOT_BLOCKSIZE) size = LANGBOOT_BLOCKSIZE;
  770. xflash_rd_data(src_addr + state * LANGBOOT_BLOCKSIZE, (uint8_t*)LANGBOOT_RAMBUFFER, size);
  771. if (state == 0)
  772. {
  773. //TODO - check header integrity
  774. }
  775. bootapp_ram2flash(LANGBOOT_RAMBUFFER, _SEC_LANG_TABLE + state * LANGBOOT_BLOCKSIZE, size);
  776. }
  777. else
  778. {
  779. //TODO - check sec lang data integrity
  780. eeprom_update_byte((unsigned char *)EEPROM_LANG, LANG_ID_SEC);
  781. }
  782. }
  783. }
  784. boot_app_flags &= ~BOOT_APP_FLG_USER0;
  785. }
  786. #ifdef DEBUG_XFLASH
  787. uint8_t lang_xflash_enum_codes(uint16_t* codes)
  788. {
  789. lang_table_header_t header;
  790. uint8_t count = 0;
  791. uint32_t addr = 0x00000;
  792. while (1)
  793. {
  794. printf_P(_n("LANGTABLE%d:"), count);
  795. xflash_rd_data(addr, (uint8_t*)&header, sizeof(lang_table_header_t));
  796. if (header.magic != LANG_MAGIC)
  797. {
  798. puts_P(_n("NG!"));
  799. break;
  800. }
  801. puts_P(_n("OK"));
  802. printf_P(_n(" _lt_magic = 0x%08lx %S\n"), header.magic, (header.magic==LANG_MAGIC)?_n("OK"):_n("NA"));
  803. printf_P(_n(" _lt_size = 0x%04x (%d)\n"), header.size, header.size);
  804. printf_P(_n(" _lt_count = 0x%04x (%d)\n"), header.count, header.count);
  805. printf_P(_n(" _lt_chsum = 0x%04x\n"), header.checksum);
  806. printf_P(_n(" _lt_code = 0x%04x (%c%c)\n"), header.code, header.code >> 8, header.code & 0xff);
  807. printf_P(_n(" _lt_sign = 0x%08lx\n"), header.signature);
  808. addr += header.size;
  809. codes[count] = header.code;
  810. count ++;
  811. }
  812. return count;
  813. }
  814. void list_sec_lang_from_external_flash()
  815. {
  816. uint16_t codes[8];
  817. uint8_t count = lang_xflash_enum_codes(codes);
  818. printf_P(_n("XFlash lang count = %hhd\n"), count);
  819. }
  820. #endif //DEBUG_XFLASH
  821. #endif //XFLASH
  822. #endif //(LANG_MODE != 0)
  823. static void fw_crash_init()
  824. {
  825. #ifdef XFLASH_DUMP
  826. dump_crash_reason crash_reason;
  827. if(xfdump_check_state(&crash_reason))
  828. {
  829. // always signal to the host that a dump is available for retrieval
  830. puts_P(_N("// action:dump_available"));
  831. #ifdef EMERGENCY_DUMP
  832. if(crash_reason != dump_crash_reason::manual &&
  833. eeprom_read_byte((uint8_t*)EEPROM_FW_CRASH_FLAG) != 0xFF)
  834. {
  835. lcd_show_fullscreen_message_and_wait_P(
  836. _n("FW crash detected! "
  837. "You can continue printing. "
  838. "Debug data available for analysis. "
  839. "Contact support to submit details."));
  840. }
  841. #endif
  842. }
  843. #else //XFLASH_DUMP
  844. dump_crash_reason crash_reason = (dump_crash_reason)eeprom_read_byte((uint8_t*)EEPROM_FW_CRASH_FLAG);
  845. if(crash_reason != dump_crash_reason::manual && (uint8_t)crash_reason != 0xFF)
  846. {
  847. lcd_beeper_quick_feedback();
  848. lcd_clear();
  849. lcd_puts_P(_n("FIRMWARE CRASH!\nCrash reason:\n"));
  850. switch(crash_reason)
  851. {
  852. case dump_crash_reason::stack_error:
  853. lcd_puts_P(_n("Static memory has\nbeen overwritten"));
  854. break;
  855. case dump_crash_reason::watchdog:
  856. lcd_puts_P(_n("Watchdog timeout"));
  857. break;
  858. case dump_crash_reason::bad_isr:
  859. lcd_puts_P(_n("Bad interrupt"));
  860. break;
  861. default:
  862. lcd_print((uint8_t)crash_reason);
  863. break;
  864. }
  865. lcd_wait_for_click();
  866. }
  867. #endif //XFLASH_DUMP
  868. // prevent crash prompts to reappear once acknowledged
  869. eeprom_update_byte((uint8_t*)EEPROM_FW_CRASH_FLAG, 0xFF);
  870. }
  871. static void xflash_err_msg()
  872. {
  873. puts_P(_n("XFLASH not responding."));
  874. lcd_show_fullscreen_message_and_wait_P(_n("External SPI flash\nXFLASH is not res-\nponding. Language\nswitch unavailable."));
  875. }
  876. // "Setup" function is called by the Arduino framework on startup.
  877. // Before startup, the Timers-functions (PWM)/Analog RW and HardwareSerial provided by the Arduino-code
  878. // are initialized by the main() routine provided by the Arduino framework.
  879. void setup()
  880. {
  881. timer2_init(); // enables functional millis
  882. mmu_init();
  883. ultralcd_init();
  884. spi_init();
  885. lcd_splash();
  886. Sound_Init(); // also guarantee "SET_OUTPUT(BEEPER)"
  887. selectedSerialPort = eeprom_read_byte((uint8_t *)EEPROM_SECOND_SERIAL_ACTIVE);
  888. if (selectedSerialPort == 0xFF) selectedSerialPort = 0;
  889. eeprom_update_byte((uint8_t *)EEPROM_SECOND_SERIAL_ACTIVE, selectedSerialPort);
  890. MYSERIAL.begin(BAUDRATE);
  891. fdev_setup_stream(uartout, uart_putchar, NULL, _FDEV_SETUP_WRITE); //setup uart out stream
  892. stdout = uartout;
  893. #ifdef XFLASH
  894. bool xflash_success = xflash_init();
  895. uint8_t optiboot_status = 1;
  896. if (xflash_success)
  897. {
  898. optiboot_status = optiboot_xflash_enter();
  899. #if (LANG_MODE != 0) //secondary language support
  900. update_sec_lang_from_external_flash();
  901. #endif //(LANG_MODE != 0)
  902. }
  903. #else
  904. const bool xflash_success = true;
  905. #endif //XFLASH
  906. setup_killpin();
  907. setup_powerhold();
  908. farm_mode_init();
  909. #ifdef TMC2130
  910. if( FarmOrUserECool() ){
  911. //increased extruder current (PFW363)
  912. tmc2130_current_h[E_AXIS] = TMC2130_CURRENTS_FARM;
  913. tmc2130_current_r[E_AXIS] = TMC2130_CURRENTS_FARM;
  914. }
  915. #endif //TMC2130
  916. #ifdef PRUSA_SN_SUPPORT
  917. //Check for valid SN in EEPROM. Try to retrieve it in case it's invalid.
  918. //SN is valid only if it is NULL terminated and starts with "CZPX".
  919. {
  920. char SN[20];
  921. eeprom_read_block(SN, (uint8_t*)EEPROM_PRUSA_SN, 20);
  922. if (SN[19] || strncmp_P(SN, PSTR("CZPX"), 4))
  923. {
  924. if (!get_PRUSA_SN(SN))
  925. {
  926. eeprom_update_block(SN, (uint8_t*)EEPROM_PRUSA_SN, 20);
  927. puts_P(PSTR("SN updated"));
  928. }
  929. else
  930. puts_P(PSTR("SN update failed"));
  931. }
  932. }
  933. #endif //PRUSA_SN_SUPPORT
  934. #ifndef XFLASH
  935. SERIAL_PROTOCOLLNPGM("start");
  936. #else
  937. if ((optiboot_status != 0) || (selectedSerialPort != 0))
  938. SERIAL_PROTOCOLLNPGM("start");
  939. #endif
  940. SERIAL_ECHO_START;
  941. puts_P(PSTR(" " FW_VERSION_FULL));
  942. //SERIAL_ECHOPAIR("Active sheet before:", static_cast<unsigned long int>(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet))));
  943. #ifdef DEBUG_SEC_LANG
  944. lang_table_header_t header;
  945. uint32_t src_addr = 0x00000;
  946. if (lang_get_header(1, &header, &src_addr))
  947. {
  948. printf_P(
  949. _n(
  950. " _src_addr = 0x%08lx\n"
  951. " _lt_magic = 0x%08lx %S\n"
  952. " _lt_size = 0x%04x (%d)\n"
  953. " _lt_count = 0x%04x (%d)\n"
  954. " _lt_chsum = 0x%04x\n"
  955. " _lt_code = 0x%04x (%c%c)\n"
  956. " _lt_resv1 = 0x%08lx\n"
  957. ),
  958. src_addr,
  959. header.magic, (header.magic==LANG_MAGIC)?_n("OK"):_n("NA"),
  960. header.size, header.size,
  961. header.count, header.count,
  962. header.checksum,
  963. header.code, header.code >> 8, header.code & 0xff,
  964. header.signature
  965. );
  966. #if 0
  967. xflash_rd_data(0x25ba, (uint8_t*)&block_buffer, 1024);
  968. for (uint16_t i = 0; i < 1024; i++)
  969. {
  970. if ((i % 16) == 0) printf_P(_n("%04x:"), 0x25ba+i);
  971. printf_P(_n(" %02x"), ((uint8_t*)&block_buffer)[i]);
  972. if ((i % 16) == 15) putchar('\n');
  973. }
  974. #endif
  975. uint16_t sum = 0;
  976. for (uint16_t i = 0; i < header.size; i++)
  977. sum += (uint16_t)pgm_read_byte((uint8_t*)(_SEC_LANG_TABLE + i)) << ((i & 1)?0:8);
  978. printf_P(_n("_SEC_LANG_TABLE checksum = %04x\n"), sum);
  979. sum -= header.checksum; //subtract checksum
  980. printf_P(_n("_SEC_LANG_TABLE checksum = %04x\n"), sum);
  981. sum = (sum >> 8) | ((sum & 0xff) << 8); //swap bytes
  982. if (sum == header.checksum)
  983. puts_P(_n("Checksum OK"));
  984. else
  985. puts_P(_n("Checksum NG"));
  986. }
  987. else
  988. puts_P(_n("lang_get_header failed!"));
  989. #if 0
  990. for (uint16_t i = 0; i < 1024*10; i++)
  991. {
  992. if ((i % 16) == 0) printf_P(_n("%04x:"), _SEC_LANG_TABLE+i);
  993. printf_P(_n(" %02x"), pgm_read_byte((uint8_t*)(_SEC_LANG_TABLE+i)));
  994. if ((i % 16) == 15) putchar('\n');
  995. }
  996. #endif
  997. #if 0
  998. SERIAL_ECHOLN("Reading eeprom from 0 to 100: start");
  999. for (int i = 0; i < 4096; ++i) {
  1000. int b = eeprom_read_byte((unsigned char*)i);
  1001. if (b != 255) {
  1002. SERIAL_ECHO(i);
  1003. SERIAL_ECHO(":");
  1004. SERIAL_ECHO(b);
  1005. SERIAL_ECHOLN("");
  1006. }
  1007. }
  1008. SERIAL_ECHOLN("Reading eeprom from 0 to 100: done");
  1009. #endif
  1010. #endif //DEBUG_SEC_LANG
  1011. // Check startup - does nothing if bootloader sets MCUSR to 0
  1012. byte mcu = MCUSR;
  1013. /* if (mcu & 1) SERIAL_ECHOLNRPGM(MSG_POWERUP);
  1014. if (mcu & 2) SERIAL_ECHOLNRPGM(MSG_EXTERNAL_RESET);
  1015. if (mcu & 4) SERIAL_ECHOLNRPGM(MSG_BROWNOUT_RESET);
  1016. if (mcu & 8) SERIAL_ECHOLNRPGM(MSG_WATCHDOG_RESET);
  1017. if (mcu & 32) SERIAL_ECHOLNRPGM(MSG_SOFTWARE_RESET);*/
  1018. if (mcu & 1) puts_P(MSG_POWERUP);
  1019. if (mcu & 2) puts_P(MSG_EXTERNAL_RESET);
  1020. if (mcu & 4) puts_P(MSG_BROWNOUT_RESET);
  1021. if (mcu & 8) puts_P(MSG_WATCHDOG_RESET);
  1022. if (mcu & 32) puts_P(MSG_SOFTWARE_RESET);
  1023. MCUSR = 0;
  1024. //SERIAL_ECHORPGM(MSG_MARLIN);
  1025. //SERIAL_ECHOLNRPGM(VERSION_STRING);
  1026. #ifdef STRING_VERSION_CONFIG_H
  1027. #ifdef STRING_CONFIG_H_AUTHOR
  1028. SERIAL_ECHO_START;
  1029. SERIAL_ECHORPGM(_n(" Last Updated: "));////MSG_CONFIGURATION_VER
  1030. SERIAL_ECHOPGM(STRING_VERSION_CONFIG_H);
  1031. SERIAL_ECHORPGM(_n(" | Author: "));////MSG_AUTHOR
  1032. SERIAL_ECHOLNPGM(STRING_CONFIG_H_AUTHOR);
  1033. SERIAL_ECHOPGM("Compiled: ");
  1034. SERIAL_ECHOLNPGM(__DATE__);
  1035. #endif
  1036. #endif
  1037. SERIAL_ECHO_START;
  1038. SERIAL_ECHORPGM(_n(" Free Memory: "));////MSG_FREE_MEMORY
  1039. SERIAL_ECHO(freeMemory());
  1040. SERIAL_ECHORPGM(_n(" PlannerBufferBytes: "));////MSG_PLANNER_BUFFER_BYTES
  1041. SERIAL_ECHOLN((int)sizeof(block_t)*BLOCK_BUFFER_SIZE);
  1042. //lcd_update_enable(false); // why do we need this?? - andre
  1043. // loads data from EEPROM if available else uses defaults (and resets step acceleration rate)
  1044. bool previous_settings_retrieved = false;
  1045. uint8_t hw_changed = check_printer_version();
  1046. 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
  1047. previous_settings_retrieved = Config_RetrieveSettings();
  1048. }
  1049. else { //printer version was changed so use default settings
  1050. Config_ResetDefault();
  1051. }
  1052. // writes a magic number at the end of static variables to monitor against incorrect overwriting
  1053. // of static memory by stack (this needs to be done before soft_pwm_init, since the check is
  1054. // performed inside the soft_pwm_isr)
  1055. SdFatUtil::set_stack_guard();
  1056. // Initialize pwm/temperature loops
  1057. soft_pwm_init();
  1058. temp_mgr_init();
  1059. #ifdef EXTRUDER_ALTFAN_DETECT
  1060. SERIAL_ECHORPGM(_n("Extruder fan type: "));
  1061. if (extruder_altfan_detect())
  1062. SERIAL_ECHOLNRPGM(PSTR("ALTFAN"));
  1063. else
  1064. SERIAL_ECHOLNRPGM(PSTR("NOCTUA"));
  1065. #endif //EXTRUDER_ALTFAN_DETECT
  1066. plan_init(); // Initialize planner;
  1067. factory_reset();
  1068. if (eeprom_read_dword((uint32_t*)(EEPROM_TOP - 4)) == 0x0ffffffff &&
  1069. eeprom_read_dword((uint32_t*)(EEPROM_TOP - 8)) == 0x0ffffffff)
  1070. {
  1071. // Maiden startup. The firmware has been loaded and first started on a virgin RAMBo board,
  1072. // where all the EEPROM entries are set to 0x0ff.
  1073. // Once a firmware boots up, it forces at least a language selection, which changes
  1074. // EEPROM_LANG to number lower than 0x0ff.
  1075. // 1) Set a high power mode.
  1076. eeprom_update_byte((uint8_t*)EEPROM_SILENT, SILENT_MODE_OFF);
  1077. #ifdef TMC2130
  1078. tmc2130_mode = TMC2130_MODE_NORMAL;
  1079. #endif //TMC2130
  1080. eeprom_write_byte((uint8_t*)EEPROM_WIZARD_ACTIVE, 1); //run wizard
  1081. }
  1082. lcd_encoder_diff=0;
  1083. #ifdef TMC2130
  1084. uint8_t silentMode = eeprom_read_byte((uint8_t*)EEPROM_SILENT);
  1085. if (silentMode == 0xff) silentMode = 0;
  1086. tmc2130_mode = TMC2130_MODE_NORMAL;
  1087. if (lcd_crash_detect_enabled() && !farm_mode)
  1088. {
  1089. lcd_crash_detect_enable();
  1090. puts_P(_N("CrashDetect ENABLED!"));
  1091. }
  1092. else
  1093. {
  1094. lcd_crash_detect_disable();
  1095. puts_P(_N("CrashDetect DISABLED"));
  1096. }
  1097. #ifdef TMC2130_LINEARITY_CORRECTION
  1098. #ifdef TMC2130_LINEARITY_CORRECTION_XYZ
  1099. tmc2130_wave_fac[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_X_FAC);
  1100. tmc2130_wave_fac[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_Y_FAC);
  1101. tmc2130_wave_fac[Z_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_Z_FAC);
  1102. #endif //TMC2130_LINEARITY_CORRECTION_XYZ
  1103. tmc2130_wave_fac[E_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_E_FAC);
  1104. if (tmc2130_wave_fac[X_AXIS] == 0xff) tmc2130_wave_fac[X_AXIS] = 0;
  1105. if (tmc2130_wave_fac[Y_AXIS] == 0xff) tmc2130_wave_fac[Y_AXIS] = 0;
  1106. if (tmc2130_wave_fac[Z_AXIS] == 0xff) tmc2130_wave_fac[Z_AXIS] = 0;
  1107. if (tmc2130_wave_fac[E_AXIS] == 0xff) tmc2130_wave_fac[E_AXIS] = 0;
  1108. #endif //TMC2130_LINEARITY_CORRECTION
  1109. #ifdef TMC2130_VARIABLE_RESOLUTION
  1110. tmc2130_mres[X_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[X_AXIS]);
  1111. tmc2130_mres[Y_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[Y_AXIS]);
  1112. tmc2130_mres[Z_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[Z_AXIS]);
  1113. tmc2130_mres[E_AXIS] = tmc2130_usteps2mres(cs.axis_ustep_resolution[E_AXIS]);
  1114. #else //TMC2130_VARIABLE_RESOLUTION
  1115. tmc2130_mres[X_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_XY);
  1116. tmc2130_mres[Y_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_XY);
  1117. tmc2130_mres[Z_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_Z);
  1118. tmc2130_mres[E_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_E);
  1119. #endif //TMC2130_VARIABLE_RESOLUTION
  1120. #endif //TMC2130
  1121. st_init(); // Initialize stepper, this enables interrupts!
  1122. #ifdef TMC2130
  1123. tmc2130_mode = silentMode?TMC2130_MODE_SILENT:TMC2130_MODE_NORMAL;
  1124. update_mode_profile();
  1125. tmc2130_init(TMCInitParams(false, FarmOrUserECool() ));
  1126. #endif //TMC2130
  1127. #ifdef PSU_Delta
  1128. init_force_z(); // ! important for correct Z-axis initialization
  1129. #endif // PSU_Delta
  1130. setup_photpin();
  1131. #if 0
  1132. servo_init();
  1133. #endif
  1134. // Reset the machine correction matrix.
  1135. // It does not make sense to load the correction matrix until the machine is homed.
  1136. world2machine_reset();
  1137. // Initialize current_position accounting for software endstops to
  1138. // avoid unexpected initial shifts on the first move
  1139. clamp_to_software_endstops(current_position);
  1140. plan_set_position_curposXYZE();
  1141. // Show the xflash error message now that serial, lcd and encoder are available
  1142. if (!xflash_success)
  1143. xflash_err_msg();
  1144. #ifdef FILAMENT_SENSOR
  1145. fsensor.init();
  1146. #endif //FILAMENT_SENSOR
  1147. #if defined(CONTROLLERFAN_PIN) && (CONTROLLERFAN_PIN > -1)
  1148. SET_OUTPUT(CONTROLLERFAN_PIN); //Set pin used for driver cooling fan
  1149. #endif
  1150. setup_homepin();
  1151. #if defined(Z_AXIS_ALWAYS_ON)
  1152. enable_z();
  1153. #endif
  1154. // The farm monitoring SW may accidentally expect
  1155. // 2 messages of "printer started" to consider a printer working.
  1156. prusa_statistics(8);
  1157. // Enable Toshiba FlashAir SD card / WiFi enahanced card.
  1158. card.ToshibaFlashAir_enable(eeprom_read_byte((unsigned char*)EEPROM_TOSHIBA_FLASH_AIR_COMPATIBLITY) == 1);
  1159. // Force SD card update. Otherwise the SD card update is done from loop() on card.checkautostart(false),
  1160. // but this times out if a blocking dialog is shown in setup().
  1161. card.initsd();
  1162. #ifdef DEBUG_SD_SPEED_TEST
  1163. if (card.cardOK)
  1164. {
  1165. uint8_t* buff = (uint8_t*)block_buffer;
  1166. uint32_t block = 0;
  1167. uint32_t sumr = 0;
  1168. uint32_t sumw = 0;
  1169. for (int i = 0; i < 1024; i++)
  1170. {
  1171. uint32_t u = _micros();
  1172. bool res = card.card.readBlock(i, buff);
  1173. u = _micros() - u;
  1174. if (res)
  1175. {
  1176. printf_P(PSTR("readBlock %4d 512 bytes %lu us\n"), i, u);
  1177. sumr += u;
  1178. u = _micros();
  1179. res = card.card.writeBlock(i, buff);
  1180. u = _micros() - u;
  1181. if (res)
  1182. {
  1183. printf_P(PSTR("writeBlock %4d 512 bytes %lu us\n"), i, u);
  1184. sumw += u;
  1185. }
  1186. else
  1187. {
  1188. printf_P(PSTR("writeBlock %4d error\n"), i);
  1189. break;
  1190. }
  1191. }
  1192. else
  1193. {
  1194. printf_P(PSTR("readBlock %4d error\n"), i);
  1195. break;
  1196. }
  1197. }
  1198. uint32_t avg_rspeed = (1024 * 1000000) / (sumr / 512);
  1199. uint32_t avg_wspeed = (1024 * 1000000) / (sumw / 512);
  1200. printf_P(PSTR("avg read speed %lu bytes/s\n"), avg_rspeed);
  1201. printf_P(PSTR("avg write speed %lu bytes/s\n"), avg_wspeed);
  1202. }
  1203. else
  1204. printf_P(PSTR("Card NG!\n"));
  1205. #endif //DEBUG_SD_SPEED_TEST
  1206. eeprom_init();
  1207. // In the future, somewhere here would one compare the current firmware version against the firmware version stored in the EEPROM.
  1208. // If they differ, an update procedure may need to be performed. At the end of this block, the current firmware version
  1209. // is being written into the EEPROM, so the update procedure will be triggered only once.
  1210. #if (LANG_MODE != 0) //secondary language support
  1211. #ifdef DEBUG_XFLASH
  1212. XFLASH_SPI_ENTER();
  1213. uint8_t uid[8]; // 64bit unique id
  1214. xflash_rd_uid(uid);
  1215. puts_P(_n("XFLASH UID="));
  1216. for (uint8_t i = 0; i < 8; i ++)
  1217. printf_P(PSTR("%02x"), uid[i]);
  1218. putchar('\n');
  1219. list_sec_lang_from_external_flash();
  1220. #endif //DEBUG_XFLASH
  1221. // lang_reset();
  1222. if (!lang_select(eeprom_read_byte((uint8_t*)EEPROM_LANG)))
  1223. lcd_language();
  1224. #ifdef DEBUG_SEC_LANG
  1225. uint16_t sec_lang_code = lang_get_code(1);
  1226. uint16_t ui = _SEC_LANG_TABLE; //table pointer
  1227. 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);
  1228. lang_print_sec_lang(uartout);
  1229. #endif //DEBUG_SEC_LANG
  1230. #endif //(LANG_MODE != 0)
  1231. if (eeprom_read_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE) == 255) {
  1232. eeprom_write_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE, 0);
  1233. }
  1234. if (eeprom_read_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA) == 255) {
  1235. //eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0);
  1236. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  1237. int16_t z_shift = 0;
  1238. for (uint8_t i = 0; i < 5; i++) {
  1239. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  1240. }
  1241. eeprom_write_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE, 0);
  1242. }
  1243. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO) == 255) {
  1244. eeprom_write_byte((uint8_t*)EEPROM_UVLO, 0);
  1245. }
  1246. if (eeprom_read_byte((uint8_t*)EEPROM_SD_SORT) == 255) {
  1247. eeprom_write_byte((uint8_t*)EEPROM_SD_SORT, 0);
  1248. }
  1249. //mbl_mode_init();
  1250. mbl_settings_init();
  1251. SilentModeMenu_MMU = eeprom_read_byte((uint8_t*)EEPROM_MMU_STEALTH);
  1252. if (SilentModeMenu_MMU == 255) {
  1253. SilentModeMenu_MMU = 1;
  1254. eeprom_write_byte((uint8_t*)EEPROM_MMU_STEALTH, SilentModeMenu_MMU);
  1255. }
  1256. #if !defined(DEBUG_DISABLE_FANCHECK) && defined(FANCHECK) && defined(TACH_1) && TACH_1 >-1
  1257. setup_fan_interrupt();
  1258. #endif //DEBUG_DISABLE_FANCHECK
  1259. #ifndef DEBUG_DISABLE_STARTMSGS
  1260. KEEPALIVE_STATE(PAUSED_FOR_USER);
  1261. if (!farm_mode) {
  1262. check_if_fw_is_on_right_printer();
  1263. show_fw_version_warnings();
  1264. }
  1265. switch (hw_changed) {
  1266. //if motherboard or printer type was changed inform user as it can indicate flashing wrong firmware version
  1267. //if user confirms with knob, new hw version (printer and/or motherboard) is written to eeprom and message will be not shown next time
  1268. case(0b01):
  1269. lcd_show_fullscreen_message_and_wait_P(_i("Warning: motherboard type changed.")); ////MSG_CHANGED_MOTHERBOARD c=20 r=4
  1270. eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  1271. break;
  1272. case(0b10):
  1273. lcd_show_fullscreen_message_and_wait_P(_i("Warning: printer type changed.")); ////MSG_CHANGED_PRINTER c=20 r=4
  1274. eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  1275. break;
  1276. case(0b11):
  1277. lcd_show_fullscreen_message_and_wait_P(_i("Warning: both printer type and motherboard type changed.")); ////MSG_CHANGED_BOTH c=20 r=4
  1278. eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  1279. eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  1280. break;
  1281. default: break; //no change, show no message
  1282. }
  1283. if (!previous_settings_retrieved) {
  1284. 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
  1285. Config_StoreSettings();
  1286. }
  1287. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) >= 1) {
  1288. lcd_wizard(WizState::Run);
  1289. }
  1290. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) == 0) { //dont show calibration status messages if wizard is currently active
  1291. if (calibration_status() == CALIBRATION_STATUS_ASSEMBLED ||
  1292. calibration_status() == CALIBRATION_STATUS_UNKNOWN ||
  1293. calibration_status() == CALIBRATION_STATUS_XYZ_CALIBRATION) {
  1294. // Reset the babystepping values, so the printer will not move the Z axis up when the babystepping is enabled.
  1295. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  1296. // Show the message.
  1297. lcd_show_fullscreen_message_and_wait_P(_T(MSG_FOLLOW_CALIBRATION_FLOW));
  1298. }
  1299. else if (calibration_status() == CALIBRATION_STATUS_LIVE_ADJUST) {
  1300. // Show the message.
  1301. lcd_show_fullscreen_message_and_wait_P(_T(MSG_BABYSTEP_Z_NOT_SET));
  1302. lcd_update_enable(true);
  1303. }
  1304. else if (calibration_status() == CALIBRATION_STATUS_CALIBRATED && eeprom_read_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE) && calibration_status_pinda() == false) {
  1305. //lcd_show_fullscreen_message_and_wait_P(_i("Temperature calibration has not been run yet"));////MSG_PINDA_NOT_CALIBRATED c=20 r=4
  1306. lcd_update_enable(true);
  1307. }
  1308. else if (calibration_status() == CALIBRATION_STATUS_Z_CALIBRATION) {
  1309. // Show the message.
  1310. lcd_show_fullscreen_message_and_wait_P(_T(MSG_FOLLOW_Z_CALIBRATION_FLOW));
  1311. }
  1312. }
  1313. #if !defined (DEBUG_DISABLE_FORCE_SELFTEST) && defined (TMC2130)
  1314. if (force_selftest_if_fw_version() && calibration_status() < CALIBRATION_STATUS_ASSEMBLED) {
  1315. lcd_show_fullscreen_message_and_wait_P(_i("Selftest will be run to calibrate accurate sensorless rehoming."));////MSG_FORCE_SELFTEST c=20 r=8
  1316. update_current_firmware_version_to_eeprom();
  1317. lcd_selftest();
  1318. }
  1319. #endif //TMC2130 && !DEBUG_DISABLE_FORCE_SELFTEST
  1320. KEEPALIVE_STATE(IN_PROCESS);
  1321. #endif //DEBUG_DISABLE_STARTMSGS
  1322. lcd_update_enable(true);
  1323. lcd_clear();
  1324. lcd_update(2);
  1325. // Store the currently running firmware into an eeprom,
  1326. // so the next time the firmware gets updated, it will know from which version it has been updated.
  1327. update_current_firmware_version_to_eeprom();
  1328. #ifdef TMC2130
  1329. tmc2130_home_origin[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_X_ORIGIN);
  1330. tmc2130_home_bsteps[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_X_BSTEPS);
  1331. tmc2130_home_fsteps[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_X_FSTEPS);
  1332. if (tmc2130_home_origin[X_AXIS] == 0xff) tmc2130_home_origin[X_AXIS] = 0;
  1333. if (tmc2130_home_bsteps[X_AXIS] == 0xff) tmc2130_home_bsteps[X_AXIS] = 48;
  1334. if (tmc2130_home_fsteps[X_AXIS] == 0xff) tmc2130_home_fsteps[X_AXIS] = 48;
  1335. tmc2130_home_origin[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_ORIGIN);
  1336. tmc2130_home_bsteps[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_BSTEPS);
  1337. tmc2130_home_fsteps[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_FSTEPS);
  1338. if (tmc2130_home_origin[Y_AXIS] == 0xff) tmc2130_home_origin[Y_AXIS] = 0;
  1339. if (tmc2130_home_bsteps[Y_AXIS] == 0xff) tmc2130_home_bsteps[Y_AXIS] = 48;
  1340. if (tmc2130_home_fsteps[Y_AXIS] == 0xff) tmc2130_home_fsteps[Y_AXIS] = 48;
  1341. tmc2130_home_enabled = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_ENABLED);
  1342. if (tmc2130_home_enabled == 0xff) tmc2130_home_enabled = 0;
  1343. #endif //TMC2130
  1344. // report crash failures
  1345. fw_crash_init();
  1346. #ifdef UVLO_SUPPORT
  1347. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO) != 0) { //previous print was terminated by UVLO
  1348. /*
  1349. if (lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_RECOVER_PRINT), false)) recover_print();
  1350. else {
  1351. eeprom_update_byte((uint8_t*)EEPROM_UVLO, 0);
  1352. lcd_update_enable(true);
  1353. lcd_update(2);
  1354. lcd_setstatuspgm(MSG_WELCOME);
  1355. }
  1356. */
  1357. manage_heater(); // Update temperatures
  1358. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1359. 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));
  1360. #endif
  1361. if ( degBed() > ( (float)eeprom_read_byte((uint8_t*)EEPROM_UVLO_TARGET_BED) - AUTOMATIC_UVLO_BED_TEMP_OFFSET) ){
  1362. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1363. puts_P(_N("Automatic recovery!"));
  1364. #endif
  1365. recover_print(1);
  1366. }
  1367. else{
  1368. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1369. puts_P(_N("Normal recovery!"));
  1370. #endif
  1371. if ( lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_RECOVER_PRINT), false) ) recover_print(0);
  1372. else {
  1373. eeprom_update_byte((uint8_t*)EEPROM_UVLO, 0);
  1374. lcd_update_enable(true);
  1375. lcd_update(2);
  1376. lcd_setstatuspgm(MSG_WELCOME);
  1377. }
  1378. }
  1379. }
  1380. // Only arm the uvlo interrupt _after_ a recovering print has been initialized and
  1381. // the entire state machine initialized.
  1382. setup_uvlo_interrupt();
  1383. #endif //UVLO_SUPPORT
  1384. fCheckModeInit();
  1385. fSetMmuMode(mmu_enabled);
  1386. KEEPALIVE_STATE(NOT_BUSY);
  1387. #ifdef WATCHDOG
  1388. wdt_enable(WDTO_4S);
  1389. #ifdef EMERGENCY_HANDLERS
  1390. WDTCSR |= (1 << WDIE);
  1391. #endif //EMERGENCY_HANDLERS
  1392. #endif //WATCHDOG
  1393. }
  1394. static inline void crash_and_burn(dump_crash_reason reason)
  1395. {
  1396. WRITE(BEEPER, HIGH);
  1397. eeprom_update_byte((uint8_t*)EEPROM_FW_CRASH_FLAG, (uint8_t)reason);
  1398. #ifdef EMERGENCY_DUMP
  1399. xfdump_full_dump_and_reset(reason);
  1400. #elif defined(EMERGENCY_SERIAL_DUMP)
  1401. if(emergency_serial_dump)
  1402. serial_dump_and_reset(reason);
  1403. #endif
  1404. softReset();
  1405. }
  1406. #ifdef EMERGENCY_HANDLERS
  1407. #ifdef WATCHDOG
  1408. ISR(WDT_vect)
  1409. {
  1410. crash_and_burn(dump_crash_reason::watchdog);
  1411. }
  1412. #endif
  1413. ISR(BADISR_vect)
  1414. {
  1415. crash_and_burn(dump_crash_reason::bad_isr);
  1416. }
  1417. #endif //EMERGENCY_HANDLERS
  1418. void stack_error() {
  1419. crash_and_burn(dump_crash_reason::stack_error);
  1420. }
  1421. /**
  1422. * Output autoreport values according to features requested in M155
  1423. */
  1424. #if defined(AUTO_REPORT)
  1425. void host_autoreport()
  1426. {
  1427. if (autoReportFeatures.TimerExpired())
  1428. {
  1429. if(autoReportFeatures.Temp()){
  1430. gcode_M105(active_extruder);
  1431. }
  1432. if(autoReportFeatures.Pos()){
  1433. gcode_M114();
  1434. }
  1435. #if defined(AUTO_REPORT) && (defined(FANCHECK) && (((defined(TACH_0) && (TACH_0 >-1)) || (defined(TACH_1) && (TACH_1 > -1)))))
  1436. if(autoReportFeatures.Fans()){
  1437. gcode_M123();
  1438. }
  1439. #endif //AUTO_REPORT and (FANCHECK and TACH_0 or TACH_1)
  1440. autoReportFeatures.TimerStart();
  1441. }
  1442. }
  1443. #endif //AUTO_REPORT
  1444. /**
  1445. * Output a "busy" message at regular intervals
  1446. * while the machine is not accepting commands.
  1447. */
  1448. void host_keepalive() {
  1449. #ifndef HOST_KEEPALIVE_FEATURE
  1450. return;
  1451. #endif //HOST_KEEPALIVE_FEATURE
  1452. if (farm_mode) return;
  1453. long ms = _millis();
  1454. if (host_keepalive_interval && busy_state != NOT_BUSY) {
  1455. if ((ms - prev_busy_signal_ms) < (long)(1000L * host_keepalive_interval)) return;
  1456. switch (busy_state) {
  1457. case IN_HANDLER:
  1458. case IN_PROCESS:
  1459. SERIAL_ECHO_START;
  1460. SERIAL_ECHOLNPGM("busy: processing");
  1461. break;
  1462. case PAUSED_FOR_USER:
  1463. SERIAL_ECHO_START;
  1464. SERIAL_ECHOLNPGM("busy: paused for user");
  1465. break;
  1466. case PAUSED_FOR_INPUT:
  1467. SERIAL_ECHO_START;
  1468. SERIAL_ECHOLNPGM("busy: paused for input");
  1469. break;
  1470. default:
  1471. break;
  1472. }
  1473. }
  1474. prev_busy_signal_ms = ms;
  1475. }
  1476. // The loop() function is called in an endless loop by the Arduino framework from the default main() routine.
  1477. // Before loop(), the setup() function is called by the main() routine.
  1478. void loop()
  1479. {
  1480. // Reset a previously aborted command, we can now start processing motion again
  1481. planner_aborted = false;
  1482. if(Stopped) {
  1483. // Currently Stopped (possibly due to an error) and not accepting new serial commands.
  1484. // Signal to the host that we're currently busy waiting for supervision.
  1485. KEEPALIVE_STATE(PAUSED_FOR_USER);
  1486. } else {
  1487. // Printer is available for processing, reset state
  1488. KEEPALIVE_STATE(NOT_BUSY);
  1489. }
  1490. if (isPrintPaused && saved_printing_type == PRINTING_TYPE_USB) { //keep believing that usb is being printed. Prevents accessing dangerous menus while pausing.
  1491. usb_timer.start();
  1492. }
  1493. else if (usb_timer.expired(10000)) { //just need to check if it expired. Nothing else is needed to be done.
  1494. ;
  1495. }
  1496. #ifdef PRUSA_M28
  1497. if (prusa_sd_card_upload)
  1498. {
  1499. //we read byte-by byte
  1500. serial_read_stream();
  1501. }
  1502. else
  1503. #endif
  1504. {
  1505. get_command();
  1506. #ifdef SDSUPPORT
  1507. card.checkautostart(false);
  1508. #endif
  1509. if(buflen)
  1510. {
  1511. cmdbuffer_front_already_processed = false;
  1512. #ifdef SDSUPPORT
  1513. if(card.saving)
  1514. {
  1515. // Saving a G-code file onto an SD-card is in progress.
  1516. // Saving starts with M28, saving until M29 is seen.
  1517. if(strstr_P(CMDBUFFER_CURRENT_STRING, PSTR("M29")) == NULL) {
  1518. card.write_command(CMDBUFFER_CURRENT_STRING);
  1519. if(card.logging)
  1520. process_commands();
  1521. else
  1522. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  1523. } else {
  1524. card.closefile();
  1525. SERIAL_PROTOCOLLNRPGM(MSG_FILE_SAVED);
  1526. }
  1527. } else {
  1528. process_commands();
  1529. }
  1530. #else
  1531. process_commands();
  1532. #endif //SDSUPPORT
  1533. if (! cmdbuffer_front_already_processed && buflen)
  1534. {
  1535. // ptr points to the start of the block currently being processed.
  1536. // The first character in the block is the block type.
  1537. char *ptr = cmdbuffer + bufindr;
  1538. if (*ptr == CMDBUFFER_CURRENT_TYPE_SDCARD) {
  1539. // To support power panic, move the lenght of the command on the SD card to a planner buffer.
  1540. union {
  1541. struct {
  1542. char lo;
  1543. char hi;
  1544. } lohi;
  1545. uint16_t value;
  1546. } sdlen;
  1547. sdlen.value = 0;
  1548. {
  1549. // This block locks the interrupts globally for 3.25 us,
  1550. // which corresponds to a maximum repeat frequency of 307.69 kHz.
  1551. // This blocking is safe in the context of a 10kHz stepper driver interrupt
  1552. // or a 115200 Bd serial line receive interrupt, which will not trigger faster than 12kHz.
  1553. cli();
  1554. // Reset the command to something, which will be ignored by the power panic routine,
  1555. // so this buffer length will not be counted twice.
  1556. *ptr ++ = CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED;
  1557. // Extract the current buffer length.
  1558. sdlen.lohi.lo = *ptr ++;
  1559. sdlen.lohi.hi = *ptr;
  1560. // and pass it to the planner queue.
  1561. planner_add_sd_length(sdlen.value);
  1562. sei();
  1563. }
  1564. }
  1565. else if((*ptr == CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR) && !IS_SD_PRINTING){
  1566. cli();
  1567. *ptr ++ = CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED;
  1568. // and one for each command to previous block in the planner queue.
  1569. planner_add_sd_length(1);
  1570. sei();
  1571. }
  1572. // Now it is safe to release the already processed command block. If interrupted by the power panic now,
  1573. // this block's SD card length will not be counted twice as its command type has been replaced
  1574. // by CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED.
  1575. cmdqueue_pop_front();
  1576. }
  1577. host_keepalive();
  1578. }
  1579. }
  1580. //check heater every n milliseconds
  1581. manage_heater();
  1582. manage_inactivity(isPrintPaused);
  1583. checkHitEndstops();
  1584. lcd_update(0);
  1585. #ifdef TMC2130
  1586. tmc2130_check_overtemp();
  1587. if (tmc2130_sg_crash)
  1588. {
  1589. uint8_t crash = tmc2130_sg_crash;
  1590. tmc2130_sg_crash = 0;
  1591. // crashdet_stop_and_save_print();
  1592. switch (crash)
  1593. {
  1594. case 1: enquecommand_P((PSTR("CRASH_DETECTEDX"))); break;
  1595. case 2: enquecommand_P((PSTR("CRASH_DETECTEDY"))); break;
  1596. case 3: enquecommand_P((PSTR("CRASH_DETECTEDXY"))); break;
  1597. }
  1598. }
  1599. #endif //TMC2130
  1600. mmu_loop();
  1601. }
  1602. #define DEFINE_PGM_READ_ANY(type, reader) \
  1603. static inline type pgm_read_any(const type *p) \
  1604. { return pgm_read_##reader##_near(p); }
  1605. DEFINE_PGM_READ_ANY(float, float);
  1606. DEFINE_PGM_READ_ANY(signed char, byte);
  1607. #define XYZ_CONSTS_FROM_CONFIG(type, array, CONFIG) \
  1608. static const PROGMEM type array##_P[3] = \
  1609. { X_##CONFIG, Y_##CONFIG, Z_##CONFIG }; \
  1610. static inline type array(uint8_t axis) \
  1611. { return pgm_read_any(&array##_P[axis]); } \
  1612. type array##_ext(uint8_t axis) \
  1613. { return pgm_read_any(&array##_P[axis]); }
  1614. XYZ_CONSTS_FROM_CONFIG(float, base_min_pos, MIN_POS);
  1615. XYZ_CONSTS_FROM_CONFIG(float, base_max_pos, MAX_POS);
  1616. XYZ_CONSTS_FROM_CONFIG(float, base_home_pos, HOME_POS);
  1617. XYZ_CONSTS_FROM_CONFIG(float, max_length, MAX_LENGTH);
  1618. XYZ_CONSTS_FROM_CONFIG(float, home_retract_mm, HOME_RETRACT_MM);
  1619. XYZ_CONSTS_FROM_CONFIG(signed char, home_dir, HOME_DIR);
  1620. static void axis_is_at_home(uint8_t axis) {
  1621. current_position[axis] = base_home_pos(axis) + cs.add_homing[axis];
  1622. min_pos[axis] = base_min_pos(axis) + cs.add_homing[axis];
  1623. max_pos[axis] = base_max_pos(axis) + cs.add_homing[axis];
  1624. }
  1625. //! @return original feedmultiply
  1626. static int setup_for_endstop_move(bool enable_endstops_now = true) {
  1627. saved_feedrate = feedrate;
  1628. int l_feedmultiply = feedmultiply;
  1629. feedmultiply = 100;
  1630. previous_millis_cmd.start();
  1631. enable_endstops(enable_endstops_now);
  1632. return l_feedmultiply;
  1633. }
  1634. //! @param original_feedmultiply feedmultiply to restore
  1635. static void clean_up_after_endstop_move(int original_feedmultiply) {
  1636. #ifdef ENDSTOPS_ONLY_FOR_HOMING
  1637. enable_endstops(false);
  1638. #endif
  1639. feedrate = saved_feedrate;
  1640. feedmultiply = original_feedmultiply;
  1641. previous_millis_cmd.start();
  1642. }
  1643. #ifdef ENABLE_AUTO_BED_LEVELING
  1644. #ifdef AUTO_BED_LEVELING_GRID
  1645. static void set_bed_level_equation_lsq(double *plane_equation_coefficients)
  1646. {
  1647. vector_3 planeNormal = vector_3(-plane_equation_coefficients[0], -plane_equation_coefficients[1], 1);
  1648. planeNormal.debug("planeNormal");
  1649. plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1650. //bedLevel.debug("bedLevel");
  1651. //plan_bed_level_matrix.debug("bed level before");
  1652. //vector_3 uncorrected_position = plan_get_position_mm();
  1653. //uncorrected_position.debug("position before");
  1654. vector_3 corrected_position = plan_get_position();
  1655. // corrected_position.debug("position after");
  1656. current_position[X_AXIS] = corrected_position.x;
  1657. current_position[Y_AXIS] = corrected_position.y;
  1658. current_position[Z_AXIS] = corrected_position.z;
  1659. // put the bed at 0 so we don't go below it.
  1660. current_position[Z_AXIS] = cs.zprobe_zoffset; // in the lsq we reach here after raising the extruder due to the loop structure
  1661. plan_set_position_curposXYZE();
  1662. }
  1663. #else // not AUTO_BED_LEVELING_GRID
  1664. static void set_bed_level_equation_3pts(float z_at_pt_1, float z_at_pt_2, float z_at_pt_3) {
  1665. plan_bed_level_matrix.set_to_identity();
  1666. vector_3 pt1 = vector_3(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, z_at_pt_1);
  1667. vector_3 pt2 = vector_3(ABL_PROBE_PT_2_X, ABL_PROBE_PT_2_Y, z_at_pt_2);
  1668. vector_3 pt3 = vector_3(ABL_PROBE_PT_3_X, ABL_PROBE_PT_3_Y, z_at_pt_3);
  1669. vector_3 from_2_to_1 = (pt1 - pt2).get_normal();
  1670. vector_3 from_2_to_3 = (pt3 - pt2).get_normal();
  1671. vector_3 planeNormal = vector_3::cross(from_2_to_1, from_2_to_3).get_normal();
  1672. planeNormal = vector_3(planeNormal.x, planeNormal.y, abs(planeNormal.z));
  1673. plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1674. vector_3 corrected_position = plan_get_position();
  1675. current_position[X_AXIS] = corrected_position.x;
  1676. current_position[Y_AXIS] = corrected_position.y;
  1677. current_position[Z_AXIS] = corrected_position.z;
  1678. // put the bed at 0 so we don't go below it.
  1679. current_position[Z_AXIS] = cs.zprobe_zoffset;
  1680. plan_set_position_curposXYZE();
  1681. }
  1682. #endif // AUTO_BED_LEVELING_GRID
  1683. static void run_z_probe() {
  1684. plan_bed_level_matrix.set_to_identity();
  1685. feedrate = homing_feedrate[Z_AXIS];
  1686. // move down until you find the bed
  1687. float zPosition = -10;
  1688. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1689. st_synchronize();
  1690. // we have to let the planner know where we are right now as it is not where we said to go.
  1691. zPosition = st_get_position_mm(Z_AXIS);
  1692. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS]);
  1693. // move up the retract distance
  1694. zPosition += home_retract_mm(Z_AXIS);
  1695. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1696. st_synchronize();
  1697. // move back down slowly to find bed
  1698. feedrate = homing_feedrate[Z_AXIS]/4;
  1699. zPosition -= home_retract_mm(Z_AXIS) * 2;
  1700. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1701. st_synchronize();
  1702. current_position[Z_AXIS] = st_get_position_mm(Z_AXIS);
  1703. // make sure the planner knows where we are as it may be a bit different than we last said to move to
  1704. plan_set_position_curposXYZE();
  1705. }
  1706. static void do_blocking_move_to(float x, float y, float z) {
  1707. float oldFeedRate = feedrate;
  1708. feedrate = homing_feedrate[Z_AXIS];
  1709. current_position[Z_AXIS] = z;
  1710. plan_buffer_line_curposXYZE(feedrate/60, active_extruder);
  1711. st_synchronize();
  1712. feedrate = XY_TRAVEL_SPEED;
  1713. current_position[X_AXIS] = x;
  1714. current_position[Y_AXIS] = y;
  1715. plan_buffer_line_curposXYZE(feedrate/60, active_extruder);
  1716. st_synchronize();
  1717. feedrate = oldFeedRate;
  1718. }
  1719. static void do_blocking_move_relative(float offset_x, float offset_y, float offset_z) {
  1720. do_blocking_move_to(current_position[X_AXIS] + offset_x, current_position[Y_AXIS] + offset_y, current_position[Z_AXIS] + offset_z);
  1721. }
  1722. /// Probe bed height at position (x,y), returns the measured z value
  1723. static float probe_pt(float x, float y, float z_before) {
  1724. // move to right place
  1725. do_blocking_move_to(current_position[X_AXIS], current_position[Y_AXIS], z_before);
  1726. do_blocking_move_to(x - X_PROBE_OFFSET_FROM_EXTRUDER, y - Y_PROBE_OFFSET_FROM_EXTRUDER, current_position[Z_AXIS]);
  1727. run_z_probe();
  1728. float measured_z = current_position[Z_AXIS];
  1729. SERIAL_PROTOCOLRPGM(_T(MSG_BED));
  1730. SERIAL_PROTOCOLPGM(" x: ");
  1731. SERIAL_PROTOCOL(x);
  1732. SERIAL_PROTOCOLPGM(" y: ");
  1733. SERIAL_PROTOCOL(y);
  1734. SERIAL_PROTOCOLPGM(" z: ");
  1735. SERIAL_PROTOCOL(measured_z);
  1736. SERIAL_PROTOCOLPGM("\n");
  1737. return measured_z;
  1738. }
  1739. #endif // #ifdef ENABLE_AUTO_BED_LEVELING
  1740. #ifdef LIN_ADVANCE
  1741. /**
  1742. * M900: Set and/or Get advance K factor
  1743. *
  1744. * K<factor> Set advance K factor
  1745. */
  1746. inline void gcode_M900() {
  1747. float newK = code_seen('K') ? code_value_float() : -2;
  1748. #ifdef LA_NOCOMPAT
  1749. if (newK >= 0 && newK < LA_K_MAX)
  1750. extruder_advance_K = newK;
  1751. else
  1752. SERIAL_ECHOLNPGM("K out of allowed range!");
  1753. #else
  1754. if (newK == 0)
  1755. {
  1756. extruder_advance_K = 0;
  1757. la10c_reset();
  1758. }
  1759. else
  1760. {
  1761. newK = la10c_value(newK);
  1762. if (newK < 0)
  1763. SERIAL_ECHOLNPGM("K out of allowed range!");
  1764. else
  1765. extruder_advance_K = newK;
  1766. }
  1767. #endif
  1768. SERIAL_ECHO_START;
  1769. SERIAL_ECHOPGM("Advance K=");
  1770. SERIAL_ECHOLN(extruder_advance_K);
  1771. }
  1772. #endif // LIN_ADVANCE
  1773. bool check_commands() {
  1774. bool end_command_found = false;
  1775. while (buflen)
  1776. {
  1777. if ((code_seen_P(PSTR("M84"))) || (code_seen_P(PSTR("M 84")))) end_command_found = true;
  1778. if (!cmdbuffer_front_already_processed)
  1779. cmdqueue_pop_front();
  1780. cmdbuffer_front_already_processed = false;
  1781. }
  1782. return end_command_found;
  1783. }
  1784. // raise_z_above: slowly raise Z to the requested height
  1785. //
  1786. // contrarily to a simple move, this function will carefully plan a move
  1787. // when the current Z position is unknown. In such cases, stallguard is
  1788. // enabled and will prevent prolonged pushing against the Z tops
  1789. void raise_z_above(float target, bool plan)
  1790. {
  1791. if (current_position[Z_AXIS] >= target)
  1792. return;
  1793. // Z needs raising
  1794. current_position[Z_AXIS] = target;
  1795. clamp_to_software_endstops(current_position);
  1796. #if defined(Z_MIN_PIN) && (Z_MIN_PIN > -1) && !defined(DEBUG_DISABLE_ZMINLIMIT)
  1797. bool z_min_endstop = (READ(Z_MIN_PIN) != Z_MIN_ENDSTOP_INVERTING);
  1798. #else
  1799. bool z_min_endstop = false;
  1800. #endif
  1801. if (axis_known_position[Z_AXIS] || z_min_endstop)
  1802. {
  1803. // current position is known or very low, it's safe to raise Z
  1804. if(plan) plan_buffer_line_curposXYZE(max_feedrate[Z_AXIS]);
  1805. return;
  1806. }
  1807. // ensure Z is powered in normal mode to overcome initial load
  1808. enable_z();
  1809. st_synchronize();
  1810. // rely on crashguard to limit damage
  1811. bool z_endstop_enabled = enable_z_endstop(true);
  1812. #ifdef TMC2130
  1813. tmc2130_home_enter(Z_AXIS_MASK);
  1814. #endif //TMC2130
  1815. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 60);
  1816. st_synchronize();
  1817. #ifdef TMC2130
  1818. if (endstop_z_hit_on_purpose())
  1819. {
  1820. // not necessarily exact, but will avoid further vertical moves
  1821. current_position[Z_AXIS] = max_pos[Z_AXIS];
  1822. plan_set_position_curposXYZE();
  1823. }
  1824. tmc2130_home_exit();
  1825. #endif //TMC2130
  1826. enable_z_endstop(z_endstop_enabled);
  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. enable_endstops(false);
  1848. current_position[Z_AXIS] = 0;
  1849. plan_set_position_curposXYZE();
  1850. set_destination_to_current();
  1851. destination[Z_AXIS] += 10 * axis_up_dir; //10mm up
  1852. feedrate = homing_feedrate[Z_AXIS] / 2;
  1853. plan_buffer_line_destinationXYZE(feedrate / 60);
  1854. st_synchronize();
  1855. enable_endstops(endstops_enabled);
  1856. if (PRINTER_TYPE == PRINTER_MK3) {
  1857. current_position[Z_AXIS] = Z_MAX_POS + 2.0;
  1858. }
  1859. else {
  1860. current_position[Z_AXIS] = Z_MAX_POS + 9.0;
  1861. }
  1862. plan_set_position_curposXYZE();
  1863. return true;
  1864. }
  1865. #endif //TMC2130
  1866. #ifdef TMC2130
  1867. static void check_Z_crash(void)
  1868. {
  1869. if (!READ(Z_TMC2130_DIAG)) { //Z crash
  1870. FORCE_HIGH_POWER_END;
  1871. current_position[Z_AXIS] = 0;
  1872. plan_set_position_curposXYZE();
  1873. current_position[Z_AXIS] += MESH_HOME_Z_SEARCH;
  1874. plan_buffer_line_curposXYZE(max_feedrate[Z_AXIS]);
  1875. st_synchronize();
  1876. kill(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  1877. }
  1878. }
  1879. #endif //TMC2130
  1880. #ifdef TMC2130
  1881. void homeaxis(uint8_t axis, uint8_t cnt, uint8_t* pstep)
  1882. #else
  1883. void homeaxis(uint8_t axis, uint8_t cnt)
  1884. #endif //TMC2130
  1885. {
  1886. bool endstops_enabled = enable_endstops(true); //RP: endstops should be allways enabled durring homing
  1887. #define HOMEAXIS_DO(LETTER) \
  1888. ((LETTER##_MIN_PIN > -1 && LETTER##_HOME_DIR==-1) || (LETTER##_MAX_PIN > -1 && LETTER##_HOME_DIR==1))
  1889. if ((axis==X_AXIS)?HOMEAXIS_DO(X):(axis==Y_AXIS)?HOMEAXIS_DO(Y):0)
  1890. {
  1891. int axis_home_dir = home_dir(axis);
  1892. feedrate = homing_feedrate[axis];
  1893. #ifdef TMC2130
  1894. tmc2130_home_enter(X_AXIS_MASK << axis);
  1895. #endif //TMC2130
  1896. // Move away a bit, so that the print head does not touch the end position,
  1897. // and the following movement to endstop has a chance to achieve the required velocity
  1898. // for the stall guard to work.
  1899. current_position[axis] = 0;
  1900. plan_set_position_curposXYZE();
  1901. set_destination_to_current();
  1902. // destination[axis] = 11.f;
  1903. destination[axis] = -3.f * axis_home_dir;
  1904. plan_buffer_line_destinationXYZE(feedrate/60);
  1905. st_synchronize();
  1906. // Move away from the possible collision with opposite endstop with the collision detection disabled.
  1907. endstops_hit_on_purpose();
  1908. enable_endstops(false);
  1909. current_position[axis] = 0;
  1910. plan_set_position_curposXYZE();
  1911. destination[axis] = 1. * axis_home_dir;
  1912. plan_buffer_line_destinationXYZE(feedrate/60);
  1913. st_synchronize();
  1914. // Now continue to move up to the left end stop with the collision detection enabled.
  1915. enable_endstops(true);
  1916. destination[axis] = 1.1 * axis_home_dir * max_length(axis);
  1917. plan_buffer_line_destinationXYZE(feedrate/60);
  1918. st_synchronize();
  1919. for (uint8_t i = 0; i < cnt; i++)
  1920. {
  1921. // Move away from the collision to a known distance from the left end stop with the collision detection disabled.
  1922. endstops_hit_on_purpose();
  1923. enable_endstops(false);
  1924. current_position[axis] = 0;
  1925. plan_set_position_curposXYZE();
  1926. destination[axis] = -10.f * axis_home_dir;
  1927. plan_buffer_line_destinationXYZE(feedrate/60);
  1928. st_synchronize();
  1929. endstops_hit_on_purpose();
  1930. // Now move left up to the collision, this time with a repeatable velocity.
  1931. enable_endstops(true);
  1932. destination[axis] = 11.f * axis_home_dir;
  1933. #ifdef TMC2130
  1934. feedrate = homing_feedrate[axis];
  1935. #else //TMC2130
  1936. feedrate = homing_feedrate[axis] / 2;
  1937. #endif //TMC2130
  1938. plan_buffer_line_destinationXYZE(feedrate/60);
  1939. st_synchronize();
  1940. #ifdef TMC2130
  1941. uint16_t mscnt = tmc2130_rd_MSCNT(axis);
  1942. if (pstep) pstep[i] = mscnt >> 4;
  1943. printf_P(PSTR("%3d step=%2d mscnt=%4d\n"), i, mscnt >> 4, mscnt);
  1944. #endif //TMC2130
  1945. }
  1946. endstops_hit_on_purpose();
  1947. enable_endstops(false);
  1948. #ifdef TMC2130
  1949. uint8_t orig = tmc2130_home_origin[axis];
  1950. uint8_t back = tmc2130_home_bsteps[axis];
  1951. if (tmc2130_home_enabled && (orig <= 63))
  1952. {
  1953. tmc2130_goto_step(axis, orig, 2, 1000, tmc2130_get_res(axis));
  1954. if (back > 0)
  1955. tmc2130_do_steps(axis, back, -axis_home_dir, 1000);
  1956. }
  1957. else
  1958. tmc2130_do_steps(axis, 8, -axis_home_dir, 1000);
  1959. tmc2130_home_exit();
  1960. #endif //TMC2130
  1961. axis_is_at_home(axis);
  1962. axis_known_position[axis] = true;
  1963. // Move from minimum
  1964. #ifdef TMC2130
  1965. float dist = - axis_home_dir * 0.01f * tmc2130_home_fsteps[axis];
  1966. #else //TMC2130
  1967. float dist = - axis_home_dir * 0.01f * 64;
  1968. #endif //TMC2130
  1969. current_position[axis] -= dist;
  1970. plan_set_position_curposXYZE();
  1971. current_position[axis] += dist;
  1972. destination[axis] = current_position[axis];
  1973. plan_buffer_line_destinationXYZE(0.5f*feedrate/60);
  1974. st_synchronize();
  1975. feedrate = 0.0;
  1976. }
  1977. else if ((axis==Z_AXIS)?HOMEAXIS_DO(Z):0)
  1978. {
  1979. #ifdef TMC2130
  1980. FORCE_HIGH_POWER_START;
  1981. #endif
  1982. int axis_home_dir = home_dir(axis);
  1983. current_position[axis] = 0;
  1984. plan_set_position_curposXYZE();
  1985. destination[axis] = 1.5 * max_length(axis) * axis_home_dir;
  1986. feedrate = homing_feedrate[axis];
  1987. plan_buffer_line_destinationXYZE(feedrate/60);
  1988. st_synchronize();
  1989. #ifdef TMC2130
  1990. check_Z_crash();
  1991. #endif //TMC2130
  1992. current_position[axis] = 0;
  1993. plan_set_position_curposXYZE();
  1994. destination[axis] = -home_retract_mm(axis) * axis_home_dir;
  1995. plan_buffer_line_destinationXYZE(feedrate/60);
  1996. st_synchronize();
  1997. destination[axis] = 2*home_retract_mm(axis) * axis_home_dir;
  1998. feedrate = homing_feedrate[axis]/2 ;
  1999. plan_buffer_line_destinationXYZE(feedrate/60);
  2000. st_synchronize();
  2001. #ifdef TMC2130
  2002. check_Z_crash();
  2003. #endif //TMC2130
  2004. axis_is_at_home(axis);
  2005. destination[axis] = current_position[axis];
  2006. feedrate = 0.0;
  2007. endstops_hit_on_purpose();
  2008. axis_known_position[axis] = true;
  2009. #ifdef TMC2130
  2010. FORCE_HIGH_POWER_END;
  2011. #endif
  2012. }
  2013. enable_endstops(endstops_enabled);
  2014. }
  2015. /**/
  2016. void home_xy()
  2017. {
  2018. set_destination_to_current();
  2019. homeaxis(X_AXIS);
  2020. homeaxis(Y_AXIS);
  2021. plan_set_position_curposXYZE();
  2022. endstops_hit_on_purpose();
  2023. }
  2024. void refresh_cmd_timeout(void)
  2025. {
  2026. previous_millis_cmd.start();
  2027. }
  2028. #ifdef FWRETRACT
  2029. void retract(bool retracting, bool swapretract = false) {
  2030. // Perform FW retraction, just if needed, but behave as if the move has never took place in
  2031. // order to keep E/Z coordinates unchanged. This is done by manipulating the internal planner
  2032. // position, which requires a sync
  2033. if(retracting && !retracted[active_extruder]) {
  2034. st_synchronize();
  2035. set_destination_to_current();
  2036. current_position[E_AXIS]+=(swapretract?retract_length_swap:cs.retract_length)*float(extrudemultiply)*0.01f;
  2037. plan_set_e_position(current_position[E_AXIS]);
  2038. float oldFeedrate = feedrate;
  2039. feedrate=cs.retract_feedrate*60;
  2040. retracted[active_extruder]=true;
  2041. prepare_move();
  2042. if(cs.retract_zlift) {
  2043. st_synchronize();
  2044. current_position[Z_AXIS]-=cs.retract_zlift;
  2045. plan_set_position_curposXYZE();
  2046. prepare_move();
  2047. }
  2048. feedrate = oldFeedrate;
  2049. } else if(!retracting && retracted[active_extruder]) {
  2050. st_synchronize();
  2051. set_destination_to_current();
  2052. float oldFeedrate = feedrate;
  2053. feedrate=cs.retract_recover_feedrate*60;
  2054. if(cs.retract_zlift) {
  2055. current_position[Z_AXIS]+=cs.retract_zlift;
  2056. plan_set_position_curposXYZE();
  2057. prepare_move();
  2058. st_synchronize();
  2059. }
  2060. current_position[E_AXIS]-=(swapretract?(retract_length_swap+retract_recover_length_swap):(cs.retract_length+cs.retract_recover_length))*float(extrudemultiply)*0.01f;
  2061. plan_set_e_position(current_position[E_AXIS]);
  2062. retracted[active_extruder]=false;
  2063. prepare_move();
  2064. feedrate = oldFeedrate;
  2065. }
  2066. } //retract
  2067. #endif //FWRETRACT
  2068. #ifdef TMC2130
  2069. void force_high_power_mode(bool start_high_power_section) {
  2070. #ifdef PSU_Delta
  2071. if (start_high_power_section == true) enable_force_z();
  2072. #endif //PSU_Delta
  2073. uint8_t silent;
  2074. silent = eeprom_read_byte((uint8_t*)EEPROM_SILENT);
  2075. if (silent == 1) {
  2076. //we are in silent mode, set to normal mode to enable crash detection
  2077. // Wait for the planner queue to drain and for the stepper timer routine to reach an idle state.
  2078. st_synchronize();
  2079. cli();
  2080. tmc2130_mode = (start_high_power_section == true) ? TMC2130_MODE_NORMAL : TMC2130_MODE_SILENT;
  2081. update_mode_profile();
  2082. tmc2130_init(TMCInitParams(FarmOrUserECool()));
  2083. // We may have missed a stepper timer interrupt due to the time spent in the tmc2130_init() routine.
  2084. // Be safe than sorry, reset the stepper timer before re-enabling interrupts.
  2085. st_reset_timer();
  2086. sei();
  2087. }
  2088. }
  2089. #endif //TMC2130
  2090. void gcode_M105(uint8_t extruder)
  2091. {
  2092. #if defined(TEMP_0_PIN) && TEMP_0_PIN > -1
  2093. SERIAL_PROTOCOLPGM("T:");
  2094. SERIAL_PROTOCOL_F(degHotend(extruder),1);
  2095. SERIAL_PROTOCOLPGM(" /");
  2096. SERIAL_PROTOCOL_F(degTargetHotend(extruder),1);
  2097. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  2098. SERIAL_PROTOCOLPGM(" B:");
  2099. SERIAL_PROTOCOL_F(degBed(),1);
  2100. SERIAL_PROTOCOLPGM(" /");
  2101. SERIAL_PROTOCOL_F(degTargetBed(),1);
  2102. #endif //TEMP_BED_PIN
  2103. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  2104. SERIAL_PROTOCOLPGM(" T");
  2105. SERIAL_PROTOCOL(cur_extruder);
  2106. SERIAL_PROTOCOL(':');
  2107. SERIAL_PROTOCOL_F(degHotend(cur_extruder),1);
  2108. SERIAL_PROTOCOLPGM(" /");
  2109. SERIAL_PROTOCOL_F(degTargetHotend(cur_extruder),1);
  2110. }
  2111. #else
  2112. SERIAL_ERROR_START;
  2113. SERIAL_ERRORLNRPGM(_n("No thermistors - no temperature"));////MSG_ERR_NO_THERMISTORS
  2114. #endif
  2115. SERIAL_PROTOCOLPGM(" @:");
  2116. #ifdef EXTRUDER_WATTS
  2117. SERIAL_PROTOCOL((EXTRUDER_WATTS * getHeaterPower(tmp_extruder))/127);
  2118. SERIAL_PROTOCOLPGM("W");
  2119. #else
  2120. SERIAL_PROTOCOL(getHeaterPower(extruder));
  2121. #endif
  2122. SERIAL_PROTOCOLPGM(" B@:");
  2123. #ifdef BED_WATTS
  2124. SERIAL_PROTOCOL((BED_WATTS * getHeaterPower(-1))/127);
  2125. SERIAL_PROTOCOLPGM("W");
  2126. #else
  2127. SERIAL_PROTOCOL(getHeaterPower(-1));
  2128. #endif
  2129. #ifdef PINDA_THERMISTOR
  2130. SERIAL_PROTOCOLPGM(" P:");
  2131. SERIAL_PROTOCOL_F(current_temperature_pinda,1);
  2132. #endif //PINDA_THERMISTOR
  2133. #ifdef AMBIENT_THERMISTOR
  2134. SERIAL_PROTOCOLPGM(" A:");
  2135. SERIAL_PROTOCOL_F(current_temperature_ambient,1);
  2136. #endif //AMBIENT_THERMISTOR
  2137. #ifdef SHOW_TEMP_ADC_VALUES
  2138. {
  2139. float raw = 0.0;
  2140. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  2141. SERIAL_PROTOCOLPGM(" ADC B:");
  2142. SERIAL_PROTOCOL_F(degBed(),1);
  2143. SERIAL_PROTOCOLPGM("C->");
  2144. raw = rawBedTemp();
  2145. SERIAL_PROTOCOL_F(raw/OVERSAMPLENR,5);
  2146. SERIAL_PROTOCOLPGM(" Rb->");
  2147. SERIAL_PROTOCOL_F(100 * (1 + (PtA * (raw/OVERSAMPLENR)) + (PtB * sq((raw/OVERSAMPLENR)))), 5);
  2148. SERIAL_PROTOCOLPGM(" Rxb->");
  2149. SERIAL_PROTOCOL_F(raw, 5);
  2150. #endif
  2151. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  2152. SERIAL_PROTOCOLPGM(" T");
  2153. SERIAL_PROTOCOL(cur_extruder);
  2154. SERIAL_PROTOCOLPGM(":");
  2155. SERIAL_PROTOCOL_F(degHotend(cur_extruder),1);
  2156. SERIAL_PROTOCOLPGM("C->");
  2157. raw = rawHotendTemp(cur_extruder);
  2158. SERIAL_PROTOCOL_F(raw/OVERSAMPLENR,5);
  2159. SERIAL_PROTOCOLPGM(" Rt");
  2160. SERIAL_PROTOCOL(cur_extruder);
  2161. SERIAL_PROTOCOLPGM("->");
  2162. SERIAL_PROTOCOL_F(100 * (1 + (PtA * (raw/OVERSAMPLENR)) + (PtB * sq((raw/OVERSAMPLENR)))), 5);
  2163. SERIAL_PROTOCOLPGM(" Rx");
  2164. SERIAL_PROTOCOL(cur_extruder);
  2165. SERIAL_PROTOCOLPGM("->");
  2166. SERIAL_PROTOCOL_F(raw, 5);
  2167. }
  2168. }
  2169. #endif
  2170. SERIAL_PROTOCOLLN();
  2171. }
  2172. #ifdef TMC2130
  2173. 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)
  2174. #else
  2175. 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)
  2176. #endif //TMC2130
  2177. {
  2178. // Flag for the display update routine and to disable the print cancelation during homing.
  2179. st_synchronize();
  2180. homing_flag = true;
  2181. #if 0
  2182. SERIAL_ECHOPGM("G28, initial "); print_world_coordinates();
  2183. SERIAL_ECHOPGM("G28, initial "); print_physical_coordinates();
  2184. #endif
  2185. // Which axes should be homed?
  2186. bool home_x = home_x_axis;
  2187. bool home_y = home_y_axis;
  2188. bool home_z = home_z_axis;
  2189. // Either all X,Y,Z codes are present, or none of them.
  2190. bool home_all_axes = home_x == home_y && home_x == home_z;
  2191. if (home_all_axes)
  2192. // No X/Y/Z code provided means to home all axes.
  2193. home_x = home_y = home_z = true;
  2194. //if we are homing all axes, first move z higher to protect heatbed/steel sheet
  2195. if (home_all_axes) {
  2196. raise_z_above(MESH_HOME_Z_SEARCH);
  2197. st_synchronize();
  2198. }
  2199. #ifdef ENABLE_AUTO_BED_LEVELING
  2200. plan_bed_level_matrix.set_to_identity(); //Reset the plane ("erase" all leveling data)
  2201. #endif //ENABLE_AUTO_BED_LEVELING
  2202. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  2203. // the planner will not perform any adjustments in the XY plane.
  2204. // Wait for the motors to stop and update the current position with the absolute values.
  2205. world2machine_revert_to_uncorrected();
  2206. // For mesh bed leveling deactivate the matrix temporarily.
  2207. // It is necessary to disable the bed leveling for the X and Y homing moves, so that the move is performed
  2208. // in a single axis only.
  2209. // In case of re-homing the X or Y axes only, the mesh bed leveling is restored after G28.
  2210. #ifdef MESH_BED_LEVELING
  2211. uint8_t mbl_was_active = mbl.active;
  2212. mbl.active = 0;
  2213. current_position[Z_AXIS] = st_get_position_mm(Z_AXIS);
  2214. #endif
  2215. // Reset baby stepping to zero, if the babystepping has already been loaded before.
  2216. if (home_z)
  2217. babystep_undo();
  2218. int l_feedmultiply = setup_for_endstop_move();
  2219. set_destination_to_current();
  2220. feedrate = 0.0;
  2221. #if Z_HOME_DIR > 0 // If homing away from BED do Z first
  2222. if(home_z)
  2223. homeaxis(Z_AXIS);
  2224. #endif
  2225. #ifdef QUICK_HOME
  2226. // In the quick mode, if both x and y are to be homed, a diagonal move will be performed initially.
  2227. if(home_x && home_y) //first diagonal move
  2228. {
  2229. current_position[X_AXIS] = 0;current_position[Y_AXIS] = 0;
  2230. uint8_t x_axis_home_dir = home_dir(X_AXIS);
  2231. plan_set_position_curposXYZE();
  2232. 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);
  2233. feedrate = homing_feedrate[X_AXIS];
  2234. if(homing_feedrate[Y_AXIS]<feedrate)
  2235. feedrate = homing_feedrate[Y_AXIS];
  2236. if (max_length(X_AXIS) > max_length(Y_AXIS)) {
  2237. feedrate *= sqrt(pow(max_length(Y_AXIS) / max_length(X_AXIS), 2) + 1);
  2238. } else {
  2239. feedrate *= sqrt(pow(max_length(X_AXIS) / max_length(Y_AXIS), 2) + 1);
  2240. }
  2241. plan_buffer_line_destinationXYZE(feedrate/60);
  2242. st_synchronize();
  2243. axis_is_at_home(X_AXIS);
  2244. axis_is_at_home(Y_AXIS);
  2245. plan_set_position_curposXYZE();
  2246. destination[X_AXIS] = current_position[X_AXIS];
  2247. destination[Y_AXIS] = current_position[Y_AXIS];
  2248. plan_buffer_line_destinationXYZE(feedrate/60);
  2249. feedrate = 0.0;
  2250. st_synchronize();
  2251. endstops_hit_on_purpose();
  2252. current_position[X_AXIS] = destination[X_AXIS];
  2253. current_position[Y_AXIS] = destination[Y_AXIS];
  2254. current_position[Z_AXIS] = destination[Z_AXIS];
  2255. }
  2256. #endif /* QUICK_HOME */
  2257. #ifdef TMC2130
  2258. if(home_x)
  2259. {
  2260. if (!calib)
  2261. homeaxis(X_AXIS);
  2262. else
  2263. tmc2130_home_calibrate(X_AXIS);
  2264. }
  2265. if(home_y)
  2266. {
  2267. if (!calib)
  2268. homeaxis(Y_AXIS);
  2269. else
  2270. tmc2130_home_calibrate(Y_AXIS);
  2271. }
  2272. #else //TMC2130
  2273. if(home_x) homeaxis(X_AXIS);
  2274. if(home_y) homeaxis(Y_AXIS);
  2275. #endif //TMC2130
  2276. if(home_x_axis && home_x_value != 0)
  2277. current_position[X_AXIS]=home_x_value+cs.add_homing[X_AXIS];
  2278. if(home_y_axis && home_y_value != 0)
  2279. current_position[Y_AXIS]=home_y_value+cs.add_homing[Y_AXIS];
  2280. #if Z_HOME_DIR < 0 // If homing towards BED do Z last
  2281. #ifndef Z_SAFE_HOMING
  2282. if(home_z) {
  2283. #if defined (Z_RAISE_BEFORE_HOMING) && (Z_RAISE_BEFORE_HOMING > 0)
  2284. raise_z_above(Z_RAISE_BEFORE_HOMING);
  2285. st_synchronize();
  2286. #endif // defined (Z_RAISE_BEFORE_HOMING) && (Z_RAISE_BEFORE_HOMING > 0)
  2287. #ifdef MESH_BED_LEVELING // If Mesh bed leveling, move X&Y to safe position for home
  2288. raise_z_above(MESH_HOME_Z_SEARCH);
  2289. st_synchronize();
  2290. if (!axis_known_position[X_AXIS]) homeaxis(X_AXIS);
  2291. if (!axis_known_position[Y_AXIS]) homeaxis(Y_AXIS);
  2292. // 1st mesh bed leveling measurement point, corrected.
  2293. world2machine_initialize();
  2294. world2machine(pgm_read_float(bed_ref_points_4), pgm_read_float(bed_ref_points_4+1), destination[X_AXIS], destination[Y_AXIS]);
  2295. world2machine_reset();
  2296. if (destination[Y_AXIS] < Y_MIN_POS)
  2297. destination[Y_AXIS] = Y_MIN_POS;
  2298. feedrate = homing_feedrate[X_AXIS] / 20;
  2299. enable_endstops(false);
  2300. #ifdef DEBUG_BUILD
  2301. SERIAL_ECHOLNPGM("plan_set_position()");
  2302. MYSERIAL.println(current_position[X_AXIS]);MYSERIAL.println(current_position[Y_AXIS]);
  2303. MYSERIAL.println(current_position[Z_AXIS]);MYSERIAL.println(current_position[E_AXIS]);
  2304. #endif
  2305. plan_set_position_curposXYZE();
  2306. #ifdef DEBUG_BUILD
  2307. SERIAL_ECHOLNPGM("plan_buffer_line()");
  2308. MYSERIAL.println(destination[X_AXIS]);MYSERIAL.println(destination[Y_AXIS]);
  2309. MYSERIAL.println(destination[Z_AXIS]);MYSERIAL.println(destination[E_AXIS]);
  2310. MYSERIAL.println(feedrate);MYSERIAL.println(active_extruder);
  2311. #endif
  2312. plan_buffer_line_destinationXYZE(feedrate);
  2313. st_synchronize();
  2314. current_position[X_AXIS] = destination[X_AXIS];
  2315. current_position[Y_AXIS] = destination[Y_AXIS];
  2316. enable_endstops(true);
  2317. endstops_hit_on_purpose();
  2318. homeaxis(Z_AXIS);
  2319. #else // MESH_BED_LEVELING
  2320. homeaxis(Z_AXIS);
  2321. #endif // MESH_BED_LEVELING
  2322. }
  2323. #else // defined(Z_SAFE_HOMING): Z Safe mode activated.
  2324. if(home_all_axes) {
  2325. destination[X_AXIS] = round(Z_SAFE_HOMING_X_POINT - X_PROBE_OFFSET_FROM_EXTRUDER);
  2326. destination[Y_AXIS] = round(Z_SAFE_HOMING_Y_POINT - Y_PROBE_OFFSET_FROM_EXTRUDER);
  2327. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  2328. feedrate = XY_TRAVEL_SPEED/60;
  2329. current_position[Z_AXIS] = 0;
  2330. plan_set_position_curposXYZE();
  2331. plan_buffer_line_destinationXYZE(feedrate);
  2332. st_synchronize();
  2333. current_position[X_AXIS] = destination[X_AXIS];
  2334. current_position[Y_AXIS] = destination[Y_AXIS];
  2335. homeaxis(Z_AXIS);
  2336. }
  2337. // Let's see if X and Y are homed and probe is inside bed area.
  2338. if(home_z) {
  2339. if ( (axis_known_position[X_AXIS]) && (axis_known_position[Y_AXIS]) \
  2340. && (current_position[X_AXIS]+X_PROBE_OFFSET_FROM_EXTRUDER >= X_MIN_POS) \
  2341. && (current_position[X_AXIS]+X_PROBE_OFFSET_FROM_EXTRUDER <= X_MAX_POS) \
  2342. && (current_position[Y_AXIS]+Y_PROBE_OFFSET_FROM_EXTRUDER >= Y_MIN_POS) \
  2343. && (current_position[Y_AXIS]+Y_PROBE_OFFSET_FROM_EXTRUDER <= Y_MAX_POS)) {
  2344. current_position[Z_AXIS] = 0;
  2345. plan_set_position_curposXYZE();
  2346. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  2347. feedrate = max_feedrate[Z_AXIS];
  2348. plan_buffer_line_destinationXYZE(feedrate);
  2349. st_synchronize();
  2350. homeaxis(Z_AXIS);
  2351. } else if (!((axis_known_position[X_AXIS]) && (axis_known_position[Y_AXIS]))) {
  2352. LCD_MESSAGERPGM(MSG_POSITION_UNKNOWN);
  2353. SERIAL_ECHO_START;
  2354. SERIAL_ECHOLNRPGM(MSG_POSITION_UNKNOWN);
  2355. } else {
  2356. LCD_MESSAGERPGM(MSG_ZPROBE_OUT);
  2357. SERIAL_ECHO_START;
  2358. SERIAL_ECHOLNRPGM(MSG_ZPROBE_OUT);
  2359. }
  2360. }
  2361. #endif // Z_SAFE_HOMING
  2362. #endif // Z_HOME_DIR < 0
  2363. if(home_z_axis && home_z_value != 0)
  2364. current_position[Z_AXIS]=home_z_value+cs.add_homing[Z_AXIS];
  2365. #ifdef ENABLE_AUTO_BED_LEVELING
  2366. if(home_z)
  2367. current_position[Z_AXIS] += cs.zprobe_zoffset; //Add Z_Probe offset (the distance is negative)
  2368. #endif
  2369. // Set the planner and stepper routine positions.
  2370. // At this point the mesh bed leveling and world2machine corrections are disabled and current_position
  2371. // contains the machine coordinates.
  2372. plan_set_position_curposXYZE();
  2373. clean_up_after_endstop_move(l_feedmultiply);
  2374. endstops_hit_on_purpose();
  2375. #ifndef MESH_BED_LEVELING
  2376. //-// Oct 2019 :: this part of code is (from) now probably un-compilable
  2377. // If MESH_BED_LEVELING is not active, then it is the original Prusa i3.
  2378. // Offer the user to load the baby step value, which has been adjusted at the previous print session.
  2379. if(card.sdprinting && eeprom_read_word((uint16_t *)EEPROM_BABYSTEP_Z))
  2380. lcd_adjust_z();
  2381. #endif
  2382. // Load the machine correction matrix
  2383. world2machine_initialize();
  2384. // and correct the current_position XY axes to match the transformed coordinate system.
  2385. world2machine_update_current();
  2386. #ifdef MESH_BED_LEVELING
  2387. if (home_x_axis || home_y_axis || without_mbl || home_z_axis)
  2388. {
  2389. if (! home_z && mbl_was_active) {
  2390. // Re-enable the mesh bed leveling if only the X and Y axes were re-homed.
  2391. mbl.active = true;
  2392. // and re-adjust the current logical Z axis with the bed leveling offset applicable at the current XY position.
  2393. current_position[Z_AXIS] -= mbl.get_z(st_get_position_mm(X_AXIS), st_get_position_mm(Y_AXIS));
  2394. }
  2395. }
  2396. #endif
  2397. prusa_statistics(20);
  2398. st_synchronize();
  2399. homing_flag = false;
  2400. #if 0
  2401. SERIAL_ECHOPGM("G28, final "); print_world_coordinates();
  2402. SERIAL_ECHOPGM("G28, final "); print_physical_coordinates();
  2403. SERIAL_ECHOPGM("G28, final "); print_mesh_bed_leveling_table();
  2404. #endif
  2405. }
  2406. static void gcode_G28(bool home_x_axis, bool home_y_axis, bool home_z_axis)
  2407. {
  2408. #ifdef TMC2130
  2409. gcode_G28(home_x_axis, 0, home_y_axis, 0, home_z_axis, 0, false, true);
  2410. #else
  2411. gcode_G28(home_x_axis, 0, home_y_axis, 0, home_z_axis, 0, true);
  2412. #endif //TMC2130
  2413. }
  2414. // G80 - Automatic mesh bed leveling
  2415. static void gcode_G80()
  2416. {
  2417. st_synchronize();
  2418. if (planner_aborted)
  2419. return;
  2420. mesh_bed_leveling_flag = true;
  2421. #ifndef PINDA_THERMISTOR
  2422. static bool run = false; // thermistor-less PINDA temperature compensation is running
  2423. #endif // ndef PINDA_THERMISTOR
  2424. #ifdef SUPPORT_VERBOSITY
  2425. int8_t verbosity_level = 0;
  2426. if (code_seen('V')) {
  2427. // Just 'V' without a number counts as V1.
  2428. char c = strchr_pointer[1];
  2429. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  2430. }
  2431. #endif //SUPPORT_VERBOSITY
  2432. // Firstly check if we know where we are
  2433. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  2434. // We don't know where we are! HOME!
  2435. // Push the commands to the front of the message queue in the reverse order!
  2436. // There shall be always enough space reserved for these commands.
  2437. repeatcommand_front(); // repeat G80 with all its parameters
  2438. enquecommand_front_P(G28W0);
  2439. return;
  2440. }
  2441. uint8_t nMeasPoints = MESH_MEAS_NUM_X_POINTS;
  2442. if (code_seen('N')) {
  2443. nMeasPoints = code_value_uint8();
  2444. if (nMeasPoints != 7) {
  2445. nMeasPoints = 3;
  2446. }
  2447. }
  2448. else {
  2449. nMeasPoints = eeprom_read_byte((uint8_t*)EEPROM_MBL_POINTS_NR);
  2450. }
  2451. uint8_t nProbeRetry = 3;
  2452. if (code_seen('R')) {
  2453. nProbeRetry = code_value_uint8();
  2454. if (nProbeRetry > 10) {
  2455. nProbeRetry = 10;
  2456. }
  2457. }
  2458. else {
  2459. nProbeRetry = eeprom_read_byte((uint8_t*)EEPROM_MBL_PROBE_NR);
  2460. }
  2461. bool magnet_elimination = (eeprom_read_byte((uint8_t*)EEPROM_MBL_MAGNET_ELIMINATION) > 0);
  2462. #ifndef PINDA_THERMISTOR
  2463. if (run == false && eeprom_read_byte((uint8_t *)EEPROM_TEMP_CAL_ACTIVE) && calibration_status_pinda() == true && target_temperature_bed >= 50)
  2464. {
  2465. temp_compensation_start();
  2466. run = true;
  2467. repeatcommand_front(); // repeat G80 with all its parameters
  2468. enquecommand_front_P(G28W0);
  2469. break;
  2470. }
  2471. run = false;
  2472. #endif //PINDA_THERMISTOR
  2473. // Save custom message state, set a new custom message state to display: Calibrating point 9.
  2474. CustomMsg custom_message_type_old = custom_message_type;
  2475. uint8_t custom_message_state_old = custom_message_state;
  2476. custom_message_type = CustomMsg::MeshBedLeveling;
  2477. custom_message_state = (nMeasPoints * nMeasPoints) + 10;
  2478. lcd_update(1);
  2479. mbl.reset(); //reset mesh bed leveling
  2480. // Reset baby stepping to zero, if the babystepping has already been loaded before.
  2481. babystep_undo();
  2482. // Cycle through all points and probe them
  2483. // First move up. During this first movement, the babystepping will be reverted.
  2484. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2485. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 60);
  2486. // The move to the first calibration point.
  2487. current_position[X_AXIS] = BED_X0;
  2488. current_position[Y_AXIS] = BED_Y0;
  2489. #ifdef SUPPORT_VERBOSITY
  2490. if (verbosity_level >= 1)
  2491. {
  2492. bool clamped = world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  2493. clamped ? SERIAL_PROTOCOLPGM("First calibration point clamped.\n") : SERIAL_PROTOCOLPGM("No clamping for first calibration point.\n");
  2494. }
  2495. #else //SUPPORT_VERBOSITY
  2496. world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  2497. #endif //SUPPORT_VERBOSITY
  2498. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  2499. plan_buffer_line_curposXYZE(XY_AXIS_FEEDRATE);
  2500. // Wait until the move is finished.
  2501. st_synchronize();
  2502. if (planner_aborted)
  2503. {
  2504. custom_message_type = custom_message_type_old;
  2505. custom_message_state = custom_message_state_old;
  2506. return;
  2507. }
  2508. uint8_t mesh_point = 0; //index number of calibration point
  2509. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  2510. 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)
  2511. #ifdef SUPPORT_VERBOSITY
  2512. if (verbosity_level >= 1) {
  2513. has_z ? SERIAL_PROTOCOLPGM("Z jitter data from Z cal. valid.\n") : SERIAL_PROTOCOLPGM("Z jitter data from Z cal. not valid.\n");
  2514. }
  2515. #endif // SUPPORT_VERBOSITY
  2516. int l_feedmultiply = setup_for_endstop_move(false); //save feedrate and feedmultiply, sets feedmultiply to 100
  2517. while (mesh_point != nMeasPoints * nMeasPoints) {
  2518. // Get coords of a measuring point.
  2519. uint8_t ix = mesh_point % nMeasPoints; // from 0 to MESH_NUM_X_POINTS - 1
  2520. uint8_t iy = mesh_point / nMeasPoints;
  2521. /*if (!mbl_point_measurement_valid(ix, iy, nMeasPoints, true)) {
  2522. printf_P(PSTR("Skipping point [%d;%d] \n"), ix, iy);
  2523. custom_message_state--;
  2524. mesh_point++;
  2525. continue; //skip
  2526. }*/
  2527. if (iy & 1) ix = (nMeasPoints - 1) - ix; // Zig zag
  2528. if (nMeasPoints == 7) //if we have 7x7 mesh, compare with Z-calibration for points which are in 3x3 mesh
  2529. {
  2530. has_z = ((ix % 3 == 0) && (iy % 3 == 0)) && is_bed_z_jitter_data_valid();
  2531. }
  2532. float z0 = 0.f;
  2533. if (has_z && (mesh_point > 0)) {
  2534. uint16_t z_offset_u = 0;
  2535. if (nMeasPoints == 7) {
  2536. z_offset_u = eeprom_read_word((uint16_t*)(EEPROM_BED_CALIBRATION_Z_JITTER + 2 * ((ix/3) + iy - 1)));
  2537. }
  2538. else {
  2539. z_offset_u = eeprom_read_word((uint16_t*)(EEPROM_BED_CALIBRATION_Z_JITTER + 2 * (ix + iy * 3 - 1)));
  2540. }
  2541. z0 = mbl.z_values[0][0] + *reinterpret_cast<int16_t*>(&z_offset_u) * 0.01;
  2542. #ifdef SUPPORT_VERBOSITY
  2543. if (verbosity_level >= 1) {
  2544. printf_P(PSTR("Bed leveling, point: %d, calibration Z stored in eeprom: %d, calibration z: %f \n"), mesh_point, z_offset_u, z0);
  2545. }
  2546. #endif // SUPPORT_VERBOSITY
  2547. }
  2548. // Move Z up to MESH_HOME_Z_SEARCH.
  2549. if((ix == 0) && (iy == 0)) current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2550. else current_position[Z_AXIS] += 2.f / nMeasPoints; //use relative movement from Z coordinate where PINDa triggered on previous point. This makes calibration faster.
  2551. float init_z_bckp = current_position[Z_AXIS];
  2552. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  2553. st_synchronize();
  2554. // Move to XY position of the sensor point.
  2555. current_position[X_AXIS] = BED_X(ix, nMeasPoints);
  2556. current_position[Y_AXIS] = BED_Y(iy, nMeasPoints);
  2557. //printf_P(PSTR("[%f;%f]\n"), current_position[X_AXIS], current_position[Y_AXIS]);
  2558. #ifdef SUPPORT_VERBOSITY
  2559. if (verbosity_level >= 1) {
  2560. bool clamped = world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  2561. SERIAL_PROTOCOL(mesh_point);
  2562. clamped ? SERIAL_PROTOCOLPGM(": xy clamped.\n") : SERIAL_PROTOCOLPGM(": no xy clamping\n");
  2563. }
  2564. #else //SUPPORT_VERBOSITY
  2565. world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  2566. #endif // SUPPORT_VERBOSITY
  2567. //printf_P(PSTR("after clamping: [%f;%f]\n"), current_position[X_AXIS], current_position[Y_AXIS]);
  2568. plan_buffer_line_curposXYZE(XY_AXIS_FEEDRATE);
  2569. st_synchronize();
  2570. if (planner_aborted)
  2571. {
  2572. custom_message_type = custom_message_type_old;
  2573. custom_message_state = custom_message_state_old;
  2574. return;
  2575. }
  2576. // Go down until endstop is hit
  2577. const float Z_CALIBRATION_THRESHOLD = 1.f;
  2578. 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
  2579. printf_P(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  2580. break;
  2581. }
  2582. 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.
  2583. //printf_P(PSTR("Another attempt! Current Z position: %f\n"), current_position[Z_AXIS]);
  2584. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2585. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  2586. st_synchronize();
  2587. 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
  2588. printf_P(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  2589. break;
  2590. }
  2591. if (MESH_HOME_Z_SEARCH - current_position[Z_AXIS] < 0.1f) {
  2592. puts_P(PSTR("Bed leveling failed. Sensor disconnected or cable broken."));
  2593. break;
  2594. }
  2595. }
  2596. 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
  2597. puts_P(PSTR("Bed leveling failed. Sensor triggered too high."));
  2598. break;
  2599. }
  2600. #ifdef SUPPORT_VERBOSITY
  2601. if (verbosity_level >= 10) {
  2602. SERIAL_ECHOPGM("X: ");
  2603. MYSERIAL.print(current_position[X_AXIS], 5);
  2604. SERIAL_ECHOLNPGM("");
  2605. SERIAL_ECHOPGM("Y: ");
  2606. MYSERIAL.print(current_position[Y_AXIS], 5);
  2607. SERIAL_PROTOCOLPGM("\n");
  2608. }
  2609. #endif // SUPPORT_VERBOSITY
  2610. float offset_z = 0;
  2611. #ifdef PINDA_THERMISTOR
  2612. offset_z = temp_compensation_pinda_thermistor_offset(current_temperature_pinda);
  2613. #endif //PINDA_THERMISTOR
  2614. // #ifdef SUPPORT_VERBOSITY
  2615. /* if (verbosity_level >= 1)
  2616. {
  2617. SERIAL_ECHOPGM("mesh bed leveling: ");
  2618. MYSERIAL.print(current_position[Z_AXIS], 5);
  2619. SERIAL_ECHOPGM(" offset: ");
  2620. MYSERIAL.print(offset_z, 5);
  2621. SERIAL_ECHOLNPGM("");
  2622. }*/
  2623. // #endif // SUPPORT_VERBOSITY
  2624. mbl.set_z(ix, iy, current_position[Z_AXIS] - offset_z); //store measured z values z_values[iy][ix] = z - offset_z;
  2625. custom_message_state--;
  2626. mesh_point++;
  2627. lcd_update(1);
  2628. }
  2629. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2630. #ifdef SUPPORT_VERBOSITY
  2631. if (verbosity_level >= 20) {
  2632. SERIAL_ECHOLNPGM("Mesh bed leveling while loop finished.");
  2633. SERIAL_ECHOLNPGM("MESH_HOME_Z_SEARCH: ");
  2634. MYSERIAL.print(current_position[Z_AXIS], 5);
  2635. }
  2636. #endif // SUPPORT_VERBOSITY
  2637. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  2638. st_synchronize();
  2639. if (mesh_point != nMeasPoints * nMeasPoints) {
  2640. Sound_MakeSound(e_SOUND_TYPE_StandardAlert);
  2641. bool bState;
  2642. do { // repeat until Z-leveling o.k.
  2643. lcd_display_message_fullscreen_P(_i("Some problem encountered, Z-leveling enforced ...")); ////MSG_ZLEVELING_ENFORCED c=20 r=4
  2644. #ifdef TMC2130
  2645. lcd_wait_for_click_delay(MSG_BED_LEVELING_FAILED_TIMEOUT);
  2646. calibrate_z_auto(); // Z-leveling (X-assembly stay up!!!)
  2647. #else // TMC2130
  2648. lcd_wait_for_click_delay(0); // ~ no timeout
  2649. lcd_calibrate_z_end_stop_manual(true); // Z-leveling (X-assembly stay up!!!)
  2650. #endif // TMC2130
  2651. // ~ Z-homing (can not be used "G28", because X & Y-homing would have been done before (Z-homing))
  2652. bState=enable_z_endstop(false);
  2653. current_position[Z_AXIS] -= 1;
  2654. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2655. st_synchronize();
  2656. enable_z_endstop(true);
  2657. #ifdef TMC2130
  2658. tmc2130_home_enter(Z_AXIS_MASK);
  2659. #endif // TMC2130
  2660. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2661. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2662. st_synchronize();
  2663. #ifdef TMC2130
  2664. tmc2130_home_exit();
  2665. #endif // TMC2130
  2666. enable_z_endstop(bState);
  2667. } while (st_get_position_mm(Z_AXIS) > MESH_HOME_Z_SEARCH); // i.e. Z-leveling not o.k.
  2668. // plan_set_z_position(MESH_HOME_Z_SEARCH); // is not necessary ('do-while' loop always ends at the expected Z-position)
  2669. custom_message_type = custom_message_type_old;
  2670. custom_message_state = custom_message_state_old;
  2671. lcd_update_enable(true); // display / status-line recovery
  2672. gcode_G28(true, true, true); // X & Y & Z-homing (must be after individual Z-homing (problem with spool-holder)!)
  2673. repeatcommand_front(); // re-run (i.e. of "G80")
  2674. return;
  2675. }
  2676. clean_up_after_endstop_move(l_feedmultiply);
  2677. // SERIAL_ECHOLNPGM("clean up finished ");
  2678. #ifndef PINDA_THERMISTOR
  2679. if(eeprom_read_byte((uint8_t *)EEPROM_TEMP_CAL_ACTIVE) && calibration_status_pinda() == true) temp_compensation_apply(); //apply PINDA temperature compensation
  2680. #endif
  2681. babystep_apply(); // Apply Z height correction aka baby stepping before mesh bed leveing gets activated.
  2682. // SERIAL_ECHOLNPGM("babystep applied");
  2683. bool eeprom_bed_correction_valid = eeprom_read_byte((unsigned char*)EEPROM_BED_CORRECTION_VALID) == 1;
  2684. #ifdef SUPPORT_VERBOSITY
  2685. if (verbosity_level >= 1) {
  2686. eeprom_bed_correction_valid ? SERIAL_PROTOCOLPGM("Bed correction data valid\n") : SERIAL_PROTOCOLPGM("Bed correction data not valid\n");
  2687. }
  2688. #endif // SUPPORT_VERBOSITY
  2689. for (uint8_t i = 0; i < 4; ++i) {
  2690. unsigned char codes[4] = { 'L', 'R', 'F', 'B' };
  2691. long correction = 0;
  2692. if (code_seen(codes[i]))
  2693. correction = code_value_long();
  2694. else if (eeprom_bed_correction_valid) {
  2695. unsigned char *addr = (i < 2) ?
  2696. ((i == 0) ? (unsigned char*)EEPROM_BED_CORRECTION_LEFT : (unsigned char*)EEPROM_BED_CORRECTION_RIGHT) :
  2697. ((i == 2) ? (unsigned char*)EEPROM_BED_CORRECTION_FRONT : (unsigned char*)EEPROM_BED_CORRECTION_REAR);
  2698. correction = eeprom_read_int8(addr);
  2699. }
  2700. if (correction == 0)
  2701. continue;
  2702. if (labs(correction) > BED_ADJUSTMENT_UM_MAX) {
  2703. SERIAL_ERROR_START;
  2704. SERIAL_ECHOPGM("Excessive bed leveling correction: ");
  2705. SERIAL_ECHO(correction);
  2706. SERIAL_ECHOLNPGM(" microns");
  2707. }
  2708. else {
  2709. float offset = float(correction) * 0.001f;
  2710. switch (i) {
  2711. case 0:
  2712. for (uint8_t row = 0; row < nMeasPoints; ++row) {
  2713. for (uint8_t col = 0; col < nMeasPoints - 1; ++col) {
  2714. mbl.z_values[row][col] += offset * (nMeasPoints - 1 - col) / (nMeasPoints - 1);
  2715. }
  2716. }
  2717. break;
  2718. case 1:
  2719. for (uint8_t row = 0; row < nMeasPoints; ++row) {
  2720. for (uint8_t col = 1; col < nMeasPoints; ++col) {
  2721. mbl.z_values[row][col] += offset * col / (nMeasPoints - 1);
  2722. }
  2723. }
  2724. break;
  2725. case 2:
  2726. for (uint8_t col = 0; col < nMeasPoints; ++col) {
  2727. for (uint8_t row = 0; row < nMeasPoints; ++row) {
  2728. mbl.z_values[row][col] += offset * (nMeasPoints - 1 - row) / (nMeasPoints - 1);
  2729. }
  2730. }
  2731. break;
  2732. case 3:
  2733. for (uint8_t col = 0; col < nMeasPoints; ++col) {
  2734. for (uint8_t row = 1; row < nMeasPoints; ++row) {
  2735. mbl.z_values[row][col] += offset * row / (nMeasPoints - 1);
  2736. }
  2737. }
  2738. break;
  2739. }
  2740. }
  2741. }
  2742. // SERIAL_ECHOLNPGM("Bed leveling correction finished");
  2743. if (nMeasPoints == 3) {
  2744. 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)
  2745. }
  2746. /*
  2747. SERIAL_PROTOCOLPGM("Num X,Y: ");
  2748. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  2749. SERIAL_PROTOCOLPGM(",");
  2750. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  2751. SERIAL_PROTOCOLPGM("\nZ search height: ");
  2752. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  2753. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  2754. for (int y = MESH_NUM_Y_POINTS-1; y >= 0; y--) {
  2755. for (int x = 0; x < MESH_NUM_X_POINTS; x++) {
  2756. SERIAL_PROTOCOLPGM(" ");
  2757. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  2758. }
  2759. SERIAL_PROTOCOLPGM("\n");
  2760. }
  2761. */
  2762. if (nMeasPoints == 7 && magnet_elimination) {
  2763. mbl_interpolation(nMeasPoints);
  2764. }
  2765. /*
  2766. SERIAL_PROTOCOLPGM("Num X,Y: ");
  2767. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  2768. SERIAL_PROTOCOLPGM(",");
  2769. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  2770. SERIAL_PROTOCOLPGM("\nZ search height: ");
  2771. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  2772. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  2773. for (int y = MESH_NUM_Y_POINTS-1; y >= 0; y--) {
  2774. for (int x = 0; x < MESH_NUM_X_POINTS; x++) {
  2775. SERIAL_PROTOCOLPGM(" ");
  2776. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  2777. }
  2778. SERIAL_PROTOCOLPGM("\n");
  2779. }
  2780. */
  2781. // SERIAL_ECHOLNPGM("Upsample finished");
  2782. mbl.active = 1; //activate mesh bed leveling
  2783. // SERIAL_ECHOLNPGM("Mesh bed leveling activated");
  2784. go_home_with_z_lift();
  2785. // SERIAL_ECHOLNPGM("Go home finished");
  2786. //unretract (after PINDA preheat retraction)
  2787. if (((int)degHotend(active_extruder) > extrude_min_temp) && eeprom_read_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE) && calibration_status_pinda() && (target_temperature_bed >= 50)) {
  2788. current_position[E_AXIS] += default_retraction;
  2789. plan_buffer_line_curposXYZE(400);
  2790. }
  2791. KEEPALIVE_STATE(NOT_BUSY);
  2792. // Restore custom message state
  2793. lcd_setstatuspgm(MSG_WELCOME);
  2794. custom_message_type = custom_message_type_old;
  2795. custom_message_state = custom_message_state_old;
  2796. lcd_update(2);
  2797. st_synchronize();
  2798. mesh_bed_leveling_flag = false;
  2799. }
  2800. void adjust_bed_reset()
  2801. {
  2802. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_VALID, 1);
  2803. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_LEFT, 0);
  2804. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_RIGHT, 0);
  2805. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_FRONT, 0);
  2806. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_REAR, 0);
  2807. }
  2808. //! @brief Calibrate XYZ
  2809. //! @param onlyZ if true, calibrate only Z axis
  2810. //! @param verbosity_level
  2811. //! @retval true Succeeded
  2812. //! @retval false Failed
  2813. bool gcode_M45(bool onlyZ, int8_t verbosity_level)
  2814. {
  2815. bool final_result = false;
  2816. #ifdef TMC2130
  2817. FORCE_HIGH_POWER_START;
  2818. #endif // TMC2130
  2819. FORCE_BL_ON_START;
  2820. // Only Z calibration?
  2821. if (!onlyZ)
  2822. {
  2823. setTargetBed(0);
  2824. setAllTargetHotends(0);
  2825. adjust_bed_reset(); //reset bed level correction
  2826. }
  2827. // Disable the default update procedure of the display. We will do a modal dialog.
  2828. lcd_update_enable(false);
  2829. // Let the planner use the uncorrected coordinates.
  2830. mbl.reset();
  2831. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  2832. // the planner will not perform any adjustments in the XY plane.
  2833. // Wait for the motors to stop and update the current position with the absolute values.
  2834. world2machine_revert_to_uncorrected();
  2835. // Reset the baby step value applied without moving the axes.
  2836. babystep_reset();
  2837. // Mark all axes as in a need for homing.
  2838. memset(axis_known_position, 0, sizeof(axis_known_position));
  2839. // Home in the XY plane.
  2840. //set_destination_to_current();
  2841. int l_feedmultiply = setup_for_endstop_move();
  2842. lcd_display_message_fullscreen_P(_T(MSG_AUTO_HOME));
  2843. raise_z_above(MESH_HOME_Z_SEARCH);
  2844. st_synchronize();
  2845. home_xy();
  2846. enable_endstops(false);
  2847. current_position[X_AXIS] += 5;
  2848. current_position[Y_AXIS] += 5;
  2849. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2850. st_synchronize();
  2851. // Let the user move the Z axes up to the end stoppers.
  2852. #ifdef TMC2130
  2853. if (calibrate_z_auto())
  2854. {
  2855. #else //TMC2130
  2856. if (lcd_calibrate_z_end_stop_manual(onlyZ))
  2857. {
  2858. #endif //TMC2130
  2859. lcd_show_fullscreen_message_and_wait_P(_T(MSG_CONFIRM_NOZZLE_CLEAN));
  2860. if(onlyZ){
  2861. lcd_display_message_fullscreen_P(_T(MSG_MEASURE_BED_REFERENCE_HEIGHT_LINE1));
  2862. lcd_puts_at_P(0,3,_n("1/9"));
  2863. }else{
  2864. //lcd_show_fullscreen_message_and_wait_P(_T(MSG_PAPER));
  2865. lcd_display_message_fullscreen_P(_T(MSG_FIND_BED_OFFSET_AND_SKEW_LINE1));
  2866. lcd_puts_at_P(0,3,_n("1/4"));
  2867. }
  2868. refresh_cmd_timeout();
  2869. #ifndef STEEL_SHEET
  2870. if (((degHotend(0) > MAX_HOTEND_TEMP_CALIBRATION) || (degBed() > MAX_BED_TEMP_CALIBRATION)) && (!onlyZ))
  2871. {
  2872. lcd_wait_for_cool_down();
  2873. }
  2874. #endif //STEEL_SHEET
  2875. if(!onlyZ)
  2876. {
  2877. KEEPALIVE_STATE(PAUSED_FOR_USER);
  2878. #ifdef STEEL_SHEET
  2879. bool result = lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_STEEL_SHEET_CHECK), false, false);
  2880. if(result) lcd_show_fullscreen_message_and_wait_P(_T(MSG_REMOVE_STEEL_SHEET));
  2881. #endif //STEEL_SHEET
  2882. lcd_show_fullscreen_message_and_wait_P(_T(MSG_PAPER));
  2883. KEEPALIVE_STATE(IN_HANDLER);
  2884. lcd_display_message_fullscreen_P(_T(MSG_FIND_BED_OFFSET_AND_SKEW_LINE1));
  2885. lcd_puts_at_P(0,3,_n("1/4"));
  2886. }
  2887. bool endstops_enabled = enable_endstops(false);
  2888. current_position[Z_AXIS] -= 1; //move 1mm down with disabled endstop
  2889. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2890. st_synchronize();
  2891. // Move the print head close to the bed.
  2892. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2893. enable_endstops(true);
  2894. #ifdef TMC2130
  2895. tmc2130_home_enter(Z_AXIS_MASK);
  2896. #endif //TMC2130
  2897. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2898. st_synchronize();
  2899. #ifdef TMC2130
  2900. tmc2130_home_exit();
  2901. #endif //TMC2130
  2902. enable_endstops(endstops_enabled);
  2903. if ((st_get_position_mm(Z_AXIS) <= (MESH_HOME_Z_SEARCH + HOME_Z_SEARCH_THRESHOLD)) &&
  2904. (st_get_position_mm(Z_AXIS) >= (MESH_HOME_Z_SEARCH - HOME_Z_SEARCH_THRESHOLD)))
  2905. {
  2906. if (onlyZ)
  2907. {
  2908. clean_up_after_endstop_move(l_feedmultiply);
  2909. // Z only calibration.
  2910. // Load the machine correction matrix
  2911. world2machine_initialize();
  2912. // and correct the current_position to match the transformed coordinate system.
  2913. world2machine_update_current();
  2914. //FIXME
  2915. bool result = sample_mesh_and_store_reference();
  2916. if (result)
  2917. {
  2918. if (calibration_status() == CALIBRATION_STATUS_Z_CALIBRATION)
  2919. {
  2920. // Shipped, the nozzle height has been set already. The user can start printing now.
  2921. calibration_status_store(CALIBRATION_STATUS_CALIBRATED);
  2922. }
  2923. final_result = true;
  2924. // babystep_apply();
  2925. }
  2926. }
  2927. else
  2928. {
  2929. // Reset the baby step value and the baby step applied flag.
  2930. calibration_status_store(CALIBRATION_STATUS_XYZ_CALIBRATION);
  2931. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  2932. // Complete XYZ calibration.
  2933. uint8_t point_too_far_mask = 0;
  2934. BedSkewOffsetDetectionResultType result = find_bed_offset_and_skew(verbosity_level, point_too_far_mask);
  2935. clean_up_after_endstop_move(l_feedmultiply);
  2936. // Print head up.
  2937. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2938. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2939. st_synchronize();
  2940. //#ifndef NEW_XYZCAL
  2941. if (result >= 0)
  2942. {
  2943. #ifdef HEATBED_V2
  2944. sample_z();
  2945. #else //HEATBED_V2
  2946. point_too_far_mask = 0;
  2947. // Second half: The fine adjustment.
  2948. // Let the planner use the uncorrected coordinates.
  2949. mbl.reset();
  2950. world2machine_reset();
  2951. // Home in the XY plane.
  2952. int l_feedmultiply = setup_for_endstop_move();
  2953. home_xy();
  2954. result = improve_bed_offset_and_skew(1, verbosity_level, point_too_far_mask);
  2955. clean_up_after_endstop_move(l_feedmultiply);
  2956. // Print head up.
  2957. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2958. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 40);
  2959. st_synchronize();
  2960. // if (result >= 0) babystep_apply();
  2961. #endif //HEATBED_V2
  2962. }
  2963. //#endif //NEW_XYZCAL
  2964. lcd_update_enable(true);
  2965. lcd_update(2);
  2966. lcd_bed_calibration_show_result(result, point_too_far_mask);
  2967. if (result >= 0)
  2968. {
  2969. // Calibration valid, the machine should be able to print. Advise the user to run the V2Calibration.gcode.
  2970. calibration_status_store(CALIBRATION_STATUS_LIVE_ADJUST);
  2971. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) != 1) lcd_show_fullscreen_message_and_wait_P(_T(MSG_BABYSTEP_Z_NOT_SET));
  2972. final_result = true;
  2973. }
  2974. }
  2975. #ifdef TMC2130
  2976. tmc2130_home_exit();
  2977. #endif
  2978. }
  2979. else
  2980. {
  2981. lcd_show_fullscreen_message_and_wait_P(PSTR("Calibration failed! Check the axes and run again."));
  2982. final_result = false;
  2983. }
  2984. }
  2985. else
  2986. {
  2987. // Timeouted.
  2988. }
  2989. lcd_update_enable(true);
  2990. #ifdef TMC2130
  2991. FORCE_HIGH_POWER_END;
  2992. #endif // TMC2130
  2993. FORCE_BL_ON_END;
  2994. return final_result;
  2995. }
  2996. void gcode_M114()
  2997. {
  2998. SERIAL_PROTOCOLPGM("X:");
  2999. SERIAL_PROTOCOL(current_position[X_AXIS]);
  3000. SERIAL_PROTOCOLPGM(" Y:");
  3001. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  3002. SERIAL_PROTOCOLPGM(" Z:");
  3003. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  3004. SERIAL_PROTOCOLPGM(" E:");
  3005. SERIAL_PROTOCOL(current_position[E_AXIS]);
  3006. SERIAL_PROTOCOLRPGM(_n(" Count X: "));////MSG_COUNT_X
  3007. SERIAL_PROTOCOL(float(st_get_position(X_AXIS)) / cs.axis_steps_per_unit[X_AXIS]);
  3008. SERIAL_PROTOCOLPGM(" Y:");
  3009. SERIAL_PROTOCOL(float(st_get_position(Y_AXIS)) / cs.axis_steps_per_unit[Y_AXIS]);
  3010. SERIAL_PROTOCOLPGM(" Z:");
  3011. SERIAL_PROTOCOL(float(st_get_position(Z_AXIS)) / cs.axis_steps_per_unit[Z_AXIS]);
  3012. SERIAL_PROTOCOLPGM(" E:");
  3013. SERIAL_PROTOCOLLN(float(st_get_position(E_AXIS)) / cs.axis_steps_per_unit[E_AXIS]);
  3014. }
  3015. #if (defined(FANCHECK) && (((defined(TACH_0) && (TACH_0 >-1)) || (defined(TACH_1) && (TACH_1 > -1)))))
  3016. void gcode_M123()
  3017. {
  3018. 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);
  3019. }
  3020. #endif //FANCHECK and TACH_0 or TACH_1
  3021. //! extracted code to compute z_shift for M600 in case of filament change operation
  3022. //! requested from fsensors.
  3023. //! The function ensures, that the printhead lifts to at least 25mm above the heat bed
  3024. //! unlike the previous implementation, which was adding 25mm even when the head was
  3025. //! printing at e.g. 24mm height.
  3026. //! A safety margin of FILAMENTCHANGE_ZADD is added in all cases to avoid touching
  3027. //! the printout.
  3028. //! This function is templated to enable fast change of computation data type.
  3029. //! @return new z_shift value
  3030. template<typename T>
  3031. static T gcode_M600_filament_change_z_shift()
  3032. {
  3033. #ifdef FILAMENTCHANGE_ZADD
  3034. static_assert(Z_MAX_POS < (255 - FILAMENTCHANGE_ZADD), "Z-range too high, change the T type from uint8_t to uint16_t");
  3035. // avoid floating point arithmetics when not necessary - results in shorter code
  3036. T z_shift = T(FILAMENTCHANGE_ZADD); // always move above printout
  3037. T ztmp = T( current_position[Z_AXIS] );
  3038. if((ztmp + z_shift) < T(MIN_Z_FOR_SWAP)){
  3039. z_shift = T(MIN_Z_FOR_SWAP) - ztmp; // make sure to be at least 25mm above the heat bed
  3040. }
  3041. return z_shift;
  3042. #else
  3043. return T(0);
  3044. #endif
  3045. }
  3046. static void gcode_M600(bool automatic, float x_position, float y_position, float z_shift, float e_shift, float /*e_shift_late*/)
  3047. {
  3048. st_synchronize();
  3049. float lastpos[4];
  3050. prusa_statistics(22);
  3051. //First backup current position and settings
  3052. int feedmultiplyBckp = feedmultiply;
  3053. float HotendTempBckp = degTargetHotend(active_extruder);
  3054. int fanSpeedBckp = fanSpeed;
  3055. lastpos[X_AXIS] = current_position[X_AXIS];
  3056. lastpos[Y_AXIS] = current_position[Y_AXIS];
  3057. lastpos[Z_AXIS] = current_position[Z_AXIS];
  3058. lastpos[E_AXIS] = current_position[E_AXIS];
  3059. //Retract E
  3060. current_position[E_AXIS] += e_shift;
  3061. plan_buffer_line_curposXYZE(FILAMENTCHANGE_RFEED);
  3062. st_synchronize();
  3063. //Lift Z
  3064. current_position[Z_AXIS] += z_shift;
  3065. clamp_to_software_endstops(current_position);
  3066. plan_buffer_line_curposXYZE(FILAMENTCHANGE_ZFEED);
  3067. st_synchronize();
  3068. //Move XY to side
  3069. current_position[X_AXIS] = x_position;
  3070. current_position[Y_AXIS] = y_position;
  3071. plan_buffer_line_curposXYZE(FILAMENTCHANGE_XYFEED);
  3072. st_synchronize();
  3073. //Beep, manage nozzle heater and wait for user to start unload filament
  3074. if(!mmu_enabled) M600_wait_for_user(HotendTempBckp);
  3075. lcd_change_fil_state = 0;
  3076. // Unload filament
  3077. if (mmu_enabled) extr_unload(); //unload just current filament for multimaterial printers (used also in M702)
  3078. else unload_filament(true); //unload filament for single material (used also in M702)
  3079. //finish moves
  3080. st_synchronize();
  3081. if (!mmu_enabled)
  3082. {
  3083. KEEPALIVE_STATE(PAUSED_FOR_USER);
  3084. lcd_change_fil_state = lcd_show_fullscreen_message_yes_no_and_wait_P(
  3085. _i("Was filament unload successful?"), ////MSG_UNLOAD_SUCCESSFUL c=20 r=2
  3086. false, true);
  3087. if (lcd_change_fil_state == 0)
  3088. {
  3089. lcd_clear();
  3090. lcd_puts_at_P(0, 2, _T(MSG_PLEASE_WAIT));
  3091. current_position[X_AXIS] -= 100;
  3092. plan_buffer_line_curposXYZE(FILAMENTCHANGE_XYFEED);
  3093. st_synchronize();
  3094. lcd_show_fullscreen_message_and_wait_P(_i("Please open idler and remove filament manually."));////MSG_CHECK_IDLER c=20 r=5
  3095. }
  3096. }
  3097. if (mmu_enabled)
  3098. {
  3099. if (!automatic) {
  3100. if (saved_printing) mmu_eject_filament(mmu_extruder, false); //if M600 was invoked by filament senzor (FINDA) eject filament so user can easily remove it
  3101. mmu_M600_wait_and_beep();
  3102. if (saved_printing) {
  3103. lcd_clear();
  3104. lcd_puts_at_P(0, 2, _T(MSG_PLEASE_WAIT));
  3105. mmu_command(MmuCmd::R0);
  3106. manage_response(false, false);
  3107. }
  3108. }
  3109. mmu_M600_load_filament(automatic, HotendTempBckp);
  3110. }
  3111. else
  3112. M600_load_filament();
  3113. if (!automatic) M600_check_state(HotendTempBckp);
  3114. lcd_update_enable(true);
  3115. //Not let's go back to print
  3116. fanSpeed = fanSpeedBckp;
  3117. //Feed a little of filament to stabilize pressure
  3118. if (!automatic)
  3119. {
  3120. current_position[E_AXIS] += FILAMENTCHANGE_RECFEED;
  3121. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EXFEED);
  3122. }
  3123. //Move XY back
  3124. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS],
  3125. FILAMENTCHANGE_XYFEED, active_extruder);
  3126. st_synchronize();
  3127. //Move Z back
  3128. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], lastpos[Z_AXIS], current_position[E_AXIS],
  3129. FILAMENTCHANGE_ZFEED, active_extruder);
  3130. st_synchronize();
  3131. //Set E position to original
  3132. plan_set_e_position(lastpos[E_AXIS]);
  3133. memcpy(current_position, lastpos, sizeof(lastpos));
  3134. set_destination_to_current();
  3135. //Recover feed rate
  3136. feedmultiply = feedmultiplyBckp;
  3137. char cmd[9];
  3138. sprintf_P(cmd, PSTR("M220 S%i"), feedmultiplyBckp);
  3139. enquecommand(cmd);
  3140. #ifdef FILAMENT_SENSOR
  3141. fsensor.settings_init();
  3142. #endif
  3143. lcd_setstatuspgm(MSG_WELCOME);
  3144. custom_message_type = CustomMsg::Status;
  3145. }
  3146. void gcode_M701()
  3147. {
  3148. printf_P(PSTR("gcode_M701 begin\n"));
  3149. #ifdef FILAMENT_SENSOR
  3150. fsensor.setRunoutEnabled(false); //suppress filament runouts while loading filament.
  3151. fsensor.setAutoLoadEnabled(false); //suppress filament autoloads while loading filament.
  3152. #endif
  3153. prusa_statistics(22);
  3154. if (mmu_enabled)
  3155. {
  3156. extr_adj(tmp_extruder);//loads current extruder
  3157. mmu_extruder = tmp_extruder;
  3158. }
  3159. else
  3160. {
  3161. enable_z();
  3162. custom_message_type = CustomMsg::FilamentLoading;
  3163. #ifdef FSENSOR_QUALITY
  3164. fsensor_oq_meassure_start(40);
  3165. #endif //FSENSOR_QUALITY
  3166. const int feed_mm_before_raising = 30;
  3167. static_assert(feed_mm_before_raising <= FILAMENTCHANGE_FIRSTFEED);
  3168. lcd_setstatuspgm(_T(MSG_LOADING_FILAMENT));
  3169. current_position[E_AXIS] += FILAMENTCHANGE_FIRSTFEED - feed_mm_before_raising;
  3170. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EFEED_FIRST); //fast sequence
  3171. st_synchronize();
  3172. raise_z_above(MIN_Z_FOR_LOAD, false);
  3173. current_position[E_AXIS] += feed_mm_before_raising;
  3174. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EFEED_FIRST); //fast sequence
  3175. load_filament_final_feed(); //slow sequence
  3176. st_synchronize();
  3177. Sound_MakeCustom(50,500,false);
  3178. if (!farm_mode && loading_flag) {
  3179. lcd_load_filament_color_check();
  3180. }
  3181. lcd_update_enable(true);
  3182. lcd_update(2);
  3183. lcd_setstatuspgm(MSG_WELCOME);
  3184. disable_z();
  3185. loading_flag = false;
  3186. custom_message_type = CustomMsg::Status;
  3187. #ifdef FSENSOR_QUALITY
  3188. fsensor_oq_meassure_stop();
  3189. if (!fsensor_oq_result())
  3190. {
  3191. bool disable = lcd_show_fullscreen_message_yes_no_and_wait_P(_n("Fil. sensor response is poor, disable it?"), false, true);
  3192. lcd_update_enable(true);
  3193. lcd_update(2);
  3194. if (disable)
  3195. fsensor_disable();
  3196. }
  3197. eFilamentAction = FilamentAction::None;
  3198. #ifdef FILAMENT_SENSOR
  3199. fsensor.settings_init(); //restore filament runout state.
  3200. #endif
  3201. }
  3202. /**
  3203. * @brief Get serial number from 32U2 processor
  3204. *
  3205. * Typical format of S/N is:CZPX0917X003XC13518
  3206. *
  3207. * Send command ;S to serial port 0 to retrieve serial number stored in 32U2 processor,
  3208. * reply is stored in *SN.
  3209. * Operation takes typically 23 ms. If no valid SN can be retrieved within the 250ms window, the function aborts
  3210. * and returns a general failure flag.
  3211. * The command will fail if the 32U2 processor is unpowered via USB since it is isolated from the rest of the electronics.
  3212. * In that case the value that is stored in the EEPROM should be used instead.
  3213. *
  3214. * @return 0 on success
  3215. * @return 1 on general failure
  3216. */
  3217. #ifdef PRUSA_SN_SUPPORT
  3218. static uint8_t get_PRUSA_SN(char* SN)
  3219. {
  3220. uint8_t selectedSerialPort_bak = selectedSerialPort;
  3221. uint8_t rxIndex;
  3222. bool SN_valid = false;
  3223. ShortTimer timeout;
  3224. selectedSerialPort = 0;
  3225. timeout.start();
  3226. while (!SN_valid)
  3227. {
  3228. rxIndex = 0;
  3229. _delay(50);
  3230. MYSERIAL.flush(); //clear RX buffer
  3231. SERIAL_ECHOLNRPGM(PSTR(";S"));
  3232. while (rxIndex < 19)
  3233. {
  3234. if (timeout.expired(250u))
  3235. goto exit;
  3236. if (MYSERIAL.available() > 0)
  3237. {
  3238. SN[rxIndex] = MYSERIAL.read();
  3239. rxIndex++;
  3240. }
  3241. }
  3242. SN[rxIndex] = 0;
  3243. // printf_P(PSTR("SN:%s\n"), SN);
  3244. SN_valid = (strncmp_P(SN, PSTR("CZPX"), 4) == 0);
  3245. }
  3246. exit:
  3247. selectedSerialPort = selectedSerialPort_bak;
  3248. return !SN_valid;
  3249. }
  3250. #endif //PRUSA_SN_SUPPORT
  3251. //! Detection of faulty RAMBo 1.1b boards equipped with bigger capacitors
  3252. //! at the TACH_1 pin, which causes bad detection of print fan speed.
  3253. //! Warning: This function is not to be used by ordinary users, it is here only for automated testing purposes,
  3254. //! it may even interfere with other functions of the printer! You have been warned!
  3255. //! The test idea is to measure the time necessary to charge the capacitor.
  3256. //! So the algorithm is as follows:
  3257. //! 1. Set TACH_1 pin to INPUT mode and LOW
  3258. //! 2. Wait a few ms
  3259. //! 3. disable interrupts and measure the time until the TACH_1 pin reaches HIGH
  3260. //! Repeat 1.-3. several times
  3261. //! Good RAMBo's times are in the range of approx. 260-320 us
  3262. //! Bad RAMBo's times are approx. 260-1200 us
  3263. //! So basically we are interested in maximum time, the minima are mostly the same.
  3264. //! May be that's why the bad RAMBo's still produce some fan RPM reading, but not corresponding to reality
  3265. static void gcode_PRUSA_BadRAMBoFanTest(){
  3266. //printf_P(PSTR("Enter fan pin test\n"));
  3267. #if !defined(DEBUG_DISABLE_FANCHECK) && defined(FANCHECK) && defined(TACH_1) && TACH_1 >-1
  3268. fan_measuring = false; // prevent EXTINT7 breaking into the measurement
  3269. unsigned long tach1max = 0;
  3270. uint8_t tach1cntr = 0;
  3271. for( /* nothing */; tach1cntr < 100; ++tach1cntr){
  3272. //printf_P(PSTR("TACH_1: %d\n"), tach1cntr);
  3273. SET_OUTPUT(TACH_1);
  3274. WRITE(TACH_1, LOW);
  3275. _delay(20); // the delay may be lower
  3276. unsigned long tachMeasure = _micros();
  3277. cli();
  3278. SET_INPUT(TACH_1);
  3279. // just wait brutally in an endless cycle until we reach HIGH
  3280. // if this becomes a problem it may be improved to non-endless cycle
  3281. while( READ(TACH_1) == 0 ) ;
  3282. sei();
  3283. tachMeasure = _micros() - tachMeasure;
  3284. if( tach1max < tachMeasure )
  3285. tach1max = tachMeasure;
  3286. //printf_P(PSTR("TACH_1: %d: capacitor check time=%lu us\n"), (int)tach1cntr, tachMeasure);
  3287. }
  3288. //printf_P(PSTR("TACH_1: max=%lu us\n"), tach1max);
  3289. SERIAL_PROTOCOLPGM("RAMBo FAN ");
  3290. if( tach1max > 500 ){
  3291. // bad RAMBo
  3292. SERIAL_PROTOCOLLNPGM("BAD");
  3293. } else {
  3294. SERIAL_PROTOCOLLNPGM("OK");
  3295. }
  3296. // cleanup after the test function
  3297. SET_INPUT(TACH_1);
  3298. WRITE(TACH_1, HIGH);
  3299. #endif
  3300. }
  3301. // G92 - Set current position to coordinates given
  3302. static void gcode_G92()
  3303. {
  3304. bool codes[NUM_AXIS];
  3305. float values[NUM_AXIS];
  3306. // Check which axes need to be set
  3307. for(uint8_t i = 0; i < NUM_AXIS; ++i)
  3308. {
  3309. codes[i] = code_seen(axis_codes[i]);
  3310. if(codes[i])
  3311. values[i] = code_value();
  3312. }
  3313. if((codes[E_AXIS] && values[E_AXIS] == 0) &&
  3314. (!codes[X_AXIS] && !codes[Y_AXIS] && !codes[Z_AXIS]))
  3315. {
  3316. // As a special optimization, when _just_ clearing the E position
  3317. // we schedule a flag asynchronously along with the next block to
  3318. // reset the starting E position instead of stopping the planner
  3319. current_position[E_AXIS] = 0;
  3320. plan_reset_next_e();
  3321. }
  3322. else
  3323. {
  3324. // In any other case we're forced to synchronize
  3325. st_synchronize();
  3326. for(uint8_t i = 0; i < 3; ++i)
  3327. {
  3328. if(codes[i])
  3329. current_position[i] = values[i] + cs.add_homing[i];
  3330. }
  3331. if(codes[E_AXIS])
  3332. current_position[E_AXIS] = values[E_AXIS];
  3333. // Set all at once
  3334. plan_set_position_curposXYZE();
  3335. }
  3336. }
  3337. #ifdef EXTENDED_CAPABILITIES_REPORT
  3338. static void cap_line(const char* name, bool ena = false) {
  3339. printf_P(PSTR("Cap:%S:%c\n"), name, (char)ena + '0');
  3340. }
  3341. static void extended_capabilities_report()
  3342. {
  3343. // AUTOREPORT_TEMP (M155)
  3344. cap_line(PSTR("AUTOREPORT_TEMP"), ENABLED(AUTO_REPORT));
  3345. #if (defined(FANCHECK) && (((defined(TACH_0) && (TACH_0 >-1)) || (defined(TACH_1) && (TACH_1 > -1)))))
  3346. // AUTOREPORT_FANS (M123)
  3347. cap_line(PSTR("AUTOREPORT_FANS"), ENABLED(AUTO_REPORT));
  3348. #endif //FANCHECK and TACH_0 or TACH_1
  3349. // AUTOREPORT_POSITION (M114)
  3350. cap_line(PSTR("AUTOREPORT_POSITION"), ENABLED(AUTO_REPORT));
  3351. // EXTENDED_M20 (support for L and T parameters)
  3352. cap_line(PSTR("EXTENDED_M20"), 1);
  3353. cap_line(PSTR("PRUSA_MMU2"), 1); //this will soon change to ENABLED(PRUSA_MMU2_SUPPORT)
  3354. }
  3355. #endif //EXTENDED_CAPABILITIES_REPORT
  3356. #ifdef BACKLASH_X
  3357. extern uint8_t st_backlash_x;
  3358. #endif //BACKLASH_X
  3359. #ifdef BACKLASH_Y
  3360. extern uint8_t st_backlash_y;
  3361. #endif //BACKLASH_Y
  3362. //! \ingroup marlin_main
  3363. //! @brief Parse and process commands
  3364. //!
  3365. //! look here for descriptions of G-codes: https://reprap.org/wiki/G-code
  3366. //!
  3367. //!
  3368. //! Implemented Codes
  3369. //! -------------------
  3370. //!
  3371. //! * _This list is not updated. Current documentation is maintained inside the process_cmd function._
  3372. //!
  3373. //!@n PRUSA CODES
  3374. //!@n P F - Returns FW versions
  3375. //!@n P R - Returns revision of printer
  3376. //!
  3377. //!@n G0 -> G1
  3378. //!@n G1 - Coordinated Movement X Y Z E
  3379. //!@n G2 - CW ARC
  3380. //!@n G3 - CCW ARC
  3381. //!@n G4 - Dwell S<seconds> or P<milliseconds>
  3382. //!@n G10 - retract filament according to settings of M207
  3383. //!@n G11 - retract recover filament according to settings of M208
  3384. //!@n G28 - Home all Axes
  3385. //!@n G29 - Detailed Z-Probe, probes the bed at 3 or more points. Will fail if you haven't homed yet.
  3386. //!@n G30 - Single Z Probe, probes bed at current XY location.
  3387. //!@n G31 - Dock sled (Z_PROBE_SLED only)
  3388. //!@n G32 - Undock sled (Z_PROBE_SLED only)
  3389. //!@n G80 - Automatic mesh bed leveling
  3390. //!@n G81 - Print bed profile
  3391. //!@n G90 - Use Absolute Coordinates
  3392. //!@n G91 - Use Relative Coordinates
  3393. //!@n G92 - Set current position to coordinates given
  3394. //!
  3395. //!@n M Codes
  3396. //!@n M0 - Unconditional stop - Wait for user to press a button on the LCD
  3397. //!@n M1 - Same as M0
  3398. //!@n M17 - Enable/Power all stepper motors
  3399. //!@n M18 - Disable all stepper motors; same as M84
  3400. //!@n M20 - List SD card
  3401. //!@n M21 - Init SD card
  3402. //!@n M22 - Release SD card
  3403. //!@n M23 - Select SD file (M23 filename.g)
  3404. //!@n M24 - Start/resume SD print
  3405. //!@n M25 - Pause SD print
  3406. //!@n M26 - Set SD position in bytes (M26 S12345)
  3407. //!@n M27 - Report SD print status
  3408. //!@n M28 - Start SD write (M28 filename.g)
  3409. //!@n M29 - Stop SD write
  3410. //!@n M30 - Delete file from SD (M30 filename.g)
  3411. //!@n M31 - Output time since last M109 or SD card start to serial
  3412. //!@n M32 - Select file and start SD print (Can be used _while_ printing from SD card files):
  3413. //! syntax "M32 /path/filename#", or "M32 S<startpos bytes> !filename#"
  3414. //! Call gcode file : "M32 P !filename#" and return to caller file after finishing (similar to #include).
  3415. //! The '#' is necessary when calling from within sd files, as it stops buffer prereading
  3416. //!@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.
  3417. //!@n M73 - Show percent done and print time remaining
  3418. //!@n M80 - Turn on Power Supply
  3419. //!@n M81 - Turn off Power Supply
  3420. //!@n M82 - Set E codes absolute (default)
  3421. //!@n M83 - Set E codes relative while in Absolute Coordinates (G90) mode
  3422. //!@n M84 - Disable steppers until next move,
  3423. //! or use S<seconds> to specify an inactivity timeout, after which the steppers will be disabled. S0 to disable the timeout.
  3424. //!@n M85 - Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
  3425. //!@n M86 - Set safety timer expiration time with parameter S<seconds>; M86 S0 will disable safety timer
  3426. //!@n M92 - Set axis_steps_per_unit - same syntax as G92
  3427. //!@n M104 - Set extruder target temp
  3428. //!@n M105 - Read current temp
  3429. //!@n M106 - Fan on
  3430. //!@n M107 - Fan off
  3431. //!@n M109 - Sxxx Wait for extruder current temp to reach target temp. Waits only when heating
  3432. //! Rxxx Wait for extruder current temp to reach target temp. Waits when heating and cooling
  3433. //! IF AUTOTEMP is enabled, S<mintemp> B<maxtemp> F<factor>. Exit autotemp by any M109 without F
  3434. //!@n M112 - Emergency stop
  3435. //!@n M113 - Get or set the timeout interval for Host Keepalive "busy" messages
  3436. //!@n M114 - Output current position to serial port
  3437. //!@n M115 - Capabilities string
  3438. //!@n M117 - display message
  3439. //!@n M119 - Output Endstop status to serial port
  3440. //!@n M123 - Tachometer value
  3441. //!@n M126 - Solenoid Air Valve Open (BariCUDA support by jmil)
  3442. //!@n M127 - Solenoid Air Valve Closed (BariCUDA vent to atmospheric pressure by jmil)
  3443. //!@n M128 - EtoP Open (BariCUDA EtoP = electricity to air pressure transducer by jmil)
  3444. //!@n M129 - EtoP Closed (BariCUDA EtoP = electricity to air pressure transducer by jmil)
  3445. //!@n M140 - Set bed target temp
  3446. //!@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.
  3447. //!@n M155 - Automatically send temperatures, fan speeds, position
  3448. //!@n M190 - Sxxx Wait for bed current temp to reach target temp. Waits only when heating
  3449. //! Rxxx Wait for bed current temp to reach target temp. Waits when heating and cooling
  3450. //!@n M200 D<millimeters>- set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).
  3451. //!@n M201 - Set max acceleration in units/s^2 for print moves (M201 X1000 Y1000)
  3452. //!@n M202 - Set max acceleration in units/s^2 for travel moves (M202 X1000 Y1000) Unused in Marlin!!
  3453. //!@n M203 - Set maximum feedrate that your machine can sustain (M203 X200 Y200 Z300 E10000) in mm/sec
  3454. //!@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
  3455. //!@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
  3456. //!@n M206 - set additional homing offset
  3457. //!@n M207 - set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop], stays in mm regardless of M200 setting
  3458. //!@n M208 - set recover=unretract length S[positive mm surplus to the M207 S*] F[feedrate mm/sec]
  3459. //!@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.
  3460. //!@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>
  3461. //!@n M218 - set hotend offset (in mm): T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  3462. //!@n M220 S<factor in percent>- set speed factor override percentage
  3463. //!@n M221 S<factor in percent>- set extrude factor override percentage
  3464. //!@n M226 P<pin number> S<pin state>- Wait until the specified pin reaches the state required
  3465. //!@n M240 - Trigger a camera to take a photograph
  3466. //!@n M250 - Set LCD contrast C<contrast value> (value 0..63)
  3467. //!@n M280 - set servo position absolute. P: servo index, S: angle or microseconds
  3468. //!@n M300 - Play beep sound S<frequency Hz> P<duration ms>
  3469. //!@n M301 - Set PID parameters P I and D
  3470. //!@n M302 - Allow cold extrudes, or set the minimum extrude S<temperature>.
  3471. //!@n M303 - PID relay autotune S<temperature> sets the target temperature. (default target temperature = 150C)
  3472. //!@n M304 - Set bed PID parameters P I and D
  3473. //!@n M310 - Temperature model settings
  3474. //!@n M400 - Finish all moves
  3475. //!@n M401 - Lower z-probe if present
  3476. //!@n M402 - Raise z-probe if present
  3477. //!@n M404 - N<dia in mm> Enter the nominal filament width (3mm, 1.75mm ) or will display nominal filament width without parameters
  3478. //!@n M405 - Turn on Filament Sensor extrusion control. Optional D<delay in cm> to set delay in centimeters between sensor and extruder
  3479. //!@n M406 - Turn off Filament Sensor extrusion control
  3480. //!@n M407 - Displays measured filament diameter
  3481. //!@n M500 - stores parameters in EEPROM
  3482. //!@n M501 - reads parameters from EEPROM (if you need reset them after you changed them temporarily).
  3483. //!@n M502 - reverts to the default "factory settings". You still need to store them in EEPROM afterwards if you want to.
  3484. //!@n M503 - print the current settings (from memory not from EEPROM)
  3485. //!@n M509 - force language selection on next restart
  3486. //!@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)
  3487. //!@n M552 - Set IP address
  3488. //!@n M600 - Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  3489. //!@n M605 - Set dual x-carriage movement mode: S<mode> [ X<duplication x-offset> R<duplication temp offset> ]
  3490. //!@n M860 - Wait for PINDA thermistor to reach target temperature.
  3491. //!@n M861 - Set / Read PINDA temperature compensation offsets
  3492. //!@n M900 - Set LIN_ADVANCE options, if enabled. See Configuration_adv.h for details.
  3493. //!@n M907 - Set digital trimpot motor current using axis codes.
  3494. //!@n M908 - Control digital trimpot directly.
  3495. //!@n M350 - Set microstepping mode.
  3496. //!@n M351 - Toggle MS1 MS2 pins directly.
  3497. //!
  3498. //!@n M928 - Start SD logging (M928 filename.g) - ended by M29
  3499. //!@n M999 - Restart after being stopped by error
  3500. //! <br><br>
  3501. /** @defgroup marlin_main Marlin main */
  3502. /** \ingroup GCodes */
  3503. //! _This is a list of currently implemented G Codes in Prusa firmware (dynamically generated from doxygen)._
  3504. /**
  3505. They are shown in order of appearance in the code.
  3506. There are reasons why some G Codes aren't in numerical order.
  3507. */
  3508. void process_commands()
  3509. {
  3510. if (!buflen) return; //empty command
  3511. #ifdef CMDBUFFER_DEBUG
  3512. SERIAL_ECHOPGM("Processing a GCODE command: ");
  3513. SERIAL_ECHO(cmdbuffer+bufindr+CMDHDRSIZE);
  3514. SERIAL_ECHOLNPGM("");
  3515. SERIAL_ECHOPGM("In cmdqueue: ");
  3516. SERIAL_ECHO(buflen);
  3517. SERIAL_ECHOLNPGM("");
  3518. #endif /* CMDBUFFER_DEBUG */
  3519. unsigned long codenum; //throw away variable
  3520. char *starpos = NULL;
  3521. #ifdef ENABLE_AUTO_BED_LEVELING
  3522. float x_tmp, y_tmp, z_tmp, real_z;
  3523. #endif
  3524. // PRUSA GCODES
  3525. KEEPALIVE_STATE(IN_HANDLER);
  3526. /*!
  3527. ---------------------------------------------------------------------------------
  3528. ### M117 - Display Message <a href="https://reprap.org/wiki/G-code#M117:_Display_Message">M117: Display Message</a>
  3529. This causes the given message to be shown in the status line on an attached LCD.
  3530. It is processed early as to allow printing messages that contain G, M, N or T.
  3531. ---------------------------------------------------------------------------------
  3532. ### Special internal commands
  3533. These are used by internal functions to process certain actions in the right order. Some of these are also usable by the user.
  3534. They are processed early as the commands are complex (strings).
  3535. These are only available on the MK3(S) as these require TMC2130 drivers:
  3536. - CRASH DETECTED
  3537. - CRASH RECOVER
  3538. - CRASH_CANCEL
  3539. - TMC_SET_WAVE
  3540. - TMC_SET_STEP
  3541. - TMC_SET_CHOP
  3542. */
  3543. if (code_seen_P(PSTR("M117"))) //moved to highest priority place to be able to to print strings which includes "G", "PRUSA" and "^"
  3544. {
  3545. starpos = (strchr(strchr_pointer + 5, '*'));
  3546. if (starpos != NULL)
  3547. *(starpos) = '\0';
  3548. lcd_setstatus(strchr_pointer + 5);
  3549. custom_message_type = CustomMsg::M117;
  3550. }
  3551. /*!
  3552. ### M0, M1 - Stop the printer <a href="https://reprap.org/wiki/G-code#M0:_Stop_or_Unconditional_stop">M0: Stop or Unconditional stop</a>
  3553. #### Usage
  3554. M0 [P<ms<] [S<sec>] [string]
  3555. M1 [P<ms>] [S<sec>] [string]
  3556. #### Parameters
  3557. - `P<ms>` - Expire time, in milliseconds
  3558. - `S<sec>` - Expire time, in seconds
  3559. - `string` - Must for M1 and optional for M0 message to display on the LCD
  3560. */
  3561. 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
  3562. const char *src = strchr_pointer + 2;
  3563. codenum = 0;
  3564. bool hasP = false, hasS = false;
  3565. if (code_seen('P')) {
  3566. codenum = code_value_long(); // milliseconds to wait
  3567. hasP = codenum > 0;
  3568. }
  3569. if (code_seen('S')) {
  3570. codenum = code_value_long() * 1000; // seconds to wait
  3571. hasS = codenum > 0;
  3572. }
  3573. starpos = strchr(src, '*');
  3574. if (starpos != NULL) *(starpos) = '\0';
  3575. while (*src == ' ') ++src;
  3576. custom_message_type = CustomMsg::M0Wait;
  3577. if (!hasP && !hasS && *src != '\0') {
  3578. lcd_setstatus(src);
  3579. } else {
  3580. // farmers want to abuse a bug from the previous firmware releases
  3581. // - they need to see the filename on the status screen instead of "Wait for user..."
  3582. // So we won't update the message in farm mode...
  3583. if( ! farm_mode){
  3584. LCD_MESSAGERPGM(_i("Wait for user..."));////MSG_USERWAIT c=20
  3585. } else {
  3586. custom_message_type = CustomMsg::Status; // let the lcd display the name of the printed G-code file in farm mode
  3587. }
  3588. }
  3589. lcd_ignore_click(); //call lcd_ignore_click also for else ???
  3590. st_synchronize();
  3591. previous_millis_cmd.start();
  3592. if (codenum > 0 ) {
  3593. codenum += _millis(); // keep track of when we started waiting
  3594. KEEPALIVE_STATE(PAUSED_FOR_USER);
  3595. while(_millis() < codenum && !lcd_clicked()) {
  3596. manage_heater();
  3597. manage_inactivity(true);
  3598. lcd_update(0);
  3599. }
  3600. KEEPALIVE_STATE(IN_HANDLER);
  3601. lcd_ignore_click(false);
  3602. } else {
  3603. marlin_wait_for_click();
  3604. }
  3605. if (IS_SD_PRINTING)
  3606. custom_message_type = CustomMsg::Status;
  3607. else
  3608. LCD_MESSAGERPGM(MSG_WELCOME);
  3609. }
  3610. #ifdef TMC2130
  3611. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("CRASH_"), 6) == 0)
  3612. {
  3613. // ### CRASH_DETECTED - TMC2130
  3614. // ---------------------------------
  3615. if(code_seen_P(PSTR("CRASH_DETECTED")))
  3616. {
  3617. uint8_t mask = 0;
  3618. if (code_seen('X')) mask |= X_AXIS_MASK;
  3619. if (code_seen('Y')) mask |= Y_AXIS_MASK;
  3620. crashdet_detected(mask);
  3621. }
  3622. // ### CRASH_RECOVER - TMC2130
  3623. // ----------------------------------
  3624. else if(code_seen_P(PSTR("CRASH_RECOVER")))
  3625. crashdet_recover();
  3626. // ### CRASH_CANCEL - TMC2130
  3627. // ----------------------------------
  3628. else if(code_seen_P(PSTR("CRASH_CANCEL")))
  3629. crashdet_cancel();
  3630. }
  3631. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("TMC_"), 4) == 0)
  3632. {
  3633. // ### TMC_SET_WAVE_
  3634. // --------------------
  3635. if (strncmp_P(CMDBUFFER_CURRENT_STRING + 4, PSTR("SET_WAVE_"), 9) == 0)
  3636. {
  3637. uint8_t axis = *(CMDBUFFER_CURRENT_STRING + 13);
  3638. axis = (axis == 'E')?3:(axis - 'X');
  3639. if (axis < 4)
  3640. {
  3641. uint8_t fac = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 14, NULL, 10);
  3642. tmc2130_set_wave(axis, 247, fac);
  3643. }
  3644. }
  3645. // ### TMC_SET_STEP_
  3646. // ------------------
  3647. else if (strncmp_P(CMDBUFFER_CURRENT_STRING + 4, PSTR("SET_STEP_"), 9) == 0)
  3648. {
  3649. uint8_t axis = *(CMDBUFFER_CURRENT_STRING + 13);
  3650. axis = (axis == 'E')?3:(axis - 'X');
  3651. if (axis < 4)
  3652. {
  3653. uint8_t step = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 14, NULL, 10);
  3654. uint16_t res = tmc2130_get_res(axis);
  3655. tmc2130_goto_step(axis, step & (4*res - 1), 2, 1000, res);
  3656. }
  3657. }
  3658. // ### TMC_SET_CHOP_
  3659. // -------------------
  3660. else if (strncmp_P(CMDBUFFER_CURRENT_STRING + 4, PSTR("SET_CHOP_"), 9) == 0)
  3661. {
  3662. uint8_t axis = *(CMDBUFFER_CURRENT_STRING + 13);
  3663. axis = (axis == 'E')?3:(axis - 'X');
  3664. if (axis < 4)
  3665. {
  3666. uint8_t chop0 = tmc2130_chopper_config[axis].toff;
  3667. uint8_t chop1 = tmc2130_chopper_config[axis].hstr;
  3668. uint8_t chop2 = tmc2130_chopper_config[axis].hend;
  3669. uint8_t chop3 = tmc2130_chopper_config[axis].tbl;
  3670. char* str_end = 0;
  3671. if (CMDBUFFER_CURRENT_STRING[14])
  3672. {
  3673. chop0 = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 14, &str_end, 10) & 15;
  3674. if (str_end && *str_end)
  3675. {
  3676. chop1 = (uint8_t)strtol(str_end, &str_end, 10) & 7;
  3677. if (str_end && *str_end)
  3678. {
  3679. chop2 = (uint8_t)strtol(str_end, &str_end, 10) & 15;
  3680. if (str_end && *str_end)
  3681. chop3 = (uint8_t)strtol(str_end, &str_end, 10) & 3;
  3682. }
  3683. }
  3684. }
  3685. tmc2130_chopper_config[axis].toff = chop0;
  3686. tmc2130_chopper_config[axis].hstr = chop1 & 7;
  3687. tmc2130_chopper_config[axis].hend = chop2 & 15;
  3688. tmc2130_chopper_config[axis].tbl = chop3 & 3;
  3689. tmc2130_setup_chopper(axis, tmc2130_mres[axis], tmc2130_current_h[axis], tmc2130_current_r[axis]);
  3690. //printf_P(_N("TMC_SET_CHOP_%c %d %d %d %d\n"), "xyze"[axis], chop0, chop1, chop2, chop3);
  3691. }
  3692. }
  3693. }
  3694. #ifdef BACKLASH_X
  3695. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("BACKLASH_X"), 10) == 0)
  3696. {
  3697. uint8_t bl = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 10, NULL, 10);
  3698. st_backlash_x = bl;
  3699. printf_P(_N("st_backlash_x = %d\n"), st_backlash_x);
  3700. }
  3701. #endif //BACKLASH_X
  3702. #ifdef BACKLASH_Y
  3703. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("BACKLASH_Y"), 10) == 0)
  3704. {
  3705. uint8_t bl = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 10, NULL, 10);
  3706. st_backlash_y = bl;
  3707. printf_P(_N("st_backlash_y = %d\n"), st_backlash_y);
  3708. }
  3709. #endif //BACKLASH_Y
  3710. #endif //TMC2130
  3711. else if(code_seen_P(PSTR("PRUSA"))){
  3712. /*!
  3713. ---------------------------------------------------------------------------------
  3714. ### PRUSA - Internal command set <a href="https://reprap.org/wiki/G-code#G98:_Activate_farm_mode">G98: Activate farm mode - Notes</a>
  3715. Set of internal PRUSA commands
  3716. #### Usage
  3717. PRUSA [ PRN | FAN | thx | uvlo | MMURES | RESET | fv | M28 | SN | Fir | Rev | Lang | Lz | FR ]
  3718. #### Parameters
  3719. - `PRN` - Prints revision of the printer
  3720. - `FAN` - Prints fan details
  3721. - `thx`
  3722. - `uvlo`
  3723. - `MMURES` - Reset MMU
  3724. - `RESET` - (Careful!)
  3725. - `fv` - ?
  3726. - `M28`
  3727. - `SN`
  3728. - `Fir` - Prints firmware version
  3729. - `Rev`- Prints filament size, elelectronics, nozzle type
  3730. - `Lang` - Reset the language
  3731. - `Lz`
  3732. - `FR` - Full factory reset
  3733. - `nozzle set <diameter>` - set nozzle diameter (farm mode only), e.g. `PRUSA nozzle set 0.4`
  3734. - `nozzle D<diameter>` - check the nozzle diameter (farm mode only), works like M862.1 P, e.g. `PRUSA nozzle D0.4`
  3735. - `nozzle` - prints nozzle diameter (farm mode only), works like M862.1 P, e.g. `PRUSA nozzle`
  3736. */
  3737. if (farm_prusa_code_seen()) {}
  3738. else if(code_seen_P(PSTR("FANPINTST"))) {
  3739. gcode_PRUSA_BadRAMBoFanTest();
  3740. }
  3741. else if (code_seen_P(PSTR("FAN"))) { // PRUSA FAN
  3742. printf_P(_N("E0:%d RPM\nPRN0:%d RPM\n"), 60*fan_speed[0], 60*fan_speed[1]);
  3743. }
  3744. else if (code_seen_P(PSTR("uvlo"))) { // PRUSA uvlo
  3745. eeprom_update_byte((uint8_t*)EEPROM_UVLO,0);
  3746. enquecommand_P(PSTR("M24"));
  3747. }
  3748. else if (code_seen_P(PSTR("MMURES"))) // PRUSA MMURES
  3749. {
  3750. mmu_reset();
  3751. }
  3752. else if (code_seen_P(PSTR("RESET"))) { // PRUSA RESET
  3753. #ifdef WATCHDOG
  3754. #if defined(XFLASH) && defined(BOOTAPP)
  3755. boot_app_magic = BOOT_APP_MAGIC;
  3756. boot_app_flags = BOOT_APP_FLG_RUN;
  3757. #endif //defined(XFLASH) && defined(BOOTAPP)
  3758. softReset();
  3759. #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.
  3760. asm volatile("jmp 0x3E000");
  3761. #endif
  3762. }
  3763. #ifdef PRUSA_SN_SUPPORT
  3764. else if (code_seen_P(PSTR("SN"))) { // PRUSA SN
  3765. char SN[20];
  3766. eeprom_read_block(SN, (uint8_t*)EEPROM_PRUSA_SN, 20);
  3767. if (SN[19])
  3768. puts_P(PSTR("SN invalid"));
  3769. else
  3770. puts(SN);
  3771. }
  3772. #endif //PRUSA_SN_SUPPORT
  3773. else if(code_seen_P(PSTR("Fir"))){ // PRUSA Fir
  3774. SERIAL_PROTOCOLLN(FW_VERSION_FULL);
  3775. } else if(code_seen_P(PSTR("Rev"))){ // PRUSA Rev
  3776. SERIAL_PROTOCOLLN(FILAMENT_SIZE "-" ELECTRONICS "-" NOZZLE_TYPE );
  3777. } else if(code_seen_P(PSTR("Lang"))) { // PRUSA Lang
  3778. lang_reset();
  3779. } else if(code_seen_P(PSTR("Lz"))) { // PRUSA Lz
  3780. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  3781. } else if(code_seen_P(PSTR("FR"))) { // PRUSA FR
  3782. // Factory full reset
  3783. factory_reset(0);
  3784. } else if(code_seen_P(PSTR("MBL"))) { // PRUSA MBL
  3785. // Change the MBL status without changing the logical Z position.
  3786. if(code_seen('V')) {
  3787. bool value = code_value_short();
  3788. st_synchronize();
  3789. if(value != mbl.active) {
  3790. mbl.active = value;
  3791. // Use plan_set_z_position to reset the physical values
  3792. plan_set_z_position(current_position[Z_AXIS]);
  3793. }
  3794. }
  3795. //-//
  3796. /*
  3797. } else if(code_seen("rrr")) {
  3798. MYSERIAL.println("=== checking ===");
  3799. MYSERIAL.println(eeprom_read_byte((uint8_t*)EEPROM_CHECK_MODE),DEC);
  3800. MYSERIAL.println(eeprom_read_byte((uint8_t*)EEPROM_NOZZLE_DIAMETER),DEC);
  3801. MYSERIAL.println(eeprom_read_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM),DEC);
  3802. MYSERIAL.println(farm_mode,DEC);
  3803. MYSERIAL.println(eCheckMode,DEC);
  3804. } else if(code_seen("www")) {
  3805. MYSERIAL.println("=== @ FF ===");
  3806. eeprom_update_byte((uint8_t*)EEPROM_CHECK_MODE,0xFF);
  3807. eeprom_update_byte((uint8_t*)EEPROM_NOZZLE_DIAMETER,0xFF);
  3808. eeprom_update_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM,0xFFFF);
  3809. */
  3810. } else if (code_seen_P(PSTR("nozzle"))) { // PRUSA nozzle
  3811. uint16_t nDiameter;
  3812. if(code_seen('D'))
  3813. {
  3814. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  3815. nozzle_diameter_check(nDiameter);
  3816. }
  3817. else if(code_seen_P(PSTR("set")) && farm_mode)
  3818. {
  3819. strchr_pointer++; // skip 1st char (~ 's')
  3820. strchr_pointer++; // skip 2nd char (~ 'e')
  3821. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  3822. eeprom_update_byte((uint8_t*)EEPROM_NOZZLE_DIAMETER,(uint8_t)ClNozzleDiameter::_Diameter_Undef); // for correct synchronization after farm-mode exiting
  3823. eeprom_update_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM,nDiameter);
  3824. }
  3825. else SERIAL_PROTOCOLLN((float)eeprom_read_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM)/1000.0);
  3826. //-// !!! SupportMenu
  3827. /*
  3828. // musi byt PRED "PRUSA model"
  3829. } else if (code_seen("smodel")) { //! PRUSA smodel
  3830. size_t nOffset;
  3831. // ! -> "l"
  3832. strchr_pointer+=5*sizeof(*strchr_pointer); // skip 1st - 5th char (~ 'smode')
  3833. nOffset=strspn(strchr_pointer+1," \t\n\r\v\f");
  3834. if(*(strchr_pointer+1+nOffset))
  3835. printer_smodel_check(strchr_pointer);
  3836. else SERIAL_PROTOCOLLN(PRINTER_NAME);
  3837. } else if (code_seen("model")) { //! PRUSA model
  3838. uint16_t nPrinterModel;
  3839. strchr_pointer+=4*sizeof(*strchr_pointer); // skip 1st - 4th char (~ 'mode')
  3840. nPrinterModel=(uint16_t)code_value_long();
  3841. if(nPrinterModel!=0)
  3842. printer_model_check(nPrinterModel);
  3843. else SERIAL_PROTOCOLLN(PRINTER_TYPE);
  3844. } else if (code_seen("version")) { //! PRUSA version
  3845. strchr_pointer+=7*sizeof(*strchr_pointer); // skip 1st - 7th char (~ 'version')
  3846. while(*strchr_pointer==' ') // skip leading spaces
  3847. strchr_pointer++;
  3848. if(*strchr_pointer!=0)
  3849. fw_version_check(strchr_pointer);
  3850. else SERIAL_PROTOCOLLN(FW_VERSION);
  3851. } else if (code_seen("gcode")) { //! PRUSA gcode
  3852. uint16_t nGcodeLevel;
  3853. strchr_pointer+=4*sizeof(*strchr_pointer); // skip 1st - 4th char (~ 'gcod')
  3854. nGcodeLevel=(uint16_t)code_value_long();
  3855. if(nGcodeLevel!=0)
  3856. gcode_level_check(nGcodeLevel);
  3857. else SERIAL_PROTOCOLLN(GCODE_LEVEL);
  3858. */
  3859. }
  3860. //else if (code_seen('Cal')) {
  3861. // lcd_calibration();
  3862. // }
  3863. }
  3864. // This prevents reading files with "^" in their names.
  3865. // Since it is unclear, if there is some usage of this construct,
  3866. // it will be deprecated in 3.9 alpha a possibly completely removed in the future:
  3867. // else if (code_seen('^')) {
  3868. // // nothing, this is a version line
  3869. // }
  3870. else if(code_seen('G'))
  3871. {
  3872. gcode_in_progress = code_value_short();
  3873. // printf_P(_N("BEGIN G-CODE=%u\n"), gcode_in_progress);
  3874. switch (gcode_in_progress)
  3875. {
  3876. /*!
  3877. ---------------------------------------------------------------------------------
  3878. # G Codes
  3879. ### G0, G1 - Coordinated movement X Y Z E <a href="https://reprap.org/wiki/G-code#G0_.26_G1:_Move">G0 & G1: Move</a>
  3880. In Prusa Firmware G0 and G1 are the same.
  3881. #### Usage
  3882. G0 [ X | Y | Z | E | F | S ]
  3883. G1 [ X | Y | Z | E | F | S ]
  3884. #### Parameters
  3885. - `X` - The position to move to on the X axis
  3886. - `Y` - The position to move to on the Y axis
  3887. - `Z` - The position to move to on the Z axis
  3888. - `E` - The amount to extrude between the starting point and ending point
  3889. - `F` - The feedrate per minute of the move between the starting point and ending point (if supplied)
  3890. */
  3891. case 0: // G0 -> G1
  3892. case 1: // G1
  3893. {
  3894. uint16_t start_segment_idx = restore_interrupted_gcode();
  3895. get_coordinates(); // For X Y Z E F
  3896. if (total_filament_used > ((current_position[E_AXIS] - destination[E_AXIS]) * 100)) { //protection against total_filament_used overflow
  3897. total_filament_used = total_filament_used + ((destination[E_AXIS] - current_position[E_AXIS]) * 100);
  3898. }
  3899. #ifdef FWRETRACT
  3900. if(cs.autoretract_enabled) {
  3901. if( !(code_seen('X') || code_seen('Y') || code_seen('Z')) && code_seen('E')) {
  3902. float echange=destination[E_AXIS]-current_position[E_AXIS];
  3903. if((echange<-MIN_RETRACT && !retracted[active_extruder]) || (echange>MIN_RETRACT && retracted[active_extruder])) { //move appears to be an attempt to retract or recover
  3904. st_synchronize();
  3905. current_position[E_AXIS] = destination[E_AXIS]; //hide the slicer-generated retract/recover from calculations
  3906. plan_set_e_position(current_position[E_AXIS]); //AND from the planner
  3907. retract(!retracted[active_extruder]);
  3908. return;
  3909. }
  3910. }
  3911. }
  3912. #endif //FWRETRACT
  3913. prepare_move(start_segment_idx);
  3914. //ClearToSend();
  3915. }
  3916. break;
  3917. /*!
  3918. ### 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>
  3919. These commands don't propperly work with MBL enabled. The compensation only happens at the end of the move, so avoid long arcs.
  3920. #### Usage
  3921. G2 [ X | Y | I | E | F ] (Clockwise Arc)
  3922. G3 [ X | Y | I | E | F ] (Counter-Clockwise Arc)
  3923. #### Parameters
  3924. - `X` - The position to move to on the X axis
  3925. - `Y` - The position to move to on the Y axis
  3926. - 'Z' - The position to move to on the Z axis
  3927. - `I` - The point in X space from the current X position to maintain a constant distance from
  3928. - `J` - The point in Y space from the current Y position to maintain a constant distance from
  3929. - `E` - The amount to extrude between the starting point and ending point
  3930. - `F` - The feedrate per minute of the move between the starting point and ending point (if supplied)
  3931. */
  3932. case 2:
  3933. case 3:
  3934. {
  3935. uint16_t start_segment_idx = restore_interrupted_gcode();
  3936. #ifdef SF_ARC_FIX
  3937. bool relative_mode_backup = relative_mode;
  3938. relative_mode = true;
  3939. #endif
  3940. get_coordinates(); // For X Y Z E F
  3941. #ifdef SF_ARC_FIX
  3942. relative_mode=relative_mode_backup;
  3943. #endif
  3944. offset[0] = code_seen('I') ? code_value() : 0.f;
  3945. offset[1] = code_seen('J') ? code_value() : 0.f;
  3946. prepare_arc_move((gcode_in_progress == 2), start_segment_idx);
  3947. } break;
  3948. /*!
  3949. ### G4 - Dwell <a href="https://reprap.org/wiki/G-code#G4:_Dwell">G4: Dwell</a>
  3950. Pause the machine for a period of time.
  3951. #### Usage
  3952. G4 [ P | S ]
  3953. #### Parameters
  3954. - `P` - Time to wait, in milliseconds
  3955. - `S` - Time to wait, in seconds
  3956. */
  3957. case 4:
  3958. codenum = 0;
  3959. if(code_seen('P')) codenum = code_value(); // milliseconds to wait
  3960. if(code_seen('S')) codenum = code_value() * 1000; // seconds to wait
  3961. if(codenum != 0)
  3962. {
  3963. if(custom_message_type != CustomMsg::M117)
  3964. {
  3965. LCD_MESSAGERPGM(_n("Sleep..."));////MSG_DWELL
  3966. }
  3967. }
  3968. st_synchronize();
  3969. codenum += _millis(); // keep track of when we started waiting
  3970. previous_millis_cmd.start();
  3971. while(_millis() < codenum) {
  3972. manage_heater();
  3973. manage_inactivity();
  3974. lcd_update(0);
  3975. }
  3976. break;
  3977. #ifdef FWRETRACT
  3978. /*!
  3979. ### G10 - Retract <a href="https://reprap.org/wiki/G-code#G10:_Retract">G10: Retract</a>
  3980. Retracts filament according to settings of `M207`
  3981. */
  3982. case 10:
  3983. #if EXTRUDERS > 1
  3984. retracted_swap[active_extruder]=(code_seen('S') && code_value_long() == 1); // checks for swap retract argument
  3985. retract(true,retracted_swap[active_extruder]);
  3986. #else
  3987. retract(true);
  3988. #endif
  3989. break;
  3990. /*!
  3991. ### G11 - Retract recover <a href="https://reprap.org/wiki/G-code#G11:_Unretract">G11: Unretract</a>
  3992. Unretracts/recovers filament according to settings of `M208`
  3993. */
  3994. case 11:
  3995. #if EXTRUDERS > 1
  3996. retract(false,retracted_swap[active_extruder]);
  3997. #else
  3998. retract(false);
  3999. #endif
  4000. break;
  4001. #endif //FWRETRACT
  4002. /*!
  4003. ### G21 - Sets Units to Millimters <a href="https://reprap.org/wiki/G-code#G21:_Set_Units_to_Millimeters">G21: Set Units to Millimeters</a>
  4004. Units are in millimeters. Prusa doesn't support inches.
  4005. */
  4006. case 21:
  4007. break; //Doing nothing. This is just to prevent serial UNKOWN warnings.
  4008. /*!
  4009. ### 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>
  4010. 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).
  4011. #### Usage
  4012. G28 [ X | Y | Z | W | C ]
  4013. #### Parameters
  4014. - `X` - Flag to go back to the X axis origin
  4015. - `Y` - Flag to go back to the Y axis origin
  4016. - `Z` - Flag to go back to the Z axis origin
  4017. - `W` - Suppress mesh bed leveling if `X`, `Y` or `Z` are not provided
  4018. - `C` - Calibrate X and Y origin (home) - Only on MK3/s
  4019. */
  4020. case 28:
  4021. {
  4022. long home_x_value = 0;
  4023. long home_y_value = 0;
  4024. long home_z_value = 0;
  4025. // Which axes should be homed?
  4026. bool home_x = code_seen(axis_codes[X_AXIS]);
  4027. if (home_x) home_x_value = code_value_long();
  4028. bool home_y = code_seen(axis_codes[Y_AXIS]);
  4029. if (home_y) home_y_value = code_value_long();
  4030. bool home_z = code_seen(axis_codes[Z_AXIS]);
  4031. if (home_z) home_z_value = code_value_long();
  4032. bool without_mbl = code_seen('W');
  4033. // calibrate?
  4034. #ifdef TMC2130
  4035. bool calib = code_seen('C');
  4036. gcode_G28(home_x, home_x_value, home_y, home_y_value, home_z, home_z_value, calib, without_mbl);
  4037. #else
  4038. gcode_G28(home_x, home_x_value, home_y, home_y_value, home_z, home_z_value, without_mbl);
  4039. #endif //TMC2130
  4040. if ((home_x || home_y || without_mbl || home_z) == false) {
  4041. gcode_G80();
  4042. }
  4043. break;
  4044. }
  4045. #ifdef ENABLE_AUTO_BED_LEVELING
  4046. /*!
  4047. ### G29 - Detailed Z-Probe <a href="https://reprap.org/wiki/G-code#G29:_Detailed_Z-Probe">G29: Detailed Z-Probe</a>
  4048. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4049. See `G81`
  4050. */
  4051. case 29:
  4052. {
  4053. #if Z_MIN_PIN == -1
  4054. #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."
  4055. #endif
  4056. // Prevent user from running a G29 without first homing in X and Y
  4057. if (! (axis_known_position[X_AXIS] && axis_known_position[Y_AXIS]) )
  4058. {
  4059. LCD_MESSAGERPGM(MSG_POSITION_UNKNOWN);
  4060. SERIAL_ECHO_START;
  4061. SERIAL_ECHOLNRPGM(MSG_POSITION_UNKNOWN);
  4062. break; // abort G29, since we don't know where we are
  4063. }
  4064. st_synchronize();
  4065. // make sure the bed_level_rotation_matrix is identity or the planner will get it incorectly
  4066. //vector_3 corrected_position = plan_get_position_mm();
  4067. //corrected_position.debug("position before G29");
  4068. plan_bed_level_matrix.set_to_identity();
  4069. vector_3 uncorrected_position = plan_get_position();
  4070. //uncorrected_position.debug("position durring G29");
  4071. current_position[X_AXIS] = uncorrected_position.x;
  4072. current_position[Y_AXIS] = uncorrected_position.y;
  4073. current_position[Z_AXIS] = uncorrected_position.z;
  4074. plan_set_position_curposXYZE();
  4075. int l_feedmultiply = setup_for_endstop_move();
  4076. feedrate = homing_feedrate[Z_AXIS];
  4077. #ifdef AUTO_BED_LEVELING_GRID
  4078. // probe at the points of a lattice grid
  4079. int xGridSpacing = (RIGHT_PROBE_BED_POSITION - LEFT_PROBE_BED_POSITION) / (AUTO_BED_LEVELING_GRID_POINTS-1);
  4080. int yGridSpacing = (BACK_PROBE_BED_POSITION - FRONT_PROBE_BED_POSITION) / (AUTO_BED_LEVELING_GRID_POINTS-1);
  4081. // solve the plane equation ax + by + d = z
  4082. // A is the matrix with rows [x y 1] for all the probed points
  4083. // B is the vector of the Z positions
  4084. // 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
  4085. // so Vx = -a Vy = -b Vz = 1 (we want the vector facing towards positive Z
  4086. // "A" matrix of the linear system of equations
  4087. double eqnAMatrix[AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS*3];
  4088. // "B" vector of Z points
  4089. double eqnBVector[AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS];
  4090. int probePointCounter = 0;
  4091. bool zig = true;
  4092. for (int yProbe=FRONT_PROBE_BED_POSITION; yProbe <= BACK_PROBE_BED_POSITION; yProbe += yGridSpacing)
  4093. {
  4094. int xProbe, xInc;
  4095. if (zig)
  4096. {
  4097. xProbe = LEFT_PROBE_BED_POSITION;
  4098. //xEnd = RIGHT_PROBE_BED_POSITION;
  4099. xInc = xGridSpacing;
  4100. zig = false;
  4101. } else // zag
  4102. {
  4103. xProbe = RIGHT_PROBE_BED_POSITION;
  4104. //xEnd = LEFT_PROBE_BED_POSITION;
  4105. xInc = -xGridSpacing;
  4106. zig = true;
  4107. }
  4108. for (int xCount=0; xCount < AUTO_BED_LEVELING_GRID_POINTS; xCount++)
  4109. {
  4110. float z_before;
  4111. if (probePointCounter == 0)
  4112. {
  4113. // raise before probing
  4114. z_before = Z_RAISE_BEFORE_PROBING;
  4115. } else
  4116. {
  4117. // raise extruder
  4118. z_before = current_position[Z_AXIS] + Z_RAISE_BETWEEN_PROBINGS;
  4119. }
  4120. float measured_z = probe_pt(xProbe, yProbe, z_before);
  4121. eqnBVector[probePointCounter] = measured_z;
  4122. eqnAMatrix[probePointCounter + 0*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = xProbe;
  4123. eqnAMatrix[probePointCounter + 1*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = yProbe;
  4124. eqnAMatrix[probePointCounter + 2*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = 1;
  4125. probePointCounter++;
  4126. xProbe += xInc;
  4127. }
  4128. }
  4129. clean_up_after_endstop_move(l_feedmultiply);
  4130. // solve lsq problem
  4131. double *plane_equation_coefficients = qr_solve(AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS, 3, eqnAMatrix, eqnBVector);
  4132. SERIAL_PROTOCOLPGM("Eqn coefficients: a: ");
  4133. SERIAL_PROTOCOL(plane_equation_coefficients[0]);
  4134. SERIAL_PROTOCOLPGM(" b: ");
  4135. SERIAL_PROTOCOL(plane_equation_coefficients[1]);
  4136. SERIAL_PROTOCOLPGM(" d: ");
  4137. SERIAL_PROTOCOLLN(plane_equation_coefficients[2]);
  4138. set_bed_level_equation_lsq(plane_equation_coefficients);
  4139. free(plane_equation_coefficients);
  4140. #else // AUTO_BED_LEVELING_GRID not defined
  4141. // Probe at 3 arbitrary points
  4142. // probe 1
  4143. float z_at_pt_1 = probe_pt(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, Z_RAISE_BEFORE_PROBING);
  4144. // probe 2
  4145. 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);
  4146. // probe 3
  4147. 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);
  4148. clean_up_after_endstop_move(l_feedmultiply);
  4149. set_bed_level_equation_3pts(z_at_pt_1, z_at_pt_2, z_at_pt_3);
  4150. #endif // AUTO_BED_LEVELING_GRID
  4151. st_synchronize();
  4152. // The following code correct the Z height difference from z-probe position and hotend tip position.
  4153. // The Z height on homing is measured by Z-Probe, but the probe is quite far from the hotend.
  4154. // When the bed is uneven, this height must be corrected.
  4155. 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)
  4156. x_tmp = current_position[X_AXIS] + X_PROBE_OFFSET_FROM_EXTRUDER;
  4157. y_tmp = current_position[Y_AXIS] + Y_PROBE_OFFSET_FROM_EXTRUDER;
  4158. z_tmp = current_position[Z_AXIS];
  4159. apply_rotation_xyz(plan_bed_level_matrix, x_tmp, y_tmp, z_tmp); //Apply the correction sending the probe offset
  4160. current_position[Z_AXIS] = z_tmp - real_z + current_position[Z_AXIS]; //The difference is added to current position and sent to planner.
  4161. plan_set_position_curposXYZE();
  4162. }
  4163. break;
  4164. #ifndef Z_PROBE_SLED
  4165. /*!
  4166. ### G30 - Single Z Probe <a href="https://reprap.org/wiki/G-code#G30:_Single_Z-Probe">G30: Single Z-Probe</a>
  4167. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4168. */
  4169. case 30:
  4170. {
  4171. st_synchronize();
  4172. // TODO: make sure the bed_level_rotation_matrix is identity or the planner will get set incorectly
  4173. int l_feedmultiply = setup_for_endstop_move();
  4174. feedrate = homing_feedrate[Z_AXIS];
  4175. run_z_probe();
  4176. SERIAL_PROTOCOLPGM(_T(MSG_BED));
  4177. SERIAL_PROTOCOLPGM(" X: ");
  4178. SERIAL_PROTOCOL(current_position[X_AXIS]);
  4179. SERIAL_PROTOCOLPGM(" Y: ");
  4180. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  4181. SERIAL_PROTOCOLPGM(" Z: ");
  4182. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  4183. SERIAL_PROTOCOLPGM("\n");
  4184. clean_up_after_endstop_move(l_feedmultiply);
  4185. }
  4186. break;
  4187. #else
  4188. /*!
  4189. ### G31 - Dock the sled <a href="https://reprap.org/wiki/G-code#G31:_Dock_Z_Probe_sled">G31: Dock Z Probe sled</a>
  4190. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4191. */
  4192. case 31:
  4193. dock_sled(true);
  4194. break;
  4195. /*!
  4196. ### G32 - Undock the sled <a href="https://reprap.org/wiki/G-code#G32:_Undock_Z_Probe_sled">G32: Undock Z Probe sled</a>
  4197. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4198. */
  4199. case 32:
  4200. dock_sled(false);
  4201. break;
  4202. #endif // Z_PROBE_SLED
  4203. #endif // ENABLE_AUTO_BED_LEVELING
  4204. #ifdef MESH_BED_LEVELING
  4205. /*!
  4206. ### G30 - Single Z Probe <a href="https://reprap.org/wiki/G-code#G30:_Single_Z-Probe">G30: Single Z-Probe</a>
  4207. Sensor must be over the bed.
  4208. The maximum travel distance before an error is triggered is 10mm.
  4209. */
  4210. case 30:
  4211. {
  4212. st_synchronize();
  4213. homing_flag = true;
  4214. // TODO: make sure the bed_level_rotation_matrix is identity or the planner will get set incorectly
  4215. int l_feedmultiply = setup_for_endstop_move();
  4216. feedrate = homing_feedrate[Z_AXIS];
  4217. find_bed_induction_sensor_point_z(-10.f, 3);
  4218. printf_P(_N("%S X: %.5f Y: %.5f Z: %.5f\n"), _T(MSG_BED), _x, _y, _z);
  4219. clean_up_after_endstop_move(l_feedmultiply);
  4220. homing_flag = false;
  4221. }
  4222. break;
  4223. /*!
  4224. ### G75 - Print temperature interpolation <a href="https://reprap.org/wiki/G-code#G75:_Print_temperature_interpolation">G75: Print temperature interpolation</a>
  4225. Show/print PINDA temperature interpolating.
  4226. */
  4227. case 75:
  4228. {
  4229. for (uint8_t i = 40; i <= 110; i++)
  4230. printf_P(_N("%d %.2f"), i, temp_comp_interpolation(i));
  4231. }
  4232. break;
  4233. /*!
  4234. ### G76 - PINDA probe temperature calibration <a href="https://reprap.org/wiki/G-code#G76:_PINDA_probe_temperature_calibration">G76: PINDA probe temperature calibration</a>
  4235. This G-code is used to calibrate the temperature drift of the PINDA (inductive Sensor).
  4236. The PINDAv2 sensor has a built-in thermistor which has the advantage that the calibration can be done once for all materials.
  4237. The Original i3 Prusa MK2/s uses PINDAv1 and this calibration improves the temperature drift, but not as good as the PINDAv2.
  4238. superPINDA sensor has internal temperature compensation and no thermistor output. There is no point of doing temperature calibration in such case.
  4239. If PINDA_THERMISTOR and SUPERPINDA_SUPPORT is defined during compilation, calibration is skipped with serial message "No PINDA thermistor".
  4240. This can be caused also if PINDA thermistor connection is broken or PINDA temperature is lower than PINDA_MINTEMP.
  4241. #### Example
  4242. ```
  4243. G76
  4244. echo PINDA probe calibration start
  4245. echo start temperature: 35.0°
  4246. echo ...
  4247. echo PINDA temperature -- Z shift (mm): 0.---
  4248. ```
  4249. */
  4250. case 76:
  4251. {
  4252. #ifdef PINDA_THERMISTOR
  4253. if (!has_temperature_compensation())
  4254. {
  4255. SERIAL_ECHOLNPGM("No PINDA thermistor");
  4256. break;
  4257. }
  4258. if (calibration_status() >= CALIBRATION_STATUS_XYZ_CALIBRATION) {
  4259. //we need to know accurate position of first calibration point
  4260. //if xyz calibration was not performed yet, interrupt temperature calibration and inform user that xyz cal. is needed
  4261. lcd_show_fullscreen_message_and_wait_P(_i("Please run XYZ calibration first.")); ////MSG_RUN_XYZ c=20 r=4
  4262. break;
  4263. }
  4264. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS]))
  4265. {
  4266. // We don't know where we are! HOME!
  4267. // Push the commands to the front of the message queue in the reverse order!
  4268. // There shall be always enough space reserved for these commands.
  4269. repeatcommand_front(); // repeat G76 with all its parameters
  4270. enquecommand_front_P(G28W0);
  4271. break;
  4272. }
  4273. 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
  4274. bool result = lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_STEEL_SHEET_CHECK), false, false);
  4275. if (result)
  4276. {
  4277. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4278. plan_buffer_line_curposXYZE(3000 / 60);
  4279. current_position[Z_AXIS] = 50;
  4280. current_position[Y_AXIS] = 180;
  4281. plan_buffer_line_curposXYZE(3000 / 60);
  4282. st_synchronize();
  4283. lcd_show_fullscreen_message_and_wait_P(_T(MSG_REMOVE_STEEL_SHEET));
  4284. current_position[Y_AXIS] = pgm_read_float(bed_ref_points_4 + 1);
  4285. current_position[X_AXIS] = pgm_read_float(bed_ref_points_4);
  4286. plan_buffer_line_curposXYZE(3000 / 60);
  4287. st_synchronize();
  4288. gcode_G28(false, false, true);
  4289. }
  4290. if ((current_temperature_pinda > 35) && (farm_mode == false)) {
  4291. //waiting for PIDNA probe to cool down in case that we are not in farm mode
  4292. current_position[Z_AXIS] = 100;
  4293. plan_buffer_line_curposXYZE(3000 / 60);
  4294. if (lcd_wait_for_pinda(35) == false) { //waiting for PINDA probe to cool, if this takes more then time expected, temp. cal. fails
  4295. lcd_temp_cal_show_result(false);
  4296. break;
  4297. }
  4298. }
  4299. st_synchronize();
  4300. homing_flag = true; // keep homing on to avoid babystepping while the LCD is enabled
  4301. lcd_update_enable(true);
  4302. SERIAL_ECHOLNPGM("PINDA probe calibration start");
  4303. float zero_z;
  4304. int z_shift = 0; //unit: steps
  4305. float start_temp = 5 * (int)(current_temperature_pinda / 5);
  4306. if (start_temp < 35) start_temp = 35;
  4307. if (start_temp < current_temperature_pinda) start_temp += 5;
  4308. printf_P(_N("start temperature: %.1f\n"), start_temp);
  4309. // setTargetHotend(200, 0);
  4310. setTargetBed(70 + (start_temp - 30));
  4311. custom_message_type = CustomMsg::TempCal;
  4312. custom_message_state = 1;
  4313. lcd_setstatuspgm(_T(MSG_PINDA_CALIBRATION));
  4314. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4315. plan_buffer_line_curposXYZE(3000 / 60);
  4316. current_position[X_AXIS] = PINDA_PREHEAT_X;
  4317. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  4318. plan_buffer_line_curposXYZE(3000 / 60);
  4319. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  4320. plan_buffer_line_curposXYZE(3000 / 60);
  4321. st_synchronize();
  4322. while (current_temperature_pinda < start_temp)
  4323. {
  4324. delay_keep_alive(1000);
  4325. serialecho_temperatures();
  4326. }
  4327. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0); //invalidate temp. calibration in case that in will be aborted during the calibration process
  4328. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4329. plan_buffer_line_curposXYZE(3000 / 60);
  4330. current_position[X_AXIS] = pgm_read_float(bed_ref_points_4);
  4331. current_position[Y_AXIS] = pgm_read_float(bed_ref_points_4 + 1);
  4332. plan_buffer_line_curposXYZE(3000 / 60);
  4333. st_synchronize();
  4334. bool find_z_result = find_bed_induction_sensor_point_z(-1.f);
  4335. if (find_z_result == false) {
  4336. lcd_temp_cal_show_result(find_z_result);
  4337. homing_flag = false;
  4338. break;
  4339. }
  4340. zero_z = current_position[Z_AXIS];
  4341. printf_P(_N("\nZERO: %.3f\n"), current_position[Z_AXIS]);
  4342. int i = -1; for (; i < 5; i++)
  4343. {
  4344. float temp = (40 + i * 5);
  4345. printf_P(_N("\nStep: %d/6 (skipped)\nPINDA temperature: %d Z shift (mm):0\n"), i + 2, (40 + i*5));
  4346. if (i >= 0) {
  4347. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  4348. }
  4349. if (start_temp <= temp) break;
  4350. }
  4351. for (i++; i < 5; i++)
  4352. {
  4353. float temp = (40 + i * 5);
  4354. printf_P(_N("\nStep: %d/6\n"), i + 2);
  4355. custom_message_state = i + 2;
  4356. setTargetBed(50 + 10 * (temp - 30) / 5);
  4357. // setTargetHotend(255, 0);
  4358. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4359. plan_buffer_line_curposXYZE(3000 / 60);
  4360. current_position[X_AXIS] = PINDA_PREHEAT_X;
  4361. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  4362. plan_buffer_line_curposXYZE(3000 / 60);
  4363. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  4364. plan_buffer_line_curposXYZE(3000 / 60);
  4365. st_synchronize();
  4366. while (current_temperature_pinda < temp)
  4367. {
  4368. delay_keep_alive(1000);
  4369. serialecho_temperatures();
  4370. }
  4371. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4372. plan_buffer_line_curposXYZE(3000 / 60);
  4373. current_position[X_AXIS] = pgm_read_float(bed_ref_points_4);
  4374. current_position[Y_AXIS] = pgm_read_float(bed_ref_points_4 + 1);
  4375. plan_buffer_line_curposXYZE(3000 / 60);
  4376. st_synchronize();
  4377. find_z_result = find_bed_induction_sensor_point_z(-1.f);
  4378. if (find_z_result == false) {
  4379. lcd_temp_cal_show_result(find_z_result);
  4380. break;
  4381. }
  4382. z_shift = (int)((current_position[Z_AXIS] - zero_z)*cs.axis_steps_per_unit[Z_AXIS]);
  4383. printf_P(_N("\nPINDA temperature: %.1f Z shift (mm): %.3f"), current_temperature_pinda, current_position[Z_AXIS] - zero_z);
  4384. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  4385. }
  4386. lcd_temp_cal_show_result(true);
  4387. homing_flag = false;
  4388. #else //PINDA_THERMISTOR
  4389. setTargetBed(PINDA_MIN_T);
  4390. float zero_z;
  4391. int z_shift = 0; //unit: steps
  4392. int t_c; // temperature
  4393. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  4394. // We don't know where we are! HOME!
  4395. // Push the commands to the front of the message queue in the reverse order!
  4396. // There shall be always enough space reserved for these commands.
  4397. repeatcommand_front(); // repeat G76 with all its parameters
  4398. enquecommand_front_P(G28W0);
  4399. break;
  4400. }
  4401. puts_P(_N("PINDA probe calibration start"));
  4402. custom_message_type = CustomMsg::TempCal;
  4403. custom_message_state = 1;
  4404. lcd_setstatuspgm(_T(MSG_PINDA_CALIBRATION));
  4405. current_position[X_AXIS] = PINDA_PREHEAT_X;
  4406. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  4407. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  4408. plan_buffer_line_curposXYZE(3000 / 60);
  4409. st_synchronize();
  4410. while (fabs(degBed() - PINDA_MIN_T) > 1) {
  4411. delay_keep_alive(1000);
  4412. serialecho_temperatures();
  4413. }
  4414. //enquecommand_P(PSTR("M190 S50"));
  4415. for (int i = 0; i < PINDA_HEAT_T; i++) {
  4416. delay_keep_alive(1000);
  4417. serialecho_temperatures();
  4418. }
  4419. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0); //invalidate temp. calibration in case that in will be aborted during the calibration process
  4420. current_position[Z_AXIS] = 5;
  4421. plan_buffer_line_curposXYZE(3000 / 60);
  4422. current_position[X_AXIS] = BED_X0;
  4423. current_position[Y_AXIS] = BED_Y0;
  4424. plan_buffer_line_curposXYZE(3000 / 60);
  4425. st_synchronize();
  4426. find_bed_induction_sensor_point_z(-1.f);
  4427. zero_z = current_position[Z_AXIS];
  4428. printf_P(_N("\nZERO: %.3f\n"), current_position[Z_AXIS]);
  4429. for (int i = 0; i<5; i++) {
  4430. printf_P(_N("\nStep: %d/6\n"), i + 2);
  4431. custom_message_state = i + 2;
  4432. t_c = 60 + i * 10;
  4433. setTargetBed(t_c);
  4434. current_position[X_AXIS] = PINDA_PREHEAT_X;
  4435. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  4436. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  4437. plan_buffer_line_curposXYZE(3000 / 60);
  4438. st_synchronize();
  4439. while (degBed() < t_c) {
  4440. delay_keep_alive(1000);
  4441. serialecho_temperatures();
  4442. }
  4443. for (int i = 0; i < PINDA_HEAT_T; i++) {
  4444. delay_keep_alive(1000);
  4445. serialecho_temperatures();
  4446. }
  4447. current_position[Z_AXIS] = 5;
  4448. plan_buffer_line_curposXYZE(3000 / 60);
  4449. current_position[X_AXIS] = BED_X0;
  4450. current_position[Y_AXIS] = BED_Y0;
  4451. plan_buffer_line_curposXYZE(3000 / 60);
  4452. st_synchronize();
  4453. find_bed_induction_sensor_point_z(-1.f);
  4454. z_shift = (int)((current_position[Z_AXIS] - zero_z)*cs.axis_steps_per_unit[Z_AXIS]);
  4455. printf_P(_N("\nTemperature: %d Z shift (mm): %.3f\n"), t_c, current_position[Z_AXIS] - zero_z);
  4456. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  4457. }
  4458. custom_message_type = CustomMsg::Status;
  4459. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  4460. puts_P(_N("Temperature calibration done."));
  4461. disable_x();
  4462. disable_y();
  4463. disable_z();
  4464. disable_e0();
  4465. disable_e1();
  4466. disable_e2();
  4467. setTargetBed(0); //set bed target temperature back to 0
  4468. lcd_show_fullscreen_message_and_wait_P(_T(MSG_PINDA_CALIBRATION_DONE));
  4469. eeprom_update_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE, 1);
  4470. lcd_update_enable(true);
  4471. lcd_update(2);
  4472. #endif //PINDA_THERMISTOR
  4473. }
  4474. break;
  4475. /*!
  4476. ### G80 - Mesh-based Z probe <a href="https://reprap.org/wiki/G-code#G80:_Mesh-based_Z_probe">G80: Mesh-based Z probe</a>
  4477. Default 3x3 grid can be changed on MK2.5/s and MK3/s to 7x7 grid.
  4478. #### Usage
  4479. G80 [ N | R | V | L | R | F | B ]
  4480. #### Parameters
  4481. - `N` - Number of mesh points on x axis. Default is 3. Valid values are 3 and 7.
  4482. - `R` - Probe retries. Default 3 max. 10
  4483. - `V` - Verbosity level 1=low, 10=mid, 20=high. It only can be used if the firmware has been compiled with SUPPORT_VERBOSITY active.
  4484. Using the following parameters enables additional "manual" bed leveling correction. Valid values are -100 microns to 100 microns.
  4485. #### Additional Parameters
  4486. - `L` - Left Bed Level correct value in um.
  4487. - `R` - Right Bed Level correct value in um.
  4488. - `F` - Front Bed Level correct value in um.
  4489. - `B` - Back Bed Level correct value in um.
  4490. */
  4491. /*
  4492. * Probes a grid and produces a mesh to compensate for variable bed height
  4493. * The S0 report the points as below
  4494. * +----> X-axis
  4495. * |
  4496. * |
  4497. * v Y-axis
  4498. */
  4499. case 80: {
  4500. gcode_G80();
  4501. }
  4502. break;
  4503. /*!
  4504. ### G81 - Mesh bed leveling status <a href="https://reprap.org/wiki/G-code#G81:_Mesh_bed_leveling_status">G81: Mesh bed leveling status</a>
  4505. Prints mesh bed leveling status and bed profile if activated.
  4506. */
  4507. case 81:
  4508. if (mbl.active) {
  4509. SERIAL_PROTOCOLPGM("Num X,Y: ");
  4510. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  4511. SERIAL_PROTOCOL(',');
  4512. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  4513. SERIAL_PROTOCOLPGM("\nZ search height: ");
  4514. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  4515. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  4516. for (uint8_t y = MESH_NUM_Y_POINTS; y-- > 0;) {
  4517. for (uint8_t x = 0; x < MESH_NUM_X_POINTS; x++) {
  4518. SERIAL_PROTOCOLPGM(" ");
  4519. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  4520. }
  4521. SERIAL_PROTOCOLLN();
  4522. }
  4523. }
  4524. else
  4525. SERIAL_PROTOCOLLNPGM("Mesh bed leveling not active.");
  4526. break;
  4527. #if 0
  4528. /*!
  4529. ### 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>
  4530. WARNING! USE WITH CAUTION! If you'll try to probe where is no leveling pad, nasty things can happen!
  4531. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4532. */
  4533. case 82:
  4534. SERIAL_PROTOCOLLNPGM("Finding bed ");
  4535. int l_feedmultiply = setup_for_endstop_move();
  4536. find_bed_induction_sensor_point_z();
  4537. clean_up_after_endstop_move(l_feedmultiply);
  4538. SERIAL_PROTOCOLPGM("Bed found at: ");
  4539. SERIAL_PROTOCOL_F(current_position[Z_AXIS], 5);
  4540. SERIAL_PROTOCOLPGM("\n");
  4541. break;
  4542. /*!
  4543. ### 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>
  4544. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4545. */
  4546. case 83:
  4547. {
  4548. int babystepz = code_seen('S') ? code_value() : 0;
  4549. int BabyPosition = code_seen('P') ? code_value() : 0;
  4550. if (babystepz != 0) {
  4551. //FIXME Vojtech: What shall be the index of the axis Z: 3 or 4?
  4552. // Is the axis indexed starting with zero or one?
  4553. if (BabyPosition > 4) {
  4554. SERIAL_PROTOCOLLNPGM("Index out of bounds");
  4555. }else{
  4556. // Save it to the eeprom
  4557. babystepLoadZ = babystepz;
  4558. eeprom_update_word((uint16_t*)EEPROM_BABYSTEP_Z0 + BabyPosition, babystepLoadZ);
  4559. // adjust the Z
  4560. babystepsTodoZadd(babystepLoadZ);
  4561. }
  4562. }
  4563. }
  4564. break;
  4565. /*!
  4566. ### 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>
  4567. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4568. */
  4569. case 84:
  4570. babystepsTodoZsubtract(babystepLoadZ);
  4571. // babystepLoadZ = 0;
  4572. break;
  4573. /*!
  4574. ### G85: Pick best babystep - Not active <a href="https://reprap.org/wiki/G-code#G85:_Pick_best_babystep">G85: Pick best babystep</a>
  4575. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  4576. */
  4577. case 85:
  4578. lcd_pick_babystep();
  4579. break;
  4580. #endif
  4581. /*!
  4582. ### 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>
  4583. This G-code will be performed at the start of a calibration script.
  4584. (Prusa3D specific)
  4585. */
  4586. case 86:
  4587. calibration_status_store(CALIBRATION_STATUS_LIVE_ADJUST);
  4588. break;
  4589. /*!
  4590. ### 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>
  4591. This G-code will be performed at the end of a calibration script.
  4592. (Prusa3D specific)
  4593. */
  4594. case 87:
  4595. calibration_status_store(CALIBRATION_STATUS_CALIBRATED);
  4596. break;
  4597. /*!
  4598. ### G88 - Reserved <a href="https://reprap.org/wiki/G-code#G88:_Reserved">G88: Reserved</a>
  4599. Currently has no effect.
  4600. */
  4601. // Prusa3D specific: Don't know what it is for, it is in V2Calibration.gcode
  4602. case 88:
  4603. break;
  4604. #endif // ENABLE_MESH_BED_LEVELING
  4605. /*!
  4606. ### G90 - Switch off relative mode <a href="https://reprap.org/wiki/G-code#G90:_Set_to_Absolute_Positioning">G90: Set to Absolute Positioning</a>
  4607. All coordinates from now on are absolute relative to the origin of the machine. E axis is left intact.
  4608. */
  4609. case 90: {
  4610. axis_relative_modes &= ~(X_AXIS_MASK | Y_AXIS_MASK | Z_AXIS_MASK);
  4611. }
  4612. break;
  4613. /*!
  4614. ### G91 - Switch on relative mode <a href="https://reprap.org/wiki/G-code#G91:_Set_to_Relative_Positioning">G91: Set to Relative Positioning</a>
  4615. All coordinates from now on are relative to the last position. E axis is left intact.
  4616. */
  4617. case 91: {
  4618. axis_relative_modes |= X_AXIS_MASK | Y_AXIS_MASK | Z_AXIS_MASK;
  4619. }
  4620. break;
  4621. /*!
  4622. ### G92 - Set position <a href="https://reprap.org/wiki/G-code#G92:_Set_Position">G92: Set Position</a>
  4623. It is used for setting the current position of each axis. The parameters are always absolute to the origin.
  4624. If a parameter is omitted, that axis will not be affected.
  4625. 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`).
  4626. A G92 without coordinates will reset all axes to zero on some firmware. This is not the case for Prusa-Firmware!
  4627. #### Usage
  4628. G92 [ X | Y | Z | E ]
  4629. #### Parameters
  4630. - `X` - new X axis position
  4631. - `Y` - new Y axis position
  4632. - `Z` - new Z axis position
  4633. - `E` - new extruder position
  4634. */
  4635. case 92: {
  4636. gcode_G92();
  4637. }
  4638. break;
  4639. #ifdef PRUSA_FARM
  4640. /*!
  4641. ### G98 - Activate farm mode <a href="https://reprap.org/wiki/G-code#G98:_Activate_farm_mode">G98: Activate farm mode</a>
  4642. Enable Prusa-specific Farm functions and g-code.
  4643. See Internal Prusa commands.
  4644. */
  4645. case 98:
  4646. farm_gcode_g98();
  4647. break;
  4648. /*! ### G99 - Deactivate farm mode <a href="https://reprap.org/wiki/G-code#G99:_Deactivate_farm_mode">G99: Deactivate farm mode</a>
  4649. Disables Prusa-specific Farm functions and g-code.
  4650. */
  4651. case 99:
  4652. farm_gcode_g99();
  4653. break;
  4654. #endif //PRUSA_FARM
  4655. default:
  4656. printf_P(MSG_UNKNOWN_CODE, 'G', cmdbuffer + bufindr + CMDHDRSIZE);
  4657. }
  4658. // printf_P(_N("END G-CODE=%u\n"), gcode_in_progress);
  4659. gcode_in_progress = 0;
  4660. } // end if(code_seen('G'))
  4661. /*!
  4662. ### End of G-Codes
  4663. */
  4664. /*!
  4665. ---------------------------------------------------------------------------------
  4666. # M Commands
  4667. */
  4668. else if(code_seen('M'))
  4669. {
  4670. int index;
  4671. for (index = 1; *(strchr_pointer + index) == ' ' || *(strchr_pointer + index) == '\t'; index++);
  4672. /*for (++strchr_pointer; *strchr_pointer == ' ' || *strchr_pointer == '\t'; ++strchr_pointer);*/
  4673. if (*(strchr_pointer+index) < '0' || *(strchr_pointer+index) > '9') {
  4674. printf_P(PSTR("Invalid M code: %s\n"), cmdbuffer + bufindr + CMDHDRSIZE);
  4675. } else
  4676. {
  4677. mcode_in_progress = code_value_short();
  4678. // printf_P(_N("BEGIN M-CODE=%u\n"), mcode_in_progress);
  4679. switch(mcode_in_progress)
  4680. {
  4681. /*!
  4682. ### 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>
  4683. */
  4684. case 17:
  4685. LCD_MESSAGERPGM(_i("No move."));////MSG_NO_MOVE c=20
  4686. enable_x();
  4687. enable_y();
  4688. enable_z();
  4689. enable_e0();
  4690. enable_e1();
  4691. enable_e2();
  4692. break;
  4693. #ifdef SDSUPPORT
  4694. /*!
  4695. ### M20 - SD Card file list <a href="https://reprap.org/wiki/G-code#M20:_List_SD_card">M20: List SD card</a>
  4696. #### Usage
  4697. M20 [ L | T ]
  4698. #### Parameters
  4699. - `T` - Report timestamps as well. The value is one uint32_t encoded as hex. Requires host software parsing (Cap:EXTENDED_M20).
  4700. - `L` - Reports long filenames instead of just short filenames. Requires host software parsing (Cap:EXTENDED_M20).
  4701. */
  4702. case 20:
  4703. KEEPALIVE_STATE(NOT_BUSY); // do not send busy messages during listing. Inhibits the output of manage_heater()
  4704. SERIAL_PROTOCOLLNRPGM(_N("Begin file list"));////MSG_BEGIN_FILE_LIST
  4705. card.ls(CardReader::ls_param(code_seen('L'), code_seen('T')));
  4706. SERIAL_PROTOCOLLNRPGM(_N("End file list"));////MSG_END_FILE_LIST
  4707. break;
  4708. /*!
  4709. ### M21 - Init SD card <a href="https://reprap.org/wiki/G-code#M21:_Initialize_SD_card">M21: Initialize SD card</a>
  4710. */
  4711. case 21:
  4712. card.initsd();
  4713. break;
  4714. /*!
  4715. ### M22 - Release SD card <a href="https://reprap.org/wiki/G-code#M22:_Release_SD_card">M22: Release SD card</a>
  4716. */
  4717. case 22:
  4718. card.release();
  4719. break;
  4720. /*!
  4721. ### M23 - Select file <a href="https://reprap.org/wiki/G-code#M23:_Select_SD_file">M23: Select SD file</a>
  4722. #### Usage
  4723. M23 [filename]
  4724. */
  4725. case 23:
  4726. starpos = (strchr(strchr_pointer + 4,'*'));
  4727. if(starpos!=NULL)
  4728. *(starpos)='\0';
  4729. card.openFileReadFilteredGcode(strchr_pointer + 4, true);
  4730. break;
  4731. /*!
  4732. ### M24 - Start SD print <a href="https://reprap.org/wiki/G-code#M24:_Start.2Fresume_SD_print">M24: Start/resume SD print</a>
  4733. */
  4734. case 24:
  4735. if (isPrintPaused)
  4736. lcd_resume_print();
  4737. else
  4738. {
  4739. if (!card.get_sdpos())
  4740. {
  4741. // A new print has started from scratch, reset stats
  4742. failstats_reset_print();
  4743. sdpos_atomic = 0;
  4744. #ifndef LA_NOCOMPAT
  4745. la10c_reset();
  4746. #endif
  4747. }
  4748. card.startFileprint();
  4749. starttime=_millis();
  4750. }
  4751. break;
  4752. /*!
  4753. ### M26 - Set SD index <a href="https://reprap.org/wiki/G-code#M26:_Set_SD_position">M26: Set SD position</a>
  4754. Set position in SD card file to index in bytes.
  4755. This command is expected to be called after M23 and before M24.
  4756. Otherwise effect of this command is undefined.
  4757. #### Usage
  4758. M26 [ S ]
  4759. #### Parameters
  4760. - `S` - Index in bytes
  4761. */
  4762. case 26:
  4763. if(card.cardOK && code_seen('S')) {
  4764. long index = code_value_long();
  4765. card.setIndex(index);
  4766. // We don't disable interrupt during update of sdpos_atomic
  4767. // as we expect, that SD card print is not active in this moment
  4768. sdpos_atomic = index;
  4769. }
  4770. break;
  4771. /*!
  4772. ### M27 - Get SD status <a href="https://reprap.org/wiki/G-code#M27:_Report_SD_print_status">M27: Report SD print status</a>
  4773. #### Usage
  4774. M27 [ P ]
  4775. #### Parameters
  4776. - `P` - Show full SFN path instead of LFN only.
  4777. */
  4778. case 27:
  4779. card.getStatus(code_seen('P'));
  4780. break;
  4781. /*!
  4782. ### 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>
  4783. */
  4784. case 28:
  4785. starpos = (strchr(strchr_pointer + 4,'*'));
  4786. if(starpos != NULL){
  4787. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  4788. strchr_pointer = strchr(npos,' ') + 1;
  4789. *(starpos) = '\0';
  4790. }
  4791. card.openFileWrite(strchr_pointer+4);
  4792. break;
  4793. /*! ### 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>
  4794. 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.
  4795. */
  4796. case 29:
  4797. //processed in write to file routine above
  4798. //card,saving = false;
  4799. break;
  4800. /*!
  4801. ### 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>
  4802. #### Usage
  4803. M30 [filename]
  4804. */
  4805. case 30:
  4806. if (card.cardOK){
  4807. card.closefile();
  4808. starpos = (strchr(strchr_pointer + 4,'*'));
  4809. if(starpos != NULL){
  4810. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  4811. strchr_pointer = strchr(npos,' ') + 1;
  4812. *(starpos) = '\0';
  4813. }
  4814. card.removeFile(strchr_pointer + 4);
  4815. }
  4816. break;
  4817. /*!
  4818. ### 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>
  4819. @todo What are the parameters P and S for in M32?
  4820. */
  4821. case 32:
  4822. {
  4823. if(card.sdprinting) {
  4824. st_synchronize();
  4825. }
  4826. starpos = (strchr(strchr_pointer + 4,'*'));
  4827. const char* namestartpos = (strchr(strchr_pointer + 4,'!')); //find ! to indicate filename string start.
  4828. if(namestartpos==NULL)
  4829. {
  4830. namestartpos=strchr_pointer + 4; //default name position, 4 letters after the M
  4831. }
  4832. else
  4833. namestartpos++; //to skip the '!'
  4834. if(starpos!=NULL)
  4835. *(starpos)='\0';
  4836. bool call_procedure=(code_seen('P'));
  4837. if(strchr_pointer>namestartpos)
  4838. call_procedure=false; //false alert, 'P' found within filename
  4839. if( card.cardOK )
  4840. {
  4841. card.openFileReadFilteredGcode(namestartpos,!call_procedure);
  4842. if(code_seen('S'))
  4843. if(strchr_pointer<namestartpos) //only if "S" is occuring _before_ the filename
  4844. card.setIndex(code_value_long());
  4845. card.startFileprint();
  4846. if(!call_procedure)
  4847. {
  4848. if(!card.get_sdpos())
  4849. {
  4850. // A new print has started from scratch, reset stats
  4851. failstats_reset_print();
  4852. sdpos_atomic = 0;
  4853. #ifndef LA_NOCOMPAT
  4854. la10c_reset();
  4855. #endif
  4856. }
  4857. starttime=_millis(); // procedure calls count as normal print time.
  4858. }
  4859. }
  4860. } break;
  4861. /*!
  4862. ### M928 - Start SD logging <a href="https://reprap.org/wiki/G-code#M928:_Start_SD_logging">M928: Start SD logging</a>
  4863. #### Usage
  4864. M928 [filename]
  4865. */
  4866. case 928:
  4867. starpos = (strchr(strchr_pointer + 5,'*'));
  4868. if(starpos != NULL){
  4869. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  4870. strchr_pointer = strchr(npos,' ') + 1;
  4871. *(starpos) = '\0';
  4872. }
  4873. card.openLogFile(strchr_pointer+5);
  4874. break;
  4875. #endif //SDSUPPORT
  4876. /*!
  4877. ### 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>
  4878. */
  4879. case 31: //M31 take time since the start of the SD print or an M109 command
  4880. {
  4881. stoptime=_millis();
  4882. char time[30];
  4883. unsigned long t=(stoptime-starttime)/1000;
  4884. int sec,min;
  4885. min=t/60;
  4886. sec=t%60;
  4887. sprintf_P(time, PSTR("%i min, %i sec"), min, sec);
  4888. SERIAL_ECHO_START;
  4889. SERIAL_ECHOLN(time);
  4890. lcd_setstatus(time);
  4891. autotempShutdown();
  4892. }
  4893. break;
  4894. /*!
  4895. ### M42 - Set pin state <a href="https://reprap.org/wiki/G-code#M42:_Switch_I.2FO_pin">M42: Switch I/O pin</a>
  4896. #### Usage
  4897. M42 [ P | S ]
  4898. #### Parameters
  4899. - `P` - Pin number.
  4900. - `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.
  4901. */
  4902. case 42:
  4903. if (code_seen('S'))
  4904. {
  4905. uint8_t pin_status = code_value_uint8();
  4906. int8_t pin_number = LED_PIN;
  4907. if (code_seen('P'))
  4908. pin_number = code_value_uint8();
  4909. for(int8_t i = 0; i < (int8_t)(sizeof(sensitive_pins)/sizeof(sensitive_pins[0])); i++)
  4910. {
  4911. if ((int8_t)pgm_read_byte(&sensitive_pins[i]) == pin_number)
  4912. {
  4913. pin_number = -1;
  4914. break;
  4915. }
  4916. }
  4917. #if defined(FAN_PIN) && FAN_PIN > -1
  4918. if (pin_number == FAN_PIN)
  4919. fanSpeed = pin_status;
  4920. #endif
  4921. if (pin_number > -1)
  4922. {
  4923. pinMode(pin_number, OUTPUT);
  4924. digitalWrite(pin_number, pin_status);
  4925. analogWrite(pin_number, pin_status);
  4926. }
  4927. }
  4928. break;
  4929. /*!
  4930. ### 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>
  4931. */
  4932. case 44: // M44: Prusa3D: Reset the bed skew and offset calibration.
  4933. // Reset the baby step value and the baby step applied flag.
  4934. calibration_status_store(CALIBRATION_STATUS_ASSEMBLED);
  4935. eeprom_update_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),0);
  4936. // Reset the skew and offset in both RAM and EEPROM.
  4937. reset_bed_offset_and_skew();
  4938. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  4939. // the planner will not perform any adjustments in the XY plane.
  4940. // Wait for the motors to stop and update the current position with the absolute values.
  4941. world2machine_revert_to_uncorrected();
  4942. break;
  4943. /*!
  4944. ### 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>
  4945. #### Usage
  4946. M45 [ V ]
  4947. #### Parameters
  4948. - `V` - Verbosity level 1, 10 and 20 (low, mid, high). Only when SUPPORT_VERBOSITY is defined. Optional.
  4949. - `Z` - If it is provided, only Z calibration will run. Otherwise full calibration is executed.
  4950. */
  4951. case 45: // M45: Prusa3D: bed skew and offset with manual Z up
  4952. {
  4953. int8_t verbosity_level = 0;
  4954. bool only_Z = code_seen('Z');
  4955. #ifdef SUPPORT_VERBOSITY
  4956. if (code_seen('V'))
  4957. {
  4958. // Just 'V' without a number counts as V1.
  4959. char c = strchr_pointer[1];
  4960. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  4961. }
  4962. #endif //SUPPORT_VERBOSITY
  4963. gcode_M45(only_Z, verbosity_level);
  4964. }
  4965. break;
  4966. /*!
  4967. ### 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>
  4968. */
  4969. case 46:
  4970. {
  4971. // M46: Prusa3D: Show the assigned IP address.
  4972. if (card.ToshibaFlashAir_isEnabled()) {
  4973. uint8_t ip[4];
  4974. if (card.ToshibaFlashAir_GetIP(ip)) {
  4975. // SERIAL_PROTOCOLPGM("Toshiba FlashAir current IP: ");
  4976. SERIAL_PROTOCOL(uint8_t(ip[0]));
  4977. SERIAL_PROTOCOL('.');
  4978. SERIAL_PROTOCOL(uint8_t(ip[1]));
  4979. SERIAL_PROTOCOL('.');
  4980. SERIAL_PROTOCOL(uint8_t(ip[2]));
  4981. SERIAL_PROTOCOL('.');
  4982. SERIAL_PROTOCOLLN(uint8_t(ip[3]));
  4983. } else {
  4984. SERIAL_PROTOCOLPGM("?Toshiba FlashAir GetIP failed\n");
  4985. }
  4986. } else {
  4987. SERIAL_PROTOCOLLNPGM("n/a");
  4988. }
  4989. break;
  4990. }
  4991. /*!
  4992. ### 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>
  4993. */
  4994. case 47:
  4995. KEEPALIVE_STATE(PAUSED_FOR_USER);
  4996. lcd_diag_show_end_stops();
  4997. KEEPALIVE_STATE(IN_HANDLER);
  4998. break;
  4999. #if 0
  5000. case 48: // M48: scan the bed induction sensor points, print the sensor trigger coordinates to the serial line for visualization on the PC.
  5001. {
  5002. // Disable the default update procedure of the display. We will do a modal dialog.
  5003. lcd_update_enable(false);
  5004. // Let the planner use the uncorrected coordinates.
  5005. mbl.reset();
  5006. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  5007. // the planner will not perform any adjustments in the XY plane.
  5008. // Wait for the motors to stop and update the current position with the absolute values.
  5009. world2machine_revert_to_uncorrected();
  5010. // Move the print head close to the bed.
  5011. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  5012. 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);
  5013. st_synchronize();
  5014. // Home in the XY plane.
  5015. set_destination_to_current();
  5016. int l_feedmultiply = setup_for_endstop_move();
  5017. home_xy();
  5018. int8_t verbosity_level = 0;
  5019. if (code_seen('V')) {
  5020. // Just 'V' without a number counts as V1.
  5021. char c = strchr_pointer[1];
  5022. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  5023. }
  5024. bool success = scan_bed_induction_points(verbosity_level);
  5025. clean_up_after_endstop_move(l_feedmultiply);
  5026. // Print head up.
  5027. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  5028. 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);
  5029. st_synchronize();
  5030. lcd_update_enable(true);
  5031. break;
  5032. }
  5033. #endif
  5034. #ifdef ENABLE_AUTO_BED_LEVELING
  5035. #ifdef Z_PROBE_REPEATABILITY_TEST
  5036. /*!
  5037. ### 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>
  5038. 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.
  5039. 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.
  5040. @todo Why would you check for both uppercase and lowercase? Seems wasteful.
  5041. #### Usage
  5042. M48 [ n | X | Y | V | L ]
  5043. #### Parameters
  5044. - `n` - Number of samples. Valid values 4-50
  5045. - `X` - X position for samples
  5046. - `Y` - Y position for samples
  5047. - `V` - Verbose level. Valid values 1-4
  5048. - `L` - Legs of movementprior to doing probe. Valid values 1-15
  5049. */
  5050. case 48: // M48 Z-Probe repeatability
  5051. {
  5052. #if Z_MIN_PIN == -1
  5053. #error "You must have a Z_MIN endstop in order to enable calculation of Z-Probe repeatability."
  5054. #endif
  5055. double sum=0.0;
  5056. double mean=0.0;
  5057. double sigma=0.0;
  5058. double sample_set[50];
  5059. int verbose_level=1, n=0, j, n_samples = 10, n_legs=0;
  5060. double X_current, Y_current, Z_current;
  5061. double X_probe_location, Y_probe_location, Z_start_location, ext_position;
  5062. if (code_seen('V') || code_seen('v')) {
  5063. verbose_level = code_value();
  5064. if (verbose_level<0 || verbose_level>4 ) {
  5065. SERIAL_PROTOCOLPGM("?Verbose Level not plausable.\n");
  5066. goto Sigma_Exit;
  5067. }
  5068. }
  5069. if (verbose_level > 0) {
  5070. SERIAL_PROTOCOLPGM("M48 Z-Probe Repeatability test. Version 2.00\n");
  5071. SERIAL_PROTOCOLPGM("Full support at: http://3dprintboard.com/forum.php\n");
  5072. }
  5073. if (code_seen('n')) {
  5074. n_samples = code_value();
  5075. if (n_samples<4 || n_samples>50 ) {
  5076. SERIAL_PROTOCOLPGM("?Specified sample size not plausable.\n");
  5077. goto Sigma_Exit;
  5078. }
  5079. }
  5080. X_current = X_probe_location = st_get_position_mm(X_AXIS);
  5081. Y_current = Y_probe_location = st_get_position_mm(Y_AXIS);
  5082. Z_current = st_get_position_mm(Z_AXIS);
  5083. Z_start_location = st_get_position_mm(Z_AXIS) + Z_RAISE_BEFORE_PROBING;
  5084. ext_position = st_get_position_mm(E_AXIS);
  5085. if (code_seen('X') || code_seen('x') ) {
  5086. X_probe_location = code_value() - X_PROBE_OFFSET_FROM_EXTRUDER;
  5087. if (X_probe_location<X_MIN_POS || X_probe_location>X_MAX_POS ) {
  5088. SERIAL_PROTOCOLPGM("?Specified X position out of range.\n");
  5089. goto Sigma_Exit;
  5090. }
  5091. }
  5092. if (code_seen('Y') || code_seen('y') ) {
  5093. Y_probe_location = code_value() - Y_PROBE_OFFSET_FROM_EXTRUDER;
  5094. if (Y_probe_location<Y_MIN_POS || Y_probe_location>Y_MAX_POS ) {
  5095. SERIAL_PROTOCOLPGM("?Specified Y position out of range.\n");
  5096. goto Sigma_Exit;
  5097. }
  5098. }
  5099. if (code_seen('L') || code_seen('l') ) {
  5100. n_legs = code_value();
  5101. if ( n_legs==1 )
  5102. n_legs = 2;
  5103. if ( n_legs<0 || n_legs>15 ) {
  5104. SERIAL_PROTOCOLPGM("?Specified number of legs in movement not plausable.\n");
  5105. goto Sigma_Exit;
  5106. }
  5107. }
  5108. //
  5109. // Do all the preliminary setup work. First raise the probe.
  5110. //
  5111. st_synchronize();
  5112. plan_bed_level_matrix.set_to_identity();
  5113. plan_buffer_line( X_current, Y_current, Z_start_location,
  5114. ext_position,
  5115. homing_feedrate[Z_AXIS]/60,
  5116. active_extruder);
  5117. st_synchronize();
  5118. //
  5119. // Now get everything to the specified probe point So we can safely do a probe to
  5120. // get us close to the bed. If the Z-Axis is far from the bed, we don't want to
  5121. // use that as a starting point for each probe.
  5122. //
  5123. if (verbose_level > 2)
  5124. SERIAL_PROTOCOL("Positioning probe for the test.\n");
  5125. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  5126. ext_position,
  5127. homing_feedrate[X_AXIS]/60,
  5128. active_extruder);
  5129. st_synchronize();
  5130. current_position[X_AXIS] = X_current = st_get_position_mm(X_AXIS);
  5131. current_position[Y_AXIS] = Y_current = st_get_position_mm(Y_AXIS);
  5132. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  5133. current_position[E_AXIS] = ext_position = st_get_position_mm(E_AXIS);
  5134. //
  5135. // OK, do the inital probe to get us close to the bed.
  5136. // Then retrace the right amount and use that in subsequent probes
  5137. //
  5138. int l_feedmultiply = setup_for_endstop_move();
  5139. run_z_probe();
  5140. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  5141. Z_start_location = st_get_position_mm(Z_AXIS) + Z_RAISE_BEFORE_PROBING;
  5142. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  5143. ext_position,
  5144. homing_feedrate[X_AXIS]/60,
  5145. active_extruder);
  5146. st_synchronize();
  5147. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  5148. for( n=0; n<n_samples; n++) {
  5149. do_blocking_move_to( X_probe_location, Y_probe_location, Z_start_location); // Make sure we are at the probe location
  5150. if ( n_legs) {
  5151. double radius=0.0, theta=0.0, x_sweep, y_sweep;
  5152. int rotational_direction, l;
  5153. rotational_direction = (unsigned long) _millis() & 0x0001; // clockwise or counter clockwise
  5154. radius = (unsigned long) _millis() % (long) (X_MAX_LENGTH/4); // limit how far out to go
  5155. theta = (float) ((unsigned long) _millis() % (long) 360) / (360./(2*3.1415926)); // turn into radians
  5156. //SERIAL_ECHOPAIR("starting radius: ",radius);
  5157. //SERIAL_ECHOPAIR(" theta: ",theta);
  5158. //SERIAL_ECHOPAIR(" direction: ",rotational_direction);
  5159. //SERIAL_PROTOCOLLNPGM("");
  5160. for( l=0; l<n_legs-1; l++) {
  5161. if (rotational_direction==1)
  5162. theta += (float) ((unsigned long) _millis() % (long) 20) / (360.0/(2*3.1415926)); // turn into radians
  5163. else
  5164. theta -= (float) ((unsigned long) _millis() % (long) 20) / (360.0/(2*3.1415926)); // turn into radians
  5165. radius += (float) ( ((long) ((unsigned long) _millis() % (long) 10)) - 5);
  5166. if ( radius<0.0 )
  5167. radius = -radius;
  5168. X_current = X_probe_location + cos(theta) * radius;
  5169. Y_current = Y_probe_location + sin(theta) * radius;
  5170. if ( X_current<X_MIN_POS) // Make sure our X & Y are sane
  5171. X_current = X_MIN_POS;
  5172. if ( X_current>X_MAX_POS)
  5173. X_current = X_MAX_POS;
  5174. if ( Y_current<Y_MIN_POS) // Make sure our X & Y are sane
  5175. Y_current = Y_MIN_POS;
  5176. if ( Y_current>Y_MAX_POS)
  5177. Y_current = Y_MAX_POS;
  5178. if (verbose_level>3 ) {
  5179. SERIAL_ECHOPAIR("x: ", X_current);
  5180. SERIAL_ECHOPAIR("y: ", Y_current);
  5181. SERIAL_PROTOCOLLNPGM("");
  5182. }
  5183. do_blocking_move_to( X_current, Y_current, Z_current );
  5184. }
  5185. do_blocking_move_to( X_probe_location, Y_probe_location, Z_start_location); // Go back to the probe location
  5186. }
  5187. int l_feedmultiply = setup_for_endstop_move();
  5188. run_z_probe();
  5189. sample_set[n] = current_position[Z_AXIS];
  5190. //
  5191. // Get the current mean for the data points we have so far
  5192. //
  5193. sum=0.0;
  5194. for( j=0; j<=n; j++) {
  5195. sum = sum + sample_set[j];
  5196. }
  5197. mean = sum / (double (n+1));
  5198. //
  5199. // Now, use that mean to calculate the standard deviation for the
  5200. // data points we have so far
  5201. //
  5202. sum=0.0;
  5203. for( j=0; j<=n; j++) {
  5204. sum = sum + (sample_set[j]-mean) * (sample_set[j]-mean);
  5205. }
  5206. sigma = sqrt( sum / (double (n+1)) );
  5207. if (verbose_level > 1) {
  5208. SERIAL_PROTOCOL(n+1);
  5209. SERIAL_PROTOCOL(" of ");
  5210. SERIAL_PROTOCOL(n_samples);
  5211. SERIAL_PROTOCOLPGM(" z: ");
  5212. SERIAL_PROTOCOL_F(current_position[Z_AXIS], 6);
  5213. }
  5214. if (verbose_level > 2) {
  5215. SERIAL_PROTOCOL(" mean: ");
  5216. SERIAL_PROTOCOL_F(mean,6);
  5217. SERIAL_PROTOCOL(" sigma: ");
  5218. SERIAL_PROTOCOL_F(sigma,6);
  5219. }
  5220. if (verbose_level > 0)
  5221. SERIAL_PROTOCOLPGM("\n");
  5222. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  5223. current_position[E_AXIS], homing_feedrate[Z_AXIS]/60, active_extruder);
  5224. st_synchronize();
  5225. }
  5226. _delay(1000);
  5227. clean_up_after_endstop_move(l_feedmultiply);
  5228. // enable_endstops(true);
  5229. if (verbose_level > 0) {
  5230. SERIAL_PROTOCOLPGM("Mean: ");
  5231. SERIAL_PROTOCOL_F(mean, 6);
  5232. SERIAL_PROTOCOLPGM("\n");
  5233. }
  5234. SERIAL_PROTOCOLPGM("Standard Deviation: ");
  5235. SERIAL_PROTOCOL_F(sigma, 6);
  5236. SERIAL_PROTOCOLPGM("\n\n");
  5237. Sigma_Exit:
  5238. break;
  5239. }
  5240. #endif // Z_PROBE_REPEATABILITY_TEST
  5241. #endif // ENABLE_AUTO_BED_LEVELING
  5242. /*!
  5243. ### M73 - Set/get print progress <a href="https://reprap.org/wiki/G-code#M73:_Set.2FGet_build_percentage">M73: Set/Get build percentage</a>
  5244. #### Usage
  5245. M73 [ P | R | Q | S | C | D ]
  5246. #### Parameters
  5247. - `P` - Percent in normal mode
  5248. - `R` - Time remaining in normal mode
  5249. - `Q` - Percent in silent mode
  5250. - `S` - Time in silent mode
  5251. - `C` - Time to change/pause/user interaction in normal mode
  5252. - `D` - Time to change/pause/user interaction in silent mode
  5253. */
  5254. case 73: //M73 show percent done, time remaining and time to change/pause
  5255. {
  5256. if(code_seen('P')) print_percent_done_normal = code_value_uint8();
  5257. if(code_seen('R')) print_time_remaining_normal = code_value();
  5258. if(code_seen('Q')) print_percent_done_silent = code_value_uint8();
  5259. if(code_seen('S')) print_time_remaining_silent = code_value();
  5260. if(code_seen('C')){
  5261. float print_time_to_change_normal_f = code_value_float();
  5262. print_time_to_change_normal = ( print_time_to_change_normal_f <= 0 ) ? PRINT_TIME_REMAINING_INIT : print_time_to_change_normal_f;
  5263. }
  5264. if(code_seen('D')){
  5265. float print_time_to_change_silent_f = code_value_float();
  5266. print_time_to_change_silent = ( print_time_to_change_silent_f <= 0 ) ? PRINT_TIME_REMAINING_INIT : print_time_to_change_silent_f;
  5267. }
  5268. {
  5269. const char* _msg_mode_done_remain = _N("%S MODE: Percent done: %hhd; print time remaining in mins: %d; Change in mins: %d\n");
  5270. printf_P(_msg_mode_done_remain, _N("NORMAL"), int8_t(print_percent_done_normal), print_time_remaining_normal, print_time_to_change_normal);
  5271. printf_P(_msg_mode_done_remain, _N("SILENT"), int8_t(print_percent_done_silent), print_time_remaining_silent, print_time_to_change_silent);
  5272. }
  5273. break;
  5274. }
  5275. /*!
  5276. ### M104 - Set hotend temperature <a href="https://reprap.org/wiki/G-code#M104:_Set_Extruder_Temperature">M104: Set Extruder Temperature</a>
  5277. #### Usage
  5278. M104 [ S ]
  5279. #### Parameters
  5280. - `S` - Target temperature
  5281. */
  5282. case 104: // M104
  5283. {
  5284. uint8_t extruder;
  5285. if(setTargetedHotend(104,extruder)){
  5286. break;
  5287. }
  5288. if (code_seen('S'))
  5289. {
  5290. setTargetHotendSafe(code_value(), extruder);
  5291. }
  5292. break;
  5293. }
  5294. /*!
  5295. ### M112 - Emergency stop <a href="https://reprap.org/wiki/G-code#M112:_Full_.28Emergency.29_Stop">M112: Full (Emergency) Stop</a>
  5296. It is processed much earlier as to bypass the cmdqueue.
  5297. */
  5298. case 112:
  5299. kill(MSG_M112_KILL, 3);
  5300. break;
  5301. /*!
  5302. ### M140 - Set bed temperature <a href="https://reprap.org/wiki/G-code#M140:_Set_Bed_Temperature_.28Fast.29">M140: Set Bed Temperature (Fast)</a>
  5303. #### Usage
  5304. M140 [ S ]
  5305. #### Parameters
  5306. - `S` - Target temperature
  5307. */
  5308. case 140:
  5309. if (code_seen('S')) setTargetBed(code_value());
  5310. break;
  5311. /*!
  5312. ### M105 - Report temperatures <a href="https://reprap.org/wiki/G-code#M105:_Get_Extruder_Temperature">M105: Get Extruder Temperature</a>
  5313. Prints temperatures:
  5314. - `T:` - Hotend (actual / target)
  5315. - `B:` - Bed (actual / target)
  5316. - `Tx:` - x Tool (actual / target)
  5317. - `@:` - Hotend power
  5318. - `B@:` - Bed power
  5319. - `P:` - PINDAv2 actual (only MK2.5/s and MK3/s)
  5320. - `A:` - Ambient actual (only MK3/s)
  5321. _Example:_
  5322. 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
  5323. */
  5324. case 105:
  5325. {
  5326. uint8_t extruder;
  5327. if(setTargetedHotend(105, extruder)){
  5328. break;
  5329. }
  5330. SERIAL_PROTOCOLPGM("ok ");
  5331. gcode_M105(extruder);
  5332. cmdqueue_pop_front(); //prevent an ok after the command since this command uses an ok at the beginning.
  5333. cmdbuffer_front_already_processed = true;
  5334. break;
  5335. }
  5336. #if defined(AUTO_REPORT)
  5337. /*!
  5338. ### M155 - Automatically send status <a href="https://reprap.org/wiki/G-code#M155:_Automatically_send_temperatures">M155: Automatically send temperatures</a>
  5339. #### Usage
  5340. M155 [ S ] [ C ]
  5341. #### Parameters
  5342. - `S` - Set autoreporting interval in seconds. 0 to disable. Maximum: 255
  5343. - `C` - Activate auto-report function (bit mask). Default is temperature.
  5344. bit 0 = Auto-report temperatures
  5345. bit 1 = Auto-report fans
  5346. bit 2 = Auto-report position
  5347. bit 3 = free
  5348. bit 4 = free
  5349. bit 5 = free
  5350. bit 6 = free
  5351. bit 7 = free
  5352. */
  5353. case 155:
  5354. {
  5355. if (code_seen('S')){
  5356. autoReportFeatures.SetPeriod( code_value_uint8() );
  5357. }
  5358. if (code_seen('C')){
  5359. autoReportFeatures.SetMask(code_value_uint8());
  5360. } else{
  5361. autoReportFeatures.SetMask(1); //Backwards compability to host systems like Octoprint to send only temp if paramerter `C`isn't used.
  5362. }
  5363. }
  5364. break;
  5365. #endif //AUTO_REPORT
  5366. /*!
  5367. ### 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>
  5368. #### Usage
  5369. M104 [ B | R | S ]
  5370. #### Parameters (not mandatory)
  5371. - `S` - Set extruder temperature
  5372. - `R` - Set extruder temperature
  5373. - `B` - Set max. extruder temperature, while `S` is min. temperature. Not active in default, only if AUTOTEMP is defined in source code.
  5374. Parameters S and R are treated identically.
  5375. Command always waits for both cool down and heat up.
  5376. If no parameters are supplied waits for previously set extruder temperature.
  5377. */
  5378. case 109:
  5379. {
  5380. uint8_t extruder;
  5381. if(setTargetedHotend(109, extruder)){
  5382. break;
  5383. }
  5384. LCD_MESSAGERPGM(_T(MSG_HEATING));
  5385. heating_status = HeatingStatus::EXTRUDER_HEATING;
  5386. prusa_statistics(1);
  5387. #ifdef AUTOTEMP
  5388. autotemp_enabled=false;
  5389. #endif
  5390. if (code_seen('S')) {
  5391. setTargetHotendSafe(code_value(), extruder);
  5392. } else if (code_seen('R')) {
  5393. setTargetHotendSafe(code_value(), extruder);
  5394. }
  5395. #ifdef AUTOTEMP
  5396. if (code_seen('S')) autotemp_min=code_value();
  5397. if (code_seen('B')) autotemp_max=code_value();
  5398. if (code_seen('F'))
  5399. {
  5400. autotemp_factor=code_value();
  5401. autotemp_enabled=true;
  5402. }
  5403. #endif
  5404. codenum = _millis();
  5405. /* See if we are heating up or cooling down */
  5406. target_direction = isHeatingHotend(extruder); // true if heating, false if cooling
  5407. cancel_heatup = false;
  5408. wait_for_heater(codenum, extruder); //loops until target temperature is reached
  5409. LCD_MESSAGERPGM(_T(MSG_HEATING_COMPLETE));
  5410. heating_status = HeatingStatus::EXTRUDER_HEATING_COMPLETE;
  5411. prusa_statistics(2);
  5412. //starttime=_millis();
  5413. previous_millis_cmd.start();
  5414. }
  5415. break;
  5416. /*!
  5417. ### 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>
  5418. #### Usage
  5419. M190 [ R | S ]
  5420. #### Parameters (not mandatory)
  5421. - `S` - Set extruder temperature and wait for heating
  5422. - `R` - Set extruder temperature and wait for heating or cooling
  5423. If no parameter is supplied, waits for heating or cooling to previously set temperature.
  5424. */
  5425. case 190:
  5426. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  5427. {
  5428. bool CooldownNoWait = false;
  5429. LCD_MESSAGERPGM(_T(MSG_BED_HEATING));
  5430. heating_status = HeatingStatus::BED_HEATING;
  5431. prusa_statistics(1);
  5432. if (code_seen('S'))
  5433. {
  5434. setTargetBed(code_value());
  5435. CooldownNoWait = true;
  5436. }
  5437. else if (code_seen('R'))
  5438. {
  5439. setTargetBed(code_value());
  5440. }
  5441. codenum = _millis();
  5442. cancel_heatup = false;
  5443. target_direction = isHeatingBed(); // true if heating, false if cooling
  5444. while ( (!cancel_heatup) && (target_direction ? (isHeatingBed()) : (isCoolingBed()&&(CooldownNoWait==false))) )
  5445. {
  5446. if(( _millis() - codenum) > 1000 ) //Print Temp Reading every 1 second while heating up.
  5447. {
  5448. if (!farm_mode) {
  5449. float tt = degHotend(active_extruder);
  5450. SERIAL_PROTOCOLPGM("T:");
  5451. SERIAL_PROTOCOL(tt);
  5452. SERIAL_PROTOCOLPGM(" E:");
  5453. SERIAL_PROTOCOL((int)active_extruder);
  5454. SERIAL_PROTOCOLPGM(" B:");
  5455. SERIAL_PROTOCOL_F(degBed(), 1);
  5456. SERIAL_PROTOCOLLN();
  5457. }
  5458. codenum = _millis();
  5459. }
  5460. manage_heater();
  5461. manage_inactivity();
  5462. lcd_update(0);
  5463. }
  5464. LCD_MESSAGERPGM(_T(MSG_BED_DONE));
  5465. heating_status = HeatingStatus::BED_HEATING_COMPLETE;
  5466. previous_millis_cmd.start();
  5467. }
  5468. #endif
  5469. break;
  5470. #if defined(FAN_PIN) && FAN_PIN > -1
  5471. /*!
  5472. ### M106 - Set fan speed <a href="https://reprap.org/wiki/G-code#M106:_Fan_On">M106: Fan On</a>
  5473. #### Usage
  5474. M106 [ S ]
  5475. #### Parameters
  5476. - `S` - Specifies the duty cycle of the print fan. Allowed values are 0-255. If it's omitted, a value of 255 is used.
  5477. */
  5478. case 106: // M106 Sxxx Fan On S<speed> 0 .. 255
  5479. if (code_seen('S')){
  5480. fanSpeed = code_value_uint8();
  5481. }
  5482. else {
  5483. fanSpeed = 255;
  5484. }
  5485. break;
  5486. /*!
  5487. ### M107 - Fan off <a href="https://reprap.org/wiki/G-code#M107:_Fan_Off">M107: Fan Off</a>
  5488. */
  5489. case 107:
  5490. fanSpeed = 0;
  5491. break;
  5492. #endif //FAN_PIN
  5493. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  5494. /*!
  5495. ### M80 - Turn on the Power Supply <a href="https://reprap.org/wiki/G-code#M80:_ATX_Power_On">M80: ATX Power On</a>
  5496. Only works if the firmware is compiled with PS_ON_PIN defined.
  5497. */
  5498. case 80:
  5499. SET_OUTPUT(PS_ON_PIN); //GND
  5500. WRITE(PS_ON_PIN, PS_ON_AWAKE);
  5501. // If you have a switch on suicide pin, this is useful
  5502. // if you want to start another print with suicide feature after
  5503. // a print without suicide...
  5504. #if defined SUICIDE_PIN && SUICIDE_PIN > -1
  5505. SET_OUTPUT(SUICIDE_PIN);
  5506. WRITE(SUICIDE_PIN, HIGH);
  5507. #endif
  5508. powersupply = true;
  5509. LCD_MESSAGERPGM(MSG_WELCOME);
  5510. lcd_update(0);
  5511. break;
  5512. /*!
  5513. ### M81 - Turn off Power Supply <a href="https://reprap.org/wiki/G-code#M81:_ATX_Power_Off">M81: ATX Power Off</a>
  5514. Only works if the firmware is compiled with PS_ON_PIN defined.
  5515. */
  5516. case 81:
  5517. disable_heater();
  5518. st_synchronize();
  5519. disable_e0();
  5520. disable_e1();
  5521. disable_e2();
  5522. finishAndDisableSteppers();
  5523. fanSpeed = 0;
  5524. _delay(1000); // Wait a little before to switch off
  5525. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  5526. st_synchronize();
  5527. suicide();
  5528. #elif defined(PS_ON_PIN) && PS_ON_PIN > -1
  5529. SET_OUTPUT(PS_ON_PIN);
  5530. WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  5531. #endif
  5532. powersupply = false;
  5533. LCD_MESSAGERPGM(CAT4(CUSTOM_MENDEL_NAME,PSTR(" "),MSG_OFF,PSTR(".")));
  5534. lcd_update(0);
  5535. break;
  5536. #endif
  5537. /*!
  5538. ### 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>
  5539. Makes the extruder interpret extrusion as absolute positions.
  5540. */
  5541. case 82:
  5542. axis_relative_modes &= ~E_AXIS_MASK;
  5543. break;
  5544. /*!
  5545. ### 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>
  5546. Makes the extruder interpret extrusion values as relative positions.
  5547. */
  5548. case 83:
  5549. axis_relative_modes |= E_AXIS_MASK;
  5550. break;
  5551. /*!
  5552. ### M84 - Disable steppers <a href="https://reprap.org/wiki/G-code#M84:_Stop_idle_hold">M84: Stop idle hold</a>
  5553. This command can be used to set the stepper inactivity timeout (`S`) or to disable steppers (`X`,`Y`,`Z`,`E`)
  5554. This command can be used without any additional parameters. In that case all steppers are disabled.
  5555. 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.
  5556. M84 [ S | X | Y | Z | E ]
  5557. - `S` - Seconds
  5558. - `X` - X axis
  5559. - `Y` - Y axis
  5560. - `Z` - Z axis
  5561. - `E` - Extruder
  5562. ### M18 - Disable steppers <a href="https://reprap.org/wiki/G-code#M18:_Disable_all_stepper_motors">M18: Disable all stepper motors</a>
  5563. Equal to M84 (compatibility)
  5564. */
  5565. case 18: //compatibility
  5566. case 84: // M84
  5567. if(code_seen('S')){
  5568. stepper_inactive_time = code_value() * 1000;
  5569. }
  5570. else
  5571. {
  5572. 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])));
  5573. if(all_axis)
  5574. {
  5575. st_synchronize();
  5576. disable_e0();
  5577. disable_e1();
  5578. disable_e2();
  5579. finishAndDisableSteppers();
  5580. }
  5581. else
  5582. {
  5583. st_synchronize();
  5584. if (code_seen('X')) disable_x();
  5585. if (code_seen('Y')) disable_y();
  5586. if (code_seen('Z')) disable_z();
  5587. #if ((E0_ENABLE_PIN != X_ENABLE_PIN) && (E1_ENABLE_PIN != Y_ENABLE_PIN)) // Only enable on boards that have seperate ENABLE_PINS
  5588. if (code_seen('E')) {
  5589. disable_e0();
  5590. disable_e1();
  5591. disable_e2();
  5592. }
  5593. #endif
  5594. }
  5595. }
  5596. break;
  5597. /*!
  5598. ### M85 - Set max inactive time <a href="https://reprap.org/wiki/G-code#M85:_Set_Inactivity_Shutdown_Timer">M85: Set Inactivity Shutdown Timer</a>
  5599. #### Usage
  5600. M85 [ S ]
  5601. #### Parameters
  5602. - `S` - specifies the time in seconds. If a value of 0 is specified, the timer is disabled.
  5603. */
  5604. case 85: // M85
  5605. if(code_seen('S')) {
  5606. max_inactive_time = code_value() * 1000;
  5607. }
  5608. break;
  5609. #ifdef SAFETYTIMER
  5610. /*!
  5611. ### 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>
  5612. When safety timer expires, heatbed and nozzle target temperatures are set to zero.
  5613. #### Usage
  5614. M86 [ S ]
  5615. #### Parameters
  5616. - `S` - specifies the time in seconds. If a value of 0 is specified, the timer is disabled.
  5617. */
  5618. case 86:
  5619. if (code_seen('S')) {
  5620. safetytimer_inactive_time = code_value() * 1000;
  5621. safetyTimer.start();
  5622. }
  5623. break;
  5624. #endif
  5625. /*!
  5626. ### 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>
  5627. 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)
  5628. #### Usage
  5629. M92 [ X | Y | Z | E ]
  5630. #### Parameters
  5631. - `X` - Steps per unit for the X drive
  5632. - `Y` - Steps per unit for the Y drive
  5633. - `Z` - Steps per unit for the Z drive
  5634. - `E` - Steps per unit for the extruder drive
  5635. */
  5636. case 92:
  5637. for(int8_t i=0; i < NUM_AXIS; i++)
  5638. {
  5639. if(code_seen(axis_codes[i]))
  5640. {
  5641. if(i == E_AXIS) { // E
  5642. float value = code_value();
  5643. if(value < 20.0) {
  5644. float factor = cs.axis_steps_per_unit[i] / value; // increase e constants if M92 E14 is given for netfab.
  5645. cs.max_jerk[E_AXIS] *= factor;
  5646. max_feedrate[i] *= factor;
  5647. axis_steps_per_sqr_second[i] *= factor;
  5648. }
  5649. cs.axis_steps_per_unit[i] = value;
  5650. #if defined(FILAMENT_SENSOR) && defined(PAT9125)
  5651. fsensor_set_axis_steps_per_unit(value);
  5652. #endif
  5653. }
  5654. else {
  5655. cs.axis_steps_per_unit[i] = code_value();
  5656. }
  5657. }
  5658. }
  5659. reset_acceleration_rates();
  5660. break;
  5661. /*!
  5662. ### M110 - Set Line number <a href="https://reprap.org/wiki/G-code#M110:_Set_Current_Line_Number">M110: Set Current Line Number</a>
  5663. Sets the line number in G-code
  5664. #### Usage
  5665. M110 [ N ]
  5666. #### Parameters
  5667. - `N` - Line number
  5668. */
  5669. case 110:
  5670. if (code_seen('N'))
  5671. gcode_LastN = code_value_long();
  5672. break;
  5673. /*!
  5674. ### M113 - Get or set host keep-alive interval <a href="https://reprap.org/wiki/G-code#M113:_Host_Keepalive">M113: Host Keepalive</a>
  5675. 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).
  5676. #### Usage
  5677. M113 [ S ]
  5678. #### Parameters
  5679. - `S` - Seconds. Default is 2 seconds between "busy" messages
  5680. */
  5681. case 113:
  5682. if (code_seen('S')) {
  5683. host_keepalive_interval = code_value_uint8();
  5684. // NOMORE(host_keepalive_interval, 60);
  5685. }
  5686. else {
  5687. SERIAL_ECHO_START;
  5688. SERIAL_ECHOPAIR("M113 S", (unsigned long)host_keepalive_interval);
  5689. SERIAL_PROTOCOLLN();
  5690. }
  5691. break;
  5692. /*!
  5693. ### M115 - Firmware info <a href="https://reprap.org/wiki/G-code#M115:_Get_Firmware_Version_and_Capabilities">M115: Get Firmware Version and Capabilities</a>
  5694. Print the firmware info and capabilities
  5695. Without any arguments, prints Prusa firmware version number, machine type, extruder count and UUID.
  5696. `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.
  5697. _Examples:_
  5698. `M115` results:
  5699. `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`
  5700. `M115 V` results:
  5701. `3.8.1`
  5702. `M115 U3.8.2-RC1` results on LCD display for 30s or user interaction:
  5703. `New firmware version available: 3.8.2-RC1 Please upgrade.`
  5704. #### Usage
  5705. M115 [ V | U ]
  5706. #### Parameters
  5707. - V - Report current installed firmware version
  5708. - U - Firmware version provided by G-code to be compared to current one.
  5709. */
  5710. case 115: // M115
  5711. if (code_seen('V')) {
  5712. // Report the Prusa version number.
  5713. SERIAL_PROTOCOLLNRPGM(FW_VERSION_STR_P());
  5714. } else if (code_seen('U')) {
  5715. // Check the firmware version provided. If the firmware version provided by the U code is higher than the currently running firmware,
  5716. // pause the print for 30s and ask the user to upgrade the firmware.
  5717. show_upgrade_dialog_if_version_newer(++ strchr_pointer);
  5718. } else {
  5719. SERIAL_ECHOPGM("FIRMWARE_NAME:Prusa-Firmware ");
  5720. SERIAL_ECHORPGM(FW_VERSION_STR_P());
  5721. SERIAL_ECHOPGM(" based on Marlin FIRMWARE_URL:https://github.com/prusa3d/Prusa-Firmware PROTOCOL_VERSION:");
  5722. SERIAL_ECHOPGM(PROTOCOL_VERSION);
  5723. SERIAL_ECHOPGM(" MACHINE_TYPE:");
  5724. SERIAL_ECHOPGM(CUSTOM_MENDEL_NAME);
  5725. SERIAL_ECHOPGM(" EXTRUDER_COUNT:");
  5726. SERIAL_ECHOPGM(STRINGIFY(EXTRUDERS));
  5727. SERIAL_ECHOPGM(" UUID:");
  5728. SERIAL_ECHOLNPGM(MACHINE_UUID);
  5729. #ifdef EXTENDED_CAPABILITIES_REPORT
  5730. extended_capabilities_report();
  5731. #endif //EXTENDED_CAPABILITIES_REPORT
  5732. }
  5733. break;
  5734. /*!
  5735. ### M114 - Get current position <a href="https://reprap.org/wiki/G-code#M114:_Get_Current_Position">M114: Get Current Position</a>
  5736. */
  5737. case 114:
  5738. gcode_M114();
  5739. break;
  5740. /*
  5741. M117 moved up to get the high priority
  5742. case 117: // M117 display message
  5743. starpos = (strchr(strchr_pointer + 5,'*'));
  5744. if(starpos!=NULL)
  5745. *(starpos)='\0';
  5746. lcd_setstatus(strchr_pointer + 5);
  5747. break;*/
  5748. #ifdef M120_M121_ENABLED
  5749. /*!
  5750. ### M120 - Enable endstops <a href="https://reprap.org/wiki/G-code#M120:_Enable_endstop_detection">M120: Enable endstop detection</a>
  5751. */
  5752. case 120:
  5753. enable_endstops(true) ;
  5754. break;
  5755. /*!
  5756. ### M121 - Disable endstops <a href="https://reprap.org/wiki/G-code#M121:_Disable_endstop_detection">M121: Disable endstop detection</a>
  5757. */
  5758. case 121:
  5759. enable_endstops(false) ;
  5760. break;
  5761. #endif //M120_M121_ENABLED
  5762. /*!
  5763. ### M119 - Get endstop states <a href="https://reprap.org/wiki/G-code#M119:_Get_Endstop_Status">M119: Get Endstop Status</a>
  5764. 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.
  5765. */
  5766. case 119:
  5767. SERIAL_PROTOCOLRPGM(_N("Reporting endstop status"));////MSG_M119_REPORT
  5768. SERIAL_PROTOCOLLN();
  5769. #if defined(X_MIN_PIN) && X_MIN_PIN > -1
  5770. SERIAL_PROTOCOLRPGM(_n("x_min: "));////MSG_X_MIN
  5771. if(READ(X_MIN_PIN)^X_MIN_ENDSTOP_INVERTING){
  5772. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5773. }else{
  5774. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5775. }
  5776. SERIAL_PROTOCOLLN();
  5777. #endif
  5778. #if defined(X_MAX_PIN) && X_MAX_PIN > -1
  5779. SERIAL_PROTOCOLRPGM(_n("x_max: "));////MSG_X_MAX
  5780. if(READ(X_MAX_PIN)^X_MAX_ENDSTOP_INVERTING){
  5781. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5782. }else{
  5783. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5784. }
  5785. SERIAL_PROTOCOLLN();
  5786. #endif
  5787. #if defined(Y_MIN_PIN) && Y_MIN_PIN > -1
  5788. SERIAL_PROTOCOLRPGM(_n("y_min: "));////MSG_Y_MIN
  5789. if(READ(Y_MIN_PIN)^Y_MIN_ENDSTOP_INVERTING){
  5790. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5791. }else{
  5792. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5793. }
  5794. SERIAL_PROTOCOLLN();
  5795. #endif
  5796. #if defined(Y_MAX_PIN) && Y_MAX_PIN > -1
  5797. SERIAL_PROTOCOLRPGM(_n("y_max: "));////MSG_Y_MAX
  5798. if(READ(Y_MAX_PIN)^Y_MAX_ENDSTOP_INVERTING){
  5799. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5800. }else{
  5801. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5802. }
  5803. SERIAL_PROTOCOLLN();
  5804. #endif
  5805. #if defined(Z_MIN_PIN) && Z_MIN_PIN > -1
  5806. SERIAL_PROTOCOLRPGM(MSG_Z_MIN);
  5807. if(READ(Z_MIN_PIN)^Z_MIN_ENDSTOP_INVERTING){
  5808. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5809. }else{
  5810. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5811. }
  5812. SERIAL_PROTOCOLLN();
  5813. #endif
  5814. #if defined(Z_MAX_PIN) && Z_MAX_PIN > -1
  5815. SERIAL_PROTOCOLRPGM(MSG_Z_MAX);
  5816. if(READ(Z_MAX_PIN)^Z_MAX_ENDSTOP_INVERTING){
  5817. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5818. }else{
  5819. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5820. }
  5821. SERIAL_PROTOCOLLN();
  5822. #endif
  5823. break;
  5824. //!@todo update for all axes, use for loop
  5825. #if (defined(FANCHECK) && (((defined(TACH_0) && (TACH_0 >-1)) || (defined(TACH_1) && (TACH_1 > -1)))))
  5826. /*!
  5827. ### M123 - Tachometer value <a href="https://www.reprap.org/wiki/G-code#M123:_Tachometer_value_.28RepRap_.26_Prusa.29">M123: Tachometer value</a>
  5828. This command is used to report fan speeds and fan pwm values.
  5829. #### Usage
  5830. M123
  5831. - E0: - Hotend fan speed in RPM
  5832. - PRN1: - Part cooling fans speed in RPM
  5833. - E0@: - Hotend fan PWM value
  5834. - PRN1@: -Part cooling fan PWM value
  5835. _Example:_
  5836. E0:3240 RPM PRN1:4560 RPM E0@:255 PRN1@:255
  5837. */
  5838. case 123:
  5839. gcode_M123();
  5840. break;
  5841. #endif //FANCHECK and TACH_0 and TACH_1
  5842. #ifdef BLINKM
  5843. /*!
  5844. ### M150 - Set RGB(W) Color <a href="https://reprap.org/wiki/G-code#M150:_Set_LED_color">M150: Set LED color</a>
  5845. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code by defining BLINKM and its dependencies.
  5846. #### Usage
  5847. M150 [ R | U | B ]
  5848. #### Parameters
  5849. - `R` - Red color value
  5850. - `U` - Green color value. It is NOT `G`!
  5851. - `B` - Blue color value
  5852. */
  5853. case 150:
  5854. {
  5855. byte red;
  5856. byte grn;
  5857. byte blu;
  5858. if(code_seen('R')) red = code_value();
  5859. if(code_seen('U')) grn = code_value();
  5860. if(code_seen('B')) blu = code_value();
  5861. SendColors(red,grn,blu);
  5862. }
  5863. break;
  5864. #endif //BLINKM
  5865. /*!
  5866. ### M200 - Set filament diameter <a href="https://reprap.org/wiki/G-code#M200:_Set_filament_diameter">M200: Set filament diameter</a>
  5867. #### Usage
  5868. M200 [ D | T ]
  5869. #### Parameters
  5870. - `D` - Diameter in mm
  5871. - `T` - Number of extruder (MMUs)
  5872. */
  5873. case 200: // M200 D<millimeters> set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).
  5874. {
  5875. uint8_t extruder = active_extruder;
  5876. if(code_seen('T')) {
  5877. extruder = code_value_uint8();
  5878. if(extruder >= EXTRUDERS) {
  5879. SERIAL_ECHO_START;
  5880. SERIAL_ECHO(_n("M200 Invalid extruder "));////MSG_M200_INVALID_EXTRUDER
  5881. break;
  5882. }
  5883. }
  5884. if(code_seen('D')) {
  5885. float diameter = code_value();
  5886. if (diameter == 0.0) {
  5887. // setting any extruder filament size disables volumetric on the assumption that
  5888. // slicers either generate in extruder values as cubic mm or as as filament feeds
  5889. // for all extruders
  5890. cs.volumetric_enabled = false;
  5891. } else {
  5892. cs.filament_size[extruder] = code_value();
  5893. // make sure all extruders have some sane value for the filament size
  5894. cs.filament_size[0] = (cs.filament_size[0] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[0]);
  5895. #if EXTRUDERS > 1
  5896. cs.filament_size[1] = (cs.filament_size[1] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[1]);
  5897. #if EXTRUDERS > 2
  5898. cs.filament_size[2] = (cs.filament_size[2] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[2]);
  5899. #endif
  5900. #endif
  5901. cs.volumetric_enabled = true;
  5902. }
  5903. } else {
  5904. //reserved for setting filament diameter via UFID or filament measuring device
  5905. break;
  5906. }
  5907. calculate_extruder_multipliers();
  5908. }
  5909. break;
  5910. /*!
  5911. ### M201 - Set Print Max Acceleration <a href="https://reprap.org/wiki/G-code#M201:_Set_max_acceleration">M201: Set max printing acceleration</a>
  5912. For each axis individually.
  5913. ##### Usage
  5914. M201 [ X | Y | Z | E ]
  5915. ##### Parameters
  5916. - `X` - Acceleration for X axis in units/s^2
  5917. - `Y` - Acceleration for Y axis in units/s^2
  5918. - `Z` - Acceleration for Z axis in units/s^2
  5919. - `E` - Acceleration for the active or specified extruder in units/s^2
  5920. */
  5921. case 201:
  5922. for (int8_t i = 0; i < NUM_AXIS; i++)
  5923. {
  5924. if (code_seen(axis_codes[i]))
  5925. {
  5926. unsigned long val = code_value();
  5927. #ifdef TMC2130
  5928. unsigned long val_silent = val;
  5929. if ((i == X_AXIS) || (i == Y_AXIS))
  5930. {
  5931. if (val > NORMAL_MAX_ACCEL_XY)
  5932. val = NORMAL_MAX_ACCEL_XY;
  5933. if (val_silent > SILENT_MAX_ACCEL_XY)
  5934. val_silent = SILENT_MAX_ACCEL_XY;
  5935. }
  5936. cs.max_acceleration_units_per_sq_second_normal[i] = val;
  5937. cs.max_acceleration_units_per_sq_second_silent[i] = val_silent;
  5938. #else //TMC2130
  5939. max_acceleration_units_per_sq_second[i] = val;
  5940. #endif //TMC2130
  5941. }
  5942. }
  5943. // 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)
  5944. reset_acceleration_rates();
  5945. break;
  5946. #if 0 // Not used for Sprinter/grbl gen6
  5947. case 202: // M202
  5948. for(int8_t i=0; i < NUM_AXIS; i++) {
  5949. if(code_seen(axis_codes[i])) axis_travel_steps_per_sqr_second[i] = code_value() * cs.axis_steps_per_unit[i];
  5950. }
  5951. break;
  5952. #endif
  5953. /*!
  5954. ### M203 - Set Max Feedrate <a href="https://reprap.org/wiki/G-code#M203:_Set_maximum_feedrate">M203: Set maximum feedrate</a>
  5955. For each axis individually.
  5956. ##### Usage
  5957. M203 [ X | Y | Z | E ]
  5958. ##### Parameters
  5959. - `X` - Maximum feedrate for X axis
  5960. - `Y` - Maximum feedrate for Y axis
  5961. - `Z` - Maximum feedrate for Z axis
  5962. - `E` - Maximum feedrate for extruder drives
  5963. */
  5964. case 203: // M203 max feedrate mm/sec
  5965. for (uint8_t i = 0; i < NUM_AXIS; i++)
  5966. {
  5967. if (code_seen(axis_codes[i]))
  5968. {
  5969. float val = code_value();
  5970. #ifdef TMC2130
  5971. float val_silent = val;
  5972. if ((i == X_AXIS) || (i == Y_AXIS))
  5973. {
  5974. if (val > NORMAL_MAX_FEEDRATE_XY)
  5975. val = NORMAL_MAX_FEEDRATE_XY;
  5976. if (val_silent > SILENT_MAX_FEEDRATE_XY)
  5977. val_silent = SILENT_MAX_FEEDRATE_XY;
  5978. }
  5979. cs.max_feedrate_normal[i] = val;
  5980. cs.max_feedrate_silent[i] = val_silent;
  5981. #else //TMC2130
  5982. max_feedrate[i] = val;
  5983. #endif //TMC2130
  5984. }
  5985. }
  5986. break;
  5987. /*!
  5988. ### M204 - Acceleration settings <a href="https://reprap.org/wiki/G-code#M204:_Set_default_acceleration">M204: Set default acceleration</a>
  5989. #### Old format:
  5990. ##### Usage
  5991. M204 [ S | T ]
  5992. ##### Parameters
  5993. - `S` - normal moves
  5994. - `T` - filmanent only moves
  5995. #### New format:
  5996. ##### Usage
  5997. M204 [ P | R | T ]
  5998. ##### Parameters
  5999. - `P` - printing moves
  6000. - `R` - filmanent only moves
  6001. - `T` - travel moves (as of now T is ignored)
  6002. */
  6003. case 204:
  6004. {
  6005. if(code_seen('S')) {
  6006. // Legacy acceleration format. This format is used by the legacy Marlin, MK2 or MK3 firmware,
  6007. // and it is also generated by Slic3r to control acceleration per extrusion type
  6008. // (there is a separate acceleration settings in Slicer for perimeter, first layer etc).
  6009. cs.acceleration = cs.travel_acceleration = code_value();
  6010. // Interpret the T value as retract acceleration in the old Marlin format.
  6011. if(code_seen('T'))
  6012. cs.retract_acceleration = code_value();
  6013. } else {
  6014. // New acceleration format, compatible with the upstream Marlin.
  6015. if(code_seen('P'))
  6016. cs.acceleration = code_value();
  6017. if(code_seen('R'))
  6018. cs.retract_acceleration = code_value();
  6019. if(code_seen('T'))
  6020. cs.travel_acceleration = code_value();
  6021. }
  6022. }
  6023. break;
  6024. /*!
  6025. ### M205 - Set advanced settings <a href="https://reprap.org/wiki/G-code#M205:_Advanced_settings">M205: Advanced settings</a>
  6026. Set some advanced settings related to movement.
  6027. #### Usage
  6028. M205 [ S | T | B | X | Y | Z | E ]
  6029. #### Parameters
  6030. - `S` - Minimum feedrate for print moves (unit/s)
  6031. - `T` - Minimum feedrate for travel moves (units/s)
  6032. - `B` - Minimum segment time (us)
  6033. - `X` - Maximum X jerk (units/s)
  6034. - `Y` - Maximum Y jerk (units/s)
  6035. - `Z` - Maximum Z jerk (units/s)
  6036. - `E` - Maximum E jerk (units/s)
  6037. */
  6038. case 205:
  6039. {
  6040. if(code_seen('S')) cs.minimumfeedrate = code_value();
  6041. if(code_seen('T')) cs.mintravelfeedrate = code_value();
  6042. if(code_seen('B')) cs.minsegmenttime = code_value() ;
  6043. if(code_seen('X')) cs.max_jerk[X_AXIS] = cs.max_jerk[Y_AXIS] = code_value();
  6044. if(code_seen('Y')) cs.max_jerk[Y_AXIS] = code_value();
  6045. if(code_seen('Z')) cs.max_jerk[Z_AXIS] = code_value();
  6046. if(code_seen('E'))
  6047. {
  6048. float e = code_value();
  6049. #ifndef LA_NOCOMPAT
  6050. e = la10c_jerk(e);
  6051. #endif
  6052. cs.max_jerk[E_AXIS] = e;
  6053. }
  6054. }
  6055. break;
  6056. /*!
  6057. ### M206 - Set additional homing offsets <a href="https://reprap.org/wiki/G-code#M206:_Offset_axes">M206: Offset axes</a>
  6058. #### Usage
  6059. M206 [ X | Y | Z ]
  6060. #### Parameters
  6061. - `X` - X axis offset
  6062. - `Y` - Y axis offset
  6063. - `Z` - Z axis offset
  6064. */
  6065. case 206:
  6066. for(uint8_t i=0; i < 3; i++)
  6067. {
  6068. if(code_seen(axis_codes[i])) cs.add_homing[i] = code_value();
  6069. }
  6070. break;
  6071. #ifdef FWRETRACT
  6072. /*!
  6073. ### M207 - Set firmware retraction <a href="https://reprap.org/wiki/G-code#M207:_Set_retract_length">M207: Set retract length</a>
  6074. #### Usage
  6075. M207 [ S | F | Z ]
  6076. #### Parameters
  6077. - `S` - positive length to retract, in mm
  6078. - `F` - retraction feedrate, in mm/min
  6079. - `Z` - additional zlift/hop
  6080. */
  6081. case 207: //M207 - set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop]
  6082. {
  6083. if(code_seen('S'))
  6084. {
  6085. cs.retract_length = code_value() ;
  6086. }
  6087. if(code_seen('F'))
  6088. {
  6089. cs.retract_feedrate = code_value()/60 ;
  6090. }
  6091. if(code_seen('Z'))
  6092. {
  6093. cs.retract_zlift = code_value() ;
  6094. }
  6095. }break;
  6096. /*!
  6097. ### M208 - Set retract recover length <a href="https://reprap.org/wiki/G-code#M208:_Set_unretract_length">M208: Set unretract length</a>
  6098. #### Usage
  6099. M208 [ S | F ]
  6100. #### Parameters
  6101. - `S` - positive length surplus to the M207 Snnn, in mm
  6102. - `F` - feedrate, in mm/sec
  6103. */
  6104. case 208: // M208 - set retract recover length S[positive mm surplus to the M207 S*] F[feedrate mm/min]
  6105. {
  6106. if(code_seen('S'))
  6107. {
  6108. cs.retract_recover_length = code_value() ;
  6109. }
  6110. if(code_seen('F'))
  6111. {
  6112. cs.retract_recover_feedrate = code_value()/60 ;
  6113. }
  6114. }break;
  6115. /*!
  6116. ### M209 - Enable/disable automatict retract <a href="https://reprap.org/wiki/G-code#M209:_Enable_automatic_retract">M209: Enable automatic retract</a>
  6117. 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.
  6118. #### Usage
  6119. M209 [ S ]
  6120. #### Parameters
  6121. - `S` - 1=true or 0=false
  6122. */
  6123. 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.
  6124. {
  6125. if(code_seen('S'))
  6126. {
  6127. switch(code_value_uint8())
  6128. {
  6129. case 0:
  6130. {
  6131. cs.autoretract_enabled=false;
  6132. retracted[0]=false;
  6133. #if EXTRUDERS > 1
  6134. retracted[1]=false;
  6135. #endif
  6136. #if EXTRUDERS > 2
  6137. retracted[2]=false;
  6138. #endif
  6139. }break;
  6140. case 1:
  6141. {
  6142. cs.autoretract_enabled=true;
  6143. retracted[0]=false;
  6144. #if EXTRUDERS > 1
  6145. retracted[1]=false;
  6146. #endif
  6147. #if EXTRUDERS > 2
  6148. retracted[2]=false;
  6149. #endif
  6150. }break;
  6151. default:
  6152. SERIAL_ECHO_START;
  6153. SERIAL_ECHORPGM(MSG_UNKNOWN_COMMAND);
  6154. SERIAL_ECHO(CMDBUFFER_CURRENT_STRING);
  6155. SERIAL_ECHOLNPGM("\"(1)");
  6156. }
  6157. }
  6158. }break;
  6159. #endif // FWRETRACT
  6160. /*!
  6161. ### M214 - Set Arc configuration values (Use M500 to store in eeprom)
  6162. #### Usage
  6163. M214 [P] [S] [N] [R] [F]
  6164. #### Parameters
  6165. - `P` - A float representing the max and default millimeters per arc segment. Must be greater than 0.
  6166. - `S` - A float representing the minimum allowable millimeters per arc segment. Set to 0 to disable
  6167. - `N` - An int representing the number of arcs to draw before correcting the small angle approximation. Set to 0 to disable.
  6168. - `R` - An int representing the minimum number of segments per arcs of any radius,
  6169. except when the results in segment lengths greater than or less than the minimum
  6170. and maximum segment length. Set to 0 to disable.
  6171. - 'F' - An int representing the number of segments per second, unless this results in segment lengths
  6172. greater than or less than the minimum and maximum segment length. Set to 0 to disable.
  6173. */
  6174. 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>
  6175. {
  6176. // Extract all possible parameters if they appear
  6177. float p = code_seen('P') ? code_value_float() : cs.mm_per_arc_segment;
  6178. float s = code_seen('S') ? code_value_float() : cs.min_mm_per_arc_segment;
  6179. unsigned char n = code_seen('N') ? code_value() : cs.n_arc_correction;
  6180. unsigned short r = code_seen('R') ? code_value() : cs.min_arc_segments;
  6181. unsigned short f = code_seen('F') ? code_value() : cs.arc_segments_per_sec;
  6182. // 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
  6183. if (p <=0 || s < 0 || p < s)
  6184. {
  6185. // Should we display some error here?
  6186. break;
  6187. }
  6188. cs.mm_per_arc_segment = p;
  6189. cs.min_mm_per_arc_segment = s;
  6190. cs.n_arc_correction = n;
  6191. cs.min_arc_segments = r;
  6192. cs.arc_segments_per_sec = f;
  6193. }break;
  6194. #if EXTRUDERS > 1
  6195. /*!
  6196. ### M218 - Set hotend offset <a href="https://reprap.org/wiki/G-code#M218:_Set_Hotend_Offset">M218: Set Hotend Offset</a>
  6197. 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.
  6198. #### Usage
  6199. M218 [ X | Y ]
  6200. #### Parameters
  6201. - `X` - X offset
  6202. - `Y` - Y offset
  6203. */
  6204. case 218: // M218 - set hotend offset (in mm), T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  6205. {
  6206. uint8_t extruder;
  6207. if(setTargetedHotend(218, extruder)){
  6208. break;
  6209. }
  6210. if(code_seen('X'))
  6211. {
  6212. extruder_offset[X_AXIS][extruder] = code_value();
  6213. }
  6214. if(code_seen('Y'))
  6215. {
  6216. extruder_offset[Y_AXIS][extruder] = code_value();
  6217. }
  6218. SERIAL_ECHO_START;
  6219. SERIAL_ECHORPGM(MSG_HOTEND_OFFSET);
  6220. for(extruder = 0; extruder < EXTRUDERS; extruder++)
  6221. {
  6222. SERIAL_ECHO(" ");
  6223. SERIAL_ECHO(extruder_offset[X_AXIS][extruder]);
  6224. SERIAL_ECHO(",");
  6225. SERIAL_ECHO(extruder_offset[Y_AXIS][extruder]);
  6226. }
  6227. SERIAL_ECHOLN("");
  6228. }break;
  6229. #endif
  6230. /*!
  6231. ### 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>
  6232. #### Usage
  6233. M220 [ B | S | R ]
  6234. #### Parameters
  6235. - `B` - Backup current speed factor
  6236. - `S` - Speed factor override percentage (0..100 or higher)
  6237. - `R` - Restore previous speed factor
  6238. */
  6239. case 220: // M220 S<factor in percent>- set speed factor override percentage
  6240. {
  6241. bool codesWereSeen = false;
  6242. if (code_seen('B')) //backup current speed factor
  6243. {
  6244. saved_feedmultiply_mm = feedmultiply;
  6245. codesWereSeen = true;
  6246. }
  6247. if (code_seen('S'))
  6248. {
  6249. feedmultiply = code_value_short();
  6250. codesWereSeen = true;
  6251. }
  6252. if (code_seen('R')) //restore previous feedmultiply
  6253. {
  6254. feedmultiply = saved_feedmultiply_mm;
  6255. codesWereSeen = true;
  6256. }
  6257. if (!codesWereSeen)
  6258. {
  6259. printf_P(PSTR("%i%%\n"), feedmultiply);
  6260. }
  6261. }
  6262. break;
  6263. /*!
  6264. ### 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>
  6265. #### Usage
  6266. M221 [ S | T ]
  6267. #### Parameters
  6268. - `S` - Extrude factor override percentage (0..100 or higher), default 100%
  6269. - `T` - Extruder drive number (Prusa Firmware only), default 0 if not set.
  6270. */
  6271. case 221: // M221 S<factor in percent>- set extrude factor override percentage
  6272. {
  6273. if (code_seen('S'))
  6274. {
  6275. int tmp_code = code_value_short();
  6276. if (code_seen('T'))
  6277. {
  6278. uint8_t extruder;
  6279. if (setTargetedHotend(221, extruder))
  6280. break;
  6281. extruder_multiply[extruder] = tmp_code;
  6282. }
  6283. else
  6284. {
  6285. extrudemultiply = tmp_code ;
  6286. }
  6287. }
  6288. else
  6289. {
  6290. printf_P(PSTR("%i%%\n"), extrudemultiply);
  6291. }
  6292. calculate_extruder_multipliers();
  6293. }
  6294. break;
  6295. /*!
  6296. ### M226 - Wait for Pin state <a href="https://reprap.org/wiki/G-code#M226:_Wait_for_pin_state">M226: Wait for pin state</a>
  6297. Wait until the specified pin reaches the state required
  6298. #### Usage
  6299. M226 [ P | S ]
  6300. #### Parameters
  6301. - `P` - pin number
  6302. - `S` - pin state
  6303. */
  6304. case 226: // M226 P<pin number> S<pin state>- Wait until the specified pin reaches the state required
  6305. {
  6306. if(code_seen('P')){
  6307. int pin_number = code_value_short(); // pin number
  6308. int pin_state = -1; // required pin state - default is inverted
  6309. if(code_seen('S')) pin_state = code_value_short(); // required pin state
  6310. if(pin_state >= -1 && pin_state <= 1){
  6311. for(int8_t i = 0; i < (int8_t)(sizeof(sensitive_pins)/sizeof(sensitive_pins[0])); i++)
  6312. {
  6313. if (((int8_t)pgm_read_byte(&sensitive_pins[i]) == pin_number))
  6314. {
  6315. pin_number = -1;
  6316. break;
  6317. }
  6318. }
  6319. if (pin_number > -1)
  6320. {
  6321. int target = LOW;
  6322. st_synchronize();
  6323. pinMode(pin_number, INPUT);
  6324. switch(pin_state){
  6325. case 1:
  6326. target = HIGH;
  6327. break;
  6328. case 0:
  6329. target = LOW;
  6330. break;
  6331. case -1:
  6332. target = !digitalRead(pin_number);
  6333. break;
  6334. }
  6335. while(digitalRead(pin_number) != target){
  6336. manage_heater();
  6337. manage_inactivity();
  6338. lcd_update(0);
  6339. }
  6340. }
  6341. }
  6342. }
  6343. }
  6344. break;
  6345. #if NUM_SERVOS > 0
  6346. /*!
  6347. ### M280 - Set/Get servo position <a href="https://reprap.org/wiki/G-code#M280:_Set_servo_position">M280: Set servo position</a>
  6348. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  6349. #### Usage
  6350. M280 [ P | S ]
  6351. #### Parameters
  6352. - `P` - Servo index (id)
  6353. - `S` - Target position
  6354. */
  6355. case 280: // M280 - set servo position absolute. P: servo index, S: angle or microseconds
  6356. {
  6357. int servo_index = -1;
  6358. int servo_position = 0;
  6359. if (code_seen('P'))
  6360. servo_index = code_value();
  6361. if (code_seen('S')) {
  6362. servo_position = code_value();
  6363. if ((servo_index >= 0) && (servo_index < NUM_SERVOS)) {
  6364. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  6365. servos[servo_index].attach(0);
  6366. #endif
  6367. servos[servo_index].write(servo_position);
  6368. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  6369. _delay(PROBE_SERVO_DEACTIVATION_DELAY);
  6370. servos[servo_index].detach();
  6371. #endif
  6372. }
  6373. else {
  6374. SERIAL_ECHO_START;
  6375. SERIAL_ECHO("Servo ");
  6376. SERIAL_ECHO(servo_index);
  6377. SERIAL_ECHOLN(" out of range");
  6378. }
  6379. }
  6380. else if (servo_index >= 0) {
  6381. SERIAL_PROTOCOL(MSG_OK);
  6382. SERIAL_PROTOCOL(" Servo ");
  6383. SERIAL_PROTOCOL(servo_index);
  6384. SERIAL_PROTOCOL(": ");
  6385. SERIAL_PROTOCOLLN(servos[servo_index].read());
  6386. }
  6387. }
  6388. break;
  6389. #endif // NUM_SERVOS > 0
  6390. #if (LARGE_FLASH == true && ( BEEPER > 0 || defined(ULTRALCD) || defined(LCD_USE_I2C_BUZZER)))
  6391. /*!
  6392. ### M300 - Play tone <a href="https://reprap.org/wiki/G-code#M300:_Play_beep_sound">M300: Play beep sound</a>
  6393. In Prusa Firmware the defaults are `100Hz` and `1000ms`, so that `M300` without parameters will beep for a second.
  6394. #### Usage
  6395. M300 [ S | P ]
  6396. #### Parameters
  6397. - `S` - frequency in Hz. Not all firmware versions support this parameter
  6398. - `P` - duration in milliseconds
  6399. */
  6400. case 300: // M300
  6401. {
  6402. uint16_t beepS = code_seen('S') ? code_value() : 0;
  6403. uint16_t beepP = code_seen('P') ? code_value() : 1000;
  6404. #if BEEPER > 0
  6405. if (beepP > 0)
  6406. Sound_MakeCustom(beepP,beepS,false);
  6407. #endif
  6408. }
  6409. break;
  6410. #endif // M300
  6411. #ifdef PIDTEMP
  6412. /*!
  6413. ### M301 - Set hotend PID <a href="https://reprap.org/wiki/G-code#M301:_Set_PID_parameters">M301: Set PID parameters</a>
  6414. Sets Proportional (P), Integral (I) and Derivative (D) values for hot end.
  6415. See also <a href="https://reprap.org/wiki/PID_Tuning">PID Tuning.</a>
  6416. #### Usage
  6417. M301 [ P | I | D ]
  6418. #### Parameters
  6419. - `P` - proportional (Kp)
  6420. - `I` - integral (Ki)
  6421. - `D` - derivative (Kd)
  6422. */
  6423. case 301:
  6424. {
  6425. if(code_seen('P')) cs.Kp = code_value();
  6426. if(code_seen('I')) cs.Ki = scalePID_i(code_value());
  6427. if(code_seen('D')) cs.Kd = scalePID_d(code_value());
  6428. updatePID();
  6429. SERIAL_PROTOCOLRPGM(MSG_OK);
  6430. SERIAL_PROTOCOLPGM(" p:");
  6431. SERIAL_PROTOCOL(cs.Kp);
  6432. SERIAL_PROTOCOLPGM(" i:");
  6433. SERIAL_PROTOCOL(unscalePID_i(cs.Ki));
  6434. SERIAL_PROTOCOLPGM(" d:");
  6435. SERIAL_PROTOCOL(unscalePID_d(cs.Kd));
  6436. SERIAL_PROTOCOLLN();
  6437. }
  6438. break;
  6439. #endif //PIDTEMP
  6440. #ifdef PIDTEMPBED
  6441. /*!
  6442. ### M304 - Set bed PID <a href="https://reprap.org/wiki/G-code#M304:_Set_PID_parameters_-_Bed">M304: Set PID parameters - Bed</a>
  6443. Sets Proportional (P), Integral (I) and Derivative (D) values for bed.
  6444. See also <a href="https://reprap.org/wiki/PID_Tuning">PID Tuning.</a>
  6445. #### Usage
  6446. M304 [ P | I | D ]
  6447. #### Parameters
  6448. - `P` - proportional (Kp)
  6449. - `I` - integral (Ki)
  6450. - `D` - derivative (Kd)
  6451. */
  6452. case 304:
  6453. {
  6454. if(code_seen('P')) cs.bedKp = code_value();
  6455. if(code_seen('I')) cs.bedKi = scalePID_i(code_value());
  6456. if(code_seen('D')) cs.bedKd = scalePID_d(code_value());
  6457. updatePID();
  6458. SERIAL_PROTOCOLRPGM(MSG_OK);
  6459. SERIAL_PROTOCOLPGM(" p:");
  6460. SERIAL_PROTOCOL(cs.bedKp);
  6461. SERIAL_PROTOCOLPGM(" i:");
  6462. SERIAL_PROTOCOL(unscalePID_i(cs.bedKi));
  6463. SERIAL_PROTOCOLPGM(" d:");
  6464. SERIAL_PROTOCOLLN(unscalePID_d(cs.bedKd));
  6465. }
  6466. break;
  6467. #endif //PIDTEMP
  6468. /*!
  6469. ### M240 - Trigger camera <a href="https://reprap.org/wiki/G-code#M240:_Trigger_camera">M240: Trigger camera</a>
  6470. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code.
  6471. You need to (re)define and assign `CHDK` or `PHOTOGRAPH_PIN` the correct pin number to be able to use the feature.
  6472. */
  6473. case 240: // M240 Triggers a camera by emulating a Canon RC-1 : http://www.doc-diy.net/photo/rc-1_hacked/
  6474. {
  6475. #ifdef CHDK
  6476. SET_OUTPUT(CHDK);
  6477. WRITE(CHDK, HIGH);
  6478. chdkHigh = _millis();
  6479. chdkActive = true;
  6480. #else
  6481. #if defined(PHOTOGRAPH_PIN) && PHOTOGRAPH_PIN > -1
  6482. const uint8_t NUM_PULSES=16;
  6483. const float PULSE_LENGTH=0.01524;
  6484. for(int i=0; i < NUM_PULSES; i++) {
  6485. WRITE(PHOTOGRAPH_PIN, HIGH);
  6486. _delay_ms(PULSE_LENGTH);
  6487. WRITE(PHOTOGRAPH_PIN, LOW);
  6488. _delay_ms(PULSE_LENGTH);
  6489. }
  6490. _delay(7.33);
  6491. for(int i=0; i < NUM_PULSES; i++) {
  6492. WRITE(PHOTOGRAPH_PIN, HIGH);
  6493. _delay_ms(PULSE_LENGTH);
  6494. WRITE(PHOTOGRAPH_PIN, LOW);
  6495. _delay_ms(PULSE_LENGTH);
  6496. }
  6497. #endif
  6498. #endif //chdk end if
  6499. }
  6500. break;
  6501. #ifdef PREVENT_DANGEROUS_EXTRUDE
  6502. /*!
  6503. ### 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>
  6504. 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.
  6505. #### Usage
  6506. M302 [ S ]
  6507. #### Parameters
  6508. - `S` - Cold extrude minimum temperature
  6509. */
  6510. case 302:
  6511. {
  6512. int temp = 0;
  6513. if (code_seen('S')) temp=code_value_short();
  6514. set_extrude_min_temp(temp);
  6515. }
  6516. break;
  6517. #endif
  6518. /*!
  6519. ### M303 - PID autotune <a href="https://reprap.org/wiki/G-code#M303:_Run_PID_tuning">M303: Run PID tuning</a>
  6520. 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.
  6521. #### Usage
  6522. M303 [ E | S | C ]
  6523. #### Parameters
  6524. - `E` - Extruder, default `E0`. Use `E-1` to calibrate the bed PID
  6525. - `S` - Target temperature, default `210°C` for hotend, 70 for bed
  6526. - `C` - Cycles, default `5`
  6527. */
  6528. case 303:
  6529. {
  6530. float temp = 150.0;
  6531. int e = 0;
  6532. int c = 5;
  6533. if (code_seen('E')) e = code_value_short();
  6534. if (e < 0)
  6535. temp = 70;
  6536. if (code_seen('S')) temp = code_value();
  6537. if (code_seen('C')) c = code_value_short();
  6538. PID_autotune(temp, e, c);
  6539. }
  6540. break;
  6541. #ifdef TEMP_MODEL
  6542. /*!
  6543. ### M310 - Temperature model settings <a href="https://reprap.org/wiki/G-code#M310:_Temperature_model_settings">M310: Temperature model settings</a>
  6544. #### Usage
  6545. M310 ; report values
  6546. M310 [ A ] [ F ] ; autotune
  6547. M310 [ S ] ; set 0=disable 1=enable
  6548. M310 [ I ] [ R ] ; set resistance at index
  6549. M310 [ P | C ] ; set power, capacitance
  6550. M310 [ B | E | W ] ; set beeper, warning and error threshold
  6551. M310 [ T ] ; set ambient temperature correction
  6552. #### Parameters
  6553. - `I` - resistance index position (0-15)
  6554. - `R` - resistance value at index (K/W; requires `I`)
  6555. - `P` - power (W)
  6556. - `C` - capacitance (J/K)
  6557. - `S` - set 0=disable 1=enable
  6558. - `B` - beep and warn when reaching warning threshold 0=disable 1=enable (default: 1)
  6559. - `E` - error threshold (K/s; default in variant)
  6560. - `W` - warning threshold (K/s; default in variant)
  6561. - `T` - ambient temperature correction (K; default in variant)
  6562. - `A` - autotune C+R values
  6563. - `F` - force model self-test state (0=off 1=on) during autotune using current values
  6564. */
  6565. case 310:
  6566. {
  6567. // parse all parameters
  6568. float P = NAN, C = NAN, R = NAN, E = NAN, W = NAN, T = NAN;
  6569. int8_t I = -1, S = -1, B = -1, A = -1, F = -1;
  6570. if(code_seen('C')) C = code_value();
  6571. if(code_seen('P')) P = code_value();
  6572. if(code_seen('I')) I = code_value_short();
  6573. if(code_seen('R')) R = code_value();
  6574. if(code_seen('S')) S = code_value_short();
  6575. if(code_seen('B')) B = code_value_short();
  6576. if(code_seen('E')) E = code_value();
  6577. if(code_seen('W')) W = code_value();
  6578. if(code_seen('T')) T = code_value();
  6579. if(code_seen('A')) A = code_value_short();
  6580. if(code_seen('F')) F = code_value_short();
  6581. // report values if nothing has been requested
  6582. if(isnan(C) && isnan(P) && isnan(R) && isnan(E) && isnan(W) && isnan(T) && I < 0 && S < 0 && B < 0 && A < 0) {
  6583. temp_model_report_settings();
  6584. break;
  6585. }
  6586. // update all parameters
  6587. if(B >= 0) temp_model_set_warn_beep(B);
  6588. if(!isnan(C) || !isnan(P) || !isnan(T) || !isnan(W) || !isnan(E)) temp_model_set_params(C, P, T, W, E);
  6589. if(I >= 0 && !isnan(R)) temp_model_set_resistance(I, R);
  6590. // enable the model last, if requested
  6591. if(S >= 0) temp_model_set_enabled(S);
  6592. // run autotune
  6593. if(A >= 0) temp_model_autotune(A, F > 0);
  6594. }
  6595. break;
  6596. #endif
  6597. /*!
  6598. ### 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>
  6599. Finishes all current moves and and thus clears the buffer.
  6600. Equivalent to `G4` with no parameters.
  6601. */
  6602. case 400:
  6603. {
  6604. st_synchronize();
  6605. }
  6606. break;
  6607. /*!
  6608. ### 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>
  6609. Currently three different materials are needed (default, flex and PVA).
  6610. And storing this information for different load/unload profiles etc. in the future firmware does not have to wait for "ok" from MMU.
  6611. #### Usage
  6612. M403 [ E | F ]
  6613. #### Parameters
  6614. - `E` - Extruder number. 0-indexed.
  6615. - `F` - Filament type
  6616. */
  6617. case 403:
  6618. {
  6619. // currently three different materials are needed (default, flex and PVA)
  6620. // add storing this information for different load/unload profiles etc. in the future
  6621. // firmware does not wait for "ok" from mmu
  6622. if (mmu_enabled)
  6623. {
  6624. uint8_t extruder = 255;
  6625. uint8_t filament = FILAMENT_UNDEFINED;
  6626. if(code_seen('E')) extruder = code_value_uint8();
  6627. if(code_seen('F')) filament = code_value_uint8();
  6628. mmu_set_filament_type(extruder, filament);
  6629. }
  6630. }
  6631. break;
  6632. /*!
  6633. ### 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>
  6634. Save current parameters to EEPROM.
  6635. */
  6636. case 500:
  6637. {
  6638. Config_StoreSettings();
  6639. }
  6640. break;
  6641. /*!
  6642. ### M501 - Read settings from EEPROM <a href="https://reprap.org/wiki/G-code#M501:_Read_parameters_from_EEPROM">M501: Read parameters from EEPROM</a>
  6643. Set the active parameters to those stored in the EEPROM. This is useful to revert parameters after experimenting with them.
  6644. */
  6645. case 501:
  6646. {
  6647. Config_RetrieveSettings();
  6648. }
  6649. break;
  6650. /*!
  6651. ### M502 - Revert all settings to factory default <a href="https://reprap.org/wiki/G-code#M502:_Restore_Default_Settings">M502: Restore Default Settings</a>
  6652. 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.
  6653. */
  6654. case 502:
  6655. {
  6656. Config_ResetDefault();
  6657. }
  6658. break;
  6659. /*!
  6660. ### M503 - Repport all settings currently in memory <a href="https://reprap.org/wiki/G-code#M503:_Report_Current_Settings">M503: Report Current Settings</a>
  6661. 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.
  6662. */
  6663. case 503:
  6664. {
  6665. Config_PrintSettings();
  6666. }
  6667. break;
  6668. /*!
  6669. ### M509 - Force language selection <a href="https://reprap.org/wiki/G-code#M509:_Force_language_selection">M509: Force language selection</a>
  6670. Resets the language to English.
  6671. Only on Original Prusa i3 MK2.5/s and MK3/s with multiple languages.
  6672. */
  6673. case 509:
  6674. {
  6675. lang_reset();
  6676. SERIAL_ECHO_START;
  6677. SERIAL_PROTOCOLPGM(("LANG SEL FORCED"));
  6678. }
  6679. break;
  6680. #ifdef ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED
  6681. /*!
  6682. ### 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>
  6683. 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`.
  6684. #### Usage
  6685. M540 [ S ]
  6686. #### Parameters
  6687. - `S` - disabled=0, enabled=1
  6688. */
  6689. case 540:
  6690. {
  6691. if(code_seen('S')) abort_on_endstop_hit = code_value() > 0;
  6692. }
  6693. break;
  6694. #endif
  6695. #ifdef ENABLE_AUTO_BED_LEVELING
  6696. /*!
  6697. ### M851 - Set Z-Probe Offset <a href="https://reprap.org/wiki/G-code#M851:_Set_Z-Probe_Offset">M851: Set Z-Probe Offset"</a>
  6698. 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.
  6699. 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.)
  6700. #### Usage
  6701. M851 [ Z ]
  6702. #### Parameters
  6703. - `Z` - Z offset probe to nozzle.
  6704. */
  6705. #ifdef CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  6706. case CUSTOM_M_CODE_SET_Z_PROBE_OFFSET:
  6707. {
  6708. float value;
  6709. if (code_seen('Z'))
  6710. {
  6711. value = code_value();
  6712. if ((Z_PROBE_OFFSET_RANGE_MIN <= value) && (value <= Z_PROBE_OFFSET_RANGE_MAX))
  6713. {
  6714. cs.zprobe_zoffset = -value; // compare w/ line 278 of ConfigurationStore.cpp
  6715. SERIAL_ECHO_START;
  6716. SERIAL_ECHOLNRPGM(CAT4(MSG_ZPROBE_ZOFFSET, " ", MSG_OK,PSTR("")));
  6717. SERIAL_PROTOCOLLN();
  6718. }
  6719. else
  6720. {
  6721. SERIAL_ECHO_START;
  6722. SERIAL_ECHORPGM(MSG_ZPROBE_ZOFFSET);
  6723. SERIAL_ECHORPGM(MSG_Z_MIN);
  6724. SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MIN);
  6725. SERIAL_ECHORPGM(MSG_Z_MAX);
  6726. SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MAX);
  6727. SERIAL_PROTOCOLLN();
  6728. }
  6729. }
  6730. else
  6731. {
  6732. SERIAL_ECHO_START;
  6733. SERIAL_ECHOLNRPGM(CAT2(MSG_ZPROBE_ZOFFSET, PSTR(" : ")));
  6734. SERIAL_ECHO(-cs.zprobe_zoffset);
  6735. SERIAL_PROTOCOLLN();
  6736. }
  6737. break;
  6738. }
  6739. #endif // CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  6740. #endif // ENABLE_AUTO_BED_LEVELING
  6741. /*!
  6742. ### 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>
  6743. Sets the printer IP address that is shown in the support menu. Designed to be used with the help of host software.
  6744. If P is not specified nothing happens.
  6745. 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.
  6746. #### Usage
  6747. M552 [ P<IP_address> ]
  6748. #### Parameters
  6749. - `P` - The IP address in xxx.xxx.xxx.xxx format. Eg: P192.168.1.14
  6750. */
  6751. case 552:
  6752. {
  6753. if (code_seen('P'))
  6754. {
  6755. uint8_t valCnt = 0;
  6756. IP_address = 0;
  6757. do
  6758. {
  6759. *strchr_pointer = '*';
  6760. ((uint8_t*)&IP_address)[valCnt] = code_value_short();
  6761. valCnt++;
  6762. } while ((valCnt < 4) && code_seen('.'));
  6763. if (valCnt != 4)
  6764. IP_address = 0;
  6765. }
  6766. } break;
  6767. #ifdef FILAMENTCHANGEENABLE
  6768. /*!
  6769. ### M600 - Initiate Filament change procedure <a href="https://reprap.org/wiki/G-code#M600:_Filament_change_pause">M600: Filament change pause</a>
  6770. Initiates Filament change, it is also used during Filament Runout Sensor process.
  6771. If the `M600` is triggered under 25mm it will do a Z-lift of 25mm to prevent a filament blob.
  6772. #### Usage
  6773. M600 [ X | Y | Z | E | L | AUTO ]
  6774. - `X` - X position, default 211
  6775. - `Y` - Y position, default 0
  6776. - `Z` - relative lift Z, default 2.
  6777. - `E` - initial retract, default -2
  6778. - `L` - later retract distance for removal, default -80
  6779. - `AUTO` - Automatically (only with MMU)
  6780. */
  6781. case 600: //Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  6782. {
  6783. st_synchronize();
  6784. float x_position = current_position[X_AXIS];
  6785. float y_position = current_position[Y_AXIS];
  6786. float z_shift = 0; // is it necessary to be a float?
  6787. float e_shift_init = 0;
  6788. float e_shift_late = 0;
  6789. bool automatic = false;
  6790. //Retract extruder
  6791. if(code_seen('E'))
  6792. {
  6793. e_shift_init = code_value();
  6794. }
  6795. else
  6796. {
  6797. #ifdef FILAMENTCHANGE_FIRSTRETRACT
  6798. e_shift_init = FILAMENTCHANGE_FIRSTRETRACT ;
  6799. #endif
  6800. }
  6801. //currently don't work as we are using the same unload sequence as in M702, needs re-work
  6802. if (code_seen('L'))
  6803. {
  6804. e_shift_late = code_value();
  6805. }
  6806. else
  6807. {
  6808. #ifdef FILAMENTCHANGE_FINALRETRACT
  6809. e_shift_late = FILAMENTCHANGE_FINALRETRACT;
  6810. #endif
  6811. }
  6812. //Lift Z
  6813. if(code_seen('Z'))
  6814. {
  6815. z_shift = code_value();
  6816. }
  6817. else
  6818. {
  6819. z_shift = gcode_M600_filament_change_z_shift<uint8_t>();
  6820. }
  6821. //Move XY to side
  6822. if(code_seen('X'))
  6823. {
  6824. x_position = code_value();
  6825. }
  6826. else
  6827. {
  6828. #ifdef FILAMENTCHANGE_XPOS
  6829. x_position = FILAMENTCHANGE_XPOS;
  6830. #endif
  6831. }
  6832. if(code_seen('Y'))
  6833. {
  6834. y_position = code_value();
  6835. }
  6836. else
  6837. {
  6838. #ifdef FILAMENTCHANGE_YPOS
  6839. y_position = FILAMENTCHANGE_YPOS ;
  6840. #endif
  6841. }
  6842. if (mmu_enabled && code_seen_P(PSTR("AUTO")))
  6843. automatic = true;
  6844. gcode_M600(automatic, x_position, y_position, z_shift, e_shift_init, e_shift_late);
  6845. }
  6846. break;
  6847. #endif //FILAMENTCHANGEENABLE
  6848. /*!
  6849. ### M601 - Pause print <a href="https://reprap.org/wiki/G-code#M601:_Pause_print">M601: Pause print</a>
  6850. */
  6851. /*!
  6852. ### M125 - Pause print (TODO: not implemented)
  6853. */
  6854. /*!
  6855. ### M25 - Pause SD print <a href="https://reprap.org/wiki/G-code#M25:_Pause_SD_print">M25: Pause SD print</a>
  6856. */
  6857. case 25:
  6858. case 601:
  6859. {
  6860. if (!isPrintPaused) {
  6861. st_synchronize();
  6862. ClearToSend(); //send OK even before the command finishes executing because we want to make sure it is not skipped because of cmdqueue_pop_front();
  6863. cmdqueue_pop_front(); //trick because we want skip this command (M601) after restore
  6864. lcd_pause_print();
  6865. }
  6866. }
  6867. break;
  6868. /*!
  6869. ### M602 - Resume print <a href="https://reprap.org/wiki/G-code#M602:_Resume_print">M602: Resume print</a>
  6870. */
  6871. case 602:
  6872. {
  6873. if (isPrintPaused) lcd_resume_print();
  6874. }
  6875. break;
  6876. /*!
  6877. ### M603 - Stop print <a href="https://reprap.org/wiki/G-code#M603:_Stop_print">M603: Stop print</a>
  6878. */
  6879. case 603: {
  6880. lcd_print_stop();
  6881. }
  6882. break;
  6883. #ifdef PINDA_THERMISTOR
  6884. /*!
  6885. ### 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>
  6886. Wait for PINDA thermistor to reach target temperature
  6887. #### Usage
  6888. M860 [ S ]
  6889. #### Parameters
  6890. - `S` - Target temperature
  6891. */
  6892. case 860:
  6893. {
  6894. int set_target_pinda = 0;
  6895. if (code_seen('S')) {
  6896. set_target_pinda = code_value_short();
  6897. }
  6898. else {
  6899. break;
  6900. }
  6901. LCD_MESSAGERPGM(_T(MSG_PLEASE_WAIT));
  6902. SERIAL_PROTOCOLPGM("Wait for PINDA target temperature:");
  6903. SERIAL_PROTOCOLLN(set_target_pinda);
  6904. codenum = _millis();
  6905. cancel_heatup = false;
  6906. bool is_pinda_cooling = false;
  6907. if ((degTargetBed() == 0) && (degTargetHotend(0) == 0)) {
  6908. is_pinda_cooling = true;
  6909. }
  6910. while ( ((!is_pinda_cooling) && (!cancel_heatup) && (current_temperature_pinda < set_target_pinda)) || (is_pinda_cooling && (current_temperature_pinda > set_target_pinda)) ) {
  6911. if ((_millis() - codenum) > 1000) //Print Temp Reading every 1 second while waiting.
  6912. {
  6913. SERIAL_PROTOCOLPGM("P:");
  6914. SERIAL_PROTOCOL_F(current_temperature_pinda, 1);
  6915. SERIAL_PROTOCOL('/');
  6916. SERIAL_PROTOCOLLN(set_target_pinda);
  6917. codenum = _millis();
  6918. }
  6919. manage_heater();
  6920. manage_inactivity();
  6921. lcd_update(0);
  6922. }
  6923. LCD_MESSAGERPGM(MSG_OK);
  6924. break;
  6925. }
  6926. /*!
  6927. ### 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>
  6928. Set compensation ustep value `S` for compensation table index `I`.
  6929. #### Usage
  6930. M861 [ ? | ! | Z | S | I ]
  6931. #### Parameters
  6932. - `?` - Print current EEPROM offset values
  6933. - `!` - Set factory default values
  6934. - `Z` - Set all values to 0 (effectively disabling PINDA temperature compensation)
  6935. - `S` - Microsteps
  6936. - `I` - Table index
  6937. */
  6938. case 861: {
  6939. const char * const _header = PSTR("index, temp, ustep, um");
  6940. if (code_seen('?')) { // ? - Print out current EEPROM offset values
  6941. int16_t usteps = 0;
  6942. SERIAL_PROTOCOLPGM("PINDA cal status: ");
  6943. SERIAL_PROTOCOLLN(calibration_status_pinda());
  6944. SERIAL_PROTOCOLLNRPGM(_header);
  6945. for (uint8_t i = 0; i < 6; i++)
  6946. {
  6947. if(i > 0) {
  6948. usteps = eeprom_read_word((uint16_t*) EEPROM_PROBE_TEMP_SHIFT + (i - 1));
  6949. }
  6950. float mm = ((float)usteps) / cs.axis_steps_per_unit[Z_AXIS];
  6951. i == 0 ? SERIAL_PROTOCOLPGM("n/a") : SERIAL_PROTOCOL(i - 1);
  6952. SERIAL_PROTOCOLPGM(", ");
  6953. SERIAL_PROTOCOL(35 + (i * 5));
  6954. SERIAL_PROTOCOLPGM(", ");
  6955. SERIAL_PROTOCOL(usteps);
  6956. SERIAL_PROTOCOLPGM(", ");
  6957. SERIAL_PROTOCOLLN(mm * 1000);
  6958. }
  6959. }
  6960. else if (code_seen('!')) { // ! - Set factory default values
  6961. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  6962. int16_t z_shift = 8; //40C - 20um - 8usteps
  6963. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT, z_shift);
  6964. z_shift = 24; //45C - 60um - 24usteps
  6965. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + 1, z_shift);
  6966. z_shift = 48; //50C - 120um - 48usteps
  6967. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + 2, z_shift);
  6968. z_shift = 80; //55C - 200um - 80usteps
  6969. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + 3, z_shift);
  6970. z_shift = 120; //60C - 300um - 120usteps
  6971. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + 4, z_shift);
  6972. SERIAL_PROTOCOLLNPGM("factory restored");
  6973. }
  6974. else if (code_seen('Z')) { // Z - Set all values to 0 (effectively disabling PINDA temperature compensation)
  6975. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  6976. int16_t z_shift = 0;
  6977. for (uint8_t i = 0; i < 5; i++) {
  6978. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i, z_shift);
  6979. }
  6980. SERIAL_PROTOCOLLNPGM("zerorized");
  6981. }
  6982. else if (code_seen('S')) { // Sxxx Iyyy - Set compensation ustep value S for compensation table index I
  6983. int16_t usteps = code_value_short();
  6984. if (code_seen('I')) {
  6985. uint8_t index = code_value_uint8();
  6986. if (index < 5) {
  6987. eeprom_update_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + index, usteps);
  6988. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  6989. SERIAL_PROTOCOLLNRPGM(_header);
  6990. for (uint8_t i = 0; i < 6; i++)
  6991. {
  6992. usteps = 0;
  6993. if (i > 0) {
  6994. usteps = eeprom_read_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + (i - 1));
  6995. }
  6996. float mm = ((float)usteps) / cs.axis_steps_per_unit[Z_AXIS];
  6997. i == 0 ? SERIAL_PROTOCOLPGM("n/a") : SERIAL_PROTOCOL(i - 1);
  6998. SERIAL_PROTOCOLPGM(", ");
  6999. SERIAL_PROTOCOL(35 + (i * 5));
  7000. SERIAL_PROTOCOLPGM(", ");
  7001. SERIAL_PROTOCOL(usteps);
  7002. SERIAL_PROTOCOLPGM(", ");
  7003. SERIAL_PROTOCOLLN(mm * 1000);
  7004. }
  7005. }
  7006. }
  7007. }
  7008. else {
  7009. SERIAL_PROTOCOLLNPGM("no valid command");
  7010. }
  7011. } break;
  7012. #endif //PINDA_THERMISTOR
  7013. /*!
  7014. ### M862 - Print checking <a href="https://reprap.org/wiki/G-code#M862:_Print_checking">M862: Print checking</a>
  7015. Checks the parameters of the printer and gcode and performs compatibility check
  7016. - M862.1 { P<nozzle_diameter> | Q } 0.25/0.40/0.60
  7017. - M862.2 { P<model_code> | Q }
  7018. - M862.3 { P"<model_name>" | Q }
  7019. - M862.4 { P<fw_version> | Q }
  7020. - M862.5 { P<gcode_level> | Q }
  7021. When run with P<> argument, the check is performed against the input value.
  7022. When run with Q argument, the current value is shown.
  7023. M862.3 accepts text identifiers of printer types too.
  7024. The syntax of M862.3 is (note the quotes around the type):
  7025. M862.3 P "MK3S"
  7026. Accepted printer type identifiers and their numeric counterparts:
  7027. - MK1 (100)
  7028. - MK2 (200)
  7029. - MK2MM (201)
  7030. - MK2S (202)
  7031. - MK2SMM (203)
  7032. - MK2.5 (250)
  7033. - MK2.5MMU2 (20250)
  7034. - MK2.5S (252)
  7035. - MK2.5SMMU2S (20252)
  7036. - MK3 (300)
  7037. - MK3MMU2 (20300)
  7038. - MK3S (302)
  7039. - MK3SMMU2S (20302)
  7040. */
  7041. case 862: // M862: print checking
  7042. float nDummy;
  7043. uint8_t nCommand;
  7044. nCommand=(uint8_t)(modff(code_value_float(),&nDummy)*10.0+0.5);
  7045. switch((ClPrintChecking)nCommand)
  7046. {
  7047. case ClPrintChecking::_Nozzle: // ~ .1
  7048. uint16_t nDiameter;
  7049. if(code_seen('P'))
  7050. {
  7051. nDiameter=(uint16_t)(code_value()*1000.0+0.5); // [,um]
  7052. nozzle_diameter_check(nDiameter);
  7053. }
  7054. else if(code_seen('Q'))
  7055. SERIAL_PROTOCOLLN((float)eeprom_read_word((uint16_t*)EEPROM_NOZZLE_DIAMETER_uM)/1000.0);
  7056. break;
  7057. case ClPrintChecking::_Model: // ~ .2
  7058. if(code_seen('P'))
  7059. {
  7060. uint16_t nPrinterModel;
  7061. nPrinterModel=(uint16_t)code_value_long();
  7062. printer_model_check(nPrinterModel);
  7063. }
  7064. else if(code_seen('Q'))
  7065. SERIAL_PROTOCOLLN(nPrinterType);
  7066. break;
  7067. case ClPrintChecking::_Smodel: // ~ .3
  7068. if(code_seen('P'))
  7069. printer_smodel_check(strchr_pointer);
  7070. else if(code_seen('Q'))
  7071. SERIAL_PROTOCOLLNRPGM(sPrinterName);
  7072. break;
  7073. case ClPrintChecking::_Version: // ~ .4
  7074. if(code_seen('P'))
  7075. fw_version_check(++strchr_pointer);
  7076. else if(code_seen('Q'))
  7077. SERIAL_PROTOCOLLNRPGM(FW_VERSION_STR_P());
  7078. break;
  7079. case ClPrintChecking::_Gcode: // ~ .5
  7080. if(code_seen('P'))
  7081. {
  7082. uint16_t nGcodeLevel;
  7083. nGcodeLevel=(uint16_t)code_value_long();
  7084. gcode_level_check(nGcodeLevel);
  7085. }
  7086. else if(code_seen('Q'))
  7087. SERIAL_PROTOCOLLN(GCODE_LEVEL);
  7088. break;
  7089. }
  7090. break;
  7091. #ifdef LIN_ADVANCE
  7092. /*!
  7093. ### 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>
  7094. 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.
  7095. #### Usage
  7096. M900 [ K | R | W | H | D]
  7097. #### Parameters
  7098. - `K` - Advance K factor
  7099. - `R` - Set ratio directly (overrides WH/D)
  7100. - `W` - Width
  7101. - `H` - Height
  7102. - `D` - Diameter Set ratio from WH/D
  7103. */
  7104. case 900:
  7105. gcode_M900();
  7106. break;
  7107. #endif
  7108. /*!
  7109. ### 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>
  7110. Set digital trimpot motor current using axis codes (X, Y, Z, E, B, S).
  7111. M907 has no effect when the experimental Extruder motor current scaling mode is active (that applies to farm printing as well)
  7112. #### Usage
  7113. M907 [ X | Y | Z | E | B | S ]
  7114. #### Parameters
  7115. - `X` - X motor driver
  7116. - `Y` - Y motor driver
  7117. - `Z` - Z motor driver
  7118. - `E` - Extruder motor driver
  7119. - `B` - Second Extruder motor driver
  7120. - `S` - All motors
  7121. */
  7122. case 907:
  7123. {
  7124. #ifdef TMC2130
  7125. // See tmc2130_cur2val() for translation to 0 .. 63 range
  7126. for (uint_least8_t i = 0; i < NUM_AXIS; i++){
  7127. if(code_seen(axis_codes[i])){
  7128. if( i == E_AXIS && FarmOrUserECool() ){
  7129. SERIAL_ECHORPGM(eMotorCurrentScalingEnabled);
  7130. SERIAL_ECHOLNPGM(", M907 E ignored");
  7131. continue;
  7132. }
  7133. long cur_mA = code_value_long();
  7134. uint8_t val = tmc2130_cur2val(cur_mA);
  7135. tmc2130_set_current_h(i, val);
  7136. tmc2130_set_current_r(i, val);
  7137. //if (i == E_AXIS) printf_P(PSTR("E-axis current=%ldmA\n"), cur_mA);
  7138. }
  7139. }
  7140. #else //TMC2130
  7141. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  7142. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) st_current_set(i,code_value());
  7143. if(code_seen('B')) st_current_set(4,code_value());
  7144. if(code_seen('S')) for(int i=0;i<=4;i++) st_current_set(i,code_value());
  7145. #endif
  7146. #ifdef MOTOR_CURRENT_PWM_XY_PIN
  7147. if(code_seen('X')) st_current_set(0, code_value());
  7148. #endif
  7149. #ifdef MOTOR_CURRENT_PWM_Z_PIN
  7150. if(code_seen('Z')) st_current_set(1, code_value());
  7151. #endif
  7152. #ifdef MOTOR_CURRENT_PWM_E_PIN
  7153. if(code_seen('E')) st_current_set(2, code_value());
  7154. #endif
  7155. #endif //TMC2130
  7156. }
  7157. break;
  7158. /*!
  7159. ### M908 - Control digital trimpot directly <a href="https://reprap.org/wiki/G-code#M908:_Control_digital_trimpot_directly">M908: Control digital trimpot directly</a>
  7160. In Prusa Firmware this G-code is deactivated by default, must be turned on in the source code. Not usable on Prusa printers.
  7161. #### Usage
  7162. M908 [ P | S ]
  7163. #### Parameters
  7164. - `P` - channel
  7165. - `S` - current
  7166. */
  7167. case 908:
  7168. {
  7169. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  7170. uint8_t channel,current;
  7171. if(code_seen('P')) channel=code_value();
  7172. if(code_seen('S')) current=code_value();
  7173. digitalPotWrite(channel, current);
  7174. #endif
  7175. }
  7176. break;
  7177. #ifdef TMC2130_SERVICE_CODES_M910_M918
  7178. /*!
  7179. ### M910 - TMC2130 init <a href="https://reprap.org/wiki/G-code#M910:_TMC2130_init">M910: TMC2130 init</a>
  7180. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7181. */
  7182. case 910:
  7183. {
  7184. tmc2130_init(TMCInitParams(false, FarmOrUserECool()));
  7185. }
  7186. break;
  7187. /*!
  7188. ### M911 - Set TMC2130 holding currents <a href="https://reprap.org/wiki/G-code#M911:_Set_TMC2130_holding_currents">M911: Set TMC2130 holding currents</a>
  7189. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7190. #### Usage
  7191. M911 [ X | Y | Z | E ]
  7192. #### Parameters
  7193. - `X` - X stepper driver holding current value
  7194. - `Y` - Y stepper driver holding current value
  7195. - `Z` - Z stepper driver holding current value
  7196. - `E` - Extruder stepper driver holding current value
  7197. */
  7198. case 911:
  7199. {
  7200. if (code_seen('X')) tmc2130_set_current_h(0, code_value());
  7201. if (code_seen('Y')) tmc2130_set_current_h(1, code_value());
  7202. if (code_seen('Z')) tmc2130_set_current_h(2, code_value());
  7203. if (code_seen('E')) tmc2130_set_current_h(3, code_value());
  7204. }
  7205. break;
  7206. /*!
  7207. ### M912 - Set TMC2130 running currents <a href="https://reprap.org/wiki/G-code#M912:_Set_TMC2130_running_currents">M912: Set TMC2130 running currents</a>
  7208. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7209. #### Usage
  7210. M912 [ X | Y | Z | E ]
  7211. #### Parameters
  7212. - `X` - X stepper driver running current value
  7213. - `Y` - Y stepper driver running current value
  7214. - `Z` - Z stepper driver running current value
  7215. - `E` - Extruder stepper driver running current value
  7216. */
  7217. case 912:
  7218. {
  7219. if (code_seen('X')) tmc2130_set_current_r(0, code_value());
  7220. if (code_seen('Y')) tmc2130_set_current_r(1, code_value());
  7221. if (code_seen('Z')) tmc2130_set_current_r(2, code_value());
  7222. if (code_seen('E')) tmc2130_set_current_r(3, code_value());
  7223. }
  7224. break;
  7225. /*!
  7226. ### M913 - Print TMC2130 currents <a href="https://reprap.org/wiki/G-code#M913:_Print_TMC2130_currents">M913: Print TMC2130 currents</a>
  7227. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7228. Shows TMC2130 currents.
  7229. */
  7230. case 913:
  7231. {
  7232. tmc2130_print_currents();
  7233. }
  7234. break;
  7235. /*!
  7236. ### M914 - Set TMC2130 normal mode <a href="https://reprap.org/wiki/G-code#M914:_Set_TMC2130_normal_mode">M914: Set TMC2130 normal mode</a>
  7237. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7238. */
  7239. case 914:
  7240. {
  7241. tmc2130_mode = TMC2130_MODE_NORMAL;
  7242. update_mode_profile();
  7243. tmc2130_init(TMCInitParams(false, FarmOrUserECool()));
  7244. }
  7245. break;
  7246. /*!
  7247. ### M915 - Set TMC2130 silent mode <a href="https://reprap.org/wiki/G-code#M915:_Set_TMC2130_silent_mode">M915: Set TMC2130 silent mode</a>
  7248. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7249. */
  7250. case 915:
  7251. {
  7252. tmc2130_mode = TMC2130_MODE_SILENT;
  7253. update_mode_profile();
  7254. tmc2130_init(TMCInitParams(false, FarmOrUserECool()));
  7255. }
  7256. break;
  7257. /*!
  7258. ### 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>
  7259. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7260. #### Usage
  7261. M916 [ X | Y | Z | E ]
  7262. #### Parameters
  7263. - `X` - X stepper driver stallguard sensitivity threshold value
  7264. - `Y` - Y stepper driver stallguard sensitivity threshold value
  7265. - `Z` - Z stepper driver stallguard sensitivity threshold value
  7266. - `E` - Extruder stepper driver stallguard sensitivity threshold value
  7267. */
  7268. case 916:
  7269. {
  7270. if (code_seen('X')) tmc2130_sg_thr[X_AXIS] = code_value();
  7271. if (code_seen('Y')) tmc2130_sg_thr[Y_AXIS] = code_value();
  7272. if (code_seen('Z')) tmc2130_sg_thr[Z_AXIS] = code_value();
  7273. if (code_seen('E')) tmc2130_sg_thr[E_AXIS] = code_value();
  7274. for (uint8_t a = X_AXIS; a <= E_AXIS; a++)
  7275. printf_P(_N("tmc2130_sg_thr[%c]=%d\n"), "XYZE"[a], tmc2130_sg_thr[a]);
  7276. }
  7277. break;
  7278. /*!
  7279. ### 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>
  7280. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7281. #### Usage
  7282. M917 [ X | Y | Z | E ]
  7283. #### Parameters
  7284. - `X` - X stepper driver PWM amplitude offset value
  7285. - `Y` - Y stepper driver PWM amplitude offset value
  7286. - `Z` - Z stepper driver PWM amplitude offset value
  7287. - `E` - Extruder stepper driver PWM amplitude offset value
  7288. */
  7289. case 917:
  7290. {
  7291. if (code_seen('X')) tmc2130_set_pwm_ampl(0, code_value());
  7292. if (code_seen('Y')) tmc2130_set_pwm_ampl(1, code_value());
  7293. if (code_seen('Z')) tmc2130_set_pwm_ampl(2, code_value());
  7294. if (code_seen('E')) tmc2130_set_pwm_ampl(3, code_value());
  7295. }
  7296. break;
  7297. /*!
  7298. ### 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>
  7299. Not active in default, only if `TMC2130_SERVICE_CODES_M910_M918` is defined in source code.
  7300. #### Usage
  7301. M918 [ X | Y | Z | E ]
  7302. #### Parameters
  7303. - `X` - X stepper driver PWM amplitude gradient value
  7304. - `Y` - Y stepper driver PWM amplitude gradient value
  7305. - `Z` - Z stepper driver PWM amplitude gradient value
  7306. - `E` - Extruder stepper driver PWM amplitude gradient value
  7307. */
  7308. case 918:
  7309. {
  7310. if (code_seen('X')) tmc2130_set_pwm_grad(0, code_value());
  7311. if (code_seen('Y')) tmc2130_set_pwm_grad(1, code_value());
  7312. if (code_seen('Z')) tmc2130_set_pwm_grad(2, code_value());
  7313. if (code_seen('E')) tmc2130_set_pwm_grad(3, code_value());
  7314. }
  7315. break;
  7316. #endif //TMC2130_SERVICE_CODES_M910_M918
  7317. /*!
  7318. ### M350 - Set microstepping mode <a href="https://reprap.org/wiki/G-code#M350:_Set_microstepping_mode">M350: Set microstepping mode</a>
  7319. 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!
  7320. Printers without TMC2130 drivers also have `B` and `S` options. In this case, the steps-per-unit value in not changed!
  7321. #### Usage
  7322. M350 [ X | Y | Z | E | B | S ]
  7323. #### Parameters
  7324. - `X` - X new resolution
  7325. - `Y` - Y new resolution
  7326. - `Z` - Z new resolution
  7327. - `E` - E new resolution
  7328. Only valid for MK2.5(S) or printers without TMC2130 drivers
  7329. - `B` - Second extruder new resolution
  7330. - `S` - All axes new resolution
  7331. */
  7332. case 350:
  7333. {
  7334. #ifdef TMC2130
  7335. for (uint_least8_t i=0; i<NUM_AXIS; i++)
  7336. {
  7337. if(code_seen(axis_codes[i]))
  7338. {
  7339. uint16_t res_new = code_value();
  7340. #ifdef ALLOW_ALL_MRES
  7341. bool res_valid = res_new > 0 && res_new <= 256 && !(res_new & (res_new - 1)); // must be a power of two
  7342. #else
  7343. bool res_valid = (res_new == 8) || (res_new == 16) || (res_new == 32); // resolutions valid for all axis
  7344. res_valid |= (i != E_AXIS) && ((res_new == 1) || (res_new == 2) || (res_new == 4)); // resolutions valid for X Y Z only
  7345. res_valid |= (i == E_AXIS) && ((res_new == 64) || (res_new == 128)); // resolutions valid for E only
  7346. #endif
  7347. if (res_valid)
  7348. {
  7349. st_synchronize();
  7350. uint16_t res = tmc2130_get_res(i);
  7351. tmc2130_set_res(i, res_new);
  7352. cs.axis_ustep_resolution[i] = res_new;
  7353. if (res_new > res)
  7354. {
  7355. uint16_t fac = (res_new / res);
  7356. cs.axis_steps_per_unit[i] *= fac;
  7357. position[i] *= fac;
  7358. }
  7359. else
  7360. {
  7361. uint16_t fac = (res / res_new);
  7362. cs.axis_steps_per_unit[i] /= fac;
  7363. position[i] /= fac;
  7364. }
  7365. #if defined(FILAMENT_SENSOR) && defined(PAT9125)
  7366. if (i == E_AXIS)
  7367. fsensor_set_axis_steps_per_unit(cs.axis_steps_per_unit[i]);
  7368. #endif
  7369. }
  7370. }
  7371. }
  7372. reset_acceleration_rates();
  7373. #else //TMC2130
  7374. #if defined(X_MS1_PIN) && X_MS1_PIN > -1
  7375. if(code_seen('S')) for(int i=0;i<=4;i++) microstep_mode(i,code_value());
  7376. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_mode(i,(uint8_t)code_value());
  7377. if(code_seen('B')) microstep_mode(4,code_value());
  7378. microstep_readings();
  7379. #endif
  7380. #endif //TMC2130
  7381. }
  7382. break;
  7383. /*!
  7384. ### 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>
  7385. Toggle MS1 MS2 pins directly.
  7386. #### Usage
  7387. M351 [B<0|1>] [E<0|1>] S<1|2> [X<0|1>] [Y<0|1>] [Z<0|1>]
  7388. #### Parameters
  7389. - `X` - Update X axis
  7390. - `Y` - Update Y axis
  7391. - `Z` - Update Z axis
  7392. - `E` - Update E axis
  7393. - `S` - which MSx pin to toggle
  7394. - `B` - new pin value
  7395. */
  7396. case 351:
  7397. {
  7398. #if defined(X_MS1_PIN) && X_MS1_PIN > -1
  7399. if(code_seen('S')) switch((int)code_value())
  7400. {
  7401. case 1:
  7402. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_ms(i,code_value(),-1);
  7403. if(code_seen('B')) microstep_ms(4,code_value(),-1);
  7404. break;
  7405. case 2:
  7406. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_ms(i,-1,code_value());
  7407. if(code_seen('B')) microstep_ms(4,-1,code_value());
  7408. break;
  7409. }
  7410. microstep_readings();
  7411. #endif
  7412. }
  7413. break;
  7414. /*!
  7415. ### M701 - Load filament <a href="https://reprap.org/wiki/G-code#M701:_Load_filament">M701: Load filament</a>
  7416. #### Usage
  7417. M701 [ E | T ]
  7418. #### Parameters
  7419. - `E` - ID of filament to load, ranges from 0 to 4
  7420. - `T` - Alias of `E`. Used for compatibility with Marlin
  7421. */
  7422. case 701:
  7423. {
  7424. if (mmu_enabled && (code_seen('E') || code_seen('T')))
  7425. tmp_extruder = code_value_uint8();
  7426. gcode_M701();
  7427. }
  7428. break;
  7429. /*!
  7430. ### M702 - Unload filament <a href="https://reprap.org/wiki/G-code#M702:_Unload_filament">G32: Undock Z Probe sled</a>
  7431. #### Usage
  7432. M702 [ C ]
  7433. #### Parameters
  7434. - `C` - Unload just current filament
  7435. - without any parameters unload all filaments
  7436. */
  7437. case 702:
  7438. {
  7439. if (code_seen('C')) {
  7440. if(mmu_enabled) extr_unload(); //! if "C" unload current filament; if mmu is not present no action is performed
  7441. }
  7442. else {
  7443. if(mmu_enabled) extr_unload(); //! unload current filament
  7444. else unload_filament();
  7445. }
  7446. }
  7447. break;
  7448. /*!
  7449. #### End of M-Commands
  7450. */
  7451. default:
  7452. printf_P(MSG_UNKNOWN_CODE, 'M', cmdbuffer + bufindr + CMDHDRSIZE);
  7453. }
  7454. // printf_P(_N("END M-CODE=%u\n"), mcode_in_progress);
  7455. mcode_in_progress = 0;
  7456. }
  7457. }
  7458. // end if(code_seen('M')) (end of M codes)
  7459. /*!
  7460. -----------------------------------------------------------------------------------------
  7461. # T Codes
  7462. T<extruder nr.> - select extruder in case of multi extruder printer. select filament in case of MMU_V2.
  7463. #### For MMU_V2:
  7464. T<n> Gcode to extrude at least 38.10 mm at feedrate 19.02 mm/s must follow immediately to load to extruder wheels.
  7465. @n T? Gcode to extrude shouldn't have to follow, load to extruder wheels is done automatically
  7466. @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.
  7467. @n Tc Load to nozzle after filament was prepared by Tc and extruder nozzle is already heated.
  7468. */
  7469. else if(code_seen('T'))
  7470. {
  7471. static const char duplicate_Tcode_ignored[] PROGMEM = "Duplicate T-code ignored.";
  7472. int index;
  7473. bool load_to_nozzle = false;
  7474. for (index = 1; *(strchr_pointer + index) == ' ' || *(strchr_pointer + index) == '\t'; index++);
  7475. *(strchr_pointer + index) = tolower(*(strchr_pointer + index));
  7476. if ((*(strchr_pointer + index) < '0' || *(strchr_pointer + index) > '4') && *(strchr_pointer + index) != '?' && *(strchr_pointer + index) != 'x' && *(strchr_pointer + index) != 'c') {
  7477. SERIAL_ECHOLNPGM("Invalid T code.");
  7478. }
  7479. else if (*(strchr_pointer + index) == 'x'){ //load to bondtech gears; if mmu is not present do nothing
  7480. if (mmu_enabled)
  7481. {
  7482. tmp_extruder = choose_menu_P(_T(MSG_SELECT_FILAMENT), _T(MSG_FILAMENT));
  7483. if ((tmp_extruder == mmu_extruder) && mmu_fil_loaded) //dont execute the same T-code twice in a row
  7484. {
  7485. puts_P(duplicate_Tcode_ignored);
  7486. }
  7487. else
  7488. {
  7489. st_synchronize();
  7490. mmu_command(MmuCmd::T0 + tmp_extruder);
  7491. manage_response(true, true, MMU_TCODE_MOVE);
  7492. }
  7493. }
  7494. }
  7495. else if (*(strchr_pointer + index) == 'c') { //load to from bondtech gears to nozzle (nozzle should be preheated)
  7496. if (mmu_enabled)
  7497. {
  7498. st_synchronize();
  7499. mmu_continue_loading(usb_timer.running() || (lcd_commands_type == LcdCommands::Layer1Cal));
  7500. mmu_extruder = tmp_extruder; //filament change is finished
  7501. mmu_load_to_nozzle();
  7502. }
  7503. }
  7504. else {
  7505. if (*(strchr_pointer + index) == '?')
  7506. {
  7507. if(mmu_enabled)
  7508. {
  7509. tmp_extruder = choose_menu_P(_T(MSG_SELECT_FILAMENT), _T(MSG_FILAMENT));
  7510. load_to_nozzle = true;
  7511. } else
  7512. {
  7513. tmp_extruder = choose_menu_P(_T(MSG_SELECT_EXTRUDER), _T(MSG_EXTRUDER));
  7514. }
  7515. }
  7516. else {
  7517. tmp_extruder = code_value();
  7518. if (mmu_enabled && lcd_autoDepleteEnabled())
  7519. {
  7520. tmp_extruder = ad_getAlternative(tmp_extruder);
  7521. }
  7522. }
  7523. st_synchronize();
  7524. if (mmu_enabled)
  7525. {
  7526. if ((tmp_extruder == mmu_extruder) && mmu_fil_loaded) //dont execute the same T-code twice in a row
  7527. {
  7528. puts_P(duplicate_Tcode_ignored);
  7529. }
  7530. else
  7531. {
  7532. #if defined(MMU_HAS_CUTTER) && defined(MMU_ALWAYS_CUT)
  7533. if (EEPROM_MMU_CUTTER_ENABLED_always == eeprom_read_byte((uint8_t*)EEPROM_MMU_CUTTER_ENABLED))
  7534. {
  7535. mmu_command(MmuCmd::K0 + tmp_extruder);
  7536. manage_response(true, true, MMU_UNLOAD_MOVE);
  7537. }
  7538. #endif //defined(MMU_HAS_CUTTER) && defined(MMU_ALWAYS_CUT)
  7539. mmu_command(MmuCmd::T0 + tmp_extruder);
  7540. manage_response(true, true, MMU_TCODE_MOVE);
  7541. mmu_continue_loading(usb_timer.running() || (lcd_commands_type == LcdCommands::Layer1Cal));
  7542. mmu_extruder = tmp_extruder; //filament change is finished
  7543. if (load_to_nozzle)// for single material usage with mmu
  7544. {
  7545. mmu_load_to_nozzle();
  7546. }
  7547. }
  7548. }
  7549. else
  7550. {
  7551. if (tmp_extruder >= EXTRUDERS) {
  7552. SERIAL_ECHO_START;
  7553. SERIAL_ECHO('T');
  7554. SERIAL_PROTOCOLLN((int)tmp_extruder);
  7555. SERIAL_ECHOLNRPGM(_n("Invalid extruder"));////MSG_INVALID_EXTRUDER
  7556. }
  7557. else {
  7558. #if EXTRUDERS > 1
  7559. bool make_move = false;
  7560. #endif
  7561. if (code_seen('F')) {
  7562. #if EXTRUDERS > 1
  7563. make_move = true;
  7564. #endif
  7565. next_feedrate = code_value();
  7566. if (next_feedrate > 0.0) {
  7567. feedrate = next_feedrate;
  7568. }
  7569. }
  7570. #if EXTRUDERS > 1
  7571. if (tmp_extruder != active_extruder) {
  7572. // Save current position to return to after applying extruder offset
  7573. set_destination_to_current();
  7574. // Offset extruder (only by XY)
  7575. int i;
  7576. for (i = 0; i < 2; i++) {
  7577. current_position[i] = current_position[i] -
  7578. extruder_offset[i][active_extruder] +
  7579. extruder_offset[i][tmp_extruder];
  7580. }
  7581. // Set the new active extruder and position
  7582. active_extruder = tmp_extruder;
  7583. plan_set_position_curposXYZE();
  7584. // Move to the old position if 'F' was in the parameters
  7585. if (make_move) {
  7586. prepare_move();
  7587. }
  7588. }
  7589. #endif
  7590. SERIAL_ECHO_START;
  7591. SERIAL_ECHORPGM(_n("Active Extruder: "));////MSG_ACTIVE_EXTRUDER
  7592. SERIAL_PROTOCOLLN((int)active_extruder);
  7593. }
  7594. }
  7595. }
  7596. } // end if(code_seen('T')) (end of T codes)
  7597. /*!
  7598. #### End of T-Codes
  7599. */
  7600. /**
  7601. *---------------------------------------------------------------------------------
  7602. *# D codes
  7603. */
  7604. else if (code_seen('D')) // D codes (debug)
  7605. {
  7606. switch(code_value_short())
  7607. {
  7608. /*!
  7609. ### D-1 - Endless Loop <a href="https://reprap.org/wiki/G-code#D-1:_Endless_Loop">D-1: Endless Loop</a>
  7610. */
  7611. case -1:
  7612. dcode__1(); break;
  7613. #ifdef DEBUG_DCODES
  7614. /*!
  7615. ### D0 - Reset <a href="https://reprap.org/wiki/G-code#D0:_Reset">D0: Reset</a>
  7616. #### Usage
  7617. D0 [ B ]
  7618. #### Parameters
  7619. - `B` - Bootloader
  7620. */
  7621. case 0:
  7622. dcode_0(); break;
  7623. /*!
  7624. *
  7625. ### D1 - Clear EEPROM and RESET <a href="https://reprap.org/wiki/G-code#D1:_Clear_EEPROM_and_RESET">D1: Clear EEPROM and RESET</a>
  7626. D1
  7627. *
  7628. */
  7629. case 1:
  7630. dcode_1(); break;
  7631. #endif
  7632. #if defined DEBUG_DCODE2 || defined DEBUG_DCODES
  7633. /*!
  7634. ### D2 - Read/Write RAM <a href="https://reprap.org/wiki/G-code#D2:_Read.2FWrite_RAM">D3: Read/Write RAM</a>
  7635. This command can be used without any additional parameters. It will read the entire RAM.
  7636. #### Usage
  7637. D2 [ A | C | X ]
  7638. #### Parameters
  7639. - `A` - Address (x0000-x1fff)
  7640. - `C` - Count (1-8192)
  7641. - `X` - Data
  7642. #### Notes
  7643. - The hex address needs to be lowercase without the 0 before the x
  7644. - Count is decimal
  7645. - The hex data needs to be lowercase
  7646. */
  7647. case 2:
  7648. dcode_2(); break;
  7649. #endif //DEBUG_DCODES
  7650. #if defined DEBUG_DCODE3 || defined DEBUG_DCODES
  7651. /*!
  7652. ### D3 - Read/Write EEPROM <a href="https://reprap.org/wiki/G-code#D3:_Read.2FWrite_EEPROM">D3: Read/Write EEPROM</a>
  7653. This command can be used without any additional parameters. It will read the entire eeprom.
  7654. #### Usage
  7655. D3 [ A | C | X ]
  7656. #### Parameters
  7657. - `A` - Address (x0000-x0fff)
  7658. - `C` - Count (1-4096)
  7659. - `X` - Data (hex)
  7660. #### Notes
  7661. - The hex address needs to be lowercase without the 0 before the x
  7662. - Count is decimal
  7663. - The hex data needs to be lowercase
  7664. */
  7665. case 3:
  7666. dcode_3(); break;
  7667. #endif //DEBUG_DCODE3
  7668. #ifdef DEBUG_DCODES
  7669. /*!
  7670. ### D4 - Read/Write PIN <a href="https://reprap.org/wiki/G-code#D4:_Read.2FWrite_PIN">D4: Read/Write PIN</a>
  7671. To read the digital value of a pin you need only to define the pin number.
  7672. #### Usage
  7673. D4 [ P | F | V ]
  7674. #### Parameters
  7675. - `P` - Pin (0-255)
  7676. - `F` - Function in/out (0/1)
  7677. - `V` - Value (0/1)
  7678. */
  7679. case 4:
  7680. dcode_4(); break;
  7681. #endif //DEBUG_DCODES
  7682. #if defined DEBUG_DCODE5 || defined DEBUG_DCODES
  7683. /*!
  7684. ### D5 - Read/Write FLASH <a href="https://reprap.org/wiki/G-code#D5:_Read.2FWrite_FLASH">D5: Read/Write Flash</a>
  7685. This command can be used without any additional parameters. It will read the 1kb FLASH.
  7686. #### Usage
  7687. D5 [ A | C | X | E ]
  7688. #### Parameters
  7689. - `A` - Address (x00000-x3ffff)
  7690. - `C` - Count (1-8192)
  7691. - `X` - Data (hex)
  7692. - `E` - Erase
  7693. #### Notes
  7694. - The hex address needs to be lowercase without the 0 before the x
  7695. - Count is decimal
  7696. - The hex data needs to be lowercase
  7697. */
  7698. case 5:
  7699. dcode_5(); break;
  7700. #endif //DEBUG_DCODE5
  7701. #if defined DEBUG_DCODE6 || defined DEBUG_DCODES
  7702. /*!
  7703. ### D6 - Read/Write external FLASH <a href="https://reprap.org/wiki/G-code#D6:_Read.2FWrite_external_FLASH">D6: Read/Write external Flash</a>
  7704. Reserved
  7705. */
  7706. case 6:
  7707. dcode_6(); break;
  7708. #endif
  7709. #ifdef DEBUG_DCODES
  7710. /*!
  7711. ### D7 - Read/Write Bootloader <a href="https://reprap.org/wiki/G-code#D7:_Read.2FWrite_Bootloader">D7: Read/Write Bootloader</a>
  7712. Reserved
  7713. */
  7714. case 7:
  7715. dcode_7(); break;
  7716. /*!
  7717. ### D8 - Read/Write PINDA <a href="https://reprap.org/wiki/G-code#D8:_Read.2FWrite_PINDA">D8: Read/Write PINDA</a>
  7718. #### Usage
  7719. D8 [ ? | ! | P | Z ]
  7720. #### Parameters
  7721. - `?` - Read PINDA temperature shift values
  7722. - `!` - Reset PINDA temperature shift values to default
  7723. - `P` - Pinda temperature [C]
  7724. - `Z` - Z Offset [mm]
  7725. */
  7726. case 8:
  7727. dcode_8(); break;
  7728. /*!
  7729. ### D9 - Read ADC <a href="https://reprap.org/wiki/G-code#D9:_Read.2FWrite_ADC">D9: Read ADC</a>
  7730. #### Usage
  7731. D9 [ I | V ]
  7732. #### Parameters
  7733. - `I` - ADC channel index
  7734. - `0` - Heater 0 temperature
  7735. - `1` - Heater 1 temperature
  7736. - `2` - Bed temperature
  7737. - `3` - PINDA temperature
  7738. - `4` - PWR voltage
  7739. - `5` - Ambient temperature
  7740. - `6` - BED voltage
  7741. - `V` Value to be written as simulated
  7742. */
  7743. case 9:
  7744. dcode_9(); break;
  7745. /*!
  7746. ### 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>
  7747. */
  7748. case 10:
  7749. dcode_10(); break;
  7750. /*!
  7751. ### D12 - Time <a href="https://reprap.org/wiki/G-code#D12:_Time">D12: Time</a>
  7752. Writes the current time in the log file.
  7753. */
  7754. #endif //DEBUG_DCODES
  7755. #ifdef XFLASH_DUMP
  7756. /*!
  7757. ### 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>
  7758. Generate a crash dump for later retrival.
  7759. #### Usage
  7760. D20 [E]
  7761. ### Parameters
  7762. - `E` - Perform an emergency crash dump (resets the printer).
  7763. ### Notes
  7764. - A crash dump can be later recovered with D21, or cleared with D22.
  7765. - An emergency crash dump includes register data, but will cause the printer to reset after the dump
  7766. is completed.
  7767. */
  7768. case 20: {
  7769. dcode_20();
  7770. break;
  7771. };
  7772. /*!
  7773. ### 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>
  7774. Output the complete crash dump (if present) to the serial.
  7775. #### Usage
  7776. D21
  7777. ### Notes
  7778. - The starting address can vary between builds, but it's always at the beginning of the data section.
  7779. */
  7780. case 21: {
  7781. dcode_21();
  7782. break;
  7783. };
  7784. /*!
  7785. ### D22 - Clear crash dump state <a href="https://reprap.org/wiki/G-code#D22:_Clear_crash_dump_state">D22: Clear crash dump state</a>
  7786. Clear an existing internal crash dump.
  7787. #### Usage
  7788. D22
  7789. */
  7790. case 22: {
  7791. dcode_22();
  7792. break;
  7793. };
  7794. #endif //XFLASH_DUMP
  7795. #ifdef EMERGENCY_SERIAL_DUMP
  7796. /*!
  7797. ### 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>
  7798. On boards without offline dump support, request online dumps to the serial port on firmware faults.
  7799. When online dumps are enabled, the FW will dump memory on the serial before resetting.
  7800. #### Usage
  7801. D23 [E] [R]
  7802. #### Parameters
  7803. - `E` - Perform an emergency crash dump (resets the printer).
  7804. - `R` - Disable online dumps.
  7805. */
  7806. case 23: {
  7807. dcode_23();
  7808. break;
  7809. };
  7810. #endif
  7811. #ifdef TEMP_MODEL_DEBUG
  7812. /*!
  7813. ## D70 - Enable low-level temperature model logging for offline simulation
  7814. #### Usage
  7815. D70 [ S ]
  7816. #### Parameters
  7817. - `S` - Enable 0-1 (default 0)
  7818. */
  7819. case 70: {
  7820. if(code_seen('S'))
  7821. temp_model_log_enable(code_value_short());
  7822. break;
  7823. }
  7824. #endif
  7825. #ifdef HEATBED_ANALYSIS
  7826. /*!
  7827. ### D80 - Bed check <a href="https://reprap.org/wiki/G-code#D80:_Bed_check">D80: Bed check</a>
  7828. This command will log data to SD card file "mesh.txt".
  7829. #### Usage
  7830. D80 [ E | F | G | H | I | J ]
  7831. #### Parameters
  7832. - `E` - Dimension X (default 40)
  7833. - `F` - Dimention Y (default 40)
  7834. - `G` - Points X (default 40)
  7835. - `H` - Points Y (default 40)
  7836. - `I` - Offset X (default 74)
  7837. - `J` - Offset Y (default 34)
  7838. */
  7839. case 80:
  7840. dcode_80(); break;
  7841. /*!
  7842. ### D81 - Bed analysis <a href="https://reprap.org/wiki/G-code#D81:_Bed_analysis">D80: Bed analysis</a>
  7843. This command will log data to SD card file "wldsd.txt".
  7844. #### Usage
  7845. D81 [ E | F | G | H | I | J ]
  7846. #### Parameters
  7847. - `E` - Dimension X (default 40)
  7848. - `F` - Dimention Y (default 40)
  7849. - `G` - Points X (default 40)
  7850. - `H` - Points Y (default 40)
  7851. - `I` - Offset X (default 74)
  7852. - `J` - Offset Y (default 34)
  7853. */
  7854. case 81:
  7855. dcode_81(); break;
  7856. #endif //HEATBED_ANALYSIS
  7857. #ifdef DEBUG_DCODES
  7858. /*!
  7859. ### 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>
  7860. */
  7861. case 106:
  7862. dcode_106(); break;
  7863. #ifdef TMC2130
  7864. /*!
  7865. ### D2130 - Trinamic stepper controller <a href="https://reprap.org/wiki/G-code#D2130:_Trinamic_stepper_controller">D2130: Trinamic stepper controller</a>
  7866. @todo Please review by owner of the code. RepRap Wiki Gcode needs to be updated after review of owner as well.
  7867. #### Usage
  7868. D2130 [ Axis | Command | Subcommand | Value ]
  7869. #### Parameters
  7870. - Axis
  7871. - `X` - X stepper driver
  7872. - `Y` - Y stepper driver
  7873. - `Z` - Z stepper driver
  7874. - `E` - Extruder stepper driver
  7875. - Commands
  7876. - `0` - Current off
  7877. - `1` - Current on
  7878. - `+` - Single step
  7879. - `-` - Single step oposite direction
  7880. - `NNN` - Value sereval steps
  7881. - `?` - Read register
  7882. - Subcommands for read register
  7883. - `mres` - Micro step resolution. More information in datasheet '5.5.2 CHOPCONF – Chopper Configuration'
  7884. - `step` - Step
  7885. - `mscnt` - Microstep counter. More information in datasheet '5.5 Motor Driver Registers'
  7886. - `mscuract` - Actual microstep current for motor. More information in datasheet '5.5 Motor Driver Registers'
  7887. - `wave` - Microstep linearity compensation curve
  7888. - `!` - Set register
  7889. - Subcommands for set register
  7890. - `mres` - Micro step resolution
  7891. - `step` - Step
  7892. - `wave` - Microstep linearity compensation curve
  7893. - Values for set register
  7894. - `0, 180 --> 250` - Off
  7895. - `0.9 --> 1.25` - Valid values (recommended is 1.1)
  7896. - `@` - Home calibrate axis
  7897. Examples:
  7898. D2130E?wave
  7899. Print extruder microstep linearity compensation curve
  7900. D2130E!wave0
  7901. Disable extruder linearity compensation curve, (sine curve is used)
  7902. D2130E!wave220
  7903. (sin(x))^1.1 extruder microstep compensation curve used
  7904. Notes:
  7905. For more information see https://www.trinamic.com/fileadmin/assets/Products/ICs_Documents/TMC2130_datasheet.pdf
  7906. *
  7907. */
  7908. case 2130:
  7909. dcode_2130(); break;
  7910. #endif //TMC2130
  7911. #if (defined (FILAMENT_SENSOR) && defined(PAT9125))
  7912. /*!
  7913. ### D9125 - PAT9125 filament sensor <a href="https://reprap.org/wiki/G-code#D9:_Read.2FWrite_ADC">D9125: PAT9125 filament sensor</a>
  7914. #### Usage
  7915. D9125 [ ? | ! | R | X | Y | L ]
  7916. #### Parameters
  7917. - `?` - Print values
  7918. - `!` - Print values
  7919. - `R` - Resolution. Not active in code
  7920. - `X` - X values
  7921. - `Y` - Y values
  7922. - `L` - Activate filament sensor log
  7923. */
  7924. case 9125:
  7925. dcode_9125(); break;
  7926. #endif //FILAMENT_SENSOR
  7927. #endif //DEBUG_DCODES
  7928. default:
  7929. printf_P(MSG_UNKNOWN_CODE, 'D', cmdbuffer + bufindr + CMDHDRSIZE);
  7930. }
  7931. }
  7932. else
  7933. {
  7934. SERIAL_ECHO_START;
  7935. SERIAL_ECHORPGM(MSG_UNKNOWN_COMMAND);
  7936. SERIAL_ECHO(CMDBUFFER_CURRENT_STRING);
  7937. SERIAL_ECHOLNPGM("\"(2)");
  7938. }
  7939. KEEPALIVE_STATE(NOT_BUSY);
  7940. ClearToSend();
  7941. }
  7942. /*!
  7943. #### End of D-Codes
  7944. */
  7945. /** @defgroup GCodes G-Code List
  7946. */
  7947. // ---------------------------------------------------
  7948. void FlushSerialRequestResend()
  7949. {
  7950. //char cmdbuffer[bufindr][100]="Resend:";
  7951. MYSERIAL.flush();
  7952. printf_P(_N("%S: %ld\n%S\n"), _n("Resend"), gcode_LastN + 1, MSG_OK);
  7953. }
  7954. // Confirm the execution of a command, if sent from a serial line.
  7955. // Execution of a command from a SD card will not be confirmed.
  7956. void ClearToSend()
  7957. {
  7958. previous_millis_cmd.start();
  7959. if (buflen && ((CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB) || (CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR)))
  7960. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  7961. }
  7962. #if MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  7963. void update_currents() {
  7964. float current_high[3] = DEFAULT_PWM_MOTOR_CURRENT_LOUD;
  7965. float current_low[3] = DEFAULT_PWM_MOTOR_CURRENT;
  7966. float tmp_motor[3];
  7967. //SERIAL_ECHOLNPGM("Currents updated: ");
  7968. if (destination[Z_AXIS] < Z_SILENT) {
  7969. //SERIAL_ECHOLNPGM("LOW");
  7970. for (uint8_t i = 0; i < 3; i++) {
  7971. st_current_set(i, current_low[i]);
  7972. /*MYSERIAL.print(int(i));
  7973. SERIAL_ECHOPGM(": ");
  7974. MYSERIAL.println(current_low[i]);*/
  7975. }
  7976. }
  7977. else if (destination[Z_AXIS] > Z_HIGH_POWER) {
  7978. //SERIAL_ECHOLNPGM("HIGH");
  7979. for (uint8_t i = 0; i < 3; i++) {
  7980. st_current_set(i, current_high[i]);
  7981. /*MYSERIAL.print(int(i));
  7982. SERIAL_ECHOPGM(": ");
  7983. MYSERIAL.println(current_high[i]);*/
  7984. }
  7985. }
  7986. else {
  7987. for (uint8_t i = 0; i < 3; i++) {
  7988. float q = current_low[i] - Z_SILENT*((current_high[i] - current_low[i]) / (Z_HIGH_POWER - Z_SILENT));
  7989. tmp_motor[i] = ((current_high[i] - current_low[i]) / (Z_HIGH_POWER - Z_SILENT))*destination[Z_AXIS] + q;
  7990. st_current_set(i, tmp_motor[i]);
  7991. /*MYSERIAL.print(int(i));
  7992. SERIAL_ECHOPGM(": ");
  7993. MYSERIAL.println(tmp_motor[i]);*/
  7994. }
  7995. }
  7996. }
  7997. #endif //MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  7998. void get_coordinates() {
  7999. bool seen[4]={false,false,false,false};
  8000. for(int8_t i=0; i < NUM_AXIS; i++) {
  8001. if(code_seen(axis_codes[i]))
  8002. {
  8003. bool relative = axis_relative_modes & (1 << i);
  8004. destination[i] = code_value();
  8005. if (i == E_AXIS) {
  8006. float emult = extruder_multiplier[active_extruder];
  8007. if (emult != 1.) {
  8008. if (! relative) {
  8009. destination[i] -= current_position[i];
  8010. relative = true;
  8011. }
  8012. destination[i] *= emult;
  8013. }
  8014. }
  8015. if (relative)
  8016. destination[i] += current_position[i];
  8017. seen[i]=true;
  8018. #if MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  8019. if (i == Z_AXIS && SilentModeMenu == SILENT_MODE_AUTO) update_currents();
  8020. #endif //MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  8021. }
  8022. else destination[i] = current_position[i]; //Are these else lines really needed?
  8023. }
  8024. if(code_seen('F')) {
  8025. next_feedrate = code_value();
  8026. if(next_feedrate > 0.0) feedrate = next_feedrate;
  8027. if (!seen[0] && !seen[1] && !seen[2] && seen[3])
  8028. {
  8029. // float e_max_speed =
  8030. // printf_P(PSTR("E MOVE speed %7.3f\n"), feedrate / 60)
  8031. }
  8032. }
  8033. }
  8034. void clamp_to_software_endstops(float target[3])
  8035. {
  8036. #ifdef DEBUG_DISABLE_SWLIMITS
  8037. return;
  8038. #endif //DEBUG_DISABLE_SWLIMITS
  8039. world2machine_clamp(target[0], target[1]);
  8040. // Clamp the Z coordinate.
  8041. if (min_software_endstops) {
  8042. float negative_z_offset = 0;
  8043. #ifdef ENABLE_AUTO_BED_LEVELING
  8044. if (Z_PROBE_OFFSET_FROM_EXTRUDER < 0) negative_z_offset = negative_z_offset + Z_PROBE_OFFSET_FROM_EXTRUDER;
  8045. if (cs.add_homing[Z_AXIS] < 0) negative_z_offset = negative_z_offset + cs.add_homing[Z_AXIS];
  8046. #endif
  8047. if (target[Z_AXIS] < min_pos[Z_AXIS]+negative_z_offset) target[Z_AXIS] = min_pos[Z_AXIS]+negative_z_offset;
  8048. }
  8049. if (max_software_endstops) {
  8050. if (target[Z_AXIS] > max_pos[Z_AXIS]) target[Z_AXIS] = max_pos[Z_AXIS];
  8051. }
  8052. }
  8053. uint16_t restore_interrupted_gcode() {
  8054. // When recovering from a previous print move, restore the originally
  8055. // calculated start position on the first USB/SD command. This accounts
  8056. // properly for relative moves
  8057. if (
  8058. (saved_start_position[0] != SAVED_START_POSITION_UNSET) && (
  8059. (CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_SDCARD) ||
  8060. (CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR)
  8061. )
  8062. ) {
  8063. memcpy(current_position, saved_start_position, sizeof(current_position));
  8064. saved_start_position[0] = SAVED_START_POSITION_UNSET;
  8065. return saved_segment_idx;
  8066. }
  8067. else
  8068. return 1; //begin with the first segment
  8069. }
  8070. #ifdef MESH_BED_LEVELING
  8071. 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) {
  8072. float dx = x - current_position[X_AXIS];
  8073. float dy = y - current_position[Y_AXIS];
  8074. uint16_t n_segments = 0;
  8075. if (mbl.active) {
  8076. float len = fabs(dx) + fabs(dy);
  8077. if (len > 0)
  8078. // Split to 3cm segments or shorter.
  8079. n_segments = uint16_t(ceil(len / 30.f));
  8080. }
  8081. if (n_segments > 1 && start_segment_idx) {
  8082. float dz = z - current_position[Z_AXIS];
  8083. float de = e - current_position[E_AXIS];
  8084. for (uint16_t i = start_segment_idx; i < n_segments; ++ i) {
  8085. float t = float(i) / float(n_segments);
  8086. plan_buffer_line(current_position[X_AXIS] + t * dx,
  8087. current_position[Y_AXIS] + t * dy,
  8088. current_position[Z_AXIS] + t * dz,
  8089. current_position[E_AXIS] + t * de,
  8090. feed_rate, extruder, current_position, i);
  8091. if (planner_aborted)
  8092. return;
  8093. }
  8094. }
  8095. // The rest of the path.
  8096. plan_buffer_line(x, y, z, e, feed_rate, extruder, current_position);
  8097. }
  8098. #endif // MESH_BED_LEVELING
  8099. void prepare_move(uint16_t start_segment_idx)
  8100. {
  8101. clamp_to_software_endstops(destination);
  8102. previous_millis_cmd.start();
  8103. // Do not use feedmultiply for E or Z only moves
  8104. if((current_position[X_AXIS] == destination[X_AXIS]) && (current_position[Y_AXIS] == destination[Y_AXIS])) {
  8105. plan_buffer_line_destinationXYZE(feedrate/60);
  8106. }
  8107. else {
  8108. #ifdef MESH_BED_LEVELING
  8109. 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);
  8110. #else
  8111. plan_buffer_line_destinationXYZE(feedrate*feedmultiply*(1./(60.f*100.f)));
  8112. #endif
  8113. }
  8114. set_current_to_destination();
  8115. }
  8116. void prepare_arc_move(bool isclockwise, uint16_t start_segment_idx) {
  8117. float r = hypot(offset[X_AXIS], offset[Y_AXIS]); // Compute arc radius for mc_arc
  8118. // Trace the arc
  8119. mc_arc(current_position, destination, offset, feedrate * feedmultiply / 60 / 100.0, r, isclockwise, active_extruder, start_segment_idx);
  8120. // As far as the parser is concerned, the position is now == target. In reality the
  8121. // motion control system might still be processing the action and the real tool position
  8122. // in any intermediate location.
  8123. set_current_to_destination();
  8124. previous_millis_cmd.start();
  8125. }
  8126. #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1
  8127. #if defined(FAN_PIN)
  8128. #if CONTROLLERFAN_PIN == FAN_PIN
  8129. #error "You cannot set CONTROLLERFAN_PIN equal to FAN_PIN"
  8130. #endif
  8131. #endif
  8132. unsigned long lastMotor = 0; //Save the time for when a motor was turned on last
  8133. unsigned long lastMotorCheck = 0;
  8134. void controllerFan()
  8135. {
  8136. if ((_millis() - lastMotorCheck) >= 2500) //Not a time critical function, so we only check every 2500ms
  8137. {
  8138. lastMotorCheck = _millis();
  8139. if(!READ(X_ENABLE_PIN) || !READ(Y_ENABLE_PIN) || !READ(Z_ENABLE_PIN) || (soft_pwm_bed > 0)
  8140. #if EXTRUDERS > 2
  8141. || !READ(E2_ENABLE_PIN)
  8142. #endif
  8143. #if EXTRUDER > 1
  8144. #if defined(X2_ENABLE_PIN) && X2_ENABLE_PIN > -1
  8145. || !READ(X2_ENABLE_PIN)
  8146. #endif
  8147. || !READ(E1_ENABLE_PIN)
  8148. #endif
  8149. || !READ(E0_ENABLE_PIN)) //If any of the drivers are enabled...
  8150. {
  8151. lastMotor = _millis(); //... set time to NOW so the fan will turn on
  8152. }
  8153. if ((_millis() - lastMotor) >= (CONTROLLERFAN_SECS*1000UL) || lastMotor == 0) //If the last time any driver was enabled, is longer since than CONTROLLERSEC...
  8154. {
  8155. digitalWrite(CONTROLLERFAN_PIN, 0);
  8156. analogWrite(CONTROLLERFAN_PIN, 0);
  8157. }
  8158. else
  8159. {
  8160. // allows digital or PWM fan output to be used (see M42 handling)
  8161. digitalWrite(CONTROLLERFAN_PIN, CONTROLLERFAN_SPEED);
  8162. analogWrite(CONTROLLERFAN_PIN, CONTROLLERFAN_SPEED);
  8163. }
  8164. }
  8165. }
  8166. #endif
  8167. #ifdef SAFETYTIMER
  8168. /**
  8169. * @brief Turn off heating after safetytimer_inactive_time milliseconds of inactivity
  8170. *
  8171. * Full screen blocking notification message is shown after heater turning off.
  8172. * Paused print is not considered inactivity, as nozzle is cooled anyway and bed cooling would
  8173. * damage print.
  8174. *
  8175. * If safetytimer_inactive_time is zero, feature is disabled (heating is never turned off because of inactivity)
  8176. */
  8177. static void handleSafetyTimer()
  8178. {
  8179. #if (EXTRUDERS > 1)
  8180. #error Implemented only for one extruder.
  8181. #endif //(EXTRUDERS > 1)
  8182. if (printer_active() || (!degTargetBed() && !degTargetHotend(0)) || (!safetytimer_inactive_time))
  8183. {
  8184. safetyTimer.stop();
  8185. }
  8186. else if ((degTargetBed() || degTargetHotend(0)) && (!safetyTimer.running()))
  8187. {
  8188. safetyTimer.start();
  8189. }
  8190. else if (safetyTimer.expired(farm_mode?FARM_DEFAULT_SAFETYTIMER_TIME_ms:safetytimer_inactive_time))
  8191. {
  8192. setTargetBed(0);
  8193. setAllTargetHotends(0);
  8194. lcd_show_fullscreen_message_and_wait_P(_i("Heating disabled by safety timer."));////MSG_BED_HEATING_SAFETY_DISABLED c=20 r=4
  8195. }
  8196. }
  8197. #endif //SAFETYTIMER
  8198. void manage_inactivity(bool ignore_stepper_queue/*=false*/) //default argument set in Marlin.h
  8199. {
  8200. #ifdef FILAMENT_SENSOR
  8201. if (fsensor.update()) {
  8202. lcd_draw_update = 1; //cause lcd update so that fsensor event polling can be done from the lcd draw routine.
  8203. }
  8204. #endif
  8205. #ifdef SAFETYTIMER
  8206. handleSafetyTimer();
  8207. #endif //SAFETYTIMER
  8208. #if defined(KILL_PIN) && KILL_PIN > -1
  8209. static int killCount = 0; // make the inactivity button a bit less responsive
  8210. const int KILL_DELAY = 10000;
  8211. #endif
  8212. if(buflen < (BUFSIZE-1)){
  8213. get_command();
  8214. }
  8215. if(previous_millis_cmd.expired(max_inactive_time))
  8216. if(max_inactive_time)
  8217. kill(_n("Inactivity Shutdown"), 4);
  8218. if(stepper_inactive_time) {
  8219. if(previous_millis_cmd.expired(stepper_inactive_time))
  8220. {
  8221. if(blocks_queued() == false && ignore_stepper_queue == false) {
  8222. disable_x();
  8223. disable_y();
  8224. disable_z();
  8225. disable_e0();
  8226. disable_e1();
  8227. disable_e2();
  8228. }
  8229. }
  8230. }
  8231. #ifdef CHDK //Check if pin should be set to LOW after M240 set it to HIGH
  8232. if (chdkActive && (_millis() - chdkHigh > CHDK_DELAY))
  8233. {
  8234. chdkActive = false;
  8235. WRITE(CHDK, LOW);
  8236. }
  8237. #endif
  8238. #if defined(KILL_PIN) && KILL_PIN > -1
  8239. // Check if the kill button was pressed and wait just in case it was an accidental
  8240. // key kill key press
  8241. // -------------------------------------------------------------------------------
  8242. if( 0 == READ(KILL_PIN) )
  8243. {
  8244. killCount++;
  8245. }
  8246. else if (killCount > 0)
  8247. {
  8248. killCount--;
  8249. }
  8250. // Exceeded threshold and we can confirm that it was not accidental
  8251. // KILL the machine
  8252. // ----------------------------------------------------------------
  8253. if ( killCount >= KILL_DELAY)
  8254. {
  8255. kill(NULL, 5);
  8256. }
  8257. #endif
  8258. #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1
  8259. controllerFan(); //Check if fan should be turned on to cool stepper drivers down
  8260. #endif
  8261. #ifdef EXTRUDER_RUNOUT_PREVENT
  8262. if(previous_millis_cmd.expired(EXTRUDER_RUNOUT_SECONDS*1000))
  8263. if(degHotend(active_extruder)>EXTRUDER_RUNOUT_MINTEMP)
  8264. {
  8265. bool oldstatus=READ(E0_ENABLE_PIN);
  8266. enable_e0();
  8267. float oldepos=current_position[E_AXIS];
  8268. float oldedes=destination[E_AXIS];
  8269. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS],
  8270. destination[E_AXIS]+EXTRUDER_RUNOUT_EXTRUDE*EXTRUDER_RUNOUT_ESTEPS/cs.axis_steps_per_unit[E_AXIS],
  8271. EXTRUDER_RUNOUT_SPEED/60.*EXTRUDER_RUNOUT_ESTEPS/cs.axis_steps_per_unit[E_AXIS], active_extruder);
  8272. current_position[E_AXIS]=oldepos;
  8273. destination[E_AXIS]=oldedes;
  8274. plan_set_e_position(oldepos);
  8275. previous_millis_cmd.start();
  8276. st_synchronize();
  8277. WRITE(E0_ENABLE_PIN,oldstatus);
  8278. }
  8279. #endif
  8280. check_axes_activity();
  8281. mmu_loop();
  8282. // handle longpress
  8283. if(lcd_longpress_trigger)
  8284. {
  8285. // long press is not possible in modal mode, wait until ready
  8286. if (lcd_longpress_func && lcd_update_enabled)
  8287. {
  8288. lcd_longpress_func();
  8289. lcd_longpress_trigger = 0;
  8290. }
  8291. }
  8292. #if defined(AUTO_REPORT)
  8293. host_autoreport();
  8294. #endif //AUTO_REPORT
  8295. host_keepalive();
  8296. }
  8297. void kill(const char *full_screen_message, unsigned char id)
  8298. {
  8299. printf_P(_N("KILL: %d\n"), id);
  8300. //return;
  8301. cli(); // Stop interrupts
  8302. disable_heater();
  8303. disable_x();
  8304. // SERIAL_ECHOLNPGM("kill - disable Y");
  8305. disable_y();
  8306. poweroff_z();
  8307. disable_e0();
  8308. disable_e1();
  8309. disable_e2();
  8310. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  8311. pinMode(PS_ON_PIN,INPUT);
  8312. #endif
  8313. SERIAL_ERROR_START;
  8314. SERIAL_ERRORLNRPGM(_n("Printer halted. kill() called!"));////MSG_ERR_KILLED
  8315. if (full_screen_message != NULL) {
  8316. SERIAL_ERRORLNRPGM(full_screen_message);
  8317. lcd_display_message_fullscreen_P(full_screen_message);
  8318. } else {
  8319. LCD_ALERTMESSAGERPGM(_n("KILLED. "));////MSG_KILLED
  8320. }
  8321. // FMC small patch to update the LCD before ending
  8322. sei(); // enable interrupts
  8323. for ( int i=5; i--; lcd_update(0))
  8324. {
  8325. _delay(200);
  8326. }
  8327. cli(); // disable interrupts
  8328. suicide();
  8329. while(1)
  8330. {
  8331. #ifdef WATCHDOG
  8332. wdt_reset();
  8333. #endif //WATCHDOG
  8334. /* Intentionally left empty */
  8335. } // Wait for reset
  8336. }
  8337. void UnconditionalStop()
  8338. {
  8339. CRITICAL_SECTION_START;
  8340. // Disable all heaters and unroll the temperature wait loop stack
  8341. disable_heater();
  8342. cancel_heatup = true;
  8343. heating_status = HeatingStatus::NO_HEATING;
  8344. // Clear any saved printing state
  8345. cancel_saved_printing();
  8346. // Abort the planner
  8347. planner_abort_hard();
  8348. // Reset the queue
  8349. cmdqueue_reset();
  8350. cmdqueue_serial_disabled = false;
  8351. // Reset the sd status
  8352. card.sdprinting = false;
  8353. card.closefile();
  8354. st_reset_timer();
  8355. CRITICAL_SECTION_END;
  8356. }
  8357. // Emergency stop used by overtemp functions which allows recovery
  8358. // WARNING: This function is called *continuously* during a thermal failure.
  8359. //
  8360. // This either pauses (for thermal model errors) or stops *without recovery* depending on
  8361. // "allow_pause". If pause is allowed, this forces a printer-initiated instantanenous pause (just
  8362. // like an LCD pause) that bypasses the host pausing functionality. In this state the printer is
  8363. // kept in busy state and *must* be recovered from the LCD.
  8364. void ThermalStop(bool allow_pause)
  8365. {
  8366. if(Stopped == false) {
  8367. Stopped = true;
  8368. if(allow_pause && (IS_SD_PRINTING || usb_timer.running())) {
  8369. if (!isPrintPaused) {
  8370. lcd_setalertstatuspgm(_T(MSG_PAUSED_THERMAL_ERROR), LCD_STATUS_CRITICAL);
  8371. // we cannot make a distinction for the host here, the pause must be instantaneous
  8372. // so we call the lcd_pause_print to save the print state internally. Thermal errors
  8373. // disable heaters and save the original temperatures to saved_*, which will get
  8374. // overwritten by stop_and_save_print_to_ram. For this corner-case, re-instate the
  8375. // original values after the pause handler is called.
  8376. float bed_temp = saved_bed_temperature;
  8377. float ext_temp = saved_extruder_temperature;
  8378. int fan_speed = saved_fan_speed;
  8379. lcd_pause_print();
  8380. saved_bed_temperature = bed_temp;
  8381. saved_extruder_temperature = ext_temp;
  8382. saved_fan_speed = fan_speed;
  8383. }
  8384. } else {
  8385. // We got a hard thermal error and/or there is no print going on. Just stop.
  8386. lcd_print_stop();
  8387. // Also prevent further menu entry
  8388. menu_set_block(MENU_BLOCK_THERMAL_ERROR);
  8389. }
  8390. // Report the status on the serial, switch to a busy state
  8391. SERIAL_ERROR_START;
  8392. SERIAL_ERRORLNRPGM(MSG_ERR_STOPPED);
  8393. // Eventually report the stopped status on the lcd (though this is usually overridden by a
  8394. // higher-priority alert status message)
  8395. LCD_MESSAGERPGM(_T(MSG_STOPPED));
  8396. // Make a warning sound! We cannot use Sound_MakeCustom as this would stop further moves.
  8397. // Turn on the speaker here (if not already), and turn it off when back in the main loop.
  8398. WRITE(BEEPER, HIGH);
  8399. }
  8400. // Return to the status screen to stop any pending menu action which could have been
  8401. // started by the user while stuck in the Stopped state. This also ensures the NEW
  8402. // error is immediately shown.
  8403. if (menu_menu != lcd_status_screen)
  8404. lcd_return_to_status();
  8405. }
  8406. bool IsStopped() { return Stopped; };
  8407. void finishAndDisableSteppers()
  8408. {
  8409. st_synchronize();
  8410. disable_x();
  8411. disable_y();
  8412. disable_z();
  8413. disable_e0();
  8414. disable_e1();
  8415. disable_e2();
  8416. #ifndef LA_NOCOMPAT
  8417. // Steppers are disabled both when a print is stopped and also via M84 (which is additionally
  8418. // checked-for to indicate a complete file), so abuse this function to reset the LA detection
  8419. // state for the next print.
  8420. la10c_reset();
  8421. #endif
  8422. //in the end of print set estimated time to end of print and extruders used during print to default values for next print
  8423. print_time_remaining_init();
  8424. }
  8425. #ifdef FAST_PWM_FAN
  8426. void setPwmFrequency(uint8_t pin, int val)
  8427. {
  8428. val &= 0x07;
  8429. switch(digitalPinToTimer(pin))
  8430. {
  8431. #if defined(TCCR0A)
  8432. case TIMER0A:
  8433. case TIMER0B:
  8434. // TCCR0B &= ~(_BV(CS00) | _BV(CS01) | _BV(CS02));
  8435. // TCCR0B |= val;
  8436. break;
  8437. #endif
  8438. #if defined(TCCR1A)
  8439. case TIMER1A:
  8440. case TIMER1B:
  8441. // TCCR1B &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  8442. // TCCR1B |= val;
  8443. break;
  8444. #endif
  8445. #if defined(TCCR2)
  8446. case TIMER2:
  8447. case TIMER2:
  8448. TCCR2 &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  8449. TCCR2 |= val;
  8450. break;
  8451. #endif
  8452. #if defined(TCCR2A)
  8453. case TIMER2A:
  8454. case TIMER2B:
  8455. TCCR2B &= ~(_BV(CS20) | _BV(CS21) | _BV(CS22));
  8456. TCCR2B |= val;
  8457. break;
  8458. #endif
  8459. #if defined(TCCR3A)
  8460. case TIMER3A:
  8461. case TIMER3B:
  8462. case TIMER3C:
  8463. TCCR3B &= ~(_BV(CS30) | _BV(CS31) | _BV(CS32));
  8464. TCCR3B |= val;
  8465. break;
  8466. #endif
  8467. #if defined(TCCR4A)
  8468. case TIMER4A:
  8469. case TIMER4B:
  8470. case TIMER4C:
  8471. TCCR4B &= ~(_BV(CS40) | _BV(CS41) | _BV(CS42));
  8472. TCCR4B |= val;
  8473. break;
  8474. #endif
  8475. #if defined(TCCR5A)
  8476. case TIMER5A:
  8477. case TIMER5B:
  8478. case TIMER5C:
  8479. TCCR5B &= ~(_BV(CS50) | _BV(CS51) | _BV(CS52));
  8480. TCCR5B |= val;
  8481. break;
  8482. #endif
  8483. }
  8484. }
  8485. #endif //FAST_PWM_FAN
  8486. //! @brief Get and validate extruder number
  8487. //!
  8488. //! If it is not specified, active_extruder is returned in parameter extruder.
  8489. //! @param [in] code M code number
  8490. //! @param [out] extruder
  8491. //! @return error
  8492. //! @retval true Invalid extruder specified in T code
  8493. //! @retval false Valid extruder specified in T code, or not specifiead
  8494. bool setTargetedHotend(int code, uint8_t &extruder)
  8495. {
  8496. extruder = active_extruder;
  8497. if(code_seen('T')) {
  8498. extruder = code_value_uint8();
  8499. if(extruder >= EXTRUDERS) {
  8500. SERIAL_ECHO_START;
  8501. switch(code){
  8502. case 104:
  8503. SERIAL_ECHORPGM(_n("M104 Invalid extruder "));////MSG_M104_INVALID_EXTRUDER
  8504. break;
  8505. case 105:
  8506. SERIAL_ECHORPGM(_n("M105 Invalid extruder "));////MSG_M105_INVALID_EXTRUDER
  8507. break;
  8508. case 109:
  8509. SERIAL_ECHORPGM(_n("M109 Invalid extruder "));////MSG_M109_INVALID_EXTRUDER
  8510. break;
  8511. case 218:
  8512. SERIAL_ECHORPGM(_n("M218 Invalid extruder "));////MSG_M218_INVALID_EXTRUDER
  8513. break;
  8514. case 221:
  8515. SERIAL_ECHORPGM(_n("M221 Invalid extruder "));////MSG_M221_INVALID_EXTRUDER
  8516. break;
  8517. }
  8518. SERIAL_PROTOCOLLN((int)extruder);
  8519. return true;
  8520. }
  8521. }
  8522. return false;
  8523. }
  8524. void save_statistics(unsigned long _total_filament_used, unsigned long _total_print_time) //_total_filament_used unit: mm/100; print time in s
  8525. {
  8526. 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)
  8527. {
  8528. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, 0);
  8529. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, 0);
  8530. }
  8531. unsigned long _previous_filament = eeprom_read_dword((uint32_t *)EEPROM_FILAMENTUSED); //_previous_filament unit: cm
  8532. unsigned long _previous_time = eeprom_read_dword((uint32_t *)EEPROM_TOTALTIME); //_previous_time unit: min
  8533. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, _previous_time + (_total_print_time/60)); //EEPROM_TOTALTIME unit: min
  8534. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, _previous_filament + (_total_filament_used / 1000));
  8535. total_filament_used = 0;
  8536. }
  8537. float calculate_extruder_multiplier(float diameter) {
  8538. float out = 1.f;
  8539. if (cs.volumetric_enabled && diameter > 0.f) {
  8540. float area = M_PI * diameter * diameter * 0.25;
  8541. out = 1.f / area;
  8542. }
  8543. if (extrudemultiply != 100)
  8544. out *= float(extrudemultiply) * 0.01f;
  8545. return out;
  8546. }
  8547. void calculate_extruder_multipliers() {
  8548. extruder_multiplier[0] = calculate_extruder_multiplier(cs.filament_size[0]);
  8549. #if EXTRUDERS > 1
  8550. extruder_multiplier[1] = calculate_extruder_multiplier(cs.filament_size[1]);
  8551. #if EXTRUDERS > 2
  8552. extruder_multiplier[2] = calculate_extruder_multiplier(cs.filament_size[2]);
  8553. #endif
  8554. #endif
  8555. }
  8556. void delay_keep_alive(unsigned int ms)
  8557. {
  8558. for (;;) {
  8559. manage_heater();
  8560. // Manage inactivity, but don't disable steppers on timeout.
  8561. manage_inactivity(true);
  8562. lcd_update(0);
  8563. if (ms == 0)
  8564. break;
  8565. else if (ms >= 50) {
  8566. _delay(50);
  8567. ms -= 50;
  8568. } else {
  8569. _delay(ms);
  8570. ms = 0;
  8571. }
  8572. }
  8573. }
  8574. static void wait_for_heater(long codenum, uint8_t extruder) {
  8575. if (!degTargetHotend(extruder))
  8576. return;
  8577. #ifdef TEMP_RESIDENCY_TIME
  8578. long residencyStart;
  8579. residencyStart = -1;
  8580. /* continue to loop until we have reached the target temp
  8581. _and_ until TEMP_RESIDENCY_TIME hasn't passed since we reached it */
  8582. cancel_heatup = false;
  8583. while ((!cancel_heatup) && ((residencyStart == -1) ||
  8584. (residencyStart >= 0 && (((unsigned int)(_millis() - residencyStart)) < (TEMP_RESIDENCY_TIME * 1000UL))))) {
  8585. #else
  8586. while (target_direction ? (isHeatingHotend(tmp_extruder)) : (isCoolingHotend(tmp_extruder) && (CooldownNoWait == false))) {
  8587. #endif //TEMP_RESIDENCY_TIME
  8588. if ((_millis() - codenum) > 1000UL)
  8589. { //Print Temp Reading and remaining time every 1 second while heating up/cooling down
  8590. if (!farm_mode) {
  8591. SERIAL_PROTOCOLPGM("T:");
  8592. SERIAL_PROTOCOL_F(degHotend(extruder), 1);
  8593. SERIAL_PROTOCOLPGM(" E:");
  8594. SERIAL_PROTOCOL((int)extruder);
  8595. #ifdef TEMP_RESIDENCY_TIME
  8596. SERIAL_PROTOCOLPGM(" W:");
  8597. if (residencyStart > -1)
  8598. {
  8599. codenum = ((TEMP_RESIDENCY_TIME * 1000UL) - (_millis() - residencyStart)) / 1000UL;
  8600. SERIAL_PROTOCOLLN(codenum);
  8601. }
  8602. else
  8603. {
  8604. SERIAL_PROTOCOLLN('?');
  8605. }
  8606. }
  8607. #else
  8608. SERIAL_PROTOCOLLN();
  8609. #endif
  8610. codenum = _millis();
  8611. }
  8612. manage_heater();
  8613. manage_inactivity(true); //do not disable steppers
  8614. lcd_update(0);
  8615. #ifdef TEMP_RESIDENCY_TIME
  8616. /* start/restart the TEMP_RESIDENCY_TIME timer whenever we reach target temp for the first time
  8617. or when current temp falls outside the hysteresis after target temp was reached */
  8618. if ((residencyStart == -1 && target_direction && (degHotend(extruder) >= (degTargetHotend(extruder) - TEMP_WINDOW))) ||
  8619. (residencyStart == -1 && !target_direction && (degHotend(extruder) <= (degTargetHotend(extruder) + TEMP_WINDOW))) ||
  8620. (residencyStart > -1 && labs(degHotend(extruder) - degTargetHotend(extruder)) > TEMP_HYSTERESIS))
  8621. {
  8622. residencyStart = _millis();
  8623. }
  8624. #endif //TEMP_RESIDENCY_TIME
  8625. }
  8626. }
  8627. void check_babystep()
  8628. {
  8629. int babystep_z = eeprom_read_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->
  8630. s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)));
  8631. if ((babystep_z < Z_BABYSTEP_MIN) || (babystep_z > Z_BABYSTEP_MAX)) {
  8632. babystep_z = 0; //if babystep value is out of min max range, set it to 0
  8633. SERIAL_ECHOLNPGM("Z live adjust out of range. Setting to 0");
  8634. eeprom_write_word(reinterpret_cast<uint16_t *>(&(EEPROM_Sheets_base->
  8635. s[(eeprom_read_byte(&(EEPROM_Sheets_base->active_sheet)))].z_offset)),
  8636. babystep_z);
  8637. lcd_show_fullscreen_message_and_wait_P(PSTR("Z live adjust out of range. Setting to 0. Click to continue."));
  8638. lcd_update_enable(true);
  8639. }
  8640. }
  8641. #ifdef HEATBED_ANALYSIS
  8642. void d_setup()
  8643. {
  8644. pinMode(D_DATACLOCK, INPUT_PULLUP);
  8645. pinMode(D_DATA, INPUT_PULLUP);
  8646. pinMode(D_REQUIRE, OUTPUT);
  8647. digitalWrite(D_REQUIRE, HIGH);
  8648. }
  8649. float d_ReadData()
  8650. {
  8651. int digit[13];
  8652. String mergeOutput;
  8653. float output;
  8654. digitalWrite(D_REQUIRE, HIGH);
  8655. for (int i = 0; i<13; i++)
  8656. {
  8657. for (int j = 0; j < 4; j++)
  8658. {
  8659. while (digitalRead(D_DATACLOCK) == LOW) {}
  8660. while (digitalRead(D_DATACLOCK) == HIGH) {}
  8661. bitWrite(digit[i], j, digitalRead(D_DATA));
  8662. }
  8663. }
  8664. digitalWrite(D_REQUIRE, LOW);
  8665. mergeOutput = "";
  8666. output = 0;
  8667. for (int r = 5; r <= 10; r++) //Merge digits
  8668. {
  8669. mergeOutput += digit[r];
  8670. }
  8671. output = mergeOutput.toFloat();
  8672. if (digit[4] == 8) //Handle sign
  8673. {
  8674. output *= -1;
  8675. }
  8676. for (int i = digit[11]; i > 0; i--) //Handle floating point
  8677. {
  8678. output /= 10;
  8679. }
  8680. return output;
  8681. }
  8682. void bed_check(float x_dimension, float y_dimension, int x_points_num, int y_points_num, float shift_x, float shift_y) {
  8683. int t1 = 0;
  8684. int t_delay = 0;
  8685. int digit[13];
  8686. int m;
  8687. char str[3];
  8688. //String mergeOutput;
  8689. char mergeOutput[15];
  8690. float output;
  8691. int mesh_point = 0; //index number of calibration point
  8692. 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
  8693. float bed_zero_ref_y = (-0.6f + Y_PROBE_OFFSET_FROM_EXTRUDER);
  8694. float mesh_home_z_search = 4;
  8695. float measure_z_height = 0.2f;
  8696. float row[x_points_num];
  8697. int ix = 0;
  8698. int iy = 0;
  8699. const char* filename_wldsd = "mesh.txt";
  8700. char data_wldsd[x_points_num * 7 + 1]; //6 chars(" -A.BCD")for each measurement + null
  8701. char numb_wldsd[8]; // (" -A.BCD" + null)
  8702. #ifdef MICROMETER_LOGGING
  8703. d_setup();
  8704. #endif //MICROMETER_LOGGING
  8705. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  8706. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  8707. unsigned int custom_message_type_old = custom_message_type;
  8708. unsigned int custom_message_state_old = custom_message_state;
  8709. custom_message_type = CustomMsg::MeshBedLeveling;
  8710. custom_message_state = (x_points_num * y_points_num) + 10;
  8711. lcd_update(1);
  8712. //mbl.reset();
  8713. babystep_undo();
  8714. card.openFile(filename_wldsd, false);
  8715. /*destination[Z_AXIS] = mesh_home_z_search;
  8716. //plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  8717. plan_buffer_line_destinationXYZE(Z_LIFT_FEEDRATE);
  8718. for(int8_t i=0; i < NUM_AXIS; i++) {
  8719. current_position[i] = destination[i];
  8720. }
  8721. st_synchronize();
  8722. */
  8723. destination[Z_AXIS] = measure_z_height;
  8724. plan_buffer_line_destinationXYZE(Z_LIFT_FEEDRATE);
  8725. for(int8_t i=0; i < NUM_AXIS; i++) {
  8726. current_position[i] = destination[i];
  8727. }
  8728. st_synchronize();
  8729. /*int l_feedmultiply = */setup_for_endstop_move(false);
  8730. SERIAL_PROTOCOLPGM("Num X,Y: ");
  8731. SERIAL_PROTOCOL(x_points_num);
  8732. SERIAL_PROTOCOLPGM(",");
  8733. SERIAL_PROTOCOL(y_points_num);
  8734. SERIAL_PROTOCOLPGM("\nZ search height: ");
  8735. SERIAL_PROTOCOL(mesh_home_z_search);
  8736. SERIAL_PROTOCOLPGM("\nDimension X,Y: ");
  8737. SERIAL_PROTOCOL(x_dimension);
  8738. SERIAL_PROTOCOLPGM(",");
  8739. SERIAL_PROTOCOL(y_dimension);
  8740. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  8741. while (mesh_point != x_points_num * y_points_num) {
  8742. ix = mesh_point % x_points_num; // from 0 to MESH_NUM_X_POINTS - 1
  8743. iy = mesh_point / x_points_num;
  8744. if (iy & 1) ix = (x_points_num - 1) - ix; // Zig zag
  8745. float z0 = 0.f;
  8746. /*destination[Z_AXIS] = mesh_home_z_search;
  8747. //plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE);
  8748. plan_buffer_line_destinationXYZE(Z_LIFT_FEEDRATE);
  8749. for(int8_t i=0; i < NUM_AXIS; i++) {
  8750. current_position[i] = destination[i];
  8751. }
  8752. st_synchronize();*/
  8753. //current_position[X_AXIS] = 13.f + ix * (x_dimension / (x_points_num - 1)) - bed_zero_ref_x + shift_x;
  8754. //current_position[Y_AXIS] = 6.4f + iy * (y_dimension / (y_points_num - 1)) - bed_zero_ref_y + shift_y;
  8755. destination[X_AXIS] = ix * (x_dimension / (x_points_num - 1)) + shift_x;
  8756. destination[Y_AXIS] = iy * (y_dimension / (y_points_num - 1)) + shift_y;
  8757. mesh_plan_buffer_line_destinationXYZE(XY_AXIS_FEEDRATE/6);
  8758. set_current_to_destination();
  8759. st_synchronize();
  8760. // printf_P(PSTR("X = %f; Y= %f \n"), current_position[X_AXIS], current_position[Y_AXIS]);
  8761. delay_keep_alive(1000);
  8762. #ifdef MICROMETER_LOGGING
  8763. //memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8764. //dtostrf(d_ReadData(), 8, 5, numb_wldsd);
  8765. //strcat(data_wldsd, numb_wldsd);
  8766. //MYSERIAL.println(data_wldsd);
  8767. //delay(1000);
  8768. //delay(3000);
  8769. //t1 = millis();
  8770. //while (digitalRead(D_DATACLOCK) == LOW) {}
  8771. //while (digitalRead(D_DATACLOCK) == HIGH) {}
  8772. memset(digit, 0, sizeof(digit));
  8773. //cli();
  8774. digitalWrite(D_REQUIRE, LOW);
  8775. for (int i = 0; i<13; i++)
  8776. {
  8777. //t1 = millis();
  8778. for (int j = 0; j < 4; j++)
  8779. {
  8780. while (digitalRead(D_DATACLOCK) == LOW) {}
  8781. while (digitalRead(D_DATACLOCK) == HIGH) {}
  8782. //printf_P(PSTR("Done %d\n"), j);
  8783. bitWrite(digit[i], j, digitalRead(D_DATA));
  8784. }
  8785. //t_delay = (millis() - t1);
  8786. //SERIAL_PROTOCOLPGM(" ");
  8787. //SERIAL_PROTOCOL_F(t_delay, 5);
  8788. //SERIAL_PROTOCOLPGM(" ");
  8789. }
  8790. //sei();
  8791. digitalWrite(D_REQUIRE, HIGH);
  8792. mergeOutput[0] = '\0';
  8793. output = 0;
  8794. for (int r = 5; r <= 10; r++) //Merge digits
  8795. {
  8796. sprintf(str, "%d", digit[r]);
  8797. strcat(mergeOutput, str);
  8798. }
  8799. output = atof(mergeOutput);
  8800. if (digit[4] == 8) //Handle sign
  8801. {
  8802. output *= -1;
  8803. }
  8804. for (int i = digit[11]; i > 0; i--) //Handle floating point
  8805. {
  8806. output *= 0.1;
  8807. }
  8808. //output = d_ReadData();
  8809. //row[ix] = current_position[Z_AXIS];
  8810. //row[ix] = d_ReadData();
  8811. row[ix] = output;
  8812. if (iy % 2 == 1 ? ix == 0 : ix == x_points_num - 1) {
  8813. memset(data_wldsd, 0, sizeof(data_wldsd));
  8814. for (int i = 0; i < x_points_num; i++) {
  8815. SERIAL_PROTOCOLPGM(" ");
  8816. SERIAL_PROTOCOL_F(row[i], 5);
  8817. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8818. dtostrf(row[i], 7, 3, numb_wldsd);
  8819. strcat(data_wldsd, numb_wldsd);
  8820. }
  8821. card.write_command(data_wldsd);
  8822. SERIAL_PROTOCOLPGM("\n");
  8823. }
  8824. custom_message_state--;
  8825. mesh_point++;
  8826. lcd_update(1);
  8827. }
  8828. #endif //MICROMETER_LOGGING
  8829. card.closefile();
  8830. //clean_up_after_endstop_move(l_feedmultiply);
  8831. }
  8832. void bed_analysis(float x_dimension, float y_dimension, int x_points_num, int y_points_num, float shift_x, float shift_y) {
  8833. int t1 = 0;
  8834. int t_delay = 0;
  8835. int digit[13];
  8836. int m;
  8837. char str[3];
  8838. //String mergeOutput;
  8839. char mergeOutput[15];
  8840. float output;
  8841. int mesh_point = 0; //index number of calibration point
  8842. 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
  8843. float bed_zero_ref_y = (-0.6f + Y_PROBE_OFFSET_FROM_EXTRUDER);
  8844. float mesh_home_z_search = 4;
  8845. float row[x_points_num];
  8846. int ix = 0;
  8847. int iy = 0;
  8848. const char* filename_wldsd = "wldsd.txt";
  8849. char data_wldsd[70];
  8850. char numb_wldsd[10];
  8851. d_setup();
  8852. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  8853. // We don't know where we are! HOME!
  8854. // Push the commands to the front of the message queue in the reverse order!
  8855. // There shall be always enough space reserved for these commands.
  8856. repeatcommand_front(); // repeat G80 with all its parameters
  8857. enquecommand_front_P(G28W0);
  8858. enquecommand_front_P((PSTR("G1 Z5")));
  8859. return;
  8860. }
  8861. unsigned int custom_message_type_old = custom_message_type;
  8862. unsigned int custom_message_state_old = custom_message_state;
  8863. custom_message_type = CustomMsg::MeshBedLeveling;
  8864. custom_message_state = (x_points_num * y_points_num) + 10;
  8865. lcd_update(1);
  8866. mbl.reset();
  8867. babystep_undo();
  8868. card.openFile(filename_wldsd, false);
  8869. current_position[Z_AXIS] = mesh_home_z_search;
  8870. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS] / 60, active_extruder);
  8871. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  8872. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  8873. int l_feedmultiply = setup_for_endstop_move(false);
  8874. SERIAL_PROTOCOLPGM("Num X,Y: ");
  8875. SERIAL_PROTOCOL(x_points_num);
  8876. SERIAL_PROTOCOLPGM(",");
  8877. SERIAL_PROTOCOL(y_points_num);
  8878. SERIAL_PROTOCOLPGM("\nZ search height: ");
  8879. SERIAL_PROTOCOL(mesh_home_z_search);
  8880. SERIAL_PROTOCOLPGM("\nDimension X,Y: ");
  8881. SERIAL_PROTOCOL(x_dimension);
  8882. SERIAL_PROTOCOLPGM(",");
  8883. SERIAL_PROTOCOL(y_dimension);
  8884. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  8885. while (mesh_point != x_points_num * y_points_num) {
  8886. ix = mesh_point % x_points_num; // from 0 to MESH_NUM_X_POINTS - 1
  8887. iy = mesh_point / x_points_num;
  8888. if (iy & 1) ix = (x_points_num - 1) - ix; // Zig zag
  8889. float z0 = 0.f;
  8890. current_position[Z_AXIS] = mesh_home_z_search;
  8891. plan_buffer_line_curposXYZE(Z_LIFT_FEEDRATE, active_extruder);
  8892. st_synchronize();
  8893. current_position[X_AXIS] = 13.f + ix * (x_dimension / (x_points_num - 1)) - bed_zero_ref_x + shift_x;
  8894. current_position[Y_AXIS] = 6.4f + iy * (y_dimension / (y_points_num - 1)) - bed_zero_ref_y + shift_y;
  8895. plan_buffer_line_curposXYZE(XY_AXIS_FEEDRATE, active_extruder);
  8896. st_synchronize();
  8897. 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
  8898. break;
  8899. card.closefile();
  8900. }
  8901. //memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8902. //dtostrf(d_ReadData(), 8, 5, numb_wldsd);
  8903. //strcat(data_wldsd, numb_wldsd);
  8904. //MYSERIAL.println(data_wldsd);
  8905. //_delay(1000);
  8906. //_delay(3000);
  8907. //t1 = _millis();
  8908. //while (digitalRead(D_DATACLOCK) == LOW) {}
  8909. //while (digitalRead(D_DATACLOCK) == HIGH) {}
  8910. memset(digit, 0, sizeof(digit));
  8911. //cli();
  8912. digitalWrite(D_REQUIRE, LOW);
  8913. for (int i = 0; i<13; i++)
  8914. {
  8915. //t1 = _millis();
  8916. for (int j = 0; j < 4; j++)
  8917. {
  8918. while (digitalRead(D_DATACLOCK) == LOW) {}
  8919. while (digitalRead(D_DATACLOCK) == HIGH) {}
  8920. bitWrite(digit[i], j, digitalRead(D_DATA));
  8921. }
  8922. //t_delay = (_millis() - t1);
  8923. //SERIAL_PROTOCOLPGM(" ");
  8924. //SERIAL_PROTOCOL_F(t_delay, 5);
  8925. //SERIAL_PROTOCOLPGM(" ");
  8926. }
  8927. //sei();
  8928. digitalWrite(D_REQUIRE, HIGH);
  8929. mergeOutput[0] = '\0';
  8930. output = 0;
  8931. for (int r = 5; r <= 10; r++) //Merge digits
  8932. {
  8933. sprintf(str, "%d", digit[r]);
  8934. strcat(mergeOutput, str);
  8935. }
  8936. output = atof(mergeOutput);
  8937. if (digit[4] == 8) //Handle sign
  8938. {
  8939. output *= -1;
  8940. }
  8941. for (int i = digit[11]; i > 0; i--) //Handle floating point
  8942. {
  8943. output *= 0.1;
  8944. }
  8945. //output = d_ReadData();
  8946. //row[ix] = current_position[Z_AXIS];
  8947. memset(data_wldsd, 0, sizeof(data_wldsd));
  8948. for (int i = 0; i <3; i++) {
  8949. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8950. dtostrf(current_position[i], 8, 5, numb_wldsd);
  8951. strcat(data_wldsd, numb_wldsd);
  8952. strcat(data_wldsd, ";");
  8953. }
  8954. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  8955. dtostrf(output, 8, 5, numb_wldsd);
  8956. strcat(data_wldsd, numb_wldsd);
  8957. //strcat(data_wldsd, ";");
  8958. card.write_command(data_wldsd);
  8959. //row[ix] = d_ReadData();
  8960. row[ix] = output; // current_position[Z_AXIS];
  8961. if (iy % 2 == 1 ? ix == 0 : ix == x_points_num - 1) {
  8962. for (int i = 0; i < x_points_num; i++) {
  8963. SERIAL_PROTOCOLPGM(" ");
  8964. SERIAL_PROTOCOL_F(row[i], 5);
  8965. }
  8966. SERIAL_PROTOCOLPGM("\n");
  8967. }
  8968. custom_message_state--;
  8969. mesh_point++;
  8970. lcd_update(1);
  8971. }
  8972. card.closefile();
  8973. clean_up_after_endstop_move(l_feedmultiply);
  8974. }
  8975. #endif //HEATBED_ANALYSIS
  8976. #ifndef PINDA_THERMISTOR
  8977. static void temp_compensation_start() {
  8978. custom_message_type = CustomMsg::TempCompPreheat;
  8979. custom_message_state = PINDA_HEAT_T + 1;
  8980. lcd_update(2);
  8981. if ((int)degHotend(active_extruder) > extrude_min_temp) {
  8982. current_position[E_AXIS] -= default_retraction;
  8983. }
  8984. plan_buffer_line_curposXYZE(400, active_extruder);
  8985. current_position[X_AXIS] = PINDA_PREHEAT_X;
  8986. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  8987. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  8988. plan_buffer_line_curposXYZE(3000 / 60, active_extruder);
  8989. st_synchronize();
  8990. while (fabs(degBed() - target_temperature_bed) > 1) delay_keep_alive(1000);
  8991. for (int i = 0; i < PINDA_HEAT_T; i++) {
  8992. delay_keep_alive(1000);
  8993. custom_message_state = PINDA_HEAT_T - i;
  8994. if (custom_message_state == 99 || custom_message_state == 9) lcd_update(2); //force whole display redraw if number of digits changed
  8995. else lcd_update(1);
  8996. }
  8997. custom_message_type = CustomMsg::Status;
  8998. custom_message_state = 0;
  8999. }
  9000. static void temp_compensation_apply() {
  9001. int i_add;
  9002. int z_shift = 0;
  9003. float z_shift_mm;
  9004. if (calibration_status() == CALIBRATION_STATUS_CALIBRATED) {
  9005. if (target_temperature_bed % 10 == 0 && target_temperature_bed >= 60 && target_temperature_bed <= 100) {
  9006. i_add = (target_temperature_bed - 60) / 10;
  9007. z_shift = eeprom_read_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + i_add);
  9008. z_shift_mm = z_shift / cs.axis_steps_per_unit[Z_AXIS];
  9009. }else {
  9010. //interpolation
  9011. z_shift_mm = temp_comp_interpolation(target_temperature_bed) / cs.axis_steps_per_unit[Z_AXIS];
  9012. }
  9013. printf_P(_N("\nZ shift applied:%.3f\n"), z_shift_mm);
  9014. 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);
  9015. st_synchronize();
  9016. plan_set_z_position(current_position[Z_AXIS]);
  9017. }
  9018. else {
  9019. //we have no temp compensation data
  9020. }
  9021. }
  9022. #endif //ndef PINDA_THERMISTOR
  9023. float temp_comp_interpolation(float inp_temperature) {
  9024. //cubic spline interpolation
  9025. int n, i, j;
  9026. float h[10], a, b, c, d, sum, s[10] = { 0 }, x[10], F[10], f[10], m[10][10] = { 0 }, temp;
  9027. int shift[10];
  9028. int temp_C[10];
  9029. n = 6; //number of measured points
  9030. shift[0] = 0;
  9031. for (i = 0; i < n; i++) {
  9032. if (i > 0) {
  9033. //read shift in steps from EEPROM
  9034. shift[i] = eeprom_read_word((uint16_t*)EEPROM_PROBE_TEMP_SHIFT + (i - 1));
  9035. }
  9036. temp_C[i] = 50 + i * 10; //temperature in C
  9037. #ifdef PINDA_THERMISTOR
  9038. constexpr int start_compensating_temp = 35;
  9039. temp_C[i] = start_compensating_temp + i * 5; //temperature in degrees C
  9040. #ifdef SUPERPINDA_SUPPORT
  9041. static_assert(start_compensating_temp >= PINDA_MINTEMP, "Temperature compensation start point is lower than PINDA_MINTEMP.");
  9042. #endif //SUPERPINDA_SUPPORT
  9043. #else
  9044. temp_C[i] = 50 + i * 10; //temperature in C
  9045. #endif
  9046. x[i] = (float)temp_C[i];
  9047. f[i] = (float)shift[i];
  9048. }
  9049. if (inp_temperature < x[0]) return 0;
  9050. for (i = n - 1; i>0; i--) {
  9051. F[i] = (f[i] - f[i - 1]) / (x[i] - x[i - 1]);
  9052. h[i - 1] = x[i] - x[i - 1];
  9053. }
  9054. //*********** formation of h, s , f matrix **************
  9055. for (i = 1; i<n - 1; i++) {
  9056. m[i][i] = 2 * (h[i - 1] + h[i]);
  9057. if (i != 1) {
  9058. m[i][i - 1] = h[i - 1];
  9059. m[i - 1][i] = h[i - 1];
  9060. }
  9061. m[i][n - 1] = 6 * (F[i + 1] - F[i]);
  9062. }
  9063. //*********** forward elimination **************
  9064. for (i = 1; i<n - 2; i++) {
  9065. temp = (m[i + 1][i] / m[i][i]);
  9066. for (j = 1; j <= n - 1; j++)
  9067. m[i + 1][j] -= temp*m[i][j];
  9068. }
  9069. //*********** backward substitution *********
  9070. for (i = n - 2; i>0; i--) {
  9071. sum = 0;
  9072. for (j = i; j <= n - 2; j++)
  9073. sum += m[i][j] * s[j];
  9074. s[i] = (m[i][n - 1] - sum) / m[i][i];
  9075. }
  9076. for (i = 0; i<n - 1; i++)
  9077. if ((x[i] <= inp_temperature && inp_temperature <= x[i + 1]) || (i == n-2 && inp_temperature > x[i + 1])) {
  9078. a = (s[i + 1] - s[i]) / (6 * h[i]);
  9079. b = s[i] / 2;
  9080. c = (f[i + 1] - f[i]) / h[i] - (2 * h[i] * s[i] + s[i + 1] * h[i]) / 6;
  9081. d = f[i];
  9082. sum = a*pow((inp_temperature - x[i]), 3) + b*pow((inp_temperature - x[i]), 2) + c*(inp_temperature - x[i]) + d;
  9083. }
  9084. return sum;
  9085. }
  9086. #ifdef PINDA_THERMISTOR
  9087. float temp_compensation_pinda_thermistor_offset(float temperature_pinda)
  9088. {
  9089. if (!eeprom_read_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE)) return 0;
  9090. if (!calibration_status_pinda()) return 0;
  9091. return temp_comp_interpolation(temperature_pinda) / cs.axis_steps_per_unit[Z_AXIS];
  9092. }
  9093. #endif //PINDA_THERMISTOR
  9094. void long_pause() //long pause print
  9095. {
  9096. st_synchronize();
  9097. start_pause_print = _millis();
  9098. // Stop heaters
  9099. heating_status = HeatingStatus::NO_HEATING;
  9100. setAllTargetHotends(0);
  9101. // Lift z
  9102. raise_z_above(current_position[Z_AXIS] + Z_PAUSE_LIFT, true);
  9103. // Move XY to side
  9104. if (axis_known_position[X_AXIS] && axis_known_position[Y_AXIS]) {
  9105. current_position[X_AXIS] = X_PAUSE_POS;
  9106. current_position[Y_AXIS] = Y_PAUSE_POS;
  9107. plan_buffer_line_curposXYZE(50);
  9108. }
  9109. // did we come here from a thermal error?
  9110. if(get_temp_error()) {
  9111. // time to stop the error beep
  9112. WRITE(BEEPER, LOW);
  9113. } else {
  9114. // Turn off the print fan
  9115. fanSpeed = 0;
  9116. }
  9117. }
  9118. void serialecho_temperatures() {
  9119. float tt = degHotend(active_extruder);
  9120. SERIAL_PROTOCOLPGM("T:");
  9121. SERIAL_PROTOCOL(tt);
  9122. SERIAL_PROTOCOLPGM(" E:");
  9123. SERIAL_PROTOCOL((int)active_extruder);
  9124. SERIAL_PROTOCOLPGM(" B:");
  9125. SERIAL_PROTOCOL_F(degBed(), 1);
  9126. SERIAL_PROTOCOLLN();
  9127. }
  9128. #ifdef UVLO_SUPPORT
  9129. void uvlo_drain_reset()
  9130. {
  9131. // burn all that residual power
  9132. wdt_enable(WDTO_1S);
  9133. WRITE(BEEPER,HIGH);
  9134. lcd_clear();
  9135. lcd_puts_at_P(0, 1, MSG_POWERPANIC_DETECTED);
  9136. while(1);
  9137. }
  9138. void uvlo_()
  9139. {
  9140. unsigned long time_start = _millis();
  9141. bool sd_print = card.sdprinting;
  9142. // Conserve power as soon as possible.
  9143. #ifdef LCD_BL_PIN
  9144. backlightMode = BACKLIGHT_MODE_DIM;
  9145. backlightLevel_LOW = 0;
  9146. backlight_update();
  9147. #endif //LCD_BL_PIN
  9148. disable_x();
  9149. disable_y();
  9150. #ifdef TMC2130
  9151. tmc2130_set_current_h(Z_AXIS, 20);
  9152. tmc2130_set_current_r(Z_AXIS, 20);
  9153. tmc2130_set_current_h(E_AXIS, 20);
  9154. tmc2130_set_current_r(E_AXIS, 20);
  9155. #endif //TMC2130
  9156. // Stop all heaters
  9157. uint8_t saved_target_temperature_bed = target_temperature_bed;
  9158. uint16_t saved_target_temperature_ext = target_temperature[active_extruder];
  9159. setAllTargetHotends(0);
  9160. setTargetBed(0);
  9161. // Calculate the file position, from which to resume this print.
  9162. long sd_position = sdpos_atomic; //atomic sd position of last command added in queue
  9163. {
  9164. uint16_t sdlen_planner = planner_calc_sd_length(); //length of sd commands in planner
  9165. sd_position -= sdlen_planner;
  9166. uint16_t sdlen_cmdqueue = cmdqueue_calc_sd_length(); //length of sd commands in cmdqueue
  9167. sd_position -= sdlen_cmdqueue;
  9168. if (sd_position < 0) sd_position = 0;
  9169. }
  9170. // save the global state at planning time
  9171. bool pos_invalid = XY_NO_RESTORE_FLAG;
  9172. uint16_t feedrate_bckp;
  9173. if (current_block && !pos_invalid)
  9174. {
  9175. memcpy(saved_start_position, current_block->gcode_start_position, sizeof(saved_start_position));
  9176. feedrate_bckp = current_block->gcode_feedrate;
  9177. saved_segment_idx = current_block->segment_idx;
  9178. }
  9179. else
  9180. {
  9181. saved_start_position[0] = SAVED_START_POSITION_UNSET;
  9182. feedrate_bckp = feedrate;
  9183. saved_segment_idx = 0;
  9184. }
  9185. // From this point on and up to the print recovery, Z should not move during X/Y travels and
  9186. // should be controlled precisely. Reset the MBL status before planner_abort_hard in order to
  9187. // get the physical Z for further manipulation.
  9188. bool mbl_was_active = mbl.active;
  9189. mbl.active = false;
  9190. // After this call, the planner queue is emptied and the current_position is set to a current logical coordinate.
  9191. // The logical coordinate will likely differ from the machine coordinate if the skew calibration and mesh bed leveling
  9192. // are in action.
  9193. planner_abort_hard();
  9194. // Store the print logical Z position, which we need to recover (a slight error here would be
  9195. // recovered on the next Gcode instruction, while a physical location error would not)
  9196. float logical_z = current_position[Z_AXIS];
  9197. if(mbl_was_active) logical_z -= mbl.get_z(st_get_position_mm(X_AXIS), st_get_position_mm(Y_AXIS));
  9198. eeprom_update_float((float*)EEPROM_UVLO_CURRENT_POSITION_Z, logical_z);
  9199. // Store the print E position before we lose track
  9200. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION_E), current_position[E_AXIS]);
  9201. eeprom_update_byte((uint8_t*)EEPROM_UVLO_E_ABS, (axis_relative_modes & E_AXIS_MASK)?0:1);
  9202. // Clean the input command queue, inhibit serial processing using saved_printing
  9203. cmdqueue_reset();
  9204. card.sdprinting = false;
  9205. saved_printing = true;
  9206. // Enable stepper driver interrupt to move Z axis. This should be fine as the planner and
  9207. // command queues are empty, SD card printing is disabled, usb is inhibited.
  9208. planner_aborted = false;
  9209. sei();
  9210. // Retract
  9211. current_position[E_AXIS] -= default_retraction;
  9212. plan_buffer_line_curposXYZE(95);
  9213. st_synchronize();
  9214. disable_e0();
  9215. // Read out the current Z motor microstep counter to move the axis up towards
  9216. // a full step before powering off. NOTE: we need to ensure to schedule more
  9217. // than "dropsegments" steps in order to move (this is always the case here
  9218. // due to UVLO_Z_AXIS_SHIFT being used)
  9219. uint16_t z_res = tmc2130_get_res(Z_AXIS);
  9220. uint16_t z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9221. current_position[Z_AXIS] += float(1024 - z_microsteps)
  9222. / (z_res * cs.axis_steps_per_unit[Z_AXIS])
  9223. + UVLO_Z_AXIS_SHIFT;
  9224. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS]/60);
  9225. st_synchronize();
  9226. poweroff_z();
  9227. // Write the file position.
  9228. eeprom_update_dword((uint32_t*)(EEPROM_FILE_POSITION), sd_position);
  9229. // Store the mesh bed leveling offsets. This is 2*7*7=98 bytes, which takes 98*3.4us=333us in worst case.
  9230. for (uint8_t mesh_point = 0; mesh_point < MESH_NUM_X_POINTS * MESH_NUM_Y_POINTS; ++ mesh_point) {
  9231. uint8_t ix = mesh_point % MESH_NUM_X_POINTS; // from 0 to MESH_NUM_X_POINTS - 1
  9232. uint8_t iy = mesh_point / MESH_NUM_X_POINTS;
  9233. // Scale the z value to 1u resolution.
  9234. int16_t v = mbl_was_active ? int16_t(floor(mbl.z_values[iy][ix] * 1000.f + 0.5f)) : 0;
  9235. eeprom_update_word((uint16_t*)(EEPROM_UVLO_MESH_BED_LEVELING_FULL +2*mesh_point), *reinterpret_cast<uint16_t*>(&v));
  9236. }
  9237. // Write the _final_ Z position and motor microstep counter (unused).
  9238. eeprom_update_float((float*)EEPROM_UVLO_TINY_CURRENT_POSITION_Z, current_position[Z_AXIS]);
  9239. z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9240. eeprom_update_word((uint16_t*)(EEPROM_UVLO_Z_MICROSTEPS), z_microsteps);
  9241. // Store the current position.
  9242. if (pos_invalid)
  9243. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0), X_COORD_INVALID);
  9244. else
  9245. {
  9246. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0), current_position[X_AXIS]);
  9247. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 4), current_position[Y_AXIS]);
  9248. }
  9249. // Store the current feed rate, temperatures, fan speed and extruder multipliers (flow rates)
  9250. eeprom_update_word((uint16_t*)EEPROM_UVLO_FEEDRATE, feedrate_bckp);
  9251. eeprom_update_word((uint16_t*)EEPROM_UVLO_FEEDMULTIPLY, feedmultiply);
  9252. eeprom_update_word((uint16_t*)EEPROM_UVLO_TARGET_HOTEND, saved_target_temperature_ext);
  9253. eeprom_update_byte((uint8_t*)EEPROM_UVLO_TARGET_BED, saved_target_temperature_bed);
  9254. eeprom_update_byte((uint8_t*)EEPROM_UVLO_FAN_SPEED, fanSpeed);
  9255. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_0), extruder_multiplier[0]);
  9256. #if EXTRUDERS > 1
  9257. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_1), extruder_multiplier[1]);
  9258. #if EXTRUDERS > 2
  9259. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_2), extruder_multiplier[2]);
  9260. #endif
  9261. #endif
  9262. eeprom_update_word((uint16_t*)(EEPROM_EXTRUDEMULTIPLY), (uint16_t)extrudemultiply);
  9263. eeprom_update_float((float*)(EEPROM_UVLO_ACCELL), cs.acceleration);
  9264. eeprom_update_float((float*)(EEPROM_UVLO_RETRACT_ACCELL), cs.retract_acceleration);
  9265. eeprom_update_float((float*)(EEPROM_UVLO_TRAVEL_ACCELL), cs.travel_acceleration);
  9266. // Store the saved target
  9267. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+0*4), saved_start_position[X_AXIS]);
  9268. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+1*4), saved_start_position[Y_AXIS]);
  9269. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+2*4), saved_start_position[Z_AXIS]);
  9270. eeprom_update_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+3*4), saved_start_position[E_AXIS]);
  9271. eeprom_update_word((uint16_t*)EEPROM_UVLO_SAVED_SEGMENT_IDX, saved_segment_idx);
  9272. #ifdef LIN_ADVANCE
  9273. eeprom_update_float((float*)(EEPROM_UVLO_LA_K), extruder_advance_K);
  9274. #endif
  9275. // Finaly store the "power outage" flag.
  9276. if(sd_print) eeprom_update_byte((uint8_t*)EEPROM_UVLO, 1);
  9277. // Increment power failure counter
  9278. eeprom_update_byte((uint8_t*)EEPROM_POWER_COUNT, eeprom_read_byte((uint8_t*)EEPROM_POWER_COUNT) + 1);
  9279. eeprom_update_word((uint16_t*)EEPROM_POWER_COUNT_TOT, eeprom_read_word((uint16_t*)EEPROM_POWER_COUNT_TOT) + 1);
  9280. printf_P(_N("UVLO - end %d\n"), _millis() - time_start);
  9281. WRITE(BEEPER,HIGH);
  9282. // All is set: with all the juice left, try to move extruder away to detach the nozzle completely from the print
  9283. poweron_z();
  9284. current_position[X_AXIS] = (current_position[X_AXIS] < 0.5f * (X_MIN_POS + X_MAX_POS)) ? X_MIN_POS : X_MAX_POS;
  9285. plan_buffer_line_curposXYZE(500);
  9286. st_synchronize();
  9287. wdt_enable(WDTO_1S);
  9288. while(1);
  9289. }
  9290. void uvlo_tiny()
  9291. {
  9292. unsigned long time_start = _millis();
  9293. // Conserve power as soon as possible.
  9294. disable_x();
  9295. disable_y();
  9296. disable_e0();
  9297. #ifdef TMC2130
  9298. tmc2130_set_current_h(Z_AXIS, 20);
  9299. tmc2130_set_current_r(Z_AXIS, 20);
  9300. #endif //TMC2130
  9301. // Stop all heaters
  9302. setAllTargetHotends(0);
  9303. setTargetBed(0);
  9304. // When power is interrupted on the _first_ recovery an attempt can be made to raise the
  9305. // extruder, causing the Z position to change. Similarly, when recovering, the Z position is
  9306. // lowered. In such cases we cannot just save Z, we need to re-align the steppers to a fullstep.
  9307. // Disable MBL (if not already) to work with physical coordinates.
  9308. mbl.active = false;
  9309. planner_abort_hard();
  9310. // Allow for small roundoffs to be ignored
  9311. 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])
  9312. {
  9313. // Clean the input command queue, inhibit serial processing using saved_printing
  9314. cmdqueue_reset();
  9315. card.sdprinting = false;
  9316. saved_printing = true;
  9317. // Enable stepper driver interrupt to move Z axis. This should be fine as the planner and
  9318. // command queues are empty, SD card printing is disabled, usb is inhibited.
  9319. planner_aborted = false;
  9320. sei();
  9321. // The axis was moved: adjust Z as done on a regular UVLO.
  9322. uint16_t z_res = tmc2130_get_res(Z_AXIS);
  9323. uint16_t z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9324. current_position[Z_AXIS] += float(1024 - z_microsteps)
  9325. / (z_res * cs.axis_steps_per_unit[Z_AXIS])
  9326. + UVLO_TINY_Z_AXIS_SHIFT;
  9327. plan_buffer_line_curposXYZE(homing_feedrate[Z_AXIS]/60);
  9328. st_synchronize();
  9329. poweroff_z();
  9330. // Update Z position
  9331. eeprom_update_float((float*)(EEPROM_UVLO_TINY_CURRENT_POSITION_Z), current_position[Z_AXIS]);
  9332. // Update the _final_ Z motor microstep counter (unused).
  9333. z_microsteps = tmc2130_rd_MSCNT(Z_AXIS);
  9334. eeprom_update_word((uint16_t*)(EEPROM_UVLO_Z_MICROSTEPS), z_microsteps);
  9335. }
  9336. // Update the the "power outage" flag.
  9337. eeprom_update_byte((uint8_t*)EEPROM_UVLO,2);
  9338. // Increment power failure counter
  9339. eeprom_update_byte((uint8_t*)EEPROM_POWER_COUNT, eeprom_read_byte((uint8_t*)EEPROM_POWER_COUNT) + 1);
  9340. eeprom_update_word((uint16_t*)EEPROM_POWER_COUNT_TOT, eeprom_read_word((uint16_t*)EEPROM_POWER_COUNT_TOT) + 1);
  9341. printf_P(_N("UVLO_TINY - end %d\n"), _millis() - time_start);
  9342. uvlo_drain_reset();
  9343. }
  9344. #endif //UVLO_SUPPORT
  9345. #if (defined(FANCHECK) && defined(TACH_1) && (TACH_1 >-1))
  9346. void setup_fan_interrupt() {
  9347. //INT7
  9348. DDRE &= ~(1 << 7); //input pin
  9349. PORTE &= ~(1 << 7); //no internal pull-up
  9350. //start with sensing rising edge
  9351. EICRB &= ~(1 << 6);
  9352. EICRB |= (1 << 7);
  9353. //enable INT7 interrupt
  9354. EIMSK |= (1 << 7);
  9355. }
  9356. // The fan interrupt is triggered at maximum 325Hz (may be a bit more due to component tollerances),
  9357. // and it takes 4.24 us to process (the interrupt invocation overhead not taken into account).
  9358. ISR(INT7_vect) {
  9359. //measuring speed now works for fanSpeed > 18 (approximately), which is sufficient because MIN_PRINT_FAN_SPEED is higher
  9360. #ifdef FAN_SOFT_PWM
  9361. if (!fan_measuring || (fanSpeedSoftPwm < MIN_PRINT_FAN_SPEED)) return;
  9362. #else //FAN_SOFT_PWM
  9363. if (fanSpeed < MIN_PRINT_FAN_SPEED) return;
  9364. #endif //FAN_SOFT_PWM
  9365. if ((1 << 6) & EICRB) { //interrupt was triggered by rising edge
  9366. t_fan_rising_edge = millis_nc();
  9367. }
  9368. else { //interrupt was triggered by falling edge
  9369. if ((millis_nc() - t_fan_rising_edge) >= FAN_PULSE_WIDTH_LIMIT) {//this pulse was from sensor and not from pwm
  9370. fan_edge_counter[1] += 2; //we are currently counting all edges so lets count two edges for one pulse
  9371. }
  9372. }
  9373. EICRB ^= (1 << 6); //change edge
  9374. }
  9375. #endif
  9376. #ifdef UVLO_SUPPORT
  9377. void setup_uvlo_interrupt() {
  9378. DDRE &= ~(1 << 4); //input pin
  9379. PORTE &= ~(1 << 4); //no internal pull-up
  9380. // sensing falling edge
  9381. EICRB |= (1 << 0);
  9382. EICRB &= ~(1 << 1);
  9383. // enable INT4 interrupt
  9384. EIMSK |= (1 << 4);
  9385. // check if power was lost before we armed the interrupt
  9386. if(!(PINE & (1 << 4)) && eeprom_read_byte((uint8_t*)EEPROM_UVLO))
  9387. {
  9388. SERIAL_ECHOLNPGM("INT4");
  9389. uvlo_drain_reset();
  9390. }
  9391. }
  9392. ISR(INT4_vect) {
  9393. EIMSK &= ~(1 << 4); //disable INT4 interrupt to make sure that this code will be executed just once
  9394. SERIAL_ECHOLNPGM("INT4");
  9395. //fire normal uvlo only in case where EEPROM_UVLO is 0 or if IS_SD_PRINTING is 1.
  9396. if(printer_active() && (!(eeprom_read_byte((uint8_t*)EEPROM_UVLO)))) uvlo_();
  9397. if(eeprom_read_byte((uint8_t*)EEPROM_UVLO)) uvlo_tiny();
  9398. }
  9399. void recover_print(uint8_t automatic) {
  9400. char cmd[30];
  9401. lcd_update_enable(true);
  9402. lcd_update(2);
  9403. lcd_setstatuspgm(_i("Recovering print"));////MSG_RECOVERING_PRINT c=20
  9404. // Recover position, temperatures and extrude_multipliers
  9405. bool mbl_was_active = recover_machine_state_after_power_panic();
  9406. // Lift the print head 25mm, first to avoid collisions with oozed material with the print,
  9407. // and second also so one may remove the excess priming material.
  9408. if(eeprom_read_byte((uint8_t*)EEPROM_UVLO) == 1)
  9409. {
  9410. sprintf_P(cmd, PSTR("G1 Z%.3f F800"), current_position[Z_AXIS] + 25);
  9411. enquecommand(cmd);
  9412. }
  9413. // Home X and Y axes. Homing just X and Y shall not touch the babystep and the world2machine
  9414. // transformation status. G28 will not touch Z when MBL is off.
  9415. enquecommand_P(PSTR("G28 X Y"));
  9416. // Set the target bed and nozzle temperatures and wait.
  9417. sprintf_P(cmd, PSTR("M104 S%d"), target_temperature[active_extruder]);
  9418. enquecommand(cmd);
  9419. sprintf_P(cmd, PSTR("M140 S%d"), target_temperature_bed);
  9420. enquecommand(cmd);
  9421. sprintf_P(cmd, PSTR("M109 S%d"), target_temperature[active_extruder]);
  9422. enquecommand(cmd);
  9423. enquecommand_P(PSTR("M83")); //E axis relative mode
  9424. // If not automatically recoreverd (long power loss)
  9425. if(automatic == 0){
  9426. //Extrude some filament to stabilize the pressure
  9427. enquecommand_P(PSTR("G1 E5 F120"));
  9428. // Retract to be consistent with a short pause
  9429. sprintf_P(cmd, PSTR("G1 E%-0.3f F2700"), default_retraction);
  9430. enquecommand(cmd);
  9431. }
  9432. 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]);
  9433. // Restart the print.
  9434. restore_print_from_eeprom(mbl_was_active);
  9435. printf_P(_N("Current pos Z_AXIS:%.3f\nCurrent pos E_AXIS:%.3f\n"), current_position[Z_AXIS], current_position[E_AXIS]);
  9436. }
  9437. bool recover_machine_state_after_power_panic()
  9438. {
  9439. // 1) Preset some dummy values for the XY axes
  9440. current_position[X_AXIS] = 0;
  9441. current_position[Y_AXIS] = 0;
  9442. // 2) Restore the mesh bed leveling offsets, but not the MBL status.
  9443. // This is 2*7*7=98 bytes, which takes 98*3.4us=333us in worst case.
  9444. bool mbl_was_active = false;
  9445. for (int8_t mesh_point = 0; mesh_point < MESH_NUM_X_POINTS * MESH_NUM_Y_POINTS; ++ mesh_point) {
  9446. uint8_t ix = mesh_point % MESH_NUM_X_POINTS; // from 0 to MESH_NUM_X_POINTS - 1
  9447. uint8_t iy = mesh_point / MESH_NUM_X_POINTS;
  9448. // Scale the z value to 10u resolution.
  9449. int16_t v;
  9450. eeprom_read_block(&v, (void*)(EEPROM_UVLO_MESH_BED_LEVELING_FULL+2*mesh_point), 2);
  9451. if (v != 0)
  9452. mbl_was_active = true;
  9453. mbl.z_values[iy][ix] = float(v) * 0.001f;
  9454. }
  9455. // Recover the physical coordinate of the Z axis at the time of the power panic.
  9456. // The current position after power panic is moved to the next closest 0th full step.
  9457. current_position[Z_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_TINY_CURRENT_POSITION_Z));
  9458. // Recover last E axis position
  9459. current_position[E_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_E));
  9460. // 3) Initialize the logical to physical coordinate system transformation.
  9461. world2machine_initialize();
  9462. // SERIAL_ECHOPGM("recover_machine_state_after_power_panic, initial ");
  9463. // print_mesh_bed_leveling_table();
  9464. // 4) Load the baby stepping value, which is expected to be active at the time of power panic.
  9465. // The baby stepping value is used to reset the physical Z axis when rehoming the Z axis.
  9466. babystep_load();
  9467. // 5) Set the physical positions from the logical positions using the world2machine transformation
  9468. // This is only done to inizialize Z/E axes with physical locations, since X/Y are unknown.
  9469. clamp_to_software_endstops(current_position);
  9470. set_destination_to_current();
  9471. plan_set_position_curposXYZE();
  9472. SERIAL_ECHOPGM("recover_machine_state_after_power_panic, initial ");
  9473. print_world_coordinates();
  9474. // 6) Power up the Z motors, mark their positions as known.
  9475. axis_known_position[Z_AXIS] = true;
  9476. enable_z();
  9477. // 7) Recover the target temperatures.
  9478. target_temperature[active_extruder] = eeprom_read_word((uint16_t*)EEPROM_UVLO_TARGET_HOTEND);
  9479. target_temperature_bed = eeprom_read_byte((uint8_t*)EEPROM_UVLO_TARGET_BED);
  9480. // 8) Recover extruder multipilers
  9481. extruder_multiplier[0] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_0));
  9482. #if EXTRUDERS > 1
  9483. extruder_multiplier[1] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_1));
  9484. #if EXTRUDERS > 2
  9485. extruder_multiplier[2] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_2));
  9486. #endif
  9487. #endif
  9488. extrudemultiply = (int)eeprom_read_word((uint16_t*)(EEPROM_EXTRUDEMULTIPLY));
  9489. // 9) Recover the saved target
  9490. saved_start_position[X_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+0*4));
  9491. saved_start_position[Y_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+1*4));
  9492. saved_start_position[Z_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+2*4));
  9493. saved_start_position[E_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_SAVED_START_POSITION+3*4));
  9494. saved_segment_idx = eeprom_read_word((uint16_t*)EEPROM_UVLO_SAVED_SEGMENT_IDX);
  9495. #ifdef LIN_ADVANCE
  9496. extruder_advance_K = eeprom_read_float((float*)EEPROM_UVLO_LA_K);
  9497. #endif
  9498. return mbl_was_active;
  9499. }
  9500. void restore_print_from_eeprom(bool mbl_was_active) {
  9501. int feedrate_rec;
  9502. int feedmultiply_rec;
  9503. uint8_t fan_speed_rec;
  9504. char cmd[48];
  9505. char filename[FILENAME_LENGTH];
  9506. uint8_t depth = 0;
  9507. char dir_name[9];
  9508. fan_speed_rec = eeprom_read_byte((uint8_t*)EEPROM_UVLO_FAN_SPEED);
  9509. feedrate_rec = eeprom_read_word((uint16_t*)EEPROM_UVLO_FEEDRATE);
  9510. feedmultiply_rec = eeprom_read_word((uint16_t*)EEPROM_UVLO_FEEDMULTIPLY);
  9511. SERIAL_ECHOPGM("Feedrate:");
  9512. MYSERIAL.print(feedrate_rec);
  9513. SERIAL_ECHOPGM(", feedmultiply:");
  9514. MYSERIAL.println(feedmultiply_rec);
  9515. depth = eeprom_read_byte((uint8_t*)EEPROM_DIR_DEPTH);
  9516. MYSERIAL.println(int(depth));
  9517. for (uint8_t i = 0; i < depth; i++) {
  9518. for (uint8_t j = 0; j < 8; j++) {
  9519. dir_name[j] = eeprom_read_byte((uint8_t*)EEPROM_DIRS + j + 8 * i);
  9520. }
  9521. dir_name[8] = '\0';
  9522. MYSERIAL.println(dir_name);
  9523. // strcpy(card.dir_names[i], dir_name);
  9524. card.chdir(dir_name, false);
  9525. }
  9526. for (uint8_t i = 0; i < 8; i++) {
  9527. filename[i] = eeprom_read_byte((uint8_t*)EEPROM_FILENAME + i);
  9528. }
  9529. filename[8] = '\0';
  9530. MYSERIAL.print(filename);
  9531. strcat_P(filename, PSTR(".gco"));
  9532. sprintf_P(cmd, PSTR("M23 %s"), filename);
  9533. enquecommand(cmd);
  9534. uint32_t position = eeprom_read_dword((uint32_t*)(EEPROM_FILE_POSITION));
  9535. SERIAL_ECHOPGM("Position read from eeprom:");
  9536. MYSERIAL.println(position);
  9537. // Move to the XY print position in logical coordinates, where the print has been killed, but
  9538. // without shifting Z along the way. This requires performing the move without mbl.
  9539. float pos_x = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0));
  9540. float pos_y = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 4));
  9541. if (pos_x != X_COORD_INVALID)
  9542. {
  9543. sprintf_P(cmd, PSTR("G1 X%f Y%f F3000"), pos_x, pos_y);
  9544. enquecommand(cmd);
  9545. }
  9546. // Enable MBL and switch to logical positioning
  9547. if (mbl_was_active)
  9548. enquecommand_P(PSTR("PRUSA MBL V1"));
  9549. // Move the Z axis down to the print, in logical coordinates.
  9550. sprintf_P(cmd, PSTR("G1 Z%f"), eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_Z)));
  9551. enquecommand(cmd);
  9552. // Restore acceleration settings
  9553. float acceleration = eeprom_read_float((float*)(EEPROM_UVLO_ACCELL));
  9554. float retract_acceleration = eeprom_read_float((float*)(EEPROM_UVLO_RETRACT_ACCELL));
  9555. float travel_acceleration = eeprom_read_float((float*)(EEPROM_UVLO_TRAVEL_ACCELL));
  9556. sprintf_P(cmd, PSTR("M204 P%f R%f T%f"), acceleration, retract_acceleration, travel_acceleration);
  9557. enquecommand(cmd);
  9558. // Unretract.
  9559. sprintf_P(cmd, PSTR("G1 E%0.3f F2700"), default_retraction);
  9560. enquecommand(cmd);
  9561. // Recover final E axis position and mode
  9562. float pos_e = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_E));
  9563. sprintf_P(cmd, PSTR("G92 E%6.3f"), pos_e);
  9564. enquecommand(cmd);
  9565. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO_E_ABS))
  9566. enquecommand_P(PSTR("M82")); //E axis abslute mode
  9567. // Set the feedrates saved at the power panic.
  9568. sprintf_P(cmd, PSTR("G1 F%d"), feedrate_rec);
  9569. enquecommand(cmd);
  9570. sprintf_P(cmd, PSTR("M220 S%d"), feedmultiply_rec);
  9571. enquecommand(cmd);
  9572. // Set the fan speed saved at the power panic.
  9573. strcpy_P(cmd, PSTR("M106 S"));
  9574. strcat(cmd, itostr3(int(fan_speed_rec)));
  9575. enquecommand(cmd);
  9576. // Set a position in the file.
  9577. sprintf_P(cmd, PSTR("M26 S%lu"), position);
  9578. enquecommand(cmd);
  9579. enquecommand_P(PSTR("G4 S0"));
  9580. enquecommand_P(PSTR("PRUSA uvlo"));
  9581. }
  9582. #endif //UVLO_SUPPORT
  9583. //! @brief Immediately stop print moves
  9584. //!
  9585. //! Immediately stop print moves, save current extruder temperature and position to RAM.
  9586. //! If printing from sd card, position in file is saved.
  9587. //! If printing from USB, line number is saved.
  9588. //!
  9589. //! @param z_move
  9590. //! @param e_move
  9591. void stop_and_save_print_to_ram(float z_move, float e_move)
  9592. {
  9593. if (saved_printing) return;
  9594. #if 0
  9595. unsigned char nplanner_blocks;
  9596. #endif
  9597. unsigned char nlines;
  9598. uint16_t sdlen_planner;
  9599. uint16_t sdlen_cmdqueue;
  9600. cli();
  9601. if (card.sdprinting) {
  9602. #if 0
  9603. nplanner_blocks = number_of_blocks();
  9604. #endif
  9605. saved_sdpos = sdpos_atomic; //atomic sd position of last command added in queue
  9606. sdlen_planner = planner_calc_sd_length(); //length of sd commands in planner
  9607. saved_sdpos -= sdlen_planner;
  9608. sdlen_cmdqueue = cmdqueue_calc_sd_length(); //length of sd commands in cmdqueue
  9609. saved_sdpos -= sdlen_cmdqueue;
  9610. saved_printing_type = PRINTING_TYPE_SD;
  9611. }
  9612. else if (usb_timer.running()) { //reuse saved_sdpos for storing line number
  9613. saved_sdpos = gcode_LastN; //start with line number of command added recently to cmd queue
  9614. //reuse planner_calc_sd_length function for getting number of lines of commands in planner:
  9615. nlines = planner_calc_sd_length(); //number of lines of commands in planner
  9616. saved_sdpos -= nlines;
  9617. saved_sdpos -= buflen; //number of blocks in cmd buffer
  9618. saved_printing_type = PRINTING_TYPE_USB;
  9619. }
  9620. else {
  9621. saved_printing_type = PRINTING_TYPE_NONE;
  9622. //not sd printing nor usb printing
  9623. }
  9624. #if 0
  9625. SERIAL_ECHOPGM("SDPOS_ATOMIC="); MYSERIAL.println(sdpos_atomic, DEC);
  9626. SERIAL_ECHOPGM("SDPOS="); MYSERIAL.println(card.get_sdpos(), DEC);
  9627. SERIAL_ECHOPGM("SDLEN_PLAN="); MYSERIAL.println(sdlen_planner, DEC);
  9628. SERIAL_ECHOPGM("SDLEN_CMDQ="); MYSERIAL.println(sdlen_cmdqueue, DEC);
  9629. SERIAL_ECHOPGM("PLANNERBLOCKS="); MYSERIAL.println(int(nplanner_blocks), DEC);
  9630. SERIAL_ECHOPGM("SDSAVED="); MYSERIAL.println(saved_sdpos, DEC);
  9631. //SERIAL_ECHOPGM("SDFILELEN="); MYSERIAL.println(card.fileSize(), DEC);
  9632. {
  9633. card.setIndex(saved_sdpos);
  9634. SERIAL_ECHOLNPGM("Content of planner buffer: ");
  9635. for (unsigned int idx = 0; idx < sdlen_planner; ++ idx)
  9636. MYSERIAL.print(char(card.get()));
  9637. SERIAL_ECHOLNPGM("Content of command buffer: ");
  9638. for (unsigned int idx = 0; idx < sdlen_cmdqueue; ++ idx)
  9639. MYSERIAL.print(char(card.get()));
  9640. SERIAL_ECHOLNPGM("End of command buffer");
  9641. }
  9642. {
  9643. // Print the content of the planner buffer, line by line:
  9644. card.setIndex(saved_sdpos);
  9645. int8_t iline = 0;
  9646. for (unsigned char idx = block_buffer_tail; idx != block_buffer_head; idx = (idx + 1) & (BLOCK_BUFFER_SIZE - 1), ++ iline) {
  9647. SERIAL_ECHOPGM("Planner line (from file): ");
  9648. MYSERIAL.print(int(iline), DEC);
  9649. SERIAL_ECHOPGM(", length: ");
  9650. MYSERIAL.print(block_buffer[idx].sdlen, DEC);
  9651. SERIAL_ECHOPGM(", steps: (");
  9652. MYSERIAL.print(block_buffer[idx].steps_x, DEC);
  9653. SERIAL_ECHOPGM(",");
  9654. MYSERIAL.print(block_buffer[idx].steps_y, DEC);
  9655. SERIAL_ECHOPGM(",");
  9656. MYSERIAL.print(block_buffer[idx].steps_z, DEC);
  9657. SERIAL_ECHOPGM(",");
  9658. MYSERIAL.print(block_buffer[idx].steps_e, DEC);
  9659. SERIAL_ECHOPGM("), events: ");
  9660. MYSERIAL.println(block_buffer[idx].step_event_count, DEC);
  9661. for (int len = block_buffer[idx].sdlen; len > 0; -- len)
  9662. MYSERIAL.print(char(card.get()));
  9663. }
  9664. }
  9665. {
  9666. // Print the content of the command buffer, line by line:
  9667. int8_t iline = 0;
  9668. union {
  9669. struct {
  9670. char lo;
  9671. char hi;
  9672. } lohi;
  9673. uint16_t value;
  9674. } sdlen_single;
  9675. int _bufindr = bufindr;
  9676. for (int _buflen = buflen; _buflen > 0; ++ iline) {
  9677. if (cmdbuffer[_bufindr] == CMDBUFFER_CURRENT_TYPE_SDCARD) {
  9678. sdlen_single.lohi.lo = cmdbuffer[_bufindr + 1];
  9679. sdlen_single.lohi.hi = cmdbuffer[_bufindr + 2];
  9680. }
  9681. SERIAL_ECHOPGM("Buffer line (from buffer): ");
  9682. MYSERIAL.print(int(iline), DEC);
  9683. SERIAL_ECHOPGM(", type: ");
  9684. MYSERIAL.print(int(cmdbuffer[_bufindr]), DEC);
  9685. SERIAL_ECHOPGM(", len: ");
  9686. MYSERIAL.println(sdlen_single.value, DEC);
  9687. // Print the content of the buffer line.
  9688. MYSERIAL.println(cmdbuffer + _bufindr + CMDHDRSIZE);
  9689. SERIAL_ECHOPGM("Buffer line (from file): ");
  9690. MYSERIAL.println(int(iline), DEC);
  9691. for (; sdlen_single.value > 0; -- sdlen_single.value)
  9692. MYSERIAL.print(char(card.get()));
  9693. if (-- _buflen == 0)
  9694. break;
  9695. // First skip the current command ID and iterate up to the end of the string.
  9696. for (_bufindr += CMDHDRSIZE; cmdbuffer[_bufindr] != 0; ++ _bufindr) ;
  9697. // Second, skip the end of string null character and iterate until a nonzero command ID is found.
  9698. for (++ _bufindr; _bufindr < sizeof(cmdbuffer) && cmdbuffer[_bufindr] == 0; ++ _bufindr) ;
  9699. // If the end of the buffer was empty,
  9700. if (_bufindr == sizeof(cmdbuffer)) {
  9701. // skip to the start and find the nonzero command.
  9702. for (_bufindr = 0; cmdbuffer[_bufindr] == 0; ++ _bufindr) ;
  9703. }
  9704. }
  9705. }
  9706. #endif
  9707. // save the global state at planning time
  9708. bool pos_invalid = XY_NO_RESTORE_FLAG;
  9709. if (current_block && !pos_invalid)
  9710. {
  9711. memcpy(saved_start_position, current_block->gcode_start_position, sizeof(saved_start_position));
  9712. saved_feedrate2 = current_block->gcode_feedrate;
  9713. saved_segment_idx = current_block->segment_idx;
  9714. // 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);
  9715. }
  9716. else
  9717. {
  9718. saved_start_position[0] = SAVED_START_POSITION_UNSET;
  9719. saved_feedrate2 = feedrate;
  9720. saved_segment_idx = 0;
  9721. }
  9722. planner_abort_hard(); //abort printing
  9723. memcpy(saved_pos, current_position, sizeof(saved_pos));
  9724. if (pos_invalid) saved_pos[X_AXIS] = X_COORD_INVALID;
  9725. saved_feedmultiply2 = feedmultiply; //save feedmultiply
  9726. saved_active_extruder = active_extruder; //save active_extruder
  9727. saved_extruder_temperature = degTargetHotend(active_extruder);
  9728. saved_bed_temperature = degTargetBed();
  9729. saved_extruder_relative_mode = axis_relative_modes & E_AXIS_MASK;
  9730. saved_fan_speed = fanSpeed;
  9731. cmdqueue_reset(); //empty cmdqueue
  9732. card.sdprinting = false;
  9733. // card.closefile();
  9734. saved_printing = true;
  9735. // We may have missed a stepper timer interrupt. Be safe than sorry, reset the stepper timer before re-enabling interrupts.
  9736. st_reset_timer();
  9737. sei();
  9738. if ((z_move != 0) || (e_move != 0)) { // extruder or z move
  9739. // Rather than calling plan_buffer_line directly, push the move into the command queue so that
  9740. // the caller can continue processing. This is used during powerpanic to save the state as we
  9741. // move away from the print.
  9742. char buf[48];
  9743. if(e_move)
  9744. {
  9745. // First unretract (relative extrusion)
  9746. if(!saved_extruder_relative_mode){
  9747. enquecommand(PSTR("M83"), true);
  9748. }
  9749. //retract 45mm/s
  9750. // A single sprintf may not be faster, but is definitely 20B shorter
  9751. // than a sequence of commands building the string piece by piece
  9752. // A snprintf would have been a safer call, but since it is not used
  9753. // in the whole program, its implementation would bring more bytes to the total size
  9754. // The behavior of dtostrf 8,3 should be roughly the same as %-0.3
  9755. sprintf_P(buf, PSTR("G1 E%-0.3f F2700"), e_move);
  9756. enquecommand(buf, false);
  9757. }
  9758. if(z_move)
  9759. {
  9760. // Then lift Z axis
  9761. sprintf_P(buf, PSTR("G1 Z%-0.3f F%-0.3f"), saved_pos[Z_AXIS] + z_move, homing_feedrate[Z_AXIS]);
  9762. enquecommand(buf, false);
  9763. }
  9764. // If this call is invoked from the main Arduino loop() function, let the caller know that the command
  9765. // in the command queue is not the original command, but a new one, so it should not be removed from the queue.
  9766. repeatcommand_front();
  9767. }
  9768. }
  9769. //! @brief Restore print from ram
  9770. //!
  9771. //! Restore print saved by stop_and_save_print_to_ram(). Is blocking, restores
  9772. //! print fan speed, waits for extruder temperature restore, then restores
  9773. //! position and continues print moves.
  9774. //!
  9775. //! Internally lcd_update() is called by wait_for_heater().
  9776. //!
  9777. //! @param e_move
  9778. void restore_print_from_ram_and_continue(float e_move)
  9779. {
  9780. if (!saved_printing) return;
  9781. #ifdef FANCHECK
  9782. // Do not allow resume printing if fans are still not ok
  9783. if ((fan_check_error != EFCE_OK) && (fan_check_error != EFCE_FIXED)) return;
  9784. if (fan_check_error == EFCE_FIXED) fan_check_error = EFCE_OK; //reenable serial stream processing if printing from usb
  9785. #endif
  9786. // restore bed temperature (bed can be disabled during a thermal warning)
  9787. if (degBed() != saved_bed_temperature)
  9788. setTargetBed(saved_bed_temperature);
  9789. // restore active_extruder
  9790. active_extruder = saved_active_extruder;
  9791. fanSpeed = saved_fan_speed;
  9792. if (degTargetHotend(saved_active_extruder) != saved_extruder_temperature)
  9793. {
  9794. setTargetHotendSafe(saved_extruder_temperature, saved_active_extruder);
  9795. heating_status = HeatingStatus::EXTRUDER_HEATING;
  9796. wait_for_heater(_millis(), saved_active_extruder);
  9797. heating_status = HeatingStatus::EXTRUDER_HEATING_COMPLETE;
  9798. }
  9799. axis_relative_modes ^= (-saved_extruder_relative_mode ^ axis_relative_modes) & E_AXIS_MASK;
  9800. float e = saved_pos[E_AXIS] - e_move;
  9801. plan_set_e_position(e);
  9802. #ifdef FANCHECK
  9803. fans_check_enabled = false;
  9804. #endif
  9805. // do not restore XY for commands that do not require that
  9806. if (saved_pos[X_AXIS] == X_COORD_INVALID)
  9807. {
  9808. saved_pos[X_AXIS] = current_position[X_AXIS];
  9809. saved_pos[Y_AXIS] = current_position[Y_AXIS];
  9810. }
  9811. //first move print head in XY to the saved position:
  9812. 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);
  9813. //then move Z
  9814. 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);
  9815. //and finaly unretract (35mm/s)
  9816. plan_buffer_line(saved_pos[X_AXIS], saved_pos[Y_AXIS], saved_pos[Z_AXIS], saved_pos[E_AXIS], FILAMENTCHANGE_RFEED, active_extruder);
  9817. st_synchronize();
  9818. #ifdef FANCHECK
  9819. fans_check_enabled = true;
  9820. #endif
  9821. // restore original feedrate/feedmultiply _after_ restoring the extruder position
  9822. feedrate = saved_feedrate2;
  9823. feedmultiply = saved_feedmultiply2;
  9824. memcpy(current_position, saved_pos, sizeof(saved_pos));
  9825. set_destination_to_current();
  9826. if (saved_printing_type == PRINTING_TYPE_SD) { //was sd printing
  9827. card.setIndex(saved_sdpos);
  9828. sdpos_atomic = saved_sdpos;
  9829. card.sdprinting = true;
  9830. }
  9831. else if (saved_printing_type == PRINTING_TYPE_USB) { //was usb printing
  9832. gcode_LastN = saved_sdpos; //saved_sdpos was reused for storing line number when usb printing
  9833. serial_count = 0;
  9834. FlushSerialRequestResend();
  9835. }
  9836. else {
  9837. //not sd printing nor usb printing
  9838. }
  9839. lcd_setstatuspgm(MSG_WELCOME);
  9840. saved_printing_type = PRINTING_TYPE_NONE;
  9841. saved_printing = false;
  9842. planner_aborted = true; // unroll the stack
  9843. }
  9844. // Cancel the state related to a currently saved print
  9845. void cancel_saved_printing()
  9846. {
  9847. eeprom_update_byte((uint8_t*)EEPROM_UVLO, 0);
  9848. saved_start_position[0] = SAVED_START_POSITION_UNSET;
  9849. saved_printing_type = PRINTING_TYPE_NONE;
  9850. saved_printing = false;
  9851. }
  9852. void print_world_coordinates()
  9853. {
  9854. printf_P(_N("world coordinates: (%.3f, %.3f, %.3f)\n"), current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS]);
  9855. }
  9856. void print_physical_coordinates()
  9857. {
  9858. 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));
  9859. }
  9860. void print_mesh_bed_leveling_table()
  9861. {
  9862. SERIAL_ECHOPGM("mesh bed leveling: ");
  9863. for (int8_t y = 0; y < MESH_NUM_Y_POINTS; ++ y)
  9864. for (int8_t x = 0; x < MESH_NUM_Y_POINTS; ++ x) {
  9865. MYSERIAL.print(mbl.z_values[y][x], 3);
  9866. SERIAL_ECHO(' ');
  9867. }
  9868. SERIAL_ECHOLN();
  9869. }
  9870. uint8_t calc_percent_done()
  9871. {
  9872. //in case that we have information from M73 gcode return percentage counted by slicer, else return percentage counted as byte_printed/filesize
  9873. uint8_t percent_done = 0;
  9874. #ifdef TMC2130
  9875. if (SilentModeMenu == SILENT_MODE_OFF && print_percent_done_normal <= 100)
  9876. {
  9877. percent_done = print_percent_done_normal;
  9878. }
  9879. else if (print_percent_done_silent <= 100)
  9880. {
  9881. percent_done = print_percent_done_silent;
  9882. }
  9883. #else
  9884. if (print_percent_done_normal <= 100)
  9885. {
  9886. percent_done = print_percent_done_normal;
  9887. }
  9888. #endif //TMC2130
  9889. else
  9890. {
  9891. percent_done = card.percentDone();
  9892. }
  9893. return percent_done;
  9894. }
  9895. static void print_time_remaining_init()
  9896. {
  9897. print_time_remaining_normal = PRINT_TIME_REMAINING_INIT;
  9898. print_percent_done_normal = PRINT_PERCENT_DONE_INIT;
  9899. print_time_remaining_silent = PRINT_TIME_REMAINING_INIT;
  9900. print_percent_done_silent = PRINT_PERCENT_DONE_INIT;
  9901. print_time_to_change_normal = PRINT_TIME_REMAINING_INIT;
  9902. print_time_to_change_silent = PRINT_TIME_REMAINING_INIT;
  9903. }
  9904. void load_filament_final_feed()
  9905. {
  9906. current_position[E_AXIS]+= FILAMENTCHANGE_FINALFEED;
  9907. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EFEED_FINAL);
  9908. }
  9909. //! @brief Wait for user to check the state
  9910. //! @par nozzle_temp nozzle temperature to load filament
  9911. void M600_check_state(float nozzle_temp)
  9912. {
  9913. lcd_change_fil_state = 0;
  9914. while (lcd_change_fil_state != 1)
  9915. {
  9916. lcd_change_fil_state = 0;
  9917. KEEPALIVE_STATE(PAUSED_FOR_USER);
  9918. lcd_alright();
  9919. KEEPALIVE_STATE(IN_HANDLER);
  9920. switch(lcd_change_fil_state)
  9921. {
  9922. // Filament failed to load so load it again
  9923. case 2:
  9924. if (mmu_enabled)
  9925. mmu_M600_load_filament(false, nozzle_temp); //nonautomatic load; change to "wrong filament loaded" option?
  9926. else
  9927. M600_load_filament_movements();
  9928. break;
  9929. // Filament loaded properly but color is not clear
  9930. case 3:
  9931. st_synchronize();
  9932. load_filament_final_feed();
  9933. lcd_loading_color();
  9934. st_synchronize();
  9935. break;
  9936. // Everything good
  9937. default:
  9938. lcd_change_success();
  9939. break;
  9940. }
  9941. }
  9942. }
  9943. //! @brief Wait for user action
  9944. //!
  9945. //! Beep, manage nozzle heater and wait for user to start unload filament
  9946. //! If times out, active extruder temperature is set to 0.
  9947. //!
  9948. //! @param HotendTempBckp Temperature to be restored for active extruder, after user resolves MMU problem.
  9949. void M600_wait_for_user(float HotendTempBckp) {
  9950. KEEPALIVE_STATE(PAUSED_FOR_USER);
  9951. int counterBeep = 0;
  9952. unsigned long waiting_start_time = _millis();
  9953. uint8_t wait_for_user_state = 0;
  9954. lcd_display_message_fullscreen_P(_T(MSG_PRESS_TO_UNLOAD));
  9955. bool bFirst=true;
  9956. while (!(wait_for_user_state == 0 && lcd_clicked())){
  9957. manage_heater();
  9958. manage_inactivity(true);
  9959. #if BEEPER > 0
  9960. if (counterBeep == 500) {
  9961. counterBeep = 0;
  9962. }
  9963. SET_OUTPUT(BEEPER);
  9964. if (counterBeep == 0) {
  9965. if((eSoundMode==e_SOUND_MODE_BLIND)|| (eSoundMode==e_SOUND_MODE_LOUD)||((eSoundMode==e_SOUND_MODE_ONCE)&&bFirst))
  9966. {
  9967. bFirst=false;
  9968. WRITE(BEEPER, HIGH);
  9969. }
  9970. }
  9971. if (counterBeep == 20) {
  9972. WRITE(BEEPER, LOW);
  9973. }
  9974. counterBeep++;
  9975. #endif //BEEPER > 0
  9976. switch (wait_for_user_state) {
  9977. case 0: //nozzle is hot, waiting for user to press the knob to unload filament
  9978. delay_keep_alive(4);
  9979. if (_millis() > waiting_start_time + (unsigned long)M600_TIMEOUT * 1000) {
  9980. lcd_display_message_fullscreen_P(_i("Press the knob to preheat nozzle and continue."));////MSG_PRESS_TO_PREHEAT c=20 r=4
  9981. wait_for_user_state = 1;
  9982. setAllTargetHotends(0);
  9983. st_synchronize();
  9984. disable_e0();
  9985. disable_e1();
  9986. disable_e2();
  9987. }
  9988. break;
  9989. case 1: //nozzle target temperature is set to zero, waiting for user to start nozzle preheat
  9990. delay_keep_alive(4);
  9991. if (lcd_clicked()) {
  9992. setTargetHotend(HotendTempBckp, active_extruder);
  9993. lcd_wait_for_heater();
  9994. wait_for_user_state = 2;
  9995. }
  9996. break;
  9997. case 2: //waiting for nozzle to reach target temperature
  9998. if (fabs(degTargetHotend(active_extruder) - degHotend(active_extruder)) < 1) {
  9999. lcd_display_message_fullscreen_P(_T(MSG_PRESS_TO_UNLOAD));
  10000. waiting_start_time = _millis();
  10001. wait_for_user_state = 0;
  10002. }
  10003. else {
  10004. counterBeep = 20; //beeper will be inactive during waiting for nozzle preheat
  10005. lcd_set_cursor(1, 4);
  10006. lcd_printf_P(PSTR("%3d"), (int16_t)degHotend(active_extruder));
  10007. }
  10008. break;
  10009. }
  10010. }
  10011. WRITE(BEEPER, LOW);
  10012. }
  10013. void M600_load_filament_movements()
  10014. {
  10015. current_position[E_AXIS]+= FILAMENTCHANGE_FIRSTFEED;
  10016. plan_buffer_line_curposXYZE(FILAMENTCHANGE_EFEED_FIRST);
  10017. load_filament_final_feed();
  10018. lcd_loading_filament();
  10019. st_synchronize();
  10020. }
  10021. void M600_load_filament() {
  10022. //load filament for single material and MMU
  10023. lcd_wait_interact();
  10024. //load_filament_time = _millis();
  10025. KEEPALIVE_STATE(PAUSED_FOR_USER);
  10026. while(!lcd_clicked())
  10027. {
  10028. manage_heater();
  10029. manage_inactivity(true);
  10030. #ifdef FILAMENT_SENSOR
  10031. if (fsensor.getFilamentLoadEvent()) {
  10032. Sound_MakeCustom(50,1000,false);
  10033. break;
  10034. }
  10035. #endif //FILAMENT_SENSOR
  10036. }
  10037. KEEPALIVE_STATE(IN_HANDLER);
  10038. M600_load_filament_movements();
  10039. Sound_MakeCustom(50,1000,false);
  10040. lcd_update_enable(false);
  10041. }
  10042. //! @brief Wait for click
  10043. //!
  10044. //! Set
  10045. void marlin_wait_for_click()
  10046. {
  10047. int8_t busy_state_backup = busy_state;
  10048. KEEPALIVE_STATE(PAUSED_FOR_USER);
  10049. lcd_consume_click();
  10050. while(!lcd_clicked())
  10051. {
  10052. manage_heater();
  10053. manage_inactivity(true);
  10054. lcd_update(0);
  10055. }
  10056. KEEPALIVE_STATE(busy_state_backup);
  10057. }
  10058. #define FIL_LOAD_LENGTH 60
  10059. #ifdef PSU_Delta
  10060. bool bEnableForce_z;
  10061. void init_force_z()
  10062. {
  10063. WRITE(Z_ENABLE_PIN,Z_ENABLE_ON);
  10064. bEnableForce_z=true; // "true"-value enforce "disable_force_z()" executing
  10065. disable_force_z();
  10066. }
  10067. void check_force_z()
  10068. {
  10069. if(!(bEnableForce_z||eeprom_read_byte((uint8_t*)EEPROM_SILENT)))
  10070. init_force_z(); // causes enforced switching into disable-state
  10071. }
  10072. void disable_force_z()
  10073. {
  10074. if(!bEnableForce_z) return; // motor already disabled (may be ;-p )
  10075. bEnableForce_z=false;
  10076. // switching to silent mode
  10077. #ifdef TMC2130
  10078. tmc2130_mode=TMC2130_MODE_SILENT;
  10079. update_mode_profile();
  10080. tmc2130_init(TMCInitParams(true, FarmOrUserECool()));
  10081. #endif // TMC2130
  10082. }
  10083. void enable_force_z()
  10084. {
  10085. if(bEnableForce_z)
  10086. return; // motor already enabled (may be ;-p )
  10087. bEnableForce_z=true;
  10088. // mode recovering
  10089. #ifdef TMC2130
  10090. tmc2130_mode=eeprom_read_byte((uint8_t*)EEPROM_SILENT)?TMC2130_MODE_SILENT:TMC2130_MODE_NORMAL;
  10091. update_mode_profile();
  10092. tmc2130_init(TMCInitParams(true, FarmOrUserECool()));
  10093. #endif // TMC2130
  10094. WRITE(Z_ENABLE_PIN,Z_ENABLE_ON); // slightly redundant ;-p
  10095. }
  10096. #endif // PSU_Delta