Marlin_main.cpp 252 KB

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