Marlin_main.cpp 235 KB

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