Marlin_main.cpp 219 KB

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