Marlin_main.cpp 250 KB

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