Marlin_main.cpp 232 KB

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