Marlin_main.cpp 229 KB

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