Marlin_main.cpp 389 KB

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