Marlin_main.cpp 240 KB

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