Marlin_main.cpp 222 KB

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