Marlin_main.cpp 222 KB

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