Marlin_main.cpp 314 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234
  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. #include "Marlin.h"
  45. #ifdef ENABLE_AUTO_BED_LEVELING
  46. #include "vector_3.h"
  47. #ifdef AUTO_BED_LEVELING_GRID
  48. #include "qr_solve.h"
  49. #endif
  50. #endif // ENABLE_AUTO_BED_LEVELING
  51. #ifdef MESH_BED_LEVELING
  52. #include "mesh_bed_leveling.h"
  53. #include "mesh_bed_calibration.h"
  54. #endif
  55. #include "printers.h"
  56. #include "menu.h"
  57. #include "ultralcd.h"
  58. #include "planner.h"
  59. #include "stepper.h"
  60. #include "temperature.h"
  61. #include "motion_control.h"
  62. #include "cardreader.h"
  63. #include "ConfigurationStore.h"
  64. #include "language.h"
  65. #include "pins_arduino.h"
  66. #include "math.h"
  67. #include "util.h"
  68. #include "Timer.h"
  69. #include <avr/wdt.h>
  70. #include <avr/pgmspace.h>
  71. #include "Dcodes.h"
  72. #ifdef SWSPI
  73. #include "swspi.h"
  74. #endif //SWSPI
  75. #include "spi.h"
  76. #ifdef SWI2C
  77. #include "swi2c.h"
  78. #endif //SWI2C
  79. #ifdef FILAMENT_SENSOR
  80. #include "fsensor.h"
  81. #endif //FILAMENT_SENSOR
  82. #ifdef TMC2130
  83. #include "tmc2130.h"
  84. #endif //TMC2130
  85. #ifdef W25X20CL
  86. #include "w25x20cl.h"
  87. #include "optiboot_w25x20cl.h"
  88. #endif //W25X20CL
  89. #ifdef BLINKM
  90. #include "BlinkM.h"
  91. #include "Wire.h"
  92. #endif
  93. #ifdef ULTRALCD
  94. #include "ultralcd.h"
  95. #endif
  96. #if NUM_SERVOS > 0
  97. #include "Servo.h"
  98. #endif
  99. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  100. #include <SPI.h>
  101. #endif
  102. #include "mmu.h"
  103. #define VERSION_STRING "1.0.2"
  104. #include "ultralcd.h"
  105. #include "sound.h"
  106. #include "cmdqueue.h"
  107. #include "io_atmega2560.h"
  108. // Macros for bit masks
  109. #define BIT(b) (1<<(b))
  110. #define TEST(n,b) (((n)&BIT(b))!=0)
  111. #define SET_BIT(n,b,value) (n) ^= ((-value)^(n)) & (BIT(b))
  112. //Macro for print fan speed
  113. #define FAN_PULSE_WIDTH_LIMIT ((fanSpeed > 100) ? 3 : 4) //time in ms
  114. #define PRINTING_TYPE_SD 0
  115. #define PRINTING_TYPE_USB 1
  116. //filament types
  117. #define FILAMENT_DEFAULT 0
  118. #define FILAMENT_FLEX 1
  119. #define FILAMENT_PVA 2
  120. #define FILAMENT_UNDEFINED 255
  121. //Stepper Movement Variables
  122. //===========================================================================
  123. //=============================imported variables============================
  124. //===========================================================================
  125. //===========================================================================
  126. //=============================public variables=============================
  127. //===========================================================================
  128. #ifdef SDSUPPORT
  129. CardReader card;
  130. #endif
  131. unsigned long PingTime = millis();
  132. unsigned long NcTime;
  133. //used for PINDA temp calibration and pause print
  134. #define DEFAULT_RETRACTION 1
  135. #define DEFAULT_RETRACTION_MM 4 //MM
  136. float default_retraction = DEFAULT_RETRACTION;
  137. float homing_feedrate[] = HOMING_FEEDRATE;
  138. // Currently only the extruder axis may be switched to a relative mode.
  139. // Other axes are always absolute or relative based on the common relative_mode flag.
  140. bool axis_relative_modes[] = AXIS_RELATIVE_MODES;
  141. int feedmultiply=100; //100->1 200->2
  142. int extrudemultiply=100; //100->1 200->2
  143. int extruder_multiply[EXTRUDERS] = {100
  144. #if EXTRUDERS > 1
  145. , 100
  146. #if EXTRUDERS > 2
  147. , 100
  148. #endif
  149. #endif
  150. };
  151. int bowden_length[4] = {385, 385, 385, 385};
  152. bool is_usb_printing = false;
  153. bool homing_flag = false;
  154. bool temp_cal_active = false;
  155. unsigned long kicktime = millis()+100000;
  156. unsigned int usb_printing_counter;
  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. bool mesh_bed_run_from_menu = false;
  166. int8_t FarmMode = 0;
  167. bool prusa_sd_card_upload = false;
  168. unsigned int status_number = 0;
  169. unsigned long total_filament_used;
  170. unsigned int heating_status;
  171. unsigned int heating_status_counter;
  172. bool loading_flag = false;
  173. char snmm_filaments_used = 0;
  174. bool fan_state[2];
  175. int fan_edge_counter[2];
  176. int fan_speed[2];
  177. char dir_names[3][9];
  178. bool sortAlpha = false;
  179. float extruder_multiplier[EXTRUDERS] = {1.0
  180. #if EXTRUDERS > 1
  181. , 1.0
  182. #if EXTRUDERS > 2
  183. , 1.0
  184. #endif
  185. #endif
  186. };
  187. float current_position[NUM_AXIS] = { 0.0, 0.0, 0.0, 0.0 };
  188. //shortcuts for more readable code
  189. #define _x current_position[X_AXIS]
  190. #define _y current_position[Y_AXIS]
  191. #define _z current_position[Z_AXIS]
  192. #define _e current_position[E_AXIS]
  193. float min_pos[3] = { X_MIN_POS, Y_MIN_POS, Z_MIN_POS };
  194. float max_pos[3] = { X_MAX_POS, Y_MAX_POS, Z_MAX_POS };
  195. bool axis_known_position[3] = {false, false, false};
  196. // Extruder offset
  197. #if EXTRUDERS > 1
  198. #define NUM_EXTRUDER_OFFSETS 2 // only in XY plane
  199. float extruder_offset[NUM_EXTRUDER_OFFSETS][EXTRUDERS] = {
  200. #if defined(EXTRUDER_OFFSET_X) && defined(EXTRUDER_OFFSET_Y)
  201. EXTRUDER_OFFSET_X, EXTRUDER_OFFSET_Y
  202. #endif
  203. };
  204. #endif
  205. uint8_t active_extruder = 0;
  206. int fanSpeed=0;
  207. #ifdef FWRETRACT
  208. bool retracted[EXTRUDERS]={false
  209. #if EXTRUDERS > 1
  210. , false
  211. #if EXTRUDERS > 2
  212. , false
  213. #endif
  214. #endif
  215. };
  216. bool retracted_swap[EXTRUDERS]={false
  217. #if EXTRUDERS > 1
  218. , false
  219. #if EXTRUDERS > 2
  220. , false
  221. #endif
  222. #endif
  223. };
  224. float retract_length_swap = RETRACT_LENGTH_SWAP;
  225. float retract_recover_length_swap = RETRACT_RECOVER_LENGTH_SWAP;
  226. #endif
  227. #ifdef PS_DEFAULT_OFF
  228. bool powersupply = false;
  229. #else
  230. bool powersupply = true;
  231. #endif
  232. bool cancel_heatup = false ;
  233. #ifdef HOST_KEEPALIVE_FEATURE
  234. int busy_state = NOT_BUSY;
  235. static long prev_busy_signal_ms = -1;
  236. uint8_t host_keepalive_interval = HOST_KEEPALIVE_INTERVAL;
  237. #else
  238. #define host_keepalive();
  239. #define KEEPALIVE_STATE(n);
  240. #endif
  241. const char errormagic[] PROGMEM = "Error:";
  242. const char echomagic[] PROGMEM = "echo:";
  243. bool no_response = false;
  244. uint8_t important_status;
  245. uint8_t saved_filament_type;
  246. // save/restore printing in case that mmu was not responding
  247. bool mmu_print_saved = false;
  248. // storing estimated time to end of print counted by slicer
  249. uint8_t print_percent_done_normal = PRINT_PERCENT_DONE_INIT;
  250. uint16_t print_time_remaining_normal = PRINT_TIME_REMAINING_INIT; //estimated remaining print time in minutes
  251. uint8_t print_percent_done_silent = PRINT_PERCENT_DONE_INIT;
  252. uint16_t print_time_remaining_silent = PRINT_TIME_REMAINING_INIT; //estimated remaining print time in minutes
  253. bool wizard_active = false; //autoload temporarily disabled during wizard
  254. //===========================================================================
  255. //=============================Private Variables=============================
  256. //===========================================================================
  257. #define MSG_BED_LEVELING_FAILED_TIMEOUT 30
  258. const char axis_codes[NUM_AXIS] = {'X', 'Y', 'Z', 'E'};
  259. float destination[NUM_AXIS] = { 0.0, 0.0, 0.0, 0.0};
  260. // For tracing an arc
  261. static float offset[3] = {0.0, 0.0, 0.0};
  262. static float feedrate = 1500.0, next_feedrate, saved_feedrate;
  263. // Determines Absolute or Relative Coordinates.
  264. // Also there is bool axis_relative_modes[] per axis flag.
  265. static bool relative_mode = false;
  266. const int sensitive_pins[] = SENSITIVE_PINS; // Sensitive pin list for M42
  267. //static float tt = 0;
  268. //static float bt = 0;
  269. //Inactivity shutdown variables
  270. static unsigned long previous_millis_cmd = 0;
  271. unsigned long max_inactive_time = 0;
  272. static unsigned long stepper_inactive_time = DEFAULT_STEPPER_DEACTIVE_TIME*1000l;
  273. static unsigned long safetytimer_inactive_time = DEFAULT_SAFETYTIMER_TIME_MINS*60*1000ul;
  274. unsigned long starttime=0;
  275. unsigned long stoptime=0;
  276. unsigned long _usb_timer = 0;
  277. bool extruder_under_pressure = true;
  278. bool Stopped=false;
  279. #if NUM_SERVOS > 0
  280. Servo servos[NUM_SERVOS];
  281. #endif
  282. bool CooldownNoWait = true;
  283. bool target_direction;
  284. //Insert variables if CHDK is defined
  285. #ifdef CHDK
  286. unsigned long chdkHigh = 0;
  287. boolean chdkActive = false;
  288. #endif
  289. //! @name RAM save/restore printing
  290. //! @{
  291. bool saved_printing = false; //!< Print is paused and saved in RAM
  292. static uint32_t saved_sdpos = 0; //!< SD card position, or line number in case of USB printing
  293. static uint8_t saved_printing_type = PRINTING_TYPE_SD;
  294. static float saved_pos[4] = { 0, 0, 0, 0 };
  295. //! Feedrate hopefully derived from an active block of the planner at the time the print has been canceled, in mm/min.
  296. static float saved_feedrate2 = 0;
  297. static uint8_t saved_active_extruder = 0;
  298. static float saved_extruder_temperature = 0.0; //!< Active extruder temperature
  299. static bool saved_extruder_under_pressure = false;
  300. static bool saved_extruder_relative_mode = false;
  301. static int saved_fanSpeed = 0; //!< Print fan speed
  302. //! @}
  303. static int saved_feedmultiply_mm = 100;
  304. //===========================================================================
  305. //=============================Routines======================================
  306. //===========================================================================
  307. static void get_arc_coordinates();
  308. static bool setTargetedHotend(int code, uint8_t &extruder);
  309. static void print_time_remaining_init();
  310. static void wait_for_heater(long codenum, uint8_t extruder);
  311. uint16_t gcode_in_progress = 0;
  312. uint16_t mcode_in_progress = 0;
  313. void serial_echopair_P(const char *s_P, float v)
  314. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  315. void serial_echopair_P(const char *s_P, double v)
  316. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  317. void serial_echopair_P(const char *s_P, unsigned long v)
  318. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  319. #ifdef SDSUPPORT
  320. #include "SdFatUtil.h"
  321. int freeMemory() { return SdFatUtil::FreeRam(); }
  322. #else
  323. extern "C" {
  324. extern unsigned int __bss_end;
  325. extern unsigned int __heap_start;
  326. extern void *__brkval;
  327. int freeMemory() {
  328. int free_memory;
  329. if ((int)__brkval == 0)
  330. free_memory = ((int)&free_memory) - ((int)&__bss_end);
  331. else
  332. free_memory = ((int)&free_memory) - ((int)__brkval);
  333. return free_memory;
  334. }
  335. }
  336. #endif //!SDSUPPORT
  337. void setup_killpin()
  338. {
  339. #if defined(KILL_PIN) && KILL_PIN > -1
  340. SET_INPUT(KILL_PIN);
  341. WRITE(KILL_PIN,HIGH);
  342. #endif
  343. }
  344. // Set home pin
  345. void setup_homepin(void)
  346. {
  347. #if defined(HOME_PIN) && HOME_PIN > -1
  348. SET_INPUT(HOME_PIN);
  349. WRITE(HOME_PIN,HIGH);
  350. #endif
  351. }
  352. void setup_photpin()
  353. {
  354. #if defined(PHOTOGRAPH_PIN) && PHOTOGRAPH_PIN > -1
  355. SET_OUTPUT(PHOTOGRAPH_PIN);
  356. WRITE(PHOTOGRAPH_PIN, LOW);
  357. #endif
  358. }
  359. void setup_powerhold()
  360. {
  361. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  362. SET_OUTPUT(SUICIDE_PIN);
  363. WRITE(SUICIDE_PIN, HIGH);
  364. #endif
  365. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  366. SET_OUTPUT(PS_ON_PIN);
  367. #if defined(PS_DEFAULT_OFF)
  368. WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  369. #else
  370. WRITE(PS_ON_PIN, PS_ON_AWAKE);
  371. #endif
  372. #endif
  373. }
  374. void suicide()
  375. {
  376. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  377. SET_OUTPUT(SUICIDE_PIN);
  378. WRITE(SUICIDE_PIN, LOW);
  379. #endif
  380. }
  381. void servo_init()
  382. {
  383. #if (NUM_SERVOS >= 1) && defined(SERVO0_PIN) && (SERVO0_PIN > -1)
  384. servos[0].attach(SERVO0_PIN);
  385. #endif
  386. #if (NUM_SERVOS >= 2) && defined(SERVO1_PIN) && (SERVO1_PIN > -1)
  387. servos[1].attach(SERVO1_PIN);
  388. #endif
  389. #if (NUM_SERVOS >= 3) && defined(SERVO2_PIN) && (SERVO2_PIN > -1)
  390. servos[2].attach(SERVO2_PIN);
  391. #endif
  392. #if (NUM_SERVOS >= 4) && defined(SERVO3_PIN) && (SERVO3_PIN > -1)
  393. servos[3].attach(SERVO3_PIN);
  394. #endif
  395. #if (NUM_SERVOS >= 5)
  396. #error "TODO: enter initalisation code for more servos"
  397. #endif
  398. }
  399. bool fans_check_enabled = true;
  400. #ifdef TMC2130
  401. extern int8_t CrashDetectMenu;
  402. void crashdet_enable()
  403. {
  404. tmc2130_sg_stop_on_crash = true;
  405. eeprom_update_byte((uint8_t*)EEPROM_CRASH_DET, 0xFF);
  406. CrashDetectMenu = 1;
  407. }
  408. void crashdet_disable()
  409. {
  410. tmc2130_sg_stop_on_crash = false;
  411. tmc2130_sg_crash = 0;
  412. eeprom_update_byte((uint8_t*)EEPROM_CRASH_DET, 0x00);
  413. CrashDetectMenu = 0;
  414. }
  415. void crashdet_stop_and_save_print()
  416. {
  417. stop_and_save_print_to_ram(10, -default_retraction); //XY - no change, Z 10mm up, E -1mm retract
  418. }
  419. void crashdet_restore_print_and_continue()
  420. {
  421. restore_print_from_ram_and_continue(default_retraction); //XYZ = orig, E +1mm unretract
  422. // babystep_apply();
  423. }
  424. void crashdet_stop_and_save_print2()
  425. {
  426. cli();
  427. planner_abort_hard(); //abort printing
  428. cmdqueue_reset(); //empty cmdqueue
  429. card.sdprinting = false;
  430. card.closefile();
  431. // Reset and re-enable the stepper timer just before the global interrupts are enabled.
  432. st_reset_timer();
  433. sei();
  434. }
  435. void crashdet_detected(uint8_t mask)
  436. {
  437. st_synchronize();
  438. static uint8_t crashDet_counter = 0;
  439. bool automatic_recovery_after_crash = true;
  440. if (crashDet_counter++ == 0) {
  441. crashDetTimer.start();
  442. }
  443. else if (crashDetTimer.expired(CRASHDET_TIMER * 1000ul)){
  444. crashDetTimer.stop();
  445. crashDet_counter = 0;
  446. }
  447. else if(crashDet_counter == CRASHDET_COUNTER_MAX){
  448. automatic_recovery_after_crash = false;
  449. crashDetTimer.stop();
  450. crashDet_counter = 0;
  451. }
  452. else {
  453. crashDetTimer.start();
  454. }
  455. lcd_update_enable(true);
  456. lcd_clear();
  457. lcd_update(2);
  458. if (mask & X_AXIS_MASK)
  459. {
  460. eeprom_update_byte((uint8_t*)EEPROM_CRASH_COUNT_X, eeprom_read_byte((uint8_t*)EEPROM_CRASH_COUNT_X) + 1);
  461. eeprom_update_word((uint16_t*)EEPROM_CRASH_COUNT_X_TOT, eeprom_read_word((uint16_t*)EEPROM_CRASH_COUNT_X_TOT) + 1);
  462. }
  463. if (mask & Y_AXIS_MASK)
  464. {
  465. eeprom_update_byte((uint8_t*)EEPROM_CRASH_COUNT_Y, eeprom_read_byte((uint8_t*)EEPROM_CRASH_COUNT_Y) + 1);
  466. eeprom_update_word((uint16_t*)EEPROM_CRASH_COUNT_Y_TOT, eeprom_read_word((uint16_t*)EEPROM_CRASH_COUNT_Y_TOT) + 1);
  467. }
  468. lcd_update_enable(true);
  469. lcd_update(2);
  470. lcd_setstatuspgm(_T(MSG_CRASH_DETECTED));
  471. gcode_G28(true, true, false); //home X and Y
  472. st_synchronize();
  473. if (automatic_recovery_after_crash) {
  474. enquecommand_P(PSTR("CRASH_RECOVER"));
  475. }else{
  476. setTargetHotend(0, active_extruder);
  477. bool yesno = lcd_show_fullscreen_message_yes_no_and_wait_P(_i("Crash detected. Resume print?"), false);
  478. lcd_update_enable(true);
  479. if (yesno)
  480. {
  481. enquecommand_P(PSTR("CRASH_RECOVER"));
  482. }
  483. else
  484. {
  485. enquecommand_P(PSTR("CRASH_CANCEL"));
  486. }
  487. }
  488. }
  489. void crashdet_recover()
  490. {
  491. crashdet_restore_print_and_continue();
  492. tmc2130_sg_stop_on_crash = true;
  493. }
  494. void crashdet_cancel()
  495. {
  496. saved_printing = false;
  497. tmc2130_sg_stop_on_crash = true;
  498. if (saved_printing_type == PRINTING_TYPE_SD) {
  499. lcd_print_stop();
  500. }else if(saved_printing_type == PRINTING_TYPE_USB){
  501. SERIAL_ECHOLNPGM("// action:cancel"); //for Octoprint: works the same as clicking "Abort" button in Octoprint GUI
  502. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  503. }
  504. }
  505. #endif //TMC2130
  506. void failstats_reset_print()
  507. {
  508. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_X, 0);
  509. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_Y, 0);
  510. eeprom_update_byte((uint8_t *)EEPROM_FERROR_COUNT, 0);
  511. eeprom_update_byte((uint8_t *)EEPROM_POWER_COUNT, 0);
  512. eeprom_update_byte((uint8_t *)EEPROM_MMU_FAIL, 0);
  513. eeprom_update_byte((uint8_t *)EEPROM_MMU_LOAD_FAIL, 0);
  514. }
  515. #ifdef MESH_BED_LEVELING
  516. enum MeshLevelingState { MeshReport, MeshStart, MeshNext, MeshSet };
  517. #endif
  518. // Factory reset function
  519. // This function is used to erase parts or whole EEPROM memory which is used for storing calibration and and so on.
  520. // Level input parameter sets depth of reset
  521. int er_progress = 0;
  522. static void factory_reset(char level)
  523. {
  524. lcd_clear();
  525. switch (level) {
  526. // Level 0: Language reset
  527. case 0:
  528. if((eSoundMode==e_SOUND_MODE_LOUD)||(eSoundMode==e_SOUND_MODE_ONCE))
  529. WRITE(BEEPER, HIGH);
  530. _delay_ms(100);
  531. WRITE(BEEPER, LOW);
  532. lang_reset();
  533. break;
  534. //Level 1: Reset statistics
  535. case 1:
  536. if((eSoundMode==e_SOUND_MODE_LOUD)||(eSoundMode==e_SOUND_MODE_ONCE))
  537. WRITE(BEEPER, HIGH);
  538. _delay_ms(100);
  539. WRITE(BEEPER, LOW);
  540. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, 0);
  541. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, 0);
  542. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_X, 0);
  543. eeprom_update_byte((uint8_t *)EEPROM_CRASH_COUNT_Y, 0);
  544. eeprom_update_byte((uint8_t *)EEPROM_FERROR_COUNT, 0);
  545. eeprom_update_byte((uint8_t *)EEPROM_POWER_COUNT, 0);
  546. eeprom_update_word((uint16_t *)EEPROM_CRASH_COUNT_X_TOT, 0);
  547. eeprom_update_word((uint16_t *)EEPROM_CRASH_COUNT_Y_TOT, 0);
  548. eeprom_update_word((uint16_t *)EEPROM_FERROR_COUNT_TOT, 0);
  549. eeprom_update_word((uint16_t *)EEPROM_POWER_COUNT_TOT, 0);
  550. eeprom_update_word((uint16_t *)EEPROM_MMU_FAIL_TOT, 0);
  551. eeprom_update_word((uint16_t *)EEPROM_MMU_LOAD_FAIL_TOT, 0);
  552. eeprom_update_byte((uint8_t *)EEPROM_MMU_FAIL, 0);
  553. eeprom_update_byte((uint8_t *)EEPROM_MMU_LOAD_FAIL, 0);
  554. lcd_menu_statistics();
  555. break;
  556. // Level 2: Prepare for shipping
  557. case 2:
  558. //lcd_puts_P(PSTR("Factory RESET"));
  559. //lcd_puts_at_P(1,2,PSTR("Shipping prep"));
  560. // Force language selection at the next boot up.
  561. lang_reset();
  562. // Force the "Follow calibration flow" message at the next boot up.
  563. calibration_status_store(CALIBRATION_STATUS_Z_CALIBRATION);
  564. eeprom_write_byte((uint8_t*)EEPROM_WIZARD_ACTIVE, 1); //run wizard
  565. farm_no = 0;
  566. farm_mode = false;
  567. eeprom_update_byte((uint8_t*)EEPROM_FARM_MODE, farm_mode);
  568. EEPROM_save_B(EEPROM_FARM_NUMBER, &farm_no);
  569. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, 0);
  570. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, 0);
  571. eeprom_update_word((uint16_t *)EEPROM_CRASH_COUNT_X_TOT, 0);
  572. eeprom_update_word((uint16_t *)EEPROM_CRASH_COUNT_Y_TOT, 0);
  573. eeprom_update_word((uint16_t *)EEPROM_FERROR_COUNT_TOT, 0);
  574. eeprom_update_word((uint16_t *)EEPROM_POWER_COUNT_TOT, 0);
  575. eeprom_update_word((uint16_t *)EEPROM_MMU_FAIL_TOT, 0);
  576. eeprom_update_word((uint16_t *)EEPROM_MMU_LOAD_FAIL_TOT, 0);
  577. eeprom_update_byte((uint8_t *)EEPROM_MMU_FAIL, 0);
  578. eeprom_update_byte((uint8_t *)EEPROM_MMU_LOAD_FAIL, 0);
  579. #ifdef FILAMENT_SENSOR
  580. fsensor_enable();
  581. fsensor_autoload_set(true);
  582. #endif //FILAMENT_SENSOR
  583. if((eSoundMode==e_SOUND_MODE_LOUD)||(eSoundMode==e_SOUND_MODE_ONCE))
  584. WRITE(BEEPER, HIGH);
  585. _delay_ms(100);
  586. WRITE(BEEPER, LOW);
  587. //_delay_ms(2000);
  588. break;
  589. // Level 3: erase everything, whole EEPROM will be set to 0xFF
  590. case 3:
  591. lcd_puts_P(PSTR("Factory RESET"));
  592. lcd_puts_at_P(1, 2, PSTR("ERASING all data"));
  593. if((eSoundMode==e_SOUND_MODE_LOUD)||(eSoundMode==e_SOUND_MODE_ONCE))
  594. WRITE(BEEPER, HIGH);
  595. _delay_ms(100);
  596. WRITE(BEEPER, LOW);
  597. er_progress = 0;
  598. lcd_puts_at_P(3, 3, PSTR(" "));
  599. lcd_set_cursor(3, 3);
  600. lcd_print(er_progress);
  601. // Erase EEPROM
  602. for (int i = 0; i < 4096; i++) {
  603. eeprom_update_byte((uint8_t*)i, 0xFF);
  604. if (i % 41 == 0) {
  605. er_progress++;
  606. lcd_puts_at_P(3, 3, PSTR(" "));
  607. lcd_set_cursor(3, 3);
  608. lcd_print(er_progress);
  609. lcd_puts_P(PSTR("%"));
  610. }
  611. }
  612. break;
  613. case 4:
  614. bowden_menu();
  615. break;
  616. default:
  617. break;
  618. }
  619. }
  620. extern "C" {
  621. FILE _uartout; //= {0}; Global variable is always zero initialized. No need to explicitly state this.
  622. }
  623. int uart_putchar(char c, FILE *)
  624. {
  625. MYSERIAL.write(c);
  626. return 0;
  627. }
  628. void lcd_splash()
  629. {
  630. // lcd_puts_at_P(0, 1, PSTR(" Original Prusa "));
  631. // lcd_puts_at_P(0, 2, PSTR(" 3D Printers "));
  632. // lcd_puts_P(PSTR("\x1b[1;3HOriginal Prusa\x1b[2;4H3D Printers"));
  633. // fputs_P(PSTR(ESC_2J ESC_H(1,1) "Original Prusa i3" ESC_H(3,2) "Prusa Research"), lcdout);
  634. lcd_puts_P(PSTR(ESC_2J ESC_H(1,1) "Original Prusa i3" ESC_H(3,2) "Prusa Research"));
  635. // lcd_printf_P(_N(ESC_2J "x:%.3f\ny:%.3f\nz:%.3f\ne:%.3f"), _x, _y, _z, _e);
  636. }
  637. void factory_reset()
  638. {
  639. KEEPALIVE_STATE(PAUSED_FOR_USER);
  640. if (!READ(BTN_ENC))
  641. {
  642. _delay_ms(1000);
  643. if (!READ(BTN_ENC))
  644. {
  645. lcd_clear();
  646. lcd_puts_P(PSTR("Factory RESET"));
  647. SET_OUTPUT(BEEPER);
  648. if((eSoundMode==e_SOUND_MODE_LOUD)||(eSoundMode==e_SOUND_MODE_ONCE))
  649. WRITE(BEEPER, HIGH);
  650. while (!READ(BTN_ENC));
  651. WRITE(BEEPER, LOW);
  652. _delay_ms(2000);
  653. char level = reset_menu();
  654. factory_reset(level);
  655. switch (level) {
  656. case 0: _delay_ms(0); break;
  657. case 1: _delay_ms(0); break;
  658. case 2: _delay_ms(0); break;
  659. case 3: _delay_ms(0); break;
  660. }
  661. }
  662. }
  663. KEEPALIVE_STATE(IN_HANDLER);
  664. }
  665. void show_fw_version_warnings() {
  666. if (FW_DEV_VERSION == FW_VERSION_GOLD || FW_DEV_VERSION == FW_VERSION_RC) return;
  667. switch (FW_DEV_VERSION) {
  668. 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
  669. 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
  670. case(FW_VERSION_DEVEL):
  671. case(FW_VERSION_DEBUG):
  672. lcd_update_enable(false);
  673. lcd_clear();
  674. #if FW_DEV_VERSION == FW_VERSION_DEVEL
  675. lcd_puts_at_P(0, 0, PSTR("Development build !!"));
  676. #else
  677. lcd_puts_at_P(0, 0, PSTR("Debbugging build !!!"));
  678. #endif
  679. lcd_puts_at_P(0, 1, PSTR("May destroy printer!"));
  680. lcd_puts_at_P(0, 2, PSTR("ver ")); lcd_puts_P(PSTR(FW_VERSION_FULL));
  681. lcd_puts_at_P(0, 3, PSTR(FW_REPOSITORY));
  682. lcd_wait_for_click();
  683. break;
  684. // 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
  685. }
  686. lcd_update_enable(true);
  687. }
  688. uint8_t check_printer_version()
  689. {
  690. uint8_t version_changed = 0;
  691. uint16_t printer_type = eeprom_read_word((uint16_t*)EEPROM_PRINTER_TYPE);
  692. uint16_t motherboard = eeprom_read_word((uint16_t*)EEPROM_BOARD_TYPE);
  693. if (printer_type != PRINTER_TYPE) {
  694. if (printer_type == 0xffff) eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  695. else version_changed |= 0b10;
  696. }
  697. if (motherboard != MOTHERBOARD) {
  698. if(motherboard == 0xffff) eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  699. else version_changed |= 0b01;
  700. }
  701. return version_changed;
  702. }
  703. #ifdef BOOTAPP
  704. #include "bootapp.h" //bootloader support
  705. #endif //BOOTAPP
  706. #if (LANG_MODE != 0) //secondary language support
  707. #ifdef W25X20CL
  708. // language update from external flash
  709. #define LANGBOOT_BLOCKSIZE 0x1000u
  710. #define LANGBOOT_RAMBUFFER 0x0800
  711. void update_sec_lang_from_external_flash()
  712. {
  713. if ((boot_app_magic == BOOT_APP_MAGIC) && (boot_app_flags & BOOT_APP_FLG_USER0))
  714. {
  715. uint8_t lang = boot_reserved >> 4;
  716. uint8_t state = boot_reserved & 0xf;
  717. lang_table_header_t header;
  718. uint32_t src_addr;
  719. if (lang_get_header(lang, &header, &src_addr))
  720. {
  721. fputs_P(PSTR(ESC_H(1,3) "Language update."), lcdout);
  722. for (uint8_t i = 0; i < state; i++) fputc('.', lcdout);
  723. delay(100);
  724. boot_reserved = (state + 1) | (lang << 4);
  725. if ((state * LANGBOOT_BLOCKSIZE) < header.size)
  726. {
  727. cli();
  728. uint16_t size = header.size - state * LANGBOOT_BLOCKSIZE;
  729. if (size > LANGBOOT_BLOCKSIZE) size = LANGBOOT_BLOCKSIZE;
  730. w25x20cl_rd_data(src_addr + state * LANGBOOT_BLOCKSIZE, (uint8_t*)LANGBOOT_RAMBUFFER, size);
  731. if (state == 0)
  732. {
  733. //TODO - check header integrity
  734. }
  735. bootapp_ram2flash(LANGBOOT_RAMBUFFER, _SEC_LANG_TABLE + state * LANGBOOT_BLOCKSIZE, size);
  736. }
  737. else
  738. {
  739. //TODO - check sec lang data integrity
  740. eeprom_update_byte((unsigned char *)EEPROM_LANG, LANG_ID_SEC);
  741. }
  742. }
  743. }
  744. boot_app_flags &= ~BOOT_APP_FLG_USER0;
  745. }
  746. #ifdef DEBUG_W25X20CL
  747. uint8_t lang_xflash_enum_codes(uint16_t* codes)
  748. {
  749. lang_table_header_t header;
  750. uint8_t count = 0;
  751. uint32_t addr = 0x00000;
  752. while (1)
  753. {
  754. printf_P(_n("LANGTABLE%d:"), count);
  755. w25x20cl_rd_data(addr, (uint8_t*)&header, sizeof(lang_table_header_t));
  756. if (header.magic != LANG_MAGIC)
  757. {
  758. printf_P(_n("NG!\n"));
  759. break;
  760. }
  761. printf_P(_n("OK\n"));
  762. printf_P(_n(" _lt_magic = 0x%08lx %S\n"), header.magic, (header.magic==LANG_MAGIC)?_n("OK"):_n("NA"));
  763. printf_P(_n(" _lt_size = 0x%04x (%d)\n"), header.size, header.size);
  764. printf_P(_n(" _lt_count = 0x%04x (%d)\n"), header.count, header.count);
  765. printf_P(_n(" _lt_chsum = 0x%04x\n"), header.checksum);
  766. printf_P(_n(" _lt_code = 0x%04x (%c%c)\n"), header.code, header.code >> 8, header.code & 0xff);
  767. printf_P(_n(" _lt_sign = 0x%08lx\n"), header.signature);
  768. addr += header.size;
  769. codes[count] = header.code;
  770. count ++;
  771. }
  772. return count;
  773. }
  774. void list_sec_lang_from_external_flash()
  775. {
  776. uint16_t codes[8];
  777. uint8_t count = lang_xflash_enum_codes(codes);
  778. printf_P(_n("XFlash lang count = %hhd\n"), count);
  779. }
  780. #endif //DEBUG_W25X20CL
  781. #endif //W25X20CL
  782. #endif //(LANG_MODE != 0)
  783. // "Setup" function is called by the Arduino framework on startup.
  784. // Before startup, the Timers-functions (PWM)/Analog RW and HardwareSerial provided by the Arduino-code
  785. // are initialized by the main() routine provided by the Arduino framework.
  786. void setup()
  787. {
  788. mmu_init();
  789. ultralcd_init();
  790. spi_init();
  791. lcd_splash();
  792. Sound_Init(); // also guarantee "SET_OUTPUT(BEEPER)"
  793. #ifdef W25X20CL
  794. if (!w25x20cl_init())
  795. kill(_i("External SPI flash W25X20CL not responding."));
  796. // Enter an STK500 compatible Optiboot boot loader waiting for flashing the languages to an external flash memory.
  797. optiboot_w25x20cl_enter();
  798. #endif
  799. #if (LANG_MODE != 0) //secondary language support
  800. #ifdef W25X20CL
  801. if (w25x20cl_init())
  802. update_sec_lang_from_external_flash();
  803. #endif //W25X20CL
  804. #endif //(LANG_MODE != 0)
  805. setup_killpin();
  806. setup_powerhold();
  807. farm_mode = eeprom_read_byte((uint8_t*)EEPROM_FARM_MODE);
  808. EEPROM_read_B(EEPROM_FARM_NUMBER, &farm_no);
  809. if ((farm_mode == 0xFF && farm_no == 0) || ((uint16_t)farm_no == 0xFFFF))
  810. farm_mode = false; //if farm_mode has not been stored to eeprom yet and farm number is set to zero or EEPROM is fresh, deactivate farm mode
  811. if ((uint16_t)farm_no == 0xFFFF) farm_no = 0;
  812. selectedSerialPort = eeprom_read_byte((uint8_t*)EEPROM_SECOND_SERIAL_ACTIVE);
  813. if (selectedSerialPort == 0xFF) selectedSerialPort = 0;
  814. if (farm_mode)
  815. {
  816. no_response = true; //we need confirmation by recieving PRUSA thx
  817. important_status = 8;
  818. prusa_statistics(8);
  819. selectedSerialPort = 1;
  820. #ifdef TMC2130
  821. //increased extruder current (PFW363)
  822. tmc2130_current_h[E_AXIS] = 36;
  823. tmc2130_current_r[E_AXIS] = 36;
  824. #endif //TMC2130
  825. #ifdef FILAMENT_SENSOR
  826. //disabled filament autoload (PFW360)
  827. fsensor_autoload_set(false);
  828. #endif //FILAMENT_SENSOR
  829. }
  830. MYSERIAL.begin(BAUDRATE);
  831. fdev_setup_stream(uartout, uart_putchar, NULL, _FDEV_SETUP_WRITE); //setup uart out stream
  832. #ifndef W25X20CL
  833. SERIAL_PROTOCOLLNPGM("start");
  834. #endif //W25X20CL
  835. stdout = uartout;
  836. SERIAL_ECHO_START;
  837. printf_P(PSTR(" " FW_VERSION_FULL "\n"));
  838. #ifdef DEBUG_SEC_LANG
  839. lang_table_header_t header;
  840. uint32_t src_addr = 0x00000;
  841. if (lang_get_header(1, &header, &src_addr))
  842. {
  843. //this is comparsion of some printing-methods regarding to flash space usage and code size/readability
  844. #define LT_PRINT_TEST 2
  845. // flash usage
  846. // total p.test
  847. //0 252718 t+c text code
  848. //1 253142 424 170 254
  849. //2 253040 322 164 158
  850. //3 253248 530 135 395
  851. #if (LT_PRINT_TEST==1) //not optimized printf
  852. printf_P(_n(" _src_addr = 0x%08lx\n"), src_addr);
  853. printf_P(_n(" _lt_magic = 0x%08lx %S\n"), header.magic, (header.magic==LANG_MAGIC)?_n("OK"):_n("NA"));
  854. printf_P(_n(" _lt_size = 0x%04x (%d)\n"), header.size, header.size);
  855. printf_P(_n(" _lt_count = 0x%04x (%d)\n"), header.count, header.count);
  856. printf_P(_n(" _lt_chsum = 0x%04x\n"), header.checksum);
  857. printf_P(_n(" _lt_code = 0x%04x (%c%c)\n"), header.code, header.code >> 8, header.code & 0xff);
  858. printf_P(_n(" _lt_sign = 0x%08lx\n"), header.signature);
  859. #elif (LT_PRINT_TEST==2) //optimized printf
  860. printf_P(
  861. _n(
  862. " _src_addr = 0x%08lx\n"
  863. " _lt_magic = 0x%08lx %S\n"
  864. " _lt_size = 0x%04x (%d)\n"
  865. " _lt_count = 0x%04x (%d)\n"
  866. " _lt_chsum = 0x%04x\n"
  867. " _lt_code = 0x%04x (%c%c)\n"
  868. " _lt_resv1 = 0x%08lx\n"
  869. ),
  870. src_addr,
  871. header.magic, (header.magic==LANG_MAGIC)?_n("OK"):_n("NA"),
  872. header.size, header.size,
  873. header.count, header.count,
  874. header.checksum,
  875. header.code, header.code >> 8, header.code & 0xff,
  876. header.signature
  877. );
  878. #elif (LT_PRINT_TEST==3) //arduino print/println (leading zeros not solved)
  879. MYSERIAL.print(" _src_addr = 0x");
  880. MYSERIAL.println(src_addr, 16);
  881. MYSERIAL.print(" _lt_magic = 0x");
  882. MYSERIAL.print(header.magic, 16);
  883. MYSERIAL.println((header.magic==LANG_MAGIC)?" OK":" NA");
  884. MYSERIAL.print(" _lt_size = 0x");
  885. MYSERIAL.print(header.size, 16);
  886. MYSERIAL.print(" (");
  887. MYSERIAL.print(header.size, 10);
  888. MYSERIAL.println(")");
  889. MYSERIAL.print(" _lt_count = 0x");
  890. MYSERIAL.print(header.count, 16);
  891. MYSERIAL.print(" (");
  892. MYSERIAL.print(header.count, 10);
  893. MYSERIAL.println(")");
  894. MYSERIAL.print(" _lt_chsum = 0x");
  895. MYSERIAL.println(header.checksum, 16);
  896. MYSERIAL.print(" _lt_code = 0x");
  897. MYSERIAL.print(header.code, 16);
  898. MYSERIAL.print(" (");
  899. MYSERIAL.print((char)(header.code >> 8), 0);
  900. MYSERIAL.print((char)(header.code & 0xff), 0);
  901. MYSERIAL.println(")");
  902. MYSERIAL.print(" _lt_resv1 = 0x");
  903. MYSERIAL.println(header.signature, 16);
  904. #endif //(LT_PRINT_TEST==)
  905. #undef LT_PRINT_TEST
  906. #if 0
  907. w25x20cl_rd_data(0x25ba, (uint8_t*)&block_buffer, 1024);
  908. for (uint16_t i = 0; i < 1024; i++)
  909. {
  910. if ((i % 16) == 0) printf_P(_n("%04x:"), 0x25ba+i);
  911. printf_P(_n(" %02x"), ((uint8_t*)&block_buffer)[i]);
  912. if ((i % 16) == 15) putchar('\n');
  913. }
  914. #endif
  915. uint16_t sum = 0;
  916. for (uint16_t i = 0; i < header.size; i++)
  917. sum += (uint16_t)pgm_read_byte((uint8_t*)(_SEC_LANG_TABLE + i)) << ((i & 1)?0:8);
  918. printf_P(_n("_SEC_LANG_TABLE checksum = %04x\n"), sum);
  919. sum -= header.checksum; //subtract checksum
  920. printf_P(_n("_SEC_LANG_TABLE checksum = %04x\n"), sum);
  921. sum = (sum >> 8) | ((sum & 0xff) << 8); //swap bytes
  922. if (sum == header.checksum)
  923. printf_P(_n("Checksum OK\n"), sum);
  924. else
  925. printf_P(_n("Checksum NG\n"), sum);
  926. }
  927. else
  928. printf_P(_n("lang_get_header failed!\n"));
  929. #if 0
  930. for (uint16_t i = 0; i < 1024*10; i++)
  931. {
  932. if ((i % 16) == 0) printf_P(_n("%04x:"), _SEC_LANG_TABLE+i);
  933. printf_P(_n(" %02x"), pgm_read_byte((uint8_t*)(_SEC_LANG_TABLE+i)));
  934. if ((i % 16) == 15) putchar('\n');
  935. }
  936. #endif
  937. #if 0
  938. SERIAL_ECHOLN("Reading eeprom from 0 to 100: start");
  939. for (int i = 0; i < 4096; ++i) {
  940. int b = eeprom_read_byte((unsigned char*)i);
  941. if (b != 255) {
  942. SERIAL_ECHO(i);
  943. SERIAL_ECHO(":");
  944. SERIAL_ECHO(b);
  945. SERIAL_ECHOLN("");
  946. }
  947. }
  948. SERIAL_ECHOLN("Reading eeprom from 0 to 100: done");
  949. #endif
  950. #endif //DEBUG_SEC_LANG
  951. // Check startup - does nothing if bootloader sets MCUSR to 0
  952. byte mcu = MCUSR;
  953. /* if (mcu & 1) SERIAL_ECHOLNRPGM(MSG_POWERUP);
  954. if (mcu & 2) SERIAL_ECHOLNRPGM(MSG_EXTERNAL_RESET);
  955. if (mcu & 4) SERIAL_ECHOLNRPGM(MSG_BROWNOUT_RESET);
  956. if (mcu & 8) SERIAL_ECHOLNRPGM(MSG_WATCHDOG_RESET);
  957. if (mcu & 32) SERIAL_ECHOLNRPGM(MSG_SOFTWARE_RESET);*/
  958. if (mcu & 1) puts_P(MSG_POWERUP);
  959. if (mcu & 2) puts_P(MSG_EXTERNAL_RESET);
  960. if (mcu & 4) puts_P(MSG_BROWNOUT_RESET);
  961. if (mcu & 8) puts_P(MSG_WATCHDOG_RESET);
  962. if (mcu & 32) puts_P(MSG_SOFTWARE_RESET);
  963. MCUSR = 0;
  964. //SERIAL_ECHORPGM(MSG_MARLIN);
  965. //SERIAL_ECHOLNRPGM(VERSION_STRING);
  966. #ifdef STRING_VERSION_CONFIG_H
  967. #ifdef STRING_CONFIG_H_AUTHOR
  968. SERIAL_ECHO_START;
  969. SERIAL_ECHORPGM(_n(" Last Updated: "));////MSG_CONFIGURATION_VER c=0 r=0
  970. SERIAL_ECHOPGM(STRING_VERSION_CONFIG_H);
  971. SERIAL_ECHORPGM(_n(" | Author: "));////MSG_AUTHOR c=0 r=0
  972. SERIAL_ECHOLNPGM(STRING_CONFIG_H_AUTHOR);
  973. SERIAL_ECHOPGM("Compiled: ");
  974. SERIAL_ECHOLNPGM(__DATE__);
  975. #endif
  976. #endif
  977. SERIAL_ECHO_START;
  978. SERIAL_ECHORPGM(_n(" Free Memory: "));////MSG_FREE_MEMORY c=0 r=0
  979. SERIAL_ECHO(freeMemory());
  980. SERIAL_ECHORPGM(_n(" PlannerBufferBytes: "));////MSG_PLANNER_BUFFER_BYTES c=0 r=0
  981. SERIAL_ECHOLN((int)sizeof(block_t)*BLOCK_BUFFER_SIZE);
  982. //lcd_update_enable(false); // why do we need this?? - andre
  983. // loads data from EEPROM if available else uses defaults (and resets step acceleration rate)
  984. bool previous_settings_retrieved = false;
  985. uint8_t hw_changed = check_printer_version();
  986. 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
  987. previous_settings_retrieved = Config_RetrieveSettings();
  988. }
  989. else { //printer version was changed so use default settings
  990. Config_ResetDefault();
  991. }
  992. SdFatUtil::set_stack_guard(); //writes magic number at the end of static variables to protect against overwriting static memory by stack
  993. tp_init(); // Initialize temperature loop
  994. lcd_splash(); // we need to do this again, because tp_init() kills lcd
  995. plan_init(); // Initialize planner;
  996. factory_reset();
  997. lcd_encoder_diff=0;
  998. #ifdef TMC2130
  999. uint8_t silentMode = eeprom_read_byte((uint8_t*)EEPROM_SILENT);
  1000. if (silentMode == 0xff) silentMode = 0;
  1001. tmc2130_mode = TMC2130_MODE_NORMAL;
  1002. uint8_t crashdet = eeprom_read_byte((uint8_t*)EEPROM_CRASH_DET);
  1003. if (crashdet && !farm_mode)
  1004. {
  1005. crashdet_enable();
  1006. puts_P(_N("CrashDetect ENABLED!"));
  1007. }
  1008. else
  1009. {
  1010. crashdet_disable();
  1011. puts_P(_N("CrashDetect DISABLED"));
  1012. }
  1013. #ifdef TMC2130_LINEARITY_CORRECTION
  1014. #ifdef TMC2130_LINEARITY_CORRECTION_XYZ
  1015. tmc2130_wave_fac[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_X_FAC);
  1016. tmc2130_wave_fac[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_Y_FAC);
  1017. tmc2130_wave_fac[Z_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_Z_FAC);
  1018. #endif //TMC2130_LINEARITY_CORRECTION_XYZ
  1019. tmc2130_wave_fac[E_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_WAVE_E_FAC);
  1020. if (tmc2130_wave_fac[X_AXIS] == 0xff) tmc2130_wave_fac[X_AXIS] = 0;
  1021. if (tmc2130_wave_fac[Y_AXIS] == 0xff) tmc2130_wave_fac[Y_AXIS] = 0;
  1022. if (tmc2130_wave_fac[Z_AXIS] == 0xff) tmc2130_wave_fac[Z_AXIS] = 0;
  1023. if (tmc2130_wave_fac[E_AXIS] == 0xff) tmc2130_wave_fac[E_AXIS] = 0;
  1024. #endif //TMC2130_LINEARITY_CORRECTION
  1025. #ifdef TMC2130_VARIABLE_RESOLUTION
  1026. tmc2130_mres[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_X_MRES);
  1027. tmc2130_mres[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_Y_MRES);
  1028. tmc2130_mres[Z_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_Z_MRES);
  1029. tmc2130_mres[E_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_E_MRES);
  1030. if (tmc2130_mres[X_AXIS] == 0xff) tmc2130_mres[X_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_XY);
  1031. if (tmc2130_mres[Y_AXIS] == 0xff) tmc2130_mres[Y_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_XY);
  1032. if (tmc2130_mres[Z_AXIS] == 0xff) tmc2130_mres[Z_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_Z);
  1033. if (tmc2130_mres[E_AXIS] == 0xff) tmc2130_mres[E_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_E);
  1034. eeprom_update_byte((uint8_t*)EEPROM_TMC2130_X_MRES, tmc2130_mres[X_AXIS]);
  1035. eeprom_update_byte((uint8_t*)EEPROM_TMC2130_Y_MRES, tmc2130_mres[Y_AXIS]);
  1036. eeprom_update_byte((uint8_t*)EEPROM_TMC2130_Z_MRES, tmc2130_mres[Z_AXIS]);
  1037. eeprom_update_byte((uint8_t*)EEPROM_TMC2130_E_MRES, tmc2130_mres[E_AXIS]);
  1038. #else //TMC2130_VARIABLE_RESOLUTION
  1039. tmc2130_mres[X_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_XY);
  1040. tmc2130_mres[Y_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_XY);
  1041. tmc2130_mres[Z_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_Z);
  1042. tmc2130_mres[E_AXIS] = tmc2130_usteps2mres(TMC2130_USTEPS_E);
  1043. #endif //TMC2130_VARIABLE_RESOLUTION
  1044. #endif //TMC2130
  1045. st_init(); // Initialize stepper, this enables interrupts!
  1046. #ifdef TMC2130
  1047. tmc2130_mode = silentMode?TMC2130_MODE_SILENT:TMC2130_MODE_NORMAL;
  1048. update_mode_profile();
  1049. tmc2130_init();
  1050. #endif //TMC2130
  1051. setup_photpin();
  1052. servo_init();
  1053. // Reset the machine correction matrix.
  1054. // It does not make sense to load the correction matrix until the machine is homed.
  1055. world2machine_reset();
  1056. #ifdef FILAMENT_SENSOR
  1057. fsensor_init();
  1058. #endif //FILAMENT_SENSOR
  1059. #if defined(CONTROLLERFAN_PIN) && (CONTROLLERFAN_PIN > -1)
  1060. SET_OUTPUT(CONTROLLERFAN_PIN); //Set pin used for driver cooling fan
  1061. #endif
  1062. setup_homepin();
  1063. #ifdef TMC2130
  1064. if (1) {
  1065. // try to run to zero phase before powering the Z motor.
  1066. // Move in negative direction
  1067. WRITE(Z_DIR_PIN,INVERT_Z_DIR);
  1068. // Round the current micro-micro steps to micro steps.
  1069. for (uint16_t phase = (tmc2130_rd_MSCNT(Z_AXIS) + 8) >> 4; phase > 0; -- phase) {
  1070. // Until the phase counter is reset to zero.
  1071. WRITE(Z_STEP_PIN, !INVERT_Z_STEP_PIN);
  1072. delay(2);
  1073. WRITE(Z_STEP_PIN, INVERT_Z_STEP_PIN);
  1074. delay(2);
  1075. }
  1076. }
  1077. #endif //TMC2130
  1078. #if defined(Z_AXIS_ALWAYS_ON)
  1079. enable_z();
  1080. #endif
  1081. farm_mode = eeprom_read_byte((uint8_t*)EEPROM_FARM_MODE);
  1082. EEPROM_read_B(EEPROM_FARM_NUMBER, &farm_no);
  1083. if ((farm_mode == 0xFF && farm_no == 0) || (farm_no == static_cast<int>(0xFFFF))) farm_mode = false; //if farm_mode has not been stored to eeprom yet and farm number is set to zero or EEPROM is fresh, deactivate farm mode
  1084. if (farm_no == static_cast<int>(0xFFFF)) farm_no = 0;
  1085. if (farm_mode)
  1086. {
  1087. prusa_statistics(8);
  1088. }
  1089. // Enable Toshiba FlashAir SD card / WiFi enahanced card.
  1090. card.ToshibaFlashAir_enable(eeprom_read_byte((unsigned char*)EEPROM_TOSHIBA_FLASH_AIR_COMPATIBLITY) == 1);
  1091. if (eeprom_read_dword((uint32_t*)(EEPROM_TOP - 4)) == 0x0ffffffff &&
  1092. eeprom_read_dword((uint32_t*)(EEPROM_TOP - 8)) == 0x0ffffffff) {
  1093. // Maiden startup. The firmware has been loaded and first started on a virgin RAMBo board,
  1094. // where all the EEPROM entries are set to 0x0ff.
  1095. // Once a firmware boots up, it forces at least a language selection, which changes
  1096. // EEPROM_LANG to number lower than 0x0ff.
  1097. // 1) Set a high power mode.
  1098. #ifdef TMC2130
  1099. eeprom_write_byte((uint8_t*)EEPROM_SILENT, 0);
  1100. tmc2130_mode = TMC2130_MODE_NORMAL;
  1101. #endif //TMC2130
  1102. eeprom_write_byte((uint8_t*)EEPROM_WIZARD_ACTIVE, 1); //run wizard
  1103. }
  1104. // Force SD card update. Otherwise the SD card update is done from loop() on card.checkautostart(false),
  1105. // but this times out if a blocking dialog is shown in setup().
  1106. card.initsd();
  1107. #ifdef DEBUG_SD_SPEED_TEST
  1108. if (card.cardOK)
  1109. {
  1110. uint8_t* buff = (uint8_t*)block_buffer;
  1111. uint32_t block = 0;
  1112. uint32_t sumr = 0;
  1113. uint32_t sumw = 0;
  1114. for (int i = 0; i < 1024; i++)
  1115. {
  1116. uint32_t u = micros();
  1117. bool res = card.card.readBlock(i, buff);
  1118. u = micros() - u;
  1119. if (res)
  1120. {
  1121. printf_P(PSTR("readBlock %4d 512 bytes %lu us\n"), i, u);
  1122. sumr += u;
  1123. u = micros();
  1124. res = card.card.writeBlock(i, buff);
  1125. u = micros() - u;
  1126. if (res)
  1127. {
  1128. printf_P(PSTR("writeBlock %4d 512 bytes %lu us\n"), i, u);
  1129. sumw += u;
  1130. }
  1131. else
  1132. {
  1133. printf_P(PSTR("writeBlock %4d error\n"), i);
  1134. break;
  1135. }
  1136. }
  1137. else
  1138. {
  1139. printf_P(PSTR("readBlock %4d error\n"), i);
  1140. break;
  1141. }
  1142. }
  1143. uint32_t avg_rspeed = (1024 * 1000000) / (sumr / 512);
  1144. uint32_t avg_wspeed = (1024 * 1000000) / (sumw / 512);
  1145. printf_P(PSTR("avg read speed %lu bytes/s\n"), avg_rspeed);
  1146. printf_P(PSTR("avg write speed %lu bytes/s\n"), avg_wspeed);
  1147. }
  1148. else
  1149. printf_P(PSTR("Card NG!\n"));
  1150. #endif //DEBUG_SD_SPEED_TEST
  1151. if (eeprom_read_byte((uint8_t*)EEPROM_POWER_COUNT) == 0xff) eeprom_write_byte((uint8_t*)EEPROM_POWER_COUNT, 0);
  1152. if (eeprom_read_byte((uint8_t*)EEPROM_CRASH_COUNT_X) == 0xff) eeprom_write_byte((uint8_t*)EEPROM_CRASH_COUNT_X, 0);
  1153. if (eeprom_read_byte((uint8_t*)EEPROM_CRASH_COUNT_Y) == 0xff) eeprom_write_byte((uint8_t*)EEPROM_CRASH_COUNT_Y, 0);
  1154. if (eeprom_read_byte((uint8_t*)EEPROM_FERROR_COUNT) == 0xff) eeprom_write_byte((uint8_t*)EEPROM_FERROR_COUNT, 0);
  1155. if (eeprom_read_word((uint16_t*)EEPROM_POWER_COUNT_TOT) == 0xffff) eeprom_write_word((uint16_t*)EEPROM_POWER_COUNT_TOT, 0);
  1156. if (eeprom_read_word((uint16_t*)EEPROM_CRASH_COUNT_X_TOT) == 0xffff) eeprom_write_word((uint16_t*)EEPROM_CRASH_COUNT_X_TOT, 0);
  1157. if (eeprom_read_word((uint16_t*)EEPROM_CRASH_COUNT_Y_TOT) == 0xffff) eeprom_write_word((uint16_t*)EEPROM_CRASH_COUNT_Y_TOT, 0);
  1158. if (eeprom_read_word((uint16_t*)EEPROM_FERROR_COUNT_TOT) == 0xffff) eeprom_write_word((uint16_t*)EEPROM_FERROR_COUNT_TOT, 0);
  1159. if (eeprom_read_word((uint16_t*)EEPROM_MMU_FAIL_TOT) == 0xffff) eeprom_update_word((uint16_t *)EEPROM_MMU_FAIL_TOT, 0);
  1160. if (eeprom_read_word((uint16_t*)EEPROM_MMU_LOAD_FAIL_TOT) == 0xffff) eeprom_update_word((uint16_t *)EEPROM_MMU_LOAD_FAIL_TOT, 0);
  1161. if (eeprom_read_byte((uint8_t*)EEPROM_MMU_FAIL) == 0xff) eeprom_update_byte((uint8_t *)EEPROM_MMU_FAIL, 0);
  1162. if (eeprom_read_byte((uint8_t*)EEPROM_MMU_LOAD_FAIL) == 0xff) eeprom_update_byte((uint8_t *)EEPROM_MMU_LOAD_FAIL, 0);
  1163. #ifdef SNMM
  1164. if (eeprom_read_dword((uint32_t*)EEPROM_BOWDEN_LENGTH) == 0x0ffffffff) { //bowden length used for SNMM
  1165. int _z = BOWDEN_LENGTH;
  1166. for(int i = 0; i<4; i++) EEPROM_save_B(EEPROM_BOWDEN_LENGTH + i * 2, &_z);
  1167. }
  1168. #endif
  1169. // In the future, somewhere here would one compare the current firmware version against the firmware version stored in the EEPROM.
  1170. // If they differ, an update procedure may need to be performed. At the end of this block, the current firmware version
  1171. // is being written into the EEPROM, so the update procedure will be triggered only once.
  1172. #if (LANG_MODE != 0) //secondary language support
  1173. #ifdef DEBUG_W25X20CL
  1174. W25X20CL_SPI_ENTER();
  1175. uint8_t uid[8]; // 64bit unique id
  1176. w25x20cl_rd_uid(uid);
  1177. puts_P(_n("W25X20CL UID="));
  1178. for (uint8_t i = 0; i < 8; i ++)
  1179. printf_P(PSTR("%02hhx"), uid[i]);
  1180. putchar('\n');
  1181. list_sec_lang_from_external_flash();
  1182. #endif //DEBUG_W25X20CL
  1183. // lang_reset();
  1184. if (!lang_select(eeprom_read_byte((uint8_t*)EEPROM_LANG)))
  1185. lcd_language();
  1186. #ifdef DEBUG_SEC_LANG
  1187. uint16_t sec_lang_code = lang_get_code(1);
  1188. uint16_t ui = _SEC_LANG_TABLE; //table pointer
  1189. 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);
  1190. lang_print_sec_lang(uartout);
  1191. #endif //DEBUG_SEC_LANG
  1192. #endif //(LANG_MODE != 0)
  1193. if (eeprom_read_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE) == 255) {
  1194. eeprom_write_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE, 0);
  1195. temp_cal_active = false;
  1196. } else temp_cal_active = eeprom_read_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE);
  1197. if (eeprom_read_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA) == 255) {
  1198. //eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0);
  1199. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  1200. int16_t z_shift = 0;
  1201. for (uint8_t i = 0; i < 5; i++) EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + i * 2, &z_shift);
  1202. eeprom_write_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE, 0);
  1203. temp_cal_active = false;
  1204. }
  1205. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO) == 255) {
  1206. eeprom_write_byte((uint8_t*)EEPROM_UVLO, 0);
  1207. }
  1208. if (eeprom_read_byte((uint8_t*)EEPROM_SD_SORT) == 255) {
  1209. eeprom_write_byte((uint8_t*)EEPROM_SD_SORT, 0);
  1210. }
  1211. check_babystep(); //checking if Z babystep is in allowed range
  1212. #ifdef UVLO_SUPPORT
  1213. setup_uvlo_interrupt();
  1214. #endif //UVLO_SUPPORT
  1215. #if !defined(DEBUG_DISABLE_FANCHECK) && defined(FANCHECK) && defined(TACH_1) && TACH_1 >-1
  1216. setup_fan_interrupt();
  1217. #endif //DEBUG_DISABLE_FANCHECK
  1218. #ifdef FILAMENT_SENSOR
  1219. fsensor_setup_interrupt();
  1220. #endif //FILAMENT_SENSOR
  1221. for (int i = 0; i<4; i++) EEPROM_read_B(EEPROM_BOWDEN_LENGTH + i * 2, &bowden_length[i]);
  1222. #ifndef DEBUG_DISABLE_STARTMSGS
  1223. KEEPALIVE_STATE(PAUSED_FOR_USER);
  1224. show_fw_version_warnings();
  1225. switch (hw_changed) {
  1226. //if motherboard or printer type was changed inform user as it can indicate flashing wrong firmware version
  1227. //if user confirms with knob, new hw version (printer and/or motherboard) is written to eeprom and message will be not shown next time
  1228. case(0b01):
  1229. lcd_show_fullscreen_message_and_wait_P(_i("Warning: motherboard type changed.")); ////MSG_CHANGED_MOTHERBOARD c=20 r=4
  1230. eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  1231. break;
  1232. case(0b10):
  1233. lcd_show_fullscreen_message_and_wait_P(_i("Warning: printer type changed.")); ////MSG_CHANGED_PRINTER c=20 r=4
  1234. eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  1235. break;
  1236. case(0b11):
  1237. lcd_show_fullscreen_message_and_wait_P(_i("Warning: both printer type and motherboard type changed.")); ////MSG_CHANGED_BOTH c=20 r=4
  1238. eeprom_write_word((uint16_t*)EEPROM_PRINTER_TYPE, PRINTER_TYPE);
  1239. eeprom_write_word((uint16_t*)EEPROM_BOARD_TYPE, MOTHERBOARD);
  1240. break;
  1241. default: break; //no change, show no message
  1242. }
  1243. if (!previous_settings_retrieved) {
  1244. 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=4
  1245. Config_StoreSettings();
  1246. }
  1247. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) == 1) {
  1248. lcd_wizard(WizState::Run);
  1249. }
  1250. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) == 0) { //dont show calibration status messages if wizard is currently active
  1251. if (calibration_status() == CALIBRATION_STATUS_ASSEMBLED ||
  1252. calibration_status() == CALIBRATION_STATUS_UNKNOWN ||
  1253. calibration_status() == CALIBRATION_STATUS_XYZ_CALIBRATION) {
  1254. // Reset the babystepping values, so the printer will not move the Z axis up when the babystepping is enabled.
  1255. eeprom_update_word((uint16_t*)EEPROM_BABYSTEP_Z, 0);
  1256. // Show the message.
  1257. lcd_show_fullscreen_message_and_wait_P(_T(MSG_FOLLOW_CALIBRATION_FLOW));
  1258. }
  1259. else if (calibration_status() == CALIBRATION_STATUS_LIVE_ADJUST) {
  1260. // Show the message.
  1261. lcd_show_fullscreen_message_and_wait_P(_T(MSG_BABYSTEP_Z_NOT_SET));
  1262. lcd_update_enable(true);
  1263. }
  1264. else if (calibration_status() == CALIBRATION_STATUS_CALIBRATED && temp_cal_active == true && calibration_status_pinda() == false) {
  1265. //lcd_show_fullscreen_message_and_wait_P(_i("Temperature calibration has not been run yet"));////MSG_PINDA_NOT_CALIBRATED c=20 r=4
  1266. lcd_update_enable(true);
  1267. }
  1268. else if (calibration_status() == CALIBRATION_STATUS_Z_CALIBRATION) {
  1269. // Show the message.
  1270. lcd_show_fullscreen_message_and_wait_P(_T(MSG_FOLLOW_Z_CALIBRATION_FLOW));
  1271. }
  1272. }
  1273. #if !defined (DEBUG_DISABLE_FORCE_SELFTEST) && defined (TMC2130)
  1274. if (force_selftest_if_fw_version() && calibration_status() < CALIBRATION_STATUS_ASSEMBLED) {
  1275. lcd_show_fullscreen_message_and_wait_P(_i("Selftest will be run to calibrate accurate sensorless rehoming."));////MSG_FORCE_SELFTEST c=20 r=8
  1276. update_current_firmware_version_to_eeprom();
  1277. lcd_selftest();
  1278. }
  1279. #endif //TMC2130 && !DEBUG_DISABLE_FORCE_SELFTEST
  1280. KEEPALIVE_STATE(IN_PROCESS);
  1281. #endif //DEBUG_DISABLE_STARTMSGS
  1282. lcd_update_enable(true);
  1283. lcd_clear();
  1284. lcd_update(2);
  1285. // Store the currently running firmware into an eeprom,
  1286. // so the next time the firmware gets updated, it will know from which version it has been updated.
  1287. update_current_firmware_version_to_eeprom();
  1288. #ifdef TMC2130
  1289. tmc2130_home_origin[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_X_ORIGIN);
  1290. tmc2130_home_bsteps[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_X_BSTEPS);
  1291. tmc2130_home_fsteps[X_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_X_FSTEPS);
  1292. if (tmc2130_home_origin[X_AXIS] == 0xff) tmc2130_home_origin[X_AXIS] = 0;
  1293. if (tmc2130_home_bsteps[X_AXIS] == 0xff) tmc2130_home_bsteps[X_AXIS] = 48;
  1294. if (tmc2130_home_fsteps[X_AXIS] == 0xff) tmc2130_home_fsteps[X_AXIS] = 48;
  1295. tmc2130_home_origin[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_ORIGIN);
  1296. tmc2130_home_bsteps[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_BSTEPS);
  1297. tmc2130_home_fsteps[Y_AXIS] = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_Y_FSTEPS);
  1298. if (tmc2130_home_origin[Y_AXIS] == 0xff) tmc2130_home_origin[Y_AXIS] = 0;
  1299. if (tmc2130_home_bsteps[Y_AXIS] == 0xff) tmc2130_home_bsteps[Y_AXIS] = 48;
  1300. if (tmc2130_home_fsteps[Y_AXIS] == 0xff) tmc2130_home_fsteps[Y_AXIS] = 48;
  1301. tmc2130_home_enabled = eeprom_read_byte((uint8_t*)EEPROM_TMC2130_HOME_ENABLED);
  1302. if (tmc2130_home_enabled == 0xff) tmc2130_home_enabled = 0;
  1303. #endif //TMC2130
  1304. #ifdef UVLO_SUPPORT
  1305. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO) != 0) { //previous print was terminated by UVLO
  1306. /*
  1307. if (lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_RECOVER_PRINT), false)) recover_print();
  1308. else {
  1309. eeprom_update_byte((uint8_t*)EEPROM_UVLO, 0);
  1310. lcd_update_enable(true);
  1311. lcd_update(2);
  1312. lcd_setstatuspgm(_T(WELCOME_MSG));
  1313. }
  1314. */
  1315. manage_heater(); // Update temperatures
  1316. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1317. 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))
  1318. #endif
  1319. if ( degBed() > ( (float)eeprom_read_byte((uint8_t*)EEPROM_UVLO_TARGET_BED) - AUTOMATIC_UVLO_BED_TEMP_OFFSET) ){
  1320. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1321. puts_P(_N("Automatic recovery!"));
  1322. #endif
  1323. recover_print(1);
  1324. }
  1325. else{
  1326. #ifdef DEBUG_UVLO_AUTOMATIC_RECOVER
  1327. puts_P(_N("Normal recovery!"));
  1328. #endif
  1329. if ( lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_RECOVER_PRINT), false) ) recover_print(0);
  1330. else {
  1331. eeprom_update_byte((uint8_t*)EEPROM_UVLO, 0);
  1332. lcd_update_enable(true);
  1333. lcd_update(2);
  1334. lcd_setstatuspgm(_T(WELCOME_MSG));
  1335. }
  1336. }
  1337. }
  1338. #endif //UVLO_SUPPORT
  1339. KEEPALIVE_STATE(NOT_BUSY);
  1340. #ifdef WATCHDOG
  1341. wdt_enable(WDTO_4S);
  1342. #endif //WATCHDOG
  1343. }
  1344. void trace();
  1345. #define CHUNK_SIZE 64 // bytes
  1346. #define SAFETY_MARGIN 1
  1347. char chunk[CHUNK_SIZE+SAFETY_MARGIN];
  1348. int chunkHead = 0;
  1349. void serial_read_stream() {
  1350. setAllTargetHotends(0);
  1351. setTargetBed(0);
  1352. lcd_clear();
  1353. lcd_puts_P(PSTR(" Upload in progress"));
  1354. // first wait for how many bytes we will receive
  1355. uint32_t bytesToReceive;
  1356. // receive the four bytes
  1357. char bytesToReceiveBuffer[4];
  1358. for (int i=0; i<4; i++) {
  1359. int data;
  1360. while ((data = MYSERIAL.read()) == -1) {};
  1361. bytesToReceiveBuffer[i] = data;
  1362. }
  1363. // make it a uint32
  1364. memcpy(&bytesToReceive, &bytesToReceiveBuffer, 4);
  1365. // we're ready, notify the sender
  1366. MYSERIAL.write('+');
  1367. // lock in the routine
  1368. uint32_t receivedBytes = 0;
  1369. while (prusa_sd_card_upload) {
  1370. int i;
  1371. for (i=0; i<CHUNK_SIZE; i++) {
  1372. int data;
  1373. // check if we're not done
  1374. if (receivedBytes == bytesToReceive) {
  1375. break;
  1376. }
  1377. // read the next byte
  1378. while ((data = MYSERIAL.read()) == -1) {};
  1379. receivedBytes++;
  1380. // save it to the chunk
  1381. chunk[i] = data;
  1382. }
  1383. // write the chunk to SD
  1384. card.write_command_no_newline(&chunk[0]);
  1385. // notify the sender we're ready for more data
  1386. MYSERIAL.write('+');
  1387. // for safety
  1388. manage_heater();
  1389. // check if we're done
  1390. if(receivedBytes == bytesToReceive) {
  1391. trace(); // beep
  1392. card.closefile();
  1393. prusa_sd_card_upload = false;
  1394. SERIAL_PROTOCOLLNRPGM(MSG_FILE_SAVED);
  1395. }
  1396. }
  1397. }
  1398. #ifdef HOST_KEEPALIVE_FEATURE
  1399. /**
  1400. * Output a "busy" message at regular intervals
  1401. * while the machine is not accepting commands.
  1402. */
  1403. void host_keepalive() {
  1404. if (farm_mode) return;
  1405. long ms = millis();
  1406. if (host_keepalive_interval && busy_state != NOT_BUSY) {
  1407. if ((ms - prev_busy_signal_ms) < (long)(1000L * host_keepalive_interval)) return;
  1408. switch (busy_state) {
  1409. case IN_HANDLER:
  1410. case IN_PROCESS:
  1411. SERIAL_ECHO_START;
  1412. SERIAL_ECHOLNPGM("busy: processing");
  1413. break;
  1414. case PAUSED_FOR_USER:
  1415. SERIAL_ECHO_START;
  1416. SERIAL_ECHOLNPGM("busy: paused for user");
  1417. break;
  1418. case PAUSED_FOR_INPUT:
  1419. SERIAL_ECHO_START;
  1420. SERIAL_ECHOLNPGM("busy: paused for input");
  1421. break;
  1422. default:
  1423. break;
  1424. }
  1425. }
  1426. prev_busy_signal_ms = ms;
  1427. }
  1428. #endif
  1429. // The loop() function is called in an endless loop by the Arduino framework from the default main() routine.
  1430. // Before loop(), the setup() function is called by the main() routine.
  1431. void loop()
  1432. {
  1433. KEEPALIVE_STATE(NOT_BUSY);
  1434. if ((usb_printing_counter > 0) && ((millis()-_usb_timer) > 1000))
  1435. {
  1436. is_usb_printing = true;
  1437. usb_printing_counter--;
  1438. _usb_timer = millis();
  1439. }
  1440. if (usb_printing_counter == 0)
  1441. {
  1442. is_usb_printing = false;
  1443. }
  1444. if (prusa_sd_card_upload)
  1445. {
  1446. //we read byte-by byte
  1447. serial_read_stream();
  1448. } else
  1449. {
  1450. get_command();
  1451. #ifdef SDSUPPORT
  1452. card.checkautostart(false);
  1453. #endif
  1454. if(buflen)
  1455. {
  1456. cmdbuffer_front_already_processed = false;
  1457. #ifdef SDSUPPORT
  1458. if(card.saving)
  1459. {
  1460. // Saving a G-code file onto an SD-card is in progress.
  1461. // Saving starts with M28, saving until M29 is seen.
  1462. if(strstr_P(CMDBUFFER_CURRENT_STRING, PSTR("M29")) == NULL) {
  1463. card.write_command(CMDBUFFER_CURRENT_STRING);
  1464. if(card.logging)
  1465. process_commands();
  1466. else
  1467. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  1468. } else {
  1469. card.closefile();
  1470. SERIAL_PROTOCOLLNRPGM(MSG_FILE_SAVED);
  1471. }
  1472. } else {
  1473. process_commands();
  1474. }
  1475. #else
  1476. process_commands();
  1477. #endif //SDSUPPORT
  1478. if (! cmdbuffer_front_already_processed && buflen)
  1479. {
  1480. // ptr points to the start of the block currently being processed.
  1481. // The first character in the block is the block type.
  1482. char *ptr = cmdbuffer + bufindr;
  1483. if (*ptr == CMDBUFFER_CURRENT_TYPE_SDCARD) {
  1484. // To support power panic, move the lenght of the command on the SD card to a planner buffer.
  1485. union {
  1486. struct {
  1487. char lo;
  1488. char hi;
  1489. } lohi;
  1490. uint16_t value;
  1491. } sdlen;
  1492. sdlen.value = 0;
  1493. {
  1494. // This block locks the interrupts globally for 3.25 us,
  1495. // which corresponds to a maximum repeat frequency of 307.69 kHz.
  1496. // This blocking is safe in the context of a 10kHz stepper driver interrupt
  1497. // or a 115200 Bd serial line receive interrupt, which will not trigger faster than 12kHz.
  1498. cli();
  1499. // Reset the command to something, which will be ignored by the power panic routine,
  1500. // so this buffer length will not be counted twice.
  1501. *ptr ++ = CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED;
  1502. // Extract the current buffer length.
  1503. sdlen.lohi.lo = *ptr ++;
  1504. sdlen.lohi.hi = *ptr;
  1505. // and pass it to the planner queue.
  1506. planner_add_sd_length(sdlen.value);
  1507. sei();
  1508. }
  1509. }
  1510. else if((*ptr == CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR) && !IS_SD_PRINTING){
  1511. cli();
  1512. *ptr ++ = CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED;
  1513. // and one for each command to previous block in the planner queue.
  1514. planner_add_sd_length(1);
  1515. sei();
  1516. }
  1517. // Now it is safe to release the already processed command block. If interrupted by the power panic now,
  1518. // this block's SD card length will not be counted twice as its command type has been replaced
  1519. // by CMDBUFFER_CURRENT_TYPE_TO_BE_REMOVED.
  1520. cmdqueue_pop_front();
  1521. }
  1522. host_keepalive();
  1523. }
  1524. }
  1525. //check heater every n milliseconds
  1526. manage_heater();
  1527. isPrintPaused ? manage_inactivity(true) : manage_inactivity(false);
  1528. checkHitEndstops();
  1529. lcd_update(0);
  1530. #ifdef TMC2130
  1531. tmc2130_check_overtemp();
  1532. if (tmc2130_sg_crash)
  1533. {
  1534. uint8_t crash = tmc2130_sg_crash;
  1535. tmc2130_sg_crash = 0;
  1536. // crashdet_stop_and_save_print();
  1537. switch (crash)
  1538. {
  1539. case 1: enquecommand_P((PSTR("CRASH_DETECTEDX"))); break;
  1540. case 2: enquecommand_P((PSTR("CRASH_DETECTEDY"))); break;
  1541. case 3: enquecommand_P((PSTR("CRASH_DETECTEDXY"))); break;
  1542. }
  1543. }
  1544. #endif //TMC2130
  1545. mmu_loop();
  1546. }
  1547. #define DEFINE_PGM_READ_ANY(type, reader) \
  1548. static inline type pgm_read_any(const type *p) \
  1549. { return pgm_read_##reader##_near(p); }
  1550. DEFINE_PGM_READ_ANY(float, float);
  1551. DEFINE_PGM_READ_ANY(signed char, byte);
  1552. #define XYZ_CONSTS_FROM_CONFIG(type, array, CONFIG) \
  1553. static const PROGMEM type array##_P[3] = \
  1554. { X_##CONFIG, Y_##CONFIG, Z_##CONFIG }; \
  1555. static inline type array(int axis) \
  1556. { return pgm_read_any(&array##_P[axis]); } \
  1557. type array##_ext(int axis) \
  1558. { return pgm_read_any(&array##_P[axis]); }
  1559. XYZ_CONSTS_FROM_CONFIG(float, base_min_pos, MIN_POS);
  1560. XYZ_CONSTS_FROM_CONFIG(float, base_max_pos, MAX_POS);
  1561. XYZ_CONSTS_FROM_CONFIG(float, base_home_pos, HOME_POS);
  1562. XYZ_CONSTS_FROM_CONFIG(float, max_length, MAX_LENGTH);
  1563. XYZ_CONSTS_FROM_CONFIG(float, home_retract_mm, HOME_RETRACT_MM);
  1564. XYZ_CONSTS_FROM_CONFIG(signed char, home_dir, HOME_DIR);
  1565. static void axis_is_at_home(int axis) {
  1566. current_position[axis] = base_home_pos(axis) + cs.add_homing[axis];
  1567. min_pos[axis] = base_min_pos(axis) + cs.add_homing[axis];
  1568. max_pos[axis] = base_max_pos(axis) + cs.add_homing[axis];
  1569. }
  1570. inline void set_current_to_destination() { memcpy(current_position, destination, sizeof(current_position)); }
  1571. inline void set_destination_to_current() { memcpy(destination, current_position, sizeof(destination)); }
  1572. //! @return original feedmultiply
  1573. static int setup_for_endstop_move(bool enable_endstops_now = true) {
  1574. saved_feedrate = feedrate;
  1575. int l_feedmultiply = feedmultiply;
  1576. feedmultiply = 100;
  1577. previous_millis_cmd = millis();
  1578. enable_endstops(enable_endstops_now);
  1579. return l_feedmultiply;
  1580. }
  1581. //! @param original_feedmultiply feedmultiply to restore
  1582. static void clean_up_after_endstop_move(int original_feedmultiply) {
  1583. #ifdef ENDSTOPS_ONLY_FOR_HOMING
  1584. enable_endstops(false);
  1585. #endif
  1586. feedrate = saved_feedrate;
  1587. feedmultiply = original_feedmultiply;
  1588. previous_millis_cmd = millis();
  1589. }
  1590. #ifdef ENABLE_AUTO_BED_LEVELING
  1591. #ifdef AUTO_BED_LEVELING_GRID
  1592. static void set_bed_level_equation_lsq(double *plane_equation_coefficients)
  1593. {
  1594. vector_3 planeNormal = vector_3(-plane_equation_coefficients[0], -plane_equation_coefficients[1], 1);
  1595. planeNormal.debug("planeNormal");
  1596. plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1597. //bedLevel.debug("bedLevel");
  1598. //plan_bed_level_matrix.debug("bed level before");
  1599. //vector_3 uncorrected_position = plan_get_position_mm();
  1600. //uncorrected_position.debug("position before");
  1601. vector_3 corrected_position = plan_get_position();
  1602. // corrected_position.debug("position after");
  1603. current_position[X_AXIS] = corrected_position.x;
  1604. current_position[Y_AXIS] = corrected_position.y;
  1605. current_position[Z_AXIS] = corrected_position.z;
  1606. // put the bed at 0 so we don't go below it.
  1607. current_position[Z_AXIS] = cs.zprobe_zoffset; // in the lsq we reach here after raising the extruder due to the loop structure
  1608. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1609. }
  1610. #else // not AUTO_BED_LEVELING_GRID
  1611. static void set_bed_level_equation_3pts(float z_at_pt_1, float z_at_pt_2, float z_at_pt_3) {
  1612. plan_bed_level_matrix.set_to_identity();
  1613. vector_3 pt1 = vector_3(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, z_at_pt_1);
  1614. vector_3 pt2 = vector_3(ABL_PROBE_PT_2_X, ABL_PROBE_PT_2_Y, z_at_pt_2);
  1615. vector_3 pt3 = vector_3(ABL_PROBE_PT_3_X, ABL_PROBE_PT_3_Y, z_at_pt_3);
  1616. vector_3 from_2_to_1 = (pt1 - pt2).get_normal();
  1617. vector_3 from_2_to_3 = (pt3 - pt2).get_normal();
  1618. vector_3 planeNormal = vector_3::cross(from_2_to_1, from_2_to_3).get_normal();
  1619. planeNormal = vector_3(planeNormal.x, planeNormal.y, abs(planeNormal.z));
  1620. plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1621. vector_3 corrected_position = plan_get_position();
  1622. current_position[X_AXIS] = corrected_position.x;
  1623. current_position[Y_AXIS] = corrected_position.y;
  1624. current_position[Z_AXIS] = corrected_position.z;
  1625. // put the bed at 0 so we don't go below it.
  1626. current_position[Z_AXIS] = cs.zprobe_zoffset;
  1627. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1628. }
  1629. #endif // AUTO_BED_LEVELING_GRID
  1630. static void run_z_probe() {
  1631. plan_bed_level_matrix.set_to_identity();
  1632. feedrate = homing_feedrate[Z_AXIS];
  1633. // move down until you find the bed
  1634. float zPosition = -10;
  1635. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1636. st_synchronize();
  1637. // we have to let the planner know where we are right now as it is not where we said to go.
  1638. zPosition = st_get_position_mm(Z_AXIS);
  1639. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS]);
  1640. // move up the retract distance
  1641. zPosition += home_retract_mm(Z_AXIS);
  1642. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1643. st_synchronize();
  1644. // move back down slowly to find bed
  1645. feedrate = homing_feedrate[Z_AXIS]/4;
  1646. zPosition -= home_retract_mm(Z_AXIS) * 2;
  1647. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1648. st_synchronize();
  1649. current_position[Z_AXIS] = st_get_position_mm(Z_AXIS);
  1650. // make sure the planner knows where we are as it may be a bit different than we last said to move to
  1651. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1652. }
  1653. static void do_blocking_move_to(float x, float y, float z) {
  1654. float oldFeedRate = feedrate;
  1655. feedrate = homing_feedrate[Z_AXIS];
  1656. current_position[Z_AXIS] = z;
  1657. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], feedrate/60, active_extruder);
  1658. st_synchronize();
  1659. feedrate = XY_TRAVEL_SPEED;
  1660. current_position[X_AXIS] = x;
  1661. current_position[Y_AXIS] = y;
  1662. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], feedrate/60, active_extruder);
  1663. st_synchronize();
  1664. feedrate = oldFeedRate;
  1665. }
  1666. static void do_blocking_move_relative(float offset_x, float offset_y, float offset_z) {
  1667. do_blocking_move_to(current_position[X_AXIS] + offset_x, current_position[Y_AXIS] + offset_y, current_position[Z_AXIS] + offset_z);
  1668. }
  1669. /// Probe bed height at position (x,y), returns the measured z value
  1670. static float probe_pt(float x, float y, float z_before) {
  1671. // move to right place
  1672. do_blocking_move_to(current_position[X_AXIS], current_position[Y_AXIS], z_before);
  1673. do_blocking_move_to(x - X_PROBE_OFFSET_FROM_EXTRUDER, y - Y_PROBE_OFFSET_FROM_EXTRUDER, current_position[Z_AXIS]);
  1674. run_z_probe();
  1675. float measured_z = current_position[Z_AXIS];
  1676. SERIAL_PROTOCOLRPGM(_T(MSG_BED));
  1677. SERIAL_PROTOCOLPGM(" x: ");
  1678. SERIAL_PROTOCOL(x);
  1679. SERIAL_PROTOCOLPGM(" y: ");
  1680. SERIAL_PROTOCOL(y);
  1681. SERIAL_PROTOCOLPGM(" z: ");
  1682. SERIAL_PROTOCOL(measured_z);
  1683. SERIAL_PROTOCOLPGM("\n");
  1684. return measured_z;
  1685. }
  1686. #endif // #ifdef ENABLE_AUTO_BED_LEVELING
  1687. #ifdef LIN_ADVANCE
  1688. /**
  1689. * M900: Set and/or Get advance K factor and WH/D ratio
  1690. *
  1691. * K<factor> Set advance K factor
  1692. * R<ratio> Set ratio directly (overrides WH/D)
  1693. * W<width> H<height> D<diam> Set ratio from WH/D
  1694. */
  1695. inline void gcode_M900() {
  1696. st_synchronize();
  1697. const float newK = code_seen('K') ? code_value_float() : -1;
  1698. if (newK >= 0) extruder_advance_k = newK;
  1699. float newR = code_seen('R') ? code_value_float() : -1;
  1700. if (newR < 0) {
  1701. const float newD = code_seen('D') ? code_value_float() : -1,
  1702. newW = code_seen('W') ? code_value_float() : -1,
  1703. newH = code_seen('H') ? code_value_float() : -1;
  1704. if (newD >= 0 && newW >= 0 && newH >= 0)
  1705. newR = newD ? (newW * newH) / (sq(newD * 0.5) * M_PI) : 0;
  1706. }
  1707. if (newR >= 0) advance_ed_ratio = newR;
  1708. SERIAL_ECHO_START;
  1709. SERIAL_ECHOPGM("Advance K=");
  1710. SERIAL_ECHOLN(extruder_advance_k);
  1711. SERIAL_ECHOPGM(" E/D=");
  1712. const float ratio = advance_ed_ratio;
  1713. if (ratio) SERIAL_ECHOLN(ratio); else SERIAL_ECHOLNPGM("Auto");
  1714. }
  1715. #endif // LIN_ADVANCE
  1716. bool check_commands() {
  1717. bool end_command_found = false;
  1718. while (buflen)
  1719. {
  1720. if ((code_seen("M84")) || (code_seen("M 84"))) end_command_found = true;
  1721. if (!cmdbuffer_front_already_processed)
  1722. cmdqueue_pop_front();
  1723. cmdbuffer_front_already_processed = false;
  1724. }
  1725. return end_command_found;
  1726. }
  1727. #ifdef TMC2130
  1728. bool calibrate_z_auto()
  1729. {
  1730. //lcd_display_message_fullscreen_P(_T(MSG_CALIBRATE_Z_AUTO));
  1731. lcd_clear();
  1732. lcd_puts_at_P(0,1, _T(MSG_CALIBRATE_Z_AUTO));
  1733. bool endstops_enabled = enable_endstops(true);
  1734. int axis_up_dir = -home_dir(Z_AXIS);
  1735. tmc2130_home_enter(Z_AXIS_MASK);
  1736. current_position[Z_AXIS] = 0;
  1737. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1738. set_destination_to_current();
  1739. destination[Z_AXIS] += (1.1 * max_length(Z_AXIS) * axis_up_dir);
  1740. feedrate = homing_feedrate[Z_AXIS];
  1741. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1742. st_synchronize();
  1743. // current_position[axis] = 0;
  1744. // plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1745. tmc2130_home_exit();
  1746. enable_endstops(false);
  1747. current_position[Z_AXIS] = 0;
  1748. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1749. set_destination_to_current();
  1750. destination[Z_AXIS] += 10 * axis_up_dir; //10mm up
  1751. feedrate = homing_feedrate[Z_AXIS] / 2;
  1752. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1753. st_synchronize();
  1754. enable_endstops(endstops_enabled);
  1755. current_position[Z_AXIS] = Z_MAX_POS+2.0;
  1756. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1757. return true;
  1758. }
  1759. #endif //TMC2130
  1760. void homeaxis(int axis, uint8_t cnt, uint8_t* pstep)
  1761. {
  1762. bool endstops_enabled = enable_endstops(true); //RP: endstops should be allways enabled durring homing
  1763. #define HOMEAXIS_DO(LETTER) \
  1764. ((LETTER##_MIN_PIN > -1 && LETTER##_HOME_DIR==-1) || (LETTER##_MAX_PIN > -1 && LETTER##_HOME_DIR==1))
  1765. if ((axis==X_AXIS)?HOMEAXIS_DO(X):(axis==Y_AXIS)?HOMEAXIS_DO(Y):0)
  1766. {
  1767. int axis_home_dir = home_dir(axis);
  1768. feedrate = homing_feedrate[axis];
  1769. #ifdef TMC2130
  1770. tmc2130_home_enter(X_AXIS_MASK << axis);
  1771. #endif //TMC2130
  1772. // Move away a bit, so that the print head does not touch the end position,
  1773. // and the following movement to endstop has a chance to achieve the required velocity
  1774. // for the stall guard to work.
  1775. current_position[axis] = 0;
  1776. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1777. set_destination_to_current();
  1778. // destination[axis] = 11.f;
  1779. destination[axis] = -3.f * axis_home_dir;
  1780. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1781. st_synchronize();
  1782. // Move away from the possible collision with opposite endstop with the collision detection disabled.
  1783. endstops_hit_on_purpose();
  1784. enable_endstops(false);
  1785. current_position[axis] = 0;
  1786. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1787. destination[axis] = 1. * axis_home_dir;
  1788. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1789. st_synchronize();
  1790. // Now continue to move up to the left end stop with the collision detection enabled.
  1791. enable_endstops(true);
  1792. destination[axis] = 1.1 * axis_home_dir * max_length(axis);
  1793. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1794. st_synchronize();
  1795. for (uint8_t i = 0; i < cnt; i++)
  1796. {
  1797. // Move away from the collision to a known distance from the left end stop with the collision detection disabled.
  1798. endstops_hit_on_purpose();
  1799. enable_endstops(false);
  1800. current_position[axis] = 0;
  1801. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1802. destination[axis] = -10.f * axis_home_dir;
  1803. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1804. st_synchronize();
  1805. endstops_hit_on_purpose();
  1806. // Now move left up to the collision, this time with a repeatable velocity.
  1807. enable_endstops(true);
  1808. destination[axis] = 11.f * axis_home_dir;
  1809. #ifdef TMC2130
  1810. feedrate = homing_feedrate[axis];
  1811. #else //TMC2130
  1812. feedrate = homing_feedrate[axis] / 2;
  1813. #endif //TMC2130
  1814. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1815. st_synchronize();
  1816. #ifdef TMC2130
  1817. uint16_t mscnt = tmc2130_rd_MSCNT(axis);
  1818. if (pstep) pstep[i] = mscnt >> 4;
  1819. printf_P(PSTR("%3d step=%2d mscnt=%4d\n"), i, mscnt >> 4, mscnt);
  1820. #endif //TMC2130
  1821. }
  1822. endstops_hit_on_purpose();
  1823. enable_endstops(false);
  1824. #ifdef TMC2130
  1825. uint8_t orig = tmc2130_home_origin[axis];
  1826. uint8_t back = tmc2130_home_bsteps[axis];
  1827. if (tmc2130_home_enabled && (orig <= 63))
  1828. {
  1829. tmc2130_goto_step(axis, orig, 2, 1000, tmc2130_get_res(axis));
  1830. if (back > 0)
  1831. tmc2130_do_steps(axis, back, -axis_home_dir, 1000);
  1832. }
  1833. else
  1834. tmc2130_do_steps(axis, 8, -axis_home_dir, 1000);
  1835. tmc2130_home_exit();
  1836. #endif //TMC2130
  1837. axis_is_at_home(axis);
  1838. axis_known_position[axis] = true;
  1839. // Move from minimum
  1840. #ifdef TMC2130
  1841. float dist = - axis_home_dir * 0.01f * tmc2130_home_fsteps[axis];
  1842. #else //TMC2130
  1843. float dist = - axis_home_dir * 0.01f * 64;
  1844. #endif //TMC2130
  1845. current_position[axis] -= dist;
  1846. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1847. current_position[axis] += dist;
  1848. destination[axis] = current_position[axis];
  1849. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], 0.5f*feedrate/60, active_extruder);
  1850. st_synchronize();
  1851. feedrate = 0.0;
  1852. }
  1853. else if ((axis==Z_AXIS)?HOMEAXIS_DO(Z):0)
  1854. {
  1855. #ifdef TMC2130
  1856. FORCE_HIGH_POWER_START;
  1857. #endif
  1858. int axis_home_dir = home_dir(axis);
  1859. current_position[axis] = 0;
  1860. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1861. destination[axis] = 1.5 * max_length(axis) * axis_home_dir;
  1862. feedrate = homing_feedrate[axis];
  1863. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1864. st_synchronize();
  1865. #ifdef TMC2130
  1866. if (READ(Z_TMC2130_DIAG) != 0) { //Z crash
  1867. FORCE_HIGH_POWER_END;
  1868. kill(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  1869. return;
  1870. }
  1871. #endif //TMC2130
  1872. current_position[axis] = 0;
  1873. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1874. destination[axis] = -home_retract_mm(axis) * axis_home_dir;
  1875. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1876. st_synchronize();
  1877. destination[axis] = 2*home_retract_mm(axis) * axis_home_dir;
  1878. feedrate = homing_feedrate[axis]/2 ;
  1879. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1880. st_synchronize();
  1881. #ifdef TMC2130
  1882. if (READ(Z_TMC2130_DIAG) != 0) { //Z crash
  1883. FORCE_HIGH_POWER_END;
  1884. kill(_T(MSG_BED_LEVELING_FAILED_POINT_LOW));
  1885. return;
  1886. }
  1887. #endif //TMC2130
  1888. axis_is_at_home(axis);
  1889. destination[axis] = current_position[axis];
  1890. feedrate = 0.0;
  1891. endstops_hit_on_purpose();
  1892. axis_known_position[axis] = true;
  1893. #ifdef TMC2130
  1894. FORCE_HIGH_POWER_END;
  1895. #endif
  1896. }
  1897. enable_endstops(endstops_enabled);
  1898. }
  1899. /**/
  1900. void home_xy()
  1901. {
  1902. set_destination_to_current();
  1903. homeaxis(X_AXIS);
  1904. homeaxis(Y_AXIS);
  1905. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1906. endstops_hit_on_purpose();
  1907. }
  1908. void refresh_cmd_timeout(void)
  1909. {
  1910. previous_millis_cmd = millis();
  1911. }
  1912. #ifdef FWRETRACT
  1913. void retract(bool retracting, bool swapretract = false) {
  1914. if(retracting && !retracted[active_extruder]) {
  1915. destination[X_AXIS]=current_position[X_AXIS];
  1916. destination[Y_AXIS]=current_position[Y_AXIS];
  1917. destination[Z_AXIS]=current_position[Z_AXIS];
  1918. destination[E_AXIS]=current_position[E_AXIS];
  1919. current_position[E_AXIS]+=(swapretract?retract_length_swap:cs.retract_length)*float(extrudemultiply)*0.01f;
  1920. plan_set_e_position(current_position[E_AXIS]);
  1921. float oldFeedrate = feedrate;
  1922. feedrate=cs.retract_feedrate*60;
  1923. retracted[active_extruder]=true;
  1924. prepare_move();
  1925. current_position[Z_AXIS]-=cs.retract_zlift;
  1926. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1927. prepare_move();
  1928. feedrate = oldFeedrate;
  1929. } else if(!retracting && retracted[active_extruder]) {
  1930. destination[X_AXIS]=current_position[X_AXIS];
  1931. destination[Y_AXIS]=current_position[Y_AXIS];
  1932. destination[Z_AXIS]=current_position[Z_AXIS];
  1933. destination[E_AXIS]=current_position[E_AXIS];
  1934. current_position[Z_AXIS]+=cs.retract_zlift;
  1935. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1936. current_position[E_AXIS]-=(swapretract?(retract_length_swap+retract_recover_length_swap):(cs.retract_length+cs.retract_recover_length))*float(extrudemultiply)*0.01f;
  1937. plan_set_e_position(current_position[E_AXIS]);
  1938. float oldFeedrate = feedrate;
  1939. feedrate=cs.retract_recover_feedrate*60;
  1940. retracted[active_extruder]=false;
  1941. prepare_move();
  1942. feedrate = oldFeedrate;
  1943. }
  1944. } //retract
  1945. #endif //FWRETRACT
  1946. void trace() {
  1947. //if((eSoundMode==e_SOUND_MODE_LOUD)||(eSoundMode==e_SOUND_MODE_ONCE))
  1948. tone(BEEPER, 440);
  1949. delay(25);
  1950. noTone(BEEPER);
  1951. delay(20);
  1952. }
  1953. /*
  1954. void ramming() {
  1955. // float tmp[4] = DEFAULT_MAX_FEEDRATE;
  1956. if (current_temperature[0] < 230) {
  1957. //PLA
  1958. max_feedrate[E_AXIS] = 50;
  1959. //current_position[E_AXIS] -= 8;
  1960. //plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 2100 / 60, active_extruder);
  1961. //current_position[E_AXIS] += 8;
  1962. //plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 2100 / 60, active_extruder);
  1963. current_position[E_AXIS] += 5.4;
  1964. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 2800 / 60, active_extruder);
  1965. current_position[E_AXIS] += 3.2;
  1966. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  1967. current_position[E_AXIS] += 3;
  1968. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3400 / 60, active_extruder);
  1969. st_synchronize();
  1970. max_feedrate[E_AXIS] = 80;
  1971. current_position[E_AXIS] -= 82;
  1972. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 9500 / 60, active_extruder);
  1973. max_feedrate[E_AXIS] = 50;//tmp[E_AXIS];
  1974. current_position[E_AXIS] -= 20;
  1975. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 1200 / 60, active_extruder);
  1976. current_position[E_AXIS] += 5;
  1977. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 400 / 60, active_extruder);
  1978. current_position[E_AXIS] += 5;
  1979. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 600 / 60, active_extruder);
  1980. current_position[E_AXIS] -= 10;
  1981. st_synchronize();
  1982. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 600 / 60, active_extruder);
  1983. current_position[E_AXIS] += 10;
  1984. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 600 / 60, active_extruder);
  1985. current_position[E_AXIS] -= 10;
  1986. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 800 / 60, active_extruder);
  1987. current_position[E_AXIS] += 10;
  1988. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 800 / 60, active_extruder);
  1989. current_position[E_AXIS] -= 10;
  1990. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 800 / 60, active_extruder);
  1991. st_synchronize();
  1992. }
  1993. else {
  1994. //ABS
  1995. max_feedrate[E_AXIS] = 50;
  1996. //current_position[E_AXIS] -= 8;
  1997. //plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 2100 / 60, active_extruder);
  1998. //current_position[E_AXIS] += 8;
  1999. //plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 2100 / 60, active_extruder);
  2000. current_position[E_AXIS] += 3.1;
  2001. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 2000 / 60, active_extruder);
  2002. current_position[E_AXIS] += 3.1;
  2003. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 2500 / 60, active_extruder);
  2004. current_position[E_AXIS] += 4;
  2005. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  2006. st_synchronize();
  2007. //current_position[X_AXIS] += 23; //delay
  2008. //plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 600/60, active_extruder); //delay
  2009. //current_position[X_AXIS] -= 23; //delay
  2010. //plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 600/60, active_extruder); //delay
  2011. delay(4700);
  2012. max_feedrate[E_AXIS] = 80;
  2013. current_position[E_AXIS] -= 92;
  2014. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 9900 / 60, active_extruder);
  2015. max_feedrate[E_AXIS] = 50;//tmp[E_AXIS];
  2016. current_position[E_AXIS] -= 5;
  2017. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 800 / 60, active_extruder);
  2018. current_position[E_AXIS] += 5;
  2019. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 400 / 60, active_extruder);
  2020. current_position[E_AXIS] -= 5;
  2021. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 600 / 60, active_extruder);
  2022. st_synchronize();
  2023. current_position[E_AXIS] += 5;
  2024. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 600 / 60, active_extruder);
  2025. current_position[E_AXIS] -= 5;
  2026. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 600 / 60, active_extruder);
  2027. current_position[E_AXIS] += 5;
  2028. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 600 / 60, active_extruder);
  2029. current_position[E_AXIS] -= 5;
  2030. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 600 / 60, active_extruder);
  2031. st_synchronize();
  2032. }
  2033. }
  2034. */
  2035. #ifdef TMC2130
  2036. void force_high_power_mode(bool start_high_power_section) {
  2037. uint8_t silent;
  2038. silent = eeprom_read_byte((uint8_t*)EEPROM_SILENT);
  2039. if (silent == 1) {
  2040. //we are in silent mode, set to normal mode to enable crash detection
  2041. // Wait for the planner queue to drain and for the stepper timer routine to reach an idle state.
  2042. st_synchronize();
  2043. cli();
  2044. tmc2130_mode = (start_high_power_section == true) ? TMC2130_MODE_NORMAL : TMC2130_MODE_SILENT;
  2045. update_mode_profile();
  2046. tmc2130_init();
  2047. // We may have missed a stepper timer interrupt due to the time spent in the tmc2130_init() routine.
  2048. // Be safe than sorry, reset the stepper timer before re-enabling interrupts.
  2049. st_reset_timer();
  2050. sei();
  2051. }
  2052. }
  2053. #endif //TMC2130
  2054. void gcode_G28(bool home_x_axis, bool home_y_axis, bool home_z_axis) {
  2055. gcode_G28(home_x_axis, 0, home_y_axis, 0, home_z_axis, 0, false, true);
  2056. }
  2057. 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) {
  2058. st_synchronize();
  2059. #if 0
  2060. SERIAL_ECHOPGM("G28, initial "); print_world_coordinates();
  2061. SERIAL_ECHOPGM("G28, initial "); print_physical_coordinates();
  2062. #endif
  2063. // Flag for the display update routine and to disable the print cancelation during homing.
  2064. homing_flag = true;
  2065. // Which axes should be homed?
  2066. bool home_x = home_x_axis;
  2067. bool home_y = home_y_axis;
  2068. bool home_z = home_z_axis;
  2069. // Either all X,Y,Z codes are present, or none of them.
  2070. bool home_all_axes = home_x == home_y && home_x == home_z;
  2071. if (home_all_axes)
  2072. // No X/Y/Z code provided means to home all axes.
  2073. home_x = home_y = home_z = true;
  2074. //if we are homing all axes, first move z higher to protect heatbed/steel sheet
  2075. if (home_all_axes) {
  2076. current_position[Z_AXIS] += MESH_HOME_Z_SEARCH;
  2077. feedrate = homing_feedrate[Z_AXIS];
  2078. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], feedrate / 60, active_extruder);
  2079. st_synchronize();
  2080. }
  2081. #ifdef ENABLE_AUTO_BED_LEVELING
  2082. plan_bed_level_matrix.set_to_identity(); //Reset the plane ("erase" all leveling data)
  2083. #endif //ENABLE_AUTO_BED_LEVELING
  2084. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  2085. // the planner will not perform any adjustments in the XY plane.
  2086. // Wait for the motors to stop and update the current position with the absolute values.
  2087. world2machine_revert_to_uncorrected();
  2088. // For mesh bed leveling deactivate the matrix temporarily.
  2089. // It is necessary to disable the bed leveling for the X and Y homing moves, so that the move is performed
  2090. // in a single axis only.
  2091. // In case of re-homing the X or Y axes only, the mesh bed leveling is restored after G28.
  2092. #ifdef MESH_BED_LEVELING
  2093. uint8_t mbl_was_active = mbl.active;
  2094. mbl.active = 0;
  2095. current_position[Z_AXIS] = st_get_position_mm(Z_AXIS);
  2096. #endif
  2097. // Reset baby stepping to zero, if the babystepping has already been loaded before. The babystepsTodo value will be
  2098. // consumed during the first movements following this statement.
  2099. if (home_z)
  2100. babystep_undo();
  2101. saved_feedrate = feedrate;
  2102. int l_feedmultiply = feedmultiply;
  2103. feedmultiply = 100;
  2104. previous_millis_cmd = millis();
  2105. enable_endstops(true);
  2106. memcpy(destination, current_position, sizeof(destination));
  2107. feedrate = 0.0;
  2108. #if Z_HOME_DIR > 0 // If homing away from BED do Z first
  2109. if(home_z)
  2110. homeaxis(Z_AXIS);
  2111. #endif
  2112. #ifdef QUICK_HOME
  2113. // In the quick mode, if both x and y are to be homed, a diagonal move will be performed initially.
  2114. if(home_x && home_y) //first diagonal move
  2115. {
  2116. current_position[X_AXIS] = 0;current_position[Y_AXIS] = 0;
  2117. int x_axis_home_dir = home_dir(X_AXIS);
  2118. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  2119. 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);
  2120. feedrate = homing_feedrate[X_AXIS];
  2121. if(homing_feedrate[Y_AXIS]<feedrate)
  2122. feedrate = homing_feedrate[Y_AXIS];
  2123. if (max_length(X_AXIS) > max_length(Y_AXIS)) {
  2124. feedrate *= sqrt(pow(max_length(Y_AXIS) / max_length(X_AXIS), 2) + 1);
  2125. } else {
  2126. feedrate *= sqrt(pow(max_length(X_AXIS) / max_length(Y_AXIS), 2) + 1);
  2127. }
  2128. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  2129. st_synchronize();
  2130. axis_is_at_home(X_AXIS);
  2131. axis_is_at_home(Y_AXIS);
  2132. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  2133. destination[X_AXIS] = current_position[X_AXIS];
  2134. destination[Y_AXIS] = current_position[Y_AXIS];
  2135. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  2136. feedrate = 0.0;
  2137. st_synchronize();
  2138. endstops_hit_on_purpose();
  2139. current_position[X_AXIS] = destination[X_AXIS];
  2140. current_position[Y_AXIS] = destination[Y_AXIS];
  2141. current_position[Z_AXIS] = destination[Z_AXIS];
  2142. }
  2143. #endif /* QUICK_HOME */
  2144. #ifdef TMC2130
  2145. if(home_x)
  2146. {
  2147. if (!calib)
  2148. homeaxis(X_AXIS);
  2149. else
  2150. tmc2130_home_calibrate(X_AXIS);
  2151. }
  2152. if(home_y)
  2153. {
  2154. if (!calib)
  2155. homeaxis(Y_AXIS);
  2156. else
  2157. tmc2130_home_calibrate(Y_AXIS);
  2158. }
  2159. #else //TMC2130
  2160. if(home_x) homeaxis(X_AXIS);
  2161. if(home_y) homeaxis(Y_AXIS);
  2162. #endif //TMC2130
  2163. if(home_x_axis && home_x_value != 0)
  2164. current_position[X_AXIS]=home_x_value+cs.add_homing[X_AXIS];
  2165. if(home_y_axis && home_y_value != 0)
  2166. current_position[Y_AXIS]=home_y_value+cs.add_homing[Y_AXIS];
  2167. #if Z_HOME_DIR < 0 // If homing towards BED do Z last
  2168. #ifndef Z_SAFE_HOMING
  2169. if(home_z) {
  2170. #if defined (Z_RAISE_BEFORE_HOMING) && (Z_RAISE_BEFORE_HOMING > 0)
  2171. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  2172. feedrate = max_feedrate[Z_AXIS];
  2173. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate, active_extruder);
  2174. st_synchronize();
  2175. #endif // defined (Z_RAISE_BEFORE_HOMING) && (Z_RAISE_BEFORE_HOMING > 0)
  2176. #if (defined(MESH_BED_LEVELING) && !defined(MK1BP)) // If Mesh bed leveling, move X&Y to safe position for home
  2177. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] ))
  2178. {
  2179. homeaxis(X_AXIS);
  2180. homeaxis(Y_AXIS);
  2181. }
  2182. // 1st mesh bed leveling measurement point, corrected.
  2183. world2machine_initialize();
  2184. world2machine(pgm_read_float(bed_ref_points_4), pgm_read_float(bed_ref_points_4+1), destination[X_AXIS], destination[Y_AXIS]);
  2185. world2machine_reset();
  2186. if (destination[Y_AXIS] < Y_MIN_POS)
  2187. destination[Y_AXIS] = Y_MIN_POS;
  2188. destination[Z_AXIS] = MESH_HOME_Z_SEARCH; // Set destination away from bed
  2189. feedrate = homing_feedrate[Z_AXIS]/10;
  2190. current_position[Z_AXIS] = 0;
  2191. enable_endstops(false);
  2192. #ifdef DEBUG_BUILD
  2193. SERIAL_ECHOLNPGM("plan_set_position()");
  2194. MYSERIAL.println(current_position[X_AXIS]);MYSERIAL.println(current_position[Y_AXIS]);
  2195. MYSERIAL.println(current_position[Z_AXIS]);MYSERIAL.println(current_position[E_AXIS]);
  2196. #endif
  2197. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  2198. #ifdef DEBUG_BUILD
  2199. SERIAL_ECHOLNPGM("plan_buffer_line()");
  2200. MYSERIAL.println(destination[X_AXIS]);MYSERIAL.println(destination[Y_AXIS]);
  2201. MYSERIAL.println(destination[Z_AXIS]);MYSERIAL.println(destination[E_AXIS]);
  2202. MYSERIAL.println(feedrate);MYSERIAL.println(active_extruder);
  2203. #endif
  2204. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate, active_extruder);
  2205. st_synchronize();
  2206. current_position[X_AXIS] = destination[X_AXIS];
  2207. current_position[Y_AXIS] = destination[Y_AXIS];
  2208. enable_endstops(true);
  2209. endstops_hit_on_purpose();
  2210. homeaxis(Z_AXIS);
  2211. #else // MESH_BED_LEVELING
  2212. homeaxis(Z_AXIS);
  2213. #endif // MESH_BED_LEVELING
  2214. }
  2215. #else // defined(Z_SAFE_HOMING): Z Safe mode activated.
  2216. if(home_all_axes) {
  2217. destination[X_AXIS] = round(Z_SAFE_HOMING_X_POINT - X_PROBE_OFFSET_FROM_EXTRUDER);
  2218. destination[Y_AXIS] = round(Z_SAFE_HOMING_Y_POINT - Y_PROBE_OFFSET_FROM_EXTRUDER);
  2219. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  2220. feedrate = XY_TRAVEL_SPEED/60;
  2221. current_position[Z_AXIS] = 0;
  2222. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  2223. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate, active_extruder);
  2224. st_synchronize();
  2225. current_position[X_AXIS] = destination[X_AXIS];
  2226. current_position[Y_AXIS] = destination[Y_AXIS];
  2227. homeaxis(Z_AXIS);
  2228. }
  2229. // Let's see if X and Y are homed and probe is inside bed area.
  2230. if(home_z) {
  2231. if ( (axis_known_position[X_AXIS]) && (axis_known_position[Y_AXIS]) \
  2232. && (current_position[X_AXIS]+X_PROBE_OFFSET_FROM_EXTRUDER >= X_MIN_POS) \
  2233. && (current_position[X_AXIS]+X_PROBE_OFFSET_FROM_EXTRUDER <= X_MAX_POS) \
  2234. && (current_position[Y_AXIS]+Y_PROBE_OFFSET_FROM_EXTRUDER >= Y_MIN_POS) \
  2235. && (current_position[Y_AXIS]+Y_PROBE_OFFSET_FROM_EXTRUDER <= Y_MAX_POS)) {
  2236. current_position[Z_AXIS] = 0;
  2237. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  2238. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  2239. feedrate = max_feedrate[Z_AXIS];
  2240. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate, active_extruder);
  2241. st_synchronize();
  2242. homeaxis(Z_AXIS);
  2243. } else if (!((axis_known_position[X_AXIS]) && (axis_known_position[Y_AXIS]))) {
  2244. LCD_MESSAGERPGM(MSG_POSITION_UNKNOWN);
  2245. SERIAL_ECHO_START;
  2246. SERIAL_ECHOLNRPGM(MSG_POSITION_UNKNOWN);
  2247. } else {
  2248. LCD_MESSAGERPGM(MSG_ZPROBE_OUT);
  2249. SERIAL_ECHO_START;
  2250. SERIAL_ECHOLNRPGM(MSG_ZPROBE_OUT);
  2251. }
  2252. }
  2253. #endif // Z_SAFE_HOMING
  2254. #endif // Z_HOME_DIR < 0
  2255. if(home_z_axis && home_z_value != 0)
  2256. current_position[Z_AXIS]=home_z_value+cs.add_homing[Z_AXIS];
  2257. #ifdef ENABLE_AUTO_BED_LEVELING
  2258. if(home_z)
  2259. current_position[Z_AXIS] += cs.zprobe_zoffset; //Add Z_Probe offset (the distance is negative)
  2260. #endif
  2261. // Set the planner and stepper routine positions.
  2262. // At this point the mesh bed leveling and world2machine corrections are disabled and current_position
  2263. // contains the machine coordinates.
  2264. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  2265. #ifdef ENDSTOPS_ONLY_FOR_HOMING
  2266. enable_endstops(false);
  2267. #endif
  2268. feedrate = saved_feedrate;
  2269. feedmultiply = l_feedmultiply;
  2270. previous_millis_cmd = millis();
  2271. endstops_hit_on_purpose();
  2272. #ifndef MESH_BED_LEVELING
  2273. // If MESH_BED_LEVELING is not active, then it is the original Prusa i3.
  2274. // Offer the user to load the baby step value, which has been adjusted at the previous print session.
  2275. if(card.sdprinting && eeprom_read_word((uint16_t *)EEPROM_BABYSTEP_Z))
  2276. lcd_adjust_z();
  2277. #endif
  2278. // Load the machine correction matrix
  2279. world2machine_initialize();
  2280. // and correct the current_position XY axes to match the transformed coordinate system.
  2281. world2machine_update_current();
  2282. #if (defined(MESH_BED_LEVELING) && !defined(MK1BP))
  2283. if (home_x_axis || home_y_axis || without_mbl || home_z_axis)
  2284. {
  2285. if (! home_z && mbl_was_active) {
  2286. // Re-enable the mesh bed leveling if only the X and Y axes were re-homed.
  2287. mbl.active = true;
  2288. // and re-adjust the current logical Z axis with the bed leveling offset applicable at the current XY position.
  2289. current_position[Z_AXIS] -= mbl.get_z(st_get_position_mm(X_AXIS), st_get_position_mm(Y_AXIS));
  2290. }
  2291. }
  2292. else
  2293. {
  2294. st_synchronize();
  2295. homing_flag = false;
  2296. }
  2297. #endif
  2298. if (farm_mode) { prusa_statistics(20); };
  2299. homing_flag = false;
  2300. #if 0
  2301. SERIAL_ECHOPGM("G28, final "); print_world_coordinates();
  2302. SERIAL_ECHOPGM("G28, final "); print_physical_coordinates();
  2303. SERIAL_ECHOPGM("G28, final "); print_mesh_bed_leveling_table();
  2304. #endif
  2305. }
  2306. void adjust_bed_reset()
  2307. {
  2308. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_VALID, 1);
  2309. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_LEFT, 0);
  2310. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_RIGHT, 0);
  2311. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_FRONT, 0);
  2312. eeprom_update_byte((unsigned char*)EEPROM_BED_CORRECTION_REAR, 0);
  2313. }
  2314. //! @brief Calibrate XYZ
  2315. //! @param onlyZ if true, calibrate only Z axis
  2316. //! @param verbosity_level
  2317. //! @retval true Succeeded
  2318. //! @retval false Failed
  2319. bool gcode_M45(bool onlyZ, int8_t verbosity_level)
  2320. {
  2321. bool final_result = false;
  2322. #ifdef TMC2130
  2323. FORCE_HIGH_POWER_START;
  2324. #endif // TMC2130
  2325. // Only Z calibration?
  2326. if (!onlyZ)
  2327. {
  2328. setTargetBed(0);
  2329. setAllTargetHotends(0);
  2330. adjust_bed_reset(); //reset bed level correction
  2331. }
  2332. // Disable the default update procedure of the display. We will do a modal dialog.
  2333. lcd_update_enable(false);
  2334. // Let the planner use the uncorrected coordinates.
  2335. mbl.reset();
  2336. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  2337. // the planner will not perform any adjustments in the XY plane.
  2338. // Wait for the motors to stop and update the current position with the absolute values.
  2339. world2machine_revert_to_uncorrected();
  2340. // Reset the baby step value applied without moving the axes.
  2341. babystep_reset();
  2342. // Mark all axes as in a need for homing.
  2343. memset(axis_known_position, 0, sizeof(axis_known_position));
  2344. // Home in the XY plane.
  2345. //set_destination_to_current();
  2346. int l_feedmultiply = setup_for_endstop_move();
  2347. lcd_display_message_fullscreen_P(_T(MSG_AUTO_HOME));
  2348. home_xy();
  2349. enable_endstops(false);
  2350. current_position[X_AXIS] += 5;
  2351. current_position[Y_AXIS] += 5;
  2352. 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);
  2353. st_synchronize();
  2354. // Let the user move the Z axes up to the end stoppers.
  2355. #ifdef TMC2130
  2356. if (calibrate_z_auto())
  2357. {
  2358. #else //TMC2130
  2359. if (lcd_calibrate_z_end_stop_manual(onlyZ))
  2360. {
  2361. #endif //TMC2130
  2362. lcd_show_fullscreen_message_and_wait_P(_T(MSG_CONFIRM_NOZZLE_CLEAN));
  2363. if(onlyZ){
  2364. lcd_display_message_fullscreen_P(_T(MSG_MEASURE_BED_REFERENCE_HEIGHT_LINE1));
  2365. lcd_set_cursor(0, 3);
  2366. lcd_print(1);
  2367. lcd_puts_P(_T(MSG_MEASURE_BED_REFERENCE_HEIGHT_LINE2));
  2368. }else{
  2369. //lcd_show_fullscreen_message_and_wait_P(_T(MSG_PAPER));
  2370. lcd_display_message_fullscreen_P(_T(MSG_FIND_BED_OFFSET_AND_SKEW_LINE1));
  2371. lcd_set_cursor(0, 2);
  2372. lcd_print(1);
  2373. lcd_puts_P(_T(MSG_FIND_BED_OFFSET_AND_SKEW_LINE2));
  2374. }
  2375. refresh_cmd_timeout();
  2376. #ifndef STEEL_SHEET
  2377. if (((degHotend(0) > MAX_HOTEND_TEMP_CALIBRATION) || (degBed() > MAX_BED_TEMP_CALIBRATION)) && (!onlyZ))
  2378. {
  2379. lcd_wait_for_cool_down();
  2380. }
  2381. #endif //STEEL_SHEET
  2382. if(!onlyZ)
  2383. {
  2384. KEEPALIVE_STATE(PAUSED_FOR_USER);
  2385. #ifdef STEEL_SHEET
  2386. bool result = lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_STEEL_SHEET_CHECK), false, false);
  2387. if(result) lcd_show_fullscreen_message_and_wait_P(_T(MSG_REMOVE_STEEL_SHEET));
  2388. #endif //STEEL_SHEET
  2389. lcd_show_fullscreen_message_and_wait_P(_T(MSG_PAPER));
  2390. KEEPALIVE_STATE(IN_HANDLER);
  2391. lcd_display_message_fullscreen_P(_T(MSG_FIND_BED_OFFSET_AND_SKEW_LINE1));
  2392. lcd_set_cursor(0, 2);
  2393. lcd_print(1);
  2394. lcd_puts_P(_T(MSG_FIND_BED_OFFSET_AND_SKEW_LINE2));
  2395. }
  2396. bool endstops_enabled = enable_endstops(false);
  2397. current_position[Z_AXIS] -= 1; //move 1mm down with disabled endstop
  2398. 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);
  2399. st_synchronize();
  2400. // Move the print head close to the bed.
  2401. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2402. enable_endstops(true);
  2403. #ifdef TMC2130
  2404. tmc2130_home_enter(Z_AXIS_MASK);
  2405. #endif //TMC2130
  2406. 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);
  2407. st_synchronize();
  2408. #ifdef TMC2130
  2409. tmc2130_home_exit();
  2410. #endif //TMC2130
  2411. enable_endstops(endstops_enabled);
  2412. if (st_get_position_mm(Z_AXIS) == MESH_HOME_Z_SEARCH)
  2413. {
  2414. if (onlyZ)
  2415. {
  2416. clean_up_after_endstop_move(l_feedmultiply);
  2417. // Z only calibration.
  2418. // Load the machine correction matrix
  2419. world2machine_initialize();
  2420. // and correct the current_position to match the transformed coordinate system.
  2421. world2machine_update_current();
  2422. //FIXME
  2423. bool result = sample_mesh_and_store_reference();
  2424. if (result)
  2425. {
  2426. if (calibration_status() == CALIBRATION_STATUS_Z_CALIBRATION)
  2427. // Shipped, the nozzle height has been set already. The user can start printing now.
  2428. calibration_status_store(CALIBRATION_STATUS_CALIBRATED);
  2429. final_result = true;
  2430. // babystep_apply();
  2431. }
  2432. }
  2433. else
  2434. {
  2435. // Reset the baby step value and the baby step applied flag.
  2436. calibration_status_store(CALIBRATION_STATUS_XYZ_CALIBRATION);
  2437. eeprom_update_word((uint16_t*)EEPROM_BABYSTEP_Z, 0);
  2438. // Complete XYZ calibration.
  2439. uint8_t point_too_far_mask = 0;
  2440. BedSkewOffsetDetectionResultType result = find_bed_offset_and_skew(verbosity_level, point_too_far_mask);
  2441. clean_up_after_endstop_move(l_feedmultiply);
  2442. // Print head up.
  2443. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2444. 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);
  2445. st_synchronize();
  2446. //#ifndef NEW_XYZCAL
  2447. if (result >= 0)
  2448. {
  2449. #ifdef HEATBED_V2
  2450. sample_z();
  2451. #else //HEATBED_V2
  2452. point_too_far_mask = 0;
  2453. // Second half: The fine adjustment.
  2454. // Let the planner use the uncorrected coordinates.
  2455. mbl.reset();
  2456. world2machine_reset();
  2457. // Home in the XY plane.
  2458. int l_feedmultiply = setup_for_endstop_move();
  2459. home_xy();
  2460. result = improve_bed_offset_and_skew(1, verbosity_level, point_too_far_mask);
  2461. clean_up_after_endstop_move(l_feedmultiply);
  2462. // Print head up.
  2463. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2464. 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);
  2465. st_synchronize();
  2466. // if (result >= 0) babystep_apply();
  2467. #endif //HEATBED_V2
  2468. }
  2469. //#endif //NEW_XYZCAL
  2470. lcd_update_enable(true);
  2471. lcd_update(2);
  2472. lcd_bed_calibration_show_result(result, point_too_far_mask);
  2473. if (result >= 0)
  2474. {
  2475. // Calibration valid, the machine should be able to print. Advise the user to run the V2Calibration.gcode.
  2476. calibration_status_store(CALIBRATION_STATUS_LIVE_ADJUST);
  2477. if (eeprom_read_byte((uint8_t*)EEPROM_WIZARD_ACTIVE) != 1) lcd_show_fullscreen_message_and_wait_P(_T(MSG_BABYSTEP_Z_NOT_SET));
  2478. final_result = true;
  2479. }
  2480. }
  2481. #ifdef TMC2130
  2482. tmc2130_home_exit();
  2483. #endif
  2484. }
  2485. else
  2486. {
  2487. lcd_show_fullscreen_message_and_wait_P(PSTR("Calibration failed! Check the axes and run again."));
  2488. final_result = false;
  2489. }
  2490. }
  2491. else
  2492. {
  2493. // Timeouted.
  2494. }
  2495. lcd_update_enable(true);
  2496. #ifdef TMC2130
  2497. FORCE_HIGH_POWER_END;
  2498. #endif // TMC2130
  2499. return final_result;
  2500. }
  2501. void gcode_M114()
  2502. {
  2503. SERIAL_PROTOCOLPGM("X:");
  2504. SERIAL_PROTOCOL(current_position[X_AXIS]);
  2505. SERIAL_PROTOCOLPGM(" Y:");
  2506. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  2507. SERIAL_PROTOCOLPGM(" Z:");
  2508. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  2509. SERIAL_PROTOCOLPGM(" E:");
  2510. SERIAL_PROTOCOL(current_position[E_AXIS]);
  2511. SERIAL_PROTOCOLRPGM(_n(" Count X: "));////MSG_COUNT_X c=0 r=0
  2512. SERIAL_PROTOCOL(float(st_get_position(X_AXIS)) / cs.axis_steps_per_unit[X_AXIS]);
  2513. SERIAL_PROTOCOLPGM(" Y:");
  2514. SERIAL_PROTOCOL(float(st_get_position(Y_AXIS)) / cs.axis_steps_per_unit[Y_AXIS]);
  2515. SERIAL_PROTOCOLPGM(" Z:");
  2516. SERIAL_PROTOCOL(float(st_get_position(Z_AXIS)) / cs.axis_steps_per_unit[Z_AXIS]);
  2517. SERIAL_PROTOCOLPGM(" E:");
  2518. SERIAL_PROTOCOL(float(st_get_position(E_AXIS)) / cs.axis_steps_per_unit[E_AXIS]);
  2519. SERIAL_PROTOCOLLN("");
  2520. }
  2521. static void gcode_M600(bool automatic, float x_position, float y_position, float z_shift, float e_shift, float /*e_shift_late*/)
  2522. {
  2523. st_synchronize();
  2524. float lastpos[4];
  2525. if (farm_mode)
  2526. {
  2527. prusa_statistics(22);
  2528. }
  2529. //First backup current position and settings
  2530. int feedmultiplyBckp = feedmultiply;
  2531. float HotendTempBckp = degTargetHotend(active_extruder);
  2532. int fanSpeedBckp = fanSpeed;
  2533. lastpos[X_AXIS] = current_position[X_AXIS];
  2534. lastpos[Y_AXIS] = current_position[Y_AXIS];
  2535. lastpos[Z_AXIS] = current_position[Z_AXIS];
  2536. lastpos[E_AXIS] = current_position[E_AXIS];
  2537. //Retract E
  2538. current_position[E_AXIS] += e_shift;
  2539. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS],
  2540. current_position[E_AXIS], FILAMENTCHANGE_RFEED, active_extruder);
  2541. st_synchronize();
  2542. //Lift Z
  2543. current_position[Z_AXIS] += z_shift;
  2544. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS],
  2545. current_position[E_AXIS], FILAMENTCHANGE_ZFEED, active_extruder);
  2546. st_synchronize();
  2547. //Move XY to side
  2548. current_position[X_AXIS] = x_position;
  2549. current_position[Y_AXIS] = y_position;
  2550. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS],
  2551. current_position[E_AXIS], FILAMENTCHANGE_XYFEED, active_extruder);
  2552. st_synchronize();
  2553. //Beep, manage nozzle heater and wait for user to start unload filament
  2554. if(!mmu_enabled) M600_wait_for_user(HotendTempBckp);
  2555. lcd_change_fil_state = 0;
  2556. // Unload filament
  2557. if (mmu_enabled) extr_unload(); //unload just current filament for multimaterial printers (used also in M702)
  2558. else unload_filament(); //unload filament for single material (used also in M702)
  2559. //finish moves
  2560. st_synchronize();
  2561. if (!mmu_enabled)
  2562. {
  2563. KEEPALIVE_STATE(PAUSED_FOR_USER);
  2564. lcd_change_fil_state = lcd_show_fullscreen_message_yes_no_and_wait_P(_i("Was filament unload successful?"),
  2565. false, true); ////MSG_UNLOAD_SUCCESSFUL c=20 r=2
  2566. if (lcd_change_fil_state == 0)
  2567. {
  2568. lcd_clear();
  2569. lcd_set_cursor(0, 2);
  2570. lcd_puts_P(_T(MSG_PLEASE_WAIT));
  2571. current_position[X_AXIS] -= 100;
  2572. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS],
  2573. current_position[E_AXIS], FILAMENTCHANGE_XYFEED, active_extruder);
  2574. st_synchronize();
  2575. lcd_show_fullscreen_message_and_wait_P(_i("Please open idler and remove filament manually."));////MSG_CHECK_IDLER c=20 r=4
  2576. }
  2577. }
  2578. if (mmu_enabled)
  2579. {
  2580. if (!automatic) {
  2581. 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
  2582. mmu_M600_wait_and_beep();
  2583. if (saved_printing) {
  2584. lcd_clear();
  2585. lcd_set_cursor(0, 2);
  2586. lcd_puts_P(_T(MSG_PLEASE_WAIT));
  2587. mmu_command(MMU_CMD_R0);
  2588. manage_response(false, false);
  2589. }
  2590. }
  2591. mmu_M600_load_filament(automatic);
  2592. }
  2593. else
  2594. M600_load_filament();
  2595. if (!automatic) M600_check_state();
  2596. lcd_update_enable(true);
  2597. //Not let's go back to print
  2598. fanSpeed = fanSpeedBckp;
  2599. //Feed a little of filament to stabilize pressure
  2600. if (!automatic)
  2601. {
  2602. current_position[E_AXIS] += FILAMENTCHANGE_RECFEED;
  2603. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS],
  2604. current_position[E_AXIS], FILAMENTCHANGE_EXFEED, active_extruder);
  2605. }
  2606. //Move XY back
  2607. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS],
  2608. FILAMENTCHANGE_XYFEED, active_extruder);
  2609. st_synchronize();
  2610. //Move Z back
  2611. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], lastpos[Z_AXIS], current_position[E_AXIS],
  2612. FILAMENTCHANGE_ZFEED, active_extruder);
  2613. st_synchronize();
  2614. //Set E position to original
  2615. plan_set_e_position(lastpos[E_AXIS]);
  2616. memcpy(current_position, lastpos, sizeof(lastpos));
  2617. memcpy(destination, current_position, sizeof(current_position));
  2618. //Recover feed rate
  2619. feedmultiply = feedmultiplyBckp;
  2620. char cmd[9];
  2621. sprintf_P(cmd, PSTR("M220 S%i"), feedmultiplyBckp);
  2622. enquecommand(cmd);
  2623. lcd_setstatuspgm(_T(WELCOME_MSG));
  2624. custom_message_type = CUSTOM_MSG_TYPE_STATUS;
  2625. }
  2626. void gcode_M701()
  2627. {
  2628. printf_P(PSTR("gcode_M701 begin\n"));
  2629. if (mmu_enabled)
  2630. {
  2631. extr_adj(tmp_extruder);//loads current extruder
  2632. mmu_extruder = tmp_extruder;
  2633. }
  2634. else
  2635. {
  2636. enable_z();
  2637. custom_message_type = CUSTOM_MSG_TYPE_F_LOAD;
  2638. #ifdef FSENSOR_QUALITY
  2639. fsensor_oq_meassure_start(40);
  2640. #endif //FSENSOR_QUALITY
  2641. lcd_setstatuspgm(_T(MSG_LOADING_FILAMENT));
  2642. current_position[E_AXIS] += 40;
  2643. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 400 / 60, active_extruder); //fast sequence
  2644. st_synchronize();
  2645. if (current_position[Z_AXIS] < 20) current_position[Z_AXIS] += 30;
  2646. current_position[E_AXIS] += 30;
  2647. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 400 / 60, active_extruder); //fast sequence
  2648. load_filament_final_feed(); //slow sequence
  2649. st_synchronize();
  2650. if((eSoundMode==e_SOUND_MODE_LOUD)||(eSoundMode==e_SOUND_MODE_ONCE)) tone(BEEPER, 500);
  2651. delay_keep_alive(50);
  2652. noTone(BEEPER);
  2653. if (!farm_mode && loading_flag) {
  2654. lcd_load_filament_color_check();
  2655. }
  2656. lcd_update_enable(true);
  2657. lcd_update(2);
  2658. lcd_setstatuspgm(_T(WELCOME_MSG));
  2659. disable_z();
  2660. loading_flag = false;
  2661. custom_message_type = CUSTOM_MSG_TYPE_STATUS;
  2662. #ifdef FSENSOR_QUALITY
  2663. fsensor_oq_meassure_stop();
  2664. if (!fsensor_oq_result())
  2665. {
  2666. bool disable = lcd_show_fullscreen_message_yes_no_and_wait_P(_i("Fil. sensor response is poor, disable it?"), false, true);
  2667. lcd_update_enable(true);
  2668. lcd_update(2);
  2669. if (disable)
  2670. fsensor_disable();
  2671. }
  2672. #endif //FSENSOR_QUALITY
  2673. }
  2674. }
  2675. /**
  2676. * @brief Get serial number from 32U2 processor
  2677. *
  2678. * Typical format of S/N is:CZPX0917X003XC13518
  2679. *
  2680. * Command operates only in farm mode, if not in farm mode, "Not in farm mode." is written to MYSERIAL.
  2681. *
  2682. * Send command ;S to serial port 0 to retrieve serial number stored in 32U2 processor,
  2683. * reply is transmitted to serial port 1 character by character.
  2684. * Operation takes typically 23 ms. If the retransmit is not finished until 100 ms,
  2685. * it is interrupted, so less, or no characters are retransmitted, only newline character is send
  2686. * in any case.
  2687. */
  2688. static void gcode_PRUSA_SN()
  2689. {
  2690. if (farm_mode) {
  2691. selectedSerialPort = 0;
  2692. putchar(';');
  2693. putchar('S');
  2694. int numbersRead = 0;
  2695. ShortTimer timeout;
  2696. timeout.start();
  2697. while (numbersRead < 19) {
  2698. while (MSerial.available() > 0) {
  2699. uint8_t serial_char = MSerial.read();
  2700. selectedSerialPort = 1;
  2701. putchar(serial_char);
  2702. numbersRead++;
  2703. selectedSerialPort = 0;
  2704. }
  2705. if (timeout.expired(100u)) break;
  2706. }
  2707. selectedSerialPort = 1;
  2708. putchar('\n');
  2709. #if 0
  2710. for (int b = 0; b < 3; b++) {
  2711. tone(BEEPER, 110);
  2712. delay(50);
  2713. noTone(BEEPER);
  2714. delay(50);
  2715. }
  2716. #endif
  2717. } else {
  2718. puts_P(_N("Not in farm mode."));
  2719. }
  2720. }
  2721. #ifdef BACKLASH_X
  2722. extern uint8_t st_backlash_x;
  2723. #endif //BACKLASH_X
  2724. #ifdef BACKLASH_Y
  2725. extern uint8_t st_backlash_y;
  2726. #endif //BACKLASH_Y
  2727. //! @brief Parse and process commands
  2728. //!
  2729. //! look here for descriptions of G-codes: http://linuxcnc.org/handbook/gcode/g-code.html
  2730. //! http://objects.reprap.org/wiki/Mendel_User_Manual:_RepRapGCodes
  2731. //!
  2732. //! Implemented Codes
  2733. //! -------------------
  2734. //!
  2735. //!@n PRUSA CODES
  2736. //!@n P F - Returns FW versions
  2737. //!@n P R - Returns revision of printer
  2738. //!
  2739. //!@n G0 -> G1
  2740. //!@n G1 - Coordinated Movement X Y Z E
  2741. //!@n G2 - CW ARC
  2742. //!@n G3 - CCW ARC
  2743. //!@n G4 - Dwell S<seconds> or P<milliseconds>
  2744. //!@n G10 - retract filament according to settings of M207
  2745. //!@n G11 - retract recover filament according to settings of M208
  2746. //!@n G28 - Home all Axis
  2747. //!@n G29 - Detailed Z-Probe, probes the bed at 3 or more points. Will fail if you haven't homed yet.
  2748. //!@n G30 - Single Z Probe, probes bed at current XY location.
  2749. //!@n G31 - Dock sled (Z_PROBE_SLED only)
  2750. //!@n G32 - Undock sled (Z_PROBE_SLED only)
  2751. //!@n G80 - Automatic mesh bed leveling
  2752. //!@n G81 - Print bed profile
  2753. //!@n G90 - Use Absolute Coordinates
  2754. //!@n G91 - Use Relative Coordinates
  2755. //!@n G92 - Set current position to coordinates given
  2756. //!
  2757. //!@n M Codes
  2758. //!@n M0 - Unconditional stop - Wait for user to press a button on the LCD
  2759. //!@n M1 - Same as M0
  2760. //!@n M17 - Enable/Power all stepper motors
  2761. //!@n M18 - Disable all stepper motors; same as M84
  2762. //!@n M20 - List SD card
  2763. //!@n M21 - Init SD card
  2764. //!@n M22 - Release SD card
  2765. //!@n M23 - Select SD file (M23 filename.g)
  2766. //!@n M24 - Start/resume SD print
  2767. //!@n M25 - Pause SD print
  2768. //!@n M26 - Set SD position in bytes (M26 S12345)
  2769. //!@n M27 - Report SD print status
  2770. //!@n M28 - Start SD write (M28 filename.g)
  2771. //!@n M29 - Stop SD write
  2772. //!@n M30 - Delete file from SD (M30 filename.g)
  2773. //!@n M31 - Output time since last M109 or SD card start to serial
  2774. //!@n M32 - Select file and start SD print (Can be used _while_ printing from SD card files):
  2775. //! syntax "M32 /path/filename#", or "M32 S<startpos bytes> !filename#"
  2776. //! Call gcode file : "M32 P !filename#" and return to caller file after finishing (similar to #include).
  2777. //! The '#' is necessary when calling from within sd files, as it stops buffer prereading
  2778. //!@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.
  2779. //!@n M73 - Show percent done and print time remaining
  2780. //!@n M80 - Turn on Power Supply
  2781. //!@n M81 - Turn off Power Supply
  2782. //!@n M82 - Set E codes absolute (default)
  2783. //!@n M83 - Set E codes relative while in Absolute Coordinates (G90) mode
  2784. //!@n M84 - Disable steppers until next move,
  2785. //! or use S<seconds> to specify an inactivity timeout, after which the steppers will be disabled. S0 to disable the timeout.
  2786. //!@n M85 - Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
  2787. //!@n M86 - Set safety timer expiration time with parameter S<seconds>; M86 S0 will disable safety timer
  2788. //!@n M92 - Set axis_steps_per_unit - same syntax as G92
  2789. //!@n M104 - Set extruder target temp
  2790. //!@n M105 - Read current temp
  2791. //!@n M106 - Fan on
  2792. //!@n M107 - Fan off
  2793. //!@n M109 - Sxxx Wait for extruder current temp to reach target temp. Waits only when heating
  2794. //! Rxxx Wait for extruder current temp to reach target temp. Waits when heating and cooling
  2795. //! IF AUTOTEMP is enabled, S<mintemp> B<maxtemp> F<factor>. Exit autotemp by any M109 without F
  2796. //!@n M112 - Emergency stop
  2797. //!@n M113 - Get or set the timeout interval for Host Keepalive "busy" messages
  2798. //!@n M114 - Output current position to serial port
  2799. //!@n M115 - Capabilities string
  2800. //!@n M117 - display message
  2801. //!@n M119 - Output Endstop status to serial port
  2802. //!@n M126 - Solenoid Air Valve Open (BariCUDA support by jmil)
  2803. //!@n M127 - Solenoid Air Valve Closed (BariCUDA vent to atmospheric pressure by jmil)
  2804. //!@n M128 - EtoP Open (BariCUDA EtoP = electricity to air pressure transducer by jmil)
  2805. //!@n M129 - EtoP Closed (BariCUDA EtoP = electricity to air pressure transducer by jmil)
  2806. //!@n M140 - Set bed target temp
  2807. //!@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.
  2808. //!@n M190 - Sxxx Wait for bed current temp to reach target temp. Waits only when heating
  2809. //! Rxxx Wait for bed current temp to reach target temp. Waits when heating and cooling
  2810. //!@n M200 D<millimeters>- set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).
  2811. //!@n M201 - Set max acceleration in units/s^2 for print moves (M201 X1000 Y1000)
  2812. //!@n M202 - Set max acceleration in units/s^2 for travel moves (M202 X1000 Y1000) Unused in Marlin!!
  2813. //!@n M203 - Set maximum feedrate that your machine can sustain (M203 X200 Y200 Z300 E10000) in mm/sec
  2814. //!@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
  2815. //!@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
  2816. //!@n M206 - set additional homing offset
  2817. //!@n M207 - set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop], stays in mm regardless of M200 setting
  2818. //!@n M208 - set recover=unretract length S[positive mm surplus to the M207 S*] F[feedrate mm/sec]
  2819. //!@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.
  2820. //!@n M218 - set hotend offset (in mm): T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  2821. //!@n M220 S<factor in percent>- set speed factor override percentage
  2822. //!@n M221 S<factor in percent>- set extrude factor override percentage
  2823. //!@n M226 P<pin number> S<pin state>- Wait until the specified pin reaches the state required
  2824. //!@n M240 - Trigger a camera to take a photograph
  2825. //!@n M250 - Set LCD contrast C<contrast value> (value 0..63)
  2826. //!@n M280 - set servo position absolute. P: servo index, S: angle or microseconds
  2827. //!@n M300 - Play beep sound S<frequency Hz> P<duration ms>
  2828. //!@n M301 - Set PID parameters P I and D
  2829. //!@n M302 - Allow cold extrudes, or set the minimum extrude S<temperature>.
  2830. //!@n M303 - PID relay autotune S<temperature> sets the target temperature. (default target temperature = 150C)
  2831. //!@n M304 - Set bed PID parameters P I and D
  2832. //!@n M400 - Finish all moves
  2833. //!@n M401 - Lower z-probe if present
  2834. //!@n M402 - Raise z-probe if present
  2835. //!@n M404 - N<dia in mm> Enter the nominal filament width (3mm, 1.75mm ) or will display nominal filament width without parameters
  2836. //!@n M405 - Turn on Filament Sensor extrusion control. Optional D<delay in cm> to set delay in centimeters between sensor and extruder
  2837. //!@n M406 - Turn off Filament Sensor extrusion control
  2838. //!@n M407 - Displays measured filament diameter
  2839. //!@n M500 - stores parameters in EEPROM
  2840. //!@n M501 - reads parameters from EEPROM (if you need reset them after you changed them temporarily).
  2841. //!@n M502 - reverts to the default "factory settings". You still need to store them in EEPROM afterwards if you want to.
  2842. //!@n M503 - print the current settings (from memory not from EEPROM)
  2843. //!@n M509 - force language selection on next restart
  2844. //!@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)
  2845. //!@n M600 - Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  2846. //!@n M605 - Set dual x-carriage movement mode: S<mode> [ X<duplication x-offset> R<duplication temp offset> ]
  2847. //!@n M860 - Wait for PINDA thermistor to reach target temperature.
  2848. //!@n M861 - Set / Read PINDA temperature compensation offsets
  2849. //!@n M900 - Set LIN_ADVANCE options, if enabled. See Configuration_adv.h for details.
  2850. //!@n M907 - Set digital trimpot motor current using axis codes.
  2851. //!@n M908 - Control digital trimpot directly.
  2852. //!@n M350 - Set microstepping mode.
  2853. //!@n M351 - Toggle MS1 MS2 pins directly.
  2854. //!
  2855. //!@n M928 - Start SD logging (M928 filename.g) - ended by M29
  2856. //!@n M999 - Restart after being stopped by error
  2857. void process_commands()
  2858. {
  2859. if (!buflen) return; //empty command
  2860. #ifdef FILAMENT_RUNOUT_SUPPORT
  2861. SET_INPUT(FR_SENS);
  2862. #endif
  2863. #ifdef CMDBUFFER_DEBUG
  2864. SERIAL_ECHOPGM("Processing a GCODE command: ");
  2865. SERIAL_ECHO(cmdbuffer+bufindr+CMDHDRSIZE);
  2866. SERIAL_ECHOLNPGM("");
  2867. SERIAL_ECHOPGM("In cmdqueue: ");
  2868. SERIAL_ECHO(buflen);
  2869. SERIAL_ECHOLNPGM("");
  2870. #endif /* CMDBUFFER_DEBUG */
  2871. unsigned long codenum; //throw away variable
  2872. char *starpos = NULL;
  2873. #ifdef ENABLE_AUTO_BED_LEVELING
  2874. float x_tmp, y_tmp, z_tmp, real_z;
  2875. #endif
  2876. // PRUSA GCODES
  2877. KEEPALIVE_STATE(IN_HANDLER);
  2878. #ifdef SNMM
  2879. float tmp_motor[3] = DEFAULT_PWM_MOTOR_CURRENT;
  2880. float tmp_motor_loud[3] = DEFAULT_PWM_MOTOR_CURRENT_LOUD;
  2881. int8_t SilentMode;
  2882. #endif
  2883. if (code_seen("M117")) { //moved to highest priority place to be able to to print strings which includes "G", "PRUSA" and "^"
  2884. starpos = (strchr(strchr_pointer + 5, '*'));
  2885. if (starpos != NULL)
  2886. *(starpos) = '\0';
  2887. lcd_setstatus(strchr_pointer + 5);
  2888. }
  2889. #ifdef TMC2130
  2890. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("CRASH_"), 6) == 0)
  2891. {
  2892. if(code_seen("CRASH_DETECTED")) //! CRASH_DETECTED
  2893. {
  2894. uint8_t mask = 0;
  2895. if (code_seen('X')) mask |= X_AXIS_MASK;
  2896. if (code_seen('Y')) mask |= Y_AXIS_MASK;
  2897. crashdet_detected(mask);
  2898. }
  2899. else if(code_seen("CRASH_RECOVER")) //! CRASH_RECOVER
  2900. crashdet_recover();
  2901. else if(code_seen("CRASH_CANCEL")) //! CRASH_CANCEL
  2902. crashdet_cancel();
  2903. }
  2904. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("TMC_"), 4) == 0)
  2905. {
  2906. if (strncmp_P(CMDBUFFER_CURRENT_STRING + 4, PSTR("SET_WAVE_"), 9) == 0) //! TMC_SET_WAVE_
  2907. {
  2908. uint8_t axis = *(CMDBUFFER_CURRENT_STRING + 13);
  2909. axis = (axis == 'E')?3:(axis - 'X');
  2910. if (axis < 4)
  2911. {
  2912. uint8_t fac = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 14, NULL, 10);
  2913. tmc2130_set_wave(axis, 247, fac);
  2914. }
  2915. }
  2916. else if (strncmp_P(CMDBUFFER_CURRENT_STRING + 4, PSTR("SET_STEP_"), 9) == 0) //! TMC_SET_STEP_
  2917. {
  2918. uint8_t axis = *(CMDBUFFER_CURRENT_STRING + 13);
  2919. axis = (axis == 'E')?3:(axis - 'X');
  2920. if (axis < 4)
  2921. {
  2922. uint8_t step = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 14, NULL, 10);
  2923. uint16_t res = tmc2130_get_res(axis);
  2924. tmc2130_goto_step(axis, step & (4*res - 1), 2, 1000, res);
  2925. }
  2926. }
  2927. else if (strncmp_P(CMDBUFFER_CURRENT_STRING + 4, PSTR("SET_CHOP_"), 9) == 0) //! TMC_SET_CHOP_
  2928. {
  2929. uint8_t axis = *(CMDBUFFER_CURRENT_STRING + 13);
  2930. axis = (axis == 'E')?3:(axis - 'X');
  2931. if (axis < 4)
  2932. {
  2933. uint8_t chop0 = tmc2130_chopper_config[axis].toff;
  2934. uint8_t chop1 = tmc2130_chopper_config[axis].hstr;
  2935. uint8_t chop2 = tmc2130_chopper_config[axis].hend;
  2936. uint8_t chop3 = tmc2130_chopper_config[axis].tbl;
  2937. char* str_end = 0;
  2938. if (CMDBUFFER_CURRENT_STRING[14])
  2939. {
  2940. chop0 = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 14, &str_end, 10) & 15;
  2941. if (str_end && *str_end)
  2942. {
  2943. chop1 = (uint8_t)strtol(str_end, &str_end, 10) & 7;
  2944. if (str_end && *str_end)
  2945. {
  2946. chop2 = (uint8_t)strtol(str_end, &str_end, 10) & 15;
  2947. if (str_end && *str_end)
  2948. chop3 = (uint8_t)strtol(str_end, &str_end, 10) & 3;
  2949. }
  2950. }
  2951. }
  2952. tmc2130_chopper_config[axis].toff = chop0;
  2953. tmc2130_chopper_config[axis].hstr = chop1 & 7;
  2954. tmc2130_chopper_config[axis].hend = chop2 & 15;
  2955. tmc2130_chopper_config[axis].tbl = chop3 & 3;
  2956. tmc2130_setup_chopper(axis, tmc2130_mres[axis], tmc2130_current_h[axis], tmc2130_current_r[axis]);
  2957. //printf_P(_N("TMC_SET_CHOP_%c %hhd %hhd %hhd %hhd\n"), "xyze"[axis], chop0, chop1, chop2, chop3);
  2958. }
  2959. }
  2960. }
  2961. #ifdef BACKLASH_X
  2962. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("BACKLASH_X"), 10) == 0)
  2963. {
  2964. uint8_t bl = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 10, NULL, 10);
  2965. st_backlash_x = bl;
  2966. printf_P(_N("st_backlash_x = %hhd\n"), st_backlash_x);
  2967. }
  2968. #endif //BACKLASH_X
  2969. #ifdef BACKLASH_Y
  2970. else if (strncmp_P(CMDBUFFER_CURRENT_STRING, PSTR("BACKLASH_Y"), 10) == 0)
  2971. {
  2972. uint8_t bl = (uint8_t)strtol(CMDBUFFER_CURRENT_STRING + 10, NULL, 10);
  2973. st_backlash_y = bl;
  2974. printf_P(_N("st_backlash_y = %hhd\n"), st_backlash_y);
  2975. }
  2976. #endif //BACKLASH_Y
  2977. #endif //TMC2130
  2978. #ifdef PAT9125
  2979. else if (code_seen("FSENSOR_RECOVER")) { //! FSENSOR_RECOVER
  2980. fsensor_restore_print_and_continue();
  2981. }
  2982. #endif //PAT9125
  2983. else if(code_seen("PRUSA")){
  2984. if (code_seen("Ping")) { //! PRUSA Ping
  2985. if (farm_mode) {
  2986. PingTime = millis();
  2987. //MYSERIAL.print(farm_no); MYSERIAL.println(": OK");
  2988. }
  2989. }
  2990. else if (code_seen("PRN")) { //! PRUSA PRN
  2991. printf_P(_N("%d"), status_number);
  2992. }else if (code_seen("FAN")) { //! PRUSA FAN
  2993. printf_P(_N("E0:%d RPM\nPRN0:%d RPM\n"), 60*fan_speed[0], 60*fan_speed[1]);
  2994. }else if (code_seen("fn")) { //! PRUSA fn
  2995. if (farm_mode) {
  2996. printf_P(_N("%d"), farm_no);
  2997. }
  2998. else {
  2999. puts_P(_N("Not in farm mode."));
  3000. }
  3001. }
  3002. else if (code_seen("thx")) //! PRUSA thx
  3003. {
  3004. no_response = false;
  3005. }
  3006. else if (code_seen("uvlo")) //! PRUSA uvlo
  3007. {
  3008. eeprom_update_byte((uint8_t*)EEPROM_UVLO,0);
  3009. enquecommand_P(PSTR("M24"));
  3010. }
  3011. else if (code_seen("MMURES")) //! PRUSA MMURES
  3012. {
  3013. mmu_reset();
  3014. }
  3015. else if (code_seen("RESET")) { //! PRUSA RESET
  3016. // careful!
  3017. if (farm_mode) {
  3018. #ifdef WATCHDOG
  3019. boot_app_magic = BOOT_APP_MAGIC;
  3020. boot_app_flags = BOOT_APP_FLG_RUN;
  3021. wdt_enable(WDTO_15MS);
  3022. cli();
  3023. while(1);
  3024. #else //WATCHDOG
  3025. asm volatile("jmp 0x3E000");
  3026. #endif //WATCHDOG
  3027. }
  3028. else {
  3029. MYSERIAL.println("Not in farm mode.");
  3030. }
  3031. }else if (code_seen("fv")) { //! PRUSA fv
  3032. // get file version
  3033. #ifdef SDSUPPORT
  3034. card.openFile(strchr_pointer + 3,true);
  3035. while (true) {
  3036. uint16_t readByte = card.get();
  3037. MYSERIAL.write(readByte);
  3038. if (readByte=='\n') {
  3039. break;
  3040. }
  3041. }
  3042. card.closefile();
  3043. #endif // SDSUPPORT
  3044. } else if (code_seen("M28")) { //! PRUSA M28
  3045. trace();
  3046. prusa_sd_card_upload = true;
  3047. card.openFile(strchr_pointer+4,false);
  3048. } else if (code_seen("SN")) { //! PRUSA SN
  3049. gcode_PRUSA_SN();
  3050. } else if(code_seen("Fir")){ //! PRUSA Fir
  3051. SERIAL_PROTOCOLLN(FW_VERSION_FULL);
  3052. } else if(code_seen("Rev")){ //! PRUSA Rev
  3053. SERIAL_PROTOCOLLN(FILAMENT_SIZE "-" ELECTRONICS "-" NOZZLE_TYPE );
  3054. } else if(code_seen("Lang")) { //! PRUSA Lang
  3055. lang_reset();
  3056. } else if(code_seen("Lz")) { //! PRUSA Lz
  3057. EEPROM_save_B(EEPROM_BABYSTEP_Z,0);
  3058. } else if(code_seen("Beat")) { //! PRUSA Beat
  3059. // Kick farm link timer
  3060. kicktime = millis();
  3061. } else if(code_seen("FR")) { //! PRUSA FR
  3062. // Factory full reset
  3063. factory_reset(0);
  3064. }
  3065. //else if (code_seen('Cal')) {
  3066. // lcd_calibration();
  3067. // }
  3068. }
  3069. else if (code_seen('^')) {
  3070. // nothing, this is a version line
  3071. } else if(code_seen('G'))
  3072. {
  3073. gcode_in_progress = (int)code_value();
  3074. // printf_P(_N("BEGIN G-CODE=%u\n"), gcode_in_progress);
  3075. switch (gcode_in_progress)
  3076. {
  3077. case 0: // G0 -> G1
  3078. case 1: // G1
  3079. if(Stopped == false) {
  3080. #ifdef FILAMENT_RUNOUT_SUPPORT
  3081. if(READ(FR_SENS)){
  3082. int feedmultiplyBckp=feedmultiply;
  3083. float target[4];
  3084. float lastpos[4];
  3085. target[X_AXIS]=current_position[X_AXIS];
  3086. target[Y_AXIS]=current_position[Y_AXIS];
  3087. target[Z_AXIS]=current_position[Z_AXIS];
  3088. target[E_AXIS]=current_position[E_AXIS];
  3089. lastpos[X_AXIS]=current_position[X_AXIS];
  3090. lastpos[Y_AXIS]=current_position[Y_AXIS];
  3091. lastpos[Z_AXIS]=current_position[Z_AXIS];
  3092. lastpos[E_AXIS]=current_position[E_AXIS];
  3093. //retract by E
  3094. target[E_AXIS]+= FILAMENTCHANGE_FIRSTRETRACT ;
  3095. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 400, active_extruder);
  3096. target[Z_AXIS]+= FILAMENTCHANGE_ZADD ;
  3097. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 300, active_extruder);
  3098. target[X_AXIS]= FILAMENTCHANGE_XPOS ;
  3099. target[Y_AXIS]= FILAMENTCHANGE_YPOS ;
  3100. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 70, active_extruder);
  3101. target[E_AXIS]+= FILAMENTCHANGE_FINALRETRACT ;
  3102. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 20, active_extruder);
  3103. //finish moves
  3104. st_synchronize();
  3105. //disable extruder steppers so filament can be removed
  3106. disable_e0();
  3107. disable_e1();
  3108. disable_e2();
  3109. delay(100);
  3110. //LCD_ALERTMESSAGEPGM(_T(MSG_FILAMENTCHANGE));
  3111. uint8_t cnt=0;
  3112. int counterBeep = 0;
  3113. lcd_wait_interact();
  3114. while(!lcd_clicked()){
  3115. cnt++;
  3116. manage_heater();
  3117. manage_inactivity(true);
  3118. //lcd_update(0);
  3119. if(cnt==0)
  3120. {
  3121. #if BEEPER > 0
  3122. if (counterBeep== 500){
  3123. counterBeep = 0;
  3124. }
  3125. SET_OUTPUT(BEEPER);
  3126. if (counterBeep== 0){
  3127. if((eSoundMode==e_SOUND_MODE_LOUD)||(eSoundMode==e_SOUND_MODE_ONCE))
  3128. WRITE(BEEPER,HIGH);
  3129. }
  3130. if (counterBeep== 20){
  3131. WRITE(BEEPER,LOW);
  3132. }
  3133. counterBeep++;
  3134. #else
  3135. #endif
  3136. }
  3137. }
  3138. WRITE(BEEPER,LOW);
  3139. target[E_AXIS]+= FILAMENTCHANGE_FIRSTFEED ;
  3140. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 20, active_extruder);
  3141. target[E_AXIS]+= FILAMENTCHANGE_FINALFEED ;
  3142. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 2, active_extruder);
  3143. lcd_change_fil_state = 0;
  3144. lcd_loading_filament();
  3145. while ((lcd_change_fil_state == 0)||(lcd_change_fil_state != 1)){
  3146. lcd_change_fil_state = 0;
  3147. lcd_alright();
  3148. switch(lcd_change_fil_state){
  3149. case 2:
  3150. target[E_AXIS]+= FILAMENTCHANGE_FIRSTFEED ;
  3151. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 20, active_extruder);
  3152. target[E_AXIS]+= FILAMENTCHANGE_FINALFEED ;
  3153. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 2, active_extruder);
  3154. lcd_loading_filament();
  3155. break;
  3156. case 3:
  3157. target[E_AXIS]+= FILAMENTCHANGE_FINALFEED ;
  3158. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 2, active_extruder);
  3159. lcd_loading_color();
  3160. break;
  3161. default:
  3162. lcd_change_success();
  3163. break;
  3164. }
  3165. }
  3166. target[E_AXIS]+= 5;
  3167. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 2, active_extruder);
  3168. target[E_AXIS]+= FILAMENTCHANGE_FIRSTRETRACT;
  3169. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 400, active_extruder);
  3170. //current_position[E_AXIS]=target[E_AXIS]; //the long retract of L is compensated by manual filament feeding
  3171. //plan_set_e_position(current_position[E_AXIS]);
  3172. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 70, active_extruder); //should do nothing
  3173. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], target[Z_AXIS], target[E_AXIS], 70, active_extruder); //move xy back
  3174. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], lastpos[Z_AXIS], target[E_AXIS], 200, active_extruder); //move z back
  3175. target[E_AXIS]= target[E_AXIS] - FILAMENTCHANGE_FIRSTRETRACT;
  3176. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], lastpos[Z_AXIS], target[E_AXIS], 5, active_extruder); //final untretract
  3177. plan_set_e_position(lastpos[E_AXIS]);
  3178. feedmultiply=feedmultiplyBckp;
  3179. char cmd[9];
  3180. sprintf_P(cmd, PSTR("M220 S%i"), feedmultiplyBckp);
  3181. enquecommand(cmd);
  3182. }
  3183. #endif
  3184. get_coordinates(); // For X Y Z E F
  3185. if (total_filament_used > ((current_position[E_AXIS] - destination[E_AXIS]) * 100)) { //protection against total_filament_used overflow
  3186. total_filament_used = total_filament_used + ((destination[E_AXIS] - current_position[E_AXIS]) * 100);
  3187. }
  3188. #ifdef FWRETRACT
  3189. if(cs.autoretract_enabled)
  3190. if( !(code_seen('X') || code_seen('Y') || code_seen('Z')) && code_seen('E')) {
  3191. float echange=destination[E_AXIS]-current_position[E_AXIS];
  3192. if((echange<-MIN_RETRACT && !retracted[active_extruder]) || (echange>MIN_RETRACT && retracted[active_extruder])) { //move appears to be an attempt to retract or recover
  3193. current_position[E_AXIS] = destination[E_AXIS]; //hide the slicer-generated retract/recover from calculations
  3194. plan_set_e_position(current_position[E_AXIS]); //AND from the planner
  3195. retract(!retracted[active_extruder]);
  3196. return;
  3197. }
  3198. }
  3199. #endif //FWRETRACT
  3200. prepare_move();
  3201. //ClearToSend();
  3202. }
  3203. break;
  3204. case 2: // G2 - CW ARC
  3205. if(Stopped == false) {
  3206. get_arc_coordinates();
  3207. prepare_arc_move(true);
  3208. }
  3209. break;
  3210. case 3: // G3 - CCW ARC
  3211. if(Stopped == false) {
  3212. get_arc_coordinates();
  3213. prepare_arc_move(false);
  3214. }
  3215. break;
  3216. case 4: // G4 dwell
  3217. codenum = 0;
  3218. if(code_seen('P')) codenum = code_value(); // milliseconds to wait
  3219. if(code_seen('S')) codenum = code_value() * 1000; // seconds to wait
  3220. if(codenum != 0) LCD_MESSAGERPGM(_n("Sleep..."));////MSG_DWELL c=0 r=0
  3221. st_synchronize();
  3222. codenum += millis(); // keep track of when we started waiting
  3223. previous_millis_cmd = millis();
  3224. while(millis() < codenum) {
  3225. manage_heater();
  3226. manage_inactivity();
  3227. lcd_update(0);
  3228. }
  3229. break;
  3230. #ifdef FWRETRACT
  3231. case 10: // G10 retract
  3232. #if EXTRUDERS > 1
  3233. retracted_swap[active_extruder]=(code_seen('S') && code_value_long() == 1); // checks for swap retract argument
  3234. retract(true,retracted_swap[active_extruder]);
  3235. #else
  3236. retract(true);
  3237. #endif
  3238. break;
  3239. case 11: // G11 retract_recover
  3240. #if EXTRUDERS > 1
  3241. retract(false,retracted_swap[active_extruder]);
  3242. #else
  3243. retract(false);
  3244. #endif
  3245. break;
  3246. #endif //FWRETRACT
  3247. case 28: //G28 Home all Axis one at a time
  3248. {
  3249. long home_x_value = 0;
  3250. long home_y_value = 0;
  3251. long home_z_value = 0;
  3252. // Which axes should be homed?
  3253. bool home_x = code_seen(axis_codes[X_AXIS]);
  3254. home_x_value = code_value_long();
  3255. bool home_y = code_seen(axis_codes[Y_AXIS]);
  3256. home_y_value = code_value_long();
  3257. bool home_z = code_seen(axis_codes[Z_AXIS]);
  3258. home_z_value = code_value_long();
  3259. bool without_mbl = code_seen('W');
  3260. // calibrate?
  3261. bool calib = code_seen('C');
  3262. gcode_G28(home_x, home_x_value, home_y, home_y_value, home_z, home_z_value, calib, without_mbl);
  3263. if ((home_x || home_y || without_mbl || home_z) == false) {
  3264. // Push the commands to the front of the message queue in the reverse order!
  3265. // There shall be always enough space reserved for these commands.
  3266. goto case_G80;
  3267. }
  3268. break;
  3269. }
  3270. #ifdef ENABLE_AUTO_BED_LEVELING
  3271. case 29: // G29 Detailed Z-Probe, probes the bed at 3 or more points.
  3272. {
  3273. #if Z_MIN_PIN == -1
  3274. #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."
  3275. #endif
  3276. // Prevent user from running a G29 without first homing in X and Y
  3277. if (! (axis_known_position[X_AXIS] && axis_known_position[Y_AXIS]) )
  3278. {
  3279. LCD_MESSAGERPGM(MSG_POSITION_UNKNOWN);
  3280. SERIAL_ECHO_START;
  3281. SERIAL_ECHOLNRPGM(MSG_POSITION_UNKNOWN);
  3282. break; // abort G29, since we don't know where we are
  3283. }
  3284. st_synchronize();
  3285. // make sure the bed_level_rotation_matrix is identity or the planner will get it incorectly
  3286. //vector_3 corrected_position = plan_get_position_mm();
  3287. //corrected_position.debug("position before G29");
  3288. plan_bed_level_matrix.set_to_identity();
  3289. vector_3 uncorrected_position = plan_get_position();
  3290. //uncorrected_position.debug("position durring G29");
  3291. current_position[X_AXIS] = uncorrected_position.x;
  3292. current_position[Y_AXIS] = uncorrected_position.y;
  3293. current_position[Z_AXIS] = uncorrected_position.z;
  3294. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  3295. int l_feedmultiply = setup_for_endstop_move();
  3296. feedrate = homing_feedrate[Z_AXIS];
  3297. #ifdef AUTO_BED_LEVELING_GRID
  3298. // probe at the points of a lattice grid
  3299. int xGridSpacing = (RIGHT_PROBE_BED_POSITION - LEFT_PROBE_BED_POSITION) / (AUTO_BED_LEVELING_GRID_POINTS-1);
  3300. int yGridSpacing = (BACK_PROBE_BED_POSITION - FRONT_PROBE_BED_POSITION) / (AUTO_BED_LEVELING_GRID_POINTS-1);
  3301. // solve the plane equation ax + by + d = z
  3302. // A is the matrix with rows [x y 1] for all the probed points
  3303. // B is the vector of the Z positions
  3304. // 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
  3305. // so Vx = -a Vy = -b Vz = 1 (we want the vector facing towards positive Z
  3306. // "A" matrix of the linear system of equations
  3307. double eqnAMatrix[AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS*3];
  3308. // "B" vector of Z points
  3309. double eqnBVector[AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS];
  3310. int probePointCounter = 0;
  3311. bool zig = true;
  3312. for (int yProbe=FRONT_PROBE_BED_POSITION; yProbe <= BACK_PROBE_BED_POSITION; yProbe += yGridSpacing)
  3313. {
  3314. int xProbe, xInc;
  3315. if (zig)
  3316. {
  3317. xProbe = LEFT_PROBE_BED_POSITION;
  3318. //xEnd = RIGHT_PROBE_BED_POSITION;
  3319. xInc = xGridSpacing;
  3320. zig = false;
  3321. } else // zag
  3322. {
  3323. xProbe = RIGHT_PROBE_BED_POSITION;
  3324. //xEnd = LEFT_PROBE_BED_POSITION;
  3325. xInc = -xGridSpacing;
  3326. zig = true;
  3327. }
  3328. for (int xCount=0; xCount < AUTO_BED_LEVELING_GRID_POINTS; xCount++)
  3329. {
  3330. float z_before;
  3331. if (probePointCounter == 0)
  3332. {
  3333. // raise before probing
  3334. z_before = Z_RAISE_BEFORE_PROBING;
  3335. } else
  3336. {
  3337. // raise extruder
  3338. z_before = current_position[Z_AXIS] + Z_RAISE_BETWEEN_PROBINGS;
  3339. }
  3340. float measured_z = probe_pt(xProbe, yProbe, z_before);
  3341. eqnBVector[probePointCounter] = measured_z;
  3342. eqnAMatrix[probePointCounter + 0*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = xProbe;
  3343. eqnAMatrix[probePointCounter + 1*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = yProbe;
  3344. eqnAMatrix[probePointCounter + 2*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = 1;
  3345. probePointCounter++;
  3346. xProbe += xInc;
  3347. }
  3348. }
  3349. clean_up_after_endstop_move(l_feedmultiply);
  3350. // solve lsq problem
  3351. double *plane_equation_coefficients = qr_solve(AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS, 3, eqnAMatrix, eqnBVector);
  3352. SERIAL_PROTOCOLPGM("Eqn coefficients: a: ");
  3353. SERIAL_PROTOCOL(plane_equation_coefficients[0]);
  3354. SERIAL_PROTOCOLPGM(" b: ");
  3355. SERIAL_PROTOCOL(plane_equation_coefficients[1]);
  3356. SERIAL_PROTOCOLPGM(" d: ");
  3357. SERIAL_PROTOCOLLN(plane_equation_coefficients[2]);
  3358. set_bed_level_equation_lsq(plane_equation_coefficients);
  3359. free(plane_equation_coefficients);
  3360. #else // AUTO_BED_LEVELING_GRID not defined
  3361. // Probe at 3 arbitrary points
  3362. // probe 1
  3363. float z_at_pt_1 = probe_pt(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, Z_RAISE_BEFORE_PROBING);
  3364. // probe 2
  3365. 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);
  3366. // probe 3
  3367. 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);
  3368. clean_up_after_endstop_move(l_feedmultiply);
  3369. set_bed_level_equation_3pts(z_at_pt_1, z_at_pt_2, z_at_pt_3);
  3370. #endif // AUTO_BED_LEVELING_GRID
  3371. st_synchronize();
  3372. // The following code correct the Z height difference from z-probe position and hotend tip position.
  3373. // The Z height on homing is measured by Z-Probe, but the probe is quite far from the hotend.
  3374. // When the bed is uneven, this height must be corrected.
  3375. 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)
  3376. x_tmp = current_position[X_AXIS] + X_PROBE_OFFSET_FROM_EXTRUDER;
  3377. y_tmp = current_position[Y_AXIS] + Y_PROBE_OFFSET_FROM_EXTRUDER;
  3378. z_tmp = current_position[Z_AXIS];
  3379. apply_rotation_xyz(plan_bed_level_matrix, x_tmp, y_tmp, z_tmp); //Apply the correction sending the probe offset
  3380. current_position[Z_AXIS] = z_tmp - real_z + current_position[Z_AXIS]; //The difference is added to current position and sent to planner.
  3381. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  3382. }
  3383. break;
  3384. #ifndef Z_PROBE_SLED
  3385. case 30: // G30 Single Z Probe
  3386. {
  3387. st_synchronize();
  3388. // TODO: make sure the bed_level_rotation_matrix is identity or the planner will get set incorectly
  3389. int l_feedmultiply = setup_for_endstop_move();
  3390. feedrate = homing_feedrate[Z_AXIS];
  3391. run_z_probe();
  3392. SERIAL_PROTOCOLPGM(_T(MSG_BED));
  3393. SERIAL_PROTOCOLPGM(" X: ");
  3394. SERIAL_PROTOCOL(current_position[X_AXIS]);
  3395. SERIAL_PROTOCOLPGM(" Y: ");
  3396. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  3397. SERIAL_PROTOCOLPGM(" Z: ");
  3398. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  3399. SERIAL_PROTOCOLPGM("\n");
  3400. clean_up_after_endstop_move(l_feedmultiply);
  3401. }
  3402. break;
  3403. #else
  3404. case 31: // dock the sled
  3405. dock_sled(true);
  3406. break;
  3407. case 32: // undock the sled
  3408. dock_sled(false);
  3409. break;
  3410. #endif // Z_PROBE_SLED
  3411. #endif // ENABLE_AUTO_BED_LEVELING
  3412. #ifdef MESH_BED_LEVELING
  3413. case 30: // G30 Single Z Probe
  3414. {
  3415. st_synchronize();
  3416. // TODO: make sure the bed_level_rotation_matrix is identity or the planner will get set incorectly
  3417. int l_feedmultiply = setup_for_endstop_move();
  3418. feedrate = homing_feedrate[Z_AXIS];
  3419. find_bed_induction_sensor_point_z(-10.f, 3);
  3420. printf_P(_N("%S X: %.5f Y: %.5f Z: %.5f\n"), _T(MSG_BED), _x, _y, _z);
  3421. clean_up_after_endstop_move(l_feedmultiply);
  3422. }
  3423. break;
  3424. case 75:
  3425. {
  3426. for (int i = 40; i <= 110; i++)
  3427. printf_P(_N("%d %.2f"), i, temp_comp_interpolation(i));
  3428. }
  3429. break;
  3430. case 76: //! G76 - PINDA probe temperature calibration
  3431. {
  3432. #ifdef PINDA_THERMISTOR
  3433. if (true)
  3434. {
  3435. if (calibration_status() >= CALIBRATION_STATUS_XYZ_CALIBRATION) {
  3436. //we need to know accurate position of first calibration point
  3437. //if xyz calibration was not performed yet, interrupt temperature calibration and inform user that xyz cal. is needed
  3438. lcd_show_fullscreen_message_and_wait_P(_i("Please run XYZ calibration first."));
  3439. break;
  3440. }
  3441. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS]))
  3442. {
  3443. // We don't know where we are! HOME!
  3444. // Push the commands to the front of the message queue in the reverse order!
  3445. // There shall be always enough space reserved for these commands.
  3446. repeatcommand_front(); // repeat G76 with all its parameters
  3447. enquecommand_front_P((PSTR("G28 W0")));
  3448. break;
  3449. }
  3450. 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
  3451. bool result = lcd_show_fullscreen_message_yes_no_and_wait_P(_T(MSG_STEEL_SHEET_CHECK), false, false);
  3452. if (result)
  3453. {
  3454. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  3455. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3456. current_position[Z_AXIS] = 50;
  3457. current_position[Y_AXIS] = 180;
  3458. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3459. st_synchronize();
  3460. lcd_show_fullscreen_message_and_wait_P(_T(MSG_REMOVE_STEEL_SHEET));
  3461. current_position[Y_AXIS] = pgm_read_float(bed_ref_points_4 + 1);
  3462. current_position[X_AXIS] = pgm_read_float(bed_ref_points_4);
  3463. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3464. st_synchronize();
  3465. gcode_G28(false, false, true);
  3466. }
  3467. if ((current_temperature_pinda > 35) && (farm_mode == false)) {
  3468. //waiting for PIDNA probe to cool down in case that we are not in farm mode
  3469. current_position[Z_AXIS] = 100;
  3470. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3471. if (lcd_wait_for_pinda(35) == false) { //waiting for PINDA probe to cool, if this takes more then time expected, temp. cal. fails
  3472. lcd_temp_cal_show_result(false);
  3473. break;
  3474. }
  3475. }
  3476. lcd_update_enable(true);
  3477. KEEPALIVE_STATE(NOT_BUSY); //no need to print busy messages as we print current temperatures periodicaly
  3478. SERIAL_ECHOLNPGM("PINDA probe calibration start");
  3479. float zero_z;
  3480. int z_shift = 0; //unit: steps
  3481. float start_temp = 5 * (int)(current_temperature_pinda / 5);
  3482. if (start_temp < 35) start_temp = 35;
  3483. if (start_temp < current_temperature_pinda) start_temp += 5;
  3484. printf_P(_N("start temperature: %.1f\n"), start_temp);
  3485. // setTargetHotend(200, 0);
  3486. setTargetBed(70 + (start_temp - 30));
  3487. custom_message_type = CUSTOM_MSG_TYPE_TEMCAL;
  3488. custom_message_state = 1;
  3489. lcd_setstatuspgm(_T(MSG_TEMP_CALIBRATION));
  3490. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  3491. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3492. current_position[X_AXIS] = PINDA_PREHEAT_X;
  3493. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  3494. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3495. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  3496. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3497. st_synchronize();
  3498. while (current_temperature_pinda < start_temp)
  3499. {
  3500. delay_keep_alive(1000);
  3501. serialecho_temperatures();
  3502. }
  3503. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0); //invalidate temp. calibration in case that in will be aborted during the calibration process
  3504. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  3505. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3506. current_position[X_AXIS] = pgm_read_float(bed_ref_points_4);
  3507. current_position[Y_AXIS] = pgm_read_float(bed_ref_points_4 + 1);
  3508. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3509. st_synchronize();
  3510. bool find_z_result = find_bed_induction_sensor_point_z(-1.f);
  3511. if (find_z_result == false) {
  3512. lcd_temp_cal_show_result(find_z_result);
  3513. break;
  3514. }
  3515. zero_z = current_position[Z_AXIS];
  3516. printf_P(_N("\nZERO: %.3f\n"), current_position[Z_AXIS]);
  3517. int i = -1; for (; i < 5; i++)
  3518. {
  3519. float temp = (40 + i * 5);
  3520. printf_P(_N("\nStep: %d/6 (skipped)\nPINDA temperature: %d Z shift (mm):0\n"), i + 2, (40 + i*5));
  3521. if (i >= 0) EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + i * 2, &z_shift);
  3522. if (start_temp <= temp) break;
  3523. }
  3524. for (i++; i < 5; i++)
  3525. {
  3526. float temp = (40 + i * 5);
  3527. printf_P(_N("\nStep: %d/6\n"), i + 2);
  3528. custom_message_state = i + 2;
  3529. setTargetBed(50 + 10 * (temp - 30) / 5);
  3530. // setTargetHotend(255, 0);
  3531. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  3532. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3533. current_position[X_AXIS] = PINDA_PREHEAT_X;
  3534. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  3535. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3536. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  3537. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3538. st_synchronize();
  3539. while (current_temperature_pinda < temp)
  3540. {
  3541. delay_keep_alive(1000);
  3542. serialecho_temperatures();
  3543. }
  3544. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  3545. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3546. current_position[X_AXIS] = pgm_read_float(bed_ref_points_4);
  3547. current_position[Y_AXIS] = pgm_read_float(bed_ref_points_4 + 1);
  3548. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3549. st_synchronize();
  3550. find_z_result = find_bed_induction_sensor_point_z(-1.f);
  3551. if (find_z_result == false) {
  3552. lcd_temp_cal_show_result(find_z_result);
  3553. break;
  3554. }
  3555. z_shift = (int)((current_position[Z_AXIS] - zero_z)*cs.axis_steps_per_unit[Z_AXIS]);
  3556. printf_P(_N("\nPINDA temperature: %.1f Z shift (mm): %.3f"), current_temperature_pinda, current_position[Z_AXIS] - zero_z);
  3557. EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + i * 2, &z_shift);
  3558. }
  3559. lcd_temp_cal_show_result(true);
  3560. break;
  3561. }
  3562. #endif //PINDA_THERMISTOR
  3563. setTargetBed(PINDA_MIN_T);
  3564. float zero_z;
  3565. int z_shift = 0; //unit: steps
  3566. int t_c; // temperature
  3567. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  3568. // We don't know where we are! HOME!
  3569. // Push the commands to the front of the message queue in the reverse order!
  3570. // There shall be always enough space reserved for these commands.
  3571. repeatcommand_front(); // repeat G76 with all its parameters
  3572. enquecommand_front_P((PSTR("G28 W0")));
  3573. break;
  3574. }
  3575. puts_P(_N("PINDA probe calibration start"));
  3576. custom_message_type = CUSTOM_MSG_TYPE_TEMCAL;
  3577. custom_message_state = 1;
  3578. lcd_setstatuspgm(_T(MSG_TEMP_CALIBRATION));
  3579. current_position[X_AXIS] = PINDA_PREHEAT_X;
  3580. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  3581. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  3582. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3583. st_synchronize();
  3584. while (abs(degBed() - PINDA_MIN_T) > 1) {
  3585. delay_keep_alive(1000);
  3586. serialecho_temperatures();
  3587. }
  3588. //enquecommand_P(PSTR("M190 S50"));
  3589. for (int i = 0; i < PINDA_HEAT_T; i++) {
  3590. delay_keep_alive(1000);
  3591. serialecho_temperatures();
  3592. }
  3593. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0); //invalidate temp. calibration in case that in will be aborted during the calibration process
  3594. current_position[Z_AXIS] = 5;
  3595. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3596. current_position[X_AXIS] = pgm_read_float(bed_ref_points);
  3597. current_position[Y_AXIS] = pgm_read_float(bed_ref_points + 1);
  3598. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3599. st_synchronize();
  3600. find_bed_induction_sensor_point_z(-1.f);
  3601. zero_z = current_position[Z_AXIS];
  3602. printf_P(_N("\nZERO: %.3f\n"), current_position[Z_AXIS]);
  3603. for (int i = 0; i<5; i++) {
  3604. printf_P(_N("\nStep: %d/6\n"), i + 2);
  3605. custom_message_state = i + 2;
  3606. t_c = 60 + i * 10;
  3607. setTargetBed(t_c);
  3608. current_position[X_AXIS] = PINDA_PREHEAT_X;
  3609. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  3610. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  3611. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3612. st_synchronize();
  3613. while (degBed() < t_c) {
  3614. delay_keep_alive(1000);
  3615. serialecho_temperatures();
  3616. }
  3617. for (int i = 0; i < PINDA_HEAT_T; i++) {
  3618. delay_keep_alive(1000);
  3619. serialecho_temperatures();
  3620. }
  3621. current_position[Z_AXIS] = 5;
  3622. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3623. current_position[X_AXIS] = pgm_read_float(bed_ref_points);
  3624. current_position[Y_AXIS] = pgm_read_float(bed_ref_points + 1);
  3625. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  3626. st_synchronize();
  3627. find_bed_induction_sensor_point_z(-1.f);
  3628. z_shift = (int)((current_position[Z_AXIS] - zero_z)*cs.axis_steps_per_unit[Z_AXIS]);
  3629. printf_P(_N("\nTemperature: %d Z shift (mm): %.3f\n"), t_c, current_position[Z_AXIS] - zero_z);
  3630. EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + i*2, &z_shift);
  3631. }
  3632. custom_message_type = CUSTOM_MSG_TYPE_STATUS;
  3633. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  3634. puts_P(_N("Temperature calibration done."));
  3635. disable_x();
  3636. disable_y();
  3637. disable_z();
  3638. disable_e0();
  3639. disable_e1();
  3640. disable_e2();
  3641. setTargetBed(0); //set bed target temperature back to 0
  3642. lcd_show_fullscreen_message_and_wait_P(_T(MSG_TEMP_CALIBRATION_DONE));
  3643. temp_cal_active = true;
  3644. eeprom_update_byte((unsigned char *)EEPROM_TEMP_CAL_ACTIVE, 1);
  3645. lcd_update_enable(true);
  3646. lcd_update(2);
  3647. }
  3648. break;
  3649. #ifdef DIS
  3650. case 77:
  3651. {
  3652. //! G77 X200 Y150 XP100 YP15 XO10 Y015
  3653. //! for 9 point mesh bed leveling G77 X203 Y196 XP3 YP3 XO0 YO0
  3654. //! G77 X232 Y218 XP116 YP109 XO-11 YO0
  3655. float dimension_x = 40;
  3656. float dimension_y = 40;
  3657. int points_x = 40;
  3658. int points_y = 40;
  3659. float offset_x = 74;
  3660. float offset_y = 33;
  3661. if (code_seen('X')) dimension_x = code_value();
  3662. if (code_seen('Y')) dimension_y = code_value();
  3663. if (code_seen("XP")) { strchr_pointer+=1; points_x = code_value(); }
  3664. if (code_seen("YP")) { strchr_pointer+=1; points_y = code_value(); }
  3665. if (code_seen("XO")) { strchr_pointer+=1; offset_x = code_value(); }
  3666. if (code_seen("YO")) { strchr_pointer+=1; offset_y = code_value(); }
  3667. bed_analysis(dimension_x,dimension_y,points_x,points_y,offset_x,offset_y);
  3668. } break;
  3669. #endif
  3670. case 79: {
  3671. for (int i = 255; i > 0; i = i - 5) {
  3672. fanSpeed = i;
  3673. //delay_keep_alive(2000);
  3674. for (int j = 0; j < 100; j++) {
  3675. delay_keep_alive(100);
  3676. }
  3677. printf_P(_N("%d: %d\n"), i, fan_speed[1]);
  3678. }
  3679. }break;
  3680. /**
  3681. * G80: Mesh-based Z probe, probes a grid and produces a
  3682. * mesh to compensate for variable bed height
  3683. *
  3684. * The S0 report the points as below
  3685. * @code{.unparsed}
  3686. * +----> X-axis
  3687. * |
  3688. * |
  3689. * v Y-axis
  3690. * @endcode
  3691. */
  3692. case 80:
  3693. #ifdef MK1BP
  3694. break;
  3695. #endif //MK1BP
  3696. case_G80:
  3697. {
  3698. mesh_bed_leveling_flag = true;
  3699. static bool run = false;
  3700. #ifdef SUPPORT_VERBOSITY
  3701. int8_t verbosity_level = 0;
  3702. if (code_seen('V')) {
  3703. // Just 'V' without a number counts as V1.
  3704. char c = strchr_pointer[1];
  3705. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  3706. }
  3707. #endif //SUPPORT_VERBOSITY
  3708. // Firstly check if we know where we are
  3709. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  3710. // We don't know where we are! HOME!
  3711. // Push the commands to the front of the message queue in the reverse order!
  3712. // There shall be always enough space reserved for these commands.
  3713. if (lcd_commands_type != LCD_COMMAND_STOP_PRINT) {
  3714. repeatcommand_front(); // repeat G80 with all its parameters
  3715. enquecommand_front_P((PSTR("G28 W0")));
  3716. }
  3717. else {
  3718. mesh_bed_leveling_flag = false;
  3719. }
  3720. break;
  3721. }
  3722. bool temp_comp_start = true;
  3723. #ifdef PINDA_THERMISTOR
  3724. temp_comp_start = false;
  3725. #endif //PINDA_THERMISTOR
  3726. if (temp_comp_start)
  3727. if (run == false && temp_cal_active == true && calibration_status_pinda() == true && target_temperature_bed >= 50) {
  3728. if (lcd_commands_type != LCD_COMMAND_STOP_PRINT) {
  3729. temp_compensation_start();
  3730. run = true;
  3731. repeatcommand_front(); // repeat G80 with all its parameters
  3732. enquecommand_front_P((PSTR("G28 W0")));
  3733. }
  3734. else {
  3735. mesh_bed_leveling_flag = false;
  3736. }
  3737. break;
  3738. }
  3739. run = false;
  3740. if (lcd_commands_type == LCD_COMMAND_STOP_PRINT) {
  3741. mesh_bed_leveling_flag = false;
  3742. break;
  3743. }
  3744. // Save custom message state, set a new custom message state to display: Calibrating point 9.
  3745. unsigned int custom_message_type_old = custom_message_type;
  3746. unsigned int custom_message_state_old = custom_message_state;
  3747. custom_message_type = CUSTOM_MSG_TYPE_MESHBL;
  3748. custom_message_state = (MESH_MEAS_NUM_X_POINTS * MESH_MEAS_NUM_Y_POINTS) + 10;
  3749. lcd_update(1);
  3750. mbl.reset(); //reset mesh bed leveling
  3751. // Reset baby stepping to zero, if the babystepping has already been loaded before. The babystepsTodo value will be
  3752. // consumed during the first movements following this statement.
  3753. babystep_undo();
  3754. // Cycle through all points and probe them
  3755. // First move up. During this first movement, the babystepping will be reverted.
  3756. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  3757. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], homing_feedrate[Z_AXIS] / 60, active_extruder);
  3758. // The move to the first calibration point.
  3759. current_position[X_AXIS] = pgm_read_float(bed_ref_points);
  3760. current_position[Y_AXIS] = pgm_read_float(bed_ref_points + 1);
  3761. #ifdef SUPPORT_VERBOSITY
  3762. if (verbosity_level >= 1)
  3763. {
  3764. bool clamped = world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  3765. clamped ? SERIAL_PROTOCOLPGM("First calibration point clamped.\n") : SERIAL_PROTOCOLPGM("No clamping for first calibration point.\n");
  3766. }
  3767. #endif //SUPPORT_VERBOSITY
  3768. // mbl.get_meas_xy(0, 0, current_position[X_AXIS], current_position[Y_AXIS], false);
  3769. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], homing_feedrate[X_AXIS] / 30, active_extruder);
  3770. // Wait until the move is finished.
  3771. st_synchronize();
  3772. int mesh_point = 0; //index number of calibration point
  3773. int ix = 0;
  3774. int iy = 0;
  3775. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  3776. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  3777. 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)
  3778. #ifdef SUPPORT_VERBOSITY
  3779. if (verbosity_level >= 1) {
  3780. has_z ? SERIAL_PROTOCOLPGM("Z jitter data from Z cal. valid.\n") : SERIAL_PROTOCOLPGM("Z jitter data from Z cal. not valid.\n");
  3781. }
  3782. #endif // SUPPORT_VERBOSITY
  3783. int l_feedmultiply = setup_for_endstop_move(false); //save feedrate and feedmultiply, sets feedmultiply to 100
  3784. const char *kill_message = NULL;
  3785. while (mesh_point != MESH_MEAS_NUM_X_POINTS * MESH_MEAS_NUM_Y_POINTS) {
  3786. // Get coords of a measuring point.
  3787. ix = mesh_point % MESH_MEAS_NUM_X_POINTS; // from 0 to MESH_NUM_X_POINTS - 1
  3788. iy = mesh_point / MESH_MEAS_NUM_X_POINTS;
  3789. if (iy & 1) ix = (MESH_MEAS_NUM_X_POINTS - 1) - ix; // Zig zag
  3790. float z0 = 0.f;
  3791. if (has_z && mesh_point > 0) {
  3792. uint16_t z_offset_u = eeprom_read_word((uint16_t*)(EEPROM_BED_CALIBRATION_Z_JITTER + 2 * (ix + iy * 3 - 1)));
  3793. z0 = mbl.z_values[0][0] + *reinterpret_cast<int16_t*>(&z_offset_u) * 0.01;
  3794. //#if 0
  3795. #ifdef SUPPORT_VERBOSITY
  3796. if (verbosity_level >= 1) {
  3797. SERIAL_ECHOLNPGM("");
  3798. SERIAL_ECHOPGM("Bed leveling, point: ");
  3799. MYSERIAL.print(mesh_point);
  3800. SERIAL_ECHOPGM(", calibration z: ");
  3801. MYSERIAL.print(z0, 5);
  3802. SERIAL_ECHOLNPGM("");
  3803. }
  3804. #endif // SUPPORT_VERBOSITY
  3805. //#endif
  3806. }
  3807. // Move Z up to MESH_HOME_Z_SEARCH.
  3808. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  3809. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], Z_LIFT_FEEDRATE, active_extruder);
  3810. st_synchronize();
  3811. // Move to XY position of the sensor point.
  3812. current_position[X_AXIS] = pgm_read_float(bed_ref_points + 2 * mesh_point);
  3813. current_position[Y_AXIS] = pgm_read_float(bed_ref_points + 2 * mesh_point + 1);
  3814. world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  3815. #ifdef SUPPORT_VERBOSITY
  3816. if (verbosity_level >= 1) {
  3817. SERIAL_PROTOCOL(mesh_point);
  3818. clamped ? SERIAL_PROTOCOLPGM(": xy clamped.\n") : SERIAL_PROTOCOLPGM(": no xy clamping\n");
  3819. }
  3820. #endif // SUPPORT_VERBOSITY
  3821. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], XY_AXIS_FEEDRATE, active_extruder);
  3822. st_synchronize();
  3823. // Go down until endstop is hit
  3824. const float Z_CALIBRATION_THRESHOLD = 1.f;
  3825. if (!find_bed_induction_sensor_point_z((has_z && mesh_point > 0) ? z0 - Z_CALIBRATION_THRESHOLD : -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
  3826. kill_message = _T(MSG_BED_LEVELING_FAILED_POINT_LOW);
  3827. break;
  3828. }
  3829. if (MESH_HOME_Z_SEARCH - current_position[Z_AXIS] < 0.1f) {
  3830. kill_message = _i("Bed leveling failed. Sensor disconnected or cable broken. Waiting for reset.");////MSG_BED_LEVELING_FAILED_PROBE_DISCONNECTED c=20 r=4
  3831. break;
  3832. }
  3833. 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
  3834. kill_message = _i("Bed leveling failed. Sensor triggered too high. Waiting for reset.");////MSG_BED_LEVELING_FAILED_POINT_HIGH c=20 r=4
  3835. break;
  3836. }
  3837. #ifdef SUPPORT_VERBOSITY
  3838. if (verbosity_level >= 10) {
  3839. SERIAL_ECHOPGM("X: ");
  3840. MYSERIAL.print(current_position[X_AXIS], 5);
  3841. SERIAL_ECHOLNPGM("");
  3842. SERIAL_ECHOPGM("Y: ");
  3843. MYSERIAL.print(current_position[Y_AXIS], 5);
  3844. SERIAL_PROTOCOLPGM("\n");
  3845. }
  3846. #endif // SUPPORT_VERBOSITY
  3847. float offset_z = 0;
  3848. #ifdef PINDA_THERMISTOR
  3849. offset_z = temp_compensation_pinda_thermistor_offset(current_temperature_pinda);
  3850. #endif //PINDA_THERMISTOR
  3851. // #ifdef SUPPORT_VERBOSITY
  3852. /* if (verbosity_level >= 1)
  3853. {
  3854. SERIAL_ECHOPGM("mesh bed leveling: ");
  3855. MYSERIAL.print(current_position[Z_AXIS], 5);
  3856. SERIAL_ECHOPGM(" offset: ");
  3857. MYSERIAL.print(offset_z, 5);
  3858. SERIAL_ECHOLNPGM("");
  3859. }*/
  3860. // #endif // SUPPORT_VERBOSITY
  3861. mbl.set_z(ix, iy, current_position[Z_AXIS] - offset_z); //store measured z values z_values[iy][ix] = z - offset_z;
  3862. custom_message_state--;
  3863. mesh_point++;
  3864. lcd_update(1);
  3865. }
  3866. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  3867. #ifdef SUPPORT_VERBOSITY
  3868. if (verbosity_level >= 20) {
  3869. SERIAL_ECHOLNPGM("Mesh bed leveling while loop finished.");
  3870. SERIAL_ECHOLNPGM("MESH_HOME_Z_SEARCH: ");
  3871. MYSERIAL.print(current_position[Z_AXIS], 5);
  3872. }
  3873. #endif // SUPPORT_VERBOSITY
  3874. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], Z_LIFT_FEEDRATE, active_extruder);
  3875. st_synchronize();
  3876. if (mesh_point != MESH_MEAS_NUM_X_POINTS * MESH_MEAS_NUM_Y_POINTS) {
  3877. Sound_MakeSound(e_SOUND_TYPE_StandardAlert);
  3878. bool bState;
  3879. do { // repeat until Z-leveling o.k.
  3880. lcd_display_message_fullscreen_P(_i("Some problem encountered, Z-leveling enforced ..."));
  3881. #ifdef TMC2130
  3882. lcd_wait_for_click_delay(MSG_BED_LEVELING_FAILED_TIMEOUT);
  3883. calibrate_z_auto(); // Z-leveling (X-assembly stay up!!!)
  3884. #else // TMC2130
  3885. lcd_wait_for_click_delay(0); // ~ no timeout
  3886. lcd_calibrate_z_end_stop_manual(true); // Z-leveling (X-assembly stay up!!!)
  3887. #endif // TMC2130
  3888. // ~ Z-homing (can not be used "G28", because X & Y-homing would have been done before (Z-homing))
  3889. bState=enable_z_endstop(false);
  3890. current_position[Z_AXIS] -= 1;
  3891. 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);
  3892. st_synchronize();
  3893. enable_z_endstop(true);
  3894. #ifdef TMC2130
  3895. tmc2130_home_enter(Z_AXIS_MASK);
  3896. #endif // TMC2130
  3897. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  3898. 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);
  3899. st_synchronize();
  3900. #ifdef TMC2130
  3901. tmc2130_home_exit();
  3902. #endif // TMC2130
  3903. enable_z_endstop(bState);
  3904. } while (st_get_position_mm(Z_AXIS) > MESH_HOME_Z_SEARCH); // i.e. Z-leveling not o.k.
  3905. // plan_set_z_position(MESH_HOME_Z_SEARCH); // is not necessary ('do-while' loop always ends at the expected Z-position)
  3906. custom_message_type=CUSTOM_MSG_TYPE_STATUS; // display / status-line recovery
  3907. lcd_update_enable(true); // display / status-line recovery
  3908. gcode_G28(true, true, true); // X & Y & Z-homing (must be after individual Z-homing (problem with spool-holder)!)
  3909. repeatcommand_front(); // re-run (i.e. of "G80")
  3910. break;
  3911. }
  3912. clean_up_after_endstop_move(l_feedmultiply);
  3913. // SERIAL_ECHOLNPGM("clean up finished ");
  3914. bool apply_temp_comp = true;
  3915. #ifdef PINDA_THERMISTOR
  3916. apply_temp_comp = false;
  3917. #endif
  3918. if (apply_temp_comp)
  3919. if(temp_cal_active == true && calibration_status_pinda() == true) temp_compensation_apply(); //apply PINDA temperature compensation
  3920. babystep_apply(); // Apply Z height correction aka baby stepping before mesh bed leveing gets activated.
  3921. // SERIAL_ECHOLNPGM("babystep applied");
  3922. bool eeprom_bed_correction_valid = eeprom_read_byte((unsigned char*)EEPROM_BED_CORRECTION_VALID) == 1;
  3923. #ifdef SUPPORT_VERBOSITY
  3924. if (verbosity_level >= 1) {
  3925. eeprom_bed_correction_valid ? SERIAL_PROTOCOLPGM("Bed correction data valid\n") : SERIAL_PROTOCOLPGM("Bed correction data not valid\n");
  3926. }
  3927. #endif // SUPPORT_VERBOSITY
  3928. for (uint8_t i = 0; i < 4; ++i) {
  3929. unsigned char codes[4] = { 'L', 'R', 'F', 'B' };
  3930. long correction = 0;
  3931. if (code_seen(codes[i]))
  3932. correction = code_value_long();
  3933. else if (eeprom_bed_correction_valid) {
  3934. unsigned char *addr = (i < 2) ?
  3935. ((i == 0) ? (unsigned char*)EEPROM_BED_CORRECTION_LEFT : (unsigned char*)EEPROM_BED_CORRECTION_RIGHT) :
  3936. ((i == 2) ? (unsigned char*)EEPROM_BED_CORRECTION_FRONT : (unsigned char*)EEPROM_BED_CORRECTION_REAR);
  3937. correction = eeprom_read_int8(addr);
  3938. }
  3939. if (correction == 0)
  3940. continue;
  3941. float offset = float(correction) * 0.001f;
  3942. if (fabs(offset) > 0.101f) {
  3943. SERIAL_ERROR_START;
  3944. SERIAL_ECHOPGM("Excessive bed leveling correction: ");
  3945. SERIAL_ECHO(offset);
  3946. SERIAL_ECHOLNPGM(" microns");
  3947. }
  3948. else {
  3949. switch (i) {
  3950. case 0:
  3951. for (uint8_t row = 0; row < 3; ++row) {
  3952. mbl.z_values[row][1] += 0.5f * offset;
  3953. mbl.z_values[row][0] += offset;
  3954. }
  3955. break;
  3956. case 1:
  3957. for (uint8_t row = 0; row < 3; ++row) {
  3958. mbl.z_values[row][1] += 0.5f * offset;
  3959. mbl.z_values[row][2] += offset;
  3960. }
  3961. break;
  3962. case 2:
  3963. for (uint8_t col = 0; col < 3; ++col) {
  3964. mbl.z_values[1][col] += 0.5f * offset;
  3965. mbl.z_values[0][col] += offset;
  3966. }
  3967. break;
  3968. case 3:
  3969. for (uint8_t col = 0; col < 3; ++col) {
  3970. mbl.z_values[1][col] += 0.5f * offset;
  3971. mbl.z_values[2][col] += offset;
  3972. }
  3973. break;
  3974. }
  3975. }
  3976. }
  3977. // SERIAL_ECHOLNPGM("Bed leveling correction finished");
  3978. mbl.upsample_3x3(); //bilinear interpolation from 3x3 to 7x7 points while using the same array z_values[iy][ix] for storing (just coppying measured data to new destination and interpolating between them)
  3979. // SERIAL_ECHOLNPGM("Upsample finished");
  3980. mbl.active = 1; //activate mesh bed leveling
  3981. // SERIAL_ECHOLNPGM("Mesh bed leveling activated");
  3982. go_home_with_z_lift();
  3983. // SERIAL_ECHOLNPGM("Go home finished");
  3984. //unretract (after PINDA preheat retraction)
  3985. if (degHotend(active_extruder) > EXTRUDE_MINTEMP && temp_cal_active == true && calibration_status_pinda() == true && target_temperature_bed >= 50) {
  3986. current_position[E_AXIS] += default_retraction;
  3987. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 400, active_extruder);
  3988. }
  3989. KEEPALIVE_STATE(NOT_BUSY);
  3990. // Restore custom message state
  3991. lcd_setstatuspgm(_T(WELCOME_MSG));
  3992. custom_message_type = custom_message_type_old;
  3993. custom_message_state = custom_message_state_old;
  3994. mesh_bed_leveling_flag = false;
  3995. mesh_bed_run_from_menu = false;
  3996. lcd_update(2);
  3997. }
  3998. break;
  3999. /**
  4000. * G81: Print mesh bed leveling status and bed profile if activated
  4001. */
  4002. case 81:
  4003. if (mbl.active) {
  4004. SERIAL_PROTOCOLPGM("Num X,Y: ");
  4005. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  4006. SERIAL_PROTOCOLPGM(",");
  4007. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  4008. SERIAL_PROTOCOLPGM("\nZ search height: ");
  4009. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  4010. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  4011. for (int y = MESH_NUM_Y_POINTS-1; y >= 0; y--) {
  4012. for (int x = 0; x < MESH_NUM_X_POINTS; x++) {
  4013. SERIAL_PROTOCOLPGM(" ");
  4014. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  4015. }
  4016. SERIAL_PROTOCOLPGM("\n");
  4017. }
  4018. }
  4019. else
  4020. SERIAL_PROTOCOLLNPGM("Mesh bed leveling not active.");
  4021. break;
  4022. #if 0
  4023. /**
  4024. * G82: Single Z probe at current location
  4025. *
  4026. * WARNING! USE WITH CAUTION! If you'll try to probe where is no leveling pad, nasty things can happen!
  4027. *
  4028. */
  4029. case 82:
  4030. SERIAL_PROTOCOLLNPGM("Finding bed ");
  4031. int l_feedmultiply = setup_for_endstop_move();
  4032. find_bed_induction_sensor_point_z();
  4033. clean_up_after_endstop_move(l_feedmultiply);
  4034. SERIAL_PROTOCOLPGM("Bed found at: ");
  4035. SERIAL_PROTOCOL_F(current_position[Z_AXIS], 5);
  4036. SERIAL_PROTOCOLPGM("\n");
  4037. break;
  4038. /**
  4039. * G83: Prusa3D specific: Babystep in Z and store to EEPROM
  4040. */
  4041. case 83:
  4042. {
  4043. int babystepz = code_seen('S') ? code_value() : 0;
  4044. int BabyPosition = code_seen('P') ? code_value() : 0;
  4045. if (babystepz != 0) {
  4046. //FIXME Vojtech: What shall be the index of the axis Z: 3 or 4?
  4047. // Is the axis indexed starting with zero or one?
  4048. if (BabyPosition > 4) {
  4049. SERIAL_PROTOCOLLNPGM("Index out of bounds");
  4050. }else{
  4051. // Save it to the eeprom
  4052. babystepLoadZ = babystepz;
  4053. EEPROM_save_B(EEPROM_BABYSTEP_Z0+(BabyPosition*2),&babystepLoadZ);
  4054. // adjust the Z
  4055. babystepsTodoZadd(babystepLoadZ);
  4056. }
  4057. }
  4058. }
  4059. break;
  4060. /**
  4061. * G84: Prusa3D specific: UNDO Babystep Z (move Z axis back)
  4062. */
  4063. case 84:
  4064. babystepsTodoZsubtract(babystepLoadZ);
  4065. // babystepLoadZ = 0;
  4066. break;
  4067. /**
  4068. * G85: Prusa3D specific: Pick best babystep
  4069. */
  4070. case 85:
  4071. lcd_pick_babystep();
  4072. break;
  4073. #endif
  4074. /**
  4075. * G86: Prusa3D specific: Disable babystep correction after home.
  4076. * This G-code will be performed at the start of a calibration script.
  4077. */
  4078. case 86:
  4079. calibration_status_store(CALIBRATION_STATUS_LIVE_ADJUST);
  4080. break;
  4081. /**
  4082. * G87: Prusa3D specific: Enable babystep correction after home
  4083. * This G-code will be performed at the end of a calibration script.
  4084. */
  4085. case 87:
  4086. calibration_status_store(CALIBRATION_STATUS_CALIBRATED);
  4087. break;
  4088. /**
  4089. * G88: Prusa3D specific: Don't know what it is for, it is in V2Calibration.gcode
  4090. */
  4091. case 88:
  4092. break;
  4093. #endif // ENABLE_MESH_BED_LEVELING
  4094. case 90: // G90
  4095. relative_mode = false;
  4096. break;
  4097. case 91: // G91
  4098. relative_mode = true;
  4099. break;
  4100. case 92: // G92
  4101. if(!code_seen(axis_codes[E_AXIS]))
  4102. st_synchronize();
  4103. for(int8_t i=0; i < NUM_AXIS; i++) {
  4104. if(code_seen(axis_codes[i])) {
  4105. if(i == E_AXIS) {
  4106. current_position[i] = code_value();
  4107. plan_set_e_position(current_position[E_AXIS]);
  4108. }
  4109. else {
  4110. current_position[i] = code_value()+cs.add_homing[i];
  4111. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  4112. }
  4113. }
  4114. }
  4115. break;
  4116. case 98: //! G98 (activate farm mode)
  4117. farm_mode = 1;
  4118. PingTime = millis();
  4119. eeprom_update_byte((unsigned char *)EEPROM_FARM_MODE, farm_mode);
  4120. EEPROM_save_B(EEPROM_FARM_NUMBER, &farm_no);
  4121. SilentModeMenu = SILENT_MODE_OFF;
  4122. eeprom_update_byte((unsigned char *)EEPROM_SILENT, SilentModeMenu);
  4123. break;
  4124. case 99: //! G99 (deactivate farm mode)
  4125. farm_mode = 0;
  4126. lcd_printer_connected();
  4127. eeprom_update_byte((unsigned char *)EEPROM_FARM_MODE, farm_mode);
  4128. lcd_update(2);
  4129. break;
  4130. default:
  4131. printf_P(PSTR("Unknown G code: %s \n"), cmdbuffer + bufindr + CMDHDRSIZE);
  4132. }
  4133. // printf_P(_N("END G-CODE=%u\n"), gcode_in_progress);
  4134. gcode_in_progress = 0;
  4135. } // end if(code_seen('G'))
  4136. else if(code_seen('M'))
  4137. {
  4138. int index;
  4139. for (index = 1; *(strchr_pointer + index) == ' ' || *(strchr_pointer + index) == '\t'; index++);
  4140. /*for (++strchr_pointer; *strchr_pointer == ' ' || *strchr_pointer == '\t'; ++strchr_pointer);*/
  4141. if (*(strchr_pointer+index) < '0' || *(strchr_pointer+index) > '9') {
  4142. printf_P(PSTR("Invalid M code: %s \n"), cmdbuffer + bufindr + CMDHDRSIZE);
  4143. } else
  4144. {
  4145. mcode_in_progress = (int)code_value();
  4146. // printf_P(_N("BEGIN M-CODE=%u\n"), mcode_in_progress);
  4147. switch(mcode_in_progress)
  4148. {
  4149. case 0: // M0 - Unconditional stop - Wait for user button press on LCD
  4150. case 1: // M1 - Conditional stop - Wait for user button press on LCD
  4151. {
  4152. char *src = strchr_pointer + 2;
  4153. codenum = 0;
  4154. bool hasP = false, hasS = false;
  4155. if (code_seen('P')) {
  4156. codenum = code_value(); // milliseconds to wait
  4157. hasP = codenum > 0;
  4158. }
  4159. if (code_seen('S')) {
  4160. codenum = code_value() * 1000; // seconds to wait
  4161. hasS = codenum > 0;
  4162. }
  4163. starpos = strchr(src, '*');
  4164. if (starpos != NULL) *(starpos) = '\0';
  4165. while (*src == ' ') ++src;
  4166. if (!hasP && !hasS && *src != '\0') {
  4167. lcd_setstatus(src);
  4168. } else {
  4169. LCD_MESSAGERPGM(_i("Wait for user..."));////MSG_USERWAIT c=0 r=0
  4170. }
  4171. lcd_ignore_click(); //call lcd_ignore_click aslo for else ???
  4172. st_synchronize();
  4173. previous_millis_cmd = millis();
  4174. if (codenum > 0){
  4175. codenum += millis(); // keep track of when we started waiting
  4176. KEEPALIVE_STATE(PAUSED_FOR_USER);
  4177. while(millis() < codenum && !lcd_clicked()){
  4178. manage_heater();
  4179. manage_inactivity(true);
  4180. lcd_update(0);
  4181. }
  4182. KEEPALIVE_STATE(IN_HANDLER);
  4183. lcd_ignore_click(false);
  4184. }else{
  4185. KEEPALIVE_STATE(PAUSED_FOR_USER);
  4186. while(!lcd_clicked()){
  4187. manage_heater();
  4188. manage_inactivity(true);
  4189. lcd_update(0);
  4190. }
  4191. KEEPALIVE_STATE(IN_HANDLER);
  4192. }
  4193. if (IS_SD_PRINTING)
  4194. LCD_MESSAGERPGM(_T(MSG_RESUMING_PRINT));
  4195. else
  4196. LCD_MESSAGERPGM(_T(WELCOME_MSG));
  4197. }
  4198. break;
  4199. case 17:
  4200. LCD_MESSAGERPGM(_i("No move."));////MSG_NO_MOVE c=0 r=0
  4201. enable_x();
  4202. enable_y();
  4203. enable_z();
  4204. enable_e0();
  4205. enable_e1();
  4206. enable_e2();
  4207. break;
  4208. #ifdef SDSUPPORT
  4209. case 20: // M20 - list SD card
  4210. SERIAL_PROTOCOLLNRPGM(_N("Begin file list"));////MSG_BEGIN_FILE_LIST c=0 r=0
  4211. card.ls();
  4212. SERIAL_PROTOCOLLNRPGM(_N("End file list"));////MSG_END_FILE_LIST c=0 r=0
  4213. break;
  4214. case 21: // M21 - init SD card
  4215. card.initsd();
  4216. break;
  4217. case 22: //M22 - release SD card
  4218. card.release();
  4219. break;
  4220. case 23: //M23 - Select file
  4221. starpos = (strchr(strchr_pointer + 4,'*'));
  4222. if(starpos!=NULL)
  4223. *(starpos)='\0';
  4224. card.openFile(strchr_pointer + 4,true);
  4225. break;
  4226. case 24: //M24 - Start SD print
  4227. if (!card.paused)
  4228. failstats_reset_print();
  4229. card.startFileprint();
  4230. starttime=millis();
  4231. break;
  4232. case 25: //M25 - Pause SD print
  4233. card.pauseSDPrint();
  4234. break;
  4235. case 26: //M26 - Set SD index
  4236. if(card.cardOK && code_seen('S')) {
  4237. card.setIndex(code_value_long());
  4238. }
  4239. break;
  4240. case 27: //M27 - Get SD status
  4241. card.getStatus();
  4242. break;
  4243. case 28: //M28 - Start SD write
  4244. starpos = (strchr(strchr_pointer + 4,'*'));
  4245. if(starpos != NULL){
  4246. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  4247. strchr_pointer = strchr(npos,' ') + 1;
  4248. *(starpos) = '\0';
  4249. }
  4250. card.openFile(strchr_pointer+4,false);
  4251. break;
  4252. case 29: //M29 - Stop SD write
  4253. //processed in write to file routine above
  4254. //card,saving = false;
  4255. break;
  4256. case 30: //M30 <filename> Delete File
  4257. if (card.cardOK){
  4258. card.closefile();
  4259. starpos = (strchr(strchr_pointer + 4,'*'));
  4260. if(starpos != NULL){
  4261. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  4262. strchr_pointer = strchr(npos,' ') + 1;
  4263. *(starpos) = '\0';
  4264. }
  4265. card.removeFile(strchr_pointer + 4);
  4266. }
  4267. break;
  4268. case 32: //M32 - Select file and start SD print
  4269. {
  4270. if(card.sdprinting) {
  4271. st_synchronize();
  4272. }
  4273. starpos = (strchr(strchr_pointer + 4,'*'));
  4274. char* namestartpos = (strchr(strchr_pointer + 4,'!')); //find ! to indicate filename string start.
  4275. if(namestartpos==NULL)
  4276. {
  4277. namestartpos=strchr_pointer + 4; //default name position, 4 letters after the M
  4278. }
  4279. else
  4280. namestartpos++; //to skip the '!'
  4281. if(starpos!=NULL)
  4282. *(starpos)='\0';
  4283. bool call_procedure=(code_seen('P'));
  4284. if(strchr_pointer>namestartpos)
  4285. call_procedure=false; //false alert, 'P' found within filename
  4286. if( card.cardOK )
  4287. {
  4288. card.openFile(namestartpos,true,!call_procedure);
  4289. if(code_seen('S'))
  4290. if(strchr_pointer<namestartpos) //only if "S" is occuring _before_ the filename
  4291. card.setIndex(code_value_long());
  4292. card.startFileprint();
  4293. if(!call_procedure)
  4294. starttime=millis(); //procedure calls count as normal print time.
  4295. }
  4296. } break;
  4297. case 928: //M928 - Start SD write
  4298. starpos = (strchr(strchr_pointer + 5,'*'));
  4299. if(starpos != NULL){
  4300. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  4301. strchr_pointer = strchr(npos,' ') + 1;
  4302. *(starpos) = '\0';
  4303. }
  4304. card.openLogFile(strchr_pointer+5);
  4305. break;
  4306. #endif //SDSUPPORT
  4307. case 31: //M31 take time since the start of the SD print or an M109 command
  4308. {
  4309. stoptime=millis();
  4310. char time[30];
  4311. unsigned long t=(stoptime-starttime)/1000;
  4312. int sec,min;
  4313. min=t/60;
  4314. sec=t%60;
  4315. sprintf_P(time, PSTR("%i min, %i sec"), min, sec);
  4316. SERIAL_ECHO_START;
  4317. SERIAL_ECHOLN(time);
  4318. lcd_setstatus(time);
  4319. autotempShutdown();
  4320. }
  4321. break;
  4322. case 42: //M42 -Change pin status via gcode
  4323. if (code_seen('S'))
  4324. {
  4325. int pin_status = code_value();
  4326. int pin_number = LED_PIN;
  4327. if (code_seen('P') && pin_status >= 0 && pin_status <= 255)
  4328. pin_number = code_value();
  4329. for(int8_t i = 0; i < (int8_t)(sizeof(sensitive_pins)/sizeof(int)); i++)
  4330. {
  4331. if (sensitive_pins[i] == pin_number)
  4332. {
  4333. pin_number = -1;
  4334. break;
  4335. }
  4336. }
  4337. #if defined(FAN_PIN) && FAN_PIN > -1
  4338. if (pin_number == FAN_PIN)
  4339. fanSpeed = pin_status;
  4340. #endif
  4341. if (pin_number > -1)
  4342. {
  4343. pinMode(pin_number, OUTPUT);
  4344. digitalWrite(pin_number, pin_status);
  4345. analogWrite(pin_number, pin_status);
  4346. }
  4347. }
  4348. break;
  4349. case 44: //! M44: Prusa3D: Reset the bed skew and offset calibration.
  4350. // Reset the baby step value and the baby step applied flag.
  4351. calibration_status_store(CALIBRATION_STATUS_ASSEMBLED);
  4352. eeprom_update_word((uint16_t*)EEPROM_BABYSTEP_Z, 0);
  4353. // Reset the skew and offset in both RAM and EEPROM.
  4354. reset_bed_offset_and_skew();
  4355. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  4356. // the planner will not perform any adjustments in the XY plane.
  4357. // Wait for the motors to stop and update the current position with the absolute values.
  4358. world2machine_revert_to_uncorrected();
  4359. break;
  4360. case 45: //! M45: Prusa3D: bed skew and offset with manual Z up
  4361. {
  4362. int8_t verbosity_level = 0;
  4363. bool only_Z = code_seen('Z');
  4364. #ifdef SUPPORT_VERBOSITY
  4365. if (code_seen('V'))
  4366. {
  4367. // Just 'V' without a number counts as V1.
  4368. char c = strchr_pointer[1];
  4369. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  4370. }
  4371. #endif //SUPPORT_VERBOSITY
  4372. gcode_M45(only_Z, verbosity_level);
  4373. }
  4374. break;
  4375. /*
  4376. case 46:
  4377. {
  4378. // M46: Prusa3D: Show the assigned IP address.
  4379. uint8_t ip[4];
  4380. bool hasIP = card.ToshibaFlashAir_GetIP(ip);
  4381. if (hasIP) {
  4382. SERIAL_ECHOPGM("Toshiba FlashAir current IP: ");
  4383. SERIAL_ECHO(int(ip[0]));
  4384. SERIAL_ECHOPGM(".");
  4385. SERIAL_ECHO(int(ip[1]));
  4386. SERIAL_ECHOPGM(".");
  4387. SERIAL_ECHO(int(ip[2]));
  4388. SERIAL_ECHOPGM(".");
  4389. SERIAL_ECHO(int(ip[3]));
  4390. SERIAL_ECHOLNPGM("");
  4391. } else {
  4392. SERIAL_ECHOLNPGM("Toshiba FlashAir GetIP failed");
  4393. }
  4394. break;
  4395. }
  4396. */
  4397. case 47:
  4398. //! M47: Prusa3D: Show end stops dialog on the display.
  4399. KEEPALIVE_STATE(PAUSED_FOR_USER);
  4400. lcd_diag_show_end_stops();
  4401. KEEPALIVE_STATE(IN_HANDLER);
  4402. break;
  4403. #if 0
  4404. case 48: //! M48: scan the bed induction sensor points, print the sensor trigger coordinates to the serial line for visualization on the PC.
  4405. {
  4406. // Disable the default update procedure of the display. We will do a modal dialog.
  4407. lcd_update_enable(false);
  4408. // Let the planner use the uncorrected coordinates.
  4409. mbl.reset();
  4410. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  4411. // the planner will not perform any adjustments in the XY plane.
  4412. // Wait for the motors to stop and update the current position with the absolute values.
  4413. world2machine_revert_to_uncorrected();
  4414. // Move the print head close to the bed.
  4415. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4416. 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);
  4417. st_synchronize();
  4418. // Home in the XY plane.
  4419. set_destination_to_current();
  4420. int l_feedmultiply = setup_for_endstop_move();
  4421. home_xy();
  4422. int8_t verbosity_level = 0;
  4423. if (code_seen('V')) {
  4424. // Just 'V' without a number counts as V1.
  4425. char c = strchr_pointer[1];
  4426. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  4427. }
  4428. bool success = scan_bed_induction_points(verbosity_level);
  4429. clean_up_after_endstop_move(l_feedmultiply);
  4430. // Print head up.
  4431. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  4432. 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);
  4433. st_synchronize();
  4434. lcd_update_enable(true);
  4435. break;
  4436. }
  4437. #endif
  4438. #ifdef ENABLE_AUTO_BED_LEVELING
  4439. #ifdef Z_PROBE_REPEATABILITY_TEST
  4440. //! M48 Z-Probe repeatability measurement function.
  4441. //!
  4442. //! Usage: M48 <n #_samples> <X X_position_for_samples> <Y Y_position_for_samples> <V Verbose_Level> <L legs_of_movement_prior_to_doing_probe>
  4443. //!
  4444. //! This function assumes the bed has been homed. Specificaly, that a G28 command
  4445. //! as been issued prior to invoking the M48 Z-Probe repeatability measurement function.
  4446. //! Any information generated by a prior G29 Bed leveling command will be lost and need to be
  4447. //! regenerated.
  4448. //!
  4449. //! The number of samples will default to 10 if not specified. You can use upper or lower case
  4450. //! letters for any of the options EXCEPT n. n must be in lower case because Marlin uses a capital
  4451. //! N for its communication protocol and will get horribly confused if you send it a capital N.
  4452. //!
  4453. case 48: // M48 Z-Probe repeatability
  4454. {
  4455. #if Z_MIN_PIN == -1
  4456. #error "You must have a Z_MIN endstop in order to enable calculation of Z-Probe repeatability."
  4457. #endif
  4458. double sum=0.0;
  4459. double mean=0.0;
  4460. double sigma=0.0;
  4461. double sample_set[50];
  4462. int verbose_level=1, n=0, j, n_samples = 10, n_legs=0;
  4463. double X_current, Y_current, Z_current;
  4464. double X_probe_location, Y_probe_location, Z_start_location, ext_position;
  4465. if (code_seen('V') || code_seen('v')) {
  4466. verbose_level = code_value();
  4467. if (verbose_level<0 || verbose_level>4 ) {
  4468. SERIAL_PROTOCOLPGM("?Verbose Level not plausable.\n");
  4469. goto Sigma_Exit;
  4470. }
  4471. }
  4472. if (verbose_level > 0) {
  4473. SERIAL_PROTOCOLPGM("M48 Z-Probe Repeatability test. Version 2.00\n");
  4474. SERIAL_PROTOCOLPGM("Full support at: http://3dprintboard.com/forum.php\n");
  4475. }
  4476. if (code_seen('n')) {
  4477. n_samples = code_value();
  4478. if (n_samples<4 || n_samples>50 ) {
  4479. SERIAL_PROTOCOLPGM("?Specified sample size not plausable.\n");
  4480. goto Sigma_Exit;
  4481. }
  4482. }
  4483. X_current = X_probe_location = st_get_position_mm(X_AXIS);
  4484. Y_current = Y_probe_location = st_get_position_mm(Y_AXIS);
  4485. Z_current = st_get_position_mm(Z_AXIS);
  4486. Z_start_location = st_get_position_mm(Z_AXIS) + Z_RAISE_BEFORE_PROBING;
  4487. ext_position = st_get_position_mm(E_AXIS);
  4488. if (code_seen('X') || code_seen('x') ) {
  4489. X_probe_location = code_value() - X_PROBE_OFFSET_FROM_EXTRUDER;
  4490. if (X_probe_location<X_MIN_POS || X_probe_location>X_MAX_POS ) {
  4491. SERIAL_PROTOCOLPGM("?Specified X position out of range.\n");
  4492. goto Sigma_Exit;
  4493. }
  4494. }
  4495. if (code_seen('Y') || code_seen('y') ) {
  4496. Y_probe_location = code_value() - Y_PROBE_OFFSET_FROM_EXTRUDER;
  4497. if (Y_probe_location<Y_MIN_POS || Y_probe_location>Y_MAX_POS ) {
  4498. SERIAL_PROTOCOLPGM("?Specified Y position out of range.\n");
  4499. goto Sigma_Exit;
  4500. }
  4501. }
  4502. if (code_seen('L') || code_seen('l') ) {
  4503. n_legs = code_value();
  4504. if ( n_legs==1 )
  4505. n_legs = 2;
  4506. if ( n_legs<0 || n_legs>15 ) {
  4507. SERIAL_PROTOCOLPGM("?Specified number of legs in movement not plausable.\n");
  4508. goto Sigma_Exit;
  4509. }
  4510. }
  4511. //
  4512. // Do all the preliminary setup work. First raise the probe.
  4513. //
  4514. st_synchronize();
  4515. plan_bed_level_matrix.set_to_identity();
  4516. plan_buffer_line( X_current, Y_current, Z_start_location,
  4517. ext_position,
  4518. homing_feedrate[Z_AXIS]/60,
  4519. active_extruder);
  4520. st_synchronize();
  4521. //
  4522. // Now get everything to the specified probe point So we can safely do a probe to
  4523. // get us close to the bed. If the Z-Axis is far from the bed, we don't want to
  4524. // use that as a starting point for each probe.
  4525. //
  4526. if (verbose_level > 2)
  4527. SERIAL_PROTOCOL("Positioning probe for the test.\n");
  4528. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  4529. ext_position,
  4530. homing_feedrate[X_AXIS]/60,
  4531. active_extruder);
  4532. st_synchronize();
  4533. current_position[X_AXIS] = X_current = st_get_position_mm(X_AXIS);
  4534. current_position[Y_AXIS] = Y_current = st_get_position_mm(Y_AXIS);
  4535. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  4536. current_position[E_AXIS] = ext_position = st_get_position_mm(E_AXIS);
  4537. //
  4538. // OK, do the inital probe to get us close to the bed.
  4539. // Then retrace the right amount and use that in subsequent probes
  4540. //
  4541. int l_feedmultiply = setup_for_endstop_move();
  4542. run_z_probe();
  4543. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  4544. Z_start_location = st_get_position_mm(Z_AXIS) + Z_RAISE_BEFORE_PROBING;
  4545. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  4546. ext_position,
  4547. homing_feedrate[X_AXIS]/60,
  4548. active_extruder);
  4549. st_synchronize();
  4550. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  4551. for( n=0; n<n_samples; n++) {
  4552. do_blocking_move_to( X_probe_location, Y_probe_location, Z_start_location); // Make sure we are at the probe location
  4553. if ( n_legs) {
  4554. double radius=0.0, theta=0.0, x_sweep, y_sweep;
  4555. int rotational_direction, l;
  4556. rotational_direction = (unsigned long) millis() & 0x0001; // clockwise or counter clockwise
  4557. radius = (unsigned long) millis() % (long) (X_MAX_LENGTH/4); // limit how far out to go
  4558. theta = (float) ((unsigned long) millis() % (long) 360) / (360./(2*3.1415926)); // turn into radians
  4559. //SERIAL_ECHOPAIR("starting radius: ",radius);
  4560. //SERIAL_ECHOPAIR(" theta: ",theta);
  4561. //SERIAL_ECHOPAIR(" direction: ",rotational_direction);
  4562. //SERIAL_PROTOCOLLNPGM("");
  4563. for( l=0; l<n_legs-1; l++) {
  4564. if (rotational_direction==1)
  4565. theta += (float) ((unsigned long) millis() % (long) 20) / (360.0/(2*3.1415926)); // turn into radians
  4566. else
  4567. theta -= (float) ((unsigned long) millis() % (long) 20) / (360.0/(2*3.1415926)); // turn into radians
  4568. radius += (float) ( ((long) ((unsigned long) millis() % (long) 10)) - 5);
  4569. if ( radius<0.0 )
  4570. radius = -radius;
  4571. X_current = X_probe_location + cos(theta) * radius;
  4572. Y_current = Y_probe_location + sin(theta) * radius;
  4573. if ( X_current<X_MIN_POS) // Make sure our X & Y are sane
  4574. X_current = X_MIN_POS;
  4575. if ( X_current>X_MAX_POS)
  4576. X_current = X_MAX_POS;
  4577. if ( Y_current<Y_MIN_POS) // Make sure our X & Y are sane
  4578. Y_current = Y_MIN_POS;
  4579. if ( Y_current>Y_MAX_POS)
  4580. Y_current = Y_MAX_POS;
  4581. if (verbose_level>3 ) {
  4582. SERIAL_ECHOPAIR("x: ", X_current);
  4583. SERIAL_ECHOPAIR("y: ", Y_current);
  4584. SERIAL_PROTOCOLLNPGM("");
  4585. }
  4586. do_blocking_move_to( X_current, Y_current, Z_current );
  4587. }
  4588. do_blocking_move_to( X_probe_location, Y_probe_location, Z_start_location); // Go back to the probe location
  4589. }
  4590. int l_feedmultiply = setup_for_endstop_move();
  4591. run_z_probe();
  4592. sample_set[n] = current_position[Z_AXIS];
  4593. //
  4594. // Get the current mean for the data points we have so far
  4595. //
  4596. sum=0.0;
  4597. for( j=0; j<=n; j++) {
  4598. sum = sum + sample_set[j];
  4599. }
  4600. mean = sum / (double (n+1));
  4601. //
  4602. // Now, use that mean to calculate the standard deviation for the
  4603. // data points we have so far
  4604. //
  4605. sum=0.0;
  4606. for( j=0; j<=n; j++) {
  4607. sum = sum + (sample_set[j]-mean) * (sample_set[j]-mean);
  4608. }
  4609. sigma = sqrt( sum / (double (n+1)) );
  4610. if (verbose_level > 1) {
  4611. SERIAL_PROTOCOL(n+1);
  4612. SERIAL_PROTOCOL(" of ");
  4613. SERIAL_PROTOCOL(n_samples);
  4614. SERIAL_PROTOCOLPGM(" z: ");
  4615. SERIAL_PROTOCOL_F(current_position[Z_AXIS], 6);
  4616. }
  4617. if (verbose_level > 2) {
  4618. SERIAL_PROTOCOL(" mean: ");
  4619. SERIAL_PROTOCOL_F(mean,6);
  4620. SERIAL_PROTOCOL(" sigma: ");
  4621. SERIAL_PROTOCOL_F(sigma,6);
  4622. }
  4623. if (verbose_level > 0)
  4624. SERIAL_PROTOCOLPGM("\n");
  4625. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  4626. current_position[E_AXIS], homing_feedrate[Z_AXIS]/60, active_extruder);
  4627. st_synchronize();
  4628. }
  4629. delay(1000);
  4630. clean_up_after_endstop_move(l_feedmultiply);
  4631. // enable_endstops(true);
  4632. if (verbose_level > 0) {
  4633. SERIAL_PROTOCOLPGM("Mean: ");
  4634. SERIAL_PROTOCOL_F(mean, 6);
  4635. SERIAL_PROTOCOLPGM("\n");
  4636. }
  4637. SERIAL_PROTOCOLPGM("Standard Deviation: ");
  4638. SERIAL_PROTOCOL_F(sigma, 6);
  4639. SERIAL_PROTOCOLPGM("\n\n");
  4640. Sigma_Exit:
  4641. break;
  4642. }
  4643. #endif // Z_PROBE_REPEATABILITY_TEST
  4644. #endif // ENABLE_AUTO_BED_LEVELING
  4645. case 73: //M73 show percent done and time remaining
  4646. if(code_seen('P')) print_percent_done_normal = code_value();
  4647. if(code_seen('R')) print_time_remaining_normal = code_value();
  4648. if(code_seen('Q')) print_percent_done_silent = code_value();
  4649. if(code_seen('S')) print_time_remaining_silent = code_value();
  4650. {
  4651. const char* _msg_mode_done_remain = _N("%S MODE: Percent done: %d; print time remaining in mins: %d\n");
  4652. printf_P(_msg_mode_done_remain, _N("NORMAL"), int(print_percent_done_normal), print_time_remaining_normal);
  4653. printf_P(_msg_mode_done_remain, _N("SILENT"), int(print_percent_done_silent), print_time_remaining_silent);
  4654. }
  4655. break;
  4656. case 104: // M104
  4657. {
  4658. uint8_t extruder;
  4659. if(setTargetedHotend(104,extruder)){
  4660. break;
  4661. }
  4662. if (code_seen('S'))
  4663. {
  4664. setTargetHotendSafe(code_value(), extruder);
  4665. }
  4666. setWatch();
  4667. break;
  4668. }
  4669. case 112: // M112 -Emergency Stop
  4670. kill(_n(""), 3);
  4671. break;
  4672. case 140: // M140 set bed temp
  4673. if (code_seen('S')) setTargetBed(code_value());
  4674. break;
  4675. case 105 : // M105
  4676. {
  4677. uint8_t extruder;
  4678. if(setTargetedHotend(105, extruder)){
  4679. break;
  4680. }
  4681. #if defined(TEMP_0_PIN) && TEMP_0_PIN > -1
  4682. SERIAL_PROTOCOLPGM("ok T:");
  4683. SERIAL_PROTOCOL_F(degHotend(extruder),1);
  4684. SERIAL_PROTOCOLPGM(" /");
  4685. SERIAL_PROTOCOL_F(degTargetHotend(extruder),1);
  4686. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  4687. SERIAL_PROTOCOLPGM(" B:");
  4688. SERIAL_PROTOCOL_F(degBed(),1);
  4689. SERIAL_PROTOCOLPGM(" /");
  4690. SERIAL_PROTOCOL_F(degTargetBed(),1);
  4691. #endif //TEMP_BED_PIN
  4692. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  4693. SERIAL_PROTOCOLPGM(" T");
  4694. SERIAL_PROTOCOL(cur_extruder);
  4695. SERIAL_PROTOCOLPGM(":");
  4696. SERIAL_PROTOCOL_F(degHotend(cur_extruder),1);
  4697. SERIAL_PROTOCOLPGM(" /");
  4698. SERIAL_PROTOCOL_F(degTargetHotend(cur_extruder),1);
  4699. }
  4700. #else
  4701. SERIAL_ERROR_START;
  4702. SERIAL_ERRORLNRPGM(_i("No thermistors - no temperature"));////MSG_ERR_NO_THERMISTORS c=0 r=0
  4703. #endif
  4704. SERIAL_PROTOCOLPGM(" @:");
  4705. #ifdef EXTRUDER_WATTS
  4706. SERIAL_PROTOCOL((EXTRUDER_WATTS * getHeaterPower(tmp_extruder))/127);
  4707. SERIAL_PROTOCOLPGM("W");
  4708. #else
  4709. SERIAL_PROTOCOL(getHeaterPower(extruder));
  4710. #endif
  4711. SERIAL_PROTOCOLPGM(" B@:");
  4712. #ifdef BED_WATTS
  4713. SERIAL_PROTOCOL((BED_WATTS * getHeaterPower(-1))/127);
  4714. SERIAL_PROTOCOLPGM("W");
  4715. #else
  4716. SERIAL_PROTOCOL(getHeaterPower(-1));
  4717. #endif
  4718. #ifdef PINDA_THERMISTOR
  4719. SERIAL_PROTOCOLPGM(" P:");
  4720. SERIAL_PROTOCOL_F(current_temperature_pinda,1);
  4721. #endif //PINDA_THERMISTOR
  4722. #ifdef AMBIENT_THERMISTOR
  4723. SERIAL_PROTOCOLPGM(" A:");
  4724. SERIAL_PROTOCOL_F(current_temperature_ambient,1);
  4725. #endif //AMBIENT_THERMISTOR
  4726. #ifdef SHOW_TEMP_ADC_VALUES
  4727. {float raw = 0.0;
  4728. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  4729. SERIAL_PROTOCOLPGM(" ADC B:");
  4730. SERIAL_PROTOCOL_F(degBed(),1);
  4731. SERIAL_PROTOCOLPGM("C->");
  4732. raw = rawBedTemp();
  4733. SERIAL_PROTOCOL_F(raw/OVERSAMPLENR,5);
  4734. SERIAL_PROTOCOLPGM(" Rb->");
  4735. SERIAL_PROTOCOL_F(100 * (1 + (PtA * (raw/OVERSAMPLENR)) + (PtB * sq((raw/OVERSAMPLENR)))), 5);
  4736. SERIAL_PROTOCOLPGM(" Rxb->");
  4737. SERIAL_PROTOCOL_F(raw, 5);
  4738. #endif
  4739. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  4740. SERIAL_PROTOCOLPGM(" T");
  4741. SERIAL_PROTOCOL(cur_extruder);
  4742. SERIAL_PROTOCOLPGM(":");
  4743. SERIAL_PROTOCOL_F(degHotend(cur_extruder),1);
  4744. SERIAL_PROTOCOLPGM("C->");
  4745. raw = rawHotendTemp(cur_extruder);
  4746. SERIAL_PROTOCOL_F(raw/OVERSAMPLENR,5);
  4747. SERIAL_PROTOCOLPGM(" Rt");
  4748. SERIAL_PROTOCOL(cur_extruder);
  4749. SERIAL_PROTOCOLPGM("->");
  4750. SERIAL_PROTOCOL_F(100 * (1 + (PtA * (raw/OVERSAMPLENR)) + (PtB * sq((raw/OVERSAMPLENR)))), 5);
  4751. SERIAL_PROTOCOLPGM(" Rx");
  4752. SERIAL_PROTOCOL(cur_extruder);
  4753. SERIAL_PROTOCOLPGM("->");
  4754. SERIAL_PROTOCOL_F(raw, 5);
  4755. }}
  4756. #endif
  4757. SERIAL_PROTOCOLLN("");
  4758. KEEPALIVE_STATE(NOT_BUSY);
  4759. return;
  4760. break;
  4761. }
  4762. case 109:
  4763. {// M109 - Wait for extruder heater to reach target.
  4764. uint8_t extruder;
  4765. if(setTargetedHotend(109, extruder)){
  4766. break;
  4767. }
  4768. LCD_MESSAGERPGM(_T(MSG_HEATING));
  4769. heating_status = 1;
  4770. if (farm_mode) { prusa_statistics(1); };
  4771. #ifdef AUTOTEMP
  4772. autotemp_enabled=false;
  4773. #endif
  4774. if (code_seen('S')) {
  4775. setTargetHotendSafe(code_value(), extruder);
  4776. CooldownNoWait = true;
  4777. } else if (code_seen('R')) {
  4778. setTargetHotendSafe(code_value(), extruder);
  4779. CooldownNoWait = false;
  4780. }
  4781. #ifdef AUTOTEMP
  4782. if (code_seen('S')) autotemp_min=code_value();
  4783. if (code_seen('B')) autotemp_max=code_value();
  4784. if (code_seen('F'))
  4785. {
  4786. autotemp_factor=code_value();
  4787. autotemp_enabled=true;
  4788. }
  4789. #endif
  4790. setWatch();
  4791. codenum = millis();
  4792. /* See if we are heating up or cooling down */
  4793. target_direction = isHeatingHotend(extruder); // true if heating, false if cooling
  4794. KEEPALIVE_STATE(NOT_BUSY);
  4795. cancel_heatup = false;
  4796. wait_for_heater(codenum, extruder); //loops until target temperature is reached
  4797. LCD_MESSAGERPGM(_T(MSG_HEATING_COMPLETE));
  4798. KEEPALIVE_STATE(IN_HANDLER);
  4799. heating_status = 2;
  4800. if (farm_mode) { prusa_statistics(2); };
  4801. //starttime=millis();
  4802. previous_millis_cmd = millis();
  4803. }
  4804. break;
  4805. case 190: // M190 - Wait for bed heater to reach target.
  4806. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  4807. LCD_MESSAGERPGM(_T(MSG_BED_HEATING));
  4808. heating_status = 3;
  4809. if (farm_mode) { prusa_statistics(1); };
  4810. if (code_seen('S'))
  4811. {
  4812. setTargetBed(code_value());
  4813. CooldownNoWait = true;
  4814. }
  4815. else if (code_seen('R'))
  4816. {
  4817. setTargetBed(code_value());
  4818. CooldownNoWait = false;
  4819. }
  4820. codenum = millis();
  4821. cancel_heatup = false;
  4822. target_direction = isHeatingBed(); // true if heating, false if cooling
  4823. KEEPALIVE_STATE(NOT_BUSY);
  4824. while ( (target_direction)&&(!cancel_heatup) ? (isHeatingBed()) : (isCoolingBed()&&(CooldownNoWait==false)) )
  4825. {
  4826. if(( millis() - codenum) > 1000 ) //Print Temp Reading every 1 second while heating up.
  4827. {
  4828. if (!farm_mode) {
  4829. float tt = degHotend(active_extruder);
  4830. SERIAL_PROTOCOLPGM("T:");
  4831. SERIAL_PROTOCOL(tt);
  4832. SERIAL_PROTOCOLPGM(" E:");
  4833. SERIAL_PROTOCOL((int)active_extruder);
  4834. SERIAL_PROTOCOLPGM(" B:");
  4835. SERIAL_PROTOCOL_F(degBed(), 1);
  4836. SERIAL_PROTOCOLLN("");
  4837. }
  4838. codenum = millis();
  4839. }
  4840. manage_heater();
  4841. manage_inactivity();
  4842. lcd_update(0);
  4843. }
  4844. LCD_MESSAGERPGM(_T(MSG_BED_DONE));
  4845. KEEPALIVE_STATE(IN_HANDLER);
  4846. heating_status = 4;
  4847. previous_millis_cmd = millis();
  4848. #endif
  4849. break;
  4850. #if defined(FAN_PIN) && FAN_PIN > -1
  4851. case 106: //!M106 Sxxx Fan On S<speed> 0 .. 255
  4852. if (code_seen('S')){
  4853. fanSpeed=constrain(code_value(),0,255);
  4854. }
  4855. else {
  4856. fanSpeed=255;
  4857. }
  4858. break;
  4859. case 107: //M107 Fan Off
  4860. fanSpeed = 0;
  4861. break;
  4862. #endif //FAN_PIN
  4863. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  4864. case 80: // M80 - Turn on Power Supply
  4865. SET_OUTPUT(PS_ON_PIN); //GND
  4866. WRITE(PS_ON_PIN, PS_ON_AWAKE);
  4867. // If you have a switch on suicide pin, this is useful
  4868. // if you want to start another print with suicide feature after
  4869. // a print without suicide...
  4870. #if defined SUICIDE_PIN && SUICIDE_PIN > -1
  4871. SET_OUTPUT(SUICIDE_PIN);
  4872. WRITE(SUICIDE_PIN, HIGH);
  4873. #endif
  4874. powersupply = true;
  4875. LCD_MESSAGERPGM(_T(WELCOME_MSG));
  4876. lcd_update(0);
  4877. break;
  4878. #endif
  4879. case 81: // M81 - Turn off Power Supply
  4880. disable_heater();
  4881. st_synchronize();
  4882. disable_e0();
  4883. disable_e1();
  4884. disable_e2();
  4885. finishAndDisableSteppers();
  4886. fanSpeed = 0;
  4887. delay(1000); // Wait a little before to switch off
  4888. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  4889. st_synchronize();
  4890. suicide();
  4891. #elif defined(PS_ON_PIN) && PS_ON_PIN > -1
  4892. SET_OUTPUT(PS_ON_PIN);
  4893. WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  4894. #endif
  4895. powersupply = false;
  4896. LCD_MESSAGERPGM(CAT4(CUSTOM_MENDEL_NAME,PSTR(" "),MSG_OFF,PSTR(".")));
  4897. lcd_update(0);
  4898. break;
  4899. case 82:
  4900. axis_relative_modes[3] = false;
  4901. break;
  4902. case 83:
  4903. axis_relative_modes[3] = true;
  4904. break;
  4905. case 18: //compatibility
  4906. case 84: // M84
  4907. if(code_seen('S')){
  4908. stepper_inactive_time = code_value() * 1000;
  4909. }
  4910. else
  4911. {
  4912. 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])));
  4913. if(all_axis)
  4914. {
  4915. st_synchronize();
  4916. disable_e0();
  4917. disable_e1();
  4918. disable_e2();
  4919. finishAndDisableSteppers();
  4920. }
  4921. else
  4922. {
  4923. st_synchronize();
  4924. if (code_seen('X')) disable_x();
  4925. if (code_seen('Y')) disable_y();
  4926. if (code_seen('Z')) disable_z();
  4927. #if ((E0_ENABLE_PIN != X_ENABLE_PIN) && (E1_ENABLE_PIN != Y_ENABLE_PIN)) // Only enable on boards that have seperate ENABLE_PINS
  4928. if (code_seen('E')) {
  4929. disable_e0();
  4930. disable_e1();
  4931. disable_e2();
  4932. }
  4933. #endif
  4934. }
  4935. }
  4936. //in the end of print set estimated time to end of print and extruders used during print to default values for next print
  4937. print_time_remaining_init();
  4938. snmm_filaments_used = 0;
  4939. break;
  4940. case 85: // M85
  4941. if(code_seen('S')) {
  4942. max_inactive_time = code_value() * 1000;
  4943. }
  4944. break;
  4945. #ifdef SAFETYTIMER
  4946. case 86: // M86 - set safety timer expiration time in seconds; M86 S0 will disable safety timer
  4947. //when safety timer expires heatbed and nozzle target temperatures are set to zero
  4948. if (code_seen('S')) {
  4949. safetytimer_inactive_time = code_value() * 1000;
  4950. safetyTimer.start();
  4951. }
  4952. break;
  4953. #endif
  4954. case 92: // M92
  4955. for(int8_t i=0; i < NUM_AXIS; i++)
  4956. {
  4957. if(code_seen(axis_codes[i]))
  4958. {
  4959. if(i == 3) { // E
  4960. float value = code_value();
  4961. if(value < 20.0) {
  4962. float factor = cs.axis_steps_per_unit[i] / value; // increase e constants if M92 E14 is given for netfab.
  4963. cs.max_jerk[E_AXIS] *= factor;
  4964. max_feedrate[i] *= factor;
  4965. axis_steps_per_sqr_second[i] *= factor;
  4966. }
  4967. cs.axis_steps_per_unit[i] = value;
  4968. }
  4969. else {
  4970. cs.axis_steps_per_unit[i] = code_value();
  4971. }
  4972. }
  4973. }
  4974. break;
  4975. case 110: //! M110 N<line number> - reset line pos
  4976. if (code_seen('N'))
  4977. gcode_LastN = code_value_long();
  4978. break;
  4979. #ifdef HOST_KEEPALIVE_FEATURE
  4980. case 113: // M113 - Get or set Host Keepalive interval
  4981. if (code_seen('S')) {
  4982. host_keepalive_interval = (uint8_t)code_value_short();
  4983. // NOMORE(host_keepalive_interval, 60);
  4984. }
  4985. else {
  4986. SERIAL_ECHO_START;
  4987. SERIAL_ECHOPAIR("M113 S", (unsigned long)host_keepalive_interval);
  4988. SERIAL_PROTOCOLLN("");
  4989. }
  4990. break;
  4991. #endif
  4992. case 115: // M115
  4993. if (code_seen('V')) {
  4994. // Report the Prusa version number.
  4995. SERIAL_PROTOCOLLNRPGM(FW_VERSION_STR_P());
  4996. } else if (code_seen('U')) {
  4997. // Check the firmware version provided. If the firmware version provided by the U code is higher than the currently running firmware,
  4998. // pause the print and ask the user to upgrade the firmware.
  4999. show_upgrade_dialog_if_version_newer(++ strchr_pointer);
  5000. } else {
  5001. SERIAL_ECHOPGM("FIRMWARE_NAME:Prusa-Firmware ");
  5002. SERIAL_ECHORPGM(FW_VERSION_STR_P());
  5003. SERIAL_ECHOPGM(" based on Marlin FIRMWARE_URL:https://github.com/prusa3d/Prusa-Firmware PROTOCOL_VERSION:");
  5004. SERIAL_ECHOPGM(PROTOCOL_VERSION);
  5005. SERIAL_ECHOPGM(" MACHINE_TYPE:");
  5006. SERIAL_ECHOPGM(CUSTOM_MENDEL_NAME);
  5007. SERIAL_ECHOPGM(" EXTRUDER_COUNT:");
  5008. SERIAL_ECHOPGM(STRINGIFY(EXTRUDERS));
  5009. SERIAL_ECHOPGM(" UUID:");
  5010. SERIAL_ECHOLNPGM(MACHINE_UUID);
  5011. }
  5012. break;
  5013. /* case 117: // M117 display message
  5014. starpos = (strchr(strchr_pointer + 5,'*'));
  5015. if(starpos!=NULL)
  5016. *(starpos)='\0';
  5017. lcd_setstatus(strchr_pointer + 5);
  5018. break;*/
  5019. case 114: // M114
  5020. gcode_M114();
  5021. break;
  5022. case 120: //! M120 - Disable endstops
  5023. enable_endstops(false) ;
  5024. break;
  5025. case 121: //! M121 - Enable endstops
  5026. enable_endstops(true) ;
  5027. break;
  5028. case 119: // M119
  5029. SERIAL_PROTOCOLRPGM(_N("Reporting endstop status"));////MSG_M119_REPORT c=0 r=0
  5030. SERIAL_PROTOCOLLN("");
  5031. #if defined(X_MIN_PIN) && X_MIN_PIN > -1
  5032. SERIAL_PROTOCOLRPGM(_n("x_min: "));////MSG_X_MIN c=0 r=0
  5033. if(READ(X_MIN_PIN)^X_MIN_ENDSTOP_INVERTING){
  5034. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5035. }else{
  5036. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5037. }
  5038. SERIAL_PROTOCOLLN("");
  5039. #endif
  5040. #if defined(X_MAX_PIN) && X_MAX_PIN > -1
  5041. SERIAL_PROTOCOLRPGM(_n("x_max: "));////MSG_X_MAX c=0 r=0
  5042. if(READ(X_MAX_PIN)^X_MAX_ENDSTOP_INVERTING){
  5043. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5044. }else{
  5045. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5046. }
  5047. SERIAL_PROTOCOLLN("");
  5048. #endif
  5049. #if defined(Y_MIN_PIN) && Y_MIN_PIN > -1
  5050. SERIAL_PROTOCOLRPGM(_n("y_min: "));////MSG_Y_MIN c=0 r=0
  5051. if(READ(Y_MIN_PIN)^Y_MIN_ENDSTOP_INVERTING){
  5052. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5053. }else{
  5054. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5055. }
  5056. SERIAL_PROTOCOLLN("");
  5057. #endif
  5058. #if defined(Y_MAX_PIN) && Y_MAX_PIN > -1
  5059. SERIAL_PROTOCOLRPGM(_n("y_max: "));////MSG_Y_MAX c=0 r=0
  5060. if(READ(Y_MAX_PIN)^Y_MAX_ENDSTOP_INVERTING){
  5061. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5062. }else{
  5063. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5064. }
  5065. SERIAL_PROTOCOLLN("");
  5066. #endif
  5067. #if defined(Z_MIN_PIN) && Z_MIN_PIN > -1
  5068. SERIAL_PROTOCOLRPGM(MSG_Z_MIN);
  5069. if(READ(Z_MIN_PIN)^Z_MIN_ENDSTOP_INVERTING){
  5070. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5071. }else{
  5072. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5073. }
  5074. SERIAL_PROTOCOLLN("");
  5075. #endif
  5076. #if defined(Z_MAX_PIN) && Z_MAX_PIN > -1
  5077. SERIAL_PROTOCOLRPGM(MSG_Z_MAX);
  5078. if(READ(Z_MAX_PIN)^Z_MAX_ENDSTOP_INVERTING){
  5079. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  5080. }else{
  5081. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  5082. }
  5083. SERIAL_PROTOCOLLN("");
  5084. #endif
  5085. break;
  5086. //TODO: update for all axis, use for loop
  5087. #ifdef BLINKM
  5088. case 150: // M150
  5089. {
  5090. byte red;
  5091. byte grn;
  5092. byte blu;
  5093. if(code_seen('R')) red = code_value();
  5094. if(code_seen('U')) grn = code_value();
  5095. if(code_seen('B')) blu = code_value();
  5096. SendColors(red,grn,blu);
  5097. }
  5098. break;
  5099. #endif //BLINKM
  5100. case 200: // M200 D<millimeters> set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).
  5101. {
  5102. uint8_t extruder = active_extruder;
  5103. if(code_seen('T')) {
  5104. extruder = code_value();
  5105. if(extruder >= EXTRUDERS) {
  5106. SERIAL_ECHO_START;
  5107. SERIAL_ECHO(_n("M200 Invalid extruder "));////MSG_M200_INVALID_EXTRUDER c=0 r=0
  5108. break;
  5109. }
  5110. }
  5111. if(code_seen('D')) {
  5112. float diameter = (float)code_value();
  5113. if (diameter == 0.0) {
  5114. // setting any extruder filament size disables volumetric on the assumption that
  5115. // slicers either generate in extruder values as cubic mm or as as filament feeds
  5116. // for all extruders
  5117. cs.volumetric_enabled = false;
  5118. } else {
  5119. cs.filament_size[extruder] = (float)code_value();
  5120. // make sure all extruders have some sane value for the filament size
  5121. cs.filament_size[0] = (cs.filament_size[0] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[0]);
  5122. #if EXTRUDERS > 1
  5123. cs.filament_size[1] = (cs.filament_size[1] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[1]);
  5124. #if EXTRUDERS > 2
  5125. cs.filament_size[2] = (cs.filament_size[2] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : cs.filament_size[2]);
  5126. #endif
  5127. #endif
  5128. cs.volumetric_enabled = true;
  5129. }
  5130. } else {
  5131. //reserved for setting filament diameter via UFID or filament measuring device
  5132. break;
  5133. }
  5134. calculate_extruder_multipliers();
  5135. }
  5136. break;
  5137. case 201: // M201
  5138. for (int8_t i = 0; i < NUM_AXIS; i++)
  5139. {
  5140. if (code_seen(axis_codes[i]))
  5141. {
  5142. unsigned long val = code_value();
  5143. #ifdef TMC2130
  5144. unsigned long val_silent = val;
  5145. if ((i == X_AXIS) || (i == Y_AXIS))
  5146. {
  5147. if (val > NORMAL_MAX_ACCEL_XY)
  5148. val = NORMAL_MAX_ACCEL_XY;
  5149. if (val_silent > SILENT_MAX_ACCEL_XY)
  5150. val_silent = SILENT_MAX_ACCEL_XY;
  5151. }
  5152. cs.max_acceleration_units_per_sq_second_normal[i] = val;
  5153. cs.max_acceleration_units_per_sq_second_silent[i] = val_silent;
  5154. #else //TMC2130
  5155. max_acceleration_units_per_sq_second[i] = val;
  5156. #endif //TMC2130
  5157. }
  5158. }
  5159. // 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)
  5160. reset_acceleration_rates();
  5161. break;
  5162. #if 0 // Not used for Sprinter/grbl gen6
  5163. case 202: // M202
  5164. for(int8_t i=0; i < NUM_AXIS; i++) {
  5165. if(code_seen(axis_codes[i])) axis_travel_steps_per_sqr_second[i] = code_value() * cs.axis_steps_per_unit[i];
  5166. }
  5167. break;
  5168. #endif
  5169. case 203: // M203 max feedrate mm/sec
  5170. for (int8_t i = 0; i < NUM_AXIS; i++)
  5171. {
  5172. if (code_seen(axis_codes[i]))
  5173. {
  5174. float val = code_value();
  5175. #ifdef TMC2130
  5176. float val_silent = val;
  5177. if ((i == X_AXIS) || (i == Y_AXIS))
  5178. {
  5179. if (val > NORMAL_MAX_FEEDRATE_XY)
  5180. val = NORMAL_MAX_FEEDRATE_XY;
  5181. if (val_silent > SILENT_MAX_FEEDRATE_XY)
  5182. val_silent = SILENT_MAX_FEEDRATE_XY;
  5183. }
  5184. cs.max_feedrate_normal[i] = val;
  5185. cs.max_feedrate_silent[i] = val_silent;
  5186. #else //TMC2130
  5187. max_feedrate[i] = val;
  5188. #endif //TMC2130
  5189. }
  5190. }
  5191. break;
  5192. case 204:
  5193. //! M204 acclereration settings.
  5194. //!@n Supporting old format: M204 S[normal moves] T[filmanent only moves]
  5195. //!@n and new format: M204 P[printing moves] R[filmanent only moves] T[travel moves] (as of now T is ignored)
  5196. {
  5197. if(code_seen('S')) {
  5198. // Legacy acceleration format. This format is used by the legacy Marlin, MK2 or MK3 firmware,
  5199. // and it is also generated by Slic3r to control acceleration per extrusion type
  5200. // (there is a separate acceleration settings in Slicer for perimeter, first layer etc).
  5201. cs.acceleration = code_value();
  5202. // Interpret the T value as retract acceleration in the old Marlin format.
  5203. if(code_seen('T'))
  5204. cs.retract_acceleration = code_value();
  5205. } else {
  5206. // New acceleration format, compatible with the upstream Marlin.
  5207. if(code_seen('P'))
  5208. cs.acceleration = code_value();
  5209. if(code_seen('R'))
  5210. cs.retract_acceleration = code_value();
  5211. if(code_seen('T')) {
  5212. // Interpret the T value as the travel acceleration in the new Marlin format.
  5213. //FIXME Prusa3D firmware currently does not support travel acceleration value independent from the extruding acceleration value.
  5214. // travel_acceleration = code_value();
  5215. }
  5216. }
  5217. }
  5218. break;
  5219. case 205: //M205 advanced settings: minimum travel speed S=while printing T=travel only, B=minimum segment time X= maximum xy jerk, Z=maximum Z jerk
  5220. {
  5221. if(code_seen('S')) cs.minimumfeedrate = code_value();
  5222. if(code_seen('T')) cs.mintravelfeedrate = code_value();
  5223. if(code_seen('B')) cs.minsegmenttime = code_value() ;
  5224. if(code_seen('X')) cs.max_jerk[X_AXIS] = cs.max_jerk[Y_AXIS] = code_value();
  5225. if(code_seen('Y')) cs.max_jerk[Y_AXIS] = code_value();
  5226. if(code_seen('Z')) cs.max_jerk[Z_AXIS] = code_value();
  5227. if(code_seen('E')) cs.max_jerk[E_AXIS] = code_value();
  5228. if (cs.max_jerk[X_AXIS] > DEFAULT_XJERK) cs.max_jerk[X_AXIS] = DEFAULT_XJERK;
  5229. if (cs.max_jerk[Y_AXIS] > DEFAULT_YJERK) cs.max_jerk[Y_AXIS] = DEFAULT_YJERK;
  5230. }
  5231. break;
  5232. case 206: // M206 additional homing offset
  5233. for(int8_t i=0; i < 3; i++)
  5234. {
  5235. if(code_seen(axis_codes[i])) cs.add_homing[i] = code_value();
  5236. }
  5237. break;
  5238. #ifdef FWRETRACT
  5239. case 207: //M207 - set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop]
  5240. {
  5241. if(code_seen('S'))
  5242. {
  5243. cs.retract_length = code_value() ;
  5244. }
  5245. if(code_seen('F'))
  5246. {
  5247. cs.retract_feedrate = code_value()/60 ;
  5248. }
  5249. if(code_seen('Z'))
  5250. {
  5251. cs.retract_zlift = code_value() ;
  5252. }
  5253. }break;
  5254. case 208: // M208 - set retract recover length S[positive mm surplus to the M207 S*] F[feedrate mm/min]
  5255. {
  5256. if(code_seen('S'))
  5257. {
  5258. cs.retract_recover_length = code_value() ;
  5259. }
  5260. if(code_seen('F'))
  5261. {
  5262. cs.retract_recover_feedrate = code_value()/60 ;
  5263. }
  5264. }break;
  5265. 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.
  5266. {
  5267. if(code_seen('S'))
  5268. {
  5269. int t= code_value() ;
  5270. switch(t)
  5271. {
  5272. case 0:
  5273. {
  5274. cs.autoretract_enabled=false;
  5275. retracted[0]=false;
  5276. #if EXTRUDERS > 1
  5277. retracted[1]=false;
  5278. #endif
  5279. #if EXTRUDERS > 2
  5280. retracted[2]=false;
  5281. #endif
  5282. }break;
  5283. case 1:
  5284. {
  5285. cs.autoretract_enabled=true;
  5286. retracted[0]=false;
  5287. #if EXTRUDERS > 1
  5288. retracted[1]=false;
  5289. #endif
  5290. #if EXTRUDERS > 2
  5291. retracted[2]=false;
  5292. #endif
  5293. }break;
  5294. default:
  5295. SERIAL_ECHO_START;
  5296. SERIAL_ECHORPGM(MSG_UNKNOWN_COMMAND);
  5297. SERIAL_ECHO(CMDBUFFER_CURRENT_STRING);
  5298. SERIAL_ECHOLNPGM("\"(1)");
  5299. }
  5300. }
  5301. }break;
  5302. #endif // FWRETRACT
  5303. #if EXTRUDERS > 1
  5304. case 218: // M218 - set hotend offset (in mm), T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  5305. {
  5306. uint8_t extruder;
  5307. if(setTargetedHotend(218, extruder)){
  5308. break;
  5309. }
  5310. if(code_seen('X'))
  5311. {
  5312. extruder_offset[X_AXIS][extruder] = code_value();
  5313. }
  5314. if(code_seen('Y'))
  5315. {
  5316. extruder_offset[Y_AXIS][extruder] = code_value();
  5317. }
  5318. SERIAL_ECHO_START;
  5319. SERIAL_ECHORPGM(MSG_HOTEND_OFFSET);
  5320. for(extruder = 0; extruder < EXTRUDERS; extruder++)
  5321. {
  5322. SERIAL_ECHO(" ");
  5323. SERIAL_ECHO(extruder_offset[X_AXIS][extruder]);
  5324. SERIAL_ECHO(",");
  5325. SERIAL_ECHO(extruder_offset[Y_AXIS][extruder]);
  5326. }
  5327. SERIAL_ECHOLN("");
  5328. }break;
  5329. #endif
  5330. case 220: // M220 S<factor in percent>- set speed factor override percentage
  5331. {
  5332. if (code_seen('B')) //backup current speed factor
  5333. {
  5334. saved_feedmultiply_mm = feedmultiply;
  5335. }
  5336. if(code_seen('S'))
  5337. {
  5338. feedmultiply = code_value() ;
  5339. }
  5340. if (code_seen('R')) { //restore previous feedmultiply
  5341. feedmultiply = saved_feedmultiply_mm;
  5342. }
  5343. }
  5344. break;
  5345. case 221: // M221 S<factor in percent>- set extrude factor override percentage
  5346. {
  5347. if(code_seen('S'))
  5348. {
  5349. int tmp_code = code_value();
  5350. if (code_seen('T'))
  5351. {
  5352. uint8_t extruder;
  5353. if(setTargetedHotend(221, extruder)){
  5354. break;
  5355. }
  5356. extruder_multiply[extruder] = tmp_code;
  5357. }
  5358. else
  5359. {
  5360. extrudemultiply = tmp_code ;
  5361. }
  5362. }
  5363. calculate_extruder_multipliers();
  5364. }
  5365. break;
  5366. case 226: // M226 P<pin number> S<pin state>- Wait until the specified pin reaches the state required
  5367. {
  5368. if(code_seen('P')){
  5369. int pin_number = code_value(); // pin number
  5370. int pin_state = -1; // required pin state - default is inverted
  5371. if(code_seen('S')) pin_state = code_value(); // required pin state
  5372. if(pin_state >= -1 && pin_state <= 1){
  5373. for(int8_t i = 0; i < (int8_t)(sizeof(sensitive_pins)/sizeof(int)); i++)
  5374. {
  5375. if (sensitive_pins[i] == pin_number)
  5376. {
  5377. pin_number = -1;
  5378. break;
  5379. }
  5380. }
  5381. if (pin_number > -1)
  5382. {
  5383. int target = LOW;
  5384. st_synchronize();
  5385. pinMode(pin_number, INPUT);
  5386. switch(pin_state){
  5387. case 1:
  5388. target = HIGH;
  5389. break;
  5390. case 0:
  5391. target = LOW;
  5392. break;
  5393. case -1:
  5394. target = !digitalRead(pin_number);
  5395. break;
  5396. }
  5397. while(digitalRead(pin_number) != target){
  5398. manage_heater();
  5399. manage_inactivity();
  5400. lcd_update(0);
  5401. }
  5402. }
  5403. }
  5404. }
  5405. }
  5406. break;
  5407. #if NUM_SERVOS > 0
  5408. case 280: // M280 - set servo position absolute. P: servo index, S: angle or microseconds
  5409. {
  5410. int servo_index = -1;
  5411. int servo_position = 0;
  5412. if (code_seen('P'))
  5413. servo_index = code_value();
  5414. if (code_seen('S')) {
  5415. servo_position = code_value();
  5416. if ((servo_index >= 0) && (servo_index < NUM_SERVOS)) {
  5417. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  5418. servos[servo_index].attach(0);
  5419. #endif
  5420. servos[servo_index].write(servo_position);
  5421. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  5422. delay(PROBE_SERVO_DEACTIVATION_DELAY);
  5423. servos[servo_index].detach();
  5424. #endif
  5425. }
  5426. else {
  5427. SERIAL_ECHO_START;
  5428. SERIAL_ECHO("Servo ");
  5429. SERIAL_ECHO(servo_index);
  5430. SERIAL_ECHOLN(" out of range");
  5431. }
  5432. }
  5433. else if (servo_index >= 0) {
  5434. SERIAL_PROTOCOL(MSG_OK);
  5435. SERIAL_PROTOCOL(" Servo ");
  5436. SERIAL_PROTOCOL(servo_index);
  5437. SERIAL_PROTOCOL(": ");
  5438. SERIAL_PROTOCOL(servos[servo_index].read());
  5439. SERIAL_PROTOCOLLN("");
  5440. }
  5441. }
  5442. break;
  5443. #endif // NUM_SERVOS > 0
  5444. #if (LARGE_FLASH == true && ( BEEPER > 0 || defined(ULTRALCD) || defined(LCD_USE_I2C_BUZZER)))
  5445. case 300: // M300
  5446. {
  5447. int beepS = code_seen('S') ? code_value() : 110;
  5448. int beepP = code_seen('P') ? code_value() : 1000;
  5449. if (beepS > 0)
  5450. {
  5451. #if BEEPER > 0
  5452. if((eSoundMode==e_SOUND_MODE_LOUD)||(eSoundMode==e_SOUND_MODE_ONCE))
  5453. tone(BEEPER, beepS);
  5454. delay(beepP);
  5455. noTone(BEEPER);
  5456. #endif
  5457. }
  5458. else
  5459. {
  5460. delay(beepP);
  5461. }
  5462. }
  5463. break;
  5464. #endif // M300
  5465. #ifdef PIDTEMP
  5466. case 301: // M301
  5467. {
  5468. if(code_seen('P')) cs.Kp = code_value();
  5469. if(code_seen('I')) cs.Ki = scalePID_i(code_value());
  5470. if(code_seen('D')) cs.Kd = scalePID_d(code_value());
  5471. #ifdef PID_ADD_EXTRUSION_RATE
  5472. if(code_seen('C')) Kc = code_value();
  5473. #endif
  5474. updatePID();
  5475. SERIAL_PROTOCOLRPGM(MSG_OK);
  5476. SERIAL_PROTOCOL(" p:");
  5477. SERIAL_PROTOCOL(cs.Kp);
  5478. SERIAL_PROTOCOL(" i:");
  5479. SERIAL_PROTOCOL(unscalePID_i(cs.Ki));
  5480. SERIAL_PROTOCOL(" d:");
  5481. SERIAL_PROTOCOL(unscalePID_d(cs.Kd));
  5482. #ifdef PID_ADD_EXTRUSION_RATE
  5483. SERIAL_PROTOCOL(" c:");
  5484. //Kc does not have scaling applied above, or in resetting defaults
  5485. SERIAL_PROTOCOL(Kc);
  5486. #endif
  5487. SERIAL_PROTOCOLLN("");
  5488. }
  5489. break;
  5490. #endif //PIDTEMP
  5491. #ifdef PIDTEMPBED
  5492. case 304: // M304
  5493. {
  5494. if(code_seen('P')) cs.bedKp = code_value();
  5495. if(code_seen('I')) cs.bedKi = scalePID_i(code_value());
  5496. if(code_seen('D')) cs.bedKd = scalePID_d(code_value());
  5497. updatePID();
  5498. SERIAL_PROTOCOLRPGM(MSG_OK);
  5499. SERIAL_PROTOCOL(" p:");
  5500. SERIAL_PROTOCOL(cs.bedKp);
  5501. SERIAL_PROTOCOL(" i:");
  5502. SERIAL_PROTOCOL(unscalePID_i(cs.bedKi));
  5503. SERIAL_PROTOCOL(" d:");
  5504. SERIAL_PROTOCOL(unscalePID_d(cs.bedKd));
  5505. SERIAL_PROTOCOLLN("");
  5506. }
  5507. break;
  5508. #endif //PIDTEMP
  5509. case 240: // M240 Triggers a camera by emulating a Canon RC-1 : http://www.doc-diy.net/photo/rc-1_hacked/
  5510. {
  5511. #ifdef CHDK
  5512. SET_OUTPUT(CHDK);
  5513. WRITE(CHDK, HIGH);
  5514. chdkHigh = millis();
  5515. chdkActive = true;
  5516. #else
  5517. #if defined(PHOTOGRAPH_PIN) && PHOTOGRAPH_PIN > -1
  5518. const uint8_t NUM_PULSES=16;
  5519. const float PULSE_LENGTH=0.01524;
  5520. for(int i=0; i < NUM_PULSES; i++) {
  5521. WRITE(PHOTOGRAPH_PIN, HIGH);
  5522. _delay_ms(PULSE_LENGTH);
  5523. WRITE(PHOTOGRAPH_PIN, LOW);
  5524. _delay_ms(PULSE_LENGTH);
  5525. }
  5526. delay(7.33);
  5527. for(int i=0; i < NUM_PULSES; i++) {
  5528. WRITE(PHOTOGRAPH_PIN, HIGH);
  5529. _delay_ms(PULSE_LENGTH);
  5530. WRITE(PHOTOGRAPH_PIN, LOW);
  5531. _delay_ms(PULSE_LENGTH);
  5532. }
  5533. #endif
  5534. #endif //chdk end if
  5535. }
  5536. break;
  5537. #ifdef PREVENT_DANGEROUS_EXTRUDE
  5538. case 302: // allow cold extrudes, or set the minimum extrude temperature
  5539. {
  5540. float temp = .0;
  5541. if (code_seen('S')) temp=code_value();
  5542. set_extrude_min_temp(temp);
  5543. }
  5544. break;
  5545. #endif
  5546. case 303: // M303 PID autotune
  5547. {
  5548. float temp = 150.0;
  5549. int e=0;
  5550. int c=5;
  5551. if (code_seen('E')) e=code_value();
  5552. if (e<0)
  5553. temp=70;
  5554. if (code_seen('S')) temp=code_value();
  5555. if (code_seen('C')) c=code_value();
  5556. PID_autotune(temp, e, c);
  5557. }
  5558. break;
  5559. case 400: // M400 finish all moves
  5560. {
  5561. st_synchronize();
  5562. }
  5563. break;
  5564. case 403: //! M403 set filament type (material) for particular extruder and send this information to mmu
  5565. {
  5566. //! currently three different materials are needed (default, flex and PVA)
  5567. //! add storing this information for different load/unload profiles etc. in the future
  5568. //!firmware does not wait for "ok" from mmu
  5569. if (mmu_enabled)
  5570. {
  5571. uint8_t extruder = 255;
  5572. uint8_t filament = FILAMENT_UNDEFINED;
  5573. if(code_seen('E')) extruder = code_value();
  5574. if(code_seen('F')) filament = code_value();
  5575. mmu_set_filament_type(extruder, filament);
  5576. }
  5577. }
  5578. break;
  5579. case 500: // M500 Store settings in EEPROM
  5580. {
  5581. Config_StoreSettings();
  5582. }
  5583. break;
  5584. case 501: // M501 Read settings from EEPROM
  5585. {
  5586. Config_RetrieveSettings();
  5587. }
  5588. break;
  5589. case 502: // M502 Revert to default settings
  5590. {
  5591. Config_ResetDefault();
  5592. }
  5593. break;
  5594. case 503: // M503 print settings currently in memory
  5595. {
  5596. Config_PrintSettings();
  5597. }
  5598. break;
  5599. case 509: //M509 Force language selection
  5600. {
  5601. lang_reset();
  5602. SERIAL_ECHO_START;
  5603. SERIAL_PROTOCOLPGM(("LANG SEL FORCED"));
  5604. }
  5605. break;
  5606. #ifdef ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED
  5607. case 540:
  5608. {
  5609. if(code_seen('S')) abort_on_endstop_hit = code_value() > 0;
  5610. }
  5611. break;
  5612. #endif
  5613. #ifdef CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  5614. case CUSTOM_M_CODE_SET_Z_PROBE_OFFSET:
  5615. {
  5616. float value;
  5617. if (code_seen('Z'))
  5618. {
  5619. value = code_value();
  5620. if ((Z_PROBE_OFFSET_RANGE_MIN <= value) && (value <= Z_PROBE_OFFSET_RANGE_MAX))
  5621. {
  5622. cs.zprobe_zoffset = -value; // compare w/ line 278 of ConfigurationStore.cpp
  5623. SERIAL_ECHO_START;
  5624. SERIAL_ECHOLNRPGM(CAT4(MSG_ZPROBE_ZOFFSET, " ", MSG_OK,PSTR("")));
  5625. SERIAL_PROTOCOLLN("");
  5626. }
  5627. else
  5628. {
  5629. SERIAL_ECHO_START;
  5630. SERIAL_ECHORPGM(MSG_ZPROBE_ZOFFSET);
  5631. SERIAL_ECHORPGM(MSG_Z_MIN);
  5632. SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MIN);
  5633. SERIAL_ECHORPGM(MSG_Z_MAX);
  5634. SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MAX);
  5635. SERIAL_PROTOCOLLN("");
  5636. }
  5637. }
  5638. else
  5639. {
  5640. SERIAL_ECHO_START;
  5641. SERIAL_ECHOLNRPGM(CAT2(MSG_ZPROBE_ZOFFSET, PSTR(" : ")));
  5642. SERIAL_ECHO(-cs.zprobe_zoffset);
  5643. SERIAL_PROTOCOLLN("");
  5644. }
  5645. break;
  5646. }
  5647. #endif // CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  5648. #ifdef FILAMENTCHANGEENABLE
  5649. case 600: //Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  5650. {
  5651. st_synchronize();
  5652. float x_position = current_position[X_AXIS];
  5653. float y_position = current_position[Y_AXIS];
  5654. float z_shift = 0;
  5655. float e_shift_init = 0;
  5656. float e_shift_late = 0;
  5657. bool automatic = false;
  5658. //Retract extruder
  5659. if(code_seen('E'))
  5660. {
  5661. e_shift_init = code_value();
  5662. }
  5663. else
  5664. {
  5665. #ifdef FILAMENTCHANGE_FIRSTRETRACT
  5666. e_shift_init = FILAMENTCHANGE_FIRSTRETRACT ;
  5667. #endif
  5668. }
  5669. //currently don't work as we are using the same unload sequence as in M702, needs re-work
  5670. if (code_seen('L'))
  5671. {
  5672. e_shift_late = code_value();
  5673. }
  5674. else
  5675. {
  5676. #ifdef FILAMENTCHANGE_FINALRETRACT
  5677. e_shift_late = FILAMENTCHANGE_FINALRETRACT;
  5678. #endif
  5679. }
  5680. //Lift Z
  5681. if(code_seen('Z'))
  5682. {
  5683. z_shift = code_value();
  5684. }
  5685. else
  5686. {
  5687. #ifdef FILAMENTCHANGE_ZADD
  5688. z_shift= FILAMENTCHANGE_ZADD ;
  5689. if(current_position[Z_AXIS] < 25) z_shift+= 25 ;
  5690. #endif
  5691. }
  5692. //Move XY to side
  5693. if(code_seen('X'))
  5694. {
  5695. x_position = code_value();
  5696. }
  5697. else
  5698. {
  5699. #ifdef FILAMENTCHANGE_XPOS
  5700. x_position = FILAMENTCHANGE_XPOS;
  5701. #endif
  5702. }
  5703. if(code_seen('Y'))
  5704. {
  5705. y_position = code_value();
  5706. }
  5707. else
  5708. {
  5709. #ifdef FILAMENTCHANGE_YPOS
  5710. y_position = FILAMENTCHANGE_YPOS ;
  5711. #endif
  5712. }
  5713. if (mmu_enabled && code_seen("AUTO"))
  5714. automatic = true;
  5715. gcode_M600(automatic, x_position, y_position, z_shift, e_shift_init, e_shift_late);
  5716. }
  5717. break;
  5718. #endif //FILAMENTCHANGEENABLE
  5719. case 601: //! M601 - Pause print
  5720. {
  5721. cmdqueue_pop_front(); //trick because we want skip this command (M601) after restore
  5722. lcd_pause_print();
  5723. }
  5724. break;
  5725. case 602: { //! M602 - Resume print
  5726. lcd_resume_print();
  5727. }
  5728. break;
  5729. #ifdef PINDA_THERMISTOR
  5730. case 860: // M860 - Wait for PINDA thermistor to reach target temperature.
  5731. {
  5732. int set_target_pinda = 0;
  5733. if (code_seen('S')) {
  5734. set_target_pinda = code_value();
  5735. }
  5736. else {
  5737. break;
  5738. }
  5739. LCD_MESSAGERPGM(_T(MSG_PLEASE_WAIT));
  5740. SERIAL_PROTOCOLPGM("Wait for PINDA target temperature:");
  5741. SERIAL_PROTOCOL(set_target_pinda);
  5742. SERIAL_PROTOCOLLN("");
  5743. codenum = millis();
  5744. cancel_heatup = false;
  5745. bool is_pinda_cooling = false;
  5746. if ((degTargetBed() == 0) && (degTargetHotend(0) == 0)) {
  5747. is_pinda_cooling = true;
  5748. }
  5749. while ( ((!is_pinda_cooling) && (!cancel_heatup) && (current_temperature_pinda < set_target_pinda)) || (is_pinda_cooling && (current_temperature_pinda > set_target_pinda)) ) {
  5750. if ((millis() - codenum) > 1000) //Print Temp Reading every 1 second while waiting.
  5751. {
  5752. SERIAL_PROTOCOLPGM("P:");
  5753. SERIAL_PROTOCOL_F(current_temperature_pinda, 1);
  5754. SERIAL_PROTOCOLPGM("/");
  5755. SERIAL_PROTOCOL(set_target_pinda);
  5756. SERIAL_PROTOCOLLN("");
  5757. codenum = millis();
  5758. }
  5759. manage_heater();
  5760. manage_inactivity();
  5761. lcd_update(0);
  5762. }
  5763. LCD_MESSAGERPGM(MSG_OK);
  5764. break;
  5765. }
  5766. case 861: // M861 - Set/Read PINDA temperature compensation offsets
  5767. if (code_seen('?')) { // ? - Print out current EEPROM offset values
  5768. uint8_t cal_status = calibration_status_pinda();
  5769. int16_t usteps = 0;
  5770. cal_status ? SERIAL_PROTOCOLLN("PINDA cal status: 1") : SERIAL_PROTOCOLLN("PINDA cal status: 0");
  5771. SERIAL_PROTOCOLLN("index, temp, ustep, um");
  5772. for (uint8_t i = 0; i < 6; i++)
  5773. {
  5774. if(i>0) EEPROM_read_B(EEPROM_PROBE_TEMP_SHIFT + (i-1) * 2, &usteps);
  5775. float mm = ((float)usteps) / cs.axis_steps_per_unit[Z_AXIS];
  5776. i == 0 ? SERIAL_PROTOCOLPGM("n/a") : SERIAL_PROTOCOL(i - 1);
  5777. SERIAL_PROTOCOLPGM(", ");
  5778. SERIAL_PROTOCOL(35 + (i * 5));
  5779. SERIAL_PROTOCOLPGM(", ");
  5780. SERIAL_PROTOCOL(usteps);
  5781. SERIAL_PROTOCOLPGM(", ");
  5782. SERIAL_PROTOCOL(mm * 1000);
  5783. SERIAL_PROTOCOLLN("");
  5784. }
  5785. }
  5786. else if (code_seen('!')) { // ! - Set factory default values
  5787. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  5788. int16_t z_shift = 8; //40C - 20um - 8usteps
  5789. EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT, &z_shift);
  5790. z_shift = 24; //45C - 60um - 24usteps
  5791. EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + 2, &z_shift);
  5792. z_shift = 48; //50C - 120um - 48usteps
  5793. EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + 4, &z_shift);
  5794. z_shift = 80; //55C - 200um - 80usteps
  5795. EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + 6, &z_shift);
  5796. z_shift = 120; //60C - 300um - 120usteps
  5797. EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + 8, &z_shift);
  5798. SERIAL_PROTOCOLLN("factory restored");
  5799. }
  5800. else if (code_seen('Z')) { // Z - Set all values to 0 (effectively disabling PINDA temperature compensation)
  5801. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  5802. int16_t z_shift = 0;
  5803. for (uint8_t i = 0; i < 5; i++) EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + i * 2, &z_shift);
  5804. SERIAL_PROTOCOLLN("zerorized");
  5805. }
  5806. else if (code_seen('S')) { // Sxxx Iyyy - Set compensation ustep value S for compensation table index I
  5807. int16_t usteps = code_value();
  5808. if (code_seen('I')) {
  5809. uint8_t index = code_value();
  5810. if (index < 5) {
  5811. EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + index * 2, &usteps);
  5812. SERIAL_PROTOCOLLN("OK");
  5813. SERIAL_PROTOCOLLN("index, temp, ustep, um");
  5814. for (uint8_t i = 0; i < 6; i++)
  5815. {
  5816. usteps = 0;
  5817. if (i>0) EEPROM_read_B(EEPROM_PROBE_TEMP_SHIFT + (i - 1) * 2, &usteps);
  5818. float mm = ((float)usteps) / cs.axis_steps_per_unit[Z_AXIS];
  5819. i == 0 ? SERIAL_PROTOCOLPGM("n/a") : SERIAL_PROTOCOL(i - 1);
  5820. SERIAL_PROTOCOLPGM(", ");
  5821. SERIAL_PROTOCOL(35 + (i * 5));
  5822. SERIAL_PROTOCOLPGM(", ");
  5823. SERIAL_PROTOCOL(usteps);
  5824. SERIAL_PROTOCOLPGM(", ");
  5825. SERIAL_PROTOCOL(mm * 1000);
  5826. SERIAL_PROTOCOLLN("");
  5827. }
  5828. }
  5829. }
  5830. }
  5831. else {
  5832. SERIAL_PROTOCOLPGM("no valid command");
  5833. }
  5834. break;
  5835. #endif //PINDA_THERMISTOR
  5836. #ifdef LIN_ADVANCE
  5837. case 900: // M900: Set LIN_ADVANCE options.
  5838. gcode_M900();
  5839. break;
  5840. #endif
  5841. case 907: // M907 Set digital trimpot motor current using axis codes.
  5842. {
  5843. #ifdef TMC2130
  5844. for (int i = 0; i < NUM_AXIS; i++)
  5845. if(code_seen(axis_codes[i]))
  5846. {
  5847. long cur_mA = code_value_long();
  5848. uint8_t val = tmc2130_cur2val(cur_mA);
  5849. tmc2130_set_current_h(i, val);
  5850. tmc2130_set_current_r(i, val);
  5851. //if (i == E_AXIS) printf_P(PSTR("E-axis current=%ldmA\n"), cur_mA);
  5852. }
  5853. #else //TMC2130
  5854. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  5855. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) st_current_set(i,code_value());
  5856. if(code_seen('B')) st_current_set(4,code_value());
  5857. if(code_seen('S')) for(int i=0;i<=4;i++) st_current_set(i,code_value());
  5858. #endif
  5859. #ifdef MOTOR_CURRENT_PWM_XY_PIN
  5860. if(code_seen('X')) st_current_set(0, code_value());
  5861. #endif
  5862. #ifdef MOTOR_CURRENT_PWM_Z_PIN
  5863. if(code_seen('Z')) st_current_set(1, code_value());
  5864. #endif
  5865. #ifdef MOTOR_CURRENT_PWM_E_PIN
  5866. if(code_seen('E')) st_current_set(2, code_value());
  5867. #endif
  5868. #endif //TMC2130
  5869. }
  5870. break;
  5871. case 908: // M908 Control digital trimpot directly.
  5872. {
  5873. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  5874. uint8_t channel,current;
  5875. if(code_seen('P')) channel=code_value();
  5876. if(code_seen('S')) current=code_value();
  5877. digitalPotWrite(channel, current);
  5878. #endif
  5879. }
  5880. break;
  5881. #ifdef TMC2130_SERVICE_CODES_M910_M918
  5882. case 910: //! M910 - TMC2130 init
  5883. {
  5884. tmc2130_init();
  5885. }
  5886. break;
  5887. case 911: //! M911 - Set TMC2130 holding currents
  5888. {
  5889. if (code_seen('X')) tmc2130_set_current_h(0, code_value());
  5890. if (code_seen('Y')) tmc2130_set_current_h(1, code_value());
  5891. if (code_seen('Z')) tmc2130_set_current_h(2, code_value());
  5892. if (code_seen('E')) tmc2130_set_current_h(3, code_value());
  5893. }
  5894. break;
  5895. case 912: //! M912 - Set TMC2130 running currents
  5896. {
  5897. if (code_seen('X')) tmc2130_set_current_r(0, code_value());
  5898. if (code_seen('Y')) tmc2130_set_current_r(1, code_value());
  5899. if (code_seen('Z')) tmc2130_set_current_r(2, code_value());
  5900. if (code_seen('E')) tmc2130_set_current_r(3, code_value());
  5901. }
  5902. break;
  5903. case 913: //! M913 - Print TMC2130 currents
  5904. {
  5905. tmc2130_print_currents();
  5906. }
  5907. break;
  5908. case 914: //! M914 - Set normal mode
  5909. {
  5910. tmc2130_mode = TMC2130_MODE_NORMAL;
  5911. update_mode_profile();
  5912. tmc2130_init();
  5913. }
  5914. break;
  5915. case 915: //! M915 - Set silent mode
  5916. {
  5917. tmc2130_mode = TMC2130_MODE_SILENT;
  5918. update_mode_profile();
  5919. tmc2130_init();
  5920. }
  5921. break;
  5922. case 916: //! M916 - Set sg_thrs
  5923. {
  5924. if (code_seen('X')) tmc2130_sg_thr[X_AXIS] = code_value();
  5925. if (code_seen('Y')) tmc2130_sg_thr[Y_AXIS] = code_value();
  5926. if (code_seen('Z')) tmc2130_sg_thr[Z_AXIS] = code_value();
  5927. if (code_seen('E')) tmc2130_sg_thr[E_AXIS] = code_value();
  5928. for (uint8_t a = X_AXIS; a <= E_AXIS; a++)
  5929. printf_P(_N("tmc2130_sg_thr[%c]=%d\n"), "XYZE"[a], tmc2130_sg_thr[a]);
  5930. }
  5931. break;
  5932. case 917: //! M917 - Set TMC2130 pwm_ampl
  5933. {
  5934. if (code_seen('X')) tmc2130_set_pwm_ampl(0, code_value());
  5935. if (code_seen('Y')) tmc2130_set_pwm_ampl(1, code_value());
  5936. if (code_seen('Z')) tmc2130_set_pwm_ampl(2, code_value());
  5937. if (code_seen('E')) tmc2130_set_pwm_ampl(3, code_value());
  5938. }
  5939. break;
  5940. case 918: //! M918 - Set TMC2130 pwm_grad
  5941. {
  5942. if (code_seen('X')) tmc2130_set_pwm_grad(0, code_value());
  5943. if (code_seen('Y')) tmc2130_set_pwm_grad(1, code_value());
  5944. if (code_seen('Z')) tmc2130_set_pwm_grad(2, code_value());
  5945. if (code_seen('E')) tmc2130_set_pwm_grad(3, code_value());
  5946. }
  5947. break;
  5948. #endif //TMC2130_SERVICE_CODES_M910_M918
  5949. case 350: //! M350 - Set microstepping mode. Warning: Steps per unit remains unchanged. S code sets stepping mode for all drivers.
  5950. {
  5951. #ifdef TMC2130
  5952. if(code_seen('E'))
  5953. {
  5954. uint16_t res_new = code_value();
  5955. if ((res_new == 8) || (res_new == 16) || (res_new == 32) || (res_new == 64) || (res_new == 128))
  5956. {
  5957. st_synchronize();
  5958. uint8_t axis = E_AXIS;
  5959. uint16_t res = tmc2130_get_res(axis);
  5960. tmc2130_set_res(axis, res_new);
  5961. if (res_new > res)
  5962. {
  5963. uint16_t fac = (res_new / res);
  5964. cs.axis_steps_per_unit[axis] *= fac;
  5965. position[E_AXIS] *= fac;
  5966. }
  5967. else
  5968. {
  5969. uint16_t fac = (res / res_new);
  5970. cs.axis_steps_per_unit[axis] /= fac;
  5971. position[E_AXIS] /= fac;
  5972. }
  5973. }
  5974. }
  5975. #else //TMC2130
  5976. #if defined(X_MS1_PIN) && X_MS1_PIN > -1
  5977. if(code_seen('S')) for(int i=0;i<=4;i++) microstep_mode(i,code_value());
  5978. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_mode(i,(uint8_t)code_value());
  5979. if(code_seen('B')) microstep_mode(4,code_value());
  5980. microstep_readings();
  5981. #endif
  5982. #endif //TMC2130
  5983. }
  5984. break;
  5985. case 351: //! M351 - Toggle MS1 MS2 pins directly, S# determines MS1 or MS2, X# sets the pin high/low.
  5986. {
  5987. #if defined(X_MS1_PIN) && X_MS1_PIN > -1
  5988. if(code_seen('S')) switch((int)code_value())
  5989. {
  5990. case 1:
  5991. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_ms(i,code_value(),-1);
  5992. if(code_seen('B')) microstep_ms(4,code_value(),-1);
  5993. break;
  5994. case 2:
  5995. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_ms(i,-1,code_value());
  5996. if(code_seen('B')) microstep_ms(4,-1,code_value());
  5997. break;
  5998. }
  5999. microstep_readings();
  6000. #endif
  6001. }
  6002. break;
  6003. case 701: //! M701 - load filament
  6004. {
  6005. if (mmu_enabled && code_seen('E'))
  6006. tmp_extruder = code_value();
  6007. gcode_M701();
  6008. }
  6009. break;
  6010. case 702: //! M702 [U C] -
  6011. {
  6012. #ifdef SNMM
  6013. if (code_seen('U'))
  6014. extr_unload_used(); //! if "U" unload all filaments which were used in current print
  6015. else if (code_seen('C'))
  6016. extr_unload(); //! if "C" unload just current filament
  6017. else
  6018. extr_unload_all(); //! otherwise unload all filaments
  6019. #else
  6020. if (code_seen('C')) {
  6021. if(mmu_enabled) extr_unload(); //! if "C" unload current filament; if mmu is not present no action is performed
  6022. }
  6023. else {
  6024. if(mmu_enabled) extr_unload(); //! unload current filament
  6025. else unload_filament();
  6026. }
  6027. #endif //SNMM
  6028. }
  6029. break;
  6030. case 999: // M999: Restart after being stopped
  6031. Stopped = false;
  6032. lcd_reset_alert_level();
  6033. gcode_LastN = Stopped_gcode_LastN;
  6034. FlushSerialRequestResend();
  6035. break;
  6036. default:
  6037. printf_P(PSTR("Unknown M code: %s \n"), cmdbuffer + bufindr + CMDHDRSIZE);
  6038. }
  6039. // printf_P(_N("END M-CODE=%u\n"), mcode_in_progress);
  6040. mcode_in_progress = 0;
  6041. }
  6042. }
  6043. // end if(code_seen('M')) (end of M codes)
  6044. //! T<extruder nr.> - select extruder in case of multi extruder printer
  6045. //! select filament in case of MMU_V2
  6046. //! if extruder is "?", open menu to let the user select extruder/filament
  6047. //!
  6048. //! For MMU_V2:
  6049. //! @n T<n> Gcode to extrude at least 38.10 mm at feedrate 19.02 mm/s must follow immediately to load to extruder wheels.
  6050. //! @n T? Gcode to extrude shouldn't have to follow, load to extruder wheels is done automatically
  6051. //! @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.
  6052. //! @n Tc Load to nozzle after filament was prepared by Tc and extruder nozzle is already heated.
  6053. else if(code_seen('T'))
  6054. {
  6055. int index;
  6056. bool load_to_nozzle = false;
  6057. for (index = 1; *(strchr_pointer + index) == ' ' || *(strchr_pointer + index) == '\t'; index++);
  6058. *(strchr_pointer + index) = tolower(*(strchr_pointer + index));
  6059. if ((*(strchr_pointer + index) < '0' || *(strchr_pointer + index) > '4') && *(strchr_pointer + index) != '?' && *(strchr_pointer + index) != 'x' && *(strchr_pointer + index) != 'c') {
  6060. SERIAL_ECHOLNPGM("Invalid T code.");
  6061. }
  6062. else if (*(strchr_pointer + index) == 'x'){ //load to bondtech gears; if mmu is not present do nothing
  6063. if (mmu_enabled)
  6064. {
  6065. tmp_extruder = choose_menu_P(_T(MSG_CHOOSE_FILAMENT), _T(MSG_FILAMENT));
  6066. if ((tmp_extruder == mmu_extruder) && mmu_fil_loaded) {
  6067. printf_P(PSTR("Duplicit T-code ignored.\n"));
  6068. return; //dont execute the same T-code twice in a row
  6069. }
  6070. st_synchronize();
  6071. mmu_command(MMU_CMD_T0 + tmp_extruder);
  6072. manage_response(true, true, MMU_TCODE_MOVE);
  6073. }
  6074. }
  6075. else if (*(strchr_pointer + index) == 'c') { //load to from bondtech gears to nozzle (nozzle should be preheated)
  6076. if (mmu_enabled)
  6077. {
  6078. st_synchronize();
  6079. mmu_continue_loading();
  6080. mmu_extruder = tmp_extruder; //filament change is finished
  6081. mmu_load_to_nozzle();
  6082. }
  6083. }
  6084. else {
  6085. if (*(strchr_pointer + index) == '?')
  6086. {
  6087. if(mmu_enabled)
  6088. {
  6089. tmp_extruder = choose_menu_P(_T(MSG_CHOOSE_FILAMENT), _T(MSG_FILAMENT));
  6090. load_to_nozzle = true;
  6091. } else
  6092. {
  6093. tmp_extruder = choose_menu_P(_T(MSG_CHOOSE_EXTRUDER), _T(MSG_EXTRUDER));
  6094. }
  6095. }
  6096. else {
  6097. tmp_extruder = code_value();
  6098. }
  6099. st_synchronize();
  6100. snmm_filaments_used |= (1 << tmp_extruder); //for stop print
  6101. if (mmu_enabled)
  6102. {
  6103. if ((tmp_extruder == mmu_extruder) && mmu_fil_loaded) {
  6104. printf_P(PSTR("Duplicit T-code ignored.\n"));
  6105. return; //dont execute the same T-code twice in a row
  6106. }
  6107. mmu_command(MMU_CMD_T0 + tmp_extruder);
  6108. manage_response(true, true, MMU_TCODE_MOVE);
  6109. mmu_continue_loading();
  6110. mmu_extruder = tmp_extruder; //filament change is finished
  6111. if (load_to_nozzle)// for single material usage with mmu
  6112. {
  6113. mmu_load_to_nozzle();
  6114. }
  6115. }
  6116. else
  6117. {
  6118. #ifdef SNMM
  6119. #ifdef LIN_ADVANCE
  6120. if (mmu_extruder != tmp_extruder)
  6121. clear_current_adv_vars(); //Check if the selected extruder is not the active one and reset LIN_ADVANCE variables if so.
  6122. #endif
  6123. mmu_extruder = tmp_extruder;
  6124. delay(100);
  6125. disable_e0();
  6126. disable_e1();
  6127. disable_e2();
  6128. pinMode(E_MUX0_PIN, OUTPUT);
  6129. pinMode(E_MUX1_PIN, OUTPUT);
  6130. delay(100);
  6131. SERIAL_ECHO_START;
  6132. SERIAL_ECHO("T:");
  6133. SERIAL_ECHOLN((int)tmp_extruder);
  6134. switch (tmp_extruder) {
  6135. case 1:
  6136. WRITE(E_MUX0_PIN, HIGH);
  6137. WRITE(E_MUX1_PIN, LOW);
  6138. break;
  6139. case 2:
  6140. WRITE(E_MUX0_PIN, LOW);
  6141. WRITE(E_MUX1_PIN, HIGH);
  6142. break;
  6143. case 3:
  6144. WRITE(E_MUX0_PIN, HIGH);
  6145. WRITE(E_MUX1_PIN, HIGH);
  6146. break;
  6147. default:
  6148. WRITE(E_MUX0_PIN, LOW);
  6149. WRITE(E_MUX1_PIN, LOW);
  6150. break;
  6151. }
  6152. delay(100);
  6153. #else //SNMM
  6154. if (tmp_extruder >= EXTRUDERS) {
  6155. SERIAL_ECHO_START;
  6156. SERIAL_ECHOPGM("T");
  6157. SERIAL_PROTOCOLLN((int)tmp_extruder);
  6158. SERIAL_ECHOLNRPGM(_n("Invalid extruder"));////MSG_INVALID_EXTRUDER c=0 r=0
  6159. }
  6160. else {
  6161. #if EXTRUDERS > 1
  6162. boolean make_move = false;
  6163. #endif
  6164. if (code_seen('F')) {
  6165. #if EXTRUDERS > 1
  6166. make_move = true;
  6167. #endif
  6168. next_feedrate = code_value();
  6169. if (next_feedrate > 0.0) {
  6170. feedrate = next_feedrate;
  6171. }
  6172. }
  6173. #if EXTRUDERS > 1
  6174. if (tmp_extruder != active_extruder) {
  6175. // Save current position to return to after applying extruder offset
  6176. memcpy(destination, current_position, sizeof(destination));
  6177. // Offset extruder (only by XY)
  6178. int i;
  6179. for (i = 0; i < 2; i++) {
  6180. current_position[i] = current_position[i] -
  6181. extruder_offset[i][active_extruder] +
  6182. extruder_offset[i][tmp_extruder];
  6183. }
  6184. // Set the new active extruder and position
  6185. active_extruder = tmp_extruder;
  6186. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  6187. // Move to the old position if 'F' was in the parameters
  6188. if (make_move && Stopped == false) {
  6189. prepare_move();
  6190. }
  6191. }
  6192. #endif
  6193. SERIAL_ECHO_START;
  6194. SERIAL_ECHORPGM(_n("Active Extruder: "));////MSG_ACTIVE_EXTRUDER c=0 r=0
  6195. SERIAL_PROTOCOLLN((int)active_extruder);
  6196. }
  6197. #endif //SNMM
  6198. }
  6199. }
  6200. } // end if(code_seen('T')) (end of T codes)
  6201. else if (code_seen('D')) // D codes (debug)
  6202. {
  6203. switch((int)code_value())
  6204. {
  6205. #ifdef DEBUG_DCODES
  6206. case -1: //! D-1 - Endless loop
  6207. dcode__1(); break;
  6208. case 0: //! D0 - Reset
  6209. dcode_0(); break;
  6210. case 1: //! D1 - Clear EEPROM
  6211. dcode_1(); break;
  6212. case 2: //! D2 - Read/Write RAM
  6213. dcode_2(); break;
  6214. #endif //DEBUG_DCODES
  6215. #ifdef DEBUG_DCODE3
  6216. case 3: //! D3 - Read/Write EEPROM
  6217. dcode_3(); break;
  6218. #endif //DEBUG_DCODE3
  6219. #ifdef DEBUG_DCODES
  6220. case 4: //! D4 - Read/Write PIN
  6221. dcode_4(); break;
  6222. #endif //DEBUG_DCODES
  6223. #ifdef DEBUG_DCODE5
  6224. case 5: // D5 - Read/Write FLASH
  6225. dcode_5(); break;
  6226. break;
  6227. #endif //DEBUG_DCODE5
  6228. #ifdef DEBUG_DCODES
  6229. case 6: // D6 - Read/Write external FLASH
  6230. dcode_6(); break;
  6231. case 7: //! D7 - Read/Write Bootloader
  6232. dcode_7(); break;
  6233. case 8: //! D8 - Read/Write PINDA
  6234. dcode_8(); break;
  6235. case 9: //! D9 - Read/Write ADC
  6236. dcode_9(); break;
  6237. case 10: //! D10 - XYZ calibration = OK
  6238. dcode_10(); break;
  6239. #ifdef TMC2130
  6240. case 2130: //! D2130 - TMC2130
  6241. dcode_2130(); break;
  6242. #endif //TMC2130
  6243. #ifdef FILAMENT_SENSOR
  6244. case 9125: //! D9125 - FILAMENT_SENSOR
  6245. dcode_9125(); break;
  6246. #endif //FILAMENT_SENSOR
  6247. #endif //DEBUG_DCODES
  6248. }
  6249. }
  6250. else
  6251. {
  6252. SERIAL_ECHO_START;
  6253. SERIAL_ECHORPGM(MSG_UNKNOWN_COMMAND);
  6254. SERIAL_ECHO(CMDBUFFER_CURRENT_STRING);
  6255. SERIAL_ECHOLNPGM("\"(2)");
  6256. }
  6257. KEEPALIVE_STATE(NOT_BUSY);
  6258. ClearToSend();
  6259. }
  6260. void FlushSerialRequestResend()
  6261. {
  6262. //char cmdbuffer[bufindr][100]="Resend:";
  6263. MYSERIAL.flush();
  6264. printf_P(_N("%S: %ld\n%S\n"), _n("Resend"), gcode_LastN + 1, MSG_OK);
  6265. }
  6266. // Confirm the execution of a command, if sent from a serial line.
  6267. // Execution of a command from a SD card will not be confirmed.
  6268. void ClearToSend()
  6269. {
  6270. previous_millis_cmd = millis();
  6271. if ((CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB) || (CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR))
  6272. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  6273. }
  6274. #if MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  6275. void update_currents() {
  6276. float current_high[3] = DEFAULT_PWM_MOTOR_CURRENT_LOUD;
  6277. float current_low[3] = DEFAULT_PWM_MOTOR_CURRENT;
  6278. float tmp_motor[3];
  6279. //SERIAL_ECHOLNPGM("Currents updated: ");
  6280. if (destination[Z_AXIS] < Z_SILENT) {
  6281. //SERIAL_ECHOLNPGM("LOW");
  6282. for (uint8_t i = 0; i < 3; i++) {
  6283. st_current_set(i, current_low[i]);
  6284. /*MYSERIAL.print(int(i));
  6285. SERIAL_ECHOPGM(": ");
  6286. MYSERIAL.println(current_low[i]);*/
  6287. }
  6288. }
  6289. else if (destination[Z_AXIS] > Z_HIGH_POWER) {
  6290. //SERIAL_ECHOLNPGM("HIGH");
  6291. for (uint8_t i = 0; i < 3; i++) {
  6292. st_current_set(i, current_high[i]);
  6293. /*MYSERIAL.print(int(i));
  6294. SERIAL_ECHOPGM(": ");
  6295. MYSERIAL.println(current_high[i]);*/
  6296. }
  6297. }
  6298. else {
  6299. for (uint8_t i = 0; i < 3; i++) {
  6300. float q = current_low[i] - Z_SILENT*((current_high[i] - current_low[i]) / (Z_HIGH_POWER - Z_SILENT));
  6301. tmp_motor[i] = ((current_high[i] - current_low[i]) / (Z_HIGH_POWER - Z_SILENT))*destination[Z_AXIS] + q;
  6302. st_current_set(i, tmp_motor[i]);
  6303. /*MYSERIAL.print(int(i));
  6304. SERIAL_ECHOPGM(": ");
  6305. MYSERIAL.println(tmp_motor[i]);*/
  6306. }
  6307. }
  6308. }
  6309. #endif //MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  6310. void get_coordinates()
  6311. {
  6312. bool seen[4]={false,false,false,false};
  6313. for(int8_t i=0; i < NUM_AXIS; i++) {
  6314. if(code_seen(axis_codes[i]))
  6315. {
  6316. bool relative = axis_relative_modes[i] || relative_mode;
  6317. destination[i] = (float)code_value();
  6318. if (i == E_AXIS) {
  6319. float emult = extruder_multiplier[active_extruder];
  6320. if (emult != 1.) {
  6321. if (! relative) {
  6322. destination[i] -= current_position[i];
  6323. relative = true;
  6324. }
  6325. destination[i] *= emult;
  6326. }
  6327. }
  6328. if (relative)
  6329. destination[i] += current_position[i];
  6330. seen[i]=true;
  6331. #if MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  6332. if (i == Z_AXIS && SilentModeMenu == SILENT_MODE_AUTO) update_currents();
  6333. #endif //MOTHERBOARD == BOARD_RAMBO_MINI_1_0 || MOTHERBOARD == BOARD_RAMBO_MINI_1_3
  6334. }
  6335. else destination[i] = current_position[i]; //Are these else lines really needed?
  6336. }
  6337. if(code_seen('F')) {
  6338. next_feedrate = code_value();
  6339. #ifdef MAX_SILENT_FEEDRATE
  6340. if (tmc2130_mode == TMC2130_MODE_SILENT)
  6341. if (next_feedrate > MAX_SILENT_FEEDRATE) next_feedrate = MAX_SILENT_FEEDRATE;
  6342. #endif //MAX_SILENT_FEEDRATE
  6343. if(next_feedrate > 0.0) feedrate = next_feedrate;
  6344. if (!seen[0] && !seen[1] && !seen[2] && seen[3])
  6345. {
  6346. // float e_max_speed =
  6347. // printf_P(PSTR("E MOVE speed %7.3f\n"), feedrate / 60)
  6348. }
  6349. }
  6350. }
  6351. void get_arc_coordinates()
  6352. {
  6353. #ifdef SF_ARC_FIX
  6354. bool relative_mode_backup = relative_mode;
  6355. relative_mode = true;
  6356. #endif
  6357. get_coordinates();
  6358. #ifdef SF_ARC_FIX
  6359. relative_mode=relative_mode_backup;
  6360. #endif
  6361. if(code_seen('I')) {
  6362. offset[0] = code_value();
  6363. }
  6364. else {
  6365. offset[0] = 0.0;
  6366. }
  6367. if(code_seen('J')) {
  6368. offset[1] = code_value();
  6369. }
  6370. else {
  6371. offset[1] = 0.0;
  6372. }
  6373. }
  6374. void clamp_to_software_endstops(float target[3])
  6375. {
  6376. #ifdef DEBUG_DISABLE_SWLIMITS
  6377. return;
  6378. #endif //DEBUG_DISABLE_SWLIMITS
  6379. world2machine_clamp(target[0], target[1]);
  6380. // Clamp the Z coordinate.
  6381. if (min_software_endstops) {
  6382. float negative_z_offset = 0;
  6383. #ifdef ENABLE_AUTO_BED_LEVELING
  6384. if (Z_PROBE_OFFSET_FROM_EXTRUDER < 0) negative_z_offset = negative_z_offset + Z_PROBE_OFFSET_FROM_EXTRUDER;
  6385. if (cs.add_homing[Z_AXIS] < 0) negative_z_offset = negative_z_offset + cs.add_homing[Z_AXIS];
  6386. #endif
  6387. if (target[Z_AXIS] < min_pos[Z_AXIS]+negative_z_offset) target[Z_AXIS] = min_pos[Z_AXIS]+negative_z_offset;
  6388. }
  6389. if (max_software_endstops) {
  6390. if (target[Z_AXIS] > max_pos[Z_AXIS]) target[Z_AXIS] = max_pos[Z_AXIS];
  6391. }
  6392. }
  6393. #ifdef MESH_BED_LEVELING
  6394. 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) {
  6395. float dx = x - current_position[X_AXIS];
  6396. float dy = y - current_position[Y_AXIS];
  6397. float dz = z - current_position[Z_AXIS];
  6398. int n_segments = 0;
  6399. if (mbl.active) {
  6400. float len = abs(dx) + abs(dy);
  6401. if (len > 0)
  6402. // Split to 3cm segments or shorter.
  6403. n_segments = int(ceil(len / 30.f));
  6404. }
  6405. if (n_segments > 1) {
  6406. float de = e - current_position[E_AXIS];
  6407. for (int i = 1; i < n_segments; ++ i) {
  6408. float t = float(i) / float(n_segments);
  6409. if (saved_printing || (mbl.active == false)) return;
  6410. plan_buffer_line(
  6411. current_position[X_AXIS] + t * dx,
  6412. current_position[Y_AXIS] + t * dy,
  6413. current_position[Z_AXIS] + t * dz,
  6414. current_position[E_AXIS] + t * de,
  6415. feed_rate, extruder);
  6416. }
  6417. }
  6418. // The rest of the path.
  6419. plan_buffer_line(x, y, z, e, feed_rate, extruder);
  6420. current_position[X_AXIS] = x;
  6421. current_position[Y_AXIS] = y;
  6422. current_position[Z_AXIS] = z;
  6423. current_position[E_AXIS] = e;
  6424. }
  6425. #endif // MESH_BED_LEVELING
  6426. void prepare_move()
  6427. {
  6428. clamp_to_software_endstops(destination);
  6429. previous_millis_cmd = millis();
  6430. // Do not use feedmultiply for E or Z only moves
  6431. if( (current_position[X_AXIS] == destination [X_AXIS]) && (current_position[Y_AXIS] == destination [Y_AXIS])) {
  6432. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  6433. }
  6434. else {
  6435. #ifdef MESH_BED_LEVELING
  6436. 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);
  6437. #else
  6438. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate*feedmultiply*(1./(60.f*100.f)), active_extruder);
  6439. #endif
  6440. }
  6441. for(int8_t i=0; i < NUM_AXIS; i++) {
  6442. current_position[i] = destination[i];
  6443. }
  6444. }
  6445. void prepare_arc_move(char isclockwise) {
  6446. float r = hypot(offset[X_AXIS], offset[Y_AXIS]); // Compute arc radius for mc_arc
  6447. // Trace the arc
  6448. mc_arc(current_position, destination, offset, X_AXIS, Y_AXIS, Z_AXIS, feedrate*feedmultiply/60/100.0, r, isclockwise, active_extruder);
  6449. // As far as the parser is concerned, the position is now == target. In reality the
  6450. // motion control system might still be processing the action and the real tool position
  6451. // in any intermediate location.
  6452. for(int8_t i=0; i < NUM_AXIS; i++) {
  6453. current_position[i] = destination[i];
  6454. }
  6455. previous_millis_cmd = millis();
  6456. }
  6457. #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1
  6458. #if defined(FAN_PIN)
  6459. #if CONTROLLERFAN_PIN == FAN_PIN
  6460. #error "You cannot set CONTROLLERFAN_PIN equal to FAN_PIN"
  6461. #endif
  6462. #endif
  6463. unsigned long lastMotor = 0; //Save the time for when a motor was turned on last
  6464. unsigned long lastMotorCheck = 0;
  6465. void controllerFan()
  6466. {
  6467. if ((millis() - lastMotorCheck) >= 2500) //Not a time critical function, so we only check every 2500ms
  6468. {
  6469. lastMotorCheck = millis();
  6470. if(!READ(X_ENABLE_PIN) || !READ(Y_ENABLE_PIN) || !READ(Z_ENABLE_PIN) || (soft_pwm_bed > 0)
  6471. #if EXTRUDERS > 2
  6472. || !READ(E2_ENABLE_PIN)
  6473. #endif
  6474. #if EXTRUDER > 1
  6475. #if defined(X2_ENABLE_PIN) && X2_ENABLE_PIN > -1
  6476. || !READ(X2_ENABLE_PIN)
  6477. #endif
  6478. || !READ(E1_ENABLE_PIN)
  6479. #endif
  6480. || !READ(E0_ENABLE_PIN)) //If any of the drivers are enabled...
  6481. {
  6482. lastMotor = millis(); //... set time to NOW so the fan will turn on
  6483. }
  6484. if ((millis() - lastMotor) >= (CONTROLLERFAN_SECS*1000UL) || lastMotor == 0) //If the last time any driver was enabled, is longer since than CONTROLLERSEC...
  6485. {
  6486. digitalWrite(CONTROLLERFAN_PIN, 0);
  6487. analogWrite(CONTROLLERFAN_PIN, 0);
  6488. }
  6489. else
  6490. {
  6491. // allows digital or PWM fan output to be used (see M42 handling)
  6492. digitalWrite(CONTROLLERFAN_PIN, CONTROLLERFAN_SPEED);
  6493. analogWrite(CONTROLLERFAN_PIN, CONTROLLERFAN_SPEED);
  6494. }
  6495. }
  6496. }
  6497. #endif
  6498. #ifdef TEMP_STAT_LEDS
  6499. static bool blue_led = false;
  6500. static bool red_led = false;
  6501. static uint32_t stat_update = 0;
  6502. void handle_status_leds(void) {
  6503. float max_temp = 0.0;
  6504. if(millis() > stat_update) {
  6505. stat_update += 500; // Update every 0.5s
  6506. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  6507. max_temp = max(max_temp, degHotend(cur_extruder));
  6508. max_temp = max(max_temp, degTargetHotend(cur_extruder));
  6509. }
  6510. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  6511. max_temp = max(max_temp, degTargetBed());
  6512. max_temp = max(max_temp, degBed());
  6513. #endif
  6514. if((max_temp > 55.0) && (red_led == false)) {
  6515. digitalWrite(STAT_LED_RED, 1);
  6516. digitalWrite(STAT_LED_BLUE, 0);
  6517. red_led = true;
  6518. blue_led = false;
  6519. }
  6520. if((max_temp < 54.0) && (blue_led == false)) {
  6521. digitalWrite(STAT_LED_RED, 0);
  6522. digitalWrite(STAT_LED_BLUE, 1);
  6523. red_led = false;
  6524. blue_led = true;
  6525. }
  6526. }
  6527. }
  6528. #endif
  6529. #ifdef SAFETYTIMER
  6530. /**
  6531. * @brief Turn off heating after safetytimer_inactive_time milliseconds of inactivity
  6532. *
  6533. * Full screen blocking notification message is shown after heater turning off.
  6534. * Paused print is not considered inactivity, as nozzle is cooled anyway and bed cooling would
  6535. * damage print.
  6536. *
  6537. * If safetytimer_inactive_time is zero, feature is disabled (heating is never turned off because of inactivity)
  6538. */
  6539. static void handleSafetyTimer()
  6540. {
  6541. #if (EXTRUDERS > 1)
  6542. #error Implemented only for one extruder.
  6543. #endif //(EXTRUDERS > 1)
  6544. if ((PRINTER_ACTIVE) || (!degTargetBed() && !degTargetHotend(0)) || (!safetytimer_inactive_time))
  6545. {
  6546. safetyTimer.stop();
  6547. }
  6548. else if ((degTargetBed() || degTargetHotend(0)) && (!safetyTimer.running()))
  6549. {
  6550. safetyTimer.start();
  6551. }
  6552. else if (safetyTimer.expired(safetytimer_inactive_time))
  6553. {
  6554. setTargetBed(0);
  6555. setAllTargetHotends(0);
  6556. lcd_show_fullscreen_message_and_wait_P(_i("Heating disabled by safety timer."));////MSG_BED_HEATING_SAFETY_DISABLED c=0 r=0
  6557. }
  6558. }
  6559. #endif //SAFETYTIMER
  6560. void manage_inactivity(bool ignore_stepper_queue/*=false*/) //default argument set in Marlin.h
  6561. {
  6562. #ifdef FILAMENT_SENSOR
  6563. if (mmu_enabled == false)
  6564. {
  6565. if (mcode_in_progress != 600) //M600 not in progress
  6566. {
  6567. if (!moves_planned() && !IS_SD_PRINTING && !is_usb_printing && (lcd_commands_type != LCD_COMMAND_V2_CAL) && !wizard_active)
  6568. {
  6569. if (fsensor_check_autoload())
  6570. {
  6571. fsensor_autoload_check_stop();
  6572. if (degHotend0() > EXTRUDE_MINTEMP)
  6573. {
  6574. if ((eSoundMode == e_SOUND_MODE_LOUD) || (eSoundMode == e_SOUND_MODE_ONCE))
  6575. tone(BEEPER, 1000);
  6576. delay_keep_alive(50);
  6577. noTone(BEEPER);
  6578. loading_flag = true;
  6579. enquecommand_front_P((PSTR("M701")));
  6580. }
  6581. else
  6582. {
  6583. lcd_update_enable(false);
  6584. show_preheat_nozzle_warning();
  6585. lcd_update_enable(true);
  6586. }
  6587. }
  6588. }
  6589. else
  6590. {
  6591. fsensor_autoload_check_stop();
  6592. fsensor_update();
  6593. }
  6594. }
  6595. }
  6596. #endif //FILAMENT_SENSOR
  6597. #ifdef SAFETYTIMER
  6598. handleSafetyTimer();
  6599. #endif //SAFETYTIMER
  6600. #if defined(KILL_PIN) && KILL_PIN > -1
  6601. static int killCount = 0; // make the inactivity button a bit less responsive
  6602. const int KILL_DELAY = 10000;
  6603. #endif
  6604. if(buflen < (BUFSIZE-1)){
  6605. get_command();
  6606. }
  6607. if( (millis() - previous_millis_cmd) > max_inactive_time )
  6608. if(max_inactive_time)
  6609. kill(_n(""), 4);
  6610. if(stepper_inactive_time) {
  6611. if( (millis() - previous_millis_cmd) > stepper_inactive_time )
  6612. {
  6613. if(blocks_queued() == false && ignore_stepper_queue == false) {
  6614. disable_x();
  6615. disable_y();
  6616. disable_z();
  6617. disable_e0();
  6618. disable_e1();
  6619. disable_e2();
  6620. }
  6621. }
  6622. }
  6623. #ifdef CHDK //Check if pin should be set to LOW after M240 set it to HIGH
  6624. if (chdkActive && (millis() - chdkHigh > CHDK_DELAY))
  6625. {
  6626. chdkActive = false;
  6627. WRITE(CHDK, LOW);
  6628. }
  6629. #endif
  6630. #if defined(KILL_PIN) && KILL_PIN > -1
  6631. // Check if the kill button was pressed and wait just in case it was an accidental
  6632. // key kill key press
  6633. // -------------------------------------------------------------------------------
  6634. if( 0 == READ(KILL_PIN) )
  6635. {
  6636. killCount++;
  6637. }
  6638. else if (killCount > 0)
  6639. {
  6640. killCount--;
  6641. }
  6642. // Exceeded threshold and we can confirm that it was not accidental
  6643. // KILL the machine
  6644. // ----------------------------------------------------------------
  6645. if ( killCount >= KILL_DELAY)
  6646. {
  6647. kill("", 5);
  6648. }
  6649. #endif
  6650. #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1
  6651. controllerFan(); //Check if fan should be turned on to cool stepper drivers down
  6652. #endif
  6653. #ifdef EXTRUDER_RUNOUT_PREVENT
  6654. if( (millis() - previous_millis_cmd) > EXTRUDER_RUNOUT_SECONDS*1000 )
  6655. if(degHotend(active_extruder)>EXTRUDER_RUNOUT_MINTEMP)
  6656. {
  6657. bool oldstatus=READ(E0_ENABLE_PIN);
  6658. enable_e0();
  6659. float oldepos=current_position[E_AXIS];
  6660. float oldedes=destination[E_AXIS];
  6661. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS],
  6662. destination[E_AXIS]+EXTRUDER_RUNOUT_EXTRUDE*EXTRUDER_RUNOUT_ESTEPS/cs.axis_steps_per_unit[E_AXIS],
  6663. EXTRUDER_RUNOUT_SPEED/60.*EXTRUDER_RUNOUT_ESTEPS/cs.axis_steps_per_unit[E_AXIS], active_extruder);
  6664. current_position[E_AXIS]=oldepos;
  6665. destination[E_AXIS]=oldedes;
  6666. plan_set_e_position(oldepos);
  6667. previous_millis_cmd=millis();
  6668. st_synchronize();
  6669. WRITE(E0_ENABLE_PIN,oldstatus);
  6670. }
  6671. #endif
  6672. #ifdef TEMP_STAT_LEDS
  6673. handle_status_leds();
  6674. #endif
  6675. check_axes_activity();
  6676. mmu_loop();
  6677. }
  6678. void kill(const char *full_screen_message, unsigned char id)
  6679. {
  6680. printf_P(_N("KILL: %d\n"), id);
  6681. //return;
  6682. cli(); // Stop interrupts
  6683. disable_heater();
  6684. disable_x();
  6685. // SERIAL_ECHOLNPGM("kill - disable Y");
  6686. disable_y();
  6687. disable_z();
  6688. disable_e0();
  6689. disable_e1();
  6690. disable_e2();
  6691. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  6692. pinMode(PS_ON_PIN,INPUT);
  6693. #endif
  6694. SERIAL_ERROR_START;
  6695. SERIAL_ERRORLNRPGM(_n("Printer halted. kill() called!"));////MSG_ERR_KILLED c=0 r=0
  6696. if (full_screen_message != NULL) {
  6697. SERIAL_ERRORLNRPGM(full_screen_message);
  6698. lcd_display_message_fullscreen_P(full_screen_message);
  6699. } else {
  6700. LCD_ALERTMESSAGERPGM(_n("KILLED. "));////MSG_KILLED c=0 r=0
  6701. }
  6702. // FMC small patch to update the LCD before ending
  6703. sei(); // enable interrupts
  6704. for ( int i=5; i--; lcd_update(0))
  6705. {
  6706. delay(200);
  6707. }
  6708. cli(); // disable interrupts
  6709. suicide();
  6710. while(1)
  6711. {
  6712. #ifdef WATCHDOG
  6713. wdt_reset();
  6714. #endif //WATCHDOG
  6715. /* Intentionally left empty */
  6716. } // Wait for reset
  6717. }
  6718. void Stop()
  6719. {
  6720. disable_heater();
  6721. if(Stopped == false) {
  6722. Stopped = true;
  6723. Stopped_gcode_LastN = gcode_LastN; // Save last g_code for restart
  6724. SERIAL_ERROR_START;
  6725. SERIAL_ERRORLNRPGM(MSG_ERR_STOPPED);
  6726. LCD_MESSAGERPGM(_T(MSG_STOPPED));
  6727. }
  6728. }
  6729. bool IsStopped() { return Stopped; };
  6730. #ifdef FAST_PWM_FAN
  6731. void setPwmFrequency(uint8_t pin, int val)
  6732. {
  6733. val &= 0x07;
  6734. switch(digitalPinToTimer(pin))
  6735. {
  6736. #if defined(TCCR0A)
  6737. case TIMER0A:
  6738. case TIMER0B:
  6739. // TCCR0B &= ~(_BV(CS00) | _BV(CS01) | _BV(CS02));
  6740. // TCCR0B |= val;
  6741. break;
  6742. #endif
  6743. #if defined(TCCR1A)
  6744. case TIMER1A:
  6745. case TIMER1B:
  6746. // TCCR1B &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  6747. // TCCR1B |= val;
  6748. break;
  6749. #endif
  6750. #if defined(TCCR2)
  6751. case TIMER2:
  6752. case TIMER2:
  6753. TCCR2 &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  6754. TCCR2 |= val;
  6755. break;
  6756. #endif
  6757. #if defined(TCCR2A)
  6758. case TIMER2A:
  6759. case TIMER2B:
  6760. TCCR2B &= ~(_BV(CS20) | _BV(CS21) | _BV(CS22));
  6761. TCCR2B |= val;
  6762. break;
  6763. #endif
  6764. #if defined(TCCR3A)
  6765. case TIMER3A:
  6766. case TIMER3B:
  6767. case TIMER3C:
  6768. TCCR3B &= ~(_BV(CS30) | _BV(CS31) | _BV(CS32));
  6769. TCCR3B |= val;
  6770. break;
  6771. #endif
  6772. #if defined(TCCR4A)
  6773. case TIMER4A:
  6774. case TIMER4B:
  6775. case TIMER4C:
  6776. TCCR4B &= ~(_BV(CS40) | _BV(CS41) | _BV(CS42));
  6777. TCCR4B |= val;
  6778. break;
  6779. #endif
  6780. #if defined(TCCR5A)
  6781. case TIMER5A:
  6782. case TIMER5B:
  6783. case TIMER5C:
  6784. TCCR5B &= ~(_BV(CS50) | _BV(CS51) | _BV(CS52));
  6785. TCCR5B |= val;
  6786. break;
  6787. #endif
  6788. }
  6789. }
  6790. #endif //FAST_PWM_FAN
  6791. //! @brief Get and validate extruder number
  6792. //!
  6793. //! If it is not specified, active_extruder is returned in parameter extruder.
  6794. //! @param [in] code M code number
  6795. //! @param [out] extruder
  6796. //! @return error
  6797. //! @retval true Invalid extruder specified in T code
  6798. //! @retval false Valid extruder specified in T code, or not specifiead
  6799. bool setTargetedHotend(int code, uint8_t &extruder)
  6800. {
  6801. extruder = active_extruder;
  6802. if(code_seen('T')) {
  6803. extruder = code_value();
  6804. if(extruder >= EXTRUDERS) {
  6805. SERIAL_ECHO_START;
  6806. switch(code){
  6807. case 104:
  6808. SERIAL_ECHORPGM(_n("M104 Invalid extruder "));////MSG_M104_INVALID_EXTRUDER c=0 r=0
  6809. break;
  6810. case 105:
  6811. SERIAL_ECHO(_n("M105 Invalid extruder "));////MSG_M105_INVALID_EXTRUDER c=0 r=0
  6812. break;
  6813. case 109:
  6814. SERIAL_ECHO(_n("M109 Invalid extruder "));////MSG_M109_INVALID_EXTRUDER c=0 r=0
  6815. break;
  6816. case 218:
  6817. SERIAL_ECHO(_n("M218 Invalid extruder "));////MSG_M218_INVALID_EXTRUDER c=0 r=0
  6818. break;
  6819. case 221:
  6820. SERIAL_ECHO(_n("M221 Invalid extruder "));////MSG_M221_INVALID_EXTRUDER c=0 r=0
  6821. break;
  6822. }
  6823. SERIAL_PROTOCOLLN((int)extruder);
  6824. return true;
  6825. }
  6826. }
  6827. return false;
  6828. }
  6829. void save_statistics(unsigned long _total_filament_used, unsigned long _total_print_time) //_total_filament_used unit: mm/100; print time in s
  6830. {
  6831. 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)
  6832. {
  6833. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, 0);
  6834. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, 0);
  6835. }
  6836. unsigned long _previous_filament = eeprom_read_dword((uint32_t *)EEPROM_FILAMENTUSED); //_previous_filament unit: cm
  6837. unsigned long _previous_time = eeprom_read_dword((uint32_t *)EEPROM_TOTALTIME); //_previous_time unit: min
  6838. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, _previous_time + (_total_print_time/60)); //EEPROM_TOTALTIME unit: min
  6839. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, _previous_filament + (_total_filament_used / 1000));
  6840. total_filament_used = 0;
  6841. }
  6842. float calculate_extruder_multiplier(float diameter) {
  6843. float out = 1.f;
  6844. if (cs.volumetric_enabled && diameter > 0.f) {
  6845. float area = M_PI * diameter * diameter * 0.25;
  6846. out = 1.f / area;
  6847. }
  6848. if (extrudemultiply != 100)
  6849. out *= float(extrudemultiply) * 0.01f;
  6850. return out;
  6851. }
  6852. void calculate_extruder_multipliers() {
  6853. extruder_multiplier[0] = calculate_extruder_multiplier(cs.filament_size[0]);
  6854. #if EXTRUDERS > 1
  6855. extruder_multiplier[1] = calculate_extruder_multiplier(cs.filament_size[1]);
  6856. #if EXTRUDERS > 2
  6857. extruder_multiplier[2] = calculate_extruder_multiplier(cs.filament_size[2]);
  6858. #endif
  6859. #endif
  6860. }
  6861. void delay_keep_alive(unsigned int ms)
  6862. {
  6863. for (;;) {
  6864. manage_heater();
  6865. // Manage inactivity, but don't disable steppers on timeout.
  6866. manage_inactivity(true);
  6867. lcd_update(0);
  6868. if (ms == 0)
  6869. break;
  6870. else if (ms >= 50) {
  6871. delay(50);
  6872. ms -= 50;
  6873. } else {
  6874. delay(ms);
  6875. ms = 0;
  6876. }
  6877. }
  6878. }
  6879. static void wait_for_heater(long codenum, uint8_t extruder) {
  6880. #ifdef TEMP_RESIDENCY_TIME
  6881. long residencyStart;
  6882. residencyStart = -1;
  6883. /* continue to loop until we have reached the target temp
  6884. _and_ until TEMP_RESIDENCY_TIME hasn't passed since we reached it */
  6885. while ((!cancel_heatup) && ((residencyStart == -1) ||
  6886. (residencyStart >= 0 && (((unsigned int)(millis() - residencyStart)) < (TEMP_RESIDENCY_TIME * 1000UL))))) {
  6887. #else
  6888. while (target_direction ? (isHeatingHotend(tmp_extruder)) : (isCoolingHotend(tmp_extruder) && (CooldownNoWait == false))) {
  6889. #endif //TEMP_RESIDENCY_TIME
  6890. if ((millis() - codenum) > 1000UL)
  6891. { //Print Temp Reading and remaining time every 1 second while heating up/cooling down
  6892. if (!farm_mode) {
  6893. SERIAL_PROTOCOLPGM("T:");
  6894. SERIAL_PROTOCOL_F(degHotend(extruder), 1);
  6895. SERIAL_PROTOCOLPGM(" E:");
  6896. SERIAL_PROTOCOL((int)extruder);
  6897. #ifdef TEMP_RESIDENCY_TIME
  6898. SERIAL_PROTOCOLPGM(" W:");
  6899. if (residencyStart > -1)
  6900. {
  6901. codenum = ((TEMP_RESIDENCY_TIME * 1000UL) - (millis() - residencyStart)) / 1000UL;
  6902. SERIAL_PROTOCOLLN(codenum);
  6903. }
  6904. else
  6905. {
  6906. SERIAL_PROTOCOLLN("?");
  6907. }
  6908. }
  6909. #else
  6910. SERIAL_PROTOCOLLN("");
  6911. #endif
  6912. codenum = millis();
  6913. }
  6914. manage_heater();
  6915. manage_inactivity(true); //do not disable steppers
  6916. lcd_update(0);
  6917. #ifdef TEMP_RESIDENCY_TIME
  6918. /* start/restart the TEMP_RESIDENCY_TIME timer whenever we reach target temp for the first time
  6919. or when current temp falls outside the hysteresis after target temp was reached */
  6920. if ((residencyStart == -1 && target_direction && (degHotend(extruder) >= (degTargetHotend(extruder) - TEMP_WINDOW))) ||
  6921. (residencyStart == -1 && !target_direction && (degHotend(extruder) <= (degTargetHotend(extruder) + TEMP_WINDOW))) ||
  6922. (residencyStart > -1 && labs(degHotend(extruder) - degTargetHotend(extruder)) > TEMP_HYSTERESIS))
  6923. {
  6924. residencyStart = millis();
  6925. }
  6926. #endif //TEMP_RESIDENCY_TIME
  6927. }
  6928. }
  6929. void check_babystep()
  6930. {
  6931. int babystep_z;
  6932. EEPROM_read_B(EEPROM_BABYSTEP_Z, &babystep_z);
  6933. if ((babystep_z < Z_BABYSTEP_MIN) || (babystep_z > Z_BABYSTEP_MAX)) {
  6934. babystep_z = 0; //if babystep value is out of min max range, set it to 0
  6935. SERIAL_ECHOLNPGM("Z live adjust out of range. Setting to 0");
  6936. EEPROM_save_B(EEPROM_BABYSTEP_Z, &babystep_z);
  6937. lcd_show_fullscreen_message_and_wait_P(PSTR("Z live adjust out of range. Setting to 0. Click to continue."));
  6938. lcd_update_enable(true);
  6939. }
  6940. }
  6941. #ifdef DIS
  6942. void d_setup()
  6943. {
  6944. pinMode(D_DATACLOCK, INPUT_PULLUP);
  6945. pinMode(D_DATA, INPUT_PULLUP);
  6946. pinMode(D_REQUIRE, OUTPUT);
  6947. digitalWrite(D_REQUIRE, HIGH);
  6948. }
  6949. float d_ReadData()
  6950. {
  6951. int digit[13];
  6952. String mergeOutput;
  6953. float output;
  6954. digitalWrite(D_REQUIRE, HIGH);
  6955. for (int i = 0; i<13; i++)
  6956. {
  6957. for (int j = 0; j < 4; j++)
  6958. {
  6959. while (digitalRead(D_DATACLOCK) == LOW) {}
  6960. while (digitalRead(D_DATACLOCK) == HIGH) {}
  6961. bitWrite(digit[i], j, digitalRead(D_DATA));
  6962. }
  6963. }
  6964. digitalWrite(D_REQUIRE, LOW);
  6965. mergeOutput = "";
  6966. output = 0;
  6967. for (int r = 5; r <= 10; r++) //Merge digits
  6968. {
  6969. mergeOutput += digit[r];
  6970. }
  6971. output = mergeOutput.toFloat();
  6972. if (digit[4] == 8) //Handle sign
  6973. {
  6974. output *= -1;
  6975. }
  6976. for (int i = digit[11]; i > 0; i--) //Handle floating point
  6977. {
  6978. output /= 10;
  6979. }
  6980. return output;
  6981. }
  6982. void bed_analysis(float x_dimension, float y_dimension, int x_points_num, int y_points_num, float shift_x, float shift_y) {
  6983. int t1 = 0;
  6984. int t_delay = 0;
  6985. int digit[13];
  6986. int m;
  6987. char str[3];
  6988. //String mergeOutput;
  6989. char mergeOutput[15];
  6990. float output;
  6991. int mesh_point = 0; //index number of calibration point
  6992. 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
  6993. float bed_zero_ref_y = (-0.6f + Y_PROBE_OFFSET_FROM_EXTRUDER);
  6994. float mesh_home_z_search = 4;
  6995. float row[x_points_num];
  6996. int ix = 0;
  6997. int iy = 0;
  6998. const char* filename_wldsd = "wldsd.txt";
  6999. char data_wldsd[70];
  7000. char numb_wldsd[10];
  7001. d_setup();
  7002. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  7003. // We don't know where we are! HOME!
  7004. // Push the commands to the front of the message queue in the reverse order!
  7005. // There shall be always enough space reserved for these commands.
  7006. repeatcommand_front(); // repeat G80 with all its parameters
  7007. enquecommand_front_P((PSTR("G28 W0")));
  7008. enquecommand_front_P((PSTR("G1 Z5")));
  7009. return;
  7010. }
  7011. unsigned int custom_message_type_old = custom_message_type;
  7012. unsigned int custom_message_state_old = custom_message_state;
  7013. custom_message_type = CUSTOM_MSG_TYPE_MESHBL;
  7014. custom_message_state = (x_points_num * y_points_num) + 10;
  7015. lcd_update(1);
  7016. mbl.reset();
  7017. babystep_undo();
  7018. card.openFile(filename_wldsd, false);
  7019. current_position[Z_AXIS] = mesh_home_z_search;
  7020. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], homing_feedrate[Z_AXIS] / 60, active_extruder);
  7021. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  7022. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  7023. int l_feedmultiply = setup_for_endstop_move(false);
  7024. SERIAL_PROTOCOLPGM("Num X,Y: ");
  7025. SERIAL_PROTOCOL(x_points_num);
  7026. SERIAL_PROTOCOLPGM(",");
  7027. SERIAL_PROTOCOL(y_points_num);
  7028. SERIAL_PROTOCOLPGM("\nZ search height: ");
  7029. SERIAL_PROTOCOL(mesh_home_z_search);
  7030. SERIAL_PROTOCOLPGM("\nDimension X,Y: ");
  7031. SERIAL_PROTOCOL(x_dimension);
  7032. SERIAL_PROTOCOLPGM(",");
  7033. SERIAL_PROTOCOL(y_dimension);
  7034. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  7035. while (mesh_point != x_points_num * y_points_num) {
  7036. ix = mesh_point % x_points_num; // from 0 to MESH_NUM_X_POINTS - 1
  7037. iy = mesh_point / x_points_num;
  7038. if (iy & 1) ix = (x_points_num - 1) - ix; // Zig zag
  7039. float z0 = 0.f;
  7040. current_position[Z_AXIS] = mesh_home_z_search;
  7041. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], Z_LIFT_FEEDRATE, active_extruder);
  7042. st_synchronize();
  7043. current_position[X_AXIS] = 13.f + ix * (x_dimension / (x_points_num - 1)) - bed_zero_ref_x + shift_x;
  7044. current_position[Y_AXIS] = 6.4f + iy * (y_dimension / (y_points_num - 1)) - bed_zero_ref_y + shift_y;
  7045. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], XY_AXIS_FEEDRATE, active_extruder);
  7046. st_synchronize();
  7047. 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
  7048. break;
  7049. card.closefile();
  7050. }
  7051. //memset(numb_wldsd, 0, sizeof(numb_wldsd));
  7052. //dtostrf(d_ReadData(), 8, 5, numb_wldsd);
  7053. //strcat(data_wldsd, numb_wldsd);
  7054. //MYSERIAL.println(data_wldsd);
  7055. //delay(1000);
  7056. //delay(3000);
  7057. //t1 = millis();
  7058. //while (digitalRead(D_DATACLOCK) == LOW) {}
  7059. //while (digitalRead(D_DATACLOCK) == HIGH) {}
  7060. memset(digit, 0, sizeof(digit));
  7061. //cli();
  7062. digitalWrite(D_REQUIRE, LOW);
  7063. for (int i = 0; i<13; i++)
  7064. {
  7065. //t1 = millis();
  7066. for (int j = 0; j < 4; j++)
  7067. {
  7068. while (digitalRead(D_DATACLOCK) == LOW) {}
  7069. while (digitalRead(D_DATACLOCK) == HIGH) {}
  7070. bitWrite(digit[i], j, digitalRead(D_DATA));
  7071. }
  7072. //t_delay = (millis() - t1);
  7073. //SERIAL_PROTOCOLPGM(" ");
  7074. //SERIAL_PROTOCOL_F(t_delay, 5);
  7075. //SERIAL_PROTOCOLPGM(" ");
  7076. }
  7077. //sei();
  7078. digitalWrite(D_REQUIRE, HIGH);
  7079. mergeOutput[0] = '\0';
  7080. output = 0;
  7081. for (int r = 5; r <= 10; r++) //Merge digits
  7082. {
  7083. sprintf(str, "%d", digit[r]);
  7084. strcat(mergeOutput, str);
  7085. }
  7086. output = atof(mergeOutput);
  7087. if (digit[4] == 8) //Handle sign
  7088. {
  7089. output *= -1;
  7090. }
  7091. for (int i = digit[11]; i > 0; i--) //Handle floating point
  7092. {
  7093. output *= 0.1;
  7094. }
  7095. //output = d_ReadData();
  7096. //row[ix] = current_position[Z_AXIS];
  7097. memset(data_wldsd, 0, sizeof(data_wldsd));
  7098. for (int i = 0; i <3; i++) {
  7099. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  7100. dtostrf(current_position[i], 8, 5, numb_wldsd);
  7101. strcat(data_wldsd, numb_wldsd);
  7102. strcat(data_wldsd, ";");
  7103. }
  7104. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  7105. dtostrf(output, 8, 5, numb_wldsd);
  7106. strcat(data_wldsd, numb_wldsd);
  7107. //strcat(data_wldsd, ";");
  7108. card.write_command(data_wldsd);
  7109. //row[ix] = d_ReadData();
  7110. row[ix] = output; // current_position[Z_AXIS];
  7111. if (iy % 2 == 1 ? ix == 0 : ix == x_points_num - 1) {
  7112. for (int i = 0; i < x_points_num; i++) {
  7113. SERIAL_PROTOCOLPGM(" ");
  7114. SERIAL_PROTOCOL_F(row[i], 5);
  7115. }
  7116. SERIAL_PROTOCOLPGM("\n");
  7117. }
  7118. custom_message_state--;
  7119. mesh_point++;
  7120. lcd_update(1);
  7121. }
  7122. card.closefile();
  7123. clean_up_after_endstop_move(l_feedmultiply);
  7124. }
  7125. #endif
  7126. void temp_compensation_start() {
  7127. custom_message_type = CUSTOM_MSG_TYPE_TEMPRE;
  7128. custom_message_state = PINDA_HEAT_T + 1;
  7129. lcd_update(2);
  7130. if (degHotend(active_extruder) > EXTRUDE_MINTEMP) {
  7131. current_position[E_AXIS] -= default_retraction;
  7132. }
  7133. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 400, active_extruder);
  7134. current_position[X_AXIS] = PINDA_PREHEAT_X;
  7135. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  7136. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  7137. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  7138. st_synchronize();
  7139. while (fabs(degBed() - target_temperature_bed) > 1) delay_keep_alive(1000);
  7140. for (int i = 0; i < PINDA_HEAT_T; i++) {
  7141. delay_keep_alive(1000);
  7142. custom_message_state = PINDA_HEAT_T - i;
  7143. if (custom_message_state == 99 || custom_message_state == 9) lcd_update(2); //force whole display redraw if number of digits changed
  7144. else lcd_update(1);
  7145. }
  7146. custom_message_type = CUSTOM_MSG_TYPE_STATUS;
  7147. custom_message_state = 0;
  7148. }
  7149. void temp_compensation_apply() {
  7150. int i_add;
  7151. int z_shift = 0;
  7152. float z_shift_mm;
  7153. if (calibration_status() == CALIBRATION_STATUS_CALIBRATED) {
  7154. if (target_temperature_bed % 10 == 0 && target_temperature_bed >= 60 && target_temperature_bed <= 100) {
  7155. i_add = (target_temperature_bed - 60) / 10;
  7156. EEPROM_read_B(EEPROM_PROBE_TEMP_SHIFT + i_add * 2, &z_shift);
  7157. z_shift_mm = z_shift / cs.axis_steps_per_unit[Z_AXIS];
  7158. }else {
  7159. //interpolation
  7160. z_shift_mm = temp_comp_interpolation(target_temperature_bed) / cs.axis_steps_per_unit[Z_AXIS];
  7161. }
  7162. printf_P(_N("\nZ shift applied:%.3f\n"), z_shift_mm);
  7163. 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);
  7164. st_synchronize();
  7165. plan_set_z_position(current_position[Z_AXIS]);
  7166. }
  7167. else {
  7168. //we have no temp compensation data
  7169. }
  7170. }
  7171. float temp_comp_interpolation(float inp_temperature) {
  7172. //cubic spline interpolation
  7173. int n, i, j;
  7174. float h[10], a, b, c, d, sum, s[10] = { 0 }, x[10], F[10], f[10], m[10][10] = { 0 }, temp;
  7175. int shift[10];
  7176. int temp_C[10];
  7177. n = 6; //number of measured points
  7178. shift[0] = 0;
  7179. for (i = 0; i < n; i++) {
  7180. if (i>0) EEPROM_read_B(EEPROM_PROBE_TEMP_SHIFT + (i-1) * 2, &shift[i]); //read shift in steps from EEPROM
  7181. temp_C[i] = 50 + i * 10; //temperature in C
  7182. #ifdef PINDA_THERMISTOR
  7183. temp_C[i] = 35 + i * 5; //temperature in C
  7184. #else
  7185. temp_C[i] = 50 + i * 10; //temperature in C
  7186. #endif
  7187. x[i] = (float)temp_C[i];
  7188. f[i] = (float)shift[i];
  7189. }
  7190. if (inp_temperature < x[0]) return 0;
  7191. for (i = n - 1; i>0; i--) {
  7192. F[i] = (f[i] - f[i - 1]) / (x[i] - x[i - 1]);
  7193. h[i - 1] = x[i] - x[i - 1];
  7194. }
  7195. //*********** formation of h, s , f matrix **************
  7196. for (i = 1; i<n - 1; i++) {
  7197. m[i][i] = 2 * (h[i - 1] + h[i]);
  7198. if (i != 1) {
  7199. m[i][i - 1] = h[i - 1];
  7200. m[i - 1][i] = h[i - 1];
  7201. }
  7202. m[i][n - 1] = 6 * (F[i + 1] - F[i]);
  7203. }
  7204. //*********** forward elimination **************
  7205. for (i = 1; i<n - 2; i++) {
  7206. temp = (m[i + 1][i] / m[i][i]);
  7207. for (j = 1; j <= n - 1; j++)
  7208. m[i + 1][j] -= temp*m[i][j];
  7209. }
  7210. //*********** backward substitution *********
  7211. for (i = n - 2; i>0; i--) {
  7212. sum = 0;
  7213. for (j = i; j <= n - 2; j++)
  7214. sum += m[i][j] * s[j];
  7215. s[i] = (m[i][n - 1] - sum) / m[i][i];
  7216. }
  7217. for (i = 0; i<n - 1; i++)
  7218. if ((x[i] <= inp_temperature && inp_temperature <= x[i + 1]) || (i == n-2 && inp_temperature > x[i + 1])) {
  7219. a = (s[i + 1] - s[i]) / (6 * h[i]);
  7220. b = s[i] / 2;
  7221. c = (f[i + 1] - f[i]) / h[i] - (2 * h[i] * s[i] + s[i + 1] * h[i]) / 6;
  7222. d = f[i];
  7223. sum = a*pow((inp_temperature - x[i]), 3) + b*pow((inp_temperature - x[i]), 2) + c*(inp_temperature - x[i]) + d;
  7224. }
  7225. return sum;
  7226. }
  7227. #ifdef PINDA_THERMISTOR
  7228. float temp_compensation_pinda_thermistor_offset(float temperature_pinda)
  7229. {
  7230. if (!temp_cal_active) return 0;
  7231. if (!calibration_status_pinda()) return 0;
  7232. return temp_comp_interpolation(temperature_pinda) / cs.axis_steps_per_unit[Z_AXIS];
  7233. }
  7234. #endif //PINDA_THERMISTOR
  7235. void long_pause() //long pause print
  7236. {
  7237. st_synchronize();
  7238. start_pause_print = millis();
  7239. //retract
  7240. current_position[E_AXIS] -= default_retraction;
  7241. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 400, active_extruder);
  7242. //lift z
  7243. current_position[Z_AXIS] += Z_PAUSE_LIFT;
  7244. if (current_position[Z_AXIS] > Z_MAX_POS) current_position[Z_AXIS] = Z_MAX_POS;
  7245. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 15, active_extruder);
  7246. //Move XY to side
  7247. current_position[X_AXIS] = X_PAUSE_POS;
  7248. current_position[Y_AXIS] = Y_PAUSE_POS;
  7249. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 50, active_extruder);
  7250. // Turn off the print fan
  7251. fanSpeed = 0;
  7252. st_synchronize();
  7253. }
  7254. void serialecho_temperatures() {
  7255. float tt = degHotend(active_extruder);
  7256. SERIAL_PROTOCOLPGM("T:");
  7257. SERIAL_PROTOCOL(tt);
  7258. SERIAL_PROTOCOLPGM(" E:");
  7259. SERIAL_PROTOCOL((int)active_extruder);
  7260. SERIAL_PROTOCOLPGM(" B:");
  7261. SERIAL_PROTOCOL_F(degBed(), 1);
  7262. SERIAL_PROTOCOLLN("");
  7263. }
  7264. extern uint32_t sdpos_atomic;
  7265. #ifdef UVLO_SUPPORT
  7266. void uvlo_()
  7267. {
  7268. unsigned long time_start = millis();
  7269. bool sd_print = card.sdprinting;
  7270. // Conserve power as soon as possible.
  7271. disable_x();
  7272. disable_y();
  7273. #ifdef TMC2130
  7274. tmc2130_set_current_h(Z_AXIS, 20);
  7275. tmc2130_set_current_r(Z_AXIS, 20);
  7276. tmc2130_set_current_h(E_AXIS, 20);
  7277. tmc2130_set_current_r(E_AXIS, 20);
  7278. #endif //TMC2130
  7279. // Indicate that the interrupt has been triggered.
  7280. // SERIAL_ECHOLNPGM("UVLO");
  7281. // Read out the current Z motor microstep counter. This will be later used
  7282. // for reaching the zero full step before powering off.
  7283. uint16_t z_microsteps = 0;
  7284. #ifdef TMC2130
  7285. z_microsteps = tmc2130_rd_MSCNT(Z_TMC2130_CS);
  7286. #endif //TMC2130
  7287. // Calculate the file position, from which to resume this print.
  7288. long sd_position = sdpos_atomic; //atomic sd position of last command added in queue
  7289. {
  7290. uint16_t sdlen_planner = planner_calc_sd_length(); //length of sd commands in planner
  7291. sd_position -= sdlen_planner;
  7292. uint16_t sdlen_cmdqueue = cmdqueue_calc_sd_length(); //length of sd commands in cmdqueue
  7293. sd_position -= sdlen_cmdqueue;
  7294. if (sd_position < 0) sd_position = 0;
  7295. }
  7296. // Backup the feedrate in mm/min.
  7297. int feedrate_bckp = blocks_queued() ? (block_buffer[block_buffer_tail].nominal_speed * 60.f) : feedrate;
  7298. // After this call, the planner queue is emptied and the current_position is set to a current logical coordinate.
  7299. // The logical coordinate will likely differ from the machine coordinate if the skew calibration and mesh bed leveling
  7300. // are in action.
  7301. planner_abort_hard();
  7302. // Store the current extruder position.
  7303. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION_E), st_get_position_mm(E_AXIS));
  7304. eeprom_update_byte((uint8_t*)EEPROM_UVLO_E_ABS, axis_relative_modes[3]?0:1);
  7305. // Clean the input command queue.
  7306. cmdqueue_reset();
  7307. card.sdprinting = false;
  7308. // card.closefile();
  7309. // Enable stepper driver interrupt to move Z axis.
  7310. // This should be fine as the planner and command queues are empty and the SD card printing is disabled.
  7311. //FIXME one may want to disable serial lines at this point of time to avoid interfering with the command queue,
  7312. // though it should not happen that the command queue is touched as the plan_buffer_line always succeed without blocking.
  7313. sei();
  7314. plan_buffer_line(
  7315. current_position[X_AXIS],
  7316. current_position[Y_AXIS],
  7317. current_position[Z_AXIS],
  7318. current_position[E_AXIS] - default_retraction,
  7319. 95, active_extruder);
  7320. st_synchronize();
  7321. disable_e0();
  7322. plan_buffer_line(
  7323. current_position[X_AXIS],
  7324. current_position[Y_AXIS],
  7325. current_position[Z_AXIS] + UVLO_Z_AXIS_SHIFT + float((1024 - z_microsteps + 7) >> 4) / cs.axis_steps_per_unit[Z_AXIS],
  7326. current_position[E_AXIS] - default_retraction,
  7327. 40, active_extruder);
  7328. st_synchronize();
  7329. disable_e0();
  7330. plan_buffer_line(
  7331. current_position[X_AXIS],
  7332. current_position[Y_AXIS],
  7333. current_position[Z_AXIS] + UVLO_Z_AXIS_SHIFT + float((1024 - z_microsteps + 7) >> 4) / cs.axis_steps_per_unit[Z_AXIS],
  7334. current_position[E_AXIS] - default_retraction,
  7335. 40, active_extruder);
  7336. st_synchronize();
  7337. disable_e0();
  7338. disable_z();
  7339. // Move Z up to the next 0th full step.
  7340. // Write the file position.
  7341. eeprom_update_dword((uint32_t*)(EEPROM_FILE_POSITION), sd_position);
  7342. // Store the mesh bed leveling offsets. This is 2*9=18 bytes, which takes 18*3.4us=52us in worst case.
  7343. for (int8_t mesh_point = 0; mesh_point < 9; ++ mesh_point) {
  7344. uint8_t ix = mesh_point % MESH_MEAS_NUM_X_POINTS; // from 0 to MESH_NUM_X_POINTS - 1
  7345. uint8_t iy = mesh_point / MESH_MEAS_NUM_X_POINTS;
  7346. // Scale the z value to 1u resolution.
  7347. int16_t v = mbl.active ? int16_t(floor(mbl.z_values[iy*3][ix*3] * 1000.f + 0.5f)) : 0;
  7348. eeprom_update_word((uint16_t*)(EEPROM_UVLO_MESH_BED_LEVELING+2*mesh_point), *reinterpret_cast<uint16_t*>(&v));
  7349. }
  7350. // Read out the current Z motor microstep counter. This will be later used
  7351. // for reaching the zero full step before powering off.
  7352. eeprom_update_word((uint16_t*)(EEPROM_UVLO_Z_MICROSTEPS), z_microsteps);
  7353. // Store the current position.
  7354. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0), current_position[X_AXIS]);
  7355. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 4), current_position[Y_AXIS]);
  7356. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION_Z), current_position[Z_AXIS]);
  7357. // Store the current feed rate, temperatures, fan speed and extruder multipliers (flow rates)
  7358. EEPROM_save_B(EEPROM_UVLO_FEEDRATE, &feedrate_bckp);
  7359. eeprom_update_byte((uint8_t*)EEPROM_UVLO_TARGET_HOTEND, target_temperature[active_extruder]);
  7360. eeprom_update_byte((uint8_t*)EEPROM_UVLO_TARGET_BED, target_temperature_bed);
  7361. eeprom_update_byte((uint8_t*)EEPROM_UVLO_FAN_SPEED, fanSpeed);
  7362. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_0), extruder_multiplier[0]);
  7363. #if EXTRUDERS > 1
  7364. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_1), extruder_multiplier[1]);
  7365. #if EXTRUDERS > 2
  7366. eeprom_update_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_2), extruder_multiplier[2]);
  7367. #endif
  7368. #endif
  7369. eeprom_update_word((uint16_t*)(EEPROM_EXTRUDEMULTIPLY), (uint16_t)extrudemultiply);
  7370. // Finaly store the "power outage" flag.
  7371. if(sd_print) eeprom_update_byte((uint8_t*)EEPROM_UVLO, 1);
  7372. st_synchronize();
  7373. printf_P(_N("stps%d\n"), tmc2130_rd_MSCNT(Z_AXIS));
  7374. disable_z();
  7375. // Increment power failure counter
  7376. eeprom_update_byte((uint8_t*)EEPROM_POWER_COUNT, eeprom_read_byte((uint8_t*)EEPROM_POWER_COUNT) + 1);
  7377. eeprom_update_word((uint16_t*)EEPROM_POWER_COUNT_TOT, eeprom_read_word((uint16_t*)EEPROM_POWER_COUNT_TOT) + 1);
  7378. printf_P(_N("UVLO - end %d\n"), millis() - time_start);
  7379. #if 0
  7380. // Move the print head to the side of the print until all the power stored in the power supply capacitors is depleted.
  7381. current_position[X_AXIS] = (current_position[X_AXIS] < 0.5f * (X_MIN_POS + X_MAX_POS)) ? X_MIN_POS : X_MAX_POS;
  7382. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 500, active_extruder);
  7383. st_synchronize();
  7384. #endif
  7385. wdt_enable(WDTO_500MS);
  7386. WRITE(BEEPER,HIGH);
  7387. while(1)
  7388. ;
  7389. }
  7390. void uvlo_tiny()
  7391. {
  7392. uint16_t z_microsteps=0;
  7393. // Conserve power as soon as possible.
  7394. disable_x();
  7395. disable_y();
  7396. disable_e0();
  7397. #ifdef TMC2130
  7398. tmc2130_set_current_h(Z_AXIS, 20);
  7399. tmc2130_set_current_r(Z_AXIS, 20);
  7400. #endif //TMC2130
  7401. // Read out the current Z motor microstep counter
  7402. #ifdef TMC2130
  7403. z_microsteps=tmc2130_rd_MSCNT(Z_TMC2130_CS);
  7404. #endif //TMC2130
  7405. planner_abort_hard();
  7406. sei();
  7407. plan_buffer_line(
  7408. current_position[X_AXIS],
  7409. current_position[Y_AXIS],
  7410. // current_position[Z_AXIS]+float((1024-z_microsteps+7)>>4)/axis_steps_per_unit[Z_AXIS],
  7411. current_position[Z_AXIS]+UVLO_Z_AXIS_SHIFT+float((1024-z_microsteps+7)>>4)/cs.axis_steps_per_unit[Z_AXIS],
  7412. current_position[E_AXIS],
  7413. 40, active_extruder);
  7414. st_synchronize();
  7415. disable_z();
  7416. // Finaly store the "power outage" flag.
  7417. //if(sd_print)
  7418. eeprom_update_byte((uint8_t*)EEPROM_UVLO,2);
  7419. eeprom_update_word((uint16_t*)(EEPROM_UVLO_TINY_Z_MICROSTEPS),z_microsteps);
  7420. eeprom_update_float((float*)(EEPROM_UVLO_TINY_CURRENT_POSITION_Z), current_position[Z_AXIS]);
  7421. // Increment power failure counter
  7422. eeprom_update_byte((uint8_t*)EEPROM_POWER_COUNT, eeprom_read_byte((uint8_t*)EEPROM_POWER_COUNT) + 1);
  7423. eeprom_update_word((uint16_t*)EEPROM_POWER_COUNT_TOT, eeprom_read_word((uint16_t*)EEPROM_POWER_COUNT_TOT) + 1);
  7424. wdt_enable(WDTO_500MS);
  7425. WRITE(BEEPER,HIGH);
  7426. while(1)
  7427. ;
  7428. }
  7429. #endif //UVLO_SUPPORT
  7430. #if (defined(FANCHECK) && defined(TACH_1) && (TACH_1 >-1))
  7431. void setup_fan_interrupt() {
  7432. //INT7
  7433. DDRE &= ~(1 << 7); //input pin
  7434. PORTE &= ~(1 << 7); //no internal pull-up
  7435. //start with sensing rising edge
  7436. EICRB &= ~(1 << 6);
  7437. EICRB |= (1 << 7);
  7438. //enable INT7 interrupt
  7439. EIMSK |= (1 << 7);
  7440. }
  7441. // The fan interrupt is triggered at maximum 325Hz (may be a bit more due to component tollerances),
  7442. // and it takes 4.24 us to process (the interrupt invocation overhead not taken into account).
  7443. ISR(INT7_vect) {
  7444. //measuring speed now works for fanSpeed > 18 (approximately), which is sufficient because MIN_PRINT_FAN_SPEED is higher
  7445. if (fanSpeed < MIN_PRINT_FAN_SPEED) return;
  7446. if ((1 << 6) & EICRB) { //interrupt was triggered by rising edge
  7447. t_fan_rising_edge = millis_nc();
  7448. }
  7449. else { //interrupt was triggered by falling edge
  7450. if ((millis_nc() - t_fan_rising_edge) >= FAN_PULSE_WIDTH_LIMIT) {//this pulse was from sensor and not from pwm
  7451. fan_edge_counter[1] += 2; //we are currently counting all edges so lets count two edges for one pulse
  7452. }
  7453. }
  7454. EICRB ^= (1 << 6); //change edge
  7455. }
  7456. #endif
  7457. #ifdef UVLO_SUPPORT
  7458. void setup_uvlo_interrupt() {
  7459. DDRE &= ~(1 << 4); //input pin
  7460. PORTE &= ~(1 << 4); //no internal pull-up
  7461. //sensing falling edge
  7462. EICRB |= (1 << 0);
  7463. EICRB &= ~(1 << 1);
  7464. //enable INT4 interrupt
  7465. EIMSK |= (1 << 4);
  7466. }
  7467. ISR(INT4_vect) {
  7468. EIMSK &= ~(1 << 4); //disable INT4 interrupt to make sure that this code will be executed just once
  7469. SERIAL_ECHOLNPGM("INT4");
  7470. if(IS_SD_PRINTING && (!(eeprom_read_byte((uint8_t*)EEPROM_UVLO))) ) uvlo_();
  7471. if(eeprom_read_byte((uint8_t*)EEPROM_UVLO)) uvlo_tiny();
  7472. }
  7473. void recover_print(uint8_t automatic) {
  7474. char cmd[30];
  7475. lcd_update_enable(true);
  7476. lcd_update(2);
  7477. lcd_setstatuspgm(_i("Recovering print "));////MSG_RECOVERING_PRINT c=20 r=1
  7478. bool bTiny=(eeprom_read_byte((uint8_t*)EEPROM_UVLO)==2);
  7479. recover_machine_state_after_power_panic(bTiny); //recover position, temperatures and extrude_multipliers
  7480. // Lift the print head, so one may remove the excess priming material.
  7481. if(!bTiny&&(current_position[Z_AXIS]<25))
  7482. enquecommand_P(PSTR("G1 Z25 F800"));
  7483. // Home X and Y axes. Homing just X and Y shall not touch the babystep and the world2machine transformation status.
  7484. enquecommand_P(PSTR("G28 X Y"));
  7485. // Set the target bed and nozzle temperatures and wait.
  7486. sprintf_P(cmd, PSTR("M109 S%d"), target_temperature[active_extruder]);
  7487. enquecommand(cmd);
  7488. sprintf_P(cmd, PSTR("M190 S%d"), target_temperature_bed);
  7489. enquecommand(cmd);
  7490. enquecommand_P(PSTR("M83")); //E axis relative mode
  7491. //enquecommand_P(PSTR("G1 E5 F120")); //Extrude some filament to stabilize pessure
  7492. // If not automatically recoreverd (long power loss), extrude extra filament to stabilize
  7493. if(automatic == 0){
  7494. enquecommand_P(PSTR("G1 E5 F120")); //Extrude some filament to stabilize pessure
  7495. }
  7496. enquecommand_P(PSTR("G1 E" STRINGIFY(-default_retraction)" F480"));
  7497. 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]);
  7498. // Restart the print.
  7499. restore_print_from_eeprom();
  7500. printf_P(_N("Current pos Z_AXIS:%.3f\nCurrent pos E_AXIS:%.3f\n"), current_position[Z_AXIS], current_position[E_AXIS]);
  7501. }
  7502. void recover_machine_state_after_power_panic(bool bTiny)
  7503. {
  7504. char cmd[30];
  7505. // 1) Recover the logical cordinates at the time of the power panic.
  7506. // The logical XY coordinates are needed to recover the machine Z coordinate corrected by the mesh bed leveling.
  7507. current_position[X_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0));
  7508. current_position[Y_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 4));
  7509. // Recover the logical coordinate of the Z axis at the time of the power panic.
  7510. // The current position after power panic is moved to the next closest 0th full step.
  7511. if(bTiny)
  7512. current_position[Z_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_TINY_CURRENT_POSITION_Z)) +
  7513. UVLO_Z_AXIS_SHIFT + float((1024 - eeprom_read_word((uint16_t*)(EEPROM_UVLO_TINY_Z_MICROSTEPS)) + 7) >> 4) / cs.axis_steps_per_unit[Z_AXIS];
  7514. else
  7515. current_position[Z_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_Z)) +
  7516. UVLO_Z_AXIS_SHIFT + float((1024 - eeprom_read_word((uint16_t*)(EEPROM_UVLO_Z_MICROSTEPS)) + 7) >> 4) / cs.axis_steps_per_unit[Z_AXIS];
  7517. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO_E_ABS)) {
  7518. current_position[E_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_E));
  7519. sprintf_P(cmd, PSTR("G92 E"));
  7520. dtostrf(current_position[E_AXIS], 6, 3, cmd + strlen(cmd));
  7521. enquecommand(cmd);
  7522. }
  7523. memcpy(destination, current_position, sizeof(destination));
  7524. SERIAL_ECHOPGM("recover_machine_state_after_power_panic, initial ");
  7525. print_world_coordinates();
  7526. // 2) Initialize the logical to physical coordinate system transformation.
  7527. world2machine_initialize();
  7528. // 3) Restore the mesh bed leveling offsets. This is 2*9=18 bytes, which takes 18*3.4us=52us in worst case.
  7529. mbl.active = false;
  7530. for (int8_t mesh_point = 0; mesh_point < 9; ++ mesh_point) {
  7531. uint8_t ix = mesh_point % MESH_MEAS_NUM_X_POINTS; // from 0 to MESH_NUM_X_POINTS - 1
  7532. uint8_t iy = mesh_point / MESH_MEAS_NUM_X_POINTS;
  7533. // Scale the z value to 10u resolution.
  7534. int16_t v;
  7535. eeprom_read_block(&v, (void*)(EEPROM_UVLO_MESH_BED_LEVELING+2*mesh_point), 2);
  7536. if (v != 0)
  7537. mbl.active = true;
  7538. mbl.z_values[iy][ix] = float(v) * 0.001f;
  7539. }
  7540. if (mbl.active)
  7541. mbl.upsample_3x3();
  7542. // SERIAL_ECHOPGM("recover_machine_state_after_power_panic, initial ");
  7543. // print_mesh_bed_leveling_table();
  7544. // 4) Load the baby stepping value, which is expected to be active at the time of power panic.
  7545. // The baby stepping value is used to reset the physical Z axis when rehoming the Z axis.
  7546. babystep_load();
  7547. // 5) Set the physical positions from the logical positions using the world2machine transformation and the active bed leveling.
  7548. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  7549. // 6) Power up the motors, mark their positions as known.
  7550. //FIXME Verfiy, whether the X and Y axes should be powered up here, as they will later be re-homed anyway.
  7551. axis_known_position[X_AXIS] = true; enable_x();
  7552. axis_known_position[Y_AXIS] = true; enable_y();
  7553. axis_known_position[Z_AXIS] = true; enable_z();
  7554. SERIAL_ECHOPGM("recover_machine_state_after_power_panic, initial ");
  7555. print_physical_coordinates();
  7556. // 7) Recover the target temperatures.
  7557. target_temperature[active_extruder] = eeprom_read_byte((uint8_t*)EEPROM_UVLO_TARGET_HOTEND);
  7558. target_temperature_bed = eeprom_read_byte((uint8_t*)EEPROM_UVLO_TARGET_BED);
  7559. // 8) Recover extruder multipilers
  7560. extruder_multiplier[0] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_0));
  7561. #if EXTRUDERS > 1
  7562. extruder_multiplier[1] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_1));
  7563. #if EXTRUDERS > 2
  7564. extruder_multiplier[2] = eeprom_read_float((float*)(EEPROM_EXTRUDER_MULTIPLIER_2));
  7565. #endif
  7566. #endif
  7567. extrudemultiply = (int)eeprom_read_word((uint16_t*)(EEPROM_EXTRUDEMULTIPLY));
  7568. }
  7569. void restore_print_from_eeprom() {
  7570. int feedrate_rec;
  7571. uint8_t fan_speed_rec;
  7572. char cmd[30];
  7573. char filename[13];
  7574. uint8_t depth = 0;
  7575. char dir_name[9];
  7576. fan_speed_rec = eeprom_read_byte((uint8_t*)EEPROM_UVLO_FAN_SPEED);
  7577. EEPROM_read_B(EEPROM_UVLO_FEEDRATE, &feedrate_rec);
  7578. SERIAL_ECHOPGM("Feedrate:");
  7579. MYSERIAL.println(feedrate_rec);
  7580. depth = eeprom_read_byte((uint8_t*)EEPROM_DIR_DEPTH);
  7581. MYSERIAL.println(int(depth));
  7582. for (int i = 0; i < depth; i++) {
  7583. for (int j = 0; j < 8; j++) {
  7584. dir_name[j] = eeprom_read_byte((uint8_t*)EEPROM_DIRS + j + 8 * i);
  7585. }
  7586. dir_name[8] = '\0';
  7587. MYSERIAL.println(dir_name);
  7588. strcpy(dir_names[i], dir_name);
  7589. card.chdir(dir_name);
  7590. }
  7591. for (int i = 0; i < 8; i++) {
  7592. filename[i] = eeprom_read_byte((uint8_t*)EEPROM_FILENAME + i);
  7593. }
  7594. filename[8] = '\0';
  7595. MYSERIAL.print(filename);
  7596. strcat_P(filename, PSTR(".gco"));
  7597. sprintf_P(cmd, PSTR("M23 %s"), filename);
  7598. enquecommand(cmd);
  7599. uint32_t position = eeprom_read_dword((uint32_t*)(EEPROM_FILE_POSITION));
  7600. SERIAL_ECHOPGM("Position read from eeprom:");
  7601. MYSERIAL.println(position);
  7602. // E axis relative mode.
  7603. enquecommand_P(PSTR("M83"));
  7604. // Move to the XY print position in logical coordinates, where the print has been killed.
  7605. strcpy_P(cmd, PSTR("G1 X")); strcat(cmd, ftostr32(eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0))));
  7606. strcat_P(cmd, PSTR(" Y")); strcat(cmd, ftostr32(eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 4))));
  7607. strcat_P(cmd, PSTR(" F2000"));
  7608. enquecommand(cmd);
  7609. // Move the Z axis down to the print, in logical coordinates.
  7610. strcpy_P(cmd, PSTR("G1 Z")); strcat(cmd, ftostr32(eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_Z))));
  7611. enquecommand(cmd);
  7612. // Unretract.
  7613. enquecommand_P(PSTR("G1 E" STRINGIFY(2*default_retraction)" F480"));
  7614. // Set the feedrate saved at the power panic.
  7615. sprintf_P(cmd, PSTR("G1 F%d"), feedrate_rec);
  7616. enquecommand(cmd);
  7617. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO_E_ABS))
  7618. {
  7619. enquecommand_P(PSTR("M82")); //E axis abslute mode
  7620. }
  7621. // Set the fan speed saved at the power panic.
  7622. strcpy_P(cmd, PSTR("M106 S"));
  7623. strcat(cmd, itostr3(int(fan_speed_rec)));
  7624. enquecommand(cmd);
  7625. // Set a position in the file.
  7626. sprintf_P(cmd, PSTR("M26 S%lu"), position);
  7627. enquecommand(cmd);
  7628. enquecommand_P(PSTR("G4 S0"));
  7629. enquecommand_P(PSTR("PRUSA uvlo"));
  7630. }
  7631. #endif //UVLO_SUPPORT
  7632. //! @brief Immediately stop print moves
  7633. //!
  7634. //! Immediately stop print moves, save current extruder temperature and position to RAM.
  7635. //! If printing from sd card, position in file is saved.
  7636. //! If printing from USB, line number is saved.
  7637. //!
  7638. //! @param z_move
  7639. //! @param e_move
  7640. void stop_and_save_print_to_ram(float z_move, float e_move)
  7641. {
  7642. if (saved_printing) return;
  7643. #if 0
  7644. unsigned char nplanner_blocks;
  7645. #endif
  7646. unsigned char nlines;
  7647. uint16_t sdlen_planner;
  7648. uint16_t sdlen_cmdqueue;
  7649. cli();
  7650. if (card.sdprinting) {
  7651. #if 0
  7652. nplanner_blocks = number_of_blocks();
  7653. #endif
  7654. saved_sdpos = sdpos_atomic; //atomic sd position of last command added in queue
  7655. sdlen_planner = planner_calc_sd_length(); //length of sd commands in planner
  7656. saved_sdpos -= sdlen_planner;
  7657. sdlen_cmdqueue = cmdqueue_calc_sd_length(); //length of sd commands in cmdqueue
  7658. saved_sdpos -= sdlen_cmdqueue;
  7659. saved_printing_type = PRINTING_TYPE_SD;
  7660. }
  7661. else if (is_usb_printing) { //reuse saved_sdpos for storing line number
  7662. saved_sdpos = gcode_LastN; //start with line number of command added recently to cmd queue
  7663. //reuse planner_calc_sd_length function for getting number of lines of commands in planner:
  7664. nlines = planner_calc_sd_length(); //number of lines of commands in planner
  7665. saved_sdpos -= nlines;
  7666. saved_sdpos -= buflen; //number of blocks in cmd buffer
  7667. saved_printing_type = PRINTING_TYPE_USB;
  7668. }
  7669. else {
  7670. //not sd printing nor usb printing
  7671. }
  7672. #if 0
  7673. SERIAL_ECHOPGM("SDPOS_ATOMIC="); MYSERIAL.println(sdpos_atomic, DEC);
  7674. SERIAL_ECHOPGM("SDPOS="); MYSERIAL.println(card.get_sdpos(), DEC);
  7675. SERIAL_ECHOPGM("SDLEN_PLAN="); MYSERIAL.println(sdlen_planner, DEC);
  7676. SERIAL_ECHOPGM("SDLEN_CMDQ="); MYSERIAL.println(sdlen_cmdqueue, DEC);
  7677. SERIAL_ECHOPGM("PLANNERBLOCKS="); MYSERIAL.println(int(nplanner_blocks), DEC);
  7678. SERIAL_ECHOPGM("SDSAVED="); MYSERIAL.println(saved_sdpos, DEC);
  7679. //SERIAL_ECHOPGM("SDFILELEN="); MYSERIAL.println(card.fileSize(), DEC);
  7680. {
  7681. card.setIndex(saved_sdpos);
  7682. SERIAL_ECHOLNPGM("Content of planner buffer: ");
  7683. for (unsigned int idx = 0; idx < sdlen_planner; ++ idx)
  7684. MYSERIAL.print(char(card.get()));
  7685. SERIAL_ECHOLNPGM("Content of command buffer: ");
  7686. for (unsigned int idx = 0; idx < sdlen_cmdqueue; ++ idx)
  7687. MYSERIAL.print(char(card.get()));
  7688. SERIAL_ECHOLNPGM("End of command buffer");
  7689. }
  7690. {
  7691. // Print the content of the planner buffer, line by line:
  7692. card.setIndex(saved_sdpos);
  7693. int8_t iline = 0;
  7694. for (unsigned char idx = block_buffer_tail; idx != block_buffer_head; idx = (idx + 1) & (BLOCK_BUFFER_SIZE - 1), ++ iline) {
  7695. SERIAL_ECHOPGM("Planner line (from file): ");
  7696. MYSERIAL.print(int(iline), DEC);
  7697. SERIAL_ECHOPGM(", length: ");
  7698. MYSERIAL.print(block_buffer[idx].sdlen, DEC);
  7699. SERIAL_ECHOPGM(", steps: (");
  7700. MYSERIAL.print(block_buffer[idx].steps_x, DEC);
  7701. SERIAL_ECHOPGM(",");
  7702. MYSERIAL.print(block_buffer[idx].steps_y, DEC);
  7703. SERIAL_ECHOPGM(",");
  7704. MYSERIAL.print(block_buffer[idx].steps_z, DEC);
  7705. SERIAL_ECHOPGM(",");
  7706. MYSERIAL.print(block_buffer[idx].steps_e, DEC);
  7707. SERIAL_ECHOPGM("), events: ");
  7708. MYSERIAL.println(block_buffer[idx].step_event_count, DEC);
  7709. for (int len = block_buffer[idx].sdlen; len > 0; -- len)
  7710. MYSERIAL.print(char(card.get()));
  7711. }
  7712. }
  7713. {
  7714. // Print the content of the command buffer, line by line:
  7715. int8_t iline = 0;
  7716. union {
  7717. struct {
  7718. char lo;
  7719. char hi;
  7720. } lohi;
  7721. uint16_t value;
  7722. } sdlen_single;
  7723. int _bufindr = bufindr;
  7724. for (int _buflen = buflen; _buflen > 0; ++ iline) {
  7725. if (cmdbuffer[_bufindr] == CMDBUFFER_CURRENT_TYPE_SDCARD) {
  7726. sdlen_single.lohi.lo = cmdbuffer[_bufindr + 1];
  7727. sdlen_single.lohi.hi = cmdbuffer[_bufindr + 2];
  7728. }
  7729. SERIAL_ECHOPGM("Buffer line (from buffer): ");
  7730. MYSERIAL.print(int(iline), DEC);
  7731. SERIAL_ECHOPGM(", type: ");
  7732. MYSERIAL.print(int(cmdbuffer[_bufindr]), DEC);
  7733. SERIAL_ECHOPGM(", len: ");
  7734. MYSERIAL.println(sdlen_single.value, DEC);
  7735. // Print the content of the buffer line.
  7736. MYSERIAL.println(cmdbuffer + _bufindr + CMDHDRSIZE);
  7737. SERIAL_ECHOPGM("Buffer line (from file): ");
  7738. MYSERIAL.println(int(iline), DEC);
  7739. for (; sdlen_single.value > 0; -- sdlen_single.value)
  7740. MYSERIAL.print(char(card.get()));
  7741. if (-- _buflen == 0)
  7742. break;
  7743. // First skip the current command ID and iterate up to the end of the string.
  7744. for (_bufindr += CMDHDRSIZE; cmdbuffer[_bufindr] != 0; ++ _bufindr) ;
  7745. // Second, skip the end of string null character and iterate until a nonzero command ID is found.
  7746. for (++ _bufindr; _bufindr < sizeof(cmdbuffer) && cmdbuffer[_bufindr] == 0; ++ _bufindr) ;
  7747. // If the end of the buffer was empty,
  7748. if (_bufindr == sizeof(cmdbuffer)) {
  7749. // skip to the start and find the nonzero command.
  7750. for (_bufindr = 0; cmdbuffer[_bufindr] == 0; ++ _bufindr) ;
  7751. }
  7752. }
  7753. }
  7754. #endif
  7755. #if 0
  7756. saved_feedrate2 = feedrate; //save feedrate
  7757. #else
  7758. // Try to deduce the feedrate from the first block of the planner.
  7759. // Speed is in mm/min.
  7760. saved_feedrate2 = blocks_queued() ? (block_buffer[block_buffer_tail].nominal_speed * 60.f) : feedrate;
  7761. #endif
  7762. planner_abort_hard(); //abort printing
  7763. memcpy(saved_pos, current_position, sizeof(saved_pos));
  7764. saved_active_extruder = active_extruder; //save active_extruder
  7765. saved_extruder_temperature = degTargetHotend(active_extruder);
  7766. saved_extruder_under_pressure = extruder_under_pressure; //extruder under pressure flag - currently unused
  7767. saved_extruder_relative_mode = axis_relative_modes[E_AXIS];
  7768. saved_fanSpeed = fanSpeed;
  7769. cmdqueue_reset(); //empty cmdqueue
  7770. card.sdprinting = false;
  7771. // card.closefile();
  7772. saved_printing = true;
  7773. // We may have missed a stepper timer interrupt. Be safe than sorry, reset the stepper timer before re-enabling interrupts.
  7774. st_reset_timer();
  7775. sei();
  7776. if ((z_move != 0) || (e_move != 0)) { // extruder or z move
  7777. #if 1
  7778. // Rather than calling plan_buffer_line directly, push the move into the command queue,
  7779. char buf[48];
  7780. // First unretract (relative extrusion)
  7781. if(!saved_extruder_relative_mode){
  7782. strcpy_P(buf, PSTR("M83"));
  7783. enquecommand(buf, false);
  7784. }
  7785. //retract 45mm/s
  7786. strcpy_P(buf, PSTR("G1 E"));
  7787. dtostrf(e_move, 6, 3, buf + strlen(buf));
  7788. strcat_P(buf, PSTR(" F"));
  7789. dtostrf(2700, 8, 3, buf + strlen(buf));
  7790. enquecommand(buf, false);
  7791. // Then lift Z axis
  7792. strcpy_P(buf, PSTR("G1 Z"));
  7793. dtostrf(saved_pos[Z_AXIS] + z_move, 8, 3, buf + strlen(buf));
  7794. strcat_P(buf, PSTR(" F"));
  7795. dtostrf(homing_feedrate[Z_AXIS], 8, 3, buf + strlen(buf));
  7796. // At this point the command queue is empty.
  7797. enquecommand(buf, false);
  7798. // If this call is invoked from the main Arduino loop() function, let the caller know that the command
  7799. // in the command queue is not the original command, but a new one, so it should not be removed from the queue.
  7800. repeatcommand_front();
  7801. #else
  7802. plan_buffer_line(saved_pos[X_AXIS], saved_pos[Y_AXIS], saved_pos[Z_AXIS] + z_move, saved_pos[E_AXIS] + e_move, homing_feedrate[Z_AXIS], active_extruder);
  7803. st_synchronize(); //wait moving
  7804. memcpy(current_position, saved_pos, sizeof(saved_pos));
  7805. memcpy(destination, current_position, sizeof(destination));
  7806. #endif
  7807. }
  7808. }
  7809. //! @brief Restore print from ram
  7810. //!
  7811. //! Restore print saved by stop_and_save_print_to_ram(). Is blocking,
  7812. //! waits for extruder temperature restore, then restores position and continues
  7813. //! print moves.
  7814. //! Internaly lcd_update() is called by wait_for_heater().
  7815. //!
  7816. //! @param e_move
  7817. void restore_print_from_ram_and_continue(float e_move)
  7818. {
  7819. if (!saved_printing) return;
  7820. // for (int axis = X_AXIS; axis <= E_AXIS; axis++)
  7821. // current_position[axis] = st_get_position_mm(axis);
  7822. active_extruder = saved_active_extruder; //restore active_extruder
  7823. setTargetHotendSafe(saved_extruder_temperature,saved_active_extruder);
  7824. heating_status = 1;
  7825. wait_for_heater(millis(),saved_active_extruder);
  7826. heating_status = 2;
  7827. feedrate = saved_feedrate2; //restore feedrate
  7828. axis_relative_modes[E_AXIS] = saved_extruder_relative_mode;
  7829. fanSpeed = saved_fanSpeed;
  7830. float e = saved_pos[E_AXIS] - e_move;
  7831. plan_set_e_position(e);
  7832. //first move print head in XY to the saved position:
  7833. 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);
  7834. st_synchronize();
  7835. //then move Z
  7836. 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);
  7837. st_synchronize();
  7838. //and finaly unretract (35mm/s)
  7839. plan_buffer_line(saved_pos[X_AXIS], saved_pos[Y_AXIS], saved_pos[Z_AXIS], saved_pos[E_AXIS], 35, active_extruder);
  7840. st_synchronize();
  7841. memcpy(current_position, saved_pos, sizeof(saved_pos));
  7842. memcpy(destination, current_position, sizeof(destination));
  7843. if (saved_printing_type == PRINTING_TYPE_SD) { //was sd printing
  7844. card.setIndex(saved_sdpos);
  7845. sdpos_atomic = saved_sdpos;
  7846. card.sdprinting = true;
  7847. printf_P(PSTR("ok\n")); //dummy response because of octoprint is waiting for this
  7848. }
  7849. else if (saved_printing_type == PRINTING_TYPE_USB) { //was usb printing
  7850. gcode_LastN = saved_sdpos; //saved_sdpos was reused for storing line number when usb printing
  7851. serial_count = 0;
  7852. FlushSerialRequestResend();
  7853. }
  7854. else {
  7855. //not sd printing nor usb printing
  7856. }
  7857. lcd_setstatuspgm(_T(WELCOME_MSG));
  7858. saved_printing = false;
  7859. }
  7860. void print_world_coordinates()
  7861. {
  7862. printf_P(_N("world coordinates: (%.3f, %.3f, %.3f)\n"), current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS]);
  7863. }
  7864. void print_physical_coordinates()
  7865. {
  7866. 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));
  7867. }
  7868. void print_mesh_bed_leveling_table()
  7869. {
  7870. SERIAL_ECHOPGM("mesh bed leveling: ");
  7871. for (int8_t y = 0; y < MESH_NUM_Y_POINTS; ++ y)
  7872. for (int8_t x = 0; x < MESH_NUM_Y_POINTS; ++ x) {
  7873. MYSERIAL.print(mbl.z_values[y][x], 3);
  7874. SERIAL_ECHOPGM(" ");
  7875. }
  7876. SERIAL_ECHOLNPGM("");
  7877. }
  7878. uint16_t print_time_remaining() {
  7879. uint16_t print_t = PRINT_TIME_REMAINING_INIT;
  7880. #ifdef TMC2130
  7881. if (SilentModeMenu == SILENT_MODE_OFF) print_t = print_time_remaining_normal;
  7882. else print_t = print_time_remaining_silent;
  7883. #else
  7884. print_t = print_time_remaining_normal;
  7885. #endif //TMC2130
  7886. if ((print_t != PRINT_TIME_REMAINING_INIT) && (feedmultiply != 0)) print_t = 100ul * print_t / feedmultiply;
  7887. return print_t;
  7888. }
  7889. uint8_t calc_percent_done()
  7890. {
  7891. //in case that we have information from M73 gcode return percentage counted by slicer, else return percentage counted as byte_printed/filesize
  7892. uint8_t percent_done = 0;
  7893. #ifdef TMC2130
  7894. if (SilentModeMenu == SILENT_MODE_OFF && print_percent_done_normal <= 100) {
  7895. percent_done = print_percent_done_normal;
  7896. }
  7897. else if (print_percent_done_silent <= 100) {
  7898. percent_done = print_percent_done_silent;
  7899. }
  7900. #else
  7901. if (print_percent_done_normal <= 100) {
  7902. percent_done = print_percent_done_normal;
  7903. }
  7904. #endif //TMC2130
  7905. else {
  7906. percent_done = card.percentDone();
  7907. }
  7908. return percent_done;
  7909. }
  7910. static void print_time_remaining_init()
  7911. {
  7912. print_time_remaining_normal = PRINT_TIME_REMAINING_INIT;
  7913. print_time_remaining_silent = PRINT_TIME_REMAINING_INIT;
  7914. print_percent_done_normal = PRINT_PERCENT_DONE_INIT;
  7915. print_percent_done_silent = PRINT_PERCENT_DONE_INIT;
  7916. }
  7917. void load_filament_final_feed()
  7918. {
  7919. current_position[E_AXIS]+= FILAMENTCHANGE_FINALFEED;
  7920. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], FILAMENTCHANGE_EFEED_FINAL, active_extruder);
  7921. }
  7922. void M600_check_state()
  7923. {
  7924. //Wait for user to check the state
  7925. lcd_change_fil_state = 0;
  7926. while (lcd_change_fil_state != 1){
  7927. lcd_change_fil_state = 0;
  7928. KEEPALIVE_STATE(PAUSED_FOR_USER);
  7929. lcd_alright();
  7930. KEEPALIVE_STATE(IN_HANDLER);
  7931. switch(lcd_change_fil_state){
  7932. // Filament failed to load so load it again
  7933. case 2:
  7934. if (mmu_enabled)
  7935. mmu_M600_load_filament(false); //nonautomatic load; change to "wrong filament loaded" option?
  7936. else
  7937. M600_load_filament_movements();
  7938. break;
  7939. // Filament loaded properly but color is not clear
  7940. case 3:
  7941. st_synchronize();
  7942. load_filament_final_feed();
  7943. lcd_loading_color();
  7944. st_synchronize();
  7945. break;
  7946. // Everything good
  7947. default:
  7948. lcd_change_success();
  7949. break;
  7950. }
  7951. }
  7952. }
  7953. //! @brief Wait for user action
  7954. //!
  7955. //! Beep, manage nozzle heater and wait for user to start unload filament
  7956. //! If times out, active extruder temperature is set to 0.
  7957. //!
  7958. //! @param HotendTempBckp Temperature to be restored for active extruder, after user resolves MMU problem.
  7959. void M600_wait_for_user(float HotendTempBckp) {
  7960. KEEPALIVE_STATE(PAUSED_FOR_USER);
  7961. int counterBeep = 0;
  7962. unsigned long waiting_start_time = millis();
  7963. uint8_t wait_for_user_state = 0;
  7964. lcd_display_message_fullscreen_P(_T(MSG_PRESS_TO_UNLOAD));
  7965. bool bFirst=true;
  7966. while (!(wait_for_user_state == 0 && lcd_clicked())){
  7967. manage_heater();
  7968. manage_inactivity(true);
  7969. #if BEEPER > 0
  7970. if (counterBeep == 500) {
  7971. counterBeep = 0;
  7972. }
  7973. SET_OUTPUT(BEEPER);
  7974. if (counterBeep == 0) {
  7975. if((eSoundMode==e_SOUND_MODE_LOUD)||((eSoundMode==e_SOUND_MODE_ONCE)&&bFirst))
  7976. {
  7977. bFirst=false;
  7978. WRITE(BEEPER, HIGH);
  7979. }
  7980. }
  7981. if (counterBeep == 20) {
  7982. WRITE(BEEPER, LOW);
  7983. }
  7984. counterBeep++;
  7985. #endif //BEEPER > 0
  7986. switch (wait_for_user_state) {
  7987. case 0: //nozzle is hot, waiting for user to press the knob to unload filament
  7988. delay_keep_alive(4);
  7989. if (millis() > waiting_start_time + (unsigned long)M600_TIMEOUT * 1000) {
  7990. lcd_display_message_fullscreen_P(_i("Press knob to preheat nozzle and continue."));////MSG_PRESS_TO_PREHEAT c=20 r=4
  7991. wait_for_user_state = 1;
  7992. setAllTargetHotends(0);
  7993. st_synchronize();
  7994. disable_e0();
  7995. disable_e1();
  7996. disable_e2();
  7997. }
  7998. break;
  7999. case 1: //nozzle target temperature is set to zero, waiting for user to start nozzle preheat
  8000. delay_keep_alive(4);
  8001. if (lcd_clicked()) {
  8002. setTargetHotend(HotendTempBckp, active_extruder);
  8003. lcd_wait_for_heater();
  8004. wait_for_user_state = 2;
  8005. }
  8006. break;
  8007. case 2: //waiting for nozzle to reach target temperature
  8008. if (abs(degTargetHotend(active_extruder) - degHotend(active_extruder)) < 1) {
  8009. lcd_display_message_fullscreen_P(_T(MSG_PRESS_TO_UNLOAD));
  8010. waiting_start_time = millis();
  8011. wait_for_user_state = 0;
  8012. }
  8013. else {
  8014. counterBeep = 20; //beeper will be inactive during waiting for nozzle preheat
  8015. lcd_set_cursor(1, 4);
  8016. lcd_print(ftostr3(degHotend(active_extruder)));
  8017. }
  8018. break;
  8019. }
  8020. }
  8021. WRITE(BEEPER, LOW);
  8022. }
  8023. void M600_load_filament_movements()
  8024. {
  8025. #ifdef SNMM
  8026. display_loading();
  8027. do
  8028. {
  8029. current_position[E_AXIS] += 0.002;
  8030. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 500, active_extruder);
  8031. delay_keep_alive(2);
  8032. }
  8033. while (!lcd_clicked());
  8034. st_synchronize();
  8035. current_position[E_AXIS] += bowden_length[mmu_extruder];
  8036. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000, active_extruder);
  8037. current_position[E_AXIS] += FIL_LOAD_LENGTH - 60;
  8038. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 1400, active_extruder);
  8039. current_position[E_AXIS] += 40;
  8040. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 400, active_extruder);
  8041. current_position[E_AXIS] += 10;
  8042. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 50, active_extruder);
  8043. #else
  8044. current_position[E_AXIS]+= FILAMENTCHANGE_FIRSTFEED ;
  8045. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], FILAMENTCHANGE_EFEED_FIRST, active_extruder);
  8046. #endif
  8047. load_filament_final_feed();
  8048. lcd_loading_filament();
  8049. st_synchronize();
  8050. }
  8051. void M600_load_filament() {
  8052. //load filament for single material and SNMM
  8053. lcd_wait_interact();
  8054. //load_filament_time = millis();
  8055. KEEPALIVE_STATE(PAUSED_FOR_USER);
  8056. #ifdef FILAMENT_SENSOR
  8057. fsensor_autoload_check_start();
  8058. #endif //FILAMENT_SENSOR
  8059. while(!lcd_clicked())
  8060. {
  8061. manage_heater();
  8062. manage_inactivity(true);
  8063. #ifdef FILAMENT_SENSOR
  8064. if (fsensor_check_autoload())
  8065. {
  8066. if((eSoundMode==e_SOUND_MODE_LOUD)||(eSoundMode==e_SOUND_MODE_ONCE))
  8067. tone(BEEPER, 1000);
  8068. delay_keep_alive(50);
  8069. noTone(BEEPER);
  8070. break;
  8071. }
  8072. #endif //FILAMENT_SENSOR
  8073. }
  8074. #ifdef FILAMENT_SENSOR
  8075. fsensor_autoload_check_stop();
  8076. #endif //FILAMENT_SENSOR
  8077. KEEPALIVE_STATE(IN_HANDLER);
  8078. #ifdef FSENSOR_QUALITY
  8079. fsensor_oq_meassure_start(70);
  8080. #endif //FSENSOR_QUALITY
  8081. M600_load_filament_movements();
  8082. if((eSoundMode==e_SOUND_MODE_LOUD)||(eSoundMode==e_SOUND_MODE_ONCE))
  8083. tone(BEEPER, 500);
  8084. delay_keep_alive(50);
  8085. noTone(BEEPER);
  8086. #ifdef FSENSOR_QUALITY
  8087. fsensor_oq_meassure_stop();
  8088. if (!fsensor_oq_result())
  8089. {
  8090. bool disable = lcd_show_fullscreen_message_yes_no_and_wait_P(_i("Fil. sensor response is poor, disable it?"), false, true);
  8091. lcd_update_enable(true);
  8092. lcd_update(2);
  8093. if (disable)
  8094. fsensor_disable();
  8095. }
  8096. #endif //FSENSOR_QUALITY
  8097. lcd_update_enable(false);
  8098. }
  8099. #define FIL_LOAD_LENGTH 60