Marlin_main.cpp 249 KB

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