Marlin_main.cpp 228 KB

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