Marlin_main.cpp 347 KB

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