Marlin_main.cpp 230 KB

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