Marlin_main.cpp 227 KB

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