Marlin_main.cpp 245 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359
  1. /* -*- c++ -*- */
  2. /*
  3. Reprap firmware based on Sprinter and grbl.
  4. Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
  5. This program is free software: you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation, either version 3 of the License, or
  8. (at your option) any later version.
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with this program. If not, see <http://www.gnu.org/licenses/>.
  15. */
  16. /*
  17. This firmware is a mashup between Sprinter and grbl.
  18. (https://github.com/kliment/Sprinter)
  19. (https://github.com/simen/grbl/tree)
  20. It has preliminary support for Matthew Roberts advance algorithm
  21. http://reprap.org/pipermail/reprap-dev/2011-May/003323.html
  22. */
  23. #include "Marlin.h"
  24. #ifdef ENABLE_AUTO_BED_LEVELING
  25. #include "vector_3.h"
  26. #ifdef AUTO_BED_LEVELING_GRID
  27. #include "qr_solve.h"
  28. #endif
  29. #endif // ENABLE_AUTO_BED_LEVELING
  30. #ifdef MESH_BED_LEVELING
  31. #include "mesh_bed_leveling.h"
  32. #include "mesh_bed_calibration.h"
  33. #endif
  34. #include "ultralcd.h"
  35. #include "Configuration_prusa.h"
  36. #include "planner.h"
  37. #include "stepper.h"
  38. #include "temperature.h"
  39. #include "motion_control.h"
  40. #include "cardreader.h"
  41. #include "watchdog.h"
  42. #include "ConfigurationStore.h"
  43. #include "language.h"
  44. #include "pins_arduino.h"
  45. #include "math.h"
  46. #include "util.h"
  47. #include <avr/wdt.h>
  48. #include "Dcodes.h"
  49. #ifdef SWSPI
  50. #include "swspi.h"
  51. #endif //SWSPI
  52. #ifdef SWI2C
  53. #include "swi2c.h"
  54. #endif //SWI2C
  55. #ifdef PAT9125
  56. #include "pat9125.h"
  57. #endif //PAT9125
  58. #ifdef TMC2130
  59. #include "tmc2130.h"
  60. #endif //TMC2130
  61. #ifdef BLINKM
  62. #include "BlinkM.h"
  63. #include "Wire.h"
  64. #endif
  65. #ifdef ULTRALCD
  66. #include "ultralcd.h"
  67. #endif
  68. #if NUM_SERVOS > 0
  69. #include "Servo.h"
  70. #endif
  71. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  72. #include <SPI.h>
  73. #endif
  74. #define VERSION_STRING "1.0.2"
  75. #include "ultralcd.h"
  76. #include "cmdqueue.h"
  77. // Macros for bit masks
  78. #define BIT(b) (1<<(b))
  79. #define TEST(n,b) (((n)&BIT(b))!=0)
  80. #define SET_BIT(n,b,value) (n) ^= ((-value)^(n)) & (BIT(b))
  81. // look here for descriptions of G-codes: http://linuxcnc.org/handbook/gcode/g-code.html
  82. // http://objects.reprap.org/wiki/Mendel_User_Manual:_RepRapGCodes
  83. //Implemented Codes
  84. //-------------------
  85. // PRUSA CODES
  86. // P F - Returns FW versions
  87. // P R - Returns revision of printer
  88. // G0 -> G1
  89. // G1 - Coordinated Movement X Y Z E
  90. // G2 - CW ARC
  91. // G3 - CCW ARC
  92. // G4 - Dwell S<seconds> or P<milliseconds>
  93. // G10 - retract filament according to settings of M207
  94. // G11 - retract recover filament according to settings of M208
  95. // G28 - Home all Axis
  96. // G29 - Detailed Z-Probe, probes the bed at 3 or more points. Will fail if you haven't homed yet.
  97. // G30 - Single Z Probe, probes bed at current XY location.
  98. // G31 - Dock sled (Z_PROBE_SLED only)
  99. // G32 - Undock sled (Z_PROBE_SLED only)
  100. // G80 - Automatic mesh bed leveling
  101. // G81 - Print bed profile
  102. // G90 - Use Absolute Coordinates
  103. // G91 - Use Relative Coordinates
  104. // G92 - Set current position to coordinates given
  105. // M Codes
  106. // M0 - Unconditional stop - Wait for user to press a button on the LCD (Only if ULTRA_LCD is enabled)
  107. // M1 - Same as M0
  108. // M17 - Enable/Power all stepper motors
  109. // M18 - Disable all stepper motors; same as M84
  110. // M20 - List SD card
  111. // M21 - Init SD card
  112. // M22 - Release SD card
  113. // M23 - Select SD file (M23 filename.g)
  114. // M24 - Start/resume SD print
  115. // M25 - Pause SD print
  116. // M26 - Set SD position in bytes (M26 S12345)
  117. // M27 - Report SD print status
  118. // M28 - Start SD write (M28 filename.g)
  119. // M29 - Stop SD write
  120. // M30 - Delete file from SD (M30 filename.g)
  121. // M31 - Output time since last M109 or SD card start to serial
  122. // M32 - Select file and start SD print (Can be used _while_ printing from SD card files):
  123. // syntax "M32 /path/filename#", or "M32 S<startpos bytes> !filename#"
  124. // Call gcode file : "M32 P !filename#" and return to caller file after finishing (similar to #include).
  125. // The '#' is necessary when calling from within sd files, as it stops buffer prereading
  126. // 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.
  127. // M80 - Turn on Power Supply
  128. // M81 - Turn off Power Supply
  129. // M82 - Set E codes absolute (default)
  130. // M83 - Set E codes relative while in Absolute Coordinates (G90) mode
  131. // M84 - Disable steppers until next move,
  132. // or use S<seconds> to specify an inactivity timeout, after which the steppers will be disabled. S0 to disable the timeout.
  133. // M85 - Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
  134. // M92 - Set axis_steps_per_unit - same syntax as G92
  135. // M104 - Set extruder target temp
  136. // M105 - Read current temp
  137. // M106 - Fan on
  138. // M107 - Fan off
  139. // M109 - Sxxx Wait for extruder current temp to reach target temp. Waits only when heating
  140. // Rxxx Wait for extruder current temp to reach target temp. Waits when heating and cooling
  141. // IF AUTOTEMP is enabled, S<mintemp> B<maxtemp> F<factor>. Exit autotemp by any M109 without F
  142. // M112 - Emergency stop
  143. // M114 - Output current position to serial port
  144. // M115 - Capabilities string
  145. // M117 - display message
  146. // M119 - Output Endstop status to serial port
  147. // M126 - Solenoid Air Valve Open (BariCUDA support by jmil)
  148. // M127 - Solenoid Air Valve Closed (BariCUDA vent to atmospheric pressure by jmil)
  149. // M128 - EtoP Open (BariCUDA EtoP = electricity to air pressure transducer by jmil)
  150. // M129 - EtoP Closed (BariCUDA EtoP = electricity to air pressure transducer by jmil)
  151. // M140 - Set bed target temp
  152. // 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.
  153. // M190 - Sxxx Wait for bed current temp to reach target temp. Waits only when heating
  154. // Rxxx Wait for bed current temp to reach target temp. Waits when heating and cooling
  155. // M200 D<millimeters>- set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).
  156. // M201 - Set max acceleration in units/s^2 for print moves (M201 X1000 Y1000)
  157. // M202 - Set max acceleration in units/s^2 for travel moves (M202 X1000 Y1000) Unused in Marlin!!
  158. // M203 - Set maximum feedrate that your machine can sustain (M203 X200 Y200 Z300 E10000) in mm/sec
  159. // 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
  160. // 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
  161. // M206 - set additional homing offset
  162. // M207 - set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop], stays in mm regardless of M200 setting
  163. // M208 - set recover=unretract length S[positive mm surplus to the M207 S*] F[feedrate mm/sec]
  164. // 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.
  165. // M218 - set hotend offset (in mm): T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  166. // M220 S<factor in percent>- set speed factor override percentage
  167. // M221 S<factor in percent>- set extrude factor override percentage
  168. // M226 P<pin number> S<pin state>- Wait until the specified pin reaches the state required
  169. // M240 - Trigger a camera to take a photograph
  170. // M250 - Set LCD contrast C<contrast value> (value 0..63)
  171. // M280 - set servo position absolute. P: servo index, S: angle or microseconds
  172. // M300 - Play beep sound S<frequency Hz> P<duration ms>
  173. // M301 - Set PID parameters P I and D
  174. // M302 - Allow cold extrudes, or set the minimum extrude S<temperature>.
  175. // M303 - PID relay autotune S<temperature> sets the target temperature. (default target temperature = 150C)
  176. // M304 - Set bed PID parameters P I and D
  177. // M400 - Finish all moves
  178. // M401 - Lower z-probe if present
  179. // M402 - Raise z-probe if present
  180. // M404 - N<dia in mm> Enter the nominal filament width (3mm, 1.75mm ) or will display nominal filament width without parameters
  181. // M405 - Turn on Filament Sensor extrusion control. Optional D<delay in cm> to set delay in centimeters between sensor and extruder
  182. // M406 - Turn off Filament Sensor extrusion control
  183. // M407 - Displays measured filament diameter
  184. // M500 - stores parameters in EEPROM
  185. // M501 - reads parameters from EEPROM (if you need reset them after you changed them temporarily).
  186. // M502 - reverts to the default "factory settings". You still need to store them in EEPROM afterwards if you want to.
  187. // M503 - print the current settings (from memory not from EEPROM)
  188. // M509 - force language selection on next restart
  189. // M540 - Use S[0|1] to enable or disable the stop SD card print on endstop hit (requires ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  190. // M600 - Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  191. // M605 - Set dual x-carriage movement mode: S<mode> [ X<duplication x-offset> R<duplication temp offset> ]
  192. // M900 - Set LIN_ADVANCE options, if enabled. See Configuration_adv.h for details.
  193. // M907 - Set digital trimpot motor current using axis codes.
  194. // M908 - Control digital trimpot directly.
  195. // M350 - Set microstepping mode.
  196. // M351 - Toggle MS1 MS2 pins directly.
  197. // M928 - Start SD logging (M928 filename.g) - ended by M29
  198. // M999 - Restart after being stopped by error
  199. //Stepper Movement Variables
  200. //===========================================================================
  201. //=============================imported variables============================
  202. //===========================================================================
  203. //===========================================================================
  204. //=============================public variables=============================
  205. //===========================================================================
  206. #ifdef SDSUPPORT
  207. CardReader card;
  208. #endif
  209. unsigned long PingTime = millis();
  210. union Data
  211. {
  212. byte b[2];
  213. int value;
  214. };
  215. float homing_feedrate[] = HOMING_FEEDRATE;
  216. // Currently only the extruder axis may be switched to a relative mode.
  217. // Other axes are always absolute or relative based on the common relative_mode flag.
  218. bool axis_relative_modes[] = AXIS_RELATIVE_MODES;
  219. int feedmultiply=100; //100->1 200->2
  220. int saved_feedmultiply;
  221. int extrudemultiply=100; //100->1 200->2
  222. int extruder_multiply[EXTRUDERS] = {100
  223. #if EXTRUDERS > 1
  224. , 100
  225. #if EXTRUDERS > 2
  226. , 100
  227. #endif
  228. #endif
  229. };
  230. int bowden_length[4];
  231. bool is_usb_printing = false;
  232. bool homing_flag = false;
  233. bool temp_cal_active = false;
  234. unsigned long kicktime = millis()+100000;
  235. unsigned int usb_printing_counter;
  236. int lcd_change_fil_state = 0;
  237. int feedmultiplyBckp = 100;
  238. float HotendTempBckp = 0;
  239. int fanSpeedBckp = 0;
  240. float pause_lastpos[4];
  241. unsigned long pause_time = 0;
  242. unsigned long start_pause_print = millis();
  243. unsigned long load_filament_time;
  244. bool mesh_bed_leveling_flag = false;
  245. bool mesh_bed_run_from_menu = false;
  246. unsigned char lang_selected = 0;
  247. int8_t FarmMode = 0;
  248. bool prusa_sd_card_upload = false;
  249. unsigned int status_number = 0;
  250. unsigned long total_filament_used;
  251. unsigned int heating_status;
  252. unsigned int heating_status_counter;
  253. bool custom_message;
  254. bool loading_flag = false;
  255. unsigned int custom_message_type;
  256. unsigned int custom_message_state;
  257. char snmm_filaments_used = 0;
  258. float distance_from_min[3];
  259. float angleDiff;
  260. bool fan_state[2];
  261. int fan_edge_counter[2];
  262. int fan_speed[2];
  263. bool volumetric_enabled = false;
  264. float filament_size[EXTRUDERS] = { DEFAULT_NOMINAL_FILAMENT_DIA
  265. #if EXTRUDERS > 1
  266. , DEFAULT_NOMINAL_FILAMENT_DIA
  267. #if EXTRUDERS > 2
  268. , DEFAULT_NOMINAL_FILAMENT_DIA
  269. #endif
  270. #endif
  271. };
  272. float volumetric_multiplier[EXTRUDERS] = {1.0
  273. #if EXTRUDERS > 1
  274. , 1.0
  275. #if EXTRUDERS > 2
  276. , 1.0
  277. #endif
  278. #endif
  279. };
  280. float current_position[NUM_AXIS] = { 0.0, 0.0, 0.0, 0.0 };
  281. float add_homing[3]={0,0,0};
  282. float min_pos[3] = { X_MIN_POS, Y_MIN_POS, Z_MIN_POS };
  283. float max_pos[3] = { X_MAX_POS, Y_MAX_POS, Z_MAX_POS };
  284. bool axis_known_position[3] = {false, false, false};
  285. float zprobe_zoffset;
  286. // Extruder offset
  287. #if EXTRUDERS > 1
  288. #define NUM_EXTRUDER_OFFSETS 2 // only in XY plane
  289. float extruder_offset[NUM_EXTRUDER_OFFSETS][EXTRUDERS] = {
  290. #if defined(EXTRUDER_OFFSET_X) && defined(EXTRUDER_OFFSET_Y)
  291. EXTRUDER_OFFSET_X, EXTRUDER_OFFSET_Y
  292. #endif
  293. };
  294. #endif
  295. uint8_t active_extruder = 0;
  296. int fanSpeed=0;
  297. #ifdef FWRETRACT
  298. bool autoretract_enabled=false;
  299. bool retracted[EXTRUDERS]={false
  300. #if EXTRUDERS > 1
  301. , false
  302. #if EXTRUDERS > 2
  303. , false
  304. #endif
  305. #endif
  306. };
  307. bool retracted_swap[EXTRUDERS]={false
  308. #if EXTRUDERS > 1
  309. , false
  310. #if EXTRUDERS > 2
  311. , false
  312. #endif
  313. #endif
  314. };
  315. float retract_length = RETRACT_LENGTH;
  316. float retract_length_swap = RETRACT_LENGTH_SWAP;
  317. float retract_feedrate = RETRACT_FEEDRATE;
  318. float retract_zlift = RETRACT_ZLIFT;
  319. float retract_recover_length = RETRACT_RECOVER_LENGTH;
  320. float retract_recover_length_swap = RETRACT_RECOVER_LENGTH_SWAP;
  321. float retract_recover_feedrate = RETRACT_RECOVER_FEEDRATE;
  322. #endif
  323. #ifdef ULTIPANEL
  324. #ifdef PS_DEFAULT_OFF
  325. bool powersupply = false;
  326. #else
  327. bool powersupply = true;
  328. #endif
  329. #endif
  330. bool cancel_heatup = false ;
  331. #ifdef FILAMENT_SENSOR
  332. //Variables for Filament Sensor input
  333. float filament_width_nominal=DEFAULT_NOMINAL_FILAMENT_DIA; //Set nominal filament width, can be changed with M404
  334. bool filament_sensor=false; //M405 turns on filament_sensor control, M406 turns it off
  335. float filament_width_meas=DEFAULT_MEASURED_FILAMENT_DIA; //Stores the measured filament diameter
  336. signed char measurement_delay[MAX_MEASUREMENT_DELAY+1]; //ring buffer to delay measurement store extruder factor after subtracting 100
  337. int delay_index1=0; //index into ring buffer
  338. int delay_index2=-1; //index into ring buffer - set to -1 on startup to indicate ring buffer needs to be initialized
  339. float delay_dist=0; //delay distance counter
  340. int meas_delay_cm = MEASUREMENT_DELAY_CM; //distance delay setting
  341. #endif
  342. const char errormagic[] PROGMEM = "Error:";
  343. const char echomagic[] PROGMEM = "echo:";
  344. //===========================================================================
  345. //=============================Private Variables=============================
  346. //===========================================================================
  347. const char axis_codes[NUM_AXIS] = {'X', 'Y', 'Z', 'E'};
  348. float destination[NUM_AXIS] = { 0.0, 0.0, 0.0, 0.0};
  349. static float delta[3] = {0.0, 0.0, 0.0};
  350. // For tracing an arc
  351. static float offset[3] = {0.0, 0.0, 0.0};
  352. static float feedrate = 1500.0, next_feedrate, saved_feedrate;
  353. // Determines Absolute or Relative Coordinates.
  354. // Also there is bool axis_relative_modes[] per axis flag.
  355. static bool relative_mode = false;
  356. const int sensitive_pins[] = SENSITIVE_PINS; // Sensitive pin list for M42
  357. //static float tt = 0;
  358. //static float bt = 0;
  359. //Inactivity shutdown variables
  360. static unsigned long previous_millis_cmd = 0;
  361. unsigned long max_inactive_time = 0;
  362. static unsigned long stepper_inactive_time = DEFAULT_STEPPER_DEACTIVE_TIME*1000l;
  363. unsigned long starttime=0;
  364. unsigned long stoptime=0;
  365. unsigned long _usb_timer = 0;
  366. static uint8_t tmp_extruder;
  367. bool extruder_under_pressure = true;
  368. bool Stopped=false;
  369. #if NUM_SERVOS > 0
  370. Servo servos[NUM_SERVOS];
  371. #endif
  372. bool CooldownNoWait = true;
  373. bool target_direction;
  374. //Insert variables if CHDK is defined
  375. #ifdef CHDK
  376. unsigned long chdkHigh = 0;
  377. boolean chdkActive = false;
  378. #endif
  379. //===========================================================================
  380. //=============================Routines======================================
  381. //===========================================================================
  382. void get_arc_coordinates();
  383. bool setTargetedHotend(int code);
  384. void serial_echopair_P(const char *s_P, float v)
  385. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  386. void serial_echopair_P(const char *s_P, double v)
  387. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  388. void serial_echopair_P(const char *s_P, unsigned long v)
  389. { serialprintPGM(s_P); SERIAL_ECHO(v); }
  390. #ifdef SDSUPPORT
  391. #include "SdFatUtil.h"
  392. int freeMemory() { return SdFatUtil::FreeRam(); }
  393. #else
  394. extern "C" {
  395. extern unsigned int __bss_end;
  396. extern unsigned int __heap_start;
  397. extern void *__brkval;
  398. int freeMemory() {
  399. int free_memory;
  400. if ((int)__brkval == 0)
  401. free_memory = ((int)&free_memory) - ((int)&__bss_end);
  402. else
  403. free_memory = ((int)&free_memory) - ((int)__brkval);
  404. return free_memory;
  405. }
  406. }
  407. #endif //!SDSUPPORT
  408. void setup_killpin()
  409. {
  410. #if defined(KILL_PIN) && KILL_PIN > -1
  411. SET_INPUT(KILL_PIN);
  412. WRITE(KILL_PIN,HIGH);
  413. #endif
  414. }
  415. // Set home pin
  416. void setup_homepin(void)
  417. {
  418. #if defined(HOME_PIN) && HOME_PIN > -1
  419. SET_INPUT(HOME_PIN);
  420. WRITE(HOME_PIN,HIGH);
  421. #endif
  422. }
  423. void setup_photpin()
  424. {
  425. #if defined(PHOTOGRAPH_PIN) && PHOTOGRAPH_PIN > -1
  426. SET_OUTPUT(PHOTOGRAPH_PIN);
  427. WRITE(PHOTOGRAPH_PIN, LOW);
  428. #endif
  429. }
  430. void setup_powerhold()
  431. {
  432. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  433. SET_OUTPUT(SUICIDE_PIN);
  434. WRITE(SUICIDE_PIN, HIGH);
  435. #endif
  436. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  437. SET_OUTPUT(PS_ON_PIN);
  438. #if defined(PS_DEFAULT_OFF)
  439. WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  440. #else
  441. WRITE(PS_ON_PIN, PS_ON_AWAKE);
  442. #endif
  443. #endif
  444. }
  445. void suicide()
  446. {
  447. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  448. SET_OUTPUT(SUICIDE_PIN);
  449. WRITE(SUICIDE_PIN, LOW);
  450. #endif
  451. }
  452. void servo_init()
  453. {
  454. #if (NUM_SERVOS >= 1) && defined(SERVO0_PIN) && (SERVO0_PIN > -1)
  455. servos[0].attach(SERVO0_PIN);
  456. #endif
  457. #if (NUM_SERVOS >= 2) && defined(SERVO1_PIN) && (SERVO1_PIN > -1)
  458. servos[1].attach(SERVO1_PIN);
  459. #endif
  460. #if (NUM_SERVOS >= 3) && defined(SERVO2_PIN) && (SERVO2_PIN > -1)
  461. servos[2].attach(SERVO2_PIN);
  462. #endif
  463. #if (NUM_SERVOS >= 4) && defined(SERVO3_PIN) && (SERVO3_PIN > -1)
  464. servos[3].attach(SERVO3_PIN);
  465. #endif
  466. #if (NUM_SERVOS >= 5)
  467. #error "TODO: enter initalisation code for more servos"
  468. #endif
  469. }
  470. static void lcd_language_menu();
  471. void stop_and_save_print_to_ram(float z_move, float e_move);
  472. void restore_print_from_ram_and_continue(float e_move);
  473. void crashdet_enable()
  474. {
  475. tmc2130_sg_stop_on_crash = true;
  476. }
  477. void crashdet_disable()
  478. {
  479. tmc2130_sg_stop_on_crash = false;
  480. }
  481. void crashdet_stop_and_save_print()
  482. {
  483. stop_and_save_print_to_ram(10, 0); //XY - no change, Z 10mm up, E - no change
  484. }
  485. void crashdet_restore_print_and_continue()
  486. {
  487. restore_print_from_ram_and_continue(0); //XYZ = orig, E - no change
  488. }
  489. #ifdef PAT9125
  490. void fsensor_stop_and_save_print()
  491. {
  492. // stop_and_save_print_to_ram(10, -0.8); //XY - no change, Z 10mm up, E 0.8mm in
  493. stop_and_save_print_to_ram(0, 0); //XY - no change, Z 10mm up, E 0.8mm in
  494. }
  495. void fsensor_restore_print_and_continue()
  496. {
  497. restore_print_from_ram_and_continue(0); //XYZ = orig, E - no change
  498. }
  499. bool fsensor_enabled = false;
  500. bool fsensor_ignore_error = true;
  501. bool fsensor_M600 = false;
  502. long fsensor_prev_pos_e = 0;
  503. uint8_t fsensor_err_cnt = 0;
  504. #define FSENS_ESTEPS 280 //extruder resolution [steps/mm]
  505. //#define FSENS_MINDEL 560 //filament sensor min delta [steps] (3mm)
  506. #define FSENS_MINDEL 280 //filament sensor min delta [steps] (3mm)
  507. #define FSENS_MINFAC 3 //filament sensor minimum factor [count/mm]
  508. //#define FSENS_MAXFAC 50 //filament sensor maximum factor [count/mm]
  509. #define FSENS_MAXFAC 40 //filament sensor maximum factor [count/mm]
  510. //#define FSENS_MAXERR 2 //filament sensor max error count
  511. #define FSENS_MAXERR 5 //filament sensor max error count
  512. void fsensor_enable()
  513. {
  514. MYSERIAL.println("fsensor_enable");
  515. pat9125_y = 0;
  516. fsensor_prev_pos_e = st_get_position(E_AXIS);
  517. fsensor_err_cnt = 0;
  518. fsensor_enabled = true;
  519. fsensor_ignore_error = true;
  520. fsensor_M600 = false;
  521. }
  522. void fsensor_disable()
  523. {
  524. MYSERIAL.println("fsensor_disable");
  525. fsensor_enabled = false;
  526. }
  527. void fsensor_update()
  528. {
  529. if (!fsensor_enabled) return;
  530. long pos_e = st_get_position(E_AXIS); //current position
  531. pat9125_update();
  532. long del_e = pos_e - fsensor_prev_pos_e; //delta
  533. if (abs(del_e) < FSENS_MINDEL) return;
  534. float de = ((float)del_e / FSENS_ESTEPS);
  535. int cmin = de * FSENS_MINFAC;
  536. int cmax = de * FSENS_MAXFAC;
  537. int cnt = -pat9125_y;
  538. fsensor_prev_pos_e = pos_e;
  539. pat9125_y = 0;
  540. bool err = false;
  541. if ((del_e > 0) && ((cnt < cmin) || (cnt > cmax))) err = true;
  542. if ((del_e < 0) && ((cnt > cmin) || (cnt < cmax))) err = true;
  543. if (err)
  544. fsensor_err_cnt++;
  545. else
  546. fsensor_err_cnt = 0;
  547. /**/
  548. MYSERIAL.print("pos_e=");
  549. MYSERIAL.print(pos_e);
  550. MYSERIAL.print(" de=");
  551. MYSERIAL.print(de);
  552. MYSERIAL.print(" cmin=");
  553. MYSERIAL.print((int)cmin);
  554. MYSERIAL.print(" cmax=");
  555. MYSERIAL.print((int)cmax);
  556. MYSERIAL.print(" cnt=");
  557. MYSERIAL.print((int)cnt);
  558. MYSERIAL.print(" err=");
  559. MYSERIAL.println((int)fsensor_err_cnt);/**/
  560. // return;
  561. if (fsensor_err_cnt > FSENS_MAXERR)
  562. {
  563. MYSERIAL.println("fsensor_update (fsensor_err_cnt > FSENS_MAXERR)");
  564. if (fsensor_ignore_error)
  565. {
  566. MYSERIAL.println("fsensor_update - error ignored)");
  567. fsensor_ignore_error = false;
  568. }
  569. else
  570. {
  571. MYSERIAL.println("fsensor_update - ERROR!!!");
  572. fsensor_stop_and_save_print();
  573. enquecommand_front_P((PSTR("M600")));
  574. fsensor_M600 = true;
  575. fsensor_enabled = false;
  576. }
  577. }
  578. }
  579. #endif //PAT9125
  580. #ifdef MESH_BED_LEVELING
  581. enum MeshLevelingState { MeshReport, MeshStart, MeshNext, MeshSet };
  582. #endif
  583. // Factory reset function
  584. // This function is used to erase parts or whole EEPROM memory which is used for storing calibration and and so on.
  585. // Level input parameter sets depth of reset
  586. // Quiet parameter masks all waitings for user interact.
  587. int er_progress = 0;
  588. void factory_reset(char level, bool quiet)
  589. {
  590. lcd_implementation_clear();
  591. int cursor_pos = 0;
  592. switch (level) {
  593. // Level 0: Language reset
  594. case 0:
  595. WRITE(BEEPER, HIGH);
  596. _delay_ms(100);
  597. WRITE(BEEPER, LOW);
  598. lcd_force_language_selection();
  599. break;
  600. //Level 1: Reset statistics
  601. case 1:
  602. WRITE(BEEPER, HIGH);
  603. _delay_ms(100);
  604. WRITE(BEEPER, LOW);
  605. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, 0);
  606. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, 0);
  607. lcd_menu_statistics();
  608. break;
  609. // Level 2: Prepare for shipping
  610. case 2:
  611. //lcd_printPGM(PSTR("Factory RESET"));
  612. //lcd_print_at_PGM(1,2,PSTR("Shipping prep"));
  613. // Force language selection at the next boot up.
  614. lcd_force_language_selection();
  615. // Force the "Follow calibration flow" message at the next boot up.
  616. calibration_status_store(CALIBRATION_STATUS_Z_CALIBRATION);
  617. farm_no = 0;
  618. farm_mode == false;
  619. eeprom_update_byte((uint8_t*)EEPROM_FARM_MODE, farm_mode);
  620. EEPROM_save_B(EEPROM_FARM_NUMBER, &farm_no);
  621. WRITE(BEEPER, HIGH);
  622. _delay_ms(100);
  623. WRITE(BEEPER, LOW);
  624. //_delay_ms(2000);
  625. break;
  626. // Level 3: erase everything, whole EEPROM will be set to 0xFF
  627. case 3:
  628. lcd_printPGM(PSTR("Factory RESET"));
  629. lcd_print_at_PGM(1, 2, PSTR("ERASING all data"));
  630. WRITE(BEEPER, HIGH);
  631. _delay_ms(100);
  632. WRITE(BEEPER, LOW);
  633. er_progress = 0;
  634. lcd_print_at_PGM(3, 3, PSTR(" "));
  635. lcd_implementation_print_at(3, 3, er_progress);
  636. // Erase EEPROM
  637. for (int i = 0; i < 4096; i++) {
  638. eeprom_write_byte((uint8_t*)i, 0xFF);
  639. if (i % 41 == 0) {
  640. er_progress++;
  641. lcd_print_at_PGM(3, 3, PSTR(" "));
  642. lcd_implementation_print_at(3, 3, er_progress);
  643. lcd_printPGM(PSTR("%"));
  644. }
  645. }
  646. break;
  647. case 4:
  648. bowden_menu();
  649. break;
  650. default:
  651. break;
  652. }
  653. }
  654. // "Setup" function is called by the Arduino framework on startup.
  655. // Before startup, the Timers-functions (PWM)/Analog RW and HardwareSerial provided by the Arduino-code
  656. // are initialized by the main() routine provided by the Arduino framework.
  657. void setup()
  658. {
  659. lcd_init();
  660. lcd_print_at_PGM(0, 1, PSTR(" Original Prusa "));
  661. lcd_print_at_PGM(0, 2, PSTR(" 3D Printers "));
  662. setup_killpin();
  663. setup_powerhold();
  664. farm_mode = eeprom_read_byte((uint8_t*)EEPROM_FARM_MODE);
  665. EEPROM_read_B(EEPROM_FARM_NUMBER, &farm_no);
  666. if ((farm_mode == 0xFF && farm_no == 0) || (farm_no == 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
  667. if (farm_no == 0xFFFF) farm_no = 0;
  668. if (farm_mode)
  669. {
  670. prusa_statistics(8);
  671. selectedSerialPort = 1;
  672. }
  673. else
  674. selectedSerialPort = 0;
  675. MYSERIAL.begin(BAUDRATE);
  676. SERIAL_PROTOCOLLNPGM("start");
  677. SERIAL_ECHO_START;
  678. #if 0
  679. SERIAL_ECHOLN("Reading eeprom from 0 to 100: start");
  680. for (int i = 0; i < 4096; ++i) {
  681. int b = eeprom_read_byte((unsigned char*)i);
  682. if (b != 255) {
  683. SERIAL_ECHO(i);
  684. SERIAL_ECHO(":");
  685. SERIAL_ECHO(b);
  686. SERIAL_ECHOLN("");
  687. }
  688. }
  689. SERIAL_ECHOLN("Reading eeprom from 0 to 100: done");
  690. #endif
  691. // Check startup - does nothing if bootloader sets MCUSR to 0
  692. byte mcu = MCUSR;
  693. if (mcu & 1) SERIAL_ECHOLNRPGM(MSG_POWERUP);
  694. if (mcu & 2) SERIAL_ECHOLNRPGM(MSG_EXTERNAL_RESET);
  695. if (mcu & 4) SERIAL_ECHOLNRPGM(MSG_BROWNOUT_RESET);
  696. if (mcu & 8) SERIAL_ECHOLNRPGM(MSG_WATCHDOG_RESET);
  697. if (mcu & 32) SERIAL_ECHOLNRPGM(MSG_SOFTWARE_RESET);
  698. MCUSR = 0;
  699. //SERIAL_ECHORPGM(MSG_MARLIN);
  700. //SERIAL_ECHOLNRPGM(VERSION_STRING);
  701. #ifdef STRING_VERSION_CONFIG_H
  702. #ifdef STRING_CONFIG_H_AUTHOR
  703. SERIAL_ECHO_START;
  704. SERIAL_ECHORPGM(MSG_CONFIGURATION_VER);
  705. SERIAL_ECHOPGM(STRING_VERSION_CONFIG_H);
  706. SERIAL_ECHORPGM(MSG_AUTHOR);
  707. SERIAL_ECHOLNPGM(STRING_CONFIG_H_AUTHOR);
  708. SERIAL_ECHOPGM("Compiled: ");
  709. SERIAL_ECHOLNPGM(__DATE__);
  710. #endif
  711. #endif
  712. SERIAL_ECHO_START;
  713. SERIAL_ECHORPGM(MSG_FREE_MEMORY);
  714. SERIAL_ECHO(freeMemory());
  715. SERIAL_ECHORPGM(MSG_PLANNER_BUFFER_BYTES);
  716. SERIAL_ECHOLN((int)sizeof(block_t)*BLOCK_BUFFER_SIZE);
  717. //lcd_update_enable(false); // why do we need this?? - andre
  718. // loads data from EEPROM if available else uses defaults (and resets step acceleration rate)
  719. Config_RetrieveSettings(EEPROM_OFFSET);
  720. SdFatUtil::set_stack_guard(); //writes magic number at the end of static variables to protect against overwriting static memory by stack
  721. tp_init(); // Initialize temperature loop
  722. plan_init(); // Initialize planner;
  723. watchdog_init();
  724. #ifdef TMC2130
  725. uint8_t silentMode = eeprom_read_byte((uint8_t*)EEPROM_SILENT);
  726. tmc2130_mode = silentMode?TMC2130_MODE_SILENT:TMC2130_MODE_NORMAL;
  727. #endif //TMC2130
  728. #ifdef PAT9125
  729. MYSERIAL.print("PAT9125_init:");
  730. MYSERIAL.println(pat9125_init(200, 200));
  731. #endif //PAT9125
  732. st_init(); // Initialize stepper, this enables interrupts!
  733. setup_photpin();
  734. lcd_print_at_PGM(0, 1, PSTR(" Original Prusa ")); // we need to do this again for some reason, no time to research
  735. lcd_print_at_PGM(0, 2, PSTR(" 3D Printers "));
  736. servo_init();
  737. // Reset the machine correction matrix.
  738. // It does not make sense to load the correction matrix until the machine is homed.
  739. world2machine_reset();
  740. if (!READ(BTN_ENC))
  741. {
  742. _delay_ms(1000);
  743. if (!READ(BTN_ENC))
  744. {
  745. lcd_implementation_clear();
  746. lcd_printPGM(PSTR("Factory RESET"));
  747. SET_OUTPUT(BEEPER);
  748. WRITE(BEEPER, HIGH);
  749. while (!READ(BTN_ENC));
  750. WRITE(BEEPER, LOW);
  751. _delay_ms(2000);
  752. char level = reset_menu();
  753. factory_reset(level, false);
  754. switch (level) {
  755. case 0: _delay_ms(0); break;
  756. case 1: _delay_ms(0); break;
  757. case 2: _delay_ms(0); break;
  758. case 3: _delay_ms(0); break;
  759. }
  760. // _delay_ms(100);
  761. /*
  762. #ifdef MESH_BED_LEVELING
  763. _delay_ms(2000);
  764. if (!READ(BTN_ENC))
  765. {
  766. WRITE(BEEPER, HIGH);
  767. _delay_ms(100);
  768. WRITE(BEEPER, LOW);
  769. _delay_ms(200);
  770. WRITE(BEEPER, HIGH);
  771. _delay_ms(100);
  772. WRITE(BEEPER, LOW);
  773. int _z = 0;
  774. calibration_status_store(CALIBRATION_STATUS_CALIBRATED);
  775. EEPROM_save_B(EEPROM_BABYSTEP_X, &_z);
  776. EEPROM_save_B(EEPROM_BABYSTEP_Y, &_z);
  777. EEPROM_save_B(EEPROM_BABYSTEP_Z, &_z);
  778. }
  779. else
  780. {
  781. WRITE(BEEPER, HIGH);
  782. _delay_ms(100);
  783. WRITE(BEEPER, LOW);
  784. }
  785. #endif // mesh */
  786. }
  787. }
  788. else
  789. {
  790. //_delay_ms(1000); // wait 1sec to display the splash screen // what's this and why do we need it?? - andre
  791. }
  792. #if defined(CONTROLLERFAN_PIN) && (CONTROLLERFAN_PIN > -1)
  793. SET_OUTPUT(CONTROLLERFAN_PIN); //Set pin used for driver cooling fan
  794. #endif
  795. #if defined(LCD_PWM_PIN) && (LCD_PWM_PIN > -1)
  796. SET_OUTPUT(LCD_PWM_PIN); //Set pin used for driver cooling fan
  797. #endif
  798. #ifdef DIGIPOT_I2C
  799. digipot_i2c_init();
  800. #endif
  801. setup_homepin();
  802. #if defined(Z_AXIS_ALWAYS_ON)
  803. enable_z();
  804. #endif
  805. farm_mode = eeprom_read_byte((uint8_t*)EEPROM_FARM_MODE);
  806. EEPROM_read_B(EEPROM_FARM_NUMBER, &farm_no);
  807. if ((farm_mode == 0xFF && farm_no == 0) || (farm_no == 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
  808. if (farm_no == 0xFFFF) farm_no = 0;
  809. if (farm_mode)
  810. {
  811. prusa_statistics(8);
  812. }
  813. // Enable Toshiba FlashAir SD card / WiFi enahanced card.
  814. card.ToshibaFlashAir_enable(eeprom_read_byte((unsigned char*)EEPROM_TOSHIBA_FLASH_AIR_COMPATIBLITY) == 1);
  815. // Force SD card update. Otherwise the SD card update is done from loop() on card.checkautostart(false),
  816. // but this times out if a blocking dialog is shown in setup().
  817. card.initsd();
  818. if (eeprom_read_dword((uint32_t*)(EEPROM_TOP - 4)) == 0x0ffffffff &&
  819. eeprom_read_dword((uint32_t*)(EEPROM_TOP - 8)) == 0x0ffffffff &&
  820. eeprom_read_dword((uint32_t*)(EEPROM_TOP - 12)) == 0x0ffffffff) {
  821. // Maiden startup. The firmware has been loaded and first started on a virgin RAMBo board,
  822. // where all the EEPROM entries are set to 0x0ff.
  823. // Once a firmware boots up, it forces at least a language selection, which changes
  824. // EEPROM_LANG to number lower than 0x0ff.
  825. // 1) Set a high power mode.
  826. eeprom_write_byte((uint8_t*)EEPROM_SILENT, 0);
  827. }
  828. #ifdef SNMM
  829. if (eeprom_read_dword((uint32_t*)EEPROM_BOWDEN_LENGTH) == 0x0ffffffff) { //bowden length used for SNMM
  830. int _z = BOWDEN_LENGTH;
  831. for(int i = 0; i<4; i++) EEPROM_save_B(EEPROM_BOWDEN_LENGTH + i * 2, &_z);
  832. }
  833. #endif
  834. // In the future, somewhere here would one compare the current firmware version against the firmware version stored in the EEPROM.
  835. // If they differ, an update procedure may need to be performed. At the end of this block, the current firmware version
  836. // is being written into the EEPROM, so the update procedure will be triggered only once.
  837. lang_selected = eeprom_read_byte((uint8_t*)EEPROM_LANG);
  838. if (lang_selected >= LANG_NUM){
  839. lcd_mylang();
  840. }
  841. if (eeprom_read_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE) == 255) {
  842. eeprom_write_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE, 0);
  843. temp_cal_active = false;
  844. } else temp_cal_active = eeprom_read_byte((uint8_t*)EEPROM_TEMP_CAL_ACTIVE);
  845. if (eeprom_read_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA) == 255) {
  846. eeprom_write_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0);
  847. }
  848. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO) == 255) {
  849. eeprom_write_byte((uint8_t*)EEPROM_UVLO, 0);
  850. }
  851. {
  852. SERIAL_ECHOPGM("power up "); print_world_coordinates();
  853. SERIAL_ECHOPGM("power up "); print_physical_coordinates();
  854. SERIAL_ECHOPGM("initial zsteps on power up: "); MYSERIAL.println(tmc2130_rd_MSCNT(Z_TMC2130_CS));
  855. float z0 = current_position[Z_AXIS];
  856. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], z0 + 0.04, current_position[E_AXIS], feedrate/60, active_extruder);
  857. st_synchronize();
  858. SERIAL_ECHOPGM("full step: "); MYSERIAL.println(tmc2130_rd_MSCNT(Z_TMC2130_CS));
  859. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], z0 + 0.08, current_position[E_AXIS], feedrate/60, active_extruder);
  860. st_synchronize();
  861. SERIAL_ECHOPGM("two full steps: "); MYSERIAL.println(tmc2130_rd_MSCNT(Z_TMC2130_CS));
  862. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], z0 + 0.16 - 0.01, current_position[E_AXIS], feedrate/60, active_extruder);
  863. st_synchronize();
  864. SERIAL_ECHOPGM("nearly full cycle: "); MYSERIAL.println(tmc2130_rd_MSCNT(Z_TMC2130_CS));
  865. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], z0 + 0.16, current_position[E_AXIS], feedrate/60, active_extruder);
  866. st_synchronize();
  867. SERIAL_ECHOPGM("full cycle: "); MYSERIAL.println(tmc2130_rd_MSCNT(Z_TMC2130_CS));
  868. }
  869. #ifndef DEBUG_DISABLE_STARTMSGS
  870. check_babystep(); //checking if Z babystep is in allowed range
  871. setup_uvlo_interrupt();
  872. if (calibration_status() == CALIBRATION_STATUS_ASSEMBLED ||
  873. calibration_status() == CALIBRATION_STATUS_UNKNOWN) {
  874. // Reset the babystepping values, so the printer will not move the Z axis up when the babystepping is enabled.
  875. eeprom_update_word((uint16_t*)EEPROM_BABYSTEP_Z, 0);
  876. // Show the message.
  877. lcd_show_fullscreen_message_and_wait_P(MSG_FOLLOW_CALIBRATION_FLOW);
  878. } else if (calibration_status() == CALIBRATION_STATUS_LIVE_ADJUST) {
  879. // Show the message.
  880. lcd_show_fullscreen_message_and_wait_P(MSG_BABYSTEP_Z_NOT_SET);
  881. lcd_update_enable(true);
  882. } else if (calibration_status() == CALIBRATION_STATUS_CALIBRATED && temp_cal_active == true && calibration_status_pinda() == false) {
  883. lcd_show_fullscreen_message_and_wait_P(MSG_PINDA_NOT_CALIBRATED);
  884. lcd_update_enable(true);
  885. } else if (calibration_status() == CALIBRATION_STATUS_Z_CALIBRATION) {
  886. // Show the message.
  887. lcd_show_fullscreen_message_and_wait_P(MSG_FOLLOW_CALIBRATION_FLOW);
  888. }
  889. #endif //DEBUG_DISABLE_STARTMSGS
  890. for (int i = 0; i<4; i++) EEPROM_read_B(EEPROM_BOWDEN_LENGTH + i * 2, &bowden_length[i]);
  891. lcd_update_enable(true);
  892. lcd_implementation_clear();
  893. lcd_update(2);
  894. // Store the currently running firmware into an eeprom,
  895. // so the next time the firmware gets updated, it will know from which version it has been updated.
  896. update_current_firmware_version_to_eeprom();
  897. if (eeprom_read_byte((uint8_t*)EEPROM_UVLO) == 1) { //previous print was terminated by UVLO
  898. if (lcd_show_fullscreen_message_yes_no_and_wait_P(MSG_RECOVER_PRINT, false)) recover_print();
  899. else {
  900. eeprom_update_byte((uint8_t*)EEPROM_UVLO, 0);
  901. lcd_update_enable(true);
  902. lcd_update(2);
  903. lcd_setstatuspgm(WELCOME_MSG);
  904. }
  905. }
  906. }
  907. void trace();
  908. #define CHUNK_SIZE 64 // bytes
  909. #define SAFETY_MARGIN 1
  910. char chunk[CHUNK_SIZE+SAFETY_MARGIN];
  911. int chunkHead = 0;
  912. int serial_read_stream() {
  913. setTargetHotend(0, 0);
  914. setTargetBed(0);
  915. lcd_implementation_clear();
  916. lcd_printPGM(PSTR(" Upload in progress"));
  917. // first wait for how many bytes we will receive
  918. uint32_t bytesToReceive;
  919. // receive the four bytes
  920. char bytesToReceiveBuffer[4];
  921. for (int i=0; i<4; i++) {
  922. int data;
  923. while ((data = MYSERIAL.read()) == -1) {};
  924. bytesToReceiveBuffer[i] = data;
  925. }
  926. // make it a uint32
  927. memcpy(&bytesToReceive, &bytesToReceiveBuffer, 4);
  928. // we're ready, notify the sender
  929. MYSERIAL.write('+');
  930. // lock in the routine
  931. uint32_t receivedBytes = 0;
  932. while (prusa_sd_card_upload) {
  933. int i;
  934. for (i=0; i<CHUNK_SIZE; i++) {
  935. int data;
  936. // check if we're not done
  937. if (receivedBytes == bytesToReceive) {
  938. break;
  939. }
  940. // read the next byte
  941. while ((data = MYSERIAL.read()) == -1) {};
  942. receivedBytes++;
  943. // save it to the chunk
  944. chunk[i] = data;
  945. }
  946. // write the chunk to SD
  947. card.write_command_no_newline(&chunk[0]);
  948. // notify the sender we're ready for more data
  949. MYSERIAL.write('+');
  950. // for safety
  951. manage_heater();
  952. // check if we're done
  953. if(receivedBytes == bytesToReceive) {
  954. trace(); // beep
  955. card.closefile();
  956. prusa_sd_card_upload = false;
  957. SERIAL_PROTOCOLLNRPGM(MSG_FILE_SAVED);
  958. return 0;
  959. }
  960. }
  961. }
  962. // The loop() function is called in an endless loop by the Arduino framework from the default main() routine.
  963. // Before loop(), the setup() function is called by the main() routine.
  964. void loop()
  965. {
  966. bool stack_integrity = true;
  967. if (usb_printing_counter > 0 && millis()-_usb_timer > 1000)
  968. {
  969. is_usb_printing = true;
  970. usb_printing_counter--;
  971. _usb_timer = millis();
  972. }
  973. if (usb_printing_counter == 0)
  974. {
  975. is_usb_printing = false;
  976. }
  977. if (prusa_sd_card_upload)
  978. {
  979. //we read byte-by byte
  980. serial_read_stream();
  981. } else
  982. {
  983. get_command();
  984. #ifdef SDSUPPORT
  985. card.checkautostart(false);
  986. #endif
  987. if(buflen)
  988. {
  989. cmdbuffer_front_already_processed = false;
  990. #ifdef SDSUPPORT
  991. if(card.saving)
  992. {
  993. // Saving a G-code file onto an SD-card is in progress.
  994. // Saving starts with M28, saving until M29 is seen.
  995. if(strstr_P(CMDBUFFER_CURRENT_STRING, PSTR("M29")) == NULL) {
  996. card.write_command(CMDBUFFER_CURRENT_STRING);
  997. if(card.logging)
  998. process_commands();
  999. else
  1000. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  1001. } else {
  1002. card.closefile();
  1003. SERIAL_PROTOCOLLNRPGM(MSG_FILE_SAVED);
  1004. }
  1005. } else {
  1006. process_commands();
  1007. }
  1008. #else
  1009. process_commands();
  1010. #endif //SDSUPPORT
  1011. if (! cmdbuffer_front_already_processed && buflen)
  1012. {
  1013. cli();
  1014. union {
  1015. struct {
  1016. char lo;
  1017. char hi;
  1018. } lohi;
  1019. uint16_t value;
  1020. } sdlen;
  1021. sdlen.value = 0;
  1022. if (CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_SDCARD) {
  1023. sdlen.lohi.lo = cmdbuffer[bufindr + 1];
  1024. sdlen.lohi.hi = cmdbuffer[bufindr + 2];
  1025. }
  1026. cmdqueue_pop_front();
  1027. planner_add_sd_length(sdlen.value);
  1028. sei();
  1029. }
  1030. }
  1031. }
  1032. //check heater every n milliseconds
  1033. manage_heater();
  1034. isPrintPaused ? manage_inactivity(true) : manage_inactivity(false);
  1035. checkHitEndstops();
  1036. lcd_update();
  1037. #ifdef PAT9125
  1038. fsensor_update();
  1039. #endif //PAT9125
  1040. #ifdef TMC2130
  1041. tmc2130_check_overtemp();
  1042. if (tmc2130_sg_crash)
  1043. {
  1044. tmc2130_sg_crash = false;
  1045. crashdet_stop_and_save_print();
  1046. enquecommand_P((PSTR("D999")));
  1047. }
  1048. #endif //TMC2130
  1049. }
  1050. #define DEFINE_PGM_READ_ANY(type, reader) \
  1051. static inline type pgm_read_any(const type *p) \
  1052. { return pgm_read_##reader##_near(p); }
  1053. DEFINE_PGM_READ_ANY(float, float);
  1054. DEFINE_PGM_READ_ANY(signed char, byte);
  1055. #define XYZ_CONSTS_FROM_CONFIG(type, array, CONFIG) \
  1056. static const PROGMEM type array##_P[3] = \
  1057. { X_##CONFIG, Y_##CONFIG, Z_##CONFIG }; \
  1058. static inline type array(int axis) \
  1059. { return pgm_read_any(&array##_P[axis]); } \
  1060. type array##_ext(int axis) \
  1061. { return pgm_read_any(&array##_P[axis]); }
  1062. XYZ_CONSTS_FROM_CONFIG(float, base_min_pos, MIN_POS);
  1063. XYZ_CONSTS_FROM_CONFIG(float, base_max_pos, MAX_POS);
  1064. XYZ_CONSTS_FROM_CONFIG(float, base_home_pos, HOME_POS);
  1065. XYZ_CONSTS_FROM_CONFIG(float, max_length, MAX_LENGTH);
  1066. XYZ_CONSTS_FROM_CONFIG(float, home_retract_mm, HOME_RETRACT_MM);
  1067. XYZ_CONSTS_FROM_CONFIG(signed char, home_dir, HOME_DIR);
  1068. static void axis_is_at_home(int axis) {
  1069. current_position[axis] = base_home_pos(axis) + add_homing[axis];
  1070. min_pos[axis] = base_min_pos(axis) + add_homing[axis];
  1071. max_pos[axis] = base_max_pos(axis) + add_homing[axis];
  1072. }
  1073. inline void set_current_to_destination() { memcpy(current_position, destination, sizeof(current_position)); }
  1074. inline void set_destination_to_current() { memcpy(destination, current_position, sizeof(destination)); }
  1075. static void setup_for_endstop_move(bool enable_endstops_now = true) {
  1076. saved_feedrate = feedrate;
  1077. saved_feedmultiply = feedmultiply;
  1078. feedmultiply = 100;
  1079. previous_millis_cmd = millis();
  1080. enable_endstops(enable_endstops_now);
  1081. }
  1082. static void clean_up_after_endstop_move() {
  1083. #ifdef ENDSTOPS_ONLY_FOR_HOMING
  1084. enable_endstops(false);
  1085. #endif
  1086. feedrate = saved_feedrate;
  1087. feedmultiply = saved_feedmultiply;
  1088. previous_millis_cmd = millis();
  1089. }
  1090. #ifdef ENABLE_AUTO_BED_LEVELING
  1091. #ifdef AUTO_BED_LEVELING_GRID
  1092. static void set_bed_level_equation_lsq(double *plane_equation_coefficients)
  1093. {
  1094. vector_3 planeNormal = vector_3(-plane_equation_coefficients[0], -plane_equation_coefficients[1], 1);
  1095. planeNormal.debug("planeNormal");
  1096. plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1097. //bedLevel.debug("bedLevel");
  1098. //plan_bed_level_matrix.debug("bed level before");
  1099. //vector_3 uncorrected_position = plan_get_position_mm();
  1100. //uncorrected_position.debug("position before");
  1101. vector_3 corrected_position = plan_get_position();
  1102. // corrected_position.debug("position after");
  1103. current_position[X_AXIS] = corrected_position.x;
  1104. current_position[Y_AXIS] = corrected_position.y;
  1105. current_position[Z_AXIS] = corrected_position.z;
  1106. // put the bed at 0 so we don't go below it.
  1107. current_position[Z_AXIS] = zprobe_zoffset; // in the lsq we reach here after raising the extruder due to the loop structure
  1108. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1109. }
  1110. #else // not AUTO_BED_LEVELING_GRID
  1111. static void set_bed_level_equation_3pts(float z_at_pt_1, float z_at_pt_2, float z_at_pt_3) {
  1112. plan_bed_level_matrix.set_to_identity();
  1113. vector_3 pt1 = vector_3(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, z_at_pt_1);
  1114. vector_3 pt2 = vector_3(ABL_PROBE_PT_2_X, ABL_PROBE_PT_2_Y, z_at_pt_2);
  1115. vector_3 pt3 = vector_3(ABL_PROBE_PT_3_X, ABL_PROBE_PT_3_Y, z_at_pt_3);
  1116. vector_3 from_2_to_1 = (pt1 - pt2).get_normal();
  1117. vector_3 from_2_to_3 = (pt3 - pt2).get_normal();
  1118. vector_3 planeNormal = vector_3::cross(from_2_to_1, from_2_to_3).get_normal();
  1119. planeNormal = vector_3(planeNormal.x, planeNormal.y, abs(planeNormal.z));
  1120. plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1121. vector_3 corrected_position = plan_get_position();
  1122. current_position[X_AXIS] = corrected_position.x;
  1123. current_position[Y_AXIS] = corrected_position.y;
  1124. current_position[Z_AXIS] = corrected_position.z;
  1125. // put the bed at 0 so we don't go below it.
  1126. current_position[Z_AXIS] = zprobe_zoffset;
  1127. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1128. }
  1129. #endif // AUTO_BED_LEVELING_GRID
  1130. static void run_z_probe() {
  1131. plan_bed_level_matrix.set_to_identity();
  1132. feedrate = homing_feedrate[Z_AXIS];
  1133. // move down until you find the bed
  1134. float zPosition = -10;
  1135. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1136. st_synchronize();
  1137. // we have to let the planner know where we are right now as it is not where we said to go.
  1138. zPosition = st_get_position_mm(Z_AXIS);
  1139. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS]);
  1140. // move up the retract distance
  1141. zPosition += home_retract_mm(Z_AXIS);
  1142. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1143. st_synchronize();
  1144. // move back down slowly to find bed
  1145. feedrate = homing_feedrate[Z_AXIS]/4;
  1146. zPosition -= home_retract_mm(Z_AXIS) * 2;
  1147. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder);
  1148. st_synchronize();
  1149. current_position[Z_AXIS] = st_get_position_mm(Z_AXIS);
  1150. // make sure the planner knows where we are as it may be a bit different than we last said to move to
  1151. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1152. }
  1153. static void do_blocking_move_to(float x, float y, float z) {
  1154. float oldFeedRate = feedrate;
  1155. feedrate = homing_feedrate[Z_AXIS];
  1156. current_position[Z_AXIS] = z;
  1157. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], feedrate/60, active_extruder);
  1158. st_synchronize();
  1159. feedrate = XY_TRAVEL_SPEED;
  1160. current_position[X_AXIS] = x;
  1161. current_position[Y_AXIS] = y;
  1162. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], feedrate/60, active_extruder);
  1163. st_synchronize();
  1164. feedrate = oldFeedRate;
  1165. }
  1166. static void do_blocking_move_relative(float offset_x, float offset_y, float offset_z) {
  1167. do_blocking_move_to(current_position[X_AXIS] + offset_x, current_position[Y_AXIS] + offset_y, current_position[Z_AXIS] + offset_z);
  1168. }
  1169. /// Probe bed height at position (x,y), returns the measured z value
  1170. static float probe_pt(float x, float y, float z_before) {
  1171. // move to right place
  1172. do_blocking_move_to(current_position[X_AXIS], current_position[Y_AXIS], z_before);
  1173. do_blocking_move_to(x - X_PROBE_OFFSET_FROM_EXTRUDER, y - Y_PROBE_OFFSET_FROM_EXTRUDER, current_position[Z_AXIS]);
  1174. run_z_probe();
  1175. float measured_z = current_position[Z_AXIS];
  1176. SERIAL_PROTOCOLRPGM(MSG_BED);
  1177. SERIAL_PROTOCOLPGM(" x: ");
  1178. SERIAL_PROTOCOL(x);
  1179. SERIAL_PROTOCOLPGM(" y: ");
  1180. SERIAL_PROTOCOL(y);
  1181. SERIAL_PROTOCOLPGM(" z: ");
  1182. SERIAL_PROTOCOL(measured_z);
  1183. SERIAL_PROTOCOLPGM("\n");
  1184. return measured_z;
  1185. }
  1186. #endif // #ifdef ENABLE_AUTO_BED_LEVELING
  1187. #ifdef LIN_ADVANCE
  1188. /**
  1189. * M900: Set and/or Get advance K factor and WH/D ratio
  1190. *
  1191. * K<factor> Set advance K factor
  1192. * R<ratio> Set ratio directly (overrides WH/D)
  1193. * W<width> H<height> D<diam> Set ratio from WH/D
  1194. */
  1195. inline void gcode_M900() {
  1196. st_synchronize();
  1197. const float newK = code_seen('K') ? code_value_float() : -1;
  1198. if (newK >= 0) extruder_advance_k = newK;
  1199. float newR = code_seen('R') ? code_value_float() : -1;
  1200. if (newR < 0) {
  1201. const float newD = code_seen('D') ? code_value_float() : -1,
  1202. newW = code_seen('W') ? code_value_float() : -1,
  1203. newH = code_seen('H') ? code_value_float() : -1;
  1204. if (newD >= 0 && newW >= 0 && newH >= 0)
  1205. newR = newD ? (newW * newH) / (sq(newD * 0.5) * M_PI) : 0;
  1206. }
  1207. if (newR >= 0) advance_ed_ratio = newR;
  1208. SERIAL_ECHO_START;
  1209. SERIAL_ECHOPGM("Advance K=");
  1210. SERIAL_ECHOLN(extruder_advance_k);
  1211. SERIAL_ECHOPGM(" E/D=");
  1212. const float ratio = advance_ed_ratio;
  1213. if (ratio) SERIAL_ECHOLN(ratio); else SERIAL_ECHOLNPGM("Auto");
  1214. }
  1215. #endif // LIN_ADVANCE
  1216. #ifdef TMC2130
  1217. bool calibrate_z_auto()
  1218. {
  1219. lcd_display_message_fullscreen_P(MSG_CALIBRATE_Z_AUTO);
  1220. bool endstops_enabled = enable_endstops(true);
  1221. int axis_up_dir = -home_dir(Z_AXIS);
  1222. tmc2130_home_enter(Z_AXIS_MASK);
  1223. current_position[Z_AXIS] = 0;
  1224. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1225. set_destination_to_current();
  1226. destination[Z_AXIS] += (1.1 * max_length(Z_AXIS) * axis_up_dir);
  1227. feedrate = homing_feedrate[Z_AXIS];
  1228. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1229. tmc2130_home_restart(Z_AXIS);
  1230. st_synchronize();
  1231. // current_position[axis] = 0;
  1232. // plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1233. tmc2130_home_exit();
  1234. enable_endstops(false);
  1235. current_position[Z_AXIS] = 0;
  1236. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1237. set_destination_to_current();
  1238. destination[Z_AXIS] += 10 * axis_up_dir; //10mm up
  1239. feedrate = homing_feedrate[Z_AXIS] / 2;
  1240. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1241. st_synchronize();
  1242. enable_endstops(endstops_enabled);
  1243. current_position[Z_AXIS] = Z_MAX_POS-3.f;
  1244. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1245. return true;
  1246. }
  1247. #endif //TMC2130
  1248. void homeaxis(int axis)
  1249. {
  1250. bool endstops_enabled = enable_endstops(true); //RP: endstops should be allways enabled durring homming
  1251. #define HOMEAXIS_DO(LETTER) \
  1252. ((LETTER##_MIN_PIN > -1 && LETTER##_HOME_DIR==-1) || (LETTER##_MAX_PIN > -1 && LETTER##_HOME_DIR==1))
  1253. if ((axis==X_AXIS)?HOMEAXIS_DO(X):(axis==Y_AXIS)?HOMEAXIS_DO(Y):0)
  1254. {
  1255. int axis_home_dir = home_dir(axis);
  1256. #ifdef TMC2130
  1257. tmc2130_home_enter(X_AXIS_MASK << axis);
  1258. #endif
  1259. current_position[axis] = 0;
  1260. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1261. destination[axis] = 1.5 * max_length(axis) * axis_home_dir;
  1262. feedrate = homing_feedrate[axis];
  1263. #ifdef TMC2130
  1264. tmc2130_home_restart(axis);
  1265. #endif
  1266. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1267. st_synchronize();
  1268. /*
  1269. tmc2130_home_pause(axis);
  1270. current_position[axis] = 0;
  1271. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1272. destination[axis] = -home_retract_mm(axis) * axis_home_dir;
  1273. #ifdef TMC2130
  1274. tmc2130_home_restart(axis);
  1275. #endif
  1276. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1277. st_synchronize();
  1278. tmc2130_home_resume(axis);
  1279. destination[axis] = 2*home_retract_mm(axis) * axis_home_dir;
  1280. //#ifdef TMC2130
  1281. // feedrate = homing_feedrate[axis];
  1282. //#else
  1283. feedrate = homing_feedrate[axis] / 2;
  1284. //#endif
  1285. #ifdef TMC2130
  1286. tmc2130_home_restart(axis);
  1287. #endif
  1288. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1289. st_synchronize();
  1290. */
  1291. tmc2130_home_pause(axis);
  1292. current_position[axis] = 0;
  1293. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1294. destination[axis] = -0.32 * axis_home_dir;
  1295. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1296. st_synchronize();
  1297. axis_is_at_home(axis);
  1298. destination[axis] = current_position[axis];
  1299. feedrate = 0.0;
  1300. endstops_hit_on_purpose();
  1301. axis_known_position[axis] = true;
  1302. #ifdef TMC2130
  1303. tmc2130_home_exit();
  1304. // destination[axis] += 2;
  1305. // plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], homing_feedrate[axis]/60, active_extruder);
  1306. // st_synchronize();
  1307. #endif
  1308. }
  1309. else if ((axis==Z_AXIS)?HOMEAXIS_DO(Z):0)
  1310. {
  1311. int axis_home_dir = home_dir(axis);
  1312. current_position[axis] = 0;
  1313. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1314. destination[axis] = 1.5 * max_length(axis) * axis_home_dir;
  1315. feedrate = homing_feedrate[axis];
  1316. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1317. st_synchronize();
  1318. current_position[axis] = 0;
  1319. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1320. destination[axis] = -home_retract_mm(axis) * axis_home_dir;
  1321. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1322. st_synchronize();
  1323. destination[axis] = 2*home_retract_mm(axis) * axis_home_dir;
  1324. feedrate = homing_feedrate[axis]/2 ;
  1325. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1326. st_synchronize();
  1327. axis_is_at_home(axis);
  1328. destination[axis] = current_position[axis];
  1329. feedrate = 0.0;
  1330. endstops_hit_on_purpose();
  1331. axis_known_position[axis] = true;
  1332. }
  1333. enable_endstops(endstops_enabled);
  1334. }
  1335. /**/
  1336. void home_xy()
  1337. {
  1338. set_destination_to_current();
  1339. homeaxis(X_AXIS);
  1340. homeaxis(Y_AXIS);
  1341. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1342. endstops_hit_on_purpose();
  1343. }
  1344. void refresh_cmd_timeout(void)
  1345. {
  1346. previous_millis_cmd = millis();
  1347. }
  1348. #ifdef FWRETRACT
  1349. void retract(bool retracting, bool swapretract = false) {
  1350. if(retracting && !retracted[active_extruder]) {
  1351. destination[X_AXIS]=current_position[X_AXIS];
  1352. destination[Y_AXIS]=current_position[Y_AXIS];
  1353. destination[Z_AXIS]=current_position[Z_AXIS];
  1354. destination[E_AXIS]=current_position[E_AXIS];
  1355. if (swapretract) {
  1356. current_position[E_AXIS]+=retract_length_swap/volumetric_multiplier[active_extruder];
  1357. } else {
  1358. current_position[E_AXIS]+=retract_length/volumetric_multiplier[active_extruder];
  1359. }
  1360. plan_set_e_position(current_position[E_AXIS]);
  1361. float oldFeedrate = feedrate;
  1362. feedrate=retract_feedrate*60;
  1363. retracted[active_extruder]=true;
  1364. prepare_move();
  1365. current_position[Z_AXIS]-=retract_zlift;
  1366. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1367. prepare_move();
  1368. feedrate = oldFeedrate;
  1369. } else if(!retracting && retracted[active_extruder]) {
  1370. destination[X_AXIS]=current_position[X_AXIS];
  1371. destination[Y_AXIS]=current_position[Y_AXIS];
  1372. destination[Z_AXIS]=current_position[Z_AXIS];
  1373. destination[E_AXIS]=current_position[E_AXIS];
  1374. current_position[Z_AXIS]+=retract_zlift;
  1375. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1376. //prepare_move();
  1377. if (swapretract) {
  1378. current_position[E_AXIS]-=(retract_length_swap+retract_recover_length_swap)/volumetric_multiplier[active_extruder];
  1379. } else {
  1380. current_position[E_AXIS]-=(retract_length+retract_recover_length)/volumetric_multiplier[active_extruder];
  1381. }
  1382. plan_set_e_position(current_position[E_AXIS]);
  1383. float oldFeedrate = feedrate;
  1384. feedrate=retract_recover_feedrate*60;
  1385. retracted[active_extruder]=false;
  1386. prepare_move();
  1387. feedrate = oldFeedrate;
  1388. }
  1389. } //retract
  1390. #endif //FWRETRACT
  1391. void trace() {
  1392. tone(BEEPER, 440);
  1393. delay(25);
  1394. noTone(BEEPER);
  1395. delay(20);
  1396. }
  1397. /*
  1398. void ramming() {
  1399. // float tmp[4] = DEFAULT_MAX_FEEDRATE;
  1400. if (current_temperature[0] < 230) {
  1401. //PLA
  1402. max_feedrate[E_AXIS] = 50;
  1403. //current_position[E_AXIS] -= 8;
  1404. //plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 2100 / 60, active_extruder);
  1405. //current_position[E_AXIS] += 8;
  1406. //plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 2100 / 60, active_extruder);
  1407. current_position[E_AXIS] += 5.4;
  1408. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 2800 / 60, active_extruder);
  1409. current_position[E_AXIS] += 3.2;
  1410. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  1411. current_position[E_AXIS] += 3;
  1412. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3400 / 60, active_extruder);
  1413. st_synchronize();
  1414. max_feedrate[E_AXIS] = 80;
  1415. current_position[E_AXIS] -= 82;
  1416. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 9500 / 60, active_extruder);
  1417. max_feedrate[E_AXIS] = 50;//tmp[E_AXIS];
  1418. current_position[E_AXIS] -= 20;
  1419. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 1200 / 60, active_extruder);
  1420. current_position[E_AXIS] += 5;
  1421. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 400 / 60, active_extruder);
  1422. current_position[E_AXIS] += 5;
  1423. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 600 / 60, active_extruder);
  1424. current_position[E_AXIS] -= 10;
  1425. st_synchronize();
  1426. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 600 / 60, active_extruder);
  1427. current_position[E_AXIS] += 10;
  1428. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 600 / 60, active_extruder);
  1429. current_position[E_AXIS] -= 10;
  1430. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 800 / 60, active_extruder);
  1431. current_position[E_AXIS] += 10;
  1432. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 800 / 60, active_extruder);
  1433. current_position[E_AXIS] -= 10;
  1434. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 800 / 60, active_extruder);
  1435. st_synchronize();
  1436. }
  1437. else {
  1438. //ABS
  1439. max_feedrate[E_AXIS] = 50;
  1440. //current_position[E_AXIS] -= 8;
  1441. //plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 2100 / 60, active_extruder);
  1442. //current_position[E_AXIS] += 8;
  1443. //plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 2100 / 60, active_extruder);
  1444. current_position[E_AXIS] += 3.1;
  1445. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 2000 / 60, active_extruder);
  1446. current_position[E_AXIS] += 3.1;
  1447. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 2500 / 60, active_extruder);
  1448. current_position[E_AXIS] += 4;
  1449. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  1450. st_synchronize();
  1451. //current_position[X_AXIS] += 23; //delay
  1452. //plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 600/60, active_extruder); //delay
  1453. //current_position[X_AXIS] -= 23; //delay
  1454. //plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 600/60, active_extruder); //delay
  1455. delay(4700);
  1456. max_feedrate[E_AXIS] = 80;
  1457. current_position[E_AXIS] -= 92;
  1458. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 9900 / 60, active_extruder);
  1459. max_feedrate[E_AXIS] = 50;//tmp[E_AXIS];
  1460. current_position[E_AXIS] -= 5;
  1461. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 800 / 60, active_extruder);
  1462. current_position[E_AXIS] += 5;
  1463. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 400 / 60, active_extruder);
  1464. current_position[E_AXIS] -= 5;
  1465. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 600 / 60, active_extruder);
  1466. st_synchronize();
  1467. current_position[E_AXIS] += 5;
  1468. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 600 / 60, active_extruder);
  1469. current_position[E_AXIS] -= 5;
  1470. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 600 / 60, active_extruder);
  1471. current_position[E_AXIS] += 5;
  1472. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 600 / 60, active_extruder);
  1473. current_position[E_AXIS] -= 5;
  1474. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 600 / 60, active_extruder);
  1475. st_synchronize();
  1476. }
  1477. }
  1478. */
  1479. void process_commands()
  1480. {
  1481. #ifdef FILAMENT_RUNOUT_SUPPORT
  1482. SET_INPUT(FR_SENS);
  1483. #endif
  1484. #ifdef CMDBUFFER_DEBUG
  1485. SERIAL_ECHOPGM("Processing a GCODE command: ");
  1486. SERIAL_ECHO(cmdbuffer+bufindr+CMDHDRSIZE);
  1487. SERIAL_ECHOLNPGM("");
  1488. SERIAL_ECHOPGM("In cmdqueue: ");
  1489. SERIAL_ECHO(buflen);
  1490. SERIAL_ECHOLNPGM("");
  1491. #endif /* CMDBUFFER_DEBUG */
  1492. unsigned long codenum; //throw away variable
  1493. char *starpos = NULL;
  1494. #ifdef ENABLE_AUTO_BED_LEVELING
  1495. float x_tmp, y_tmp, z_tmp, real_z;
  1496. #endif
  1497. // PRUSA GCODES
  1498. #ifdef SNMM
  1499. float tmp_motor[3] = DEFAULT_PWM_MOTOR_CURRENT;
  1500. float tmp_motor_loud[3] = DEFAULT_PWM_MOTOR_CURRENT_LOUD;
  1501. int8_t SilentMode;
  1502. #endif
  1503. if (code_seen("M117")) { //moved to highest priority place to be able to to print strings which includes "G", "PRUSA" and "^"
  1504. starpos = (strchr(strchr_pointer + 5, '*'));
  1505. if (starpos != NULL)
  1506. *(starpos) = '\0';
  1507. lcd_setstatus(strchr_pointer + 5);
  1508. }
  1509. else if(code_seen("PRUSA")){
  1510. if (code_seen("Ping")) { //PRUSA Ping
  1511. if (farm_mode) {
  1512. PingTime = millis();
  1513. //MYSERIAL.print(farm_no); MYSERIAL.println(": OK");
  1514. }
  1515. }
  1516. else if (code_seen("PRN")) {
  1517. MYSERIAL.println(status_number);
  1518. }else if (code_seen("fn")) {
  1519. if (farm_mode) {
  1520. MYSERIAL.println(farm_no);
  1521. }
  1522. else {
  1523. MYSERIAL.println("Not in farm mode.");
  1524. }
  1525. }else if (code_seen("fv")) {
  1526. // get file version
  1527. #ifdef SDSUPPORT
  1528. card.openFile(strchr_pointer + 3,true);
  1529. while (true) {
  1530. uint16_t readByte = card.get();
  1531. MYSERIAL.write(readByte);
  1532. if (readByte=='\n') {
  1533. break;
  1534. }
  1535. }
  1536. card.closefile();
  1537. #endif // SDSUPPORT
  1538. } else if (code_seen("M28")) {
  1539. trace();
  1540. prusa_sd_card_upload = true;
  1541. card.openFile(strchr_pointer+4,false);
  1542. } else if (code_seen("SN")) {
  1543. if (farm_mode) {
  1544. selectedSerialPort = 0;
  1545. MSerial.write(";S");
  1546. // S/N is:CZPX0917X003XC13518
  1547. int numbersRead = 0;
  1548. while (numbersRead < 19) {
  1549. while (MSerial.available() > 0) {
  1550. uint8_t serial_char = MSerial.read();
  1551. selectedSerialPort = 1;
  1552. MSerial.write(serial_char);
  1553. numbersRead++;
  1554. selectedSerialPort = 0;
  1555. }
  1556. }
  1557. selectedSerialPort = 1;
  1558. MSerial.write('\n');
  1559. /*for (int b = 0; b < 3; b++) {
  1560. tone(BEEPER, 110);
  1561. delay(50);
  1562. noTone(BEEPER);
  1563. delay(50);
  1564. }*/
  1565. } else {
  1566. MYSERIAL.println("Not in farm mode.");
  1567. }
  1568. } else if(code_seen("Fir")){
  1569. SERIAL_PROTOCOLLN(FW_version);
  1570. } else if(code_seen("Rev")){
  1571. SERIAL_PROTOCOLLN(FILAMENT_SIZE "-" ELECTRONICS "-" NOZZLE_TYPE );
  1572. } else if(code_seen("Lang")) {
  1573. lcd_force_language_selection();
  1574. } else if(code_seen("Lz")) {
  1575. EEPROM_save_B(EEPROM_BABYSTEP_Z,0);
  1576. } else if (code_seen("SERIAL LOW")) {
  1577. MYSERIAL.println("SERIAL LOW");
  1578. MYSERIAL.begin(BAUDRATE);
  1579. return;
  1580. } else if (code_seen("SERIAL HIGH")) {
  1581. MYSERIAL.println("SERIAL HIGH");
  1582. MYSERIAL.begin(1152000);
  1583. return;
  1584. } else if(code_seen("Beat")) {
  1585. // Kick farm link timer
  1586. kicktime = millis();
  1587. } else if(code_seen("FR")) {
  1588. // Factory full reset
  1589. factory_reset(0,true);
  1590. }
  1591. //else if (code_seen('Cal')) {
  1592. // lcd_calibration();
  1593. // }
  1594. }
  1595. else if (code_seen('^')) {
  1596. // nothing, this is a version line
  1597. } else if(code_seen('G'))
  1598. {
  1599. switch((int)code_value())
  1600. {
  1601. case 0: // G0 -> G1
  1602. case 1: // G1
  1603. if(Stopped == false) {
  1604. #ifdef FILAMENT_RUNOUT_SUPPORT
  1605. if(READ(FR_SENS)){
  1606. feedmultiplyBckp=feedmultiply;
  1607. float target[4];
  1608. float lastpos[4];
  1609. target[X_AXIS]=current_position[X_AXIS];
  1610. target[Y_AXIS]=current_position[Y_AXIS];
  1611. target[Z_AXIS]=current_position[Z_AXIS];
  1612. target[E_AXIS]=current_position[E_AXIS];
  1613. lastpos[X_AXIS]=current_position[X_AXIS];
  1614. lastpos[Y_AXIS]=current_position[Y_AXIS];
  1615. lastpos[Z_AXIS]=current_position[Z_AXIS];
  1616. lastpos[E_AXIS]=current_position[E_AXIS];
  1617. //retract by E
  1618. target[E_AXIS]+= FILAMENTCHANGE_FIRSTRETRACT ;
  1619. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 400, active_extruder);
  1620. target[Z_AXIS]+= FILAMENTCHANGE_ZADD ;
  1621. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 300, active_extruder);
  1622. target[X_AXIS]= FILAMENTCHANGE_XPOS ;
  1623. target[Y_AXIS]= FILAMENTCHANGE_YPOS ;
  1624. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 70, active_extruder);
  1625. target[E_AXIS]+= FILAMENTCHANGE_FINALRETRACT ;
  1626. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 20, active_extruder);
  1627. //finish moves
  1628. st_synchronize();
  1629. //disable extruder steppers so filament can be removed
  1630. disable_e0();
  1631. disable_e1();
  1632. disable_e2();
  1633. delay(100);
  1634. //LCD_ALERTMESSAGEPGM(MSG_FILAMENTCHANGE);
  1635. uint8_t cnt=0;
  1636. int counterBeep = 0;
  1637. lcd_wait_interact();
  1638. while(!lcd_clicked()){
  1639. cnt++;
  1640. manage_heater();
  1641. manage_inactivity(true);
  1642. //lcd_update();
  1643. if(cnt==0)
  1644. {
  1645. #if BEEPER > 0
  1646. if (counterBeep== 500){
  1647. counterBeep = 0;
  1648. }
  1649. SET_OUTPUT(BEEPER);
  1650. if (counterBeep== 0){
  1651. WRITE(BEEPER,HIGH);
  1652. }
  1653. if (counterBeep== 20){
  1654. WRITE(BEEPER,LOW);
  1655. }
  1656. counterBeep++;
  1657. #else
  1658. #if !defined(LCD_FEEDBACK_FREQUENCY_HZ) || !defined(LCD_FEEDBACK_FREQUENCY_DURATION_MS)
  1659. lcd_buzz(1000/6,100);
  1660. #else
  1661. lcd_buzz(LCD_FEEDBACK_FREQUENCY_DURATION_MS,LCD_FEEDBACK_FREQUENCY_HZ);
  1662. #endif
  1663. #endif
  1664. }
  1665. }
  1666. WRITE(BEEPER,LOW);
  1667. target[E_AXIS]+= FILAMENTCHANGE_FIRSTFEED ;
  1668. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 20, active_extruder);
  1669. target[E_AXIS]+= FILAMENTCHANGE_FINALFEED ;
  1670. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 2, active_extruder);
  1671. lcd_change_fil_state = 0;
  1672. lcd_loading_filament();
  1673. while ((lcd_change_fil_state == 0)||(lcd_change_fil_state != 1)){
  1674. lcd_change_fil_state = 0;
  1675. lcd_alright();
  1676. switch(lcd_change_fil_state){
  1677. case 2:
  1678. target[E_AXIS]+= FILAMENTCHANGE_FIRSTFEED ;
  1679. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 20, active_extruder);
  1680. target[E_AXIS]+= FILAMENTCHANGE_FINALFEED ;
  1681. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 2, active_extruder);
  1682. lcd_loading_filament();
  1683. break;
  1684. case 3:
  1685. target[E_AXIS]+= FILAMENTCHANGE_FINALFEED ;
  1686. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 2, active_extruder);
  1687. lcd_loading_color();
  1688. break;
  1689. default:
  1690. lcd_change_success();
  1691. break;
  1692. }
  1693. }
  1694. target[E_AXIS]+= 5;
  1695. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 2, active_extruder);
  1696. target[E_AXIS]+= FILAMENTCHANGE_FIRSTRETRACT;
  1697. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 400, active_extruder);
  1698. //current_position[E_AXIS]=target[E_AXIS]; //the long retract of L is compensated by manual filament feeding
  1699. //plan_set_e_position(current_position[E_AXIS]);
  1700. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 70, active_extruder); //should do nothing
  1701. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], target[Z_AXIS], target[E_AXIS], 70, active_extruder); //move xy back
  1702. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], lastpos[Z_AXIS], target[E_AXIS], 200, active_extruder); //move z back
  1703. target[E_AXIS]= target[E_AXIS] - FILAMENTCHANGE_FIRSTRETRACT;
  1704. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], lastpos[Z_AXIS], target[E_AXIS], 5, active_extruder); //final untretract
  1705. plan_set_e_position(lastpos[E_AXIS]);
  1706. feedmultiply=feedmultiplyBckp;
  1707. char cmd[9];
  1708. sprintf_P(cmd, PSTR("M220 S%i"), feedmultiplyBckp);
  1709. enquecommand(cmd);
  1710. }
  1711. #endif
  1712. get_coordinates(); // For X Y Z E F
  1713. if (total_filament_used > ((current_position[E_AXIS] - destination[E_AXIS]) * 100)) { //protection against total_filament_used overflow
  1714. total_filament_used = total_filament_used + ((destination[E_AXIS] - current_position[E_AXIS]) * 100);
  1715. }
  1716. #ifdef FWRETRACT
  1717. if(autoretract_enabled)
  1718. if( !(code_seen('X') || code_seen('Y') || code_seen('Z')) && code_seen('E')) {
  1719. float echange=destination[E_AXIS]-current_position[E_AXIS];
  1720. if((echange<-MIN_RETRACT && !retracted) || (echange>MIN_RETRACT && retracted)) { //move appears to be an attempt to retract or recover
  1721. current_position[E_AXIS] = destination[E_AXIS]; //hide the slicer-generated retract/recover from calculations
  1722. plan_set_e_position(current_position[E_AXIS]); //AND from the planner
  1723. retract(!retracted);
  1724. return;
  1725. }
  1726. }
  1727. #endif //FWRETRACT
  1728. prepare_move();
  1729. //ClearToSend();
  1730. }
  1731. break;
  1732. case 2: // G2 - CW ARC
  1733. if(Stopped == false) {
  1734. get_arc_coordinates();
  1735. prepare_arc_move(true);
  1736. }
  1737. break;
  1738. case 3: // G3 - CCW ARC
  1739. if(Stopped == false) {
  1740. get_arc_coordinates();
  1741. prepare_arc_move(false);
  1742. }
  1743. break;
  1744. case 4: // G4 dwell
  1745. codenum = 0;
  1746. if(code_seen('P')) codenum = code_value(); // milliseconds to wait
  1747. if(code_seen('S')) codenum = code_value() * 1000; // seconds to wait
  1748. if(codenum != 0) LCD_MESSAGERPGM(MSG_DWELL);
  1749. st_synchronize();
  1750. codenum += millis(); // keep track of when we started waiting
  1751. previous_millis_cmd = millis();
  1752. while(millis() < codenum) {
  1753. manage_heater();
  1754. manage_inactivity();
  1755. lcd_update();
  1756. }
  1757. break;
  1758. #ifdef FWRETRACT
  1759. case 10: // G10 retract
  1760. #if EXTRUDERS > 1
  1761. retracted_swap[active_extruder]=(code_seen('S') && code_value_long() == 1); // checks for swap retract argument
  1762. retract(true,retracted_swap[active_extruder]);
  1763. #else
  1764. retract(true);
  1765. #endif
  1766. break;
  1767. case 11: // G11 retract_recover
  1768. #if EXTRUDERS > 1
  1769. retract(false,retracted_swap[active_extruder]);
  1770. #else
  1771. retract(false);
  1772. #endif
  1773. break;
  1774. #endif //FWRETRACT
  1775. case 28: //G28 Home all Axis one at a time
  1776. {
  1777. st_synchronize();
  1778. #if 1
  1779. SERIAL_ECHOPGM("G28, initial "); print_world_coordinates();
  1780. SERIAL_ECHOPGM("G28, initial "); print_physical_coordinates();
  1781. #endif
  1782. // Flag for the display update routine and to disable the print cancelation during homing.
  1783. homing_flag = true;
  1784. // Which axes should be homed?
  1785. bool home_x = code_seen(axis_codes[X_AXIS]);
  1786. bool home_y = code_seen(axis_codes[Y_AXIS]);
  1787. bool home_z = code_seen(axis_codes[Z_AXIS]);
  1788. // Either all X,Y,Z codes are present, or none of them.
  1789. bool home_all_axes = home_x == home_y && home_x == home_z;
  1790. if (home_all_axes)
  1791. // No X/Y/Z code provided means to home all axes.
  1792. home_x = home_y = home_z = true;
  1793. #ifdef ENABLE_AUTO_BED_LEVELING
  1794. plan_bed_level_matrix.set_to_identity(); //Reset the plane ("erase" all leveling data)
  1795. #endif //ENABLE_AUTO_BED_LEVELING
  1796. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  1797. // the planner will not perform any adjustments in the XY plane.
  1798. // Wait for the motors to stop and update the current position with the absolute values.
  1799. world2machine_revert_to_uncorrected();
  1800. // For mesh bed leveling deactivate the matrix temporarily.
  1801. // It is necessary to disable the bed leveling for the X and Y homing moves, so that the move is performed
  1802. // in a single axis only.
  1803. // In case of re-homing the X or Y axes only, the mesh bed leveling is restored after G28.
  1804. #ifdef MESH_BED_LEVELING
  1805. uint8_t mbl_was_active = mbl.active;
  1806. mbl.active = 0;
  1807. current_position[Z_AXIS] = st_get_position_mm(Z_AXIS);
  1808. #endif
  1809. // Reset baby stepping to zero, if the babystepping has already been loaded before. The babystepsTodo value will be
  1810. // consumed during the first movements following this statement.
  1811. if (home_z)
  1812. babystep_undo();
  1813. saved_feedrate = feedrate;
  1814. saved_feedmultiply = feedmultiply;
  1815. feedmultiply = 100;
  1816. previous_millis_cmd = millis();
  1817. enable_endstops(true);
  1818. memcpy(destination, current_position, sizeof(destination));
  1819. feedrate = 0.0;
  1820. #if Z_HOME_DIR > 0 // If homing away from BED do Z first
  1821. if(home_z)
  1822. homeaxis(Z_AXIS);
  1823. #endif
  1824. #ifdef QUICK_HOME
  1825. // In the quick mode, if both x and y are to be homed, a diagonal move will be performed initially.
  1826. if(home_x && home_y) //first diagonal move
  1827. {
  1828. current_position[X_AXIS] = 0;current_position[Y_AXIS] = 0;
  1829. int x_axis_home_dir = home_dir(X_AXIS);
  1830. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1831. 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);
  1832. feedrate = homing_feedrate[X_AXIS];
  1833. if(homing_feedrate[Y_AXIS]<feedrate)
  1834. feedrate = homing_feedrate[Y_AXIS];
  1835. if (max_length(X_AXIS) > max_length(Y_AXIS)) {
  1836. feedrate *= sqrt(pow(max_length(Y_AXIS) / max_length(X_AXIS), 2) + 1);
  1837. } else {
  1838. feedrate *= sqrt(pow(max_length(X_AXIS) / max_length(Y_AXIS), 2) + 1);
  1839. }
  1840. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1841. st_synchronize();
  1842. axis_is_at_home(X_AXIS);
  1843. axis_is_at_home(Y_AXIS);
  1844. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1845. destination[X_AXIS] = current_position[X_AXIS];
  1846. destination[Y_AXIS] = current_position[Y_AXIS];
  1847. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  1848. feedrate = 0.0;
  1849. st_synchronize();
  1850. endstops_hit_on_purpose();
  1851. current_position[X_AXIS] = destination[X_AXIS];
  1852. current_position[Y_AXIS] = destination[Y_AXIS];
  1853. current_position[Z_AXIS] = destination[Z_AXIS];
  1854. }
  1855. #endif /* QUICK_HOME */
  1856. if(home_x)
  1857. homeaxis(X_AXIS);
  1858. if(home_y)
  1859. homeaxis(Y_AXIS);
  1860. if(code_seen(axis_codes[X_AXIS]) && code_value_long() != 0)
  1861. current_position[X_AXIS]=code_value()+add_homing[X_AXIS];
  1862. if(code_seen(axis_codes[Y_AXIS]) && code_value_long() != 0)
  1863. current_position[Y_AXIS]=code_value()+add_homing[Y_AXIS];
  1864. #if Z_HOME_DIR < 0 // If homing towards BED do Z last
  1865. #ifndef Z_SAFE_HOMING
  1866. if(home_z) {
  1867. #if defined (Z_RAISE_BEFORE_HOMING) && (Z_RAISE_BEFORE_HOMING > 0)
  1868. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  1869. feedrate = max_feedrate[Z_AXIS];
  1870. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate, active_extruder);
  1871. st_synchronize();
  1872. #endif // defined (Z_RAISE_BEFORE_HOMING) && (Z_RAISE_BEFORE_HOMING > 0)
  1873. #if (defined(MESH_BED_LEVELING) && !defined(MK1BP)) // If Mesh bed leveling, moxve X&Y to safe position for home
  1874. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] ))
  1875. {
  1876. homeaxis(X_AXIS);
  1877. homeaxis(Y_AXIS);
  1878. }
  1879. // 1st mesh bed leveling measurement point, corrected.
  1880. world2machine_initialize();
  1881. world2machine(pgm_read_float(bed_ref_points), pgm_read_float(bed_ref_points+1), destination[X_AXIS], destination[Y_AXIS]);
  1882. world2machine_reset();
  1883. if (destination[Y_AXIS] < Y_MIN_POS)
  1884. destination[Y_AXIS] = Y_MIN_POS;
  1885. destination[Z_AXIS] = MESH_HOME_Z_SEARCH; // Set destination away from bed
  1886. feedrate = homing_feedrate[Z_AXIS]/10;
  1887. current_position[Z_AXIS] = 0;
  1888. enable_endstops(false);
  1889. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1890. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate, active_extruder);
  1891. st_synchronize();
  1892. current_position[X_AXIS] = destination[X_AXIS];
  1893. current_position[Y_AXIS] = destination[Y_AXIS];
  1894. enable_endstops(true);
  1895. endstops_hit_on_purpose();
  1896. homeaxis(Z_AXIS);
  1897. #else // MESH_BED_LEVELING
  1898. homeaxis(Z_AXIS);
  1899. #endif // MESH_BED_LEVELING
  1900. }
  1901. #else // defined(Z_SAFE_HOMING): Z Safe mode activated.
  1902. if(home_all_axes) {
  1903. destination[X_AXIS] = round(Z_SAFE_HOMING_X_POINT - X_PROBE_OFFSET_FROM_EXTRUDER);
  1904. destination[Y_AXIS] = round(Z_SAFE_HOMING_Y_POINT - Y_PROBE_OFFSET_FROM_EXTRUDER);
  1905. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  1906. feedrate = XY_TRAVEL_SPEED/60;
  1907. current_position[Z_AXIS] = 0;
  1908. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1909. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate, active_extruder);
  1910. st_synchronize();
  1911. current_position[X_AXIS] = destination[X_AXIS];
  1912. current_position[Y_AXIS] = destination[Y_AXIS];
  1913. homeaxis(Z_AXIS);
  1914. }
  1915. // Let's see if X and Y are homed and probe is inside bed area.
  1916. if(home_z) {
  1917. if ( (axis_known_position[X_AXIS]) && (axis_known_position[Y_AXIS]) \
  1918. && (current_position[X_AXIS]+X_PROBE_OFFSET_FROM_EXTRUDER >= X_MIN_POS) \
  1919. && (current_position[X_AXIS]+X_PROBE_OFFSET_FROM_EXTRUDER <= X_MAX_POS) \
  1920. && (current_position[Y_AXIS]+Y_PROBE_OFFSET_FROM_EXTRUDER >= Y_MIN_POS) \
  1921. && (current_position[Y_AXIS]+Y_PROBE_OFFSET_FROM_EXTRUDER <= Y_MAX_POS)) {
  1922. current_position[Z_AXIS] = 0;
  1923. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1924. destination[Z_AXIS] = Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS) * (-1); // Set destination away from bed
  1925. feedrate = max_feedrate[Z_AXIS];
  1926. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate, active_extruder);
  1927. st_synchronize();
  1928. homeaxis(Z_AXIS);
  1929. } else if (!((axis_known_position[X_AXIS]) && (axis_known_position[Y_AXIS]))) {
  1930. LCD_MESSAGERPGM(MSG_POSITION_UNKNOWN);
  1931. SERIAL_ECHO_START;
  1932. SERIAL_ECHOLNRPGM(MSG_POSITION_UNKNOWN);
  1933. } else {
  1934. LCD_MESSAGERPGM(MSG_ZPROBE_OUT);
  1935. SERIAL_ECHO_START;
  1936. SERIAL_ECHOLNRPGM(MSG_ZPROBE_OUT);
  1937. }
  1938. }
  1939. #endif // Z_SAFE_HOMING
  1940. #endif // Z_HOME_DIR < 0
  1941. if(code_seen(axis_codes[Z_AXIS]) && code_value_long() != 0)
  1942. current_position[Z_AXIS]=code_value()+add_homing[Z_AXIS];
  1943. #ifdef ENABLE_AUTO_BED_LEVELING
  1944. if(home_z)
  1945. current_position[Z_AXIS] += zprobe_zoffset; //Add Z_Probe offset (the distance is negative)
  1946. #endif
  1947. // Set the planner and stepper routine positions.
  1948. // At this point the mesh bed leveling and world2machine corrections are disabled and current_position
  1949. // contains the machine coordinates.
  1950. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1951. #ifdef ENDSTOPS_ONLY_FOR_HOMING
  1952. enable_endstops(false);
  1953. #endif
  1954. feedrate = saved_feedrate;
  1955. feedmultiply = saved_feedmultiply;
  1956. previous_millis_cmd = millis();
  1957. endstops_hit_on_purpose();
  1958. #ifndef MESH_BED_LEVELING
  1959. // If MESH_BED_LEVELING is not active, then it is the original Prusa i3.
  1960. // Offer the user to load the baby step value, which has been adjusted at the previous print session.
  1961. if(card.sdprinting && eeprom_read_word((uint16_t *)EEPROM_BABYSTEP_Z))
  1962. lcd_adjust_z();
  1963. #endif
  1964. // Load the machine correction matrix
  1965. world2machine_initialize();
  1966. // and correct the current_position XY axes to match the transformed coordinate system.
  1967. world2machine_update_current();
  1968. #if (defined(MESH_BED_LEVELING) && !defined(MK1BP))
  1969. if (code_seen(axis_codes[X_AXIS]) || code_seen(axis_codes[Y_AXIS]) || code_seen('W') || code_seen(axis_codes[Z_AXIS]))
  1970. {
  1971. if (! home_z && mbl_was_active) {
  1972. // Re-enable the mesh bed leveling if only the X and Y axes were re-homed.
  1973. mbl.active = true;
  1974. // and re-adjust the current logical Z axis with the bed leveling offset applicable at the current XY position.
  1975. current_position[Z_AXIS] -= mbl.get_z(st_get_position_mm(X_AXIS), st_get_position_mm(Y_AXIS));
  1976. }
  1977. }
  1978. else
  1979. {
  1980. st_synchronize();
  1981. homing_flag = false;
  1982. // Push the commands to the front of the message queue in the reverse order!
  1983. // There shall be always enough space reserved for these commands.
  1984. // enquecommand_front_P((PSTR("G80")));
  1985. goto case_G80;
  1986. }
  1987. #endif
  1988. if (farm_mode) { prusa_statistics(20); };
  1989. homing_flag = false;
  1990. SERIAL_ECHOPGM("G28, final "); print_world_coordinates();
  1991. SERIAL_ECHOPGM("G28, final "); print_physical_coordinates();
  1992. SERIAL_ECHOPGM("G28, final "); print_mesh_bed_leveling_table();
  1993. break;
  1994. }
  1995. #ifdef ENABLE_AUTO_BED_LEVELING
  1996. case 29: // G29 Detailed Z-Probe, probes the bed at 3 or more points.
  1997. {
  1998. #if Z_MIN_PIN == -1
  1999. #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."
  2000. #endif
  2001. // Prevent user from running a G29 without first homing in X and Y
  2002. if (! (axis_known_position[X_AXIS] && axis_known_position[Y_AXIS]) )
  2003. {
  2004. LCD_MESSAGERPGM(MSG_POSITION_UNKNOWN);
  2005. SERIAL_ECHO_START;
  2006. SERIAL_ECHOLNRPGM(MSG_POSITION_UNKNOWN);
  2007. break; // abort G29, since we don't know where we are
  2008. }
  2009. st_synchronize();
  2010. // make sure the bed_level_rotation_matrix is identity or the planner will get it incorectly
  2011. //vector_3 corrected_position = plan_get_position_mm();
  2012. //corrected_position.debug("position before G29");
  2013. plan_bed_level_matrix.set_to_identity();
  2014. vector_3 uncorrected_position = plan_get_position();
  2015. //uncorrected_position.debug("position durring G29");
  2016. current_position[X_AXIS] = uncorrected_position.x;
  2017. current_position[Y_AXIS] = uncorrected_position.y;
  2018. current_position[Z_AXIS] = uncorrected_position.z;
  2019. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  2020. setup_for_endstop_move();
  2021. feedrate = homing_feedrate[Z_AXIS];
  2022. #ifdef AUTO_BED_LEVELING_GRID
  2023. // probe at the points of a lattice grid
  2024. int xGridSpacing = (RIGHT_PROBE_BED_POSITION - LEFT_PROBE_BED_POSITION) / (AUTO_BED_LEVELING_GRID_POINTS-1);
  2025. int yGridSpacing = (BACK_PROBE_BED_POSITION - FRONT_PROBE_BED_POSITION) / (AUTO_BED_LEVELING_GRID_POINTS-1);
  2026. // solve the plane equation ax + by + d = z
  2027. // A is the matrix with rows [x y 1] for all the probed points
  2028. // B is the vector of the Z positions
  2029. // 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
  2030. // so Vx = -a Vy = -b Vz = 1 (we want the vector facing towards positive Z
  2031. // "A" matrix of the linear system of equations
  2032. double eqnAMatrix[AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS*3];
  2033. // "B" vector of Z points
  2034. double eqnBVector[AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS];
  2035. int probePointCounter = 0;
  2036. bool zig = true;
  2037. for (int yProbe=FRONT_PROBE_BED_POSITION; yProbe <= BACK_PROBE_BED_POSITION; yProbe += yGridSpacing)
  2038. {
  2039. int xProbe, xInc;
  2040. if (zig)
  2041. {
  2042. xProbe = LEFT_PROBE_BED_POSITION;
  2043. //xEnd = RIGHT_PROBE_BED_POSITION;
  2044. xInc = xGridSpacing;
  2045. zig = false;
  2046. } else // zag
  2047. {
  2048. xProbe = RIGHT_PROBE_BED_POSITION;
  2049. //xEnd = LEFT_PROBE_BED_POSITION;
  2050. xInc = -xGridSpacing;
  2051. zig = true;
  2052. }
  2053. for (int xCount=0; xCount < AUTO_BED_LEVELING_GRID_POINTS; xCount++)
  2054. {
  2055. float z_before;
  2056. if (probePointCounter == 0)
  2057. {
  2058. // raise before probing
  2059. z_before = Z_RAISE_BEFORE_PROBING;
  2060. } else
  2061. {
  2062. // raise extruder
  2063. z_before = current_position[Z_AXIS] + Z_RAISE_BETWEEN_PROBINGS;
  2064. }
  2065. float measured_z = probe_pt(xProbe, yProbe, z_before);
  2066. eqnBVector[probePointCounter] = measured_z;
  2067. eqnAMatrix[probePointCounter + 0*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = xProbe;
  2068. eqnAMatrix[probePointCounter + 1*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = yProbe;
  2069. eqnAMatrix[probePointCounter + 2*AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS] = 1;
  2070. probePointCounter++;
  2071. xProbe += xInc;
  2072. }
  2073. }
  2074. clean_up_after_endstop_move();
  2075. // solve lsq problem
  2076. double *plane_equation_coefficients = qr_solve(AUTO_BED_LEVELING_GRID_POINTS*AUTO_BED_LEVELING_GRID_POINTS, 3, eqnAMatrix, eqnBVector);
  2077. SERIAL_PROTOCOLPGM("Eqn coefficients: a: ");
  2078. SERIAL_PROTOCOL(plane_equation_coefficients[0]);
  2079. SERIAL_PROTOCOLPGM(" b: ");
  2080. SERIAL_PROTOCOL(plane_equation_coefficients[1]);
  2081. SERIAL_PROTOCOLPGM(" d: ");
  2082. SERIAL_PROTOCOLLN(plane_equation_coefficients[2]);
  2083. set_bed_level_equation_lsq(plane_equation_coefficients);
  2084. free(plane_equation_coefficients);
  2085. #else // AUTO_BED_LEVELING_GRID not defined
  2086. // Probe at 3 arbitrary points
  2087. // probe 1
  2088. float z_at_pt_1 = probe_pt(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, Z_RAISE_BEFORE_PROBING);
  2089. // probe 2
  2090. 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);
  2091. // probe 3
  2092. 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);
  2093. clean_up_after_endstop_move();
  2094. set_bed_level_equation_3pts(z_at_pt_1, z_at_pt_2, z_at_pt_3);
  2095. #endif // AUTO_BED_LEVELING_GRID
  2096. st_synchronize();
  2097. // The following code correct the Z height difference from z-probe position and hotend tip position.
  2098. // The Z height on homing is measured by Z-Probe, but the probe is quite far from the hotend.
  2099. // When the bed is uneven, this height must be corrected.
  2100. real_z = float(st_get_position(Z_AXIS))/axis_steps_per_unit[Z_AXIS]; //get the real Z (since the auto bed leveling is already correcting the plane)
  2101. x_tmp = current_position[X_AXIS] + X_PROBE_OFFSET_FROM_EXTRUDER;
  2102. y_tmp = current_position[Y_AXIS] + Y_PROBE_OFFSET_FROM_EXTRUDER;
  2103. z_tmp = current_position[Z_AXIS];
  2104. apply_rotation_xyz(plan_bed_level_matrix, x_tmp, y_tmp, z_tmp); //Apply the correction sending the probe offset
  2105. current_position[Z_AXIS] = z_tmp - real_z + current_position[Z_AXIS]; //The difference is added to current position and sent to planner.
  2106. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  2107. }
  2108. break;
  2109. #ifndef Z_PROBE_SLED
  2110. case 30: // G30 Single Z Probe
  2111. {
  2112. st_synchronize();
  2113. // TODO: make sure the bed_level_rotation_matrix is identity or the planner will get set incorectly
  2114. setup_for_endstop_move();
  2115. feedrate = homing_feedrate[Z_AXIS];
  2116. run_z_probe();
  2117. SERIAL_PROTOCOLPGM(MSG_BED);
  2118. SERIAL_PROTOCOLPGM(" X: ");
  2119. SERIAL_PROTOCOL(current_position[X_AXIS]);
  2120. SERIAL_PROTOCOLPGM(" Y: ");
  2121. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  2122. SERIAL_PROTOCOLPGM(" Z: ");
  2123. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  2124. SERIAL_PROTOCOLPGM("\n");
  2125. clean_up_after_endstop_move();
  2126. }
  2127. break;
  2128. #else
  2129. case 31: // dock the sled
  2130. dock_sled(true);
  2131. break;
  2132. case 32: // undock the sled
  2133. dock_sled(false);
  2134. break;
  2135. #endif // Z_PROBE_SLED
  2136. #endif // ENABLE_AUTO_BED_LEVELING
  2137. #ifdef MESH_BED_LEVELING
  2138. case 30: // G30 Single Z Probe
  2139. {
  2140. st_synchronize();
  2141. // TODO: make sure the bed_level_rotation_matrix is identity or the planner will get set incorectly
  2142. setup_for_endstop_move();
  2143. feedrate = homing_feedrate[Z_AXIS];
  2144. find_bed_induction_sensor_point_z(-10.f, 3);
  2145. SERIAL_PROTOCOLRPGM(MSG_BED);
  2146. SERIAL_PROTOCOLPGM(" X: ");
  2147. MYSERIAL.print(current_position[X_AXIS], 5);
  2148. SERIAL_PROTOCOLPGM(" Y: ");
  2149. MYSERIAL.print(current_position[Y_AXIS], 5);
  2150. SERIAL_PROTOCOLPGM(" Z: ");
  2151. MYSERIAL.print(current_position[Z_AXIS], 5);
  2152. SERIAL_PROTOCOLPGM("\n");
  2153. clean_up_after_endstop_move();
  2154. }
  2155. break;
  2156. case 75:
  2157. {
  2158. for (int i = 40; i <= 110; i++) {
  2159. MYSERIAL.print(i);
  2160. MYSERIAL.print(" ");
  2161. MYSERIAL.println(temp_comp_interpolation(i));// / axis_steps_per_unit[Z_AXIS]);
  2162. }
  2163. }
  2164. break;
  2165. case 76: //PINDA probe temperature calibration
  2166. {
  2167. #ifdef PINDA_THERMISTOR
  2168. if (true)
  2169. {
  2170. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  2171. // We don't know where we are! HOME!
  2172. // Push the commands to the front of the message queue in the reverse order!
  2173. // There shall be always enough space reserved for these commands.
  2174. repeatcommand_front(); // repeat G76 with all its parameters
  2175. enquecommand_front_P((PSTR("G28 W0")));
  2176. break;
  2177. }
  2178. SERIAL_ECHOLNPGM("PINDA probe calibration start");
  2179. float zero_z;
  2180. int z_shift = 0; //unit: steps
  2181. float start_temp = 5 * (int)(current_temperature_pinda / 5);
  2182. if (start_temp < 35) start_temp = 35;
  2183. if (start_temp < current_temperature_pinda) start_temp += 5;
  2184. SERIAL_ECHOPGM("start temperature: ");
  2185. MYSERIAL.println(start_temp);
  2186. // setTargetHotend(200, 0);
  2187. setTargetBed(50 + 10 * (start_temp - 30) / 5);
  2188. custom_message = true;
  2189. custom_message_type = 4;
  2190. custom_message_state = 1;
  2191. custom_message = MSG_TEMP_CALIBRATION;
  2192. current_position[X_AXIS] = PINDA_PREHEAT_X;
  2193. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  2194. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  2195. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  2196. st_synchronize();
  2197. while (current_temperature_pinda < start_temp)
  2198. {
  2199. delay_keep_alive(1000);
  2200. serialecho_temperatures();
  2201. }
  2202. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0); //invalidate temp. calibration in case that in will be aborted during the calibration process
  2203. current_position[Z_AXIS] = 5;
  2204. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  2205. current_position[X_AXIS] = pgm_read_float(bed_ref_points);
  2206. current_position[Y_AXIS] = pgm_read_float(bed_ref_points + 1);
  2207. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  2208. st_synchronize();
  2209. find_bed_induction_sensor_point_z(-1.f);
  2210. zero_z = current_position[Z_AXIS];
  2211. //current_position[Z_AXIS]
  2212. SERIAL_ECHOLNPGM("");
  2213. SERIAL_ECHOPGM("ZERO: ");
  2214. MYSERIAL.print(current_position[Z_AXIS]);
  2215. SERIAL_ECHOLNPGM("");
  2216. int i = -1; for (; i < 5; i++)
  2217. {
  2218. float temp = (40 + i * 5);
  2219. SERIAL_ECHOPGM("Step: ");
  2220. MYSERIAL.print(i + 2);
  2221. SERIAL_ECHOLNPGM("/6 (skipped)");
  2222. SERIAL_ECHOPGM("PINDA temperature: ");
  2223. MYSERIAL.print((40 + i*5));
  2224. SERIAL_ECHOPGM(" Z shift (mm):");
  2225. MYSERIAL.print(0);
  2226. SERIAL_ECHOLNPGM("");
  2227. if (i >= 0) EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + i * 2, &z_shift);
  2228. if (start_temp <= temp) break;
  2229. }
  2230. for (i++; i < 5; i++)
  2231. {
  2232. float temp = (40 + i * 5);
  2233. SERIAL_ECHOPGM("Step: ");
  2234. MYSERIAL.print(i + 2);
  2235. SERIAL_ECHOLNPGM("/6");
  2236. custom_message_state = i + 2;
  2237. setTargetBed(50 + 10 * (temp - 30) / 5);
  2238. // setTargetHotend(255, 0);
  2239. current_position[X_AXIS] = PINDA_PREHEAT_X;
  2240. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  2241. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  2242. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  2243. st_synchronize();
  2244. while (current_temperature_pinda < temp)
  2245. {
  2246. delay_keep_alive(1000);
  2247. serialecho_temperatures();
  2248. }
  2249. current_position[Z_AXIS] = 5;
  2250. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  2251. current_position[X_AXIS] = pgm_read_float(bed_ref_points);
  2252. current_position[Y_AXIS] = pgm_read_float(bed_ref_points + 1);
  2253. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  2254. st_synchronize();
  2255. find_bed_induction_sensor_point_z(-1.f);
  2256. z_shift = (int)((current_position[Z_AXIS] - zero_z)*axis_steps_per_unit[Z_AXIS]);
  2257. SERIAL_ECHOLNPGM("");
  2258. SERIAL_ECHOPGM("PINDA temperature: ");
  2259. MYSERIAL.print(current_temperature_pinda);
  2260. SERIAL_ECHOPGM(" Z shift (mm):");
  2261. MYSERIAL.print(current_position[Z_AXIS] - zero_z);
  2262. SERIAL_ECHOLNPGM("");
  2263. EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + i * 2, &z_shift);
  2264. }
  2265. custom_message_type = 0;
  2266. custom_message = false;
  2267. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  2268. SERIAL_ECHOLNPGM("Temperature calibration done. Continue with pressing the knob.");
  2269. disable_x();
  2270. disable_y();
  2271. disable_z();
  2272. disable_e0();
  2273. disable_e1();
  2274. disable_e2();
  2275. lcd_show_fullscreen_message_and_wait_P(MSG_TEMP_CALIBRATION_DONE);
  2276. lcd_update_enable(true);
  2277. lcd_update(2);
  2278. setTargetBed(0); //set bed target temperature back to 0
  2279. // setTargetHotend(0,0); //set hotend target temperature back to 0
  2280. break;
  2281. }
  2282. #endif //PINDA_THERMISTOR
  2283. setTargetBed(PINDA_MIN_T);
  2284. float zero_z;
  2285. int z_shift = 0; //unit: steps
  2286. int t_c; // temperature
  2287. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  2288. // We don't know where we are! HOME!
  2289. // Push the commands to the front of the message queue in the reverse order!
  2290. // There shall be always enough space reserved for these commands.
  2291. repeatcommand_front(); // repeat G76 with all its parameters
  2292. enquecommand_front_P((PSTR("G28 W0")));
  2293. break;
  2294. }
  2295. SERIAL_ECHOLNPGM("PINDA probe calibration start");
  2296. custom_message = true;
  2297. custom_message_type = 4;
  2298. custom_message_state = 1;
  2299. custom_message = MSG_TEMP_CALIBRATION;
  2300. current_position[X_AXIS] = PINDA_PREHEAT_X;
  2301. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  2302. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  2303. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  2304. st_synchronize();
  2305. while (abs(degBed() - PINDA_MIN_T) > 1) {
  2306. delay_keep_alive(1000);
  2307. serialecho_temperatures();
  2308. }
  2309. //enquecommand_P(PSTR("M190 S50"));
  2310. for (int i = 0; i < PINDA_HEAT_T; i++) {
  2311. delay_keep_alive(1000);
  2312. serialecho_temperatures();
  2313. }
  2314. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 0); //invalidate temp. calibration in case that in will be aborted during the calibration process
  2315. current_position[Z_AXIS] = 5;
  2316. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  2317. current_position[X_AXIS] = pgm_read_float(bed_ref_points);
  2318. current_position[Y_AXIS] = pgm_read_float(bed_ref_points + 1);
  2319. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  2320. st_synchronize();
  2321. find_bed_induction_sensor_point_z(-1.f);
  2322. zero_z = current_position[Z_AXIS];
  2323. //current_position[Z_AXIS]
  2324. SERIAL_ECHOLNPGM("");
  2325. SERIAL_ECHOPGM("ZERO: ");
  2326. MYSERIAL.print(current_position[Z_AXIS]);
  2327. SERIAL_ECHOLNPGM("");
  2328. for (int i = 0; i<5; i++) {
  2329. SERIAL_ECHOPGM("Step: ");
  2330. MYSERIAL.print(i+2);
  2331. SERIAL_ECHOLNPGM("/6");
  2332. custom_message_state = i + 2;
  2333. t_c = 60 + i * 10;
  2334. setTargetBed(t_c);
  2335. current_position[X_AXIS] = PINDA_PREHEAT_X;
  2336. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  2337. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  2338. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  2339. st_synchronize();
  2340. while (degBed() < t_c) {
  2341. delay_keep_alive(1000);
  2342. serialecho_temperatures();
  2343. }
  2344. for (int i = 0; i < PINDA_HEAT_T; i++) {
  2345. delay_keep_alive(1000);
  2346. serialecho_temperatures();
  2347. }
  2348. current_position[Z_AXIS] = 5;
  2349. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  2350. current_position[X_AXIS] = pgm_read_float(bed_ref_points);
  2351. current_position[Y_AXIS] = pgm_read_float(bed_ref_points + 1);
  2352. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  2353. st_synchronize();
  2354. find_bed_induction_sensor_point_z(-1.f);
  2355. z_shift = (int)((current_position[Z_AXIS] - zero_z)*axis_steps_per_unit[Z_AXIS]);
  2356. SERIAL_ECHOLNPGM("");
  2357. SERIAL_ECHOPGM("Temperature: ");
  2358. MYSERIAL.print(t_c);
  2359. SERIAL_ECHOPGM(" Z shift (mm):");
  2360. MYSERIAL.print(current_position[Z_AXIS] - zero_z);
  2361. SERIAL_ECHOLNPGM("");
  2362. EEPROM_save_B(EEPROM_PROBE_TEMP_SHIFT + i*2, &z_shift);
  2363. }
  2364. custom_message_type = 0;
  2365. custom_message = false;
  2366. eeprom_update_byte((uint8_t*)EEPROM_CALIBRATION_STATUS_PINDA, 1);
  2367. SERIAL_ECHOLNPGM("Temperature calibration done. Continue with pressing the knob.");
  2368. disable_x();
  2369. disable_y();
  2370. disable_z();
  2371. disable_e0();
  2372. disable_e1();
  2373. disable_e2();
  2374. setTargetBed(0); //set bed target temperature back to 0
  2375. lcd_show_fullscreen_message_and_wait_P(MSG_TEMP_CALIBRATION_DONE);
  2376. lcd_update_enable(true);
  2377. lcd_update(2);
  2378. }
  2379. break;
  2380. #ifdef DIS
  2381. case 77:
  2382. {
  2383. //G77 X200 Y150 XP100 YP15 XO10 Y015
  2384. //for 9 point mesh bed leveling G77 X203 Y196 XP3 YP3 XO0 YO0
  2385. //G77 X232 Y218 XP116 YP109 XO-11 YO0
  2386. float dimension_x = 40;
  2387. float dimension_y = 40;
  2388. int points_x = 40;
  2389. int points_y = 40;
  2390. float offset_x = 74;
  2391. float offset_y = 33;
  2392. if (code_seen('X')) dimension_x = code_value();
  2393. if (code_seen('Y')) dimension_y = code_value();
  2394. if (code_seen('XP')) points_x = code_value();
  2395. if (code_seen('YP')) points_y = code_value();
  2396. if (code_seen('XO')) offset_x = code_value();
  2397. if (code_seen('YO')) offset_y = code_value();
  2398. bed_analysis(dimension_x,dimension_y,points_x,points_y,offset_x,offset_y);
  2399. } break;
  2400. #endif
  2401. case 79: {
  2402. for (int i = 255; i > 0; i = i - 5) {
  2403. fanSpeed = i;
  2404. //delay_keep_alive(2000);
  2405. for (int j = 0; j < 100; j++) {
  2406. delay_keep_alive(100);
  2407. }
  2408. fan_speed[1];
  2409. MYSERIAL.print(i); SERIAL_ECHOPGM(": "); MYSERIAL.println(fan_speed[1]);
  2410. }
  2411. }break;
  2412. /**
  2413. * G80: Mesh-based Z probe, probes a grid and produces a
  2414. * mesh to compensate for variable bed height
  2415. *
  2416. * The S0 report the points as below
  2417. *
  2418. * +----> X-axis
  2419. * |
  2420. * |
  2421. * v Y-axis
  2422. *
  2423. */
  2424. case 80:
  2425. #ifdef MK1BP
  2426. break;
  2427. #endif //MK1BP
  2428. case_G80:
  2429. {
  2430. mesh_bed_leveling_flag = true;
  2431. int8_t verbosity_level = 0;
  2432. static bool run = false;
  2433. if (code_seen('V')) {
  2434. // Just 'V' without a number counts as V1.
  2435. char c = strchr_pointer[1];
  2436. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  2437. }
  2438. // Firstly check if we know where we are
  2439. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  2440. // We don't know where we are! HOME!
  2441. // Push the commands to the front of the message queue in the reverse order!
  2442. // There shall be always enough space reserved for these commands.
  2443. if (lcd_commands_type != LCD_COMMAND_STOP_PRINT) {
  2444. repeatcommand_front(); // repeat G80 with all its parameters
  2445. enquecommand_front_P((PSTR("G28 W0")));
  2446. }
  2447. else {
  2448. mesh_bed_leveling_flag = false;
  2449. }
  2450. break;
  2451. }
  2452. bool temp_comp_start = true;
  2453. #ifdef PINDA_THERMISTOR
  2454. temp_comp_start = false;
  2455. #endif //PINDA_THERMISTOR
  2456. if (temp_comp_start)
  2457. if (run == false && temp_cal_active == true && calibration_status_pinda() == true && target_temperature_bed >= 50) {
  2458. if (lcd_commands_type != LCD_COMMAND_STOP_PRINT) {
  2459. temp_compensation_start();
  2460. run = true;
  2461. repeatcommand_front(); // repeat G80 with all its parameters
  2462. enquecommand_front_P((PSTR("G28 W0")));
  2463. }
  2464. else {
  2465. mesh_bed_leveling_flag = false;
  2466. }
  2467. break;
  2468. }
  2469. run = false;
  2470. if (lcd_commands_type == LCD_COMMAND_STOP_PRINT) {
  2471. mesh_bed_leveling_flag = false;
  2472. break;
  2473. }
  2474. // Save custom message state, set a new custom message state to display: Calibrating point 9.
  2475. bool custom_message_old = custom_message;
  2476. unsigned int custom_message_type_old = custom_message_type;
  2477. unsigned int custom_message_state_old = custom_message_state;
  2478. custom_message = true;
  2479. custom_message_type = 1;
  2480. custom_message_state = (MESH_MEAS_NUM_X_POINTS * MESH_MEAS_NUM_Y_POINTS) + 10;
  2481. lcd_update(1);
  2482. mbl.reset(); //reset mesh bed leveling
  2483. // Reset baby stepping to zero, if the babystepping has already been loaded before. The babystepsTodo value will be
  2484. // consumed during the first movements following this statement.
  2485. babystep_undo();
  2486. // Cycle through all points and probe them
  2487. // First move up. During this first movement, the babystepping will be reverted.
  2488. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2489. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], homing_feedrate[Z_AXIS] / 60, active_extruder);
  2490. // The move to the first calibration point.
  2491. current_position[X_AXIS] = pgm_read_float(bed_ref_points);
  2492. current_position[Y_AXIS] = pgm_read_float(bed_ref_points + 1);
  2493. bool clamped = world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  2494. if (verbosity_level >= 1) {
  2495. clamped ? SERIAL_PROTOCOLPGM("First calibration point clamped.\n") : SERIAL_PROTOCOLPGM("No clamping for first calibration point.\n");
  2496. }
  2497. // mbl.get_meas_xy(0, 0, current_position[X_AXIS], current_position[Y_AXIS], false);
  2498. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], homing_feedrate[X_AXIS] / 30, active_extruder);
  2499. // Wait until the move is finished.
  2500. st_synchronize();
  2501. int mesh_point = 0; //index number of calibration point
  2502. int ix = 0;
  2503. int iy = 0;
  2504. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  2505. int Z_PROBE_FEEDRATE = homing_feedrate[Z_AXIS] / 60;
  2506. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  2507. 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)
  2508. if (verbosity_level >= 1) {
  2509. has_z ? SERIAL_PROTOCOLPGM("Z jitter data from Z cal. valid.\n") : SERIAL_PROTOCOLPGM("Z jitter data from Z cal. not valid.\n");
  2510. }
  2511. setup_for_endstop_move(false); //save feedrate and feedmultiply, sets feedmultiply to 100
  2512. const char *kill_message = NULL;
  2513. while (mesh_point != MESH_MEAS_NUM_X_POINTS * MESH_MEAS_NUM_Y_POINTS) {
  2514. if (verbosity_level >= 1) SERIAL_ECHOLNPGM("");
  2515. // Get coords of a measuring point.
  2516. ix = mesh_point % MESH_MEAS_NUM_X_POINTS; // from 0 to MESH_NUM_X_POINTS - 1
  2517. iy = mesh_point / MESH_MEAS_NUM_X_POINTS;
  2518. if (iy & 1) ix = (MESH_MEAS_NUM_X_POINTS - 1) - ix; // Zig zag
  2519. float z0 = 0.f;
  2520. if (has_z && mesh_point > 0) {
  2521. uint16_t z_offset_u = eeprom_read_word((uint16_t*)(EEPROM_BED_CALIBRATION_Z_JITTER + 2 * (ix + iy * 3 - 1)));
  2522. z0 = mbl.z_values[0][0] + *reinterpret_cast<int16_t*>(&z_offset_u) * 0.01;
  2523. //#if 0
  2524. if (verbosity_level >= 1) {
  2525. SERIAL_ECHOPGM("Bed leveling, point: ");
  2526. MYSERIAL.print(mesh_point);
  2527. SERIAL_ECHOPGM(", calibration z: ");
  2528. MYSERIAL.print(z0, 5);
  2529. SERIAL_ECHOLNPGM("");
  2530. }
  2531. //#endif
  2532. }
  2533. // Move Z up to MESH_HOME_Z_SEARCH.
  2534. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2535. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], Z_LIFT_FEEDRATE, active_extruder);
  2536. st_synchronize();
  2537. // Move to XY position of the sensor point.
  2538. current_position[X_AXIS] = pgm_read_float(bed_ref_points + 2 * mesh_point);
  2539. current_position[Y_AXIS] = pgm_read_float(bed_ref_points + 2 * mesh_point + 1);
  2540. world2machine_clamp(current_position[X_AXIS], current_position[Y_AXIS]);
  2541. if (verbosity_level >= 1) {
  2542. SERIAL_PROTOCOL(mesh_point);
  2543. clamped ? SERIAL_PROTOCOLPGM(": xy clamped.\n") : SERIAL_PROTOCOLPGM(": no xy clamping\n");
  2544. }
  2545. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], XY_AXIS_FEEDRATE, active_extruder);
  2546. st_synchronize();
  2547. // Go down until endstop is hit
  2548. const float Z_CALIBRATION_THRESHOLD = 1.f;
  2549. if (!find_bed_induction_sensor_point_z((has_z && mesh_point > 0) ? z0 - Z_CALIBRATION_THRESHOLD : -10.f)) { //if we have data from z calibration max allowed difference is 1mm for each point, if we dont have data max difference is 10mm from initial point
  2550. kill_message = MSG_BED_LEVELING_FAILED_POINT_LOW;
  2551. break;
  2552. }
  2553. if (MESH_HOME_Z_SEARCH - current_position[Z_AXIS] < 0.1f) {
  2554. kill_message = MSG_BED_LEVELING_FAILED_PROBE_DISCONNECTED;
  2555. break;
  2556. }
  2557. 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
  2558. kill_message = MSG_BED_LEVELING_FAILED_POINT_HIGH;
  2559. break;
  2560. }
  2561. if (verbosity_level >= 10) {
  2562. SERIAL_ECHOPGM("X: ");
  2563. MYSERIAL.print(current_position[X_AXIS], 5);
  2564. SERIAL_ECHOLNPGM("");
  2565. SERIAL_ECHOPGM("Y: ");
  2566. MYSERIAL.print(current_position[Y_AXIS], 5);
  2567. SERIAL_PROTOCOLPGM("\n");
  2568. }
  2569. float offset_z = 0;
  2570. #ifdef PINDA_THERMISTOR
  2571. offset_z = temp_compensation_pinda_thermistor_offset();
  2572. #endif //PINDA_THERMISTOR
  2573. if (verbosity_level >= 1) {
  2574. SERIAL_ECHOPGM("mesh bed leveling: ");
  2575. MYSERIAL.print(current_position[Z_AXIS], 5);
  2576. SERIAL_ECHOPGM(" offset: ");
  2577. MYSERIAL.print(offset_z, 5);
  2578. SERIAL_ECHOLNPGM("");
  2579. }
  2580. mbl.set_z(ix, iy, current_position[Z_AXIS] - offset_z); //store measured z values z_values[iy][ix] = z - offset_z;
  2581. custom_message_state--;
  2582. mesh_point++;
  2583. lcd_update(1);
  2584. }
  2585. if (verbosity_level >= 20) SERIAL_ECHOLNPGM("Mesh bed leveling while loop finished.");
  2586. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  2587. if (verbosity_level >= 20) {
  2588. SERIAL_ECHOLNPGM("MESH_HOME_Z_SEARCH: ");
  2589. MYSERIAL.print(current_position[Z_AXIS], 5);
  2590. }
  2591. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], Z_LIFT_FEEDRATE, active_extruder);
  2592. st_synchronize();
  2593. if (mesh_point != MESH_MEAS_NUM_X_POINTS * MESH_MEAS_NUM_Y_POINTS) {
  2594. kill(kill_message);
  2595. SERIAL_ECHOLNPGM("killed");
  2596. }
  2597. clean_up_after_endstop_move();
  2598. SERIAL_ECHOLNPGM("clean up finished ");
  2599. bool apply_temp_comp = true;
  2600. #ifdef PINDA_THERMISTOR
  2601. apply_temp_comp = false;
  2602. #endif
  2603. if (apply_temp_comp)
  2604. if(temp_cal_active == true && calibration_status_pinda() == true) temp_compensation_apply(); //apply PINDA temperature compensation
  2605. babystep_apply(); // Apply Z height correction aka baby stepping before mesh bed leveing gets activated.
  2606. SERIAL_ECHOLNPGM("babystep applied");
  2607. bool eeprom_bed_correction_valid = eeprom_read_byte((unsigned char*)EEPROM_BED_CORRECTION_VALID) == 1;
  2608. if (verbosity_level >= 1) {
  2609. eeprom_bed_correction_valid ? SERIAL_PROTOCOLPGM("Bed correction data valid\n") : SERIAL_PROTOCOLPGM("Bed correction data not valid\n");
  2610. }
  2611. for (uint8_t i = 0; i < 4; ++i) {
  2612. unsigned char codes[4] = { 'L', 'R', 'F', 'B' };
  2613. long correction = 0;
  2614. if (code_seen(codes[i]))
  2615. correction = code_value_long();
  2616. else if (eeprom_bed_correction_valid) {
  2617. unsigned char *addr = (i < 2) ?
  2618. ((i == 0) ? (unsigned char*)EEPROM_BED_CORRECTION_LEFT : (unsigned char*)EEPROM_BED_CORRECTION_RIGHT) :
  2619. ((i == 2) ? (unsigned char*)EEPROM_BED_CORRECTION_FRONT : (unsigned char*)EEPROM_BED_CORRECTION_REAR);
  2620. correction = eeprom_read_int8(addr);
  2621. }
  2622. if (correction == 0)
  2623. continue;
  2624. float offset = float(correction) * 0.001f;
  2625. if (fabs(offset) > 0.101f) {
  2626. SERIAL_ERROR_START;
  2627. SERIAL_ECHOPGM("Excessive bed leveling correction: ");
  2628. SERIAL_ECHO(offset);
  2629. SERIAL_ECHOLNPGM(" microns");
  2630. }
  2631. else {
  2632. switch (i) {
  2633. case 0:
  2634. for (uint8_t row = 0; row < 3; ++row) {
  2635. mbl.z_values[row][1] += 0.5f * offset;
  2636. mbl.z_values[row][0] += offset;
  2637. }
  2638. break;
  2639. case 1:
  2640. for (uint8_t row = 0; row < 3; ++row) {
  2641. mbl.z_values[row][1] += 0.5f * offset;
  2642. mbl.z_values[row][2] += offset;
  2643. }
  2644. break;
  2645. case 2:
  2646. for (uint8_t col = 0; col < 3; ++col) {
  2647. mbl.z_values[1][col] += 0.5f * offset;
  2648. mbl.z_values[0][col] += offset;
  2649. }
  2650. break;
  2651. case 3:
  2652. for (uint8_t col = 0; col < 3; ++col) {
  2653. mbl.z_values[1][col] += 0.5f * offset;
  2654. mbl.z_values[2][col] += offset;
  2655. }
  2656. break;
  2657. }
  2658. }
  2659. }
  2660. SERIAL_ECHOLNPGM("Bed leveling correction finished");
  2661. mbl.upsample_3x3(); //bilinear interpolation from 3x3 to 7x7 points while using the same array z_values[iy][ix] for storing (just coppying measured data to new destination and interpolating between them)
  2662. SERIAL_ECHOLNPGM("Upsample finished");
  2663. mbl.active = 1; //activate mesh bed leveling
  2664. SERIAL_ECHOLNPGM("Mesh bed leveling activated");
  2665. go_home_with_z_lift();
  2666. SERIAL_ECHOLNPGM("Go home finished");
  2667. //unretract (after PINDA preheat retraction)
  2668. if (degHotend(active_extruder) > EXTRUDE_MINTEMP && temp_cal_active == true && calibration_status_pinda() == true && target_temperature_bed >= 50) {
  2669. current_position[E_AXIS] += DEFAULT_RETRACTION;
  2670. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 400, active_extruder);
  2671. }
  2672. // Restore custom message state
  2673. custom_message = custom_message_old;
  2674. custom_message_type = custom_message_type_old;
  2675. custom_message_state = custom_message_state_old;
  2676. mesh_bed_leveling_flag = false;
  2677. mesh_bed_run_from_menu = false;
  2678. lcd_update(2);
  2679. }
  2680. break;
  2681. /**
  2682. * G81: Print mesh bed leveling status and bed profile if activated
  2683. */
  2684. case 81:
  2685. if (mbl.active) {
  2686. SERIAL_PROTOCOLPGM("Num X,Y: ");
  2687. SERIAL_PROTOCOL(MESH_NUM_X_POINTS);
  2688. SERIAL_PROTOCOLPGM(",");
  2689. SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  2690. SERIAL_PROTOCOLPGM("\nZ search height: ");
  2691. SERIAL_PROTOCOL(MESH_HOME_Z_SEARCH);
  2692. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  2693. for (int y = MESH_NUM_Y_POINTS-1; y >= 0; y--) {
  2694. for (int x = 0; x < MESH_NUM_X_POINTS; x++) {
  2695. SERIAL_PROTOCOLPGM(" ");
  2696. SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5);
  2697. }
  2698. SERIAL_PROTOCOLPGM("\n");
  2699. }
  2700. }
  2701. else
  2702. SERIAL_PROTOCOLLNPGM("Mesh bed leveling not active.");
  2703. break;
  2704. #if 0
  2705. /**
  2706. * G82: Single Z probe at current location
  2707. *
  2708. * WARNING! USE WITH CAUTION! If you'll try to probe where is no leveling pad, nasty things can happen!
  2709. *
  2710. */
  2711. case 82:
  2712. SERIAL_PROTOCOLLNPGM("Finding bed ");
  2713. setup_for_endstop_move();
  2714. find_bed_induction_sensor_point_z();
  2715. clean_up_after_endstop_move();
  2716. SERIAL_PROTOCOLPGM("Bed found at: ");
  2717. SERIAL_PROTOCOL_F(current_position[Z_AXIS], 5);
  2718. SERIAL_PROTOCOLPGM("\n");
  2719. break;
  2720. /**
  2721. * G83: Prusa3D specific: Babystep in Z and store to EEPROM
  2722. */
  2723. case 83:
  2724. {
  2725. int babystepz = code_seen('S') ? code_value() : 0;
  2726. int BabyPosition = code_seen('P') ? code_value() : 0;
  2727. if (babystepz != 0) {
  2728. //FIXME Vojtech: What shall be the index of the axis Z: 3 or 4?
  2729. // Is the axis indexed starting with zero or one?
  2730. if (BabyPosition > 4) {
  2731. SERIAL_PROTOCOLLNPGM("Index out of bounds");
  2732. }else{
  2733. // Save it to the eeprom
  2734. babystepLoadZ = babystepz;
  2735. EEPROM_save_B(EEPROM_BABYSTEP_Z0+(BabyPosition*2),&babystepLoadZ);
  2736. // adjust the Z
  2737. babystepsTodoZadd(babystepLoadZ);
  2738. }
  2739. }
  2740. }
  2741. break;
  2742. /**
  2743. * G84: Prusa3D specific: UNDO Babystep Z (move Z axis back)
  2744. */
  2745. case 84:
  2746. babystepsTodoZsubtract(babystepLoadZ);
  2747. // babystepLoadZ = 0;
  2748. break;
  2749. /**
  2750. * G85: Prusa3D specific: Pick best babystep
  2751. */
  2752. case 85:
  2753. lcd_pick_babystep();
  2754. break;
  2755. #endif
  2756. /**
  2757. * G86: Prusa3D specific: Disable babystep correction after home.
  2758. * This G-code will be performed at the start of a calibration script.
  2759. */
  2760. case 86:
  2761. calibration_status_store(CALIBRATION_STATUS_LIVE_ADJUST);
  2762. break;
  2763. /**
  2764. * G87: Prusa3D specific: Enable babystep correction after home
  2765. * This G-code will be performed at the end of a calibration script.
  2766. */
  2767. case 87:
  2768. calibration_status_store(CALIBRATION_STATUS_CALIBRATED);
  2769. break;
  2770. /**
  2771. * G88: Prusa3D specific: Don't know what it is for, it is in V2Calibration.gcode
  2772. */
  2773. case 88:
  2774. break;
  2775. #endif // ENABLE_MESH_BED_LEVELING
  2776. case 90: // G90
  2777. relative_mode = false;
  2778. break;
  2779. case 91: // G91
  2780. relative_mode = true;
  2781. break;
  2782. case 92: // G92
  2783. if(!code_seen(axis_codes[E_AXIS]))
  2784. st_synchronize();
  2785. for(int8_t i=0; i < NUM_AXIS; i++) {
  2786. if(code_seen(axis_codes[i])) {
  2787. if(i == E_AXIS) {
  2788. current_position[i] = code_value();
  2789. plan_set_e_position(current_position[E_AXIS]);
  2790. }
  2791. else {
  2792. current_position[i] = code_value()+add_homing[i];
  2793. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  2794. }
  2795. }
  2796. }
  2797. break;
  2798. case 98: //activate farm mode
  2799. farm_mode = 1;
  2800. PingTime = millis();
  2801. eeprom_update_byte((unsigned char *)EEPROM_FARM_MODE, farm_mode);
  2802. break;
  2803. case 99: //deactivate farm mode
  2804. farm_mode = 0;
  2805. lcd_printer_connected();
  2806. eeprom_update_byte((unsigned char *)EEPROM_FARM_MODE, farm_mode);
  2807. lcd_update(2);
  2808. break;
  2809. }
  2810. } // end if(code_seen('G'))
  2811. else if(code_seen('M'))
  2812. {
  2813. int index;
  2814. for (index = 1; *(strchr_pointer + index) == ' ' || *(strchr_pointer + index) == '\t'; index++);
  2815. /*for (++strchr_pointer; *strchr_pointer == ' ' || *strchr_pointer == '\t'; ++strchr_pointer);*/
  2816. if (*(strchr_pointer+index) < '0' || *(strchr_pointer+index) > '9') {
  2817. SERIAL_ECHOLNPGM("Invalid M code");
  2818. } else
  2819. switch((int)code_value())
  2820. {
  2821. #ifdef ULTIPANEL
  2822. case 0: // M0 - Unconditional stop - Wait for user button press on LCD
  2823. case 1: // M1 - Conditional stop - Wait for user button press on LCD
  2824. {
  2825. char *src = strchr_pointer + 2;
  2826. codenum = 0;
  2827. bool hasP = false, hasS = false;
  2828. if (code_seen('P')) {
  2829. codenum = code_value(); // milliseconds to wait
  2830. hasP = codenum > 0;
  2831. }
  2832. if (code_seen('S')) {
  2833. codenum = code_value() * 1000; // seconds to wait
  2834. hasS = codenum > 0;
  2835. }
  2836. starpos = strchr(src, '*');
  2837. if (starpos != NULL) *(starpos) = '\0';
  2838. while (*src == ' ') ++src;
  2839. if (!hasP && !hasS && *src != '\0') {
  2840. lcd_setstatus(src);
  2841. } else {
  2842. LCD_MESSAGERPGM(MSG_USERWAIT);
  2843. }
  2844. lcd_ignore_click(); //call lcd_ignore_click aslo for else ???
  2845. st_synchronize();
  2846. previous_millis_cmd = millis();
  2847. if (codenum > 0){
  2848. codenum += millis(); // keep track of when we started waiting
  2849. while(millis() < codenum && !lcd_clicked()){
  2850. manage_heater();
  2851. manage_inactivity(true);
  2852. lcd_update();
  2853. }
  2854. lcd_ignore_click(false);
  2855. }else{
  2856. if (!lcd_detected())
  2857. break;
  2858. while(!lcd_clicked()){
  2859. manage_heater();
  2860. manage_inactivity(true);
  2861. lcd_update();
  2862. }
  2863. }
  2864. if (IS_SD_PRINTING)
  2865. LCD_MESSAGERPGM(MSG_RESUMING);
  2866. else
  2867. LCD_MESSAGERPGM(WELCOME_MSG);
  2868. }
  2869. break;
  2870. #endif
  2871. case 17:
  2872. LCD_MESSAGERPGM(MSG_NO_MOVE);
  2873. enable_x();
  2874. enable_y();
  2875. enable_z();
  2876. enable_e0();
  2877. enable_e1();
  2878. enable_e2();
  2879. break;
  2880. #ifdef SDSUPPORT
  2881. case 20: // M20 - list SD card
  2882. SERIAL_PROTOCOLLNRPGM(MSG_BEGIN_FILE_LIST);
  2883. card.ls();
  2884. SERIAL_PROTOCOLLNRPGM(MSG_END_FILE_LIST);
  2885. break;
  2886. case 21: // M21 - init SD card
  2887. card.initsd();
  2888. break;
  2889. case 22: //M22 - release SD card
  2890. card.release();
  2891. break;
  2892. case 23: //M23 - Select file
  2893. starpos = (strchr(strchr_pointer + 4,'*'));
  2894. if(starpos!=NULL)
  2895. *(starpos)='\0';
  2896. card.openFile(strchr_pointer + 4,true);
  2897. break;
  2898. case 24: //M24 - Start SD print
  2899. card.startFileprint();
  2900. starttime=millis();
  2901. break;
  2902. case 25: //M25 - Pause SD print
  2903. card.pauseSDPrint();
  2904. break;
  2905. case 26: //M26 - Set SD index
  2906. if(card.cardOK && code_seen('S')) {
  2907. card.setIndex(code_value_long());
  2908. }
  2909. break;
  2910. case 27: //M27 - Get SD status
  2911. card.getStatus();
  2912. break;
  2913. case 28: //M28 - Start SD write
  2914. starpos = (strchr(strchr_pointer + 4,'*'));
  2915. if(starpos != NULL){
  2916. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  2917. strchr_pointer = strchr(npos,' ') + 1;
  2918. *(starpos) = '\0';
  2919. }
  2920. card.openFile(strchr_pointer+4,false);
  2921. break;
  2922. case 29: //M29 - Stop SD write
  2923. //processed in write to file routine above
  2924. //card,saving = false;
  2925. break;
  2926. case 30: //M30 <filename> Delete File
  2927. if (card.cardOK){
  2928. card.closefile();
  2929. starpos = (strchr(strchr_pointer + 4,'*'));
  2930. if(starpos != NULL){
  2931. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  2932. strchr_pointer = strchr(npos,' ') + 1;
  2933. *(starpos) = '\0';
  2934. }
  2935. card.removeFile(strchr_pointer + 4);
  2936. }
  2937. break;
  2938. case 32: //M32 - Select file and start SD print
  2939. {
  2940. if(card.sdprinting) {
  2941. st_synchronize();
  2942. }
  2943. starpos = (strchr(strchr_pointer + 4,'*'));
  2944. char* namestartpos = (strchr(strchr_pointer + 4,'!')); //find ! to indicate filename string start.
  2945. if(namestartpos==NULL)
  2946. {
  2947. namestartpos=strchr_pointer + 4; //default name position, 4 letters after the M
  2948. }
  2949. else
  2950. namestartpos++; //to skip the '!'
  2951. if(starpos!=NULL)
  2952. *(starpos)='\0';
  2953. bool call_procedure=(code_seen('P'));
  2954. if(strchr_pointer>namestartpos)
  2955. call_procedure=false; //false alert, 'P' found within filename
  2956. if( card.cardOK )
  2957. {
  2958. card.openFile(namestartpos,true,!call_procedure);
  2959. if(code_seen('S'))
  2960. if(strchr_pointer<namestartpos) //only if "S" is occuring _before_ the filename
  2961. card.setIndex(code_value_long());
  2962. card.startFileprint();
  2963. if(!call_procedure)
  2964. starttime=millis(); //procedure calls count as normal print time.
  2965. }
  2966. } break;
  2967. case 928: //M928 - Start SD write
  2968. starpos = (strchr(strchr_pointer + 5,'*'));
  2969. if(starpos != NULL){
  2970. char* npos = strchr(CMDBUFFER_CURRENT_STRING, 'N');
  2971. strchr_pointer = strchr(npos,' ') + 1;
  2972. *(starpos) = '\0';
  2973. }
  2974. card.openLogFile(strchr_pointer+5);
  2975. break;
  2976. #endif //SDSUPPORT
  2977. case 31: //M31 take time since the start of the SD print or an M109 command
  2978. {
  2979. stoptime=millis();
  2980. char time[30];
  2981. unsigned long t=(stoptime-starttime)/1000;
  2982. int sec,min;
  2983. min=t/60;
  2984. sec=t%60;
  2985. sprintf_P(time, PSTR("%i min, %i sec"), min, sec);
  2986. SERIAL_ECHO_START;
  2987. SERIAL_ECHOLN(time);
  2988. lcd_setstatus(time);
  2989. autotempShutdown();
  2990. }
  2991. break;
  2992. case 42: //M42 -Change pin status via gcode
  2993. if (code_seen('S'))
  2994. {
  2995. int pin_status = code_value();
  2996. int pin_number = LED_PIN;
  2997. if (code_seen('P') && pin_status >= 0 && pin_status <= 255)
  2998. pin_number = code_value();
  2999. for(int8_t i = 0; i < (int8_t)(sizeof(sensitive_pins)/sizeof(int)); i++)
  3000. {
  3001. if (sensitive_pins[i] == pin_number)
  3002. {
  3003. pin_number = -1;
  3004. break;
  3005. }
  3006. }
  3007. #if defined(FAN_PIN) && FAN_PIN > -1
  3008. if (pin_number == FAN_PIN)
  3009. fanSpeed = pin_status;
  3010. #endif
  3011. if (pin_number > -1)
  3012. {
  3013. pinMode(pin_number, OUTPUT);
  3014. digitalWrite(pin_number, pin_status);
  3015. analogWrite(pin_number, pin_status);
  3016. }
  3017. }
  3018. break;
  3019. case 44: // M44: Prusa3D: Reset the bed skew and offset calibration.
  3020. // Reset the baby step value and the baby step applied flag.
  3021. calibration_status_store(CALIBRATION_STATUS_ASSEMBLED);
  3022. eeprom_update_word((uint16_t*)EEPROM_BABYSTEP_Z, 0);
  3023. // Reset the skew and offset in both RAM and EEPROM.
  3024. reset_bed_offset_and_skew();
  3025. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  3026. // the planner will not perform any adjustments in the XY plane.
  3027. // Wait for the motors to stop and update the current position with the absolute values.
  3028. world2machine_revert_to_uncorrected();
  3029. break;
  3030. case 45: // M45: Prusa3D: bed skew and offset with manual Z up
  3031. {
  3032. // Only Z calibration?
  3033. bool onlyZ = code_seen('Z');
  3034. if (!onlyZ) {
  3035. setTargetBed(0);
  3036. setTargetHotend(0, 0);
  3037. setTargetHotend(0, 1);
  3038. setTargetHotend(0, 2);
  3039. adjust_bed_reset(); //reset bed level correction
  3040. }
  3041. // Disable the default update procedure of the display. We will do a modal dialog.
  3042. lcd_update_enable(false);
  3043. // Let the planner use the uncorrected coordinates.
  3044. mbl.reset();
  3045. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  3046. // the planner will not perform any adjustments in the XY plane.
  3047. // Wait for the motors to stop and update the current position with the absolute values.
  3048. world2machine_revert_to_uncorrected();
  3049. // Reset the baby step value applied without moving the axes.
  3050. babystep_reset();
  3051. // Mark all axes as in a need for homing.
  3052. memset(axis_known_position, 0, sizeof(axis_known_position));
  3053. // Home in the XY plane.
  3054. //set_destination_to_current();
  3055. setup_for_endstop_move();
  3056. lcd_display_message_fullscreen_P(MSG_AUTO_HOME);
  3057. home_xy();
  3058. // Let the user move the Z axes up to the end stoppers.
  3059. #ifdef TMC2130
  3060. if (calibrate_z_auto()) {
  3061. #else //TMC2130
  3062. if (lcd_calibrate_z_end_stop_manual( onlyZ )) {
  3063. #endif //TMC2130
  3064. refresh_cmd_timeout();
  3065. if (((degHotend(0) > MAX_HOTEND_TEMP_CALIBRATION) || (degBed() > MAX_BED_TEMP_CALIBRATION)) && (!onlyZ)) {
  3066. lcd_wait_for_cool_down();
  3067. lcd_show_fullscreen_message_and_wait_P(MSG_PAPER);
  3068. lcd_display_message_fullscreen_P(MSG_FIND_BED_OFFSET_AND_SKEW_LINE1);
  3069. lcd_implementation_print_at(0, 2, 1);
  3070. lcd_printPGM(MSG_FIND_BED_OFFSET_AND_SKEW_LINE2);
  3071. }
  3072. // Move the print head close to the bed.
  3073. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  3074. 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);
  3075. st_synchronize();
  3076. //#ifdef TMC2130
  3077. // tmc2130_home_enter(X_AXIS_MASK | Y_AXIS_MASK);
  3078. //#endif
  3079. int8_t verbosity_level = 0;
  3080. if (code_seen('V')) {
  3081. // Just 'V' without a number counts as V1.
  3082. char c = strchr_pointer[1];
  3083. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  3084. }
  3085. if (onlyZ) {
  3086. clean_up_after_endstop_move();
  3087. // Z only calibration.
  3088. // Load the machine correction matrix
  3089. world2machine_initialize();
  3090. // and correct the current_position to match the transformed coordinate system.
  3091. world2machine_update_current();
  3092. //FIXME
  3093. bool result = sample_mesh_and_store_reference();
  3094. if (result) {
  3095. if (calibration_status() == CALIBRATION_STATUS_Z_CALIBRATION)
  3096. // Shipped, the nozzle height has been set already. The user can start printing now.
  3097. calibration_status_store(CALIBRATION_STATUS_CALIBRATED);
  3098. // babystep_apply();
  3099. }
  3100. } else {
  3101. // Reset the baby step value and the baby step applied flag.
  3102. calibration_status_store(CALIBRATION_STATUS_ASSEMBLED);
  3103. eeprom_update_word((uint16_t*)EEPROM_BABYSTEP_Z, 0);
  3104. // Complete XYZ calibration.
  3105. uint8_t point_too_far_mask = 0;
  3106. BedSkewOffsetDetectionResultType result = find_bed_offset_and_skew(verbosity_level, point_too_far_mask);
  3107. clean_up_after_endstop_move();
  3108. // Print head up.
  3109. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  3110. 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);
  3111. st_synchronize();
  3112. if (result >= 0) {
  3113. point_too_far_mask = 0;
  3114. // Second half: The fine adjustment.
  3115. // Let the planner use the uncorrected coordinates.
  3116. mbl.reset();
  3117. world2machine_reset();
  3118. // Home in the XY plane.
  3119. setup_for_endstop_move();
  3120. home_xy();
  3121. result = improve_bed_offset_and_skew(1, verbosity_level, point_too_far_mask);
  3122. clean_up_after_endstop_move();
  3123. // Print head up.
  3124. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  3125. 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);
  3126. st_synchronize();
  3127. // if (result >= 0) babystep_apply();
  3128. }
  3129. lcd_bed_calibration_show_result(result, point_too_far_mask);
  3130. if (result >= 0) {
  3131. // Calibration valid, the machine should be able to print. Advise the user to run the V2Calibration.gcode.
  3132. calibration_status_store(CALIBRATION_STATUS_LIVE_ADJUST);
  3133. lcd_show_fullscreen_message_and_wait_P(MSG_BABYSTEP_Z_NOT_SET);
  3134. }
  3135. }
  3136. #ifdef TMC2130
  3137. tmc2130_home_exit();
  3138. #endif
  3139. } else {
  3140. // Timeouted.
  3141. }
  3142. lcd_update_enable(true);
  3143. break;
  3144. }
  3145. /*
  3146. case 46:
  3147. {
  3148. // M46: Prusa3D: Show the assigned IP address.
  3149. uint8_t ip[4];
  3150. bool hasIP = card.ToshibaFlashAir_GetIP(ip);
  3151. if (hasIP) {
  3152. SERIAL_ECHOPGM("Toshiba FlashAir current IP: ");
  3153. SERIAL_ECHO(int(ip[0]));
  3154. SERIAL_ECHOPGM(".");
  3155. SERIAL_ECHO(int(ip[1]));
  3156. SERIAL_ECHOPGM(".");
  3157. SERIAL_ECHO(int(ip[2]));
  3158. SERIAL_ECHOPGM(".");
  3159. SERIAL_ECHO(int(ip[3]));
  3160. SERIAL_ECHOLNPGM("");
  3161. } else {
  3162. SERIAL_ECHOLNPGM("Toshiba FlashAir GetIP failed");
  3163. }
  3164. break;
  3165. }
  3166. */
  3167. case 47:
  3168. // M47: Prusa3D: Show end stops dialog on the display.
  3169. lcd_diag_show_end_stops();
  3170. break;
  3171. #if 0
  3172. case 48: // M48: scan the bed induction sensor points, print the sensor trigger coordinates to the serial line for visualization on the PC.
  3173. {
  3174. // Disable the default update procedure of the display. We will do a modal dialog.
  3175. lcd_update_enable(false);
  3176. // Let the planner use the uncorrected coordinates.
  3177. mbl.reset();
  3178. // Reset world2machine_rotation_and_skew and world2machine_shift, therefore
  3179. // the planner will not perform any adjustments in the XY plane.
  3180. // Wait for the motors to stop and update the current position with the absolute values.
  3181. world2machine_revert_to_uncorrected();
  3182. // Move the print head close to the bed.
  3183. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  3184. 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);
  3185. st_synchronize();
  3186. // Home in the XY plane.
  3187. set_destination_to_current();
  3188. setup_for_endstop_move();
  3189. home_xy();
  3190. int8_t verbosity_level = 0;
  3191. if (code_seen('V')) {
  3192. // Just 'V' without a number counts as V1.
  3193. char c = strchr_pointer[1];
  3194. verbosity_level = (c == ' ' || c == '\t' || c == 0) ? 1 : code_value_short();
  3195. }
  3196. bool success = scan_bed_induction_points(verbosity_level);
  3197. clean_up_after_endstop_move();
  3198. // Print head up.
  3199. current_position[Z_AXIS] = MESH_HOME_Z_SEARCH;
  3200. 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);
  3201. st_synchronize();
  3202. lcd_update_enable(true);
  3203. break;
  3204. }
  3205. #endif
  3206. // M48 Z-Probe repeatability measurement function.
  3207. //
  3208. // Usage: M48 <n #_samples> <X X_position_for_samples> <Y Y_position_for_samples> <V Verbose_Level> <L legs_of_movement_prior_to_doing_probe>
  3209. //
  3210. // This function assumes the bed has been homed. Specificaly, that a G28 command
  3211. // as been issued prior to invoking the M48 Z-Probe repeatability measurement function.
  3212. // Any information generated by a prior G29 Bed leveling command will be lost and need to be
  3213. // regenerated.
  3214. //
  3215. // The number of samples will default to 10 if not specified. You can use upper or lower case
  3216. // letters for any of the options EXCEPT n. n must be in lower case because Marlin uses a capital
  3217. // N for its communication protocol and will get horribly confused if you send it a capital N.
  3218. //
  3219. #ifdef ENABLE_AUTO_BED_LEVELING
  3220. #ifdef Z_PROBE_REPEATABILITY_TEST
  3221. case 48: // M48 Z-Probe repeatability
  3222. {
  3223. #if Z_MIN_PIN == -1
  3224. #error "You must have a Z_MIN endstop in order to enable calculation of Z-Probe repeatability."
  3225. #endif
  3226. double sum=0.0;
  3227. double mean=0.0;
  3228. double sigma=0.0;
  3229. double sample_set[50];
  3230. int verbose_level=1, n=0, j, n_samples = 10, n_legs=0;
  3231. double X_current, Y_current, Z_current;
  3232. double X_probe_location, Y_probe_location, Z_start_location, ext_position;
  3233. if (code_seen('V') || code_seen('v')) {
  3234. verbose_level = code_value();
  3235. if (verbose_level<0 || verbose_level>4 ) {
  3236. SERIAL_PROTOCOLPGM("?Verbose Level not plausable.\n");
  3237. goto Sigma_Exit;
  3238. }
  3239. }
  3240. if (verbose_level > 0) {
  3241. SERIAL_PROTOCOLPGM("M48 Z-Probe Repeatability test. Version 2.00\n");
  3242. SERIAL_PROTOCOLPGM("Full support at: http://3dprintboard.com/forum.php\n");
  3243. }
  3244. if (code_seen('n')) {
  3245. n_samples = code_value();
  3246. if (n_samples<4 || n_samples>50 ) {
  3247. SERIAL_PROTOCOLPGM("?Specified sample size not plausable.\n");
  3248. goto Sigma_Exit;
  3249. }
  3250. }
  3251. X_current = X_probe_location = st_get_position_mm(X_AXIS);
  3252. Y_current = Y_probe_location = st_get_position_mm(Y_AXIS);
  3253. Z_current = st_get_position_mm(Z_AXIS);
  3254. Z_start_location = st_get_position_mm(Z_AXIS) + Z_RAISE_BEFORE_PROBING;
  3255. ext_position = st_get_position_mm(E_AXIS);
  3256. if (code_seen('X') || code_seen('x') ) {
  3257. X_probe_location = code_value() - X_PROBE_OFFSET_FROM_EXTRUDER;
  3258. if (X_probe_location<X_MIN_POS || X_probe_location>X_MAX_POS ) {
  3259. SERIAL_PROTOCOLPGM("?Specified X position out of range.\n");
  3260. goto Sigma_Exit;
  3261. }
  3262. }
  3263. if (code_seen('Y') || code_seen('y') ) {
  3264. Y_probe_location = code_value() - Y_PROBE_OFFSET_FROM_EXTRUDER;
  3265. if (Y_probe_location<Y_MIN_POS || Y_probe_location>Y_MAX_POS ) {
  3266. SERIAL_PROTOCOLPGM("?Specified Y position out of range.\n");
  3267. goto Sigma_Exit;
  3268. }
  3269. }
  3270. if (code_seen('L') || code_seen('l') ) {
  3271. n_legs = code_value();
  3272. if ( n_legs==1 )
  3273. n_legs = 2;
  3274. if ( n_legs<0 || n_legs>15 ) {
  3275. SERIAL_PROTOCOLPGM("?Specified number of legs in movement not plausable.\n");
  3276. goto Sigma_Exit;
  3277. }
  3278. }
  3279. //
  3280. // Do all the preliminary setup work. First raise the probe.
  3281. //
  3282. st_synchronize();
  3283. plan_bed_level_matrix.set_to_identity();
  3284. plan_buffer_line( X_current, Y_current, Z_start_location,
  3285. ext_position,
  3286. homing_feedrate[Z_AXIS]/60,
  3287. active_extruder);
  3288. st_synchronize();
  3289. //
  3290. // Now get everything to the specified probe point So we can safely do a probe to
  3291. // get us close to the bed. If the Z-Axis is far from the bed, we don't want to
  3292. // use that as a starting point for each probe.
  3293. //
  3294. if (verbose_level > 2)
  3295. SERIAL_PROTOCOL("Positioning probe for the test.\n");
  3296. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  3297. ext_position,
  3298. homing_feedrate[X_AXIS]/60,
  3299. active_extruder);
  3300. st_synchronize();
  3301. current_position[X_AXIS] = X_current = st_get_position_mm(X_AXIS);
  3302. current_position[Y_AXIS] = Y_current = st_get_position_mm(Y_AXIS);
  3303. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  3304. current_position[E_AXIS] = ext_position = st_get_position_mm(E_AXIS);
  3305. //
  3306. // OK, do the inital probe to get us close to the bed.
  3307. // Then retrace the right amount and use that in subsequent probes
  3308. //
  3309. setup_for_endstop_move();
  3310. run_z_probe();
  3311. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  3312. Z_start_location = st_get_position_mm(Z_AXIS) + Z_RAISE_BEFORE_PROBING;
  3313. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  3314. ext_position,
  3315. homing_feedrate[X_AXIS]/60,
  3316. active_extruder);
  3317. st_synchronize();
  3318. current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS);
  3319. for( n=0; n<n_samples; n++) {
  3320. do_blocking_move_to( X_probe_location, Y_probe_location, Z_start_location); // Make sure we are at the probe location
  3321. if ( n_legs) {
  3322. double radius=0.0, theta=0.0, x_sweep, y_sweep;
  3323. int rotational_direction, l;
  3324. rotational_direction = (unsigned long) millis() & 0x0001; // clockwise or counter clockwise
  3325. radius = (unsigned long) millis() % (long) (X_MAX_LENGTH/4); // limit how far out to go
  3326. theta = (float) ((unsigned long) millis() % (long) 360) / (360./(2*3.1415926)); // turn into radians
  3327. //SERIAL_ECHOPAIR("starting radius: ",radius);
  3328. //SERIAL_ECHOPAIR(" theta: ",theta);
  3329. //SERIAL_ECHOPAIR(" direction: ",rotational_direction);
  3330. //SERIAL_PROTOCOLLNPGM("");
  3331. for( l=0; l<n_legs-1; l++) {
  3332. if (rotational_direction==1)
  3333. theta += (float) ((unsigned long) millis() % (long) 20) / (360.0/(2*3.1415926)); // turn into radians
  3334. else
  3335. theta -= (float) ((unsigned long) millis() % (long) 20) / (360.0/(2*3.1415926)); // turn into radians
  3336. radius += (float) ( ((long) ((unsigned long) millis() % (long) 10)) - 5);
  3337. if ( radius<0.0 )
  3338. radius = -radius;
  3339. X_current = X_probe_location + cos(theta) * radius;
  3340. Y_current = Y_probe_location + sin(theta) * radius;
  3341. if ( X_current<X_MIN_POS) // Make sure our X & Y are sane
  3342. X_current = X_MIN_POS;
  3343. if ( X_current>X_MAX_POS)
  3344. X_current = X_MAX_POS;
  3345. if ( Y_current<Y_MIN_POS) // Make sure our X & Y are sane
  3346. Y_current = Y_MIN_POS;
  3347. if ( Y_current>Y_MAX_POS)
  3348. Y_current = Y_MAX_POS;
  3349. if (verbose_level>3 ) {
  3350. SERIAL_ECHOPAIR("x: ", X_current);
  3351. SERIAL_ECHOPAIR("y: ", Y_current);
  3352. SERIAL_PROTOCOLLNPGM("");
  3353. }
  3354. do_blocking_move_to( X_current, Y_current, Z_current );
  3355. }
  3356. do_blocking_move_to( X_probe_location, Y_probe_location, Z_start_location); // Go back to the probe location
  3357. }
  3358. setup_for_endstop_move();
  3359. run_z_probe();
  3360. sample_set[n] = current_position[Z_AXIS];
  3361. //
  3362. // Get the current mean for the data points we have so far
  3363. //
  3364. sum=0.0;
  3365. for( j=0; j<=n; j++) {
  3366. sum = sum + sample_set[j];
  3367. }
  3368. mean = sum / (double (n+1));
  3369. //
  3370. // Now, use that mean to calculate the standard deviation for the
  3371. // data points we have so far
  3372. //
  3373. sum=0.0;
  3374. for( j=0; j<=n; j++) {
  3375. sum = sum + (sample_set[j]-mean) * (sample_set[j]-mean);
  3376. }
  3377. sigma = sqrt( sum / (double (n+1)) );
  3378. if (verbose_level > 1) {
  3379. SERIAL_PROTOCOL(n+1);
  3380. SERIAL_PROTOCOL(" of ");
  3381. SERIAL_PROTOCOL(n_samples);
  3382. SERIAL_PROTOCOLPGM(" z: ");
  3383. SERIAL_PROTOCOL_F(current_position[Z_AXIS], 6);
  3384. }
  3385. if (verbose_level > 2) {
  3386. SERIAL_PROTOCOL(" mean: ");
  3387. SERIAL_PROTOCOL_F(mean,6);
  3388. SERIAL_PROTOCOL(" sigma: ");
  3389. SERIAL_PROTOCOL_F(sigma,6);
  3390. }
  3391. if (verbose_level > 0)
  3392. SERIAL_PROTOCOLPGM("\n");
  3393. plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location,
  3394. current_position[E_AXIS], homing_feedrate[Z_AXIS]/60, active_extruder);
  3395. st_synchronize();
  3396. }
  3397. delay(1000);
  3398. clean_up_after_endstop_move();
  3399. // enable_endstops(true);
  3400. if (verbose_level > 0) {
  3401. SERIAL_PROTOCOLPGM("Mean: ");
  3402. SERIAL_PROTOCOL_F(mean, 6);
  3403. SERIAL_PROTOCOLPGM("\n");
  3404. }
  3405. SERIAL_PROTOCOLPGM("Standard Deviation: ");
  3406. SERIAL_PROTOCOL_F(sigma, 6);
  3407. SERIAL_PROTOCOLPGM("\n\n");
  3408. Sigma_Exit:
  3409. break;
  3410. }
  3411. #endif // Z_PROBE_REPEATABILITY_TEST
  3412. #endif // ENABLE_AUTO_BED_LEVELING
  3413. case 104: // M104
  3414. if(setTargetedHotend(104)){
  3415. break;
  3416. }
  3417. if (code_seen('S')) setTargetHotend(code_value(), tmp_extruder);
  3418. setWatch();
  3419. break;
  3420. case 112: // M112 -Emergency Stop
  3421. kill("", 3);
  3422. break;
  3423. case 140: // M140 set bed temp
  3424. if (code_seen('S')) setTargetBed(code_value());
  3425. break;
  3426. case 105 : // M105
  3427. if(setTargetedHotend(105)){
  3428. break;
  3429. }
  3430. #if defined(TEMP_0_PIN) && TEMP_0_PIN > -1
  3431. SERIAL_PROTOCOLPGM("ok T:");
  3432. SERIAL_PROTOCOL_F(degHotend(tmp_extruder),1);
  3433. SERIAL_PROTOCOLPGM(" /");
  3434. SERIAL_PROTOCOL_F(degTargetHotend(tmp_extruder),1);
  3435. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  3436. SERIAL_PROTOCOLPGM(" B:");
  3437. SERIAL_PROTOCOL_F(degBed(),1);
  3438. SERIAL_PROTOCOLPGM(" /");
  3439. SERIAL_PROTOCOL_F(degTargetBed(),1);
  3440. #endif //TEMP_BED_PIN
  3441. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  3442. SERIAL_PROTOCOLPGM(" T");
  3443. SERIAL_PROTOCOL(cur_extruder);
  3444. SERIAL_PROTOCOLPGM(":");
  3445. SERIAL_PROTOCOL_F(degHotend(cur_extruder),1);
  3446. SERIAL_PROTOCOLPGM(" /");
  3447. SERIAL_PROTOCOL_F(degTargetHotend(cur_extruder),1);
  3448. }
  3449. #else
  3450. SERIAL_ERROR_START;
  3451. SERIAL_ERRORLNRPGM(MSG_ERR_NO_THERMISTORS);
  3452. #endif
  3453. SERIAL_PROTOCOLPGM(" @:");
  3454. #ifdef EXTRUDER_WATTS
  3455. SERIAL_PROTOCOL((EXTRUDER_WATTS * getHeaterPower(tmp_extruder))/127);
  3456. SERIAL_PROTOCOLPGM("W");
  3457. #else
  3458. SERIAL_PROTOCOL(getHeaterPower(tmp_extruder));
  3459. #endif
  3460. SERIAL_PROTOCOLPGM(" B@:");
  3461. #ifdef BED_WATTS
  3462. SERIAL_PROTOCOL((BED_WATTS * getHeaterPower(-1))/127);
  3463. SERIAL_PROTOCOLPGM("W");
  3464. #else
  3465. SERIAL_PROTOCOL(getHeaterPower(-1));
  3466. #endif
  3467. #ifdef PINDA_THERMISTOR
  3468. SERIAL_PROTOCOLPGM(" P:");
  3469. SERIAL_PROTOCOL_F(current_temperature_pinda,1);
  3470. #endif //PINDA_THERMISTOR
  3471. #ifdef AMBIENT_THERMISTOR
  3472. SERIAL_PROTOCOLPGM(" A:");
  3473. SERIAL_PROTOCOL_F(current_temperature_ambient,1);
  3474. #endif //AMBIENT_THERMISTOR
  3475. #ifdef SHOW_TEMP_ADC_VALUES
  3476. {float raw = 0.0;
  3477. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  3478. SERIAL_PROTOCOLPGM(" ADC B:");
  3479. SERIAL_PROTOCOL_F(degBed(),1);
  3480. SERIAL_PROTOCOLPGM("C->");
  3481. raw = rawBedTemp();
  3482. SERIAL_PROTOCOL_F(raw/OVERSAMPLENR,5);
  3483. SERIAL_PROTOCOLPGM(" Rb->");
  3484. SERIAL_PROTOCOL_F(100 * (1 + (PtA * (raw/OVERSAMPLENR)) + (PtB * sq((raw/OVERSAMPLENR)))), 5);
  3485. SERIAL_PROTOCOLPGM(" Rxb->");
  3486. SERIAL_PROTOCOL_F(raw, 5);
  3487. #endif
  3488. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  3489. SERIAL_PROTOCOLPGM(" T");
  3490. SERIAL_PROTOCOL(cur_extruder);
  3491. SERIAL_PROTOCOLPGM(":");
  3492. SERIAL_PROTOCOL_F(degHotend(cur_extruder),1);
  3493. SERIAL_PROTOCOLPGM("C->");
  3494. raw = rawHotendTemp(cur_extruder);
  3495. SERIAL_PROTOCOL_F(raw/OVERSAMPLENR,5);
  3496. SERIAL_PROTOCOLPGM(" Rt");
  3497. SERIAL_PROTOCOL(cur_extruder);
  3498. SERIAL_PROTOCOLPGM("->");
  3499. SERIAL_PROTOCOL_F(100 * (1 + (PtA * (raw/OVERSAMPLENR)) + (PtB * sq((raw/OVERSAMPLENR)))), 5);
  3500. SERIAL_PROTOCOLPGM(" Rx");
  3501. SERIAL_PROTOCOL(cur_extruder);
  3502. SERIAL_PROTOCOLPGM("->");
  3503. SERIAL_PROTOCOL_F(raw, 5);
  3504. }}
  3505. #endif
  3506. SERIAL_PROTOCOLLN("");
  3507. return;
  3508. break;
  3509. case 109:
  3510. {// M109 - Wait for extruder heater to reach target.
  3511. if(setTargetedHotend(109)){
  3512. break;
  3513. }
  3514. LCD_MESSAGERPGM(MSG_HEATING);
  3515. heating_status = 1;
  3516. if (farm_mode) { prusa_statistics(1); };
  3517. #ifdef AUTOTEMP
  3518. autotemp_enabled=false;
  3519. #endif
  3520. if (code_seen('S')) {
  3521. setTargetHotend(code_value(), tmp_extruder);
  3522. CooldownNoWait = true;
  3523. } else if (code_seen('R')) {
  3524. setTargetHotend(code_value(), tmp_extruder);
  3525. CooldownNoWait = false;
  3526. }
  3527. #ifdef AUTOTEMP
  3528. if (code_seen('S')) autotemp_min=code_value();
  3529. if (code_seen('B')) autotemp_max=code_value();
  3530. if (code_seen('F'))
  3531. {
  3532. autotemp_factor=code_value();
  3533. autotemp_enabled=true;
  3534. }
  3535. #endif
  3536. setWatch();
  3537. codenum = millis();
  3538. /* See if we are heating up or cooling down */
  3539. target_direction = isHeatingHotend(tmp_extruder); // true if heating, false if cooling
  3540. cancel_heatup = false;
  3541. wait_for_heater(codenum); //loops until target temperature is reached
  3542. LCD_MESSAGERPGM(MSG_HEATING_COMPLETE);
  3543. heating_status = 2;
  3544. if (farm_mode) { prusa_statistics(2); };
  3545. //starttime=millis();
  3546. previous_millis_cmd = millis();
  3547. }
  3548. break;
  3549. case 190: // M190 - Wait for bed heater to reach target.
  3550. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  3551. LCD_MESSAGERPGM(MSG_BED_HEATING);
  3552. heating_status = 3;
  3553. if (farm_mode) { prusa_statistics(1); };
  3554. if (code_seen('S'))
  3555. {
  3556. setTargetBed(code_value());
  3557. CooldownNoWait = true;
  3558. }
  3559. else if (code_seen('R'))
  3560. {
  3561. setTargetBed(code_value());
  3562. CooldownNoWait = false;
  3563. }
  3564. codenum = millis();
  3565. cancel_heatup = false;
  3566. target_direction = isHeatingBed(); // true if heating, false if cooling
  3567. while ( (target_direction)&&(!cancel_heatup) ? (isHeatingBed()) : (isCoolingBed()&&(CooldownNoWait==false)) )
  3568. {
  3569. if(( millis() - codenum) > 1000 ) //Print Temp Reading every 1 second while heating up.
  3570. {
  3571. if (!farm_mode) {
  3572. float tt = degHotend(active_extruder);
  3573. SERIAL_PROTOCOLPGM("T:");
  3574. SERIAL_PROTOCOL(tt);
  3575. SERIAL_PROTOCOLPGM(" E:");
  3576. SERIAL_PROTOCOL((int)active_extruder);
  3577. SERIAL_PROTOCOLPGM(" B:");
  3578. SERIAL_PROTOCOL_F(degBed(), 1);
  3579. SERIAL_PROTOCOLLN("");
  3580. }
  3581. codenum = millis();
  3582. }
  3583. manage_heater();
  3584. manage_inactivity();
  3585. lcd_update();
  3586. }
  3587. LCD_MESSAGERPGM(MSG_BED_DONE);
  3588. heating_status = 4;
  3589. previous_millis_cmd = millis();
  3590. #endif
  3591. break;
  3592. #if defined(FAN_PIN) && FAN_PIN > -1
  3593. case 106: //M106 Fan On
  3594. if (code_seen('S')){
  3595. fanSpeed=constrain(code_value(),0,255);
  3596. }
  3597. else {
  3598. fanSpeed=255;
  3599. }
  3600. break;
  3601. case 107: //M107 Fan Off
  3602. fanSpeed = 0;
  3603. break;
  3604. #endif //FAN_PIN
  3605. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  3606. case 80: // M80 - Turn on Power Supply
  3607. SET_OUTPUT(PS_ON_PIN); //GND
  3608. WRITE(PS_ON_PIN, PS_ON_AWAKE);
  3609. // If you have a switch on suicide pin, this is useful
  3610. // if you want to start another print with suicide feature after
  3611. // a print without suicide...
  3612. #if defined SUICIDE_PIN && SUICIDE_PIN > -1
  3613. SET_OUTPUT(SUICIDE_PIN);
  3614. WRITE(SUICIDE_PIN, HIGH);
  3615. #endif
  3616. #ifdef ULTIPANEL
  3617. powersupply = true;
  3618. LCD_MESSAGERPGM(WELCOME_MSG);
  3619. lcd_update();
  3620. #endif
  3621. break;
  3622. #endif
  3623. case 81: // M81 - Turn off Power Supply
  3624. disable_heater();
  3625. st_synchronize();
  3626. disable_e0();
  3627. disable_e1();
  3628. disable_e2();
  3629. finishAndDisableSteppers();
  3630. fanSpeed = 0;
  3631. delay(1000); // Wait a little before to switch off
  3632. #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
  3633. st_synchronize();
  3634. suicide();
  3635. #elif defined(PS_ON_PIN) && PS_ON_PIN > -1
  3636. SET_OUTPUT(PS_ON_PIN);
  3637. WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  3638. #endif
  3639. #ifdef ULTIPANEL
  3640. powersupply = false;
  3641. LCD_MESSAGERPGM(CAT4(CUSTOM_MENDEL_NAME,PSTR(" "),MSG_OFF,PSTR("."))); //!!
  3642. /*
  3643. MACHNAME = "Prusa i3"
  3644. MSGOFF = "Vypnuto"
  3645. "Prusai3"" ""vypnuto""."
  3646. "Prusa i3"" "MSG_ALL[lang_selected][50]"."
  3647. */
  3648. lcd_update();
  3649. #endif
  3650. break;
  3651. case 82:
  3652. axis_relative_modes[3] = false;
  3653. break;
  3654. case 83:
  3655. axis_relative_modes[3] = true;
  3656. break;
  3657. case 18: //compatibility
  3658. case 84: // M84
  3659. if(code_seen('S')){
  3660. stepper_inactive_time = code_value() * 1000;
  3661. }
  3662. else
  3663. {
  3664. 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])));
  3665. if(all_axis)
  3666. {
  3667. st_synchronize();
  3668. disable_e0();
  3669. disable_e1();
  3670. disable_e2();
  3671. finishAndDisableSteppers();
  3672. }
  3673. else
  3674. {
  3675. st_synchronize();
  3676. if (code_seen('X')) disable_x();
  3677. if (code_seen('Y')) disable_y();
  3678. if (code_seen('Z')) disable_z();
  3679. #if ((E0_ENABLE_PIN != X_ENABLE_PIN) && (E1_ENABLE_PIN != Y_ENABLE_PIN)) // Only enable on boards that have seperate ENABLE_PINS
  3680. if (code_seen('E')) {
  3681. disable_e0();
  3682. disable_e1();
  3683. disable_e2();
  3684. }
  3685. #endif
  3686. }
  3687. }
  3688. snmm_filaments_used = 0;
  3689. break;
  3690. case 85: // M85
  3691. if(code_seen('S')) {
  3692. max_inactive_time = code_value() * 1000;
  3693. }
  3694. break;
  3695. case 92: // M92
  3696. for(int8_t i=0; i < NUM_AXIS; i++)
  3697. {
  3698. if(code_seen(axis_codes[i]))
  3699. {
  3700. if(i == 3) { // E
  3701. float value = code_value();
  3702. if(value < 20.0) {
  3703. float factor = axis_steps_per_unit[i] / value; // increase e constants if M92 E14 is given for netfab.
  3704. max_jerk[E_AXIS] *= factor;
  3705. max_feedrate[i] *= factor;
  3706. axis_steps_per_sqr_second[i] *= factor;
  3707. }
  3708. axis_steps_per_unit[i] = value;
  3709. }
  3710. else {
  3711. axis_steps_per_unit[i] = code_value();
  3712. }
  3713. }
  3714. }
  3715. break;
  3716. case 115: // M115
  3717. if (code_seen('V')) {
  3718. // Report the Prusa version number.
  3719. SERIAL_PROTOCOLLNRPGM(FW_VERSION_STR_P());
  3720. } else if (code_seen('U')) {
  3721. // Check the firmware version provided. If the firmware version provided by the U code is higher than the currently running firmware,
  3722. // pause the print and ask the user to upgrade the firmware.
  3723. show_upgrade_dialog_if_version_newer(++ strchr_pointer);
  3724. } else {
  3725. SERIAL_PROTOCOLRPGM(MSG_M115_REPORT);
  3726. }
  3727. break;
  3728. /* case 117: // M117 display message
  3729. starpos = (strchr(strchr_pointer + 5,'*'));
  3730. if(starpos!=NULL)
  3731. *(starpos)='\0';
  3732. lcd_setstatus(strchr_pointer + 5);
  3733. break;*/
  3734. case 114: // M114
  3735. SERIAL_PROTOCOLPGM("X:");
  3736. SERIAL_PROTOCOL(current_position[X_AXIS]);
  3737. SERIAL_PROTOCOLPGM(" Y:");
  3738. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  3739. SERIAL_PROTOCOLPGM(" Z:");
  3740. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  3741. SERIAL_PROTOCOLPGM(" E:");
  3742. SERIAL_PROTOCOL(current_position[E_AXIS]);
  3743. SERIAL_PROTOCOLRPGM(MSG_COUNT_X);
  3744. SERIAL_PROTOCOL(float(st_get_position(X_AXIS))/axis_steps_per_unit[X_AXIS]);
  3745. SERIAL_PROTOCOLPGM(" Y:");
  3746. SERIAL_PROTOCOL(float(st_get_position(Y_AXIS))/axis_steps_per_unit[Y_AXIS]);
  3747. SERIAL_PROTOCOLPGM(" Z:");
  3748. SERIAL_PROTOCOL(float(st_get_position(Z_AXIS))/axis_steps_per_unit[Z_AXIS]);
  3749. SERIAL_PROTOCOLLN("");
  3750. break;
  3751. case 120: // M120
  3752. enable_endstops(false) ;
  3753. break;
  3754. case 121: // M121
  3755. enable_endstops(true) ;
  3756. break;
  3757. case 119: // M119
  3758. SERIAL_PROTOCOLRPGM(MSG_M119_REPORT);
  3759. SERIAL_PROTOCOLLN("");
  3760. #if defined(X_MIN_PIN) && X_MIN_PIN > -1
  3761. SERIAL_PROTOCOLRPGM(MSG_X_MIN);
  3762. if(READ(X_MIN_PIN)^X_MIN_ENDSTOP_INVERTING){
  3763. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  3764. }else{
  3765. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  3766. }
  3767. SERIAL_PROTOCOLLN("");
  3768. #endif
  3769. #if defined(X_MAX_PIN) && X_MAX_PIN > -1
  3770. SERIAL_PROTOCOLRPGM(MSG_X_MAX);
  3771. if(READ(X_MAX_PIN)^X_MAX_ENDSTOP_INVERTING){
  3772. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  3773. }else{
  3774. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  3775. }
  3776. SERIAL_PROTOCOLLN("");
  3777. #endif
  3778. #if defined(Y_MIN_PIN) && Y_MIN_PIN > -1
  3779. SERIAL_PROTOCOLRPGM(MSG_Y_MIN);
  3780. if(READ(Y_MIN_PIN)^Y_MIN_ENDSTOP_INVERTING){
  3781. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  3782. }else{
  3783. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  3784. }
  3785. SERIAL_PROTOCOLLN("");
  3786. #endif
  3787. #if defined(Y_MAX_PIN) && Y_MAX_PIN > -1
  3788. SERIAL_PROTOCOLRPGM(MSG_Y_MAX);
  3789. if(READ(Y_MAX_PIN)^Y_MAX_ENDSTOP_INVERTING){
  3790. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  3791. }else{
  3792. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  3793. }
  3794. SERIAL_PROTOCOLLN("");
  3795. #endif
  3796. #if defined(Z_MIN_PIN) && Z_MIN_PIN > -1
  3797. SERIAL_PROTOCOLRPGM(MSG_Z_MIN);
  3798. if(READ(Z_MIN_PIN)^Z_MIN_ENDSTOP_INVERTING){
  3799. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  3800. }else{
  3801. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  3802. }
  3803. SERIAL_PROTOCOLLN("");
  3804. #endif
  3805. #if defined(Z_MAX_PIN) && Z_MAX_PIN > -1
  3806. SERIAL_PROTOCOLRPGM(MSG_Z_MAX);
  3807. if(READ(Z_MAX_PIN)^Z_MAX_ENDSTOP_INVERTING){
  3808. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_HIT);
  3809. }else{
  3810. SERIAL_PROTOCOLRPGM(MSG_ENDSTOP_OPEN);
  3811. }
  3812. SERIAL_PROTOCOLLN("");
  3813. #endif
  3814. break;
  3815. //TODO: update for all axis, use for loop
  3816. #ifdef BLINKM
  3817. case 150: // M150
  3818. {
  3819. byte red;
  3820. byte grn;
  3821. byte blu;
  3822. if(code_seen('R')) red = code_value();
  3823. if(code_seen('U')) grn = code_value();
  3824. if(code_seen('B')) blu = code_value();
  3825. SendColors(red,grn,blu);
  3826. }
  3827. break;
  3828. #endif //BLINKM
  3829. case 200: // M200 D<millimeters> set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).
  3830. {
  3831. tmp_extruder = active_extruder;
  3832. if(code_seen('T')) {
  3833. tmp_extruder = code_value();
  3834. if(tmp_extruder >= EXTRUDERS) {
  3835. SERIAL_ECHO_START;
  3836. SERIAL_ECHO(MSG_M200_INVALID_EXTRUDER);
  3837. break;
  3838. }
  3839. }
  3840. float area = .0;
  3841. if(code_seen('D')) {
  3842. float diameter = (float)code_value();
  3843. if (diameter == 0.0) {
  3844. // setting any extruder filament size disables volumetric on the assumption that
  3845. // slicers either generate in extruder values as cubic mm or as as filament feeds
  3846. // for all extruders
  3847. volumetric_enabled = false;
  3848. } else {
  3849. filament_size[tmp_extruder] = (float)code_value();
  3850. // make sure all extruders have some sane value for the filament size
  3851. filament_size[0] = (filament_size[0] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : filament_size[0]);
  3852. #if EXTRUDERS > 1
  3853. filament_size[1] = (filament_size[1] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : filament_size[1]);
  3854. #if EXTRUDERS > 2
  3855. filament_size[2] = (filament_size[2] == 0.0 ? DEFAULT_NOMINAL_FILAMENT_DIA : filament_size[2]);
  3856. #endif
  3857. #endif
  3858. volumetric_enabled = true;
  3859. }
  3860. } else {
  3861. //reserved for setting filament diameter via UFID or filament measuring device
  3862. break;
  3863. }
  3864. calculate_volumetric_multipliers();
  3865. }
  3866. break;
  3867. case 201: // M201
  3868. for(int8_t i=0; i < NUM_AXIS; i++)
  3869. {
  3870. if(code_seen(axis_codes[i]))
  3871. {
  3872. max_acceleration_units_per_sq_second[i] = code_value();
  3873. }
  3874. }
  3875. // 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)
  3876. reset_acceleration_rates();
  3877. break;
  3878. #if 0 // Not used for Sprinter/grbl gen6
  3879. case 202: // M202
  3880. for(int8_t i=0; i < NUM_AXIS; i++) {
  3881. if(code_seen(axis_codes[i])) axis_travel_steps_per_sqr_second[i] = code_value() * axis_steps_per_unit[i];
  3882. }
  3883. break;
  3884. #endif
  3885. case 203: // M203 max feedrate mm/sec
  3886. for(int8_t i=0; i < NUM_AXIS; i++) {
  3887. if(code_seen(axis_codes[i])) max_feedrate[i] = code_value();
  3888. }
  3889. break;
  3890. case 204: // M204 acclereration S normal moves T filmanent only moves
  3891. {
  3892. if(code_seen('S')) acceleration = code_value() ;
  3893. if(code_seen('T')) retract_acceleration = code_value() ;
  3894. }
  3895. break;
  3896. case 205: //M205 advanced settings: minimum travel speed S=while printing T=travel only, B=minimum segment time X= maximum xy jerk, Z=maximum Z jerk
  3897. {
  3898. if(code_seen('S')) minimumfeedrate = code_value();
  3899. if(code_seen('T')) mintravelfeedrate = code_value();
  3900. if(code_seen('B')) minsegmenttime = code_value() ;
  3901. if(code_seen('X')) max_jerk[X_AXIS] = max_jerk[Y_AXIS] = code_value();
  3902. if(code_seen('Y')) max_jerk[Y_AXIS] = code_value();
  3903. if(code_seen('Z')) max_jerk[Z_AXIS] = code_value();
  3904. if(code_seen('E')) max_jerk[E_AXIS] = code_value();
  3905. }
  3906. break;
  3907. case 206: // M206 additional homing offset
  3908. for(int8_t i=0; i < 3; i++)
  3909. {
  3910. if(code_seen(axis_codes[i])) add_homing[i] = code_value();
  3911. }
  3912. break;
  3913. #ifdef FWRETRACT
  3914. case 207: //M207 - set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop]
  3915. {
  3916. if(code_seen('S'))
  3917. {
  3918. retract_length = code_value() ;
  3919. }
  3920. if(code_seen('F'))
  3921. {
  3922. retract_feedrate = code_value()/60 ;
  3923. }
  3924. if(code_seen('Z'))
  3925. {
  3926. retract_zlift = code_value() ;
  3927. }
  3928. }break;
  3929. case 208: // M208 - set retract recover length S[positive mm surplus to the M207 S*] F[feedrate mm/min]
  3930. {
  3931. if(code_seen('S'))
  3932. {
  3933. retract_recover_length = code_value() ;
  3934. }
  3935. if(code_seen('F'))
  3936. {
  3937. retract_recover_feedrate = code_value()/60 ;
  3938. }
  3939. }break;
  3940. 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.
  3941. {
  3942. if(code_seen('S'))
  3943. {
  3944. int t= code_value() ;
  3945. switch(t)
  3946. {
  3947. case 0:
  3948. {
  3949. autoretract_enabled=false;
  3950. retracted[0]=false;
  3951. #if EXTRUDERS > 1
  3952. retracted[1]=false;
  3953. #endif
  3954. #if EXTRUDERS > 2
  3955. retracted[2]=false;
  3956. #endif
  3957. }break;
  3958. case 1:
  3959. {
  3960. autoretract_enabled=true;
  3961. retracted[0]=false;
  3962. #if EXTRUDERS > 1
  3963. retracted[1]=false;
  3964. #endif
  3965. #if EXTRUDERS > 2
  3966. retracted[2]=false;
  3967. #endif
  3968. }break;
  3969. default:
  3970. SERIAL_ECHO_START;
  3971. SERIAL_ECHORPGM(MSG_UNKNOWN_COMMAND);
  3972. SERIAL_ECHO(CMDBUFFER_CURRENT_STRING);
  3973. SERIAL_ECHOLNPGM("\"(1)");
  3974. }
  3975. }
  3976. }break;
  3977. #endif // FWRETRACT
  3978. #if EXTRUDERS > 1
  3979. case 218: // M218 - set hotend offset (in mm), T<extruder_number> X<offset_on_X> Y<offset_on_Y>
  3980. {
  3981. if(setTargetedHotend(218)){
  3982. break;
  3983. }
  3984. if(code_seen('X'))
  3985. {
  3986. extruder_offset[X_AXIS][tmp_extruder] = code_value();
  3987. }
  3988. if(code_seen('Y'))
  3989. {
  3990. extruder_offset[Y_AXIS][tmp_extruder] = code_value();
  3991. }
  3992. SERIAL_ECHO_START;
  3993. SERIAL_ECHORPGM(MSG_HOTEND_OFFSET);
  3994. for(tmp_extruder = 0; tmp_extruder < EXTRUDERS; tmp_extruder++)
  3995. {
  3996. SERIAL_ECHO(" ");
  3997. SERIAL_ECHO(extruder_offset[X_AXIS][tmp_extruder]);
  3998. SERIAL_ECHO(",");
  3999. SERIAL_ECHO(extruder_offset[Y_AXIS][tmp_extruder]);
  4000. }
  4001. SERIAL_ECHOLN("");
  4002. }break;
  4003. #endif
  4004. case 220: // M220 S<factor in percent>- set speed factor override percentage
  4005. {
  4006. if(code_seen('S'))
  4007. {
  4008. feedmultiply = code_value() ;
  4009. }
  4010. }
  4011. break;
  4012. case 221: // M221 S<factor in percent>- set extrude factor override percentage
  4013. {
  4014. if(code_seen('S'))
  4015. {
  4016. int tmp_code = code_value();
  4017. if (code_seen('T'))
  4018. {
  4019. if(setTargetedHotend(221)){
  4020. break;
  4021. }
  4022. extruder_multiply[tmp_extruder] = tmp_code;
  4023. }
  4024. else
  4025. {
  4026. extrudemultiply = tmp_code ;
  4027. }
  4028. }
  4029. }
  4030. break;
  4031. case 226: // M226 P<pin number> S<pin state>- Wait until the specified pin reaches the state required
  4032. {
  4033. if(code_seen('P')){
  4034. int pin_number = code_value(); // pin number
  4035. int pin_state = -1; // required pin state - default is inverted
  4036. if(code_seen('S')) pin_state = code_value(); // required pin state
  4037. if(pin_state >= -1 && pin_state <= 1){
  4038. for(int8_t i = 0; i < (int8_t)(sizeof(sensitive_pins)/sizeof(int)); i++)
  4039. {
  4040. if (sensitive_pins[i] == pin_number)
  4041. {
  4042. pin_number = -1;
  4043. break;
  4044. }
  4045. }
  4046. if (pin_number > -1)
  4047. {
  4048. int target = LOW;
  4049. st_synchronize();
  4050. pinMode(pin_number, INPUT);
  4051. switch(pin_state){
  4052. case 1:
  4053. target = HIGH;
  4054. break;
  4055. case 0:
  4056. target = LOW;
  4057. break;
  4058. case -1:
  4059. target = !digitalRead(pin_number);
  4060. break;
  4061. }
  4062. while(digitalRead(pin_number) != target){
  4063. manage_heater();
  4064. manage_inactivity();
  4065. lcd_update();
  4066. }
  4067. }
  4068. }
  4069. }
  4070. }
  4071. break;
  4072. #if NUM_SERVOS > 0
  4073. case 280: // M280 - set servo position absolute. P: servo index, S: angle or microseconds
  4074. {
  4075. int servo_index = -1;
  4076. int servo_position = 0;
  4077. if (code_seen('P'))
  4078. servo_index = code_value();
  4079. if (code_seen('S')) {
  4080. servo_position = code_value();
  4081. if ((servo_index >= 0) && (servo_index < NUM_SERVOS)) {
  4082. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  4083. servos[servo_index].attach(0);
  4084. #endif
  4085. servos[servo_index].write(servo_position);
  4086. #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
  4087. delay(PROBE_SERVO_DEACTIVATION_DELAY);
  4088. servos[servo_index].detach();
  4089. #endif
  4090. }
  4091. else {
  4092. SERIAL_ECHO_START;
  4093. SERIAL_ECHO("Servo ");
  4094. SERIAL_ECHO(servo_index);
  4095. SERIAL_ECHOLN(" out of range");
  4096. }
  4097. }
  4098. else if (servo_index >= 0) {
  4099. SERIAL_PROTOCOL(MSG_OK);
  4100. SERIAL_PROTOCOL(" Servo ");
  4101. SERIAL_PROTOCOL(servo_index);
  4102. SERIAL_PROTOCOL(": ");
  4103. SERIAL_PROTOCOL(servos[servo_index].read());
  4104. SERIAL_PROTOCOLLN("");
  4105. }
  4106. }
  4107. break;
  4108. #endif // NUM_SERVOS > 0
  4109. #if (LARGE_FLASH == true && ( BEEPER > 0 || defined(ULTRALCD) || defined(LCD_USE_I2C_BUZZER)))
  4110. case 300: // M300
  4111. {
  4112. int beepS = code_seen('S') ? code_value() : 110;
  4113. int beepP = code_seen('P') ? code_value() : 1000;
  4114. if (beepS > 0)
  4115. {
  4116. #if BEEPER > 0
  4117. tone(BEEPER, beepS);
  4118. delay(beepP);
  4119. noTone(BEEPER);
  4120. #elif defined(ULTRALCD)
  4121. lcd_buzz(beepS, beepP);
  4122. #elif defined(LCD_USE_I2C_BUZZER)
  4123. lcd_buzz(beepP, beepS);
  4124. #endif
  4125. }
  4126. else
  4127. {
  4128. delay(beepP);
  4129. }
  4130. }
  4131. break;
  4132. #endif // M300
  4133. #ifdef PIDTEMP
  4134. case 301: // M301
  4135. {
  4136. if(code_seen('P')) Kp = code_value();
  4137. if(code_seen('I')) Ki = scalePID_i(code_value());
  4138. if(code_seen('D')) Kd = scalePID_d(code_value());
  4139. #ifdef PID_ADD_EXTRUSION_RATE
  4140. if(code_seen('C')) Kc = code_value();
  4141. #endif
  4142. updatePID();
  4143. SERIAL_PROTOCOLRPGM(MSG_OK);
  4144. SERIAL_PROTOCOL(" p:");
  4145. SERIAL_PROTOCOL(Kp);
  4146. SERIAL_PROTOCOL(" i:");
  4147. SERIAL_PROTOCOL(unscalePID_i(Ki));
  4148. SERIAL_PROTOCOL(" d:");
  4149. SERIAL_PROTOCOL(unscalePID_d(Kd));
  4150. #ifdef PID_ADD_EXTRUSION_RATE
  4151. SERIAL_PROTOCOL(" c:");
  4152. //Kc does not have scaling applied above, or in resetting defaults
  4153. SERIAL_PROTOCOL(Kc);
  4154. #endif
  4155. SERIAL_PROTOCOLLN("");
  4156. }
  4157. break;
  4158. #endif //PIDTEMP
  4159. #ifdef PIDTEMPBED
  4160. case 304: // M304
  4161. {
  4162. if(code_seen('P')) bedKp = code_value();
  4163. if(code_seen('I')) bedKi = scalePID_i(code_value());
  4164. if(code_seen('D')) bedKd = scalePID_d(code_value());
  4165. updatePID();
  4166. SERIAL_PROTOCOLRPGM(MSG_OK);
  4167. SERIAL_PROTOCOL(" p:");
  4168. SERIAL_PROTOCOL(bedKp);
  4169. SERIAL_PROTOCOL(" i:");
  4170. SERIAL_PROTOCOL(unscalePID_i(bedKi));
  4171. SERIAL_PROTOCOL(" d:");
  4172. SERIAL_PROTOCOL(unscalePID_d(bedKd));
  4173. SERIAL_PROTOCOLLN("");
  4174. }
  4175. break;
  4176. #endif //PIDTEMP
  4177. case 240: // M240 Triggers a camera by emulating a Canon RC-1 : http://www.doc-diy.net/photo/rc-1_hacked/
  4178. {
  4179. #ifdef CHDK
  4180. SET_OUTPUT(CHDK);
  4181. WRITE(CHDK, HIGH);
  4182. chdkHigh = millis();
  4183. chdkActive = true;
  4184. #else
  4185. #if defined(PHOTOGRAPH_PIN) && PHOTOGRAPH_PIN > -1
  4186. const uint8_t NUM_PULSES=16;
  4187. const float PULSE_LENGTH=0.01524;
  4188. for(int i=0; i < NUM_PULSES; i++) {
  4189. WRITE(PHOTOGRAPH_PIN, HIGH);
  4190. _delay_ms(PULSE_LENGTH);
  4191. WRITE(PHOTOGRAPH_PIN, LOW);
  4192. _delay_ms(PULSE_LENGTH);
  4193. }
  4194. delay(7.33);
  4195. for(int i=0; i < NUM_PULSES; i++) {
  4196. WRITE(PHOTOGRAPH_PIN, HIGH);
  4197. _delay_ms(PULSE_LENGTH);
  4198. WRITE(PHOTOGRAPH_PIN, LOW);
  4199. _delay_ms(PULSE_LENGTH);
  4200. }
  4201. #endif
  4202. #endif //chdk end if
  4203. }
  4204. break;
  4205. #ifdef DOGLCD
  4206. case 250: // M250 Set LCD contrast value: C<value> (value 0..63)
  4207. {
  4208. if (code_seen('C')) {
  4209. lcd_setcontrast( ((int)code_value())&63 );
  4210. }
  4211. SERIAL_PROTOCOLPGM("lcd contrast value: ");
  4212. SERIAL_PROTOCOL(lcd_contrast);
  4213. SERIAL_PROTOCOLLN("");
  4214. }
  4215. break;
  4216. #endif
  4217. #ifdef PREVENT_DANGEROUS_EXTRUDE
  4218. case 302: // allow cold extrudes, or set the minimum extrude temperature
  4219. {
  4220. float temp = .0;
  4221. if (code_seen('S')) temp=code_value();
  4222. set_extrude_min_temp(temp);
  4223. }
  4224. break;
  4225. #endif
  4226. case 303: // M303 PID autotune
  4227. {
  4228. float temp = 150.0;
  4229. int e=0;
  4230. int c=5;
  4231. if (code_seen('E')) e=code_value();
  4232. if (e<0)
  4233. temp=70;
  4234. if (code_seen('S')) temp=code_value();
  4235. if (code_seen('C')) c=code_value();
  4236. PID_autotune(temp, e, c);
  4237. }
  4238. break;
  4239. case 400: // M400 finish all moves
  4240. {
  4241. st_synchronize();
  4242. }
  4243. break;
  4244. #ifdef FILAMENT_SENSOR
  4245. case 404: //M404 Enter the nominal filament width (3mm, 1.75mm ) N<3.0> or display nominal filament width
  4246. {
  4247. #if (FILWIDTH_PIN > -1)
  4248. if(code_seen('N')) filament_width_nominal=code_value();
  4249. else{
  4250. SERIAL_PROTOCOLPGM("Filament dia (nominal mm):");
  4251. SERIAL_PROTOCOLLN(filament_width_nominal);
  4252. }
  4253. #endif
  4254. }
  4255. break;
  4256. case 405: //M405 Turn on filament sensor for control
  4257. {
  4258. if(code_seen('D')) meas_delay_cm=code_value();
  4259. if(meas_delay_cm> MAX_MEASUREMENT_DELAY)
  4260. meas_delay_cm = MAX_MEASUREMENT_DELAY;
  4261. if(delay_index2 == -1) //initialize the ring buffer if it has not been done since startup
  4262. {
  4263. int temp_ratio = widthFil_to_size_ratio();
  4264. for (delay_index1=0; delay_index1<(MAX_MEASUREMENT_DELAY+1); ++delay_index1 ){
  4265. measurement_delay[delay_index1]=temp_ratio-100; //subtract 100 to scale within a signed byte
  4266. }
  4267. delay_index1=0;
  4268. delay_index2=0;
  4269. }
  4270. filament_sensor = true ;
  4271. //SERIAL_PROTOCOLPGM("Filament dia (measured mm):");
  4272. //SERIAL_PROTOCOL(filament_width_meas);
  4273. //SERIAL_PROTOCOLPGM("Extrusion ratio(%):");
  4274. //SERIAL_PROTOCOL(extrudemultiply);
  4275. }
  4276. break;
  4277. case 406: //M406 Turn off filament sensor for control
  4278. {
  4279. filament_sensor = false ;
  4280. }
  4281. break;
  4282. case 407: //M407 Display measured filament diameter
  4283. {
  4284. SERIAL_PROTOCOLPGM("Filament dia (measured mm):");
  4285. SERIAL_PROTOCOLLN(filament_width_meas);
  4286. }
  4287. break;
  4288. #endif
  4289. case 500: // M500 Store settings in EEPROM
  4290. {
  4291. Config_StoreSettings(EEPROM_OFFSET);
  4292. }
  4293. break;
  4294. case 501: // M501 Read settings from EEPROM
  4295. {
  4296. Config_RetrieveSettings(EEPROM_OFFSET);
  4297. }
  4298. break;
  4299. case 502: // M502 Revert to default settings
  4300. {
  4301. Config_ResetDefault();
  4302. }
  4303. break;
  4304. case 503: // M503 print settings currently in memory
  4305. {
  4306. Config_PrintSettings();
  4307. }
  4308. break;
  4309. case 509: //M509 Force language selection
  4310. {
  4311. lcd_force_language_selection();
  4312. SERIAL_ECHO_START;
  4313. SERIAL_PROTOCOLPGM(("LANG SEL FORCED"));
  4314. }
  4315. break;
  4316. #ifdef ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED
  4317. case 540:
  4318. {
  4319. if(code_seen('S')) abort_on_endstop_hit = code_value() > 0;
  4320. }
  4321. break;
  4322. #endif
  4323. #ifdef CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  4324. case CUSTOM_M_CODE_SET_Z_PROBE_OFFSET:
  4325. {
  4326. float value;
  4327. if (code_seen('Z'))
  4328. {
  4329. value = code_value();
  4330. if ((Z_PROBE_OFFSET_RANGE_MIN <= value) && (value <= Z_PROBE_OFFSET_RANGE_MAX))
  4331. {
  4332. zprobe_zoffset = -value; // compare w/ line 278 of ConfigurationStore.cpp
  4333. SERIAL_ECHO_START;
  4334. SERIAL_ECHOLNRPGM(CAT4(MSG_ZPROBE_ZOFFSET, " ", MSG_OK,PSTR("")));
  4335. SERIAL_PROTOCOLLN("");
  4336. }
  4337. else
  4338. {
  4339. SERIAL_ECHO_START;
  4340. SERIAL_ECHORPGM(MSG_ZPROBE_ZOFFSET);
  4341. SERIAL_ECHORPGM(MSG_Z_MIN);
  4342. SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MIN);
  4343. SERIAL_ECHORPGM(MSG_Z_MAX);
  4344. SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MAX);
  4345. SERIAL_PROTOCOLLN("");
  4346. }
  4347. }
  4348. else
  4349. {
  4350. SERIAL_ECHO_START;
  4351. SERIAL_ECHOLNRPGM(CAT2(MSG_ZPROBE_ZOFFSET, PSTR(" : ")));
  4352. SERIAL_ECHO(-zprobe_zoffset);
  4353. SERIAL_PROTOCOLLN("");
  4354. }
  4355. break;
  4356. }
  4357. #endif // CUSTOM_M_CODE_SET_Z_PROBE_OFFSET
  4358. #ifdef FILAMENTCHANGEENABLE
  4359. case 600: //Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  4360. {
  4361. MYSERIAL.println("!!!!M600!!!!");
  4362. st_synchronize();
  4363. float target[4];
  4364. float lastpos[4];
  4365. if (farm_mode)
  4366. {
  4367. prusa_statistics(22);
  4368. }
  4369. feedmultiplyBckp=feedmultiply;
  4370. int8_t TooLowZ = 0;
  4371. target[X_AXIS]=current_position[X_AXIS];
  4372. target[Y_AXIS]=current_position[Y_AXIS];
  4373. target[Z_AXIS]=current_position[Z_AXIS];
  4374. target[E_AXIS]=current_position[E_AXIS];
  4375. lastpos[X_AXIS]=current_position[X_AXIS];
  4376. lastpos[Y_AXIS]=current_position[Y_AXIS];
  4377. lastpos[Z_AXIS]=current_position[Z_AXIS];
  4378. lastpos[E_AXIS]=current_position[E_AXIS];
  4379. //Restract extruder
  4380. if(code_seen('E'))
  4381. {
  4382. target[E_AXIS]+= code_value();
  4383. }
  4384. else
  4385. {
  4386. #ifdef FILAMENTCHANGE_FIRSTRETRACT
  4387. target[E_AXIS]+= FILAMENTCHANGE_FIRSTRETRACT ;
  4388. #endif
  4389. }
  4390. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], FILAMENTCHANGE_RFEED, active_extruder);
  4391. //Lift Z
  4392. if(code_seen('Z'))
  4393. {
  4394. target[Z_AXIS]+= code_value();
  4395. }
  4396. else
  4397. {
  4398. #ifdef FILAMENTCHANGE_ZADD
  4399. target[Z_AXIS]+= FILAMENTCHANGE_ZADD ;
  4400. if(target[Z_AXIS] < 10){
  4401. target[Z_AXIS]+= 10 ;
  4402. TooLowZ = 1;
  4403. }else{
  4404. TooLowZ = 0;
  4405. }
  4406. #endif
  4407. }
  4408. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], FILAMENTCHANGE_ZFEED, active_extruder);
  4409. //Move XY to side
  4410. if(code_seen('X'))
  4411. {
  4412. target[X_AXIS]+= code_value();
  4413. }
  4414. else
  4415. {
  4416. #ifdef FILAMENTCHANGE_XPOS
  4417. target[X_AXIS]= FILAMENTCHANGE_XPOS ;
  4418. #endif
  4419. }
  4420. if(code_seen('Y'))
  4421. {
  4422. target[Y_AXIS]= code_value();
  4423. }
  4424. else
  4425. {
  4426. #ifdef FILAMENTCHANGE_YPOS
  4427. target[Y_AXIS]= FILAMENTCHANGE_YPOS ;
  4428. #endif
  4429. }
  4430. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], FILAMENTCHANGE_XYFEED, active_extruder);
  4431. st_synchronize();
  4432. custom_message = true;
  4433. lcd_setstatuspgm(MSG_UNLOADING_FILAMENT);
  4434. // Unload filament
  4435. if(code_seen('L'))
  4436. {
  4437. target[E_AXIS]+= code_value();
  4438. }
  4439. else
  4440. {
  4441. #ifdef SNMM
  4442. #else
  4443. #ifdef FILAMENTCHANGE_FINALRETRACT
  4444. target[E_AXIS] += FILAMENTCHANGE_FINALRETRACT;
  4445. #endif
  4446. #endif // SNMM
  4447. }
  4448. #ifdef SNMM
  4449. target[E_AXIS] += 12;
  4450. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 3500, active_extruder);
  4451. target[E_AXIS] += 6;
  4452. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 5000, active_extruder);
  4453. target[E_AXIS] += (FIL_LOAD_LENGTH * -1);
  4454. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 5000, active_extruder);
  4455. st_synchronize();
  4456. target[E_AXIS] += (FIL_COOLING);
  4457. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 50, active_extruder);
  4458. target[E_AXIS] += (FIL_COOLING*-1);
  4459. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 50, active_extruder);
  4460. target[E_AXIS] += (bowden_length[snmm_extruder] *-1);
  4461. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 3000, active_extruder);
  4462. st_synchronize();
  4463. #else
  4464. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], FILAMENTCHANGE_RFEED, active_extruder);
  4465. #endif // SNMM
  4466. //finish moves
  4467. st_synchronize();
  4468. //disable extruder steppers so filament can be removed
  4469. disable_e0();
  4470. disable_e1();
  4471. disable_e2();
  4472. delay(100);
  4473. //Wait for user to insert filament
  4474. uint8_t cnt=0;
  4475. int counterBeep = 0;
  4476. lcd_wait_interact();
  4477. load_filament_time = millis();
  4478. while(!lcd_clicked()){
  4479. cnt++;
  4480. manage_heater();
  4481. manage_inactivity(true);
  4482. /*#ifdef SNMM
  4483. target[E_AXIS] += 0.002;
  4484. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 500, active_extruder);
  4485. #endif // SNMM*/
  4486. if(cnt==0)
  4487. {
  4488. #if BEEPER > 0
  4489. if (counterBeep== 500){
  4490. counterBeep = 0;
  4491. }
  4492. SET_OUTPUT(BEEPER);
  4493. if (counterBeep== 0){
  4494. WRITE(BEEPER,HIGH);
  4495. }
  4496. if (counterBeep== 20){
  4497. WRITE(BEEPER,LOW);
  4498. }
  4499. counterBeep++;
  4500. #else
  4501. #if !defined(LCD_FEEDBACK_FREQUENCY_HZ) || !defined(LCD_FEEDBACK_FREQUENCY_DURATION_MS)
  4502. lcd_buzz(1000/6,100);
  4503. #else
  4504. lcd_buzz(LCD_FEEDBACK_FREQUENCY_DURATION_MS,LCD_FEEDBACK_FREQUENCY_HZ);
  4505. #endif
  4506. #endif
  4507. }
  4508. }
  4509. #ifdef SNMM
  4510. display_loading();
  4511. do {
  4512. target[E_AXIS] += 0.002;
  4513. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 500, active_extruder);
  4514. delay_keep_alive(2);
  4515. } while (!lcd_clicked());
  4516. /*if (millis() - load_filament_time > 2) {
  4517. load_filament_time = millis();
  4518. target[E_AXIS] += 0.001;
  4519. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 1000, active_extruder);
  4520. }*/
  4521. #endif
  4522. //Filament inserted
  4523. WRITE(BEEPER,LOW);
  4524. //Feed the filament to the end of nozzle quickly
  4525. #ifdef SNMM
  4526. st_synchronize();
  4527. target[E_AXIS] += bowden_length[snmm_extruder];
  4528. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 3000, active_extruder);
  4529. target[E_AXIS] += FIL_LOAD_LENGTH - 60;
  4530. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 1400, active_extruder);
  4531. target[E_AXIS] += 40;
  4532. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 400, active_extruder);
  4533. target[E_AXIS] += 10;
  4534. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 50, active_extruder);
  4535. #else
  4536. target[E_AXIS] += FILAMENTCHANGE_FIRSTFEED;
  4537. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], FILAMENTCHANGE_EFEED, active_extruder);
  4538. #endif // SNMM
  4539. //Extrude some filament
  4540. target[E_AXIS]+= FILAMENTCHANGE_FINALFEED ;
  4541. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], FILAMENTCHANGE_EXFEED, active_extruder);
  4542. //Wait for user to check the state
  4543. lcd_change_fil_state = 0;
  4544. lcd_loading_filament();
  4545. while ((lcd_change_fil_state == 0)||(lcd_change_fil_state != 1)){
  4546. lcd_change_fil_state = 0;
  4547. lcd_alright();
  4548. switch(lcd_change_fil_state){
  4549. // Filament failed to load so load it again
  4550. case 2:
  4551. #ifdef SNMM
  4552. display_loading();
  4553. do {
  4554. target[E_AXIS] += 0.002;
  4555. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 500, active_extruder);
  4556. delay_keep_alive(2);
  4557. } while (!lcd_clicked());
  4558. st_synchronize();
  4559. target[E_AXIS] += bowden_length[snmm_extruder];
  4560. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 3000, active_extruder);
  4561. target[E_AXIS] += FIL_LOAD_LENGTH - 60;
  4562. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 1400, active_extruder);
  4563. target[E_AXIS] += 40;
  4564. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 400, active_extruder);
  4565. target[E_AXIS] += 10;
  4566. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 50, active_extruder);
  4567. #else
  4568. target[E_AXIS]+= FILAMENTCHANGE_FIRSTFEED ;
  4569. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], FILAMENTCHANGE_EFEED, active_extruder);
  4570. #endif
  4571. target[E_AXIS]+= FILAMENTCHANGE_FINALFEED ;
  4572. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], FILAMENTCHANGE_EXFEED, active_extruder);
  4573. lcd_loading_filament();
  4574. break;
  4575. // Filament loaded properly but color is not clear
  4576. case 3:
  4577. target[E_AXIS]+= FILAMENTCHANGE_FINALFEED ;
  4578. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 2, active_extruder);
  4579. lcd_loading_color();
  4580. break;
  4581. // Everything good
  4582. default:
  4583. lcd_change_success();
  4584. lcd_update_enable(true);
  4585. break;
  4586. }
  4587. }
  4588. //Not let's go back to print
  4589. //Feed a little of filament to stabilize pressure
  4590. target[E_AXIS]+= FILAMENTCHANGE_RECFEED;
  4591. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], FILAMENTCHANGE_EXFEED, active_extruder);
  4592. //Retract
  4593. target[E_AXIS]+= FILAMENTCHANGE_FIRSTRETRACT;
  4594. plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], FILAMENTCHANGE_RFEED, active_extruder);
  4595. //plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], 70, active_extruder); //should do nothing
  4596. //Move XY back
  4597. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], target[Z_AXIS], target[E_AXIS], FILAMENTCHANGE_XYFEED, active_extruder);
  4598. //Move Z back
  4599. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], lastpos[Z_AXIS], target[E_AXIS], FILAMENTCHANGE_ZFEED, active_extruder);
  4600. target[E_AXIS]= target[E_AXIS] - FILAMENTCHANGE_FIRSTRETRACT;
  4601. //Unretract
  4602. plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], lastpos[Z_AXIS], target[E_AXIS], FILAMENTCHANGE_RFEED, active_extruder);
  4603. //Set E position to original
  4604. plan_set_e_position(lastpos[E_AXIS]);
  4605. //Recover feed rate
  4606. feedmultiply=feedmultiplyBckp;
  4607. char cmd[9];
  4608. sprintf_P(cmd, PSTR("M220 S%i"), feedmultiplyBckp);
  4609. enquecommand(cmd);
  4610. lcd_setstatuspgm(WELCOME_MSG);
  4611. custom_message = false;
  4612. custom_message_type = 0;
  4613. #ifdef PAT9125
  4614. if (fsensor_M600)
  4615. {
  4616. cmdqueue_pop_front(); //hack because M600 repeated 2x when enqueued to front
  4617. st_synchronize();
  4618. while (!is_buffer_empty())
  4619. {
  4620. process_commands();
  4621. cmdqueue_pop_front();
  4622. }
  4623. fsensor_enable();
  4624. fsensor_restore_print_and_continue();
  4625. }
  4626. #endif //PAT9125
  4627. }
  4628. break;
  4629. #endif //FILAMENTCHANGEENABLE
  4630. case 601: {
  4631. if(lcd_commands_type == 0) lcd_commands_type = LCD_COMMAND_LONG_PAUSE;
  4632. }
  4633. break;
  4634. case 602: {
  4635. if(lcd_commands_type == 0) lcd_commands_type = LCD_COMMAND_LONG_PAUSE_RESUME;
  4636. }
  4637. break;
  4638. #ifdef LIN_ADVANCE
  4639. case 900: // M900: Set LIN_ADVANCE options.
  4640. gcode_M900();
  4641. break;
  4642. #endif
  4643. case 907: // M907 Set digital trimpot motor current using axis codes.
  4644. {
  4645. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  4646. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) digipot_current(i,code_value());
  4647. if(code_seen('B')) digipot_current(4,code_value());
  4648. if(code_seen('S')) for(int i=0;i<=4;i++) digipot_current(i,code_value());
  4649. #endif
  4650. #ifdef MOTOR_CURRENT_PWM_XY_PIN
  4651. if(code_seen('X')) digipot_current(0, code_value());
  4652. #endif
  4653. #ifdef MOTOR_CURRENT_PWM_Z_PIN
  4654. if(code_seen('Z')) digipot_current(1, code_value());
  4655. #endif
  4656. #ifdef MOTOR_CURRENT_PWM_E_PIN
  4657. if(code_seen('E')) digipot_current(2, code_value());
  4658. #endif
  4659. #ifdef DIGIPOT_I2C
  4660. // this one uses actual amps in floating point
  4661. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) digipot_i2c_set_current(i, code_value());
  4662. // for each additional extruder (named B,C,D,E..., channels 4,5,6,7...)
  4663. for(int i=NUM_AXIS;i<DIGIPOT_I2C_NUM_CHANNELS;i++) if(code_seen('B'+i-NUM_AXIS)) digipot_i2c_set_current(i, code_value());
  4664. #endif
  4665. }
  4666. break;
  4667. case 908: // M908 Control digital trimpot directly.
  4668. {
  4669. #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
  4670. uint8_t channel,current;
  4671. if(code_seen('P')) channel=code_value();
  4672. if(code_seen('S')) current=code_value();
  4673. digitalPotWrite(channel, current);
  4674. #endif
  4675. }
  4676. break;
  4677. case 910: // M910 TMC2130 init
  4678. {
  4679. tmc2130_init();
  4680. }
  4681. break;
  4682. case 911: // M911 Set TMC2130 holding currents
  4683. {
  4684. if (code_seen('X')) tmc2130_set_current_h(0, code_value());
  4685. if (code_seen('Y')) tmc2130_set_current_h(1, code_value());
  4686. if (code_seen('Z')) tmc2130_set_current_h(2, code_value());
  4687. if (code_seen('E')) tmc2130_set_current_h(3, code_value());
  4688. }
  4689. break;
  4690. case 912: // M912 Set TMC2130 running currents
  4691. {
  4692. if (code_seen('X')) tmc2130_set_current_r(0, code_value());
  4693. if (code_seen('Y')) tmc2130_set_current_r(1, code_value());
  4694. if (code_seen('Z')) tmc2130_set_current_r(2, code_value());
  4695. if (code_seen('E')) tmc2130_set_current_r(3, code_value());
  4696. }
  4697. break;
  4698. case 913: // M913 Print TMC2130 currents
  4699. {
  4700. tmc2130_print_currents();
  4701. }
  4702. break;
  4703. case 914: // M914 Set normal mode
  4704. {
  4705. tmc2130_mode = TMC2130_MODE_NORMAL;
  4706. tmc2130_init();
  4707. }
  4708. break;
  4709. case 915: // M915 Set silent mode
  4710. {
  4711. tmc2130_mode = TMC2130_MODE_SILENT;
  4712. tmc2130_init();
  4713. }
  4714. break;
  4715. case 916: // M916 Set sg_thrs
  4716. {
  4717. if (code_seen('X')) tmc2130_axis_sg_thr[X_AXIS] = code_value();
  4718. if (code_seen('Y')) tmc2130_axis_sg_thr[Y_AXIS] = code_value();
  4719. if (code_seen('Z')) tmc2130_axis_sg_thr[Z_AXIS] = code_value();
  4720. MYSERIAL.print("tmc2130_axis_sg_thr[X]=");
  4721. MYSERIAL.print(tmc2130_axis_sg_thr[X_AXIS], DEC);
  4722. MYSERIAL.print("tmc2130_axis_sg_thr[Y]=");
  4723. MYSERIAL.print(tmc2130_axis_sg_thr[Y_AXIS], DEC);
  4724. MYSERIAL.print("tmc2130_axis_sg_thr[Z]=");
  4725. MYSERIAL.print(tmc2130_axis_sg_thr[Z_AXIS], DEC);
  4726. }
  4727. break;
  4728. case 917: // M917 Set TMC2130 pwm_ampl
  4729. {
  4730. if (code_seen('X')) tmc2130_set_pwm_ampl(0, code_value());
  4731. if (code_seen('Y')) tmc2130_set_pwm_ampl(1, code_value());
  4732. if (code_seen('Z')) tmc2130_set_pwm_ampl(2, code_value());
  4733. if (code_seen('E')) tmc2130_set_pwm_ampl(3, code_value());
  4734. }
  4735. break;
  4736. case 918: // M918 Set TMC2130 pwm_grad
  4737. {
  4738. if (code_seen('X')) tmc2130_set_pwm_grad(0, code_value());
  4739. if (code_seen('Y')) tmc2130_set_pwm_grad(1, code_value());
  4740. if (code_seen('Z')) tmc2130_set_pwm_grad(2, code_value());
  4741. if (code_seen('E')) tmc2130_set_pwm_grad(3, code_value());
  4742. }
  4743. break;
  4744. case 350: // M350 Set microstepping mode. Warning: Steps per unit remains unchanged. S code sets stepping mode for all drivers.
  4745. {
  4746. #if defined(X_MS1_PIN) && X_MS1_PIN > -1
  4747. if(code_seen('S')) for(int i=0;i<=4;i++) microstep_mode(i,code_value());
  4748. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_mode(i,(uint8_t)code_value());
  4749. if(code_seen('B')) microstep_mode(4,code_value());
  4750. microstep_readings();
  4751. #endif
  4752. }
  4753. break;
  4754. case 351: // M351 Toggle MS1 MS2 pins directly, S# determines MS1 or MS2, X# sets the pin high/low.
  4755. {
  4756. #if defined(X_MS1_PIN) && X_MS1_PIN > -1
  4757. if(code_seen('S')) switch((int)code_value())
  4758. {
  4759. case 1:
  4760. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_ms(i,code_value(),-1);
  4761. if(code_seen('B')) microstep_ms(4,code_value(),-1);
  4762. break;
  4763. case 2:
  4764. for(int i=0;i<NUM_AXIS;i++) if(code_seen(axis_codes[i])) microstep_ms(i,-1,code_value());
  4765. if(code_seen('B')) microstep_ms(4,-1,code_value());
  4766. break;
  4767. }
  4768. microstep_readings();
  4769. #endif
  4770. }
  4771. break;
  4772. case 701: //M701: load filament
  4773. {
  4774. enable_z();
  4775. custom_message = true;
  4776. custom_message_type = 2;
  4777. lcd_setstatuspgm(MSG_LOADING_FILAMENT);
  4778. current_position[E_AXIS] += 70;
  4779. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 400 / 60, active_extruder); //fast sequence
  4780. current_position[E_AXIS] += 25;
  4781. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 100 / 60, active_extruder); //slow sequence
  4782. st_synchronize();
  4783. if (!farm_mode && loading_flag) {
  4784. bool clean = lcd_show_fullscreen_message_yes_no_and_wait_P(MSG_FILAMENT_CLEAN, false, true);
  4785. while (!clean) {
  4786. lcd_update_enable(true);
  4787. lcd_update(2);
  4788. current_position[E_AXIS] += 25;
  4789. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 100 / 60, active_extruder); //slow sequence
  4790. st_synchronize();
  4791. clean = lcd_show_fullscreen_message_yes_no_and_wait_P(MSG_FILAMENT_CLEAN, false, true);
  4792. }
  4793. }
  4794. lcd_update_enable(true);
  4795. lcd_update(2);
  4796. lcd_setstatuspgm(WELCOME_MSG);
  4797. disable_z();
  4798. loading_flag = false;
  4799. custom_message = false;
  4800. custom_message_type = 0;
  4801. }
  4802. break;
  4803. case 702:
  4804. {
  4805. #ifdef SNMM
  4806. if (code_seen('U')) {
  4807. extr_unload_used(); //unload all filaments which were used in current print
  4808. }
  4809. else if (code_seen('C')) {
  4810. extr_unload(); //unload just current filament
  4811. }
  4812. else {
  4813. extr_unload_all(); //unload all filaments
  4814. }
  4815. #else
  4816. custom_message = true;
  4817. custom_message_type = 2;
  4818. lcd_setstatuspgm(MSG_UNLOADING_FILAMENT);
  4819. current_position[E_AXIS] -= 80;
  4820. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 7000 / 60, active_extruder);
  4821. st_synchronize();
  4822. lcd_setstatuspgm(WELCOME_MSG);
  4823. custom_message = false;
  4824. custom_message_type = 0;
  4825. #endif
  4826. }
  4827. break;
  4828. case 999: // M999: Restart after being stopped
  4829. Stopped = false;
  4830. lcd_reset_alert_level();
  4831. gcode_LastN = Stopped_gcode_LastN;
  4832. FlushSerialRequestResend();
  4833. break;
  4834. default: SERIAL_ECHOLNPGM("Invalid M code.");
  4835. }
  4836. } // end if(code_seen('M')) (end of M codes)
  4837. else if(code_seen('T'))
  4838. {
  4839. int index;
  4840. for (index = 1; *(strchr_pointer + index) == ' ' || *(strchr_pointer + index) == '\t'; index++);
  4841. if ((*(strchr_pointer + index) < '0' || *(strchr_pointer + index) > '9') && *(strchr_pointer + index) != '?') {
  4842. SERIAL_ECHOLNPGM("Invalid T code.");
  4843. }
  4844. else {
  4845. if (*(strchr_pointer + index) == '?') {
  4846. tmp_extruder = choose_extruder_menu();
  4847. }
  4848. else {
  4849. tmp_extruder = code_value();
  4850. }
  4851. snmm_filaments_used |= (1 << tmp_extruder); //for stop print
  4852. #ifdef SNMM
  4853. #ifdef LIN_ADVANCE
  4854. if (snmm_extruder != tmp_extruder)
  4855. clear_current_adv_vars(); //Check if the selected extruder is not the active one and reset LIN_ADVANCE variables if so.
  4856. #endif
  4857. snmm_extruder = tmp_extruder;
  4858. st_synchronize();
  4859. delay(100);
  4860. disable_e0();
  4861. disable_e1();
  4862. disable_e2();
  4863. pinMode(E_MUX0_PIN, OUTPUT);
  4864. pinMode(E_MUX1_PIN, OUTPUT);
  4865. pinMode(E_MUX2_PIN, OUTPUT);
  4866. delay(100);
  4867. SERIAL_ECHO_START;
  4868. SERIAL_ECHO("T:");
  4869. SERIAL_ECHOLN((int)tmp_extruder);
  4870. switch (tmp_extruder) {
  4871. case 1:
  4872. WRITE(E_MUX0_PIN, HIGH);
  4873. WRITE(E_MUX1_PIN, LOW);
  4874. WRITE(E_MUX2_PIN, LOW);
  4875. break;
  4876. case 2:
  4877. WRITE(E_MUX0_PIN, LOW);
  4878. WRITE(E_MUX1_PIN, HIGH);
  4879. WRITE(E_MUX2_PIN, LOW);
  4880. break;
  4881. case 3:
  4882. WRITE(E_MUX0_PIN, HIGH);
  4883. WRITE(E_MUX1_PIN, HIGH);
  4884. WRITE(E_MUX2_PIN, LOW);
  4885. break;
  4886. default:
  4887. WRITE(E_MUX0_PIN, LOW);
  4888. WRITE(E_MUX1_PIN, LOW);
  4889. WRITE(E_MUX2_PIN, LOW);
  4890. break;
  4891. }
  4892. delay(100);
  4893. #else
  4894. if (tmp_extruder >= EXTRUDERS) {
  4895. SERIAL_ECHO_START;
  4896. SERIAL_ECHOPGM("T");
  4897. SERIAL_PROTOCOLLN((int)tmp_extruder);
  4898. SERIAL_ECHOLNRPGM(MSG_INVALID_EXTRUDER);
  4899. }
  4900. else {
  4901. boolean make_move = false;
  4902. if (code_seen('F')) {
  4903. make_move = true;
  4904. next_feedrate = code_value();
  4905. if (next_feedrate > 0.0) {
  4906. feedrate = next_feedrate;
  4907. }
  4908. }
  4909. #if EXTRUDERS > 1
  4910. if (tmp_extruder != active_extruder) {
  4911. // Save current position to return to after applying extruder offset
  4912. memcpy(destination, current_position, sizeof(destination));
  4913. // Offset extruder (only by XY)
  4914. int i;
  4915. for (i = 0; i < 2; i++) {
  4916. current_position[i] = current_position[i] -
  4917. extruder_offset[i][active_extruder] +
  4918. extruder_offset[i][tmp_extruder];
  4919. }
  4920. // Set the new active extruder and position
  4921. active_extruder = tmp_extruder;
  4922. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  4923. // Move to the old position if 'F' was in the parameters
  4924. if (make_move && Stopped == false) {
  4925. prepare_move();
  4926. }
  4927. }
  4928. #endif
  4929. SERIAL_ECHO_START;
  4930. SERIAL_ECHORPGM(MSG_ACTIVE_EXTRUDER);
  4931. SERIAL_PROTOCOLLN((int)active_extruder);
  4932. }
  4933. #endif
  4934. }
  4935. } // end if(code_seen('T')) (end of T codes)
  4936. #ifdef DEBUG_DCODES
  4937. else if (code_seen('D')) // D codes (debug)
  4938. {
  4939. switch((int)code_value())
  4940. {
  4941. case 0: // D0 - Reset
  4942. dcode_0(); break;
  4943. case 1: // D1 - Clear EEPROM
  4944. dcode_1(); break;
  4945. case 2: // D2 - Read/Write RAM
  4946. dcode_2(); break;
  4947. case 3: // D3 - Read/Write EEPROM
  4948. dcode_3(); break;
  4949. case 4: // D4 - Read/Write PIN
  4950. dcode_4(); break;
  4951. case 5:
  4952. MYSERIAL.println("D5 - Test");
  4953. if (code_seen('P'))
  4954. selectedSerialPort = (int)code_value();
  4955. MYSERIAL.print("selectedSerialPort = ");
  4956. MYSERIAL.println(selectedSerialPort, DEC);
  4957. break;
  4958. case 999:
  4959. {
  4960. MYSERIAL.println("D999 - crash");
  4961. /* while (!is_buffer_empty())
  4962. {
  4963. process_commands();
  4964. cmdqueue_pop_front();
  4965. }*/
  4966. st_synchronize();
  4967. lcd_update_enable(true);
  4968. lcd_implementation_clear();
  4969. lcd_update(2);
  4970. bool yesno = lcd_show_fullscreen_message_yes_no_and_wait_P(MSG_CRASH_DETECTED, false);
  4971. lcd_update_enable(true);
  4972. lcd_update(2);
  4973. lcd_setstatuspgm(WELCOME_MSG);
  4974. if (yesno)
  4975. {
  4976. enquecommand_P(PSTR("G28 X"));
  4977. enquecommand_P(PSTR("G28 Y"));
  4978. enquecommand_P(PSTR("D1000"));
  4979. }
  4980. else
  4981. {
  4982. enquecommand_P(PSTR("D1001"));
  4983. }
  4984. }
  4985. break;
  4986. case 1000:
  4987. crashdet_restore_print_and_continue();
  4988. tmc2130_sg_stop_on_crash = true;
  4989. break;
  4990. case 1001:
  4991. card.sdprinting = false;
  4992. card.closefile();
  4993. tmc2130_sg_stop_on_crash = true;
  4994. break;
  4995. /* case 4:
  4996. {
  4997. MYSERIAL.println("D4 - Test");
  4998. uint8_t data[16];
  4999. int cnt = parse_hex(strchr_pointer + 2, data, 16);
  5000. MYSERIAL.println(cnt, DEC);
  5001. for (int i = 0; i < cnt; i++)
  5002. {
  5003. serial_print_hex_byte(data[i]);
  5004. MYSERIAL.write(' ');
  5005. }
  5006. MYSERIAL.write('\n');
  5007. }
  5008. break;
  5009. /* case 3:
  5010. if (code_seen('L')) // lcd pwm (0-255)
  5011. {
  5012. lcdSoftPwm = (int)code_value();
  5013. }
  5014. if (code_seen('B')) // lcd blink delay (0-255)
  5015. {
  5016. lcdBlinkDelay = (int)code_value();
  5017. }
  5018. // calibrate_z_auto();
  5019. /* MYSERIAL.print("fsensor_enable()");
  5020. #ifdef PAT9125
  5021. fsensor_enable();
  5022. #endif*/
  5023. break;
  5024. // case 4:
  5025. // lcdBlinkDelay = 10;
  5026. /* MYSERIAL.print("fsensor_disable()");
  5027. #ifdef PAT9125
  5028. fsensor_disable();
  5029. #endif
  5030. break;*/
  5031. // break;
  5032. /* case 5:
  5033. {
  5034. MYSERIAL.print("tmc2130_rd_MSCNT(0)=");
  5035. int val = tmc2130_rd_MSCNT(tmc2130_cs[0]);
  5036. MYSERIAL.println(val);
  5037. homeaxis(0);
  5038. }
  5039. break;*/
  5040. case 6:
  5041. {
  5042. /* MYSERIAL.print("tmc2130_rd_MSCNT(1)=");
  5043. int val = tmc2130_rd_MSCNT(tmc2130_cs[1]);
  5044. MYSERIAL.println(val);*/
  5045. homeaxis(1);
  5046. }
  5047. break;
  5048. case 7:
  5049. {
  5050. MYSERIAL.print("pat9125_init=");
  5051. MYSERIAL.println(pat9125_init(200, 200));
  5052. }
  5053. break;
  5054. case 8:
  5055. {
  5056. MYSERIAL.print("swi2c_check=");
  5057. MYSERIAL.println(swi2c_check(0x75));
  5058. }
  5059. break;
  5060. }
  5061. }
  5062. #endif //DEBUG_DCODES
  5063. else
  5064. {
  5065. SERIAL_ECHO_START;
  5066. SERIAL_ECHORPGM(MSG_UNKNOWN_COMMAND);
  5067. SERIAL_ECHO(CMDBUFFER_CURRENT_STRING);
  5068. SERIAL_ECHOLNPGM("\"(2)");
  5069. }
  5070. ClearToSend();
  5071. }
  5072. void FlushSerialRequestResend()
  5073. {
  5074. //char cmdbuffer[bufindr][100]="Resend:";
  5075. MYSERIAL.flush();
  5076. SERIAL_PROTOCOLRPGM(MSG_RESEND);
  5077. SERIAL_PROTOCOLLN(gcode_LastN + 1);
  5078. ClearToSend();
  5079. }
  5080. // Confirm the execution of a command, if sent from a serial line.
  5081. // Execution of a command from a SD card will not be confirmed.
  5082. void ClearToSend()
  5083. {
  5084. previous_millis_cmd = millis();
  5085. if (CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB)
  5086. SERIAL_PROTOCOLLNRPGM(MSG_OK);
  5087. }
  5088. void get_coordinates()
  5089. {
  5090. bool seen[4]={false,false,false,false};
  5091. for(int8_t i=0; i < NUM_AXIS; i++) {
  5092. if(code_seen(axis_codes[i]))
  5093. {
  5094. destination[i] = (float)code_value() + (axis_relative_modes[i] || relative_mode)*current_position[i];
  5095. seen[i]=true;
  5096. }
  5097. else destination[i] = current_position[i]; //Are these else lines really needed?
  5098. }
  5099. if(code_seen('F')) {
  5100. next_feedrate = code_value();
  5101. #ifdef MAX_SILENT_FEEDRATE
  5102. if (tmc2130_mode == TMC2130_MODE_SILENT)
  5103. if (next_feedrate > MAX_SILENT_FEEDRATE) next_feedrate = MAX_SILENT_FEEDRATE;
  5104. #endif //MAX_SILENT_FEEDRATE
  5105. if(next_feedrate > 0.0) feedrate = next_feedrate;
  5106. }
  5107. }
  5108. void get_arc_coordinates()
  5109. {
  5110. #ifdef SF_ARC_FIX
  5111. bool relative_mode_backup = relative_mode;
  5112. relative_mode = true;
  5113. #endif
  5114. get_coordinates();
  5115. #ifdef SF_ARC_FIX
  5116. relative_mode=relative_mode_backup;
  5117. #endif
  5118. if(code_seen('I')) {
  5119. offset[0] = code_value();
  5120. }
  5121. else {
  5122. offset[0] = 0.0;
  5123. }
  5124. if(code_seen('J')) {
  5125. offset[1] = code_value();
  5126. }
  5127. else {
  5128. offset[1] = 0.0;
  5129. }
  5130. }
  5131. void clamp_to_software_endstops(float target[3])
  5132. {
  5133. #ifdef DEBUG_DISABLE_SWLIMITS
  5134. return;
  5135. #endif //DEBUG_DISABLE_SWLIMITS
  5136. world2machine_clamp(target[0], target[1]);
  5137. // Clamp the Z coordinate.
  5138. if (min_software_endstops) {
  5139. float negative_z_offset = 0;
  5140. #ifdef ENABLE_AUTO_BED_LEVELING
  5141. if (Z_PROBE_OFFSET_FROM_EXTRUDER < 0) negative_z_offset = negative_z_offset + Z_PROBE_OFFSET_FROM_EXTRUDER;
  5142. if (add_homing[Z_AXIS] < 0) negative_z_offset = negative_z_offset + add_homing[Z_AXIS];
  5143. #endif
  5144. if (target[Z_AXIS] < min_pos[Z_AXIS]+negative_z_offset) target[Z_AXIS] = min_pos[Z_AXIS]+negative_z_offset;
  5145. }
  5146. if (max_software_endstops) {
  5147. if (target[Z_AXIS] > max_pos[Z_AXIS]) target[Z_AXIS] = max_pos[Z_AXIS];
  5148. }
  5149. }
  5150. #ifdef MESH_BED_LEVELING
  5151. 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) {
  5152. float dx = x - current_position[X_AXIS];
  5153. float dy = y - current_position[Y_AXIS];
  5154. float dz = z - current_position[Z_AXIS];
  5155. int n_segments = 0;
  5156. if (mbl.active) {
  5157. float len = abs(dx) + abs(dy);
  5158. if (len > 0)
  5159. // Split to 3cm segments or shorter.
  5160. n_segments = int(ceil(len / 30.f));
  5161. }
  5162. if (n_segments > 1) {
  5163. float de = e - current_position[E_AXIS];
  5164. for (int i = 1; i < n_segments; ++ i) {
  5165. float t = float(i) / float(n_segments);
  5166. plan_buffer_line(
  5167. current_position[X_AXIS] + t * dx,
  5168. current_position[Y_AXIS] + t * dy,
  5169. current_position[Z_AXIS] + t * dz,
  5170. current_position[E_AXIS] + t * de,
  5171. feed_rate, extruder);
  5172. }
  5173. }
  5174. // The rest of the path.
  5175. plan_buffer_line(x, y, z, e, feed_rate, extruder);
  5176. current_position[X_AXIS] = x;
  5177. current_position[Y_AXIS] = y;
  5178. current_position[Z_AXIS] = z;
  5179. current_position[E_AXIS] = e;
  5180. }
  5181. #endif // MESH_BED_LEVELING
  5182. void prepare_move()
  5183. {
  5184. clamp_to_software_endstops(destination);
  5185. previous_millis_cmd = millis();
  5186. // Do not use feedmultiply for E or Z only moves
  5187. if( (current_position[X_AXIS] == destination [X_AXIS]) && (current_position[Y_AXIS] == destination [Y_AXIS])) {
  5188. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder);
  5189. }
  5190. else {
  5191. #ifdef MESH_BED_LEVELING
  5192. 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);
  5193. #else
  5194. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate*feedmultiply*(1./(60.f*100.f)), active_extruder);
  5195. #endif
  5196. }
  5197. for(int8_t i=0; i < NUM_AXIS; i++) {
  5198. current_position[i] = destination[i];
  5199. }
  5200. }
  5201. void prepare_arc_move(char isclockwise) {
  5202. float r = hypot(offset[X_AXIS], offset[Y_AXIS]); // Compute arc radius for mc_arc
  5203. // Trace the arc
  5204. mc_arc(current_position, destination, offset, X_AXIS, Y_AXIS, Z_AXIS, feedrate*feedmultiply/60/100.0, r, isclockwise, active_extruder);
  5205. // As far as the parser is concerned, the position is now == target. In reality the
  5206. // motion control system might still be processing the action and the real tool position
  5207. // in any intermediate location.
  5208. for(int8_t i=0; i < NUM_AXIS; i++) {
  5209. current_position[i] = destination[i];
  5210. }
  5211. previous_millis_cmd = millis();
  5212. }
  5213. #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1
  5214. #if defined(FAN_PIN)
  5215. #if CONTROLLERFAN_PIN == FAN_PIN
  5216. #error "You cannot set CONTROLLERFAN_PIN equal to FAN_PIN"
  5217. #endif
  5218. #endif
  5219. unsigned long lastMotor = 0; //Save the time for when a motor was turned on last
  5220. unsigned long lastMotorCheck = 0;
  5221. void controllerFan()
  5222. {
  5223. if ((millis() - lastMotorCheck) >= 2500) //Not a time critical function, so we only check every 2500ms
  5224. {
  5225. lastMotorCheck = millis();
  5226. if(!READ(X_ENABLE_PIN) || !READ(Y_ENABLE_PIN) || !READ(Z_ENABLE_PIN) || (soft_pwm_bed > 0)
  5227. #if EXTRUDERS > 2
  5228. || !READ(E2_ENABLE_PIN)
  5229. #endif
  5230. #if EXTRUDER > 1
  5231. #if defined(X2_ENABLE_PIN) && X2_ENABLE_PIN > -1
  5232. || !READ(X2_ENABLE_PIN)
  5233. #endif
  5234. || !READ(E1_ENABLE_PIN)
  5235. #endif
  5236. || !READ(E0_ENABLE_PIN)) //If any of the drivers are enabled...
  5237. {
  5238. lastMotor = millis(); //... set time to NOW so the fan will turn on
  5239. }
  5240. if ((millis() - lastMotor) >= (CONTROLLERFAN_SECS*1000UL) || lastMotor == 0) //If the last time any driver was enabled, is longer since than CONTROLLERSEC...
  5241. {
  5242. digitalWrite(CONTROLLERFAN_PIN, 0);
  5243. analogWrite(CONTROLLERFAN_PIN, 0);
  5244. }
  5245. else
  5246. {
  5247. // allows digital or PWM fan output to be used (see M42 handling)
  5248. digitalWrite(CONTROLLERFAN_PIN, CONTROLLERFAN_SPEED);
  5249. analogWrite(CONTROLLERFAN_PIN, CONTROLLERFAN_SPEED);
  5250. }
  5251. }
  5252. }
  5253. #endif
  5254. #ifdef TEMP_STAT_LEDS
  5255. static bool blue_led = false;
  5256. static bool red_led = false;
  5257. static uint32_t stat_update = 0;
  5258. void handle_status_leds(void) {
  5259. float max_temp = 0.0;
  5260. if(millis() > stat_update) {
  5261. stat_update += 500; // Update every 0.5s
  5262. for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
  5263. max_temp = max(max_temp, degHotend(cur_extruder));
  5264. max_temp = max(max_temp, degTargetHotend(cur_extruder));
  5265. }
  5266. #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1
  5267. max_temp = max(max_temp, degTargetBed());
  5268. max_temp = max(max_temp, degBed());
  5269. #endif
  5270. if((max_temp > 55.0) && (red_led == false)) {
  5271. digitalWrite(STAT_LED_RED, 1);
  5272. digitalWrite(STAT_LED_BLUE, 0);
  5273. red_led = true;
  5274. blue_led = false;
  5275. }
  5276. if((max_temp < 54.0) && (blue_led == false)) {
  5277. digitalWrite(STAT_LED_RED, 0);
  5278. digitalWrite(STAT_LED_BLUE, 1);
  5279. red_led = false;
  5280. blue_led = true;
  5281. }
  5282. }
  5283. }
  5284. #endif
  5285. void manage_inactivity(bool ignore_stepper_queue/*=false*/) //default argument set in Marlin.h
  5286. {
  5287. #if defined(KILL_PIN) && KILL_PIN > -1
  5288. static int killCount = 0; // make the inactivity button a bit less responsive
  5289. const int KILL_DELAY = 10000;
  5290. #endif
  5291. if(buflen < (BUFSIZE-1)){
  5292. get_command();
  5293. }
  5294. if( (millis() - previous_millis_cmd) > max_inactive_time )
  5295. if(max_inactive_time)
  5296. kill("", 4);
  5297. if(stepper_inactive_time) {
  5298. if( (millis() - previous_millis_cmd) > stepper_inactive_time )
  5299. {
  5300. if(blocks_queued() == false && ignore_stepper_queue == false) {
  5301. disable_x();
  5302. // SERIAL_ECHOLNPGM("manage_inactivity - disable Y");
  5303. disable_y();
  5304. disable_z();
  5305. disable_e0();
  5306. disable_e1();
  5307. disable_e2();
  5308. }
  5309. }
  5310. }
  5311. #ifdef CHDK //Check if pin should be set to LOW after M240 set it to HIGH
  5312. if (chdkActive && (millis() - chdkHigh > CHDK_DELAY))
  5313. {
  5314. chdkActive = false;
  5315. WRITE(CHDK, LOW);
  5316. }
  5317. #endif
  5318. #if defined(KILL_PIN) && KILL_PIN > -1
  5319. // Check if the kill button was pressed and wait just in case it was an accidental
  5320. // key kill key press
  5321. // -------------------------------------------------------------------------------
  5322. if( 0 == READ(KILL_PIN) )
  5323. {
  5324. killCount++;
  5325. }
  5326. else if (killCount > 0)
  5327. {
  5328. killCount--;
  5329. }
  5330. // Exceeded threshold and we can confirm that it was not accidental
  5331. // KILL the machine
  5332. // ----------------------------------------------------------------
  5333. if ( killCount >= KILL_DELAY)
  5334. {
  5335. kill("", 5);
  5336. }
  5337. #endif
  5338. #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1
  5339. controllerFan(); //Check if fan should be turned on to cool stepper drivers down
  5340. #endif
  5341. #ifdef EXTRUDER_RUNOUT_PREVENT
  5342. if( (millis() - previous_millis_cmd) > EXTRUDER_RUNOUT_SECONDS*1000 )
  5343. if(degHotend(active_extruder)>EXTRUDER_RUNOUT_MINTEMP)
  5344. {
  5345. bool oldstatus=READ(E0_ENABLE_PIN);
  5346. enable_e0();
  5347. float oldepos=current_position[E_AXIS];
  5348. float oldedes=destination[E_AXIS];
  5349. plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS],
  5350. destination[E_AXIS]+EXTRUDER_RUNOUT_EXTRUDE*EXTRUDER_RUNOUT_ESTEPS/axis_steps_per_unit[E_AXIS],
  5351. EXTRUDER_RUNOUT_SPEED/60.*EXTRUDER_RUNOUT_ESTEPS/axis_steps_per_unit[E_AXIS], active_extruder);
  5352. current_position[E_AXIS]=oldepos;
  5353. destination[E_AXIS]=oldedes;
  5354. plan_set_e_position(oldepos);
  5355. previous_millis_cmd=millis();
  5356. st_synchronize();
  5357. WRITE(E0_ENABLE_PIN,oldstatus);
  5358. }
  5359. #endif
  5360. #ifdef TEMP_STAT_LEDS
  5361. handle_status_leds();
  5362. #endif
  5363. check_axes_activity();
  5364. }
  5365. void kill(const char *full_screen_message, unsigned char id)
  5366. {
  5367. SERIAL_ECHOPGM("KILL: ");
  5368. MYSERIAL.println(int(id));
  5369. //return;
  5370. cli(); // Stop interrupts
  5371. disable_heater();
  5372. disable_x();
  5373. // SERIAL_ECHOLNPGM("kill - disable Y");
  5374. disable_y();
  5375. disable_z();
  5376. disable_e0();
  5377. disable_e1();
  5378. disable_e2();
  5379. #if defined(PS_ON_PIN) && PS_ON_PIN > -1
  5380. pinMode(PS_ON_PIN,INPUT);
  5381. #endif
  5382. SERIAL_ERROR_START;
  5383. SERIAL_ERRORLNRPGM(MSG_ERR_KILLED);
  5384. if (full_screen_message != NULL) {
  5385. SERIAL_ERRORLNRPGM(full_screen_message);
  5386. lcd_display_message_fullscreen_P(full_screen_message);
  5387. } else {
  5388. LCD_ALERTMESSAGERPGM(MSG_KILLED);
  5389. }
  5390. // FMC small patch to update the LCD before ending
  5391. sei(); // enable interrupts
  5392. for ( int i=5; i--; lcd_update())
  5393. {
  5394. delay(200);
  5395. }
  5396. cli(); // disable interrupts
  5397. suicide();
  5398. while(1) { /* Intentionally left empty */ } // Wait for reset
  5399. }
  5400. void Stop()
  5401. {
  5402. disable_heater();
  5403. if(Stopped == false) {
  5404. Stopped = true;
  5405. Stopped_gcode_LastN = gcode_LastN; // Save last g_code for restart
  5406. SERIAL_ERROR_START;
  5407. SERIAL_ERRORLNRPGM(MSG_ERR_STOPPED);
  5408. LCD_MESSAGERPGM(MSG_STOPPED);
  5409. }
  5410. }
  5411. bool IsStopped() { return Stopped; };
  5412. #ifdef FAST_PWM_FAN
  5413. void setPwmFrequency(uint8_t pin, int val)
  5414. {
  5415. val &= 0x07;
  5416. switch(digitalPinToTimer(pin))
  5417. {
  5418. #if defined(TCCR0A)
  5419. case TIMER0A:
  5420. case TIMER0B:
  5421. // TCCR0B &= ~(_BV(CS00) | _BV(CS01) | _BV(CS02));
  5422. // TCCR0B |= val;
  5423. break;
  5424. #endif
  5425. #if defined(TCCR1A)
  5426. case TIMER1A:
  5427. case TIMER1B:
  5428. // TCCR1B &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  5429. // TCCR1B |= val;
  5430. break;
  5431. #endif
  5432. #if defined(TCCR2)
  5433. case TIMER2:
  5434. case TIMER2:
  5435. TCCR2 &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  5436. TCCR2 |= val;
  5437. break;
  5438. #endif
  5439. #if defined(TCCR2A)
  5440. case TIMER2A:
  5441. case TIMER2B:
  5442. TCCR2B &= ~(_BV(CS20) | _BV(CS21) | _BV(CS22));
  5443. TCCR2B |= val;
  5444. break;
  5445. #endif
  5446. #if defined(TCCR3A)
  5447. case TIMER3A:
  5448. case TIMER3B:
  5449. case TIMER3C:
  5450. TCCR3B &= ~(_BV(CS30) | _BV(CS31) | _BV(CS32));
  5451. TCCR3B |= val;
  5452. break;
  5453. #endif
  5454. #if defined(TCCR4A)
  5455. case TIMER4A:
  5456. case TIMER4B:
  5457. case TIMER4C:
  5458. TCCR4B &= ~(_BV(CS40) | _BV(CS41) | _BV(CS42));
  5459. TCCR4B |= val;
  5460. break;
  5461. #endif
  5462. #if defined(TCCR5A)
  5463. case TIMER5A:
  5464. case TIMER5B:
  5465. case TIMER5C:
  5466. TCCR5B &= ~(_BV(CS50) | _BV(CS51) | _BV(CS52));
  5467. TCCR5B |= val;
  5468. break;
  5469. #endif
  5470. }
  5471. }
  5472. #endif //FAST_PWM_FAN
  5473. bool setTargetedHotend(int code){
  5474. tmp_extruder = active_extruder;
  5475. if(code_seen('T')) {
  5476. tmp_extruder = code_value();
  5477. if(tmp_extruder >= EXTRUDERS) {
  5478. SERIAL_ECHO_START;
  5479. switch(code){
  5480. case 104:
  5481. SERIAL_ECHORPGM(MSG_M104_INVALID_EXTRUDER);
  5482. break;
  5483. case 105:
  5484. SERIAL_ECHO(MSG_M105_INVALID_EXTRUDER);
  5485. break;
  5486. case 109:
  5487. SERIAL_ECHO(MSG_M109_INVALID_EXTRUDER);
  5488. break;
  5489. case 218:
  5490. SERIAL_ECHO(MSG_M218_INVALID_EXTRUDER);
  5491. break;
  5492. case 221:
  5493. SERIAL_ECHO(MSG_M221_INVALID_EXTRUDER);
  5494. break;
  5495. }
  5496. SERIAL_PROTOCOLLN((int)tmp_extruder);
  5497. return true;
  5498. }
  5499. }
  5500. return false;
  5501. }
  5502. void save_statistics(unsigned long _total_filament_used, unsigned long _total_print_time) //_total_filament_used unit: mm/100; print time in s
  5503. {
  5504. 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)
  5505. {
  5506. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, 0);
  5507. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, 0);
  5508. }
  5509. unsigned long _previous_filament = eeprom_read_dword((uint32_t *)EEPROM_FILAMENTUSED); //_previous_filament unit: cm
  5510. unsigned long _previous_time = eeprom_read_dword((uint32_t *)EEPROM_TOTALTIME); //_previous_time unit: min
  5511. eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, _previous_time + (_total_print_time/60)); //EEPROM_TOTALTIME unit: min
  5512. eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, _previous_filament + (_total_filament_used / 1000));
  5513. total_filament_used = 0;
  5514. }
  5515. float calculate_volumetric_multiplier(float diameter) {
  5516. float area = .0;
  5517. float radius = .0;
  5518. radius = diameter * .5;
  5519. if (! volumetric_enabled || radius == 0) {
  5520. area = 1;
  5521. }
  5522. else {
  5523. area = M_PI * pow(radius, 2);
  5524. }
  5525. return 1.0 / area;
  5526. }
  5527. void calculate_volumetric_multipliers() {
  5528. volumetric_multiplier[0] = calculate_volumetric_multiplier(filament_size[0]);
  5529. #if EXTRUDERS > 1
  5530. volumetric_multiplier[1] = calculate_volumetric_multiplier(filament_size[1]);
  5531. #if EXTRUDERS > 2
  5532. volumetric_multiplier[2] = calculate_volumetric_multiplier(filament_size[2]);
  5533. #endif
  5534. #endif
  5535. }
  5536. void delay_keep_alive(unsigned int ms)
  5537. {
  5538. for (;;) {
  5539. manage_heater();
  5540. // Manage inactivity, but don't disable steppers on timeout.
  5541. manage_inactivity(true);
  5542. lcd_update();
  5543. if (ms == 0)
  5544. break;
  5545. else if (ms >= 50) {
  5546. delay(50);
  5547. ms -= 50;
  5548. } else {
  5549. delay(ms);
  5550. ms = 0;
  5551. }
  5552. }
  5553. }
  5554. void wait_for_heater(long codenum) {
  5555. #ifdef TEMP_RESIDENCY_TIME
  5556. long residencyStart;
  5557. residencyStart = -1;
  5558. /* continue to loop until we have reached the target temp
  5559. _and_ until TEMP_RESIDENCY_TIME hasn't passed since we reached it */
  5560. while ((!cancel_heatup) && ((residencyStart == -1) ||
  5561. (residencyStart >= 0 && (((unsigned int)(millis() - residencyStart)) < (TEMP_RESIDENCY_TIME * 1000UL))))) {
  5562. #else
  5563. while (target_direction ? (isHeatingHotend(tmp_extruder)) : (isCoolingHotend(tmp_extruder) && (CooldownNoWait == false))) {
  5564. #endif //TEMP_RESIDENCY_TIME
  5565. if ((millis() - codenum) > 1000UL)
  5566. { //Print Temp Reading and remaining time every 1 second while heating up/cooling down
  5567. if (!farm_mode) {
  5568. SERIAL_PROTOCOLPGM("T:");
  5569. SERIAL_PROTOCOL_F(degHotend(tmp_extruder), 1);
  5570. SERIAL_PROTOCOLPGM(" E:");
  5571. SERIAL_PROTOCOL((int)tmp_extruder);
  5572. #ifdef TEMP_RESIDENCY_TIME
  5573. SERIAL_PROTOCOLPGM(" W:");
  5574. if (residencyStart > -1)
  5575. {
  5576. codenum = ((TEMP_RESIDENCY_TIME * 1000UL) - (millis() - residencyStart)) / 1000UL;
  5577. SERIAL_PROTOCOLLN(codenum);
  5578. }
  5579. else
  5580. {
  5581. SERIAL_PROTOCOLLN("?");
  5582. }
  5583. }
  5584. #else
  5585. SERIAL_PROTOCOLLN("");
  5586. #endif
  5587. codenum = millis();
  5588. }
  5589. manage_heater();
  5590. manage_inactivity();
  5591. lcd_update();
  5592. #ifdef TEMP_RESIDENCY_TIME
  5593. /* start/restart the TEMP_RESIDENCY_TIME timer whenever we reach target temp for the first time
  5594. or when current temp falls outside the hysteresis after target temp was reached */
  5595. if ((residencyStart == -1 && target_direction && (degHotend(tmp_extruder) >= (degTargetHotend(tmp_extruder) - TEMP_WINDOW))) ||
  5596. (residencyStart == -1 && !target_direction && (degHotend(tmp_extruder) <= (degTargetHotend(tmp_extruder) + TEMP_WINDOW))) ||
  5597. (residencyStart > -1 && labs(degHotend(tmp_extruder) - degTargetHotend(tmp_extruder)) > TEMP_HYSTERESIS))
  5598. {
  5599. residencyStart = millis();
  5600. }
  5601. #endif //TEMP_RESIDENCY_TIME
  5602. }
  5603. }
  5604. void check_babystep() {
  5605. int babystep_z;
  5606. EEPROM_read_B(EEPROM_BABYSTEP_Z, &babystep_z);
  5607. if ((babystep_z < Z_BABYSTEP_MIN) || (babystep_z > Z_BABYSTEP_MAX)) {
  5608. babystep_z = 0; //if babystep value is out of min max range, set it to 0
  5609. SERIAL_ECHOLNPGM("Z live adjust out of range. Setting to 0");
  5610. EEPROM_save_B(EEPROM_BABYSTEP_Z, &babystep_z);
  5611. lcd_show_fullscreen_message_and_wait_P(PSTR("Z live adjust out of range. Setting to 0. Click to continue."));
  5612. lcd_update_enable(true);
  5613. }
  5614. }
  5615. #ifdef DIS
  5616. void d_setup()
  5617. {
  5618. pinMode(D_DATACLOCK, INPUT_PULLUP);
  5619. pinMode(D_DATA, INPUT_PULLUP);
  5620. pinMode(D_REQUIRE, OUTPUT);
  5621. digitalWrite(D_REQUIRE, HIGH);
  5622. }
  5623. float d_ReadData()
  5624. {
  5625. int digit[13];
  5626. String mergeOutput;
  5627. float output;
  5628. digitalWrite(D_REQUIRE, HIGH);
  5629. for (int i = 0; i<13; i++)
  5630. {
  5631. for (int j = 0; j < 4; j++)
  5632. {
  5633. while (digitalRead(D_DATACLOCK) == LOW) {}
  5634. while (digitalRead(D_DATACLOCK) == HIGH) {}
  5635. bitWrite(digit[i], j, digitalRead(D_DATA));
  5636. }
  5637. }
  5638. digitalWrite(D_REQUIRE, LOW);
  5639. mergeOutput = "";
  5640. output = 0;
  5641. for (int r = 5; r <= 10; r++) //Merge digits
  5642. {
  5643. mergeOutput += digit[r];
  5644. }
  5645. output = mergeOutput.toFloat();
  5646. if (digit[4] == 8) //Handle sign
  5647. {
  5648. output *= -1;
  5649. }
  5650. for (int i = digit[11]; i > 0; i--) //Handle floating point
  5651. {
  5652. output /= 10;
  5653. }
  5654. return output;
  5655. }
  5656. void bed_analysis(float x_dimension, float y_dimension, int x_points_num, int y_points_num, float shift_x, float shift_y) {
  5657. int t1 = 0;
  5658. int t_delay = 0;
  5659. int digit[13];
  5660. int m;
  5661. char str[3];
  5662. //String mergeOutput;
  5663. char mergeOutput[15];
  5664. float output;
  5665. int mesh_point = 0; //index number of calibration point
  5666. 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
  5667. float bed_zero_ref_y = (-0.6f + Y_PROBE_OFFSET_FROM_EXTRUDER);
  5668. float mesh_home_z_search = 4;
  5669. float row[x_points_num];
  5670. int ix = 0;
  5671. int iy = 0;
  5672. char* filename_wldsd = "wldsd.txt";
  5673. char data_wldsd[70];
  5674. char numb_wldsd[10];
  5675. d_setup();
  5676. if (!(axis_known_position[X_AXIS] && axis_known_position[Y_AXIS] && axis_known_position[Z_AXIS])) {
  5677. // We don't know where we are! HOME!
  5678. // Push the commands to the front of the message queue in the reverse order!
  5679. // There shall be always enough space reserved for these commands.
  5680. repeatcommand_front(); // repeat G80 with all its parameters
  5681. enquecommand_front_P((PSTR("G28 W0")));
  5682. enquecommand_front_P((PSTR("G1 Z5")));
  5683. return;
  5684. }
  5685. bool custom_message_old = custom_message;
  5686. unsigned int custom_message_type_old = custom_message_type;
  5687. unsigned int custom_message_state_old = custom_message_state;
  5688. custom_message = true;
  5689. custom_message_type = 1;
  5690. custom_message_state = (x_points_num * y_points_num) + 10;
  5691. lcd_update(1);
  5692. mbl.reset();
  5693. babystep_undo();
  5694. card.openFile(filename_wldsd, false);
  5695. current_position[Z_AXIS] = mesh_home_z_search;
  5696. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], homing_feedrate[Z_AXIS] / 60, active_extruder);
  5697. int XY_AXIS_FEEDRATE = homing_feedrate[X_AXIS] / 20;
  5698. int Z_PROBE_FEEDRATE = homing_feedrate[Z_AXIS] / 60;
  5699. int Z_LIFT_FEEDRATE = homing_feedrate[Z_AXIS] / 40;
  5700. setup_for_endstop_move(false);
  5701. SERIAL_PROTOCOLPGM("Num X,Y: ");
  5702. SERIAL_PROTOCOL(x_points_num);
  5703. SERIAL_PROTOCOLPGM(",");
  5704. SERIAL_PROTOCOL(y_points_num);
  5705. SERIAL_PROTOCOLPGM("\nZ search height: ");
  5706. SERIAL_PROTOCOL(mesh_home_z_search);
  5707. SERIAL_PROTOCOLPGM("\nDimension X,Y: ");
  5708. SERIAL_PROTOCOL(x_dimension);
  5709. SERIAL_PROTOCOLPGM(",");
  5710. SERIAL_PROTOCOL(y_dimension);
  5711. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  5712. while (mesh_point != x_points_num * y_points_num) {
  5713. ix = mesh_point % x_points_num; // from 0 to MESH_NUM_X_POINTS - 1
  5714. iy = mesh_point / x_points_num;
  5715. if (iy & 1) ix = (x_points_num - 1) - ix; // Zig zag
  5716. float z0 = 0.f;
  5717. current_position[Z_AXIS] = mesh_home_z_search;
  5718. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], Z_LIFT_FEEDRATE, active_extruder);
  5719. st_synchronize();
  5720. current_position[X_AXIS] = 13.f + ix * (x_dimension / (x_points_num - 1)) - bed_zero_ref_x + shift_x;
  5721. current_position[Y_AXIS] = 6.4f + iy * (y_dimension / (y_points_num - 1)) - bed_zero_ref_y + shift_y;
  5722. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], XY_AXIS_FEEDRATE, active_extruder);
  5723. st_synchronize();
  5724. 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
  5725. break;
  5726. card.closefile();
  5727. }
  5728. //memset(numb_wldsd, 0, sizeof(numb_wldsd));
  5729. //dtostrf(d_ReadData(), 8, 5, numb_wldsd);
  5730. //strcat(data_wldsd, numb_wldsd);
  5731. //MYSERIAL.println(data_wldsd);
  5732. //delay(1000);
  5733. //delay(3000);
  5734. //t1 = millis();
  5735. //while (digitalRead(D_DATACLOCK) == LOW) {}
  5736. //while (digitalRead(D_DATACLOCK) == HIGH) {}
  5737. memset(digit, 0, sizeof(digit));
  5738. //cli();
  5739. digitalWrite(D_REQUIRE, LOW);
  5740. for (int i = 0; i<13; i++)
  5741. {
  5742. //t1 = millis();
  5743. for (int j = 0; j < 4; j++)
  5744. {
  5745. while (digitalRead(D_DATACLOCK) == LOW) {}
  5746. while (digitalRead(D_DATACLOCK) == HIGH) {}
  5747. bitWrite(digit[i], j, digitalRead(D_DATA));
  5748. }
  5749. //t_delay = (millis() - t1);
  5750. //SERIAL_PROTOCOLPGM(" ");
  5751. //SERIAL_PROTOCOL_F(t_delay, 5);
  5752. //SERIAL_PROTOCOLPGM(" ");
  5753. }
  5754. //sei();
  5755. digitalWrite(D_REQUIRE, HIGH);
  5756. mergeOutput[0] = '\0';
  5757. output = 0;
  5758. for (int r = 5; r <= 10; r++) //Merge digits
  5759. {
  5760. sprintf(str, "%d", digit[r]);
  5761. strcat(mergeOutput, str);
  5762. }
  5763. output = atof(mergeOutput);
  5764. if (digit[4] == 8) //Handle sign
  5765. {
  5766. output *= -1;
  5767. }
  5768. for (int i = digit[11]; i > 0; i--) //Handle floating point
  5769. {
  5770. output *= 0.1;
  5771. }
  5772. //output = d_ReadData();
  5773. //row[ix] = current_position[Z_AXIS];
  5774. memset(data_wldsd, 0, sizeof(data_wldsd));
  5775. for (int i = 0; i <3; i++) {
  5776. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  5777. dtostrf(current_position[i], 8, 5, numb_wldsd);
  5778. strcat(data_wldsd, numb_wldsd);
  5779. strcat(data_wldsd, ";");
  5780. }
  5781. memset(numb_wldsd, 0, sizeof(numb_wldsd));
  5782. dtostrf(output, 8, 5, numb_wldsd);
  5783. strcat(data_wldsd, numb_wldsd);
  5784. //strcat(data_wldsd, ";");
  5785. card.write_command(data_wldsd);
  5786. //row[ix] = d_ReadData();
  5787. row[ix] = output; // current_position[Z_AXIS];
  5788. if (iy % 2 == 1 ? ix == 0 : ix == x_points_num - 1) {
  5789. for (int i = 0; i < x_points_num; i++) {
  5790. SERIAL_PROTOCOLPGM(" ");
  5791. SERIAL_PROTOCOL_F(row[i], 5);
  5792. }
  5793. SERIAL_PROTOCOLPGM("\n");
  5794. }
  5795. custom_message_state--;
  5796. mesh_point++;
  5797. lcd_update(1);
  5798. }
  5799. card.closefile();
  5800. }
  5801. #endif
  5802. void temp_compensation_start() {
  5803. custom_message = true;
  5804. custom_message_type = 5;
  5805. custom_message_state = PINDA_HEAT_T + 1;
  5806. lcd_update(2);
  5807. if (degHotend(active_extruder) > EXTRUDE_MINTEMP) {
  5808. current_position[E_AXIS] -= DEFAULT_RETRACTION;
  5809. }
  5810. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 400, active_extruder);
  5811. current_position[X_AXIS] = PINDA_PREHEAT_X;
  5812. current_position[Y_AXIS] = PINDA_PREHEAT_Y;
  5813. current_position[Z_AXIS] = PINDA_PREHEAT_Z;
  5814. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 3000 / 60, active_extruder);
  5815. st_synchronize();
  5816. while (fabs(degBed() - target_temperature_bed) > 1) delay_keep_alive(1000);
  5817. for (int i = 0; i < PINDA_HEAT_T; i++) {
  5818. delay_keep_alive(1000);
  5819. custom_message_state = PINDA_HEAT_T - i;
  5820. if (custom_message_state == 99 || custom_message_state == 9) lcd_update(2); //force whole display redraw if number of digits changed
  5821. else lcd_update(1);
  5822. }
  5823. custom_message_type = 0;
  5824. custom_message_state = 0;
  5825. custom_message = false;
  5826. }
  5827. void temp_compensation_apply() {
  5828. int i_add;
  5829. int compensation_value;
  5830. int z_shift = 0;
  5831. float z_shift_mm;
  5832. if (calibration_status() == CALIBRATION_STATUS_CALIBRATED) {
  5833. if (target_temperature_bed % 10 == 0 && target_temperature_bed >= 60 && target_temperature_bed <= 100) {
  5834. i_add = (target_temperature_bed - 60) / 10;
  5835. EEPROM_read_B(EEPROM_PROBE_TEMP_SHIFT + i_add * 2, &z_shift);
  5836. z_shift_mm = z_shift / axis_steps_per_unit[Z_AXIS];
  5837. }else {
  5838. //interpolation
  5839. z_shift_mm = temp_comp_interpolation(target_temperature_bed) / axis_steps_per_unit[Z_AXIS];
  5840. }
  5841. SERIAL_PROTOCOLPGM("\n");
  5842. SERIAL_PROTOCOLPGM("Z shift applied:");
  5843. MYSERIAL.print(z_shift_mm);
  5844. 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);
  5845. st_synchronize();
  5846. plan_set_z_position(current_position[Z_AXIS]);
  5847. }
  5848. else {
  5849. //we have no temp compensation data
  5850. }
  5851. }
  5852. float temp_comp_interpolation(float inp_temperature) {
  5853. //cubic spline interpolation
  5854. int n, i, j, k;
  5855. float h[10], a, b, c, d, sum, s[10] = { 0 }, x[10], F[10], f[10], m[10][10] = { 0 }, temp;
  5856. int shift[10];
  5857. int temp_C[10];
  5858. n = 6; //number of measured points
  5859. shift[0] = 0;
  5860. for (i = 0; i < n; i++) {
  5861. if (i>0) EEPROM_read_B(EEPROM_PROBE_TEMP_SHIFT + (i-1) * 2, &shift[i]); //read shift in steps from EEPROM
  5862. temp_C[i] = 50 + i * 10; //temperature in C
  5863. #ifdef PINDA_THERMISTOR
  5864. temp_C[i] = 35 + i * 5; //temperature in C
  5865. #else
  5866. temp_C[i] = 50 + i * 10; //temperature in C
  5867. #endif
  5868. x[i] = (float)temp_C[i];
  5869. f[i] = (float)shift[i];
  5870. }
  5871. if (inp_temperature < x[0]) return 0;
  5872. for (i = n - 1; i>0; i--) {
  5873. F[i] = (f[i] - f[i - 1]) / (x[i] - x[i - 1]);
  5874. h[i - 1] = x[i] - x[i - 1];
  5875. }
  5876. //*********** formation of h, s , f matrix **************
  5877. for (i = 1; i<n - 1; i++) {
  5878. m[i][i] = 2 * (h[i - 1] + h[i]);
  5879. if (i != 1) {
  5880. m[i][i - 1] = h[i - 1];
  5881. m[i - 1][i] = h[i - 1];
  5882. }
  5883. m[i][n - 1] = 6 * (F[i + 1] - F[i]);
  5884. }
  5885. //*********** forward elimination **************
  5886. for (i = 1; i<n - 2; i++) {
  5887. temp = (m[i + 1][i] / m[i][i]);
  5888. for (j = 1; j <= n - 1; j++)
  5889. m[i + 1][j] -= temp*m[i][j];
  5890. }
  5891. //*********** backward substitution *********
  5892. for (i = n - 2; i>0; i--) {
  5893. sum = 0;
  5894. for (j = i; j <= n - 2; j++)
  5895. sum += m[i][j] * s[j];
  5896. s[i] = (m[i][n - 1] - sum) / m[i][i];
  5897. }
  5898. for (i = 0; i<n - 1; i++)
  5899. if ((x[i] <= inp_temperature && inp_temperature <= x[i + 1]) || (i == n-2 && inp_temperature > x[i + 1])) {
  5900. a = (s[i + 1] - s[i]) / (6 * h[i]);
  5901. b = s[i] / 2;
  5902. c = (f[i + 1] - f[i]) / h[i] - (2 * h[i] * s[i] + s[i + 1] * h[i]) / 6;
  5903. d = f[i];
  5904. sum = a*pow((inp_temperature - x[i]), 3) + b*pow((inp_temperature - x[i]), 2) + c*(inp_temperature - x[i]) + d;
  5905. }
  5906. return sum;
  5907. }
  5908. #ifdef PINDA_THERMISTOR
  5909. float temp_compensation_pinda_thermistor_offset()
  5910. {
  5911. if (!temp_cal_active) return 0;
  5912. if (!calibration_status_pinda()) return 0;
  5913. return temp_comp_interpolation(current_temperature_pinda) / axis_steps_per_unit[Z_AXIS];
  5914. }
  5915. #endif //PINDA_THERMISTOR
  5916. void long_pause() //long pause print
  5917. {
  5918. st_synchronize();
  5919. //save currently set parameters to global variables
  5920. saved_feedmultiply = feedmultiply;
  5921. HotendTempBckp = degTargetHotend(active_extruder);
  5922. fanSpeedBckp = fanSpeed;
  5923. start_pause_print = millis();
  5924. //save position
  5925. pause_lastpos[X_AXIS] = current_position[X_AXIS];
  5926. pause_lastpos[Y_AXIS] = current_position[Y_AXIS];
  5927. pause_lastpos[Z_AXIS] = current_position[Z_AXIS];
  5928. pause_lastpos[E_AXIS] = current_position[E_AXIS];
  5929. //retract
  5930. current_position[E_AXIS] -= DEFAULT_RETRACTION;
  5931. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 400, active_extruder);
  5932. //lift z
  5933. current_position[Z_AXIS] += Z_PAUSE_LIFT;
  5934. if (current_position[Z_AXIS] > Z_MAX_POS) current_position[Z_AXIS] = Z_MAX_POS;
  5935. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 15, active_extruder);
  5936. //set nozzle target temperature to 0
  5937. setTargetHotend(0, 0);
  5938. setTargetHotend(0, 1);
  5939. setTargetHotend(0, 2);
  5940. //Move XY to side
  5941. current_position[X_AXIS] = X_PAUSE_POS;
  5942. current_position[Y_AXIS] = Y_PAUSE_POS;
  5943. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 50, active_extruder);
  5944. // Turn off the print fan
  5945. fanSpeed = 0;
  5946. st_synchronize();
  5947. }
  5948. void serialecho_temperatures() {
  5949. float tt = degHotend(active_extruder);
  5950. SERIAL_PROTOCOLPGM("T:");
  5951. SERIAL_PROTOCOL(tt);
  5952. SERIAL_PROTOCOLPGM(" E:");
  5953. SERIAL_PROTOCOL((int)active_extruder);
  5954. SERIAL_PROTOCOLPGM(" B:");
  5955. SERIAL_PROTOCOL_F(degBed(), 1);
  5956. SERIAL_PROTOCOLLN("");
  5957. }
  5958. extern uint32_t sdpos_atomic;
  5959. void uvlo_()
  5960. {
  5961. // Conserve power as soon as possible.
  5962. disable_x();
  5963. disable_y();
  5964. // Indicate that the interrupt has been triggered.
  5965. SERIAL_ECHOLNPGM("UVLO");
  5966. // Read out the current Z motor microstep counter. This will be later used
  5967. // for reaching the zero full step before powering off.
  5968. uint16_t z_microsteps = tmc2130_rd_MSCNT(Z_TMC2130_CS);
  5969. // Calculate the file position, from which to resume this print.
  5970. long sd_position = sdpos_atomic; //atomic sd position of last command added in queue
  5971. {
  5972. uint16_t sdlen_planner = planner_calc_sd_length(); //length of sd commands in planner
  5973. sd_position -= sdlen_planner;
  5974. uint16_t sdlen_cmdqueue = cmdqueue_calc_sd_length(); //length of sd commands in cmdqueue
  5975. sd_position -= sdlen_cmdqueue;
  5976. if (sd_position < 0) sd_position = 0;
  5977. }
  5978. // Backup the feedrate in mm/min.
  5979. int feedrate_bckp = blocks_queued() ? (block_buffer[block_buffer_tail].nominal_speed * 60.f) : feedrate;
  5980. // After this call, the planner queue is emptied and the current_position is set to a current logical coordinate.
  5981. // The logical coordinate will likely differ from the machine coordinate if the skew calibration and mesh bed leveling
  5982. // are in action.
  5983. planner_abort_hard();
  5984. // Clean the input command queue.
  5985. cmdqueue_reset();
  5986. card.sdprinting = false;
  5987. // card.closefile();
  5988. // Enable stepper driver interrupt to move Z axis.
  5989. // This should be fine as the planner and command queues are empty and the SD card printing is disabled.
  5990. //FIXME one may want to disable serial lines at this point of time to avoid interfering with the command queue,
  5991. // though it should not happen that the command queue is touched as the plan_buffer_line always succeed without blocking.
  5992. sei();
  5993. plan_buffer_line(
  5994. current_position[X_AXIS],
  5995. current_position[Y_AXIS],
  5996. current_position[Z_AXIS],
  5997. current_position[E_AXIS] - DEFAULT_RETRACTION,
  5998. 400, active_extruder);
  5999. plan_buffer_line(
  6000. current_position[X_AXIS],
  6001. current_position[Y_AXIS],
  6002. current_position[Z_AXIS] + UVLO_Z_AXIS_SHIFT + float((1024 - z_microsteps + 7) >> 4) / axis_steps_per_unit[Z_AXIS],
  6003. current_position[E_AXIS] - DEFAULT_RETRACTION,
  6004. 40, active_extruder);
  6005. // Move Z up to the next 0th full step.
  6006. // Write the file position.
  6007. eeprom_update_dword((uint32_t*)(EEPROM_FILE_POSITION), sd_position);
  6008. // Store the mesh bed leveling offsets. This is 2*9=18 bytes, which takes 18*3.4us=52us in worst case.
  6009. for (int8_t mesh_point = 0; mesh_point < 9; ++ mesh_point) {
  6010. uint8_t ix = mesh_point % MESH_MEAS_NUM_X_POINTS; // from 0 to MESH_NUM_X_POINTS - 1
  6011. uint8_t iy = mesh_point / MESH_MEAS_NUM_X_POINTS;
  6012. // Scale the z value to 1u resolution.
  6013. int16_t v = mbl.active ? int16_t(floor(mbl.z_values[iy*3][ix*3] * 1000.f + 0.5f)) : 0;
  6014. eeprom_update_word((uint16_t*)(EEPROM_UVLO_MESH_BED_LEVELING+2*mesh_point), *reinterpret_cast<uint16_t*>(&v));
  6015. }
  6016. // Read out the current Z motor microstep counter. This will be later used
  6017. // for reaching the zero full step before powering off.
  6018. eeprom_update_word((uint16_t*)(EEPROM_UVLO_Z_MICROSTEPS), z_microsteps);
  6019. // Store the current position.
  6020. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0), current_position[X_AXIS]);
  6021. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 4), current_position[Y_AXIS]);
  6022. eeprom_update_float((float*)(EEPROM_UVLO_CURRENT_POSITION_Z), current_position[Z_AXIS]);
  6023. // Store the current feed rate, temperatures and fan speed.
  6024. EEPROM_save_B(EEPROM_UVLO_FEEDRATE, &feedrate_bckp);
  6025. eeprom_update_byte((uint8_t*)EEPROM_UVLO_TARGET_HOTEND, target_temperature[active_extruder]);
  6026. eeprom_update_byte((uint8_t*)EEPROM_UVLO_TARGET_BED, target_temperature_bed);
  6027. eeprom_update_byte((uint8_t*)EEPROM_UVLO_FAN_SPEED, fanSpeed);
  6028. // Finaly store the "power outage" flag.
  6029. eeprom_update_byte((uint8_t*)EEPROM_UVLO, 1);
  6030. st_synchronize();
  6031. SERIAL_ECHOPGM("stps");
  6032. MYSERIAL.println(tmc2130_rd_MSCNT(Z_TMC2130_CS));
  6033. #if 0
  6034. // Move the print head to the side of the print until all the power stored in the power supply capacitors is depleted.
  6035. current_position[X_AXIS] = (current_position[X_AXIS] < 0.5f * (X_MIN_POS + X_MAX_POS)) ? X_MIN_POS : X_MAX_POS;
  6036. plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 500, active_extruder);
  6037. st_synchronize();
  6038. #endif
  6039. disable_z();
  6040. SERIAL_ECHOLNPGM("UVLO - end");
  6041. cli();
  6042. while(1);
  6043. }
  6044. void setup_uvlo_interrupt() {
  6045. DDRE &= ~(1 << 4); //input pin
  6046. PORTE &= ~(1 << 4); //no internal pull-up
  6047. //sensing falling edge
  6048. EICRB |= (1 << 0);
  6049. EICRB &= ~(1 << 1);
  6050. //enable INT4 interrupt
  6051. EIMSK |= (1 << 4);
  6052. }
  6053. ISR(INT4_vect) {
  6054. EIMSK &= ~(1 << 4); //disable INT4 interrupt to make sure that this code will be executed just once
  6055. SERIAL_ECHOLNPGM("INT4");
  6056. if (IS_SD_PRINTING) uvlo_();
  6057. }
  6058. void recover_print() {
  6059. char cmd[30];
  6060. lcd_update_enable(true);
  6061. lcd_update(2);
  6062. lcd_setstatuspgm(MSG_RECOVERING_PRINT);
  6063. recover_machine_state_after_power_panic();
  6064. // Lift the print head, so one may remove the excess priming material.
  6065. if (current_position[Z_AXIS] < 25)
  6066. enquecommand_P(PSTR("G1 Z25 F800"));
  6067. // Home X and Y axes. Homing just X and Y shall not touch the babystep and the world2machine transformation status.
  6068. enquecommand_P(PSTR("G28 X Y"));
  6069. // Set the target bed and nozzle temperatures.
  6070. sprintf_P(cmd, PSTR("M109 S%d"), target_temperature[active_extruder]);
  6071. enquecommand(cmd);
  6072. sprintf_P(cmd, PSTR("M190 S%d"), target_temperature_bed);
  6073. enquecommand(cmd);
  6074. enquecommand_P(PSTR("M83")); //E axis relative mode
  6075. enquecommand_P(PSTR("G1 E5 F120")); //Extrude some filament to stabilize pessure
  6076. enquecommand_P(PSTR("G1 E" STRINGIFY(-DEFAULT_RETRACTION)" F480"));
  6077. // Mark the power panic status as inactive.
  6078. eeprom_update_byte((uint8_t*)EEPROM_UVLO, 0);
  6079. /*while ((abs(degHotend(0)- target_temperature[0])>5) || (abs(degBed() -target_temperature_bed)>3)) { //wait for heater and bed to reach target temp
  6080. delay_keep_alive(1000);
  6081. }*/
  6082. SERIAL_ECHOPGM("After waiting for temp:");
  6083. SERIAL_ECHOPGM("Current position X_AXIS:");
  6084. MYSERIAL.println(current_position[X_AXIS]);
  6085. SERIAL_ECHOPGM("Current position Y_AXIS:");
  6086. MYSERIAL.println(current_position[Y_AXIS]);
  6087. // Restart the print.
  6088. restore_print_from_eeprom();
  6089. SERIAL_ECHOPGM("current_position[Z_AXIS]:");
  6090. MYSERIAL.print(current_position[Z_AXIS]);
  6091. }
  6092. void recover_machine_state_after_power_panic()
  6093. {
  6094. // 1) Recover the logical cordinates at the time of the power panic.
  6095. // The logical XY coordinates are needed to recover the machine Z coordinate corrected by the mesh bed leveling.
  6096. current_position[X_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0));
  6097. current_position[Y_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 4));
  6098. // Recover the logical coordinate of the Z axis at the time of the power panic.
  6099. // The current position after power panic is moved to the next closest 0th full step.
  6100. current_position[Z_AXIS] = eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_Z)) +
  6101. UVLO_Z_AXIS_SHIFT + float((1024 - eeprom_read_word((uint16_t*)(EEPROM_UVLO_Z_MICROSTEPS)) + 7) >> 4) / axis_steps_per_unit[Z_AXIS];
  6102. memcpy(destination, current_position, sizeof(destination));
  6103. SERIAL_ECHOPGM("recover_machine_state_after_power_panic, initial ");
  6104. print_world_coordinates();
  6105. // 2) Initialize the logical to physical coordinate system transformation.
  6106. world2machine_initialize();
  6107. // 3) Restore the mesh bed leveling offsets. This is 2*9=18 bytes, which takes 18*3.4us=52us in worst case.
  6108. mbl.active = false;
  6109. for (int8_t mesh_point = 0; mesh_point < 9; ++ mesh_point) {
  6110. uint8_t ix = mesh_point % MESH_MEAS_NUM_X_POINTS; // from 0 to MESH_NUM_X_POINTS - 1
  6111. uint8_t iy = mesh_point / MESH_MEAS_NUM_X_POINTS;
  6112. // Scale the z value to 10u resolution.
  6113. int16_t v;
  6114. eeprom_read_block(&v, (void*)(EEPROM_UVLO_MESH_BED_LEVELING+2*mesh_point), 2);
  6115. if (v != 0)
  6116. mbl.active = true;
  6117. mbl.z_values[iy][ix] = float(v) * 0.001f;
  6118. }
  6119. if (mbl.active)
  6120. mbl.upsample_3x3();
  6121. SERIAL_ECHOPGM("recover_machine_state_after_power_panic, initial ");
  6122. print_mesh_bed_leveling_table();
  6123. // 4) Load the baby stepping value, which is expected to be active at the time of power panic.
  6124. // The baby stepping value is used to reset the physical Z axis when rehoming the Z axis.
  6125. babystep_load();
  6126. // 5) Set the physical positions from the logical positions using the world2machine transformation and the active bed leveling.
  6127. plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  6128. // 6) Power up the motors, mark their positions as known.
  6129. //FIXME Verfiy, whether the X and Y axes should be powered up here, as they will later be re-homed anyway.
  6130. axis_known_position[X_AXIS] = true; enable_x();
  6131. axis_known_position[Y_AXIS] = true; enable_y();
  6132. axis_known_position[Z_AXIS] = true; enable_z();
  6133. SERIAL_ECHOPGM("recover_machine_state_after_power_panic, initial ");
  6134. print_physical_coordinates();
  6135. // 7) Recover the target temperatures.
  6136. target_temperature[active_extruder] = eeprom_read_byte((uint8_t*)EEPROM_UVLO_TARGET_HOTEND);
  6137. target_temperature_bed = eeprom_read_byte((uint8_t*)EEPROM_UVLO_TARGET_BED);
  6138. }
  6139. void restore_print_from_eeprom() {
  6140. float x_rec, y_rec, z_pos;
  6141. int feedrate_rec;
  6142. uint8_t fan_speed_rec;
  6143. char cmd[30];
  6144. char* c;
  6145. char filename[13];
  6146. fan_speed_rec = eeprom_read_byte((uint8_t*)EEPROM_UVLO_FAN_SPEED);
  6147. EEPROM_read_B(EEPROM_UVLO_FEEDRATE, &feedrate_rec);
  6148. SERIAL_ECHOPGM("Feedrate:");
  6149. MYSERIAL.println(feedrate_rec);
  6150. for (int i = 0; i < 8; i++) {
  6151. filename[i] = eeprom_read_byte((uint8_t*)EEPROM_FILENAME + i);
  6152. }
  6153. filename[8] = '\0';
  6154. MYSERIAL.print(filename);
  6155. strcat_P(filename, PSTR(".gco"));
  6156. sprintf_P(cmd, PSTR("M23 %s"), filename);
  6157. for (c = &cmd[4]; *c; c++)
  6158. *c = tolower(*c);
  6159. enquecommand(cmd);
  6160. uint32_t position = eeprom_read_dword((uint32_t*)(EEPROM_FILE_POSITION));
  6161. SERIAL_ECHOPGM("Position read from eeprom:");
  6162. MYSERIAL.println(position);
  6163. // E axis relative mode.
  6164. enquecommand_P(PSTR("M83"));
  6165. // Move to the XY print position in logical coordinates, where the print has been killed.
  6166. strcpy_P(cmd, PSTR("G1 X")); strcat(cmd, ftostr32(eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 0))));
  6167. strcat_P(cmd, PSTR(" Y")); strcat(cmd, ftostr32(eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION + 4))));
  6168. strcat_P(cmd, PSTR(" F2000"));
  6169. enquecommand(cmd);
  6170. // Move the Z axis down to the print, in logical coordinates.
  6171. strcpy_P(cmd, PSTR("G1 Z")); strcat(cmd, ftostr32(eeprom_read_float((float*)(EEPROM_UVLO_CURRENT_POSITION_Z))));
  6172. enquecommand(cmd);
  6173. // Unretract.
  6174. enquecommand_P(PSTR("G1 E" STRINGIFY(DEFAULT_RETRACTION)" F480"));
  6175. // Set the feedrate saved at the power panic.
  6176. sprintf_P(cmd, PSTR("G1 F%d"), feedrate_rec);
  6177. enquecommand(cmd);
  6178. // Set the fan speed saved at the power panic.
  6179. strcpy_P(cmd, PSTR("M106 S"));
  6180. strcat(cmd, itostr3(int(fan_speed_rec)));
  6181. enquecommand(cmd);
  6182. // Set a position in the file.
  6183. sprintf_P(cmd, PSTR("M26 S%lu"), position);
  6184. enquecommand(cmd);
  6185. // Start SD print.
  6186. enquecommand_P(PSTR("M24"));
  6187. }
  6188. ////////////////////////////////////////////////////////////////////////////////
  6189. // new save/restore printing
  6190. //extern uint32_t sdpos_atomic;
  6191. bool saved_printing = false;
  6192. uint32_t saved_sdpos = 0;
  6193. float saved_pos[4] = {0, 0, 0, 0};
  6194. // Feedrate hopefully derived from an active block of the planner at the time the print has been canceled, in mm/min.
  6195. float saved_feedrate2 = 0;
  6196. uint8_t saved_active_extruder = 0;
  6197. bool saved_extruder_under_pressure = false;
  6198. void stop_and_save_print_to_ram(float z_move, float e_move)
  6199. {
  6200. if (saved_printing) return;
  6201. cli();
  6202. unsigned char nplanner_blocks = number_of_blocks();
  6203. saved_sdpos = sdpos_atomic; //atomic sd position of last command added in queue
  6204. uint16_t sdlen_planner = planner_calc_sd_length(); //length of sd commands in planner
  6205. saved_sdpos -= sdlen_planner;
  6206. uint16_t sdlen_cmdqueue = cmdqueue_calc_sd_length(); //length of sd commands in cmdqueue
  6207. saved_sdpos -= sdlen_cmdqueue;
  6208. #if 0
  6209. SERIAL_ECHOPGM("SDPOS_ATOMIC="); MYSERIAL.println(sdpos_atomic, DEC);
  6210. SERIAL_ECHOPGM("SDPOS="); MYSERIAL.println(card.get_sdpos(), DEC);
  6211. SERIAL_ECHOPGM("SDLEN_PLAN="); MYSERIAL.println(sdlen_planner, DEC);
  6212. SERIAL_ECHOPGM("SDLEN_CMDQ="); MYSERIAL.println(sdlen_cmdqueue, DEC);
  6213. SERIAL_ECHOPGM("PLANNERBLOCKS="); MYSERIAL.println(int(nplanner_blocks), DEC);
  6214. SERIAL_ECHOPGM("SDSAVED="); MYSERIAL.println(saved_sdpos, DEC);
  6215. SERIAL_ECHOPGM("SDFILELEN="); MYSERIAL.println(card.fileSize(), DEC);
  6216. {
  6217. card.setIndex(saved_sdpos);
  6218. SERIAL_ECHOLNPGM("Content of planner buffer: ");
  6219. for (unsigned int idx = 0; idx < sdlen_planner; ++ idx)
  6220. MYSERIAL.print(char(card.get()));
  6221. SERIAL_ECHOLNPGM("Content of command buffer: ");
  6222. for (unsigned int idx = 0; idx < sdlen_cmdqueue; ++ idx)
  6223. MYSERIAL.print(char(card.get()));
  6224. SERIAL_ECHOLNPGM("End of command buffer");
  6225. }
  6226. {
  6227. // Print the content of the planner buffer, line by line:
  6228. card.setIndex(saved_sdpos);
  6229. int8_t iline = 0;
  6230. for (unsigned char idx = block_buffer_tail; idx != block_buffer_head; idx = (idx + 1) & (BLOCK_BUFFER_SIZE - 1), ++ iline) {
  6231. SERIAL_ECHOPGM("Planner line (from file): ");
  6232. MYSERIAL.print(int(iline), DEC);
  6233. SERIAL_ECHOPGM(", length: ");
  6234. MYSERIAL.print(block_buffer[idx].sdlen, DEC);
  6235. SERIAL_ECHOPGM(", steps: (");
  6236. MYSERIAL.print(block_buffer[idx].steps_x, DEC);
  6237. SERIAL_ECHOPGM(",");
  6238. MYSERIAL.print(block_buffer[idx].steps_y, DEC);
  6239. SERIAL_ECHOPGM(",");
  6240. MYSERIAL.print(block_buffer[idx].steps_z, DEC);
  6241. SERIAL_ECHOPGM(",");
  6242. MYSERIAL.print(block_buffer[idx].steps_e, DEC);
  6243. SERIAL_ECHOPGM("), events: ");
  6244. MYSERIAL.println(block_buffer[idx].step_event_count, DEC);
  6245. for (int len = block_buffer[idx].sdlen; len > 0; -- len)
  6246. MYSERIAL.print(char(card.get()));
  6247. }
  6248. }
  6249. {
  6250. // Print the content of the command buffer, line by line:
  6251. int8_t iline = 0;
  6252. union {
  6253. struct {
  6254. char lo;
  6255. char hi;
  6256. } lohi;
  6257. uint16_t value;
  6258. } sdlen_single;
  6259. int _bufindr = bufindr;
  6260. for (int _buflen = buflen; _buflen > 0; ++ iline) {
  6261. if (cmdbuffer[_bufindr] == CMDBUFFER_CURRENT_TYPE_SDCARD) {
  6262. sdlen_single.lohi.lo = cmdbuffer[_bufindr + 1];
  6263. sdlen_single.lohi.hi = cmdbuffer[_bufindr + 2];
  6264. }
  6265. SERIAL_ECHOPGM("Buffer line (from buffer): ");
  6266. MYSERIAL.print(int(iline), DEC);
  6267. SERIAL_ECHOPGM(", type: ");
  6268. MYSERIAL.print(int(cmdbuffer[_bufindr]), DEC);
  6269. SERIAL_ECHOPGM(", len: ");
  6270. MYSERIAL.println(sdlen_single.value, DEC);
  6271. // Print the content of the buffer line.
  6272. MYSERIAL.println(cmdbuffer + _bufindr + CMDHDRSIZE);
  6273. SERIAL_ECHOPGM("Buffer line (from file): ");
  6274. MYSERIAL.print(int(iline), DEC);
  6275. MYSERIAL.println(int(iline), DEC);
  6276. for (; sdlen_single.value > 0; -- sdlen_single.value)
  6277. MYSERIAL.print(char(card.get()));
  6278. if (-- _buflen == 0)
  6279. break;
  6280. // First skip the current command ID and iterate up to the end of the string.
  6281. for (_bufindr += CMDHDRSIZE; cmdbuffer[_bufindr] != 0; ++ _bufindr) ;
  6282. // Second, skip the end of string null character and iterate until a nonzero command ID is found.
  6283. for (++ _bufindr; _bufindr < sizeof(cmdbuffer) && cmdbuffer[_bufindr] == 0; ++ _bufindr) ;
  6284. // If the end of the buffer was empty,
  6285. if (_bufindr == sizeof(cmdbuffer)) {
  6286. // skip to the start and find the nonzero command.
  6287. for (_bufindr = 0; cmdbuffer[_bufindr] == 0; ++ _bufindr) ;
  6288. }
  6289. }
  6290. }
  6291. #endif
  6292. #if 0
  6293. saved_feedrate2 = feedrate; //save feedrate
  6294. #else
  6295. // Try to deduce the feedrate from the first block of the planner.
  6296. // Speed is in mm/min.
  6297. saved_feedrate2 = blocks_queued() ? (block_buffer[block_buffer_tail].nominal_speed * 60.f) : feedrate;
  6298. #endif
  6299. planner_abort_hard(); //abort printing
  6300. memcpy(saved_pos, current_position, sizeof(saved_pos));
  6301. saved_active_extruder = active_extruder; //save active_extruder
  6302. saved_extruder_under_pressure = extruder_under_pressure; //extruder under pressure flag - currently unused
  6303. cmdqueue_reset(); //empty cmdqueue
  6304. card.sdprinting = false;
  6305. // card.closefile();
  6306. saved_printing = true;
  6307. sei();
  6308. if ((z_move != 0) || (e_move != 0)) { // extruder and z move
  6309. #if 1
  6310. // Rather than calling plan_buffer_line directly, push the move into the command queue,
  6311. char buf[48];
  6312. strcpy_P(buf, PSTR("G1 Z"));
  6313. dtostrf(saved_pos[Z_AXIS] + z_move, 8, 3, buf + strlen(buf));
  6314. strcat_P(buf, PSTR(" E"));
  6315. // Relative extrusion
  6316. dtostrf(e_move, 6, 3, buf + strlen(buf));
  6317. strcat_P(buf, PSTR(" F"));
  6318. dtostrf(homing_feedrate[Z_AXIS], 8, 3, buf + strlen(buf));
  6319. // At this point the command queue is empty.
  6320. enquecommand(buf, false);
  6321. // If this call is invoked from the main Arduino loop() function, let the caller know that the command
  6322. // in the command queue is not the original command, but a new one, so it should not be removed from the queue.
  6323. repeatcommand_front();
  6324. #else
  6325. 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);
  6326. st_synchronize(); //wait moving
  6327. memcpy(current_position, saved_pos, sizeof(saved_pos));
  6328. memcpy(destination, current_position, sizeof(destination));
  6329. #endif
  6330. }
  6331. }
  6332. void restore_print_from_ram_and_continue(float e_move)
  6333. {
  6334. if (!saved_printing) return;
  6335. // for (int axis = X_AXIS; axis <= E_AXIS; axis++)
  6336. // current_position[axis] = st_get_position_mm(axis);
  6337. active_extruder = saved_active_extruder; //restore active_extruder
  6338. feedrate = saved_feedrate2; //restore feedrate
  6339. float e = saved_pos[E_AXIS] - e_move;
  6340. plan_set_e_position(e);
  6341. plan_buffer_line(saved_pos[X_AXIS], saved_pos[Y_AXIS], saved_pos[Z_AXIS], saved_pos[E_AXIS], homing_feedrate[Z_AXIS], active_extruder);
  6342. st_synchronize();
  6343. memcpy(current_position, saved_pos, sizeof(saved_pos));
  6344. memcpy(destination, current_position, sizeof(destination));
  6345. card.setIndex(saved_sdpos);
  6346. sdpos_atomic = saved_sdpos;
  6347. card.sdprinting = true;
  6348. saved_printing = false;
  6349. }
  6350. void print_world_coordinates()
  6351. {
  6352. SERIAL_ECHOPGM("world coordinates: (");
  6353. MYSERIAL.print(current_position[X_AXIS], 3);
  6354. SERIAL_ECHOPGM(", ");
  6355. MYSERIAL.print(current_position[Y_AXIS], 3);
  6356. SERIAL_ECHOPGM(", ");
  6357. MYSERIAL.print(current_position[Z_AXIS], 3);
  6358. SERIAL_ECHOLNPGM(")");
  6359. }
  6360. void print_physical_coordinates()
  6361. {
  6362. SERIAL_ECHOPGM("physical coordinates: (");
  6363. MYSERIAL.print(st_get_position_mm(X_AXIS), 3);
  6364. SERIAL_ECHOPGM(", ");
  6365. MYSERIAL.print(st_get_position_mm(Y_AXIS), 3);
  6366. SERIAL_ECHOPGM(", ");
  6367. MYSERIAL.print(st_get_position_mm(Z_AXIS), 3);
  6368. SERIAL_ECHOLNPGM(")");
  6369. }
  6370. void print_mesh_bed_leveling_table()
  6371. {
  6372. SERIAL_ECHOPGM("mesh bed leveling: ");
  6373. for (int8_t y = 0; y < MESH_NUM_Y_POINTS; ++ y)
  6374. for (int8_t x = 0; x < MESH_NUM_Y_POINTS; ++ x) {
  6375. MYSERIAL.print(mbl.z_values[y][x], 3);
  6376. SERIAL_ECHOPGM(" ");
  6377. }
  6378. SERIAL_ECHOLNPGM("");
  6379. }