Marlin_main.cpp 351 KB

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